diff --git a/.ci/update_windows/update.py b/.ci/update_windows/update.py
index cc79a914e..6a04e5e16 100755
--- a/.ci/update_windows/update.py
+++ b/.ci/update_windows/update.py
@@ -75,6 +75,25 @@ else:
print("pulling latest changes")
pull(repo)
+if "--stable" in sys.argv:
+ def latest_tag(repo):
+ versions = []
+ for k in repo.references:
+ try:
+ prefix = "refs/tags/v"
+ if k.startswith(prefix):
+ version = list(map(int, k[len(prefix):].split(".")))
+ versions.append((version[0] * 10000000000 + version[1] * 100000 + version[2], k))
+ except:
+ pass
+ versions.sort()
+ if len(versions) > 0:
+ return versions[-1][1]
+ return None
+ latest_tag = latest_tag(repo)
+ if latest_tag is not None:
+ repo.checkout(latest_tag)
+
print("Done!")
self_update = True
@@ -115,3 +134,13 @@ if not os.path.exists(req_path) or not files_equal(repo_req_path, req_path):
shutil.copy(repo_req_path, req_path)
except:
pass
+
+
+stable_update_script = os.path.join(repo_path, ".ci/update_windows/update_comfyui_stable.bat")
+stable_update_script_to = os.path.join(cur_path, "update_comfyui_stable.bat")
+
+try:
+ if not file_size(stable_update_script_to) > 10:
+ shutil.copy(stable_update_script, stable_update_script_to)
+except:
+ pass
diff --git a/.ci/update_windows/update_comfyui_stable.bat b/.ci/update_windows/update_comfyui_stable.bat
new file mode 100755
index 000000000..e18010da3
--- /dev/null
+++ b/.ci/update_windows/update_comfyui_stable.bat
@@ -0,0 +1,8 @@
+@echo off
+..\python_embeded\python.exe .\update.py ..\ComfyUI\ --stable
+if exist update_new.py (
+ move /y update_new.py update.py
+ echo Running updater again since it got updated.
+ ..\python_embeded\python.exe .\update.py ..\ComfyUI\ --skip_self_update --stable
+)
+if "%~1"=="" pause
diff --git a/.ci/windows_base_files/README_VERY_IMPORTANT.txt b/.ci/windows_base_files/README_VERY_IMPORTANT.txt
index 0216658de..d46acbcbf 100755
--- a/.ci/windows_base_files/README_VERY_IMPORTANT.txt
+++ b/.ci/windows_base_files/README_VERY_IMPORTANT.txt
@@ -14,7 +14,7 @@ run_cpu.bat
IF YOU GET A RED ERROR IN THE UI MAKE SURE YOU HAVE A MODEL/CHECKPOINT IN: ComfyUI\models\checkpoints
-You can download the stable diffusion 1.5 one from: https://huggingface.co/runwayml/stable-diffusion-v1-5/blob/main/v1-5-pruned-emaonly.ckpt
+You can download the stable diffusion 1.5 one from: https://huggingface.co/Comfy-Org/stable-diffusion-v1-5-archive/blob/main/v1-5-pruned-emaonly-fp16.safetensors
RECOMMENDED WAY TO UPDATE:
diff --git a/.ci/windows_nightly_base_files/run_nvidia_gpu_fast.bat b/.ci/windows_nightly_base_files/run_nvidia_gpu_fast.bat
new file mode 100644
index 000000000..ca6d6868a
--- /dev/null
+++ b/.ci/windows_nightly_base_files/run_nvidia_gpu_fast.bat
@@ -0,0 +1,2 @@
+.\python_embeded\python.exe -s ComfyUI\main.py --windows-standalone-build --fast
+pause
diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 000000000..4391de678
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,2 @@
+/web/assets/** linguist-generated
+/web/** linguist-vendored
diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml
index 2c519ede5..09fea712e 100644
--- a/.github/ISSUE_TEMPLATE/config.yml
+++ b/.github/ISSUE_TEMPLATE/config.yml
@@ -1,5 +1,8 @@
blank_issues_enabled: true
contact_links:
+ - name: ComfyUI Frontend Issues
+ url: https://github.com/Comfy-Org/ComfyUI_frontend/issues
+ about: Issues related to the ComfyUI frontend (display issues, user interaction bugs), please go to the frontend repo to file the issue
- name: ComfyUI Matrix Space
url: https://app.element.io/#/room/%23comfyui_space%3Amatrix.org
about: The ComfyUI Matrix Space is available for support and general discussion related to ComfyUI (Matrix is like Discord but open source).
diff --git a/.github/workflows/stable-release.yml b/.github/workflows/stable-release.yml
index 658816afe..e5444d367 100644
--- a/.github/workflows/stable-release.yml
+++ b/.github/workflows/stable-release.yml
@@ -12,7 +12,7 @@ on:
description: 'CUDA version'
required: true
type: string
- default: "121"
+ default: "124"
python_minor:
description: 'Python minor version'
required: true
diff --git a/.github/workflows/stale-issues.yml b/.github/workflows/stale-issues.yml
new file mode 100644
index 000000000..045996070
--- /dev/null
+++ b/.github/workflows/stale-issues.yml
@@ -0,0 +1,21 @@
+name: 'Close stale issues'
+on:
+ schedule:
+ # Run daily at 430 am PT
+ - cron: '30 11 * * *'
+permissions:
+ issues: write
+
+jobs:
+ stale:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/stale@v9
+ with:
+ stale-issue-message: "This issue is being marked stale because it has not had any activity for 30 days. Reply below within 7 days if your issue still isn't solved, and it will be left open. Otherwise, the issue will be closed automatically."
+ days-before-stale: 30
+ days-before-close: 7
+ stale-issue-label: 'Stale'
+ only-labels: 'User Support'
+ exempt-all-assignees: true
+ exempt-all-milestones: true
diff --git a/.github/workflows/test-browser.yml b/.github/workflows/test-launch.yml
similarity index 50%
rename from .github/workflows/test-browser.yml
rename to .github/workflows/test-launch.yml
index ce0bc37a3..42f1dbe99 100644
--- a/.github/workflows/test-browser.yml
+++ b/.github/workflows/test-launch.yml
@@ -1,10 +1,4 @@
-# This is a temporary action during frontend TS migration.
-# This file should be removed after TS migration is completed.
-# The browser test is here to ensure TS repo is working the same way as the
-# current JS code.
-# If you are adding UI feature, please sync your changes to the TS repo:
-# huchenlei/ComfyUI_frontend and update test expectation files accordingly.
-name: Playwright Browser Tests CI
+name: Test server launches without errors
on:
push:
@@ -21,15 +15,6 @@ jobs:
with:
repository: "comfyanonymous/ComfyUI"
path: "ComfyUI"
- - name: Checkout ComfyUI_frontend
- uses: actions/checkout@v4
- with:
- repository: "huchenlei/ComfyUI_frontend"
- path: "ComfyUI_frontend"
- ref: "fcc54d803e5b6a9b08a462a1d94899318c96dcbb"
- - uses: actions/setup-node@v3
- with:
- node-version: lts/*
- uses: actions/setup-python@v4
with:
python-version: '3.8'
@@ -45,16 +30,6 @@ jobs:
python main.py --cpu 2>&1 | tee console_output.log &
wait-for-it --service 127.0.0.1:8188 -t 600
working-directory: ComfyUI
- - name: Install ComfyUI_frontend dependencies
- run: |
- npm ci
- working-directory: ComfyUI_frontend
- - name: Install Playwright Browsers
- run: npx playwright install --with-deps
- working-directory: ComfyUI_frontend
- - name: Run Playwright tests
- run: npx playwright test
- working-directory: ComfyUI_frontend
- name: Check for unhandled exceptions in server log
run: |
if grep -qE "Exception|Error" console_output.log; then
@@ -62,12 +37,6 @@ jobs:
exit 1
fi
working-directory: ComfyUI
- - uses: actions/upload-artifact@v4
- if: always()
- with:
- name: playwright-report
- path: ComfyUI_frontend/playwright-report/
- retention-days: 30
- uses: actions/upload-artifact@v4
if: always()
with:
diff --git a/.github/workflows/test-ui.yaml b/.github/workflows/test-unit.yml
similarity index 58%
rename from .github/workflows/test-ui.yaml
rename to .github/workflows/test-unit.yml
index d947e9d5f..b3a4b4ea0 100644
--- a/.github/workflows/test-ui.yaml
+++ b/.github/workflows/test-unit.yml
@@ -1,29 +1,29 @@
-name: Tests CI
+name: Unit Tests
-on: [push, pull_request]
+on:
+ push:
+ branches: [ main, master ]
+ pull_request:
+ branches: [ main, master ]
jobs:
test:
- runs-on: ubuntu-latest
+ strategy:
+ matrix:
+ os: [ubuntu-latest, windows-latest, macos-latest]
+ runs-on: ${{ matrix.os }}
+ continue-on-error: true
steps:
- uses: actions/checkout@v4
- - uses: actions/setup-node@v3
+ - name: Set up Python
+ uses: actions/setup-python@v4
with:
- node-version: 18
- - uses: actions/setup-python@v4
- with:
python-version: '3.10'
- name: Install requirements
run: |
python -m pip install --upgrade pip
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu
pip install -r requirements.txt
- - name: Run Tests
- run: |
- npm ci
- npm run test:generate
- npm test -- --verbose
- working-directory: ./tests-ui
- name: Run Unit Tests
run: |
pip install -r tests-unit/requirements.txt
diff --git a/.github/workflows/windows_release_nightly_pytorch.yml b/.github/workflows/windows_release_nightly_pytorch.yml
index 0b29b4d91..07f52e0b2 100644
--- a/.github/workflows/windows_release_nightly_pytorch.yml
+++ b/.github/workflows/windows_release_nightly_pytorch.yml
@@ -67,6 +67,7 @@ jobs:
mkdir update
cp -r ComfyUI/.ci/update_windows/* ./update/
cp -r ComfyUI/.ci/windows_base_files/* ./
+ cp -r ComfyUI/.ci/windows_nightly_base_files/* ./
echo "call update_comfyui.bat nopause
..\python_embeded\python.exe -s -m pip install --upgrade --pre torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/nightly/cu${{ inputs.cu }} -r ../ComfyUI/requirements.txt pygit2
diff --git a/.gitignore b/.gitignore
index b212b0297..61881b8a4 100644
--- a/.gitignore
+++ b/.gitignore
@@ -12,6 +12,7 @@ extra_model_paths.yaml
.vscode/
.idea/
venv/
+.venv/
/web/extensions/*
!/web/extensions/logging.js.example
!/web/extensions/core/
diff --git a/README.md b/README.md
index d5ded7297..745cf1a35 100644
--- a/README.md
+++ b/README.md
@@ -1,8 +1,35 @@
-ComfyUI
-=======
-The most powerful and modular stable diffusion GUI and backend.
------------
+
+
+# ComfyUI
+**The most powerful and modular diffusion model GUI and backend.**
+
+
+[![Website][website-shield]][website-url]
+[![Dynamic JSON Badge][discord-shield]][discord-url]
+[![Matrix][matrix-shield]][matrix-url]
+
+[![][github-release-shield]][github-release-link]
+[![][github-release-date-shield]][github-release-link]
+[![][github-downloads-shield]][github-downloads-link]
+[![][github-downloads-latest-shield]][github-downloads-link]
+
+[matrix-shield]: https://img.shields.io/badge/Matrix-000000?style=flat&logo=matrix&logoColor=white
+[matrix-url]: https://app.element.io/#/room/%23comfyui_space%3Amatrix.org
+[website-shield]: https://img.shields.io/badge/ComfyOrg-4285F4?style=flat
+[website-url]: https://www.comfy.org/
+
+[discord-shield]: https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fdiscord.com%2Fapi%2Finvites%2Fcomfyorg%3Fwith_counts%3Dtrue&query=%24.approximate_member_count&logo=discord&logoColor=white&label=Discord&color=green&suffix=%20total
+[discord-url]: https://www.comfy.org/discord
+
+[github-release-shield]: https://img.shields.io/github/v/release/comfyanonymous/ComfyUI?style=flat&sort=semver
+[github-release-link]: https://github.com/comfyanonymous/ComfyUI/releases
+[github-release-date-shield]: https://img.shields.io/github/release-date/comfyanonymous/ComfyUI?style=flat
+[github-downloads-shield]: https://img.shields.io/github/downloads/comfyanonymous/ComfyUI/total?style=flat
+[github-downloads-latest-shield]: https://img.shields.io/github/downloads/comfyanonymous/ComfyUI/latest/total?style=flat&label=downloads%40latest
+[github-downloads-link]: https://github.com/comfyanonymous/ComfyUI/releases
+

+
This ui will let you design and execute advanced stable diffusion pipelines using a graph/nodes/flowchart based interface. For some workflow examples and see what ComfyUI can do you can check out:
### [ComfyUI Examples](https://comfyanonymous.github.io/ComfyUI_examples/)
@@ -48,6 +75,7 @@ Workflow examples can be found on the [Examples page](https://comfyanonymous.git
|------------------------------------|--------------------------------------------------------------------------------------------------------------------|
| Ctrl + Enter | Queue up current graph for generation |
| Ctrl + Shift + Enter | Queue up current graph as first for generation |
+| Ctrl + Alt + Enter | Cancel current generation |
| Ctrl + Z/Ctrl + Y | Undo/Redo |
| Ctrl + S | Save workflow |
| Ctrl + O | Load workflow |
@@ -66,10 +94,14 @@ Workflow examples can be found on the [Examples page](https://comfyanonymous.git
| Alt + `+` | Canvas Zoom in |
| Alt + `-` | Canvas Zoom out |
| Ctrl + Shift + LMB + Vertical drag | Canvas Zoom in/out |
+| P | Pin/Unpin selected nodes |
+| Ctrl + G | Group selected nodes |
| Q | Toggle visibility of the queue |
| H | Toggle visibility of history |
| R | Refresh graph |
| Double-Click LMB | Open node quick search palette |
+| Shift + Drag | Move multiple wires at once |
+| Ctrl + Alt + LMB | Disconnect all wires from clicked slot |
Ctrl can also be replaced with Cmd instead for macOS users
@@ -105,17 +137,17 @@ Put your VAE in: models/vae
### AMD GPUs (Linux only)
AMD users can install rocm and pytorch with pip if you don't have it already installed, this is the command to install the stable version:
-```pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/rocm6.0```
+```pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/rocm6.1```
-This is the command to install the nightly with ROCm 6.0 which might have some performance improvements:
+This is the command to install the nightly with ROCm 6.2 which might have some performance improvements:
-```pip install --pre torch torchvision torchaudio --index-url https://download.pytorch.org/whl/nightly/rocm6.1```
+```pip install --pre torch torchvision torchaudio --index-url https://download.pytorch.org/whl/nightly/rocm6.2```
### NVIDIA
Nvidia users should install stable pytorch using this command:
-```pip install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu121```
+```pip install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu124```
This is the command to install pytorch nightly instead which might have performance improvements:
@@ -200,7 +232,7 @@ To use a textual inversion concepts/embeddings in a text prompt put them in the
Use ```--preview-method auto``` to enable previews.
-The default installation includes a fast latent preview method that's low-resolution. To enable higher-quality previews with [TAESD](https://github.com/madebyollin/taesd), download the [taesd_decoder.pth](https://github.com/madebyollin/taesd/raw/main/taesd_decoder.pth) (for SD1.x and SD2.x) and [taesdxl_decoder.pth](https://github.com/madebyollin/taesd/raw/main/taesdxl_decoder.pth) (for SDXL) models and place them in the `models/vae_approx` folder. Once they're installed, restart ComfyUI to enable high-quality previews.
+The default installation includes a fast latent preview method that's low-resolution. To enable higher-quality previews with [TAESD](https://github.com/madebyollin/taesd), download the [taesd_decoder.pth, taesdxl_decoder.pth, taesd3_decoder.pth and taef1_decoder.pth](https://github.com/madebyollin/taesd/) and place them in the `models/vae_approx` folder. Once they're installed, restart ComfyUI and launch it with `--preview-method taesd` to enable high-quality previews.
## How to use TLS/SSL?
Generate a self-signed certificate (not appropriate for shared/production use) and key by running the command: `openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -sha256 -days 3650 -nodes -subj "/C=XX/ST=StateName/L=CityName/O=CompanyName/OU=CompanySectionName/CN=CommonNameOrHostname"`
@@ -216,6 +248,47 @@ Use `--tls-keyfile key.pem --tls-certfile cert.pem` to enable TLS/SSL, the app w
See also: [https://www.comfy.org/](https://www.comfy.org/)
+## Frontend Development
+
+As of August 15, 2024, we have transitioned to a new frontend, which is now hosted in a separate repository: [ComfyUI Frontend](https://github.com/Comfy-Org/ComfyUI_frontend). This repository now hosts the compiled JS (from TS/Vue) under the `web/` directory.
+
+### Reporting Issues and Requesting Features
+
+For any bugs, issues, or feature requests related to the frontend, please use the [ComfyUI Frontend repository](https://github.com/Comfy-Org/ComfyUI_frontend). This will help us manage and address frontend-specific concerns more efficiently.
+
+### Using the Latest Frontend
+
+The new frontend is now the default for ComfyUI. However, please note:
+
+1. The frontend in the main ComfyUI repository is updated weekly.
+2. Daily releases are available in the separate frontend repository.
+
+To use the most up-to-date frontend version:
+
+1. For the latest daily release, launch ComfyUI with this command line argument:
+
+ ```
+ --front-end-version Comfy-Org/ComfyUI_frontend@latest
+ ```
+
+2. For a specific version, replace `latest` with the desired version number:
+
+ ```
+ --front-end-version Comfy-Org/ComfyUI_frontend@1.2.2
+ ```
+
+This approach allows you to easily switch between the stable weekly release and the cutting-edge daily updates, or even specific versions for testing purposes.
+
+### Accessing the Legacy Frontend
+
+If you need to use the legacy frontend for any reason, you can access it using the following command line argument:
+
+```
+--front-end-version Comfy-Org/ComfyUI_legacy_frontend@latest
+```
+
+This will use a snapshot of the legacy frontend preserved in the [ComfyUI Legacy Frontend repository](https://github.com/Comfy-Org/ComfyUI_legacy_frontend).
+
# QA
### Which GPU should I buy for this?
diff --git a/api_server/__init__.py b/api_server/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/api_server/routes/__init__.py b/api_server/routes/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/api_server/routes/internal/README.md b/api_server/routes/internal/README.md
new file mode 100644
index 000000000..35330c36f
--- /dev/null
+++ b/api_server/routes/internal/README.md
@@ -0,0 +1,3 @@
+# ComfyUI Internal Routes
+
+All routes under the `/internal` path are designated for **internal use by ComfyUI only**. These routes are not intended for use by external applications may change at any time without notice.
diff --git a/api_server/routes/internal/__init__.py b/api_server/routes/internal/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/api_server/routes/internal/internal_routes.py b/api_server/routes/internal/internal_routes.py
new file mode 100644
index 000000000..63704f13a
--- /dev/null
+++ b/api_server/routes/internal/internal_routes.py
@@ -0,0 +1,51 @@
+from aiohttp import web
+from typing import Optional
+from folder_paths import models_dir, user_directory, output_directory, folder_names_and_paths
+from api_server.services.file_service import FileService
+import app.logger
+
+class InternalRoutes:
+ '''
+ The top level web router for internal routes: /internal/*
+ The endpoints here should NOT be depended upon. It is for ComfyUI frontend use only.
+ Check README.md for more information.
+
+ '''
+ def __init__(self):
+ self.routes: web.RouteTableDef = web.RouteTableDef()
+ self._app: Optional[web.Application] = None
+ self.file_service = FileService({
+ "models": models_dir,
+ "user": user_directory,
+ "output": output_directory
+ })
+
+ def setup_routes(self):
+ @self.routes.get('/files')
+ async def list_files(request):
+ directory_key = request.query.get('directory', '')
+ try:
+ file_list = self.file_service.list_files(directory_key)
+ return web.json_response({"files": file_list})
+ except ValueError as e:
+ return web.json_response({"error": str(e)}, status=400)
+ except Exception as e:
+ return web.json_response({"error": str(e)}, status=500)
+
+ @self.routes.get('/logs')
+ async def get_logs(request):
+ return web.json_response(app.logger.get_logs())
+
+ @self.routes.get('/folder_paths')
+ async def get_folder_paths(request):
+ response = {}
+ for key in folder_names_and_paths:
+ response[key] = folder_names_and_paths[key][0]
+ return web.json_response(response)
+
+ def get_app(self):
+ if self._app is None:
+ self._app = web.Application()
+ self.setup_routes()
+ self._app.add_routes(self.routes)
+ return self._app
diff --git a/api_server/services/__init__.py b/api_server/services/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/api_server/services/file_service.py b/api_server/services/file_service.py
new file mode 100644
index 000000000..394571084
--- /dev/null
+++ b/api_server/services/file_service.py
@@ -0,0 +1,13 @@
+from typing import Dict, List, Optional
+from api_server.utils.file_operations import FileSystemOperations, FileSystemItem
+
+class FileService:
+ def __init__(self, allowed_directories: Dict[str, str], file_system_ops: Optional[FileSystemOperations] = None):
+ self.allowed_directories: Dict[str, str] = allowed_directories
+ self.file_system_ops: FileSystemOperations = file_system_ops or FileSystemOperations()
+
+ def list_files(self, directory_key: str) -> List[FileSystemItem]:
+ if directory_key not in self.allowed_directories:
+ raise ValueError("Invalid directory key")
+ directory_path: str = self.allowed_directories[directory_key]
+ return self.file_system_ops.walk_directory(directory_path)
\ No newline at end of file
diff --git a/api_server/utils/file_operations.py b/api_server/utils/file_operations.py
new file mode 100644
index 000000000..ef1bf999e
--- /dev/null
+++ b/api_server/utils/file_operations.py
@@ -0,0 +1,42 @@
+import os
+from typing import List, Union, TypedDict, Literal
+from typing_extensions import TypeGuard
+class FileInfo(TypedDict):
+ name: str
+ path: str
+ type: Literal["file"]
+ size: int
+
+class DirectoryInfo(TypedDict):
+ name: str
+ path: str
+ type: Literal["directory"]
+
+FileSystemItem = Union[FileInfo, DirectoryInfo]
+
+def is_file_info(item: FileSystemItem) -> TypeGuard[FileInfo]:
+ return item["type"] == "file"
+
+class FileSystemOperations:
+ @staticmethod
+ def walk_directory(directory: str) -> List[FileSystemItem]:
+ file_list: List[FileSystemItem] = []
+ for root, dirs, files in os.walk(directory):
+ for name in files:
+ file_path = os.path.join(root, name)
+ relative_path = os.path.relpath(file_path, directory)
+ file_list.append({
+ "name": name,
+ "path": relative_path,
+ "type": "file",
+ "size": os.path.getsize(file_path)
+ })
+ for name in dirs:
+ dir_path = os.path.join(root, name)
+ relative_path = os.path.relpath(dir_path, directory)
+ file_list.append({
+ "name": name,
+ "path": relative_path,
+ "type": "directory"
+ })
+ return file_list
\ No newline at end of file
diff --git a/app/frontend_management.py b/app/frontend_management.py
index fb57b23f3..9c832e46d 100644
--- a/app/frontend_management.py
+++ b/app/frontend_management.py
@@ -8,7 +8,7 @@ import zipfile
from dataclasses import dataclass
from functools import cached_property
from pathlib import Path
-from typing import TypedDict
+from typing import TypedDict, Optional
import requests
from typing_extensions import NotRequired
@@ -132,12 +132,13 @@ class FrontendManager:
return match_result.group(1), match_result.group(2), match_result.group(3)
@classmethod
- def init_frontend_unsafe(cls, version_string: str) -> str:
+ def init_frontend_unsafe(cls, version_string: str, provider: Optional[FrontEndProvider] = None) -> str:
"""
Initializes the frontend for the specified version.
Args:
version_string (str): The version string.
+ provider (FrontEndProvider, optional): The provider to use. Defaults to None.
Returns:
str: The path to the initialized frontend.
@@ -150,7 +151,7 @@ class FrontendManager:
return cls.DEFAULT_FRONTEND_PATH
repo_owner, repo_name, version = cls.parse_version_string(version_string)
- provider = FrontEndProvider(repo_owner, repo_name)
+ provider = provider or FrontEndProvider(repo_owner, repo_name)
release = provider.get_release(version)
semantic_version = release["tag_name"].lstrip("v")
@@ -158,15 +159,21 @@ class FrontendManager:
Path(cls.CUSTOM_FRONTENDS_ROOT) / provider.folder_name / semantic_version
)
if not os.path.exists(web_root):
- os.makedirs(web_root, exist_ok=True)
- logging.info(
- "Downloading frontend(%s) version(%s) to (%s)",
- provider.folder_name,
- semantic_version,
- web_root,
- )
- logging.debug(release)
- download_release_asset_zip(release, destination_path=web_root)
+ try:
+ os.makedirs(web_root, exist_ok=True)
+ logging.info(
+ "Downloading frontend(%s) version(%s) to (%s)",
+ provider.folder_name,
+ semantic_version,
+ web_root,
+ )
+ logging.debug(release)
+ download_release_asset_zip(release, destination_path=web_root)
+ finally:
+ # Clean up the directory if it is empty, i.e. the download failed
+ if not os.listdir(web_root):
+ os.rmdir(web_root)
+
return web_root
@classmethod
diff --git a/app/logger.py b/app/logger.py
new file mode 100644
index 000000000..17662c9e7
--- /dev/null
+++ b/app/logger.py
@@ -0,0 +1,31 @@
+import logging
+from logging.handlers import MemoryHandler
+from collections import deque
+
+logs = None
+formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
+
+
+def get_logs():
+ return "\n".join([formatter.format(x) for x in logs])
+
+
+def setup_logger(verbose: bool = False, capacity: int = 300):
+ global logs
+ if logs:
+ return
+
+ # Setup default global logger
+ logger = logging.getLogger()
+ logger.setLevel(logging.DEBUG if verbose else logging.INFO)
+
+ stream_handler = logging.StreamHandler()
+ stream_handler.setFormatter(logging.Formatter("%(message)s"))
+ logger.addHandler(stream_handler)
+
+ # Create a memory handler with a deque as its buffer
+ logs = deque(maxlen=capacity)
+ memory_handler = MemoryHandler(capacity, flushLevel=logging.INFO)
+ memory_handler.buffer = logs
+ memory_handler.setFormatter(formatter)
+ logger.addHandler(memory_handler)
diff --git a/app/user_manager.py b/app/user_manager.py
index 53dff18b7..208178444 100644
--- a/app/user_manager.py
+++ b/app/user_manager.py
@@ -5,17 +5,17 @@ import uuid
import glob
import shutil
from aiohttp import web
+from urllib import parse
from comfy.cli_args import args
-from folder_paths import user_directory
+import folder_paths
from .app_settings import AppSettings
default_user = "default"
-users_file = os.path.join(user_directory, "users.json")
class UserManager():
def __init__(self):
- global user_directory
+ user_directory = folder_paths.get_user_directory()
self.settings = AppSettings(self)
if not os.path.exists(user_directory):
@@ -25,14 +25,17 @@ class UserManager():
print("****** For multi-user setups add the --multi-user CLI argument to enable multiple user profiles. ******")
if args.multi_user:
- if os.path.isfile(users_file):
- with open(users_file) as f:
+ if os.path.isfile(self.get_users_file()):
+ with open(self.get_users_file()) as f:
self.users = json.load(f)
else:
self.users = {}
else:
self.users = {"default": "default"}
+ def get_users_file(self):
+ return os.path.join(folder_paths.get_user_directory(), "users.json")
+
def get_request_user_id(self, request):
user = "default"
if args.multi_user and "comfy-user" in request.headers:
@@ -44,7 +47,7 @@ class UserManager():
return user
def get_request_user_filepath(self, request, file, type="userdata", create_dir=True):
- global user_directory
+ user_directory = folder_paths.get_user_directory()
if type == "userdata":
root_dir = user_directory
@@ -59,6 +62,10 @@ class UserManager():
return None
if file is not None:
+ # Check if filename is url encoded
+ if "%" in file:
+ file = parse.unquote(file)
+
# prevent leaving /{type}/{user}
path = os.path.abspath(os.path.join(user_root, file))
if os.path.commonpath((user_root, path)) != user_root:
@@ -80,8 +87,7 @@ class UserManager():
self.users[user_id] = name
- global users_file
- with open(users_file, "w") as f:
+ with open(self.get_users_file(), "w") as f:
json.dump(self.users, f)
return user_id
@@ -112,25 +118,69 @@ class UserManager():
@routes.get("/userdata")
async def listuserdata(request):
+ """
+ List user data files in a specified directory.
+
+ This endpoint allows listing files in a user's data directory, with options for recursion,
+ full file information, and path splitting.
+
+ Query Parameters:
+ - dir (required): The directory to list files from.
+ - recurse (optional): If "true", recursively list files in subdirectories.
+ - full_info (optional): If "true", return detailed file information (path, size, modified time).
+ - split (optional): If "true", split file paths into components (only applies when full_info is false).
+
+ Returns:
+ - 400: If 'dir' parameter is missing.
+ - 403: If the requested path is not allowed.
+ - 404: If the requested directory does not exist.
+ - 200: JSON response with the list of files or file information.
+
+ The response format depends on the query parameters:
+ - Default: List of relative file paths.
+ - full_info=true: List of dictionaries with file details.
+ - split=true (and full_info=false): List of lists, each containing path components.
+ """
directory = request.rel_url.query.get('dir', '')
if not directory:
- return web.Response(status=400)
-
+ return web.Response(status=400, text="Directory not provided")
+
path = self.get_request_user_filepath(request, directory)
if not path:
- return web.Response(status=403)
-
+ return web.Response(status=403, text="Invalid directory")
+
if not os.path.exists(path):
- return web.Response(status=404)
-
+ return web.Response(status=404, text="Directory not found")
+
recurse = request.rel_url.query.get('recurse', '').lower() == "true"
- results = glob.glob(os.path.join(
- glob.escape(path), '**/*'), recursive=recurse)
- results = [os.path.relpath(x, path) for x in results if os.path.isfile(x)]
-
+ full_info = request.rel_url.query.get('full_info', '').lower() == "true"
+
+ # Use different patterns based on whether we're recursing or not
+ if recurse:
+ pattern = os.path.join(glob.escape(path), '**', '*')
+ else:
+ pattern = os.path.join(glob.escape(path), '*')
+
+ results = glob.glob(pattern, recursive=recurse)
+
+ if full_info:
+ results = [
+ {
+ 'path': os.path.relpath(x, path).replace(os.sep, '/'),
+ 'size': os.path.getsize(x),
+ 'modified': os.path.getmtime(x)
+ } for x in results if os.path.isfile(x)
+ ]
+ else:
+ results = [
+ os.path.relpath(x, path).replace(os.sep, '/')
+ for x in results
+ if os.path.isfile(x)
+ ]
+
split_path = request.rel_url.query.get('split', '').lower() == "true"
- if split_path:
- results = [[x] + x.split(os.sep) for x in results]
+ if split_path and not full_info:
+ results = [[x] + x.split('/') for x in results]
return web.json_response(results)
@@ -138,14 +188,14 @@ class UserManager():
file = request.match_info.get(param, None)
if not file:
return web.Response(status=400)
-
+
path = self.get_request_user_filepath(request, file)
if not path:
return web.Response(status=403)
-
+
if check_exists and not os.path.exists(path):
return web.Response(status=404)
-
+
return path
@routes.get("/userdata/{file}")
@@ -153,7 +203,7 @@ class UserManager():
path = get_user_data_path(request, check_exists=True)
if not isinstance(path, str):
return path
-
+
return web.FileResponse(path)
@routes.post("/userdata/{file}")
@@ -161,7 +211,7 @@ class UserManager():
path = get_user_data_path(request)
if not isinstance(path, str):
return path
-
+
overwrite = request.query["overwrite"] != "false"
if not overwrite and os.path.exists(path):
return web.Response(status=409)
@@ -170,7 +220,7 @@ class UserManager():
with open(path, "wb") as f:
f.write(body)
-
+
resp = os.path.relpath(path, self.get_request_user_filepath(request, None))
return web.json_response(resp)
@@ -181,7 +231,7 @@ class UserManager():
return path
os.remove(path)
-
+
return web.Response(status=204)
@routes.post("/userdata/{file}/move/{dest}")
@@ -189,17 +239,17 @@ class UserManager():
source = get_user_data_path(request, check_exists=True)
if not isinstance(source, str):
return source
-
+
dest = get_user_data_path(request, check_exists=False, param="dest")
if not isinstance(source, str):
return dest
-
+
overwrite = request.query["overwrite"] != "false"
if not overwrite and os.path.exists(dest):
return web.Response(status=409)
print(f"moving '{source}' -> '{dest}'")
shutil.move(source, dest)
-
+
resp = os.path.relpath(dest, self.get_request_user_filepath(request, None))
return web.json_response(resp)
diff --git a/comfy/cldm/mmdit.py b/comfy/cldm/mmdit.py
index 025c2fb5d..54a58ab83 100644
--- a/comfy/cldm/mmdit.py
+++ b/comfy/cldm/mmdit.py
@@ -6,6 +6,7 @@ class ControlNet(comfy.ldm.modules.diffusionmodules.mmdit.MMDiT):
def __init__(
self,
num_blocks = None,
+ control_latent_channels = None,
dtype = None,
device = None,
operations = None,
@@ -17,10 +18,13 @@ class ControlNet(comfy.ldm.modules.diffusionmodules.mmdit.MMDiT):
for _ in range(len(self.joint_blocks)):
self.controlnet_blocks.append(operations.Linear(self.hidden_size, self.hidden_size, device=device, dtype=dtype))
+ if control_latent_channels is None:
+ control_latent_channels = self.in_channels
+
self.pos_embed_input = comfy.ldm.modules.diffusionmodules.mmdit.PatchEmbed(
None,
self.patch_size,
- self.in_channels,
+ control_latent_channels,
self.hidden_size,
bias=True,
strict_img_size=False,
diff --git a/comfy/cli_args.py b/comfy/cli_args.py
index 2397de3d6..ed0bbec60 100644
--- a/comfy/cli_args.py
+++ b/comfy/cli_args.py
@@ -36,7 +36,7 @@ class EnumAction(argparse.Action):
parser = argparse.ArgumentParser()
-parser.add_argument("--listen", type=str, default="127.0.0.1", metavar="IP", nargs="?", const="0.0.0.0", help="Specify the IP address to listen on (default: 127.0.0.1). If --listen is provided without an argument, it defaults to 0.0.0.0. (listens on all)")
+parser.add_argument("--listen", type=str, default="127.0.0.1", metavar="IP", nargs="?", const="0.0.0.0,::", help="Specify the IP address to listen on (default: 127.0.0.1). You can give a list of ip addresses by separating them with a comma like: 127.2.2.2,127.3.3.3 If --listen is provided without an argument, it defaults to 0.0.0.0,:: (listens on all ipv4 and ipv6)")
parser.add_argument("--port", type=int, default=8188, help="Set the listen port.")
parser.add_argument("--tls-keyfile", type=str, help="Path to TLS (SSL) key file. Enables TLS, makes app accessible at https://... requires --tls-certfile to function")
parser.add_argument("--tls-certfile", type=str, help="Path to TLS (SSL) certificate file. Enables TLS, makes app accessible at https://... requires --tls-keyfile to function")
@@ -92,6 +92,12 @@ class LatentPreviewMethod(enum.Enum):
parser.add_argument("--preview-method", type=LatentPreviewMethod, default=LatentPreviewMethod.NoPreviews, help="Default preview method for sampler nodes.", action=EnumAction)
+parser.add_argument("--preview-size", type=int, default=512, help="Sets the maximum preview size for sampler nodes.")
+
+cache_group = parser.add_mutually_exclusive_group()
+cache_group.add_argument("--cache-classic", action="store_true", help="Use the old style (aggressive) caching.")
+cache_group.add_argument("--cache-lru", type=int, default=0, help="Use LRU caching with a maximum of N node results cached. May use more RAM/VRAM.")
+
attn_group = parser.add_mutually_exclusive_group()
attn_group.add_argument("--use-split-cross-attention", action="store_true", help="Use the split cross attention optimization. Ignored when xformers is used.")
attn_group.add_argument("--use-quad-cross-attention", action="store_true", help="Use the sub-quadratic cross attention optimization . Ignored when xformers is used.")
@@ -112,10 +118,14 @@ vram_group.add_argument("--lowvram", action="store_true", help="Split the unet i
vram_group.add_argument("--novram", action="store_true", help="When lowvram isn't enough.")
vram_group.add_argument("--cpu", action="store_true", help="To use the CPU for everything (slow).")
+parser.add_argument("--reserve-vram", type=float, default=None, help="Set the amount of vram in GB you want to reserve for use by your OS/other software. By default some amount is reverved depending on your OS.")
+
+
parser.add_argument("--default-hashing-function", type=str, choices=['md5', 'sha1', 'sha256', 'sha512'], default='sha256', help="Allows you to choose the hash function to use for duplicate filename / contents comparison. Default is sha256.")
parser.add_argument("--disable-smart-memory", action="store_true", help="Force ComfyUI to agressively offload to regular ram instead of keeping models in vram when it can.")
parser.add_argument("--deterministic", action="store_true", help="Make pytorch use slower deterministic algorithms when it can. Note that this might not make images deterministic in all cases.")
+parser.add_argument("--fast", action="store_true", help="Enable some untested and potentially quality deteriorating optimizations.")
parser.add_argument("--dont-print-server", action="store_true", help="Don't print server output.")
parser.add_argument("--quick-test-for-ci", action="store_true", help="Quick test for CI.")
@@ -161,6 +171,8 @@ parser.add_argument(
help="The local filesystem path to the directory where the frontend is located. Overrides --front-end-version.",
)
+parser.add_argument("--user-directory", type=is_valid_directory, default=None, help="Set the ComfyUI user directory with an absolute path.")
+
if comfy.options.args_parsing:
args = parser.parse_args()
else:
@@ -171,10 +183,3 @@ if args.windows_standalone_build:
if args.disable_auto_launch:
args.auto_launch = False
-
-import logging
-logging_level = logging.INFO
-if args.verbose:
- logging_level = logging.DEBUG
-
-logging.basicConfig(format="%(message)s", level=logging_level)
diff --git a/comfy/clip_model.py b/comfy/clip_model.py
index 3c67b737a..42cdc4f6e 100644
--- a/comfy/clip_model.py
+++ b/comfy/clip_model.py
@@ -88,10 +88,11 @@ class CLIPTextModel_(torch.nn.Module):
heads = config_dict["num_attention_heads"]
intermediate_size = config_dict["intermediate_size"]
intermediate_activation = config_dict["hidden_act"]
+ num_positions = config_dict["max_position_embeddings"]
self.eos_token_id = config_dict["eos_token_id"]
super().__init__()
- self.embeddings = CLIPEmbeddings(embed_dim, dtype=dtype, device=device, operations=operations)
+ self.embeddings = CLIPEmbeddings(embed_dim, num_positions=num_positions, dtype=dtype, device=device, operations=operations)
self.encoder = CLIPEncoder(num_layers, embed_dim, heads, intermediate_size, intermediate_activation, dtype, device, operations)
self.final_layer_norm = operations.LayerNorm(embed_dim, dtype=dtype, device=device)
@@ -123,7 +124,6 @@ class CLIPTextModel(torch.nn.Module):
self.text_model = CLIPTextModel_(config_dict, dtype, device, operations)
embed_dim = config_dict["hidden_size"]
self.text_projection = operations.Linear(embed_dim, embed_dim, bias=False, dtype=dtype, device=device)
- self.text_projection.weight.copy_(torch.eye(embed_dim))
self.dtype = dtype
def get_input_embeddings(self):
diff --git a/comfy/types.py b/comfy/comfy_types.py
similarity index 100%
rename from comfy/types.py
rename to comfy/comfy_types.py
diff --git a/comfy/controlnet.py b/comfy/controlnet.py
index dcfe492ce..37914e5fe 100644
--- a/comfy/controlnet.py
+++ b/comfy/controlnet.py
@@ -34,7 +34,7 @@ import comfy.t2i_adapter.adapter
import comfy.ldm.cascade.controlnet
import comfy.cldm.mmdit
import comfy.ldm.hydit.controlnet
-import comfy.ldm.flux.controlnet_xlabs
+import comfy.ldm.flux.controlnet
def broadcast_image_to(tensor, target_batch_size, batched_number):
@@ -79,13 +79,21 @@ class ControlBase:
self.previous_controlnet = None
self.extra_conds = []
self.strength_type = StrengthType.CONSTANT
+ self.concat_mask = False
+ self.extra_concat_orig = []
+ self.extra_concat = None
- def set_cond_hint(self, cond_hint, strength=1.0, timestep_percent_range=(0.0, 1.0), vae=None):
+ def set_cond_hint(self, cond_hint, strength=1.0, timestep_percent_range=(0.0, 1.0), vae=None, extra_concat=[]):
self.cond_hint_original = cond_hint
self.strength = strength
self.timestep_percent_range = timestep_percent_range
if self.latent_format is not None:
+ if vae is None:
+ logging.warning("WARNING: no VAE provided to the controlnet apply node when this controlnet requires one.")
self.vae = vae
+ self.extra_concat_orig = extra_concat.copy()
+ if self.concat_mask and len(self.extra_concat_orig) == 0:
+ self.extra_concat_orig.append(torch.tensor([[[[1.0]]]]))
return self
def pre_run(self, model, percent_to_timestep_function):
@@ -100,9 +108,9 @@ class ControlBase:
def cleanup(self):
if self.previous_controlnet is not None:
self.previous_controlnet.cleanup()
- if self.cond_hint is not None:
- del self.cond_hint
- self.cond_hint = None
+
+ self.cond_hint = None
+ self.extra_concat = None
self.timestep_range = None
def get_models(self):
@@ -123,6 +131,8 @@ class ControlBase:
c.vae = self.vae
c.extra_conds = self.extra_conds.copy()
c.strength_type = self.strength_type
+ c.concat_mask = self.concat_mask
+ c.extra_concat_orig = self.extra_concat_orig.copy()
def inference_memory_requirements(self, dtype):
if self.previous_controlnet is not None:
@@ -148,7 +158,7 @@ class ControlBase:
elif self.strength_type == StrengthType.LINEAR_UP:
x *= (self.strength ** float(len(control_output) - i))
- if x.dtype != output_dtype:
+ if output_dtype is not None and x.dtype != output_dtype:
x = x.to(output_dtype)
out[key].append(x)
@@ -175,7 +185,7 @@ class ControlBase:
class ControlNet(ControlBase):
- def __init__(self, control_model=None, global_average_pooling=False, compression_ratio=8, latent_format=None, device=None, load_device=None, manual_cast_dtype=None, extra_conds=["y"], strength_type=StrengthType.CONSTANT):
+ def __init__(self, control_model=None, global_average_pooling=False, compression_ratio=8, latent_format=None, device=None, load_device=None, manual_cast_dtype=None, extra_conds=["y"], strength_type=StrengthType.CONSTANT, concat_mask=False):
super().__init__(device)
self.control_model = control_model
self.load_device = load_device
@@ -189,6 +199,7 @@ class ControlNet(ControlBase):
self.latent_format = latent_format
self.extra_conds += extra_conds
self.strength_type = strength_type
+ self.concat_mask = concat_mask
def get_control(self, x_noisy, t, cond, batched_number):
control_prev = None
@@ -206,7 +217,6 @@ class ControlNet(ControlBase):
if self.manual_cast_dtype is not None:
dtype = self.manual_cast_dtype
- output_dtype = x_noisy.dtype
if self.cond_hint is None or x_noisy.shape[2] * self.compression_ratio != self.cond_hint.shape[2] or x_noisy.shape[3] * self.compression_ratio != self.cond_hint.shape[3]:
if self.cond_hint is not None:
del self.cond_hint
@@ -214,6 +224,9 @@ class ControlNet(ControlBase):
compression_ratio = self.compression_ratio
if self.vae is not None:
compression_ratio *= self.vae.downscale_ratio
+ else:
+ if self.latent_format is not None:
+ raise ValueError("This Controlnet needs a VAE but none was provided, please use a ControlNetApply node with a VAE input and connect it.")
self.cond_hint = comfy.utils.common_upscale(self.cond_hint_original, x_noisy.shape[3] * compression_ratio, x_noisy.shape[2] * compression_ratio, self.upscale_algorithm, "center")
if self.vae is not None:
loaded_models = comfy.model_management.loaded_models(only_currently_used=True)
@@ -221,6 +234,13 @@ class ControlNet(ControlBase):
comfy.model_management.load_models_gpu(loaded_models)
if self.latent_format is not None:
self.cond_hint = self.latent_format.process_in(self.cond_hint)
+ if len(self.extra_concat_orig) > 0:
+ to_concat = []
+ for c in self.extra_concat_orig:
+ c = comfy.utils.common_upscale(c, self.cond_hint.shape[3], self.cond_hint.shape[2], self.upscale_algorithm, "center")
+ to_concat.append(comfy.utils.repeat_to_batch_size(c, self.cond_hint.shape[0]))
+ self.cond_hint = torch.cat([self.cond_hint] + to_concat, dim=1)
+
self.cond_hint = self.cond_hint.to(device=self.device, dtype=dtype)
if x_noisy.shape[0] != self.cond_hint.shape[0]:
self.cond_hint = broadcast_image_to(self.cond_hint, x_noisy.shape[0], batched_number)
@@ -236,7 +256,7 @@ class ControlNet(ControlBase):
x_noisy = self.model_sampling_current.calculate_input(t, x_noisy)
control = self.control_model(x=x_noisy.to(dtype), hint=self.cond_hint, timesteps=timestep.to(dtype), context=context.to(dtype), **extra)
- return self.control_merge(control, control_prev, output_dtype)
+ return self.control_merge(control, control_prev, output_dtype=None)
def copy(self):
c = ControlNet(None, global_average_pooling=self.global_average_pooling, load_device=self.load_device, manual_cast_dtype=self.manual_cast_dtype)
@@ -320,7 +340,7 @@ class ControlLoraOps:
class ControlLora(ControlNet):
- def __init__(self, control_weights, global_average_pooling=False, device=None):
+ def __init__(self, control_weights, global_average_pooling=False, device=None, model_options={}): #TODO? model_options
ControlBase.__init__(self, device)
self.control_weights = control_weights
self.global_average_pooling = global_average_pooling
@@ -377,21 +397,28 @@ class ControlLora(ControlNet):
def inference_memory_requirements(self, dtype):
return comfy.utils.calculate_parameters(self.control_weights) * comfy.model_management.dtype_size(dtype) + ControlBase.inference_memory_requirements(self, dtype)
-def controlnet_config(sd):
+def controlnet_config(sd, model_options={}):
model_config = comfy.model_detection.model_config_from_unet(sd, "", True)
- supported_inference_dtypes = model_config.supported_inference_dtypes
+ unet_dtype = model_options.get("dtype", None)
+ if unet_dtype is None:
+ weight_dtype = comfy.utils.weight_dtype(sd)
+
+ supported_inference_dtypes = list(model_config.supported_inference_dtypes)
+ if weight_dtype is not None:
+ supported_inference_dtypes.append(weight_dtype)
+
+ unet_dtype = comfy.model_management.unet_dtype(model_params=-1, supported_dtypes=supported_inference_dtypes)
- controlnet_config = model_config.unet_config
- unet_dtype = comfy.model_management.unet_dtype(supported_dtypes=supported_inference_dtypes)
load_device = comfy.model_management.get_torch_device()
manual_cast_dtype = comfy.model_management.unet_manual_cast(unet_dtype, load_device)
- if manual_cast_dtype is not None:
- operations = comfy.ops.manual_cast
- else:
- operations = comfy.ops.disable_weight_init
- return model_config, operations, load_device, unet_dtype, manual_cast_dtype
+ operations = model_options.get("custom_operations", None)
+ if operations is None:
+ operations = comfy.ops.pick_operations(unet_dtype, manual_cast_dtype, disable_fast_fp8=True)
+
+ offload_device = comfy.model_management.unet_offload_device()
+ return model_config, operations, load_device, unet_dtype, manual_cast_dtype, offload_device
def controlnet_load_state_dict(control_model, sd):
missing, unexpected = control_model.load_state_dict(sd, strict=False)
@@ -403,26 +430,31 @@ def controlnet_load_state_dict(control_model, sd):
logging.debug("unexpected controlnet keys: {}".format(unexpected))
return control_model
-def load_controlnet_mmdit(sd):
+def load_controlnet_mmdit(sd, model_options={}):
new_sd = comfy.model_detection.convert_diffusers_mmdit(sd, "")
- model_config, operations, load_device, unet_dtype, manual_cast_dtype = controlnet_config(new_sd)
+ model_config, operations, load_device, unet_dtype, manual_cast_dtype, offload_device = controlnet_config(new_sd, model_options=model_options)
num_blocks = comfy.model_detection.count_blocks(new_sd, 'joint_blocks.{}.')
for k in sd:
new_sd[k] = sd[k]
- control_model = comfy.cldm.mmdit.ControlNet(num_blocks=num_blocks, operations=operations, device=load_device, dtype=unet_dtype, **model_config.unet_config)
+ concat_mask = False
+ control_latent_channels = new_sd.get("pos_embed_input.proj.weight").shape[1]
+ if control_latent_channels == 17: #inpaint controlnet
+ concat_mask = True
+
+ control_model = comfy.cldm.mmdit.ControlNet(num_blocks=num_blocks, control_latent_channels=control_latent_channels, operations=operations, device=offload_device, dtype=unet_dtype, **model_config.unet_config)
control_model = controlnet_load_state_dict(control_model, new_sd)
latent_format = comfy.latent_formats.SD3()
latent_format.shift_factor = 0 #SD3 controlnet weirdness
- control = ControlNet(control_model, compression_ratio=1, latent_format=latent_format, load_device=load_device, manual_cast_dtype=manual_cast_dtype)
+ control = ControlNet(control_model, compression_ratio=1, latent_format=latent_format, concat_mask=concat_mask, load_device=load_device, manual_cast_dtype=manual_cast_dtype)
return control
-def load_controlnet_hunyuandit(controlnet_data):
- model_config, operations, load_device, unet_dtype, manual_cast_dtype = controlnet_config(controlnet_data)
+def load_controlnet_hunyuandit(controlnet_data, model_options={}):
+ model_config, operations, load_device, unet_dtype, manual_cast_dtype, offload_device = controlnet_config(controlnet_data, model_options=model_options)
- control_model = comfy.ldm.hydit.controlnet.HunYuanControlNet(operations=operations, device=load_device, dtype=unet_dtype)
+ control_model = comfy.ldm.hydit.controlnet.HunYuanControlNet(operations=operations, device=offload_device, dtype=unet_dtype)
control_model = controlnet_load_state_dict(control_model, controlnet_data)
latent_format = comfy.latent_formats.SDXL()
@@ -430,22 +462,49 @@ def load_controlnet_hunyuandit(controlnet_data):
control = ControlNet(control_model, compression_ratio=1, latent_format=latent_format, load_device=load_device, manual_cast_dtype=manual_cast_dtype, extra_conds=extra_conds, strength_type=StrengthType.CONSTANT)
return control
-def load_controlnet_flux_xlabs(sd):
- model_config, operations, load_device, unet_dtype, manual_cast_dtype = controlnet_config(sd)
- control_model = comfy.ldm.flux.controlnet_xlabs.ControlNetFlux(operations=operations, device=load_device, dtype=unet_dtype, **model_config.unet_config)
+def load_controlnet_flux_xlabs_mistoline(sd, mistoline=False, model_options={}):
+ model_config, operations, load_device, unet_dtype, manual_cast_dtype, offload_device = controlnet_config(sd, model_options=model_options)
+ control_model = comfy.ldm.flux.controlnet.ControlNetFlux(mistoline=mistoline, operations=operations, device=offload_device, dtype=unet_dtype, **model_config.unet_config)
control_model = controlnet_load_state_dict(control_model, sd)
extra_conds = ['y', 'guidance']
control = ControlNet(control_model, load_device=load_device, manual_cast_dtype=manual_cast_dtype, extra_conds=extra_conds)
return control
+def load_controlnet_flux_instantx(sd, model_options={}):
+ new_sd = comfy.model_detection.convert_diffusers_mmdit(sd, "")
+ model_config, operations, load_device, unet_dtype, manual_cast_dtype, offload_device = controlnet_config(new_sd, model_options=model_options)
+ for k in sd:
+ new_sd[k] = sd[k]
-def load_controlnet(ckpt_path, model=None):
- controlnet_data = comfy.utils.load_torch_file(ckpt_path, safe_load=True)
+ num_union_modes = 0
+ union_cnet = "controlnet_mode_embedder.weight"
+ if union_cnet in new_sd:
+ num_union_modes = new_sd[union_cnet].shape[0]
+
+ control_latent_channels = new_sd.get("pos_embed_input.weight").shape[1] // 4
+ concat_mask = False
+ if control_latent_channels == 17:
+ concat_mask = True
+
+ control_model = comfy.ldm.flux.controlnet.ControlNetFlux(latent_input=True, num_union_modes=num_union_modes, control_latent_channels=control_latent_channels, operations=operations, device=offload_device, dtype=unet_dtype, **model_config.unet_config)
+ control_model = controlnet_load_state_dict(control_model, new_sd)
+
+ latent_format = comfy.latent_formats.Flux()
+ extra_conds = ['y', 'guidance']
+ control = ControlNet(control_model, compression_ratio=1, latent_format=latent_format, concat_mask=concat_mask, load_device=load_device, manual_cast_dtype=manual_cast_dtype, extra_conds=extra_conds)
+ return control
+
+def convert_mistoline(sd):
+ return comfy.utils.state_dict_prefix_replace(sd, {"single_controlnet_blocks.": "controlnet_single_blocks."})
+
+
+def load_controlnet_state_dict(state_dict, model=None, model_options={}):
+ controlnet_data = state_dict
if 'after_proj_list.18.bias' in controlnet_data.keys(): #Hunyuan DiT
- return load_controlnet_hunyuandit(controlnet_data)
+ return load_controlnet_hunyuandit(controlnet_data, model_options=model_options)
if "lora_controlnet" in controlnet_data:
- return ControlLora(controlnet_data)
+ return ControlLora(controlnet_data, model_options=model_options)
controlnet_config = None
supported_inference_dtypes = None
@@ -500,11 +559,15 @@ def load_controlnet(ckpt_path, model=None):
if len(leftover_keys) > 0:
logging.warning("leftover keys: {}".format(leftover_keys))
controlnet_data = new_sd
- elif "controlnet_blocks.0.weight" in controlnet_data: #SD3 diffusers format
+ elif "controlnet_blocks.0.weight" in controlnet_data:
if "double_blocks.0.img_attn.norm.key_norm.scale" in controlnet_data:
- return load_controlnet_flux_xlabs(controlnet_data)
- else:
- return load_controlnet_mmdit(controlnet_data)
+ return load_controlnet_flux_xlabs_mistoline(controlnet_data, model_options=model_options)
+ elif "pos_embed_input.proj.weight" in controlnet_data:
+ return load_controlnet_mmdit(controlnet_data, model_options=model_options) #SD3 diffusers controlnet
+ elif "controlnet_x_embedder.weight" in controlnet_data:
+ return load_controlnet_flux_instantx(controlnet_data, model_options=model_options)
+ elif "controlnet_blocks.0.linear.weight" in controlnet_data: #mistoline flux
+ return load_controlnet_flux_xlabs_mistoline(convert_mistoline(controlnet_data), mistoline=True, model_options=model_options)
pth_key = 'control_model.zero_convs.0.0.weight'
pth = False
@@ -516,26 +579,38 @@ def load_controlnet(ckpt_path, model=None):
elif key in controlnet_data:
prefix = ""
else:
- net = load_t2i_adapter(controlnet_data)
+ net = load_t2i_adapter(controlnet_data, model_options=model_options)
if net is None:
- logging.error("error checkpoint does not contain controlnet or t2i adapter data {}".format(ckpt_path))
+ logging.error("error could not detect control model type.")
return net
if controlnet_config is None:
model_config = comfy.model_detection.model_config_from_unet(controlnet_data, prefix, True)
- supported_inference_dtypes = model_config.supported_inference_dtypes
+ supported_inference_dtypes = list(model_config.supported_inference_dtypes)
controlnet_config = model_config.unet_config
+ unet_dtype = model_options.get("dtype", None)
+ if unet_dtype is None:
+ weight_dtype = comfy.utils.weight_dtype(controlnet_data)
+
+ if supported_inference_dtypes is None:
+ supported_inference_dtypes = [comfy.model_management.unet_dtype()]
+
+ if weight_dtype is not None:
+ supported_inference_dtypes.append(weight_dtype)
+
+ unet_dtype = comfy.model_management.unet_dtype(model_params=-1, supported_dtypes=supported_inference_dtypes)
+
load_device = comfy.model_management.get_torch_device()
- if supported_inference_dtypes is None:
- unet_dtype = comfy.model_management.unet_dtype()
- else:
- unet_dtype = comfy.model_management.unet_dtype(supported_dtypes=supported_inference_dtypes)
manual_cast_dtype = comfy.model_management.unet_manual_cast(unet_dtype, load_device)
- if manual_cast_dtype is not None:
- controlnet_config["operations"] = comfy.ops.manual_cast
+ operations = model_options.get("custom_operations", None)
+ if operations is None:
+ operations = comfy.ops.pick_operations(unet_dtype, manual_cast_dtype)
+
+ controlnet_config["operations"] = operations
controlnet_config["dtype"] = unet_dtype
+ controlnet_config["device"] = comfy.model_management.unet_offload_device()
controlnet_config.pop("out_channels")
controlnet_config["hint_channels"] = controlnet_data["{}input_hint_block.0.weight".format(prefix)].shape[1]
control_model = comfy.cldm.cldm.ControlNet(**controlnet_config)
@@ -569,14 +644,21 @@ def load_controlnet(ckpt_path, model=None):
if len(unexpected) > 0:
logging.debug("unexpected controlnet keys: {}".format(unexpected))
- global_average_pooling = False
- filename = os.path.splitext(ckpt_path)[0]
- if filename.endswith("_shuffle") or filename.endswith("_shuffle_fp16"): #TODO: smarter way of enabling global_average_pooling
- global_average_pooling = True
-
+ global_average_pooling = model_options.get("global_average_pooling", False)
control = ControlNet(control_model, global_average_pooling=global_average_pooling, load_device=load_device, manual_cast_dtype=manual_cast_dtype)
return control
+def load_controlnet(ckpt_path, model=None, model_options={}):
+ if "global_average_pooling" not in model_options:
+ filename = os.path.splitext(ckpt_path)[0]
+ if filename.endswith("_shuffle") or filename.endswith("_shuffle_fp16"): #TODO: smarter way of enabling global_average_pooling
+ model_options["global_average_pooling"] = True
+
+ cnet = load_controlnet_state_dict(comfy.utils.load_torch_file(ckpt_path, safe_load=True), model=model, model_options=model_options)
+ if cnet is None:
+ logging.error("error checkpoint does not contain controlnet or t2i adapter data {}".format(ckpt_path))
+ return cnet
+
class T2IAdapter(ControlBase):
def __init__(self, t2i_model, channels_in, compression_ratio, upscale_algorithm, device=None):
super().__init__(device)
@@ -632,7 +714,7 @@ class T2IAdapter(ControlBase):
self.copy_to(c)
return c
-def load_t2i_adapter(t2i_data):
+def load_t2i_adapter(t2i_data, model_options={}): #TODO: model_options
compression_ratio = 8
upscale_algorithm = 'nearest-exact'
diff --git a/comfy/float.py b/comfy/float.py
new file mode 100644
index 000000000..4a6ae6776
--- /dev/null
+++ b/comfy/float.py
@@ -0,0 +1,66 @@
+import torch
+import math
+
+def calc_mantissa(abs_x, exponent, normal_mask, MANTISSA_BITS, EXPONENT_BIAS, generator=None):
+ mantissa_scaled = torch.where(
+ normal_mask,
+ (abs_x / (2.0 ** (exponent - EXPONENT_BIAS)) - 1.0) * (2**MANTISSA_BITS),
+ (abs_x / (2.0 ** (-EXPONENT_BIAS + 1 - MANTISSA_BITS)))
+ )
+
+ mantissa_scaled += torch.rand(mantissa_scaled.size(), dtype=mantissa_scaled.dtype, layout=mantissa_scaled.layout, device=mantissa_scaled.device, generator=generator)
+ return mantissa_scaled.floor() / (2**MANTISSA_BITS)
+
+#Not 100% sure about this
+def manual_stochastic_round_to_float8(x, dtype, generator=None):
+ if dtype == torch.float8_e4m3fn:
+ EXPONENT_BITS, MANTISSA_BITS, EXPONENT_BIAS = 4, 3, 7
+ elif dtype == torch.float8_e5m2:
+ EXPONENT_BITS, MANTISSA_BITS, EXPONENT_BIAS = 5, 2, 15
+ else:
+ raise ValueError("Unsupported dtype")
+
+ x = x.half()
+ sign = torch.sign(x)
+ abs_x = x.abs()
+ sign = torch.where(abs_x == 0, 0, sign)
+
+ # Combine exponent calculation and clamping
+ exponent = torch.clamp(
+ torch.floor(torch.log2(abs_x)) + EXPONENT_BIAS,
+ 0, 2**EXPONENT_BITS - 1
+ )
+
+ # Combine mantissa calculation and rounding
+ normal_mask = ~(exponent == 0)
+
+ abs_x[:] = calc_mantissa(abs_x, exponent, normal_mask, MANTISSA_BITS, EXPONENT_BIAS, generator=generator)
+
+ sign *= torch.where(
+ normal_mask,
+ (2.0 ** (exponent - EXPONENT_BIAS)) * (1.0 + abs_x),
+ (2.0 ** (-EXPONENT_BIAS + 1)) * abs_x
+ )
+
+ return sign
+
+
+
+def stochastic_rounding(value, dtype, seed=0):
+ if dtype == torch.float32:
+ return value.to(dtype=torch.float32)
+ if dtype == torch.float16:
+ return value.to(dtype=torch.float16)
+ if dtype == torch.bfloat16:
+ return value.to(dtype=torch.bfloat16)
+ if dtype == torch.float8_e4m3fn or dtype == torch.float8_e5m2:
+ generator = torch.Generator(device=value.device)
+ generator.manual_seed(seed)
+ output = torch.empty_like(value, dtype=dtype)
+ num_slices = max(1, (value.numel() / (4096 * 4096)))
+ slice_size = max(1, round(value.shape[0] / num_slices))
+ for i in range(0, value.shape[0], slice_size):
+ output[i:i+slice_size].copy_(manual_stochastic_round_to_float8(value[i:i+slice_size], dtype, generator=generator))
+ return output
+
+ return value.to(dtype=dtype)
diff --git a/comfy/k_diffusion/sampling.py b/comfy/k_diffusion/sampling.py
index 763d8cc78..70273d9d5 100644
--- a/comfy/k_diffusion/sampling.py
+++ b/comfy/k_diffusion/sampling.py
@@ -9,6 +9,7 @@ from tqdm.auto import trange, tqdm
from . import utils
from . import deis
import comfy.model_patcher
+import comfy.model_sampling
def append_zero(x):
return torch.cat([x, x.new_zeros([1])])
@@ -43,6 +44,17 @@ def get_sigmas_vp(n, beta_d=19.9, beta_min=0.1, eps_s=1e-3, device='cpu'):
return append_zero(sigmas)
+def get_sigmas_laplace(n, sigma_min, sigma_max, mu=0., beta=0.5, device='cpu'):
+ """Constructs the noise schedule proposed by Tiankai et al. (2024). """
+ epsilon = 1e-5 # avoid log(0)
+ x = torch.linspace(0, 1, n, device=device)
+ clamp = lambda x: torch.clamp(x, min=sigma_min, max=sigma_max)
+ lmb = mu - beta * torch.sign(0.5-x) * torch.log(1 - 2 * torch.abs(0.5-x) + epsilon)
+ sigmas = clamp(torch.exp(lmb))
+ return sigmas
+
+
+
def to_d(x, sigma, denoised):
"""Converts a denoiser output to a Karras ODE derivative."""
return (x - denoised) / utils.append_dims(sigma, x.ndim)
@@ -509,6 +521,9 @@ def sample_dpm_adaptive(model, x, sigma_min, sigma_max, extra_args=None, callbac
@torch.no_grad()
def sample_dpmpp_2s_ancestral(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None):
+ if isinstance(model.inner_model.inner_model.model_sampling, comfy.model_sampling.CONST):
+ return sample_dpmpp_2s_ancestral_RF(model, x, sigmas, extra_args, callback, disable, eta, s_noise, noise_sampler)
+
"""Ancestral sampling with DPM-Solver++(2S) second-order steps."""
extra_args = {} if extra_args is None else extra_args
noise_sampler = default_noise_sampler(x) if noise_sampler is None else noise_sampler
@@ -541,6 +556,55 @@ def sample_dpmpp_2s_ancestral(model, x, sigmas, extra_args=None, callback=None,
return x
+@torch.no_grad()
+def sample_dpmpp_2s_ancestral_RF(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None):
+ """Ancestral sampling with DPM-Solver++(2S) second-order steps."""
+ extra_args = {} if extra_args is None else extra_args
+ noise_sampler = default_noise_sampler(x) if noise_sampler is None else noise_sampler
+ s_in = x.new_ones([x.shape[0]])
+ sigma_fn = lambda lbda: (lbda.exp() + 1) ** -1
+ lambda_fn = lambda sigma: ((1-sigma)/sigma).log()
+
+ # logged_x = x.unsqueeze(0)
+
+ for i in trange(len(sigmas) - 1, disable=disable):
+ denoised = model(x, sigmas[i] * s_in, **extra_args)
+ downstep_ratio = 1 + (sigmas[i+1]/sigmas[i] - 1) * eta
+ sigma_down = sigmas[i+1] * downstep_ratio
+ alpha_ip1 = 1 - sigmas[i+1]
+ alpha_down = 1 - sigma_down
+ renoise_coeff = (sigmas[i+1]**2 - sigma_down**2*alpha_ip1**2/alpha_down**2)**0.5
+ # sigma_down, sigma_up = get_ancestral_step(sigmas[i], sigmas[i + 1], eta=eta)
+ if callback is not None:
+ callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised})
+ if sigmas[i + 1] == 0:
+ # Euler method
+ d = to_d(x, sigmas[i], denoised)
+ dt = sigma_down - sigmas[i]
+ x = x + d * dt
+ else:
+ # DPM-Solver++(2S)
+ if sigmas[i] == 1.0:
+ sigma_s = 0.9999
+ else:
+ t_i, t_down = lambda_fn(sigmas[i]), lambda_fn(sigma_down)
+ r = 1 / 2
+ h = t_down - t_i
+ s = t_i + r * h
+ sigma_s = sigma_fn(s)
+ # sigma_s = sigmas[i+1]
+ sigma_s_i_ratio = sigma_s / sigmas[i]
+ u = sigma_s_i_ratio * x + (1 - sigma_s_i_ratio) * denoised
+ D_i = model(u, sigma_s * s_in, **extra_args)
+ sigma_down_i_ratio = sigma_down / sigmas[i]
+ x = sigma_down_i_ratio * x + (1 - sigma_down_i_ratio) * D_i
+ # print("sigma_i", sigmas[i], "sigma_ip1", sigmas[i+1],"sigma_down", sigma_down, "sigma_down_i_ratio", sigma_down_i_ratio, "sigma_s_i_ratio", sigma_s_i_ratio, "renoise_coeff", renoise_coeff)
+ # Noise addition
+ if sigmas[i + 1] > 0 and eta > 0:
+ x = (alpha_ip1/alpha_down) * x + noise_sampler(sigmas[i], sigmas[i + 1]) * s_noise * renoise_coeff
+ # logged_x = torch.cat((logged_x, x.unsqueeze(0)), dim=0)
+ return x
+
@torch.no_grad()
def sample_dpmpp_sde(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None, r=1 / 2):
"""DPM-Solver++ (stochastic)."""
@@ -1048,3 +1112,78 @@ def sample_euler_ancestral_cfg_pp(model, x, sigmas, extra_args=None, callback=No
if sigmas[i + 1] > 0:
x = x + noise_sampler(sigmas[i], sigmas[i + 1]) * s_noise * sigma_up
return x
+@torch.no_grad()
+def sample_dpmpp_2s_ancestral_cfg_pp(model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1., s_noise=1., noise_sampler=None):
+ """Ancestral sampling with DPM-Solver++(2S) second-order steps."""
+ extra_args = {} if extra_args is None else extra_args
+ noise_sampler = default_noise_sampler(x) if noise_sampler is None else noise_sampler
+
+ temp = [0]
+ def post_cfg_function(args):
+ temp[0] = args["uncond_denoised"]
+ return args["denoised"]
+
+ model_options = extra_args.get("model_options", {}).copy()
+ extra_args["model_options"] = comfy.model_patcher.set_model_options_post_cfg_function(model_options, post_cfg_function, disable_cfg1_optimization=True)
+
+ s_in = x.new_ones([x.shape[0]])
+ sigma_fn = lambda t: t.neg().exp()
+ t_fn = lambda sigma: sigma.log().neg()
+
+ for i in trange(len(sigmas) - 1, disable=disable):
+ denoised = model(x, sigmas[i] * s_in, **extra_args)
+ sigma_down, sigma_up = get_ancestral_step(sigmas[i], sigmas[i + 1], eta=eta)
+ if callback is not None:
+ callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised})
+ if sigma_down == 0:
+ # Euler method
+ d = to_d(x, sigmas[i], temp[0])
+ dt = sigma_down - sigmas[i]
+ x = denoised + d * sigma_down
+ else:
+ # DPM-Solver++(2S)
+ t, t_next = t_fn(sigmas[i]), t_fn(sigma_down)
+ # r = torch.sinh(1 + (2 - eta) * (t_next - t) / (t - t_fn(sigma_up))) works only on non-cfgpp, weird
+ r = 1 / 2
+ h = t_next - t
+ s = t + r * h
+ x_2 = (sigma_fn(s) / sigma_fn(t)) * (x + (denoised - temp[0])) - (-h * r).expm1() * denoised
+ denoised_2 = model(x_2, sigma_fn(s) * s_in, **extra_args)
+ x = (sigma_fn(t_next) / sigma_fn(t)) * (x + (denoised - temp[0])) - (-h).expm1() * denoised_2
+ # Noise addition
+ if sigmas[i + 1] > 0:
+ x = x + noise_sampler(sigmas[i], sigmas[i + 1]) * s_noise * sigma_up
+ return x
+
+@torch.no_grad()
+def sample_dpmpp_2m_cfg_pp(model, x, sigmas, extra_args=None, callback=None, disable=None):
+ """DPM-Solver++(2M)."""
+ extra_args = {} if extra_args is None else extra_args
+ s_in = x.new_ones([x.shape[0]])
+ t_fn = lambda sigma: sigma.log().neg()
+
+ old_uncond_denoised = None
+ uncond_denoised = None
+ def post_cfg_function(args):
+ nonlocal uncond_denoised
+ uncond_denoised = args["uncond_denoised"]
+ return args["denoised"]
+
+ model_options = extra_args.get("model_options", {}).copy()
+ extra_args["model_options"] = comfy.model_patcher.set_model_options_post_cfg_function(model_options, post_cfg_function, disable_cfg1_optimization=True)
+
+ for i in trange(len(sigmas) - 1, disable=disable):
+ denoised = model(x, sigmas[i] * s_in, **extra_args)
+ if callback is not None:
+ callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised})
+ t, t_next = t_fn(sigmas[i]), t_fn(sigmas[i + 1])
+ h = t_next - t
+ if old_uncond_denoised is None or sigmas[i + 1] == 0:
+ denoised_mix = -torch.exp(-h) * uncond_denoised
+ else:
+ h_last = t - t_fn(sigmas[i - 1])
+ r = h_last / h
+ denoised_mix = -torch.exp(-h) * uncond_denoised - torch.expm1(-h) * (1 / (2 * r)) * (denoised - old_uncond_denoised)
+ x = denoised + denoised_mix + torch.exp(-h) * x
+ old_uncond_denoised = uncond_denoised
+ return x
\ No newline at end of file
diff --git a/comfy/latent_formats.py b/comfy/latent_formats.py
index ecb03b010..ee19faeae 100644
--- a/comfy/latent_formats.py
+++ b/comfy/latent_formats.py
@@ -141,6 +141,7 @@ class StableAudio1(LatentFormat):
latent_channels = 64
class Flux(SD3):
+ latent_channels = 16
def __init__(self):
self.scale_factor = 0.3611
self.shift_factor = 0.1159
@@ -162,6 +163,7 @@ class Flux(SD3):
[-0.0005, -0.0530, -0.0020],
[-0.1273, -0.0932, -0.0680]
]
+ self.taesd_decoder_name = "taef1_decoder"
def process_in(self, latent):
return (latent - self.shift_factor) * self.scale_factor
diff --git a/comfy/ldm/common_dit.py b/comfy/ldm/common_dit.py
index 990025521..5aebaf9ea 100644
--- a/comfy/ldm/common_dit.py
+++ b/comfy/ldm/common_dit.py
@@ -1,4 +1,5 @@
import torch
+import comfy.ops
def pad_to_patch_size(img, patch_size=(2, 2), padding_mode="circular"):
if padding_mode == "circular" and torch.jit.is_tracing() or torch.jit.is_scripting():
@@ -6,3 +7,15 @@ def pad_to_patch_size(img, patch_size=(2, 2), padding_mode="circular"):
pad_h = (patch_size[0] - img.shape[-2] % patch_size[0]) % patch_size[0]
pad_w = (patch_size[1] - img.shape[-1] % patch_size[1]) % patch_size[1]
return torch.nn.functional.pad(img, (0, pad_w, 0, pad_h), mode=padding_mode)
+
+try:
+ rms_norm_torch = torch.nn.functional.rms_norm
+except:
+ rms_norm_torch = None
+
+def rms_norm(x, weight, eps=1e-6):
+ if rms_norm_torch is not None and not (torch.jit.is_tracing() or torch.jit.is_scripting()):
+ return rms_norm_torch(x, weight.shape, weight=comfy.ops.cast_to(weight, dtype=x.dtype, device=x.device), eps=eps)
+ else:
+ rrms = torch.rsqrt(torch.mean(x**2, dim=-1, keepdim=True) + eps)
+ return (x * rrms) * comfy.ops.cast_to(weight, dtype=x.dtype, device=x.device)
diff --git a/comfy/ldm/flux/controlnet.py b/comfy/ldm/flux/controlnet.py
new file mode 100644
index 000000000..c033dea52
--- /dev/null
+++ b/comfy/ldm/flux/controlnet.py
@@ -0,0 +1,205 @@
+#Original code can be found on: https://github.com/XLabs-AI/x-flux/blob/main/src/flux/controlnet.py
+#modified to support different types of flux controlnets
+
+import torch
+import math
+from torch import Tensor, nn
+from einops import rearrange, repeat
+
+from .layers import (DoubleStreamBlock, EmbedND, LastLayer,
+ MLPEmbedder, SingleStreamBlock,
+ timestep_embedding)
+
+from .model import Flux
+import comfy.ldm.common_dit
+
+class MistolineCondDownsamplBlock(nn.Module):
+ def __init__(self, dtype=None, device=None, operations=None):
+ super().__init__()
+ self.encoder = nn.Sequential(
+ operations.Conv2d(3, 16, 3, padding=1, dtype=dtype, device=device),
+ nn.SiLU(),
+ operations.Conv2d(16, 16, 1, dtype=dtype, device=device),
+ nn.SiLU(),
+ operations.Conv2d(16, 16, 3, padding=1, dtype=dtype, device=device),
+ nn.SiLU(),
+ operations.Conv2d(16, 16, 3, padding=1, stride=2, dtype=dtype, device=device),
+ nn.SiLU(),
+ operations.Conv2d(16, 16, 3, padding=1, dtype=dtype, device=device),
+ nn.SiLU(),
+ operations.Conv2d(16, 16, 3, padding=1, stride=2, dtype=dtype, device=device),
+ nn.SiLU(),
+ operations.Conv2d(16, 16, 3, padding=1, dtype=dtype, device=device),
+ nn.SiLU(),
+ operations.Conv2d(16, 16, 3, padding=1, stride=2, dtype=dtype, device=device),
+ nn.SiLU(),
+ operations.Conv2d(16, 16, 1, dtype=dtype, device=device),
+ nn.SiLU(),
+ operations.Conv2d(16, 16, 3, padding=1, dtype=dtype, device=device)
+ )
+
+ def forward(self, x):
+ return self.encoder(x)
+
+class MistolineControlnetBlock(nn.Module):
+ def __init__(self, hidden_size, dtype=None, device=None, operations=None):
+ super().__init__()
+ self.linear = operations.Linear(hidden_size, hidden_size, dtype=dtype, device=device)
+ self.act = nn.SiLU()
+
+ def forward(self, x):
+ return self.act(self.linear(x))
+
+
+class ControlNetFlux(Flux):
+ def __init__(self, latent_input=False, num_union_modes=0, mistoline=False, control_latent_channels=None, image_model=None, dtype=None, device=None, operations=None, **kwargs):
+ super().__init__(final_layer=False, dtype=dtype, device=device, operations=operations, **kwargs)
+
+ self.main_model_double = 19
+ self.main_model_single = 38
+
+ self.mistoline = mistoline
+ # add ControlNet blocks
+ if self.mistoline:
+ control_block = lambda : MistolineControlnetBlock(self.hidden_size, dtype=dtype, device=device, operations=operations)
+ else:
+ control_block = lambda : operations.Linear(self.hidden_size, self.hidden_size, dtype=dtype, device=device)
+
+ self.controlnet_blocks = nn.ModuleList([])
+ for _ in range(self.params.depth):
+ self.controlnet_blocks.append(control_block())
+
+ self.controlnet_single_blocks = nn.ModuleList([])
+ for _ in range(self.params.depth_single_blocks):
+ self.controlnet_single_blocks.append(control_block())
+
+ self.num_union_modes = num_union_modes
+ self.controlnet_mode_embedder = None
+ if self.num_union_modes > 0:
+ self.controlnet_mode_embedder = operations.Embedding(self.num_union_modes, self.hidden_size, dtype=dtype, device=device)
+
+ self.gradient_checkpointing = False
+ self.latent_input = latent_input
+ if control_latent_channels is None:
+ control_latent_channels = self.in_channels
+ else:
+ control_latent_channels *= 2 * 2 #patch size
+
+ self.pos_embed_input = operations.Linear(control_latent_channels, self.hidden_size, bias=True, dtype=dtype, device=device)
+ if not self.latent_input:
+ if self.mistoline:
+ self.input_cond_block = MistolineCondDownsamplBlock(dtype=dtype, device=device, operations=operations)
+ else:
+ self.input_hint_block = nn.Sequential(
+ operations.Conv2d(3, 16, 3, padding=1, dtype=dtype, device=device),
+ nn.SiLU(),
+ operations.Conv2d(16, 16, 3, padding=1, dtype=dtype, device=device),
+ nn.SiLU(),
+ operations.Conv2d(16, 16, 3, padding=1, stride=2, dtype=dtype, device=device),
+ nn.SiLU(),
+ operations.Conv2d(16, 16, 3, padding=1, dtype=dtype, device=device),
+ nn.SiLU(),
+ operations.Conv2d(16, 16, 3, padding=1, stride=2, dtype=dtype, device=device),
+ nn.SiLU(),
+ operations.Conv2d(16, 16, 3, padding=1, dtype=dtype, device=device),
+ nn.SiLU(),
+ operations.Conv2d(16, 16, 3, padding=1, stride=2, dtype=dtype, device=device),
+ nn.SiLU(),
+ operations.Conv2d(16, 16, 3, padding=1, dtype=dtype, device=device)
+ )
+
+ def forward_orig(
+ self,
+ img: Tensor,
+ img_ids: Tensor,
+ controlnet_cond: Tensor,
+ txt: Tensor,
+ txt_ids: Tensor,
+ timesteps: Tensor,
+ y: Tensor,
+ guidance: Tensor = None,
+ control_type: Tensor = None,
+ ) -> Tensor:
+ if img.ndim != 3 or txt.ndim != 3:
+ raise ValueError("Input img and txt tensors must have 3 dimensions.")
+
+ # running on sequences img
+ img = self.img_in(img)
+
+ controlnet_cond = self.pos_embed_input(controlnet_cond)
+ img = img + controlnet_cond
+ vec = self.time_in(timestep_embedding(timesteps, 256))
+ if self.params.guidance_embed:
+ vec = vec + self.guidance_in(timestep_embedding(guidance, 256))
+ vec = vec + self.vector_in(y)
+ txt = self.txt_in(txt)
+
+ if self.controlnet_mode_embedder is not None and len(control_type) > 0:
+ control_cond = self.controlnet_mode_embedder(torch.tensor(control_type, device=img.device), out_dtype=img.dtype).unsqueeze(0).repeat((txt.shape[0], 1, 1))
+ txt = torch.cat([control_cond, txt], dim=1)
+ txt_ids = torch.cat([txt_ids[:,:1], txt_ids], dim=1)
+
+ ids = torch.cat((txt_ids, img_ids), dim=1)
+ pe = self.pe_embedder(ids)
+
+ controlnet_double = ()
+
+ for i in range(len(self.double_blocks)):
+ img, txt = self.double_blocks[i](img=img, txt=txt, vec=vec, pe=pe)
+ controlnet_double = controlnet_double + (self.controlnet_blocks[i](img),)
+
+ img = torch.cat((txt, img), 1)
+
+ controlnet_single = ()
+
+ for i in range(len(self.single_blocks)):
+ img = self.single_blocks[i](img, vec=vec, pe=pe)
+ controlnet_single = controlnet_single + (self.controlnet_single_blocks[i](img[:, txt.shape[1] :, ...]),)
+
+ repeat = math.ceil(self.main_model_double / len(controlnet_double))
+ if self.latent_input:
+ out_input = ()
+ for x in controlnet_double:
+ out_input += (x,) * repeat
+ else:
+ out_input = (controlnet_double * repeat)
+
+ out = {"input": out_input[:self.main_model_double]}
+ if len(controlnet_single) > 0:
+ repeat = math.ceil(self.main_model_single / len(controlnet_single))
+ out_output = ()
+ if self.latent_input:
+ for x in controlnet_single:
+ out_output += (x,) * repeat
+ else:
+ out_output = (controlnet_single * repeat)
+ out["output"] = out_output[:self.main_model_single]
+ return out
+
+ def forward(self, x, timesteps, context, y, guidance=None, hint=None, **kwargs):
+ patch_size = 2
+ if self.latent_input:
+ hint = comfy.ldm.common_dit.pad_to_patch_size(hint, (patch_size, patch_size))
+ elif self.mistoline:
+ hint = hint * 2.0 - 1.0
+ hint = self.input_cond_block(hint)
+ else:
+ hint = hint * 2.0 - 1.0
+ hint = self.input_hint_block(hint)
+
+ hint = rearrange(hint, "b c (h ph) (w pw) -> b (h w) (c ph pw)", ph=patch_size, pw=patch_size)
+
+ bs, c, h, w = x.shape
+ x = comfy.ldm.common_dit.pad_to_patch_size(x, (patch_size, patch_size))
+
+ img = rearrange(x, "b c (h ph) (w pw) -> b (h w) (c ph pw)", ph=patch_size, pw=patch_size)
+
+ h_len = ((h + (patch_size // 2)) // patch_size)
+ w_len = ((w + (patch_size // 2)) // patch_size)
+ img_ids = torch.zeros((h_len, w_len, 3), device=x.device, dtype=x.dtype)
+ img_ids[..., 1] = img_ids[..., 1] + torch.linspace(0, h_len - 1, steps=h_len, device=x.device, dtype=x.dtype)[:, None]
+ img_ids[..., 2] = img_ids[..., 2] + torch.linspace(0, w_len - 1, steps=w_len, device=x.device, dtype=x.dtype)[None, :]
+ img_ids = repeat(img_ids, "h w c -> b (h w) c", b=bs)
+
+ txt_ids = torch.zeros((bs, context.shape[1], 3), device=x.device, dtype=x.dtype)
+ return self.forward_orig(img, img_ids, hint, context, txt_ids, timesteps, y, guidance, control_type=kwargs.get("control_type", []))
diff --git a/comfy/ldm/flux/controlnet_xlabs.py b/comfy/ldm/flux/controlnet_xlabs.py
deleted file mode 100644
index 3f40021b2..000000000
--- a/comfy/ldm/flux/controlnet_xlabs.py
+++ /dev/null
@@ -1,104 +0,0 @@
-#Original code can be found on: https://github.com/XLabs-AI/x-flux/blob/main/src/flux/controlnet.py
-
-import torch
-from torch import Tensor, nn
-from einops import rearrange, repeat
-
-from .layers import (DoubleStreamBlock, EmbedND, LastLayer,
- MLPEmbedder, SingleStreamBlock,
- timestep_embedding)
-
-from .model import Flux
-import comfy.ldm.common_dit
-
-
-class ControlNetFlux(Flux):
- def __init__(self, image_model=None, dtype=None, device=None, operations=None, **kwargs):
- super().__init__(final_layer=False, dtype=dtype, device=device, operations=operations, **kwargs)
-
- # add ControlNet blocks
- self.controlnet_blocks = nn.ModuleList([])
- for _ in range(self.params.depth):
- controlnet_block = operations.Linear(self.hidden_size, self.hidden_size, dtype=dtype, device=device)
- # controlnet_block = zero_module(controlnet_block)
- self.controlnet_blocks.append(controlnet_block)
- self.pos_embed_input = operations.Linear(self.in_channels, self.hidden_size, bias=True, dtype=dtype, device=device)
- self.gradient_checkpointing = False
- self.input_hint_block = nn.Sequential(
- operations.Conv2d(3, 16, 3, padding=1, dtype=dtype, device=device),
- nn.SiLU(),
- operations.Conv2d(16, 16, 3, padding=1, dtype=dtype, device=device),
- nn.SiLU(),
- operations.Conv2d(16, 16, 3, padding=1, stride=2, dtype=dtype, device=device),
- nn.SiLU(),
- operations.Conv2d(16, 16, 3, padding=1, dtype=dtype, device=device),
- nn.SiLU(),
- operations.Conv2d(16, 16, 3, padding=1, stride=2, dtype=dtype, device=device),
- nn.SiLU(),
- operations.Conv2d(16, 16, 3, padding=1, dtype=dtype, device=device),
- nn.SiLU(),
- operations.Conv2d(16, 16, 3, padding=1, stride=2, dtype=dtype, device=device),
- nn.SiLU(),
- operations.Conv2d(16, 16, 3, padding=1, dtype=dtype, device=device)
- )
-
- def forward_orig(
- self,
- img: Tensor,
- img_ids: Tensor,
- controlnet_cond: Tensor,
- txt: Tensor,
- txt_ids: Tensor,
- timesteps: Tensor,
- y: Tensor,
- guidance: Tensor = None,
- ) -> Tensor:
- if img.ndim != 3 or txt.ndim != 3:
- raise ValueError("Input img and txt tensors must have 3 dimensions.")
-
- # running on sequences img
- img = self.img_in(img)
- controlnet_cond = self.input_hint_block(controlnet_cond)
- controlnet_cond = rearrange(controlnet_cond, "b c (h ph) (w pw) -> b (h w) (c ph pw)", ph=2, pw=2)
- controlnet_cond = self.pos_embed_input(controlnet_cond)
- img = img + controlnet_cond
- vec = self.time_in(timestep_embedding(timesteps, 256))
- if self.params.guidance_embed:
- vec = vec + self.guidance_in(timestep_embedding(guidance, 256))
- vec = vec + self.vector_in(y)
- txt = self.txt_in(txt)
-
- ids = torch.cat((txt_ids, img_ids), dim=1)
- pe = self.pe_embedder(ids)
-
- block_res_samples = ()
-
- for block in self.double_blocks:
- img, txt = block(img=img, txt=txt, vec=vec, pe=pe)
- block_res_samples = block_res_samples + (img,)
-
- controlnet_block_res_samples = ()
- for block_res_sample, controlnet_block in zip(block_res_samples, self.controlnet_blocks):
- block_res_sample = controlnet_block(block_res_sample)
- controlnet_block_res_samples = controlnet_block_res_samples + (block_res_sample,)
-
- return {"output": (controlnet_block_res_samples * 10)[:19]}
-
- def forward(self, x, timesteps, context, y, guidance=None, hint=None, **kwargs):
- hint = hint * 2.0 - 1.0
-
- bs, c, h, w = x.shape
- patch_size = 2
- x = comfy.ldm.common_dit.pad_to_patch_size(x, (patch_size, patch_size))
-
- img = rearrange(x, "b c (h ph) (w pw) -> b (h w) (c ph pw)", ph=patch_size, pw=patch_size)
-
- h_len = ((h + (patch_size // 2)) // patch_size)
- w_len = ((w + (patch_size // 2)) // patch_size)
- img_ids = torch.zeros((h_len, w_len, 3), device=x.device, dtype=x.dtype)
- img_ids[..., 1] = img_ids[..., 1] + torch.linspace(0, h_len - 1, steps=h_len, device=x.device, dtype=x.dtype)[:, None]
- img_ids[..., 2] = img_ids[..., 2] + torch.linspace(0, w_len - 1, steps=w_len, device=x.device, dtype=x.dtype)[None, :]
- img_ids = repeat(img_ids, "h w c -> b (h w) c", b=bs)
-
- txt_ids = torch.zeros((bs, context.shape[1], 3), device=x.device, dtype=x.dtype)
- return self.forward_orig(img, img_ids, hint, context, txt_ids, timesteps, y, guidance)
diff --git a/comfy/ldm/flux/layers.py b/comfy/ldm/flux/layers.py
index da0cf61b1..dabab3e33 100644
--- a/comfy/ldm/flux/layers.py
+++ b/comfy/ldm/flux/layers.py
@@ -6,6 +6,7 @@ from torch import Tensor, nn
from .math import attention, rope
import comfy.ops
+import comfy.ldm.common_dit
class EmbedND(nn.Module):
@@ -63,10 +64,7 @@ class RMSNorm(torch.nn.Module):
self.scale = nn.Parameter(torch.empty((dim), dtype=dtype, device=device))
def forward(self, x: Tensor):
- x_dtype = x.dtype
- x = x.float()
- rrms = torch.rsqrt(torch.mean(x**2, dim=-1, keepdim=True) + 1e-6)
- return (x * rrms).to(dtype=x_dtype) * comfy.ops.cast_to(self.scale, dtype=x_dtype, device=x.device)
+ return comfy.ldm.common_dit.rms_norm(x, self.scale, 1e-6)
class QKNorm(torch.nn.Module):
@@ -178,7 +176,7 @@ class DoubleStreamBlock(nn.Module):
txt += txt_mod2.gate * self.txt_mlp((1 + txt_mod2.scale) * self.txt_norm2(txt) + txt_mod2.shift)
if txt.dtype == torch.float16:
- txt = txt.clip(-65504, 65504)
+ txt = torch.nan_to_num(txt, nan=0.0, posinf=65504, neginf=-65504)
return img, txt
@@ -233,7 +231,7 @@ class SingleStreamBlock(nn.Module):
output = self.linear2(torch.cat((attn, self.mlp_act(mlp)), 2))
x += mod.gate * output
if x.dtype == torch.float16:
- x = x.clip(-65504, 65504)
+ x = torch.nan_to_num(x, nan=0.0, posinf=65504, neginf=-65504)
return x
diff --git a/comfy/ldm/flux/model.py b/comfy/ldm/flux/model.py
index b5373540a..63970cad2 100644
--- a/comfy/ldm/flux/model.py
+++ b/comfy/ldm/flux/model.py
@@ -114,19 +114,28 @@ class Flux(nn.Module):
ids = torch.cat((txt_ids, img_ids), dim=1)
pe = self.pe_embedder(ids)
- for i in range(len(self.double_blocks)):
- img, txt = self.double_blocks[i](img=img, txt=txt, vec=vec, pe=pe)
+ for i, block in enumerate(self.double_blocks):
+ img, txt = block(img=img, txt=txt, vec=vec, pe=pe)
- if control is not None: #Controlnet
- control_o = control.get("output")
- if i < len(control_o):
- add = control_o[i]
+ if control is not None: # Controlnet
+ control_i = control.get("input")
+ if i < len(control_i):
+ add = control_i[i]
if add is not None:
img += add
img = torch.cat((txt, img), 1)
- for block in self.single_blocks:
+
+ for i, block in enumerate(self.single_blocks):
img = block(img, vec=vec, pe=pe)
+
+ if control is not None: # Controlnet
+ control_o = control.get("output")
+ if i < len(control_o):
+ add = control_o[i]
+ if add is not None:
+ img[:, txt.shape[1] :, ...] += add
+
img = img[:, txt.shape[1] :, ...]
img = self.final_layer(img, vec) # (N, T, patch_size ** 2 * out_channels)
diff --git a/comfy/ldm/hydit/models.py b/comfy/ldm/hydit/models.py
index f3afaad34..44e806cba 100644
--- a/comfy/ldm/hydit/models.py
+++ b/comfy/ldm/hydit/models.py
@@ -372,7 +372,7 @@ class HunYuanDiT(nn.Module):
for layer, block in enumerate(self.blocks):
if layer > self.depth // 2:
if controls is not None:
- skip = skips.pop() + controls.pop()
+ skip = skips.pop() + controls.pop().to(dtype=x.dtype)
else:
skip = skips.pop()
x = block(x, c, text_states, freqs_cis_img, skip) # (N, L, D)
diff --git a/comfy/ldm/modules/diffusionmodules/mmdit.py b/comfy/ldm/modules/diffusionmodules/mmdit.py
index 491a58a20..759788a97 100644
--- a/comfy/ldm/modules/diffusionmodules/mmdit.py
+++ b/comfy/ldm/modules/diffusionmodules/mmdit.py
@@ -355,29 +355,9 @@ class RMSNorm(torch.nn.Module):
else:
self.register_parameter("weight", None)
- def _norm(self, x):
- """
- Apply the RMSNorm normalization to the input tensor.
- Args:
- x (torch.Tensor): The input tensor.
- Returns:
- torch.Tensor: The normalized tensor.
- """
- return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
-
def forward(self, x):
- """
- Forward pass through the RMSNorm layer.
- Args:
- x (torch.Tensor): The input tensor.
- Returns:
- torch.Tensor: The output tensor after applying RMSNorm.
- """
- x = self._norm(x)
- if self.learnable_scale:
- return x * self.weight.to(device=x.device, dtype=x.dtype)
- else:
- return x
+ return comfy.ldm.common_dit.rms_norm(x, self.weight, self.eps)
+
class SwiGLUFeedForward(nn.Module):
diff --git a/comfy/ldm/modules/diffusionmodules/openaimodel.py b/comfy/ldm/modules/diffusionmodules/openaimodel.py
index 6535e899c..2902073d5 100644
--- a/comfy/ldm/modules/diffusionmodules/openaimodel.py
+++ b/comfy/ldm/modules/diffusionmodules/openaimodel.py
@@ -842,6 +842,11 @@ class UNetModel(nn.Module):
t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False).to(x.dtype)
emb = self.time_embed(t_emb)
+ if "emb_patch" in transformer_patches:
+ patch = transformer_patches["emb_patch"]
+ for p in patch:
+ emb = p(emb, self.model_channels, transformer_options)
+
if self.num_classes is not None:
assert y.shape[0] == x.shape[0]
emb = emb + self.label_emb(y)
diff --git a/comfy/lora.py b/comfy/lora.py
index 3b8b6c162..83e55ec07 100644
--- a/comfy/lora.py
+++ b/comfy/lora.py
@@ -16,8 +16,12 @@
along with this program. If not, see .
"""
+from __future__ import annotations
import comfy.utils
+import comfy.model_management
+import comfy.model_base
import logging
+import torch
LORA_CLIP_MAP = {
"mlp.fc1": "mlp_fc1",
@@ -197,9 +201,13 @@ def load_lora(lora, to_load):
def model_lora_keys_clip(model, key_map={}):
sdk = model.state_dict().keys()
+ for k in sdk:
+ if k.endswith(".weight"):
+ key_map["text_encoders.{}".format(k[:-len(".weight")])] = k #generic lora format without any weird key names
text_model_lora_key = "lora_te_text_model_encoder_layers_{}_{}"
clip_l_present = False
+ clip_g_present = False
for b in range(32): #TODO: clean up
for c in LORA_CLIP_MAP:
k = "clip_h.transformer.text_model.encoder.layers.{}.{}.weight".format(b, c)
@@ -223,6 +231,7 @@ def model_lora_keys_clip(model, key_map={}):
k = "clip_g.transformer.text_model.encoder.layers.{}.{}.weight".format(b, c)
if k in sdk:
+ clip_g_present = True
if clip_l_present:
lora_key = "lora_te2_text_model_encoder_layers_{}_{}".format(b, LORA_CLIP_MAP[c]) #SDXL base
key_map[lora_key] = k
@@ -238,10 +247,18 @@ def model_lora_keys_clip(model, key_map={}):
for k in sdk:
if k.endswith(".weight"):
- if k.startswith("t5xxl.transformer."):#OneTrainer SD3 lora
+ if k.startswith("t5xxl.transformer."):#OneTrainer SD3 and Flux lora
l_key = k[len("t5xxl.transformer."):-len(".weight")]
- lora_key = "lora_te3_{}".format(l_key.replace(".", "_"))
- key_map[lora_key] = k
+ t5_index = 1
+ if clip_g_present:
+ t5_index += 1
+ if clip_l_present:
+ t5_index += 1
+ if t5_index == 2:
+ key_map["lora_te{}_{}".format(t5_index, l_key.replace(".", "_"))] = k #OneTrainer Flux
+ t5_index += 1
+
+ key_map["lora_te{}_{}".format(t5_index, l_key.replace(".", "_"))] = k
elif k.startswith("hydit_clip.transformer.bert."): #HunyuanDiT Lora
l_key = k[len("hydit_clip.transformer.bert."):-len(".weight")]
lora_key = "lora_te1_{}".format(l_key.replace(".", "_"))
@@ -318,7 +335,256 @@ def model_lora_keys_unet(model, key_map={}):
for k in diffusers_keys:
if k.endswith(".weight"):
to = diffusers_keys[k]
- key_lora = "transformer.{}".format(k[:-len(".weight")]) #simpletrainer and probably regular diffusers flux lora format
- key_map[key_lora] = to
+ key_map["transformer.{}".format(k[:-len(".weight")])] = to #simpletrainer and probably regular diffusers flux lora format
+ key_map["lycoris_{}".format(k[:-len(".weight")].replace(".", "_"))] = to #simpletrainer lycoris
+ key_map["lora_transformer_{}".format(k[:-len(".weight")].replace(".", "_"))] = to #onetrainer
return key_map
+
+
+def weight_decompose(dora_scale, weight, lora_diff, alpha, strength, intermediate_dtype):
+ dora_scale = comfy.model_management.cast_to_device(dora_scale, weight.device, intermediate_dtype)
+ lora_diff *= alpha
+ weight_calc = weight + lora_diff.type(weight.dtype)
+ weight_norm = (
+ weight_calc.transpose(0, 1)
+ .reshape(weight_calc.shape[1], -1)
+ .norm(dim=1, keepdim=True)
+ .reshape(weight_calc.shape[1], *[1] * (weight_calc.dim() - 1))
+ .transpose(0, 1)
+ )
+
+ weight_calc *= (dora_scale / weight_norm).type(weight.dtype)
+ if strength != 1.0:
+ weight_calc -= weight
+ weight += strength * (weight_calc)
+ else:
+ weight[:] = weight_calc
+ return weight
+
+def pad_tensor_to_shape(tensor: torch.Tensor, new_shape: list[int]) -> torch.Tensor:
+ """
+ Pad a tensor to a new shape with zeros.
+
+ Args:
+ tensor (torch.Tensor): The original tensor to be padded.
+ new_shape (List[int]): The desired shape of the padded tensor.
+
+ Returns:
+ torch.Tensor: A new tensor padded with zeros to the specified shape.
+
+ Note:
+ If the new shape is smaller than the original tensor in any dimension,
+ the original tensor will be truncated in that dimension.
+ """
+ if any([new_shape[i] < tensor.shape[i] for i in range(len(new_shape))]):
+ raise ValueError("The new shape must be larger than the original tensor in all dimensions")
+
+ if len(new_shape) != len(tensor.shape):
+ raise ValueError("The new shape must have the same number of dimensions as the original tensor")
+
+ # Create a new tensor filled with zeros
+ padded_tensor = torch.zeros(new_shape, dtype=tensor.dtype, device=tensor.device)
+
+ # Create slicing tuples for both tensors
+ orig_slices = tuple(slice(0, dim) for dim in tensor.shape)
+ new_slices = tuple(slice(0, dim) for dim in tensor.shape)
+
+ # Copy the original tensor into the new tensor
+ padded_tensor[new_slices] = tensor[orig_slices]
+
+ return padded_tensor
+
+def calculate_weight(patches, weight, key, intermediate_dtype=torch.float32):
+ for p in patches:
+ strength = p[0]
+ v = p[1]
+ strength_model = p[2]
+ offset = p[3]
+ function = p[4]
+ if function is None:
+ function = lambda a: a
+
+ old_weight = None
+ if offset is not None:
+ old_weight = weight
+ weight = weight.narrow(offset[0], offset[1], offset[2])
+
+ if strength_model != 1.0:
+ weight *= strength_model
+
+ if isinstance(v, list):
+ v = (calculate_weight(v[1:], comfy.model_management.cast_to_device(v[0], weight.device, intermediate_dtype, copy=True), key, intermediate_dtype=intermediate_dtype), )
+
+ if len(v) == 1:
+ patch_type = "diff"
+ elif len(v) == 2:
+ patch_type = v[0]
+ v = v[1]
+
+ if patch_type == "diff":
+ diff: torch.Tensor = v[0]
+ # An extra flag to pad the weight if the diff's shape is larger than the weight
+ do_pad_weight = len(v) > 1 and v[1]['pad_weight']
+ if do_pad_weight and diff.shape != weight.shape:
+ logging.info("Pad weight {} from {} to shape: {}".format(key, weight.shape, diff.shape))
+ weight = pad_tensor_to_shape(weight, diff.shape)
+
+ if strength != 0.0:
+ if diff.shape != weight.shape:
+ logging.warning("WARNING SHAPE MISMATCH {} WEIGHT NOT MERGED {} != {}".format(key, diff.shape, weight.shape))
+ else:
+ weight += function(strength * comfy.model_management.cast_to_device(diff, weight.device, weight.dtype))
+ elif patch_type == "lora": #lora/locon
+ mat1 = comfy.model_management.cast_to_device(v[0], weight.device, intermediate_dtype)
+ mat2 = comfy.model_management.cast_to_device(v[1], weight.device, intermediate_dtype)
+ dora_scale = v[4]
+ if v[2] is not None:
+ alpha = v[2] / mat2.shape[0]
+ else:
+ alpha = 1.0
+
+ if v[3] is not None:
+ #locon mid weights, hopefully the math is fine because I didn't properly test it
+ mat3 = comfy.model_management.cast_to_device(v[3], weight.device, intermediate_dtype)
+ final_shape = [mat2.shape[1], mat2.shape[0], mat3.shape[2], mat3.shape[3]]
+ mat2 = torch.mm(mat2.transpose(0, 1).flatten(start_dim=1), mat3.transpose(0, 1).flatten(start_dim=1)).reshape(final_shape).transpose(0, 1)
+ try:
+ lora_diff = torch.mm(mat1.flatten(start_dim=1), mat2.flatten(start_dim=1)).reshape(weight.shape)
+ if dora_scale is not None:
+ weight = function(weight_decompose(dora_scale, weight, lora_diff, alpha, strength, intermediate_dtype))
+ else:
+ weight += function(((strength * alpha) * lora_diff).type(weight.dtype))
+ except Exception as e:
+ logging.error("ERROR {} {} {}".format(patch_type, key, e))
+ elif patch_type == "lokr":
+ w1 = v[0]
+ w2 = v[1]
+ w1_a = v[3]
+ w1_b = v[4]
+ w2_a = v[5]
+ w2_b = v[6]
+ t2 = v[7]
+ dora_scale = v[8]
+ dim = None
+
+ if w1 is None:
+ dim = w1_b.shape[0]
+ w1 = torch.mm(comfy.model_management.cast_to_device(w1_a, weight.device, intermediate_dtype),
+ comfy.model_management.cast_to_device(w1_b, weight.device, intermediate_dtype))
+ else:
+ w1 = comfy.model_management.cast_to_device(w1, weight.device, intermediate_dtype)
+
+ if w2 is None:
+ dim = w2_b.shape[0]
+ if t2 is None:
+ w2 = torch.mm(comfy.model_management.cast_to_device(w2_a, weight.device, intermediate_dtype),
+ comfy.model_management.cast_to_device(w2_b, weight.device, intermediate_dtype))
+ else:
+ w2 = torch.einsum('i j k l, j r, i p -> p r k l',
+ comfy.model_management.cast_to_device(t2, weight.device, intermediate_dtype),
+ comfy.model_management.cast_to_device(w2_b, weight.device, intermediate_dtype),
+ comfy.model_management.cast_to_device(w2_a, weight.device, intermediate_dtype))
+ else:
+ w2 = comfy.model_management.cast_to_device(w2, weight.device, intermediate_dtype)
+
+ if len(w2.shape) == 4:
+ w1 = w1.unsqueeze(2).unsqueeze(2)
+ if v[2] is not None and dim is not None:
+ alpha = v[2] / dim
+ else:
+ alpha = 1.0
+
+ try:
+ lora_diff = torch.kron(w1, w2).reshape(weight.shape)
+ if dora_scale is not None:
+ weight = function(weight_decompose(dora_scale, weight, lora_diff, alpha, strength, intermediate_dtype))
+ else:
+ weight += function(((strength * alpha) * lora_diff).type(weight.dtype))
+ except Exception as e:
+ logging.error("ERROR {} {} {}".format(patch_type, key, e))
+ elif patch_type == "loha":
+ w1a = v[0]
+ w1b = v[1]
+ if v[2] is not None:
+ alpha = v[2] / w1b.shape[0]
+ else:
+ alpha = 1.0
+
+ w2a = v[3]
+ w2b = v[4]
+ dora_scale = v[7]
+ if v[5] is not None: #cp decomposition
+ t1 = v[5]
+ t2 = v[6]
+ m1 = torch.einsum('i j k l, j r, i p -> p r k l',
+ comfy.model_management.cast_to_device(t1, weight.device, intermediate_dtype),
+ comfy.model_management.cast_to_device(w1b, weight.device, intermediate_dtype),
+ comfy.model_management.cast_to_device(w1a, weight.device, intermediate_dtype))
+
+ m2 = torch.einsum('i j k l, j r, i p -> p r k l',
+ comfy.model_management.cast_to_device(t2, weight.device, intermediate_dtype),
+ comfy.model_management.cast_to_device(w2b, weight.device, intermediate_dtype),
+ comfy.model_management.cast_to_device(w2a, weight.device, intermediate_dtype))
+ else:
+ m1 = torch.mm(comfy.model_management.cast_to_device(w1a, weight.device, intermediate_dtype),
+ comfy.model_management.cast_to_device(w1b, weight.device, intermediate_dtype))
+ m2 = torch.mm(comfy.model_management.cast_to_device(w2a, weight.device, intermediate_dtype),
+ comfy.model_management.cast_to_device(w2b, weight.device, intermediate_dtype))
+
+ try:
+ lora_diff = (m1 * m2).reshape(weight.shape)
+ if dora_scale is not None:
+ weight = function(weight_decompose(dora_scale, weight, lora_diff, alpha, strength, intermediate_dtype))
+ else:
+ weight += function(((strength * alpha) * lora_diff).type(weight.dtype))
+ except Exception as e:
+ logging.error("ERROR {} {} {}".format(patch_type, key, e))
+ elif patch_type == "glora":
+ dora_scale = v[5]
+
+ old_glora = False
+ if v[3].shape[1] == v[2].shape[0] == v[0].shape[0] == v[1].shape[1]:
+ rank = v[0].shape[0]
+ old_glora = True
+
+ if v[3].shape[0] == v[2].shape[1] == v[0].shape[1] == v[1].shape[0]:
+ if old_glora and v[1].shape[0] == weight.shape[0] and weight.shape[0] == weight.shape[1]:
+ pass
+ else:
+ old_glora = False
+ rank = v[1].shape[0]
+
+ a1 = comfy.model_management.cast_to_device(v[0].flatten(start_dim=1), weight.device, intermediate_dtype)
+ a2 = comfy.model_management.cast_to_device(v[1].flatten(start_dim=1), weight.device, intermediate_dtype)
+ b1 = comfy.model_management.cast_to_device(v[2].flatten(start_dim=1), weight.device, intermediate_dtype)
+ b2 = comfy.model_management.cast_to_device(v[3].flatten(start_dim=1), weight.device, intermediate_dtype)
+
+ if v[4] is not None:
+ alpha = v[4] / rank
+ else:
+ alpha = 1.0
+
+ try:
+ if old_glora:
+ lora_diff = (torch.mm(b2, b1) + torch.mm(torch.mm(weight.flatten(start_dim=1).to(dtype=intermediate_dtype), a2), a1)).reshape(weight.shape) #old lycoris glora
+ else:
+ if weight.dim() > 2:
+ lora_diff = torch.einsum("o i ..., i j -> o j ...", torch.einsum("o i ..., i j -> o j ...", weight.to(dtype=intermediate_dtype), a1), a2).reshape(weight.shape)
+ else:
+ lora_diff = torch.mm(torch.mm(weight.to(dtype=intermediate_dtype), a1), a2).reshape(weight.shape)
+ lora_diff += torch.mm(b1, b2).reshape(weight.shape)
+
+ if dora_scale is not None:
+ weight = function(weight_decompose(dora_scale, weight, lora_diff, alpha, strength, intermediate_dtype))
+ else:
+ weight += function(((strength * alpha) * lora_diff).type(weight.dtype))
+ except Exception as e:
+ logging.error("ERROR {} {} {}".format(patch_type, key, e))
+ else:
+ logging.warning("patch type not recognized {} {}".format(patch_type, key))
+
+ if old_weight is not None:
+ weight = old_weight
+
+ return weight
diff --git a/comfy/model_base.py b/comfy/model_base.py
index 830bcc68c..9bfdb3b3e 100644
--- a/comfy/model_base.py
+++ b/comfy/model_base.py
@@ -96,10 +96,7 @@ class BaseModel(torch.nn.Module):
if not unet_config.get("disable_unet_model_creation", False):
if model_config.custom_operations is None:
- if self.manual_cast_dtype is not None:
- operations = comfy.ops.manual_cast
- else:
- operations = comfy.ops.disable_weight_init
+ operations = comfy.ops.pick_operations(unet_config.get("dtype", None), self.manual_cast_dtype)
else:
operations = model_config.custom_operations
self.diffusion_model = unet_model(**unet_config, device=device, operations=operations)
diff --git a/comfy/model_detection.py b/comfy/model_detection.py
index c05975cc9..1edbcda4d 100644
--- a/comfy/model_detection.py
+++ b/comfy/model_detection.py
@@ -472,9 +472,15 @@ def unet_config_from_diffusers_unet(state_dict, dtype=None):
'transformer_depth': [0, 1, 1], 'channel_mult': [1, 2, 4], 'transformer_depth_middle': -2, 'use_linear_in_transformer': False,
'context_dim': 768, 'num_head_channels': 64, 'transformer_depth_output': [0, 0, 1, 1, 1, 1],
'use_temporal_attention': False, 'use_temporal_resblock': False}
+
+ SD15_diffusers_inpaint = {'use_checkpoint': False, 'image_size': 32, 'out_channels': 4, 'use_spatial_transformer': True, 'legacy': False, 'adm_in_channels': None,
+ 'dtype': dtype, 'in_channels': 9, 'model_channels': 320, 'num_res_blocks': [2, 2, 2, 2], 'transformer_depth': [1, 1, 1, 1, 1, 1, 0, 0],
+ 'channel_mult': [1, 2, 4, 4], 'transformer_depth_middle': 1, 'use_linear_in_transformer': False, 'context_dim': 768, 'num_heads': 8,
+ 'transformer_depth_output': [1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0],
+ 'use_temporal_attention': False, 'use_temporal_resblock': False}
- supported_models = [SDXL, SDXL_refiner, SD21, SD15, SD21_uncliph, SD21_unclipl, SDXL_mid_cnet, SDXL_small_cnet, SDXL_diffusers_inpaint, SSD_1B, Segmind_Vega, KOALA_700M, KOALA_1B, SD09_XS, SD_XS, SDXL_diffusers_ip2p]
+ supported_models = [SDXL, SDXL_refiner, SD21, SD15, SD21_uncliph, SD21_unclipl, SDXL_mid_cnet, SDXL_small_cnet, SDXL_diffusers_inpaint, SSD_1B, Segmind_Vega, KOALA_700M, KOALA_1B, SD09_XS, SD_XS, SDXL_diffusers_ip2p, SD15_diffusers_inpaint]
for unet_config in supported_models:
matches = True
diff --git a/comfy/model_management.py b/comfy/model_management.py
index a6996709b..a97d489d5 100644
--- a/comfy/model_management.py
+++ b/comfy/model_management.py
@@ -44,9 +44,15 @@ cpu_state = CPUState.GPU
total_vram = 0
-lowvram_available = True
xpu_available = False
+torch_version = ""
+try:
+ torch_version = torch.version.__version__
+ xpu_available = (int(torch_version[0]) < 2 or (int(torch_version[0]) == 2 and int(torch_version[2]) <= 4)) and torch.xpu.is_available()
+except:
+ pass
+lowvram_available = True
if args.deterministic:
logging.info("Using deterministic algorithms for pytorch")
torch.use_deterministic_algorithms(True, warn_only=True)
@@ -66,10 +72,10 @@ if args.directml is not None:
try:
import intel_extension_for_pytorch as ipex
- if torch.xpu.is_available():
- xpu_available = True
+ _ = torch.xpu.device_count()
+ xpu_available = torch.xpu.is_available()
except:
- pass
+ xpu_available = xpu_available or (hasattr(torch, "xpu") and torch.xpu.is_available())
try:
if torch.backends.mps.is_available():
@@ -189,7 +195,6 @@ VAE_DTYPES = [torch.float32]
try:
if is_nvidia():
- torch_version = torch.version.__version__
if int(torch_version[0]) >= 2:
if ENABLE_PYTORCH_ATTENTION == False and args.use_split_cross_attention == False and args.use_quad_cross_attention == False:
ENABLE_PYTORCH_ATTENTION = True
@@ -315,17 +320,15 @@ class LoadedModel:
self.model_use_more_vram(use_more_vram)
else:
try:
- if lowvram_model_memory > 0 and load_weights:
- self.real_model = self.model.patch_model_lowvram(device_to=patch_model_to, lowvram_model_memory=lowvram_model_memory, force_patch_weights=force_patch_weights)
- else:
- self.real_model = self.model.patch_model(device_to=patch_model_to, patch_weights=load_weights)
+ self.real_model = self.model.patch_model(device_to=patch_model_to, lowvram_model_memory=lowvram_model_memory, load_weights=load_weights, force_patch_weights=force_patch_weights)
except Exception as e:
self.model.unpatch_model(self.model.offload_device)
self.model_unload()
raise e
- if is_intel_xpu() and not args.disable_ipex_optimize:
- self.real_model = ipex.optimize(self.real_model.eval(), graph_mode=True, concat_linear=True)
+ if is_intel_xpu() and not args.disable_ipex_optimize and 'ipex' in globals() and self.real_model is not None:
+ with torch.no_grad():
+ self.real_model = ipex.optimize(self.real_model.eval(), inplace=True, graph_mode=True, concat_linear=True)
self.weights_loaded = True
return self.real_model
@@ -367,8 +370,21 @@ def offloaded_memory(loaded_models, device):
offloaded_mem += m.model_offloaded_memory()
return offloaded_mem
+WINDOWS = any(platform.win32_ver())
+
+EXTRA_RESERVED_VRAM = 400 * 1024 * 1024
+if WINDOWS:
+ EXTRA_RESERVED_VRAM = 600 * 1024 * 1024 #Windows is higher because of the shared vram issue
+
+if args.reserve_vram is not None:
+ EXTRA_RESERVED_VRAM = args.reserve_vram * 1024 * 1024 * 1024
+ logging.debug("Reserving {}MB vram for other applications.".format(EXTRA_RESERVED_VRAM / (1024 * 1024)))
+
+def extra_reserved_memory():
+ return EXTRA_RESERVED_VRAM
+
def minimum_inference_memory():
- return (1024 * 1024 * 1024) * 1.2
+ return (1024 * 1024 * 1024) * 0.8 + extra_reserved_memory()
def unload_model_clones(model, unload_weights_only=True, force_unload=True):
to_unload = []
@@ -392,6 +408,8 @@ def unload_model_clones(model, unload_weights_only=True, force_unload=True):
if not force_unload:
if unload_weights_only and unload_weight == False:
return None
+ else:
+ unload_weight = True
for i in to_unload:
logging.debug("unload clone {} {}".format(i, unload_weight))
@@ -408,7 +426,7 @@ def free_memory(memory_required, device, keep_loaded=[]):
shift_model = current_loaded_models[i]
if shift_model.device == device:
if shift_model not in keep_loaded:
- can_unload.append((sys.getrefcount(shift_model.model), shift_model.model_memory(), i))
+ can_unload.append((-shift_model.model_offloaded_memory(), sys.getrefcount(shift_model.model), shift_model.model_memory(), i))
shift_model.currently_used = False
for x in sorted(can_unload):
@@ -439,11 +457,11 @@ def load_models_gpu(models, memory_required=0, force_patch_weights=False, minimu
global vram_state
inference_memory = minimum_inference_memory()
- extra_mem = max(inference_memory, memory_required + 300 * 1024 * 1024)
+ extra_mem = max(inference_memory, memory_required + extra_reserved_memory())
if minimum_memory_required is None:
minimum_memory_required = extra_mem
else:
- minimum_memory_required = max(inference_memory, minimum_memory_required + 300 * 1024 * 1024)
+ minimum_memory_required = max(inference_memory, minimum_memory_required + extra_reserved_memory())
models = set(models)
@@ -553,7 +571,9 @@ def loaded_models(only_currently_used=False):
def cleanup_models(keep_clone_weights_loaded=False):
to_delete = []
for i in range(len(current_loaded_models)):
- if sys.getrefcount(current_loaded_models[i].model) <= 2:
+ #TODO: very fragile function needs improvement
+ num_refs = sys.getrefcount(current_loaded_models[i].model)
+ if num_refs <= 2:
if not keep_clone_weights_loaded:
to_delete = [i] + to_delete
#TODO: find a less fragile way to do this.
@@ -606,6 +626,8 @@ def maximum_vram_for_weights(device=None):
return (get_total_memory(device) * 0.88 - minimum_inference_memory())
def unet_dtype(device=None, model_params=0, supported_dtypes=[torch.float16, torch.bfloat16, torch.float32]):
+ if model_params < 0:
+ model_params = 1000000000000000000000
if args.bf16_unet:
return torch.bfloat16
if args.fp16_unet:
@@ -660,6 +682,7 @@ def unet_manual_cast(weight_dtype, inference_device, supported_dtypes=[torch.flo
if bf16_supported and weight_dtype == torch.bfloat16:
return None
+ fp16_supported = should_use_fp16(inference_device, prioritize_performance=True)
for dt in supported_dtypes:
if dt == torch.float16 and fp16_supported:
return torch.float16
@@ -875,7 +898,8 @@ def pytorch_attention_flash_attention():
def force_upcast_attention_dtype():
upcast = args.force_upcast_attention
try:
- if platform.mac_ver()[0] in ['14.5']: #black image bug on OSX Sonoma 14.5
+ macos_version = tuple(int(n) for n in platform.mac_ver()[0].split("."))
+ if (14, 5) <= macos_version < (14, 7): # black image bug on recent versions of MacOS
upcast = True
except:
pass
@@ -971,23 +995,23 @@ def should_use_fp16(device=None, model_params=0, prioritize_performance=True, ma
if torch.version.hip:
return True
- props = torch.cuda.get_device_properties("cuda")
+ props = torch.cuda.get_device_properties(device)
if props.major >= 8:
return True
if props.major < 6:
return False
- fp16_works = False
- #FP16 is confirmed working on a 1080 (GP104) but it's a bit slower than FP32 so it should only be enabled
- #when the model doesn't actually fit on the card
- #TODO: actually test if GP106 and others have the same type of behavior
+ #FP16 is confirmed working on a 1080 (GP104) and on latest pytorch actually seems faster than fp32
nvidia_10_series = ["1080", "1070", "titan x", "p3000", "p3200", "p4000", "p4200", "p5000", "p5200", "p6000", "1060", "1050", "p40", "p100", "p6", "p4"]
for x in nvidia_10_series:
if x in props.name.lower():
- fp16_works = True
+ if WINDOWS or manual_cast:
+ return True
+ else:
+ return False #weird linux behavior where fp32 is faster
- if fp16_works or manual_cast:
+ if manual_cast:
free_model_memory = maximum_vram_for_weights(device)
if (not prioritize_performance) or model_params * 4 > free_model_memory:
return True
@@ -1027,7 +1051,7 @@ def should_use_bf16(device=None, model_params=0, prioritize_performance=True, ma
if is_intel_xpu():
return True
- props = torch.cuda.get_device_properties("cuda")
+ props = torch.cuda.get_device_properties(device)
if props.major >= 8:
return True
@@ -1040,6 +1064,16 @@ def should_use_bf16(device=None, model_params=0, prioritize_performance=True, ma
return False
+def supports_fp8_compute(device=None):
+ props = torch.cuda.get_device_properties(device)
+ if props.major >= 9:
+ return True
+ if props.major < 8:
+ return False
+ if props.minor < 9:
+ return False
+ return True
+
def soft_empty_cache(force=False):
global cpu_state
if cpu_state == CPUState.MPS:
diff --git a/comfy/model_patcher.py b/comfy/model_patcher.py
index 1edbf24ab..6ca124e6d 100644
--- a/comfy/model_patcher.py
+++ b/comfy/model_patcher.py
@@ -22,32 +22,26 @@ import inspect
import logging
import uuid
import collections
+import math
import comfy.utils
+import comfy.float
import comfy.model_management
-from comfy.types import UnetWrapperFunction
-
-
-def weight_decompose(dora_scale, weight, lora_diff, alpha, strength):
- dora_scale = comfy.model_management.cast_to_device(dora_scale, weight.device, torch.float32)
- lora_diff *= alpha
- weight_calc = weight + lora_diff.type(weight.dtype)
- weight_norm = (
- weight_calc.transpose(0, 1)
- .reshape(weight_calc.shape[1], -1)
- .norm(dim=1, keepdim=True)
- .reshape(weight_calc.shape[1], *[1] * (weight_calc.dim() - 1))
- .transpose(0, 1)
- )
-
- weight_calc *= (dora_scale / weight_norm).type(weight.dtype)
- if strength != 1.0:
- weight_calc -= weight
- weight += strength * (weight_calc)
- else:
- weight[:] = weight_calc
- return weight
+import comfy.lora
+from comfy.comfy_types import UnetWrapperFunction
+def string_to_seed(data):
+ crc = 0xFFFFFFFF
+ for byte in data:
+ if isinstance(byte, str):
+ byte = ord(byte)
+ crc ^= byte
+ for _ in range(8):
+ if crc & 1:
+ crc = (crc >> 1) ^ 0xEDB88320
+ else:
+ crc >>= 1
+ return crc ^ 0xFFFFFFFF
def set_model_options_patch_replace(model_options, patch, name, block_name, number, transformer_index=None):
to = model_options["transformer_options"].copy()
@@ -90,12 +84,11 @@ def wipe_lowvram_weight(m):
m.bias_function = None
class LowVramPatch:
- def __init__(self, key, model_patcher):
+ def __init__(self, key, patches):
self.key = key
- self.model_patcher = model_patcher
+ self.patches = patches
def __call__(self, weight):
- return self.model_patcher.calculate_weight(self.model_patcher.patches[self.key], weight, self.key)
-
+ return comfy.lora.calculate_weight(self.patches[self.key], weight, self.key, intermediate_dtype=weight.dtype)
class ModelPatcher:
def __init__(self, model, load_device, offload_device, size=0, weight_inplace_update=False):
@@ -290,17 +283,21 @@ class ModelPatcher:
return list(p)
def get_key_patches(self, filter_prefix=None):
- comfy.model_management.unload_model_clones(self)
model_sd = self.model_state_dict()
p = {}
for k in model_sd:
if filter_prefix is not None:
if not k.startswith(filter_prefix):
continue
- if k in self.patches:
- p[k] = [model_sd[k]] + self.patches[k]
+ bk = self.backup.get(k, None)
+ if bk is not None:
+ weight = bk.weight
else:
- p[k] = (model_sd[k],)
+ weight = model_sd[k]
+ if k in self.patches:
+ p[k] = [weight] + self.patches[k]
+ else:
+ p[k] = (weight,)
return p
def model_state_dict(self, filter_prefix=None):
@@ -327,47 +324,36 @@ class ModelPatcher:
temp_weight = comfy.model_management.cast_to_device(weight, device_to, torch.float32, copy=True)
else:
temp_weight = weight.to(torch.float32, copy=True)
- out_weight = self.calculate_weight(self.patches[key], temp_weight, key).to(weight.dtype)
+ out_weight = comfy.lora.calculate_weight(self.patches[key], temp_weight, key)
+ out_weight = comfy.float.stochastic_rounding(out_weight, weight.dtype, seed=string_to_seed(key))
if inplace_update:
comfy.utils.copy_to_param(self.model, key, out_weight)
else:
comfy.utils.set_attr_param(self.model, key, out_weight)
- def patch_model(self, device_to=None, patch_weights=True):
- for k in self.object_patches:
- old = comfy.utils.set_attr(self.model, k, self.object_patches[k])
- if k not in self.object_patches_backup:
- self.object_patches_backup[k] = old
-
- if patch_weights:
- model_sd = self.model_state_dict()
- for key in self.patches:
- if key not in model_sd:
- logging.warning("could not patch. key doesn't exist in model: {}".format(key))
- continue
-
- self.patch_weight_to_device(key, device_to)
-
- if device_to is not None:
- self.model.to(device_to)
- self.model.device = device_to
- self.model.model_loaded_weight_memory = self.model_size()
-
- return self.model
-
- def lowvram_load(self, device_to=None, lowvram_model_memory=0, force_patch_weights=False, full_load=False):
+ def load(self, device_to=None, lowvram_model_memory=0, force_patch_weights=False, full_load=False):
mem_counter = 0
patch_counter = 0
lowvram_counter = 0
+ loading = []
for n, m in self.model.named_modules():
+ if hasattr(m, "comfy_cast_weights") or hasattr(m, "weight"):
+ loading.append((comfy.model_management.module_size(m), n, m))
+
+ load_completely = []
+ loading.sort(reverse=True)
+ for x in loading:
+ n = x[1]
+ m = x[2]
+ module_mem = x[0]
+
lowvram_weight = False
if not full_load and hasattr(m, "comfy_cast_weights"):
- module_mem = comfy.model_management.module_size(m)
if mem_counter + module_mem >= lowvram_model_memory:
lowvram_weight = True
lowvram_counter += 1
- if m.comfy_cast_weights:
+ if hasattr(m, "prev_comfy_cast_weights"): #Already lowvramed
continue
weight_key = "{}.weight".format(n)
@@ -378,13 +364,13 @@ class ModelPatcher:
if force_patch_weights:
self.patch_weight_to_device(weight_key)
else:
- m.weight_function = LowVramPatch(weight_key, self)
+ m.weight_function = LowVramPatch(weight_key, self.patches)
patch_counter += 1
if bias_key in self.patches:
if force_patch_weights:
self.patch_weight_to_device(bias_key)
else:
- m.bias_function = LowVramPatch(bias_key, self)
+ m.bias_function = LowVramPatch(bias_key, self.patches)
patch_counter += 1
m.prev_comfy_cast_weights = m.comfy_cast_weights
@@ -395,205 +381,56 @@ class ModelPatcher:
wipe_lowvram_weight(m)
if hasattr(m, "weight"):
- mem_counter += comfy.model_management.module_size(m)
- param = list(m.parameters())
- if len(param) > 0:
- weight = param[0]
- if weight.device == device_to:
- continue
+ mem_counter += module_mem
+ load_completely.append((module_mem, n, m))
- weight_to = None
- if full_load:#TODO
- weight_to = device_to
- self.patch_weight_to_device(weight_key, device_to=weight_to) #TODO: speed this up without OOM
- self.patch_weight_to_device(bias_key, device_to=weight_to)
- m.to(device_to)
- logging.debug("lowvram: loaded module regularly {} {}".format(n, m))
+ load_completely.sort(reverse=True)
+ for x in load_completely:
+ n = x[1]
+ m = x[2]
+ weight_key = "{}.weight".format(n)
+ bias_key = "{}.bias".format(n)
+ if hasattr(m, "comfy_patched_weights"):
+ if m.comfy_patched_weights == True:
+ continue
+
+ self.patch_weight_to_device(weight_key, device_to=device_to)
+ self.patch_weight_to_device(bias_key, device_to=device_to)
+ logging.debug("lowvram: loaded module regularly {} {}".format(n, m))
+ m.comfy_patched_weights = True
+
+ for x in load_completely:
+ x[2].to(device_to)
if lowvram_counter > 0:
logging.info("loaded partially {} {} {}".format(lowvram_model_memory / (1024 * 1024), mem_counter / (1024 * 1024), patch_counter))
self.model.model_lowvram = True
else:
- logging.info("loaded completely {} {}".format(lowvram_model_memory / (1024 * 1024), mem_counter / (1024 * 1024)))
+ logging.info("loaded completely {} {} {}".format(lowvram_model_memory / (1024 * 1024), mem_counter / (1024 * 1024), full_load))
self.model.model_lowvram = False
+ if full_load:
+ self.model.to(device_to)
+ mem_counter = self.model_size()
+
self.model.lowvram_patch_counter += patch_counter
self.model.device = device_to
self.model.model_loaded_weight_memory = mem_counter
+ def patch_model(self, device_to=None, lowvram_model_memory=0, load_weights=True, force_patch_weights=False):
+ for k in self.object_patches:
+ old = comfy.utils.set_attr(self.model, k, self.object_patches[k])
+ if k not in self.object_patches_backup:
+ self.object_patches_backup[k] = old
- def patch_model_lowvram(self, device_to=None, lowvram_model_memory=0, force_patch_weights=False):
- self.patch_model(device_to, patch_weights=False)
- self.lowvram_load(device_to, lowvram_model_memory=lowvram_model_memory, force_patch_weights=force_patch_weights)
+ if lowvram_model_memory == 0:
+ full_load = True
+ else:
+ full_load = False
+
+ if load_weights:
+ self.load(device_to, lowvram_model_memory=lowvram_model_memory, force_patch_weights=force_patch_weights, full_load=full_load)
return self.model
- def calculate_weight(self, patches, weight, key):
- for p in patches:
- strength = p[0]
- v = p[1]
- strength_model = p[2]
- offset = p[3]
- function = p[4]
- if function is None:
- function = lambda a: a
-
- old_weight = None
- if offset is not None:
- old_weight = weight
- weight = weight.narrow(offset[0], offset[1], offset[2])
-
- if strength_model != 1.0:
- weight *= strength_model
-
- if isinstance(v, list):
- v = (self.calculate_weight(v[1:], v[0].clone(), key), )
-
- if len(v) == 1:
- patch_type = "diff"
- elif len(v) == 2:
- patch_type = v[0]
- v = v[1]
-
- if patch_type == "diff":
- w1 = v[0]
- if strength != 0.0:
- if w1.shape != weight.shape:
- logging.warning("WARNING SHAPE MISMATCH {} WEIGHT NOT MERGED {} != {}".format(key, w1.shape, weight.shape))
- else:
- weight += function(strength * comfy.model_management.cast_to_device(w1, weight.device, weight.dtype))
- elif patch_type == "lora": #lora/locon
- mat1 = comfy.model_management.cast_to_device(v[0], weight.device, torch.float32)
- mat2 = comfy.model_management.cast_to_device(v[1], weight.device, torch.float32)
- dora_scale = v[4]
- if v[2] is not None:
- alpha = v[2] / mat2.shape[0]
- else:
- alpha = 1.0
-
- if v[3] is not None:
- #locon mid weights, hopefully the math is fine because I didn't properly test it
- mat3 = comfy.model_management.cast_to_device(v[3], weight.device, torch.float32)
- final_shape = [mat2.shape[1], mat2.shape[0], mat3.shape[2], mat3.shape[3]]
- mat2 = torch.mm(mat2.transpose(0, 1).flatten(start_dim=1), mat3.transpose(0, 1).flatten(start_dim=1)).reshape(final_shape).transpose(0, 1)
- try:
- lora_diff = torch.mm(mat1.flatten(start_dim=1), mat2.flatten(start_dim=1)).reshape(weight.shape)
- if dora_scale is not None:
- weight = function(weight_decompose(dora_scale, weight, lora_diff, alpha, strength))
- else:
- weight += function(((strength * alpha) * lora_diff).type(weight.dtype))
- except Exception as e:
- logging.error("ERROR {} {} {}".format(patch_type, key, e))
- elif patch_type == "lokr":
- w1 = v[0]
- w2 = v[1]
- w1_a = v[3]
- w1_b = v[4]
- w2_a = v[5]
- w2_b = v[6]
- t2 = v[7]
- dora_scale = v[8]
- dim = None
-
- if w1 is None:
- dim = w1_b.shape[0]
- w1 = torch.mm(comfy.model_management.cast_to_device(w1_a, weight.device, torch.float32),
- comfy.model_management.cast_to_device(w1_b, weight.device, torch.float32))
- else:
- w1 = comfy.model_management.cast_to_device(w1, weight.device, torch.float32)
-
- if w2 is None:
- dim = w2_b.shape[0]
- if t2 is None:
- w2 = torch.mm(comfy.model_management.cast_to_device(w2_a, weight.device, torch.float32),
- comfy.model_management.cast_to_device(w2_b, weight.device, torch.float32))
- else:
- w2 = torch.einsum('i j k l, j r, i p -> p r k l',
- comfy.model_management.cast_to_device(t2, weight.device, torch.float32),
- comfy.model_management.cast_to_device(w2_b, weight.device, torch.float32),
- comfy.model_management.cast_to_device(w2_a, weight.device, torch.float32))
- else:
- w2 = comfy.model_management.cast_to_device(w2, weight.device, torch.float32)
-
- if len(w2.shape) == 4:
- w1 = w1.unsqueeze(2).unsqueeze(2)
- if v[2] is not None and dim is not None:
- alpha = v[2] / dim
- else:
- alpha = 1.0
-
- try:
- lora_diff = torch.kron(w1, w2).reshape(weight.shape)
- if dora_scale is not None:
- weight = function(weight_decompose(dora_scale, weight, lora_diff, alpha, strength))
- else:
- weight += function(((strength * alpha) * lora_diff).type(weight.dtype))
- except Exception as e:
- logging.error("ERROR {} {} {}".format(patch_type, key, e))
- elif patch_type == "loha":
- w1a = v[0]
- w1b = v[1]
- if v[2] is not None:
- alpha = v[2] / w1b.shape[0]
- else:
- alpha = 1.0
-
- w2a = v[3]
- w2b = v[4]
- dora_scale = v[7]
- if v[5] is not None: #cp decomposition
- t1 = v[5]
- t2 = v[6]
- m1 = torch.einsum('i j k l, j r, i p -> p r k l',
- comfy.model_management.cast_to_device(t1, weight.device, torch.float32),
- comfy.model_management.cast_to_device(w1b, weight.device, torch.float32),
- comfy.model_management.cast_to_device(w1a, weight.device, torch.float32))
-
- m2 = torch.einsum('i j k l, j r, i p -> p r k l',
- comfy.model_management.cast_to_device(t2, weight.device, torch.float32),
- comfy.model_management.cast_to_device(w2b, weight.device, torch.float32),
- comfy.model_management.cast_to_device(w2a, weight.device, torch.float32))
- else:
- m1 = torch.mm(comfy.model_management.cast_to_device(w1a, weight.device, torch.float32),
- comfy.model_management.cast_to_device(w1b, weight.device, torch.float32))
- m2 = torch.mm(comfy.model_management.cast_to_device(w2a, weight.device, torch.float32),
- comfy.model_management.cast_to_device(w2b, weight.device, torch.float32))
-
- try:
- lora_diff = (m1 * m2).reshape(weight.shape)
- if dora_scale is not None:
- weight = function(weight_decompose(dora_scale, weight, lora_diff, alpha, strength))
- else:
- weight += function(((strength * alpha) * lora_diff).type(weight.dtype))
- except Exception as e:
- logging.error("ERROR {} {} {}".format(patch_type, key, e))
- elif patch_type == "glora":
- if v[4] is not None:
- alpha = v[4] / v[0].shape[0]
- else:
- alpha = 1.0
-
- dora_scale = v[5]
-
- a1 = comfy.model_management.cast_to_device(v[0].flatten(start_dim=1), weight.device, torch.float32)
- a2 = comfy.model_management.cast_to_device(v[1].flatten(start_dim=1), weight.device, torch.float32)
- b1 = comfy.model_management.cast_to_device(v[2].flatten(start_dim=1), weight.device, torch.float32)
- b2 = comfy.model_management.cast_to_device(v[3].flatten(start_dim=1), weight.device, torch.float32)
-
- try:
- lora_diff = (torch.mm(b2, b1) + torch.mm(torch.mm(weight.flatten(start_dim=1), a2), a1)).reshape(weight.shape)
- if dora_scale is not None:
- weight = function(weight_decompose(dora_scale, weight, lora_diff, alpha, strength))
- else:
- weight += function(((strength * alpha) * lora_diff).type(weight.dtype))
- except Exception as e:
- logging.error("ERROR {} {} {}".format(patch_type, key, e))
- else:
- logging.warning("patch type not recognized {} {}".format(patch_type, key))
-
- if old_weight is not None:
- weight = old_weight
-
- return weight
-
def unpatch_model(self, device_to=None, unpatch_weights=True):
if unpatch_weights:
if self.model.model_lowvram:
@@ -619,6 +456,10 @@ class ModelPatcher:
self.model.device = device_to
self.model.model_loaded_weight_memory = 0
+ for m in self.model.modules():
+ if hasattr(m, "comfy_patched_weights"):
+ del m.comfy_patched_weights
+
keys = list(self.object_patches_backup.keys())
for k in keys:
comfy.utils.set_attr(self.model, k, self.object_patches_backup[k])
@@ -628,40 +469,47 @@ class ModelPatcher:
def partially_unload(self, device_to, memory_to_free=0):
memory_freed = 0
patch_counter = 0
+ unload_list = []
- for n, m in list(self.model.named_modules())[::-1]:
- if memory_to_free < memory_freed:
- break
-
+ for n, m in self.model.named_modules():
shift_lowvram = False
if hasattr(m, "comfy_cast_weights"):
module_mem = comfy.model_management.module_size(m)
- weight_key = "{}.weight".format(n)
- bias_key = "{}.bias".format(n)
+ unload_list.append((module_mem, n, m))
+ unload_list.sort()
+ for unload in unload_list:
+ if memory_to_free < memory_freed:
+ break
+ module_mem = unload[0]
+ n = unload[1]
+ m = unload[2]
+ weight_key = "{}.weight".format(n)
+ bias_key = "{}.bias".format(n)
- if m.weight is not None and m.weight.device != device_to:
- for key in [weight_key, bias_key]:
- bk = self.backup.get(key, None)
- if bk is not None:
- if bk.inplace_update:
- comfy.utils.copy_to_param(self.model, key, bk.weight)
- else:
- comfy.utils.set_attr_param(self.model, key, bk.weight)
- self.backup.pop(key)
+ if hasattr(m, "comfy_patched_weights") and m.comfy_patched_weights == True:
+ for key in [weight_key, bias_key]:
+ bk = self.backup.get(key, None)
+ if bk is not None:
+ if bk.inplace_update:
+ comfy.utils.copy_to_param(self.model, key, bk.weight)
+ else:
+ comfy.utils.set_attr_param(self.model, key, bk.weight)
+ self.backup.pop(key)
- m.to(device_to)
- if weight_key in self.patches:
- m.weight_function = LowVramPatch(weight_key, self)
- patch_counter += 1
- if bias_key in self.patches:
- m.bias_function = LowVramPatch(bias_key, self)
- patch_counter += 1
+ m.to(device_to)
+ if weight_key in self.patches:
+ m.weight_function = LowVramPatch(weight_key, self.patches)
+ patch_counter += 1
+ if bias_key in self.patches:
+ m.bias_function = LowVramPatch(bias_key, self.patches)
+ patch_counter += 1
- m.prev_comfy_cast_weights = m.comfy_cast_weights
- m.comfy_cast_weights = True
- memory_freed += module_mem
- logging.debug("freed {}".format(n))
+ m.prev_comfy_cast_weights = m.comfy_cast_weights
+ m.comfy_cast_weights = True
+ m.comfy_patched_weights = False
+ memory_freed += module_mem
+ logging.debug("freed {}".format(n))
self.model.model_lowvram = True
self.model.lowvram_patch_counter += patch_counter
@@ -670,15 +518,19 @@ class ModelPatcher:
def partially_load(self, device_to, extra_memory=0):
self.unpatch_model(unpatch_weights=False)
- self.patch_model(patch_weights=False)
+ self.patch_model(load_weights=False)
full_load = False
if self.model.model_lowvram == False:
return 0
if self.model.model_loaded_weight_memory + extra_memory > self.model_size():
full_load = True
current_used = self.model.model_loaded_weight_memory
- self.lowvram_load(device_to, lowvram_model_memory=current_used + extra_memory, full_load=full_load)
+ self.load(device_to, lowvram_model_memory=current_used + extra_memory, full_load=full_load)
return self.model.model_loaded_weight_memory - current_used
def current_loaded_device(self):
return self.model.device
+
+ def calculate_weight(self, patches, weight, key, intermediate_dtype=torch.float32):
+ print("WARNING the ModelPatcher.calculate_weight function is deprecated, please use: comfy.lora.calculate_weight instead")
+ return comfy.lora.calculate_weight(patches, weight, key, intermediate_dtype=intermediate_dtype)
diff --git a/comfy/ops.py b/comfy/ops.py
index 47e8d7a9d..f9411ba59 100644
--- a/comfy/ops.py
+++ b/comfy/ops.py
@@ -18,29 +18,42 @@
import torch
import comfy.model_management
+from comfy.cli_args import args
+def cast_to(weight, dtype=None, device=None, non_blocking=False, copy=False):
+ if device is None or weight.device == device:
+ if not copy:
+ if dtype is None or weight.dtype == dtype:
+ return weight
+ return weight.to(dtype=dtype, copy=copy)
-def cast_to(weight, dtype=None, device=None, non_blocking=False):
- return weight.to(device=device, dtype=dtype, non_blocking=non_blocking)
+ r = torch.empty_like(weight, dtype=dtype, device=device)
+ r.copy_(weight, non_blocking=non_blocking)
+ return r
-def cast_to_input(weight, input, non_blocking=False):
- return cast_to(weight, input.dtype, input.device, non_blocking=non_blocking)
+def cast_to_input(weight, input, non_blocking=False, copy=True):
+ return cast_to(weight, input.dtype, input.device, non_blocking=non_blocking, copy=copy)
-def cast_bias_weight(s, input=None, dtype=None, device=None):
+def cast_bias_weight(s, input=None, dtype=None, device=None, bias_dtype=None):
if input is not None:
if dtype is None:
dtype = input.dtype
+ if bias_dtype is None:
+ bias_dtype = dtype
if device is None:
device = input.device
bias = None
- non_blocking = comfy.model_management.device_should_use_non_blocking(device)
+ non_blocking = comfy.model_management.device_supports_non_blocking(device)
if s.bias is not None:
- bias = cast_to(s.bias, dtype, device, non_blocking=non_blocking)
- if s.bias_function is not None:
+ has_function = s.bias_function is not None
+ bias = cast_to(s.bias, bias_dtype, device, non_blocking=non_blocking, copy=has_function)
+ if has_function:
bias = s.bias_function(bias)
- weight = cast_to(s.weight, dtype, device, non_blocking=non_blocking)
- if s.weight_function is not None:
+
+ has_function = s.weight_function is not None
+ weight = cast_to(s.weight, dtype, device, non_blocking=non_blocking, copy=has_function)
+ if has_function:
weight = s.weight_function(weight)
return weight, bias
@@ -238,3 +251,58 @@ class manual_cast(disable_weight_init):
class Embedding(disable_weight_init.Embedding):
comfy_cast_weights = True
+
+
+def fp8_linear(self, input):
+ dtype = self.weight.dtype
+ if dtype not in [torch.float8_e4m3fn]:
+ return None
+
+ if len(input.shape) == 3:
+ inn = input.reshape(-1, input.shape[2]).to(dtype)
+ w, bias = cast_bias_weight(self, input, dtype=dtype, bias_dtype=input.dtype)
+ w = w.t()
+
+ scale_weight = self.scale_weight
+ scale_input = self.scale_input
+ if scale_weight is None:
+ scale_weight = torch.ones((1), device=input.device, dtype=torch.float32)
+ if scale_input is None:
+ scale_input = scale_weight
+ if scale_input is None:
+ scale_input = torch.ones((1), device=input.device, dtype=torch.float32)
+
+ if bias is not None:
+ o = torch._scaled_mm(inn, w, out_dtype=input.dtype, bias=bias, scale_a=scale_input, scale_b=scale_weight)
+ else:
+ o = torch._scaled_mm(inn, w, out_dtype=input.dtype, scale_a=scale_input, scale_b=scale_weight)
+
+ if isinstance(o, tuple):
+ o = o[0]
+
+ return o.reshape((-1, input.shape[1], self.weight.shape[0]))
+ return None
+
+class fp8_ops(manual_cast):
+ class Linear(manual_cast.Linear):
+ def reset_parameters(self):
+ self.scale_weight = None
+ self.scale_input = None
+ return None
+
+ def forward_comfy_cast_weights(self, input):
+ out = fp8_linear(self, input)
+ if out is not None:
+ return out
+
+ weight, bias = cast_bias_weight(self, input)
+ return torch.nn.functional.linear(input, weight, bias)
+
+
+def pick_operations(weight_dtype, compute_dtype, load_device=None, disable_fast_fp8=False):
+ if compute_dtype is None or weight_dtype == compute_dtype:
+ return disable_weight_init
+ if args.fast and not disable_fast_fp8:
+ if comfy.model_management.supports_fp8_compute(load_device):
+ return fp8_ops
+ return manual_cast
diff --git a/comfy/samplers.py b/comfy/samplers.py
index ce4371d50..1ecb41dda 100644
--- a/comfy/samplers.py
+++ b/comfy/samplers.py
@@ -6,7 +6,7 @@ from comfy import model_management
import math
import logging
import comfy.sampler_helpers
-import scipy
+import scipy.stats
import numpy
def get_area_and_mult(conds, x_in, timestep_in):
@@ -570,8 +570,8 @@ class Sampler:
return math.isclose(max_sigma, sigma, rel_tol=1e-05) or sigma > max_sigma
KSAMPLER_NAMES = ["euler", "euler_cfg_pp", "euler_ancestral", "euler_ancestral_cfg_pp", "heun", "heunpp2","dpm_2", "dpm_2_ancestral",
- "lms", "dpm_fast", "dpm_adaptive", "dpmpp_2s_ancestral", "dpmpp_sde", "dpmpp_sde_gpu",
- "dpmpp_2m", "dpmpp_2m_sde", "dpmpp_2m_sde_gpu", "dpmpp_3m_sde", "dpmpp_3m_sde_gpu", "ddpm", "lcm",
+ "lms", "dpm_fast", "dpm_adaptive", "dpmpp_2s_ancestral", "dpmpp_2s_ancestral_cfg_pp", "dpmpp_sde", "dpmpp_sde_gpu",
+ "dpmpp_2m", "dpmpp_2m_cfg_pp", "dpmpp_2m_sde", "dpmpp_2m_sde_gpu", "dpmpp_3m_sde", "dpmpp_3m_sde_gpu", "ddpm", "lcm",
"ipndm", "ipndm_v", "deis"]
class KSAMPLER(Sampler):
diff --git a/comfy/sd.py b/comfy/sd.py
index edd0b51d8..99859d241 100644
--- a/comfy/sd.py
+++ b/comfy/sd.py
@@ -24,6 +24,7 @@ import comfy.text_encoders.sa_t5
import comfy.text_encoders.aura_t5
import comfy.text_encoders.hydit
import comfy.text_encoders.flux
+import comfy.text_encoders.long_clipl
import comfy.model_patcher
import comfy.lora
@@ -62,18 +63,23 @@ def load_lora_for_models(model, clip, lora, strength_model, strength_clip):
class CLIP:
- def __init__(self, target=None, embedding_directory=None, no_init=False, tokenizer_data={}, parameters=0):
+ def __init__(self, target=None, embedding_directory=None, no_init=False, tokenizer_data={}, parameters=0, model_options={}):
if no_init:
return
params = target.params.copy()
clip = target.clip
tokenizer = target.tokenizer
- load_device = model_management.text_encoder_device()
- offload_device = model_management.text_encoder_offload_device()
- dtype = model_management.text_encoder_dtype(load_device)
+ load_device = model_options.get("load_device", model_management.text_encoder_device())
+ offload_device = model_options.get("offload_device", model_management.text_encoder_offload_device())
+ dtype = model_options.get("dtype", None)
+ if dtype is None:
+ dtype = model_management.text_encoder_dtype(load_device)
+
params['dtype'] = dtype
- params['device'] = model_management.text_encoder_initial_device(load_device, offload_device, parameters * model_management.dtype_size(dtype))
+ params['device'] = model_options.get("initial_device", model_management.text_encoder_initial_device(load_device, offload_device, parameters * model_management.dtype_size(dtype)))
+ params['model_options'] = model_options
+
self.cond_stage_model = clip(**(params))
for dt in self.cond_stage_model.dtypes:
@@ -394,11 +400,14 @@ class CLIPType(Enum):
HUNYUAN_DIT = 5
FLUX = 6
-def load_clip(ckpt_paths, embedding_directory=None, clip_type=CLIPType.STABLE_DIFFUSION):
+def load_clip(ckpt_paths, embedding_directory=None, clip_type=CLIPType.STABLE_DIFFUSION, model_options={}):
clip_data = []
for p in ckpt_paths:
clip_data.append(comfy.utils.load_torch_file(p, safe_load=True))
+ return load_text_encoder_state_dicts(clip_data, embedding_directory=embedding_directory, clip_type=clip_type, model_options=model_options)
+def load_text_encoder_state_dicts(state_dicts=[], embedding_directory=None, clip_type=CLIPType.STABLE_DIFFUSION, model_options={}):
+ clip_data = state_dicts
class EmptyClass:
pass
@@ -435,6 +444,7 @@ def load_clip(ckpt_paths, embedding_directory=None, clip_type=CLIPType.STABLE_DI
clip_target.clip = comfy.text_encoders.sa_t5.SAT5Model
clip_target.tokenizer = comfy.text_encoders.sa_t5.SAT5Tokenizer
else:
+ w = clip_data[0].get("text_model.embeddings.position_embedding.weight", None)
clip_target.clip = sd1_clip.SD1ClipModel
clip_target.tokenizer = sd1_clip.SD1Tokenizer
elif len(clip_data) == 2:
@@ -461,10 +471,12 @@ def load_clip(ckpt_paths, embedding_directory=None, clip_type=CLIPType.STABLE_DI
clip_target.tokenizer = comfy.text_encoders.sd3_clip.SD3Tokenizer
parameters = 0
+ tokenizer_data = {}
for c in clip_data:
parameters += comfy.utils.calculate_parameters(c)
+ tokenizer_data, model_options = comfy.text_encoders.long_clipl.model_options_long_clip(c, tokenizer_data, model_options)
- clip = CLIP(clip_target, embedding_directory=embedding_directory, parameters=parameters)
+ clip = CLIP(clip_target, embedding_directory=embedding_directory, parameters=parameters, tokenizer_data=tokenizer_data, model_options=model_options)
for c in clip_data:
m, u = clip.load_sd(c)
if len(m) > 0:
@@ -506,14 +518,14 @@ def load_checkpoint(config_path=None, ckpt_path=None, output_vae=True, output_cl
return (model, clip, vae)
-def load_checkpoint_guess_config(ckpt_path, output_vae=True, output_clip=True, output_clipvision=False, embedding_directory=None, output_model=True, model_options={}):
+def load_checkpoint_guess_config(ckpt_path, output_vae=True, output_clip=True, output_clipvision=False, embedding_directory=None, output_model=True, model_options={}, te_model_options={}):
sd = comfy.utils.load_torch_file(ckpt_path)
- out = load_state_dict_guess_config(sd, output_vae, output_clip, output_clipvision, embedding_directory, output_model, model_options)
+ out = load_state_dict_guess_config(sd, output_vae, output_clip, output_clipvision, embedding_directory, output_model, model_options, te_model_options=te_model_options)
if out is None:
raise RuntimeError("ERROR: Could not detect model type of: {}".format(ckpt_path))
return out
-def load_state_dict_guess_config(sd, output_vae=True, output_clip=True, output_clipvision=False, embedding_directory=None, output_model=True, model_options={}):
+def load_state_dict_guess_config(sd, output_vae=True, output_clip=True, output_clipvision=False, embedding_directory=None, output_model=True, model_options={}, te_model_options={}):
clip = None
clipvision = None
vae = None
@@ -563,7 +575,7 @@ def load_state_dict_guess_config(sd, output_vae=True, output_clip=True, output_c
clip_sd = model_config.process_clip_state_dict(sd)
if len(clip_sd) > 0:
parameters = comfy.utils.calculate_parameters(clip_sd)
- clip = CLIP(clip_target, embedding_directory=embedding_directory, tokenizer_data=clip_sd, parameters=parameters)
+ clip = CLIP(clip_target, embedding_directory=embedding_directory, tokenizer_data=clip_sd, parameters=parameters, model_options=te_model_options)
m, u = clip.load_sd(clip_sd, full_model=True)
if len(m) > 0:
m_filter = list(filter(lambda a: ".logit_scale" not in a and ".transformer.text_projection.weight" not in a, m))
@@ -633,7 +645,7 @@ def load_diffusion_model_state_dict(sd, model_options={}): #load unet in diffuse
manual_cast_dtype = model_management.unet_manual_cast(unet_dtype, load_device, model_config.supported_inference_dtypes)
model_config.set_inference_dtype(unet_dtype, manual_cast_dtype)
- model_config.custom_operations = model_options.get("custom_operations", None)
+ model_config.custom_operations = model_options.get("custom_operations", model_config.custom_operations)
model = model_config.get_model(new_sd, "")
model = model.to(offload_device)
model.load_model_weights(new_sd, "")
@@ -665,10 +677,13 @@ def save_checkpoint(output_path, model, clip=None, vae=None, clip_vision=None, m
if clip is not None:
load_models.append(clip.load_model())
clip_sd = clip.get_sd()
+ vae_sd = None
+ if vae is not None:
+ vae_sd = vae.get_sd()
model_management.load_models_gpu(load_models, force_patch_weights=True)
clip_vision_sd = clip_vision.get_sd() if clip_vision is not None else None
- sd = model.model.state_dict_for_saving(clip_sd, vae.get_sd(), clip_vision_sd)
+ sd = model.model.state_dict_for_saving(clip_sd, vae_sd, clip_vision_sd)
for k in extra_keys:
sd[k] = extra_keys[k]
diff --git a/comfy/sd1_clip.py b/comfy/sd1_clip.py
index e65cab285..9f0d95b0a 100644
--- a/comfy/sd1_clip.py
+++ b/comfy/sd1_clip.py
@@ -75,7 +75,6 @@ class ClipTokenWeightEncoder:
return r
class SDClipModel(torch.nn.Module, ClipTokenWeightEncoder):
- """Uses the CLIP transformer encoder for text (from huggingface)"""
LAYERS = [
"last",
"pooled",
@@ -84,7 +83,7 @@ class SDClipModel(torch.nn.Module, ClipTokenWeightEncoder):
def __init__(self, version="openai/clip-vit-large-patch14", device="cpu", max_length=77,
freeze=True, layer="last", layer_idx=None, textmodel_json_config=None, dtype=None, model_class=comfy.clip_model.CLIPTextModel,
special_tokens={"start": 49406, "end": 49407, "pad": 49407}, layer_norm_hidden_state=True, enable_attention_masks=False, zero_out_masked=False,
- return_projected_pooled=True, return_attention_masks=False): # clip-vit-base-patch32
+ return_projected_pooled=True, return_attention_masks=False, model_options={}): # clip-vit-base-patch32
super().__init__()
assert layer in self.LAYERS
@@ -94,7 +93,11 @@ class SDClipModel(torch.nn.Module, ClipTokenWeightEncoder):
with open(textmodel_json_config) as f:
config = json.load(f)
- self.operations = comfy.ops.manual_cast
+ operations = model_options.get("custom_operations", None)
+ if operations is None:
+ operations = comfy.ops.manual_cast
+
+ self.operations = operations
self.transformer = model_class(config, dtype, device, self.operations)
self.num_layers = self.transformer.num_layers
@@ -539,6 +542,7 @@ class SD1Tokenizer:
def __init__(self, embedding_directory=None, tokenizer_data={}, clip_name="l", tokenizer=SDTokenizer):
self.clip_name = clip_name
self.clip = "clip_{}".format(self.clip_name)
+ tokenizer = tokenizer_data.get("{}_tokenizer_class".format(self.clip), tokenizer)
setattr(self, self.clip, tokenizer(embedding_directory=embedding_directory, tokenizer_data=tokenizer_data))
def tokenize_with_weights(self, text:str, return_word_ids=False):
@@ -552,8 +556,12 @@ class SD1Tokenizer:
def state_dict(self):
return {}
+class SD1CheckpointClipModel(SDClipModel):
+ def __init__(self, device="cpu", dtype=None, model_options={}):
+ super().__init__(device=device, return_projected_pooled=False, dtype=dtype, model_options=model_options)
+
class SD1ClipModel(torch.nn.Module):
- def __init__(self, device="cpu", dtype=None, clip_name="l", clip_model=SDClipModel, name=None, **kwargs):
+ def __init__(self, device="cpu", dtype=None, model_options={}, clip_name="l", clip_model=SD1CheckpointClipModel, name=None, **kwargs):
super().__init__()
if name is not None:
@@ -563,7 +571,8 @@ class SD1ClipModel(torch.nn.Module):
self.clip_name = clip_name
self.clip = "clip_{}".format(self.clip_name)
- setattr(self, self.clip, clip_model(device=device, dtype=dtype, **kwargs))
+ clip_model = model_options.get("{}_class".format(self.clip), clip_model)
+ setattr(self, self.clip, clip_model(device=device, dtype=dtype, model_options=model_options, **kwargs))
self.dtypes = set()
if dtype is not None:
diff --git a/comfy/sdxl_clip.py b/comfy/sdxl_clip.py
index 6e6b87d62..4d0a4e8e7 100644
--- a/comfy/sdxl_clip.py
+++ b/comfy/sdxl_clip.py
@@ -3,14 +3,14 @@ import torch
import os
class SDXLClipG(sd1_clip.SDClipModel):
- def __init__(self, device="cpu", max_length=77, freeze=True, layer="penultimate", layer_idx=None, dtype=None):
+ def __init__(self, device="cpu", max_length=77, freeze=True, layer="penultimate", layer_idx=None, dtype=None, model_options={}):
if layer == "penultimate":
layer="hidden"
layer_idx=-2
textmodel_json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "clip_config_bigg.json")
super().__init__(device=device, freeze=freeze, layer=layer, layer_idx=layer_idx, textmodel_json_config=textmodel_json_config, dtype=dtype,
- special_tokens={"start": 49406, "end": 49407, "pad": 0}, layer_norm_hidden_state=False)
+ special_tokens={"start": 49406, "end": 49407, "pad": 0}, layer_norm_hidden_state=False, return_projected_pooled=True, model_options=model_options)
def load_sd(self, sd):
return super().load_sd(sd)
@@ -22,7 +22,8 @@ class SDXLClipGTokenizer(sd1_clip.SDTokenizer):
class SDXLTokenizer:
def __init__(self, embedding_directory=None, tokenizer_data={}):
- self.clip_l = sd1_clip.SDTokenizer(embedding_directory=embedding_directory)
+ clip_l_tokenizer_class = tokenizer_data.get("clip_l_tokenizer_class", sd1_clip.SDTokenizer)
+ self.clip_l = clip_l_tokenizer_class(embedding_directory=embedding_directory)
self.clip_g = SDXLClipGTokenizer(embedding_directory=embedding_directory)
def tokenize_with_weights(self, text:str, return_word_ids=False):
@@ -38,10 +39,11 @@ class SDXLTokenizer:
return {}
class SDXLClipModel(torch.nn.Module):
- def __init__(self, device="cpu", dtype=None):
+ def __init__(self, device="cpu", dtype=None, model_options={}):
super().__init__()
- self.clip_l = sd1_clip.SDClipModel(layer="hidden", layer_idx=-2, device=device, dtype=dtype, layer_norm_hidden_state=False)
- self.clip_g = SDXLClipG(device=device, dtype=dtype)
+ clip_l_class = model_options.get("clip_l_class", sd1_clip.SDClipModel)
+ self.clip_l = clip_l_class(layer="hidden", layer_idx=-2, device=device, dtype=dtype, layer_norm_hidden_state=False, model_options=model_options)
+ self.clip_g = SDXLClipG(device=device, dtype=dtype, model_options=model_options)
self.dtypes = set([dtype])
def set_clip_options(self, options):
@@ -57,7 +59,8 @@ class SDXLClipModel(torch.nn.Module):
token_weight_pairs_l = token_weight_pairs["l"]
g_out, g_pooled = self.clip_g.encode_token_weights(token_weight_pairs_g)
l_out, l_pooled = self.clip_l.encode_token_weights(token_weight_pairs_l)
- return torch.cat([l_out, g_out], dim=-1), g_pooled
+ cut_to = min(l_out.shape[1], g_out.shape[1])
+ return torch.cat([l_out[:,:cut_to], g_out[:,:cut_to]], dim=-1), g_pooled
def load_sd(self, sd):
if "text_model.encoder.layers.30.mlp.fc1.weight" in sd:
@@ -66,8 +69,8 @@ class SDXLClipModel(torch.nn.Module):
return self.clip_l.load_sd(sd)
class SDXLRefinerClipModel(sd1_clip.SD1ClipModel):
- def __init__(self, device="cpu", dtype=None):
- super().__init__(device=device, dtype=dtype, clip_name="g", clip_model=SDXLClipG)
+ def __init__(self, device="cpu", dtype=None, model_options={}):
+ super().__init__(device=device, dtype=dtype, clip_name="g", clip_model=SDXLClipG, model_options=model_options)
class StableCascadeClipGTokenizer(sd1_clip.SDTokenizer):
@@ -79,14 +82,14 @@ class StableCascadeTokenizer(sd1_clip.SD1Tokenizer):
super().__init__(embedding_directory=embedding_directory, tokenizer_data=tokenizer_data, clip_name="g", tokenizer=StableCascadeClipGTokenizer)
class StableCascadeClipG(sd1_clip.SDClipModel):
- def __init__(self, device="cpu", max_length=77, freeze=True, layer="hidden", layer_idx=-1, dtype=None):
+ def __init__(self, device="cpu", max_length=77, freeze=True, layer="hidden", layer_idx=-1, dtype=None, model_options={}):
textmodel_json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "clip_config_bigg.json")
super().__init__(device=device, freeze=freeze, layer=layer, layer_idx=layer_idx, textmodel_json_config=textmodel_json_config, dtype=dtype,
- special_tokens={"start": 49406, "end": 49407, "pad": 49407}, layer_norm_hidden_state=False, enable_attention_masks=True)
+ special_tokens={"start": 49406, "end": 49407, "pad": 49407}, layer_norm_hidden_state=False, enable_attention_masks=True, return_projected_pooled=True, model_options=model_options)
def load_sd(self, sd):
return super().load_sd(sd)
class StableCascadeClipModel(sd1_clip.SD1ClipModel):
- def __init__(self, device="cpu", dtype=None):
- super().__init__(device=device, dtype=dtype, clip_name="g", clip_model=StableCascadeClipG)
+ def __init__(self, device="cpu", dtype=None, model_options={}):
+ super().__init__(device=device, dtype=dtype, clip_name="g", clip_model=StableCascadeClipG, model_options=model_options)
diff --git a/comfy/supported_models.py b/comfy/supported_models.py
index d07a7106c..3603313fa 100644
--- a/comfy/supported_models.py
+++ b/comfy/supported_models.py
@@ -181,7 +181,7 @@ class SDXL(supported_models_base.BASE):
latent_format = latent_formats.SDXL
- memory_usage_factor = 0.7
+ memory_usage_factor = 0.8
def model_type(self, state_dict, prefix=""):
if 'edm_mean' in state_dict and 'edm_std' in state_dict: #Playground V2.5
@@ -654,6 +654,7 @@ class Flux(supported_models_base.BASE):
def clip_target(self, state_dict={}):
pref = self.text_encoder_key_prefix[0]
t5_key = "{}t5xxl.transformer.encoder.final_layer_norm.weight".format(pref)
+ dtype_t5 = None
if t5_key in state_dict:
dtype_t5 = state_dict[t5_key].dtype
return supported_models_base.ClipTarget(comfy.text_encoders.flux.FluxTokenizer, comfy.text_encoders.flux.flux_clip(dtype_t5=dtype_t5))
diff --git a/comfy/text_encoders/aura_t5.py b/comfy/text_encoders/aura_t5.py
index 8500c7b70..e9ad45a7f 100644
--- a/comfy/text_encoders/aura_t5.py
+++ b/comfy/text_encoders/aura_t5.py
@@ -4,9 +4,9 @@ import comfy.text_encoders.t5
import os
class PT5XlModel(sd1_clip.SDClipModel):
- def __init__(self, device="cpu", layer="last", layer_idx=None, dtype=None):
+ def __init__(self, device="cpu", layer="last", layer_idx=None, dtype=None, model_options={}):
textmodel_json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "t5_pile_config_xl.json")
- super().__init__(device=device, layer=layer, layer_idx=layer_idx, textmodel_json_config=textmodel_json_config, dtype=dtype, special_tokens={"end": 2, "pad": 1}, model_class=comfy.text_encoders.t5.T5, enable_attention_masks=True, zero_out_masked=True)
+ super().__init__(device=device, layer=layer, layer_idx=layer_idx, textmodel_json_config=textmodel_json_config, dtype=dtype, special_tokens={"end": 2, "pad": 1}, model_class=comfy.text_encoders.t5.T5, enable_attention_masks=True, zero_out_masked=True, model_options=model_options)
class PT5XlTokenizer(sd1_clip.SDTokenizer):
def __init__(self, embedding_directory=None, tokenizer_data={}):
@@ -18,5 +18,5 @@ class AuraT5Tokenizer(sd1_clip.SD1Tokenizer):
super().__init__(embedding_directory=embedding_directory, tokenizer_data=tokenizer_data, clip_name="pile_t5xl", tokenizer=PT5XlTokenizer)
class AuraT5Model(sd1_clip.SD1ClipModel):
- def __init__(self, device="cpu", dtype=None, **kwargs):
- super().__init__(device=device, dtype=dtype, name="pile_t5xl", clip_model=PT5XlModel, **kwargs)
+ def __init__(self, device="cpu", dtype=None, model_options={}, **kwargs):
+ super().__init__(device=device, dtype=dtype, model_options=model_options, name="pile_t5xl", clip_model=PT5XlModel, **kwargs)
diff --git a/comfy/text_encoders/flux.py b/comfy/text_encoders/flux.py
index ee26f560d..7c75fe64b 100644
--- a/comfy/text_encoders/flux.py
+++ b/comfy/text_encoders/flux.py
@@ -6,9 +6,9 @@ import torch
import os
class T5XXLModel(sd1_clip.SDClipModel):
- def __init__(self, device="cpu", layer="last", layer_idx=None, dtype=None):
+ def __init__(self, device="cpu", layer="last", layer_idx=None, dtype=None, model_options={}):
textmodel_json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "t5_config_xxl.json")
- super().__init__(device=device, layer=layer, layer_idx=layer_idx, textmodel_json_config=textmodel_json_config, dtype=dtype, special_tokens={"end": 1, "pad": 0}, model_class=comfy.text_encoders.t5.T5)
+ super().__init__(device=device, layer=layer, layer_idx=layer_idx, textmodel_json_config=textmodel_json_config, dtype=dtype, special_tokens={"end": 1, "pad": 0}, model_class=comfy.text_encoders.t5.T5, model_options=model_options)
class T5XXLTokenizer(sd1_clip.SDTokenizer):
def __init__(self, embedding_directory=None, tokenizer_data={}):
@@ -18,7 +18,8 @@ class T5XXLTokenizer(sd1_clip.SDTokenizer):
class FluxTokenizer:
def __init__(self, embedding_directory=None, tokenizer_data={}):
- self.clip_l = sd1_clip.SDTokenizer(embedding_directory=embedding_directory)
+ clip_l_tokenizer_class = tokenizer_data.get("clip_l_tokenizer_class", sd1_clip.SDTokenizer)
+ self.clip_l = clip_l_tokenizer_class(embedding_directory=embedding_directory)
self.t5xxl = T5XXLTokenizer(embedding_directory=embedding_directory)
def tokenize_with_weights(self, text:str, return_word_ids=False):
@@ -35,11 +36,12 @@ class FluxTokenizer:
class FluxClipModel(torch.nn.Module):
- def __init__(self, dtype_t5=None, device="cpu", dtype=None):
+ def __init__(self, dtype_t5=None, device="cpu", dtype=None, model_options={}):
super().__init__()
dtype_t5 = comfy.model_management.pick_weight_dtype(dtype_t5, dtype, device)
- self.clip_l = sd1_clip.SDClipModel(device=device, dtype=dtype, return_projected_pooled=False)
- self.t5xxl = T5XXLModel(device=device, dtype=dtype_t5)
+ clip_l_class = model_options.get("clip_l_class", sd1_clip.SDClipModel)
+ self.clip_l = clip_l_class(device=device, dtype=dtype, return_projected_pooled=False, model_options=model_options)
+ self.t5xxl = T5XXLModel(device=device, dtype=dtype_t5, model_options=model_options)
self.dtypes = set([dtype, dtype_t5])
def set_clip_options(self, options):
@@ -66,6 +68,6 @@ class FluxClipModel(torch.nn.Module):
def flux_clip(dtype_t5=None):
class FluxClipModel_(FluxClipModel):
- def __init__(self, device="cpu", dtype=None):
- super().__init__(dtype_t5=dtype_t5, device=device, dtype=dtype)
+ def __init__(self, device="cpu", dtype=None, model_options={}):
+ super().__init__(dtype_t5=dtype_t5, device=device, dtype=dtype, model_options=model_options)
return FluxClipModel_
diff --git a/comfy/text_encoders/hydit.py b/comfy/text_encoders/hydit.py
index 9dfa288b1..7cb790f45 100644
--- a/comfy/text_encoders/hydit.py
+++ b/comfy/text_encoders/hydit.py
@@ -7,9 +7,9 @@ import os
import torch
class HyditBertModel(sd1_clip.SDClipModel):
- def __init__(self, device="cpu", layer="last", layer_idx=None, dtype=None):
+ def __init__(self, device="cpu", layer="last", layer_idx=None, dtype=None, model_options={}):
textmodel_json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "hydit_clip.json")
- super().__init__(device=device, layer=layer, layer_idx=layer_idx, textmodel_json_config=textmodel_json_config, dtype=dtype, special_tokens={"start": 101, "end": 102, "pad": 0}, model_class=BertModel, enable_attention_masks=True, return_attention_masks=True)
+ super().__init__(device=device, layer=layer, layer_idx=layer_idx, textmodel_json_config=textmodel_json_config, dtype=dtype, special_tokens={"start": 101, "end": 102, "pad": 0}, model_class=BertModel, enable_attention_masks=True, return_attention_masks=True, model_options=model_options)
class HyditBertTokenizer(sd1_clip.SDTokenizer):
def __init__(self, embedding_directory=None, tokenizer_data={}):
@@ -18,9 +18,9 @@ class HyditBertTokenizer(sd1_clip.SDTokenizer):
class MT5XLModel(sd1_clip.SDClipModel):
- def __init__(self, device="cpu", layer="last", layer_idx=None, dtype=None):
+ def __init__(self, device="cpu", layer="last", layer_idx=None, dtype=None, model_options={}):
textmodel_json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "mt5_config_xl.json")
- super().__init__(device=device, layer=layer, layer_idx=layer_idx, textmodel_json_config=textmodel_json_config, dtype=dtype, special_tokens={"end": 1, "pad": 0}, model_class=comfy.text_encoders.t5.T5, enable_attention_masks=True, return_attention_masks=True)
+ super().__init__(device=device, layer=layer, layer_idx=layer_idx, textmodel_json_config=textmodel_json_config, dtype=dtype, special_tokens={"end": 1, "pad": 0}, model_class=comfy.text_encoders.t5.T5, enable_attention_masks=True, return_attention_masks=True, model_options=model_options)
class MT5XLTokenizer(sd1_clip.SDTokenizer):
def __init__(self, embedding_directory=None, tokenizer_data={}):
@@ -50,10 +50,10 @@ class HyditTokenizer:
return {"mt5xl.spiece_model": self.mt5xl.state_dict()["spiece_model"]}
class HyditModel(torch.nn.Module):
- def __init__(self, device="cpu", dtype=None):
+ def __init__(self, device="cpu", dtype=None, model_options={}):
super().__init__()
- self.hydit_clip = HyditBertModel(dtype=dtype)
- self.mt5xl = MT5XLModel(dtype=dtype)
+ self.hydit_clip = HyditBertModel(dtype=dtype, model_options=model_options)
+ self.mt5xl = MT5XLModel(dtype=dtype, model_options=model_options)
self.dtypes = set()
if dtype is not None:
diff --git a/comfy/text_encoders/long_clipl.json b/comfy/text_encoders/long_clipl.json
new file mode 100644
index 000000000..5e2056ff3
--- /dev/null
+++ b/comfy/text_encoders/long_clipl.json
@@ -0,0 +1,25 @@
+{
+ "_name_or_path": "openai/clip-vit-large-patch14",
+ "architectures": [
+ "CLIPTextModel"
+ ],
+ "attention_dropout": 0.0,
+ "bos_token_id": 0,
+ "dropout": 0.0,
+ "eos_token_id": 49407,
+ "hidden_act": "quick_gelu",
+ "hidden_size": 768,
+ "initializer_factor": 1.0,
+ "initializer_range": 0.02,
+ "intermediate_size": 3072,
+ "layer_norm_eps": 1e-05,
+ "max_position_embeddings": 248,
+ "model_type": "clip_text_model",
+ "num_attention_heads": 12,
+ "num_hidden_layers": 12,
+ "pad_token_id": 1,
+ "projection_dim": 768,
+ "torch_dtype": "float32",
+ "transformers_version": "4.24.0",
+ "vocab_size": 49408
+}
diff --git a/comfy/text_encoders/long_clipl.py b/comfy/text_encoders/long_clipl.py
new file mode 100644
index 000000000..b81912cb3
--- /dev/null
+++ b/comfy/text_encoders/long_clipl.py
@@ -0,0 +1,30 @@
+from comfy import sd1_clip
+import os
+
+class LongClipTokenizer_(sd1_clip.SDTokenizer):
+ def __init__(self, embedding_directory=None, tokenizer_data={}):
+ super().__init__(max_length=248, embedding_directory=embedding_directory, tokenizer_data=tokenizer_data)
+
+class LongClipModel_(sd1_clip.SDClipModel):
+ def __init__(self, *args, **kwargs):
+ textmodel_json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "long_clipl.json")
+ super().__init__(*args, textmodel_json_config=textmodel_json_config, **kwargs)
+
+class LongClipTokenizer(sd1_clip.SD1Tokenizer):
+ def __init__(self, embedding_directory=None, tokenizer_data={}):
+ super().__init__(embedding_directory=embedding_directory, tokenizer_data=tokenizer_data, tokenizer=LongClipTokenizer_)
+
+class LongClipModel(sd1_clip.SD1ClipModel):
+ def __init__(self, device="cpu", dtype=None, model_options={}, **kwargs):
+ super().__init__(device=device, dtype=dtype, model_options=model_options, clip_model=LongClipModel_, **kwargs)
+
+def model_options_long_clip(sd, tokenizer_data, model_options):
+ w = sd.get("clip_l.text_model.embeddings.position_embedding.weight", None)
+ if w is None:
+ w = sd.get("text_model.embeddings.position_embedding.weight", None)
+ if w is not None and w.shape[0] == 248:
+ tokenizer_data = tokenizer_data.copy()
+ model_options = model_options.copy()
+ tokenizer_data["clip_l_tokenizer_class"] = LongClipTokenizer_
+ model_options["clip_l_class"] = LongClipModel_
+ return tokenizer_data, model_options
diff --git a/comfy/text_encoders/sa_t5.py b/comfy/text_encoders/sa_t5.py
index 189f8c181..7778ce47a 100644
--- a/comfy/text_encoders/sa_t5.py
+++ b/comfy/text_encoders/sa_t5.py
@@ -4,9 +4,9 @@ import comfy.text_encoders.t5
import os
class T5BaseModel(sd1_clip.SDClipModel):
- def __init__(self, device="cpu", layer="last", layer_idx=None, dtype=None):
+ def __init__(self, device="cpu", layer="last", layer_idx=None, dtype=None, model_options={}):
textmodel_json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "t5_config_base.json")
- super().__init__(device=device, layer=layer, layer_idx=layer_idx, textmodel_json_config=textmodel_json_config, dtype=dtype, special_tokens={"end": 1, "pad": 0}, model_class=comfy.text_encoders.t5.T5, enable_attention_masks=True, zero_out_masked=True)
+ super().__init__(device=device, layer=layer, layer_idx=layer_idx, textmodel_json_config=textmodel_json_config, dtype=dtype, model_options=model_options, special_tokens={"end": 1, "pad": 0}, model_class=comfy.text_encoders.t5.T5, enable_attention_masks=True, zero_out_masked=True)
class T5BaseTokenizer(sd1_clip.SDTokenizer):
def __init__(self, embedding_directory=None, tokenizer_data={}):
@@ -18,5 +18,5 @@ class SAT5Tokenizer(sd1_clip.SD1Tokenizer):
super().__init__(embedding_directory=embedding_directory, tokenizer_data=tokenizer_data, clip_name="t5base", tokenizer=T5BaseTokenizer)
class SAT5Model(sd1_clip.SD1ClipModel):
- def __init__(self, device="cpu", dtype=None, **kwargs):
- super().__init__(device=device, dtype=dtype, name="t5base", clip_model=T5BaseModel, **kwargs)
+ def __init__(self, device="cpu", dtype=None, model_options={}, **kwargs):
+ super().__init__(device=device, dtype=dtype, model_options=model_options, name="t5base", clip_model=T5BaseModel, **kwargs)
diff --git a/comfy/text_encoders/sd2_clip.py b/comfy/text_encoders/sd2_clip.py
index 8ea8e1cd0..31fc89869 100644
--- a/comfy/text_encoders/sd2_clip.py
+++ b/comfy/text_encoders/sd2_clip.py
@@ -2,13 +2,13 @@ from comfy import sd1_clip
import os
class SD2ClipHModel(sd1_clip.SDClipModel):
- def __init__(self, arch="ViT-H-14", device="cpu", max_length=77, freeze=True, layer="penultimate", layer_idx=None, dtype=None):
+ def __init__(self, arch="ViT-H-14", device="cpu", max_length=77, freeze=True, layer="penultimate", layer_idx=None, dtype=None, model_options={}):
if layer == "penultimate":
layer="hidden"
layer_idx=-2
textmodel_json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "sd2_clip_config.json")
- super().__init__(device=device, freeze=freeze, layer=layer, layer_idx=layer_idx, textmodel_json_config=textmodel_json_config, dtype=dtype, special_tokens={"start": 49406, "end": 49407, "pad": 0})
+ super().__init__(device=device, freeze=freeze, layer=layer, layer_idx=layer_idx, textmodel_json_config=textmodel_json_config, dtype=dtype, special_tokens={"start": 49406, "end": 49407, "pad": 0}, return_projected_pooled=True, model_options=model_options)
class SD2ClipHTokenizer(sd1_clip.SDTokenizer):
def __init__(self, tokenizer_path=None, embedding_directory=None, tokenizer_data={}):
@@ -19,5 +19,5 @@ class SD2Tokenizer(sd1_clip.SD1Tokenizer):
super().__init__(embedding_directory=embedding_directory, tokenizer_data=tokenizer_data, clip_name="h", tokenizer=SD2ClipHTokenizer)
class SD2ClipModel(sd1_clip.SD1ClipModel):
- def __init__(self, device="cpu", dtype=None, **kwargs):
- super().__init__(device=device, dtype=dtype, clip_name="h", clip_model=SD2ClipHModel, **kwargs)
+ def __init__(self, device="cpu", dtype=None, model_options={}, **kwargs):
+ super().__init__(device=device, dtype=dtype, model_options=model_options, clip_name="h", clip_model=SD2ClipHModel, **kwargs)
diff --git a/comfy/text_encoders/sd3_clip.py b/comfy/text_encoders/sd3_clip.py
index 549c068e9..c54f28856 100644
--- a/comfy/text_encoders/sd3_clip.py
+++ b/comfy/text_encoders/sd3_clip.py
@@ -8,19 +8,20 @@ import comfy.model_management
import logging
class T5XXLModel(sd1_clip.SDClipModel):
- def __init__(self, device="cpu", layer="last", layer_idx=None, dtype=None):
+ def __init__(self, device="cpu", layer="last", layer_idx=None, dtype=None, model_options={}):
textmodel_json_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "t5_config_xxl.json")
- super().__init__(device=device, layer=layer, layer_idx=layer_idx, textmodel_json_config=textmodel_json_config, dtype=dtype, special_tokens={"end": 1, "pad": 0}, model_class=comfy.text_encoders.t5.T5)
+ super().__init__(device=device, layer=layer, layer_idx=layer_idx, textmodel_json_config=textmodel_json_config, dtype=dtype, special_tokens={"end": 1, "pad": 0}, model_class=comfy.text_encoders.t5.T5, model_options=model_options)
class T5XXLTokenizer(sd1_clip.SDTokenizer):
def __init__(self, embedding_directory=None, tokenizer_data={}):
tokenizer_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "t5_tokenizer")
- super().__init__(tokenizer_path, pad_with_end=False, embedding_size=4096, embedding_key='t5xxl', tokenizer_class=T5TokenizerFast, has_start_token=False, pad_to_max_length=False, max_length=99999999, min_length=77)
+ super().__init__(tokenizer_path, embedding_directory=embedding_directory, pad_with_end=False, embedding_size=4096, embedding_key='t5xxl', tokenizer_class=T5TokenizerFast, has_start_token=False, pad_to_max_length=False, max_length=99999999, min_length=77)
class SD3Tokenizer:
def __init__(self, embedding_directory=None, tokenizer_data={}):
- self.clip_l = sd1_clip.SDTokenizer(embedding_directory=embedding_directory)
+ clip_l_tokenizer_class = tokenizer_data.get("clip_l_tokenizer_class", sd1_clip.SDTokenizer)
+ self.clip_l = clip_l_tokenizer_class(embedding_directory=embedding_directory)
self.clip_g = sdxl_clip.SDXLClipGTokenizer(embedding_directory=embedding_directory)
self.t5xxl = T5XXLTokenizer(embedding_directory=embedding_directory)
@@ -38,24 +39,25 @@ class SD3Tokenizer:
return {}
class SD3ClipModel(torch.nn.Module):
- def __init__(self, clip_l=True, clip_g=True, t5=True, dtype_t5=None, device="cpu", dtype=None):
+ def __init__(self, clip_l=True, clip_g=True, t5=True, dtype_t5=None, device="cpu", dtype=None, model_options={}):
super().__init__()
self.dtypes = set()
if clip_l:
- self.clip_l = sd1_clip.SDClipModel(layer="hidden", layer_idx=-2, device=device, dtype=dtype, layer_norm_hidden_state=False, return_projected_pooled=False)
+ clip_l_class = model_options.get("clip_l_class", sd1_clip.SDClipModel)
+ self.clip_l = clip_l_class(layer="hidden", layer_idx=-2, device=device, dtype=dtype, layer_norm_hidden_state=False, return_projected_pooled=False, model_options=model_options)
self.dtypes.add(dtype)
else:
self.clip_l = None
if clip_g:
- self.clip_g = sdxl_clip.SDXLClipG(device=device, dtype=dtype)
+ self.clip_g = sdxl_clip.SDXLClipG(device=device, dtype=dtype, model_options=model_options)
self.dtypes.add(dtype)
else:
self.clip_g = None
if t5:
dtype_t5 = comfy.model_management.pick_weight_dtype(dtype_t5, dtype, device)
- self.t5xxl = T5XXLModel(device=device, dtype=dtype_t5)
+ self.t5xxl = T5XXLModel(device=device, dtype=dtype_t5, model_options=model_options)
self.dtypes.add(dtype_t5)
else:
self.t5xxl = None
@@ -95,7 +97,8 @@ class SD3ClipModel(torch.nn.Module):
if self.clip_g is not None:
g_out, g_pooled = self.clip_g.encode_token_weights(token_weight_pairs_g)
if lg_out is not None:
- lg_out = torch.cat([lg_out, g_out], dim=-1)
+ cut_to = min(lg_out.shape[1], g_out.shape[1])
+ lg_out = torch.cat([lg_out[:,:cut_to], g_out[:,:cut_to]], dim=-1)
else:
lg_out = torch.nn.functional.pad(g_out, (768, 0))
else:
@@ -132,6 +135,6 @@ class SD3ClipModel(torch.nn.Module):
def sd3_clip(clip_l=True, clip_g=True, t5=True, dtype_t5=None):
class SD3ClipModel_(SD3ClipModel):
- def __init__(self, device="cpu", dtype=None):
- super().__init__(clip_l=clip_l, clip_g=clip_g, t5=t5, dtype_t5=dtype_t5, device=device, dtype=dtype)
+ def __init__(self, device="cpu", dtype=None, model_options={}):
+ super().__init__(clip_l=clip_l, clip_g=clip_g, t5=t5, dtype_t5=dtype_t5, device=device, dtype=dtype, model_options=model_options)
return SD3ClipModel_
diff --git a/comfy/utils.py b/comfy/utils.py
index d0d410d97..78f8314fc 100644
--- a/comfy/utils.py
+++ b/comfy/utils.py
@@ -528,6 +528,8 @@ def flux_to_diffusers(mmdit_config, output_prefix=""):
("guidance_in.out_layer.weight", "time_text_embed.guidance_embedder.linear_2.weight"),
("final_layer.adaLN_modulation.1.bias", "norm_out.linear.bias", swap_scale_shift),
("final_layer.adaLN_modulation.1.weight", "norm_out.linear.weight", swap_scale_shift),
+ ("pos_embed_input.bias", "controlnet_x_embedder.bias"),
+ ("pos_embed_input.weight", "controlnet_x_embedder.weight"),
}
for k in MAP_BASIC:
@@ -711,7 +713,9 @@ def common_upscale(samples, width, height, upscale_method, crop):
return torch.nn.functional.interpolate(s, size=(height, width), mode=upscale_method)
def get_tiled_scale_steps(width, height, tile_x, tile_y, overlap):
- return math.ceil((height / (tile_y - overlap))) * math.ceil((width / (tile_x - overlap)))
+ rows = 1 if height <= tile_y else math.ceil((height - overlap) / (tile_y - overlap))
+ cols = 1 if width <= tile_x else math.ceil((width - overlap) / (tile_x - overlap))
+ return rows * cols
@torch.inference_mode()
def tiled_scale_multidim(samples, function, tile=(64, 64), overlap = 8, upscale_amount = 4, out_channels = 3, output_device="cpu", pbar = None):
@@ -720,10 +724,20 @@ def tiled_scale_multidim(samples, function, tile=(64, 64), overlap = 8, upscale_
for b in range(samples.shape[0]):
s = samples[b:b+1]
+
+ # handle entire input fitting in a single tile
+ if all(s.shape[d+2] <= tile[d] for d in range(dims)):
+ output[b:b+1] = function(s).to(output_device)
+ if pbar is not None:
+ pbar.update(1)
+ continue
+
out = torch.zeros([s.shape[0], out_channels] + list(map(lambda a: round(a * upscale_amount), s.shape[2:])), device=output_device)
out_div = torch.zeros([s.shape[0], out_channels] + list(map(lambda a: round(a * upscale_amount), s.shape[2:])), device=output_device)
- for it in itertools.product(*map(lambda a: range(0, a[0], a[1] - overlap), zip(s.shape[2:], tile))):
+ positions = [range(0, s.shape[d+2], tile[d] - overlap) if s.shape[d+2] > tile[d] else [0] for d in range(dims)]
+
+ for it in itertools.product(*positions):
s_in = s
upscaled = []
@@ -732,15 +746,16 @@ def tiled_scale_multidim(samples, function, tile=(64, 64), overlap = 8, upscale_
l = min(tile[d], s.shape[d + 2] - pos)
s_in = s_in.narrow(d + 2, pos, l)
upscaled.append(round(pos * upscale_amount))
+
ps = function(s_in).to(output_device)
mask = torch.ones_like(ps)
feather = round(overlap * upscale_amount)
+
for t in range(feather):
for d in range(2, dims + 2):
- m = mask.narrow(d, t, 1)
- m *= ((1.0/feather) * (t + 1))
- m = mask.narrow(d, mask.shape[d] -1 -t, 1)
- m *= ((1.0/feather) * (t + 1))
+ a = (t + 1) / feather
+ mask.narrow(d, t, 1).mul_(a)
+ mask.narrow(d, mask.shape[d] - 1 - t, 1).mul_(a)
o = out
o_d = out_div
@@ -748,8 +763,8 @@ def tiled_scale_multidim(samples, function, tile=(64, 64), overlap = 8, upscale_
o = o.narrow(d + 2, upscaled[d], mask.shape[d + 2])
o_d = o_d.narrow(d + 2, upscaled[d], mask.shape[d + 2])
- o += ps * mask
- o_d += mask
+ o.add_(ps * mask)
+ o_d.add_(mask)
if pbar is not None:
pbar.update(1)
diff --git a/comfy_execution/caching.py b/comfy_execution/caching.py
new file mode 100644
index 000000000..630f280fc
--- /dev/null
+++ b/comfy_execution/caching.py
@@ -0,0 +1,318 @@
+import itertools
+from typing import Sequence, Mapping, Dict
+from comfy_execution.graph import DynamicPrompt
+
+import nodes
+
+from comfy_execution.graph_utils import is_link
+
+NODE_CLASS_CONTAINS_UNIQUE_ID: Dict[str, bool] = {}
+
+
+def include_unique_id_in_input(class_type: str) -> bool:
+ if class_type in NODE_CLASS_CONTAINS_UNIQUE_ID:
+ return NODE_CLASS_CONTAINS_UNIQUE_ID[class_type]
+ class_def = nodes.NODE_CLASS_MAPPINGS[class_type]
+ NODE_CLASS_CONTAINS_UNIQUE_ID[class_type] = "UNIQUE_ID" in class_def.INPUT_TYPES().get("hidden", {}).values()
+ return NODE_CLASS_CONTAINS_UNIQUE_ID[class_type]
+
+class CacheKeySet:
+ def __init__(self, dynprompt, node_ids, is_changed_cache):
+ self.keys = {}
+ self.subcache_keys = {}
+
+ def add_keys(self, node_ids):
+ raise NotImplementedError()
+
+ def all_node_ids(self):
+ return set(self.keys.keys())
+
+ def get_used_keys(self):
+ return self.keys.values()
+
+ def get_used_subcache_keys(self):
+ return self.subcache_keys.values()
+
+ def get_data_key(self, node_id):
+ return self.keys.get(node_id, None)
+
+ def get_subcache_key(self, node_id):
+ return self.subcache_keys.get(node_id, None)
+
+class Unhashable:
+ def __init__(self):
+ self.value = float("NaN")
+
+def to_hashable(obj):
+ # So that we don't infinitely recurse since frozenset and tuples
+ # are Sequences.
+ if isinstance(obj, (int, float, str, bool, type(None))):
+ return obj
+ elif isinstance(obj, Mapping):
+ return frozenset([(to_hashable(k), to_hashable(v)) for k, v in sorted(obj.items())])
+ elif isinstance(obj, Sequence):
+ return frozenset(zip(itertools.count(), [to_hashable(i) for i in obj]))
+ else:
+ # TODO - Support other objects like tensors?
+ return Unhashable()
+
+class CacheKeySetID(CacheKeySet):
+ def __init__(self, dynprompt, node_ids, is_changed_cache):
+ super().__init__(dynprompt, node_ids, is_changed_cache)
+ self.dynprompt = dynprompt
+ self.add_keys(node_ids)
+
+ def add_keys(self, node_ids):
+ for node_id in node_ids:
+ if node_id in self.keys:
+ continue
+ if not self.dynprompt.has_node(node_id):
+ continue
+ node = self.dynprompt.get_node(node_id)
+ self.keys[node_id] = (node_id, node["class_type"])
+ self.subcache_keys[node_id] = (node_id, node["class_type"])
+
+class CacheKeySetInputSignature(CacheKeySet):
+ def __init__(self, dynprompt, node_ids, is_changed_cache):
+ super().__init__(dynprompt, node_ids, is_changed_cache)
+ self.dynprompt = dynprompt
+ self.is_changed_cache = is_changed_cache
+ self.add_keys(node_ids)
+
+ def include_node_id_in_input(self) -> bool:
+ return False
+
+ def add_keys(self, node_ids):
+ for node_id in node_ids:
+ if node_id in self.keys:
+ continue
+ if not self.dynprompt.has_node(node_id):
+ continue
+ node = self.dynprompt.get_node(node_id)
+ self.keys[node_id] = self.get_node_signature(self.dynprompt, node_id)
+ self.subcache_keys[node_id] = (node_id, node["class_type"])
+
+ def get_node_signature(self, dynprompt, node_id):
+ signature = []
+ ancestors, order_mapping = self.get_ordered_ancestry(dynprompt, node_id)
+ signature.append(self.get_immediate_node_signature(dynprompt, node_id, order_mapping))
+ for ancestor_id in ancestors:
+ signature.append(self.get_immediate_node_signature(dynprompt, ancestor_id, order_mapping))
+ return to_hashable(signature)
+
+ def get_immediate_node_signature(self, dynprompt, node_id, ancestor_order_mapping):
+ if not dynprompt.has_node(node_id):
+ # This node doesn't exist -- we can't cache it.
+ return [float("NaN")]
+ node = dynprompt.get_node(node_id)
+ class_type = node["class_type"]
+ class_def = nodes.NODE_CLASS_MAPPINGS[class_type]
+ signature = [class_type, self.is_changed_cache.get(node_id)]
+ if self.include_node_id_in_input() or (hasattr(class_def, "NOT_IDEMPOTENT") and class_def.NOT_IDEMPOTENT) or include_unique_id_in_input(class_type):
+ signature.append(node_id)
+ inputs = node["inputs"]
+ for key in sorted(inputs.keys()):
+ if is_link(inputs[key]):
+ (ancestor_id, ancestor_socket) = inputs[key]
+ ancestor_index = ancestor_order_mapping[ancestor_id]
+ signature.append((key,("ANCESTOR", ancestor_index, ancestor_socket)))
+ else:
+ signature.append((key, inputs[key]))
+ return signature
+
+ # This function returns a list of all ancestors of the given node. The order of the list is
+ # deterministic based on which specific inputs the ancestor is connected by.
+ def get_ordered_ancestry(self, dynprompt, node_id):
+ ancestors = []
+ order_mapping = {}
+ self.get_ordered_ancestry_internal(dynprompt, node_id, ancestors, order_mapping)
+ return ancestors, order_mapping
+
+ def get_ordered_ancestry_internal(self, dynprompt, node_id, ancestors, order_mapping):
+ if not dynprompt.has_node(node_id):
+ return
+ inputs = dynprompt.get_node(node_id)["inputs"]
+ input_keys = sorted(inputs.keys())
+ for key in input_keys:
+ if is_link(inputs[key]):
+ ancestor_id = inputs[key][0]
+ if ancestor_id not in order_mapping:
+ ancestors.append(ancestor_id)
+ order_mapping[ancestor_id] = len(ancestors) - 1
+ self.get_ordered_ancestry_internal(dynprompt, ancestor_id, ancestors, order_mapping)
+
+class BasicCache:
+ def __init__(self, key_class):
+ self.key_class = key_class
+ self.initialized = False
+ self.dynprompt: DynamicPrompt
+ self.cache_key_set: CacheKeySet
+ self.cache = {}
+ self.subcaches = {}
+
+ def set_prompt(self, dynprompt, node_ids, is_changed_cache):
+ self.dynprompt = dynprompt
+ self.cache_key_set = self.key_class(dynprompt, node_ids, is_changed_cache)
+ self.is_changed_cache = is_changed_cache
+ self.initialized = True
+
+ def all_node_ids(self):
+ assert self.initialized
+ node_ids = self.cache_key_set.all_node_ids()
+ for subcache in self.subcaches.values():
+ node_ids = node_ids.union(subcache.all_node_ids())
+ return node_ids
+
+ def _clean_cache(self):
+ preserve_keys = set(self.cache_key_set.get_used_keys())
+ to_remove = []
+ for key in self.cache:
+ if key not in preserve_keys:
+ to_remove.append(key)
+ for key in to_remove:
+ del self.cache[key]
+
+ def _clean_subcaches(self):
+ preserve_subcaches = set(self.cache_key_set.get_used_subcache_keys())
+
+ to_remove = []
+ for key in self.subcaches:
+ if key not in preserve_subcaches:
+ to_remove.append(key)
+ for key in to_remove:
+ del self.subcaches[key]
+
+ def clean_unused(self):
+ assert self.initialized
+ self._clean_cache()
+ self._clean_subcaches()
+
+ def _set_immediate(self, node_id, value):
+ assert self.initialized
+ cache_key = self.cache_key_set.get_data_key(node_id)
+ self.cache[cache_key] = value
+
+ def _get_immediate(self, node_id):
+ if not self.initialized:
+ return None
+ cache_key = self.cache_key_set.get_data_key(node_id)
+ if cache_key in self.cache:
+ return self.cache[cache_key]
+ else:
+ return None
+
+ def _ensure_subcache(self, node_id, children_ids):
+ subcache_key = self.cache_key_set.get_subcache_key(node_id)
+ subcache = self.subcaches.get(subcache_key, None)
+ if subcache is None:
+ subcache = BasicCache(self.key_class)
+ self.subcaches[subcache_key] = subcache
+ subcache.set_prompt(self.dynprompt, children_ids, self.is_changed_cache)
+ return subcache
+
+ def _get_subcache(self, node_id):
+ assert self.initialized
+ subcache_key = self.cache_key_set.get_subcache_key(node_id)
+ if subcache_key in self.subcaches:
+ return self.subcaches[subcache_key]
+ else:
+ return None
+
+ def recursive_debug_dump(self):
+ result = []
+ for key in self.cache:
+ result.append({"key": key, "value": self.cache[key]})
+ for key in self.subcaches:
+ result.append({"subcache_key": key, "subcache": self.subcaches[key].recursive_debug_dump()})
+ return result
+
+class HierarchicalCache(BasicCache):
+ def __init__(self, key_class):
+ super().__init__(key_class)
+
+ def _get_cache_for(self, node_id):
+ assert self.dynprompt is not None
+ parent_id = self.dynprompt.get_parent_node_id(node_id)
+ if parent_id is None:
+ return self
+
+ hierarchy = []
+ while parent_id is not None:
+ hierarchy.append(parent_id)
+ parent_id = self.dynprompt.get_parent_node_id(parent_id)
+
+ cache = self
+ for parent_id in reversed(hierarchy):
+ cache = cache._get_subcache(parent_id)
+ if cache is None:
+ return None
+ return cache
+
+ def get(self, node_id):
+ cache = self._get_cache_for(node_id)
+ if cache is None:
+ return None
+ return cache._get_immediate(node_id)
+
+ def set(self, node_id, value):
+ cache = self._get_cache_for(node_id)
+ assert cache is not None
+ cache._set_immediate(node_id, value)
+
+ def ensure_subcache_for(self, node_id, children_ids):
+ cache = self._get_cache_for(node_id)
+ assert cache is not None
+ return cache._ensure_subcache(node_id, children_ids)
+
+class LRUCache(BasicCache):
+ def __init__(self, key_class, max_size=100):
+ super().__init__(key_class)
+ self.max_size = max_size
+ self.min_generation = 0
+ self.generation = 0
+ self.used_generation = {}
+ self.children = {}
+
+ def set_prompt(self, dynprompt, node_ids, is_changed_cache):
+ super().set_prompt(dynprompt, node_ids, is_changed_cache)
+ self.generation += 1
+ for node_id in node_ids:
+ self._mark_used(node_id)
+
+ def clean_unused(self):
+ while len(self.cache) > self.max_size and self.min_generation < self.generation:
+ self.min_generation += 1
+ to_remove = [key for key in self.cache if self.used_generation[key] < self.min_generation]
+ for key in to_remove:
+ del self.cache[key]
+ del self.used_generation[key]
+ if key in self.children:
+ del self.children[key]
+ self._clean_subcaches()
+
+ def get(self, node_id):
+ self._mark_used(node_id)
+ return self._get_immediate(node_id)
+
+ def _mark_used(self, node_id):
+ cache_key = self.cache_key_set.get_data_key(node_id)
+ if cache_key is not None:
+ self.used_generation[cache_key] = self.generation
+
+ def set(self, node_id, value):
+ self._mark_used(node_id)
+ return self._set_immediate(node_id, value)
+
+ def ensure_subcache_for(self, node_id, children_ids):
+ # Just uses subcaches for tracking 'live' nodes
+ super()._ensure_subcache(node_id, children_ids)
+
+ self.cache_key_set.add_keys(children_ids)
+ self._mark_used(node_id)
+ cache_key = self.cache_key_set.get_data_key(node_id)
+ self.children[cache_key] = []
+ for child_id in children_ids:
+ self._mark_used(child_id)
+ self.children[cache_key].append(self.cache_key_set.get_data_key(child_id))
+ return self
+
diff --git a/comfy_execution/graph.py b/comfy_execution/graph.py
new file mode 100644
index 000000000..0b5bf1899
--- /dev/null
+++ b/comfy_execution/graph.py
@@ -0,0 +1,270 @@
+import nodes
+
+from comfy_execution.graph_utils import is_link
+
+class DependencyCycleError(Exception):
+ pass
+
+class NodeInputError(Exception):
+ pass
+
+class NodeNotFoundError(Exception):
+ pass
+
+class DynamicPrompt:
+ def __init__(self, original_prompt):
+ # The original prompt provided by the user
+ self.original_prompt = original_prompt
+ # Any extra pieces of the graph created during execution
+ self.ephemeral_prompt = {}
+ self.ephemeral_parents = {}
+ self.ephemeral_display = {}
+
+ def get_node(self, node_id):
+ if node_id in self.ephemeral_prompt:
+ return self.ephemeral_prompt[node_id]
+ if node_id in self.original_prompt:
+ return self.original_prompt[node_id]
+ raise NodeNotFoundError(f"Node {node_id} not found")
+
+ def has_node(self, node_id):
+ return node_id in self.original_prompt or node_id in self.ephemeral_prompt
+
+ def add_ephemeral_node(self, node_id, node_info, parent_id, display_id):
+ self.ephemeral_prompt[node_id] = node_info
+ self.ephemeral_parents[node_id] = parent_id
+ self.ephemeral_display[node_id] = display_id
+
+ def get_real_node_id(self, node_id):
+ while node_id in self.ephemeral_parents:
+ node_id = self.ephemeral_parents[node_id]
+ return node_id
+
+ def get_parent_node_id(self, node_id):
+ return self.ephemeral_parents.get(node_id, None)
+
+ def get_display_node_id(self, node_id):
+ while node_id in self.ephemeral_display:
+ node_id = self.ephemeral_display[node_id]
+ return node_id
+
+ def all_node_ids(self):
+ return set(self.original_prompt.keys()).union(set(self.ephemeral_prompt.keys()))
+
+ def get_original_prompt(self):
+ return self.original_prompt
+
+def get_input_info(class_def, input_name):
+ valid_inputs = class_def.INPUT_TYPES()
+ input_info = None
+ input_category = None
+ if "required" in valid_inputs and input_name in valid_inputs["required"]:
+ input_category = "required"
+ input_info = valid_inputs["required"][input_name]
+ elif "optional" in valid_inputs and input_name in valid_inputs["optional"]:
+ input_category = "optional"
+ input_info = valid_inputs["optional"][input_name]
+ elif "hidden" in valid_inputs and input_name in valid_inputs["hidden"]:
+ input_category = "hidden"
+ input_info = valid_inputs["hidden"][input_name]
+ if input_info is None:
+ return None, None, None
+ input_type = input_info[0]
+ if len(input_info) > 1:
+ extra_info = input_info[1]
+ else:
+ extra_info = {}
+ return input_type, input_category, extra_info
+
+class TopologicalSort:
+ def __init__(self, dynprompt):
+ self.dynprompt = dynprompt
+ self.pendingNodes = {}
+ self.blockCount = {} # Number of nodes this node is directly blocked by
+ self.blocking = {} # Which nodes are blocked by this node
+
+ def get_input_info(self, unique_id, input_name):
+ class_type = self.dynprompt.get_node(unique_id)["class_type"]
+ class_def = nodes.NODE_CLASS_MAPPINGS[class_type]
+ return get_input_info(class_def, input_name)
+
+ def make_input_strong_link(self, to_node_id, to_input):
+ inputs = self.dynprompt.get_node(to_node_id)["inputs"]
+ if to_input not in inputs:
+ raise NodeInputError(f"Node {to_node_id} says it needs input {to_input}, but there is no input to that node at all")
+ value = inputs[to_input]
+ if not is_link(value):
+ raise NodeInputError(f"Node {to_node_id} says it needs input {to_input}, but that value is a constant")
+ from_node_id, from_socket = value
+ self.add_strong_link(from_node_id, from_socket, to_node_id)
+
+ def add_strong_link(self, from_node_id, from_socket, to_node_id):
+ if not self.is_cached(from_node_id):
+ self.add_node(from_node_id)
+ if to_node_id not in self.blocking[from_node_id]:
+ self.blocking[from_node_id][to_node_id] = {}
+ self.blockCount[to_node_id] += 1
+ self.blocking[from_node_id][to_node_id][from_socket] = True
+
+ def add_node(self, node_unique_id, include_lazy=False, subgraph_nodes=None):
+ node_ids = [node_unique_id]
+ links = []
+
+ while len(node_ids) > 0:
+ unique_id = node_ids.pop()
+ if unique_id in self.pendingNodes:
+ continue
+
+ self.pendingNodes[unique_id] = True
+ self.blockCount[unique_id] = 0
+ self.blocking[unique_id] = {}
+
+ inputs = self.dynprompt.get_node(unique_id)["inputs"]
+ for input_name in inputs:
+ value = inputs[input_name]
+ if is_link(value):
+ from_node_id, from_socket = value
+ if subgraph_nodes is not None and from_node_id not in subgraph_nodes:
+ continue
+ input_type, input_category, input_info = self.get_input_info(unique_id, input_name)
+ is_lazy = input_info is not None and "lazy" in input_info and input_info["lazy"]
+ if (include_lazy or not is_lazy) and not self.is_cached(from_node_id):
+ node_ids.append(from_node_id)
+ links.append((from_node_id, from_socket, unique_id))
+
+ for link in links:
+ self.add_strong_link(*link)
+
+ def is_cached(self, node_id):
+ return False
+
+ def get_ready_nodes(self):
+ return [node_id for node_id in self.pendingNodes if self.blockCount[node_id] == 0]
+
+ def pop_node(self, unique_id):
+ del self.pendingNodes[unique_id]
+ for blocked_node_id in self.blocking[unique_id]:
+ self.blockCount[blocked_node_id] -= 1
+ del self.blocking[unique_id]
+
+ def is_empty(self):
+ return len(self.pendingNodes) == 0
+
+class ExecutionList(TopologicalSort):
+ """
+ ExecutionList implements a topological dissolve of the graph. After a node is staged for execution,
+ it can still be returned to the graph after having further dependencies added.
+ """
+ def __init__(self, dynprompt, output_cache):
+ super().__init__(dynprompt)
+ self.output_cache = output_cache
+ self.staged_node_id = None
+
+ def is_cached(self, node_id):
+ return self.output_cache.get(node_id) is not None
+
+ def stage_node_execution(self):
+ assert self.staged_node_id is None
+ if self.is_empty():
+ return None, None, None
+ available = self.get_ready_nodes()
+ if len(available) == 0:
+ cycled_nodes = self.get_nodes_in_cycle()
+ # Because cycles composed entirely of static nodes are caught during initial validation,
+ # we will 'blame' the first node in the cycle that is not a static node.
+ blamed_node = cycled_nodes[0]
+ for node_id in cycled_nodes:
+ display_node_id = self.dynprompt.get_display_node_id(node_id)
+ if display_node_id != node_id:
+ blamed_node = display_node_id
+ break
+ ex = DependencyCycleError("Dependency cycle detected")
+ error_details = {
+ "node_id": blamed_node,
+ "exception_message": str(ex),
+ "exception_type": "graph.DependencyCycleError",
+ "traceback": [],
+ "current_inputs": []
+ }
+ return None, error_details, ex
+
+ self.staged_node_id = self.ux_friendly_pick_node(available)
+ return self.staged_node_id, None, None
+
+ def ux_friendly_pick_node(self, node_list):
+ # If an output node is available, do that first.
+ # Technically this has no effect on the overall length of execution, but it feels better as a user
+ # for a PreviewImage to display a result as soon as it can
+ # Some other heuristics could probably be used here to improve the UX further.
+ def is_output(node_id):
+ class_type = self.dynprompt.get_node(node_id)["class_type"]
+ class_def = nodes.NODE_CLASS_MAPPINGS[class_type]
+ if hasattr(class_def, 'OUTPUT_NODE') and class_def.OUTPUT_NODE == True:
+ return True
+ return False
+
+ for node_id in node_list:
+ if is_output(node_id):
+ return node_id
+
+ #This should handle the VAEDecode -> preview case
+ for node_id in node_list:
+ for blocked_node_id in self.blocking[node_id]:
+ if is_output(blocked_node_id):
+ return node_id
+
+ #This should handle the VAELoader -> VAEDecode -> preview case
+ for node_id in node_list:
+ for blocked_node_id in self.blocking[node_id]:
+ for blocked_node_id1 in self.blocking[blocked_node_id]:
+ if is_output(blocked_node_id1):
+ return node_id
+
+ #TODO: this function should be improved
+ return node_list[0]
+
+ def unstage_node_execution(self):
+ assert self.staged_node_id is not None
+ self.staged_node_id = None
+
+ def complete_node_execution(self):
+ node_id = self.staged_node_id
+ self.pop_node(node_id)
+ self.staged_node_id = None
+
+ def get_nodes_in_cycle(self):
+ # We'll dissolve the graph in reverse topological order to leave only the nodes in the cycle.
+ # We're skipping some of the performance optimizations from the original TopologicalSort to keep
+ # the code simple (and because having a cycle in the first place is a catastrophic error)
+ blocked_by = { node_id: {} for node_id in self.pendingNodes }
+ for from_node_id in self.blocking:
+ for to_node_id in self.blocking[from_node_id]:
+ if True in self.blocking[from_node_id][to_node_id].values():
+ blocked_by[to_node_id][from_node_id] = True
+ to_remove = [node_id for node_id in blocked_by if len(blocked_by[node_id]) == 0]
+ while len(to_remove) > 0:
+ for node_id in to_remove:
+ for to_node_id in blocked_by:
+ if node_id in blocked_by[to_node_id]:
+ del blocked_by[to_node_id][node_id]
+ del blocked_by[node_id]
+ to_remove = [node_id for node_id in blocked_by if len(blocked_by[node_id]) == 0]
+ return list(blocked_by.keys())
+
+class ExecutionBlocker:
+ """
+ Return this from a node and any users will be blocked with the given error message.
+ If the message is None, execution will be blocked silently instead.
+ Generally, you should avoid using this functionality unless absolutely necessary. Whenever it's
+ possible, a lazy input will be more efficient and have a better user experience.
+ This functionality is useful in two cases:
+ 1. You want to conditionally prevent an output node from executing. (Particularly a built-in node
+ like SaveImage. For your own output nodes, I would recommend just adding a BOOL input and using
+ lazy evaluation to let it conditionally disable itself.)
+ 2. You have a node with multiple possible outputs, some of which are invalid and should not be used.
+ (I would recommend not making nodes like this in the future -- instead, make multiple nodes with
+ different outputs. Unfortunately, there are several popular existing nodes using this pattern.)
+ """
+ def __init__(self, message):
+ self.message = message
+
diff --git a/comfy_execution/graph_utils.py b/comfy_execution/graph_utils.py
new file mode 100644
index 000000000..8595e942d
--- /dev/null
+++ b/comfy_execution/graph_utils.py
@@ -0,0 +1,139 @@
+def is_link(obj):
+ if not isinstance(obj, list):
+ return False
+ if len(obj) != 2:
+ return False
+ if not isinstance(obj[0], str):
+ return False
+ if not isinstance(obj[1], int) and not isinstance(obj[1], float):
+ return False
+ return True
+
+# The GraphBuilder is just a utility class that outputs graphs in the form expected by the ComfyUI back-end
+class GraphBuilder:
+ _default_prefix_root = ""
+ _default_prefix_call_index = 0
+ _default_prefix_graph_index = 0
+
+ def __init__(self, prefix = None):
+ if prefix is None:
+ self.prefix = GraphBuilder.alloc_prefix()
+ else:
+ self.prefix = prefix
+ self.nodes = {}
+ self.id_gen = 1
+
+ @classmethod
+ def set_default_prefix(cls, prefix_root, call_index, graph_index = 0):
+ cls._default_prefix_root = prefix_root
+ cls._default_prefix_call_index = call_index
+ cls._default_prefix_graph_index = graph_index
+
+ @classmethod
+ def alloc_prefix(cls, root=None, call_index=None, graph_index=None):
+ if root is None:
+ root = GraphBuilder._default_prefix_root
+ if call_index is None:
+ call_index = GraphBuilder._default_prefix_call_index
+ if graph_index is None:
+ graph_index = GraphBuilder._default_prefix_graph_index
+ result = f"{root}.{call_index}.{graph_index}."
+ GraphBuilder._default_prefix_graph_index += 1
+ return result
+
+ def node(self, class_type, id=None, **kwargs):
+ if id is None:
+ id = str(self.id_gen)
+ self.id_gen += 1
+ id = self.prefix + id
+ if id in self.nodes:
+ return self.nodes[id]
+
+ node = Node(id, class_type, kwargs)
+ self.nodes[id] = node
+ return node
+
+ def lookup_node(self, id):
+ id = self.prefix + id
+ return self.nodes.get(id)
+
+ def finalize(self):
+ output = {}
+ for node_id, node in self.nodes.items():
+ output[node_id] = node.serialize()
+ return output
+
+ def replace_node_output(self, node_id, index, new_value):
+ node_id = self.prefix + node_id
+ to_remove = []
+ for node in self.nodes.values():
+ for key, value in node.inputs.items():
+ if is_link(value) and value[0] == node_id and value[1] == index:
+ if new_value is None:
+ to_remove.append((node, key))
+ else:
+ node.inputs[key] = new_value
+ for node, key in to_remove:
+ del node.inputs[key]
+
+ def remove_node(self, id):
+ id = self.prefix + id
+ del self.nodes[id]
+
+class Node:
+ def __init__(self, id, class_type, inputs):
+ self.id = id
+ self.class_type = class_type
+ self.inputs = inputs
+ self.override_display_id = None
+
+ def out(self, index):
+ return [self.id, index]
+
+ def set_input(self, key, value):
+ if value is None:
+ if key in self.inputs:
+ del self.inputs[key]
+ else:
+ self.inputs[key] = value
+
+ def get_input(self, key):
+ return self.inputs.get(key)
+
+ def set_override_display_id(self, override_display_id):
+ self.override_display_id = override_display_id
+
+ def serialize(self):
+ serialized = {
+ "class_type": self.class_type,
+ "inputs": self.inputs
+ }
+ if self.override_display_id is not None:
+ serialized["override_display_id"] = self.override_display_id
+ return serialized
+
+def add_graph_prefix(graph, outputs, prefix):
+ # Change the node IDs and any internal links
+ new_graph = {}
+ for node_id, node_info in graph.items():
+ # Make sure the added nodes have unique IDs
+ new_node_id = prefix + node_id
+ new_node = { "class_type": node_info["class_type"], "inputs": {} }
+ for input_name, input_value in node_info.get("inputs", {}).items():
+ if is_link(input_value):
+ new_node["inputs"][input_name] = [prefix + input_value[0], input_value[1]]
+ else:
+ new_node["inputs"][input_name] = input_value
+ new_graph[new_node_id] = new_node
+
+ # Change the node IDs in the outputs
+ new_outputs = []
+ for n in range(len(outputs)):
+ output = outputs[n]
+ if is_link(output):
+ new_outputs.append([prefix + output[0], output[1]])
+ else:
+ new_outputs.append(output)
+
+ return new_graph, tuple(new_outputs)
+
diff --git a/comfy_extras/nodes_audio.py b/comfy_extras/nodes_audio.py
index 762b48279..e5cc4dffe 100644
--- a/comfy_extras/nodes_audio.py
+++ b/comfy_extras/nodes_audio.py
@@ -16,14 +16,15 @@ class EmptyLatentAudio:
@classmethod
def INPUT_TYPES(s):
- return {"required": {"seconds": ("FLOAT", {"default": 47.6, "min": 1.0, "max": 1000.0, "step": 0.1})}}
+ return {"required": {"seconds": ("FLOAT", {"default": 47.6, "min": 1.0, "max": 1000.0, "step": 0.1}),
+ "batch_size": ("INT", {"default": 1, "min": 1, "max": 4096, "tooltip": "The number of latent images in the batch."}),
+ }}
RETURN_TYPES = ("LATENT",)
FUNCTION = "generate"
CATEGORY = "latent/audio"
- def generate(self, seconds):
- batch_size = 1
+ def generate(self, seconds, batch_size):
length = round((seconds * 44100 / 2048) / 2) * 2
latent = torch.zeros([batch_size, 64, length], device=self.device)
return ({"samples":latent, "type": "audio"}, )
@@ -58,6 +59,9 @@ class VAEDecodeAudio:
def decode(self, vae, samples):
audio = vae.decode(samples["samples"]).movedim(-1, 1)
+ std = torch.std(audio, dim=[1,2], keepdim=True) * 5.0
+ std[std < 1.0] = 1.0
+ audio /= std
return ({"waveform": audio, "sample_rate": 44100}, )
@@ -183,17 +187,10 @@ class PreviewAudio(SaveAudio):
}
class LoadAudio:
- SUPPORTED_FORMATS = ('.wav', '.mp3', '.ogg', '.flac', '.aiff', '.aif')
-
@classmethod
def INPUT_TYPES(s):
input_dir = folder_paths.get_input_directory()
- files = [
- f for f in os.listdir(input_dir)
- if (os.path.isfile(os.path.join(input_dir, f))
- and f.endswith(LoadAudio.SUPPORTED_FORMATS)
- )
- ]
+ files = folder_paths.filter_files_content_types(os.listdir(input_dir), ["audio", "video"])
return {"required": {"audio": (sorted(files), {"audio_upload": True})}}
CATEGORY = "audio"
diff --git a/comfy_extras/nodes_controlnet.py b/comfy_extras/nodes_controlnet.py
index 0773c8a5b..2d20e1fed 100644
--- a/comfy_extras/nodes_controlnet.py
+++ b/comfy_extras/nodes_controlnet.py
@@ -1,4 +1,6 @@
from comfy.cldm.control_types import UNION_CONTROLNET_TYPES
+import nodes
+import comfy.utils
class SetUnionControlNetType:
@classmethod
@@ -22,6 +24,37 @@ class SetUnionControlNetType:
return (control_net,)
+class ControlNetInpaintingAliMamaApply(nodes.ControlNetApplyAdvanced):
+ @classmethod
+ def INPUT_TYPES(s):
+ return {"required": {"positive": ("CONDITIONING", ),
+ "negative": ("CONDITIONING", ),
+ "control_net": ("CONTROL_NET", ),
+ "vae": ("VAE", ),
+ "image": ("IMAGE", ),
+ "mask": ("MASK", ),
+ "strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
+ "start_percent": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.001}),
+ "end_percent": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.001})
+ }}
+
+ FUNCTION = "apply_inpaint_controlnet"
+
+ CATEGORY = "conditioning/controlnet"
+
+ def apply_inpaint_controlnet(self, positive, negative, control_net, vae, image, mask, strength, start_percent, end_percent):
+ extra_concat = []
+ if control_net.concat_mask:
+ mask = 1.0 - mask.reshape((-1, 1, mask.shape[-2], mask.shape[-1]))
+ mask_apply = comfy.utils.common_upscale(mask, image.shape[2], image.shape[1], "bilinear", "center").round()
+ image = image * mask_apply.movedim(1, -1).repeat(1, 1, 1, image.shape[3])
+ extra_concat = [mask]
+
+ return self.apply_controlnet(positive, negative, control_net, image, strength, start_percent, end_percent, vae=vae, extra_concat=extra_concat)
+
+
+
NODE_CLASS_MAPPINGS = {
"SetUnionControlNetType": SetUnionControlNetType,
+ "ControlNetInpaintingAliMamaApply": ControlNetInpaintingAliMamaApply,
}
diff --git a/comfy_extras/nodes_custom_sampler.py b/comfy_extras/nodes_custom_sampler.py
index 219975e27..c7ff9a4d8 100644
--- a/comfy_extras/nodes_custom_sampler.py
+++ b/comfy_extras/nodes_custom_sampler.py
@@ -90,6 +90,27 @@ class PolyexponentialScheduler:
sigmas = k_diffusion_sampling.get_sigmas_polyexponential(n=steps, sigma_min=sigma_min, sigma_max=sigma_max, rho=rho)
return (sigmas, )
+class LaplaceScheduler:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {"required":
+ {"steps": ("INT", {"default": 20, "min": 1, "max": 10000}),
+ "sigma_max": ("FLOAT", {"default": 14.614642, "min": 0.0, "max": 5000.0, "step":0.01, "round": False}),
+ "sigma_min": ("FLOAT", {"default": 0.0291675, "min": 0.0, "max": 5000.0, "step":0.01, "round": False}),
+ "mu": ("FLOAT", {"default": 0.0, "min": -10.0, "max": 10.0, "step":0.1, "round": False}),
+ "beta": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 10.0, "step":0.1, "round": False}),
+ }
+ }
+ RETURN_TYPES = ("SIGMAS",)
+ CATEGORY = "sampling/custom_sampling/schedulers"
+
+ FUNCTION = "get_sigmas"
+
+ def get_sigmas(self, steps, sigma_max, sigma_min, mu, beta):
+ sigmas = k_diffusion_sampling.get_sigmas_laplace(n=steps, sigma_min=sigma_min, sigma_max=sigma_max, mu=mu, beta=beta)
+ return (sigmas, )
+
+
class SDTurboScheduler:
@classmethod
def INPUT_TYPES(s):
@@ -673,6 +694,7 @@ NODE_CLASS_MAPPINGS = {
"KarrasScheduler": KarrasScheduler,
"ExponentialScheduler": ExponentialScheduler,
"PolyexponentialScheduler": PolyexponentialScheduler,
+ "LaplaceScheduler": LaplaceScheduler,
"VPScheduler": VPScheduler,
"BetaSamplingScheduler": BetaSamplingScheduler,
"SDTurboScheduler": SDTurboScheduler,
diff --git a/comfy_extras/nodes_hypernetwork.py b/comfy_extras/nodes_hypernetwork.py
index cafafa6ab..665632292 100644
--- a/comfy_extras/nodes_hypernetwork.py
+++ b/comfy_extras/nodes_hypernetwork.py
@@ -107,7 +107,7 @@ class HypernetworkLoader:
CATEGORY = "loaders"
def load_hypernetwork(self, model, hypernetwork_name, strength):
- hypernetwork_path = folder_paths.get_full_path("hypernetworks", hypernetwork_name)
+ hypernetwork_path = folder_paths.get_full_path_or_raise("hypernetworks", hypernetwork_name)
model_hypernetwork = model.clone()
patch = load_hypernetwork_patch(hypernetwork_path, strength)
if patch is not None:
diff --git a/comfy_extras/nodes_lora_extract.py b/comfy_extras/nodes_lora_extract.py
new file mode 100644
index 000000000..3c2f179d3
--- /dev/null
+++ b/comfy_extras/nodes_lora_extract.py
@@ -0,0 +1,115 @@
+import torch
+import comfy.model_management
+import comfy.utils
+import folder_paths
+import os
+import logging
+from enum import Enum
+
+CLAMP_QUANTILE = 0.99
+
+def extract_lora(diff, rank):
+ conv2d = (len(diff.shape) == 4)
+ kernel_size = None if not conv2d else diff.size()[2:4]
+ conv2d_3x3 = conv2d and kernel_size != (1, 1)
+ out_dim, in_dim = diff.size()[0:2]
+ rank = min(rank, in_dim, out_dim)
+
+ if conv2d:
+ if conv2d_3x3:
+ diff = diff.flatten(start_dim=1)
+ else:
+ diff = diff.squeeze()
+
+
+ U, S, Vh = torch.linalg.svd(diff.float())
+ U = U[:, :rank]
+ S = S[:rank]
+ U = U @ torch.diag(S)
+ Vh = Vh[:rank, :]
+
+ dist = torch.cat([U.flatten(), Vh.flatten()])
+ hi_val = torch.quantile(dist, CLAMP_QUANTILE)
+ low_val = -hi_val
+
+ U = U.clamp(low_val, hi_val)
+ Vh = Vh.clamp(low_val, hi_val)
+ if conv2d:
+ U = U.reshape(out_dim, rank, 1, 1)
+ Vh = Vh.reshape(rank, in_dim, kernel_size[0], kernel_size[1])
+ return (U, Vh)
+
+class LORAType(Enum):
+ STANDARD = 0
+ FULL_DIFF = 1
+
+LORA_TYPES = {"standard": LORAType.STANDARD,
+ "full_diff": LORAType.FULL_DIFF}
+
+def calc_lora_model(model_diff, rank, prefix_model, prefix_lora, output_sd, lora_type, bias_diff=False):
+ comfy.model_management.load_models_gpu([model_diff], force_patch_weights=True)
+ sd = model_diff.model_state_dict(filter_prefix=prefix_model)
+
+ for k in sd:
+ if k.endswith(".weight"):
+ weight_diff = sd[k]
+ if lora_type == LORAType.STANDARD:
+ if weight_diff.ndim < 2:
+ if bias_diff:
+ output_sd["{}{}.diff".format(prefix_lora, k[len(prefix_model):-7])] = weight_diff.contiguous().half().cpu()
+ continue
+ try:
+ out = extract_lora(weight_diff, rank)
+ output_sd["{}{}.lora_up.weight".format(prefix_lora, k[len(prefix_model):-7])] = out[0].contiguous().half().cpu()
+ output_sd["{}{}.lora_down.weight".format(prefix_lora, k[len(prefix_model):-7])] = out[1].contiguous().half().cpu()
+ except:
+ logging.warning("Could not generate lora weights for key {}, is the weight difference a zero?".format(k))
+ elif lora_type == LORAType.FULL_DIFF:
+ output_sd["{}{}.diff".format(prefix_lora, k[len(prefix_model):-7])] = weight_diff.contiguous().half().cpu()
+
+ elif bias_diff and k.endswith(".bias"):
+ output_sd["{}{}.diff_b".format(prefix_lora, k[len(prefix_model):-5])] = sd[k].contiguous().half().cpu()
+ return output_sd
+
+class LoraSave:
+ def __init__(self):
+ self.output_dir = folder_paths.get_output_directory()
+
+ @classmethod
+ def INPUT_TYPES(s):
+ return {"required": {"filename_prefix": ("STRING", {"default": "loras/ComfyUI_extracted_lora"}),
+ "rank": ("INT", {"default": 8, "min": 1, "max": 4096, "step": 1}),
+ "lora_type": (tuple(LORA_TYPES.keys()),),
+ "bias_diff": ("BOOLEAN", {"default": True}),
+ },
+ "optional": {"model_diff": ("MODEL",),
+ "text_encoder_diff": ("CLIP",)},
+ }
+ RETURN_TYPES = ()
+ FUNCTION = "save"
+ OUTPUT_NODE = True
+
+ CATEGORY = "_for_testing"
+
+ def save(self, filename_prefix, rank, lora_type, bias_diff, model_diff=None, text_encoder_diff=None):
+ if model_diff is None and text_encoder_diff is None:
+ return {}
+
+ lora_type = LORA_TYPES.get(lora_type)
+ full_output_folder, filename, counter, subfolder, filename_prefix = folder_paths.get_save_image_path(filename_prefix, self.output_dir)
+
+ output_sd = {}
+ if model_diff is not None:
+ output_sd = calc_lora_model(model_diff, rank, "diffusion_model.", "diffusion_model.", output_sd, lora_type, bias_diff=bias_diff)
+ if text_encoder_diff is not None:
+ output_sd = calc_lora_model(text_encoder_diff.patcher, rank, "", "text_encoders.", output_sd, lora_type, bias_diff=bias_diff)
+
+ output_checkpoint = f"{filename}_{counter:05}_.safetensors"
+ output_checkpoint = os.path.join(full_output_folder, output_checkpoint)
+
+ comfy.utils.save_torch_file(output_sd, output_checkpoint, metadata=None)
+ return {}
+
+NODE_CLASS_MAPPINGS = {
+ "LoraSave": LoraSave
+}
diff --git a/comfy_extras/nodes_model_merging.py b/comfy_extras/nodes_model_merging.py
index 136f9a984..ccf601158 100644
--- a/comfy_extras/nodes_model_merging.py
+++ b/comfy_extras/nodes_model_merging.py
@@ -333,6 +333,25 @@ class VAESave:
comfy.utils.save_torch_file(vae.get_sd(), output_checkpoint, metadata=metadata)
return {}
+class ModelSave:
+ def __init__(self):
+ self.output_dir = folder_paths.get_output_directory()
+
+ @classmethod
+ def INPUT_TYPES(s):
+ return {"required": { "model": ("MODEL",),
+ "filename_prefix": ("STRING", {"default": "diffusion_models/ComfyUI"}),},
+ "hidden": {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO"},}
+ RETURN_TYPES = ()
+ FUNCTION = "save"
+ OUTPUT_NODE = True
+
+ CATEGORY = "advanced/model_merging"
+
+ def save(self, model, filename_prefix, prompt=None, extra_pnginfo=None):
+ save_checkpoint(model, filename_prefix=filename_prefix, output_dir=self.output_dir, prompt=prompt, extra_pnginfo=extra_pnginfo)
+ return {}
+
NODE_CLASS_MAPPINGS = {
"ModelMergeSimple": ModelMergeSimple,
"ModelMergeBlocks": ModelMergeBlocks,
@@ -344,4 +363,9 @@ NODE_CLASS_MAPPINGS = {
"CLIPMergeAdd": CLIPAdd,
"CLIPSave": CLIPSave,
"VAESave": VAESave,
+ "ModelSave": ModelSave,
+}
+
+NODE_DISPLAY_NAME_MAPPINGS = {
+ "CheckpointSave": "Save Checkpoint",
}
diff --git a/comfy_extras/nodes_perpneg.py b/comfy_extras/nodes_perpneg.py
index 546276aa1..762c40220 100644
--- a/comfy_extras/nodes_perpneg.py
+++ b/comfy_extras/nodes_perpneg.py
@@ -26,6 +26,7 @@ class PerpNeg:
FUNCTION = "patch"
CATEGORY = "_for_testing"
+ DEPRECATED = True
def patch(self, model, empty_conditioning, neg_scale):
m = model.clone()
diff --git a/comfy_extras/nodes_photomaker.py b/comfy_extras/nodes_photomaker.py
index 29d127d74..95d24dd22 100644
--- a/comfy_extras/nodes_photomaker.py
+++ b/comfy_extras/nodes_photomaker.py
@@ -126,7 +126,7 @@ class PhotoMakerLoader:
CATEGORY = "_for_testing/photomaker"
def load_photomaker_model(self, photomaker_model_name):
- photomaker_model_path = folder_paths.get_full_path("photomaker", photomaker_model_name)
+ photomaker_model_path = folder_paths.get_full_path_or_raise("photomaker", photomaker_model_name)
photomaker_model = PhotoMakerIDEncoder()
data = comfy.utils.load_torch_file(photomaker_model_path, safe_load=True)
if "id_encoder" in data:
diff --git a/comfy_extras/nodes_sd3.py b/comfy_extras/nodes_sd3.py
index 046096cba..ddf538deb 100644
--- a/comfy_extras/nodes_sd3.py
+++ b/comfy_extras/nodes_sd3.py
@@ -15,9 +15,9 @@ class TripleCLIPLoader:
CATEGORY = "advanced/loaders"
def load_clip(self, clip_name1, clip_name2, clip_name3):
- clip_path1 = folder_paths.get_full_path("clip", clip_name1)
- clip_path2 = folder_paths.get_full_path("clip", clip_name2)
- clip_path3 = folder_paths.get_full_path("clip", clip_name3)
+ clip_path1 = folder_paths.get_full_path_or_raise("clip", clip_name1)
+ clip_path2 = folder_paths.get_full_path_or_raise("clip", clip_name2)
+ clip_path3 = folder_paths.get_full_path_or_raise("clip", clip_name3)
clip = comfy.sd.load_clip(ckpt_paths=[clip_path1, clip_path2, clip_path3], embedding_directory=folder_paths.get_folder_paths("embeddings"))
return (clip,)
@@ -36,7 +36,7 @@ class EmptySD3LatentImage:
CATEGORY = "latent/sd3"
def generate(self, width, height, batch_size=1):
- latent = torch.ones([batch_size, 16, height // 8, width // 8], device=self.device) * 0.0609
+ latent = torch.zeros([batch_size, 16, height // 8, width // 8], device=self.device)
return ({"samples":latent}, )
class CLIPTextEncodeSD3:
@@ -93,6 +93,7 @@ class ControlNetApplySD3(nodes.ControlNetApplyAdvanced):
"end_percent": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.001})
}}
CATEGORY = "conditioning/controlnet"
+ DEPRECATED = True
NODE_CLASS_MAPPINGS = {
"TripleCLIPLoader": TripleCLIPLoader,
@@ -103,5 +104,5 @@ NODE_CLASS_MAPPINGS = {
NODE_DISPLAY_NAME_MAPPINGS = {
# Sampling
- "ControlNetApplySD3": "ControlNetApply SD3 and HunyuanDiT",
+ "ControlNetApplySD3": "Apply Controlnet with VAE",
}
diff --git a/comfy_extras/nodes_torch_compile.py b/comfy_extras/nodes_torch_compile.py
new file mode 100644
index 000000000..1d914fa93
--- /dev/null
+++ b/comfy_extras/nodes_torch_compile.py
@@ -0,0 +1,21 @@
+import torch
+
+class TorchCompileModel:
+ @classmethod
+ def INPUT_TYPES(s):
+ return {"required": { "model": ("MODEL",),
+ }}
+ RETURN_TYPES = ("MODEL",)
+ FUNCTION = "patch"
+
+ CATEGORY = "_for_testing"
+ EXPERIMENTAL = True
+
+ def patch(self, model):
+ m = model.clone()
+ m.add_object_patch("diffusion_model", torch.compile(model=m.get_model_object("diffusion_model")))
+ return (m, )
+
+NODE_CLASS_MAPPINGS = {
+ "TorchCompileModel": TorchCompileModel,
+}
diff --git a/comfy_extras/nodes_upscale_model.py b/comfy_extras/nodes_upscale_model.py
index bca79ef2e..6ba3e404f 100644
--- a/comfy_extras/nodes_upscale_model.py
+++ b/comfy_extras/nodes_upscale_model.py
@@ -25,7 +25,7 @@ class UpscaleModelLoader:
CATEGORY = "loaders"
def load_model(self, model_name):
- model_path = folder_paths.get_full_path("upscale_models", model_name)
+ model_path = folder_paths.get_full_path_or_raise("upscale_models", model_name)
sd = comfy.utils.load_torch_file(model_path, safe_load=True)
if "module.layers.0.residual_group.blocks.0.norm1.weight" in sd:
sd = comfy.utils.state_dict_prefix_replace(sd, {"module.":""})
diff --git a/comfy_extras/nodes_video_model.py b/comfy_extras/nodes_video_model.py
index 1a0189ed4..7f2146d1e 100644
--- a/comfy_extras/nodes_video_model.py
+++ b/comfy_extras/nodes_video_model.py
@@ -17,7 +17,7 @@ class ImageOnlyCheckpointLoader:
CATEGORY = "loaders/video_models"
def load_checkpoint(self, ckpt_name, output_vae=True, output_clip=True):
- ckpt_path = folder_paths.get_full_path("checkpoints", ckpt_name)
+ ckpt_path = folder_paths.get_full_path_or_raise("checkpoints", ckpt_name)
out = comfy.sd.load_checkpoint_guess_config(ckpt_path, output_vae=True, output_clip=False, output_clipvision=True, embedding_directory=folder_paths.get_folder_paths("embeddings"))
return (out[0], out[3], out[2])
diff --git a/custom_nodes/example_node.py.example b/custom_nodes/example_node.py.example
index 72ca3688c..29ab2aa72 100644
--- a/custom_nodes/example_node.py.example
+++ b/custom_nodes/example_node.py.example
@@ -4,14 +4,14 @@ class Example:
Class methods
-------------
- INPUT_TYPES (dict):
+ INPUT_TYPES (dict):
Tell the main program input parameters of nodes.
IS_CHANGED:
optional method to control when the node is re executed.
Attributes
----------
- RETURN_TYPES (`tuple`):
+ RETURN_TYPES (`tuple`):
The type of each element in the output tuple.
RETURN_NAMES (`tuple`):
Optional: The name of each output in the output tuple.
@@ -23,13 +23,19 @@ class Example:
Assumed to be False if not present.
CATEGORY (`str`):
The category the node should appear in the UI.
+ DEPRECATED (`bool`):
+ Indicates whether the node is deprecated. Deprecated nodes are hidden by default in the UI, but remain
+ functional in existing workflows that use them.
+ EXPERIMENTAL (`bool`):
+ Indicates whether the node is experimental. 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.
execute(s) -> tuple || None:
The entry point method. The name of this method must be the same as the value of property `FUNCTION`.
For example, if `FUNCTION = "execute"` then this method's name must be `execute`, if `FUNCTION = "foo"` then it must be `foo`.
"""
def __init__(self):
pass
-
+
@classmethod
def INPUT_TYPES(s):
"""
@@ -54,7 +60,8 @@ class Example:
"min": 0, #Minimum value
"max": 4096, #Maximum value
"step": 64, #Slider's step
- "display": "number" # Cosmetic only: display as "number" or "slider"
+ "display": "number", # Cosmetic only: display as "number" or "slider"
+ "lazy": True # Will only be evaluated if check_lazy_status requires it
}),
"float_field": ("FLOAT", {
"default": 1.0,
@@ -62,11 +69,14 @@ class Example:
"max": 10.0,
"step": 0.01,
"round": 0.001, #The value representing the precision to round to, will be set to the step value by default. Can be set to False to disable rounding.
- "display": "number"}),
+ "display": "number",
+ "lazy": True
+ }),
"print_to_screen": (["enable", "disable"],),
"string_field": ("STRING", {
"multiline": False, #True if you want the field to look like the one on the ClipTextEncode node
- "default": "Hello World!"
+ "default": "Hello World!",
+ "lazy": True
}),
},
}
@@ -80,6 +90,23 @@ class Example:
CATEGORY = "Example"
+ def check_lazy_status(self, image, string_field, int_field, float_field, print_to_screen):
+ """
+ Return a list of input names that need to be evaluated.
+
+ This function will be called if there are any lazy inputs which have not yet been
+ evaluated. As long as you return at least one field which has not yet been evaluated
+ (and more exist), this function will be called again once the value of the requested
+ field is available.
+
+ Any evaluated inputs will be passed as arguments to this function. Any unevaluated
+ inputs will have the value None.
+ """
+ if print_to_screen == "enable":
+ return ["int_field", "float_field", "string_field"]
+ else:
+ return []
+
def test(self, image, string_field, int_field, float_field, print_to_screen):
if print_to_screen == "enable":
print(f"""Your input contains:
diff --git a/execution.py b/execution.py
index d207e1b9e..6c386341b 100644
--- a/execution.py
+++ b/execution.py
@@ -5,6 +5,7 @@ import threading
import heapq
import time
import traceback
+from enum import Enum
import inspect
from typing import List, Literal, NamedTuple, Optional
@@ -12,102 +13,225 @@ import torch
import nodes
import comfy.model_management
+from comfy_execution.graph import get_input_info, ExecutionList, DynamicPrompt, ExecutionBlocker
+from comfy_execution.graph_utils import is_link, GraphBuilder
+from comfy_execution.caching import HierarchicalCache, LRUCache, CacheKeySetInputSignature, CacheKeySetID
+from comfy.cli_args import args
-def get_input_data(inputs, class_def, unique_id, outputs={}, prompt={}, extra_data={}):
+class ExecutionResult(Enum):
+ SUCCESS = 0
+ FAILURE = 1
+ PENDING = 2
+
+class DuplicateNodeError(Exception):
+ pass
+
+class IsChangedCache:
+ def __init__(self, dynprompt, outputs_cache):
+ self.dynprompt = dynprompt
+ self.outputs_cache = outputs_cache
+ self.is_changed = {}
+
+ def get(self, node_id):
+ if node_id in self.is_changed:
+ return self.is_changed[node_id]
+
+ node = self.dynprompt.get_node(node_id)
+ class_type = node["class_type"]
+ class_def = nodes.NODE_CLASS_MAPPINGS[class_type]
+ if not hasattr(class_def, "IS_CHANGED"):
+ self.is_changed[node_id] = False
+ return self.is_changed[node_id]
+
+ if "is_changed" in node:
+ self.is_changed[node_id] = node["is_changed"]
+ return self.is_changed[node_id]
+
+ # Intentionally do not use cached outputs here. We only want constants in IS_CHANGED
+ input_data_all, _ = get_input_data(node["inputs"], class_def, node_id, None)
+ try:
+ is_changed = _map_node_over_list(class_def, input_data_all, "IS_CHANGED")
+ node["is_changed"] = [None if isinstance(x, ExecutionBlocker) else x for x in is_changed]
+ except Exception as e:
+ logging.warning("WARNING: {}".format(e))
+ node["is_changed"] = float("NaN")
+ finally:
+ self.is_changed[node_id] = node["is_changed"]
+ return self.is_changed[node_id]
+
+class CacheSet:
+ def __init__(self, lru_size=None):
+ if lru_size is None or lru_size == 0:
+ self.init_classic_cache()
+ else:
+ self.init_lru_cache(lru_size)
+ self.all = [self.outputs, self.ui, self.objects]
+
+ # Useful for those with ample RAM/VRAM -- allows experimenting without
+ # blowing away the cache every time
+ def init_lru_cache(self, cache_size):
+ self.outputs = LRUCache(CacheKeySetInputSignature, max_size=cache_size)
+ self.ui = LRUCache(CacheKeySetInputSignature, max_size=cache_size)
+ self.objects = HierarchicalCache(CacheKeySetID)
+
+ # Performs like the old cache -- dump data ASAP
+ def init_classic_cache(self):
+ self.outputs = HierarchicalCache(CacheKeySetInputSignature)
+ self.ui = HierarchicalCache(CacheKeySetInputSignature)
+ self.objects = HierarchicalCache(CacheKeySetID)
+
+ def recursive_debug_dump(self):
+ result = {
+ "outputs": self.outputs.recursive_debug_dump(),
+ "ui": self.ui.recursive_debug_dump(),
+ }
+ return result
+
+def get_input_data(inputs, class_def, unique_id, outputs=None, dynprompt=None, extra_data={}):
valid_inputs = class_def.INPUT_TYPES()
input_data_all = {}
+ missing_keys = {}
for x in inputs:
input_data = inputs[x]
- if isinstance(input_data, list):
+ input_type, input_category, input_info = get_input_info(class_def, x)
+ def mark_missing():
+ missing_keys[x] = True
+ input_data_all[x] = (None,)
+ if is_link(input_data) and (not input_info or not input_info.get("rawLink", False)):
input_unique_id = input_data[0]
output_index = input_data[1]
- if input_unique_id not in outputs:
- input_data_all[x] = (None,)
+ if outputs is None:
+ mark_missing()
+ continue # This might be a lazily-evaluated input
+ cached_output = outputs.get(input_unique_id)
+ if cached_output is None:
+ mark_missing()
continue
- obj = outputs[input_unique_id][output_index]
+ if output_index >= len(cached_output):
+ mark_missing()
+ continue
+ obj = cached_output[output_index]
input_data_all[x] = obj
- else:
- if ("required" in valid_inputs and x in valid_inputs["required"]) or ("optional" in valid_inputs and x in valid_inputs["optional"]):
- input_data_all[x] = [input_data]
+ elif input_category is not None:
+ input_data_all[x] = [input_data]
if "hidden" in valid_inputs:
h = valid_inputs["hidden"]
for x in h:
if h[x] == "PROMPT":
- input_data_all[x] = [prompt]
+ input_data_all[x] = [dynprompt.get_original_prompt() if dynprompt is not None else {}]
+ if h[x] == "DYNPROMPT":
+ input_data_all[x] = [dynprompt]
if h[x] == "EXTRA_PNGINFO":
input_data_all[x] = [extra_data.get('extra_pnginfo', None)]
if h[x] == "UNIQUE_ID":
input_data_all[x] = [unique_id]
- return input_data_all
+ return input_data_all, missing_keys
-def map_node_over_list(obj, input_data_all, func, allow_interrupt=False):
+map_node_over_list = None #Don't hook this please
+
+def _map_node_over_list(obj, input_data_all, func, allow_interrupt=False, execution_block_cb=None, pre_execute_cb=None):
# check if node wants the lists
- input_is_list = False
- if hasattr(obj, "INPUT_IS_LIST"):
- input_is_list = obj.INPUT_IS_LIST
+ input_is_list = getattr(obj, "INPUT_IS_LIST", False)
if len(input_data_all) == 0:
max_len_input = 0
else:
- max_len_input = max([len(x) for x in input_data_all.values()])
+ max_len_input = max(len(x) for x in input_data_all.values())
# get a slice of inputs, repeat last input when list isn't long enough
def slice_dict(d, i):
- d_new = dict()
- for k,v in d.items():
- d_new[k] = v[i if len(v) > i else -1]
- return d_new
+ return {k: v[i if len(v) > i else -1] for k, v in d.items()}
results = []
+ def process_inputs(inputs, index=None):
+ if allow_interrupt:
+ nodes.before_node_execution()
+ execution_block = None
+ for k, v in inputs.items():
+ if isinstance(v, ExecutionBlocker):
+ execution_block = execution_block_cb(v) if execution_block_cb else v
+ break
+ if execution_block is None:
+ if pre_execute_cb is not None and index is not None:
+ pre_execute_cb(index)
+ results.append(getattr(obj, func)(**inputs))
+ else:
+ results.append(execution_block)
+
if input_is_list:
- if allow_interrupt:
- nodes.before_node_execution()
- results.append(getattr(obj, func)(**input_data_all))
+ process_inputs(input_data_all, 0)
elif max_len_input == 0:
- if allow_interrupt:
- nodes.before_node_execution()
- results.append(getattr(obj, func)())
- else:
+ process_inputs({})
+ else:
for i in range(max_len_input):
- if allow_interrupt:
- nodes.before_node_execution()
- results.append(getattr(obj, func)(**slice_dict(input_data_all, i)))
+ input_dict = slice_dict(input_data_all, i)
+ process_inputs(input_dict, i)
return results
-def get_output_data(obj, input_data_all):
+def merge_result_data(results, obj):
+ # check which outputs need concatenating
+ output = []
+ output_is_list = [False] * len(results[0])
+ if hasattr(obj, "OUTPUT_IS_LIST"):
+ output_is_list = obj.OUTPUT_IS_LIST
+
+ # merge node execution results
+ for i, is_list in zip(range(len(results[0])), output_is_list):
+ if is_list:
+ value = []
+ for o in results:
+ if isinstance(o[i], ExecutionBlocker):
+ value.append(o[i])
+ else:
+ value.extend(o[i])
+ output.append(value)
+ else:
+ output.append([o[i] for o in results])
+ return output
+
+def get_output_data(obj, input_data_all, execution_block_cb=None, pre_execute_cb=None):
results = []
uis = []
- return_values = map_node_over_list(obj, input_data_all, obj.FUNCTION, allow_interrupt=True)
-
- for r in return_values:
+ subgraph_results = []
+ return_values = _map_node_over_list(obj, input_data_all, obj.FUNCTION, allow_interrupt=True, execution_block_cb=execution_block_cb, pre_execute_cb=pre_execute_cb)
+ has_subgraph = False
+ for i in range(len(return_values)):
+ r = return_values[i]
if isinstance(r, dict):
if 'ui' in r:
uis.append(r['ui'])
- if 'result' in r:
- results.append(r['result'])
+ if 'expand' in r:
+ # Perform an expansion, but do not append results
+ has_subgraph = True
+ new_graph = r['expand']
+ result = r.get("result", None)
+ if isinstance(result, ExecutionBlocker):
+ result = tuple([result] * len(obj.RETURN_TYPES))
+ subgraph_results.append((new_graph, result))
+ elif 'result' in r:
+ result = r.get("result", None)
+ if isinstance(result, ExecutionBlocker):
+ result = tuple([result] * len(obj.RETURN_TYPES))
+ results.append(result)
+ subgraph_results.append((None, result))
else:
+ if isinstance(r, ExecutionBlocker):
+ r = tuple([r] * len(obj.RETURN_TYPES))
results.append(r)
+ subgraph_results.append((None, r))
- output = []
- if len(results) > 0:
- # check which outputs need concatenating
- output_is_list = [False] * len(results[0])
- if hasattr(obj, "OUTPUT_IS_LIST"):
- output_is_list = obj.OUTPUT_IS_LIST
-
- # merge node execution results
- for i, is_list in zip(range(len(results[0])), output_is_list):
- if is_list:
- output.append([x for o in results for x in o[i]])
- else:
- output.append([o[i] for o in results])
-
+ if has_subgraph:
+ output = subgraph_results
+ elif len(results) > 0:
+ output = merge_result_data(results, obj)
+ else:
+ output = []
ui = dict()
if len(uis) > 0:
ui = {k: [y for x in uis for y in x[k]] for k in uis[0].keys()}
- return output, ui
+ return output, ui, has_subgraph
def format_value(x):
if x is None:
@@ -117,53 +241,145 @@ def format_value(x):
else:
return str(x)
-def recursive_execute(server, prompt, outputs, current_item, extra_data, executed, prompt_id, outputs_ui, object_storage):
+def execute(server, dynprompt, caches, current_item, extra_data, executed, prompt_id, execution_list, pending_subgraph_results):
unique_id = current_item
- inputs = prompt[unique_id]['inputs']
- class_type = prompt[unique_id]['class_type']
+ real_node_id = dynprompt.get_real_node_id(unique_id)
+ display_node_id = dynprompt.get_display_node_id(unique_id)
+ parent_node_id = dynprompt.get_parent_node_id(unique_id)
+ inputs = dynprompt.get_node(unique_id)['inputs']
+ class_type = dynprompt.get_node(unique_id)['class_type']
class_def = nodes.NODE_CLASS_MAPPINGS[class_type]
- if unique_id in outputs:
- return (True, None, None)
-
- for x in inputs:
- input_data = inputs[x]
-
- if isinstance(input_data, list):
- input_unique_id = input_data[0]
- output_index = input_data[1]
- if input_unique_id not in outputs:
- result = recursive_execute(server, prompt, outputs, input_unique_id, extra_data, executed, prompt_id, outputs_ui, object_storage)
- if result[0] is not True:
- # Another node failed further upstream
- return result
+ if caches.outputs.get(unique_id) is not None:
+ if server.client_id is not None:
+ cached_output = caches.ui.get(unique_id) or {}
+ server.send_sync("executed", { "node": unique_id, "display_node": display_node_id, "output": cached_output.get("output",None), "prompt_id": prompt_id }, server.client_id)
+ return (ExecutionResult.SUCCESS, None, None)
input_data_all = None
try:
- input_data_all = get_input_data(inputs, class_def, unique_id, outputs, prompt, extra_data)
- if server.client_id is not None:
- server.last_node_id = unique_id
- server.send_sync("executing", { "node": unique_id, "prompt_id": prompt_id }, server.client_id)
+ if unique_id in pending_subgraph_results:
+ cached_results = pending_subgraph_results[unique_id]
+ resolved_outputs = []
+ for is_subgraph, result in cached_results:
+ if not is_subgraph:
+ resolved_outputs.append(result)
+ else:
+ resolved_output = []
+ for r in result:
+ if is_link(r):
+ source_node, source_output = r[0], r[1]
+ node_output = caches.outputs.get(source_node)[source_output]
+ for o in node_output:
+ resolved_output.append(o)
- obj = object_storage.get((unique_id, class_type), None)
- if obj is None:
- obj = class_def()
- object_storage[(unique_id, class_type)] = obj
-
- output_data, output_ui = get_output_data(obj, input_data_all)
- outputs[unique_id] = output_data
- if len(output_ui) > 0:
- outputs_ui[unique_id] = output_ui
+ else:
+ resolved_output.append(r)
+ resolved_outputs.append(tuple(resolved_output))
+ output_data = merge_result_data(resolved_outputs, class_def)
+ output_ui = []
+ has_subgraph = False
+ else:
+ input_data_all, missing_keys = get_input_data(inputs, class_def, unique_id, caches.outputs, dynprompt, extra_data)
if server.client_id is not None:
- server.send_sync("executed", { "node": unique_id, "output": output_ui, "prompt_id": prompt_id }, server.client_id)
+ server.last_node_id = display_node_id
+ server.send_sync("executing", { "node": unique_id, "display_node": display_node_id, "prompt_id": prompt_id }, server.client_id)
+
+ obj = caches.objects.get(unique_id)
+ if obj is None:
+ obj = class_def()
+ caches.objects.set(unique_id, obj)
+
+ if hasattr(obj, "check_lazy_status"):
+ required_inputs = _map_node_over_list(obj, input_data_all, "check_lazy_status", allow_interrupt=True)
+ required_inputs = set(sum([r for r in required_inputs if isinstance(r,list)], []))
+ required_inputs = [x for x in required_inputs if isinstance(x,str) and (
+ x not in input_data_all or x in missing_keys
+ )]
+ if len(required_inputs) > 0:
+ for i in required_inputs:
+ execution_list.make_input_strong_link(unique_id, i)
+ return (ExecutionResult.PENDING, None, None)
+
+ def execution_block_cb(block):
+ if block.message is not None:
+ mes = {
+ "prompt_id": prompt_id,
+ "node_id": unique_id,
+ "node_type": class_type,
+ "executed": list(executed),
+
+ "exception_message": f"Execution Blocked: {block.message}",
+ "exception_type": "ExecutionBlocked",
+ "traceback": [],
+ "current_inputs": [],
+ "current_outputs": [],
+ }
+ server.send_sync("execution_error", mes, server.client_id)
+ return ExecutionBlocker(None)
+ else:
+ return block
+ def pre_execute_cb(call_index):
+ GraphBuilder.set_default_prefix(unique_id, call_index, 0)
+ output_data, output_ui, has_subgraph = get_output_data(obj, input_data_all, execution_block_cb=execution_block_cb, pre_execute_cb=pre_execute_cb)
+ if len(output_ui) > 0:
+ caches.ui.set(unique_id, {
+ "meta": {
+ "node_id": unique_id,
+ "display_node": display_node_id,
+ "parent_node": parent_node_id,
+ "real_node_id": real_node_id,
+ },
+ "output": output_ui
+ })
+ if server.client_id is not None:
+ server.send_sync("executed", { "node": unique_id, "display_node": display_node_id, "output": output_ui, "prompt_id": prompt_id }, server.client_id)
+ if has_subgraph:
+ cached_outputs = []
+ new_node_ids = []
+ new_output_ids = []
+ new_output_links = []
+ for i in range(len(output_data)):
+ new_graph, node_outputs = output_data[i]
+ if new_graph is None:
+ cached_outputs.append((False, node_outputs))
+ else:
+ # Check for conflicts
+ for node_id in new_graph.keys():
+ if dynprompt.has_node(node_id):
+ raise DuplicateNodeError(f"Attempt to add duplicate node {node_id}. Ensure node ids are unique and deterministic or use graph_utils.GraphBuilder.")
+ for node_id, node_info in new_graph.items():
+ new_node_ids.append(node_id)
+ display_id = node_info.get("override_display_id", unique_id)
+ dynprompt.add_ephemeral_node(node_id, node_info, unique_id, display_id)
+ # Figure out if the newly created node is an output node
+ class_type = node_info["class_type"]
+ class_def = nodes.NODE_CLASS_MAPPINGS[class_type]
+ if hasattr(class_def, 'OUTPUT_NODE') and class_def.OUTPUT_NODE == True:
+ new_output_ids.append(node_id)
+ for i in range(len(node_outputs)):
+ if is_link(node_outputs[i]):
+ from_node_id, from_socket = node_outputs[i][0], node_outputs[i][1]
+ new_output_links.append((from_node_id, from_socket))
+ cached_outputs.append((True, node_outputs))
+ new_node_ids = set(new_node_ids)
+ for cache in caches.all:
+ cache.ensure_subcache_for(unique_id, new_node_ids).clean_unused()
+ for node_id in new_output_ids:
+ execution_list.add_node(node_id)
+ for link in new_output_links:
+ execution_list.add_strong_link(link[0], link[1], unique_id)
+ pending_subgraph_results[unique_id] = cached_outputs
+ return (ExecutionResult.PENDING, None, None)
+ caches.outputs.set(unique_id, output_data)
except comfy.model_management.InterruptProcessingException as iex:
logging.info("Processing interrupted")
# skip formatting inputs/outputs
error_details = {
- "node_id": unique_id,
+ "node_id": real_node_id,
}
- return (False, error_details, iex)
+ return (ExecutionResult.FAILURE, error_details, iex)
except Exception as ex:
typ, _, tb = sys.exc_info()
exception_type = full_type_name(typ)
@@ -173,121 +389,36 @@ def recursive_execute(server, prompt, outputs, current_item, extra_data, execute
for name, inputs in input_data_all.items():
input_data_formatted[name] = [format_value(x) for x in inputs]
- output_data_formatted = {}
- for node_id, node_outputs in outputs.items():
- output_data_formatted[node_id] = [[format_value(x) for x in l] for l in node_outputs]
-
- logging.error(f"!!! Exception during processing!!! {ex}")
+ logging.error(f"!!! Exception during processing !!! {ex}")
logging.error(traceback.format_exc())
error_details = {
- "node_id": unique_id,
+ "node_id": real_node_id,
"exception_message": str(ex),
"exception_type": exception_type,
"traceback": traceback.format_tb(tb),
- "current_inputs": input_data_formatted,
- "current_outputs": output_data_formatted
+ "current_inputs": input_data_formatted
}
-
if isinstance(ex, comfy.model_management.OOM_EXCEPTION):
logging.error("Got an OOM, unloading all loaded models.")
comfy.model_management.unload_all_models()
- return (False, error_details, ex)
+ return (ExecutionResult.FAILURE, error_details, ex)
executed.add(unique_id)
- return (True, None, None)
-
-def recursive_will_execute(prompt, outputs, current_item, memo={}):
- unique_id = current_item
-
- if unique_id in memo:
- return memo[unique_id]
-
- inputs = prompt[unique_id]['inputs']
- will_execute = []
- if unique_id in outputs:
- return []
-
- for x in inputs:
- input_data = inputs[x]
- if isinstance(input_data, list):
- input_unique_id = input_data[0]
- output_index = input_data[1]
- if input_unique_id not in outputs:
- will_execute += recursive_will_execute(prompt, outputs, input_unique_id, memo)
-
- memo[unique_id] = will_execute + [unique_id]
- return memo[unique_id]
-
-def recursive_output_delete_if_changed(prompt, old_prompt, outputs, current_item):
- unique_id = current_item
- inputs = prompt[unique_id]['inputs']
- class_type = prompt[unique_id]['class_type']
- class_def = nodes.NODE_CLASS_MAPPINGS[class_type]
-
- is_changed_old = ''
- is_changed = ''
- to_delete = False
- if hasattr(class_def, 'IS_CHANGED'):
- if unique_id in old_prompt and 'is_changed' in old_prompt[unique_id]:
- is_changed_old = old_prompt[unique_id]['is_changed']
- if 'is_changed' not in prompt[unique_id]:
- input_data_all = get_input_data(inputs, class_def, unique_id, outputs)
- if input_data_all is not None:
- try:
- #is_changed = class_def.IS_CHANGED(**input_data_all)
- is_changed = map_node_over_list(class_def, input_data_all, "IS_CHANGED")
- prompt[unique_id]['is_changed'] = is_changed
- except:
- to_delete = True
- else:
- is_changed = prompt[unique_id]['is_changed']
-
- if unique_id not in outputs:
- return True
-
- if not to_delete:
- if is_changed != is_changed_old:
- to_delete = True
- elif unique_id not in old_prompt:
- to_delete = True
- elif class_type != old_prompt[unique_id]['class_type']:
- to_delete = True
- elif inputs == old_prompt[unique_id]['inputs']:
- for x in inputs:
- input_data = inputs[x]
-
- if isinstance(input_data, list):
- input_unique_id = input_data[0]
- output_index = input_data[1]
- if input_unique_id in outputs:
- to_delete = recursive_output_delete_if_changed(prompt, old_prompt, outputs, input_unique_id)
- else:
- to_delete = True
- if to_delete:
- break
- else:
- to_delete = True
-
- if to_delete:
- d = outputs.pop(unique_id)
- del d
- return to_delete
+ return (ExecutionResult.SUCCESS, None, None)
class PromptExecutor:
- def __init__(self, server):
+ def __init__(self, server, lru_size=None):
+ self.lru_size = lru_size
self.server = server
self.reset()
def reset(self):
- self.outputs = {}
- self.object_storage = {}
- self.outputs_ui = {}
+ self.caches = CacheSet(self.lru_size)
self.status_messages = []
self.success = True
- self.old_prompt = {}
def add_message(self, event, data: dict, broadcast: bool):
data = {
@@ -318,26 +449,13 @@ class PromptExecutor:
"node_id": node_id,
"node_type": class_type,
"executed": list(executed),
-
"exception_message": error["exception_message"],
"exception_type": error["exception_type"],
"traceback": error["traceback"],
"current_inputs": error["current_inputs"],
- "current_outputs": error["current_outputs"],
+ "current_outputs": list(current_outputs),
}
self.add_message("execution_error", mes, broadcast=False)
-
- # Next, remove the subsequent outputs since they will not be executed
- to_delete = []
- for o in self.outputs:
- if (o not in current_outputs) and (o not in executed):
- to_delete += [o]
- if o in self.old_prompt:
- d = self.old_prompt.pop(o)
- del d
- for o in to_delete:
- d = self.outputs.pop(o)
- del d
def execute(self, prompt, prompt_id, extra_data={}, execute_outputs=[]):
nodes.interrupt_processing(False)
@@ -351,65 +469,59 @@ class PromptExecutor:
self.add_message("execution_start", { "prompt_id": prompt_id}, broadcast=False)
with torch.inference_mode():
- #delete cached outputs if nodes don't exist for them
- to_delete = []
- for o in self.outputs:
- if o not in prompt:
- to_delete += [o]
- for o in to_delete:
- d = self.outputs.pop(o)
- del d
- to_delete = []
- for o in self.object_storage:
- if o[0] not in prompt:
- to_delete += [o]
- else:
- p = prompt[o[0]]
- if o[1] != p['class_type']:
- to_delete += [o]
- for o in to_delete:
- d = self.object_storage.pop(o)
- del d
+ dynamic_prompt = DynamicPrompt(prompt)
+ is_changed_cache = IsChangedCache(dynamic_prompt, self.caches.outputs)
+ for cache in self.caches.all:
+ cache.set_prompt(dynamic_prompt, prompt.keys(), is_changed_cache)
+ cache.clean_unused()
- for x in prompt:
- recursive_output_delete_if_changed(prompt, self.old_prompt, self.outputs, x)
-
- current_outputs = set(self.outputs.keys())
- for x in list(self.outputs_ui.keys()):
- if x not in current_outputs:
- d = self.outputs_ui.pop(x)
- del d
+ cached_nodes = []
+ for node_id in prompt:
+ if self.caches.outputs.get(node_id) is not None:
+ cached_nodes.append(node_id)
comfy.model_management.cleanup_models(keep_clone_weights_loaded=True)
self.add_message("execution_cached",
- { "nodes": list(current_outputs) , "prompt_id": prompt_id},
+ { "nodes": cached_nodes, "prompt_id": prompt_id},
broadcast=False)
+ pending_subgraph_results = {}
executed = set()
- output_node_id = None
- to_execute = []
-
+ execution_list = ExecutionList(dynamic_prompt, self.caches.outputs)
+ current_outputs = self.caches.outputs.all_node_ids()
for node_id in list(execute_outputs):
- to_execute += [(0, node_id)]
+ execution_list.add_node(node_id)
- while len(to_execute) > 0:
- #always execute the output that depends on the least amount of unexecuted nodes first
- memo = {}
- to_execute = sorted(list(map(lambda a: (len(recursive_will_execute(prompt, self.outputs, a[-1], memo)), a[-1]), to_execute)))
- output_node_id = to_execute.pop(0)[-1]
-
- # This call shouldn't raise anything if there's an error deep in
- # the actual SD code, instead it will report the node where the
- # error was raised
- self.success, error, ex = recursive_execute(self.server, prompt, self.outputs, output_node_id, extra_data, executed, prompt_id, self.outputs_ui, self.object_storage)
- if self.success is not True:
- self.handle_execution_error(prompt_id, prompt, current_outputs, executed, error, ex)
+ while not execution_list.is_empty():
+ node_id, error, ex = execution_list.stage_node_execution()
+ if error is not None:
+ self.handle_execution_error(prompt_id, dynamic_prompt.original_prompt, current_outputs, executed, error, ex)
break
+
+ result, error, ex = execute(self.server, dynamic_prompt, self.caches, node_id, extra_data, executed, prompt_id, execution_list, pending_subgraph_results)
+ self.success = result != ExecutionResult.FAILURE
+ if result == ExecutionResult.FAILURE:
+ self.handle_execution_error(prompt_id, dynamic_prompt.original_prompt, current_outputs, executed, error, ex)
+ break
+ elif result == ExecutionResult.PENDING:
+ execution_list.unstage_node_execution()
+ else: # result == ExecutionResult.SUCCESS:
+ execution_list.complete_node_execution()
else:
# Only execute when the while-loop ends without break
self.add_message("execution_success", { "prompt_id": prompt_id }, broadcast=False)
- for x in executed:
- self.old_prompt[x] = copy.deepcopy(prompt[x])
+ ui_outputs = {}
+ meta_outputs = {}
+ all_node_ids = self.caches.ui.all_node_ids()
+ for node_id in all_node_ids:
+ ui_info = self.caches.ui.get(node_id)
+ if ui_info is not None:
+ ui_outputs[node_id] = ui_info["output"]
+ meta_outputs[node_id] = ui_info["meta"]
+ self.history_result = {
+ "outputs": ui_outputs,
+ "meta": meta_outputs,
+ }
self.server.last_node_id = None
if comfy.model_management.DISABLE_SMART_MEMORY:
comfy.model_management.unload_all_models()
@@ -426,31 +538,37 @@ def validate_inputs(prompt, item, validated):
obj_class = nodes.NODE_CLASS_MAPPINGS[class_type]
class_inputs = obj_class.INPUT_TYPES()
- required_inputs = class_inputs['required']
+ valid_inputs = set(class_inputs.get('required',{})).union(set(class_inputs.get('optional',{})))
errors = []
valid = True
validate_function_inputs = []
+ validate_has_kwargs = False
if hasattr(obj_class, "VALIDATE_INPUTS"):
- validate_function_inputs = inspect.getfullargspec(obj_class.VALIDATE_INPUTS).args
+ argspec = inspect.getfullargspec(obj_class.VALIDATE_INPUTS)
+ validate_function_inputs = argspec.args
+ validate_has_kwargs = argspec.varkw is not None
+ received_types = {}
- for x in required_inputs:
+ for x in valid_inputs:
+ type_input, input_category, extra_info = get_input_info(obj_class, x)
+ assert extra_info is not None
if x not in inputs:
- error = {
- "type": "required_input_missing",
- "message": "Required input is missing",
- "details": f"{x}",
- "extra_info": {
- "input_name": x
+ if input_category == "required":
+ error = {
+ "type": "required_input_missing",
+ "message": "Required input is missing",
+ "details": f"{x}",
+ "extra_info": {
+ "input_name": x
+ }
}
- }
- errors.append(error)
+ errors.append(error)
continue
val = inputs[x]
- info = required_inputs[x]
- type_input = info[0]
+ info = (type_input, extra_info)
if isinstance(val, list):
if len(val) != 2:
error = {
@@ -469,8 +587,9 @@ def validate_inputs(prompt, item, validated):
o_id = val[0]
o_class_type = prompt[o_id]['class_type']
r = nodes.NODE_CLASS_MAPPINGS[o_class_type].RETURN_TYPES
- if r[val[1]] != type_input:
- received_type = r[val[1]]
+ received_type = r[val[1]]
+ received_types[x] = received_type
+ if 'input_types' not in validate_function_inputs and received_type != type_input:
details = f"{x}, {received_type} != {type_input}"
error = {
"type": "return_type_mismatch",
@@ -521,6 +640,9 @@ def validate_inputs(prompt, item, validated):
if type_input == "STRING":
val = str(val)
inputs[x] = val
+ if type_input == "BOOLEAN":
+ val = bool(val)
+ inputs[x] = val
except Exception as ex:
error = {
"type": "invalid_input_type",
@@ -536,11 +658,11 @@ def validate_inputs(prompt, item, validated):
errors.append(error)
continue
- if len(info) > 1:
- if "min" in info[1] and val < info[1]["min"]:
+ if x not in validate_function_inputs and not validate_has_kwargs:
+ if "min" in extra_info and val < extra_info["min"]:
error = {
"type": "value_smaller_than_min",
- "message": "Value {} smaller than min of {}".format(val, info[1]["min"]),
+ "message": "Value {} smaller than min of {}".format(val, extra_info["min"]),
"details": f"{x}",
"extra_info": {
"input_name": x,
@@ -550,10 +672,10 @@ def validate_inputs(prompt, item, validated):
}
errors.append(error)
continue
- if "max" in info[1] and val > info[1]["max"]:
+ if "max" in extra_info and val > extra_info["max"]:
error = {
"type": "value_bigger_than_max",
- "message": "Value {} bigger than max of {}".format(val, info[1]["max"]),
+ "message": "Value {} bigger than max of {}".format(val, extra_info["max"]),
"details": f"{x}",
"extra_info": {
"input_name": x,
@@ -564,7 +686,6 @@ def validate_inputs(prompt, item, validated):
errors.append(error)
continue
- if x not in validate_function_inputs:
if isinstance(type_input, list):
if val not in type_input:
input_config = info
@@ -591,18 +712,20 @@ def validate_inputs(prompt, item, validated):
errors.append(error)
continue
- if len(validate_function_inputs) > 0:
- input_data_all = get_input_data(inputs, obj_class, unique_id)
+ if len(validate_function_inputs) > 0 or validate_has_kwargs:
+ input_data_all, _ = get_input_data(inputs, obj_class, unique_id)
input_filtered = {}
for x in input_data_all:
- if x in validate_function_inputs:
+ if x in validate_function_inputs or validate_has_kwargs:
input_filtered[x] = input_data_all[x]
+ if 'input_types' in validate_function_inputs:
+ input_filtered['input_types'] = [received_types]
#ret = obj_class.VALIDATE_INPUTS(**input_filtered)
- ret = map_node_over_list(obj_class, input_filtered, "VALIDATE_INPUTS")
+ ret = _map_node_over_list(obj_class, input_filtered, "VALIDATE_INPUTS")
for x in input_filtered:
for i, r in enumerate(ret):
- if r is not True:
+ if r is not True and not isinstance(r, ExecutionBlocker):
details = f"{x}"
if r is not False:
details += f" - {str(r)}"
@@ -613,8 +736,6 @@ def validate_inputs(prompt, item, validated):
"details": details,
"extra_info": {
"input_name": x,
- "input_config": info,
- "received_value": val,
}
}
errors.append(error)
@@ -780,7 +901,7 @@ class PromptQueue:
completed: bool
messages: List[str]
- def task_done(self, item_id, outputs,
+ def task_done(self, item_id, history_result,
status: Optional['PromptQueue.ExecutionStatus']):
with self.mutex:
prompt = self.currently_running.pop(item_id)
@@ -793,9 +914,10 @@ class PromptQueue:
self.history[prompt[1]] = {
"prompt": prompt,
- "outputs": copy.deepcopy(outputs),
+ "outputs": {},
'status': status_dict,
}
+ self.history[prompt[1]].update(history_result)
self.server.queue_updated()
def get_current_queue(self):
diff --git a/extra_model_paths.yaml.example b/extra_model_paths.yaml.example
index 36a58b2b2..8519341c6 100644
--- a/extra_model_paths.yaml.example
+++ b/extra_model_paths.yaml.example
@@ -25,12 +25,16 @@ a111:
#comfyui:
# base_path: path/to/comfyui/
+# # You can use is_default to mark that these folders should be listed first, and used as the default dirs for eg downloads
+# #is_default: true
# checkpoints: models/checkpoints/
# clip: models/clip/
# clip_vision: models/clip_vision/
# configs: models/configs/
# controlnet: models/controlnet/
-# diffusers: models/diffusers/
+# diffusion_models: |
+# models/diffusion_models
+# models/unet
# embeddings: models/embeddings/
# gligen: models/gligen/
# hypernetworks: models/hypernetworks/
diff --git a/folder_paths.py b/folder_paths.py
index 3db1da61a..1f03c08d8 100644
--- a/folder_paths.py
+++ b/folder_paths.py
@@ -2,7 +2,9 @@ from __future__ import annotations
import os
import time
+import mimetypes
import logging
+from typing import Set, List, Dict, Tuple, Literal
from collections.abc import Collection
supported_pt_extensions: set[str] = {'.ckpt', '.pt', '.bin', '.pth', '.safetensors', '.pkl', '.sft'}
@@ -17,7 +19,7 @@ folder_names_and_paths["configs"] = ([os.path.join(models_dir, "configs")], [".y
folder_names_and_paths["loras"] = ([os.path.join(models_dir, "loras")], supported_pt_extensions)
folder_names_and_paths["vae"] = ([os.path.join(models_dir, "vae")], supported_pt_extensions)
folder_names_and_paths["clip"] = ([os.path.join(models_dir, "clip")], supported_pt_extensions)
-folder_names_and_paths["unet"] = ([os.path.join(models_dir, "unet")], supported_pt_extensions)
+folder_names_and_paths["diffusion_models"] = ([os.path.join(models_dir, "unet"), os.path.join(models_dir, "diffusion_models")], supported_pt_extensions)
folder_names_and_paths["clip_vision"] = ([os.path.join(models_dir, "clip_vision")], supported_pt_extensions)
folder_names_and_paths["style_models"] = ([os.path.join(models_dir, "style_models")], supported_pt_extensions)
folder_names_and_paths["embeddings"] = ([os.path.join(models_dir, "embeddings")], supported_pt_extensions)
@@ -44,6 +46,44 @@ user_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), "user
filename_list_cache: dict[str, tuple[list[str], dict[str, float], float]] = {}
+class CacheHelper:
+ """
+ Helper class for managing file list cache data.
+ """
+ def __init__(self):
+ self.cache: dict[str, tuple[list[str], dict[str, float], float]] = {}
+ self.active = False
+
+ def get(self, key: str, default=None) -> tuple[list[str], dict[str, float], float]:
+ if not self.active:
+ return default
+ return self.cache.get(key, default)
+
+ def set(self, key: str, value: tuple[list[str], dict[str, float], float]) -> None:
+ if self.active:
+ self.cache[key] = value
+
+ def clear(self):
+ self.cache.clear()
+
+ def __enter__(self):
+ self.active = True
+ return self
+
+ def __exit__(self, exc_type, exc_value, traceback):
+ self.active = False
+ self.clear()
+
+cache_helper = CacheHelper()
+
+extension_mimetypes_cache = {
+ "webp" : "image",
+}
+
+def map_legacy(folder_name: str) -> str:
+ legacy = {"unet": "diffusion_models"}
+ return legacy.get(folder_name, folder_name)
+
if not os.path.exists(input_directory):
try:
os.makedirs(input_directory)
@@ -74,6 +114,13 @@ def get_input_directory() -> str:
global input_directory
return input_directory
+def get_user_directory() -> str:
+ return user_directory
+
+def set_user_directory(user_dir: str) -> None:
+ global user_directory
+ user_directory = user_dir
+
#NOTE: used in http server so don't put folders that should not be accessed remotely
def get_directory_by_type(type_name: str) -> str | None:
@@ -85,6 +132,28 @@ def get_directory_by_type(type_name: str) -> str | None:
return get_input_directory()
return None
+def filter_files_content_types(files: List[str], content_types: Literal["image", "video", "audio"]) -> List[str]:
+ """
+ Example:
+ files = os.listdir(folder_paths.get_input_directory())
+ filter_files_content_types(files, ["image", "audio", "video"])
+ """
+ global extension_mimetypes_cache
+ result = []
+ for file in files:
+ extension = file.split('.')[-1]
+ if extension not in extension_mimetypes_cache:
+ mime_type, _ = mimetypes.guess_type(file, strict=False)
+ if not mime_type:
+ continue
+ content_type = mime_type.split('/')[0]
+ extension_mimetypes_cache[extension] = content_type
+ else:
+ content_type = extension_mimetypes_cache[extension]
+
+ if content_type in content_types:
+ result.append(file)
+ return result
# determine base_dir rely on annotation if name is 'filename.ext [annotation]' format
# otherwise use default_path as base_dir
@@ -126,14 +195,19 @@ def exists_annotated_filepath(name) -> bool:
return os.path.exists(filepath)
-def add_model_folder_path(folder_name: str, full_folder_path: str) -> None:
+def add_model_folder_path(folder_name: str, full_folder_path: str, is_default: bool = False) -> None:
global folder_names_and_paths
+ folder_name = map_legacy(folder_name)
if folder_name in folder_names_and_paths:
- folder_names_and_paths[folder_name][0].append(full_folder_path)
+ if is_default:
+ folder_names_and_paths[folder_name][0].insert(0, full_folder_path)
+ else:
+ folder_names_and_paths[folder_name][0].append(full_folder_path)
else:
folder_names_and_paths[folder_name] = ([full_folder_path], set())
def get_folder_paths(folder_name: str) -> list[str]:
+ folder_name = map_legacy(folder_name)
return folder_names_and_paths[folder_name][0][:]
def recursive_search(directory: str, excluded_dir_names: list[str] | None=None) -> tuple[list[str], dict[str, float]]:
@@ -180,6 +254,7 @@ def filter_files_extensions(files: Collection[str], extensions: Collection[str])
def get_full_path(folder_name: str, filename: str) -> str | None:
global folder_names_and_paths
+ folder_name = map_legacy(folder_name)
if folder_name not in folder_names_and_paths:
return None
folders = folder_names_and_paths[folder_name]
@@ -193,7 +268,16 @@ def get_full_path(folder_name: str, filename: str) -> str | None:
return None
+
+def get_full_path_or_raise(folder_name: str, filename: str) -> str:
+ full_path = get_full_path(folder_name, filename)
+ if full_path is None:
+ raise FileNotFoundError(f"Model in folder '{folder_name}' with filename '{filename}' not found.")
+ return full_path
+
+
def get_filename_list_(folder_name: str) -> tuple[list[str], dict[str, float], float]:
+ folder_name = map_legacy(folder_name)
global folder_names_and_paths
output_list = set()
folders = folder_names_and_paths[folder_name]
@@ -206,8 +290,13 @@ def get_filename_list_(folder_name: str) -> tuple[list[str], dict[str, float], f
return sorted(list(output_list)), output_folders, time.perf_counter()
def cached_filename_list_(folder_name: str) -> tuple[list[str], dict[str, float], float] | None:
+ strong_cache = cache_helper.get(folder_name)
+ if strong_cache is not None:
+ return strong_cache
+
global filename_list_cache
global folder_names_and_paths
+ folder_name = map_legacy(folder_name)
if folder_name not in filename_list_cache:
return None
out = filename_list_cache[folder_name]
@@ -227,11 +316,13 @@ def cached_filename_list_(folder_name: str) -> tuple[list[str], dict[str, float]
return out
def get_filename_list(folder_name: str) -> list[str]:
+ folder_name = map_legacy(folder_name)
out = cached_filename_list_(folder_name)
if out is None:
out = get_filename_list_(folder_name)
global filename_list_cache
filename_list_cache[folder_name] = out
+ cache_helper.set(folder_name, out)
return list(out[0])
def get_save_image_path(filename_prefix: str, output_dir: str, image_width=0, image_height=0) -> tuple[str, str, int, str, str]:
@@ -247,9 +338,17 @@ def get_save_image_path(filename_prefix: str, output_dir: str, image_width=0, im
def compute_vars(input: str, image_width: int, image_height: int) -> str:
input = input.replace("%width%", str(image_width))
input = input.replace("%height%", str(image_height))
+ now = time.localtime()
+ input = input.replace("%year%", str(now.tm_year))
+ input = input.replace("%month%", str(now.tm_mon).zfill(2))
+ input = input.replace("%day%", str(now.tm_mday).zfill(2))
+ input = input.replace("%hour%", str(now.tm_hour).zfill(2))
+ input = input.replace("%minute%", str(now.tm_min).zfill(2))
+ input = input.replace("%second%", str(now.tm_sec).zfill(2))
return input
- filename_prefix = compute_vars(filename_prefix, image_width, image_height)
+ if "%" in filename_prefix:
+ filename_prefix = compute_vars(filename_prefix, image_width, image_height)
subfolder = os.path.dirname(os.path.normpath(filename_prefix))
filename = os.path.basename(os.path.normpath(filename_prefix))
diff --git a/latent_preview.py b/latent_preview.py
index ae6c106e4..e14c72ce4 100644
--- a/latent_preview.py
+++ b/latent_preview.py
@@ -9,7 +9,7 @@ import folder_paths
import comfy.utils
import logging
-MAX_PREVIEW_RESOLUTION = 512
+MAX_PREVIEW_RESOLUTION = args.preview_size
def preview_to_image(latent_image):
latents_ubyte = (((latent_image + 1.0) / 2.0).clamp(0, 1) # change scale from -1..1 to 0..1
diff --git a/main.py b/main.py
index b878b3e01..3f5e2137e 100644
--- a/main.py
+++ b/main.py
@@ -6,6 +6,10 @@ import importlib.util
import folder_paths
import time
from comfy.cli_args import args
+from app.logger import setup_logger
+
+
+setup_logger(verbose=args.verbose)
def execute_prestartup_script():
@@ -59,6 +63,7 @@ import threading
import gc
import logging
+import utils.extra_config
if os.name == "nt":
logging.getLogger("xformers").addFilter(lambda record: 'A matching Triton is not available' not in record.getMessage())
@@ -81,7 +86,6 @@ if args.windows_standalone_build:
pass
import comfy.utils
-import yaml
import execution
import server
@@ -101,7 +105,7 @@ def cuda_malloc_warning():
logging.warning("\nWARNING: this card most likely does not support cuda-malloc, if you get \"CUDA error\" please run ComfyUI with: --disable-cuda-malloc\n")
def prompt_worker(q, server):
- e = execution.PromptExecutor(server)
+ e = execution.PromptExecutor(server, lru_size=args.cache_lru)
last_gc_collect = 0
need_gc = False
gc_collect_interval = 10.0
@@ -121,7 +125,7 @@ def prompt_worker(q, server):
e.execute(item[2], prompt_id, item[3], item[4])
need_gc = True
q.task_done(item_id,
- e.outputs_ui,
+ e.history_result,
status=execution.PromptQueue.ExecutionStatus(
status_str='success' if e.success else 'error',
completed=e.success,
@@ -156,7 +160,10 @@ def prompt_worker(q, server):
need_gc = False
async def run(server, address='', port=8188, verbose=True, call_on_start=None):
- await asyncio.gather(server.start(address, port, verbose, call_on_start), server.publish_loop())
+ addresses = []
+ for addr in address.split(","):
+ addresses.append((addr, port))
+ await asyncio.gather(server.start_multi_address(addresses, call_on_start), server.publish_loop())
def hijack_progress(server):
@@ -176,27 +183,6 @@ def cleanup_temp():
shutil.rmtree(temp_dir, ignore_errors=True)
-def load_extra_path_config(yaml_path):
- with open(yaml_path, 'r') as stream:
- config = yaml.safe_load(stream)
- for c in config:
- conf = config[c]
- if conf is None:
- continue
- base_path = None
- if "base_path" in conf:
- base_path = conf.pop("base_path")
- for x in conf:
- for y in conf[x].split("\n"):
- if len(y) == 0:
- continue
- full_path = y
- if base_path is not None:
- full_path = os.path.join(base_path, full_path)
- logging.info("Adding extra search path {} {}".format(x, full_path))
- folder_paths.add_model_folder_path(x, full_path)
-
-
if __name__ == "__main__":
if args.temp_directory:
temp_dir = os.path.join(os.path.abspath(args.temp_directory), "temp")
@@ -218,11 +204,11 @@ if __name__ == "__main__":
extra_model_paths_config_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "extra_model_paths.yaml")
if os.path.isfile(extra_model_paths_config_path):
- load_extra_path_config(extra_model_paths_config_path)
+ utils.extra_config.load_extra_path_config(extra_model_paths_config_path)
if args.extra_model_paths_config:
for config_path in itertools.chain(*args.extra_model_paths_config):
- load_extra_path_config(config_path)
+ utils.extra_config.load_extra_path_config(config_path)
nodes.init_extra_nodes(init_custom_nodes=not args.disable_all_custom_nodes)
@@ -242,21 +228,31 @@ if __name__ == "__main__":
folder_paths.add_model_folder_path("checkpoints", os.path.join(folder_paths.get_output_directory(), "checkpoints"))
folder_paths.add_model_folder_path("clip", os.path.join(folder_paths.get_output_directory(), "clip"))
folder_paths.add_model_folder_path("vae", os.path.join(folder_paths.get_output_directory(), "vae"))
+ folder_paths.add_model_folder_path("diffusion_models", os.path.join(folder_paths.get_output_directory(), "diffusion_models"))
+ folder_paths.add_model_folder_path("loras", os.path.join(folder_paths.get_output_directory(), "loras"))
if args.input_directory:
input_dir = os.path.abspath(args.input_directory)
logging.info(f"Setting input directory to: {input_dir}")
folder_paths.set_input_directory(input_dir)
+
+ if args.user_directory:
+ user_dir = os.path.abspath(args.user_directory)
+ logging.info(f"Setting user directory to: {user_dir}")
+ folder_paths.set_user_directory(user_dir)
if args.quick_test_for_ci:
exit(0)
+ os.makedirs(folder_paths.get_temp_directory(), exist_ok=True)
call_on_start = None
if args.auto_launch:
def startup_server(scheme, address, port):
import webbrowser
if os.name == 'nt' and address == '0.0.0.0':
address = '127.0.0.1'
+ if ':' in address:
+ address = "[{}]".format(address)
webbrowser.open(f"{scheme}://{address}:{port}")
call_on_start = startup_server
diff --git a/model_filemanager/__init__.py b/model_filemanager/__init__.py
index e318351c0..b7ac16256 100644
--- a/model_filemanager/__init__.py
+++ b/model_filemanager/__init__.py
@@ -1,2 +1,2 @@
# model_manager/__init__.py
-from .download_models import download_model, DownloadModelStatus, DownloadStatusType, create_model_path, check_file_exists, track_download_progress, validate_model_subdirectory, validate_filename
+from .download_models import download_model, DownloadModelStatus, DownloadStatusType, create_model_path, check_file_exists, track_download_progress, validate_filename
diff --git a/model_filemanager/download_models.py b/model_filemanager/download_models.py
index 712d59328..5ffec395e 100644
--- a/model_filemanager/download_models.py
+++ b/model_filemanager/download_models.py
@@ -3,7 +3,7 @@ import aiohttp
import os
import traceback
import logging
-from folder_paths import models_dir
+from folder_paths import folder_names_and_paths, get_folder_paths
import re
from typing import Callable, Any, Optional, Awaitable, Dict
from enum import Enum
@@ -17,6 +17,7 @@ class DownloadStatusType(Enum):
COMPLETED = "completed"
ERROR = "error"
+
@dataclass
class DownloadModelStatus():
status: str
@@ -29,7 +30,7 @@ class DownloadModelStatus():
self.progress_percentage = progress_percentage
self.message = message
self.already_existed = already_existed
-
+
def to_dict(self) -> Dict[str, Any]:
return {
"status": self.status,
@@ -38,102 +39,112 @@ class DownloadModelStatus():
"already_existed": self.already_existed
}
+
async def download_model(model_download_request: Callable[[str], Awaitable[aiohttp.ClientResponse]],
- model_name: str,
- model_url: str,
- model_sub_directory: str,
+ model_name: str,
+ model_url: str,
+ model_directory: str,
+ folder_path: str,
progress_callback: Callable[[str, DownloadModelStatus], Awaitable[Any]],
progress_interval: float = 1.0) -> DownloadModelStatus:
"""
Download a model file from a given URL into the models directory.
Args:
- model_download_request (Callable[[str], Awaitable[aiohttp.ClientResponse]]):
+ model_download_request (Callable[[str], Awaitable[aiohttp.ClientResponse]]):
A function that makes an HTTP request. This makes it easier to mock in unit tests.
- model_name (str):
+ model_name (str):
The name of the model file to be downloaded. This will be the filename on disk.
- model_url (str):
+ model_url (str):
The URL from which to download the model.
- model_sub_directory (str):
- The subdirectory within the main models directory where the model
+ model_directory (str):
+ The subdirectory within the main models directory where the model
should be saved (e.g., 'checkpoints', 'loras', etc.).
- progress_callback (Callable[[str, DownloadModelStatus], Awaitable[Any]]):
+ progress_callback (Callable[[str, DownloadModelStatus], Awaitable[Any]]):
An asynchronous function to call with progress updates.
+ folder_path (str);
+ Path to which model folder should be used as the root.
Returns:
DownloadModelStatus: The result of the download operation.
"""
- if not validate_model_subdirectory(model_sub_directory):
- return DownloadModelStatus(
- DownloadStatusType.ERROR,
- 0,
- "Invalid model subdirectory",
- False
- )
-
if not validate_filename(model_name):
return DownloadModelStatus(
- DownloadStatusType.ERROR,
+ DownloadStatusType.ERROR,
0,
- "Invalid model name",
+ "Invalid model name",
False
)
- file_path, relative_path = create_model_path(model_name, model_sub_directory, models_dir)
- existing_file = await check_file_exists(file_path, model_name, progress_callback, relative_path)
+ if not model_directory in folder_names_and_paths:
+ return DownloadModelStatus(
+ DownloadStatusType.ERROR,
+ 0,
+ "Invalid or unrecognized model directory. model_directory must be a known model type (eg 'checkpoints'). If you are seeing this error for a custom model type, ensure the relevant custom nodes are installed and working.",
+ False
+ )
+
+ if not folder_path in get_folder_paths(model_directory):
+ return DownloadModelStatus(
+ DownloadStatusType.ERROR,
+ 0,
+ f"Invalid folder path '{folder_path}', does not match the list of known directories ({get_folder_paths(model_directory)}). If you're seeing this in the downloader UI, you may need to refresh the page.",
+ False
+ )
+
+ file_path = create_model_path(model_name, folder_path)
+ existing_file = await check_file_exists(file_path, model_name, progress_callback)
if existing_file:
return existing_file
try:
+ logging.info(f"Downloading {model_name} from {model_url}")
status = DownloadModelStatus(DownloadStatusType.PENDING, 0, f"Starting download of {model_name}", False)
- await progress_callback(relative_path, status)
+ await progress_callback(model_name, status)
response = await model_download_request(model_url)
if response.status != 200:
error_message = f"Failed to download {model_name}. Status code: {response.status}"
logging.error(error_message)
status = DownloadModelStatus(DownloadStatusType.ERROR, 0, error_message, False)
- await progress_callback(relative_path, status)
+ await progress_callback(model_name, status)
return DownloadModelStatus(DownloadStatusType.ERROR, 0, error_message, False)
- return await track_download_progress(response, file_path, model_name, progress_callback, relative_path, progress_interval)
+ return await track_download_progress(response, file_path, model_name, progress_callback, progress_interval)
except Exception as e:
logging.error(f"Error in downloading model: {e}")
- return await handle_download_error(e, model_name, progress_callback, relative_path)
-
+ return await handle_download_error(e, model_name, progress_callback)
-def create_model_path(model_name: str, model_directory: str, models_base_dir: str) -> tuple[str, str]:
- full_model_dir = os.path.join(models_base_dir, model_directory)
- os.makedirs(full_model_dir, exist_ok=True)
- file_path = os.path.join(full_model_dir, model_name)
+
+def create_model_path(model_name: str, folder_path: str) -> tuple[str, str]:
+ os.makedirs(folder_path, exist_ok=True)
+ file_path = os.path.join(folder_path, model_name)
# Ensure the resulting path is still within the base directory
abs_file_path = os.path.abspath(file_path)
- abs_base_dir = os.path.abspath(str(models_base_dir))
+ abs_base_dir = os.path.abspath(folder_path)
if os.path.commonprefix([abs_file_path, abs_base_dir]) != abs_base_dir:
- raise Exception(f"Invalid model directory: {model_directory}/{model_name}")
+ raise Exception(f"Invalid model directory: {folder_path}/{model_name}")
+
+ return file_path
- relative_path = '/'.join([model_directory, model_name])
- return file_path, relative_path
-
-async def check_file_exists(file_path: str,
- model_name: str,
- progress_callback: Callable[[str, DownloadModelStatus], Awaitable[Any]],
- relative_path: str) -> Optional[DownloadModelStatus]:
+async def check_file_exists(file_path: str,
+ model_name: str,
+ progress_callback: Callable[[str, DownloadModelStatus], Awaitable[Any]]
+ ) -> Optional[DownloadModelStatus]:
if os.path.exists(file_path):
status = DownloadModelStatus(DownloadStatusType.COMPLETED, 100, f"{model_name} already exists", True)
- await progress_callback(relative_path, status)
+ await progress_callback(model_name, status)
return status
return None
-async def track_download_progress(response: aiohttp.ClientResponse,
- file_path: str,
- model_name: str,
- progress_callback: Callable[[str, DownloadModelStatus], Awaitable[Any]],
- relative_path: str,
+async def track_download_progress(response: aiohttp.ClientResponse,
+ file_path: str,
+ model_name: str,
+ progress_callback: Callable[[str, DownloadModelStatus], Awaitable[Any]],
interval: float = 1.0) -> DownloadModelStatus:
try:
total_size = int(response.headers.get('Content-Length', 0))
@@ -144,10 +155,11 @@ async def track_download_progress(response: aiohttp.ClientResponse,
nonlocal last_update_time
progress = (downloaded / total_size) * 100 if total_size > 0 else 0
status = DownloadModelStatus(DownloadStatusType.IN_PROGRESS, progress, f"Downloading {model_name}", False)
- await progress_callback(relative_path, status)
+ await progress_callback(model_name, status)
last_update_time = time.time()
- with open(file_path, 'wb') as f:
+ temp_file_path = file_path + '.tmp'
+ with open(temp_file_path, 'wb') as f:
chunk_iterator = response.content.iter_chunked(8192)
while True:
try:
@@ -156,58 +168,39 @@ async def track_download_progress(response: aiohttp.ClientResponse,
break
f.write(chunk)
downloaded += len(chunk)
-
+
if time.time() - last_update_time >= interval:
await update_progress()
+ os.rename(temp_file_path, file_path)
+
await update_progress()
-
+
logging.info(f"Successfully downloaded {model_name}. Total downloaded: {downloaded}")
status = DownloadModelStatus(DownloadStatusType.COMPLETED, 100, f"Successfully downloaded {model_name}", False)
- await progress_callback(relative_path, status)
+ await progress_callback(model_name, status)
return status
except Exception as e:
logging.error(f"Error in track_download_progress: {e}")
logging.error(traceback.format_exc())
- return await handle_download_error(e, model_name, progress_callback, relative_path)
+ return await handle_download_error(e, model_name, progress_callback)
-async def handle_download_error(e: Exception,
- model_name: str,
- progress_callback: Callable[[str, DownloadModelStatus], Any],
- relative_path: str) -> DownloadModelStatus:
+
+async def handle_download_error(e: Exception,
+ model_name: str,
+ progress_callback: Callable[[str, DownloadModelStatus], Any]
+ ) -> DownloadModelStatus:
error_message = f"Error downloading {model_name}: {str(e)}"
status = DownloadModelStatus(DownloadStatusType.ERROR, 0, error_message, False)
- await progress_callback(relative_path, status)
+ await progress_callback(model_name, status)
return status
-def validate_model_subdirectory(model_subdirectory: str) -> bool:
- """
- Validate that the model subdirectory is safe to install into.
- Must not contain relative paths, nested paths or special characters
- other than underscores and hyphens.
-
- Args:
- model_subdirectory (str): The subdirectory for the specific model type.
-
- Returns:
- bool: True if the subdirectory is safe, False otherwise.
- """
- if len(model_subdirectory) > 50:
- return False
-
- if '..' in model_subdirectory or '/' in model_subdirectory:
- return False
-
- if not re.match(r'^[a-zA-Z0-9_-]+$', model_subdirectory):
- return False
-
- return True
def validate_filename(filename: str)-> bool:
"""
Validate a filename to ensure it's safe and doesn't contain any path traversal attempts.
-
+
Args:
filename (str): The filename to validate
diff --git a/models/diffusion_models/put_diffusion_model_files_here b/models/diffusion_models/put_diffusion_model_files_here
new file mode 100644
index 000000000..e69de29bb
diff --git a/nodes.py b/nodes.py
index 16f5c9b00..a4065c764 100644
--- a/nodes.py
+++ b/nodes.py
@@ -511,10 +511,11 @@ class CheckpointLoader:
FUNCTION = "load_checkpoint"
CATEGORY = "advanced/loaders"
+ DEPRECATED = True
def load_checkpoint(self, config_name, ckpt_name):
config_path = folder_paths.get_full_path("configs", config_name)
- ckpt_path = folder_paths.get_full_path("checkpoints", ckpt_name)
+ ckpt_path = folder_paths.get_full_path_or_raise("checkpoints", ckpt_name)
return comfy.sd.load_checkpoint(config_path, ckpt_path, output_vae=True, output_clip=True, embedding_directory=folder_paths.get_folder_paths("embeddings"))
class CheckpointLoaderSimple:
@@ -535,7 +536,7 @@ class CheckpointLoaderSimple:
DESCRIPTION = "Loads a diffusion model checkpoint, diffusion models are used to denoise latents."
def load_checkpoint(self, ckpt_name):
- ckpt_path = folder_paths.get_full_path("checkpoints", ckpt_name)
+ ckpt_path = folder_paths.get_full_path_or_raise("checkpoints", ckpt_name)
out = comfy.sd.load_checkpoint_guess_config(ckpt_path, output_vae=True, output_clip=True, embedding_directory=folder_paths.get_folder_paths("embeddings"))
return out[:3]
@@ -577,7 +578,7 @@ class unCLIPCheckpointLoader:
CATEGORY = "loaders"
def load_checkpoint(self, ckpt_name, output_vae=True, output_clip=True):
- ckpt_path = folder_paths.get_full_path("checkpoints", ckpt_name)
+ ckpt_path = folder_paths.get_full_path_or_raise("checkpoints", ckpt_name)
out = comfy.sd.load_checkpoint_guess_config(ckpt_path, output_vae=True, output_clip=True, output_clipvision=True, embedding_directory=folder_paths.get_folder_paths("embeddings"))
return out
@@ -624,7 +625,7 @@ class LoraLoader:
if strength_model == 0 and strength_clip == 0:
return (model, clip)
- lora_path = folder_paths.get_full_path("loras", lora_name)
+ lora_path = folder_paths.get_full_path_or_raise("loras", lora_name)
lora = None
if self.loaded_lora is not None:
if self.loaded_lora[0] == lora_path:
@@ -665,6 +666,8 @@ class VAELoader:
sd1_taesd_dec = False
sd3_taesd_enc = False
sd3_taesd_dec = False
+ f1_taesd_enc = False
+ f1_taesd_dec = False
for v in approx_vaes:
if v.startswith("taesd_decoder."):
@@ -679,12 +682,18 @@ class VAELoader:
sd3_taesd_dec = True
elif v.startswith("taesd3_encoder."):
sd3_taesd_enc = True
+ elif v.startswith("taef1_encoder."):
+ f1_taesd_dec = True
+ elif v.startswith("taef1_decoder."):
+ f1_taesd_enc = True
if sd1_taesd_dec and sd1_taesd_enc:
vaes.append("taesd")
if sdxl_taesd_dec and sdxl_taesd_enc:
vaes.append("taesdxl")
if sd3_taesd_dec and sd3_taesd_enc:
vaes.append("taesd3")
+ if f1_taesd_dec and f1_taesd_enc:
+ vaes.append("taef1")
return vaes
@staticmethod
@@ -695,11 +704,11 @@ class VAELoader:
encoder = next(filter(lambda a: a.startswith("{}_encoder.".format(name)), approx_vaes))
decoder = next(filter(lambda a: a.startswith("{}_decoder.".format(name)), approx_vaes))
- enc = comfy.utils.load_torch_file(folder_paths.get_full_path("vae_approx", encoder))
+ enc = comfy.utils.load_torch_file(folder_paths.get_full_path_or_raise("vae_approx", encoder))
for k in enc:
sd["taesd_encoder.{}".format(k)] = enc[k]
- dec = comfy.utils.load_torch_file(folder_paths.get_full_path("vae_approx", decoder))
+ dec = comfy.utils.load_torch_file(folder_paths.get_full_path_or_raise("vae_approx", decoder))
for k in dec:
sd["taesd_decoder.{}".format(k)] = dec[k]
@@ -712,6 +721,9 @@ class VAELoader:
elif name == "taesd3":
sd["vae_scale"] = torch.tensor(1.5305)
sd["vae_shift"] = torch.tensor(0.0609)
+ elif name == "taef1":
+ sd["vae_scale"] = torch.tensor(0.3611)
+ sd["vae_shift"] = torch.tensor(0.1159)
return sd
@classmethod
@@ -724,10 +736,10 @@ class VAELoader:
#TODO: scale factor?
def load_vae(self, vae_name):
- if vae_name in ["taesd", "taesdxl", "taesd3"]:
+ if vae_name in ["taesd", "taesdxl", "taesd3", "taef1"]:
sd = self.load_taesd(vae_name)
else:
- vae_path = folder_paths.get_full_path("vae", vae_name)
+ vae_path = folder_paths.get_full_path_or_raise("vae", vae_name)
sd = comfy.utils.load_torch_file(vae_path)
vae = comfy.sd.VAE(sd=sd)
return (vae,)
@@ -743,7 +755,7 @@ class ControlNetLoader:
CATEGORY = "loaders"
def load_controlnet(self, control_net_name):
- controlnet_path = folder_paths.get_full_path("controlnet", control_net_name)
+ controlnet_path = folder_paths.get_full_path_or_raise("controlnet", control_net_name)
controlnet = comfy.controlnet.load_controlnet(controlnet_path)
return (controlnet,)
@@ -759,7 +771,7 @@ class DiffControlNetLoader:
CATEGORY = "loaders"
def load_controlnet(self, model, control_net_name):
- controlnet_path = folder_paths.get_full_path("controlnet", control_net_name)
+ controlnet_path = folder_paths.get_full_path_or_raise("controlnet", control_net_name)
controlnet = comfy.controlnet.load_controlnet(controlnet_path, model)
return (controlnet,)
@@ -775,6 +787,7 @@ class ControlNetApply:
RETURN_TYPES = ("CONDITIONING",)
FUNCTION = "apply_controlnet"
+ DEPRECATED = True
CATEGORY = "conditioning/controlnet"
def apply_controlnet(self, conditioning, control_net, image, strength):
@@ -804,7 +817,10 @@ class ControlNetApplyAdvanced:
"strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
"start_percent": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.001}),
"end_percent": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.001})
- }}
+ },
+ "optional": {"vae": ("VAE", ),
+ }
+ }
RETURN_TYPES = ("CONDITIONING","CONDITIONING")
RETURN_NAMES = ("positive", "negative")
@@ -812,7 +828,7 @@ class ControlNetApplyAdvanced:
CATEGORY = "conditioning/controlnet"
- def apply_controlnet(self, positive, negative, control_net, image, strength, start_percent, end_percent, vae=None):
+ def apply_controlnet(self, positive, negative, control_net, image, strength, start_percent, end_percent, vae=None, extra_concat=[]):
if strength == 0:
return (positive, negative)
@@ -829,7 +845,7 @@ class ControlNetApplyAdvanced:
if prev_cnet in cnets:
c_net = cnets[prev_cnet]
else:
- c_net = control_net.copy().set_cond_hint(control_hint, strength, (start_percent, end_percent), vae)
+ c_net = control_net.copy().set_cond_hint(control_hint, strength, (start_percent, end_percent), vae=vae, extra_concat=extra_concat)
c_net.set_previous_controlnet(prev_cnet)
cnets[prev_cnet] = c_net
@@ -844,7 +860,7 @@ class ControlNetApplyAdvanced:
class UNETLoader:
@classmethod
def INPUT_TYPES(s):
- return {"required": { "unet_name": (folder_paths.get_filename_list("unet"), ),
+ return {"required": { "unet_name": (folder_paths.get_filename_list("diffusion_models"), ),
"weight_dtype": (["default", "fp8_e4m3fn", "fp8_e5m2"],)
}}
RETURN_TYPES = ("MODEL",)
@@ -859,7 +875,7 @@ class UNETLoader:
elif weight_dtype == "fp8_e5m2":
model_options["dtype"] = torch.float8_e5m2
- unet_path = folder_paths.get_full_path("unet", unet_name)
+ unet_path = folder_paths.get_full_path_or_raise("diffusion_models", unet_name)
model = comfy.sd.load_diffusion_model(unet_path, model_options=model_options)
return (model,)
@@ -884,7 +900,7 @@ class CLIPLoader:
else:
clip_type = comfy.sd.CLIPType.STABLE_DIFFUSION
- clip_path = folder_paths.get_full_path("clip", clip_name)
+ clip_path = folder_paths.get_full_path_or_raise("clip", clip_name)
clip = comfy.sd.load_clip(ckpt_paths=[clip_path], embedding_directory=folder_paths.get_folder_paths("embeddings"), clip_type=clip_type)
return (clip,)
@@ -901,8 +917,8 @@ class DualCLIPLoader:
CATEGORY = "advanced/loaders"
def load_clip(self, clip_name1, clip_name2, type):
- clip_path1 = folder_paths.get_full_path("clip", clip_name1)
- clip_path2 = folder_paths.get_full_path("clip", clip_name2)
+ clip_path1 = folder_paths.get_full_path_or_raise("clip", clip_name1)
+ clip_path2 = folder_paths.get_full_path_or_raise("clip", clip_name2)
if type == "sdxl":
clip_type = comfy.sd.CLIPType.STABLE_DIFFUSION
elif type == "sd3":
@@ -924,7 +940,7 @@ class CLIPVisionLoader:
CATEGORY = "loaders"
def load_clip(self, clip_name):
- clip_path = folder_paths.get_full_path("clip_vision", clip_name)
+ clip_path = folder_paths.get_full_path_or_raise("clip_vision", clip_name)
clip_vision = comfy.clip_vision.load(clip_path)
return (clip_vision,)
@@ -954,7 +970,7 @@ class StyleModelLoader:
CATEGORY = "loaders"
def load_style_model(self, style_model_name):
- style_model_path = folder_paths.get_full_path("style_models", style_model_name)
+ style_model_path = folder_paths.get_full_path_or_raise("style_models", style_model_name)
style_model = comfy.sd.load_style_model(style_model_path)
return (style_model,)
@@ -1019,7 +1035,7 @@ class GLIGENLoader:
CATEGORY = "loaders"
def load_gligen(self, gligen_name):
- gligen_path = folder_paths.get_full_path("gligen", gligen_name)
+ gligen_path = folder_paths.get_full_path_or_raise("gligen", gligen_name)
gligen = comfy.sd.load_gligen(gligen_path)
return (gligen,)
@@ -1905,8 +1921,8 @@ NODE_DISPLAY_NAME_MAPPINGS = {
"ConditioningSetArea": "Conditioning (Set Area)",
"ConditioningSetAreaPercentage": "Conditioning (Set Area with Percentage)",
"ConditioningSetMask": "Conditioning (Set Mask)",
- "ControlNetApply": "Apply ControlNet",
- "ControlNetApplyAdvanced": "Apply ControlNet (Advanced)",
+ "ControlNetApply": "Apply ControlNet (OLD)",
+ "ControlNetApplyAdvanced": "Apply ControlNet",
# Latent
"VAEEncodeForInpaint": "VAE Encode (for Inpainting)",
"SetLatentNoiseMask": "Set Latent Noise Mask",
@@ -2090,6 +2106,8 @@ def init_builtin_extra_nodes():
"nodes_controlnet.py",
"nodes_hunyuan.py",
"nodes_flux.py",
+ "nodes_lora_extract.py",
+ "nodes_torch_compile.py",
]
import_failed = []
@@ -2118,3 +2136,5 @@ def init_extra_nodes(init_custom_nodes=True):
else:
logging.warning("Please do a: pip install -r requirements.txt")
logging.warning("")
+
+ return import_failed
diff --git a/notebooks/comfyui_colab.ipynb b/notebooks/comfyui_colab.ipynb
index ec83265b4..b1ed4ac9a 100644
--- a/notebooks/comfyui_colab.ipynb
+++ b/notebooks/comfyui_colab.ipynb
@@ -79,7 +79,7 @@
"#!wget -c https://huggingface.co/comfyanonymous/clip_vision_g/resolve/main/clip_vision_g.safetensors -P ./models/clip_vision/\n",
"\n",
"# SD1.5\n",
- "!wget -c https://huggingface.co/runwayml/stable-diffusion-v1-5/resolve/main/v1-5-pruned-emaonly.ckpt -P ./models/checkpoints/\n",
+ "!wget -c https://huggingface.co/Comfy-Org/stable-diffusion-v1-5-archive/resolve/main/v1-5-pruned-emaonly-fp16.safetensors -P ./models/checkpoints/\n",
"\n",
"# SD2\n",
"#!wget -c https://huggingface.co/stabilityai/stable-diffusion-2-1-base/resolve/main/v2-1_512-ema-pruned.safetensors -P ./models/checkpoints/\n",
diff --git a/pytest.ini b/pytest.ini
index 8b7a747e7..a224d8cbb 100644
--- a/pytest.ini
+++ b/pytest.ini
@@ -1,6 +1,7 @@
[pytest]
markers =
inference: mark as inference test (deselect with '-m "not inference"')
+ execution: mark as execution test (deselect with '-m "not execution"')
testpaths =
tests
tests-unit
diff --git a/script_examples/basic_api_example.py b/script_examples/basic_api_example.py
index 242d3175f..bc8ad7134 100644
--- a/script_examples/basic_api_example.py
+++ b/script_examples/basic_api_example.py
@@ -43,7 +43,7 @@ prompt_text = """
"4": {
"class_type": "CheckpointLoaderSimple",
"inputs": {
- "ckpt_name": "v1-5-pruned-emaonly.ckpt"
+ "ckpt_name": "v1-5-pruned-emaonly.safetensors"
}
},
"5": {
diff --git a/script_examples/websockets_api_example.py b/script_examples/websockets_api_example.py
index 57a6cbd9b..d696d2bba 100644
--- a/script_examples/websockets_api_example.py
+++ b/script_examples/websockets_api_example.py
@@ -38,18 +38,20 @@ def get_images(ws, prompt):
if data['node'] is None and data['prompt_id'] == prompt_id:
break #Execution is done
else:
+ # If you want to be able to decode the binary stream for latent previews, here is how you can do it:
+ # bytesIO = BytesIO(out[8:])
+ # preview_image = Image.open(bytesIO) # This is your preview in PIL image format, store it in a global
continue #previews are binary data
history = get_history(prompt_id)[prompt_id]
- for o in history['outputs']:
- for node_id in history['outputs']:
- node_output = history['outputs'][node_id]
- if 'images' in node_output:
- images_output = []
- for image in node_output['images']:
- image_data = get_image(image['filename'], image['subfolder'], image['type'])
- images_output.append(image_data)
- output_images[node_id] = images_output
+ for node_id in history['outputs']:
+ node_output = history['outputs'][node_id]
+ images_output = []
+ if 'images' in node_output:
+ for image in node_output['images']:
+ image_data = get_image(image['filename'], image['subfolder'], image['type'])
+ images_output.append(image_data)
+ output_images[node_id] = images_output
return output_images
@@ -85,7 +87,7 @@ prompt_text = """
"4": {
"class_type": "CheckpointLoaderSimple",
"inputs": {
- "ckpt_name": "v1-5-pruned-emaonly.ckpt"
+ "ckpt_name": "v1-5-pruned-emaonly.safetensors"
}
},
"5": {
@@ -152,7 +154,7 @@ prompt["3"]["inputs"]["seed"] = 5
ws = websocket.WebSocket()
ws.connect("ws://{}/ws?clientId={}".format(server_address, client_id))
images = get_images(ws, prompt)
-
+ws.close() # for in case this example is used in an environment where it will be repeatedly called, like in a Gradio app. otherwise, you'll randomly receive connection timeouts
#Commented out code to display the output images:
# for node_id in images:
diff --git a/script_examples/websockets_api_example_ws_images.py b/script_examples/websockets_api_example_ws_images.py
index 737488621..6508ecc99 100644
--- a/script_examples/websockets_api_example_ws_images.py
+++ b/script_examples/websockets_api_example_ws_images.py
@@ -81,7 +81,7 @@ prompt_text = """
"4": {
"class_type": "CheckpointLoaderSimple",
"inputs": {
- "ckpt_name": "v1-5-pruned-emaonly.ckpt"
+ "ckpt_name": "v1-5-pruned-emaonly.safetensors"
}
},
"5": {
@@ -147,7 +147,7 @@ prompt["3"]["inputs"]["seed"] = 5
ws = websocket.WebSocket()
ws.connect("ws://{}/ws?clientId={}".format(server_address, client_id))
images = get_images(ws, prompt)
-
+ws.close() # for in case this example is used in an environment where it will be repeatedly called, like in a Gradio app. otherwise, you'll randomly receive connection timeouts
#Commented out code to display the output images:
# for node_id in images:
diff --git a/server.py b/server.py
index 9d8269f22..f1971f2d2 100644
--- a/server.py
+++ b/server.py
@@ -12,6 +12,8 @@ import json
import glob
import struct
import ssl
+import socket
+import ipaddress
from PIL import Image, ImageOps
from PIL.PngImagePlugin import PngInfo
from io import BytesIO
@@ -29,6 +31,7 @@ from app.frontend_management import FrontendManager
from app.user_manager import UserManager
from model_filemanager import download_model, DownloadModelStatus
from typing import Optional
+from api_server.routes.internal.internal_routes import InternalRoutes
class BinaryEventTypes:
PREVIEW_IMAGE = 1
@@ -40,6 +43,21 @@ async def send_socket_catch_exception(function, message):
except (aiohttp.ClientError, aiohttp.ClientPayloadError, ConnectionResetError) as err:
logging.warning("send error: {}".format(err))
+def get_comfyui_version():
+ comfyui_version = "unknown"
+ repo_path = os.path.dirname(os.path.realpath(__file__))
+ try:
+ import pygit2
+ repo = pygit2.Repository(repo_path)
+ comfyui_version = repo.describe(describe_strategy=pygit2.GIT_DESCRIBE_TAGS)
+ except Exception:
+ try:
+ import subprocess
+ comfyui_version = subprocess.check_output(["git", "describe", "--tags"], cwd=repo_path).decode('utf-8')
+ except Exception as e:
+ logging.warning(f"Failed to get ComfyUI version: {e}")
+ return comfyui_version.strip()
+
@web.middleware
async def cache_control(request: web.Request, handler):
response: web.Response = await handler(request)
@@ -64,6 +82,68 @@ def create_cors_middleware(allowed_origin: str):
return cors_middleware
+def is_loopback(host):
+ if host is None:
+ return False
+ try:
+ if ipaddress.ip_address(host).is_loopback:
+ return True
+ else:
+ return False
+ except:
+ pass
+
+ loopback = False
+ for family in (socket.AF_INET, socket.AF_INET6):
+ try:
+ r = socket.getaddrinfo(host, None, family, socket.SOCK_STREAM)
+ for family, _, _, _, sockaddr in r:
+ if not ipaddress.ip_address(sockaddr[0]).is_loopback:
+ return loopback
+ else:
+ loopback = True
+ except socket.gaierror:
+ pass
+
+ return loopback
+
+
+def create_origin_only_middleware():
+ @web.middleware
+ async def origin_only_middleware(request: web.Request, handler):
+ #this code is used to prevent the case where a random website can queue comfy workflows by making a POST to 127.0.0.1 which browsers don't prevent for some dumb reason.
+ #in that case the Host and Origin hostnames won't match
+ #I know the proper fix would be to add a cookie but this should take care of the problem in the meantime
+ if 'Host' in request.headers and 'Origin' in request.headers:
+ host = request.headers['Host']
+ origin = request.headers['Origin']
+ host_domain = host.lower()
+ parsed = urllib.parse.urlparse(origin)
+ origin_domain = parsed.netloc.lower()
+ host_domain_parsed = urllib.parse.urlsplit('//' + host_domain)
+
+ #limit the check to when the host domain is localhost, this makes it slightly less safe but should still prevent the exploit
+ loopback = is_loopback(host_domain_parsed.hostname)
+
+ if parsed.port is None: #if origin doesn't have a port strip it from the host to handle weird browsers, same for host
+ host_domain = host_domain_parsed.hostname
+ if host_domain_parsed.port is None:
+ origin_domain = parsed.hostname
+
+ if loopback and host_domain is not None and origin_domain is not None and len(host_domain) > 0 and len(origin_domain) > 0:
+ if host_domain != origin_domain:
+ logging.warning("WARNING: request with non matching host and origin {} != {}, returning 403".format(host_domain, origin_domain))
+ return web.Response(status=403)
+
+ if request.method == "OPTIONS":
+ response = web.Response()
+ else:
+ response = await handler(request)
+
+ return response
+
+ return origin_only_middleware
+
class PromptServer():
def __init__(self, loop):
PromptServer.instance = self
@@ -72,6 +152,7 @@ class PromptServer():
mimetypes.types_map['.js'] = 'application/javascript; charset=utf-8'
self.user_manager = UserManager()
+ self.internal_routes = InternalRoutes()
self.supports = ["custom_nodes_from_web"]
self.prompt_queue = None
self.loop = loop
@@ -82,6 +163,8 @@ class PromptServer():
middlewares = [cache_control]
if args.enable_cors_header:
middlewares.append(create_cors_middleware(args.enable_cors_header))
+ else:
+ middlewares.append(create_origin_only_middleware())
max_upload_size = round(args.max_upload_size * 1024 * 1024)
self.app = web.Application(client_max_size=max_upload_size, middlewares=middlewares)
@@ -138,6 +221,20 @@ class PromptServer():
def get_embeddings(self):
embeddings = folder_paths.get_filename_list("embeddings")
return web.json_response(list(map(lambda a: os.path.splitext(a)[0], embeddings)))
+
+ @routes.get("/models")
+ def list_model_types(request):
+ model_types = list(folder_paths.folder_names_and_paths.keys())
+
+ return web.json_response(model_types)
+
+ @routes.get("/models/{folder}")
+ async def get_models(request):
+ folder = request.match_info.get("folder", None)
+ if not folder in folder_paths.folder_names_and_paths:
+ return web.Response(status=404)
+ files = folder_paths.get_filename_list(folder)
+ return web.json_response(files)
@routes.get("/extensions")
async def get_extensions(request):
@@ -390,16 +487,25 @@ class PromptServer():
return web.json_response(dt["__metadata__"])
@routes.get("/system_stats")
- async def get_queue(request):
+ async def system_stats(request):
device = comfy.model_management.get_torch_device()
device_name = comfy.model_management.get_torch_device_name(device)
+ cpu_device = comfy.model_management.torch.device("cpu")
+ ram_total = comfy.model_management.get_total_memory(cpu_device)
+ ram_free = comfy.model_management.get_free_memory(cpu_device)
vram_total, torch_vram_total = comfy.model_management.get_total_memory(device, torch_total_too=True)
vram_free, torch_vram_free = comfy.model_management.get_free_memory(device, torch_free_too=True)
+
system_stats = {
"system": {
"os": os.name,
+ "ram_total": ram_total,
+ "ram_free": ram_free,
+ "comfyui_version": get_comfyui_version(),
"python_version": sys.version,
- "embedded_python": os.path.split(os.path.split(sys.executable)[0])[1] == "python_embeded"
+ "pytorch_version": comfy.model_management.torch_version,
+ "embedded_python": os.path.split(os.path.split(sys.executable)[0])[1] == "python_embeded",
+ "argv": sys.argv
},
"devices": [
{
@@ -423,6 +529,7 @@ class PromptServer():
obj_class = nodes.NODE_CLASS_MAPPINGS[node_class]
info = {}
info['input'] = obj_class.INPUT_TYPES()
+ info['input_order'] = {key: list(value.keys()) for (key, value) in obj_class.INPUT_TYPES().items()}
info['output'] = obj_class.RETURN_TYPES
info['output_is_list'] = obj_class.OUTPUT_IS_LIST if hasattr(obj_class, 'OUTPUT_IS_LIST') else [False] * len(obj_class.RETURN_TYPES)
info['output_name'] = obj_class.RETURN_NAMES if hasattr(obj_class, 'RETURN_NAMES') else info['output']
@@ -441,18 +548,24 @@ class PromptServer():
if hasattr(obj_class, 'OUTPUT_TOOLTIPS'):
info['output_tooltips'] = obj_class.OUTPUT_TOOLTIPS
+
+ if getattr(obj_class, "DEPRECATED", False):
+ info['deprecated'] = True
+ if getattr(obj_class, "EXPERIMENTAL", False):
+ info['experimental'] = True
return info
@routes.get("/object_info")
async def get_object_info(request):
- out = {}
- for x in nodes.NODE_CLASS_MAPPINGS:
- try:
- out[x] = node_info(x)
- except Exception as e:
- logging.error(f"[ERROR] An error occurred while retrieving information for the '{x}' node.")
- logging.error(traceback.format_exc())
- return web.json_response(out)
+ with folder_paths.cache_helper:
+ out = {}
+ for x in nodes.NODE_CLASS_MAPPINGS:
+ try:
+ out[x] = node_info(x)
+ except Exception as e:
+ logging.error(f"[ERROR] An error occurred while retrieving information for the '{x}' node.")
+ logging.error(traceback.format_exc())
+ return web.json_response(out)
@routes.get("/object_info/{node_class}")
async def get_object_info_node(request):
@@ -569,15 +682,18 @@ class PromptServer():
@routes.post("/internal/models/download")
async def download_handler(request):
async def report_progress(filename: str, status: DownloadModelStatus):
- await self.send_json("download_progress", status.to_dict())
+ payload = status.to_dict()
+ payload['download_path'] = filename
+ await self.send_json("download_progress", payload)
data = await request.json()
url = data.get('url')
model_directory = data.get('model_directory')
+ folder_path = data.get('folder_path')
model_filename = data.get('model_filename')
progress_interval = data.get('progress_interval', 1.0) # In seconds, how often to report download progress.
- if not url or not model_directory or not model_filename:
+ if not url or not model_directory or not model_filename or not folder_path:
return web.json_response({"status": "error", "message": "Missing URL or folder path or filename"}, status=400)
session = self.client_session
@@ -585,7 +701,7 @@ class PromptServer():
logging.error("Client session is not initialized")
return web.Response(status=500)
- task = asyncio.create_task(download_model(lambda url: session.get(url), model_filename, url, model_directory, report_progress, progress_interval))
+ task = asyncio.create_task(download_model(lambda url: session.get(url), model_filename, url, model_directory, folder_path, report_progress, progress_interval))
await task
return web.json_response(task.result().to_dict())
@@ -596,6 +712,7 @@ class PromptServer():
def add_routes(self):
self.user_manager.add_routes(self.routes)
+ self.app.add_subapp('/internal', self.internal_routes.get_app())
# Prefix every route with /api for easier matching for delegation.
# This is very useful for frontend dev server, which need to forward
@@ -701,6 +818,9 @@ class PromptServer():
await self.send(*msg)
async def start(self, address, port, verbose=True, call_on_start=None):
+ await self.start_multi_address([(address, port)], call_on_start=call_on_start)
+
+ async def start_multi_address(self, addresses, call_on_start=None):
runner = web.AppRunner(self.app, access_log=None)
await runner.setup()
ssl_ctx = None
@@ -711,14 +831,26 @@ class PromptServer():
keyfile=args.tls_keyfile)
scheme = "https"
- site = web.TCPSite(runner, address, port, ssl_context=ssl_ctx)
- await site.start()
+ logging.info("Starting server\n")
+ for addr in addresses:
+ address = addr[0]
+ port = addr[1]
+ site = web.TCPSite(runner, address, port, ssl_context=ssl_ctx)
+ await site.start()
+
+ if not hasattr(self, 'address'):
+ self.address = address #TODO: remove this
+ self.port = port
+
+ if ':' in address:
+ address_print = "[{}]".format(address)
+ else:
+ address_print = address
+
+ logging.info("To see the GUI go to: {}://{}:{}".format(scheme, address_print, port))
- if verbose:
- logging.info("Starting server\n")
- logging.info("To see the GUI go to: {}://{}:{}".format(scheme, address, port))
if call_on_start is not None:
- call_on_start(scheme, address, port)
+ call_on_start(scheme, self.address, self.port)
def add_on_prompt_handler(self, handler):
self.on_prompt_handlers.append(handler)
diff --git a/tests-ui/.gitignore b/tests-ui/.gitignore
deleted file mode 100644
index b512c09d4..000000000
--- a/tests-ui/.gitignore
+++ /dev/null
@@ -1 +0,0 @@
-node_modules
\ No newline at end of file
diff --git a/tests-ui/afterSetup.js b/tests-ui/afterSetup.js
deleted file mode 100644
index 983f3af64..000000000
--- a/tests-ui/afterSetup.js
+++ /dev/null
@@ -1,9 +0,0 @@
-const { start } = require("./utils");
-const lg = require("./utils/litegraph");
-
-// Load things once per test file before to ensure its all warmed up for the tests
-beforeAll(async () => {
- lg.setup(global);
- await start({ resetEnv: true });
- lg.teardown(global);
-});
diff --git a/tests-ui/babel.config.json b/tests-ui/babel.config.json
deleted file mode 100644
index f27d6c397..000000000
--- a/tests-ui/babel.config.json
+++ /dev/null
@@ -1,4 +0,0 @@
-{
- "presets": ["@babel/preset-env"],
- "plugins": ["babel-plugin-transform-import-meta"]
-}
diff --git a/tests-ui/globalSetup.js b/tests-ui/globalSetup.js
deleted file mode 100644
index b9d97f58a..000000000
--- a/tests-ui/globalSetup.js
+++ /dev/null
@@ -1,14 +0,0 @@
-module.exports = async function () {
- global.ResizeObserver = class ResizeObserver {
- observe() {}
- unobserve() {}
- disconnect() {}
- };
-
- const { nop } = require("./utils/nopProxy");
- global.enableWebGLCanvas = nop;
-
- HTMLCanvasElement.prototype.getContext = nop;
-
- localStorage["Comfy.Settings.Comfy.Logging.Enabled"] = "false";
-};
diff --git a/tests-ui/jest.config.js b/tests-ui/jest.config.js
deleted file mode 100644
index 86fff5057..000000000
--- a/tests-ui/jest.config.js
+++ /dev/null
@@ -1,11 +0,0 @@
-/** @type {import('jest').Config} */
-const config = {
- testEnvironment: "jsdom",
- setupFiles: ["./globalSetup.js"],
- setupFilesAfterEnv: ["./afterSetup.js"],
- clearMocks: true,
- resetModules: true,
- testTimeout: 10000
-};
-
-module.exports = config;
diff --git a/tests-ui/package-lock.json b/tests-ui/package-lock.json
deleted file mode 100644
index 0f409ca24..000000000
--- a/tests-ui/package-lock.json
+++ /dev/null
@@ -1,5586 +0,0 @@
-{
- "name": "comfui-tests",
- "version": "1.0.0",
- "lockfileVersion": 3,
- "requires": true,
- "packages": {
- "": {
- "name": "comfui-tests",
- "version": "1.0.0",
- "license": "GPL-3.0",
- "devDependencies": {
- "@babel/preset-env": "^7.22.20",
- "@types/jest": "^29.5.5",
- "babel-plugin-transform-import-meta": "^2.2.1",
- "jest": "^29.7.0",
- "jest-environment-jsdom": "^29.7.0"
- }
- },
- "node_modules/@ampproject/remapping": {
- "version": "2.2.1",
- "resolved": "https://registry.npmjs.org/@ampproject/remapping/-/remapping-2.2.1.tgz",
- "integrity": "sha512-lFMjJTrFL3j7L9yBxwYfCq2k6qqwHyzuUl/XBnif78PWTJYyL/dfowQHWE3sp6U6ZzqWiiIZnpTMO96zhkjwtg==",
- "dev": true,
- "dependencies": {
- "@jridgewell/gen-mapping": "^0.3.0",
- "@jridgewell/trace-mapping": "^0.3.9"
- },
- "engines": {
- "node": ">=6.0.0"
- }
- },
- "node_modules/@babel/code-frame": {
- "version": "7.22.13",
- "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.22.13.tgz",
- "integrity": "sha512-XktuhWlJ5g+3TJXc5upd9Ks1HutSArik6jf2eAjYFyIOf4ej3RN+184cZbzDvbPnuTJIUhPKKJE3cIsYTiAT3w==",
- "dev": true,
- "dependencies": {
- "@babel/highlight": "^7.22.13",
- "chalk": "^2.4.2"
- },
- "engines": {
- "node": ">=6.9.0"
- }
- },
- "node_modules/@babel/code-frame/node_modules/ansi-styles": {
- "version": "3.2.1",
- "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz",
- "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==",
- "dev": true,
- "dependencies": {
- "color-convert": "^1.9.0"
- },
- "engines": {
- "node": ">=4"
- }
- },
- "node_modules/@babel/code-frame/node_modules/chalk": {
- "version": "2.4.2",
- "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz",
- "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==",
- "dev": true,
- "dependencies": {
- "ansi-styles": "^3.2.1",
- "escape-string-regexp": "^1.0.5",
- "supports-color": "^5.3.0"
- },
- "engines": {
- "node": ">=4"
- }
- },
- "node_modules/@babel/code-frame/node_modules/color-convert": {
- "version": "1.9.3",
- "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz",
- "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==",
- "dev": true,
- "dependencies": {
- "color-name": "1.1.3"
- }
- },
- "node_modules/@babel/code-frame/node_modules/color-name": {
- "version": "1.1.3",
- "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz",
- "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==",
- "dev": true
- },
- "node_modules/@babel/code-frame/node_modules/escape-string-regexp": {
- "version": "1.0.5",
- "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz",
- "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==",
- "dev": true,
- "engines": {
- "node": ">=0.8.0"
- }
- },
- "node_modules/@babel/code-frame/node_modules/has-flag": {
- "version": "3.0.0",
- "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz",
- "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==",
- "dev": true,
- "engines": {
- "node": ">=4"
- }
- },
- "node_modules/@babel/code-frame/node_modules/supports-color": {
- "version": "5.5.0",
- "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz",
- "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==",
- "dev": true,
- "dependencies": {
- "has-flag": "^3.0.0"
- },
- "engines": {
- "node": ">=4"
- }
- },
- "node_modules/@babel/compat-data": {
- "version": "7.22.20",
- "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.22.20.tgz",
- "integrity": "sha512-BQYjKbpXjoXwFW5jGqiizJQQT/aC7pFm9Ok1OWssonuguICi264lbgMzRp2ZMmRSlfkX6DsWDDcsrctK8Rwfiw==",
- "dev": true,
- "engines": {
- "node": ">=6.9.0"
- }
- },
- "node_modules/@babel/core": {
- "version": "7.23.0",
- "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.23.0.tgz",
- "integrity": "sha512-97z/ju/Jy1rZmDxybphrBuI+jtJjFVoz7Mr9yUQVVVi+DNZE333uFQeMOqcCIy1x3WYBIbWftUSLmbNXNT7qFQ==",
- "dev": true,
- "dependencies": {
- "@ampproject/remapping": "^2.2.0",
- "@babel/code-frame": "^7.22.13",
- "@babel/generator": "^7.23.0",
- "@babel/helper-compilation-targets": "^7.22.15",
- "@babel/helper-module-transforms": "^7.23.0",
- "@babel/helpers": "^7.23.0",
- "@babel/parser": "^7.23.0",
- "@babel/template": "^7.22.15",
- "@babel/traverse": "^7.23.0",
- "@babel/types": "^7.23.0",
- "convert-source-map": "^2.0.0",
- "debug": "^4.1.0",
- "gensync": "^1.0.0-beta.2",
- "json5": "^2.2.3",
- "semver": "^6.3.1"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/babel"
- }
- },
- "node_modules/@babel/generator": {
- "version": "7.23.0",
- "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.23.0.tgz",
- "integrity": "sha512-lN85QRR+5IbYrMWM6Y4pE/noaQtg4pNiqeNGX60eqOfo6gtEj6uw/JagelB8vVztSd7R6M5n1+PQkDbHbBRU4g==",
- "dev": true,
- "dependencies": {
- "@babel/types": "^7.23.0",
- "@jridgewell/gen-mapping": "^0.3.2",
- "@jridgewell/trace-mapping": "^0.3.17",
- "jsesc": "^2.5.1"
- },
- "engines": {
- "node": ">=6.9.0"
- }
- },
- "node_modules/@babel/helper-annotate-as-pure": {
- "version": "7.22.5",
- "resolved": "https://registry.npmjs.org/@babel/helper-annotate-as-pure/-/helper-annotate-as-pure-7.22.5.tgz",
- "integrity": "sha512-LvBTxu8bQSQkcyKOU+a1btnNFQ1dMAd0R6PyW3arXes06F6QLWLIrd681bxRPIXlrMGR3XYnW9JyML7dP3qgxg==",
- "dev": true,
- "dependencies": {
- "@babel/types": "^7.22.5"
- },
- "engines": {
- "node": ">=6.9.0"
- }
- },
- "node_modules/@babel/helper-builder-binary-assignment-operator-visitor": {
- "version": "7.22.15",
- "resolved": "https://registry.npmjs.org/@babel/helper-builder-binary-assignment-operator-visitor/-/helper-builder-binary-assignment-operator-visitor-7.22.15.tgz",
- "integrity": "sha512-QkBXwGgaoC2GtGZRoma6kv7Szfv06khvhFav67ZExau2RaXzy8MpHSMO2PNoP2XtmQphJQRHFfg77Bq731Yizw==",
- "dev": true,
- "dependencies": {
- "@babel/types": "^7.22.15"
- },
- "engines": {
- "node": ">=6.9.0"
- }
- },
- "node_modules/@babel/helper-compilation-targets": {
- "version": "7.22.15",
- "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.22.15.tgz",
- "integrity": "sha512-y6EEzULok0Qvz8yyLkCvVX+02ic+By2UdOhylwUOvOn9dvYc9mKICJuuU1n1XBI02YWsNsnrY1kc6DVbjcXbtw==",
- "dev": true,
- "dependencies": {
- "@babel/compat-data": "^7.22.9",
- "@babel/helper-validator-option": "^7.22.15",
- "browserslist": "^4.21.9",
- "lru-cache": "^5.1.1",
- "semver": "^6.3.1"
- },
- "engines": {
- "node": ">=6.9.0"
- }
- },
- "node_modules/@babel/helper-create-class-features-plugin": {
- "version": "7.22.15",
- "resolved": "https://registry.npmjs.org/@babel/helper-create-class-features-plugin/-/helper-create-class-features-plugin-7.22.15.tgz",
- "integrity": "sha512-jKkwA59IXcvSaiK2UN45kKwSC9o+KuoXsBDvHvU/7BecYIp8GQ2UwrVvFgJASUT+hBnwJx6MhvMCuMzwZZ7jlg==",
- "dev": true,
- "dependencies": {
- "@babel/helper-annotate-as-pure": "^7.22.5",
- "@babel/helper-environment-visitor": "^7.22.5",
- "@babel/helper-function-name": "^7.22.5",
- "@babel/helper-member-expression-to-functions": "^7.22.15",
- "@babel/helper-optimise-call-expression": "^7.22.5",
- "@babel/helper-replace-supers": "^7.22.9",
- "@babel/helper-skip-transparent-expression-wrappers": "^7.22.5",
- "@babel/helper-split-export-declaration": "^7.22.6",
- "semver": "^6.3.1"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0"
- }
- },
- "node_modules/@babel/helper-create-regexp-features-plugin": {
- "version": "7.22.15",
- "resolved": "https://registry.npmjs.org/@babel/helper-create-regexp-features-plugin/-/helper-create-regexp-features-plugin-7.22.15.tgz",
- "integrity": "sha512-29FkPLFjn4TPEa3RE7GpW+qbE8tlsu3jntNYNfcGsc49LphF1PQIiD+vMZ1z1xVOKt+93khA9tc2JBs3kBjA7w==",
- "dev": true,
- "dependencies": {
- "@babel/helper-annotate-as-pure": "^7.22.5",
- "regexpu-core": "^5.3.1",
- "semver": "^6.3.1"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0"
- }
- },
- "node_modules/@babel/helper-define-polyfill-provider": {
- "version": "0.4.2",
- "resolved": "https://registry.npmjs.org/@babel/helper-define-polyfill-provider/-/helper-define-polyfill-provider-0.4.2.tgz",
- "integrity": "sha512-k0qnnOqHn5dK9pZpfD5XXZ9SojAITdCKRn2Lp6rnDGzIbaP0rHyMPk/4wsSxVBVz4RfN0q6VpXWP2pDGIoQ7hw==",
- "dev": true,
- "dependencies": {
- "@babel/helper-compilation-targets": "^7.22.6",
- "@babel/helper-plugin-utils": "^7.22.5",
- "debug": "^4.1.1",
- "lodash.debounce": "^4.0.8",
- "resolve": "^1.14.2"
- },
- "peerDependencies": {
- "@babel/core": "^7.4.0 || ^8.0.0-0 <8.0.0"
- }
- },
- "node_modules/@babel/helper-environment-visitor": {
- "version": "7.22.20",
- "resolved": "https://registry.npmjs.org/@babel/helper-environment-visitor/-/helper-environment-visitor-7.22.20.tgz",
- "integrity": "sha512-zfedSIzFhat/gFhWfHtgWvlec0nqB9YEIVrpuwjruLlXfUSnA8cJB0miHKwqDnQ7d32aKo2xt88/xZptwxbfhA==",
- "dev": true,
- "engines": {
- "node": ">=6.9.0"
- }
- },
- "node_modules/@babel/helper-function-name": {
- "version": "7.23.0",
- "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.23.0.tgz",
- "integrity": "sha512-OErEqsrxjZTJciZ4Oo+eoZqeW9UIiOcuYKRJA4ZAgV9myA+pOXhhmpfNCKjEH/auVfEYVFJ6y1Tc4r0eIApqiw==",
- "dev": true,
- "dependencies": {
- "@babel/template": "^7.22.15",
- "@babel/types": "^7.23.0"
- },
- "engines": {
- "node": ">=6.9.0"
- }
- },
- "node_modules/@babel/helper-hoist-variables": {
- "version": "7.22.5",
- "resolved": "https://registry.npmjs.org/@babel/helper-hoist-variables/-/helper-hoist-variables-7.22.5.tgz",
- "integrity": "sha512-wGjk9QZVzvknA6yKIUURb8zY3grXCcOZt+/7Wcy8O2uctxhplmUPkOdlgoNhmdVee2c92JXbf1xpMtVNbfoxRw==",
- "dev": true,
- "dependencies": {
- "@babel/types": "^7.22.5"
- },
- "engines": {
- "node": ">=6.9.0"
- }
- },
- "node_modules/@babel/helper-member-expression-to-functions": {
- "version": "7.23.0",
- "resolved": "https://registry.npmjs.org/@babel/helper-member-expression-to-functions/-/helper-member-expression-to-functions-7.23.0.tgz",
- "integrity": "sha512-6gfrPwh7OuT6gZyJZvd6WbTfrqAo7vm4xCzAXOusKqq/vWdKXphTpj5klHKNmRUU6/QRGlBsyU9mAIPaWHlqJA==",
- "dev": true,
- "dependencies": {
- "@babel/types": "^7.23.0"
- },
- "engines": {
- "node": ">=6.9.0"
- }
- },
- "node_modules/@babel/helper-module-imports": {
- "version": "7.22.15",
- "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.22.15.tgz",
- "integrity": "sha512-0pYVBnDKZO2fnSPCrgM/6WMc7eS20Fbok+0r88fp+YtWVLZrp4CkafFGIp+W0VKw4a22sgebPT99y+FDNMdP4w==",
- "dev": true,
- "dependencies": {
- "@babel/types": "^7.22.15"
- },
- "engines": {
- "node": ">=6.9.0"
- }
- },
- "node_modules/@babel/helper-module-transforms": {
- "version": "7.23.0",
- "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.23.0.tgz",
- "integrity": "sha512-WhDWw1tdrlT0gMgUJSlX0IQvoO1eN279zrAUbVB+KpV2c3Tylz8+GnKOLllCS6Z/iZQEyVYxhZVUdPTqs2YYPw==",
- "dev": true,
- "dependencies": {
- "@babel/helper-environment-visitor": "^7.22.20",
- "@babel/helper-module-imports": "^7.22.15",
- "@babel/helper-simple-access": "^7.22.5",
- "@babel/helper-split-export-declaration": "^7.22.6",
- "@babel/helper-validator-identifier": "^7.22.20"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0"
- }
- },
- "node_modules/@babel/helper-optimise-call-expression": {
- "version": "7.22.5",
- "resolved": "https://registry.npmjs.org/@babel/helper-optimise-call-expression/-/helper-optimise-call-expression-7.22.5.tgz",
- "integrity": "sha512-HBwaojN0xFRx4yIvpwGqxiV2tUfl7401jlok564NgB9EHS1y6QT17FmKWm4ztqjeVdXLuC4fSvHc5ePpQjoTbw==",
- "dev": true,
- "dependencies": {
- "@babel/types": "^7.22.5"
- },
- "engines": {
- "node": ">=6.9.0"
- }
- },
- "node_modules/@babel/helper-plugin-utils": {
- "version": "7.22.5",
- "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.22.5.tgz",
- "integrity": "sha512-uLls06UVKgFG9QD4OeFYLEGteMIAa5kpTPcFL28yuCIIzsf6ZyKZMllKVOCZFhiZ5ptnwX4mtKdWCBE/uT4amg==",
- "dev": true,
- "engines": {
- "node": ">=6.9.0"
- }
- },
- "node_modules/@babel/helper-remap-async-to-generator": {
- "version": "7.22.20",
- "resolved": "https://registry.npmjs.org/@babel/helper-remap-async-to-generator/-/helper-remap-async-to-generator-7.22.20.tgz",
- "integrity": "sha512-pBGyV4uBqOns+0UvhsTO8qgl8hO89PmiDYv+/COyp1aeMcmfrfruz+/nCMFiYyFF/Knn0yfrC85ZzNFjembFTw==",
- "dev": true,
- "dependencies": {
- "@babel/helper-annotate-as-pure": "^7.22.5",
- "@babel/helper-environment-visitor": "^7.22.20",
- "@babel/helper-wrap-function": "^7.22.20"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0"
- }
- },
- "node_modules/@babel/helper-replace-supers": {
- "version": "7.22.20",
- "resolved": "https://registry.npmjs.org/@babel/helper-replace-supers/-/helper-replace-supers-7.22.20.tgz",
- "integrity": "sha512-qsW0In3dbwQUbK8kejJ4R7IHVGwHJlV6lpG6UA7a9hSa2YEiAib+N1T2kr6PEeUT+Fl7najmSOS6SmAwCHK6Tw==",
- "dev": true,
- "dependencies": {
- "@babel/helper-environment-visitor": "^7.22.20",
- "@babel/helper-member-expression-to-functions": "^7.22.15",
- "@babel/helper-optimise-call-expression": "^7.22.5"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0"
- }
- },
- "node_modules/@babel/helper-simple-access": {
- "version": "7.22.5",
- "resolved": "https://registry.npmjs.org/@babel/helper-simple-access/-/helper-simple-access-7.22.5.tgz",
- "integrity": "sha512-n0H99E/K+Bika3++WNL17POvo4rKWZ7lZEp1Q+fStVbUi8nxPQEBOlTmCOxW/0JsS56SKKQ+ojAe2pHKJHN35w==",
- "dev": true,
- "dependencies": {
- "@babel/types": "^7.22.5"
- },
- "engines": {
- "node": ">=6.9.0"
- }
- },
- "node_modules/@babel/helper-skip-transparent-expression-wrappers": {
- "version": "7.22.5",
- "resolved": "https://registry.npmjs.org/@babel/helper-skip-transparent-expression-wrappers/-/helper-skip-transparent-expression-wrappers-7.22.5.tgz",
- "integrity": "sha512-tK14r66JZKiC43p8Ki33yLBVJKlQDFoA8GYN67lWCDCqoL6EMMSuM9b+Iff2jHaM/RRFYl7K+iiru7hbRqNx8Q==",
- "dev": true,
- "dependencies": {
- "@babel/types": "^7.22.5"
- },
- "engines": {
- "node": ">=6.9.0"
- }
- },
- "node_modules/@babel/helper-split-export-declaration": {
- "version": "7.22.6",
- "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.22.6.tgz",
- "integrity": "sha512-AsUnxuLhRYsisFiaJwvp1QF+I3KjD5FOxut14q/GzovUe6orHLesW2C7d754kRm53h5gqrz6sFl6sxc4BVtE/g==",
- "dev": true,
- "dependencies": {
- "@babel/types": "^7.22.5"
- },
- "engines": {
- "node": ">=6.9.0"
- }
- },
- "node_modules/@babel/helper-string-parser": {
- "version": "7.22.5",
- "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.22.5.tgz",
- "integrity": "sha512-mM4COjgZox8U+JcXQwPijIZLElkgEpO5rsERVDJTc2qfCDfERyob6k5WegS14SX18IIjv+XD+GrqNumY5JRCDw==",
- "dev": true,
- "engines": {
- "node": ">=6.9.0"
- }
- },
- "node_modules/@babel/helper-validator-identifier": {
- "version": "7.22.20",
- "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.22.20.tgz",
- "integrity": "sha512-Y4OZ+ytlatR8AI+8KZfKuL5urKp7qey08ha31L8b3BwewJAoJamTzyvxPR/5D+KkdJCGPq/+8TukHBlY10FX9A==",
- "dev": true,
- "engines": {
- "node": ">=6.9.0"
- }
- },
- "node_modules/@babel/helper-validator-option": {
- "version": "7.22.15",
- "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.22.15.tgz",
- "integrity": "sha512-bMn7RmyFjY/mdECUbgn9eoSY4vqvacUnS9i9vGAGttgFWesO6B4CYWA7XlpbWgBt71iv/hfbPlynohStqnu5hA==",
- "dev": true,
- "engines": {
- "node": ">=6.9.0"
- }
- },
- "node_modules/@babel/helper-wrap-function": {
- "version": "7.22.20",
- "resolved": "https://registry.npmjs.org/@babel/helper-wrap-function/-/helper-wrap-function-7.22.20.tgz",
- "integrity": "sha512-pms/UwkOpnQe/PDAEdV/d7dVCoBbB+R4FvYoHGZz+4VPcg7RtYy2KP7S2lbuWM6FCSgob5wshfGESbC/hzNXZw==",
- "dev": true,
- "dependencies": {
- "@babel/helper-function-name": "^7.22.5",
- "@babel/template": "^7.22.15",
- "@babel/types": "^7.22.19"
- },
- "engines": {
- "node": ">=6.9.0"
- }
- },
- "node_modules/@babel/helpers": {
- "version": "7.23.1",
- "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.23.1.tgz",
- "integrity": "sha512-chNpneuK18yW5Oxsr+t553UZzzAs3aZnFm4bxhebsNTeshrC95yA7l5yl7GBAG+JG1rF0F7zzD2EixK9mWSDoA==",
- "dev": true,
- "dependencies": {
- "@babel/template": "^7.22.15",
- "@babel/traverse": "^7.23.0",
- "@babel/types": "^7.23.0"
- },
- "engines": {
- "node": ">=6.9.0"
- }
- },
- "node_modules/@babel/highlight": {
- "version": "7.22.20",
- "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.22.20.tgz",
- "integrity": "sha512-dkdMCN3py0+ksCgYmGG8jKeGA/8Tk+gJwSYYlFGxG5lmhfKNoAy004YpLxpS1W2J8m/EK2Ew+yOs9pVRwO89mg==",
- "dev": true,
- "dependencies": {
- "@babel/helper-validator-identifier": "^7.22.20",
- "chalk": "^2.4.2",
- "js-tokens": "^4.0.0"
- },
- "engines": {
- "node": ">=6.9.0"
- }
- },
- "node_modules/@babel/highlight/node_modules/ansi-styles": {
- "version": "3.2.1",
- "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz",
- "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==",
- "dev": true,
- "dependencies": {
- "color-convert": "^1.9.0"
- },
- "engines": {
- "node": ">=4"
- }
- },
- "node_modules/@babel/highlight/node_modules/chalk": {
- "version": "2.4.2",
- "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz",
- "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==",
- "dev": true,
- "dependencies": {
- "ansi-styles": "^3.2.1",
- "escape-string-regexp": "^1.0.5",
- "supports-color": "^5.3.0"
- },
- "engines": {
- "node": ">=4"
- }
- },
- "node_modules/@babel/highlight/node_modules/color-convert": {
- "version": "1.9.3",
- "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz",
- "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==",
- "dev": true,
- "dependencies": {
- "color-name": "1.1.3"
- }
- },
- "node_modules/@babel/highlight/node_modules/color-name": {
- "version": "1.1.3",
- "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz",
- "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==",
- "dev": true
- },
- "node_modules/@babel/highlight/node_modules/escape-string-regexp": {
- "version": "1.0.5",
- "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz",
- "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==",
- "dev": true,
- "engines": {
- "node": ">=0.8.0"
- }
- },
- "node_modules/@babel/highlight/node_modules/has-flag": {
- "version": "3.0.0",
- "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz",
- "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==",
- "dev": true,
- "engines": {
- "node": ">=4"
- }
- },
- "node_modules/@babel/highlight/node_modules/supports-color": {
- "version": "5.5.0",
- "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz",
- "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==",
- "dev": true,
- "dependencies": {
- "has-flag": "^3.0.0"
- },
- "engines": {
- "node": ">=4"
- }
- },
- "node_modules/@babel/parser": {
- "version": "7.23.0",
- "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.23.0.tgz",
- "integrity": "sha512-vvPKKdMemU85V9WE/l5wZEmImpCtLqbnTvqDS2U1fJ96KrxoW7KrXhNsNCblQlg8Ck4b85yxdTyelsMUgFUXiw==",
- "dev": true,
- "bin": {
- "parser": "bin/babel-parser.js"
- },
- "engines": {
- "node": ">=6.0.0"
- }
- },
- "node_modules/@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression": {
- "version": "7.22.15",
- "resolved": "https://registry.npmjs.org/@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression/-/plugin-bugfix-safari-id-destructuring-collision-in-function-expression-7.22.15.tgz",
- "integrity": "sha512-FB9iYlz7rURmRJyXRKEnalYPPdn87H5no108cyuQQyMwlpJ2SJtpIUBI27kdTin956pz+LPypkPVPUTlxOmrsg==",
- "dev": true,
- "dependencies": {
- "@babel/helper-plugin-utils": "^7.22.5"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0"
- }
- },
- "node_modules/@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining": {
- "version": "7.22.15",
- "resolved": "https://registry.npmjs.org/@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining/-/plugin-bugfix-v8-spread-parameters-in-optional-chaining-7.22.15.tgz",
- "integrity": "sha512-Hyph9LseGvAeeXzikV88bczhsrLrIZqDPxO+sSmAunMPaGrBGhfMWzCPYTtiW9t+HzSE2wtV8e5cc5P6r1xMDQ==",
- "dev": true,
- "dependencies": {
- "@babel/helper-plugin-utils": "^7.22.5",
- "@babel/helper-skip-transparent-expression-wrappers": "^7.22.5",
- "@babel/plugin-transform-optional-chaining": "^7.22.15"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.13.0"
- }
- },
- "node_modules/@babel/plugin-proposal-private-property-in-object": {
- "version": "7.21.0-placeholder-for-preset-env.2",
- "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-private-property-in-object/-/plugin-proposal-private-property-in-object-7.21.0-placeholder-for-preset-env.2.tgz",
- "integrity": "sha512-SOSkfJDddaM7mak6cPEpswyTRnuRltl429hMraQEglW+OkovnCzsiszTmsrlY//qLFjCpQDFRvjdm2wA5pPm9w==",
- "dev": true,
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-syntax-async-generators": {
- "version": "7.8.4",
- "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-async-generators/-/plugin-syntax-async-generators-7.8.4.tgz",
- "integrity": "sha512-tycmZxkGfZaxhMRbXlPXuVFpdWlXpir2W4AMhSJgRKzk/eDlIXOhb2LHWoLpDF7TEHylV5zNhykX6KAgHJmTNw==",
- "dev": true,
- "dependencies": {
- "@babel/helper-plugin-utils": "^7.8.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-syntax-bigint": {
- "version": "7.8.3",
- "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-bigint/-/plugin-syntax-bigint-7.8.3.tgz",
- "integrity": "sha512-wnTnFlG+YxQm3vDxpGE57Pj0srRU4sHE/mDkt1qv2YJJSeUAec2ma4WLUnUPeKjyrfntVwe/N6dCXpU+zL3Npg==",
- "dev": true,
- "dependencies": {
- "@babel/helper-plugin-utils": "^7.8.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-syntax-class-properties": {
- "version": "7.12.13",
- "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-class-properties/-/plugin-syntax-class-properties-7.12.13.tgz",
- "integrity": "sha512-fm4idjKla0YahUNgFNLCB0qySdsoPiZP3iQE3rky0mBUtMZ23yDJ9SJdg6dXTSDnulOVqiF3Hgr9nbXvXTQZYA==",
- "dev": true,
- "dependencies": {
- "@babel/helper-plugin-utils": "^7.12.13"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-syntax-class-static-block": {
- "version": "7.14.5",
- "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-class-static-block/-/plugin-syntax-class-static-block-7.14.5.tgz",
- "integrity": "sha512-b+YyPmr6ldyNnM6sqYeMWE+bgJcJpO6yS4QD7ymxgH34GBPNDM/THBh8iunyvKIZztiwLH4CJZ0RxTk9emgpjw==",
- "dev": true,
- "dependencies": {
- "@babel/helper-plugin-utils": "^7.14.5"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-syntax-dynamic-import": {
- "version": "7.8.3",
- "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-dynamic-import/-/plugin-syntax-dynamic-import-7.8.3.tgz",
- "integrity": "sha512-5gdGbFon+PszYzqs83S3E5mpi7/y/8M9eC90MRTZfduQOYW76ig6SOSPNe41IG5LoP3FGBn2N0RjVDSQiS94kQ==",
- "dev": true,
- "dependencies": {
- "@babel/helper-plugin-utils": "^7.8.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-syntax-export-namespace-from": {
- "version": "7.8.3",
- "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-export-namespace-from/-/plugin-syntax-export-namespace-from-7.8.3.tgz",
- "integrity": "sha512-MXf5laXo6c1IbEbegDmzGPwGNTsHZmEy6QGznu5Sh2UCWvueywb2ee+CCE4zQiZstxU9BMoQO9i6zUFSY0Kj0Q==",
- "dev": true,
- "dependencies": {
- "@babel/helper-plugin-utils": "^7.8.3"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-syntax-import-assertions": {
- "version": "7.22.5",
- "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-assertions/-/plugin-syntax-import-assertions-7.22.5.tgz",
- "integrity": "sha512-rdV97N7KqsRzeNGoWUOK6yUsWarLjE5Su/Snk9IYPU9CwkWHs4t+rTGOvffTR8XGkJMTAdLfO0xVnXm8wugIJg==",
- "dev": true,
- "dependencies": {
- "@babel/helper-plugin-utils": "^7.22.5"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-syntax-import-attributes": {
- "version": "7.22.5",
- "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-attributes/-/plugin-syntax-import-attributes-7.22.5.tgz",
- "integrity": "sha512-KwvoWDeNKPETmozyFE0P2rOLqh39EoQHNjqizrI5B8Vt0ZNS7M56s7dAiAqbYfiAYOuIzIh96z3iR2ktgu3tEg==",
- "dev": true,
- "dependencies": {
- "@babel/helper-plugin-utils": "^7.22.5"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-syntax-import-meta": {
- "version": "7.10.4",
- "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-meta/-/plugin-syntax-import-meta-7.10.4.tgz",
- "integrity": "sha512-Yqfm+XDx0+Prh3VSeEQCPU81yC+JWZ2pDPFSS4ZdpfZhp4MkFMaDC1UqseovEKwSUpnIL7+vK+Clp7bfh0iD7g==",
- "dev": true,
- "dependencies": {
- "@babel/helper-plugin-utils": "^7.10.4"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-syntax-json-strings": {
- "version": "7.8.3",
- "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-json-strings/-/plugin-syntax-json-strings-7.8.3.tgz",
- "integrity": "sha512-lY6kdGpWHvjoe2vk4WrAapEuBR69EMxZl+RoGRhrFGNYVK8mOPAW8VfbT/ZgrFbXlDNiiaxQnAtgVCZ6jv30EA==",
- "dev": true,
- "dependencies": {
- "@babel/helper-plugin-utils": "^7.8.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-syntax-jsx": {
- "version": "7.22.5",
- "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.22.5.tgz",
- "integrity": "sha512-gvyP4hZrgrs/wWMaocvxZ44Hw0b3W8Pe+cMxc8V1ULQ07oh8VNbIRaoD1LRZVTvD+0nieDKjfgKg89sD7rrKrg==",
- "dev": true,
- "dependencies": {
- "@babel/helper-plugin-utils": "^7.22.5"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-syntax-logical-assignment-operators": {
- "version": "7.10.4",
- "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-logical-assignment-operators/-/plugin-syntax-logical-assignment-operators-7.10.4.tgz",
- "integrity": "sha512-d8waShlpFDinQ5MtvGU9xDAOzKH47+FFoney2baFIoMr952hKOLp1HR7VszoZvOsV/4+RRszNY7D17ba0te0ig==",
- "dev": true,
- "dependencies": {
- "@babel/helper-plugin-utils": "^7.10.4"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-syntax-nullish-coalescing-operator": {
- "version": "7.8.3",
- "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-nullish-coalescing-operator/-/plugin-syntax-nullish-coalescing-operator-7.8.3.tgz",
- "integrity": "sha512-aSff4zPII1u2QD7y+F8oDsz19ew4IGEJg9SVW+bqwpwtfFleiQDMdzA/R+UlWDzfnHFCxxleFT0PMIrR36XLNQ==",
- "dev": true,
- "dependencies": {
- "@babel/helper-plugin-utils": "^7.8.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-syntax-numeric-separator": {
- "version": "7.10.4",
- "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-numeric-separator/-/plugin-syntax-numeric-separator-7.10.4.tgz",
- "integrity": "sha512-9H6YdfkcK/uOnY/K7/aA2xpzaAgkQn37yzWUMRK7OaPOqOpGS1+n0H5hxT9AUw9EsSjPW8SVyMJwYRtWs3X3ug==",
- "dev": true,
- "dependencies": {
- "@babel/helper-plugin-utils": "^7.10.4"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-syntax-object-rest-spread": {
- "version": "7.8.3",
- "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-object-rest-spread/-/plugin-syntax-object-rest-spread-7.8.3.tgz",
- "integrity": "sha512-XoqMijGZb9y3y2XskN+P1wUGiVwWZ5JmoDRwx5+3GmEplNyVM2s2Dg8ILFQm8rWM48orGy5YpI5Bl8U1y7ydlA==",
- "dev": true,
- "dependencies": {
- "@babel/helper-plugin-utils": "^7.8.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-syntax-optional-catch-binding": {
- "version": "7.8.3",
- "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-catch-binding/-/plugin-syntax-optional-catch-binding-7.8.3.tgz",
- "integrity": "sha512-6VPD0Pc1lpTqw0aKoeRTMiB+kWhAoT24PA+ksWSBrFtl5SIRVpZlwN3NNPQjehA2E/91FV3RjLWoVTglWcSV3Q==",
- "dev": true,
- "dependencies": {
- "@babel/helper-plugin-utils": "^7.8.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-syntax-optional-chaining": {
- "version": "7.8.3",
- "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-chaining/-/plugin-syntax-optional-chaining-7.8.3.tgz",
- "integrity": "sha512-KoK9ErH1MBlCPxV0VANkXW2/dw4vlbGDrFgz8bmUsBGYkFRcbRwMh6cIJubdPrkxRwuGdtCk0v/wPTKbQgBjkg==",
- "dev": true,
- "dependencies": {
- "@babel/helper-plugin-utils": "^7.8.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-syntax-private-property-in-object": {
- "version": "7.14.5",
- "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-private-property-in-object/-/plugin-syntax-private-property-in-object-7.14.5.tgz",
- "integrity": "sha512-0wVnp9dxJ72ZUJDV27ZfbSj6iHLoytYZmh3rFcxNnvsJF3ktkzLDZPy/mA17HGsaQT3/DQsWYX1f1QGWkCoVUg==",
- "dev": true,
- "dependencies": {
- "@babel/helper-plugin-utils": "^7.14.5"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-syntax-top-level-await": {
- "version": "7.14.5",
- "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-top-level-await/-/plugin-syntax-top-level-await-7.14.5.tgz",
- "integrity": "sha512-hx++upLv5U1rgYfwe1xBQUhRmU41NEvpUvrp8jkrSCdvGSnM5/qdRMtylJ6PG5OFkBaHkbTAKTnd3/YyESRHFw==",
- "dev": true,
- "dependencies": {
- "@babel/helper-plugin-utils": "^7.14.5"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-syntax-typescript": {
- "version": "7.22.5",
- "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-typescript/-/plugin-syntax-typescript-7.22.5.tgz",
- "integrity": "sha512-1mS2o03i7t1c6VzH6fdQ3OA8tcEIxwG18zIPRp+UY1Ihv6W+XZzBCVxExF9upussPXJ0xE9XRHwMoNs1ep/nRQ==",
- "dev": true,
- "dependencies": {
- "@babel/helper-plugin-utils": "^7.22.5"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-syntax-unicode-sets-regex": {
- "version": "7.18.6",
- "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-unicode-sets-regex/-/plugin-syntax-unicode-sets-regex-7.18.6.tgz",
- "integrity": "sha512-727YkEAPwSIQTv5im8QHz3upqp92JTWhidIC81Tdx4VJYIte/VndKf1qKrfnnhPLiPghStWfvC/iFaMCQu7Nqg==",
- "dev": true,
- "dependencies": {
- "@babel/helper-create-regexp-features-plugin": "^7.18.6",
- "@babel/helper-plugin-utils": "^7.18.6"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0"
- }
- },
- "node_modules/@babel/plugin-transform-arrow-functions": {
- "version": "7.22.5",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-arrow-functions/-/plugin-transform-arrow-functions-7.22.5.tgz",
- "integrity": "sha512-26lTNXoVRdAnsaDXPpvCNUq+OVWEVC6bx7Vvz9rC53F2bagUWW4u4ii2+h8Fejfh7RYqPxn+libeFBBck9muEw==",
- "dev": true,
- "dependencies": {
- "@babel/helper-plugin-utils": "^7.22.5"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-transform-async-generator-functions": {
- "version": "7.22.15",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-async-generator-functions/-/plugin-transform-async-generator-functions-7.22.15.tgz",
- "integrity": "sha512-jBm1Es25Y+tVoTi5rfd5t1KLmL8ogLKpXszboWOTTtGFGz2RKnQe2yn7HbZ+kb/B8N0FVSGQo874NSlOU1T4+w==",
- "dev": true,
- "dependencies": {
- "@babel/helper-environment-visitor": "^7.22.5",
- "@babel/helper-plugin-utils": "^7.22.5",
- "@babel/helper-remap-async-to-generator": "^7.22.9",
- "@babel/plugin-syntax-async-generators": "^7.8.4"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-transform-async-to-generator": {
- "version": "7.22.5",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-async-to-generator/-/plugin-transform-async-to-generator-7.22.5.tgz",
- "integrity": "sha512-b1A8D8ZzE/VhNDoV1MSJTnpKkCG5bJo+19R4o4oy03zM7ws8yEMK755j61Dc3EyvdysbqH5BOOTquJ7ZX9C6vQ==",
- "dev": true,
- "dependencies": {
- "@babel/helper-module-imports": "^7.22.5",
- "@babel/helper-plugin-utils": "^7.22.5",
- "@babel/helper-remap-async-to-generator": "^7.22.5"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-transform-block-scoped-functions": {
- "version": "7.22.5",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-block-scoped-functions/-/plugin-transform-block-scoped-functions-7.22.5.tgz",
- "integrity": "sha512-tdXZ2UdknEKQWKJP1KMNmuF5Lx3MymtMN/pvA+p/VEkhK8jVcQ1fzSy8KM9qRYhAf2/lV33hoMPKI/xaI9sADA==",
- "dev": true,
- "dependencies": {
- "@babel/helper-plugin-utils": "^7.22.5"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-transform-block-scoping": {
- "version": "7.23.0",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-block-scoping/-/plugin-transform-block-scoping-7.23.0.tgz",
- "integrity": "sha512-cOsrbmIOXmf+5YbL99/S49Y3j46k/T16b9ml8bm9lP6N9US5iQ2yBK7gpui1pg0V/WMcXdkfKbTb7HXq9u+v4g==",
- "dev": true,
- "dependencies": {
- "@babel/helper-plugin-utils": "^7.22.5"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-transform-class-properties": {
- "version": "7.22.5",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-class-properties/-/plugin-transform-class-properties-7.22.5.tgz",
- "integrity": "sha512-nDkQ0NfkOhPTq8YCLiWNxp1+f9fCobEjCb0n8WdbNUBc4IB5V7P1QnX9IjpSoquKrXF5SKojHleVNs2vGeHCHQ==",
- "dev": true,
- "dependencies": {
- "@babel/helper-create-class-features-plugin": "^7.22.5",
- "@babel/helper-plugin-utils": "^7.22.5"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-transform-class-static-block": {
- "version": "7.22.11",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-class-static-block/-/plugin-transform-class-static-block-7.22.11.tgz",
- "integrity": "sha512-GMM8gGmqI7guS/llMFk1bJDkKfn3v3C4KHK9Yg1ey5qcHcOlKb0QvcMrgzvxo+T03/4szNh5lghY+fEC98Kq9g==",
- "dev": true,
- "dependencies": {
- "@babel/helper-create-class-features-plugin": "^7.22.11",
- "@babel/helper-plugin-utils": "^7.22.5",
- "@babel/plugin-syntax-class-static-block": "^7.14.5"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.12.0"
- }
- },
- "node_modules/@babel/plugin-transform-classes": {
- "version": "7.22.15",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-classes/-/plugin-transform-classes-7.22.15.tgz",
- "integrity": "sha512-VbbC3PGjBdE0wAWDdHM9G8Gm977pnYI0XpqMd6LrKISj8/DJXEsWqgRuTYaNE9Bv0JGhTZUzHDlMk18IpOuoqw==",
- "dev": true,
- "dependencies": {
- "@babel/helper-annotate-as-pure": "^7.22.5",
- "@babel/helper-compilation-targets": "^7.22.15",
- "@babel/helper-environment-visitor": "^7.22.5",
- "@babel/helper-function-name": "^7.22.5",
- "@babel/helper-optimise-call-expression": "^7.22.5",
- "@babel/helper-plugin-utils": "^7.22.5",
- "@babel/helper-replace-supers": "^7.22.9",
- "@babel/helper-split-export-declaration": "^7.22.6",
- "globals": "^11.1.0"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-transform-computed-properties": {
- "version": "7.22.5",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-computed-properties/-/plugin-transform-computed-properties-7.22.5.tgz",
- "integrity": "sha512-4GHWBgRf0krxPX+AaPtgBAlTgTeZmqDynokHOX7aqqAB4tHs3U2Y02zH6ETFdLZGcg9UQSD1WCmkVrE9ErHeOg==",
- "dev": true,
- "dependencies": {
- "@babel/helper-plugin-utils": "^7.22.5",
- "@babel/template": "^7.22.5"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-transform-destructuring": {
- "version": "7.23.0",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-destructuring/-/plugin-transform-destructuring-7.23.0.tgz",
- "integrity": "sha512-vaMdgNXFkYrB+8lbgniSYWHsgqK5gjaMNcc84bMIOMRLH0L9AqYq3hwMdvnyqj1OPqea8UtjPEuS/DCenah1wg==",
- "dev": true,
- "dependencies": {
- "@babel/helper-plugin-utils": "^7.22.5"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-transform-dotall-regex": {
- "version": "7.22.5",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-dotall-regex/-/plugin-transform-dotall-regex-7.22.5.tgz",
- "integrity": "sha512-5/Yk9QxCQCl+sOIB1WelKnVRxTJDSAIxtJLL2/pqL14ZVlbH0fUQUZa/T5/UnQtBNgghR7mfB8ERBKyKPCi7Vw==",
- "dev": true,
- "dependencies": {
- "@babel/helper-create-regexp-features-plugin": "^7.22.5",
- "@babel/helper-plugin-utils": "^7.22.5"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-transform-duplicate-keys": {
- "version": "7.22.5",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-duplicate-keys/-/plugin-transform-duplicate-keys-7.22.5.tgz",
- "integrity": "sha512-dEnYD+9BBgld5VBXHnF/DbYGp3fqGMsyxKbtD1mDyIA7AkTSpKXFhCVuj/oQVOoALfBs77DudA0BE4d5mcpmqw==",
- "dev": true,
- "dependencies": {
- "@babel/helper-plugin-utils": "^7.22.5"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-transform-dynamic-import": {
- "version": "7.22.11",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-dynamic-import/-/plugin-transform-dynamic-import-7.22.11.tgz",
- "integrity": "sha512-g/21plo58sfteWjaO0ZNVb+uEOkJNjAaHhbejrnBmu011l/eNDScmkbjCC3l4FKb10ViaGU4aOkFznSu2zRHgA==",
- "dev": true,
- "dependencies": {
- "@babel/helper-plugin-utils": "^7.22.5",
- "@babel/plugin-syntax-dynamic-import": "^7.8.3"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-transform-exponentiation-operator": {
- "version": "7.22.5",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-exponentiation-operator/-/plugin-transform-exponentiation-operator-7.22.5.tgz",
- "integrity": "sha512-vIpJFNM/FjZ4rh1myqIya9jXwrwwgFRHPjT3DkUA9ZLHuzox8jiXkOLvwm1H+PQIP3CqfC++WPKeuDi0Sjdj1g==",
- "dev": true,
- "dependencies": {
- "@babel/helper-builder-binary-assignment-operator-visitor": "^7.22.5",
- "@babel/helper-plugin-utils": "^7.22.5"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-transform-export-namespace-from": {
- "version": "7.22.11",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-export-namespace-from/-/plugin-transform-export-namespace-from-7.22.11.tgz",
- "integrity": "sha512-xa7aad7q7OiT8oNZ1mU7NrISjlSkVdMbNxn9IuLZyL9AJEhs1Apba3I+u5riX1dIkdptP5EKDG5XDPByWxtehw==",
- "dev": true,
- "dependencies": {
- "@babel/helper-plugin-utils": "^7.22.5",
- "@babel/plugin-syntax-export-namespace-from": "^7.8.3"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-transform-for-of": {
- "version": "7.22.15",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-for-of/-/plugin-transform-for-of-7.22.15.tgz",
- "integrity": "sha512-me6VGeHsx30+xh9fbDLLPi0J1HzmeIIyenoOQHuw2D4m2SAU3NrspX5XxJLBpqn5yrLzrlw2Iy3RA//Bx27iOA==",
- "dev": true,
- "dependencies": {
- "@babel/helper-plugin-utils": "^7.22.5"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-transform-function-name": {
- "version": "7.22.5",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-function-name/-/plugin-transform-function-name-7.22.5.tgz",
- "integrity": "sha512-UIzQNMS0p0HHiQm3oelztj+ECwFnj+ZRV4KnguvlsD2of1whUeM6o7wGNj6oLwcDoAXQ8gEqfgC24D+VdIcevg==",
- "dev": true,
- "dependencies": {
- "@babel/helper-compilation-targets": "^7.22.5",
- "@babel/helper-function-name": "^7.22.5",
- "@babel/helper-plugin-utils": "^7.22.5"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-transform-json-strings": {
- "version": "7.22.11",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-json-strings/-/plugin-transform-json-strings-7.22.11.tgz",
- "integrity": "sha512-CxT5tCqpA9/jXFlme9xIBCc5RPtdDq3JpkkhgHQqtDdiTnTI0jtZ0QzXhr5DILeYifDPp2wvY2ad+7+hLMW5Pw==",
- "dev": true,
- "dependencies": {
- "@babel/helper-plugin-utils": "^7.22.5",
- "@babel/plugin-syntax-json-strings": "^7.8.3"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-transform-literals": {
- "version": "7.22.5",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-literals/-/plugin-transform-literals-7.22.5.tgz",
- "integrity": "sha512-fTLj4D79M+mepcw3dgFBTIDYpbcB9Sm0bpm4ppXPaO+U+PKFFyV9MGRvS0gvGw62sd10kT5lRMKXAADb9pWy8g==",
- "dev": true,
- "dependencies": {
- "@babel/helper-plugin-utils": "^7.22.5"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-transform-logical-assignment-operators": {
- "version": "7.22.11",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-logical-assignment-operators/-/plugin-transform-logical-assignment-operators-7.22.11.tgz",
- "integrity": "sha512-qQwRTP4+6xFCDV5k7gZBF3C31K34ut0tbEcTKxlX/0KXxm9GLcO14p570aWxFvVzx6QAfPgq7gaeIHXJC8LswQ==",
- "dev": true,
- "dependencies": {
- "@babel/helper-plugin-utils": "^7.22.5",
- "@babel/plugin-syntax-logical-assignment-operators": "^7.10.4"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-transform-member-expression-literals": {
- "version": "7.22.5",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-member-expression-literals/-/plugin-transform-member-expression-literals-7.22.5.tgz",
- "integrity": "sha512-RZEdkNtzzYCFl9SE9ATaUMTj2hqMb4StarOJLrZRbqqU4HSBE7UlBw9WBWQiDzrJZJdUWiMTVDI6Gv/8DPvfew==",
- "dev": true,
- "dependencies": {
- "@babel/helper-plugin-utils": "^7.22.5"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-transform-modules-amd": {
- "version": "7.23.0",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-amd/-/plugin-transform-modules-amd-7.23.0.tgz",
- "integrity": "sha512-xWT5gefv2HGSm4QHtgc1sYPbseOyf+FFDo2JbpE25GWl5BqTGO9IMwTYJRoIdjsF85GE+VegHxSCUt5EvoYTAw==",
- "dev": true,
- "dependencies": {
- "@babel/helper-module-transforms": "^7.23.0",
- "@babel/helper-plugin-utils": "^7.22.5"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-transform-modules-commonjs": {
- "version": "7.23.0",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-commonjs/-/plugin-transform-modules-commonjs-7.23.0.tgz",
- "integrity": "sha512-32Xzss14/UVc7k9g775yMIvkVK8xwKE0DPdP5JTapr3+Z9w4tzeOuLNY6BXDQR6BdnzIlXnCGAzsk/ICHBLVWQ==",
- "dev": true,
- "dependencies": {
- "@babel/helper-module-transforms": "^7.23.0",
- "@babel/helper-plugin-utils": "^7.22.5",
- "@babel/helper-simple-access": "^7.22.5"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-transform-modules-systemjs": {
- "version": "7.23.0",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-systemjs/-/plugin-transform-modules-systemjs-7.23.0.tgz",
- "integrity": "sha512-qBej6ctXZD2f+DhlOC9yO47yEYgUh5CZNz/aBoH4j/3NOlRfJXJbY7xDQCqQVf9KbrqGzIWER1f23doHGrIHFg==",
- "dev": true,
- "dependencies": {
- "@babel/helper-hoist-variables": "^7.22.5",
- "@babel/helper-module-transforms": "^7.23.0",
- "@babel/helper-plugin-utils": "^7.22.5",
- "@babel/helper-validator-identifier": "^7.22.20"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-transform-modules-umd": {
- "version": "7.22.5",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-umd/-/plugin-transform-modules-umd-7.22.5.tgz",
- "integrity": "sha512-+S6kzefN/E1vkSsKx8kmQuqeQsvCKCd1fraCM7zXm4SFoggI099Tr4G8U81+5gtMdUeMQ4ipdQffbKLX0/7dBQ==",
- "dev": true,
- "dependencies": {
- "@babel/helper-module-transforms": "^7.22.5",
- "@babel/helper-plugin-utils": "^7.22.5"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-transform-named-capturing-groups-regex": {
- "version": "7.22.5",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-named-capturing-groups-regex/-/plugin-transform-named-capturing-groups-regex-7.22.5.tgz",
- "integrity": "sha512-YgLLKmS3aUBhHaxp5hi1WJTgOUb/NCuDHzGT9z9WTt3YG+CPRhJs6nprbStx6DnWM4dh6gt7SU3sZodbZ08adQ==",
- "dev": true,
- "dependencies": {
- "@babel/helper-create-regexp-features-plugin": "^7.22.5",
- "@babel/helper-plugin-utils": "^7.22.5"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0"
- }
- },
- "node_modules/@babel/plugin-transform-new-target": {
- "version": "7.22.5",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-new-target/-/plugin-transform-new-target-7.22.5.tgz",
- "integrity": "sha512-AsF7K0Fx/cNKVyk3a+DW0JLo+Ua598/NxMRvxDnkpCIGFh43+h/v2xyhRUYf6oD8gE4QtL83C7zZVghMjHd+iw==",
- "dev": true,
- "dependencies": {
- "@babel/helper-plugin-utils": "^7.22.5"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-transform-nullish-coalescing-operator": {
- "version": "7.22.11",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-nullish-coalescing-operator/-/plugin-transform-nullish-coalescing-operator-7.22.11.tgz",
- "integrity": "sha512-YZWOw4HxXrotb5xsjMJUDlLgcDXSfO9eCmdl1bgW4+/lAGdkjaEvOnQ4p5WKKdUgSzO39dgPl0pTnfxm0OAXcg==",
- "dev": true,
- "dependencies": {
- "@babel/helper-plugin-utils": "^7.22.5",
- "@babel/plugin-syntax-nullish-coalescing-operator": "^7.8.3"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-transform-numeric-separator": {
- "version": "7.22.11",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-numeric-separator/-/plugin-transform-numeric-separator-7.22.11.tgz",
- "integrity": "sha512-3dzU4QGPsILdJbASKhF/V2TVP+gJya1PsueQCxIPCEcerqF21oEcrob4mzjsp2Py/1nLfF5m+xYNMDpmA8vffg==",
- "dev": true,
- "dependencies": {
- "@babel/helper-plugin-utils": "^7.22.5",
- "@babel/plugin-syntax-numeric-separator": "^7.10.4"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-transform-object-rest-spread": {
- "version": "7.22.15",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-object-rest-spread/-/plugin-transform-object-rest-spread-7.22.15.tgz",
- "integrity": "sha512-fEB+I1+gAmfAyxZcX1+ZUwLeAuuf8VIg67CTznZE0MqVFumWkh8xWtn58I4dxdVf080wn7gzWoF8vndOViJe9Q==",
- "dev": true,
- "dependencies": {
- "@babel/compat-data": "^7.22.9",
- "@babel/helper-compilation-targets": "^7.22.15",
- "@babel/helper-plugin-utils": "^7.22.5",
- "@babel/plugin-syntax-object-rest-spread": "^7.8.3",
- "@babel/plugin-transform-parameters": "^7.22.15"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-transform-object-super": {
- "version": "7.22.5",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-object-super/-/plugin-transform-object-super-7.22.5.tgz",
- "integrity": "sha512-klXqyaT9trSjIUrcsYIfETAzmOEZL3cBYqOYLJxBHfMFFggmXOv+NYSX/Jbs9mzMVESw/WycLFPRx8ba/b2Ipw==",
- "dev": true,
- "dependencies": {
- "@babel/helper-plugin-utils": "^7.22.5",
- "@babel/helper-replace-supers": "^7.22.5"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-transform-optional-catch-binding": {
- "version": "7.22.11",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-optional-catch-binding/-/plugin-transform-optional-catch-binding-7.22.11.tgz",
- "integrity": "sha512-rli0WxesXUeCJnMYhzAglEjLWVDF6ahb45HuprcmQuLidBJFWjNnOzssk2kuc6e33FlLaiZhG/kUIzUMWdBKaQ==",
- "dev": true,
- "dependencies": {
- "@babel/helper-plugin-utils": "^7.22.5",
- "@babel/plugin-syntax-optional-catch-binding": "^7.8.3"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-transform-optional-chaining": {
- "version": "7.23.0",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-optional-chaining/-/plugin-transform-optional-chaining-7.23.0.tgz",
- "integrity": "sha512-sBBGXbLJjxTzLBF5rFWaikMnOGOk/BmK6vVByIdEggZ7Vn6CvWXZyRkkLFK6WE0IF8jSliyOkUN6SScFgzCM0g==",
- "dev": true,
- "dependencies": {
- "@babel/helper-plugin-utils": "^7.22.5",
- "@babel/helper-skip-transparent-expression-wrappers": "^7.22.5",
- "@babel/plugin-syntax-optional-chaining": "^7.8.3"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-transform-parameters": {
- "version": "7.22.15",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-parameters/-/plugin-transform-parameters-7.22.15.tgz",
- "integrity": "sha512-hjk7qKIqhyzhhUvRT683TYQOFa/4cQKwQy7ALvTpODswN40MljzNDa0YldevS6tGbxwaEKVn502JmY0dP7qEtQ==",
- "dev": true,
- "dependencies": {
- "@babel/helper-plugin-utils": "^7.22.5"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-transform-private-methods": {
- "version": "7.22.5",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-private-methods/-/plugin-transform-private-methods-7.22.5.tgz",
- "integrity": "sha512-PPjh4gyrQnGe97JTalgRGMuU4icsZFnWkzicB/fUtzlKUqvsWBKEpPPfr5a2JiyirZkHxnAqkQMO5Z5B2kK3fA==",
- "dev": true,
- "dependencies": {
- "@babel/helper-create-class-features-plugin": "^7.22.5",
- "@babel/helper-plugin-utils": "^7.22.5"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-transform-private-property-in-object": {
- "version": "7.22.11",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-private-property-in-object/-/plugin-transform-private-property-in-object-7.22.11.tgz",
- "integrity": "sha512-sSCbqZDBKHetvjSwpyWzhuHkmW5RummxJBVbYLkGkaiTOWGxml7SXt0iWa03bzxFIx7wOj3g/ILRd0RcJKBeSQ==",
- "dev": true,
- "dependencies": {
- "@babel/helper-annotate-as-pure": "^7.22.5",
- "@babel/helper-create-class-features-plugin": "^7.22.11",
- "@babel/helper-plugin-utils": "^7.22.5",
- "@babel/plugin-syntax-private-property-in-object": "^7.14.5"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-transform-property-literals": {
- "version": "7.22.5",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-property-literals/-/plugin-transform-property-literals-7.22.5.tgz",
- "integrity": "sha512-TiOArgddK3mK/x1Qwf5hay2pxI6wCZnvQqrFSqbtg1GLl2JcNMitVH/YnqjP+M31pLUeTfzY1HAXFDnUBV30rQ==",
- "dev": true,
- "dependencies": {
- "@babel/helper-plugin-utils": "^7.22.5"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-transform-regenerator": {
- "version": "7.22.10",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-regenerator/-/plugin-transform-regenerator-7.22.10.tgz",
- "integrity": "sha512-F28b1mDt8KcT5bUyJc/U9nwzw6cV+UmTeRlXYIl2TNqMMJif0Jeey9/RQ3C4NOd2zp0/TRsDns9ttj2L523rsw==",
- "dev": true,
- "dependencies": {
- "@babel/helper-plugin-utils": "^7.22.5",
- "regenerator-transform": "^0.15.2"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-transform-reserved-words": {
- "version": "7.22.5",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-reserved-words/-/plugin-transform-reserved-words-7.22.5.tgz",
- "integrity": "sha512-DTtGKFRQUDm8svigJzZHzb/2xatPc6TzNvAIJ5GqOKDsGFYgAskjRulbR/vGsPKq3OPqtexnz327qYpP57RFyA==",
- "dev": true,
- "dependencies": {
- "@babel/helper-plugin-utils": "^7.22.5"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-transform-shorthand-properties": {
- "version": "7.22.5",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-shorthand-properties/-/plugin-transform-shorthand-properties-7.22.5.tgz",
- "integrity": "sha512-vM4fq9IXHscXVKzDv5itkO1X52SmdFBFcMIBZ2FRn2nqVYqw6dBexUgMvAjHW+KXpPPViD/Yo3GrDEBaRC0QYA==",
- "dev": true,
- "dependencies": {
- "@babel/helper-plugin-utils": "^7.22.5"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-transform-spread": {
- "version": "7.22.5",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-spread/-/plugin-transform-spread-7.22.5.tgz",
- "integrity": "sha512-5ZzDQIGyvN4w8+dMmpohL6MBo+l2G7tfC/O2Dg7/hjpgeWvUx8FzfeOKxGog9IimPa4YekaQ9PlDqTLOljkcxg==",
- "dev": true,
- "dependencies": {
- "@babel/helper-plugin-utils": "^7.22.5",
- "@babel/helper-skip-transparent-expression-wrappers": "^7.22.5"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-transform-sticky-regex": {
- "version": "7.22.5",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-sticky-regex/-/plugin-transform-sticky-regex-7.22.5.tgz",
- "integrity": "sha512-zf7LuNpHG0iEeiyCNwX4j3gDg1jgt1k3ZdXBKbZSoA3BbGQGvMiSvfbZRR3Dr3aeJe3ooWFZxOOG3IRStYp2Bw==",
- "dev": true,
- "dependencies": {
- "@babel/helper-plugin-utils": "^7.22.5"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-transform-template-literals": {
- "version": "7.22.5",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-template-literals/-/plugin-transform-template-literals-7.22.5.tgz",
- "integrity": "sha512-5ciOehRNf+EyUeewo8NkbQiUs4d6ZxiHo6BcBcnFlgiJfu16q0bQUw9Jvo0b0gBKFG1SMhDSjeKXSYuJLeFSMA==",
- "dev": true,
- "dependencies": {
- "@babel/helper-plugin-utils": "^7.22.5"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-transform-typeof-symbol": {
- "version": "7.22.5",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-typeof-symbol/-/plugin-transform-typeof-symbol-7.22.5.tgz",
- "integrity": "sha512-bYkI5lMzL4kPii4HHEEChkD0rkc+nvnlR6+o/qdqR6zrm0Sv/nodmyLhlq2DO0YKLUNd2VePmPRjJXSBh9OIdA==",
- "dev": true,
- "dependencies": {
- "@babel/helper-plugin-utils": "^7.22.5"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-transform-unicode-escapes": {
- "version": "7.22.10",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-unicode-escapes/-/plugin-transform-unicode-escapes-7.22.10.tgz",
- "integrity": "sha512-lRfaRKGZCBqDlRU3UIFovdp9c9mEvlylmpod0/OatICsSfuQ9YFthRo1tpTkGsklEefZdqlEFdY4A2dwTb6ohg==",
- "dev": true,
- "dependencies": {
- "@babel/helper-plugin-utils": "^7.22.5"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-transform-unicode-property-regex": {
- "version": "7.22.5",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-unicode-property-regex/-/plugin-transform-unicode-property-regex-7.22.5.tgz",
- "integrity": "sha512-HCCIb+CbJIAE6sXn5CjFQXMwkCClcOfPCzTlilJ8cUatfzwHlWQkbtV0zD338u9dZskwvuOYTuuaMaA8J5EI5A==",
- "dev": true,
- "dependencies": {
- "@babel/helper-create-regexp-features-plugin": "^7.22.5",
- "@babel/helper-plugin-utils": "^7.22.5"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-transform-unicode-regex": {
- "version": "7.22.5",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-unicode-regex/-/plugin-transform-unicode-regex-7.22.5.tgz",
- "integrity": "sha512-028laaOKptN5vHJf9/Arr/HiJekMd41hOEZYvNsrsXqJ7YPYuX2bQxh31fkZzGmq3YqHRJzYFFAVYvKfMPKqyg==",
- "dev": true,
- "dependencies": {
- "@babel/helper-create-regexp-features-plugin": "^7.22.5",
- "@babel/helper-plugin-utils": "^7.22.5"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/plugin-transform-unicode-sets-regex": {
- "version": "7.22.5",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-unicode-sets-regex/-/plugin-transform-unicode-sets-regex-7.22.5.tgz",
- "integrity": "sha512-lhMfi4FC15j13eKrh3DnYHjpGj6UKQHtNKTbtc1igvAhRy4+kLhV07OpLcsN0VgDEw/MjAvJO4BdMJsHwMhzCg==",
- "dev": true,
- "dependencies": {
- "@babel/helper-create-regexp-features-plugin": "^7.22.5",
- "@babel/helper-plugin-utils": "^7.22.5"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0"
- }
- },
- "node_modules/@babel/preset-env": {
- "version": "7.22.20",
- "resolved": "https://registry.npmjs.org/@babel/preset-env/-/preset-env-7.22.20.tgz",
- "integrity": "sha512-11MY04gGC4kSzlPHRfvVkNAZhUxOvm7DCJ37hPDnUENwe06npjIRAfInEMTGSb4LZK5ZgDFkv5hw0lGebHeTyg==",
- "dev": true,
- "dependencies": {
- "@babel/compat-data": "^7.22.20",
- "@babel/helper-compilation-targets": "^7.22.15",
- "@babel/helper-plugin-utils": "^7.22.5",
- "@babel/helper-validator-option": "^7.22.15",
- "@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression": "^7.22.15",
- "@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining": "^7.22.15",
- "@babel/plugin-proposal-private-property-in-object": "7.21.0-placeholder-for-preset-env.2",
- "@babel/plugin-syntax-async-generators": "^7.8.4",
- "@babel/plugin-syntax-class-properties": "^7.12.13",
- "@babel/plugin-syntax-class-static-block": "^7.14.5",
- "@babel/plugin-syntax-dynamic-import": "^7.8.3",
- "@babel/plugin-syntax-export-namespace-from": "^7.8.3",
- "@babel/plugin-syntax-import-assertions": "^7.22.5",
- "@babel/plugin-syntax-import-attributes": "^7.22.5",
- "@babel/plugin-syntax-import-meta": "^7.10.4",
- "@babel/plugin-syntax-json-strings": "^7.8.3",
- "@babel/plugin-syntax-logical-assignment-operators": "^7.10.4",
- "@babel/plugin-syntax-nullish-coalescing-operator": "^7.8.3",
- "@babel/plugin-syntax-numeric-separator": "^7.10.4",
- "@babel/plugin-syntax-object-rest-spread": "^7.8.3",
- "@babel/plugin-syntax-optional-catch-binding": "^7.8.3",
- "@babel/plugin-syntax-optional-chaining": "^7.8.3",
- "@babel/plugin-syntax-private-property-in-object": "^7.14.5",
- "@babel/plugin-syntax-top-level-await": "^7.14.5",
- "@babel/plugin-syntax-unicode-sets-regex": "^7.18.6",
- "@babel/plugin-transform-arrow-functions": "^7.22.5",
- "@babel/plugin-transform-async-generator-functions": "^7.22.15",
- "@babel/plugin-transform-async-to-generator": "^7.22.5",
- "@babel/plugin-transform-block-scoped-functions": "^7.22.5",
- "@babel/plugin-transform-block-scoping": "^7.22.15",
- "@babel/plugin-transform-class-properties": "^7.22.5",
- "@babel/plugin-transform-class-static-block": "^7.22.11",
- "@babel/plugin-transform-classes": "^7.22.15",
- "@babel/plugin-transform-computed-properties": "^7.22.5",
- "@babel/plugin-transform-destructuring": "^7.22.15",
- "@babel/plugin-transform-dotall-regex": "^7.22.5",
- "@babel/plugin-transform-duplicate-keys": "^7.22.5",
- "@babel/plugin-transform-dynamic-import": "^7.22.11",
- "@babel/plugin-transform-exponentiation-operator": "^7.22.5",
- "@babel/plugin-transform-export-namespace-from": "^7.22.11",
- "@babel/plugin-transform-for-of": "^7.22.15",
- "@babel/plugin-transform-function-name": "^7.22.5",
- "@babel/plugin-transform-json-strings": "^7.22.11",
- "@babel/plugin-transform-literals": "^7.22.5",
- "@babel/plugin-transform-logical-assignment-operators": "^7.22.11",
- "@babel/plugin-transform-member-expression-literals": "^7.22.5",
- "@babel/plugin-transform-modules-amd": "^7.22.5",
- "@babel/plugin-transform-modules-commonjs": "^7.22.15",
- "@babel/plugin-transform-modules-systemjs": "^7.22.11",
- "@babel/plugin-transform-modules-umd": "^7.22.5",
- "@babel/plugin-transform-named-capturing-groups-regex": "^7.22.5",
- "@babel/plugin-transform-new-target": "^7.22.5",
- "@babel/plugin-transform-nullish-coalescing-operator": "^7.22.11",
- "@babel/plugin-transform-numeric-separator": "^7.22.11",
- "@babel/plugin-transform-object-rest-spread": "^7.22.15",
- "@babel/plugin-transform-object-super": "^7.22.5",
- "@babel/plugin-transform-optional-catch-binding": "^7.22.11",
- "@babel/plugin-transform-optional-chaining": "^7.22.15",
- "@babel/plugin-transform-parameters": "^7.22.15",
- "@babel/plugin-transform-private-methods": "^7.22.5",
- "@babel/plugin-transform-private-property-in-object": "^7.22.11",
- "@babel/plugin-transform-property-literals": "^7.22.5",
- "@babel/plugin-transform-regenerator": "^7.22.10",
- "@babel/plugin-transform-reserved-words": "^7.22.5",
- "@babel/plugin-transform-shorthand-properties": "^7.22.5",
- "@babel/plugin-transform-spread": "^7.22.5",
- "@babel/plugin-transform-sticky-regex": "^7.22.5",
- "@babel/plugin-transform-template-literals": "^7.22.5",
- "@babel/plugin-transform-typeof-symbol": "^7.22.5",
- "@babel/plugin-transform-unicode-escapes": "^7.22.10",
- "@babel/plugin-transform-unicode-property-regex": "^7.22.5",
- "@babel/plugin-transform-unicode-regex": "^7.22.5",
- "@babel/plugin-transform-unicode-sets-regex": "^7.22.5",
- "@babel/preset-modules": "0.1.6-no-external-plugins",
- "@babel/types": "^7.22.19",
- "babel-plugin-polyfill-corejs2": "^0.4.5",
- "babel-plugin-polyfill-corejs3": "^0.8.3",
- "babel-plugin-polyfill-regenerator": "^0.5.2",
- "core-js-compat": "^3.31.0",
- "semver": "^6.3.1"
- },
- "engines": {
- "node": ">=6.9.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0"
- }
- },
- "node_modules/@babel/preset-modules": {
- "version": "0.1.6-no-external-plugins",
- "resolved": "https://registry.npmjs.org/@babel/preset-modules/-/preset-modules-0.1.6-no-external-plugins.tgz",
- "integrity": "sha512-HrcgcIESLm9aIR842yhJ5RWan/gebQUJ6E/E5+rf0y9o6oj7w0Br+sWuL6kEQ/o/AdfvR1Je9jG18/gnpwjEyA==",
- "dev": true,
- "dependencies": {
- "@babel/helper-plugin-utils": "^7.0.0",
- "@babel/types": "^7.4.4",
- "esutils": "^2.0.2"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0-0 || ^8.0.0-0 <8.0.0"
- }
- },
- "node_modules/@babel/regjsgen": {
- "version": "0.8.0",
- "resolved": "https://registry.npmjs.org/@babel/regjsgen/-/regjsgen-0.8.0.tgz",
- "integrity": "sha512-x/rqGMdzj+fWZvCOYForTghzbtqPDZ5gPwaoNGHdgDfF2QA/XZbCBp4Moo5scrkAMPhB7z26XM/AaHuIJdgauA==",
- "dev": true
- },
- "node_modules/@babel/runtime": {
- "version": "7.23.1",
- "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.23.1.tgz",
- "integrity": "sha512-hC2v6p8ZSI/W0HUzh3V8C5g+NwSKzKPtJwSpTjwl0o297GP9+ZLQSkdvHz46CM3LqyoXxq+5G9komY+eSqSO0g==",
- "dev": true,
- "dependencies": {
- "regenerator-runtime": "^0.14.0"
- },
- "engines": {
- "node": ">=6.9.0"
- }
- },
- "node_modules/@babel/template": {
- "version": "7.22.15",
- "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.22.15.tgz",
- "integrity": "sha512-QPErUVm4uyJa60rkI73qneDacvdvzxshT3kksGqlGWYdOTIUOwJ7RDUL8sGqslY1uXWSL6xMFKEXDS3ox2uF0w==",
- "dev": true,
- "dependencies": {
- "@babel/code-frame": "^7.22.13",
- "@babel/parser": "^7.22.15",
- "@babel/types": "^7.22.15"
- },
- "engines": {
- "node": ">=6.9.0"
- }
- },
- "node_modules/@babel/traverse": {
- "version": "7.23.2",
- "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.23.2.tgz",
- "integrity": "sha512-azpe59SQ48qG6nu2CzcMLbxUudtN+dOM9kDbUqGq3HXUJRlo7i8fvPoxQUzYgLZ4cMVmuZgm8vvBpNeRhd6XSw==",
- "dev": true,
- "dependencies": {
- "@babel/code-frame": "^7.22.13",
- "@babel/generator": "^7.23.0",
- "@babel/helper-environment-visitor": "^7.22.20",
- "@babel/helper-function-name": "^7.23.0",
- "@babel/helper-hoist-variables": "^7.22.5",
- "@babel/helper-split-export-declaration": "^7.22.6",
- "@babel/parser": "^7.23.0",
- "@babel/types": "^7.23.0",
- "debug": "^4.1.0",
- "globals": "^11.1.0"
- },
- "engines": {
- "node": ">=6.9.0"
- }
- },
- "node_modules/@babel/types": {
- "version": "7.23.0",
- "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.23.0.tgz",
- "integrity": "sha512-0oIyUfKoI3mSqMvsxBdclDwxXKXAUA8v/apZbc+iSyARYou1o8ZGDxbUYyLFoW2arqS2jDGqJuZvv1d/io1axg==",
- "dev": true,
- "dependencies": {
- "@babel/helper-string-parser": "^7.22.5",
- "@babel/helper-validator-identifier": "^7.22.20",
- "to-fast-properties": "^2.0.0"
- },
- "engines": {
- "node": ">=6.9.0"
- }
- },
- "node_modules/@bcoe/v8-coverage": {
- "version": "0.2.3",
- "resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-0.2.3.tgz",
- "integrity": "sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==",
- "dev": true
- },
- "node_modules/@istanbuljs/load-nyc-config": {
- "version": "1.1.0",
- "resolved": "https://registry.npmjs.org/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz",
- "integrity": "sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ==",
- "dev": true,
- "dependencies": {
- "camelcase": "^5.3.1",
- "find-up": "^4.1.0",
- "get-package-type": "^0.1.0",
- "js-yaml": "^3.13.1",
- "resolve-from": "^5.0.0"
- },
- "engines": {
- "node": ">=8"
- }
- },
- "node_modules/@istanbuljs/schema": {
- "version": "0.1.3",
- "resolved": "https://registry.npmjs.org/@istanbuljs/schema/-/schema-0.1.3.tgz",
- "integrity": "sha512-ZXRY4jNvVgSVQ8DL3LTcakaAtXwTVUxE81hslsyD2AtoXW/wVob10HkOJ1X/pAlcI7D+2YoZKg5do8G/w6RYgA==",
- "dev": true,
- "engines": {
- "node": ">=8"
- }
- },
- "node_modules/@jest/console": {
- "version": "29.7.0",
- "resolved": "https://registry.npmjs.org/@jest/console/-/console-29.7.0.tgz",
- "integrity": "sha512-5Ni4CU7XHQi32IJ398EEP4RrB8eV09sXP2ROqD4bksHrnTree52PsxvX8tpL8LvTZ3pFzXyPbNQReSN41CAhOg==",
- "dev": true,
- "dependencies": {
- "@jest/types": "^29.6.3",
- "@types/node": "*",
- "chalk": "^4.0.0",
- "jest-message-util": "^29.7.0",
- "jest-util": "^29.7.0",
- "slash": "^3.0.0"
- },
- "engines": {
- "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
- }
- },
- "node_modules/@jest/core": {
- "version": "29.7.0",
- "resolved": "https://registry.npmjs.org/@jest/core/-/core-29.7.0.tgz",
- "integrity": "sha512-n7aeXWKMnGtDA48y8TLWJPJmLmmZ642Ceo78cYWEpiD7FzDgmNDV/GCVRorPABdXLJZ/9wzzgZAlHjXjxDHGsg==",
- "dev": true,
- "dependencies": {
- "@jest/console": "^29.7.0",
- "@jest/reporters": "^29.7.0",
- "@jest/test-result": "^29.7.0",
- "@jest/transform": "^29.7.0",
- "@jest/types": "^29.6.3",
- "@types/node": "*",
- "ansi-escapes": "^4.2.1",
- "chalk": "^4.0.0",
- "ci-info": "^3.2.0",
- "exit": "^0.1.2",
- "graceful-fs": "^4.2.9",
- "jest-changed-files": "^29.7.0",
- "jest-config": "^29.7.0",
- "jest-haste-map": "^29.7.0",
- "jest-message-util": "^29.7.0",
- "jest-regex-util": "^29.6.3",
- "jest-resolve": "^29.7.0",
- "jest-resolve-dependencies": "^29.7.0",
- "jest-runner": "^29.7.0",
- "jest-runtime": "^29.7.0",
- "jest-snapshot": "^29.7.0",
- "jest-util": "^29.7.0",
- "jest-validate": "^29.7.0",
- "jest-watcher": "^29.7.0",
- "micromatch": "^4.0.4",
- "pretty-format": "^29.7.0",
- "slash": "^3.0.0",
- "strip-ansi": "^6.0.0"
- },
- "engines": {
- "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
- },
- "peerDependencies": {
- "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0"
- },
- "peerDependenciesMeta": {
- "node-notifier": {
- "optional": true
- }
- }
- },
- "node_modules/@jest/environment": {
- "version": "29.7.0",
- "resolved": "https://registry.npmjs.org/@jest/environment/-/environment-29.7.0.tgz",
- "integrity": "sha512-aQIfHDq33ExsN4jP1NWGXhxgQ/wixs60gDiKO+XVMd8Mn0NWPWgc34ZQDTb2jKaUWQ7MuwoitXAsN2XVXNMpAw==",
- "dev": true,
- "dependencies": {
- "@jest/fake-timers": "^29.7.0",
- "@jest/types": "^29.6.3",
- "@types/node": "*",
- "jest-mock": "^29.7.0"
- },
- "engines": {
- "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
- }
- },
- "node_modules/@jest/expect": {
- "version": "29.7.0",
- "resolved": "https://registry.npmjs.org/@jest/expect/-/expect-29.7.0.tgz",
- "integrity": "sha512-8uMeAMycttpva3P1lBHB8VciS9V0XAr3GymPpipdyQXbBcuhkLQOSe8E/p92RyAdToS6ZD1tFkX+CkhoECE0dQ==",
- "dev": true,
- "dependencies": {
- "expect": "^29.7.0",
- "jest-snapshot": "^29.7.0"
- },
- "engines": {
- "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
- }
- },
- "node_modules/@jest/expect-utils": {
- "version": "29.7.0",
- "resolved": "https://registry.npmjs.org/@jest/expect-utils/-/expect-utils-29.7.0.tgz",
- "integrity": "sha512-GlsNBWiFQFCVi9QVSx7f5AgMeLxe9YCCs5PuP2O2LdjDAA8Jh9eX7lA1Jq/xdXw3Wb3hyvlFNfZIfcRetSzYcA==",
- "dev": true,
- "dependencies": {
- "jest-get-type": "^29.6.3"
- },
- "engines": {
- "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
- }
- },
- "node_modules/@jest/fake-timers": {
- "version": "29.7.0",
- "resolved": "https://registry.npmjs.org/@jest/fake-timers/-/fake-timers-29.7.0.tgz",
- "integrity": "sha512-q4DH1Ha4TTFPdxLsqDXK1d3+ioSL7yL5oCMJZgDYm6i+6CygW5E5xVr/D1HdsGxjt1ZWSfUAs9OxSB/BNelWrQ==",
- "dev": true,
- "dependencies": {
- "@jest/types": "^29.6.3",
- "@sinonjs/fake-timers": "^10.0.2",
- "@types/node": "*",
- "jest-message-util": "^29.7.0",
- "jest-mock": "^29.7.0",
- "jest-util": "^29.7.0"
- },
- "engines": {
- "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
- }
- },
- "node_modules/@jest/globals": {
- "version": "29.7.0",
- "resolved": "https://registry.npmjs.org/@jest/globals/-/globals-29.7.0.tgz",
- "integrity": "sha512-mpiz3dutLbkW2MNFubUGUEVLkTGiqW6yLVTA+JbP6fI6J5iL9Y0Nlg8k95pcF8ctKwCS7WVxteBs29hhfAotzQ==",
- "dev": true,
- "dependencies": {
- "@jest/environment": "^29.7.0",
- "@jest/expect": "^29.7.0",
- "@jest/types": "^29.6.3",
- "jest-mock": "^29.7.0"
- },
- "engines": {
- "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
- }
- },
- "node_modules/@jest/reporters": {
- "version": "29.7.0",
- "resolved": "https://registry.npmjs.org/@jest/reporters/-/reporters-29.7.0.tgz",
- "integrity": "sha512-DApq0KJbJOEzAFYjHADNNxAE3KbhxQB1y5Kplb5Waqw6zVbuWatSnMjE5gs8FUgEPmNsnZA3NCWl9NG0ia04Pg==",
- "dev": true,
- "dependencies": {
- "@bcoe/v8-coverage": "^0.2.3",
- "@jest/console": "^29.7.0",
- "@jest/test-result": "^29.7.0",
- "@jest/transform": "^29.7.0",
- "@jest/types": "^29.6.3",
- "@jridgewell/trace-mapping": "^0.3.18",
- "@types/node": "*",
- "chalk": "^4.0.0",
- "collect-v8-coverage": "^1.0.0",
- "exit": "^0.1.2",
- "glob": "^7.1.3",
- "graceful-fs": "^4.2.9",
- "istanbul-lib-coverage": "^3.0.0",
- "istanbul-lib-instrument": "^6.0.0",
- "istanbul-lib-report": "^3.0.0",
- "istanbul-lib-source-maps": "^4.0.0",
- "istanbul-reports": "^3.1.3",
- "jest-message-util": "^29.7.0",
- "jest-util": "^29.7.0",
- "jest-worker": "^29.7.0",
- "slash": "^3.0.0",
- "string-length": "^4.0.1",
- "strip-ansi": "^6.0.0",
- "v8-to-istanbul": "^9.0.1"
- },
- "engines": {
- "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
- },
- "peerDependencies": {
- "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0"
- },
- "peerDependenciesMeta": {
- "node-notifier": {
- "optional": true
- }
- }
- },
- "node_modules/@jest/schemas": {
- "version": "29.6.3",
- "resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-29.6.3.tgz",
- "integrity": "sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA==",
- "dev": true,
- "dependencies": {
- "@sinclair/typebox": "^0.27.8"
- },
- "engines": {
- "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
- }
- },
- "node_modules/@jest/source-map": {
- "version": "29.6.3",
- "resolved": "https://registry.npmjs.org/@jest/source-map/-/source-map-29.6.3.tgz",
- "integrity": "sha512-MHjT95QuipcPrpLM+8JMSzFx6eHp5Bm+4XeFDJlwsvVBjmKNiIAvasGK2fxz2WbGRlnvqehFbh07MMa7n3YJnw==",
- "dev": true,
- "dependencies": {
- "@jridgewell/trace-mapping": "^0.3.18",
- "callsites": "^3.0.0",
- "graceful-fs": "^4.2.9"
- },
- "engines": {
- "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
- }
- },
- "node_modules/@jest/test-result": {
- "version": "29.7.0",
- "resolved": "https://registry.npmjs.org/@jest/test-result/-/test-result-29.7.0.tgz",
- "integrity": "sha512-Fdx+tv6x1zlkJPcWXmMDAG2HBnaR9XPSd5aDWQVsfrZmLVT3lU1cwyxLgRmXR9yrq4NBoEm9BMsfgFzTQAbJYA==",
- "dev": true,
- "dependencies": {
- "@jest/console": "^29.7.0",
- "@jest/types": "^29.6.3",
- "@types/istanbul-lib-coverage": "^2.0.0",
- "collect-v8-coverage": "^1.0.0"
- },
- "engines": {
- "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
- }
- },
- "node_modules/@jest/test-sequencer": {
- "version": "29.7.0",
- "resolved": "https://registry.npmjs.org/@jest/test-sequencer/-/test-sequencer-29.7.0.tgz",
- "integrity": "sha512-GQwJ5WZVrKnOJuiYiAF52UNUJXgTZx1NHjFSEB0qEMmSZKAkdMoIzw/Cj6x6NF4AvV23AUqDpFzQkN/eYCYTxw==",
- "dev": true,
- "dependencies": {
- "@jest/test-result": "^29.7.0",
- "graceful-fs": "^4.2.9",
- "jest-haste-map": "^29.7.0",
- "slash": "^3.0.0"
- },
- "engines": {
- "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
- }
- },
- "node_modules/@jest/transform": {
- "version": "29.7.0",
- "resolved": "https://registry.npmjs.org/@jest/transform/-/transform-29.7.0.tgz",
- "integrity": "sha512-ok/BTPFzFKVMwO5eOHRrvnBVHdRy9IrsrW1GpMaQ9MCnilNLXQKmAX8s1YXDFaai9xJpac2ySzV0YeRRECr2Vw==",
- "dev": true,
- "dependencies": {
- "@babel/core": "^7.11.6",
- "@jest/types": "^29.6.3",
- "@jridgewell/trace-mapping": "^0.3.18",
- "babel-plugin-istanbul": "^6.1.1",
- "chalk": "^4.0.0",
- "convert-source-map": "^2.0.0",
- "fast-json-stable-stringify": "^2.1.0",
- "graceful-fs": "^4.2.9",
- "jest-haste-map": "^29.7.0",
- "jest-regex-util": "^29.6.3",
- "jest-util": "^29.7.0",
- "micromatch": "^4.0.4",
- "pirates": "^4.0.4",
- "slash": "^3.0.0",
- "write-file-atomic": "^4.0.2"
- },
- "engines": {
- "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
- }
- },
- "node_modules/@jest/types": {
- "version": "29.6.3",
- "resolved": "https://registry.npmjs.org/@jest/types/-/types-29.6.3.tgz",
- "integrity": "sha512-u3UPsIilWKOM3F9CXtrG8LEJmNxwoCQC/XVj4IKYXvvpx7QIi/Kg1LI5uDmDpKlac62NUtX7eLjRh+jVZcLOzw==",
- "dev": true,
- "dependencies": {
- "@jest/schemas": "^29.6.3",
- "@types/istanbul-lib-coverage": "^2.0.0",
- "@types/istanbul-reports": "^3.0.0",
- "@types/node": "*",
- "@types/yargs": "^17.0.8",
- "chalk": "^4.0.0"
- },
- "engines": {
- "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
- }
- },
- "node_modules/@jridgewell/gen-mapping": {
- "version": "0.3.3",
- "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.3.tgz",
- "integrity": "sha512-HLhSWOLRi875zjjMG/r+Nv0oCW8umGb0BgEhyX3dDX3egwZtB8PqLnjz3yedt8R5StBrzcg4aBpnh8UA9D1BoQ==",
- "dev": true,
- "dependencies": {
- "@jridgewell/set-array": "^1.0.1",
- "@jridgewell/sourcemap-codec": "^1.4.10",
- "@jridgewell/trace-mapping": "^0.3.9"
- },
- "engines": {
- "node": ">=6.0.0"
- }
- },
- "node_modules/@jridgewell/resolve-uri": {
- "version": "3.1.1",
- "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.1.tgz",
- "integrity": "sha512-dSYZh7HhCDtCKm4QakX0xFpsRDqjjtZf/kjI/v3T3Nwt5r8/qz/M19F9ySyOqU94SXBmeG9ttTul+YnR4LOxFA==",
- "dev": true,
- "engines": {
- "node": ">=6.0.0"
- }
- },
- "node_modules/@jridgewell/set-array": {
- "version": "1.1.2",
- "resolved": "https://registry.npmjs.org/@jridgewell/set-array/-/set-array-1.1.2.tgz",
- "integrity": "sha512-xnkseuNADM0gt2bs+BvhO0p78Mk762YnZdsuzFV018NoG1Sj1SCQvpSqa7XUaTam5vAGasABV9qXASMKnFMwMw==",
- "dev": true,
- "engines": {
- "node": ">=6.0.0"
- }
- },
- "node_modules/@jridgewell/sourcemap-codec": {
- "version": "1.4.15",
- "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.15.tgz",
- "integrity": "sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg==",
- "dev": true
- },
- "node_modules/@jridgewell/trace-mapping": {
- "version": "0.3.19",
- "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.19.tgz",
- "integrity": "sha512-kf37QtfW+Hwx/buWGMPcR60iF9ziHa6r/CZJIHbmcm4+0qrXiVdxegAH0F6yddEVQ7zdkjcGCgCzUu+BcbhQxw==",
- "dev": true,
- "dependencies": {
- "@jridgewell/resolve-uri": "^3.1.0",
- "@jridgewell/sourcemap-codec": "^1.4.14"
- }
- },
- "node_modules/@sinclair/typebox": {
- "version": "0.27.8",
- "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.27.8.tgz",
- "integrity": "sha512-+Fj43pSMwJs4KRrH/938Uf+uAELIgVBmQzg/q1YG10djyfA3TnrU8N8XzqCh/okZdszqBQTZf96idMfE5lnwTA==",
- "dev": true
- },
- "node_modules/@sinonjs/commons": {
- "version": "3.0.0",
- "resolved": "https://registry.npmjs.org/@sinonjs/commons/-/commons-3.0.0.tgz",
- "integrity": "sha512-jXBtWAF4vmdNmZgD5FoKsVLv3rPgDnLgPbU84LIJ3otV44vJlDRokVng5v8NFJdCf/da9legHcKaRuZs4L7faA==",
- "dev": true,
- "dependencies": {
- "type-detect": "4.0.8"
- }
- },
- "node_modules/@sinonjs/fake-timers": {
- "version": "10.3.0",
- "resolved": "https://registry.npmjs.org/@sinonjs/fake-timers/-/fake-timers-10.3.0.tgz",
- "integrity": "sha512-V4BG07kuYSUkTCSBHG8G8TNhM+F19jXFWnQtzj+we8DrkpSBCee9Z3Ms8yiGer/dlmhe35/Xdgyo3/0rQKg7YA==",
- "dev": true,
- "dependencies": {
- "@sinonjs/commons": "^3.0.0"
- }
- },
- "node_modules/@tootallnate/once": {
- "version": "2.0.0",
- "resolved": "https://registry.npmjs.org/@tootallnate/once/-/once-2.0.0.tgz",
- "integrity": "sha512-XCuKFP5PS55gnMVu3dty8KPatLqUoy/ZYzDzAGCQ8JNFCkLXzmI7vNHCR+XpbZaMWQK/vQubr7PkYq8g470J/A==",
- "dev": true,
- "engines": {
- "node": ">= 10"
- }
- },
- "node_modules/@types/babel__core": {
- "version": "7.20.2",
- "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.2.tgz",
- "integrity": "sha512-pNpr1T1xLUc2l3xJKuPtsEky3ybxN3m4fJkknfIpTCTfIZCDW57oAg+EfCgIIp2rvCe0Wn++/FfodDS4YXxBwA==",
- "dev": true,
- "dependencies": {
- "@babel/parser": "^7.20.7",
- "@babel/types": "^7.20.7",
- "@types/babel__generator": "*",
- "@types/babel__template": "*",
- "@types/babel__traverse": "*"
- }
- },
- "node_modules/@types/babel__generator": {
- "version": "7.6.5",
- "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.6.5.tgz",
- "integrity": "sha512-h9yIuWbJKdOPLJTbmSpPzkF67e659PbQDba7ifWm5BJ8xTv+sDmS7rFmywkWOvXedGTivCdeGSIIX8WLcRTz8w==",
- "dev": true,
- "dependencies": {
- "@babel/types": "^7.0.0"
- }
- },
- "node_modules/@types/babel__template": {
- "version": "7.4.2",
- "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.2.tgz",
- "integrity": "sha512-/AVzPICMhMOMYoSx9MoKpGDKdBRsIXMNByh1PXSZoa+v6ZoLa8xxtsT/uLQ/NJm0XVAWl/BvId4MlDeXJaeIZQ==",
- "dev": true,
- "dependencies": {
- "@babel/parser": "^7.1.0",
- "@babel/types": "^7.0.0"
- }
- },
- "node_modules/@types/babel__traverse": {
- "version": "7.20.2",
- "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.20.2.tgz",
- "integrity": "sha512-ojlGK1Hsfce93J0+kn3H5R73elidKUaZonirN33GSmgTUMpzI/MIFfSpF3haANe3G1bEBS9/9/QEqwTzwqFsKw==",
- "dev": true,
- "dependencies": {
- "@babel/types": "^7.20.7"
- }
- },
- "node_modules/@types/graceful-fs": {
- "version": "4.1.7",
- "resolved": "https://registry.npmjs.org/@types/graceful-fs/-/graceful-fs-4.1.7.tgz",
- "integrity": "sha512-MhzcwU8aUygZroVwL2jeYk6JisJrPl/oov/gsgGCue9mkgl9wjGbzReYQClxiUgFDnib9FuHqTndccKeZKxTRw==",
- "dev": true,
- "dependencies": {
- "@types/node": "*"
- }
- },
- "node_modules/@types/istanbul-lib-coverage": {
- "version": "2.0.4",
- "resolved": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.4.tgz",
- "integrity": "sha512-z/QT1XN4K4KYuslS23k62yDIDLwLFkzxOuMplDtObz0+y7VqJCaO2o+SPwHCvLFZh7xazvvoor2tA/hPz9ee7g==",
- "dev": true
- },
- "node_modules/@types/istanbul-lib-report": {
- "version": "3.0.1",
- "resolved": "https://registry.npmjs.org/@types/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz",
- "integrity": "sha512-gPQuzaPR5h/djlAv2apEG1HVOyj1IUs7GpfMZixU0/0KXT3pm64ylHuMUI1/Akh+sq/iikxg6Z2j+fcMDXaaTQ==",
- "dev": true,
- "dependencies": {
- "@types/istanbul-lib-coverage": "*"
- }
- },
- "node_modules/@types/istanbul-reports": {
- "version": "3.0.2",
- "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.2.tgz",
- "integrity": "sha512-kv43F9eb3Lhj+lr/Hn6OcLCs/sSM8bt+fIaP11rCYngfV6NVjzWXJ17owQtDQTL9tQ8WSLUrGsSJ6rJz0F1w1A==",
- "dev": true,
- "dependencies": {
- "@types/istanbul-lib-report": "*"
- }
- },
- "node_modules/@types/jest": {
- "version": "29.5.5",
- "resolved": "https://registry.npmjs.org/@types/jest/-/jest-29.5.5.tgz",
- "integrity": "sha512-ebylz2hnsWR9mYvmBFbXJXr+33UPc4+ZdxyDXh5w0FlPBTfCVN3wPL+kuOiQt3xvrK419v7XWeAs+AeOksafXg==",
- "dev": true,
- "dependencies": {
- "expect": "^29.0.0",
- "pretty-format": "^29.0.0"
- }
- },
- "node_modules/@types/jsdom": {
- "version": "20.0.1",
- "resolved": "https://registry.npmjs.org/@types/jsdom/-/jsdom-20.0.1.tgz",
- "integrity": "sha512-d0r18sZPmMQr1eG35u12FZfhIXNrnsPU/g5wvRKCUf/tOGilKKwYMYGqh33BNR6ba+2gkHw1EUiHoN3mn7E5IQ==",
- "dev": true,
- "dependencies": {
- "@types/node": "*",
- "@types/tough-cookie": "*",
- "parse5": "^7.0.0"
- }
- },
- "node_modules/@types/node": {
- "version": "20.8.3",
- "resolved": "https://registry.npmjs.org/@types/node/-/node-20.8.3.tgz",
- "integrity": "sha512-jxiZQFpb+NlH5kjW49vXxvxTjeeqlbsnTAdBTKpzEdPs9itay7MscYXz3Fo9VYFEsfQ6LJFitHad3faerLAjCw==",
- "dev": true
- },
- "node_modules/@types/stack-utils": {
- "version": "2.0.1",
- "resolved": "https://registry.npmjs.org/@types/stack-utils/-/stack-utils-2.0.1.tgz",
- "integrity": "sha512-Hl219/BT5fLAaz6NDkSuhzasy49dwQS/DSdu4MdggFB8zcXv7vflBI3xp7FEmkmdDkBUI2bPUNeMttp2knYdxw==",
- "dev": true
- },
- "node_modules/@types/tough-cookie": {
- "version": "4.0.3",
- "resolved": "https://registry.npmjs.org/@types/tough-cookie/-/tough-cookie-4.0.3.tgz",
- "integrity": "sha512-THo502dA5PzG/sfQH+42Lw3fvmYkceefOspdCwpHRul8ik2Jv1K8I5OZz1AT3/rs46kwgMCe9bSBmDLYkkOMGg==",
- "dev": true
- },
- "node_modules/@types/yargs": {
- "version": "17.0.28",
- "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.28.tgz",
- "integrity": "sha512-N3e3fkS86hNhtk6BEnc0rj3zcehaxx8QWhCROJkqpl5Zaoi7nAic3jH8q94jVD3zu5LGk+PUB6KAiDmimYOEQw==",
- "dev": true,
- "dependencies": {
- "@types/yargs-parser": "*"
- }
- },
- "node_modules/@types/yargs-parser": {
- "version": "21.0.1",
- "resolved": "https://registry.npmjs.org/@types/yargs-parser/-/yargs-parser-21.0.1.tgz",
- "integrity": "sha512-axdPBuLuEJt0c4yI5OZssC19K2Mq1uKdrfZBzuxLvaztgqUtFYZUNw7lETExPYJR9jdEoIg4mb7RQKRQzOkeGQ==",
- "dev": true
- },
- "node_modules/abab": {
- "version": "2.0.6",
- "resolved": "https://registry.npmjs.org/abab/-/abab-2.0.6.tgz",
- "integrity": "sha512-j2afSsaIENvHZN2B8GOpF566vZ5WVk5opAiMTvWgaQT8DkbOqsTfvNAvHoRGU2zzP8cPoqys+xHTRDWW8L+/BA==",
- "dev": true
- },
- "node_modules/acorn": {
- "version": "8.10.0",
- "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.10.0.tgz",
- "integrity": "sha512-F0SAmZ8iUtS//m8DmCTA0jlh6TDKkHQyK6xc6V4KDTyZKA9dnvX9/3sRTVQrWm79glUAZbnmmNcdYwUIHWVybw==",
- "dev": true,
- "bin": {
- "acorn": "bin/acorn"
- },
- "engines": {
- "node": ">=0.4.0"
- }
- },
- "node_modules/acorn-globals": {
- "version": "7.0.1",
- "resolved": "https://registry.npmjs.org/acorn-globals/-/acorn-globals-7.0.1.tgz",
- "integrity": "sha512-umOSDSDrfHbTNPuNpC2NSnnA3LUrqpevPb4T9jRx4MagXNS0rs+gwiTcAvqCRmsD6utzsrzNt+ebm00SNWiC3Q==",
- "dev": true,
- "dependencies": {
- "acorn": "^8.1.0",
- "acorn-walk": "^8.0.2"
- }
- },
- "node_modules/acorn-walk": {
- "version": "8.2.0",
- "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.2.0.tgz",
- "integrity": "sha512-k+iyHEuPgSw6SbuDpGQM+06HQUa04DZ3o+F6CSzXMvvI5KMvnaEqXe+YVe555R9nn6GPt404fos4wcgpw12SDA==",
- "dev": true,
- "engines": {
- "node": ">=0.4.0"
- }
- },
- "node_modules/agent-base": {
- "version": "6.0.2",
- "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz",
- "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==",
- "dev": true,
- "dependencies": {
- "debug": "4"
- },
- "engines": {
- "node": ">= 6.0.0"
- }
- },
- "node_modules/ansi-escapes": {
- "version": "4.3.2",
- "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz",
- "integrity": "sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==",
- "dev": true,
- "dependencies": {
- "type-fest": "^0.21.3"
- },
- "engines": {
- "node": ">=8"
- },
- "funding": {
- "url": "https://github.com/sponsors/sindresorhus"
- }
- },
- "node_modules/ansi-regex": {
- "version": "5.0.1",
- "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
- "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
- "dev": true,
- "engines": {
- "node": ">=8"
- }
- },
- "node_modules/ansi-styles": {
- "version": "4.3.0",
- "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",
- "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",
- "dev": true,
- "dependencies": {
- "color-convert": "^2.0.1"
- },
- "engines": {
- "node": ">=8"
- },
- "funding": {
- "url": "https://github.com/chalk/ansi-styles?sponsor=1"
- }
- },
- "node_modules/anymatch": {
- "version": "3.1.3",
- "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz",
- "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==",
- "dev": true,
- "dependencies": {
- "normalize-path": "^3.0.0",
- "picomatch": "^2.0.4"
- },
- "engines": {
- "node": ">= 8"
- }
- },
- "node_modules/argparse": {
- "version": "1.0.10",
- "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz",
- "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==",
- "dev": true,
- "dependencies": {
- "sprintf-js": "~1.0.2"
- }
- },
- "node_modules/asynckit": {
- "version": "0.4.0",
- "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
- "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==",
- "dev": true
- },
- "node_modules/babel-jest": {
- "version": "29.7.0",
- "resolved": "https://registry.npmjs.org/babel-jest/-/babel-jest-29.7.0.tgz",
- "integrity": "sha512-BrvGY3xZSwEcCzKvKsCi2GgHqDqsYkOP4/by5xCgIwGXQxIEh+8ew3gmrE1y7XRR6LHZIj6yLYnUi/mm2KXKBg==",
- "dev": true,
- "dependencies": {
- "@jest/transform": "^29.7.0",
- "@types/babel__core": "^7.1.14",
- "babel-plugin-istanbul": "^6.1.1",
- "babel-preset-jest": "^29.6.3",
- "chalk": "^4.0.0",
- "graceful-fs": "^4.2.9",
- "slash": "^3.0.0"
- },
- "engines": {
- "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.8.0"
- }
- },
- "node_modules/babel-plugin-istanbul": {
- "version": "6.1.1",
- "resolved": "https://registry.npmjs.org/babel-plugin-istanbul/-/babel-plugin-istanbul-6.1.1.tgz",
- "integrity": "sha512-Y1IQok9821cC9onCx5otgFfRm7Lm+I+wwxOx738M/WLPZ9Q42m4IG5W0FNX8WLL2gYMZo3JkuXIH2DOpWM+qwA==",
- "dev": true,
- "dependencies": {
- "@babel/helper-plugin-utils": "^7.0.0",
- "@istanbuljs/load-nyc-config": "^1.0.0",
- "@istanbuljs/schema": "^0.1.2",
- "istanbul-lib-instrument": "^5.0.4",
- "test-exclude": "^6.0.0"
- },
- "engines": {
- "node": ">=8"
- }
- },
- "node_modules/babel-plugin-istanbul/node_modules/istanbul-lib-instrument": {
- "version": "5.2.1",
- "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-5.2.1.tgz",
- "integrity": "sha512-pzqtp31nLv/XFOzXGuvhCb8qhjmTVo5vjVk19XE4CRlSWz0KoeJ3bw9XsA7nOp9YBf4qHjwBxkDzKcME/J29Yg==",
- "dev": true,
- "dependencies": {
- "@babel/core": "^7.12.3",
- "@babel/parser": "^7.14.7",
- "@istanbuljs/schema": "^0.1.2",
- "istanbul-lib-coverage": "^3.2.0",
- "semver": "^6.3.0"
- },
- "engines": {
- "node": ">=8"
- }
- },
- "node_modules/babel-plugin-jest-hoist": {
- "version": "29.6.3",
- "resolved": "https://registry.npmjs.org/babel-plugin-jest-hoist/-/babel-plugin-jest-hoist-29.6.3.tgz",
- "integrity": "sha512-ESAc/RJvGTFEzRwOTT4+lNDk/GNHMkKbNzsvT0qKRfDyyYTskxB5rnU2njIDYVxXCBHHEI1c0YwHob3WaYujOg==",
- "dev": true,
- "dependencies": {
- "@babel/template": "^7.3.3",
- "@babel/types": "^7.3.3",
- "@types/babel__core": "^7.1.14",
- "@types/babel__traverse": "^7.0.6"
- },
- "engines": {
- "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
- }
- },
- "node_modules/babel-plugin-polyfill-corejs2": {
- "version": "0.4.5",
- "resolved": "https://registry.npmjs.org/babel-plugin-polyfill-corejs2/-/babel-plugin-polyfill-corejs2-0.4.5.tgz",
- "integrity": "sha512-19hwUH5FKl49JEsvyTcoHakh6BE0wgXLLptIyKZ3PijHc/Ci521wygORCUCCred+E/twuqRyAkE02BAWPmsHOg==",
- "dev": true,
- "dependencies": {
- "@babel/compat-data": "^7.22.6",
- "@babel/helper-define-polyfill-provider": "^0.4.2",
- "semver": "^6.3.1"
- },
- "peerDependencies": {
- "@babel/core": "^7.4.0 || ^8.0.0-0 <8.0.0"
- }
- },
- "node_modules/babel-plugin-polyfill-corejs3": {
- "version": "0.8.4",
- "resolved": "https://registry.npmjs.org/babel-plugin-polyfill-corejs3/-/babel-plugin-polyfill-corejs3-0.8.4.tgz",
- "integrity": "sha512-9l//BZZsPR+5XjyJMPtZSK4jv0BsTO1zDac2GC6ygx9WLGlcsnRd1Co0B2zT5fF5Ic6BZy+9m3HNZ3QcOeDKfg==",
- "dev": true,
- "dependencies": {
- "@babel/helper-define-polyfill-provider": "^0.4.2",
- "core-js-compat": "^3.32.2"
- },
- "peerDependencies": {
- "@babel/core": "^7.4.0 || ^8.0.0-0 <8.0.0"
- }
- },
- "node_modules/babel-plugin-polyfill-regenerator": {
- "version": "0.5.2",
- "resolved": "https://registry.npmjs.org/babel-plugin-polyfill-regenerator/-/babel-plugin-polyfill-regenerator-0.5.2.tgz",
- "integrity": "sha512-tAlOptU0Xj34V1Y2PNTL4Y0FOJMDB6bZmoW39FeCQIhigGLkqu3Fj6uiXpxIf6Ij274ENdYx64y6Au+ZKlb1IA==",
- "dev": true,
- "dependencies": {
- "@babel/helper-define-polyfill-provider": "^0.4.2"
- },
- "peerDependencies": {
- "@babel/core": "^7.4.0 || ^8.0.0-0 <8.0.0"
- }
- },
- "node_modules/babel-plugin-transform-import-meta": {
- "version": "2.2.1",
- "resolved": "https://registry.npmjs.org/babel-plugin-transform-import-meta/-/babel-plugin-transform-import-meta-2.2.1.tgz",
- "integrity": "sha512-AxNh27Pcg8Kt112RGa3Vod2QS2YXKKJ6+nSvRtv7qQTJAdx0MZa4UHZ4lnxHUWA2MNbLuZQv5FVab4P1CoLOWw==",
- "dev": true,
- "dependencies": {
- "@babel/template": "^7.4.4",
- "tslib": "^2.4.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.10.0"
- }
- },
- "node_modules/babel-preset-current-node-syntax": {
- "version": "1.0.1",
- "resolved": "https://registry.npmjs.org/babel-preset-current-node-syntax/-/babel-preset-current-node-syntax-1.0.1.tgz",
- "integrity": "sha512-M7LQ0bxarkxQoN+vz5aJPsLBn77n8QgTFmo8WK0/44auK2xlCXrYcUxHFxgU7qW5Yzw/CjmLRK2uJzaCd7LvqQ==",
- "dev": true,
- "dependencies": {
- "@babel/plugin-syntax-async-generators": "^7.8.4",
- "@babel/plugin-syntax-bigint": "^7.8.3",
- "@babel/plugin-syntax-class-properties": "^7.8.3",
- "@babel/plugin-syntax-import-meta": "^7.8.3",
- "@babel/plugin-syntax-json-strings": "^7.8.3",
- "@babel/plugin-syntax-logical-assignment-operators": "^7.8.3",
- "@babel/plugin-syntax-nullish-coalescing-operator": "^7.8.3",
- "@babel/plugin-syntax-numeric-separator": "^7.8.3",
- "@babel/plugin-syntax-object-rest-spread": "^7.8.3",
- "@babel/plugin-syntax-optional-catch-binding": "^7.8.3",
- "@babel/plugin-syntax-optional-chaining": "^7.8.3",
- "@babel/plugin-syntax-top-level-await": "^7.8.3"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0"
- }
- },
- "node_modules/babel-preset-jest": {
- "version": "29.6.3",
- "resolved": "https://registry.npmjs.org/babel-preset-jest/-/babel-preset-jest-29.6.3.tgz",
- "integrity": "sha512-0B3bhxR6snWXJZtR/RliHTDPRgn1sNHOR0yVtq/IiQFyuOVjFS+wuio/R4gSNkyYmKmJB4wGZv2NZanmKmTnNA==",
- "dev": true,
- "dependencies": {
- "babel-plugin-jest-hoist": "^29.6.3",
- "babel-preset-current-node-syntax": "^1.0.0"
- },
- "engines": {
- "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
- },
- "peerDependencies": {
- "@babel/core": "^7.0.0"
- }
- },
- "node_modules/balanced-match": {
- "version": "1.0.2",
- "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
- "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
- "dev": true
- },
- "node_modules/brace-expansion": {
- "version": "1.1.11",
- "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz",
- "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==",
- "dev": true,
- "dependencies": {
- "balanced-match": "^1.0.0",
- "concat-map": "0.0.1"
- }
- },
- "node_modules/braces": {
- "version": "3.0.2",
- "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz",
- "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==",
- "dev": true,
- "dependencies": {
- "fill-range": "^7.0.1"
- },
- "engines": {
- "node": ">=8"
- }
- },
- "node_modules/browserslist": {
- "version": "4.22.1",
- "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.22.1.tgz",
- "integrity": "sha512-FEVc202+2iuClEhZhrWy6ZiAcRLvNMyYcxZ8raemul1DYVOVdFsbqckWLdsixQZCpJlwe77Z3UTalE7jsjnKfQ==",
- "dev": true,
- "funding": [
- {
- "type": "opencollective",
- "url": "https://opencollective.com/browserslist"
- },
- {
- "type": "tidelift",
- "url": "https://tidelift.com/funding/github/npm/browserslist"
- },
- {
- "type": "github",
- "url": "https://github.com/sponsors/ai"
- }
- ],
- "dependencies": {
- "caniuse-lite": "^1.0.30001541",
- "electron-to-chromium": "^1.4.535",
- "node-releases": "^2.0.13",
- "update-browserslist-db": "^1.0.13"
- },
- "bin": {
- "browserslist": "cli.js"
- },
- "engines": {
- "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"
- }
- },
- "node_modules/bser": {
- "version": "2.1.1",
- "resolved": "https://registry.npmjs.org/bser/-/bser-2.1.1.tgz",
- "integrity": "sha512-gQxTNE/GAfIIrmHLUE3oJyp5FO6HRBfhjnw4/wMmA63ZGDJnWBmgY/lyQBpnDUkGmAhbSe39tx2d/iTOAfglwQ==",
- "dev": true,
- "dependencies": {
- "node-int64": "^0.4.0"
- }
- },
- "node_modules/buffer-from": {
- "version": "1.1.2",
- "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",
- "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==",
- "dev": true
- },
- "node_modules/callsites": {
- "version": "3.1.0",
- "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz",
- "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==",
- "dev": true,
- "engines": {
- "node": ">=6"
- }
- },
- "node_modules/camelcase": {
- "version": "5.3.1",
- "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz",
- "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==",
- "dev": true,
- "engines": {
- "node": ">=6"
- }
- },
- "node_modules/caniuse-lite": {
- "version": "1.0.30001546",
- "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001546.tgz",
- "integrity": "sha512-zvtSJwuQFpewSyRrI3AsftF6rM0X80mZkChIt1spBGEvRglCrjTniXvinc8JKRoqTwXAgvqTImaN9igfSMtUBw==",
- "dev": true,
- "funding": [
- {
- "type": "opencollective",
- "url": "https://opencollective.com/browserslist"
- },
- {
- "type": "tidelift",
- "url": "https://tidelift.com/funding/github/npm/caniuse-lite"
- },
- {
- "type": "github",
- "url": "https://github.com/sponsors/ai"
- }
- ]
- },
- "node_modules/chalk": {
- "version": "4.1.2",
- "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
- "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==",
- "dev": true,
- "dependencies": {
- "ansi-styles": "^4.1.0",
- "supports-color": "^7.1.0"
- },
- "engines": {
- "node": ">=10"
- },
- "funding": {
- "url": "https://github.com/chalk/chalk?sponsor=1"
- }
- },
- "node_modules/char-regex": {
- "version": "1.0.2",
- "resolved": "https://registry.npmjs.org/char-regex/-/char-regex-1.0.2.tgz",
- "integrity": "sha512-kWWXztvZ5SBQV+eRgKFeh8q5sLuZY2+8WUIzlxWVTg+oGwY14qylx1KbKzHd8P6ZYkAg0xyIDU9JMHhyJMZ1jw==",
- "dev": true,
- "engines": {
- "node": ">=10"
- }
- },
- "node_modules/ci-info": {
- "version": "3.9.0",
- "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-3.9.0.tgz",
- "integrity": "sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ==",
- "dev": true,
- "funding": [
- {
- "type": "github",
- "url": "https://github.com/sponsors/sibiraj-s"
- }
- ],
- "engines": {
- "node": ">=8"
- }
- },
- "node_modules/cjs-module-lexer": {
- "version": "1.2.3",
- "resolved": "https://registry.npmjs.org/cjs-module-lexer/-/cjs-module-lexer-1.2.3.tgz",
- "integrity": "sha512-0TNiGstbQmCFwt4akjjBg5pLRTSyj/PkWQ1ZoO2zntmg9yLqSRxwEa4iCfQLGjqhiqBfOJa7W/E8wfGrTDmlZQ==",
- "dev": true
- },
- "node_modules/cliui": {
- "version": "8.0.1",
- "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz",
- "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==",
- "dev": true,
- "dependencies": {
- "string-width": "^4.2.0",
- "strip-ansi": "^6.0.1",
- "wrap-ansi": "^7.0.0"
- },
- "engines": {
- "node": ">=12"
- }
- },
- "node_modules/co": {
- "version": "4.6.0",
- "resolved": "https://registry.npmjs.org/co/-/co-4.6.0.tgz",
- "integrity": "sha512-QVb0dM5HvG+uaxitm8wONl7jltx8dqhfU33DcqtOZcLSVIKSDDLDi7+0LbAKiyI8hD9u42m2YxXSkMGWThaecQ==",
- "dev": true,
- "engines": {
- "iojs": ">= 1.0.0",
- "node": ">= 0.12.0"
- }
- },
- "node_modules/collect-v8-coverage": {
- "version": "1.0.2",
- "resolved": "https://registry.npmjs.org/collect-v8-coverage/-/collect-v8-coverage-1.0.2.tgz",
- "integrity": "sha512-lHl4d5/ONEbLlJvaJNtsF/Lz+WvB07u2ycqTYbdrq7UypDXailES4valYb2eWiJFxZlVmpGekfqoxQhzyFdT4Q==",
- "dev": true
- },
- "node_modules/color-convert": {
- "version": "2.0.1",
- "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
- "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
- "dev": true,
- "dependencies": {
- "color-name": "~1.1.4"
- },
- "engines": {
- "node": ">=7.0.0"
- }
- },
- "node_modules/color-name": {
- "version": "1.1.4",
- "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
- "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
- "dev": true
- },
- "node_modules/combined-stream": {
- "version": "1.0.8",
- "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
- "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
- "dev": true,
- "dependencies": {
- "delayed-stream": "~1.0.0"
- },
- "engines": {
- "node": ">= 0.8"
- }
- },
- "node_modules/concat-map": {
- "version": "0.0.1",
- "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
- "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==",
- "dev": true
- },
- "node_modules/convert-source-map": {
- "version": "2.0.0",
- "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",
- "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==",
- "dev": true
- },
- "node_modules/core-js-compat": {
- "version": "3.33.0",
- "resolved": "https://registry.npmjs.org/core-js-compat/-/core-js-compat-3.33.0.tgz",
- "integrity": "sha512-0w4LcLXsVEuNkIqwjjf9rjCoPhK8uqA4tMRh4Ge26vfLtUutshn+aRJU21I9LCJlh2QQHfisNToLjw1XEJLTWw==",
- "dev": true,
- "dependencies": {
- "browserslist": "^4.22.1"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/core-js"
- }
- },
- "node_modules/create-jest": {
- "version": "29.7.0",
- "resolved": "https://registry.npmjs.org/create-jest/-/create-jest-29.7.0.tgz",
- "integrity": "sha512-Adz2bdH0Vq3F53KEMJOoftQFutWCukm6J24wbPWRO4k1kMY7gS7ds/uoJkNuV8wDCtWWnuwGcJwpWcih+zEW1Q==",
- "dev": true,
- "dependencies": {
- "@jest/types": "^29.6.3",
- "chalk": "^4.0.0",
- "exit": "^0.1.2",
- "graceful-fs": "^4.2.9",
- "jest-config": "^29.7.0",
- "jest-util": "^29.7.0",
- "prompts": "^2.0.1"
- },
- "bin": {
- "create-jest": "bin/create-jest.js"
- },
- "engines": {
- "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
- }
- },
- "node_modules/cross-spawn": {
- "version": "7.0.3",
- "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz",
- "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==",
- "dev": true,
- "dependencies": {
- "path-key": "^3.1.0",
- "shebang-command": "^2.0.0",
- "which": "^2.0.1"
- },
- "engines": {
- "node": ">= 8"
- }
- },
- "node_modules/cssom": {
- "version": "0.5.0",
- "resolved": "https://registry.npmjs.org/cssom/-/cssom-0.5.0.tgz",
- "integrity": "sha512-iKuQcq+NdHqlAcwUY0o/HL69XQrUaQdMjmStJ8JFmUaiiQErlhrmuigkg/CU4E2J0IyUKUrMAgl36TvN67MqTw==",
- "dev": true
- },
- "node_modules/cssstyle": {
- "version": "2.3.0",
- "resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-2.3.0.tgz",
- "integrity": "sha512-AZL67abkUzIuvcHqk7c09cezpGNcxUxU4Ioi/05xHk4DQeTkWmGYftIE6ctU6AEt+Gn4n1lDStOtj7FKycP71A==",
- "dev": true,
- "dependencies": {
- "cssom": "~0.3.6"
- },
- "engines": {
- "node": ">=8"
- }
- },
- "node_modules/cssstyle/node_modules/cssom": {
- "version": "0.3.8",
- "resolved": "https://registry.npmjs.org/cssom/-/cssom-0.3.8.tgz",
- "integrity": "sha512-b0tGHbfegbhPJpxpiBPU2sCkigAqtM9O121le6bbOlgyV+NyGyCmVfJ6QW9eRjz8CpNfWEOYBIMIGRYkLwsIYg==",
- "dev": true
- },
- "node_modules/data-urls": {
- "version": "3.0.2",
- "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-3.0.2.tgz",
- "integrity": "sha512-Jy/tj3ldjZJo63sVAvg6LHt2mHvl4V6AgRAmNDtLdm7faqtsx+aJG42rsyCo9JCoRVKwPFzKlIPx3DIibwSIaQ==",
- "dev": true,
- "dependencies": {
- "abab": "^2.0.6",
- "whatwg-mimetype": "^3.0.0",
- "whatwg-url": "^11.0.0"
- },
- "engines": {
- "node": ">=12"
- }
- },
- "node_modules/debug": {
- "version": "4.3.4",
- "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz",
- "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==",
- "dev": true,
- "dependencies": {
- "ms": "2.1.2"
- },
- "engines": {
- "node": ">=6.0"
- },
- "peerDependenciesMeta": {
- "supports-color": {
- "optional": true
- }
- }
- },
- "node_modules/decimal.js": {
- "version": "10.4.3",
- "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.4.3.tgz",
- "integrity": "sha512-VBBaLc1MgL5XpzgIP7ny5Z6Nx3UrRkIViUkPUdtl9aya5amy3De1gsUUSB1g3+3sExYNjCAsAznmukyxCb1GRA==",
- "dev": true
- },
- "node_modules/dedent": {
- "version": "1.5.1",
- "resolved": "https://registry.npmjs.org/dedent/-/dedent-1.5.1.tgz",
- "integrity": "sha512-+LxW+KLWxu3HW3M2w2ympwtqPrqYRzU8fqi6Fhd18fBALe15blJPI/I4+UHveMVG6lJqB4JNd4UG0S5cnVHwIg==",
- "dev": true,
- "peerDependencies": {
- "babel-plugin-macros": "^3.1.0"
- },
- "peerDependenciesMeta": {
- "babel-plugin-macros": {
- "optional": true
- }
- }
- },
- "node_modules/deepmerge": {
- "version": "4.3.1",
- "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz",
- "integrity": "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==",
- "dev": true,
- "engines": {
- "node": ">=0.10.0"
- }
- },
- "node_modules/delayed-stream": {
- "version": "1.0.0",
- "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
- "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",
- "dev": true,
- "engines": {
- "node": ">=0.4.0"
- }
- },
- "node_modules/detect-newline": {
- "version": "3.1.0",
- "resolved": "https://registry.npmjs.org/detect-newline/-/detect-newline-3.1.0.tgz",
- "integrity": "sha512-TLz+x/vEXm/Y7P7wn1EJFNLxYpUD4TgMosxY6fAVJUnJMbupHBOncxyWUG9OpTaH9EBD7uFI5LfEgmMOc54DsA==",
- "dev": true,
- "engines": {
- "node": ">=8"
- }
- },
- "node_modules/diff-sequences": {
- "version": "29.6.3",
- "resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-29.6.3.tgz",
- "integrity": "sha512-EjePK1srD3P08o2j4f0ExnylqRs5B9tJjcp9t1krH2qRi8CCdsYfwe9JgSLurFBWwq4uOlipzfk5fHNvwFKr8Q==",
- "dev": true,
- "engines": {
- "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
- }
- },
- "node_modules/domexception": {
- "version": "4.0.0",
- "resolved": "https://registry.npmjs.org/domexception/-/domexception-4.0.0.tgz",
- "integrity": "sha512-A2is4PLG+eeSfoTMA95/s4pvAoSo2mKtiM5jlHkAVewmiO8ISFTFKZjH7UAM1Atli/OT/7JHOrJRJiMKUZKYBw==",
- "dev": true,
- "dependencies": {
- "webidl-conversions": "^7.0.0"
- },
- "engines": {
- "node": ">=12"
- }
- },
- "node_modules/electron-to-chromium": {
- "version": "1.4.544",
- "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.544.tgz",
- "integrity": "sha512-54z7squS1FyFRSUqq/knOFSptjjogLZXbKcYk3B0qkE1KZzvqASwRZnY2KzZQJqIYLVD38XZeoiMRflYSwyO4w==",
- "dev": true
- },
- "node_modules/emittery": {
- "version": "0.13.1",
- "resolved": "https://registry.npmjs.org/emittery/-/emittery-0.13.1.tgz",
- "integrity": "sha512-DeWwawk6r5yR9jFgnDKYt4sLS0LmHJJi3ZOnb5/JdbYwj3nW+FxQnHIjhBKz8YLC7oRNPVM9NQ47I3CVx34eqQ==",
- "dev": true,
- "engines": {
- "node": ">=12"
- },
- "funding": {
- "url": "https://github.com/sindresorhus/emittery?sponsor=1"
- }
- },
- "node_modules/emoji-regex": {
- "version": "8.0.0",
- "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
- "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
- "dev": true
- },
- "node_modules/entities": {
- "version": "4.5.0",
- "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz",
- "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==",
- "dev": true,
- "engines": {
- "node": ">=0.12"
- },
- "funding": {
- "url": "https://github.com/fb55/entities?sponsor=1"
- }
- },
- "node_modules/error-ex": {
- "version": "1.3.2",
- "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz",
- "integrity": "sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==",
- "dev": true,
- "dependencies": {
- "is-arrayish": "^0.2.1"
- }
- },
- "node_modules/escalade": {
- "version": "3.1.1",
- "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.1.tgz",
- "integrity": "sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==",
- "dev": true,
- "engines": {
- "node": ">=6"
- }
- },
- "node_modules/escape-string-regexp": {
- "version": "2.0.0",
- "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz",
- "integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==",
- "dev": true,
- "engines": {
- "node": ">=8"
- }
- },
- "node_modules/escodegen": {
- "version": "2.1.0",
- "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-2.1.0.tgz",
- "integrity": "sha512-2NlIDTwUWJN0mRPQOdtQBzbUHvdGY2P1VXSyU83Q3xKxM7WHX2Ql8dKq782Q9TgQUNOLEzEYu9bzLNj1q88I5w==",
- "dev": true,
- "dependencies": {
- "esprima": "^4.0.1",
- "estraverse": "^5.2.0",
- "esutils": "^2.0.2"
- },
- "bin": {
- "escodegen": "bin/escodegen.js",
- "esgenerate": "bin/esgenerate.js"
- },
- "engines": {
- "node": ">=6.0"
- },
- "optionalDependencies": {
- "source-map": "~0.6.1"
- }
- },
- "node_modules/esprima": {
- "version": "4.0.1",
- "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz",
- "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==",
- "dev": true,
- "bin": {
- "esparse": "bin/esparse.js",
- "esvalidate": "bin/esvalidate.js"
- },
- "engines": {
- "node": ">=4"
- }
- },
- "node_modules/estraverse": {
- "version": "5.3.0",
- "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz",
- "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==",
- "dev": true,
- "engines": {
- "node": ">=4.0"
- }
- },
- "node_modules/esutils": {
- "version": "2.0.3",
- "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz",
- "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==",
- "dev": true,
- "engines": {
- "node": ">=0.10.0"
- }
- },
- "node_modules/execa": {
- "version": "5.1.1",
- "resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz",
- "integrity": "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==",
- "dev": true,
- "dependencies": {
- "cross-spawn": "^7.0.3",
- "get-stream": "^6.0.0",
- "human-signals": "^2.1.0",
- "is-stream": "^2.0.0",
- "merge-stream": "^2.0.0",
- "npm-run-path": "^4.0.1",
- "onetime": "^5.1.2",
- "signal-exit": "^3.0.3",
- "strip-final-newline": "^2.0.0"
- },
- "engines": {
- "node": ">=10"
- },
- "funding": {
- "url": "https://github.com/sindresorhus/execa?sponsor=1"
- }
- },
- "node_modules/exit": {
- "version": "0.1.2",
- "resolved": "https://registry.npmjs.org/exit/-/exit-0.1.2.tgz",
- "integrity": "sha512-Zk/eNKV2zbjpKzrsQ+n1G6poVbErQxJ0LBOJXaKZ1EViLzH+hrLu9cdXI4zw9dBQJslwBEpbQ2P1oS7nDxs6jQ==",
- "dev": true,
- "engines": {
- "node": ">= 0.8.0"
- }
- },
- "node_modules/expect": {
- "version": "29.7.0",
- "resolved": "https://registry.npmjs.org/expect/-/expect-29.7.0.tgz",
- "integrity": "sha512-2Zks0hf1VLFYI1kbh0I5jP3KHHyCHpkfyHBzsSXRFgl/Bg9mWYfMW8oD+PdMPlEwy5HNsR9JutYy6pMeOh61nw==",
- "dev": true,
- "dependencies": {
- "@jest/expect-utils": "^29.7.0",
- "jest-get-type": "^29.6.3",
- "jest-matcher-utils": "^29.7.0",
- "jest-message-util": "^29.7.0",
- "jest-util": "^29.7.0"
- },
- "engines": {
- "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
- }
- },
- "node_modules/fast-json-stable-stringify": {
- "version": "2.1.0",
- "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz",
- "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==",
- "dev": true
- },
- "node_modules/fb-watchman": {
- "version": "2.0.2",
- "resolved": "https://registry.npmjs.org/fb-watchman/-/fb-watchman-2.0.2.tgz",
- "integrity": "sha512-p5161BqbuCaSnB8jIbzQHOlpgsPmK5rJVDfDKO91Axs5NC1uu3HRQm6wt9cd9/+GtQQIO53JdGXXoyDpTAsgYA==",
- "dev": true,
- "dependencies": {
- "bser": "2.1.1"
- }
- },
- "node_modules/fill-range": {
- "version": "7.0.1",
- "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz",
- "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==",
- "dev": true,
- "dependencies": {
- "to-regex-range": "^5.0.1"
- },
- "engines": {
- "node": ">=8"
- }
- },
- "node_modules/find-up": {
- "version": "4.1.0",
- "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz",
- "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==",
- "dev": true,
- "dependencies": {
- "locate-path": "^5.0.0",
- "path-exists": "^4.0.0"
- },
- "engines": {
- "node": ">=8"
- }
- },
- "node_modules/form-data": {
- "version": "4.0.0",
- "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz",
- "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==",
- "dev": true,
- "dependencies": {
- "asynckit": "^0.4.0",
- "combined-stream": "^1.0.8",
- "mime-types": "^2.1.12"
- },
- "engines": {
- "node": ">= 6"
- }
- },
- "node_modules/fs.realpath": {
- "version": "1.0.0",
- "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz",
- "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==",
- "dev": true
- },
- "node_modules/fsevents": {
- "version": "2.3.3",
- "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
- "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
- "dev": true,
- "hasInstallScript": true,
- "optional": true,
- "os": [
- "darwin"
- ],
- "engines": {
- "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
- }
- },
- "node_modules/gensync": {
- "version": "1.0.0-beta.2",
- "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz",
- "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==",
- "dev": true,
- "engines": {
- "node": ">=6.9.0"
- }
- },
- "node_modules/get-caller-file": {
- "version": "2.0.5",
- "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",
- "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==",
- "dev": true,
- "engines": {
- "node": "6.* || 8.* || >= 10.*"
- }
- },
- "node_modules/get-package-type": {
- "version": "0.1.0",
- "resolved": "https://registry.npmjs.org/get-package-type/-/get-package-type-0.1.0.tgz",
- "integrity": "sha512-pjzuKtY64GYfWizNAJ0fr9VqttZkNiK2iS430LtIHzjBEr6bX8Am2zm4sW4Ro5wjWW5cAlRL1qAMTcXbjNAO2Q==",
- "dev": true,
- "engines": {
- "node": ">=8.0.0"
- }
- },
- "node_modules/get-stream": {
- "version": "6.0.1",
- "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz",
- "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==",
- "dev": true,
- "engines": {
- "node": ">=10"
- },
- "funding": {
- "url": "https://github.com/sponsors/sindresorhus"
- }
- },
- "node_modules/glob": {
- "version": "7.2.3",
- "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz",
- "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==",
- "dev": true,
- "dependencies": {
- "fs.realpath": "^1.0.0",
- "inflight": "^1.0.4",
- "inherits": "2",
- "minimatch": "^3.1.1",
- "once": "^1.3.0",
- "path-is-absolute": "^1.0.0"
- },
- "engines": {
- "node": "*"
- },
- "funding": {
- "url": "https://github.com/sponsors/isaacs"
- }
- },
- "node_modules/globals": {
- "version": "11.12.0",
- "resolved": "https://registry.npmjs.org/globals/-/globals-11.12.0.tgz",
- "integrity": "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==",
- "dev": true,
- "engines": {
- "node": ">=4"
- }
- },
- "node_modules/graceful-fs": {
- "version": "4.2.11",
- "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
- "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",
- "dev": true
- },
- "node_modules/has": {
- "version": "1.0.4",
- "resolved": "https://registry.npmjs.org/has/-/has-1.0.4.tgz",
- "integrity": "sha512-qdSAmqLF6209RFj4VVItywPMbm3vWylknmB3nvNiUIs72xAimcM8nVYxYr7ncvZq5qzk9MKIZR8ijqD/1QuYjQ==",
- "dev": true,
- "engines": {
- "node": ">= 0.4.0"
- }
- },
- "node_modules/has-flag": {
- "version": "4.0.0",
- "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
- "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",
- "dev": true,
- "engines": {
- "node": ">=8"
- }
- },
- "node_modules/html-encoding-sniffer": {
- "version": "3.0.0",
- "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-3.0.0.tgz",
- "integrity": "sha512-oWv4T4yJ52iKrufjnyZPkrN0CH3QnrUqdB6In1g5Fe1mia8GmF36gnfNySxoZtxD5+NmYw1EElVXiBk93UeskA==",
- "dev": true,
- "dependencies": {
- "whatwg-encoding": "^2.0.0"
- },
- "engines": {
- "node": ">=12"
- }
- },
- "node_modules/html-escaper": {
- "version": "2.0.2",
- "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz",
- "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==",
- "dev": true
- },
- "node_modules/http-proxy-agent": {
- "version": "5.0.0",
- "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-5.0.0.tgz",
- "integrity": "sha512-n2hY8YdoRE1i7r6M0w9DIw5GgZN0G25P8zLCRQ8rjXtTU3vsNFBI/vWK/UIeE6g5MUUz6avwAPXmL6Fy9D/90w==",
- "dev": true,
- "dependencies": {
- "@tootallnate/once": "2",
- "agent-base": "6",
- "debug": "4"
- },
- "engines": {
- "node": ">= 6"
- }
- },
- "node_modules/https-proxy-agent": {
- "version": "5.0.1",
- "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz",
- "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==",
- "dev": true,
- "dependencies": {
- "agent-base": "6",
- "debug": "4"
- },
- "engines": {
- "node": ">= 6"
- }
- },
- "node_modules/human-signals": {
- "version": "2.1.0",
- "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz",
- "integrity": "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==",
- "dev": true,
- "engines": {
- "node": ">=10.17.0"
- }
- },
- "node_modules/iconv-lite": {
- "version": "0.6.3",
- "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz",
- "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==",
- "dev": true,
- "dependencies": {
- "safer-buffer": ">= 2.1.2 < 3.0.0"
- },
- "engines": {
- "node": ">=0.10.0"
- }
- },
- "node_modules/import-local": {
- "version": "3.1.0",
- "resolved": "https://registry.npmjs.org/import-local/-/import-local-3.1.0.tgz",
- "integrity": "sha512-ASB07uLtnDs1o6EHjKpX34BKYDSqnFerfTOJL2HvMqF70LnxpjkzDB8J44oT9pu4AMPkQwf8jl6szgvNd2tRIg==",
- "dev": true,
- "dependencies": {
- "pkg-dir": "^4.2.0",
- "resolve-cwd": "^3.0.0"
- },
- "bin": {
- "import-local-fixture": "fixtures/cli.js"
- },
- "engines": {
- "node": ">=8"
- },
- "funding": {
- "url": "https://github.com/sponsors/sindresorhus"
- }
- },
- "node_modules/imurmurhash": {
- "version": "0.1.4",
- "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz",
- "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==",
- "dev": true,
- "engines": {
- "node": ">=0.8.19"
- }
- },
- "node_modules/inflight": {
- "version": "1.0.6",
- "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz",
- "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==",
- "dev": true,
- "dependencies": {
- "once": "^1.3.0",
- "wrappy": "1"
- }
- },
- "node_modules/inherits": {
- "version": "2.0.4",
- "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
- "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
- "dev": true
- },
- "node_modules/is-arrayish": {
- "version": "0.2.1",
- "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz",
- "integrity": "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==",
- "dev": true
- },
- "node_modules/is-core-module": {
- "version": "2.13.0",
- "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.13.0.tgz",
- "integrity": "sha512-Z7dk6Qo8pOCp3l4tsX2C5ZVas4V+UxwQodwZhLopL91TX8UyyHEXafPcyoeeWuLrwzHcr3igO78wNLwHJHsMCQ==",
- "dev": true,
- "dependencies": {
- "has": "^1.0.3"
- },
- "funding": {
- "url": "https://github.com/sponsors/ljharb"
- }
- },
- "node_modules/is-fullwidth-code-point": {
- "version": "3.0.0",
- "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
- "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",
- "dev": true,
- "engines": {
- "node": ">=8"
- }
- },
- "node_modules/is-generator-fn": {
- "version": "2.1.0",
- "resolved": "https://registry.npmjs.org/is-generator-fn/-/is-generator-fn-2.1.0.tgz",
- "integrity": "sha512-cTIB4yPYL/Grw0EaSzASzg6bBy9gqCofvWN8okThAYIxKJZC+udlRAmGbM0XLeniEJSs8uEgHPGuHSe1XsOLSQ==",
- "dev": true,
- "engines": {
- "node": ">=6"
- }
- },
- "node_modules/is-number": {
- "version": "7.0.0",
- "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz",
- "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==",
- "dev": true,
- "engines": {
- "node": ">=0.12.0"
- }
- },
- "node_modules/is-potential-custom-element-name": {
- "version": "1.0.1",
- "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz",
- "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==",
- "dev": true
- },
- "node_modules/is-stream": {
- "version": "2.0.1",
- "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz",
- "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==",
- "dev": true,
- "engines": {
- "node": ">=8"
- },
- "funding": {
- "url": "https://github.com/sponsors/sindresorhus"
- }
- },
- "node_modules/isexe": {
- "version": "2.0.0",
- "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
- "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
- "dev": true
- },
- "node_modules/istanbul-lib-coverage": {
- "version": "3.2.0",
- "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.0.tgz",
- "integrity": "sha512-eOeJ5BHCmHYvQK7xt9GkdHuzuCGS1Y6g9Gvnx3Ym33fz/HpLRYxiS0wHNr+m/MBC8B647Xt608vCDEvhl9c6Mw==",
- "dev": true,
- "engines": {
- "node": ">=8"
- }
- },
- "node_modules/istanbul-lib-instrument": {
- "version": "6.0.1",
- "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-6.0.1.tgz",
- "integrity": "sha512-EAMEJBsYuyyztxMxW3g7ugGPkrZsV57v0Hmv3mm1uQsmB+QnZuepg731CRaIgeUVSdmsTngOkSnauNF8p7FIhA==",
- "dev": true,
- "dependencies": {
- "@babel/core": "^7.12.3",
- "@babel/parser": "^7.14.7",
- "@istanbuljs/schema": "^0.1.2",
- "istanbul-lib-coverage": "^3.2.0",
- "semver": "^7.5.4"
- },
- "engines": {
- "node": ">=10"
- }
- },
- "node_modules/istanbul-lib-instrument/node_modules/lru-cache": {
- "version": "6.0.0",
- "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz",
- "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==",
- "dev": true,
- "dependencies": {
- "yallist": "^4.0.0"
- },
- "engines": {
- "node": ">=10"
- }
- },
- "node_modules/istanbul-lib-instrument/node_modules/semver": {
- "version": "7.5.4",
- "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz",
- "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==",
- "dev": true,
- "dependencies": {
- "lru-cache": "^6.0.0"
- },
- "bin": {
- "semver": "bin/semver.js"
- },
- "engines": {
- "node": ">=10"
- }
- },
- "node_modules/istanbul-lib-instrument/node_modules/yallist": {
- "version": "4.0.0",
- "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",
- "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==",
- "dev": true
- },
- "node_modules/istanbul-lib-report": {
- "version": "3.0.1",
- "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz",
- "integrity": "sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==",
- "dev": true,
- "dependencies": {
- "istanbul-lib-coverage": "^3.0.0",
- "make-dir": "^4.0.0",
- "supports-color": "^7.1.0"
- },
- "engines": {
- "node": ">=10"
- }
- },
- "node_modules/istanbul-lib-source-maps": {
- "version": "4.0.1",
- "resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-4.0.1.tgz",
- "integrity": "sha512-n3s8EwkdFIJCG3BPKBYvskgXGoy88ARzvegkitk60NxRdwltLOTaH7CUiMRXvwYorl0Q712iEjcWB+fK/MrWVw==",
- "dev": true,
- "dependencies": {
- "debug": "^4.1.1",
- "istanbul-lib-coverage": "^3.0.0",
- "source-map": "^0.6.1"
- },
- "engines": {
- "node": ">=10"
- }
- },
- "node_modules/istanbul-reports": {
- "version": "3.1.6",
- "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.1.6.tgz",
- "integrity": "sha512-TLgnMkKg3iTDsQ9PbPTdpfAK2DzjF9mqUG7RMgcQl8oFjad8ob4laGxv5XV5U9MAfx8D6tSJiUyuAwzLicaxlg==",
- "dev": true,
- "dependencies": {
- "html-escaper": "^2.0.0",
- "istanbul-lib-report": "^3.0.0"
- },
- "engines": {
- "node": ">=8"
- }
- },
- "node_modules/jest": {
- "version": "29.7.0",
- "resolved": "https://registry.npmjs.org/jest/-/jest-29.7.0.tgz",
- "integrity": "sha512-NIy3oAFp9shda19hy4HK0HRTWKtPJmGdnvywu01nOqNC2vZg+Z+fvJDxpMQA88eb2I9EcafcdjYgsDthnYTvGw==",
- "dev": true,
- "dependencies": {
- "@jest/core": "^29.7.0",
- "@jest/types": "^29.6.3",
- "import-local": "^3.0.2",
- "jest-cli": "^29.7.0"
- },
- "bin": {
- "jest": "bin/jest.js"
- },
- "engines": {
- "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
- },
- "peerDependencies": {
- "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0"
- },
- "peerDependenciesMeta": {
- "node-notifier": {
- "optional": true
- }
- }
- },
- "node_modules/jest-changed-files": {
- "version": "29.7.0",
- "resolved": "https://registry.npmjs.org/jest-changed-files/-/jest-changed-files-29.7.0.tgz",
- "integrity": "sha512-fEArFiwf1BpQ+4bXSprcDc3/x4HSzL4al2tozwVpDFpsxALjLYdyiIK4e5Vz66GQJIbXJ82+35PtysofptNX2w==",
- "dev": true,
- "dependencies": {
- "execa": "^5.0.0",
- "jest-util": "^29.7.0",
- "p-limit": "^3.1.0"
- },
- "engines": {
- "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
- }
- },
- "node_modules/jest-circus": {
- "version": "29.7.0",
- "resolved": "https://registry.npmjs.org/jest-circus/-/jest-circus-29.7.0.tgz",
- "integrity": "sha512-3E1nCMgipcTkCocFwM90XXQab9bS+GMsjdpmPrlelaxwD93Ad8iVEjX/vvHPdLPnFf+L40u+5+iutRdA1N9myw==",
- "dev": true,
- "dependencies": {
- "@jest/environment": "^29.7.0",
- "@jest/expect": "^29.7.0",
- "@jest/test-result": "^29.7.0",
- "@jest/types": "^29.6.3",
- "@types/node": "*",
- "chalk": "^4.0.0",
- "co": "^4.6.0",
- "dedent": "^1.0.0",
- "is-generator-fn": "^2.0.0",
- "jest-each": "^29.7.0",
- "jest-matcher-utils": "^29.7.0",
- "jest-message-util": "^29.7.0",
- "jest-runtime": "^29.7.0",
- "jest-snapshot": "^29.7.0",
- "jest-util": "^29.7.0",
- "p-limit": "^3.1.0",
- "pretty-format": "^29.7.0",
- "pure-rand": "^6.0.0",
- "slash": "^3.0.0",
- "stack-utils": "^2.0.3"
- },
- "engines": {
- "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
- }
- },
- "node_modules/jest-cli": {
- "version": "29.7.0",
- "resolved": "https://registry.npmjs.org/jest-cli/-/jest-cli-29.7.0.tgz",
- "integrity": "sha512-OVVobw2IubN/GSYsxETi+gOe7Ka59EFMR/twOU3Jb2GnKKeMGJB5SGUUrEz3SFVmJASUdZUzy83sLNNQ2gZslg==",
- "dev": true,
- "dependencies": {
- "@jest/core": "^29.7.0",
- "@jest/test-result": "^29.7.0",
- "@jest/types": "^29.6.3",
- "chalk": "^4.0.0",
- "create-jest": "^29.7.0",
- "exit": "^0.1.2",
- "import-local": "^3.0.2",
- "jest-config": "^29.7.0",
- "jest-util": "^29.7.0",
- "jest-validate": "^29.7.0",
- "yargs": "^17.3.1"
- },
- "bin": {
- "jest": "bin/jest.js"
- },
- "engines": {
- "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
- },
- "peerDependencies": {
- "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0"
- },
- "peerDependenciesMeta": {
- "node-notifier": {
- "optional": true
- }
- }
- },
- "node_modules/jest-config": {
- "version": "29.7.0",
- "resolved": "https://registry.npmjs.org/jest-config/-/jest-config-29.7.0.tgz",
- "integrity": "sha512-uXbpfeQ7R6TZBqI3/TxCU4q4ttk3u0PJeC+E0zbfSoSjq6bJ7buBPxzQPL0ifrkY4DNu4JUdk0ImlBUYi840eQ==",
- "dev": true,
- "dependencies": {
- "@babel/core": "^7.11.6",
- "@jest/test-sequencer": "^29.7.0",
- "@jest/types": "^29.6.3",
- "babel-jest": "^29.7.0",
- "chalk": "^4.0.0",
- "ci-info": "^3.2.0",
- "deepmerge": "^4.2.2",
- "glob": "^7.1.3",
- "graceful-fs": "^4.2.9",
- "jest-circus": "^29.7.0",
- "jest-environment-node": "^29.7.0",
- "jest-get-type": "^29.6.3",
- "jest-regex-util": "^29.6.3",
- "jest-resolve": "^29.7.0",
- "jest-runner": "^29.7.0",
- "jest-util": "^29.7.0",
- "jest-validate": "^29.7.0",
- "micromatch": "^4.0.4",
- "parse-json": "^5.2.0",
- "pretty-format": "^29.7.0",
- "slash": "^3.0.0",
- "strip-json-comments": "^3.1.1"
- },
- "engines": {
- "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
- },
- "peerDependencies": {
- "@types/node": "*",
- "ts-node": ">=9.0.0"
- },
- "peerDependenciesMeta": {
- "@types/node": {
- "optional": true
- },
- "ts-node": {
- "optional": true
- }
- }
- },
- "node_modules/jest-diff": {
- "version": "29.7.0",
- "resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-29.7.0.tgz",
- "integrity": "sha512-LMIgiIrhigmPrs03JHpxUh2yISK3vLFPkAodPeo0+BuF7wA2FoQbkEg1u8gBYBThncu7e1oEDUfIXVuTqLRUjw==",
- "dev": true,
- "dependencies": {
- "chalk": "^4.0.0",
- "diff-sequences": "^29.6.3",
- "jest-get-type": "^29.6.3",
- "pretty-format": "^29.7.0"
- },
- "engines": {
- "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
- }
- },
- "node_modules/jest-docblock": {
- "version": "29.7.0",
- "resolved": "https://registry.npmjs.org/jest-docblock/-/jest-docblock-29.7.0.tgz",
- "integrity": "sha512-q617Auw3A612guyaFgsbFeYpNP5t2aoUNLwBUbc/0kD1R4t9ixDbyFTHd1nok4epoVFpr7PmeWHrhvuV3XaJ4g==",
- "dev": true,
- "dependencies": {
- "detect-newline": "^3.0.0"
- },
- "engines": {
- "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
- }
- },
- "node_modules/jest-each": {
- "version": "29.7.0",
- "resolved": "https://registry.npmjs.org/jest-each/-/jest-each-29.7.0.tgz",
- "integrity": "sha512-gns+Er14+ZrEoC5fhOfYCY1LOHHr0TI+rQUHZS8Ttw2l7gl+80eHc/gFf2Ktkw0+SIACDTeWvpFcv3B04VembQ==",
- "dev": true,
- "dependencies": {
- "@jest/types": "^29.6.3",
- "chalk": "^4.0.0",
- "jest-get-type": "^29.6.3",
- "jest-util": "^29.7.0",
- "pretty-format": "^29.7.0"
- },
- "engines": {
- "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
- }
- },
- "node_modules/jest-environment-jsdom": {
- "version": "29.7.0",
- "resolved": "https://registry.npmjs.org/jest-environment-jsdom/-/jest-environment-jsdom-29.7.0.tgz",
- "integrity": "sha512-k9iQbsf9OyOfdzWH8HDmrRT0gSIcX+FLNW7IQq94tFX0gynPwqDTW0Ho6iMVNjGz/nb+l/vW3dWM2bbLLpkbXA==",
- "dev": true,
- "dependencies": {
- "@jest/environment": "^29.7.0",
- "@jest/fake-timers": "^29.7.0",
- "@jest/types": "^29.6.3",
- "@types/jsdom": "^20.0.0",
- "@types/node": "*",
- "jest-mock": "^29.7.0",
- "jest-util": "^29.7.0",
- "jsdom": "^20.0.0"
- },
- "engines": {
- "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
- },
- "peerDependencies": {
- "canvas": "^2.5.0"
- },
- "peerDependenciesMeta": {
- "canvas": {
- "optional": true
- }
- }
- },
- "node_modules/jest-environment-node": {
- "version": "29.7.0",
- "resolved": "https://registry.npmjs.org/jest-environment-node/-/jest-environment-node-29.7.0.tgz",
- "integrity": "sha512-DOSwCRqXirTOyheM+4d5YZOrWcdu0LNZ87ewUoywbcb2XR4wKgqiG8vNeYwhjFMbEkfju7wx2GYH0P2gevGvFw==",
- "dev": true,
- "dependencies": {
- "@jest/environment": "^29.7.0",
- "@jest/fake-timers": "^29.7.0",
- "@jest/types": "^29.6.3",
- "@types/node": "*",
- "jest-mock": "^29.7.0",
- "jest-util": "^29.7.0"
- },
- "engines": {
- "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
- }
- },
- "node_modules/jest-get-type": {
- "version": "29.6.3",
- "resolved": "https://registry.npmjs.org/jest-get-type/-/jest-get-type-29.6.3.tgz",
- "integrity": "sha512-zrteXnqYxfQh7l5FHyL38jL39di8H8rHoecLH3JNxH3BwOrBsNeabdap5e0I23lD4HHI8W5VFBZqG4Eaq5LNcw==",
- "dev": true,
- "engines": {
- "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
- }
- },
- "node_modules/jest-haste-map": {
- "version": "29.7.0",
- "resolved": "https://registry.npmjs.org/jest-haste-map/-/jest-haste-map-29.7.0.tgz",
- "integrity": "sha512-fP8u2pyfqx0K1rGn1R9pyE0/KTn+G7PxktWidOBTqFPLYX0b9ksaMFkhK5vrS3DVun09pckLdlx90QthlW7AmA==",
- "dev": true,
- "dependencies": {
- "@jest/types": "^29.6.3",
- "@types/graceful-fs": "^4.1.3",
- "@types/node": "*",
- "anymatch": "^3.0.3",
- "fb-watchman": "^2.0.0",
- "graceful-fs": "^4.2.9",
- "jest-regex-util": "^29.6.3",
- "jest-util": "^29.7.0",
- "jest-worker": "^29.7.0",
- "micromatch": "^4.0.4",
- "walker": "^1.0.8"
- },
- "engines": {
- "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
- },
- "optionalDependencies": {
- "fsevents": "^2.3.2"
- }
- },
- "node_modules/jest-leak-detector": {
- "version": "29.7.0",
- "resolved": "https://registry.npmjs.org/jest-leak-detector/-/jest-leak-detector-29.7.0.tgz",
- "integrity": "sha512-kYA8IJcSYtST2BY9I+SMC32nDpBT3J2NvWJx8+JCuCdl/CR1I4EKUJROiP8XtCcxqgTTBGJNdbB1A8XRKbTetw==",
- "dev": true,
- "dependencies": {
- "jest-get-type": "^29.6.3",
- "pretty-format": "^29.7.0"
- },
- "engines": {
- "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
- }
- },
- "node_modules/jest-matcher-utils": {
- "version": "29.7.0",
- "resolved": "https://registry.npmjs.org/jest-matcher-utils/-/jest-matcher-utils-29.7.0.tgz",
- "integrity": "sha512-sBkD+Xi9DtcChsI3L3u0+N0opgPYnCRPtGcQYrgXmR+hmt/fYfWAL0xRXYU8eWOdfuLgBe0YCW3AFtnRLagq/g==",
- "dev": true,
- "dependencies": {
- "chalk": "^4.0.0",
- "jest-diff": "^29.7.0",
- "jest-get-type": "^29.6.3",
- "pretty-format": "^29.7.0"
- },
- "engines": {
- "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
- }
- },
- "node_modules/jest-message-util": {
- "version": "29.7.0",
- "resolved": "https://registry.npmjs.org/jest-message-util/-/jest-message-util-29.7.0.tgz",
- "integrity": "sha512-GBEV4GRADeP+qtB2+6u61stea8mGcOT4mCtrYISZwfu9/ISHFJ/5zOMXYbpBE9RsS5+Gb63DW4FgmnKJ79Kf6w==",
- "dev": true,
- "dependencies": {
- "@babel/code-frame": "^7.12.13",
- "@jest/types": "^29.6.3",
- "@types/stack-utils": "^2.0.0",
- "chalk": "^4.0.0",
- "graceful-fs": "^4.2.9",
- "micromatch": "^4.0.4",
- "pretty-format": "^29.7.0",
- "slash": "^3.0.0",
- "stack-utils": "^2.0.3"
- },
- "engines": {
- "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
- }
- },
- "node_modules/jest-mock": {
- "version": "29.7.0",
- "resolved": "https://registry.npmjs.org/jest-mock/-/jest-mock-29.7.0.tgz",
- "integrity": "sha512-ITOMZn+UkYS4ZFh83xYAOzWStloNzJFO2s8DWrE4lhtGD+AorgnbkiKERe4wQVBydIGPx059g6riW5Btp6Llnw==",
- "dev": true,
- "dependencies": {
- "@jest/types": "^29.6.3",
- "@types/node": "*",
- "jest-util": "^29.7.0"
- },
- "engines": {
- "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
- }
- },
- "node_modules/jest-pnp-resolver": {
- "version": "1.2.3",
- "resolved": "https://registry.npmjs.org/jest-pnp-resolver/-/jest-pnp-resolver-1.2.3.tgz",
- "integrity": "sha512-+3NpwQEnRoIBtx4fyhblQDPgJI0H1IEIkX7ShLUjPGA7TtUTvI1oiKi3SR4oBR0hQhQR80l4WAe5RrXBwWMA8w==",
- "dev": true,
- "engines": {
- "node": ">=6"
- },
- "peerDependencies": {
- "jest-resolve": "*"
- },
- "peerDependenciesMeta": {
- "jest-resolve": {
- "optional": true
- }
- }
- },
- "node_modules/jest-regex-util": {
- "version": "29.6.3",
- "resolved": "https://registry.npmjs.org/jest-regex-util/-/jest-regex-util-29.6.3.tgz",
- "integrity": "sha512-KJJBsRCyyLNWCNBOvZyRDnAIfUiRJ8v+hOBQYGn8gDyF3UegwiP4gwRR3/SDa42g1YbVycTidUF3rKjyLFDWbg==",
- "dev": true,
- "engines": {
- "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
- }
- },
- "node_modules/jest-resolve": {
- "version": "29.7.0",
- "resolved": "https://registry.npmjs.org/jest-resolve/-/jest-resolve-29.7.0.tgz",
- "integrity": "sha512-IOVhZSrg+UvVAshDSDtHyFCCBUl/Q3AAJv8iZ6ZjnZ74xzvwuzLXid9IIIPgTnY62SJjfuupMKZsZQRsCvxEgA==",
- "dev": true,
- "dependencies": {
- "chalk": "^4.0.0",
- "graceful-fs": "^4.2.9",
- "jest-haste-map": "^29.7.0",
- "jest-pnp-resolver": "^1.2.2",
- "jest-util": "^29.7.0",
- "jest-validate": "^29.7.0",
- "resolve": "^1.20.0",
- "resolve.exports": "^2.0.0",
- "slash": "^3.0.0"
- },
- "engines": {
- "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
- }
- },
- "node_modules/jest-resolve-dependencies": {
- "version": "29.7.0",
- "resolved": "https://registry.npmjs.org/jest-resolve-dependencies/-/jest-resolve-dependencies-29.7.0.tgz",
- "integrity": "sha512-un0zD/6qxJ+S0et7WxeI3H5XSe9lTBBR7bOHCHXkKR6luG5mwDDlIzVQ0V5cZCuoTgEdcdwzTghYkTWfubi+nA==",
- "dev": true,
- "dependencies": {
- "jest-regex-util": "^29.6.3",
- "jest-snapshot": "^29.7.0"
- },
- "engines": {
- "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
- }
- },
- "node_modules/jest-runner": {
- "version": "29.7.0",
- "resolved": "https://registry.npmjs.org/jest-runner/-/jest-runner-29.7.0.tgz",
- "integrity": "sha512-fsc4N6cPCAahybGBfTRcq5wFR6fpLznMg47sY5aDpsoejOcVYFb07AHuSnR0liMcPTgBsA3ZJL6kFOjPdoNipQ==",
- "dev": true,
- "dependencies": {
- "@jest/console": "^29.7.0",
- "@jest/environment": "^29.7.0",
- "@jest/test-result": "^29.7.0",
- "@jest/transform": "^29.7.0",
- "@jest/types": "^29.6.3",
- "@types/node": "*",
- "chalk": "^4.0.0",
- "emittery": "^0.13.1",
- "graceful-fs": "^4.2.9",
- "jest-docblock": "^29.7.0",
- "jest-environment-node": "^29.7.0",
- "jest-haste-map": "^29.7.0",
- "jest-leak-detector": "^29.7.0",
- "jest-message-util": "^29.7.0",
- "jest-resolve": "^29.7.0",
- "jest-runtime": "^29.7.0",
- "jest-util": "^29.7.0",
- "jest-watcher": "^29.7.0",
- "jest-worker": "^29.7.0",
- "p-limit": "^3.1.0",
- "source-map-support": "0.5.13"
- },
- "engines": {
- "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
- }
- },
- "node_modules/jest-runtime": {
- "version": "29.7.0",
- "resolved": "https://registry.npmjs.org/jest-runtime/-/jest-runtime-29.7.0.tgz",
- "integrity": "sha512-gUnLjgwdGqW7B4LvOIkbKs9WGbn+QLqRQQ9juC6HndeDiezIwhDP+mhMwHWCEcfQ5RUXa6OPnFF8BJh5xegwwQ==",
- "dev": true,
- "dependencies": {
- "@jest/environment": "^29.7.0",
- "@jest/fake-timers": "^29.7.0",
- "@jest/globals": "^29.7.0",
- "@jest/source-map": "^29.6.3",
- "@jest/test-result": "^29.7.0",
- "@jest/transform": "^29.7.0",
- "@jest/types": "^29.6.3",
- "@types/node": "*",
- "chalk": "^4.0.0",
- "cjs-module-lexer": "^1.0.0",
- "collect-v8-coverage": "^1.0.0",
- "glob": "^7.1.3",
- "graceful-fs": "^4.2.9",
- "jest-haste-map": "^29.7.0",
- "jest-message-util": "^29.7.0",
- "jest-mock": "^29.7.0",
- "jest-regex-util": "^29.6.3",
- "jest-resolve": "^29.7.0",
- "jest-snapshot": "^29.7.0",
- "jest-util": "^29.7.0",
- "slash": "^3.0.0",
- "strip-bom": "^4.0.0"
- },
- "engines": {
- "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
- }
- },
- "node_modules/jest-snapshot": {
- "version": "29.7.0",
- "resolved": "https://registry.npmjs.org/jest-snapshot/-/jest-snapshot-29.7.0.tgz",
- "integrity": "sha512-Rm0BMWtxBcioHr1/OX5YCP8Uov4riHvKPknOGs804Zg9JGZgmIBkbtlxJC/7Z4msKYVbIJtfU+tKb8xlYNfdkw==",
- "dev": true,
- "dependencies": {
- "@babel/core": "^7.11.6",
- "@babel/generator": "^7.7.2",
- "@babel/plugin-syntax-jsx": "^7.7.2",
- "@babel/plugin-syntax-typescript": "^7.7.2",
- "@babel/types": "^7.3.3",
- "@jest/expect-utils": "^29.7.0",
- "@jest/transform": "^29.7.0",
- "@jest/types": "^29.6.3",
- "babel-preset-current-node-syntax": "^1.0.0",
- "chalk": "^4.0.0",
- "expect": "^29.7.0",
- "graceful-fs": "^4.2.9",
- "jest-diff": "^29.7.0",
- "jest-get-type": "^29.6.3",
- "jest-matcher-utils": "^29.7.0",
- "jest-message-util": "^29.7.0",
- "jest-util": "^29.7.0",
- "natural-compare": "^1.4.0",
- "pretty-format": "^29.7.0",
- "semver": "^7.5.3"
- },
- "engines": {
- "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
- }
- },
- "node_modules/jest-snapshot/node_modules/lru-cache": {
- "version": "6.0.0",
- "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz",
- "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==",
- "dev": true,
- "dependencies": {
- "yallist": "^4.0.0"
- },
- "engines": {
- "node": ">=10"
- }
- },
- "node_modules/jest-snapshot/node_modules/semver": {
- "version": "7.5.4",
- "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz",
- "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==",
- "dev": true,
- "dependencies": {
- "lru-cache": "^6.0.0"
- },
- "bin": {
- "semver": "bin/semver.js"
- },
- "engines": {
- "node": ">=10"
- }
- },
- "node_modules/jest-snapshot/node_modules/yallist": {
- "version": "4.0.0",
- "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",
- "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==",
- "dev": true
- },
- "node_modules/jest-util": {
- "version": "29.7.0",
- "resolved": "https://registry.npmjs.org/jest-util/-/jest-util-29.7.0.tgz",
- "integrity": "sha512-z6EbKajIpqGKU56y5KBUgy1dt1ihhQJgWzUlZHArA/+X2ad7Cb5iF+AK1EWVL/Bo7Rz9uurpqw6SiBCefUbCGA==",
- "dev": true,
- "dependencies": {
- "@jest/types": "^29.6.3",
- "@types/node": "*",
- "chalk": "^4.0.0",
- "ci-info": "^3.2.0",
- "graceful-fs": "^4.2.9",
- "picomatch": "^2.2.3"
- },
- "engines": {
- "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
- }
- },
- "node_modules/jest-validate": {
- "version": "29.7.0",
- "resolved": "https://registry.npmjs.org/jest-validate/-/jest-validate-29.7.0.tgz",
- "integrity": "sha512-ZB7wHqaRGVw/9hST/OuFUReG7M8vKeq0/J2egIGLdvjHCmYqGARhzXmtgi+gVeZ5uXFF219aOc3Ls2yLg27tkw==",
- "dev": true,
- "dependencies": {
- "@jest/types": "^29.6.3",
- "camelcase": "^6.2.0",
- "chalk": "^4.0.0",
- "jest-get-type": "^29.6.3",
- "leven": "^3.1.0",
- "pretty-format": "^29.7.0"
- },
- "engines": {
- "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
- }
- },
- "node_modules/jest-validate/node_modules/camelcase": {
- "version": "6.3.0",
- "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.3.0.tgz",
- "integrity": "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==",
- "dev": true,
- "engines": {
- "node": ">=10"
- },
- "funding": {
- "url": "https://github.com/sponsors/sindresorhus"
- }
- },
- "node_modules/jest-watcher": {
- "version": "29.7.0",
- "resolved": "https://registry.npmjs.org/jest-watcher/-/jest-watcher-29.7.0.tgz",
- "integrity": "sha512-49Fg7WXkU3Vl2h6LbLtMQ/HyB6rXSIX7SqvBLQmssRBGN9I0PNvPmAmCWSOY6SOvrjhI/F7/bGAv9RtnsPA03g==",
- "dev": true,
- "dependencies": {
- "@jest/test-result": "^29.7.0",
- "@jest/types": "^29.6.3",
- "@types/node": "*",
- "ansi-escapes": "^4.2.1",
- "chalk": "^4.0.0",
- "emittery": "^0.13.1",
- "jest-util": "^29.7.0",
- "string-length": "^4.0.1"
- },
- "engines": {
- "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
- }
- },
- "node_modules/jest-worker": {
- "version": "29.7.0",
- "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-29.7.0.tgz",
- "integrity": "sha512-eIz2msL/EzL9UFTFFx7jBTkeZfku0yUAyZZZmJ93H2TYEiroIx2PQjEXcwYtYl8zXCxb+PAmA2hLIt/6ZEkPHw==",
- "dev": true,
- "dependencies": {
- "@types/node": "*",
- "jest-util": "^29.7.0",
- "merge-stream": "^2.0.0",
- "supports-color": "^8.0.0"
- },
- "engines": {
- "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
- }
- },
- "node_modules/jest-worker/node_modules/supports-color": {
- "version": "8.1.1",
- "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz",
- "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==",
- "dev": true,
- "dependencies": {
- "has-flag": "^4.0.0"
- },
- "engines": {
- "node": ">=10"
- },
- "funding": {
- "url": "https://github.com/chalk/supports-color?sponsor=1"
- }
- },
- "node_modules/js-tokens": {
- "version": "4.0.0",
- "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
- "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",
- "dev": true
- },
- "node_modules/js-yaml": {
- "version": "3.14.1",
- "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz",
- "integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==",
- "dev": true,
- "dependencies": {
- "argparse": "^1.0.7",
- "esprima": "^4.0.0"
- },
- "bin": {
- "js-yaml": "bin/js-yaml.js"
- }
- },
- "node_modules/jsdom": {
- "version": "20.0.3",
- "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-20.0.3.tgz",
- "integrity": "sha512-SYhBvTh89tTfCD/CRdSOm13mOBa42iTaTyfyEWBdKcGdPxPtLFBXuHR8XHb33YNYaP+lLbmSvBTsnoesCNJEsQ==",
- "dev": true,
- "dependencies": {
- "abab": "^2.0.6",
- "acorn": "^8.8.1",
- "acorn-globals": "^7.0.0",
- "cssom": "^0.5.0",
- "cssstyle": "^2.3.0",
- "data-urls": "^3.0.2",
- "decimal.js": "^10.4.2",
- "domexception": "^4.0.0",
- "escodegen": "^2.0.0",
- "form-data": "^4.0.0",
- "html-encoding-sniffer": "^3.0.0",
- "http-proxy-agent": "^5.0.0",
- "https-proxy-agent": "^5.0.1",
- "is-potential-custom-element-name": "^1.0.1",
- "nwsapi": "^2.2.2",
- "parse5": "^7.1.1",
- "saxes": "^6.0.0",
- "symbol-tree": "^3.2.4",
- "tough-cookie": "^4.1.2",
- "w3c-xmlserializer": "^4.0.0",
- "webidl-conversions": "^7.0.0",
- "whatwg-encoding": "^2.0.0",
- "whatwg-mimetype": "^3.0.0",
- "whatwg-url": "^11.0.0",
- "ws": "^8.11.0",
- "xml-name-validator": "^4.0.0"
- },
- "engines": {
- "node": ">=14"
- },
- "peerDependencies": {
- "canvas": "^2.5.0"
- },
- "peerDependenciesMeta": {
- "canvas": {
- "optional": true
- }
- }
- },
- "node_modules/jsesc": {
- "version": "2.5.2",
- "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz",
- "integrity": "sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==",
- "dev": true,
- "bin": {
- "jsesc": "bin/jsesc"
- },
- "engines": {
- "node": ">=4"
- }
- },
- "node_modules/json-parse-even-better-errors": {
- "version": "2.3.1",
- "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz",
- "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==",
- "dev": true
- },
- "node_modules/json5": {
- "version": "2.2.3",
- "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz",
- "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==",
- "dev": true,
- "bin": {
- "json5": "lib/cli.js"
- },
- "engines": {
- "node": ">=6"
- }
- },
- "node_modules/kleur": {
- "version": "3.0.3",
- "resolved": "https://registry.npmjs.org/kleur/-/kleur-3.0.3.tgz",
- "integrity": "sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==",
- "dev": true,
- "engines": {
- "node": ">=6"
- }
- },
- "node_modules/leven": {
- "version": "3.1.0",
- "resolved": "https://registry.npmjs.org/leven/-/leven-3.1.0.tgz",
- "integrity": "sha512-qsda+H8jTaUaN/x5vzW2rzc+8Rw4TAQ/4KjB46IwK5VH+IlVeeeje/EoZRpiXvIqjFgK84QffqPztGI3VBLG1A==",
- "dev": true,
- "engines": {
- "node": ">=6"
- }
- },
- "node_modules/lines-and-columns": {
- "version": "1.2.4",
- "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz",
- "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==",
- "dev": true
- },
- "node_modules/locate-path": {
- "version": "5.0.0",
- "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz",
- "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==",
- "dev": true,
- "dependencies": {
- "p-locate": "^4.1.0"
- },
- "engines": {
- "node": ">=8"
- }
- },
- "node_modules/lodash.debounce": {
- "version": "4.0.8",
- "resolved": "https://registry.npmjs.org/lodash.debounce/-/lodash.debounce-4.0.8.tgz",
- "integrity": "sha512-FT1yDzDYEoYWhnSGnpE/4Kj1fLZkDFyqRb7fNt6FdYOSxlUWAtp42Eh6Wb0rGIv/m9Bgo7x4GhQbm5Ys4SG5ow==",
- "dev": true
- },
- "node_modules/lru-cache": {
- "version": "5.1.1",
- "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz",
- "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==",
- "dev": true,
- "dependencies": {
- "yallist": "^3.0.2"
- }
- },
- "node_modules/make-dir": {
- "version": "4.0.0",
- "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz",
- "integrity": "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==",
- "dev": true,
- "dependencies": {
- "semver": "^7.5.3"
- },
- "engines": {
- "node": ">=10"
- },
- "funding": {
- "url": "https://github.com/sponsors/sindresorhus"
- }
- },
- "node_modules/make-dir/node_modules/lru-cache": {
- "version": "6.0.0",
- "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz",
- "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==",
- "dev": true,
- "dependencies": {
- "yallist": "^4.0.0"
- },
- "engines": {
- "node": ">=10"
- }
- },
- "node_modules/make-dir/node_modules/semver": {
- "version": "7.5.4",
- "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz",
- "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==",
- "dev": true,
- "dependencies": {
- "lru-cache": "^6.0.0"
- },
- "bin": {
- "semver": "bin/semver.js"
- },
- "engines": {
- "node": ">=10"
- }
- },
- "node_modules/make-dir/node_modules/yallist": {
- "version": "4.0.0",
- "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",
- "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==",
- "dev": true
- },
- "node_modules/makeerror": {
- "version": "1.0.12",
- "resolved": "https://registry.npmjs.org/makeerror/-/makeerror-1.0.12.tgz",
- "integrity": "sha512-JmqCvUhmt43madlpFzG4BQzG2Z3m6tvQDNKdClZnO3VbIudJYmxsT0FNJMeiB2+JTSlTQTSbU8QdesVmwJcmLg==",
- "dev": true,
- "dependencies": {
- "tmpl": "1.0.5"
- }
- },
- "node_modules/merge-stream": {
- "version": "2.0.0",
- "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz",
- "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==",
- "dev": true
- },
- "node_modules/micromatch": {
- "version": "4.0.5",
- "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.5.tgz",
- "integrity": "sha512-DMy+ERcEW2q8Z2Po+WNXuw3c5YaUSFjAO5GsJqfEl7UjvtIuFKO6ZrKvcItdy98dwFI2N1tg3zNIdKaQT+aNdA==",
- "dev": true,
- "dependencies": {
- "braces": "^3.0.2",
- "picomatch": "^2.3.1"
- },
- "engines": {
- "node": ">=8.6"
- }
- },
- "node_modules/mime-db": {
- "version": "1.52.0",
- "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
- "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
- "dev": true,
- "engines": {
- "node": ">= 0.6"
- }
- },
- "node_modules/mime-types": {
- "version": "2.1.35",
- "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
- "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
- "dev": true,
- "dependencies": {
- "mime-db": "1.52.0"
- },
- "engines": {
- "node": ">= 0.6"
- }
- },
- "node_modules/mimic-fn": {
- "version": "2.1.0",
- "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz",
- "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==",
- "dev": true,
- "engines": {
- "node": ">=6"
- }
- },
- "node_modules/minimatch": {
- "version": "3.1.2",
- "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz",
- "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==",
- "dev": true,
- "dependencies": {
- "brace-expansion": "^1.1.7"
- },
- "engines": {
- "node": "*"
- }
- },
- "node_modules/ms": {
- "version": "2.1.2",
- "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",
- "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==",
- "dev": true
- },
- "node_modules/natural-compare": {
- "version": "1.4.0",
- "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz",
- "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==",
- "dev": true
- },
- "node_modules/node-int64": {
- "version": "0.4.0",
- "resolved": "https://registry.npmjs.org/node-int64/-/node-int64-0.4.0.tgz",
- "integrity": "sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw==",
- "dev": true
- },
- "node_modules/node-releases": {
- "version": "2.0.13",
- "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.13.tgz",
- "integrity": "sha512-uYr7J37ae/ORWdZeQ1xxMJe3NtdmqMC/JZK+geofDrkLUApKRHPd18/TxtBOJ4A0/+uUIliorNrfYV6s1b02eQ==",
- "dev": true
- },
- "node_modules/normalize-path": {
- "version": "3.0.0",
- "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz",
- "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==",
- "dev": true,
- "engines": {
- "node": ">=0.10.0"
- }
- },
- "node_modules/npm-run-path": {
- "version": "4.0.1",
- "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz",
- "integrity": "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==",
- "dev": true,
- "dependencies": {
- "path-key": "^3.0.0"
- },
- "engines": {
- "node": ">=8"
- }
- },
- "node_modules/nwsapi": {
- "version": "2.2.7",
- "resolved": "https://registry.npmjs.org/nwsapi/-/nwsapi-2.2.7.tgz",
- "integrity": "sha512-ub5E4+FBPKwAZx0UwIQOjYWGHTEq5sPqHQNRN8Z9e4A7u3Tj1weLJsL59yH9vmvqEtBHaOmT6cYQKIZOxp35FQ==",
- "dev": true
- },
- "node_modules/once": {
- "version": "1.4.0",
- "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
- "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
- "dev": true,
- "dependencies": {
- "wrappy": "1"
- }
- },
- "node_modules/onetime": {
- "version": "5.1.2",
- "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz",
- "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==",
- "dev": true,
- "dependencies": {
- "mimic-fn": "^2.1.0"
- },
- "engines": {
- "node": ">=6"
- },
- "funding": {
- "url": "https://github.com/sponsors/sindresorhus"
- }
- },
- "node_modules/p-limit": {
- "version": "3.1.0",
- "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz",
- "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==",
- "dev": true,
- "dependencies": {
- "yocto-queue": "^0.1.0"
- },
- "engines": {
- "node": ">=10"
- },
- "funding": {
- "url": "https://github.com/sponsors/sindresorhus"
- }
- },
- "node_modules/p-locate": {
- "version": "4.1.0",
- "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz",
- "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==",
- "dev": true,
- "dependencies": {
- "p-limit": "^2.2.0"
- },
- "engines": {
- "node": ">=8"
- }
- },
- "node_modules/p-locate/node_modules/p-limit": {
- "version": "2.3.0",
- "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz",
- "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==",
- "dev": true,
- "dependencies": {
- "p-try": "^2.0.0"
- },
- "engines": {
- "node": ">=6"
- },
- "funding": {
- "url": "https://github.com/sponsors/sindresorhus"
- }
- },
- "node_modules/p-try": {
- "version": "2.2.0",
- "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz",
- "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==",
- "dev": true,
- "engines": {
- "node": ">=6"
- }
- },
- "node_modules/parse-json": {
- "version": "5.2.0",
- "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz",
- "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==",
- "dev": true,
- "dependencies": {
- "@babel/code-frame": "^7.0.0",
- "error-ex": "^1.3.1",
- "json-parse-even-better-errors": "^2.3.0",
- "lines-and-columns": "^1.1.6"
- },
- "engines": {
- "node": ">=8"
- },
- "funding": {
- "url": "https://github.com/sponsors/sindresorhus"
- }
- },
- "node_modules/parse5": {
- "version": "7.1.2",
- "resolved": "https://registry.npmjs.org/parse5/-/parse5-7.1.2.tgz",
- "integrity": "sha512-Czj1WaSVpaoj0wbhMzLmWD69anp2WH7FXMB9n1Sy8/ZFF9jolSQVMu1Ij5WIyGmcBmhk7EOndpO4mIpihVqAXw==",
- "dev": true,
- "dependencies": {
- "entities": "^4.4.0"
- },
- "funding": {
- "url": "https://github.com/inikulin/parse5?sponsor=1"
- }
- },
- "node_modules/path-exists": {
- "version": "4.0.0",
- "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz",
- "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==",
- "dev": true,
- "engines": {
- "node": ">=8"
- }
- },
- "node_modules/path-is-absolute": {
- "version": "1.0.1",
- "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz",
- "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==",
- "dev": true,
- "engines": {
- "node": ">=0.10.0"
- }
- },
- "node_modules/path-key": {
- "version": "3.1.1",
- "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
- "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",
- "dev": true,
- "engines": {
- "node": ">=8"
- }
- },
- "node_modules/path-parse": {
- "version": "1.0.7",
- "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz",
- "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==",
- "dev": true
- },
- "node_modules/picocolors": {
- "version": "1.0.0",
- "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.0.0.tgz",
- "integrity": "sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ==",
- "dev": true
- },
- "node_modules/picomatch": {
- "version": "2.3.1",
- "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz",
- "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==",
- "dev": true,
- "engines": {
- "node": ">=8.6"
- },
- "funding": {
- "url": "https://github.com/sponsors/jonschlinkert"
- }
- },
- "node_modules/pirates": {
- "version": "4.0.6",
- "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.6.tgz",
- "integrity": "sha512-saLsH7WeYYPiD25LDuLRRY/i+6HaPYr6G1OUlN39otzkSTxKnubR9RTxS3/Kk50s1g2JTgFwWQDQyplC5/SHZg==",
- "dev": true,
- "engines": {
- "node": ">= 6"
- }
- },
- "node_modules/pkg-dir": {
- "version": "4.2.0",
- "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz",
- "integrity": "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==",
- "dev": true,
- "dependencies": {
- "find-up": "^4.0.0"
- },
- "engines": {
- "node": ">=8"
- }
- },
- "node_modules/pretty-format": {
- "version": "29.7.0",
- "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.7.0.tgz",
- "integrity": "sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ==",
- "dev": true,
- "dependencies": {
- "@jest/schemas": "^29.6.3",
- "ansi-styles": "^5.0.0",
- "react-is": "^18.0.0"
- },
- "engines": {
- "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
- }
- },
- "node_modules/pretty-format/node_modules/ansi-styles": {
- "version": "5.2.0",
- "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz",
- "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==",
- "dev": true,
- "engines": {
- "node": ">=10"
- },
- "funding": {
- "url": "https://github.com/chalk/ansi-styles?sponsor=1"
- }
- },
- "node_modules/prompts": {
- "version": "2.4.2",
- "resolved": "https://registry.npmjs.org/prompts/-/prompts-2.4.2.tgz",
- "integrity": "sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q==",
- "dev": true,
- "dependencies": {
- "kleur": "^3.0.3",
- "sisteransi": "^1.0.5"
- },
- "engines": {
- "node": ">= 6"
- }
- },
- "node_modules/psl": {
- "version": "1.9.0",
- "resolved": "https://registry.npmjs.org/psl/-/psl-1.9.0.tgz",
- "integrity": "sha512-E/ZsdU4HLs/68gYzgGTkMicWTLPdAftJLfJFlLUAAKZGkStNU72sZjT66SnMDVOfOWY/YAoiD7Jxa9iHvngcag==",
- "dev": true
- },
- "node_modules/punycode": {
- "version": "2.3.0",
- "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.0.tgz",
- "integrity": "sha512-rRV+zQD8tVFys26lAGR9WUuS4iUAngJScM+ZRSKtvl5tKeZ2t5bvdNFdNHBW9FWR4guGHlgmsZ1G7BSm2wTbuA==",
- "dev": true,
- "engines": {
- "node": ">=6"
- }
- },
- "node_modules/pure-rand": {
- "version": "6.0.4",
- "resolved": "https://registry.npmjs.org/pure-rand/-/pure-rand-6.0.4.tgz",
- "integrity": "sha512-LA0Y9kxMYv47GIPJy6MI84fqTd2HmYZI83W/kM/SkKfDlajnZYfmXFTxkbY+xSBPkLJxltMa9hIkmdc29eguMA==",
- "dev": true,
- "funding": [
- {
- "type": "individual",
- "url": "https://github.com/sponsors/dubzzz"
- },
- {
- "type": "opencollective",
- "url": "https://opencollective.com/fast-check"
- }
- ]
- },
- "node_modules/querystringify": {
- "version": "2.2.0",
- "resolved": "https://registry.npmjs.org/querystringify/-/querystringify-2.2.0.tgz",
- "integrity": "sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ==",
- "dev": true
- },
- "node_modules/react-is": {
- "version": "18.2.0",
- "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.2.0.tgz",
- "integrity": "sha512-xWGDIW6x921xtzPkhiULtthJHoJvBbF3q26fzloPCK0hsvxtPVelvftw3zjbHWSkR2km9Z+4uxbDDK/6Zw9B8w==",
- "dev": true
- },
- "node_modules/regenerate": {
- "version": "1.4.2",
- "resolved": "https://registry.npmjs.org/regenerate/-/regenerate-1.4.2.tgz",
- "integrity": "sha512-zrceR/XhGYU/d/opr2EKO7aRHUeiBI8qjtfHqADTwZd6Szfy16la6kqD0MIUs5z5hx6AaKa+PixpPrR289+I0A==",
- "dev": true
- },
- "node_modules/regenerate-unicode-properties": {
- "version": "10.1.1",
- "resolved": "https://registry.npmjs.org/regenerate-unicode-properties/-/regenerate-unicode-properties-10.1.1.tgz",
- "integrity": "sha512-X007RyZLsCJVVrjgEFVpLUTZwyOZk3oiL75ZcuYjlIWd6rNJtOjkBwQc5AsRrpbKVkxN6sklw/k/9m2jJYOf8Q==",
- "dev": true,
- "dependencies": {
- "regenerate": "^1.4.2"
- },
- "engines": {
- "node": ">=4"
- }
- },
- "node_modules/regenerator-runtime": {
- "version": "0.14.0",
- "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.14.0.tgz",
- "integrity": "sha512-srw17NI0TUWHuGa5CFGGmhfNIeja30WMBfbslPNhf6JrqQlLN5gcrvig1oqPxiVaXb0oW0XRKtH6Nngs5lKCIA==",
- "dev": true
- },
- "node_modules/regenerator-transform": {
- "version": "0.15.2",
- "resolved": "https://registry.npmjs.org/regenerator-transform/-/regenerator-transform-0.15.2.tgz",
- "integrity": "sha512-hfMp2BoF0qOk3uc5V20ALGDS2ddjQaLrdl7xrGXvAIow7qeWRM2VA2HuCHkUKk9slq3VwEwLNK3DFBqDfPGYtg==",
- "dev": true,
- "dependencies": {
- "@babel/runtime": "^7.8.4"
- }
- },
- "node_modules/regexpu-core": {
- "version": "5.3.2",
- "resolved": "https://registry.npmjs.org/regexpu-core/-/regexpu-core-5.3.2.tgz",
- "integrity": "sha512-RAM5FlZz+Lhmo7db9L298p2vHP5ZywrVXmVXpmAD9GuL5MPH6t9ROw1iA/wfHkQ76Qe7AaPF0nGuim96/IrQMQ==",
- "dev": true,
- "dependencies": {
- "@babel/regjsgen": "^0.8.0",
- "regenerate": "^1.4.2",
- "regenerate-unicode-properties": "^10.1.0",
- "regjsparser": "^0.9.1",
- "unicode-match-property-ecmascript": "^2.0.0",
- "unicode-match-property-value-ecmascript": "^2.1.0"
- },
- "engines": {
- "node": ">=4"
- }
- },
- "node_modules/regjsparser": {
- "version": "0.9.1",
- "resolved": "https://registry.npmjs.org/regjsparser/-/regjsparser-0.9.1.tgz",
- "integrity": "sha512-dQUtn90WanSNl+7mQKcXAgZxvUe7Z0SqXlgzv0za4LwiUhyzBC58yQO3liFoUgu8GiJVInAhJjkj1N0EtQ5nkQ==",
- "dev": true,
- "dependencies": {
- "jsesc": "~0.5.0"
- },
- "bin": {
- "regjsparser": "bin/parser"
- }
- },
- "node_modules/regjsparser/node_modules/jsesc": {
- "version": "0.5.0",
- "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-0.5.0.tgz",
- "integrity": "sha512-uZz5UnB7u4T9LvwmFqXii7pZSouaRPorGs5who1Ip7VO0wxanFvBL7GkM6dTHlgX+jhBApRetaWpnDabOeTcnA==",
- "dev": true,
- "bin": {
- "jsesc": "bin/jsesc"
- }
- },
- "node_modules/require-directory": {
- "version": "2.1.1",
- "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",
- "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==",
- "dev": true,
- "engines": {
- "node": ">=0.10.0"
- }
- },
- "node_modules/requires-port": {
- "version": "1.0.0",
- "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz",
- "integrity": "sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==",
- "dev": true
- },
- "node_modules/resolve": {
- "version": "1.22.6",
- "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.6.tgz",
- "integrity": "sha512-njhxM7mV12JfufShqGy3Rz8j11RPdLy4xi15UurGJeoHLfJpVXKdh3ueuOqbYUcDZnffr6X739JBo5LzyahEsw==",
- "dev": true,
- "dependencies": {
- "is-core-module": "^2.13.0",
- "path-parse": "^1.0.7",
- "supports-preserve-symlinks-flag": "^1.0.0"
- },
- "bin": {
- "resolve": "bin/resolve"
- },
- "funding": {
- "url": "https://github.com/sponsors/ljharb"
- }
- },
- "node_modules/resolve-cwd": {
- "version": "3.0.0",
- "resolved": "https://registry.npmjs.org/resolve-cwd/-/resolve-cwd-3.0.0.tgz",
- "integrity": "sha512-OrZaX2Mb+rJCpH/6CpSqt9xFVpN++x01XnN2ie9g6P5/3xelLAkXWVADpdz1IHD/KFfEXyE6V0U01OQ3UO2rEg==",
- "dev": true,
- "dependencies": {
- "resolve-from": "^5.0.0"
- },
- "engines": {
- "node": ">=8"
- }
- },
- "node_modules/resolve-from": {
- "version": "5.0.0",
- "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz",
- "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==",
- "dev": true,
- "engines": {
- "node": ">=8"
- }
- },
- "node_modules/resolve.exports": {
- "version": "2.0.2",
- "resolved": "https://registry.npmjs.org/resolve.exports/-/resolve.exports-2.0.2.tgz",
- "integrity": "sha512-X2UW6Nw3n/aMgDVy+0rSqgHlv39WZAlZrXCdnbyEiKm17DSqHX4MmQMaST3FbeWR5FTuRcUwYAziZajji0Y7mg==",
- "dev": true,
- "engines": {
- "node": ">=10"
- }
- },
- "node_modules/safer-buffer": {
- "version": "2.1.2",
- "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
- "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
- "dev": true
- },
- "node_modules/saxes": {
- "version": "6.0.0",
- "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz",
- "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==",
- "dev": true,
- "dependencies": {
- "xmlchars": "^2.2.0"
- },
- "engines": {
- "node": ">=v12.22.7"
- }
- },
- "node_modules/semver": {
- "version": "6.3.1",
- "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",
- "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",
- "dev": true,
- "bin": {
- "semver": "bin/semver.js"
- }
- },
- "node_modules/shebang-command": {
- "version": "2.0.0",
- "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
- "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",
- "dev": true,
- "dependencies": {
- "shebang-regex": "^3.0.0"
- },
- "engines": {
- "node": ">=8"
- }
- },
- "node_modules/shebang-regex": {
- "version": "3.0.0",
- "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",
- "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",
- "dev": true,
- "engines": {
- "node": ">=8"
- }
- },
- "node_modules/signal-exit": {
- "version": "3.0.7",
- "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz",
- "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==",
- "dev": true
- },
- "node_modules/sisteransi": {
- "version": "1.0.5",
- "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz",
- "integrity": "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==",
- "dev": true
- },
- "node_modules/slash": {
- "version": "3.0.0",
- "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz",
- "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==",
- "dev": true,
- "engines": {
- "node": ">=8"
- }
- },
- "node_modules/source-map": {
- "version": "0.6.1",
- "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",
- "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==",
- "dev": true,
- "engines": {
- "node": ">=0.10.0"
- }
- },
- "node_modules/source-map-support": {
- "version": "0.5.13",
- "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.13.tgz",
- "integrity": "sha512-SHSKFHadjVA5oR4PPqhtAVdcBWwRYVd6g6cAXnIbRiIwc2EhPrTuKUBdSLvlEKyIP3GCf89fltvcZiP9MMFA1w==",
- "dev": true,
- "dependencies": {
- "buffer-from": "^1.0.0",
- "source-map": "^0.6.0"
- }
- },
- "node_modules/sprintf-js": {
- "version": "1.0.3",
- "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz",
- "integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==",
- "dev": true
- },
- "node_modules/stack-utils": {
- "version": "2.0.6",
- "resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.6.tgz",
- "integrity": "sha512-XlkWvfIm6RmsWtNJx+uqtKLS8eqFbxUg0ZzLXqY0caEy9l7hruX8IpiDnjsLavoBgqCCR71TqWO8MaXYheJ3RQ==",
- "dev": true,
- "dependencies": {
- "escape-string-regexp": "^2.0.0"
- },
- "engines": {
- "node": ">=10"
- }
- },
- "node_modules/string-length": {
- "version": "4.0.2",
- "resolved": "https://registry.npmjs.org/string-length/-/string-length-4.0.2.tgz",
- "integrity": "sha512-+l6rNN5fYHNhZZy41RXsYptCjA2Igmq4EG7kZAYFQI1E1VTXarr6ZPXBg6eq7Y6eK4FEhY6AJlyuFIb/v/S0VQ==",
- "dev": true,
- "dependencies": {
- "char-regex": "^1.0.2",
- "strip-ansi": "^6.0.0"
- },
- "engines": {
- "node": ">=10"
- }
- },
- "node_modules/string-width": {
- "version": "4.2.3",
- "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
- "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
- "dev": true,
- "dependencies": {
- "emoji-regex": "^8.0.0",
- "is-fullwidth-code-point": "^3.0.0",
- "strip-ansi": "^6.0.1"
- },
- "engines": {
- "node": ">=8"
- }
- },
- "node_modules/strip-ansi": {
- "version": "6.0.1",
- "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
- "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
- "dev": true,
- "dependencies": {
- "ansi-regex": "^5.0.1"
- },
- "engines": {
- "node": ">=8"
- }
- },
- "node_modules/strip-bom": {
- "version": "4.0.0",
- "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-4.0.0.tgz",
- "integrity": "sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w==",
- "dev": true,
- "engines": {
- "node": ">=8"
- }
- },
- "node_modules/strip-final-newline": {
- "version": "2.0.0",
- "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz",
- "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==",
- "dev": true,
- "engines": {
- "node": ">=6"
- }
- },
- "node_modules/strip-json-comments": {
- "version": "3.1.1",
- "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz",
- "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==",
- "dev": true,
- "engines": {
- "node": ">=8"
- },
- "funding": {
- "url": "https://github.com/sponsors/sindresorhus"
- }
- },
- "node_modules/supports-color": {
- "version": "7.2.0",
- "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
- "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",
- "dev": true,
- "dependencies": {
- "has-flag": "^4.0.0"
- },
- "engines": {
- "node": ">=8"
- }
- },
- "node_modules/supports-preserve-symlinks-flag": {
- "version": "1.0.0",
- "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz",
- "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==",
- "dev": true,
- "engines": {
- "node": ">= 0.4"
- },
- "funding": {
- "url": "https://github.com/sponsors/ljharb"
- }
- },
- "node_modules/symbol-tree": {
- "version": "3.2.4",
- "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz",
- "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==",
- "dev": true
- },
- "node_modules/test-exclude": {
- "version": "6.0.0",
- "resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-6.0.0.tgz",
- "integrity": "sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==",
- "dev": true,
- "dependencies": {
- "@istanbuljs/schema": "^0.1.2",
- "glob": "^7.1.4",
- "minimatch": "^3.0.4"
- },
- "engines": {
- "node": ">=8"
- }
- },
- "node_modules/tmpl": {
- "version": "1.0.5",
- "resolved": "https://registry.npmjs.org/tmpl/-/tmpl-1.0.5.tgz",
- "integrity": "sha512-3f0uOEAQwIqGuWW2MVzYg8fV/QNnc/IpuJNG837rLuczAaLVHslWHZQj4IGiEl5Hs3kkbhwL9Ab7Hrsmuj+Smw==",
- "dev": true
- },
- "node_modules/to-fast-properties": {
- "version": "2.0.0",
- "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz",
- "integrity": "sha512-/OaKK0xYrs3DmxRYqL/yDc+FxFUVYhDlXMhRmv3z915w2HF1tnN1omB354j8VUGO/hbRzyD6Y3sA7v7GS/ceog==",
- "dev": true,
- "engines": {
- "node": ">=4"
- }
- },
- "node_modules/to-regex-range": {
- "version": "5.0.1",
- "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz",
- "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==",
- "dev": true,
- "dependencies": {
- "is-number": "^7.0.0"
- },
- "engines": {
- "node": ">=8.0"
- }
- },
- "node_modules/tough-cookie": {
- "version": "4.1.3",
- "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-4.1.3.tgz",
- "integrity": "sha512-aX/y5pVRkfRnfmuX+OdbSdXvPe6ieKX/G2s7e98f4poJHnqH3281gDPm/metm6E/WRamfx7WC4HUqkWHfQHprw==",
- "dev": true,
- "dependencies": {
- "psl": "^1.1.33",
- "punycode": "^2.1.1",
- "universalify": "^0.2.0",
- "url-parse": "^1.5.3"
- },
- "engines": {
- "node": ">=6"
- }
- },
- "node_modules/tr46": {
- "version": "3.0.0",
- "resolved": "https://registry.npmjs.org/tr46/-/tr46-3.0.0.tgz",
- "integrity": "sha512-l7FvfAHlcmulp8kr+flpQZmVwtu7nfRV7NZujtN0OqES8EL4O4e0qqzL0DC5gAvx/ZC/9lk6rhcUwYvkBnBnYA==",
- "dev": true,
- "dependencies": {
- "punycode": "^2.1.1"
- },
- "engines": {
- "node": ">=12"
- }
- },
- "node_modules/tslib": {
- "version": "2.6.2",
- "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.6.2.tgz",
- "integrity": "sha512-AEYxH93jGFPn/a2iVAwW87VuUIkR1FVUKB77NwMF7nBTDkDrrT/Hpt/IrCJ0QXhW27jTBDcf5ZY7w6RiqTMw2Q==",
- "dev": true
- },
- "node_modules/type-detect": {
- "version": "4.0.8",
- "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz",
- "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==",
- "dev": true,
- "engines": {
- "node": ">=4"
- }
- },
- "node_modules/type-fest": {
- "version": "0.21.3",
- "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.21.3.tgz",
- "integrity": "sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==",
- "dev": true,
- "engines": {
- "node": ">=10"
- },
- "funding": {
- "url": "https://github.com/sponsors/sindresorhus"
- }
- },
- "node_modules/unicode-canonical-property-names-ecmascript": {
- "version": "2.0.0",
- "resolved": "https://registry.npmjs.org/unicode-canonical-property-names-ecmascript/-/unicode-canonical-property-names-ecmascript-2.0.0.tgz",
- "integrity": "sha512-yY5PpDlfVIU5+y/BSCxAJRBIS1Zc2dDG3Ujq+sR0U+JjUevW2JhocOF+soROYDSaAezOzOKuyyixhD6mBknSmQ==",
- "dev": true,
- "engines": {
- "node": ">=4"
- }
- },
- "node_modules/unicode-match-property-ecmascript": {
- "version": "2.0.0",
- "resolved": "https://registry.npmjs.org/unicode-match-property-ecmascript/-/unicode-match-property-ecmascript-2.0.0.tgz",
- "integrity": "sha512-5kaZCrbp5mmbz5ulBkDkbY0SsPOjKqVS35VpL9ulMPfSl0J0Xsm+9Evphv9CoIZFwre7aJoa94AY6seMKGVN5Q==",
- "dev": true,
- "dependencies": {
- "unicode-canonical-property-names-ecmascript": "^2.0.0",
- "unicode-property-aliases-ecmascript": "^2.0.0"
- },
- "engines": {
- "node": ">=4"
- }
- },
- "node_modules/unicode-match-property-value-ecmascript": {
- "version": "2.1.0",
- "resolved": "https://registry.npmjs.org/unicode-match-property-value-ecmascript/-/unicode-match-property-value-ecmascript-2.1.0.tgz",
- "integrity": "sha512-qxkjQt6qjg/mYscYMC0XKRn3Rh0wFPlfxB0xkt9CfyTvpX1Ra0+rAmdX2QyAobptSEvuy4RtpPRui6XkV+8wjA==",
- "dev": true,
- "engines": {
- "node": ">=4"
- }
- },
- "node_modules/unicode-property-aliases-ecmascript": {
- "version": "2.1.0",
- "resolved": "https://registry.npmjs.org/unicode-property-aliases-ecmascript/-/unicode-property-aliases-ecmascript-2.1.0.tgz",
- "integrity": "sha512-6t3foTQI9qne+OZoVQB/8x8rk2k1eVy1gRXhV3oFQ5T6R1dqQ1xtin3XqSlx3+ATBkliTaR/hHyJBm+LVPNM8w==",
- "dev": true,
- "engines": {
- "node": ">=4"
- }
- },
- "node_modules/universalify": {
- "version": "0.2.0",
- "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.2.0.tgz",
- "integrity": "sha512-CJ1QgKmNg3CwvAv/kOFmtnEN05f0D/cn9QntgNOQlQF9dgvVTHj3t+8JPdjqawCHk7V/KA+fbUqzZ9XWhcqPUg==",
- "dev": true,
- "engines": {
- "node": ">= 4.0.0"
- }
- },
- "node_modules/update-browserslist-db": {
- "version": "1.0.13",
- "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.0.13.tgz",
- "integrity": "sha512-xebP81SNcPuNpPP3uzeW1NYXxI3rxyJzF3pD6sH4jE7o/IX+WtSpwnVU+qIsDPyk0d3hmFQ7mjqc6AtV604hbg==",
- "dev": true,
- "funding": [
- {
- "type": "opencollective",
- "url": "https://opencollective.com/browserslist"
- },
- {
- "type": "tidelift",
- "url": "https://tidelift.com/funding/github/npm/browserslist"
- },
- {
- "type": "github",
- "url": "https://github.com/sponsors/ai"
- }
- ],
- "dependencies": {
- "escalade": "^3.1.1",
- "picocolors": "^1.0.0"
- },
- "bin": {
- "update-browserslist-db": "cli.js"
- },
- "peerDependencies": {
- "browserslist": ">= 4.21.0"
- }
- },
- "node_modules/url-parse": {
- "version": "1.5.10",
- "resolved": "https://registry.npmjs.org/url-parse/-/url-parse-1.5.10.tgz",
- "integrity": "sha512-WypcfiRhfeUP9vvF0j6rw0J3hrWrw6iZv3+22h6iRMJ/8z1Tj6XfLP4DsUix5MhMPnXpiHDoKyoZ/bdCkwBCiQ==",
- "dev": true,
- "dependencies": {
- "querystringify": "^2.1.1",
- "requires-port": "^1.0.0"
- }
- },
- "node_modules/v8-to-istanbul": {
- "version": "9.1.3",
- "resolved": "https://registry.npmjs.org/v8-to-istanbul/-/v8-to-istanbul-9.1.3.tgz",
- "integrity": "sha512-9lDD+EVI2fjFsMWXc6dy5JJzBsVTcQ2fVkfBvncZ6xJWG9wtBhOldG+mHkSL0+V1K/xgZz0JDO5UT5hFwHUghg==",
- "dev": true,
- "dependencies": {
- "@jridgewell/trace-mapping": "^0.3.12",
- "@types/istanbul-lib-coverage": "^2.0.1",
- "convert-source-map": "^2.0.0"
- },
- "engines": {
- "node": ">=10.12.0"
- }
- },
- "node_modules/w3c-xmlserializer": {
- "version": "4.0.0",
- "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-4.0.0.tgz",
- "integrity": "sha512-d+BFHzbiCx6zGfz0HyQ6Rg69w9k19nviJspaj4yNscGjrHu94sVP+aRm75yEbCh+r2/yR+7q6hux9LVtbuTGBw==",
- "dev": true,
- "dependencies": {
- "xml-name-validator": "^4.0.0"
- },
- "engines": {
- "node": ">=14"
- }
- },
- "node_modules/walker": {
- "version": "1.0.8",
- "resolved": "https://registry.npmjs.org/walker/-/walker-1.0.8.tgz",
- "integrity": "sha512-ts/8E8l5b7kY0vlWLewOkDXMmPdLcVV4GmOQLyxuSswIJsweeFZtAsMF7k1Nszz+TYBQrlYRmzOnr398y1JemQ==",
- "dev": true,
- "dependencies": {
- "makeerror": "1.0.12"
- }
- },
- "node_modules/webidl-conversions": {
- "version": "7.0.0",
- "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz",
- "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==",
- "dev": true,
- "engines": {
- "node": ">=12"
- }
- },
- "node_modules/whatwg-encoding": {
- "version": "2.0.0",
- "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-2.0.0.tgz",
- "integrity": "sha512-p41ogyeMUrw3jWclHWTQg1k05DSVXPLcVxRTYsXUk+ZooOCZLcoYgPZ/HL/D/N+uQPOtcp1me1WhBEaX02mhWg==",
- "dev": true,
- "dependencies": {
- "iconv-lite": "0.6.3"
- },
- "engines": {
- "node": ">=12"
- }
- },
- "node_modules/whatwg-mimetype": {
- "version": "3.0.0",
- "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-3.0.0.tgz",
- "integrity": "sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q==",
- "dev": true,
- "engines": {
- "node": ">=12"
- }
- },
- "node_modules/whatwg-url": {
- "version": "11.0.0",
- "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-11.0.0.tgz",
- "integrity": "sha512-RKT8HExMpoYx4igMiVMY83lN6UeITKJlBQ+vR/8ZJ8OCdSiN3RwCq+9gH0+Xzj0+5IrM6i4j/6LuvzbZIQgEcQ==",
- "dev": true,
- "dependencies": {
- "tr46": "^3.0.0",
- "webidl-conversions": "^7.0.0"
- },
- "engines": {
- "node": ">=12"
- }
- },
- "node_modules/which": {
- "version": "2.0.2",
- "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
- "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",
- "dev": true,
- "dependencies": {
- "isexe": "^2.0.0"
- },
- "bin": {
- "node-which": "bin/node-which"
- },
- "engines": {
- "node": ">= 8"
- }
- },
- "node_modules/wrap-ansi": {
- "version": "7.0.0",
- "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz",
- "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==",
- "dev": true,
- "dependencies": {
- "ansi-styles": "^4.0.0",
- "string-width": "^4.1.0",
- "strip-ansi": "^6.0.0"
- },
- "engines": {
- "node": ">=10"
- },
- "funding": {
- "url": "https://github.com/chalk/wrap-ansi?sponsor=1"
- }
- },
- "node_modules/wrappy": {
- "version": "1.0.2",
- "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
- "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
- "dev": true
- },
- "node_modules/write-file-atomic": {
- "version": "4.0.2",
- "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-4.0.2.tgz",
- "integrity": "sha512-7KxauUdBmSdWnmpaGFg+ppNjKF8uNLry8LyzjauQDOVONfFLNKrKvQOxZ/VuTIcS/gge/YNahf5RIIQWTSarlg==",
- "dev": true,
- "dependencies": {
- "imurmurhash": "^0.1.4",
- "signal-exit": "^3.0.7"
- },
- "engines": {
- "node": "^12.13.0 || ^14.15.0 || >=16.0.0"
- }
- },
- "node_modules/ws": {
- "version": "8.14.2",
- "resolved": "https://registry.npmjs.org/ws/-/ws-8.14.2.tgz",
- "integrity": "sha512-wEBG1ftX4jcglPxgFCMJmZ2PLtSbJ2Peg6TmpJFTbe9GZYOQCDPdMYu/Tm0/bGZkw8paZnJY45J4K2PZrLYq8g==",
- "dev": true,
- "engines": {
- "node": ">=10.0.0"
- },
- "peerDependencies": {
- "bufferutil": "^4.0.1",
- "utf-8-validate": ">=5.0.2"
- },
- "peerDependenciesMeta": {
- "bufferutil": {
- "optional": true
- },
- "utf-8-validate": {
- "optional": true
- }
- }
- },
- "node_modules/xml-name-validator": {
- "version": "4.0.0",
- "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-4.0.0.tgz",
- "integrity": "sha512-ICP2e+jsHvAj2E2lIHxa5tjXRlKDJo4IdvPvCXbXQGdzSfmSpNVyIKMvoZHjDY9DP0zV17iI85o90vRFXNccRw==",
- "dev": true,
- "engines": {
- "node": ">=12"
- }
- },
- "node_modules/xmlchars": {
- "version": "2.2.0",
- "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz",
- "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==",
- "dev": true
- },
- "node_modules/y18n": {
- "version": "5.0.8",
- "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",
- "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==",
- "dev": true,
- "engines": {
- "node": ">=10"
- }
- },
- "node_modules/yallist": {
- "version": "3.1.1",
- "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",
- "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==",
- "dev": true
- },
- "node_modules/yargs": {
- "version": "17.7.2",
- "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz",
- "integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==",
- "dev": true,
- "dependencies": {
- "cliui": "^8.0.1",
- "escalade": "^3.1.1",
- "get-caller-file": "^2.0.5",
- "require-directory": "^2.1.1",
- "string-width": "^4.2.3",
- "y18n": "^5.0.5",
- "yargs-parser": "^21.1.1"
- },
- "engines": {
- "node": ">=12"
- }
- },
- "node_modules/yargs-parser": {
- "version": "21.1.1",
- "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz",
- "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==",
- "dev": true,
- "engines": {
- "node": ">=12"
- }
- },
- "node_modules/yocto-queue": {
- "version": "0.1.0",
- "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz",
- "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==",
- "dev": true,
- "engines": {
- "node": ">=10"
- },
- "funding": {
- "url": "https://github.com/sponsors/sindresorhus"
- }
- }
- }
-}
diff --git a/tests-ui/package.json b/tests-ui/package.json
deleted file mode 100644
index ae7e49084..000000000
--- a/tests-ui/package.json
+++ /dev/null
@@ -1,31 +0,0 @@
-{
- "name": "comfui-tests",
- "version": "1.0.0",
- "description": "UI tests",
- "main": "index.js",
- "scripts": {
- "test": "jest",
- "test:generate": "node setup.js"
- },
- "repository": {
- "type": "git",
- "url": "git+https://github.com/comfyanonymous/ComfyUI.git"
- },
- "keywords": [
- "comfyui",
- "test"
- ],
- "author": "comfyanonymous",
- "license": "GPL-3.0",
- "bugs": {
- "url": "https://github.com/comfyanonymous/ComfyUI/issues"
- },
- "homepage": "https://github.com/comfyanonymous/ComfyUI#readme",
- "devDependencies": {
- "@babel/preset-env": "^7.22.20",
- "@types/jest": "^29.5.5",
- "babel-plugin-transform-import-meta": "^2.2.1",
- "jest": "^29.7.0",
- "jest-environment-jsdom": "^29.7.0"
- }
-}
diff --git a/tests-ui/setup.js b/tests-ui/setup.js
deleted file mode 100644
index 8bbd9dcdf..000000000
--- a/tests-ui/setup.js
+++ /dev/null
@@ -1,88 +0,0 @@
-const { spawn } = require("child_process");
-const { resolve } = require("path");
-const { existsSync, mkdirSync, writeFileSync } = require("fs");
-const http = require("http");
-
-async function setup() {
- // Wait up to 30s for it to start
- let success = false;
- let child;
- for (let i = 0; i < 30; i++) {
- try {
- await new Promise((res, rej) => {
- http
- .get("http://127.0.0.1:8188/object_info", (resp) => {
- let data = "";
- resp.on("data", (chunk) => {
- data += chunk;
- });
- resp.on("end", () => {
- // Modify the response data to add some checkpoints
- const objectInfo = JSON.parse(data);
- objectInfo.CheckpointLoaderSimple.input.required.ckpt_name[0] = ["model1.safetensors", "model2.ckpt"];
- objectInfo.VAELoader.input.required.vae_name[0] = ["vae1.safetensors", "vae2.ckpt"];
-
- data = JSON.stringify(objectInfo, undefined, "\t");
-
- const outDir = resolve("./data");
- if (!existsSync(outDir)) {
- mkdirSync(outDir);
- }
-
- const outPath = resolve(outDir, "object_info.json");
- console.log(`Writing ${Object.keys(objectInfo).length} nodes to ${outPath}`);
- writeFileSync(outPath, data, {
- encoding: "utf8",
- });
- res();
- });
- })
- .on("error", rej);
- });
- success = true;
- break;
- } catch (error) {
- console.log(i + "/30", error);
- if (i === 0) {
- // Start the server on first iteration if it fails to connect
- console.log("Starting ComfyUI server...");
-
- let python = resolve("../../python_embeded/python.exe");
- let args;
- let cwd;
- if (existsSync(python)) {
- args = ["-s", "ComfyUI/main.py"];
- cwd = "../..";
- } else {
- python = "python";
- args = ["main.py"];
- cwd = "..";
- }
- args.push("--cpu");
- console.log(python, ...args);
- child = spawn(python, args, { cwd });
- child.on("error", (err) => {
- console.log(`Server error (${err})`);
- i = 30;
- });
- child.on("exit", (code) => {
- if (!success) {
- console.log(`Server exited (${code})`);
- i = 30;
- }
- });
- }
- await new Promise((r) => {
- setTimeout(r, 1000);
- });
- }
- }
-
- child?.kill();
-
- if (!success) {
- throw new Error("Waiting for server failed...");
- }
-}
-
- setup();
\ No newline at end of file
diff --git a/tests-ui/tests/extensions.test.js b/tests-ui/tests/extensions.test.js
deleted file mode 100644
index 159e5113a..000000000
--- a/tests-ui/tests/extensions.test.js
+++ /dev/null
@@ -1,196 +0,0 @@
-// @ts-check
-///
-const { start } = require("../utils");
-const lg = require("../utils/litegraph");
-
-describe("extensions", () => {
- beforeEach(() => {
- lg.setup(global);
- });
-
- afterEach(() => {
- lg.teardown(global);
- });
-
- it("calls each extension hook", async () => {
- const mockExtension = {
- name: "TestExtension",
- init: jest.fn(),
- setup: jest.fn(),
- addCustomNodeDefs: jest.fn(),
- getCustomWidgets: jest.fn(),
- beforeRegisterNodeDef: jest.fn(),
- registerCustomNodes: jest.fn(),
- loadedGraphNode: jest.fn(),
- nodeCreated: jest.fn(),
- beforeConfigureGraph: jest.fn(),
- afterConfigureGraph: jest.fn(),
- };
-
- const { app, ez, graph } = await start({
- async preSetup(app) {
- app.registerExtension(mockExtension);
- },
- });
-
- // Basic initialisation hooks should be called once, with app
- expect(mockExtension.init).toHaveBeenCalledTimes(1);
- expect(mockExtension.init).toHaveBeenCalledWith(app);
-
- // Adding custom node defs should be passed the full list of nodes
- expect(mockExtension.addCustomNodeDefs).toHaveBeenCalledTimes(1);
- expect(mockExtension.addCustomNodeDefs.mock.calls[0][1]).toStrictEqual(app);
- const defs = mockExtension.addCustomNodeDefs.mock.calls[0][0];
- expect(defs).toHaveProperty("KSampler");
- expect(defs).toHaveProperty("LoadImage");
-
- // Get custom widgets is called once and should return new widget types
- expect(mockExtension.getCustomWidgets).toHaveBeenCalledTimes(1);
- expect(mockExtension.getCustomWidgets).toHaveBeenCalledWith(app);
-
- // Before register node def will be called once per node type
- const nodeNames = Object.keys(defs);
- const nodeCount = nodeNames.length;
- expect(mockExtension.beforeRegisterNodeDef).toHaveBeenCalledTimes(nodeCount);
- for (let i = 0; i < 10; i++) {
- // It should be send the JS class and the original JSON definition
- const nodeClass = mockExtension.beforeRegisterNodeDef.mock.calls[i][0];
- const nodeDef = mockExtension.beforeRegisterNodeDef.mock.calls[i][1];
-
- expect(nodeClass.name).toBe("ComfyNode");
- expect(nodeClass.comfyClass).toBe(nodeNames[i]);
- expect(nodeDef.name).toBe(nodeNames[i]);
- expect(nodeDef).toHaveProperty("input");
- expect(nodeDef).toHaveProperty("output");
- }
-
- // Register custom nodes is called once after registerNode defs to allow adding other frontend nodes
- expect(mockExtension.registerCustomNodes).toHaveBeenCalledTimes(1);
-
- // Before configure graph will be called here as the default graph is being loaded
- expect(mockExtension.beforeConfigureGraph).toHaveBeenCalledTimes(1);
- // it gets sent the graph data that is going to be loaded
- const graphData = mockExtension.beforeConfigureGraph.mock.calls[0][0];
-
- // A node created is fired for each node constructor that is called
- expect(mockExtension.nodeCreated).toHaveBeenCalledTimes(graphData.nodes.length);
- for (let i = 0; i < graphData.nodes.length; i++) {
- expect(mockExtension.nodeCreated.mock.calls[i][0].type).toBe(graphData.nodes[i].type);
- }
-
- // Each node then calls loadedGraphNode to allow them to be updated
- expect(mockExtension.loadedGraphNode).toHaveBeenCalledTimes(graphData.nodes.length);
- for (let i = 0; i < graphData.nodes.length; i++) {
- expect(mockExtension.loadedGraphNode.mock.calls[i][0].type).toBe(graphData.nodes[i].type);
- }
-
- // After configure is then called once all the setup is done
- expect(mockExtension.afterConfigureGraph).toHaveBeenCalledTimes(1);
-
- expect(mockExtension.setup).toHaveBeenCalledTimes(1);
- expect(mockExtension.setup).toHaveBeenCalledWith(app);
-
- // Ensure hooks are called in the correct order
- const callOrder = [
- "init",
- "addCustomNodeDefs",
- "getCustomWidgets",
- "beforeRegisterNodeDef",
- "registerCustomNodes",
- "beforeConfigureGraph",
- "nodeCreated",
- "loadedGraphNode",
- "afterConfigureGraph",
- "setup",
- ];
- for (let i = 1; i < callOrder.length; i++) {
- const fn1 = mockExtension[callOrder[i - 1]];
- const fn2 = mockExtension[callOrder[i]];
- expect(fn1.mock.invocationCallOrder[0]).toBeLessThan(fn2.mock.invocationCallOrder[0]);
- }
-
- graph.clear();
-
- // Ensure adding a new node calls the correct callback
- ez.LoadImage();
- expect(mockExtension.loadedGraphNode).toHaveBeenCalledTimes(graphData.nodes.length);
- expect(mockExtension.nodeCreated).toHaveBeenCalledTimes(graphData.nodes.length + 1);
- expect(mockExtension.nodeCreated.mock.lastCall[0].type).toBe("LoadImage");
-
- // Reload the graph to ensure correct hooks are fired
- await graph.reload();
-
- // These hooks should not be fired again
- expect(mockExtension.init).toHaveBeenCalledTimes(1);
- expect(mockExtension.addCustomNodeDefs).toHaveBeenCalledTimes(1);
- expect(mockExtension.getCustomWidgets).toHaveBeenCalledTimes(1);
- expect(mockExtension.registerCustomNodes).toHaveBeenCalledTimes(1);
- expect(mockExtension.beforeRegisterNodeDef).toHaveBeenCalledTimes(nodeCount);
- expect(mockExtension.setup).toHaveBeenCalledTimes(1);
-
- // These should be called again
- expect(mockExtension.beforeConfigureGraph).toHaveBeenCalledTimes(2);
- expect(mockExtension.nodeCreated).toHaveBeenCalledTimes(graphData.nodes.length + 2);
- expect(mockExtension.loadedGraphNode).toHaveBeenCalledTimes(graphData.nodes.length + 1);
- expect(mockExtension.afterConfigureGraph).toHaveBeenCalledTimes(2);
- }, 15000);
-
- it("allows custom nodeDefs and widgets to be registered", async () => {
- const widgetMock = jest.fn((node, inputName, inputData, app) => {
- expect(node.constructor.comfyClass).toBe("TestNode");
- expect(inputName).toBe("test_input");
- expect(inputData[0]).toBe("CUSTOMWIDGET");
- expect(inputData[1]?.hello).toBe("world");
- expect(app).toStrictEqual(app);
-
- return {
- widget: node.addWidget("button", inputName, "hello", () => {}),
- };
- });
-
- // Register our extension that adds a custom node + widget type
- const mockExtension = {
- name: "TestExtension",
- addCustomNodeDefs: (nodeDefs) => {
- nodeDefs["TestNode"] = {
- output: [],
- output_name: [],
- output_is_list: [],
- name: "TestNode",
- display_name: "TestNode",
- category: "Test",
- input: {
- required: {
- test_input: ["CUSTOMWIDGET", { hello: "world" }],
- },
- },
- };
- },
- getCustomWidgets: jest.fn(() => {
- return {
- CUSTOMWIDGET: widgetMock,
- };
- }),
- };
-
- const { graph, ez } = await start({
- async preSetup(app) {
- app.registerExtension(mockExtension);
- },
- });
-
- expect(mockExtension.getCustomWidgets).toBeCalledTimes(1);
-
- graph.clear();
- expect(widgetMock).toBeCalledTimes(0);
- const node = ez.TestNode();
- expect(widgetMock).toBeCalledTimes(1);
-
- // Ensure our custom widget is created
- expect(node.inputs.length).toBe(0);
- expect(node.widgets.length).toBe(1);
- const w = node.widgets[0].widget;
- expect(w.name).toBe("test_input");
- expect(w.type).toBe("button");
- });
-});
diff --git a/tests-ui/tests/groupNode.test.js b/tests-ui/tests/groupNode.test.js
deleted file mode 100644
index 53a5828d1..000000000
--- a/tests-ui/tests/groupNode.test.js
+++ /dev/null
@@ -1,1005 +0,0 @@
-// @ts-check
-///
-
-const { start, createDefaultWorkflow, getNodeDef, checkBeforeAndAfterReload } = require("../utils");
-const lg = require("../utils/litegraph");
-
-describe("group node", () => {
- beforeEach(() => {
- lg.setup(global);
- });
-
- afterEach(() => {
- lg.teardown(global);
- });
-
- /**
- *
- * @param {*} app
- * @param {*} graph
- * @param {*} name
- * @param {*} nodes
- * @returns { Promise> }
- */
- async function convertToGroup(app, graph, name, nodes) {
- // Select the nodes we are converting
- for (const n of nodes) {
- n.select(true);
- }
-
- expect(Object.keys(app.canvas.selected_nodes).sort((a, b) => +a - +b)).toEqual(
- nodes.map((n) => n.id + "").sort((a, b) => +a - +b)
- );
-
- global.prompt = jest.fn().mockImplementation(() => name);
- const groupNode = await nodes[0].menu["Convert to Group Node"].call(false);
-
- // Check group name was requested
- expect(window.prompt).toHaveBeenCalled();
-
- // Ensure old nodes are removed
- for (const n of nodes) {
- expect(n.isRemoved).toBeTruthy();
- }
-
- expect(groupNode.type).toEqual("workflow/" + name);
-
- return graph.find(groupNode);
- }
-
- /**
- * @param { Record | number[] } idMap
- * @param { Record> } valueMap
- */
- function getOutput(idMap = {}, valueMap = {}) {
- if (idMap instanceof Array) {
- idMap = idMap.reduce((p, n) => {
- p[n] = n + "";
- return p;
- }, {});
- }
- const expected = {
- 1: { inputs: { ckpt_name: "model1.safetensors", ...valueMap?.[1] }, class_type: "CheckpointLoaderSimple" },
- 2: { inputs: { text: "positive", clip: ["1", 1], ...valueMap?.[2] }, class_type: "CLIPTextEncode" },
- 3: { inputs: { text: "negative", clip: ["1", 1], ...valueMap?.[3] }, class_type: "CLIPTextEncode" },
- 4: { inputs: { width: 512, height: 512, batch_size: 1, ...valueMap?.[4] }, class_type: "EmptyLatentImage" },
- 5: {
- inputs: {
- seed: 0,
- steps: 20,
- cfg: 8,
- sampler_name: "euler",
- scheduler: "normal",
- denoise: 1,
- model: ["1", 0],
- positive: ["2", 0],
- negative: ["3", 0],
- latent_image: ["4", 0],
- ...valueMap?.[5],
- },
- class_type: "KSampler",
- },
- 6: { inputs: { samples: ["5", 0], vae: ["1", 2], ...valueMap?.[6] }, class_type: "VAEDecode" },
- 7: { inputs: { filename_prefix: "ComfyUI", images: ["6", 0], ...valueMap?.[7] }, class_type: "SaveImage" },
- };
-
- // Map old IDs to new at the top level
- const mapped = {};
- for (const oldId in idMap) {
- mapped[idMap[oldId]] = expected[oldId];
- delete expected[oldId];
- }
- Object.assign(mapped, expected);
-
- // Map old IDs to new inside links
- for (const k in mapped) {
- for (const input in mapped[k].inputs) {
- const v = mapped[k].inputs[input];
- if (v instanceof Array) {
- if (v[0] in idMap) {
- v[0] = idMap[v[0]] + "";
- }
- }
- }
- }
-
- return mapped;
- }
-
- test("can be created from selected nodes", async () => {
- const { ez, graph, app } = await start();
- const nodes = createDefaultWorkflow(ez, graph);
- const group = await convertToGroup(app, graph, "test", [nodes.pos, nodes.neg, nodes.empty]);
-
- // Ensure links are now to the group node
- expect(group.inputs).toHaveLength(2);
- expect(group.outputs).toHaveLength(3);
-
- expect(group.inputs.map((i) => i.input.name)).toEqual(["clip", "CLIPTextEncode clip"]);
- expect(group.outputs.map((i) => i.output.name)).toEqual(["LATENT", "CONDITIONING", "CLIPTextEncode CONDITIONING"]);
-
- // ckpt clip to both clip inputs on the group
- expect(nodes.ckpt.outputs.CLIP.connections.map((t) => [t.targetNode.id, t.targetInput.index])).toEqual([
- [group.id, 0],
- [group.id, 1],
- ]);
-
- // group conditioning to sampler
- expect(group.outputs["CONDITIONING"].connections.map((t) => [t.targetNode.id, t.targetInput.index])).toEqual([
- [nodes.sampler.id, 1],
- ]);
- // group conditioning 2 to sampler
- expect(
- group.outputs["CLIPTextEncode CONDITIONING"].connections.map((t) => [t.targetNode.id, t.targetInput.index])
- ).toEqual([[nodes.sampler.id, 2]]);
- // group latent to sampler
- expect(group.outputs["LATENT"].connections.map((t) => [t.targetNode.id, t.targetInput.index])).toEqual([
- [nodes.sampler.id, 3],
- ]);
- });
-
- test("maintains all output links on conversion", async () => {
- const { ez, graph, app } = await start();
- const nodes = createDefaultWorkflow(ez, graph);
- const save2 = ez.SaveImage(...nodes.decode.outputs);
- const save3 = ez.SaveImage(...nodes.decode.outputs);
- // Ensure an output with multiple links maintains them on convert to group
- const group = await convertToGroup(app, graph, "test", [nodes.sampler, nodes.decode]);
- expect(group.outputs[0].connections.length).toBe(3);
- expect(group.outputs[0].connections[0].targetNode.id).toBe(nodes.save.id);
- expect(group.outputs[0].connections[1].targetNode.id).toBe(save2.id);
- expect(group.outputs[0].connections[2].targetNode.id).toBe(save3.id);
-
- // and they're still linked when converting back to nodes
- const newNodes = group.menu["Convert to nodes"].call();
- const decode = graph.find(newNodes.find((n) => n.type === "VAEDecode"));
- expect(decode.outputs[0].connections.length).toBe(3);
- expect(decode.outputs[0].connections[0].targetNode.id).toBe(nodes.save.id);
- expect(decode.outputs[0].connections[1].targetNode.id).toBe(save2.id);
- expect(decode.outputs[0].connections[2].targetNode.id).toBe(save3.id);
- });
- test("can be be converted back to nodes", async () => {
- const { ez, graph, app } = await start();
- const nodes = createDefaultWorkflow(ez, graph);
- const toConvert = [nodes.pos, nodes.neg, nodes.empty, nodes.sampler];
- const group = await convertToGroup(app, graph, "test", toConvert);
-
- // Edit some values to ensure they are set back onto the converted nodes
- expect(group.widgets["text"].value).toBe("positive");
- group.widgets["text"].value = "pos";
- expect(group.widgets["CLIPTextEncode text"].value).toBe("negative");
- group.widgets["CLIPTextEncode text"].value = "neg";
- expect(group.widgets["width"].value).toBe(512);
- group.widgets["width"].value = 1024;
- expect(group.widgets["sampler_name"].value).toBe("euler");
- group.widgets["sampler_name"].value = "ddim";
- expect(group.widgets["control_after_generate"].value).toBe("randomize");
- group.widgets["control_after_generate"].value = "fixed";
-
- /** @type { Array } */
- group.menu["Convert to nodes"].call();
-
- // ensure widget values are set
- const pos = graph.find(nodes.pos.id);
- expect(pos.node.type).toBe("CLIPTextEncode");
- expect(pos.widgets["text"].value).toBe("pos");
- const neg = graph.find(nodes.neg.id);
- expect(neg.node.type).toBe("CLIPTextEncode");
- expect(neg.widgets["text"].value).toBe("neg");
- const empty = graph.find(nodes.empty.id);
- expect(empty.node.type).toBe("EmptyLatentImage");
- expect(empty.widgets["width"].value).toBe(1024);
- const sampler = graph.find(nodes.sampler.id);
- expect(sampler.node.type).toBe("KSampler");
- expect(sampler.widgets["sampler_name"].value).toBe("ddim");
- expect(sampler.widgets["control_after_generate"].value).toBe("fixed");
-
- // validate links
- expect(nodes.ckpt.outputs.CLIP.connections.map((t) => [t.targetNode.id, t.targetInput.index])).toEqual([
- [pos.id, 0],
- [neg.id, 0],
- ]);
-
- expect(pos.outputs["CONDITIONING"].connections.map((t) => [t.targetNode.id, t.targetInput.index])).toEqual([
- [nodes.sampler.id, 1],
- ]);
-
- expect(neg.outputs["CONDITIONING"].connections.map((t) => [t.targetNode.id, t.targetInput.index])).toEqual([
- [nodes.sampler.id, 2],
- ]);
-
- expect(empty.outputs["LATENT"].connections.map((t) => [t.targetNode.id, t.targetInput.index])).toEqual([
- [nodes.sampler.id, 3],
- ]);
- });
- test("it can embed reroutes as inputs", async () => {
- const { ez, graph, app } = await start();
- const nodes = createDefaultWorkflow(ez, graph);
-
- // Add and connect a reroute to the clip text encodes
- const reroute = ez.Reroute();
- nodes.ckpt.outputs.CLIP.connectTo(reroute.inputs[0]);
- reroute.outputs[0].connectTo(nodes.pos.inputs[0]);
- reroute.outputs[0].connectTo(nodes.neg.inputs[0]);
-
- // Convert to group and ensure we only have 1 input of the correct type
- const group = await convertToGroup(app, graph, "test", [nodes.pos, nodes.neg, nodes.empty, reroute]);
- expect(group.inputs).toHaveLength(1);
- expect(group.inputs[0].input.type).toEqual("CLIP");
-
- expect((await graph.toPrompt()).output).toEqual(getOutput());
- });
- test("it can embed reroutes as outputs", async () => {
- const { ez, graph, app } = await start();
- const nodes = createDefaultWorkflow(ez, graph);
-
- // Add a reroute with no output so we output IMAGE even though its used internally
- const reroute = ez.Reroute();
- nodes.decode.outputs.IMAGE.connectTo(reroute.inputs[0]);
-
- // Convert to group and ensure there is an IMAGE output
- const group = await convertToGroup(app, graph, "test", [nodes.decode, nodes.save, reroute]);
- expect(group.outputs).toHaveLength(1);
- expect(group.outputs[0].output.type).toEqual("IMAGE");
- expect((await graph.toPrompt()).output).toEqual(getOutput([nodes.decode.id, nodes.save.id]));
- });
- test("it can embed reroutes as pipes", async () => {
- const { ez, graph, app } = await start();
- const nodes = createDefaultWorkflow(ez, graph);
-
- // Use reroutes as a pipe
- const rerouteModel = ez.Reroute();
- const rerouteClip = ez.Reroute();
- const rerouteVae = ez.Reroute();
- nodes.ckpt.outputs.MODEL.connectTo(rerouteModel.inputs[0]);
- nodes.ckpt.outputs.CLIP.connectTo(rerouteClip.inputs[0]);
- nodes.ckpt.outputs.VAE.connectTo(rerouteVae.inputs[0]);
-
- const group = await convertToGroup(app, graph, "test", [rerouteModel, rerouteClip, rerouteVae]);
-
- expect(group.outputs).toHaveLength(3);
- expect(group.outputs.map((o) => o.output.type)).toEqual(["MODEL", "CLIP", "VAE"]);
-
- expect(group.outputs).toHaveLength(3);
- expect(group.outputs.map((o) => o.output.type)).toEqual(["MODEL", "CLIP", "VAE"]);
-
- group.outputs[0].connectTo(nodes.sampler.inputs.model);
- group.outputs[1].connectTo(nodes.pos.inputs.clip);
- group.outputs[1].connectTo(nodes.neg.inputs.clip);
- });
- test("can handle reroutes used internally", async () => {
- const { ez, graph, app } = await start();
- const nodes = createDefaultWorkflow(ez, graph);
-
- let reroutes = [];
- let prevNode = nodes.ckpt;
- for (let i = 0; i < 5; i++) {
- const reroute = ez.Reroute();
- prevNode.outputs[0].connectTo(reroute.inputs[0]);
- prevNode = reroute;
- reroutes.push(reroute);
- }
- prevNode.outputs[0].connectTo(nodes.sampler.inputs.model);
-
- const group = await convertToGroup(app, graph, "test", [...reroutes, ...Object.values(nodes)]);
- expect((await graph.toPrompt()).output).toEqual(getOutput());
-
- group.menu["Convert to nodes"].call();
- expect((await graph.toPrompt()).output).toEqual(getOutput());
- });
- test("creates with widget values from inner nodes", async () => {
- const { ez, graph, app } = await start();
- const nodes = createDefaultWorkflow(ez, graph);
-
- nodes.ckpt.widgets.ckpt_name.value = "model2.ckpt";
- nodes.pos.widgets.text.value = "hello";
- nodes.neg.widgets.text.value = "world";
- nodes.empty.widgets.width.value = 256;
- nodes.empty.widgets.height.value = 1024;
- nodes.sampler.widgets.seed.value = 1;
- nodes.sampler.widgets.control_after_generate.value = "increment";
- nodes.sampler.widgets.steps.value = 8;
- nodes.sampler.widgets.cfg.value = 4.5;
- nodes.sampler.widgets.sampler_name.value = "uni_pc";
- nodes.sampler.widgets.scheduler.value = "karras";
- nodes.sampler.widgets.denoise.value = 0.9;
-
- const group = await convertToGroup(app, graph, "test", [
- nodes.ckpt,
- nodes.pos,
- nodes.neg,
- nodes.empty,
- nodes.sampler,
- ]);
-
- expect(group.widgets["ckpt_name"].value).toEqual("model2.ckpt");
- expect(group.widgets["text"].value).toEqual("hello");
- expect(group.widgets["CLIPTextEncode text"].value).toEqual("world");
- expect(group.widgets["width"].value).toEqual(256);
- expect(group.widgets["height"].value).toEqual(1024);
- expect(group.widgets["seed"].value).toEqual(1);
- expect(group.widgets["control_after_generate"].value).toEqual("increment");
- expect(group.widgets["steps"].value).toEqual(8);
- expect(group.widgets["cfg"].value).toEqual(4.5);
- expect(group.widgets["sampler_name"].value).toEqual("uni_pc");
- expect(group.widgets["scheduler"].value).toEqual("karras");
- expect(group.widgets["denoise"].value).toEqual(0.9);
-
- expect((await graph.toPrompt()).output).toEqual(
- getOutput([nodes.ckpt.id, nodes.pos.id, nodes.neg.id, nodes.empty.id, nodes.sampler.id], {
- [nodes.ckpt.id]: { ckpt_name: "model2.ckpt" },
- [nodes.pos.id]: { text: "hello" },
- [nodes.neg.id]: { text: "world" },
- [nodes.empty.id]: { width: 256, height: 1024 },
- [nodes.sampler.id]: {
- seed: 1,
- steps: 8,
- cfg: 4.5,
- sampler_name: "uni_pc",
- scheduler: "karras",
- denoise: 0.9,
- },
- })
- );
- });
- test("group inputs can be reroutes", async () => {
- const { ez, graph, app } = await start();
- const nodes = createDefaultWorkflow(ez, graph);
- const group = await convertToGroup(app, graph, "test", [nodes.pos, nodes.neg]);
-
- const reroute = ez.Reroute();
- nodes.ckpt.outputs.CLIP.connectTo(reroute.inputs[0]);
-
- reroute.outputs[0].connectTo(group.inputs[0]);
- reroute.outputs[0].connectTo(group.inputs[1]);
-
- expect((await graph.toPrompt()).output).toEqual(getOutput([nodes.pos.id, nodes.neg.id]));
- });
- test("group outputs can be reroutes", async () => {
- const { ez, graph, app } = await start();
- const nodes = createDefaultWorkflow(ez, graph);
- const group = await convertToGroup(app, graph, "test", [nodes.pos, nodes.neg]);
-
- const reroute1 = ez.Reroute();
- const reroute2 = ez.Reroute();
- group.outputs[0].connectTo(reroute1.inputs[0]);
- group.outputs[1].connectTo(reroute2.inputs[0]);
-
- reroute1.outputs[0].connectTo(nodes.sampler.inputs.positive);
- reroute2.outputs[0].connectTo(nodes.sampler.inputs.negative);
-
- expect((await graph.toPrompt()).output).toEqual(getOutput([nodes.pos.id, nodes.neg.id]));
- });
- test("groups can connect to each other", async () => {
- const { ez, graph, app } = await start();
- const nodes = createDefaultWorkflow(ez, graph);
- const group1 = await convertToGroup(app, graph, "test", [nodes.pos, nodes.neg]);
- const group2 = await convertToGroup(app, graph, "test2", [nodes.empty, nodes.sampler]);
-
- group1.outputs[0].connectTo(group2.inputs["positive"]);
- group1.outputs[1].connectTo(group2.inputs["negative"]);
-
- expect((await graph.toPrompt()).output).toEqual(
- getOutput([nodes.pos.id, nodes.neg.id, nodes.empty.id, nodes.sampler.id])
- );
- });
- test("groups can connect to each other via internal reroutes", async () => {
- const { ez, graph, app } = await start();
-
- const latent = ez.EmptyLatentImage();
- const vae = ez.VAELoader();
- const latentReroute = ez.Reroute();
- const vaeReroute = ez.Reroute();
-
- latent.outputs[0].connectTo(latentReroute.inputs[0]);
- vae.outputs[0].connectTo(vaeReroute.inputs[0]);
-
- const group1 = await convertToGroup(app, graph, "test", [latentReroute, vaeReroute]);
- group1.menu.Clone.call();
- expect(app.graph._nodes).toHaveLength(4);
- const group2 = graph.find(app.graph._nodes[3]);
- expect(group2.node.type).toEqual("workflow/test");
- expect(group2.id).not.toEqual(group1.id);
-
- group1.outputs.VAE.connectTo(group2.inputs.VAE);
- group1.outputs.LATENT.connectTo(group2.inputs.LATENT);
-
- const decode = ez.VAEDecode(group2.outputs.LATENT, group2.outputs.VAE);
- const preview = ez.PreviewImage(decode.outputs[0]);
-
- const output = {
- [latent.id]: { inputs: { width: 512, height: 512, batch_size: 1 }, class_type: "EmptyLatentImage" },
- [vae.id]: { inputs: { vae_name: "vae1.safetensors" }, class_type: "VAELoader" },
- [decode.id]: { inputs: { samples: [latent.id + "", 0], vae: [vae.id + "", 0] }, class_type: "VAEDecode" },
- [preview.id]: { inputs: { images: [decode.id + "", 0] }, class_type: "PreviewImage" },
- };
- expect((await graph.toPrompt()).output).toEqual(output);
-
- // Ensure missing connections dont cause errors
- group2.inputs.VAE.disconnect();
- delete output[decode.id].inputs.vae;
- expect((await graph.toPrompt()).output).toEqual(output);
- });
- test("displays generated image on group node", async () => {
- const { ez, graph, app } = await start();
- const nodes = createDefaultWorkflow(ez, graph);
- let group = await convertToGroup(app, graph, "test", [
- nodes.pos,
- nodes.neg,
- nodes.empty,
- nodes.sampler,
- nodes.decode,
- nodes.save,
- ]);
-
- const { api } = require("../../web/scripts/api");
-
- api.dispatchEvent(new CustomEvent("execution_start", {}));
- api.dispatchEvent(new CustomEvent("executing", { detail: `${nodes.save.id}` }));
- // Event should be forwarded to group node id
- expect(+app.runningNodeId).toEqual(group.id);
- expect(group.node["imgs"]).toBeFalsy();
- api.dispatchEvent(
- new CustomEvent("executed", {
- detail: {
- node: `${nodes.save.id}`,
- output: {
- images: [
- {
- filename: "test.png",
- type: "output",
- },
- ],
- },
- },
- })
- );
-
- // Trigger paint
- group.node.onDrawBackground?.(app.canvas.ctx, app.canvas.canvas);
-
- expect(group.node["images"]).toEqual([
- {
- filename: "test.png",
- type: "output",
- },
- ]);
-
- // Reload
- const workflow = JSON.stringify((await graph.toPrompt()).workflow);
- await app.loadGraphData(JSON.parse(workflow));
- group = graph.find(group);
-
- // Trigger inner nodes to get created
- group.node["getInnerNodes"]();
-
- // Check it works for internal node ids
- api.dispatchEvent(new CustomEvent("execution_start", {}));
- api.dispatchEvent(new CustomEvent("executing", { detail: `${group.id}:5` }));
- // Event should be forwarded to group node id
- expect(+app.runningNodeId).toEqual(group.id);
- expect(group.node["imgs"]).toBeFalsy();
- api.dispatchEvent(
- new CustomEvent("executed", {
- detail: {
- node: `${group.id}:5`,
- output: {
- images: [
- {
- filename: "test2.png",
- type: "output",
- },
- ],
- },
- },
- })
- );
-
- // Trigger paint
- group.node.onDrawBackground?.(app.canvas.ctx, app.canvas.canvas);
-
- expect(group.node["images"]).toEqual([
- {
- filename: "test2.png",
- type: "output",
- },
- ]);
- });
- test("allows widgets to be converted to inputs", async () => {
- const { ez, graph, app } = await start();
- const nodes = createDefaultWorkflow(ez, graph);
- const group = await convertToGroup(app, graph, "test", [nodes.pos, nodes.neg]);
- group.widgets[0].convertToInput();
-
- const primitive = ez.PrimitiveNode();
- primitive.outputs[0].connectTo(group.inputs["text"]);
- primitive.widgets[0].value = "hello";
-
- expect((await graph.toPrompt()).output).toEqual(
- getOutput([nodes.pos.id, nodes.neg.id], {
- [nodes.pos.id]: { text: "hello" },
- })
- );
- });
- test("can be copied", async () => {
- const { ez, graph, app } = await start();
- const nodes = createDefaultWorkflow(ez, graph);
-
- const group1 = await convertToGroup(app, graph, "test", [
- nodes.pos,
- nodes.neg,
- nodes.empty,
- nodes.sampler,
- nodes.decode,
- nodes.save,
- ]);
-
- group1.widgets["text"].value = "hello";
- group1.widgets["width"].value = 256;
- group1.widgets["seed"].value = 1;
-
- // Clone the node
- group1.menu.Clone.call();
- expect(app.graph._nodes).toHaveLength(3);
- const group2 = graph.find(app.graph._nodes[2]);
- expect(group2.node.type).toEqual("workflow/test");
- expect(group2.id).not.toEqual(group1.id);
-
- // Reconnect ckpt
- nodes.ckpt.outputs.MODEL.connectTo(group2.inputs["model"]);
- nodes.ckpt.outputs.CLIP.connectTo(group2.inputs["clip"]);
- nodes.ckpt.outputs.CLIP.connectTo(group2.inputs["CLIPTextEncode clip"]);
- nodes.ckpt.outputs.VAE.connectTo(group2.inputs["vae"]);
-
- group2.widgets["text"].value = "world";
- group2.widgets["width"].value = 1024;
- group2.widgets["seed"].value = 100;
-
- let i = 0;
- expect((await graph.toPrompt()).output).toEqual({
- ...getOutput([nodes.empty.id, nodes.pos.id, nodes.neg.id, nodes.sampler.id, nodes.decode.id, nodes.save.id], {
- [nodes.empty.id]: { width: 256 },
- [nodes.pos.id]: { text: "hello" },
- [nodes.sampler.id]: { seed: 1 },
- }),
- ...getOutput(
- {
- [nodes.empty.id]: `${group2.id}:${i++}`,
- [nodes.pos.id]: `${group2.id}:${i++}`,
- [nodes.neg.id]: `${group2.id}:${i++}`,
- [nodes.sampler.id]: `${group2.id}:${i++}`,
- [nodes.decode.id]: `${group2.id}:${i++}`,
- [nodes.save.id]: `${group2.id}:${i++}`,
- },
- {
- [nodes.empty.id]: { width: 1024 },
- [nodes.pos.id]: { text: "world" },
- [nodes.sampler.id]: { seed: 100 },
- }
- ),
- });
-
- graph.arrange();
- });
- test("is embedded in workflow", async () => {
- let { ez, graph, app } = await start();
- const nodes = createDefaultWorkflow(ez, graph);
- let group = await convertToGroup(app, graph, "test", [nodes.pos, nodes.neg]);
- const workflow = JSON.stringify((await graph.toPrompt()).workflow);
-
- // Clear the environment
- ({ ez, graph, app } = await start({
- resetEnv: true,
- }));
- // Ensure the node isnt registered
- expect(() => ez["workflow/test"]).toThrow();
-
- // Reload the workflow
- await app.loadGraphData(JSON.parse(workflow));
-
- // Ensure the node is found
- group = graph.find(group);
-
- // Generate prompt and ensure it is as expected
- expect((await graph.toPrompt()).output).toEqual(
- getOutput({
- [nodes.pos.id]: `${group.id}:0`,
- [nodes.neg.id]: `${group.id}:1`,
- })
- );
- });
- test("shows missing node error on missing internal node when loading graph data", async () => {
- const { graph } = await start();
-
- const dialogShow = jest.spyOn(graph.app.ui.dialog, "show");
- await graph.app.loadGraphData({
- last_node_id: 3,
- last_link_id: 1,
- nodes: [
- {
- id: 3,
- type: "workflow/testerror",
- },
- ],
- links: [],
- groups: [],
- config: {},
- extra: {
- groupNodes: {
- testerror: {
- nodes: [
- {
- type: "NotKSampler",
- },
- {
- type: "NotVAEDecode",
- },
- ],
- },
- },
- },
- });
-
- expect(dialogShow).toBeCalledTimes(1);
- const call = dialogShow.mock.calls[0][0].innerHTML;
- expect(call).toContain("the following node types were not found");
- expect(call).toContain("NotKSampler");
- expect(call).toContain("NotVAEDecode");
- expect(call).toContain("workflow/testerror");
- });
- test("maintains widget inputs on conversion back to nodes", async () => {
- const { ez, graph, app } = await start();
- let pos = ez.CLIPTextEncode({ text: "positive" });
- pos.node.title = "Positive";
- let neg = ez.CLIPTextEncode({ text: "negative" });
- neg.node.title = "Negative";
- pos.widgets.text.convertToInput();
- neg.widgets.text.convertToInput();
-
- let primitive = ez.PrimitiveNode();
- primitive.outputs[0].connectTo(pos.inputs.text);
- primitive.outputs[0].connectTo(neg.inputs.text);
-
- const group = await convertToGroup(app, graph, "test", [pos, neg, primitive]);
- // This will use a primitive widget named 'value'
- expect(group.widgets.length).toBe(1);
- expect(group.widgets["value"].value).toBe("positive");
-
- const newNodes = group.menu["Convert to nodes"].call();
- pos = graph.find(newNodes.find((n) => n.title === "Positive"));
- neg = graph.find(newNodes.find((n) => n.title === "Negative"));
- primitive = graph.find(newNodes.find((n) => n.type === "PrimitiveNode"));
-
- expect(pos.inputs).toHaveLength(2);
- expect(neg.inputs).toHaveLength(2);
- expect(primitive.outputs[0].connections).toHaveLength(2);
-
- expect((await graph.toPrompt()).output).toEqual({
- 1: { inputs: { text: "positive" }, class_type: "CLIPTextEncode" },
- 2: { inputs: { text: "positive" }, class_type: "CLIPTextEncode" },
- });
- });
- test("correctly handles widget inputs", async () => {
- const { ez, graph, app } = await start();
- const upscaleMethods = (await getNodeDef("ImageScaleBy")).input.required["upscale_method"][0];
-
- const image = ez.LoadImage();
- const scale1 = ez.ImageScaleBy(image.outputs[0]);
- const scale2 = ez.ImageScaleBy(image.outputs[0]);
- const preview1 = ez.PreviewImage(scale1.outputs[0]);
- const preview2 = ez.PreviewImage(scale2.outputs[0]);
- scale1.widgets.upscale_method.value = upscaleMethods[1];
- scale1.widgets.upscale_method.convertToInput();
-
- const group = await convertToGroup(app, graph, "test", [scale1, scale2]);
- expect(group.inputs.length).toBe(3);
- expect(group.inputs[0].input.type).toBe("IMAGE");
- expect(group.inputs[1].input.type).toBe("IMAGE");
- expect(group.inputs[2].input.type).toBe("COMBO");
-
- // Ensure links are maintained
- expect(group.inputs[0].connection?.originNode?.id).toBe(image.id);
- expect(group.inputs[1].connection?.originNode?.id).toBe(image.id);
- expect(group.inputs[2].connection).toBeFalsy();
-
- // Ensure primitive gets correct type
- const primitive = ez.PrimitiveNode();
- primitive.outputs[0].connectTo(group.inputs[2]);
- expect(primitive.widgets.value.widget.options.values).toBe(upscaleMethods);
- expect(primitive.widgets.value.value).toBe(upscaleMethods[1]); // Ensure value is copied
- primitive.widgets.value.value = upscaleMethods[1];
-
- await checkBeforeAndAfterReload(graph, async (r) => {
- const scale1id = r ? `${group.id}:0` : scale1.id;
- const scale2id = r ? `${group.id}:1` : scale2.id;
- // Ensure widget value is applied to prompt
- expect((await graph.toPrompt()).output).toStrictEqual({
- [image.id]: { inputs: { image: "example.png", upload: "image" }, class_type: "LoadImage" },
- [scale1id]: {
- inputs: { upscale_method: upscaleMethods[1], scale_by: 1, image: [`${image.id}`, 0] },
- class_type: "ImageScaleBy",
- },
- [scale2id]: {
- inputs: { upscale_method: "nearest-exact", scale_by: 1, image: [`${image.id}`, 0] },
- class_type: "ImageScaleBy",
- },
- [preview1.id]: { inputs: { images: [`${scale1id}`, 0] }, class_type: "PreviewImage" },
- [preview2.id]: { inputs: { images: [`${scale2id}`, 0] }, class_type: "PreviewImage" },
- });
- });
- });
- test("adds widgets in node execution order", async () => {
- const { ez, graph, app } = await start();
- const scale = ez.LatentUpscale();
- const save = ez.SaveImage();
- const empty = ez.EmptyLatentImage();
- const decode = ez.VAEDecode();
-
- scale.outputs.LATENT.connectTo(decode.inputs.samples);
- decode.outputs.IMAGE.connectTo(save.inputs.images);
- empty.outputs.LATENT.connectTo(scale.inputs.samples);
-
- const group = await convertToGroup(app, graph, "test", [scale, save, empty, decode]);
- const widgets = group.widgets.map((w) => w.widget.name);
- expect(widgets).toStrictEqual([
- "width",
- "height",
- "batch_size",
- "upscale_method",
- "LatentUpscale width",
- "LatentUpscale height",
- "crop",
- "filename_prefix",
- ]);
- });
- test("adds output for external links when converting to group", async () => {
- const { ez, graph, app } = await start();
- const img = ez.EmptyLatentImage();
- let decode = ez.VAEDecode(...img.outputs);
- const preview1 = ez.PreviewImage(...decode.outputs);
- const preview2 = ez.PreviewImage(...decode.outputs);
-
- const group = await convertToGroup(app, graph, "test", [img, decode, preview1]);
-
- // Ensure we have an output connected to the 2nd preview node
- expect(group.outputs.length).toBe(1);
- expect(group.outputs[0].connections.length).toBe(1);
- expect(group.outputs[0].connections[0].targetNode.id).toBe(preview2.id);
-
- // Convert back and ensure bothe previews are still connected
- group.menu["Convert to nodes"].call();
- decode = graph.find(decode);
- expect(decode.outputs[0].connections.length).toBe(2);
- expect(decode.outputs[0].connections[0].targetNode.id).toBe(preview1.id);
- expect(decode.outputs[0].connections[1].targetNode.id).toBe(preview2.id);
- });
- test("adds output for external links when converting to group when nodes are not in execution order", async () => {
- const { ez, graph, app } = await start();
- const sampler = ez.KSampler();
- const ckpt = ez.CheckpointLoaderSimple();
- const empty = ez.EmptyLatentImage();
- const pos = ez.CLIPTextEncode(ckpt.outputs.CLIP, { text: "positive" });
- const neg = ez.CLIPTextEncode(ckpt.outputs.CLIP, { text: "negative" });
- const decode1 = ez.VAEDecode(sampler.outputs.LATENT, ckpt.outputs.VAE);
- const save = ez.SaveImage(decode1.outputs.IMAGE);
- ckpt.outputs.MODEL.connectTo(sampler.inputs.model);
- pos.outputs.CONDITIONING.connectTo(sampler.inputs.positive);
- neg.outputs.CONDITIONING.connectTo(sampler.inputs.negative);
- empty.outputs.LATENT.connectTo(sampler.inputs.latent_image);
-
- const encode = ez.VAEEncode(decode1.outputs.IMAGE);
- const vae = ez.VAELoader();
- const decode2 = ez.VAEDecode(encode.outputs.LATENT, vae.outputs.VAE);
- const preview = ez.PreviewImage(decode2.outputs.IMAGE);
- vae.outputs.VAE.connectTo(encode.inputs.vae);
-
- const group = await convertToGroup(app, graph, "test", [vae, decode1, encode, sampler]);
-
- expect(group.outputs.length).toBe(3);
- expect(group.outputs[0].output.name).toBe("VAE");
- expect(group.outputs[0].output.type).toBe("VAE");
- expect(group.outputs[1].output.name).toBe("IMAGE");
- expect(group.outputs[1].output.type).toBe("IMAGE");
- expect(group.outputs[2].output.name).toBe("LATENT");
- expect(group.outputs[2].output.type).toBe("LATENT");
-
- expect(group.outputs[0].connections.length).toBe(1);
- expect(group.outputs[0].connections[0].targetNode.id).toBe(decode2.id);
- expect(group.outputs[0].connections[0].targetInput.index).toBe(1);
-
- expect(group.outputs[1].connections.length).toBe(1);
- expect(group.outputs[1].connections[0].targetNode.id).toBe(save.id);
- expect(group.outputs[1].connections[0].targetInput.index).toBe(0);
-
- expect(group.outputs[2].connections.length).toBe(1);
- expect(group.outputs[2].connections[0].targetNode.id).toBe(decode2.id);
- expect(group.outputs[2].connections[0].targetInput.index).toBe(0);
-
- expect((await graph.toPrompt()).output).toEqual({
- ...getOutput({ 1: ckpt.id, 2: pos.id, 3: neg.id, 4: empty.id, 5: sampler.id, 6: decode1.id, 7: save.id }),
- [vae.id]: { inputs: { vae_name: "vae1.safetensors" }, class_type: vae.node.type },
- [encode.id]: { inputs: { pixels: ["6", 0], vae: [vae.id + "", 0] }, class_type: encode.node.type },
- [decode2.id]: { inputs: { samples: [encode.id + "", 0], vae: [vae.id + "", 0] }, class_type: decode2.node.type },
- [preview.id]: { inputs: { images: [decode2.id + "", 0] }, class_type: preview.node.type },
- });
- });
- test("works with IMAGEUPLOAD widget", async () => {
- const { ez, graph, app } = await start();
- const img = ez.LoadImage();
- const preview1 = ez.PreviewImage(img.outputs[0]);
-
- const group = await convertToGroup(app, graph, "test", [img, preview1]);
- const widget = group.widgets["upload"];
- expect(widget).toBeTruthy();
- expect(widget.widget.type).toBe("button");
- });
- test("internal primitive populates widgets for all linked inputs", async () => {
- const { ez, graph, app } = await start();
- const img = ez.LoadImage();
- const scale1 = ez.ImageScale(img.outputs[0]);
- const scale2 = ez.ImageScale(img.outputs[0]);
- ez.PreviewImage(scale1.outputs[0]);
- ez.PreviewImage(scale2.outputs[0]);
-
- scale1.widgets.width.convertToInput();
- scale2.widgets.height.convertToInput();
-
- const primitive = ez.PrimitiveNode();
- primitive.outputs[0].connectTo(scale1.inputs.width);
- primitive.outputs[0].connectTo(scale2.inputs.height);
-
- const group = await convertToGroup(app, graph, "test", [img, primitive, scale1, scale2]);
- group.widgets.value.value = 100;
- expect((await graph.toPrompt()).output).toEqual({
- 1: {
- inputs: { image: img.widgets.image.value, upload: "image" },
- class_type: "LoadImage",
- },
- 2: {
- inputs: { upscale_method: "nearest-exact", width: 100, height: 512, crop: "disabled", image: ["1", 0] },
- class_type: "ImageScale",
- },
- 3: {
- inputs: { upscale_method: "nearest-exact", width: 512, height: 100, crop: "disabled", image: ["1", 0] },
- class_type: "ImageScale",
- },
- 4: { inputs: { images: ["2", 0] }, class_type: "PreviewImage" },
- 5: { inputs: { images: ["3", 0] }, class_type: "PreviewImage" },
- });
- });
- test("primitive control widgets values are copied on convert", async () => {
- const { ez, graph, app } = await start();
- const sampler = ez.KSampler();
- sampler.widgets.seed.convertToInput();
- sampler.widgets.sampler_name.convertToInput();
-
- let p1 = ez.PrimitiveNode();
- let p2 = ez.PrimitiveNode();
- p1.outputs[0].connectTo(sampler.inputs.seed);
- p2.outputs[0].connectTo(sampler.inputs.sampler_name);
-
- p1.widgets.control_after_generate.value = "increment";
- p2.widgets.control_after_generate.value = "decrement";
- p2.widgets.control_filter_list.value = "/.*/";
-
- p2.node.title = "p2";
-
- const group = await convertToGroup(app, graph, "test", [sampler, p1, p2]);
- expect(group.widgets.control_after_generate.value).toBe("increment");
- expect(group.widgets["p2 control_after_generate"].value).toBe("decrement");
- expect(group.widgets["p2 control_filter_list"].value).toBe("/.*/");
-
- group.widgets.control_after_generate.value = "fixed";
- group.widgets["p2 control_after_generate"].value = "randomize";
- group.widgets["p2 control_filter_list"].value = "/.+/";
-
- group.menu["Convert to nodes"].call();
- p1 = graph.find(p1);
- p2 = graph.find(p2);
-
- expect(p1.widgets.control_after_generate.value).toBe("fixed");
- expect(p2.widgets.control_after_generate.value).toBe("randomize");
- expect(p2.widgets.control_filter_list.value).toBe("/.+/");
- });
- test("internal reroutes work with converted inputs and merge options", async () => {
- const { ez, graph, app } = await start();
- const vae = ez.VAELoader();
- const latent = ez.EmptyLatentImage();
- const decode = ez.VAEDecode(latent.outputs.LATENT, vae.outputs.VAE);
- const scale = ez.ImageScale(decode.outputs.IMAGE);
- ez.PreviewImage(scale.outputs.IMAGE);
-
- const r1 = ez.Reroute();
- const r2 = ez.Reroute();
-
- latent.widgets.width.value = 64;
- latent.widgets.height.value = 128;
-
- latent.widgets.width.convertToInput();
- latent.widgets.height.convertToInput();
- latent.widgets.batch_size.convertToInput();
-
- scale.widgets.width.convertToInput();
- scale.widgets.height.convertToInput();
-
- r1.inputs[0].input.label = "hbw";
- r1.outputs[0].connectTo(latent.inputs.height);
- r1.outputs[0].connectTo(latent.inputs.batch_size);
- r1.outputs[0].connectTo(scale.inputs.width);
-
- r2.inputs[0].input.label = "wh";
- r2.outputs[0].connectTo(latent.inputs.width);
- r2.outputs[0].connectTo(scale.inputs.height);
-
- const group = await convertToGroup(app, graph, "test", [r1, r2, latent, decode, scale]);
-
- expect(group.inputs[0].input.type).toBe("VAE");
- expect(group.inputs[1].input.type).toBe("INT");
- expect(group.inputs[2].input.type).toBe("INT");
-
- const p1 = ez.PrimitiveNode();
- const p2 = ez.PrimitiveNode();
- p1.outputs[0].connectTo(group.inputs[1]);
- p2.outputs[0].connectTo(group.inputs[2]);
-
- expect(p1.widgets.value.widget.options?.min).toBe(16); // width/height min
- expect(p1.widgets.value.widget.options?.max).toBe(4096); // batch max
- expect(p1.widgets.value.widget.options?.step).toBe(80); // width/height step * 10
-
- expect(p2.widgets.value.widget.options?.min).toBe(16); // width/height min
- expect(p2.widgets.value.widget.options?.max).toBe(16384); // width/height max
- expect(p2.widgets.value.widget.options?.step).toBe(80); // width/height step * 10
-
- expect(p1.widgets.value.value).toBe(128);
- expect(p2.widgets.value.value).toBe(64);
-
- p1.widgets.value.value = 16;
- p2.widgets.value.value = 32;
-
- await checkBeforeAndAfterReload(graph, async (r) => {
- const id = (v) => (r ? `${group.id}:` : "") + v;
- expect((await graph.toPrompt()).output).toStrictEqual({
- 1: { inputs: { vae_name: "vae1.safetensors" }, class_type: "VAELoader" },
- [id(2)]: { inputs: { width: 32, height: 16, batch_size: 16 }, class_type: "EmptyLatentImage" },
- [id(3)]: { inputs: { samples: [id(2), 0], vae: ["1", 0] }, class_type: "VAEDecode" },
- [id(4)]: {
- inputs: { upscale_method: "nearest-exact", width: 16, height: 32, crop: "disabled", image: [id(3), 0] },
- class_type: "ImageScale",
- },
- 5: { inputs: { images: [id(4), 0] }, class_type: "PreviewImage" },
- });
- });
- });
- test("converted inputs with linked widgets map values correctly on creation", async () => {
- const { ez, graph, app } = await start();
- const k1 = ez.KSampler();
- const k2 = ez.KSampler();
- k1.widgets.seed.convertToInput();
- k2.widgets.seed.convertToInput();
-
- const rr = ez.Reroute();
- rr.outputs[0].connectTo(k1.inputs.seed);
- rr.outputs[0].connectTo(k2.inputs.seed);
-
- const group = await convertToGroup(app, graph, "test", [k1, k2, rr]);
- expect(group.widgets.steps.value).toBe(20);
- expect(group.widgets.cfg.value).toBe(8);
- expect(group.widgets.scheduler.value).toBe("normal");
- expect(group.widgets["KSampler steps"].value).toBe(20);
- expect(group.widgets["KSampler cfg"].value).toBe(8);
- expect(group.widgets["KSampler scheduler"].value).toBe("normal");
- });
- test("allow multiple of the same node type to be added", async () => {
- const { ez, graph, app } = await start();
- const nodes = [...Array(10)].map(() => ez.ImageScaleBy());
- const group = await convertToGroup(app, graph, "test", nodes);
- expect(group.inputs.length).toBe(10);
- expect(group.outputs.length).toBe(10);
- expect(group.widgets.length).toBe(20);
- expect(group.widgets.map((w) => w.widget.name)).toStrictEqual(
- [...Array(10)]
- .map((_, i) => `${i > 0 ? "ImageScaleBy " : ""}${i > 1 ? i + " " : ""}`)
- .flatMap((p) => [`${p}upscale_method`, `${p}scale_by`])
- );
- });
-});
diff --git a/tests-ui/tests/users.test.js b/tests-ui/tests/users.test.js
deleted file mode 100644
index 5e0730730..000000000
--- a/tests-ui/tests/users.test.js
+++ /dev/null
@@ -1,295 +0,0 @@
-// @ts-check
-///
-const { start } = require("../utils");
-const lg = require("../utils/litegraph");
-
-describe("users", () => {
- beforeEach(() => {
- lg.setup(global);
- });
-
- afterEach(() => {
- lg.teardown(global);
- });
-
- function expectNoUserScreen() {
- // Ensure login isnt visible
- const selection = document.querySelectorAll("#comfy-user-selection")?.[0];
- expect(selection["style"].display).toBe("none");
- const menu = document.querySelectorAll(".comfy-menu")?.[0];
- expect(window.getComputedStyle(menu)?.display).not.toBe("none");
- }
-
- describe("multi-user", () => {
- function mockAddStylesheet() {
- const utils = require("../../web/scripts/utils");
- utils.addStylesheet = jest.fn().mockReturnValue(Promise.resolve());
- }
-
- async function waitForUserScreenShow() {
- mockAddStylesheet();
-
- // Wait for "show" to be called
- const { UserSelectionScreen } = require("../../web/scripts/ui/userSelection");
- let resolve, reject;
- const fn = UserSelectionScreen.prototype.show;
- const p = new Promise((res, rej) => {
- resolve = res;
- reject = rej;
- });
- jest.spyOn(UserSelectionScreen.prototype, "show").mockImplementation(async (...args) => {
- const res = fn(...args);
- await new Promise(process.nextTick); // wait for promises to resolve
- resolve();
- return res;
- });
- // @ts-ignore
- setTimeout(() => reject("timeout waiting for UserSelectionScreen to be shown."), 500);
- await p;
- await new Promise(process.nextTick); // wait for promises to resolve
- }
-
- async function testUserScreen(onShown, users) {
- if (!users) {
- users = {};
- }
- const starting = start({
- resetEnv: true,
- userConfig: { storage: "server", users },
- });
-
- // Ensure no current user
- expect(localStorage["Comfy.userId"]).toBeFalsy();
- expect(localStorage["Comfy.userName"]).toBeFalsy();
-
- await waitForUserScreenShow();
-
- const selection = document.querySelectorAll("#comfy-user-selection")?.[0];
- expect(selection).toBeTruthy();
-
- // Ensure login is visible
- expect(window.getComputedStyle(selection)?.display).not.toBe("none");
- // Ensure menu is hidden
- const menu = document.querySelectorAll(".comfy-menu")?.[0];
- expect(window.getComputedStyle(menu)?.display).toBe("none");
-
- const isCreate = await onShown(selection);
-
- // Submit form
- selection.querySelectorAll("form")[0].submit();
- await new Promise(process.nextTick); // wait for promises to resolve
-
- // Wait for start
- const s = await starting;
-
- // Ensure login is removed
- expect(document.querySelectorAll("#comfy-user-selection")).toHaveLength(0);
- expect(window.getComputedStyle(menu)?.display).not.toBe("none");
-
- // Ensure settings + templates are saved
- const { api } = require("../../web/scripts/api");
- expect(api.createUser).toHaveBeenCalledTimes(+isCreate);
- expect(api.storeSettings).toHaveBeenCalledTimes(+isCreate);
- expect(api.storeUserData).toHaveBeenCalledTimes(+isCreate);
- if (isCreate) {
- expect(api.storeUserData).toHaveBeenCalledWith("comfy.templates.json", null, { stringify: false });
- expect(s.app.isNewUserSession).toBeTruthy();
- } else {
- expect(s.app.isNewUserSession).toBeFalsy();
- }
-
- return { users, selection, ...s };
- }
-
- it("allows user creation if no users", async () => {
- const { users } = await testUserScreen((selection) => {
- // Ensure we have no users flag added
- expect(selection.classList.contains("no-users")).toBeTruthy();
-
- // Enter a username
- const input = selection.getElementsByTagName("input")[0];
- input.focus();
- input.value = "Test User";
-
- return true;
- });
-
- expect(users).toStrictEqual({
- "Test User!": "Test User",
- });
-
- expect(localStorage["Comfy.userId"]).toBe("Test User!");
- expect(localStorage["Comfy.userName"]).toBe("Test User");
- });
- it("allows user creation if no current user but other users", async () => {
- const users = {
- "Test User 2!": "Test User 2",
- };
-
- await testUserScreen((selection) => {
- expect(selection.classList.contains("no-users")).toBeFalsy();
-
- // Enter a username
- const input = selection.getElementsByTagName("input")[0];
- input.focus();
- input.value = "Test User 3";
- return true;
- }, users);
-
- expect(users).toStrictEqual({
- "Test User 2!": "Test User 2",
- "Test User 3!": "Test User 3",
- });
-
- expect(localStorage["Comfy.userId"]).toBe("Test User 3!");
- expect(localStorage["Comfy.userName"]).toBe("Test User 3");
- });
- it("allows user selection if no current user but other users", async () => {
- const users = {
- "A!": "A",
- "B!": "B",
- "C!": "C",
- };
-
- await testUserScreen((selection) => {
- expect(selection.classList.contains("no-users")).toBeFalsy();
-
- // Check user list
- const select = selection.getElementsByTagName("select")[0];
- const options = select.getElementsByTagName("option");
- expect(
- [...options]
- .filter((o) => !o.disabled)
- .reduce((p, n) => {
- p[n.getAttribute("value")] = n.textContent;
- return p;
- }, {})
- ).toStrictEqual(users);
-
- // Select an option
- select.focus();
- select.value = options[2].value;
-
- return false;
- }, users);
-
- expect(users).toStrictEqual(users);
-
- expect(localStorage["Comfy.userId"]).toBe("B!");
- expect(localStorage["Comfy.userName"]).toBe("B");
- });
- it("doesnt show user screen if current user", async () => {
- const starting = start({
- resetEnv: true,
- userConfig: {
- storage: "server",
- users: {
- "User!": "User",
- },
- },
- localStorage: {
- "Comfy.userId": "User!",
- "Comfy.userName": "User",
- },
- });
- await new Promise(process.nextTick); // wait for promises to resolve
-
- expectNoUserScreen();
-
- await starting;
- });
- it("allows user switching", async () => {
- const { app } = await start({
- resetEnv: true,
- userConfig: {
- storage: "server",
- users: {
- "User!": "User",
- },
- },
- localStorage: {
- "Comfy.userId": "User!",
- "Comfy.userName": "User",
- },
- });
-
- // cant actually test switching user easily but can check the setting is present
- expect(app.ui.settings.settingsLookup["Comfy.SwitchUser"]).toBeTruthy();
- });
- });
- describe("single-user", () => {
- it("doesnt show user creation if no default user", async () => {
- const { app } = await start({
- resetEnv: true,
- userConfig: { migrated: false, storage: "server" },
- });
- expectNoUserScreen();
-
- // It should store the settings
- const { api } = require("../../web/scripts/api");
- expect(api.storeSettings).toHaveBeenCalledTimes(1);
- expect(api.storeUserData).toHaveBeenCalledTimes(1);
- expect(api.storeUserData).toHaveBeenCalledWith("comfy.templates.json", null, { stringify: false });
- expect(app.isNewUserSession).toBeTruthy();
- });
- it("doesnt show user creation if default user", async () => {
- const { app } = await start({
- resetEnv: true,
- userConfig: { migrated: true, storage: "server" },
- });
- expectNoUserScreen();
-
- // It should store the settings
- const { api } = require("../../web/scripts/api");
- expect(api.storeSettings).toHaveBeenCalledTimes(0);
- expect(api.storeUserData).toHaveBeenCalledTimes(0);
- expect(app.isNewUserSession).toBeFalsy();
- });
- it("doesnt allow user switching", async () => {
- const { app } = await start({
- resetEnv: true,
- userConfig: { migrated: true, storage: "server" },
- });
- expectNoUserScreen();
-
- expect(app.ui.settings.settingsLookup["Comfy.SwitchUser"]).toBeFalsy();
- });
- });
- describe("browser-user", () => {
- it("doesnt show user creation if no default user", async () => {
- const { app } = await start({
- resetEnv: true,
- userConfig: { migrated: false, storage: "browser" },
- });
- expectNoUserScreen();
-
- // It should store the settings
- const { api } = require("../../web/scripts/api");
- expect(api.storeSettings).toHaveBeenCalledTimes(0);
- expect(api.storeUserData).toHaveBeenCalledTimes(0);
- expect(app.isNewUserSession).toBeFalsy();
- });
- it("doesnt show user creation if default user", async () => {
- const { app } = await start({
- resetEnv: true,
- userConfig: { migrated: true, storage: "server" },
- });
- expectNoUserScreen();
-
- // It should store the settings
- const { api } = require("../../web/scripts/api");
- expect(api.storeSettings).toHaveBeenCalledTimes(0);
- expect(api.storeUserData).toHaveBeenCalledTimes(0);
- expect(app.isNewUserSession).toBeFalsy();
- });
- it("doesnt allow user switching", async () => {
- const { app } = await start({
- resetEnv: true,
- userConfig: { migrated: true, storage: "browser" },
- });
- expectNoUserScreen();
-
- expect(app.ui.settings.settingsLookup["Comfy.SwitchUser"]).toBeFalsy();
- });
- });
-});
diff --git a/tests-ui/tests/widgetInputs.test.js b/tests-ui/tests/widgetInputs.test.js
deleted file mode 100644
index 67e3fa341..000000000
--- a/tests-ui/tests/widgetInputs.test.js
+++ /dev/null
@@ -1,557 +0,0 @@
-// @ts-check
-///
-
-const {
- start,
- makeNodeDef,
- checkBeforeAndAfterReload,
- assertNotNullOrUndefined,
- createDefaultWorkflow,
-} = require("../utils");
-const lg = require("../utils/litegraph");
-
-/**
- * @typedef { import("../utils/ezgraph") } Ez
- * @typedef { ReturnType["ez"] } EzNodeFactory
- */
-
-/**
- * @param { EzNodeFactory } ez
- * @param { InstanceType } graph
- * @param { InstanceType } input
- * @param { string } widgetType
- * @param { number } controlWidgetCount
- * @returns
- */
-async function connectPrimitiveAndReload(ez, graph, input, widgetType, controlWidgetCount = 0) {
- // Connect to primitive and ensure its still connected after
- let primitive = ez.PrimitiveNode();
- primitive.outputs[0].connectTo(input);
-
- await checkBeforeAndAfterReload(graph, async () => {
- primitive = graph.find(primitive);
- let { connections } = primitive.outputs[0];
- expect(connections).toHaveLength(1);
- expect(connections[0].targetNode.id).toBe(input.node.node.id);
-
- // Ensure widget is correct type
- const valueWidget = primitive.widgets.value;
- expect(valueWidget.widget.type).toBe(widgetType);
-
- // Check if control_after_generate should be added
- if (controlWidgetCount) {
- const controlWidget = primitive.widgets.control_after_generate;
- expect(controlWidget.widget.type).toBe("combo");
- if (widgetType === "combo") {
- const filterWidget = primitive.widgets.control_filter_list;
- expect(filterWidget.widget.type).toBe("string");
- }
- }
-
- // Ensure we dont have other widgets
- expect(primitive.node.widgets).toHaveLength(1 + controlWidgetCount);
- });
-
- return primitive;
-}
-
-describe("widget inputs", () => {
- beforeEach(() => {
- lg.setup(global);
- });
-
- afterEach(() => {
- lg.teardown(global);
- });
-
- [
- { name: "int", type: "INT", widget: "number", control: 1 },
- { name: "float", type: "FLOAT", widget: "number", control: 1 },
- { name: "text", type: "STRING" },
- {
- name: "customtext",
- type: "STRING",
- opt: { multiline: true },
- },
- { name: "toggle", type: "BOOLEAN" },
- { name: "combo", type: ["a", "b", "c"], control: 2 },
- ].forEach((c) => {
- test(`widget conversion + primitive works on ${c.name}`, async () => {
- const { ez, graph } = await start({
- mockNodeDefs: makeNodeDef("TestNode", { [c.name]: [c.type, c.opt ?? {}] }),
- });
-
- // Create test node and convert to input
- const n = ez.TestNode();
- const w = n.widgets[c.name];
- w.convertToInput();
- expect(w.isConvertedToInput).toBeTruthy();
- const input = w.getConvertedInput();
- expect(input).toBeTruthy();
-
- // @ts-ignore : input is valid here
- await connectPrimitiveAndReload(ez, graph, input, c.widget ?? c.name, c.control);
- });
- });
-
- test("converted widget works after reload", async () => {
- const { ez, graph } = await start();
- let n = ez.CheckpointLoaderSimple();
-
- const inputCount = n.inputs.length;
-
- // Convert ckpt name to an input
- n.widgets.ckpt_name.convertToInput();
- expect(n.widgets.ckpt_name.isConvertedToInput).toBeTruthy();
- expect(n.inputs.ckpt_name).toBeTruthy();
- expect(n.inputs.length).toEqual(inputCount + 1);
-
- // Convert back to widget and ensure input is removed
- n.widgets.ckpt_name.convertToWidget();
- expect(n.widgets.ckpt_name.isConvertedToInput).toBeFalsy();
- expect(n.inputs.ckpt_name).toBeFalsy();
- expect(n.inputs.length).toEqual(inputCount);
-
- // Convert again and reload the graph to ensure it maintains state
- n.widgets.ckpt_name.convertToInput();
- expect(n.inputs.length).toEqual(inputCount + 1);
-
- const primitive = await connectPrimitiveAndReload(ez, graph, n.inputs.ckpt_name, "combo", 2);
-
- // Disconnect & reconnect
- primitive.outputs[0].connections[0].disconnect();
- let { connections } = primitive.outputs[0];
- expect(connections).toHaveLength(0);
-
- primitive.outputs[0].connectTo(n.inputs.ckpt_name);
- ({ connections } = primitive.outputs[0]);
- expect(connections).toHaveLength(1);
- expect(connections[0].targetNode.id).toBe(n.node.id);
-
- // Convert back to widget and ensure input is removed
- n.widgets.ckpt_name.convertToWidget();
- expect(n.widgets.ckpt_name.isConvertedToInput).toBeFalsy();
- expect(n.inputs.ckpt_name).toBeFalsy();
- expect(n.inputs.length).toEqual(inputCount);
- });
-
- test("converted widget works on clone", async () => {
- const { graph, ez } = await start();
- let n = ez.CheckpointLoaderSimple();
-
- // Convert the widget to an input
- n.widgets.ckpt_name.convertToInput();
- expect(n.widgets.ckpt_name.isConvertedToInput).toBeTruthy();
-
- // Clone the node
- n.menu["Clone"].call();
- expect(graph.nodes).toHaveLength(2);
- const clone = graph.nodes[1];
- expect(clone.id).not.toEqual(n.id);
-
- // Ensure the clone has an input
- expect(clone.widgets.ckpt_name.isConvertedToInput).toBeTruthy();
- expect(clone.inputs.ckpt_name).toBeTruthy();
-
- // Ensure primitive connects to both nodes
- let primitive = ez.PrimitiveNode();
- primitive.outputs[0].connectTo(n.inputs.ckpt_name);
- primitive.outputs[0].connectTo(clone.inputs.ckpt_name);
- expect(primitive.outputs[0].connections).toHaveLength(2);
-
- // Convert back to widget and ensure input is removed
- clone.widgets.ckpt_name.convertToWidget();
- expect(clone.widgets.ckpt_name.isConvertedToInput).toBeFalsy();
- expect(clone.inputs.ckpt_name).toBeFalsy();
- });
-
- test("shows missing node error on custom node with converted input", async () => {
- const { graph } = await start();
-
- const dialogShow = jest.spyOn(graph.app.ui.dialog, "show");
-
- await graph.app.loadGraphData({
- last_node_id: 3,
- last_link_id: 4,
- nodes: [
- {
- id: 1,
- type: "TestNode",
- pos: [41.87329101561909, 389.7381480823742],
- size: { 0: 220, 1: 374 },
- flags: {},
- order: 1,
- mode: 0,
- inputs: [{ name: "test", type: "FLOAT", link: 4, widget: { name: "test" }, slot_index: 0 }],
- outputs: [],
- properties: { "Node name for S&R": "TestNode" },
- widgets_values: [1],
- },
- {
- id: 3,
- type: "PrimitiveNode",
- pos: [-312, 433],
- size: { 0: 210, 1: 82 },
- flags: {},
- order: 0,
- mode: 0,
- outputs: [{ links: [4], widget: { name: "test" } }],
- title: "test",
- properties: {},
- },
- ],
- links: [[4, 3, 0, 1, 6, "FLOAT"]],
- groups: [],
- config: {},
- extra: {},
- version: 0.4,
- });
-
- expect(dialogShow).toBeCalledTimes(1);
- expect(dialogShow.mock.calls[0][0].innerHTML).toContain("the following node types were not found");
- expect(dialogShow.mock.calls[0][0].innerHTML).toContain("TestNode");
- });
-
- test("defaultInput widgets can be converted back to inputs", async () => {
- const { graph, ez } = await start({
- mockNodeDefs: makeNodeDef("TestNode", { example: ["INT", { defaultInput: true }] }),
- });
-
- // Create test node and ensure it starts as an input
- let n = ez.TestNode();
- let w = n.widgets.example;
- expect(w.isConvertedToInput).toBeTruthy();
- let input = w.getConvertedInput();
- expect(input).toBeTruthy();
-
- // Ensure it can be converted to
- w.convertToWidget();
- expect(w.isConvertedToInput).toBeFalsy();
- expect(n.inputs.length).toEqual(0);
- // and from
- w.convertToInput();
- expect(w.isConvertedToInput).toBeTruthy();
- input = w.getConvertedInput();
-
- // Reload and ensure it still only has 1 converted widget
- if (!assertNotNullOrUndefined(input)) return;
-
- await connectPrimitiveAndReload(ez, graph, input, "number", 1);
- n = graph.find(n);
- expect(n.widgets).toHaveLength(1);
- w = n.widgets.example;
- expect(w.isConvertedToInput).toBeTruthy();
-
- // Convert back to widget and ensure it is still a widget after reload
- w.convertToWidget();
- await graph.reload();
- n = graph.find(n);
- expect(n.widgets).toHaveLength(1);
- expect(n.widgets[0].isConvertedToInput).toBeFalsy();
- expect(n.inputs.length).toEqual(0);
- });
-
- test("forceInput widgets can not be converted back to inputs", async () => {
- const { graph, ez } = await start({
- mockNodeDefs: makeNodeDef("TestNode", { example: ["INT", { forceInput: true }] }),
- });
-
- // Create test node and ensure it starts as an input
- let n = ez.TestNode();
- let w = n.widgets.example;
- expect(w.isConvertedToInput).toBeTruthy();
- const input = w.getConvertedInput();
- expect(input).toBeTruthy();
-
- // Convert to widget should error
- expect(() => w.convertToWidget()).toThrow();
-
- // Reload and ensure it still only has 1 converted widget
- if (assertNotNullOrUndefined(input)) {
- await connectPrimitiveAndReload(ez, graph, input, "number", 1);
- n = graph.find(n);
- expect(n.widgets).toHaveLength(1);
- expect(n.widgets.example.isConvertedToInput).toBeTruthy();
- }
- });
-
- test("primitive can connect to matching combos on converted widgets", async () => {
- const { ez } = await start({
- mockNodeDefs: {
- ...makeNodeDef("TestNode1", { example: [["A", "B", "C"], { forceInput: true }] }),
- ...makeNodeDef("TestNode2", { example: [["A", "B", "C"], { forceInput: true }] }),
- },
- });
-
- const n1 = ez.TestNode1();
- const n2 = ez.TestNode2();
- const p = ez.PrimitiveNode();
- p.outputs[0].connectTo(n1.inputs[0]);
- p.outputs[0].connectTo(n2.inputs[0]);
- expect(p.outputs[0].connections).toHaveLength(2);
- const valueWidget = p.widgets.value;
- expect(valueWidget.widget.type).toBe("combo");
- expect(valueWidget.widget.options.values).toEqual(["A", "B", "C"]);
- });
-
- test("primitive can not connect to non matching combos on converted widgets", async () => {
- const { ez } = await start({
- mockNodeDefs: {
- ...makeNodeDef("TestNode1", { example: [["A", "B", "C"], { forceInput: true }] }),
- ...makeNodeDef("TestNode2", { example: [["A", "B"], { forceInput: true }] }),
- },
- });
-
- const n1 = ez.TestNode1();
- const n2 = ez.TestNode2();
- const p = ez.PrimitiveNode();
- p.outputs[0].connectTo(n1.inputs[0]);
- expect(() => p.outputs[0].connectTo(n2.inputs[0])).toThrow();
- expect(p.outputs[0].connections).toHaveLength(1);
- });
-
- test("combo output can not connect to non matching combos list input", async () => {
- const { ez } = await start({
- mockNodeDefs: {
- ...makeNodeDef("TestNode1", {}, [["A", "B"]]),
- ...makeNodeDef("TestNode2", { example: [["A", "B"], { forceInput: true }] }),
- ...makeNodeDef("TestNode3", { example: [["A", "B", "C"], { forceInput: true }] }),
- },
- });
-
- const n1 = ez.TestNode1();
- const n2 = ez.TestNode2();
- const n3 = ez.TestNode3();
-
- n1.outputs[0].connectTo(n2.inputs[0]);
- expect(() => n1.outputs[0].connectTo(n3.inputs[0])).toThrow();
- });
-
- test("combo primitive can filter list when control_after_generate called", async () => {
- const { ez } = await start({
- mockNodeDefs: {
- ...makeNodeDef("TestNode1", { example: [["A", "B", "C", "D", "AA", "BB", "CC", "DD", "AAA", "BBB"], {}] }),
- },
- });
-
- const n1 = ez.TestNode1();
- n1.widgets.example.convertToInput();
- const p = ez.PrimitiveNode();
- p.outputs[0].connectTo(n1.inputs[0]);
-
- const value = p.widgets.value;
- const control = p.widgets.control_after_generate.widget;
- const filter = p.widgets.control_filter_list;
-
- expect(p.widgets.length).toBe(3);
- control.value = "increment";
- expect(value.value).toBe("A");
-
- // Manually trigger after queue when set to increment
- control["afterQueued"]();
- expect(value.value).toBe("B");
-
- // Filter to items containing D
- filter.value = "D";
- control["afterQueued"]();
- expect(value.value).toBe("D");
- control["afterQueued"]();
- expect(value.value).toBe("DD");
-
- // Check decrement
- value.value = "BBB";
- control.value = "decrement";
- filter.value = "B";
- control["afterQueued"]();
- expect(value.value).toBe("BB");
- control["afterQueued"]();
- expect(value.value).toBe("B");
-
- // Check regex works
- value.value = "BBB";
- filter.value = "/[AB]|^C$/";
- control["afterQueued"]();
- expect(value.value).toBe("AAA");
- control["afterQueued"]();
- expect(value.value).toBe("BB");
- control["afterQueued"]();
- expect(value.value).toBe("AA");
- control["afterQueued"]();
- expect(value.value).toBe("C");
- control["afterQueued"]();
- expect(value.value).toBe("B");
- control["afterQueued"]();
- expect(value.value).toBe("A");
-
- // Check random
- control.value = "randomize";
- filter.value = "/D/";
- for (let i = 0; i < 100; i++) {
- control["afterQueued"]();
- expect(value.value === "D" || value.value === "DD").toBeTruthy();
- }
-
- // Ensure it doesnt apply when fixed
- control.value = "fixed";
- value.value = "B";
- filter.value = "C";
- control["afterQueued"]();
- expect(value.value).toBe("B");
- });
-
- describe("reroutes", () => {
- async function checkOutput(graph, values) {
- expect((await graph.toPrompt()).output).toStrictEqual({
- 1: { inputs: { ckpt_name: "model1.safetensors" }, class_type: "CheckpointLoaderSimple" },
- 2: { inputs: { text: "positive", clip: ["1", 1] }, class_type: "CLIPTextEncode" },
- 3: { inputs: { text: "negative", clip: ["1", 1] }, class_type: "CLIPTextEncode" },
- 4: {
- inputs: { width: values.width ?? 512, height: values.height ?? 512, batch_size: values?.batch_size ?? 1 },
- class_type: "EmptyLatentImage",
- },
- 5: {
- inputs: {
- seed: 0,
- steps: 20,
- cfg: 8,
- sampler_name: "euler",
- scheduler: values?.scheduler ?? "normal",
- denoise: 1,
- model: ["1", 0],
- positive: ["2", 0],
- negative: ["3", 0],
- latent_image: ["4", 0],
- },
- class_type: "KSampler",
- },
- 6: { inputs: { samples: ["5", 0], vae: ["1", 2] }, class_type: "VAEDecode" },
- 7: {
- inputs: { filename_prefix: values.filename_prefix ?? "ComfyUI", images: ["6", 0] },
- class_type: "SaveImage",
- },
- });
- }
-
- async function waitForWidget(node) {
- // widgets are created slightly after the graph is ready
- // hard to find an exact hook to get these so just wait for them to be ready
- for (let i = 0; i < 10; i++) {
- await new Promise((r) => setTimeout(r, 10));
- if (node.widgets?.value) {
- return;
- }
- }
- }
-
- it("can connect primitive via a reroute path to a widget input", async () => {
- const { ez, graph } = await start();
- const nodes = createDefaultWorkflow(ez, graph);
-
- nodes.empty.widgets.width.convertToInput();
- nodes.sampler.widgets.scheduler.convertToInput();
- nodes.save.widgets.filename_prefix.convertToInput();
-
- let widthReroute = ez.Reroute();
- let schedulerReroute = ez.Reroute();
- let fileReroute = ez.Reroute();
-
- let widthNext = widthReroute;
- let schedulerNext = schedulerReroute;
- let fileNext = fileReroute;
-
- for (let i = 0; i < 5; i++) {
- let next = ez.Reroute();
- widthNext.outputs[0].connectTo(next.inputs[0]);
- widthNext = next;
-
- next = ez.Reroute();
- schedulerNext.outputs[0].connectTo(next.inputs[0]);
- schedulerNext = next;
-
- next = ez.Reroute();
- fileNext.outputs[0].connectTo(next.inputs[0]);
- fileNext = next;
- }
-
- widthNext.outputs[0].connectTo(nodes.empty.inputs.width);
- schedulerNext.outputs[0].connectTo(nodes.sampler.inputs.scheduler);
- fileNext.outputs[0].connectTo(nodes.save.inputs.filename_prefix);
-
- let widthPrimitive = ez.PrimitiveNode();
- let schedulerPrimitive = ez.PrimitiveNode();
- let filePrimitive = ez.PrimitiveNode();
-
- widthPrimitive.outputs[0].connectTo(widthReroute.inputs[0]);
- schedulerPrimitive.outputs[0].connectTo(schedulerReroute.inputs[0]);
- filePrimitive.outputs[0].connectTo(fileReroute.inputs[0]);
- expect(widthPrimitive.widgets.value.value).toBe(512);
- widthPrimitive.widgets.value.value = 1024;
- expect(schedulerPrimitive.widgets.value.value).toBe("normal");
- schedulerPrimitive.widgets.value.value = "simple";
- expect(filePrimitive.widgets.value.value).toBe("ComfyUI");
- filePrimitive.widgets.value.value = "ComfyTest";
-
- await checkBeforeAndAfterReload(graph, async () => {
- widthPrimitive = graph.find(widthPrimitive);
- schedulerPrimitive = graph.find(schedulerPrimitive);
- filePrimitive = graph.find(filePrimitive);
- await waitForWidget(filePrimitive);
- expect(widthPrimitive.widgets.length).toBe(2);
- expect(schedulerPrimitive.widgets.length).toBe(3);
- expect(filePrimitive.widgets.length).toBe(1);
-
- await checkOutput(graph, {
- width: 1024,
- scheduler: "simple",
- filename_prefix: "ComfyTest",
- });
- });
- });
- it("can connect primitive via a reroute path to multiple widget inputs", async () => {
- const { ez, graph } = await start();
- const nodes = createDefaultWorkflow(ez, graph);
-
- nodes.empty.widgets.width.convertToInput();
- nodes.empty.widgets.height.convertToInput();
- nodes.empty.widgets.batch_size.convertToInput();
-
- let reroute = ez.Reroute();
- let prevReroute = reroute;
- for (let i = 0; i < 5; i++) {
- const next = ez.Reroute();
- prevReroute.outputs[0].connectTo(next.inputs[0]);
- prevReroute = next;
- }
-
- const r1 = ez.Reroute(prevReroute.outputs[0]);
- const r2 = ez.Reroute(prevReroute.outputs[0]);
- const r3 = ez.Reroute(r2.outputs[0]);
- const r4 = ez.Reroute(r2.outputs[0]);
-
- r1.outputs[0].connectTo(nodes.empty.inputs.width);
- r3.outputs[0].connectTo(nodes.empty.inputs.height);
- r4.outputs[0].connectTo(nodes.empty.inputs.batch_size);
-
- let primitive = ez.PrimitiveNode();
- primitive.outputs[0].connectTo(reroute.inputs[0]);
- expect(primitive.widgets.value.value).toBe(1);
- primitive.widgets.value.value = 64;
-
- await checkBeforeAndAfterReload(graph, async (r) => {
- primitive = graph.find(primitive);
- await waitForWidget(primitive);
-
- // Ensure widget configs are merged
- expect(primitive.widgets.value.widget.options?.min).toBe(16); // width/height min
- expect(primitive.widgets.value.widget.options?.max).toBe(4096); // batch max
- expect(primitive.widgets.value.widget.options?.step).toBe(80); // width/height step * 10
-
- await checkOutput(graph, {
- width: 64,
- height: 64,
- batch_size: 64,
- });
- });
- });
- });
-});
diff --git a/tests-ui/utils/ezgraph.js b/tests-ui/utils/ezgraph.js
deleted file mode 100644
index 97be7aa72..000000000
--- a/tests-ui/utils/ezgraph.js
+++ /dev/null
@@ -1,452 +0,0 @@
-// @ts-check
-///
-
-/**
- * @typedef { import("../../web/scripts/app")["app"] } app
- * @typedef { import("../../web/types/litegraph") } LG
- * @typedef { import("../../web/types/litegraph").IWidget } IWidget
- * @typedef { import("../../web/types/litegraph").ContextMenuItem } ContextMenuItem
- * @typedef { import("../../web/types/litegraph").INodeInputSlot } INodeInputSlot
- * @typedef { import("../../web/types/litegraph").INodeOutputSlot } INodeOutputSlot
- * @typedef { InstanceType & { widgets?: Array } } LGNode
- * @typedef { (...args: EzOutput[] | [...EzOutput[], Record]) => EzNode } EzNodeFactory
- */
-
-export class EzConnection {
- /** @type { app } */
- app;
- /** @type { InstanceType } */
- link;
-
- get originNode() {
- return new EzNode(this.app, this.app.graph.getNodeById(this.link.origin_id));
- }
-
- get originOutput() {
- return this.originNode.outputs[this.link.origin_slot];
- }
-
- get targetNode() {
- return new EzNode(this.app, this.app.graph.getNodeById(this.link.target_id));
- }
-
- get targetInput() {
- return this.targetNode.inputs[this.link.target_slot];
- }
-
- /**
- * @param { app } app
- * @param { InstanceType } link
- */
- constructor(app, link) {
- this.app = app;
- this.link = link;
- }
-
- disconnect() {
- this.targetInput.disconnect();
- }
-}
-
-export class EzSlot {
- /** @type { EzNode } */
- node;
- /** @type { number } */
- index;
-
- /**
- * @param { EzNode } node
- * @param { number } index
- */
- constructor(node, index) {
- this.node = node;
- this.index = index;
- }
-}
-
-export class EzInput extends EzSlot {
- /** @type { INodeInputSlot } */
- input;
-
- /**
- * @param { EzNode } node
- * @param { number } index
- * @param { INodeInputSlot } input
- */
- constructor(node, index, input) {
- super(node, index);
- this.input = input;
- }
-
- get connection() {
- const link = this.node.node.inputs?.[this.index]?.link;
- if (link == null) {
- return null;
- }
- return new EzConnection(this.node.app, this.node.app.graph.links[link]);
- }
-
- disconnect() {
- this.node.node.disconnectInput(this.index);
- }
-}
-
-export class EzOutput extends EzSlot {
- /** @type { INodeOutputSlot } */
- output;
-
- /**
- * @param { EzNode } node
- * @param { number } index
- * @param { INodeOutputSlot } output
- */
- constructor(node, index, output) {
- super(node, index);
- this.output = output;
- }
-
- get connections() {
- return (this.node.node.outputs?.[this.index]?.links ?? []).map(
- (l) => new EzConnection(this.node.app, this.node.app.graph.links[l])
- );
- }
-
- /**
- * @param { EzInput } input
- */
- connectTo(input) {
- if (!input) throw new Error("Invalid input");
-
- /**
- * @type { LG["LLink"] | null }
- */
- const link = this.node.node.connect(this.index, input.node.node, input.index);
- if (!link) {
- const inp = input.input;
- const inName = inp.name || inp.label || inp.type;
- throw new Error(
- `Connecting from ${input.node.node.type}#${input.node.id}[${inName}#${input.index}] -> ${this.node.node.type}#${this.node.id}[${
- this.output.name ?? this.output.type
- }#${this.index}] failed.`
- );
- }
- return link;
- }
-}
-
-export class EzNodeMenuItem {
- /** @type { EzNode } */
- node;
- /** @type { number } */
- index;
- /** @type { ContextMenuItem } */
- item;
-
- /**
- * @param { EzNode } node
- * @param { number } index
- * @param { ContextMenuItem } item
- */
- constructor(node, index, item) {
- this.node = node;
- this.index = index;
- this.item = item;
- }
-
- call(selectNode = true) {
- if (!this.item?.callback) throw new Error(`Menu Item ${this.item?.content ?? "[null]"} has no callback.`);
- if (selectNode) {
- this.node.select();
- }
- return this.item.callback.call(this.node.node, undefined, undefined, undefined, undefined, this.node.node);
- }
-}
-
-export class EzWidget {
- /** @type { EzNode } */
- node;
- /** @type { number } */
- index;
- /** @type { IWidget } */
- widget;
-
- /**
- * @param { EzNode } node
- * @param { number } index
- * @param { IWidget } widget
- */
- constructor(node, index, widget) {
- this.node = node;
- this.index = index;
- this.widget = widget;
- }
-
- get value() {
- return this.widget.value;
- }
-
- set value(v) {
- this.widget.value = v;
- this.widget.callback?.call?.(this.widget, v)
- }
-
- get isConvertedToInput() {
- // @ts-ignore : this type is valid for converted widgets
- return this.widget.type === "converted-widget";
- }
-
- getConvertedInput() {
- if (!this.isConvertedToInput) throw new Error(`Widget ${this.widget.name} is not converted to input.`);
-
- return this.node.inputs.find((inp) => inp.input["widget"]?.name === this.widget.name);
- }
-
- convertToWidget() {
- if (!this.isConvertedToInput)
- throw new Error(`Widget ${this.widget.name} cannot be converted as it is already a widget.`);
- var menu = this.node.menu["Convert Input to Widget"].item.submenu.options;
- var index = menu.findIndex(a => a.content == `Convert ${this.widget.name} to widget`);
- menu[index].callback.call();
- }
-
- convertToInput() {
- if (this.isConvertedToInput)
- throw new Error(`Widget ${this.widget.name} cannot be converted as it is already an input.`);
- var menu = this.node.menu["Convert Widget to Input"].item.submenu.options;
- var index = menu.findIndex(a => a.content == `Convert ${this.widget.name} to input`);
- menu[index].callback.call();
- }
-}
-
-export class EzNode {
- /** @type { app } */
- app;
- /** @type { LGNode } */
- node;
-
- /**
- * @param { app } app
- * @param { LGNode } node
- */
- constructor(app, node) {
- this.app = app;
- this.node = node;
- }
-
- get id() {
- return this.node.id;
- }
-
- get inputs() {
- return this.#makeLookupArray("inputs", "name", EzInput);
- }
-
- get outputs() {
- return this.#makeLookupArray("outputs", "name", EzOutput);
- }
-
- get widgets() {
- return this.#makeLookupArray("widgets", "name", EzWidget);
- }
-
- get menu() {
- return this.#makeLookupArray(() => this.app.canvas.getNodeMenuOptions(this.node), "content", EzNodeMenuItem);
- }
-
- get isRemoved() {
- return !this.app.graph.getNodeById(this.id);
- }
-
- select(addToSelection = false) {
- this.app.canvas.selectNode(this.node, addToSelection);
- }
-
- // /**
- // * @template { "inputs" | "outputs" } T
- // * @param { T } type
- // * @returns { Record & (type extends "inputs" ? EzInput [] : EzOutput[]) }
- // */
- // #getSlotItems(type) {
- // // @ts-ignore : these items are correct
- // return (this.node[type] ?? []).reduce((p, s, i) => {
- // if (s.name in p) {
- // throw new Error(`Unable to store input ${s.name} on array as name conflicts.`);
- // }
- // // @ts-ignore
- // p.push((p[s.name] = new (type === "inputs" ? EzInput : EzOutput)(this, i, s)));
- // return p;
- // }, Object.assign([], { $: this }));
- // }
-
- /**
- * @template { { new(node: EzNode, index: number, obj: any): any } } T
- * @param { "inputs" | "outputs" | "widgets" | (() => Array) } nodeProperty
- * @param { string } nameProperty
- * @param { T } ctor
- * @returns { Record> & Array> }
- */
- #makeLookupArray(nodeProperty, nameProperty, ctor) {
- const items = typeof nodeProperty === "function" ? nodeProperty() : this.node[nodeProperty];
- // @ts-ignore
- return (items ?? []).reduce((p, s, i) => {
- if (!s) return p;
-
- const name = s[nameProperty];
- const item = new ctor(this, i, s);
- // @ts-ignore
- p.push(item);
- if (name) {
- // @ts-ignore
- if (name in p) {
- throw new Error(`Unable to store ${nodeProperty} ${name} on array as name conflicts.`);
- }
- }
- // @ts-ignore
- p[name] = item;
- return p;
- }, Object.assign([], { $: this }));
- }
-}
-
-export class EzGraph {
- /** @type { app } */
- app;
-
- /**
- * @param { app } app
- */
- constructor(app) {
- this.app = app;
- }
-
- get nodes() {
- return this.app.graph._nodes.map((n) => new EzNode(this.app, n));
- }
-
- clear() {
- this.app.graph.clear();
- }
-
- arrange() {
- this.app.graph.arrange();
- }
-
- stringify() {
- return JSON.stringify(this.app.graph.serialize(), undefined);
- }
-
- /**
- * @param { number | LGNode | EzNode } obj
- * @returns { EzNode }
- */
- find(obj) {
- let match;
- let id;
- if (typeof obj === "number") {
- id = obj;
- } else {
- id = obj.id;
- }
-
- match = this.app.graph.getNodeById(id);
-
- if (!match) {
- throw new Error(`Unable to find node with ID ${id}.`);
- }
-
- return new EzNode(this.app, match);
- }
-
- /**
- * @returns { Promise }
- */
- reload() {
- const graph = JSON.parse(JSON.stringify(this.app.graph.serialize()));
- return new Promise((r) => {
- this.app.graph.clear();
- setTimeout(async () => {
- await this.app.loadGraphData(graph);
- r();
- }, 10);
- });
- }
-
- /**
- * @returns { Promise<{
- * workflow: {},
- * output: Record
- * }>}> }
- */
- toPrompt() {
- // @ts-ignore
- return this.app.graphToPrompt();
- }
-}
-
-export const Ez = {
- /**
- * Quickly build and interact with a ComfyUI graph
- * @example
- * const { ez, graph } = Ez.graph(app);
- * graph.clear();
- * const [model, clip, vae] = ez.CheckpointLoaderSimple().outputs;
- * const [pos] = ez.CLIPTextEncode(clip, { text: "positive" }).outputs;
- * const [neg] = ez.CLIPTextEncode(clip, { text: "negative" }).outputs;
- * const [latent] = ez.KSampler(model, pos, neg, ...ez.EmptyLatentImage().outputs).outputs;
- * const [image] = ez.VAEDecode(latent, vae).outputs;
- * const saveNode = ez.SaveImage(image);
- * console.log(saveNode);
- * graph.arrange();
- * @param { app } app
- * @param { LG["LiteGraph"] } LiteGraph
- * @param { LG["LGraphCanvas"] } LGraphCanvas
- * @param { boolean } clearGraph
- * @returns { { graph: EzGraph, ez: Record } }
- */
- graph(app, LiteGraph = window["LiteGraph"], LGraphCanvas = window["LGraphCanvas"], clearGraph = true) {
- // Always set the active canvas so things work
- LGraphCanvas.active_canvas = app.canvas;
-
- if (clearGraph) {
- app.graph.clear();
- }
-
- // @ts-ignore : this proxy handles utility methods & node creation
- const factory = new Proxy(
- {},
- {
- get(_, p) {
- if (typeof p !== "string") throw new Error("Invalid node");
- const node = LiteGraph.createNode(p);
- if (!node) throw new Error(`Unknown node "${p}"`);
- app.graph.add(node);
-
- /**
- * @param {Parameters} args
- */
- return function (...args) {
- const ezNode = new EzNode(app, node);
- const inputs = ezNode.inputs;
-
- let slot = 0;
- for (const arg of args) {
- if (arg instanceof EzOutput) {
- arg.connectTo(inputs[slot++]);
- } else {
- for (const k in arg) {
- ezNode.widgets[k].value = arg[k];
- }
- }
- }
-
- return ezNode;
- };
- },
- }
- );
-
- return { graph: new EzGraph(app), ez: factory };
- },
-};
diff --git a/tests-ui/utils/index.js b/tests-ui/utils/index.js
deleted file mode 100644
index 74b6cf93d..000000000
--- a/tests-ui/utils/index.js
+++ /dev/null
@@ -1,129 +0,0 @@
-const { mockApi } = require("./setup");
-const { Ez } = require("./ezgraph");
-const lg = require("./litegraph");
-const fs = require("fs");
-const path = require("path");
-
-const html = fs.readFileSync(path.resolve(__dirname, "../../web/index.html"))
-
-/**
- *
- * @param { Parameters[0] & {
- * resetEnv?: boolean,
- * preSetup?(app): Promise,
- * localStorage?: Record
- * } } config
- * @returns
- */
-export async function start(config = {}) {
- if(config.resetEnv) {
- jest.resetModules();
- jest.resetAllMocks();
- lg.setup(global);
- localStorage.clear();
- sessionStorage.clear();
- }
-
- Object.assign(localStorage, config.localStorage ?? {});
- document.body.innerHTML = html;
-
- mockApi(config);
- const { app } = require("../../web/scripts/app");
- config.preSetup?.(app);
- await app.setup();
-
- return { ...Ez.graph(app, global["LiteGraph"], global["LGraphCanvas"]), app };
-}
-
-/**
- * @param { ReturnType["graph"] } graph
- * @param { (hasReloaded: boolean) => (Promise | void) } cb
- */
-export async function checkBeforeAndAfterReload(graph, cb) {
- await cb(false);
- await graph.reload();
- await cb(true);
-}
-
-/**
- * @param { string } name
- * @param { Record } input
- * @param { (string | string[])[] | Record } output
- * @returns { Record }
- */
-export function makeNodeDef(name, input, output = {}) {
- const nodeDef = {
- name,
- category: "test",
- output: [],
- output_name: [],
- output_is_list: [],
- input: {
- required: {},
- },
- };
- for (const k in input) {
- nodeDef.input.required[k] = typeof input[k] === "string" ? [input[k], {}] : [...input[k]];
- }
- if (output instanceof Array) {
- output = output.reduce((p, c) => {
- p[c] = c;
- return p;
- }, {});
- }
- for (const k in output) {
- nodeDef.output.push(output[k]);
- nodeDef.output_name.push(k);
- nodeDef.output_is_list.push(false);
- }
-
- return { [name]: nodeDef };
-}
-
-/**
-/**
- * @template { any } T
- * @param { T } x
- * @returns { x is Exclude }
- */
-export function assertNotNullOrUndefined(x) {
- expect(x).not.toEqual(null);
- expect(x).not.toEqual(undefined);
- return true;
-}
-
-/**
- *
- * @param { ReturnType["ez"] } ez
- * @param { ReturnType["graph"] } graph
- */
-export function createDefaultWorkflow(ez, graph) {
- graph.clear();
- const ckpt = ez.CheckpointLoaderSimple();
-
- const pos = ez.CLIPTextEncode(ckpt.outputs.CLIP, { text: "positive" });
- const neg = ez.CLIPTextEncode(ckpt.outputs.CLIP, { text: "negative" });
-
- const empty = ez.EmptyLatentImage();
- const sampler = ez.KSampler(
- ckpt.outputs.MODEL,
- pos.outputs.CONDITIONING,
- neg.outputs.CONDITIONING,
- empty.outputs.LATENT
- );
-
- const decode = ez.VAEDecode(sampler.outputs.LATENT, ckpt.outputs.VAE);
- const save = ez.SaveImage(decode.outputs.IMAGE);
- graph.arrange();
-
- return { ckpt, pos, neg, empty, sampler, decode, save };
-}
-
-export async function getNodeDefs() {
- const { api } = require("../../web/scripts/api");
- return api.getNodeDefs();
-}
-
-export async function getNodeDef(nodeId) {
- return (await getNodeDefs())[nodeId];
-}
\ No newline at end of file
diff --git a/tests-ui/utils/litegraph.js b/tests-ui/utils/litegraph.js
deleted file mode 100644
index 777f8c3ba..000000000
--- a/tests-ui/utils/litegraph.js
+++ /dev/null
@@ -1,36 +0,0 @@
-const fs = require("fs");
-const path = require("path");
-const { nop } = require("../utils/nopProxy");
-
-function forEachKey(cb) {
- for (const k of [
- "LiteGraph",
- "LGraph",
- "LLink",
- "LGraphNode",
- "LGraphGroup",
- "DragAndScale",
- "LGraphCanvas",
- "ContextMenu",
- ]) {
- cb(k);
- }
-}
-
-export function setup(ctx) {
- const lg = fs.readFileSync(path.resolve("../web/lib/litegraph.core.js"), "utf-8");
- const globalTemp = {};
- (function (console) {
- eval(lg);
- }).call(globalTemp, nop);
-
- forEachKey((k) => (ctx[k] = globalTemp[k]));
- require(path.resolve("../web/lib/litegraph.extensions.js"));
-}
-
-export function teardown(ctx) {
- forEachKey((k) => delete ctx[k]);
-
- // Clear document after each run
- document.getElementsByTagName("html")[0].innerHTML = "";
-}
diff --git a/tests-ui/utils/nopProxy.js b/tests-ui/utils/nopProxy.js
deleted file mode 100644
index 2502d9d03..000000000
--- a/tests-ui/utils/nopProxy.js
+++ /dev/null
@@ -1,6 +0,0 @@
-export const nop = new Proxy(function () {}, {
- get: () => nop,
- set: () => true,
- apply: () => nop,
- construct: () => nop,
-});
diff --git a/tests-ui/utils/setup.js b/tests-ui/utils/setup.js
deleted file mode 100644
index 3a6d69b72..000000000
--- a/tests-ui/utils/setup.js
+++ /dev/null
@@ -1,82 +0,0 @@
-require("../../web/scripts/api");
-
-const fs = require("fs");
-const path = require("path");
-function* walkSync(dir) {
- const files = fs.readdirSync(dir, { withFileTypes: true });
- for (const file of files) {
- if (file.isDirectory()) {
- yield* walkSync(path.join(dir, file.name));
- } else {
- yield path.join(dir, file.name);
- }
- }
-}
-
-/**
- * @typedef { import("../../web/types/comfy").ComfyObjectInfo } ComfyObjectInfo
- */
-
-/**
- * @param {{
- * mockExtensions?: string[],
- * mockNodeDefs?: Record,
-* settings?: Record
-* userConfig?: {storage: "server" | "browser", users?: Record, migrated?: boolean },
-* userData?: Record
- * }} config
- */
-export function mockApi(config = {}) {
- let { mockExtensions, mockNodeDefs, userConfig, settings, userData } = {
- userConfig,
- settings: {},
- userData: {},
- ...config,
- };
- if (!mockExtensions) {
- mockExtensions = Array.from(walkSync(path.resolve("../web/extensions/core")))
- .filter((x) => x.endsWith(".js"))
- .map((x) => path.relative(path.resolve("../web"), x));
- }
- if (!mockNodeDefs) {
- mockNodeDefs = JSON.parse(fs.readFileSync(path.resolve("./data/object_info.json")));
- }
-
- const events = new EventTarget();
- const mockApi = {
- addEventListener: events.addEventListener.bind(events),
- removeEventListener: events.removeEventListener.bind(events),
- dispatchEvent: events.dispatchEvent.bind(events),
- getSystemStats: jest.fn(),
- getExtensions: jest.fn(() => mockExtensions),
- getNodeDefs: jest.fn(() => mockNodeDefs),
- init: jest.fn(),
- apiURL: jest.fn((x) => "../../web/" + x),
- createUser: jest.fn((username) => {
- if(username in userConfig.users) {
- return { status: 400, json: () => "Duplicate" }
- }
- userConfig.users[username + "!"] = username;
- return { status: 200, json: () => username + "!" }
- }),
- getUserConfig: jest.fn(() => userConfig ?? { storage: "browser", migrated: false }),
- getSettings: jest.fn(() => settings),
- storeSettings: jest.fn((v) => Object.assign(settings, v)),
- getUserData: jest.fn((f) => {
- if (f in userData) {
- return { status: 200, json: () => userData[f] };
- } else {
- return { status: 404 };
- }
- }),
- storeUserData: jest.fn((file, data) => {
- userData[file] = data;
- }),
- listUserData: jest.fn(() => [])
- };
- jest.mock("../../web/scripts/api", () => ({
- get api() {
- return mockApi;
- },
- }));
-}
diff --git a/tests-unit/README.md b/tests-unit/README.md
index 94abd9853..81692b8f1 100644
--- a/tests-unit/README.md
+++ b/tests-unit/README.md
@@ -2,7 +2,7 @@
## Install test dependencies
-`pip install -r tests-units/requirements.txt`
+`pip install -r tests-unit/requirements.txt`
## Run tests
-`pytest tests-units/`
+`pytest tests-unit/`
diff --git a/tests-unit/app_test/frontend_manager_test.py b/tests-unit/app_test/frontend_manager_test.py
index 637869cfb..a8df52484 100644
--- a/tests-unit/app_test/frontend_manager_test.py
+++ b/tests-unit/app_test/frontend_manager_test.py
@@ -1,6 +1,7 @@
import argparse
import pytest
from requests.exceptions import HTTPError
+from unittest.mock import patch
from app.frontend_management import (
FrontendManager,
@@ -83,6 +84,35 @@ def test_init_frontend_invalid_provider():
with pytest.raises(HTTPError):
FrontendManager.init_frontend_unsafe(version_string)
+@pytest.fixture
+def mock_os_functions():
+ with patch('app.frontend_management.os.makedirs') as mock_makedirs, \
+ patch('app.frontend_management.os.listdir') as mock_listdir, \
+ patch('app.frontend_management.os.rmdir') as mock_rmdir:
+ mock_listdir.return_value = [] # Simulate empty directory
+ yield mock_makedirs, mock_listdir, mock_rmdir
+
+@pytest.fixture
+def mock_download():
+ with patch('app.frontend_management.download_release_asset_zip') as mock:
+ mock.side_effect = Exception("Download failed") # Simulate download failure
+ yield mock
+
+def test_finally_block(mock_os_functions, mock_download, mock_provider):
+ # Arrange
+ mock_makedirs, mock_listdir, mock_rmdir = mock_os_functions
+ version_string = 'test-owner/test-repo@1.0.0'
+
+ # Act & Assert
+ with pytest.raises(Exception):
+ FrontendManager.init_frontend_unsafe(version_string, mock_provider)
+
+ # Assert
+ mock_makedirs.assert_called_once()
+ mock_download.assert_called_once()
+ mock_listdir.assert_called_once()
+ mock_rmdir.assert_called_once()
+
def test_parse_version_string():
version_string = "owner/repo@1.0.0"
diff --git a/tests-unit/comfy_test/folder_path_test.py b/tests-unit/comfy_test/folder_path_test.py
new file mode 100644
index 000000000..0bbec593b
--- /dev/null
+++ b/tests-unit/comfy_test/folder_path_test.py
@@ -0,0 +1,66 @@
+### 🗻 This file is created through the spirit of Mount Fuji at its peak
+# TODO(yoland): clean up this after I get back down
+import pytest
+import os
+import tempfile
+from unittest.mock import patch
+
+import folder_paths
+
+@pytest.fixture
+def temp_dir():
+ with tempfile.TemporaryDirectory() as tmpdirname:
+ yield tmpdirname
+
+
+def test_get_directory_by_type():
+ test_dir = "/test/dir"
+ folder_paths.set_output_directory(test_dir)
+ assert folder_paths.get_directory_by_type("output") == test_dir
+ assert folder_paths.get_directory_by_type("invalid") is None
+
+def test_annotated_filepath():
+ assert folder_paths.annotated_filepath("test.txt") == ("test.txt", None)
+ assert folder_paths.annotated_filepath("test.txt [output]") == ("test.txt", folder_paths.get_output_directory())
+ assert folder_paths.annotated_filepath("test.txt [input]") == ("test.txt", folder_paths.get_input_directory())
+ assert folder_paths.annotated_filepath("test.txt [temp]") == ("test.txt", folder_paths.get_temp_directory())
+
+def test_get_annotated_filepath():
+ default_dir = "/default/dir"
+ assert folder_paths.get_annotated_filepath("test.txt", default_dir) == os.path.join(default_dir, "test.txt")
+ assert folder_paths.get_annotated_filepath("test.txt [output]") == os.path.join(folder_paths.get_output_directory(), "test.txt")
+
+def test_add_model_folder_path():
+ folder_paths.add_model_folder_path("test_folder", "/test/path")
+ assert "/test/path" in folder_paths.get_folder_paths("test_folder")
+
+def test_recursive_search(temp_dir):
+ os.makedirs(os.path.join(temp_dir, "subdir"))
+ open(os.path.join(temp_dir, "file1.txt"), "w").close()
+ open(os.path.join(temp_dir, "subdir", "file2.txt"), "w").close()
+
+ files, dirs = folder_paths.recursive_search(temp_dir)
+ assert set(files) == {"file1.txt", os.path.join("subdir", "file2.txt")}
+ assert len(dirs) == 2 # temp_dir and subdir
+
+def test_filter_files_extensions():
+ files = ["file1.txt", "file2.jpg", "file3.png", "file4.txt"]
+ assert folder_paths.filter_files_extensions(files, [".txt"]) == ["file1.txt", "file4.txt"]
+ assert folder_paths.filter_files_extensions(files, [".jpg", ".png"]) == ["file2.jpg", "file3.png"]
+ assert folder_paths.filter_files_extensions(files, []) == files
+
+@patch("folder_paths.recursive_search")
+@patch("folder_paths.folder_names_and_paths")
+def test_get_filename_list(mock_folder_names_and_paths, mock_recursive_search):
+ mock_folder_names_and_paths.__getitem__.return_value = (["/test/path"], {".txt"})
+ mock_recursive_search.return_value = (["file1.txt", "file2.jpg"], {})
+ assert folder_paths.get_filename_list("test_folder") == ["file1.txt"]
+
+def test_get_save_image_path(temp_dir):
+ with patch("folder_paths.output_directory", temp_dir):
+ full_output_folder, filename, counter, subfolder, filename_prefix = folder_paths.get_save_image_path("test", temp_dir, 100, 100)
+ assert os.path.samefile(full_output_folder, temp_dir)
+ assert filename == "test"
+ assert counter == 1
+ assert subfolder == ""
+ assert filename_prefix == "test"
\ No newline at end of file
diff --git a/tests-unit/folder_paths_test/__init__.py b/tests-unit/folder_paths_test/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/tests-unit/folder_paths_test/filter_by_content_types_test.py b/tests-unit/folder_paths_test/filter_by_content_types_test.py
new file mode 100644
index 000000000..5574789ec
--- /dev/null
+++ b/tests-unit/folder_paths_test/filter_by_content_types_test.py
@@ -0,0 +1,52 @@
+import pytest
+import os
+import tempfile
+from folder_paths import filter_files_content_types
+
+@pytest.fixture(scope="module")
+def file_extensions():
+ return {
+ 'image': ['gif', 'heif', 'ico', 'jpeg', 'jpg', 'png', 'pnm', 'ppm', 'svg', 'tiff', 'webp', 'xbm', 'xpm'],
+ 'audio': ['aif', 'aifc', 'aiff', 'au', 'flac', 'm4a', 'mp2', 'mp3', 'ogg', 'snd', 'wav'],
+ 'video': ['avi', 'm2v', 'm4v', 'mkv', 'mov', 'mp4', 'mpeg', 'mpg', 'ogv', 'qt', 'webm', 'wmv']
+ }
+
+
+@pytest.fixture(scope="module")
+def mock_dir(file_extensions):
+ with tempfile.TemporaryDirectory() as directory:
+ for content_type, extensions in file_extensions.items():
+ for extension in extensions:
+ with open(f"{directory}/sample_{content_type}.{extension}", "w") as f:
+ f.write(f"Sample {content_type} file in {extension} format")
+ yield directory
+
+
+def test_categorizes_all_correctly(mock_dir, file_extensions):
+ files = os.listdir(mock_dir)
+ for content_type, extensions in file_extensions.items():
+ filtered_files = filter_files_content_types(files, [content_type])
+ for extension in extensions:
+ assert f"sample_{content_type}.{extension}" in filtered_files
+
+
+def test_categorizes_all_uniquely(mock_dir, file_extensions):
+ files = os.listdir(mock_dir)
+ for content_type, extensions in file_extensions.items():
+ filtered_files = filter_files_content_types(files, [content_type])
+ assert len(filtered_files) == len(extensions)
+
+
+def test_handles_bad_extensions():
+ files = ["file1.txt", "file2.py", "file3.example", "file4.pdf", "file5.ini", "file6.doc", "file7.md"]
+ assert filter_files_content_types(files, ["image", "audio", "video"]) == []
+
+
+def test_handles_no_extension():
+ files = ["file1", "file2", "file3", "file4", "file5", "file6", "file7"]
+ assert filter_files_content_types(files, ["image", "audio", "video"]) == []
+
+
+def test_handles_no_files():
+ files = []
+ assert filter_files_content_types(files, ["image", "audio", "video"]) == []
\ No newline at end of file
diff --git a/tests-unit/prompt_server_test/download_models_test.py b/tests-unit/prompt_server_test/download_models_test.py
index 66150a468..128dfeb9a 100644
--- a/tests-unit/prompt_server_test/download_models_test.py
+++ b/tests-unit/prompt_server_test/download_models_test.py
@@ -1,10 +1,17 @@
import pytest
+import tempfile
import aiohttp
from aiohttp import ClientResponse
import itertools
-import os
+import os
from unittest.mock import AsyncMock, patch, MagicMock
-from model_filemanager import download_model, validate_model_subdirectory, track_download_progress, create_model_path, check_file_exists, DownloadStatusType, DownloadModelStatus, validate_filename
+from model_filemanager import download_model, track_download_progress, create_model_path, check_file_exists, DownloadStatusType, DownloadModelStatus, validate_filename
+import folder_paths
+
+@pytest.fixture
+def temp_dir():
+ with tempfile.TemporaryDirectory() as tmpdirname:
+ yield tmpdirname
class AsyncIteratorMock:
"""
@@ -42,7 +49,7 @@ class ContentMock:
return AsyncIteratorMock(self.chunks)
@pytest.mark.asyncio
-async def test_download_model_success():
+async def test_download_model_success(temp_dir):
mock_response = AsyncMock(spec=aiohttp.ClientResponse)
mock_response.status = 200
mock_response.headers = {'Content-Length': '1000'}
@@ -53,15 +60,13 @@ async def test_download_model_success():
mock_make_request = AsyncMock(return_value=mock_response)
mock_progress_callback = AsyncMock()
- # Mock file operations
- mock_open = MagicMock()
- mock_file = MagicMock()
- mock_open.return_value.__enter__.return_value = mock_file
time_values = itertools.count(0, 0.1)
- with patch('model_filemanager.create_model_path', return_value=('models/checkpoints/model.sft', 'checkpoints/model.sft')), \
+ fake_paths = {'checkpoints': ([temp_dir], folder_paths.supported_pt_extensions)}
+
+ with patch('model_filemanager.create_model_path', return_value=('models/checkpoints/model.sft', 'model.sft')), \
patch('model_filemanager.check_file_exists', return_value=None), \
- patch('builtins.open', mock_open), \
+ patch('folder_paths.folder_names_and_paths', fake_paths), \
patch('time.time', side_effect=time_values): # Simulate time passing
result = await download_model(
@@ -69,6 +74,7 @@ async def test_download_model_success():
'model.sft',
'http://example.com/model.sft',
'checkpoints',
+ temp_dir,
mock_progress_callback
)
@@ -83,44 +89,48 @@ async def test_download_model_success():
# Check initial call
mock_progress_callback.assert_any_call(
- 'checkpoints/model.sft',
+ 'model.sft',
DownloadModelStatus(DownloadStatusType.PENDING, 0, "Starting download of model.sft", False)
)
# Check final call
mock_progress_callback.assert_any_call(
- 'checkpoints/model.sft',
+ 'model.sft',
DownloadModelStatus(DownloadStatusType.COMPLETED, 100, "Successfully downloaded model.sft", False)
)
- # Verify file writing
- mock_file.write.assert_any_call(b'a' * 500)
- mock_file.write.assert_any_call(b'b' * 300)
- mock_file.write.assert_any_call(b'c' * 200)
+ mock_file_path = os.path.join(temp_dir, 'model.sft')
+ assert os.path.exists(mock_file_path)
+ with open(mock_file_path, 'rb') as mock_file:
+ assert mock_file.read() == b''.join(chunks)
+ os.remove(mock_file_path)
# Verify request was made
mock_make_request.assert_called_once_with('http://example.com/model.sft')
@pytest.mark.asyncio
-async def test_download_model_url_request_failure():
+async def test_download_model_url_request_failure(temp_dir):
# Mock dependencies
mock_response = AsyncMock(spec=ClientResponse)
mock_response.status = 404 # Simulate a "Not Found" error
mock_get = AsyncMock(return_value=mock_response)
mock_progress_callback = AsyncMock()
+
+ fake_paths = {'checkpoints': ([temp_dir], folder_paths.supported_pt_extensions)}
# Mock the create_model_path function
- with patch('model_filemanager.create_model_path', return_value=('/mock/path/model.safetensors', 'mock/path/model.safetensors')):
- # Mock the check_file_exists function to return None (file doesn't exist)
- with patch('model_filemanager.check_file_exists', return_value=None):
- # Call the function
- result = await download_model(
- mock_get,
- 'model.safetensors',
- 'http://example.com/model.safetensors',
- 'mock_directory',
- mock_progress_callback
- )
+ with patch('model_filemanager.create_model_path', return_value='/mock/path/model.safetensors'), \
+ patch('model_filemanager.check_file_exists', return_value=None), \
+ patch('folder_paths.folder_names_and_paths', fake_paths):
+ # Call the function
+ result = await download_model(
+ mock_get,
+ 'model.safetensors',
+ 'http://example.com/model.safetensors',
+ 'checkpoints',
+ temp_dir,
+ mock_progress_callback
+ )
# Assert the expected behavior
assert isinstance(result, DownloadModelStatus)
@@ -130,7 +140,7 @@ async def test_download_model_url_request_failure():
# Check that progress_callback was called with the correct arguments
mock_progress_callback.assert_any_call(
- 'mock_directory/model.safetensors',
+ 'model.safetensors',
DownloadModelStatus(
status=DownloadStatusType.PENDING,
progress_percentage=0,
@@ -139,7 +149,7 @@ async def test_download_model_url_request_failure():
)
)
mock_progress_callback.assert_called_with(
- 'mock_directory/model.safetensors',
+ 'model.safetensors',
DownloadModelStatus(
status=DownloadStatusType.ERROR,
progress_percentage=0,
@@ -153,98 +163,125 @@ async def test_download_model_url_request_failure():
@pytest.mark.asyncio
async def test_download_model_invalid_model_subdirectory():
-
mock_make_request = AsyncMock()
mock_progress_callback = AsyncMock()
-
result = await download_model(
mock_make_request,
'model.sft',
'http://example.com/model.sft',
'../bad_path',
+ '../bad_path',
mock_progress_callback
)
# Assert the result
assert isinstance(result, DownloadModelStatus)
- assert result.message == 'Invalid model subdirectory'
+ assert result.message.startswith('Invalid or unrecognized model directory')
assert result.status == 'error'
assert result.already_existed is False
+@pytest.mark.asyncio
+async def test_download_model_invalid_folder_path():
+ mock_make_request = AsyncMock()
+ mock_progress_callback = AsyncMock()
+
+ result = await download_model(
+ mock_make_request,
+ 'model.sft',
+ 'http://example.com/model.sft',
+ 'checkpoints',
+ 'invalid_path',
+ mock_progress_callback
+ )
+
+ # Assert the result
+ assert isinstance(result, DownloadModelStatus)
+ assert result.message.startswith("Invalid folder path")
+ assert result.status == 'error'
+ assert result.already_existed is False
-# For create_model_path function
def test_create_model_path(tmp_path, monkeypatch):
- mock_models_dir = tmp_path / "models"
- monkeypatch.setattr('folder_paths.models_dir', str(mock_models_dir))
-
- model_name = "test_model.sft"
- model_directory = "test_dir"
-
- file_path, relative_path = create_model_path(model_name, model_directory, mock_models_dir)
-
- assert file_path == str(mock_models_dir / model_directory / model_name)
- assert relative_path == f"{model_directory}/{model_name}"
+ model_name = "model.safetensors"
+ folder_path = os.path.join(tmp_path, "mock_dir")
+
+ file_path = create_model_path(model_name, folder_path)
+
+ assert file_path == os.path.join(folder_path, "model.safetensors")
assert os.path.exists(os.path.dirname(file_path))
+ with pytest.raises(Exception, match="Invalid model directory"):
+ create_model_path("../path_traversal.safetensors", folder_path)
+
+ with pytest.raises(Exception, match="Invalid model directory"):
+ create_model_path("/etc/some_root_path", folder_path)
+
@pytest.mark.asyncio
async def test_check_file_exists_when_file_exists(tmp_path):
file_path = tmp_path / "existing_model.sft"
file_path.touch() # Create an empty file
-
+
mock_callback = AsyncMock()
-
- result = await check_file_exists(str(file_path), "existing_model.sft", mock_callback, "test/existing_model.sft")
-
+
+ result = await check_file_exists(str(file_path), "existing_model.sft", mock_callback)
+
assert result is not None
assert result.status == "completed"
assert result.message == "existing_model.sft already exists"
assert result.already_existed is True
-
+
mock_callback.assert_called_once_with(
- "test/existing_model.sft",
+ "existing_model.sft",
DownloadModelStatus(DownloadStatusType.COMPLETED, 100, "existing_model.sft already exists", already_existed=True)
)
@pytest.mark.asyncio
async def test_check_file_exists_when_file_does_not_exist(tmp_path):
file_path = tmp_path / "non_existing_model.sft"
-
+
mock_callback = AsyncMock()
-
- result = await check_file_exists(str(file_path), "non_existing_model.sft", mock_callback, "test/non_existing_model.sft")
-
+
+ result = await check_file_exists(str(file_path), "non_existing_model.sft", mock_callback)
+
assert result is None
mock_callback.assert_not_called()
@pytest.mark.asyncio
-async def test_track_download_progress_no_content_length():
+async def test_track_download_progress_no_content_length(temp_dir):
mock_response = AsyncMock(spec=aiohttp.ClientResponse)
mock_response.headers = {} # No Content-Length header
- mock_response.content.iter_chunked.return_value = AsyncIteratorMock([b'a' * 500, b'b' * 500])
+ chunks = [b'a' * 500, b'b' * 500]
+ mock_response.content.iter_chunked.return_value = AsyncIteratorMock(chunks)
mock_callback = AsyncMock()
- mock_open = MagicMock(return_value=MagicMock())
- with patch('builtins.open', mock_open):
- result = await track_download_progress(
- mock_response, '/mock/path/model.sft', 'model.sft',
- mock_callback, 'models/model.sft', interval=0.1
- )
+ full_path = os.path.join(temp_dir, 'model.sft')
+
+ result = await track_download_progress(
+ mock_response, full_path, 'model.sft',
+ mock_callback, interval=0.1
+ )
assert result.status == "completed"
+
+ assert os.path.exists(full_path)
+ with open(full_path, 'rb') as f:
+ assert f.read() == b''.join(chunks)
+ os.remove(full_path)
+
# Check that progress was reported even without knowing the total size
mock_callback.assert_any_call(
- 'models/model.sft',
+ 'model.sft',
DownloadModelStatus(DownloadStatusType.IN_PROGRESS, 0, "Downloading model.sft", already_existed=False)
)
@pytest.mark.asyncio
-async def test_track_download_progress_interval():
+async def test_track_download_progress_interval(temp_dir):
mock_response = AsyncMock(spec=aiohttp.ClientResponse)
mock_response.headers = {'Content-Length': '1000'}
- mock_response.content.iter_chunked.return_value = AsyncIteratorMock([b'a' * 100] * 10)
+ chunks = [b'a' * 100] * 10
+ mock_response.content.iter_chunked.return_value = AsyncIteratorMock(chunks)
mock_callback = AsyncMock()
mock_open = MagicMock(return_value=MagicMock())
@@ -253,18 +290,18 @@ async def test_track_download_progress_interval():
mock_time = MagicMock()
mock_time.side_effect = [i * 0.5 for i in range(30)] # This should be enough for 10 chunks
- with patch('builtins.open', mock_open), \
- patch('time.time', mock_time):
- await track_download_progress(
- mock_response, '/mock/path/model.sft', 'model.sft',
- mock_callback, 'models/model.sft', interval=1.0
- )
+ full_path = os.path.join(temp_dir, 'model.sft')
- # Print out the actual call count and the arguments of each call for debugging
- print(f"mock_callback was called {mock_callback.call_count} times")
- for i, call in enumerate(mock_callback.call_args_list):
- args, kwargs = call
- print(f"Call {i + 1}: {args[1].status}, Progress: {args[1].progress_percentage:.2f}%")
+ with patch('time.time', mock_time):
+ await track_download_progress(
+ mock_response, full_path, 'model.sft',
+ mock_callback, interval=1.0
+ )
+
+ assert os.path.exists(full_path)
+ with open(full_path, 'rb') as f:
+ assert f.read() == b''.join(chunks)
+ os.remove(full_path)
# Assert that progress was updated at least 3 times (start, at least one interval, and end)
assert mock_callback.call_count >= 3, f"Expected at least 3 calls, but got {mock_callback.call_count}"
@@ -279,27 +316,6 @@ async def test_track_download_progress_interval():
assert last_call[0][1].status == "completed"
assert last_call[0][1].progress_percentage == 100
-def test_valid_subdirectory():
- assert validate_model_subdirectory("valid-model123") is True
-
-def test_subdirectory_too_long():
- assert validate_model_subdirectory("a" * 51) is False
-
-def test_subdirectory_with_double_dots():
- assert validate_model_subdirectory("model/../unsafe") is False
-
-def test_subdirectory_with_slash():
- assert validate_model_subdirectory("model/unsafe") is False
-
-def test_subdirectory_with_special_characters():
- assert validate_model_subdirectory("model@unsafe") is False
-
-def test_subdirectory_with_underscore_and_dash():
- assert validate_model_subdirectory("valid_model-name") is True
-
-def test_empty_subdirectory():
- assert validate_model_subdirectory("") is False
-
@pytest.mark.parametrize("filename, expected", [
("valid_model.safetensors", True),
("valid_model.sft", True),
diff --git a/tests-unit/prompt_server_test/user_manager_test.py b/tests-unit/prompt_server_test/user_manager_test.py
new file mode 100644
index 000000000..936c6bd27
--- /dev/null
+++ b/tests-unit/prompt_server_test/user_manager_test.py
@@ -0,0 +1,120 @@
+import pytest
+import os
+from aiohttp import web
+from app.user_manager import UserManager
+from unittest.mock import patch
+
+pytestmark = (
+ pytest.mark.asyncio
+) # This applies the asyncio mark to all test functions in the module
+
+
+@pytest.fixture
+def user_manager(tmp_path):
+ um = UserManager()
+ um.get_request_user_filepath = lambda req, file, **kwargs: os.path.join(
+ tmp_path, file
+ )
+ return um
+
+
+@pytest.fixture
+def app(user_manager):
+ app = web.Application()
+ routes = web.RouteTableDef()
+ user_manager.add_routes(routes)
+ app.add_routes(routes)
+ return app
+
+
+async def test_listuserdata_empty_directory(aiohttp_client, app, tmp_path):
+ client = await aiohttp_client(app)
+ resp = await client.get("/userdata?dir=test_dir")
+ assert resp.status == 404
+
+
+async def test_listuserdata_with_files(aiohttp_client, app, tmp_path):
+ os.makedirs(tmp_path / "test_dir")
+ with open(tmp_path / "test_dir" / "file1.txt", "w") as f:
+ f.write("test content")
+
+ client = await aiohttp_client(app)
+ resp = await client.get("/userdata?dir=test_dir")
+ assert resp.status == 200
+ assert await resp.json() == ["file1.txt"]
+
+
+async def test_listuserdata_recursive(aiohttp_client, app, tmp_path):
+ os.makedirs(tmp_path / "test_dir" / "subdir")
+ with open(tmp_path / "test_dir" / "file1.txt", "w") as f:
+ f.write("test content")
+ with open(tmp_path / "test_dir" / "subdir" / "file2.txt", "w") as f:
+ f.write("test content")
+
+ client = await aiohttp_client(app)
+ resp = await client.get("/userdata?dir=test_dir&recurse=true")
+ assert resp.status == 200
+ assert set(await resp.json()) == {"file1.txt", "subdir/file2.txt"}
+
+
+async def test_listuserdata_full_info(aiohttp_client, app, tmp_path):
+ os.makedirs(tmp_path / "test_dir")
+ with open(tmp_path / "test_dir" / "file1.txt", "w") as f:
+ f.write("test content")
+
+ client = await aiohttp_client(app)
+ resp = await client.get("/userdata?dir=test_dir&full_info=true")
+ assert resp.status == 200
+ result = await resp.json()
+ assert len(result) == 1
+ assert result[0]["path"] == "file1.txt"
+ assert "size" in result[0]
+ assert "modified" in result[0]
+
+
+async def test_listuserdata_split_path(aiohttp_client, app, tmp_path):
+ os.makedirs(tmp_path / "test_dir" / "subdir")
+ with open(tmp_path / "test_dir" / "subdir" / "file1.txt", "w") as f:
+ f.write("test content")
+
+ client = await aiohttp_client(app)
+ resp = await client.get("/userdata?dir=test_dir&recurse=true&split=true")
+ assert resp.status == 200
+ assert await resp.json() == [
+ ["subdir/file1.txt", "subdir", "file1.txt"]
+ ]
+
+
+async def test_listuserdata_invalid_directory(aiohttp_client, app):
+ client = await aiohttp_client(app)
+ resp = await client.get("/userdata?dir=")
+ assert resp.status == 400
+
+
+async def test_listuserdata_normalized_separator(aiohttp_client, app, tmp_path):
+ os_sep = "\\"
+ with patch("os.sep", os_sep):
+ with patch("os.path.sep", os_sep):
+ os.makedirs(tmp_path / "test_dir" / "subdir")
+ with open(tmp_path / "test_dir" / "subdir" / "file1.txt", "w") as f:
+ f.write("test content")
+
+ client = await aiohttp_client(app)
+ resp = await client.get("/userdata?dir=test_dir&recurse=true")
+ assert resp.status == 200
+ result = await resp.json()
+ assert len(result) == 1
+ assert "/" in result[0] # Ensure forward slash is used
+ assert "\\" not in result[0] # Ensure backslash is not present
+ assert result[0] == "subdir/file1.txt"
+
+ # Test with full_info
+ resp = await client.get(
+ "/userdata?dir=test_dir&recurse=true&full_info=true"
+ )
+ assert resp.status == 200
+ result = await resp.json()
+ assert len(result) == 1
+ assert "/" in result[0]["path"] # Ensure forward slash is used
+ assert "\\" not in result[0]["path"] # Ensure backslash is not present
+ assert result[0]["path"] == "subdir/file1.txt"
diff --git a/tests-unit/server/routes/internal_routes_test.py b/tests-unit/server/routes/internal_routes_test.py
new file mode 100644
index 000000000..2d2b43bd6
--- /dev/null
+++ b/tests-unit/server/routes/internal_routes_test.py
@@ -0,0 +1,115 @@
+import pytest
+from aiohttp import web
+from unittest.mock import MagicMock, patch
+from api_server.routes.internal.internal_routes import InternalRoutes
+from api_server.services.file_service import FileService
+from folder_paths import models_dir, user_directory, output_directory
+
+
+@pytest.fixture
+def internal_routes():
+ return InternalRoutes()
+
+@pytest.fixture
+def aiohttp_client_factory(aiohttp_client, internal_routes):
+ async def _get_client():
+ app = internal_routes.get_app()
+ return await aiohttp_client(app)
+ return _get_client
+
+@pytest.mark.asyncio
+async def test_list_files_valid_directory(aiohttp_client_factory, internal_routes):
+ mock_file_list = [
+ {"name": "file1.txt", "path": "file1.txt", "type": "file", "size": 100},
+ {"name": "dir1", "path": "dir1", "type": "directory"}
+ ]
+ internal_routes.file_service.list_files = MagicMock(return_value=mock_file_list)
+ client = await aiohttp_client_factory()
+ resp = await client.get('/files?directory=models')
+ assert resp.status == 200
+ data = await resp.json()
+ assert 'files' in data
+ assert len(data['files']) == 2
+ assert data['files'] == mock_file_list
+
+ # Check other valid directories
+ resp = await client.get('/files?directory=user')
+ assert resp.status == 200
+ resp = await client.get('/files?directory=output')
+ assert resp.status == 200
+
+@pytest.mark.asyncio
+async def test_list_files_invalid_directory(aiohttp_client_factory, internal_routes):
+ internal_routes.file_service.list_files = MagicMock(side_effect=ValueError("Invalid directory key"))
+ client = await aiohttp_client_factory()
+ resp = await client.get('/files?directory=invalid')
+ assert resp.status == 400
+ data = await resp.json()
+ assert 'error' in data
+ assert data['error'] == "Invalid directory key"
+
+@pytest.mark.asyncio
+async def test_list_files_exception(aiohttp_client_factory, internal_routes):
+ internal_routes.file_service.list_files = MagicMock(side_effect=Exception("Unexpected error"))
+ client = await aiohttp_client_factory()
+ resp = await client.get('/files?directory=models')
+ assert resp.status == 500
+ data = await resp.json()
+ assert 'error' in data
+ assert data['error'] == "Unexpected error"
+
+@pytest.mark.asyncio
+async def test_list_files_no_directory_param(aiohttp_client_factory, internal_routes):
+ mock_file_list = []
+ internal_routes.file_service.list_files = MagicMock(return_value=mock_file_list)
+ client = await aiohttp_client_factory()
+ resp = await client.get('/files')
+ assert resp.status == 200
+ data = await resp.json()
+ assert 'files' in data
+ assert len(data['files']) == 0
+
+def test_setup_routes(internal_routes):
+ internal_routes.setup_routes()
+ routes = internal_routes.routes
+ assert any(route.method == 'GET' and str(route.path) == '/files' for route in routes)
+
+def test_get_app(internal_routes):
+ app = internal_routes.get_app()
+ assert isinstance(app, web.Application)
+ assert internal_routes._app is not None
+
+def test_get_app_reuse(internal_routes):
+ app1 = internal_routes.get_app()
+ app2 = internal_routes.get_app()
+ assert app1 is app2
+
+@pytest.mark.asyncio
+async def test_routes_added_to_app(aiohttp_client_factory, internal_routes):
+ client = await aiohttp_client_factory()
+ try:
+ resp = await client.get('/files')
+ print(f"Response received: status {resp.status}")
+ except Exception as e:
+ print(f"Exception occurred during GET request: {e}")
+ raise
+
+ assert resp.status != 404, "Route /files does not exist"
+
+@pytest.mark.asyncio
+async def test_file_service_initialization():
+ with patch('api_server.routes.internal.internal_routes.FileService') as MockFileService:
+ # Create a mock instance
+ mock_file_service_instance = MagicMock(spec=FileService)
+ MockFileService.return_value = mock_file_service_instance
+ internal_routes = InternalRoutes()
+
+ # Check if FileService was initialized with the correct parameters
+ MockFileService.assert_called_once_with({
+ "models": models_dir,
+ "user": user_directory,
+ "output": output_directory
+ })
+
+ # Verify that the file_service attribute of InternalRoutes is set
+ assert internal_routes.file_service == mock_file_service_instance
\ No newline at end of file
diff --git a/tests-unit/server/services/file_service_test.py b/tests-unit/server/services/file_service_test.py
new file mode 100644
index 000000000..5650452a3
--- /dev/null
+++ b/tests-unit/server/services/file_service_test.py
@@ -0,0 +1,54 @@
+import pytest
+from unittest.mock import MagicMock
+from api_server.services.file_service import FileService
+
+@pytest.fixture
+def mock_file_system_ops():
+ return MagicMock()
+
+@pytest.fixture
+def file_service(mock_file_system_ops):
+ allowed_directories = {
+ "models": "/path/to/models",
+ "user": "/path/to/user",
+ "output": "/path/to/output"
+ }
+ return FileService(allowed_directories, file_system_ops=mock_file_system_ops)
+
+def test_list_files_valid_directory(file_service, mock_file_system_ops):
+ mock_file_system_ops.walk_directory.return_value = [
+ {"name": "file1.txt", "path": "file1.txt", "type": "file", "size": 100},
+ {"name": "dir1", "path": "dir1", "type": "directory"}
+ ]
+
+ result = file_service.list_files("models")
+
+ assert len(result) == 2
+ assert result[0]["name"] == "file1.txt"
+ assert result[1]["name"] == "dir1"
+ mock_file_system_ops.walk_directory.assert_called_once_with("/path/to/models")
+
+def test_list_files_invalid_directory(file_service):
+ # Does not support walking directories outside of the allowed directories
+ with pytest.raises(ValueError, match="Invalid directory key"):
+ file_service.list_files("invalid_key")
+
+def test_list_files_empty_directory(file_service, mock_file_system_ops):
+ mock_file_system_ops.walk_directory.return_value = []
+
+ result = file_service.list_files("models")
+
+ assert len(result) == 0
+ mock_file_system_ops.walk_directory.assert_called_once_with("/path/to/models")
+
+@pytest.mark.parametrize("directory_key", ["models", "user", "output"])
+def test_list_files_all_allowed_directories(file_service, mock_file_system_ops, directory_key):
+ mock_file_system_ops.walk_directory.return_value = [
+ {"name": f"file_{directory_key}.txt", "path": f"file_{directory_key}.txt", "type": "file", "size": 100}
+ ]
+
+ result = file_service.list_files(directory_key)
+
+ assert len(result) == 1
+ assert result[0]["name"] == f"file_{directory_key}.txt"
+ mock_file_system_ops.walk_directory.assert_called_once_with(f"/path/to/{directory_key}")
\ No newline at end of file
diff --git a/tests-unit/server/utils/file_operations_test.py b/tests-unit/server/utils/file_operations_test.py
new file mode 100644
index 000000000..5a2a83713
--- /dev/null
+++ b/tests-unit/server/utils/file_operations_test.py
@@ -0,0 +1,42 @@
+import pytest
+from typing import List
+from api_server.utils.file_operations import FileSystemOperations, FileSystemItem, is_file_info
+
+@pytest.fixture
+def temp_directory(tmp_path):
+ # Create a temporary directory structure
+ dir1 = tmp_path / "dir1"
+ dir2 = tmp_path / "dir2"
+ dir1.mkdir()
+ dir2.mkdir()
+ (dir1 / "file1.txt").write_text("content1")
+ (dir2 / "file2.txt").write_text("content2")
+ (tmp_path / "file3.txt").write_text("content3")
+ return tmp_path
+
+def test_walk_directory(temp_directory):
+ result: List[FileSystemItem] = FileSystemOperations.walk_directory(str(temp_directory))
+
+ assert len(result) == 5 # 2 directories and 3 files
+
+ files = [item for item in result if item['type'] == 'file']
+ dirs = [item for item in result if item['type'] == 'directory']
+
+ assert len(files) == 3
+ assert len(dirs) == 2
+
+ file_names = {file['name'] for file in files}
+ assert file_names == {'file1.txt', 'file2.txt', 'file3.txt'}
+
+ dir_names = {dir['name'] for dir in dirs}
+ assert dir_names == {'dir1', 'dir2'}
+
+def test_walk_directory_empty(tmp_path):
+ result = FileSystemOperations.walk_directory(str(tmp_path))
+ assert len(result) == 0
+
+def test_walk_directory_file_size(temp_directory):
+ result: List[FileSystemItem] = FileSystemOperations.walk_directory(str(temp_directory))
+ files = [item for item in result if is_file_info(item)]
+ for file in files:
+ assert file['size'] > 0 # Assuming all files have some content
diff --git a/tests-unit/utils/extra_config_test.py b/tests-unit/utils/extra_config_test.py
new file mode 100644
index 000000000..ef772d40b
--- /dev/null
+++ b/tests-unit/utils/extra_config_test.py
@@ -0,0 +1,126 @@
+import pytest
+import yaml
+import os
+from unittest.mock import Mock, patch, mock_open
+
+from utils.extra_config import load_extra_path_config
+import folder_paths
+
+@pytest.fixture
+def mock_yaml_content():
+ return {
+ 'test_config': {
+ 'base_path': '~/App/',
+ 'checkpoints': 'subfolder1',
+ }
+ }
+
+@pytest.fixture
+def mock_expanded_home():
+ return '/home/user'
+
+@pytest.fixture
+def yaml_config_with_appdata():
+ return """
+ test_config:
+ base_path: '%APPDATA%/ComfyUI'
+ checkpoints: 'models/checkpoints'
+ """
+
+@pytest.fixture
+def mock_yaml_content_appdata(yaml_config_with_appdata):
+ return yaml.safe_load(yaml_config_with_appdata)
+
+@pytest.fixture
+def mock_expandvars_appdata():
+ mock = Mock()
+ mock.side_effect = lambda path: path.replace('%APPDATA%', 'C:/Users/TestUser/AppData/Roaming')
+ return mock
+
+@pytest.fixture
+def mock_add_model_folder_path():
+ return Mock()
+
+@pytest.fixture
+def mock_expanduser(mock_expanded_home):
+ def _expanduser(path):
+ if path.startswith('~/'):
+ return os.path.join(mock_expanded_home, path[2:])
+ return path
+ return _expanduser
+
+@pytest.fixture
+def mock_yaml_safe_load(mock_yaml_content):
+ return Mock(return_value=mock_yaml_content)
+
+@patch('builtins.open', new_callable=mock_open, read_data="dummy file content")
+def test_load_extra_model_paths_expands_userpath(
+ mock_file,
+ monkeypatch,
+ mock_add_model_folder_path,
+ mock_expanduser,
+ mock_yaml_safe_load,
+ mock_expanded_home
+):
+ # Attach mocks used by load_extra_path_config
+ monkeypatch.setattr(folder_paths, 'add_model_folder_path', mock_add_model_folder_path)
+ monkeypatch.setattr(os.path, 'expanduser', mock_expanduser)
+ monkeypatch.setattr(yaml, 'safe_load', mock_yaml_safe_load)
+
+ dummy_yaml_file_name = 'dummy_path.yaml'
+ load_extra_path_config(dummy_yaml_file_name)
+
+ expected_calls = [
+ ('checkpoints', os.path.join(mock_expanded_home, 'App', 'subfolder1'), False),
+ ]
+
+ assert mock_add_model_folder_path.call_count == len(expected_calls)
+
+ # Check if add_model_folder_path was called with the correct arguments
+ for actual_call, expected_call in zip(mock_add_model_folder_path.call_args_list, expected_calls):
+ assert actual_call.args[0] == expected_call[0]
+ assert os.path.normpath(actual_call.args[1]) == os.path.normpath(expected_call[1]) # Normalize and check the path to check on multiple OS.
+ assert actual_call.args[2] == expected_call[2]
+
+ # Check if yaml.safe_load was called
+ mock_yaml_safe_load.assert_called_once()
+
+ # Check if open was called with the correct file path
+ mock_file.assert_called_once_with(dummy_yaml_file_name, 'r')
+
+@patch('builtins.open', new_callable=mock_open)
+def test_load_extra_model_paths_expands_appdata(
+ mock_file,
+ monkeypatch,
+ mock_add_model_folder_path,
+ mock_expandvars_appdata,
+ yaml_config_with_appdata,
+ mock_yaml_content_appdata
+):
+ # Set the mock_file to return yaml with appdata as a variable
+ mock_file.return_value.read.return_value = yaml_config_with_appdata
+
+ # Attach mocks
+ monkeypatch.setattr(folder_paths, 'add_model_folder_path', mock_add_model_folder_path)
+ monkeypatch.setattr(os.path, 'expandvars', mock_expandvars_appdata)
+ monkeypatch.setattr(yaml, 'safe_load', Mock(return_value=mock_yaml_content_appdata))
+
+ # Mock expanduser to do nothing (since we're not testing it here)
+ monkeypatch.setattr(os.path, 'expanduser', lambda x: x)
+
+ dummy_yaml_file_name = 'dummy_path.yaml'
+ load_extra_path_config(dummy_yaml_file_name)
+
+ expected_base_path = 'C:/Users/TestUser/AppData/Roaming/ComfyUI'
+ expected_calls = [
+ ('checkpoints', os.path.join(expected_base_path, 'models/checkpoints'), False),
+ ]
+
+ assert mock_add_model_folder_path.call_count == len(expected_calls)
+
+ # Check the base path variable was expanded
+ for actual_call, expected_call in zip(mock_add_model_folder_path.call_args_list, expected_calls):
+ assert actual_call.args == expected_call
+
+ # Verify that expandvars was called
+ assert mock_expandvars_appdata.called
diff --git a/tests/inference/extra_model_paths.yaml b/tests/inference/extra_model_paths.yaml
new file mode 100644
index 000000000..75b2e1ae4
--- /dev/null
+++ b/tests/inference/extra_model_paths.yaml
@@ -0,0 +1,4 @@
+# Config for testing nodes
+testing:
+ custom_nodes: tests/inference/testing_nodes
+
diff --git a/tests/inference/test_execution.py b/tests/inference/test_execution.py
new file mode 100644
index 000000000..3909ca68d
--- /dev/null
+++ b/tests/inference/test_execution.py
@@ -0,0 +1,524 @@
+from io import BytesIO
+import numpy
+from PIL import Image
+import pytest
+from pytest import fixture
+import time
+import torch
+from typing import Union, Dict
+import json
+import subprocess
+import websocket #NOTE: websocket-client (https://github.com/websocket-client/websocket-client)
+import uuid
+import urllib.request
+import urllib.parse
+import urllib.error
+from comfy_execution.graph_utils import GraphBuilder, Node
+
+class RunResult:
+ def __init__(self, prompt_id: str):
+ self.outputs: Dict[str,Dict] = {}
+ self.runs: Dict[str,bool] = {}
+ self.prompt_id: str = prompt_id
+
+ def get_output(self, node: Node):
+ return self.outputs.get(node.id, None)
+
+ def did_run(self, node: Node):
+ return self.runs.get(node.id, False)
+
+ def get_images(self, node: Node):
+ output = self.get_output(node)
+ if output is None:
+ return []
+ return output.get('image_objects', [])
+
+ def get_prompt_id(self):
+ return self.prompt_id
+
+class ComfyClient:
+ def __init__(self):
+ self.test_name = ""
+
+ def connect(self,
+ listen:str = '127.0.0.1',
+ port:Union[str,int] = 8188,
+ client_id: str = str(uuid.uuid4())
+ ):
+ self.client_id = client_id
+ self.server_address = f"{listen}:{port}"
+ ws = websocket.WebSocket()
+ ws.connect("ws://{}/ws?clientId={}".format(self.server_address, self.client_id))
+ self.ws = ws
+
+ def queue_prompt(self, prompt):
+ p = {"prompt": prompt, "client_id": self.client_id}
+ data = json.dumps(p).encode('utf-8')
+ req = urllib.request.Request("http://{}/prompt".format(self.server_address), data=data)
+ return json.loads(urllib.request.urlopen(req).read())
+
+ def get_image(self, filename, subfolder, folder_type):
+ data = {"filename": filename, "subfolder": subfolder, "type": folder_type}
+ url_values = urllib.parse.urlencode(data)
+ with urllib.request.urlopen("http://{}/view?{}".format(self.server_address, url_values)) as response:
+ return response.read()
+
+ def get_history(self, prompt_id):
+ with urllib.request.urlopen("http://{}/history/{}".format(self.server_address, prompt_id)) as response:
+ return json.loads(response.read())
+
+ def set_test_name(self, name):
+ self.test_name = name
+
+ def run(self, graph):
+ prompt = graph.finalize()
+ for node in graph.nodes.values():
+ if node.class_type == 'SaveImage':
+ node.inputs['filename_prefix'] = self.test_name
+
+ prompt_id = self.queue_prompt(prompt)['prompt_id']
+ result = RunResult(prompt_id)
+ while True:
+ out = self.ws.recv()
+ if isinstance(out, str):
+ message = json.loads(out)
+ if message['type'] == 'executing':
+ data = message['data']
+ if data['prompt_id'] != prompt_id:
+ continue
+ if data['node'] is None:
+ break
+ result.runs[data['node']] = True
+ elif message['type'] == 'execution_error':
+ raise Exception(message['data'])
+ elif message['type'] == 'execution_cached':
+ pass # Probably want to store this off for testing
+
+ history = self.get_history(prompt_id)[prompt_id]
+ for node_id in history['outputs']:
+ node_output = history['outputs'][node_id]
+ result.outputs[node_id] = node_output
+ images_output = []
+ if 'images' in node_output:
+ for image in node_output['images']:
+ image_data = self.get_image(image['filename'], image['subfolder'], image['type'])
+ image_obj = Image.open(BytesIO(image_data))
+ images_output.append(image_obj)
+ node_output['image_objects'] = images_output
+
+ return result
+
+#
+# Loop through these variables
+#
+@pytest.mark.execution
+class TestExecution:
+ #
+ # Initialize server and client
+ #
+ @fixture(scope="class", autouse=True, params=[
+ # (use_lru, lru_size)
+ (False, 0),
+ (True, 0),
+ (True, 100),
+ ])
+ def _server(self, args_pytest, request):
+ # Start server
+ pargs = [
+ 'python','main.py',
+ '--output-directory', args_pytest["output_dir"],
+ '--listen', args_pytest["listen"],
+ '--port', str(args_pytest["port"]),
+ '--extra-model-paths-config', 'tests/inference/extra_model_paths.yaml',
+ ]
+ use_lru, lru_size = request.param
+ if use_lru:
+ pargs += ['--cache-lru', str(lru_size)]
+ print("Running server with args:", pargs)
+ p = subprocess.Popen(pargs)
+ yield
+ p.kill()
+ torch.cuda.empty_cache()
+
+ def start_client(self, listen:str, port:int):
+ # Start client
+ comfy_client = ComfyClient()
+ # Connect to server (with retries)
+ n_tries = 5
+ for i in range(n_tries):
+ time.sleep(4)
+ try:
+ comfy_client.connect(listen=listen, port=port)
+ except ConnectionRefusedError as e:
+ print(e)
+ print(f"({i+1}/{n_tries}) Retrying...")
+ else:
+ break
+ return comfy_client
+
+ @fixture(scope="class", autouse=True)
+ def shared_client(self, args_pytest, _server):
+ client = self.start_client(args_pytest["listen"], args_pytest["port"])
+ yield client
+ del client
+ torch.cuda.empty_cache()
+
+ @fixture
+ def client(self, shared_client, request):
+ shared_client.set_test_name(f"execution[{request.node.name}]")
+ yield shared_client
+
+ @fixture
+ def builder(self, request):
+ yield GraphBuilder(prefix=request.node.name)
+
+ def test_lazy_input(self, client: ComfyClient, builder: GraphBuilder):
+ g = builder
+ input1 = g.node("StubImage", content="BLACK", height=512, width=512, batch_size=1)
+ input2 = g.node("StubImage", content="WHITE", height=512, width=512, batch_size=1)
+ mask = g.node("StubMask", value=0.0, height=512, width=512, batch_size=1)
+
+ lazy_mix = g.node("TestLazyMixImages", image1=input1.out(0), image2=input2.out(0), mask=mask.out(0))
+ output = g.node("SaveImage", images=lazy_mix.out(0))
+ result = client.run(g)
+
+ result_image = result.get_images(output)[0]
+ assert numpy.array(result_image).any() == 0, "Image should be black"
+ assert result.did_run(input1)
+ assert not result.did_run(input2)
+ assert result.did_run(mask)
+ assert result.did_run(lazy_mix)
+
+ def test_full_cache(self, client: ComfyClient, builder: GraphBuilder):
+ g = builder
+ input1 = g.node("StubImage", content="BLACK", height=512, width=512, batch_size=1)
+ input2 = g.node("StubImage", content="NOISE", height=512, width=512, batch_size=1)
+ mask = g.node("StubMask", value=0.5, height=512, width=512, batch_size=1)
+
+ lazy_mix = g.node("TestLazyMixImages", image1=input1.out(0), image2=input2.out(0), mask=mask.out(0))
+ g.node("SaveImage", images=lazy_mix.out(0))
+
+ client.run(g)
+ result2 = client.run(g)
+ for node_id, node in g.nodes.items():
+ assert not result2.did_run(node), f"Node {node_id} ran, but should have been cached"
+
+ def test_partial_cache(self, client: ComfyClient, builder: GraphBuilder):
+ g = builder
+ input1 = g.node("StubImage", content="BLACK", height=512, width=512, batch_size=1)
+ input2 = g.node("StubImage", content="NOISE", height=512, width=512, batch_size=1)
+ mask = g.node("StubMask", value=0.5, height=512, width=512, batch_size=1)
+
+ lazy_mix = g.node("TestLazyMixImages", image1=input1.out(0), image2=input2.out(0), mask=mask.out(0))
+ g.node("SaveImage", images=lazy_mix.out(0))
+
+ client.run(g)
+ mask.inputs['value'] = 0.4
+ result2 = client.run(g)
+ assert not result2.did_run(input1), "Input1 should have been cached"
+ assert not result2.did_run(input2), "Input2 should have been cached"
+
+ def test_error(self, client: ComfyClient, builder: GraphBuilder):
+ g = builder
+ input1 = g.node("StubImage", content="BLACK", height=512, width=512, batch_size=1)
+ # Different size of the two images
+ input2 = g.node("StubImage", content="NOISE", height=256, width=256, batch_size=1)
+ mask = g.node("StubMask", value=0.5, height=512, width=512, batch_size=1)
+
+ lazy_mix = g.node("TestLazyMixImages", image1=input1.out(0), image2=input2.out(0), mask=mask.out(0))
+ g.node("SaveImage", images=lazy_mix.out(0))
+
+ try:
+ client.run(g)
+ assert False, "Should have raised an error"
+ except Exception as e:
+ assert 'prompt_id' in e.args[0], f"Did not get back a proper error message: {e}"
+
+ @pytest.mark.parametrize("test_value, expect_error", [
+ (5, True),
+ ("foo", True),
+ (5.0, False),
+ ])
+ def test_validation_error_literal(self, test_value, expect_error, client: ComfyClient, builder: GraphBuilder):
+ g = builder
+ validation1 = g.node("TestCustomValidation1", input1=test_value, input2=3.0)
+ g.node("SaveImage", images=validation1.out(0))
+
+ if expect_error:
+ with pytest.raises(urllib.error.HTTPError):
+ client.run(g)
+ else:
+ client.run(g)
+
+ @pytest.mark.parametrize("test_type, test_value", [
+ ("StubInt", 5),
+ ("StubFloat", 5.0)
+ ])
+ def test_validation_error_edge1(self, test_type, test_value, client: ComfyClient, builder: GraphBuilder):
+ g = builder
+ stub = g.node(test_type, value=test_value)
+ validation1 = g.node("TestCustomValidation1", input1=stub.out(0), input2=3.0)
+ g.node("SaveImage", images=validation1.out(0))
+
+ with pytest.raises(urllib.error.HTTPError):
+ client.run(g)
+
+ @pytest.mark.parametrize("test_type, test_value, expect_error", [
+ ("StubInt", 5, True),
+ ("StubFloat", 5.0, False)
+ ])
+ def test_validation_error_edge2(self, test_type, test_value, expect_error, client: ComfyClient, builder: GraphBuilder):
+ g = builder
+ stub = g.node(test_type, value=test_value)
+ validation2 = g.node("TestCustomValidation2", input1=stub.out(0), input2=3.0)
+ g.node("SaveImage", images=validation2.out(0))
+
+ if expect_error:
+ with pytest.raises(urllib.error.HTTPError):
+ client.run(g)
+ else:
+ client.run(g)
+
+ @pytest.mark.parametrize("test_type, test_value, expect_error", [
+ ("StubInt", 5, True),
+ ("StubFloat", 5.0, False)
+ ])
+ def test_validation_error_edge3(self, test_type, test_value, expect_error, client: ComfyClient, builder: GraphBuilder):
+ g = builder
+ stub = g.node(test_type, value=test_value)
+ validation3 = g.node("TestCustomValidation3", input1=stub.out(0), input2=3.0)
+ g.node("SaveImage", images=validation3.out(0))
+
+ if expect_error:
+ with pytest.raises(urllib.error.HTTPError):
+ client.run(g)
+ else:
+ client.run(g)
+
+ @pytest.mark.parametrize("test_type, test_value, expect_error", [
+ ("StubInt", 5, True),
+ ("StubFloat", 5.0, False)
+ ])
+ def test_validation_error_edge4(self, test_type, test_value, expect_error, client: ComfyClient, builder: GraphBuilder):
+ g = builder
+ stub = g.node(test_type, value=test_value)
+ validation4 = g.node("TestCustomValidation4", input1=stub.out(0), input2=3.0)
+ g.node("SaveImage", images=validation4.out(0))
+
+ if expect_error:
+ with pytest.raises(urllib.error.HTTPError):
+ client.run(g)
+ else:
+ client.run(g)
+
+ @pytest.mark.parametrize("test_value1, test_value2, expect_error", [
+ (0.0, 0.5, False),
+ (0.0, 5.0, False),
+ (0.0, 7.0, True)
+ ])
+ def test_validation_error_kwargs(self, test_value1, test_value2, expect_error, client: ComfyClient, builder: GraphBuilder):
+ g = builder
+ validation5 = g.node("TestCustomValidation5", input1=test_value1, input2=test_value2)
+ g.node("SaveImage", images=validation5.out(0))
+
+ if expect_error:
+ with pytest.raises(urllib.error.HTTPError):
+ client.run(g)
+ else:
+ client.run(g)
+
+ def test_cycle_error(self, client: ComfyClient, builder: GraphBuilder):
+ g = builder
+ input1 = g.node("StubImage", content="BLACK", height=512, width=512, batch_size=1)
+ input2 = g.node("StubImage", content="WHITE", height=512, width=512, batch_size=1)
+ mask = g.node("StubMask", value=0.5, height=512, width=512, batch_size=1)
+
+ lazy_mix1 = g.node("TestLazyMixImages", image1=input1.out(0), mask=mask.out(0))
+ lazy_mix2 = g.node("TestLazyMixImages", image1=lazy_mix1.out(0), image2=input2.out(0), mask=mask.out(0))
+ g.node("SaveImage", images=lazy_mix2.out(0))
+
+ # When the cycle exists on initial submission, it should raise a validation error
+ with pytest.raises(urllib.error.HTTPError):
+ client.run(g)
+
+ def test_dynamic_cycle_error(self, client: ComfyClient, builder: GraphBuilder):
+ g = builder
+ input1 = g.node("StubImage", content="BLACK", height=512, width=512, batch_size=1)
+ input2 = g.node("StubImage", content="WHITE", height=512, width=512, batch_size=1)
+ generator = g.node("TestDynamicDependencyCycle", input1=input1.out(0), input2=input2.out(0))
+ g.node("SaveImage", images=generator.out(0))
+
+ # When the cycle is in a graph that is generated dynamically, it should raise a runtime error
+ try:
+ client.run(g)
+ assert False, "Should have raised an error"
+ except Exception as e:
+ assert 'prompt_id' in e.args[0], f"Did not get back a proper error message: {e}"
+ assert e.args[0]['node_id'] == generator.id, "Error should have been on the generator node"
+
+ def test_missing_node_error(self, client: ComfyClient, builder: GraphBuilder):
+ g = builder
+ input1 = g.node("StubImage", content="BLACK", height=512, width=512, batch_size=1)
+ input2 = g.node("StubImage", id="removeme", content="WHITE", height=512, width=512, batch_size=1)
+ input3 = g.node("StubImage", content="WHITE", height=512, width=512, batch_size=1)
+ mask = g.node("StubMask", value=0.5, height=512, width=512, batch_size=1)
+ mix1 = g.node("TestLazyMixImages", image1=input1.out(0), image2=input2.out(0), mask=mask.out(0))
+ mix2 = g.node("TestLazyMixImages", image1=input1.out(0), image2=input3.out(0), mask=mask.out(0))
+ # We have multiple outputs. The first is invalid, but the second is valid
+ g.node("SaveImage", images=mix1.out(0))
+ g.node("SaveImage", images=mix2.out(0))
+ g.remove_node("removeme")
+
+ client.run(g)
+
+ # Add back in the missing node to make sure the error doesn't break the server
+ input2 = g.node("StubImage", id="removeme", content="WHITE", height=512, width=512, batch_size=1)
+ client.run(g)
+
+ def test_custom_is_changed(self, client: ComfyClient, builder: GraphBuilder):
+ g = builder
+ # Creating the nodes in this specific order previously caused a bug
+ save = g.node("SaveImage")
+ is_changed = g.node("TestCustomIsChanged", should_change=False)
+ input1 = g.node("StubImage", content="BLACK", height=512, width=512, batch_size=1)
+
+ save.set_input('images', is_changed.out(0))
+ is_changed.set_input('image', input1.out(0))
+
+ result1 = client.run(g)
+ result2 = client.run(g)
+ is_changed.set_input('should_change', True)
+ result3 = client.run(g)
+ result4 = client.run(g)
+ assert result1.did_run(is_changed), "is_changed should have been run"
+ assert not result2.did_run(is_changed), "is_changed should have been cached"
+ assert result3.did_run(is_changed), "is_changed should have been re-run"
+ assert result4.did_run(is_changed), "is_changed should not have been cached"
+
+ def test_undeclared_inputs(self, client: ComfyClient, builder: GraphBuilder):
+ g = builder
+ input1 = g.node("StubImage", content="BLACK", height=512, width=512, batch_size=1)
+ input2 = g.node("StubImage", content="WHITE", height=512, width=512, batch_size=1)
+ input3 = g.node("StubImage", content="BLACK", height=512, width=512, batch_size=1)
+ input4 = g.node("StubImage", content="BLACK", height=512, width=512, batch_size=1)
+ average = g.node("TestVariadicAverage", input1=input1.out(0), input2=input2.out(0), input3=input3.out(0), input4=input4.out(0))
+ output = g.node("SaveImage", images=average.out(0))
+
+ result = client.run(g)
+ result_image = result.get_images(output)[0]
+ expected = 255 // 4
+ assert numpy.array(result_image).min() == expected and numpy.array(result_image).max() == expected, "Image should be grey"
+
+ def test_for_loop(self, client: ComfyClient, builder: GraphBuilder):
+ g = builder
+ iterations = 4
+ input1 = g.node("StubImage", content="BLACK", height=512, width=512, batch_size=1)
+ input2 = g.node("StubImage", content="WHITE", height=512, width=512, batch_size=1)
+ is_changed = g.node("TestCustomIsChanged", should_change=True, image=input2.out(0))
+ for_open = g.node("TestForLoopOpen", remaining=iterations, initial_value1=is_changed.out(0))
+ average = g.node("TestVariadicAverage", input1=input1.out(0), input2=for_open.out(2))
+ for_close = g.node("TestForLoopClose", flow_control=for_open.out(0), initial_value1=average.out(0))
+ output = g.node("SaveImage", images=for_close.out(0))
+
+ for iterations in range(1, 5):
+ for_open.set_input('remaining', iterations)
+ result = client.run(g)
+ result_image = result.get_images(output)[0]
+ expected = 255 // (2 ** iterations)
+ assert numpy.array(result_image).min() == expected and numpy.array(result_image).max() == expected, "Image should be grey"
+ assert result.did_run(is_changed)
+
+ def test_mixed_expansion_returns(self, client: ComfyClient, builder: GraphBuilder):
+ g = builder
+ val_list = g.node("TestMakeListNode", value1=0.1, value2=0.2, value3=0.3)
+ mixed = g.node("TestMixedExpansionReturns", input1=val_list.out(0))
+ output_dynamic = g.node("SaveImage", images=mixed.out(0))
+ output_literal = g.node("SaveImage", images=mixed.out(1))
+
+ result = client.run(g)
+ images_dynamic = result.get_images(output_dynamic)
+ assert len(images_dynamic) == 3, "Should have 2 images"
+ assert numpy.array(images_dynamic[0]).min() == 25 and numpy.array(images_dynamic[0]).max() == 25, "First image should be 0.1"
+ assert numpy.array(images_dynamic[1]).min() == 51 and numpy.array(images_dynamic[1]).max() == 51, "Second image should be 0.2"
+ assert numpy.array(images_dynamic[2]).min() == 76 and numpy.array(images_dynamic[2]).max() == 76, "Third image should be 0.3"
+
+ images_literal = result.get_images(output_literal)
+ assert len(images_literal) == 3, "Should have 2 images"
+ for i in range(3):
+ assert numpy.array(images_literal[i]).min() == 255 and numpy.array(images_literal[i]).max() == 255, "All images should be white"
+
+ def test_mixed_lazy_results(self, client: ComfyClient, builder: GraphBuilder):
+ g = builder
+ val_list = g.node("TestMakeListNode", value1=0.0, value2=0.5, value3=1.0)
+ mask = g.node("StubMask", value=val_list.out(0), height=512, width=512, batch_size=1)
+ input1 = g.node("StubImage", content="BLACK", height=512, width=512, batch_size=1)
+ input2 = g.node("StubImage", content="WHITE", height=512, width=512, batch_size=1)
+ mix = g.node("TestLazyMixImages", image1=input1.out(0), image2=input2.out(0), mask=mask.out(0))
+ rebatch = g.node("RebatchImages", images=mix.out(0), batch_size=3)
+ output = g.node("SaveImage", images=rebatch.out(0))
+
+ result = client.run(g)
+ images = result.get_images(output)
+ assert len(images) == 3, "Should have 3 image"
+ assert numpy.array(images[0]).min() == 0 and numpy.array(images[0]).max() == 0, "First image should be 0.0"
+ assert numpy.array(images[1]).min() == 127 and numpy.array(images[1]).max() == 127, "Second image should be 0.5"
+ assert numpy.array(images[2]).min() == 255 and numpy.array(images[2]).max() == 255, "Third image should be 1.0"
+
+ def test_output_reuse(self, client: ComfyClient, builder: GraphBuilder):
+ g = builder
+ input1 = g.node("StubImage", content="BLACK", height=512, width=512, batch_size=1)
+
+ output1 = g.node("SaveImage", images=input1.out(0))
+ output2 = g.node("SaveImage", images=input1.out(0))
+
+ result = client.run(g)
+ images1 = result.get_images(output1)
+ images2 = result.get_images(output2)
+ assert len(images1) == 1, "Should have 1 image"
+ assert len(images2) == 1, "Should have 1 image"
+
+
+ # This tests that only constant outputs are used in the call to `IS_CHANGED`
+ def test_is_changed_with_outputs(self, client: ComfyClient, builder: GraphBuilder):
+ g = builder
+ input1 = g.node("StubConstantImage", value=0.5, height=512, width=512, batch_size=1)
+ test_node = g.node("TestIsChangedWithConstants", image=input1.out(0), value=0.5)
+
+ output = g.node("PreviewImage", images=test_node.out(0))
+
+ result = client.run(g)
+ images = result.get_images(output)
+ assert len(images) == 1, "Should have 1 image"
+ assert numpy.array(images[0]).min() == 63 and numpy.array(images[0]).max() == 63, "Image should have value 0.25"
+
+ result = client.run(g)
+ images = result.get_images(output)
+ assert len(images) == 1, "Should have 1 image"
+ assert numpy.array(images[0]).min() == 63 and numpy.array(images[0]).max() == 63, "Image should have value 0.25"
+ assert not result.did_run(test_node), "The execution should have been cached"
+
+ # This tests that nodes with OUTPUT_IS_LIST function correctly when they receive an ExecutionBlocker
+ # as input. We also test that when that list (containing an ExecutionBlocker) is passed to a node,
+ # only that one entry in the list is blocked.
+ def test_execution_block_list_output(self, client: ComfyClient, builder: GraphBuilder):
+ g = builder
+ image1 = g.node("StubImage", content="BLACK", height=512, width=512, batch_size=1)
+ image2 = g.node("StubImage", content="WHITE", height=512, width=512, batch_size=1)
+ image3 = g.node("StubImage", content="BLACK", height=512, width=512, batch_size=1)
+ image_list = g.node("TestMakeListNode", value1=image1.out(0), value2=image2.out(0), value3=image3.out(0))
+ int1 = g.node("StubInt", value=1)
+ int2 = g.node("StubInt", value=2)
+ int3 = g.node("StubInt", value=3)
+ int_list = g.node("TestMakeListNode", value1=int1.out(0), value2=int2.out(0), value3=int3.out(0))
+ compare = g.node("TestIntConditions", a=int_list.out(0), b=2, operation="==")
+ blocker = g.node("TestExecutionBlocker", input=image_list.out(0), block=compare.out(0), verbose=False)
+
+ list_output = g.node("TestMakeListNode", value1=blocker.out(0))
+ output = g.node("PreviewImage", images=list_output.out(0))
+
+ result = client.run(g)
+ assert result.did_run(output), "The execution should have run"
+ images = result.get_images(output)
+ assert len(images) == 2, "Should have 2 images"
+ assert numpy.array(images[0]).min() == 0 and numpy.array(images[0]).max() == 0, "First image should be black"
+ assert numpy.array(images[1]).min() == 0 and numpy.array(images[1]).max() == 0, "Second image should also be black"
diff --git a/tests/inference/test_inference.py b/tests/inference/test_inference.py
index 141cc5c7e..2e11778f2 100644
--- a/tests/inference/test_inference.py
+++ b/tests/inference/test_inference.py
@@ -109,15 +109,14 @@ class ComfyClient:
continue #previews are binary data
history = self.get_history(prompt_id)[prompt_id]
- for o in history['outputs']:
- for node_id in history['outputs']:
- node_output = history['outputs'][node_id]
- if 'images' in node_output:
- images_output = []
- for image in node_output['images']:
- image_data = self.get_image(image['filename'], image['subfolder'], image['type'])
- images_output.append(image_data)
- output_images[node_id] = images_output
+ for node_id in history['outputs']:
+ node_output = history['outputs'][node_id]
+ images_output = []
+ if 'images' in node_output:
+ for image in node_output['images']:
+ image_data = self.get_image(image['filename'], image['subfolder'], image['type'])
+ images_output.append(image_data)
+ output_images[node_id] = images_output
return output_images
diff --git a/tests/inference/testing_nodes/testing-pack/__init__.py b/tests/inference/testing_nodes/testing-pack/__init__.py
new file mode 100644
index 000000000..dcc71659a
--- /dev/null
+++ b/tests/inference/testing_nodes/testing-pack/__init__.py
@@ -0,0 +1,23 @@
+from .specific_tests import TEST_NODE_CLASS_MAPPINGS, TEST_NODE_DISPLAY_NAME_MAPPINGS
+from .flow_control import FLOW_CONTROL_NODE_CLASS_MAPPINGS, FLOW_CONTROL_NODE_DISPLAY_NAME_MAPPINGS
+from .util import UTILITY_NODE_CLASS_MAPPINGS, UTILITY_NODE_DISPLAY_NAME_MAPPINGS
+from .conditions import CONDITION_NODE_CLASS_MAPPINGS, CONDITION_NODE_DISPLAY_NAME_MAPPINGS
+from .stubs import TEST_STUB_NODE_CLASS_MAPPINGS, TEST_STUB_NODE_DISPLAY_NAME_MAPPINGS
+
+# NODE_CLASS_MAPPINGS = GENERAL_NODE_CLASS_MAPPINGS.update(COMPONENT_NODE_CLASS_MAPPINGS)
+# NODE_DISPLAY_NAME_MAPPINGS = GENERAL_NODE_DISPLAY_NAME_MAPPINGS.update(COMPONENT_NODE_DISPLAY_NAME_MAPPINGS)
+
+NODE_CLASS_MAPPINGS = {}
+NODE_CLASS_MAPPINGS.update(TEST_NODE_CLASS_MAPPINGS)
+NODE_CLASS_MAPPINGS.update(FLOW_CONTROL_NODE_CLASS_MAPPINGS)
+NODE_CLASS_MAPPINGS.update(UTILITY_NODE_CLASS_MAPPINGS)
+NODE_CLASS_MAPPINGS.update(CONDITION_NODE_CLASS_MAPPINGS)
+NODE_CLASS_MAPPINGS.update(TEST_STUB_NODE_CLASS_MAPPINGS)
+
+NODE_DISPLAY_NAME_MAPPINGS = {}
+NODE_DISPLAY_NAME_MAPPINGS.update(TEST_NODE_DISPLAY_NAME_MAPPINGS)
+NODE_DISPLAY_NAME_MAPPINGS.update(FLOW_CONTROL_NODE_DISPLAY_NAME_MAPPINGS)
+NODE_DISPLAY_NAME_MAPPINGS.update(UTILITY_NODE_DISPLAY_NAME_MAPPINGS)
+NODE_DISPLAY_NAME_MAPPINGS.update(CONDITION_NODE_DISPLAY_NAME_MAPPINGS)
+NODE_DISPLAY_NAME_MAPPINGS.update(TEST_STUB_NODE_DISPLAY_NAME_MAPPINGS)
+
diff --git a/tests/inference/testing_nodes/testing-pack/conditions.py b/tests/inference/testing_nodes/testing-pack/conditions.py
new file mode 100644
index 000000000..0c200ee28
--- /dev/null
+++ b/tests/inference/testing_nodes/testing-pack/conditions.py
@@ -0,0 +1,194 @@
+import re
+import torch
+
+class TestIntConditions:
+ def __init__(self):
+ pass
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "a": ("INT", {"default": 0, "min": -0xffffffffffffffff, "max": 0xffffffffffffffff, "step": 1}),
+ "b": ("INT", {"default": 0, "min": -0xffffffffffffffff, "max": 0xffffffffffffffff, "step": 1}),
+ "operation": (["==", "!=", "<", ">", "<=", ">="],),
+ },
+ }
+
+ RETURN_TYPES = ("BOOLEAN",)
+ FUNCTION = "int_condition"
+
+ CATEGORY = "Testing/Logic"
+
+ def int_condition(self, a, b, operation):
+ if operation == "==":
+ return (a == b,)
+ elif operation == "!=":
+ return (a != b,)
+ elif operation == "<":
+ return (a < b,)
+ elif operation == ">":
+ return (a > b,)
+ elif operation == "<=":
+ return (a <= b,)
+ elif operation == ">=":
+ return (a >= b,)
+
+
+class TestFloatConditions:
+ def __init__(self):
+ pass
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "a": ("FLOAT", {"default": 0, "min": -999999999999.0, "max": 999999999999.0, "step": 1}),
+ "b": ("FLOAT", {"default": 0, "min": -999999999999.0, "max": 999999999999.0, "step": 1}),
+ "operation": (["==", "!=", "<", ">", "<=", ">="],),
+ },
+ }
+
+ RETURN_TYPES = ("BOOLEAN",)
+ FUNCTION = "float_condition"
+
+ CATEGORY = "Testing/Logic"
+
+ def float_condition(self, a, b, operation):
+ if operation == "==":
+ return (a == b,)
+ elif operation == "!=":
+ return (a != b,)
+ elif operation == "<":
+ return (a < b,)
+ elif operation == ">":
+ return (a > b,)
+ elif operation == "<=":
+ return (a <= b,)
+ elif operation == ">=":
+ return (a >= b,)
+
+class TestStringConditions:
+ def __init__(self):
+ pass
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "a": ("STRING", {"multiline": False}),
+ "b": ("STRING", {"multiline": False}),
+ "operation": (["a == b", "a != b", "a IN b", "a MATCH REGEX(b)", "a BEGINSWITH b", "a ENDSWITH b"],),
+ "case_sensitive": ("BOOLEAN", {"default": True}),
+ },
+ }
+
+ RETURN_TYPES = ("BOOLEAN",)
+ FUNCTION = "string_condition"
+
+ CATEGORY = "Testing/Logic"
+
+ def string_condition(self, a, b, operation, case_sensitive):
+ if not case_sensitive:
+ a = a.lower()
+ b = b.lower()
+
+ if operation == "a == b":
+ return (a == b,)
+ elif operation == "a != b":
+ return (a != b,)
+ elif operation == "a IN b":
+ return (a in b,)
+ elif operation == "a MATCH REGEX(b)":
+ try:
+ return (re.match(b, a) is not None,)
+ except:
+ return (False,)
+ elif operation == "a BEGINSWITH b":
+ return (a.startswith(b),)
+ elif operation == "a ENDSWITH b":
+ return (a.endswith(b),)
+
+class TestToBoolNode:
+ def __init__(self):
+ pass
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "value": ("*",),
+ },
+ "optional": {
+ "invert": ("BOOLEAN", {"default": False}),
+ },
+ }
+
+ RETURN_TYPES = ("BOOLEAN",)
+ FUNCTION = "to_bool"
+
+ CATEGORY = "Testing/Logic"
+
+ def to_bool(self, value, invert = False):
+ if isinstance(value, torch.Tensor):
+ if value.max().item() == 0 and value.min().item() == 0:
+ result = False
+ else:
+ result = True
+ else:
+ try:
+ result = bool(value)
+ except:
+ # Can't convert it? Well then it's something or other. I dunno, I'm not a Python programmer.
+ result = True
+
+ if invert:
+ result = not result
+
+ return (result,)
+
+class TestBoolOperationNode:
+ def __init__(self):
+ pass
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "a": ("BOOLEAN",),
+ "b": ("BOOLEAN",),
+ "op": (["a AND b", "a OR b", "a XOR b", "NOT a"],),
+ },
+ }
+
+ RETURN_TYPES = ("BOOLEAN",)
+ FUNCTION = "bool_operation"
+
+ CATEGORY = "Testing/Logic"
+
+ def bool_operation(self, a, b, op):
+ if op == "a AND b":
+ return (a and b,)
+ elif op == "a OR b":
+ return (a or b,)
+ elif op == "a XOR b":
+ return (a ^ b,)
+ elif op == "NOT a":
+ return (not a,)
+
+
+CONDITION_NODE_CLASS_MAPPINGS = {
+ "TestIntConditions": TestIntConditions,
+ "TestFloatConditions": TestFloatConditions,
+ "TestStringConditions": TestStringConditions,
+ "TestToBoolNode": TestToBoolNode,
+ "TestBoolOperationNode": TestBoolOperationNode,
+}
+
+CONDITION_NODE_DISPLAY_NAME_MAPPINGS = {
+ "TestIntConditions": "Int Condition",
+ "TestFloatConditions": "Float Condition",
+ "TestStringConditions": "String Condition",
+ "TestToBoolNode": "To Bool",
+ "TestBoolOperationNode": "Bool Operation",
+}
diff --git a/tests/inference/testing_nodes/testing-pack/flow_control.py b/tests/inference/testing_nodes/testing-pack/flow_control.py
new file mode 100644
index 000000000..ba943be60
--- /dev/null
+++ b/tests/inference/testing_nodes/testing-pack/flow_control.py
@@ -0,0 +1,173 @@
+from comfy_execution.graph_utils import GraphBuilder, is_link
+from comfy_execution.graph import ExecutionBlocker
+from .tools import VariantSupport
+
+NUM_FLOW_SOCKETS = 5
+@VariantSupport()
+class TestWhileLoopOpen:
+ def __init__(self):
+ pass
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ inputs = {
+ "required": {
+ "condition": ("BOOLEAN", {"default": True}),
+ },
+ "optional": {
+ },
+ }
+ for i in range(NUM_FLOW_SOCKETS):
+ inputs["optional"][f"initial_value{i}"] = ("*",)
+ return inputs
+
+ RETURN_TYPES = tuple(["FLOW_CONTROL"] + ["*"] * NUM_FLOW_SOCKETS)
+ RETURN_NAMES = tuple(["FLOW_CONTROL"] + [f"value{i}" for i in range(NUM_FLOW_SOCKETS)])
+ FUNCTION = "while_loop_open"
+
+ CATEGORY = "Testing/Flow"
+
+ def while_loop_open(self, condition, **kwargs):
+ values = []
+ for i in range(NUM_FLOW_SOCKETS):
+ values.append(kwargs.get(f"initial_value{i}", None))
+ return tuple(["stub"] + values)
+
+@VariantSupport()
+class TestWhileLoopClose:
+ def __init__(self):
+ pass
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ inputs = {
+ "required": {
+ "flow_control": ("FLOW_CONTROL", {"rawLink": True}),
+ "condition": ("BOOLEAN", {"forceInput": True}),
+ },
+ "optional": {
+ },
+ "hidden": {
+ "dynprompt": "DYNPROMPT",
+ "unique_id": "UNIQUE_ID",
+ }
+ }
+ for i in range(NUM_FLOW_SOCKETS):
+ inputs["optional"][f"initial_value{i}"] = ("*",)
+ return inputs
+
+ RETURN_TYPES = tuple(["*"] * NUM_FLOW_SOCKETS)
+ RETURN_NAMES = tuple([f"value{i}" for i in range(NUM_FLOW_SOCKETS)])
+ FUNCTION = "while_loop_close"
+
+ CATEGORY = "Testing/Flow"
+
+ def explore_dependencies(self, node_id, dynprompt, upstream):
+ node_info = dynprompt.get_node(node_id)
+ if "inputs" not in node_info:
+ return
+ for k, v in node_info["inputs"].items():
+ if is_link(v):
+ parent_id = v[0]
+ if parent_id not in upstream:
+ upstream[parent_id] = []
+ self.explore_dependencies(parent_id, dynprompt, upstream)
+ upstream[parent_id].append(node_id)
+
+ def collect_contained(self, node_id, upstream, contained):
+ if node_id not in upstream:
+ return
+ for child_id in upstream[node_id]:
+ if child_id not in contained:
+ contained[child_id] = True
+ self.collect_contained(child_id, upstream, contained)
+
+
+ def while_loop_close(self, flow_control, condition, dynprompt=None, unique_id=None, **kwargs):
+ assert dynprompt is not None
+ if not condition:
+ # We're done with the loop
+ values = []
+ for i in range(NUM_FLOW_SOCKETS):
+ values.append(kwargs.get(f"initial_value{i}", None))
+ return tuple(values)
+
+ # We want to loop
+ upstream = {}
+ # Get the list of all nodes between the open and close nodes
+ self.explore_dependencies(unique_id, dynprompt, upstream)
+
+ contained = {}
+ open_node = flow_control[0]
+ self.collect_contained(open_node, upstream, contained)
+ contained[unique_id] = True
+ contained[open_node] = True
+
+ # We'll use the default prefix, but to avoid having node names grow exponentially in size,
+ # we'll use "Recurse" for the name of the recursively-generated copy of this node.
+ graph = GraphBuilder()
+ for node_id in contained:
+ original_node = dynprompt.get_node(node_id)
+ node = graph.node(original_node["class_type"], "Recurse" if node_id == unique_id else node_id)
+ node.set_override_display_id(node_id)
+ for node_id in contained:
+ original_node = dynprompt.get_node(node_id)
+ node = graph.lookup_node("Recurse" if node_id == unique_id else node_id)
+ assert node is not None
+ for k, v in original_node["inputs"].items():
+ if is_link(v) and v[0] in contained:
+ parent = graph.lookup_node(v[0])
+ assert parent is not None
+ node.set_input(k, parent.out(v[1]))
+ else:
+ node.set_input(k, v)
+ new_open = graph.lookup_node(open_node)
+ assert new_open is not None
+ for i in range(NUM_FLOW_SOCKETS):
+ key = f"initial_value{i}"
+ new_open.set_input(key, kwargs.get(key, None))
+ my_clone = graph.lookup_node("Recurse")
+ assert my_clone is not None
+ result = map(lambda x: my_clone.out(x), range(NUM_FLOW_SOCKETS))
+ return {
+ "result": tuple(result),
+ "expand": graph.finalize(),
+ }
+
+@VariantSupport()
+class TestExecutionBlockerNode:
+ def __init__(self):
+ pass
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ inputs = {
+ "required": {
+ "input": ("*",),
+ "block": ("BOOLEAN",),
+ "verbose": ("BOOLEAN", {"default": False}),
+ },
+ }
+ return inputs
+
+ RETURN_TYPES = ("*",)
+ RETURN_NAMES = ("output",)
+ FUNCTION = "execution_blocker"
+
+ CATEGORY = "Testing/Flow"
+
+ def execution_blocker(self, input, block, verbose):
+ if block:
+ return (ExecutionBlocker("Blocked Execution" if verbose else None),)
+ return (input,)
+
+FLOW_CONTROL_NODE_CLASS_MAPPINGS = {
+ "TestWhileLoopOpen": TestWhileLoopOpen,
+ "TestWhileLoopClose": TestWhileLoopClose,
+ "TestExecutionBlocker": TestExecutionBlockerNode,
+}
+FLOW_CONTROL_NODE_DISPLAY_NAME_MAPPINGS = {
+ "TestWhileLoopOpen": "While Loop Open",
+ "TestWhileLoopClose": "While Loop Close",
+ "TestExecutionBlocker": "Execution Blocker",
+}
diff --git a/tests/inference/testing_nodes/testing-pack/specific_tests.py b/tests/inference/testing_nodes/testing-pack/specific_tests.py
new file mode 100644
index 000000000..dd8100237
--- /dev/null
+++ b/tests/inference/testing_nodes/testing-pack/specific_tests.py
@@ -0,0 +1,362 @@
+import torch
+from .tools import VariantSupport
+from comfy_execution.graph_utils import GraphBuilder
+
+class TestLazyMixImages:
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "image1": ("IMAGE",{"lazy": True}),
+ "image2": ("IMAGE",{"lazy": True}),
+ "mask": ("MASK",),
+ },
+ }
+
+ RETURN_TYPES = ("IMAGE",)
+ FUNCTION = "mix"
+
+ CATEGORY = "Testing/Nodes"
+
+ def check_lazy_status(self, mask, image1, image2):
+ mask_min = mask.min()
+ mask_max = mask.max()
+ needed = []
+ if image1 is None and (mask_min != 1.0 or mask_max != 1.0):
+ needed.append("image1")
+ if image2 is None and (mask_min != 0.0 or mask_max != 0.0):
+ needed.append("image2")
+ return needed
+
+ # Not trying to handle different batch sizes here just to keep the demo simple
+ def mix(self, mask, image1, image2):
+ mask_min = mask.min()
+ mask_max = mask.max()
+ if mask_min == 0.0 and mask_max == 0.0:
+ return (image1,)
+ elif mask_min == 1.0 and mask_max == 1.0:
+ return (image2,)
+
+ if len(mask.shape) == 2:
+ mask = mask.unsqueeze(0)
+ if len(mask.shape) == 3:
+ mask = mask.unsqueeze(3)
+ if mask.shape[3] < image1.shape[3]:
+ mask = mask.repeat(1, 1, 1, image1.shape[3])
+
+ result = image1 * (1. - mask) + image2 * mask,
+ return (result[0],)
+
+class TestVariadicAverage:
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "input1": ("IMAGE",),
+ },
+ }
+
+ RETURN_TYPES = ("IMAGE",)
+ FUNCTION = "variadic_average"
+
+ CATEGORY = "Testing/Nodes"
+
+ def variadic_average(self, input1, **kwargs):
+ inputs = [input1]
+ while 'input' + str(len(inputs) + 1) in kwargs:
+ inputs.append(kwargs['input' + str(len(inputs) + 1)])
+ return (torch.stack(inputs).mean(dim=0),)
+
+
+class TestCustomIsChanged:
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "image": ("IMAGE",),
+ },
+ "optional": {
+ "should_change": ("BOOL", {"default": False}),
+ },
+ }
+
+ RETURN_TYPES = ("IMAGE",)
+ FUNCTION = "custom_is_changed"
+
+ CATEGORY = "Testing/Nodes"
+
+ def custom_is_changed(self, image, should_change=False):
+ return (image,)
+
+ @classmethod
+ def IS_CHANGED(cls, should_change=False, *args, **kwargs):
+ if should_change:
+ return float("NaN")
+ else:
+ return False
+
+class TestIsChangedWithConstants:
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "image": ("IMAGE",),
+ "value": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0}),
+ },
+ }
+
+ RETURN_TYPES = ("IMAGE",)
+ FUNCTION = "custom_is_changed"
+
+ CATEGORY = "Testing/Nodes"
+
+ def custom_is_changed(self, image, value):
+ return (image * value,)
+
+ @classmethod
+ def IS_CHANGED(cls, image, value):
+ if image is None:
+ return value
+ else:
+ return image.mean().item() * value
+
+class TestCustomValidation1:
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "input1": ("IMAGE,FLOAT",),
+ "input2": ("IMAGE,FLOAT",),
+ },
+ }
+
+ RETURN_TYPES = ("IMAGE",)
+ FUNCTION = "custom_validation1"
+
+ CATEGORY = "Testing/Nodes"
+
+ def custom_validation1(self, input1, input2):
+ if isinstance(input1, float) and isinstance(input2, float):
+ result = torch.ones([1, 512, 512, 3]) * input1 * input2
+ else:
+ result = input1 * input2
+ return (result,)
+
+ @classmethod
+ def VALIDATE_INPUTS(cls, input1=None, input2=None):
+ if input1 is not None:
+ if not isinstance(input1, (torch.Tensor, float)):
+ return f"Invalid type of input1: {type(input1)}"
+ if input2 is not None:
+ if not isinstance(input2, (torch.Tensor, float)):
+ return f"Invalid type of input2: {type(input2)}"
+
+ return True
+
+class TestCustomValidation2:
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "input1": ("IMAGE,FLOAT",),
+ "input2": ("IMAGE,FLOAT",),
+ },
+ }
+
+ RETURN_TYPES = ("IMAGE",)
+ FUNCTION = "custom_validation2"
+
+ CATEGORY = "Testing/Nodes"
+
+ def custom_validation2(self, input1, input2):
+ if isinstance(input1, float) and isinstance(input2, float):
+ result = torch.ones([1, 512, 512, 3]) * input1 * input2
+ else:
+ result = input1 * input2
+ return (result,)
+
+ @classmethod
+ def VALIDATE_INPUTS(cls, input_types, input1=None, input2=None):
+ if input1 is not None:
+ if not isinstance(input1, (torch.Tensor, float)):
+ return f"Invalid type of input1: {type(input1)}"
+ if input2 is not None:
+ if not isinstance(input2, (torch.Tensor, float)):
+ return f"Invalid type of input2: {type(input2)}"
+
+ if 'input1' in input_types:
+ if input_types['input1'] not in ["IMAGE", "FLOAT"]:
+ return f"Invalid type of input1: {input_types['input1']}"
+ if 'input2' in input_types:
+ if input_types['input2'] not in ["IMAGE", "FLOAT"]:
+ return f"Invalid type of input2: {input_types['input2']}"
+
+ return True
+
+@VariantSupport()
+class TestCustomValidation3:
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "input1": ("IMAGE,FLOAT",),
+ "input2": ("IMAGE,FLOAT",),
+ },
+ }
+
+ RETURN_TYPES = ("IMAGE",)
+ FUNCTION = "custom_validation3"
+
+ CATEGORY = "Testing/Nodes"
+
+ def custom_validation3(self, input1, input2):
+ if isinstance(input1, float) and isinstance(input2, float):
+ result = torch.ones([1, 512, 512, 3]) * input1 * input2
+ else:
+ result = input1 * input2
+ return (result,)
+
+class TestCustomValidation4:
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "input1": ("FLOAT",),
+ "input2": ("FLOAT",),
+ },
+ }
+
+ RETURN_TYPES = ("IMAGE",)
+ FUNCTION = "custom_validation4"
+
+ CATEGORY = "Testing/Nodes"
+
+ def custom_validation4(self, input1, input2):
+ result = torch.ones([1, 512, 512, 3]) * input1 * input2
+ return (result,)
+
+ @classmethod
+ def VALIDATE_INPUTS(cls, input1, input2):
+ if input1 is not None:
+ if not isinstance(input1, float):
+ return f"Invalid type of input1: {type(input1)}"
+ if input2 is not None:
+ if not isinstance(input2, float):
+ return f"Invalid type of input2: {type(input2)}"
+
+ return True
+
+class TestCustomValidation5:
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "input1": ("FLOAT", {"min": 0.0, "max": 1.0}),
+ "input2": ("FLOAT", {"min": 0.0, "max": 1.0}),
+ },
+ }
+
+ RETURN_TYPES = ("IMAGE",)
+ FUNCTION = "custom_validation5"
+
+ CATEGORY = "Testing/Nodes"
+
+ def custom_validation5(self, input1, input2):
+ value = input1 * input2
+ return (torch.ones([1, 512, 512, 3]) * value,)
+
+ @classmethod
+ def VALIDATE_INPUTS(cls, **kwargs):
+ if kwargs['input2'] == 7.0:
+ return "7s are not allowed. I've never liked 7s."
+ return True
+
+class TestDynamicDependencyCycle:
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "input1": ("IMAGE",),
+ "input2": ("IMAGE",),
+ },
+ }
+
+ RETURN_TYPES = ("IMAGE",)
+ FUNCTION = "dynamic_dependency_cycle"
+
+ CATEGORY = "Testing/Nodes"
+
+ def dynamic_dependency_cycle(self, input1, input2):
+ g = GraphBuilder()
+ mask = g.node("StubMask", value=0.5, height=512, width=512, batch_size=1)
+ mix1 = g.node("TestLazyMixImages", image1=input1, mask=mask.out(0))
+ mix2 = g.node("TestLazyMixImages", image1=mix1.out(0), image2=input2, mask=mask.out(0))
+
+ # Create the cyle
+ mix1.set_input("image2", mix2.out(0))
+
+ return {
+ "result": (mix2.out(0),),
+ "expand": g.finalize(),
+ }
+
+class TestMixedExpansionReturns:
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "input1": ("FLOAT",),
+ },
+ }
+
+ RETURN_TYPES = ("IMAGE","IMAGE")
+ FUNCTION = "mixed_expansion_returns"
+
+ CATEGORY = "Testing/Nodes"
+
+ def mixed_expansion_returns(self, input1):
+ white_image = torch.ones([1, 512, 512, 3])
+ if input1 <= 0.1:
+ return (torch.ones([1, 512, 512, 3]) * 0.1, white_image)
+ elif input1 <= 0.2:
+ return {
+ "result": (torch.ones([1, 512, 512, 3]) * 0.2, white_image),
+ }
+ else:
+ g = GraphBuilder()
+ mask = g.node("StubMask", value=0.3, height=512, width=512, batch_size=1)
+ black = g.node("StubImage", content="BLACK", height=512, width=512, batch_size=1)
+ white = g.node("StubImage", content="WHITE", height=512, width=512, batch_size=1)
+ mix = g.node("TestLazyMixImages", image1=black.out(0), image2=white.out(0), mask=mask.out(0))
+ return {
+ "result": (mix.out(0), white_image),
+ "expand": g.finalize(),
+ }
+
+TEST_NODE_CLASS_MAPPINGS = {
+ "TestLazyMixImages": TestLazyMixImages,
+ "TestVariadicAverage": TestVariadicAverage,
+ "TestCustomIsChanged": TestCustomIsChanged,
+ "TestIsChangedWithConstants": TestIsChangedWithConstants,
+ "TestCustomValidation1": TestCustomValidation1,
+ "TestCustomValidation2": TestCustomValidation2,
+ "TestCustomValidation3": TestCustomValidation3,
+ "TestCustomValidation4": TestCustomValidation4,
+ "TestCustomValidation5": TestCustomValidation5,
+ "TestDynamicDependencyCycle": TestDynamicDependencyCycle,
+ "TestMixedExpansionReturns": TestMixedExpansionReturns,
+}
+
+TEST_NODE_DISPLAY_NAME_MAPPINGS = {
+ "TestLazyMixImages": "Lazy Mix Images",
+ "TestVariadicAverage": "Variadic Average",
+ "TestCustomIsChanged": "Custom IsChanged",
+ "TestIsChangedWithConstants": "IsChanged With Constants",
+ "TestCustomValidation1": "Custom Validation 1",
+ "TestCustomValidation2": "Custom Validation 2",
+ "TestCustomValidation3": "Custom Validation 3",
+ "TestCustomValidation4": "Custom Validation 4",
+ "TestCustomValidation5": "Custom Validation 5",
+ "TestDynamicDependencyCycle": "Dynamic Dependency Cycle",
+ "TestMixedExpansionReturns": "Mixed Expansion Returns",
+}
diff --git a/tests/inference/testing_nodes/testing-pack/stubs.py b/tests/inference/testing_nodes/testing-pack/stubs.py
new file mode 100644
index 000000000..a1df87529
--- /dev/null
+++ b/tests/inference/testing_nodes/testing-pack/stubs.py
@@ -0,0 +1,129 @@
+import torch
+
+class StubImage:
+ def __init__(self):
+ pass
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "content": (['WHITE', 'BLACK', 'NOISE'],),
+ "height": ("INT", {"default": 512, "min": 1, "max": 1024 ** 3, "step": 1}),
+ "width": ("INT", {"default": 512, "min": 1, "max": 4096 ** 3, "step": 1}),
+ "batch_size": ("INT", {"default": 1, "min": 1, "max": 1024 ** 3, "step": 1}),
+ },
+ }
+
+ RETURN_TYPES = ("IMAGE",)
+ FUNCTION = "stub_image"
+
+ CATEGORY = "Testing/Stub Nodes"
+
+ def stub_image(self, content, height, width, batch_size):
+ if content == "WHITE":
+ return (torch.ones(batch_size, height, width, 3),)
+ elif content == "BLACK":
+ return (torch.zeros(batch_size, height, width, 3),)
+ elif content == "NOISE":
+ return (torch.rand(batch_size, height, width, 3),)
+
+class StubConstantImage:
+ def __init__(self):
+ pass
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "value": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 1.0, "step": 0.01}),
+ "height": ("INT", {"default": 512, "min": 1, "max": 1024 ** 3, "step": 1}),
+ "width": ("INT", {"default": 512, "min": 1, "max": 4096 ** 3, "step": 1}),
+ "batch_size": ("INT", {"default": 1, "min": 1, "max": 1024 ** 3, "step": 1}),
+ },
+ }
+
+ RETURN_TYPES = ("IMAGE",)
+ FUNCTION = "stub_constant_image"
+
+ CATEGORY = "Testing/Stub Nodes"
+
+ def stub_constant_image(self, value, height, width, batch_size):
+ return (torch.ones(batch_size, height, width, 3) * value,)
+
+class StubMask:
+ def __init__(self):
+ pass
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "value": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 1.0, "step": 0.01}),
+ "height": ("INT", {"default": 512, "min": 1, "max": 1024 ** 3, "step": 1}),
+ "width": ("INT", {"default": 512, "min": 1, "max": 4096 ** 3, "step": 1}),
+ "batch_size": ("INT", {"default": 1, "min": 1, "max": 1024 ** 3, "step": 1}),
+ },
+ }
+
+ RETURN_TYPES = ("MASK",)
+ FUNCTION = "stub_mask"
+
+ CATEGORY = "Testing/Stub Nodes"
+
+ def stub_mask(self, value, height, width, batch_size):
+ return (torch.ones(batch_size, height, width) * value,)
+
+class StubInt:
+ def __init__(self):
+ pass
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "value": ("INT", {"default": 0, "min": -0xffffffff, "max": 0xffffffff, "step": 1}),
+ },
+ }
+
+ RETURN_TYPES = ("INT",)
+ FUNCTION = "stub_int"
+
+ CATEGORY = "Testing/Stub Nodes"
+
+ def stub_int(self, value):
+ return (value,)
+
+class StubFloat:
+ def __init__(self):
+ pass
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "value": ("FLOAT", {"default": 0.0, "min": -1.0e38, "max": 1.0e38, "step": 0.01}),
+ },
+ }
+
+ RETURN_TYPES = ("FLOAT",)
+ FUNCTION = "stub_float"
+
+ CATEGORY = "Testing/Stub Nodes"
+
+ def stub_float(self, value):
+ return (value,)
+
+TEST_STUB_NODE_CLASS_MAPPINGS = {
+ "StubImage": StubImage,
+ "StubConstantImage": StubConstantImage,
+ "StubMask": StubMask,
+ "StubInt": StubInt,
+ "StubFloat": StubFloat,
+}
+TEST_STUB_NODE_DISPLAY_NAME_MAPPINGS = {
+ "StubImage": "Stub Image",
+ "StubConstantImage": "Stub Constant Image",
+ "StubMask": "Stub Mask",
+ "StubInt": "Stub Int",
+ "StubFloat": "Stub Float",
+}
diff --git a/tests/inference/testing_nodes/testing-pack/tools.py b/tests/inference/testing_nodes/testing-pack/tools.py
new file mode 100644
index 000000000..34b28c0eb
--- /dev/null
+++ b/tests/inference/testing_nodes/testing-pack/tools.py
@@ -0,0 +1,53 @@
+
+def MakeSmartType(t):
+ if isinstance(t, str):
+ return SmartType(t)
+ return t
+
+class SmartType(str):
+ def __ne__(self, other):
+ if self == "*" or other == "*":
+ return False
+ selfset = set(self.split(','))
+ otherset = set(other.split(','))
+ return not selfset.issubset(otherset)
+
+def VariantSupport():
+ def decorator(cls):
+ if hasattr(cls, "INPUT_TYPES"):
+ old_input_types = getattr(cls, "INPUT_TYPES")
+ def new_input_types(*args, **kwargs):
+ types = old_input_types(*args, **kwargs)
+ for category in ["required", "optional"]:
+ if category not in types:
+ continue
+ for key, value in types[category].items():
+ if isinstance(value, tuple):
+ types[category][key] = (MakeSmartType(value[0]),) + value[1:]
+ return types
+ setattr(cls, "INPUT_TYPES", new_input_types)
+ if hasattr(cls, "RETURN_TYPES"):
+ old_return_types = cls.RETURN_TYPES
+ setattr(cls, "RETURN_TYPES", tuple(MakeSmartType(x) for x in old_return_types))
+ if hasattr(cls, "VALIDATE_INPUTS"):
+ # Reflection is used to determine what the function signature is, so we can't just change the function signature
+ raise NotImplementedError("VariantSupport does not support VALIDATE_INPUTS yet")
+ else:
+ def validate_inputs(input_types):
+ inputs = cls.INPUT_TYPES()
+ for key, value in input_types.items():
+ if isinstance(value, SmartType):
+ continue
+ if "required" in inputs and key in inputs["required"]:
+ expected_type = inputs["required"][key][0]
+ elif "optional" in inputs and key in inputs["optional"]:
+ expected_type = inputs["optional"][key][0]
+ else:
+ expected_type = None
+ if expected_type is not None and MakeSmartType(value) != expected_type:
+ return f"Invalid type of {key}: {value} (expected {expected_type})"
+ return True
+ setattr(cls, "VALIDATE_INPUTS", validate_inputs)
+ return cls
+ return decorator
+
diff --git a/tests/inference/testing_nodes/testing-pack/util.py b/tests/inference/testing_nodes/testing-pack/util.py
new file mode 100644
index 000000000..ca116c16e
--- /dev/null
+++ b/tests/inference/testing_nodes/testing-pack/util.py
@@ -0,0 +1,364 @@
+from comfy_execution.graph_utils import GraphBuilder
+from .tools import VariantSupport
+
+@VariantSupport()
+class TestAccumulateNode:
+ def __init__(self):
+ pass
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "to_add": ("*",),
+ },
+ "optional": {
+ "accumulation": ("ACCUMULATION",),
+ },
+ }
+
+ RETURN_TYPES = ("ACCUMULATION",)
+ FUNCTION = "accumulate"
+
+ CATEGORY = "Testing/Lists"
+
+ def accumulate(self, to_add, accumulation = None):
+ if accumulation is None:
+ value = [to_add]
+ else:
+ value = accumulation["accum"] + [to_add]
+ return ({"accum": value},)
+
+@VariantSupport()
+class TestAccumulationHeadNode:
+ def __init__(self):
+ pass
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "accumulation": ("ACCUMULATION",),
+ },
+ }
+
+ RETURN_TYPES = ("ACCUMULATION", "*",)
+ FUNCTION = "accumulation_head"
+
+ CATEGORY = "Testing/Lists"
+
+ def accumulation_head(self, accumulation):
+ accum = accumulation["accum"]
+ if len(accum) == 0:
+ return (accumulation, None)
+ else:
+ return ({"accum": accum[1:]}, accum[0])
+
+class TestAccumulationTailNode:
+ def __init__(self):
+ pass
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "accumulation": ("ACCUMULATION",),
+ },
+ }
+
+ RETURN_TYPES = ("ACCUMULATION", "*",)
+ FUNCTION = "accumulation_tail"
+
+ CATEGORY = "Testing/Lists"
+
+ def accumulation_tail(self, accumulation):
+ accum = accumulation["accum"]
+ if len(accum) == 0:
+ return (None, accumulation)
+ else:
+ return ({"accum": accum[:-1]}, accum[-1])
+
+@VariantSupport()
+class TestAccumulationToListNode:
+ def __init__(self):
+ pass
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "accumulation": ("ACCUMULATION",),
+ },
+ }
+
+ RETURN_TYPES = ("*",)
+ OUTPUT_IS_LIST = (True,)
+
+ FUNCTION = "accumulation_to_list"
+
+ CATEGORY = "Testing/Lists"
+
+ def accumulation_to_list(self, accumulation):
+ return (accumulation["accum"],)
+
+@VariantSupport()
+class TestListToAccumulationNode:
+ def __init__(self):
+ pass
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "list": ("*",),
+ },
+ }
+
+ RETURN_TYPES = ("ACCUMULATION",)
+ INPUT_IS_LIST = (True,)
+
+ FUNCTION = "list_to_accumulation"
+
+ CATEGORY = "Testing/Lists"
+
+ def list_to_accumulation(self, list):
+ return ({"accum": list},)
+
+@VariantSupport()
+class TestAccumulationGetLengthNode:
+ def __init__(self):
+ pass
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "accumulation": ("ACCUMULATION",),
+ },
+ }
+
+ RETURN_TYPES = ("INT",)
+
+ FUNCTION = "accumlength"
+
+ CATEGORY = "Testing/Lists"
+
+ def accumlength(self, accumulation):
+ return (len(accumulation['accum']),)
+
+@VariantSupport()
+class TestAccumulationGetItemNode:
+ def __init__(self):
+ pass
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "accumulation": ("ACCUMULATION",),
+ "index": ("INT", {"default":0, "step":1})
+ },
+ }
+
+ RETURN_TYPES = ("*",)
+
+ FUNCTION = "get_item"
+
+ CATEGORY = "Testing/Lists"
+
+ def get_item(self, accumulation, index):
+ return (accumulation['accum'][index],)
+
+@VariantSupport()
+class TestAccumulationSetItemNode:
+ def __init__(self):
+ pass
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "accumulation": ("ACCUMULATION",),
+ "index": ("INT", {"default":0, "step":1}),
+ "value": ("*",),
+ },
+ }
+
+ RETURN_TYPES = ("ACCUMULATION",)
+
+ FUNCTION = "set_item"
+
+ CATEGORY = "Testing/Lists"
+
+ def set_item(self, accumulation, index, value):
+ new_accum = accumulation['accum'][:]
+ new_accum[index] = value
+ return ({"accum": new_accum},)
+
+class TestIntMathOperation:
+ def __init__(self):
+ pass
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "a": ("INT", {"default": 0, "min": -0xffffffffffffffff, "max": 0xffffffffffffffff, "step": 1}),
+ "b": ("INT", {"default": 0, "min": -0xffffffffffffffff, "max": 0xffffffffffffffff, "step": 1}),
+ "operation": (["add", "subtract", "multiply", "divide", "modulo", "power"],),
+ },
+ }
+
+ RETURN_TYPES = ("INT",)
+ FUNCTION = "int_math_operation"
+
+ CATEGORY = "Testing/Logic"
+
+ def int_math_operation(self, a, b, operation):
+ if operation == "add":
+ return (a + b,)
+ elif operation == "subtract":
+ return (a - b,)
+ elif operation == "multiply":
+ return (a * b,)
+ elif operation == "divide":
+ return (a // b,)
+ elif operation == "modulo":
+ return (a % b,)
+ elif operation == "power":
+ return (a ** b,)
+
+
+from .flow_control import NUM_FLOW_SOCKETS
+@VariantSupport()
+class TestForLoopOpen:
+ def __init__(self):
+ pass
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "remaining": ("INT", {"default": 1, "min": 0, "max": 100000, "step": 1}),
+ },
+ "optional": {
+ f"initial_value{i}": ("*",) for i in range(1, NUM_FLOW_SOCKETS)
+ },
+ "hidden": {
+ "initial_value0": ("*",)
+ }
+ }
+
+ RETURN_TYPES = tuple(["FLOW_CONTROL", "INT",] + ["*"] * (NUM_FLOW_SOCKETS-1))
+ RETURN_NAMES = tuple(["flow_control", "remaining"] + [f"value{i}" for i in range(1, NUM_FLOW_SOCKETS)])
+ FUNCTION = "for_loop_open"
+
+ CATEGORY = "Testing/Flow"
+
+ def for_loop_open(self, remaining, **kwargs):
+ graph = GraphBuilder()
+ if "initial_value0" in kwargs:
+ remaining = kwargs["initial_value0"]
+ while_open = graph.node("TestWhileLoopOpen", condition=remaining, initial_value0=remaining, **{(f"initial_value{i}"): kwargs.get(f"initial_value{i}", None) for i in range(1, NUM_FLOW_SOCKETS)})
+ outputs = [kwargs.get(f"initial_value{i}", None) for i in range(1, NUM_FLOW_SOCKETS)]
+ return {
+ "result": tuple(["stub", remaining] + outputs),
+ "expand": graph.finalize(),
+ }
+
+@VariantSupport()
+class TestForLoopClose:
+ def __init__(self):
+ pass
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "flow_control": ("FLOW_CONTROL", {"rawLink": True}),
+ },
+ "optional": {
+ f"initial_value{i}": ("*",{"rawLink": True}) for i in range(1, NUM_FLOW_SOCKETS)
+ },
+ }
+
+ RETURN_TYPES = tuple(["*"] * (NUM_FLOW_SOCKETS-1))
+ RETURN_NAMES = tuple([f"value{i}" for i in range(1, NUM_FLOW_SOCKETS)])
+ FUNCTION = "for_loop_close"
+
+ CATEGORY = "Testing/Flow"
+
+ def for_loop_close(self, flow_control, **kwargs):
+ graph = GraphBuilder()
+ while_open = flow_control[0]
+ sub = graph.node("TestIntMathOperation", operation="subtract", a=[while_open,1], b=1)
+ cond = graph.node("TestToBoolNode", value=sub.out(0))
+ input_values = {f"initial_value{i}": kwargs.get(f"initial_value{i}", None) for i in range(1, NUM_FLOW_SOCKETS)}
+ while_close = graph.node("TestWhileLoopClose",
+ flow_control=flow_control,
+ condition=cond.out(0),
+ initial_value0=sub.out(0),
+ **input_values)
+ return {
+ "result": tuple([while_close.out(i) for i in range(1, NUM_FLOW_SOCKETS)]),
+ "expand": graph.finalize(),
+ }
+
+NUM_LIST_SOCKETS = 10
+@VariantSupport()
+class TestMakeListNode:
+ def __init__(self):
+ pass
+
+ @classmethod
+ def INPUT_TYPES(cls):
+ return {
+ "required": {
+ "value1": ("*",),
+ },
+ "optional": {
+ f"value{i}": ("*",) for i in range(1, NUM_LIST_SOCKETS)
+ },
+ }
+
+ RETURN_TYPES = ("*",)
+ FUNCTION = "make_list"
+ OUTPUT_IS_LIST = (True,)
+
+ CATEGORY = "Testing/Lists"
+
+ def make_list(self, **kwargs):
+ result = []
+ for i in range(NUM_LIST_SOCKETS):
+ if f"value{i}" in kwargs:
+ result.append(kwargs[f"value{i}"])
+ return (result,)
+
+UTILITY_NODE_CLASS_MAPPINGS = {
+ "TestAccumulateNode": TestAccumulateNode,
+ "TestAccumulationHeadNode": TestAccumulationHeadNode,
+ "TestAccumulationTailNode": TestAccumulationTailNode,
+ "TestAccumulationToListNode": TestAccumulationToListNode,
+ "TestListToAccumulationNode": TestListToAccumulationNode,
+ "TestAccumulationGetLengthNode": TestAccumulationGetLengthNode,
+ "TestAccumulationGetItemNode": TestAccumulationGetItemNode,
+ "TestAccumulationSetItemNode": TestAccumulationSetItemNode,
+ "TestForLoopOpen": TestForLoopOpen,
+ "TestForLoopClose": TestForLoopClose,
+ "TestIntMathOperation": TestIntMathOperation,
+ "TestMakeListNode": TestMakeListNode,
+}
+UTILITY_NODE_DISPLAY_NAME_MAPPINGS = {
+ "TestAccumulateNode": "Accumulate",
+ "TestAccumulationHeadNode": "Accumulation Head",
+ "TestAccumulationTailNode": "Accumulation Tail",
+ "TestAccumulationToListNode": "Accumulation to List",
+ "TestListToAccumulationNode": "List to Accumulation",
+ "TestAccumulationGetLengthNode": "Accumulation Get Length",
+ "TestAccumulationGetItemNode": "Accumulation Get Item",
+ "TestAccumulationSetItemNode": "Accumulation Set Item",
+ "TestForLoopOpen": "For Loop Open",
+ "TestForLoopClose": "For Loop Close",
+ "TestIntMathOperation": "Int Math Operation",
+ "TestMakeListNode": "Make List",
+}
diff --git a/utils/__init__.py b/utils/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/utils/extra_config.py b/utils/extra_config.py
new file mode 100644
index 000000000..908765902
--- /dev/null
+++ b/utils/extra_config.py
@@ -0,0 +1,28 @@
+import os
+import yaml
+import folder_paths
+import logging
+
+def load_extra_path_config(yaml_path):
+ with open(yaml_path, 'r') as stream:
+ config = yaml.safe_load(stream)
+ for c in config:
+ conf = config[c]
+ if conf is None:
+ continue
+ base_path = None
+ if "base_path" in conf:
+ base_path = conf.pop("base_path")
+ base_path = os.path.expandvars(os.path.expanduser(base_path))
+ is_default = False
+ if "is_default" in conf:
+ is_default = conf.pop("is_default")
+ for x in conf:
+ for y in conf[x].split("\n"):
+ if len(y) == 0:
+ continue
+ full_path = y
+ if base_path is not None:
+ full_path = os.path.join(base_path, full_path)
+ logging.info("Adding extra search path {} {}".format(x, full_path))
+ folder_paths.add_model_folder_path(x, full_path, is_default)
diff --git a/web/assets/CREDIT.txt b/web/assets/CREDIT.txt
new file mode 100644
index 000000000..b3a9bc906
--- /dev/null
+++ b/web/assets/CREDIT.txt
@@ -0,0 +1 @@
+Thanks to OpenArt (https://openart.ai) for providing the sorted-custom-node-map data, captured in September 2024.
\ No newline at end of file
diff --git a/web/assets/GraphView-DN9xGvF3.js b/web/assets/GraphView-DN9xGvF3.js
new file mode 100644
index 000000000..842727fc5
--- /dev/null
+++ b/web/assets/GraphView-DN9xGvF3.js
@@ -0,0 +1,3142 @@
+var __defProp = Object.defineProperty;
+var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
+import { d as defineComponent, u as useSettingStore, r as ref, a as useTitleEditorStore, b as useCanvasStore, w as watch, L as LGraphGroup, c as app, e as LGraphNode, o as onMounted, f as onUnmounted, g as openBlock, h as createElementBlock, i as createVNode, E as EditableText, n as normalizeStyle, j as createCommentVNode, k as LiteGraph, _ as _export_sfc, B as BaseStyle, s as script$5, l as resolveComponent, m as mergeProps, p as renderSlot, q as computed, t as resolveDirective, v as withDirectives, x as createBlock, y as withCtx, z as unref, A as createBaseVNode, C as normalizeClass, D as script$6, F as useDialogStore, S as SettingDialogHeader, G as SettingDialogContent, H as useWorkspaceStore, I as onBeforeUnmount, J as Fragment, K as renderList, T as Teleport, M as resolveDynamicComponent, N as pushScopeId, O as popScopeId, P as script$7, Q as getWidth, R as getHeight, U as getOuterWidth, V as getOuterHeight, W as getVNodeProp, X as isArray, Y as vShow, Z as isNotEmpty, $ as UniqueComponentId, a0 as ZIndex, a1 as resolveFieldData, a2 as focus, a3 as OverlayEventBus, a4 as isEmpty, a5 as addStyle, a6 as relativePosition, a7 as absolutePosition, a8 as ConnectedOverlayScrollHandler, a9 as isTouchDevice, aa as equals, ab as findLastIndex, ac as findSingle, ad as script$8, ae as script$9, af as script$a, ag as script$b, ah as script$c, ai as script$d, aj as Ripple, ak as toDisplayString, al as Transition, am as createSlots, an as createTextVNode, ao as useNodeFrequencyStore, ap as useNodeBookmarkStore, aq as highlightQuery, ar as script$e, as as formatNumberWithSuffix, at as NodeSourceType, au as useI18n, av as useNodeDefStore, aw as NodePreview, ax as NodeSearchFilter, ay as script$f, az as SearchFilterChip, aA as watchEffect, aB as toRaw, aC as LinkReleaseTriggerAction, aD as nextTick, aE as LGraph, aF as LLink, aG as DragAndScale, aH as LGraphCanvas, aI as ContextMenu, aJ as LGraphBadge$1, aK as dropTargetForElements, aL as ComfyNodeDefImpl } from "./index-Drc_oD2f.js";
+const _sfc_main$c = /* @__PURE__ */ defineComponent({
+ __name: "TitleEditor",
+ setup(__props) {
+ const settingStore = useSettingStore();
+ const showInput = ref(false);
+ const editedTitle = ref("");
+ const inputStyle = ref({
+ position: "fixed",
+ left: "0px",
+ top: "0px",
+ width: "200px",
+ height: "20px",
+ fontSize: "12px"
+ });
+ const titleEditorStore = useTitleEditorStore();
+ const canvasStore = useCanvasStore();
+ const previousCanvasDraggable = ref(true);
+ const onEdit = /* @__PURE__ */ __name((newValue) => {
+ if (titleEditorStore.titleEditorTarget && newValue.trim() !== "") {
+ titleEditorStore.titleEditorTarget.title = newValue.trim();
+ app.graph.setDirtyCanvas(true, true);
+ }
+ showInput.value = false;
+ titleEditorStore.titleEditorTarget = null;
+ canvasStore.canvas.allow_dragcanvas = previousCanvasDraggable.value;
+ }, "onEdit");
+ watch(
+ () => titleEditorStore.titleEditorTarget,
+ (target) => {
+ if (target === null) {
+ return;
+ }
+ editedTitle.value = target.title;
+ showInput.value = true;
+ previousCanvasDraggable.value = canvasStore.canvas.allow_dragcanvas;
+ canvasStore.canvas.allow_dragcanvas = false;
+ if (target instanceof LGraphGroup) {
+ const group = target;
+ const [x, y] = group.pos;
+ const [w, h] = group.size;
+ const [left, top] = app.canvasPosToClientPos([x, y]);
+ inputStyle.value.left = `${left}px`;
+ inputStyle.value.top = `${top}px`;
+ const width = w * app.canvas.ds.scale;
+ const height = group.titleHeight * app.canvas.ds.scale;
+ inputStyle.value.width = `${width}px`;
+ inputStyle.value.height = `${height}px`;
+ const fontSize = group.font_size * app.canvas.ds.scale;
+ inputStyle.value.fontSize = `${fontSize}px`;
+ } else if (target instanceof LGraphNode) {
+ const node = target;
+ const [x, y] = node.getBounding();
+ const canvasWidth = node.width;
+ const canvasHeight = LiteGraph.NODE_TITLE_HEIGHT;
+ const [left, top] = app.canvasPosToClientPos([x, y]);
+ inputStyle.value.left = `${left}px`;
+ inputStyle.value.top = `${top}px`;
+ const width = canvasWidth * app.canvas.ds.scale;
+ const height = canvasHeight * app.canvas.ds.scale;
+ inputStyle.value.width = `${width}px`;
+ inputStyle.value.height = `${height}px`;
+ const fontSize = 12 * app.canvas.ds.scale;
+ inputStyle.value.fontSize = `${fontSize}px`;
+ }
+ }
+ );
+ const canvasEventHandler = /* @__PURE__ */ __name((event) => {
+ if (!settingStore.get("Comfy.Group.DoubleClickTitleToEdit")) {
+ return;
+ }
+ if (event.detail.subType === "group-double-click") {
+ const group = event.detail.group;
+ const [x, y] = group.pos;
+ const e = event.detail.originalEvent;
+ const relativeY = e.canvasY - y;
+ if (relativeY > group.titleHeight) {
+ return;
+ }
+ titleEditorStore.titleEditorTarget = group;
+ }
+ }, "canvasEventHandler");
+ const extension = {
+ name: "Comfy.NodeTitleEditor",
+ nodeCreated(node) {
+ const originalCallback = node.onNodeTitleDblClick;
+ node.onNodeTitleDblClick = function(e, ...args) {
+ if (!settingStore.get("Comfy.Node.DoubleClickTitleToEdit")) {
+ return;
+ }
+ titleEditorStore.titleEditorTarget = this;
+ if (typeof originalCallback === "function") {
+ originalCallback.call(this, e, ...args);
+ }
+ };
+ }
+ };
+ onMounted(() => {
+ document.addEventListener("litegraph:canvas", canvasEventHandler);
+ app.registerExtension(extension);
+ });
+ onUnmounted(() => {
+ document.removeEventListener("litegraph:canvas", canvasEventHandler);
+ });
+ return (_ctx, _cache) => {
+ return showInput.value ? (openBlock(), createElementBlock("div", {
+ key: 0,
+ class: "group-title-editor node-title-editor",
+ style: normalizeStyle(inputStyle.value)
+ }, [
+ createVNode(EditableText, {
+ isEditing: showInput.value,
+ modelValue: editedTitle.value,
+ onEdit
+ }, null, 8, ["isEditing", "modelValue"])
+ ], 4)) : createCommentVNode("", true);
+ };
+ }
+});
+const TitleEditor = /* @__PURE__ */ _export_sfc(_sfc_main$c, [["__scopeId", "data-v-fc3f26e3"]]);
+var theme$2 = /* @__PURE__ */ __name(function theme(_ref) {
+ var dt = _ref.dt;
+ return "\n.p-overlaybadge {\n position: relative;\n}\n\n.p-overlaybadge .p-badge {\n position: absolute;\n top: 0;\n right: 0;\n transform: translate(50%, -50%);\n transform-origin: 100% 0;\n margin: 0;\n outline-width: ".concat(dt("overlaybadge.outline.width"), ";\n outline-style: solid;\n outline-color: ").concat(dt("overlaybadge.outline.color"), ";\n}\n");
+}, "theme");
+var classes$3 = {
+ root: "p-overlaybadge"
+};
+var OverlayBadgeStyle = BaseStyle.extend({
+ name: "overlaybadge",
+ theme: theme$2,
+ classes: classes$3
+});
+var script$1$3 = {
+ name: "OverlayBadge",
+ "extends": script$5,
+ style: OverlayBadgeStyle,
+ provide: /* @__PURE__ */ __name(function provide() {
+ return {
+ $pcOverlayBadge: this,
+ $parentInstance: this
+ };
+ }, "provide")
+};
+var script$4 = {
+ name: "OverlayBadge",
+ "extends": script$1$3,
+ inheritAttrs: false,
+ components: {
+ Badge: script$5
+ }
+};
+function render$3(_ctx, _cache, $props, $setup, $data, $options) {
+ var _component_Badge = resolveComponent("Badge");
+ return openBlock(), createElementBlock("div", mergeProps({
+ "class": _ctx.cx("root")
+ }, _ctx.ptmi("root")), [renderSlot(_ctx.$slots, "default"), createVNode(_component_Badge, mergeProps(_ctx.$props, {
+ pt: _ctx.ptm("pcBadge")
+ }), null, 16, ["pt"])], 16);
+}
+__name(render$3, "render$3");
+script$4.render = render$3;
+const _sfc_main$b = /* @__PURE__ */ defineComponent({
+ __name: "SidebarIcon",
+ props: {
+ icon: String,
+ selected: Boolean,
+ tooltip: {
+ type: String,
+ default: ""
+ },
+ class: {
+ type: String,
+ default: ""
+ },
+ iconBadge: {
+ type: [String, Function],
+ default: ""
+ }
+ },
+ emits: ["click"],
+ setup(__props, { emit: __emit }) {
+ const props = __props;
+ const emit = __emit;
+ const overlayValue = computed(
+ () => typeof props.iconBadge === "function" ? props.iconBadge() || "" : props.iconBadge
+ );
+ const shouldShowBadge = computed(() => !!overlayValue.value);
+ return (_ctx, _cache) => {
+ const _directive_tooltip = resolveDirective("tooltip");
+ return withDirectives((openBlock(), createBlock(unref(script$6), {
+ class: normalizeClass(props.class),
+ text: "",
+ pt: {
+ root: {
+ class: `side-bar-button ${props.selected ? "p-button-primary side-bar-button-selected" : "p-button-secondary"}`,
+ "aria-label": props.tooltip
+ }
+ },
+ onClick: _cache[0] || (_cache[0] = ($event) => emit("click", $event))
+ }, {
+ icon: withCtx(() => [
+ shouldShowBadge.value ? (openBlock(), createBlock(unref(script$4), {
+ key: 0,
+ value: overlayValue.value
+ }, {
+ default: withCtx(() => [
+ createBaseVNode("i", {
+ class: normalizeClass(props.icon + " side-bar-button-icon")
+ }, null, 2)
+ ]),
+ _: 1
+ }, 8, ["value"])) : (openBlock(), createElementBlock("i", {
+ key: 1,
+ class: normalizeClass(props.icon + " side-bar-button-icon")
+ }, null, 2))
+ ]),
+ _: 1
+ }, 8, ["class", "pt"])), [
+ [_directive_tooltip, { value: props.tooltip, showDelay: 300, hideDelay: 300 }]
+ ]);
+ };
+ }
+});
+const SidebarIcon = /* @__PURE__ */ _export_sfc(_sfc_main$b, [["__scopeId", "data-v-caa3ee9c"]]);
+const _sfc_main$a = /* @__PURE__ */ defineComponent({
+ __name: "SidebarThemeToggleIcon",
+ setup(__props) {
+ const previousDarkTheme = ref("dark");
+ const currentTheme = computed(() => useSettingStore().get("Comfy.ColorPalette"));
+ const isDarkMode = computed(() => currentTheme.value !== "light");
+ const icon = computed(() => isDarkMode.value ? "pi pi-moon" : "pi pi-sun");
+ const toggleTheme = /* @__PURE__ */ __name(() => {
+ if (isDarkMode.value) {
+ previousDarkTheme.value = currentTheme.value;
+ useSettingStore().set("Comfy.ColorPalette", "light");
+ } else {
+ useSettingStore().set("Comfy.ColorPalette", previousDarkTheme.value);
+ }
+ }, "toggleTheme");
+ return (_ctx, _cache) => {
+ return openBlock(), createBlock(SidebarIcon, {
+ icon: icon.value,
+ onClick: toggleTheme,
+ tooltip: _ctx.$t("sideToolbar.themeToggle"),
+ class: "comfy-vue-theme-toggle"
+ }, null, 8, ["icon", "tooltip"]);
+ };
+ }
+});
+const _sfc_main$9 = /* @__PURE__ */ defineComponent({
+ __name: "SidebarSettingsToggleIcon",
+ setup(__props) {
+ const dialogStore = useDialogStore();
+ const showSetting = /* @__PURE__ */ __name(() => {
+ dialogStore.showDialog({
+ headerComponent: SettingDialogHeader,
+ component: SettingDialogContent
+ });
+ }, "showSetting");
+ return (_ctx, _cache) => {
+ return openBlock(), createBlock(SidebarIcon, {
+ icon: "pi pi-cog",
+ onClick: showSetting,
+ tooltip: _ctx.$t("settings")
+ }, null, 8, ["tooltip"]);
+ };
+ }
+});
+const _withScopeId$3 = /* @__PURE__ */ __name((n) => (pushScopeId("data-v-ed7a1148"), n = n(), popScopeId(), n), "_withScopeId$3");
+const _hoisted_1$5 = { class: "side-tool-bar-end" };
+const _hoisted_2$4 = {
+ key: 0,
+ class: "sidebar-content-container"
+};
+const _sfc_main$8 = /* @__PURE__ */ defineComponent({
+ __name: "SideToolbar",
+ setup(__props) {
+ const workspaceStore = useWorkspaceStore();
+ const settingStore = useSettingStore();
+ const teleportTarget = computed(
+ () => settingStore.get("Comfy.Sidebar.Location") === "left" ? ".comfyui-body-left" : ".comfyui-body-right"
+ );
+ const isSmall = computed(
+ () => settingStore.get("Comfy.Sidebar.Size") === "small"
+ );
+ const tabs = computed(() => workspaceStore.getSidebarTabs());
+ const selectedTab = computed(() => {
+ const tabId = workspaceStore.activeSidebarTab;
+ return tabs.value.find((tab) => tab.id === tabId) || null;
+ });
+ const mountCustomTab = /* @__PURE__ */ __name((tab, el) => {
+ tab.render(el);
+ }, "mountCustomTab");
+ const onTabClick = /* @__PURE__ */ __name((item) => {
+ workspaceStore.updateActiveSidebarTab(
+ workspaceStore.activeSidebarTab === item.id ? null : item.id
+ );
+ }, "onTabClick");
+ onBeforeUnmount(() => {
+ tabs.value.forEach((tab) => {
+ if (tab.type === "custom" && tab.destroy) {
+ tab.destroy();
+ }
+ });
+ });
+ return (_ctx, _cache) => {
+ return openBlock(), createElementBlock(Fragment, null, [
+ (openBlock(), createBlock(Teleport, { to: teleportTarget.value }, [
+ createBaseVNode("nav", {
+ class: normalizeClass("side-tool-bar-container" + (isSmall.value ? " small-sidebar" : ""))
+ }, [
+ (openBlock(true), createElementBlock(Fragment, null, renderList(tabs.value, (tab) => {
+ return openBlock(), createBlock(SidebarIcon, {
+ key: tab.id,
+ icon: tab.icon,
+ iconBadge: tab.iconBadge,
+ tooltip: tab.tooltip,
+ selected: tab === selectedTab.value,
+ class: normalizeClass(tab.id + "-tab-button"),
+ onClick: /* @__PURE__ */ __name(($event) => onTabClick(tab), "onClick")
+ }, null, 8, ["icon", "iconBadge", "tooltip", "selected", "class", "onClick"]);
+ }), 128)),
+ createBaseVNode("div", _hoisted_1$5, [
+ createVNode(_sfc_main$a),
+ createVNode(_sfc_main$9)
+ ])
+ ], 2)
+ ], 8, ["to"])),
+ selectedTab.value ? (openBlock(), createElementBlock("div", _hoisted_2$4, [
+ selectedTab.value.type === "vue" ? (openBlock(), createBlock(resolveDynamicComponent(selectedTab.value.component), { key: 0 })) : (openBlock(), createElementBlock("div", {
+ key: 1,
+ ref: /* @__PURE__ */ __name((el) => {
+ if (el)
+ mountCustomTab(
+ selectedTab.value,
+ el
+ );
+ }, "ref")
+ }, null, 512))
+ ])) : createCommentVNode("", true)
+ ], 64);
+ };
+ }
+});
+const SideToolbar = /* @__PURE__ */ _export_sfc(_sfc_main$8, [["__scopeId", "data-v-ed7a1148"]]);
+var theme$1 = /* @__PURE__ */ __name(function theme2(_ref) {
+ var dt = _ref.dt;
+ 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");
+}, "theme");
+var classes$2 = {
+ root: /* @__PURE__ */ __name(function root(_ref2) {
+ var props = _ref2.props;
+ return ["p-splitter p-component", "p-splitter-" + props.layout];
+ }, "root"),
+ gutter: "p-splitter-gutter",
+ gutterHandle: "p-splitter-gutter-handle"
+};
+var inlineStyles$1 = {
+ root: /* @__PURE__ */ __name(function root2(_ref3) {
+ var props = _ref3.props;
+ return [{
+ display: "flex",
+ "flex-wrap": "nowrap"
+ }, props.layout === "vertical" ? {
+ "flex-direction": "column"
+ } : ""];
+ }, "root")
+};
+var SplitterStyle = BaseStyle.extend({
+ name: "splitter",
+ theme: theme$1,
+ classes: classes$2,
+ inlineStyles: inlineStyles$1
+});
+var script$1$2 = {
+ name: "BaseSplitter",
+ "extends": script$7,
+ props: {
+ layout: {
+ type: String,
+ "default": "horizontal"
+ },
+ gutterSize: {
+ type: Number,
+ "default": 4
+ },
+ stateKey: {
+ type: String,
+ "default": null
+ },
+ stateStorage: {
+ type: String,
+ "default": "session"
+ },
+ step: {
+ type: Number,
+ "default": 5
+ }
+ },
+ style: SplitterStyle,
+ provide: /* @__PURE__ */ __name(function provide2() {
+ return {
+ $pcSplitter: this,
+ $parentInstance: this
+ };
+ }, "provide")
+};
+function _toConsumableArray$1(r) {
+ return _arrayWithoutHoles$1(r) || _iterableToArray$1(r) || _unsupportedIterableToArray$1(r) || _nonIterableSpread$1();
+}
+__name(_toConsumableArray$1, "_toConsumableArray$1");
+function _nonIterableSpread$1() {
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
+}
+__name(_nonIterableSpread$1, "_nonIterableSpread$1");
+function _unsupportedIterableToArray$1(r, a) {
+ if (r) {
+ if ("string" == typeof r) return _arrayLikeToArray$1(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$1(r, a) : void 0;
+ }
+}
+__name(_unsupportedIterableToArray$1, "_unsupportedIterableToArray$1");
+function _iterableToArray$1(r) {
+ if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r);
+}
+__name(_iterableToArray$1, "_iterableToArray$1");
+function _arrayWithoutHoles$1(r) {
+ if (Array.isArray(r)) return _arrayLikeToArray$1(r);
+}
+__name(_arrayWithoutHoles$1, "_arrayWithoutHoles$1");
+function _arrayLikeToArray$1(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;
+}
+__name(_arrayLikeToArray$1, "_arrayLikeToArray$1");
+var script$3 = {
+ name: "Splitter",
+ "extends": script$1$2,
+ inheritAttrs: false,
+ emits: ["resizestart", "resizeend", "resize"],
+ dragging: false,
+ mouseMoveListener: null,
+ mouseUpListener: null,
+ touchMoveListener: null,
+ touchEndListener: null,
+ size: null,
+ gutterElement: null,
+ startPos: null,
+ prevPanelElement: null,
+ nextPanelElement: null,
+ nextPanelSize: null,
+ prevPanelSize: null,
+ panelSizes: null,
+ prevPanelIndex: null,
+ timer: null,
+ data: /* @__PURE__ */ __name(function data() {
+ return {
+ prevSize: null
+ };
+ }, "data"),
+ mounted: /* @__PURE__ */ __name(function mounted() {
+ var _this = this;
+ if (this.panels && this.panels.length) {
+ var initialized = false;
+ if (this.isStateful()) {
+ initialized = this.restoreState();
+ }
+ if (!initialized) {
+ var children = _toConsumableArray$1(this.$el.children).filter(function(child) {
+ return child.getAttribute("data-pc-name") === "splitterpanel";
+ });
+ var _panelSizes = [];
+ this.panels.map(function(panel, i) {
+ var panelInitialSize = panel.props && panel.props.size ? panel.props.size : null;
+ var panelSize = panelInitialSize || 100 / _this.panels.length;
+ _panelSizes[i] = panelSize;
+ children[i].style.flexBasis = "calc(" + panelSize + "% - " + (_this.panels.length - 1) * _this.gutterSize + "px)";
+ });
+ this.panelSizes = _panelSizes;
+ this.prevSize = parseFloat(_panelSizes[0]).toFixed(4);
+ }
+ }
+ }, "mounted"),
+ beforeUnmount: /* @__PURE__ */ __name(function beforeUnmount() {
+ this.clear();
+ this.unbindMouseListeners();
+ }, "beforeUnmount"),
+ methods: {
+ isSplitterPanel: /* @__PURE__ */ __name(function isSplitterPanel(child) {
+ return child.type.name === "SplitterPanel";
+ }, "isSplitterPanel"),
+ onResizeStart: /* @__PURE__ */ __name(function onResizeStart(event, index, isKeyDown) {
+ this.gutterElement = event.currentTarget || event.target.parentElement;
+ this.size = this.horizontal ? getWidth(this.$el) : getHeight(this.$el);
+ if (!isKeyDown) {
+ this.dragging = true;
+ this.startPos = this.layout === "horizontal" ? event.pageX || event.changedTouches[0].pageX : event.pageY || event.changedTouches[0].pageY;
+ }
+ this.prevPanelElement = this.gutterElement.previousElementSibling;
+ this.nextPanelElement = this.gutterElement.nextElementSibling;
+ if (isKeyDown) {
+ this.prevPanelSize = this.horizontal ? getOuterWidth(this.prevPanelElement, true) : getOuterHeight(this.prevPanelElement, true);
+ this.nextPanelSize = this.horizontal ? getOuterWidth(this.nextPanelElement, true) : getOuterHeight(this.nextPanelElement, true);
+ } else {
+ this.prevPanelSize = 100 * (this.horizontal ? getOuterWidth(this.prevPanelElement, true) : getOuterHeight(this.prevPanelElement, true)) / this.size;
+ this.nextPanelSize = 100 * (this.horizontal ? getOuterWidth(this.nextPanelElement, true) : getOuterHeight(this.nextPanelElement, true)) / this.size;
+ }
+ this.prevPanelIndex = index;
+ this.$emit("resizestart", {
+ originalEvent: event,
+ sizes: this.panelSizes
+ });
+ this.$refs.gutter[index].setAttribute("data-p-gutter-resizing", true);
+ this.$el.setAttribute("data-p-resizing", true);
+ }, "onResizeStart"),
+ onResize: /* @__PURE__ */ __name(function onResize(event, step, isKeyDown) {
+ var newPos, newPrevPanelSize, newNextPanelSize;
+ if (isKeyDown) {
+ if (this.horizontal) {
+ newPrevPanelSize = 100 * (this.prevPanelSize + step) / this.size;
+ newNextPanelSize = 100 * (this.nextPanelSize - step) / this.size;
+ } else {
+ newPrevPanelSize = 100 * (this.prevPanelSize - step) / this.size;
+ newNextPanelSize = 100 * (this.nextPanelSize + step) / this.size;
+ }
+ } else {
+ 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;
+ newPrevPanelSize = this.prevPanelSize + newPos;
+ newNextPanelSize = this.nextPanelSize - newPos;
+ }
+ if (this.validateResize(newPrevPanelSize, newNextPanelSize)) {
+ this.prevPanelElement.style.flexBasis = "calc(" + newPrevPanelSize + "% - " + (this.panels.length - 1) * this.gutterSize + "px)";
+ this.nextPanelElement.style.flexBasis = "calc(" + newNextPanelSize + "% - " + (this.panels.length - 1) * this.gutterSize + "px)";
+ this.panelSizes[this.prevPanelIndex] = newPrevPanelSize;
+ this.panelSizes[this.prevPanelIndex + 1] = newNextPanelSize;
+ this.prevSize = parseFloat(newPrevPanelSize).toFixed(4);
+ }
+ this.$emit("resize", {
+ originalEvent: event,
+ sizes: this.panelSizes
+ });
+ }, "onResize"),
+ onResizeEnd: /* @__PURE__ */ __name(function onResizeEnd(event) {
+ if (this.isStateful()) {
+ this.saveState();
+ }
+ this.$emit("resizeend", {
+ originalEvent: event,
+ sizes: this.panelSizes
+ });
+ this.$refs.gutter.forEach(function(gutter) {
+ return gutter.setAttribute("data-p-gutter-resizing", false);
+ });
+ this.$el.setAttribute("data-p-resizing", false);
+ this.clear();
+ }, "onResizeEnd"),
+ repeat: /* @__PURE__ */ __name(function repeat(event, index, step) {
+ this.onResizeStart(event, index, true);
+ this.onResize(event, step, true);
+ }, "repeat"),
+ setTimer: /* @__PURE__ */ __name(function setTimer(event, index, step) {
+ var _this2 = this;
+ if (!this.timer) {
+ this.timer = setInterval(function() {
+ _this2.repeat(event, index, step);
+ }, 40);
+ }
+ }, "setTimer"),
+ clearTimer: /* @__PURE__ */ __name(function clearTimer() {
+ if (this.timer) {
+ clearInterval(this.timer);
+ this.timer = null;
+ }
+ }, "clearTimer"),
+ onGutterKeyUp: /* @__PURE__ */ __name(function onGutterKeyUp() {
+ this.clearTimer();
+ this.onResizeEnd();
+ }, "onGutterKeyUp"),
+ onGutterKeyDown: /* @__PURE__ */ __name(function onGutterKeyDown(event, index) {
+ switch (event.code) {
+ case "ArrowLeft": {
+ if (this.layout === "horizontal") {
+ this.setTimer(event, index, this.step * -1);
+ }
+ event.preventDefault();
+ break;
+ }
+ case "ArrowRight": {
+ if (this.layout === "horizontal") {
+ this.setTimer(event, index, this.step);
+ }
+ event.preventDefault();
+ break;
+ }
+ case "ArrowDown": {
+ if (this.layout === "vertical") {
+ this.setTimer(event, index, this.step * -1);
+ }
+ event.preventDefault();
+ break;
+ }
+ case "ArrowUp": {
+ if (this.layout === "vertical") {
+ this.setTimer(event, index, this.step);
+ }
+ event.preventDefault();
+ break;
+ }
+ }
+ }, "onGutterKeyDown"),
+ onGutterMouseDown: /* @__PURE__ */ __name(function onGutterMouseDown(event, index) {
+ this.onResizeStart(event, index);
+ this.bindMouseListeners();
+ }, "onGutterMouseDown"),
+ onGutterTouchStart: /* @__PURE__ */ __name(function onGutterTouchStart(event, index) {
+ this.onResizeStart(event, index);
+ this.bindTouchListeners();
+ event.preventDefault();
+ }, "onGutterTouchStart"),
+ onGutterTouchMove: /* @__PURE__ */ __name(function onGutterTouchMove(event) {
+ this.onResize(event);
+ event.preventDefault();
+ }, "onGutterTouchMove"),
+ onGutterTouchEnd: /* @__PURE__ */ __name(function onGutterTouchEnd(event) {
+ this.onResizeEnd(event);
+ this.unbindTouchListeners();
+ event.preventDefault();
+ }, "onGutterTouchEnd"),
+ bindMouseListeners: /* @__PURE__ */ __name(function bindMouseListeners() {
+ var _this3 = this;
+ if (!this.mouseMoveListener) {
+ this.mouseMoveListener = function(event) {
+ return _this3.onResize(event);
+ };
+ document.addEventListener("mousemove", this.mouseMoveListener);
+ }
+ if (!this.mouseUpListener) {
+ this.mouseUpListener = function(event) {
+ _this3.onResizeEnd(event);
+ _this3.unbindMouseListeners();
+ };
+ document.addEventListener("mouseup", this.mouseUpListener);
+ }
+ }, "bindMouseListeners"),
+ bindTouchListeners: /* @__PURE__ */ __name(function bindTouchListeners() {
+ var _this4 = this;
+ if (!this.touchMoveListener) {
+ this.touchMoveListener = function(event) {
+ return _this4.onResize(event.changedTouches[0]);
+ };
+ document.addEventListener("touchmove", this.touchMoveListener);
+ }
+ if (!this.touchEndListener) {
+ this.touchEndListener = function(event) {
+ _this4.resizeEnd(event);
+ _this4.unbindTouchListeners();
+ };
+ document.addEventListener("touchend", this.touchEndListener);
+ }
+ }, "bindTouchListeners"),
+ validateResize: /* @__PURE__ */ __name(function validateResize(newPrevPanelSize, newNextPanelSize) {
+ if (newPrevPanelSize > 100 || newPrevPanelSize < 0) return false;
+ if (newNextPanelSize > 100 || newNextPanelSize < 0) return false;
+ var prevPanelMinSize = getVNodeProp(this.panels[this.prevPanelIndex], "minSize");
+ if (this.panels[this.prevPanelIndex].props && prevPanelMinSize && prevPanelMinSize > newPrevPanelSize) {
+ return false;
+ }
+ var newPanelMinSize = getVNodeProp(this.panels[this.prevPanelIndex + 1], "minSize");
+ if (this.panels[this.prevPanelIndex + 1].props && newPanelMinSize && newPanelMinSize > newNextPanelSize) {
+ return false;
+ }
+ return true;
+ }, "validateResize"),
+ unbindMouseListeners: /* @__PURE__ */ __name(function unbindMouseListeners() {
+ if (this.mouseMoveListener) {
+ document.removeEventListener("mousemove", this.mouseMoveListener);
+ this.mouseMoveListener = null;
+ }
+ if (this.mouseUpListener) {
+ document.removeEventListener("mouseup", this.mouseUpListener);
+ this.mouseUpListener = null;
+ }
+ }, "unbindMouseListeners"),
+ unbindTouchListeners: /* @__PURE__ */ __name(function unbindTouchListeners() {
+ if (this.touchMoveListener) {
+ document.removeEventListener("touchmove", this.touchMoveListener);
+ this.touchMoveListener = null;
+ }
+ if (this.touchEndListener) {
+ document.removeEventListener("touchend", this.touchEndListener);
+ this.touchEndListener = null;
+ }
+ }, "unbindTouchListeners"),
+ clear: /* @__PURE__ */ __name(function clear() {
+ this.dragging = false;
+ this.size = null;
+ this.startPos = null;
+ this.prevPanelElement = null;
+ this.nextPanelElement = null;
+ this.prevPanelSize = null;
+ this.nextPanelSize = null;
+ this.gutterElement = null;
+ this.prevPanelIndex = null;
+ }, "clear"),
+ isStateful: /* @__PURE__ */ __name(function isStateful() {
+ return this.stateKey != null;
+ }, "isStateful"),
+ getStorage: /* @__PURE__ */ __name(function getStorage() {
+ switch (this.stateStorage) {
+ case "local":
+ return window.localStorage;
+ case "session":
+ return window.sessionStorage;
+ default:
+ throw new Error(this.stateStorage + ' is not a valid value for the state storage, supported values are "local" and "session".');
+ }
+ }, "getStorage"),
+ saveState: /* @__PURE__ */ __name(function saveState() {
+ if (isArray(this.panelSizes)) {
+ this.getStorage().setItem(this.stateKey, JSON.stringify(this.panelSizes));
+ }
+ }, "saveState"),
+ restoreState: /* @__PURE__ */ __name(function restoreState() {
+ var _this5 = this;
+ var storage = this.getStorage();
+ var stateString = storage.getItem(this.stateKey);
+ if (stateString) {
+ this.panelSizes = JSON.parse(stateString);
+ var children = _toConsumableArray$1(this.$el.children).filter(function(child) {
+ return child.getAttribute("data-pc-name") === "splitterpanel";
+ });
+ children.forEach(function(child, i) {
+ child.style.flexBasis = "calc(" + _this5.panelSizes[i] + "% - " + (_this5.panels.length - 1) * _this5.gutterSize + "px)";
+ });
+ return true;
+ }
+ return false;
+ }, "restoreState")
+ },
+ computed: {
+ panels: /* @__PURE__ */ __name(function panels() {
+ var _this6 = this;
+ var panels2 = [];
+ this.$slots["default"]().forEach(function(child) {
+ if (_this6.isSplitterPanel(child)) {
+ panels2.push(child);
+ } else if (child.children instanceof Array) {
+ child.children.forEach(function(nestedChild) {
+ if (_this6.isSplitterPanel(nestedChild)) {
+ panels2.push(nestedChild);
+ }
+ });
+ }
+ });
+ return panels2;
+ }, "panels"),
+ gutterStyle: /* @__PURE__ */ __name(function gutterStyle() {
+ if (this.horizontal) return {
+ width: this.gutterSize + "px"
+ };
+ else return {
+ height: this.gutterSize + "px"
+ };
+ }, "gutterStyle"),
+ horizontal: /* @__PURE__ */ __name(function horizontal() {
+ return this.layout === "horizontal";
+ }, "horizontal"),
+ getPTOptions: /* @__PURE__ */ __name(function getPTOptions() {
+ var _this$$parentInstance;
+ return {
+ context: {
+ nested: (_this$$parentInstance = this.$parentInstance) === null || _this$$parentInstance === void 0 ? void 0 : _this$$parentInstance.nestedState
+ }
+ };
+ }, "getPTOptions")
+ }
+};
+var _hoisted_1$4 = ["onMousedown", "onTouchstart", "onTouchmove", "onTouchend"];
+var _hoisted_2$3 = ["aria-orientation", "aria-valuenow", "onKeydown"];
+function render$2(_ctx, _cache, $props, $setup, $data, $options) {
+ return openBlock(), createElementBlock("div", mergeProps({
+ "class": _ctx.cx("root"),
+ style: _ctx.sx("root"),
+ "data-p-resizing": false
+ }, _ctx.ptmi("root", $options.getPTOptions)), [(openBlock(true), createElementBlock(Fragment, null, renderList($options.panels, function(panel, i) {
+ return openBlock(), createElementBlock(Fragment, {
+ key: i
+ }, [(openBlock(), createBlock(resolveDynamicComponent(panel), {
+ tabindex: "-1"
+ })), i !== $options.panels.length - 1 ? (openBlock(), createElementBlock("div", mergeProps({
+ key: 0,
+ ref_for: true,
+ ref: "gutter",
+ "class": _ctx.cx("gutter"),
+ role: "separator",
+ tabindex: "-1",
+ onMousedown: /* @__PURE__ */ __name(function onMousedown($event) {
+ return $options.onGutterMouseDown($event, i);
+ }, "onMousedown"),
+ onTouchstart: /* @__PURE__ */ __name(function onTouchstart($event) {
+ return $options.onGutterTouchStart($event, i);
+ }, "onTouchstart"),
+ onTouchmove: /* @__PURE__ */ __name(function onTouchmove($event) {
+ return $options.onGutterTouchMove($event, i);
+ }, "onTouchmove"),
+ onTouchend: /* @__PURE__ */ __name(function onTouchend($event) {
+ return $options.onGutterTouchEnd($event, i);
+ }, "onTouchend"),
+ "data-p-gutter-resizing": false
+ }, _ctx.ptm("gutter")), [createBaseVNode("div", mergeProps({
+ "class": _ctx.cx("gutterHandle"),
+ tabindex: "0",
+ style: [$options.gutterStyle],
+ "aria-orientation": _ctx.layout,
+ "aria-valuenow": $data.prevSize,
+ onKeyup: _cache[0] || (_cache[0] = function() {
+ return $options.onGutterKeyUp && $options.onGutterKeyUp.apply($options, arguments);
+ }),
+ onKeydown: /* @__PURE__ */ __name(function onKeydown($event) {
+ return $options.onGutterKeyDown($event, i);
+ }, "onKeydown"),
+ ref_for: true
+ }, _ctx.ptm("gutterHandle")), null, 16, _hoisted_2$3)], 16, _hoisted_1$4)) : createCommentVNode("", true)], 64);
+ }), 128))], 16);
+}
+__name(render$2, "render$2");
+script$3.render = render$2;
+var classes$1 = {
+ root: /* @__PURE__ */ __name(function root3(_ref) {
+ var instance = _ref.instance;
+ return ["p-splitterpanel", {
+ "p-splitterpanel-nested": instance.isNested
+ }];
+ }, "root")
+};
+var SplitterPanelStyle = BaseStyle.extend({
+ name: "splitterpanel",
+ classes: classes$1
+});
+var script$1$1 = {
+ name: "BaseSplitterPanel",
+ "extends": script$7,
+ props: {
+ size: {
+ type: Number,
+ "default": null
+ },
+ minSize: {
+ type: Number,
+ "default": null
+ }
+ },
+ style: SplitterPanelStyle,
+ provide: /* @__PURE__ */ __name(function provide3() {
+ return {
+ $pcSplitterPanel: this,
+ $parentInstance: this
+ };
+ }, "provide")
+};
+var script$2 = {
+ name: "SplitterPanel",
+ "extends": script$1$1,
+ inheritAttrs: false,
+ data: /* @__PURE__ */ __name(function data2() {
+ return {
+ nestedState: null
+ };
+ }, "data"),
+ computed: {
+ isNested: /* @__PURE__ */ __name(function isNested() {
+ var _this = this;
+ return this.$slots["default"]().some(function(child) {
+ _this.nestedState = child.type.name === "Splitter" ? true : null;
+ return _this.nestedState;
+ });
+ }, "isNested"),
+ getPTOptions: /* @__PURE__ */ __name(function getPTOptions2() {
+ return {
+ context: {
+ nested: this.isNested
+ }
+ };
+ }, "getPTOptions")
+ }
+};
+function render$1(_ctx, _cache, $props, $setup, $data, $options) {
+ return openBlock(), createElementBlock("div", mergeProps({
+ ref: "container",
+ "class": _ctx.cx("root")
+ }, _ctx.ptmi("root", $options.getPTOptions)), [renderSlot(_ctx.$slots, "default")], 16);
+}
+__name(render$1, "render$1");
+script$2.render = render$1;
+const _withScopeId$2 = /* @__PURE__ */ __name((n) => (pushScopeId("data-v-edca8328"), n = n(), popScopeId(), n), "_withScopeId$2");
+const _hoisted_1$3 = /* @__PURE__ */ _withScopeId$2(() => /* @__PURE__ */ createBaseVNode("div", null, null, -1));
+const _sfc_main$7 = /* @__PURE__ */ defineComponent({
+ __name: "LiteGraphCanvasSplitterOverlay",
+ setup(__props) {
+ const settingStore = useSettingStore();
+ const sidebarLocation = computed(
+ () => settingStore.get("Comfy.Sidebar.Location")
+ );
+ const sidebarPanelVisible = computed(
+ () => useWorkspaceStore().activeSidebarTab !== null
+ );
+ const gutterClass = computed(() => {
+ return sidebarPanelVisible.value ? "" : "gutter-hidden";
+ });
+ return (_ctx, _cache) => {
+ return openBlock(), createBlock(unref(script$3), {
+ class: "splitter-overlay",
+ "pt:gutter": gutterClass.value
+ }, {
+ default: withCtx(() => [
+ sidebarLocation.value === "left" ? withDirectives((openBlock(), createBlock(unref(script$2), {
+ key: 0,
+ class: "side-bar-panel",
+ minSize: 10,
+ size: 20
+ }, {
+ default: withCtx(() => [
+ renderSlot(_ctx.$slots, "side-bar-panel", {}, void 0, true)
+ ]),
+ _: 3
+ }, 512)), [
+ [vShow, sidebarPanelVisible.value]
+ ]) : createCommentVNode("", true),
+ createVNode(unref(script$2), {
+ class: "graph-canvas-panel",
+ size: 100
+ }, {
+ default: withCtx(() => [
+ _hoisted_1$3
+ ]),
+ _: 1
+ }),
+ sidebarLocation.value === "right" ? withDirectives((openBlock(), createBlock(unref(script$2), {
+ key: 1,
+ class: "side-bar-panel",
+ minSize: 10,
+ size: 20
+ }, {
+ default: withCtx(() => [
+ renderSlot(_ctx.$slots, "side-bar-panel", {}, void 0, true)
+ ]),
+ _: 3
+ }, 512)), [
+ [vShow, sidebarPanelVisible.value]
+ ]) : createCommentVNode("", true)
+ ]),
+ _: 3
+ }, 8, ["pt:gutter"]);
+ };
+ }
+});
+const LiteGraphCanvasSplitterOverlay = /* @__PURE__ */ _export_sfc(_sfc_main$7, [["__scopeId", "data-v-edca8328"]]);
+var theme3 = /* @__PURE__ */ __name(function theme4(_ref) {
+ var dt = _ref.dt;
+ 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");
+}, "theme");
+var inlineStyles = {
+ root: {
+ position: "relative"
+ }
+};
+var classes = {
+ root: /* @__PURE__ */ __name(function root4(_ref2) {
+ var instance = _ref2.instance, props = _ref2.props;
+ return ["p-autocomplete p-component p-inputwrapper", {
+ "p-disabled": props.disabled,
+ "p-invalid": props.invalid,
+ "p-focus": instance.focused,
+ "p-inputwrapper-filled": props.modelValue || isNotEmpty(instance.inputValue),
+ "p-inputwrapper-focus": instance.focused,
+ "p-autocomplete-open": instance.overlayVisible,
+ "p-autocomplete-fluid": instance.hasFluid
+ }];
+ }, "root"),
+ pcInput: "p-autocomplete-input",
+ inputMultiple: /* @__PURE__ */ __name(function inputMultiple(_ref3) {
+ var props = _ref3.props, instance = _ref3.instance;
+ return ["p-autocomplete-input-multiple", {
+ "p-variant-filled": props.variant ? props.variant === "filled" : instance.$primevue.config.inputStyle === "filled" || instance.$primevue.config.inputVariant === "filled"
+ }];
+ }, "inputMultiple"),
+ chipItem: /* @__PURE__ */ __name(function chipItem(_ref4) {
+ var instance = _ref4.instance, i = _ref4.i;
+ return ["p-autocomplete-chip-item", {
+ "p-focus": instance.focusedMultipleOptionIndex === i
+ }];
+ }, "chipItem"),
+ pcChip: "p-autocomplete-chip",
+ chipIcon: "p-autocomplete-chip-icon",
+ inputChip: "p-autocomplete-input-chip",
+ loader: "p-autocomplete-loader",
+ dropdown: "p-autocomplete-dropdown",
+ overlay: "p-autocomplete-overlay p-component",
+ list: "p-autocomplete-list",
+ optionGroup: "p-autocomplete-option-group",
+ option: /* @__PURE__ */ __name(function option(_ref5) {
+ var instance = _ref5.instance, _option = _ref5.option, i = _ref5.i, getItemOptions = _ref5.getItemOptions;
+ return ["p-autocomplete-option", {
+ "p-autocomplete-option-selected": instance.isSelected(_option),
+ "p-focus": instance.focusedOptionIndex === instance.getOptionIndex(i, getItemOptions),
+ "p-disabled": instance.isOptionDisabled(_option)
+ }];
+ }, "option"),
+ emptyMessage: "p-autocomplete-empty-message"
+};
+var AutoCompleteStyle = BaseStyle.extend({
+ name: "autocomplete",
+ theme: theme3,
+ classes,
+ inlineStyles
+});
+var script$1 = {
+ name: "BaseAutoComplete",
+ "extends": script$7,
+ props: {
+ modelValue: null,
+ suggestions: {
+ type: Array,
+ "default": null
+ },
+ optionLabel: null,
+ optionDisabled: null,
+ optionGroupLabel: null,
+ optionGroupChildren: null,
+ scrollHeight: {
+ type: String,
+ "default": "14rem"
+ },
+ dropdown: {
+ type: Boolean,
+ "default": false
+ },
+ dropdownMode: {
+ type: String,
+ "default": "blank"
+ },
+ multiple: {
+ type: Boolean,
+ "default": false
+ },
+ loading: {
+ type: Boolean,
+ "default": false
+ },
+ variant: {
+ type: String,
+ "default": null
+ },
+ invalid: {
+ type: Boolean,
+ "default": false
+ },
+ disabled: {
+ type: Boolean,
+ "default": false
+ },
+ placeholder: {
+ type: String,
+ "default": null
+ },
+ dataKey: {
+ type: String,
+ "default": null
+ },
+ minLength: {
+ type: Number,
+ "default": 1
+ },
+ delay: {
+ type: Number,
+ "default": 300
+ },
+ appendTo: {
+ type: [String, Object],
+ "default": "body"
+ },
+ forceSelection: {
+ type: Boolean,
+ "default": false
+ },
+ completeOnFocus: {
+ type: Boolean,
+ "default": false
+ },
+ inputId: {
+ type: String,
+ "default": null
+ },
+ inputStyle: {
+ type: Object,
+ "default": null
+ },
+ inputClass: {
+ type: [String, Object],
+ "default": null
+ },
+ panelStyle: {
+ type: Object,
+ "default": null
+ },
+ panelClass: {
+ type: [String, Object],
+ "default": null
+ },
+ overlayStyle: {
+ type: Object,
+ "default": null
+ },
+ overlayClass: {
+ type: [String, Object],
+ "default": null
+ },
+ dropdownIcon: {
+ type: String,
+ "default": null
+ },
+ dropdownClass: {
+ type: [String, Object],
+ "default": null
+ },
+ loader: {
+ type: String,
+ "default": null
+ },
+ loadingIcon: {
+ type: String,
+ "default": null
+ },
+ removeTokenIcon: {
+ type: String,
+ "default": null
+ },
+ chipIcon: {
+ type: String,
+ "default": null
+ },
+ virtualScrollerOptions: {
+ type: Object,
+ "default": null
+ },
+ autoOptionFocus: {
+ type: Boolean,
+ "default": false
+ },
+ selectOnFocus: {
+ type: Boolean,
+ "default": false
+ },
+ focusOnHover: {
+ type: Boolean,
+ "default": true
+ },
+ searchLocale: {
+ type: String,
+ "default": void 0
+ },
+ searchMessage: {
+ type: String,
+ "default": null
+ },
+ selectionMessage: {
+ type: String,
+ "default": null
+ },
+ emptySelectionMessage: {
+ type: String,
+ "default": null
+ },
+ emptySearchMessage: {
+ type: String,
+ "default": null
+ },
+ tabindex: {
+ type: Number,
+ "default": 0
+ },
+ typeahead: {
+ type: Boolean,
+ "default": true
+ },
+ ariaLabel: {
+ type: String,
+ "default": null
+ },
+ ariaLabelledby: {
+ type: String,
+ "default": null
+ },
+ fluid: {
+ type: Boolean,
+ "default": null
+ }
+ },
+ style: AutoCompleteStyle,
+ provide: /* @__PURE__ */ __name(function provide4() {
+ return {
+ $pcAutoComplete: this,
+ $parentInstance: this
+ };
+ }, "provide")
+};
+function _typeof$1(o) {
+ "@babel/helpers - typeof";
+ return _typeof$1 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
+ return typeof o2;
+ } : function(o2) {
+ return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
+ }, _typeof$1(o);
+}
+__name(_typeof$1, "_typeof$1");
+function _toConsumableArray(r) {
+ return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread();
+}
+__name(_toConsumableArray, "_toConsumableArray");
+function _nonIterableSpread() {
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
+}
+__name(_nonIterableSpread, "_nonIterableSpread");
+function _unsupportedIterableToArray(r, a) {
+ if (r) {
+ if ("string" == typeof r) return _arrayLikeToArray(r, a);
+ var t = {}.toString.call(r).slice(8, -1);
+ return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
+ }
+}
+__name(_unsupportedIterableToArray, "_unsupportedIterableToArray");
+function _iterableToArray(r) {
+ if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r);
+}
+__name(_iterableToArray, "_iterableToArray");
+function _arrayWithoutHoles(r) {
+ if (Array.isArray(r)) return _arrayLikeToArray(r);
+}
+__name(_arrayWithoutHoles, "_arrayWithoutHoles");
+function _arrayLikeToArray(r, a) {
+ (null == a || a > r.length) && (a = r.length);
+ for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
+ return n;
+}
+__name(_arrayLikeToArray, "_arrayLikeToArray");
+var script = {
+ name: "AutoComplete",
+ "extends": script$1,
+ inheritAttrs: false,
+ emits: ["update:modelValue", "change", "focus", "blur", "item-select", "item-unselect", "option-select", "option-unselect", "dropdown-click", "clear", "complete", "before-show", "before-hide", "show", "hide"],
+ inject: {
+ $pcFluid: {
+ "default": null
+ }
+ },
+ outsideClickListener: null,
+ resizeListener: null,
+ scrollHandler: null,
+ overlay: null,
+ virtualScroller: null,
+ searchTimeout: null,
+ dirty: false,
+ data: /* @__PURE__ */ __name(function data3() {
+ return {
+ id: this.$attrs.id,
+ clicked: false,
+ focused: false,
+ focusedOptionIndex: -1,
+ focusedMultipleOptionIndex: -1,
+ overlayVisible: false,
+ searching: false
+ };
+ }, "data"),
+ watch: {
+ "$attrs.id": /* @__PURE__ */ __name(function $attrsId(newValue) {
+ this.id = newValue || UniqueComponentId();
+ }, "$attrsId"),
+ suggestions: /* @__PURE__ */ __name(function suggestions() {
+ if (this.searching) {
+ this.show();
+ this.focusedOptionIndex = this.overlayVisible && this.autoOptionFocus ? this.findFirstFocusedOptionIndex() : -1;
+ this.searching = false;
+ }
+ this.autoUpdateModel();
+ }, "suggestions")
+ },
+ mounted: /* @__PURE__ */ __name(function mounted2() {
+ this.id = this.id || UniqueComponentId();
+ this.autoUpdateModel();
+ }, "mounted"),
+ updated: /* @__PURE__ */ __name(function updated() {
+ if (this.overlayVisible) {
+ this.alignOverlay();
+ }
+ }, "updated"),
+ beforeUnmount: /* @__PURE__ */ __name(function beforeUnmount2() {
+ this.unbindOutsideClickListener();
+ this.unbindResizeListener();
+ if (this.scrollHandler) {
+ this.scrollHandler.destroy();
+ this.scrollHandler = null;
+ }
+ if (this.overlay) {
+ ZIndex.clear(this.overlay);
+ this.overlay = null;
+ }
+ }, "beforeUnmount"),
+ methods: {
+ getOptionIndex: /* @__PURE__ */ __name(function getOptionIndex(index, fn) {
+ return this.virtualScrollerDisabled ? index : fn && fn(index)["index"];
+ }, "getOptionIndex"),
+ getOptionLabel: /* @__PURE__ */ __name(function getOptionLabel(option2) {
+ return this.optionLabel ? resolveFieldData(option2, this.optionLabel) : option2;
+ }, "getOptionLabel"),
+ getOptionValue: /* @__PURE__ */ __name(function getOptionValue(option2) {
+ return option2;
+ }, "getOptionValue"),
+ getOptionRenderKey: /* @__PURE__ */ __name(function getOptionRenderKey(option2, index) {
+ return (this.dataKey ? resolveFieldData(option2, this.dataKey) : this.getOptionLabel(option2)) + "_" + index;
+ }, "getOptionRenderKey"),
+ getPTOptions: /* @__PURE__ */ __name(function getPTOptions3(option2, itemOptions, index, key) {
+ return this.ptm(key, {
+ context: {
+ selected: this.isSelected(option2),
+ focused: this.focusedOptionIndex === this.getOptionIndex(index, itemOptions),
+ disabled: this.isOptionDisabled(option2)
+ }
+ });
+ }, "getPTOptions"),
+ isOptionDisabled: /* @__PURE__ */ __name(function isOptionDisabled(option2) {
+ return this.optionDisabled ? resolveFieldData(option2, this.optionDisabled) : false;
+ }, "isOptionDisabled"),
+ isOptionGroup: /* @__PURE__ */ __name(function isOptionGroup(option2) {
+ return this.optionGroupLabel && option2.optionGroup && option2.group;
+ }, "isOptionGroup"),
+ getOptionGroupLabel: /* @__PURE__ */ __name(function getOptionGroupLabel(optionGroup) {
+ return resolveFieldData(optionGroup, this.optionGroupLabel);
+ }, "getOptionGroupLabel"),
+ getOptionGroupChildren: /* @__PURE__ */ __name(function getOptionGroupChildren(optionGroup) {
+ return resolveFieldData(optionGroup, this.optionGroupChildren);
+ }, "getOptionGroupChildren"),
+ getAriaPosInset: /* @__PURE__ */ __name(function getAriaPosInset(index) {
+ var _this = this;
+ return (this.optionGroupLabel ? index - this.visibleOptions.slice(0, index).filter(function(option2) {
+ return _this.isOptionGroup(option2);
+ }).length : index) + 1;
+ }, "getAriaPosInset"),
+ show: /* @__PURE__ */ __name(function show(isFocus) {
+ this.$emit("before-show");
+ this.dirty = true;
+ this.overlayVisible = true;
+ this.focusedOptionIndex = this.focusedOptionIndex !== -1 ? this.focusedOptionIndex : this.autoOptionFocus ? this.findFirstFocusedOptionIndex() : -1;
+ isFocus && focus(this.multiple ? this.$refs.focusInput : this.$refs.focusInput.$el);
+ }, "show"),
+ hide: /* @__PURE__ */ __name(function hide(isFocus) {
+ var _this2 = this;
+ var _hide = /* @__PURE__ */ __name(function _hide2() {
+ _this2.$emit("before-hide");
+ _this2.dirty = isFocus;
+ _this2.overlayVisible = false;
+ _this2.clicked = false;
+ _this2.focusedOptionIndex = -1;
+ isFocus && focus(_this2.multiple ? _this2.$refs.focusInput : _this2.$refs.focusInput.$el);
+ }, "_hide");
+ setTimeout(function() {
+ _hide();
+ }, 0);
+ }, "hide"),
+ onFocus: /* @__PURE__ */ __name(function onFocus(event) {
+ if (this.disabled) {
+ return;
+ }
+ if (!this.dirty && this.completeOnFocus) {
+ this.search(event, event.target.value, "focus");
+ }
+ this.dirty = true;
+ this.focused = true;
+ if (this.overlayVisible) {
+ this.focusedOptionIndex = this.focusedOptionIndex !== -1 ? this.focusedOptionIndex : this.overlayVisible && this.autoOptionFocus ? this.findFirstFocusedOptionIndex() : -1;
+ this.scrollInView(this.focusedOptionIndex);
+ }
+ this.$emit("focus", event);
+ }, "onFocus"),
+ onBlur: /* @__PURE__ */ __name(function onBlur(event) {
+ this.dirty = false;
+ this.focused = false;
+ this.focusedOptionIndex = -1;
+ this.$emit("blur", event);
+ }, "onBlur"),
+ onKeyDown: /* @__PURE__ */ __name(function onKeyDown(event) {
+ if (this.disabled) {
+ event.preventDefault();
+ return;
+ }
+ switch (event.code) {
+ case "ArrowDown":
+ this.onArrowDownKey(event);
+ break;
+ case "ArrowUp":
+ this.onArrowUpKey(event);
+ break;
+ case "ArrowLeft":
+ this.onArrowLeftKey(event);
+ break;
+ case "ArrowRight":
+ this.onArrowRightKey(event);
+ break;
+ case "Home":
+ this.onHomeKey(event);
+ break;
+ case "End":
+ this.onEndKey(event);
+ break;
+ case "PageDown":
+ this.onPageDownKey(event);
+ break;
+ case "PageUp":
+ this.onPageUpKey(event);
+ break;
+ case "Enter":
+ case "NumpadEnter":
+ this.onEnterKey(event);
+ break;
+ case "Escape":
+ this.onEscapeKey(event);
+ break;
+ case "Tab":
+ this.onTabKey(event);
+ break;
+ case "Backspace":
+ this.onBackspaceKey(event);
+ break;
+ }
+ this.clicked = false;
+ }, "onKeyDown"),
+ onInput: /* @__PURE__ */ __name(function onInput(event) {
+ var _this3 = this;
+ if (this.typeahead) {
+ if (this.searchTimeout) {
+ clearTimeout(this.searchTimeout);
+ }
+ var query = event.target.value;
+ if (!this.multiple) {
+ this.updateModel(event, query);
+ }
+ if (query.length === 0) {
+ this.hide();
+ this.$emit("clear");
+ } else {
+ if (query.length >= this.minLength) {
+ this.focusedOptionIndex = -1;
+ this.searchTimeout = setTimeout(function() {
+ _this3.search(event, query, "input");
+ }, this.delay);
+ } else {
+ this.hide();
+ }
+ }
+ }
+ }, "onInput"),
+ onChange: /* @__PURE__ */ __name(function onChange(event) {
+ var _this4 = this;
+ if (this.forceSelection) {
+ var valid = false;
+ if (this.visibleOptions && !this.multiple) {
+ var value = this.multiple ? this.$refs.focusInput.value : this.$refs.focusInput.$el.value;
+ var matchedValue = this.visibleOptions.find(function(option2) {
+ return _this4.isOptionMatched(option2, value || "");
+ });
+ if (matchedValue !== void 0) {
+ valid = true;
+ !this.isSelected(matchedValue) && this.onOptionSelect(event, matchedValue);
+ }
+ }
+ if (!valid) {
+ if (this.multiple) this.$refs.focusInput.value = "";
+ else this.$refs.focusInput.$el.value = "";
+ this.$emit("clear");
+ !this.multiple && this.updateModel(event, null);
+ }
+ }
+ }, "onChange"),
+ onMultipleContainerFocus: /* @__PURE__ */ __name(function onMultipleContainerFocus() {
+ if (this.disabled) {
+ return;
+ }
+ this.focused = true;
+ }, "onMultipleContainerFocus"),
+ onMultipleContainerBlur: /* @__PURE__ */ __name(function onMultipleContainerBlur() {
+ this.focusedMultipleOptionIndex = -1;
+ this.focused = false;
+ }, "onMultipleContainerBlur"),
+ onMultipleContainerKeyDown: /* @__PURE__ */ __name(function onMultipleContainerKeyDown(event) {
+ if (this.disabled) {
+ event.preventDefault();
+ return;
+ }
+ switch (event.code) {
+ case "ArrowLeft":
+ this.onArrowLeftKeyOnMultiple(event);
+ break;
+ case "ArrowRight":
+ this.onArrowRightKeyOnMultiple(event);
+ break;
+ case "Backspace":
+ this.onBackspaceKeyOnMultiple(event);
+ break;
+ }
+ }, "onMultipleContainerKeyDown"),
+ onContainerClick: /* @__PURE__ */ __name(function onContainerClick(event) {
+ this.clicked = true;
+ if (this.disabled || this.searching || this.loading || this.isInputClicked(event) || this.isDropdownClicked(event)) {
+ return;
+ }
+ if (!this.overlay || !this.overlay.contains(event.target)) {
+ focus(this.multiple ? this.$refs.focusInput : this.$refs.focusInput.$el);
+ }
+ }, "onContainerClick"),
+ onDropdownClick: /* @__PURE__ */ __name(function onDropdownClick(event) {
+ var query = void 0;
+ if (this.overlayVisible) {
+ this.hide(true);
+ } else {
+ var target = this.multiple ? this.$refs.focusInput : this.$refs.focusInput.$el;
+ focus(target);
+ query = target.value;
+ if (this.dropdownMode === "blank") this.search(event, "", "dropdown");
+ else if (this.dropdownMode === "current") this.search(event, query, "dropdown");
+ }
+ this.$emit("dropdown-click", {
+ originalEvent: event,
+ query
+ });
+ }, "onDropdownClick"),
+ onOptionSelect: /* @__PURE__ */ __name(function onOptionSelect(event, option2) {
+ var isHide = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : true;
+ var value = this.getOptionValue(option2);
+ if (this.multiple) {
+ this.$refs.focusInput.value = "";
+ if (!this.isSelected(option2)) {
+ this.updateModel(event, [].concat(_toConsumableArray(this.modelValue || []), [value]));
+ }
+ } else {
+ this.updateModel(event, value);
+ }
+ this.$emit("item-select", {
+ originalEvent: event,
+ value: option2
+ });
+ this.$emit("option-select", {
+ originalEvent: event,
+ value: option2
+ });
+ isHide && this.hide(true);
+ }, "onOptionSelect"),
+ onOptionMouseMove: /* @__PURE__ */ __name(function onOptionMouseMove(event, index) {
+ if (this.focusOnHover) {
+ this.changeFocusedOptionIndex(event, index);
+ }
+ }, "onOptionMouseMove"),
+ onOverlayClick: /* @__PURE__ */ __name(function onOverlayClick(event) {
+ OverlayEventBus.emit("overlay-click", {
+ originalEvent: event,
+ target: this.$el
+ });
+ }, "onOverlayClick"),
+ onOverlayKeyDown: /* @__PURE__ */ __name(function onOverlayKeyDown(event) {
+ switch (event.code) {
+ case "Escape":
+ this.onEscapeKey(event);
+ break;
+ }
+ }, "onOverlayKeyDown"),
+ onArrowDownKey: /* @__PURE__ */ __name(function onArrowDownKey(event) {
+ if (!this.overlayVisible) {
+ return;
+ }
+ var optionIndex = this.focusedOptionIndex !== -1 ? this.findNextOptionIndex(this.focusedOptionIndex) : this.clicked ? this.findFirstOptionIndex() : this.findFirstFocusedOptionIndex();
+ this.changeFocusedOptionIndex(event, optionIndex);
+ event.preventDefault();
+ }, "onArrowDownKey"),
+ onArrowUpKey: /* @__PURE__ */ __name(function onArrowUpKey(event) {
+ if (!this.overlayVisible) {
+ return;
+ }
+ if (event.altKey) {
+ if (this.focusedOptionIndex !== -1) {
+ this.onOptionSelect(event, this.visibleOptions[this.focusedOptionIndex]);
+ }
+ this.overlayVisible && this.hide();
+ event.preventDefault();
+ } else {
+ var optionIndex = this.focusedOptionIndex !== -1 ? this.findPrevOptionIndex(this.focusedOptionIndex) : this.clicked ? this.findLastOptionIndex() : this.findLastFocusedOptionIndex();
+ this.changeFocusedOptionIndex(event, optionIndex);
+ event.preventDefault();
+ }
+ }, "onArrowUpKey"),
+ onArrowLeftKey: /* @__PURE__ */ __name(function onArrowLeftKey(event) {
+ var target = event.currentTarget;
+ this.focusedOptionIndex = -1;
+ if (this.multiple) {
+ if (isEmpty(target.value) && this.hasSelectedOption) {
+ focus(this.$refs.multiContainer);
+ this.focusedMultipleOptionIndex = this.modelValue.length;
+ } else {
+ event.stopPropagation();
+ }
+ }
+ }, "onArrowLeftKey"),
+ onArrowRightKey: /* @__PURE__ */ __name(function onArrowRightKey(event) {
+ this.focusedOptionIndex = -1;
+ this.multiple && event.stopPropagation();
+ }, "onArrowRightKey"),
+ onHomeKey: /* @__PURE__ */ __name(function onHomeKey(event) {
+ var currentTarget = event.currentTarget;
+ var len = currentTarget.value.length;
+ currentTarget.setSelectionRange(0, event.shiftKey ? len : 0);
+ this.focusedOptionIndex = -1;
+ event.preventDefault();
+ }, "onHomeKey"),
+ onEndKey: /* @__PURE__ */ __name(function onEndKey(event) {
+ var currentTarget = event.currentTarget;
+ var len = currentTarget.value.length;
+ currentTarget.setSelectionRange(event.shiftKey ? 0 : len, len);
+ this.focusedOptionIndex = -1;
+ event.preventDefault();
+ }, "onEndKey"),
+ onPageUpKey: /* @__PURE__ */ __name(function onPageUpKey(event) {
+ this.scrollInView(0);
+ event.preventDefault();
+ }, "onPageUpKey"),
+ onPageDownKey: /* @__PURE__ */ __name(function onPageDownKey(event) {
+ this.scrollInView(this.visibleOptions.length - 1);
+ event.preventDefault();
+ }, "onPageDownKey"),
+ onEnterKey: /* @__PURE__ */ __name(function onEnterKey(event) {
+ if (!this.typeahead) {
+ if (this.multiple) {
+ this.updateModel(event, [].concat(_toConsumableArray(this.modelValue || []), [event.target.value]));
+ this.$refs.focusInput.value = "";
+ }
+ } else {
+ if (!this.overlayVisible) {
+ this.focusedOptionIndex = -1;
+ this.onArrowDownKey(event);
+ } else {
+ if (this.focusedOptionIndex !== -1) {
+ this.onOptionSelect(event, this.visibleOptions[this.focusedOptionIndex]);
+ }
+ this.hide();
+ }
+ }
+ }, "onEnterKey"),
+ onEscapeKey: /* @__PURE__ */ __name(function onEscapeKey(event) {
+ this.overlayVisible && this.hide(true);
+ event.preventDefault();
+ }, "onEscapeKey"),
+ onTabKey: /* @__PURE__ */ __name(function onTabKey(event) {
+ if (this.focusedOptionIndex !== -1) {
+ this.onOptionSelect(event, this.visibleOptions[this.focusedOptionIndex]);
+ }
+ this.overlayVisible && this.hide();
+ }, "onTabKey"),
+ onBackspaceKey: /* @__PURE__ */ __name(function onBackspaceKey(event) {
+ if (this.multiple) {
+ if (isNotEmpty(this.modelValue) && !this.$refs.focusInput.value) {
+ var removedValue = this.modelValue[this.modelValue.length - 1];
+ var newValue = this.modelValue.slice(0, -1);
+ this.$emit("update:modelValue", newValue);
+ this.$emit("item-unselect", {
+ originalEvent: event,
+ value: removedValue
+ });
+ this.$emit("option-unselect", {
+ originalEvent: event,
+ value: removedValue
+ });
+ }
+ event.stopPropagation();
+ }
+ }, "onBackspaceKey"),
+ onArrowLeftKeyOnMultiple: /* @__PURE__ */ __name(function onArrowLeftKeyOnMultiple() {
+ this.focusedMultipleOptionIndex = this.focusedMultipleOptionIndex < 1 ? 0 : this.focusedMultipleOptionIndex - 1;
+ }, "onArrowLeftKeyOnMultiple"),
+ onArrowRightKeyOnMultiple: /* @__PURE__ */ __name(function onArrowRightKeyOnMultiple() {
+ this.focusedMultipleOptionIndex++;
+ if (this.focusedMultipleOptionIndex > this.modelValue.length - 1) {
+ this.focusedMultipleOptionIndex = -1;
+ focus(this.$refs.focusInput);
+ }
+ }, "onArrowRightKeyOnMultiple"),
+ onBackspaceKeyOnMultiple: /* @__PURE__ */ __name(function onBackspaceKeyOnMultiple(event) {
+ if (this.focusedMultipleOptionIndex !== -1) {
+ this.removeOption(event, this.focusedMultipleOptionIndex);
+ }
+ }, "onBackspaceKeyOnMultiple"),
+ onOverlayEnter: /* @__PURE__ */ __name(function onOverlayEnter(el) {
+ ZIndex.set("overlay", el, this.$primevue.config.zIndex.overlay);
+ addStyle(el, {
+ position: "absolute",
+ top: "0",
+ left: "0"
+ });
+ this.alignOverlay();
+ }, "onOverlayEnter"),
+ onOverlayAfterEnter: /* @__PURE__ */ __name(function onOverlayAfterEnter() {
+ this.bindOutsideClickListener();
+ this.bindScrollListener();
+ this.bindResizeListener();
+ this.$emit("show");
+ }, "onOverlayAfterEnter"),
+ onOverlayLeave: /* @__PURE__ */ __name(function onOverlayLeave() {
+ this.unbindOutsideClickListener();
+ this.unbindScrollListener();
+ this.unbindResizeListener();
+ this.$emit("hide");
+ this.overlay = null;
+ }, "onOverlayLeave"),
+ onOverlayAfterLeave: /* @__PURE__ */ __name(function onOverlayAfterLeave(el) {
+ ZIndex.clear(el);
+ }, "onOverlayAfterLeave"),
+ alignOverlay: /* @__PURE__ */ __name(function alignOverlay() {
+ var target = this.multiple ? this.$refs.multiContainer : this.$refs.focusInput.$el;
+ if (this.appendTo === "self") {
+ relativePosition(this.overlay, target);
+ } else {
+ this.overlay.style.minWidth = getOuterWidth(target) + "px";
+ absolutePosition(this.overlay, target);
+ }
+ }, "alignOverlay"),
+ bindOutsideClickListener: /* @__PURE__ */ __name(function bindOutsideClickListener() {
+ var _this5 = this;
+ if (!this.outsideClickListener) {
+ this.outsideClickListener = function(event) {
+ if (_this5.overlayVisible && _this5.overlay && _this5.isOutsideClicked(event)) {
+ _this5.hide();
+ }
+ };
+ document.addEventListener("click", this.outsideClickListener);
+ }
+ }, "bindOutsideClickListener"),
+ unbindOutsideClickListener: /* @__PURE__ */ __name(function unbindOutsideClickListener() {
+ if (this.outsideClickListener) {
+ document.removeEventListener("click", this.outsideClickListener);
+ this.outsideClickListener = null;
+ }
+ }, "unbindOutsideClickListener"),
+ bindScrollListener: /* @__PURE__ */ __name(function bindScrollListener() {
+ var _this6 = this;
+ if (!this.scrollHandler) {
+ this.scrollHandler = new ConnectedOverlayScrollHandler(this.$refs.container, function() {
+ if (_this6.overlayVisible) {
+ _this6.hide();
+ }
+ });
+ }
+ this.scrollHandler.bindScrollListener();
+ }, "bindScrollListener"),
+ unbindScrollListener: /* @__PURE__ */ __name(function unbindScrollListener() {
+ if (this.scrollHandler) {
+ this.scrollHandler.unbindScrollListener();
+ }
+ }, "unbindScrollListener"),
+ bindResizeListener: /* @__PURE__ */ __name(function bindResizeListener() {
+ var _this7 = this;
+ if (!this.resizeListener) {
+ this.resizeListener = function() {
+ if (_this7.overlayVisible && !isTouchDevice()) {
+ _this7.hide();
+ }
+ };
+ window.addEventListener("resize", this.resizeListener);
+ }
+ }, "bindResizeListener"),
+ unbindResizeListener: /* @__PURE__ */ __name(function unbindResizeListener() {
+ if (this.resizeListener) {
+ window.removeEventListener("resize", this.resizeListener);
+ this.resizeListener = null;
+ }
+ }, "unbindResizeListener"),
+ isOutsideClicked: /* @__PURE__ */ __name(function isOutsideClicked(event) {
+ return !this.overlay.contains(event.target) && !this.isInputClicked(event) && !this.isDropdownClicked(event);
+ }, "isOutsideClicked"),
+ isInputClicked: /* @__PURE__ */ __name(function isInputClicked(event) {
+ if (this.multiple) return event.target === this.$refs.multiContainer || this.$refs.multiContainer.contains(event.target);
+ else return event.target === this.$refs.focusInput.$el;
+ }, "isInputClicked"),
+ isDropdownClicked: /* @__PURE__ */ __name(function isDropdownClicked(event) {
+ return this.$refs.dropdownButton ? event.target === this.$refs.dropdownButton || this.$refs.dropdownButton.contains(event.target) : false;
+ }, "isDropdownClicked"),
+ isOptionMatched: /* @__PURE__ */ __name(function isOptionMatched(option2, value) {
+ var _this$getOptionLabel;
+ return this.isValidOption(option2) && ((_this$getOptionLabel = this.getOptionLabel(option2)) === null || _this$getOptionLabel === void 0 ? void 0 : _this$getOptionLabel.toLocaleLowerCase(this.searchLocale)) === value.toLocaleLowerCase(this.searchLocale);
+ }, "isOptionMatched"),
+ isValidOption: /* @__PURE__ */ __name(function isValidOption(option2) {
+ return isNotEmpty(option2) && !(this.isOptionDisabled(option2) || this.isOptionGroup(option2));
+ }, "isValidOption"),
+ isValidSelectedOption: /* @__PURE__ */ __name(function isValidSelectedOption(option2) {
+ return this.isValidOption(option2) && this.isSelected(option2);
+ }, "isValidSelectedOption"),
+ isEquals: /* @__PURE__ */ __name(function isEquals(value1, value2) {
+ return equals(value1, value2, this.equalityKey);
+ }, "isEquals"),
+ isSelected: /* @__PURE__ */ __name(function isSelected(option2) {
+ var _this8 = this;
+ var optionValue = this.getOptionValue(option2);
+ return this.multiple ? (this.modelValue || []).some(function(value) {
+ return _this8.isEquals(value, optionValue);
+ }) : this.isEquals(this.modelValue, this.getOptionValue(option2));
+ }, "isSelected"),
+ findFirstOptionIndex: /* @__PURE__ */ __name(function findFirstOptionIndex() {
+ var _this9 = this;
+ return this.visibleOptions.findIndex(function(option2) {
+ return _this9.isValidOption(option2);
+ });
+ }, "findFirstOptionIndex"),
+ findLastOptionIndex: /* @__PURE__ */ __name(function findLastOptionIndex() {
+ var _this10 = this;
+ return findLastIndex(this.visibleOptions, function(option2) {
+ return _this10.isValidOption(option2);
+ });
+ }, "findLastOptionIndex"),
+ findNextOptionIndex: /* @__PURE__ */ __name(function findNextOptionIndex(index) {
+ var _this11 = this;
+ var matchedOptionIndex = index < this.visibleOptions.length - 1 ? this.visibleOptions.slice(index + 1).findIndex(function(option2) {
+ return _this11.isValidOption(option2);
+ }) : -1;
+ return matchedOptionIndex > -1 ? matchedOptionIndex + index + 1 : index;
+ }, "findNextOptionIndex"),
+ findPrevOptionIndex: /* @__PURE__ */ __name(function findPrevOptionIndex(index) {
+ var _this12 = this;
+ var matchedOptionIndex = index > 0 ? findLastIndex(this.visibleOptions.slice(0, index), function(option2) {
+ return _this12.isValidOption(option2);
+ }) : -1;
+ return matchedOptionIndex > -1 ? matchedOptionIndex : index;
+ }, "findPrevOptionIndex"),
+ findSelectedOptionIndex: /* @__PURE__ */ __name(function findSelectedOptionIndex() {
+ var _this13 = this;
+ return this.hasSelectedOption ? this.visibleOptions.findIndex(function(option2) {
+ return _this13.isValidSelectedOption(option2);
+ }) : -1;
+ }, "findSelectedOptionIndex"),
+ findFirstFocusedOptionIndex: /* @__PURE__ */ __name(function findFirstFocusedOptionIndex() {
+ var selectedIndex = this.findSelectedOptionIndex();
+ return selectedIndex < 0 ? this.findFirstOptionIndex() : selectedIndex;
+ }, "findFirstFocusedOptionIndex"),
+ findLastFocusedOptionIndex: /* @__PURE__ */ __name(function findLastFocusedOptionIndex() {
+ var selectedIndex = this.findSelectedOptionIndex();
+ return selectedIndex < 0 ? this.findLastOptionIndex() : selectedIndex;
+ }, "findLastFocusedOptionIndex"),
+ search: /* @__PURE__ */ __name(function search(event, query, source) {
+ if (query === void 0 || query === null) {
+ return;
+ }
+ if (source === "input" && query.trim().length === 0) {
+ return;
+ }
+ this.searching = true;
+ this.$emit("complete", {
+ originalEvent: event,
+ query
+ });
+ }, "search"),
+ removeOption: /* @__PURE__ */ __name(function removeOption(event, index) {
+ var _this14 = this;
+ var removedOption = this.modelValue[index];
+ var value = this.modelValue.filter(function(_, i) {
+ return i !== index;
+ }).map(function(option2) {
+ return _this14.getOptionValue(option2);
+ });
+ this.updateModel(event, value);
+ this.$emit("item-unselect", {
+ originalEvent: event,
+ value: removedOption
+ });
+ this.$emit("option-unselect", {
+ originalEvent: event,
+ value: removedOption
+ });
+ this.dirty = true;
+ focus(this.multiple ? this.$refs.focusInput : this.$refs.focusInput.$el);
+ }, "removeOption"),
+ changeFocusedOptionIndex: /* @__PURE__ */ __name(function changeFocusedOptionIndex(event, index) {
+ if (this.focusedOptionIndex !== index) {
+ this.focusedOptionIndex = index;
+ this.scrollInView();
+ if (this.selectOnFocus) {
+ this.onOptionSelect(event, this.visibleOptions[index], false);
+ }
+ }
+ }, "changeFocusedOptionIndex"),
+ scrollInView: /* @__PURE__ */ __name(function scrollInView() {
+ var _this15 = this;
+ var index = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : -1;
+ this.$nextTick(function() {
+ var id = index !== -1 ? "".concat(_this15.id, "_").concat(index) : _this15.focusedOptionId;
+ var element = findSingle(_this15.list, 'li[id="'.concat(id, '"]'));
+ if (element) {
+ element.scrollIntoView && element.scrollIntoView({
+ block: "nearest",
+ inline: "start"
+ });
+ } else if (!_this15.virtualScrollerDisabled) {
+ _this15.virtualScroller && _this15.virtualScroller.scrollToIndex(index !== -1 ? index : _this15.focusedOptionIndex);
+ }
+ });
+ }, "scrollInView"),
+ autoUpdateModel: /* @__PURE__ */ __name(function autoUpdateModel() {
+ if (this.selectOnFocus && this.autoOptionFocus && !this.hasSelectedOption) {
+ this.focusedOptionIndex = this.findFirstFocusedOptionIndex();
+ this.onOptionSelect(null, this.visibleOptions[this.focusedOptionIndex], false);
+ }
+ }, "autoUpdateModel"),
+ updateModel: /* @__PURE__ */ __name(function updateModel(event, value) {
+ this.$emit("update:modelValue", value);
+ this.$emit("change", {
+ originalEvent: event,
+ value
+ });
+ }, "updateModel"),
+ flatOptions: /* @__PURE__ */ __name(function flatOptions(options) {
+ var _this16 = this;
+ return (options || []).reduce(function(result, option2, index) {
+ result.push({
+ optionGroup: option2,
+ group: true,
+ index
+ });
+ var optionGroupChildren = _this16.getOptionGroupChildren(option2);
+ optionGroupChildren && optionGroupChildren.forEach(function(o) {
+ return result.push(o);
+ });
+ return result;
+ }, []);
+ }, "flatOptions"),
+ overlayRef: /* @__PURE__ */ __name(function overlayRef(el) {
+ this.overlay = el;
+ }, "overlayRef"),
+ listRef: /* @__PURE__ */ __name(function listRef(el, contentRef) {
+ this.list = el;
+ contentRef && contentRef(el);
+ }, "listRef"),
+ virtualScrollerRef: /* @__PURE__ */ __name(function virtualScrollerRef(el) {
+ this.virtualScroller = el;
+ }, "virtualScrollerRef")
+ },
+ computed: {
+ visibleOptions: /* @__PURE__ */ __name(function visibleOptions() {
+ return this.optionGroupLabel ? this.flatOptions(this.suggestions) : this.suggestions || [];
+ }, "visibleOptions"),
+ inputValue: /* @__PURE__ */ __name(function inputValue() {
+ if (isNotEmpty(this.modelValue)) {
+ if (_typeof$1(this.modelValue) === "object") {
+ var label = this.getOptionLabel(this.modelValue);
+ return label != null ? label : this.modelValue;
+ } else {
+ return this.modelValue;
+ }
+ } else {
+ return "";
+ }
+ }, "inputValue"),
+ hasSelectedOption: /* @__PURE__ */ __name(function hasSelectedOption() {
+ return isNotEmpty(this.modelValue);
+ }, "hasSelectedOption"),
+ equalityKey: /* @__PURE__ */ __name(function equalityKey() {
+ return this.dataKey;
+ }, "equalityKey"),
+ searchResultMessageText: /* @__PURE__ */ __name(function searchResultMessageText() {
+ return isNotEmpty(this.visibleOptions) && this.overlayVisible ? this.searchMessageText.replaceAll("{0}", this.visibleOptions.length) : this.emptySearchMessageText;
+ }, "searchResultMessageText"),
+ searchMessageText: /* @__PURE__ */ __name(function searchMessageText() {
+ return this.searchMessage || this.$primevue.config.locale.searchMessage || "";
+ }, "searchMessageText"),
+ emptySearchMessageText: /* @__PURE__ */ __name(function emptySearchMessageText() {
+ return this.emptySearchMessage || this.$primevue.config.locale.emptySearchMessage || "";
+ }, "emptySearchMessageText"),
+ selectionMessageText: /* @__PURE__ */ __name(function selectionMessageText() {
+ return this.selectionMessage || this.$primevue.config.locale.selectionMessage || "";
+ }, "selectionMessageText"),
+ emptySelectionMessageText: /* @__PURE__ */ __name(function emptySelectionMessageText() {
+ return this.emptySelectionMessage || this.$primevue.config.locale.emptySelectionMessage || "";
+ }, "emptySelectionMessageText"),
+ selectedMessageText: /* @__PURE__ */ __name(function selectedMessageText() {
+ return this.hasSelectedOption ? this.selectionMessageText.replaceAll("{0}", this.multiple ? this.modelValue.length : "1") : this.emptySelectionMessageText;
+ }, "selectedMessageText"),
+ listAriaLabel: /* @__PURE__ */ __name(function listAriaLabel() {
+ return this.$primevue.config.locale.aria ? this.$primevue.config.locale.aria.listLabel : void 0;
+ }, "listAriaLabel"),
+ focusedOptionId: /* @__PURE__ */ __name(function focusedOptionId() {
+ return this.focusedOptionIndex !== -1 ? "".concat(this.id, "_").concat(this.focusedOptionIndex) : null;
+ }, "focusedOptionId"),
+ focusedMultipleOptionId: /* @__PURE__ */ __name(function focusedMultipleOptionId() {
+ return this.focusedMultipleOptionIndex !== -1 ? "".concat(this.id, "_multiple_option_").concat(this.focusedMultipleOptionIndex) : null;
+ }, "focusedMultipleOptionId"),
+ ariaSetSize: /* @__PURE__ */ __name(function ariaSetSize() {
+ var _this17 = this;
+ return this.visibleOptions.filter(function(option2) {
+ return !_this17.isOptionGroup(option2);
+ }).length;
+ }, "ariaSetSize"),
+ virtualScrollerDisabled: /* @__PURE__ */ __name(function virtualScrollerDisabled() {
+ return !this.virtualScrollerOptions;
+ }, "virtualScrollerDisabled"),
+ panelId: /* @__PURE__ */ __name(function panelId() {
+ return this.id + "_panel";
+ }, "panelId"),
+ hasFluid: /* @__PURE__ */ __name(function hasFluid() {
+ return isEmpty(this.fluid) ? !!this.$pcFluid : this.fluid;
+ }, "hasFluid")
+ },
+ components: {
+ InputText: script$8,
+ VirtualScroller: script$9,
+ Portal: script$a,
+ ChevronDownIcon: script$b,
+ SpinnerIcon: script$c,
+ Chip: script$d
+ },
+ directives: {
+ ripple: Ripple
+ }
+};
+function _typeof(o) {
+ "@babel/helpers - typeof";
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
+ return typeof o2;
+ } : function(o2) {
+ return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
+ }, _typeof(o);
+}
+__name(_typeof, "_typeof");
+function ownKeys(e, r) {
+ var t = Object.keys(e);
+ if (Object.getOwnPropertySymbols) {
+ var o = Object.getOwnPropertySymbols(e);
+ r && (o = o.filter(function(r2) {
+ return Object.getOwnPropertyDescriptor(e, r2).enumerable;
+ })), t.push.apply(t, o);
+ }
+ return t;
+}
+__name(ownKeys, "ownKeys");
+function _objectSpread(e) {
+ for (var r = 1; r < arguments.length; r++) {
+ var t = null != arguments[r] ? arguments[r] : {};
+ r % 2 ? ownKeys(Object(t), true).forEach(function(r2) {
+ _defineProperty(e, r2, t[r2]);
+ }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r2) {
+ Object.defineProperty(e, r2, Object.getOwnPropertyDescriptor(t, r2));
+ });
+ }
+ return e;
+}
+__name(_objectSpread, "_objectSpread");
+function _defineProperty(e, r, t) {
+ return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: true, configurable: true, writable: true }) : e[r] = t, e;
+}
+__name(_defineProperty, "_defineProperty");
+function _toPropertyKey(t) {
+ var i = _toPrimitive(t, "string");
+ return "symbol" == _typeof(i) ? i : i + "";
+}
+__name(_toPropertyKey, "_toPropertyKey");
+function _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);
+}
+__name(_toPrimitive, "_toPrimitive");
+var _hoisted_1$2 = ["aria-activedescendant"];
+var _hoisted_2$2 = ["id", "aria-label", "aria-setsize", "aria-posinset"];
+var _hoisted_3$2 = ["id", "placeholder", "tabindex", "disabled", "aria-label", "aria-labelledby", "aria-expanded", "aria-controls", "aria-activedescendant", "aria-invalid"];
+var _hoisted_4$2 = ["disabled", "aria-expanded", "aria-controls"];
+var _hoisted_5$1 = ["id"];
+var _hoisted_6$1 = ["id", "aria-label"];
+var _hoisted_7$1 = ["id"];
+var _hoisted_8$1 = ["id", "aria-label", "aria-selected", "aria-disabled", "aria-setsize", "aria-posinset", "onClick", "onMousemove", "data-p-selected", "data-p-focus", "data-p-disabled"];
+function render(_ctx, _cache, $props, $setup, $data, $options) {
+ var _component_InputText = resolveComponent("InputText");
+ var _component_Chip = resolveComponent("Chip");
+ var _component_SpinnerIcon = resolveComponent("SpinnerIcon");
+ var _component_VirtualScroller = resolveComponent("VirtualScroller");
+ var _component_Portal = resolveComponent("Portal");
+ var _directive_ripple = resolveDirective("ripple");
+ return openBlock(), createElementBlock("div", mergeProps({
+ ref: "container",
+ "class": _ctx.cx("root"),
+ style: _ctx.sx("root"),
+ onClick: _cache[11] || (_cache[11] = function() {
+ return $options.onContainerClick && $options.onContainerClick.apply($options, arguments);
+ })
+ }, _ctx.ptmi("root")), [!_ctx.multiple ? (openBlock(), createBlock(_component_InputText, {
+ key: 0,
+ ref: "focusInput",
+ id: _ctx.inputId,
+ type: "text",
+ "class": normalizeClass([_ctx.cx("pcInput"), _ctx.inputClass]),
+ style: normalizeStyle(_ctx.inputStyle),
+ value: $options.inputValue,
+ placeholder: _ctx.placeholder,
+ tabindex: !_ctx.disabled ? _ctx.tabindex : -1,
+ fluid: $options.hasFluid,
+ disabled: _ctx.disabled,
+ invalid: _ctx.invalid,
+ variant: _ctx.variant,
+ autocomplete: "off",
+ role: "combobox",
+ "aria-label": _ctx.ariaLabel,
+ "aria-labelledby": _ctx.ariaLabelledby,
+ "aria-haspopup": "listbox",
+ "aria-autocomplete": "list",
+ "aria-expanded": $data.overlayVisible,
+ "aria-controls": $options.panelId,
+ "aria-activedescendant": $data.focused ? $options.focusedOptionId : void 0,
+ onFocus: $options.onFocus,
+ onBlur: $options.onBlur,
+ onKeydown: $options.onKeyDown,
+ onInput: $options.onInput,
+ onChange: $options.onChange,
+ unstyled: _ctx.unstyled,
+ pt: _ctx.ptm("pcInput")
+ }, null, 8, ["id", "class", "style", "value", "placeholder", "tabindex", "fluid", "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({
+ key: 1,
+ ref: "multiContainer",
+ "class": _ctx.cx("inputMultiple"),
+ tabindex: "-1",
+ role: "listbox",
+ "aria-orientation": "horizontal",
+ "aria-activedescendant": $data.focused ? $options.focusedMultipleOptionId : void 0,
+ onFocus: _cache[5] || (_cache[5] = function() {
+ return $options.onMultipleContainerFocus && $options.onMultipleContainerFocus.apply($options, arguments);
+ }),
+ onBlur: _cache[6] || (_cache[6] = function() {
+ return $options.onMultipleContainerBlur && $options.onMultipleContainerBlur.apply($options, arguments);
+ }),
+ onKeydown: _cache[7] || (_cache[7] = function() {
+ return $options.onMultipleContainerKeyDown && $options.onMultipleContainerKeyDown.apply($options, arguments);
+ })
+ }, _ctx.ptm("inputMultiple")), [(openBlock(true), createElementBlock(Fragment, null, renderList(_ctx.modelValue, function(option2, i) {
+ return openBlock(), createElementBlock("li", mergeProps({
+ key: "".concat(i, "_").concat($options.getOptionLabel(option2)),
+ id: $data.id + "_multiple_option_" + i,
+ "class": _ctx.cx("chipItem", {
+ i
+ }),
+ role: "option",
+ "aria-label": $options.getOptionLabel(option2),
+ "aria-selected": true,
+ "aria-setsize": _ctx.modelValue.length,
+ "aria-posinset": i + 1,
+ ref_for: true
+ }, _ctx.ptm("chipItem")), [renderSlot(_ctx.$slots, "chip", mergeProps({
+ "class": _ctx.cx("pcChip"),
+ value: option2,
+ index: i,
+ removeCallback: /* @__PURE__ */ __name(function removeCallback(event) {
+ return $options.removeOption(event, i);
+ }, "removeCallback"),
+ ref_for: true
+ }, _ctx.ptm("pcChip")), function() {
+ return [createVNode(_component_Chip, {
+ "class": normalizeClass(_ctx.cx("pcChip")),
+ label: $options.getOptionLabel(option2),
+ removeIcon: _ctx.chipIcon || _ctx.removeTokenIcon,
+ removable: "",
+ unstyled: _ctx.unstyled,
+ onRemove: /* @__PURE__ */ __name(function onRemove($event) {
+ return $options.removeOption($event, i);
+ }, "onRemove"),
+ pt: _ctx.ptm("pcChip")
+ }, {
+ removeicon: withCtx(function() {
+ return [renderSlot(_ctx.$slots, _ctx.$slots.chipicon ? "chipicon" : "removetokenicon", {
+ "class": normalizeClass(_ctx.cx("chipIcon")),
+ index: i,
+ removeCallback: /* @__PURE__ */ __name(function removeCallback(event) {
+ return $options.removeOption(event, i);
+ }, "removeCallback")
+ })];
+ }),
+ _: 2
+ }, 1032, ["class", "label", "removeIcon", "unstyled", "onRemove", "pt"])];
+ })], 16, _hoisted_2$2);
+ }), 128)), createBaseVNode("li", mergeProps({
+ "class": _ctx.cx("inputChip"),
+ role: "option"
+ }, _ctx.ptm("inputChip")), [createBaseVNode("input", mergeProps({
+ ref: "focusInput",
+ id: _ctx.inputId,
+ type: "text",
+ style: _ctx.inputStyle,
+ "class": _ctx.inputClass,
+ placeholder: _ctx.placeholder,
+ tabindex: !_ctx.disabled ? _ctx.tabindex : -1,
+ disabled: _ctx.disabled,
+ autocomplete: "off",
+ role: "combobox",
+ "aria-label": _ctx.ariaLabel,
+ "aria-labelledby": _ctx.ariaLabelledby,
+ "aria-haspopup": "listbox",
+ "aria-autocomplete": "list",
+ "aria-expanded": $data.overlayVisible,
+ "aria-controls": $data.id + "_list",
+ "aria-activedescendant": $data.focused ? $options.focusedOptionId : void 0,
+ "aria-invalid": _ctx.invalid || void 0,
+ onFocus: _cache[0] || (_cache[0] = function() {
+ return $options.onFocus && $options.onFocus.apply($options, arguments);
+ }),
+ onBlur: _cache[1] || (_cache[1] = function() {
+ return $options.onBlur && $options.onBlur.apply($options, arguments);
+ }),
+ onKeydown: _cache[2] || (_cache[2] = function() {
+ return $options.onKeyDown && $options.onKeyDown.apply($options, arguments);
+ }),
+ onInput: _cache[3] || (_cache[3] = function() {
+ return $options.onInput && $options.onInput.apply($options, arguments);
+ }),
+ onChange: _cache[4] || (_cache[4] = function() {
+ return $options.onChange && $options.onChange.apply($options, arguments);
+ })
+ }, _ctx.ptm("input")), null, 16, _hoisted_3$2)], 16)], 16, _hoisted_1$2)) : createCommentVNode("", true), $data.searching || _ctx.loading ? renderSlot(_ctx.$slots, _ctx.$slots.loader ? "loader" : "loadingicon", {
+ key: 2,
+ "class": normalizeClass(_ctx.cx("loader"))
+ }, function() {
+ return [_ctx.loader || _ctx.loadingIcon ? (openBlock(), createElementBlock("i", mergeProps({
+ key: 0,
+ "class": ["pi-spin", _ctx.cx("loader"), _ctx.loader, _ctx.loadingIcon],
+ "aria-hidden": "true"
+ }, _ctx.ptm("loader")), null, 16)) : (openBlock(), createBlock(_component_SpinnerIcon, mergeProps({
+ key: 1,
+ "class": _ctx.cx("loader"),
+ spin: "",
+ "aria-hidden": "true"
+ }, _ctx.ptm("loader")), null, 16, ["class"]))];
+ }) : createCommentVNode("", true), renderSlot(_ctx.$slots, _ctx.$slots.dropdown ? "dropdown" : "dropdownbutton", {
+ toggleCallback: /* @__PURE__ */ __name(function toggleCallback(event) {
+ return $options.onDropdownClick(event);
+ }, "toggleCallback")
+ }, function() {
+ return [_ctx.dropdown ? (openBlock(), createElementBlock("button", mergeProps({
+ key: 0,
+ ref: "dropdownButton",
+ type: "button",
+ "class": [_ctx.cx("dropdown"), _ctx.dropdownClass],
+ disabled: _ctx.disabled,
+ "aria-haspopup": "listbox",
+ "aria-expanded": $data.overlayVisible,
+ "aria-controls": $options.panelId,
+ onClick: _cache[8] || (_cache[8] = function() {
+ return $options.onDropdownClick && $options.onDropdownClick.apply($options, arguments);
+ })
+ }, _ctx.ptm("dropdown")), [renderSlot(_ctx.$slots, "dropdownicon", {
+ "class": normalizeClass(_ctx.dropdownIcon)
+ }, function() {
+ return [(openBlock(), createBlock(resolveDynamicComponent(_ctx.dropdownIcon ? "span" : "ChevronDownIcon"), mergeProps({
+ "class": _ctx.dropdownIcon
+ }, _ctx.ptm("dropdownIcon")), null, 16, ["class"]))];
+ })], 16, _hoisted_4$2)) : createCommentVNode("", true)];
+ }), createBaseVNode("span", mergeProps({
+ role: "status",
+ "aria-live": "polite",
+ "class": "p-hidden-accessible"
+ }, _ctx.ptm("hiddenSearchResult"), {
+ "data-p-hidden-accessible": true
+ }), toDisplayString($options.searchResultMessageText), 17), createVNode(_component_Portal, {
+ appendTo: _ctx.appendTo
+ }, {
+ "default": withCtx(function() {
+ return [createVNode(Transition, mergeProps({
+ name: "p-connected-overlay",
+ onEnter: $options.onOverlayEnter,
+ onAfterEnter: $options.onOverlayAfterEnter,
+ onLeave: $options.onOverlayLeave,
+ onAfterLeave: $options.onOverlayAfterLeave
+ }, _ctx.ptm("transition")), {
+ "default": withCtx(function() {
+ return [$data.overlayVisible ? (openBlock(), createElementBlock("div", mergeProps({
+ key: 0,
+ ref: $options.overlayRef,
+ id: $options.panelId,
+ "class": [_ctx.cx("overlay"), _ctx.panelClass, _ctx.overlayClass],
+ style: _objectSpread(_objectSpread(_objectSpread({}, _ctx.panelStyle), _ctx.overlayStyle), {}, {
+ "max-height": $options.virtualScrollerDisabled ? _ctx.scrollHeight : ""
+ }),
+ onClick: _cache[9] || (_cache[9] = function() {
+ return $options.onOverlayClick && $options.onOverlayClick.apply($options, arguments);
+ }),
+ onKeydown: _cache[10] || (_cache[10] = function() {
+ return $options.onOverlayKeyDown && $options.onOverlayKeyDown.apply($options, arguments);
+ })
+ }, _ctx.ptm("overlay")), [renderSlot(_ctx.$slots, "header", {
+ value: _ctx.modelValue,
+ suggestions: $options.visibleOptions
+ }), createVNode(_component_VirtualScroller, mergeProps({
+ ref: $options.virtualScrollerRef
+ }, _ctx.virtualScrollerOptions, {
+ style: {
+ height: _ctx.scrollHeight
+ },
+ items: $options.visibleOptions,
+ tabindex: -1,
+ disabled: $options.virtualScrollerDisabled,
+ pt: _ctx.ptm("virtualScroller")
+ }), createSlots({
+ content: withCtx(function(_ref) {
+ var styleClass = _ref.styleClass, contentRef = _ref.contentRef, items = _ref.items, getItemOptions = _ref.getItemOptions, contentStyle = _ref.contentStyle, itemSize = _ref.itemSize;
+ return [createBaseVNode("ul", mergeProps({
+ ref: /* @__PURE__ */ __name(function ref2(el) {
+ return $options.listRef(el, contentRef);
+ }, "ref"),
+ id: $data.id + "_list",
+ "class": [_ctx.cx("list"), styleClass],
+ style: contentStyle,
+ role: "listbox",
+ "aria-label": $options.listAriaLabel
+ }, _ctx.ptm("list")), [(openBlock(true), createElementBlock(Fragment, null, renderList(items, function(option2, i) {
+ return openBlock(), createElementBlock(Fragment, {
+ key: $options.getOptionRenderKey(option2, $options.getOptionIndex(i, getItemOptions))
+ }, [$options.isOptionGroup(option2) ? (openBlock(), createElementBlock("li", mergeProps({
+ key: 0,
+ id: $data.id + "_" + $options.getOptionIndex(i, getItemOptions),
+ style: {
+ height: itemSize ? itemSize + "px" : void 0
+ },
+ "class": _ctx.cx("optionGroup"),
+ role: "option",
+ ref_for: true
+ }, _ctx.ptm("optionGroup")), [renderSlot(_ctx.$slots, "optiongroup", {
+ option: option2.optionGroup,
+ index: $options.getOptionIndex(i, getItemOptions)
+ }, function() {
+ return [createTextVNode(toDisplayString($options.getOptionGroupLabel(option2.optionGroup)), 1)];
+ })], 16, _hoisted_7$1)) : withDirectives((openBlock(), createElementBlock("li", mergeProps({
+ key: 1,
+ id: $data.id + "_" + $options.getOptionIndex(i, getItemOptions),
+ style: {
+ height: itemSize ? itemSize + "px" : void 0
+ },
+ "class": _ctx.cx("option", {
+ option: option2,
+ i,
+ getItemOptions
+ }),
+ role: "option",
+ "aria-label": $options.getOptionLabel(option2),
+ "aria-selected": $options.isSelected(option2),
+ "aria-disabled": $options.isOptionDisabled(option2),
+ "aria-setsize": $options.ariaSetSize,
+ "aria-posinset": $options.getAriaPosInset($options.getOptionIndex(i, getItemOptions)),
+ onClick: /* @__PURE__ */ __name(function onClick($event) {
+ return $options.onOptionSelect($event, option2);
+ }, "onClick"),
+ onMousemove: /* @__PURE__ */ __name(function onMousemove($event) {
+ return $options.onOptionMouseMove($event, $options.getOptionIndex(i, getItemOptions));
+ }, "onMousemove"),
+ "data-p-selected": $options.isSelected(option2),
+ "data-p-focus": $data.focusedOptionIndex === $options.getOptionIndex(i, getItemOptions),
+ "data-p-disabled": $options.isOptionDisabled(option2),
+ ref_for: true
+ }, $options.getPTOptions(option2, getItemOptions, i, "option")), [renderSlot(_ctx.$slots, "option", {
+ option: option2,
+ index: $options.getOptionIndex(i, getItemOptions)
+ }, function() {
+ return [createTextVNode(toDisplayString($options.getOptionLabel(option2)), 1)];
+ })], 16, _hoisted_8$1)), [[_directive_ripple]])], 64);
+ }), 128)), !items || items && items.length === 0 ? (openBlock(), createElementBlock("li", mergeProps({
+ key: 0,
+ "class": _ctx.cx("emptyMessage"),
+ role: "option"
+ }, _ctx.ptm("emptyMessage")), [renderSlot(_ctx.$slots, "empty", {}, function() {
+ return [createTextVNode(toDisplayString($options.searchResultMessageText), 1)];
+ })], 16)) : createCommentVNode("", true)], 16, _hoisted_6$1)];
+ }),
+ _: 2
+ }, [_ctx.$slots.loader ? {
+ name: "loader",
+ fn: withCtx(function(_ref2) {
+ var options = _ref2.options;
+ return [renderSlot(_ctx.$slots, "loader", {
+ options
+ })];
+ }),
+ key: "0"
+ } : void 0]), 1040, ["style", "items", "disabled", "pt"]), renderSlot(_ctx.$slots, "footer", {
+ value: _ctx.modelValue,
+ suggestions: $options.visibleOptions
+ }), createBaseVNode("span", mergeProps({
+ role: "status",
+ "aria-live": "polite",
+ "class": "p-hidden-accessible"
+ }, _ctx.ptm("hiddenSelectedMessage"), {
+ "data-p-hidden-accessible": true
+ }), toDisplayString($options.selectedMessageText), 17)], 16, _hoisted_5$1)) : createCommentVNode("", true)];
+ }),
+ _: 3
+ }, 16, ["onEnter", "onAfterEnter", "onLeave", "onAfterLeave"])];
+ }),
+ _: 3
+ }, 8, ["appendTo"])], 16);
+}
+__name(render, "render");
+script.render = render;
+const _sfc_main$6 = {
+ name: "AutoCompletePlus",
+ extends: script,
+ emits: ["focused-option-changed"],
+ mounted() {
+ if (typeof script.mounted === "function") {
+ script.mounted.call(this);
+ }
+ this.$watch(
+ () => this.focusedOptionIndex,
+ (newVal, oldVal) => {
+ this.$emit("focused-option-changed", newVal);
+ }
+ );
+ }
+};
+const _withScopeId$1 = /* @__PURE__ */ __name((n) => (pushScopeId("data-v-37f672ab"), n = n(), popScopeId(), n), "_withScopeId$1");
+const _hoisted_1$1 = { class: "option-container flex justify-between items-center px-2 py-0 cursor-pointer overflow-hidden w-full" };
+const _hoisted_2$1 = { class: "option-display-name font-semibold flex flex-col" };
+const _hoisted_3$1 = { key: 0 };
+const _hoisted_4$1 = /* @__PURE__ */ _withScopeId$1(() => /* @__PURE__ */ createBaseVNode("i", { class: "pi pi-bookmark-fill text-sm mr-1" }, null, -1));
+const _hoisted_5 = [
+ _hoisted_4$1
+];
+const _hoisted_6 = ["innerHTML"];
+const _hoisted_7 = /* @__PURE__ */ _withScopeId$1(() => /* @__PURE__ */ createBaseVNode("span", null, " ", -1));
+const _hoisted_8 = ["innerHTML"];
+const _hoisted_9 = {
+ key: 0,
+ class: "option-category font-light text-sm text-gray-400 overflow-hidden text-ellipsis whitespace-nowrap"
+};
+const _hoisted_10 = { class: "option-badges" };
+const _sfc_main$5 = /* @__PURE__ */ defineComponent({
+ __name: "NodeSearchItem",
+ props: {
+ nodeDef: {},
+ currentQuery: {}
+ },
+ setup(__props) {
+ const settingStore = useSettingStore();
+ const showCategory = computed(
+ () => settingStore.get("Comfy.NodeSearchBoxImpl.ShowCategory")
+ );
+ const showIdName = computed(
+ () => settingStore.get("Comfy.NodeSearchBoxImpl.ShowIdName")
+ );
+ const showNodeFrequency = computed(
+ () => settingStore.get("Comfy.NodeSearchBoxImpl.ShowNodeFrequency")
+ );
+ const nodeFrequencyStore = useNodeFrequencyStore();
+ const nodeFrequency = computed(
+ () => nodeFrequencyStore.getNodeFrequency(props.nodeDef)
+ );
+ const nodeBookmarkStore = useNodeBookmarkStore();
+ const isBookmarked = computed(
+ () => nodeBookmarkStore.isBookmarked(props.nodeDef)
+ );
+ const props = __props;
+ return (_ctx, _cache) => {
+ return openBlock(), createElementBlock("div", _hoisted_1$1, [
+ createBaseVNode("div", _hoisted_2$1, [
+ createBaseVNode("div", null, [
+ isBookmarked.value ? (openBlock(), createElementBlock("span", _hoisted_3$1, _hoisted_5)) : createCommentVNode("", true),
+ createBaseVNode("span", {
+ innerHTML: unref(highlightQuery)(_ctx.nodeDef.display_name, _ctx.currentQuery)
+ }, null, 8, _hoisted_6),
+ _hoisted_7,
+ showIdName.value ? (openBlock(), createBlock(unref(script$e), {
+ key: 1,
+ severity: "secondary"
+ }, {
+ default: withCtx(() => [
+ createBaseVNode("span", {
+ innerHTML: unref(highlightQuery)(_ctx.nodeDef.name, _ctx.currentQuery)
+ }, null, 8, _hoisted_8)
+ ]),
+ _: 1
+ })) : createCommentVNode("", true)
+ ]),
+ showCategory.value ? (openBlock(), createElementBlock("div", _hoisted_9, toDisplayString(_ctx.nodeDef.category.replaceAll("/", " > ")), 1)) : createCommentVNode("", true)
+ ]),
+ createBaseVNode("div", _hoisted_10, [
+ _ctx.nodeDef.experimental ? (openBlock(), createBlock(unref(script$e), {
+ key: 0,
+ value: _ctx.$t("experimental"),
+ severity: "primary"
+ }, null, 8, ["value"])) : createCommentVNode("", true),
+ _ctx.nodeDef.deprecated ? (openBlock(), createBlock(unref(script$e), {
+ key: 1,
+ value: _ctx.$t("deprecated"),
+ severity: "danger"
+ }, null, 8, ["value"])) : createCommentVNode("", true),
+ showNodeFrequency.value && nodeFrequency.value > 0 ? (openBlock(), createBlock(unref(script$e), {
+ key: 2,
+ value: unref(formatNumberWithSuffix)(nodeFrequency.value, { roundToInt: true }),
+ severity: "secondary"
+ }, null, 8, ["value"])) : createCommentVNode("", true),
+ _ctx.nodeDef.nodeSource.type !== unref(NodeSourceType).Unknown ? (openBlock(), createBlock(unref(script$d), {
+ key: 3,
+ class: "text-sm font-light"
+ }, {
+ default: withCtx(() => [
+ createTextVNode(toDisplayString(_ctx.nodeDef.nodeSource.displayText), 1)
+ ]),
+ _: 1
+ })) : createCommentVNode("", true)
+ ])
+ ]);
+ };
+ }
+});
+const NodeSearchItem = /* @__PURE__ */ _export_sfc(_sfc_main$5, [["__scopeId", "data-v-37f672ab"]]);
+const _withScopeId = /* @__PURE__ */ __name((n) => (pushScopeId("data-v-2d409367"), n = n(), popScopeId(), n), "_withScopeId");
+const _hoisted_1 = { class: "comfy-vue-node-search-container" };
+const _hoisted_2 = {
+ key: 0,
+ class: "comfy-vue-node-preview-container"
+};
+const _hoisted_3 = /* @__PURE__ */ _withScopeId(() => /* @__PURE__ */ createBaseVNode("h3", null, "Add node filter condition", -1));
+const _hoisted_4 = { class: "_dialog-body" };
+const _sfc_main$4 = /* @__PURE__ */ defineComponent({
+ __name: "NodeSearchBox",
+ props: {
+ filters: {},
+ searchLimit: { default: 64 }
+ },
+ emits: ["addFilter", "removeFilter", "addNode"],
+ setup(__props, { emit: __emit }) {
+ const settingStore = useSettingStore();
+ const { t } = useI18n();
+ const enableNodePreview = computed(
+ () => settingStore.get("Comfy.NodeSearchBoxImpl.NodePreview")
+ );
+ const props = __props;
+ const nodeSearchFilterVisible = ref(false);
+ const inputId = `comfy-vue-node-search-box-input-${Math.random()}`;
+ const suggestions2 = ref([]);
+ const hoveredSuggestion = ref(null);
+ const currentQuery = ref("");
+ const placeholder = computed(() => {
+ return props.filters.length === 0 ? t("searchNodes") + "..." : "";
+ });
+ const nodeDefStore = useNodeDefStore();
+ const nodeFrequencyStore = useNodeFrequencyStore();
+ const search2 = /* @__PURE__ */ __name((query) => {
+ const queryIsEmpty = query === "" && props.filters.length === 0;
+ currentQuery.value = query;
+ suggestions2.value = queryIsEmpty ? nodeFrequencyStore.topNodeDefs : [
+ ...nodeDefStore.nodeSearchService.searchNode(query, props.filters, {
+ limit: props.searchLimit
+ })
+ ];
+ }, "search");
+ const emit = __emit;
+ const reFocusInput = /* @__PURE__ */ __name(() => {
+ const inputElement = document.getElementById(inputId);
+ if (inputElement) {
+ inputElement.blur();
+ inputElement.focus();
+ }
+ }, "reFocusInput");
+ onMounted(reFocusInput);
+ const onAddFilter = /* @__PURE__ */ __name((filterAndValue) => {
+ nodeSearchFilterVisible.value = false;
+ emit("addFilter", filterAndValue);
+ reFocusInput();
+ }, "onAddFilter");
+ const onRemoveFilter = /* @__PURE__ */ __name((event, filterAndValue) => {
+ event.stopPropagation();
+ event.preventDefault();
+ emit("removeFilter", filterAndValue);
+ reFocusInput();
+ }, "onRemoveFilter");
+ const setHoverSuggestion = /* @__PURE__ */ __name((index) => {
+ if (index === -1) {
+ hoveredSuggestion.value = null;
+ return;
+ }
+ const value = suggestions2.value[index];
+ hoveredSuggestion.value = value;
+ }, "setHoverSuggestion");
+ return (_ctx, _cache) => {
+ return openBlock(), createElementBlock("div", _hoisted_1, [
+ enableNodePreview.value ? (openBlock(), createElementBlock("div", _hoisted_2, [
+ hoveredSuggestion.value ? (openBlock(), createBlock(NodePreview, {
+ nodeDef: hoveredSuggestion.value,
+ key: hoveredSuggestion.value?.name || ""
+ }, null, 8, ["nodeDef"])) : createCommentVNode("", true)
+ ])) : createCommentVNode("", true),
+ createVNode(unref(script$6), {
+ icon: "pi pi-filter",
+ severity: "secondary",
+ class: "_filter-button",
+ onClick: _cache[0] || (_cache[0] = ($event) => nodeSearchFilterVisible.value = true)
+ }),
+ createVNode(unref(script$f), {
+ visible: nodeSearchFilterVisible.value,
+ "onUpdate:visible": _cache[1] || (_cache[1] = ($event) => nodeSearchFilterVisible.value = $event),
+ class: "_dialog"
+ }, {
+ header: withCtx(() => [
+ _hoisted_3
+ ]),
+ default: withCtx(() => [
+ createBaseVNode("div", _hoisted_4, [
+ createVNode(NodeSearchFilter, { onAddFilter })
+ ])
+ ]),
+ _: 1
+ }, 8, ["visible"]),
+ createVNode(_sfc_main$6, {
+ "model-value": props.filters,
+ class: "comfy-vue-node-search-box",
+ scrollHeight: "40vh",
+ placeholder: placeholder.value,
+ "input-id": inputId,
+ "append-to": "self",
+ suggestions: suggestions2.value,
+ "min-length": 0,
+ delay: 100,
+ loading: !unref(nodeFrequencyStore).isLoaded,
+ onComplete: _cache[2] || (_cache[2] = ($event) => search2($event.query)),
+ onOptionSelect: _cache[3] || (_cache[3] = ($event) => emit("addNode", $event.value)),
+ onFocusedOptionChanged: _cache[4] || (_cache[4] = ($event) => setHoverSuggestion($event)),
+ "complete-on-focus": "",
+ "auto-option-focus": "",
+ "force-selection": "",
+ multiple: "",
+ optionLabel: "display_name"
+ }, {
+ option: withCtx(({ option: option2 }) => [
+ createVNode(NodeSearchItem, {
+ nodeDef: option2,
+ currentQuery: currentQuery.value
+ }, null, 8, ["nodeDef", "currentQuery"])
+ ]),
+ chip: withCtx(({ value }) => [
+ createVNode(SearchFilterChip, {
+ onRemove: /* @__PURE__ */ __name(($event) => onRemoveFilter($event, value), "onRemove"),
+ text: value[1],
+ badge: value[0].invokeSequence.toUpperCase(),
+ "badge-class": value[0].invokeSequence + "-badge"
+ }, null, 8, ["onRemove", "text", "badge", "badge-class"])
+ ]),
+ _: 1
+ }, 8, ["model-value", "placeholder", "suggestions", "loading"])
+ ]);
+ };
+ }
+});
+const NodeSearchBox = /* @__PURE__ */ _export_sfc(_sfc_main$4, [["__scopeId", "data-v-2d409367"]]);
+class ConnectingLinkImpl {
+ static {
+ __name(this, "ConnectingLinkImpl");
+ }
+ node;
+ slot;
+ input;
+ output;
+ pos;
+ constructor(node, slot, input, output, pos) {
+ this.node = node;
+ this.slot = slot;
+ this.input = input;
+ this.output = output;
+ this.pos = pos;
+ }
+ static createFromPlainObject(obj) {
+ return new ConnectingLinkImpl(
+ obj.node,
+ obj.slot,
+ obj.input,
+ obj.output,
+ obj.pos
+ );
+ }
+ get type() {
+ const result = this.input ? this.input.type : this.output.type;
+ return result === -1 ? null : result;
+ }
+ /**
+ * Which slot type is release and need to be reconnected.
+ * - 'output' means we need a new node's outputs slot to connect with this link
+ */
+ get releaseSlotType() {
+ return this.output ? "input" : "output";
+ }
+ connectTo(newNode) {
+ const newNodeSlots = this.releaseSlotType === "output" ? newNode.outputs : newNode.inputs;
+ if (!newNodeSlots) return;
+ const newNodeSlot = newNodeSlots.findIndex(
+ (slot) => LiteGraph.isValidConnection(slot.type, this.type)
+ );
+ if (newNodeSlot === -1) {
+ console.warn(
+ `Could not find slot with type ${this.type} on node ${newNode.title}. This should never happen`
+ );
+ return;
+ }
+ if (this.releaseSlotType === "input") {
+ this.node.connect(this.slot, newNode, newNodeSlot);
+ } else {
+ newNode.connect(newNodeSlot, this.node, this.slot);
+ }
+ }
+}
+const _sfc_main$3 = /* @__PURE__ */ defineComponent({
+ __name: "NodeSearchBoxPopover",
+ setup(__props) {
+ const settingStore = useSettingStore();
+ const visible = ref(false);
+ const dismissable = ref(true);
+ const triggerEvent = ref(null);
+ const getNewNodeLocation = /* @__PURE__ */ __name(() => {
+ if (triggerEvent.value === null) {
+ return [100, 100];
+ }
+ const originalEvent = triggerEvent.value.detail.originalEvent;
+ return [originalEvent.canvasX, originalEvent.canvasY];
+ }, "getNewNodeLocation");
+ const nodeFilters = ref([]);
+ const addFilter = /* @__PURE__ */ __name((filter) => {
+ nodeFilters.value.push(filter);
+ }, "addFilter");
+ const removeFilter = /* @__PURE__ */ __name((filter) => {
+ nodeFilters.value = nodeFilters.value.filter(
+ (f) => toRaw(f) !== toRaw(filter)
+ );
+ }, "removeFilter");
+ const clearFilters = /* @__PURE__ */ __name(() => {
+ nodeFilters.value = [];
+ }, "clearFilters");
+ const closeDialog = /* @__PURE__ */ __name(() => {
+ visible.value = false;
+ }, "closeDialog");
+ const addNode = /* @__PURE__ */ __name((nodeDef) => {
+ const node = app.addNodeOnGraph(nodeDef, { pos: getNewNodeLocation() });
+ const eventDetail = triggerEvent.value.detail;
+ if (eventDetail.subType === "empty-release") {
+ eventDetail.linkReleaseContext.links.forEach((link) => {
+ ConnectingLinkImpl.createFromPlainObject(link).connectTo(node);
+ });
+ }
+ window.setTimeout(() => {
+ closeDialog();
+ }, 100);
+ }, "addNode");
+ const newSearchBoxEnabled = computed(
+ () => settingStore.get("Comfy.NodeSearchBoxImpl") === "default"
+ );
+ const showSearchBox = /* @__PURE__ */ __name((e) => {
+ if (newSearchBoxEnabled.value) {
+ if (e.detail.originalEvent?.pointerType === "touch") {
+ setTimeout(() => {
+ showNewSearchBox(e);
+ }, 128);
+ } else {
+ showNewSearchBox(e);
+ }
+ } else {
+ canvasStore.canvas.showSearchBox(e.detail.originalEvent);
+ }
+ }, "showSearchBox");
+ const nodeDefStore = useNodeDefStore();
+ const showNewSearchBox = /* @__PURE__ */ __name((e) => {
+ if (e.detail.linkReleaseContext) {
+ const links = e.detail.linkReleaseContext.links;
+ if (links.length === 0) {
+ console.warn("Empty release with no links! This should never happen");
+ return;
+ }
+ const firstLink = ConnectingLinkImpl.createFromPlainObject(links[0]);
+ const filter = nodeDefStore.nodeSearchService.getFilterById(
+ firstLink.releaseSlotType
+ );
+ const dataType = firstLink.type;
+ addFilter([filter, dataType]);
+ }
+ visible.value = true;
+ triggerEvent.value = e;
+ dismissable.value = false;
+ setTimeout(() => {
+ dismissable.value = true;
+ }, 300);
+ }, "showNewSearchBox");
+ const showContextMenu = /* @__PURE__ */ __name((e) => {
+ const links = e.detail.linkReleaseContext.links;
+ if (links.length === 0) {
+ console.warn("Empty release with no links! This should never happen");
+ return;
+ }
+ const firstLink = ConnectingLinkImpl.createFromPlainObject(links[0]);
+ const mouseEvent = e.detail.originalEvent;
+ const commonOptions = {
+ e: mouseEvent,
+ allow_searchbox: true,
+ showSearchBox: /* @__PURE__ */ __name(() => showSearchBox(e), "showSearchBox")
+ };
+ const connectionOptions = firstLink.output ? { nodeFrom: firstLink.node, slotFrom: firstLink.output } : { nodeTo: firstLink.node, slotTo: firstLink.input };
+ canvasStore.canvas.showConnectionMenu({
+ ...connectionOptions,
+ ...commonOptions
+ });
+ }, "showContextMenu");
+ const canvasStore = useCanvasStore();
+ watchEffect(() => {
+ if (canvasStore.canvas) {
+ LiteGraph.release_link_on_empty_shows_menu = false;
+ canvasStore.canvas.allow_searchbox = false;
+ }
+ });
+ const canvasEventHandler = /* @__PURE__ */ __name((e) => {
+ if (e.detail.subType === "empty-double-click") {
+ showSearchBox(e);
+ } else if (e.detail.subType === "empty-release") {
+ handleCanvasEmptyRelease(e);
+ } else if (e.detail.subType === "group-double-click") {
+ const group = e.detail.group;
+ const [x, y] = group.pos;
+ const relativeY = e.detail.originalEvent.canvasY - y;
+ if (relativeY > group.titleHeight) {
+ showSearchBox(e);
+ }
+ }
+ }, "canvasEventHandler");
+ const linkReleaseAction = computed(() => {
+ return settingStore.get("Comfy.LinkRelease.Action");
+ });
+ const linkReleaseActionShift = computed(() => {
+ return settingStore.get("Comfy.LinkRelease.ActionShift");
+ });
+ const handleCanvasEmptyRelease = /* @__PURE__ */ __name((e) => {
+ const originalEvent = e.detail.originalEvent;
+ const shiftPressed = originalEvent.shiftKey;
+ const action = shiftPressed ? linkReleaseActionShift.value : linkReleaseAction.value;
+ switch (action) {
+ case LinkReleaseTriggerAction.SEARCH_BOX:
+ showSearchBox(e);
+ break;
+ case LinkReleaseTriggerAction.CONTEXT_MENU:
+ showContextMenu(e);
+ break;
+ case LinkReleaseTriggerAction.NO_ACTION:
+ default:
+ break;
+ }
+ }, "handleCanvasEmptyRelease");
+ onMounted(() => {
+ document.addEventListener("litegraph:canvas", canvasEventHandler);
+ });
+ onUnmounted(() => {
+ document.removeEventListener("litegraph:canvas", canvasEventHandler);
+ });
+ return (_ctx, _cache) => {
+ return openBlock(), createElementBlock("div", null, [
+ createVNode(unref(script$f), {
+ visible: visible.value,
+ "onUpdate:visible": _cache[0] || (_cache[0] = ($event) => visible.value = $event),
+ modal: "",
+ "dismissable-mask": dismissable.value,
+ onHide: clearFilters,
+ pt: {
+ root: {
+ class: "invisible-dialog-root",
+ role: "search"
+ },
+ mask: { class: "node-search-box-dialog-mask" },
+ transition: {
+ enterFromClass: "opacity-0 scale-75",
+ // 100ms is the duration of the transition in the dialog component
+ enterActiveClass: "transition-all duration-100 ease-out",
+ leaveActiveClass: "transition-all duration-100 ease-in",
+ leaveToClass: "opacity-0 scale-75"
+ }
+ }
+ }, {
+ container: withCtx(() => [
+ createVNode(NodeSearchBox, {
+ filters: nodeFilters.value,
+ onAddFilter: addFilter,
+ onRemoveFilter: removeFilter,
+ onAddNode: addNode
+ }, null, 8, ["filters"])
+ ]),
+ _: 1
+ }, 8, ["visible", "dismissable-mask"])
+ ]);
+ };
+ }
+});
+const _sfc_main$2 = /* @__PURE__ */ defineComponent({
+ __name: "NodeTooltip",
+ setup(__props) {
+ let idleTimeout;
+ const nodeDefStore = useNodeDefStore();
+ const settingStore = useSettingStore();
+ const tooltipRef = ref();
+ const tooltipText = ref("");
+ const left = ref();
+ const top = ref();
+ const getHoveredWidget = /* @__PURE__ */ __name(() => {
+ const node = app.canvas.node_over;
+ if (!node.widgets) return;
+ const graphPos = app.canvas.graph_mouse;
+ const x = graphPos[0] - node.pos[0];
+ const y = graphPos[1] - node.pos[1];
+ for (const w of node.widgets) {
+ let widgetWidth, widgetHeight;
+ if (w.computeSize) {
+ ;
+ [widgetWidth, widgetHeight] = w.computeSize(node.size[0]);
+ } else {
+ widgetWidth = w.width || node.size[0];
+ widgetHeight = LiteGraph.NODE_WIDGET_HEIGHT;
+ }
+ if (w.last_y !== void 0 && x >= 6 && x <= widgetWidth - 12 && y >= w.last_y && y <= w.last_y + widgetHeight) {
+ return w;
+ }
+ }
+ }, "getHoveredWidget");
+ const hideTooltip = /* @__PURE__ */ __name(() => tooltipText.value = null, "hideTooltip");
+ const showTooltip = /* @__PURE__ */ __name(async (tooltip) => {
+ if (!tooltip) return;
+ left.value = app.canvas.mouse[0] + "px";
+ top.value = app.canvas.mouse[1] + "px";
+ tooltipText.value = tooltip;
+ await nextTick();
+ const rect = tooltipRef.value.getBoundingClientRect();
+ if (rect.right > window.innerWidth) {
+ left.value = app.canvas.mouse[0] - rect.width + "px";
+ }
+ if (rect.top < 0) {
+ top.value = app.canvas.mouse[1] + rect.height + "px";
+ }
+ }, "showTooltip");
+ const onIdle = /* @__PURE__ */ __name(() => {
+ const { canvas } = app;
+ const node = canvas.node_over;
+ if (!node) return;
+ const ctor = node.constructor;
+ const nodeDef = nodeDefStore.nodeDefsByName[node.type];
+ if (ctor.title_mode !== LiteGraph.NO_TITLE && canvas.graph_mouse[1] < node.pos[1]) {
+ return showTooltip(nodeDef.description);
+ }
+ if (node.flags?.collapsed) return;
+ const inputSlot = canvas.isOverNodeInput(
+ node,
+ canvas.graph_mouse[0],
+ canvas.graph_mouse[1],
+ [0, 0]
+ );
+ if (inputSlot !== -1) {
+ const inputName = node.inputs[inputSlot].name;
+ return showTooltip(nodeDef.input.getInput(inputName)?.tooltip);
+ }
+ const outputSlot = canvas.isOverNodeOutput(
+ node,
+ canvas.graph_mouse[0],
+ canvas.graph_mouse[1],
+ [0, 0]
+ );
+ if (outputSlot !== -1) {
+ return showTooltip(nodeDef.output.all?.[outputSlot].tooltip);
+ }
+ const widget = getHoveredWidget();
+ if (widget && !widget.element) {
+ return showTooltip(
+ widget.tooltip ?? nodeDef.input.getInput(widget.name)?.tooltip
+ );
+ }
+ }, "onIdle");
+ const onMouseMove = /* @__PURE__ */ __name((e) => {
+ hideTooltip();
+ clearTimeout(idleTimeout);
+ if (e.target.nodeName !== "CANVAS") return;
+ idleTimeout = window.setTimeout(onIdle, 500);
+ }, "onMouseMove");
+ watch(
+ () => settingStore.get("Comfy.EnableTooltips"),
+ (enabled) => {
+ if (enabled) {
+ window.addEventListener("mousemove", onMouseMove);
+ window.addEventListener("click", hideTooltip);
+ } else {
+ window.removeEventListener("mousemove", onMouseMove);
+ window.removeEventListener("click", hideTooltip);
+ }
+ },
+ { immediate: true }
+ );
+ onBeforeUnmount(() => {
+ window.removeEventListener("mousemove", onMouseMove);
+ window.removeEventListener("click", hideTooltip);
+ });
+ return (_ctx, _cache) => {
+ return tooltipText.value ? (openBlock(), createElementBlock("div", {
+ key: 0,
+ ref_key: "tooltipRef",
+ ref: tooltipRef,
+ class: "node-tooltip",
+ style: normalizeStyle({ left: left.value, top: top.value })
+ }, toDisplayString(tooltipText.value), 5)) : createCommentVNode("", true);
+ };
+ }
+});
+const NodeTooltip = /* @__PURE__ */ _export_sfc(_sfc_main$2, [["__scopeId", "data-v-e0597bf9"]]);
+const _sfc_main$1 = /* @__PURE__ */ defineComponent({
+ __name: "GraphCanvas",
+ emits: ["ready"],
+ setup(__props, { emit: __emit }) {
+ const emit = __emit;
+ const canvasRef = ref(null);
+ const settingStore = useSettingStore();
+ const nodeDefStore = useNodeDefStore();
+ const workspaceStore = useWorkspaceStore();
+ const canvasStore = useCanvasStore();
+ const betaMenuEnabled = computed(
+ () => settingStore.get("Comfy.UseNewMenu") !== "Disabled"
+ );
+ watchEffect(() => {
+ const canvasInfoEnabled = settingStore.get("Comfy.Graph.CanvasInfo");
+ if (canvasStore.canvas) {
+ canvasStore.canvas.show_info = canvasInfoEnabled;
+ }
+ });
+ watchEffect(() => {
+ const zoomSpeed = settingStore.get("Comfy.Graph.ZoomSpeed");
+ if (canvasStore.canvas) {
+ canvasStore.canvas.zoom_speed = zoomSpeed;
+ }
+ });
+ watchEffect(() => {
+ nodeDefStore.showDeprecated = settingStore.get("Comfy.Node.ShowDeprecated");
+ });
+ watchEffect(() => {
+ nodeDefStore.showExperimental = settingStore.get(
+ "Comfy.Node.ShowExperimental"
+ );
+ });
+ watchEffect(() => {
+ const spellcheckEnabled = settingStore.get("Comfy.TextareaWidget.Spellcheck");
+ const textareas = document.querySelectorAll("textarea.comfy-multiline-input");
+ textareas.forEach((textarea) => {
+ textarea.spellcheck = spellcheckEnabled;
+ textarea.focus();
+ textarea.blur();
+ });
+ });
+ let dropTargetCleanup = /* @__PURE__ */ __name(() => {
+ }, "dropTargetCleanup");
+ onMounted(async () => {
+ window["LiteGraph"] = LiteGraph;
+ window["LGraph"] = LGraph;
+ window["LLink"] = LLink;
+ window["LGraphNode"] = LGraphNode;
+ window["LGraphGroup"] = LGraphGroup;
+ window["DragAndScale"] = DragAndScale;
+ window["LGraphCanvas"] = LGraphCanvas;
+ window["ContextMenu"] = ContextMenu;
+ window["LGraphBadge"] = LGraphBadge$1;
+ app.vueAppReady = true;
+ workspaceStore.spinner = true;
+ await app.setup(canvasRef.value);
+ canvasStore.canvas = app.canvas;
+ workspaceStore.spinner = false;
+ window["app"] = app;
+ window["graph"] = app.graph;
+ dropTargetCleanup = dropTargetForElements({
+ element: canvasRef.value,
+ onDrop: /* @__PURE__ */ __name((event) => {
+ const loc = event.location.current.input;
+ const dndData = event.source.data;
+ if (dndData.type === "tree-explorer-node") {
+ const node = dndData.data;
+ if (node.data instanceof ComfyNodeDefImpl) {
+ const nodeDef = node.data;
+ const pos = app.clientPosToCanvasPos([
+ loc.clientX - 20,
+ loc.clientY
+ ]);
+ app.addNodeOnGraph(nodeDef, { pos });
+ }
+ }
+ }, "onDrop")
+ });
+ useNodeBookmarkStore().migrateLegacyBookmarks();
+ useNodeDefStore().nodeSearchService.endsWithFilterStartSequence("");
+ useNodeFrequencyStore().loadNodeFrequencies();
+ emit("ready");
+ });
+ onUnmounted(() => {
+ dropTargetCleanup();
+ });
+ return (_ctx, _cache) => {
+ return openBlock(), createElementBlock(Fragment, null, [
+ (openBlock(), createBlock(Teleport, { to: ".graph-canvas-container" }, [
+ betaMenuEnabled.value ? (openBlock(), createBlock(LiteGraphCanvasSplitterOverlay, { key: 0 }, {
+ "side-bar-panel": withCtx(() => [
+ createVNode(SideToolbar)
+ ]),
+ _: 1
+ })) : createCommentVNode("", true),
+ createVNode(TitleEditor),
+ createBaseVNode("canvas", {
+ ref_key: "canvasRef",
+ ref: canvasRef,
+ id: "graph-canvas",
+ tabindex: "1"
+ }, null, 512)
+ ])),
+ createVNode(_sfc_main$3),
+ createVNode(NodeTooltip)
+ ], 64);
+ };
+ }
+});
+const _sfc_main = /* @__PURE__ */ defineComponent({
+ __name: "GraphView",
+ setup(__props) {
+ return (_ctx, _cache) => {
+ return openBlock(), createBlock(_sfc_main$1);
+ };
+ }
+});
+export {
+ _sfc_main as default
+};
+//# sourceMappingURL=GraphView-DN9xGvF3.js.map
diff --git a/web/assets/GraphView-DN9xGvF3.js.map b/web/assets/GraphView-DN9xGvF3.js.map
new file mode 100644
index 000000000..147e0c75e
--- /dev/null
+++ b/web/assets/GraphView-DN9xGvF3.js.map
@@ -0,0 +1 @@
+{"version":3,"file":"GraphView-DN9xGvF3.js","sources":["../../src/components/graph/TitleEditor.vue","../../node_modules/primevue/overlaybadge/style/index.mjs","../../node_modules/primevue/overlaybadge/index.mjs","../../src/components/sidebar/SidebarIcon.vue","../../src/components/sidebar/SidebarThemeToggleIcon.vue","../../src/components/sidebar/SidebarSettingsToggleIcon.vue","../../src/components/sidebar/SideToolbar.vue","../../node_modules/primevue/splitter/style/index.mjs","../../node_modules/primevue/splitter/index.mjs","../../node_modules/primevue/splitterpanel/style/index.mjs","../../node_modules/primevue/splitterpanel/index.mjs","../../src/components/LiteGraphCanvasSplitterOverlay.vue","../../node_modules/primevue/autocomplete/style/index.mjs","../../node_modules/primevue/autocomplete/index.mjs","../../src/components/primevueOverride/AutoCompletePlus.vue","../../src/components/searchbox/NodeSearchItem.vue","../../src/components/searchbox/NodeSearchBox.vue","../../src/types/litegraphTypes.ts","../../src/components/searchbox/NodeSearchBoxPopover.vue","../../src/components/graph/NodeTooltip.vue","../../src/components/graph/GraphCanvas.vue"],"sourcesContent":["\n \n \n
\n \n\n\n\n\n","import BaseStyle from '@primevue/core/base/style';\n\nvar theme = function theme(_ref) {\n var dt = _ref.dt;\n return \"\\n.p-overlaybadge {\\n position: relative;\\n}\\n\\n.p-overlaybadge .p-badge {\\n position: absolute;\\n top: 0;\\n right: 0;\\n transform: translate(50%, -50%);\\n transform-origin: 100% 0;\\n margin: 0;\\n outline-width: \".concat(dt('overlaybadge.outline.width'), \";\\n outline-style: solid;\\n outline-color: \").concat(dt('overlaybadge.outline.color'), \";\\n}\\n\");\n};\nvar classes = {\n root: 'p-overlaybadge'\n};\nvar OverlayBadgeStyle = BaseStyle.extend({\n name: 'overlaybadge',\n theme: theme,\n classes: classes\n});\n\nexport { OverlayBadgeStyle as default };\n//# sourceMappingURL=index.mjs.map\n","import Badge from 'primevue/badge';\nimport OverlayBadgeStyle from 'primevue/overlaybadge/style';\nimport { resolveComponent, openBlock, createElementBlock, mergeProps, renderSlot, createVNode } from 'vue';\n\nvar script$1 = {\n name: 'OverlayBadge',\n \"extends\": Badge,\n style: OverlayBadgeStyle,\n provide: function provide() {\n return {\n $pcOverlayBadge: this,\n $parentInstance: this\n };\n }\n};\n\nvar script = {\n name: 'OverlayBadge',\n \"extends\": script$1,\n inheritAttrs: false,\n components: {\n Badge: Badge\n }\n};\n\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n var _component_Badge = resolveComponent(\"Badge\");\n return openBlock(), createElementBlock(\"div\", mergeProps({\n \"class\": _ctx.cx('root')\n }, _ctx.ptmi('root')), [renderSlot(_ctx.$slots, \"default\"), createVNode(_component_Badge, mergeProps(_ctx.$props, {\n pt: _ctx.ptm('pcBadge')\n }), null, 16, [\"pt\"])], 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","\n \n \n \n \n \n \n \n \n \n\n\n\n\n\n\n","\n \n \n\n\n","\n \n \n\n\n","\n \n \n \n \n \n \n
\n \n \n \n \n\n\n\n\n\n\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","\n \n \n \n \n \n
\n \n \n \n \n \n \n\n\n\n\n\n\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': instance.hasFluid\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 { 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 { UniqueComponentId, ConnectedOverlayScrollHandler } from '@primevue/core/utils';\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\": null\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 inject: {\n $pcFluid: {\n \"default\": null\n }\n },\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 var target = this.multiple ? this.$refs.focusInput : this.$refs.focusInput.$el;\n focus(target);\n query = target.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 hasFluid: function hasFluid() {\n return isEmpty(this.fluid) ? !!this.$pcFluid : this.fluid;\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 fluid: $options.hasFluid,\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\", \"fluid\", \"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","\n\n","\n \n
\n
\n \n \n \n \n \n \n \n \n
\n
\n {{ nodeDef.category.replaceAll('/', ' > ') }}\n
\n
\n
\n \n \n 0\"\n :value=\"formatNumberWithSuffix(nodeFrequency, { roundToInt: true })\"\n severity=\"secondary\"\n />\n \n {{ nodeDef.nodeSource.displayText }}\n \n
\n
\n \n\n\n\n\n","\n \n
\n \n
\n\n
\n
\n \n Add node filter condition \n \n \n \n
\n \n\n
\n \n \n \n \n \n \n \n \n
\n \n\n\n\n\n","import type {\n ConnectingLink,\n LGraphNode,\n Vector2,\n INodeInputSlot,\n INodeOutputSlot,\n INodeSlot\n} from '@comfyorg/litegraph'\nimport { LiteGraph } from '@comfyorg/litegraph'\n\nexport class ConnectingLinkImpl implements ConnectingLink {\n node: LGraphNode\n slot: number\n input: INodeInputSlot | null\n output: INodeOutputSlot | null\n pos: Vector2\n\n constructor(\n node: LGraphNode,\n slot: number,\n input: INodeInputSlot | null,\n output: INodeOutputSlot | null,\n pos: Vector2\n ) {\n this.node = node\n this.slot = slot\n this.input = input\n this.output = output\n this.pos = pos\n }\n\n static createFromPlainObject(obj: ConnectingLink) {\n return new ConnectingLinkImpl(\n obj.node,\n obj.slot,\n obj.input,\n obj.output,\n obj.pos\n )\n }\n\n get type(): string | null {\n const result = this.input ? this.input.type : this.output.type\n return result === -1 ? null : result\n }\n\n /**\n * Which slot type is release and need to be reconnected.\n * - 'output' means we need a new node's outputs slot to connect with this link\n */\n get releaseSlotType(): 'input' | 'output' {\n return this.output ? 'input' : 'output'\n }\n\n connectTo(newNode: LGraphNode) {\n const newNodeSlots =\n this.releaseSlotType === 'output' ? newNode.outputs : newNode.inputs\n if (!newNodeSlots) return\n\n const newNodeSlot = newNodeSlots.findIndex((slot: INodeSlot) =>\n LiteGraph.isValidConnection(slot.type, this.type)\n )\n\n if (newNodeSlot === -1) {\n console.warn(\n `Could not find slot with type ${this.type} on node ${newNode.title}. This should never happen`\n )\n return\n }\n\n if (this.releaseSlotType === 'input') {\n this.node.connect(this.slot, newNode, newNodeSlot)\n } else {\n newNode.connect(newNodeSlot, this.node, this.slot)\n }\n }\n}\n\nexport type CanvasDragAndDropData = {\n type: 'add-node'\n data: T\n}\n","\n \n \n \n \n \n \n
\n \n\n\n\n\n","\n \n {{ tooltipText }}\n
\n \n\n\n\n\n","\n \n \n \n \n \n \n \n \n \n \n \n \n\n\n"],"names":["theme","classes","script$1","Badge","script","render","inlineStyles","root","BaseComponent","provide","_toConsumableArray","_arrayWithoutHoles","_iterableToArray","_unsupportedIterableToArray","_nonIterableSpread","_arrayLikeToArray","panels","_hoisted_1","_hoisted_2","createElementVNode","data","getPTOptions","o","mounted","beforeUnmount","option","_hide","InputText","VirtualScroller","Portal","ChevronDownIcon","SpinnerIcon","Chip","r","_hoisted_3","_hoisted_4","_hoisted_5","_hoisted_6","_hoisted_7","_hoisted_8","ref","_sfc_main","AutoComplete","suggestions","search","comfyApp","LGraphBadge"],"mappings":";;;;;;AAwBA,UAAM,eAAe;AAEf,UAAA,YAAY,IAAI,KAAK;AACrB,UAAA,cAAc,IAAI,EAAE;AAC1B,UAAM,aAAa,IAAmB;AAAA,MACpC,UAAU;AAAA,MACV,MAAM;AAAA,MACN,KAAK;AAAA,MACL,OAAO;AAAA,MACP,QAAQ;AAAA,MACR,UAAU;AAAA,IAAA,CACX;AAED,UAAM,mBAAmB;AACzB,UAAM,cAAc;AACd,UAAA,0BAA0B,IAAI,IAAI;AAElC,UAAA,SAAS,wBAAC,aAAqB;AACnC,UAAI,iBAAiB,qBAAqB,SAAS,KAAA,MAAW,IAAI;AAC/C,yBAAA,kBAAkB,QAAQ,SAAS,KAAK;AACrD,YAAA,MAAM,eAAe,MAAM,IAAI;AAAA,MACrC;AACA,gBAAU,QAAQ;AAClB,uBAAiB,oBAAoB;AACzB,kBAAA,OAAQ,mBAAmB,wBAAwB;AAAA,IAAA,GAPlD;AAUf;AAAA,MACE,MAAM,iBAAiB;AAAA,MACvB,CAAC,WAAW;AACV,YAAI,WAAW,MAAM;AACnB;AAAA,QACF;AACA,oBAAY,QAAQ,OAAO;AAC3B,kBAAU,QAAQ;AACM,gCAAA,QAAQ,YAAY,OAAQ;AACpD,oBAAY,OAAQ,mBAAmB;AAEvC,YAAI,kBAAkB,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jB,gBAAA,KAAK,gBAAgB,kBAAkB;AACzC,oBAAM,UAAU,KAAK;AAGf,oBAAA,MAAMA,IAAS,qBAAqB;AAAA,gBACxC,IAAI,UAAU;AAAA,gBACd,IAAI;AAAA,cAAA,CACL;AACDA,kBAAS,eAAe,SAAS,EAAE,IAAK,CAAA;AAAA,YAC1C;AAAA,UACF;AAAA,QACF,GAjBQ;AAAA,MAiBR,CACD;AAGD,2BAAA,EAAuB;AAIP,wBAAE,kBAAkB,4BAA4B,EAAE;AAGlE,4BAAA,EAAwB;AACxB,WAAK,OAAO;AAAA,IAAA,CACb;AAED,gBAAY,MAAM;AACE;IAAA,CACnB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","x_google_ignoreList":[1,2,7,8,9,10,12,13]}
\ No newline at end of file
diff --git a/web/assets/GraphView-DXU9yRen.css b/web/assets/GraphView-DXU9yRen.css
new file mode 100644
index 000000000..493781ff1
--- /dev/null
+++ b/web/assets/GraphView-DXU9yRen.css
@@ -0,0 +1,158 @@
+
+.group-title-editor.node-title-editor[data-v-fc3f26e3] {
+ z-index: 9999;
+ padding: 0.25rem;
+}
+[data-v-fc3f26e3] .editable-text {
+ width: 100%;
+ height: 100%;
+}
+[data-v-fc3f26e3] .editable-text input {
+ width: 100%;
+ height: 100%;
+ /* Override the default font size */
+ font-size: inherit;
+}
+
+.side-bar-button-icon {
+ font-size: var(--sidebar-icon-size) !important;
+}
+.side-bar-button-selected .side-bar-button-icon {
+ font-size: var(--sidebar-icon-size) !important;
+ font-weight: bold;
+}
+
+.side-bar-button[data-v-caa3ee9c] {
+ width: var(--sidebar-width);
+ height: var(--sidebar-width);
+ border-radius: 0;
+}
+.comfyui-body-left .side-bar-button.side-bar-button-selected[data-v-caa3ee9c],
+.comfyui-body-left .side-bar-button.side-bar-button-selected[data-v-caa3ee9c]:hover {
+ border-left: 4px solid var(--p-button-text-primary-color);
+}
+.comfyui-body-right .side-bar-button.side-bar-button-selected[data-v-caa3ee9c],
+.comfyui-body-right .side-bar-button.side-bar-button-selected[data-v-caa3ee9c]:hover {
+ border-right: 4px solid var(--p-button-text-primary-color);
+}
+
+:root {
+ --sidebar-width: 64px;
+ --sidebar-icon-size: 1.5rem;
+}
+:root .small-sidebar {
+ --sidebar-width: 40px;
+ --sidebar-icon-size: 1rem;
+}
+
+.side-tool-bar-container[data-v-ed7a1148] {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+
+ pointer-events: auto;
+
+ width: var(--sidebar-width);
+ height: 100%;
+
+ background-color: var(--comfy-menu-bg);
+ color: var(--fg-color);
+}
+.side-tool-bar-end[data-v-ed7a1148] {
+ align-self: flex-end;
+ margin-top: auto;
+}
+.sidebar-content-container[data-v-ed7a1148] {
+ height: 100%;
+ overflow-y: auto;
+}
+
+.p-splitter-gutter {
+ pointer-events: auto;
+}
+.gutter-hidden {
+ display: none !important;
+}
+
+.side-bar-panel[data-v-edca8328] {
+ background-color: var(--bg-color);
+ pointer-events: auto;
+}
+.splitter-overlay[data-v-edca8328] {
+ width: 100%;
+ height: 100%;
+ position: absolute;
+ top: 0;
+ left: 0;
+ background-color: transparent;
+ pointer-events: none;
+ /* Set it the same as the ComfyUI menu */
+ /* Note: Lite-graph DOM widgets have the same z-index as the node id, so
+ 999 should be sufficient to make sure splitter overlays on node's DOM
+ widgets */
+ z-index: 999;
+ border: none;
+}
+
+[data-v-37f672ab] .highlight {
+ background-color: var(--p-primary-color);
+ color: var(--p-primary-contrast-color);
+ font-weight: bold;
+ border-radius: 0.25rem;
+ padding: 0rem 0.125rem;
+ margin: -0.125rem 0.125rem;
+}
+
+.comfy-vue-node-search-container[data-v-2d409367] {
+ display: flex;
+ width: 100%;
+ min-width: 26rem;
+ align-items: center;
+ justify-content: center;
+}
+.comfy-vue-node-search-container[data-v-2d409367] * {
+ pointer-events: auto;
+}
+.comfy-vue-node-preview-container[data-v-2d409367] {
+ position: absolute;
+ left: -350px;
+ top: 50px;
+}
+.comfy-vue-node-search-box[data-v-2d409367] {
+ z-index: 10;
+ flex-grow: 1;
+}
+._filter-button[data-v-2d409367] {
+ z-index: 10;
+}
+._dialog[data-v-2d409367] {
+ min-width: 26rem;
+}
+
+.invisible-dialog-root {
+ width: 30%;
+ min-width: 24rem;
+ max-width: 48rem;
+ border: 0 !important;
+ background-color: transparent !important;
+ margin-top: 25vh;
+}
+.node-search-box-dialog-mask {
+ align-items: flex-start !important;
+}
+
+.node-tooltip[data-v-e0597bf9] {
+ background: var(--comfy-input-bg);
+ border-radius: 5px;
+ box-shadow: 0 0 5px rgba(0, 0, 0, 0.4);
+ color: var(--input-text);
+ font-family: sans-serif;
+ left: 0;
+ max-width: 30vw;
+ padding: 4px 8px;
+ position: absolute;
+ top: 0;
+ transform: translate(5px, calc(-100% - 5px));
+ white-space: pre-wrap;
+ z-index: 99999;
+}
diff --git a/web/assets/index-8NH3XvqK.css b/web/assets/index-8NH3XvqK.css
new file mode 100644
index 000000000..cbe95b755
--- /dev/null
+++ b/web/assets/index-8NH3XvqK.css
@@ -0,0 +1,4582 @@
+
+.comfy-image-wrap[data-v-9bc23daf] {
+ display: contents;
+}
+.comfy-image-blur[data-v-9bc23daf] {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ -o-object-fit: cover;
+ object-fit: cover;
+}
+.comfy-image-main[data-v-9bc23daf] {
+ width: 100%;
+ height: 100%;
+ -o-object-fit: cover;
+ object-fit: cover;
+ -o-object-position: center;
+ object-position: center;
+ z-index: 1;
+}
+.contain .comfy-image-wrap[data-v-9bc23daf] {
+ position: relative;
+ width: 100%;
+ height: 100%;
+}
+.contain .comfy-image-main[data-v-9bc23daf] {
+ -o-object-fit: contain;
+ object-fit: contain;
+ -webkit-backdrop-filter: blur(10px);
+ backdrop-filter: blur(10px);
+ position: absolute;
+}
+.broken-image-placeholder[data-v-9bc23daf] {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ width: 100%;
+ height: 100%;
+ margin: 2rem;
+}
+.broken-image-placeholder i[data-v-9bc23daf] {
+ font-size: 3rem;
+ margin-bottom: 0.5rem;
+}
+
+:root {
+ --red-600: #dc3545;
+}
+
+.comfy-missing-nodes[data-v-0a88b934] {
+ font-family: monospace;
+ color: var(--red-600);
+ padding: 1.5rem;
+ background-color: var(--surface-ground);
+ border-radius: var(--border-radius);
+ box-shadow: var(--card-shadow);
+}
+.warning-title[data-v-0a88b934] {
+ margin-top: 0;
+ margin-bottom: 1rem;
+}
+.warning-description[data-v-0a88b934] {
+ margin-bottom: 1rem;
+}
+.missing-nodes-list[data-v-0a88b934] {
+ max-height: 300px;
+ overflow-y: auto;
+}
+.missing-nodes-list.maximized[data-v-0a88b934] {
+ max-height: unset;
+}
+.missing-node-item[data-v-0a88b934] {
+ display: flex;
+ align-items: center;
+ padding: 0.5rem;
+}
+.node-type[data-v-0a88b934] {
+ font-weight: 600;
+ color: var(--text-color);
+}
+.node-hint[data-v-0a88b934] {
+ margin-left: 0.5rem;
+ font-style: italic;
+ color: var(--text-color-secondary);
+}
+[data-v-0a88b934] .p-button {
+ margin-left: auto;
+}
+.added-nodes-warning[data-v-0a88b934] {
+ margin-top: 1rem;
+ font-style: italic;
+}
+
+:root {
+ --red-600: #dc3545;
+ --green-500: #28a745;
+}
+
+.comfy-missing-models[data-v-a71fe7ef] {
+ font-family: monospace;
+ color: var(--red-600);
+ padding: 1.5rem;
+ background-color: var(--surface-ground);
+ border-radius: var(--border-radius);
+ box-shadow: var(--card-shadow);
+}
+.warning-title[data-v-a71fe7ef] {
+ margin-top: 0;
+ margin-bottom: 1rem;
+}
+.warning-description[data-v-a71fe7ef] {
+ margin-bottom: 1rem;
+}
+.missing-models-list[data-v-a71fe7ef] {
+ max-height: 300px;
+ overflow-y: auto;
+}
+.missing-models-list.maximized[data-v-a71fe7ef] {
+ max-height: unset;
+}
+.missing-model-item[data-v-a71fe7ef] {
+ display: flex;
+ align-items: flex-start;
+ padding: 0.5rem;
+ position: relative;
+ overflow: hidden;
+ width: 100%;
+}
+.missing-model-item[data-v-a71fe7ef]::before {
+ content: '';
+ position: absolute;
+ top: 0;
+ left: 0;
+ height: 100%;
+ width: var(--progress);
+ background-color: var(--green-500);
+ opacity: 0.2;
+ transition: width 0.3s ease;
+}
+.model-info[data-v-a71fe7ef] {
+ flex: 1;
+ min-width: 0;
+ z-index: 1;
+ display: flex;
+ flex-direction: column;
+ margin-right: 1rem;
+ overflow: hidden;
+}
+.model-details[data-v-a71fe7ef] {
+ display: flex;
+ align-items: center;
+ flex-wrap: wrap;
+}
+.model-type[data-v-a71fe7ef] {
+ font-weight: 600;
+ color: var(--text-color);
+ margin-right: 0.5rem;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+.model-hint[data-v-a71fe7ef] {
+ font-style: italic;
+ color: var(--text-color-secondary);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+.model-error[data-v-a71fe7ef] {
+ color: var(--red-600);
+ font-size: 0.8rem;
+ margin-top: 0.25rem;
+}
+.model-action[data-v-a71fe7ef] {
+ display: flex;
+ align-items: center;
+ justify-content: flex-end;
+ z-index: 1;
+}
+.model-action-button[data-v-a71fe7ef] {
+ min-width: 80px;
+}
+.download-progress[data-v-a71fe7ef],
+.download-complete[data-v-a71fe7ef],
+.download-error[data-v-a71fe7ef] {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ min-width: 80px;
+}
+.progress-text[data-v-a71fe7ef] {
+ font-size: 0.8rem;
+ color: var(--text-color);
+}
+.download-complete i[data-v-a71fe7ef],
+.download-error i[data-v-a71fe7ef] {
+ font-size: 1.2rem;
+}
+
+.input-slider[data-v-640d580c] {
+ display: flex;
+ align-items: center;
+ gap: 1rem;
+}
+.slider-part[data-v-640d580c] {
+ flex-grow: 1;
+}
+.input-part[data-v-640d580c] {
+ width: 5rem !important;
+}
+
+.info-chip[data-v-d24ca1bc] {
+ background: transparent;
+}
+.setting-item[data-v-d24ca1bc] {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ margin-bottom: 1rem;
+}
+.setting-label[data-v-d24ca1bc] {
+ display: flex;
+ align-items: center;
+ flex: 1;
+}
+.setting-input[data-v-d24ca1bc] {
+ flex: 1;
+ display: flex;
+ justify-content: flex-end;
+ margin-left: 1rem;
+}
+
+/* Ensure PrimeVue components take full width of their container */
+.setting-input[data-v-d24ca1bc] .p-inputtext,
+.setting-input[data-v-d24ca1bc] .input-slider,
+.setting-input[data-v-d24ca1bc] .p-select,
+.setting-input[data-v-d24ca1bc] .p-togglebutton {
+ width: 100%;
+ max-width: 200px;
+}
+.setting-input[data-v-d24ca1bc] .p-inputtext {
+ max-width: unset;
+}
+
+/* Special case for ToggleSwitch to align it to the right */
+.setting-input[data-v-d24ca1bc] .p-toggleswitch {
+ margin-left: auto;
+}
+
+[data-v-a4c03005] .i-badge {
+
+ --tw-bg-opacity: 1;
+
+ background-color: rgb(150 206 76 / var(--tw-bg-opacity));
+
+ --tw-text-opacity: 1;
+
+ color: rgb(255 255 255 / var(--tw-text-opacity))
+}
+[data-v-a4c03005] .o-badge {
+
+ --tw-bg-opacity: 1;
+
+ background-color: rgb(239 68 68 / var(--tw-bg-opacity));
+
+ --tw-text-opacity: 1;
+
+ color: rgb(255 255 255 / var(--tw-text-opacity))
+}
+[data-v-a4c03005] .c-badge {
+
+ --tw-bg-opacity: 1;
+
+ background-color: rgb(66 153 225 / var(--tw-bg-opacity));
+
+ --tw-text-opacity: 1;
+
+ color: rgb(255 255 255 / var(--tw-text-opacity))
+}
+[data-v-a4c03005] .s-badge {
+
+ --tw-bg-opacity: 1;
+
+ background-color: rgb(234 179 8 / var(--tw-bg-opacity))
+}
+
+.search-box-input[data-v-f28148d1] {
+ width: 100%;
+ padding-left: 36px;
+}
+.search-box-input.with-filter[data-v-f28148d1] {
+ padding-right: 36px;
+}
+.p-button.p-inputicon[data-v-f28148d1] {
+ padding: 0;
+ width: auto;
+ border: none !important;
+}
+
+.no-results-placeholder[data-v-c19e9e10] {
+ height: 100%;
+ padding: 2rem;
+}
+.no-results-placeholder[data-v-c19e9e10] .p-card {
+ background-color: var(--surface-ground);
+ text-align: center;
+ box-shadow: unset;
+}
+.no-results-placeholder h3[data-v-c19e9e10] {
+ color: var(--text-color);
+ margin-bottom: 0.5rem;
+}
+.no-results-placeholder p[data-v-c19e9e10] {
+ color: var(--text-color-secondary);
+ margin-bottom: 1rem;
+}
+
+.settings-tab-panels {
+ padding-top: 0px !important;
+}
+
+.settings-container[data-v-0f66fa3f] {
+ display: flex;
+ height: 70vh;
+ width: 60vw;
+ max-width: 1000px;
+ overflow: hidden;
+ /* Prevents container from scrolling */
+}
+.settings-sidebar[data-v-0f66fa3f] {
+ width: 250px;
+ flex-shrink: 0;
+ /* Prevents sidebar from shrinking */
+ overflow-y: auto;
+ padding: 10px;
+}
+.settings-search-box[data-v-0f66fa3f] {
+ width: 100%;
+ margin-bottom: 10px;
+}
+.settings-content[data-v-0f66fa3f] {
+ flex-grow: 1;
+ overflow-y: auto;
+ /* Allows vertical scrolling */
+}
+
+/* Ensure the Listbox takes full width of the sidebar */
+.settings-sidebar[data-v-0f66fa3f] .p-listbox {
+ width: 100%;
+}
+
+/* Optional: Style scrollbars for webkit browsers */
+.settings-sidebar[data-v-0f66fa3f]::-webkit-scrollbar,
+.settings-content[data-v-0f66fa3f]::-webkit-scrollbar {
+ width: 1px;
+}
+.settings-sidebar[data-v-0f66fa3f]::-webkit-scrollbar-thumb,
+.settings-content[data-v-0f66fa3f]::-webkit-scrollbar-thumb {
+ background-color: transparent;
+}
+@media (max-width: 768px) {
+.settings-container[data-v-0f66fa3f] {
+ flex-direction: column;
+ height: auto;
+}
+.settings-sidebar[data-v-0f66fa3f] {
+ width: 100%;
+}
+}
+
+.pi-cog[data-v-3f3c5ee5] {
+ font-size: 1.25rem;
+ margin-right: 0.5rem;
+}
+.version-tag[data-v-3f3c5ee5] {
+ margin-left: 0.5rem;
+}
+
+.comfy-error-report[data-v-a103fd62] {
+ display: flex;
+ flex-direction: column;
+ gap: 1rem;
+}
+.action-container[data-v-a103fd62] {
+ display: flex;
+ gap: 1rem;
+ justify-content: flex-end;
+}
+.wrapper-pre[data-v-a103fd62] {
+ white-space: pre-wrap;
+ word-wrap: break-word;
+}
+.no-results-placeholder[data-v-a103fd62] {
+ padding-top: 0;
+}
+.lds-ring {
+ display: inline-block;
+ position: relative;
+ width: 1em;
+ height: 1em;
+}
+.lds-ring div {
+ box-sizing: border-box;
+ display: block;
+ position: absolute;
+ width: 100%;
+ height: 100%;
+ border: 0.15em solid #fff;
+ border-radius: 50%;
+ animation: lds-ring 1.2s cubic-bezier(0.5, 0, 0.5, 1) infinite;
+ border-color: #fff transparent transparent transparent;
+}
+.lds-ring div:nth-child(1) {
+ animation-delay: -0.45s;
+}
+.lds-ring div:nth-child(2) {
+ animation-delay: -0.3s;
+}
+.lds-ring div:nth-child(3) {
+ animation-delay: -0.15s;
+}
+@keyframes lds-ring {
+ 0% {
+ transform: rotate(0deg);
+ }
+ 100% {
+ transform: rotate(360deg);
+ }
+}
+.relative {
+ position: relative;
+}
+.hidden {
+ display: none !important;
+}
+.mdi.rotate270::before {
+ transform: rotate(270deg);
+}
+
+/* Generic */
+.comfyui-button {
+ display: flex;
+ align-items: center;
+ gap: 0.5em;
+ cursor: pointer;
+ border: none;
+ border-radius: 4px;
+ padding: 4px 8px;
+ box-sizing: border-box;
+ margin: 0;
+ transition: box-shadow 0.1s;
+}
+
+.comfyui-button:active {
+ box-shadow: inset 1px 1px 10px rgba(0, 0, 0, 0.5);
+}
+
+.comfyui-button:disabled {
+ opacity: 0.5;
+ cursor: not-allowed;
+}
+.primary .comfyui-button,
+.primary.comfyui-button {
+ background-color: var(--primary-bg) !important;
+ color: var(--primary-fg) !important;
+}
+
+.primary .comfyui-button:not(:disabled):hover,
+.primary.comfyui-button:not(:disabled):hover {
+ background-color: var(--primary-hover-bg) !important;
+ color: var(--primary-hover-fg) !important;
+}
+
+/* Popup */
+.comfyui-popup {
+ position: absolute;
+ left: var(--left);
+ right: var(--right);
+ top: var(--top);
+ bottom: var(--bottom);
+ z-index: 2000;
+ max-height: calc(100vh - var(--limit) - 10px);
+ box-shadow: 3px 3px 5px 0px rgba(0, 0, 0, 0.3);
+}
+
+.comfyui-popup:not(.open) {
+ display: none;
+}
+
+.comfyui-popup.right.open {
+ border-top-left-radius: 4px;
+ border-bottom-right-radius: 4px;
+ border-bottom-left-radius: 4px;
+ overflow: hidden;
+}
+/* Split button */
+.comfyui-split-button {
+ position: relative;
+ display: flex;
+}
+
+.comfyui-split-primary {
+ flex: auto;
+}
+
+.comfyui-split-primary .comfyui-button {
+ border-top-right-radius: 0;
+ border-bottom-right-radius: 0;
+ border-right: 1px solid var(--comfy-menu-bg);
+ width: 100%;
+}
+
+.comfyui-split-arrow .comfyui-button {
+ border-top-left-radius: 0;
+ border-bottom-left-radius: 0;
+ padding-left: 2px;
+ padding-right: 2px;
+}
+
+.comfyui-split-button-popup {
+ white-space: nowrap;
+ background-color: var(--content-bg);
+ color: var(--content-fg);
+ display: flex;
+ flex-direction: column;
+ overflow: auto;
+}
+
+.comfyui-split-button-popup.hover {
+ z-index: 2001;
+}
+.comfyui-split-button-popup > .comfyui-button {
+ border: none;
+ background-color: transparent;
+ color: var(--fg-color);
+ padding: 8px 12px 8px 8px;
+}
+
+.comfyui-split-button-popup > .comfyui-button:not(:disabled):hover {
+ background-color: var(--comfy-input-bg);
+}
+
+/* Button group */
+.comfyui-button-group {
+ display: flex;
+ border-radius: 4px;
+ overflow: hidden;
+}
+
+.comfyui-button-group > .comfyui-button,
+.comfyui-button-group > .comfyui-button-wrapper > .comfyui-button {
+ padding: 4px 10px;
+ border-radius: 0;
+}
+
+/* Menu */
+.comfyui-menu {
+ width: 100vw;
+ background: var(--comfy-menu-bg);
+ color: var(--fg-color);
+ font-family: Arial, Helvetica, sans-serif;
+ font-size: 0.8em;
+ display: flex;
+ padding: 4px 8px;
+ align-items: center;
+ gap: 8px;
+ box-sizing: border-box;
+ z-index: 1000;
+ order: 0;
+ grid-column: 1/-1;
+ overflow: auto;
+ max-height: 90vh;
+}
+
+.comfyui-menu>* {
+ flex-shrink: 0;
+}
+.comfyui-menu .mdi::before {
+ font-size: 18px;
+}
+
+.comfyui-menu .comfyui-button {
+ background: var(--comfy-input-bg);
+ color: var(--fg-color);
+ white-space: nowrap;
+}
+
+.comfyui-menu .comfyui-button:not(:disabled):hover {
+ background: var(--border-color);
+ color: var(--content-fg);
+}
+
+.comfyui-menu .comfyui-split-button-popup > .comfyui-button {
+ border-radius: 0;
+ background-color: transparent;
+}
+
+.comfyui-menu .comfyui-split-button-popup > .comfyui-button:not(:disabled):hover {
+ background-color: var(--comfy-input-bg);
+}
+
+.comfyui-menu .comfyui-split-button-popup.left {
+ border-top-right-radius: 4px;
+ border-bottom-left-radius: 4px;
+ border-bottom-right-radius: 4px;
+}
+
+.comfyui-menu .comfyui-button.popup-open {
+ background-color: var(--content-bg);
+ color: var(--content-fg);
+}
+
+.comfyui-menu-push {
+ margin-left: -0.8em;
+ flex: auto;
+}
+
+.comfyui-logo {
+ font-size: 1.2em;
+ margin: 0;
+ -webkit-user-select: none;
+ -moz-user-select: none;
+ user-select: none;
+ cursor: default;
+}
+
+/* Workflows */
+.comfyui-workflows-button {
+ flex-direction: row-reverse;
+ max-width: 200px;
+ position: relative;
+ z-index: 0;
+}
+
+.comfyui-workflows-button.popup-open {
+ border-bottom-left-radius: 0;
+ border-bottom-right-radius: 0;
+}
+.comfyui-workflows-button.unsaved {
+ font-style: italic;
+}
+.comfyui-workflows-button-progress {
+ position: absolute;
+ top: 0;
+ left: 0;
+ background-color: green;
+ height: 100%;
+ border-radius: 4px;
+ z-index: -1;
+}
+
+.comfyui-workflows-button > span {
+ flex: auto;
+ text-align: left;
+ overflow: hidden;
+}
+.comfyui-workflows-button-inner {
+ display: flex;
+ align-items: center;
+ gap: 7px;
+ width: 150px;
+}
+.comfyui-workflows-label {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ direction: rtl;
+ flex: auto;
+ position: relative;
+}
+
+.comfyui-workflows-button.unsaved .comfyui-workflows-label {
+ padding-left: 8px;
+}
+
+.comfyui-workflows-button.unsaved .comfyui-workflows-label:after {
+ content: "*";
+ position: absolute;
+ top: 0;
+ left: 0;
+}
+.comfyui-workflows-button-inner .mdi-graph::before {
+ transform: rotate(-90deg);
+}
+
+.comfyui-workflows-popup {
+ font-family: Arial, Helvetica, sans-serif;
+ font-size: 0.8em;
+ padding: 10px;
+ overflow: auto;
+ background-color: var(--content-bg);
+ color: var(--content-fg);
+ border-top-right-radius: 4px;
+ border-bottom-right-radius: 4px;
+ border-bottom-left-radius: 4px;
+ z-index: 1001;
+}
+
+.comfyui-workflows-panel {
+ min-height: 150px;
+}
+
+.comfyui-workflows-panel .lds-ring {
+ transform: translate(-50%);
+ position: absolute;
+ left: 50%;
+ top: 75px;
+}
+
+.comfyui-workflows-panel h3 {
+ margin: 10px 0 10px 0;
+ font-size: 11px;
+ opacity: 0.8;
+}
+
+.comfyui-workflows-panel section header {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+}
+.comfy-ui-workflows-search .mdi {
+ position: relative;
+ top: 2px;
+ pointer-events: none;
+}
+.comfy-ui-workflows-search input {
+ background-color: var(--comfy-input-bg);
+ color: var(--input-text);
+ border: none;
+ border-radius: 4px;
+ padding: 4px 10px;
+ margin-left: -24px;
+ text-indent: 18px;
+}
+.comfy-ui-workflows-search input:-moz-placeholder-shown {
+ width: 10px;
+}
+.comfy-ui-workflows-search input:placeholder-shown {
+ width: 10px;
+}
+.comfy-ui-workflows-search input:-moz-placeholder-shown:focus {
+ width: auto;
+}
+.comfy-ui-workflows-search input:placeholder-shown:focus {
+ width: auto;
+}
+.comfyui-workflows-actions {
+ display: flex;
+ gap: 10px;
+ margin-bottom: 10px;
+}
+
+.comfyui-workflows-actions .comfyui-button {
+ background: var(--comfy-input-bg);
+ color: var(--input-text);
+}
+
+.comfyui-workflows-actions .comfyui-button:not(:disabled):hover {
+ background: var(--primary-bg);
+ color: var(--primary-fg);
+}
+
+.comfyui-workflows-favorites,
+.comfyui-workflows-open {
+ border-bottom: 1px solid var(--comfy-input-bg);
+ padding-bottom: 5px;
+ margin-bottom: 5px;
+}
+
+.comfyui-workflows-open .active {
+ font-weight: bold;
+ color: var(--primary-fg);
+}
+
+.comfyui-workflows-favorites:empty {
+ display: none;
+}
+
+.comfyui-workflows-tree {
+ padding: 0;
+ margin: 0;
+}
+
+.comfyui-workflows-tree:empty::after {
+ content: "No saved workflows";
+ display: block;
+ text-align: center;
+}
+.comfyui-workflows-tree > ul {
+ padding: 0;
+}
+
+.comfyui-workflows-tree > ul ul {
+ margin: 0;
+ padding: 0 0 0 25px;
+}
+
+.comfyui-workflows-tree:not(.filtered) .closed > ul {
+ display: none;
+}
+
+.comfyui-workflows-tree li,
+.comfyui-workflows-tree-file {
+ --item-height: 32px;
+ list-style-type: none;
+ height: var(--item-height);
+ display: flex;
+ align-items: center;
+ gap: 5px;
+ cursor: pointer;
+ -webkit-user-select: none;
+ -moz-user-select: none;
+ user-select: none;
+}
+
+.comfyui-workflows-tree-file.active::before,
+.comfyui-workflows-tree li:hover::before,
+.comfyui-workflows-tree-file:hover::before {
+ content: "";
+ position: absolute;
+ width: 100%;
+ left: 0;
+ height: var(--item-height);
+ background-color: var(--content-hover-bg);
+ color: var(--content-hover-fg);
+ z-index: -1;
+}
+
+.comfyui-workflows-tree-file.active::before {
+ background-color: var(--primary-bg);
+ color: var(--primary-fg);
+}
+
+.comfyui-workflows-tree-file.running:not(:hover)::before {
+ content: "";
+ position: absolute;
+ width: var(--progress, 0);
+ left: 0;
+ height: var(--item-height);
+ background-color: green;
+ z-index: -1;
+}
+
+.comfyui-workflows-tree-file.unsaved span {
+ font-style: italic;
+}
+
+.comfyui-workflows-tree-file span {
+ flex: auto;
+}
+
+.comfyui-workflows-tree-file span + .comfyui-workflows-file-action {
+ margin-left: 10px;
+}
+
+.comfyui-workflows-tree-file .comfyui-workflows-file-action {
+ background-color: transparent;
+ color: var(--fg-color);
+ padding: 2px 4px;
+}
+
+.comfyui-workflows-tree-file.active .comfyui-workflows-file-action {
+ color: var(--primary-fg);
+}
+
+.lg ~ .comfyui-workflows-popup .comfyui-workflows-tree-file:not(:hover) .comfyui-workflows-file-action {
+ opacity: 0;
+}
+
+.comfyui-workflows-tree-file .comfyui-workflows-file-action:hover {
+ background-color: var(--primary-bg);
+ color: var(--primary-fg);
+}
+
+.comfyui-workflows-tree-file .comfyui-workflows-file-action-primary {
+ background-color: transparent;
+ color: var(--fg-color);
+ padding: 2px 4px;
+ margin: 0 -4px;
+}
+
+.comfyui-workflows-file-action-favorite .mdi-star {
+ color: orange;
+}
+
+/* View List */
+.comfyui-view-list-popup {
+ padding: 10px;
+ background-color: var(--content-bg);
+ color: var(--content-fg);
+ min-width: 170px;
+ min-height: 435px;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ box-sizing: border-box;
+}
+.comfyui-view-list-popup h3 {
+ margin: 0 0 5px 0;
+}
+.comfyui-view-list-items {
+ width: 100%;
+ background: var(--comfy-menu-bg);
+ border-radius: 5px;
+ display: flex;
+ justify-content: center;
+ flex: auto;
+ align-items: center;
+ flex-direction: column;
+}
+.comfyui-view-list-items section {
+ max-height: 400px;
+ overflow: auto;
+ width: 100%;
+ display: grid;
+ grid-template-columns: auto auto auto;
+ align-items: center;
+ justify-content: center;
+ gap: 5px;
+ padding: 5px 0;
+}
+.comfyui-view-list-items section + section {
+ border-top: 1px solid var(--border-color);
+ margin-top: 10px;
+ padding-top: 5px;
+}
+.comfyui-view-list-items section h5 {
+ grid-column: 1 / 4;
+ text-align: center;
+ margin: 5px;
+}
+.comfyui-view-list-items span {
+ text-align: center;
+ padding: 0 2px;
+}
+.comfyui-view-list-popup header {
+ margin-bottom: 10px;
+ display: flex;
+ gap: 5px;
+}
+.comfyui-view-list-popup header .comfyui-button {
+ border: 1px solid transparent;
+}
+.comfyui-view-list-popup header .comfyui-button:not(:disabled):hover {
+ border: 1px solid var(--comfy-menu-bg);
+}
+/* Queue button */
+.comfyui-queue-button .comfyui-split-primary .comfyui-button {
+ padding-right: 12px;
+}
+.comfyui-queue-count {
+ margin-left: 5px;
+ border-radius: 10px;
+ background-color: rgb(8, 80, 153);
+ padding: 2px 4px;
+ font-size: 10px;
+ min-width: 1em;
+ display: inline-block;
+}
+/* Queue options*/
+.comfyui-queue-options {
+ padding: 10px;
+ font-family: Arial, Helvetica, sans-serif;
+ font-size: 12px;
+ display: flex;
+ gap: 10px;
+}
+
+.comfyui-queue-batch {
+ display: flex;
+ flex-direction: column;
+ border-right: 1px solid var(--comfy-menu-bg);
+ padding-right: 10px;
+ gap: 5px;
+}
+
+.comfyui-queue-batch input {
+ width: 145px;
+}
+
+.comfyui-queue-batch .comfyui-queue-batch-value {
+ width: 70px;
+}
+
+.comfyui-queue-mode {
+ display: flex;
+ flex-direction: column;
+}
+
+.comfyui-queue-mode span {
+ font-weight: bold;
+ margin-bottom: 2px;
+}
+
+.comfyui-queue-mode label {
+ display: flex;
+ flex-direction: row-reverse;
+ justify-content: start;
+ gap: 5px;
+ padding: 2px 0;
+}
+
+.comfyui-queue-mode label input {
+ padding: 0;
+ margin: 0;
+}
+
+/** Send to workflow widget selection dialog */
+.comfy-widget-selection-dialog {
+ border: none;
+}
+
+.comfy-widget-selection-dialog div {
+ color: var(--fg-color);
+ font-family: Arial, Helvetica, sans-serif;
+}
+
+.comfy-widget-selection-dialog h2 {
+ margin-top: 0;
+}
+
+.comfy-widget-selection-dialog section {
+ width: -moz-fit-content;
+ width: fit-content;
+ display: flex;
+ flex-direction: column;
+}
+
+.comfy-widget-selection-item {
+ display: flex;
+ gap: 10px;
+ align-items: center;
+}
+
+.comfy-widget-selection-item span {
+ margin-right: auto;
+}
+
+.comfy-widget-selection-item span::before {
+ content: '#' attr(data-id);
+ opacity: 0.5;
+ margin-right: 5px;
+}
+
+.comfy-modal .comfy-widget-selection-item button {
+ font-size: 1em;
+}
+
+/***** Responsive *****/
+.lg.comfyui-menu .lt-lg-show {
+ display: none !important;
+}
+.comfyui-menu:not(.lg) .nlg-hide {
+ display: none !important;
+}
+/** Large screen */
+.lg.comfyui-menu>.comfyui-menu-mobile-collapse .comfyui-button span,
+.lg.comfyui-menu>.comfyui-menu-mobile-collapse.comfyui-button span {
+ display: none;
+}
+.lg.comfyui-menu>.comfyui-menu-mobile-collapse .comfyui-popup .comfyui-button span {
+ display: unset;
+}
+
+/** Non large screen */
+.lt-lg.comfyui-menu {
+ flex-wrap: wrap;
+}
+
+.lt-lg.comfyui-menu > *:not(.comfyui-menu-mobile-collapse) {
+ order: 1;
+}
+
+.lt-lg.comfyui-menu > .comfyui-menu-mobile-collapse {
+ order: 9999;
+ width: 100%;
+}
+
+.comfyui-body-bottom .lt-lg.comfyui-menu > .comfyui-menu-mobile-collapse {
+ order: -1;
+}
+
+.comfyui-body-bottom .lt-lg.comfyui-menu > .comfyui-menu-button {
+ top: unset;
+ bottom: 4px;
+}
+
+.lt-lg.comfyui-menu > .comfyui-menu-mobile-collapse.comfyui-button-group {
+ flex-wrap: wrap;
+}
+
+.lt-lg.comfyui-menu > .comfyui-menu-mobile-collapse .comfyui-button,
+.lt-lg.comfyui-menu > .comfyui-menu-mobile-collapse.comfyui-button {
+ padding: 10px;
+}
+.lt-lg.comfyui-menu > .comfyui-menu-mobile-collapse .comfyui-button,
+.lt-lg.comfyui-menu > .comfyui-menu-mobile-collapse .comfyui-button-wrapper {
+ width: 100%;
+}
+
+.lt-lg.comfyui-menu > .comfyui-menu-mobile-collapse .comfyui-popup {
+ position: static;
+ background-color: var(--comfy-input-bg);
+ max-width: unset;
+ max-height: 50vh;
+ overflow: auto;
+}
+
+.lt-lg.comfyui-menu:not(.expanded) > .comfyui-menu-mobile-collapse {
+ display: none;
+}
+
+.lt-lg .comfyui-queue-button {
+ margin-right: 44px;
+}
+
+.lt-lg .comfyui-menu-button {
+ position: absolute;
+ top: 4px;
+ right: 8px;
+}
+
+.lt-lg.comfyui-menu > .comfyui-menu-mobile-collapse .comfyui-view-list-popup {
+ border-radius: 0;
+}
+
+.lt-lg.comfyui-menu .comfyui-workflows-popup {
+ width: 100vw;
+}
+
+/** Small */
+.lt-md .comfyui-workflows-button-inner {
+ width: unset !important;
+}
+.lt-md .comfyui-workflows-label {
+ display: none;
+}
+
+/** Extra small */
+.lt-sm .comfyui-queue-button {
+ margin-right: 0;
+ width: 100%;
+}
+.lt-sm .comfyui-queue-button .comfyui-button {
+ justify-content: center;
+}
+.lt-sm .comfyui-interrupt-button {
+ margin-right: 45px;
+}
+.comfyui-body-bottom .lt-sm.comfyui-menu > .comfyui-menu-button{
+ bottom: 41px;
+}
+.result-container[data-v-d9c060ae] {
+ width: 100%;
+ height: 100%;
+ aspect-ratio: 1 / 1;
+ overflow: hidden;
+ position: relative;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+}
+.image-preview-mask[data-v-d9c060ae] {
+ position: absolute;
+ left: 50%;
+ top: 50%;
+ transform: translate(-50%, -50%);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ opacity: 0;
+ transition: opacity 0.3s ease;
+ z-index: 1;
+}
+.result-container:hover .image-preview-mask[data-v-d9c060ae] {
+ opacity: 1;
+}
+
+.task-result-preview[data-v-11ef4cfe] {
+ aspect-ratio: 1 / 1;
+ overflow: hidden;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ width: 100%;
+ height: 100%;
+}
+.task-result-preview i[data-v-11ef4cfe],
+.task-result-preview span[data-v-11ef4cfe] {
+ font-size: 2rem;
+}
+.task-item[data-v-11ef4cfe] {
+ display: flex;
+ flex-direction: column;
+ border-radius: 4px;
+ overflow: hidden;
+ position: relative;
+}
+.task-item-details[data-v-11ef4cfe] {
+ position: absolute;
+ bottom: 0;
+ padding: 0.6rem;
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ width: 100%;
+ z-index: 1;
+}
+.task-node-link[data-v-11ef4cfe] {
+ padding: 2px;
+}
+
+/* In dark mode, transparent background color for tags is not ideal for tags that
+are floating on top of images. */
+.tag-wrapper[data-v-11ef4cfe] {
+ background-color: var(--p-primary-contrast-color);
+ border-radius: 6px;
+ display: inline-flex;
+}
+.node-name-tag[data-v-11ef4cfe] {
+ word-break: break-all;
+}
+.status-tag-group[data-v-11ef4cfe] {
+ display: flex;
+ flex-direction: column;
+}
+
+/* PrimeVue's galleria teleports the fullscreen gallery out of subtree so we
+cannot use scoped style here. */
+img.galleria-image {
+ max-width: 100vw;
+ max-height: 100vh;
+ -o-object-fit: contain;
+ object-fit: contain;
+}
+.p-galleria-close-button {
+ /* Set z-index so the close button doesn't get hidden behind the image when image is large */
+ z-index: 1;
+}
+
+.comfy-vue-side-bar-container[data-v-1b0a8fe3] {
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+ overflow: hidden;
+}
+.comfy-vue-side-bar-header[data-v-1b0a8fe3] {
+ flex-shrink: 0;
+ border-left: none;
+ border-right: none;
+ border-top: none;
+ border-radius: 0;
+ padding: 0.25rem 1rem;
+ min-height: 2.5rem;
+}
+.comfy-vue-side-bar-header-span[data-v-1b0a8fe3] {
+ font-size: small;
+}
+.comfy-vue-side-bar-body[data-v-1b0a8fe3] {
+ flex-grow: 1;
+ overflow: auto;
+ scrollbar-width: thin;
+ scrollbar-color: transparent transparent;
+}
+.comfy-vue-side-bar-body[data-v-1b0a8fe3]::-webkit-scrollbar {
+ width: 1px;
+}
+.comfy-vue-side-bar-body[data-v-1b0a8fe3]::-webkit-scrollbar-thumb {
+ background-color: transparent;
+}
+
+.scroll-container[data-v-67a8405b] {
+ height: 100%;
+ overflow-y: auto;
+}
+.queue-grid[data-v-67a8405b] {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
+ padding: 0.5rem;
+ gap: 0.5rem;
+}
+
+.editable-text[data-v-8a54db9f] {
+ display: inline-block;
+}
+.editable-text input[data-v-8a54db9f] {
+ width: 100%;
+ box-sizing: border-box;
+}
+
+.tree-node[data-v-99654e96] {
+ width: 100%;
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+}
+.leaf-count-badge[data-v-99654e96] {
+ margin-left: 0.5rem;
+}
+.node-content[data-v-99654e96] {
+ display: flex;
+ align-items: center;
+ flex-grow: 1;
+}
+.leaf-label[data-v-99654e96] {
+ margin-left: 0.5rem;
+}
+[data-v-99654e96] .editable-text span {
+ word-break: break-all;
+}
+
+[data-v-a3a0a064] .tree-explorer-node-label {
+ width: 100%;
+ display: flex;
+ align-items: center;
+ margin-left: var(--p-tree-node-gap);
+ flex-grow: 1;
+}
+
+/*
+ * The following styles are necessary to avoid layout shift when dragging nodes over folders.
+ * By setting the position to relative on the parent and using an absolutely positioned pseudo-element,
+ * we can create a visual indicator for the drop target without affecting the layout of other elements.
+ */
+[data-v-a3a0a064] .p-tree-node-content:has(.tree-folder) {
+ position: relative;
+}
+[data-v-a3a0a064] .p-tree-node-content:has(.tree-folder.can-drop)::after {
+ content: '';
+ position: absolute;
+ top: 0;
+ left: 0;
+ right: 0;
+ bottom: 0;
+ border: 1px solid var(--p-content-color);
+ pointer-events: none;
+}
+
+.slot_row[data-v-cbec679a] {
+ padding: 2px;
+}
+
+/* Original N-Sidebar styles */
+._sb_dot[data-v-cbec679a] {
+ width: 8px;
+ height: 8px;
+ border-radius: 50%;
+ background-color: grey;
+}
+.node_header[data-v-cbec679a] {
+ line-height: 1;
+ padding: 8px 13px 7px;
+ background: var(--comfy-input-bg);
+ margin-bottom: 5px;
+ font-size: 15px;
+ text-wrap: nowrap;
+ overflow: hidden;
+ display: flex;
+ align-items: center;
+}
+.headdot[data-v-cbec679a] {
+ width: 10px;
+ height: 10px;
+ float: inline-start;
+ margin-right: 8px;
+}
+.IMAGE[data-v-cbec679a] {
+ background-color: #64b5f6;
+}
+.VAE[data-v-cbec679a] {
+ background-color: #ff6e6e;
+}
+.LATENT[data-v-cbec679a] {
+ background-color: #ff9cf9;
+}
+.MASK[data-v-cbec679a] {
+ background-color: #81c784;
+}
+.CONDITIONING[data-v-cbec679a] {
+ background-color: #ffa931;
+}
+.CLIP[data-v-cbec679a] {
+ background-color: #ffd500;
+}
+.MODEL[data-v-cbec679a] {
+ background-color: #b39ddb;
+}
+.CONTROL_NET[data-v-cbec679a] {
+ background-color: #a5d6a7;
+}
+._sb_node_preview[data-v-cbec679a] {
+ background-color: var(--comfy-menu-bg);
+ font-family: 'Open Sans', sans-serif;
+ font-size: small;
+ color: var(--descrip-text);
+ border: 1px solid var(--descrip-text);
+ min-width: 300px;
+ width: -moz-min-content;
+ width: min-content;
+ height: -moz-fit-content;
+ height: fit-content;
+ z-index: 9999;
+ border-radius: 12px;
+ overflow: hidden;
+ font-size: 12px;
+ padding-bottom: 10px;
+}
+._sb_node_preview ._sb_description[data-v-cbec679a] {
+ margin: 10px;
+ padding: 6px;
+ background: var(--border-color);
+ border-radius: 5px;
+ font-style: italic;
+ font-weight: 500;
+ font-size: 0.9rem;
+ word-break: break-word;
+}
+._sb_table[data-v-cbec679a] {
+ display: grid;
+
+ grid-column-gap: 10px;
+ /* Spazio tra le colonne */
+ width: 100%;
+ /* Imposta la larghezza della tabella al 100% del contenitore */
+}
+._sb_row[data-v-cbec679a] {
+ display: grid;
+ grid-template-columns: 10px 1fr 1fr 1fr 10px;
+ grid-column-gap: 10px;
+ align-items: center;
+ padding-left: 9px;
+ padding-right: 9px;
+}
+._sb_row_string[data-v-cbec679a] {
+ grid-template-columns: 10px 1fr 1fr 10fr 1fr;
+}
+._sb_col[data-v-cbec679a] {
+ border: 0px solid #000;
+ display: flex;
+ align-items: flex-end;
+ flex-direction: row-reverse;
+ flex-wrap: nowrap;
+ align-content: flex-start;
+ justify-content: flex-end;
+}
+._sb_inherit[data-v-cbec679a] {
+ display: inherit;
+}
+._long_field[data-v-cbec679a] {
+ background: var(--bg-color);
+ border: 2px solid var(--border-color);
+ margin: 5px 5px 0 5px;
+ border-radius: 10px;
+ line-height: 1.7;
+ text-wrap: nowrap;
+}
+._sb_arrow[data-v-cbec679a] {
+ color: var(--fg-color);
+}
+._sb_preview_badge[data-v-cbec679a] {
+ text-align: center;
+ background: var(--comfy-input-bg);
+ font-weight: bold;
+ color: var(--error-text);
+}
+
+.node-lib-node-container[data-v-3238e135] {
+ height: 100%;
+ width: 100%;
+}
+.bookmark-button[data-v-3238e135] {
+ width: unset;
+ padding: 0.25rem;
+}
+
+.p-selectbutton .p-button[data-v-91077f2a] {
+ padding: 0.5rem;
+}
+.p-selectbutton .p-button .pi[data-v-91077f2a] {
+ font-size: 1.5rem;
+}
+.field[data-v-91077f2a] {
+ display: flex;
+ flex-direction: column;
+ gap: 0.5rem;
+}
+.color-picker-container[data-v-91077f2a] {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+}
+
+._content[data-v-e7b35fd9] {
+
+ display: flex;
+
+ flex-direction: column
+}
+._content[data-v-e7b35fd9] > :not([hidden]) ~ :not([hidden]) {
+
+ --tw-space-y-reverse: 0;
+
+ margin-top: calc(0.5rem * calc(1 - var(--tw-space-y-reverse)));
+
+ margin-bottom: calc(0.5rem * var(--tw-space-y-reverse))
+}
+._footer[data-v-e7b35fd9] {
+
+ display: flex;
+
+ flex-direction: column;
+
+ align-items: flex-end;
+
+ padding-top: 1rem
+}
+
+.node-lib-filter-popup {
+ margin-left: -13px;
+}
+
+[data-v-f6a7371a] .comfy-vue-side-bar-body {
+ background: var(--p-tree-background);
+}
+[data-v-f6a7371a] .node-lib-bookmark-tree-explorer {
+ padding-bottom: 2px;
+}
+[data-v-f6a7371a] .p-divider {
+ margin: var(--comfy-tree-explorer-item-padding) 0px;
+}
+
+.p-tree-node-content {
+ padding: var(--comfy-tree-explorer-item-padding) !important;
+}
+
+.spinner[data-v-4cb36b07] {
+ position: absolute;
+ inset: 0px;
+ display: flex;
+ height: 100vh;
+ align-items: center;
+ justify-content: center
+}
+/* this CSS contains only the basic CSS needed to run the app and use it */
+
+.lgraphcanvas {
+ /*cursor: crosshair;*/
+ user-select: none;
+ -moz-user-select: none;
+ -webkit-user-select: none;
+ outline: none;
+ font-family: Tahoma, sans-serif;
+}
+
+.lgraphcanvas * {
+ box-sizing: border-box;
+}
+
+.litegraph.litecontextmenu {
+ font-family: Tahoma, sans-serif;
+ position: fixed;
+ top: 100px;
+ left: 100px;
+ min-width: 100px;
+ color: #aaf;
+ padding: 0;
+ box-shadow: 0 0 10px black !important;
+ background-color: #2e2e2e !important;
+ z-index: 10;
+}
+
+.litegraph.litecontextmenu.dark {
+ background-color: #000 !important;
+}
+
+.litegraph.litecontextmenu .litemenu-title img {
+ margin-top: 2px;
+ margin-left: 2px;
+ margin-right: 4px;
+}
+
+.litegraph.litecontextmenu .litemenu-entry {
+ margin: 2px;
+ padding: 2px;
+}
+
+.litegraph.litecontextmenu .litemenu-entry.submenu {
+ background-color: #2e2e2e !important;
+}
+
+.litegraph.litecontextmenu.dark .litemenu-entry.submenu {
+ background-color: #000 !important;
+}
+
+.litegraph .litemenubar ul {
+ font-family: Tahoma, sans-serif;
+ margin: 0;
+ padding: 0;
+}
+
+.litegraph .litemenubar li {
+ font-size: 14px;
+ color: #999;
+ display: inline-block;
+ min-width: 50px;
+ padding-left: 10px;
+ padding-right: 10px;
+ user-select: none;
+ -moz-user-select: none;
+ -webkit-user-select: none;
+ cursor: pointer;
+}
+
+.litegraph .litemenubar li:hover {
+ background-color: #777;
+ color: #eee;
+}
+
+.litegraph .litegraph .litemenubar-panel {
+ position: absolute;
+ top: 5px;
+ left: 5px;
+ min-width: 100px;
+ background-color: #444;
+ box-shadow: 0 0 3px black;
+ padding: 4px;
+ border-bottom: 2px solid #aaf;
+ z-index: 10;
+}
+
+.litegraph .litemenu-entry,
+.litemenu-title {
+ font-size: 12px;
+ color: #aaa;
+ padding: 0 0 0 4px;
+ margin: 2px;
+ padding-left: 2px;
+ -moz-user-select: none;
+ -webkit-user-select: none;
+ user-select: none;
+ cursor: pointer;
+}
+
+.litegraph .litemenu-entry .icon {
+ display: inline-block;
+ width: 12px;
+ height: 12px;
+ margin: 2px;
+ vertical-align: top;
+}
+
+.litegraph .litemenu-entry.checked .icon {
+ background-color: #aaf;
+}
+
+.litegraph .litemenu-entry .more {
+ float: right;
+ padding-right: 5px;
+}
+
+.litegraph .litemenu-entry.disabled {
+ opacity: 0.5;
+ cursor: default;
+}
+
+.litegraph .litemenu-entry.separator {
+ display: block;
+ border-top: 1px solid #333;
+ border-bottom: 1px solid #666;
+ width: 100%;
+ height: 0px;
+ margin: 3px 0 2px 0;
+ background-color: transparent;
+ padding: 0 !important;
+ cursor: default !important;
+}
+
+.litegraph .litemenu-entry.has_submenu {
+ border-right: 2px solid cyan;
+}
+
+.litegraph .litemenu-title {
+ color: #dde;
+ background-color: #111;
+ margin: 0;
+ padding: 2px;
+ cursor: default;
+}
+
+.litegraph .litemenu-entry:hover:not(.disabled):not(.separator) {
+ background-color: #444 !important;
+ color: #eee;
+ transition: all 0.2s;
+}
+
+.litegraph .litemenu-entry .property_name {
+ display: inline-block;
+ text-align: left;
+ min-width: 80px;
+ min-height: 1.2em;
+}
+
+.litegraph .litemenu-entry .property_value {
+ display: inline-block;
+ background-color: rgba(0, 0, 0, 0.5);
+ text-align: right;
+ min-width: 80px;
+ min-height: 1.2em;
+ vertical-align: middle;
+ padding-right: 10px;
+}
+
+.litegraph.litesearchbox {
+ font-family: Tahoma, sans-serif;
+ position: absolute;
+ background-color: rgba(0, 0, 0, 0.5);
+ padding-top: 4px;
+}
+
+.litegraph.litesearchbox input,
+.litegraph.litesearchbox select {
+ margin-top: 3px;
+ min-width: 60px;
+ min-height: 1.5em;
+ background-color: black;
+ border: 0;
+ color: white;
+ padding-left: 10px;
+ margin-right: 5px;
+ max-width: 300px;
+}
+
+.litegraph.litesearchbox .name {
+ display: inline-block;
+ min-width: 60px;
+ min-height: 1.5em;
+ padding-left: 10px;
+}
+
+.litegraph.litesearchbox .helper {
+ overflow: auto;
+ max-height: 200px;
+ margin-top: 2px;
+}
+
+.litegraph.lite-search-item {
+ font-family: Tahoma, sans-serif;
+ background-color: rgba(0, 0, 0, 0.5);
+ color: white;
+ padding-top: 2px;
+}
+
+.litegraph.lite-search-item.not_in_filter{
+ /*background-color: rgba(50, 50, 50, 0.5);*/
+ /*color: #999;*/
+ color: #B99;
+ font-style: italic;
+}
+
+.litegraph.lite-search-item.generic_type{
+ /*background-color: rgba(50, 50, 50, 0.5);*/
+ /*color: #DD9;*/
+ color: #999;
+ font-style: italic;
+}
+
+.litegraph.lite-search-item:hover,
+.litegraph.lite-search-item.selected {
+ cursor: pointer;
+ background-color: white;
+ color: black;
+}
+
+.litegraph.lite-search-item-type {
+ display: inline-block;
+ background: rgba(0,0,0,0.2);
+ margin-left: 5px;
+ font-size: 14px;
+ padding: 2px 5px;
+ position: relative;
+ top: -2px;
+ opacity: 0.8;
+ border-radius: 4px;
+ }
+
+/* DIALOGs ******/
+
+.litegraph .dialog {
+ position: absolute;
+ top: 50%;
+ left: 50%;
+ margin-top: -150px;
+ margin-left: -200px;
+
+ background-color: #2A2A2A;
+
+ min-width: 400px;
+ min-height: 200px;
+ box-shadow: 0 0 4px #111;
+ border-radius: 6px;
+}
+
+.litegraph .dialog.settings {
+ left: 10px;
+ top: 10px;
+ height: calc( 100% - 20px );
+ margin: auto;
+ max-width: 50%;
+}
+
+.litegraph .dialog.centered {
+ top: 50px;
+ left: 50%;
+ position: absolute;
+ transform: translateX(-50%);
+ min-width: 600px;
+ min-height: 300px;
+ height: calc( 100% - 100px );
+ margin: auto;
+}
+
+.litegraph .dialog .close {
+ float: right;
+ margin: 4px;
+ margin-right: 10px;
+ cursor: pointer;
+ font-size: 1.4em;
+}
+
+.litegraph .dialog .close:hover {
+ color: white;
+}
+
+.litegraph .dialog .dialog-header {
+ color: #AAA;
+ border-bottom: 1px solid #161616; height: 40px;
+}
+.litegraph .dialog .dialog-footer { height: 50px; padding: 10px; border-top: 1px solid #1a1a1a;}
+
+.litegraph .dialog .dialog-header .dialog-title {
+ font: 20px "Arial";
+ margin: 4px;
+ padding: 4px 10px;
+ display: inline-block;
+}
+
+.litegraph .dialog .dialog-content, .litegraph .dialog .dialog-alt-content {
+ height: calc(100% - 90px);
+ width: 100%;
+ min-height: 100px;
+ display: inline-block;
+ color: #AAA;
+ /*background-color: black;*/
+ overflow: auto;
+}
+
+.litegraph .dialog .dialog-content h3 {
+ margin: 10px;
+}
+
+.litegraph .dialog .dialog-content .connections {
+ flex-direction: row;
+}
+
+.litegraph .dialog .dialog-content .connections .connections_side {
+ width: calc(50% - 5px);
+ min-height: 100px;
+ background-color: black;
+ display: flex;
+}
+
+.litegraph .dialog .node_type {
+ font-size: 1.2em;
+ display: block;
+ margin: 10px;
+}
+
+.litegraph .dialog .node_desc {
+ opacity: 0.5;
+ display: block;
+ margin: 10px;
+}
+
+.litegraph .dialog .separator {
+ display: block;
+ width: calc( 100% - 4px );
+ height: 1px;
+ border-top: 1px solid #000;
+ border-bottom: 1px solid #333;
+ margin: 10px 2px;
+ padding: 0;
+}
+
+.litegraph .dialog .property {
+ margin-bottom: 2px;
+ padding: 4px;
+}
+
+.litegraph .dialog .property:hover {
+ background: #545454;
+}
+
+.litegraph .dialog .property_name {
+ color: #737373;
+ display: inline-block;
+ text-align: left;
+ vertical-align: top;
+ width: 160px;
+ padding-left: 4px;
+ overflow: hidden;
+ margin-right: 6px;
+}
+
+.litegraph .dialog .property:hover .property_name {
+ color: white;
+}
+
+.litegraph .dialog .property_value {
+ display: inline-block;
+ text-align: right;
+ color: #AAA;
+ background-color: #1A1A1A;
+ /*width: calc( 100% - 122px );*/
+ max-width: calc( 100% - 162px );
+ min-width: 200px;
+ max-height: 300px;
+ min-height: 20px;
+ padding: 4px;
+ padding-right: 12px;
+ overflow: hidden;
+ cursor: pointer;
+ border-radius: 3px;
+}
+
+.litegraph .dialog .property_value:hover {
+ color: white;
+}
+
+.litegraph .dialog .property.boolean .property_value {
+ padding-right: 30px;
+ color: #A88;
+ /*width: auto;
+ float: right;*/
+}
+
+.litegraph .dialog .property.boolean.bool-on .property_name{
+ color: #8A8;
+}
+.litegraph .dialog .property.boolean.bool-on .property_value{
+ color: #8A8;
+}
+
+.litegraph .dialog .btn {
+ border: 0;
+ border-radius: 4px;
+ padding: 4px 20px;
+ margin-left: 0px;
+ background-color: #060606;
+ color: #8e8e8e;
+}
+
+.litegraph .dialog .btn:hover {
+ background-color: #111;
+ color: #FFF;
+}
+
+.litegraph .dialog .btn.delete:hover {
+ background-color: #F33;
+ color: black;
+}
+
+.litegraph .subgraph_property {
+ padding: 4px;
+}
+
+.litegraph .subgraph_property:hover {
+ background-color: #333;
+}
+
+.litegraph .subgraph_property.extra {
+ margin-top: 8px;
+}
+
+.litegraph .subgraph_property span.name {
+ font-size: 1.3em;
+ padding-left: 4px;
+}
+
+.litegraph .subgraph_property span.type {
+ opacity: 0.5;
+ margin-right: 20px;
+ padding-left: 4px;
+}
+
+.litegraph .subgraph_property span.label {
+ display: inline-block;
+ width: 60px;
+ padding: 0px 10px;
+}
+
+.litegraph .subgraph_property input {
+ width: 140px;
+ color: #999;
+ background-color: #1A1A1A;
+ border-radius: 4px;
+ border: 0;
+ margin-right: 10px;
+ padding: 4px;
+ padding-left: 10px;
+}
+
+.litegraph .subgraph_property button {
+ background-color: #1c1c1c;
+ color: #aaa;
+ border: 0;
+ border-radius: 2px;
+ padding: 4px 10px;
+ cursor: pointer;
+}
+
+.litegraph .subgraph_property.extra {
+ color: #ccc;
+}
+
+.litegraph .subgraph_property.extra input {
+ background-color: #111;
+}
+
+.litegraph .bullet_icon {
+ margin-left: 10px;
+ border-radius: 10px;
+ width: 12px;
+ height: 12px;
+ background-color: #666;
+ display: inline-block;
+ margin-top: 2px;
+ margin-right: 4px;
+ transition: background-color 0.1s ease 0s;
+ -moz-transition: background-color 0.1s ease 0s;
+}
+
+.litegraph .bullet_icon:hover {
+ background-color: #698;
+ cursor: pointer;
+}
+
+/* OLD */
+
+.graphcontextmenu {
+ padding: 4px;
+ min-width: 100px;
+}
+
+.graphcontextmenu-title {
+ color: #dde;
+ background-color: #222;
+ margin: 0;
+ padding: 2px;
+ cursor: default;
+}
+
+.graphmenu-entry {
+ box-sizing: border-box;
+ margin: 2px;
+ padding-left: 20px;
+ user-select: none;
+ -moz-user-select: none;
+ -webkit-user-select: none;
+ transition: all linear 0.3s;
+}
+
+.graphmenu-entry.event,
+.litemenu-entry.event {
+ border-left: 8px solid orange;
+ padding-left: 12px;
+}
+
+.graphmenu-entry.disabled {
+ opacity: 0.3;
+}
+
+.graphmenu-entry.submenu {
+ border-right: 2px solid #eee;
+}
+
+.graphmenu-entry:hover {
+ background-color: #555;
+}
+
+.graphmenu-entry.separator {
+ background-color: #111;
+ border-bottom: 1px solid #666;
+ height: 1px;
+ width: calc(100% - 20px);
+ -moz-width: calc(100% - 20px);
+ -webkit-width: calc(100% - 20px);
+}
+
+.graphmenu-entry .property_name {
+ display: inline-block;
+ text-align: left;
+ min-width: 80px;
+ min-height: 1.2em;
+}
+
+.graphmenu-entry .property_value,
+.litemenu-entry .property_value {
+ display: inline-block;
+ background-color: rgba(0, 0, 0, 0.5);
+ text-align: right;
+ min-width: 80px;
+ min-height: 1.2em;
+ vertical-align: middle;
+ padding-right: 10px;
+}
+
+.graphdialog {
+ position: absolute;
+ top: 10px;
+ left: 10px;
+ min-height: 2em;
+ background-color: #333;
+ font-size: 1.2em;
+ box-shadow: 0 0 10px black !important;
+ z-index: 10;
+}
+
+.graphdialog.rounded {
+ border-radius: 12px;
+ padding-right: 2px;
+}
+
+.graphdialog .name {
+ display: inline-block;
+ min-width: 60px;
+ min-height: 1.5em;
+ padding-left: 10px;
+}
+
+.graphdialog input,
+.graphdialog textarea,
+.graphdialog select {
+ margin: 3px;
+ min-width: 60px;
+ min-height: 1.5em;
+ background-color: black;
+ border: 0;
+ color: white;
+ padding-left: 10px;
+ outline: none;
+}
+
+.graphdialog textarea {
+ min-height: 150px;
+}
+
+.graphdialog button {
+ margin-top: 3px;
+ vertical-align: top;
+ background-color: #999;
+ border: 0;
+}
+
+.graphdialog button.rounded,
+.graphdialog input.rounded {
+ border-radius: 0 12px 12px 0;
+}
+
+.graphdialog .helper {
+ overflow: auto;
+ max-height: 200px;
+}
+
+.graphdialog .help-item {
+ padding-left: 10px;
+}
+
+.graphdialog .help-item:hover,
+.graphdialog .help-item.selected {
+ cursor: pointer;
+ background-color: white;
+ color: black;
+}
+
+.litegraph .dialog {
+ min-height: 0;
+}
+.litegraph .dialog .dialog-content {
+display: block;
+}
+.litegraph .dialog .dialog-content .subgraph_property {
+padding: 5px;
+}
+.litegraph .dialog .dialog-footer {
+margin: 0;
+}
+.litegraph .dialog .dialog-footer .subgraph_property {
+margin-top: 0;
+display: flex;
+align-items: center;
+padding: 5px;
+}
+.litegraph .dialog .dialog-footer .subgraph_property .name {
+flex: 1;
+}
+.litegraph .graphdialog {
+display: flex;
+align-items: center;
+border-radius: 20px;
+padding: 4px 10px;
+position: fixed;
+}
+.litegraph .graphdialog .name {
+padding: 0;
+min-height: 0;
+font-size: 16px;
+vertical-align: middle;
+}
+.litegraph .graphdialog .value {
+font-size: 16px;
+min-height: 0;
+margin: 0 10px;
+padding: 2px 5px;
+}
+.litegraph .graphdialog input[type="checkbox"] {
+width: 16px;
+height: 16px;
+}
+.litegraph .graphdialog button {
+padding: 4px 18px;
+border-radius: 20px;
+cursor: pointer;
+}
+
+@layer primevue, tailwind-utilities;
+
+@layer tailwind-utilities {
+ .container{
+ width: 100%;
+ }
+ @media (min-width: 640px){
+
+ .container{
+ max-width: 640px;
+ }
+ }
+ @media (min-width: 768px){
+
+ .container{
+ max-width: 768px;
+ }
+ }
+ @media (min-width: 1024px){
+
+ .container{
+ max-width: 1024px;
+ }
+ }
+ @media (min-width: 1280px){
+
+ .container{
+ max-width: 1280px;
+ }
+ }
+ @media (min-width: 1536px){
+
+ .container{
+ max-width: 1536px;
+ }
+ }
+ @media (min-width: 1800px){
+
+ .container{
+ max-width: 1800px;
+ }
+ }
+ @media (min-width: 2500px){
+
+ .container{
+ max-width: 2500px;
+ }
+ }
+ @media (min-width: 3200px){
+
+ .container{
+ max-width: 3200px;
+ }
+ }
+ .\!visible{
+ visibility: visible !important;
+ }
+ .visible{
+ visibility: visible;
+ }
+ .collapse{
+ visibility: collapse;
+ }
+ .static{
+ position: static;
+ }
+ .fixed{
+ position: fixed;
+ }
+ .absolute{
+ position: absolute;
+ }
+ .relative{
+ position: relative;
+ }
+ .inset-0{
+ inset: 0px;
+ }
+ .z-10{
+ z-index: 10;
+ }
+ .mx-4{
+ margin-left: 1rem;
+ margin-right: 1rem;
+ }
+ .mb-2{
+ margin-bottom: 0.5rem;
+ }
+ .mb-4{
+ margin-bottom: 1rem;
+ }
+ .mb-6{
+ margin-bottom: 1.5rem;
+ }
+ .mr-1{
+ margin-right: 0.25rem;
+ }
+ .mr-2{
+ margin-right: 0.5rem;
+ }
+ .mt-1{
+ margin-top: 0.25rem;
+ }
+ .mt-4{
+ margin-top: 1rem;
+ }
+ .block{
+ display: block;
+ }
+ .flex{
+ display: flex;
+ }
+ .inline-flex{
+ display: inline-flex;
+ }
+ .table{
+ display: table;
+ }
+ .grid{
+ display: grid;
+ }
+ .contents{
+ display: contents;
+ }
+ .hidden{
+ display: none;
+ }
+ .h-full{
+ height: 100%;
+ }
+ .min-h-screen{
+ min-height: 100vh;
+ }
+ .w-full{
+ width: 100%;
+ }
+ .flex-shrink{
+ flex-shrink: 1;
+ }
+ .flex-shrink-0{
+ flex-shrink: 0;
+ }
+ .shrink{
+ flex-shrink: 1;
+ }
+ .flex-grow{
+ flex-grow: 1;
+ }
+ .grow{
+ flex-grow: 1;
+ }
+ .scale-75{
+ --tw-scale-x: .75;
+ --tw-scale-y: .75;
+ transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y));
+ }
+ .transform{
+ transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y));
+ }
+ .cursor-pointer{
+ cursor: pointer;
+ }
+ .resize{
+ resize: both;
+ }
+ .grid-cols-2{
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ }
+ .flex-col{
+ flex-direction: column;
+ }
+ .flex-wrap{
+ flex-wrap: wrap;
+ }
+ .items-center{
+ align-items: center;
+ }
+ .justify-center{
+ justify-content: center;
+ }
+ .justify-between{
+ justify-content: space-between;
+ }
+ .gap-2{
+ gap: 0.5rem;
+ }
+ .space-y-2 > :not([hidden]) ~ :not([hidden]){
+ --tw-space-y-reverse: 0;
+ margin-top: calc(0.5rem * calc(1 - var(--tw-space-y-reverse)));
+ margin-bottom: calc(0.5rem * var(--tw-space-y-reverse));
+ }
+ .overflow-hidden{
+ overflow: hidden;
+ }
+ .overflow-y-auto{
+ overflow-y: auto;
+ }
+ .truncate{
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .text-ellipsis{
+ text-overflow: ellipsis;
+ }
+ .whitespace-nowrap{
+ white-space: nowrap;
+ }
+ .whitespace-pre-line{
+ white-space: pre-line;
+ }
+ .text-wrap{
+ text-wrap: wrap;
+ }
+ .rounded{
+ border-radius: 0.25rem;
+ }
+ .border{
+ border-width: 1px;
+ }
+ .border-none{
+ border-style: none;
+ }
+ .bg-blue-500{
+ --tw-bg-opacity: 1;
+ background-color: rgb(66 153 225 / var(--tw-bg-opacity));
+ }
+ .bg-green-500{
+ --tw-bg-opacity: 1;
+ background-color: rgb(150 206 76 / var(--tw-bg-opacity));
+ }
+ .bg-red-500{
+ --tw-bg-opacity: 1;
+ background-color: rgb(239 68 68 / var(--tw-bg-opacity));
+ }
+ .px-2{
+ padding-left: 0.5rem;
+ padding-right: 0.5rem;
+ }
+ .py-0{
+ padding-top: 0px;
+ padding-bottom: 0px;
+ }
+ .pt-2{
+ padding-top: 0.5rem;
+ }
+ .pt-4{
+ padding-top: 1rem;
+ }
+ .text-center{
+ text-align: center;
+ }
+ .text-2xl{
+ font-size: 1.5rem;
+ }
+ .text-sm{
+ font-size: 0.875rem;
+ }
+ .text-xl{
+ font-size: 1.25rem;
+ }
+ .font-bold{
+ font-weight: 700;
+ }
+ .font-light{
+ font-weight: 300;
+ }
+ .font-medium{
+ font-weight: 500;
+ }
+ .font-semibold{
+ font-weight: 600;
+ }
+ .uppercase{
+ text-transform: uppercase;
+ }
+ .italic{
+ font-style: italic;
+ }
+ .text-gray-400{
+ --tw-text-opacity: 1;
+ color: rgb(203 213 224 / var(--tw-text-opacity));
+ }
+ .no-underline{
+ text-decoration-line: none;
+ }
+ .opacity-0{
+ opacity: 0;
+ }
+ .outline{
+ outline-style: solid;
+ }
+ .blur{
+ --tw-blur: blur(8px);
+ filter: var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow);
+ }
+ .invert{
+ --tw-invert: invert(100%);
+ filter: var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow);
+ }
+ .filter{
+ filter: var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow);
+ }
+ .backdrop-filter{
+ -webkit-backdrop-filter: var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);
+ backdrop-filter: var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);
+ }
+ .transition{
+ transition-property: color, background-color, border-color, text-decoration-color, fill, stroke, opacity, box-shadow, transform, filter, -webkit-backdrop-filter;
+ transition-property: color, background-color, border-color, text-decoration-color, fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter;
+ transition-property: color, background-color, border-color, text-decoration-color, fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter, -webkit-backdrop-filter;
+ transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
+ transition-duration: 150ms;
+ }
+ .transition-all{
+ transition-property: all;
+ transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
+ transition-duration: 150ms;
+ }
+ .duration-100{
+ transition-duration: 100ms;
+ }
+ .ease-in{
+ transition-timing-function: cubic-bezier(0.4, 0, 1, 1);
+ }
+ .ease-out{
+ transition-timing-function: cubic-bezier(0, 0, 0.2, 1);
+ }
+}
+
+:root {
+ --fg-color: #000;
+ --bg-color: #fff;
+ --comfy-menu-bg: #353535;
+ --comfy-input-bg: #222;
+ --input-text: #ddd;
+ --descrip-text: #999;
+ --drag-text: #ccc;
+ --error-text: #ff4444;
+ --border-color: #4e4e4e;
+ --tr-even-bg-color: #222;
+ --tr-odd-bg-color: #353535;
+ --primary-bg: #236692;
+ --primary-fg: #ffffff;
+ --primary-hover-bg: #3485bb;
+ --primary-hover-fg: #ffffff;
+ --content-bg: #e0e0e0;
+ --content-fg: #000;
+ --content-hover-bg: #adadad;
+ --content-hover-fg: #000;
+}
+
+@media (prefers-color-scheme: dark) {
+ :root {
+ --fg-color: #fff;
+ --bg-color: #202020;
+ --content-bg: #4e4e4e;
+ --content-fg: #fff;
+ --content-hover-bg: #222;
+ --content-hover-fg: #fff;
+ }
+}
+
+body {
+ width: 100vw;
+ height: 100vh;
+ margin: 0;
+ overflow: hidden;
+ grid-template-columns: auto 1fr auto;
+ grid-template-rows: auto 1fr auto;
+ background: var(--bg-color) var(--bg-img);
+ color: var(--fg-color);
+ min-height: -webkit-fill-available;
+ max-height: -webkit-fill-available;
+ min-width: -webkit-fill-available;
+ max-width: -webkit-fill-available;
+ font-family: Arial, sans-serif;
+}
+
+/**
+ +------------------+------------------+------------------+
+ | |
+ | .comfyui-body- |
+ | top |
+ | (spans all cols) |
+ | |
+ +------------------+------------------+------------------+
+ | | | |
+ | .comfyui-body- | #graph-canvas | .comfyui-body- |
+ | left | | right |
+ | | | |
+ | | | |
+ +------------------+------------------+------------------+
+ | |
+ | .comfyui-body- |
+ | bottom |
+ | (spans all cols) |
+ | |
+ +------------------+------------------+------------------+
+*/
+
+.comfyui-body-top {
+ order: -5;
+ /* Span across all columns */
+ grid-column: 1/-1;
+ /* Position at the first row */
+ grid-row: 1;
+ z-index: 10;
+ display: flex;
+ flex-direction: column;
+}
+
+.comfyui-body-left {
+ order: -4;
+ /* Position in the first column */
+ grid-column: 1;
+ /* Position below the top element */
+ grid-row: 2;
+ z-index: 10;
+ display: flex;
+}
+
+.graph-canvas-container {
+ width: 100%;
+ height: 100%;
+ order: -3;
+ grid-column: 2;
+ grid-row: 2;
+ position: relative;
+ overflow: hidden;
+}
+
+#graph-canvas {
+ width: 100%;
+ height: 100%;
+ touch-action: none;
+}
+
+.comfyui-body-right {
+ order: -2;
+ z-index: 10;
+ grid-column: 3;
+ grid-row: 2;
+}
+
+.comfyui-body-bottom {
+ order: 4;
+ /* Span across all columns */
+ grid-column: 1/-1;
+ grid-row: 3;
+ z-index: 10;
+ display: flex;
+ flex-direction: column;
+}
+
+.comfy-multiline-input {
+ background-color: var(--comfy-input-bg);
+ color: var(--input-text);
+ overflow: hidden;
+ overflow-y: auto;
+ padding: 2px;
+ resize: none;
+ border: none;
+ box-sizing: border-box;
+ font-size: var(--comfy-textarea-font-size);
+}
+
+.comfy-modal {
+ display: none; /* Hidden by default */
+ position: fixed; /* Stay in place */
+ z-index: 100; /* Sit on top */
+ padding: 30px 30px 10px 30px;
+ background-color: var(--comfy-menu-bg); /* Modal background */
+ color: var(--error-text);
+ box-shadow: 0 0 20px #888888;
+ border-radius: 10px;
+ top: 50%;
+ left: 50%;
+ max-width: 80vw;
+ max-height: 80vh;
+ transform: translate(-50%, -50%);
+ overflow: hidden;
+ justify-content: center;
+ font-family: monospace;
+ font-size: 15px;
+}
+
+.comfy-modal-content {
+ display: flex;
+ flex-direction: column;
+}
+
+.comfy-modal p {
+ overflow: auto;
+ white-space: pre-line; /* This will respect line breaks */
+ margin-bottom: 20px; /* Add some margin between the text and the close button*/
+}
+
+.comfy-modal select,
+.comfy-modal input[type=button],
+.comfy-modal input[type=checkbox] {
+ margin: 3px 3px 3px 4px;
+}
+
+.comfy-menu-hamburger {
+ position: fixed;
+ top: 10px;
+ z-index: 9999;
+ right: 10px;
+ width: 30px;
+ display: none;
+ gap: 8px;
+ flex-direction: column;
+ cursor: pointer;
+}
+
+.comfy-menu-hamburger div {
+ height: 3px;
+ width: 100%;
+ border-radius: 20px;
+ background-color: white;
+}
+
+.comfy-menu {
+ font-size: 15px;
+ position: absolute;
+ top: 50%;
+ right: 0;
+ text-align: center;
+ z-index: 999;
+ width: 190px;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ color: var(--descrip-text);
+ background-color: var(--comfy-menu-bg);
+ font-family: sans-serif;
+ padding: 10px;
+ border-radius: 0 8px 8px 8px;
+ box-shadow: 3px 3px 8px rgba(0, 0, 0, 0.4);
+}
+
+.comfy-menu-header {
+ display: flex;
+}
+
+.comfy-menu-actions {
+ display: flex;
+ gap: 3px;
+ align-items: center;
+ height: 20px;
+ position: relative;
+ top: -1px;
+ font-size: 22px;
+}
+
+.comfy-menu .comfy-menu-actions button {
+ background-color: rgba(0, 0, 0, 0);
+ padding: 0;
+ border: none;
+ cursor: pointer;
+ font-size: inherit;
+}
+
+.comfy-menu .comfy-menu-actions .comfy-settings-btn {
+ font-size: 0.6em;
+}
+
+button.comfy-close-menu-btn {
+ font-size: 1em;
+ line-height: 12px;
+ color: #ccc;
+ position: relative;
+ top: -1px;
+}
+
+.comfy-menu-queue-size {
+ flex: auto;
+}
+
+.comfy-menu button,
+.comfy-modal button {
+ font-size: 20px;
+}
+
+.comfy-menu-btns {
+ margin-bottom: 10px;
+ width: 100%;
+}
+
+.comfy-menu-btns button {
+ font-size: 10px;
+ width: 50%;
+ color: var(--descrip-text) !important;
+}
+
+.comfy-menu > button {
+ width: 100%;
+}
+
+.comfy-btn,
+.comfy-menu > button,
+.comfy-menu-btns button,
+.comfy-menu .comfy-list button,
+.comfy-modal button {
+ color: var(--input-text);
+ background-color: var(--comfy-input-bg);
+ border-radius: 8px;
+ border-color: var(--border-color);
+ border-style: solid;
+ margin-top: 2px;
+}
+
+.comfy-btn:hover:not(:disabled),
+.comfy-menu > button:hover,
+.comfy-menu-btns button:hover,
+.comfy-menu .comfy-list button:hover,
+.comfy-modal button:hover,
+.comfy-menu-actions button:hover {
+ filter: brightness(1.2);
+ will-change: transform;
+ cursor: pointer;
+}
+
+span.drag-handle {
+ width: 10px;
+ height: 20px;
+ display: inline-block;
+ overflow: hidden;
+ line-height: 5px;
+ padding: 3px 4px;
+ cursor: move;
+ vertical-align: middle;
+ margin-top: -.4em;
+ margin-left: -.2em;
+ font-size: 12px;
+ font-family: sans-serif;
+ letter-spacing: 2px;
+ color: var(--drag-text);
+ text-shadow: 1px 0 1px black;
+}
+
+span.drag-handle::after {
+ content: '.. .. ..';
+}
+
+.comfy-queue-btn {
+ width: 100%;
+}
+
+.comfy-list {
+ color: var(--descrip-text);
+ background-color: var(--comfy-menu-bg);
+ margin-bottom: 10px;
+ border-color: var(--border-color);
+ border-style: solid;
+}
+
+.comfy-list-items {
+ overflow-y: scroll;
+ max-height: 100px;
+ min-height: 25px;
+ background-color: var(--comfy-input-bg);
+ padding: 5px;
+}
+
+.comfy-list h4 {
+ min-width: 160px;
+ margin: 0;
+ padding: 3px;
+ font-weight: normal;
+}
+
+.comfy-list-items button {
+ font-size: 10px;
+}
+
+.comfy-list-actions {
+ margin: 5px;
+ display: flex;
+ gap: 5px;
+ justify-content: center;
+}
+
+.comfy-list-actions button {
+ font-size: 12px;
+}
+
+button.comfy-queue-btn {
+ margin: 6px 0 !important;
+}
+
+.comfy-modal.comfy-settings,
+.comfy-modal.comfy-manage-templates {
+ text-align: center;
+ font-family: sans-serif;
+ color: var(--descrip-text);
+ z-index: 99;
+}
+
+.comfy-modal.comfy-settings input[type="range"] {
+ vertical-align: middle;
+}
+
+.comfy-modal.comfy-settings input[type="range"] + input[type="number"] {
+ width: 3.5em;
+}
+
+.comfy-modal input,
+.comfy-modal select {
+ color: var(--input-text);
+ background-color: var(--comfy-input-bg);
+ border-radius: 8px;
+ border-color: var(--border-color);
+ border-style: solid;
+ font-size: inherit;
+}
+
+.comfy-tooltip-indicator {
+ text-decoration: underline;
+ text-decoration-style: dashed;
+}
+
+@media only screen and (max-height: 850px) {
+ .comfy-menu {
+ top: 0 !important;
+ bottom: 0 !important;
+ left: auto !important;
+ right: 0 !important;
+ border-radius: 0;
+ }
+
+ .comfy-menu span.drag-handle {
+ display: none;
+ }
+
+ .comfy-menu-queue-size {
+ flex: unset;
+ }
+
+ .comfy-menu-header {
+ justify-content: space-between;
+ }
+ .comfy-menu-actions {
+ gap: 10px;
+ font-size: 28px;
+ }
+}
+
+/* Input popup */
+
+.graphdialog {
+ min-height: 1em;
+ background-color: var(--comfy-menu-bg);
+}
+
+.graphdialog .name {
+ font-size: 14px;
+ font-family: sans-serif;
+ color: var(--descrip-text);
+}
+
+.graphdialog button {
+ margin-top: unset;
+ vertical-align: unset;
+ height: 1.6em;
+ padding-right: 8px;
+}
+
+.graphdialog input, .graphdialog textarea, .graphdialog select {
+ background-color: var(--comfy-input-bg);
+ border: 2px solid;
+ border-color: var(--border-color);
+ color: var(--input-text);
+ border-radius: 12px 0 0 12px;
+}
+
+/* Dialogs */
+
+dialog {
+ box-shadow: 0 0 20px #888888;
+}
+
+dialog::backdrop {
+ background: rgba(0, 0, 0, 0.5);
+}
+
+.comfy-dialog.comfyui-dialog.comfy-modal {
+ top: 0;
+ left: 0;
+ right: 0;
+ bottom: 0;
+ transform: none;
+}
+
+.comfy-dialog.comfy-modal {
+ font-family: Arial, sans-serif;
+ border-color: var(--bg-color);
+ box-shadow: none;
+ border: 2px solid var(--border-color);
+}
+
+.comfy-dialog .comfy-modal-content {
+ flex-direction: row;
+ flex-wrap: wrap;
+ gap: 10px;
+ color: var(--fg-color);
+}
+
+.comfy-dialog .comfy-modal-content h3 {
+ margin-top: 0;
+}
+
+.comfy-dialog .comfy-modal-content > p {
+ width: 100%;
+}
+
+.comfy-dialog .comfy-modal-content > .comfyui-button {
+ flex: 1;
+ justify-content: center;
+}
+
+#comfy-settings-dialog {
+ padding: 0;
+ width: 41rem;
+}
+
+#comfy-settings-dialog tr > td:first-child {
+ text-align: right;
+}
+
+#comfy-settings-dialog tbody button, #comfy-settings-dialog table > button {
+ background-color: var(--bg-color);
+ border: 1px var(--border-color) solid;
+ border-radius: 0;
+ color: var(--input-text);
+ font-size: 1rem;
+ padding: 0.5rem;
+}
+
+#comfy-settings-dialog button:hover {
+ background-color: var(--tr-odd-bg-color);
+}
+
+/* General CSS for tables */
+
+.comfy-table {
+ border-collapse: collapse;
+ color: var(--input-text);
+ font-family: Arial, sans-serif;
+ width: 100%;
+}
+
+.comfy-table caption {
+ position: sticky;
+ top: 0;
+ background-color: var(--bg-color);
+ color: var(--input-text);
+ font-size: 1rem;
+ font-weight: bold;
+ padding: 8px;
+ text-align: center;
+ border-bottom: 1px solid var(--border-color);
+}
+
+.comfy-table caption .comfy-btn {
+ position: absolute;
+ top: -2px;
+ right: 0;
+ bottom: 0;
+ cursor: pointer;
+ border: none;
+ height: 100%;
+ border-radius: 0;
+ aspect-ratio: 1/1;
+ -webkit-user-select: none;
+ -moz-user-select: none;
+ user-select: none;
+ font-size: 20px;
+}
+
+.comfy-table caption .comfy-btn:focus {
+ outline: none;
+}
+
+.comfy-table tr:nth-child(even) {
+ background-color: var(--tr-even-bg-color);
+}
+
+.comfy-table tr:nth-child(odd) {
+ background-color: var(--tr-odd-bg-color);
+}
+
+.comfy-table td,
+.comfy-table th {
+ border: 1px solid var(--border-color);
+ padding: 8px;
+}
+
+/* Context menu */
+
+.litegraph .dialog {
+ z-index: 1;
+ font-family: Arial, sans-serif;
+}
+
+.litegraph .litemenu-entry.has_submenu {
+ position: relative;
+ padding-right: 20px;
+}
+
+.litemenu-entry.has_submenu::after {
+ content: ">";
+ position: absolute;
+ top: 0;
+ right: 2px;
+}
+
+.litegraph.litecontextmenu,
+.litegraph.litecontextmenu.dark {
+ z-index: 9999 !important;
+ background-color: var(--comfy-menu-bg) !important;
+ filter: brightness(95%);
+ will-change: transform;
+}
+
+.litegraph.litecontextmenu .litemenu-entry:hover:not(.disabled):not(.separator) {
+ background-color: var(--comfy-menu-bg) !important;
+ filter: brightness(155%);
+ will-change: transform;
+ color: var(--input-text);
+}
+
+.litegraph.litecontextmenu .litemenu-entry.submenu,
+.litegraph.litecontextmenu.dark .litemenu-entry.submenu {
+ background-color: var(--comfy-menu-bg) !important;
+ color: var(--input-text);
+}
+
+.litegraph.litecontextmenu input {
+ background-color: var(--comfy-input-bg) !important;
+ color: var(--input-text) !important;
+}
+
+.comfy-context-menu-filter {
+ box-sizing: border-box;
+ border: 1px solid #999;
+ margin: 0 0 5px 5px;
+ width: calc(100% - 10px);
+}
+
+.comfy-img-preview {
+ pointer-events: none;
+ overflow: hidden;
+ display: flex;
+ flex-wrap: wrap;
+ align-content: flex-start;
+ justify-content: center;
+}
+
+.comfy-img-preview img {
+ -o-object-fit: contain;
+ object-fit: contain;
+ width: var(--comfy-img-preview-width);
+ height: var(--comfy-img-preview-height);
+}
+
+.comfy-missing-nodes li button {
+ font-size: 12px;
+ margin-left: 5px;
+}
+
+/* Search box */
+
+.litegraph.litesearchbox {
+ z-index: 9999 !important;
+ background-color: var(--comfy-menu-bg) !important;
+ overflow: hidden;
+ display: block;
+}
+
+.litegraph.litesearchbox input,
+.litegraph.litesearchbox select {
+ background-color: var(--comfy-input-bg) !important;
+ color: var(--input-text);
+}
+
+.litegraph.lite-search-item {
+ color: var(--input-text);
+ background-color: var(--comfy-input-bg);
+ filter: brightness(80%);
+ will-change: transform;
+ padding-left: 0.2em;
+}
+
+.litegraph.lite-search-item.generic_type {
+ color: var(--input-text);
+ filter: brightness(50%);
+ will-change: transform;
+}
+
+@media only screen and (max-width: 450px) {
+ #comfy-settings-dialog .comfy-table tbody {
+ display: grid;
+ }
+ #comfy-settings-dialog .comfy-table tr {
+ display: grid;
+ }
+ #comfy-settings-dialog tr > td:first-child {
+ text-align: center;
+ border-bottom: none;
+ padding-bottom: 0;
+ }
+ #comfy-settings-dialog tr > td:not(:first-child) {
+ text-align: center;
+ border-top: none;
+ }
+}
+
+audio.comfy-audio.empty-audio-widget {
+ display: none;
+}
+
+#vue-app {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ pointer-events: none;
+}
+
+/* Set auto complete panel's width as it is not accessible within vue-root */
+.p-autocomplete-overlay {
+ max-width: 25vw;
+}
+@font-face {
+ font-family: 'primeicons';
+ font-display: block;
+ src: url('./primeicons-DMOk5skT.eot');
+ src: url('./primeicons-DMOk5skT.eot?#iefix') format('embedded-opentype'), url('./primeicons-C6QP2o4f.woff2') format('woff2'), url('./primeicons-WjwUDZjB.woff') format('woff'), url('./primeicons-MpK4pl85.ttf') format('truetype'), url('./primeicons-Dr5RGzOO.svg?#primeicons') format('svg');
+ font-weight: normal;
+ font-style: normal;
+}
+
+.pi {
+ font-family: 'primeicons';
+ speak: none;
+ font-style: normal;
+ font-weight: normal;
+ font-variant: normal;
+ text-transform: none;
+ line-height: 1;
+ display: inline-block;
+ -webkit-font-smoothing: antialiased;
+ -moz-osx-font-smoothing: grayscale;
+}
+
+.pi:before {
+ --webkit-backface-visibility:hidden;
+ backface-visibility: hidden;
+}
+
+.pi-fw {
+ width: 1.28571429em;
+ text-align: center;
+}
+
+.pi-spin {
+ animation: fa-spin 2s infinite linear;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .pi-spin {
+ animation-delay: -1ms;
+ animation-duration: 1ms;
+ animation-iteration-count: 1;
+ transition-delay: 0s;
+ transition-duration: 0s;
+ }
+}
+
+@keyframes fa-spin {
+ 0% {
+ transform: rotate(0deg);
+ }
+ 100% {
+ transform: rotate(359deg);
+ }
+}
+
+.pi-folder-plus:before {
+ content: "\ea05";
+}
+
+.pi-receipt:before {
+ content: "\ea06";
+}
+
+.pi-asterisk:before {
+ content: "\ea07";
+}
+
+.pi-face-smile:before {
+ content: "\ea08";
+}
+
+.pi-pinterest:before {
+ content: "\ea09";
+}
+
+.pi-expand:before {
+ content: "\ea0a";
+}
+
+.pi-pen-to-square:before {
+ content: "\ea0b";
+}
+
+.pi-wave-pulse:before {
+ content: "\ea0c";
+}
+
+.pi-turkish-lira:before {
+ content: "\ea0d";
+}
+
+.pi-spinner-dotted:before {
+ content: "\ea0e";
+}
+
+.pi-crown:before {
+ content: "\ea0f";
+}
+
+.pi-pause-circle:before {
+ content: "\ea10";
+}
+
+.pi-warehouse:before {
+ content: "\ea11";
+}
+
+.pi-objects-column:before {
+ content: "\ea12";
+}
+
+.pi-clipboard:before {
+ content: "\ea13";
+}
+
+.pi-play-circle:before {
+ content: "\ea14";
+}
+
+.pi-venus:before {
+ content: "\ea15";
+}
+
+.pi-cart-minus:before {
+ content: "\ea16";
+}
+
+.pi-file-plus:before {
+ content: "\ea17";
+}
+
+.pi-microchip:before {
+ content: "\ea18";
+}
+
+.pi-twitch:before {
+ content: "\ea19";
+}
+
+.pi-building-columns:before {
+ content: "\ea1a";
+}
+
+.pi-file-check:before {
+ content: "\ea1b";
+}
+
+.pi-microchip-ai:before {
+ content: "\ea1c";
+}
+
+.pi-trophy:before {
+ content: "\ea1d";
+}
+
+.pi-barcode:before {
+ content: "\ea1e";
+}
+
+.pi-file-arrow-up:before {
+ content: "\ea1f";
+}
+
+.pi-mars:before {
+ content: "\ea20";
+}
+
+.pi-tiktok:before {
+ content: "\ea21";
+}
+
+.pi-arrow-up-right-and-arrow-down-left-from-center:before {
+ content: "\ea22";
+}
+
+.pi-ethereum:before {
+ content: "\ea23";
+}
+
+.pi-list-check:before {
+ content: "\ea24";
+}
+
+.pi-thumbtack:before {
+ content: "\ea25";
+}
+
+.pi-arrow-down-left-and-arrow-up-right-to-center:before {
+ content: "\ea26";
+}
+
+.pi-equals:before {
+ content: "\ea27";
+}
+
+.pi-lightbulb:before {
+ content: "\ea28";
+}
+
+.pi-star-half:before {
+ content: "\ea29";
+}
+
+.pi-address-book:before {
+ content: "\ea2a";
+}
+
+.pi-chart-scatter:before {
+ content: "\ea2b";
+}
+
+.pi-indian-rupee:before {
+ content: "\ea2c";
+}
+
+.pi-star-half-fill:before {
+ content: "\ea2d";
+}
+
+.pi-cart-arrow-down:before {
+ content: "\ea2e";
+}
+
+.pi-calendar-clock:before {
+ content: "\ea2f";
+}
+
+.pi-sort-up-fill:before {
+ content: "\ea30";
+}
+
+.pi-sparkles:before {
+ content: "\ea31";
+}
+
+.pi-bullseye:before {
+ content: "\ea32";
+}
+
+.pi-sort-down-fill:before {
+ content: "\ea33";
+}
+
+.pi-graduation-cap:before {
+ content: "\ea34";
+}
+
+.pi-hammer:before {
+ content: "\ea35";
+}
+
+.pi-bell-slash:before {
+ content: "\ea36";
+}
+
+.pi-gauge:before {
+ content: "\ea37";
+}
+
+.pi-shop:before {
+ content: "\ea38";
+}
+
+.pi-headphones:before {
+ content: "\ea39";
+}
+
+.pi-eraser:before {
+ content: "\ea04";
+}
+
+.pi-stopwatch:before {
+ content: "\ea01";
+}
+
+.pi-verified:before {
+ content: "\ea02";
+}
+
+.pi-delete-left:before {
+ content: "\ea03";
+}
+
+.pi-hourglass:before {
+ content: "\e9fe";
+}
+
+.pi-truck:before {
+ content: "\ea00";
+}
+
+.pi-wrench:before {
+ content: "\e9ff";
+}
+
+.pi-microphone:before {
+ content: "\e9fa";
+}
+
+.pi-megaphone:before {
+ content: "\e9fb";
+}
+
+.pi-arrow-right-arrow-left:before {
+ content: "\e9fc";
+}
+
+.pi-bitcoin:before {
+ content: "\e9fd";
+}
+
+.pi-file-edit:before {
+ content: "\e9f6";
+}
+
+.pi-language:before {
+ content: "\e9f7";
+}
+
+.pi-file-export:before {
+ content: "\e9f8";
+}
+
+.pi-file-import:before {
+ content: "\e9f9";
+}
+
+.pi-file-word:before {
+ content: "\e9f1";
+}
+
+.pi-gift:before {
+ content: "\e9f2";
+}
+
+.pi-cart-plus:before {
+ content: "\e9f3";
+}
+
+.pi-thumbs-down-fill:before {
+ content: "\e9f4";
+}
+
+.pi-thumbs-up-fill:before {
+ content: "\e9f5";
+}
+
+.pi-arrows-alt:before {
+ content: "\e9f0";
+}
+
+.pi-calculator:before {
+ content: "\e9ef";
+}
+
+.pi-sort-alt-slash:before {
+ content: "\e9ee";
+}
+
+.pi-arrows-h:before {
+ content: "\e9ec";
+}
+
+.pi-arrows-v:before {
+ content: "\e9ed";
+}
+
+.pi-pound:before {
+ content: "\e9eb";
+}
+
+.pi-prime:before {
+ content: "\e9ea";
+}
+
+.pi-chart-pie:before {
+ content: "\e9e9";
+}
+
+.pi-reddit:before {
+ content: "\e9e8";
+}
+
+.pi-code:before {
+ content: "\e9e7";
+}
+
+.pi-sync:before {
+ content: "\e9e6";
+}
+
+.pi-shopping-bag:before {
+ content: "\e9e5";
+}
+
+.pi-server:before {
+ content: "\e9e4";
+}
+
+.pi-database:before {
+ content: "\e9e3";
+}
+
+.pi-hashtag:before {
+ content: "\e9e2";
+}
+
+.pi-bookmark-fill:before {
+ content: "\e9df";
+}
+
+.pi-filter-fill:before {
+ content: "\e9e0";
+}
+
+.pi-heart-fill:before {
+ content: "\e9e1";
+}
+
+.pi-flag-fill:before {
+ content: "\e9de";
+}
+
+.pi-circle:before {
+ content: "\e9dc";
+}
+
+.pi-circle-fill:before {
+ content: "\e9dd";
+}
+
+.pi-bolt:before {
+ content: "\e9db";
+}
+
+.pi-history:before {
+ content: "\e9da";
+}
+
+.pi-box:before {
+ content: "\e9d9";
+}
+
+.pi-at:before {
+ content: "\e9d8";
+}
+
+.pi-arrow-up-right:before {
+ content: "\e9d4";
+}
+
+.pi-arrow-up-left:before {
+ content: "\e9d5";
+}
+
+.pi-arrow-down-left:before {
+ content: "\e9d6";
+}
+
+.pi-arrow-down-right:before {
+ content: "\e9d7";
+}
+
+.pi-telegram:before {
+ content: "\e9d3";
+}
+
+.pi-stop-circle:before {
+ content: "\e9d2";
+}
+
+.pi-stop:before {
+ content: "\e9d1";
+}
+
+.pi-whatsapp:before {
+ content: "\e9d0";
+}
+
+.pi-building:before {
+ content: "\e9cf";
+}
+
+.pi-qrcode:before {
+ content: "\e9ce";
+}
+
+.pi-car:before {
+ content: "\e9cd";
+}
+
+.pi-instagram:before {
+ content: "\e9cc";
+}
+
+.pi-linkedin:before {
+ content: "\e9cb";
+}
+
+.pi-send:before {
+ content: "\e9ca";
+}
+
+.pi-slack:before {
+ content: "\e9c9";
+}
+
+.pi-sun:before {
+ content: "\e9c8";
+}
+
+.pi-moon:before {
+ content: "\e9c7";
+}
+
+.pi-vimeo:before {
+ content: "\e9c6";
+}
+
+.pi-youtube:before {
+ content: "\e9c5";
+}
+
+.pi-flag:before {
+ content: "\e9c4";
+}
+
+.pi-wallet:before {
+ content: "\e9c3";
+}
+
+.pi-map:before {
+ content: "\e9c2";
+}
+
+.pi-link:before {
+ content: "\e9c1";
+}
+
+.pi-credit-card:before {
+ content: "\e9bf";
+}
+
+.pi-discord:before {
+ content: "\e9c0";
+}
+
+.pi-percentage:before {
+ content: "\e9be";
+}
+
+.pi-euro:before {
+ content: "\e9bd";
+}
+
+.pi-book:before {
+ content: "\e9ba";
+}
+
+.pi-shield:before {
+ content: "\e9b9";
+}
+
+.pi-paypal:before {
+ content: "\e9bb";
+}
+
+.pi-amazon:before {
+ content: "\e9bc";
+}
+
+.pi-phone:before {
+ content: "\e9b8";
+}
+
+.pi-filter-slash:before {
+ content: "\e9b7";
+}
+
+.pi-facebook:before {
+ content: "\e9b4";
+}
+
+.pi-github:before {
+ content: "\e9b5";
+}
+
+.pi-twitter:before {
+ content: "\e9b6";
+}
+
+.pi-step-backward-alt:before {
+ content: "\e9ac";
+}
+
+.pi-step-forward-alt:before {
+ content: "\e9ad";
+}
+
+.pi-forward:before {
+ content: "\e9ae";
+}
+
+.pi-backward:before {
+ content: "\e9af";
+}
+
+.pi-fast-backward:before {
+ content: "\e9b0";
+}
+
+.pi-fast-forward:before {
+ content: "\e9b1";
+}
+
+.pi-pause:before {
+ content: "\e9b2";
+}
+
+.pi-play:before {
+ content: "\e9b3";
+}
+
+.pi-compass:before {
+ content: "\e9ab";
+}
+
+.pi-id-card:before {
+ content: "\e9aa";
+}
+
+.pi-ticket:before {
+ content: "\e9a9";
+}
+
+.pi-file-o:before {
+ content: "\e9a8";
+}
+
+.pi-reply:before {
+ content: "\e9a7";
+}
+
+.pi-directions-alt:before {
+ content: "\e9a5";
+}
+
+.pi-directions:before {
+ content: "\e9a6";
+}
+
+.pi-thumbs-up:before {
+ content: "\e9a3";
+}
+
+.pi-thumbs-down:before {
+ content: "\e9a4";
+}
+
+.pi-sort-numeric-down-alt:before {
+ content: "\e996";
+}
+
+.pi-sort-numeric-up-alt:before {
+ content: "\e997";
+}
+
+.pi-sort-alpha-down-alt:before {
+ content: "\e998";
+}
+
+.pi-sort-alpha-up-alt:before {
+ content: "\e999";
+}
+
+.pi-sort-numeric-down:before {
+ content: "\e99a";
+}
+
+.pi-sort-numeric-up:before {
+ content: "\e99b";
+}
+
+.pi-sort-alpha-down:before {
+ content: "\e99c";
+}
+
+.pi-sort-alpha-up:before {
+ content: "\e99d";
+}
+
+.pi-sort-alt:before {
+ content: "\e99e";
+}
+
+.pi-sort-amount-up:before {
+ content: "\e99f";
+}
+
+.pi-sort-amount-down:before {
+ content: "\e9a0";
+}
+
+.pi-sort-amount-down-alt:before {
+ content: "\e9a1";
+}
+
+.pi-sort-amount-up-alt:before {
+ content: "\e9a2";
+}
+
+.pi-palette:before {
+ content: "\e995";
+}
+
+.pi-undo:before {
+ content: "\e994";
+}
+
+.pi-desktop:before {
+ content: "\e993";
+}
+
+.pi-sliders-v:before {
+ content: "\e991";
+}
+
+.pi-sliders-h:before {
+ content: "\e992";
+}
+
+.pi-search-plus:before {
+ content: "\e98f";
+}
+
+.pi-search-minus:before {
+ content: "\e990";
+}
+
+.pi-file-excel:before {
+ content: "\e98e";
+}
+
+.pi-file-pdf:before {
+ content: "\e98d";
+}
+
+.pi-check-square:before {
+ content: "\e98c";
+}
+
+.pi-chart-line:before {
+ content: "\e98b";
+}
+
+.pi-user-edit:before {
+ content: "\e98a";
+}
+
+.pi-exclamation-circle:before {
+ content: "\e989";
+}
+
+.pi-android:before {
+ content: "\e985";
+}
+
+.pi-google:before {
+ content: "\e986";
+}
+
+.pi-apple:before {
+ content: "\e987";
+}
+
+.pi-microsoft:before {
+ content: "\e988";
+}
+
+.pi-heart:before {
+ content: "\e984";
+}
+
+.pi-mobile:before {
+ content: "\e982";
+}
+
+.pi-tablet:before {
+ content: "\e983";
+}
+
+.pi-key:before {
+ content: "\e981";
+}
+
+.pi-shopping-cart:before {
+ content: "\e980";
+}
+
+.pi-comments:before {
+ content: "\e97e";
+}
+
+.pi-comment:before {
+ content: "\e97f";
+}
+
+.pi-briefcase:before {
+ content: "\e97d";
+}
+
+.pi-bell:before {
+ content: "\e97c";
+}
+
+.pi-paperclip:before {
+ content: "\e97b";
+}
+
+.pi-share-alt:before {
+ content: "\e97a";
+}
+
+.pi-envelope:before {
+ content: "\e979";
+}
+
+.pi-volume-down:before {
+ content: "\e976";
+}
+
+.pi-volume-up:before {
+ content: "\e977";
+}
+
+.pi-volume-off:before {
+ content: "\e978";
+}
+
+.pi-eject:before {
+ content: "\e975";
+}
+
+.pi-money-bill:before {
+ content: "\e974";
+}
+
+.pi-images:before {
+ content: "\e973";
+}
+
+.pi-image:before {
+ content: "\e972";
+}
+
+.pi-sign-in:before {
+ content: "\e970";
+}
+
+.pi-sign-out:before {
+ content: "\e971";
+}
+
+.pi-wifi:before {
+ content: "\e96f";
+}
+
+.pi-sitemap:before {
+ content: "\e96e";
+}
+
+.pi-chart-bar:before {
+ content: "\e96d";
+}
+
+.pi-camera:before {
+ content: "\e96c";
+}
+
+.pi-dollar:before {
+ content: "\e96b";
+}
+
+.pi-lock-open:before {
+ content: "\e96a";
+}
+
+.pi-table:before {
+ content: "\e969";
+}
+
+.pi-map-marker:before {
+ content: "\e968";
+}
+
+.pi-list:before {
+ content: "\e967";
+}
+
+.pi-eye-slash:before {
+ content: "\e965";
+}
+
+.pi-eye:before {
+ content: "\e966";
+}
+
+.pi-folder-open:before {
+ content: "\e964";
+}
+
+.pi-folder:before {
+ content: "\e963";
+}
+
+.pi-video:before {
+ content: "\e962";
+}
+
+.pi-inbox:before {
+ content: "\e961";
+}
+
+.pi-lock:before {
+ content: "\e95f";
+}
+
+.pi-unlock:before {
+ content: "\e960";
+}
+
+.pi-tags:before {
+ content: "\e95d";
+}
+
+.pi-tag:before {
+ content: "\e95e";
+}
+
+.pi-power-off:before {
+ content: "\e95c";
+}
+
+.pi-save:before {
+ content: "\e95b";
+}
+
+.pi-question-circle:before {
+ content: "\e959";
+}
+
+.pi-question:before {
+ content: "\e95a";
+}
+
+.pi-copy:before {
+ content: "\e957";
+}
+
+.pi-file:before {
+ content: "\e958";
+}
+
+.pi-clone:before {
+ content: "\e955";
+}
+
+.pi-calendar-times:before {
+ content: "\e952";
+}
+
+.pi-calendar-minus:before {
+ content: "\e953";
+}
+
+.pi-calendar-plus:before {
+ content: "\e954";
+}
+
+.pi-ellipsis-v:before {
+ content: "\e950";
+}
+
+.pi-ellipsis-h:before {
+ content: "\e951";
+}
+
+.pi-bookmark:before {
+ content: "\e94e";
+}
+
+.pi-globe:before {
+ content: "\e94f";
+}
+
+.pi-replay:before {
+ content: "\e94d";
+}
+
+.pi-filter:before {
+ content: "\e94c";
+}
+
+.pi-print:before {
+ content: "\e94b";
+}
+
+.pi-align-right:before {
+ content: "\e946";
+}
+
+.pi-align-left:before {
+ content: "\e947";
+}
+
+.pi-align-center:before {
+ content: "\e948";
+}
+
+.pi-align-justify:before {
+ content: "\e949";
+}
+
+.pi-cog:before {
+ content: "\e94a";
+}
+
+.pi-cloud-download:before {
+ content: "\e943";
+}
+
+.pi-cloud-upload:before {
+ content: "\e944";
+}
+
+.pi-cloud:before {
+ content: "\e945";
+}
+
+.pi-pencil:before {
+ content: "\e942";
+}
+
+.pi-users:before {
+ content: "\e941";
+}
+
+.pi-clock:before {
+ content: "\e940";
+}
+
+.pi-user-minus:before {
+ content: "\e93e";
+}
+
+.pi-user-plus:before {
+ content: "\e93f";
+}
+
+.pi-trash:before {
+ content: "\e93d";
+}
+
+.pi-external-link:before {
+ content: "\e93c";
+}
+
+.pi-window-maximize:before {
+ content: "\e93b";
+}
+
+.pi-window-minimize:before {
+ content: "\e93a";
+}
+
+.pi-refresh:before {
+ content: "\e938";
+}
+
+.pi-user:before {
+ content: "\e939";
+}
+
+.pi-exclamation-triangle:before {
+ content: "\e922";
+}
+
+.pi-calendar:before {
+ content: "\e927";
+}
+
+.pi-chevron-circle-left:before {
+ content: "\e928";
+}
+
+.pi-chevron-circle-down:before {
+ content: "\e929";
+}
+
+.pi-chevron-circle-right:before {
+ content: "\e92a";
+}
+
+.pi-chevron-circle-up:before {
+ content: "\e92b";
+}
+
+.pi-angle-double-down:before {
+ content: "\e92c";
+}
+
+.pi-angle-double-left:before {
+ content: "\e92d";
+}
+
+.pi-angle-double-right:before {
+ content: "\e92e";
+}
+
+.pi-angle-double-up:before {
+ content: "\e92f";
+}
+
+.pi-angle-down:before {
+ content: "\e930";
+}
+
+.pi-angle-left:before {
+ content: "\e931";
+}
+
+.pi-angle-right:before {
+ content: "\e932";
+}
+
+.pi-angle-up:before {
+ content: "\e933";
+}
+
+.pi-upload:before {
+ content: "\e934";
+}
+
+.pi-download:before {
+ content: "\e956";
+}
+
+.pi-ban:before {
+ content: "\e935";
+}
+
+.pi-star-fill:before {
+ content: "\e936";
+}
+
+.pi-star:before {
+ content: "\e937";
+}
+
+.pi-chevron-left:before {
+ content: "\e900";
+}
+
+.pi-chevron-right:before {
+ content: "\e901";
+}
+
+.pi-chevron-down:before {
+ content: "\e902";
+}
+
+.pi-chevron-up:before {
+ content: "\e903";
+}
+
+.pi-caret-left:before {
+ content: "\e904";
+}
+
+.pi-caret-right:before {
+ content: "\e905";
+}
+
+.pi-caret-down:before {
+ content: "\e906";
+}
+
+.pi-caret-up:before {
+ content: "\e907";
+}
+
+.pi-search:before {
+ content: "\e908";
+}
+
+.pi-check:before {
+ content: "\e909";
+}
+
+.pi-check-circle:before {
+ content: "\e90a";
+}
+
+.pi-times:before {
+ content: "\e90b";
+}
+
+.pi-times-circle:before {
+ content: "\e90c";
+}
+
+.pi-plus:before {
+ content: "\e90d";
+}
+
+.pi-plus-circle:before {
+ content: "\e90e";
+}
+
+.pi-minus:before {
+ content: "\e90f";
+}
+
+.pi-minus-circle:before {
+ content: "\e910";
+}
+
+.pi-circle-on:before {
+ content: "\e911";
+}
+
+.pi-circle-off:before {
+ content: "\e912";
+}
+
+.pi-sort-down:before {
+ content: "\e913";
+}
+
+.pi-sort-up:before {
+ content: "\e914";
+}
+
+.pi-sort:before {
+ content: "\e915";
+}
+
+.pi-step-backward:before {
+ content: "\e916";
+}
+
+.pi-step-forward:before {
+ content: "\e917";
+}
+
+.pi-th-large:before {
+ content: "\e918";
+}
+
+.pi-arrow-down:before {
+ content: "\e919";
+}
+
+.pi-arrow-left:before {
+ content: "\e91a";
+}
+
+.pi-arrow-right:before {
+ content: "\e91b";
+}
+
+.pi-arrow-up:before {
+ content: "\e91c";
+}
+
+.pi-bars:before {
+ content: "\e91d";
+}
+
+.pi-arrow-circle-down:before {
+ content: "\e91e";
+}
+
+.pi-arrow-circle-left:before {
+ content: "\e91f";
+}
+
+.pi-arrow-circle-right:before {
+ content: "\e920";
+}
+
+.pi-arrow-circle-up:before {
+ content: "\e921";
+}
+
+.pi-info:before {
+ content: "\e923";
+}
+
+.pi-info-circle:before {
+ content: "\e924";
+}
+
+.pi-home:before {
+ content: "\e925";
+}
+
+.pi-spinner:before {
+ content: "\e926";
+}
diff --git a/web/assets/index-BDBCRrlL.js b/web/assets/index-BDBCRrlL.js
new file mode 100644
index 000000000..2c88af6d1
--- /dev/null
+++ b/web/assets/index-BDBCRrlL.js
@@ -0,0 +1,6243 @@
+var __defProp = Object.defineProperty;
+var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
+import { aM as ComfyDialog, aN as $el, aO as ComfyApp, c as app, aH as LGraphCanvas, k as LiteGraph, e as LGraphNode, aP as applyTextReplacements, aQ as ComfyWidgets, aR as addValueControlWidgets, aS as DraggableList, av as useNodeDefStore, aT as api, L as LGraphGroup, aU as useToastStore, at as NodeSourceType, aV as NodeBadgeMode, u as useSettingStore, q as computed, w as watch, aW as BadgePosition, aJ as LGraphBadge$1, aX as _ } from "./index-Drc_oD2f.js";
+class ClipspaceDialog extends ComfyDialog {
+ static {
+ __name(this, "ClipspaceDialog");
+ }
+ static items = [];
+ static instance = null;
+ static registerButton(name, contextPredicate, callback) {
+ const item = $el("button", {
+ type: "button",
+ textContent: name,
+ contextPredicate,
+ onclick: callback
+ });
+ ClipspaceDialog.items.push(item);
+ }
+ static invalidatePreview() {
+ if (ComfyApp.clipspace && ComfyApp.clipspace.imgs && ComfyApp.clipspace.imgs.length > 0) {
+ const img_preview = document.getElementById(
+ "clipspace_preview"
+ );
+ if (img_preview) {
+ img_preview.src = ComfyApp.clipspace.imgs[ComfyApp.clipspace["selectedIndex"]].src;
+ img_preview.style.maxHeight = "100%";
+ img_preview.style.maxWidth = "100%";
+ }
+ }
+ }
+ static invalidate() {
+ if (ClipspaceDialog.instance) {
+ const self = ClipspaceDialog.instance;
+ const children = $el("div.comfy-modal-content", [
+ self.createImgSettings(),
+ ...self.createButtons()
+ ]);
+ if (self.element) {
+ self.element.removeChild(self.element.firstChild);
+ self.element.appendChild(children);
+ } else {
+ self.element = $el("div.comfy-modal", { parent: document.body }, [
+ children
+ ]);
+ }
+ if (self.element.children[0].children.length <= 1) {
+ self.element.children[0].appendChild(
+ $el("p", {}, [
+ "Unable to find the features to edit content of a format stored in the current Clipspace."
+ ])
+ );
+ }
+ ClipspaceDialog.invalidatePreview();
+ }
+ }
+ constructor() {
+ super();
+ }
+ createButtons() {
+ const buttons = [];
+ for (let idx in ClipspaceDialog.items) {
+ const item = ClipspaceDialog.items[idx];
+ if (!item.contextPredicate || item.contextPredicate())
+ buttons.push(ClipspaceDialog.items[idx]);
+ }
+ buttons.push(
+ $el("button", {
+ type: "button",
+ textContent: "Close",
+ onclick: /* @__PURE__ */ __name(() => {
+ this.close();
+ }, "onclick")
+ })
+ );
+ return buttons;
+ }
+ createImgSettings() {
+ if (ComfyApp.clipspace.imgs) {
+ const combo_items = [];
+ const imgs = ComfyApp.clipspace.imgs;
+ for (let i = 0; i < imgs.length; i++) {
+ combo_items.push($el("option", { value: i }, [`${i}`]));
+ }
+ const combo1 = $el(
+ "select",
+ {
+ id: "clipspace_img_selector",
+ onchange: /* @__PURE__ */ __name((event) => {
+ ComfyApp.clipspace["selectedIndex"] = event.target.selectedIndex;
+ ClipspaceDialog.invalidatePreview();
+ }, "onchange")
+ },
+ combo_items
+ );
+ const row1 = $el("tr", {}, [
+ $el("td", {}, [$el("font", { color: "white" }, ["Select Image"])]),
+ $el("td", {}, [combo1])
+ ]);
+ const combo2 = $el(
+ "select",
+ {
+ id: "clipspace_img_paste_mode",
+ onchange: /* @__PURE__ */ __name((event) => {
+ ComfyApp.clipspace["img_paste_mode"] = event.target.value;
+ }, "onchange")
+ },
+ [
+ $el("option", { value: "selected" }, "selected"),
+ $el("option", { value: "all" }, "all")
+ ]
+ );
+ combo2.value = ComfyApp.clipspace["img_paste_mode"];
+ const row2 = $el("tr", {}, [
+ $el("td", {}, [$el("font", { color: "white" }, ["Paste Mode"])]),
+ $el("td", {}, [combo2])
+ ]);
+ const td = $el(
+ "td",
+ { align: "center", width: "100px", height: "100px", colSpan: "2" },
+ [$el("img", { id: "clipspace_preview", ondragstart: /* @__PURE__ */ __name(() => false, "ondragstart") }, [])]
+ );
+ const row3 = $el("tr", {}, [td]);
+ return $el("table", {}, [row1, row2, row3]);
+ } else {
+ return [];
+ }
+ }
+ createImgPreview() {
+ if (ComfyApp.clipspace.imgs) {
+ return $el("img", { id: "clipspace_preview", ondragstart: /* @__PURE__ */ __name(() => false, "ondragstart") });
+ } else return [];
+ }
+ show() {
+ const img_preview = document.getElementById("clipspace_preview");
+ ClipspaceDialog.invalidate();
+ this.element.style.display = "block";
+ }
+}
+app.registerExtension({
+ name: "Comfy.Clipspace",
+ init(app2) {
+ app2.openClipspace = function() {
+ if (!ClipspaceDialog.instance) {
+ ClipspaceDialog.instance = new ClipspaceDialog();
+ ComfyApp.clipspace_invalidate_handler = ClipspaceDialog.invalidate;
+ }
+ if (ComfyApp.clipspace) {
+ ClipspaceDialog.instance.show();
+ } else app2.ui.dialog.show("Clipspace is Empty!");
+ };
+ }
+});
+window.comfyAPI = window.comfyAPI || {};
+window.comfyAPI.clipspace = window.comfyAPI.clipspace || {};
+window.comfyAPI.clipspace.ClipspaceDialog = ClipspaceDialog;
+const colorPalettes = {
+ dark: {
+ id: "dark",
+ name: "Dark (Default)",
+ colors: {
+ node_slot: {
+ CLIP: "#FFD500",
+ // bright yellow
+ CLIP_VISION: "#A8DADC",
+ // light blue-gray
+ CLIP_VISION_OUTPUT: "#ad7452",
+ // rusty brown-orange
+ CONDITIONING: "#FFA931",
+ // vibrant orange-yellow
+ CONTROL_NET: "#6EE7B7",
+ // soft mint green
+ IMAGE: "#64B5F6",
+ // bright sky blue
+ LATENT: "#FF9CF9",
+ // light pink-purple
+ MASK: "#81C784",
+ // muted green
+ MODEL: "#B39DDB",
+ // light lavender-purple
+ STYLE_MODEL: "#C2FFAE",
+ // light green-yellow
+ VAE: "#FF6E6E",
+ // bright red
+ NOISE: "#B0B0B0",
+ // gray
+ GUIDER: "#66FFFF",
+ // cyan
+ SAMPLER: "#ECB4B4",
+ // very soft red
+ SIGMAS: "#CDFFCD",
+ // soft lime green
+ TAESD: "#DCC274"
+ // cheesecake
+ },
+ litegraph_base: {
+ BACKGROUND_IMAGE: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAIAAAD/gAIDAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAQBJREFUeNrs1rEKwjAUhlETUkj3vP9rdmr1Ysammk2w5wdxuLgcMHyptfawuZX4pJSWZTnfnu/lnIe/jNNxHHGNn//HNbbv+4dr6V+11uF527arU7+u63qfa/bnmh8sWLBgwYJlqRf8MEptXPBXJXa37BSl3ixYsGDBMliwFLyCV/DeLIMFCxYsWLBMwSt4Be/NggXLYMGCBUvBK3iNruC9WbBgwYJlsGApeAWv4L1ZBgsWLFiwYJmCV/AK3psFC5bBggULloJX8BpdwXuzYMGCBctgwVLwCl7Be7MMFixYsGDBsu8FH1FaSmExVfAxBa/gvVmwYMGCZbBg/W4vAQYA5tRF9QYlv/QAAAAASUVORK5CYII=",
+ CLEAR_BACKGROUND_COLOR: "#222",
+ NODE_TITLE_COLOR: "#999",
+ NODE_SELECTED_TITLE_COLOR: "#FFF",
+ NODE_TEXT_SIZE: 14,
+ NODE_TEXT_COLOR: "#AAA",
+ NODE_SUBTEXT_SIZE: 12,
+ NODE_DEFAULT_COLOR: "#333",
+ NODE_DEFAULT_BGCOLOR: "#353535",
+ NODE_DEFAULT_BOXCOLOR: "#666",
+ NODE_DEFAULT_SHAPE: "box",
+ NODE_BOX_OUTLINE_COLOR: "#FFF",
+ DEFAULT_SHADOW_COLOR: "rgba(0,0,0,0.5)",
+ DEFAULT_GROUP_FONT: 24,
+ WIDGET_BGCOLOR: "#222",
+ WIDGET_OUTLINE_COLOR: "#666",
+ WIDGET_TEXT_COLOR: "#DDD",
+ WIDGET_SECONDARY_TEXT_COLOR: "#999",
+ LINK_COLOR: "#9A9",
+ EVENT_LINK_COLOR: "#A86",
+ CONNECTING_LINK_COLOR: "#AFA",
+ BADGE_FG_COLOR: "#FFF",
+ BADGE_BG_COLOR: "#0F1F0F"
+ },
+ comfy_base: {
+ "fg-color": "#fff",
+ "bg-color": "#202020",
+ "comfy-menu-bg": "#353535",
+ "comfy-input-bg": "#222",
+ "input-text": "#ddd",
+ "descrip-text": "#999",
+ "drag-text": "#ccc",
+ "error-text": "#ff4444",
+ "border-color": "#4e4e4e",
+ "tr-even-bg-color": "#222",
+ "tr-odd-bg-color": "#353535",
+ "content-bg": "#4e4e4e",
+ "content-fg": "#fff",
+ "content-hover-bg": "#222",
+ "content-hover-fg": "#fff"
+ }
+ }
+ },
+ light: {
+ id: "light",
+ name: "Light",
+ colors: {
+ node_slot: {
+ CLIP: "#FFA726",
+ // orange
+ CLIP_VISION: "#5C6BC0",
+ // indigo
+ CLIP_VISION_OUTPUT: "#8D6E63",
+ // brown
+ CONDITIONING: "#EF5350",
+ // red
+ CONTROL_NET: "#66BB6A",
+ // green
+ IMAGE: "#42A5F5",
+ // blue
+ LATENT: "#AB47BC",
+ // purple
+ MASK: "#9CCC65",
+ // light green
+ MODEL: "#7E57C2",
+ // deep purple
+ STYLE_MODEL: "#D4E157",
+ // lime
+ VAE: "#FF7043"
+ // deep orange
+ },
+ litegraph_base: {
+ BACKGROUND_IMAGE: "data:image/gif;base64,R0lGODlhZABkALMAAAAAAP///+vr6+rq6ujo6Ofn5+bm5uXl5d3d3f///wAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAAkALAAAAABkAGQAAAT/UMhJq7046827HkcoHkYxjgZhnGG6si5LqnIM0/fL4qwwIMAg0CAsEovBIxKhRDaNy2GUOX0KfVFrssrNdpdaqTeKBX+dZ+jYvEaTf+y4W66mC8PUdrE879f9d2mBeoNLfH+IhYBbhIx2jkiHiomQlGKPl4uZe3CaeZifnnijgkESBqipqqusra6vsLGys62SlZO4t7qbuby7CLa+wqGWxL3Gv3jByMOkjc2lw8vOoNSi0czAncXW3Njdx9Pf48/Z4Kbbx+fQ5evZ4u3k1fKR6cn03vHlp7T9/v8A/8Gbp4+gwXoFryXMB2qgwoMMHyKEqA5fxX322FG8tzBcRnMW/zlulPbRncmQGidKjMjyYsOSKEF2FBlJQMCbOHP6c9iSZs+UnGYCdbnSo1CZI5F64kn0p1KnTH02nSoV3dGTV7FFHVqVq1dtWcMmVQZTbNGu72zqXMuW7danVL+6e4t1bEy6MeueBYLXrNO5Ze36jQtWsOG97wIj1vt3St/DjTEORss4nNq2mDP3e7w4r1bFkSET5hy6s2TRlD2/mSxXtSHQhCunXo26NevCpmvD/UU6tuullzULH76q92zdZG/Ltv1a+W+osI/nRmyc+fRi1Xdbh+68+0vv10dH3+77KD/i6IdnX669/frn5Zsjh4/2PXju8+8bzc9/6fj27LFnX11/+IUnXWl7BJfegm79FyB9JOl3oHgSklefgxAC+FmFGpqHIYcCfkhgfCohSKKJVo044YUMttggiBkmp6KFXw1oII24oYhjiDByaKOOHcp3Y5BD/njikSkO+eBREQAAOw==",
+ CLEAR_BACKGROUND_COLOR: "lightgray",
+ NODE_TITLE_COLOR: "#222",
+ NODE_SELECTED_TITLE_COLOR: "#000",
+ NODE_TEXT_SIZE: 14,
+ NODE_TEXT_COLOR: "#444",
+ NODE_SUBTEXT_SIZE: 12,
+ NODE_DEFAULT_COLOR: "#F7F7F7",
+ NODE_DEFAULT_BGCOLOR: "#F5F5F5",
+ NODE_DEFAULT_BOXCOLOR: "#CCC",
+ NODE_DEFAULT_SHAPE: "box",
+ NODE_BOX_OUTLINE_COLOR: "#000",
+ DEFAULT_SHADOW_COLOR: "rgba(0,0,0,0.1)",
+ DEFAULT_GROUP_FONT: 24,
+ WIDGET_BGCOLOR: "#D4D4D4",
+ WIDGET_OUTLINE_COLOR: "#999",
+ WIDGET_TEXT_COLOR: "#222",
+ WIDGET_SECONDARY_TEXT_COLOR: "#555",
+ LINK_COLOR: "#4CAF50",
+ EVENT_LINK_COLOR: "#FF9800",
+ CONNECTING_LINK_COLOR: "#2196F3",
+ BADGE_FG_COLOR: "#000",
+ BADGE_BG_COLOR: "#FFF"
+ },
+ comfy_base: {
+ "fg-color": "#222",
+ "bg-color": "#DDD",
+ "comfy-menu-bg": "#F5F5F5",
+ "comfy-input-bg": "#C9C9C9",
+ "input-text": "#222",
+ "descrip-text": "#444",
+ "drag-text": "#555",
+ "error-text": "#F44336",
+ "border-color": "#888",
+ "tr-even-bg-color": "#f9f9f9",
+ "tr-odd-bg-color": "#fff",
+ "content-bg": "#e0e0e0",
+ "content-fg": "#222",
+ "content-hover-bg": "#adadad",
+ "content-hover-fg": "#222"
+ }
+ }
+ },
+ solarized: {
+ id: "solarized",
+ name: "Solarized",
+ colors: {
+ node_slot: {
+ CLIP: "#2AB7CA",
+ // light blue
+ CLIP_VISION: "#6c71c4",
+ // blue violet
+ CLIP_VISION_OUTPUT: "#859900",
+ // olive green
+ CONDITIONING: "#d33682",
+ // magenta
+ CONTROL_NET: "#d1ffd7",
+ // light mint green
+ IMAGE: "#5940bb",
+ // deep blue violet
+ LATENT: "#268bd2",
+ // blue
+ MASK: "#CCC9E7",
+ // light purple-gray
+ MODEL: "#dc322f",
+ // red
+ STYLE_MODEL: "#1a998a",
+ // teal
+ UPSCALE_MODEL: "#054A29",
+ // dark green
+ VAE: "#facfad"
+ // light pink-orange
+ },
+ litegraph_base: {
+ NODE_TITLE_COLOR: "#fdf6e3",
+ // Base3
+ NODE_SELECTED_TITLE_COLOR: "#A9D400",
+ NODE_TEXT_SIZE: 14,
+ NODE_TEXT_COLOR: "#657b83",
+ // Base00
+ NODE_SUBTEXT_SIZE: 12,
+ NODE_DEFAULT_COLOR: "#094656",
+ NODE_DEFAULT_BGCOLOR: "#073642",
+ // Base02
+ NODE_DEFAULT_BOXCOLOR: "#839496",
+ // Base0
+ NODE_DEFAULT_SHAPE: "box",
+ NODE_BOX_OUTLINE_COLOR: "#fdf6e3",
+ // Base3
+ DEFAULT_SHADOW_COLOR: "rgba(0,0,0,0.5)",
+ DEFAULT_GROUP_FONT: 24,
+ WIDGET_BGCOLOR: "#002b36",
+ // Base03
+ WIDGET_OUTLINE_COLOR: "#839496",
+ // Base0
+ WIDGET_TEXT_COLOR: "#fdf6e3",
+ // Base3
+ WIDGET_SECONDARY_TEXT_COLOR: "#93a1a1",
+ // Base1
+ LINK_COLOR: "#2aa198",
+ // Solarized Cyan
+ EVENT_LINK_COLOR: "#268bd2",
+ // Solarized Blue
+ CONNECTING_LINK_COLOR: "#859900"
+ // Solarized Green
+ },
+ comfy_base: {
+ "fg-color": "#fdf6e3",
+ // Base3
+ "bg-color": "#002b36",
+ // Base03
+ "comfy-menu-bg": "#073642",
+ // Base02
+ "comfy-input-bg": "#002b36",
+ // Base03
+ "input-text": "#93a1a1",
+ // Base1
+ "descrip-text": "#586e75",
+ // Base01
+ "drag-text": "#839496",
+ // Base0
+ "error-text": "#dc322f",
+ // Solarized Red
+ "border-color": "#657b83",
+ // Base00
+ "tr-even-bg-color": "#002b36",
+ "tr-odd-bg-color": "#073642",
+ "content-bg": "#657b83",
+ "content-fg": "#fdf6e3",
+ "content-hover-bg": "#002b36",
+ "content-hover-fg": "#fdf6e3"
+ }
+ }
+ },
+ arc: {
+ id: "arc",
+ name: "Arc",
+ colors: {
+ node_slot: {
+ BOOLEAN: "",
+ CLIP: "#eacb8b",
+ CLIP_VISION: "#A8DADC",
+ CLIP_VISION_OUTPUT: "#ad7452",
+ CONDITIONING: "#cf876f",
+ CONTROL_NET: "#00d78d",
+ CONTROL_NET_WEIGHTS: "",
+ FLOAT: "",
+ GLIGEN: "",
+ IMAGE: "#80a1c0",
+ IMAGEUPLOAD: "",
+ INT: "",
+ LATENT: "#b38ead",
+ LATENT_KEYFRAME: "",
+ MASK: "#a3bd8d",
+ MODEL: "#8978a7",
+ SAMPLER: "",
+ SIGMAS: "",
+ STRING: "",
+ STYLE_MODEL: "#C2FFAE",
+ T2I_ADAPTER_WEIGHTS: "",
+ TAESD: "#DCC274",
+ TIMESTEP_KEYFRAME: "",
+ UPSCALE_MODEL: "",
+ VAE: "#be616b"
+ },
+ litegraph_base: {
+ BACKGROUND_IMAGE: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAACXBIWXMAAAsTAAALEwEAmpwYAAABcklEQVR4nO3YMUoDARgF4RfxBqZI6/0vZqFn0MYtrLIQMFN8U6V4LAtD+Jm9XG/v30OGl2e/AP7yevz4+vx45nvgF/+QGITEICQGITEIiUFIjNNC3q43u3/YnRJyPOzeQ+0e220nhRzReC8e7R7bbdvl+Jal1Bs46jEIiUFIDEJiEBKDkBhKPbZT6qHdptRTu02p53DUYxASg5AYhMQgJAYhMZR6bKfUQ7tNqad2m1LP4ajHICQGITEIiUFIDEJiKPXYTqmHdptST+02pZ7DUY9BSAxCYhASg5AYhMRQ6rGdUg/tNqWe2m1KPYejHoOQGITEICQGITEIiaHUYzulHtptSj2125R6Dkc9BiExCIlBSAxCYhASQ6nHdko9tNuUemq3KfUcjnoMQmIQEoOQGITEICSGUo/tlHpotyn11G5T6jkc9RiExCAkBiExCIlBSAylHtsp9dBuU+qp3abUczjqMQiJQUgMQmIQEoOQGITE+AHFISNQrFTGuwAAAABJRU5ErkJggg==",
+ CLEAR_BACKGROUND_COLOR: "#2b2f38",
+ NODE_TITLE_COLOR: "#b2b7bd",
+ NODE_SELECTED_TITLE_COLOR: "#FFF",
+ NODE_TEXT_SIZE: 14,
+ NODE_TEXT_COLOR: "#AAA",
+ NODE_SUBTEXT_SIZE: 12,
+ NODE_DEFAULT_COLOR: "#2b2f38",
+ NODE_DEFAULT_BGCOLOR: "#242730",
+ NODE_DEFAULT_BOXCOLOR: "#6e7581",
+ NODE_DEFAULT_SHAPE: "box",
+ NODE_BOX_OUTLINE_COLOR: "#FFF",
+ DEFAULT_SHADOW_COLOR: "rgba(0,0,0,0.5)",
+ DEFAULT_GROUP_FONT: 22,
+ WIDGET_BGCOLOR: "#2b2f38",
+ WIDGET_OUTLINE_COLOR: "#6e7581",
+ WIDGET_TEXT_COLOR: "#DDD",
+ WIDGET_SECONDARY_TEXT_COLOR: "#b2b7bd",
+ LINK_COLOR: "#9A9",
+ EVENT_LINK_COLOR: "#A86",
+ CONNECTING_LINK_COLOR: "#AFA"
+ },
+ comfy_base: {
+ "fg-color": "#fff",
+ "bg-color": "#2b2f38",
+ "comfy-menu-bg": "#242730",
+ "comfy-input-bg": "#2b2f38",
+ "input-text": "#ddd",
+ "descrip-text": "#b2b7bd",
+ "drag-text": "#ccc",
+ "error-text": "#ff4444",
+ "border-color": "#6e7581",
+ "tr-even-bg-color": "#2b2f38",
+ "tr-odd-bg-color": "#242730",
+ "content-bg": "#6e7581",
+ "content-fg": "#fff",
+ "content-hover-bg": "#2b2f38",
+ "content-hover-fg": "#fff"
+ }
+ }
+ },
+ nord: {
+ id: "nord",
+ name: "Nord",
+ colors: {
+ node_slot: {
+ BOOLEAN: "",
+ CLIP: "#eacb8b",
+ CLIP_VISION: "#A8DADC",
+ CLIP_VISION_OUTPUT: "#ad7452",
+ CONDITIONING: "#cf876f",
+ CONTROL_NET: "#00d78d",
+ CONTROL_NET_WEIGHTS: "",
+ FLOAT: "",
+ GLIGEN: "",
+ IMAGE: "#80a1c0",
+ IMAGEUPLOAD: "",
+ INT: "",
+ LATENT: "#b38ead",
+ LATENT_KEYFRAME: "",
+ MASK: "#a3bd8d",
+ MODEL: "#8978a7",
+ SAMPLER: "",
+ SIGMAS: "",
+ STRING: "",
+ STYLE_MODEL: "#C2FFAE",
+ T2I_ADAPTER_WEIGHTS: "",
+ TAESD: "#DCC274",
+ TIMESTEP_KEYFRAME: "",
+ UPSCALE_MODEL: "",
+ VAE: "#be616b"
+ },
+ litegraph_base: {
+ BACKGROUND_IMAGE: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAIAAAD/gAIDAAAACXBIWXMAAAsTAAALEwEAmpwYAAAFu2lUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4gPHg6eG1wbWV0YSB4b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6ywF77IUvA8eFixYBgsWrNfWAZPltufdad+1AAAAAElFTkSuQmCC",
+ CLEAR_BACKGROUND_COLOR: "#212732",
+ NODE_TITLE_COLOR: "#999",
+ NODE_SELECTED_TITLE_COLOR: "#e5eaf0",
+ NODE_TEXT_SIZE: 14,
+ NODE_TEXT_COLOR: "#bcc2c8",
+ NODE_SUBTEXT_SIZE: 12,
+ NODE_DEFAULT_COLOR: "#2e3440",
+ NODE_DEFAULT_BGCOLOR: "#161b22",
+ NODE_DEFAULT_BOXCOLOR: "#545d70",
+ NODE_DEFAULT_SHAPE: "box",
+ NODE_BOX_OUTLINE_COLOR: "#e5eaf0",
+ DEFAULT_SHADOW_COLOR: "rgba(0,0,0,0.5)",
+ DEFAULT_GROUP_FONT: 24,
+ WIDGET_BGCOLOR: "#2e3440",
+ WIDGET_OUTLINE_COLOR: "#545d70",
+ WIDGET_TEXT_COLOR: "#bcc2c8",
+ WIDGET_SECONDARY_TEXT_COLOR: "#999",
+ LINK_COLOR: "#9A9",
+ EVENT_LINK_COLOR: "#A86",
+ CONNECTING_LINK_COLOR: "#AFA"
+ },
+ comfy_base: {
+ "fg-color": "#e5eaf0",
+ "bg-color": "#2e3440",
+ "comfy-menu-bg": "#161b22",
+ "comfy-input-bg": "#2e3440",
+ "input-text": "#bcc2c8",
+ "descrip-text": "#999",
+ "drag-text": "#ccc",
+ "error-text": "#ff4444",
+ "border-color": "#545d70",
+ "tr-even-bg-color": "#2e3440",
+ "tr-odd-bg-color": "#161b22",
+ "content-bg": "#545d70",
+ "content-fg": "#e5eaf0",
+ "content-hover-bg": "#2e3440",
+ "content-hover-fg": "#e5eaf0"
+ }
+ }
+ },
+ github: {
+ id: "github",
+ name: "Github",
+ colors: {
+ node_slot: {
+ BOOLEAN: "",
+ CLIP: "#eacb8b",
+ CLIP_VISION: "#A8DADC",
+ CLIP_VISION_OUTPUT: "#ad7452",
+ CONDITIONING: "#cf876f",
+ CONTROL_NET: "#00d78d",
+ CONTROL_NET_WEIGHTS: "",
+ FLOAT: "",
+ GLIGEN: "",
+ IMAGE: "#80a1c0",
+ IMAGEUPLOAD: "",
+ INT: "",
+ LATENT: "#b38ead",
+ LATENT_KEYFRAME: "",
+ MASK: "#a3bd8d",
+ MODEL: "#8978a7",
+ SAMPLER: "",
+ SIGMAS: "",
+ STRING: "",
+ STYLE_MODEL: "#C2FFAE",
+ T2I_ADAPTER_WEIGHTS: "",
+ TAESD: "#DCC274",
+ TIMESTEP_KEYFRAME: "",
+ UPSCALE_MODEL: "",
+ VAE: "#be616b"
+ },
+ litegraph_base: {
+ BACKGROUND_IMAGE: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAIAAAD/gAIDAAAACXBIWXMAAAsTAAALEwEAmpwYAAAGlmlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4gPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iQWRvYmUgWE1QIENvcmUgOS4xLWMwMDEgNzkuMTQ2Mjg5OSwgMjAyMy8wNi8yNS0yMDowMTo1NSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczpkYz0iaHR0cDovL3B1cmwub3JnL2RjL2VsZW1lbnRzLzEuMS8iIHhtbG5zOnBob3Rvc2hvcD0iaHR0cDovL25zLmFkb2JlLmNvbS9waG90b3Nob3AvMS4wLyIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0RXZ0PSJodHRwOi8v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",
+ NODE_DEFAULT_BGCOLOR: "#13171d",
+ NODE_DEFAULT_BOXCOLOR: "#30363d",
+ NODE_DEFAULT_SHAPE: "box",
+ NODE_BOX_OUTLINE_COLOR: "#e5eaf0",
+ DEFAULT_SHADOW_COLOR: "rgba(0,0,0,0.5)",
+ DEFAULT_GROUP_FONT: 24,
+ WIDGET_BGCOLOR: "#161b22",
+ WIDGET_OUTLINE_COLOR: "#30363d",
+ WIDGET_TEXT_COLOR: "#bcc2c8",
+ WIDGET_SECONDARY_TEXT_COLOR: "#999",
+ LINK_COLOR: "#9A9",
+ EVENT_LINK_COLOR: "#A86",
+ CONNECTING_LINK_COLOR: "#AFA"
+ },
+ comfy_base: {
+ "fg-color": "#e5eaf0",
+ "bg-color": "#161b22",
+ "comfy-menu-bg": "#13171d",
+ "comfy-input-bg": "#161b22",
+ "input-text": "#bcc2c8",
+ "descrip-text": "#999",
+ "drag-text": "#ccc",
+ "error-text": "#ff4444",
+ "border-color": "#30363d",
+ "tr-even-bg-color": "#161b22",
+ "tr-odd-bg-color": "#13171d",
+ "content-bg": "#30363d",
+ "content-fg": "#e5eaf0",
+ "content-hover-bg": "#161b22",
+ "content-hover-fg": "#e5eaf0"
+ }
+ }
+ }
+};
+const id$4 = "Comfy.ColorPalette";
+const idCustomColorPalettes = "Comfy.CustomColorPalettes";
+const defaultColorPaletteId = "dark";
+const els = {
+ select: null
+};
+const getCustomColorPalettes = /* @__PURE__ */ __name(() => {
+ return app.ui.settings.getSettingValue(idCustomColorPalettes, {});
+}, "getCustomColorPalettes");
+const setCustomColorPalettes = /* @__PURE__ */ __name((customColorPalettes) => {
+ return app.ui.settings.setSettingValue(
+ idCustomColorPalettes,
+ customColorPalettes
+ );
+}, "setCustomColorPalettes");
+const defaultColorPalette = colorPalettes[defaultColorPaletteId];
+const getColorPalette = /* @__PURE__ */ __name((colorPaletteId) => {
+ if (!colorPaletteId) {
+ colorPaletteId = app.ui.settings.getSettingValue(id$4, defaultColorPaletteId);
+ }
+ if (colorPaletteId.startsWith("custom_")) {
+ colorPaletteId = colorPaletteId.substr(7);
+ let customColorPalettes = getCustomColorPalettes();
+ if (customColorPalettes[colorPaletteId]) {
+ return customColorPalettes[colorPaletteId];
+ }
+ }
+ return colorPalettes[colorPaletteId];
+}, "getColorPalette");
+const setColorPalette = /* @__PURE__ */ __name((colorPaletteId) => {
+ app.ui.settings.setSettingValue(id$4, colorPaletteId);
+}, "setColorPalette");
+app.registerExtension({
+ name: id$4,
+ init() {
+ LGraphCanvas.prototype.updateBackground = function(image, clearBackgroundColor) {
+ this._bg_img = new Image();
+ this._bg_img.name = image;
+ this._bg_img.src = image;
+ this._bg_img.onload = () => {
+ this.draw(true, true);
+ };
+ this.background_image = image;
+ this.clear_background = true;
+ this.clear_background_color = clearBackgroundColor;
+ this._pattern = null;
+ };
+ },
+ addCustomNodeDefs(node_defs) {
+ const sortObjectKeys = /* @__PURE__ */ __name((unordered) => {
+ return Object.keys(unordered).sort().reduce((obj, key) => {
+ obj[key] = unordered[key];
+ return obj;
+ }, {});
+ }, "sortObjectKeys");
+ function getSlotTypes() {
+ var types = [];
+ const defs = node_defs;
+ for (const nodeId in defs) {
+ const nodeData = defs[nodeId];
+ var inputs = nodeData["input"]["required"];
+ if (nodeData["input"]["optional"] !== void 0) {
+ inputs = Object.assign(
+ {},
+ nodeData["input"]["required"],
+ nodeData["input"]["optional"]
+ );
+ }
+ for (const inputName in inputs) {
+ const inputData = inputs[inputName];
+ const type = inputData[0];
+ if (!Array.isArray(type)) {
+ types.push(type);
+ }
+ }
+ for (const o in nodeData["output"]) {
+ const output = nodeData["output"][o];
+ types.push(output);
+ }
+ }
+ return types;
+ }
+ __name(getSlotTypes, "getSlotTypes");
+ function completeColorPalette(colorPalette) {
+ var types = getSlotTypes();
+ for (const type of types) {
+ if (!colorPalette.colors.node_slot[type]) {
+ colorPalette.colors.node_slot[type] = "";
+ }
+ }
+ colorPalette.colors.node_slot = sortObjectKeys(
+ colorPalette.colors.node_slot
+ );
+ return colorPalette;
+ }
+ __name(completeColorPalette, "completeColorPalette");
+ const getColorPaletteTemplate = /* @__PURE__ */ __name(async () => {
+ let colorPalette = {
+ id: "my_color_palette_unique_id",
+ name: "My Color Palette",
+ colors: {
+ node_slot: {},
+ litegraph_base: {},
+ comfy_base: {}
+ }
+ };
+ const defaultColorPalette2 = colorPalettes[defaultColorPaletteId];
+ for (const key in defaultColorPalette2.colors.litegraph_base) {
+ if (!colorPalette.colors.litegraph_base[key]) {
+ colorPalette.colors.litegraph_base[key] = "";
+ }
+ }
+ for (const key in defaultColorPalette2.colors.comfy_base) {
+ if (!colorPalette.colors.comfy_base[key]) {
+ colorPalette.colors.comfy_base[key] = "";
+ }
+ }
+ return completeColorPalette(colorPalette);
+ }, "getColorPaletteTemplate");
+ const addCustomColorPalette = /* @__PURE__ */ __name(async (colorPalette) => {
+ if (typeof colorPalette !== "object") {
+ alert("Invalid color palette.");
+ return;
+ }
+ if (!colorPalette.id) {
+ alert("Color palette missing id.");
+ return;
+ }
+ if (!colorPalette.name) {
+ alert("Color palette missing name.");
+ return;
+ }
+ if (!colorPalette.colors) {
+ alert("Color palette missing colors.");
+ return;
+ }
+ if (colorPalette.colors.node_slot && typeof colorPalette.colors.node_slot !== "object") {
+ alert("Invalid color palette colors.node_slot.");
+ return;
+ }
+ const customColorPalettes = getCustomColorPalettes();
+ customColorPalettes[colorPalette.id] = colorPalette;
+ setCustomColorPalettes(customColorPalettes);
+ for (const option of els.select.childNodes) {
+ if (option.value === "custom_" + colorPalette.id) {
+ els.select.removeChild(option);
+ }
+ }
+ els.select.append(
+ $el("option", {
+ textContent: colorPalette.name + " (custom)",
+ value: "custom_" + colorPalette.id,
+ selected: true
+ })
+ );
+ setColorPalette("custom_" + colorPalette.id);
+ await loadColorPalette(colorPalette);
+ }, "addCustomColorPalette");
+ const deleteCustomColorPalette = /* @__PURE__ */ __name(async (colorPaletteId) => {
+ const customColorPalettes = getCustomColorPalettes();
+ delete customColorPalettes[colorPaletteId];
+ setCustomColorPalettes(customColorPalettes);
+ for (const opt of els.select.childNodes) {
+ const option = opt;
+ if (option.value === defaultColorPaletteId) {
+ option.selected = true;
+ }
+ if (option.value === "custom_" + colorPaletteId) {
+ els.select.removeChild(option);
+ }
+ }
+ setColorPalette(defaultColorPaletteId);
+ await loadColorPalette(getColorPalette());
+ }, "deleteCustomColorPalette");
+ const loadColorPalette = /* @__PURE__ */ __name(async (colorPalette) => {
+ colorPalette = await completeColorPalette(colorPalette);
+ if (colorPalette.colors) {
+ if (colorPalette.colors.node_slot) {
+ Object.assign(
+ // @ts-expect-error
+ app.canvas.default_connection_color_byType,
+ colorPalette.colors.node_slot
+ );
+ Object.assign(
+ LGraphCanvas.link_type_colors,
+ colorPalette.colors.node_slot
+ );
+ }
+ if (colorPalette.colors.litegraph_base) {
+ app.canvas.node_title_color = colorPalette.colors.litegraph_base.NODE_TITLE_COLOR;
+ app.canvas.default_link_color = colorPalette.colors.litegraph_base.LINK_COLOR;
+ for (const key in colorPalette.colors.litegraph_base) {
+ if (colorPalette.colors.litegraph_base.hasOwnProperty(key) && LiteGraph.hasOwnProperty(key)) {
+ LiteGraph[key] = colorPalette.colors.litegraph_base[key];
+ }
+ }
+ }
+ if (colorPalette.colors.comfy_base) {
+ const rootStyle = document.documentElement.style;
+ for (const key in colorPalette.colors.comfy_base) {
+ rootStyle.setProperty(
+ "--" + key,
+ colorPalette.colors.comfy_base[key]
+ );
+ }
+ }
+ app.canvas.draw(true, true);
+ }
+ }, "loadColorPalette");
+ const fileInput = $el("input", {
+ type: "file",
+ accept: ".json",
+ style: { display: "none" },
+ parent: document.body,
+ onchange: /* @__PURE__ */ __name(() => {
+ const file2 = fileInput.files[0];
+ if (file2.type === "application/json" || file2.name.endsWith(".json")) {
+ const reader = new FileReader();
+ reader.onload = async () => {
+ await addCustomColorPalette(JSON.parse(reader.result));
+ };
+ reader.readAsText(file2);
+ }
+ }, "onchange")
+ });
+ app.ui.settings.addSetting({
+ id: id$4,
+ category: ["Comfy", "ColorPalette"],
+ name: "Color Palette",
+ type: /* @__PURE__ */ __name((name, setter, value) => {
+ const options = [
+ ...Object.values(colorPalettes).map(
+ (c) => $el("option", {
+ textContent: c.name,
+ value: c.id,
+ selected: c.id === value
+ })
+ ),
+ ...Object.values(getCustomColorPalettes()).map(
+ (c) => $el("option", {
+ textContent: `${c.name} (custom)`,
+ value: `custom_${c.id}`,
+ selected: `custom_${c.id}` === value
+ })
+ )
+ ];
+ els.select = $el(
+ "select",
+ {
+ style: {
+ marginBottom: "0.15rem",
+ width: "100%"
+ },
+ onchange: /* @__PURE__ */ __name((e) => {
+ setter(e.target.value);
+ }, "onchange")
+ },
+ options
+ );
+ return $el("tr", [
+ $el("td", [
+ els.select,
+ $el(
+ "div",
+ {
+ style: {
+ display: "grid",
+ gap: "4px",
+ gridAutoFlow: "column"
+ }
+ },
+ [
+ $el("input", {
+ type: "button",
+ value: "Export",
+ onclick: /* @__PURE__ */ __name(async () => {
+ const colorPaletteId = app.ui.settings.getSettingValue(
+ id$4,
+ defaultColorPaletteId
+ );
+ const colorPalette = await completeColorPalette(
+ getColorPalette(colorPaletteId)
+ );
+ const json = JSON.stringify(colorPalette, null, 2);
+ const blob = new Blob([json], { type: "application/json" });
+ const url = URL.createObjectURL(blob);
+ const a = $el("a", {
+ href: url,
+ download: colorPaletteId + ".json",
+ style: { display: "none" },
+ parent: document.body
+ });
+ a.click();
+ setTimeout(function() {
+ a.remove();
+ window.URL.revokeObjectURL(url);
+ }, 0);
+ }, "onclick")
+ }),
+ $el("input", {
+ type: "button",
+ value: "Import",
+ onclick: /* @__PURE__ */ __name(() => {
+ fileInput.click();
+ }, "onclick")
+ }),
+ $el("input", {
+ type: "button",
+ value: "Template",
+ onclick: /* @__PURE__ */ __name(async () => {
+ const colorPalette = await getColorPaletteTemplate();
+ const json = JSON.stringify(colorPalette, null, 2);
+ const blob = new Blob([json], { type: "application/json" });
+ const url = URL.createObjectURL(blob);
+ const a = $el("a", {
+ href: url,
+ download: "color_palette.json",
+ style: { display: "none" },
+ parent: document.body
+ });
+ a.click();
+ setTimeout(function() {
+ a.remove();
+ window.URL.revokeObjectURL(url);
+ }, 0);
+ }, "onclick")
+ }),
+ $el("input", {
+ type: "button",
+ value: "Delete",
+ onclick: /* @__PURE__ */ __name(async () => {
+ let colorPaletteId = app.ui.settings.getSettingValue(
+ id$4,
+ defaultColorPaletteId
+ );
+ if (colorPalettes[colorPaletteId]) {
+ alert("You cannot delete a built-in color palette.");
+ return;
+ }
+ if (colorPaletteId.startsWith("custom_")) {
+ colorPaletteId = colorPaletteId.substr(7);
+ }
+ await deleteCustomColorPalette(colorPaletteId);
+ }, "onclick")
+ })
+ ]
+ )
+ ])
+ ]);
+ }, "type"),
+ defaultValue: defaultColorPaletteId,
+ async onChange(value) {
+ if (!value) {
+ return;
+ }
+ let palette = colorPalettes[value];
+ if (palette) {
+ await loadColorPalette(palette);
+ } else if (value.startsWith("custom_")) {
+ value = value.substr(7);
+ let customColorPalettes = getCustomColorPalettes();
+ if (customColorPalettes[value]) {
+ palette = customColorPalettes[value];
+ await loadColorPalette(customColorPalettes[value]);
+ }
+ }
+ let { BACKGROUND_IMAGE, CLEAR_BACKGROUND_COLOR } = palette.colors.litegraph_base;
+ if (BACKGROUND_IMAGE === void 0 || CLEAR_BACKGROUND_COLOR === void 0) {
+ const base = colorPalettes["dark"].colors.litegraph_base;
+ BACKGROUND_IMAGE = base.BACKGROUND_IMAGE;
+ CLEAR_BACKGROUND_COLOR = base.CLEAR_BACKGROUND_COLOR;
+ }
+ app.canvas.updateBackground(BACKGROUND_IMAGE, CLEAR_BACKGROUND_COLOR);
+ }
+ });
+ }
+});
+window.comfyAPI = window.comfyAPI || {};
+window.comfyAPI.colorPalette = window.comfyAPI.colorPalette || {};
+window.comfyAPI.colorPalette.defaultColorPalette = defaultColorPalette;
+window.comfyAPI.colorPalette.getColorPalette = getColorPalette;
+const ext$2 = {
+ name: "Comfy.ContextMenuFilter",
+ init() {
+ const ctxMenu = LiteGraph.ContextMenu;
+ LiteGraph.ContextMenu = function(values, options) {
+ const ctx = new ctxMenu(values, options);
+ if (options?.className === "dark" && values?.length > 4) {
+ const filter = document.createElement("input");
+ filter.classList.add("comfy-context-menu-filter");
+ filter.placeholder = "Filter list";
+ ctx.root.prepend(filter);
+ const items = Array.from(
+ ctx.root.querySelectorAll(".litemenu-entry")
+ );
+ let displayedItems = [...items];
+ let itemCount = displayedItems.length;
+ requestAnimationFrame(() => {
+ const currentNode = LGraphCanvas.active_canvas.current_node;
+ const clickedComboValue = currentNode.widgets?.filter(
+ (w) => w.type === "combo" && w.options.values.length === values.length
+ ).find(
+ (w) => w.options.values.every((v, i) => v === values[i])
+ )?.value;
+ let selectedIndex = clickedComboValue ? values.findIndex((v) => v === clickedComboValue) : 0;
+ if (selectedIndex < 0) {
+ selectedIndex = 0;
+ }
+ let selectedItem = displayedItems[selectedIndex];
+ updateSelected();
+ function updateSelected() {
+ selectedItem?.style.setProperty("background-color", "");
+ selectedItem?.style.setProperty("color", "");
+ selectedItem = displayedItems[selectedIndex];
+ selectedItem?.style.setProperty(
+ "background-color",
+ "#ccc",
+ "important"
+ );
+ selectedItem?.style.setProperty("color", "#000", "important");
+ }
+ __name(updateSelected, "updateSelected");
+ const positionList = /* @__PURE__ */ __name(() => {
+ const rect = ctx.root.getBoundingClientRect();
+ if (rect.top < 0) {
+ const scale = 1 - ctx.root.getBoundingClientRect().height / ctx.root.clientHeight;
+ const shift = ctx.root.clientHeight * scale / 2;
+ ctx.root.style.top = -shift + "px";
+ }
+ }, "positionList");
+ filter.addEventListener("keydown", (event) => {
+ switch (event.key) {
+ case "ArrowUp":
+ event.preventDefault();
+ if (selectedIndex === 0) {
+ selectedIndex = itemCount - 1;
+ } else {
+ selectedIndex--;
+ }
+ updateSelected();
+ break;
+ case "ArrowRight":
+ event.preventDefault();
+ selectedIndex = itemCount - 1;
+ updateSelected();
+ break;
+ case "ArrowDown":
+ event.preventDefault();
+ if (selectedIndex === itemCount - 1) {
+ selectedIndex = 0;
+ } else {
+ selectedIndex++;
+ }
+ updateSelected();
+ break;
+ case "ArrowLeft":
+ event.preventDefault();
+ selectedIndex = 0;
+ updateSelected();
+ break;
+ case "Enter":
+ selectedItem?.click();
+ break;
+ case "Escape":
+ ctx.close();
+ break;
+ }
+ });
+ filter.addEventListener("input", () => {
+ const term = filter.value.toLocaleLowerCase();
+ displayedItems = items.filter((item) => {
+ const isVisible = !term || item.textContent.toLocaleLowerCase().includes(term);
+ item.style.display = isVisible ? "block" : "none";
+ return isVisible;
+ });
+ selectedIndex = 0;
+ if (displayedItems.includes(selectedItem)) {
+ selectedIndex = displayedItems.findIndex(
+ (d) => d === selectedItem
+ );
+ }
+ itemCount = displayedItems.length;
+ updateSelected();
+ if (options.event) {
+ let top = options.event.clientY - 10;
+ const bodyRect = document.body.getBoundingClientRect();
+ const rootRect = ctx.root.getBoundingClientRect();
+ if (bodyRect.height && top > bodyRect.height - rootRect.height - 10) {
+ top = Math.max(0, bodyRect.height - rootRect.height - 10);
+ }
+ ctx.root.style.top = top + "px";
+ positionList();
+ }
+ });
+ requestAnimationFrame(() => {
+ filter.focus();
+ positionList();
+ });
+ });
+ }
+ return ctx;
+ };
+ LiteGraph.ContextMenu.prototype = ctxMenu.prototype;
+ }
+};
+app.registerExtension(ext$2);
+function stripComments(str) {
+ return str.replace(/\/\*[\s\S]*?\*\/|\/\/.*/g, "");
+}
+__name(stripComments, "stripComments");
+app.registerExtension({
+ name: "Comfy.DynamicPrompts",
+ nodeCreated(node) {
+ if (node.widgets) {
+ const widgets = node.widgets.filter((n) => n.dynamicPrompts);
+ for (const widget of widgets) {
+ widget.serializeValue = (workflowNode, widgetIndex) => {
+ let prompt2 = stripComments(widget.value);
+ while (prompt2.replace("\\{", "").includes("{") && prompt2.replace("\\}", "").includes("}")) {
+ const startIndex = prompt2.replace("\\{", "00").indexOf("{");
+ const endIndex = prompt2.replace("\\}", "00").indexOf("}");
+ const optionsString = prompt2.substring(startIndex + 1, endIndex);
+ const options = optionsString.split("|");
+ const randomIndex = Math.floor(Math.random() * options.length);
+ const randomOption = options[randomIndex];
+ prompt2 = prompt2.substring(0, startIndex) + randomOption + prompt2.substring(endIndex + 1);
+ }
+ if (workflowNode?.widgets_values)
+ workflowNode.widgets_values[widgetIndex] = prompt2;
+ return prompt2;
+ };
+ }
+ }
+ }
+});
+app.registerExtension({
+ name: "Comfy.EditAttention",
+ init() {
+ const editAttentionDelta = app.ui.settings.addSetting({
+ id: "Comfy.EditAttention.Delta",
+ name: "Ctrl+up/down precision",
+ type: "slider",
+ attrs: {
+ min: 0.01,
+ max: 0.5,
+ step: 0.01
+ },
+ defaultValue: 0.05
+ });
+ function incrementWeight(weight, delta) {
+ const floatWeight = parseFloat(weight);
+ if (isNaN(floatWeight)) return weight;
+ const newWeight = floatWeight + delta;
+ return String(Number(newWeight.toFixed(10)));
+ }
+ __name(incrementWeight, "incrementWeight");
+ function findNearestEnclosure(text, cursorPos) {
+ let start = cursorPos, end = cursorPos;
+ let openCount = 0, closeCount = 0;
+ while (start >= 0) {
+ start--;
+ if (text[start] === "(" && openCount === closeCount) break;
+ if (text[start] === "(") openCount++;
+ if (text[start] === ")") closeCount++;
+ }
+ if (start < 0) return false;
+ openCount = 0;
+ closeCount = 0;
+ while (end < text.length) {
+ if (text[end] === ")" && openCount === closeCount) break;
+ if (text[end] === "(") openCount++;
+ if (text[end] === ")") closeCount++;
+ end++;
+ }
+ if (end === text.length) return false;
+ return { start: start + 1, end };
+ }
+ __name(findNearestEnclosure, "findNearestEnclosure");
+ function addWeightToParentheses(text) {
+ const parenRegex = /^\((.*)\)$/;
+ const parenMatch = text.match(parenRegex);
+ const floatRegex = /:([+-]?(\d*\.)?\d+([eE][+-]?\d+)?)/;
+ const floatMatch = text.match(floatRegex);
+ if (parenMatch && !floatMatch) {
+ return `(${parenMatch[1]}:1.0)`;
+ } else {
+ return text;
+ }
+ }
+ __name(addWeightToParentheses, "addWeightToParentheses");
+ function editAttention(event) {
+ const inputField = event.composedPath()[0];
+ const delta = parseFloat(editAttentionDelta.value);
+ if (inputField.tagName !== "TEXTAREA") return;
+ if (!(event.key === "ArrowUp" || event.key === "ArrowDown")) return;
+ if (!event.ctrlKey && !event.metaKey) return;
+ event.preventDefault();
+ let start = inputField.selectionStart;
+ let end = inputField.selectionEnd;
+ let selectedText = inputField.value.substring(start, end);
+ if (!selectedText) {
+ const nearestEnclosure = findNearestEnclosure(inputField.value, start);
+ if (nearestEnclosure) {
+ start = nearestEnclosure.start;
+ end = nearestEnclosure.end;
+ selectedText = inputField.value.substring(start, end);
+ } else {
+ const delimiters = " .,\\/!?%^*;:{}=-_`~()\r\n ";
+ while (!delimiters.includes(inputField.value[start - 1]) && start > 0) {
+ start--;
+ }
+ while (!delimiters.includes(inputField.value[end]) && end < inputField.value.length) {
+ end++;
+ }
+ selectedText = inputField.value.substring(start, end);
+ if (!selectedText) return;
+ }
+ }
+ if (selectedText[selectedText.length - 1] === " ") {
+ selectedText = selectedText.substring(0, selectedText.length - 1);
+ end -= 1;
+ }
+ if (inputField.value[start - 1] === "(" && inputField.value[end] === ")") {
+ start -= 1;
+ end += 1;
+ selectedText = inputField.value.substring(start, end);
+ }
+ if (selectedText[0] !== "(" || selectedText[selectedText.length - 1] !== ")") {
+ selectedText = `(${selectedText})`;
+ }
+ selectedText = addWeightToParentheses(selectedText);
+ const weightDelta = event.key === "ArrowUp" ? delta : -delta;
+ const updatedText = selectedText.replace(
+ /\((.*):([+-]?\d+(?:\.\d+)?)\)/,
+ (match, text, weight) => {
+ weight = incrementWeight(weight, weightDelta);
+ if (weight == 1) {
+ return text;
+ } else {
+ return `(${text}:${weight})`;
+ }
+ }
+ );
+ inputField.setSelectionRange(start, end);
+ document.execCommand("insertText", false, updatedText);
+ inputField.setSelectionRange(start, start + updatedText.length);
+ }
+ __name(editAttention, "editAttention");
+ window.addEventListener("keydown", editAttention);
+ }
+});
+const CONVERTED_TYPE = "converted-widget";
+const VALID_TYPES = ["STRING", "combo", "number", "toggle", "BOOLEAN"];
+const CONFIG = Symbol();
+const GET_CONFIG = Symbol();
+const TARGET = Symbol();
+const replacePropertyName = "Run widget replace on values";
+class PrimitiveNode extends LGraphNode {
+ static {
+ __name(this, "PrimitiveNode");
+ }
+ controlValues;
+ lastType;
+ static category;
+ constructor(title) {
+ super(title);
+ this.addOutput("connect to widget input", "*");
+ this.serialize_widgets = true;
+ this.isVirtualNode = true;
+ if (!this.properties || !(replacePropertyName in this.properties)) {
+ this.addProperty(replacePropertyName, false, "boolean");
+ }
+ }
+ applyToGraph(extraLinks = []) {
+ if (!this.outputs[0].links?.length) return;
+ function get_links(node) {
+ let links2 = [];
+ for (const l of node.outputs[0].links) {
+ const linkInfo = app.graph.links[l];
+ const n = node.graph.getNodeById(linkInfo.target_id);
+ if (n.type == "Reroute") {
+ links2 = links2.concat(get_links(n));
+ } else {
+ links2.push(l);
+ }
+ }
+ return links2;
+ }
+ __name(get_links, "get_links");
+ let links = [
+ ...get_links(this).map((l) => app.graph.links[l]),
+ ...extraLinks
+ ];
+ let v = this.widgets?.[0].value;
+ if (v && this.properties[replacePropertyName]) {
+ v = applyTextReplacements(app, v);
+ }
+ for (const linkInfo of links) {
+ const node = this.graph.getNodeById(linkInfo.target_id);
+ const input = node.inputs[linkInfo.target_slot];
+ let widget;
+ if (input.widget[TARGET]) {
+ widget = input.widget[TARGET];
+ } else {
+ const widgetName = input.widget.name;
+ if (widgetName) {
+ widget = node.widgets.find((w) => w.name === widgetName);
+ }
+ }
+ if (widget) {
+ widget.value = v;
+ if (widget.callback) {
+ widget.callback(
+ widget.value,
+ app.canvas,
+ node,
+ app.canvas.graph_mouse,
+ {}
+ );
+ }
+ }
+ }
+ }
+ refreshComboInNode() {
+ const widget = this.widgets?.[0];
+ if (widget?.type === "combo") {
+ widget.options.values = this.outputs[0].widget[GET_CONFIG]()[0];
+ if (!widget.options.values.includes(widget.value)) {
+ widget.value = widget.options.values[0];
+ widget.callback(widget.value);
+ }
+ }
+ }
+ onAfterGraphConfigured() {
+ if (this.outputs[0].links?.length && !this.widgets?.length) {
+ if (!this.#onFirstConnection()) return;
+ if (this.widgets) {
+ for (let i = 0; i < this.widgets_values.length; i++) {
+ const w = this.widgets[i];
+ if (w) {
+ w.value = this.widgets_values[i];
+ }
+ }
+ }
+ this.#mergeWidgetConfig();
+ }
+ }
+ onConnectionsChange(_2, index, connected) {
+ if (app.configuringGraph) {
+ return;
+ }
+ const links = this.outputs[0].links;
+ if (connected) {
+ if (links?.length && !this.widgets?.length) {
+ this.#onFirstConnection();
+ }
+ } else {
+ this.#mergeWidgetConfig();
+ if (!links?.length) {
+ this.onLastDisconnect();
+ }
+ }
+ }
+ onConnectOutput(slot, type, input, target_node, target_slot) {
+ if (!input.widget) {
+ if (!(input.type in ComfyWidgets)) return false;
+ }
+ if (this.outputs[slot].links?.length) {
+ const valid = this.#isValidConnection(input);
+ if (valid) {
+ this.applyToGraph([{ target_id: target_node.id, target_slot }]);
+ }
+ return valid;
+ }
+ }
+ #onFirstConnection(recreating) {
+ if (!this.outputs[0].links) {
+ this.onLastDisconnect();
+ return;
+ }
+ const linkId = this.outputs[0].links[0];
+ const link = this.graph.links[linkId];
+ if (!link) return;
+ const theirNode = this.graph.getNodeById(link.target_id);
+ if (!theirNode || !theirNode.inputs) return;
+ const input = theirNode.inputs[link.target_slot];
+ if (!input) return;
+ let widget;
+ if (!input.widget) {
+ if (!(input.type in ComfyWidgets)) return;
+ widget = { name: input.name, [GET_CONFIG]: () => [input.type, {}] };
+ } else {
+ widget = input.widget;
+ }
+ const config = widget[GET_CONFIG]?.();
+ if (!config) return;
+ const { type } = getWidgetType(config);
+ this.outputs[0].type = type;
+ this.outputs[0].name = type;
+ this.outputs[0].widget = widget;
+ this.#createWidget(
+ widget[CONFIG] ?? config,
+ theirNode,
+ widget.name,
+ recreating,
+ widget[TARGET]
+ );
+ }
+ #createWidget(inputData, node, widgetName, recreating, targetWidget) {
+ let type = inputData[0];
+ if (type instanceof Array) {
+ type = "COMBO";
+ }
+ const size = this.size;
+ let widget;
+ if (type in ComfyWidgets) {
+ widget = (ComfyWidgets[type](this, "value", inputData, app) || {}).widget;
+ } else {
+ widget = this.addWidget(type, "value", null, () => {
+ }, {});
+ }
+ if (targetWidget) {
+ widget.value = targetWidget.value;
+ } else if (node?.widgets && widget) {
+ const theirWidget = node.widgets.find((w) => w.name === widgetName);
+ if (theirWidget) {
+ widget.value = theirWidget.value;
+ }
+ }
+ if (!inputData?.[1]?.control_after_generate && (widget.type === "number" || widget.type === "combo")) {
+ let control_value = this.widgets_values?.[1];
+ if (!control_value) {
+ control_value = "fixed";
+ }
+ addValueControlWidgets(
+ this,
+ widget,
+ control_value,
+ void 0,
+ inputData
+ );
+ let filter = this.widgets_values?.[2];
+ if (filter && this.widgets.length === 3) {
+ this.widgets[2].value = filter;
+ }
+ }
+ const controlValues = this.controlValues;
+ if (this.lastType === this.widgets[0].type && controlValues?.length === this.widgets.length - 1) {
+ for (let i = 0; i < controlValues.length; i++) {
+ this.widgets[i + 1].value = controlValues[i];
+ }
+ }
+ const callback = widget.callback;
+ const self = this;
+ widget.callback = function() {
+ const r = callback ? callback.apply(this, arguments) : void 0;
+ self.applyToGraph();
+ return r;
+ };
+ this.size = [
+ Math.max(this.size[0], size[0]),
+ Math.max(this.size[1], size[1])
+ ];
+ if (!recreating) {
+ const sz = this.computeSize();
+ if (this.size[0] < sz[0]) {
+ this.size[0] = sz[0];
+ }
+ if (this.size[1] < sz[1]) {
+ this.size[1] = sz[1];
+ }
+ requestAnimationFrame(() => {
+ if (this.onResize) {
+ this.onResize(this.size);
+ }
+ });
+ }
+ }
+ recreateWidget() {
+ const values = this.widgets?.map((w) => w.value);
+ this.#removeWidgets();
+ this.#onFirstConnection(true);
+ if (values?.length) {
+ for (let i = 0; i < this.widgets?.length; i++)
+ this.widgets[i].value = values[i];
+ }
+ return this.widgets?.[0];
+ }
+ #mergeWidgetConfig() {
+ const output = this.outputs[0];
+ const links = output.links;
+ const hasConfig = !!output.widget[CONFIG];
+ if (hasConfig) {
+ delete output.widget[CONFIG];
+ }
+ if (links?.length < 2 && hasConfig) {
+ if (links.length) {
+ this.recreateWidget();
+ }
+ return;
+ }
+ const config1 = output.widget[GET_CONFIG]();
+ const isNumber = config1[0] === "INT" || config1[0] === "FLOAT";
+ if (!isNumber) return;
+ for (const linkId of links) {
+ const link = app.graph.links[linkId];
+ if (!link) continue;
+ const theirNode = app.graph.getNodeById(link.target_id);
+ const theirInput = theirNode.inputs[link.target_slot];
+ this.#isValidConnection(theirInput, hasConfig);
+ }
+ }
+ #isValidConnection(input, forceUpdate) {
+ const output = this.outputs[0];
+ const config2 = input.widget[GET_CONFIG]();
+ return !!mergeIfValid.call(
+ this,
+ output,
+ config2,
+ forceUpdate,
+ this.recreateWidget
+ );
+ }
+ #removeWidgets() {
+ if (this.widgets) {
+ for (const w of this.widgets) {
+ if (w.onRemove) {
+ w.onRemove();
+ }
+ }
+ this.controlValues = [];
+ this.lastType = this.widgets[0]?.type;
+ for (let i = 1; i < this.widgets.length; i++) {
+ this.controlValues.push(this.widgets[i].value);
+ }
+ setTimeout(() => {
+ delete this.lastType;
+ delete this.controlValues;
+ }, 15);
+ this.widgets.length = 0;
+ }
+ }
+ onLastDisconnect() {
+ this.outputs[0].type = "*";
+ this.outputs[0].name = "connect to widget input";
+ delete this.outputs[0].widget;
+ this.#removeWidgets();
+ }
+}
+function getWidgetConfig(slot) {
+ return slot.widget[CONFIG] ?? slot.widget[GET_CONFIG]();
+}
+__name(getWidgetConfig, "getWidgetConfig");
+function getConfig(widgetName) {
+ const { nodeData } = this.constructor;
+ return nodeData?.input?.required?.[widgetName] ?? nodeData?.input?.optional?.[widgetName];
+}
+__name(getConfig, "getConfig");
+function isConvertibleWidget(widget, config) {
+ return (VALID_TYPES.includes(widget.type) || VALID_TYPES.includes(config[0])) && !widget.options?.forceInput;
+}
+__name(isConvertibleWidget, "isConvertibleWidget");
+function hideWidget(node, widget, suffix = "") {
+ if (widget.type?.startsWith(CONVERTED_TYPE)) return;
+ widget.origType = widget.type;
+ widget.origComputeSize = widget.computeSize;
+ widget.origSerializeValue = widget.serializeValue;
+ widget.computeSize = () => [0, -4];
+ widget.type = CONVERTED_TYPE + suffix;
+ widget.serializeValue = () => {
+ if (!node.inputs) {
+ return void 0;
+ }
+ let node_input = node.inputs.find((i) => i.widget?.name === widget.name);
+ if (!node_input || !node_input.link) {
+ return void 0;
+ }
+ return widget.origSerializeValue ? widget.origSerializeValue() : widget.value;
+ };
+ if (widget.linkedWidgets) {
+ for (const w of widget.linkedWidgets) {
+ hideWidget(node, w, ":" + widget.name);
+ }
+ }
+}
+__name(hideWidget, "hideWidget");
+function showWidget(widget) {
+ widget.type = widget.origType;
+ widget.computeSize = widget.origComputeSize;
+ widget.serializeValue = widget.origSerializeValue;
+ delete widget.origType;
+ delete widget.origComputeSize;
+ delete widget.origSerializeValue;
+ if (widget.linkedWidgets) {
+ for (const w of widget.linkedWidgets) {
+ showWidget(w);
+ }
+ }
+}
+__name(showWidget, "showWidget");
+function convertToInput(node, widget, config) {
+ hideWidget(node, widget);
+ const { type } = getWidgetType(config);
+ const sz = node.size;
+ node.addInput(widget.name, type, {
+ widget: { name: widget.name, [GET_CONFIG]: () => config }
+ });
+ for (const widget2 of node.widgets) {
+ widget2.last_y += LiteGraph.NODE_SLOT_HEIGHT;
+ }
+ node.setSize([Math.max(sz[0], node.size[0]), Math.max(sz[1], node.size[1])]);
+}
+__name(convertToInput, "convertToInput");
+function convertToWidget(node, widget) {
+ showWidget(widget);
+ const sz = node.size;
+ node.removeInput(node.inputs.findIndex((i) => i.widget?.name === widget.name));
+ for (const widget2 of node.widgets) {
+ widget2.last_y -= LiteGraph.NODE_SLOT_HEIGHT;
+ }
+ node.setSize([Math.max(sz[0], node.size[0]), Math.max(sz[1], node.size[1])]);
+}
+__name(convertToWidget, "convertToWidget");
+function getWidgetType(config) {
+ let type = config[0];
+ if (type instanceof Array) {
+ type = "COMBO";
+ }
+ return { type };
+}
+__name(getWidgetType, "getWidgetType");
+function isValidCombo(combo, obj) {
+ if (!(obj instanceof Array)) {
+ console.log(`connection rejected: tried to connect combo to ${obj}`);
+ return false;
+ }
+ if (combo.length !== obj.length) {
+ console.log(`connection rejected: combo lists dont match`);
+ return false;
+ }
+ if (combo.find((v, i) => obj[i] !== v)) {
+ console.log(`connection rejected: combo lists dont match`);
+ return false;
+ }
+ return true;
+}
+__name(isValidCombo, "isValidCombo");
+function isPrimitiveNode(node) {
+ return node.type === "PrimitiveNode";
+}
+__name(isPrimitiveNode, "isPrimitiveNode");
+function setWidgetConfig(slot, config, target) {
+ if (!slot.widget) return;
+ if (config) {
+ slot.widget[GET_CONFIG] = () => config;
+ slot.widget[TARGET] = target;
+ } else {
+ delete slot.widget;
+ }
+ if (slot.link) {
+ const link = app.graph.links[slot.link];
+ if (link) {
+ const originNode = app.graph.getNodeById(link.origin_id);
+ if (isPrimitiveNode(originNode)) {
+ if (config) {
+ originNode.recreateWidget();
+ } else if (!app.configuringGraph) {
+ originNode.disconnectOutput(0);
+ originNode.onLastDisconnect();
+ }
+ }
+ }
+ }
+}
+__name(setWidgetConfig, "setWidgetConfig");
+function mergeIfValid(output, config2, forceUpdate, recreateWidget, config1) {
+ if (!config1) {
+ config1 = output.widget[CONFIG] ?? output.widget[GET_CONFIG]();
+ }
+ if (config1[0] instanceof Array) {
+ if (!isValidCombo(config1[0], config2[0])) return;
+ } else if (config1[0] !== config2[0]) {
+ console.log(`connection rejected: types dont match`, config1[0], config2[0]);
+ return;
+ }
+ const keys = /* @__PURE__ */ new Set([
+ ...Object.keys(config1[1] ?? {}),
+ ...Object.keys(config2[1] ?? {})
+ ]);
+ let customConfig;
+ const getCustomConfig = /* @__PURE__ */ __name(() => {
+ if (!customConfig) {
+ if (typeof structuredClone === "undefined") {
+ customConfig = JSON.parse(JSON.stringify(config1[1] ?? {}));
+ } else {
+ customConfig = structuredClone(config1[1] ?? {});
+ }
+ }
+ return customConfig;
+ }, "getCustomConfig");
+ const isNumber = config1[0] === "INT" || config1[0] === "FLOAT";
+ for (const k of keys.values()) {
+ if (k !== "default" && k !== "forceInput" && k !== "defaultInput" && k !== "control_after_generate" && k !== "multiline" && k !== "tooltip") {
+ let v1 = config1[1][k];
+ let v2 = config2[1]?.[k];
+ if (v1 === v2 || !v1 && !v2) continue;
+ if (isNumber) {
+ if (k === "min") {
+ const theirMax = config2[1]?.["max"];
+ if (theirMax != null && v1 > theirMax) {
+ console.log("connection rejected: min > max", v1, theirMax);
+ return;
+ }
+ getCustomConfig()[k] = v1 == null ? v2 : v2 == null ? v1 : Math.max(v1, v2);
+ continue;
+ } else if (k === "max") {
+ const theirMin = config2[1]?.["min"];
+ if (theirMin != null && v1 < theirMin) {
+ console.log("connection rejected: max < min", v1, theirMin);
+ return;
+ }
+ getCustomConfig()[k] = v1 == null ? v2 : v2 == null ? v1 : Math.min(v1, v2);
+ continue;
+ } else if (k === "step") {
+ let step;
+ if (v1 == null) {
+ step = v2;
+ } else if (v2 == null) {
+ step = v1;
+ } else {
+ if (v1 < v2) {
+ const a = v2;
+ v2 = v1;
+ v1 = a;
+ }
+ if (v1 % v2) {
+ console.log(
+ "connection rejected: steps not divisible",
+ "current:",
+ v1,
+ "new:",
+ v2
+ );
+ return;
+ }
+ step = v1;
+ }
+ getCustomConfig()[k] = step;
+ continue;
+ }
+ }
+ console.log(`connection rejected: config ${k} values dont match`, v1, v2);
+ return;
+ }
+ }
+ if (customConfig || forceUpdate) {
+ if (customConfig) {
+ output.widget[CONFIG] = [config1[0], customConfig];
+ }
+ const widget = recreateWidget?.call(this);
+ if (widget) {
+ const min = widget.options.min;
+ const max = widget.options.max;
+ if (min != null && widget.value < min) widget.value = min;
+ if (max != null && widget.value > max) widget.value = max;
+ widget.callback(widget.value);
+ }
+ }
+ return { customConfig };
+}
+__name(mergeIfValid, "mergeIfValid");
+let useConversionSubmenusSetting;
+app.registerExtension({
+ name: "Comfy.WidgetInputs",
+ init() {
+ useConversionSubmenusSetting = app.ui.settings.addSetting({
+ id: "Comfy.NodeInputConversionSubmenus",
+ name: "In the node context menu, place the entries that convert between input/widget in sub-menus.",
+ type: "boolean",
+ defaultValue: true
+ });
+ },
+ async beforeRegisterNodeDef(nodeType, nodeData, app2) {
+ const origGetExtraMenuOptions = nodeType.prototype.getExtraMenuOptions;
+ nodeType.prototype.convertWidgetToInput = function(widget) {
+ const config = getConfig.call(this, widget.name) ?? [
+ widget.type,
+ widget.options || {}
+ ];
+ if (!isConvertibleWidget(widget, config)) return false;
+ convertToInput(this, widget, config);
+ return true;
+ };
+ nodeType.prototype.getExtraMenuOptions = function(_2, options) {
+ const r = origGetExtraMenuOptions ? origGetExtraMenuOptions.apply(this, arguments) : void 0;
+ if (this.widgets) {
+ let toInput = [];
+ let toWidget = [];
+ for (const w of this.widgets) {
+ if (w.options?.forceInput) {
+ continue;
+ }
+ if (w.type === CONVERTED_TYPE) {
+ toWidget.push({
+ content: `Convert ${w.name} to widget`,
+ callback: /* @__PURE__ */ __name(() => convertToWidget(this, w), "callback")
+ });
+ } else {
+ const config = getConfig.call(this, w.name) ?? [
+ w.type,
+ w.options || {}
+ ];
+ if (isConvertibleWidget(w, config)) {
+ toInput.push({
+ content: `Convert ${w.name} to input`,
+ callback: /* @__PURE__ */ __name(() => convertToInput(this, w, config), "callback")
+ });
+ }
+ }
+ }
+ if (toInput.length) {
+ if (useConversionSubmenusSetting.value) {
+ options.push({
+ content: "Convert Widget to Input",
+ submenu: {
+ options: toInput
+ }
+ });
+ } else {
+ options.push(...toInput, null);
+ }
+ }
+ if (toWidget.length) {
+ if (useConversionSubmenusSetting.value) {
+ options.push({
+ content: "Convert Input to Widget",
+ submenu: {
+ options: toWidget
+ }
+ });
+ } else {
+ options.push(...toWidget, null);
+ }
+ }
+ }
+ return r;
+ };
+ nodeType.prototype.onGraphConfigured = function() {
+ if (!this.inputs) return;
+ this.widgets ??= [];
+ for (const input of this.inputs) {
+ if (input.widget) {
+ if (!input.widget[GET_CONFIG]) {
+ input.widget[GET_CONFIG] = () => getConfig.call(this, input.widget.name);
+ }
+ if (input.widget.config) {
+ if (input.widget.config[0] instanceof Array) {
+ input.type = "COMBO";
+ const link = app2.graph.links[input.link];
+ if (link) {
+ link.type = input.type;
+ }
+ }
+ delete input.widget.config;
+ }
+ const w = this.widgets.find((w2) => w2.name === input.widget.name);
+ if (w) {
+ hideWidget(this, w);
+ } else {
+ convertToWidget(this, input);
+ }
+ }
+ }
+ };
+ const origOnNodeCreated = nodeType.prototype.onNodeCreated;
+ nodeType.prototype.onNodeCreated = function() {
+ const r = origOnNodeCreated ? origOnNodeCreated.apply(this) : void 0;
+ if (!app2.configuringGraph && this.widgets) {
+ for (const w of this.widgets) {
+ if (w?.options?.forceInput || w?.options?.defaultInput) {
+ const config = getConfig.call(this, w.name) ?? [
+ w.type,
+ w.options || {}
+ ];
+ convertToInput(this, w, config);
+ }
+ }
+ }
+ return r;
+ };
+ const origOnConfigure = nodeType.prototype.onConfigure;
+ nodeType.prototype.onConfigure = function() {
+ const r = origOnConfigure ? origOnConfigure.apply(this, arguments) : void 0;
+ if (!app2.configuringGraph && this.inputs) {
+ for (const input of this.inputs) {
+ if (input.widget && !input.widget[GET_CONFIG]) {
+ input.widget[GET_CONFIG] = () => getConfig.call(this, input.widget.name);
+ const w = this.widgets.find((w2) => w2.name === input.widget.name);
+ if (w) {
+ hideWidget(this, w);
+ }
+ }
+ }
+ }
+ return r;
+ };
+ function isNodeAtPos(pos) {
+ for (const n of app2.graph.nodes) {
+ if (n.pos[0] === pos[0] && n.pos[1] === pos[1]) {
+ return true;
+ }
+ }
+ return false;
+ }
+ __name(isNodeAtPos, "isNodeAtPos");
+ const origOnInputDblClick = nodeType.prototype.onInputDblClick;
+ const ignoreDblClick = Symbol();
+ nodeType.prototype.onInputDblClick = function(slot) {
+ const r = origOnInputDblClick ? origOnInputDblClick.apply(this, arguments) : void 0;
+ const input = this.inputs[slot];
+ if (!input.widget || !input[ignoreDblClick]) {
+ if (!(input.type in ComfyWidgets) && !(input.widget[GET_CONFIG]?.()?.[0] instanceof Array)) {
+ return r;
+ }
+ }
+ const node = LiteGraph.createNode("PrimitiveNode");
+ app2.graph.add(node);
+ const pos = [
+ this.pos[0] - node.size[0] - 30,
+ this.pos[1]
+ ];
+ while (isNodeAtPos(pos)) {
+ pos[1] += LiteGraph.NODE_TITLE_HEIGHT;
+ }
+ node.pos = pos;
+ node.connect(0, this, slot);
+ node.title = input.name;
+ input[ignoreDblClick] = true;
+ setTimeout(() => {
+ delete input[ignoreDblClick];
+ }, 300);
+ return r;
+ };
+ const onConnectInput = nodeType.prototype.onConnectInput;
+ nodeType.prototype.onConnectInput = function(targetSlot, type, output, originNode, originSlot) {
+ const v = onConnectInput?.(this, arguments);
+ if (type !== "COMBO") return v;
+ if (originNode.outputs[originSlot].widget) return v;
+ const targetCombo = this.inputs[targetSlot].widget?.[GET_CONFIG]?.()?.[0];
+ if (!targetCombo || !(targetCombo instanceof Array)) return v;
+ const originConfig = originNode.constructor?.nodeData?.output?.[originSlot];
+ if (!originConfig || !isValidCombo(targetCombo, originConfig)) {
+ return false;
+ }
+ return v;
+ };
+ },
+ registerCustomNodes() {
+ LiteGraph.registerNodeType(
+ "PrimitiveNode",
+ Object.assign(PrimitiveNode, {
+ title: "Primitive"
+ })
+ );
+ PrimitiveNode.category = "utils";
+ }
+});
+window.comfyAPI = window.comfyAPI || {};
+window.comfyAPI.widgetInputs = window.comfyAPI.widgetInputs || {};
+window.comfyAPI.widgetInputs.getWidgetConfig = getWidgetConfig;
+window.comfyAPI.widgetInputs.setWidgetConfig = setWidgetConfig;
+window.comfyAPI.widgetInputs.mergeIfValid = mergeIfValid;
+const ORDER = Symbol();
+function merge(target, source) {
+ if (typeof target === "object" && typeof source === "object") {
+ for (const key in source) {
+ const sv = source[key];
+ if (typeof sv === "object") {
+ let tv = target[key];
+ if (!tv) tv = target[key] = {};
+ merge(tv, source[key]);
+ } else {
+ target[key] = sv;
+ }
+ }
+ }
+ return target;
+}
+__name(merge, "merge");
+class ManageGroupDialog extends ComfyDialog {
+ static {
+ __name(this, "ManageGroupDialog");
+ }
+ tabs;
+ selectedNodeIndex;
+ selectedTab = "Inputs";
+ selectedGroup;
+ modifications = {};
+ nodeItems;
+ app;
+ groupNodeType;
+ groupNodeDef;
+ groupData;
+ innerNodesList;
+ widgetsPage;
+ inputsPage;
+ outputsPage;
+ draggable;
+ get selectedNodeInnerIndex() {
+ return +this.nodeItems[this.selectedNodeIndex].dataset.nodeindex;
+ }
+ constructor(app2) {
+ super();
+ this.app = app2;
+ this.element = $el("dialog.comfy-group-manage", {
+ parent: document.body
+ });
+ }
+ changeTab(tab) {
+ this.tabs[this.selectedTab].tab.classList.remove("active");
+ this.tabs[this.selectedTab].page.classList.remove("active");
+ this.tabs[tab].tab.classList.add("active");
+ this.tabs[tab].page.classList.add("active");
+ this.selectedTab = tab;
+ }
+ changeNode(index, force) {
+ if (!force && this.selectedNodeIndex === index) return;
+ if (this.selectedNodeIndex != null) {
+ this.nodeItems[this.selectedNodeIndex].classList.remove("selected");
+ }
+ this.nodeItems[index].classList.add("selected");
+ this.selectedNodeIndex = index;
+ if (!this.buildInputsPage() && this.selectedTab === "Inputs") {
+ this.changeTab("Widgets");
+ }
+ if (!this.buildWidgetsPage() && this.selectedTab === "Widgets") {
+ this.changeTab("Outputs");
+ }
+ if (!this.buildOutputsPage() && this.selectedTab === "Outputs") {
+ this.changeTab("Inputs");
+ }
+ this.changeTab(this.selectedTab);
+ }
+ getGroupData() {
+ this.groupNodeType = LiteGraph.registered_node_types["workflow/" + this.selectedGroup];
+ this.groupNodeDef = this.groupNodeType.nodeData;
+ this.groupData = GroupNodeHandler.getGroupData(this.groupNodeType);
+ }
+ changeGroup(group, reset = true) {
+ this.selectedGroup = group;
+ this.getGroupData();
+ const nodes = this.groupData.nodeData.nodes;
+ this.nodeItems = nodes.map(
+ (n, i) => $el(
+ "li.draggable-item",
+ {
+ dataset: {
+ nodeindex: n.index + ""
+ },
+ onclick: /* @__PURE__ */ __name(() => {
+ this.changeNode(i);
+ }, "onclick")
+ },
+ [
+ $el("span.drag-handle"),
+ $el(
+ "div",
+ {
+ textContent: n.title ?? n.type
+ },
+ n.title ? $el("span", {
+ textContent: n.type
+ }) : []
+ )
+ ]
+ )
+ );
+ this.innerNodesList.replaceChildren(...this.nodeItems);
+ if (reset) {
+ this.selectedNodeIndex = null;
+ this.changeNode(0);
+ } else {
+ const items = this.draggable.getAllItems();
+ let index = items.findIndex((item) => item.classList.contains("selected"));
+ if (index === -1) index = this.selectedNodeIndex;
+ this.changeNode(index, true);
+ }
+ const ordered = [...nodes];
+ this.draggable?.dispose();
+ this.draggable = new DraggableList(this.innerNodesList, "li");
+ this.draggable.addEventListener(
+ "dragend",
+ ({ detail: { oldPosition, newPosition } }) => {
+ if (oldPosition === newPosition) return;
+ ordered.splice(newPosition, 0, ordered.splice(oldPosition, 1)[0]);
+ for (let i = 0; i < ordered.length; i++) {
+ this.storeModification({
+ nodeIndex: ordered[i].index,
+ section: ORDER,
+ prop: "order",
+ value: i
+ });
+ }
+ }
+ );
+ }
+ storeModification(props) {
+ const { nodeIndex, section, prop, value } = props;
+ const groupMod = this.modifications[this.selectedGroup] ??= {};
+ const nodesMod = groupMod.nodes ??= {};
+ const nodeMod = nodesMod[nodeIndex ?? this.selectedNodeInnerIndex] ??= {};
+ const typeMod = nodeMod[section] ??= {};
+ if (typeof value === "object") {
+ const objMod = typeMod[prop] ??= {};
+ Object.assign(objMod, value);
+ } else {
+ typeMod[prop] = value;
+ }
+ }
+ getEditElement(section, prop, value, placeholder, checked, checkable = true) {
+ if (value === placeholder) value = "";
+ const mods = this.modifications[this.selectedGroup]?.nodes?.[this.selectedNodeInnerIndex]?.[section]?.[prop];
+ if (mods) {
+ if (mods.name != null) {
+ value = mods.name;
+ }
+ if (mods.visible != null) {
+ checked = mods.visible;
+ }
+ }
+ return $el("div", [
+ $el("input", {
+ value,
+ placeholder,
+ type: "text",
+ onchange: /* @__PURE__ */ __name((e) => {
+ this.storeModification({
+ section,
+ prop,
+ value: { name: e.target.value }
+ });
+ }, "onchange")
+ }),
+ $el("label", { textContent: "Visible" }, [
+ $el("input", {
+ type: "checkbox",
+ checked,
+ disabled: !checkable,
+ onchange: /* @__PURE__ */ __name((e) => {
+ this.storeModification({
+ section,
+ prop,
+ value: { visible: !!e.target.checked }
+ });
+ }, "onchange")
+ })
+ ])
+ ]);
+ }
+ buildWidgetsPage() {
+ const widgets = this.groupData.oldToNewWidgetMap[this.selectedNodeInnerIndex];
+ const items = Object.keys(widgets ?? {});
+ const type = app.graph.extra.groupNodes[this.selectedGroup];
+ const config = type.config?.[this.selectedNodeInnerIndex]?.input;
+ this.widgetsPage.replaceChildren(
+ ...items.map((oldName) => {
+ return this.getEditElement(
+ "input",
+ oldName,
+ widgets[oldName],
+ oldName,
+ config?.[oldName]?.visible !== false
+ );
+ })
+ );
+ return !!items.length;
+ }
+ buildInputsPage() {
+ const inputs = this.groupData.nodeInputs[this.selectedNodeInnerIndex];
+ const items = Object.keys(inputs ?? {});
+ const type = app.graph.extra.groupNodes[this.selectedGroup];
+ const config = type.config?.[this.selectedNodeInnerIndex]?.input;
+ this.inputsPage.replaceChildren(
+ ...items.map((oldName) => {
+ let value = inputs[oldName];
+ if (!value) {
+ return;
+ }
+ return this.getEditElement(
+ "input",
+ oldName,
+ value,
+ oldName,
+ config?.[oldName]?.visible !== false
+ );
+ }).filter(Boolean)
+ );
+ return !!items.length;
+ }
+ buildOutputsPage() {
+ const nodes = this.groupData.nodeData.nodes;
+ const innerNodeDef = this.groupData.getNodeDef(
+ nodes[this.selectedNodeInnerIndex]
+ );
+ const outputs = innerNodeDef?.output ?? [];
+ const groupOutputs = this.groupData.oldToNewOutputMap[this.selectedNodeInnerIndex];
+ const type = app.graph.extra.groupNodes[this.selectedGroup];
+ const config = type.config?.[this.selectedNodeInnerIndex]?.output;
+ const node = this.groupData.nodeData.nodes[this.selectedNodeInnerIndex];
+ const checkable = node.type !== "PrimitiveNode";
+ this.outputsPage.replaceChildren(
+ ...outputs.map((type2, slot) => {
+ const groupOutputIndex = groupOutputs?.[slot];
+ const oldName = innerNodeDef.output_name?.[slot] ?? type2;
+ let value = config?.[slot]?.name;
+ const visible = config?.[slot]?.visible || groupOutputIndex != null;
+ if (!value || value === oldName) {
+ value = "";
+ }
+ return this.getEditElement(
+ "output",
+ slot,
+ value,
+ oldName,
+ visible,
+ checkable
+ );
+ }).filter(Boolean)
+ );
+ return !!outputs.length;
+ }
+ show(type) {
+ const groupNodes = Object.keys(app.graph.extra?.groupNodes ?? {}).sort(
+ (a, b) => a.localeCompare(b)
+ );
+ this.innerNodesList = $el(
+ "ul.comfy-group-manage-list-items"
+ );
+ this.widgetsPage = $el("section.comfy-group-manage-node-page");
+ this.inputsPage = $el("section.comfy-group-manage-node-page");
+ this.outputsPage = $el("section.comfy-group-manage-node-page");
+ const pages = $el("div", [
+ this.widgetsPage,
+ this.inputsPage,
+ this.outputsPage
+ ]);
+ this.tabs = [
+ ["Inputs", this.inputsPage],
+ ["Widgets", this.widgetsPage],
+ ["Outputs", this.outputsPage]
+ ].reduce((p, [name, page]) => {
+ p[name] = {
+ tab: $el("a", {
+ onclick: /* @__PURE__ */ __name(() => {
+ this.changeTab(name);
+ }, "onclick"),
+ textContent: name
+ }),
+ page
+ };
+ return p;
+ }, {});
+ const outer = $el("div.comfy-group-manage-outer", [
+ $el("header", [
+ $el("h2", "Group Nodes"),
+ $el(
+ "select",
+ {
+ onchange: /* @__PURE__ */ __name((e) => {
+ this.changeGroup(e.target.value);
+ }, "onchange")
+ },
+ groupNodes.map(
+ (g) => $el("option", {
+ textContent: g,
+ selected: "workflow/" + g === type,
+ value: g
+ })
+ )
+ )
+ ]),
+ $el("main", [
+ $el("section.comfy-group-manage-list", this.innerNodesList),
+ $el("section.comfy-group-manage-node", [
+ $el(
+ "header",
+ Object.values(this.tabs).map((t) => t.tab)
+ ),
+ pages
+ ])
+ ]),
+ $el("footer", [
+ $el(
+ "button.comfy-btn",
+ {
+ onclick: /* @__PURE__ */ __name((e) => {
+ const node = app.graph.nodes.find(
+ (n) => n.type === "workflow/" + this.selectedGroup
+ );
+ if (node) {
+ alert(
+ "This group node is in use in the current workflow, please first remove these."
+ );
+ return;
+ }
+ if (confirm(
+ `Are you sure you want to remove the node: "${this.selectedGroup}"`
+ )) {
+ delete app.graph.extra.groupNodes[this.selectedGroup];
+ LiteGraph.unregisterNodeType("workflow/" + this.selectedGroup);
+ }
+ this.show();
+ }, "onclick")
+ },
+ "Delete Group Node"
+ ),
+ $el(
+ "button.comfy-btn",
+ {
+ onclick: /* @__PURE__ */ __name(async () => {
+ let nodesByType;
+ let recreateNodes = [];
+ const types = {};
+ for (const g in this.modifications) {
+ const type2 = app.graph.extra.groupNodes[g];
+ let config = type2.config ??= {};
+ let nodeMods = this.modifications[g]?.nodes;
+ if (nodeMods) {
+ const keys = Object.keys(nodeMods);
+ if (nodeMods[keys[0]][ORDER]) {
+ const orderedNodes = [];
+ const orderedMods = {};
+ const orderedConfig = {};
+ for (const n of keys) {
+ const order = nodeMods[n][ORDER].order;
+ orderedNodes[order] = type2.nodes[+n];
+ orderedMods[order] = nodeMods[n];
+ orderedNodes[order].index = order;
+ }
+ for (const l of type2.links) {
+ if (l[0] != null) l[0] = type2.nodes[l[0]].index;
+ if (l[2] != null) l[2] = type2.nodes[l[2]].index;
+ }
+ if (type2.external) {
+ for (const ext2 of type2.external) {
+ ext2[0] = type2.nodes[ext2[0]];
+ }
+ }
+ for (const id2 of keys) {
+ if (config[id2]) {
+ orderedConfig[type2.nodes[id2].index] = config[id2];
+ }
+ delete config[id2];
+ }
+ type2.nodes = orderedNodes;
+ nodeMods = orderedMods;
+ type2.config = config = orderedConfig;
+ }
+ merge(config, nodeMods);
+ }
+ types[g] = type2;
+ if (!nodesByType) {
+ nodesByType = app.graph.nodes.reduce((p, n) => {
+ p[n.type] ??= [];
+ p[n.type].push(n);
+ return p;
+ }, {});
+ }
+ const nodes = nodesByType["workflow/" + g];
+ if (nodes) recreateNodes.push(...nodes);
+ }
+ await GroupNodeConfig.registerFromWorkflow(types, {});
+ for (const node of recreateNodes) {
+ node.recreate();
+ }
+ this.modifications = {};
+ this.app.graph.setDirtyCanvas(true, true);
+ this.changeGroup(this.selectedGroup, false);
+ }, "onclick")
+ },
+ "Save"
+ ),
+ $el(
+ "button.comfy-btn",
+ { onclick: /* @__PURE__ */ __name(() => this.element.close(), "onclick") },
+ "Close"
+ )
+ ])
+ ]);
+ this.element.replaceChildren(outer);
+ this.changeGroup(
+ type ? groupNodes.find((g) => "workflow/" + g === type) : groupNodes[0]
+ );
+ this.element.showModal();
+ this.element.addEventListener("close", () => {
+ this.draggable?.dispose();
+ });
+ }
+}
+window.comfyAPI = window.comfyAPI || {};
+window.comfyAPI.groupNodeManage = window.comfyAPI.groupNodeManage || {};
+window.comfyAPI.groupNodeManage.ManageGroupDialog = ManageGroupDialog;
+const GROUP = Symbol();
+const Workflow = {
+ InUse: {
+ Free: 0,
+ Registered: 1,
+ InWorkflow: 2
+ },
+ isInUseGroupNode(name) {
+ const id2 = `workflow/${name}`;
+ if (app.graph.extra?.groupNodes?.[name]) {
+ if (app.graph.nodes.find((n) => n.type === id2)) {
+ return Workflow.InUse.InWorkflow;
+ } else {
+ return Workflow.InUse.Registered;
+ }
+ }
+ return Workflow.InUse.Free;
+ },
+ storeGroupNode(name, data) {
+ let extra = app.graph.extra;
+ if (!extra) app.graph.extra = extra = {};
+ let groupNodes = extra.groupNodes;
+ if (!groupNodes) extra.groupNodes = groupNodes = {};
+ groupNodes[name] = data;
+ }
+};
+class GroupNodeBuilder {
+ static {
+ __name(this, "GroupNodeBuilder");
+ }
+ nodes;
+ nodeData;
+ constructor(nodes) {
+ this.nodes = nodes;
+ }
+ build() {
+ const name = this.getName();
+ if (!name) return;
+ this.sortNodes();
+ this.nodeData = this.getNodeData();
+ Workflow.storeGroupNode(name, this.nodeData);
+ return { name, nodeData: this.nodeData };
+ }
+ getName() {
+ const name = prompt("Enter group name");
+ if (!name) return;
+ const used = Workflow.isInUseGroupNode(name);
+ switch (used) {
+ case Workflow.InUse.InWorkflow:
+ alert(
+ "An in use group node with this name already exists embedded in this workflow, please remove any instances or use a new name."
+ );
+ return;
+ case Workflow.InUse.Registered:
+ if (!confirm(
+ "A group node with this name already exists embedded in this workflow, are you sure you want to overwrite it?"
+ )) {
+ return;
+ }
+ break;
+ }
+ return name;
+ }
+ sortNodes() {
+ const nodesInOrder = app.graph.computeExecutionOrder(false);
+ this.nodes = this.nodes.map((node) => ({ index: nodesInOrder.indexOf(node), node })).sort((a, b) => a.index - b.index || a.node.id - b.node.id).map(({ node }) => node);
+ }
+ getNodeData() {
+ const storeLinkTypes = /* @__PURE__ */ __name((config) => {
+ for (const link of config.links) {
+ const origin = app.graph.getNodeById(link[4]);
+ const type = origin.outputs[link[1]].type;
+ link.push(type);
+ }
+ }, "storeLinkTypes");
+ const storeExternalLinks = /* @__PURE__ */ __name((config) => {
+ config.external = [];
+ for (let i = 0; i < this.nodes.length; i++) {
+ const node = this.nodes[i];
+ if (!node.outputs?.length) continue;
+ for (let slot = 0; slot < node.outputs.length; slot++) {
+ let hasExternal = false;
+ const output = node.outputs[slot];
+ let type = output.type;
+ if (!output.links?.length) continue;
+ for (const l of output.links) {
+ const link = app.graph.links[l];
+ if (!link) continue;
+ if (type === "*") type = link.type;
+ if (!app.canvas.selected_nodes[link.target_id]) {
+ hasExternal = true;
+ break;
+ }
+ }
+ if (hasExternal) {
+ config.external.push([i, slot, type]);
+ }
+ }
+ }
+ }, "storeExternalLinks");
+ const backup = localStorage.getItem("litegrapheditor_clipboard");
+ try {
+ app.canvas.copyToClipboard(this.nodes);
+ const config = JSON.parse(
+ localStorage.getItem("litegrapheditor_clipboard")
+ );
+ storeLinkTypes(config);
+ storeExternalLinks(config);
+ return config;
+ } finally {
+ localStorage.setItem("litegrapheditor_clipboard", backup);
+ }
+ }
+}
+class GroupNodeConfig {
+ static {
+ __name(this, "GroupNodeConfig");
+ }
+ name;
+ nodeData;
+ inputCount;
+ oldToNewOutputMap;
+ newToOldOutputMap;
+ oldToNewInputMap;
+ oldToNewWidgetMap;
+ newToOldWidgetMap;
+ primitiveDefs;
+ widgetToPrimitive;
+ primitiveToWidget;
+ nodeInputs;
+ outputVisibility;
+ nodeDef;
+ inputs;
+ linksFrom;
+ linksTo;
+ externalFrom;
+ constructor(name, nodeData) {
+ this.name = name;
+ this.nodeData = nodeData;
+ this.getLinks();
+ this.inputCount = 0;
+ this.oldToNewOutputMap = {};
+ this.newToOldOutputMap = {};
+ this.oldToNewInputMap = {};
+ this.oldToNewWidgetMap = {};
+ this.newToOldWidgetMap = {};
+ this.primitiveDefs = {};
+ this.widgetToPrimitive = {};
+ this.primitiveToWidget = {};
+ this.nodeInputs = {};
+ this.outputVisibility = [];
+ }
+ async registerType(source = "workflow") {
+ this.nodeDef = {
+ output: [],
+ output_name: [],
+ output_is_list: [],
+ output_is_hidden: [],
+ name: source + "/" + this.name,
+ display_name: this.name,
+ category: "group nodes" + ("/" + source),
+ input: { required: {} },
+ description: `Group node combining ${this.nodeData.nodes.map((n) => n.type).join(", ")}`,
+ python_module: "custom_nodes." + this.name,
+ [GROUP]: this
+ };
+ this.inputs = [];
+ const seenInputs = {};
+ const seenOutputs = {};
+ for (let i = 0; i < this.nodeData.nodes.length; i++) {
+ const node = this.nodeData.nodes[i];
+ node.index = i;
+ this.processNode(node, seenInputs, seenOutputs);
+ }
+ for (const p of this.#convertedToProcess) {
+ p();
+ }
+ this.#convertedToProcess = null;
+ await app.registerNodeDef("workflow/" + this.name, this.nodeDef);
+ useNodeDefStore().addNodeDef(this.nodeDef);
+ }
+ getLinks() {
+ this.linksFrom = {};
+ this.linksTo = {};
+ this.externalFrom = {};
+ for (const l of this.nodeData.links) {
+ const [sourceNodeId, sourceNodeSlot, targetNodeId, targetNodeSlot] = l;
+ if (sourceNodeId == null) continue;
+ if (!this.linksFrom[sourceNodeId]) {
+ this.linksFrom[sourceNodeId] = {};
+ }
+ if (!this.linksFrom[sourceNodeId][sourceNodeSlot]) {
+ this.linksFrom[sourceNodeId][sourceNodeSlot] = [];
+ }
+ this.linksFrom[sourceNodeId][sourceNodeSlot].push(l);
+ if (!this.linksTo[targetNodeId]) {
+ this.linksTo[targetNodeId] = {};
+ }
+ this.linksTo[targetNodeId][targetNodeSlot] = l;
+ }
+ if (this.nodeData.external) {
+ for (const ext2 of this.nodeData.external) {
+ if (!this.externalFrom[ext2[0]]) {
+ this.externalFrom[ext2[0]] = { [ext2[1]]: ext2[2] };
+ } else {
+ this.externalFrom[ext2[0]][ext2[1]] = ext2[2];
+ }
+ }
+ }
+ }
+ processNode(node, seenInputs, seenOutputs) {
+ const def = this.getNodeDef(node);
+ if (!def) return;
+ const inputs = { ...def.input?.required, ...def.input?.optional };
+ this.inputs.push(this.processNodeInputs(node, seenInputs, inputs));
+ if (def.output?.length) this.processNodeOutputs(node, seenOutputs, def);
+ }
+ getNodeDef(node) {
+ const def = globalDefs[node.type];
+ if (def) return def;
+ const linksFrom = this.linksFrom[node.index];
+ if (node.type === "PrimitiveNode") {
+ if (!linksFrom) return;
+ let type = linksFrom["0"][0][5];
+ if (type === "COMBO") {
+ const source = node.outputs[0].widget.name;
+ const fromTypeName = this.nodeData.nodes[linksFrom["0"][0][2]].type;
+ const fromType = globalDefs[fromTypeName];
+ const input = fromType.input.required[source] ?? fromType.input.optional[source];
+ type = input[0];
+ }
+ const def2 = this.primitiveDefs[node.index] = {
+ input: {
+ required: {
+ value: [type, {}]
+ }
+ },
+ output: [type],
+ output_name: [],
+ output_is_list: []
+ };
+ return def2;
+ } else if (node.type === "Reroute") {
+ const linksTo = this.linksTo[node.index];
+ if (linksTo && linksFrom && !this.externalFrom[node.index]?.[0]) {
+ return null;
+ }
+ let config = {};
+ let rerouteType = "*";
+ if (linksFrom) {
+ for (const [, , id2, slot] of linksFrom["0"]) {
+ const node2 = this.nodeData.nodes[id2];
+ const input = node2.inputs[slot];
+ if (rerouteType === "*") {
+ rerouteType = input.type;
+ }
+ if (input.widget) {
+ const targetDef = globalDefs[node2.type];
+ const targetWidget = targetDef.input.required[input.widget.name] ?? targetDef.input.optional[input.widget.name];
+ const widget = [targetWidget[0], config];
+ const res = mergeIfValid(
+ {
+ widget
+ },
+ targetWidget,
+ false,
+ null,
+ widget
+ );
+ config = res?.customConfig ?? config;
+ }
+ }
+ } else if (linksTo) {
+ const [id2, slot] = linksTo["0"];
+ rerouteType = this.nodeData.nodes[id2].outputs[slot].type;
+ } else {
+ for (const l of this.nodeData.links) {
+ if (l[2] === node.index) {
+ rerouteType = l[5];
+ break;
+ }
+ }
+ if (rerouteType === "*") {
+ const t = this.externalFrom[node.index]?.[0];
+ if (t) {
+ rerouteType = t;
+ }
+ }
+ }
+ config.forceInput = true;
+ return {
+ input: {
+ required: {
+ [rerouteType]: [rerouteType, config]
+ }
+ },
+ output: [rerouteType],
+ output_name: [],
+ output_is_list: []
+ };
+ }
+ console.warn(
+ "Skipping virtual node " + node.type + " when building group node " + this.name
+ );
+ }
+ getInputConfig(node, inputName, seenInputs, config, extra) {
+ const customConfig = this.nodeData.config?.[node.index]?.input?.[inputName];
+ let name = customConfig?.name ?? node.inputs?.find((inp) => inp.name === inputName)?.label ?? inputName;
+ let key = name;
+ let prefix = "";
+ if (node.type === "PrimitiveNode" && node.title || name in seenInputs) {
+ prefix = `${node.title ?? node.type} `;
+ key = name = `${prefix}${inputName}`;
+ if (name in seenInputs) {
+ name = `${prefix}${seenInputs[name]} ${inputName}`;
+ }
+ }
+ seenInputs[key] = (seenInputs[key] ?? 1) + 1;
+ if (inputName === "seed" || inputName === "noise_seed") {
+ if (!extra) extra = {};
+ extra.control_after_generate = `${prefix}control_after_generate`;
+ }
+ if (config[0] === "IMAGEUPLOAD") {
+ if (!extra) extra = {};
+ extra.widget = this.oldToNewWidgetMap[node.index]?.[config[1]?.widget ?? "image"] ?? "image";
+ }
+ if (extra) {
+ config = [config[0], { ...config[1], ...extra }];
+ }
+ return { name, config, customConfig };
+ }
+ processWidgetInputs(inputs, node, inputNames, seenInputs) {
+ const slots = [];
+ const converted = /* @__PURE__ */ new Map();
+ const widgetMap = this.oldToNewWidgetMap[node.index] = {};
+ for (const inputName of inputNames) {
+ let widgetType = app.getWidgetType(inputs[inputName], inputName);
+ if (widgetType) {
+ const convertedIndex = node.inputs?.findIndex(
+ (inp) => inp.name === inputName && inp.widget?.name === inputName
+ );
+ if (convertedIndex > -1) {
+ converted.set(convertedIndex, inputName);
+ widgetMap[inputName] = null;
+ } else {
+ const { name, config } = this.getInputConfig(
+ node,
+ inputName,
+ seenInputs,
+ inputs[inputName]
+ );
+ this.nodeDef.input.required[name] = config;
+ widgetMap[inputName] = name;
+ this.newToOldWidgetMap[name] = { node, inputName };
+ }
+ } else {
+ slots.push(inputName);
+ }
+ }
+ return { converted, slots };
+ }
+ checkPrimitiveConnection(link, inputName, inputs) {
+ const sourceNode = this.nodeData.nodes[link[0]];
+ if (sourceNode.type === "PrimitiveNode") {
+ const [sourceNodeId, _2, targetNodeId, __] = link;
+ const primitiveDef = this.primitiveDefs[sourceNodeId];
+ const targetWidget = inputs[inputName];
+ const primitiveConfig = primitiveDef.input.required.value;
+ const output = { widget: primitiveConfig };
+ const config = mergeIfValid(
+ output,
+ targetWidget,
+ false,
+ null,
+ primitiveConfig
+ );
+ primitiveConfig[1] = config?.customConfig ?? inputs[inputName][1] ? { ...inputs[inputName][1] } : {};
+ let name = this.oldToNewWidgetMap[sourceNodeId]["value"];
+ name = name.substr(0, name.length - 6);
+ primitiveConfig[1].control_after_generate = true;
+ primitiveConfig[1].control_prefix = name;
+ let toPrimitive = this.widgetToPrimitive[targetNodeId];
+ if (!toPrimitive) {
+ toPrimitive = this.widgetToPrimitive[targetNodeId] = {};
+ }
+ if (toPrimitive[inputName]) {
+ toPrimitive[inputName].push(sourceNodeId);
+ }
+ toPrimitive[inputName] = sourceNodeId;
+ let toWidget = this.primitiveToWidget[sourceNodeId];
+ if (!toWidget) {
+ toWidget = this.primitiveToWidget[sourceNodeId] = [];
+ }
+ toWidget.push({ nodeId: targetNodeId, inputName });
+ }
+ }
+ processInputSlots(inputs, node, slots, linksTo, inputMap, seenInputs) {
+ this.nodeInputs[node.index] = {};
+ for (let i = 0; i < slots.length; i++) {
+ const inputName = slots[i];
+ if (linksTo[i]) {
+ this.checkPrimitiveConnection(linksTo[i], inputName, inputs);
+ continue;
+ }
+ const { name, config, customConfig } = this.getInputConfig(
+ node,
+ inputName,
+ seenInputs,
+ inputs[inputName]
+ );
+ this.nodeInputs[node.index][inputName] = name;
+ if (customConfig?.visible === false) continue;
+ this.nodeDef.input.required[name] = config;
+ inputMap[i] = this.inputCount++;
+ }
+ }
+ processConvertedWidgets(inputs, node, slots, converted, linksTo, inputMap, seenInputs) {
+ const convertedSlots = [...converted.keys()].sort().map((k) => converted.get(k));
+ for (let i = 0; i < convertedSlots.length; i++) {
+ const inputName = convertedSlots[i];
+ if (linksTo[slots.length + i]) {
+ this.checkPrimitiveConnection(
+ linksTo[slots.length + i],
+ inputName,
+ inputs
+ );
+ continue;
+ }
+ const { name, config } = this.getInputConfig(
+ node,
+ inputName,
+ seenInputs,
+ inputs[inputName],
+ {
+ defaultInput: true
+ }
+ );
+ this.nodeDef.input.required[name] = config;
+ this.newToOldWidgetMap[name] = { node, inputName };
+ if (!this.oldToNewWidgetMap[node.index]) {
+ this.oldToNewWidgetMap[node.index] = {};
+ }
+ this.oldToNewWidgetMap[node.index][inputName] = name;
+ inputMap[slots.length + i] = this.inputCount++;
+ }
+ }
+ #convertedToProcess = [];
+ processNodeInputs(node, seenInputs, inputs) {
+ const inputMapping = [];
+ const inputNames = Object.keys(inputs);
+ if (!inputNames.length) return;
+ const { converted, slots } = this.processWidgetInputs(
+ inputs,
+ node,
+ inputNames,
+ seenInputs
+ );
+ const linksTo = this.linksTo[node.index] ?? {};
+ const inputMap = this.oldToNewInputMap[node.index] = {};
+ this.processInputSlots(inputs, node, slots, linksTo, inputMap, seenInputs);
+ this.#convertedToProcess.push(
+ () => this.processConvertedWidgets(
+ inputs,
+ node,
+ slots,
+ converted,
+ linksTo,
+ inputMap,
+ seenInputs
+ )
+ );
+ return inputMapping;
+ }
+ processNodeOutputs(node, seenOutputs, def) {
+ const oldToNew = this.oldToNewOutputMap[node.index] = {};
+ for (let outputId = 0; outputId < def.output.length; outputId++) {
+ const linksFrom = this.linksFrom[node.index];
+ const hasLink = linksFrom?.[outputId] && !this.externalFrom[node.index]?.[outputId];
+ const customConfig = this.nodeData.config?.[node.index]?.output?.[outputId];
+ const visible = customConfig?.visible ?? !hasLink;
+ this.outputVisibility.push(visible);
+ if (!visible) {
+ continue;
+ }
+ oldToNew[outputId] = this.nodeDef.output.length;
+ this.newToOldOutputMap[this.nodeDef.output.length] = {
+ node,
+ slot: outputId
+ };
+ this.nodeDef.output.push(def.output[outputId]);
+ this.nodeDef.output_is_list.push(def.output_is_list[outputId]);
+ let label = customConfig?.name;
+ if (!label) {
+ label = def.output_name?.[outputId] ?? def.output[outputId];
+ const output = node.outputs.find((o) => o.name === label);
+ if (output?.label) {
+ label = output.label;
+ }
+ }
+ let name = label;
+ if (name in seenOutputs) {
+ const prefix = `${node.title ?? node.type} `;
+ name = `${prefix}${label}`;
+ if (name in seenOutputs) {
+ name = `${prefix}${node.index} ${label}`;
+ }
+ }
+ seenOutputs[name] = 1;
+ this.nodeDef.output_name.push(name);
+ }
+ }
+ static async registerFromWorkflow(groupNodes, missingNodeTypes) {
+ const clean = app.clean;
+ app.clean = function() {
+ for (const g in groupNodes) {
+ try {
+ LiteGraph.unregisterNodeType("workflow/" + g);
+ } catch (error) {
+ }
+ }
+ app.clean = clean;
+ };
+ for (const g in groupNodes) {
+ const groupData = groupNodes[g];
+ let hasMissing = false;
+ for (const n of groupData.nodes) {
+ if (!(n.type in LiteGraph.registered_node_types)) {
+ missingNodeTypes.push({
+ type: n.type,
+ hint: ` (In group node 'workflow/${g}')`
+ });
+ missingNodeTypes.push({
+ type: "workflow/" + g,
+ action: {
+ text: "Remove from workflow",
+ callback: /* @__PURE__ */ __name((e) => {
+ delete groupNodes[g];
+ e.target.textContent = "Removed";
+ e.target.style.pointerEvents = "none";
+ e.target.style.opacity = 0.7;
+ }, "callback")
+ }
+ });
+ hasMissing = true;
+ }
+ }
+ if (hasMissing) continue;
+ const config = new GroupNodeConfig(g, groupData);
+ await config.registerType();
+ }
+ }
+}
+class GroupNodeHandler {
+ static {
+ __name(this, "GroupNodeHandler");
+ }
+ node;
+ groupData;
+ innerNodes;
+ constructor(node) {
+ this.node = node;
+ this.groupData = node.constructor?.nodeData?.[GROUP];
+ this.node.setInnerNodes = (innerNodes) => {
+ this.innerNodes = innerNodes;
+ for (let innerNodeIndex = 0; innerNodeIndex < this.innerNodes.length; innerNodeIndex++) {
+ const innerNode = this.innerNodes[innerNodeIndex];
+ for (const w of innerNode.widgets ?? []) {
+ if (w.type === "converted-widget") {
+ w.serializeValue = w.origSerializeValue;
+ }
+ }
+ innerNode.index = innerNodeIndex;
+ innerNode.getInputNode = (slot) => {
+ const externalSlot = this.groupData.oldToNewInputMap[innerNode.index]?.[slot];
+ if (externalSlot != null) {
+ return this.node.getInputNode(externalSlot);
+ }
+ const innerLink = this.groupData.linksTo[innerNode.index]?.[slot];
+ if (!innerLink) return null;
+ const inputNode = innerNodes[innerLink[0]];
+ if (inputNode.type === "PrimitiveNode") return null;
+ return inputNode;
+ };
+ innerNode.getInputLink = (slot) => {
+ const externalSlot = this.groupData.oldToNewInputMap[innerNode.index]?.[slot];
+ if (externalSlot != null) {
+ const linkId = this.node.inputs[externalSlot].link;
+ let link2 = app.graph.links[linkId];
+ link2 = {
+ ...link2,
+ target_id: innerNode.id,
+ target_slot: +slot
+ };
+ return link2;
+ }
+ let link = this.groupData.linksTo[innerNode.index]?.[slot];
+ if (!link) return null;
+ link = {
+ origin_id: innerNodes[link[0]].id,
+ origin_slot: link[1],
+ target_id: innerNode.id,
+ target_slot: +slot
+ };
+ return link;
+ };
+ }
+ };
+ this.node.updateLink = (link) => {
+ link = { ...link };
+ const output = this.groupData.newToOldOutputMap[link.origin_slot];
+ let innerNode = this.innerNodes[output.node.index];
+ let l;
+ while (innerNode?.type === "Reroute") {
+ l = innerNode.getInputLink(0);
+ innerNode = innerNode.getInputNode(0);
+ }
+ if (!innerNode) {
+ return null;
+ }
+ if (l && GroupNodeHandler.isGroupNode(innerNode)) {
+ return innerNode.updateLink(l);
+ }
+ link.origin_id = innerNode.id;
+ link.origin_slot = l?.origin_slot ?? output.slot;
+ return link;
+ };
+ this.node.getInnerNodes = () => {
+ if (!this.innerNodes) {
+ this.node.setInnerNodes(
+ this.groupData.nodeData.nodes.map((n, i) => {
+ const innerNode = LiteGraph.createNode(n.type);
+ innerNode.configure(n);
+ innerNode.id = `${this.node.id}:${i}`;
+ return innerNode;
+ })
+ );
+ }
+ this.updateInnerWidgets();
+ return this.innerNodes;
+ };
+ this.node.recreate = async () => {
+ const id2 = this.node.id;
+ const sz = this.node.size;
+ const nodes = this.node.convertToNodes();
+ const groupNode = LiteGraph.createNode(this.node.type);
+ groupNode.id = id2;
+ groupNode.setInnerNodes(nodes);
+ groupNode[GROUP].populateWidgets();
+ app.graph.add(groupNode);
+ groupNode.size = [
+ Math.max(groupNode.size[0], sz[0]),
+ Math.max(groupNode.size[1], sz[1])
+ ];
+ groupNode[GROUP].replaceNodes(nodes);
+ return groupNode;
+ };
+ this.node.convertToNodes = () => {
+ const addInnerNodes = /* @__PURE__ */ __name(() => {
+ const backup = localStorage.getItem("litegrapheditor_clipboard");
+ const c = { ...this.groupData.nodeData };
+ c.nodes = [...c.nodes];
+ const innerNodes = this.node.getInnerNodes();
+ let ids = [];
+ for (let i = 0; i < c.nodes.length; i++) {
+ let id2 = innerNodes?.[i]?.id;
+ if (id2 == null || isNaN(id2)) {
+ id2 = void 0;
+ } else {
+ ids.push(id2);
+ }
+ c.nodes[i] = { ...c.nodes[i], id: id2 };
+ }
+ localStorage.setItem("litegrapheditor_clipboard", JSON.stringify(c));
+ app.canvas.pasteFromClipboard();
+ localStorage.setItem("litegrapheditor_clipboard", backup);
+ const [x, y] = this.node.pos;
+ let top;
+ let left;
+ const selectedIds2 = ids.length ? ids : Object.keys(app.canvas.selected_nodes);
+ const newNodes2 = [];
+ for (let i = 0; i < selectedIds2.length; i++) {
+ const id2 = selectedIds2[i];
+ const newNode = app.graph.getNodeById(id2);
+ const innerNode = innerNodes[i];
+ newNodes2.push(newNode);
+ if (left == null || newNode.pos[0] < left) {
+ left = newNode.pos[0];
+ }
+ if (top == null || newNode.pos[1] < top) {
+ top = newNode.pos[1];
+ }
+ if (!newNode.widgets) continue;
+ const map = this.groupData.oldToNewWidgetMap[innerNode.index];
+ if (map) {
+ const widgets = Object.keys(map);
+ for (const oldName of widgets) {
+ const newName = map[oldName];
+ if (!newName) continue;
+ const widgetIndex = this.node.widgets.findIndex(
+ (w) => w.name === newName
+ );
+ if (widgetIndex === -1) continue;
+ if (innerNode.type === "PrimitiveNode") {
+ for (let i2 = 0; i2 < newNode.widgets.length; i2++) {
+ newNode.widgets[i2].value = this.node.widgets[widgetIndex + i2].value;
+ }
+ } else {
+ const outerWidget = this.node.widgets[widgetIndex];
+ const newWidget = newNode.widgets.find(
+ (w) => w.name === oldName
+ );
+ if (!newWidget) continue;
+ newWidget.value = outerWidget.value;
+ for (let w = 0; w < outerWidget.linkedWidgets?.length; w++) {
+ newWidget.linkedWidgets[w].value = outerWidget.linkedWidgets[w].value;
+ }
+ }
+ }
+ }
+ }
+ for (const newNode of newNodes2) {
+ newNode.pos = [
+ newNode.pos[0] - (left - x),
+ newNode.pos[1] - (top - y)
+ ];
+ }
+ return { newNodes: newNodes2, selectedIds: selectedIds2 };
+ }, "addInnerNodes");
+ const reconnectInputs = /* @__PURE__ */ __name((selectedIds2) => {
+ for (const innerNodeIndex in this.groupData.oldToNewInputMap) {
+ const id2 = selectedIds2[innerNodeIndex];
+ const newNode = app.graph.getNodeById(id2);
+ const map = this.groupData.oldToNewInputMap[innerNodeIndex];
+ for (const innerInputId in map) {
+ const groupSlotId = map[innerInputId];
+ if (groupSlotId == null) continue;
+ const slot = node.inputs[groupSlotId];
+ if (slot.link == null) continue;
+ const link = app.graph.links[slot.link];
+ if (!link) continue;
+ const originNode = app.graph.getNodeById(link.origin_id);
+ originNode.connect(link.origin_slot, newNode, +innerInputId);
+ }
+ }
+ }, "reconnectInputs");
+ const reconnectOutputs = /* @__PURE__ */ __name((selectedIds2) => {
+ for (let groupOutputId = 0; groupOutputId < node.outputs?.length; groupOutputId++) {
+ const output = node.outputs[groupOutputId];
+ if (!output.links) continue;
+ const links = [...output.links];
+ for (const l of links) {
+ const slot = this.groupData.newToOldOutputMap[groupOutputId];
+ const link = app.graph.links[l];
+ const targetNode = app.graph.getNodeById(link.target_id);
+ const newNode = app.graph.getNodeById(selectedIds2[slot.node.index]);
+ newNode.connect(slot.slot, targetNode, link.target_slot);
+ }
+ }
+ }, "reconnectOutputs");
+ const { newNodes, selectedIds } = addInnerNodes();
+ reconnectInputs(selectedIds);
+ reconnectOutputs(selectedIds);
+ app.graph.remove(this.node);
+ return newNodes;
+ };
+ const getExtraMenuOptions = this.node.getExtraMenuOptions;
+ this.node.getExtraMenuOptions = function(_2, options) {
+ getExtraMenuOptions?.apply(this, arguments);
+ let optionIndex = options.findIndex((o) => o.content === "Outputs");
+ if (optionIndex === -1) optionIndex = options.length;
+ else optionIndex++;
+ options.splice(
+ optionIndex,
+ 0,
+ null,
+ {
+ content: "Convert to nodes",
+ callback: /* @__PURE__ */ __name(() => {
+ return this.convertToNodes();
+ }, "callback")
+ },
+ {
+ content: "Manage Group Node",
+ callback: /* @__PURE__ */ __name(() => {
+ new ManageGroupDialog(app).show(this.type);
+ }, "callback")
+ }
+ );
+ };
+ const onDrawTitleBox = this.node.onDrawTitleBox;
+ this.node.onDrawTitleBox = function(ctx, height, size, scale) {
+ onDrawTitleBox?.apply(this, arguments);
+ const fill = ctx.fillStyle;
+ ctx.beginPath();
+ ctx.rect(11, -height + 11, 2, 2);
+ ctx.rect(14, -height + 11, 2, 2);
+ ctx.rect(17, -height + 11, 2, 2);
+ ctx.rect(11, -height + 14, 2, 2);
+ ctx.rect(14, -height + 14, 2, 2);
+ ctx.rect(17, -height + 14, 2, 2);
+ ctx.rect(11, -height + 17, 2, 2);
+ ctx.rect(14, -height + 17, 2, 2);
+ ctx.rect(17, -height + 17, 2, 2);
+ ctx.fillStyle = this.boxcolor || LiteGraph.NODE_DEFAULT_BOXCOLOR;
+ ctx.fill();
+ ctx.fillStyle = fill;
+ };
+ const onDrawForeground = node.onDrawForeground;
+ const groupData = this.groupData.nodeData;
+ node.onDrawForeground = function(ctx) {
+ const r = onDrawForeground?.apply?.(this, arguments);
+ if (+app.runningNodeId === this.id && this.runningInternalNodeId !== null) {
+ const n = groupData.nodes[this.runningInternalNodeId];
+ if (!n) return;
+ const message = `Running ${n.title || n.type} (${this.runningInternalNodeId}/${groupData.nodes.length})`;
+ ctx.save();
+ ctx.font = "12px sans-serif";
+ const sz = ctx.measureText(message);
+ ctx.fillStyle = node.boxcolor || LiteGraph.NODE_DEFAULT_BOXCOLOR;
+ ctx.beginPath();
+ ctx.roundRect(
+ 0,
+ -LiteGraph.NODE_TITLE_HEIGHT - 20,
+ sz.width + 12,
+ 20,
+ 5
+ );
+ ctx.fill();
+ ctx.fillStyle = "#fff";
+ ctx.fillText(message, 6, -LiteGraph.NODE_TITLE_HEIGHT - 6);
+ ctx.restore();
+ }
+ };
+ const onExecutionStart = this.node.onExecutionStart;
+ this.node.onExecutionStart = function() {
+ this.resetExecution = true;
+ return onExecutionStart?.apply(this, arguments);
+ };
+ const self = this;
+ const onNodeCreated = this.node.onNodeCreated;
+ this.node.onNodeCreated = function() {
+ if (!this.widgets) {
+ return;
+ }
+ const config = self.groupData.nodeData.config;
+ if (config) {
+ for (const n in config) {
+ const inputs = config[n]?.input;
+ for (const w in inputs) {
+ if (inputs[w].visible !== false) continue;
+ const widgetName = self.groupData.oldToNewWidgetMap[n][w];
+ const widget = this.widgets.find((w2) => w2.name === widgetName);
+ if (widget) {
+ widget.type = "hidden";
+ widget.computeSize = () => [0, -4];
+ }
+ }
+ }
+ }
+ return onNodeCreated?.apply(this, arguments);
+ };
+ function handleEvent(type, getId, getEvent) {
+ const handler = /* @__PURE__ */ __name(({ detail }) => {
+ const id2 = getId(detail);
+ if (!id2) return;
+ const node2 = app.graph.getNodeById(id2);
+ if (node2) return;
+ const innerNodeIndex = this.innerNodes?.findIndex((n) => n.id == id2);
+ if (innerNodeIndex > -1) {
+ this.node.runningInternalNodeId = innerNodeIndex;
+ api.dispatchEvent(
+ new CustomEvent(type, {
+ detail: getEvent(detail, this.node.id + "", this.node)
+ })
+ );
+ }
+ }, "handler");
+ api.addEventListener(type, handler);
+ return handler;
+ }
+ __name(handleEvent, "handleEvent");
+ const executing = handleEvent.call(
+ this,
+ "executing",
+ (d) => d,
+ (d, id2, node2) => id2
+ );
+ const executed = handleEvent.call(
+ this,
+ "executed",
+ (d) => d?.display_node || d?.node,
+ (d, id2, node2) => ({
+ ...d,
+ node: id2,
+ display_node: id2,
+ merge: !node2.resetExecution
+ })
+ );
+ const onRemoved = node.onRemoved;
+ this.node.onRemoved = function() {
+ onRemoved?.apply(this, arguments);
+ api.removeEventListener("executing", executing);
+ api.removeEventListener("executed", executed);
+ };
+ this.node.refreshComboInNode = (defs) => {
+ for (const widgetName in this.groupData.newToOldWidgetMap) {
+ const widget = this.node.widgets.find((w) => w.name === widgetName);
+ if (widget?.type === "combo") {
+ const old = this.groupData.newToOldWidgetMap[widgetName];
+ const def = defs[old.node.type];
+ const input = def?.input?.required?.[old.inputName] ?? def?.input?.optional?.[old.inputName];
+ if (!input) continue;
+ widget.options.values = input[0];
+ if (old.inputName !== "image" && !widget.options.values.includes(widget.value)) {
+ widget.value = widget.options.values[0];
+ widget.callback(widget.value);
+ }
+ }
+ }
+ };
+ }
+ updateInnerWidgets() {
+ for (const newWidgetName in this.groupData.newToOldWidgetMap) {
+ const newWidget = this.node.widgets.find((w) => w.name === newWidgetName);
+ if (!newWidget) continue;
+ const newValue = newWidget.value;
+ const old = this.groupData.newToOldWidgetMap[newWidgetName];
+ let innerNode = this.innerNodes[old.node.index];
+ if (innerNode.type === "PrimitiveNode") {
+ innerNode.primitiveValue = newValue;
+ const primitiveLinked = this.groupData.primitiveToWidget[old.node.index];
+ for (const linked of primitiveLinked ?? []) {
+ const node = this.innerNodes[linked.nodeId];
+ const widget2 = node.widgets.find((w) => w.name === linked.inputName);
+ if (widget2) {
+ widget2.value = newValue;
+ }
+ }
+ continue;
+ } else if (innerNode.type === "Reroute") {
+ const rerouteLinks = this.groupData.linksFrom[old.node.index];
+ if (rerouteLinks) {
+ for (const [_2, , targetNodeId, targetSlot] of rerouteLinks["0"]) {
+ const node = this.innerNodes[targetNodeId];
+ const input = node.inputs[targetSlot];
+ if (input.widget) {
+ const widget2 = node.widgets?.find(
+ (w) => w.name === input.widget.name
+ );
+ if (widget2) {
+ widget2.value = newValue;
+ }
+ }
+ }
+ }
+ }
+ const widget = innerNode.widgets?.find((w) => w.name === old.inputName);
+ if (widget) {
+ widget.value = newValue;
+ }
+ }
+ }
+ populatePrimitive(node, nodeId, oldName, i, linkedShift) {
+ const primitiveId = this.groupData.widgetToPrimitive[nodeId]?.[oldName];
+ if (primitiveId == null) return;
+ const targetWidgetName = this.groupData.oldToNewWidgetMap[primitiveId]["value"];
+ const targetWidgetIndex = this.node.widgets.findIndex(
+ (w) => w.name === targetWidgetName
+ );
+ if (targetWidgetIndex > -1) {
+ const primitiveNode = this.innerNodes[primitiveId];
+ let len = primitiveNode.widgets.length;
+ if (len - 1 !== this.node.widgets[targetWidgetIndex].linkedWidgets?.length) {
+ len = 1;
+ }
+ for (let i2 = 0; i2 < len; i2++) {
+ this.node.widgets[targetWidgetIndex + i2].value = primitiveNode.widgets[i2].value;
+ }
+ }
+ return true;
+ }
+ populateReroute(node, nodeId, map) {
+ if (node.type !== "Reroute") return;
+ const link = this.groupData.linksFrom[nodeId]?.[0]?.[0];
+ if (!link) return;
+ const [, , targetNodeId, targetNodeSlot] = link;
+ const targetNode = this.groupData.nodeData.nodes[targetNodeId];
+ const inputs = targetNode.inputs;
+ const targetWidget = inputs?.[targetNodeSlot]?.widget;
+ if (!targetWidget) return;
+ const offset = inputs.length - (targetNode.widgets_values?.length ?? 0);
+ const v = targetNode.widgets_values?.[targetNodeSlot - offset];
+ if (v == null) return;
+ const widgetName = Object.values(map)[0];
+ const widget = this.node.widgets.find((w) => w.name === widgetName);
+ if (widget) {
+ widget.value = v;
+ }
+ }
+ populateWidgets() {
+ if (!this.node.widgets) return;
+ for (let nodeId = 0; nodeId < this.groupData.nodeData.nodes.length; nodeId++) {
+ const node = this.groupData.nodeData.nodes[nodeId];
+ const map = this.groupData.oldToNewWidgetMap[nodeId] ?? {};
+ const widgets = Object.keys(map);
+ if (!node.widgets_values?.length) {
+ this.populateReroute(node, nodeId, map);
+ continue;
+ }
+ let linkedShift = 0;
+ for (let i = 0; i < widgets.length; i++) {
+ const oldName = widgets[i];
+ const newName = map[oldName];
+ const widgetIndex = this.node.widgets.findIndex(
+ (w) => w.name === newName
+ );
+ const mainWidget = this.node.widgets[widgetIndex];
+ if (this.populatePrimitive(node, nodeId, oldName, i, linkedShift) || widgetIndex === -1) {
+ const innerWidget = this.innerNodes[nodeId].widgets?.find(
+ (w) => w.name === oldName
+ );
+ linkedShift += innerWidget?.linkedWidgets?.length ?? 0;
+ }
+ if (widgetIndex === -1) {
+ continue;
+ }
+ mainWidget.value = node.widgets_values[i + linkedShift];
+ for (let w = 0; w < mainWidget.linkedWidgets?.length; w++) {
+ this.node.widgets[widgetIndex + w + 1].value = node.widgets_values[i + ++linkedShift];
+ }
+ }
+ }
+ }
+ replaceNodes(nodes) {
+ let top;
+ let left;
+ for (let i = 0; i < nodes.length; i++) {
+ const node = nodes[i];
+ if (left == null || node.pos[0] < left) {
+ left = node.pos[0];
+ }
+ if (top == null || node.pos[1] < top) {
+ top = node.pos[1];
+ }
+ this.linkOutputs(node, i);
+ app.graph.remove(node);
+ }
+ this.linkInputs();
+ this.node.pos = [left, top];
+ }
+ linkOutputs(originalNode, nodeId) {
+ if (!originalNode.outputs) return;
+ for (const output of originalNode.outputs) {
+ if (!output.links) continue;
+ const links = [...output.links];
+ for (const l of links) {
+ const link = app.graph.links[l];
+ if (!link) continue;
+ const targetNode = app.graph.getNodeById(link.target_id);
+ const newSlot = this.groupData.oldToNewOutputMap[nodeId]?.[link.origin_slot];
+ if (newSlot != null) {
+ this.node.connect(newSlot, targetNode, link.target_slot);
+ }
+ }
+ }
+ }
+ linkInputs() {
+ for (const link of this.groupData.nodeData.links ?? []) {
+ const [, originSlot, targetId, targetSlot, actualOriginId] = link;
+ const originNode = app.graph.getNodeById(actualOriginId);
+ if (!originNode) continue;
+ originNode.connect(
+ originSlot,
+ this.node.id,
+ this.groupData.oldToNewInputMap[targetId][targetSlot]
+ );
+ }
+ }
+ static getGroupData(node) {
+ return (node.nodeData ?? node.constructor?.nodeData)?.[GROUP];
+ }
+ static isGroupNode(node) {
+ return !!node.constructor?.nodeData?.[GROUP];
+ }
+ static async fromNodes(nodes) {
+ const builder = new GroupNodeBuilder(nodes);
+ const res = builder.build();
+ if (!res) return;
+ const { name, nodeData } = res;
+ const config = new GroupNodeConfig(name, nodeData);
+ await config.registerType();
+ const groupNode = LiteGraph.createNode(`workflow/${name}`);
+ groupNode.setInnerNodes(builder.nodes);
+ groupNode[GROUP].populateWidgets();
+ app.graph.add(groupNode);
+ groupNode[GROUP].replaceNodes(builder.nodes);
+ return groupNode;
+ }
+}
+function addConvertToGroupOptions() {
+ function addConvertOption(options, index) {
+ const selected = Object.values(app.canvas.selected_nodes ?? {});
+ const disabled = selected.length < 2 || selected.find((n) => GroupNodeHandler.isGroupNode(n));
+ options.splice(index + 1, null, {
+ content: `Convert to Group Node`,
+ disabled,
+ callback: /* @__PURE__ */ __name(async () => {
+ return await GroupNodeHandler.fromNodes(selected);
+ }, "callback")
+ });
+ }
+ __name(addConvertOption, "addConvertOption");
+ function addManageOption(options, index) {
+ const groups = app.graph.extra?.groupNodes;
+ const disabled = !groups || !Object.keys(groups).length;
+ options.splice(index + 1, null, {
+ content: `Manage Group Nodes`,
+ disabled,
+ callback: /* @__PURE__ */ __name(() => {
+ new ManageGroupDialog(app).show();
+ }, "callback")
+ });
+ }
+ __name(addManageOption, "addManageOption");
+ const getCanvasMenuOptions = LGraphCanvas.prototype.getCanvasMenuOptions;
+ LGraphCanvas.prototype.getCanvasMenuOptions = function() {
+ const options = getCanvasMenuOptions.apply(this, arguments);
+ const index = options.findIndex((o) => o?.content === "Add Group") + 1 || options.length;
+ addConvertOption(options, index);
+ addManageOption(options, index + 1);
+ return options;
+ };
+ const getNodeMenuOptions = LGraphCanvas.prototype.getNodeMenuOptions;
+ LGraphCanvas.prototype.getNodeMenuOptions = function(node) {
+ const options = getNodeMenuOptions.apply(this, arguments);
+ if (!GroupNodeHandler.isGroupNode(node)) {
+ const index = options.findIndex((o) => o?.content === "Outputs") + 1 || options.length - 1;
+ addConvertOption(options, index);
+ }
+ return options;
+ };
+}
+__name(addConvertToGroupOptions, "addConvertToGroupOptions");
+const id$3 = "Comfy.GroupNode";
+let globalDefs;
+const ext$1 = {
+ name: id$3,
+ setup() {
+ addConvertToGroupOptions();
+ },
+ async beforeConfigureGraph(graphData, missingNodeTypes) {
+ const nodes = graphData?.extra?.groupNodes;
+ if (nodes) {
+ await GroupNodeConfig.registerFromWorkflow(nodes, missingNodeTypes);
+ }
+ },
+ addCustomNodeDefs(defs) {
+ globalDefs = defs;
+ },
+ nodeCreated(node) {
+ if (GroupNodeHandler.isGroupNode(node)) {
+ node[GROUP] = new GroupNodeHandler(node);
+ }
+ },
+ async refreshComboInNodes(defs) {
+ Object.assign(globalDefs, defs);
+ const nodes = app.graph.extra?.groupNodes;
+ if (nodes) {
+ await GroupNodeConfig.registerFromWorkflow(nodes, {});
+ }
+ }
+};
+app.registerExtension(ext$1);
+window.comfyAPI = window.comfyAPI || {};
+window.comfyAPI.groupNode = window.comfyAPI.groupNode || {};
+window.comfyAPI.groupNode.GroupNodeConfig = GroupNodeConfig;
+window.comfyAPI.groupNode.GroupNodeHandler = GroupNodeHandler;
+function setNodeMode(node, mode) {
+ node.mode = mode;
+ node.graph.change();
+}
+__name(setNodeMode, "setNodeMode");
+function addNodesToGroup(group, nodes = []) {
+ var x1, y1, x2, y2;
+ var nx1, ny1, nx2, ny2;
+ var node;
+ x1 = y1 = x2 = y2 = -1;
+ nx1 = ny1 = nx2 = ny2 = -1;
+ for (var n of [group.nodes, nodes]) {
+ for (var i in n) {
+ node = n[i];
+ nx1 = node.pos[0];
+ ny1 = node.pos[1];
+ nx2 = node.pos[0] + node.size[0];
+ ny2 = node.pos[1] + node.size[1];
+ if (node.type != "Reroute") {
+ ny1 -= LiteGraph.NODE_TITLE_HEIGHT;
+ }
+ if (node.flags?.collapsed) {
+ ny2 = ny1 + LiteGraph.NODE_TITLE_HEIGHT;
+ if (node?._collapsed_width) {
+ nx2 = nx1 + Math.round(node._collapsed_width);
+ }
+ }
+ if (x1 == -1 || nx1 < x1) {
+ x1 = nx1;
+ }
+ if (y1 == -1 || ny1 < y1) {
+ y1 = ny1;
+ }
+ if (x2 == -1 || nx2 > x2) {
+ x2 = nx2;
+ }
+ if (y2 == -1 || ny2 > y2) {
+ y2 = ny2;
+ }
+ }
+ }
+ var padding = 10;
+ y1 = y1 - Math.round(group.font_size * 1.4);
+ group.pos = [x1 - padding, y1 - padding];
+ group.size = [x2 - x1 + padding * 2, y2 - y1 + padding * 2];
+}
+__name(addNodesToGroup, "addNodesToGroup");
+app.registerExtension({
+ name: "Comfy.GroupOptions",
+ setup() {
+ const orig = LGraphCanvas.prototype.getCanvasMenuOptions;
+ LGraphCanvas.prototype.getCanvasMenuOptions = function() {
+ const options = orig.apply(this, arguments);
+ const group = this.graph.getGroupOnPos(
+ this.graph_mouse[0],
+ this.graph_mouse[1]
+ );
+ if (!group) {
+ options.push({
+ content: "Add Group For Selected Nodes",
+ disabled: !Object.keys(app.canvas.selected_nodes || {}).length,
+ callback: /* @__PURE__ */ __name(() => {
+ const group2 = new LGraphGroup();
+ addNodesToGroup(group2, this.selected_nodes);
+ app.canvas.graph.add(group2);
+ this.graph.change();
+ }, "callback")
+ });
+ return options;
+ }
+ group.recomputeInsideNodes();
+ const nodesInGroup = group.nodes;
+ options.push({
+ content: "Add Selected Nodes To Group",
+ disabled: !Object.keys(app.canvas.selected_nodes || {}).length,
+ callback: /* @__PURE__ */ __name(() => {
+ addNodesToGroup(group, this.selected_nodes);
+ this.graph.change();
+ }, "callback")
+ });
+ if (nodesInGroup.length === 0) {
+ return options;
+ } else {
+ options.push(null);
+ }
+ let allNodesAreSameMode = true;
+ for (let i = 1; i < nodesInGroup.length; i++) {
+ if (nodesInGroup[i].mode !== nodesInGroup[0].mode) {
+ allNodesAreSameMode = false;
+ break;
+ }
+ }
+ options.push({
+ content: "Fit Group To Nodes",
+ callback: /* @__PURE__ */ __name(() => {
+ addNodesToGroup(group);
+ this.graph.change();
+ }, "callback")
+ });
+ options.push({
+ content: "Select Nodes",
+ callback: /* @__PURE__ */ __name(() => {
+ this.selectNodes(nodesInGroup);
+ this.graph.change();
+ this.canvas.focus();
+ }, "callback")
+ });
+ if (allNodesAreSameMode) {
+ const mode = nodesInGroup[0].mode;
+ switch (mode) {
+ case 0:
+ options.push({
+ content: "Set Group Nodes to Never",
+ callback: /* @__PURE__ */ __name(() => {
+ for (const node of nodesInGroup) {
+ setNodeMode(node, 2);
+ }
+ }, "callback")
+ });
+ options.push({
+ content: "Bypass Group Nodes",
+ callback: /* @__PURE__ */ __name(() => {
+ for (const node of nodesInGroup) {
+ setNodeMode(node, 4);
+ }
+ }, "callback")
+ });
+ break;
+ case 2:
+ options.push({
+ content: "Set Group Nodes to Always",
+ callback: /* @__PURE__ */ __name(() => {
+ for (const node of nodesInGroup) {
+ setNodeMode(node, 0);
+ }
+ }, "callback")
+ });
+ options.push({
+ content: "Bypass Group Nodes",
+ callback: /* @__PURE__ */ __name(() => {
+ for (const node of nodesInGroup) {
+ setNodeMode(node, 4);
+ }
+ }, "callback")
+ });
+ break;
+ case 4:
+ options.push({
+ content: "Set Group Nodes to Always",
+ callback: /* @__PURE__ */ __name(() => {
+ for (const node of nodesInGroup) {
+ setNodeMode(node, 0);
+ }
+ }, "callback")
+ });
+ options.push({
+ content: "Set Group Nodes to Never",
+ callback: /* @__PURE__ */ __name(() => {
+ for (const node of nodesInGroup) {
+ setNodeMode(node, 2);
+ }
+ }, "callback")
+ });
+ break;
+ default:
+ options.push({
+ content: "Set Group Nodes to Always",
+ callback: /* @__PURE__ */ __name(() => {
+ for (const node of nodesInGroup) {
+ setNodeMode(node, 0);
+ }
+ }, "callback")
+ });
+ options.push({
+ content: "Set Group Nodes to Never",
+ callback: /* @__PURE__ */ __name(() => {
+ for (const node of nodesInGroup) {
+ setNodeMode(node, 2);
+ }
+ }, "callback")
+ });
+ options.push({
+ content: "Bypass Group Nodes",
+ callback: /* @__PURE__ */ __name(() => {
+ for (const node of nodesInGroup) {
+ setNodeMode(node, 4);
+ }
+ }, "callback")
+ });
+ break;
+ }
+ } else {
+ options.push({
+ content: "Set Group Nodes to Always",
+ callback: /* @__PURE__ */ __name(() => {
+ for (const node of nodesInGroup) {
+ setNodeMode(node, 0);
+ }
+ }, "callback")
+ });
+ options.push({
+ content: "Set Group Nodes to Never",
+ callback: /* @__PURE__ */ __name(() => {
+ for (const node of nodesInGroup) {
+ setNodeMode(node, 2);
+ }
+ }, "callback")
+ });
+ options.push({
+ content: "Bypass Group Nodes",
+ callback: /* @__PURE__ */ __name(() => {
+ for (const node of nodesInGroup) {
+ setNodeMode(node, 4);
+ }
+ }, "callback")
+ });
+ }
+ return options;
+ };
+ }
+});
+const id$2 = "Comfy.InvertMenuScrolling";
+app.registerExtension({
+ name: id$2,
+ init() {
+ const ctxMenu = LiteGraph.ContextMenu;
+ const replace = /* @__PURE__ */ __name(() => {
+ LiteGraph.ContextMenu = function(values, options) {
+ options = options || {};
+ if (options.scroll_speed) {
+ options.scroll_speed *= -1;
+ } else {
+ options.scroll_speed = -0.1;
+ }
+ return ctxMenu.call(this, values, options);
+ };
+ LiteGraph.ContextMenu.prototype = ctxMenu.prototype;
+ }, "replace");
+ app.ui.settings.addSetting({
+ id: id$2,
+ category: ["Comfy", "Graph", "InvertMenuScrolling"],
+ name: "Invert Context Menu Scrolling",
+ type: "boolean",
+ defaultValue: false,
+ onChange(value) {
+ if (value) {
+ replace();
+ } else {
+ LiteGraph.ContextMenu = ctxMenu;
+ }
+ }
+ });
+ }
+});
+app.registerExtension({
+ name: "Comfy.Keybinds",
+ init() {
+ const keybindListener = /* @__PURE__ */ __name(async function(event) {
+ const modifierPressed = event.ctrlKey || event.metaKey;
+ if (modifierPressed && event.key === "Enter") {
+ if (event.altKey) {
+ await api.interrupt();
+ useToastStore().add({
+ severity: "info",
+ summary: "Interrupted",
+ detail: "Execution has been interrupted",
+ life: 1e3
+ });
+ return;
+ }
+ app.queuePrompt(event.shiftKey ? -1 : 0).then();
+ return;
+ }
+ const target = event.composedPath()[0];
+ if (target.tagName === "TEXTAREA" || target.tagName === "INPUT" || target.tagName === "SPAN" && target.classList.contains("property_value")) {
+ return;
+ }
+ const modifierKeyIdMap = {
+ s: "#comfy-save-button",
+ o: "#comfy-file-input",
+ Backspace: "#comfy-clear-button",
+ d: "#comfy-load-default-button",
+ g: "#comfy-group-selected-nodes-button"
+ };
+ const modifierKeybindId = modifierKeyIdMap[event.key];
+ if (modifierPressed && modifierKeybindId) {
+ event.preventDefault();
+ const elem = document.querySelector(modifierKeybindId);
+ elem.click();
+ return;
+ }
+ if (event.ctrlKey || event.altKey || event.metaKey) {
+ return;
+ }
+ if (event.key === "Escape") {
+ const modals = document.querySelectorAll(".comfy-modal");
+ const modal = Array.from(modals).find(
+ (modal2) => window.getComputedStyle(modal2).getPropertyValue("display") !== "none"
+ );
+ if (modal) {
+ modal.style.display = "none";
+ }
+ ;
+ [...document.querySelectorAll("dialog")].forEach((d) => {
+ d.close();
+ });
+ }
+ const keyIdMap = {
+ q: ".queue-tab-button.side-bar-button",
+ h: ".queue-tab-button.side-bar-button",
+ r: "#comfy-refresh-button"
+ };
+ const buttonId = keyIdMap[event.key];
+ if (buttonId) {
+ const button = document.querySelector(buttonId);
+ button.click();
+ }
+ }, "keybindListener");
+ window.addEventListener("keydown", keybindListener, true);
+ }
+});
+const id$1 = "Comfy.LinkRenderMode";
+const ext = {
+ name: id$1,
+ async setup(app2) {
+ app2.ui.settings.addSetting({
+ id: id$1,
+ category: ["Comfy", "Graph", "LinkRenderMode"],
+ name: "Link Render Mode",
+ defaultValue: 2,
+ type: "combo",
+ // @ts-expect-error
+ options: [...LiteGraph.LINK_RENDER_MODES, "Hidden"].map((m, i) => ({
+ value: i,
+ text: m,
+ selected: i == app2.canvas.links_render_mode
+ })),
+ onChange(value) {
+ app2.canvas.links_render_mode = +value;
+ app2.graph.setDirtyCanvas(true);
+ }
+ });
+ }
+};
+app.registerExtension(ext);
+function dataURLToBlob(dataURL) {
+ const parts = dataURL.split(";base64,");
+ const contentType = parts[0].split(":")[1];
+ const byteString = atob(parts[1]);
+ const arrayBuffer = new ArrayBuffer(byteString.length);
+ const uint8Array = new Uint8Array(arrayBuffer);
+ for (let i = 0; i < byteString.length; i++) {
+ uint8Array[i] = byteString.charCodeAt(i);
+ }
+ return new Blob([arrayBuffer], { type: contentType });
+}
+__name(dataURLToBlob, "dataURLToBlob");
+function loadedImageToBlob(image) {
+ const canvas = document.createElement("canvas");
+ canvas.width = image.width;
+ canvas.height = image.height;
+ const ctx = canvas.getContext("2d");
+ ctx.drawImage(image, 0, 0);
+ const dataURL = canvas.toDataURL("image/png", 1);
+ const blob = dataURLToBlob(dataURL);
+ return blob;
+}
+__name(loadedImageToBlob, "loadedImageToBlob");
+function loadImage(imagePath) {
+ return new Promise((resolve, reject) => {
+ const image = new Image();
+ image.onload = function() {
+ resolve(image);
+ };
+ image.src = imagePath;
+ });
+}
+__name(loadImage, "loadImage");
+async function uploadMask(filepath, formData) {
+ await api.fetchApi("/upload/mask", {
+ method: "POST",
+ body: formData
+ }).then((response) => {
+ }).catch((error) => {
+ console.error("Error:", error);
+ });
+ ComfyApp.clipspace.imgs[ComfyApp.clipspace["selectedIndex"]] = new Image();
+ ComfyApp.clipspace.imgs[ComfyApp.clipspace["selectedIndex"]].src = api.apiURL(
+ "/view?" + new URLSearchParams(filepath).toString() + app.getPreviewFormatParam() + app.getRandParam()
+ );
+ if (ComfyApp.clipspace.images)
+ ComfyApp.clipspace.images[ComfyApp.clipspace["selectedIndex"]] = filepath;
+ ClipspaceDialog.invalidatePreview();
+}
+__name(uploadMask, "uploadMask");
+function prepare_mask(image, maskCanvas, maskCtx, maskColor) {
+ maskCtx.drawImage(image, 0, 0, maskCanvas.width, maskCanvas.height);
+ const maskData = maskCtx.getImageData(
+ 0,
+ 0,
+ maskCanvas.width,
+ maskCanvas.height
+ );
+ for (let i = 0; i < maskData.data.length; i += 4) {
+ if (maskData.data[i + 3] == 255) maskData.data[i + 3] = 0;
+ else maskData.data[i + 3] = 255;
+ maskData.data[i] = maskColor.r;
+ maskData.data[i + 1] = maskColor.g;
+ maskData.data[i + 2] = maskColor.b;
+ }
+ maskCtx.globalCompositeOperation = "source-over";
+ maskCtx.putImageData(maskData, 0, 0);
+}
+__name(prepare_mask, "prepare_mask");
+var PointerType = /* @__PURE__ */ ((PointerType2) => {
+ PointerType2["Arc"] = "arc";
+ PointerType2["Rect"] = "rect";
+ return PointerType2;
+})(PointerType || {});
+var CompositionOperation = /* @__PURE__ */ ((CompositionOperation2) => {
+ CompositionOperation2["SourceOver"] = "source-over";
+ CompositionOperation2["DestinationOut"] = "destination-out";
+ return CompositionOperation2;
+})(CompositionOperation || {});
+class MaskEditorDialog extends ComfyDialog {
+ static {
+ __name(this, "MaskEditorDialog");
+ }
+ static instance = null;
+ static mousedown_x = null;
+ static mousedown_y = null;
+ brush;
+ maskCtx;
+ maskCanvas;
+ brush_size_slider;
+ brush_opacity_slider;
+ colorButton;
+ saveButton;
+ zoom_ratio;
+ pan_x;
+ pan_y;
+ imgCanvas;
+ last_display_style;
+ is_visible;
+ image;
+ handler_registered;
+ brush_slider_input;
+ cursorX;
+ cursorY;
+ mousedown_pan_x;
+ mousedown_pan_y;
+ last_pressure;
+ pointer_type;
+ brush_pointer_type_select;
+ static getInstance() {
+ if (!MaskEditorDialog.instance) {
+ MaskEditorDialog.instance = new MaskEditorDialog();
+ }
+ return MaskEditorDialog.instance;
+ }
+ is_layout_created = false;
+ constructor() {
+ super();
+ this.element = $el("div.comfy-modal", { parent: document.body }, [
+ $el("div.comfy-modal-content", [...this.createButtons()])
+ ]);
+ }
+ createButtons() {
+ return [];
+ }
+ createButton(name, callback) {
+ var button = document.createElement("button");
+ button.style.pointerEvents = "auto";
+ button.innerText = name;
+ button.addEventListener("click", callback);
+ return button;
+ }
+ createLeftButton(name, callback) {
+ var button = this.createButton(name, callback);
+ button.style.cssFloat = "left";
+ button.style.marginRight = "4px";
+ return button;
+ }
+ createRightButton(name, callback) {
+ var button = this.createButton(name, callback);
+ button.style.cssFloat = "right";
+ button.style.marginLeft = "4px";
+ return button;
+ }
+ createLeftSlider(self, name, callback) {
+ const divElement = document.createElement("div");
+ divElement.id = "maskeditor-slider";
+ divElement.style.cssFloat = "left";
+ divElement.style.fontFamily = "sans-serif";
+ divElement.style.marginRight = "4px";
+ divElement.style.color = "var(--input-text)";
+ divElement.style.backgroundColor = "var(--comfy-input-bg)";
+ divElement.style.borderRadius = "8px";
+ divElement.style.borderColor = "var(--border-color)";
+ divElement.style.borderStyle = "solid";
+ divElement.style.fontSize = "15px";
+ divElement.style.height = "25px";
+ divElement.style.padding = "1px 6px";
+ divElement.style.display = "flex";
+ divElement.style.position = "relative";
+ divElement.style.top = "2px";
+ divElement.style.pointerEvents = "auto";
+ self.brush_slider_input = document.createElement("input");
+ self.brush_slider_input.setAttribute("type", "range");
+ self.brush_slider_input.setAttribute("min", "1");
+ self.brush_slider_input.setAttribute("max", "100");
+ self.brush_slider_input.setAttribute("value", "10");
+ const labelElement = document.createElement("label");
+ labelElement.textContent = name;
+ divElement.appendChild(labelElement);
+ divElement.appendChild(self.brush_slider_input);
+ self.brush_slider_input.addEventListener("change", callback);
+ return divElement;
+ }
+ createOpacitySlider(self, name, callback) {
+ const divElement = document.createElement("div");
+ divElement.id = "maskeditor-opacity-slider";
+ divElement.style.cssFloat = "left";
+ divElement.style.fontFamily = "sans-serif";
+ divElement.style.marginRight = "4px";
+ divElement.style.color = "var(--input-text)";
+ divElement.style.backgroundColor = "var(--comfy-input-bg)";
+ divElement.style.borderRadius = "8px";
+ divElement.style.borderColor = "var(--border-color)";
+ divElement.style.borderStyle = "solid";
+ divElement.style.fontSize = "15px";
+ divElement.style.height = "25px";
+ divElement.style.padding = "1px 6px";
+ divElement.style.display = "flex";
+ divElement.style.position = "relative";
+ divElement.style.top = "2px";
+ divElement.style.pointerEvents = "auto";
+ self.opacity_slider_input = document.createElement("input");
+ self.opacity_slider_input.setAttribute("type", "range");
+ self.opacity_slider_input.setAttribute("min", "0.1");
+ self.opacity_slider_input.setAttribute("max", "1.0");
+ self.opacity_slider_input.setAttribute("step", "0.01");
+ self.opacity_slider_input.setAttribute("value", "0.7");
+ const labelElement = document.createElement("label");
+ labelElement.textContent = name;
+ divElement.appendChild(labelElement);
+ divElement.appendChild(self.opacity_slider_input);
+ self.opacity_slider_input.addEventListener("input", callback);
+ return divElement;
+ }
+ createPointerTypeSelect(self) {
+ const divElement = document.createElement("div");
+ divElement.id = "maskeditor-pointer-type";
+ divElement.style.cssFloat = "left";
+ divElement.style.fontFamily = "sans-serif";
+ divElement.style.marginRight = "4px";
+ divElement.style.color = "var(--input-text)";
+ divElement.style.backgroundColor = "var(--comfy-input-bg)";
+ divElement.style.borderRadius = "8px";
+ divElement.style.borderColor = "var(--border-color)";
+ divElement.style.borderStyle = "solid";
+ divElement.style.fontSize = "15px";
+ divElement.style.height = "25px";
+ divElement.style.padding = "1px 6px";
+ divElement.style.display = "flex";
+ divElement.style.position = "relative";
+ divElement.style.top = "2px";
+ divElement.style.pointerEvents = "auto";
+ const labelElement = document.createElement("label");
+ labelElement.textContent = "Pointer Type:";
+ const selectElement = document.createElement("select");
+ selectElement.style.borderRadius = "0";
+ selectElement.style.borderColor = "transparent";
+ selectElement.style.borderStyle = "unset";
+ selectElement.style.fontSize = "0.9em";
+ const optionArc = document.createElement("option");
+ optionArc.value = "arc";
+ optionArc.text = "Circle";
+ optionArc.selected = true;
+ const optionRect = document.createElement("option");
+ optionRect.value = "rect";
+ optionRect.text = "Square";
+ selectElement.appendChild(optionArc);
+ selectElement.appendChild(optionRect);
+ selectElement.addEventListener("change", (event) => {
+ const target = event.target;
+ self.pointer_type = target.value;
+ this.setBrushBorderRadius(self);
+ });
+ divElement.appendChild(labelElement);
+ divElement.appendChild(selectElement);
+ return divElement;
+ }
+ setBrushBorderRadius(self) {
+ if (self.pointer_type === "rect") {
+ this.brush.style.borderRadius = "0%";
+ this.brush.style.MozBorderRadius = "0%";
+ this.brush.style.WebkitBorderRadius = "0%";
+ } else {
+ this.brush.style.borderRadius = "50%";
+ this.brush.style.MozBorderRadius = "50%";
+ this.brush.style.WebkitBorderRadius = "50%";
+ }
+ }
+ setlayout(imgCanvas, maskCanvas) {
+ const self = this;
+ self.pointer_type = "arc";
+ var bottom_panel = document.createElement("div");
+ bottom_panel.style.position = "absolute";
+ bottom_panel.style.bottom = "0px";
+ bottom_panel.style.left = "20px";
+ bottom_panel.style.right = "20px";
+ bottom_panel.style.height = "50px";
+ bottom_panel.style.pointerEvents = "none";
+ var brush = document.createElement("div");
+ brush.id = "brush";
+ brush.style.backgroundColor = "transparent";
+ brush.style.outline = "1px dashed black";
+ brush.style.boxShadow = "0 0 0 1px white";
+ brush.style.position = "absolute";
+ brush.style.zIndex = "8889";
+ brush.style.pointerEvents = "none";
+ this.brush = brush;
+ this.setBrushBorderRadius(self);
+ this.element.appendChild(imgCanvas);
+ this.element.appendChild(maskCanvas);
+ this.element.appendChild(bottom_panel);
+ document.body.appendChild(brush);
+ var clearButton = this.createLeftButton("Clear", () => {
+ self.maskCtx.clearRect(
+ 0,
+ 0,
+ self.maskCanvas.width,
+ self.maskCanvas.height
+ );
+ });
+ this.brush_size_slider = this.createLeftSlider(
+ self,
+ "Thickness",
+ (event) => {
+ self.brush_size = event.target.value;
+ self.updateBrushPreview(self);
+ }
+ );
+ this.brush_opacity_slider = this.createOpacitySlider(
+ self,
+ "Opacity",
+ (event) => {
+ self.brush_opacity = event.target.value;
+ if (self.brush_color_mode !== "negative") {
+ self.maskCanvas.style.opacity = self.brush_opacity.toString();
+ }
+ }
+ );
+ this.brush_pointer_type_select = this.createPointerTypeSelect(self);
+ this.colorButton = this.createLeftButton(this.getColorButtonText(), () => {
+ if (self.brush_color_mode === "black") {
+ self.brush_color_mode = "white";
+ } else if (self.brush_color_mode === "white") {
+ self.brush_color_mode = "negative";
+ } else {
+ self.brush_color_mode = "black";
+ }
+ self.updateWhenBrushColorModeChanged();
+ });
+ var cancelButton = this.createRightButton("Cancel", () => {
+ document.removeEventListener("keydown", MaskEditorDialog.handleKeyDown);
+ self.close();
+ });
+ this.saveButton = this.createRightButton("Save", () => {
+ document.removeEventListener("keydown", MaskEditorDialog.handleKeyDown);
+ self.save();
+ });
+ this.element.appendChild(imgCanvas);
+ this.element.appendChild(maskCanvas);
+ this.element.appendChild(bottom_panel);
+ bottom_panel.appendChild(clearButton);
+ bottom_panel.appendChild(this.saveButton);
+ bottom_panel.appendChild(cancelButton);
+ bottom_panel.appendChild(this.brush_size_slider);
+ bottom_panel.appendChild(this.brush_opacity_slider);
+ bottom_panel.appendChild(this.brush_pointer_type_select);
+ bottom_panel.appendChild(this.colorButton);
+ imgCanvas.style.position = "absolute";
+ maskCanvas.style.position = "absolute";
+ imgCanvas.style.top = "200";
+ imgCanvas.style.left = "0";
+ maskCanvas.style.top = imgCanvas.style.top;
+ maskCanvas.style.left = imgCanvas.style.left;
+ const maskCanvasStyle = this.getMaskCanvasStyle();
+ maskCanvas.style.mixBlendMode = maskCanvasStyle.mixBlendMode;
+ maskCanvas.style.opacity = maskCanvasStyle.opacity.toString();
+ }
+ async show() {
+ this.zoom_ratio = 1;
+ this.pan_x = 0;
+ this.pan_y = 0;
+ if (!this.is_layout_created) {
+ const imgCanvas = document.createElement("canvas");
+ const maskCanvas = document.createElement("canvas");
+ imgCanvas.id = "imageCanvas";
+ maskCanvas.id = "maskCanvas";
+ this.setlayout(imgCanvas, maskCanvas);
+ this.imgCanvas = imgCanvas;
+ this.maskCanvas = maskCanvas;
+ this.maskCtx = maskCanvas.getContext("2d", { willReadFrequently: true });
+ this.setEventHandler(maskCanvas);
+ this.is_layout_created = true;
+ const self = this;
+ const observer = new MutationObserver(function(mutations) {
+ mutations.forEach(function(mutation) {
+ if (mutation.type === "attributes" && mutation.attributeName === "style") {
+ if (self.last_display_style && self.last_display_style != "none" && self.element.style.display == "none") {
+ self.brush.style.display = "none";
+ ComfyApp.onClipspaceEditorClosed();
+ }
+ self.last_display_style = self.element.style.display;
+ }
+ });
+ });
+ const config = { attributes: true };
+ observer.observe(this.element, config);
+ }
+ document.addEventListener("keydown", MaskEditorDialog.handleKeyDown);
+ if (ComfyApp.clipspace_return_node) {
+ this.saveButton.innerText = "Save to node";
+ } else {
+ this.saveButton.innerText = "Save";
+ }
+ this.saveButton.disabled = false;
+ this.element.style.display = "block";
+ this.element.style.width = "85%";
+ this.element.style.margin = "0 7.5%";
+ this.element.style.height = "100vh";
+ this.element.style.top = "50%";
+ this.element.style.left = "42%";
+ this.element.style.zIndex = "8888";
+ await this.setImages(this.imgCanvas);
+ this.is_visible = true;
+ }
+ isOpened() {
+ return this.element.style.display == "block";
+ }
+ invalidateCanvas(orig_image, mask_image) {
+ this.imgCanvas.width = orig_image.width;
+ this.imgCanvas.height = orig_image.height;
+ this.maskCanvas.width = orig_image.width;
+ this.maskCanvas.height = orig_image.height;
+ let imgCtx = this.imgCanvas.getContext("2d", { willReadFrequently: true });
+ let maskCtx = this.maskCanvas.getContext("2d", {
+ willReadFrequently: true
+ });
+ imgCtx.drawImage(orig_image, 0, 0, orig_image.width, orig_image.height);
+ prepare_mask(mask_image, this.maskCanvas, maskCtx, this.getMaskColor());
+ }
+ async setImages(imgCanvas) {
+ let self = this;
+ const imgCtx = imgCanvas.getContext("2d", { willReadFrequently: true });
+ const maskCtx = this.maskCtx;
+ const maskCanvas = this.maskCanvas;
+ imgCtx.clearRect(0, 0, this.imgCanvas.width, this.imgCanvas.height);
+ maskCtx.clearRect(0, 0, this.maskCanvas.width, this.maskCanvas.height);
+ const filepath = ComfyApp.clipspace.images;
+ const alpha_url = new URL(
+ ComfyApp.clipspace.imgs[ComfyApp.clipspace["selectedIndex"]].src
+ );
+ alpha_url.searchParams.delete("channel");
+ alpha_url.searchParams.delete("preview");
+ alpha_url.searchParams.set("channel", "a");
+ let mask_image = await loadImage(alpha_url);
+ const rgb_url = new URL(
+ ComfyApp.clipspace.imgs[ComfyApp.clipspace["selectedIndex"]].src
+ );
+ rgb_url.searchParams.delete("channel");
+ rgb_url.searchParams.set("channel", "rgb");
+ this.image = new Image();
+ this.image.onload = function() {
+ maskCanvas.width = self.image.width;
+ maskCanvas.height = self.image.height;
+ self.invalidateCanvas(self.image, mask_image);
+ self.initializeCanvasPanZoom();
+ };
+ this.image.src = rgb_url.toString();
+ }
+ initializeCanvasPanZoom() {
+ let drawWidth = this.image.width;
+ let drawHeight = this.image.height;
+ let width = this.element.clientWidth;
+ let height = this.element.clientHeight;
+ if (this.image.width > width) {
+ drawWidth = width;
+ drawHeight = drawWidth / this.image.width * this.image.height;
+ }
+ if (drawHeight > height) {
+ drawHeight = height;
+ drawWidth = drawHeight / this.image.height * this.image.width;
+ }
+ this.zoom_ratio = drawWidth / this.image.width;
+ const canvasX = (width - drawWidth) / 2;
+ const canvasY = (height - drawHeight) / 2;
+ this.pan_x = canvasX;
+ this.pan_y = canvasY;
+ this.invalidatePanZoom();
+ }
+ invalidatePanZoom() {
+ let raw_width = this.image.width * this.zoom_ratio;
+ let raw_height = this.image.height * this.zoom_ratio;
+ if (this.pan_x + raw_width < 10) {
+ this.pan_x = 10 - raw_width;
+ }
+ if (this.pan_y + raw_height < 10) {
+ this.pan_y = 10 - raw_height;
+ }
+ let width = `${raw_width}px`;
+ let height = `${raw_height}px`;
+ let left = `${this.pan_x}px`;
+ let top = `${this.pan_y}px`;
+ this.maskCanvas.style.width = width;
+ this.maskCanvas.style.height = height;
+ this.maskCanvas.style.left = left;
+ this.maskCanvas.style.top = top;
+ this.imgCanvas.style.width = width;
+ this.imgCanvas.style.height = height;
+ this.imgCanvas.style.left = left;
+ this.imgCanvas.style.top = top;
+ }
+ setEventHandler(maskCanvas) {
+ const self = this;
+ if (!this.handler_registered) {
+ maskCanvas.addEventListener("contextmenu", (event) => {
+ event.preventDefault();
+ });
+ this.element.addEventListener(
+ "wheel",
+ (event) => this.handleWheelEvent(self, event)
+ );
+ this.element.addEventListener(
+ "pointermove",
+ (event) => this.pointMoveEvent(self, event)
+ );
+ this.element.addEventListener(
+ "touchmove",
+ (event) => this.pointMoveEvent(self, event)
+ );
+ this.element.addEventListener("dragstart", (event) => {
+ if (event.ctrlKey) {
+ event.preventDefault();
+ }
+ });
+ maskCanvas.addEventListener(
+ "pointerdown",
+ (event) => this.handlePointerDown(self, event)
+ );
+ maskCanvas.addEventListener(
+ "pointermove",
+ (event) => this.draw_move(self, event)
+ );
+ maskCanvas.addEventListener(
+ "touchmove",
+ (event) => this.draw_move(self, event)
+ );
+ maskCanvas.addEventListener("pointerover", (event) => {
+ this.brush.style.display = "block";
+ });
+ maskCanvas.addEventListener("pointerleave", (event) => {
+ this.brush.style.display = "none";
+ });
+ document.addEventListener("pointerup", MaskEditorDialog.handlePointerUp);
+ this.handler_registered = true;
+ }
+ }
+ getMaskCanvasStyle() {
+ if (this.brush_color_mode === "negative") {
+ return {
+ mixBlendMode: "difference",
+ opacity: "1"
+ };
+ } else {
+ return {
+ mixBlendMode: "initial",
+ opacity: this.brush_opacity
+ };
+ }
+ }
+ getMaskColor() {
+ if (this.brush_color_mode === "black") {
+ return { r: 0, g: 0, b: 0 };
+ }
+ if (this.brush_color_mode === "white") {
+ return { r: 255, g: 255, b: 255 };
+ }
+ if (this.brush_color_mode === "negative") {
+ return { r: 255, g: 255, b: 255 };
+ }
+ return { r: 0, g: 0, b: 0 };
+ }
+ getMaskFillStyle() {
+ const maskColor = this.getMaskColor();
+ return "rgb(" + maskColor.r + "," + maskColor.g + "," + maskColor.b + ")";
+ }
+ getColorButtonText() {
+ let colorCaption = "unknown";
+ if (this.brush_color_mode === "black") {
+ colorCaption = "black";
+ } else if (this.brush_color_mode === "white") {
+ colorCaption = "white";
+ } else if (this.brush_color_mode === "negative") {
+ colorCaption = "negative";
+ }
+ return "Color: " + colorCaption;
+ }
+ updateWhenBrushColorModeChanged() {
+ this.colorButton.innerText = this.getColorButtonText();
+ const maskCanvasStyle = this.getMaskCanvasStyle();
+ this.maskCanvas.style.mixBlendMode = maskCanvasStyle.mixBlendMode;
+ this.maskCanvas.style.opacity = maskCanvasStyle.opacity.toString();
+ const maskColor = this.getMaskColor();
+ const maskData = this.maskCtx.getImageData(
+ 0,
+ 0,
+ this.maskCanvas.width,
+ this.maskCanvas.height
+ );
+ for (let i = 0; i < maskData.data.length; i += 4) {
+ maskData.data[i] = maskColor.r;
+ maskData.data[i + 1] = maskColor.g;
+ maskData.data[i + 2] = maskColor.b;
+ }
+ this.maskCtx.putImageData(maskData, 0, 0);
+ }
+ brush_opacity = 0.7;
+ brush_size = 10;
+ brush_color_mode = "black";
+ drawing_mode = false;
+ lastx = -1;
+ lasty = -1;
+ lasttime = 0;
+ static handleKeyDown(event) {
+ const self = MaskEditorDialog.instance;
+ if (event.key === "]") {
+ self.brush_size = Math.min(self.brush_size + 2, 100);
+ self.brush_slider_input.value = self.brush_size;
+ } else if (event.key === "[") {
+ self.brush_size = Math.max(self.brush_size - 2, 1);
+ self.brush_slider_input.value = self.brush_size;
+ } else if (event.key === "Enter") {
+ self.save();
+ }
+ self.updateBrushPreview(self);
+ }
+ static handlePointerUp(event) {
+ event.preventDefault();
+ this.mousedown_x = null;
+ this.mousedown_y = null;
+ MaskEditorDialog.instance.drawing_mode = false;
+ }
+ updateBrushPreview(self) {
+ const brush = self.brush;
+ var centerX = self.cursorX;
+ var centerY = self.cursorY;
+ brush.style.width = self.brush_size * 2 * this.zoom_ratio + "px";
+ brush.style.height = self.brush_size * 2 * this.zoom_ratio + "px";
+ brush.style.left = centerX - self.brush_size * this.zoom_ratio + "px";
+ brush.style.top = centerY - self.brush_size * this.zoom_ratio + "px";
+ }
+ handleWheelEvent(self, event) {
+ event.preventDefault();
+ if (event.ctrlKey) {
+ if (event.deltaY < 0) {
+ this.zoom_ratio = Math.min(10, this.zoom_ratio + 0.2);
+ } else {
+ this.zoom_ratio = Math.max(0.2, this.zoom_ratio - 0.2);
+ }
+ this.invalidatePanZoom();
+ } else {
+ if (event.deltaY < 0) this.brush_size = Math.min(this.brush_size + 2, 100);
+ else this.brush_size = Math.max(this.brush_size - 2, 1);
+ this.brush_slider_input.value = this.brush_size.toString();
+ this.updateBrushPreview(this);
+ }
+ }
+ pointMoveEvent(self, event) {
+ this.cursorX = event.pageX;
+ this.cursorY = event.pageY;
+ self.updateBrushPreview(self);
+ if (event.ctrlKey) {
+ event.preventDefault();
+ self.pan_move(self, event);
+ }
+ let left_button_down = window.TouchEvent && event instanceof TouchEvent || event.buttons == 1;
+ if (event.shiftKey && left_button_down) {
+ self.drawing_mode = false;
+ const y = event.clientY;
+ let delta = (self.zoom_lasty - y) * 5e-3;
+ self.zoom_ratio = Math.max(
+ Math.min(10, self.last_zoom_ratio - delta),
+ 0.2
+ );
+ this.invalidatePanZoom();
+ return;
+ }
+ }
+ pan_move(self, event) {
+ if (event.buttons == 1) {
+ if (MaskEditorDialog.mousedown_x) {
+ let deltaX = MaskEditorDialog.mousedown_x - event.clientX;
+ let deltaY = MaskEditorDialog.mousedown_y - event.clientY;
+ self.pan_x = this.mousedown_pan_x - deltaX;
+ self.pan_y = this.mousedown_pan_y - deltaY;
+ self.invalidatePanZoom();
+ }
+ }
+ }
+ draw_move(self, event) {
+ if (event.ctrlKey || event.shiftKey) {
+ return;
+ }
+ event.preventDefault();
+ this.cursorX = event.pageX;
+ this.cursorY = event.pageY;
+ self.updateBrushPreview(self);
+ let left_button_down = window.TouchEvent && event instanceof TouchEvent || event.buttons == 1;
+ let right_button_down = [2, 5, 32].includes(event.buttons);
+ if (!event.altKey && left_button_down) {
+ var diff = performance.now() - self.lasttime;
+ const maskRect = self.maskCanvas.getBoundingClientRect();
+ var x = event.offsetX;
+ var y = event.offsetY;
+ if (event.offsetX == null) {
+ x = event.targetTouches[0].clientX - maskRect.left;
+ }
+ if (event.offsetY == null) {
+ y = event.targetTouches[0].clientY - maskRect.top;
+ }
+ x /= self.zoom_ratio;
+ y /= self.zoom_ratio;
+ var brush_size = this.brush_size;
+ if (event instanceof PointerEvent && event.pointerType == "pen") {
+ brush_size *= event.pressure;
+ this.last_pressure = event.pressure;
+ } else if (window.TouchEvent && event instanceof TouchEvent && diff < 20) {
+ brush_size *= this.last_pressure;
+ } else {
+ brush_size = this.brush_size;
+ }
+ if (diff > 20 && !this.drawing_mode)
+ requestAnimationFrame(() => {
+ self.init_shape(
+ self,
+ "source-over"
+ /* SourceOver */
+ );
+ self.draw_shape(self, x, y, brush_size);
+ self.lastx = x;
+ self.lasty = y;
+ });
+ else
+ requestAnimationFrame(() => {
+ self.init_shape(
+ self,
+ "source-over"
+ /* SourceOver */
+ );
+ var dx = x - self.lastx;
+ var dy = y - self.lasty;
+ var distance = Math.sqrt(dx * dx + dy * dy);
+ var directionX = dx / distance;
+ var directionY = dy / distance;
+ for (var i = 0; i < distance; i += 5) {
+ var px = self.lastx + directionX * i;
+ var py = self.lasty + directionY * i;
+ self.draw_shape(self, px, py, brush_size);
+ }
+ self.lastx = x;
+ self.lasty = y;
+ });
+ self.lasttime = performance.now();
+ } else if (event.altKey && left_button_down || right_button_down) {
+ const maskRect = self.maskCanvas.getBoundingClientRect();
+ const x2 = (event.offsetX || event.targetTouches[0].clientX - maskRect.left) / self.zoom_ratio;
+ const y2 = (event.offsetY || event.targetTouches[0].clientY - maskRect.top) / self.zoom_ratio;
+ var brush_size = this.brush_size;
+ if (event instanceof PointerEvent && event.pointerType == "pen") {
+ brush_size *= event.pressure;
+ this.last_pressure = event.pressure;
+ } else if (window.TouchEvent && event instanceof TouchEvent && diff < 20) {
+ brush_size *= this.last_pressure;
+ } else {
+ brush_size = this.brush_size;
+ }
+ if (diff > 20 && !this.drawing_mode)
+ requestAnimationFrame(() => {
+ self.init_shape(
+ self,
+ "destination-out"
+ /* DestinationOut */
+ );
+ self.draw_shape(self, x2, y2, brush_size);
+ self.lastx = x2;
+ self.lasty = y2;
+ });
+ else
+ requestAnimationFrame(() => {
+ self.init_shape(
+ self,
+ "destination-out"
+ /* DestinationOut */
+ );
+ var dx = x2 - self.lastx;
+ var dy = y2 - self.lasty;
+ var distance = Math.sqrt(dx * dx + dy * dy);
+ var directionX = dx / distance;
+ var directionY = dy / distance;
+ for (var i = 0; i < distance; i += 5) {
+ var px = self.lastx + directionX * i;
+ var py = self.lasty + directionY * i;
+ self.draw_shape(self, px, py, brush_size);
+ }
+ self.lastx = x2;
+ self.lasty = y2;
+ });
+ self.lasttime = performance.now();
+ }
+ }
+ handlePointerDown(self, event) {
+ if (event.ctrlKey) {
+ if (event.buttons == 1) {
+ MaskEditorDialog.mousedown_x = event.clientX;
+ MaskEditorDialog.mousedown_y = event.clientY;
+ this.mousedown_pan_x = this.pan_x;
+ this.mousedown_pan_y = this.pan_y;
+ }
+ return;
+ }
+ var brush_size = this.brush_size;
+ if (event instanceof PointerEvent && event.pointerType == "pen") {
+ brush_size *= event.pressure;
+ this.last_pressure = event.pressure;
+ }
+ if ([0, 2, 5].includes(event.button)) {
+ self.drawing_mode = true;
+ event.preventDefault();
+ if (event.shiftKey) {
+ self.zoom_lasty = event.clientY;
+ self.last_zoom_ratio = self.zoom_ratio;
+ return;
+ }
+ const maskRect = self.maskCanvas.getBoundingClientRect();
+ const x = (event.offsetX || event.targetTouches[0].clientX - maskRect.left) / self.zoom_ratio;
+ const y = (event.offsetY || event.targetTouches[0].clientY - maskRect.top) / self.zoom_ratio;
+ if (!event.altKey && event.button == 0) {
+ self.init_shape(
+ self,
+ "source-over"
+ /* SourceOver */
+ );
+ } else {
+ self.init_shape(
+ self,
+ "destination-out"
+ /* DestinationOut */
+ );
+ }
+ self.draw_shape(self, x, y, brush_size);
+ self.lastx = x;
+ self.lasty = y;
+ self.lasttime = performance.now();
+ }
+ }
+ init_shape(self, compositionOperation) {
+ self.maskCtx.beginPath();
+ if (compositionOperation == "source-over") {
+ self.maskCtx.fillStyle = this.getMaskFillStyle();
+ self.maskCtx.globalCompositeOperation = "source-over";
+ } else if (compositionOperation == "destination-out") {
+ self.maskCtx.globalCompositeOperation = "destination-out";
+ }
+ }
+ draw_shape(self, x, y, brush_size) {
+ if (self.pointer_type === "rect") {
+ self.maskCtx.rect(
+ x - brush_size,
+ y - brush_size,
+ brush_size * 2,
+ brush_size * 2
+ );
+ } else {
+ self.maskCtx.arc(x, y, brush_size, 0, Math.PI * 2, false);
+ }
+ self.maskCtx.fill();
+ }
+ async save() {
+ const backupCanvas = document.createElement("canvas");
+ const backupCtx = backupCanvas.getContext("2d", {
+ willReadFrequently: true
+ });
+ backupCanvas.width = this.image.width;
+ backupCanvas.height = this.image.height;
+ backupCtx.clearRect(0, 0, backupCanvas.width, backupCanvas.height);
+ backupCtx.drawImage(
+ this.maskCanvas,
+ 0,
+ 0,
+ this.maskCanvas.width,
+ this.maskCanvas.height,
+ 0,
+ 0,
+ backupCanvas.width,
+ backupCanvas.height
+ );
+ const backupData = backupCtx.getImageData(
+ 0,
+ 0,
+ backupCanvas.width,
+ backupCanvas.height
+ );
+ for (let i = 0; i < backupData.data.length; i += 4) {
+ if (backupData.data[i + 3] == 255) backupData.data[i + 3] = 0;
+ else backupData.data[i + 3] = 255;
+ backupData.data[i] = 0;
+ backupData.data[i + 1] = 0;
+ backupData.data[i + 2] = 0;
+ }
+ backupCtx.globalCompositeOperation = "source-over";
+ backupCtx.putImageData(backupData, 0, 0);
+ const formData = new FormData();
+ const filename = "clipspace-mask-" + performance.now() + ".png";
+ const item = {
+ filename,
+ subfolder: "clipspace",
+ type: "input"
+ };
+ if (ComfyApp.clipspace.images) ComfyApp.clipspace.images[0] = item;
+ if (ComfyApp.clipspace.widgets) {
+ const index = ComfyApp.clipspace.widgets.findIndex(
+ (obj) => obj.name === "image"
+ );
+ if (index >= 0) ComfyApp.clipspace.widgets[index].value = item;
+ }
+ const dataURL = backupCanvas.toDataURL();
+ const blob = dataURLToBlob(dataURL);
+ let original_url = new URL(this.image.src);
+ const original_ref = {
+ filename: original_url.searchParams.get("filename")
+ };
+ let original_subfolder = original_url.searchParams.get("subfolder");
+ if (original_subfolder) original_ref.subfolder = original_subfolder;
+ let original_type = original_url.searchParams.get("type");
+ if (original_type) original_ref.type = original_type;
+ formData.append("image", blob, filename);
+ formData.append("original_ref", JSON.stringify(original_ref));
+ formData.append("type", "input");
+ formData.append("subfolder", "clipspace");
+ this.saveButton.innerText = "Saving...";
+ this.saveButton.disabled = true;
+ await uploadMask(item, formData);
+ ComfyApp.onClipspaceEditorSave();
+ this.close();
+ }
+}
+app.registerExtension({
+ name: "Comfy.MaskEditor",
+ init(app2) {
+ ComfyApp.open_maskeditor = function() {
+ const dlg = MaskEditorDialog.getInstance();
+ if (!dlg.isOpened()) {
+ dlg.show();
+ }
+ };
+ const context_predicate = /* @__PURE__ */ __name(() => ComfyApp.clipspace && ComfyApp.clipspace.imgs && ComfyApp.clipspace.imgs.length > 0, "context_predicate");
+ ClipspaceDialog.registerButton(
+ "MaskEditor",
+ context_predicate,
+ ComfyApp.open_maskeditor
+ );
+ }
+});
+const id = "Comfy.NodeTemplates";
+const file = "comfy.templates.json";
+class ManageTemplates extends ComfyDialog {
+ static {
+ __name(this, "ManageTemplates");
+ }
+ templates;
+ draggedEl;
+ saveVisualCue;
+ emptyImg;
+ importInput;
+ constructor() {
+ super();
+ this.load().then((v) => {
+ this.templates = v;
+ });
+ this.element.classList.add("comfy-manage-templates");
+ this.draggedEl = null;
+ this.saveVisualCue = null;
+ this.emptyImg = new Image();
+ this.emptyImg.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs=";
+ this.importInput = $el("input", {
+ type: "file",
+ accept: ".json",
+ multiple: true,
+ style: { display: "none" },
+ parent: document.body,
+ onchange: /* @__PURE__ */ __name(() => this.importAll(), "onchange")
+ });
+ }
+ createButtons() {
+ const btns = super.createButtons();
+ btns[0].textContent = "Close";
+ btns[0].onclick = (e) => {
+ clearTimeout(this.saveVisualCue);
+ this.close();
+ };
+ btns.unshift(
+ $el("button", {
+ type: "button",
+ textContent: "Export",
+ onclick: /* @__PURE__ */ __name(() => this.exportAll(), "onclick")
+ })
+ );
+ btns.unshift(
+ $el("button", {
+ type: "button",
+ textContent: "Import",
+ onclick: /* @__PURE__ */ __name(() => {
+ this.importInput.click();
+ }, "onclick")
+ })
+ );
+ return btns;
+ }
+ async load() {
+ let templates = [];
+ if (app.storageLocation === "server") {
+ if (app.isNewUserSession) {
+ const json = localStorage.getItem(id);
+ if (json) {
+ templates = JSON.parse(json);
+ }
+ await api.storeUserData(file, json, { stringify: false });
+ } else {
+ const res = await api.getUserData(file);
+ if (res.status === 200) {
+ try {
+ templates = await res.json();
+ } catch (error) {
+ }
+ } else if (res.status !== 404) {
+ console.error(res.status + " " + res.statusText);
+ }
+ }
+ } else {
+ const json = localStorage.getItem(id);
+ if (json) {
+ templates = JSON.parse(json);
+ }
+ }
+ return templates ?? [];
+ }
+ async store() {
+ if (app.storageLocation === "server") {
+ const templates = JSON.stringify(this.templates, void 0, 4);
+ localStorage.setItem(id, templates);
+ try {
+ await api.storeUserData(file, templates, { stringify: false });
+ } catch (error) {
+ console.error(error);
+ alert(error.message);
+ }
+ } else {
+ localStorage.setItem(id, JSON.stringify(this.templates));
+ }
+ }
+ async importAll() {
+ for (const file2 of this.importInput.files) {
+ if (file2.type === "application/json" || file2.name.endsWith(".json")) {
+ const reader = new FileReader();
+ reader.onload = async () => {
+ const importFile = JSON.parse(reader.result);
+ if (importFile?.templates) {
+ for (const template of importFile.templates) {
+ if (template?.name && template?.data) {
+ this.templates.push(template);
+ }
+ }
+ await this.store();
+ }
+ };
+ await reader.readAsText(file2);
+ }
+ }
+ this.importInput.value = null;
+ this.close();
+ }
+ exportAll() {
+ if (this.templates.length == 0) {
+ alert("No templates to export.");
+ return;
+ }
+ const json = JSON.stringify({ templates: this.templates }, null, 2);
+ const blob = new Blob([json], { type: "application/json" });
+ const url = URL.createObjectURL(blob);
+ const a = $el("a", {
+ href: url,
+ download: "node_templates.json",
+ style: { display: "none" },
+ parent: document.body
+ });
+ a.click();
+ setTimeout(function() {
+ a.remove();
+ window.URL.revokeObjectURL(url);
+ }, 0);
+ }
+ show() {
+ super.show(
+ $el(
+ "div",
+ {},
+ this.templates.flatMap((t, i) => {
+ let nameInput;
+ return [
+ $el(
+ "div",
+ {
+ dataset: { id: i.toString() },
+ className: "templateManagerRow",
+ style: {
+ display: "grid",
+ gridTemplateColumns: "1fr auto",
+ border: "1px dashed transparent",
+ gap: "5px",
+ backgroundColor: "var(--comfy-menu-bg)"
+ },
+ ondragstart: /* @__PURE__ */ __name((e) => {
+ this.draggedEl = e.currentTarget;
+ e.currentTarget.style.opacity = "0.6";
+ e.currentTarget.style.border = "1px dashed yellow";
+ e.dataTransfer.effectAllowed = "move";
+ e.dataTransfer.setDragImage(this.emptyImg, 0, 0);
+ }, "ondragstart"),
+ ondragend: /* @__PURE__ */ __name((e) => {
+ e.target.style.opacity = "1";
+ e.currentTarget.style.border = "1px dashed transparent";
+ e.currentTarget.removeAttribute("draggable");
+ this.element.querySelectorAll(".templateManagerRow").forEach((el, i2) => {
+ var prev_i = Number.parseInt(el.dataset.id);
+ if (el == this.draggedEl && prev_i != i2) {
+ this.templates.splice(
+ i2,
+ 0,
+ this.templates.splice(prev_i, 1)[0]
+ );
+ }
+ el.dataset.id = i2.toString();
+ });
+ this.store();
+ }, "ondragend"),
+ ondragover: /* @__PURE__ */ __name((e) => {
+ e.preventDefault();
+ if (e.currentTarget == this.draggedEl) return;
+ let rect = e.currentTarget.getBoundingClientRect();
+ if (e.clientY > rect.top + rect.height / 2) {
+ e.currentTarget.parentNode.insertBefore(
+ this.draggedEl,
+ e.currentTarget.nextSibling
+ );
+ } else {
+ e.currentTarget.parentNode.insertBefore(
+ this.draggedEl,
+ e.currentTarget
+ );
+ }
+ }, "ondragover")
+ },
+ [
+ $el(
+ "label",
+ {
+ textContent: "Name: ",
+ style: {
+ cursor: "grab"
+ },
+ onmousedown: /* @__PURE__ */ __name((e) => {
+ if (e.target.localName == "label")
+ e.currentTarget.parentNode.draggable = "true";
+ }, "onmousedown")
+ },
+ [
+ $el("input", {
+ value: t.name,
+ dataset: { name: t.name },
+ style: {
+ transitionProperty: "background-color",
+ transitionDuration: "0s"
+ },
+ onchange: /* @__PURE__ */ __name((e) => {
+ clearTimeout(this.saveVisualCue);
+ var el = e.target;
+ var row = el.parentNode.parentNode;
+ this.templates[row.dataset.id].name = el.value.trim() || "untitled";
+ this.store();
+ el.style.backgroundColor = "rgb(40, 95, 40)";
+ el.style.transitionDuration = "0s";
+ this.saveVisualCue = setTimeout(function() {
+ el.style.transitionDuration = ".7s";
+ el.style.backgroundColor = "var(--comfy-input-bg)";
+ }, 15);
+ }, "onchange"),
+ onkeypress: /* @__PURE__ */ __name((e) => {
+ var el = e.target;
+ clearTimeout(this.saveVisualCue);
+ el.style.transitionDuration = "0s";
+ el.style.backgroundColor = "var(--comfy-input-bg)";
+ }, "onkeypress"),
+ $: /* @__PURE__ */ __name((el) => nameInput = el, "$")
+ })
+ ]
+ ),
+ $el("div", {}, [
+ $el("button", {
+ textContent: "Export",
+ style: {
+ fontSize: "12px",
+ fontWeight: "normal"
+ },
+ onclick: /* @__PURE__ */ __name((e) => {
+ const json = JSON.stringify({ templates: [t] }, null, 2);
+ const blob = new Blob([json], {
+ type: "application/json"
+ });
+ const url = URL.createObjectURL(blob);
+ const a = $el("a", {
+ href: url,
+ download: (nameInput.value || t.name) + ".json",
+ style: { display: "none" },
+ parent: document.body
+ });
+ a.click();
+ setTimeout(function() {
+ a.remove();
+ window.URL.revokeObjectURL(url);
+ }, 0);
+ }, "onclick")
+ }),
+ $el("button", {
+ textContent: "Delete",
+ style: {
+ fontSize: "12px",
+ color: "red",
+ fontWeight: "normal"
+ },
+ onclick: /* @__PURE__ */ __name((e) => {
+ const item = e.target.parentNode.parentNode;
+ item.parentNode.removeChild(item);
+ this.templates.splice(item.dataset.id * 1, 1);
+ this.store();
+ var that = this;
+ setTimeout(function() {
+ that.element.querySelectorAll(".templateManagerRow").forEach((el, i2) => {
+ el.dataset.id = i2.toString();
+ });
+ }, 0);
+ }, "onclick")
+ })
+ ])
+ ]
+ )
+ ];
+ })
+ )
+ );
+ }
+}
+app.registerExtension({
+ name: id,
+ setup() {
+ const manage = new ManageTemplates();
+ const clipboardAction = /* @__PURE__ */ __name(async (cb) => {
+ const old = localStorage.getItem("litegrapheditor_clipboard");
+ await cb();
+ localStorage.setItem("litegrapheditor_clipboard", old);
+ }, "clipboardAction");
+ const orig = LGraphCanvas.prototype.getCanvasMenuOptions;
+ LGraphCanvas.prototype.getCanvasMenuOptions = function() {
+ const options = orig.apply(this, arguments);
+ options.push(null);
+ options.push({
+ content: `Save Selected as Template`,
+ disabled: !Object.keys(app.canvas.selected_nodes || {}).length,
+ callback: /* @__PURE__ */ __name(() => {
+ const name = prompt("Enter name");
+ if (!name?.trim()) return;
+ clipboardAction(() => {
+ app.canvas.copyToClipboard();
+ let data = localStorage.getItem("litegrapheditor_clipboard");
+ data = JSON.parse(data);
+ const nodeIds = Object.keys(app.canvas.selected_nodes);
+ for (let i = 0; i < nodeIds.length; i++) {
+ const node = app.graph.getNodeById(nodeIds[i]);
+ const nodeData = node?.constructor.nodeData;
+ let groupData = GroupNodeHandler.getGroupData(node);
+ if (groupData) {
+ groupData = groupData.nodeData;
+ if (!data.groupNodes) {
+ data.groupNodes = {};
+ }
+ data.groupNodes[nodeData.name] = groupData;
+ data.nodes[i].type = nodeData.name;
+ }
+ }
+ manage.templates.push({
+ name,
+ data: JSON.stringify(data)
+ });
+ manage.store();
+ });
+ }, "callback")
+ });
+ const subItems = manage.templates.map((t) => {
+ return {
+ content: t.name,
+ callback: /* @__PURE__ */ __name(() => {
+ clipboardAction(async () => {
+ const data = JSON.parse(t.data);
+ await GroupNodeConfig.registerFromWorkflow(data.groupNodes, {});
+ localStorage.setItem("litegrapheditor_clipboard", t.data);
+ app.canvas.pasteFromClipboard();
+ });
+ }, "callback")
+ };
+ });
+ subItems.push(null, {
+ content: "Manage",
+ callback: /* @__PURE__ */ __name(() => manage.show(), "callback")
+ });
+ options.push({
+ content: "Node Templates",
+ submenu: {
+ options: subItems
+ }
+ });
+ return options;
+ };
+ }
+});
+app.registerExtension({
+ name: "Comfy.NoteNode",
+ registerCustomNodes() {
+ class NoteNode extends LGraphNode {
+ static {
+ __name(this, "NoteNode");
+ }
+ static category;
+ color = LGraphCanvas.node_colors.yellow.color;
+ bgcolor = LGraphCanvas.node_colors.yellow.bgcolor;
+ groupcolor = LGraphCanvas.node_colors.yellow.groupcolor;
+ isVirtualNode;
+ collapsable;
+ title_mode;
+ constructor(title) {
+ super(title);
+ if (!this.properties) {
+ this.properties = { text: "" };
+ }
+ ComfyWidgets.STRING(
+ // Should we extends LGraphNode? Yesss
+ this,
+ "",
+ // @ts-expect-error
+ ["", { default: this.properties.text, multiline: true }],
+ app
+ );
+ this.serialize_widgets = true;
+ this.isVirtualNode = true;
+ }
+ }
+ LiteGraph.registerNodeType(
+ "Note",
+ Object.assign(NoteNode, {
+ title_mode: LiteGraph.NORMAL_TITLE,
+ title: "Note",
+ collapsable: true
+ })
+ );
+ NoteNode.category = "utils";
+ }
+});
+app.registerExtension({
+ name: "Comfy.RerouteNode",
+ registerCustomNodes(app2) {
+ class RerouteNode extends LGraphNode {
+ static {
+ __name(this, "RerouteNode");
+ }
+ static category;
+ static defaultVisibility = false;
+ constructor(title) {
+ super(title);
+ if (!this.properties) {
+ this.properties = {};
+ }
+ this.properties.showOutputText = RerouteNode.defaultVisibility;
+ this.properties.horizontal = false;
+ this.addInput("", "*");
+ this.addOutput(this.properties.showOutputText ? "*" : "", "*");
+ this.onAfterGraphConfigured = function() {
+ requestAnimationFrame(() => {
+ this.onConnectionsChange(LiteGraph.INPUT, null, true, null);
+ });
+ };
+ this.onConnectionsChange = function(type, index, connected, link_info) {
+ this.applyOrientation();
+ if (connected && type === LiteGraph.OUTPUT) {
+ const types = new Set(
+ this.outputs[0].links.map((l) => app2.graph.links[l].type).filter((t) => t !== "*")
+ );
+ if (types.size > 1) {
+ const linksToDisconnect = [];
+ for (let i = 0; i < this.outputs[0].links.length - 1; i++) {
+ const linkId = this.outputs[0].links[i];
+ const link = app2.graph.links[linkId];
+ linksToDisconnect.push(link);
+ }
+ for (const link of linksToDisconnect) {
+ const node = app2.graph.getNodeById(link.target_id);
+ node.disconnectInput(link.target_slot);
+ }
+ }
+ }
+ let currentNode = this;
+ let updateNodes = [];
+ let inputType = null;
+ let inputNode = null;
+ while (currentNode) {
+ updateNodes.unshift(currentNode);
+ const linkId = currentNode.inputs[0].link;
+ if (linkId !== null) {
+ const link = app2.graph.links[linkId];
+ if (!link) return;
+ const node = app2.graph.getNodeById(link.origin_id);
+ const type2 = node.constructor.type;
+ if (type2 === "Reroute") {
+ if (node === this) {
+ currentNode.disconnectInput(link.target_slot);
+ currentNode = null;
+ } else {
+ currentNode = node;
+ }
+ } else {
+ inputNode = currentNode;
+ inputType = node.outputs[link.origin_slot]?.type ?? null;
+ break;
+ }
+ } else {
+ currentNode = null;
+ break;
+ }
+ }
+ const nodes = [this];
+ let outputType = null;
+ while (nodes.length) {
+ currentNode = nodes.pop();
+ const outputs = (currentNode.outputs ? currentNode.outputs[0].links : []) || [];
+ if (outputs.length) {
+ for (const linkId of outputs) {
+ const link = app2.graph.links[linkId];
+ if (!link) continue;
+ const node = app2.graph.getNodeById(link.target_id);
+ const type2 = node.constructor.type;
+ if (type2 === "Reroute") {
+ nodes.push(node);
+ updateNodes.push(node);
+ } else {
+ const nodeOutType = node.inputs && node.inputs[link?.target_slot] && node.inputs[link.target_slot].type ? node.inputs[link.target_slot].type : null;
+ if (inputType && !LiteGraph.isValidConnection(inputType, nodeOutType)) {
+ node.disconnectInput(link.target_slot);
+ } else {
+ outputType = nodeOutType;
+ }
+ }
+ }
+ } else {
+ }
+ }
+ const displayType = inputType || outputType || "*";
+ const color = LGraphCanvas.link_type_colors[displayType];
+ let widgetConfig;
+ let targetWidget;
+ let widgetType;
+ for (const node of updateNodes) {
+ node.outputs[0].type = inputType || "*";
+ node.__outputType = displayType;
+ node.outputs[0].name = node.properties.showOutputText ? displayType : "";
+ node.size = node.computeSize();
+ node.applyOrientation();
+ for (const l of node.outputs[0].links || []) {
+ const link = app2.graph.links[l];
+ if (link) {
+ link.color = color;
+ if (app2.configuringGraph) continue;
+ const targetNode = app2.graph.getNodeById(link.target_id);
+ const targetInput = targetNode.inputs?.[link.target_slot];
+ if (targetInput?.widget) {
+ const config = getWidgetConfig(targetInput);
+ if (!widgetConfig) {
+ widgetConfig = config[1] ?? {};
+ widgetType = config[0];
+ }
+ if (!targetWidget) {
+ targetWidget = targetNode.widgets?.find(
+ // @ts-expect-error fix widget types
+ (w) => w.name === targetInput.widget.name
+ );
+ }
+ const merged = mergeIfValid(targetInput, [
+ config[0],
+ widgetConfig
+ ]);
+ if (merged.customConfig) {
+ widgetConfig = merged.customConfig;
+ }
+ }
+ }
+ }
+ }
+ for (const node of updateNodes) {
+ if (widgetConfig && outputType) {
+ node.inputs[0].widget = { name: "value" };
+ setWidgetConfig(
+ node.inputs[0],
+ [widgetType ?? displayType, widgetConfig],
+ targetWidget
+ );
+ } else {
+ setWidgetConfig(node.inputs[0], null);
+ }
+ }
+ if (inputNode) {
+ const link = app2.graph.links[inputNode.inputs[0].link];
+ if (link) {
+ link.color = color;
+ }
+ }
+ };
+ this.clone = function() {
+ const cloned = RerouteNode.prototype.clone.apply(this);
+ cloned.removeOutput(0);
+ cloned.addOutput(this.properties.showOutputText ? "*" : "", "*");
+ cloned.size = cloned.computeSize();
+ return cloned;
+ };
+ this.isVirtualNode = true;
+ }
+ getExtraMenuOptions(_2, options) {
+ options.unshift(
+ {
+ content: (this.properties.showOutputText ? "Hide" : "Show") + " Type",
+ callback: /* @__PURE__ */ __name(() => {
+ this.properties.showOutputText = !this.properties.showOutputText;
+ if (this.properties.showOutputText) {
+ this.outputs[0].name = this.__outputType || this.outputs[0].type;
+ } else {
+ this.outputs[0].name = "";
+ }
+ this.size = this.computeSize();
+ this.applyOrientation();
+ app2.graph.setDirtyCanvas(true, true);
+ }, "callback")
+ },
+ {
+ content: (RerouteNode.defaultVisibility ? "Hide" : "Show") + " Type By Default",
+ callback: /* @__PURE__ */ __name(() => {
+ RerouteNode.setDefaultTextVisibility(
+ !RerouteNode.defaultVisibility
+ );
+ }, "callback")
+ },
+ {
+ // naming is inverted with respect to LiteGraphNode.horizontal
+ // LiteGraphNode.horizontal == true means that
+ // each slot in the inputs and outputs are laid out horizontally,
+ // which is the opposite of the visual orientation of the inputs and outputs as a node
+ content: "Set " + (this.properties.horizontal ? "Horizontal" : "Vertical"),
+ callback: /* @__PURE__ */ __name(() => {
+ this.properties.horizontal = !this.properties.horizontal;
+ this.applyOrientation();
+ }, "callback")
+ }
+ );
+ }
+ applyOrientation() {
+ this.horizontal = this.properties.horizontal;
+ if (this.horizontal) {
+ this.inputs[0].pos = [this.size[0] / 2, 0];
+ } else {
+ delete this.inputs[0].pos;
+ }
+ app2.graph.setDirtyCanvas(true, true);
+ }
+ computeSize() {
+ return [
+ this.properties.showOutputText && this.outputs && this.outputs.length ? Math.max(
+ 75,
+ LiteGraph.NODE_TEXT_SIZE * this.outputs[0].name.length * 0.6 + 40
+ ) : 75,
+ 26
+ ];
+ }
+ static setDefaultTextVisibility(visible) {
+ RerouteNode.defaultVisibility = visible;
+ if (visible) {
+ localStorage["Comfy.RerouteNode.DefaultVisibility"] = "true";
+ } else {
+ delete localStorage["Comfy.RerouteNode.DefaultVisibility"];
+ }
+ }
+ }
+ RerouteNode.setDefaultTextVisibility(
+ !!localStorage["Comfy.RerouteNode.DefaultVisibility"]
+ );
+ LiteGraph.registerNodeType(
+ "Reroute",
+ Object.assign(RerouteNode, {
+ title_mode: LiteGraph.NO_TITLE,
+ title: "Reroute",
+ collapsable: false
+ })
+ );
+ RerouteNode.category = "utils";
+ }
+});
+app.registerExtension({
+ name: "Comfy.SaveImageExtraOutput",
+ async beforeRegisterNodeDef(nodeType, nodeData, app2) {
+ if (nodeData.name === "SaveImage" || nodeData.name === "SaveAnimatedWEBP") {
+ const onNodeCreated = nodeType.prototype.onNodeCreated;
+ nodeType.prototype.onNodeCreated = function() {
+ const r = onNodeCreated ? onNodeCreated.apply(this, arguments) : void 0;
+ const widget = this.widgets.find((w) => w.name === "filename_prefix");
+ widget.serializeValue = () => {
+ return applyTextReplacements(app2, widget.value);
+ };
+ return r;
+ };
+ } else {
+ const onNodeCreated = nodeType.prototype.onNodeCreated;
+ nodeType.prototype.onNodeCreated = function() {
+ const r = onNodeCreated ? onNodeCreated.apply(this, arguments) : void 0;
+ if (!this.properties || !("Node name for S&R" in this.properties)) {
+ this.addProperty("Node name for S&R", this.constructor.type, "string");
+ }
+ return r;
+ };
+ }
+ }
+});
+let touchZooming;
+let touchCount = 0;
+app.registerExtension({
+ name: "Comfy.SimpleTouchSupport",
+ setup() {
+ let zoomPos;
+ let touchTime;
+ let lastTouch;
+ function getMultiTouchPos(e) {
+ return Math.hypot(
+ e.touches[0].clientX - e.touches[1].clientX,
+ e.touches[0].clientY - e.touches[1].clientY
+ );
+ }
+ __name(getMultiTouchPos, "getMultiTouchPos");
+ app.canvasEl.addEventListener(
+ "touchstart",
+ (e) => {
+ touchCount++;
+ lastTouch = null;
+ if (e.touches?.length === 1) {
+ touchTime = /* @__PURE__ */ new Date();
+ lastTouch = e.touches[0];
+ } else {
+ touchTime = null;
+ if (e.touches?.length === 2) {
+ zoomPos = getMultiTouchPos(e);
+ app.canvas.pointer_is_down = false;
+ }
+ }
+ },
+ true
+ );
+ app.canvasEl.addEventListener("touchend", (e) => {
+ touchZooming = false;
+ touchCount = e.touches?.length ?? touchCount - 1;
+ if (touchTime && !e.touches?.length) {
+ if ((/* @__PURE__ */ new Date()).getTime() - touchTime > 600) {
+ try {
+ e.constructor = CustomEvent;
+ } catch (error) {
+ }
+ e.clientX = lastTouch.clientX;
+ e.clientY = lastTouch.clientY;
+ app.canvas.pointer_is_down = true;
+ app.canvas._mousedown_callback(e);
+ }
+ touchTime = null;
+ }
+ });
+ app.canvasEl.addEventListener(
+ "touchmove",
+ (e) => {
+ touchTime = null;
+ if (e.touches?.length === 2) {
+ app.canvas.pointer_is_down = false;
+ touchZooming = true;
+ LiteGraph.closeAllContextMenus();
+ app.canvas.search_box?.close();
+ const newZoomPos = getMultiTouchPos(e);
+ const midX = (e.touches[0].clientX + e.touches[1].clientX) / 2;
+ const midY = (e.touches[0].clientY + e.touches[1].clientY) / 2;
+ let scale = app.canvas.ds.scale;
+ const diff = zoomPos - newZoomPos;
+ if (diff > 0.5) {
+ scale *= 1 / 1.07;
+ } else if (diff < -0.5) {
+ scale *= 1.07;
+ }
+ app.canvas.ds.changeScale(scale, [midX, midY]);
+ app.canvas.setDirty(true, true);
+ zoomPos = newZoomPos;
+ }
+ },
+ true
+ );
+ }
+});
+const processMouseDown = LGraphCanvas.prototype.processMouseDown;
+LGraphCanvas.prototype.processMouseDown = function(e) {
+ if (touchZooming || touchCount) {
+ return;
+ }
+ return processMouseDown.apply(this, arguments);
+};
+const processMouseMove = LGraphCanvas.prototype.processMouseMove;
+LGraphCanvas.prototype.processMouseMove = function(e) {
+ if (touchZooming || touchCount > 1) {
+ return;
+ }
+ return processMouseMove.apply(this, arguments);
+};
+app.registerExtension({
+ name: "Comfy.SlotDefaults",
+ suggestionsNumber: null,
+ init() {
+ LiteGraph.search_filter_enabled = true;
+ LiteGraph.middle_click_slot_add_default_node = true;
+ this.suggestionsNumber = app.ui.settings.addSetting({
+ id: "Comfy.NodeSuggestions.number",
+ category: ["Comfy", "Node Search Box", "NodeSuggestions"],
+ name: "Number of nodes suggestions",
+ tooltip: "Only for litegraph searchbox/context menu",
+ type: "slider",
+ attrs: {
+ min: 1,
+ max: 100,
+ step: 1
+ },
+ defaultValue: 5,
+ onChange: /* @__PURE__ */ __name((newVal, oldVal) => {
+ this.setDefaults(newVal);
+ }, "onChange")
+ });
+ },
+ slot_types_default_out: {},
+ slot_types_default_in: {},
+ async beforeRegisterNodeDef(nodeType, nodeData, app2) {
+ var nodeId = nodeData.name;
+ const inputs = nodeData["input"]["required"];
+ for (const inputKey in inputs) {
+ var input = inputs[inputKey];
+ if (typeof input[0] !== "string") continue;
+ var type = input[0];
+ if (type in ComfyWidgets) {
+ var customProperties = input[1];
+ if (!customProperties?.forceInput) continue;
+ }
+ if (!(type in this.slot_types_default_out)) {
+ this.slot_types_default_out[type] = ["Reroute"];
+ }
+ if (this.slot_types_default_out[type].includes(nodeId)) continue;
+ this.slot_types_default_out[type].push(nodeId);
+ const lowerType = type.toLocaleLowerCase();
+ if (!(lowerType in LiteGraph.registered_slot_in_types)) {
+ LiteGraph.registered_slot_in_types[lowerType] = { nodes: [] };
+ }
+ LiteGraph.registered_slot_in_types[lowerType].nodes.push(
+ nodeType.comfyClass
+ );
+ }
+ var outputs = nodeData["output"];
+ for (const key in outputs) {
+ var type = outputs[key];
+ if (!(type in this.slot_types_default_in)) {
+ this.slot_types_default_in[type] = ["Reroute"];
+ }
+ this.slot_types_default_in[type].push(nodeId);
+ if (!(type in LiteGraph.registered_slot_out_types)) {
+ LiteGraph.registered_slot_out_types[type] = { nodes: [] };
+ }
+ LiteGraph.registered_slot_out_types[type].nodes.push(nodeType.comfyClass);
+ if (!LiteGraph.slot_types_out.includes(type)) {
+ LiteGraph.slot_types_out.push(type);
+ }
+ }
+ var maxNum = this.suggestionsNumber.value;
+ this.setDefaults(maxNum);
+ },
+ setDefaults(maxNum) {
+ LiteGraph.slot_types_default_out = {};
+ LiteGraph.slot_types_default_in = {};
+ for (const type in this.slot_types_default_out) {
+ LiteGraph.slot_types_default_out[type] = this.slot_types_default_out[type].slice(0, maxNum);
+ }
+ for (const type in this.slot_types_default_in) {
+ LiteGraph.slot_types_default_in[type] = this.slot_types_default_in[type].slice(0, maxNum);
+ }
+ }
+});
+function roundVectorToGrid(vec) {
+ vec[0] = LiteGraph.CANVAS_GRID_SIZE * Math.round(vec[0] / LiteGraph.CANVAS_GRID_SIZE);
+ vec[1] = LiteGraph.CANVAS_GRID_SIZE * Math.round(vec[1] / LiteGraph.CANVAS_GRID_SIZE);
+ return vec;
+}
+__name(roundVectorToGrid, "roundVectorToGrid");
+app.registerExtension({
+ name: "Comfy.SnapToGrid",
+ init() {
+ app.ui.settings.addSetting({
+ id: "Comfy.SnapToGrid.GridSize",
+ category: ["Comfy", "Graph", "GridSize"],
+ name: "Snap to grid size",
+ type: "slider",
+ attrs: {
+ min: 1,
+ max: 500
+ },
+ tooltip: "When dragging and resizing nodes while holding shift they will be aligned to the grid, this controls the size of that grid.",
+ defaultValue: LiteGraph.CANVAS_GRID_SIZE,
+ onChange(value) {
+ LiteGraph.CANVAS_GRID_SIZE = +value || 10;
+ }
+ });
+ const onNodeMoved = app.canvas.onNodeMoved;
+ app.canvas.onNodeMoved = function(node) {
+ const r = onNodeMoved?.apply(this, arguments);
+ if (app.shiftDown) {
+ for (const id2 in this.selected_nodes) {
+ this.selected_nodes[id2].alignToGrid();
+ }
+ }
+ return r;
+ };
+ const onNodeAdded = app.graph.onNodeAdded;
+ app.graph.onNodeAdded = function(node) {
+ const onResize = node.onResize;
+ node.onResize = function() {
+ if (app.shiftDown) {
+ roundVectorToGrid(node.size);
+ }
+ return onResize?.apply(this, arguments);
+ };
+ return onNodeAdded?.apply(this, arguments);
+ };
+ const origDrawNode = LGraphCanvas.prototype.drawNode;
+ LGraphCanvas.prototype.drawNode = function(node, ctx) {
+ if (app.shiftDown && this.node_dragged && node.id in this.selected_nodes) {
+ const [x, y] = roundVectorToGrid([...node.pos]);
+ const shiftX = x - node.pos[0];
+ let shiftY = y - node.pos[1];
+ let w, h;
+ if (node.flags.collapsed) {
+ w = node._collapsed_width;
+ h = LiteGraph.NODE_TITLE_HEIGHT;
+ shiftY -= LiteGraph.NODE_TITLE_HEIGHT;
+ } else {
+ w = node.size[0];
+ h = node.size[1];
+ let titleMode = node.constructor.title_mode;
+ if (titleMode !== LiteGraph.TRANSPARENT_TITLE && titleMode !== LiteGraph.NO_TITLE) {
+ h += LiteGraph.NODE_TITLE_HEIGHT;
+ shiftY -= LiteGraph.NODE_TITLE_HEIGHT;
+ }
+ }
+ const f = ctx.fillStyle;
+ ctx.fillStyle = "rgba(100, 100, 100, 0.5)";
+ ctx.fillRect(shiftX, shiftY, w, h);
+ ctx.fillStyle = f;
+ }
+ return origDrawNode.apply(this, arguments);
+ };
+ let selectedAndMovingGroup = null;
+ const groupMove = LGraphGroup.prototype.move;
+ LGraphGroup.prototype.move = function(deltax, deltay, ignore_nodes) {
+ const v = groupMove.apply(this, arguments);
+ if (!selectedAndMovingGroup && app.canvas.selected_group === this && (deltax || deltay)) {
+ selectedAndMovingGroup = this;
+ }
+ if (app.canvas.last_mouse_dragging === false && app.shiftDown) {
+ this.recomputeInsideNodes();
+ for (const node of this.nodes) {
+ node.alignToGrid();
+ }
+ LGraphNode.prototype.alignToGrid.apply(this);
+ }
+ return v;
+ };
+ const drawGroups = LGraphCanvas.prototype.drawGroups;
+ LGraphCanvas.prototype.drawGroups = function(canvas, ctx) {
+ if (this.selected_group && app.shiftDown) {
+ if (this.selected_group_resizing) {
+ roundVectorToGrid(this.selected_group.size);
+ } else if (selectedAndMovingGroup) {
+ const [x, y] = roundVectorToGrid([...selectedAndMovingGroup.pos]);
+ const f = ctx.fillStyle;
+ const s = ctx.strokeStyle;
+ ctx.fillStyle = "rgba(100, 100, 100, 0.33)";
+ ctx.strokeStyle = "rgba(100, 100, 100, 0.66)";
+ ctx.rect(x, y, ...selectedAndMovingGroup.size);
+ ctx.fill();
+ ctx.stroke();
+ ctx.fillStyle = f;
+ ctx.strokeStyle = s;
+ }
+ } else if (!this.selected_group) {
+ selectedAndMovingGroup = null;
+ }
+ return drawGroups.apply(this, arguments);
+ };
+ const onGroupAdd = LGraphCanvas.onGroupAdd;
+ LGraphCanvas.onGroupAdd = function() {
+ const v = onGroupAdd.apply(app.canvas, arguments);
+ if (app.shiftDown) {
+ const lastGroup = app.graph.groups[app.graph.groups.length - 1];
+ if (lastGroup) {
+ roundVectorToGrid(lastGroup.pos);
+ roundVectorToGrid(lastGroup.size);
+ }
+ }
+ return v;
+ };
+ }
+});
+app.registerExtension({
+ name: "Comfy.UploadImage",
+ async beforeRegisterNodeDef(nodeType, nodeData, app2) {
+ if (nodeData?.input?.required?.image?.[1]?.image_upload === true) {
+ nodeData.input.required.upload = ["IMAGEUPLOAD"];
+ }
+ }
+});
+const WEBCAM_READY = Symbol();
+app.registerExtension({
+ name: "Comfy.WebcamCapture",
+ getCustomWidgets(app2) {
+ return {
+ WEBCAM(node, inputName) {
+ let res;
+ node[WEBCAM_READY] = new Promise((resolve) => res = resolve);
+ const container = document.createElement("div");
+ container.style.background = "rgba(0,0,0,0.25)";
+ container.style.textAlign = "center";
+ const video = document.createElement("video");
+ video.style.height = video.style.width = "100%";
+ const loadVideo = /* @__PURE__ */ __name(async () => {
+ try {
+ const stream = await navigator.mediaDevices.getUserMedia({
+ video: true,
+ audio: false
+ });
+ container.replaceChildren(video);
+ setTimeout(() => res(video), 500);
+ video.addEventListener("loadedmetadata", () => res(video), false);
+ video.srcObject = stream;
+ video.play();
+ } catch (error) {
+ const label = document.createElement("div");
+ label.style.color = "red";
+ label.style.overflow = "auto";
+ label.style.maxHeight = "100%";
+ label.style.whiteSpace = "pre-wrap";
+ if (window.isSecureContext) {
+ label.textContent = "Unable to load webcam, please ensure access is granted:\n" + error.message;
+ } else {
+ label.textContent = "Unable to load webcam. A secure context is required, if you are not accessing ComfyUI on localhost (127.0.0.1) you will have to enable TLS (https)\n\n" + error.message;
+ }
+ container.replaceChildren(label);
+ }
+ }, "loadVideo");
+ loadVideo();
+ return { widget: node.addDOMWidget(inputName, "WEBCAM", container) };
+ }
+ };
+ },
+ nodeCreated(node) {
+ if (node.type, node.constructor.comfyClass !== "WebcamCapture") return;
+ let video;
+ const camera = node.widgets.find((w2) => w2.name === "image");
+ const w = node.widgets.find((w2) => w2.name === "width");
+ const h = node.widgets.find((w2) => w2.name === "height");
+ const captureOnQueue = node.widgets.find(
+ (w2) => w2.name === "capture_on_queue"
+ );
+ const canvas = document.createElement("canvas");
+ const capture = /* @__PURE__ */ __name(() => {
+ canvas.width = w.value;
+ canvas.height = h.value;
+ const ctx = canvas.getContext("2d");
+ ctx.drawImage(video, 0, 0, w.value, h.value);
+ const data = canvas.toDataURL("image/png");
+ const img = new Image();
+ img.onload = () => {
+ node.imgs = [img];
+ app.graph.setDirtyCanvas(true);
+ requestAnimationFrame(() => {
+ node.setSizeForImage?.();
+ });
+ };
+ img.src = data;
+ }, "capture");
+ const btn = node.addWidget(
+ "button",
+ "waiting for camera...",
+ "capture",
+ capture
+ );
+ btn.disabled = true;
+ btn.serializeValue = () => void 0;
+ camera.serializeValue = async () => {
+ if (captureOnQueue.value) {
+ capture();
+ } else if (!node.imgs?.length) {
+ const err = `No webcam image captured`;
+ alert(err);
+ throw new Error(err);
+ }
+ const blob = await new Promise((r) => canvas.toBlob(r));
+ const name = `${+/* @__PURE__ */ new Date()}.png`;
+ const file2 = new File([blob], name);
+ const body = new FormData();
+ body.append("image", file2);
+ body.append("subfolder", "webcam");
+ body.append("type", "temp");
+ const resp = await api.fetchApi("/upload/image", {
+ method: "POST",
+ body
+ });
+ if (resp.status !== 200) {
+ const err = `Error uploading camera image: ${resp.status} - ${resp.statusText}`;
+ alert(err);
+ throw new Error(err);
+ }
+ return `webcam/${name} [temp]`;
+ };
+ node[WEBCAM_READY].then((v) => {
+ video = v;
+ if (!w.value) {
+ w.value = video.videoWidth || 640;
+ h.value = video.videoHeight || 480;
+ }
+ btn.disabled = false;
+ btn.label = "capture";
+ });
+ }
+});
+function splitFilePath(path) {
+ const folder_separator = path.lastIndexOf("/");
+ if (folder_separator === -1) {
+ return ["", path];
+ }
+ return [
+ path.substring(0, folder_separator),
+ path.substring(folder_separator + 1)
+ ];
+}
+__name(splitFilePath, "splitFilePath");
+function getResourceURL(subfolder, filename, type = "input") {
+ const params = [
+ "filename=" + encodeURIComponent(filename),
+ "type=" + type,
+ "subfolder=" + subfolder,
+ app.getRandParam().substring(1)
+ ].join("&");
+ return `/view?${params}`;
+}
+__name(getResourceURL, "getResourceURL");
+async function uploadFile(audioWidget, audioUIWidget, file2, updateNode, pasted = false) {
+ try {
+ const body = new FormData();
+ body.append("image", file2);
+ if (pasted) body.append("subfolder", "pasted");
+ const resp = await api.fetchApi("/upload/image", {
+ method: "POST",
+ body
+ });
+ if (resp.status === 200) {
+ const data = await resp.json();
+ let path = data.name;
+ if (data.subfolder) path = data.subfolder + "/" + path;
+ if (!audioWidget.options.values.includes(path)) {
+ audioWidget.options.values.push(path);
+ }
+ if (updateNode) {
+ audioUIWidget.element.src = api.apiURL(
+ getResourceURL(...splitFilePath(path))
+ );
+ audioWidget.value = path;
+ }
+ } else {
+ alert(resp.status + " - " + resp.statusText);
+ }
+ } catch (error) {
+ alert(error);
+ }
+}
+__name(uploadFile, "uploadFile");
+app.registerExtension({
+ name: "Comfy.AudioWidget",
+ async beforeRegisterNodeDef(nodeType, nodeData) {
+ if (["LoadAudio", "SaveAudio", "PreviewAudio"].includes(nodeType.comfyClass)) {
+ nodeData.input.required.audioUI = ["AUDIO_UI"];
+ }
+ },
+ getCustomWidgets() {
+ return {
+ AUDIO_UI(node, inputName) {
+ const audio = document.createElement("audio");
+ audio.controls = true;
+ audio.classList.add("comfy-audio");
+ audio.setAttribute("name", "media");
+ const audioUIWidget = node.addDOMWidget(
+ inputName,
+ /* name=*/
+ "audioUI",
+ audio
+ );
+ audioUIWidget.serialize = false;
+ const isOutputNode = node.constructor.nodeData.output_node;
+ if (isOutputNode) {
+ audioUIWidget.element.classList.add("empty-audio-widget");
+ const onExecuted = node.onExecuted;
+ node.onExecuted = function(message) {
+ onExecuted?.apply(this, arguments);
+ const audios = message.audio;
+ if (!audios) return;
+ const audio2 = audios[0];
+ audioUIWidget.element.src = api.apiURL(
+ getResourceURL(audio2.subfolder, audio2.filename, audio2.type)
+ );
+ audioUIWidget.element.classList.remove("empty-audio-widget");
+ };
+ }
+ return { widget: audioUIWidget };
+ }
+ };
+ },
+ onNodeOutputsUpdated(nodeOutputs) {
+ for (const [nodeId, output] of Object.entries(nodeOutputs)) {
+ const node = app.graph.getNodeById(nodeId);
+ if ("audio" in output) {
+ const audioUIWidget = node.widgets.find(
+ (w) => w.name === "audioUI"
+ );
+ const audio = output.audio[0];
+ audioUIWidget.element.src = api.apiURL(
+ getResourceURL(audio.subfolder, audio.filename, audio.type)
+ );
+ audioUIWidget.element.classList.remove("empty-audio-widget");
+ }
+ }
+ }
+});
+app.registerExtension({
+ name: "Comfy.UploadAudio",
+ async beforeRegisterNodeDef(nodeType, nodeData) {
+ if (nodeData?.input?.required?.audio?.[1]?.audio_upload === true) {
+ nodeData.input.required.upload = ["AUDIOUPLOAD"];
+ }
+ },
+ getCustomWidgets() {
+ return {
+ AUDIOUPLOAD(node, inputName) {
+ const audioWidget = node.widgets.find(
+ (w) => w.name === "audio"
+ );
+ const audioUIWidget = node.widgets.find(
+ (w) => w.name === "audioUI"
+ );
+ const onAudioWidgetUpdate = /* @__PURE__ */ __name(() => {
+ audioUIWidget.element.src = api.apiURL(
+ getResourceURL(...splitFilePath(audioWidget.value))
+ );
+ }, "onAudioWidgetUpdate");
+ if (audioWidget.value) {
+ onAudioWidgetUpdate();
+ }
+ audioWidget.callback = onAudioWidgetUpdate;
+ const onGraphConfigured = node.onGraphConfigured;
+ node.onGraphConfigured = function() {
+ onGraphConfigured?.apply(this, arguments);
+ if (audioWidget.value) {
+ onAudioWidgetUpdate();
+ }
+ };
+ const fileInput = document.createElement("input");
+ fileInput.type = "file";
+ fileInput.accept = "audio/*";
+ fileInput.style.display = "none";
+ fileInput.onchange = () => {
+ if (fileInput.files.length) {
+ uploadFile(audioWidget, audioUIWidget, fileInput.files[0], true);
+ }
+ };
+ const uploadWidget = node.addWidget(
+ "button",
+ inputName,
+ /* value=*/
+ "",
+ () => {
+ fileInput.click();
+ }
+ );
+ uploadWidget.label = "choose file to upload";
+ uploadWidget.serialize = false;
+ return { widget: uploadWidget };
+ }
+ };
+ }
+});
+function getNodeSource(node) {
+ const nodeDef = node.constructor.nodeData;
+ if (!nodeDef) {
+ return null;
+ }
+ const nodeDefStore = useNodeDefStore();
+ return nodeDefStore.nodeDefsByName[nodeDef.name]?.nodeSource ?? null;
+}
+__name(getNodeSource, "getNodeSource");
+function isCoreNode(node) {
+ return getNodeSource(node)?.type === NodeSourceType.Core;
+}
+__name(isCoreNode, "isCoreNode");
+function badgeTextVisible(node, badgeMode) {
+ return badgeMode === NodeBadgeMode.None || isCoreNode(node) && badgeMode === NodeBadgeMode.HideBuiltIn;
+}
+__name(badgeTextVisible, "badgeTextVisible");
+function getNodeIdBadgeText(node, nodeIdBadgeMode) {
+ return badgeTextVisible(node, nodeIdBadgeMode) ? "" : `#${node.id}`;
+}
+__name(getNodeIdBadgeText, "getNodeIdBadgeText");
+function getNodeSourceBadgeText(node, nodeSourceBadgeMode) {
+ const nodeSource = getNodeSource(node);
+ return badgeTextVisible(node, nodeSourceBadgeMode) ? "" : nodeSource?.badgeText ?? "";
+}
+__name(getNodeSourceBadgeText, "getNodeSourceBadgeText");
+function getNodeLifeCycleBadgeText(node, nodeLifeCycleBadgeMode) {
+ let text = "";
+ const nodeDef = node.constructor.nodeData;
+ if (!nodeDef) {
+ return "";
+ }
+ if (nodeDef.deprecated) {
+ text = "[DEPR]";
+ }
+ if (nodeDef.experimental) {
+ text = "[BETA]";
+ }
+ return badgeTextVisible(node, nodeLifeCycleBadgeMode) ? "" : text;
+}
+__name(getNodeLifeCycleBadgeText, "getNodeLifeCycleBadgeText");
+class NodeBadgeExtension {
+ static {
+ __name(this, "NodeBadgeExtension");
+ }
+ constructor(nodeIdBadgeMode = null, nodeSourceBadgeMode = null, nodeLifeCycleBadgeMode = null, colorPalette = null) {
+ this.nodeIdBadgeMode = nodeIdBadgeMode;
+ this.nodeSourceBadgeMode = nodeSourceBadgeMode;
+ this.nodeLifeCycleBadgeMode = nodeLifeCycleBadgeMode;
+ this.colorPalette = colorPalette;
+ }
+ name = "Comfy.NodeBadge";
+ init(app2) {
+ const settingStore = useSettingStore();
+ this.nodeSourceBadgeMode = computed(
+ () => settingStore.get("Comfy.NodeBadge.NodeSourceBadgeMode")
+ );
+ this.nodeIdBadgeMode = computed(
+ () => settingStore.get("Comfy.NodeBadge.NodeIdBadgeMode")
+ );
+ this.nodeLifeCycleBadgeMode = computed(
+ () => settingStore.get(
+ "Comfy.NodeBadge.NodeLifeCycleBadgeMode"
+ )
+ );
+ this.colorPalette = computed(
+ () => getColorPalette(settingStore.get("Comfy.ColorPalette"))
+ );
+ watch(this.nodeSourceBadgeMode, () => {
+ app2.graph.setDirtyCanvas(true, true);
+ });
+ watch(this.nodeIdBadgeMode, () => {
+ app2.graph.setDirtyCanvas(true, true);
+ });
+ watch(this.nodeLifeCycleBadgeMode, () => {
+ app2.graph.setDirtyCanvas(true, true);
+ });
+ }
+ nodeCreated(node, app2) {
+ node.badgePosition = BadgePosition.TopRight;
+ node.badge_enabled = true;
+ const badge = computed(
+ () => new LGraphBadge$1({
+ text: _.truncate(
+ [
+ getNodeIdBadgeText(node, this.nodeIdBadgeMode.value),
+ getNodeLifeCycleBadgeText(
+ node,
+ this.nodeLifeCycleBadgeMode.value
+ ),
+ getNodeSourceBadgeText(node, this.nodeSourceBadgeMode.value)
+ ].filter((s) => s.length > 0).join(" "),
+ {
+ length: 31
+ }
+ ),
+ fgColor: this.colorPalette.value.colors.litegraph_base?.BADGE_FG_COLOR || defaultColorPalette.colors.litegraph_base.BADGE_FG_COLOR,
+ bgColor: this.colorPalette.value.colors.litegraph_base?.BADGE_BG_COLOR || defaultColorPalette.colors.litegraph_base.BADGE_BG_COLOR
+ })
+ );
+ node.badges.push(() => badge.value);
+ }
+}
+app.registerExtension(new NodeBadgeExtension());
+//# sourceMappingURL=index-BDBCRrlL.js.map
diff --git a/web/assets/index-BDBCRrlL.js.map b/web/assets/index-BDBCRrlL.js.map
new file mode 100644
index 000000000..a0df5bfde
--- /dev/null
+++ b/web/assets/index-BDBCRrlL.js.map
@@ -0,0 +1 @@
+{"version":3,"file":"index-BDBCRrlL.js","sources":["../../src/extensions/core/clipspace.ts","../../src/extensions/core/colorPalette.ts","../../src/extensions/core/contextMenuFilter.ts","../../src/extensions/core/dynamicPrompts.ts","../../src/extensions/core/editAttention.ts","../../src/extensions/core/widgetInputs.ts","../../src/extensions/core/groupNodeManage.ts","../../src/extensions/core/groupNode.ts","../../src/extensions/core/groupOptions.ts","../../src/extensions/core/invertMenuScrolling.ts","../../src/extensions/core/keybinds.ts","../../src/extensions/core/linkRenderMode.ts","../../src/extensions/core/maskeditor.ts","../../src/extensions/core/nodeTemplates.ts","../../src/extensions/core/noteNode.ts","../../src/extensions/core/rerouteNode.ts","../../src/extensions/core/saveImageExtraOutput.ts","../../src/extensions/core/simpleTouchSupport.ts","../../src/extensions/core/slotDefaults.ts","../../src/extensions/core/snapToGrid.ts","../../src/extensions/core/uploadImage.ts","../../src/extensions/core/webcamCapture.ts","../../src/extensions/core/uploadAudio.ts","../../src/extensions/core/nodeBadge.ts"],"sourcesContent":["import { app } from '../../scripts/app'\nimport { ComfyDialog, $el } from '../../scripts/ui'\nimport { ComfyApp } from '../../scripts/app'\n\nexport class ClipspaceDialog extends ComfyDialog {\n static items = []\n static instance = null\n\n static registerButton(name, contextPredicate, callback) {\n const item = $el('button', {\n type: 'button',\n textContent: name,\n contextPredicate: contextPredicate,\n onclick: callback\n })\n\n ClipspaceDialog.items.push(item)\n }\n\n static invalidatePreview() {\n if (\n ComfyApp.clipspace &&\n ComfyApp.clipspace.imgs &&\n ComfyApp.clipspace.imgs.length > 0\n ) {\n const img_preview = document.getElementById(\n 'clipspace_preview'\n ) as HTMLImageElement\n if (img_preview) {\n img_preview.src =\n ComfyApp.clipspace.imgs[ComfyApp.clipspace['selectedIndex']].src\n img_preview.style.maxHeight = '100%'\n img_preview.style.maxWidth = '100%'\n }\n }\n }\n\n static invalidate() {\n if (ClipspaceDialog.instance) {\n const self = ClipspaceDialog.instance\n // allow reconstruct controls when copying from non-image to image content.\n const children = $el('div.comfy-modal-content', [\n self.createImgSettings(),\n ...self.createButtons()\n ])\n\n if (self.element) {\n // update\n self.element.removeChild(self.element.firstChild)\n self.element.appendChild(children)\n } else {\n // new\n self.element = $el('div.comfy-modal', { parent: document.body }, [\n children\n ])\n }\n\n if (self.element.children[0].children.length <= 1) {\n self.element.children[0].appendChild(\n $el('p', {}, [\n 'Unable to find the features to edit content of a format stored in the current Clipspace.'\n ])\n )\n }\n\n ClipspaceDialog.invalidatePreview()\n }\n }\n\n constructor() {\n super()\n }\n\n createButtons() {\n const buttons = []\n\n for (let idx in ClipspaceDialog.items) {\n const item = ClipspaceDialog.items[idx]\n if (!item.contextPredicate || item.contextPredicate())\n buttons.push(ClipspaceDialog.items[idx])\n }\n\n buttons.push(\n $el('button', {\n type: 'button',\n textContent: 'Close',\n onclick: () => {\n this.close()\n }\n })\n )\n\n return buttons\n }\n\n createImgSettings() {\n if (ComfyApp.clipspace.imgs) {\n const combo_items = []\n const imgs = ComfyApp.clipspace.imgs\n\n for (let i = 0; i < imgs.length; i++) {\n combo_items.push($el('option', { value: i }, [`${i}`]))\n }\n\n const combo1 = $el(\n 'select',\n {\n id: 'clipspace_img_selector',\n onchange: (event) => {\n ComfyApp.clipspace['selectedIndex'] = event.target.selectedIndex\n ClipspaceDialog.invalidatePreview()\n }\n },\n combo_items\n )\n\n const row1 = $el('tr', {}, [\n $el('td', {}, [$el('font', { color: 'white' }, ['Select Image'])]),\n $el('td', {}, [combo1])\n ])\n\n const combo2 = $el(\n 'select',\n {\n id: 'clipspace_img_paste_mode',\n onchange: (event) => {\n ComfyApp.clipspace['img_paste_mode'] = event.target.value\n }\n },\n [\n $el('option', { value: 'selected' }, 'selected'),\n $el('option', { value: 'all' }, 'all')\n ]\n ) as HTMLSelectElement\n combo2.value = ComfyApp.clipspace['img_paste_mode']\n\n const row2 = $el('tr', {}, [\n $el('td', {}, [$el('font', { color: 'white' }, ['Paste Mode'])]),\n $el('td', {}, [combo2])\n ])\n\n const td = $el(\n 'td',\n { align: 'center', width: '100px', height: '100px', colSpan: '2' },\n [$el('img', { id: 'clipspace_preview', ondragstart: () => false }, [])]\n )\n\n const row3 = $el('tr', {}, [td])\n\n return $el('table', {}, [row1, row2, row3])\n } else {\n return []\n }\n }\n\n createImgPreview() {\n if (ComfyApp.clipspace.imgs) {\n return $el('img', { id: 'clipspace_preview', ondragstart: () => false })\n } else return []\n }\n\n show() {\n const img_preview = document.getElementById('clipspace_preview')\n ClipspaceDialog.invalidate()\n\n this.element.style.display = 'block'\n }\n}\n\napp.registerExtension({\n name: 'Comfy.Clipspace',\n init(app) {\n // @ts-expect-error Move to ComfyApp\n app.openClipspace = function () {\n if (!ClipspaceDialog.instance) {\n ClipspaceDialog.instance = new ClipspaceDialog()\n ComfyApp.clipspace_invalidate_handler = ClipspaceDialog.invalidate\n }\n\n if (ComfyApp.clipspace) {\n ClipspaceDialog.instance.show()\n } else app.ui.dialog.show('Clipspace is Empty!')\n }\n }\n})\n","import { app } from '../../scripts/app'\nimport { $el } from '../../scripts/ui'\nimport type { ColorPalettes, Palette } from '@/types/colorPalette'\nimport { LGraphCanvas, LiteGraph } from '@comfyorg/litegraph'\n\n// Manage color palettes\n\nconst colorPalettes: ColorPalettes = {\n dark: {\n id: 'dark',\n name: 'Dark (Default)',\n colors: {\n node_slot: {\n CLIP: '#FFD500', // bright yellow\n CLIP_VISION: '#A8DADC', // light blue-gray\n CLIP_VISION_OUTPUT: '#ad7452', // rusty brown-orange\n CONDITIONING: '#FFA931', // vibrant orange-yellow\n CONTROL_NET: '#6EE7B7', // soft mint green\n IMAGE: '#64B5F6', // bright sky blue\n LATENT: '#FF9CF9', // light pink-purple\n MASK: '#81C784', // muted green\n MODEL: '#B39DDB', // light lavender-purple\n STYLE_MODEL: '#C2FFAE', // light green-yellow\n VAE: '#FF6E6E', // bright red\n NOISE: '#B0B0B0', // gray\n GUIDER: '#66FFFF', // cyan\n SAMPLER: '#ECB4B4', // very soft red\n SIGMAS: '#CDFFCD', // soft lime green\n TAESD: '#DCC274' // cheesecake\n },\n litegraph_base: {\n BACKGROUND_IMAGE:\n 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAIAAAD/gAIDAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAQBJREFUeNrs1rEKwjAUhlETUkj3vP9rdmr1Ysammk2w5wdxuLgcMHyptfawuZX4pJSWZTnfnu/lnIe/jNNxHHGNn//HNbbv+4dr6V+11uF527arU7+u63qfa/bnmh8sWLBgwYJlqRf8MEptXPBXJXa37BSl3ixYsGDBMliwFLyCV/DeLIMFCxYsWLBMwSt4Be/NggXLYMGCBUvBK3iNruC9WbBgwYJlsGApeAWv4L1ZBgsWLFiwYJmCV/AK3psFC5bBggULloJX8BpdwXuzYMGCBctgwVLwCl7Be7MMFixYsGDBsu8FH1FaSmExVfAxBa/gvVmwYMGCZbBg/W4vAQYA5tRF9QYlv/QAAAAASUVORK5CYII=',\n CLEAR_BACKGROUND_COLOR: '#222',\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\n WIDGET_BGCOLOR: '#222',\n WIDGET_OUTLINE_COLOR: '#666',\n WIDGET_TEXT_COLOR: '#DDD',\n WIDGET_SECONDARY_TEXT_COLOR: '#999',\n\n LINK_COLOR: '#9A9',\n EVENT_LINK_COLOR: '#A86',\n CONNECTING_LINK_COLOR: '#AFA',\n\n BADGE_FG_COLOR: '#FFF',\n BADGE_BG_COLOR: '#0F1F0F'\n },\n comfy_base: {\n 'fg-color': '#fff',\n 'bg-color': '#202020',\n 'comfy-menu-bg': '#353535',\n 'comfy-input-bg': '#222',\n 'input-text': '#ddd',\n 'descrip-text': '#999',\n 'drag-text': '#ccc',\n 'error-text': '#ff4444',\n 'border-color': '#4e4e4e',\n 'tr-even-bg-color': '#222',\n 'tr-odd-bg-color': '#353535',\n 'content-bg': '#4e4e4e',\n 'content-fg': '#fff',\n 'content-hover-bg': '#222',\n 'content-hover-fg': '#fff'\n }\n }\n },\n light: {\n id: 'light',\n name: 'Light',\n colors: {\n node_slot: {\n CLIP: '#FFA726', // orange\n CLIP_VISION: '#5C6BC0', // indigo\n CLIP_VISION_OUTPUT: '#8D6E63', // brown\n CONDITIONING: '#EF5350', // red\n CONTROL_NET: '#66BB6A', // green\n IMAGE: '#42A5F5', // blue\n LATENT: '#AB47BC', // purple\n MASK: '#9CCC65', // light green\n MODEL: '#7E57C2', // deep purple\n STYLE_MODEL: '#D4E157', // lime\n VAE: '#FF7043' // deep orange\n },\n litegraph_base: {\n BACKGROUND_IMAGE:\n 'data:image/gif;base64,R0lGODlhZABkALMAAAAAAP///+vr6+rq6ujo6Ofn5+bm5uXl5d3d3f///wAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAAkALAAAAABkAGQAAAT/UMhJq7046827HkcoHkYxjgZhnGG6si5LqnIM0/fL4qwwIMAg0CAsEovBIxKhRDaNy2GUOX0KfVFrssrNdpdaqTeKBX+dZ+jYvEaTf+y4W66mC8PUdrE879f9d2mBeoNLfH+IhYBbhIx2jkiHiomQlGKPl4uZe3CaeZifnnijgkESBqipqqusra6vsLGys62SlZO4t7qbuby7CLa+wqGWxL3Gv3jByMOkjc2lw8vOoNSi0czAncXW3Njdx9Pf48/Z4Kbbx+fQ5evZ4u3k1fKR6cn03vHlp7T9/v8A/8Gbp4+gwXoFryXMB2qgwoMMHyKEqA5fxX322FG8tzBcRnMW/zlulPbRncmQGidKjMjyYsOSKEF2FBlJQMCbOHP6c9iSZs+UnGYCdbnSo1CZI5F64kn0p1KnTH02nSoV3dGTV7FFHVqVq1dtWcMmVQZTbNGu72zqXMuW7danVL+6e4t1bEy6MeueBYLXrNO5Ze36jQtWsOG97wIj1vt3St/DjTEORss4nNq2mDP3e7w4r1bFkSET5hy6s2TRlD2/mSxXtSHQhCunXo26NevCpmvD/UU6tuullzULH76q92zdZG/Ltv1a+W+osI/nRmyc+fRi1Xdbh+68+0vv10dH3+77KD/i6IdnX669/frn5Zsjh4/2PXju8+8bzc9/6fj27LFnX11/+IUnXWl7BJfegm79FyB9JOl3oHgSklefgxAC+FmFGpqHIYcCfkhgfCohSKKJVo044YUMttggiBkmp6KFXw1oII24oYhjiDByaKOOHcp3Y5BD/njikSkO+eBREQAAOw==',\n CLEAR_BACKGROUND_COLOR: 'lightgray',\n NODE_TITLE_COLOR: '#222',\n NODE_SELECTED_TITLE_COLOR: '#000',\n NODE_TEXT_SIZE: 14,\n NODE_TEXT_COLOR: '#444',\n NODE_SUBTEXT_SIZE: 12,\n NODE_DEFAULT_COLOR: '#F7F7F7',\n NODE_DEFAULT_BGCOLOR: '#F5F5F5',\n NODE_DEFAULT_BOXCOLOR: '#CCC',\n NODE_DEFAULT_SHAPE: 'box',\n NODE_BOX_OUTLINE_COLOR: '#000',\n DEFAULT_SHADOW_COLOR: 'rgba(0,0,0,0.1)',\n DEFAULT_GROUP_FONT: 24,\n\n WIDGET_BGCOLOR: '#D4D4D4',\n WIDGET_OUTLINE_COLOR: '#999',\n WIDGET_TEXT_COLOR: '#222',\n WIDGET_SECONDARY_TEXT_COLOR: '#555',\n\n LINK_COLOR: '#4CAF50',\n EVENT_LINK_COLOR: '#FF9800',\n CONNECTING_LINK_COLOR: '#2196F3',\n\n BADGE_FG_COLOR: '#000',\n BADGE_BG_COLOR: '#FFF'\n },\n comfy_base: {\n 'fg-color': '#222',\n 'bg-color': '#DDD',\n 'comfy-menu-bg': '#F5F5F5',\n 'comfy-input-bg': '#C9C9C9',\n 'input-text': '#222',\n 'descrip-text': '#444',\n 'drag-text': '#555',\n 'error-text': '#F44336',\n 'border-color': '#888',\n 'tr-even-bg-color': '#f9f9f9',\n 'tr-odd-bg-color': '#fff',\n 'content-bg': '#e0e0e0',\n 'content-fg': '#222',\n 'content-hover-bg': '#adadad',\n 'content-hover-fg': '#222'\n }\n }\n },\n solarized: {\n id: 'solarized',\n name: 'Solarized',\n colors: {\n node_slot: {\n CLIP: '#2AB7CA', // light blue\n CLIP_VISION: '#6c71c4', // blue violet\n CLIP_VISION_OUTPUT: '#859900', // olive green\n CONDITIONING: '#d33682', // magenta\n CONTROL_NET: '#d1ffd7', // light mint green\n IMAGE: '#5940bb', // deep blue violet\n LATENT: '#268bd2', // blue\n MASK: '#CCC9E7', // light purple-gray\n MODEL: '#dc322f', // red\n STYLE_MODEL: '#1a998a', // teal\n UPSCALE_MODEL: '#054A29', // dark green\n VAE: '#facfad' // light pink-orange\n },\n litegraph_base: {\n NODE_TITLE_COLOR: '#fdf6e3', // Base3\n NODE_SELECTED_TITLE_COLOR: '#A9D400',\n NODE_TEXT_SIZE: 14,\n NODE_TEXT_COLOR: '#657b83', // Base00\n NODE_SUBTEXT_SIZE: 12,\n NODE_DEFAULT_COLOR: '#094656',\n NODE_DEFAULT_BGCOLOR: '#073642', // Base02\n NODE_DEFAULT_BOXCOLOR: '#839496', // Base0\n NODE_DEFAULT_SHAPE: 'box',\n NODE_BOX_OUTLINE_COLOR: '#fdf6e3', // Base3\n DEFAULT_SHADOW_COLOR: 'rgba(0,0,0,0.5)',\n DEFAULT_GROUP_FONT: 24,\n\n WIDGET_BGCOLOR: '#002b36', // Base03\n WIDGET_OUTLINE_COLOR: '#839496', // Base0\n WIDGET_TEXT_COLOR: '#fdf6e3', // Base3\n WIDGET_SECONDARY_TEXT_COLOR: '#93a1a1', // Base1\n\n LINK_COLOR: '#2aa198', // Solarized Cyan\n EVENT_LINK_COLOR: '#268bd2', // Solarized Blue\n CONNECTING_LINK_COLOR: '#859900' // Solarized Green\n },\n comfy_base: {\n 'fg-color': '#fdf6e3', // Base3\n 'bg-color': '#002b36', // Base03\n 'comfy-menu-bg': '#073642', // Base02\n 'comfy-input-bg': '#002b36', // Base03\n 'input-text': '#93a1a1', // Base1\n 'descrip-text': '#586e75', // Base01\n 'drag-text': '#839496', // Base0\n 'error-text': '#dc322f', // Solarized Red\n 'border-color': '#657b83', // Base00\n 'tr-even-bg-color': '#002b36',\n 'tr-odd-bg-color': '#073642',\n 'content-bg': '#657b83',\n 'content-fg': '#fdf6e3',\n 'content-hover-bg': '#002b36',\n 'content-hover-fg': '#fdf6e3'\n }\n }\n },\n arc: {\n id: 'arc',\n name: 'Arc',\n colors: {\n node_slot: {\n BOOLEAN: '',\n CLIP: '#eacb8b',\n CLIP_VISION: '#A8DADC',\n CLIP_VISION_OUTPUT: '#ad7452',\n CONDITIONING: '#cf876f',\n CONTROL_NET: '#00d78d',\n CONTROL_NET_WEIGHTS: '',\n FLOAT: '',\n GLIGEN: '',\n IMAGE: '#80a1c0',\n IMAGEUPLOAD: '',\n INT: '',\n LATENT: '#b38ead',\n LATENT_KEYFRAME: '',\n MASK: '#a3bd8d',\n MODEL: '#8978a7',\n SAMPLER: '',\n SIGMAS: '',\n STRING: '',\n STYLE_MODEL: '#C2FFAE',\n T2I_ADAPTER_WEIGHTS: '',\n TAESD: '#DCC274',\n TIMESTEP_KEYFRAME: '',\n UPSCALE_MODEL: '',\n VAE: '#be616b'\n },\n litegraph_base: {\n BACKGROUND_IMAGE:\n 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAACXBIWXMAAAsTAAALEwEAmpwYAAABcklEQVR4nO3YMUoDARgF4RfxBqZI6/0vZqFn0MYtrLIQMFN8U6V4LAtD+Jm9XG/v30OGl2e/AP7yevz4+vx45nvgF/+QGITEICQGITEIiUFIjNNC3q43u3/YnRJyPOzeQ+0e220nhRzReC8e7R7bbdvl+Jal1Bs46jEIiUFIDEJiEBKDkBhKPbZT6qHdptRTu02p53DUYxASg5AYhMQgJAYhMZR6bKfUQ7tNqad2m1LP4ajHICQGITEIiUFIDEJiKPXYTqmHdptST+02pZ7DUY9BSAxCYhASg5AYhMRQ6rGdUg/tNqWe2m1KPYejHoOQGITEICQGITEIiaHUYzulHtptSj2125R6Dkc9BiExCIlBSAxCYhASQ6nHdko9tNuUemq3KfUcjnoMQmIQEoOQGITEICSGUo/tlHpotyn11G5T6jkc9RiExCAkBiExCIlBSAylHtsp9dBuU+qp3abUczjqMQiJQUgMQmIQEoOQGITE+AHFISNQrFTGuwAAAABJRU5ErkJggg==',\n CLEAR_BACKGROUND_COLOR: '#2b2f38',\n NODE_TITLE_COLOR: '#b2b7bd',\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: '#2b2f38',\n NODE_DEFAULT_BGCOLOR: '#242730',\n NODE_DEFAULT_BOXCOLOR: '#6e7581',\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: 22,\n WIDGET_BGCOLOR: '#2b2f38',\n WIDGET_OUTLINE_COLOR: '#6e7581',\n WIDGET_TEXT_COLOR: '#DDD',\n WIDGET_SECONDARY_TEXT_COLOR: '#b2b7bd',\n LINK_COLOR: '#9A9',\n EVENT_LINK_COLOR: '#A86',\n CONNECTING_LINK_COLOR: '#AFA'\n },\n comfy_base: {\n 'fg-color': '#fff',\n 'bg-color': '#2b2f38',\n 'comfy-menu-bg': '#242730',\n 'comfy-input-bg': '#2b2f38',\n 'input-text': '#ddd',\n 'descrip-text': '#b2b7bd',\n 'drag-text': '#ccc',\n 'error-text': '#ff4444',\n 'border-color': '#6e7581',\n 'tr-even-bg-color': '#2b2f38',\n 'tr-odd-bg-color': '#242730',\n 'content-bg': '#6e7581',\n 'content-fg': '#fff',\n 'content-hover-bg': '#2b2f38',\n 'content-hover-fg': '#fff'\n }\n }\n },\n nord: {\n id: 'nord',\n name: 'Nord',\n colors: {\n node_slot: {\n BOOLEAN: '',\n CLIP: '#eacb8b',\n CLIP_VISION: '#A8DADC',\n CLIP_VISION_OUTPUT: '#ad7452',\n CONDITIONING: '#cf876f',\n CONTROL_NET: '#00d78d',\n CONTROL_NET_WEIGHTS: '',\n FLOAT: '',\n GLIGEN: '',\n IMAGE: '#80a1c0',\n IMAGEUPLOAD: '',\n INT: '',\n LATENT: '#b38ead',\n LATENT_KEYFRAME: '',\n MASK: '#a3bd8d',\n MODEL: '#8978a7',\n SAMPLER: '',\n SIGMAS: '',\n STRING: '',\n STYLE_MODEL: '#C2FFAE',\n T2I_ADAPTER_WEIGHTS: '',\n TAESD: '#DCC274',\n TIMESTEP_KEYFRAME: '',\n UPSCALE_MODEL: '',\n VAE: '#be616b'\n },\n litegraph_base: {\n BACKGROUND_IMAGE:\n 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAIAAAD/gAIDAAA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Hl1WVcvy2DBggULFizTWQpewSt4HzwsgwULFiwFr7MUvMtS8D54WLBgGSxYCl7BK3iXZbBgwYIFC5bpLAWv4BW8Dx6WwYIFC5aC11kK3mUpeB88LFiwDBYsBa/gFbzLMliwYMGCBct0loJX8AreBw/LYMGCBUvB6ywF77IUvA8eFixYBgsWrNfWAZPltufdad+1AAAAAElFTkSuQmCC',\n CLEAR_BACKGROUND_COLOR: '#212732',\n NODE_TITLE_COLOR: '#999',\n NODE_SELECTED_TITLE_COLOR: '#e5eaf0',\n NODE_TEXT_SIZE: 14,\n NODE_TEXT_COLOR: '#bcc2c8',\n NODE_SUBTEXT_SIZE: 12,\n NODE_DEFAULT_COLOR: '#2e3440',\n NODE_DEFAULT_BGCOLOR: '#161b22',\n NODE_DEFAULT_BOXCOLOR: '#545d70',\n NODE_DEFAULT_SHAPE: 'box',\n NODE_BOX_OUTLINE_COLOR: '#e5eaf0',\n DEFAULT_SHADOW_COLOR: 'rgba(0,0,0,0.5)',\n DEFAULT_GROUP_FONT: 24,\n WIDGET_BGCOLOR: '#2e3440',\n WIDGET_OUTLINE_COLOR: '#545d70',\n WIDGET_TEXT_COLOR: '#bcc2c8',\n WIDGET_SECONDARY_TEXT_COLOR: '#999',\n LINK_COLOR: '#9A9',\n EVENT_LINK_COLOR: '#A86',\n CONNECTING_LINK_COLOR: '#AFA'\n },\n comfy_base: {\n 'fg-color': '#e5eaf0',\n 'bg-color': '#2e3440',\n 'comfy-menu-bg': '#161b22',\n 'comfy-input-bg': '#2e3440',\n 'input-text': '#bcc2c8',\n 'descrip-text': '#999',\n 'drag-text': '#ccc',\n 'error-text': '#ff4444',\n 'border-color': '#545d70',\n 'tr-even-bg-color': '#2e3440',\n 'tr-odd-bg-color': '#161b22',\n 'content-bg': '#545d70',\n 'content-fg': '#e5eaf0',\n 'content-hover-bg': '#2e3440',\n 'content-hover-fg': '#e5eaf0'\n }\n }\n },\n github: {\n id: 'github',\n name: 'Github',\n colors: {\n node_slot: {\n BOOLEAN: '',\n CLIP: '#eacb8b',\n CLIP_VISION: '#A8DADC',\n CLIP_VISION_OUTPUT: '#ad7452',\n CONDITIONING: '#cf876f',\n CONTROL_NET: '#00d78d',\n CONTROL_NET_WEIGHTS: '',\n FLOAT: '',\n GLIGEN: '',\n IMAGE: '#80a1c0',\n IMAGEUPLOAD: '',\n INT: '',\n LATENT: '#b38ead',\n LATENT_KEYFRAME: '',\n MASK: '#a3bd8d',\n MODEL: '#8978a7',\n SAMPLER: '',\n SIGMAS: '',\n STRING: '',\n STYLE_MODEL: '#C2FFAE',\n T2I_ADAPTER_WEIGHTS: '',\n TAESD: '#DCC274',\n TIMESTEP_KEYFRAME: '',\n UPSCALE_MODEL: '',\n VAE: '#be616b'\n },\n litegraph_base: {\n BACKGROUND_IMAGE:\n 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAIAAAD/gAIDAAAACXBIWXMAAAsTAAALEwEAmpwYAAAGlmlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4gPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iQWRvYmUgWE1QIENvcmUgOS4xLWMwMDEgNzkuMTQ2Mjg5OSwgMjAyMy8wNi8yNS0yMDowMTo1NSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczpkYz0iaHR0cDovL3B1cmwub3JnL2RjL2VsZW1lbnRzLzEuMS8iIHhtbG5zOnBob3Rvc2hvcD0iaHR0cDovL25zLmFkb2JlLmNvbS9waG90b3Nob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',\n NODE_TEXT_SIZE: 14,\n NODE_TEXT_COLOR: '#bcc2c8',\n NODE_SUBTEXT_SIZE: 12,\n NODE_DEFAULT_COLOR: '#161b22',\n NODE_DEFAULT_BGCOLOR: '#13171d',\n NODE_DEFAULT_BOXCOLOR: '#30363d',\n NODE_DEFAULT_SHAPE: 'box',\n NODE_BOX_OUTLINE_COLOR: '#e5eaf0',\n DEFAULT_SHADOW_COLOR: 'rgba(0,0,0,0.5)',\n DEFAULT_GROUP_FONT: 24,\n WIDGET_BGCOLOR: '#161b22',\n WIDGET_OUTLINE_COLOR: '#30363d',\n WIDGET_TEXT_COLOR: '#bcc2c8',\n WIDGET_SECONDARY_TEXT_COLOR: '#999',\n LINK_COLOR: '#9A9',\n EVENT_LINK_COLOR: '#A86',\n CONNECTING_LINK_COLOR: '#AFA'\n },\n comfy_base: {\n 'fg-color': '#e5eaf0',\n 'bg-color': '#161b22',\n 'comfy-menu-bg': '#13171d',\n 'comfy-input-bg': '#161b22',\n 'input-text': '#bcc2c8',\n 'descrip-text': '#999',\n 'drag-text': '#ccc',\n 'error-text': '#ff4444',\n 'border-color': '#30363d',\n 'tr-even-bg-color': '#161b22',\n 'tr-odd-bg-color': '#13171d',\n 'content-bg': '#30363d',\n 'content-fg': '#e5eaf0',\n 'content-hover-bg': '#161b22',\n 'content-hover-fg': '#e5eaf0'\n }\n }\n }\n}\n\nconst id = 'Comfy.ColorPalette'\nconst idCustomColorPalettes = 'Comfy.CustomColorPalettes'\nconst defaultColorPaletteId = 'dark'\nconst els: { select: HTMLSelectElement | null } = {\n select: null\n}\n\nconst getCustomColorPalettes = (): ColorPalettes => {\n return app.ui.settings.getSettingValue(idCustomColorPalettes, {})\n}\n\nconst setCustomColorPalettes = (customColorPalettes: ColorPalettes) => {\n return app.ui.settings.setSettingValue(\n idCustomColorPalettes,\n customColorPalettes\n )\n}\n\nexport const defaultColorPalette = colorPalettes[defaultColorPaletteId]\nexport const getColorPalette = (colorPaletteId?) => {\n if (!colorPaletteId) {\n colorPaletteId = app.ui.settings.getSettingValue(id, defaultColorPaletteId)\n }\n\n if (colorPaletteId.startsWith('custom_')) {\n colorPaletteId = colorPaletteId.substr(7)\n let customColorPalettes = getCustomColorPalettes()\n if (customColorPalettes[colorPaletteId]) {\n return customColorPalettes[colorPaletteId]\n }\n }\n\n return colorPalettes[colorPaletteId]\n}\n\nconst setColorPalette = (colorPaletteId) => {\n app.ui.settings.setSettingValue(id, colorPaletteId)\n}\n\n// const ctxMenu = LiteGraph.ContextMenu;\napp.registerExtension({\n name: id,\n init() {\n /**\n * Changes the background color of the canvas.\n *\n * @method updateBackground\n * @param {image} String\n * @param {clearBackgroundColor} String\n */\n // @ts-expect-error\n LGraphCanvas.prototype.updateBackground = function (\n image,\n clearBackgroundColor\n ) {\n this._bg_img = new Image()\n this._bg_img.name = image\n this._bg_img.src = image\n this._bg_img.onload = () => {\n this.draw(true, true)\n }\n this.background_image = image\n\n this.clear_background = true\n this.clear_background_color = clearBackgroundColor\n this._pattern = null\n }\n },\n addCustomNodeDefs(node_defs) {\n const sortObjectKeys = (unordered) => {\n return Object.keys(unordered)\n .sort()\n .reduce((obj, key) => {\n obj[key] = unordered[key]\n return obj\n }, {})\n }\n\n function getSlotTypes() {\n var types = []\n\n const defs = node_defs\n for (const nodeId in defs) {\n const nodeData = defs[nodeId]\n\n var inputs = nodeData['input']['required']\n if (nodeData['input']['optional'] !== undefined) {\n inputs = Object.assign(\n {},\n nodeData['input']['required'],\n nodeData['input']['optional']\n )\n }\n\n for (const inputName in inputs) {\n const inputData = inputs[inputName]\n const type = inputData[0]\n\n if (!Array.isArray(type)) {\n types.push(type)\n }\n }\n\n for (const o in nodeData['output']) {\n const output = nodeData['output'][o]\n types.push(output)\n }\n }\n\n return types\n }\n\n function completeColorPalette(colorPalette) {\n var types = getSlotTypes()\n\n for (const type of types) {\n if (!colorPalette.colors.node_slot[type]) {\n colorPalette.colors.node_slot[type] = ''\n }\n }\n\n colorPalette.colors.node_slot = sortObjectKeys(\n colorPalette.colors.node_slot\n )\n\n return colorPalette\n }\n\n const getColorPaletteTemplate = async () => {\n let colorPalette = {\n id: 'my_color_palette_unique_id',\n name: 'My Color Palette',\n colors: {\n node_slot: {},\n litegraph_base: {},\n comfy_base: {}\n }\n }\n\n // Copy over missing keys from default color palette\n const defaultColorPalette = colorPalettes[defaultColorPaletteId]\n for (const key in defaultColorPalette.colors.litegraph_base) {\n if (!colorPalette.colors.litegraph_base[key]) {\n colorPalette.colors.litegraph_base[key] = ''\n }\n }\n for (const key in defaultColorPalette.colors.comfy_base) {\n if (!colorPalette.colors.comfy_base[key]) {\n colorPalette.colors.comfy_base[key] = ''\n }\n }\n\n return completeColorPalette(colorPalette)\n }\n\n const addCustomColorPalette = async (colorPalette) => {\n if (typeof colorPalette !== 'object') {\n alert('Invalid color palette.')\n return\n }\n\n if (!colorPalette.id) {\n alert('Color palette missing id.')\n return\n }\n\n if (!colorPalette.name) {\n alert('Color palette missing name.')\n return\n }\n\n if (!colorPalette.colors) {\n alert('Color palette missing colors.')\n return\n }\n\n if (\n colorPalette.colors.node_slot &&\n typeof colorPalette.colors.node_slot !== 'object'\n ) {\n alert('Invalid color palette colors.node_slot.')\n return\n }\n\n const customColorPalettes = getCustomColorPalettes()\n customColorPalettes[colorPalette.id] = colorPalette\n setCustomColorPalettes(customColorPalettes)\n\n for (const option of els.select.childNodes) {\n if (\n (option as HTMLOptionElement).value ===\n 'custom_' + colorPalette.id\n ) {\n els.select.removeChild(option)\n }\n }\n\n els.select.append(\n $el('option', {\n textContent: colorPalette.name + ' (custom)',\n value: 'custom_' + colorPalette.id,\n selected: true\n })\n )\n\n setColorPalette('custom_' + colorPalette.id)\n await loadColorPalette(colorPalette)\n }\n\n const deleteCustomColorPalette = async (colorPaletteId) => {\n const customColorPalettes = getCustomColorPalettes()\n delete customColorPalettes[colorPaletteId]\n setCustomColorPalettes(customColorPalettes)\n\n for (const opt of els.select.childNodes) {\n const option = opt as HTMLOptionElement\n if (option.value === defaultColorPaletteId) {\n option.selected = true\n }\n\n if (option.value === 'custom_' + colorPaletteId) {\n els.select.removeChild(option)\n }\n }\n\n setColorPalette(defaultColorPaletteId)\n await loadColorPalette(getColorPalette())\n }\n\n const loadColorPalette = async (colorPalette: Palette) => {\n colorPalette = await completeColorPalette(colorPalette)\n if (colorPalette.colors) {\n // Sets the colors of node slots and links\n if (colorPalette.colors.node_slot) {\n Object.assign(\n // @ts-expect-error\n app.canvas.default_connection_color_byType,\n colorPalette.colors.node_slot\n )\n Object.assign(\n LGraphCanvas.link_type_colors,\n colorPalette.colors.node_slot\n )\n }\n // Sets the colors of the LiteGraph objects\n if (colorPalette.colors.litegraph_base) {\n // Everything updates correctly in the loop, except the Node Title and Link Color for some reason\n app.canvas.node_title_color =\n colorPalette.colors.litegraph_base.NODE_TITLE_COLOR\n app.canvas.default_link_color =\n colorPalette.colors.litegraph_base.LINK_COLOR\n\n for (const key in colorPalette.colors.litegraph_base) {\n if (\n colorPalette.colors.litegraph_base.hasOwnProperty(key) &&\n LiteGraph.hasOwnProperty(key)\n ) {\n LiteGraph[key] = colorPalette.colors.litegraph_base[key]\n }\n }\n }\n // Sets the color of ComfyUI elements\n if (colorPalette.colors.comfy_base) {\n const rootStyle = document.documentElement.style\n for (const key in colorPalette.colors.comfy_base) {\n rootStyle.setProperty(\n '--' + key,\n colorPalette.colors.comfy_base[key]\n )\n }\n }\n app.canvas.draw(true, true)\n }\n }\n\n const fileInput = $el('input', {\n type: 'file',\n accept: '.json',\n style: { display: 'none' },\n parent: document.body,\n onchange: () => {\n const file = fileInput.files[0]\n if (file.type === 'application/json' || file.name.endsWith('.json')) {\n const reader = new FileReader()\n reader.onload = async () => {\n await addCustomColorPalette(JSON.parse(reader.result as string))\n }\n reader.readAsText(file)\n }\n }\n }) as HTMLInputElement\n\n app.ui.settings.addSetting({\n id,\n category: ['Comfy', 'ColorPalette'],\n name: 'Color Palette',\n type: (name, setter, value) => {\n const options = [\n ...Object.values(colorPalettes).map((c) =>\n $el('option', {\n textContent: c.name,\n value: c.id,\n selected: c.id === value\n })\n ),\n ...Object.values(getCustomColorPalettes()).map((c) =>\n $el('option', {\n textContent: `${c.name} (custom)`,\n value: `custom_${c.id}`,\n selected: `custom_${c.id}` === value\n })\n )\n ]\n\n els.select = $el(\n 'select',\n {\n style: {\n marginBottom: '0.15rem',\n width: '100%'\n },\n onchange: (e) => {\n setter(e.target.value)\n }\n },\n options\n ) as HTMLSelectElement\n\n return $el('tr', [\n $el('td', [\n els.select,\n $el(\n 'div',\n {\n style: {\n display: 'grid',\n gap: '4px',\n gridAutoFlow: 'column'\n }\n },\n [\n $el('input', {\n type: 'button',\n value: 'Export',\n onclick: async () => {\n const colorPaletteId = app.ui.settings.getSettingValue(\n id,\n defaultColorPaletteId\n )\n const colorPalette = await completeColorPalette(\n getColorPalette(colorPaletteId)\n )\n const json = JSON.stringify(colorPalette, null, 2) // convert the data to a JSON string\n const blob = new Blob([json], { type: 'application/json' })\n const url = URL.createObjectURL(blob)\n const a = $el('a', {\n href: url,\n download: colorPaletteId + '.json',\n style: { display: 'none' },\n parent: document.body\n })\n a.click()\n setTimeout(function () {\n a.remove()\n window.URL.revokeObjectURL(url)\n }, 0)\n }\n }),\n $el('input', {\n type: 'button',\n value: 'Import',\n onclick: () => {\n fileInput.click()\n }\n }),\n $el('input', {\n type: 'button',\n value: 'Template',\n onclick: async () => {\n const colorPalette = await getColorPaletteTemplate()\n const json = JSON.stringify(colorPalette, null, 2) // convert the data to a JSON string\n const blob = new Blob([json], { type: 'application/json' })\n const url = URL.createObjectURL(blob)\n const a = $el('a', {\n href: url,\n download: 'color_palette.json',\n style: { display: 'none' },\n parent: document.body\n })\n a.click()\n setTimeout(function () {\n a.remove()\n window.URL.revokeObjectURL(url)\n }, 0)\n }\n }),\n $el('input', {\n type: 'button',\n value: 'Delete',\n onclick: async () => {\n let colorPaletteId = app.ui.settings.getSettingValue(\n id,\n defaultColorPaletteId\n )\n\n if (colorPalettes[colorPaletteId]) {\n alert('You cannot delete a built-in color palette.')\n return\n }\n\n if (colorPaletteId.startsWith('custom_')) {\n colorPaletteId = colorPaletteId.substr(7)\n }\n\n await deleteCustomColorPalette(colorPaletteId)\n }\n })\n ]\n )\n ])\n ])\n },\n defaultValue: defaultColorPaletteId,\n async onChange(value) {\n if (!value) {\n return\n }\n\n let palette = colorPalettes[value]\n if (palette) {\n await loadColorPalette(palette)\n } else if (value.startsWith('custom_')) {\n value = value.substr(7)\n let customColorPalettes = getCustomColorPalettes()\n if (customColorPalettes[value]) {\n palette = customColorPalettes[value]\n await loadColorPalette(customColorPalettes[value])\n }\n }\n\n let { BACKGROUND_IMAGE, CLEAR_BACKGROUND_COLOR } =\n palette.colors.litegraph_base\n if (\n BACKGROUND_IMAGE === undefined ||\n CLEAR_BACKGROUND_COLOR === undefined\n ) {\n const base = colorPalettes['dark'].colors.litegraph_base\n BACKGROUND_IMAGE = base.BACKGROUND_IMAGE\n CLEAR_BACKGROUND_COLOR = base.CLEAR_BACKGROUND_COLOR\n }\n // @ts-expect-error\n // litegraph.extensions.js\n app.canvas.updateBackground(BACKGROUND_IMAGE, CLEAR_BACKGROUND_COLOR)\n }\n })\n }\n})\n","import { LiteGraph, LGraphCanvas } from '@comfyorg/litegraph'\nimport { app } from '../../scripts/app'\n\n// Adds filtering to combo context menus\n\nconst ext = {\n name: 'Comfy.ContextMenuFilter',\n init() {\n const ctxMenu = LiteGraph.ContextMenu\n\n // @ts-expect-error TODO Very hacky way to modify Litegraph behaviour. Fix ctx later.\n LiteGraph.ContextMenu = function (values, options) {\n const ctx = new ctxMenu(values, options)\n\n // If we are a dark menu (only used for combo boxes) then add a filter input\n if (options?.className === 'dark' && values?.length > 4) {\n const filter = document.createElement('input')\n filter.classList.add('comfy-context-menu-filter')\n filter.placeholder = 'Filter list'\n\n ctx.root.prepend(filter)\n\n const items = Array.from(\n ctx.root.querySelectorAll('.litemenu-entry')\n ) as HTMLElement[]\n let displayedItems = [...items]\n let itemCount = displayedItems.length\n\n // We must request an animation frame for the current node of the active canvas to update.\n requestAnimationFrame(() => {\n // @ts-expect-error\n const currentNode = LGraphCanvas.active_canvas.current_node\n const clickedComboValue = currentNode.widgets\n ?.filter(\n (w) =>\n w.type === 'combo' && w.options.values.length === values.length\n )\n .find((w) =>\n w.options.values.every((v, i) => v === values[i])\n )?.value\n\n let selectedIndex = clickedComboValue\n ? values.findIndex((v) => v === clickedComboValue)\n : 0\n if (selectedIndex < 0) {\n selectedIndex = 0\n }\n let selectedItem = displayedItems[selectedIndex]\n updateSelected()\n\n // Apply highlighting to the selected item\n function updateSelected() {\n selectedItem?.style.setProperty('background-color', '')\n selectedItem?.style.setProperty('color', '')\n selectedItem = displayedItems[selectedIndex]\n selectedItem?.style.setProperty(\n 'background-color',\n '#ccc',\n 'important'\n )\n selectedItem?.style.setProperty('color', '#000', 'important')\n }\n\n const positionList = () => {\n const rect = ctx.root.getBoundingClientRect()\n\n // If the top is off-screen then shift the element with scaling applied\n if (rect.top < 0) {\n const scale =\n 1 -\n ctx.root.getBoundingClientRect().height / ctx.root.clientHeight\n\n const shift = (ctx.root.clientHeight * scale) / 2\n\n ctx.root.style.top = -shift + 'px'\n }\n }\n\n // Arrow up/down to select items\n filter.addEventListener('keydown', (event) => {\n switch (event.key) {\n case 'ArrowUp':\n event.preventDefault()\n if (selectedIndex === 0) {\n selectedIndex = itemCount - 1\n } else {\n selectedIndex--\n }\n updateSelected()\n break\n case 'ArrowRight':\n event.preventDefault()\n selectedIndex = itemCount - 1\n updateSelected()\n break\n case 'ArrowDown':\n event.preventDefault()\n if (selectedIndex === itemCount - 1) {\n selectedIndex = 0\n } else {\n selectedIndex++\n }\n updateSelected()\n break\n case 'ArrowLeft':\n event.preventDefault()\n selectedIndex = 0\n updateSelected()\n break\n case 'Enter':\n selectedItem?.click()\n break\n case 'Escape':\n ctx.close()\n break\n }\n })\n\n filter.addEventListener('input', () => {\n // Hide all items that don't match our filter\n const term = filter.value.toLocaleLowerCase()\n // When filtering, recompute which items are visible for arrow up/down and maintain selection.\n displayedItems = items.filter((item) => {\n const isVisible =\n !term || item.textContent.toLocaleLowerCase().includes(term)\n item.style.display = isVisible ? 'block' : 'none'\n return isVisible\n })\n\n selectedIndex = 0\n if (displayedItems.includes(selectedItem)) {\n selectedIndex = displayedItems.findIndex(\n (d) => d === selectedItem\n )\n }\n itemCount = displayedItems.length\n\n updateSelected()\n\n // If we have an event then we can try and position the list under the source\n if (options.event) {\n let top = options.event.clientY - 10\n\n const bodyRect = document.body.getBoundingClientRect()\n\n const rootRect = ctx.root.getBoundingClientRect()\n if (\n bodyRect.height &&\n top > bodyRect.height - rootRect.height - 10\n ) {\n top = Math.max(0, bodyRect.height - rootRect.height - 10)\n }\n\n ctx.root.style.top = top + 'px'\n positionList()\n }\n })\n\n requestAnimationFrame(() => {\n // Focus the filter box when opening\n filter.focus()\n\n positionList()\n })\n })\n }\n\n return ctx\n }\n\n LiteGraph.ContextMenu.prototype = ctxMenu.prototype\n }\n}\n\napp.registerExtension(ext)\n","import { app } from '../../scripts/app'\n\n// Allows for simple dynamic prompt replacement\n// Inputs in the format {a|b} will have a random value of a or b chosen when the prompt is queued.\n\n/*\n * Strips C-style line and block comments from a string\n */\nfunction stripComments(str) {\n return str.replace(/\\/\\*[\\s\\S]*?\\*\\/|\\/\\/.*/g, '')\n}\n\napp.registerExtension({\n name: 'Comfy.DynamicPrompts',\n nodeCreated(node) {\n if (node.widgets) {\n // Locate dynamic prompt text widgets\n // Include any widgets with dynamicPrompts set to true, and customtext\n const widgets = node.widgets.filter((n) => n.dynamicPrompts)\n for (const widget of widgets) {\n // Override the serialization of the value to resolve dynamic prompts for all widgets supporting it in this node\n widget.serializeValue = (workflowNode, widgetIndex) => {\n let prompt = stripComments(widget.value)\n while (\n prompt.replace('\\\\{', '').includes('{') &&\n prompt.replace('\\\\}', '').includes('}')\n ) {\n const startIndex = prompt.replace('\\\\{', '00').indexOf('{')\n const endIndex = prompt.replace('\\\\}', '00').indexOf('}')\n\n const optionsString = prompt.substring(startIndex + 1, endIndex)\n const options = optionsString.split('|')\n\n const randomIndex = Math.floor(Math.random() * options.length)\n const randomOption = options[randomIndex]\n\n prompt =\n prompt.substring(0, startIndex) +\n randomOption +\n prompt.substring(endIndex + 1)\n }\n\n // Overwrite the value in the serialized workflow pnginfo\n if (workflowNode?.widgets_values)\n workflowNode.widgets_values[widgetIndex] = prompt\n\n return prompt\n }\n }\n }\n }\n})\n","import { app } from '../../scripts/app'\n\n// Allows you to edit the attention weight by holding ctrl (or cmd) and using the up/down arrow keys\n\napp.registerExtension({\n name: 'Comfy.EditAttention',\n init() {\n const editAttentionDelta = app.ui.settings.addSetting({\n id: 'Comfy.EditAttention.Delta',\n name: 'Ctrl+up/down precision',\n type: 'slider',\n attrs: {\n min: 0.01,\n max: 0.5,\n step: 0.01\n },\n defaultValue: 0.05\n })\n\n function incrementWeight(weight, delta) {\n const floatWeight = parseFloat(weight)\n if (isNaN(floatWeight)) return weight\n const newWeight = floatWeight + delta\n return String(Number(newWeight.toFixed(10)))\n }\n\n function findNearestEnclosure(text, cursorPos) {\n let start = cursorPos,\n end = cursorPos\n let openCount = 0,\n closeCount = 0\n\n // Find opening parenthesis before cursor\n while (start >= 0) {\n start--\n if (text[start] === '(' && openCount === closeCount) break\n if (text[start] === '(') openCount++\n if (text[start] === ')') closeCount++\n }\n if (start < 0) return false\n\n openCount = 0\n closeCount = 0\n\n // Find closing parenthesis after cursor\n while (end < text.length) {\n if (text[end] === ')' && openCount === closeCount) break\n if (text[end] === '(') openCount++\n if (text[end] === ')') closeCount++\n end++\n }\n if (end === text.length) return false\n\n return { start: start + 1, end: end }\n }\n\n function addWeightToParentheses(text) {\n const parenRegex = /^\\((.*)\\)$/\n const parenMatch = text.match(parenRegex)\n\n const floatRegex = /:([+-]?(\\d*\\.)?\\d+([eE][+-]?\\d+)?)/\n const floatMatch = text.match(floatRegex)\n\n if (parenMatch && !floatMatch) {\n return `(${parenMatch[1]}:1.0)`\n } else {\n return text\n }\n }\n\n function editAttention(event: KeyboardEvent) {\n // @ts-expect-error Runtime narrowing not impl.\n const inputField: HTMLTextAreaElement = event.composedPath()[0]\n const delta = parseFloat(editAttentionDelta.value)\n\n if (inputField.tagName !== 'TEXTAREA') return\n if (!(event.key === 'ArrowUp' || event.key === 'ArrowDown')) return\n if (!event.ctrlKey && !event.metaKey) return\n\n event.preventDefault()\n\n let start = inputField.selectionStart\n let end = inputField.selectionEnd\n let selectedText = inputField.value.substring(start, end)\n\n // If there is no selection, attempt to find the nearest enclosure, or select the current word\n if (!selectedText) {\n const nearestEnclosure = findNearestEnclosure(inputField.value, start)\n if (nearestEnclosure) {\n start = nearestEnclosure.start\n end = nearestEnclosure.end\n selectedText = inputField.value.substring(start, end)\n } else {\n // Select the current word, find the start and end of the word\n const delimiters = ' .,\\\\/!?%^*;:{}=-_`~()\\r\\n\\t'\n\n while (\n !delimiters.includes(inputField.value[start - 1]) &&\n start > 0\n ) {\n start--\n }\n\n while (\n !delimiters.includes(inputField.value[end]) &&\n end < inputField.value.length\n ) {\n end++\n }\n\n selectedText = inputField.value.substring(start, end)\n if (!selectedText) return\n }\n }\n\n // If the selection ends with a space, remove it\n if (selectedText[selectedText.length - 1] === ' ') {\n selectedText = selectedText.substring(0, selectedText.length - 1)\n end -= 1\n }\n\n // If there are parentheses left and right of the selection, select them\n if (\n inputField.value[start - 1] === '(' &&\n inputField.value[end] === ')'\n ) {\n start -= 1\n end += 1\n selectedText = inputField.value.substring(start, end)\n }\n\n // If the selection is not enclosed in parentheses, add them\n if (\n selectedText[0] !== '(' ||\n selectedText[selectedText.length - 1] !== ')'\n ) {\n selectedText = `(${selectedText})`\n }\n\n // If the selection does not have a weight, add a weight of 1.0\n selectedText = addWeightToParentheses(selectedText)\n\n // Increment the weight\n const weightDelta = event.key === 'ArrowUp' ? delta : -delta\n const updatedText = selectedText.replace(\n /\\((.*):([+-]?\\d+(?:\\.\\d+)?)\\)/,\n (match, text, weight) => {\n weight = incrementWeight(weight, weightDelta)\n if (weight == 1) {\n return text\n } else {\n return `(${text}:${weight})`\n }\n }\n )\n\n inputField.setSelectionRange(start, end)\n // Intentional use of deprecated: https://developer.mozilla.org/docs/Web/API/Document/execCommand#using_inserttext\n document.execCommand('insertText', false, updatedText)\n inputField.setSelectionRange(start, start + updatedText.length)\n }\n window.addEventListener('keydown', editAttention)\n }\n})\n","import { ComfyWidgets, addValueControlWidgets } from '../../scripts/widgets'\nimport { app } from '../../scripts/app'\nimport { applyTextReplacements } from '../../scripts/utils'\nimport { LiteGraph, LGraphNode } from '@comfyorg/litegraph'\nimport type { INodeInputSlot, IWidget } from '@comfyorg/litegraph'\n\nconst CONVERTED_TYPE = 'converted-widget'\nconst VALID_TYPES = ['STRING', 'combo', 'number', 'toggle', 'BOOLEAN']\nconst CONFIG = Symbol()\nconst GET_CONFIG = Symbol()\nconst TARGET = Symbol() // Used for reroutes to specify the real target widget\n\ninterface PrimitiveNode extends LGraphNode {}\n\nconst replacePropertyName = 'Run widget replace on values'\nclass PrimitiveNode extends LGraphNode {\n controlValues: any[]\n lastType: string\n static category: string\n constructor(title?: string) {\n super(title)\n this.addOutput('connect to widget input', '*')\n this.serialize_widgets = true\n this.isVirtualNode = true\n\n if (!this.properties || !(replacePropertyName in this.properties)) {\n this.addProperty(replacePropertyName, false, 'boolean')\n }\n }\n\n applyToGraph(extraLinks = []) {\n if (!this.outputs[0].links?.length) return\n\n function get_links(node) {\n let links = []\n for (const l of node.outputs[0].links) {\n const linkInfo = app.graph.links[l]\n const n = node.graph.getNodeById(linkInfo.target_id)\n if (n.type == 'Reroute') {\n links = links.concat(get_links(n))\n } else {\n links.push(l)\n }\n }\n return links\n }\n\n let links = [\n ...get_links(this).map((l) => app.graph.links[l]),\n ...extraLinks\n ]\n let v = this.widgets?.[0].value\n if (v && this.properties[replacePropertyName]) {\n v = applyTextReplacements(app, v)\n }\n\n // For each output link copy our value over the original widget value\n for (const linkInfo of links) {\n const node = this.graph.getNodeById(linkInfo.target_id)\n const input = node.inputs[linkInfo.target_slot]\n let widget\n if (input.widget[TARGET]) {\n widget = input.widget[TARGET]\n } else {\n const widgetName = (input.widget as { name: string }).name\n if (widgetName) {\n widget = node.widgets.find((w) => w.name === widgetName)\n }\n }\n\n if (widget) {\n widget.value = v\n if (widget.callback) {\n widget.callback(\n widget.value,\n app.canvas,\n node,\n app.canvas.graph_mouse,\n {}\n )\n }\n }\n }\n }\n\n refreshComboInNode() {\n const widget = this.widgets?.[0]\n if (widget?.type === 'combo') {\n widget.options.values = this.outputs[0].widget[GET_CONFIG]()[0]\n\n if (!widget.options.values.includes(widget.value)) {\n widget.value = widget.options.values[0]\n ;(widget.callback as Function)(widget.value)\n }\n }\n }\n\n onAfterGraphConfigured() {\n if (this.outputs[0].links?.length && !this.widgets?.length) {\n // TODO: Review this check\n // @ts-expect-error\n if (!this.#onFirstConnection()) return\n\n // Populate widget values from config data\n if (this.widgets) {\n for (let i = 0; i < this.widgets_values.length; i++) {\n const w = this.widgets[i]\n if (w) {\n w.value = this.widgets_values[i]\n }\n }\n }\n\n // Merge values if required\n this.#mergeWidgetConfig()\n }\n }\n\n onConnectionsChange(_, index, connected) {\n if (app.configuringGraph) {\n // Dont run while the graph is still setting up\n return\n }\n\n const links = this.outputs[0].links\n if (connected) {\n if (links?.length && !this.widgets?.length) {\n this.#onFirstConnection()\n }\n } else {\n // We may have removed a link that caused the constraints to change\n this.#mergeWidgetConfig()\n\n if (!links?.length) {\n this.onLastDisconnect()\n }\n }\n }\n\n onConnectOutput(slot, type, input, target_node, target_slot) {\n // Fires before the link is made allowing us to reject it if it isn't valid\n // No widget, we cant connect\n if (!input.widget) {\n if (!(input.type in ComfyWidgets)) return false\n }\n\n if (this.outputs[slot].links?.length) {\n const valid = this.#isValidConnection(input)\n if (valid) {\n // On connect of additional outputs, copy our value to their widget\n this.applyToGraph([{ target_id: target_node.id, target_slot }])\n }\n return valid\n }\n }\n\n #onFirstConnection(recreating?: boolean) {\n // First connection can fire before the graph is ready on initial load so random things can be missing\n if (!this.outputs[0].links) {\n this.onLastDisconnect()\n return\n }\n const linkId = this.outputs[0].links[0]\n const link = this.graph.links[linkId]\n if (!link) return\n\n const theirNode = this.graph.getNodeById(link.target_id)\n if (!theirNode || !theirNode.inputs) return\n\n const input = theirNode.inputs[link.target_slot]\n if (!input) return\n\n let widget\n if (!input.widget) {\n if (!(input.type in ComfyWidgets)) return\n widget = { name: input.name, [GET_CONFIG]: () => [input.type, {}] } //fake widget\n } else {\n widget = input.widget\n }\n\n const config = widget[GET_CONFIG]?.()\n if (!config) return\n\n const { type } = getWidgetType(config)\n // Update our output to restrict to the widget type\n this.outputs[0].type = type\n this.outputs[0].name = type\n this.outputs[0].widget = widget\n\n this.#createWidget(\n widget[CONFIG] ?? config,\n theirNode,\n widget.name,\n recreating,\n widget[TARGET]\n )\n }\n\n #createWidget(inputData, node, widgetName, recreating, targetWidget) {\n let type = inputData[0]\n\n if (type instanceof Array) {\n type = 'COMBO'\n }\n\n // Store current size as addWidget resizes the node\n const size = this.size\n let widget\n if (type in ComfyWidgets) {\n widget = (ComfyWidgets[type](this, 'value', inputData, app) || {}).widget\n } else {\n widget = this.addWidget(type, 'value', null, () => {}, {})\n }\n\n if (targetWidget) {\n widget.value = targetWidget.value\n } else if (node?.widgets && widget) {\n const theirWidget = node.widgets.find((w) => w.name === widgetName)\n if (theirWidget) {\n widget.value = theirWidget.value\n }\n }\n\n if (\n !inputData?.[1]?.control_after_generate &&\n (widget.type === 'number' || widget.type === 'combo')\n ) {\n let control_value = this.widgets_values?.[1]\n if (!control_value) {\n control_value = 'fixed'\n }\n addValueControlWidgets(\n this,\n widget,\n control_value as string,\n undefined,\n inputData\n )\n let filter = this.widgets_values?.[2]\n if (filter && this.widgets.length === 3) {\n this.widgets[2].value = filter\n }\n }\n\n // Restore any saved control values\n const controlValues = this.controlValues\n if (\n this.lastType === this.widgets[0].type &&\n controlValues?.length === this.widgets.length - 1\n ) {\n for (let i = 0; i < controlValues.length; i++) {\n this.widgets[i + 1].value = controlValues[i]\n }\n }\n\n // When our value changes, update other widgets to reflect our changes\n // e.g. so LoadImage shows correct image\n const callback = widget.callback\n const self = this\n widget.callback = function () {\n const r = callback ? callback.apply(this, arguments) : undefined\n self.applyToGraph()\n return r\n }\n\n // Use the biggest dimensions in case the widgets caused the node to grow\n this.size = [\n Math.max(this.size[0], size[0]),\n Math.max(this.size[1], size[1])\n ]\n\n if (!recreating) {\n // Grow our node more if required\n const sz = this.computeSize()\n if (this.size[0] < sz[0]) {\n this.size[0] = sz[0]\n }\n if (this.size[1] < sz[1]) {\n this.size[1] = sz[1]\n }\n\n requestAnimationFrame(() => {\n if (this.onResize) {\n this.onResize(this.size)\n }\n })\n }\n }\n\n recreateWidget() {\n const values = this.widgets?.map((w) => w.value)\n this.#removeWidgets()\n this.#onFirstConnection(true)\n if (values?.length) {\n for (let i = 0; i < this.widgets?.length; i++)\n this.widgets[i].value = values[i]\n }\n return this.widgets?.[0]\n }\n\n #mergeWidgetConfig() {\n // Merge widget configs if the node has multiple outputs\n const output = this.outputs[0]\n const links = output.links\n\n const hasConfig = !!output.widget[CONFIG]\n if (hasConfig) {\n delete output.widget[CONFIG]\n }\n\n if (links?.length < 2 && hasConfig) {\n // Copy the widget options from the source\n if (links.length) {\n this.recreateWidget()\n }\n\n return\n }\n\n const config1 = output.widget[GET_CONFIG]()\n const isNumber = config1[0] === 'INT' || config1[0] === 'FLOAT'\n if (!isNumber) return\n\n for (const linkId of links) {\n const link = app.graph.links[linkId]\n if (!link) continue // Can be null when removing a node\n\n const theirNode = app.graph.getNodeById(link.target_id)\n const theirInput = theirNode.inputs[link.target_slot]\n\n // Call is valid connection so it can merge the configs when validating\n this.#isValidConnection(theirInput, hasConfig)\n }\n }\n\n #isValidConnection(input: INodeInputSlot, forceUpdate?: boolean) {\n // Only allow connections where the configs match\n const output = this.outputs[0]\n const config2 = input.widget[GET_CONFIG]()\n return !!mergeIfValid.call(\n this,\n output,\n config2,\n forceUpdate,\n this.recreateWidget\n )\n }\n\n #removeWidgets() {\n if (this.widgets) {\n // Allow widgets to cleanup\n for (const w of this.widgets) {\n if (w.onRemove) {\n w.onRemove()\n }\n }\n\n // Temporarily store the current values in case the node is being recreated\n // e.g. by group node conversion\n this.controlValues = []\n this.lastType = this.widgets[0]?.type\n for (let i = 1; i < this.widgets.length; i++) {\n this.controlValues.push(this.widgets[i].value)\n }\n setTimeout(() => {\n delete this.lastType\n delete this.controlValues\n }, 15)\n this.widgets.length = 0\n }\n }\n\n onLastDisconnect() {\n // We cant remove + re-add the output here as if you drag a link over the same link\n // it removes, then re-adds, causing it to break\n this.outputs[0].type = '*'\n this.outputs[0].name = 'connect to widget input'\n delete this.outputs[0].widget\n\n this.#removeWidgets()\n }\n}\n\nexport function getWidgetConfig(slot) {\n return slot.widget[CONFIG] ?? slot.widget[GET_CONFIG]()\n}\n\nfunction getConfig(widgetName) {\n const { nodeData } = this.constructor\n return (\n nodeData?.input?.required?.[widgetName] ??\n nodeData?.input?.optional?.[widgetName]\n )\n}\n\nfunction isConvertibleWidget(widget, config) {\n return (\n (VALID_TYPES.includes(widget.type) || VALID_TYPES.includes(config[0])) &&\n !widget.options?.forceInput\n )\n}\n\nfunction hideWidget(node, widget, suffix = '') {\n if (widget.type?.startsWith(CONVERTED_TYPE)) return\n widget.origType = widget.type\n widget.origComputeSize = widget.computeSize\n widget.origSerializeValue = widget.serializeValue\n widget.computeSize = () => [0, -4] // -4 is due to the gap litegraph adds between widgets automatically\n widget.type = CONVERTED_TYPE + suffix\n widget.serializeValue = () => {\n // Prevent serializing the widget if we have no input linked\n if (!node.inputs) {\n return undefined\n }\n let node_input = node.inputs.find((i) => i.widget?.name === widget.name)\n\n if (!node_input || !node_input.link) {\n return undefined\n }\n return widget.origSerializeValue\n ? widget.origSerializeValue()\n : widget.value\n }\n\n // Hide any linked widgets, e.g. seed+seedControl\n if (widget.linkedWidgets) {\n for (const w of widget.linkedWidgets) {\n hideWidget(node, w, ':' + widget.name)\n }\n }\n}\n\nfunction showWidget(widget) {\n widget.type = widget.origType\n widget.computeSize = widget.origComputeSize\n widget.serializeValue = widget.origSerializeValue\n\n delete widget.origType\n delete widget.origComputeSize\n delete widget.origSerializeValue\n\n // Hide any linked widgets, e.g. seed+seedControl\n if (widget.linkedWidgets) {\n for (const w of widget.linkedWidgets) {\n showWidget(w)\n }\n }\n}\n\nfunction convertToInput(node, widget, config) {\n hideWidget(node, widget)\n\n const { type } = getWidgetType(config)\n\n // Add input and store widget config for creating on primitive node\n const sz = node.size\n node.addInput(widget.name, type, {\n widget: { name: widget.name, [GET_CONFIG]: () => config }\n })\n\n for (const widget of node.widgets) {\n widget.last_y += LiteGraph.NODE_SLOT_HEIGHT\n }\n\n // Restore original size but grow if needed\n node.setSize([Math.max(sz[0], node.size[0]), Math.max(sz[1], node.size[1])])\n}\n\nfunction convertToWidget(node, widget) {\n showWidget(widget)\n const sz = node.size\n node.removeInput(node.inputs.findIndex((i) => i.widget?.name === widget.name))\n\n for (const widget of node.widgets) {\n widget.last_y -= LiteGraph.NODE_SLOT_HEIGHT\n }\n\n // Restore original size but grow if needed\n node.setSize([Math.max(sz[0], node.size[0]), Math.max(sz[1], node.size[1])])\n}\n\nfunction getWidgetType(config) {\n // Special handling for COMBO so we restrict links based on the entries\n let type = config[0]\n if (type instanceof Array) {\n type = 'COMBO'\n }\n return { type }\n}\n\nfunction isValidCombo(combo, obj) {\n // New input isnt a combo\n if (!(obj instanceof Array)) {\n console.log(`connection rejected: tried to connect combo to ${obj}`)\n return false\n }\n // New input combo has a different size\n if (combo.length !== obj.length) {\n console.log(`connection rejected: combo lists dont match`)\n return false\n }\n // New input combo has different elements\n if (combo.find((v, i) => obj[i] !== v)) {\n console.log(`connection rejected: combo lists dont match`)\n return false\n }\n\n return true\n}\n\nfunction isPrimitiveNode(node: LGraphNode): node is PrimitiveNode {\n return node.type === 'PrimitiveNode'\n}\n\nexport function setWidgetConfig(slot, config, target?: IWidget) {\n if (!slot.widget) return\n if (config) {\n slot.widget[GET_CONFIG] = () => config\n slot.widget[TARGET] = target\n } else {\n delete slot.widget\n }\n\n if (slot.link) {\n const link = app.graph.links[slot.link]\n if (link) {\n const originNode = app.graph.getNodeById(link.origin_id)\n if (isPrimitiveNode(originNode)) {\n if (config) {\n originNode.recreateWidget()\n } else if (!app.configuringGraph) {\n originNode.disconnectOutput(0)\n originNode.onLastDisconnect()\n }\n }\n }\n }\n}\n\nexport function mergeIfValid(\n output,\n config2,\n forceUpdate?: boolean,\n recreateWidget?: () => void,\n config1?: unknown\n) {\n if (!config1) {\n config1 = output.widget[CONFIG] ?? output.widget[GET_CONFIG]()\n }\n\n if (config1[0] instanceof Array) {\n if (!isValidCombo(config1[0], config2[0])) return\n } else if (config1[0] !== config2[0]) {\n // Types dont match\n console.log(`connection rejected: types dont match`, config1[0], config2[0])\n return\n }\n\n const keys = new Set([\n ...Object.keys(config1[1] ?? {}),\n ...Object.keys(config2[1] ?? {})\n ])\n\n let customConfig\n const getCustomConfig = () => {\n if (!customConfig) {\n if (typeof structuredClone === 'undefined') {\n customConfig = JSON.parse(JSON.stringify(config1[1] ?? {}))\n } else {\n customConfig = structuredClone(config1[1] ?? {})\n }\n }\n return customConfig\n }\n\n const isNumber = config1[0] === 'INT' || config1[0] === 'FLOAT'\n for (const k of keys.values()) {\n if (\n k !== 'default' &&\n k !== 'forceInput' &&\n k !== 'defaultInput' &&\n k !== 'control_after_generate' &&\n k !== 'multiline' &&\n k !== 'tooltip'\n ) {\n let v1 = config1[1][k]\n let v2 = config2[1]?.[k]\n\n if (v1 === v2 || (!v1 && !v2)) continue\n\n if (isNumber) {\n if (k === 'min') {\n const theirMax = config2[1]?.['max']\n if (theirMax != null && v1 > theirMax) {\n console.log('connection rejected: min > max', v1, theirMax)\n return\n }\n getCustomConfig()[k] =\n v1 == null ? v2 : v2 == null ? v1 : Math.max(v1, v2)\n continue\n } else if (k === 'max') {\n const theirMin = config2[1]?.['min']\n if (theirMin != null && v1 < theirMin) {\n console.log('connection rejected: max < min', v1, theirMin)\n return\n }\n getCustomConfig()[k] =\n v1 == null ? v2 : v2 == null ? v1 : Math.min(v1, v2)\n continue\n } else if (k === 'step') {\n let step\n if (v1 == null) {\n // No current step\n step = v2\n } else if (v2 == null) {\n // No new step\n step = v1\n } else {\n if (v1 < v2) {\n // Ensure v1 is larger for the mod\n const a = v2\n v2 = v1\n v1 = a\n }\n if (v1 % v2) {\n console.log(\n 'connection rejected: steps not divisible',\n 'current:',\n v1,\n 'new:',\n v2\n )\n return\n }\n\n step = v1\n }\n\n getCustomConfig()[k] = step\n continue\n }\n }\n\n console.log(`connection rejected: config ${k} values dont match`, v1, v2)\n return\n }\n }\n\n if (customConfig || forceUpdate) {\n if (customConfig) {\n output.widget[CONFIG] = [config1[0], customConfig]\n }\n\n const widget = recreateWidget?.call(this)\n // When deleting a node this can be null\n if (widget) {\n const min = widget.options.min\n const max = widget.options.max\n if (min != null && widget.value < min) widget.value = min\n if (max != null && widget.value > max) widget.value = max\n widget.callback(widget.value)\n }\n }\n\n return { customConfig }\n}\n\nlet useConversionSubmenusSetting\napp.registerExtension({\n name: 'Comfy.WidgetInputs',\n init() {\n useConversionSubmenusSetting = app.ui.settings.addSetting({\n id: 'Comfy.NodeInputConversionSubmenus',\n name: 'In the node context menu, place the entries that convert between input/widget in sub-menus.',\n type: 'boolean',\n defaultValue: true\n })\n },\n async beforeRegisterNodeDef(nodeType, nodeData, app) {\n // Add menu options to convert to/from widgets\n const origGetExtraMenuOptions = nodeType.prototype.getExtraMenuOptions\n nodeType.prototype.convertWidgetToInput = function (widget) {\n const config = getConfig.call(this, widget.name) ?? [\n widget.type,\n widget.options || {}\n ]\n if (!isConvertibleWidget(widget, config)) return false\n convertToInput(this, widget, config)\n return true\n }\n nodeType.prototype.getExtraMenuOptions = function (_, options) {\n const r = origGetExtraMenuOptions\n ? origGetExtraMenuOptions.apply(this, arguments)\n : undefined\n\n if (this.widgets) {\n let toInput = []\n let toWidget = []\n for (const w of this.widgets) {\n if (w.options?.forceInput) {\n continue\n }\n if (w.type === CONVERTED_TYPE) {\n toWidget.push({\n content: `Convert ${w.name} to widget`,\n callback: () => convertToWidget(this, w)\n })\n } else {\n const config = getConfig.call(this, w.name) ?? [\n w.type,\n w.options || {}\n ]\n if (isConvertibleWidget(w, config)) {\n toInput.push({\n content: `Convert ${w.name} to input`,\n callback: () => convertToInput(this, w, config)\n })\n }\n }\n }\n\n //Convert.. main menu\n if (toInput.length) {\n if (useConversionSubmenusSetting.value) {\n options.push({\n content: 'Convert Widget to Input',\n submenu: {\n options: toInput\n }\n })\n } else {\n options.push(...toInput, null)\n }\n }\n if (toWidget.length) {\n if (useConversionSubmenusSetting.value) {\n options.push({\n content: 'Convert Input to Widget',\n submenu: {\n options: toWidget\n }\n })\n } else {\n options.push(...toWidget, null)\n }\n }\n }\n\n return r\n }\n\n nodeType.prototype.onGraphConfigured = function () {\n if (!this.inputs) return\n this.widgets ??= []\n\n for (const input of this.inputs) {\n if (input.widget) {\n if (!input.widget[GET_CONFIG]) {\n input.widget[GET_CONFIG] = () =>\n getConfig.call(this, input.widget.name)\n }\n\n // Cleanup old widget config\n if (input.widget.config) {\n if (input.widget.config[0] instanceof Array) {\n // If we are an old converted combo then replace the input type and the stored link data\n input.type = 'COMBO'\n\n const link = app.graph.links[input.link]\n if (link) {\n link.type = input.type\n }\n }\n delete input.widget.config\n }\n\n const w = this.widgets.find((w) => w.name === input.widget.name)\n if (w) {\n hideWidget(this, w)\n } else {\n convertToWidget(this, input)\n }\n }\n }\n }\n\n const origOnNodeCreated = nodeType.prototype.onNodeCreated\n nodeType.prototype.onNodeCreated = function () {\n const r = origOnNodeCreated ? origOnNodeCreated.apply(this) : undefined\n\n // When node is created, convert any force/default inputs\n if (!app.configuringGraph && this.widgets) {\n for (const w of this.widgets) {\n if (w?.options?.forceInput || w?.options?.defaultInput) {\n const config = getConfig.call(this, w.name) ?? [\n w.type,\n w.options || {}\n ]\n convertToInput(this, w, config)\n }\n }\n }\n\n return r\n }\n\n const origOnConfigure = nodeType.prototype.onConfigure\n nodeType.prototype.onConfigure = function () {\n const r = origOnConfigure\n ? origOnConfigure.apply(this, arguments)\n : undefined\n if (!app.configuringGraph && this.inputs) {\n // On copy + paste of nodes, ensure that widget configs are set up\n for (const input of this.inputs) {\n if (input.widget && !input.widget[GET_CONFIG]) {\n input.widget[GET_CONFIG] = () =>\n getConfig.call(this, input.widget.name)\n const w = this.widgets.find((w) => w.name === input.widget.name)\n if (w) {\n hideWidget(this, w)\n }\n }\n }\n }\n\n return r\n }\n\n function isNodeAtPos(pos) {\n for (const n of app.graph.nodes) {\n if (n.pos[0] === pos[0] && n.pos[1] === pos[1]) {\n return true\n }\n }\n return false\n }\n\n // Double click a widget input to automatically attach a primitive\n const origOnInputDblClick = nodeType.prototype.onInputDblClick\n const ignoreDblClick = Symbol()\n nodeType.prototype.onInputDblClick = function (slot) {\n const r = origOnInputDblClick\n ? origOnInputDblClick.apply(this, arguments)\n : undefined\n\n const input = this.inputs[slot]\n if (!input.widget || !input[ignoreDblClick]) {\n // Not a widget input or already handled input\n if (\n !(input.type in ComfyWidgets) &&\n !(input.widget[GET_CONFIG]?.()?.[0] instanceof Array)\n ) {\n return r //also Not a ComfyWidgets input or combo (do nothing)\n }\n }\n\n // Create a primitive node\n const node = LiteGraph.createNode('PrimitiveNode')\n app.graph.add(node)\n\n // Calculate a position that wont directly overlap another node\n const pos: [number, number] = [\n this.pos[0] - node.size[0] - 30,\n this.pos[1]\n ]\n while (isNodeAtPos(pos)) {\n pos[1] += LiteGraph.NODE_TITLE_HEIGHT\n }\n\n node.pos = pos\n node.connect(0, this, slot)\n node.title = input.name\n\n // Prevent adding duplicates due to triple clicking\n input[ignoreDblClick] = true\n setTimeout(() => {\n delete input[ignoreDblClick]\n }, 300)\n\n return r\n }\n\n // Prevent connecting COMBO lists to converted inputs that dont match types\n const onConnectInput = nodeType.prototype.onConnectInput\n nodeType.prototype.onConnectInput = function (\n targetSlot,\n type,\n output,\n originNode,\n originSlot\n ) {\n const v = onConnectInput?.(this, arguments)\n // Not a combo, ignore\n if (type !== 'COMBO') return v\n // Primitive output, allow that to handle\n if (originNode.outputs[originSlot].widget) return v\n\n // Ensure target is also a combo\n const targetCombo = this.inputs[targetSlot].widget?.[GET_CONFIG]?.()?.[0]\n if (!targetCombo || !(targetCombo instanceof Array)) return v\n\n // Check they match\n const originConfig =\n originNode.constructor?.nodeData?.output?.[originSlot]\n if (!originConfig || !isValidCombo(targetCombo, originConfig)) {\n return false\n }\n\n return v\n }\n },\n registerCustomNodes() {\n LiteGraph.registerNodeType(\n 'PrimitiveNode',\n Object.assign(PrimitiveNode, {\n title: 'Primitive'\n })\n )\n PrimitiveNode.category = 'utils'\n }\n})\n","import { $el, ComfyDialog } from '../../scripts/ui'\nimport { DraggableList } from '../../scripts/ui/draggableList'\nimport { GroupNodeConfig, GroupNodeHandler } from './groupNode'\nimport './groupNodeManage.css'\nimport { app, type ComfyApp } from '../../scripts/app'\nimport {\n LiteGraph,\n type LGraphNode,\n type LGraphNodeConstructor\n} from '@comfyorg/litegraph'\n\nconst ORDER: symbol = Symbol()\n\nfunction merge(target, source) {\n if (typeof target === 'object' && typeof source === 'object') {\n for (const key in source) {\n const sv = source[key]\n if (typeof sv === 'object') {\n let tv = target[key]\n if (!tv) tv = target[key] = {}\n merge(tv, source[key])\n } else {\n target[key] = sv\n }\n }\n }\n\n return target\n}\n\nexport class ManageGroupDialog extends ComfyDialog {\n tabs: Record<\n 'Inputs' | 'Outputs' | 'Widgets',\n { tab: HTMLAnchorElement; page: HTMLElement }\n >\n selectedNodeIndex: number | null | undefined\n selectedTab: keyof ManageGroupDialog['tabs'] = 'Inputs'\n selectedGroup: string | undefined\n modifications: Record<\n string,\n Record<\n string,\n Record<\n string,\n { name?: string | undefined; visible?: boolean | undefined }\n >\n >\n > = {}\n nodeItems: any[]\n app: ComfyApp\n groupNodeType: LGraphNodeConstructor\n groupNodeDef: any\n groupData: any\n\n innerNodesList: HTMLUListElement\n widgetsPage: HTMLElement\n inputsPage: HTMLElement\n outputsPage: HTMLElement\n draggable: any\n\n get selectedNodeInnerIndex() {\n return +this.nodeItems[this.selectedNodeIndex].dataset.nodeindex\n }\n\n constructor(app) {\n super()\n this.app = app\n this.element = $el('dialog.comfy-group-manage', {\n parent: document.body\n }) as HTMLDialogElement\n }\n\n changeTab(tab) {\n this.tabs[this.selectedTab].tab.classList.remove('active')\n this.tabs[this.selectedTab].page.classList.remove('active')\n this.tabs[tab].tab.classList.add('active')\n this.tabs[tab].page.classList.add('active')\n this.selectedTab = tab\n }\n\n changeNode(index, force?) {\n if (!force && this.selectedNodeIndex === index) return\n\n if (this.selectedNodeIndex != null) {\n this.nodeItems[this.selectedNodeIndex].classList.remove('selected')\n }\n this.nodeItems[index].classList.add('selected')\n this.selectedNodeIndex = index\n\n if (!this.buildInputsPage() && this.selectedTab === 'Inputs') {\n this.changeTab('Widgets')\n }\n if (!this.buildWidgetsPage() && this.selectedTab === 'Widgets') {\n this.changeTab('Outputs')\n }\n if (!this.buildOutputsPage() && this.selectedTab === 'Outputs') {\n this.changeTab('Inputs')\n }\n\n this.changeTab(this.selectedTab)\n }\n\n getGroupData() {\n this.groupNodeType =\n LiteGraph.registered_node_types['workflow/' + this.selectedGroup]\n this.groupNodeDef = this.groupNodeType.nodeData\n this.groupData = GroupNodeHandler.getGroupData(this.groupNodeType)\n }\n\n changeGroup(group, reset = true) {\n this.selectedGroup = group\n this.getGroupData()\n\n const nodes = this.groupData.nodeData.nodes\n this.nodeItems = nodes.map((n, i) =>\n $el(\n 'li.draggable-item',\n {\n dataset: {\n nodeindex: n.index + ''\n },\n onclick: () => {\n this.changeNode(i)\n }\n },\n [\n $el('span.drag-handle'),\n $el(\n 'div',\n {\n textContent: n.title ?? n.type\n },\n n.title\n ? $el('span', {\n textContent: n.type\n })\n : []\n )\n ]\n )\n )\n\n this.innerNodesList.replaceChildren(...this.nodeItems)\n\n if (reset) {\n this.selectedNodeIndex = null\n this.changeNode(0)\n } else {\n const items = this.draggable.getAllItems()\n let index = items.findIndex((item) => item.classList.contains('selected'))\n if (index === -1) index = this.selectedNodeIndex\n this.changeNode(index, true)\n }\n\n const ordered = [...nodes]\n this.draggable?.dispose()\n this.draggable = new DraggableList(this.innerNodesList, 'li')\n this.draggable.addEventListener(\n 'dragend',\n ({ detail: { oldPosition, newPosition } }) => {\n if (oldPosition === newPosition) return\n ordered.splice(newPosition, 0, ordered.splice(oldPosition, 1)[0])\n for (let i = 0; i < ordered.length; i++) {\n this.storeModification({\n nodeIndex: ordered[i].index,\n section: ORDER,\n prop: 'order',\n value: i\n })\n }\n }\n )\n }\n\n storeModification(props: {\n nodeIndex?: number\n section: symbol\n prop: string\n value: any\n }) {\n const { nodeIndex, section, prop, value } = props\n const groupMod = (this.modifications[this.selectedGroup] ??= {})\n const nodesMod = (groupMod.nodes ??= {})\n const nodeMod = (nodesMod[nodeIndex ?? this.selectedNodeInnerIndex] ??= {})\n const typeMod = (nodeMod[section] ??= {})\n if (typeof value === 'object') {\n const objMod = (typeMod[prop] ??= {})\n Object.assign(objMod, value)\n } else {\n typeMod[prop] = value\n }\n }\n\n getEditElement(section, prop, value, placeholder, checked, checkable = true) {\n if (value === placeholder) value = ''\n\n const mods =\n this.modifications[this.selectedGroup]?.nodes?.[\n this.selectedNodeInnerIndex\n ]?.[section]?.[prop]\n if (mods) {\n if (mods.name != null) {\n value = mods.name\n }\n if (mods.visible != null) {\n checked = mods.visible\n }\n }\n\n return $el('div', [\n $el('input', {\n value,\n placeholder,\n type: 'text',\n onchange: (e) => {\n this.storeModification({\n section,\n prop,\n value: { name: e.target.value }\n })\n }\n }),\n $el('label', { textContent: 'Visible' }, [\n $el('input', {\n type: 'checkbox',\n checked,\n disabled: !checkable,\n onchange: (e) => {\n this.storeModification({\n section,\n prop,\n value: { visible: !!e.target.checked }\n })\n }\n })\n ])\n ])\n }\n\n buildWidgetsPage() {\n const widgets =\n this.groupData.oldToNewWidgetMap[this.selectedNodeInnerIndex]\n const items = Object.keys(widgets ?? {})\n const type = app.graph.extra.groupNodes[this.selectedGroup]\n const config = type.config?.[this.selectedNodeInnerIndex]?.input\n this.widgetsPage.replaceChildren(\n ...items.map((oldName) => {\n return this.getEditElement(\n 'input',\n oldName,\n widgets[oldName],\n oldName,\n config?.[oldName]?.visible !== false\n )\n })\n )\n return !!items.length\n }\n\n buildInputsPage() {\n const inputs = this.groupData.nodeInputs[this.selectedNodeInnerIndex]\n const items = Object.keys(inputs ?? {})\n const type = app.graph.extra.groupNodes[this.selectedGroup]\n const config = type.config?.[this.selectedNodeInnerIndex]?.input\n this.inputsPage.replaceChildren(\n ...items\n .map((oldName) => {\n let value = inputs[oldName]\n if (!value) {\n return\n }\n\n return this.getEditElement(\n 'input',\n oldName,\n value,\n oldName,\n config?.[oldName]?.visible !== false\n )\n })\n .filter(Boolean)\n )\n return !!items.length\n }\n\n buildOutputsPage() {\n const nodes = this.groupData.nodeData.nodes\n const innerNodeDef = this.groupData.getNodeDef(\n nodes[this.selectedNodeInnerIndex]\n )\n const outputs = innerNodeDef?.output ?? []\n const groupOutputs =\n this.groupData.oldToNewOutputMap[this.selectedNodeInnerIndex]\n\n const type = app.graph.extra.groupNodes[this.selectedGroup]\n const config = type.config?.[this.selectedNodeInnerIndex]?.output\n const node = this.groupData.nodeData.nodes[this.selectedNodeInnerIndex]\n const checkable = node.type !== 'PrimitiveNode'\n this.outputsPage.replaceChildren(\n ...outputs\n .map((type, slot) => {\n const groupOutputIndex = groupOutputs?.[slot]\n const oldName = innerNodeDef.output_name?.[slot] ?? type\n let value = config?.[slot]?.name\n const visible = config?.[slot]?.visible || groupOutputIndex != null\n if (!value || value === oldName) {\n value = ''\n }\n return this.getEditElement(\n 'output',\n slot,\n value,\n oldName,\n visible,\n checkable\n )\n })\n .filter(Boolean)\n )\n return !!outputs.length\n }\n\n show(type?) {\n const groupNodes = Object.keys(app.graph.extra?.groupNodes ?? {}).sort(\n (a, b) => a.localeCompare(b)\n )\n\n this.innerNodesList = $el(\n 'ul.comfy-group-manage-list-items'\n ) as HTMLUListElement\n this.widgetsPage = $el('section.comfy-group-manage-node-page')\n this.inputsPage = $el('section.comfy-group-manage-node-page')\n this.outputsPage = $el('section.comfy-group-manage-node-page')\n const pages = $el('div', [\n this.widgetsPage,\n this.inputsPage,\n this.outputsPage\n ])\n\n this.tabs = [\n ['Inputs', this.inputsPage],\n ['Widgets', this.widgetsPage],\n ['Outputs', this.outputsPage]\n ].reduce((p, [name, page]: [string, HTMLElement]) => {\n p[name] = {\n tab: $el('a', {\n onclick: () => {\n this.changeTab(name)\n },\n textContent: name\n }),\n page\n }\n return p\n }, {}) as any\n\n const outer = $el('div.comfy-group-manage-outer', [\n $el('header', [\n $el('h2', 'Group Nodes'),\n $el(\n 'select',\n {\n onchange: (e) => {\n this.changeGroup(e.target.value)\n }\n },\n groupNodes.map((g) =>\n $el('option', {\n textContent: g,\n selected: 'workflow/' + g === type,\n value: g\n })\n )\n )\n ]),\n $el('main', [\n $el('section.comfy-group-manage-list', this.innerNodesList),\n $el('section.comfy-group-manage-node', [\n $el(\n 'header',\n Object.values(this.tabs).map((t) => t.tab)\n ),\n pages\n ])\n ]),\n $el('footer', [\n $el(\n 'button.comfy-btn',\n {\n onclick: (e) => {\n const node = app.graph.nodes.find(\n (n) => n.type === 'workflow/' + this.selectedGroup\n )\n if (node) {\n alert(\n 'This group node is in use in the current workflow, please first remove these.'\n )\n return\n }\n if (\n confirm(\n `Are you sure you want to remove the node: \"${this.selectedGroup}\"`\n )\n ) {\n delete app.graph.extra.groupNodes[this.selectedGroup]\n LiteGraph.unregisterNodeType('workflow/' + this.selectedGroup)\n }\n this.show()\n }\n },\n 'Delete Group Node'\n ),\n $el(\n 'button.comfy-btn',\n {\n onclick: async () => {\n let nodesByType\n let recreateNodes = []\n const types = {}\n for (const g in this.modifications) {\n const type = app.graph.extra.groupNodes[g]\n let config = (type.config ??= {})\n\n let nodeMods = this.modifications[g]?.nodes\n if (nodeMods) {\n const keys = Object.keys(nodeMods)\n if (nodeMods[keys[0]][ORDER]) {\n // If any node is reordered, they will all need sequencing\n const orderedNodes = []\n const orderedMods = {}\n const orderedConfig = {}\n\n for (const n of keys) {\n const order = nodeMods[n][ORDER].order\n orderedNodes[order] = type.nodes[+n]\n orderedMods[order] = nodeMods[n]\n orderedNodes[order].index = order\n }\n\n // Rewrite links\n for (const l of type.links) {\n if (l[0] != null) l[0] = type.nodes[l[0]].index\n if (l[2] != null) l[2] = type.nodes[l[2]].index\n }\n\n // Rewrite externals\n if (type.external) {\n for (const ext of type.external) {\n ext[0] = type.nodes[ext[0]]\n }\n }\n\n // Rewrite modifications\n for (const id of keys) {\n if (config[id]) {\n orderedConfig[type.nodes[id].index] = config[id]\n }\n delete config[id]\n }\n\n type.nodes = orderedNodes\n nodeMods = orderedMods\n type.config = config = orderedConfig\n }\n\n merge(config, nodeMods)\n }\n\n types[g] = type\n\n if (!nodesByType) {\n nodesByType = app.graph.nodes.reduce((p, n) => {\n p[n.type] ??= []\n p[n.type].push(n)\n return p\n }, {})\n }\n\n const nodes = nodesByType['workflow/' + g]\n if (nodes) recreateNodes.push(...nodes)\n }\n\n await GroupNodeConfig.registerFromWorkflow(types, {})\n\n for (const node of recreateNodes) {\n node.recreate()\n }\n\n this.modifications = {}\n this.app.graph.setDirtyCanvas(true, true)\n this.changeGroup(this.selectedGroup, false)\n }\n },\n 'Save'\n ),\n $el(\n 'button.comfy-btn',\n { onclick: () => this.element.close() },\n 'Close'\n )\n ])\n ])\n\n this.element.replaceChildren(outer)\n this.changeGroup(\n type ? groupNodes.find((g) => 'workflow/' + g === type) : groupNodes[0]\n )\n this.element.showModal()\n\n this.element.addEventListener('close', () => {\n this.draggable?.dispose()\n })\n }\n}\n","import { app } from '../../scripts/app'\nimport { api } from '../../scripts/api'\nimport { mergeIfValid } from './widgetInputs'\nimport { ManageGroupDialog } from './groupNodeManage'\nimport type { LGraphNode } from '@comfyorg/litegraph'\nimport { LGraphCanvas, LiteGraph } from '@comfyorg/litegraph'\nimport { useNodeDefStore } from '@/stores/nodeDefStore'\n\nconst GROUP = Symbol()\n\nconst Workflow = {\n InUse: {\n Free: 0,\n Registered: 1,\n InWorkflow: 2\n },\n isInUseGroupNode(name) {\n const id = `workflow/${name}`\n // Check if lready registered/in use in this workflow\n if (app.graph.extra?.groupNodes?.[name]) {\n if (app.graph.nodes.find((n) => n.type === id)) {\n return Workflow.InUse.InWorkflow\n } else {\n return Workflow.InUse.Registered\n }\n }\n return Workflow.InUse.Free\n },\n storeGroupNode(name, data) {\n let extra = app.graph.extra\n if (!extra) app.graph.extra = extra = {}\n let groupNodes = extra.groupNodes\n if (!groupNodes) extra.groupNodes = groupNodes = {}\n groupNodes[name] = data\n }\n}\n\nclass GroupNodeBuilder {\n nodes: LGraphNode[]\n nodeData: any\n\n constructor(nodes) {\n this.nodes = nodes\n }\n\n build() {\n const name = this.getName()\n if (!name) return\n\n // Sort the nodes so they are in execution order\n // this allows for widgets to be in the correct order when reconstructing\n this.sortNodes()\n\n this.nodeData = this.getNodeData()\n Workflow.storeGroupNode(name, this.nodeData)\n\n return { name, nodeData: this.nodeData }\n }\n\n getName() {\n const name = prompt('Enter group name')\n if (!name) return\n const used = Workflow.isInUseGroupNode(name)\n switch (used) {\n case Workflow.InUse.InWorkflow:\n alert(\n 'An in use group node with this name already exists embedded in this workflow, please remove any instances or use a new name.'\n )\n return\n case Workflow.InUse.Registered:\n if (\n !confirm(\n 'A group node with this name already exists embedded in this workflow, are you sure you want to overwrite it?'\n )\n ) {\n return\n }\n break\n }\n return name\n }\n\n sortNodes() {\n // Gets the builders nodes in graph execution order\n const nodesInOrder = app.graph.computeExecutionOrder(false)\n this.nodes = this.nodes\n .map((node) => ({ index: nodesInOrder.indexOf(node), node }))\n .sort((a, b) => a.index - b.index || a.node.id - b.node.id)\n .map(({ node }) => node)\n }\n\n getNodeData() {\n const storeLinkTypes = (config) => {\n // Store link types for dynamically typed nodes e.g. reroutes\n for (const link of config.links) {\n const origin = app.graph.getNodeById(link[4])\n const type = origin.outputs[link[1]].type\n link.push(type)\n }\n }\n\n const storeExternalLinks = (config) => {\n // Store any external links to the group in the config so when rebuilding we add extra slots\n config.external = []\n for (let i = 0; i < this.nodes.length; i++) {\n const node = this.nodes[i]\n if (!node.outputs?.length) continue\n for (let slot = 0; slot < node.outputs.length; slot++) {\n let hasExternal = false\n const output = node.outputs[slot]\n let type = output.type\n if (!output.links?.length) continue\n for (const l of output.links) {\n const link = app.graph.links[l]\n if (!link) continue\n if (type === '*') type = link.type\n\n if (!app.canvas.selected_nodes[link.target_id]) {\n hasExternal = true\n break\n }\n }\n if (hasExternal) {\n config.external.push([i, slot, type])\n }\n }\n }\n }\n\n // Use the built in copyToClipboard function to generate the node data we need\n const backup = localStorage.getItem('litegrapheditor_clipboard')\n try {\n // @ts-expect-error\n // TODO Figure out if copyToClipboard is really taking this param\n app.canvas.copyToClipboard(this.nodes)\n const config = JSON.parse(\n localStorage.getItem('litegrapheditor_clipboard')\n )\n\n storeLinkTypes(config)\n storeExternalLinks(config)\n\n return config\n } finally {\n localStorage.setItem('litegrapheditor_clipboard', backup)\n }\n }\n}\n\nexport class GroupNodeConfig {\n name: string\n nodeData: any\n inputCount: number\n oldToNewOutputMap: {}\n newToOldOutputMap: {}\n oldToNewInputMap: {}\n oldToNewWidgetMap: {}\n newToOldWidgetMap: {}\n primitiveDefs: {}\n widgetToPrimitive: {}\n primitiveToWidget: {}\n nodeInputs: {}\n outputVisibility: any[]\n nodeDef: any\n inputs: any[]\n linksFrom: {}\n linksTo: {}\n externalFrom: {}\n\n constructor(name, nodeData) {\n this.name = name\n this.nodeData = nodeData\n this.getLinks()\n\n this.inputCount = 0\n this.oldToNewOutputMap = {}\n this.newToOldOutputMap = {}\n this.oldToNewInputMap = {}\n this.oldToNewWidgetMap = {}\n this.newToOldWidgetMap = {}\n this.primitiveDefs = {}\n this.widgetToPrimitive = {}\n this.primitiveToWidget = {}\n this.nodeInputs = {}\n this.outputVisibility = []\n }\n\n async registerType(source = 'workflow') {\n this.nodeDef = {\n output: [],\n output_name: [],\n output_is_list: [],\n output_is_hidden: [],\n name: source + '/' + this.name,\n display_name: this.name,\n category: 'group nodes' + ('/' + source),\n input: { required: {} },\n description: `Group node combining ${this.nodeData.nodes\n .map((n) => n.type)\n .join(', ')}`,\n python_module: 'custom_nodes.' + this.name,\n\n [GROUP]: this\n }\n\n this.inputs = []\n const seenInputs = {}\n const seenOutputs = {}\n for (let i = 0; i < this.nodeData.nodes.length; i++) {\n const node = this.nodeData.nodes[i]\n node.index = i\n this.processNode(node, seenInputs, seenOutputs)\n }\n\n for (const p of this.#convertedToProcess) {\n p()\n }\n this.#convertedToProcess = null\n await app.registerNodeDef('workflow/' + this.name, this.nodeDef)\n useNodeDefStore().addNodeDef(this.nodeDef)\n }\n\n getLinks() {\n this.linksFrom = {}\n this.linksTo = {}\n this.externalFrom = {}\n\n // Extract links for easy lookup\n for (const l of this.nodeData.links) {\n const [sourceNodeId, sourceNodeSlot, targetNodeId, targetNodeSlot] = l\n\n // Skip links outside the copy config\n if (sourceNodeId == null) continue\n\n if (!this.linksFrom[sourceNodeId]) {\n this.linksFrom[sourceNodeId] = {}\n }\n if (!this.linksFrom[sourceNodeId][sourceNodeSlot]) {\n this.linksFrom[sourceNodeId][sourceNodeSlot] = []\n }\n this.linksFrom[sourceNodeId][sourceNodeSlot].push(l)\n\n if (!this.linksTo[targetNodeId]) {\n this.linksTo[targetNodeId] = {}\n }\n this.linksTo[targetNodeId][targetNodeSlot] = l\n }\n\n if (this.nodeData.external) {\n for (const ext of this.nodeData.external) {\n if (!this.externalFrom[ext[0]]) {\n this.externalFrom[ext[0]] = { [ext[1]]: ext[2] }\n } else {\n this.externalFrom[ext[0]][ext[1]] = ext[2]\n }\n }\n }\n }\n\n processNode(node, seenInputs, seenOutputs) {\n const def = this.getNodeDef(node)\n if (!def) return\n\n const inputs = { ...def.input?.required, ...def.input?.optional }\n\n this.inputs.push(this.processNodeInputs(node, seenInputs, inputs))\n if (def.output?.length) this.processNodeOutputs(node, seenOutputs, def)\n }\n\n getNodeDef(node) {\n const def = globalDefs[node.type]\n if (def) return def\n\n const linksFrom = this.linksFrom[node.index]\n if (node.type === 'PrimitiveNode') {\n // Skip as its not linked\n if (!linksFrom) return\n\n let type = linksFrom['0'][0][5]\n if (type === 'COMBO') {\n // Use the array items\n const source = node.outputs[0].widget.name\n const fromTypeName = this.nodeData.nodes[linksFrom['0'][0][2]].type\n const fromType = globalDefs[fromTypeName]\n const input =\n fromType.input.required[source] ?? fromType.input.optional[source]\n type = input[0]\n }\n\n const def = (this.primitiveDefs[node.index] = {\n input: {\n required: {\n value: [type, {}]\n }\n },\n output: [type],\n output_name: [],\n output_is_list: []\n })\n return def\n } else if (node.type === 'Reroute') {\n const linksTo = this.linksTo[node.index]\n if (linksTo && linksFrom && !this.externalFrom[node.index]?.[0]) {\n // Being used internally\n return null\n }\n\n let config = {}\n let rerouteType = '*'\n if (linksFrom) {\n for (const [, , id, slot] of linksFrom['0']) {\n const node = this.nodeData.nodes[id]\n const input = node.inputs[slot]\n if (rerouteType === '*') {\n rerouteType = input.type\n }\n if (input.widget) {\n const targetDef = globalDefs[node.type]\n const targetWidget =\n targetDef.input.required[input.widget.name] ??\n targetDef.input.optional[input.widget.name]\n\n const widget = [targetWidget[0], config]\n const res = mergeIfValid(\n {\n widget\n },\n targetWidget,\n false,\n null,\n widget\n )\n config = res?.customConfig ?? config\n }\n }\n } else if (linksTo) {\n const [id, slot] = linksTo['0']\n rerouteType = this.nodeData.nodes[id].outputs[slot].type\n } else {\n // Reroute used as a pipe\n for (const l of this.nodeData.links) {\n if (l[2] === node.index) {\n rerouteType = l[5]\n break\n }\n }\n if (rerouteType === '*') {\n // Check for an external link\n const t = this.externalFrom[node.index]?.[0]\n if (t) {\n rerouteType = t\n }\n }\n }\n\n // @ts-expect-error\n config.forceInput = true\n return {\n input: {\n required: {\n [rerouteType]: [rerouteType, config]\n }\n },\n output: [rerouteType],\n output_name: [],\n output_is_list: []\n }\n }\n\n console.warn(\n 'Skipping virtual node ' +\n node.type +\n ' when building group node ' +\n this.name\n )\n }\n\n getInputConfig(node, inputName, seenInputs, config, extra?) {\n const customConfig = this.nodeData.config?.[node.index]?.input?.[inputName]\n let name =\n customConfig?.name ??\n node.inputs?.find((inp) => inp.name === inputName)?.label ??\n inputName\n let key = name\n let prefix = ''\n // Special handling for primitive to include the title if it is set rather than just \"value\"\n if ((node.type === 'PrimitiveNode' && node.title) || name in seenInputs) {\n prefix = `${node.title ?? node.type} `\n key = name = `${prefix}${inputName}`\n if (name in seenInputs) {\n name = `${prefix}${seenInputs[name]} ${inputName}`\n }\n }\n seenInputs[key] = (seenInputs[key] ?? 1) + 1\n\n if (inputName === 'seed' || inputName === 'noise_seed') {\n if (!extra) extra = {}\n extra.control_after_generate = `${prefix}control_after_generate`\n }\n if (config[0] === 'IMAGEUPLOAD') {\n if (!extra) extra = {}\n extra.widget =\n this.oldToNewWidgetMap[node.index]?.[config[1]?.widget ?? 'image'] ??\n 'image'\n }\n\n if (extra) {\n config = [config[0], { ...config[1], ...extra }]\n }\n\n return { name, config, customConfig }\n }\n\n processWidgetInputs(inputs, node, inputNames, seenInputs) {\n const slots = []\n const converted = new Map()\n const widgetMap = (this.oldToNewWidgetMap[node.index] = {})\n for (const inputName of inputNames) {\n let widgetType = app.getWidgetType(inputs[inputName], inputName)\n if (widgetType) {\n const convertedIndex = node.inputs?.findIndex(\n (inp) => inp.name === inputName && inp.widget?.name === inputName\n )\n if (convertedIndex > -1) {\n // This widget has been converted to a widget\n // We need to store this in the correct position so link ids line up\n converted.set(convertedIndex, inputName)\n widgetMap[inputName] = null\n } else {\n // Normal widget\n const { name, config } = this.getInputConfig(\n node,\n inputName,\n seenInputs,\n inputs[inputName]\n )\n this.nodeDef.input.required[name] = config\n widgetMap[inputName] = name\n this.newToOldWidgetMap[name] = { node, inputName }\n }\n } else {\n // Normal input\n slots.push(inputName)\n }\n }\n return { converted, slots }\n }\n\n checkPrimitiveConnection(link, inputName, inputs) {\n const sourceNode = this.nodeData.nodes[link[0]]\n if (sourceNode.type === 'PrimitiveNode') {\n // Merge link configurations\n const [sourceNodeId, _, targetNodeId, __] = link\n const primitiveDef = this.primitiveDefs[sourceNodeId]\n const targetWidget = inputs[inputName]\n const primitiveConfig = primitiveDef.input.required.value\n const output = { widget: primitiveConfig }\n const config = mergeIfValid(\n output,\n targetWidget,\n false,\n null,\n primitiveConfig\n )\n primitiveConfig[1] =\n config?.customConfig ?? inputs[inputName][1]\n ? { ...inputs[inputName][1] }\n : {}\n\n let name = this.oldToNewWidgetMap[sourceNodeId]['value']\n name = name.substr(0, name.length - 6)\n primitiveConfig[1].control_after_generate = true\n primitiveConfig[1].control_prefix = name\n\n let toPrimitive = this.widgetToPrimitive[targetNodeId]\n if (!toPrimitive) {\n toPrimitive = this.widgetToPrimitive[targetNodeId] = {}\n }\n if (toPrimitive[inputName]) {\n toPrimitive[inputName].push(sourceNodeId)\n }\n toPrimitive[inputName] = sourceNodeId\n\n let toWidget = this.primitiveToWidget[sourceNodeId]\n if (!toWidget) {\n toWidget = this.primitiveToWidget[sourceNodeId] = []\n }\n toWidget.push({ nodeId: targetNodeId, inputName })\n }\n }\n\n processInputSlots(inputs, node, slots, linksTo, inputMap, seenInputs) {\n this.nodeInputs[node.index] = {}\n for (let i = 0; i < slots.length; i++) {\n const inputName = slots[i]\n if (linksTo[i]) {\n this.checkPrimitiveConnection(linksTo[i], inputName, inputs)\n // This input is linked so we can skip it\n continue\n }\n\n const { name, config, customConfig } = this.getInputConfig(\n node,\n inputName,\n seenInputs,\n inputs[inputName]\n )\n\n this.nodeInputs[node.index][inputName] = name\n if (customConfig?.visible === false) continue\n\n this.nodeDef.input.required[name] = config\n inputMap[i] = this.inputCount++\n }\n }\n\n processConvertedWidgets(\n inputs,\n node,\n slots,\n converted,\n linksTo,\n inputMap,\n seenInputs\n ) {\n // Add converted widgets sorted into their index order (ordered as they were converted) so link ids match up\n const convertedSlots = [...converted.keys()]\n .sort()\n .map((k) => converted.get(k))\n for (let i = 0; i < convertedSlots.length; i++) {\n const inputName = convertedSlots[i]\n if (linksTo[slots.length + i]) {\n this.checkPrimitiveConnection(\n linksTo[slots.length + i],\n inputName,\n inputs\n )\n // This input is linked so we can skip it\n continue\n }\n\n const { name, config } = this.getInputConfig(\n node,\n inputName,\n seenInputs,\n inputs[inputName],\n {\n defaultInput: true\n }\n )\n\n this.nodeDef.input.required[name] = config\n this.newToOldWidgetMap[name] = { node, inputName }\n\n if (!this.oldToNewWidgetMap[node.index]) {\n this.oldToNewWidgetMap[node.index] = {}\n }\n this.oldToNewWidgetMap[node.index][inputName] = name\n\n inputMap[slots.length + i] = this.inputCount++\n }\n }\n\n #convertedToProcess = []\n processNodeInputs(node, seenInputs, inputs) {\n const inputMapping = []\n\n const inputNames = Object.keys(inputs)\n if (!inputNames.length) return\n\n const { converted, slots } = this.processWidgetInputs(\n inputs,\n node,\n inputNames,\n seenInputs\n )\n const linksTo = this.linksTo[node.index] ?? {}\n const inputMap = (this.oldToNewInputMap[node.index] = {})\n this.processInputSlots(inputs, node, slots, linksTo, inputMap, seenInputs)\n\n // Converted inputs have to be processed after all other nodes as they'll be at the end of the list\n this.#convertedToProcess.push(() =>\n this.processConvertedWidgets(\n inputs,\n node,\n slots,\n converted,\n linksTo,\n inputMap,\n seenInputs\n )\n )\n\n return inputMapping\n }\n\n processNodeOutputs(node, seenOutputs, def) {\n const oldToNew = (this.oldToNewOutputMap[node.index] = {})\n\n // Add outputs\n for (let outputId = 0; outputId < def.output.length; outputId++) {\n const linksFrom = this.linksFrom[node.index]\n // If this output is linked internally we flag it to hide\n const hasLink =\n linksFrom?.[outputId] && !this.externalFrom[node.index]?.[outputId]\n const customConfig =\n this.nodeData.config?.[node.index]?.output?.[outputId]\n const visible = customConfig?.visible ?? !hasLink\n this.outputVisibility.push(visible)\n if (!visible) {\n continue\n }\n\n oldToNew[outputId] = this.nodeDef.output.length\n this.newToOldOutputMap[this.nodeDef.output.length] = {\n node,\n slot: outputId\n }\n this.nodeDef.output.push(def.output[outputId])\n this.nodeDef.output_is_list.push(def.output_is_list[outputId])\n\n let label = customConfig?.name\n if (!label) {\n label = def.output_name?.[outputId] ?? def.output[outputId]\n const output = node.outputs.find((o) => o.name === label)\n if (output?.label) {\n label = output.label\n }\n }\n\n let name = label\n if (name in seenOutputs) {\n const prefix = `${node.title ?? node.type} `\n name = `${prefix}${label}`\n if (name in seenOutputs) {\n name = `${prefix}${node.index} ${label}`\n }\n }\n seenOutputs[name] = 1\n\n this.nodeDef.output_name.push(name)\n }\n }\n\n static async registerFromWorkflow(groupNodes, missingNodeTypes) {\n const clean = app.clean\n app.clean = function () {\n for (const g in groupNodes) {\n try {\n LiteGraph.unregisterNodeType('workflow/' + g)\n } catch (error) {}\n }\n app.clean = clean\n }\n\n for (const g in groupNodes) {\n const groupData = groupNodes[g]\n\n let hasMissing = false\n for (const n of groupData.nodes) {\n // Find missing node types\n if (!(n.type in LiteGraph.registered_node_types)) {\n missingNodeTypes.push({\n type: n.type,\n hint: ` (In group node 'workflow/${g}')`\n })\n\n missingNodeTypes.push({\n type: 'workflow/' + g,\n action: {\n text: 'Remove from workflow',\n callback: (e) => {\n delete groupNodes[g]\n e.target.textContent = 'Removed'\n e.target.style.pointerEvents = 'none'\n e.target.style.opacity = 0.7\n }\n }\n })\n\n hasMissing = true\n }\n }\n\n if (hasMissing) continue\n\n const config = new GroupNodeConfig(g, groupData)\n await config.registerType()\n }\n }\n}\n\nexport class GroupNodeHandler {\n node\n groupData\n innerNodes: any\n\n constructor(node) {\n this.node = node\n this.groupData = node.constructor?.nodeData?.[GROUP]\n\n this.node.setInnerNodes = (innerNodes) => {\n this.innerNodes = innerNodes\n\n for (\n let innerNodeIndex = 0;\n innerNodeIndex < this.innerNodes.length;\n innerNodeIndex++\n ) {\n const innerNode = this.innerNodes[innerNodeIndex]\n\n for (const w of innerNode.widgets ?? []) {\n if (w.type === 'converted-widget') {\n w.serializeValue = w.origSerializeValue\n }\n }\n\n innerNode.index = innerNodeIndex\n innerNode.getInputNode = (slot) => {\n // Check if this input is internal or external\n const externalSlot =\n this.groupData.oldToNewInputMap[innerNode.index]?.[slot]\n if (externalSlot != null) {\n return this.node.getInputNode(externalSlot)\n }\n\n // Internal link\n const innerLink = this.groupData.linksTo[innerNode.index]?.[slot]\n if (!innerLink) return null\n\n const inputNode = innerNodes[innerLink[0]]\n // Primitives will already apply their values\n if (inputNode.type === 'PrimitiveNode') return null\n\n return inputNode\n }\n\n innerNode.getInputLink = (slot) => {\n const externalSlot =\n this.groupData.oldToNewInputMap[innerNode.index]?.[slot]\n if (externalSlot != null) {\n // The inner node is connected via the group node inputs\n const linkId = this.node.inputs[externalSlot].link\n let link = app.graph.links[linkId]\n\n // Use the outer link, but update the target to the inner node\n // @ts-expect-error\n // TODO: Fix this\n link = {\n ...link,\n target_id: innerNode.id,\n target_slot: +slot\n }\n return link\n }\n\n let link = this.groupData.linksTo[innerNode.index]?.[slot]\n if (!link) return null\n // Use the inner link, but update the origin node to be inner node id\n link = {\n origin_id: innerNodes[link[0]].id,\n origin_slot: link[1],\n target_id: innerNode.id,\n target_slot: +slot\n }\n return link\n }\n }\n }\n\n this.node.updateLink = (link) => {\n // Replace the group node reference with the internal node\n link = { ...link }\n const output = this.groupData.newToOldOutputMap[link.origin_slot]\n let innerNode = this.innerNodes[output.node.index]\n let l\n while (innerNode?.type === 'Reroute') {\n l = innerNode.getInputLink(0)\n innerNode = innerNode.getInputNode(0)\n }\n\n if (!innerNode) {\n return null\n }\n\n if (l && GroupNodeHandler.isGroupNode(innerNode)) {\n return innerNode.updateLink(l)\n }\n\n link.origin_id = innerNode.id\n link.origin_slot = l?.origin_slot ?? output.slot\n return link\n }\n\n this.node.getInnerNodes = () => {\n if (!this.innerNodes) {\n this.node.setInnerNodes(\n this.groupData.nodeData.nodes.map((n, i) => {\n const innerNode = LiteGraph.createNode(n.type)\n innerNode.configure(n)\n // @ts-expect-error\n innerNode.id = `${this.node.id}:${i}`\n return innerNode\n })\n )\n }\n\n this.updateInnerWidgets()\n\n return this.innerNodes\n }\n\n this.node.recreate = async () => {\n const id = this.node.id\n const sz = this.node.size\n const nodes = this.node.convertToNodes()\n\n const groupNode = LiteGraph.createNode(this.node.type)\n groupNode.id = id\n\n // Reuse the existing nodes for this instance\n groupNode.setInnerNodes(nodes)\n groupNode[GROUP].populateWidgets()\n app.graph.add(groupNode)\n groupNode.size = [\n Math.max(groupNode.size[0], sz[0]),\n Math.max(groupNode.size[1], sz[1])\n ]\n\n // Remove all converted nodes and relink them\n groupNode[GROUP].replaceNodes(nodes)\n return groupNode\n }\n\n this.node.convertToNodes = () => {\n const addInnerNodes = () => {\n const backup = localStorage.getItem('litegrapheditor_clipboard')\n // Clone the node data so we dont mutate it for other nodes\n const c = { ...this.groupData.nodeData }\n c.nodes = [...c.nodes]\n const innerNodes = this.node.getInnerNodes()\n let ids = []\n for (let i = 0; i < c.nodes.length; i++) {\n let id = innerNodes?.[i]?.id\n // Use existing IDs if they are set on the inner nodes\n if (id == null || isNaN(id)) {\n id = undefined\n } else {\n ids.push(id)\n }\n c.nodes[i] = { ...c.nodes[i], id }\n }\n localStorage.setItem('litegrapheditor_clipboard', JSON.stringify(c))\n app.canvas.pasteFromClipboard()\n localStorage.setItem('litegrapheditor_clipboard', backup)\n\n const [x, y] = this.node.pos\n let top\n let left\n // Configure nodes with current widget data\n const selectedIds = ids.length\n ? ids\n : Object.keys(app.canvas.selected_nodes)\n const newNodes = []\n for (let i = 0; i < selectedIds.length; i++) {\n const id = selectedIds[i]\n const newNode = app.graph.getNodeById(id)\n const innerNode = innerNodes[i]\n newNodes.push(newNode)\n\n if (left == null || newNode.pos[0] < left) {\n left = newNode.pos[0]\n }\n if (top == null || newNode.pos[1] < top) {\n top = newNode.pos[1]\n }\n\n if (!newNode.widgets) continue\n\n const map = this.groupData.oldToNewWidgetMap[innerNode.index]\n if (map) {\n const widgets = Object.keys(map)\n\n for (const oldName of widgets) {\n const newName = map[oldName]\n if (!newName) continue\n\n const widgetIndex = this.node.widgets.findIndex(\n (w) => w.name === newName\n )\n if (widgetIndex === -1) continue\n\n // Populate the main and any linked widgets\n if (innerNode.type === 'PrimitiveNode') {\n for (let i = 0; i < newNode.widgets.length; i++) {\n newNode.widgets[i].value =\n this.node.widgets[widgetIndex + i].value\n }\n } else {\n const outerWidget = this.node.widgets[widgetIndex]\n const newWidget = newNode.widgets.find(\n (w) => w.name === oldName\n )\n if (!newWidget) continue\n\n newWidget.value = outerWidget.value\n for (let w = 0; w < outerWidget.linkedWidgets?.length; w++) {\n newWidget.linkedWidgets[w].value =\n outerWidget.linkedWidgets[w].value\n }\n }\n }\n }\n }\n\n // Shift each node\n for (const newNode of newNodes) {\n newNode.pos = [\n newNode.pos[0] - (left - x),\n newNode.pos[1] - (top - y)\n ]\n }\n\n return { newNodes, selectedIds }\n }\n\n const reconnectInputs = (selectedIds) => {\n for (const innerNodeIndex in this.groupData.oldToNewInputMap) {\n const id = selectedIds[innerNodeIndex]\n const newNode = app.graph.getNodeById(id)\n const map = this.groupData.oldToNewInputMap[innerNodeIndex]\n for (const innerInputId in map) {\n const groupSlotId = map[innerInputId]\n if (groupSlotId == null) continue\n const slot = node.inputs[groupSlotId]\n if (slot.link == null) continue\n const link = app.graph.links[slot.link]\n if (!link) continue\n // connect this node output to the input of another node\n const originNode = app.graph.getNodeById(link.origin_id)\n originNode.connect(link.origin_slot, newNode, +innerInputId)\n }\n }\n }\n\n const reconnectOutputs = (selectedIds) => {\n for (\n let groupOutputId = 0;\n groupOutputId < node.outputs?.length;\n groupOutputId++\n ) {\n const output = node.outputs[groupOutputId]\n if (!output.links) continue\n const links = [...output.links]\n for (const l of links) {\n const slot = this.groupData.newToOldOutputMap[groupOutputId]\n const link = app.graph.links[l]\n const targetNode = app.graph.getNodeById(link.target_id)\n const newNode = app.graph.getNodeById(selectedIds[slot.node.index])\n newNode.connect(slot.slot, targetNode, link.target_slot)\n }\n }\n }\n\n const { newNodes, selectedIds } = addInnerNodes()\n reconnectInputs(selectedIds)\n reconnectOutputs(selectedIds)\n app.graph.remove(this.node)\n\n return newNodes\n }\n\n const getExtraMenuOptions = this.node.getExtraMenuOptions\n this.node.getExtraMenuOptions = function (_, options) {\n getExtraMenuOptions?.apply(this, arguments)\n\n let optionIndex = options.findIndex((o) => o.content === 'Outputs')\n if (optionIndex === -1) optionIndex = options.length\n else optionIndex++\n options.splice(\n optionIndex,\n 0,\n null,\n {\n content: 'Convert to nodes',\n callback: () => {\n return this.convertToNodes()\n }\n },\n {\n content: 'Manage Group Node',\n callback: () => {\n new ManageGroupDialog(app).show(this.type)\n }\n }\n )\n }\n\n // Draw custom collapse icon to identity this as a group\n const onDrawTitleBox = this.node.onDrawTitleBox\n this.node.onDrawTitleBox = function (ctx, height, size, scale) {\n onDrawTitleBox?.apply(this, arguments)\n\n const fill = ctx.fillStyle\n ctx.beginPath()\n ctx.rect(11, -height + 11, 2, 2)\n ctx.rect(14, -height + 11, 2, 2)\n ctx.rect(17, -height + 11, 2, 2)\n ctx.rect(11, -height + 14, 2, 2)\n ctx.rect(14, -height + 14, 2, 2)\n ctx.rect(17, -height + 14, 2, 2)\n ctx.rect(11, -height + 17, 2, 2)\n ctx.rect(14, -height + 17, 2, 2)\n ctx.rect(17, -height + 17, 2, 2)\n\n ctx.fillStyle = this.boxcolor || LiteGraph.NODE_DEFAULT_BOXCOLOR\n ctx.fill()\n ctx.fillStyle = fill\n }\n\n // Draw progress label\n const onDrawForeground = node.onDrawForeground\n const groupData = this.groupData.nodeData\n node.onDrawForeground = function (ctx) {\n const r = onDrawForeground?.apply?.(this, arguments)\n if (\n +app.runningNodeId === this.id &&\n this.runningInternalNodeId !== null\n ) {\n const n = groupData.nodes[this.runningInternalNodeId]\n if (!n) return\n const message = `Running ${n.title || n.type} (${this.runningInternalNodeId}/${groupData.nodes.length})`\n ctx.save()\n ctx.font = '12px sans-serif'\n const sz = ctx.measureText(message)\n ctx.fillStyle = node.boxcolor || LiteGraph.NODE_DEFAULT_BOXCOLOR\n ctx.beginPath()\n ctx.roundRect(\n 0,\n -LiteGraph.NODE_TITLE_HEIGHT - 20,\n sz.width + 12,\n 20,\n 5\n )\n ctx.fill()\n\n ctx.fillStyle = '#fff'\n ctx.fillText(message, 6, -LiteGraph.NODE_TITLE_HEIGHT - 6)\n ctx.restore()\n }\n }\n\n // Flag this node as needing to be reset\n const onExecutionStart = this.node.onExecutionStart\n this.node.onExecutionStart = function () {\n this.resetExecution = true\n return onExecutionStart?.apply(this, arguments)\n }\n\n const self = this\n const onNodeCreated = this.node.onNodeCreated\n this.node.onNodeCreated = function () {\n if (!this.widgets) {\n return\n }\n const config = self.groupData.nodeData.config\n if (config) {\n for (const n in config) {\n const inputs = config[n]?.input\n for (const w in inputs) {\n if (inputs[w].visible !== false) continue\n const widgetName = self.groupData.oldToNewWidgetMap[n][w]\n const widget = this.widgets.find((w) => w.name === widgetName)\n if (widget) {\n widget.type = 'hidden'\n widget.computeSize = () => [0, -4]\n }\n }\n }\n }\n\n return onNodeCreated?.apply(this, arguments)\n }\n\n function handleEvent(type, getId, getEvent) {\n const handler = ({ detail }) => {\n const id = getId(detail)\n if (!id) return\n const node = app.graph.getNodeById(id)\n if (node) return\n\n const innerNodeIndex = this.innerNodes?.findIndex((n) => n.id == id)\n if (innerNodeIndex > -1) {\n this.node.runningInternalNodeId = innerNodeIndex\n api.dispatchEvent(\n new CustomEvent(type, {\n detail: getEvent(detail, this.node.id + '', this.node)\n })\n )\n }\n }\n api.addEventListener(type, handler)\n return handler\n }\n\n const executing = handleEvent.call(\n this,\n 'executing',\n (d) => d,\n (d, id, node) => id\n )\n\n const executed = handleEvent.call(\n this,\n 'executed',\n (d) => d?.display_node || d?.node,\n (d, id, node) => ({\n ...d,\n node: id,\n display_node: id,\n merge: !node.resetExecution\n })\n )\n\n const onRemoved = node.onRemoved\n this.node.onRemoved = function () {\n onRemoved?.apply(this, arguments)\n api.removeEventListener('executing', executing)\n api.removeEventListener('executed', executed)\n }\n\n this.node.refreshComboInNode = (defs) => {\n // Update combo widget options\n for (const widgetName in this.groupData.newToOldWidgetMap) {\n const widget = this.node.widgets.find((w) => w.name === widgetName)\n if (widget?.type === 'combo') {\n const old = this.groupData.newToOldWidgetMap[widgetName]\n const def = defs[old.node.type]\n const input =\n def?.input?.required?.[old.inputName] ??\n def?.input?.optional?.[old.inputName]\n if (!input) continue\n\n widget.options.values = input[0]\n\n if (\n old.inputName !== 'image' &&\n !widget.options.values.includes(widget.value)\n ) {\n widget.value = widget.options.values[0]\n widget.callback(widget.value)\n }\n }\n }\n }\n }\n\n updateInnerWidgets() {\n for (const newWidgetName in this.groupData.newToOldWidgetMap) {\n const newWidget = this.node.widgets.find((w) => w.name === newWidgetName)\n if (!newWidget) continue\n\n const newValue = newWidget.value\n const old = this.groupData.newToOldWidgetMap[newWidgetName]\n let innerNode = this.innerNodes[old.node.index]\n\n if (innerNode.type === 'PrimitiveNode') {\n innerNode.primitiveValue = newValue\n const primitiveLinked = this.groupData.primitiveToWidget[old.node.index]\n for (const linked of primitiveLinked ?? []) {\n const node = this.innerNodes[linked.nodeId]\n const widget = node.widgets.find((w) => w.name === linked.inputName)\n\n if (widget) {\n widget.value = newValue\n }\n }\n continue\n } else if (innerNode.type === 'Reroute') {\n const rerouteLinks = this.groupData.linksFrom[old.node.index]\n if (rerouteLinks) {\n for (const [_, , targetNodeId, targetSlot] of rerouteLinks['0']) {\n const node = this.innerNodes[targetNodeId]\n const input = node.inputs[targetSlot]\n if (input.widget) {\n const widget = node.widgets?.find(\n (w) => w.name === input.widget.name\n )\n if (widget) {\n widget.value = newValue\n }\n }\n }\n }\n }\n\n const widget = innerNode.widgets?.find((w) => w.name === old.inputName)\n if (widget) {\n widget.value = newValue\n }\n }\n }\n\n populatePrimitive(node, nodeId, oldName, i, linkedShift) {\n // Converted widget, populate primitive if linked\n const primitiveId = this.groupData.widgetToPrimitive[nodeId]?.[oldName]\n if (primitiveId == null) return\n const targetWidgetName =\n this.groupData.oldToNewWidgetMap[primitiveId]['value']\n const targetWidgetIndex = this.node.widgets.findIndex(\n (w) => w.name === targetWidgetName\n )\n if (targetWidgetIndex > -1) {\n const primitiveNode = this.innerNodes[primitiveId]\n let len = primitiveNode.widgets.length\n if (\n len - 1 !==\n this.node.widgets[targetWidgetIndex].linkedWidgets?.length\n ) {\n // Fallback handling for if some reason the primitive has a different number of widgets\n // we dont want to overwrite random widgets, better to leave blank\n len = 1\n }\n for (let i = 0; i < len; i++) {\n this.node.widgets[targetWidgetIndex + i].value =\n primitiveNode.widgets[i].value\n }\n }\n return true\n }\n\n populateReroute(node, nodeId, map) {\n if (node.type !== 'Reroute') return\n\n const link = this.groupData.linksFrom[nodeId]?.[0]?.[0]\n if (!link) return\n const [, , targetNodeId, targetNodeSlot] = link\n const targetNode = this.groupData.nodeData.nodes[targetNodeId]\n const inputs = targetNode.inputs\n const targetWidget = inputs?.[targetNodeSlot]?.widget\n if (!targetWidget) return\n\n const offset = inputs.length - (targetNode.widgets_values?.length ?? 0)\n const v = targetNode.widgets_values?.[targetNodeSlot - offset]\n if (v == null) return\n\n const widgetName = Object.values(map)[0]\n const widget = this.node.widgets.find((w) => w.name === widgetName)\n if (widget) {\n widget.value = v\n }\n }\n\n populateWidgets() {\n if (!this.node.widgets) return\n\n for (\n let nodeId = 0;\n nodeId < this.groupData.nodeData.nodes.length;\n nodeId++\n ) {\n const node = this.groupData.nodeData.nodes[nodeId]\n const map = this.groupData.oldToNewWidgetMap[nodeId] ?? {}\n const widgets = Object.keys(map)\n\n if (!node.widgets_values?.length) {\n // special handling for populating values into reroutes\n // this allows primitives connect to them to pick up the correct value\n this.populateReroute(node, nodeId, map)\n continue\n }\n\n let linkedShift = 0\n for (let i = 0; i < widgets.length; i++) {\n const oldName = widgets[i]\n const newName = map[oldName]\n const widgetIndex = this.node.widgets.findIndex(\n (w) => w.name === newName\n )\n const mainWidget = this.node.widgets[widgetIndex]\n if (\n this.populatePrimitive(node, nodeId, oldName, i, linkedShift) ||\n widgetIndex === -1\n ) {\n // Find the inner widget and shift by the number of linked widgets as they will have been removed too\n const innerWidget = this.innerNodes[nodeId].widgets?.find(\n (w) => w.name === oldName\n )\n linkedShift += innerWidget?.linkedWidgets?.length ?? 0\n }\n if (widgetIndex === -1) {\n continue\n }\n\n // Populate the main and any linked widget\n mainWidget.value = node.widgets_values[i + linkedShift]\n for (let w = 0; w < mainWidget.linkedWidgets?.length; w++) {\n this.node.widgets[widgetIndex + w + 1].value =\n node.widgets_values[i + ++linkedShift]\n }\n }\n }\n }\n\n replaceNodes(nodes) {\n let top\n let left\n\n for (let i = 0; i < nodes.length; i++) {\n const node = nodes[i]\n if (left == null || node.pos[0] < left) {\n left = node.pos[0]\n }\n if (top == null || node.pos[1] < top) {\n top = node.pos[1]\n }\n\n this.linkOutputs(node, i)\n app.graph.remove(node)\n }\n\n this.linkInputs()\n this.node.pos = [left, top]\n }\n\n linkOutputs(originalNode, nodeId) {\n if (!originalNode.outputs) return\n\n for (const output of originalNode.outputs) {\n if (!output.links) continue\n // Clone the links as they'll be changed if we reconnect\n const links = [...output.links]\n for (const l of links) {\n const link = app.graph.links[l]\n if (!link) continue\n\n const targetNode = app.graph.getNodeById(link.target_id)\n const newSlot =\n this.groupData.oldToNewOutputMap[nodeId]?.[link.origin_slot]\n if (newSlot != null) {\n this.node.connect(newSlot, targetNode, link.target_slot)\n }\n }\n }\n }\n\n linkInputs() {\n for (const link of this.groupData.nodeData.links ?? []) {\n const [, originSlot, targetId, targetSlot, actualOriginId] = link\n const originNode = app.graph.getNodeById(actualOriginId)\n if (!originNode) continue // this node is in the group\n originNode.connect(\n originSlot,\n this.node.id,\n this.groupData.oldToNewInputMap[targetId][targetSlot]\n )\n }\n }\n\n static getGroupData(node) {\n return (node.nodeData ?? node.constructor?.nodeData)?.[GROUP]\n }\n\n static isGroupNode(node) {\n return !!node.constructor?.nodeData?.[GROUP]\n }\n\n static async fromNodes(nodes) {\n // Process the nodes into the stored workflow group node data\n const builder = new GroupNodeBuilder(nodes)\n const res = builder.build()\n if (!res) return\n\n const { name, nodeData } = res\n\n // Convert this data into a LG node definition and register it\n const config = new GroupNodeConfig(name, nodeData)\n await config.registerType()\n\n const groupNode = LiteGraph.createNode(`workflow/${name}`)\n // Reuse the existing nodes for this instance\n groupNode.setInnerNodes(builder.nodes)\n groupNode[GROUP].populateWidgets()\n app.graph.add(groupNode)\n\n // Remove all converted nodes and relink them\n groupNode[GROUP].replaceNodes(builder.nodes)\n return groupNode\n }\n}\n\nfunction addConvertToGroupOptions() {\n function addConvertOption(options, index) {\n const selected = Object.values(app.canvas.selected_nodes ?? {})\n const disabled =\n selected.length < 2 ||\n selected.find((n) => GroupNodeHandler.isGroupNode(n))\n options.splice(index + 1, null, {\n content: `Convert to Group Node`,\n disabled,\n callback: async () => {\n return await GroupNodeHandler.fromNodes(selected)\n }\n })\n }\n\n function addManageOption(options, index) {\n const groups = app.graph.extra?.groupNodes\n const disabled = !groups || !Object.keys(groups).length\n options.splice(index + 1, null, {\n content: `Manage Group Nodes`,\n disabled,\n callback: () => {\n new ManageGroupDialog(app).show()\n }\n })\n }\n\n // Add to canvas\n const getCanvasMenuOptions = LGraphCanvas.prototype.getCanvasMenuOptions\n LGraphCanvas.prototype.getCanvasMenuOptions = function () {\n const options = getCanvasMenuOptions.apply(this, arguments)\n const index =\n options.findIndex((o) => o?.content === 'Add Group') + 1 || options.length\n addConvertOption(options, index)\n addManageOption(options, index + 1)\n return options\n }\n\n // Add to nodes\n const getNodeMenuOptions = LGraphCanvas.prototype.getNodeMenuOptions\n LGraphCanvas.prototype.getNodeMenuOptions = function (node) {\n const options = getNodeMenuOptions.apply(this, arguments)\n if (!GroupNodeHandler.isGroupNode(node)) {\n const index =\n options.findIndex((o) => o?.content === 'Outputs') + 1 ||\n options.length - 1\n addConvertOption(options, index)\n }\n return options\n }\n}\n\nconst id = 'Comfy.GroupNode'\nlet globalDefs\nconst ext = {\n name: id,\n setup() {\n addConvertToGroupOptions()\n },\n async beforeConfigureGraph(graphData, missingNodeTypes) {\n const nodes = graphData?.extra?.groupNodes\n if (nodes) {\n await GroupNodeConfig.registerFromWorkflow(nodes, missingNodeTypes)\n }\n },\n addCustomNodeDefs(defs) {\n // Store this so we can mutate it later with group nodes\n globalDefs = defs\n },\n nodeCreated(node) {\n if (GroupNodeHandler.isGroupNode(node)) {\n node[GROUP] = new GroupNodeHandler(node)\n }\n },\n async refreshComboInNodes(defs) {\n // Re-register group nodes so new ones are created with the correct options\n Object.assign(globalDefs, defs)\n const nodes = app.graph.extra?.groupNodes\n if (nodes) {\n await GroupNodeConfig.registerFromWorkflow(nodes, {})\n }\n }\n}\n\napp.registerExtension(ext)\n","import { LGraphGroup } from '@comfyorg/litegraph'\nimport { app } from '../../scripts/app'\nimport { LGraphCanvas, LiteGraph } from '@comfyorg/litegraph'\n\nfunction setNodeMode(node, mode) {\n node.mode = mode\n node.graph.change()\n}\n\nfunction addNodesToGroup(group, nodes = []) {\n var x1, y1, x2, y2\n var nx1, ny1, nx2, ny2\n var node\n\n x1 = y1 = x2 = y2 = -1\n nx1 = ny1 = nx2 = ny2 = -1\n\n for (var n of [group.nodes, nodes]) {\n for (var i in n) {\n node = n[i]\n\n nx1 = node.pos[0]\n ny1 = node.pos[1]\n nx2 = node.pos[0] + node.size[0]\n ny2 = node.pos[1] + node.size[1]\n\n if (node.type != 'Reroute') {\n ny1 -= LiteGraph.NODE_TITLE_HEIGHT\n }\n\n if (node.flags?.collapsed) {\n ny2 = ny1 + LiteGraph.NODE_TITLE_HEIGHT\n\n if (node?._collapsed_width) {\n nx2 = nx1 + Math.round(node._collapsed_width)\n }\n }\n\n if (x1 == -1 || nx1 < x1) {\n x1 = nx1\n }\n\n if (y1 == -1 || ny1 < y1) {\n y1 = ny1\n }\n\n if (x2 == -1 || nx2 > x2) {\n x2 = nx2\n }\n\n if (y2 == -1 || ny2 > y2) {\n y2 = ny2\n }\n }\n }\n\n var padding = 10\n\n y1 = y1 - Math.round(group.font_size * 1.4)\n\n group.pos = [x1 - padding, y1 - padding]\n group.size = [x2 - x1 + padding * 2, y2 - y1 + padding * 2]\n}\n\napp.registerExtension({\n name: 'Comfy.GroupOptions',\n setup() {\n const orig = LGraphCanvas.prototype.getCanvasMenuOptions\n // graph_mouse\n LGraphCanvas.prototype.getCanvasMenuOptions = function () {\n const options = orig.apply(this, arguments)\n const group = this.graph.getGroupOnPos(\n this.graph_mouse[0],\n this.graph_mouse[1]\n )\n if (!group) {\n options.push({\n content: 'Add Group For Selected Nodes',\n disabled: !Object.keys(app.canvas.selected_nodes || {}).length,\n callback: () => {\n const group = new LGraphGroup()\n addNodesToGroup(group, this.selected_nodes)\n app.canvas.graph.add(group)\n this.graph.change()\n }\n })\n\n return options\n }\n\n // Group nodes aren't recomputed until the group is moved, this ensures the nodes are up-to-date\n group.recomputeInsideNodes()\n const nodesInGroup = group.nodes\n\n options.push({\n content: 'Add Selected Nodes To Group',\n disabled: !Object.keys(app.canvas.selected_nodes || {}).length,\n callback: () => {\n addNodesToGroup(group, this.selected_nodes)\n this.graph.change()\n }\n })\n\n // No nodes in group, return default options\n if (nodesInGroup.length === 0) {\n return options\n } else {\n // Add a separator between the default options and the group options\n options.push(null)\n }\n\n // Check if all nodes are the same mode\n let allNodesAreSameMode = true\n for (let i = 1; i < nodesInGroup.length; i++) {\n if (nodesInGroup[i].mode !== nodesInGroup[0].mode) {\n allNodesAreSameMode = false\n break\n }\n }\n\n options.push({\n content: 'Fit Group To Nodes',\n callback: () => {\n addNodesToGroup(group)\n this.graph.change()\n }\n })\n\n options.push({\n content: 'Select Nodes',\n callback: () => {\n this.selectNodes(nodesInGroup)\n this.graph.change()\n this.canvas.focus()\n }\n })\n\n // Modes\n // 0: Always\n // 1: On Event\n // 2: Never\n // 3: On Trigger\n // 4: Bypass\n // If all nodes are the same mode, add a menu option to change the mode\n if (allNodesAreSameMode) {\n const mode = nodesInGroup[0].mode\n switch (mode) {\n case 0:\n // All nodes are always, option to disable, and bypass\n options.push({\n content: 'Set Group Nodes to Never',\n callback: () => {\n for (const node of nodesInGroup) {\n setNodeMode(node, 2)\n }\n }\n })\n options.push({\n content: 'Bypass Group Nodes',\n callback: () => {\n for (const node of nodesInGroup) {\n setNodeMode(node, 4)\n }\n }\n })\n break\n case 2:\n // All nodes are never, option to enable, and bypass\n options.push({\n content: 'Set Group Nodes to Always',\n callback: () => {\n for (const node of nodesInGroup) {\n setNodeMode(node, 0)\n }\n }\n })\n options.push({\n content: 'Bypass Group Nodes',\n callback: () => {\n for (const node of nodesInGroup) {\n setNodeMode(node, 4)\n }\n }\n })\n break\n case 4:\n // All nodes are bypass, option to enable, and disable\n options.push({\n content: 'Set Group Nodes to Always',\n callback: () => {\n for (const node of nodesInGroup) {\n setNodeMode(node, 0)\n }\n }\n })\n options.push({\n content: 'Set Group Nodes to Never',\n callback: () => {\n for (const node of nodesInGroup) {\n setNodeMode(node, 2)\n }\n }\n })\n break\n default:\n // All nodes are On Trigger or On Event(Or other?), option to disable, set to always, or bypass\n options.push({\n content: 'Set Group Nodes to Always',\n callback: () => {\n for (const node of nodesInGroup) {\n setNodeMode(node, 0)\n }\n }\n })\n options.push({\n content: 'Set Group Nodes to Never',\n callback: () => {\n for (const node of nodesInGroup) {\n setNodeMode(node, 2)\n }\n }\n })\n options.push({\n content: 'Bypass Group Nodes',\n callback: () => {\n for (const node of nodesInGroup) {\n setNodeMode(node, 4)\n }\n }\n })\n break\n }\n } else {\n // Nodes are not all the same mode, add a menu option to change the mode to always, never, or bypass\n options.push({\n content: 'Set Group Nodes to Always',\n callback: () => {\n for (const node of nodesInGroup) {\n setNodeMode(node, 0)\n }\n }\n })\n options.push({\n content: 'Set Group Nodes to Never',\n callback: () => {\n for (const node of nodesInGroup) {\n setNodeMode(node, 2)\n }\n }\n })\n options.push({\n content: 'Bypass Group Nodes',\n callback: () => {\n for (const node of nodesInGroup) {\n setNodeMode(node, 4)\n }\n }\n })\n }\n\n return options\n }\n }\n})\n","import { LiteGraph } from '@comfyorg/litegraph'\nimport { app } from '../../scripts/app'\n\n// Inverts the scrolling of context menus\n\nconst id = 'Comfy.InvertMenuScrolling'\napp.registerExtension({\n name: id,\n init() {\n const ctxMenu = LiteGraph.ContextMenu\n const replace = () => {\n // @ts-expect-error\n LiteGraph.ContextMenu = function (values, options) {\n options = options || {}\n if (options.scroll_speed) {\n options.scroll_speed *= -1\n } else {\n options.scroll_speed = -0.1\n }\n return ctxMenu.call(this, values, options)\n }\n LiteGraph.ContextMenu.prototype = ctxMenu.prototype\n }\n app.ui.settings.addSetting({\n id,\n category: ['Comfy', 'Graph', 'InvertMenuScrolling'],\n name: 'Invert Context Menu Scrolling',\n type: 'boolean',\n defaultValue: false,\n onChange(value) {\n if (value) {\n replace()\n } else {\n LiteGraph.ContextMenu = ctxMenu\n }\n }\n })\n }\n})\n","import { app } from '../../scripts/app'\nimport { api } from '../../scripts/api'\nimport { useToastStore } from '@/stores/toastStore'\n\napp.registerExtension({\n name: 'Comfy.Keybinds',\n init() {\n const keybindListener = async function (event) {\n const modifierPressed = event.ctrlKey || event.metaKey\n\n // Queue prompt using (ctrl or command) + enter\n if (modifierPressed && event.key === 'Enter') {\n // Cancel current prompt using (ctrl or command) + alt + enter\n if (event.altKey) {\n await api.interrupt()\n useToastStore().add({\n severity: 'info',\n summary: 'Interrupted',\n detail: 'Execution has been interrupted',\n life: 1000\n })\n return\n }\n // Queue prompt as first for generation using (ctrl or command) + shift + enter\n app.queuePrompt(event.shiftKey ? -1 : 0).then()\n return\n }\n\n const target = event.composedPath()[0]\n if (\n target.tagName === 'TEXTAREA' ||\n target.tagName === 'INPUT' ||\n (target.tagName === 'SPAN' &&\n target.classList.contains('property_value'))\n ) {\n return\n }\n\n const modifierKeyIdMap = {\n s: '#comfy-save-button',\n o: '#comfy-file-input',\n Backspace: '#comfy-clear-button',\n d: '#comfy-load-default-button',\n g: '#comfy-group-selected-nodes-button'\n }\n\n const modifierKeybindId = modifierKeyIdMap[event.key]\n if (modifierPressed && modifierKeybindId) {\n event.preventDefault()\n\n const elem = document.querySelector(modifierKeybindId)\n elem.click()\n return\n }\n\n // Finished Handling all modifier keybinds, now handle the rest\n if (event.ctrlKey || event.altKey || event.metaKey) {\n return\n }\n\n // Close out of modals using escape\n if (event.key === 'Escape') {\n const modals = document.querySelectorAll('.comfy-modal')\n const modal = Array.from(modals).find(\n (modal) =>\n window.getComputedStyle(modal).getPropertyValue('display') !==\n 'none'\n )\n if (modal) {\n modal.style.display = 'none'\n }\n\n ;[...document.querySelectorAll('dialog')].forEach((d) => {\n d.close()\n })\n }\n\n const keyIdMap = {\n q: '.queue-tab-button.side-bar-button',\n h: '.queue-tab-button.side-bar-button',\n r: '#comfy-refresh-button'\n }\n\n const buttonId = keyIdMap[event.key]\n if (buttonId) {\n const button = document.querySelector(buttonId)\n button.click()\n }\n }\n\n window.addEventListener('keydown', keybindListener, true)\n }\n})\n","import { app } from '../../scripts/app'\nimport { LiteGraph } from '@comfyorg/litegraph'\nconst id = 'Comfy.LinkRenderMode'\nconst ext = {\n name: id,\n async setup(app) {\n app.ui.settings.addSetting({\n id,\n category: ['Comfy', 'Graph', 'LinkRenderMode'],\n name: 'Link Render Mode',\n defaultValue: 2,\n type: 'combo',\n // @ts-expect-error\n options: [...LiteGraph.LINK_RENDER_MODES, 'Hidden'].map((m, i) => ({\n value: i,\n text: m,\n selected: i == app.canvas.links_render_mode\n })),\n onChange(value) {\n app.canvas.links_render_mode = +value\n app.graph.setDirtyCanvas(true)\n }\n })\n }\n}\n\napp.registerExtension(ext)\n","import { app } from '../../scripts/app'\nimport { ComfyDialog, $el } from '../../scripts/ui'\nimport { ComfyApp } from '../../scripts/app'\nimport { api } from '../../scripts/api'\nimport { ClipspaceDialog } from './clipspace'\n\n// Helper function to convert a data URL to a Blob object\nfunction dataURLToBlob(dataURL) {\n const parts = dataURL.split(';base64,')\n const contentType = parts[0].split(':')[1]\n const byteString = atob(parts[1])\n const arrayBuffer = new ArrayBuffer(byteString.length)\n const uint8Array = new Uint8Array(arrayBuffer)\n for (let i = 0; i < byteString.length; i++) {\n uint8Array[i] = byteString.charCodeAt(i)\n }\n return new Blob([arrayBuffer], { type: contentType })\n}\n\nfunction loadedImageToBlob(image) {\n const canvas = document.createElement('canvas')\n\n canvas.width = image.width\n canvas.height = image.height\n\n const ctx = canvas.getContext('2d')\n\n ctx.drawImage(image, 0, 0)\n\n const dataURL = canvas.toDataURL('image/png', 1)\n const blob = dataURLToBlob(dataURL)\n\n return blob\n}\n\nfunction loadImage(imagePath) {\n return new Promise((resolve, reject) => {\n const image = new Image()\n\n image.onload = function () {\n resolve(image)\n }\n\n image.src = imagePath\n })\n}\n\nasync function uploadMask(filepath, formData) {\n await api\n .fetchApi('/upload/mask', {\n method: 'POST',\n body: formData\n })\n .then((response) => {})\n .catch((error) => {\n console.error('Error:', error)\n })\n\n ComfyApp.clipspace.imgs[ComfyApp.clipspace['selectedIndex']] = new Image()\n ComfyApp.clipspace.imgs[ComfyApp.clipspace['selectedIndex']].src = api.apiURL(\n '/view?' +\n new URLSearchParams(filepath).toString() +\n app.getPreviewFormatParam() +\n app.getRandParam()\n )\n\n if (ComfyApp.clipspace.images)\n ComfyApp.clipspace.images[ComfyApp.clipspace['selectedIndex']] = filepath\n\n ClipspaceDialog.invalidatePreview()\n}\n\nfunction prepare_mask(image, maskCanvas, maskCtx, maskColor) {\n // paste mask data into alpha channel\n maskCtx.drawImage(image, 0, 0, maskCanvas.width, maskCanvas.height)\n const maskData = maskCtx.getImageData(\n 0,\n 0,\n maskCanvas.width,\n maskCanvas.height\n )\n\n // invert mask\n for (let i = 0; i < maskData.data.length; i += 4) {\n if (maskData.data[i + 3] == 255) maskData.data[i + 3] = 0\n else maskData.data[i + 3] = 255\n\n maskData.data[i] = maskColor.r\n maskData.data[i + 1] = maskColor.g\n maskData.data[i + 2] = maskColor.b\n }\n\n maskCtx.globalCompositeOperation = 'source-over'\n maskCtx.putImageData(maskData, 0, 0)\n}\n\n// Define the PointerType enum\nenum PointerType {\n Arc = 'arc',\n Rect = 'rect'\n}\n\nenum CompositionOperation {\n SourceOver = 'source-over',\n DestinationOut = 'destination-out'\n}\n\nclass MaskEditorDialog extends ComfyDialog {\n static instance = null\n static mousedown_x: number | null = null\n static mousedown_y: number | null = null\n\n brush: HTMLDivElement\n maskCtx: any\n maskCanvas: HTMLCanvasElement\n brush_size_slider: HTMLDivElement\n brush_opacity_slider: HTMLDivElement\n colorButton: HTMLButtonElement\n saveButton: HTMLButtonElement\n zoom_ratio: number\n pan_x: number\n pan_y: number\n imgCanvas: HTMLCanvasElement\n last_display_style: string\n is_visible: boolean\n image: HTMLImageElement\n handler_registered: boolean\n brush_slider_input: HTMLInputElement\n cursorX: number\n cursorY: number\n mousedown_pan_x: number\n mousedown_pan_y: number\n last_pressure: number\n pointer_type: PointerType\n brush_pointer_type_select: HTMLDivElement\n\n static getInstance() {\n if (!MaskEditorDialog.instance) {\n MaskEditorDialog.instance = new MaskEditorDialog()\n }\n\n return MaskEditorDialog.instance\n }\n\n is_layout_created = false\n\n constructor() {\n super()\n this.element = $el('div.comfy-modal', { parent: document.body }, [\n $el('div.comfy-modal-content', [...this.createButtons()])\n ])\n }\n\n createButtons() {\n return []\n }\n\n createButton(name, callback): HTMLButtonElement {\n var button = document.createElement('button')\n button.style.pointerEvents = 'auto'\n button.innerText = name\n button.addEventListener('click', callback)\n return button\n }\n\n createLeftButton(name, callback) {\n var button = this.createButton(name, callback)\n button.style.cssFloat = 'left'\n button.style.marginRight = '4px'\n return button\n }\n\n createRightButton(name, callback) {\n var button = this.createButton(name, callback)\n button.style.cssFloat = 'right'\n button.style.marginLeft = '4px'\n return button\n }\n\n createLeftSlider(self, name, callback): HTMLDivElement {\n const divElement = document.createElement('div')\n divElement.id = 'maskeditor-slider'\n divElement.style.cssFloat = 'left'\n divElement.style.fontFamily = 'sans-serif'\n divElement.style.marginRight = '4px'\n divElement.style.color = 'var(--input-text)'\n divElement.style.backgroundColor = 'var(--comfy-input-bg)'\n divElement.style.borderRadius = '8px'\n divElement.style.borderColor = 'var(--border-color)'\n divElement.style.borderStyle = 'solid'\n divElement.style.fontSize = '15px'\n divElement.style.height = '25px'\n divElement.style.padding = '1px 6px'\n divElement.style.display = 'flex'\n divElement.style.position = 'relative'\n divElement.style.top = '2px'\n divElement.style.pointerEvents = 'auto'\n self.brush_slider_input = document.createElement('input')\n self.brush_slider_input.setAttribute('type', 'range')\n self.brush_slider_input.setAttribute('min', '1')\n self.brush_slider_input.setAttribute('max', '100')\n self.brush_slider_input.setAttribute('value', '10')\n const labelElement = document.createElement('label')\n labelElement.textContent = name\n\n divElement.appendChild(labelElement)\n divElement.appendChild(self.brush_slider_input)\n\n self.brush_slider_input.addEventListener('change', callback)\n\n return divElement\n }\n\n createOpacitySlider(self, name, callback): HTMLDivElement {\n const divElement = document.createElement('div')\n divElement.id = 'maskeditor-opacity-slider'\n divElement.style.cssFloat = 'left'\n divElement.style.fontFamily = 'sans-serif'\n divElement.style.marginRight = '4px'\n divElement.style.color = 'var(--input-text)'\n divElement.style.backgroundColor = 'var(--comfy-input-bg)'\n divElement.style.borderRadius = '8px'\n divElement.style.borderColor = 'var(--border-color)'\n divElement.style.borderStyle = 'solid'\n divElement.style.fontSize = '15px'\n divElement.style.height = '25px'\n divElement.style.padding = '1px 6px'\n divElement.style.display = 'flex'\n divElement.style.position = 'relative'\n divElement.style.top = '2px'\n divElement.style.pointerEvents = 'auto'\n self.opacity_slider_input = document.createElement('input')\n self.opacity_slider_input.setAttribute('type', 'range')\n self.opacity_slider_input.setAttribute('min', '0.1')\n self.opacity_slider_input.setAttribute('max', '1.0')\n self.opacity_slider_input.setAttribute('step', '0.01')\n self.opacity_slider_input.setAttribute('value', '0.7')\n const labelElement = document.createElement('label')\n labelElement.textContent = name\n\n divElement.appendChild(labelElement)\n divElement.appendChild(self.opacity_slider_input)\n\n self.opacity_slider_input.addEventListener('input', callback)\n\n return divElement\n }\n\n createPointerTypeSelect(self: any): HTMLDivElement {\n const divElement = document.createElement('div')\n divElement.id = 'maskeditor-pointer-type'\n divElement.style.cssFloat = 'left'\n divElement.style.fontFamily = 'sans-serif'\n divElement.style.marginRight = '4px'\n divElement.style.color = 'var(--input-text)'\n divElement.style.backgroundColor = 'var(--comfy-input-bg)'\n divElement.style.borderRadius = '8px'\n divElement.style.borderColor = 'var(--border-color)'\n divElement.style.borderStyle = 'solid'\n divElement.style.fontSize = '15px'\n divElement.style.height = '25px'\n divElement.style.padding = '1px 6px'\n divElement.style.display = 'flex'\n divElement.style.position = 'relative'\n divElement.style.top = '2px'\n divElement.style.pointerEvents = 'auto'\n\n const labelElement = document.createElement('label')\n labelElement.textContent = 'Pointer Type:'\n\n const selectElement = document.createElement('select')\n selectElement.style.borderRadius = '0'\n selectElement.style.borderColor = 'transparent'\n selectElement.style.borderStyle = 'unset'\n selectElement.style.fontSize = '0.9em'\n\n const optionArc = document.createElement('option')\n optionArc.value = 'arc'\n optionArc.text = 'Circle'\n optionArc.selected = true // Fix for TypeScript, \"selected\" should be boolean\n\n const optionRect = document.createElement('option')\n optionRect.value = 'rect'\n optionRect.text = 'Square'\n\n selectElement.appendChild(optionArc)\n selectElement.appendChild(optionRect)\n\n selectElement.addEventListener('change', (event: Event) => {\n const target = event.target as HTMLSelectElement\n self.pointer_type = target.value\n this.setBrushBorderRadius(self)\n })\n\n divElement.appendChild(labelElement)\n divElement.appendChild(selectElement)\n\n return divElement\n }\n\n setBrushBorderRadius(self: any): void {\n if (self.pointer_type === PointerType.Rect) {\n this.brush.style.borderRadius = '0%'\n // @ts-expect-error\n this.brush.style.MozBorderRadius = '0%'\n // @ts-expect-error\n this.brush.style.WebkitBorderRadius = '0%'\n } else {\n this.brush.style.borderRadius = '50%'\n // @ts-expect-error\n this.brush.style.MozBorderRadius = '50%'\n // @ts-expect-error\n this.brush.style.WebkitBorderRadius = '50%'\n }\n }\n\n setlayout(imgCanvas: HTMLCanvasElement, maskCanvas: HTMLCanvasElement) {\n const self = this\n self.pointer_type = PointerType.Arc\n\n // If it is specified as relative, using it only as a hidden placeholder for padding is recommended\n // to prevent anomalies where it exceeds a certain size and goes outside of the window.\n var bottom_panel = document.createElement('div')\n bottom_panel.style.position = 'absolute'\n bottom_panel.style.bottom = '0px'\n bottom_panel.style.left = '20px'\n bottom_panel.style.right = '20px'\n bottom_panel.style.height = '50px'\n bottom_panel.style.pointerEvents = 'none'\n\n var brush = document.createElement('div')\n brush.id = 'brush'\n brush.style.backgroundColor = 'transparent'\n brush.style.outline = '1px dashed black'\n brush.style.boxShadow = '0 0 0 1px white'\n brush.style.position = 'absolute'\n brush.style.zIndex = '8889'\n brush.style.pointerEvents = 'none'\n this.brush = brush\n this.setBrushBorderRadius(self)\n this.element.appendChild(imgCanvas)\n this.element.appendChild(maskCanvas)\n this.element.appendChild(bottom_panel)\n document.body.appendChild(brush)\n\n var clearButton = this.createLeftButton('Clear', () => {\n self.maskCtx.clearRect(\n 0,\n 0,\n self.maskCanvas.width,\n self.maskCanvas.height\n )\n })\n\n this.brush_size_slider = this.createLeftSlider(\n self,\n 'Thickness',\n (event) => {\n self.brush_size = event.target.value\n self.updateBrushPreview(self)\n }\n )\n\n this.brush_opacity_slider = this.createOpacitySlider(\n self,\n 'Opacity',\n (event) => {\n self.brush_opacity = event.target.value\n if (self.brush_color_mode !== 'negative') {\n self.maskCanvas.style.opacity = self.brush_opacity.toString()\n }\n }\n )\n\n this.brush_pointer_type_select = this.createPointerTypeSelect(self)\n this.colorButton = this.createLeftButton(this.getColorButtonText(), () => {\n if (self.brush_color_mode === 'black') {\n self.brush_color_mode = 'white'\n } else if (self.brush_color_mode === 'white') {\n self.brush_color_mode = 'negative'\n } else {\n self.brush_color_mode = 'black'\n }\n\n self.updateWhenBrushColorModeChanged()\n })\n\n var cancelButton = this.createRightButton('Cancel', () => {\n document.removeEventListener('keydown', MaskEditorDialog.handleKeyDown)\n self.close()\n })\n\n this.saveButton = this.createRightButton('Save', () => {\n document.removeEventListener('keydown', MaskEditorDialog.handleKeyDown)\n self.save()\n })\n\n this.element.appendChild(imgCanvas)\n this.element.appendChild(maskCanvas)\n this.element.appendChild(bottom_panel)\n\n bottom_panel.appendChild(clearButton)\n bottom_panel.appendChild(this.saveButton)\n bottom_panel.appendChild(cancelButton)\n bottom_panel.appendChild(this.brush_size_slider)\n bottom_panel.appendChild(this.brush_opacity_slider)\n bottom_panel.appendChild(this.brush_pointer_type_select)\n bottom_panel.appendChild(this.colorButton)\n\n imgCanvas.style.position = 'absolute'\n maskCanvas.style.position = 'absolute'\n\n imgCanvas.style.top = '200'\n imgCanvas.style.left = '0'\n\n maskCanvas.style.top = imgCanvas.style.top\n maskCanvas.style.left = imgCanvas.style.left\n\n const maskCanvasStyle = this.getMaskCanvasStyle()\n maskCanvas.style.mixBlendMode = maskCanvasStyle.mixBlendMode\n maskCanvas.style.opacity = maskCanvasStyle.opacity.toString()\n }\n\n async show() {\n this.zoom_ratio = 1.0\n this.pan_x = 0\n this.pan_y = 0\n\n if (!this.is_layout_created) {\n // layout\n const imgCanvas = document.createElement('canvas')\n const maskCanvas = document.createElement('canvas')\n\n imgCanvas.id = 'imageCanvas'\n maskCanvas.id = 'maskCanvas'\n\n this.setlayout(imgCanvas, maskCanvas)\n\n // prepare content\n this.imgCanvas = imgCanvas\n this.maskCanvas = maskCanvas\n this.maskCtx = maskCanvas.getContext('2d', { willReadFrequently: true })\n\n this.setEventHandler(maskCanvas)\n\n this.is_layout_created = true\n\n // replacement of onClose hook since close is not real close\n const self = this\n const observer = new MutationObserver(function (mutations) {\n mutations.forEach(function (mutation) {\n if (\n mutation.type === 'attributes' &&\n mutation.attributeName === 'style'\n ) {\n if (\n self.last_display_style &&\n self.last_display_style != 'none' &&\n self.element.style.display == 'none'\n ) {\n self.brush.style.display = 'none'\n ComfyApp.onClipspaceEditorClosed()\n }\n\n self.last_display_style = self.element.style.display\n }\n })\n })\n\n const config = { attributes: true }\n observer.observe(this.element, config)\n }\n\n // The keydown event needs to be reconfigured when closing the dialog as it gets removed.\n document.addEventListener('keydown', MaskEditorDialog.handleKeyDown)\n\n if (ComfyApp.clipspace_return_node) {\n this.saveButton.innerText = 'Save to node'\n } else {\n this.saveButton.innerText = 'Save'\n }\n this.saveButton.disabled = false\n\n this.element.style.display = 'block'\n this.element.style.width = '85%'\n this.element.style.margin = '0 7.5%'\n this.element.style.height = '100vh'\n this.element.style.top = '50%'\n this.element.style.left = '42%'\n this.element.style.zIndex = '8888' // NOTE: alert dialog must be high priority.\n\n await this.setImages(this.imgCanvas)\n\n this.is_visible = true\n }\n\n isOpened() {\n return this.element.style.display == 'block'\n }\n\n invalidateCanvas(orig_image, mask_image) {\n this.imgCanvas.width = orig_image.width\n this.imgCanvas.height = orig_image.height\n\n this.maskCanvas.width = orig_image.width\n this.maskCanvas.height = orig_image.height\n\n let imgCtx = this.imgCanvas.getContext('2d', { willReadFrequently: true })\n let maskCtx = this.maskCanvas.getContext('2d', {\n willReadFrequently: true\n })\n\n imgCtx.drawImage(orig_image, 0, 0, orig_image.width, orig_image.height)\n prepare_mask(mask_image, this.maskCanvas, maskCtx, this.getMaskColor())\n }\n\n async setImages(imgCanvas) {\n let self = this\n\n const imgCtx = imgCanvas.getContext('2d', { willReadFrequently: true })\n const maskCtx = this.maskCtx\n const maskCanvas = this.maskCanvas\n\n imgCtx.clearRect(0, 0, this.imgCanvas.width, this.imgCanvas.height)\n maskCtx.clearRect(0, 0, this.maskCanvas.width, this.maskCanvas.height)\n\n // image load\n const filepath = ComfyApp.clipspace.images\n\n const alpha_url = new URL(\n ComfyApp.clipspace.imgs[ComfyApp.clipspace['selectedIndex']].src\n )\n alpha_url.searchParams.delete('channel')\n alpha_url.searchParams.delete('preview')\n alpha_url.searchParams.set('channel', 'a')\n let mask_image = await loadImage(alpha_url)\n\n // original image load\n const rgb_url = new URL(\n ComfyApp.clipspace.imgs[ComfyApp.clipspace['selectedIndex']].src\n )\n rgb_url.searchParams.delete('channel')\n rgb_url.searchParams.set('channel', 'rgb')\n this.image = new Image()\n this.image.onload = function () {\n maskCanvas.width = self.image.width\n maskCanvas.height = self.image.height\n\n self.invalidateCanvas(self.image, mask_image)\n self.initializeCanvasPanZoom()\n }\n this.image.src = rgb_url.toString()\n }\n\n initializeCanvasPanZoom() {\n // set initialize\n let drawWidth = this.image.width\n let drawHeight = this.image.height\n\n let width = this.element.clientWidth\n let height = this.element.clientHeight\n\n if (this.image.width > width) {\n drawWidth = width\n drawHeight = (drawWidth / this.image.width) * this.image.height\n }\n\n if (drawHeight > height) {\n drawHeight = height\n drawWidth = (drawHeight / this.image.height) * this.image.width\n }\n\n this.zoom_ratio = drawWidth / this.image.width\n\n const canvasX = (width - drawWidth) / 2\n const canvasY = (height - drawHeight) / 2\n this.pan_x = canvasX\n this.pan_y = canvasY\n\n this.invalidatePanZoom()\n }\n\n invalidatePanZoom() {\n let raw_width = this.image.width * this.zoom_ratio\n let raw_height = this.image.height * this.zoom_ratio\n\n if (this.pan_x + raw_width < 10) {\n this.pan_x = 10 - raw_width\n }\n\n if (this.pan_y + raw_height < 10) {\n this.pan_y = 10 - raw_height\n }\n\n let width = `${raw_width}px`\n let height = `${raw_height}px`\n\n let left = `${this.pan_x}px`\n let top = `${this.pan_y}px`\n\n this.maskCanvas.style.width = width\n this.maskCanvas.style.height = height\n this.maskCanvas.style.left = left\n this.maskCanvas.style.top = top\n\n this.imgCanvas.style.width = width\n this.imgCanvas.style.height = height\n this.imgCanvas.style.left = left\n this.imgCanvas.style.top = top\n }\n\n setEventHandler(maskCanvas) {\n const self = this\n\n if (!this.handler_registered) {\n maskCanvas.addEventListener('contextmenu', (event) => {\n event.preventDefault()\n })\n\n this.element.addEventListener('wheel', (event) =>\n this.handleWheelEvent(self, event)\n )\n this.element.addEventListener('pointermove', (event) =>\n this.pointMoveEvent(self, event)\n )\n this.element.addEventListener('touchmove', (event) =>\n this.pointMoveEvent(self, event)\n )\n\n this.element.addEventListener('dragstart', (event) => {\n if (event.ctrlKey) {\n event.preventDefault()\n }\n })\n\n maskCanvas.addEventListener('pointerdown', (event) =>\n this.handlePointerDown(self, event)\n )\n maskCanvas.addEventListener('pointermove', (event) =>\n this.draw_move(self, event)\n )\n maskCanvas.addEventListener('touchmove', (event) =>\n this.draw_move(self, event)\n )\n maskCanvas.addEventListener('pointerover', (event) => {\n this.brush.style.display = 'block'\n })\n maskCanvas.addEventListener('pointerleave', (event) => {\n this.brush.style.display = 'none'\n })\n\n document.addEventListener('pointerup', MaskEditorDialog.handlePointerUp)\n\n this.handler_registered = true\n }\n }\n\n getMaskCanvasStyle() {\n if (this.brush_color_mode === 'negative') {\n return {\n mixBlendMode: 'difference',\n opacity: '1'\n }\n } else {\n return {\n mixBlendMode: 'initial',\n opacity: this.brush_opacity\n }\n }\n }\n\n getMaskColor() {\n if (this.brush_color_mode === 'black') {\n return { r: 0, g: 0, b: 0 }\n }\n if (this.brush_color_mode === 'white') {\n return { r: 255, g: 255, b: 255 }\n }\n if (this.brush_color_mode === 'negative') {\n // negative effect only works with white color\n return { r: 255, g: 255, b: 255 }\n }\n\n return { r: 0, g: 0, b: 0 }\n }\n\n getMaskFillStyle() {\n const maskColor = this.getMaskColor()\n\n return 'rgb(' + maskColor.r + ',' + maskColor.g + ',' + maskColor.b + ')'\n }\n\n getColorButtonText() {\n let colorCaption = 'unknown'\n\n if (this.brush_color_mode === 'black') {\n colorCaption = 'black'\n } else if (this.brush_color_mode === 'white') {\n colorCaption = 'white'\n } else if (this.brush_color_mode === 'negative') {\n colorCaption = 'negative'\n }\n\n return 'Color: ' + colorCaption\n }\n\n updateWhenBrushColorModeChanged() {\n this.colorButton.innerText = this.getColorButtonText()\n\n // update mask canvas css styles\n\n const maskCanvasStyle = this.getMaskCanvasStyle()\n this.maskCanvas.style.mixBlendMode = maskCanvasStyle.mixBlendMode\n this.maskCanvas.style.opacity = maskCanvasStyle.opacity.toString()\n\n // update mask canvas rgb colors\n\n const maskColor = this.getMaskColor()\n\n const maskData = this.maskCtx.getImageData(\n 0,\n 0,\n this.maskCanvas.width,\n this.maskCanvas.height\n )\n\n for (let i = 0; i < maskData.data.length; i += 4) {\n maskData.data[i] = maskColor.r\n maskData.data[i + 1] = maskColor.g\n maskData.data[i + 2] = maskColor.b\n }\n\n this.maskCtx.putImageData(maskData, 0, 0)\n }\n\n brush_opacity = 0.7\n brush_size = 10\n brush_color_mode = 'black'\n drawing_mode = false\n lastx = -1\n lasty = -1\n lasttime = 0\n\n static handleKeyDown(event) {\n const self = MaskEditorDialog.instance\n if (event.key === ']') {\n self.brush_size = Math.min(self.brush_size + 2, 100)\n self.brush_slider_input.value = self.brush_size\n } else if (event.key === '[') {\n self.brush_size = Math.max(self.brush_size - 2, 1)\n self.brush_slider_input.value = self.brush_size\n } else if (event.key === 'Enter') {\n self.save()\n }\n\n self.updateBrushPreview(self)\n }\n\n static handlePointerUp(event) {\n event.preventDefault()\n\n this.mousedown_x = null\n this.mousedown_y = null\n\n MaskEditorDialog.instance.drawing_mode = false\n }\n\n updateBrushPreview(self) {\n const brush = self.brush\n\n var centerX = self.cursorX\n var centerY = self.cursorY\n\n brush.style.width = self.brush_size * 2 * this.zoom_ratio + 'px'\n brush.style.height = self.brush_size * 2 * this.zoom_ratio + 'px'\n brush.style.left = centerX - self.brush_size * this.zoom_ratio + 'px'\n brush.style.top = centerY - self.brush_size * this.zoom_ratio + 'px'\n }\n\n handleWheelEvent(self, event) {\n event.preventDefault()\n\n if (event.ctrlKey) {\n // zoom canvas\n if (event.deltaY < 0) {\n this.zoom_ratio = Math.min(10.0, this.zoom_ratio + 0.2)\n } else {\n this.zoom_ratio = Math.max(0.2, this.zoom_ratio - 0.2)\n }\n\n this.invalidatePanZoom()\n } else {\n // adjust brush size\n if (event.deltaY < 0) this.brush_size = Math.min(this.brush_size + 2, 100)\n else this.brush_size = Math.max(this.brush_size - 2, 1)\n\n this.brush_slider_input.value = this.brush_size.toString()\n\n this.updateBrushPreview(this)\n }\n }\n\n pointMoveEvent(self, event) {\n this.cursorX = event.pageX\n this.cursorY = event.pageY\n\n self.updateBrushPreview(self)\n\n if (event.ctrlKey) {\n event.preventDefault()\n self.pan_move(self, event)\n }\n\n let left_button_down =\n (window.TouchEvent && event instanceof TouchEvent) || event.buttons == 1\n\n if (event.shiftKey && left_button_down) {\n self.drawing_mode = false\n\n const y = event.clientY\n let delta = (self.zoom_lasty - y) * 0.005\n self.zoom_ratio = Math.max(\n Math.min(10.0, self.last_zoom_ratio - delta),\n 0.2\n )\n\n this.invalidatePanZoom()\n return\n }\n }\n\n pan_move(self, event) {\n if (event.buttons == 1) {\n if (MaskEditorDialog.mousedown_x) {\n let deltaX = MaskEditorDialog.mousedown_x - event.clientX\n let deltaY = MaskEditorDialog.mousedown_y - event.clientY\n\n self.pan_x = this.mousedown_pan_x - deltaX\n self.pan_y = this.mousedown_pan_y - deltaY\n\n self.invalidatePanZoom()\n }\n }\n }\n\n draw_move(self, event) {\n if (event.ctrlKey || event.shiftKey) {\n return\n }\n\n event.preventDefault()\n\n this.cursorX = event.pageX\n this.cursorY = event.pageY\n\n self.updateBrushPreview(self)\n\n let left_button_down =\n (window.TouchEvent && event instanceof TouchEvent) || event.buttons == 1\n let right_button_down = [2, 5, 32].includes(event.buttons)\n\n if (!event.altKey && left_button_down) {\n var diff = performance.now() - self.lasttime\n\n const maskRect = self.maskCanvas.getBoundingClientRect()\n\n var x = event.offsetX\n var y = event.offsetY\n\n if (event.offsetX == null) {\n x = event.targetTouches[0].clientX - maskRect.left\n }\n\n if (event.offsetY == null) {\n y = event.targetTouches[0].clientY - maskRect.top\n }\n\n x /= self.zoom_ratio\n y /= self.zoom_ratio\n\n var brush_size = this.brush_size\n if (event instanceof PointerEvent && event.pointerType == 'pen') {\n brush_size *= event.pressure\n this.last_pressure = event.pressure\n } else if (\n window.TouchEvent &&\n event instanceof TouchEvent &&\n diff < 20\n ) {\n // The firing interval of PointerEvents in Pen is unreliable, so it is supplemented by TouchEvents.\n brush_size *= this.last_pressure\n } else {\n brush_size = this.brush_size\n }\n\n if (diff > 20 && !this.drawing_mode)\n requestAnimationFrame(() => {\n self.init_shape(self, CompositionOperation.SourceOver)\n self.draw_shape(self, x, y, brush_size)\n self.lastx = x\n self.lasty = y\n })\n else\n requestAnimationFrame(() => {\n self.init_shape(self, CompositionOperation.SourceOver)\n\n var dx = x - self.lastx\n var dy = y - self.lasty\n\n var distance = Math.sqrt(dx * dx + dy * dy)\n var directionX = dx / distance\n var directionY = dy / distance\n\n for (var i = 0; i < distance; i += 5) {\n var px = self.lastx + directionX * i\n var py = self.lasty + directionY * i\n self.draw_shape(self, px, py, brush_size)\n }\n self.lastx = x\n self.lasty = y\n })\n\n self.lasttime = performance.now()\n } else if ((event.altKey && left_button_down) || right_button_down) {\n const maskRect = self.maskCanvas.getBoundingClientRect()\n const x =\n (event.offsetX || event.targetTouches[0].clientX - maskRect.left) /\n self.zoom_ratio\n const y =\n (event.offsetY || event.targetTouches[0].clientY - maskRect.top) /\n self.zoom_ratio\n\n var brush_size = this.brush_size\n if (event instanceof PointerEvent && event.pointerType == 'pen') {\n brush_size *= event.pressure\n this.last_pressure = event.pressure\n } else if (\n window.TouchEvent &&\n event instanceof TouchEvent &&\n diff < 20\n ) {\n brush_size *= this.last_pressure\n } else {\n brush_size = this.brush_size\n }\n\n if (diff > 20 && !this.drawing_mode)\n // cannot tracking drawing_mode for touch event\n requestAnimationFrame(() => {\n self.init_shape(self, CompositionOperation.DestinationOut)\n self.draw_shape(self, x, y, brush_size)\n self.lastx = x\n self.lasty = y\n })\n else\n requestAnimationFrame(() => {\n self.init_shape(self, CompositionOperation.DestinationOut)\n\n var dx = x - self.lastx\n var dy = y - self.lasty\n\n var distance = Math.sqrt(dx * dx + dy * dy)\n var directionX = dx / distance\n var directionY = dy / distance\n\n for (var i = 0; i < distance; i += 5) {\n var px = self.lastx + directionX * i\n var py = self.lasty + directionY * i\n self.draw_shape(self, px, py, brush_size)\n }\n self.lastx = x\n self.lasty = y\n })\n\n self.lasttime = performance.now()\n }\n }\n\n handlePointerDown(self, event) {\n if (event.ctrlKey) {\n if (event.buttons == 1) {\n MaskEditorDialog.mousedown_x = event.clientX\n MaskEditorDialog.mousedown_y = event.clientY\n\n this.mousedown_pan_x = this.pan_x\n this.mousedown_pan_y = this.pan_y\n }\n return\n }\n\n var brush_size = this.brush_size\n if (event instanceof PointerEvent && event.pointerType == 'pen') {\n brush_size *= event.pressure\n this.last_pressure = event.pressure\n }\n\n if ([0, 2, 5].includes(event.button)) {\n self.drawing_mode = true\n\n event.preventDefault()\n\n if (event.shiftKey) {\n self.zoom_lasty = event.clientY\n self.last_zoom_ratio = self.zoom_ratio\n return\n }\n\n const maskRect = self.maskCanvas.getBoundingClientRect()\n const x =\n (event.offsetX || event.targetTouches[0].clientX - maskRect.left) /\n self.zoom_ratio\n const y =\n (event.offsetY || event.targetTouches[0].clientY - maskRect.top) /\n self.zoom_ratio\n\n if (!event.altKey && event.button == 0) {\n self.init_shape(self, CompositionOperation.SourceOver)\n } else {\n self.init_shape(self, CompositionOperation.DestinationOut)\n }\n self.draw_shape(self, x, y, brush_size)\n self.lastx = x\n self.lasty = y\n self.lasttime = performance.now()\n }\n }\n\n init_shape(self, compositionOperation) {\n self.maskCtx.beginPath()\n if (compositionOperation == CompositionOperation.SourceOver) {\n self.maskCtx.fillStyle = this.getMaskFillStyle()\n self.maskCtx.globalCompositeOperation = CompositionOperation.SourceOver\n } else if (compositionOperation == CompositionOperation.DestinationOut) {\n self.maskCtx.globalCompositeOperation =\n CompositionOperation.DestinationOut\n }\n }\n\n draw_shape(self, x, y, brush_size) {\n if (self.pointer_type === PointerType.Rect) {\n self.maskCtx.rect(\n x - brush_size,\n y - brush_size,\n brush_size * 2,\n brush_size * 2\n )\n } else {\n self.maskCtx.arc(x, y, brush_size, 0, Math.PI * 2, false)\n }\n self.maskCtx.fill()\n }\n\n async save() {\n const backupCanvas = document.createElement('canvas')\n const backupCtx = backupCanvas.getContext('2d', {\n willReadFrequently: true\n })\n backupCanvas.width = this.image.width\n backupCanvas.height = this.image.height\n\n backupCtx.clearRect(0, 0, backupCanvas.width, backupCanvas.height)\n backupCtx.drawImage(\n this.maskCanvas,\n 0,\n 0,\n this.maskCanvas.width,\n this.maskCanvas.height,\n 0,\n 0,\n backupCanvas.width,\n backupCanvas.height\n )\n\n // paste mask data into alpha channel\n const backupData = backupCtx.getImageData(\n 0,\n 0,\n backupCanvas.width,\n backupCanvas.height\n )\n\n // refine mask image\n for (let i = 0; i < backupData.data.length; i += 4) {\n if (backupData.data[i + 3] == 255) backupData.data[i + 3] = 0\n else backupData.data[i + 3] = 255\n\n backupData.data[i] = 0\n backupData.data[i + 1] = 0\n backupData.data[i + 2] = 0\n }\n\n backupCtx.globalCompositeOperation = CompositionOperation.SourceOver\n backupCtx.putImageData(backupData, 0, 0)\n\n const formData = new FormData()\n const filename = 'clipspace-mask-' + performance.now() + '.png'\n\n const item = {\n filename: filename,\n subfolder: 'clipspace',\n type: 'input'\n }\n\n if (ComfyApp.clipspace.images) ComfyApp.clipspace.images[0] = item\n\n if (ComfyApp.clipspace.widgets) {\n const index = ComfyApp.clipspace.widgets.findIndex(\n (obj) => obj.name === 'image'\n )\n\n if (index >= 0) ComfyApp.clipspace.widgets[index].value = item\n }\n\n const dataURL = backupCanvas.toDataURL()\n const blob = dataURLToBlob(dataURL)\n\n let original_url = new URL(this.image.src)\n\n type Ref = { filename: string; subfolder?: string; type?: string }\n\n const original_ref: Ref = {\n filename: original_url.searchParams.get('filename')\n }\n\n let original_subfolder = original_url.searchParams.get('subfolder')\n if (original_subfolder) original_ref.subfolder = original_subfolder\n\n let original_type = original_url.searchParams.get('type')\n if (original_type) original_ref.type = original_type\n\n formData.append('image', blob, filename)\n formData.append('original_ref', JSON.stringify(original_ref))\n formData.append('type', 'input')\n formData.append('subfolder', 'clipspace')\n\n this.saveButton.innerText = 'Saving...'\n this.saveButton.disabled = true\n await uploadMask(item, formData)\n ComfyApp.onClipspaceEditorSave()\n this.close()\n }\n}\n\napp.registerExtension({\n name: 'Comfy.MaskEditor',\n init(app) {\n ComfyApp.open_maskeditor = function () {\n const dlg = MaskEditorDialog.getInstance()\n if (!dlg.isOpened()) {\n dlg.show()\n }\n }\n\n const context_predicate = () =>\n ComfyApp.clipspace &&\n ComfyApp.clipspace.imgs &&\n ComfyApp.clipspace.imgs.length > 0\n ClipspaceDialog.registerButton(\n 'MaskEditor',\n context_predicate,\n ComfyApp.open_maskeditor\n )\n }\n})\n","import { app } from '../../scripts/app'\nimport { api } from '../../scripts/api'\nimport { ComfyDialog, $el } from '../../scripts/ui'\nimport { GroupNodeConfig, GroupNodeHandler } from './groupNode'\nimport { LGraphCanvas } from '@comfyorg/litegraph'\n\n// Adds the ability to save and add multiple nodes as a template\n// To save:\n// Select multiple nodes (ctrl + drag to select a region or ctrl+click individual nodes)\n// Right click the canvas\n// Save Node Template -> give it a name\n//\n// To add:\n// Right click the canvas\n// Node templates -> click the one to add\n//\n// To delete/rename:\n// Right click the canvas\n// Node templates -> Manage\n//\n// To rearrange:\n// Open the manage dialog and Drag and drop elements using the \"Name:\" label as handle\n\nconst id = 'Comfy.NodeTemplates'\nconst file = 'comfy.templates.json'\n\nclass ManageTemplates extends ComfyDialog {\n templates: any[]\n draggedEl: HTMLElement | null\n saveVisualCue: number | null\n emptyImg: HTMLImageElement\n importInput: HTMLInputElement\n\n constructor() {\n super()\n this.load().then((v) => {\n this.templates = v\n })\n\n this.element.classList.add('comfy-manage-templates')\n this.draggedEl = null\n this.saveVisualCue = null\n this.emptyImg = new Image()\n this.emptyImg.src =\n 'data:image/gif;base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs='\n\n this.importInput = $el('input', {\n type: 'file',\n accept: '.json',\n multiple: true,\n style: { display: 'none' },\n parent: document.body,\n onchange: () => this.importAll()\n }) as HTMLInputElement\n }\n\n createButtons() {\n const btns = super.createButtons()\n btns[0].textContent = 'Close'\n btns[0].onclick = (e) => {\n clearTimeout(this.saveVisualCue)\n this.close()\n }\n btns.unshift(\n $el('button', {\n type: 'button',\n textContent: 'Export',\n onclick: () => this.exportAll()\n })\n )\n btns.unshift(\n $el('button', {\n type: 'button',\n textContent: 'Import',\n onclick: () => {\n this.importInput.click()\n }\n })\n )\n return btns\n }\n\n async load() {\n let templates = []\n if (app.storageLocation === 'server') {\n if (app.isNewUserSession) {\n // New user so migrate existing templates\n const json = localStorage.getItem(id)\n if (json) {\n templates = JSON.parse(json)\n }\n await api.storeUserData(file, json, { stringify: false })\n } else {\n const res = await api.getUserData(file)\n if (res.status === 200) {\n try {\n templates = await res.json()\n } catch (error) {}\n } else if (res.status !== 404) {\n console.error(res.status + ' ' + res.statusText)\n }\n }\n } else {\n const json = localStorage.getItem(id)\n if (json) {\n templates = JSON.parse(json)\n }\n }\n\n return templates ?? []\n }\n\n async store() {\n if (app.storageLocation === 'server') {\n const templates = JSON.stringify(this.templates, undefined, 4)\n localStorage.setItem(id, templates) // Backwards compatibility\n try {\n await api.storeUserData(file, templates, { stringify: false })\n } catch (error) {\n console.error(error)\n alert(error.message)\n }\n } else {\n localStorage.setItem(id, JSON.stringify(this.templates))\n }\n }\n\n async importAll() {\n for (const file of this.importInput.files) {\n if (file.type === 'application/json' || file.name.endsWith('.json')) {\n const reader = new FileReader()\n reader.onload = async () => {\n const importFile = JSON.parse(reader.result as string)\n if (importFile?.templates) {\n for (const template of importFile.templates) {\n if (template?.name && template?.data) {\n this.templates.push(template)\n }\n }\n await this.store()\n }\n }\n await reader.readAsText(file)\n }\n }\n\n this.importInput.value = null\n\n this.close()\n }\n\n exportAll() {\n if (this.templates.length == 0) {\n alert('No templates to export.')\n return\n }\n\n const json = JSON.stringify({ templates: this.templates }, null, 2) // convert the data to a JSON string\n const blob = new Blob([json], { type: 'application/json' })\n const url = URL.createObjectURL(blob)\n const a = $el('a', {\n href: url,\n download: 'node_templates.json',\n style: { display: 'none' },\n parent: document.body\n })\n a.click()\n setTimeout(function () {\n a.remove()\n window.URL.revokeObjectURL(url)\n }, 0)\n }\n\n show() {\n // Show list of template names + delete button\n super.show(\n $el(\n 'div',\n {},\n this.templates.flatMap((t, i) => {\n let nameInput\n return [\n $el(\n 'div',\n {\n dataset: { id: i.toString() },\n className: 'templateManagerRow',\n style: {\n display: 'grid',\n gridTemplateColumns: '1fr auto',\n border: '1px dashed transparent',\n gap: '5px',\n backgroundColor: 'var(--comfy-menu-bg)'\n },\n ondragstart: (e) => {\n this.draggedEl = e.currentTarget\n e.currentTarget.style.opacity = '0.6'\n e.currentTarget.style.border = '1px dashed yellow'\n e.dataTransfer.effectAllowed = 'move'\n e.dataTransfer.setDragImage(this.emptyImg, 0, 0)\n },\n ondragend: (e) => {\n e.target.style.opacity = '1'\n e.currentTarget.style.border = '1px dashed transparent'\n e.currentTarget.removeAttribute('draggable')\n\n // rearrange the elements\n this.element\n .querySelectorAll('.templateManagerRow')\n .forEach((el: HTMLElement, i) => {\n var prev_i = Number.parseInt(el.dataset.id)\n\n if (el == this.draggedEl && prev_i != i) {\n this.templates.splice(\n i,\n 0,\n this.templates.splice(prev_i, 1)[0]\n )\n }\n el.dataset.id = i.toString()\n })\n this.store()\n },\n ondragover: (e) => {\n e.preventDefault()\n if (e.currentTarget == this.draggedEl) return\n\n let rect = e.currentTarget.getBoundingClientRect()\n if (e.clientY > rect.top + rect.height / 2) {\n e.currentTarget.parentNode.insertBefore(\n this.draggedEl,\n e.currentTarget.nextSibling\n )\n } else {\n e.currentTarget.parentNode.insertBefore(\n this.draggedEl,\n e.currentTarget\n )\n }\n }\n },\n [\n $el(\n 'label',\n {\n textContent: 'Name: ',\n style: {\n cursor: 'grab'\n },\n onmousedown: (e) => {\n // enable dragging only from the label\n if (e.target.localName == 'label')\n e.currentTarget.parentNode.draggable = 'true'\n }\n },\n [\n $el('input', {\n value: t.name,\n dataset: { name: t.name },\n style: {\n transitionProperty: 'background-color',\n transitionDuration: '0s'\n },\n onchange: (e) => {\n clearTimeout(this.saveVisualCue)\n var el = e.target\n var row = el.parentNode.parentNode\n this.templates[row.dataset.id].name =\n el.value.trim() || 'untitled'\n this.store()\n el.style.backgroundColor = 'rgb(40, 95, 40)'\n el.style.transitionDuration = '0s'\n // @ts-expect-error\n // In browser env the return value is number.\n this.saveVisualCue = setTimeout(function () {\n el.style.transitionDuration = '.7s'\n el.style.backgroundColor = 'var(--comfy-input-bg)'\n }, 15)\n },\n onkeypress: (e) => {\n var el = e.target\n clearTimeout(this.saveVisualCue)\n el.style.transitionDuration = '0s'\n el.style.backgroundColor = 'var(--comfy-input-bg)'\n },\n $: (el) => (nameInput = el)\n })\n ]\n ),\n $el('div', {}, [\n $el('button', {\n textContent: 'Export',\n style: {\n fontSize: '12px',\n fontWeight: 'normal'\n },\n onclick: (e) => {\n const json = JSON.stringify({ templates: [t] }, null, 2) // convert the data to a JSON string\n const blob = new Blob([json], {\n type: 'application/json'\n })\n const url = URL.createObjectURL(blob)\n const a = $el('a', {\n href: url,\n download: (nameInput.value || t.name) + '.json',\n style: { display: 'none' },\n parent: document.body\n })\n a.click()\n setTimeout(function () {\n a.remove()\n window.URL.revokeObjectURL(url)\n }, 0)\n }\n }),\n $el('button', {\n textContent: 'Delete',\n style: {\n fontSize: '12px',\n color: 'red',\n fontWeight: 'normal'\n },\n onclick: (e) => {\n const item = e.target.parentNode.parentNode\n item.parentNode.removeChild(item)\n this.templates.splice(item.dataset.id * 1, 1)\n this.store()\n // update the rows index, setTimeout ensures that the list is updated\n var that = this\n setTimeout(function () {\n that.element\n .querySelectorAll('.templateManagerRow')\n .forEach((el: HTMLElement, i) => {\n el.dataset.id = i.toString()\n })\n }, 0)\n }\n })\n ])\n ]\n )\n ]\n })\n )\n )\n }\n}\n\napp.registerExtension({\n name: id,\n setup() {\n const manage = new ManageTemplates()\n\n const clipboardAction = async (cb) => {\n // We use the clipboard functions but dont want to overwrite the current user clipboard\n // Restore it after we've run our callback\n const old = localStorage.getItem('litegrapheditor_clipboard')\n await cb()\n localStorage.setItem('litegrapheditor_clipboard', old)\n }\n\n const orig = LGraphCanvas.prototype.getCanvasMenuOptions\n LGraphCanvas.prototype.getCanvasMenuOptions = function () {\n const options = orig.apply(this, arguments)\n\n options.push(null)\n options.push({\n content: `Save Selected as Template`,\n disabled: !Object.keys(app.canvas.selected_nodes || {}).length,\n callback: () => {\n const name = prompt('Enter name')\n if (!name?.trim()) return\n\n clipboardAction(() => {\n app.canvas.copyToClipboard()\n let data = localStorage.getItem('litegrapheditor_clipboard')\n data = JSON.parse(data)\n const nodeIds = Object.keys(app.canvas.selected_nodes)\n for (let i = 0; i < nodeIds.length; i++) {\n const node = app.graph.getNodeById(nodeIds[i])\n // @ts-expect-error\n const nodeData = node?.constructor.nodeData\n\n let groupData = GroupNodeHandler.getGroupData(node)\n if (groupData) {\n groupData = groupData.nodeData\n // @ts-expect-error\n if (!data.groupNodes) {\n // @ts-expect-error\n data.groupNodes = {}\n }\n // @ts-expect-error\n data.groupNodes[nodeData.name] = groupData\n // @ts-expect-error\n data.nodes[i].type = nodeData.name\n }\n }\n\n manage.templates.push({\n name,\n data: JSON.stringify(data)\n })\n manage.store()\n })\n }\n })\n\n // Map each template to a menu item\n const subItems = manage.templates.map((t) => {\n return {\n content: t.name,\n callback: () => {\n clipboardAction(async () => {\n const data = JSON.parse(t.data)\n await GroupNodeConfig.registerFromWorkflow(data.groupNodes, {})\n localStorage.setItem('litegrapheditor_clipboard', t.data)\n app.canvas.pasteFromClipboard()\n })\n }\n }\n })\n\n subItems.push(null, {\n content: 'Manage',\n callback: () => manage.show()\n })\n\n options.push({\n content: 'Node Templates',\n submenu: {\n options: subItems\n }\n })\n\n return options\n }\n }\n})\n","import { LiteGraph, LGraphCanvas } from '@comfyorg/litegraph'\nimport { app } from '../../scripts/app'\nimport { ComfyWidgets } from '../../scripts/widgets'\nimport { LGraphNode } from '@comfyorg/litegraph'\n// Node that add notes to your project\n\napp.registerExtension({\n name: 'Comfy.NoteNode',\n registerCustomNodes() {\n class NoteNode extends LGraphNode {\n static category: string\n\n color = LGraphCanvas.node_colors.yellow.color\n bgcolor = LGraphCanvas.node_colors.yellow.bgcolor\n groupcolor = LGraphCanvas.node_colors.yellow.groupcolor\n isVirtualNode: boolean\n collapsable: boolean\n title_mode: number\n\n constructor(title?: string) {\n super(title)\n if (!this.properties) {\n this.properties = { text: '' }\n }\n ComfyWidgets.STRING(\n // Should we extends LGraphNode? Yesss\n this,\n '',\n // @ts-expect-error\n ['', { default: this.properties.text, multiline: true }],\n app\n )\n\n this.serialize_widgets = true\n this.isVirtualNode = true\n }\n }\n\n // Load default visibility\n\n LiteGraph.registerNodeType(\n 'Note',\n Object.assign(NoteNode, {\n title_mode: LiteGraph.NORMAL_TITLE,\n title: 'Note',\n collapsable: true\n })\n )\n\n NoteNode.category = 'utils'\n }\n})\n","import { app } from '../../scripts/app'\nimport { mergeIfValid, getWidgetConfig, setWidgetConfig } from './widgetInputs'\nimport { LiteGraph, LGraphCanvas, LGraphNode } from '@comfyorg/litegraph'\n\n// Node that allows you to redirect connections for cleaner graphs\n\napp.registerExtension({\n name: 'Comfy.RerouteNode',\n registerCustomNodes(app) {\n interface RerouteNode extends LGraphNode {\n __outputType?: string\n }\n\n class RerouteNode extends LGraphNode {\n static category: string | undefined\n static defaultVisibility = false\n\n constructor(title?: string) {\n super(title)\n if (!this.properties) {\n this.properties = {}\n }\n this.properties.showOutputText = RerouteNode.defaultVisibility\n this.properties.horizontal = false\n\n this.addInput('', '*')\n this.addOutput(this.properties.showOutputText ? '*' : '', '*')\n\n this.onAfterGraphConfigured = function () {\n requestAnimationFrame(() => {\n this.onConnectionsChange(LiteGraph.INPUT, null, true, null)\n })\n }\n\n this.onConnectionsChange = function (\n type,\n index,\n connected,\n link_info\n ) {\n this.applyOrientation()\n\n // Prevent multiple connections to different types when we have no input\n if (connected && type === LiteGraph.OUTPUT) {\n // Ignore wildcard nodes as these will be updated to real types\n const types = new Set(\n this.outputs[0].links\n .map((l) => app.graph.links[l].type)\n .filter((t) => t !== '*')\n )\n if (types.size > 1) {\n const linksToDisconnect = []\n for (let i = 0; i < this.outputs[0].links.length - 1; i++) {\n const linkId = this.outputs[0].links[i]\n const link = app.graph.links[linkId]\n linksToDisconnect.push(link)\n }\n for (const link of linksToDisconnect) {\n const node = app.graph.getNodeById(link.target_id)\n node.disconnectInput(link.target_slot)\n }\n }\n }\n\n // Find root input\n let currentNode = this\n let updateNodes = []\n let inputType = null\n let inputNode = null\n while (currentNode) {\n updateNodes.unshift(currentNode)\n const linkId = currentNode.inputs[0].link\n if (linkId !== null) {\n const link = app.graph.links[linkId]\n if (!link) return\n const node = app.graph.getNodeById(link.origin_id)\n // @ts-expect-error Nodes that extend LGraphNode will not have a static type property\n const type = node.constructor.type\n if (type === 'Reroute') {\n if (node === this) {\n // We've found a circle\n currentNode.disconnectInput(link.target_slot)\n currentNode = null\n } else {\n // Move the previous node\n currentNode = node\n }\n } else {\n // We've found the end\n inputNode = currentNode\n inputType = node.outputs[link.origin_slot]?.type ?? null\n break\n }\n } else {\n // This path has no input node\n currentNode = null\n break\n }\n }\n\n // Find all outputs\n const nodes = [this]\n let outputType = null\n while (nodes.length) {\n currentNode = nodes.pop()\n const outputs =\n (currentNode.outputs ? currentNode.outputs[0].links : []) || []\n if (outputs.length) {\n for (const linkId of outputs) {\n const link = app.graph.links[linkId]\n\n // When disconnecting sometimes the link is still registered\n if (!link) continue\n\n const node = app.graph.getNodeById(link.target_id)\n // @ts-expect-error Nodes that extend LGraphNode will not have a static type property\n const type = node.constructor.type\n\n if (type === 'Reroute') {\n // Follow reroute nodes\n nodes.push(node)\n updateNodes.push(node)\n } else {\n // We've found an output\n const nodeOutType =\n node.inputs &&\n node.inputs[link?.target_slot] &&\n node.inputs[link.target_slot].type\n ? node.inputs[link.target_slot].type\n : null\n if (\n inputType &&\n !LiteGraph.isValidConnection(inputType, nodeOutType)\n ) {\n // The output doesnt match our input so disconnect it\n node.disconnectInput(link.target_slot)\n } else {\n outputType = nodeOutType\n }\n }\n }\n } else {\n // No more outputs for this path\n }\n }\n\n const displayType = inputType || outputType || '*'\n const color = LGraphCanvas.link_type_colors[displayType]\n\n let widgetConfig\n let targetWidget\n let widgetType\n // Update the types of each node\n for (const node of updateNodes) {\n // If we dont have an input type we are always wildcard but we'll show the output type\n // This lets you change the output link to a different type and all nodes will update\n node.outputs[0].type = inputType || '*'\n node.__outputType = displayType\n node.outputs[0].name = node.properties.showOutputText\n ? displayType\n : ''\n node.size = node.computeSize()\n node.applyOrientation()\n\n for (const l of node.outputs[0].links || []) {\n const link = app.graph.links[l]\n if (link) {\n // @ts-expect-error Fix litegraph types\n link.color = color\n\n if (app.configuringGraph) continue\n const targetNode = app.graph.getNodeById(link.target_id)\n const targetInput = targetNode.inputs?.[link.target_slot]\n if (targetInput?.widget) {\n const config = getWidgetConfig(targetInput)\n if (!widgetConfig) {\n widgetConfig = config[1] ?? {}\n widgetType = config[0]\n }\n if (!targetWidget) {\n targetWidget = targetNode.widgets?.find(\n // @ts-expect-error fix widget types\n (w) => w.name === targetInput.widget.name\n )\n }\n\n const merged = mergeIfValid(targetInput, [\n config[0],\n widgetConfig\n ])\n if (merged.customConfig) {\n widgetConfig = merged.customConfig\n }\n }\n }\n }\n }\n\n for (const node of updateNodes) {\n if (widgetConfig && outputType) {\n node.inputs[0].widget = { name: 'value' }\n setWidgetConfig(\n node.inputs[0],\n [widgetType ?? displayType, widgetConfig],\n targetWidget\n )\n } else {\n setWidgetConfig(node.inputs[0], null)\n }\n }\n\n if (inputNode) {\n const link = app.graph.links[inputNode.inputs[0].link]\n if (link) {\n // @ts-expect-error Fix litegraph types\n link.color = color\n }\n }\n }\n\n this.clone = function () {\n const cloned = RerouteNode.prototype.clone.apply(this)\n cloned.removeOutput(0)\n cloned.addOutput(this.properties.showOutputText ? '*' : '', '*')\n cloned.size = cloned.computeSize()\n return cloned\n }\n\n // This node is purely frontend and does not impact the resulting prompt so should not be serialized\n this.isVirtualNode = true\n }\n\n getExtraMenuOptions(_, options) {\n options.unshift(\n {\n content:\n (this.properties.showOutputText ? 'Hide' : 'Show') + ' Type',\n callback: () => {\n this.properties.showOutputText = !this.properties.showOutputText\n if (this.properties.showOutputText) {\n this.outputs[0].name =\n this.__outputType || (this.outputs[0].type as string)\n } else {\n this.outputs[0].name = ''\n }\n this.size = this.computeSize()\n this.applyOrientation()\n app.graph.setDirtyCanvas(true, true)\n }\n },\n {\n content:\n (RerouteNode.defaultVisibility ? 'Hide' : 'Show') +\n ' Type By Default',\n callback: () => {\n RerouteNode.setDefaultTextVisibility(\n !RerouteNode.defaultVisibility\n )\n }\n },\n {\n // naming is inverted with respect to LiteGraphNode.horizontal\n // LiteGraphNode.horizontal == true means that\n // each slot in the inputs and outputs are laid out horizontally,\n // which is the opposite of the visual orientation of the inputs and outputs as a node\n content:\n 'Set ' + (this.properties.horizontal ? 'Horizontal' : 'Vertical'),\n callback: () => {\n this.properties.horizontal = !this.properties.horizontal\n this.applyOrientation()\n }\n }\n )\n }\n applyOrientation() {\n this.horizontal = this.properties.horizontal\n if (this.horizontal) {\n // we correct the input position, because LiteGraphNode.horizontal\n // doesn't account for title presence\n // which reroute nodes don't have\n this.inputs[0].pos = [this.size[0] / 2, 0]\n } else {\n delete this.inputs[0].pos\n }\n app.graph.setDirtyCanvas(true, true)\n }\n\n computeSize(): [number, number] {\n return [\n this.properties.showOutputText && this.outputs && this.outputs.length\n ? Math.max(\n 75,\n LiteGraph.NODE_TEXT_SIZE * this.outputs[0].name.length * 0.6 +\n 40\n )\n : 75,\n 26\n ]\n }\n\n static setDefaultTextVisibility(visible) {\n RerouteNode.defaultVisibility = visible\n if (visible) {\n localStorage['Comfy.RerouteNode.DefaultVisibility'] = 'true'\n } else {\n delete localStorage['Comfy.RerouteNode.DefaultVisibility']\n }\n }\n }\n\n // Load default visibility\n RerouteNode.setDefaultTextVisibility(\n !!localStorage['Comfy.RerouteNode.DefaultVisibility']\n )\n\n LiteGraph.registerNodeType(\n 'Reroute',\n Object.assign(RerouteNode, {\n title_mode: LiteGraph.NO_TITLE,\n title: 'Reroute',\n collapsable: false\n })\n )\n\n RerouteNode.category = 'utils'\n }\n})\n","import { app } from '../../scripts/app'\nimport { applyTextReplacements } from '../../scripts/utils'\n// Use widget values and dates in output filenames\n\napp.registerExtension({\n name: 'Comfy.SaveImageExtraOutput',\n async beforeRegisterNodeDef(nodeType, nodeData, app) {\n if (nodeData.name === 'SaveImage' || nodeData.name === 'SaveAnimatedWEBP') {\n const onNodeCreated = nodeType.prototype.onNodeCreated\n // When the SaveImage node is created we want to override the serialization of the output name widget to run our S&R\n nodeType.prototype.onNodeCreated = function () {\n const r = onNodeCreated\n ? onNodeCreated.apply(this, arguments)\n : undefined\n\n const widget = this.widgets.find((w) => w.name === 'filename_prefix')\n widget.serializeValue = () => {\n return applyTextReplacements(app, widget.value)\n }\n\n return r\n }\n } else {\n // When any other node is created add a property to alias the node\n const onNodeCreated = nodeType.prototype.onNodeCreated\n nodeType.prototype.onNodeCreated = function () {\n const r = onNodeCreated\n ? onNodeCreated.apply(this, arguments)\n : undefined\n\n if (!this.properties || !('Node name for S&R' in this.properties)) {\n this.addProperty('Node name for S&R', this.constructor.type, 'string')\n }\n\n return r\n }\n }\n }\n})\n","import { app } from '../../scripts/app'\nimport { LGraphCanvas, LiteGraph } from '@comfyorg/litegraph'\n\nlet touchZooming\nlet touchCount = 0\n\napp.registerExtension({\n name: 'Comfy.SimpleTouchSupport',\n setup() {\n let zoomPos\n let touchTime\n let lastTouch\n\n function getMultiTouchPos(e) {\n return Math.hypot(\n e.touches[0].clientX - e.touches[1].clientX,\n e.touches[0].clientY - e.touches[1].clientY\n )\n }\n\n app.canvasEl.addEventListener(\n 'touchstart',\n (e) => {\n touchCount++\n lastTouch = null\n if (e.touches?.length === 1) {\n // Store start time for press+hold for context menu\n touchTime = new Date()\n lastTouch = e.touches[0]\n } else {\n touchTime = null\n if (e.touches?.length === 2) {\n // Store center pos for zoom\n zoomPos = getMultiTouchPos(e)\n app.canvas.pointer_is_down = false\n }\n }\n },\n true\n )\n\n app.canvasEl.addEventListener('touchend', (e: TouchEvent) => {\n touchZooming = false\n touchCount = e.touches?.length ?? touchCount - 1\n if (touchTime && !e.touches?.length) {\n if (new Date().getTime() - touchTime > 600) {\n try {\n // hack to get litegraph to use this event\n e.constructor = CustomEvent\n } catch (error) {}\n // @ts-expect-error\n e.clientX = lastTouch.clientX\n // @ts-expect-error\n e.clientY = lastTouch.clientY\n\n app.canvas.pointer_is_down = true\n // @ts-expect-error\n app.canvas._mousedown_callback(e)\n }\n touchTime = null\n }\n })\n\n app.canvasEl.addEventListener(\n 'touchmove',\n (e) => {\n touchTime = null\n if (e.touches?.length === 2) {\n app.canvas.pointer_is_down = false\n touchZooming = true\n // @ts-expect-error\n LiteGraph.closeAllContextMenus()\n // @ts-expect-error\n app.canvas.search_box?.close()\n const newZoomPos = getMultiTouchPos(e)\n\n const midX = (e.touches[0].clientX + e.touches[1].clientX) / 2\n const midY = (e.touches[0].clientY + e.touches[1].clientY) / 2\n\n let scale = app.canvas.ds.scale\n const diff = zoomPos - newZoomPos\n if (diff > 0.5) {\n scale *= 1 / 1.07\n } else if (diff < -0.5) {\n scale *= 1.07\n }\n app.canvas.ds.changeScale(scale, [midX, midY])\n app.canvas.setDirty(true, true)\n zoomPos = newZoomPos\n }\n },\n true\n )\n }\n})\n\nconst processMouseDown = LGraphCanvas.prototype.processMouseDown\nLGraphCanvas.prototype.processMouseDown = function (e) {\n if (touchZooming || touchCount) {\n return\n }\n return processMouseDown.apply(this, arguments)\n}\n\nconst processMouseMove = LGraphCanvas.prototype.processMouseMove\nLGraphCanvas.prototype.processMouseMove = function (e) {\n if (touchZooming || touchCount > 1) {\n return\n }\n return processMouseMove.apply(this, arguments)\n}\n","import { app } from '../../scripts/app'\nimport { ComfyWidgets } from '../../scripts/widgets'\nimport { LiteGraph } from '@comfyorg/litegraph'\n// Adds defaults for quickly adding nodes with middle click on the input/output\n\napp.registerExtension({\n name: 'Comfy.SlotDefaults',\n suggestionsNumber: null,\n init() {\n LiteGraph.search_filter_enabled = true\n LiteGraph.middle_click_slot_add_default_node = true\n this.suggestionsNumber = app.ui.settings.addSetting({\n id: 'Comfy.NodeSuggestions.number',\n category: ['Comfy', 'Node Search Box', 'NodeSuggestions'],\n name: 'Number of nodes suggestions',\n tooltip: 'Only for litegraph searchbox/context menu',\n type: 'slider',\n attrs: {\n min: 1,\n max: 100,\n step: 1\n },\n defaultValue: 5,\n onChange: (newVal, oldVal) => {\n this.setDefaults(newVal)\n }\n })\n },\n slot_types_default_out: {},\n slot_types_default_in: {},\n async beforeRegisterNodeDef(nodeType, nodeData, app) {\n var nodeId = nodeData.name\n const inputs = nodeData['input']['required'] //only show required inputs to reduce the mess also not logical to create node with optional inputs\n for (const inputKey in inputs) {\n var input = inputs[inputKey]\n if (typeof input[0] !== 'string') continue\n\n var type = input[0]\n if (type in ComfyWidgets) {\n var customProperties = input[1]\n if (!customProperties?.forceInput) continue //ignore widgets that don't force input\n }\n\n if (!(type in this.slot_types_default_out)) {\n this.slot_types_default_out[type] = ['Reroute']\n }\n if (this.slot_types_default_out[type].includes(nodeId)) continue\n this.slot_types_default_out[type].push(nodeId)\n\n // Input types have to be stored as lower case\n // Store each node that can handle this input type\n const lowerType = type.toLocaleLowerCase()\n if (!(lowerType in LiteGraph.registered_slot_in_types)) {\n LiteGraph.registered_slot_in_types[lowerType] = { nodes: [] }\n }\n LiteGraph.registered_slot_in_types[lowerType].nodes.push(\n nodeType.comfyClass\n )\n }\n\n var outputs = nodeData['output']\n for (const key in outputs) {\n var type = outputs[key] as string\n if (!(type in this.slot_types_default_in)) {\n this.slot_types_default_in[type] = ['Reroute'] // [\"Reroute\", \"Primitive\"]; primitive doesn't always work :'()\n }\n\n this.slot_types_default_in[type].push(nodeId)\n\n // Store each node that can handle this output type\n if (!(type in LiteGraph.registered_slot_out_types)) {\n LiteGraph.registered_slot_out_types[type] = { nodes: [] }\n }\n LiteGraph.registered_slot_out_types[type].nodes.push(nodeType.comfyClass)\n\n if (!LiteGraph.slot_types_out.includes(type)) {\n LiteGraph.slot_types_out.push(type)\n }\n }\n var maxNum = this.suggestionsNumber.value\n this.setDefaults(maxNum)\n },\n setDefaults(maxNum) {\n LiteGraph.slot_types_default_out = {}\n LiteGraph.slot_types_default_in = {}\n\n for (const type in this.slot_types_default_out) {\n LiteGraph.slot_types_default_out[type] = this.slot_types_default_out[\n type\n ].slice(0, maxNum)\n }\n for (const type in this.slot_types_default_in) {\n LiteGraph.slot_types_default_in[type] = this.slot_types_default_in[\n type\n ].slice(0, maxNum)\n }\n }\n})\n","import { app } from '../../scripts/app'\nimport {\n LGraphCanvas,\n LGraphNode,\n LGraphGroup,\n LiteGraph\n} from '@comfyorg/litegraph'\n\n// Shift + drag/resize to snap to grid\n\n/** Rounds a Vector2 in-place to the current CANVAS_GRID_SIZE. */\nfunction roundVectorToGrid(vec) {\n vec[0] =\n LiteGraph.CANVAS_GRID_SIZE * Math.round(vec[0] / LiteGraph.CANVAS_GRID_SIZE)\n vec[1] =\n LiteGraph.CANVAS_GRID_SIZE * Math.round(vec[1] / LiteGraph.CANVAS_GRID_SIZE)\n return vec\n}\n\napp.registerExtension({\n name: 'Comfy.SnapToGrid',\n init() {\n // Add setting to control grid size\n app.ui.settings.addSetting({\n id: 'Comfy.SnapToGrid.GridSize',\n category: ['Comfy', 'Graph', 'GridSize'],\n name: 'Snap to grid size',\n type: 'slider',\n attrs: {\n min: 1,\n max: 500\n },\n tooltip:\n 'When dragging and resizing nodes while holding shift they will be aligned to the grid, this controls the size of that grid.',\n defaultValue: LiteGraph.CANVAS_GRID_SIZE,\n onChange(value) {\n LiteGraph.CANVAS_GRID_SIZE = +value || 10\n }\n })\n\n // After moving a node, if the shift key is down align it to grid\n const onNodeMoved = app.canvas.onNodeMoved\n app.canvas.onNodeMoved = function (node) {\n const r = onNodeMoved?.apply(this, arguments)\n\n if (app.shiftDown) {\n // Ensure all selected nodes are realigned\n for (const id in this.selected_nodes) {\n this.selected_nodes[id].alignToGrid()\n }\n }\n\n return r\n }\n\n // When a node is added, add a resize handler to it so we can fix align the size with the grid\n const onNodeAdded = app.graph.onNodeAdded\n app.graph.onNodeAdded = function (node) {\n const onResize = node.onResize\n node.onResize = function () {\n if (app.shiftDown) {\n roundVectorToGrid(node.size)\n }\n return onResize?.apply(this, arguments)\n }\n return onNodeAdded?.apply(this, arguments)\n }\n\n // Draw a preview of where the node will go if holding shift and the node is selected\n const origDrawNode = LGraphCanvas.prototype.drawNode\n LGraphCanvas.prototype.drawNode = function (node, ctx) {\n if (\n app.shiftDown &&\n this.node_dragged &&\n node.id in this.selected_nodes\n ) {\n const [x, y] = roundVectorToGrid([...node.pos])\n const shiftX = x - node.pos[0]\n let shiftY = y - node.pos[1]\n\n let w, h\n if (node.flags.collapsed) {\n // @ts-expect-error\n w = node._collapsed_width\n h = LiteGraph.NODE_TITLE_HEIGHT\n shiftY -= LiteGraph.NODE_TITLE_HEIGHT\n } else {\n w = node.size[0]\n h = node.size[1]\n // @ts-expect-error\n let titleMode = node.constructor.title_mode\n if (\n titleMode !== LiteGraph.TRANSPARENT_TITLE &&\n titleMode !== LiteGraph.NO_TITLE\n ) {\n h += LiteGraph.NODE_TITLE_HEIGHT\n shiftY -= LiteGraph.NODE_TITLE_HEIGHT\n }\n }\n const f = ctx.fillStyle\n ctx.fillStyle = 'rgba(100, 100, 100, 0.5)'\n ctx.fillRect(shiftX, shiftY, w, h)\n ctx.fillStyle = f\n }\n\n return origDrawNode.apply(this, arguments)\n }\n\n /**\n * The currently moving, selected group only. Set after the `selected_group` has actually started\n * moving.\n */\n let selectedAndMovingGroup: LGraphGroup | null = null\n\n /**\n * Handles moving a group; tracking when a group has been moved (to show the ghost in `drawGroups`\n * below) as well as handle the last move call from LiteGraph's `processMouseUp`.\n */\n const groupMove = LGraphGroup.prototype.move\n LGraphGroup.prototype.move = function (deltax, deltay, ignore_nodes) {\n const v = groupMove.apply(this, arguments)\n // When we've started moving, set `selectedAndMovingGroup` as LiteGraph sets `selected_group`\n // too eagerly and we don't want to behave like we're moving until we get a delta.\n if (\n !selectedAndMovingGroup &&\n app.canvas.selected_group === this &&\n (deltax || deltay)\n ) {\n selectedAndMovingGroup = this\n }\n\n // LiteGraph will call group.move both on mouse-move as well as mouse-up though we only want\n // to snap on a mouse-up which we can determine by checking if `app.canvas.last_mouse_dragging`\n // has been set to `false`. Essentially, this check here is the equivalent to calling an\n // `LGraphGroup.prototype.onNodeMoved` if it had existed.\n if (app.canvas.last_mouse_dragging === false && app.shiftDown) {\n // After moving a group (while app.shiftDown), snap all the child nodes and, finally,\n // align the group itself.\n this.recomputeInsideNodes()\n for (const node of this.nodes) {\n node.alignToGrid()\n }\n LGraphNode.prototype.alignToGrid.apply(this)\n }\n return v\n }\n\n /**\n * Handles drawing a group when, snapping the size when one is actively being resized tracking and/or\n * drawing a ghost box when one is actively being moved. This mimics the node snapping behavior for\n * both.\n */\n const drawGroups = LGraphCanvas.prototype.drawGroups\n LGraphCanvas.prototype.drawGroups = function (canvas, ctx) {\n if (this.selected_group && app.shiftDown) {\n if (this.selected_group_resizing) {\n roundVectorToGrid(this.selected_group.size)\n } else if (selectedAndMovingGroup) {\n const [x, y] = roundVectorToGrid([...selectedAndMovingGroup.pos])\n const f = ctx.fillStyle\n const s = ctx.strokeStyle\n ctx.fillStyle = 'rgba(100, 100, 100, 0.33)'\n ctx.strokeStyle = 'rgba(100, 100, 100, 0.66)'\n ctx.rect(x, y, ...selectedAndMovingGroup.size)\n ctx.fill()\n ctx.stroke()\n ctx.fillStyle = f\n ctx.strokeStyle = s\n }\n } else if (!this.selected_group) {\n selectedAndMovingGroup = null\n }\n return drawGroups.apply(this, arguments)\n }\n\n /** Handles adding a group in a snapping-enabled state. */\n const onGroupAdd = LGraphCanvas.onGroupAdd\n LGraphCanvas.onGroupAdd = function () {\n const v = onGroupAdd.apply(app.canvas, arguments)\n if (app.shiftDown) {\n const lastGroup = app.graph.groups[app.graph.groups.length - 1]\n if (lastGroup) {\n roundVectorToGrid(lastGroup.pos)\n roundVectorToGrid(lastGroup.size)\n }\n }\n return v\n }\n }\n})\n","import { app } from '../../scripts/app'\nimport { ComfyNodeDef } from '@/types/apiTypes'\n\n// Adds an upload button to the nodes\n\napp.registerExtension({\n name: 'Comfy.UploadImage',\n async beforeRegisterNodeDef(nodeType, nodeData: ComfyNodeDef, app) {\n if (nodeData?.input?.required?.image?.[1]?.image_upload === true) {\n nodeData.input.required.upload = ['IMAGEUPLOAD']\n }\n }\n})\n","import { app } from '../../scripts/app'\nimport { api } from '../../scripts/api'\n\nconst WEBCAM_READY = Symbol()\n\napp.registerExtension({\n name: 'Comfy.WebcamCapture',\n getCustomWidgets(app) {\n return {\n WEBCAM(node, inputName) {\n let res\n node[WEBCAM_READY] = new Promise((resolve) => (res = resolve))\n\n const container = document.createElement('div')\n container.style.background = 'rgba(0,0,0,0.25)'\n container.style.textAlign = 'center'\n\n const video = document.createElement('video')\n video.style.height = video.style.width = '100%'\n\n const loadVideo = async () => {\n try {\n const stream = await navigator.mediaDevices.getUserMedia({\n video: true,\n audio: false\n })\n container.replaceChildren(video)\n\n setTimeout(() => res(video), 500) // Fallback as loadedmetadata doesnt fire sometimes?\n video.addEventListener('loadedmetadata', () => res(video), false)\n video.srcObject = stream\n video.play()\n } catch (error) {\n const label = document.createElement('div')\n label.style.color = 'red'\n label.style.overflow = 'auto'\n label.style.maxHeight = '100%'\n label.style.whiteSpace = 'pre-wrap'\n\n if (window.isSecureContext) {\n label.textContent =\n 'Unable to load webcam, please ensure access is granted:\\n' +\n error.message\n } else {\n label.textContent =\n 'Unable to load webcam. A secure context is required, if you are not accessing ComfyUI on localhost (127.0.0.1) you will have to enable TLS (https)\\n\\n' +\n error.message\n }\n\n container.replaceChildren(label)\n }\n }\n\n loadVideo()\n\n return { widget: node.addDOMWidget(inputName, 'WEBCAM', container) }\n }\n }\n },\n nodeCreated(node) {\n if ((node.type, node.constructor.comfyClass !== 'WebcamCapture')) return\n\n let video\n const camera = node.widgets.find((w) => w.name === 'image')\n const w = node.widgets.find((w) => w.name === 'width')\n const h = node.widgets.find((w) => w.name === 'height')\n const captureOnQueue = node.widgets.find(\n (w) => w.name === 'capture_on_queue'\n )\n\n const canvas = document.createElement('canvas')\n\n const capture = () => {\n canvas.width = w.value\n canvas.height = h.value\n const ctx = canvas.getContext('2d')\n ctx.drawImage(video, 0, 0, w.value, h.value)\n const data = canvas.toDataURL('image/png')\n\n const img = new Image()\n img.onload = () => {\n node.imgs = [img]\n app.graph.setDirtyCanvas(true)\n requestAnimationFrame(() => {\n node.setSizeForImage?.()\n })\n }\n img.src = data\n }\n\n const btn = node.addWidget(\n 'button',\n 'waiting for camera...',\n 'capture',\n capture\n )\n btn.disabled = true\n btn.serializeValue = () => undefined\n\n camera.serializeValue = async () => {\n if (captureOnQueue.value) {\n capture()\n } else if (!node.imgs?.length) {\n const err = `No webcam image captured`\n alert(err)\n throw new Error(err)\n }\n\n // Upload image to temp storage\n const blob = await new Promise((r) => canvas.toBlob(r))\n const name = `${+new Date()}.png`\n const file = new File([blob], name)\n const body = new FormData()\n body.append('image', file)\n body.append('subfolder', 'webcam')\n body.append('type', 'temp')\n const resp = await api.fetchApi('/upload/image', {\n method: 'POST',\n body\n })\n if (resp.status !== 200) {\n const err = `Error uploading camera image: ${resp.status} - ${resp.statusText}`\n alert(err)\n throw new Error(err)\n }\n return `webcam/${name} [temp]`\n }\n\n node[WEBCAM_READY].then((v) => {\n video = v\n // If width isnt specified then use video output resolution\n if (!w.value) {\n w.value = video.videoWidth || 640\n h.value = video.videoHeight || 480\n }\n btn.disabled = false\n btn.label = 'capture'\n })\n }\n})\n","import { app } from '../../scripts/app'\nimport { api } from '../../scripts/api'\nimport type { IWidget } from '@comfyorg/litegraph'\nimport type { DOMWidget } from '@/scripts/domWidget'\nimport { ComfyNodeDef } from '@/types/apiTypes'\n\ntype FolderType = 'input' | 'output' | 'temp'\n\nfunction splitFilePath(path: string): [string, string] {\n const folder_separator = path.lastIndexOf('/')\n if (folder_separator === -1) {\n return ['', path]\n }\n return [\n path.substring(0, folder_separator),\n path.substring(folder_separator + 1)\n ]\n}\n\nfunction getResourceURL(\n subfolder: string,\n filename: string,\n type: FolderType = 'input'\n): string {\n const params = [\n 'filename=' + encodeURIComponent(filename),\n 'type=' + type,\n 'subfolder=' + subfolder,\n app.getRandParam().substring(1)\n ].join('&')\n\n return `/view?${params}`\n}\n\nasync function uploadFile(\n audioWidget: IWidget,\n audioUIWidget: DOMWidget,\n file: File,\n updateNode: boolean,\n pasted: boolean = false\n) {\n try {\n // Wrap file in formdata so it includes filename\n const body = new FormData()\n body.append('image', file)\n if (pasted) body.append('subfolder', 'pasted')\n const resp = await api.fetchApi('/upload/image', {\n method: 'POST',\n body\n })\n\n if (resp.status === 200) {\n const data = await resp.json()\n // Add the file to the dropdown list and update the widget value\n let path = data.name\n if (data.subfolder) path = data.subfolder + '/' + path\n\n if (!audioWidget.options.values.includes(path)) {\n audioWidget.options.values.push(path)\n }\n\n if (updateNode) {\n audioUIWidget.element.src = api.apiURL(\n getResourceURL(...splitFilePath(path))\n )\n audioWidget.value = path\n }\n } else {\n alert(resp.status + ' - ' + resp.statusText)\n }\n } catch (error) {\n alert(error)\n }\n}\n\n// AudioWidget MUST be registered first, as AUDIOUPLOAD depends on AUDIO_UI to be\n// present.\napp.registerExtension({\n name: 'Comfy.AudioWidget',\n async beforeRegisterNodeDef(nodeType, nodeData) {\n if (\n ['LoadAudio', 'SaveAudio', 'PreviewAudio'].includes(nodeType.comfyClass)\n ) {\n nodeData.input.required.audioUI = ['AUDIO_UI']\n }\n },\n getCustomWidgets() {\n return {\n AUDIO_UI(node, inputName: string) {\n const audio = document.createElement('audio')\n audio.controls = true\n audio.classList.add('comfy-audio')\n audio.setAttribute('name', 'media')\n\n const audioUIWidget: DOMWidget = node.addDOMWidget(\n inputName,\n /* name=*/ 'audioUI',\n audio\n )\n // @ts-expect-error\n // TODO: Sort out the DOMWidget type.\n audioUIWidget.serialize = false\n\n const isOutputNode = node.constructor.nodeData.output_node\n if (isOutputNode) {\n // Hide the audio widget when there is no audio initially.\n audioUIWidget.element.classList.add('empty-audio-widget')\n // Populate the audio widget UI on node execution.\n const onExecuted = node.onExecuted\n node.onExecuted = function (message) {\n onExecuted?.apply(this, arguments)\n const audios = message.audio\n if (!audios) return\n const audio = audios[0]\n audioUIWidget.element.src = api.apiURL(\n getResourceURL(audio.subfolder, audio.filename, audio.type)\n )\n audioUIWidget.element.classList.remove('empty-audio-widget')\n }\n }\n return { widget: audioUIWidget }\n }\n }\n },\n onNodeOutputsUpdated(nodeOutputs: Record) {\n for (const [nodeId, output] of Object.entries(nodeOutputs)) {\n const node = app.graph.getNodeById(nodeId)\n if ('audio' in output) {\n const audioUIWidget = node.widgets.find(\n (w) => w.name === 'audioUI'\n ) as unknown as DOMWidget\n const audio = output.audio[0]\n audioUIWidget.element.src = api.apiURL(\n getResourceURL(audio.subfolder, audio.filename, audio.type)\n )\n audioUIWidget.element.classList.remove('empty-audio-widget')\n }\n }\n }\n})\n\napp.registerExtension({\n name: 'Comfy.UploadAudio',\n async beforeRegisterNodeDef(nodeType, nodeData: ComfyNodeDef) {\n if (nodeData?.input?.required?.audio?.[1]?.audio_upload === true) {\n nodeData.input.required.upload = ['AUDIOUPLOAD']\n }\n },\n getCustomWidgets() {\n return {\n AUDIOUPLOAD(node, inputName: string) {\n // The widget that allows user to select file.\n const audioWidget: IWidget = node.widgets.find(\n (w: IWidget) => w.name === 'audio'\n )\n const audioUIWidget: DOMWidget = node.widgets.find(\n (w: IWidget) => w.name === 'audioUI'\n )\n\n const onAudioWidgetUpdate = () => {\n audioUIWidget.element.src = api.apiURL(\n getResourceURL(...splitFilePath(audioWidget.value))\n )\n }\n // Initially load default audio file to audioUIWidget.\n if (audioWidget.value) {\n onAudioWidgetUpdate()\n }\n audioWidget.callback = onAudioWidgetUpdate\n\n // Load saved audio file widget values if restoring from workflow\n const onGraphConfigured = node.onGraphConfigured\n node.onGraphConfigured = function () {\n onGraphConfigured?.apply(this, arguments)\n if (audioWidget.value) {\n onAudioWidgetUpdate()\n }\n }\n\n const fileInput = document.createElement('input')\n fileInput.type = 'file'\n fileInput.accept = 'audio/*'\n fileInput.style.display = 'none'\n fileInput.onchange = () => {\n if (fileInput.files.length) {\n uploadFile(audioWidget, audioUIWidget, fileInput.files[0], true)\n }\n }\n // The widget to pop up the upload dialog.\n const uploadWidget = node.addWidget(\n 'button',\n inputName,\n /* value=*/ '',\n () => {\n fileInput.click()\n }\n )\n uploadWidget.label = 'choose file to upload'\n uploadWidget.serialize = false\n\n return { widget: uploadWidget }\n }\n }\n }\n})\n","import { app, type ComfyApp } from '@/scripts/app'\nimport type { ComfyExtension } from '@/types/comfy'\nimport type { ComfyLGraphNode } from '@/types/comfyLGraphNode'\nimport { LGraphBadge } from '@comfyorg/litegraph'\nimport { useSettingStore } from '@/stores/settingStore'\nimport { computed, ComputedRef, watch } from 'vue'\nimport { NodeBadgeMode, NodeSource, NodeSourceType } from '@/types/nodeSource'\nimport _ from 'lodash'\nimport { getColorPalette, defaultColorPalette } from './colorPalette'\nimport { BadgePosition } from '@comfyorg/litegraph'\nimport type { Palette } from '@/types/colorPalette'\nimport type { ComfyNodeDef } from '@/types/apiTypes'\nimport { useNodeDefStore } from '@/stores/nodeDefStore'\n\nfunction getNodeSource(node: ComfyLGraphNode): NodeSource | null {\n const nodeDef = (node.constructor as typeof ComfyLGraphNode)\n .nodeData as ComfyNodeDef\n // Frontend-only nodes don't have nodeDef\n if (!nodeDef) {\n return null\n }\n const nodeDefStore = useNodeDefStore()\n return nodeDefStore.nodeDefsByName[nodeDef.name]?.nodeSource ?? null\n}\n\nfunction isCoreNode(node: ComfyLGraphNode) {\n return getNodeSource(node)?.type === NodeSourceType.Core\n}\n\nfunction badgeTextVisible(\n node: ComfyLGraphNode,\n badgeMode: NodeBadgeMode\n): boolean {\n return (\n badgeMode === NodeBadgeMode.None ||\n (isCoreNode(node) && badgeMode === NodeBadgeMode.HideBuiltIn)\n )\n}\n\nfunction getNodeIdBadgeText(\n node: ComfyLGraphNode,\n nodeIdBadgeMode: NodeBadgeMode\n) {\n return badgeTextVisible(node, nodeIdBadgeMode) ? '' : `#${node.id}`\n}\n\nfunction getNodeSourceBadgeText(\n node: ComfyLGraphNode,\n nodeSourceBadgeMode: NodeBadgeMode\n) {\n const nodeSource = getNodeSource(node)\n return badgeTextVisible(node, nodeSourceBadgeMode)\n ? ''\n : nodeSource?.badgeText ?? ''\n}\n\nfunction getNodeLifeCycleBadgeText(\n node: ComfyLGraphNode,\n nodeLifeCycleBadgeMode: NodeBadgeMode\n) {\n let text = ''\n const nodeDef = (node.constructor as typeof ComfyLGraphNode).nodeData\n\n // Frontend-only nodes don't have nodeDef\n if (!nodeDef) {\n return ''\n }\n\n if (nodeDef.deprecated) {\n text = '[DEPR]'\n }\n\n if (nodeDef.experimental) {\n text = '[BETA]'\n }\n\n return badgeTextVisible(node, nodeLifeCycleBadgeMode) ? '' : text\n}\n\nclass NodeBadgeExtension implements ComfyExtension {\n name = 'Comfy.NodeBadge'\n\n constructor(\n public nodeIdBadgeMode: ComputedRef | null = null,\n public nodeSourceBadgeMode: ComputedRef | null = null,\n public nodeLifeCycleBadgeMode: ComputedRef | null = null,\n public colorPalette: ComputedRef | null = null\n ) {}\n\n init(app: ComfyApp) {\n const settingStore = useSettingStore()\n this.nodeSourceBadgeMode = computed(\n () =>\n settingStore.get('Comfy.NodeBadge.NodeSourceBadgeMode') as NodeBadgeMode\n )\n this.nodeIdBadgeMode = computed(\n () => settingStore.get('Comfy.NodeBadge.NodeIdBadgeMode') as NodeBadgeMode\n )\n this.nodeLifeCycleBadgeMode = computed(\n () =>\n settingStore.get(\n 'Comfy.NodeBadge.NodeLifeCycleBadgeMode'\n ) as NodeBadgeMode\n )\n this.colorPalette = computed(() =>\n getColorPalette(settingStore.get('Comfy.ColorPalette'))\n )\n\n watch(this.nodeSourceBadgeMode, () => {\n app.graph.setDirtyCanvas(true, true)\n })\n\n watch(this.nodeIdBadgeMode, () => {\n app.graph.setDirtyCanvas(true, true)\n })\n watch(this.nodeLifeCycleBadgeMode, () => {\n app.graph.setDirtyCanvas(true, true)\n })\n }\n\n nodeCreated(node: ComfyLGraphNode, app: ComfyApp) {\n node.badgePosition = BadgePosition.TopRight\n // @ts-expect-error Disable ComfyUI-Manager's badge drawing by setting badge_enabled to true. Remove this when ComfyUI-Manager's badge drawing is removed.\n node.badge_enabled = true\n\n const badge = computed(\n () =>\n new LGraphBadge({\n text: _.truncate(\n [\n getNodeIdBadgeText(node, this.nodeIdBadgeMode.value),\n getNodeLifeCycleBadgeText(\n node,\n this.nodeLifeCycleBadgeMode.value\n ),\n getNodeSourceBadgeText(node, this.nodeSourceBadgeMode.value)\n ]\n .filter((s) => s.length > 0)\n .join(' '),\n {\n length: 31\n }\n ),\n fgColor:\n this.colorPalette.value.colors.litegraph_base?.BADGE_FG_COLOR ||\n defaultColorPalette.colors.litegraph_base.BADGE_FG_COLOR,\n bgColor:\n this.colorPalette.value.colors.litegraph_base?.BADGE_BG_COLOR ||\n defaultColorPalette.colors.litegraph_base.BADGE_BG_COLOR\n })\n )\n\n node.badges.push(() => badge.value)\n }\n}\n\napp.registerExtension(new NodeBadgeExtension())\n"],"names":["app","id","defaultColorPalette","file","ext","prompt","links","_","widget","w","type","def","node","link","selectedIds","newNodes","i","group","modal","PointerType","CompositionOperation","x","y","audio","LGraphBadge"],"mappings":";;;AAIO,MAAM,wBAAwB,YAAY;AAAA,SAAA;AAAA;AAAA;AAAA,EAC/C,OAAO,QAAQ,CAAA;AAAA,EACf,OAAO,WAAW;AAAA,EAElB,OAAO,eAAe,MAAM,kBAAkB,UAAU;AAChD,UAAA,OAAO,IAAI,UAAU;AAAA,MACzB,MAAM;AAAA,MACN,aAAa;AAAA,MACb;AAAA,MACA,SAAS;AAAA,IAAA,CACV;AAEe,oBAAA,MAAM,KAAK,IAAI;AAAA,EACjC;AAAA,EAEA,OAAO,oBAAoB;AAEvB,QAAA,SAAS,aACT,SAAS,UAAU,QACnB,SAAS,UAAU,KAAK,SAAS,GACjC;AACA,YAAM,cAAc,SAAS;AAAA,QAC3B;AAAA,MAAA;AAEF,U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AAK,eAAe;AAAA,MAAS,MAC3B,gBAAgB,aAAa,IAAI,oBAAoB,CAAC;AAAA,IAAA;AAGlD,UAAA,KAAK,qBAAqB,MAAM;AACpCA,WAAI,MAAM,eAAe,MAAM,IAAI;AAAA,IAAA,CACpC;AAEK,UAAA,KAAK,iBAAiB,MAAM;AAChCA,WAAI,MAAM,eAAe,MAAM,IAAI;AAAA,IAAA,CACpC;AACK,UAAA,KAAK,wBAAwB,MAAM;AACvCA,WAAI,MAAM,eAAe,MAAM,IAAI;AAAA,IAAA,CACpC;AAAA,EACH;AAAA,EAEA,YAAY,MAAuBA,MAAe;AAChD,SAAK,gBAAgB,cAAc;AAEnC,SAAK,gBAAgB;AAErB,UAAM,QAAQ;AAAA,MACZ,MACE,IAAIwB,cAAY;AAAA,QACd,MAAM,EAAE;AAAA,UACN;AAAA,YACE,mBAAmB,MAAM,KAAK,gBAAgB,KAAK;AAAA,YACnD;AAAA,cACE;AAAA,cACA,KAAK,uBAAuB;AAAA,YAC9B;AAAA,YACA,uBAAuB,MAAM,KAAK,oBAAoB,KAAK;AAAA,UAAA,EAE1D,OAAO,CAAC,MAAM,EAAE,SAAS,CAAC,EAC1B,KAAK,GAAG;AAAA,UACX;AAAA,YACE,QAAQ;AAAA,UACV;AAAA,QACF;AAAA,QACA,SACE,KAAK,aAAa,MAAM,OAAO,gBAAgB,kBAC/C,oBAAoB,OAAO,eAAe;AAAA,QAC5C,SACE,KAAK,aAAa,MAAM,OAAO,gBAAgB,kBAC/C,oBAAoB,OAAO,eAAe;AAAA,MAAA,CAC7C;AAAA,IAAA;AAGL,SAAK,OAAO,KAAK,MAAM,MAAM,KAAK;AAAA,EACpC;AACF;AAEA,IAAI,kBAAkB,IAAI,oBAAoB;"}
\ No newline at end of file
diff --git a/web/extensions/core/groupNodeManage.css b/web/assets/index-BRhY6FpL.css
similarity index 100%
rename from web/extensions/core/groupNodeManage.css
rename to web/assets/index-BRhY6FpL.css
diff --git a/web/assets/index-Drc_oD2f.js b/web/assets/index-Drc_oD2f.js
new file mode 100644
index 000000000..4f59c8808
--- /dev/null
+++ b/web/assets/index-Drc_oD2f.js
@@ -0,0 +1,102002 @@
+const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-BDBCRrlL.js","./index-BRhY6FpL.css","./userSelection-BM5u5JIA.js","./userSelection-CF-ymHZW.css","./GraphView-DN9xGvF3.js","./GraphView-DXU9yRen.css"])))=>i.map(i=>d[i]);
+var __defProp2 = Object.defineProperty;
+var __name = (target, value3) => __defProp2(target, "name", { value: value3, configurable: true });
+(/* @__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 root23 = typeof globalThis === "object" ? globalThis : typeof commonjsGlobal === "object" ? commonjsGlobal : typeof self === "object" ? self : typeof this === "object" ? this : sloppyModeThis();
+ var exporter = makeExporter(Reflect2);
+ if (typeof root23.Reflect !== "undefined") {
+ exporter = makeExporter(root23.Reflect, exporter);
+ }
+ factory(exporter, root23);
+ if (typeof root23.Reflect === "undefined") {
+ root23.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, root23) {
+ 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 _a = 0, parentKeys_1 = parentKeys; _a < parentKeys_1.length; _a++) {
+ var key = parentKeys_1[_a];
+ 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 prototype2 = O.prototype;
+ var prototypeProto = prototype2 && Object.getPrototypeOf(prototype2);
+ 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 root23.Reflect !== "undefined" && !(registrySymbol in root23.Reflect) && typeof root23.Reflect.defineMetadata === "function") {
+ fallback = CreateFallbackProvider(root23.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(root23.Reflect) && Object.isExtensible(root23.Reflect)) {
+ metadataRegistry2 = root23.Reflect[registrySymbol];
+ }
+ if (IsUndefined(metadataRegistry2)) {
+ metadataRegistry2 = CreateMetadataRegistry();
+ }
+ if (!IsUndefined(registrySymbol) && IsObject(root23.Reflect) && Object.isExtensible(root23.Reflect)) {
+ Object.defineProperty(root23.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, getKey2);
+ };
+ 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 getKey2(key, _2) {
+ return key;
+ }
+ __name(getKey2, "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 data22 = GenRandomBytes(UUID_SIZE);
+ data22[6] = data22[6] & 79 | 64;
+ data22[8] = data22[8] & 191 | 128;
+ var result = "";
+ for (var offset = 0; offset < UUID_SIZE; ++offset) {
+ var byte = data22[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.60";
+console.log("ComfyUI Front-end version:", "1.2.60");
+/**
+* @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$1 = 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$3 = Object.prototype.hasOwnProperty;
+const hasOwn$3 = /* @__PURE__ */ __name((val, key) => hasOwnProperty$3.call(val, key), "hasOwn$3");
+const isArray$5 = 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$3 = /* @__PURE__ */ __name((val) => toTypeString$1(val) === "[object Date]", "isDate$3");
+const isRegExp$2 = /* @__PURE__ */ __name((val) => toTypeString$1(val) === "[object RegExp]", "isRegExp$2");
+const isFunction$3 = /* @__PURE__ */ __name((val) => typeof val === "function", "isFunction$3");
+const isString$5 = /* @__PURE__ */ __name((val) => typeof val === "string", "isString$5");
+const isSymbol$1 = /* @__PURE__ */ __name((val) => typeof val === "symbol", "isSymbol$1");
+const isObject$6 = /* @__PURE__ */ __name((val) => val !== null && typeof val === "object", "isObject$6");
+const isPromise$2 = /* @__PURE__ */ __name((val) => {
+ return (isObject$6(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$3 = /* @__PURE__ */ __name((val) => toTypeString$1(val) === "[object Object]", "isPlainObject$3");
+const isIntegerKey = /* @__PURE__ */ __name((key) => isString$5(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$5(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$5(value3)) {
+ const res = {};
+ for (let i2 = 0; i2 < value3.length; i2++) {
+ const item2 = value3[i2];
+ const normalized = isString$5(item2) ? parseStringStyle(item2) : normalizeStyle(item2);
+ if (normalized) {
+ for (const key in normalized) {
+ res[key] = normalized[key];
+ }
+ }
+ }
+ return res;
+ } else if (isString$5(value3) || isObject$6(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$5(styles)) {
+ return ret;
+ }
+ for (const key in styles) {
+ const value3 = styles[key];
+ if (isString$5(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$5(value3)) {
+ res = value3;
+ } else if (isArray$5(value3)) {
+ for (let i2 = 0; i2 < value3.length; i2++) {
+ const normalized = normalizeClass(value3[i2]);
+ if (normalized) {
+ res += normalized + " ";
+ }
+ }
+ } else if (isObject$6(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$5(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$5(val) ? val : val == null ? "" : isArray$5(val) || isObject$6(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$6(val) && !isArray$5(val) && !isPlainObject$3(val)) {
+ return String(val);
+ }
+ return val;
+}, "replacer");
+const stringifySymbol = /* @__PURE__ */ __name((v2, i2 = "") => {
+ var _a;
+ return (
+ // Symbol.description in es2019+ so we need to cast here to pass
+ // the lib: es2016 check
+ isSymbol$1(v2) ? `Symbol(${(_a = v2.description) != null ? _a : 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;
+class EffectScope {
+ static {
+ __name(this, "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;
+ }
+ }
+}
+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;
+class ReactiveEffect {
+ static {
+ __name(this, "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;
+ }
+ }
+}
+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$1(_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 _a;
+ 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) {
+ (_a = effect2.onTrack) == null ? void 0 : _a.call(effect2, extend$1({ effect: effect2 }, debuggerEventExtraInfo));
+ }
+ }
+}
+__name(trackEffect, "trackEffect");
+const queueEffectSchedulers = [];
+function triggerEffects(dep, dirtyLevel, debuggerEventExtraInfo) {
+ var _a;
+ 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) {
+ (_a = effect2.onTrigger) == null ? void 0 : _a.call(effect2, extend$1({ 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$5(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$5(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$5(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$2(key) {
+ if (!isSymbol$1(key)) key = String(key);
+ const obj = toRaw(this);
+ track(obj, "has", key);
+ return obj.hasOwnProperty(key);
+}
+__name(hasOwnProperty$2, "hasOwnProperty$2");
+class BaseReactiveHandler {
+ static {
+ __name(this, "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$5(target);
+ if (!isReadonly2) {
+ if (targetIsArray && hasOwn$3(arrayInstrumentations, key)) {
+ return Reflect.get(arrayInstrumentations, key, receiver);
+ }
+ if (key === "hasOwnProperty") {
+ return hasOwnProperty$2;
+ }
+ }
+ 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$6(res)) {
+ return isReadonly2 ? readonly(res) : reactive(res);
+ }
+ return res;
+ }
+}
+class MutableReactiveHandler extends BaseReactiveHandler {
+ static {
+ __name(this, "MutableReactiveHandler");
+ }
+ 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$5(target) && isRef(oldValue) && !isRef(value3)) {
+ if (isOldValueReadonly) {
+ return false;
+ } else {
+ oldValue.value = value3;
+ return true;
+ }
+ }
+ }
+ const hadKey = isArray$5(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$5(target) ? "length" : ITERATE_KEY
+ );
+ return Reflect.ownKeys(target);
+ }
+}
+class ReadonlyReactiveHandler extends BaseReactiveHandler {
+ static {
+ __name(this, "ReadonlyReactiveHandler");
+ }
+ 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;
+ }
+}
+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 forEach2(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$6(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$6(value3) ? reactive(value3) : value3, "toReactive$1");
+const toReadonly = /* @__PURE__ */ __name((value3) => isObject$6(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`;
+class ComputedRefImpl {
+ static {
+ __name(this, "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
+}
+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 _a;
+ if (shouldTrack && activeEffect) {
+ ref2 = toRaw(ref2);
+ trackEffect(
+ activeEffect,
+ (_a = ref2.dep) != null ? _a : 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");
+class RefImpl {
+ static {
+ __name(this, "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);
+ }
+ }
+}
+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");
+class CustomRefImpl {
+ static {
+ __name(this, "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);
+ }
+}
+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$5(object) ? new Array(object.length) : {};
+ for (const key in object) {
+ ret[key] = propertyToRef(object, key);
+ }
+ return ret;
+}
+__name(toRefs$1, "toRefs$1");
+class ObjectRefImpl {
+ static {
+ __name(this, "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);
+ }
+}
+class GetterRefImpl {
+ static {
+ __name(this, "GetterRefImpl");
+ }
+ constructor(_getter) {
+ this._getter = _getter;
+ this.__v_isRef = true;
+ this.__v_isReadonly = true;
+ }
+ get value() {
+ return this._getter();
+ }
+}
+function toRef$1(source, key, defaultValue) {
+ if (isRef(source)) {
+ return source;
+ } else if (isFunction$3(source)) {
+ return new GetterRefImpl(source);
+ } else if (isObject$6(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$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 _a, _b;
+ return (_b = (_a = a.toString) == null ? void 0 : _a.call(a)) != null ? _b : 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$1, "warn$1$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$5(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$1(`${type} is not a valid number - got ${JSON.stringify(val)}.`);
+ } else if (isNaN(val)) {
+ warn$1$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$5(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$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$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$1(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$1, "findInsertionIndex$1");
+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$1(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$5(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$1(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 _a, _b;
+ 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
+ !((_b = (_a = window.navigator) == null ? void 0 : _a.userAgent) == null ? void 0 : _b.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$1(
+ `Component emitted event "${event2}" but it is neither declared in the emits option nor as an "${toHandlerKey(event2)}" prop.`
+ );
+ }
+ } else {
+ const validator3 = emitsOptions[event2];
+ if (isFunction$3(validator3)) {
+ const isValid2 = validator3(...rawArgs);
+ if (!isValid2) {
+ warn$1$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: trim2 } = props[modifiersKey] || EMPTY_OBJ;
+ if (trim2) {
+ args = rawArgs.map((a) => isString$5(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$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 handler6 = props[handlerName = toHandlerKey(event2)] || // also try camelCase event handler (#2249)
+ props[handlerName = toHandlerKey(camelize$1(event2))];
+ if (!handler6 && isModelListener2) {
+ handler6 = props[handlerName = toHandlerKey(hyphenate$1(event2))];
+ }
+ if (handler6) {
+ callWithAsyncErrorHandling(
+ handler6,
+ 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$1(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$6(comp)) {
+ cache2.set(comp, null);
+ }
+ return null;
+ }
+ if (isArray$5(raw)) {
+ raw.forEach((key) => normalized[key] = null);
+ } else {
+ extend$1(normalized, raw);
+ }
+ if (isObject$6(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: data22,
+ 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$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,
+ data22,
+ 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 root23 = result;
+ let setRoot = void 0;
+ if (false) {
+ [root23, setRoot] = getChildRoot(result);
+ }
+ if (fallthroughAttrs && inheritAttrs !== false) {
+ const keys2 = Object.keys(fallthroughAttrs);
+ const { shapeFlag } = root23;
+ if (keys2.length) {
+ if (shapeFlag & (1 | 6)) {
+ if (propsOptions && keys2.some(isModelListener)) {
+ fallthroughAttrs = filterModelListeners(
+ fallthroughAttrs,
+ propsOptions
+ );
+ }
+ root23 = cloneVNode(root23, 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$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$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$1(
+ `Runtime directive used on component with non-element root node. The directives will not function as intended.`
+ );
+ }
+ root23 = cloneVNode(root23, null, false, true);
+ root23.dirs = root23.dirs ? root23.dirs.concat(vnode.dirs) : vnode.dirs;
+ }
+ if (vnode.transition) {
+ if (false) {
+ warn$1$1(
+ `Component inside renders non-element root node that cannot be animated.`
+ );
+ }
+ root23.transition = vnode.transition;
+ }
+ if (false) {
+ setRoot(root23);
+ } else {
+ result = root23;
+ }
+ 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 root23 = parent.subTree;
+ if (root23.suspense && root23.suspense.activeBranch === vnode) {
+ root23.el = vnode.el;
+ }
+ if (root23 === 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$5(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$1(`Failed to resolve ${type.slice(0, -1)}: ${name}${extra}`);
+ }
+ return res;
+ } else if (false) {
+ warn$1$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$5(s)) {
+ const singleChild = filterSingleRoot(s);
+ if (false) {
+ warn$1$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$5(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$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$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$5(source) || isString$5(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$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$6(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$5(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$1({ 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((resolve2, reject2) => {
+ const userRetry = /* @__PURE__ */ __name(() => resolve2(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$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$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$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$1(/* @__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: data22, 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 data22[key];
+ case 4:
+ return ctx[key];
+ case 3:
+ return props[key];
+ }
+ } else if (hasSetupBinding(setupState, key)) {
+ accessCache[key] = 1;
+ return setupState[key];
+ } else if (data22 !== EMPTY_OBJ && hasOwn$3(data22, key)) {
+ accessCache[key] = 2;
+ return data22[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 (data22 !== EMPTY_OBJ && isReservedPrefix(key[0]) && hasOwn$3(data22, key)) {
+ warn$1$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$1(
+ `Property ${JSON.stringify(key)} was accessed during render but is not defined on instance.`
+ );
+ }
+ }
+ },
+ set({ _: instance }, key, value3) {
+ const { data: data22, setupState, ctx } = instance;
+ if (hasSetupBinding(setupState, key)) {
+ setupState[key] = value3;
+ return true;
+ } else if (false) {
+ warn$1$1(`Cannot mutate \n\n\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'\nimport { fromZodError } from 'zod-validation-error'\n\n// GroupNode is hacking node id to be a string, so we need to allow that.\n// innerNode.id = `${this.node.id}:${i}`\n// Remove it after GroupNode is redesigned.\nexport const zNodeId = z.union([z.number().int(), z.string()])\nexport type NodeId = z.infer\nexport const zSlotIndex = z.union([\n z.number().int(),\n z\n .string()\n .transform((val) => parseInt(val))\n .refine((val) => !isNaN(val), {\n message: 'Invalid number'\n })\n])\n\n// TODO: Investigate usage of array and number as data type usage in custom nodes.\n// Known usage:\n// - https://github.com/rgthree/rgthree-comfy Context Big node is using array as type.\nexport const zDataType = z.union([z.string(), z.array(z.string()), z.number()])\n\n// Definition of an AI model file used in the workflow.\nconst zModelFile = z.object({\n name: z.string(),\n url: z.string().url(),\n hash: z.string().optional(),\n hash_type: z.string().optional(),\n directory: z.string()\n})\n\nconst zComfyLink = z.tuple([\n z.number(), // Link id\n zNodeId, // Node id of source node\n zSlotIndex, // Output slot# of source node\n zNodeId, // Node id of destination node\n zSlotIndex, // Input slot# of destination node\n zDataType // Data type\n])\n\nconst zNodeOutput = z\n .object({\n name: z.string(),\n type: zDataType,\n links: z.array(z.number()).nullable().optional(),\n slot_index: zSlotIndex.optional()\n })\n .passthrough()\n\nconst zNodeInput = z\n .object({\n name: z.string(),\n type: zDataType,\n link: z.number().nullable().optional(),\n slot_index: zSlotIndex.optional()\n })\n .passthrough()\n\nconst zFlags = z\n .object({\n collapsed: z.boolean().optional(),\n pinned: z.boolean().optional(),\n allow_interaction: z.boolean().optional(),\n horizontal: z.boolean().optional(),\n skip_repeated_outputs: z.boolean().optional()\n })\n .passthrough()\n\nconst zProperties = z\n .object({\n ['Node name for S&R']: z.string().optional()\n })\n .passthrough()\n\nconst zVector2 = z.union([\n z\n .object({ 0: z.number(), 1: z.number() })\n .passthrough()\n .transform((v) => [v[0], v[1]]),\n z.tuple([z.number(), z.number()])\n])\n\nconst zWidgetValues = z.union([z.array(z.any()), z.record(z.any())])\n\nconst zComfyNode = z\n .object({\n id: zNodeId,\n type: z.string(),\n pos: zVector2,\n size: zVector2,\n flags: zFlags,\n order: z.number(),\n mode: z.number(),\n inputs: z.array(zNodeInput).optional(),\n outputs: z.array(zNodeOutput).optional(),\n properties: zProperties,\n widgets_values: zWidgetValues.optional(),\n color: z.string().optional(),\n bgcolor: z.string().optional()\n })\n .passthrough()\n\nconst zGroup = z\n .object({\n title: z.string(),\n bounding: z.tuple([z.number(), z.number(), z.number(), z.number()]),\n color: z.string().optional(),\n font_size: z.number().optional(),\n locked: z.boolean().optional()\n })\n .passthrough()\n\nconst zInfo = z\n .object({\n name: z.string(),\n author: z.string(),\n description: z.string(),\n version: z.string(),\n created: z.string(),\n modified: z.string(),\n software: z.string()\n })\n .passthrough()\n\nconst zDS = z\n .object({\n scale: z.number(),\n offset: zVector2\n })\n .passthrough()\n\nconst zConfig = z\n .object({\n links_ontop: z.boolean().optional(),\n align_to_grid: z.boolean().optional()\n })\n .passthrough()\n\nconst zExtra = z\n .object({\n ds: zDS.optional(),\n info: zInfo.optional()\n })\n .passthrough()\n\nexport const zComfyWorkflow = z\n .object({\n last_node_id: zNodeId,\n last_link_id: z.number(),\n nodes: z.array(zComfyNode),\n links: z.array(zComfyLink),\n groups: z.array(zGroup).optional(),\n config: zConfig.optional().nullable(),\n extra: zExtra.optional().nullable(),\n version: z.number(),\n models: z.array(zModelFile).optional()\n })\n .passthrough()\n\nexport type NodeInput = z.infer\nexport type NodeOutput = z.infer\nexport type ComfyLink = z.infer\nexport type ComfyNode = z.infer\nexport type ComfyWorkflowJSON = z.infer\n\nexport async function validateComfyWorkflow(\n data: any,\n onError: (error: string) => void = console.warn\n): Promise {\n const result = await zComfyWorkflow.safeParseAsync(data)\n if (!result.success) {\n const error = fromZodError(result.error)\n onError(`Invalid workflow against zod schema:\\n${error}`)\n return null\n }\n return result.data\n}\n","import { z } from 'zod'\n\nconst nodeSlotSchema = z\n .object({\n BOOLEAN: z.string().optional(),\n CLIP: z.string(),\n CLIP_VISION: z.string(),\n CLIP_VISION_OUTPUT: z.string(),\n CONDITIONING: z.string(),\n CONTROL_NET: z.string(),\n CONTROL_NET_WEIGHTS: z.string().optional(),\n FLOAT: z.string().optional(),\n GLIGEN: z.string().optional(),\n IMAGE: z.string(),\n IMAGEUPLOAD: z.string().optional(),\n INT: z.string().optional(),\n LATENT: z.string(),\n LATENT_KEYFRAME: z.string().optional(),\n MASK: z.string(),\n MODEL: z.string(),\n SAMPLER: z.string().optional(),\n SIGMAS: z.string().optional(),\n STRING: z.string().optional(),\n STYLE_MODEL: z.string(),\n T2I_ADAPTER_WEIGHTS: z.string().optional(),\n TAESD: z.string(),\n TIMESTEP_KEYFRAME: z.string().optional(),\n UPSCALE_MODEL: z.string().optional(),\n VAE: z.string()\n })\n .passthrough()\n\nconst litegraphBaseSchema = z\n .object({\n BACKGROUND_IMAGE: z.string(),\n CLEAR_BACKGROUND_COLOR: z.string(),\n NODE_TITLE_COLOR: z.string(),\n NODE_SELECTED_TITLE_COLOR: z.string(),\n NODE_TEXT_SIZE: z.number(),\n NODE_TEXT_COLOR: z.string(),\n NODE_SUBTEXT_SIZE: z.number(),\n NODE_DEFAULT_COLOR: z.string(),\n NODE_DEFAULT_BGCOLOR: z.string(),\n NODE_DEFAULT_BOXCOLOR: z.string(),\n NODE_DEFAULT_SHAPE: z.string(),\n NODE_BOX_OUTLINE_COLOR: z.string(),\n DEFAULT_SHADOW_COLOR: z.string(),\n DEFAULT_GROUP_FONT: z.number(),\n WIDGET_BGCOLOR: z.string(),\n WIDGET_OUTLINE_COLOR: z.string(),\n WIDGET_TEXT_COLOR: z.string(),\n WIDGET_SECONDARY_TEXT_COLOR: z.string(),\n LINK_COLOR: z.string(),\n EVENT_LINK_COLOR: z.string(),\n CONNECTING_LINK_COLOR: z.string(),\n BADGE_FG_COLOR: z.string().optional(),\n BADGE_BG_COLOR: z.string().optional()\n })\n .passthrough()\n\nconst comfyBaseSchema = z.object({\n ['fg-color']: z.string(),\n ['bg-color']: z.string(),\n ['bg-img']: z.string().optional(),\n ['comfy-menu-bg']: z.string(),\n ['comfy-input-bg']: z.string(),\n ['input-text']: z.string(),\n ['descrip-text']: z.string(),\n ['drag-text']: z.string(),\n ['error-text']: z.string(),\n ['border-color']: z.string(),\n ['tr-even-bg-color']: z.string(),\n ['tr-odd-bg-color']: z.string(),\n ['content-bg']: z.string(),\n ['content-fg']: z.string(),\n ['content-hover-bg']: z.string(),\n ['content-hover-fg']: z.string()\n})\n\nconst colorsSchema = z\n .object({\n node_slot: nodeSlotSchema,\n litegraph_base: litegraphBaseSchema,\n comfy_base: comfyBaseSchema\n })\n .passthrough()\n\nconst paletteSchema = z.object({\n id: z.string(),\n name: z.string(),\n colors: colorsSchema\n})\n\nexport const colorPalettesSchema = z.record(paletteSchema)\n\nexport type Colors = z.infer\nexport type Palette = z.infer\nexport type ColorPalettes = z.infer\n","export enum LinkReleaseTriggerMode {\n ALWAYS = 'always',\n HOLD_SHIFT = 'hold shift',\n NOT_HOLD_SHIFT = 'NOT hold shift'\n}\n\nexport enum LinkReleaseTriggerAction {\n CONTEXT_MENU = 'context menu',\n SEARCH_BOX = 'search box',\n NO_ACTION = 'no action'\n}\n","export enum NodeSourceType {\n Core = 'core',\n CustomNodes = 'custom_nodes',\n Unknown = 'unknown'\n}\n\nexport type NodeSource = {\n type: NodeSourceType\n className: string\n displayText: string\n badgeText: string\n}\n\nconst UNKNOWN_NODE_SOURCE: NodeSource = {\n type: NodeSourceType.Unknown,\n className: 'comfy-unknown',\n displayText: 'Unknown',\n badgeText: '?'\n}\n\nconst shortenNodeName = (name: string) => {\n return name\n .replace(/^(ComfyUI-|ComfyUI_|Comfy-|Comfy_)/, '')\n .replace(/(-ComfyUI|_ComfyUI|-Comfy|_Comfy)$/, '')\n}\n\nexport const getNodeSource = (python_module?: string): NodeSource => {\n if (!python_module) {\n return UNKNOWN_NODE_SOURCE\n }\n const modules = python_module.split('.')\n if (['nodes', 'comfy_extras'].includes(modules[0])) {\n return {\n type: NodeSourceType.Core,\n className: 'comfy-core',\n displayText: 'Comfy Core',\n badgeText: '🦊'\n }\n } else if (modules[0] === 'custom_nodes') {\n const displayName = shortenNodeName(modules[1])\n return {\n type: NodeSourceType.CustomNodes,\n className: 'comfy-custom-nodes',\n displayText: displayName,\n badgeText: displayName\n }\n } else {\n return UNKNOWN_NODE_SOURCE\n }\n}\n\nexport enum NodeBadgeMode {\n None = 'None',\n ShowAll = 'Show all',\n HideBuiltIn = 'Hide built-in'\n}\n","import { ZodType, z } from 'zod'\nimport { zComfyWorkflow, zNodeId } from './comfyWorkflow'\nimport { fromZodError } from 'zod-validation-error'\nimport { colorPalettesSchema } from './colorPalette'\nimport { LinkReleaseTriggerAction } from './searchBoxTypes'\nimport { NodeBadgeMode } from './nodeSource'\n\nconst zNodeType = z.string()\nconst zQueueIndex = z.number()\nconst zPromptId = z.string()\nconst zResultItem = z.object({\n filename: z.string(),\n subfolder: z.string().optional(),\n type: z.string()\n})\nexport type ResultItem = z.infer\nconst zOutputs = z\n .object({\n audio: z.array(zResultItem).optional(),\n images: z.array(zResultItem).optional()\n })\n .passthrough()\n\n// WS messages\nconst zStatusWsMessageStatus = z.object({\n exec_info: z.object({\n queue_remaining: z.number().int()\n })\n})\n\nconst zStatusWsMessage = z.object({\n status: zStatusWsMessageStatus.nullable().optional()\n})\n\nconst zProgressWsMessage = z.object({\n value: z.number().int(),\n max: z.number().int(),\n prompt_id: zPromptId,\n node: zNodeId\n})\n\nconst zExecutingWsMessage = z.object({\n node: zNodeId,\n display_node: zNodeId,\n prompt_id: zPromptId\n})\n\nconst zExecutedWsMessage = zExecutingWsMessage.extend({\n outputs: zOutputs\n})\n\nconst zExecutionWsMessageBase = z.object({\n prompt_id: zPromptId,\n timestamp: z.number().int()\n})\n\nconst zExecutionStartWsMessage = zExecutionWsMessageBase\nconst zExecutionSuccessWsMessage = zExecutionWsMessageBase\nconst zExecutionCachedWsMessage = zExecutionWsMessageBase.extend({\n nodes: z.array(zNodeId)\n})\nconst zExecutionInterruptedWsMessage = zExecutionWsMessageBase.extend({\n node_id: zNodeId,\n node_type: zNodeType,\n executed: z.array(zNodeId)\n})\nconst zExecutionErrorWsMessage = zExecutionWsMessageBase.extend({\n node_id: zNodeId,\n node_type: zNodeType,\n executed: z.array(zNodeId),\n exception_message: z.string(),\n exception_type: z.string(),\n traceback: z.array(z.string()),\n current_inputs: z.any(),\n current_outputs: z.any()\n})\n\nconst zDownloadModelStatus = z.object({\n status: z.string(),\n progress_percentage: z.number(),\n message: z.string(),\n download_path: z.string(),\n already_existed: z.boolean()\n})\n\nexport type StatusWsMessageStatus = z.infer\nexport type StatusWsMessage = z.infer\nexport type ProgressWsMessage = z.infer\nexport type ExecutingWsMessage = z.infer\nexport type ExecutedWsMessage = z.infer\nexport type ExecutionStartWsMessage = z.infer\nexport type ExecutionSuccessWsMessage = z.infer<\n typeof zExecutionSuccessWsMessage\n>\nexport type ExecutionCachedWsMessage = z.infer\nexport type ExecutionInterruptedWsMessage = z.infer<\n typeof zExecutionInterruptedWsMessage\n>\nexport type ExecutionErrorWsMessage = z.infer\n\nexport type DownloadModelStatus = z.infer\n// End of ws messages\n\nconst zPromptInputItem = z.object({\n inputs: z.record(z.string(), z.any()),\n class_type: zNodeType\n})\n\nconst zPromptInputs = z.record(zPromptInputItem)\n\nconst zExtraPngInfo = z\n .object({\n workflow: zComfyWorkflow\n })\n .passthrough()\n\nconst zExtraData = z.object({\n extra_pnginfo: zExtraPngInfo,\n client_id: z.string()\n})\nconst zOutputsToExecute = z.array(zNodeId)\n\nconst zExecutionStartMessage = z.tuple([\n z.literal('execution_start'),\n zExecutionStartWsMessage\n])\n\nconst zExecutionSuccessMessage = z.tuple([\n z.literal('execution_success'),\n zExecutionSuccessWsMessage\n])\n\nconst zExecutionCachedMessage = z.tuple([\n z.literal('execution_cached'),\n zExecutionCachedWsMessage\n])\n\nconst zExecutionInterruptedMessage = z.tuple([\n z.literal('execution_interrupted'),\n zExecutionInterruptedWsMessage\n])\n\nconst zExecutionErrorMessage = z.tuple([\n z.literal('execution_error'),\n zExecutionErrorWsMessage\n])\n\nconst zStatusMessage = z.union([\n zExecutionStartMessage,\n zExecutionSuccessMessage,\n zExecutionCachedMessage,\n zExecutionInterruptedMessage,\n zExecutionErrorMessage\n])\n\nconst zStatus = z.object({\n status_str: z.enum(['success', 'error']),\n completed: z.boolean(),\n messages: z.array(zStatusMessage)\n})\n\nconst zTaskPrompt = z.tuple([\n zQueueIndex,\n zPromptId,\n zPromptInputs,\n zExtraData,\n zOutputsToExecute\n])\n\nconst zRunningTaskItem = z.object({\n taskType: z.literal('Running'),\n prompt: zTaskPrompt,\n // @Deprecated\n remove: z.object({\n name: z.literal('Cancel'),\n cb: z.function()\n })\n})\n\nconst zPendingTaskItem = z.object({\n taskType: z.literal('Pending'),\n prompt: zTaskPrompt\n})\n\nconst zTaskOutput = z.record(zNodeId, zOutputs)\n\nconst zHistoryTaskItem = z.object({\n taskType: z.literal('History'),\n prompt: zTaskPrompt,\n status: zStatus.optional(),\n outputs: zTaskOutput\n})\n\nconst zTaskItem = z.union([\n zRunningTaskItem,\n zPendingTaskItem,\n zHistoryTaskItem\n])\n\nconst zTaskType = z.union([\n z.literal('Running'),\n z.literal('Pending'),\n z.literal('History')\n])\n\nexport type TaskType = z.infer\nexport type TaskPrompt = z.infer\nexport type TaskStatus = z.infer\nexport type TaskOutput = z.infer\n\n// `/queue`\nexport type RunningTaskItem = z.infer\nexport type PendingTaskItem = z.infer\n// `/history`\nexport type HistoryTaskItem = z.infer\nexport type TaskItem = z.infer\n\nexport function validateTaskItem(taskItem: unknown) {\n const result = zTaskItem.safeParse(taskItem)\n if (!result.success) {\n const zodError = fromZodError(result.error)\n // TODO accept a callback to report error.\n console.warn(\n `Invalid TaskItem: ${JSON.stringify(taskItem)}\\n${zodError.message}`\n )\n }\n return result\n}\n\nfunction inputSpec(\n spec: [ZodType, ZodType],\n allowUpcast: boolean = true\n): ZodType {\n const [inputType, inputSpec] = spec\n // e.g. \"INT\" => [\"INT\", {}]\n const upcastTypes: ZodType[] = allowUpcast\n ? [inputType.transform((type) => [type, {}])]\n : []\n\n return z.union([\n z.tuple([inputType, inputSpec]),\n z.tuple([inputType]).transform(([type]) => [type, {}]),\n ...upcastTypes\n ])\n}\n\nconst zBaseInputSpecValue = z\n .object({\n default: z.any().optional(),\n defaultInput: z.boolean().optional(),\n forceInput: z.boolean().optional(),\n lazy: z.boolean().optional(),\n rawLink: z.boolean().optional(),\n tooltip: z.string().optional()\n })\n .passthrough()\n\nconst zIntInputSpec = inputSpec([\n z.literal('INT'),\n zBaseInputSpecValue.extend({\n min: z.number().optional(),\n max: z.number().optional(),\n step: z.number().optional(),\n // Note: Many node authors are using INT to pass list of INT.\n // TODO: Add list of ints type.\n default: z.union([z.number(), z.array(z.number())]).optional()\n })\n])\n\nconst zFloatInputSpec = inputSpec([\n z.literal('FLOAT'),\n zBaseInputSpecValue.extend({\n min: z.number().optional(),\n max: z.number().optional(),\n step: z.number().optional(),\n round: z.union([z.number(), z.literal(false)]).optional(),\n // Note: Many node authors are using FLOAT to pass list of FLOAT.\n // TODO: Add list of floats type.\n default: z.union([z.number(), z.array(z.number())]).optional()\n })\n])\n\nconst zBooleanInputSpec = inputSpec([\n z.literal('BOOLEAN'),\n zBaseInputSpecValue.extend({\n label_on: z.string().optional(),\n label_off: z.string().optional(),\n default: z.boolean().optional()\n })\n])\n\nconst zStringInputSpec = inputSpec([\n z.literal('STRING'),\n zBaseInputSpecValue.extend({\n default: z.string().optional(),\n multiline: z.boolean().optional(),\n dynamicPrompts: z.boolean().optional(),\n\n // Multiline-only fields\n defaultVal: z.string().optional(),\n placeholder: z.string().optional()\n })\n])\n\n// Dropdown Selection.\nconst zComboInputSpec = inputSpec(\n [\n z.array(z.any()),\n zBaseInputSpecValue.extend({\n control_after_generate: z.boolean().optional(),\n image_upload: z.boolean().optional()\n })\n ],\n /* allowUpcast=*/ false\n)\n\nconst excludedLiterals = new Set(['INT', 'FLOAT', 'BOOLEAN', 'STRING', 'COMBO'])\n\nconst zCustomInputSpec = inputSpec([\n z.string().refine((value) => !excludedLiterals.has(value)),\n zBaseInputSpecValue\n])\n\nconst zInputSpec = z.union([\n zIntInputSpec,\n zFloatInputSpec,\n zBooleanInputSpec,\n zStringInputSpec,\n zComboInputSpec,\n zCustomInputSpec\n])\n\nconst zComfyInputsSpec = z.object({\n required: z.record(zInputSpec).optional(),\n optional: z.record(zInputSpec).optional(),\n // Frontend repo is not using it, but some custom nodes are using the\n // hidden field to pass various values.\n hidden: z.record(z.any()).optional()\n})\n\nconst zComfyNodeDataType = z.string()\nconst zComfyComboOutput = z.array(z.any())\nconst zComfyOutputTypesSpec = z.array(\n z.union([zComfyNodeDataType, zComfyComboOutput])\n)\n\nconst zComfyNodeDef = z.object({\n input: zComfyInputsSpec,\n output: zComfyOutputTypesSpec,\n output_is_list: z.array(z.boolean()),\n output_name: z.array(z.string()),\n output_tooltips: z.array(z.string()).optional(),\n name: z.string(),\n display_name: z.string(),\n description: z.string(),\n category: z.string(),\n output_node: z.boolean(),\n python_module: z.string(),\n deprecated: z.boolean().optional(),\n experimental: z.boolean().optional()\n})\n\n// `/object_info`\nexport type ComfyInputsSpec = z.infer\nexport type ComfyOutputTypesSpec = z.infer\nexport type ComfyNodeDef = z.infer\n\nexport function validateComfyNodeDef(\n data: any,\n onError: (error: string) => void = console.warn\n): ComfyNodeDef | null {\n const result = zComfyNodeDef.safeParse(data)\n if (!result.success) {\n const zodError = fromZodError(result.error)\n onError(\n `Invalid ComfyNodeDef: ${JSON.stringify(data)}\\n${zodError.message}`\n )\n return null\n }\n return result.data\n}\n\nconst zEmbeddingsResponse = z.array(z.string())\nconst zExtensionsResponse = z.array(z.string())\nconst zPromptResponse = z.object({\n node_errors: z.array(z.string()).optional(),\n prompt_id: z.string().optional(),\n exec_info: z\n .object({\n queue_remaining: z.number().optional()\n })\n .optional()\n})\n\nconst zDeviceStats = z.object({\n name: z.string(),\n type: z.string(),\n index: z.number(),\n vram_total: z.number(),\n vram_free: z.number(),\n torch_vram_total: z.number(),\n torch_vram_free: z.number()\n})\n\nexport const zSystemStats = z.object({\n system: z.object({\n os: z.string(),\n python_version: z.string(),\n embedded_python: z.boolean(),\n comfyui_version: z.string(),\n pytorch_version: z.string(),\n argv: z.array(z.string())\n }),\n devices: z.array(zDeviceStats)\n})\nconst zUser = z.object({\n storage: z.enum(['server', 'browser']),\n migrated: z.boolean(),\n users: z.record(z.string(), z.unknown())\n})\nconst zUserData = z.array(z.array(z.string(), z.string()))\nconst zUserDataFullInfo = z.object({\n path: z.string(),\n size: z.number(),\n modified: z.number()\n})\nconst zBookmarkCustomization = z.object({\n icon: z.string().optional(),\n color: z.string().optional()\n})\nexport type BookmarkCustomization = z.infer\n\nconst zLinkReleaseTriggerAction = z.enum(\n Object.values(LinkReleaseTriggerAction) as [string, ...string[]]\n)\n\nconst zNodeBadgeMode = z.enum(\n Object.values(NodeBadgeMode) as [string, ...string[]]\n)\n\nconst zSettings = z.record(z.any()).and(\n z\n .object({\n 'Comfy.ColorPalette': z.string(),\n 'Comfy.CustomColorPalettes': colorPalettesSchema,\n 'Comfy.ConfirmClear': z.boolean(),\n 'Comfy.DevMode': z.boolean(),\n 'Comfy.Workflow.ShowMissingNodesWarning': z.boolean(),\n 'Comfy.Workflow.ShowMissingModelsWarning': z.boolean(),\n 'Comfy.DisableFloatRounding': z.boolean(),\n 'Comfy.DisableSliders': z.boolean(),\n 'Comfy.DOMClippingEnabled': z.boolean(),\n 'Comfy.EditAttention.Delta': z.number(),\n 'Comfy.EnableTooltips': z.boolean(),\n 'Comfy.EnableWorkflowViewRestore': z.boolean(),\n 'Comfy.FloatRoundingPrecision': z.number(),\n 'Comfy.Graph.CanvasInfo': z.boolean(),\n 'Comfy.Graph.ZoomSpeed': z.number(),\n 'Comfy.Group.DoubleClickTitleToEdit': z.boolean(),\n 'Comfy.GroupSelectedNodes.Padding': z.number(),\n 'Comfy.InvertMenuScrolling': z.boolean(),\n 'Comfy.Locale': z.string(),\n 'Comfy.Logging.Enabled': z.boolean(),\n 'Comfy.NodeLibrary.Bookmarks': z.array(z.string()),\n 'Comfy.NodeLibrary.Bookmarks.V2': z.array(z.string()),\n 'Comfy.NodeLibrary.BookmarksCustomization': z.record(\n z.string(),\n zBookmarkCustomization\n ),\n 'Comfy.NodeInputConversionSubmenus': z.boolean(),\n 'Comfy.NodeSearchBoxImpl.LinkReleaseTrigger': z.enum([\n 'always',\n 'hold shift',\n 'NOT hold shift'\n ]),\n 'Comfy.LinkRelease.Action': zLinkReleaseTriggerAction,\n 'Comfy.LinkRelease.ActionShift': zLinkReleaseTriggerAction,\n 'Comfy.NodeSearchBoxImpl.NodePreview': z.boolean(),\n 'Comfy.NodeSearchBoxImpl': z.enum(['default', 'simple']),\n 'Comfy.NodeSearchBoxImpl.ShowCategory': z.boolean(),\n 'Comfy.NodeSearchBoxImpl.ShowIdName': z.boolean(),\n 'Comfy.NodeSuggestions.number': z.number(),\n 'Comfy.Node.ShowDeprecated': z.boolean(),\n 'Comfy.Node.ShowExperimental': z.boolean(),\n 'Comfy.PreviewFormat': z.string(),\n 'Comfy.PromptFilename': z.boolean(),\n 'Comfy.Sidebar.Location': z.enum(['left', 'right']),\n 'Comfy.Sidebar.Size': z.number(),\n 'Comfy.SwitchUser': z.any(),\n 'Comfy.SnapToGrid.GridSize': z.number(),\n 'Comfy.TextareaWidget.FontSize': z.number(),\n 'Comfy.TextareaWidget.Spellcheck': z.boolean(),\n 'Comfy.TreeExplorer.ItemPadding': z.number(),\n 'Comfy.UseNewMenu': z.any(),\n 'Comfy.Validation.Workflows': z.boolean(),\n 'Comfy.Workflow.SortNodeIdOnSave': z.boolean(),\n 'Comfy.Queue.ImageFit': z.enum(['contain', 'cover']),\n 'Comfy.Workflow.ModelDownload.AllowedSources': z.array(z.string()),\n 'Comfy.Workflow.ModelDownload.AllowedSuffixes': z.array(z.string()),\n 'Comfy.Node.DoubleClickTitleToEdit': z.boolean(),\n 'Comfy.Window.UnloadConfirmation': z.boolean(),\n 'Comfy.NodeBadge.NodeSourceBadgeMode': zNodeBadgeMode,\n 'Comfy.NodeBadge.NodeIdBadgeMode': zNodeBadgeMode,\n 'Comfy.NodeBadge.NodeLifeCycleBadgeMode': zNodeBadgeMode\n })\n .optional()\n)\n\nexport type EmbeddingsResponse = z.infer\nexport type ExtensionsResponse = z.infer\nexport type PromptResponse = z.infer\nexport type Settings = z.infer\nexport type DeviceStats = z.infer\nexport type SystemStats = z.infer\nexport type User = z.infer\nexport type UserData = z.infer\nexport type UserDataFullInfo = z.infer\n","'use strict';\n\nexport default function bind(fn, thisArg) {\n return function wrap() {\n return fn.apply(thisArg, arguments);\n };\n}\n","'use strict';\n\nimport bind from './helpers/bind.js';\n\n// utils is a library of generic helper functions non-specific to axios\n\nconst {toString} = Object.prototype;\nconst {getPrototypeOf} = Object;\n\nconst kindOf = (cache => thing => {\n const str = toString.call(thing);\n return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());\n})(Object.create(null));\n\nconst kindOfTest = (type) => {\n type = type.toLowerCase();\n return (thing) => kindOf(thing) === type\n}\n\nconst typeOfTest = type => thing => typeof thing === type;\n\n/**\n * Determine if a value is an Array\n *\n * @param {Object} val The value to test\n *\n * @returns {boolean} True if value is an Array, otherwise false\n */\nconst {isArray} = Array;\n\n/**\n * Determine if a value is undefined\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if the value is undefined, otherwise false\n */\nconst isUndefined = typeOfTest('undefined');\n\n/**\n * Determine if a value is a Buffer\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Buffer, otherwise false\n */\nfunction isBuffer(val) {\n return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)\n && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val);\n}\n\n/**\n * Determine if a value is an ArrayBuffer\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is an ArrayBuffer, otherwise false\n */\nconst isArrayBuffer = kindOfTest('ArrayBuffer');\n\n\n/**\n * Determine if a value is a view on an ArrayBuffer\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false\n */\nfunction isArrayBufferView(val) {\n let result;\n if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {\n result = ArrayBuffer.isView(val);\n } else {\n result = (val) && (val.buffer) && (isArrayBuffer(val.buffer));\n }\n return result;\n}\n\n/**\n * Determine if a value is a String\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a String, otherwise false\n */\nconst isString = typeOfTest('string');\n\n/**\n * Determine if a value is a Function\n *\n * @param {*} val The value to test\n * @returns {boolean} True if value is a Function, otherwise false\n */\nconst isFunction = typeOfTest('function');\n\n/**\n * Determine if a value is a Number\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Number, otherwise false\n */\nconst isNumber = typeOfTest('number');\n\n/**\n * Determine if a value is an Object\n *\n * @param {*} thing The value to test\n *\n * @returns {boolean} True if value is an Object, otherwise false\n */\nconst isObject = (thing) => thing !== null && typeof thing === 'object';\n\n/**\n * Determine if a value is a Boolean\n *\n * @param {*} thing The value to test\n * @returns {boolean} True if value is a Boolean, otherwise false\n */\nconst isBoolean = thing => thing === true || thing === false;\n\n/**\n * Determine if a value is a plain Object\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a plain Object, otherwise false\n */\nconst isPlainObject = (val) => {\n if (kindOf(val) !== 'object') {\n return false;\n }\n\n const prototype = getPrototypeOf(val);\n return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val);\n}\n\n/**\n * Determine if a value is a Date\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Date, otherwise false\n */\nconst isDate = kindOfTest('Date');\n\n/**\n * Determine if a value is a File\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a File, otherwise false\n */\nconst isFile = kindOfTest('File');\n\n/**\n * Determine if a value is a Blob\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Blob, otherwise false\n */\nconst isBlob = kindOfTest('Blob');\n\n/**\n * Determine if a value is a FileList\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a File, otherwise false\n */\nconst isFileList = kindOfTest('FileList');\n\n/**\n * Determine if a value is a Stream\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Stream, otherwise false\n */\nconst isStream = (val) => isObject(val) && isFunction(val.pipe);\n\n/**\n * Determine if a value is a FormData\n *\n * @param {*} thing The value to test\n *\n * @returns {boolean} True if value is an FormData, otherwise false\n */\nconst isFormData = (thing) => {\n let kind;\n return thing && (\n (typeof FormData === 'function' && thing instanceof FormData) || (\n isFunction(thing.append) && (\n (kind = kindOf(thing)) === 'formdata' ||\n // detect form-data instance\n (kind === 'object' && isFunction(thing.toString) && thing.toString() === '[object FormData]')\n )\n )\n )\n}\n\n/**\n * Determine if a value is a URLSearchParams object\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a URLSearchParams object, otherwise false\n */\nconst isURLSearchParams = kindOfTest('URLSearchParams');\n\nconst [isReadableStream, isRequest, isResponse, isHeaders] = ['ReadableStream', 'Request', 'Response', 'Headers'].map(kindOfTest);\n\n/**\n * Trim excess whitespace off the beginning and end of a string\n *\n * @param {String} str The String to trim\n *\n * @returns {String} The String freed of excess whitespace\n */\nconst trim = (str) => str.trim ?\n str.trim() : str.replace(/^[\\s\\uFEFF\\xA0]+|[\\s\\uFEFF\\xA0]+$/g, '');\n\n/**\n * Iterate over an Array or an Object invoking a function for each item.\n *\n * If `obj` is an Array callback will be called passing\n * the value, index, and complete array for each item.\n *\n * If 'obj' is an Object callback will be called passing\n * the value, key, and complete object for each property.\n *\n * @param {Object|Array} obj The object to iterate\n * @param {Function} fn The callback to invoke for each item\n *\n * @param {Boolean} [allOwnKeys = false]\n * @returns {any}\n */\nfunction forEach(obj, fn, {allOwnKeys = false} = {}) {\n // Don't bother if no value provided\n if (obj === null || typeof obj === 'undefined') {\n return;\n }\n\n let i;\n let l;\n\n // Force an array if not already something iterable\n if (typeof obj !== 'object') {\n /*eslint no-param-reassign:0*/\n obj = [obj];\n }\n\n if (isArray(obj)) {\n // Iterate over array values\n for (i = 0, l = obj.length; i < l; i++) {\n fn.call(null, obj[i], i, obj);\n }\n } else {\n // Iterate over object keys\n const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);\n const len = keys.length;\n let key;\n\n for (i = 0; i < len; i++) {\n key = keys[i];\n fn.call(null, obj[key], key, obj);\n }\n }\n}\n\nfunction findKey(obj, key) {\n key = key.toLowerCase();\n const keys = Object.keys(obj);\n let i = keys.length;\n let _key;\n while (i-- > 0) {\n _key = keys[i];\n if (key === _key.toLowerCase()) {\n return _key;\n }\n }\n return null;\n}\n\nconst _global = (() => {\n /*eslint no-undef:0*/\n if (typeof globalThis !== \"undefined\") return globalThis;\n return typeof self !== \"undefined\" ? self : (typeof window !== 'undefined' ? window : global)\n})();\n\nconst isContextDefined = (context) => !isUndefined(context) && context !== _global;\n\n/**\n * Accepts varargs expecting each argument to be an object, then\n * immutably merges the properties of each object and returns result.\n *\n * When multiple objects contain the same key the later object in\n * the arguments list will take precedence.\n *\n * Example:\n *\n * ```js\n * var result = merge({foo: 123}, {foo: 456});\n * console.log(result.foo); // outputs 456\n * ```\n *\n * @param {Object} obj1 Object to merge\n *\n * @returns {Object} Result of all merge properties\n */\nfunction merge(/* obj1, obj2, obj3, ... */) {\n const {caseless} = isContextDefined(this) && this || {};\n const result = {};\n const assignValue = (val, key) => {\n const targetKey = caseless && findKey(result, key) || key;\n if (isPlainObject(result[targetKey]) && isPlainObject(val)) {\n result[targetKey] = merge(result[targetKey], val);\n } else if (isPlainObject(val)) {\n result[targetKey] = merge({}, val);\n } else if (isArray(val)) {\n result[targetKey] = val.slice();\n } else {\n result[targetKey] = val;\n }\n }\n\n for (let i = 0, l = arguments.length; i < l; i++) {\n arguments[i] && forEach(arguments[i], assignValue);\n }\n return result;\n}\n\n/**\n * Extends object a by mutably adding to it the properties of object b.\n *\n * @param {Object} a The object to be extended\n * @param {Object} b The object to copy properties from\n * @param {Object} thisArg The object to bind function to\n *\n * @param {Boolean} [allOwnKeys]\n * @returns {Object} The resulting value of object a\n */\nconst extend = (a, b, thisArg, {allOwnKeys}= {}) => {\n forEach(b, (val, key) => {\n if (thisArg && isFunction(val)) {\n a[key] = bind(val, thisArg);\n } else {\n a[key] = val;\n }\n }, {allOwnKeys});\n return a;\n}\n\n/**\n * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)\n *\n * @param {string} content with BOM\n *\n * @returns {string} content value without BOM\n */\nconst stripBOM = (content) => {\n if (content.charCodeAt(0) === 0xFEFF) {\n content = content.slice(1);\n }\n return content;\n}\n\n/**\n * Inherit the prototype methods from one constructor into another\n * @param {function} constructor\n * @param {function} superConstructor\n * @param {object} [props]\n * @param {object} [descriptors]\n *\n * @returns {void}\n */\nconst inherits = (constructor, superConstructor, props, descriptors) => {\n constructor.prototype = Object.create(superConstructor.prototype, descriptors);\n constructor.prototype.constructor = constructor;\n Object.defineProperty(constructor, 'super', {\n value: superConstructor.prototype\n });\n props && Object.assign(constructor.prototype, props);\n}\n\n/**\n * Resolve object with deep prototype chain to a flat object\n * @param {Object} sourceObj source object\n * @param {Object} [destObj]\n * @param {Function|Boolean} [filter]\n * @param {Function} [propFilter]\n *\n * @returns {Object}\n */\nconst toFlatObject = (sourceObj, destObj, filter, propFilter) => {\n let props;\n let i;\n let prop;\n const merged = {};\n\n destObj = destObj || {};\n // eslint-disable-next-line no-eq-null,eqeqeq\n if (sourceObj == null) return destObj;\n\n do {\n props = Object.getOwnPropertyNames(sourceObj);\n i = props.length;\n while (i-- > 0) {\n prop = props[i];\n if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {\n destObj[prop] = sourceObj[prop];\n merged[prop] = true;\n }\n }\n sourceObj = filter !== false && getPrototypeOf(sourceObj);\n } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);\n\n return destObj;\n}\n\n/**\n * Determines whether a string ends with the characters of a specified string\n *\n * @param {String} str\n * @param {String} searchString\n * @param {Number} [position= 0]\n *\n * @returns {boolean}\n */\nconst endsWith = (str, searchString, position) => {\n str = String(str);\n if (position === undefined || position > str.length) {\n position = str.length;\n }\n position -= searchString.length;\n const lastIndex = str.indexOf(searchString, position);\n return lastIndex !== -1 && lastIndex === position;\n}\n\n\n/**\n * Returns new array from array like object or null if failed\n *\n * @param {*} [thing]\n *\n * @returns {?Array}\n */\nconst toArray = (thing) => {\n if (!thing) return null;\n if (isArray(thing)) return thing;\n let i = thing.length;\n if (!isNumber(i)) return null;\n const arr = new Array(i);\n while (i-- > 0) {\n arr[i] = thing[i];\n }\n return arr;\n}\n\n/**\n * Checking if the Uint8Array exists and if it does, it returns a function that checks if the\n * thing passed in is an instance of Uint8Array\n *\n * @param {TypedArray}\n *\n * @returns {Array}\n */\n// eslint-disable-next-line func-names\nconst isTypedArray = (TypedArray => {\n // eslint-disable-next-line func-names\n return thing => {\n return TypedArray && thing instanceof TypedArray;\n };\n})(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array));\n\n/**\n * For each entry in the object, call the function with the key and value.\n *\n * @param {Object} obj - The object to iterate over.\n * @param {Function} fn - The function to call for each entry.\n *\n * @returns {void}\n */\nconst forEachEntry = (obj, fn) => {\n const generator = obj && obj[Symbol.iterator];\n\n const iterator = generator.call(obj);\n\n let result;\n\n while ((result = iterator.next()) && !result.done) {\n const pair = result.value;\n fn.call(obj, pair[0], pair[1]);\n }\n}\n\n/**\n * It takes a regular expression and a string, and returns an array of all the matches\n *\n * @param {string} regExp - The regular expression to match against.\n * @param {string} str - The string to search.\n *\n * @returns {Array}\n */\nconst matchAll = (regExp, str) => {\n let matches;\n const arr = [];\n\n while ((matches = regExp.exec(str)) !== null) {\n arr.push(matches);\n }\n\n return arr;\n}\n\n/* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */\nconst isHTMLForm = kindOfTest('HTMLFormElement');\n\nconst toCamelCase = str => {\n return str.toLowerCase().replace(/[-_\\s]([a-z\\d])(\\w*)/g,\n function replacer(m, p1, p2) {\n return p1.toUpperCase() + p2;\n }\n );\n};\n\n/* Creating a function that will check if an object has a property. */\nconst hasOwnProperty = (({hasOwnProperty}) => (obj, prop) => hasOwnProperty.call(obj, prop))(Object.prototype);\n\n/**\n * Determine if a value is a RegExp object\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a RegExp object, otherwise false\n */\nconst isRegExp = kindOfTest('RegExp');\n\nconst reduceDescriptors = (obj, reducer) => {\n const descriptors = Object.getOwnPropertyDescriptors(obj);\n const reducedDescriptors = {};\n\n forEach(descriptors, (descriptor, name) => {\n let ret;\n if ((ret = reducer(descriptor, name, obj)) !== false) {\n reducedDescriptors[name] = ret || descriptor;\n }\n });\n\n Object.defineProperties(obj, reducedDescriptors);\n}\n\n/**\n * Makes all methods read-only\n * @param {Object} obj\n */\n\nconst freezeMethods = (obj) => {\n reduceDescriptors(obj, (descriptor, name) => {\n // skip restricted props in strict mode\n if (isFunction(obj) && ['arguments', 'caller', 'callee'].indexOf(name) !== -1) {\n return false;\n }\n\n const value = obj[name];\n\n if (!isFunction(value)) return;\n\n descriptor.enumerable = false;\n\n if ('writable' in descriptor) {\n descriptor.writable = false;\n return;\n }\n\n if (!descriptor.set) {\n descriptor.set = () => {\n throw Error('Can not rewrite read-only method \\'' + name + '\\'');\n };\n }\n });\n}\n\nconst toObjectSet = (arrayOrString, delimiter) => {\n const obj = {};\n\n const define = (arr) => {\n arr.forEach(value => {\n obj[value] = true;\n });\n }\n\n isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));\n\n return obj;\n}\n\nconst noop = () => {}\n\nconst toFiniteNumber = (value, defaultValue) => {\n return value != null && Number.isFinite(value = +value) ? value : defaultValue;\n}\n\nconst ALPHA = 'abcdefghijklmnopqrstuvwxyz'\n\nconst DIGIT = '0123456789';\n\nconst ALPHABET = {\n DIGIT,\n ALPHA,\n ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT\n}\n\nconst generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => {\n let str = '';\n const {length} = alphabet;\n while (size--) {\n str += alphabet[Math.random() * length|0]\n }\n\n return str;\n}\n\n/**\n * If the thing is a FormData object, return true, otherwise return false.\n *\n * @param {unknown} thing - The thing to check.\n *\n * @returns {boolean}\n */\nfunction isSpecCompliantForm(thing) {\n return !!(thing && isFunction(thing.append) && thing[Symbol.toStringTag] === 'FormData' && thing[Symbol.iterator]);\n}\n\nconst toJSONObject = (obj) => {\n const stack = new Array(10);\n\n const visit = (source, i) => {\n\n if (isObject(source)) {\n if (stack.indexOf(source) >= 0) {\n return;\n }\n\n if(!('toJSON' in source)) {\n stack[i] = source;\n const target = isArray(source) ? [] : {};\n\n forEach(source, (value, key) => {\n const reducedValue = visit(value, i + 1);\n !isUndefined(reducedValue) && (target[key] = reducedValue);\n });\n\n stack[i] = undefined;\n\n return target;\n }\n }\n\n return source;\n }\n\n return visit(obj, 0);\n}\n\nconst isAsyncFn = kindOfTest('AsyncFunction');\n\nconst isThenable = (thing) =>\n thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch);\n\n// original code\n// https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34\n\nconst _setImmediate = ((setImmediateSupported, postMessageSupported) => {\n if (setImmediateSupported) {\n return setImmediate;\n }\n\n return postMessageSupported ? ((token, callbacks) => {\n _global.addEventListener(\"message\", ({source, data}) => {\n if (source === _global && data === token) {\n callbacks.length && callbacks.shift()();\n }\n }, false);\n\n return (cb) => {\n callbacks.push(cb);\n _global.postMessage(token, \"*\");\n }\n })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb);\n})(\n typeof setImmediate === 'function',\n isFunction(_global.postMessage)\n);\n\nconst asap = typeof queueMicrotask !== 'undefined' ?\n queueMicrotask.bind(_global) : ( typeof process !== 'undefined' && process.nextTick || _setImmediate);\n\n// *********************\n\nexport default {\n isArray,\n isArrayBuffer,\n isBuffer,\n isFormData,\n isArrayBufferView,\n isString,\n isNumber,\n isBoolean,\n isObject,\n isPlainObject,\n isReadableStream,\n isRequest,\n isResponse,\n isHeaders,\n isUndefined,\n isDate,\n isFile,\n isBlob,\n isRegExp,\n isFunction,\n isStream,\n isURLSearchParams,\n isTypedArray,\n isFileList,\n forEach,\n merge,\n extend,\n trim,\n stripBOM,\n inherits,\n toFlatObject,\n kindOf,\n kindOfTest,\n endsWith,\n toArray,\n forEachEntry,\n matchAll,\n isHTMLForm,\n hasOwnProperty,\n hasOwnProp: hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection\n reduceDescriptors,\n freezeMethods,\n toObjectSet,\n toCamelCase,\n noop,\n toFiniteNumber,\n findKey,\n global: _global,\n isContextDefined,\n ALPHABET,\n generateString,\n isSpecCompliantForm,\n toJSONObject,\n isAsyncFn,\n isThenable,\n setImmediate: _setImmediate,\n asap\n};\n","'use strict';\n\nimport utils from '../utils.js';\n\n/**\n * Create an Error with the specified message, config, error code, request and response.\n *\n * @param {string} message The error message.\n * @param {string} [code] The error code (for example, 'ECONNABORTED').\n * @param {Object} [config] The config.\n * @param {Object} [request] The request.\n * @param {Object} [response] The response.\n *\n * @returns {Error} The created error.\n */\nfunction AxiosError(message, code, config, request, response) {\n Error.call(this);\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n } else {\n this.stack = (new Error()).stack;\n }\n\n this.message = message;\n this.name = 'AxiosError';\n code && (this.code = code);\n config && (this.config = config);\n request && (this.request = request);\n response && (this.response = response);\n}\n\nutils.inherits(AxiosError, Error, {\n toJSON: function toJSON() {\n return {\n // Standard\n message: this.message,\n name: this.name,\n // Microsoft\n description: this.description,\n number: this.number,\n // Mozilla\n fileName: this.fileName,\n lineNumber: this.lineNumber,\n columnNumber: this.columnNumber,\n stack: this.stack,\n // Axios\n config: utils.toJSONObject(this.config),\n code: this.code,\n status: this.response && this.response.status ? this.response.status : null\n };\n }\n});\n\nconst prototype = AxiosError.prototype;\nconst descriptors = {};\n\n[\n 'ERR_BAD_OPTION_VALUE',\n 'ERR_BAD_OPTION',\n 'ECONNABORTED',\n 'ETIMEDOUT',\n 'ERR_NETWORK',\n 'ERR_FR_TOO_MANY_REDIRECTS',\n 'ERR_DEPRECATED',\n 'ERR_BAD_RESPONSE',\n 'ERR_BAD_REQUEST',\n 'ERR_CANCELED',\n 'ERR_NOT_SUPPORT',\n 'ERR_INVALID_URL'\n// eslint-disable-next-line func-names\n].forEach(code => {\n descriptors[code] = {value: code};\n});\n\nObject.defineProperties(AxiosError, descriptors);\nObject.defineProperty(prototype, 'isAxiosError', {value: true});\n\n// eslint-disable-next-line func-names\nAxiosError.from = (error, code, config, request, response, customProps) => {\n const axiosError = Object.create(prototype);\n\n utils.toFlatObject(error, axiosError, function filter(obj) {\n return obj !== Error.prototype;\n }, prop => {\n return prop !== 'isAxiosError';\n });\n\n AxiosError.call(axiosError, error.message, code, config, request, response);\n\n axiosError.cause = error;\n\n axiosError.name = error.name;\n\n customProps && Object.assign(axiosError, customProps);\n\n return axiosError;\n};\n\nexport default AxiosError;\n","// eslint-disable-next-line strict\nexport default null;\n","'use strict';\n\nimport utils from '../utils.js';\nimport AxiosError from '../core/AxiosError.js';\n// temporary hotfix to avoid circular references until AxiosURLSearchParams is refactored\nimport PlatformFormData from '../platform/node/classes/FormData.js';\n\n/**\n * Determines if the given thing is a array or js object.\n *\n * @param {string} thing - The object or array to be visited.\n *\n * @returns {boolean}\n */\nfunction isVisitable(thing) {\n return utils.isPlainObject(thing) || utils.isArray(thing);\n}\n\n/**\n * It removes the brackets from the end of a string\n *\n * @param {string} key - The key of the parameter.\n *\n * @returns {string} the key without the brackets.\n */\nfunction removeBrackets(key) {\n return utils.endsWith(key, '[]') ? key.slice(0, -2) : key;\n}\n\n/**\n * It takes a path, a key, and a boolean, and returns a string\n *\n * @param {string} path - The path to the current key.\n * @param {string} key - The key of the current object being iterated over.\n * @param {string} dots - If true, the key will be rendered with dots instead of brackets.\n *\n * @returns {string} The path to the current key.\n */\nfunction renderKey(path, key, dots) {\n if (!path) return key;\n return path.concat(key).map(function each(token, i) {\n // eslint-disable-next-line no-param-reassign\n token = removeBrackets(token);\n return !dots && i ? '[' + token + ']' : token;\n }).join(dots ? '.' : '');\n}\n\n/**\n * If the array is an array and none of its elements are visitable, then it's a flat array.\n *\n * @param {Array} arr - The array to check\n *\n * @returns {boolean}\n */\nfunction isFlatArray(arr) {\n return utils.isArray(arr) && !arr.some(isVisitable);\n}\n\nconst predicates = utils.toFlatObject(utils, {}, null, function filter(prop) {\n return /^is[A-Z]/.test(prop);\n});\n\n/**\n * Convert a data object to FormData\n *\n * @param {Object} obj\n * @param {?Object} [formData]\n * @param {?Object} [options]\n * @param {Function} [options.visitor]\n * @param {Boolean} [options.metaTokens = true]\n * @param {Boolean} [options.dots = false]\n * @param {?Boolean} [options.indexes = false]\n *\n * @returns {Object}\n **/\n\n/**\n * It converts an object into a FormData object\n *\n * @param {Object} obj - The object to convert to form data.\n * @param {string} formData - The FormData object to append to.\n * @param {Object} options\n *\n * @returns\n */\nfunction toFormData(obj, formData, options) {\n if (!utils.isObject(obj)) {\n throw new TypeError('target must be an object');\n }\n\n // eslint-disable-next-line no-param-reassign\n formData = formData || new (PlatformFormData || FormData)();\n\n // eslint-disable-next-line no-param-reassign\n options = utils.toFlatObject(options, {\n metaTokens: true,\n dots: false,\n indexes: false\n }, false, function defined(option, source) {\n // eslint-disable-next-line no-eq-null,eqeqeq\n return !utils.isUndefined(source[option]);\n });\n\n const metaTokens = options.metaTokens;\n // eslint-disable-next-line no-use-before-define\n const visitor = options.visitor || defaultVisitor;\n const dots = options.dots;\n const indexes = options.indexes;\n const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob;\n const useBlob = _Blob && utils.isSpecCompliantForm(formData);\n\n if (!utils.isFunction(visitor)) {\n throw new TypeError('visitor must be a function');\n }\n\n function convertValue(value) {\n if (value === null) return '';\n\n if (utils.isDate(value)) {\n return value.toISOString();\n }\n\n if (!useBlob && utils.isBlob(value)) {\n throw new AxiosError('Blob is not supported. Use a Buffer instead.');\n }\n\n if (utils.isArrayBuffer(value) || utils.isTypedArray(value)) {\n return useBlob && typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value);\n }\n\n return value;\n }\n\n /**\n * Default visitor.\n *\n * @param {*} value\n * @param {String|Number} key\n * @param {Array} path\n * @this {FormData}\n *\n * @returns {boolean} return true to visit the each prop of the value recursively\n */\n function defaultVisitor(value, key, path) {\n let arr = value;\n\n if (value && !path && typeof value === 'object') {\n if (utils.endsWith(key, '{}')) {\n // eslint-disable-next-line no-param-reassign\n key = metaTokens ? key : key.slice(0, -2);\n // eslint-disable-next-line no-param-reassign\n value = JSON.stringify(value);\n } else if (\n (utils.isArray(value) && isFlatArray(value)) ||\n ((utils.isFileList(value) || utils.endsWith(key, '[]')) && (arr = utils.toArray(value))\n )) {\n // eslint-disable-next-line no-param-reassign\n key = removeBrackets(key);\n\n arr.forEach(function each(el, index) {\n !(utils.isUndefined(el) || el === null) && formData.append(\n // eslint-disable-next-line no-nested-ternary\n indexes === true ? renderKey([key], index, dots) : (indexes === null ? key : key + '[]'),\n convertValue(el)\n );\n });\n return false;\n }\n }\n\n if (isVisitable(value)) {\n return true;\n }\n\n formData.append(renderKey(path, key, dots), convertValue(value));\n\n return false;\n }\n\n const stack = [];\n\n const exposedHelpers = Object.assign(predicates, {\n defaultVisitor,\n convertValue,\n isVisitable\n });\n\n function build(value, path) {\n if (utils.isUndefined(value)) return;\n\n if (stack.indexOf(value) !== -1) {\n throw Error('Circular reference detected in ' + path.join('.'));\n }\n\n stack.push(value);\n\n utils.forEach(value, function each(el, key) {\n const result = !(utils.isUndefined(el) || el === null) && visitor.call(\n formData, el, utils.isString(key) ? key.trim() : key, path, exposedHelpers\n );\n\n if (result === true) {\n build(el, path ? path.concat(key) : [key]);\n }\n });\n\n stack.pop();\n }\n\n if (!utils.isObject(obj)) {\n throw new TypeError('data must be an object');\n }\n\n build(obj);\n\n return formData;\n}\n\nexport default toFormData;\n","'use strict';\n\nimport toFormData from './toFormData.js';\n\n/**\n * It encodes a string by replacing all characters that are not in the unreserved set with\n * their percent-encoded equivalents\n *\n * @param {string} str - The string to encode.\n *\n * @returns {string} The encoded string.\n */\nfunction encode(str) {\n const charMap = {\n '!': '%21',\n \"'\": '%27',\n '(': '%28',\n ')': '%29',\n '~': '%7E',\n '%20': '+',\n '%00': '\\x00'\n };\n return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) {\n return charMap[match];\n });\n}\n\n/**\n * It takes a params object and converts it to a FormData object\n *\n * @param {Object} params - The parameters to be converted to a FormData object.\n * @param {Object} options - The options object passed to the Axios constructor.\n *\n * @returns {void}\n */\nfunction AxiosURLSearchParams(params, options) {\n this._pairs = [];\n\n params && toFormData(params, this, options);\n}\n\nconst prototype = AxiosURLSearchParams.prototype;\n\nprototype.append = function append(name, value) {\n this._pairs.push([name, value]);\n};\n\nprototype.toString = function toString(encoder) {\n const _encode = encoder ? function(value) {\n return encoder.call(this, value, encode);\n } : encode;\n\n return this._pairs.map(function each(pair) {\n return _encode(pair[0]) + '=' + _encode(pair[1]);\n }, '').join('&');\n};\n\nexport default AxiosURLSearchParams;\n","'use strict';\n\nimport utils from '../utils.js';\nimport AxiosURLSearchParams from '../helpers/AxiosURLSearchParams.js';\n\n/**\n * It replaces all instances of the characters `:`, `$`, `,`, `+`, `[`, and `]` with their\n * URI encoded counterparts\n *\n * @param {string} val The value to be encoded.\n *\n * @returns {string} The encoded value.\n */\nfunction encode(val) {\n return encodeURIComponent(val).\n replace(/%3A/gi, ':').\n replace(/%24/g, '$').\n replace(/%2C/gi, ',').\n replace(/%20/g, '+').\n replace(/%5B/gi, '[').\n replace(/%5D/gi, ']');\n}\n\n/**\n * Build a URL by appending params to the end\n *\n * @param {string} url The base of the url (e.g., http://www.google.com)\n * @param {object} [params] The params to be appended\n * @param {?object} options\n *\n * @returns {string} The formatted url\n */\nexport default function buildURL(url, params, options) {\n /*eslint no-param-reassign:0*/\n if (!params) {\n return url;\n }\n \n const _encode = options && options.encode || encode;\n\n const serializeFn = options && options.serialize;\n\n let serializedParams;\n\n if (serializeFn) {\n serializedParams = serializeFn(params, options);\n } else {\n serializedParams = utils.isURLSearchParams(params) ?\n params.toString() :\n new AxiosURLSearchParams(params, options).toString(_encode);\n }\n\n if (serializedParams) {\n const hashmarkIndex = url.indexOf(\"#\");\n\n if (hashmarkIndex !== -1) {\n url = url.slice(0, hashmarkIndex);\n }\n url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;\n }\n\n return url;\n}\n","'use strict';\n\nimport utils from './../utils.js';\n\nclass InterceptorManager {\n constructor() {\n this.handlers = [];\n }\n\n /**\n * Add a new interceptor to the stack\n *\n * @param {Function} fulfilled The function to handle `then` for a `Promise`\n * @param {Function} rejected The function to handle `reject` for a `Promise`\n *\n * @return {Number} An ID used to remove interceptor later\n */\n use(fulfilled, rejected, options) {\n this.handlers.push({\n fulfilled,\n rejected,\n synchronous: options ? options.synchronous : false,\n runWhen: options ? options.runWhen : null\n });\n return this.handlers.length - 1;\n }\n\n /**\n * Remove an interceptor from the stack\n *\n * @param {Number} id The ID that was returned by `use`\n *\n * @returns {Boolean} `true` if the interceptor was removed, `false` otherwise\n */\n eject(id) {\n if (this.handlers[id]) {\n this.handlers[id] = null;\n }\n }\n\n /**\n * Clear all interceptors from the stack\n *\n * @returns {void}\n */\n clear() {\n if (this.handlers) {\n this.handlers = [];\n }\n }\n\n /**\n * Iterate over all the registered interceptors\n *\n * This method is particularly useful for skipping over any\n * interceptors that may have become `null` calling `eject`.\n *\n * @param {Function} fn The function to call for each interceptor\n *\n * @returns {void}\n */\n forEach(fn) {\n utils.forEach(this.handlers, function forEachHandler(h) {\n if (h !== null) {\n fn(h);\n }\n });\n }\n}\n\nexport default InterceptorManager;\n","'use strict';\n\nexport default {\n silentJSONParsing: true,\n forcedJSONParsing: true,\n clarifyTimeoutError: false\n};\n","'use strict';\n\nimport AxiosURLSearchParams from '../../../helpers/AxiosURLSearchParams.js';\nexport default typeof URLSearchParams !== 'undefined' ? URLSearchParams : AxiosURLSearchParams;\n","'use strict';\n\nexport default typeof FormData !== 'undefined' ? FormData : null;\n","'use strict'\n\nexport default typeof Blob !== 'undefined' ? Blob : null\n","import URLSearchParams from './classes/URLSearchParams.js'\nimport FormData from './classes/FormData.js'\nimport Blob from './classes/Blob.js'\n\nexport default {\n isBrowser: true,\n classes: {\n URLSearchParams,\n FormData,\n Blob\n },\n protocols: ['http', 'https', 'file', 'blob', 'url', 'data']\n};\n","const hasBrowserEnv = typeof window !== 'undefined' && typeof document !== 'undefined';\n\n/**\n * Determine if we're running in a standard browser environment\n *\n * This allows axios to run in a web worker, and react-native.\n * Both environments support XMLHttpRequest, but not fully standard globals.\n *\n * web workers:\n * typeof window -> undefined\n * typeof document -> undefined\n *\n * react-native:\n * navigator.product -> 'ReactNative'\n * nativescript\n * navigator.product -> 'NativeScript' or 'NS'\n *\n * @returns {boolean}\n */\nconst hasStandardBrowserEnv = (\n (product) => {\n return hasBrowserEnv && ['ReactNative', 'NativeScript', 'NS'].indexOf(product) < 0\n })(typeof navigator !== 'undefined' && navigator.product);\n\n/**\n * Determine if we're running in a standard browser webWorker environment\n *\n * Although the `isStandardBrowserEnv` method indicates that\n * `allows axios to run in a web worker`, the WebWorker will still be\n * filtered out due to its judgment standard\n * `typeof window !== 'undefined' && typeof document !== 'undefined'`.\n * This leads to a problem when axios post `FormData` in webWorker\n */\nconst hasStandardBrowserWebWorkerEnv = (() => {\n return (\n typeof WorkerGlobalScope !== 'undefined' &&\n // eslint-disable-next-line no-undef\n self instanceof WorkerGlobalScope &&\n typeof self.importScripts === 'function'\n );\n})();\n\nconst origin = hasBrowserEnv && window.location.href || 'http://localhost';\n\nexport {\n hasBrowserEnv,\n hasStandardBrowserWebWorkerEnv,\n hasStandardBrowserEnv,\n origin\n}\n","import platform from './node/index.js';\nimport * as utils from './common/utils.js';\n\nexport default {\n ...utils,\n ...platform\n}\n","'use strict';\n\nimport utils from '../utils.js';\nimport toFormData from './toFormData.js';\nimport platform from '../platform/index.js';\n\nexport default function toURLEncodedForm(data, options) {\n return toFormData(data, new platform.classes.URLSearchParams(), Object.assign({\n visitor: function(value, key, path, helpers) {\n if (platform.isNode && utils.isBuffer(value)) {\n this.append(key, value.toString('base64'));\n return false;\n }\n\n return helpers.defaultVisitor.apply(this, arguments);\n }\n }, options));\n}\n","'use strict';\n\nimport utils from '../utils.js';\n\n/**\n * It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z']\n *\n * @param {string} name - The name of the property to get.\n *\n * @returns An array of strings.\n */\nfunction parsePropPath(name) {\n // foo[x][y][z]\n // foo.x.y.z\n // foo-x-y-z\n // foo x y z\n return utils.matchAll(/\\w+|\\[(\\w*)]/g, name).map(match => {\n return match[0] === '[]' ? '' : match[1] || match[0];\n });\n}\n\n/**\n * Convert an array to an object.\n *\n * @param {Array} arr - The array to convert to an object.\n *\n * @returns An object with the same keys and values as the array.\n */\nfunction arrayToObject(arr) {\n const obj = {};\n const keys = Object.keys(arr);\n let i;\n const len = keys.length;\n let key;\n for (i = 0; i < len; i++) {\n key = keys[i];\n obj[key] = arr[key];\n }\n return obj;\n}\n\n/**\n * It takes a FormData object and returns a JavaScript object\n *\n * @param {string} formData The FormData object to convert to JSON.\n *\n * @returns {Object | null} The converted object.\n */\nfunction formDataToJSON(formData) {\n function buildPath(path, value, target, index) {\n let name = path[index++];\n\n if (name === '__proto__') return true;\n\n const isNumericKey = Number.isFinite(+name);\n const isLast = index >= path.length;\n name = !name && utils.isArray(target) ? target.length : name;\n\n if (isLast) {\n if (utils.hasOwnProp(target, name)) {\n target[name] = [target[name], value];\n } else {\n target[name] = value;\n }\n\n return !isNumericKey;\n }\n\n if (!target[name] || !utils.isObject(target[name])) {\n target[name] = [];\n }\n\n const result = buildPath(path, value, target[name], index);\n\n if (result && utils.isArray(target[name])) {\n target[name] = arrayToObject(target[name]);\n }\n\n return !isNumericKey;\n }\n\n if (utils.isFormData(formData) && utils.isFunction(formData.entries)) {\n const obj = {};\n\n utils.forEachEntry(formData, (name, value) => {\n buildPath(parsePropPath(name), value, obj, 0);\n });\n\n return obj;\n }\n\n return null;\n}\n\nexport default formDataToJSON;\n","'use strict';\n\nimport utils from '../utils.js';\nimport AxiosError from '../core/AxiosError.js';\nimport transitionalDefaults from './transitional.js';\nimport toFormData from '../helpers/toFormData.js';\nimport toURLEncodedForm from '../helpers/toURLEncodedForm.js';\nimport platform from '../platform/index.js';\nimport formDataToJSON from '../helpers/formDataToJSON.js';\n\n/**\n * It takes a string, tries to parse it, and if it fails, it returns the stringified version\n * of the input\n *\n * @param {any} rawValue - The value to be stringified.\n * @param {Function} parser - A function that parses a string into a JavaScript object.\n * @param {Function} encoder - A function that takes a value and returns a string.\n *\n * @returns {string} A stringified version of the rawValue.\n */\nfunction stringifySafely(rawValue, parser, encoder) {\n if (utils.isString(rawValue)) {\n try {\n (parser || JSON.parse)(rawValue);\n return utils.trim(rawValue);\n } catch (e) {\n if (e.name !== 'SyntaxError') {\n throw e;\n }\n }\n }\n\n return (encoder || JSON.stringify)(rawValue);\n}\n\nconst defaults = {\n\n transitional: transitionalDefaults,\n\n adapter: ['xhr', 'http', 'fetch'],\n\n transformRequest: [function transformRequest(data, headers) {\n const contentType = headers.getContentType() || '';\n const hasJSONContentType = contentType.indexOf('application/json') > -1;\n const isObjectPayload = utils.isObject(data);\n\n if (isObjectPayload && utils.isHTMLForm(data)) {\n data = new FormData(data);\n }\n\n const isFormData = utils.isFormData(data);\n\n if (isFormData) {\n return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;\n }\n\n if (utils.isArrayBuffer(data) ||\n utils.isBuffer(data) ||\n utils.isStream(data) ||\n utils.isFile(data) ||\n utils.isBlob(data) ||\n utils.isReadableStream(data)\n ) {\n return data;\n }\n if (utils.isArrayBufferView(data)) {\n return data.buffer;\n }\n if (utils.isURLSearchParams(data)) {\n headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false);\n return data.toString();\n }\n\n let isFileList;\n\n if (isObjectPayload) {\n if (contentType.indexOf('application/x-www-form-urlencoded') > -1) {\n return toURLEncodedForm(data, this.formSerializer).toString();\n }\n\n if ((isFileList = utils.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) {\n const _FormData = this.env && this.env.FormData;\n\n return toFormData(\n isFileList ? {'files[]': data} : data,\n _FormData && new _FormData(),\n this.formSerializer\n );\n }\n }\n\n if (isObjectPayload || hasJSONContentType ) {\n headers.setContentType('application/json', false);\n return stringifySafely(data);\n }\n\n return data;\n }],\n\n transformResponse: [function transformResponse(data) {\n const transitional = this.transitional || defaults.transitional;\n const forcedJSONParsing = transitional && transitional.forcedJSONParsing;\n const JSONRequested = this.responseType === 'json';\n\n if (utils.isResponse(data) || utils.isReadableStream(data)) {\n return data;\n }\n\n if (data && utils.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) {\n const silentJSONParsing = transitional && transitional.silentJSONParsing;\n const strictJSONParsing = !silentJSONParsing && JSONRequested;\n\n try {\n return JSON.parse(data);\n } catch (e) {\n if (strictJSONParsing) {\n if (e.name === 'SyntaxError') {\n throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response);\n }\n throw e;\n }\n }\n }\n\n return data;\n }],\n\n /**\n * A timeout in milliseconds to abort a request. If set to 0 (default) a\n * timeout is not created.\n */\n timeout: 0,\n\n xsrfCookieName: 'XSRF-TOKEN',\n xsrfHeaderName: 'X-XSRF-TOKEN',\n\n maxContentLength: -1,\n maxBodyLength: -1,\n\n env: {\n FormData: platform.classes.FormData,\n Blob: platform.classes.Blob\n },\n\n validateStatus: function validateStatus(status) {\n return status >= 200 && status < 300;\n },\n\n headers: {\n common: {\n 'Accept': 'application/json, text/plain, */*',\n 'Content-Type': undefined\n }\n }\n};\n\nutils.forEach(['delete', 'get', 'head', 'post', 'put', 'patch'], (method) => {\n defaults.headers[method] = {};\n});\n\nexport default defaults;\n","'use strict';\n\nimport utils from './../utils.js';\n\n// RawAxiosHeaders whose duplicates are ignored by node\n// c.f. https://nodejs.org/api/http.html#http_message_headers\nconst ignoreDuplicateOf = utils.toObjectSet([\n 'age', 'authorization', 'content-length', 'content-type', 'etag',\n 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',\n 'last-modified', 'location', 'max-forwards', 'proxy-authorization',\n 'referer', 'retry-after', 'user-agent'\n]);\n\n/**\n * Parse headers into an object\n *\n * ```\n * Date: Wed, 27 Aug 2014 08:58:49 GMT\n * Content-Type: application/json\n * Connection: keep-alive\n * Transfer-Encoding: chunked\n * ```\n *\n * @param {String} rawHeaders Headers needing to be parsed\n *\n * @returns {Object} Headers parsed into an object\n */\nexport default rawHeaders => {\n const parsed = {};\n let key;\n let val;\n let i;\n\n rawHeaders && rawHeaders.split('\\n').forEach(function parser(line) {\n i = line.indexOf(':');\n key = line.substring(0, i).trim().toLowerCase();\n val = line.substring(i + 1).trim();\n\n if (!key || (parsed[key] && ignoreDuplicateOf[key])) {\n return;\n }\n\n if (key === 'set-cookie') {\n if (parsed[key]) {\n parsed[key].push(val);\n } else {\n parsed[key] = [val];\n }\n } else {\n parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;\n }\n });\n\n return parsed;\n};\n","'use strict';\n\nimport utils from '../utils.js';\nimport parseHeaders from '../helpers/parseHeaders.js';\n\nconst $internals = Symbol('internals');\n\nfunction normalizeHeader(header) {\n return header && String(header).trim().toLowerCase();\n}\n\nfunction normalizeValue(value) {\n if (value === false || value == null) {\n return value;\n }\n\n return utils.isArray(value) ? value.map(normalizeValue) : String(value);\n}\n\nfunction parseTokens(str) {\n const tokens = Object.create(null);\n const tokensRE = /([^\\s,;=]+)\\s*(?:=\\s*([^,;]+))?/g;\n let match;\n\n while ((match = tokensRE.exec(str))) {\n tokens[match[1]] = match[2];\n }\n\n return tokens;\n}\n\nconst isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim());\n\nfunction matchHeaderValue(context, value, header, filter, isHeaderNameFilter) {\n if (utils.isFunction(filter)) {\n return filter.call(this, value, header);\n }\n\n if (isHeaderNameFilter) {\n value = header;\n }\n\n if (!utils.isString(value)) return;\n\n if (utils.isString(filter)) {\n return value.indexOf(filter) !== -1;\n }\n\n if (utils.isRegExp(filter)) {\n return filter.test(value);\n }\n}\n\nfunction formatHeader(header) {\n return header.trim()\n .toLowerCase().replace(/([a-z\\d])(\\w*)/g, (w, char, str) => {\n return char.toUpperCase() + str;\n });\n}\n\nfunction buildAccessors(obj, header) {\n const accessorName = utils.toCamelCase(' ' + header);\n\n ['get', 'set', 'has'].forEach(methodName => {\n Object.defineProperty(obj, methodName + accessorName, {\n value: function(arg1, arg2, arg3) {\n return this[methodName].call(this, header, arg1, arg2, arg3);\n },\n configurable: true\n });\n });\n}\n\nclass AxiosHeaders {\n constructor(headers) {\n headers && this.set(headers);\n }\n\n set(header, valueOrRewrite, rewrite) {\n const self = this;\n\n function setHeader(_value, _header, _rewrite) {\n const lHeader = normalizeHeader(_header);\n\n if (!lHeader) {\n throw new Error('header name must be a non-empty string');\n }\n\n const key = utils.findKey(self, lHeader);\n\n if(!key || self[key] === undefined || _rewrite === true || (_rewrite === undefined && self[key] !== false)) {\n self[key || _header] = normalizeValue(_value);\n }\n }\n\n const setHeaders = (headers, _rewrite) =>\n utils.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite));\n\n if (utils.isPlainObject(header) || header instanceof this.constructor) {\n setHeaders(header, valueOrRewrite)\n } else if(utils.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {\n setHeaders(parseHeaders(header), valueOrRewrite);\n } else if (utils.isHeaders(header)) {\n for (const [key, value] of header.entries()) {\n setHeader(value, key, rewrite);\n }\n } else {\n header != null && setHeader(valueOrRewrite, header, rewrite);\n }\n\n return this;\n }\n\n get(header, parser) {\n header = normalizeHeader(header);\n\n if (header) {\n const key = utils.findKey(this, header);\n\n if (key) {\n const value = this[key];\n\n if (!parser) {\n return value;\n }\n\n if (parser === true) {\n return parseTokens(value);\n }\n\n if (utils.isFunction(parser)) {\n return parser.call(this, value, key);\n }\n\n if (utils.isRegExp(parser)) {\n return parser.exec(value);\n }\n\n throw new TypeError('parser must be boolean|regexp|function');\n }\n }\n }\n\n has(header, matcher) {\n header = normalizeHeader(header);\n\n if (header) {\n const key = utils.findKey(this, header);\n\n return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher)));\n }\n\n return false;\n }\n\n delete(header, matcher) {\n const self = this;\n let deleted = false;\n\n function deleteHeader(_header) {\n _header = normalizeHeader(_header);\n\n if (_header) {\n const key = utils.findKey(self, _header);\n\n if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) {\n delete self[key];\n\n deleted = true;\n }\n }\n }\n\n if (utils.isArray(header)) {\n header.forEach(deleteHeader);\n } else {\n deleteHeader(header);\n }\n\n return deleted;\n }\n\n clear(matcher) {\n const keys = Object.keys(this);\n let i = keys.length;\n let deleted = false;\n\n while (i--) {\n const key = keys[i];\n if(!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {\n delete this[key];\n deleted = true;\n }\n }\n\n return deleted;\n }\n\n normalize(format) {\n const self = this;\n const headers = {};\n\n utils.forEach(this, (value, header) => {\n const key = utils.findKey(headers, header);\n\n if (key) {\n self[key] = normalizeValue(value);\n delete self[header];\n return;\n }\n\n const normalized = format ? formatHeader(header) : String(header).trim();\n\n if (normalized !== header) {\n delete self[header];\n }\n\n self[normalized] = normalizeValue(value);\n\n headers[normalized] = true;\n });\n\n return this;\n }\n\n concat(...targets) {\n return this.constructor.concat(this, ...targets);\n }\n\n toJSON(asStrings) {\n const obj = Object.create(null);\n\n utils.forEach(this, (value, header) => {\n value != null && value !== false && (obj[header] = asStrings && utils.isArray(value) ? value.join(', ') : value);\n });\n\n return obj;\n }\n\n [Symbol.iterator]() {\n return Object.entries(this.toJSON())[Symbol.iterator]();\n }\n\n toString() {\n return Object.entries(this.toJSON()).map(([header, value]) => header + ': ' + value).join('\\n');\n }\n\n get [Symbol.toStringTag]() {\n return 'AxiosHeaders';\n }\n\n static from(thing) {\n return thing instanceof this ? thing : new this(thing);\n }\n\n static concat(first, ...targets) {\n const computed = new this(first);\n\n targets.forEach((target) => computed.set(target));\n\n return computed;\n }\n\n static accessor(header) {\n const internals = this[$internals] = (this[$internals] = {\n accessors: {}\n });\n\n const accessors = internals.accessors;\n const prototype = this.prototype;\n\n function defineAccessor(_header) {\n const lHeader = normalizeHeader(_header);\n\n if (!accessors[lHeader]) {\n buildAccessors(prototype, _header);\n accessors[lHeader] = true;\n }\n }\n\n utils.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);\n\n return this;\n }\n}\n\nAxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']);\n\n// reserved names hotfix\nutils.reduceDescriptors(AxiosHeaders.prototype, ({value}, key) => {\n let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set`\n return {\n get: () => value,\n set(headerValue) {\n this[mapped] = headerValue;\n }\n }\n});\n\nutils.freezeMethods(AxiosHeaders);\n\nexport default AxiosHeaders;\n","'use strict';\n\nimport utils from './../utils.js';\nimport defaults from '../defaults/index.js';\nimport AxiosHeaders from '../core/AxiosHeaders.js';\n\n/**\n * Transform the data for a request or a response\n *\n * @param {Array|Function} fns A single function or Array of functions\n * @param {?Object} response The response object\n *\n * @returns {*} The resulting transformed data\n */\nexport default function transformData(fns, response) {\n const config = this || defaults;\n const context = response || config;\n const headers = AxiosHeaders.from(context.headers);\n let data = context.data;\n\n utils.forEach(fns, function transform(fn) {\n data = fn.call(config, data, headers.normalize(), response ? response.status : undefined);\n });\n\n headers.normalize();\n\n return data;\n}\n","'use strict';\n\nexport default function isCancel(value) {\n return !!(value && value.__CANCEL__);\n}\n","'use strict';\n\nimport AxiosError from '../core/AxiosError.js';\nimport utils from '../utils.js';\n\n/**\n * A `CanceledError` is an object that is thrown when an operation is canceled.\n *\n * @param {string=} message The message.\n * @param {Object=} config The config.\n * @param {Object=} request The request.\n *\n * @returns {CanceledError} The created error.\n */\nfunction CanceledError(message, config, request) {\n // eslint-disable-next-line no-eq-null,eqeqeq\n AxiosError.call(this, message == null ? 'canceled' : message, AxiosError.ERR_CANCELED, config, request);\n this.name = 'CanceledError';\n}\n\nutils.inherits(CanceledError, AxiosError, {\n __CANCEL__: true\n});\n\nexport default CanceledError;\n","'use strict';\n\nimport AxiosError from './AxiosError.js';\n\n/**\n * Resolve or reject a Promise based on response status.\n *\n * @param {Function} resolve A function that resolves the promise.\n * @param {Function} reject A function that rejects the promise.\n * @param {object} response The response.\n *\n * @returns {object} The response.\n */\nexport default function settle(resolve, reject, response) {\n const validateStatus = response.config.validateStatus;\n if (!response.status || !validateStatus || validateStatus(response.status)) {\n resolve(response);\n } else {\n reject(new AxiosError(\n 'Request failed with status code ' + response.status,\n [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],\n response.config,\n response.request,\n response\n ));\n }\n}\n","'use strict';\n\nexport default function parseProtocol(url) {\n const match = /^([-+\\w]{1,25})(:?\\/\\/|:)/.exec(url);\n return match && match[1] || '';\n}\n","'use strict';\n\n/**\n * Calculate data maxRate\n * @param {Number} [samplesCount= 10]\n * @param {Number} [min= 1000]\n * @returns {Function}\n */\nfunction speedometer(samplesCount, min) {\n samplesCount = samplesCount || 10;\n const bytes = new Array(samplesCount);\n const timestamps = new Array(samplesCount);\n let head = 0;\n let tail = 0;\n let firstSampleTS;\n\n min = min !== undefined ? min : 1000;\n\n return function push(chunkLength) {\n const now = Date.now();\n\n const startedAt = timestamps[tail];\n\n if (!firstSampleTS) {\n firstSampleTS = now;\n }\n\n bytes[head] = chunkLength;\n timestamps[head] = now;\n\n let i = tail;\n let bytesCount = 0;\n\n while (i !== head) {\n bytesCount += bytes[i++];\n i = i % samplesCount;\n }\n\n head = (head + 1) % samplesCount;\n\n if (head === tail) {\n tail = (tail + 1) % samplesCount;\n }\n\n if (now - firstSampleTS < min) {\n return;\n }\n\n const passed = startedAt && now - startedAt;\n\n return passed ? Math.round(bytesCount * 1000 / passed) : undefined;\n };\n}\n\nexport default speedometer;\n","/**\n * Throttle decorator\n * @param {Function} fn\n * @param {Number} freq\n * @return {Function}\n */\nfunction throttle(fn, freq) {\n let timestamp = 0;\n let threshold = 1000 / freq;\n let lastArgs;\n let timer;\n\n const invoke = (args, now = Date.now()) => {\n timestamp = now;\n lastArgs = null;\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n fn.apply(null, args);\n }\n\n const throttled = (...args) => {\n const now = Date.now();\n const passed = now - timestamp;\n if ( passed >= threshold) {\n invoke(args, now);\n } else {\n lastArgs = args;\n if (!timer) {\n timer = setTimeout(() => {\n timer = null;\n invoke(lastArgs)\n }, threshold - passed);\n }\n }\n }\n\n const flush = () => lastArgs && invoke(lastArgs);\n\n return [throttled, flush];\n}\n\nexport default throttle;\n","import speedometer from \"./speedometer.js\";\nimport throttle from \"./throttle.js\";\nimport utils from \"../utils.js\";\n\nexport const progressEventReducer = (listener, isDownloadStream, freq = 3) => {\n let bytesNotified = 0;\n const _speedometer = speedometer(50, 250);\n\n return throttle(e => {\n const loaded = e.loaded;\n const total = e.lengthComputable ? e.total : undefined;\n const progressBytes = loaded - bytesNotified;\n const rate = _speedometer(progressBytes);\n const inRange = loaded <= total;\n\n bytesNotified = loaded;\n\n const data = {\n loaded,\n total,\n progress: total ? (loaded / total) : undefined,\n bytes: progressBytes,\n rate: rate ? rate : undefined,\n estimated: rate && total && inRange ? (total - loaded) / rate : undefined,\n event: e,\n lengthComputable: total != null,\n [isDownloadStream ? 'download' : 'upload']: true\n };\n\n listener(data);\n }, freq);\n}\n\nexport const progressEventDecorator = (total, throttled) => {\n const lengthComputable = total != null;\n\n return [(loaded) => throttled[0]({\n lengthComputable,\n total,\n loaded\n }), throttled[1]];\n}\n\nexport const asyncDecorator = (fn) => (...args) => utils.asap(() => fn(...args));\n","'use strict';\n\nimport utils from './../utils.js';\nimport platform from '../platform/index.js';\n\nexport default platform.hasStandardBrowserEnv ?\n\n// Standard browser envs have full support of the APIs needed to test\n// whether the request URL is of the same origin as current location.\n (function standardBrowserEnv() {\n const msie = /(msie|trident)/i.test(navigator.userAgent);\n const urlParsingNode = document.createElement('a');\n let originURL;\n\n /**\n * Parse a URL to discover its components\n *\n * @param {String} url The URL to be parsed\n * @returns {Object}\n */\n function resolveURL(url) {\n let href = url;\n\n if (msie) {\n // IE needs attribute set twice to normalize properties\n urlParsingNode.setAttribute('href', href);\n href = urlParsingNode.href;\n }\n\n urlParsingNode.setAttribute('href', href);\n\n // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils\n return {\n href: urlParsingNode.href,\n protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',\n host: urlParsingNode.host,\n search: urlParsingNode.search ? urlParsingNode.search.replace(/^\\?/, '') : '',\n hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',\n hostname: urlParsingNode.hostname,\n port: urlParsingNode.port,\n pathname: (urlParsingNode.pathname.charAt(0) === '/') ?\n urlParsingNode.pathname :\n '/' + urlParsingNode.pathname\n };\n }\n\n originURL = resolveURL(window.location.href);\n\n /**\n * Determine if a URL shares the same origin as the current location\n *\n * @param {String} requestURL The URL to test\n * @returns {boolean} True if URL shares the same origin, otherwise false\n */\n return function isURLSameOrigin(requestURL) {\n const parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;\n return (parsed.protocol === originURL.protocol &&\n parsed.host === originURL.host);\n };\n })() :\n\n // Non standard browser envs (web workers, react-native) lack needed support.\n (function nonStandardBrowserEnv() {\n return function isURLSameOrigin() {\n return true;\n };\n })();\n","import utils from './../utils.js';\nimport platform from '../platform/index.js';\n\nexport default platform.hasStandardBrowserEnv ?\n\n // Standard browser envs support document.cookie\n {\n write(name, value, expires, path, domain, secure) {\n const cookie = [name + '=' + encodeURIComponent(value)];\n\n utils.isNumber(expires) && cookie.push('expires=' + new Date(expires).toGMTString());\n\n utils.isString(path) && cookie.push('path=' + path);\n\n utils.isString(domain) && cookie.push('domain=' + domain);\n\n secure === true && cookie.push('secure');\n\n document.cookie = cookie.join('; ');\n },\n\n read(name) {\n const match = document.cookie.match(new RegExp('(^|;\\\\s*)(' + name + ')=([^;]*)'));\n return (match ? decodeURIComponent(match[3]) : null);\n },\n\n remove(name) {\n this.write(name, '', Date.now() - 86400000);\n }\n }\n\n :\n\n // Non-standard browser env (web workers, react-native) lack needed support.\n {\n write() {},\n read() {\n return null;\n },\n remove() {}\n };\n\n","'use strict';\n\n/**\n * Determines whether the specified URL is absolute\n *\n * @param {string} url The URL to test\n *\n * @returns {boolean} True if the specified URL is absolute, otherwise false\n */\nexport default function isAbsoluteURL(url) {\n // A URL is considered absolute if it begins with \"://\" or \"//\" (protocol-relative URL).\n // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed\n // by any combination of letters, digits, plus, period, or hyphen.\n return /^([a-z][a-z\\d+\\-.]*:)?\\/\\//i.test(url);\n}\n","'use strict';\n\n/**\n * Creates a new URL by combining the specified URLs\n *\n * @param {string} baseURL The base URL\n * @param {string} relativeURL The relative URL\n *\n * @returns {string} The combined URL\n */\nexport default function combineURLs(baseURL, relativeURL) {\n return relativeURL\n ? baseURL.replace(/\\/?\\/$/, '') + '/' + relativeURL.replace(/^\\/+/, '')\n : baseURL;\n}\n","'use strict';\n\nimport isAbsoluteURL from '../helpers/isAbsoluteURL.js';\nimport combineURLs from '../helpers/combineURLs.js';\n\n/**\n * Creates a new URL by combining the baseURL with the requestedURL,\n * only when the requestedURL is not already an absolute URL.\n * If the requestURL is absolute, this function returns the requestedURL untouched.\n *\n * @param {string} baseURL The base URL\n * @param {string} requestedURL Absolute or relative URL to combine\n *\n * @returns {string} The combined full path\n */\nexport default function buildFullPath(baseURL, requestedURL) {\n if (baseURL && !isAbsoluteURL(requestedURL)) {\n return combineURLs(baseURL, requestedURL);\n }\n return requestedURL;\n}\n","'use strict';\n\nimport utils from '../utils.js';\nimport AxiosHeaders from \"./AxiosHeaders.js\";\n\nconst headersToObject = (thing) => thing instanceof AxiosHeaders ? { ...thing } : thing;\n\n/**\n * Config-specific merge-function which creates a new config-object\n * by merging two configuration objects together.\n *\n * @param {Object} config1\n * @param {Object} config2\n *\n * @returns {Object} New object resulting from merging config2 to config1\n */\nexport default function mergeConfig(config1, config2) {\n // eslint-disable-next-line no-param-reassign\n config2 = config2 || {};\n const config = {};\n\n function getMergedValue(target, source, caseless) {\n if (utils.isPlainObject(target) && utils.isPlainObject(source)) {\n return utils.merge.call({caseless}, target, source);\n } else if (utils.isPlainObject(source)) {\n return utils.merge({}, source);\n } else if (utils.isArray(source)) {\n return source.slice();\n }\n return source;\n }\n\n // eslint-disable-next-line consistent-return\n function mergeDeepProperties(a, b, caseless) {\n if (!utils.isUndefined(b)) {\n return getMergedValue(a, b, caseless);\n } else if (!utils.isUndefined(a)) {\n return getMergedValue(undefined, a, caseless);\n }\n }\n\n // eslint-disable-next-line consistent-return\n function valueFromConfig2(a, b) {\n if (!utils.isUndefined(b)) {\n return getMergedValue(undefined, b);\n }\n }\n\n // eslint-disable-next-line consistent-return\n function defaultToConfig2(a, b) {\n if (!utils.isUndefined(b)) {\n return getMergedValue(undefined, b);\n } else if (!utils.isUndefined(a)) {\n return getMergedValue(undefined, a);\n }\n }\n\n // eslint-disable-next-line consistent-return\n function mergeDirectKeys(a, b, prop) {\n if (prop in config2) {\n return getMergedValue(a, b);\n } else if (prop in config1) {\n return getMergedValue(undefined, a);\n }\n }\n\n const mergeMap = {\n url: valueFromConfig2,\n method: valueFromConfig2,\n data: valueFromConfig2,\n baseURL: defaultToConfig2,\n transformRequest: defaultToConfig2,\n transformResponse: defaultToConfig2,\n paramsSerializer: defaultToConfig2,\n timeout: defaultToConfig2,\n timeoutMessage: defaultToConfig2,\n withCredentials: defaultToConfig2,\n withXSRFToken: defaultToConfig2,\n adapter: defaultToConfig2,\n responseType: defaultToConfig2,\n xsrfCookieName: defaultToConfig2,\n xsrfHeaderName: defaultToConfig2,\n onUploadProgress: defaultToConfig2,\n onDownloadProgress: defaultToConfig2,\n decompress: defaultToConfig2,\n maxContentLength: defaultToConfig2,\n maxBodyLength: defaultToConfig2,\n beforeRedirect: defaultToConfig2,\n transport: defaultToConfig2,\n httpAgent: defaultToConfig2,\n httpsAgent: defaultToConfig2,\n cancelToken: defaultToConfig2,\n socketPath: defaultToConfig2,\n responseEncoding: defaultToConfig2,\n validateStatus: mergeDirectKeys,\n headers: (a, b) => mergeDeepProperties(headersToObject(a), headersToObject(b), true)\n };\n\n utils.forEach(Object.keys(Object.assign({}, config1, config2)), function computeConfigValue(prop) {\n const merge = mergeMap[prop] || mergeDeepProperties;\n const configValue = merge(config1[prop], config2[prop], prop);\n (utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);\n });\n\n return config;\n}\n","import platform from \"../platform/index.js\";\nimport utils from \"../utils.js\";\nimport isURLSameOrigin from \"./isURLSameOrigin.js\";\nimport cookies from \"./cookies.js\";\nimport buildFullPath from \"../core/buildFullPath.js\";\nimport mergeConfig from \"../core/mergeConfig.js\";\nimport AxiosHeaders from \"../core/AxiosHeaders.js\";\nimport buildURL from \"./buildURL.js\";\n\nexport default (config) => {\n const newConfig = mergeConfig({}, config);\n\n let {data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth} = newConfig;\n\n newConfig.headers = headers = AxiosHeaders.from(headers);\n\n newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url), config.params, config.paramsSerializer);\n\n // HTTP basic authentication\n if (auth) {\n headers.set('Authorization', 'Basic ' +\n btoa((auth.username || '') + ':' + (auth.password ? unescape(encodeURIComponent(auth.password)) : ''))\n );\n }\n\n let contentType;\n\n if (utils.isFormData(data)) {\n if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) {\n headers.setContentType(undefined); // Let the browser set it\n } else if ((contentType = headers.getContentType()) !== false) {\n // fix semicolon duplication issue for ReactNative FormData implementation\n const [type, ...tokens] = contentType ? contentType.split(';').map(token => token.trim()).filter(Boolean) : [];\n headers.setContentType([type || 'multipart/form-data', ...tokens].join('; '));\n }\n }\n\n // Add xsrf header\n // This is only done if running in a standard browser environment.\n // Specifically not if we're in a web worker, or react-native.\n\n if (platform.hasStandardBrowserEnv) {\n withXSRFToken && utils.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig));\n\n if (withXSRFToken || (withXSRFToken !== false && isURLSameOrigin(newConfig.url))) {\n // Add xsrf header\n const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName);\n\n if (xsrfValue) {\n headers.set(xsrfHeaderName, xsrfValue);\n }\n }\n }\n\n return newConfig;\n}\n\n","import utils from './../utils.js';\nimport settle from './../core/settle.js';\nimport transitionalDefaults from '../defaults/transitional.js';\nimport AxiosError from '../core/AxiosError.js';\nimport CanceledError from '../cancel/CanceledError.js';\nimport parseProtocol from '../helpers/parseProtocol.js';\nimport platform from '../platform/index.js';\nimport AxiosHeaders from '../core/AxiosHeaders.js';\nimport {progressEventReducer} from '../helpers/progressEventReducer.js';\nimport resolveConfig from \"../helpers/resolveConfig.js\";\n\nconst isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined';\n\nexport default isXHRAdapterSupported && function (config) {\n return new Promise(function dispatchXhrRequest(resolve, reject) {\n const _config = resolveConfig(config);\n let requestData = _config.data;\n const requestHeaders = AxiosHeaders.from(_config.headers).normalize();\n let {responseType, onUploadProgress, onDownloadProgress} = _config;\n let onCanceled;\n let uploadThrottled, downloadThrottled;\n let flushUpload, flushDownload;\n\n function done() {\n flushUpload && flushUpload(); // flush events\n flushDownload && flushDownload(); // flush events\n\n _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled);\n\n _config.signal && _config.signal.removeEventListener('abort', onCanceled);\n }\n\n let request = new XMLHttpRequest();\n\n request.open(_config.method.toUpperCase(), _config.url, true);\n\n // Set the request timeout in MS\n request.timeout = _config.timeout;\n\n function onloadend() {\n if (!request) {\n return;\n }\n // Prepare the response\n const responseHeaders = AxiosHeaders.from(\n 'getAllResponseHeaders' in request && request.getAllResponseHeaders()\n );\n const responseData = !responseType || responseType === 'text' || responseType === 'json' ?\n request.responseText : request.response;\n const response = {\n data: responseData,\n status: request.status,\n statusText: request.statusText,\n headers: responseHeaders,\n config,\n request\n };\n\n settle(function _resolve(value) {\n resolve(value);\n done();\n }, function _reject(err) {\n reject(err);\n done();\n }, response);\n\n // Clean up request\n request = null;\n }\n\n if ('onloadend' in request) {\n // Use onloadend if available\n request.onloadend = onloadend;\n } else {\n // Listen for ready state to emulate onloadend\n request.onreadystatechange = function handleLoad() {\n if (!request || request.readyState !== 4) {\n return;\n }\n\n // The request errored out and we didn't get a response, this will be\n // handled by onerror instead\n // With one exception: request that using file: protocol, most browsers\n // will return status as 0 even though it's a successful request\n if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {\n return;\n }\n // readystate handler is calling before onerror or ontimeout handlers,\n // so we should call onloadend on the next 'tick'\n setTimeout(onloadend);\n };\n }\n\n // Handle browser request cancellation (as opposed to a manual cancellation)\n request.onabort = function handleAbort() {\n if (!request) {\n return;\n }\n\n reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request));\n\n // Clean up request\n request = null;\n };\n\n // Handle low level network errors\n request.onerror = function handleError() {\n // Real errors are hidden from us by the browser\n // onerror should only fire if it's a network error\n reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request));\n\n // Clean up request\n request = null;\n };\n\n // Handle timeout\n request.ontimeout = function handleTimeout() {\n let timeoutErrorMessage = _config.timeout ? 'timeout of ' + _config.timeout + 'ms exceeded' : 'timeout exceeded';\n const transitional = _config.transitional || transitionalDefaults;\n if (_config.timeoutErrorMessage) {\n timeoutErrorMessage = _config.timeoutErrorMessage;\n }\n reject(new AxiosError(\n timeoutErrorMessage,\n transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,\n config,\n request));\n\n // Clean up request\n request = null;\n };\n\n // Remove Content-Type if data is undefined\n requestData === undefined && requestHeaders.setContentType(null);\n\n // Add headers to the request\n if ('setRequestHeader' in request) {\n utils.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) {\n request.setRequestHeader(key, val);\n });\n }\n\n // Add withCredentials to request if needed\n if (!utils.isUndefined(_config.withCredentials)) {\n request.withCredentials = !!_config.withCredentials;\n }\n\n // Add responseType to request if needed\n if (responseType && responseType !== 'json') {\n request.responseType = _config.responseType;\n }\n\n // Handle progress if needed\n if (onDownloadProgress) {\n ([downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true));\n request.addEventListener('progress', downloadThrottled);\n }\n\n // Not all browsers support upload events\n if (onUploadProgress && request.upload) {\n ([uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress));\n\n request.upload.addEventListener('progress', uploadThrottled);\n\n request.upload.addEventListener('loadend', flushUpload);\n }\n\n if (_config.cancelToken || _config.signal) {\n // Handle cancellation\n // eslint-disable-next-line func-names\n onCanceled = cancel => {\n if (!request) {\n return;\n }\n reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel);\n request.abort();\n request = null;\n };\n\n _config.cancelToken && _config.cancelToken.subscribe(onCanceled);\n if (_config.signal) {\n _config.signal.aborted ? onCanceled() : _config.signal.addEventListener('abort', onCanceled);\n }\n }\n\n const protocol = parseProtocol(_config.url);\n\n if (protocol && platform.protocols.indexOf(protocol) === -1) {\n reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config));\n return;\n }\n\n\n // Send the request\n request.send(requestData || null);\n });\n}\n","import CanceledError from \"../cancel/CanceledError.js\";\nimport AxiosError from \"../core/AxiosError.js\";\n\nconst composeSignals = (signals, timeout) => {\n let controller = new AbortController();\n\n let aborted;\n\n const onabort = function (cancel) {\n if (!aborted) {\n aborted = true;\n unsubscribe();\n const err = cancel instanceof Error ? cancel : this.reason;\n controller.abort(err instanceof AxiosError ? err : new CanceledError(err instanceof Error ? err.message : err));\n }\n }\n\n let timer = timeout && setTimeout(() => {\n onabort(new AxiosError(`timeout ${timeout} of ms exceeded`, AxiosError.ETIMEDOUT))\n }, timeout)\n\n const unsubscribe = () => {\n if (signals) {\n timer && clearTimeout(timer);\n timer = null;\n signals.forEach(signal => {\n signal &&\n (signal.removeEventListener ? signal.removeEventListener('abort', onabort) : signal.unsubscribe(onabort));\n });\n signals = null;\n }\n }\n\n signals.forEach((signal) => signal && signal.addEventListener && signal.addEventListener('abort', onabort));\n\n const {signal} = controller;\n\n signal.unsubscribe = unsubscribe;\n\n return [signal, () => {\n timer && clearTimeout(timer);\n timer = null;\n }];\n}\n\nexport default composeSignals;\n","\nexport const streamChunk = function* (chunk, chunkSize) {\n let len = chunk.byteLength;\n\n if (!chunkSize || len < chunkSize) {\n yield chunk;\n return;\n }\n\n let pos = 0;\n let end;\n\n while (pos < len) {\n end = pos + chunkSize;\n yield chunk.slice(pos, end);\n pos = end;\n }\n}\n\nexport const readBytes = async function* (iterable, chunkSize, encode) {\n for await (const chunk of iterable) {\n yield* streamChunk(ArrayBuffer.isView(chunk) ? chunk : (await encode(String(chunk))), chunkSize);\n }\n}\n\nexport const trackStream = (stream, chunkSize, onProgress, onFinish, encode) => {\n const iterator = readBytes(stream, chunkSize, encode);\n\n let bytes = 0;\n let done;\n let _onFinish = (e) => {\n if (!done) {\n done = true;\n onFinish && onFinish(e);\n }\n }\n\n return new ReadableStream({\n async pull(controller) {\n try {\n const {done, value} = await iterator.next();\n\n if (done) {\n _onFinish();\n controller.close();\n return;\n }\n\n let len = value.byteLength;\n if (onProgress) {\n let loadedBytes = bytes += len;\n onProgress(loadedBytes);\n }\n controller.enqueue(new Uint8Array(value));\n } catch (err) {\n _onFinish(err);\n throw err;\n }\n },\n cancel(reason) {\n _onFinish(reason);\n return iterator.return();\n }\n }, {\n highWaterMark: 2\n })\n}\n","import platform from \"../platform/index.js\";\nimport utils from \"../utils.js\";\nimport AxiosError from \"../core/AxiosError.js\";\nimport composeSignals from \"../helpers/composeSignals.js\";\nimport {trackStream} from \"../helpers/trackStream.js\";\nimport AxiosHeaders from \"../core/AxiosHeaders.js\";\nimport {progressEventReducer, progressEventDecorator, asyncDecorator} from \"../helpers/progressEventReducer.js\";\nimport resolveConfig from \"../helpers/resolveConfig.js\";\nimport settle from \"../core/settle.js\";\n\nconst isFetchSupported = typeof fetch === 'function' && typeof Request === 'function' && typeof Response === 'function';\nconst isReadableStreamSupported = isFetchSupported && typeof ReadableStream === 'function';\n\n// used only inside the fetch adapter\nconst encodeText = isFetchSupported && (typeof TextEncoder === 'function' ?\n ((encoder) => (str) => encoder.encode(str))(new TextEncoder()) :\n async (str) => new Uint8Array(await new Response(str).arrayBuffer())\n);\n\nconst test = (fn, ...args) => {\n try {\n return !!fn(...args);\n } catch (e) {\n return false\n }\n}\n\nconst supportsRequestStream = isReadableStreamSupported && test(() => {\n let duplexAccessed = false;\n\n const hasContentType = new Request(platform.origin, {\n body: new ReadableStream(),\n method: 'POST',\n get duplex() {\n duplexAccessed = true;\n return 'half';\n },\n }).headers.has('Content-Type');\n\n return duplexAccessed && !hasContentType;\n});\n\nconst DEFAULT_CHUNK_SIZE = 64 * 1024;\n\nconst supportsResponseStream = isReadableStreamSupported &&\n test(() => utils.isReadableStream(new Response('').body));\n\n\nconst resolvers = {\n stream: supportsResponseStream && ((res) => res.body)\n};\n\nisFetchSupported && (((res) => {\n ['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach(type => {\n !resolvers[type] && (resolvers[type] = utils.isFunction(res[type]) ? (res) => res[type]() :\n (_, config) => {\n throw new AxiosError(`Response type '${type}' is not supported`, AxiosError.ERR_NOT_SUPPORT, config);\n })\n });\n})(new Response));\n\nconst getBodyLength = async (body) => {\n if (body == null) {\n return 0;\n }\n\n if(utils.isBlob(body)) {\n return body.size;\n }\n\n if(utils.isSpecCompliantForm(body)) {\n return (await new Request(body).arrayBuffer()).byteLength;\n }\n\n if(utils.isArrayBufferView(body) || utils.isArrayBuffer(body)) {\n return body.byteLength;\n }\n\n if(utils.isURLSearchParams(body)) {\n body = body + '';\n }\n\n if(utils.isString(body)) {\n return (await encodeText(body)).byteLength;\n }\n}\n\nconst resolveBodyLength = async (headers, body) => {\n const length = utils.toFiniteNumber(headers.getContentLength());\n\n return length == null ? getBodyLength(body) : length;\n}\n\nexport default isFetchSupported && (async (config) => {\n let {\n url,\n method,\n data,\n signal,\n cancelToken,\n timeout,\n onDownloadProgress,\n onUploadProgress,\n responseType,\n headers,\n withCredentials = 'same-origin',\n fetchOptions\n } = resolveConfig(config);\n\n responseType = responseType ? (responseType + '').toLowerCase() : 'text';\n\n let [composedSignal, stopTimeout] = (signal || cancelToken || timeout) ?\n composeSignals([signal, cancelToken], timeout) : [];\n\n let finished, request;\n\n const onFinish = () => {\n !finished && setTimeout(() => {\n composedSignal && composedSignal.unsubscribe();\n });\n\n finished = true;\n }\n\n let requestContentLength;\n\n try {\n if (\n onUploadProgress && supportsRequestStream && method !== 'get' && method !== 'head' &&\n (requestContentLength = await resolveBodyLength(headers, data)) !== 0\n ) {\n let _request = new Request(url, {\n method: 'POST',\n body: data,\n duplex: \"half\"\n });\n\n let contentTypeHeader;\n\n if (utils.isFormData(data) && (contentTypeHeader = _request.headers.get('content-type'))) {\n headers.setContentType(contentTypeHeader)\n }\n\n if (_request.body) {\n const [onProgress, flush] = progressEventDecorator(\n requestContentLength,\n progressEventReducer(asyncDecorator(onUploadProgress))\n );\n\n data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush, encodeText);\n }\n }\n\n if (!utils.isString(withCredentials)) {\n withCredentials = withCredentials ? 'include' : 'omit';\n }\n\n request = new Request(url, {\n ...fetchOptions,\n signal: composedSignal,\n method: method.toUpperCase(),\n headers: headers.normalize().toJSON(),\n body: data,\n duplex: \"half\",\n credentials: withCredentials\n });\n\n let response = await fetch(request);\n\n const isStreamResponse = supportsResponseStream && (responseType === 'stream' || responseType === 'response');\n\n if (supportsResponseStream && (onDownloadProgress || isStreamResponse)) {\n const options = {};\n\n ['status', 'statusText', 'headers'].forEach(prop => {\n options[prop] = response[prop];\n });\n\n const responseContentLength = utils.toFiniteNumber(response.headers.get('content-length'));\n\n const [onProgress, flush] = onDownloadProgress && progressEventDecorator(\n responseContentLength,\n progressEventReducer(asyncDecorator(onDownloadProgress), true)\n ) || [];\n\n response = new Response(\n trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => {\n flush && flush();\n isStreamResponse && onFinish();\n }, encodeText),\n options\n );\n }\n\n responseType = responseType || 'text';\n\n let responseData = await resolvers[utils.findKey(resolvers, responseType) || 'text'](response, config);\n\n !isStreamResponse && onFinish();\n\n stopTimeout && stopTimeout();\n\n return await new Promise((resolve, reject) => {\n settle(resolve, reject, {\n data: responseData,\n headers: AxiosHeaders.from(response.headers),\n status: response.status,\n statusText: response.statusText,\n config,\n request\n })\n })\n } catch (err) {\n onFinish();\n\n if (err && err.name === 'TypeError' && /fetch/i.test(err.message)) {\n throw Object.assign(\n new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request),\n {\n cause: err.cause || err\n }\n )\n }\n\n throw AxiosError.from(err, err && err.code, config, request);\n }\n});\n\n\n","import utils from '../utils.js';\nimport httpAdapter from './http.js';\nimport xhrAdapter from './xhr.js';\nimport fetchAdapter from './fetch.js';\nimport AxiosError from \"../core/AxiosError.js\";\n\nconst knownAdapters = {\n http: httpAdapter,\n xhr: xhrAdapter,\n fetch: fetchAdapter\n}\n\nutils.forEach(knownAdapters, (fn, value) => {\n if (fn) {\n try {\n Object.defineProperty(fn, 'name', {value});\n } catch (e) {\n // eslint-disable-next-line no-empty\n }\n Object.defineProperty(fn, 'adapterName', {value});\n }\n});\n\nconst renderReason = (reason) => `- ${reason}`;\n\nconst isResolvedHandle = (adapter) => utils.isFunction(adapter) || adapter === null || adapter === false;\n\nexport default {\n getAdapter: (adapters) => {\n adapters = utils.isArray(adapters) ? adapters : [adapters];\n\n const {length} = adapters;\n let nameOrAdapter;\n let adapter;\n\n const rejectedReasons = {};\n\n for (let i = 0; i < length; i++) {\n nameOrAdapter = adapters[i];\n let id;\n\n adapter = nameOrAdapter;\n\n if (!isResolvedHandle(nameOrAdapter)) {\n adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()];\n\n if (adapter === undefined) {\n throw new AxiosError(`Unknown adapter '${id}'`);\n }\n }\n\n if (adapter) {\n break;\n }\n\n rejectedReasons[id || '#' + i] = adapter;\n }\n\n if (!adapter) {\n\n const reasons = Object.entries(rejectedReasons)\n .map(([id, state]) => `adapter ${id} ` +\n (state === false ? 'is not supported by the environment' : 'is not available in the build')\n );\n\n let s = length ?\n (reasons.length > 1 ? 'since :\\n' + reasons.map(renderReason).join('\\n') : ' ' + renderReason(reasons[0])) :\n 'as no adapter specified';\n\n throw new AxiosError(\n `There is no suitable adapter to dispatch the request ` + s,\n 'ERR_NOT_SUPPORT'\n );\n }\n\n return adapter;\n },\n adapters: knownAdapters\n}\n","'use strict';\n\nimport transformData from './transformData.js';\nimport isCancel from '../cancel/isCancel.js';\nimport defaults from '../defaults/index.js';\nimport CanceledError from '../cancel/CanceledError.js';\nimport AxiosHeaders from '../core/AxiosHeaders.js';\nimport adapters from \"../adapters/adapters.js\";\n\n/**\n * Throws a `CanceledError` if cancellation has been requested.\n *\n * @param {Object} config The config that is to be used for the request\n *\n * @returns {void}\n */\nfunction throwIfCancellationRequested(config) {\n if (config.cancelToken) {\n config.cancelToken.throwIfRequested();\n }\n\n if (config.signal && config.signal.aborted) {\n throw new CanceledError(null, config);\n }\n}\n\n/**\n * Dispatch a request to the server using the configured adapter.\n *\n * @param {object} config The config that is to be used for the request\n *\n * @returns {Promise} The Promise to be fulfilled\n */\nexport default function dispatchRequest(config) {\n throwIfCancellationRequested(config);\n\n config.headers = AxiosHeaders.from(config.headers);\n\n // Transform request data\n config.data = transformData.call(\n config,\n config.transformRequest\n );\n\n if (['post', 'put', 'patch'].indexOf(config.method) !== -1) {\n config.headers.setContentType('application/x-www-form-urlencoded', false);\n }\n\n const adapter = adapters.getAdapter(config.adapter || defaults.adapter);\n\n return adapter(config).then(function onAdapterResolution(response) {\n throwIfCancellationRequested(config);\n\n // Transform response data\n response.data = transformData.call(\n config,\n config.transformResponse,\n response\n );\n\n response.headers = AxiosHeaders.from(response.headers);\n\n return response;\n }, function onAdapterRejection(reason) {\n if (!isCancel(reason)) {\n throwIfCancellationRequested(config);\n\n // Transform response data\n if (reason && reason.response) {\n reason.response.data = transformData.call(\n config,\n config.transformResponse,\n reason.response\n );\n reason.response.headers = AxiosHeaders.from(reason.response.headers);\n }\n }\n\n return Promise.reject(reason);\n });\n}\n","export const VERSION = \"1.7.4\";","'use strict';\n\nimport {VERSION} from '../env/data.js';\nimport AxiosError from '../core/AxiosError.js';\n\nconst validators = {};\n\n// eslint-disable-next-line func-names\n['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach((type, i) => {\n validators[type] = function validator(thing) {\n return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;\n };\n});\n\nconst deprecatedWarnings = {};\n\n/**\n * Transitional option validator\n *\n * @param {function|boolean?} validator - set to false if the transitional option has been removed\n * @param {string?} version - deprecated version / removed since version\n * @param {string?} message - some message with additional info\n *\n * @returns {function}\n */\nvalidators.transitional = function transitional(validator, version, message) {\n function formatMessage(opt, desc) {\n return '[Axios v' + VERSION + '] Transitional option \\'' + opt + '\\'' + desc + (message ? '. ' + message : '');\n }\n\n // eslint-disable-next-line func-names\n return (value, opt, opts) => {\n if (validator === false) {\n throw new AxiosError(\n formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')),\n AxiosError.ERR_DEPRECATED\n );\n }\n\n if (version && !deprecatedWarnings[opt]) {\n deprecatedWarnings[opt] = true;\n // eslint-disable-next-line no-console\n console.warn(\n formatMessage(\n opt,\n ' has been deprecated since v' + version + ' and will be removed in the near future'\n )\n );\n }\n\n return validator ? validator(value, opt, opts) : true;\n };\n};\n\n/**\n * Assert object's properties type\n *\n * @param {object} options\n * @param {object} schema\n * @param {boolean?} allowUnknown\n *\n * @returns {object}\n */\n\nfunction assertOptions(options, schema, allowUnknown) {\n if (typeof options !== 'object') {\n throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE);\n }\n const keys = Object.keys(options);\n let i = keys.length;\n while (i-- > 0) {\n const opt = keys[i];\n const validator = schema[opt];\n if (validator) {\n const value = options[opt];\n const result = value === undefined || validator(value, opt, options);\n if (result !== true) {\n throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE);\n }\n continue;\n }\n if (allowUnknown !== true) {\n throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION);\n }\n }\n}\n\nexport default {\n assertOptions,\n validators\n};\n","'use strict';\n\nimport utils from './../utils.js';\nimport buildURL from '../helpers/buildURL.js';\nimport InterceptorManager from './InterceptorManager.js';\nimport dispatchRequest from './dispatchRequest.js';\nimport mergeConfig from './mergeConfig.js';\nimport buildFullPath from './buildFullPath.js';\nimport validator from '../helpers/validator.js';\nimport AxiosHeaders from './AxiosHeaders.js';\n\nconst validators = validator.validators;\n\n/**\n * Create a new instance of Axios\n *\n * @param {Object} instanceConfig The default config for the instance\n *\n * @return {Axios} A new instance of Axios\n */\nclass Axios {\n constructor(instanceConfig) {\n this.defaults = instanceConfig;\n this.interceptors = {\n request: new InterceptorManager(),\n response: new InterceptorManager()\n };\n }\n\n /**\n * Dispatch a request\n *\n * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)\n * @param {?Object} config\n *\n * @returns {Promise} The Promise to be fulfilled\n */\n async request(configOrUrl, config) {\n try {\n return await this._request(configOrUrl, config);\n } catch (err) {\n if (err instanceof Error) {\n let dummy;\n\n Error.captureStackTrace ? Error.captureStackTrace(dummy = {}) : (dummy = new Error());\n\n // slice off the Error: ... line\n const stack = dummy.stack ? dummy.stack.replace(/^.+\\n/, '') : '';\n try {\n if (!err.stack) {\n err.stack = stack;\n // match without the 2 top stack lines\n } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\\n.+\\n/, ''))) {\n err.stack += '\\n' + stack\n }\n } catch (e) {\n // ignore the case where \"stack\" is an un-writable property\n }\n }\n\n throw err;\n }\n }\n\n _request(configOrUrl, config) {\n /*eslint no-param-reassign:0*/\n // Allow for axios('example/url'[, config]) a la fetch API\n if (typeof configOrUrl === 'string') {\n config = config || {};\n config.url = configOrUrl;\n } else {\n config = configOrUrl || {};\n }\n\n config = mergeConfig(this.defaults, config);\n\n const {transitional, paramsSerializer, headers} = config;\n\n if (transitional !== undefined) {\n validator.assertOptions(transitional, {\n silentJSONParsing: validators.transitional(validators.boolean),\n forcedJSONParsing: validators.transitional(validators.boolean),\n clarifyTimeoutError: validators.transitional(validators.boolean)\n }, false);\n }\n\n if (paramsSerializer != null) {\n if (utils.isFunction(paramsSerializer)) {\n config.paramsSerializer = {\n serialize: paramsSerializer\n }\n } else {\n validator.assertOptions(paramsSerializer, {\n encode: validators.function,\n serialize: validators.function\n }, true);\n }\n }\n\n // Set config.method\n config.method = (config.method || this.defaults.method || 'get').toLowerCase();\n\n // Flatten headers\n let contextHeaders = headers && utils.merge(\n headers.common,\n headers[config.method]\n );\n\n headers && utils.forEach(\n ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],\n (method) => {\n delete headers[method];\n }\n );\n\n config.headers = AxiosHeaders.concat(contextHeaders, headers);\n\n // filter out skipped interceptors\n const requestInterceptorChain = [];\n let synchronousRequestInterceptors = true;\n this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {\n if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {\n return;\n }\n\n synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;\n\n requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);\n });\n\n const responseInterceptorChain = [];\n this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {\n responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);\n });\n\n let promise;\n let i = 0;\n let len;\n\n if (!synchronousRequestInterceptors) {\n const chain = [dispatchRequest.bind(this), undefined];\n chain.unshift.apply(chain, requestInterceptorChain);\n chain.push.apply(chain, responseInterceptorChain);\n len = chain.length;\n\n promise = Promise.resolve(config);\n\n while (i < len) {\n promise = promise.then(chain[i++], chain[i++]);\n }\n\n return promise;\n }\n\n len = requestInterceptorChain.length;\n\n let newConfig = config;\n\n i = 0;\n\n while (i < len) {\n const onFulfilled = requestInterceptorChain[i++];\n const onRejected = requestInterceptorChain[i++];\n try {\n newConfig = onFulfilled(newConfig);\n } catch (error) {\n onRejected.call(this, error);\n break;\n }\n }\n\n try {\n promise = dispatchRequest.call(this, newConfig);\n } catch (error) {\n return Promise.reject(error);\n }\n\n i = 0;\n len = responseInterceptorChain.length;\n\n while (i < len) {\n promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);\n }\n\n return promise;\n }\n\n getUri(config) {\n config = mergeConfig(this.defaults, config);\n const fullPath = buildFullPath(config.baseURL, config.url);\n return buildURL(fullPath, config.params, config.paramsSerializer);\n }\n}\n\n// Provide aliases for supported request methods\nutils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {\n /*eslint func-names:0*/\n Axios.prototype[method] = function(url, config) {\n return this.request(mergeConfig(config || {}, {\n method,\n url,\n data: (config || {}).data\n }));\n };\n});\n\nutils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {\n /*eslint func-names:0*/\n\n function generateHTTPMethod(isForm) {\n return function httpMethod(url, data, config) {\n return this.request(mergeConfig(config || {}, {\n method,\n headers: isForm ? {\n 'Content-Type': 'multipart/form-data'\n } : {},\n url,\n data\n }));\n };\n }\n\n Axios.prototype[method] = generateHTTPMethod();\n\n Axios.prototype[method + 'Form'] = generateHTTPMethod(true);\n});\n\nexport default Axios;\n","'use strict';\n\nimport CanceledError from './CanceledError.js';\n\n/**\n * A `CancelToken` is an object that can be used to request cancellation of an operation.\n *\n * @param {Function} executor The executor function.\n *\n * @returns {CancelToken}\n */\nclass CancelToken {\n constructor(executor) {\n if (typeof executor !== 'function') {\n throw new TypeError('executor must be a function.');\n }\n\n let resolvePromise;\n\n this.promise = new Promise(function promiseExecutor(resolve) {\n resolvePromise = resolve;\n });\n\n const token = this;\n\n // eslint-disable-next-line func-names\n this.promise.then(cancel => {\n if (!token._listeners) return;\n\n let i = token._listeners.length;\n\n while (i-- > 0) {\n token._listeners[i](cancel);\n }\n token._listeners = null;\n });\n\n // eslint-disable-next-line func-names\n this.promise.then = onfulfilled => {\n let _resolve;\n // eslint-disable-next-line func-names\n const promise = new Promise(resolve => {\n token.subscribe(resolve);\n _resolve = resolve;\n }).then(onfulfilled);\n\n promise.cancel = function reject() {\n token.unsubscribe(_resolve);\n };\n\n return promise;\n };\n\n executor(function cancel(message, config, request) {\n if (token.reason) {\n // Cancellation has already been requested\n return;\n }\n\n token.reason = new CanceledError(message, config, request);\n resolvePromise(token.reason);\n });\n }\n\n /**\n * Throws a `CanceledError` if cancellation has been requested.\n */\n throwIfRequested() {\n if (this.reason) {\n throw this.reason;\n }\n }\n\n /**\n * Subscribe to the cancel signal\n */\n\n subscribe(listener) {\n if (this.reason) {\n listener(this.reason);\n return;\n }\n\n if (this._listeners) {\n this._listeners.push(listener);\n } else {\n this._listeners = [listener];\n }\n }\n\n /**\n * Unsubscribe from the cancel signal\n */\n\n unsubscribe(listener) {\n if (!this._listeners) {\n return;\n }\n const index = this._listeners.indexOf(listener);\n if (index !== -1) {\n this._listeners.splice(index, 1);\n }\n }\n\n /**\n * Returns an object that contains a new `CancelToken` and a function that, when called,\n * cancels the `CancelToken`.\n */\n static source() {\n let cancel;\n const token = new CancelToken(function executor(c) {\n cancel = c;\n });\n return {\n token,\n cancel\n };\n }\n}\n\nexport default CancelToken;\n","'use strict';\n\n/**\n * Syntactic sugar for invoking a function and expanding an array for arguments.\n *\n * Common use case would be to use `Function.prototype.apply`.\n *\n * ```js\n * function f(x, y, z) {}\n * var args = [1, 2, 3];\n * f.apply(null, args);\n * ```\n *\n * With `spread` this example can be re-written.\n *\n * ```js\n * spread(function(x, y, z) {})([1, 2, 3]);\n * ```\n *\n * @param {Function} callback\n *\n * @returns {Function}\n */\nexport default function spread(callback) {\n return function wrap(arr) {\n return callback.apply(null, arr);\n };\n}\n","'use strict';\n\nimport utils from './../utils.js';\n\n/**\n * Determines whether the payload is an error thrown by Axios\n *\n * @param {*} payload The value to test\n *\n * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false\n */\nexport default function isAxiosError(payload) {\n return utils.isObject(payload) && (payload.isAxiosError === true);\n}\n","const HttpStatusCode = {\n Continue: 100,\n SwitchingProtocols: 101,\n Processing: 102,\n EarlyHints: 103,\n Ok: 200,\n Created: 201,\n Accepted: 202,\n NonAuthoritativeInformation: 203,\n NoContent: 204,\n ResetContent: 205,\n PartialContent: 206,\n MultiStatus: 207,\n AlreadyReported: 208,\n ImUsed: 226,\n MultipleChoices: 300,\n MovedPermanently: 301,\n Found: 302,\n SeeOther: 303,\n NotModified: 304,\n UseProxy: 305,\n Unused: 306,\n TemporaryRedirect: 307,\n PermanentRedirect: 308,\n BadRequest: 400,\n Unauthorized: 401,\n PaymentRequired: 402,\n Forbidden: 403,\n NotFound: 404,\n MethodNotAllowed: 405,\n NotAcceptable: 406,\n ProxyAuthenticationRequired: 407,\n RequestTimeout: 408,\n Conflict: 409,\n Gone: 410,\n LengthRequired: 411,\n PreconditionFailed: 412,\n PayloadTooLarge: 413,\n UriTooLong: 414,\n UnsupportedMediaType: 415,\n RangeNotSatisfiable: 416,\n ExpectationFailed: 417,\n ImATeapot: 418,\n MisdirectedRequest: 421,\n UnprocessableEntity: 422,\n Locked: 423,\n FailedDependency: 424,\n TooEarly: 425,\n UpgradeRequired: 426,\n PreconditionRequired: 428,\n TooManyRequests: 429,\n RequestHeaderFieldsTooLarge: 431,\n UnavailableForLegalReasons: 451,\n InternalServerError: 500,\n NotImplemented: 501,\n BadGateway: 502,\n ServiceUnavailable: 503,\n GatewayTimeout: 504,\n HttpVersionNotSupported: 505,\n VariantAlsoNegotiates: 506,\n InsufficientStorage: 507,\n LoopDetected: 508,\n NotExtended: 510,\n NetworkAuthenticationRequired: 511,\n};\n\nObject.entries(HttpStatusCode).forEach(([key, value]) => {\n HttpStatusCode[value] = key;\n});\n\nexport default HttpStatusCode;\n","'use strict';\n\nimport utils from './utils.js';\nimport bind from './helpers/bind.js';\nimport Axios from './core/Axios.js';\nimport mergeConfig from './core/mergeConfig.js';\nimport defaults from './defaults/index.js';\nimport formDataToJSON from './helpers/formDataToJSON.js';\nimport CanceledError from './cancel/CanceledError.js';\nimport CancelToken from './cancel/CancelToken.js';\nimport isCancel from './cancel/isCancel.js';\nimport {VERSION} from './env/data.js';\nimport toFormData from './helpers/toFormData.js';\nimport AxiosError from './core/AxiosError.js';\nimport spread from './helpers/spread.js';\nimport isAxiosError from './helpers/isAxiosError.js';\nimport AxiosHeaders from \"./core/AxiosHeaders.js\";\nimport adapters from './adapters/adapters.js';\nimport HttpStatusCode from './helpers/HttpStatusCode.js';\n\n/**\n * Create an instance of Axios\n *\n * @param {Object} defaultConfig The default config for the instance\n *\n * @returns {Axios} A new instance of Axios\n */\nfunction createInstance(defaultConfig) {\n const context = new Axios(defaultConfig);\n const instance = bind(Axios.prototype.request, context);\n\n // Copy axios.prototype to instance\n utils.extend(instance, Axios.prototype, context, {allOwnKeys: true});\n\n // Copy context to instance\n utils.extend(instance, context, null, {allOwnKeys: true});\n\n // Factory for creating new instances\n instance.create = function create(instanceConfig) {\n return createInstance(mergeConfig(defaultConfig, instanceConfig));\n };\n\n return instance;\n}\n\n// Create the default instance to be exported\nconst axios = createInstance(defaults);\n\n// Expose Axios class to allow class inheritance\naxios.Axios = Axios;\n\n// Expose Cancel & CancelToken\naxios.CanceledError = CanceledError;\naxios.CancelToken = CancelToken;\naxios.isCancel = isCancel;\naxios.VERSION = VERSION;\naxios.toFormData = toFormData;\n\n// Expose AxiosError class\naxios.AxiosError = AxiosError;\n\n// alias for CanceledError for backward compatibility\naxios.Cancel = axios.CanceledError;\n\n// Expose all/spread\naxios.all = function all(promises) {\n return Promise.all(promises);\n};\n\naxios.spread = spread;\n\n// Expose isAxiosError\naxios.isAxiosError = isAxiosError;\n\n// Expose mergeConfig\naxios.mergeConfig = mergeConfig;\n\naxios.AxiosHeaders = AxiosHeaders;\n\naxios.formToJSON = thing => formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing);\n\naxios.getAdapter = adapters.getAdapter;\n\naxios.HttpStatusCode = HttpStatusCode;\n\naxios.default = axios;\n\n// this module should only have a default export\nexport default axios\n","import axios from './lib/axios.js';\n\n// This module is intended to unwrap Axios default export as named.\n// Keep top-level export same with static properties\n// so that it can keep same with es module or cjs\nconst {\n Axios,\n AxiosError,\n CanceledError,\n isCancel,\n CancelToken,\n VERSION,\n all,\n Cancel,\n isAxiosError,\n spread,\n toFormData,\n AxiosHeaders,\n HttpStatusCode,\n formToJSON,\n getAdapter,\n mergeConfig\n} = axios;\n\nexport {\n axios as default,\n Axios,\n AxiosError,\n CanceledError,\n isCancel,\n CancelToken,\n VERSION,\n all,\n Cancel,\n isAxiosError,\n spread,\n toFormData,\n AxiosHeaders,\n HttpStatusCode,\n formToJSON,\n getAdapter,\n mergeConfig\n}\n","import { ComfyWorkflowJSON } from '@/types/comfyWorkflow'\nimport {\n DownloadModelStatus,\n HistoryTaskItem,\n PendingTaskItem,\n RunningTaskItem,\n ComfyNodeDef,\n validateComfyNodeDef,\n EmbeddingsResponse,\n ExtensionsResponse,\n PromptResponse,\n SystemStats,\n User,\n Settings,\n UserDataFullInfo\n} from '@/types/apiTypes'\nimport axios from 'axios'\n\ninterface QueuePromptRequestBody {\n client_id: string\n // Mapping from node id to node info + input values\n // TODO: Type this.\n prompt: Record\n extra_data: {\n extra_pnginfo: {\n workflow: ComfyWorkflowJSON\n }\n }\n front?: boolean\n number?: number\n}\n\nclass ComfyApi extends EventTarget {\n #registered = new Set()\n api_host: string\n api_base: string\n initialClientId: string\n user: string\n socket?: WebSocket\n clientId?: string\n\n reportedUnknownMessageTypes = new Set()\n\n constructor() {\n super()\n this.api_host = location.host\n this.api_base = location.pathname.split('/').slice(0, -1).join('/')\n this.initialClientId = sessionStorage.getItem('clientId')\n }\n\n internalURL(route: string): string {\n return this.api_base + '/internal' + route\n }\n\n apiURL(route: string): string {\n return this.api_base + '/api' + route\n }\n\n fileURL(route: string): string {\n return this.api_base + route\n }\n\n fetchApi(route: string, options?: RequestInit) {\n if (!options) {\n options = {}\n }\n if (!options.headers) {\n options.headers = {}\n }\n if (!options.cache) {\n options.cache = 'no-cache'\n }\n options.headers['Comfy-User'] = this.user\n return fetch(this.apiURL(route), options)\n }\n\n addEventListener(\n type: string,\n callback: any,\n options?: AddEventListenerOptions\n ) {\n super.addEventListener(type, callback, options)\n this.#registered.add(type)\n }\n\n /**\n * Poll status for colab and other things that don't support websockets.\n */\n #pollQueue() {\n setInterval(async () => {\n try {\n const resp = await this.fetchApi('/prompt')\n const status = await resp.json()\n this.dispatchEvent(new CustomEvent('status', { detail: status }))\n } catch (error) {\n this.dispatchEvent(new CustomEvent('status', { detail: null }))\n }\n }, 1000)\n }\n\n /**\n * Creates and connects a WebSocket for realtime updates\n * @param {boolean} isReconnect If the socket is connection is a reconnect attempt\n */\n #createSocket(isReconnect?: boolean) {\n if (this.socket) {\n return\n }\n\n let opened = false\n let existingSession = window.name\n if (existingSession) {\n existingSession = '?clientId=' + existingSession\n }\n this.socket = new WebSocket(\n `ws${window.location.protocol === 'https:' ? 's' : ''}://${this.api_host}${this.api_base}/ws${existingSession}`\n )\n this.socket.binaryType = 'arraybuffer'\n\n this.socket.addEventListener('open', () => {\n opened = true\n if (isReconnect) {\n this.dispatchEvent(new CustomEvent('reconnected'))\n }\n })\n\n this.socket.addEventListener('error', () => {\n if (this.socket) this.socket.close()\n if (!isReconnect && !opened) {\n this.#pollQueue()\n }\n })\n\n this.socket.addEventListener('close', () => {\n setTimeout(() => {\n this.socket = null\n this.#createSocket(true)\n }, 300)\n if (opened) {\n this.dispatchEvent(new CustomEvent('status', { detail: null }))\n this.dispatchEvent(new CustomEvent('reconnecting'))\n }\n })\n\n this.socket.addEventListener('message', (event) => {\n try {\n if (event.data instanceof ArrayBuffer) {\n const view = new DataView(event.data)\n const eventType = view.getUint32(0)\n const buffer = event.data.slice(4)\n switch (eventType) {\n case 1:\n const view2 = new DataView(event.data)\n const imageType = view2.getUint32(0)\n let imageMime\n switch (imageType) {\n case 1:\n default:\n imageMime = 'image/jpeg'\n break\n case 2:\n imageMime = 'image/png'\n }\n const imageBlob = new Blob([buffer.slice(4)], {\n type: imageMime\n })\n this.dispatchEvent(\n new CustomEvent('b_preview', { detail: imageBlob })\n )\n break\n default:\n throw new Error(\n `Unknown binary websocket message of type ${eventType}`\n )\n }\n } else {\n const msg = JSON.parse(event.data)\n switch (msg.type) {\n case 'status':\n if (msg.data.sid) {\n this.clientId = msg.data.sid\n window.name = this.clientId // use window name so it isnt reused when duplicating tabs\n sessionStorage.setItem('clientId', this.clientId) // store in session storage so duplicate tab can load correct workflow\n }\n this.dispatchEvent(\n new CustomEvent('status', { detail: msg.data.status })\n )\n break\n case 'progress':\n this.dispatchEvent(\n new CustomEvent('progress', { detail: msg.data })\n )\n break\n case 'executing':\n this.dispatchEvent(\n new CustomEvent('executing', {\n detail: msg.data.display_node || msg.data.node\n })\n )\n break\n case 'executed':\n this.dispatchEvent(\n new CustomEvent('executed', { detail: msg.data })\n )\n break\n case 'execution_start':\n this.dispatchEvent(\n new CustomEvent('execution_start', { detail: msg.data })\n )\n break\n case 'execution_success':\n this.dispatchEvent(\n new CustomEvent('execution_success', { detail: msg.data })\n )\n break\n case 'execution_error':\n this.dispatchEvent(\n new CustomEvent('execution_error', { detail: msg.data })\n )\n break\n case 'execution_cached':\n this.dispatchEvent(\n new CustomEvent('execution_cached', { detail: msg.data })\n )\n break\n case 'download_progress':\n this.dispatchEvent(\n new CustomEvent('download_progress', { detail: msg.data })\n )\n break\n default:\n if (this.#registered.has(msg.type)) {\n this.dispatchEvent(\n new CustomEvent(msg.type, { detail: msg.data })\n )\n } else if (!this.reportedUnknownMessageTypes.has(msg.type)) {\n this.reportedUnknownMessageTypes.add(msg.type)\n throw new Error(`Unknown message type ${msg.type}`)\n }\n }\n }\n } catch (error) {\n console.warn('Unhandled message:', event.data, error)\n }\n })\n }\n\n /**\n * Initialises sockets and realtime updates\n */\n init() {\n this.#createSocket()\n }\n\n /**\n * Gets a list of extension urls\n */\n async getExtensions(): Promise {\n const resp = await this.fetchApi('/extensions', { cache: 'no-store' })\n return await resp.json()\n }\n\n /**\n * Gets a list of embedding names\n */\n async getEmbeddings(): Promise {\n const resp = await this.fetchApi('/embeddings', { cache: 'no-store' })\n return await resp.json()\n }\n\n /**\n * Loads node object definitions for the graph\n * @returns The node definitions\n */\n async getNodeDefs(): Promise> {\n const resp = await this.fetchApi('/object_info', { cache: 'no-store' })\n const objectInfoUnsafe = await resp.json()\n const objectInfo: Record = {}\n for (const key in objectInfoUnsafe) {\n const validatedDef = validateComfyNodeDef(\n objectInfoUnsafe[key],\n /* onError=*/ (errorMessage: string) => {\n console.warn(\n `Skipping invalid node definition: ${key}. See debug log for more information.`\n )\n console.debug(errorMessage)\n }\n )\n if (validatedDef !== null) {\n objectInfo[key] = validatedDef\n }\n }\n return objectInfo\n }\n\n /**\n *\n * @param {number} number The index at which to queue the prompt, passing -1 will insert the prompt at the front of the queue\n * @param {object} prompt The prompt data to queue\n */\n async queuePrompt(\n number: number,\n { output, workflow }\n ): Promise {\n const body: QueuePromptRequestBody = {\n client_id: this.clientId,\n prompt: output,\n extra_data: { extra_pnginfo: { workflow } }\n }\n\n if (number === -1) {\n body.front = true\n } else if (number != 0) {\n body.number = number\n }\n\n const res = await this.fetchApi('/prompt', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(body)\n })\n\n if (res.status !== 200) {\n throw {\n response: await res.json()\n }\n }\n\n return await res.json()\n }\n\n /**\n * Gets a list of models in the specified folder\n * @param {string} folder The folder to list models from, such as 'checkpoints'\n * @returns The list of model filenames within the specified folder\n */\n async getModels(folder: string) {\n const res = await this.fetchApi(`/models/${folder}`)\n if (res.status === 404) {\n return null\n }\n return await res.json()\n }\n\n /**\n * Gets the metadata for a model\n * @param {string} folder The folder containing the model\n * @param {string} model The model to get metadata for\n * @returns The metadata for the model\n */\n async viewMetadata(folder: string, model: string) {\n const res = await this.fetchApi(\n `/view_metadata/${folder}?filename=${encodeURIComponent(model)}`\n )\n return await res.json()\n }\n\n /**\n * Tells the server to download a model from the specified URL to the specified directory and filename\n * @param {string} url The URL to download the model from\n * @param {string} model_directory The main directory (eg 'checkpoints') to save the model to\n * @param {string} model_filename The filename to save the model as\n * @param {number} progress_interval The interval in seconds at which to report download progress (via 'download_progress' event)\n */\n async internalDownloadModel(\n url: string,\n model_directory: string,\n model_filename: string,\n progress_interval: number\n ): Promise {\n const res = await this.fetchApi('/internal/models/download', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify({\n url,\n model_directory,\n model_filename,\n progress_interval\n })\n })\n return await res.json()\n }\n\n /**\n * Loads a list of items (queue or history)\n * @param {string} type The type of items to load, queue or history\n * @returns The items of the specified type grouped by their status\n */\n async getItems(type: 'queue' | 'history') {\n if (type === 'queue') {\n return this.getQueue()\n }\n return this.getHistory()\n }\n\n /**\n * Gets the current state of the queue\n * @returns The currently running and queued items\n */\n async getQueue(): Promise<{\n Running: RunningTaskItem[]\n Pending: PendingTaskItem[]\n }> {\n try {\n const res = await this.fetchApi('/queue')\n const data = await res.json()\n return {\n // Running action uses a different endpoint for cancelling\n Running: data.queue_running.map((prompt) => ({\n taskType: 'Running',\n prompt,\n remove: { name: 'Cancel', cb: () => api.interrupt() }\n })),\n Pending: data.queue_pending.map((prompt) => ({\n taskType: 'Pending',\n prompt\n }))\n }\n } catch (error) {\n console.error(error)\n return { Running: [], Pending: [] }\n }\n }\n\n /**\n * Gets the prompt execution history\n * @returns Prompt history including node outputs\n */\n async getHistory(\n max_items: number = 200\n ): Promise<{ History: HistoryTaskItem[] }> {\n try {\n const res = await this.fetchApi(`/history?max_items=${max_items}`)\n const json: Promise = await res.json()\n return {\n History: Object.values(json).map((item) => ({\n ...item,\n taskType: 'History'\n }))\n }\n } catch (error) {\n console.error(error)\n return { History: [] }\n }\n }\n\n /**\n * Gets system & device stats\n * @returns System stats such as python version, OS, per device info\n */\n async getSystemStats(): Promise {\n const res = await this.fetchApi('/system_stats')\n return await res.json()\n }\n\n /**\n * Sends a POST request to the API\n * @param {*} type The endpoint to post to\n * @param {*} body Optional POST data\n */\n async #postItem(type: string, body: any) {\n try {\n await this.fetchApi('/' + type, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: body ? JSON.stringify(body) : undefined\n })\n } catch (error) {\n console.error(error)\n }\n }\n\n /**\n * Deletes an item from the specified list\n * @param {string} type The type of item to delete, queue or history\n * @param {number} id The id of the item to delete\n */\n async deleteItem(type: string, id: string) {\n await this.#postItem(type, { delete: [id] })\n }\n\n /**\n * Clears the specified list\n * @param {string} type The type of list to clear, queue or history\n */\n async clearItems(type: string) {\n await this.#postItem(type, { clear: true })\n }\n\n /**\n * Interrupts the execution of the running prompt\n */\n async interrupt() {\n await this.#postItem('interrupt', null)\n }\n\n /**\n * Gets user configuration data and where data should be stored\n */\n async getUserConfig(): Promise {\n return (await this.fetchApi('/users')).json()\n }\n\n /**\n * Creates a new user\n * @param { string } username\n * @returns The fetch response\n */\n createUser(username: string) {\n return this.fetchApi('/users', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify({ username })\n })\n }\n\n /**\n * Gets all setting values for the current user\n * @returns { Promise } A dictionary of id -> value\n */\n async getSettings(): Promise {\n return (await this.fetchApi('/settings')).json()\n }\n\n /**\n * Gets a setting for the current user\n * @param { string } id The id of the setting to fetch\n * @returns { Promise } The setting value\n */\n async getSetting(id: keyof Settings): Promise {\n return (await this.fetchApi(`/settings/${encodeURIComponent(id)}`)).json()\n }\n\n /**\n * Stores a dictionary of settings for the current user\n */\n async storeSettings(settings: Settings) {\n return this.fetchApi(`/settings`, {\n method: 'POST',\n body: JSON.stringify(settings)\n })\n }\n\n /**\n * Stores a setting for the current user\n */\n async storeSetting(id: keyof Settings, value: Settings[keyof Settings]) {\n return this.fetchApi(`/settings/${encodeURIComponent(id)}`, {\n method: 'POST',\n body: JSON.stringify(value)\n })\n }\n\n /**\n * Gets a user data file for the current user\n */\n async getUserData(file: string, options?: RequestInit) {\n return this.fetchApi(`/userdata/${encodeURIComponent(file)}`, options)\n }\n\n /**\n * Stores a user data file for the current user\n * @param { string } file The name of the userdata file to save\n * @param { unknown } data The data to save to the file\n * @param { RequestInit & { stringify?: boolean, throwOnError?: boolean } } [options]\n * @returns { Promise }\n */\n async storeUserData(\n file: string,\n data: any,\n options: RequestInit & {\n overwrite?: boolean\n stringify?: boolean\n throwOnError?: boolean\n } = { overwrite: true, stringify: true, throwOnError: true }\n ): Promise {\n const resp = await this.fetchApi(\n `/userdata/${encodeURIComponent(file)}?overwrite=${options.overwrite}`,\n {\n method: 'POST',\n body: options?.stringify ? JSON.stringify(data) : data,\n ...options\n }\n )\n if (resp.status !== 200 && options.throwOnError !== false) {\n throw new Error(\n `Error storing user data file '${file}': ${resp.status} ${(await resp).statusText}`\n )\n }\n\n return resp\n }\n\n /**\n * Deletes a user data file for the current user\n * @param { string } file The name of the userdata file to delete\n */\n async deleteUserData(file: string) {\n const resp = await this.fetchApi(`/userdata/${encodeURIComponent(file)}`, {\n method: 'DELETE'\n })\n return resp\n }\n\n /**\n * Move a user data file for the current user\n * @param { string } source The userdata file to move\n * @param { string } dest The destination for the file\n */\n async moveUserData(\n source: string,\n dest: string,\n options = { overwrite: false }\n ) {\n const resp = await this.fetchApi(\n `/userdata/${encodeURIComponent(source)}/move/${encodeURIComponent(dest)}?overwrite=${options?.overwrite}`,\n {\n method: 'POST'\n }\n )\n return resp\n }\n\n /**\n * @overload\n * Lists user data files for the current user\n * @param { string } dir The directory in which to list files\n * @param { boolean } [recurse] If the listing should be recursive\n * @param { true } [split] If the paths should be split based on the os path separator\n * @returns { Promise } The list of split file paths in the format [fullPath, ...splitPath]\n */\n /**\n * @overload\n * Lists user data files for the current user\n * @param { string } dir The directory in which to list files\n * @param { boolean } [recurse] If the listing should be recursive\n * @param { false | undefined } [split] If the paths should be split based on the os path separator\n * @returns { Promise } The list of files\n */\n async listUserData(\n dir: string,\n recurse: boolean,\n split?: true\n ): Promise\n async listUserData(\n dir: string,\n recurse: boolean,\n split?: false\n ): Promise\n async listUserData(dir, recurse, split) {\n const resp = await this.fetchApi(\n `/userdata?${new URLSearchParams({\n recurse,\n dir,\n split\n })}`\n )\n if (resp.status === 404) return []\n if (resp.status !== 200) {\n throw new Error(\n `Error getting user data list '${dir}': ${resp.status} ${resp.statusText}`\n )\n }\n return resp.json()\n }\n\n async listUserDataFullInfo(dir: string): Promise {\n const resp = await this.fetchApi(\n `/userdata?dir=${encodeURIComponent(dir)}&recurse=true&split=false&full_info=true`\n )\n if (resp.status === 404) return []\n if (resp.status !== 200) {\n throw new Error(\n `Error getting user data list '${dir}': ${resp.status} ${resp.statusText}`\n )\n }\n return resp.json()\n }\n\n async getLogs(): Promise {\n return (await axios.get(this.internalURL('/logs'))).data\n }\n}\n\nexport const api = new ComfyApi()\n","import { useDialogStore } from '@/stores/dialogStore'\nimport { $el } from '../ui'\n\nexport class ComfyDialog<\n T extends HTMLElement = HTMLElement\n> extends EventTarget {\n element: T\n textElement: HTMLElement\n #buttons: HTMLButtonElement[] | null\n\n constructor(type = 'div', buttons = null) {\n super()\n this.#buttons = buttons\n this.element = $el(type + '.comfy-modal', { parent: document.body }, [\n $el('div.comfy-modal-content', [\n $el('p', { $: (p) => (this.textElement = p) }),\n ...this.createButtons()\n ])\n ]) as T\n }\n\n createButtons() {\n return (\n this.#buttons ?? [\n $el('button', {\n type: 'button',\n textContent: 'Close',\n onclick: () => this.close()\n })\n ]\n )\n }\n\n close() {\n this.element.style.display = 'none'\n }\n\n show(html) {\n if (typeof html === 'string') {\n this.textElement.innerHTML = html\n } else {\n this.textElement.replaceChildren(\n ...(html instanceof Array ? html : [html])\n )\n }\n this.element.style.display = 'flex'\n }\n}\n","import { $el } from '../ui'\n\n/**\n * @typedef { { text: string, value?: string, tooltip?: string } } ToggleSwitchItem\n */\n/**\n * Creates a toggle switch element\n * @param { string } name\n * @param { Array | ToggleSwitchItem } items\n * @param { Object } [opts]\n * @param { (e: { item: ToggleSwitchItem, prev?: ToggleSwitchItem }) => void } [opts.onChange]\n */\nexport function toggleSwitch(name, items, e?) {\n const onChange = e?.onChange\n\n let selectedIndex\n let elements\n\n function updateSelected(index) {\n if (selectedIndex != null) {\n elements[selectedIndex].classList.remove('comfy-toggle-selected')\n }\n onChange?.({\n item: items[index],\n prev: selectedIndex == null ? undefined : items[selectedIndex]\n })\n selectedIndex = index\n elements[selectedIndex].classList.add('comfy-toggle-selected')\n }\n\n elements = items.map((item, i) => {\n if (typeof item === 'string') item = { text: item }\n if (!item.value) item.value = item.text\n\n const toggle = $el(\n 'label',\n {\n textContent: item.text,\n title: item.tooltip ?? ''\n },\n $el('input', {\n name,\n type: 'radio',\n value: item.value ?? item.text,\n checked: item.selected,\n onchange: () => {\n updateSelected(i)\n }\n })\n )\n if (item.selected) {\n updateSelected(i)\n }\n return toggle\n })\n\n const container = $el('div.comfy-toggle-switch', elements)\n\n if (selectedIndex == null) {\n elements[0].children[0].checked = true\n updateSelected(0)\n }\n\n return container\n}\n","import { $el } from '../ui'\nimport { api } from '../api'\nimport { ComfyDialog } from './dialog'\nimport type { ComfyApp } from '../app'\nimport type { Setting, SettingParams } from '@/types/settingTypes'\nimport { useSettingStore } from '@/stores/settingStore'\nimport { Settings } from '@/types/apiTypes'\n\nexport class ComfySettingsDialog extends ComfyDialog {\n app: ComfyApp\n settingsValues: any\n settingsLookup: Record\n settingsParamLookup: Record\n\n constructor(app: ComfyApp) {\n super()\n const frontendVersion = window['__COMFYUI_FRONTEND_VERSION__']\n this.app = app\n this.settingsValues = {}\n this.settingsLookup = {}\n this.settingsParamLookup = {}\n this.element = $el(\n 'dialog',\n {\n id: 'comfy-settings-dialog',\n parent: document.body\n },\n [\n $el('table.comfy-modal-content.comfy-table', [\n $el(\n 'caption',\n { textContent: `Settings (v${frontendVersion})` },\n $el('button.comfy-btn', {\n type: 'button',\n textContent: '\\u00d7',\n onclick: () => {\n this.element.close()\n }\n })\n ),\n $el('tbody', { $: (tbody) => (this.textElement = tbody) }),\n $el('button', {\n type: 'button',\n textContent: 'Close',\n style: {\n cursor: 'pointer'\n },\n onclick: () => {\n this.element.close()\n }\n })\n ])\n ]\n ) as HTMLDialogElement\n }\n\n get settings() {\n return Object.values(this.settingsLookup)\n }\n\n #dispatchChange(id: string, value: T, oldValue?: T) {\n // Keep the settingStore updated. Not using `store.set` as it would trigger\n // setSettingValue again.\n // `load` re-dispatch the change for any settings added before load so\n // settingStore is always up to date.\n if (this.app.vueAppReady) {\n useSettingStore().settingValues[id] = value\n }\n\n this.dispatchEvent(\n new CustomEvent(id + '.change', {\n detail: {\n value,\n oldValue\n }\n })\n )\n }\n\n async load() {\n if (this.app.storageLocation === 'browser') {\n this.settingsValues = localStorage\n } else {\n this.settingsValues = await api.getSettings()\n }\n\n // Trigger onChange for any settings added before load\n for (const id in this.settingsLookup) {\n const value = this.settingsValues[this.getId(id)]\n this.settingsLookup[id].onChange?.(value)\n this.#dispatchChange(id, value)\n }\n }\n\n getId(id: string) {\n if (this.app.storageLocation === 'browser') {\n id = 'Comfy.Settings.' + id\n }\n return id\n }\n\n getSettingValue(\n id: K,\n defaultValue?: Settings[K]\n ): Settings[K] {\n let value = this.settingsValues[this.getId(id)]\n if (value != null) {\n if (this.app.storageLocation === 'browser') {\n try {\n value = JSON.parse(value)\n } catch (error) {}\n }\n }\n return (value ?? defaultValue) as Settings[K]\n }\n\n getSettingDefaultValue(id: string) {\n const param = this.settingsParamLookup[id]\n return param?.defaultValue\n }\n\n async setSettingValueAsync(\n id: K,\n value: Settings[K]\n ) {\n const json = JSON.stringify(value)\n localStorage['Comfy.Settings.' + id] = json // backwards compatibility for extensions keep setting in storage\n\n let oldValue = this.getSettingValue(id, undefined)\n this.settingsValues[this.getId(id)] = value\n\n if (id in this.settingsLookup) {\n this.settingsLookup[id].onChange?.(value, oldValue)\n }\n this.#dispatchChange(id, value, oldValue)\n\n await api.storeSetting(id, value)\n }\n\n setSettingValue(id: K, value: Settings[K]) {\n this.setSettingValueAsync(id, value).catch((err) => {\n alert(`Error saving setting '${id}'`)\n console.error(err)\n })\n }\n\n refreshSetting(id: keyof Settings) {\n const value = this.getSettingValue(id)\n this.settingsLookup[id].onChange?.(value)\n this.#dispatchChange(id, value)\n }\n\n addSetting(params: SettingParams) {\n const {\n id,\n name,\n type,\n defaultValue,\n onChange,\n attrs = {},\n tooltip = '',\n options = undefined\n } = params\n if (!id) {\n throw new Error('Settings must have an ID')\n }\n\n if (id in this.settingsLookup) {\n throw new Error(`Setting ${id} of type ${type} must have a unique ID.`)\n }\n\n let skipOnChange = false\n let value = this.getSettingValue(id)\n if (value == null) {\n if (this.app.isNewUserSession) {\n // Check if we have a localStorage value but not a setting value and we are a new user\n const localValue = localStorage['Comfy.Settings.' + id]\n if (localValue) {\n value = JSON.parse(localValue)\n this.setSettingValue(id, value) // Store on the server\n }\n }\n if (value == null) {\n value = defaultValue\n }\n }\n\n // Trigger initial setting of value\n if (!skipOnChange) {\n onChange?.(value, undefined)\n this.#dispatchChange(id, value)\n }\n\n this.settingsParamLookup[id] = params\n if (this.app.vueAppReady) {\n useSettingStore().settings[id] = params\n }\n this.settingsLookup[id] = {\n id,\n onChange,\n name,\n render: () => {\n if (type === 'hidden') return\n\n const setter = (v) => {\n if (onChange) {\n onChange(v, value)\n }\n\n this.setSettingValue(id, v)\n value = v\n }\n value = this.getSettingValue(id, defaultValue)\n\n let element\n const htmlID = id.replaceAll('.', '-')\n\n const labelCell = $el('td', [\n $el('label', {\n for: htmlID,\n classList: [tooltip !== '' ? 'comfy-tooltip-indicator' : ''],\n textContent: name\n })\n ])\n\n if (typeof type === 'function') {\n element = type(name, setter, value, attrs)\n } else {\n switch (type) {\n case 'boolean':\n element = $el('tr', [\n labelCell,\n $el('td', [\n $el('input', {\n id: htmlID,\n type: 'checkbox',\n checked: value,\n onchange: (event) => {\n const isChecked = event.target.checked\n if (onChange !== undefined) {\n onChange(isChecked)\n }\n this.setSettingValue(id, isChecked)\n }\n })\n ])\n ])\n break\n case 'number':\n element = $el('tr', [\n labelCell,\n $el('td', [\n $el('input', {\n type,\n value,\n id: htmlID,\n oninput: (e) => {\n setter(e.target.value)\n },\n ...attrs\n })\n ])\n ])\n break\n case 'slider':\n element = $el('tr', [\n labelCell,\n $el('td', [\n $el(\n 'div',\n {\n style: {\n display: 'grid',\n gridAutoFlow: 'column'\n }\n },\n [\n $el('input', {\n ...attrs,\n value,\n type: 'range',\n oninput: (e) => {\n setter(e.target.value)\n e.target.nextElementSibling.value = e.target.value\n }\n }),\n $el('input', {\n ...attrs,\n value,\n id: htmlID,\n type: 'number',\n style: { maxWidth: '4rem' },\n oninput: (e) => {\n setter(e.target.value)\n e.target.previousElementSibling.value = e.target.value\n }\n })\n ]\n )\n ])\n ])\n break\n case 'combo':\n element = $el('tr', [\n labelCell,\n $el('td', [\n $el(\n 'select',\n {\n oninput: (e) => {\n setter(e.target.value)\n }\n },\n (typeof options === 'function'\n ? options(value)\n : options || []\n ).map((opt) => {\n if (typeof opt === 'string') {\n opt = { text: opt }\n }\n const v = opt.value ?? opt.text\n return $el('option', {\n value: v,\n textContent: opt.text,\n selected: value + '' === v + ''\n })\n })\n )\n ])\n ])\n break\n case 'text':\n default:\n if (type !== 'text') {\n console.warn(\n `Unsupported setting type '${type}, defaulting to text`\n )\n }\n\n element = $el('tr', [\n labelCell,\n $el('td', [\n $el('input', {\n value,\n id: htmlID,\n oninput: (e) => {\n setter(e.target.value)\n },\n ...attrs\n })\n ])\n ])\n break\n }\n }\n if (tooltip) {\n element.title = tooltip\n }\n\n return element\n }\n } as Setting\n\n const self = this\n return {\n get value() {\n return self.getSettingValue(id, defaultValue)\n },\n set value(v) {\n self.setSettingValue(id, v)\n }\n }\n }\n\n show() {\n this.textElement.replaceChildren(\n $el(\n 'tr',\n {\n style: { display: 'none' }\n },\n [$el('th'), $el('th', { style: { width: '33%' } })]\n ),\n ...this.settings\n .sort((a, b) => a.name.localeCompare(b.name))\n .map((s) => s.render())\n .filter(Boolean)\n )\n this.element.showModal()\n }\n}\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","/*!\n * pinia v2.2.2\n * (c) 2024 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/*\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 = 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 // Expose pinia instance as $pinia to window\n globalThis.$pinia = pinia;\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 // Expose selected store as $store to window\n if (payload.nodeId !== PINIA_ROOT_ID)\n globalThis.$store = toRaw(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 // Do not overwrite actions mocked by @pinia/testing (#2298)\n if (!store._p._testing) {\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 }\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 ((((process.env.NODE_ENV !== 'production') || (typeof __VUE_PROD_DEVTOOLS__ !== 'undefined' && __VUE_PROD_DEVTOOLS__)) && !(process.env.NODE_ENV === 'test')) && IS_CLIENT) {\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 ((((process.env.NODE_ENV !== 'production') || (typeof __VUE_PROD_DEVTOOLS__ !== 'undefined' && __VUE_PROD_DEVTOOLS__)) && !(process.env.NODE_ENV === 'test')) && typeof Proxy !== 'undefined') {\n pinia.use(devtoolsPlugin);\n }\n return pinia;\n}\n/**\n * Dispose a Pinia instance by stopping its effectScope and removing the state, plugins and stores. This is mostly\n * useful in tests, with both a testing pinia or a regular pinia and in applications that use multiple pinia instances.\n * Once disposed, the pinia instance cannot be used anymore.\n *\n * @param pinia - pinia instance\n */\nfunction disposePinia(pinia) {\n pinia._e.stop();\n pinia._s.clear();\n pinia._p.splice(0);\n pinia.state.value = {};\n // @ts-expect-error: non valid\n pinia._a = null;\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();\n/**\n * Marks a function as an action for `$onAction`\n * @internal\n */\nconst ACTION_MARKER = Symbol();\n/**\n * Action name symbol. Allows to add a name to an action after defining it\n * @internal\n */\nconst ACTION_NAME = Symbol();\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 else if (target instanceof Set && patchToApply instanceof Set) {\n // Handle Set instances\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 if */\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 = { deep: true };\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 // @ts-expect-error: FIXME: shouldn't error?\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 * Helper that wraps function so it can be tracked with $onAction\n * @param fn - action to wrap\n * @param name - name of the action\n */\n const action = (fn, name = '') => {\n if (ACTION_MARKER in fn) {\n fn[ACTION_NAME] = name;\n return fn;\n }\n const wrappedAction = 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: wrappedAction[ACTION_NAME],\n store,\n after,\n onError,\n });\n let ret;\n try {\n ret = fn.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 wrappedAction[ACTION_MARKER] = true;\n wrappedAction[ACTION_NAME] = name; // will be set later\n // @ts-expect-error: we are intentionally limiting the returned type to just Fn\n // because all the added properties are internals that are exposed through `$onAction()` only\n return wrappedAction;\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') || ((((process.env.NODE_ENV !== 'production') || (typeof __VUE_PROD_DEVTOOLS__ !== 'undefined' && __VUE_PROD_DEVTOOLS__)) && !(process.env.NODE_ENV === 'test')) && IS_CLIENT)\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({ action }))));\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 const actionValue = (process.env.NODE_ENV !== 'production') && hot ? prop : action(prop, key);\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 // @ts-expect-error: FIXME: shouldn't error?\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 actionFn = newStore[actionName];\n set(store, actionName, action(actionFn, actionName));\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 ((((process.env.NODE_ENV !== 'production') || (typeof __VUE_PROD_DEVTOOLS__ !== 'undefined' && __VUE_PROD_DEVTOOLS__)) && !(process.env.NODE_ENV === 'test')) && IS_CLIENT) {\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 ((((process.env.NODE_ENV !== 'production') || (typeof __VUE_PROD_DEVTOOLS__ !== 'undefined' && __VUE_PROD_DEVTOOLS__)) && !(process.env.NODE_ENV === 'test')) && IS_CLIENT) {\n const extensions = scope.run(() => extender({\n store: 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: 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}\n// improves tree shaking\n/*#__NO_SIDE_EFFECTS__*/\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 // @ts-expect-error: FIXME: should work?\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 // @ts-expect-error: FIXME: should work?\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 // @ts-expect-error: FIXME: should work?\n return useStore(this.$pinia)[key];\n },\n set(value) {\n // @ts-expect-error: FIXME: should work?\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 // @ts-expect-error: FIXME: should work?\n return useStore(this.$pinia)[keysOrMapper[key]];\n },\n set(value) {\n // @ts-expect-error: FIXME: should work?\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 ((((process.env.NODE_ENV !== 'production') || (typeof __VUE_PROD_DEVTOOLS__ !== 'undefined' && __VUE_PROD_DEVTOOLS__)) && !(process.env.NODE_ENV === 'test')) && IS_CLIENT) {\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, disposePinia, 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.\n// Currently we need to bridge between legacy app code and Vue app with a Pinia store.\n\nimport { defineStore } from 'pinia'\nimport { type Component, markRaw } from 'vue'\n\ninterface DialogState {\n isVisible: boolean\n title: string\n headerComponent: Component | null\n component: Component | null\n props: Record\n}\n\nexport const useDialogStore = defineStore('dialog', {\n state: (): DialogState => ({\n isVisible: false,\n title: '',\n headerComponent: null,\n component: null,\n props: {}\n }),\n\n actions: {\n showDialog(options: {\n title?: string\n headerComponent?: Component\n component: Component\n props?: Record\n }) {\n this.title = options.title\n this.headerComponent = markRaw(options.headerComponent)\n this.component = markRaw(options.component)\n this.props = options.props || {}\n this.isVisible = true\n },\n\n closeDialog() {\n this.isVisible = false\n }\n }\n})\n","import { resolveFieldData, removeAccents, equals } from '@primeuix/utils/object';\n\nvar FilterMatchMode = {\n STARTS_WITH: 'startsWith',\n CONTAINS: 'contains',\n NOT_CONTAINS: 'notContains',\n ENDS_WITH: 'endsWith',\n EQUALS: 'equals',\n NOT_EQUALS: 'notEquals',\n IN: 'in',\n LESS_THAN: 'lt',\n LESS_THAN_OR_EQUAL_TO: 'lte',\n GREATER_THAN: 'gt',\n GREATER_THAN_OR_EQUAL_TO: 'gte',\n BETWEEN: 'between',\n DATE_IS: 'dateIs',\n DATE_IS_NOT: 'dateIsNot',\n DATE_BEFORE: 'dateBefore',\n DATE_AFTER: 'dateAfter'\n};\n\nvar FilterOperator = {\n AND: 'and',\n OR: 'or'\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 _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 _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 FilterService = {\n filter: function filter(value, fields, filterValue, filterMatchMode, filterLocale) {\n var filteredItems = [];\n if (!value) {\n return filteredItems;\n }\n var _iterator = _createForOfIteratorHelper(value),\n _step;\n try {\n for (_iterator.s(); !(_step = _iterator.n()).done;) {\n var item = _step.value;\n if (typeof item === 'string') {\n if (this.filters[filterMatchMode](item, filterValue, filterLocale)) {\n filteredItems.push(item);\n continue;\n }\n } else {\n var _iterator2 = _createForOfIteratorHelper(fields),\n _step2;\n try {\n for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {\n var field = _step2.value;\n var fieldValue = resolveFieldData(item, field);\n if (this.filters[filterMatchMode](fieldValue, filterValue, filterLocale)) {\n filteredItems.push(item);\n break;\n }\n }\n } catch (err) {\n _iterator2.e(err);\n } finally {\n _iterator2.f();\n }\n }\n }\n } catch (err) {\n _iterator.e(err);\n } finally {\n _iterator.f();\n }\n return filteredItems;\n },\n filters: {\n startsWith: function startsWith(value, filter, filterLocale) {\n if (filter === undefined || filter === null || filter === '') {\n return true;\n }\n if (value === undefined || value === null) {\n return false;\n }\n var filterValue = removeAccents(filter.toString()).toLocaleLowerCase(filterLocale);\n var stringValue = removeAccents(value.toString()).toLocaleLowerCase(filterLocale);\n return stringValue.slice(0, filterValue.length) === filterValue;\n },\n contains: function contains(value, filter, filterLocale) {\n if (filter === undefined || filter === null || filter === '') {\n return true;\n }\n if (value === undefined || value === null) {\n return false;\n }\n var filterValue = removeAccents(filter.toString()).toLocaleLowerCase(filterLocale);\n var stringValue = removeAccents(value.toString()).toLocaleLowerCase(filterLocale);\n return stringValue.indexOf(filterValue) !== -1;\n },\n notContains: function notContains(value, filter, filterLocale) {\n if (filter === undefined || filter === null || filter === '') {\n return true;\n }\n if (value === undefined || value === null) {\n return false;\n }\n var filterValue = removeAccents(filter.toString()).toLocaleLowerCase(filterLocale);\n var stringValue = removeAccents(value.toString()).toLocaleLowerCase(filterLocale);\n return stringValue.indexOf(filterValue) === -1;\n },\n endsWith: function endsWith(value, filter, filterLocale) {\n if (filter === undefined || filter === null || filter === '') {\n return true;\n }\n if (value === undefined || value === null) {\n return false;\n }\n var filterValue = removeAccents(filter.toString()).toLocaleLowerCase(filterLocale);\n var stringValue = removeAccents(value.toString()).toLocaleLowerCase(filterLocale);\n return stringValue.indexOf(filterValue, stringValue.length - filterValue.length) !== -1;\n },\n equals: function equals(value, filter, filterLocale) {\n if (filter === undefined || filter === null || filter === '') {\n return true;\n }\n if (value === undefined || value === null) {\n return false;\n }\n if (value.getTime && filter.getTime) return value.getTime() === filter.getTime();else return removeAccents(value.toString()).toLocaleLowerCase(filterLocale) == removeAccents(filter.toString()).toLocaleLowerCase(filterLocale);\n },\n notEquals: function notEquals(value, filter, filterLocale) {\n if (filter === undefined || filter === null || filter === '') {\n return false;\n }\n if (value === undefined || value === null) {\n return true;\n }\n if (value.getTime && filter.getTime) return value.getTime() !== filter.getTime();else return removeAccents(value.toString()).toLocaleLowerCase(filterLocale) != removeAccents(filter.toString()).toLocaleLowerCase(filterLocale);\n },\n \"in\": function _in(value, filter) {\n if (filter === undefined || filter === null || filter.length === 0) {\n return true;\n }\n for (var i = 0; i < filter.length; i++) {\n if (equals(value, filter[i])) {\n return true;\n }\n }\n return false;\n },\n between: function between(value, filter) {\n if (filter == null || filter[0] == null || filter[1] == null) {\n return true;\n }\n if (value === undefined || value === null) {\n return false;\n }\n if (value.getTime) return filter[0].getTime() <= value.getTime() && value.getTime() <= filter[1].getTime();else return filter[0] <= value && value <= filter[1];\n },\n lt: function lt(value, filter) {\n if (filter === undefined || filter === null) {\n return true;\n }\n if (value === undefined || value === null) {\n return false;\n }\n if (value.getTime && filter.getTime) return value.getTime() < filter.getTime();else return value < filter;\n },\n lte: function lte(value, filter) {\n if (filter === undefined || filter === null) {\n return true;\n }\n if (value === undefined || value === null) {\n return false;\n }\n if (value.getTime && filter.getTime) return value.getTime() <= filter.getTime();else return value <= filter;\n },\n gt: function gt(value, filter) {\n if (filter === undefined || filter === null) {\n return true;\n }\n if (value === undefined || value === null) {\n return false;\n }\n if (value.getTime && filter.getTime) return value.getTime() > filter.getTime();else return value > filter;\n },\n gte: function gte(value, filter) {\n if (filter === undefined || filter === null) {\n return true;\n }\n if (value === undefined || value === null) {\n return false;\n }\n if (value.getTime && filter.getTime) return value.getTime() >= filter.getTime();else return value >= filter;\n },\n dateIs: function dateIs(value, filter) {\n if (filter === undefined || filter === null) {\n return true;\n }\n if (value === undefined || value === null) {\n return false;\n }\n return value.toDateString() === filter.toDateString();\n },\n dateIsNot: function dateIsNot(value, filter) {\n if (filter === undefined || filter === null) {\n return true;\n }\n if (value === undefined || value === null) {\n return false;\n }\n return value.toDateString() !== filter.toDateString();\n },\n dateBefore: function dateBefore(value, filter) {\n if (filter === undefined || filter === null) {\n return true;\n }\n if (value === undefined || value === null) {\n return false;\n }\n return value.getTime() < filter.getTime();\n },\n dateAfter: function dateAfter(value, filter) {\n if (filter === undefined || filter === null) {\n return true;\n }\n if (value === undefined || value === null) {\n return false;\n }\n return value.getTime() > filter.getTime();\n }\n },\n register: function register(rule, fn) {\n this.filters[rule] = fn;\n }\n};\n\nvar PrimeIcons = {\n ALIGN_CENTER: 'pi pi-align-center',\n ALIGN_JUSTIFY: 'pi pi-align-justify',\n ALIGN_LEFT: 'pi pi-align-left',\n ALIGN_RIGHT: 'pi pi-align-right',\n AMAZON: 'pi pi-amazon',\n ANDROID: 'pi pi-android',\n ANGLE_DOUBLE_DOWN: 'pi pi-angle-double-down',\n ANGLE_DOUBLE_LEFT: 'pi pi-angle-double-left',\n ANGLE_DOUBLE_RIGHT: 'pi pi-angle-double-right',\n ANGLE_DOUBLE_UP: 'pi pi-angle-double-up',\n ANGLE_DOWN: 'pi pi-angle-down',\n ANGLE_LEFT: 'pi pi-angle-left',\n ANGLE_RIGHT: 'pi pi-angle-right',\n ANGLE_UP: 'pi pi-angle-up',\n APPLE: 'pi pi-apple',\n ARROW_CIRCLE_DOWN: 'pi pi-arrow-circle-down',\n ARROW_CIRCLE_LEFT: 'pi pi-arrow-circle-left',\n ARROW_CIRCLE_RIGHT: 'pi pi-arrow-circle-right',\n ARROW_CIRCLE_UP: 'pi pi-arrow-circle-up',\n ARROW_DOWN: 'pi pi-arrow-down',\n ARROW_DOWN_LEFT: 'pi pi-arrow-down-left',\n ARROW_DOWN_RIGHT: 'pi pi-arrow-down-right',\n ARROW_LEFT: 'pi pi-arrow-left',\n ARROW_RIGHT: 'pi pi-arrow-right',\n ARROW_RIGHT_ARROW_LEFT: 'pi pi-arrow-right-arrow-left',\n ARROW_UP: 'pi pi-arrow-up',\n ARROW_UP_LEFT: 'pi pi-arrow-up-left',\n ARROW_UP_RIGHT: 'pi pi-arrow-up-right',\n ARROW_H: 'pi pi-arrows-h',\n ARROW_V: 'pi pi-arrows-v',\n ARROW_A: 'pi pi-arrows-alt',\n AT: 'pi pi-at',\n BACKWARD: 'pi pi-backward',\n BAN: 'pi pi-ban',\n BARS: 'pi pi-bars',\n BELL: 'pi pi-bell',\n BITCOIN: 'pi pi-bitcoin',\n BOLT: 'pi pi-bolt',\n BOOK: 'pi pi-book',\n BOOKMARK: 'pi pi-bookmark',\n BOOKMARK_FILL: 'pi pi-bookmark-fill',\n BOX: 'pi pi-box',\n BRIEFCASE: 'pi pi-briefcase',\n BUILDING: 'pi pi-building',\n CALENDAR: 'pi pi-calendar',\n CALENDAR_MINUS: 'pi pi-calendar-minus',\n CALENDAR_PLUS: 'pi pi-calendar-plus',\n CALENDAR_TIMES: 'pi pi-calendar-times',\n CALCULATOR: 'pi pi-calculator',\n CAMERA: 'pi pi-camera',\n CAR: 'pi pi-car',\n CARET_DOWN: 'pi pi-caret-down',\n CARET_LEFT: 'pi pi-caret-left',\n CARET_RIGHT: 'pi pi-caret-right',\n CARET_UP: 'pi pi-caret-up',\n CART_PLUS: 'pi pi-cart-plus',\n CHART_BAR: 'pi pi-chart-bar',\n CHART_LINE: 'pi pi-chart-line',\n CHART_PIE: 'pi pi-chart-pie',\n CHECK: 'pi pi-check',\n CHECK_CIRCLE: 'pi pi-check-circle',\n CHECK_SQUARE: 'pi pi-check-square',\n CHEVRON_CIRCLE_DOWN: 'pi pi-chevron-circle-down',\n CHEVRON_CIRCLE_LEFT: 'pi pi-chevron-circle-left',\n CHEVRON_CIRCLE_RIGHT: 'pi pi-chevron-circle-right',\n CHEVRON_CIRCLE_UP: 'pi pi-chevron-circle-up',\n CHEVRON_DOWN: 'pi pi-chevron-down',\n CHEVRON_LEFT: 'pi pi-chevron-left',\n CHEVRON_RIGHT: 'pi pi-chevron-right',\n CHEVRON_UP: 'pi pi-chevron-up',\n CIRCLE: 'pi pi-circle',\n CIRCLE_FILL: 'pi pi-circle-fill',\n CLOCK: 'pi pi-clock',\n CLONE: 'pi pi-clone',\n CLOUD: 'pi pi-cloud',\n CLOUD_DOWNLOAD: 'pi pi-cloud-download',\n CLOUD_UPLOAD: 'pi pi-cloud-upload',\n CODE: 'pi pi-code',\n COG: 'pi pi-cog',\n COMMENT: 'pi pi-comment',\n COMMENTS: 'pi pi-comments',\n COMPASS: 'pi pi-compass',\n COPY: 'pi pi-copy',\n CREDIT_CARD: 'pi pi-credit-card',\n DATABASE: 'pi pi-database',\n DELETELEFT: 'pi pi-delete-left',\n DESKTOP: 'pi pi-desktop',\n DIRECTIONS: 'pi pi-directions',\n DIRECTIONS_ALT: 'pi pi-directions-alt',\n DISCORD: 'pi pi-discord',\n DOLLAR: 'pi pi-dollar',\n DOWNLOAD: 'pi pi-download',\n EJECT: 'pi pi-eject',\n ELLIPSIS_H: 'pi pi-ellipsis-h',\n ELLIPSIS_V: 'pi pi-ellipsis-v',\n ENVELOPE: 'pi pi-envelope',\n ERASER: 'pi pi-eraser',\n EURO: 'pi pi-euro',\n EXCLAMATION_CIRCLE: 'pi pi-exclamation-circle',\n EXCLAMATION_TRIANGLE: 'pi pi-exclamation-triangle',\n EXTERNAL_LINK: 'pi pi-external-link',\n EYE: 'pi pi-eye',\n EYE_SLASH: 'pi pi-eye-slash',\n FACEBOOK: 'pi pi-facebook',\n FAST_BACKWARD: 'pi pi-fast-backward',\n FAST_FORWARD: 'pi pi-fast-forward',\n FILE: 'pi pi-file',\n FILE_EDIT: 'pi pi-file-edit',\n FILE_EXCEL: 'pi pi-file-excel',\n FILE_EXPORT: 'pi pi-file-export',\n FILE_IMPORT: 'pi pi-file-import',\n FILE_PDF: 'pi pi-file-pdf',\n FILE_WORD: 'pi pi-file-word',\n FILTER: 'pi pi-filter',\n FILTER_FILL: 'pi pi-filter-fill',\n FILTER_SLASH: 'pi pi-filter-slash',\n FLAG: 'pi pi-flag',\n FLAG_FILL: 'pi pi-flag-fill',\n FOLDER: 'pi pi-folder',\n FOLDER_OPEN: 'pi pi-folder-open',\n FORWARD: 'pi pi-forward',\n GIFT: 'pi pi-gift',\n GITHUB: 'pi pi-github',\n GLOBE: 'pi pi-globe',\n GOOGLE: 'pi pi-google',\n HASHTAG: 'pi pi-hashtag',\n HEART: 'pi pi-heart',\n HEART_FILL: 'pi pi-heart-fill',\n HISTORY: 'pi pi-history',\n HOURGLASS: 'pi pi-hourglass',\n HOME: 'pi pi-home',\n ID_CARD: 'pi pi-id-card',\n IMAGE: 'pi pi-image',\n IMAGES: 'pi pi-images',\n INBOX: 'pi pi-inbox',\n INFO: 'pi pi-info',\n INFO_CIRCLE: 'pi pi-info-circle',\n INSTAGRAM: 'pi pi-instagram',\n KEY: 'pi pi-key',\n LANGUAGE: 'pi pi-language',\n LINK: 'pi pi-link',\n LINKEDIN: 'pi pi-linkedin',\n LIST: 'pi pi-list',\n LOCK: 'pi pi-lock',\n LOCK_OPEN: 'pi pi-lock-open',\n MAP: 'pi pi-map',\n MAP_MARKER: 'pi pi-map-marker',\n MEGAPHONE: 'pi pi-megaphone',\n MICREPHONE: 'pi pi-microphone',\n MICROSOFT: 'pi pi-microsoft',\n MINUS: 'pi pi-minus',\n MINUS_CIRCLE: 'pi pi-minus-circle',\n MOBILE: 'pi pi-mobile',\n MONEY_BILL: 'pi pi-money-bill',\n MOON: 'pi pi-moon',\n PALETTE: 'pi pi-palette',\n PAPERCLIP: 'pi pi-paperclip',\n PAUSE: 'pi pi-pause',\n PAYPAL: 'pi pi-paypal',\n PENCIL: 'pi pi-pencil',\n PERCENTAGE: 'pi pi-percentage',\n PHONE: 'pi pi-phone',\n PLAY: 'pi pi-play',\n PLUS: 'pi pi-plus',\n PLUS_CIRCLE: 'pi pi-plus-circle',\n POUND: 'pi pi-pound',\n POWER_OFF: 'pi pi-power-off',\n PRIME: 'pi pi-prime',\n PRINT: 'pi pi-print',\n QRCODE: 'pi pi-qrcode',\n QUESTION: 'pi pi-question',\n QUESTION_CIRCLE: 'pi pi-question-circle',\n REDDIT: 'pi pi-reddit',\n REFRESH: 'pi pi-refresh',\n REPLAY: 'pi pi-replay',\n REPLY: 'pi pi-reply',\n SAVE: 'pi pi-save',\n SEARCH: 'pi pi-search',\n SEARCH_MINUS: 'pi pi-search-minus',\n SEARCH_PLUS: 'pi pi-search-plus',\n SEND: 'pi pi-send',\n SERVER: 'pi pi-server',\n SHARE_ALT: 'pi pi-share-alt',\n SHIELD: 'pi pi-shield',\n SHOPPING_BAG: 'pi pi-shopping-bag',\n SHOPPING_CART: 'pi pi-shopping-cart',\n SIGN_IN: 'pi pi-sign-in',\n SIGN_OUT: 'pi pi-sign-out',\n SITEMAP: 'pi pi-sitemap',\n SLACK: 'pi pi-slack',\n SLIDERS_H: 'pi pi-sliders-h',\n SLIDERS_V: 'pi pi-sliders-v',\n SORT: 'pi pi-sort',\n SORT_ALPHA_DOWN: 'pi pi-sort-alpha-down',\n SORT_ALPHA_ALT_DOWN: 'pi pi-sort-alpha-down-alt',\n SORT_ALPHA_UP: 'pi pi-sort-alpha-up',\n SORT_ALPHA_ALT_UP: 'pi pi-sort-alpha-up-alt',\n SORT_ALT: 'pi pi-sort-alt',\n SORT_ALT_SLASH: 'pi pi-sort-alt-slash',\n SORT_AMOUNT_DOWN: 'pi pi-sort-amount-down',\n SORT_AMOUNT_DOWN_ALT: 'pi pi-sort-amount-down-alt',\n SORT_AMOUNT_UP: 'pi pi-sort-amount-up',\n SORT_AMOUNT_UP_ALT: 'pi pi-sort-amount-up-alt',\n SORT_DOWN: 'pi pi-sort-down',\n SORT_NUMERIC_DOWN: 'pi pi-sort-numeric-down',\n SORT_NUMERIC_ALT_DOWN: 'pi pi-sort-numeric-down-alt',\n SORT_NUMERIC_UP: 'pi pi-sort-numeric-up',\n SORT_NUMERIC_ALT_UP: 'pi pi-sort-numeric-up-alt',\n SORT_UP: 'pi pi-sort-up',\n SPINNER: 'pi pi-spinner',\n STAR: 'pi pi-star',\n STAR_FILL: 'pi pi-star-fill',\n STEP_BACKWARD: 'pi pi-step-backward',\n STEP_BACKWARD_ALT: 'pi pi-step-backward-alt',\n STEP_FORWARD: 'pi pi-step-forward',\n STEP_FORWARD_ALT: 'pi pi-step-forward-alt',\n STOP: 'pi pi-stop',\n STOPWATCH: 'pi pi-stopwatch',\n STOP_CIRCLE: 'pi pi-stop-circle',\n SUN: 'pi pi-sun',\n SYNC: 'pi pi-sync',\n TABLE: 'pi pi-table',\n TABLET: 'pi pi-tablet',\n TAG: 'pi pi-tag',\n TAGS: 'pi pi-tags',\n TELEGRAM: 'pi pi-telegram',\n TH_LARGE: 'pi pi-th-large',\n THUMBS_DOWN: 'pi pi-thumbs-down',\n THUMBS_DOWN_FILL: 'pi pi-thumbs-down-fill',\n THUMBS_UP: 'pi pi-thumbs-up',\n THUMBS_UP_FILL: 'pi pi-thumbs-up-fill',\n TICKET: 'pi pi-ticket',\n TIMES: 'pi pi-times',\n TIMES_CIRCLE: 'pi pi-times-circle',\n TRASH: 'pi pi-trash',\n TRUCK: 'pi pi-truck',\n TWITTER: 'pi pi-twitter',\n UNDO: 'pi pi-undo',\n UNLOCK: 'pi pi-unlock',\n UPLOAD: 'pi pi-upload',\n USER: 'pi pi-user',\n USER_EDIT: 'pi pi-user-edit',\n USER_MINUS: 'pi pi-user-minus',\n USER_PLUS: 'pi pi-user-plus',\n USERS: 'pi pi-users',\n VERIFIED: 'pi pi-verified',\n VIDEO: 'pi pi-video',\n VIMEO: 'pi pi-vimeo',\n VOLUME_DOWN: 'pi pi-volume-down',\n VOLUME_OFF: 'pi pi-volume-off',\n VOLUME_UP: 'pi pi-volume-up',\n WALLET: 'pi pi-wallet',\n WHATSAPP: 'pi pi-whatsapp',\n WIFI: 'pi pi-wifi',\n WINDOW_MAXIMIZE: 'pi pi-window-maximize',\n WINDOW_MINIMIZE: 'pi pi-window-minimize',\n WRENCH: 'pi pi-wrench',\n YOUTUBE: 'pi pi-youtube'\n};\n\nvar ToastSeverities = {\n INFO: 'info',\n WARN: 'warn',\n ERROR: 'error',\n SUCCESS: 'success'\n};\n\nexport { FilterMatchMode, FilterOperator, FilterService, PrimeIcons, ToastSeverities as ToastSeverity };\n//# sourceMappingURL=index.mjs.map\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 line-height: 1;\\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:not(:first-child) {\\n padding-left: calc((\").concat(dt('form.field.padding.x'), \" * 2) + \").concat(dt('icon.size'), \");\\n}\\n\\n.p-iconfield .p-inputtext:not(:last-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': instance.hasFluid\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 { isEmpty } from '@primeuix/utils/object';\nimport 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\": null\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 inject: {\n $pcFluid: {\n \"default\": null\n }\n },\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 hasFluid: function hasFluid() {\n return isEmpty(this.fluid) ? !!this.$pcFluid : this.fluid;\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 { focus, getFirstFocusableElement, isElement, findSingle } from '@primeuix/utils/dom';\nimport { resolveFieldData, isPrintableCharacter, isNotEmpty, equals, findLastIndex } from '@primeuix/utils/object';\nimport { FilterService } from '@primevue/core/api';\nimport { UniqueComponentId } from '@primevue/core/utils';\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, {\n unstyled: _ctx.unstyled,\n pt: _ctx.ptm('pcFilterContainer')\n }, {\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 }, 8, [\"unstyled\", \"pt\"]), 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","\n \n
Warning: Missing Node Types \n
\n When loading the graph, the following node types were not found:\n
\n
\n \n \n {{ slotProps.option.label }} \n {{\n slotProps.option.hint\n }} \n \n
\n \n \n
\n Nodes that have failed to load will show as red on the graph.\n
\n
\n \n\n\n\n\n\n\n","\n \n
Warning: Missing Models \n
\n When loading the graph, the following models were not found:\n
\n
\n \n \n
\n
\n {{\n slotProps.option.label\n }} \n
\n
\n {{ slotProps.option.error }}\n
\n
\n
\n
\n
\n {{ slotProps.option.progress.toFixed(2) }}% \n
\n
\n \n
\n
\n \n
\n
\n
\n \n \n
\n \n\n\n\n\n\n\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 display: flex;\\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-content {\\n flex-grow: 1;\\n}\\n\\n.p-tablist-nav-button {\\n all: unset;\\n position: absolute !important;\\n flex-shrink: 0;\\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 flex-shrink: 0;\\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, Number],\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, Number],\n \"default\": undefined\n },\n as: {\n type: [String, Object],\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 z-index: 1;\\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.hasFluid\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, isEmpty } 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\": 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: 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 inject: {\n $pcFluid: {\n \"default\": null\n }\n },\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 hasFluid: function hasFluid() {\n return isEmpty(this.fluid) ? !!this.$pcFluid : this.fluid;\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 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': instance.hasFluid\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 { focus, isAndroid, getFirstFocusableElement, getLastFocusableElement, addStyle, relativePosition, getOuterWidth, absolutePosition, isTouchDevice, isVisible, getFocusableElements, findSingle } from '@primeuix/utils/dom';\nimport { resolveFieldData, isPrintableCharacter, isNotEmpty, equals, findLastIndex, isEmpty } from '@primeuix/utils/object';\nimport { ZIndex } from '@primeuix/utils/zindex';\nimport { FilterService } from '@primevue/core/api';\nimport { UniqueComponentId, ConnectedOverlayScrollHandler } from '@primevue/core/utils';\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\": 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 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 inject: {\n $pcFluid: {\n \"default\": null\n }\n },\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.autoFilterFocus && focus(this.$refs.focusInput);\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 isClearIconVisible: function isClearIconVisible() {\n return this.showClear && this.modelValue != null && isNotEmpty(this.options);\n },\n virtualScrollerDisabled: function virtualScrollerDisabled() {\n return !this.virtualScrollerOptions;\n },\n hasFluid: function hasFluid() {\n return isEmpty(this.fluid) ? !!this.$pcFluid : this.fluid;\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)), $options.isClearIconVisible ? 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, {\n unstyled: _ctx.unstyled,\n pt: _ctx.ptm('pcFilterContainer')\n }, {\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 }, 8, [\"unstyled\", \"pt\"]), 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","\n
\n \n\n\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","\n \n \n \n
\n \n\n\n\n\n","export function formatCamelCase(str: string): string {\n // Check if the string is camel case\n const isCamelCase = /^([A-Z][a-z]*)+$/.test(str)\n\n if (!isCamelCase) {\n return str // Return original string if not camel case\n }\n\n // Split the string into words, keeping acronyms together\n const words = str.split(/(?=[A-Z][a-z])|\\d+/)\n\n // Process each word\n const processedWords = words.map((word) => {\n // If the word is all uppercase and longer than one character, it's likely an acronym\n if (word.length > 1 && word === word.toUpperCase()) {\n return word // Keep acronyms as is\n }\n // For other words, ensure the first letter is capitalized\n return word.charAt(0).toUpperCase() + word.slice(1)\n })\n\n // Join the words with spaces\n return processedWords.join(' ')\n}\n\nexport function appendJsonExt(path: string) {\n if (!path.toLowerCase().endsWith('.json')) {\n path += '.json'\n }\n return path\n}\n\nexport function trimJsonExt(path?: string) {\n return path?.replace(/\\.json$/, '')\n}\n\nexport function highlightQuery(text: string, query: string) {\n if (!query) return text\n const regex = new RegExp(`(${query})`, 'gi')\n return text.replace(regex, '$1 ')\n}\n\nexport function formatNumberWithSuffix(\n num: number,\n {\n precision = 1,\n roundToInt = false\n }: { precision?: number; roundToInt?: boolean } = {}\n): string {\n const suffixes = ['', 'k', 'm', 'b', 't']\n const absNum = Math.abs(num)\n\n if (absNum < 1000) {\n return roundToInt ? Math.round(num).toString() : num.toFixed(precision)\n }\n\n const exp = Math.min(Math.floor(Math.log10(absNum) / 3), suffixes.length - 1)\n const formattedNum = (num / Math.pow(1000, exp)).toFixed(precision)\n\n return `${formattedNum}${suffixes[exp]}`\n}\n","\n \n
\n
{{ formatCamelCase(group.label) }} \n
\n
\n \n \n \n {{ setting.name }}\n \n
\n
\n \n
\n
\n
\n \n\n\n\n\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': '\n\n\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'\n\nexport function buildTree(\n items: T[],\n key: string | ((item: T) => string[])\n): TreeNode {\n const root: TreeNode = {\n key: 'root',\n label: 'root',\n children: []\n }\n\n const map: Record = {\n root: root\n }\n\n for (const item of items) {\n const keys = typeof key === 'string' ? item[key] : key(item)\n let parent = root\n for (let i = 0; i < keys.length; i++) {\n const k = keys[i]\n // 'a/b/c/' represents an empty folder 'c' in folder 'b' in folder 'a'\n // 'a/b/c/' is split into ['a', 'b', 'c', '']\n if (k === '' && i === keys.length - 1) break\n\n const id = parent.key + '/' + k\n if (!map[id]) {\n const node: TreeNode = {\n key: id,\n label: k,\n leaf: false,\n children: []\n }\n map[id] = node\n parent.children.push(node)\n }\n parent = map[id]\n }\n parent.leaf = keys[keys.length - 1] !== ''\n parent.data = item\n }\n return root\n}\n\nexport function flattenTree(tree: TreeNode): T[] {\n const result: T[] = []\n const stack: TreeNode[] = [tree]\n while (stack.length) {\n const node = stack.pop()!\n if (node.leaf && node.data) result.push(node.data)\n stack.push(...(node.children || []))\n }\n return result\n}\n\nexport function sortedTree(node: TreeNode): TreeNode {\n // Create a new node with the same label and data\n const newNode: TreeNode = {\n ...node\n }\n\n if (node.children) {\n // Sort the children of the current node\n const sortedChildren = [...node.children].sort((a, b) =>\n a.label.localeCompare(b.label)\n )\n // Recursively sort the children and add them to the new node\n newNode.children = []\n for (const child of sortedChildren) {\n newNode.children.push(sortedTree(child))\n }\n }\n\n return newNode\n}\n\nexport const findNodeByKey = (root: TreeNode, key: string): TreeNode | null => {\n if (root.key === key) {\n return root\n }\n if (!root.children) {\n return null\n }\n for (const child of root.children) {\n const result = findNodeByKey(child, key)\n if (result) {\n return result\n }\n }\n return null\n}\n","import { defineStore } from 'pinia'\nimport { ref } from 'vue'\nimport { api } from '@/scripts/api'\nimport type { SystemStats } from '@/types/apiTypes'\n\nexport const useSystemStatsStore = defineStore('systemStats', () => {\n const systemStats = ref(null)\n const isLoading = ref(false)\n const error = ref(null)\n\n async function fetchSystemStats() {\n isLoading.value = true\n error.value = null\n\n try {\n systemStats.value = await api.getSystemStats()\n } catch (err) {\n error.value =\n err instanceof Error\n ? err.message\n : 'An error occurred while fetching system stats'\n console.error('Error fetching system stats:', err)\n } finally {\n isLoading.value = false\n }\n }\n\n return {\n systemStats,\n isLoading,\n error,\n fetchSystemStats\n }\n})\n","import BaseIcon from '@primevue/icons/baseicon';\nimport { openBlock, createElementBlock, mergeProps, createElementVNode } from 'vue';\n\nvar script = {\n name: 'ChevronLeftIcon',\n \"extends\": BaseIcon\n};\n\nvar _hoisted_1 = /*#__PURE__*/createElementVNode(\"path\", {\n d: \"M9.61296 13C9.50997 13.0005 9.40792 12.9804 9.3128 12.9409C9.21767 12.9014 9.13139 12.8433 9.05902 12.7701L3.83313 7.54416C3.68634 7.39718 3.60388 7.19795 3.60388 6.99022C3.60388 6.78249 3.68634 6.58325 3.83313 6.43628L9.05902 1.21039C9.20762 1.07192 9.40416 0.996539 9.60724 1.00012C9.81032 1.00371 10.0041 1.08597 10.1477 1.22959C10.2913 1.37322 10.3736 1.56698 10.3772 1.77005C10.3808 1.97313 10.3054 2.16968 10.1669 2.31827L5.49496 6.99022L10.1669 11.6622C10.3137 11.8091 10.3962 12.0084 10.3962 12.2161C10.3962 12.4238 10.3137 12.6231 10.1669 12.7701C10.0945 12.8433 10.0083 12.9014 9.91313 12.9409C9.81801 12.9804 9.71596 13.0005 9.61296 13Z\",\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: 'ChevronRightIcon',\n \"extends\": BaseIcon\n};\n\nvar _hoisted_1 = /*#__PURE__*/createElementVNode(\"path\", {\n d: \"M4.38708 13C4.28408 13.0005 4.18203 12.9804 4.08691 12.9409C3.99178 12.9014 3.9055 12.8433 3.83313 12.7701C3.68634 12.6231 3.60388 12.4238 3.60388 12.2161C3.60388 12.0084 3.68634 11.8091 3.83313 11.6622L8.50507 6.99022L3.83313 2.31827C3.69467 2.16968 3.61928 1.97313 3.62287 1.77005C3.62645 1.56698 3.70872 1.37322 3.85234 1.22959C3.99596 1.08597 4.18972 1.00371 4.3928 1.00012C4.59588 0.996539 4.79242 1.07192 4.94102 1.21039L10.1669 6.43628C10.3137 6.58325 10.3962 6.78249 10.3962 6.99022C10.3962 7.19795 10.3137 7.39718 10.1669 7.54416L4.94102 12.7701C4.86865 12.8433 4.78237 12.9014 4.68724 12.9409C4.59212 12.9804 4.49007 13.0005 4.38708 13Z\",\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-tabview-tablist-container {\\n position: relative;\\n}\\n\\n.p-tabview-scrollable > .p-tabview-tablist-container {\\n overflow: hidden;\\n}\\n\\n.p-tabview-tablist-scroll-container {\\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-tabview-tablist-scroll-container::-webkit-scrollbar {\\n display: none;\\n}\\n\\n.p-tabview-tablist {\\n display: flex;\\n margin: 0;\\n padding: 0;\\n list-style-type: none;\\n flex: 1 1 auto;\\n background: \".concat(dt('tabview.tab.list.background'), \";\\n border: 1px solid \").concat(dt('tabview.tab.list.border.color'), \";\\n border-width: 0 0 1px 0;\\n position: relative;\\n}\\n\\n.p-tabview-tab-header {\\n cursor: pointer;\\n user-select: none;\\n display: flex;\\n align-items: center;\\n text-decoration: none;\\n position: relative;\\n overflow: hidden;\\n border-style: solid;\\n border-width: 0 0 1px 0;\\n border-color: transparent transparent \").concat(dt('tabview.tab.border.color'), \" transparent;\\n color: \").concat(dt('tabview.tab.color'), \";\\n padding: 1rem 1.125rem;\\n font-weight: 600;\\n border-top-right-radius: \").concat(dt('border.radius.md'), \";\\n border-top-left-radius: \").concat(dt('border.radius.md'), \";\\n transition: color \").concat(dt('tabview.transition.duration'), \", outline-color \").concat(dt('tabview.transition.duration'), \";\\n margin: 0 0 -1px 0;\\n outline-color: transparent;\\n}\\n\\n.p-tabview-tablist-item:not(.p-disabled) .p-tabview-tab-header:focus-visible {\\n outline: \").concat(dt('focus.ring.width'), \" \").concat(dt('focus.ring.style'), \" \").concat(dt('focus.ring.color'), \";\\n outline-offset: -1px;\\n}\\n\\n.p-tabview-tablist-item:not(.p-highlight):not(.p-disabled):hover > .p-tabview-tab-header {\\n color: \").concat(dt('tabview.tab.hover.color'), \";\\n}\\n\\n.p-tabview-tablist-item.p-highlight > .p-tabview-tab-header {\\n color: \").concat(dt('tabview.tab.active.color'), \";\\n}\\n\\n.p-tabview-tab-title {\\n line-height: 1;\\n white-space: nowrap;\\n}\\n\\n.p-tabview-next-button,\\n.p-tabview-prev-button {\\n position: absolute;\\n top: 0;\\n margin: 0;\\n padding: 0;\\n z-index: 2;\\n height: 100%;\\n display: flex;\\n align-items: center;\\n justify-content: center;\\n background: \").concat(dt('tabview.nav.button.background'), \";\\n color: \").concat(dt('tabview.nav.button.color'), \";\\n width: 2.5rem;\\n border-radius: 0;\\n outline-color: transparent;\\n transition: color \").concat(dt('tabview.transition.duration'), \", outline-color \").concat(dt('tabview.transition.duration'), \";\\n box-shadow: \").concat(dt('tabview.nav.button.shadow'), \";\\n border: none;\\n cursor: pointer;\\n user-select: none;\\n}\\n\\n.p-tabview-next-button:focus-visible,\\n.p-tabview-prev-button:focus-visible {\\n outline: \").concat(dt('focus.ring.width'), \" \").concat(dt('focus.ring.style'), \" \").concat(dt('focus.ring.color'), \";\\n outline-offset: \").concat(dt('focus.ring.offset'), \";\\n}\\n\\n.p-tabview-next-button:hover,\\n.p-tabview-prev-button:hover {\\n color: \").concat(dt('tabview.nav.button.hover.color'), \";\\n}\\n\\n.p-tabview-prev-button {\\n left: 0;\\n}\\n\\n.p-tabview-next-button {\\n right: 0;\\n}\\n\\n.p-tabview-panels {\\n background: \").concat(dt('tabview.tab.panel.background'), \";\\n color: \").concat(dt('tabview.tab.panel.color'), \";\\n padding: 0.875rem 1.125rem 1.125rem 1.125rem;\\n}\\n\\n.p-tabview-ink-bar {\\n z-index: 1;\\n display: block;\\n position: absolute;\\n bottom: -1px;\\n height: 1px;\\n background: \").concat(dt('tabview.tab.active.border.color'), \";\\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-tabview p-component', {\n 'p-tabview-scrollable': props.scrollable\n }];\n },\n navContainer: 'p-tabview-tablist-container',\n prevButton: 'p-tabview-prev-button',\n navContent: 'p-tabview-tablist-scroll-container',\n nav: 'p-tabview-tablist',\n tab: {\n header: function header(_ref3) {\n var instance = _ref3.instance,\n tab = _ref3.tab,\n index = _ref3.index;\n return ['p-tabview-tablist-item', instance.getTabProp(tab, 'headerClass'), {\n 'p-tabview-tablist-item-active': instance.d_activeIndex === index,\n 'p-disabled': instance.getTabProp(tab, 'disabled')\n }];\n },\n headerAction: 'p-tabview-tab-header',\n headerTitle: 'p-tabview-tab-title',\n content: function content(_ref4) {\n var instance = _ref4.instance,\n tab = _ref4.tab;\n return ['p-tabview-panel', instance.getTabProp(tab, 'contentClass')];\n }\n },\n inkbar: 'p-tabview-ink-bar',\n nextButton: 'p-tabview-next-button',\n panelContainer: 'p-tabview-panels'\n};\nvar TabViewStyle = BaseStyle.extend({\n name: 'tabview',\n theme: theme,\n classes: classes\n});\n\nexport { TabViewStyle as default };\n//# sourceMappingURL=index.mjs.map\n","import { UniqueComponentId } from '@primevue/core/utils';\nimport { getWidth, getAttribute, findSingle, focus, getOffset } from '@primeuix/utils/dom';\nimport ChevronLeftIcon from '@primevue/icons/chevronleft';\nimport ChevronRightIcon from '@primevue/icons/chevronright';\nimport Ripple from 'primevue/ripple';\nimport { mergeProps, resolveDirective, openBlock, createElementBlock, createElementVNode, withDirectives, renderSlot, createBlock, resolveDynamicComponent, createCommentVNode, Fragment, renderList, toDisplayString, vShow } from 'vue';\nimport BaseComponent from '@primevue/core/basecomponent';\nimport TabViewStyle from 'primevue/tabview/style';\n\nvar script$1 = {\n name: 'BaseTabView',\n \"extends\": BaseComponent,\n props: {\n activeIndex: {\n type: Number,\n \"default\": 0\n },\n lazy: {\n type: Boolean,\n \"default\": false\n },\n scrollable: {\n type: Boolean,\n \"default\": false\n },\n tabindex: {\n type: Number,\n \"default\": 0\n },\n selectOnFocus: {\n type: Boolean,\n \"default\": false\n },\n prevButtonProps: {\n type: null,\n \"default\": null\n },\n nextButtonProps: {\n type: null,\n \"default\": null\n },\n prevIcon: {\n type: String,\n \"default\": undefined\n },\n nextIcon: {\n type: String,\n \"default\": undefined\n }\n },\n style: TabViewStyle,\n provide: function provide() {\n return {\n $pcTabs: undefined,\n // Backwards compatible to prevent component from breaking\n $pcTabView: this,\n $parentInstance: this\n };\n }\n};\n\nvar script = {\n name: 'TabView',\n \"extends\": script$1,\n inheritAttrs: false,\n emits: ['update:activeIndex', 'tab-change', 'tab-click'],\n data: function data() {\n return {\n id: this.$attrs.id,\n d_activeIndex: this.activeIndex,\n isPrevButtonDisabled: true,\n isNextButtonDisabled: false\n };\n },\n watch: {\n '$attrs.id': function $attrsId(newValue) {\n this.id = newValue || UniqueComponentId();\n },\n activeIndex: function activeIndex(newValue) {\n this.d_activeIndex = newValue;\n this.scrollInView({\n index: newValue\n });\n }\n },\n mounted: function mounted() {\n console.warn('Deprecated since v4. Use Tabs component instead.');\n this.id = this.id || UniqueComponentId();\n this.updateInkBar();\n this.scrollable && this.updateButtonState();\n },\n updated: function updated() {\n this.updateInkBar();\n this.scrollable && this.updateButtonState();\n },\n methods: {\n isTabPanel: function isTabPanel(child) {\n return child.type.name === 'TabPanel';\n },\n isTabActive: function isTabActive(index) {\n return this.d_activeIndex === index;\n },\n getTabProp: function getTabProp(tab, name) {\n return tab.props ? tab.props[name] : undefined;\n },\n getKey: function getKey(tab, index) {\n return this.getTabProp(tab, 'header') || index;\n },\n getTabHeaderActionId: function getTabHeaderActionId(index) {\n return \"\".concat(this.id, \"_\").concat(index, \"_header_action\");\n },\n getTabContentId: function getTabContentId(index) {\n return \"\".concat(this.id, \"_\").concat(index, \"_content\");\n },\n getTabPT: function getTabPT(tab, key, index) {\n var count = this.tabs.length;\n var tabMetaData = {\n props: tab.props,\n parent: {\n instance: this,\n props: this.$props,\n state: this.$data\n },\n context: {\n index: index,\n count: count,\n first: index === 0,\n last: index === count - 1,\n active: this.isTabActive(index)\n }\n };\n return mergeProps(this.ptm(\"tabpanel.\".concat(key), {\n tabpanel: tabMetaData\n }), this.ptm(\"tabpanel.\".concat(key), tabMetaData), this.ptmo(this.getTabProp(tab, 'pt'), key, tabMetaData));\n },\n onScroll: function onScroll(event) {\n this.scrollable && this.updateButtonState();\n event.preventDefault();\n },\n onPrevButtonClick: function onPrevButtonClick() {\n var content = this.$refs.content;\n var width = getWidth(content);\n var pos = content.scrollLeft - width;\n content.scrollLeft = pos <= 0 ? 0 : pos;\n },\n onNextButtonClick: function onNextButtonClick() {\n var content = this.$refs.content;\n var width = getWidth(content) - this.getVisibleButtonWidths();\n var pos = content.scrollLeft + width;\n var lastPos = content.scrollWidth - width;\n content.scrollLeft = pos >= lastPos ? lastPos : pos;\n },\n onTabClick: function onTabClick(event, tab, index) {\n this.changeActiveIndex(event, tab, index);\n this.$emit('tab-click', {\n originalEvent: event,\n index: index\n });\n },\n onTabKeyDown: function onTabKeyDown(event, tab, index) {\n switch (event.code) {\n case 'ArrowLeft':\n this.onTabArrowLeftKey(event);\n break;\n case 'ArrowRight':\n this.onTabArrowRightKey(event);\n break;\n case 'Home':\n this.onTabHomeKey(event);\n break;\n case 'End':\n this.onTabEndKey(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.onTabEnterKey(event, tab, index);\n break;\n }\n },\n onTabArrowRightKey: function onTabArrowRightKey(event) {\n var nextHeaderAction = this.findNextHeaderAction(event.target.parentElement);\n nextHeaderAction ? this.changeFocusedTab(event, nextHeaderAction) : this.onTabHomeKey(event);\n event.preventDefault();\n },\n onTabArrowLeftKey: function onTabArrowLeftKey(event) {\n var prevHeaderAction = this.findPrevHeaderAction(event.target.parentElement);\n prevHeaderAction ? this.changeFocusedTab(event, prevHeaderAction) : this.onTabEndKey(event);\n event.preventDefault();\n },\n onTabHomeKey: function onTabHomeKey(event) {\n var firstHeaderAction = this.findFirstHeaderAction();\n this.changeFocusedTab(event, firstHeaderAction);\n event.preventDefault();\n },\n onTabEndKey: function onTabEndKey(event) {\n var lastHeaderAction = this.findLastHeaderAction();\n this.changeFocusedTab(event, lastHeaderAction);\n event.preventDefault();\n },\n onPageDownKey: function onPageDownKey(event) {\n this.scrollInView({\n index: this.$refs.nav.children.length - 2\n });\n event.preventDefault();\n },\n onPageUpKey: function onPageUpKey(event) {\n this.scrollInView({\n index: 0\n });\n event.preventDefault();\n },\n onTabEnterKey: function onTabEnterKey(event, tab, index) {\n this.changeActiveIndex(event, tab, index);\n event.preventDefault();\n },\n findNextHeaderAction: function findNextHeaderAction(tabElement) {\n var selfCheck = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n var headerElement = selfCheck ? tabElement : tabElement.nextElementSibling;\n return headerElement ? getAttribute(headerElement, 'data-p-disabled') || getAttribute(headerElement, 'data-pc-section') === 'inkbar' ? this.findNextHeaderAction(headerElement) : findSingle(headerElement, '[data-pc-section=\"headeraction\"]') : null;\n },\n findPrevHeaderAction: function findPrevHeaderAction(tabElement) {\n var selfCheck = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n var headerElement = selfCheck ? tabElement : tabElement.previousElementSibling;\n return headerElement ? getAttribute(headerElement, 'data-p-disabled') || getAttribute(headerElement, 'data-pc-section') === 'inkbar' ? this.findPrevHeaderAction(headerElement) : findSingle(headerElement, '[data-pc-section=\"headeraction\"]') : null;\n },\n findFirstHeaderAction: function findFirstHeaderAction() {\n return this.findNextHeaderAction(this.$refs.nav.firstElementChild, true);\n },\n findLastHeaderAction: function findLastHeaderAction() {\n return this.findPrevHeaderAction(this.$refs.nav.lastElementChild, true);\n },\n changeActiveIndex: function changeActiveIndex(event, tab, index) {\n if (!this.getTabProp(tab, 'disabled') && this.d_activeIndex !== index) {\n this.d_activeIndex = index;\n this.$emit('update:activeIndex', index);\n this.$emit('tab-change', {\n originalEvent: event,\n index: index\n });\n this.scrollInView({\n index: index\n });\n }\n },\n changeFocusedTab: function changeFocusedTab(event, element) {\n if (element) {\n focus(element);\n this.scrollInView({\n element: element\n });\n if (this.selectOnFocus) {\n var index = parseInt(element.parentElement.dataset.pcIndex, 10);\n var tab = this.tabs[index];\n this.changeActiveIndex(event, tab, index);\n }\n }\n },\n scrollInView: function scrollInView(_ref) {\n var element = _ref.element,\n _ref$index = _ref.index,\n index = _ref$index === void 0 ? -1 : _ref$index;\n var currentElement = element || this.$refs.nav.children[index];\n if (currentElement) {\n currentElement.scrollIntoView && currentElement.scrollIntoView({\n block: 'nearest'\n });\n }\n },\n updateInkBar: function updateInkBar() {\n var tabHeader = this.$refs.nav.children[this.d_activeIndex];\n this.$refs.inkbar.style.width = getWidth(tabHeader) + 'px';\n this.$refs.inkbar.style.left = getOffset(tabHeader).left - getOffset(this.$refs.nav).left + 'px';\n },\n updateButtonState: function updateButtonState() {\n var content = this.$refs.content;\n var scrollLeft = content.scrollLeft,\n scrollWidth = content.scrollWidth;\n var width = getWidth(content);\n this.isPrevButtonDisabled = scrollLeft === 0;\n this.isNextButtonDisabled = parseInt(scrollLeft) === scrollWidth - width;\n },\n getVisibleButtonWidths: function getVisibleButtonWidths() {\n var _this$$refs = this.$refs,\n prevBtn = _this$$refs.prevBtn,\n nextBtn = _this$$refs.nextBtn;\n return [prevBtn, nextBtn].reduce(function (acc, el) {\n return el ? acc + getWidth(el) : acc;\n }, 0);\n }\n },\n computed: {\n tabs: function tabs() {\n var _this = this;\n return this.$slots[\"default\"]().reduce(function (tabs, child) {\n if (_this.isTabPanel(child)) {\n tabs.push(child);\n } else if (child.children && child.children instanceof Array) {\n child.children.forEach(function (nestedChild) {\n if (_this.isTabPanel(nestedChild)) {\n tabs.push(nestedChild);\n }\n });\n }\n return tabs;\n }, []);\n },\n prevButtonAriaLabel: function prevButtonAriaLabel() {\n return this.$primevue.config.locale.aria ? this.$primevue.config.locale.aria.previous : undefined;\n },\n nextButtonAriaLabel: function nextButtonAriaLabel() {\n return this.$primevue.config.locale.aria ? this.$primevue.config.locale.aria.next : undefined;\n }\n },\n directives: {\n ripple: Ripple\n },\n components: {\n ChevronLeftIcon: ChevronLeftIcon,\n ChevronRightIcon: ChevronRightIcon\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 = [\"tabindex\", \"aria-label\"];\nvar _hoisted_2 = [\"data-p-active\", \"data-p-disabled\", \"data-pc-index\"];\nvar _hoisted_3 = [\"id\", \"tabindex\", \"aria-disabled\", \"aria-selected\", \"aria-controls\", \"onClick\", \"onKeydown\"];\nvar _hoisted_4 = [\"tabindex\", \"aria-label\"];\nvar _hoisted_5 = [\"id\", \"aria-labelledby\", \"data-pc-index\", \"data-p-active\"];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n var _directive_ripple = resolveDirective(\"ripple\");\n return openBlock(), createElementBlock(\"div\", mergeProps({\n \"class\": _ctx.cx('root'),\n role: \"tablist\"\n }, _ctx.ptmi('root')), [createElementVNode(\"div\", mergeProps({\n \"class\": _ctx.cx('navContainer')\n }, _ctx.ptm('navContainer')), [_ctx.scrollable && !$data.isPrevButtonDisabled ? withDirectives((openBlock(), createElementBlock(\"button\", mergeProps({\n key: 0,\n ref: \"prevBtn\",\n type: \"button\",\n \"class\": _ctx.cx('prevButton'),\n tabindex: _ctx.tabindex,\n \"aria-label\": $options.prevButtonAriaLabel,\n onClick: _cache[0] || (_cache[0] = function () {\n return $options.onPrevButtonClick && $options.onPrevButtonClick.apply($options, arguments);\n })\n }, _objectSpread(_objectSpread({}, _ctx.prevButtonProps), _ctx.ptm('prevButton')), {\n \"data-pc-group-section\": \"navbutton\"\n }), [renderSlot(_ctx.$slots, \"previcon\", {}, function () {\n return [(openBlock(), createBlock(resolveDynamicComponent(_ctx.prevIcon ? 'span' : 'ChevronLeftIcon'), mergeProps({\n \"aria-hidden\": \"true\",\n \"class\": _ctx.prevIcon\n }, _ctx.ptm('prevIcon')), null, 16, [\"class\"]))];\n })], 16, _hoisted_1)), [[_directive_ripple]]) : createCommentVNode(\"\", true), createElementVNode(\"div\", mergeProps({\n ref: \"content\",\n \"class\": _ctx.cx('navContent'),\n onScroll: _cache[1] || (_cache[1] = function () {\n return $options.onScroll && $options.onScroll.apply($options, arguments);\n })\n }, _ctx.ptm('navContent')), [createElementVNode(\"ul\", mergeProps({\n ref: \"nav\",\n \"class\": _ctx.cx('nav')\n }, _ctx.ptm('nav')), [(openBlock(true), createElementBlock(Fragment, null, renderList($options.tabs, function (tab, index) {\n return openBlock(), createElementBlock(\"li\", mergeProps({\n key: $options.getKey(tab, index),\n style: $options.getTabProp(tab, 'headerStyle'),\n \"class\": _ctx.cx('tab.header', {\n tab: tab,\n index: index\n }),\n role: \"presentation\",\n ref_for: true\n }, _objectSpread(_objectSpread(_objectSpread({}, $options.getTabProp(tab, 'headerProps')), $options.getTabPT(tab, 'root', index)), $options.getTabPT(tab, 'header', index)), {\n \"data-pc-name\": \"tabpanel\",\n \"data-p-active\": $data.d_activeIndex === index,\n \"data-p-disabled\": $options.getTabProp(tab, 'disabled'),\n \"data-pc-index\": index\n }), [withDirectives((openBlock(), createElementBlock(\"a\", mergeProps({\n id: $options.getTabHeaderActionId(index),\n \"class\": _ctx.cx('tab.headerAction'),\n tabindex: $options.getTabProp(tab, 'disabled') || !$options.isTabActive(index) ? -1 : _ctx.tabindex,\n role: \"tab\",\n \"aria-disabled\": $options.getTabProp(tab, 'disabled'),\n \"aria-selected\": $options.isTabActive(index),\n \"aria-controls\": $options.getTabContentId(index),\n onClick: function onClick($event) {\n return $options.onTabClick($event, tab, index);\n },\n onKeydown: function onKeydown($event) {\n return $options.onTabKeyDown($event, tab, index);\n },\n ref_for: true\n }, _objectSpread(_objectSpread({}, $options.getTabProp(tab, 'headerActionProps')), $options.getTabPT(tab, 'headerAction', index))), [tab.props && tab.props.header ? (openBlock(), createElementBlock(\"span\", mergeProps({\n key: 0,\n \"class\": _ctx.cx('tab.headerTitle'),\n ref_for: true\n }, $options.getTabPT(tab, 'headerTitle', index)), toDisplayString(tab.props.header), 17)) : createCommentVNode(\"\", true), tab.children && tab.children.header ? (openBlock(), createBlock(resolveDynamicComponent(tab.children.header), {\n key: 1\n })) : createCommentVNode(\"\", true)], 16, _hoisted_3)), [[_directive_ripple]])], 16, _hoisted_2);\n }), 128)), createElementVNode(\"li\", mergeProps({\n ref: \"inkbar\",\n \"class\": _ctx.cx('inkbar'),\n role: \"presentation\",\n \"aria-hidden\": \"true\"\n }, _ctx.ptm('inkbar')), null, 16)], 16)], 16), _ctx.scrollable && !$data.isNextButtonDisabled ? withDirectives((openBlock(), createElementBlock(\"button\", mergeProps({\n key: 1,\n ref: \"nextBtn\",\n type: \"button\",\n \"class\": _ctx.cx('nextButton'),\n tabindex: _ctx.tabindex,\n \"aria-label\": $options.nextButtonAriaLabel,\n onClick: _cache[2] || (_cache[2] = function () {\n return $options.onNextButtonClick && $options.onNextButtonClick.apply($options, arguments);\n })\n }, _objectSpread(_objectSpread({}, _ctx.nextButtonProps), _ctx.ptm('nextButton')), {\n \"data-pc-group-section\": \"navbutton\"\n }), [renderSlot(_ctx.$slots, \"nexticon\", {}, function () {\n return [(openBlock(), createBlock(resolveDynamicComponent(_ctx.nextIcon ? 'span' : 'ChevronRightIcon'), mergeProps({\n \"aria-hidden\": \"true\",\n \"class\": _ctx.nextIcon\n }, _ctx.ptm('nextIcon')), null, 16, [\"class\"]))];\n })], 16, _hoisted_4)), [[_directive_ripple]]) : createCommentVNode(\"\", true)], 16), createElementVNode(\"div\", mergeProps({\n \"class\": _ctx.cx('panelContainer')\n }, _ctx.ptm('panelContainer')), [(openBlock(true), createElementBlock(Fragment, null, renderList($options.tabs, function (tab, index) {\n return openBlock(), createElementBlock(Fragment, {\n key: $options.getKey(tab, index)\n }, [(_ctx.lazy ? $options.isTabActive(index) : true) ? withDirectives((openBlock(), createElementBlock(\"div\", mergeProps({\n key: 0,\n id: $options.getTabContentId(index),\n style: $options.getTabProp(tab, 'contentStyle'),\n \"class\": _ctx.cx('tab.content', {\n tab: tab\n }),\n role: \"tabpanel\",\n \"aria-labelledby\": $options.getTabHeaderActionId(index),\n ref_for: true\n }, _objectSpread(_objectSpread(_objectSpread({}, $options.getTabProp(tab, 'contentProps')), $options.getTabPT(tab, 'root', index)), $options.getTabPT(tab, 'content', index)), {\n \"data-pc-name\": \"tabpanel\",\n \"data-pc-index\": index,\n \"data-p-active\": $data.d_activeIndex === index\n }), [(openBlock(), createBlock(resolveDynamicComponent(tab)))], 16, _hoisted_5)), [[vShow, _ctx.lazy ? true : $options.isTabActive(index)]]) : createCommentVNode(\"\", true)], 64);\n }), 128))], 16)], 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","\n \n
\n {{ $t(col.header) }}
\n {{ formatValue(props.device[col.field], col.field) }}
\n \n
\n \n\n\n","\n \n
\n
{{ $t('systemInfo') }} \n
\n
\n {{ $t(col.header) }}
\n {{ systemInfo[col.field] }}
\n \n
\n
\n\n
\n\n
\n
{{ $t('devices') }} \n 1\">\n \n \n \n \n \n \n
\n \n\n\n","\n \n
{{ $t('about') }} \n
\n\n
\n\n
\n
\n \n\n\n","\n \n \n
\n
\n
\n \n \n 0\">\n \n
\n \n \n \n (group)\n }\"\n />\n \n \n \n \n \n \n
\n
\n \n\n\n\n\n\n\n","\n \n
\n \n {{ $t('settings') }} \n \n \n \n\n\n","import BaseStyle from '@primevue/core/base/style';\n\nvar theme = function theme(_ref) {\n var dt = _ref.dt;\n return \"\\n.p-scrollpanel-content-container {\\n overflow: hidden;\\n width: 100%;\\n height: 100%;\\n position: relative;\\n z-index: 1;\\n float: left;\\n}\\n\\n.p-scrollpanel-content {\\n height: calc(100% + calc(2 * \".concat(dt('scrollpanel.bar.size'), \"));\\n width: calc(100% + calc(2 * \").concat(dt('scrollpanel.bar.size'), \"));\\n padding: 0 calc(2 * \").concat(dt('scrollpanel.bar.size'), \") calc(2 * \").concat(dt('scrollpanel.bar.size'), \") 0;\\n position: relative;\\n overflow: auto;\\n box-sizing: border-box;\\n scrollbar-width: none;\\n}\\n\\n.p-scrollpanel-content::-webkit-scrollbar {\\n display: none;\\n}\\n\\n.p-scrollpanel-bar {\\n position: relative;\\n border-radius: \").concat(dt('scrollpanel.bar.border.radius'), \";\\n z-index: 2;\\n cursor: pointer;\\n opacity: 0;\\n outline-color: transparent;\\n transition: outline-color \").concat(dt('scrollpanel.transition.duration'), \";\\n background: \").concat(dt('scrollpanel.bar.background'), \";\\n border: 0 none;\\n transition: outline-color \").concat(dt('scrollpanel.transition.duration'), \", opacity \").concat(dt('scrollpanel.transition.duration'), \";\\n}\\n\\n.p-scrollpanel-bar:focus-visible {\\n box-shadow: \").concat(dt('scrollpanel.bar.focus.ring.shadow'), \";\\n outline: \").concat(dt('scrollpanel.barfocus.ring.width'), \" \").concat(dt('scrollpanel.bar.focus.ring.style'), \" \").concat(dt('scrollpanel.bar.focus.ring.color'), \";\\n outline-offset: \").concat(dt('scrollpanel.barfocus.ring.offset'), \";\\n}\\n\\n.p-scrollpanel-bar-y {\\n width: \").concat(dt('scrollpanel.bar.size'), \";\\n top: 0;\\n}\\n\\n.p-scrollpanel-bar-x {\\n height: \").concat(dt('scrollpanel.bar.size'), \";\\n bottom: 0;\\n}\\n\\n.p-scrollpanel-hidden {\\n visibility: hidden;\\n}\\n\\n.p-scrollpanel:hover .p-scrollpanel-bar,\\n.p-scrollpanel:active .p-scrollpanel-bar {\\n opacity: 1;\\n}\\n\\n.p-scrollpanel-grabbed {\\n user-select: none;\\n}\\n\");\n};\nvar classes = {\n root: 'p-scrollpanel p-component',\n contentContainer: 'p-scrollpanel-content-container',\n content: 'p-scrollpanel-content',\n barX: 'p-scrollpanel-bar p-scrollpanel-bar-x',\n barY: 'p-scrollpanel-bar p-scrollpanel-bar-y'\n};\nvar ScrollPanelStyle = BaseStyle.extend({\n name: 'scrollpanel',\n theme: theme,\n classes: classes\n});\n\nexport { ScrollPanelStyle as default };\n//# sourceMappingURL=index.mjs.map\n","import { UniqueComponentId } from '@primevue/core/utils';\nimport { getHeight, addClass, removeClass } from '@primeuix/utils/dom';\nimport BaseComponent from '@primevue/core/basecomponent';\nimport ScrollPanelStyle from 'primevue/scrollpanel/style';\nimport { openBlock, createElementBlock, mergeProps, createElementVNode, renderSlot } from 'vue';\n\nvar script$1 = {\n name: 'BaseScrollPanel',\n \"extends\": BaseComponent,\n props: {\n step: {\n type: Number,\n \"default\": 5\n }\n },\n style: ScrollPanelStyle,\n provide: function provide() {\n return {\n $pcScrollPanel: this,\n $parentInstance: this\n };\n }\n};\n\nvar script = {\n name: 'ScrollPanel',\n \"extends\": script$1,\n inheritAttrs: false,\n initialized: false,\n documentResizeListener: null,\n documentMouseMoveListener: null,\n documentMouseUpListener: null,\n frame: null,\n scrollXRatio: null,\n scrollYRatio: null,\n isXBarClicked: false,\n isYBarClicked: false,\n lastPageX: null,\n lastPageY: null,\n timer: null,\n outsideClickListener: null,\n data: function data() {\n return {\n id: this.$attrs.id,\n orientation: 'vertical',\n lastScrollTop: 0,\n lastScrollLeft: 0\n };\n },\n watch: {\n '$attrs.id': function $attrsId(newValue) {\n this.id = newValue || UniqueComponentId();\n }\n },\n mounted: function mounted() {\n this.id = this.id || UniqueComponentId();\n if (this.$el.offsetParent) {\n this.initialize();\n }\n },\n updated: function updated() {\n if (!this.initialized && this.$el.offsetParent) {\n this.initialize();\n }\n },\n beforeUnmount: function beforeUnmount() {\n this.unbindDocumentResizeListener();\n if (this.frame) {\n window.cancelAnimationFrame(this.frame);\n }\n },\n methods: {\n initialize: function initialize() {\n this.moveBar();\n this.bindDocumentResizeListener();\n this.calculateContainerHeight();\n },\n calculateContainerHeight: function calculateContainerHeight() {\n var containerStyles = getComputedStyle(this.$el),\n xBarStyles = getComputedStyle(this.$refs.xBar),\n pureContainerHeight = getHeight(this.$el) - parseInt(xBarStyles['height'], 10);\n if (containerStyles['max-height'] !== 'none' && pureContainerHeight === 0) {\n if (this.$refs.content.offsetHeight + parseInt(xBarStyles['height'], 10) > parseInt(containerStyles['max-height'], 10)) {\n this.$el.style.height = containerStyles['max-height'];\n } else {\n this.$el.style.height = this.$refs.content.offsetHeight + parseFloat(containerStyles.paddingTop) + parseFloat(containerStyles.paddingBottom) + parseFloat(containerStyles.borderTopWidth) + parseFloat(containerStyles.borderBottomWidth) + 'px';\n }\n }\n },\n moveBar: function moveBar() {\n var _this = this;\n if (this.$refs.content) {\n /* horizontal scroll */\n var totalWidth = this.$refs.content.scrollWidth;\n var ownWidth = this.$refs.content.clientWidth;\n var bottom = (this.$el.clientHeight - this.$refs.xBar.clientHeight) * -1;\n this.scrollXRatio = ownWidth / totalWidth;\n\n /* vertical scroll */\n var totalHeight = this.$refs.content.scrollHeight;\n var ownHeight = this.$refs.content.clientHeight;\n var right = (this.$el.clientWidth - this.$refs.yBar.clientWidth) * -1;\n this.scrollYRatio = ownHeight / totalHeight;\n this.frame = this.requestAnimationFrame(function () {\n if (_this.$refs.xBar) {\n if (_this.scrollXRatio >= 1) {\n _this.$refs.xBar.setAttribute('data-p-scrollpanel-hidden', 'true');\n !_this.isUnstyled && addClass(_this.$refs.xBar, 'p-scrollpanel-hidden');\n } else {\n _this.$refs.xBar.setAttribute('data-p-scrollpanel-hidden', 'false');\n !_this.isUnstyled && removeClass(_this.$refs.xBar, 'p-scrollpanel-hidden');\n _this.$refs.xBar.style.cssText = 'width:' + Math.max(_this.scrollXRatio * 100, 10) + '%; left:' + _this.$refs.content.scrollLeft / totalWidth * 100 + '%;bottom:' + bottom + 'px;';\n }\n }\n if (_this.$refs.yBar) {\n if (_this.scrollYRatio >= 1) {\n _this.$refs.yBar.setAttribute('data-p-scrollpanel-hidden', 'true');\n !_this.isUnstyled && addClass(_this.$refs.yBar, 'p-scrollpanel-hidden');\n } else {\n _this.$refs.yBar.setAttribute('data-p-scrollpanel-hidden', 'false');\n !_this.isUnstyled && removeClass(_this.$refs.yBar, 'p-scrollpanel-hidden');\n _this.$refs.yBar.style.cssText = 'height:' + Math.max(_this.scrollYRatio * 100, 10) + '%; top: calc(' + _this.$refs.content.scrollTop / totalHeight * 100 + '% - ' + _this.$refs.xBar.clientHeight + 'px);right:' + right + 'px;';\n }\n }\n });\n }\n },\n onYBarMouseDown: function onYBarMouseDown(e) {\n this.isYBarClicked = true;\n this.$refs.yBar.focus();\n this.lastPageY = e.pageY;\n this.$refs.yBar.setAttribute('data-p-scrollpanel-grabbed', 'true');\n !this.isUnstyled && addClass(this.$refs.yBar, 'p-scrollpanel-grabbed');\n document.body.setAttribute('data-p-scrollpanel-grabbed', 'true');\n !this.isUnstyled && addClass(document.body, 'p-scrollpanel-grabbed');\n this.bindDocumentMouseListeners();\n e.preventDefault();\n },\n onXBarMouseDown: function onXBarMouseDown(e) {\n this.isXBarClicked = true;\n this.$refs.xBar.focus();\n this.lastPageX = e.pageX;\n this.$refs.yBar.setAttribute('data-p-scrollpanel-grabbed', 'false');\n !this.isUnstyled && addClass(this.$refs.xBar, 'p-scrollpanel-grabbed');\n document.body.setAttribute('data-p-scrollpanel-grabbed', 'false');\n !this.isUnstyled && addClass(document.body, 'p-scrollpanel-grabbed');\n this.bindDocumentMouseListeners();\n e.preventDefault();\n },\n onScroll: function onScroll(event) {\n if (this.lastScrollLeft !== event.target.scrollLeft) {\n this.lastScrollLeft = event.target.scrollLeft;\n this.orientation = 'horizontal';\n } else if (this.lastScrollTop !== event.target.scrollTop) {\n this.lastScrollTop = event.target.scrollTop;\n this.orientation = 'vertical';\n }\n this.moveBar();\n },\n onKeyDown: function onKeyDown(event) {\n if (this.orientation === 'vertical') {\n switch (event.code) {\n case 'ArrowDown':\n {\n this.setTimer('scrollTop', this.step);\n event.preventDefault();\n break;\n }\n case 'ArrowUp':\n {\n this.setTimer('scrollTop', this.step * -1);\n event.preventDefault();\n break;\n }\n case 'ArrowLeft':\n case 'ArrowRight':\n {\n event.preventDefault();\n break;\n }\n }\n } else if (this.orientation === 'horizontal') {\n switch (event.code) {\n case 'ArrowRight':\n {\n this.setTimer('scrollLeft', this.step);\n event.preventDefault();\n break;\n }\n case 'ArrowLeft':\n {\n this.setTimer('scrollLeft', this.step * -1);\n event.preventDefault();\n break;\n }\n case 'ArrowDown':\n case 'ArrowUp':\n {\n event.preventDefault();\n break;\n }\n }\n }\n },\n onKeyUp: function onKeyUp() {\n this.clearTimer();\n },\n repeat: function repeat(bar, step) {\n this.$refs.content[bar] += step;\n this.moveBar();\n },\n setTimer: function setTimer(bar, step) {\n var _this2 = this;\n this.clearTimer();\n this.timer = setTimeout(function () {\n _this2.repeat(bar, step);\n }, 40);\n },\n clearTimer: function clearTimer() {\n if (this.timer) {\n clearTimeout(this.timer);\n }\n },\n onDocumentMouseMove: function onDocumentMouseMove(e) {\n if (this.isXBarClicked) {\n this.onMouseMoveForXBar(e);\n } else if (this.isYBarClicked) {\n this.onMouseMoveForYBar(e);\n } else {\n this.onMouseMoveForXBar(e);\n this.onMouseMoveForYBar(e);\n }\n },\n onMouseMoveForXBar: function onMouseMoveForXBar(e) {\n var _this3 = this;\n var deltaX = e.pageX - this.lastPageX;\n this.lastPageX = e.pageX;\n this.frame = this.requestAnimationFrame(function () {\n _this3.$refs.content.scrollLeft += deltaX / _this3.scrollXRatio;\n });\n },\n onMouseMoveForYBar: function onMouseMoveForYBar(e) {\n var _this4 = this;\n var deltaY = e.pageY - this.lastPageY;\n this.lastPageY = e.pageY;\n this.frame = this.requestAnimationFrame(function () {\n _this4.$refs.content.scrollTop += deltaY / _this4.scrollYRatio;\n });\n },\n onFocus: function onFocus(event) {\n if (this.$refs.xBar.isSameNode(event.target)) {\n this.orientation = 'horizontal';\n } else if (this.$refs.yBar.isSameNode(event.target)) {\n this.orientation = 'vertical';\n }\n },\n onBlur: function onBlur() {\n if (this.orientation === 'horizontal') {\n this.orientation = 'vertical';\n }\n },\n onDocumentMouseUp: function onDocumentMouseUp() {\n this.$refs.yBar.setAttribute('data-p-scrollpanel-grabbed', 'false');\n !this.isUnstyled && removeClass(this.$refs.yBar, 'p-scrollpanel-grabbed');\n this.$refs.xBar.setAttribute('data-p-scrollpanel-grabbed', 'false');\n !this.isUnstyled && removeClass(this.$refs.xBar, 'p-scrollpanel-grabbed');\n document.body.setAttribute('data-p-scrollpanel-grabbed', 'false');\n !this.isUnstyled && removeClass(document.body, 'p-scrollpanel-grabbed');\n this.unbindDocumentMouseListeners();\n this.isXBarClicked = false;\n this.isYBarClicked = false;\n },\n requestAnimationFrame: function requestAnimationFrame(f) {\n var frame = window.requestAnimationFrame || this.timeoutFrame;\n return frame(f);\n },\n refresh: function refresh() {\n this.moveBar();\n },\n scrollTop: function scrollTop(_scrollTop) {\n var scrollableHeight = this.$refs.content.scrollHeight - this.$refs.content.clientHeight;\n _scrollTop = _scrollTop > scrollableHeight ? scrollableHeight : _scrollTop > 0 ? _scrollTop : 0;\n this.$refs.content.scrollTop = _scrollTop;\n },\n timeoutFrame: function timeoutFrame(fn) {\n setTimeout(fn, 0);\n },\n bindDocumentMouseListeners: function bindDocumentMouseListeners() {\n var _this5 = this;\n if (!this.documentMouseMoveListener) {\n this.documentMouseMoveListener = function (e) {\n _this5.onDocumentMouseMove(e);\n };\n document.addEventListener('mousemove', this.documentMouseMoveListener);\n }\n if (!this.documentMouseUpListener) {\n this.documentMouseUpListener = function (e) {\n _this5.onDocumentMouseUp(e);\n };\n document.addEventListener('mouseup', this.documentMouseUpListener);\n }\n },\n unbindDocumentMouseListeners: function unbindDocumentMouseListeners() {\n if (this.documentMouseMoveListener) {\n document.removeEventListener('mousemove', this.documentMouseMoveListener);\n this.documentMouseMoveListener = null;\n }\n if (this.documentMouseUpListener) {\n document.removeEventListener('mouseup', this.documentMouseUpListener);\n this.documentMouseUpListener = null;\n }\n },\n bindDocumentResizeListener: function bindDocumentResizeListener() {\n var _this6 = this;\n if (!this.documentResizeListener) {\n this.documentResizeListener = function () {\n _this6.moveBar();\n };\n window.addEventListener('resize', this.documentResizeListener);\n }\n },\n unbindDocumentResizeListener: function unbindDocumentResizeListener() {\n if (this.documentResizeListener) {\n window.removeEventListener('resize', this.documentResizeListener);\n this.documentResizeListener = null;\n }\n }\n },\n computed: {\n contentId: function contentId() {\n return this.id + '_content';\n }\n }\n};\n\nvar _hoisted_1 = [\"id\"];\nvar _hoisted_2 = [\"aria-controls\", \"aria-valuenow\"];\nvar _hoisted_3 = [\"aria-controls\", \"aria-valuenow\"];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"div\", mergeProps({\n \"class\": _ctx.cx('root')\n }, _ctx.ptmi('root')), [createElementVNode(\"div\", mergeProps({\n \"class\": _ctx.cx('contentContainer')\n }, _ctx.ptm('contentContainer')), [createElementVNode(\"div\", mergeProps({\n ref: \"content\",\n id: $options.contentId,\n \"class\": _ctx.cx('content'),\n onScroll: _cache[0] || (_cache[0] = function () {\n return $options.onScroll && $options.onScroll.apply($options, arguments);\n }),\n onMouseenter: _cache[1] || (_cache[1] = function () {\n return $options.moveBar && $options.moveBar.apply($options, arguments);\n })\n }, _ctx.ptm('content')), [renderSlot(_ctx.$slots, \"default\")], 16, _hoisted_1)], 16), createElementVNode(\"div\", mergeProps({\n ref: \"xBar\",\n \"class\": _ctx.cx('barx'),\n tabindex: \"0\",\n role: \"scrollbar\",\n \"aria-orientation\": \"horizontal\",\n \"aria-controls\": $options.contentId,\n \"aria-valuenow\": $data.lastScrollLeft,\n onMousedown: _cache[2] || (_cache[2] = function () {\n return $options.onXBarMouseDown && $options.onXBarMouseDown.apply($options, arguments);\n }),\n onKeydown: _cache[3] || (_cache[3] = function ($event) {\n return $options.onKeyDown($event);\n }),\n onKeyup: _cache[4] || (_cache[4] = function () {\n return $options.onKeyUp && $options.onKeyUp.apply($options, arguments);\n }),\n onFocus: _cache[5] || (_cache[5] = function () {\n return $options.onFocus && $options.onFocus.apply($options, arguments);\n }),\n onBlur: _cache[6] || (_cache[6] = function () {\n return $options.onBlur && $options.onBlur.apply($options, arguments);\n })\n }, _ctx.ptm('barx'), {\n \"data-pc-group-section\": \"bar\"\n }), null, 16, _hoisted_2), createElementVNode(\"div\", mergeProps({\n ref: \"yBar\",\n \"class\": _ctx.cx('bary'),\n tabindex: \"0\",\n role: \"scrollbar\",\n \"aria-orientation\": \"vertical\",\n \"aria-controls\": $options.contentId,\n \"aria-valuenow\": $data.lastScrollTop,\n onMousedown: _cache[7] || (_cache[7] = function () {\n return $options.onYBarMouseDown && $options.onYBarMouseDown.apply($options, arguments);\n }),\n onKeydown: _cache[8] || (_cache[8] = function ($event) {\n return $options.onKeyDown($event);\n }),\n onKeyup: _cache[9] || (_cache[9] = function () {\n return $options.onKeyUp && $options.onKeyUp.apply($options, arguments);\n }),\n onFocus: _cache[10] || (_cache[10] = function () {\n return $options.onFocus && $options.onFocus.apply($options, arguments);\n })\n }, _ctx.ptm('bary'), {\n \"data-pc-group-section\": \"bar\"\n }), null, 16, _hoisted_3)], 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","\n \n \n \n\n\n","\n \n \n
\n
\n \n \n {{ reportContent }} \n \n \n \n\n
\n \n \n
\n
\n \n\n\n\n\n","// This module is mocked in tests-ui/\n// Import vue components here to avoid tests-ui/ reporting errors\n// about importing primevue components.\nimport { useDialogStore } from '@/stores/dialogStore'\nimport LoadWorkflowWarning from '@/components/dialog/content/LoadWorkflowWarning.vue'\nimport MissingModelsWarning from '@/components/dialog/content/MissingModelsWarning.vue'\nimport SettingDialogContent from '@/components/dialog/content/SettingDialogContent.vue'\nimport SettingDialogHeader from '@/components/dialog/header/SettingDialogHeader.vue'\nimport type { ExecutionErrorWsMessage } from '@/types/apiTypes'\nimport ExecutionErrorDialogContent from '@/components/dialog/content/ExecutionErrorDialogContent.vue'\n\nexport function showLoadWorkflowWarning(props: {\n missingNodeTypes: any[]\n hasAddedNodes: boolean\n [key: string]: any\n}) {\n const dialogStore = useDialogStore()\n dialogStore.showDialog({\n component: LoadWorkflowWarning,\n props\n })\n}\n\nexport function showMissingModelsWarning(props: {\n missingModels: any[]\n [key: string]: any\n}) {\n const dialogStore = useDialogStore()\n dialogStore.showDialog({\n component: MissingModelsWarning,\n props\n })\n}\n\nexport function showSettingsDialog() {\n useDialogStore().showDialog({\n headerComponent: SettingDialogHeader,\n component: SettingDialogContent\n })\n}\n\nexport function showExecutionErrorDialog(error: ExecutionErrorWsMessage) {\n useDialogStore().showDialog({\n component: ExecutionErrorDialogContent,\n props: {\n error\n }\n })\n}\n","// Within Vue component context, you can directly call useToast().add()\n// instead of going through the store.\n// The store is useful when you need to call it from outside the Vue component context.\nimport { defineStore } from 'pinia'\nimport type { ToastMessageOptions } from 'primevue/toast'\n\nexport const useToastStore = defineStore('toast', {\n state: () => ({\n messagesToAdd: [] as ToastMessageOptions[],\n messagesToRemove: [] as ToastMessageOptions[],\n removeAllRequested: false\n }),\n\n actions: {\n add(message: ToastMessageOptions) {\n this.messagesToAdd = [...this.messagesToAdd, message]\n },\n remove(message: ToastMessageOptions) {\n this.messagesToRemove = [...this.messagesToRemove, message]\n },\n removeAll() {\n this.removeAllRequested = true\n }\n }\n})\n","var __defProp = Object.defineProperty;\nvar __typeError = (msg) => {\n throw TypeError(msg);\n};\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);\nvar __accessCheck = (obj, member, msg) => member.has(obj) || __typeError(\"Cannot \" + msg);\nvar __privateGet = (obj, member, getter) => (__accessCheck(obj, member, \"read from private field\"), getter ? getter.call(obj) : member.get(obj));\nvar __privateAdd = (obj, member, value) => member.has(obj) ? __typeError(\"Cannot add the same private member more than once\") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);\nvar BadgePosition = /* @__PURE__ */ ((BadgePosition2) => {\n BadgePosition2[\"TopLeft\"] = \"top-left\";\n BadgePosition2[\"TopRight\"] = \"top-right\";\n return BadgePosition2;\n})(BadgePosition || {});\nlet LGraphBadge$1 = class LGraphBadge2 {\n constructor({\n text,\n fgColor = \"white\",\n bgColor = \"#0F1F0F\",\n fontSize = 12,\n padding = 6,\n height = 20,\n cornerRadius = 5\n }) {\n __publicField(this, \"text\");\n __publicField(this, \"fgColor\");\n __publicField(this, \"bgColor\");\n __publicField(this, \"fontSize\");\n __publicField(this, \"padding\");\n __publicField(this, \"height\");\n __publicField(this, \"cornerRadius\");\n this.text = text;\n this.fgColor = fgColor;\n this.bgColor = bgColor;\n this.fontSize = fontSize;\n this.padding = padding;\n this.height = height;\n this.cornerRadius = cornerRadius;\n }\n get visible() {\n return this.text.length > 0;\n }\n getWidth(ctx) {\n if (!this.visible) return 0;\n ctx.save();\n ctx.font = `${this.fontSize}px sans-serif`;\n const textWidth = ctx.measureText(this.text).width;\n ctx.restore();\n return textWidth + this.padding * 2;\n }\n draw(ctx, x2, y2) {\n if (!this.visible) return;\n ctx.save();\n ctx.font = `${this.fontSize}px sans-serif`;\n const badgeWidth = this.getWidth(ctx);\n const badgeX = 0;\n ctx.fillStyle = this.bgColor;\n ctx.beginPath();\n if (ctx.roundRect) {\n ctx.roundRect(x2 + badgeX, y2, badgeWidth, this.height, this.cornerRadius);\n } else {\n ctx.rect(x2 + badgeX, y2, badgeWidth, this.height);\n }\n ctx.fill();\n ctx.fillStyle = this.fgColor;\n ctx.fillText(\n this.text,\n x2 + badgeX + this.padding,\n y2 + this.height - this.padding\n );\n ctx.restore();\n }\n};\nconst globalExport = {};\n(function(globalThis) {\n var _temp, _temp_vec2, _tmp_area, _margin_area, _link_bounding, _tempA, _tempB;\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 // Whether to highlight the bounding box of selected groups\n highlight_selected_group: 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 get nodes() {\n return this._nodes;\n }\n get groups() {\n return this._groups;\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 | null} the group or null\n */\n getGroupOnPos(x2, y2, { margin = 2 } = {}) {\n return this._groups.reverse().find((g) => g.isPointInside(\n x2,\n y2,\n margin,\n /* skip_title */\n true\n ));\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 class LGraphNode {\n constructor(title) {\n this._ctor(title);\n }\n _ctor(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.badges = [];\n this.badgePosition = BadgePosition.TopLeft;\n this.properties = {};\n this.properties_info = [];\n this.flags = {};\n }\n /**\n * configure a node from an object containing the serialized info\n * @method configure\n */\n configure(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.pinned) {\n this.pin(true);\n }\n if (this.onConfigure) {\n this.onConfigure(info);\n }\n }\n /**\n * serialize the content\n * @method serialize\n */\n serialize() {\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 /* Creates a clone of this node */\n clone() {\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 /**\n * serialize and stringify\n * @method toString\n */\n toString() {\n return JSON.stringify(this.serialize());\n }\n //LGraphNode.prototype.deserialize = function(info) {} //this cannot be done from within, must be done in LiteGraph\n /**\n * get the title string\n * @method getTitle\n */\n getTitle() {\n return this.title || this.constructor.title;\n }\n /**\n * sets the value of a property\n * @method setProperty\n * @param {String} name\n * @param {*} value\n */\n setProperty(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 // Execution *************************\n /**\n * sets the output data\n * @method setOutputData\n * @param {number} slot\n * @param {*} data\n */\n setOutputData(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 /**\n * sets the output data type, useful when you want to be able to overwrite the data type\n * @method setOutputDataType\n * @param {number} slot\n * @param {String} datatype\n */\n setOutputDataType(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 /**\n * Retrieves the input data (data traveling through the connection) from one slot\n * @method getInputData\n * @param {number} slot\n * @param {boolean} force_update if set to true it will force the connected node of this slot to output data into this link\n * @return {*} data or if it is not connected returns undefined\n */\n getInputData(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 /**\n * Retrieves the input data type (in case this supports multiple input types)\n * @method getInputDataType\n * @param {number} slot\n * @return {String} datatype in string format\n */\n getInputDataType(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 /**\n * Retrieves the input data from one slot using its name instead of slot number\n * @method getInputDataByName\n * @param {String} slot_name\n * @param {boolean} force_update if set to true it will force the connected node of this slot to output data into this link\n * @return {*} data or if it is not connected returns null\n */\n getInputDataByName(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 /**\n * tells you if there is a connection in one input slot\n * @method isInputConnected\n * @param {number} slot\n * @return {boolean}\n */\n isInputConnected(slot) {\n if (!this.inputs) {\n return false;\n }\n return slot < this.inputs.length && this.inputs[slot].link != null;\n }\n /**\n * tells you info about an input connection (which node, type, etc)\n * @method getInputInfo\n * @param {number} slot\n * @return {Object} object or null { link: id, name: string, type: string or 0 }\n */\n getInputInfo(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 /**\n * Returns the link info in the connection of an input slot\n * @method getInputLink\n * @param {number} slot\n * @return {LLink} object or null\n */\n getInputLink(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 /**\n * returns the node connected in the input slot\n * @method getInputNode\n * @param {number} slot\n * @return {LGraphNode} node or null\n */\n getInputNode(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 /**\n * returns the value of an input with this name, otherwise checks if there is a property with that name\n * @method getInputOrProperty\n * @param {string} name\n * @return {*} value\n */\n getInputOrProperty(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 /**\n * tells you the last output data that went in that slot\n * @method getOutputData\n * @param {number} slot\n * @return {Object} object or null\n */\n getOutputData(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 /**\n * tells you info about an output connection (which node, type, etc)\n * @method getOutputInfo\n * @param {number} slot\n * @return {Object} object or null { name: string, type: string, links: [ ids of links in number ] }\n */\n getOutputInfo(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 /**\n * tells you if there is a connection in one output slot\n * @method isOutputConnected\n * @param {number} slot\n * @return {boolean}\n */\n isOutputConnected(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 /**\n * tells you if there is any connection in the output slots\n * @method isAnyOutputConnected\n * @return {boolean}\n */\n isAnyOutputConnected() {\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 /**\n * retrieves all the nodes connected to this output slot\n * @method getOutputNodes\n * @param {number} slot\n * @return {array}\n */\n getOutputNodes(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 addOnTriggerInput() {\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 addOnExecutedOutput() {\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 onAfterExecuteNode(param, options) {\n var trigS = this.findOutputSlot(\"onExecuted\");\n if (trigS != -1) {\n this.triggerSlot(trigS, param, null, options);\n }\n }\n changeMode(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 /**\n * Triggers the node code execution, place a boolean/counter to mark the node as being executed\n * @method execute\n * @param {*} param\n * @param {*} options\n */\n doExecute(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 /**\n * Triggers an action, wrapped by logics to control execution flow\n * @method actionDo\n * @param {String} action name\n * @param {*} param\n */\n actionDo(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 /**\n * Triggers an event in this node, this will trigger any output with the same name\n * @method trigger\n * @param {String} event name ( \"on_play\", ... ) if action is equivalent to false then the event is send to all\n * @param {*} param\n */\n trigger(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 /**\n * Triggers a slot event in this node: cycle output slots and launch execute/action on connected nodes\n * @method triggerSlot\n * @param {Number} slot the index of the output slot\n * @param {*} param\n * @param {Number} link_id [optional] in case you want to trigger and specific output link in a slot\n */\n triggerSlot(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 /**\n * clears the trigger slot animation\n * @method clearTriggeredSlot\n * @param {Number} slot the index of the output slot\n * @param {Number} link_id [optional] in case you want to trigger and specific output link in a slot\n */\n clearTriggeredSlot(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 /**\n * changes node size and triggers callback\n * @method setSize\n * @param {vec2} size\n */\n setSize(size) {\n this.size = size;\n if (this.onResize)\n this.onResize(this.size);\n }\n /**\n * add a new property to this node\n * @method addProperty\n * @param {string} name\n * @param {*} default_value\n * @param {string} type string defining the output type (\"vec3\",\"number\",...)\n * @param {Object} extra_info this can be used to have special properties of the property (like values, etc)\n */\n addProperty(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 //connections\n /**\n * add a new output slot to use in this node\n * @method addOutput\n * @param {string} name\n * @param {string} type string defining the output type (\"vec3\",\"number\",...)\n * @param {Object} extra_info this can be used to have special properties of an output (label, special color, position, etc)\n */\n addOutput(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 /**\n * add a new output slot to use in this node\n * @method addOutputs\n * @param {Array} array of triplets like [[name,type,extra_info],[...]]\n */\n addOutputs(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 /**\n * remove an existing output slot\n * @method removeOutput\n * @param {number} slot\n */\n removeOutput(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 /**\n * add a new input slot to use in this node\n * @method addInput\n * @param {string} name\n * @param {string} type string defining the input type (\"vec3\",\"number\",...), it its a generic one use 0\n * @param {Object} extra_info this can be used to have special properties of an input (label, color, position, etc)\n */\n addInput(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 /**\n * add several new input slots in this node\n * @method addInputs\n * @param {Array} array of triplets like [[name,type,extra_info],[...]]\n */\n addInputs(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 /**\n * remove an existing input slot\n * @method removeInput\n * @param {number} slot\n */\n removeInput(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 /**\n * add an special connection to this node (used for special kinds of graphs)\n * @method addConnection\n * @param {string} name\n * @param {string} type string defining the input type (\"vec3\",\"number\",...)\n * @param {[x,y]} pos position of the connection inside the node\n * @param {string} direction if is input or output\n */\n addConnection(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 /**\n * computes the minimum size of a node according to its inputs and output slots\n * @method computeSize\n * @param {vec2} minHeight\n * @return {vec2} the total size\n */\n computeSize(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 inResizeCorner(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 /**\n * returns all the info available about a property of this node.\n *\n * @method getPropertyInfo\n * @param {String} property name of the property\n * @return {Object} the object with all the available info\n */\n getPropertyInfo(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 /**\n * Defines a widget inside the node, it will be rendered on top of the node, you can control lots of properties\n *\n * @method addWidget\n * @param {String} type the widget type (could be \"number\",\"string\",\"combo\"\n * @param {String} name the text to show on the widget\n * @param {String} value the default value\n * @param {Function|String} callback function to call when it changes (optionally, it can be the name of the property to modify)\n * @param {Object} options the object that contains special properties of this widget\n * @return {Object} the created widget object\n */\n addWidget(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 addCustomWidget(custom_widget) {\n if (!this.widgets) {\n this.widgets = [];\n }\n this.widgets.push(custom_widget);\n return custom_widget;\n }\n /**\n * returns the bounding of the object, used for rendering purposes\n * @method getBounding\n * @param out {Float32Array[4]?} [optional] a place to store the output, to free garbage\n * @param compute_outer {boolean?} [optional] set to true to include the shadow and connection points in the bounding calculation\n * @return {Float32Array[4]} the bounding box in format of [topleft_cornerx, topleft_cornery, width, height]\n */\n getBounding(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 /**\n * checks if a point is inside the shape of a node\n * @method isPointInside\n * @param {number} x\n * @param {number} y\n * @return {boolean}\n */\n isPointInside(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 /**\n * checks if a point is inside a node slot, and returns info about which slot\n * @method getSlotInPosition\n * @param {number} x\n * @param {number} y\n * @return {Object} if found the object contains { input|output: slot object, slot: number, link_pos: [x,y] }\n */\n getSlotInPosition(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 /**\n * returns the input slot with a given name (used for dynamic slots), -1 if not found\n * @method findInputSlot\n * @param {string} name the name of the slot\n * @param {boolean} returnObj if the obj itself wanted\n * @return {number_or_object} the slot (-1 if not found)\n */\n findInputSlot(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 /**\n * returns the output slot with a given name (used for dynamic slots), -1 if not found\n * @method findOutputSlot\n * @param {string} name the name of the slot\n * @param {boolean} returnObj if the obj itself wanted\n * @return {number_or_object} the slot (-1 if not found)\n */\n findOutputSlot(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 // TODO refactor: USE SINGLE findInput/findOutput functions! :: merge options\n /**\n * returns the first free input slot\n * @method findInputSlotFree\n * @param {object} options\n * @return {number_or_object} the slot (-1 if not found)\n */\n findInputSlotFree(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 /**\n * returns the first output slot free\n * @method findOutputSlotFree\n * @param {object} options\n * @return {number_or_object} the slot (-1 if not found)\n */\n findOutputSlotFree(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 /**\n * findSlotByType for INPUTS\n */\n findInputSlotByType(type, returnObj, preferFreeSlot, doNotUseOccupied) {\n return this.findSlotByType(true, type, returnObj, preferFreeSlot, doNotUseOccupied);\n }\n /**\n * findSlotByType for OUTPUTS\n */\n findOutputSlotByType(type, returnObj, preferFreeSlot, doNotUseOccupied) {\n return this.findSlotByType(false, type, returnObj, preferFreeSlot, doNotUseOccupied);\n }\n /**\n * returns the output (or input) slot with a given type, -1 if not found\n * @method findSlotByType\n * @param {boolean} input uise inputs instead of outputs\n * @param {string} type the type of the slot\n * @param {boolean} returnObj if the obj itself wanted\n * @param {boolean} preferFreeSlot if we want a free slot (if not found, will return the first of the type anyway)\n * @return {number_or_object} the slot (-1 if not found)\n */\n findSlotByType(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 /**\n * connect this node output to the input of another node BY TYPE\n * @method connectByType\n * @param {number_or_string} slot (could be the number of the slot or the string with the name of the slot)\n * @param {LGraphNode} node the target node\n * @param {string} target_type the input slot type of the target node\n * @return {Object} the link_info is created, otherwise null\n */\n connectByType(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 /**\n * connect this node input to the output of another node BY TYPE\n * @method connectByType\n * @param {number_or_string} slot (could be the number of the slot or the string with the name of the slot)\n * @param {LGraphNode} node the target node\n * @param {string} target_type the output slot type of the target node\n * @return {Object} the link_info is created, otherwise null\n */\n connectByTypeOutput(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 /**\n * connect this node output to the input of another node\n * @method connect\n * @param {number_or_string} slot (could be the number of the slot or the string with the name of the slot)\n * @param {LGraphNode} node the target node\n * @param {number_or_string} target_slot the input slot of the target node (could be the number of the slot or the string with the name of the slot, or -1 to connect a trigger)\n * @return {Object} the link_info is created, otherwise null\n */\n connect(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 /**\n * disconnect one output to an specific node\n * @method disconnectOutput\n * @param {number_or_string} slot (could be the number of the slot or the string with the name of the slot)\n * @param {LGraphNode} target_node the target node to which this slot is connected [Optional, if not target_node is specified all nodes will be disconnected]\n * @return {boolean} if it was disconnected successfully\n */\n disconnectOutput(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 /**\n * disconnect one input\n * @method disconnectInput\n * @param {number_or_string} slot (could be the number of the slot or the string with the name of the slot)\n * @return {boolean} if it was disconnected successfully\n */\n disconnectInput(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 /**\n * returns the center of a connection point in canvas coords\n * @method getConnectionPos\n * @param {boolean} is_input true if if a input slot, false if it is an output\n * @param {number_or_string} slot (could be the number of the slot or the string with the name of the slot)\n * @param {vec2} out [optional] a place to store the output, to free garbage\n * @return {[x,y]} the position\n **/\n getConnectionPos(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 /* Force align to grid */\n alignToGrid() {\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 /* Console output */\n trace(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 /* Forces to redraw or the main canvas (LGraphNode) or the bg canvas (links) */\n setDirtyCanvas(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 loadImage(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 //safe LGraphNode action execution (not sure if safe)\n /*\n LGraphNode.prototype.executeAction = function(action)\n {\n if(action == \"\") return false;\n \n if( action.indexOf(\";\") != -1 || action.indexOf(\"}\") != -1)\n {\n this.trace(\"Error: Action contains unsafe characters\");\n return false;\n }\n \n var tokens = action.split(\"(\");\n var func_name = tokens[0];\n if( typeof(this[func_name]) != \"function\")\n {\n this.trace(\"Error: Action not found on node: \" + func_name);\n return false;\n }\n \n var code = action;\n \n try\n {\n var _foo = eval;\n eval = null;\n (new Function(\"with(this) { \" + code + \"}\")).call(this);\n eval = _foo;\n }\n catch (err)\n {\n this.trace(\"Error executing action {\" + action + \"} :\" + err);\n return false;\n }\n \n return true;\n }\n */\n /* Allows to get onMouseMove and onMouseUp events even if the mouse is out of focus */\n captureInput(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 get collapsed() {\n return !!this.flags.collapsed;\n }\n get collapsible() {\n return !this.pinned && this.constructor.collapsable !== false;\n }\n /**\n * Collapse the node to make it smaller on the canvas\n * @method collapse\n **/\n collapse(force) {\n this.graph._version++;\n if (!this.collapsible && !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 get pinned() {\n return !!this.flags.pinned;\n }\n /**\n * Forces the node to do not move or realign on Z or resize\n * @method pin\n **/\n pin(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 this.resizable = !this.pinned;\n if (!this.pinned) {\n delete this.flags.pinned;\n }\n }\n localToScreen(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 get width() {\n return this.collapsed ? this._collapsed_width || LiteGraph.NODE_COLLAPSED_WIDTH : this.size[0];\n }\n get height() {\n return this.collapsed ? LiteGraph.NODE_COLLAPSED_HEIGHT : this.size[1];\n }\n drawBadges(ctx, { gap = 2 } = {}) {\n const badgeInstances = this.badges.map((badge) => badge instanceof LGraphBadge ? badge : badge());\n const isLeftAligned = this.badgePosition === BadgePosition.TopLeft;\n let currentX = isLeftAligned ? 0 : this.width - badgeInstances.reduce((acc, badge) => acc + badge.getWidth(ctx) + gap, 0);\n const y2 = -(LiteGraph.NODE_TITLE_HEIGHT + gap);\n for (const badge of badgeInstances) {\n badge.draw(ctx, currentX, y2 - badge.height);\n currentX += badge.getWidth(ctx) + gap;\n }\n }\n }\n globalThis.LGraphNode = LiteGraph.LGraphNode = LGraphNode;\n class LGraphGroup {\n constructor(title) {\n this._ctor(title);\n }\n _ctor(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 this.flags = {};\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 get nodes() {\n return this._nodes;\n }\n get titleHeight() {\n return this.font_size * 1.4;\n }\n get selected() {\n var _a, _b;\n return !!((_b = (_a = this.graph) == null ? void 0 : _a.list_of_graphcanvas) == null ? void 0 : _b.some((c) => c.selected_group === this));\n }\n get pinned() {\n return !!this.flags.pinned;\n }\n pin() {\n this.flags.pinned = true;\n }\n unpin() {\n delete this.flags.pinned;\n }\n configure(o) {\n this.title = o.title;\n this._bounding.set(o.bounding);\n this.color = o.color;\n this.flags = o.flags || this.flags;\n if (o.font_size) {\n this.font_size = o.font_size;\n }\n }\n serialize() {\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 flags: this.flags\n };\n }\n /**\n * Draws the group on the canvas\n * @param {LGraphCanvas} graphCanvas\n * @param {CanvasRenderingContext2D} ctx\n */\n draw(graphCanvas, ctx) {\n const padding = 4;\n ctx.fillStyle = this.color;\n ctx.strokeStyle = this.color;\n const [x2, y2] = this._pos;\n const [width2, height] = this._size;\n ctx.globalAlpha = 0.25 * graphCanvas.editor_alpha;\n ctx.beginPath();\n ctx.rect(x2 + 0.5, y2 + 0.5, width2, height);\n ctx.fill();\n ctx.globalAlpha = graphCanvas.editor_alpha;\n ctx.stroke();\n ctx.beginPath();\n ctx.moveTo(x2 + width2, y2 + height);\n ctx.lineTo(x2 + width2 - 10, y2 + height);\n ctx.lineTo(x2 + width2, y2 + height - 10);\n ctx.fill();\n const font_size = this.font_size || LiteGraph.DEFAULT_GROUP_FONT_SIZE;\n ctx.font = font_size + \"px Arial\";\n ctx.textAlign = \"left\";\n ctx.fillText(this.title + (this.pinned ? \"📌\" : \"\"), x2 + padding, y2 + font_size);\n if (LiteGraph.highlight_selected_group && this.selected) {\n graphCanvas.drawSelectionBounding(ctx, this._bounding, {\n shape: LiteGraph.BOX_SHAPE,\n title_height: this.titleHeight,\n title_mode: LiteGraph.NORMAL_TITLE,\n fgcolor: this.color,\n padding\n });\n }\n }\n resize(width2, height) {\n if (this.pinned) {\n return;\n }\n this._size[0] = width2;\n this._size[1] = height;\n }\n move(deltax, deltay, ignore_nodes) {\n if (this.pinned) {\n return;\n }\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 recomputeInsideNodes() {\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 /**\n * Add nodes to the group and adjust the group's position and size accordingly\n * @param {LGraphNode[]} nodes - The nodes to add to the group\n * @param {number} [padding=10] - The padding around the group\n * @returns {void}\n */\n addNodes(nodes, padding = 10) {\n if (!this._nodes && nodes.length === 0) return;\n const allNodes = [...this._nodes || [], ...nodes];\n const bounds = allNodes.reduce((acc, node2) => {\n var _a;\n const [x2, y2] = node2.pos;\n const [width2, height] = node2.size;\n const isReroute = node2.type === \"Reroute\";\n const isCollapsed = (_a = node2.flags) == null ? void 0 : _a.collapsed;\n const top = y2 - (isReroute ? 0 : LiteGraph.NODE_TITLE_HEIGHT);\n const bottom = isCollapsed ? top + LiteGraph.NODE_TITLE_HEIGHT : y2 + height;\n const right = isCollapsed && node2._collapsed_width ? x2 + Math.round(node2._collapsed_width) : x2 + width2;\n return {\n left: Math.min(acc.left, x2),\n top: Math.min(acc.top, top),\n right: Math.max(acc.right, right),\n bottom: Math.max(acc.bottom, bottom)\n };\n }, { left: Infinity, top: Infinity, right: -Infinity, bottom: -Infinity });\n this.pos = [\n bounds.left - padding,\n bounds.top - padding - this.titleHeight\n ];\n this.size = [\n bounds.right - bounds.left + padding * 2,\n bounds.bottom - bounds.top + padding * 2 + this.titleHeight\n ];\n }\n getMenuOptions() {\n return [\n {\n content: this.pinned ? \"Unpin\" : \"Pin\",\n callback: () => {\n this.pinned ? this.unpin() : this.pin();\n this.setDirtyCanvas(false, true);\n }\n },\n null,\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 }\n }\n LGraphGroup.prototype.isPointInside = LGraphNode.prototype.isPointInside;\n LGraphGroup.prototype.setDirtyCanvas = LGraphNode.prototype.setDirtyCanvas;\n globalThis.LGraphGroup = LiteGraph.LGraphGroup = LGraphGroup;\n class DragAndScale {\n constructor(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 bindEvents(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 computeVisibleArea(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 onMouse(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 toCanvasContext(ctx) {\n ctx.scale(this.scale, this.scale);\n ctx.translate(this.offset[0], this.offset[1]);\n }\n convertOffsetToCanvas(pos2) {\n return [\n (pos2[0] + this.offset[0]) * this.scale,\n (pos2[1] + this.offset[1]) * this.scale\n ];\n }\n convertCanvasToOffset(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 mouseDrag(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 changeScale(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 changeDeltaScale(value, zooming_center) {\n this.changeScale(this.scale * value, zooming_center);\n }\n reset() {\n this.scale = 1;\n this.offset[0] = 0;\n this.offset[1] = 0;\n }\n }\n LiteGraph.DragAndScale = DragAndScale;\n const _LGraphCanvas = class _LGraphCanvas {\n constructor(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.zoom_speed = 1.1;\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 static getFileExtension(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 /* this is an implementation for touch not in production and not ready\n */\n /*LGraphCanvas.prototype.touchHandler = function(event) {\n //alert(\"foo\");\n var touches = event.changedTouches,\n first = touches[0],\n type = \"\";\n \n switch (event.type) {\n case \"touchstart\":\n type = \"mousedown\";\n break;\n case \"touchmove\":\n type = \"mousemove\";\n break;\n case \"touchend\":\n type = \"mouseup\";\n break;\n default:\n return;\n }\n \n //initMouseEvent(type, canBubble, cancelable, view, clickCount,\n // screenX, screenY, clientX, clientY, ctrlKey,\n // altKey, shiftKey, metaKey, button, relatedTarget);\n \n // this is eventually a Dom object, get the LGraphCanvas back\n if(typeof this.getCanvasWindow == \"undefined\"){\n var window = this.lgraphcanvas.getCanvasWindow();\n }else{\n var window = this.getCanvasWindow();\n }\n \n var document = window.document;\n \n var simulatedEvent = document.createEvent(\"MouseEvent\");\n simulatedEvent.initMouseEvent(\n type,\n true,\n true,\n window,\n 1,\n first.screenX,\n first.screenY,\n first.clientX,\n first.clientY,\n false,\n false,\n false,\n false,\n 0, //left\n null\n );\n first.target.dispatchEvent(simulatedEvent);\n event.preventDefault();\n };*/\n /* CONTEXT MENU ********************/\n static onGroupAdd(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 /**\n * Determines the furthest nodes in each direction\n * @param nodes {LGraphNode[]} the nodes to from which boundary nodes will be extracted\n * @return {{left: LGraphNode, top: LGraphNode, right: LGraphNode, bottom: LGraphNode}}\n */\n static getBoundaryNodes(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 /**\n *\n * @param {LGraphNode[]} nodes a list of nodes\n * @param {\"top\"|\"bottom\"|\"left\"|\"right\"} direction Direction to align the nodes\n * @param {LGraphNode?} align_to Node to align to (if null, align to the furthest node in the given direction)\n */\n static alignNodes(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 static onNodeAlign(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 static onGroupAlign(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 static onMenuAdd(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({\n value: category_path,\n content: name,\n has_submenu: true,\n callback: function(value, event2, mouseEvent, contextMenu) {\n inner_onMenuAdded(value.value, contextMenu);\n }\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 static onMenuCollapseAll() {\n }\n static onMenuNodeEdit() {\n }\n static showMenuNodeOptionalInputs(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 static showMenuNodeOptionalOutputs(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 static onShowMenuNodeProperties(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 static decodeHTML(str) {\n var e = document.createElement(\"div\");\n e.innerText = str;\n return e.innerHTML;\n }\n static onMenuResizeNode(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 // TODO refactor :: this is used fot title but not for properties!\n static onShowPropertyEditor(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 = \"OK \";\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 static getPropertyPrintableValue(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 static onMenuNodeCollapse(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 static onMenuNodePin(value, options, e, menu, node2) {\n }\n static onMenuNodeMode(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 static onMenuNodeColors(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 static onMenuNodeShapes(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 static onMenuNodeRemove(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 static onMenuNodeToSubgraph(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 static onMenuNodeClone(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 /**\n * clears all the data inside\n *\n * @method clear\n */\n clear() {\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 /**\n * assigns a graph, you can reassign graphs to the same canvas\n *\n * @method setGraph\n * @param {LGraph} graph\n */\n setGraph(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 /**\n * returns the top level graph (in case there are subgraphs open on the canvas)\n *\n * @method getTopGraph\n * @return {LGraph} graph\n */\n getTopGraph() {\n if (this._graph_stack.length)\n return this._graph_stack[0];\n return this.graph;\n }\n /**\n * opens a graph contained inside a node in the current graph\n *\n * @method openSubgraph\n * @param {LGraph} graph\n */\n openSubgraph(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 /**\n * closes a subgraph contained inside a node\n *\n * @method closeSubgraph\n * @param {LGraph} assigns a graph\n */\n closeSubgraph() {\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 /**\n * returns the visually active graph (in case there are more in the stack)\n * @method getCurrentGraph\n * @return {LGraph} the active graph\n */\n getCurrentGraph() {\n return this.graph;\n }\n /**\n * assigns a canvas\n *\n * @method setCanvas\n * @param {Canvas} assigns a canvas (also accepts the ID of the element (not a selector)\n */\n setCanvas(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 //used in some events to capture them\n _doNothing(e) {\n e.preventDefault();\n return false;\n }\n _doReturnTrue(e) {\n e.preventDefault();\n return true;\n }\n /**\n * binds mouse, keyboard, touch and drag events to the canvas\n * @method bindEvents\n **/\n bindEvents() {\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 /**\n * unbinds mouse events from the canvas\n * @method unbindEvents\n **/\n unbindEvents() {\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 /**\n * this function allows to render the canvas using WebGL instead of Canvas2D\n * this is useful if you plant to render 3D objects inside your nodes, it uses litegl.js for webgl and canvas2DtoWebGL to emulate the Canvas2D calls in webGL\n * @method enableWebGL\n **/\n enableWebGL() {\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 /**\n * marks as dirty the canvas, this way it will be rendered again\n *\n * @class LGraphCanvas\n * @method setDirty\n * @param {bool} fgcanvas if the foreground canvas is dirty (the one containing the nodes)\n * @param {bool} bgcanvas if the background canvas is dirty (the one containing the wires)\n */\n setDirty(fgcanvas, bgcanvas) {\n if (fgcanvas) {\n this.dirty_canvas = true;\n }\n if (bgcanvas) {\n this.dirty_bgcanvas = true;\n }\n }\n /**\n * Used to attach the canvas in a popup\n *\n * @method getCanvasWindow\n * @return {window} returns the window where the canvas is attached (the DOM root node)\n */\n getCanvasWindow() {\n if (!this.canvas) {\n return window;\n }\n var doc = this.canvas.ownerDocument;\n return doc.defaultView || doc.parentWindow;\n }\n /**\n * starts rendering the content of the canvas when needed\n *\n * @method startRendering\n */\n startRendering() {\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 /**\n * stops rendering the content of the canvas (to save resources)\n *\n * @method stopRendering\n */\n stopRendering() {\n this.is_rendering = false;\n }\n /* LiteGraphCanvas input */\n //used to block future mouse events (because of im gui)\n blockClick() {\n this.block_click = true;\n this.last_mouseclick = 0;\n }\n processMouseDown(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 == null ? void 0 : node2.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 (pos2[1] < 0) {\n if (node2.onNodeTitleDblClick) {\n node2.onNodeTitleDblClick(e, pos2, this);\n }\n }\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 const lineWidth = this.ctx.lineWidth;\n this.ctx.lineWidth = this.connections_width + 7;\n for (var i2 = 0; i2 < this.visible_links.length; ++i2) {\n var link = this.visible_links[i2];\n var center = link._pos;\n let overLink = null;\n if (!center || e.canvasX < center[0] - 4 || e.canvasX > center[0] + 4 || e.canvasY < center[1] - 4 || e.canvasY > center[1] + 4) {\n if (e.shiftKey && link.path && this.ctx.isPointInStroke(link.path, e.canvasX, e.canvasY)) {\n overLink = link;\n } else {\n continue;\n }\n }\n if (overLink) {\n const slot = overLink.origin_slot;\n const originNode = this.graph._nodes_by_id[overLink.origin_id];\n this.connecting_links ?? (this.connecting_links = []);\n this.connecting_links.push({\n node: originNode,\n slot,\n output: originNode.outputs[slot],\n pos: originNode.getConnectionPos(false, slot)\n });\n skip_action = true;\n } else {\n this.showLinkMenu(link, e);\n this.over_link_center = null;\n }\n break;\n }\n this.ctx.lineWidth = lineWidth;\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 if (is_double_click) {\n this.canvas.dispatchEvent(new CustomEvent(\n \"litegraph:canvas\",\n {\n bubbles: true,\n detail: {\n subType: \"group-double-click\",\n originalEvent: e,\n group: this.selected_group\n }\n }\n ));\n }\n } else 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 /**\n * Called when a mouse move event has to be processed\n * @method processMouseMove\n **/\n processMouseMove(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.resize(\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 /**\n * Called when a mouse up event has to be processed\n * @method processMouseUp\n **/\n processMouseUp(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 /**\n * Called when a mouse wheel event has to be processed\n * @method processMouseWheel\n **/\n processMouseWheel(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 *= this.zoom_speed;\n } else if (delta2 < 0) {\n scale *= 1 / this.zoom_speed;\n }\n this.ds.changeScale(scale, [e.clientX, e.clientY]);\n this.graph.change();\n e.preventDefault();\n return false;\n }\n /**\n * returns true if a position (in graph space) is on top of a node little corner box\n * @method isOverNodeBox\n **/\n isOverNodeBox(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 /**\n * returns the INDEX if a position (in graph space) is on top of a node input slot\n * @method isOverNodeInput\n **/\n isOverNodeInput(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 /**\n * returns the INDEX if a position (in graph space) is on top of a node output slot\n * @method isOverNodeOuput\n **/\n isOverNodeOutput(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 /**\n * process a key event\n * @method processKey\n **/\n processKey(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 copyToClipboard(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 pasteFromClipboard(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 /**\n * process a item drop event on top the canvas\n * @method processDrop\n **/\n processDrop(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 //called if the graph doesn't have a default drop item behaviour\n checkDropItem(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 processNodeDblClicked(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 processNodeSelected(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 /**\n * selects a given node (or adds it to the current selection)\n * @method selectNode\n **/\n selectNode(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 /**\n * selects several nodes (or adds them to the current selection)\n * @method selectNodes\n **/\n selectNodes(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 /**\n * removes a node from the current selection\n * @method deselectNode\n **/\n deselectNode(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 /**\n * removes all nodes from the current selection\n * @method deselectAllNodes\n **/\n deselectAllNodes() {\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 /**\n * deletes all nodes in the current selection from the graph\n * @method deleteSelectedNodes\n **/\n deleteSelectedNodes() {\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 /**\n * centers the camera on a given node\n * @method centerOnNode\n **/\n centerOnNode(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 /**\n * adds some useful properties to a mouse event, like the position in graph coordinates\n * @method adjustMouseEvent\n **/\n adjustMouseEvent(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 /**\n * changes the zoom level of the graph (default is 1), you can pass also a place used to pivot the zoom\n * @method setZoom\n **/\n setZoom(value, zooming_center) {\n this.ds.changeScale(value, zooming_center);\n this.dirty_canvas = true;\n this.dirty_bgcanvas = true;\n }\n /**\n * converts a coordinate from graph coordinates to canvas2D coordinates\n * @method convertOffsetToCanvas\n **/\n convertOffsetToCanvas(pos2, out) {\n return this.ds.convertOffsetToCanvas(pos2, out);\n }\n /**\n * converts a coordinate from Canvas2D coordinates to graph space\n * @method convertCanvasToOffset\n **/\n convertCanvasToOffset(pos2, out) {\n return this.ds.convertCanvasToOffset(pos2, out);\n }\n //converts event coordinates from canvas2D to graph coordinates\n convertEventToCanvasOffset(e) {\n var rect = this.canvas.getBoundingClientRect();\n return this.convertCanvasToOffset([\n e.clientX - rect.left,\n e.clientY - rect.top\n ]);\n }\n /**\n * brings a node to front (above all other nodes)\n * @method bringToFront\n **/\n bringToFront(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 /**\n * sends a node to the back (below all other nodes)\n * @method sendToBack\n **/\n sendToBack(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 /* LGraphCanvas render */\n /**\n * checks which nodes are visible (inside the camera area)\n * @method computeVisibleNodes\n **/\n computeVisibleNodes(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(__privateGet(_LGraphCanvas, _temp), true))) {\n continue;\n }\n visible_nodes.push(n);\n }\n return visible_nodes;\n }\n /**\n * renders the whole canvas content, by rendering in two separated canvas, one containing the background grid and the connections, and one containing the nodes)\n * @method draw\n **/\n draw(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 /**\n * draws the front canvas (the one containing all the nodes)\n * @method drawFrontCanvas\n **/\n drawFrontCanvas() {\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 let scale = window.devicePixelRatio;\n ctx.drawImage(this.bgcanvas, 0, 0, this.bgcanvas.width / scale, this.bgcanvas.height / scale);\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 /**\n * draws the panel in the corner that shows subgraph properties\n * @method drawSubgraphPanel\n **/\n drawSubgraphPanel(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 drawSubgraphPanelLeft(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 drawSubgraphPanelRight(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 //Draws a button into the canvas overlay and computes if it was clicked using the immediate gui paradigm\n drawButton(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 isAreaClicked(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 /**\n * draws some useful stats in the corner of the canvas\n * @method renderInfo\n **/\n renderInfo(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 /**\n * draws the back canvas (the one containing the background and the connections)\n * @method drawBackCanvas\n **/\n drawBackCanvas() {\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 let scale = window.devicePixelRatio;\n ctx.restore();\n ctx.setTransform(scale, 0, 0, scale, 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 /**\n * draws the given node inside the canvas\n * @method drawNode\n **/\n drawNode(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 = __privateGet(_LGraphCanvas, _temp_vec2);\n __privateGet(_LGraphCanvas, _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 node2.drawBadges(ctx);\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 //used by this.over_link_center\n drawLinkTooltip(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 /**\n * draws the shape of the given node in the canvas\n * @method drawNodeShape\n **/\n drawNodeShape(node2, ctx, size, fgcolor, bgcolor, selected, mouse_over) {\n var _a;\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 = __privateGet(_LGraphCanvas, _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()) + (node2.pinned ? \"📌\" : \"\");\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 this.drawSelectionBounding(\n ctx,\n area,\n {\n shape,\n title_height,\n title_mode,\n fgcolor,\n collapsed: (_a = node2.flags) == null ? void 0 : _a.collapsed\n }\n );\n }\n if (node2.execute_triggered > 0) node2.execute_triggered--;\n if (node2.action_triggered > 0) node2.action_triggered--;\n }\n /**\n * Draws the selection bounding of an area.\n * @param {CanvasRenderingContext2D} ctx\n * @param {Vector4} area\n * @param {{\n * shape: LiteGraph.Shape,\n * title_height: number,\n * title_mode: LiteGraph.TitleMode,\n * fgcolor: string,\n * padding: number,\n * }} options\n */\n drawSelectionBounding(ctx, area, {\n shape = LiteGraph.BOX_SHAPE,\n title_height = LiteGraph.NODE_TITLE_HEIGHT,\n title_mode = LiteGraph.NORMAL_TITLE,\n fgcolor = LiteGraph.NODE_BOX_OUTLINE_COLOR,\n padding = 6,\n collapsed = false\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 const [x2, y2, width2, height] = area;\n switch (shape) {\n case LiteGraph.BOX_SHAPE: {\n ctx.rect(x2 - padding, y2 - padding, width2 + 2 * padding, height + 2 * padding);\n break;\n }\n case LiteGraph.ROUND_SHAPE:\n case LiteGraph.CARD_SHAPE: {\n const radius = this.round_radius * 2;\n const isCollapsed = shape === LiteGraph.CARD_SHAPE && collapsed;\n const cornerRadii = isCollapsed || shape === LiteGraph.ROUND_SHAPE ? [radius] : [radius, 2, radius, 2];\n ctx.roundRect(x2 - padding, y2 - padding, width2 + 2 * padding, height + 2 * padding, cornerRadii);\n break;\n }\n case LiteGraph.CIRCLE_SHAPE: {\n const centerX = x2 + width2 / 2;\n const centerY = y2 + height / 2;\n const radius = Math.max(width2, height) / 2 + padding;\n ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);\n break;\n }\n }\n ctx.strokeStyle = LiteGraph.NODE_BOX_OUTLINE_COLOR;\n ctx.stroke();\n ctx.strokeStyle = fgcolor;\n ctx.globalAlpha = 1;\n }\n drawConnections(ctx) {\n var now = LiteGraph.getTime();\n var visible_area = this.visible_area;\n __privateGet(_LGraphCanvas, _margin_area)[0] = visible_area[0] - 20;\n __privateGet(_LGraphCanvas, _margin_area)[1] = visible_area[1] - 20;\n __privateGet(_LGraphCanvas, _margin_area)[2] = visible_area[2] + 40;\n __privateGet(_LGraphCanvas, _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 __privateGet(_LGraphCanvas, _tempA)\n );\n }\n var end_node_slotpos = node2.getConnectionPos(true, i2, __privateGet(_LGraphCanvas, _tempB));\n __privateGet(_LGraphCanvas, _link_bounding)[0] = start_node_slotpos[0];\n __privateGet(_LGraphCanvas, _link_bounding)[1] = start_node_slotpos[1];\n __privateGet(_LGraphCanvas, _link_bounding)[2] = end_node_slotpos[0] - start_node_slotpos[0];\n __privateGet(_LGraphCanvas, _link_bounding)[3] = end_node_slotpos[1] - start_node_slotpos[1];\n if (__privateGet(_LGraphCanvas, _link_bounding)[2] < 0) {\n __privateGet(_LGraphCanvas, _link_bounding)[0] += __privateGet(_LGraphCanvas, _link_bounding)[2];\n __privateGet(_LGraphCanvas, _link_bounding)[2] = Math.abs(__privateGet(_LGraphCanvas, _link_bounding)[2]);\n }\n if (__privateGet(_LGraphCanvas, _link_bounding)[3] < 0) {\n __privateGet(_LGraphCanvas, _link_bounding)[1] += __privateGet(_LGraphCanvas, _link_bounding)[3];\n __privateGet(_LGraphCanvas, _link_bounding)[3] = Math.abs(__privateGet(_LGraphCanvas, _link_bounding)[3]);\n }\n if (!overlapBounding(__privateGet(_LGraphCanvas, _link_bounding), __privateGet(_LGraphCanvas, _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 /**\n * draws a link between two points\n * @method renderLink\n * @param {vec2} a start pos\n * @param {vec2} b end pos\n * @param {Object} link the link object with all the link info\n * @param {boolean} skip_border ignore the shadow of the link\n * @param {boolean} flow show flow animation (for events)\n * @param {string} color the color for the link\n * @param {number} start_dir the direction enum\n * @param {number} end_dir the direction enum\n * @param {number} num_sublines number of sublines (useful to represent vec3 or rgb)\n **/\n renderLink(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 const path = new Path2D();\n if (link) {\n link.path = path;\n }\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 path.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 path.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 path.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 path.lineTo(\n a[0] + start_offset_x * l,\n a[1] + start_offset_y * l + offsety\n );\n path.lineTo(\n b[0] + end_offset_x * l,\n b[1] + end_offset_y * l + offsety\n );\n path.lineTo(b[0], b[1] + offsety);\n } else if (this.links_render_mode == LiteGraph.STRAIGHT_LINK) {\n path.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 path.lineTo(start_x, start_y);\n path.lineTo((start_x + end_x) * 0.5, start_y);\n path.lineTo((start_x + end_x) * 0.5, end_y);\n path.lineTo(end_x, end_y);\n path.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(path);\n }\n ctx.lineWidth = this.connections_width;\n ctx.fillStyle = ctx.strokeStyle = color;\n ctx.stroke(path);\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 //returns the link center point based on curvature\n computeConnectionPoint(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 drawExecutionOrder(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 /**\n * draws the widgets stored inside a node\n * @method drawNodeWidgets\n **/\n drawNodeWidgets(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 /**\n * process an event on widgets\n * @method processNodeWidgets\n **/\n processNodeWidgets(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 /**\n * draws every group area in the background\n * @method drawGroups\n **/\n drawGroups(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 group.draw(this, ctx);\n }\n ctx.restore();\n }\n adjustNodesSize() {\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 /**\n * resizes the canvas to a given size, if no size is passed, then it tries to fill the parentNode\n * @method resize\n **/\n resize(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 /**\n * switches to live mode (node shapes are not rendered, only the content)\n * this feature was designed when graphs where meant to create user interfaces\n * @method switchLiveMode\n **/\n switchLiveMode(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 onNodeSelectionChange(node2) {\n return;\n }\n /**\n * Determines the furthest nodes in each direction for the currently selected nodes\n * @return {{left: LGraphNode, top: LGraphNode, right: LGraphNode, bottom: LGraphNode}}\n */\n boundaryNodesForSelection() {\n return _LGraphCanvas.getBoundaryNodes(Object.values(this.selected_nodes));\n }\n showLinkMenu(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 createDefaultNodeForSlot(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 showConnectionMenu(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 allow_searchbox: this.allow_searchbox,\n showSearchBox: this.showSearchBox\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;\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;\n }\n var options = [\"Add Node\", null];\n if (opts.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 opts.showSearchBox(e, { node_from: opts.nodeFrom, slot_from: slotX, type_filter_in: fromSlotType });\n } else {\n opts.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 }\n // refactor: there are different dialogs, some uses createDialog some dont\n prompt(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 = \" OK \";\n else\n dialog.innerHTML = \" OK \";\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 const clickTime = Date.now();\n function handleOutsideClick(e) {\n if (e.target === canvas && Date.now() - clickTime > 256) {\n dialog.close();\n canvas.parentNode.removeEventListener(\"click\", handleOutsideClick);\n canvas.parentNode.removeEventListener(\"touchend\", handleOutsideClick);\n }\n }\n canvas.parentNode.addEventListener(\"click\", handleOutsideClick);\n canvas.parentNode.addEventListener(\"touchend\", handleOutsideClick);\n }, 10);\n return dialog;\n }\n showSearchBox(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 requestAnimationFrame(function() {\n input.focus();\n });\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 showEditPropertyValue(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 for (var i2 in info.values) {\n var v2 = i2;\n if (info.values.constructor === Array)\n v2 = info.values[i2];\n input_html += \"\" + info.values[i2] + \" \";\n }\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 + \"OK \",\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 // TODO refactor, theer are different dialog, some uses createDialog, some dont\n createDialog(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 createPanel(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 closePanels() {\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 showShowGraphOptionsPanel(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 showShowNodePanel(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 showSubgraphPropertiesDialog(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 = \" + Name Type + \";\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 showSubgraphPropertiesDialogRight(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 = \" + Name Type + \";\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 checkPanels() {\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 getCanvasMenuOptions() {\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 //called by processContextMenu to extract the menu list\n getNodeMenuOptions(node2) {\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 if (node2.collapsible) {\n options.push({\n content: node2.collapsed ? \"Expand\" : \"Collapse\",\n callback: _LGraphCanvas.onMenuNodeCollapse\n });\n }\n options.push(\n {\n content: node2.pinned ? \"Unpin\" : \"Pin\",\n callback: (...args) => {\n _LGraphCanvas.onMenuNodePin(...args);\n for (const i2 in this.selected_nodes) {\n const node3 = this.selected_nodes[i2];\n node3.pin();\n }\n this.setDirty(true, true);\n }\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 getGroupMenuOptions(node2) {\n console.warn(\"LGraphCanvas.getGroupMenuOptions is deprecated, use LGraphGroup.getMenuOptions instead\");\n return node2.getMenuOptions();\n }\n processContextMenu(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: group.getMenuOptions()\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 OK \",\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 };\n _temp = new WeakMap();\n _temp_vec2 = new WeakMap();\n _tmp_area = new WeakMap();\n _margin_area = new WeakMap();\n _link_bounding = new WeakMap();\n _tempA = new WeakMap();\n _tempB = new WeakMap();\n /* Interaction */\n __privateAdd(_LGraphCanvas, _temp, new Float32Array(4));\n __privateAdd(_LGraphCanvas, _temp_vec2, new Float32Array(2));\n __privateAdd(_LGraphCanvas, _tmp_area, new Float32Array(4));\n __privateAdd(_LGraphCanvas, _margin_area, new Float32Array(4));\n __privateAdd(_LGraphCanvas, _link_bounding, new Float32Array(4));\n __privateAdd(_LGraphCanvas, _tempA, new Float32Array(2));\n __privateAdd(_LGraphCanvas, _tempB, new Float32Array(2));\n __publicField(_LGraphCanvas, \"DEFAULT_BACKGROUND_IMAGE\", \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAIAAAD/gAIDAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAQBJREFUeNrs1rEKwjAUhlETUkj3vP9rdmr1Ysammk2w5wdxuLgcMHyptfawuZX4pJSWZTnfnu/lnIe/jNNxHHGNn//HNbbv+4dr6V+11uF527arU7+u63qfa/bnmh8sWLBgwYJlqRf8MEptXPBXJXa37BSl3ixYsGDBMliwFLyCV/DeLIMFCxYsWLBMwSt4Be/NggXLYMGCBUvBK3iNruC9WbBgwYJlsGApeAWv4L1ZBgsWLFiwYJmCV/AK3psFC5bBggULloJX8BpdwXuzYMGCBctgwVLwCl7Be7MMFixYsGDBsu8FH1FaSmExVfAxBa/gvVmwYMGCZbBg/W4vAQYA5tRF9QYlv/QAAAAASUVORK5CYII=\");\n __publicField(_LGraphCanvas, \"link_type_colors\", {\n \"-1\": LiteGraph.EVENT_LINK_COLOR,\n number: \"#AAA\",\n node: \"#DCA\"\n });\n __publicField(_LGraphCanvas, \"gradients\", {});\n //cache of gradients\n __publicField(_LGraphCanvas, \"search_limit\", -1);\n __publicField(_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 let LGraphCanvas = _LGraphCanvas;\n globalThis.LGraphCanvas = LiteGraph.LGraphCanvas = LGraphCanvas;\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 BadgePosition,\n ContextMenu,\n DragAndScale,\n LGraph,\n LGraphBadge$1 as LGraphBadge,\n LGraphCanvas,\n LGraphGroup,\n LGraphNode,\n LLink,\n LiteGraph\n};\n//# sourceMappingURL=litegraph.es.js.map\n","import { LGraphNode, LGraphGroup, LGraphCanvas } from '@comfyorg/litegraph'\nimport { defineStore } from 'pinia'\nimport { shallowRef } from 'vue'\n\nexport const useTitleEditorStore = defineStore('titleEditor', () => {\n const titleEditorTarget = shallowRef(null)\n\n return {\n titleEditorTarget\n }\n})\n\nexport const useCanvasStore = defineStore('canvas', () => {\n const canvas = shallowRef(null)\n\n return {\n canvas\n }\n})\n","import { api } from './api'\nimport { ComfyDialog as _ComfyDialog } from './ui/dialog'\nimport { toggleSwitch } from './ui/toggleSwitch'\nimport { ComfySettingsDialog } from './ui/settings'\nimport { ComfyApp, app } from './app'\nimport { TaskItem } from '@/types/apiTypes'\nimport { showSettingsDialog } from '@/services/dialogService'\nimport { useToastStore } from '@/stores/toastStore'\nimport { LGraphGroup } from '@comfyorg/litegraph'\nimport { useSettingStore } from '@/stores/settingStore'\nimport { useTitleEditorStore } from '@/stores/graphStore'\n\nexport const ComfyDialog = _ComfyDialog\n\ntype Position2D = {\n x: number\n y: number\n}\n\ntype Props = {\n parent?: HTMLElement\n $?: (el: HTMLElement) => void\n dataset?: DOMStringMap\n style?: Partial\n for?: string\n textContent?: string\n [key: string]: any\n}\n\ntype Children = Element[] | Element | string | string[]\n\ntype ElementType = K extends keyof HTMLElementTagNameMap\n ? HTMLElementTagNameMap[K]\n : HTMLElement\n\nexport function $el(\n tag: TTag,\n propsOrChildren?: Children | Props,\n children?: Children\n): ElementType {\n const split = tag.split('.')\n const element = document.createElement(split.shift() as string)\n if (split.length > 0) {\n element.classList.add(...split)\n }\n\n if (propsOrChildren) {\n if (typeof propsOrChildren === 'string') {\n propsOrChildren = { textContent: propsOrChildren }\n } else if (propsOrChildren instanceof Element) {\n propsOrChildren = [propsOrChildren]\n }\n if (Array.isArray(propsOrChildren)) {\n element.append(...propsOrChildren)\n } else {\n const {\n parent,\n $: cb,\n dataset,\n style,\n ...rest\n } = propsOrChildren as Props\n\n if (rest.for) {\n element.setAttribute('for', rest.for)\n }\n\n if (style) {\n Object.assign(element.style, style)\n }\n\n if (dataset) {\n Object.assign(element.dataset, dataset)\n }\n\n Object.assign(element, rest)\n if (children) {\n element.append(...(Array.isArray(children) ? children : [children]))\n }\n\n if (parent) {\n parent.append(element)\n }\n\n if (cb) {\n cb(element)\n }\n }\n }\n return element as ElementType\n}\n\nfunction dragElement(dragEl, settings): () => void {\n var posDiffX = 0,\n posDiffY = 0,\n posStartX = 0,\n posStartY = 0,\n newPosX = 0,\n newPosY = 0\n if (dragEl.getElementsByClassName('drag-handle')[0]) {\n // if present, the handle is where you move the DIV from:\n dragEl.getElementsByClassName('drag-handle')[0].onmousedown = dragMouseDown\n } else {\n // otherwise, move the DIV from anywhere inside the DIV:\n dragEl.onmousedown = dragMouseDown\n }\n\n // When the element resizes (e.g. view queue) ensure it is still in the windows bounds\n const resizeObserver = new ResizeObserver(() => {\n ensureInBounds()\n }).observe(dragEl)\n\n function ensureInBounds() {\n try {\n newPosX = Math.min(\n document.body.clientWidth - dragEl.clientWidth,\n Math.max(0, dragEl.offsetLeft)\n )\n newPosY = Math.min(\n document.body.clientHeight - dragEl.clientHeight,\n Math.max(0, dragEl.offsetTop)\n )\n\n positionElement()\n } catch (exception) {\n // robust\n }\n }\n\n function positionElement() {\n if (dragEl.style.display === 'none') return\n\n const halfWidth = document.body.clientWidth / 2\n const anchorRight = newPosX + dragEl.clientWidth / 2 > halfWidth\n\n // set the element's new position:\n if (anchorRight) {\n dragEl.style.left = 'unset'\n dragEl.style.right =\n document.body.clientWidth - newPosX - dragEl.clientWidth + 'px'\n } else {\n dragEl.style.left = newPosX + 'px'\n dragEl.style.right = 'unset'\n }\n\n dragEl.style.top = newPosY + 'px'\n dragEl.style.bottom = 'unset'\n\n if (savePos) {\n localStorage.setItem(\n 'Comfy.MenuPosition',\n JSON.stringify({\n x: dragEl.offsetLeft,\n y: dragEl.offsetTop\n })\n )\n }\n }\n\n function restorePos() {\n let posString = localStorage.getItem('Comfy.MenuPosition')\n if (posString) {\n const pos = JSON.parse(posString) as Position2D\n newPosX = pos.x\n newPosY = pos.y\n positionElement()\n ensureInBounds()\n }\n }\n\n let savePos = undefined\n settings.addSetting({\n id: 'Comfy.MenuPosition',\n category: ['Comfy', 'Menu', 'MenuPosition'],\n name: \"Save legacy menu's position\",\n type: 'boolean',\n defaultValue: savePos,\n onChange(value) {\n if (savePos === undefined && value) {\n restorePos()\n }\n savePos = value\n }\n })\n\n function dragMouseDown(e) {\n e = e || window.event\n e.preventDefault()\n // get the mouse cursor position at startup:\n posStartX = e.clientX\n posStartY = e.clientY\n document.onmouseup = closeDragElement\n // call a function whenever the cursor moves:\n document.onmousemove = elementDrag\n }\n\n function elementDrag(e) {\n e = e || window.event\n e.preventDefault()\n\n dragEl.classList.add('comfy-menu-manual-pos')\n\n // calculate the new cursor position:\n posDiffX = e.clientX - posStartX\n posDiffY = e.clientY - posStartY\n posStartX = e.clientX\n posStartY = e.clientY\n\n newPosX = Math.min(\n document.body.clientWidth - dragEl.clientWidth,\n Math.max(0, dragEl.offsetLeft + posDiffX)\n )\n newPosY = Math.min(\n document.body.clientHeight - dragEl.clientHeight,\n Math.max(0, dragEl.offsetTop + posDiffY)\n )\n\n positionElement()\n }\n\n window.addEventListener('resize', () => {\n ensureInBounds()\n })\n\n function closeDragElement() {\n // stop moving when mouse button is released:\n document.onmouseup = null\n document.onmousemove = null\n }\n\n return restorePos\n}\n\nclass ComfyList {\n #type\n #text\n #reverse\n element: HTMLDivElement\n button?: HTMLButtonElement\n\n constructor(text, type?, reverse?) {\n this.#text = text\n this.#type = type || text.toLowerCase()\n this.#reverse = reverse || false\n this.element = $el('div.comfy-list') as HTMLDivElement\n this.element.style.display = 'none'\n }\n\n get visible() {\n return this.element.style.display !== 'none'\n }\n\n async load() {\n const items = await api.getItems(this.#type)\n this.element.replaceChildren(\n ...Object.keys(items).flatMap((section) => [\n $el('h4', {\n textContent: section\n }),\n $el('div.comfy-list-items', [\n ...(this.#reverse ? items[section].reverse() : items[section]).map(\n (item: TaskItem) => {\n // Allow items to specify a custom remove action (e.g. for interrupt current prompt)\n const removeAction =\n 'remove' in item\n ? item.remove\n : {\n name: 'Delete',\n cb: () => api.deleteItem(this.#type, item.prompt[1])\n }\n return $el('div', { textContent: item.prompt[0] + ': ' }, [\n $el('button', {\n textContent: 'Load',\n onclick: async () => {\n await app.loadGraphData(\n item.prompt[3].extra_pnginfo.workflow,\n true,\n false\n )\n if ('outputs' in item) {\n app.nodeOutputs = {}\n for (const [key, value] of Object.entries(item.outputs)) {\n const realKey = item['meta']?.[key]?.display_node ?? key\n app.nodeOutputs[realKey] = value\n }\n }\n }\n }),\n $el('button', {\n textContent: removeAction.name,\n onclick: async () => {\n await removeAction.cb()\n await this.update()\n }\n })\n ])\n }\n )\n ])\n ]),\n $el('div.comfy-list-actions', [\n $el('button', {\n textContent: 'Clear ' + this.#text,\n onclick: async () => {\n await api.clearItems(this.#type)\n await this.load()\n }\n }),\n $el('button', { textContent: 'Refresh', onclick: () => this.load() })\n ])\n )\n }\n\n async update() {\n if (this.visible) {\n await this.load()\n }\n }\n\n async show() {\n this.element.style.display = 'block'\n this.button.textContent = 'Close'\n\n await this.load()\n }\n\n hide() {\n this.element.style.display = 'none'\n this.button.textContent = 'View ' + this.#text\n }\n\n toggle() {\n if (this.visible) {\n this.hide()\n return false\n } else {\n this.show()\n return true\n }\n }\n}\n\nexport class ComfyUI {\n app: ComfyApp\n dialog: _ComfyDialog\n settings: ComfySettingsDialog\n batchCount: number\n lastQueueSize: number\n queue: ComfyList\n history: ComfyList\n autoQueueMode: string\n graphHasChanged: boolean\n autoQueueEnabled: boolean\n menuHamburger: HTMLDivElement\n menuContainer: HTMLDivElement\n queueSize: Element\n restoreMenuPosition: () => void\n loadFile: () => void\n\n constructor(app) {\n this.app = app\n this.dialog = new ComfyDialog()\n this.settings = new ComfySettingsDialog(app)\n\n this.batchCount = 1\n this.lastQueueSize = 0\n this.queue = new ComfyList('Queue')\n this.history = new ComfyList('History', 'history', true)\n\n api.addEventListener('status', () => {\n this.queue.update()\n this.history.update()\n })\n\n this.setup(document.body)\n }\n\n setup(containerElement: HTMLElement) {\n const fileInput = $el('input', {\n id: 'comfy-file-input',\n type: 'file',\n accept: '.json,image/png,.latent,.safetensors,image/webp,audio/flac',\n style: { display: 'none' },\n parent: document.body,\n onchange: () => {\n app.handleFile(fileInput.files[0])\n }\n })\n\n this.loadFile = () => fileInput.click()\n\n const autoQueueModeEl = toggleSwitch(\n 'autoQueueMode',\n [\n {\n text: 'instant',\n tooltip: 'A new prompt will be queued as soon as the queue reaches 0'\n },\n {\n text: 'change',\n tooltip:\n 'A new prompt will be queued when the queue is at 0 and the graph is/has changed'\n }\n ],\n {\n onChange: (value) => {\n this.autoQueueMode = value.item.value\n }\n }\n )\n autoQueueModeEl.style.display = 'none'\n\n api.addEventListener('graphChanged', () => {\n if (this.autoQueueMode === 'change' && this.autoQueueEnabled === true) {\n if (this.lastQueueSize === 0) {\n this.graphHasChanged = false\n app.queuePrompt(0, this.batchCount)\n } else {\n this.graphHasChanged = true\n }\n }\n })\n\n this.menuHamburger = $el(\n 'div.comfy-menu-hamburger',\n {\n parent: containerElement,\n onclick: () => {\n this.menuContainer.style.display = 'block'\n this.menuHamburger.style.display = 'none'\n }\n },\n [$el('div'), $el('div'), $el('div')]\n ) as HTMLDivElement\n\n this.menuContainer = $el('div.comfy-menu', { parent: containerElement }, [\n $el(\n 'div.drag-handle.comfy-menu-header',\n {\n style: {\n overflow: 'hidden',\n position: 'relative',\n width: '100%',\n cursor: 'default'\n }\n },\n [\n $el('span.drag-handle'),\n $el('span.comfy-menu-queue-size', { $: (q) => (this.queueSize = q) }),\n $el('div.comfy-menu-actions', [\n $el('button.comfy-settings-btn', {\n textContent: '⚙️',\n onclick: showSettingsDialog\n }),\n $el('button.comfy-close-menu-btn', {\n textContent: '\\u00d7',\n onclick: () => {\n this.menuContainer.style.display = 'none'\n this.menuHamburger.style.display = 'flex'\n }\n })\n ])\n ]\n ),\n $el('button.comfy-queue-btn', {\n id: 'queue-button',\n textContent: 'Queue Prompt',\n onclick: () => app.queuePrompt(0, this.batchCount)\n }),\n $el('div', {}, [\n $el('label', { innerHTML: 'Extra options' }, [\n $el('input', {\n type: 'checkbox',\n onchange: (i) => {\n document.getElementById('extraOptions').style.display = i\n .srcElement.checked\n ? 'block'\n : 'none'\n this.batchCount = i.srcElement.checked\n ? Number.parseInt(\n (\n document.getElementById(\n 'batchCountInputRange'\n ) as HTMLInputElement\n ).value\n )\n : 1\n ;(\n document.getElementById('autoQueueCheckbox') as HTMLInputElement\n ).checked = false\n this.autoQueueEnabled = false\n }\n })\n ])\n ]),\n $el(\n 'div',\n { id: 'extraOptions', style: { width: '100%', display: 'none' } },\n [\n $el('div', [\n $el('label', { innerHTML: 'Batch count' }),\n $el('input', {\n id: 'batchCountInputNumber',\n type: 'number',\n value: this.batchCount,\n min: '1',\n style: { width: '35%', marginLeft: '0.4em' },\n oninput: (i) => {\n this.batchCount = i.target.value\n /* Even though an element with a type of range logically represents a number (since\n it's used for numeric input), the value it holds is still treated as a string in HTML and\n JavaScript. This behavior is consistent across all elements regardless of their type\n (like text, number, or range), where the .value property is always a string. */\n ;(\n document.getElementById(\n 'batchCountInputRange'\n ) as HTMLInputElement\n ).value = this.batchCount.toString()\n }\n }),\n $el('input', {\n id: 'batchCountInputRange',\n type: 'range',\n min: '1',\n max: '100',\n value: this.batchCount,\n oninput: (i) => {\n this.batchCount = i.srcElement.value\n // Note\n ;(\n document.getElementById(\n 'batchCountInputNumber'\n ) as HTMLInputElement\n ).value = i.srcElement.value\n }\n })\n ]),\n $el('div', [\n $el('label', {\n for: 'autoQueueCheckbox',\n innerHTML: 'Auto Queue'\n }),\n $el('input', {\n id: 'autoQueueCheckbox',\n type: 'checkbox',\n checked: false,\n title: 'Automatically queue prompt when the queue size hits 0',\n onchange: (e) => {\n this.autoQueueEnabled = e.target.checked\n autoQueueModeEl.style.display = this.autoQueueEnabled\n ? ''\n : 'none'\n }\n }),\n autoQueueModeEl\n ])\n ]\n ),\n $el('div.comfy-menu-btns', [\n $el('button', {\n id: 'queue-front-button',\n textContent: 'Queue Front',\n onclick: () => app.queuePrompt(-1, this.batchCount)\n }),\n $el('button', {\n $: (b) => (this.queue.button = b as HTMLButtonElement),\n id: 'comfy-view-queue-button',\n textContent: 'View Queue',\n onclick: () => {\n this.history.hide()\n this.queue.toggle()\n }\n }),\n $el('button', {\n $: (b) => (this.history.button = b as HTMLButtonElement),\n id: 'comfy-view-history-button',\n textContent: 'View History',\n onclick: () => {\n this.queue.hide()\n this.history.toggle()\n }\n })\n ]),\n this.queue.element,\n this.history.element,\n $el('button', {\n id: 'comfy-save-button',\n textContent: 'Save',\n onclick: () => {\n let filename = 'workflow.json'\n if (useSettingStore().get('Comfy.PromptFilename')) {\n filename = prompt('Save workflow as:', filename)\n if (!filename) return\n if (!filename.toLowerCase().endsWith('.json')) {\n filename += '.json'\n }\n }\n app.graphToPrompt().then((p) => {\n const json = JSON.stringify(p.workflow, null, 2) // convert the data to a JSON string\n const blob = new Blob([json], { type: 'application/json' })\n const url = URL.createObjectURL(blob)\n const a = $el('a', {\n href: url,\n download: filename,\n style: { display: 'none' },\n parent: document.body\n })\n a.click()\n setTimeout(function () {\n a.remove()\n window.URL.revokeObjectURL(url)\n }, 0)\n })\n }\n }),\n $el('button', {\n id: 'comfy-dev-save-api-button',\n textContent: 'Save (API Format)',\n style: { width: '100%', display: 'none' },\n onclick: () => {\n let filename = 'workflow_api.json'\n if (useSettingStore().get('Comfy.PromptFilename')) {\n filename = prompt('Save workflow (API) as:', filename)\n if (!filename) return\n if (!filename.toLowerCase().endsWith('.json')) {\n filename += '.json'\n }\n }\n app.graphToPrompt().then((p) => {\n const json = JSON.stringify(p.output, null, 2) // convert the data to a JSON string\n const blob = new Blob([json], { type: 'application/json' })\n const url = URL.createObjectURL(blob)\n const a = $el('a', {\n href: url,\n download: filename,\n style: { display: 'none' },\n parent: document.body\n })\n a.click()\n setTimeout(function () {\n a.remove()\n window.URL.revokeObjectURL(url)\n }, 0)\n })\n }\n }),\n $el('button', {\n id: 'comfy-load-button',\n textContent: 'Load',\n onclick: () => fileInput.click()\n }),\n $el('button', {\n id: 'comfy-refresh-button',\n textContent: 'Refresh',\n onclick: () => app.refreshComboInNodes()\n }),\n $el('button', {\n id: 'comfy-clipspace-button',\n textContent: 'Clipspace',\n // @ts-expect-error Move to ComfyApp\n onclick: () => app.openClipspace()\n }),\n $el('button', {\n id: 'comfy-clear-button',\n textContent: 'Clear',\n onclick: () => {\n if (\n !useSettingStore().get('Comfy.ConfirmClear') ||\n confirm('Clear workflow?')\n ) {\n app.clean()\n app.graph.clear()\n app.resetView()\n api.dispatchEvent(new CustomEvent('graphCleared'))\n }\n }\n }),\n $el('button', {\n id: 'comfy-load-default-button',\n textContent: 'Load Default',\n onclick: async () => {\n if (\n !useSettingStore().get('Comfy.ConfirmClear') ||\n confirm('Load default workflow?')\n ) {\n app.resetView()\n await app.loadGraphData()\n }\n }\n }),\n $el('button', {\n id: 'comfy-reset-view-button',\n textContent: 'Reset View',\n onclick: async () => {\n app.resetView()\n }\n }),\n $el('button', {\n id: 'comfy-group-selected-nodes-button',\n textContent: 'Group',\n hidden: true,\n onclick: () => {\n if (\n !app.canvas.selected_nodes ||\n Object.keys(app.canvas.selected_nodes).length === 0\n ) {\n useToastStore().add({\n severity: 'error',\n summary: 'No nodes selected',\n detail: 'Please select nodes to group',\n life: 3000\n })\n return\n }\n const group = new LGraphGroup()\n const padding = useSettingStore().get(\n 'Comfy.GroupSelectedNodes.Padding'\n )\n group.addNodes(Object.values(app.canvas.selected_nodes), padding)\n app.canvas.graph.add(group)\n useTitleEditorStore().titleEditorTarget = group\n }\n })\n ]) as HTMLDivElement\n\n this.restoreMenuPosition = dragElement(this.menuContainer, this.settings)\n\n this.setStatus({ exec_info: { queue_remaining: 'X' } })\n }\n\n setStatus(status) {\n this.queueSize.textContent =\n 'Queue size: ' + (status ? status.exec_info.queue_remaining : 'ERR')\n if (status) {\n if (\n this.lastQueueSize != 0 &&\n status.exec_info.queue_remaining == 0 &&\n this.autoQueueEnabled &&\n (this.autoQueueMode === 'instant' || this.graphHasChanged) &&\n !app.lastExecutionError\n ) {\n app.queuePrompt(0, this.batchCount)\n status.exec_info.queue_remaining += this.batchCount\n this.graphHasChanged = false\n }\n this.lastQueueSize = status.exec_info.queue_remaining\n }\n }\n}\n","import { $el, ComfyDialog } from './ui'\nimport { api } from './api'\nimport type { ComfyApp } from './app'\n\n$el('style', {\n textContent: `\n .comfy-logging-logs {\n display: grid;\n color: var(--fg-color);\n white-space: pre-wrap;\n }\n .comfy-logging-log {\n display: contents;\n }\n .comfy-logging-title {\n background: var(--tr-even-bg-color);\n font-weight: bold;\n margin-bottom: 5px;\n text-align: center;\n }\n .comfy-logging-log div {\n background: var(--row-bg);\n padding: 5px;\n }\n `,\n parent: document.body\n})\n\n// Stringify function supporting max depth and removal of circular references\n// https://stackoverflow.com/a/57193345\nfunction stringify(val, depth, replacer, space, onGetObjID?) {\n depth = isNaN(+depth) ? 1 : depth\n var recursMap = new WeakMap()\n function _build(val, depth, o?, a?, r?) {\n // (JSON.stringify() has it's own rules, which we respect here by using it for property iteration)\n return !val || typeof val != 'object'\n ? val\n : ((r = recursMap.has(val)),\n recursMap.set(val, true),\n (a = Array.isArray(val)),\n r\n ? (o = (onGetObjID && onGetObjID(val)) || null)\n : JSON.stringify(val, function (k, v) {\n if (a || depth > 0) {\n if (replacer) v = replacer(k, v)\n if (!k) return (a = Array.isArray(v)), (val = v)\n !o && (o = a ? [] : {})\n o[k] = _build(v, a ? depth : depth - 1)\n }\n }),\n o === void 0 ? (a ? [] : {}) : o)\n }\n return JSON.stringify(_build(val, depth), null, space)\n}\n\nconst jsonReplacer = (k, v, ui) => {\n if (v instanceof Array && v.length === 1) {\n v = v[0]\n }\n if (v instanceof Date) {\n v = v.toISOString()\n if (ui) {\n v = v.split('T')[1]\n }\n }\n if (v instanceof Error) {\n let err = ''\n if (v.name) err += v.name + '\\n'\n if (v.message) err += v.message + '\\n'\n if (v.stack) err += v.stack + '\\n'\n if (!err) {\n err = v.toString()\n }\n v = err\n }\n return v\n}\n\nconst fileInput: HTMLInputElement = $el('input', {\n type: 'file',\n accept: '.json',\n style: { display: 'none' },\n parent: document.body\n}) as HTMLInputElement\n\nclass ComfyLoggingDialog extends ComfyDialog {\n logging: any\n\n constructor(logging) {\n super()\n this.logging = logging\n }\n\n clear() {\n this.logging.clear()\n this.show()\n }\n\n export() {\n const blob = new Blob(\n [stringify([...this.logging.entries], 20, jsonReplacer, '\\t')],\n {\n type: 'application/json'\n }\n )\n const url = URL.createObjectURL(blob)\n const a = $el('a', {\n href: url,\n download: `comfyui-logs-${Date.now()}.json`,\n style: { display: 'none' },\n parent: document.body\n })\n a.click()\n setTimeout(function () {\n a.remove()\n window.URL.revokeObjectURL(url)\n }, 0)\n }\n\n import() {\n fileInput.onchange = () => {\n const reader = new FileReader()\n reader.onload = () => {\n fileInput.remove()\n try {\n const obj = JSON.parse(reader.result as string)\n if (obj instanceof Array) {\n this.show(obj)\n } else {\n throw new Error('Invalid file selected.')\n }\n } catch (error) {\n alert('Unable to load logs: ' + error.message)\n }\n }\n reader.readAsText(fileInput.files[0])\n }\n fileInput.click()\n }\n\n createButtons() {\n return [\n $el('button', {\n type: 'button',\n textContent: 'Clear',\n onclick: () => this.clear()\n }),\n $el('button', {\n type: 'button',\n textContent: 'Export logs...',\n onclick: () => this.export()\n }),\n $el('button', {\n type: 'button',\n textContent: 'View exported logs...',\n onclick: () => this.import()\n }),\n ...super.createButtons()\n ]\n }\n\n getTypeColor(type) {\n switch (type) {\n case 'error':\n return 'red'\n case 'warn':\n return 'orange'\n case 'debug':\n return 'dodgerblue'\n }\n }\n\n show(entries?: any[]) {\n if (!entries) entries = this.logging.entries\n this.element.style.width = '100%'\n const cols = {\n source: 'Source',\n type: 'Type',\n timestamp: 'Timestamp',\n message: 'Message'\n }\n const keys = Object.keys(cols)\n const headers = Object.values(cols).map((title) =>\n $el('div.comfy-logging-title', {\n textContent: title\n })\n )\n const rows = entries.map((entry, i) => {\n return $el(\n 'div.comfy-logging-log',\n {\n $: (el) =>\n el.style.setProperty(\n '--row-bg',\n `var(--tr-${i % 2 ? 'even' : 'odd'}-bg-color)`\n )\n },\n keys.map((key) => {\n let v = entry[key]\n let color\n if (key === 'type') {\n color = this.getTypeColor(v)\n } else {\n v = jsonReplacer(key, v, true)\n\n if (typeof v === 'object') {\n v = stringify(v, 5, jsonReplacer, ' ')\n }\n }\n\n return $el('div', {\n style: {\n color\n },\n textContent: v\n })\n })\n )\n })\n\n const grid = $el(\n 'div.comfy-logging-logs',\n {\n style: {\n gridTemplateColumns: `repeat(${headers.length}, 1fr)`\n }\n },\n [...headers, ...rows]\n )\n const els = [grid]\n if (!this.logging.enabled) {\n els.unshift(\n $el('h3', {\n style: { textAlign: 'center' },\n textContent: 'Logging is disabled'\n })\n )\n }\n super.show($el('div', els))\n }\n}\n\nexport class ComfyLogging {\n /**\n * @type Array<{ source: string, type: string, timestamp: Date, message: any }>\n */\n entries = []\n\n #enabled\n #console = {}\n\n app: ComfyApp\n dialog: ComfyLoggingDialog\n\n get enabled() {\n return this.#enabled\n }\n\n set enabled(value) {\n if (value === this.#enabled) return\n if (value) {\n this.patchConsole()\n } else {\n this.unpatchConsole()\n }\n this.#enabled = value\n }\n\n constructor(app) {\n this.app = app\n\n this.dialog = new ComfyLoggingDialog(this)\n this.addSetting()\n this.catchUnhandled()\n this.addInitData()\n }\n\n addSetting() {\n const settingId = 'Comfy.Logging.Enabled'\n const htmlSettingId = settingId.replaceAll('.', '-')\n const setting = this.app.ui.settings.addSetting({\n id: settingId,\n name: 'Enable logging',\n defaultValue: true,\n onChange: (value) => {\n this.enabled = value\n },\n type: (name, setter, value) => {\n return $el('tr', [\n $el('td', [\n $el('label', {\n textContent: 'Logging',\n for: htmlSettingId\n })\n ]),\n $el('td', [\n $el('input', {\n id: htmlSettingId,\n type: 'checkbox',\n checked: value,\n onchange: (event) => {\n setter(event.target.checked)\n }\n }),\n $el('button', {\n textContent: 'View Logs',\n onclick: () => {\n this.app.ui.settings.element.close()\n this.dialog.show()\n },\n style: {\n fontSize: '14px',\n display: 'block',\n marginTop: '5px'\n }\n })\n ])\n ])\n }\n })\n this.enabled = setting.value\n }\n\n patchConsole() {\n // Capture common console outputs\n const self = this\n for (const type of ['log', 'warn', 'error', 'debug']) {\n const orig = console[type]\n this.#console[type] = orig\n console[type] = function () {\n orig.apply(console, arguments)\n self.addEntry('console', type, ...arguments)\n }\n }\n }\n\n unpatchConsole() {\n // Restore original console functions\n for (const type of Object.keys(this.#console)) {\n console[type] = this.#console[type]\n }\n this.#console = {}\n }\n\n catchUnhandled() {\n // Capture uncaught errors\n window.addEventListener('error', (e) => {\n this.addEntry('window', 'error', e.error ?? 'Unknown error')\n return false\n })\n\n window.addEventListener('unhandledrejection', (e) => {\n this.addEntry('unhandledrejection', 'error', e.reason ?? 'Unknown error')\n })\n }\n\n clear() {\n this.entries = []\n }\n\n addEntry(source, type, ...args) {\n if (this.enabled) {\n this.entries.push({\n source,\n type,\n timestamp: new Date(),\n message: args\n })\n }\n }\n\n log(source, ...args) {\n this.addEntry(source, 'log', ...args)\n }\n\n async addInitData() {\n if (!this.enabled) return\n const source = 'ComfyUI.Logging'\n this.addEntry(source, 'debug', { UserAgent: navigator.userAgent })\n const systemStats = await api.getSystemStats()\n this.addEntry(source, 'debug', systemStats)\n }\n}\n","import { app, ANIM_PREVIEW_WIDGET } from './app'\nimport { LGraphCanvas, LGraphNode, LiteGraph } from '@comfyorg/litegraph'\nimport type { Vector4 } from '@comfyorg/litegraph'\n\nconst SIZE = Symbol()\n\ninterface Rect {\n height: number\n width: number\n x: number\n y: number\n}\n\nexport interface DOMWidget {\n type: string\n name: string\n computedHeight?: number\n element?: T\n options: any\n value?: any\n y?: number\n callback?: (value: any) => void\n draw?: (\n ctx: CanvasRenderingContext2D,\n node: LGraphNode,\n widgetWidth: number,\n y: number,\n widgetHeight: number\n ) => void\n onRemove?: () => void\n}\n\nfunction intersect(a: Rect, b: Rect): Vector4 | null {\n const x = Math.max(a.x, b.x)\n const num1 = Math.min(a.x + a.width, b.x + b.width)\n const y = Math.max(a.y, b.y)\n const num2 = Math.min(a.y + a.height, b.y + b.height)\n if (num1 >= x && num2 >= y) return [x, y, num1 - x, num2 - y]\n else return null\n}\n\nfunction getClipPath(\n node: LGraphNode,\n element: HTMLElement,\n canvasRect: DOMRect\n): string {\n const selectedNode: LGraphNode = Object.values(\n app.canvas.selected_nodes\n )[0] as LGraphNode\n if (selectedNode && selectedNode !== node) {\n const elRect = element.getBoundingClientRect()\n const MARGIN = 7\n const scale = app.canvas.ds.scale\n\n const bounding = selectedNode.getBounding()\n const intersection = intersect(\n {\n x: elRect.x / scale - canvasRect.left,\n y: elRect.y / scale - canvasRect.top,\n width: elRect.width / scale,\n height: elRect.height / scale\n },\n {\n x: selectedNode.pos[0] + app.canvas.ds.offset[0] - MARGIN,\n y:\n selectedNode.pos[1] +\n app.canvas.ds.offset[1] -\n LiteGraph.NODE_TITLE_HEIGHT -\n MARGIN,\n width: bounding[2] + MARGIN + MARGIN,\n height: bounding[3] + MARGIN + MARGIN\n }\n )\n\n if (!intersection) {\n return ''\n }\n\n const clipX = canvasRect.left + intersection[0] - elRect.x / scale + 'px'\n const clipY = canvasRect.top + intersection[1] - elRect.y / scale + 'px'\n const clipWidth = intersection[2] + 'px'\n const clipHeight = intersection[3] + 'px'\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%)`\n return path\n }\n return ''\n}\n\nfunction computeSize(size: [number, number]): void {\n if (this.widgets?.[0]?.last_y == null) return\n\n let y = this.widgets[0].last_y\n let freeSpace = size[1] - y\n\n let widgetHeight = 0\n let dom = []\n for (const w of this.widgets) {\n if (w.type === 'converted-widget') {\n // Ignore\n delete w.computedHeight\n } else if (w.computeSize) {\n widgetHeight += w.computeSize()[1] + 4\n } else if (w.element) {\n // Extract DOM widget size info\n const styles = getComputedStyle(w.element)\n let minHeight =\n w.options.getMinHeight?.() ??\n parseInt(styles.getPropertyValue('--comfy-widget-min-height'))\n let maxHeight =\n w.options.getMaxHeight?.() ??\n parseInt(styles.getPropertyValue('--comfy-widget-max-height'))\n\n let prefHeight =\n w.options.getHeight?.() ??\n styles.getPropertyValue('--comfy-widget-height')\n if (prefHeight.endsWith?.('%')) {\n prefHeight =\n size[1] *\n (parseFloat(prefHeight.substring(0, prefHeight.length - 1)) / 100)\n } else {\n prefHeight = parseInt(prefHeight)\n if (isNaN(minHeight)) {\n minHeight = prefHeight\n }\n }\n if (isNaN(minHeight)) {\n minHeight = 50\n }\n if (!isNaN(maxHeight)) {\n if (!isNaN(prefHeight)) {\n prefHeight = Math.min(prefHeight, maxHeight)\n } else {\n prefHeight = maxHeight\n }\n }\n dom.push({\n minHeight,\n prefHeight,\n w\n })\n } else {\n widgetHeight += LiteGraph.NODE_WIDGET_HEIGHT + 4\n }\n }\n\n freeSpace -= widgetHeight\n\n // Calculate sizes with all widgets at their min height\n const prefGrow = [] // Nodes that want to grow to their prefd size\n const canGrow = [] // Nodes that can grow to auto size\n let growBy = 0\n for (const d of dom) {\n freeSpace -= d.minHeight\n if (isNaN(d.prefHeight)) {\n canGrow.push(d)\n d.w.computedHeight = d.minHeight\n } else {\n const diff = d.prefHeight - d.minHeight\n if (diff > 0) {\n prefGrow.push(d)\n growBy += diff\n d.diff = diff\n } else {\n d.w.computedHeight = d.minHeight\n }\n }\n }\n\n if (this.imgs && !this.widgets.find((w) => w.name === ANIM_PREVIEW_WIDGET)) {\n // Allocate space for image\n freeSpace -= 220\n }\n\n this.freeWidgetSpace = freeSpace\n\n if (freeSpace < 0) {\n // Not enough space for all widgets so we need to grow\n size[1] -= freeSpace\n this.graph.setDirtyCanvas(true)\n } else {\n // Share the space between each\n const growDiff = freeSpace - growBy\n if (growDiff > 0) {\n // All pref sizes can be fulfilled\n freeSpace = growDiff\n for (const d of prefGrow) {\n d.w.computedHeight = d.prefHeight\n }\n } else {\n // We need to grow evenly\n const shared = -growDiff / prefGrow.length\n for (const d of prefGrow) {\n d.w.computedHeight = d.prefHeight - shared\n }\n freeSpace = 0\n }\n\n if (freeSpace > 0 && canGrow.length) {\n // Grow any that are auto height\n const shared = freeSpace / canGrow.length\n for (const d of canGrow) {\n d.w.computedHeight += shared\n }\n }\n }\n\n // Position each of the widgets\n for (const w of this.widgets) {\n w.y = y\n if (w.computedHeight) {\n y += w.computedHeight\n } else if (w.computeSize) {\n y += w.computeSize()[1] + 4\n } else {\n y += LiteGraph.NODE_WIDGET_HEIGHT + 4\n }\n }\n}\n\n// Override the compute visible nodes function to allow us to hide/show DOM elements when the node goes offscreen\nconst elementWidgets = new Set()\n//@ts-ignore\nconst computeVisibleNodes = LGraphCanvas.prototype.computeVisibleNodes\n//@ts-ignore\nLGraphCanvas.prototype.computeVisibleNodes = function (): LGraphNode[] {\n const visibleNodes = computeVisibleNodes.apply(this, arguments)\n\n for (const node of app.graph.nodes) {\n if (elementWidgets.has(node)) {\n const hidden = visibleNodes.indexOf(node) === -1\n for (const w of node.widgets) {\n if (w.element) {\n w.element.dataset.isInVisibleNodes = hidden ? 'false' : 'true'\n const shouldOtherwiseHide = w.element.dataset.shouldHide === 'true'\n const isCollapsed = w.element.dataset.collapsed === 'true'\n const wasHidden = w.element.hidden\n const actualHidden = hidden || shouldOtherwiseHide || isCollapsed\n w.element.hidden = actualHidden\n w.element.style.display = actualHidden ? 'none' : null\n if (actualHidden && !wasHidden) {\n w.options.onHide?.(w)\n }\n }\n }\n }\n }\n\n return visibleNodes\n}\n\nlet enableDomClipping = true\n\nexport function addDomClippingSetting(): void {\n app.ui.settings.addSetting({\n id: 'Comfy.DOMClippingEnabled',\n category: ['Comfy', 'Node', 'DOMClippingEnabled'],\n name: 'Enable DOM element clipping (enabling may reduce performance)',\n type: 'boolean',\n defaultValue: enableDomClipping,\n onChange(value) {\n enableDomClipping = !!value\n }\n })\n}\n\nLGraphNode.prototype.addDOMWidget = function (\n name: string,\n type: string,\n element: HTMLElement,\n options: Record\n): DOMWidget {\n options = { hideOnZoom: true, selectOn: ['focus', 'click'], ...options }\n\n if (!element.parentElement) {\n app.canvasContainer.append(element)\n }\n element.hidden = true\n element.style.display = 'none'\n\n let mouseDownHandler\n if (element.blur) {\n mouseDownHandler = (event) => {\n if (!element.contains(event.target)) {\n element.blur()\n }\n }\n document.addEventListener('mousedown', mouseDownHandler)\n }\n\n const { nodeData } = this.constructor\n const tooltip = (nodeData?.input.required?.[name] ??\n nodeData?.input.optional?.[name])?.[1]?.tooltip\n if (tooltip && !element.title) {\n element.title = tooltip\n }\n\n const widget: DOMWidget = {\n type,\n name,\n get value() {\n return options.getValue?.() ?? undefined\n },\n set value(v) {\n options.setValue?.(v)\n widget.callback?.(widget.value)\n },\n draw: function (\n ctx: CanvasRenderingContext2D,\n node: LGraphNode,\n widgetWidth: number,\n y: number,\n widgetHeight: number\n ) {\n if (widget.computedHeight == null) {\n computeSize.call(node, node.size)\n }\n\n const hidden =\n (!!options.hideOnZoom && app.canvas.ds.scale < 0.5) ||\n widget.computedHeight <= 0 ||\n widget.type === 'converted-widget' ||\n widget.type === 'hidden'\n element.dataset.shouldHide = hidden ? 'true' : 'false'\n const isInVisibleNodes = element.dataset.isInVisibleNodes === 'true'\n const isCollapsed = element.dataset.collapsed === 'true'\n const actualHidden = hidden || !isInVisibleNodes || isCollapsed\n const wasHidden = element.hidden\n element.hidden = actualHidden\n element.style.display = actualHidden ? 'none' : null\n if (actualHidden && !wasHidden) {\n widget.options.onHide?.(widget)\n }\n if (actualHidden) {\n return\n }\n\n const margin = 10\n const elRect = ctx.canvas.getBoundingClientRect()\n const transform = new DOMMatrix()\n .scaleSelf(\n elRect.width / ctx.canvas.width,\n elRect.height / ctx.canvas.height\n )\n .multiplySelf(ctx.getTransform())\n .translateSelf(margin, margin + y)\n\n const scale = new DOMMatrix().scaleSelf(transform.a, transform.d)\n\n Object.assign(element.style, {\n transformOrigin: '0 0',\n transform: scale,\n left: `${transform.a + transform.e}px`,\n top: `${transform.d + transform.f}px`,\n width: `${widgetWidth - margin * 2}px`,\n height: `${(widget.computedHeight ?? 50) - margin * 2}px`,\n position: 'absolute',\n zIndex: app.graph.nodes.indexOf(node)\n })\n\n if (enableDomClipping) {\n element.style.clipPath = getClipPath(node, element, elRect)\n element.style.willChange = 'clip-path'\n }\n\n this.options.onDraw?.(widget)\n },\n element,\n options,\n onRemove() {\n if (mouseDownHandler) {\n document.removeEventListener('mousedown', mouseDownHandler)\n }\n element.remove()\n }\n }\n\n for (const evt of options.selectOn) {\n element.addEventListener(evt, () => {\n app.canvas.selectNode(this)\n app.canvas.bringToFront(this)\n })\n }\n\n this.addCustomWidget(widget)\n elementWidgets.add(this)\n\n const collapse = this.collapse\n this.collapse = function () {\n collapse.apply(this, arguments)\n if (this.flags?.collapsed) {\n element.hidden = true\n element.style.display = 'none'\n }\n element.dataset.collapsed = this.flags?.collapsed ? 'true' : 'false'\n }\n\n const onRemoved = this.onRemoved\n this.onRemoved = function () {\n element.remove()\n elementWidgets.delete(this)\n onRemoved?.apply(this, arguments)\n }\n\n if (!this[SIZE]) {\n this[SIZE] = true\n const onResize = this.onResize\n this.onResize = function (size) {\n options.beforeResize?.call(widget, this)\n computeSize.call(this, size)\n onResize?.apply(this, arguments)\n options.afterResize?.call(widget, this)\n }\n }\n\n return widget\n}\n","import { api } from './api'\nimport './domWidget'\nimport type { ComfyApp } from './app'\nimport type { IWidget, LGraphNode } from '@comfyorg/litegraph'\nimport { ComfyNodeDef } from '@/types/apiTypes'\nimport { useSettingStore } from '@/stores/settingStore'\n\nexport type ComfyWidgetConstructor = (\n node: LGraphNode,\n inputName: string,\n inputData: ComfyNodeDef,\n app?: ComfyApp,\n widgetName?: string\n) => { widget: IWidget; minWidth?: number; minHeight?: number }\n\nlet controlValueRunBefore = false\nexport function updateControlWidgetLabel(widget) {\n let replacement = 'after'\n let find = 'before'\n if (controlValueRunBefore) {\n ;[find, replacement] = [replacement, find]\n }\n widget.label = (widget.label ?? widget.name).replace(find, replacement)\n}\n\nconst IS_CONTROL_WIDGET = Symbol()\nconst HAS_EXECUTED = Symbol()\n\nfunction getNumberDefaults(\n inputData: ComfyNodeDef,\n defaultStep,\n precision,\n enable_rounding\n) {\n let defaultVal = inputData[1]['default']\n let { min, max, step, round } = inputData[1]\n\n if (defaultVal == undefined) defaultVal = 0\n if (min == undefined) min = 0\n if (max == undefined) max = 2048\n if (step == undefined) step = defaultStep\n // precision is the number of decimal places to show.\n // by default, display the the smallest number of decimal places such that changes of size step are visible.\n if (precision == undefined) {\n precision = Math.max(-Math.floor(Math.log10(step)), 0)\n }\n\n if (enable_rounding && (round == undefined || round === true)) {\n // by default, round the value to those decimal places shown.\n round = Math.round(1000000 * Math.pow(0.1, precision)) / 1000000\n }\n\n return {\n val: defaultVal,\n config: { min, max, step: 10.0 * step, round, precision }\n }\n}\n\nexport function addValueControlWidget(\n node,\n targetWidget,\n defaultValue = 'randomize',\n values,\n widgetName,\n inputData: ComfyNodeDef\n) {\n let name = inputData[1]?.control_after_generate\n if (typeof name !== 'string') {\n name = widgetName\n }\n const widgets = addValueControlWidgets(\n node,\n targetWidget,\n defaultValue,\n {\n addFilterList: false,\n controlAfterGenerateName: name\n },\n inputData\n )\n return widgets[0]\n}\n\nexport function addValueControlWidgets(\n node,\n targetWidget,\n defaultValue = 'randomize',\n options,\n inputData: ComfyNodeDef\n) {\n if (!defaultValue) defaultValue = 'randomize'\n if (!options) options = {}\n\n const getName = (defaultName, optionName) => {\n let name = defaultName\n if (options[optionName]) {\n name = options[optionName]\n } else if (typeof inputData?.[1]?.[defaultName] === 'string') {\n name = inputData?.[1]?.[defaultName]\n } else if (inputData?.[1]?.control_prefix) {\n name = inputData?.[1]?.control_prefix + ' ' + name\n }\n return name\n }\n\n const widgets = []\n const valueControl = node.addWidget(\n 'combo',\n getName('control_after_generate', 'controlAfterGenerateName'),\n defaultValue,\n function () {},\n {\n values: ['fixed', 'increment', 'decrement', 'randomize'],\n serialize: false // Don't include this in prompt.\n }\n )\n valueControl.tooltip =\n 'Allows the linked widget to be changed automatically, for example randomizing the noise seed.'\n valueControl[IS_CONTROL_WIDGET] = true\n updateControlWidgetLabel(valueControl)\n widgets.push(valueControl)\n\n const isCombo = targetWidget.type === 'combo'\n let comboFilter\n if (isCombo) {\n valueControl.options.values.push('increment-wrap')\n }\n if (isCombo && options.addFilterList !== false) {\n comboFilter = node.addWidget(\n 'string',\n getName('control_filter_list', 'controlFilterListName'),\n '',\n function () {},\n {\n serialize: false // Don't include this in prompt.\n }\n )\n updateControlWidgetLabel(comboFilter)\n comboFilter.tooltip =\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'.\"\n\n widgets.push(comboFilter)\n }\n\n const applyWidgetControl = () => {\n var v = valueControl.value\n\n if (isCombo && v !== 'fixed') {\n let values = targetWidget.options.values\n const filter = comboFilter?.value\n if (filter) {\n let check\n if (filter.startsWith('/') && filter.endsWith('/')) {\n try {\n const regex = new RegExp(filter.substring(1, filter.length - 1))\n check = (item) => regex.test(item)\n } catch (error) {\n console.error(\n 'Error constructing RegExp filter for node ' + node.id,\n filter,\n error\n )\n }\n }\n if (!check) {\n const lower = filter.toLocaleLowerCase()\n check = (item) => item.toLocaleLowerCase().includes(lower)\n }\n values = values.filter((item) => check(item))\n if (!values.length && targetWidget.options.values.length) {\n console.warn(\n 'Filter for node ' + node.id + ' has filtered out all items',\n filter\n )\n }\n }\n let current_index = values.indexOf(targetWidget.value)\n let current_length = values.length\n\n switch (v) {\n case 'increment':\n current_index += 1\n break\n case 'increment-wrap':\n current_index += 1\n if (current_index >= current_length) {\n current_index = 0\n }\n break\n case 'decrement':\n current_index -= 1\n break\n case 'randomize':\n current_index = Math.floor(Math.random() * current_length)\n break\n default:\n break\n }\n current_index = Math.max(0, current_index)\n current_index = Math.min(current_length - 1, current_index)\n if (current_index >= 0) {\n let value = values[current_index]\n targetWidget.value = value\n targetWidget.callback(value)\n }\n } else {\n //number\n let min = targetWidget.options.min\n let max = targetWidget.options.max\n // limit to something that javascript can handle\n max = Math.min(1125899906842624, max)\n min = Math.max(-1125899906842624, min)\n let range = (max - min) / (targetWidget.options.step / 10)\n\n //adjust values based on valueControl Behaviour\n switch (v) {\n case 'fixed':\n break\n case 'increment':\n targetWidget.value += targetWidget.options.step / 10\n break\n case 'decrement':\n targetWidget.value -= targetWidget.options.step / 10\n break\n case 'randomize':\n targetWidget.value =\n Math.floor(Math.random() * range) *\n (targetWidget.options.step / 10) +\n min\n break\n default:\n break\n }\n /*check if values are over or under their respective\n * ranges and set them to min or max.*/\n if (targetWidget.value < min) targetWidget.value = min\n\n if (targetWidget.value > max) targetWidget.value = max\n targetWidget.callback(targetWidget.value)\n }\n }\n\n valueControl.beforeQueued = () => {\n if (controlValueRunBefore) {\n // Don't run on first execution\n if (valueControl[HAS_EXECUTED]) {\n applyWidgetControl()\n }\n }\n valueControl[HAS_EXECUTED] = true\n }\n\n valueControl.afterQueued = () => {\n if (!controlValueRunBefore) {\n applyWidgetControl()\n }\n }\n\n return widgets\n}\n\nfunction seedWidget(node, inputName, inputData: ComfyNodeDef, app, widgetName) {\n const seed = createIntWidget(node, inputName, inputData, app, true)\n const seedControl = addValueControlWidget(\n node,\n seed.widget,\n 'randomize',\n undefined,\n widgetName,\n inputData\n )\n\n seed.widget.linkedWidgets = [seedControl]\n return seed\n}\n\nfunction createIntWidget(\n node,\n inputName,\n inputData: ComfyNodeDef,\n app,\n isSeedInput: boolean = false\n) {\n const control = inputData[1]?.control_after_generate\n if (!isSeedInput && control) {\n return seedWidget(\n node,\n inputName,\n inputData,\n app,\n typeof control === 'string' ? control : undefined\n )\n }\n\n let widgetType = isSlider(inputData[1]['display'], app)\n const { val, config } = getNumberDefaults(inputData, 1, 0, true)\n Object.assign(config, { precision: 0 })\n return {\n widget: node.addWidget(\n widgetType,\n inputName,\n val,\n function (v) {\n const s = this.options.step / 10\n let sh = this.options.min % s\n if (isNaN(sh)) {\n sh = 0\n }\n this.value = Math.round((v - sh) / s) * s + sh\n },\n config\n )\n }\n}\n\nfunction addMultilineWidget(node, name: string, opts, app: ComfyApp) {\n const inputEl = document.createElement('textarea')\n inputEl.className = 'comfy-multiline-input'\n inputEl.value = opts.defaultVal\n inputEl.placeholder = opts.placeholder || name\n if (app.vueAppReady) {\n inputEl.spellcheck = useSettingStore().get(\n 'Comfy.TextareaWidget.Spellcheck'\n )\n }\n\n const widget = node.addDOMWidget(name, 'customtext', inputEl, {\n getValue() {\n return inputEl.value\n },\n setValue(v) {\n inputEl.value = v\n }\n })\n widget.inputEl = inputEl\n\n inputEl.addEventListener('input', () => {\n widget.callback?.(widget.value)\n })\n\n return { minWidth: 400, minHeight: 200, widget }\n}\n\nfunction isSlider(display, app) {\n if (app.ui.settings.getSettingValue('Comfy.DisableSliders')) {\n return 'number'\n }\n\n return display === 'slider' ? 'slider' : 'number'\n}\n\nexport function initWidgets(app) {\n app.ui.settings.addSetting({\n id: 'Comfy.WidgetControlMode',\n category: ['Comfy', 'Node Widget', 'WidgetControlMode'],\n name: 'Widget control mode',\n tooltip:\n 'Controls when widget values are updated (randomize/increment/decrement), either before the prompt is queued or after.',\n type: 'combo',\n defaultValue: 'after',\n options: ['before', 'after'],\n onChange(value) {\n controlValueRunBefore = value === 'before'\n for (const n of app.graph.nodes) {\n if (!n.widgets) continue\n for (const w of n.widgets) {\n if (w[IS_CONTROL_WIDGET]) {\n updateControlWidgetLabel(w)\n if (w.linkedWidgets) {\n for (const l of w.linkedWidgets) {\n updateControlWidgetLabel(l)\n }\n }\n }\n }\n }\n app.graph.setDirtyCanvas(true)\n }\n })\n}\n\nexport const ComfyWidgets: Record = {\n 'INT:seed': seedWidget,\n 'INT:noise_seed': seedWidget,\n FLOAT(node, inputName, inputData: ComfyNodeDef, app) {\n let widgetType: 'number' | 'slider' = isSlider(inputData[1]['display'], app)\n let precision = app.ui.settings.getSettingValue(\n 'Comfy.FloatRoundingPrecision'\n )\n let disable_rounding = app.ui.settings.getSettingValue(\n 'Comfy.DisableFloatRounding'\n )\n if (precision == 0) precision = undefined\n const { val, config } = getNumberDefaults(\n inputData,\n 0.5,\n precision,\n !disable_rounding\n )\n return {\n widget: node.addWidget(\n widgetType,\n inputName,\n val,\n function (v) {\n if (config.round) {\n this.value =\n Math.round((v + Number.EPSILON) / config.round) * config.round\n if (this.value > config.max) this.value = config.max\n if (this.value < config.min) this.value = config.min\n } else {\n this.value = v\n }\n },\n config\n )\n }\n },\n INT(node, inputName, inputData: ComfyNodeDef, app) {\n return createIntWidget(node, inputName, inputData, app)\n },\n BOOLEAN(node, inputName, inputData) {\n let defaultVal = false\n let options = {}\n if (inputData[1]) {\n if (inputData[1].default) defaultVal = inputData[1].default\n if (inputData[1].label_on) options['on'] = inputData[1].label_on\n if (inputData[1].label_off) options['off'] = inputData[1].label_off\n }\n return {\n widget: node.addWidget('toggle', inputName, defaultVal, () => {}, options)\n }\n },\n STRING(node, inputName, inputData: ComfyNodeDef, app) {\n const defaultVal = inputData[1].default || ''\n const multiline = !!inputData[1].multiline\n\n let res\n if (multiline) {\n res = addMultilineWidget(\n node,\n inputName,\n { defaultVal, ...inputData[1] },\n app\n )\n } else {\n res = {\n widget: node.addWidget('text', inputName, defaultVal, () => {}, {})\n }\n }\n\n if (inputData[1].dynamicPrompts != undefined)\n res.widget.dynamicPrompts = inputData[1].dynamicPrompts\n\n return res\n },\n COMBO(node, inputName, inputData: ComfyNodeDef) {\n const type = inputData[0]\n let defaultValue = type[0]\n if (inputData[1] && inputData[1].default) {\n defaultValue = inputData[1].default\n }\n const res = {\n widget: node.addWidget('combo', inputName, defaultValue, () => {}, {\n values: type\n })\n }\n if (inputData[1]?.control_after_generate) {\n // TODO make combo handle a widget node type?\n res.widget.linkedWidgets = addValueControlWidgets(\n node,\n res.widget,\n undefined,\n undefined,\n inputData\n )\n }\n return res\n },\n IMAGEUPLOAD(\n node: LGraphNode,\n inputName: string,\n inputData: ComfyNodeDef,\n app\n ) {\n // TODO make image upload handle a custom node type?\n const imageWidget = node.widgets.find(\n (w) => w.name === (inputData[1]?.widget ?? 'image')\n )\n let uploadWidget\n\n function showImage(name) {\n const img = new Image()\n img.onload = () => {\n // @ts-expect-error\n node.imgs = [img]\n app.graph.setDirtyCanvas(true)\n }\n let folder_separator = name.lastIndexOf('/')\n let subfolder = ''\n if (folder_separator > -1) {\n subfolder = name.substring(0, folder_separator)\n name = name.substring(folder_separator + 1)\n }\n img.src = api.apiURL(\n `/view?filename=${encodeURIComponent(name)}&type=input&subfolder=${subfolder}${app.getPreviewFormatParam()}${app.getRandParam()}`\n )\n // @ts-expect-error\n node.setSizeForImage?.()\n }\n\n var default_value = imageWidget.value\n Object.defineProperty(imageWidget, 'value', {\n set: function (value) {\n this._real_value = value\n },\n\n get: function () {\n if (!this._real_value) {\n return default_value\n }\n\n let value = this._real_value\n if (value.filename) {\n let real_value = value\n value = ''\n if (real_value.subfolder) {\n value = real_value.subfolder + '/'\n }\n\n value += real_value.filename\n\n if (real_value.type && real_value.type !== 'input')\n value += ` [${real_value.type}]`\n }\n return value\n }\n })\n\n // Add our own callback to the combo widget to render an image when it changes\n // TODO: Explain this?\n // @ts-expect-error\n const cb = node.callback\n imageWidget.callback = function () {\n showImage(imageWidget.value)\n if (cb) {\n return cb.apply(this, arguments)\n }\n }\n\n // On load if we have a value then render the image\n // The value isnt set immediately so we need to wait a moment\n // No change callbacks seem to be fired on initial setting of the value\n requestAnimationFrame(() => {\n if (imageWidget.value) {\n showImage(imageWidget.value)\n }\n })\n\n async function uploadFile(file, updateNode, pasted = false) {\n try {\n // Wrap file in formdata so it includes filename\n const body = new FormData()\n body.append('image', file)\n if (pasted) body.append('subfolder', 'pasted')\n const resp = await api.fetchApi('/upload/image', {\n method: 'POST',\n body\n })\n\n if (resp.status === 200) {\n const data = await resp.json()\n // Add the file to the dropdown list and update the widget value\n let path = data.name\n if (data.subfolder) path = data.subfolder + '/' + path\n\n if (!imageWidget.options.values.includes(path)) {\n imageWidget.options.values.push(path)\n }\n\n if (updateNode) {\n showImage(path)\n imageWidget.value = path\n }\n } else {\n alert(resp.status + ' - ' + resp.statusText)\n }\n } catch (error) {\n alert(error)\n }\n }\n\n const fileInput = document.createElement('input')\n Object.assign(fileInput, {\n type: 'file',\n accept: 'image/jpeg,image/png,image/webp',\n style: 'display: none',\n onchange: async () => {\n if (fileInput.files.length) {\n await uploadFile(fileInput.files[0], true)\n }\n }\n })\n document.body.append(fileInput)\n\n // Create the button widget for selecting the files\n uploadWidget = node.addWidget('button', inputName, 'image', () => {\n fileInput.click()\n })\n uploadWidget.label = 'choose file to upload'\n uploadWidget.serialize = false\n\n // Add handler to check if an image is being dragged over our node\n // @ts-expect-error\n node.onDragOver = function (e) {\n if (e.dataTransfer && e.dataTransfer.items) {\n const image = [...e.dataTransfer.items].find((f) => f.kind === 'file')\n return !!image\n }\n\n return false\n }\n\n // On drop upload files\n // @ts-expect-error\n node.onDragDrop = function (e) {\n console.log('onDragDrop called')\n let handled = false\n for (const file of e.dataTransfer.files) {\n if (file.type.startsWith('image/')) {\n uploadFile(file, !handled) // Dont await these, any order is fine, only update on first one\n handled = true\n }\n }\n\n return handled\n }\n\n // @ts-expect-error\n node.pasteFile = function (file) {\n if (file.type.startsWith('image/')) {\n const is_pasted =\n file.name === 'image.png' && file.lastModified - Date.now() < 2000\n uploadFile(file, true, is_pasted)\n return true\n }\n return false\n }\n\n return { widget: uploadWidget }\n }\n}\n","import type { ComfyWorkflowJSON } from '@/types/comfyWorkflow'\n\nexport const defaultGraph: ComfyWorkflowJSON = {\n last_node_id: 9,\n last_link_id: 9,\n nodes: [\n {\n id: 7,\n type: 'CLIPTextEncode',\n pos: [413, 389],\n size: [425.27801513671875, 180.6060791015625],\n flags: {},\n order: 3,\n mode: 0,\n inputs: [{ name: 'clip', type: 'CLIP', link: 5 }],\n outputs: [\n {\n name: 'CONDITIONING',\n type: 'CONDITIONING',\n links: [6],\n slot_index: 0\n }\n ],\n properties: {},\n widgets_values: ['text, watermark']\n },\n {\n id: 6,\n type: 'CLIPTextEncode',\n pos: [415, 186],\n size: [422.84503173828125, 164.31304931640625],\n flags: {},\n order: 2,\n mode: 0,\n inputs: [{ name: 'clip', type: 'CLIP', link: 3 }],\n outputs: [\n {\n name: 'CONDITIONING',\n type: 'CONDITIONING',\n links: [4],\n slot_index: 0\n }\n ],\n properties: {},\n widgets_values: [\n 'beautiful scenery nature glass bottle landscape, , purple galaxy bottle,'\n ]\n },\n {\n id: 5,\n type: 'EmptyLatentImage',\n pos: [473, 609],\n size: [315, 106],\n flags: {},\n order: 1,\n mode: 0,\n outputs: [{ name: 'LATENT', type: 'LATENT', links: [2], slot_index: 0 }],\n properties: {},\n widgets_values: [512, 512, 1]\n },\n {\n id: 3,\n type: 'KSampler',\n pos: [863, 186],\n size: [315, 262],\n flags: {},\n order: 4,\n mode: 0,\n inputs: [\n { name: 'model', type: 'MODEL', link: 1 },\n { name: 'positive', type: 'CONDITIONING', link: 4 },\n { name: 'negative', type: 'CONDITIONING', link: 6 },\n { name: 'latent_image', type: 'LATENT', link: 2 }\n ],\n outputs: [{ name: 'LATENT', type: 'LATENT', links: [7], slot_index: 0 }],\n properties: {},\n widgets_values: [156680208700286, true, 20, 8, 'euler', 'normal', 1]\n },\n {\n id: 8,\n type: 'VAEDecode',\n pos: [1209, 188],\n size: [210, 46],\n flags: {},\n order: 5,\n mode: 0,\n inputs: [\n { name: 'samples', type: 'LATENT', link: 7 },\n { name: 'vae', type: 'VAE', link: 8 }\n ],\n outputs: [{ name: 'IMAGE', type: 'IMAGE', links: [9], slot_index: 0 }],\n properties: {}\n },\n {\n id: 9,\n type: 'SaveImage',\n pos: [1451, 189],\n size: [210, 26],\n flags: {},\n order: 6,\n mode: 0,\n inputs: [{ name: 'images', type: 'IMAGE', link: 9 }],\n properties: {}\n },\n {\n id: 4,\n type: 'CheckpointLoaderSimple',\n pos: [26, 474],\n size: [315, 98],\n flags: {},\n order: 0,\n mode: 0,\n outputs: [\n { name: 'MODEL', type: 'MODEL', links: [1], slot_index: 0 },\n { name: 'CLIP', type: 'CLIP', links: [3, 5], slot_index: 1 },\n { name: 'VAE', type: 'VAE', links: [8], slot_index: 2 }\n ],\n properties: {},\n widgets_values: ['v1-5-pruned-emaonly.ckpt']\n }\n ],\n links: [\n [1, 4, 0, 3, 0, 'MODEL'],\n [2, 5, 0, 3, 3, 'LATENT'],\n [3, 4, 1, 6, 0, 'CLIP'],\n [4, 6, 0, 3, 1, 'CONDITIONING'],\n [5, 4, 1, 7, 0, 'CLIP'],\n [6, 7, 0, 3, 2, 'CONDITIONING'],\n [7, 3, 0, 8, 0, 'LATENT'],\n [8, 4, 2, 8, 1, 'VAE'],\n [9, 8, 0, 9, 0, 'IMAGE']\n ],\n groups: [],\n config: {},\n extra: {},\n version: 0.4\n}\n","export function getFromPngBuffer(buffer: ArrayBuffer) {\n // Get the PNG data as a Uint8Array\n const pngData = new Uint8Array(buffer)\n const dataView = new DataView(pngData.buffer)\n\n // Check that the PNG signature is present\n if (dataView.getUint32(0) !== 0x89504e47) {\n console.error('Not a valid PNG file')\n return\n }\n\n // Start searching for chunks after the PNG signature\n let offset = 8\n let txt_chunks: Record = {}\n // Loop through the chunks in the PNG file\n while (offset < pngData.length) {\n // Get the length of the chunk\n const length = dataView.getUint32(offset)\n // Get the chunk type\n const type = String.fromCharCode(...pngData.slice(offset + 4, offset + 8))\n if (type === 'tEXt' || type == 'comf' || type === 'iTXt') {\n // Get the keyword\n let keyword_end = offset + 8\n while (pngData[keyword_end] !== 0) {\n keyword_end++\n }\n const keyword = String.fromCharCode(\n ...pngData.slice(offset + 8, keyword_end)\n )\n // Get the text\n const contentArraySegment = pngData.slice(\n keyword_end + 1,\n offset + 8 + length\n )\n const contentJson = new TextDecoder('utf-8').decode(contentArraySegment)\n txt_chunks[keyword] = contentJson\n }\n\n offset += 12 + length\n }\n return txt_chunks\n}\n\nexport function getFromPngFile(file: File) {\n return new Promise>((r) => {\n const reader = new FileReader()\n reader.onload = (event) => {\n r(getFromPngBuffer(event.target.result as ArrayBuffer))\n }\n\n reader.readAsArrayBuffer(file)\n })\n}\n","export function getFromFlacBuffer(buffer: ArrayBuffer): Record {\n const dataView = new DataView(buffer)\n\n // Verify the FLAC signature\n const signature = String.fromCharCode(...new Uint8Array(buffer, 0, 4))\n if (signature !== 'fLaC') {\n console.error('Not a valid FLAC file')\n return\n }\n\n // Parse metadata blocks\n let offset = 4\n let vorbisComment = null\n while (offset < dataView.byteLength) {\n const isLastBlock = dataView.getUint8(offset) & 0x80\n const blockType = dataView.getUint8(offset) & 0x7f\n const blockSize = dataView.getUint32(offset, false) & 0xffffff\n offset += 4\n\n if (blockType === 4) {\n // Vorbis Comment block type\n vorbisComment = parseVorbisComment(\n new DataView(buffer, offset, blockSize)\n )\n }\n\n offset += blockSize\n if (isLastBlock) break\n }\n\n return vorbisComment\n}\n\nexport function getFromFlacFile(file: File): Promise> {\n return new Promise((r) => {\n const reader = new FileReader()\n reader.onload = function (event) {\n const arrayBuffer = event.target.result as ArrayBuffer\n r(getFromFlacBuffer(arrayBuffer))\n }\n reader.readAsArrayBuffer(file)\n })\n}\n\n// Function to parse the Vorbis Comment block\nfunction parseVorbisComment(dataView: DataView): Record {\n let offset = 0\n const vendorLength = dataView.getUint32(offset, true)\n offset += 4\n const vendorString = getString(dataView, offset, vendorLength)\n offset += vendorLength\n\n const userCommentListLength = dataView.getUint32(offset, true)\n offset += 4\n const comments = {}\n for (let i = 0; i < userCommentListLength; i++) {\n const commentLength = dataView.getUint32(offset, true)\n offset += 4\n const comment = getString(dataView, offset, commentLength)\n offset += commentLength\n\n const ind = comment.indexOf('=')\n const key = comment.substring(0, ind)\n\n comments[key] = comment.substring(ind + 1)\n }\n\n return comments\n}\n\nfunction getString(dataView: DataView, offset: number, length: number): string {\n let string = ''\n for (let i = 0; i < length; i++) {\n string += String.fromCharCode(dataView.getUint8(offset + i))\n }\n return string\n}\n","import { LiteGraph } from '@comfyorg/litegraph'\nimport { api } from './api'\nimport { getFromPngFile } from './metadata/png'\nimport { getFromFlacFile } from './metadata/flac'\n\n// Original functions left in for backwards compatibility\nexport function getPngMetadata(file: File): Promise> {\n return getFromPngFile(file)\n}\n\nexport function getFlacMetadata(file: File): Promise> {\n return getFromFlacFile(file)\n}\n\nfunction parseExifData(exifData) {\n // Check for the correct TIFF header (0x4949 for little-endian or 0x4D4D for big-endian)\n const isLittleEndian = String.fromCharCode(...exifData.slice(0, 2)) === 'II'\n\n // Function to read 16-bit and 32-bit integers from binary data\n function readInt(offset, isLittleEndian, length) {\n let arr = exifData.slice(offset, offset + length)\n if (length === 2) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength).getUint16(\n 0,\n isLittleEndian\n )\n } else if (length === 4) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength).getUint32(\n 0,\n isLittleEndian\n )\n }\n }\n\n // Read the offset to the first IFD (Image File Directory)\n const ifdOffset = readInt(4, isLittleEndian, 4)\n\n function parseIFD(offset) {\n const numEntries = readInt(offset, isLittleEndian, 2)\n const result = {}\n\n for (let i = 0; i < numEntries; i++) {\n const entryOffset = offset + 2 + i * 12\n const tag = readInt(entryOffset, isLittleEndian, 2)\n const type = readInt(entryOffset + 2, isLittleEndian, 2)\n const numValues = readInt(entryOffset + 4, isLittleEndian, 4)\n const valueOffset = readInt(entryOffset + 8, isLittleEndian, 4)\n\n // Read the value(s) based on the data type\n let value\n if (type === 2) {\n // ASCII string\n value = new TextDecoder('utf-8').decode(\n exifData.subarray(valueOffset, valueOffset + numValues - 1)\n )\n }\n\n result[tag] = value\n }\n\n return result\n }\n\n // Parse the first IFD\n const ifdData = parseIFD(ifdOffset)\n return ifdData\n}\n\nfunction splitValues(input) {\n var output = {}\n for (var key in input) {\n var value = input[key]\n var splitValues = value.split(':', 2)\n output[splitValues[0]] = splitValues[1]\n }\n return output\n}\n\nexport function getWebpMetadata(file) {\n return new Promise>((r) => {\n const reader = new FileReader()\n reader.onload = (event) => {\n const webp = new Uint8Array(event.target.result as ArrayBuffer)\n const dataView = new DataView(webp.buffer)\n\n // Check that the WEBP signature is present\n if (\n dataView.getUint32(0) !== 0x52494646 ||\n dataView.getUint32(8) !== 0x57454250\n ) {\n console.error('Not a valid WEBP file')\n r({})\n return\n }\n\n // Start searching for chunks after the WEBP signature\n let offset = 12\n let txt_chunks = {}\n // Loop through the chunks in the WEBP file\n while (offset < webp.length) {\n const chunk_length = dataView.getUint32(offset + 4, true)\n const chunk_type = String.fromCharCode(\n ...webp.slice(offset, offset + 4)\n )\n if (chunk_type === 'EXIF') {\n if (\n String.fromCharCode(...webp.slice(offset + 8, offset + 8 + 6)) ==\n 'Exif\\0\\0'\n ) {\n offset += 6\n }\n let data = parseExifData(\n webp.slice(offset + 8, offset + 8 + chunk_length)\n )\n for (var key in data) {\n const value = data[key] as string\n if (typeof value === 'string') {\n const index = value.indexOf(':')\n txt_chunks[value.slice(0, index)] = value.slice(index + 1)\n }\n }\n break\n }\n\n offset += 8 + chunk_length\n }\n\n r(txt_chunks)\n }\n\n reader.readAsArrayBuffer(file)\n })\n}\n\nexport function getLatentMetadata(file) {\n return new Promise((r) => {\n const reader = new FileReader()\n reader.onload = (event) => {\n const safetensorsData = new Uint8Array(event.target.result as ArrayBuffer)\n const dataView = new DataView(safetensorsData.buffer)\n let header_size = dataView.getUint32(0, true)\n let offset = 8\n let header = JSON.parse(\n new TextDecoder().decode(\n safetensorsData.slice(offset, offset + header_size)\n )\n )\n r(header.__metadata__)\n }\n\n var slice = file.slice(0, 1024 * 1024 * 4)\n reader.readAsArrayBuffer(slice)\n })\n}\n\nexport async function importA1111(graph, parameters) {\n const p = parameters.lastIndexOf('\\nSteps:')\n if (p > -1) {\n const embeddings = await api.getEmbeddings()\n const opts = parameters\n .substr(p)\n .split('\\n')[1]\n .match(\n new RegExp('\\\\s*([^:]+:\\\\s*([^\"\\\\{].*?|\".*?\"|\\\\{.*?\\\\}))\\\\s*(,|$)', 'g')\n )\n .reduce((p, n) => {\n const s = n.split(':')\n if (s[1].endsWith(',')) {\n s[1] = s[1].substr(0, s[1].length - 1)\n }\n p[s[0].trim().toLowerCase()] = s[1].trim()\n return p\n }, {})\n const p2 = parameters.lastIndexOf('\\nNegative prompt:', p)\n if (p2 > -1) {\n let positive = parameters.substr(0, p2).trim()\n let negative = parameters.substring(p2 + 18, p).trim()\n\n const ckptNode = LiteGraph.createNode('CheckpointLoaderSimple')\n const clipSkipNode = LiteGraph.createNode('CLIPSetLastLayer')\n const positiveNode = LiteGraph.createNode('CLIPTextEncode')\n const negativeNode = LiteGraph.createNode('CLIPTextEncode')\n const samplerNode = LiteGraph.createNode('KSampler')\n const imageNode = LiteGraph.createNode('EmptyLatentImage')\n const vaeNode = LiteGraph.createNode('VAEDecode')\n const vaeLoaderNode = LiteGraph.createNode('VAELoader')\n const saveNode = LiteGraph.createNode('SaveImage')\n let hrSamplerNode = null\n let hrSteps = null\n\n const ceil64 = (v) => Math.ceil(v / 64) * 64\n\n const getWidget = (node, name) => {\n return node.widgets.find((w) => w.name === name)\n }\n\n const setWidgetValue = (node, name, value, isOptionPrefix?) => {\n const w = getWidget(node, name)\n if (isOptionPrefix) {\n const o = w.options.values.find((w) => w.startsWith(value))\n if (o) {\n w.value = o\n } else {\n console.warn(`Unknown value '${value}' for widget '${name}'`, node)\n w.value = value\n }\n } else {\n w.value = value\n }\n }\n\n const createLoraNodes = (clipNode, text, prevClip, prevModel) => {\n const loras = []\n text = text.replace(/]+)>/g, function (m, c) {\n const s = c.split(':')\n const weight = parseFloat(s[1])\n if (isNaN(weight)) {\n console.warn('Invalid LORA', m)\n } else {\n loras.push({ name: s[0], weight })\n }\n return ''\n })\n\n for (const l of loras) {\n const loraNode = LiteGraph.createNode('LoraLoader')\n graph.add(loraNode)\n setWidgetValue(loraNode, 'lora_name', l.name, true)\n setWidgetValue(loraNode, 'strength_model', l.weight)\n setWidgetValue(loraNode, 'strength_clip', l.weight)\n prevModel.node.connect(prevModel.index, loraNode, 0)\n prevClip.node.connect(prevClip.index, loraNode, 1)\n prevModel = { node: loraNode, index: 0 }\n prevClip = { node: loraNode, index: 1 }\n }\n\n prevClip.node.connect(1, clipNode, 0)\n prevModel.node.connect(0, samplerNode, 0)\n if (hrSamplerNode) {\n prevModel.node.connect(0, hrSamplerNode, 0)\n }\n\n return { text, prevModel, prevClip }\n }\n\n const replaceEmbeddings = (text) => {\n if (!embeddings.length) return text\n return text.replaceAll(\n new RegExp(\n '\\\\b(' +\n embeddings\n .map((e) => e.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'))\n .join('\\\\b|\\\\b') +\n ')\\\\b',\n 'ig'\n ),\n 'embedding:$1'\n )\n }\n\n const popOpt = (name) => {\n const v = opts[name]\n delete opts[name]\n return v\n }\n\n graph.clear()\n graph.add(ckptNode)\n graph.add(clipSkipNode)\n graph.add(positiveNode)\n graph.add(negativeNode)\n graph.add(samplerNode)\n graph.add(imageNode)\n graph.add(vaeNode)\n graph.add(vaeLoaderNode)\n graph.add(saveNode)\n\n ckptNode.connect(1, clipSkipNode, 0)\n clipSkipNode.connect(0, positiveNode, 0)\n clipSkipNode.connect(0, negativeNode, 0)\n ckptNode.connect(0, samplerNode, 0)\n positiveNode.connect(0, samplerNode, 1)\n negativeNode.connect(0, samplerNode, 2)\n imageNode.connect(0, samplerNode, 3)\n vaeNode.connect(0, saveNode, 0)\n samplerNode.connect(0, vaeNode, 0)\n vaeLoaderNode.connect(0, vaeNode, 1)\n\n const handlers = {\n model(v) {\n setWidgetValue(ckptNode, 'ckpt_name', v, true)\n },\n vae(v) {\n setWidgetValue(vaeLoaderNode, 'vae_name', v, true)\n },\n 'cfg scale'(v) {\n setWidgetValue(samplerNode, 'cfg', +v)\n },\n 'clip skip'(v) {\n setWidgetValue(clipSkipNode, 'stop_at_clip_layer', -v)\n },\n sampler(v) {\n let name = v.toLowerCase().replace('++', 'pp').replaceAll(' ', '_')\n if (name.includes('karras')) {\n name = name.replace('karras', '').replace(/_+$/, '')\n setWidgetValue(samplerNode, 'scheduler', 'karras')\n } else {\n setWidgetValue(samplerNode, 'scheduler', 'normal')\n }\n const w = getWidget(samplerNode, 'sampler_name')\n const o = w.options.values.find(\n (w) => w === name || w === 'sample_' + name\n )\n if (o) {\n setWidgetValue(samplerNode, 'sampler_name', o)\n }\n },\n size(v) {\n const wxh = v.split('x')\n const w = ceil64(+wxh[0])\n const h = ceil64(+wxh[1])\n const hrUp = popOpt('hires upscale')\n const hrSz = popOpt('hires resize')\n hrSteps = popOpt('hires steps')\n let hrMethod = popOpt('hires upscaler')\n\n setWidgetValue(imageNode, 'width', w)\n setWidgetValue(imageNode, 'height', h)\n\n if (hrUp || hrSz) {\n let uw, uh\n if (hrUp) {\n uw = w * hrUp\n uh = h * hrUp\n } else {\n const s = hrSz.split('x')\n uw = +s[0]\n uh = +s[1]\n }\n\n let upscaleNode\n let latentNode\n\n if (hrMethod.startsWith('Latent')) {\n latentNode = upscaleNode = LiteGraph.createNode('LatentUpscale')\n graph.add(upscaleNode)\n samplerNode.connect(0, upscaleNode, 0)\n\n switch (hrMethod) {\n case 'Latent (nearest-exact)':\n hrMethod = 'nearest-exact'\n break\n }\n setWidgetValue(upscaleNode, 'upscale_method', hrMethod, true)\n } else {\n const decode = LiteGraph.createNode('VAEDecodeTiled')\n graph.add(decode)\n samplerNode.connect(0, decode, 0)\n vaeLoaderNode.connect(0, decode, 1)\n\n const upscaleLoaderNode =\n LiteGraph.createNode('UpscaleModelLoader')\n graph.add(upscaleLoaderNode)\n setWidgetValue(upscaleLoaderNode, 'model_name', hrMethod, true)\n\n const modelUpscaleNode = LiteGraph.createNode(\n 'ImageUpscaleWithModel'\n )\n graph.add(modelUpscaleNode)\n decode.connect(0, modelUpscaleNode, 1)\n upscaleLoaderNode.connect(0, modelUpscaleNode, 0)\n\n upscaleNode = LiteGraph.createNode('ImageScale')\n graph.add(upscaleNode)\n modelUpscaleNode.connect(0, upscaleNode, 0)\n\n const vaeEncodeNode = (latentNode =\n LiteGraph.createNode('VAEEncodeTiled'))\n graph.add(vaeEncodeNode)\n upscaleNode.connect(0, vaeEncodeNode, 0)\n vaeLoaderNode.connect(0, vaeEncodeNode, 1)\n }\n\n setWidgetValue(upscaleNode, 'width', ceil64(uw))\n setWidgetValue(upscaleNode, 'height', ceil64(uh))\n\n hrSamplerNode = LiteGraph.createNode('KSampler')\n graph.add(hrSamplerNode)\n ckptNode.connect(0, hrSamplerNode, 0)\n positiveNode.connect(0, hrSamplerNode, 1)\n negativeNode.connect(0, hrSamplerNode, 2)\n latentNode.connect(0, hrSamplerNode, 3)\n hrSamplerNode.connect(0, vaeNode, 0)\n }\n },\n steps(v) {\n setWidgetValue(samplerNode, 'steps', +v)\n },\n seed(v) {\n setWidgetValue(samplerNode, 'seed', +v)\n }\n }\n\n for (const opt in opts) {\n if (opt in handlers) {\n handlers[opt](popOpt(opt))\n }\n }\n\n if (hrSamplerNode) {\n setWidgetValue(\n hrSamplerNode,\n 'steps',\n hrSteps ? +hrSteps : getWidget(samplerNode, 'steps').value\n )\n setWidgetValue(\n hrSamplerNode,\n 'cfg',\n getWidget(samplerNode, 'cfg').value\n )\n setWidgetValue(\n hrSamplerNode,\n 'scheduler',\n getWidget(samplerNode, 'scheduler').value\n )\n setWidgetValue(\n hrSamplerNode,\n 'sampler_name',\n getWidget(samplerNode, 'sampler_name').value\n )\n setWidgetValue(\n hrSamplerNode,\n 'denoise',\n +(popOpt('denoising strength') || '1')\n )\n }\n\n let n = createLoraNodes(\n positiveNode,\n positive,\n { node: clipSkipNode, index: 0 },\n { node: ckptNode, index: 0 }\n )\n positive = n.text\n n = createLoraNodes(negativeNode, negative, n.prevClip, n.prevModel)\n negative = n.text\n\n setWidgetValue(positiveNode, 'text', replaceEmbeddings(positive))\n setWidgetValue(negativeNode, 'text', replaceEmbeddings(negative))\n\n graph.arrange()\n\n for (const opt of [\n 'model hash',\n 'ensd',\n 'version',\n 'vae hash',\n 'ti hashes',\n 'lora hashes',\n 'hashes'\n ]) {\n delete opts[opt]\n }\n\n console.warn('Unhandled parameters:', opts)\n }\n }\n}\n","import { app } from '../app'\nimport { $el } from '../ui'\n\nexport function calculateImageGrid(imgs, dw, dh) {\n let best = 0\n let w = imgs[0].naturalWidth\n let h = imgs[0].naturalHeight\n const numImages = imgs.length\n\n let cellWidth, cellHeight, cols, rows, shiftX\n // compact style\n for (let c = 1; c <= numImages; c++) {\n const r = Math.ceil(numImages / c)\n const cW = dw / c\n const cH = dh / r\n const scaleX = cW / w\n const scaleY = cH / h\n\n const scale = Math.min(scaleX, scaleY, 1)\n const imageW = w * scale\n const imageH = h * scale\n const area = imageW * imageH * numImages\n\n if (area > best) {\n best = area\n cellWidth = imageW\n cellHeight = imageH\n cols = c\n rows = r\n shiftX = c * ((cW - imageW) / 2)\n }\n }\n\n return { cellWidth, cellHeight, cols, rows, shiftX }\n}\n\nexport function createImageHost(node) {\n const el = $el('div.comfy-img-preview')\n let currentImgs\n let first = true\n\n function updateSize() {\n let w = null\n let h = null\n\n if (currentImgs) {\n let elH = el.clientHeight\n if (first) {\n first = false\n // On first run, if we are small then grow a bit\n if (elH < 190) {\n elH = 190\n }\n el.style.setProperty('--comfy-widget-min-height', elH.toString())\n } else {\n el.style.setProperty('--comfy-widget-min-height', null)\n }\n\n const nw = node.size[0]\n ;({ cellWidth: w, cellHeight: h } = calculateImageGrid(\n currentImgs,\n nw - 20,\n elH\n ))\n w += 'px'\n h += 'px'\n\n el.style.setProperty('--comfy-img-preview-width', w)\n el.style.setProperty('--comfy-img-preview-height', h)\n }\n }\n return {\n el,\n updateImages(imgs) {\n if (imgs !== currentImgs) {\n if (currentImgs == null) {\n requestAnimationFrame(() => {\n updateSize()\n })\n }\n el.replaceChildren(...imgs)\n currentImgs = imgs\n node.onResize(node.size)\n node.graph.setDirtyCanvas(true, true)\n }\n },\n getHeight() {\n updateSize()\n },\n onDraw() {\n // Element from point uses a hittest find elements so we need to toggle pointer events\n el.style.pointerEvents = 'all'\n const over = document.elementFromPoint(\n app.canvas.mouse[0],\n app.canvas.mouse[1]\n )\n el.style.pointerEvents = 'none'\n\n if (!over) return\n // Set the overIndex so Open Image etc work\n const idx = currentImgs.indexOf(over)\n node.overIndex = idx\n }\n }\n}\n","/*\n Original implementation:\n https://github.com/TahaSh/drag-to-reorder\n MIT License\n\n Copyright (c) 2023 Taha Shashtari\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n*/\n\nimport { $el } from '../ui'\n\n$el('style', {\n parent: document.head,\n textContent: `\n .draggable-item {\n position: relative;\n will-change: transform;\n user-select: none;\n }\n .draggable-item.is-idle {\n transition: 0.25s ease transform;\n }\n .draggable-item.is-draggable {\n z-index: 10;\n }\n `\n})\n\nexport class DraggableList extends EventTarget {\n listContainer\n draggableItem\n pointerStartX\n pointerStartY\n scrollYMax\n itemsGap = 0\n items = []\n itemSelector\n handleClass = 'drag-handle'\n off = []\n offDrag = []\n\n constructor(element, itemSelector) {\n super()\n this.listContainer = element\n this.itemSelector = itemSelector\n\n if (!this.listContainer) return\n\n this.off.push(this.on(this.listContainer, 'mousedown', this.dragStart))\n this.off.push(this.on(this.listContainer, 'touchstart', this.dragStart))\n this.off.push(this.on(document, 'mouseup', this.dragEnd))\n this.off.push(this.on(document, 'touchend', this.dragEnd))\n }\n\n getAllItems() {\n if (!this.items?.length) {\n this.items = Array.from(\n this.listContainer.querySelectorAll(this.itemSelector)\n )\n this.items.forEach((element) => {\n element.classList.add('is-idle')\n })\n }\n return this.items\n }\n\n getIdleItems() {\n return this.getAllItems().filter((item) =>\n item.classList.contains('is-idle')\n )\n }\n\n isItemAbove(item) {\n return item.hasAttribute('data-is-above')\n }\n\n isItemToggled(item) {\n return item.hasAttribute('data-is-toggled')\n }\n\n on(source, event, listener, options?) {\n listener = listener.bind(this)\n source.addEventListener(event, listener, options)\n return () => source.removeEventListener(event, listener)\n }\n\n dragStart(e) {\n if (e.target.classList.contains(this.handleClass)) {\n this.draggableItem = e.target.closest(this.itemSelector)\n }\n\n if (!this.draggableItem) return\n\n this.pointerStartX = e.clientX || e.touches[0].clientX\n this.pointerStartY = e.clientY || e.touches[0].clientY\n this.scrollYMax =\n this.listContainer.scrollHeight - this.listContainer.clientHeight\n\n this.setItemsGap()\n this.initDraggableItem()\n this.initItemsState()\n\n this.offDrag.push(this.on(document, 'mousemove', this.drag))\n this.offDrag.push(\n this.on(document, 'touchmove', this.drag, { passive: false })\n )\n\n this.dispatchEvent(\n new CustomEvent('dragstart', {\n detail: {\n element: this.draggableItem,\n position: this.getAllItems().indexOf(this.draggableItem)\n }\n })\n )\n }\n\n setItemsGap() {\n if (this.getIdleItems().length <= 1) {\n this.itemsGap = 0\n return\n }\n\n const item1 = this.getIdleItems()[0]\n const item2 = this.getIdleItems()[1]\n\n const item1Rect = item1.getBoundingClientRect()\n const item2Rect = item2.getBoundingClientRect()\n\n this.itemsGap = Math.abs(item1Rect.bottom - item2Rect.top)\n }\n\n initItemsState() {\n this.getIdleItems().forEach((item, i) => {\n if (this.getAllItems().indexOf(this.draggableItem) > i) {\n item.dataset.isAbove = ''\n }\n })\n }\n\n initDraggableItem() {\n this.draggableItem.classList.remove('is-idle')\n this.draggableItem.classList.add('is-draggable')\n }\n\n drag(e) {\n if (!this.draggableItem) return\n\n e.preventDefault()\n\n const clientX = e.clientX || e.touches[0].clientX\n const clientY = e.clientY || e.touches[0].clientY\n\n const listRect = this.listContainer.getBoundingClientRect()\n\n if (clientY > listRect.bottom) {\n if (this.listContainer.scrollTop < this.scrollYMax) {\n this.listContainer.scrollBy(0, 10)\n this.pointerStartY -= 10\n }\n } else if (clientY < listRect.top && this.listContainer.scrollTop > 0) {\n this.pointerStartY += 10\n this.listContainer.scrollBy(0, -10)\n }\n\n const pointerOffsetX = clientX - this.pointerStartX\n const pointerOffsetY = clientY - this.pointerStartY\n\n this.updateIdleItemsStateAndPosition()\n this.draggableItem.style.transform = `translate(${pointerOffsetX}px, ${pointerOffsetY}px)`\n }\n\n updateIdleItemsStateAndPosition() {\n const draggableItemRect = this.draggableItem.getBoundingClientRect()\n const draggableItemY = draggableItemRect.top + draggableItemRect.height / 2\n\n // Update state\n this.getIdleItems().forEach((item) => {\n const itemRect = item.getBoundingClientRect()\n const itemY = itemRect.top + itemRect.height / 2\n if (this.isItemAbove(item)) {\n if (draggableItemY <= itemY) {\n item.dataset.isToggled = ''\n } else {\n delete item.dataset.isToggled\n }\n } else {\n if (draggableItemY >= itemY) {\n item.dataset.isToggled = ''\n } else {\n delete item.dataset.isToggled\n }\n }\n })\n\n // Update position\n this.getIdleItems().forEach((item) => {\n if (this.isItemToggled(item)) {\n const direction = this.isItemAbove(item) ? 1 : -1\n item.style.transform = `translateY(${direction * (draggableItemRect.height + this.itemsGap)}px)`\n } else {\n item.style.transform = ''\n }\n })\n }\n\n dragEnd() {\n if (!this.draggableItem) return\n\n this.applyNewItemsOrder()\n this.cleanup()\n }\n\n applyNewItemsOrder() {\n const reorderedItems = []\n\n let oldPosition = -1\n this.getAllItems().forEach((item, index) => {\n if (item === this.draggableItem) {\n oldPosition = index\n return\n }\n if (!this.isItemToggled(item)) {\n reorderedItems[index] = item\n return\n }\n const newIndex = this.isItemAbove(item) ? index + 1 : index - 1\n reorderedItems[newIndex] = item\n })\n\n for (let index = 0; index < this.getAllItems().length; index++) {\n const item = reorderedItems[index]\n if (typeof item === 'undefined') {\n reorderedItems[index] = this.draggableItem\n }\n }\n\n reorderedItems.forEach((item) => {\n this.listContainer.appendChild(item)\n })\n\n this.items = reorderedItems\n\n this.dispatchEvent(\n new CustomEvent('dragend', {\n detail: {\n element: this.draggableItem,\n oldPosition,\n newPosition: reorderedItems.indexOf(this.draggableItem)\n }\n })\n )\n }\n\n cleanup() {\n this.itemsGap = 0\n this.items = []\n this.unsetDraggableItem()\n this.unsetItemState()\n\n this.offDrag.forEach((f) => f())\n this.offDrag = []\n }\n\n unsetDraggableItem() {\n this.draggableItem.style = null\n this.draggableItem.classList.remove('is-draggable')\n this.draggableItem.classList.add('is-idle')\n this.draggableItem = null\n }\n\n unsetItemState() {\n this.getIdleItems().forEach((item, i) => {\n delete item.dataset.isAbove\n delete item.dataset.isToggled\n item.style.transform = ''\n })\n }\n\n dispose() {\n this.off.forEach((f) => f())\n }\n}\n","import { api } from './api'\nimport type { ComfyApp } from './app'\nimport { $el } from './ui'\n\n// Simple date formatter\nconst parts = {\n d: (d) => d.getDate(),\n M: (d) => d.getMonth() + 1,\n h: (d) => d.getHours(),\n m: (d) => d.getMinutes(),\n s: (d) => d.getSeconds()\n}\nconst format =\n Object.keys(parts)\n .map((k) => k + k + '?')\n .join('|') + '|yyy?y?'\n\nfunction formatDate(text: string, date: Date) {\n return text.replace(new RegExp(format, 'g'), (text: string): string => {\n if (text === 'yy') return (date.getFullYear() + '').substring(2)\n if (text === 'yyyy') return date.getFullYear().toString()\n if (text[0] in parts) {\n const p = parts[text[0]](date)\n return (p + '').padStart(text.length, '0')\n }\n return text\n })\n}\n\nexport function clone(obj) {\n try {\n if (typeof structuredClone !== 'undefined') {\n return structuredClone(obj)\n }\n } catch (error) {\n // structuredClone is stricter than using JSON.parse/stringify so fallback to that\n }\n\n return JSON.parse(JSON.stringify(obj))\n}\n\nexport function applyTextReplacements(app: ComfyApp, value: string): string {\n return value.replace(/%([^%]+)%/g, function (match, text) {\n const split = text.split('.')\n if (split.length !== 2) {\n // Special handling for dates\n if (split[0].startsWith('date:')) {\n return formatDate(split[0].substring(5), new Date())\n }\n\n if (text !== 'width' && text !== 'height') {\n // Dont warn on standard replacements\n console.warn('Invalid replacement pattern', text)\n }\n return match\n }\n\n // Find node with matching S&R property name\n let nodes = app.graph.nodes.filter(\n (n) => n.properties?.['Node name for S&R'] === split[0]\n )\n // If we cant, see if there is a node with that title\n if (!nodes.length) {\n nodes = app.graph.nodes.filter((n) => n.title === split[0])\n }\n if (!nodes.length) {\n console.warn('Unable to find node', split[0])\n return match\n }\n\n if (nodes.length > 1) {\n console.warn('Multiple nodes matched', split[0], 'using first match')\n }\n\n const node = nodes[0]\n\n const widget = node.widgets?.find((w) => w.name === split[1])\n if (!widget) {\n console.warn('Unable to find widget', split[1], 'on node', split[0], node)\n return match\n }\n\n return ((widget.value ?? '') + '').replaceAll(/\\/|\\\\/g, '_')\n })\n}\n\nexport async function addStylesheet(\n urlOrFile: string,\n relativeTo?: string\n): Promise {\n return new Promise((res, rej) => {\n let url\n if (urlOrFile.endsWith('.js')) {\n url = urlOrFile.substr(0, urlOrFile.length - 2) + 'css'\n } else {\n url = new URL(\n urlOrFile,\n relativeTo ?? `${window.location.protocol}//${window.location.host}`\n ).toString()\n }\n $el('link', {\n parent: document.head,\n rel: 'stylesheet',\n type: 'text/css',\n href: url,\n onload: res,\n onerror: rej\n })\n })\n}\n\n/**\n * @param { string } filename\n * @param { Blob } blob\n */\nexport function downloadBlob(filename, blob) {\n const url = URL.createObjectURL(blob)\n const a = $el('a', {\n href: url,\n download: filename,\n style: { display: 'none' },\n parent: document.body\n })\n a.click()\n setTimeout(function () {\n a.remove()\n window.URL.revokeObjectURL(url)\n }, 0)\n}\n\nexport function prop(\n target: object,\n name: string,\n defaultValue: T,\n onChanged?: (\n currentValue: T,\n previousValue: T,\n target: object,\n name: string\n ) => void\n): T {\n let currentValue\n Object.defineProperty(target, name, {\n get() {\n return currentValue\n },\n set(newValue) {\n const prevValue = currentValue\n currentValue = newValue\n onChanged?.(currentValue, prevValue, target, name)\n }\n })\n return defaultValue\n}\n\nexport function getStorageValue(id: string) {\n const clientId = api.clientId ?? api.initialClientId\n return (\n (clientId && sessionStorage.getItem(`${id}:${clientId}`)) ??\n localStorage.getItem(id)\n )\n}\n\nexport function setStorageValue(id: string, value: string) {\n const clientId = api.clientId ?? api.initialClientId\n if (clientId) {\n sessionStorage.setItem(`${id}:${clientId}`, value)\n }\n localStorage.setItem(id, value)\n}\n","type RGB = { r: number; g: number; b: number }\ntype HSL = { h: number; s: number; l: number }\n\nfunction rgbToHsl({ r, g, b }: RGB): HSL {\n r /= 255\n g /= 255\n b /= 255\n const max = Math.max(r, g, b),\n min = Math.min(r, g, b)\n let h: number, s: number\n const l: number = (max + min) / 2\n\n if (max === min) {\n h = s = 0 // achromatic\n } else {\n const d = max - min\n s = l > 0.5 ? d / (2 - max - min) : d / (max + min)\n switch (max) {\n case r:\n h = (g - b) / d + (g < b ? 6 : 0)\n break\n case g:\n h = (b - r) / d + 2\n break\n case b:\n h = (r - g) / d + 4\n break\n }\n h /= 6\n }\n\n return { h, s, l }\n}\n\nfunction hslToRgb({ h, s, l }: HSL): RGB {\n let r: number, g: number, b: number\n\n if (s === 0) {\n r = g = b = l // achromatic\n } else {\n const hue2rgb = (p: number, q: number, t: number) => {\n if (t < 0) t += 1\n if (t > 1) t -= 1\n if (t < 1 / 6) return p + (q - p) * 6 * t\n if (t < 1 / 2) return q\n if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6\n return p\n }\n\n const q = l < 0.5 ? l * (1 + s) : l + s - l * s\n const p = 2 * l - q\n r = hue2rgb(p, q, h + 1 / 3)\n g = hue2rgb(p, q, h)\n b = hue2rgb(p, q, h - 1 / 3)\n }\n\n return {\n r: Math.round(r * 255),\n g: Math.round(g * 255),\n b: Math.round(b * 255)\n }\n}\n\nfunction hexToRgb(hex: string): RGB {\n let r = 0,\n g = 0,\n b = 0\n // 3 digits\n if (hex.length == 4) {\n r = parseInt(hex[1] + hex[1], 16)\n g = parseInt(hex[2] + hex[2], 16)\n b = parseInt(hex[3] + hex[3], 16)\n }\n // 6 digits\n else if (hex.length == 7) {\n r = parseInt(hex.slice(1, 3), 16)\n g = parseInt(hex.slice(3, 5), 16)\n b = parseInt(hex.slice(5, 7), 16)\n }\n return { r, g, b }\n}\n\nfunction rgbToHex({ r, g, b }: RGB): string {\n return (\n '#' +\n [r, g, b]\n .map((x) => {\n const hex = x.toString(16)\n return hex.length === 1 ? '0' + hex : hex\n })\n .join('')\n )\n}\n\nexport function lightenColor(hex: string, amount: number): string {\n let rgb = hexToRgb(hex)\n const hsl = rgbToHsl(rgb)\n hsl.l = Math.min(1, hsl.l + amount)\n rgb = hslToRgb(hsl)\n return rgbToHex(rgb)\n}\n","export type ClassList = string | string[] | Record\n\nexport function applyClasses(\n element: HTMLElement,\n classList: ClassList,\n ...requiredClasses: string[]\n) {\n classList ??= ''\n\n let str: string\n if (typeof classList === 'string') {\n str = classList\n } else if (classList instanceof Array) {\n str = classList.join(' ')\n } else {\n str = Object.entries(classList).reduce((p, c) => {\n if (c[1]) {\n p += (p.length ? ' ' : '') + c[0]\n }\n return p\n }, '')\n }\n element.className = str\n if (requiredClasses) {\n element.classList.add(...requiredClasses)\n }\n}\n\nexport function toggleElement(\n element: HTMLElement,\n {\n onHide,\n onShow\n }: {\n onHide?: (el: HTMLElement) => void\n onShow?: (el: HTMLElement, value) => void\n } = {}\n) {\n let placeholder: HTMLElement | Comment\n let hidden: boolean\n return (value) => {\n if (value) {\n if (hidden) {\n hidden = false\n placeholder.replaceWith(element)\n }\n onShow?.(element, value)\n } else {\n if (!placeholder) {\n placeholder = document.createComment('')\n }\n hidden = true\n element.replaceWith(placeholder)\n onHide?.(element)\n }\n }\n}\n","import { $el } from '../../ui'\nimport { applyClasses, ClassList, toggleElement } from '../utils'\nimport { prop } from '../../utils'\nimport type { ComfyPopup } from './popup'\nimport type { ComfyComponent } from '.'\nimport type { ComfyApp } from '@/scripts/app'\nimport { Settings } from '@/types/apiTypes'\n\ntype ComfyButtonProps = {\n icon?: string\n overIcon?: string\n iconSize?: number\n content?: string | HTMLElement\n tooltip?: string\n enabled?: boolean\n action?: (e: Event, btn: ComfyButton) => void\n classList?: ClassList\n visibilitySetting?: { id: keyof Settings; showValue: boolean }\n app?: ComfyApp\n}\n\nexport class ComfyButton implements ComfyComponent {\n #over = 0\n #popupOpen = false\n isOver = false\n iconElement = $el('i.mdi')\n contentElement = $el('span')\n popup: ComfyPopup\n element: HTMLElement\n overIcon: string\n iconSize: number\n content: string | HTMLElement\n icon: string\n tooltip: string\n classList: ClassList\n hidden: boolean\n enabled: boolean\n action: (e: Event, btn: ComfyButton) => void\n\n constructor({\n icon,\n overIcon,\n iconSize,\n content,\n tooltip,\n action,\n classList = 'comfyui-button',\n visibilitySetting,\n app,\n enabled = true\n }: ComfyButtonProps) {\n this.element = $el(\n 'button',\n {\n onmouseenter: () => {\n this.isOver = true\n if (this.overIcon) {\n this.updateIcon()\n }\n },\n onmouseleave: () => {\n this.isOver = false\n if (this.overIcon) {\n this.updateIcon()\n }\n }\n },\n [this.iconElement, this.contentElement]\n )\n\n this.icon = prop(\n this,\n 'icon',\n icon,\n toggleElement(this.iconElement, { onShow: this.updateIcon })\n )\n this.overIcon = prop(this, 'overIcon', overIcon, () => {\n if (this.isOver) {\n this.updateIcon()\n }\n })\n this.iconSize = prop(this, 'iconSize', iconSize, this.updateIcon)\n this.content = prop(\n this,\n 'content',\n content,\n toggleElement(this.contentElement, {\n onShow: (el, v) => {\n if (typeof v === 'string') {\n el.textContent = v\n } else {\n el.replaceChildren(v)\n }\n }\n })\n )\n\n this.tooltip = prop(this, 'tooltip', tooltip, (v) => {\n if (v) {\n this.element.title = v\n } else {\n this.element.removeAttribute('title')\n }\n })\n if (tooltip !== undefined) {\n this.element.setAttribute('aria-label', tooltip)\n }\n this.classList = prop(this, 'classList', classList, this.updateClasses)\n this.hidden = prop(this, 'hidden', false, this.updateClasses)\n this.enabled = prop(this, 'enabled', enabled, () => {\n this.updateClasses()\n ;(this.element as HTMLButtonElement).disabled = !this.enabled\n })\n this.action = prop(this, 'action', action)\n this.element.addEventListener('click', (e) => {\n if (this.popup) {\n // we are either a touch device or triggered by click not hover\n if (!this.#over) {\n this.popup.toggle()\n }\n }\n this.action?.(e, this)\n })\n\n if (visibilitySetting?.id) {\n const settingUpdated = () => {\n this.hidden =\n app.ui.settings.getSettingValue(visibilitySetting.id) !==\n visibilitySetting.showValue\n }\n app.ui.settings.addEventListener(\n visibilitySetting.id + '.change',\n settingUpdated\n )\n settingUpdated()\n }\n }\n\n updateIcon = () =>\n (this.iconElement.className = `mdi mdi-${(this.isOver && this.overIcon) || this.icon}${this.iconSize ? ' mdi-' + this.iconSize + 'px' : ''}`)\n updateClasses = () => {\n const internalClasses = []\n if (this.hidden) {\n internalClasses.push('hidden')\n }\n if (!this.enabled) {\n internalClasses.push('disabled')\n }\n if (this.popup) {\n if (this.#popupOpen) {\n internalClasses.push('popup-open')\n } else {\n internalClasses.push('popup-closed')\n }\n }\n applyClasses(this.element, this.classList, ...internalClasses)\n }\n\n withPopup(popup: ComfyPopup, mode: 'click' | 'hover' = 'click') {\n this.popup = popup\n\n if (mode === 'hover') {\n for (const el of [this.element, this.popup.element]) {\n el.addEventListener('mouseenter', () => {\n this.popup.open = !!++this.#over\n })\n el.addEventListener('mouseleave', () => {\n this.popup.open = !!--this.#over\n })\n }\n }\n\n popup.addEventListener('change', () => {\n this.#popupOpen = popup.open\n this.updateClasses()\n })\n\n return this\n }\n}\n","import { $el } from '../../ui'\nimport { ComfyButton } from './button'\nimport { prop } from '../../utils'\n\nexport class ComfyButtonGroup {\n element = $el('div.comfyui-button-group')\n buttons: (HTMLElement | ComfyButton)[]\n\n constructor(...buttons: (HTMLElement | ComfyButton)[]) {\n this.buttons = prop(this, 'buttons', buttons, () => this.update())\n }\n\n insert(button: ComfyButton, index: number) {\n this.buttons.splice(index, 0, button)\n this.update()\n }\n\n append(button: ComfyButton) {\n this.buttons.push(button)\n this.update()\n }\n\n remove(indexOrButton: ComfyButton | number) {\n if (typeof indexOrButton !== 'number') {\n indexOrButton = this.buttons.indexOf(indexOrButton)\n }\n if (indexOrButton > -1) {\n const r = this.buttons.splice(indexOrButton, 1)\n this.update()\n return r\n }\n }\n\n update() {\n this.element.replaceChildren(...this.buttons.map((b) => b['element'] ?? b))\n }\n}\n","import { prop } from '../../utils'\nimport { $el } from '../../ui'\nimport { applyClasses, ClassList } from '../utils'\n\nexport class ComfyPopup extends EventTarget {\n element = $el('div.comfyui-popup')\n open: boolean\n children: HTMLElement[]\n target: HTMLElement\n ignoreTarget: boolean\n container: HTMLElement\n position: string\n closeOnEscape: boolean\n horizontal: string\n classList: ClassList\n\n constructor(\n {\n target,\n container = document.body,\n classList = '',\n ignoreTarget = true,\n closeOnEscape = true,\n position = 'absolute',\n horizontal = 'left'\n }: {\n target: HTMLElement\n container?: HTMLElement\n classList?: ClassList\n ignoreTarget?: boolean\n closeOnEscape?: boolean\n position?: 'absolute' | 'relative'\n horizontal?: 'left' | 'right'\n },\n ...children: HTMLElement[]\n ) {\n super()\n this.target = target\n this.ignoreTarget = ignoreTarget\n this.container = container\n this.position = position\n this.closeOnEscape = closeOnEscape\n this.horizontal = horizontal\n\n container.append(this.element)\n\n this.children = prop(this, 'children', children, () => {\n this.element.replaceChildren(...this.children)\n this.update()\n })\n this.classList = prop(this, 'classList', classList, () =>\n applyClasses(this.element, this.classList, 'comfyui-popup', horizontal)\n )\n this.open = prop(this, 'open', false, (v, o) => {\n if (v === o) return\n if (v) {\n this.#show()\n } else {\n this.#hide()\n }\n })\n }\n\n toggle() {\n this.open = !this.open\n }\n\n #hide() {\n this.element.classList.remove('open')\n window.removeEventListener('resize', this.update)\n window.removeEventListener('click', this.#clickHandler, { capture: true })\n window.removeEventListener('keydown', this.#escHandler, { capture: true })\n\n this.dispatchEvent(new CustomEvent('close'))\n this.dispatchEvent(new CustomEvent('change'))\n }\n\n #show() {\n this.element.classList.add('open')\n this.update()\n\n window.addEventListener('resize', this.update)\n window.addEventListener('click', this.#clickHandler, { capture: true })\n if (this.closeOnEscape) {\n window.addEventListener('keydown', this.#escHandler, { capture: true })\n }\n\n this.dispatchEvent(new CustomEvent('open'))\n this.dispatchEvent(new CustomEvent('change'))\n }\n\n #escHandler = (e) => {\n if (e.key === 'Escape') {\n this.open = false\n e.preventDefault()\n e.stopImmediatePropagation()\n }\n }\n\n #clickHandler = (e) => {\n /** @type {any} */\n const target = e.target\n if (\n !this.element.contains(target) &&\n this.ignoreTarget &&\n !this.target.contains(target)\n ) {\n this.open = false\n }\n }\n\n update = () => {\n const rect = this.target.getBoundingClientRect()\n this.element.style.setProperty('--bottom', 'unset')\n if (this.position === 'absolute') {\n if (this.horizontal === 'left') {\n this.element.style.setProperty('--left', rect.left + 'px')\n } else {\n this.element.style.setProperty(\n '--left',\n rect.right - this.element.clientWidth + 'px'\n )\n }\n this.element.style.setProperty('--top', rect.bottom + 'px')\n this.element.style.setProperty('--limit', rect.bottom + 'px')\n } else {\n this.element.style.setProperty('--left', 0 + 'px')\n this.element.style.setProperty('--top', rect.height + 'px')\n this.element.style.setProperty('--limit', rect.height + 'px')\n }\n\n const thisRect = this.element.getBoundingClientRect()\n if (thisRect.height < 30) {\n // Move up instead\n this.element.style.setProperty('--top', 'unset')\n this.element.style.setProperty('--bottom', rect.height + 5 + 'px')\n this.element.style.setProperty('--limit', rect.height + 5 + 'px')\n }\n }\n}\n","import { $el } from '../../ui'\nimport { ComfyButton } from './button'\nimport { prop } from '../../utils'\nimport { ComfyPopup } from './popup'\n\nexport class ComfySplitButton {\n arrow: ComfyButton\n element: HTMLElement\n popup: ComfyPopup\n items: Array\n\n constructor(\n {\n primary,\n mode,\n horizontal = 'left',\n position = 'relative'\n }: {\n primary: ComfyButton\n mode?: 'hover' | 'click'\n horizontal?: 'left' | 'right'\n position?: 'relative' | 'absolute'\n },\n ...items: Array\n ) {\n this.arrow = new ComfyButton({\n icon: 'chevron-down'\n })\n this.element = $el(\n 'div.comfyui-split-button' + (mode === 'hover' ? '.hover' : ''),\n [\n $el(\n 'div.comfyui-split-primary',\n {\n ariaLabel: 'Queue current workflow'\n },\n primary.element\n ),\n $el(\n 'div.comfyui-split-arrow',\n {\n ariaLabel: 'Open extra opens',\n ariaHasPopup: 'true'\n },\n this.arrow.element\n )\n ]\n )\n this.popup = new ComfyPopup({\n target: this.element,\n container: position === 'relative' ? this.element : document.body,\n classList:\n 'comfyui-split-button-popup' + (mode === 'hover' ? ' hover' : ''),\n closeOnEscape: mode === 'click',\n position,\n horizontal\n })\n\n this.arrow.withPopup(this.popup, mode)\n\n this.items = prop(this, 'items', items, () => this.update())\n }\n\n update() {\n this.popup.element.replaceChildren(\n ...this.items.map((b) => ('element' in b ? b.element : b))\n )\n }\n}\n","import type { ComfyApp } from '@/scripts/app'\nimport { $el } from '../../ui'\nimport { prop } from '../../utils'\n\nexport class ComfyQueueOptions extends EventTarget {\n element = $el('div.comfyui-queue-options')\n app: ComfyApp\n batchCountInput: HTMLInputElement\n batchCount: number\n batchCountRange: HTMLInputElement\n autoQueueMode: string\n autoQueueEl: HTMLElement\n\n constructor(app: ComfyApp) {\n super()\n this.app = app\n\n this.batchCountInput = $el('input', {\n className: 'comfyui-queue-batch-value',\n type: 'number',\n min: '1',\n value: '1',\n oninput: () => (this.batchCount = +this.batchCountInput.value)\n })\n\n this.batchCountRange = $el('input', {\n type: 'range',\n min: '1',\n max: '100',\n value: '1',\n oninput: () => (this.batchCount = +this.batchCountRange.value)\n })\n\n this.element.append(\n $el('div.comfyui-queue-batch', [\n $el(\n 'label',\n {\n textContent: 'Batch count: '\n },\n this.batchCountInput\n ),\n this.batchCountRange\n ])\n )\n\n const createOption = (text, value, checked = false) =>\n $el(\n 'label',\n { textContent: text },\n $el('input', {\n type: 'radio',\n name: 'AutoQueueMode',\n checked,\n value,\n oninput: (e) => (this.autoQueueMode = e.target['value'])\n })\n )\n\n this.autoQueueEl = $el('div.comfyui-queue-mode', [\n $el('span', 'Auto Queue:'),\n createOption('Disabled', '', true),\n createOption('Instant', 'instant'),\n createOption('On Change', 'change')\n ])\n\n this.element.append(this.autoQueueEl)\n\n this.batchCount = prop(this, 'batchCount', 1, () => {\n this.batchCountInput.value = this.batchCount + ''\n this.batchCountRange.value = this.batchCount + ''\n })\n\n this.autoQueueMode = prop(this, 'autoQueueMode', 'Disabled', () => {\n this.dispatchEvent(\n new CustomEvent('autoQueueMode', {\n detail: this.autoQueueMode\n })\n )\n })\n }\n}\n","import { ComfyButton } from '../components/button'\nimport { $el } from '../../ui'\nimport { api } from '../../api'\nimport { ComfySplitButton } from '../components/splitButton'\nimport { ComfyQueueOptions } from './queueOptions'\nimport { prop } from '../../utils'\nimport type { ComfyApp } from '@/scripts/app'\nimport { StatusWsMessageStatus } from '@/types/apiTypes'\n\nexport class ComfyQueueButton {\n element = $el('div.comfyui-queue-button')\n #internalQueueSize = 0\n\n queuePrompt = async (e?: MouseEvent) => {\n this.#internalQueueSize += this.queueOptions.batchCount\n // Hold shift to queue front, event is undefined when auto-queue is enabled\n await this.app.queuePrompt(\n e?.shiftKey ? -1 : 0,\n this.queueOptions.batchCount\n )\n }\n queueOptions: ComfyQueueOptions\n app: ComfyApp\n autoQueueMode: string\n graphHasChanged: boolean\n\n constructor(app: ComfyApp) {\n this.app = app\n\n const queue = new ComfyButton({\n content: $el('div', [\n $el('span', {\n textContent: 'Queue'\n })\n ]),\n icon: 'play',\n classList: 'comfyui-button',\n action: this.queuePrompt\n })\n\n this.queueOptions = new ComfyQueueOptions(app)\n\n const btn = new ComfySplitButton(\n {\n primary: queue,\n mode: 'click',\n position: 'absolute',\n horizontal: 'right'\n },\n this.queueOptions.element\n )\n btn.element.classList.add('primary')\n this.element.append(btn.element)\n\n this.autoQueueMode = prop(this, 'autoQueueMode', '', () => {\n switch (this.autoQueueMode) {\n case 'instant':\n queue.icon = 'infinity'\n break\n case 'change':\n queue.icon = 'auto-mode'\n break\n default:\n queue.icon = 'play'\n break\n }\n })\n\n this.queueOptions.addEventListener(\n 'autoQueueMode',\n (e) => (this.autoQueueMode = e['detail'])\n )\n\n api.addEventListener('graphChanged', () => {\n if (this.autoQueueMode === 'change') {\n if (this.#internalQueueSize) {\n this.graphHasChanged = true\n } else {\n this.graphHasChanged = false\n this.queuePrompt()\n }\n }\n })\n\n api.addEventListener(\n 'status',\n ({ detail }: CustomEvent) => {\n this.#internalQueueSize = detail?.exec_info?.queue_remaining\n if (this.#internalQueueSize != null) {\n if (!this.#internalQueueSize && !app.lastExecutionError) {\n if (\n this.autoQueueMode === 'instant' ||\n (this.autoQueueMode === 'change' && this.graphHasChanged)\n ) {\n this.graphHasChanged = false\n this.queuePrompt()\n }\n }\n }\n }\n )\n }\n}\n","import './spinner.css'\n\nexport function createSpinner() {\n const div = document.createElement('div')\n div.innerHTML = ``\n return div.firstElementChild\n}\n","import { ComfyDialog } from '../dialog'\nimport { $el } from '../../ui'\n\nexport class ComfyAsyncDialog extends ComfyDialog {\n #resolve: (value: any) => void\n\n constructor(actions?: Array) {\n super(\n 'dialog.comfy-dialog.comfyui-dialog',\n actions?.map((opt) => {\n if (typeof opt === 'string') {\n opt = { text: opt }\n }\n return $el('button.comfyui-button', {\n type: 'button',\n textContent: opt.text,\n onclick: () => this.close(opt.value ?? opt.text)\n })\n })\n )\n }\n\n show(html: string | HTMLElement | HTMLElement[]) {\n this.element.addEventListener('close', () => {\n this.close()\n })\n\n super.show(html)\n\n return new Promise((resolve) => {\n this.#resolve = resolve\n })\n }\n\n showModal(html: string | HTMLElement | HTMLElement[]) {\n this.element.addEventListener('close', () => {\n this.close()\n })\n\n super.show(html)\n this.element.showModal()\n\n return new Promise((resolve) => {\n this.#resolve = resolve\n })\n }\n\n close(result = null) {\n this.#resolve(result)\n this.element.close()\n super.close()\n }\n\n static async prompt({ title = null, message, actions }) {\n const dialog = new ComfyAsyncDialog(actions)\n const content = [$el('span', message)]\n if (title) {\n content.unshift($el('h3', title))\n }\n const res = await dialog.showModal(content)\n dialog.element.remove()\n return res\n }\n}\n","import { defineStore } from 'pinia'\nimport { computed, ref } from 'vue'\nimport { ComfyWorkflow } from '@/scripts/workflows'\nimport { getStorageValue } from '@/scripts/utils'\n\nexport const useWorkflowStore = defineStore('workflow', () => {\n const activeWorkflow = ref(null)\n const previousWorkflowUnsaved = ref(\n Boolean(getStorageValue('Comfy.PreviousWorkflowUnsaved'))\n )\n\n const workflowLookup = ref>({})\n const workflows = computed(() => Object.values(workflowLookup.value))\n const openWorkflows = ref([])\n\n return {\n activeWorkflow,\n previousWorkflowUnsaved,\n workflows,\n openWorkflows,\n workflowLookup\n }\n})\n","import { ComfyButton } from '../components/button'\nimport { prop, getStorageValue, setStorageValue } from '../../utils'\nimport { $el } from '../../ui'\nimport { api } from '../../api'\nimport { ComfyPopup } from '../components/popup'\nimport { createSpinner } from '../spinner'\nimport { ComfyWorkflow } from '../../workflows'\nimport { ComfyAsyncDialog } from '../components/asyncDialog'\nimport { trimJsonExt } from '@/utils/formatUtil'\nimport type { ComfyApp } from '@/scripts/app'\nimport type { ComfyComponent } from '../components'\nimport { useWorkflowStore } from '@/stores/workflowStore'\n\nexport class ComfyWorkflowsMenu {\n #first = true\n element = $el('div.comfyui-workflows')\n popup: ComfyPopup\n app: ComfyApp\n buttonProgress: HTMLElement\n workflowLabel: HTMLElement\n button: ComfyButton\n content: ComfyWorkflowsContent\n unsaved: boolean\n\n get open() {\n return this.popup.open\n }\n\n set open(open) {\n this.popup.open = open\n }\n\n constructor(app: ComfyApp) {\n this.app = app\n this.#bindEvents()\n\n const classList = {\n 'comfyui-workflows-button': true,\n 'comfyui-button': true,\n unsaved: getStorageValue('Comfy.PreviousWorkflowUnsaved') === 'true',\n running: false\n }\n this.buttonProgress = $el('div.comfyui-workflows-button-progress')\n this.workflowLabel = $el('span.comfyui-workflows-label', '')\n this.button = new ComfyButton({\n content: $el('div.comfyui-workflows-button-inner', [\n $el('i.mdi.mdi-graph'),\n this.workflowLabel,\n this.buttonProgress\n ]),\n icon: 'chevron-down',\n classList,\n tooltip: 'Click to open workflows menu'\n })\n\n this.element.append(this.button.element)\n\n this.popup = new ComfyPopup({\n target: this.element,\n classList: 'comfyui-workflows-popup'\n })\n this.content = new ComfyWorkflowsContent(app, this.popup)\n this.popup.children = [this.content.element]\n this.popup.addEventListener('change', () => {\n this.button.icon = 'chevron-' + (this.popup.open ? 'up' : 'down')\n })\n this.button.withPopup(this.popup)\n\n this.unsaved = prop(this, 'unsaved', classList.unsaved, (v) => {\n classList.unsaved = v\n this.button.classList = classList\n setStorageValue('Comfy.PreviousWorkflowUnsaved', String(v))\n\n if (this.app.vueAppReady) {\n useWorkflowStore().previousWorkflowUnsaved = v\n }\n })\n }\n\n #updateActive = () => {\n const active = this.app.workflowManager.activeWorkflow\n this.button.tooltip = active.path\n this.workflowLabel.textContent = active.name\n this.workflowLabel.ariaLabel = `Active workflow: ${active.name}`\n this.unsaved = active.unsaved\n\n if (this.#first) {\n this.#first = false\n this.content.load()\n }\n }\n\n #bindEvents() {\n this.app.workflowManager.addEventListener(\n 'changeWorkflow',\n this.#updateActive\n )\n this.app.workflowManager.addEventListener('rename', this.#updateActive)\n this.app.workflowManager.addEventListener('delete', this.#updateActive)\n\n this.app.workflowManager.addEventListener('save', () => {\n this.unsaved = this.app.workflowManager.activeWorkflow.unsaved\n })\n\n api.addEventListener('graphChanged', () => {\n this.unsaved = true\n })\n }\n\n #getMenuOptions(callback) {\n const menu = []\n const directories = new Map()\n for (const workflow of this.app.workflowManager.workflows || []) {\n const path = workflow.pathParts\n if (!path) continue\n let parent = menu\n let currentPath = ''\n for (let i = 0; i < path.length - 1; i++) {\n currentPath += '/' + path[i]\n let newParent = directories.get(currentPath)\n if (!newParent) {\n newParent = {\n title: path[i],\n has_submenu: true,\n submenu: {\n options: []\n }\n }\n parent.push(newParent)\n newParent = newParent.submenu.options\n directories.set(currentPath, newParent)\n }\n parent = newParent\n }\n parent.push({\n title: trimJsonExt(path[path.length - 1]),\n callback: () => callback(workflow)\n })\n }\n return menu\n }\n\n #getFavoriteMenuOptions(callback) {\n const menu = []\n for (const workflow of this.app.workflowManager.workflows || []) {\n if (workflow.isFavorite) {\n menu.push({\n title: '⭐ ' + workflow.name,\n callback: () => callback(workflow)\n })\n }\n }\n return menu\n }\n\n registerExtension(app: ComfyApp) {\n const self = this\n app.registerExtension({\n name: 'Comfy.Workflows',\n async beforeRegisterNodeDef(nodeType) {\n function getImageWidget(node) {\n const inputs = {\n ...node.constructor?.nodeData?.input?.required,\n ...node.constructor?.nodeData?.input?.optional\n }\n for (const input in inputs) {\n if (inputs[input][0] === 'IMAGEUPLOAD') {\n const imageWidget = node.widgets.find(\n (w) => w.name === (inputs[input]?.[1]?.widget ?? 'image')\n )\n if (imageWidget) return imageWidget\n }\n }\n }\n\n function setWidgetImage(node, widget, img) {\n const url = new URL(img.src)\n const filename = url.searchParams.get('filename')\n const subfolder = url.searchParams.get('subfolder')\n const type = url.searchParams.get('type')\n const imageId = `${subfolder ? subfolder + '/' : ''}${filename} [${type}]`\n widget.value = imageId\n node.imgs = [img]\n app.graph.setDirtyCanvas(true, true)\n }\n\n async function sendToWorkflow(\n img: HTMLImageElement,\n workflow: ComfyWorkflow\n ) {\n const openWorkflow = app.workflowManager.openWorkflows.find(\n (w) => w.path === workflow.path\n )\n if (openWorkflow) {\n workflow = openWorkflow\n }\n\n await workflow.load()\n let options = []\n const nodes = app.graph.computeExecutionOrder(false)\n for (const node of nodes) {\n const widget = getImageWidget(node)\n if (widget == null) continue\n\n if (node.title?.toLowerCase().includes('input')) {\n options = [{ widget, node }]\n break\n } else {\n options.push({ widget, node })\n }\n }\n\n if (!options.length) {\n alert('No image nodes have been found in this workflow!')\n return\n } else if (options.length > 1) {\n const dialog = new WidgetSelectionDialog(options)\n const res = await dialog.show(app)\n if (!res) return\n options = [res]\n }\n\n setWidgetImage(options[0].node, options[0].widget, img)\n }\n\n const getExtraMenuOptions = nodeType.prototype['getExtraMenuOptions']\n nodeType.prototype['getExtraMenuOptions'] = function (\n this: { imageIndex?: number; overIndex?: number; imgs: string[] },\n _,\n options\n ) {\n const r = getExtraMenuOptions?.apply?.(this, arguments)\n const setting = app.ui.settings.getSettingValue(\n 'Comfy.UseNewMenu',\n false\n )\n if (setting && setting != 'Disabled') {\n const t = this\n let img\n if (t.imageIndex != null) {\n // An image is selected so select that\n img = t.imgs?.[t.imageIndex]\n } else if (t.overIndex != null) {\n // No image is selected but one is hovered\n img = t.imgs?.[t.overIndex]\n }\n\n if (img) {\n let pos = options.findIndex((o) => o.content === 'Save Image')\n if (pos === -1) {\n pos = 0\n } else {\n pos++\n }\n\n options.splice(pos, 0, {\n content: 'Send to workflow',\n has_submenu: true,\n submenu: {\n options: [\n {\n callback: () =>\n sendToWorkflow(img, app.workflowManager.activeWorkflow),\n title: '[Current workflow]'\n },\n ...self.#getFavoriteMenuOptions(\n sendToWorkflow.bind(null, img)\n ),\n null,\n ...self.#getMenuOptions(sendToWorkflow.bind(null, img))\n ]\n }\n })\n }\n }\n\n return r\n }\n }\n })\n }\n}\n\nexport class ComfyWorkflowsContent {\n element = $el('div.comfyui-workflows-panel')\n treeState = {}\n treeFiles: Record = {}\n openFiles: Map> = new Map()\n activeElement: WorkflowElement = null\n spinner: Element\n openElement: HTMLElement\n favoritesElement: HTMLElement\n treeElement: HTMLElement\n app: ComfyApp\n popup: ComfyPopup\n actions: HTMLElement\n filterText: string | undefined\n treeRoot: HTMLElement\n\n constructor(app: ComfyApp, popup: ComfyPopup) {\n this.app = app\n this.popup = popup\n this.actions = $el('div.comfyui-workflows-actions', [\n new ComfyButton({\n content: 'Default',\n icon: 'file-code',\n iconSize: 18,\n classList: 'comfyui-button primary',\n tooltip: 'Load default workflow',\n action: () => {\n popup.open = false\n app.loadGraphData()\n app.resetView()\n }\n }).element,\n new ComfyButton({\n content: 'Browse',\n icon: 'folder',\n iconSize: 18,\n tooltip: 'Browse for an image or exported workflow',\n action: () => {\n popup.open = false\n app.ui.loadFile()\n }\n }).element,\n new ComfyButton({\n content: 'Blank',\n icon: 'plus-thick',\n iconSize: 18,\n tooltip: 'Create a new blank workflow',\n action: () => {\n app.workflowManager.setWorkflow(null)\n app.clean()\n app.graph.clear()\n app.workflowManager.activeWorkflow.track()\n popup.open = false\n }\n }).element\n ])\n\n this.spinner = createSpinner()\n this.element.replaceChildren(this.actions, this.spinner)\n\n this.popup.addEventListener('open', () => this.load())\n this.popup.addEventListener('close', () =>\n this.element.replaceChildren(this.actions, this.spinner)\n )\n\n this.app.workflowManager.addEventListener('favorite', (e) => {\n const workflow = e['detail']\n const button = this.treeFiles[workflow.path]?.primary\n if (!button) return // Can happen when a workflow is renamed\n button.icon = this.#getFavoriteIcon(workflow)\n button.overIcon = this.#getFavoriteOverIcon(workflow)\n this.updateFavorites()\n })\n\n for (const e of ['save', 'open', 'close', 'changeWorkflow']) {\n // TODO: dont be lazy and just update the specific element\n app.workflowManager.addEventListener(e, () => this.updateOpen())\n }\n this.app.workflowManager.addEventListener('rename', () => this.load())\n }\n\n async load() {\n await this.app.workflowManager.loadWorkflows()\n this.updateTree()\n this.updateFavorites()\n this.updateOpen()\n this.element.replaceChildren(\n this.actions,\n this.openElement,\n this.favoritesElement,\n this.treeElement\n )\n }\n\n updateOpen() {\n const current = this.openElement\n this.openFiles.clear()\n\n this.openElement = $el('div.comfyui-workflows-open', [\n $el('h3', 'Open'),\n ...this.app.workflowManager.openWorkflows.map((w) => {\n const wrapper = new WorkflowElement(this, w, {\n primary: { element: $el('i.mdi.mdi-18px.mdi-progress-pencil') },\n buttons: [\n this.#getRenameButton(w),\n new ComfyButton({\n icon: 'close',\n iconSize: 18,\n classList: 'comfyui-button comfyui-workflows-file-action',\n tooltip: 'Close workflow',\n action: (e) => {\n e.stopImmediatePropagation()\n this.app.workflowManager.closeWorkflow(w)\n }\n })\n ]\n })\n if (w.unsaved) {\n wrapper.element.classList.add('unsaved')\n }\n if (w === this.app.workflowManager.activeWorkflow) {\n wrapper.element.classList.add('active')\n }\n\n this.openFiles.set(w, wrapper)\n return wrapper.element\n })\n ])\n\n this.#updateActive()\n current?.replaceWith(this.openElement)\n }\n\n updateFavorites() {\n const current = this.favoritesElement\n const favorites = [\n ...this.app.workflowManager.workflows.filter((w) => w.isFavorite)\n ]\n\n this.favoritesElement = $el('div.comfyui-workflows-favorites', [\n $el('h3', 'Favorites'),\n ...favorites\n .map((w) => {\n return this.#getWorkflowElement(w).element\n })\n .filter(Boolean)\n ])\n\n current?.replaceWith(this.favoritesElement)\n }\n\n filterTree() {\n if (!this.filterText) {\n this.treeRoot.classList.remove('filtered')\n // Unfilter whole tree\n for (const item of Object.values(this.treeFiles)) {\n item.element.parentElement.style.removeProperty('display')\n this.showTreeParents(item.element.parentElement)\n }\n return\n }\n this.treeRoot.classList.add('filtered')\n const searchTerms = this.filterText.toLocaleLowerCase().split(' ')\n for (const item of Object.values(this.treeFiles)) {\n const parts = item.workflow.pathParts\n let termIndex = 0\n let valid = false\n for (const part of parts) {\n let currentIndex = 0\n do {\n currentIndex = part.indexOf(searchTerms[termIndex], currentIndex)\n if (currentIndex > -1) currentIndex += searchTerms[termIndex].length\n } while (currentIndex !== -1 && ++termIndex < searchTerms.length)\n\n if (termIndex >= searchTerms.length) {\n valid = true\n break\n }\n }\n if (valid) {\n item.element.parentElement.style.removeProperty('display')\n this.showTreeParents(item.element.parentElement)\n } else {\n item.element.parentElement.style.display = 'none'\n this.hideTreeParents(item.element.parentElement)\n }\n }\n }\n\n hideTreeParents(element) {\n // Hide all parents if no children are visible\n if (\n element.parentElement?.classList.contains('comfyui-workflows-tree') ===\n false\n ) {\n for (let i = 1; i < element.parentElement.children.length; i++) {\n const c = element.parentElement.children[i]\n if (c.style.display !== 'none') {\n return\n }\n }\n element.parentElement.style.display = 'none'\n this.hideTreeParents(element.parentElement)\n }\n }\n\n showTreeParents(element) {\n if (\n element.parentElement?.classList.contains('comfyui-workflows-tree') ===\n false\n ) {\n element.parentElement.style.removeProperty('display')\n this.showTreeParents(element.parentElement)\n }\n }\n\n updateTree() {\n const current = this.treeElement\n const nodes = {}\n let typingTimeout\n\n this.treeFiles = {}\n this.treeRoot = $el('ul.comfyui-workflows-tree')\n this.treeElement = $el('section', [\n $el('header', [\n $el('h3', 'Browse'),\n $el('div.comfy-ui-workflows-search', [\n $el('i.mdi.mdi-18px.mdi-magnify'),\n $el('input', {\n placeholder: 'Search',\n role: 'search',\n value: this.filterText ?? '',\n oninput: (e: InputEvent) => {\n this.filterText = e.target['value']?.trim()\n clearTimeout(typingTimeout)\n typingTimeout = setTimeout(() => this.filterTree(), 250)\n }\n })\n ])\n ]),\n this.treeRoot\n ])\n\n for (const workflow of this.app.workflowManager.workflows) {\n if (!workflow.pathParts) continue\n\n let currentPath = ''\n let currentRoot = this.treeRoot\n\n for (let i = 0; i < workflow.pathParts.length; i++) {\n currentPath += (currentPath ? '\\\\' : '') + workflow.pathParts[i]\n const parentNode =\n nodes[currentPath] ??\n this.#createNode(currentPath, workflow, i, currentRoot)\n\n nodes[currentPath] = parentNode\n currentRoot = parentNode\n }\n }\n\n current?.replaceWith(this.treeElement)\n this.filterTree()\n }\n\n #expandNode(el, workflow, thisPath, i) {\n const expanded = !el.classList.toggle('closed')\n if (expanded) {\n let c = ''\n for (let j = 0; j <= i; j++) {\n c += (c ? '\\\\' : '') + workflow.pathParts[j]\n this.treeState[c] = true\n }\n } else {\n let c = thisPath\n for (let j = i + 1; j < workflow.pathParts.length; j++) {\n c += (c ? '\\\\' : '') + workflow.pathParts[j]\n delete this.treeState[c]\n }\n delete this.treeState[thisPath]\n }\n }\n\n #updateActive() {\n this.#removeActive()\n\n const active = this.app.workflowManager.activePrompt\n if (!active?.workflow) return\n\n const open = this.openFiles.get(active.workflow)\n if (!open) return\n\n this.activeElement = open\n\n const total = Object.values(active.nodes)\n const done = total.filter(Boolean)\n const percent = done.length / total.length\n open.element.classList.add('running')\n open.element.style.setProperty('--progress', percent * 100 + '%')\n open.primary.element.classList.remove('mdi-progress-pencil')\n open.primary.element.classList.add('mdi-play')\n }\n\n #removeActive() {\n if (!this.activeElement) return\n this.activeElement.element.classList.remove('running')\n this.activeElement.element.style.removeProperty('--progress')\n this.activeElement.primary.element.classList.add('mdi-progress-pencil')\n this.activeElement.primary.element.classList.remove('mdi-play')\n }\n\n #getFavoriteIcon(workflow: ComfyWorkflow) {\n return workflow.isFavorite ? 'star' : 'file-outline'\n }\n\n #getFavoriteOverIcon(workflow: ComfyWorkflow) {\n return workflow.isFavorite ? 'star-off' : 'star-outline'\n }\n\n #getFavoriteTooltip(workflow: ComfyWorkflow) {\n return workflow.isFavorite\n ? 'Remove this workflow from your favorites'\n : 'Add this workflow to your favorites'\n }\n\n #getFavoriteButton(workflow: ComfyWorkflow, primary: boolean) {\n return new ComfyButton({\n icon: this.#getFavoriteIcon(workflow),\n overIcon: this.#getFavoriteOverIcon(workflow),\n iconSize: 18,\n classList:\n 'comfyui-button comfyui-workflows-file-action-favorite' +\n (primary ? ' comfyui-workflows-file-action-primary' : ''),\n tooltip: this.#getFavoriteTooltip(workflow),\n action: (e) => {\n e.stopImmediatePropagation()\n workflow.favorite(!workflow.isFavorite)\n }\n })\n }\n\n #getDeleteButton(workflow: ComfyWorkflow) {\n const deleteButton = new ComfyButton({\n icon: 'delete',\n tooltip: 'Delete this workflow',\n classList: 'comfyui-button comfyui-workflows-file-action',\n iconSize: 18,\n action: async (e, btn) => {\n e.stopImmediatePropagation()\n\n if (btn.icon === 'delete-empty') {\n btn.enabled = false\n await workflow.delete()\n await this.load()\n } else {\n btn.icon = 'delete-empty'\n btn.element.style.background = 'red'\n }\n }\n })\n deleteButton.element.addEventListener('mouseleave', () => {\n deleteButton.icon = 'delete'\n deleteButton.element.style.removeProperty('background')\n })\n return deleteButton\n }\n\n #getInsertButton(workflow: ComfyWorkflow) {\n return new ComfyButton({\n icon: 'file-move-outline',\n iconSize: 18,\n tooltip: 'Insert this workflow into the current workflow',\n classList: 'comfyui-button comfyui-workflows-file-action',\n action: (e) => {\n if (!this.app.shiftDown) {\n this.popup.open = false\n }\n e.stopImmediatePropagation()\n if (!this.app.shiftDown) {\n this.popup.open = false\n }\n workflow.insert()\n }\n })\n }\n\n /** @param {ComfyWorkflow} workflow */\n #getRenameButton(workflow: ComfyWorkflow) {\n return new ComfyButton({\n icon: 'pencil',\n tooltip: workflow.path\n ? 'Rename this workflow'\n : \"This workflow can't be renamed as it hasn't been saved.\",\n classList: 'comfyui-button comfyui-workflows-file-action',\n iconSize: 18,\n enabled: !!workflow.path,\n action: async (e) => {\n e.stopImmediatePropagation()\n const newName = prompt('Enter new name', workflow.path)\n if (newName) {\n await workflow.rename(newName)\n }\n }\n })\n }\n\n #getWorkflowElement(workflow: ComfyWorkflow) {\n return new WorkflowElement(this, workflow, {\n primary: this.#getFavoriteButton(workflow, true),\n buttons: [\n this.#getInsertButton(workflow),\n this.#getRenameButton(workflow),\n this.#getDeleteButton(workflow)\n ]\n })\n }\n\n #createLeafNode(workflow: ComfyWorkflow) {\n const fileNode = this.#getWorkflowElement(workflow)\n this.treeFiles[workflow.path] = fileNode\n return fileNode\n }\n\n #createNode(currentPath, workflow, i, currentRoot) {\n const part = workflow.pathParts[i]\n\n const parentNode = $el(\n 'ul' + (this.treeState[currentPath] ? '' : '.closed'),\n {\n $: (el) => {\n el.onclick = (e) => {\n this.#expandNode(el, workflow, currentPath, i)\n e.stopImmediatePropagation()\n }\n }\n }\n )\n currentRoot.append(parentNode)\n\n // Create a node for the current part and an inner UL for its children if it isnt a leaf node\n const leaf = i === workflow.pathParts.length - 1\n let nodeElement\n if (leaf) {\n nodeElement = this.#createLeafNode(workflow).element\n } else {\n nodeElement = $el('li', [\n $el('i.mdi.mdi-18px.mdi-folder'),\n $el('span', part)\n ])\n }\n parentNode.append(nodeElement)\n return parentNode\n }\n}\n\nclass WorkflowElement {\n parent: ComfyWorkflowsContent\n workflow: ComfyWorkflow\n primary: TPrimary\n buttons: ComfyButton[]\n element: HTMLElement\n constructor(\n parent: ComfyWorkflowsContent,\n workflow: ComfyWorkflow,\n {\n tagName = 'li',\n primary,\n buttons\n }: { tagName?: string; primary: TPrimary; buttons: ComfyButton[] }\n ) {\n this.parent = parent\n this.workflow = workflow\n this.primary = primary\n this.buttons = buttons\n\n this.element = $el(\n tagName + '.comfyui-workflows-tree-file',\n {\n onclick: () => {\n workflow.load()\n this.parent.popup.open = false\n },\n title: this.workflow.path\n },\n [\n this.primary?.element,\n $el('span', workflow.name),\n ...buttons.map((b) => b.element)\n ]\n )\n }\n}\n\ntype WidgetSelectionDialogOptions = Array<{\n widget: { name: string }\n node: { pos: [number, number]; title: string; id: string; type: string }\n}>\n\nclass WidgetSelectionDialog extends ComfyAsyncDialog {\n #options: WidgetSelectionDialogOptions\n\n constructor(options: WidgetSelectionDialogOptions) {\n super()\n this.#options = options\n }\n\n show(app) {\n this.element.classList.add('comfy-widget-selection-dialog')\n return super.show(\n $el('div', [\n $el('h2', 'Select image target'),\n $el(\n 'p',\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.\"\n ),\n $el(\n 'section',\n this.#options.map((opt) => {\n return $el('div.comfy-widget-selection-item', [\n $el(\n 'span',\n { dataset: { id: opt.node.id } },\n `${opt.node.title ?? opt.node.type} ${opt.widget.name}`\n ),\n $el(\n 'button.comfyui-button',\n {\n onclick: () => {\n app.canvas.ds.offset[0] = -opt.node.pos[0] + 50\n app.canvas.ds.offset[1] = -opt.node.pos[1] + 50\n app.canvas.selectNode(opt.node)\n app.graph.setDirtyCanvas(true, true)\n }\n },\n 'Show'\n ),\n $el(\n 'button.comfyui-button.primary',\n {\n onclick: () => {\n this.close(opt)\n }\n },\n 'Select'\n )\n ])\n })\n )\n ])\n )\n }\n}\n","import { StatusWsMessageStatus } from '@/types/apiTypes'\nimport { api } from '../../api'\nimport { ComfyButton } from '../components/button'\nimport { useToastStore } from '@/stores/toastStore'\n\nexport function getInterruptButton(visibility: string) {\n const btn = new ComfyButton({\n icon: 'close',\n tooltip: 'Cancel current generation',\n enabled: false,\n action: async () => {\n await api.interrupt()\n useToastStore().add({\n severity: 'info',\n summary: 'Interrupted',\n detail: 'Execution has been interrupted',\n life: 1000\n })\n },\n classList: ['comfyui-button', 'comfyui-interrupt-button', visibility]\n })\n\n api.addEventListener(\n 'status',\n ({ detail }: CustomEvent) => {\n const sz = detail?.exec_info?.queue_remaining\n btn.enabled = sz > 0\n }\n )\n\n return btn\n}\n","import type { ComfyApp } from '@/scripts/app'\nimport { api } from '../../api'\nimport { $el } from '../../ui'\nimport { downloadBlob } from '../../utils'\nimport { ComfyButton } from '../components/button'\nimport { ComfyButtonGroup } from '../components/buttonGroup'\nimport { ComfySplitButton } from '../components/splitButton'\nimport { ComfyQueueButton } from './queueButton'\nimport { ComfyWorkflowsMenu } from './workflows'\nimport { getInterruptButton } from './interruptButton'\nimport './menu.css'\nimport type { ComfySettingsDialog } from '../settings'\n\ntype MenuPosition = 'Disabled' | 'Top' | 'Bottom'\n\nconst collapseOnMobile = (t) => {\n ;(t.element ?? t).classList.add('comfyui-menu-mobile-collapse')\n return t\n}\nconst showOnMobile = (t) => {\n ;(t.element ?? t).classList.add('lt-lg-show')\n return t\n}\n\nexport class ComfyAppMenu {\n #sizeBreak = 'lg'\n #lastSizeBreaks = {\n lg: null,\n md: null,\n sm: null,\n xs: null\n }\n #sizeBreaks = Object.keys(this.#lastSizeBreaks)\n #cachedInnerSize = null\n #cacheTimeout = null\n app: ComfyApp\n workflows: ComfyWorkflowsMenu\n logo: HTMLElement\n saveButton: ComfySplitButton\n actionsGroup: ComfyButtonGroup\n settingsGroup: ComfyButtonGroup\n viewGroup: ComfyButtonGroup\n mobileMenuButton: ComfyButton\n queueButton: ComfyQueueButton\n element: HTMLElement\n menuPositionSetting: ReturnType\n position: MenuPosition\n\n constructor(app: ComfyApp) {\n this.app = app\n\n this.workflows = new ComfyWorkflowsMenu(app)\n const getSaveButton = (t?: string) =>\n new ComfyButton({\n icon: 'content-save',\n tooltip: 'Save the current workflow',\n action: () => app.workflowManager.activeWorkflow.save(),\n content: t\n })\n\n this.logo = $el('h1.comfyui-logo.nlg-hide', { title: 'ComfyUI' }, 'ComfyUI')\n this.saveButton = new ComfySplitButton(\n {\n primary: getSaveButton(),\n mode: 'hover',\n position: 'absolute'\n },\n getSaveButton('Save'),\n new ComfyButton({\n icon: 'content-save-edit',\n content: 'Save As',\n tooltip: 'Save the current graph as a new workflow',\n action: () => app.workflowManager.activeWorkflow.save(true)\n }),\n new ComfyButton({\n icon: 'download',\n content: 'Export',\n tooltip: 'Export the current workflow as JSON',\n action: () => this.exportWorkflow('workflow', 'workflow')\n }),\n new ComfyButton({\n icon: 'api',\n content: 'Export (API Format)',\n tooltip:\n 'Export the current workflow as JSON for use with the ComfyUI API',\n action: () => this.exportWorkflow('workflow_api', 'output'),\n visibilitySetting: { id: 'Comfy.DevMode', showValue: true },\n app\n })\n )\n\n this.actionsGroup = new ComfyButtonGroup(\n new ComfyButton({\n icon: 'refresh',\n content: 'Refresh',\n tooltip: 'Refresh widgets in nodes to find new models or files',\n action: () => app.refreshComboInNodes()\n }),\n new ComfyButton({\n icon: 'clipboard-edit-outline',\n content: 'Clipspace',\n tooltip: 'Open Clipspace window',\n action: () => app['openClipspace']()\n }),\n new ComfyButton({\n icon: 'fit-to-page-outline',\n content: 'Reset View',\n tooltip: 'Reset the canvas view',\n action: () => app.resetView()\n }),\n new ComfyButton({\n icon: 'cancel',\n content: 'Clear',\n tooltip: 'Clears current workflow',\n action: () => {\n if (\n !app.ui.settings.getSettingValue('Comfy.ConfirmClear', true) ||\n confirm('Clear workflow?')\n ) {\n app.clean()\n app.graph.clear()\n api.dispatchEvent(new CustomEvent('graphCleared'))\n }\n }\n })\n )\n // Keep the settings group as there are custom scripts attaching extra\n // elements to it.\n this.settingsGroup = new ComfyButtonGroup()\n this.viewGroup = new ComfyButtonGroup(\n getInterruptButton('nlg-hide').element\n )\n this.mobileMenuButton = new ComfyButton({\n icon: 'menu',\n action: (_, btn) => {\n btn.icon = this.element.classList.toggle('expanded')\n ? 'menu-open'\n : 'menu'\n window.dispatchEvent(new Event('resize'))\n },\n classList: 'comfyui-button comfyui-menu-button'\n })\n this.queueButton = new ComfyQueueButton(app)\n\n this.element = $el('nav.comfyui-menu.lg', { style: { display: 'none' } }, [\n this.logo,\n this.workflows.element,\n this.saveButton.element,\n collapseOnMobile(this.actionsGroup).element,\n $el('section.comfyui-menu-push'),\n collapseOnMobile(this.settingsGroup).element,\n collapseOnMobile(this.viewGroup).element,\n\n getInterruptButton('lt-lg-show').element,\n this.queueButton.element,\n showOnMobile(this.mobileMenuButton).element\n ])\n\n let resizeHandler: () => void\n this.menuPositionSetting = app.ui.settings.addSetting({\n id: 'Comfy.UseNewMenu',\n category: ['Comfy', 'Menu', 'UseNewMenu'],\n defaultValue: 'Disabled',\n name: 'Use new menu and workflow management.',\n experimental: true,\n tooltip: 'On small screens the menu will always be at the top.',\n type: 'combo',\n options: ['Disabled', 'Top', 'Bottom'],\n onChange: async (v: MenuPosition) => {\n if (v && v !== 'Disabled') {\n if (!resizeHandler) {\n resizeHandler = () => {\n this.calculateSizeBreak()\n }\n window.addEventListener('resize', resizeHandler)\n }\n this.updatePosition(v)\n } else {\n if (resizeHandler) {\n window.removeEventListener('resize', resizeHandler)\n resizeHandler = null\n }\n document.body.style.removeProperty('display')\n if (app.ui.menuContainer) {\n app.ui.menuContainer.style.removeProperty('display')\n }\n this.element.style.display = 'none'\n app.ui.restoreMenuPosition()\n }\n window.dispatchEvent(new Event('resize'))\n }\n })\n }\n\n updatePosition(v: MenuPosition) {\n document.body.style.display = 'grid'\n if (this.app.ui.menuContainer) {\n this.app.ui.menuContainer.style.display = 'none'\n }\n this.element.style.removeProperty('display')\n this.position = v\n if (v === 'Bottom') {\n this.app.bodyBottom.append(this.element)\n } else {\n this.app.bodyTop.prepend(this.element)\n }\n this.calculateSizeBreak()\n }\n\n updateSizeBreak(idx: number, prevIdx: number, direction: number) {\n const newSize = this.#sizeBreaks[idx]\n if (newSize === this.#sizeBreak) return\n this.#cachedInnerSize = null\n clearTimeout(this.#cacheTimeout)\n\n this.#sizeBreak = this.#sizeBreaks[idx]\n for (let i = 0; i < this.#sizeBreaks.length; i++) {\n const sz = this.#sizeBreaks[i]\n if (sz === this.#sizeBreak) {\n this.element.classList.add(sz)\n } else {\n this.element.classList.remove(sz)\n }\n if (i < idx) {\n this.element.classList.add('lt-' + sz)\n } else {\n this.element.classList.remove('lt-' + sz)\n }\n }\n\n if (idx) {\n // We're on a small screen, force the menu at the top\n if (this.position !== 'Top') {\n this.updatePosition('Top')\n }\n } else if (this.position != this.menuPositionSetting.value) {\n // Restore user position\n this.updatePosition(this.menuPositionSetting.value)\n }\n\n // Allow multiple updates, but prevent bouncing\n if (!direction) {\n direction = prevIdx - idx\n } else if (direction != prevIdx - idx) {\n return\n }\n this.calculateSizeBreak(direction)\n }\n\n calculateSizeBreak(direction = 0) {\n let idx = this.#sizeBreaks.indexOf(this.#sizeBreak)\n const currIdx = idx\n const innerSize = this.calculateInnerSize(idx)\n if (window.innerWidth >= this.#lastSizeBreaks[this.#sizeBreaks[idx - 1]]) {\n if (idx > 0) {\n idx--\n }\n } else if (innerSize > this.element.clientWidth) {\n this.#lastSizeBreaks[this.#sizeBreak] = Math.max(\n window.innerWidth,\n innerSize\n )\n // We need to shrink\n if (idx < this.#sizeBreaks.length - 1) {\n idx++\n }\n }\n\n this.updateSizeBreak(idx, currIdx, direction)\n }\n\n calculateInnerSize(idx: number) {\n // Cache the inner size to prevent too much calculation when resizing the window\n clearTimeout(this.#cacheTimeout)\n if (this.#cachedInnerSize) {\n // Extend cache time\n this.#cacheTimeout = setTimeout(() => (this.#cachedInnerSize = null), 100)\n } else {\n let innerSize = 0\n let count = 1\n for (const c of this.element.children) {\n if (c.classList.contains('comfyui-menu-push')) continue // ignore right push\n if (idx && c.classList.contains('comfyui-menu-mobile-collapse'))\n continue // ignore collapse items\n innerSize += c.clientWidth\n count++\n }\n innerSize += 8 * count\n this.#cachedInnerSize = innerSize\n this.#cacheTimeout = setTimeout(() => (this.#cachedInnerSize = null), 100)\n }\n return this.#cachedInnerSize\n }\n\n getFilename(defaultName: string) {\n if (this.app.ui.settings.getSettingValue('Comfy.PromptFilename', true)) {\n defaultName = prompt('Save workflow as:', defaultName)\n if (!defaultName) return\n if (!defaultName.toLowerCase().endsWith('.json')) {\n defaultName += '.json'\n }\n }\n return defaultName\n }\n\n async exportWorkflow(\n filename: string,\n promptProperty: 'workflow' | 'output'\n ) {\n if (this.app.workflowManager.activeWorkflow?.path) {\n filename = this.app.workflowManager.activeWorkflow.name\n }\n const p = await this.app.graphToPrompt()\n const json = JSON.stringify(p[promptProperty], null, 2)\n const blob = new Blob([json], { type: 'application/json' })\n const file = this.getFilename(filename)\n if (!file) return\n downloadBlob(file, blob)\n }\n}\n","import type { ComfyApp } from './app'\nimport { api } from './api'\nimport { clone } from './utils'\nimport { LGraphCanvas, LiteGraph } from '@comfyorg/litegraph'\nimport { ComfyWorkflow } from './workflows'\n\nexport class ChangeTracker {\n static MAX_HISTORY = 50\n #app: ComfyApp\n undo = []\n redo = []\n activeState = null\n isOurLoad = false\n workflow: ComfyWorkflow | null\n\n ds: { scale: number; offset: [number, number] }\n nodeOutputs: any\n\n get app() {\n return this.#app ?? this.workflow.manager.app\n }\n\n constructor(workflow: ComfyWorkflow) {\n this.workflow = workflow\n }\n\n #setApp(app) {\n this.#app = app\n }\n\n store() {\n this.ds = {\n scale: this.app.canvas.ds.scale,\n offset: [...this.app.canvas.ds.offset]\n }\n }\n\n restore() {\n if (this.ds) {\n this.app.canvas.ds.scale = this.ds.scale\n this.app.canvas.ds.offset = this.ds.offset\n }\n if (this.nodeOutputs) {\n this.app.nodeOutputs = this.nodeOutputs\n }\n }\n\n checkState() {\n if (!this.app.graph) return\n\n const currentState = this.app.graph.serialize()\n if (!this.activeState) {\n this.activeState = clone(currentState)\n return\n }\n if (!ChangeTracker.graphEqual(this.activeState, currentState)) {\n this.undo.push(this.activeState)\n if (this.undo.length > ChangeTracker.MAX_HISTORY) {\n this.undo.shift()\n }\n this.activeState = clone(currentState)\n this.redo.length = 0\n this.workflow.unsaved = true\n api.dispatchEvent(\n new CustomEvent('graphChanged', { detail: this.activeState })\n )\n }\n }\n\n async updateState(source, target) {\n const prevState = source.pop()\n if (prevState) {\n target.push(this.activeState)\n this.isOurLoad = true\n await this.app.loadGraphData(prevState, false, false, this.workflow, {\n showMissingModelsDialog: false,\n showMissingNodesDialog: false\n })\n this.activeState = prevState\n }\n }\n\n async undoRedo(e) {\n if (e.ctrlKey || e.metaKey) {\n if (e.code === 'KeyY') {\n this.updateState(this.redo, this.undo)\n return true\n } else if (e.code === 'KeyZ') {\n this.updateState(this.undo, this.redo)\n return true\n }\n }\n }\n\n static init(app: ComfyApp) {\n const changeTracker = () =>\n app.workflowManager.activeWorkflow?.changeTracker ?? globalTracker\n globalTracker.#setApp(app)\n\n const loadGraphData = app.loadGraphData\n app.loadGraphData = async function () {\n const v = await loadGraphData.apply(this, arguments)\n const ct = changeTracker()\n if (ct.isOurLoad) {\n ct.isOurLoad = false\n } else {\n ct.checkState()\n }\n return v\n }\n\n let keyIgnored = false\n window.addEventListener(\n 'keydown',\n (e) => {\n const activeEl = document.activeElement\n requestAnimationFrame(async () => {\n let bindInputEl\n // If we are auto queue in change mode then we do want to trigger on inputs\n if (!app.ui.autoQueueEnabled || app.ui.autoQueueMode === 'instant') {\n if (\n activeEl?.tagName === 'INPUT' ||\n activeEl?.['type'] === 'textarea'\n ) {\n // Ignore events on inputs, they have their native history\n return\n }\n bindInputEl = activeEl\n }\n\n keyIgnored =\n e.key === 'Control' ||\n e.key === 'Shift' ||\n e.key === 'Alt' ||\n e.key === 'Meta'\n if (keyIgnored) return\n\n // Check if this is a ctrl+z ctrl+y\n if (await changeTracker().undoRedo(e)) return\n\n // If our active element is some type of input then handle changes after they're done\n if (ChangeTracker.bindInput(app, bindInputEl)) return\n changeTracker().checkState()\n })\n },\n true\n )\n\n window.addEventListener('keyup', (e) => {\n if (keyIgnored) {\n keyIgnored = false\n changeTracker().checkState()\n }\n })\n\n // Handle clicking DOM elements (e.g. widgets)\n window.addEventListener('mouseup', () => {\n changeTracker().checkState()\n })\n\n // Handle prompt queue event for dynamic widget changes\n api.addEventListener('promptQueued', () => {\n changeTracker().checkState()\n })\n\n api.addEventListener('graphCleared', () => {\n changeTracker().checkState()\n })\n\n // Handle litegraph clicks\n const processMouseUp = LGraphCanvas.prototype.processMouseUp\n LGraphCanvas.prototype.processMouseUp = function (e) {\n const v = processMouseUp.apply(this, arguments)\n changeTracker().checkState()\n return v\n }\n const processMouseDown = LGraphCanvas.prototype.processMouseDown\n LGraphCanvas.prototype.processMouseDown = function (e) {\n const v = processMouseDown.apply(this, arguments)\n changeTracker().checkState()\n return v\n }\n\n // Handle litegraph context menu for COMBO widgets\n const close = LiteGraph.ContextMenu.prototype.close\n LiteGraph.ContextMenu.prototype.close = function (e) {\n const v = close.apply(this, arguments)\n changeTracker().checkState()\n return v\n }\n\n // Detects nodes being added via the node search dialog\n const onNodeAdded = LiteGraph.LGraph.prototype.onNodeAdded\n LiteGraph.LGraph.prototype.onNodeAdded = function () {\n const v = onNodeAdded?.apply(this, arguments)\n if (!app?.configuringGraph) {\n const ct = changeTracker()\n if (!ct.isOurLoad) {\n ct.checkState()\n }\n }\n return v\n }\n\n // Store node outputs\n api.addEventListener('executed', ({ detail }) => {\n const prompt =\n app.workflowManager.executionStore.queuedPrompts[detail.prompt_id]\n if (!prompt?.workflow) return\n const nodeOutputs = (prompt.workflow.changeTracker.nodeOutputs ??= {})\n const output = nodeOutputs[detail.node]\n if (detail.merge && output) {\n for (const k in detail.output ?? {}) {\n const v = output[k]\n if (v instanceof Array) {\n output[k] = v.concat(detail.output[k])\n } else {\n output[k] = detail.output[k]\n }\n }\n } else {\n nodeOutputs[detail.node] = detail.output\n }\n })\n }\n\n static bindInput(app, activeEl) {\n if (\n activeEl &&\n activeEl.tagName !== 'CANVAS' &&\n activeEl.tagName !== 'BODY'\n ) {\n for (const evt of ['change', 'input', 'blur']) {\n if (`on${evt}` in activeEl) {\n const listener = () => {\n app.workflowManager.activeWorkflow.changeTracker.checkState()\n activeEl.removeEventListener(evt, listener)\n }\n activeEl.addEventListener(evt, listener)\n return true\n }\n }\n }\n }\n\n static graphEqual(a, b, path = '') {\n if (a === b) return true\n\n if (typeof a == 'object' && a && typeof b == 'object' && b) {\n const keys = Object.getOwnPropertyNames(a)\n\n if (keys.length != Object.getOwnPropertyNames(b).length) {\n return false\n }\n\n for (const key of keys) {\n let av = a[key]\n let bv = b[key]\n if (!path && key === 'nodes') {\n // Nodes need to be sorted as the order changes when selecting nodes\n av = [...av].sort((a, b) => a.id - b.id)\n bv = [...bv].sort((a, b) => a.id - b.id)\n } else if (path === 'extra.ds') {\n // Ignore view changes\n continue\n }\n if (!ChangeTracker.graphEqual(av, bv, path + (path ? '.' : '') + key)) {\n return false\n }\n }\n\n return true\n }\n\n return false\n }\n}\n\nconst globalTracker = new ChangeTracker({} as ComfyWorkflow)\n","import type { ComfyApp } from './app'\nimport { api } from './api'\nimport { ChangeTracker } from './changeTracker'\nimport { ComfyAsyncDialog } from './ui/components/asyncDialog'\nimport { getStorageValue, setStorageValue } from './utils'\nimport { LGraphCanvas, LGraph } from '@comfyorg/litegraph'\nimport { appendJsonExt, trimJsonExt } from '@/utils/formatUtil'\nimport { useWorkflowStore } from '@/stores/workflowStore'\nimport { useExecutionStore } from '@/stores/executionStore'\nimport { markRaw, toRaw } from 'vue'\n\nexport class ComfyWorkflowManager extends EventTarget {\n executionStore: ReturnType | null\n workflowStore: ReturnType | null\n\n app: ComfyApp\n #unsavedCount = 0\n\n get workflowLookup(): Record {\n return this.workflowStore?.workflowLookup ?? {}\n }\n\n get workflows(): ComfyWorkflow[] {\n return this.workflowStore?.workflows ?? []\n }\n\n get openWorkflows(): ComfyWorkflow[] {\n return (this.workflowStore?.openWorkflows ?? []) as ComfyWorkflow[]\n }\n\n get _activeWorkflow(): ComfyWorkflow | null {\n if (!this.app.vueAppReady) return null\n return toRaw(useWorkflowStore().activeWorkflow) as ComfyWorkflow | null\n }\n\n set _activeWorkflow(workflow: ComfyWorkflow | null) {\n if (!this.app.vueAppReady) return\n useWorkflowStore().activeWorkflow = workflow ? markRaw(workflow) : null\n }\n\n get activeWorkflow(): ComfyWorkflow | null {\n return this._activeWorkflow ?? this.openWorkflows[0]\n }\n\n get activePromptId() {\n return this.executionStore?.activePromptId\n }\n\n get activePrompt() {\n return this.executionStore?.activePrompt\n }\n\n constructor(app: ComfyApp) {\n super()\n this.app = app\n ChangeTracker.init(app)\n }\n\n async loadWorkflows() {\n try {\n let favorites\n const resp = await api.getUserData('workflows/.index.json')\n let info\n if (resp.status === 200) {\n info = await resp.json()\n favorites = new Set(info?.favorites ?? [])\n } else {\n favorites = new Set()\n }\n\n const workflows = (await api.listUserData('workflows', true, true)).map(\n (w) => {\n let workflow = this.workflowLookup[w[0]]\n if (!workflow) {\n workflow = new ComfyWorkflow(\n this,\n w[0],\n w.slice(1),\n favorites.has(w[0])\n )\n this.workflowLookup[workflow.path] = markRaw(workflow)\n }\n return workflow\n }\n )\n } catch (error) {\n alert('Error loading workflows: ' + (error.message ?? error))\n }\n }\n\n async saveWorkflowMetadata() {\n await api.storeUserData('workflows/.index.json', {\n favorites: [\n ...this.workflows.filter((w) => w.isFavorite).map((w) => w.path)\n ]\n })\n }\n\n /**\n * @param {string | ComfyWorkflow | null} workflow\n */\n setWorkflow(workflow) {\n if (workflow && typeof workflow === 'string') {\n // Selected by path, i.e. on reload of last workflow\n const found = this.workflows.find((w) => w.path === workflow)\n if (found) {\n workflow = found\n workflow.unsaved =\n !workflow ||\n getStorageValue('Comfy.PreviousWorkflowUnsaved') === 'true'\n }\n }\n\n if (!(workflow instanceof ComfyWorkflow)) {\n // Still not found, either reloading a deleted workflow or blank\n workflow = new ComfyWorkflow(\n this,\n workflow ||\n 'Unsaved Workflow' +\n (this.#unsavedCount++ ? ` (${this.#unsavedCount})` : '')\n )\n }\n\n const index = this.openWorkflows.indexOf(workflow)\n if (index === -1) {\n // Opening a new workflow\n this.openWorkflows.push(markRaw(workflow))\n }\n\n this._activeWorkflow = workflow\n\n setStorageValue('Comfy.PreviousWorkflow', this.activeWorkflow.path ?? '')\n this.dispatchEvent(new CustomEvent('changeWorkflow'))\n }\n\n storePrompt({ nodes, id }) {\n this.executionStore?.storePrompt({\n nodes,\n id,\n workflow: this.activeWorkflow\n })\n }\n\n /**\n * @param {ComfyWorkflow} workflow\n */\n async closeWorkflow(workflow, warnIfUnsaved = true) {\n if (!workflow.isOpen) {\n return true\n }\n if (workflow.unsaved && warnIfUnsaved) {\n const res = await ComfyAsyncDialog.prompt({\n title: 'Save Changes?',\n message: `Do you want to save changes to \"${workflow.path ?? workflow.name}\" before closing?`,\n actions: ['Yes', 'No', 'Cancel']\n })\n if (res === 'Yes') {\n const active = this.activeWorkflow\n if (active !== workflow) {\n // We need to switch to the workflow to save it\n await workflow.load()\n }\n\n if (!(await workflow.save())) {\n // Save was canceled, restore the previous workflow\n if (active !== workflow) {\n await active.load()\n }\n return\n }\n } else if (res === 'Cancel') {\n return\n }\n }\n workflow.changeTracker = null\n this.openWorkflows.splice(this.openWorkflows.indexOf(workflow), 1)\n if (this.openWorkflows.length) {\n this._activeWorkflow = this.openWorkflows[0]\n await this._activeWorkflow.load()\n } else {\n // Load default\n await this.app.loadGraphData()\n }\n }\n}\n\nexport class ComfyWorkflow {\n #name\n #path\n #pathParts\n #isFavorite = false\n changeTracker: ChangeTracker | null = null\n unsaved = false\n manager: ComfyWorkflowManager\n\n get name() {\n return this.#name\n }\n\n get path() {\n return this.#path\n }\n\n get pathParts() {\n return this.#pathParts\n }\n\n get isFavorite() {\n return this.#isFavorite\n }\n\n get isOpen() {\n return !!this.changeTracker\n }\n\n constructor(\n manager: ComfyWorkflowManager,\n path: string,\n pathParts?: string[],\n isFavorite?: boolean\n ) {\n this.manager = manager\n if (pathParts) {\n this.#updatePath(path, pathParts)\n this.#isFavorite = isFavorite\n } else {\n this.#name = path\n this.unsaved = true\n }\n }\n\n #updatePath(path: string, pathParts: string[]) {\n this.#path = path\n\n if (!pathParts) {\n if (!path.includes('\\\\')) {\n pathParts = path.split('/')\n } else {\n pathParts = path.split('\\\\')\n }\n }\n\n this.#pathParts = pathParts\n this.#name = trimJsonExt(pathParts[pathParts.length - 1])\n }\n\n async getWorkflowData() {\n const resp = await api.getUserData('workflows/' + this.path)\n if (resp.status !== 200) {\n alert(\n `Error loading workflow file '${this.path}': ${resp.status} ${resp.statusText}`\n )\n return\n }\n return await resp.json()\n }\n\n load = async () => {\n if (this.isOpen) {\n await this.manager.app.loadGraphData(\n this.changeTracker.activeState,\n true,\n true,\n this,\n {\n showMissingModelsDialog: false,\n showMissingNodesDialog: false\n }\n )\n } else {\n const data = await this.getWorkflowData()\n if (!data) return\n await this.manager.app.loadGraphData(data, true, true, this)\n }\n }\n\n async save(saveAs = false) {\n if (!this.path || saveAs) {\n return !!(await this.#save(null, false))\n } else {\n return !!(await this.#save(this.path, true))\n }\n }\n\n async favorite(value: boolean) {\n try {\n if (this.#isFavorite === value) return\n this.#isFavorite = value\n await this.manager.saveWorkflowMetadata()\n this.manager.dispatchEvent(new CustomEvent('favorite', { detail: this }))\n } catch (error) {\n alert(\n 'Error favoriting workflow ' +\n this.path +\n '\\n' +\n (error.message ?? error)\n )\n }\n }\n\n async rename(path: string) {\n path = appendJsonExt(path)\n let resp = await api.moveUserData(\n 'workflows/' + this.path,\n 'workflows/' + path\n )\n\n if (resp.status === 409) {\n if (\n !confirm(\n `Workflow '${path}' already exists, do you want to overwrite it?`\n )\n )\n return resp\n resp = await api.moveUserData(\n 'workflows/' + this.path,\n 'workflows/' + path,\n { overwrite: true }\n )\n }\n\n if (resp.status !== 200) {\n alert(\n `Error renaming workflow file '${this.path}': ${resp.status} ${resp.statusText}`\n )\n return\n }\n\n const isFav = this.isFavorite\n if (isFav) {\n await this.favorite(false)\n }\n path = (await resp.json()).substring('workflows/'.length)\n this.#updatePath(path, null)\n if (isFav) {\n await this.favorite(true)\n }\n this.manager.dispatchEvent(new CustomEvent('rename', { detail: this }))\n setStorageValue('Comfy.PreviousWorkflow', this.path ?? '')\n }\n\n async insert() {\n const data = await this.getWorkflowData()\n if (!data) return\n\n const old = localStorage.getItem('litegrapheditor_clipboard')\n const graph = new LGraph(data)\n const canvas = new LGraphCanvas(null, graph, {\n // @ts-expect-error\n skip_events: true,\n skip_render: true\n })\n canvas.selectNodes()\n canvas.copyToClipboard()\n this.manager.app.canvas.pasteFromClipboard()\n localStorage.setItem('litegrapheditor_clipboard', old)\n }\n\n async delete() {\n // TODO: fix delete of current workflow - should mark workflow as unsaved and when saving use old name by default\n\n if (this.isFavorite) {\n await this.favorite(false)\n }\n const resp = await api.deleteUserData('workflows/' + this.path)\n if (resp.status !== 204) {\n alert(\n `Error removing user data file '${this.path}': ${resp.status} ${resp.statusText}`\n )\n }\n\n this.unsaved = true\n this.#path = null\n this.#pathParts = null\n this.manager.workflows.splice(this.manager.workflows.indexOf(this), 1)\n this.manager.dispatchEvent(new CustomEvent('delete', { detail: this }))\n }\n\n track() {\n if (this.changeTracker) {\n this.changeTracker.restore()\n } else {\n this.changeTracker = new ChangeTracker(this)\n }\n }\n\n async #save(path: string | null, overwrite: boolean) {\n if (!path) {\n path = prompt(\n 'Save workflow as:',\n trimJsonExt(this.path) ?? this.name ?? 'workflow'\n )\n if (!path) return\n }\n\n path = appendJsonExt(path)\n\n const p = await this.manager.app.graphToPrompt()\n const json = JSON.stringify(p.workflow, null, 2)\n let resp = await api.storeUserData('workflows/' + path, json, {\n stringify: false,\n throwOnError: false,\n overwrite\n })\n if (resp.status === 409) {\n if (\n !confirm(\n `Workflow '${path}' already exists, do you want to overwrite it?`\n )\n )\n return\n resp = await api.storeUserData('workflows/' + path, json, {\n stringify: false\n })\n }\n\n if (resp.status !== 200) {\n alert(\n `Error saving workflow '${this.path}': ${resp.status} ${resp.statusText}`\n )\n return\n }\n\n path = (await resp.json()).substring('workflows/'.length)\n\n if (!this.path) {\n // Saved new workflow, patch this instance\n this.#updatePath(path, null)\n await this.manager.loadWorkflows()\n this.unsaved = false\n this.manager.dispatchEvent(new CustomEvent('rename', { detail: this }))\n setStorageValue('Comfy.PreviousWorkflow', this.path ?? '')\n } else if (path !== this.path) {\n // Saved as, open the new copy\n await this.manager.loadWorkflows()\n const workflow = this.manager.workflowLookup[path]\n await workflow.load()\n } else {\n // Normal save\n this.unsaved = false\n this.manager.dispatchEvent(new CustomEvent('save', { detail: this }))\n }\n\n return true\n }\n}\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'\nimport Fuse, { IFuseOptions, FuseSearchOptions } from 'fuse.js'\nimport _ from 'lodash'\n\nexport type SearchAuxScore = number[]\n\ninterface ExtraSearchOptions {\n matchWildcards?: boolean\n}\n\nexport class FuseSearch {\n private fuse: Fuse\n private readonly keys: string[]\n public readonly data: T[]\n public readonly advancedScoring: boolean\n\n constructor(\n data: T[],\n options?: IFuseOptions,\n createIndex: boolean = true,\n advancedScoring: boolean = false\n ) {\n this.data = data\n this.keys = (options.keys ?? []) as string[]\n this.advancedScoring = advancedScoring\n const index =\n createIndex && options?.keys\n ? Fuse.createIndex(options.keys, data)\n : undefined\n this.fuse = new Fuse(data, options, index)\n }\n\n public search(query: string, options?: FuseSearchOptions): T[] {\n const fuseResult = !query\n ? this.data.map((x) => ({ item: x, score: 0 }))\n : this.fuse.search(query, options)\n\n if (!this.advancedScoring) {\n return fuseResult.map((x) => x.item)\n }\n\n const aux = fuseResult\n .map((x) => ({\n item: x.item,\n scores: this.calcAuxScores(query.toLocaleLowerCase(), x.item, x.score)\n }))\n .sort((a, b) => this.compareAux(a.scores, b.scores))\n\n return aux.map((x) => x.item)\n }\n\n public calcAuxScores(query: string, entry: T, score: number): SearchAuxScore {\n let values: string[] = []\n if (!this.keys.length) values = [entry as string]\n else values = this.keys.map((x) => entry[x])\n const scores = values.map((x) => this.calcAuxSingle(query, x, score))\n let result = scores.sort(this.compareAux)[0]\n\n const deprecated = values.some((x) =>\n x.toLocaleLowerCase().includes('deprecated')\n )\n result[0] += deprecated && result[0] != 0 ? 5 : 0\n if (entry['postProcessSearchScores']) {\n result = entry['postProcessSearchScores'](result) as SearchAuxScore\n }\n return result\n }\n\n public calcAuxSingle(\n query: string,\n item: string,\n score: number\n ): SearchAuxScore {\n const itemWords = item\n .split(/ |\\b|(?<=[a-z])(?=[A-Z])|(?=[A-Z][a-z])/)\n .map((x) => x.toLocaleLowerCase())\n const queryParts = query.split(' ')\n item = item.toLocaleLowerCase()\n\n let main = 9\n let aux1 = 0\n let aux2 = 0\n\n if (item == query) {\n main = 0\n } else if (item.startsWith(query)) {\n main = 1\n aux2 = item.length\n } else if (itemWords.includes(query)) {\n main = 2\n aux1 = item.indexOf(query) + item.length * 0.5\n aux2 = item.length\n } else if (item.includes(query)) {\n main = 3\n aux1 = item.indexOf(query) + item.length * 0.5\n aux2 = item.length\n } else if (queryParts.every((x) => itemWords.includes(x))) {\n const indexes = queryParts.map((x) => itemWords.indexOf(x))\n const min = Math.min(...indexes)\n const max = Math.max(...indexes)\n main = 4\n aux1 = max - min + max * 0.5 + item.length * 0.5\n aux2 = item.length\n } else if (queryParts.every((x) => item.includes(x))) {\n const min = Math.min(...queryParts.map((x) => item.indexOf(x)))\n const max = Math.max(...queryParts.map((x) => item.indexOf(x) + x.length))\n main = 5\n aux1 = max - min + max * 0.5 + item.length * 0.5\n aux2 = item.length\n }\n\n const lengthPenalty =\n 0.2 *\n (1 -\n Math.min(item.length, query.length) /\n Math.max(item.length, query.length))\n return [main, aux1, aux2, score + lengthPenalty]\n }\n\n public compareAux(a: SearchAuxScore, b: SearchAuxScore) {\n for (let i = 0; i < Math.min(a.length, b.length); i++) {\n if (a[i] !== b[i]) {\n return a[i] - b[i]\n }\n }\n return a.length - b.length\n }\n}\n\nexport type FilterAndValue = [NodeFilter, T]\n\nexport abstract class NodeFilter {\n public abstract readonly id: string\n public abstract readonly name: string\n public abstract readonly invokeSequence: string\n public abstract readonly longInvokeSequence: string\n public readonly fuseSearch: FuseSearch\n\n constructor(\n nodeDefs: ComfyNodeDefImpl[],\n options?: IFuseOptions\n ) {\n this.fuseSearch = new FuseSearch(this.getAllNodeOptions(nodeDefs), options)\n }\n\n private getAllNodeOptions(nodeDefs: ComfyNodeDefImpl[]): FilterOptionT[] {\n return [\n ...new Set(\n nodeDefs.reduce((acc, nodeDef) => {\n return [...acc, ...this.getNodeOptions(nodeDef)]\n }, [])\n )\n ]\n }\n\n public abstract getNodeOptions(node: ComfyNodeDefImpl): FilterOptionT[]\n\n public matches(\n node: ComfyNodeDefImpl,\n value: FilterOptionT,\n extraOptions?: ExtraSearchOptions\n ): boolean {\n const matchWildcards = extraOptions?.matchWildcards !== false\n if (matchWildcards && value === '*') {\n return true\n }\n const options = this.getNodeOptions(node)\n return (\n options.includes(value) ||\n (matchWildcards && _.some(options, (option) => option === '*'))\n )\n }\n}\n\nexport class InputTypeFilter extends NodeFilter {\n public readonly id: string = 'input'\n public readonly name = 'Input Type'\n public readonly invokeSequence = 'i'\n public readonly longInvokeSequence = 'input'\n\n public override getNodeOptions(node: ComfyNodeDefImpl): string[] {\n return node.input.all.map((input) => input.type)\n }\n}\n\nexport class OutputTypeFilter extends NodeFilter {\n public readonly id: string = 'output'\n public readonly name = 'Output Type'\n public readonly invokeSequence = 'o'\n public readonly longInvokeSequence = 'output'\n\n public override getNodeOptions(node: ComfyNodeDefImpl): string[] {\n return node.output.all.map((output) => output.type)\n }\n}\n\nexport class NodeSourceFilter extends NodeFilter {\n public readonly id: string = 'source'\n public readonly name = 'Source'\n public readonly invokeSequence = 's'\n public readonly longInvokeSequence = 'source'\n\n public override getNodeOptions(node: ComfyNodeDefImpl): string[] {\n return [node.nodeSource.displayText]\n }\n}\n\nexport class NodeCategoryFilter extends NodeFilter {\n public readonly id: string = 'category'\n public readonly name = 'Category'\n public readonly invokeSequence = 'c'\n public readonly longInvokeSequence = 'category'\n\n public override getNodeOptions(node: ComfyNodeDefImpl): string[] {\n return [node.category]\n }\n}\n\nexport class NodeSearchService {\n public readonly nodeFuseSearch: FuseSearch\n public readonly nodeFilters: NodeFilter[]\n\n constructor(data: ComfyNodeDefImpl[]) {\n this.nodeFuseSearch = new FuseSearch(\n data,\n {\n keys: ['name', 'display_name'],\n includeScore: true,\n threshold: 0.3,\n shouldSort: false,\n useExtendedSearch: true\n },\n true,\n true\n )\n\n const filterSearchOptions = {\n includeScore: true,\n threshold: 0.3,\n shouldSort: true\n }\n\n this.nodeFilters = [\n new InputTypeFilter(data, filterSearchOptions),\n new OutputTypeFilter(data, filterSearchOptions),\n new NodeCategoryFilter(data, filterSearchOptions)\n ]\n\n if (data[0].python_module !== undefined) {\n this.nodeFilters.push(new NodeSourceFilter(data, filterSearchOptions))\n }\n }\n\n public endsWithFilterStartSequence(query: string): boolean {\n return query.endsWith(':')\n }\n\n public searchNode(\n query: string,\n filters: FilterAndValue[] = [],\n options?: FuseSearchOptions,\n extraOptions?: ExtraSearchOptions\n ): ComfyNodeDefImpl[] {\n const matchedNodes = this.nodeFuseSearch.search(query)\n\n const results = matchedNodes.filter((node) => {\n return _.every(filters, (filterAndValue) => {\n const [filter, value] = filterAndValue\n return filter.matches(node, value, extraOptions)\n })\n })\n\n return options?.limit ? results.slice(0, options.limit) : results\n }\n\n public getFilterById(id: string): NodeFilter | undefined {\n return this.nodeFilters.find((filter) => filter.id === id)\n }\n}\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 {\n NodeSearchService,\n type SearchAuxScore\n} from '@/services/nodeSearchService'\nimport { ComfyNodeDef } from '@/types/apiTypes'\nimport { defineStore } from 'pinia'\nimport { Type, Transform, plainToClass, Expose } from 'class-transformer'\nimport { ComfyWidgetConstructor } from '@/scripts/widgets'\nimport { TreeNode } from 'primevue/treenode'\nimport { buildTree } from '@/utils/treeUtil'\nimport { computed, ref } from 'vue'\nimport axios from 'axios'\nimport { type NodeSource, getNodeSource } from '@/types/nodeSource'\n\nexport class BaseInputSpec {\n name: string\n type: string\n tooltip?: string\n default?: T\n\n @Type(() => Boolean)\n forceInput?: boolean\n\n static isInputSpec(obj: any): boolean {\n return (\n Array.isArray(obj) &&\n obj.length >= 1 &&\n (typeof obj[0] === 'string' || Array.isArray(obj[0]))\n )\n }\n}\n\nexport class NumericInputSpec extends BaseInputSpec {\n @Type(() => Number)\n min?: number\n\n @Type(() => Number)\n max?: number\n\n @Type(() => Number)\n step?: number\n}\n\nexport class IntInputSpec extends NumericInputSpec {\n type: 'INT' = 'INT'\n}\n\nexport class FloatInputSpec extends NumericInputSpec {\n type: 'FLOAT' = 'FLOAT'\n\n @Type(() => Number)\n round?: number\n}\n\nexport class BooleanInputSpec extends BaseInputSpec {\n type: 'BOOLEAN' = 'BOOLEAN'\n\n labelOn?: string\n labelOff?: string\n}\n\nexport class StringInputSpec extends BaseInputSpec {\n type: 'STRING' = 'STRING'\n\n @Type(() => Boolean)\n multiline?: boolean\n\n @Type(() => Boolean)\n dynamicPrompts?: boolean\n}\n\nexport class ComboInputSpec extends BaseInputSpec {\n type: string = 'COMBO'\n\n @Transform(({ value }) => value[0])\n comboOptions: any[]\n\n @Type(() => Boolean)\n controlAfterGenerate?: boolean\n\n @Type(() => Boolean)\n imageUpload?: boolean\n}\n\nexport class CustomInputSpec extends BaseInputSpec {}\n\nexport class ComfyInputsSpec {\n @Transform(({ value }) => ComfyInputsSpec.transformInputSpecRecord(value))\n required: Record = {}\n\n @Transform(({ value }) => ComfyInputsSpec.transformInputSpecRecord(value))\n optional: Record = {}\n\n hidden?: Record\n\n private static transformInputSpecRecord(\n record: Record\n ): Record {\n if (!record) return record\n const result: Record = {}\n for (const [key, value] of Object.entries(record)) {\n result[key] = ComfyInputsSpec.transformSingleInputSpec(key, value)\n }\n return result\n }\n\n private static transformSingleInputSpec(\n name: string,\n value: any\n ): BaseInputSpec {\n if (!BaseInputSpec.isInputSpec(value)) return value\n\n const [typeRaw, _spec] = value\n const spec = _spec ?? {}\n const type = Array.isArray(typeRaw) ? 'COMBO' : value[0]\n\n switch (type) {\n case 'INT':\n return plainToClass(IntInputSpec, { name, type, ...spec })\n case 'FLOAT':\n return plainToClass(FloatInputSpec, { name, type, ...spec })\n case 'BOOLEAN':\n return plainToClass(BooleanInputSpec, { name, type, ...spec })\n case 'STRING':\n return plainToClass(StringInputSpec, { name, type, ...spec })\n case 'COMBO':\n return plainToClass(ComboInputSpec, {\n name,\n type,\n ...spec,\n comboOptions: typeRaw,\n default: spec.default ?? typeRaw[0]\n })\n default:\n return plainToClass(CustomInputSpec, { name, type, ...spec })\n }\n }\n\n get all() {\n return [...Object.values(this.required), ...Object.values(this.optional)]\n }\n\n getInput(name: string): BaseInputSpec | undefined {\n return this.required[name] ?? this.optional[name]\n }\n}\n\nexport class ComfyOutputSpec {\n constructor(\n public index: number,\n // Name is not unique for output params\n public name: string,\n public type: string,\n public is_list: boolean,\n public comboOptions?: any[],\n public tooltip?: string\n ) {}\n}\n\nexport class ComfyOutputsSpec {\n constructor(public outputs: ComfyOutputSpec[]) {}\n\n get all() {\n return this.outputs\n }\n}\n\nexport class ComfyNodeDefImpl {\n name: string\n display_name: string\n category: string\n python_module: string\n description: string\n\n @Transform(({ value, obj }) => value ?? obj.category === '', {\n toClassOnly: true\n })\n @Type(() => Boolean)\n @Expose()\n deprecated: boolean\n\n @Transform(\n ({ value, obj }) => value ?? obj.category.startsWith('_for_testing'),\n {\n toClassOnly: true\n }\n )\n @Type(() => Boolean)\n @Expose()\n experimental: boolean\n\n @Type(() => ComfyInputsSpec)\n input: ComfyInputsSpec\n\n @Transform(({ obj }) => ComfyNodeDefImpl.transformOutputSpec(obj))\n output: ComfyOutputsSpec\n\n @Transform(({ obj }) => getNodeSource(obj.python_module), {\n toClassOnly: true\n })\n @Expose()\n nodeSource: NodeSource\n\n private static transformOutputSpec(obj: any): ComfyOutputsSpec {\n const { output, output_is_list, output_name, output_tooltips } = obj\n const result = output.map((type: string | any[], index: number) => {\n const typeString = Array.isArray(type) ? 'COMBO' : type\n\n return new ComfyOutputSpec(\n index,\n output_name[index],\n typeString,\n output_is_list[index],\n Array.isArray(type) ? type : undefined,\n output_tooltips?.[index]\n )\n })\n return new ComfyOutputsSpec(result)\n }\n\n get nodePath(): string {\n return (this.category ? this.category + '/' : '') + this.name\n }\n\n get isDummyFolder(): boolean {\n return this.name === ''\n }\n\n postProcessSearchScores(scores: SearchAuxScore): SearchAuxScore {\n const nodeFrequencyStore = useNodeFrequencyStore()\n const nodeFrequency = nodeFrequencyStore.getNodeFrequencyByName(this.name)\n return [scores[0], -nodeFrequency, ...scores.slice(1)]\n }\n}\n\nexport const SYSTEM_NODE_DEFS: Record = {\n PrimitiveNode: {\n name: 'PrimitiveNode',\n display_name: 'Primitive',\n category: 'utils',\n input: { required: {}, optional: {} },\n output: ['*'],\n output_name: ['connect to widget input'],\n output_is_list: [false],\n python_module: 'nodes',\n description: 'Primitive values like numbers, strings, and booleans.'\n },\n Reroute: {\n name: 'Reroute',\n display_name: 'Reroute',\n category: 'utils',\n input: { required: { '': ['*'] }, optional: {} },\n output: ['*'],\n output_name: [''],\n output_is_list: [false],\n python_module: 'nodes',\n description: 'Reroute the connection to another node.'\n },\n Note: {\n name: 'Note',\n display_name: 'Note',\n category: 'utils',\n input: { required: {}, optional: {} },\n output: [],\n output_name: [],\n output_is_list: [],\n python_module: 'nodes',\n description: 'Node that add notes to your project'\n }\n}\n\nexport function buildNodeDefTree(nodeDefs: ComfyNodeDefImpl[]): TreeNode {\n return buildTree(nodeDefs, (nodeDef: ComfyNodeDefImpl) =>\n nodeDef.nodePath.split('/')\n )\n}\n\nexport function createDummyFolderNodeDef(folderPath: string): ComfyNodeDefImpl {\n return plainToClass(ComfyNodeDefImpl, {\n name: '',\n display_name: '',\n category: folderPath.endsWith('/') ? folderPath.slice(0, -1) : folderPath,\n python_module: 'nodes',\n description: 'Dummy Folder Node (User should never see this string)'\n })\n}\n\ninterface State {\n nodeDefsByName: Record\n nodeDefsByDisplayName: Record\n widgets: Record\n showDeprecated: boolean\n showExperimental: boolean\n}\n\nexport const useNodeDefStore = defineStore('nodeDef', {\n state: (): State => ({\n nodeDefsByName: {},\n nodeDefsByDisplayName: {},\n widgets: {},\n showDeprecated: false,\n showExperimental: false\n }),\n getters: {\n nodeDefs(state) {\n return Object.values(state.nodeDefsByName)\n },\n // Node defs that are not deprecated\n visibleNodeDefs(state): ComfyNodeDefImpl[] {\n return this.nodeDefs.filter(\n (nodeDef: ComfyNodeDefImpl) =>\n (state.showDeprecated || !nodeDef.deprecated) &&\n (state.showExperimental || !nodeDef.experimental)\n )\n },\n nodeSearchService() {\n return new NodeSearchService(this.visibleNodeDefs)\n },\n nodeTree(): TreeNode {\n return buildNodeDefTree(this.visibleNodeDefs)\n }\n },\n actions: {\n updateNodeDefs(nodeDefs: ComfyNodeDef[]) {\n const newNodeDefsByName: { [key: string]: ComfyNodeDefImpl } = {}\n const nodeDefsByDisplayName: { [key: string]: ComfyNodeDefImpl } = {}\n for (const nodeDef of nodeDefs) {\n const nodeDefImpl = plainToClass(ComfyNodeDefImpl, nodeDef)\n newNodeDefsByName[nodeDef.name] = nodeDefImpl\n nodeDefsByDisplayName[nodeDef.display_name] = nodeDefImpl\n }\n this.nodeDefsByName = newNodeDefsByName\n this.nodeDefsByDisplayName = nodeDefsByDisplayName\n },\n addNodeDef(nodeDef: ComfyNodeDef) {\n const nodeDefImpl = plainToClass(ComfyNodeDefImpl, nodeDef)\n this.nodeDefsByName[nodeDef.name] = nodeDefImpl\n this.nodeDefsByDisplayName[nodeDef.display_name] = nodeDefImpl\n },\n updateWidgets(widgets: Record) {\n this.widgets = widgets\n },\n getWidgetType(type: string, inputName: string) {\n if (type === 'COMBO') {\n return 'COMBO'\n } else if (`${type}:${inputName}` in this.widgets) {\n return `${type}:${inputName}`\n } else if (type in this.widgets) {\n return type\n } else {\n return null\n }\n },\n inputIsWidget(spec: BaseInputSpec) {\n return this.getWidgetType(spec.type, spec.name) !== null\n }\n }\n})\n\nexport const useNodeFrequencyStore = defineStore('nodeFrequency', () => {\n const topNodeDefLimit = ref(64)\n const nodeFrequencyLookup = ref>({})\n const nodeNamesByFrequency = computed(() =>\n Object.keys(nodeFrequencyLookup.value)\n )\n const isLoaded = ref(false)\n\n const loadNodeFrequencies = async () => {\n if (!isLoaded.value) {\n try {\n const response = await axios.get('/assets/sorted-custom-node-map.json')\n nodeFrequencyLookup.value = response.data\n isLoaded.value = true\n } catch (error) {\n console.error('Error loading node frequencies:', error)\n }\n }\n }\n\n const getNodeFrequency = (nodeDef: ComfyNodeDefImpl) => {\n return getNodeFrequencyByName(nodeDef.name)\n }\n\n const getNodeFrequencyByName = (nodeName: string) => {\n return nodeFrequencyLookup.value[nodeName] ?? 0\n }\n\n const nodeDefStore = useNodeDefStore()\n const topNodeDefs = computed(() => {\n return nodeNamesByFrequency.value\n .map((nodeName: string) => nodeDefStore.nodeDefsByName[nodeName])\n .filter((nodeDef: ComfyNodeDefImpl) => nodeDef !== undefined)\n .slice(0, topNodeDefLimit.value)\n })\n\n return {\n nodeNamesByFrequency,\n topNodeDefs,\n isLoaded,\n loadNodeFrequencies,\n getNodeFrequency,\n getNodeFrequencyByName\n }\n})\n","import { api } from '@/scripts/api'\nimport { defineStore } from 'pinia'\n\n/** (Internal helper) finds a value in a metadata object from any of a list of keys. */\nfunction _findInMetadata(metadata: any, ...keys: string[]): string | null {\n for (const key of keys) {\n if (key in metadata) {\n return metadata[key]\n }\n for (const k in metadata) {\n if (k.endsWith(key)) {\n return metadata[k]\n }\n }\n }\n return null\n}\n\n/** Defines and holds metadata for a model */\nexport class ComfyModelDef {\n /** Proper filename of the model */\n name: string = ''\n /** Directory containing the model, eg 'checkpoints' */\n directory: string = ''\n /** Title / display name of the model, sometimes same as the name but not always */\n title: string = ''\n /** Metadata: architecture ID for the model, such as 'stable-diffusion-xl-v1-base' */\n architecture_id: string = ''\n /** Metadata: author of the model */\n author: string = ''\n /** Metadata: resolution of the model, eg '1024x1024' */\n resolution: string = ''\n /** Metadata: description of the model */\n description: string = ''\n /** Metadata: usage hint for the model */\n usage_hint: string = ''\n /** Metadata: trigger phrase for the model */\n trigger_phrase: string = ''\n /** Metadata: tags list for the model */\n tags: string[] = []\n /** Metadata: image for the model */\n image: string = ''\n /** Whether the model metadata has been loaded from the server, used for `load()` */\n has_loaded_metadata: boolean = false\n\n constructor(name: string, directory: string) {\n this.name = name\n this.title = name\n this.directory = directory\n }\n\n /** Loads the model metadata from the server, filling in this object if data is available */\n async load(): Promise {\n if (this.has_loaded_metadata) {\n return\n }\n const metadata = await api.viewMetadata(this.directory, this.name)\n if (!metadata) {\n return\n }\n this.title =\n _findInMetadata(\n metadata,\n 'modelspec.title',\n 'title',\n 'display_name',\n 'name'\n ) || this.name\n this.architecture_id =\n _findInMetadata(metadata, 'modelspec.architecture', 'architecture') || ''\n this.author = _findInMetadata(metadata, 'modelspec.author', 'author') || ''\n this.description =\n _findInMetadata(metadata, 'modelspec.description', 'description') || ''\n this.resolution =\n _findInMetadata(metadata, 'modelspec.resolution', 'resolution') || ''\n this.usage_hint =\n _findInMetadata(metadata, 'modelspec.usage_hint', 'usage_hint') || ''\n this.trigger_phrase =\n _findInMetadata(metadata, 'modelspec.trigger_phrase', 'trigger_phrase') ||\n ''\n this.image =\n _findInMetadata(\n metadata,\n 'modelspec.thumbnail',\n 'thumbnail',\n 'image',\n 'icon'\n ) || ''\n const tagsCommaSeparated =\n _findInMetadata(metadata, 'modelspec.tags', 'tags') || ''\n this.tags = tagsCommaSeparated.split(',').map((tag) => tag.trim())\n this.has_loaded_metadata = true\n }\n}\n\n/** Model store for a folder */\nexport class ModelStore {\n models: Record = {}\n\n constructor(directory: string, models: string[]) {\n for (const model of models) {\n this.models[model] = new ComfyModelDef(model, directory)\n }\n }\n\n async loadModelMetadata(modelName: string) {\n if (this.models[modelName]) {\n await this.models[modelName].load()\n }\n }\n}\n\n/** Model store handler, wraps individual per-folder model stores */\nexport const useModelStore = defineStore('modelStore', {\n state: () => ({\n modelStoreMap: {} as Record\n }),\n actions: {\n async getModelsInFolderCached(folder: string): Promise {\n if (folder in this.modelStoreMap) {\n return this.modelStoreMap[folder]\n }\n // TODO: needs a lock to avoid overlapping calls\n const models = await api.getModels(folder)\n if (!models) {\n return null\n }\n const store = new ModelStore(folder, models)\n this.modelStoreMap[folder] = store\n return store\n },\n clearCache() {\n this.modelStoreMap = {}\n }\n }\n})\n","import { SidebarTabExtension, ToastManager } from '@/types/extensionTypes'\nimport { defineStore } from 'pinia'\nimport { useToastStore } from './toastStore'\n\ninterface WorkspaceState {\n spinner: boolean\n activeSidebarTab: string | null\n sidebarTabs: SidebarTabExtension[]\n}\n\nexport const useWorkspaceStore = defineStore('workspace', {\n state: (): WorkspaceState => ({\n spinner: false,\n activeSidebarTab: null,\n sidebarTabs: []\n }),\n getters: {\n toast(): ToastManager {\n return useToastStore()\n }\n },\n actions: {\n updateActiveSidebarTab(tabId: string) {\n this.activeSidebarTab = tabId\n },\n registerSidebarTab(tab: SidebarTabExtension) {\n this.sidebarTabs = [...this.sidebarTabs, tab]\n },\n unregisterSidebarTab(id: string) {\n const index = this.sidebarTabs.findIndex((tab) => tab.id === id)\n if (index !== -1) {\n const tab = this.sidebarTabs[index]\n if (tab.type === 'custom' && tab.destroy) {\n tab.destroy()\n }\n const newSidebarTabs = [...this.sidebarTabs]\n newSidebarTabs.splice(index, 1)\n this.sidebarTabs = newSidebarTabs\n }\n },\n getSidebarTabs() {\n return [...this.sidebarTabs]\n }\n }\n})\n","import { ref, computed } from 'vue'\nimport { defineStore } from 'pinia'\nimport { api } from '../scripts/api'\nimport { ComfyWorkflow } from '@/scripts/workflows'\nimport type { ComfyNode, ComfyWorkflowJSON } from '@/types/comfyWorkflow'\n\nexport interface QueuedPrompt {\n nodes: Record\n workflow?: ComfyWorkflow\n}\n\ninterface NodeProgress {\n value: number\n max: number\n}\n\nexport const useExecutionStore = defineStore('execution', () => {\n const activePromptId = ref(null)\n const queuedPrompts = ref>({})\n const executingNodeId = ref(null)\n const executingNode = computed(() => {\n if (!executingNodeId.value) return null\n\n const workflow: ComfyWorkflow | null = activePrompt.value?.workflow\n if (!workflow) return null\n\n const canvasState: ComfyWorkflowJSON | null =\n workflow.changeTracker?.activeState\n if (!canvasState) return null\n\n return (\n canvasState.nodes.find((n) => String(n.id) === executingNodeId.value) ??\n null\n )\n })\n\n // This is the progress of the currently executing node, if any\n const _executingNodeProgress = ref(null)\n const executingNodeProgress = computed(() =>\n _executingNodeProgress.value\n ? Math.round(\n (_executingNodeProgress.value.value /\n _executingNodeProgress.value.max) *\n 100\n )\n : null\n )\n\n const activePrompt = computed(() => queuedPrompts.value[activePromptId.value])\n\n const totalNodesToExecute = computed(() => {\n if (!activePrompt.value) return 0\n return Object.values(activePrompt.value.nodes).length\n })\n\n const isIdle = computed(() => !activePromptId.value)\n\n const nodesExecuted = computed(() => {\n if (!activePrompt.value) return 0\n return Object.values(activePrompt.value.nodes).filter(Boolean).length\n })\n\n const executionProgress = computed(() => {\n if (!activePrompt.value) return 0\n const total = totalNodesToExecute.value\n const done = nodesExecuted.value\n return Math.round((done / total) * 100)\n })\n\n function bindExecutionEvents() {\n api.addEventListener('execution_start', handleExecutionStart)\n api.addEventListener('execution_cached', handleExecutionCached)\n api.addEventListener('executed', handleExecuted)\n api.addEventListener('executing', handleExecuting)\n api.addEventListener('progress', handleProgress)\n }\n\n function unbindExecutionEvents() {\n api.removeEventListener('execution_start', handleExecutionStart)\n api.removeEventListener('execution_cached', handleExecutionCached)\n api.removeEventListener('executed', handleExecuted)\n api.removeEventListener('executing', handleExecuting)\n api.removeEventListener('progress', handleProgress)\n }\n\n function handleExecutionStart(e: CustomEvent) {\n activePromptId.value = e.detail.prompt_id\n queuedPrompts.value[activePromptId.value] ??= { nodes: {} }\n }\n\n function handleExecutionCached(e: CustomEvent) {\n if (!activePrompt.value) return\n for (const n of e.detail.nodes) {\n activePrompt.value.nodes[n] = true\n }\n }\n\n function handleExecuted(e: CustomEvent) {\n if (!activePrompt.value) return\n activePrompt.value.nodes[e.detail.node] = true\n }\n\n function handleExecuting(e: CustomEvent) {\n // Clear the current node progress when a new node starts executing\n _executingNodeProgress.value = null\n\n if (!activePrompt.value) return\n\n if (executingNodeId.value) {\n // Seems sometimes nodes that are cached fire executing but not executed\n activePrompt.value.nodes[executingNodeId.value] = true\n }\n executingNodeId.value = e.detail ? String(e.detail) : null\n if (!executingNodeId.value) {\n delete queuedPrompts.value[activePromptId.value]\n activePromptId.value = null\n }\n }\n\n function handleProgress(e: CustomEvent) {\n _executingNodeProgress.value = e.detail\n }\n\n function storePrompt({\n nodes,\n id,\n workflow\n }: {\n nodes: string[]\n id: string\n workflow: any\n }) {\n queuedPrompts.value[id] ??= { nodes: {} }\n const queuedPrompt = queuedPrompts.value[id]\n queuedPrompt.nodes = {\n ...nodes.reduce((p, n) => {\n p[n] = false\n return p\n }, {}),\n ...queuedPrompt.nodes\n }\n queuedPrompt.workflow = workflow\n\n console.debug(\n `queued task ${id} with ${Object.values(queuedPrompt.nodes).length} nodes`\n )\n }\n\n return {\n isIdle,\n activePromptId,\n queuedPrompts,\n executingNodeId,\n activePrompt,\n totalNodesToExecute,\n nodesExecuted,\n executionProgress,\n executingNode,\n executingNodeProgress,\n bindExecutionEvents,\n unbindExecutionEvents,\n storePrompt\n }\n})\n","import { ComfyLogging } from './logging'\nimport { ComfyWidgetConstructor, ComfyWidgets, initWidgets } from './widgets'\nimport { ComfyUI, $el } from './ui'\nimport { api } from './api'\nimport { defaultGraph } from './defaultGraph'\nimport {\n getPngMetadata,\n getWebpMetadata,\n getFlacMetadata,\n importA1111,\n getLatentMetadata\n} from './pnginfo'\nimport { addDomClippingSetting } from './domWidget'\nimport { createImageHost, calculateImageGrid } from './ui/imagePreview'\nimport { DraggableList } from './ui/draggableList'\nimport { applyTextReplacements, addStylesheet } from './utils'\nimport type { ComfyExtension } from '@/types/comfy'\nimport {\n type ComfyWorkflowJSON,\n type NodeId,\n validateComfyWorkflow\n} from '../types/comfyWorkflow'\nimport { ComfyNodeDef, StatusWsMessageStatus } from '@/types/apiTypes'\nimport { lightenColor } from '@/utils/colorUtil'\nimport { ComfyAppMenu } from './ui/menu/index'\nimport { getStorageValue } from './utils'\nimport { ComfyWorkflowManager, ComfyWorkflow } from './workflows'\nimport {\n LGraphCanvas,\n LGraph,\n LGraphNode,\n LiteGraph,\n LGraphGroup\n} from '@comfyorg/litegraph'\nimport { StorageLocation } from '@/types/settingTypes'\nimport { ExtensionManager } from '@/types/extensionTypes'\nimport {\n ComfyNodeDefImpl,\n SYSTEM_NODE_DEFS,\n useNodeDefStore\n} from '@/stores/nodeDefStore'\nimport { Vector2 } from '@comfyorg/litegraph'\nimport _ from 'lodash'\nimport {\n showExecutionErrorDialog,\n showLoadWorkflowWarning,\n showMissingModelsWarning\n} from '@/services/dialogService'\nimport { useSettingStore } from '@/stores/settingStore'\nimport { useToastStore } from '@/stores/toastStore'\nimport { ModelStore, useModelStore } from '@/stores/modelStore'\nimport type { ToastMessageOptions } from 'primevue/toast'\nimport { useWorkspaceStore } from '@/stores/workspaceStateStore'\nimport { ComfyLGraphNode } from '@/types/comfyLGraphNode'\nimport { useExecutionStore } from '@/stores/executionStore'\n\nexport const ANIM_PREVIEW_WIDGET = '$$comfy_animation_preview'\n\nfunction sanitizeNodeName(string) {\n let entityMap = {\n '&': '',\n '<': '',\n '>': '',\n '\"': '',\n \"'\": '',\n '`': '',\n '=': ''\n }\n return String(string).replace(/[&<>\"'`=]/g, function fromEntityMap(s) {\n return entityMap[s]\n })\n}\n\n/**\n * @typedef {import(\"types/comfy\").ComfyExtension} ComfyExtension\n */\n\nexport class ComfyApp {\n /**\n * List of entries to queue\n * @type {{number: number, batchCount: number}[]}\n */\n #queueItems = []\n /**\n * If the queue is currently being processed\n * @type {boolean}\n */\n #processingQueue = false\n\n /**\n * Content Clipboard\n * @type {serialized node object}\n */\n static clipspace = null\n static clipspace_invalidate_handler = null\n static open_maskeditor = null\n static clipspace_return_node = null\n\n // Force vite to import utils.ts as part of index.\n // Force import of DraggableList.\n static utils = {\n applyTextReplacements,\n addStylesheet,\n DraggableList\n }\n\n vueAppReady: boolean\n ui: ComfyUI\n logging: ComfyLogging\n extensions: ComfyExtension[]\n extensionManager: ExtensionManager\n _nodeOutputs: Record\n nodePreviewImages: Record\n shiftDown: boolean\n graph: LGraph\n enableWorkflowViewRestore: any\n canvas: LGraphCanvas\n dragOverNode: LGraphNode | null\n canvasEl: HTMLCanvasElement\n // x, y, scale\n zoom_drag_start: [number, number, number] | null\n lastNodeErrors: any[] | null\n lastExecutionError: { node_id: number } | null\n progress: { value: number; max: number } | null\n configuringGraph: boolean\n isNewUserSession: boolean\n storageLocation: StorageLocation\n multiUserServer: boolean\n ctx: CanvasRenderingContext2D\n widgets: Record\n workflowManager: ComfyWorkflowManager\n bodyTop: HTMLElement\n bodyLeft: HTMLElement\n bodyRight: HTMLElement\n bodyBottom: HTMLElement\n canvasContainer: HTMLElement\n menu: ComfyAppMenu\n\n // @deprecated\n // Use useExecutionStore().executingNodeId instead\n get runningNodeId(): string | null {\n return useExecutionStore().executingNodeId\n }\n\n constructor() {\n this.vueAppReady = false\n this.ui = new ComfyUI(this)\n this.logging = new ComfyLogging(this)\n this.workflowManager = new ComfyWorkflowManager(this)\n this.bodyTop = $el('div.comfyui-body-top', { parent: document.body })\n this.bodyLeft = $el('div.comfyui-body-left', { parent: document.body })\n this.bodyRight = $el('div.comfyui-body-right', { parent: document.body })\n this.bodyBottom = $el('div.comfyui-body-bottom', { parent: document.body })\n this.canvasContainer = $el('div.graph-canvas-container', {\n parent: document.body\n })\n this.menu = new ComfyAppMenu(this)\n\n /**\n * List of extensions that are registered with the app\n * @type {ComfyExtension[]}\n */\n this.extensions = []\n\n /**\n * Stores the execution output data for each node\n * @type {Record}\n */\n this.nodeOutputs = {}\n\n /**\n * Stores the preview image data for each node\n * @type {Record}\n */\n this.nodePreviewImages = {}\n\n /**\n * If the shift key on the keyboard is pressed\n * @type {boolean}\n */\n this.shiftDown = false\n }\n\n get nodeOutputs() {\n return this._nodeOutputs\n }\n\n set nodeOutputs(value) {\n this._nodeOutputs = value\n this.#invokeExtensions('onNodeOutputsUpdated', value)\n }\n\n getPreviewFormatParam() {\n let preview_format = this.ui.settings.getSettingValue('Comfy.PreviewFormat')\n if (preview_format) return `&preview=${preview_format}`\n else return ''\n }\n\n getRandParam() {\n return '&rand=' + Math.random()\n }\n\n static isImageNode(node) {\n return (\n node.imgs ||\n (node &&\n node.widgets &&\n node.widgets.findIndex((obj) => obj.name === 'image') >= 0)\n )\n }\n\n static onClipspaceEditorSave() {\n if (ComfyApp.clipspace_return_node) {\n ComfyApp.pasteFromClipspace(ComfyApp.clipspace_return_node)\n }\n }\n\n static onClipspaceEditorClosed() {\n ComfyApp.clipspace_return_node = null\n }\n\n static copyToClipspace(node) {\n var widgets = null\n if (node.widgets) {\n widgets = node.widgets.map(({ type, name, value }) => ({\n type,\n name,\n value\n }))\n }\n\n var imgs = undefined\n var orig_imgs = undefined\n if (node.imgs != undefined) {\n imgs = []\n orig_imgs = []\n\n for (let i = 0; i < node.imgs.length; i++) {\n imgs[i] = new Image()\n imgs[i].src = node.imgs[i].src\n orig_imgs[i] = imgs[i]\n }\n }\n\n var selectedIndex = 0\n if (node.imageIndex) {\n selectedIndex = node.imageIndex\n }\n\n ComfyApp.clipspace = {\n widgets: widgets,\n imgs: imgs,\n original_imgs: orig_imgs,\n images: node.images,\n selectedIndex: selectedIndex,\n img_paste_mode: 'selected' // reset to default im_paste_mode state on copy action\n }\n\n ComfyApp.clipspace_return_node = null\n\n if (ComfyApp.clipspace_invalidate_handler) {\n ComfyApp.clipspace_invalidate_handler()\n }\n }\n\n static pasteFromClipspace(node) {\n if (ComfyApp.clipspace) {\n // image paste\n if (ComfyApp.clipspace.imgs && node.imgs) {\n if (node.images && ComfyApp.clipspace.images) {\n if (ComfyApp.clipspace['img_paste_mode'] == 'selected') {\n node.images = [\n ComfyApp.clipspace.images[ComfyApp.clipspace['selectedIndex']]\n ]\n } else {\n node.images = ComfyApp.clipspace.images\n }\n\n if (app.nodeOutputs[node.id + ''])\n app.nodeOutputs[node.id + ''].images = node.images\n }\n\n if (ComfyApp.clipspace.imgs) {\n // deep-copy to cut link with clipspace\n if (ComfyApp.clipspace['img_paste_mode'] == 'selected') {\n const img = new Image()\n img.src =\n ComfyApp.clipspace.imgs[ComfyApp.clipspace['selectedIndex']].src\n node.imgs = [img]\n node.imageIndex = 0\n } else {\n const imgs = []\n for (let i = 0; i < ComfyApp.clipspace.imgs.length; i++) {\n imgs[i] = new Image()\n imgs[i].src = ComfyApp.clipspace.imgs[i].src\n node.imgs = imgs\n }\n }\n }\n }\n\n if (node.widgets) {\n if (ComfyApp.clipspace.images) {\n const clip_image =\n ComfyApp.clipspace.images[ComfyApp.clipspace['selectedIndex']]\n const index = node.widgets.findIndex((obj) => obj.name === 'image')\n if (index >= 0) {\n if (\n node.widgets[index].type != 'image' &&\n typeof node.widgets[index].value == 'string' &&\n clip_image.filename\n ) {\n node.widgets[index].value =\n (clip_image.subfolder ? clip_image.subfolder + '/' : '') +\n clip_image.filename +\n (clip_image.type ? ` [${clip_image.type}]` : '')\n } else {\n node.widgets[index].value = clip_image\n }\n }\n }\n if (ComfyApp.clipspace.widgets) {\n ComfyApp.clipspace.widgets.forEach(({ type, name, value }) => {\n const prop = Object.values(node.widgets).find(\n // @ts-expect-errorg\n (obj) => obj.type === type && obj.name === name\n )\n // @ts-expect-error\n if (prop && prop.type != 'button') {\n if (\n // @ts-expect-error\n prop.type != 'image' &&\n // @ts-expect-error\n typeof prop.value == 'string' &&\n value.filename\n ) {\n // @ts-expect-error\n prop.value =\n (value.subfolder ? value.subfolder + '/' : '') +\n value.filename +\n (value.type ? ` [${value.type}]` : '')\n } else {\n // @ts-expect-error\n prop.value = value\n // @ts-expect-error\n prop.callback(value)\n }\n }\n })\n }\n }\n\n app.graph.setDirtyCanvas(true)\n }\n }\n\n /**\n * Invoke an extension callback\n * @param {keyof ComfyExtension} method The extension callback to execute\n * @param {any[]} args Any arguments to pass to the callback\n * @returns\n */\n #invokeExtensions(method, ...args) {\n let results = []\n for (const ext of this.extensions) {\n if (method in ext) {\n try {\n results.push(ext[method](...args, this))\n } catch (error) {\n console.error(\n `Error calling extension '${ext.name}' method '${method}'`,\n { error },\n { extension: ext },\n { args }\n )\n }\n }\n }\n return results\n }\n\n /**\n * Invoke an async extension callback\n * Each callback will be invoked concurrently\n * @param {string} method The extension callback to execute\n * @param {...any} args Any arguments to pass to the callback\n * @returns\n */\n async #invokeExtensionsAsync(method, ...args) {\n return await Promise.all(\n this.extensions.map(async (ext) => {\n if (method in ext) {\n try {\n return await ext[method](...args, this)\n } catch (error) {\n console.error(\n `Error calling extension '${ext.name}' method '${method}'`,\n { error },\n { extension: ext },\n { args }\n )\n }\n }\n })\n )\n }\n\n #addRestoreWorkflowView() {\n const serialize = LGraph.prototype.serialize\n const self = this\n LGraph.prototype.serialize = function () {\n const workflow = serialize.apply(this, arguments)\n\n // Store the drag & scale info in the serialized workflow if the setting is enabled\n if (self.enableWorkflowViewRestore.value) {\n if (!workflow.extra) {\n workflow.extra = {}\n }\n workflow.extra.ds = {\n scale: self.canvas.ds.scale,\n offset: self.canvas.ds.offset\n }\n } else if (workflow.extra?.ds) {\n // Clear any old view data\n delete workflow.extra.ds\n }\n\n return workflow\n }\n this.enableWorkflowViewRestore = this.ui.settings.addSetting({\n id: 'Comfy.EnableWorkflowViewRestore',\n category: ['Comfy', 'Workflow', 'EnableWorkflowViewRestore'],\n name: 'Save and restore canvas position and zoom level in workflows',\n type: 'boolean',\n defaultValue: true\n })\n }\n\n /**\n * Adds special context menu handling for nodes\n * e.g. this adds Open Image functionality for nodes that show images\n * @param {*} node The node to add the menu handler\n */\n #addNodeContextMenuHandler(node) {\n function getCopyImageOption(img) {\n if (typeof window.ClipboardItem === 'undefined') return []\n return [\n {\n content: 'Copy Image',\n callback: async () => {\n const url = new URL(img.src)\n url.searchParams.delete('preview')\n\n const writeImage = async (blob) => {\n await navigator.clipboard.write([\n new ClipboardItem({\n [blob.type]: blob\n })\n ])\n }\n\n try {\n const data = await fetch(url)\n const blob = await data.blob()\n try {\n await writeImage(blob)\n } catch (error) {\n // Chrome seems to only support PNG on write, convert and try again\n if (blob.type !== 'image/png') {\n const canvas = $el('canvas', {\n width: img.naturalWidth,\n height: img.naturalHeight\n }) as HTMLCanvasElement\n const ctx = canvas.getContext('2d')\n let image\n if (typeof window.createImageBitmap === 'undefined') {\n image = new Image()\n const p = new Promise((resolve, reject) => {\n image.onload = resolve\n image.onerror = reject\n }).finally(() => {\n URL.revokeObjectURL(image.src)\n })\n image.src = URL.createObjectURL(blob)\n await p\n } else {\n image = await createImageBitmap(blob)\n }\n try {\n ctx.drawImage(image, 0, 0)\n canvas.toBlob(writeImage, 'image/png')\n } finally {\n if (typeof image.close === 'function') {\n image.close()\n }\n }\n\n return\n }\n throw error\n }\n } catch (error) {\n alert('Error copying image: ' + (error.message ?? error))\n }\n }\n }\n ]\n }\n\n node.prototype.getExtraMenuOptions = function (_, options) {\n if (this.imgs) {\n // If this node has images then we add an open in new tab item\n let img\n if (this.imageIndex != null) {\n // An image is selected so select that\n img = this.imgs[this.imageIndex]\n } else if (this.overIndex != null) {\n // No image is selected but one is hovered\n img = this.imgs[this.overIndex]\n }\n if (img) {\n options.unshift(\n {\n content: 'Open Image',\n callback: () => {\n let url = new URL(img.src)\n url.searchParams.delete('preview')\n window.open(url, '_blank')\n }\n },\n ...getCopyImageOption(img),\n {\n content: 'Save Image',\n callback: () => {\n const a = document.createElement('a')\n let url = new URL(img.src)\n url.searchParams.delete('preview')\n a.href = url.toString()\n a.setAttribute(\n 'download',\n new URLSearchParams(url.search).get('filename')\n )\n document.body.append(a)\n a.click()\n requestAnimationFrame(() => a.remove())\n }\n }\n )\n }\n }\n\n options.push({\n content: 'Bypass',\n callback: (obj) => {\n if (this.mode === 4) this.mode = 0\n else this.mode = 4\n this.graph.change()\n }\n })\n\n // prevent conflict of clipspace content\n if (!ComfyApp.clipspace_return_node) {\n options.push({\n content: 'Copy (Clipspace)',\n callback: (obj) => {\n ComfyApp.copyToClipspace(this)\n }\n })\n\n if (ComfyApp.clipspace != null) {\n options.push({\n content: 'Paste (Clipspace)',\n callback: () => {\n ComfyApp.pasteFromClipspace(this)\n }\n })\n }\n\n if (ComfyApp.isImageNode(this)) {\n options.push({\n content: 'Open in MaskEditor',\n callback: (obj) => {\n ComfyApp.copyToClipspace(this)\n ComfyApp.clipspace_return_node = this\n ComfyApp.open_maskeditor()\n }\n })\n }\n }\n }\n }\n\n #addNodeKeyHandler(node) {\n const app = this\n const origNodeOnKeyDown = node.prototype.onKeyDown\n\n node.prototype.onKeyDown = function (e) {\n if (origNodeOnKeyDown && origNodeOnKeyDown.apply(this, e) === false) {\n return false\n }\n\n if (this.flags.collapsed || !this.imgs || this.imageIndex === null) {\n return\n }\n\n let handled = false\n\n if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') {\n if (e.key === 'ArrowLeft') {\n this.imageIndex -= 1\n } else if (e.key === 'ArrowRight') {\n this.imageIndex += 1\n }\n this.imageIndex %= this.imgs.length\n\n if (this.imageIndex < 0) {\n this.imageIndex = this.imgs.length + this.imageIndex\n }\n handled = true\n } else if (e.key === 'Escape') {\n this.imageIndex = null\n handled = true\n }\n\n if (handled === true) {\n e.preventDefault()\n e.stopImmediatePropagation()\n return false\n }\n }\n }\n\n /**\n * Adds Custom drawing logic for nodes\n * e.g. Draws images and handles thumbnail navigation on nodes that output images\n * @param {*} node The node to add the draw handler\n */\n #addDrawBackgroundHandler(node) {\n const app = this\n\n function getImageTop(node) {\n let shiftY\n if (node.imageOffset != null) {\n shiftY = node.imageOffset\n } else {\n if (node.widgets?.length) {\n const w = node.widgets[node.widgets.length - 1]\n shiftY = w.last_y\n if (w.computeSize) {\n shiftY += w.computeSize()[1] + 4\n } else if (w.computedHeight) {\n shiftY += w.computedHeight\n } else {\n shiftY += LiteGraph.NODE_WIDGET_HEIGHT + 4\n }\n } else {\n shiftY = node.computeSize()[1]\n }\n }\n return shiftY\n }\n\n node.prototype.setSizeForImage = function (force) {\n if (!force && this.animatedImages) return\n\n if (this.inputHeight || this.freeWidgetSpace > 210) {\n this.setSize(this.size)\n return\n }\n const minHeight = getImageTop(this) + 220\n if (this.size[1] < minHeight) {\n this.setSize([this.size[0], minHeight])\n }\n }\n\n function unsafeDrawBackground(ctx) {\n if (!this.flags.collapsed) {\n let imgURLs = []\n let imagesChanged = false\n\n const output = app.nodeOutputs[this.id + '']\n if (output?.images) {\n this.animatedImages = output?.animated?.find(Boolean)\n if (this.images !== output.images) {\n this.images = output.images\n imagesChanged = true\n imgURLs = imgURLs.concat(\n output.images.map((params) => {\n return api.apiURL(\n '/view?' +\n new URLSearchParams(params).toString() +\n (this.animatedImages ? '' : app.getPreviewFormatParam()) +\n app.getRandParam()\n )\n })\n )\n }\n }\n\n const preview = app.nodePreviewImages[this.id + '']\n if (this.preview !== preview) {\n this.preview = preview\n imagesChanged = true\n if (preview != null) {\n imgURLs.push(preview)\n }\n }\n\n if (imagesChanged) {\n this.imageIndex = null\n if (imgURLs.length > 0) {\n Promise.all(\n imgURLs.map((src) => {\n return new Promise((r) => {\n const img = new Image()\n img.onload = () => r(img)\n img.onerror = () => r(null)\n img.src = src\n })\n })\n ).then((imgs) => {\n if (\n (!output || this.images === output.images) &&\n (!preview || this.preview === preview)\n ) {\n this.imgs = imgs.filter(Boolean)\n this.setSizeForImage?.()\n app.graph.setDirtyCanvas(true)\n }\n })\n } else {\n this.imgs = null\n }\n }\n\n const is_all_same_aspect_ratio = (imgs) => {\n // assume: imgs.length >= 2\n let ratio = imgs[0].naturalWidth / imgs[0].naturalHeight\n\n for (let i = 1; i < imgs.length; i++) {\n let this_ratio = imgs[i].naturalWidth / imgs[i].naturalHeight\n if (ratio != this_ratio) return false\n }\n\n return true\n }\n\n if (this.imgs?.length) {\n const widgetIdx = this.widgets?.findIndex(\n (w) => w.name === ANIM_PREVIEW_WIDGET\n )\n\n if (this.animatedImages) {\n // Instead of using the canvas we'll use a IMG\n if (widgetIdx > -1) {\n // Replace content\n const widget = this.widgets[widgetIdx]\n widget.options.host.updateImages(this.imgs)\n } else {\n const host = createImageHost(this)\n this.setSizeForImage(true)\n const widget = this.addDOMWidget(\n ANIM_PREVIEW_WIDGET,\n 'img',\n host.el,\n {\n host,\n getHeight: host.getHeight,\n onDraw: host.onDraw,\n hideOnZoom: false\n }\n )\n widget.serializeValue = () => undefined\n widget.options.host.updateImages(this.imgs)\n }\n return\n }\n\n if (widgetIdx > -1) {\n this.widgets[widgetIdx].onRemove?.()\n this.widgets.splice(widgetIdx, 1)\n }\n\n const canvas = app.graph.list_of_graphcanvas[0]\n const mouse = canvas.graph_mouse\n if (!canvas.pointer_is_down && this.pointerDown) {\n if (\n mouse[0] === this.pointerDown.pos[0] &&\n mouse[1] === this.pointerDown.pos[1]\n ) {\n this.imageIndex = this.pointerDown.index\n }\n this.pointerDown = null\n }\n\n let imageIndex = this.imageIndex\n const numImages = this.imgs.length\n if (numImages === 1 && !imageIndex) {\n this.imageIndex = imageIndex = 0\n }\n\n const top = getImageTop(this)\n var shiftY = top\n\n let dw = this.size[0]\n let dh = this.size[1]\n dh -= shiftY\n\n if (imageIndex == null) {\n var cellWidth, cellHeight, shiftX, cell_padding, cols\n\n const compact_mode = is_all_same_aspect_ratio(this.imgs)\n if (!compact_mode) {\n // use rectangle cell style and border line\n cell_padding = 2\n // Prevent infinite canvas2d scale-up\n const largestDimension = this.imgs.reduce(\n (acc, current) =>\n Math.max(acc, current.naturalWidth, current.naturalHeight),\n 0\n )\n const fakeImgs = []\n fakeImgs.length = this.imgs.length\n fakeImgs[0] = {\n naturalWidth: largestDimension,\n naturalHeight: largestDimension\n }\n ;({ cellWidth, cellHeight, cols, shiftX } = calculateImageGrid(\n fakeImgs,\n dw,\n dh\n ))\n } else {\n cell_padding = 0\n ;({ cellWidth, cellHeight, cols, shiftX } = calculateImageGrid(\n this.imgs,\n dw,\n dh\n ))\n }\n\n let anyHovered = false\n this.imageRects = []\n for (let i = 0; i < numImages; i++) {\n const img = this.imgs[i]\n const row = Math.floor(i / cols)\n const col = i % cols\n const x = col * cellWidth + shiftX\n const y = row * cellHeight + shiftY\n if (!anyHovered) {\n anyHovered = LiteGraph.isInsideRectangle(\n mouse[0],\n mouse[1],\n x + this.pos[0],\n y + this.pos[1],\n cellWidth,\n cellHeight\n )\n if (anyHovered) {\n this.overIndex = i\n let value = 110\n if (canvas.pointer_is_down) {\n if (!this.pointerDown || this.pointerDown.index !== i) {\n this.pointerDown = { index: i, pos: [...mouse] }\n }\n value = 125\n }\n ctx.filter = `contrast(${value}%) brightness(${value}%)`\n canvas.canvas.style.cursor = 'pointer'\n }\n }\n this.imageRects.push([x, y, cellWidth, cellHeight])\n\n let wratio = cellWidth / img.width\n let hratio = cellHeight / img.height\n var ratio = Math.min(wratio, hratio)\n\n let imgHeight = ratio * img.height\n let imgY =\n row * cellHeight + shiftY + (cellHeight - imgHeight) / 2\n let imgWidth = ratio * img.width\n let imgX = col * cellWidth + shiftX + (cellWidth - imgWidth) / 2\n\n ctx.drawImage(\n img,\n imgX + cell_padding,\n imgY + cell_padding,\n imgWidth - cell_padding * 2,\n imgHeight - cell_padding * 2\n )\n if (!compact_mode) {\n // rectangle cell and border line style\n ctx.strokeStyle = '#8F8F8F'\n ctx.lineWidth = 1\n ctx.strokeRect(\n x + cell_padding,\n y + cell_padding,\n cellWidth - cell_padding * 2,\n cellHeight - cell_padding * 2\n )\n }\n\n ctx.filter = 'none'\n }\n\n if (!anyHovered) {\n this.pointerDown = null\n this.overIndex = null\n }\n } else {\n // Draw individual\n let w = this.imgs[imageIndex].naturalWidth\n let h = this.imgs[imageIndex].naturalHeight\n\n const scaleX = dw / w\n const scaleY = dh / h\n const scale = Math.min(scaleX, scaleY, 1)\n\n w *= scale\n h *= scale\n\n let x = (dw - w) / 2\n let y = (dh - h) / 2 + shiftY\n ctx.drawImage(this.imgs[imageIndex], x, y, w, h)\n\n const drawButton = (x, y, sz, text) => {\n const hovered = LiteGraph.isInsideRectangle(\n mouse[0],\n mouse[1],\n x + this.pos[0],\n y + this.pos[1],\n sz,\n sz\n )\n let fill = '#333'\n let textFill = '#fff'\n let isClicking = false\n if (hovered) {\n canvas.canvas.style.cursor = 'pointer'\n if (canvas.pointer_is_down) {\n fill = '#1e90ff'\n isClicking = true\n } else {\n fill = '#eee'\n textFill = '#000'\n }\n } else {\n this.pointerWasDown = null\n }\n\n ctx.fillStyle = fill\n ctx.beginPath()\n ctx.roundRect(x, y, sz, sz, [4])\n ctx.fill()\n ctx.fillStyle = textFill\n ctx.font = '12px Arial'\n ctx.textAlign = 'center'\n ctx.fillText(text, x + 15, y + 20)\n\n return isClicking\n }\n\n if (numImages > 1) {\n if (\n drawButton(\n dw - 40,\n dh + top - 40,\n 30,\n `${this.imageIndex + 1}/${numImages}`\n )\n ) {\n let i =\n this.imageIndex + 1 >= numImages ? 0 : this.imageIndex + 1\n if (!this.pointerDown || !this.pointerDown.index === i) {\n this.pointerDown = { index: i, pos: [...mouse] }\n }\n }\n\n if (drawButton(dw - 40, top + 10, 30, `x`)) {\n if (!this.pointerDown || !this.pointerDown.index === null) {\n this.pointerDown = { index: null, pos: [...mouse] }\n }\n }\n }\n }\n }\n }\n }\n\n node.prototype.onDrawBackground = function (ctx) {\n try {\n unsafeDrawBackground.call(this, ctx)\n } catch (error) {\n console.error('Error drawing node background', error)\n }\n }\n }\n\n /**\n * Adds a handler allowing drag+drop of files onto the window to load workflows\n */\n #addDropHandler() {\n // Get prompt from dropped PNG or json\n document.addEventListener('drop', async (event) => {\n event.preventDefault()\n event.stopPropagation()\n\n const n = this.dragOverNode\n this.dragOverNode = null\n // Node handles file drop, we dont use the built in onDropFile handler as its buggy\n // If you drag multiple files it will call it multiple times with the same file\n // @ts-expect-error This is not a standard event. TODO fix it.\n if (n && n.onDragDrop && (await n.onDragDrop(event))) {\n return\n }\n // Dragging from Chrome->Firefox there is a file but its a bmp, so ignore that\n if (\n event.dataTransfer.files.length &&\n event.dataTransfer.files[0].type !== 'image/bmp'\n ) {\n await this.handleFile(event.dataTransfer.files[0])\n } else {\n // Try loading the first URI in the transfer list\n const validTypes = ['text/uri-list', 'text/x-moz-url']\n const match = [...event.dataTransfer.types].find((t) =>\n validTypes.find((v) => t === v)\n )\n if (match) {\n const uri = event.dataTransfer.getData(match)?.split('\\n')?.[0]\n if (uri) {\n await this.handleFile(await (await fetch(uri)).blob())\n }\n }\n }\n })\n\n // Always clear over node on drag leave\n this.canvasEl.addEventListener('dragleave', async () => {\n if (this.dragOverNode) {\n this.dragOverNode = null\n this.graph.setDirtyCanvas(false, true)\n }\n })\n\n // Add handler for dropping onto a specific node\n this.canvasEl.addEventListener(\n 'dragover',\n (e) => {\n this.canvas.adjustMouseEvent(e)\n // @ts-expect-error: canvasX and canvasY are added by adjustMouseEvent in litegraph\n const node = this.graph.getNodeOnPos(e.canvasX, e.canvasY)\n if (node) {\n // @ts-expect-error This is not a standard event. TODO fix it.\n if (node.onDragOver && node.onDragOver(e)) {\n this.dragOverNode = node\n\n // dragover event is fired very frequently, run this on an animation frame\n requestAnimationFrame(() => {\n this.graph.setDirtyCanvas(false, true)\n })\n return\n }\n }\n this.dragOverNode = null\n },\n false\n )\n }\n\n /**\n * Adds a handler on paste that extracts and loads images or workflows from pasted JSON data\n */\n #addPasteHandler() {\n document.addEventListener('paste', async (e: ClipboardEvent) => {\n // ctrl+shift+v is used to paste nodes with connections\n // this is handled by litegraph\n if (this.shiftDown) return\n\n // @ts-expect-error: Property 'clipboardData' does not exist on type 'Window & typeof globalThis'.\n // Did you mean 'Clipboard'?ts(2551)\n // TODO: Not sure what the code wants to do.\n let data = e.clipboardData || window.clipboardData\n const items = data.items\n\n // Look for image paste data\n for (const item of items) {\n if (item.type.startsWith('image/')) {\n var imageNode = null\n\n // If an image node is selected, paste into it\n if (\n this.canvas.current_node &&\n this.canvas.current_node.is_selected &&\n ComfyApp.isImageNode(this.canvas.current_node)\n ) {\n imageNode = this.canvas.current_node\n }\n\n // No image node selected: add a new one\n if (!imageNode) {\n const newNode = LiteGraph.createNode('LoadImage')\n newNode.pos = [...this.canvas.graph_mouse]\n imageNode = this.graph.add(newNode)\n this.graph.change()\n }\n const blob = item.getAsFile()\n imageNode.pasteFile(blob)\n return\n }\n }\n\n // No image found. Look for node data\n data = data.getData('text/plain')\n let workflow: ComfyWorkflowJSON\n try {\n data = data.slice(data.indexOf('{'))\n workflow = JSON.parse(data)\n } catch (err) {\n try {\n data = data.slice(data.indexOf('workflow\\n'))\n data = data.slice(data.indexOf('{'))\n workflow = JSON.parse(data)\n } catch (error) {\n console.error(error)\n }\n }\n\n if (workflow && workflow.version && workflow.nodes && workflow.extra) {\n await this.loadGraphData(workflow)\n } else {\n if (\n (e.target instanceof HTMLTextAreaElement &&\n e.target.type === 'textarea') ||\n (e.target instanceof HTMLInputElement && e.target.type === 'text')\n ) {\n return\n }\n\n // Litegraph default paste\n this.canvas.pasteFromClipboard()\n }\n })\n }\n\n /**\n * Adds a handler on copy that serializes selected nodes to JSON\n */\n #addCopyHandler() {\n document.addEventListener('copy', (e) => {\n if (!(e.target instanceof Element)) {\n return\n }\n if (\n (e.target instanceof HTMLTextAreaElement &&\n e.target.type === 'textarea') ||\n (e.target instanceof HTMLInputElement && e.target.type === 'text')\n ) {\n // Default system copy\n return\n }\n const isTargetInGraph =\n e.target.classList.contains('litegraph') ||\n e.target.classList.contains('graph-canvas-container')\n\n // copy nodes and clear clipboard\n if (isTargetInGraph && this.canvas.selected_nodes) {\n this.canvas.copyToClipboard()\n e.clipboardData.setData('text', ' ') //clearData doesn't remove images from clipboard\n e.preventDefault()\n e.stopImmediatePropagation()\n return false\n }\n })\n }\n\n /**\n * Handle mouse\n *\n * Move group by header\n */\n #addProcessMouseHandler() {\n const self = this\n\n const origProcessMouseDown = LGraphCanvas.prototype.processMouseDown\n LGraphCanvas.prototype.processMouseDown = function (e) {\n // prepare for ctrl+shift drag: zoom start\n if (e.ctrlKey && e.shiftKey && e.buttons) {\n self.zoom_drag_start = [e.x, e.y, this.ds.scale]\n return\n }\n\n const res = origProcessMouseDown.apply(this, arguments)\n\n this.selected_group_moving = false\n\n if (this.selected_group && !this.selected_group_resizing) {\n var font_size =\n this.selected_group.font_size || LiteGraph.DEFAULT_GROUP_FONT_SIZE\n var height = font_size * 1.4\n\n // Move group by header\n if (\n LiteGraph.isInsideRectangle(\n // @ts-expect-error\n e.canvasX,\n // @ts-expect-error\n e.canvasY,\n this.selected_group.pos[0],\n this.selected_group.pos[1],\n this.selected_group.size[0],\n height\n )\n ) {\n this.selected_group_moving = true\n }\n }\n\n return res\n }\n const origProcessMouseMove = LGraphCanvas.prototype.processMouseMove\n LGraphCanvas.prototype.processMouseMove = function (e) {\n // handle ctrl+shift drag\n if (e.ctrlKey && e.shiftKey && self.zoom_drag_start) {\n // stop canvas zoom action\n if (!e.buttons) {\n self.zoom_drag_start = null\n return\n }\n\n // calculate delta\n let deltaY = e.y - self.zoom_drag_start[1]\n let startScale = self.zoom_drag_start[2]\n\n let scale = startScale - deltaY / 100\n\n this.ds.changeScale(scale, [\n self.zoom_drag_start[0],\n self.zoom_drag_start[1]\n ])\n this.graph.change()\n\n return\n }\n\n const orig_selected_group = this.selected_group\n\n if (\n this.selected_group &&\n !this.selected_group_resizing &&\n !this.selected_group_moving\n ) {\n this.selected_group = null\n }\n\n const res = origProcessMouseMove.apply(this, arguments)\n\n if (\n orig_selected_group &&\n !this.selected_group_resizing &&\n !this.selected_group_moving\n ) {\n this.selected_group = orig_selected_group\n }\n\n return res\n }\n }\n\n /**\n * Handle keypress\n *\n * Ctrl + M mute/unmute selected nodes\n */\n #addProcessKeyHandler() {\n const self = this\n const origProcessKey = LGraphCanvas.prototype.processKey\n LGraphCanvas.prototype.processKey = function (e) {\n if (!this.graph) {\n return\n }\n\n var block_default = false\n\n if (e.target instanceof Element && e.target.localName == 'input') {\n return\n }\n\n if (e.type == 'keydown' && !e.repeat) {\n const key = e.code\n\n // Ctrl + M mute/unmute\n if (key === 'KeyM' && (e.metaKey || e.ctrlKey)) {\n if (this.selected_nodes) {\n for (var i in this.selected_nodes) {\n if (this.selected_nodes[i].mode === 2) {\n // never\n this.selected_nodes[i].mode = 0 // always\n } else {\n this.selected_nodes[i].mode = 2 // never\n }\n }\n }\n block_default = true\n }\n\n // Ctrl + B bypass\n if (key === 'KeyB' && (e.metaKey || e.ctrlKey)) {\n if (this.selected_nodes) {\n for (var i in this.selected_nodes) {\n if (this.selected_nodes[i].mode === 4) {\n // never\n this.selected_nodes[i].mode = 0 // always\n } else {\n this.selected_nodes[i].mode = 4 // never\n }\n }\n }\n block_default = true\n }\n\n // p pin/unpin\n if (key === 'KeyP') {\n if (this.selected_nodes) {\n for (const i in this.selected_nodes) {\n const node = this.selected_nodes[i]\n node.pin()\n }\n }\n block_default = true\n }\n\n // Alt + C collapse/uncollapse\n if (key === 'KeyC' && e.altKey) {\n if (this.selected_nodes) {\n for (var i in this.selected_nodes) {\n this.selected_nodes[i].collapse()\n }\n }\n block_default = true\n }\n\n // Ctrl+C Copy\n if (key === 'KeyC' && (e.metaKey || e.ctrlKey)) {\n // Trigger onCopy\n return true\n }\n\n // Ctrl+V Paste\n if (key === 'KeyV' && (e.metaKey || e.ctrlKey) && !e.shiftKey) {\n // Trigger onPaste\n return true\n }\n\n if ((key === 'NumpadAdd' || key === 'Equal') && e.altKey) {\n block_default = true\n let scale = this.ds.scale * 1.1\n this.ds.changeScale(scale, [\n this.ds.element.width / 2,\n this.ds.element.height / 2\n ])\n this.graph.change()\n }\n\n if ((key === 'NumpadSubtract' || key === 'Minus') && e.altKey) {\n block_default = true\n let scale = this.ds.scale / 1.1\n this.ds.changeScale(scale, [\n this.ds.element.width / 2,\n this.ds.element.height / 2\n ])\n this.graph.change()\n }\n }\n\n this.graph.change()\n\n if (block_default) {\n e.preventDefault()\n e.stopImmediatePropagation()\n return false\n }\n\n // Fall through to Litegraph defaults\n return origProcessKey.apply(this, arguments)\n }\n }\n\n /**\n * Draws group header bar\n */\n #addDrawGroupsHandler() {\n const self = this\n const origDrawGroups = LGraphCanvas.prototype.drawGroups\n LGraphCanvas.prototype.drawGroups = function (canvas, ctx) {\n if (!this.graph) {\n return\n }\n\n var groups = this.graph.groups\n\n ctx.save()\n ctx.globalAlpha = 0.7 * this.editor_alpha\n\n for (var i = 0; i < groups.length; ++i) {\n var group = groups[i]\n\n if (!LiteGraph.overlapBounding(this.visible_area, group._bounding)) {\n continue\n } //out of the visible area\n\n ctx.fillStyle = group.color || '#335'\n ctx.strokeStyle = group.color || '#335'\n var pos = group._pos\n var size = group._size\n ctx.globalAlpha = 0.25 * this.editor_alpha\n ctx.beginPath()\n var font_size = group.font_size || LiteGraph.DEFAULT_GROUP_FONT_SIZE\n ctx.rect(pos[0] + 0.5, pos[1] + 0.5, size[0], font_size * 1.4)\n ctx.fill()\n ctx.globalAlpha = this.editor_alpha\n }\n\n ctx.restore()\n\n const res = origDrawGroups.apply(this, arguments)\n return res\n }\n }\n\n /**\n * Draws node highlights (executing, drag drop) and progress bar\n */\n #addDrawNodeHandler() {\n const origDrawNodeShape = LGraphCanvas.prototype.drawNodeShape\n const self = this\n LGraphCanvas.prototype.drawNodeShape = function (\n node,\n ctx,\n size,\n fgcolor,\n bgcolor,\n selected,\n mouse_over\n ) {\n const res = origDrawNodeShape.apply(this, arguments)\n\n const nodeErrors = self.lastNodeErrors?.[node.id]\n\n let color = null\n let lineWidth = 1\n if (node.id === +self.runningNodeId) {\n color = '#0f0'\n } else if (self.dragOverNode && node.id === self.dragOverNode.id) {\n color = 'dodgerblue'\n } else if (nodeErrors?.errors) {\n color = 'red'\n lineWidth = 2\n } else if (\n self.lastExecutionError &&\n +self.lastExecutionError.node_id === node.id\n ) {\n color = '#f0f'\n lineWidth = 2\n }\n\n if (color) {\n const shape =\n // @ts-expect-error\n node._shape || node.constructor.shape || LiteGraph.ROUND_SHAPE\n ctx.lineWidth = lineWidth\n ctx.globalAlpha = 0.8\n ctx.beginPath()\n if (shape == LiteGraph.BOX_SHAPE)\n ctx.rect(\n -6,\n -6 - LiteGraph.NODE_TITLE_HEIGHT,\n 12 + size[0] + 1,\n 12 + size[1] + LiteGraph.NODE_TITLE_HEIGHT\n )\n else if (\n shape == LiteGraph.ROUND_SHAPE ||\n (shape == LiteGraph.CARD_SHAPE && node.flags.collapsed)\n )\n ctx.roundRect(\n -6,\n -6 - LiteGraph.NODE_TITLE_HEIGHT,\n 12 + size[0] + 1,\n 12 + size[1] + LiteGraph.NODE_TITLE_HEIGHT,\n this.round_radius * 2\n )\n else if (shape == LiteGraph.CARD_SHAPE)\n ctx.roundRect(\n -6,\n -6 - LiteGraph.NODE_TITLE_HEIGHT,\n 12 + size[0] + 1,\n 12 + size[1] + LiteGraph.NODE_TITLE_HEIGHT,\n [this.round_radius * 2, this.round_radius * 2, 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 ctx.strokeStyle = color\n ctx.stroke()\n ctx.strokeStyle = fgcolor\n ctx.globalAlpha = 1\n }\n\n if (self.progress && node.id === +self.runningNodeId) {\n ctx.fillStyle = 'green'\n ctx.fillRect(\n 0,\n 0,\n size[0] * (self.progress.value / self.progress.max),\n 6\n )\n ctx.fillStyle = bgcolor\n }\n\n // Highlight inputs that failed validation\n if (nodeErrors) {\n ctx.lineWidth = 2\n ctx.strokeStyle = 'red'\n for (const error of nodeErrors.errors) {\n if (error.extra_info && error.extra_info.input_name) {\n const inputIndex = node.findInputSlot(error.extra_info.input_name)\n if (inputIndex !== -1) {\n let pos = node.getConnectionPos(true, inputIndex)\n ctx.beginPath()\n ctx.arc(\n pos[0] - node.pos[0],\n pos[1] - node.pos[1],\n 12,\n 0,\n 2 * Math.PI,\n false\n )\n ctx.stroke()\n }\n }\n }\n }\n\n return res\n }\n\n const origDrawNode = LGraphCanvas.prototype.drawNode\n LGraphCanvas.prototype.drawNode = function (node, ctx) {\n var editor_alpha = this.editor_alpha\n var old_color = node.color\n var old_bgcolor = node.bgcolor\n\n if (node.mode === 2) {\n // never\n this.editor_alpha = 0.4\n }\n\n // ComfyUI's custom node mode enum value 4 => bypass/never.\n // @ts-expect-error\n if (node.mode === 4) {\n // never\n node.bgcolor = '#FF00FF'\n this.editor_alpha = 0.2\n }\n\n const adjustColor = (color?: string) => {\n return color ? lightenColor(color, 0.5) : color\n }\n if (app.ui.settings.getSettingValue('Comfy.ColorPalette') === 'light') {\n node.bgcolor = adjustColor(node.bgcolor)\n node.color = adjustColor(node.color)\n }\n\n const res = origDrawNode.apply(this, arguments)\n\n this.editor_alpha = editor_alpha\n node.color = old_color\n node.bgcolor = old_bgcolor\n\n return res\n }\n }\n\n /**\n * Handles updates from the API socket\n */\n #addApiUpdateHandlers() {\n api.addEventListener(\n 'status',\n ({ detail }: CustomEvent) => {\n this.ui.setStatus(detail)\n }\n )\n\n api.addEventListener('progress', ({ detail }) => {\n this.progress = detail\n this.graph.setDirtyCanvas(true, false)\n })\n\n api.addEventListener('executing', ({ detail }) => {\n this.progress = null\n this.graph.setDirtyCanvas(true, false)\n delete this.nodePreviewImages[this.runningNodeId]\n })\n\n api.addEventListener('executed', ({ detail }) => {\n const output = this.nodeOutputs[detail.display_node || detail.node]\n if (detail.merge && output) {\n for (const k in detail.output ?? {}) {\n const v = output[k]\n if (v instanceof Array) {\n output[k] = v.concat(detail.output[k])\n } else {\n output[k] = detail.output[k]\n }\n }\n } else {\n this.nodeOutputs[detail.display_node || detail.node] = detail.output\n }\n const node = this.graph.getNodeById(detail.display_node || detail.node)\n if (node) {\n // @ts-expect-error\n if (node.onExecuted)\n // @ts-expect-error\n node.onExecuted(detail.output)\n }\n })\n\n api.addEventListener('execution_start', ({ detail }) => {\n this.lastExecutionError = null\n this.graph.nodes.forEach((node) => {\n // @ts-expect-error\n if (node.onExecutionStart)\n // @ts-expect-error\n node.onExecutionStart()\n })\n })\n\n api.addEventListener('execution_error', ({ detail }) => {\n this.lastExecutionError = detail\n showExecutionErrorDialog(detail)\n this.canvas.draw(true, true)\n })\n\n api.addEventListener('b_preview', ({ detail }) => {\n const id = this.runningNodeId\n if (id == null) return\n\n const blob = detail\n const blobUrl = URL.createObjectURL(blob)\n // @ts-expect-error\n this.nodePreviewImages[id] = [blobUrl]\n })\n\n api.init()\n }\n\n #addKeyboardHandler() {\n window.addEventListener('keydown', (e) => {\n this.shiftDown = e.shiftKey\n })\n window.addEventListener('keyup', (e) => {\n this.shiftDown = e.shiftKey\n })\n }\n\n #addConfigureHandler() {\n const app = this\n const configure = LGraph.prototype.configure\n // Flag that the graph is configuring to prevent nodes from running checks while its still loading\n LGraph.prototype.configure = function () {\n app.configuringGraph = true\n try {\n return configure.apply(this, arguments)\n } finally {\n app.configuringGraph = false\n }\n }\n }\n\n #addAfterConfigureHandler() {\n const app = this\n // @ts-expect-error\n const onConfigure = app.graph.onConfigure\n // @ts-expect-error\n app.graph.onConfigure = function () {\n // Fire callbacks before the onConfigure, this is used by widget inputs to setup the config\n for (const node of app.graph.nodes) {\n // @ts-expect-error\n node.onGraphConfigured?.()\n }\n\n const r = onConfigure?.apply(this, arguments)\n\n // Fire after onConfigure, used by primitives to generate widget using input nodes config\n for (const node of app.graph.nodes) {\n node.onAfterGraphConfigured?.()\n }\n\n return r\n }\n }\n\n /**\n * Loads all extensions from the API into the window in parallel\n */\n async #loadExtensions() {\n const extensions = await api.getExtensions()\n this.logging.addEntry('Comfy.App', 'debug', { Extensions: extensions })\n\n // Need to load core extensions first as some custom extensions\n // may depend on them.\n await import('../extensions/core/index')\n await Promise.all(\n extensions\n .filter((extension) => !extension.includes('extensions/core'))\n .map(async (ext) => {\n try {\n await import(/* @vite-ignore */ api.fileURL(ext))\n } catch (error) {\n console.error('Error loading extension', ext, error)\n }\n })\n )\n\n try {\n this.menu.workflows.registerExtension(this)\n } catch (error) {\n console.error(error)\n }\n }\n\n async #migrateSettings() {\n this.isNewUserSession = true\n // Store all current settings\n const settings = Object.keys(this.ui.settings).reduce((p, n) => {\n const v = localStorage[`Comfy.Settings.${n}`]\n if (v) {\n try {\n p[n] = JSON.parse(v)\n } catch (error) {}\n }\n return p\n }, {})\n\n await api.storeSettings(settings)\n }\n\n async #setUser() {\n const userConfig = await api.getUserConfig()\n this.storageLocation = userConfig.storage\n if (typeof userConfig.migrated == 'boolean') {\n // Single user mode migrated true/false for if the default user is created\n if (!userConfig.migrated && this.storageLocation === 'server') {\n // Default user not created yet\n await this.#migrateSettings()\n }\n return\n }\n\n this.multiUserServer = true\n let user = localStorage['Comfy.userId']\n const users = userConfig.users ?? {}\n if (!user || !users[user]) {\n // Lift spinner / BlockUI for user selection.\n if (this.vueAppReady) useWorkspaceStore().spinner = false\n\n // This will rarely be hit so move the loading to on demand\n const { UserSelectionScreen } = await import('./ui/userSelection')\n\n this.ui.menuContainer.style.display = 'none'\n const { userId, username, created } =\n await new UserSelectionScreen().show(users, user)\n this.ui.menuContainer.style.display = ''\n\n user = userId\n localStorage['Comfy.userName'] = username\n localStorage['Comfy.userId'] = user\n\n if (created) {\n api.user = user\n await this.#migrateSettings()\n }\n }\n\n api.user = user\n\n this.ui.settings.addSetting({\n id: 'Comfy.SwitchUser',\n name: 'Switch User',\n type: (name) => {\n let currentUser = localStorage['Comfy.userName']\n if (currentUser) {\n currentUser = ` (${currentUser})`\n }\n return $el('tr', [\n $el('td', [\n $el('label', {\n textContent: name\n })\n ]),\n $el('td', [\n $el('button', {\n textContent: name + (currentUser ?? ''),\n onclick: () => {\n delete localStorage['Comfy.userId']\n delete localStorage['Comfy.userName']\n window.location.reload()\n }\n })\n ])\n ])\n },\n // TODO: Is that the correct default value?\n defaultValue: undefined\n })\n }\n\n /**\n * Set up the app on the page\n */\n async setup(canvasEl: HTMLCanvasElement) {\n this.canvasEl = canvasEl\n await this.#setUser()\n\n this.resizeCanvas()\n\n await Promise.all([\n this.workflowManager.loadWorkflows(),\n this.ui.settings.load()\n ])\n await this.#loadExtensions()\n\n addDomClippingSetting()\n this.#addProcessMouseHandler()\n this.#addProcessKeyHandler()\n this.#addConfigureHandler()\n this.#addApiUpdateHandlers()\n this.#addRestoreWorkflowView()\n\n this.graph = new LGraph()\n\n this.#addAfterConfigureHandler()\n\n this.canvas = new LGraphCanvas(canvasEl, this.graph)\n this.ctx = canvasEl.getContext('2d')\n\n LiteGraph.alt_drag_do_clone_nodes = true\n\n this.graph.start()\n\n // Ensure the canvas fills the window\n this.resizeCanvas()\n window.addEventListener('resize', () => this.resizeCanvas())\n const ro = new ResizeObserver(() => this.resizeCanvas())\n ro.observe(this.bodyTop)\n ro.observe(this.bodyLeft)\n ro.observe(this.bodyRight)\n ro.observe(this.bodyBottom)\n\n await this.#invokeExtensionsAsync('init')\n await this.registerNodes()\n initWidgets(this)\n\n // Load previous workflow\n let restored = false\n try {\n const loadWorkflow = async (json) => {\n if (json) {\n const workflow = JSON.parse(json)\n const workflowName = getStorageValue('Comfy.PreviousWorkflow')\n await this.loadGraphData(workflow, true, true, workflowName)\n return true\n }\n }\n const clientId = api.initialClientId ?? api.clientId\n restored =\n (clientId &&\n (await loadWorkflow(\n sessionStorage.getItem(`workflow:${clientId}`)\n ))) ||\n (await loadWorkflow(localStorage.getItem('workflow')))\n } catch (err) {\n console.error('Error loading previous workflow', err)\n }\n\n // We failed to restore a workflow so load the default\n if (!restored) {\n await this.loadGraphData()\n }\n\n // Save current workflow automatically\n setInterval(() => {\n const sortNodes = useSettingStore().get('Comfy.Workflow.SortNodeIdOnSave')\n const workflow = JSON.stringify(this.graph.serialize({ sortNodes }))\n localStorage.setItem('workflow', workflow)\n if (api.clientId) {\n sessionStorage.setItem(`workflow:${api.clientId}`, workflow)\n }\n }, 1000)\n\n this.#addDrawNodeHandler()\n this.#addDrawGroupsHandler()\n this.#addDropHandler()\n this.#addCopyHandler()\n this.#addPasteHandler()\n this.#addKeyboardHandler()\n\n await this.#invokeExtensionsAsync('setup')\n }\n\n resizeCanvas() {\n // Limit minimal scale to 1, see https://github.com/comfyanonymous/ComfyUI/pull/845\n const scale = Math.max(window.devicePixelRatio, 1)\n\n // Clear fixed width and height while calculating rect so it uses 100% instead\n this.canvasEl.height = this.canvasEl.width = NaN\n const { width, height } = this.canvasEl.getBoundingClientRect()\n this.canvasEl.width = Math.round(width * scale)\n this.canvasEl.height = Math.round(height * scale)\n this.canvasEl.getContext('2d').scale(scale, scale)\n this.canvas?.draw(true, true)\n }\n\n private updateVueAppNodeDefs(defs: Record) {\n // Frontend only nodes registered by custom nodes.\n // Example: https://github.com/rgthree/rgthree-comfy/blob/dd534e5384be8cf0c0fa35865afe2126ba75ac55/src_web/comfyui/fast_groups_bypasser.ts#L10\n const rawDefs = Object.fromEntries(\n Object.entries(LiteGraph.registered_node_types).map(([name, node]) => [\n name,\n {\n name,\n display_name: name,\n // @ts-expect-error\n category: node.category || '__frontend_only__',\n input: { required: {}, optional: {} },\n output: [],\n output_name: [],\n output_is_list: [],\n python_module: 'custom_nodes.frontend_only',\n description: `Frontend only node for ${name}`\n }\n ])\n )\n\n const allNodeDefs = {\n ...rawDefs,\n ...defs,\n ...SYSTEM_NODE_DEFS\n }\n\n const nodeDefStore = useNodeDefStore()\n const nodeDefArray: ComfyNodeDef[] = Object.values(allNodeDefs)\n this.#invokeExtensions('beforeRegisterVueAppNodeDefs', nodeDefArray, this)\n nodeDefStore.updateNodeDefs(nodeDefArray)\n nodeDefStore.updateWidgets(this.widgets)\n }\n\n /**\n * Registers nodes with the graph\n */\n async registerNodes() {\n // Load node definitions from the backend\n const defs = await api.getNodeDefs()\n await this.registerNodesFromDefs(defs)\n await this.#invokeExtensionsAsync('registerCustomNodes')\n if (this.vueAppReady) {\n this.updateVueAppNodeDefs(defs)\n }\n }\n\n getWidgetType(inputData, inputName) {\n const type = inputData[0]\n\n if (Array.isArray(type)) {\n return 'COMBO'\n } else if (`${type}:${inputName}` in this.widgets) {\n return `${type}:${inputName}`\n } else if (type in this.widgets) {\n return type\n } else {\n return null\n }\n }\n\n async registerNodeDef(nodeId: string, nodeData: ComfyNodeDef) {\n const self = this\n const node: new () => ComfyLGraphNode = class ComfyNode extends LGraphNode {\n static comfyClass? = nodeData.name\n // TODO: change to \"title?\" once litegraph.d.ts has been updated\n static title = nodeData.display_name || nodeData.name\n static nodeData? = nodeData\n static category?: string\n\n constructor(title?: string) {\n super(title)\n var inputs = nodeData['input']['required']\n if (nodeData['input']['optional'] != undefined) {\n inputs = Object.assign(\n {},\n nodeData['input']['required'],\n nodeData['input']['optional']\n )\n }\n const config = { minWidth: 1, minHeight: 1 }\n for (const inputName in inputs) {\n const inputData = inputs[inputName]\n const type = inputData[0]\n\n let widgetCreated = true\n const widgetType = self.getWidgetType(inputData, inputName)\n if (widgetType) {\n if (widgetType === 'COMBO') {\n Object.assign(\n config,\n self.widgets.COMBO(this, inputName, inputData, app) || {}\n )\n } else {\n Object.assign(\n config,\n self.widgets[widgetType](this, inputName, inputData, app) || {}\n )\n }\n } else {\n // Node connection inputs\n this.addInput(inputName, type)\n widgetCreated = false\n }\n // @ts-expect-error\n if (widgetCreated && inputData[1]?.forceInput && config?.widget) {\n // @ts-expect-error\n if (!config.widget.options) config.widget.options = {}\n // @ts-expect-error\n config.widget.options.forceInput = inputData[1].forceInput\n }\n // @ts-expect-error\n if (widgetCreated && inputData[1]?.defaultInput && config?.widget) {\n // @ts-expect-error\n if (!config.widget.options) config.widget.options = {}\n // @ts-expect-error\n config.widget.options.defaultInput = inputData[1].defaultInput\n }\n }\n\n for (const o in nodeData['output']) {\n let output = nodeData['output'][o]\n if (output instanceof Array) output = 'COMBO'\n const outputName = nodeData['output_name'][o] || output\n const outputShape = nodeData['output_is_list'][o]\n ? LiteGraph.GRID_SHAPE\n : LiteGraph.CIRCLE_SHAPE\n this.addOutput(outputName, output, { shape: outputShape })\n }\n\n const s = this.computeSize()\n s[0] = Math.max(config.minWidth, s[0] * 1.5)\n s[1] = Math.max(config.minHeight, s[1])\n this.size = s\n this.serialize_widgets = true\n\n app.#invokeExtensionsAsync('nodeCreated', this)\n }\n }\n node.prototype.comfyClass = nodeData.name\n\n this.#addNodeContextMenuHandler(node)\n this.#addDrawBackgroundHandler(node)\n this.#addNodeKeyHandler(node)\n\n await this.#invokeExtensionsAsync('beforeRegisterNodeDef', node, nodeData)\n LiteGraph.registerNodeType(nodeId, node)\n // Note: Do not move this to the class definition, it will be overwritten\n // @ts-expect-error\n node.category = nodeData.category\n }\n\n async registerNodesFromDefs(defs: Record