diff --git a/.env b/.env deleted file mode 100644 index e69de29b..00000000 diff --git a/.github/workflows/backend-test.yml b/.github/workflows/backend-test.yml new file mode 100644 index 00000000..deb0c9d0 --- /dev/null +++ b/.github/workflows/backend-test.yml @@ -0,0 +1,39 @@ +name: Backend tests + +on: + push: + paths: + - "backend/**" + - ".github/workflows/backend-test.yml" + pull_request: + paths: + - "backend/**" + - ".github/workflows/backend-test.yml" + +permissions: + contents: read + +jobs: + test: + runs-on: ubuntu-latest + strategy: + matrix: + python-version: ["3.11", "3.12", "3.13"] + defaults: + run: + working-directory: backend + steps: + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 + with: + python-version: ${{ matrix.python-version }} + - name: Install uv + uses: astral-sh/setup-uv@e92bafb6253dcd438e0484186d7669ea7a8ca1cc # v6 + with: + enable-cache: true + cache-dependency-glob: backend/uv.lock + - name: Install dependencies + run: uv sync --frozen --extra test + - name: Run tests + run: uv run pytest diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 507be828..f6c7914d 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -73,6 +73,8 @@ jobs: steps: - name: Checkout repository uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - name: Normalize image name + run: echo "IMAGE_NAME=${GITHUB_REPOSITORY,,}" >> "$GITHUB_ENV" - name: Download build artifacts uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 with: @@ -118,17 +120,61 @@ jobs: subject-digest: ${{ steps.push.outputs.digest }} push-to-registry: true + # No-auth, no-network packaging check: prove the shipped non-root image can + # resolve the bundled Copilot runtime. Does not authenticate, use credentials, + # or reach the network, and prints no environment values. + runtime-check: + needs: build-and-push-image + runs-on: ubuntu-latest + permissions: + contents: read + packages: read + steps: + - name: Normalize image name + run: echo "IMAGE_NAME=${GITHUB_REPOSITORY,,}" >> "$GITHUB_ENV" + - name: Log in to the Container registry + uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3 + with: + registry: ${{ env.REGISTRY }} + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + - name: Get short SHA + id: get_short_sha + run: echo "short_sha=$(echo ${{ github.sha }} | cut -c1-7)" >> $GITHUB_OUTPUT + - name: Verify bundled runtime resolves for the non-root user + env: + IMAGE: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:sha-${{ steps.get_short_sha.outputs.short_sha }} + run: | + docker pull "$IMAGE" + docker run --rm -i --network none --user app --entrypoint python "$IMAGE" - <<'PY' + import os + + from openui import config + from openui.copilot.device_auth import resolve_copilot_cli_path + + data_dir = config.default_db.parent + assert data_dir.is_dir(), f"data directory was not created: {data_dir}" + assert os.access(data_dir, os.W_OK), ( + f"data directory is not writable by the app user: {data_dir}" + ) + + cli_path = resolve_copilot_cli_path() + assert os.path.exists(cli_path), "bundled Copilot runtime is missing" + assert os.access(cli_path, os.X_OK), "bundled Copilot runtime is not executable" + print("bundled Copilot runtime resolved and executable") + PY + test: permissions: contents: read - packages: write - attestations: write - id-token: write + packages: read needs: build-and-push-image timeout-minutes: 10 runs-on: ubuntu-latest steps: - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + - name: Normalize image name + run: echo "IMAGE_NAME=${GITHUB_REPOSITORY,,}" >> "$GITHUB_ENV" - uses: pnpm/action-setup@b906affcce14559ad1aafd4ab0e942779e9f58b1 # v4 name: Install pnpm with: @@ -155,12 +201,24 @@ jobs: - name: Install dependencies working-directory: ./frontend run: pnpm install + - name: Get short SHA + id: get_short_sha + run: echo "short_sha=$(git rev-parse --short HEAD)" >> "$GITHUB_OUTPUT" + - name: Log in to the Container registry + uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3 + with: + registry: ${{ env.REGISTRY }} + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + - name: Pull image for Playwright + env: + IMAGE: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:sha-${{ steps.get_short_sha.outputs.short_sha }} + run: docker pull "$IMAGE" + - name: Log out of the Container registry + run: docker logout "$REGISTRY" - name: Install Playwright Browsers working-directory: ./frontend run: pnpm exec playwright install --with-deps chromium webkit - - name: Get short SHA - id: get_short_sha - run: echo "short_sha=$(git rev-parse --short HEAD)" >> $GITHUB_OUTPUT - name: Run Playwright tests env: DOCKER_TAG: sha-${{ steps.get_short_sha.outputs.short_sha }} @@ -176,7 +234,7 @@ jobs: retention-days: 30 release: - needs: test + needs: [test, runtime-check] runs-on: ubuntu-latest permissions: contents: read @@ -184,6 +242,8 @@ jobs: attestations: write id-token: write steps: + - name: Normalize image name + run: echo "IMAGE_NAME=${GITHUB_REPOSITORY,,}" >> "$GITHUB_ENV" - name: Log in to the Container registry uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3 with: diff --git a/README.md b/README.md index 7aa0c892..824dc848 100644 --- a/README.md +++ b/README.md @@ -102,6 +102,70 @@ If you have your OPENAI_API_KEY set in the environment already, just remove `=xx *If you make changes to the frontend or backend, you'll need to run `docker-compose build` to have them reflected in the service.* +### GitHub Copilot + +This fork can use GitHub Copilot as an additional provider for text-to-UI and +screenshot-to-UI generation. It uses the official Copilot SDK; it does not turn +Copilot into a public OpenAI-compatible API. + +- Existing OpenAI, Groq, Ollama, and LiteLLM providers remain available. +- Copilot sessions run in SDK `empty` mode with no tools, shell, filesystem, + MCP servers, skills, plugins, or persistent conversation. +- A real-account smoke test is manual because it uses the account's allowance. + +Two authentication modes are available: + +**Device mode** (local single-user) — the server authenticates using the host +machine's GitHub credentials via the GitHub device flow. Set +`OPENUI_COPILOT_AUTH_MODE=device`. All requests share one machine identity and +allowance; device mode is **not suitable for untrusted multi-user access**. +Device mode is **strictly local and bare-process only**: + +- OpenUI refuses to start unless `OPENUI_ENVIRONMENT=local` and `OPENUI_HOST` + binds a loopback address (`localhost`, `127.0.0.1`, or `::1`). +- The in-app device setup endpoints only accept requests whose TCP peer is + loopback, whose `Host` and (any) `Origin` hostnames are loopback, and that + carry no proxy headers (`Forwarded`, `X-Forwarded-For`, `X-Real-IP`, `Via`). +- Device mode must **not** be served through a reverse proxy, a port-forwarding + or tunnel platform, a public tunnel, a custom hostname, or Gitpod/Codespaces + port exposure — a same-host proxy connects from loopback and would otherwise + make remote requests look local. +- Device mode **cannot run inside a container** (Docker/Kubernetes): bridge + networking delivers requests from a non-loopback gateway, so OpenUI refuses + to start device mode in a container. Container deployments must use OAuth + mode. + +The only supported private-remote path is an SSH local port forward to a bare +host process while you browse a loopback URL +(`ssh -L 7878:127.0.0.1:7878 host`), rather than exposing OpenUI directly. For +cloud, container, or multi-user deployments use OAuth mode instead. + +```bash +export OPENUI_COPILOT_ENABLED=1 +export OPENUI_COPILOT_AUTH_MODE=device +cd backend +uv run python -m copilot download-runtime +uv run python -m openui +``` + +Then open Settings, select **Connect GitHub Copilot**, copy the one-time code, +authorize at `https://github.com/login/device`, and wait for models to refresh. + +**OAuth mode** (cloud / multi-user) — each user signs in individually with +their own GitHub account and Copilot entitlement. Requires a GitHub OAuth App +and a token-encryption key. Set `OPENUI_COPILOT_AUTH_MODE=oauth` (the default). + +```bash +export OPENUI_COPILOT_ENABLED=1 +export OPENUI_COPILOT_AUTH_MODE=oauth +export OPENUI_TOKEN_ENCRYPTION_KEY='v1:' +export GITHUB_CLIENT_ID='' +export GITHUB_CLIENT_SECRET='' +``` + +See [`backend/README.md`](backend/README.md#github-copilot-provider) for full +setup instructions for both modes. + ## Development A [dev container](https://github.com/wandb/openui/blob/main/.devcontainer/devcontainer.json) is configured in this repository which is the quickest way to get started. diff --git a/backend/.github/workflows/test.yml b/backend/.github/workflows/test.yml deleted file mode 100644 index 2d435300..00000000 --- a/backend/.github/workflows/test.yml +++ /dev/null @@ -1,28 +0,0 @@ -name: Test - -on: [push, pull_request] - -permissions: - contents: read - -jobs: - test: - runs-on: ubuntu-latest - strategy: - matrix: - python-version: ["3.8", "3.9", "3.10", "3.11", "3.12"] - steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 - - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 - with: - python-version: ${{ matrix.python-version }} - cache: pip - cache-dependency-path: pyproject.toml - - name: Install dependencies - run: | - pip install '.[test]' - - name: Run tests - run: | - pytest - diff --git a/backend/Dockerfile b/backend/Dockerfile index c157d13f..56f076ed 100644 --- a/backend/Dockerfile +++ b/backend/Dockerfile @@ -3,7 +3,9 @@ FROM ghcr.io/astral-sh/uv:python3.12-bookworm-slim AS builder WORKDIR /app -ENV UV_LINK_MODE=copy UV_COMPILE_BYTECODE=1 +ENV UV_LINK_MODE=copy \ + UV_COMPILE_BYTECODE=1 \ + COPILOT_CLI_EXTRACT_DIR=/app/.copilot-runtime RUN --mount=type=cache,target=/root/.cache/uv \ --mount=type=bind,source=uv.lock,target=uv.lock \ @@ -13,15 +15,23 @@ RUN --mount=type=cache,target=/root/.cache/uv \ COPY . /app RUN --mount=type=cache,target=/root/.cache/uv \ - uv sync --frozen --extra litellm --no-dev + uv sync --frozen --extra litellm --no-dev \ + && /app/.venv/bin/python -m copilot download-runtime -# Copy the virtualenv into a distroless image FROM ghcr.io/astral-sh/uv:python3.12-bookworm-slim WORKDIR /app +RUN groupadd --system app \ + && useradd --system --gid app --home-dir /app --no-create-home app \ + && chown app:app /app + COPY --from=builder --chown=app:app /app /app -ENV PATH="/app/.venv/bin:$PATH" +ENV PATH="/app/.venv/bin:$PATH" \ + COPILOT_CLI_EXTRACT_DIR=/app/.copilot-runtime \ + HOME=/app + +USER app ENTRYPOINT ["python", "-m", "openui", "--litellm"] diff --git a/backend/README.md b/backend/README.md index a6bd9a5a..731dae5b 100644 --- a/backend/README.md +++ b/backend/README.md @@ -33,6 +33,10 @@ docker build . -t wandb/openui --load docker run -p 7878:7878 -e OPENAI_API_KEY wandb/openui ``` +> **Note:** Container deployments must use Copilot **OAuth mode**, not device +> mode. Device mode is bare-process only and refuses to start inside a container +> because bridge networking delivers requests from a non-loopback gateway. + ## Development First be sure to install the package as editable, then passing `--dev` as an argument will live reload any local changes. @@ -65,4 +69,128 @@ Create a service account with the appropriate permissions and authenticate with: ``` gcloud auth application-default login --impersonate-service-account ${GCLOUD_SERVICE_ACCOUNT}@${GCLOUD_PROJECT}.iam.gserviceaccount.com -``` \ No newline at end of file +``` + +## GitHub Copilot provider + +Copilot support is optional and disabled by default. OpenUI supports two +authentication modes: **device mode** for local single-user use, and **OAuth +mode** for cloud or multi-user deployments. + +### Device mode (local single-user) + +Device mode uses the host machine's GitHub Copilot CLI credentials. It is +intended for a single trusted user running OpenUI locally. **All requests share +one machine identity and consume that account's Copilot allowance — do not +expose device mode to untrusted or multi-user access over the network.** + +Multiple independent, non-overridable guards enforce that device mode stays a +strictly local, bare-process deployment: + +- **Startup environment guard:** if `OPENUI_ENVIRONMENT` is not `local`, OpenUI + refuses to start with Copilot device mode enabled. +- **Startup host guard:** `OPENUI_HOST` must bind a loopback address + (`localhost`, `127.0.0.1`, or `::1`). A public or custom hostname is rejected + so device mode cannot be advertised behind a reverse proxy or forwarder. +- **Startup container guard:** device mode refuses to start inside a container + (Docker/Kubernetes). Bridge networking delivers requests from a non-loopback + gateway, so device mode is bare-process only — container deployments must use + OAuth mode. +- **Request guard:** even in a local environment, the device-flow API endpoints + reject any request whose TCP peer is not loopback, whose `Host` or `Origin` + hostname is not loopback, or that carries a proxy header (`Forwarded`, + `X-Forwarded-For`, `X-Real-IP`, `Via`). These headers are never trusted or + parsed — their mere presence fails the request closed, because a same-host + reverse proxy or port forwarder connects from loopback and would otherwise + make a remote request look local. + +There is no remote-override switch. Device mode must **not** be served through a +reverse proxy, a port-forwarding or tunnel platform, a public tunnel, a custom +hostname, or Gitpod/Codespaces port exposure. The only supported private-remote +path is an SSH local port forward to a bare host process while browsing a +loopback URL (for example `ssh -L 7878:127.0.0.1:7878 your-server`) so the +request still reaches OpenUI from `127.0.0.1`. For cloud, container, or +multi-user deployments, use OAuth mode instead. + +1. Install and provision the pinned runtime: + + ```bash + uv sync --frozen + uv run python -m copilot download-runtime + ``` + +2. Set the environment without committing these values: + + ```bash + export OPENUI_COPILOT_ENABLED=1 + export OPENUI_COPILOT_AUTH_MODE=device + ``` + +3. Start OpenUI: + + ```bash + cd backend + uv run python -m openui + ``` + +4. Open `http://localhost:7878`, click the settings icon, select **Connect + GitHub Copilot**, copy the one-time code shown in the dialog, visit + `https://github.com/login/device`, enter the code, and authorize. The + model list refreshes automatically once authentication completes. + +> **Warning:** Device mode is unsuitable for untrusted multi-user or remote +> access. Every request runs as the authenticated machine account and consumes +> its Copilot allowance. The local-only guards cannot be disabled; a private +> remote operator must reach the loopback interface through an SSH tunnel +> instead of exposing OpenUI on a public interface. + +### OAuth mode (cloud / multi-user) + +OAuth mode requires a GitHub OAuth App. Each user signs in individually and +uses their own Copilot entitlement and allowance. + +1. Create a GitHub OAuth App with: + - Homepage URL: `http://localhost:7878` + - Authorization callback URL: `http://localhost:7878/v1/callback` +2. Generate the token-encryption key once: + + ```bash + python -c "import base64,secrets; print('v1:' + base64.urlsafe_b64encode(secrets.token_bytes(32)).decode().rstrip('='))" + ``` + +3. Set the environment without committing these values: + + ```bash + export OPENUI_COPILOT_ENABLED=1 + export OPENUI_COPILOT_AUTH_MODE=oauth + export OPENUI_TOKEN_ENCRYPTION_KEY='v1:' + export GITHUB_CLIENT_ID='' + export GITHUB_CLIENT_SECRET='' + export OPENUI_HOST='http://localhost:7878' + ``` + + `OPENUI_HOST` must be the deployment's public base URL (scheme + host + port, + no trailing slash) and must match the origin and path used in your OAuth App's + Authorization callback URL. The `http://localhost:7878` value above is only + correct for local development; change it to your public URL for cloud + deployments. + +4. Install and provision the pinned runtime, then start OpenUI: + + ```bash + uv sync --frozen + uv run python -m copilot download-runtime + uv run python -m openui + ``` + +Open `http://localhost:7878`, sign in with GitHub, and choose a model under +**GitHub Copilot**. No special OAuth scope named `copilot` is required. The +GitHub account must have an active Copilot entitlement. + +`OPENUI_TOKEN_ENCRYPTION_KEY` encrypts OAuth tokens stored in SQLite. Back it up +securely: changing or losing it makes existing stored tokens unusable and users +must reconnect GitHub. + +The Copilot SDK currently controls model inference settings. OpenUI's +temperature slider and `max_tokens` request field are not applied to Copilot +SDK 1.0.6 sessions. diff --git a/backend/openui/config.py b/backend/openui/config.py index 933e5a07..7f3bd048 100644 --- a/backend/openui/config.py +++ b/backend/openui/config.py @@ -1,3 +1,4 @@ +import ipaddress import os from pathlib import Path import secrets @@ -11,6 +12,11 @@ class Env(Enum): DEV = 3 +class CopilotAuthMode(str, Enum): + OAUTH = "oauth" + DEVICE = "device" + + try: env = os.getenv("OPENUI_ENVIRONMENT", "local") if env == "production": @@ -67,3 +73,149 @@ class Env(Enum): LITELLM_API_KEY = os.getenv("LITELLM_API_KEY", os.getenv("LITELLM_MASTER_KEY")) LITELLM_BASE_URL = os.getenv("LITELLM_BASE_URL", "http://0.0.0.0:4000") PORT = int(os.getenv("PORT", 7878)) + + +def env_bool(name: str, default: bool = False) -> bool: + value = os.getenv(name) + if value is None: + return default + return value.strip().lower() in {"1", "true", "yes", "on"} + + +def parse_copilot_auth_mode(value: str | None) -> CopilotAuthMode: + normalized = (value or CopilotAuthMode.OAUTH.value).strip().lower() + try: + return CopilotAuthMode(normalized) + except ValueError as exc: + raise RuntimeError( + "OPENUI_COPILOT_AUTH_MODE must be oauth or device" + ) from exc + + +def resolve_copilot_auth_mode(enabled: bool, value: str | None) -> CopilotAuthMode: + """Resolve the Copilot auth mode without crashing when Copilot is disabled. + + When Copilot is disabled the mode value is unused, so an invalid string must + not abort module import or server startup — return the safe OAuth default. + When Copilot is enabled the value is validated strictly. + """ + if not enabled: + return CopilotAuthMode.OAUTH + return parse_copilot_auth_mode(value) + + +COPILOT_ENABLED = env_bool("OPENUI_COPILOT_ENABLED") +COPILOT_AUTH_MODE = resolve_copilot_auth_mode( + COPILOT_ENABLED, os.getenv("OPENUI_COPILOT_AUTH_MODE") +) +COPILOT_TOKEN_ENCRYPTION_KEY = os.getenv("OPENUI_TOKEN_ENCRYPTION_KEY") +COPILOT_HOME = Path( + os.getenv("OPENUI_COPILOT_HOME", str(Path(DB).parent / "copilot")) +) +COPILOT_CLIENT_IDLE_SECONDS = float( + os.getenv("OPENUI_COPILOT_CLIENT_IDLE_SECONDS", "900") +) +COPILOT_CLIENT_SWEEP_SECONDS = float( + os.getenv("OPENUI_COPILOT_CLIENT_SWEEP_SECONDS", "60") +) +COPILOT_RESPONSE_TIMEOUT_SECONDS = float( + os.getenv("OPENUI_COPILOT_RESPONSE_TIMEOUT_SECONDS", "120") +) + + +def require_copilot_encryption_key() -> str: + if not COPILOT_TOKEN_ENCRYPTION_KEY: + raise RuntimeError( + "OPENUI_TOKEN_ENCRYPTION_KEY is required when Copilot is enabled" + ) + return COPILOT_TOKEN_ENCRYPTION_KEY + + +def is_local_hostname(hostname: str | None) -> bool: + """Return True only for a loopback IP or the literal hostname ``localhost``. + + Used to fail closed against public/custom hostnames. Non-loopback IPs and + arbitrary hostnames (proxy names, public DNS) are rejected. IPv4-mapped IPv6 + loopback is unwrapped and accepted. + """ + if not hostname: + return False + if hostname == "localhost": + return True + try: + parsed = ipaddress.ip_address(hostname) + except ValueError: + return False + if parsed.is_loopback: + return True + mapped = getattr(parsed, "ipv4_mapped", None) + return bool(mapped is not None and mapped.is_loopback) + + +def _detect_container( + dockerenv_path: str = "/.dockerenv", + cgroup_path: str = "/proc/1/cgroup", +) -> bool: + """Best-effort detection of running inside a Linux container. + + Checks the Docker sentinel file, Kubernetes service env, and the init + process cgroup for common container-runtime markers. Read no secrets. + """ + if os.path.exists(dockerenv_path): + return True + if os.environ.get("KUBERNETES_SERVICE_HOST"): + return True + try: + with open(cgroup_path, "r", encoding="utf-8") as handle: + content = handle.read() + except OSError: + return False + markers = ("docker", "containerd", "kubepods", "/lxc/") + return any(marker in content for marker in markers) + + +def is_running_in_container() -> bool: + return _detect_container() + + +def validate_copilot_configuration() -> None: + if not COPILOT_ENABLED: + return + + if COPILOT_AUTH_MODE is CopilotAuthMode.DEVICE: + if ENV is not Env.LOCAL: + raise RuntimeError( + "GitHub Copilot device mode is single-user and requires " + "OPENUI_ENVIRONMENT=local. For private remote use, tunnel the " + "loopback service (e.g. SSH port forwarding) instead." + ) + if is_running_in_container(): + raise RuntimeError( + "GitHub Copilot device mode is bare-process only and cannot run " + "inside a container: bridge-networked requests arrive from a " + "non-loopback gateway. Use OAuth mode " + "(OPENUI_COPILOT_AUTH_MODE=oauth) for Docker/container " + "deployments, or run device mode as a bare host process." + ) + if not is_local_hostname(urlparse(HOST).hostname): + raise RuntimeError( + "GitHub Copilot device mode requires OPENUI_HOST to bind a " + "loopback address (localhost, 127.0.0.1, or ::1). Device mode " + "must not be served on a public or custom hostname, through a " + "reverse proxy, or via a port-forwarding platform. For private " + "remote use, tunnel the loopback service (e.g. SSH port " + "forwarding) instead." + ) + return + + missing = [ + name + for name, value in ( + ("GITHUB_CLIENT_ID", GITHUB_CLIENT_ID), + ("GITHUB_CLIENT_SECRET", GITHUB_CLIENT_SECRET), + ("OPENUI_TOKEN_ENCRYPTION_KEY", COPILOT_TOKEN_ENCRYPTION_KEY), + ) + if not value + ] + if missing: + raise RuntimeError("GitHub Copilot OAuth mode requires " + ", ".join(missing)) diff --git a/backend/openui/copilot/__init__.py b/backend/openui/copilot/__init__.py new file mode 100644 index 00000000..ce57b234 --- /dev/null +++ b/backend/openui/copilot/__init__.py @@ -0,0 +1,38 @@ +from .device_auth import ( + CopilotDeviceAuthManager, + DeviceAuthState, + DeviceAuthStatus, + resolve_copilot_cli_path, +) +from .errors import CopilotProviderError +from .leases import ( + CopilotClientLeaseProvider, + OAuthClientLeaseProvider, + SharedClientLeaseProvider, +) +from .messages import CopilotModel, CopilotRequest, parse_copilot_request +from .provider import CopilotGeneration, CopilotProvider +from .registry import CopilotClientRegistry, create_device_client +from .sse import openai_sse_stream +from .token_store import OAuthTokenStore, TokenCipher + +__all__ = [ + "CopilotClientLeaseProvider", + "CopilotClientRegistry", + "CopilotDeviceAuthManager", + "CopilotGeneration", + "CopilotModel", + "CopilotProvider", + "CopilotProviderError", + "CopilotRequest", + "DeviceAuthState", + "DeviceAuthStatus", + "OAuthClientLeaseProvider", + "OAuthTokenStore", + "SharedClientLeaseProvider", + "TokenCipher", + "create_device_client", + "openai_sse_stream", + "parse_copilot_request", + "resolve_copilot_cli_path", +] diff --git a/backend/openui/copilot/device_auth.py b/backend/openui/copilot/device_auth.py new file mode 100644 index 00000000..7b1578bf --- /dev/null +++ b/backend/openui/copilot/device_auth.py @@ -0,0 +1,423 @@ +"""Bounded device-flow coordinator for GitHub Copilot CLI login.""" + +from __future__ import annotations + +import asyncio +import logging +import re +import subprocess +from dataclasses import dataclass +from datetime import datetime +from enum import Enum +from typing import Any + +from copilot._cli_download import get_cached_cli_path + +from openui.copilot.registry import sanitized_copilot_environment + + +logger = logging.getLogger(__name__) + +_MAX_OUTPUT_BYTES = 65_536 + +DEVICE_LINE = re.compile( + r"https://github\.com/login/device\b.*?\b" + r"(?P[A-Z0-9]{4}-[A-Z0-9]{4})\b", + re.DOTALL, +) + +_PLAINTEXT_STORAGE_MARKER = "Save credentials in plaintext" + + +class DeviceAuthState(str, Enum): + UNAUTHENTICATED = "unauthenticated" + STARTING = "starting" + PENDING = "pending" + AUTHENTICATED = "authenticated" + EXPIRED = "expired" + CANCELLED = "cancelled" + ERROR = "error" + UNSUPPORTED_STORAGE = "unsupported_storage" + + +@dataclass(frozen=True) +class DeviceAuthStatus: + state: DeviceAuthState + message: str | None = None + verification_uri: str | None = None + user_code: str | None = None + expires_at: datetime | None = None + + def to_api(self) -> dict[str, object | None]: + return { + "state": self.state.value, + "message": self.message, + "verification_uri": self.verification_uri, + "user_code": self.user_code, + "expires_at": ( + self.expires_at.isoformat() if self.expires_at else None + ), + } + + +def resolve_copilot_cli_path() -> str: + """Return the SDK-cached CLI executable path or raise a fixed error.""" + path = get_cached_cli_path() + if path is None: + raise RuntimeError( + "The local GitHub Copilot runtime is unavailable." + ) + return path + + +def _build_login_env() -> dict[str, str]: + """Build the sanitized environment for the login subprocess. + + ``sanitized_copilot_environment`` already applies the allowlist (which omits + ``COPILOT_DISABLE_KEYTAR`` so the secure credential store is used), sets + ``COPILOT_HOME``, and forces plugin isolation, so login and runtime clients + share the same minimal environment. + """ + return sanitized_copilot_environment() + + +class CopilotDeviceAuthManager: + """One-at-a-time device auth flow with bounded subprocess coordination.""" + + def __init__( + self, + cli_path: str, + process_factory: Any = None, + leases: Any = None, + timeout_seconds: float = 900, + start_response_timeout: float = 30, + ): + self._cli_path = cli_path + self._process_factory = process_factory or self._default_process_factory + self._leases = leases + self._timeout_seconds = timeout_seconds + self._start_response_timeout = start_response_timeout + self._lock = asyncio.Lock() + self._status = DeviceAuthStatus(state=DeviceAuthState.UNAUTHENTICATED) + self._attempt_task: asyncio.Task[None] | None = None + self._process: Any = None + self._code_event = asyncio.Event() + self._start_result: DeviceAuthStatus | None = None + self._closed = False + self._reader_tasks: list[asyncio.Task[None]] = [] + + @staticmethod + async def _default_process_factory(*args, **kwargs): + return await asyncio.create_subprocess_exec(*args, **kwargs) + + async def initialize(self) -> DeviceAuthStatus: + """Check existing auth status without starting a login process.""" + try: + await self._leases.refresh() + resp = await self._leases.auth_status() + if resp is not None and resp.isAuthenticated: + self._status = DeviceAuthStatus( + state=DeviceAuthState.AUTHENTICATED, + message="Already authenticated.", + ) + else: + self._status = DeviceAuthStatus( + state=DeviceAuthState.UNAUTHENTICATED, + message="No stored identity.", + ) + except Exception: + logger.warning("Device auth initialization failed") + self._status = DeviceAuthStatus( + state=DeviceAuthState.ERROR, + message="Failed to check authentication status.", + ) + return self._status + + def status(self) -> DeviceAuthStatus: + """Return the current public status (immutable snapshot).""" + return self._status + + async def start(self) -> DeviceAuthStatus: + """Start a device login flow. Idempotent if one is already running. + + Returns as soon as the device code is available or a terminal state is + reached. If the code is not ready within the bounded start-response + wait, returns the non-terminal ``STARTING`` state (never the stale + pre-attempt state) so the caller keeps polling. + """ + async with self._lock: + if self._closed: + return DeviceAuthStatus( + state=DeviceAuthState.ERROR, + message="Manager is closed.", + ) + # Idempotent: join the current attempt if one is already running. + if ( + self._attempt_task is not None + and not self._attempt_task.done() + ): + # Join the in-flight attempt; its status/_start_result already + # reflects STARTING or the latest code/terminal state. + pass + else: + # Launch a fresh attempt. Reset any stale result and set the + # STARTING state atomically *before* the attempt starts so a + # slow subprocess can never surface the previous state. + self._code_event.clear() + self._start_result = None + self._status = DeviceAuthStatus( + state=DeviceAuthState.STARTING, + message="Starting GitHub sign-in...", + ) + self._attempt_task = asyncio.create_task(self._run_attempt()) + + # Wait for the device code or a terminal state, bounded so a slow login + # cannot block the request. On timeout the current (STARTING) status is + # returned rather than any stale pre-attempt state. + try: + await asyncio.wait_for( + self._code_event.wait(), timeout=self._start_response_timeout + ) + except TimeoutError: + pass + # Return the snapshot captured when the code was found (or a terminal + # state); otherwise the STARTING status set above. + return self._start_result if self._start_result is not None else self._status + + async def _run_attempt(self) -> None: + """Execute the subprocess and monitor completion with incremental parsing.""" + process = None + stdout_task: asyncio.Task[None] | None = None + stderr_task: asyncio.Task[None] | None = None + try: + async with asyncio.timeout(self._timeout_seconds): + env = _build_login_env() + process = await self._process_factory( + self._cli_path, + "login", + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + env=env, + ) + self._process = process + + # Shared mutable state for incremental reading + stdout_buf = bytearray() + stderr_buf = bytearray() + total_bytes = 0 + overflow = False + + async def _read_stream( + stream: Any, buf: bytearray, is_stdout: bool + ) -> None: + nonlocal total_bytes, overflow + while True: + chunk = await stream.read(4096) + if not chunk: + return + total_bytes += len(chunk) + if total_bytes > _MAX_OUTPUT_BYTES: + overflow = True + return + buf.extend(chunk) + # Incremental parse on stdout chunks + if is_stdout and not self._code_event.is_set(): + text = buf.decode("utf-8", errors="replace") + match = DEVICE_LINE.search(text) + if match: + user_code = match.group("code") + self._status = DeviceAuthStatus( + state=DeviceAuthState.PENDING, + message="Enter the code on GitHub.", + verification_uri="https://github.com/login/device", + user_code=user_code, + ) + self._start_result = self._status + self._code_event.set() + + # Run readers as background tasks + stdout_task = asyncio.create_task( + _read_stream(process.stdout, stdout_buf, True) + ) + stderr_task = asyncio.create_task( + _read_stream(process.stderr, stderr_buf, False) + ) + self._reader_tasks = [stdout_task, stderr_task] + + # Wait for all streams to close AND process to exit. + # Streams close when process exits, so gather handles both. + # But first: if overflow, cancel peer and bail. + all_tasks = [stdout_task, stderr_task] + while all_tasks: + done, pending_set = await asyncio.wait( + all_tasks, return_when=asyncio.FIRST_COMPLETED + ) + all_tasks = list(pending_set) + if overflow: + for t in all_tasks: + t.cancel() + for t in all_tasks: + try: + await t + except (asyncio.CancelledError, Exception): + pass + all_tasks = [] + break + + if overflow: + self._status = DeviceAuthStatus( + state=DeviceAuthState.ERROR, + message="Login output exceeded safe limits.", + ) + self._start_result = self._status + self._code_event.set() + await self._cleanup_process(process) + return + + # Streams are closed. Check stderr for plaintext marker. + stderr_text = stderr_buf.decode("utf-8", errors="replace") + if _PLAINTEXT_STORAGE_MARKER in stderr_text: + self._status = DeviceAuthStatus( + state=DeviceAuthState.UNSUPPORTED_STORAGE, + message="Secure credential storage is not available.", + ) + self._start_result = self._status + self._code_event.set() + await self._cleanup_process(process) + return + + # Final parse attempt if code not yet found + if not self._code_event.is_set(): + combined_text = stdout_buf.decode("utf-8", errors="replace") + match = DEVICE_LINE.search(combined_text) + if match: + user_code = match.group("code") + self._status = DeviceAuthStatus( + state=DeviceAuthState.PENDING, + message="Enter the code on GitHub.", + verification_uri="https://github.com/login/device", + user_code=user_code, + ) + self._start_result = self._status + self._code_event.set() + + # Wait for process to exit + await process.wait() + + if not self._code_event.is_set(): + self._status = DeviceAuthStatus( + state=DeviceAuthState.ERROR, + message="Failed to parse device code from login output.", + ) + self._start_result = self._status + self._code_event.set() + return + + # Process exited — verify authentication + if process.returncode == 0: + await self._leases.refresh() + resp = await self._leases.auth_status() + if resp is not None and resp.isAuthenticated: + self._status = DeviceAuthStatus( + state=DeviceAuthState.AUTHENTICATED, + message="Successfully authenticated.", + ) + else: + self._status = DeviceAuthStatus( + state=DeviceAuthState.ERROR, + message="Login completed but authentication could not be verified.", + ) + else: + if self._status.state == DeviceAuthState.PENDING: + self._status = DeviceAuthStatus( + state=DeviceAuthState.ERROR, + message="Login process exited with an error.", + ) + + except TimeoutError: + self._status = DeviceAuthStatus( + state=DeviceAuthState.EXPIRED, + message="Login attempt timed out.", + ) + self._start_result = self._status + self._code_event.set() + await self._drain_reader_tasks(stdout_task, stderr_task) + if process is not None: + await self._cleanup_process(process) + except asyncio.CancelledError: + await self._drain_reader_tasks(stdout_task, stderr_task) + if process is not None: + await self._cleanup_process(process) + raise + except Exception: + logger.warning("Device auth attempt failed") + self._status = DeviceAuthStatus( + state=DeviceAuthState.ERROR, + message="An unexpected error occurred during login.", + ) + self._start_result = self._status + self._code_event.set() + await self._drain_reader_tasks(stdout_task, stderr_task) + if process is not None: + await self._cleanup_process(process) + finally: + self._process = None + self._code_event.set() + + async def _drain_reader_tasks(self, *tasks: asyncio.Task[None] | None) -> None: + """Cancel any unfinished reader task, then await all to retrieve results. + + Awaiting with ``return_exceptions=True`` guarantees every reader task's + result (or exception) is consumed, so no "Task exception was never + retrieved" warning can escape on timeout or cancellation. + """ + live = [t for t in tasks if t is not None] + for t in live: + if not t.done(): + t.cancel() + if live: + await asyncio.gather(*live, return_exceptions=True) + + async def _cleanup_process(self, process: Any) -> None: + """Terminate → wait → kill if needed. Never log raw output.""" + if process.returncode is None: + process.terminate() + try: + await asyncio.wait_for(process.wait(), timeout=2) + except TimeoutError: + process.kill() + await process.wait() + + async def cancel(self) -> None: + """Cancel the current flow if any.""" + async with self._lock: + if self._closed: + return + task = self._attempt_task + if task is not None and not task.done(): + task.cancel() + try: + await task + except (asyncio.CancelledError, Exception): + pass + self._attempt_task = None + self._status = DeviceAuthStatus( + state=DeviceAuthState.CANCELLED, + message="Login was cancelled.", + ) + + async def close(self) -> None: + """Clean up all resources. Idempotent.""" + async with self._lock: + if self._closed: + return + self._closed = True + task = self._attempt_task + if task is not None and not task.done(): + task.cancel() + try: + await task + except (asyncio.CancelledError, Exception): + pass + self._attempt_task = None diff --git a/backend/openui/copilot/errors.py b/backend/openui/copilot/errors.py new file mode 100644 index 00000000..cd4d8a62 --- /dev/null +++ b/backend/openui/copilot/errors.py @@ -0,0 +1,130 @@ +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any + + +@dataclass +class CopilotProviderError(Exception): + status_code: int + code: str + detail: str + correlation_id: str | None = None + + def __str__(self) -> str: + return self.detail + + def to_payload(self) -> dict[str, str]: + payload = { + "message": self.detail, + "type": "copilot_error", + "code": self.code, + } + if self.correlation_id is not None: + payload["correlation_id"] = self.correlation_id + return payload + + +def _known_error(status_code: int) -> CopilotProviderError | None: + errors = { + 400: ( + "copilot_invalid_request", + "The selected Copilot model or input is not supported.", + ), + 401: ( + "copilot_authentication_required", + "Reconnect your GitHub account.", + ), + 403: ( + "copilot_entitlement_required", + "This GitHub account does not have Copilot access.", + ), + 429: ( + "copilot_rate_limit", + "Your GitHub Copilot allowance or rate limit has been reached.", + ), + } + value = errors.get(status_code) + if value is None: + return None + code, detail = value + return CopilotProviderError(status_code, code, detail) + + +def _require_known(status_code: int) -> CopilotProviderError: + error = _known_error(status_code) + if error is None: + raise AssertionError(f"No safe Copilot error is defined for {status_code}") + return error + + +def map_sdk_status( + status_code: int | None, + *, + correlation_id: str, + error_code: str | None = None, +) -> CopilotProviderError: + if status_code is not None: + known = _known_error(status_code) + if known is not None: + return known + + normalized = (error_code or "").lower() + if any(value in normalized for value in ("auth", "unauthorized", "token")): + return _require_known(401) + if any( + value in normalized + for value in ("entitlement", "subscription", "forbidden", "not_enabled") + ): + return _require_known(403) + if any(value in normalized for value in ("rate", "quota", "allowance")): + return _require_known(429) + if any( + value in normalized + for value in ("bad_request", "model_not_found", "unsupported") + ): + return _require_known(400) + + return CopilotProviderError( + 502, + "copilot_upstream_error", + "GitHub Copilot could not complete the request.", + correlation_id, + ) + + +def map_sdk_event(data: Any, *, correlation_id: str) -> CopilotProviderError: + return map_sdk_status( + getattr(data, "status_code", None), + correlation_id=correlation_id, + error_code=( + getattr(data, "error_code", None) or getattr(data, "error_type", None) + ), + ) + + +def map_sdk_exception( + exc: Exception, + *, + correlation_id: str, + runtime_phase: bool = False, +) -> CopilotProviderError: + status_code = getattr(exc, "status_code", None) + if isinstance(status_code, int): + known = _known_error(status_code) + if known is not None: + return known + if runtime_phase: + return CopilotProviderError( + 503, + "copilot_runtime_unavailable", + "The local GitHub Copilot runtime is unavailable.", + correlation_id, + ) + return map_sdk_status( + status_code if isinstance(status_code, int) else None, + correlation_id=correlation_id, + error_code=( + getattr(exc, "error_code", None) or getattr(exc, "error_type", None) + ), + ) diff --git a/backend/openui/copilot/leases.py b/backend/openui/copilot/leases.py new file mode 100644 index 00000000..ceff2d68 --- /dev/null +++ b/backend/openui/copilot/leases.py @@ -0,0 +1,219 @@ +from __future__ import annotations + +import asyncio +import logging +from collections.abc import AsyncIterator +from contextlib import AbstractAsyncContextManager, asynccontextmanager +from dataclasses import dataclass +from typing import Any, Callable, Protocol + +from .errors import CopilotProviderError +from .registry import CopilotClientProtocol, CopilotClientRegistry +from .token_store import OAuthTokenStore, TokenDecryptionError + + +logger = logging.getLogger(__name__) + +# Synthetic user id used only by the shared pool's own auth probe so it can +# start/reuse the single shared client through the normal lease path. +_AUTH_PROBE_USER = "__auth_probe__" + + +@dataclass(frozen=True) +class _SafeAuthStatus: + """Fixed, safe auth result returned when a probe cannot be completed. + + Never authenticated, and carries no exception detail. Shaped like the SDK's + ``GetAuthStatusResponse`` so callers can read ``isAuthenticated`` uniformly. + """ + + isAuthenticated: bool = False + + +_SAFE_AUTH_STATUS = _SafeAuthStatus() + + +class CopilotClientLeaseProvider(Protocol): + def lease( + self, user_id: str + ) -> AbstractAsyncContextManager[CopilotClientProtocol]: + ... + + +class OAuthClientLeaseProvider: + def __init__(self, token_store: OAuthTokenStore, registry: CopilotClientRegistry): + self._token_store = token_store + self._registry = registry + + @asynccontextmanager + async def lease(self, user_id: str) -> AsyncIterator[CopilotClientProtocol]: + try: + token = self._token_store.get(user_id) + except TokenDecryptionError as exc: + raise CopilotProviderError( + 401, + "copilot_authentication_required", + "Reconnect your GitHub account.", + ) from exc + if token is None: + raise CopilotProviderError( + 401, + "copilot_authentication_required", + "Reconnect your GitHub account.", + ) + async with self._registry.lease(user_id, token) as client: + yield client + + +@dataclass +class _PoolEntry: + client: Any + active_leases: int + retired: bool = False + stopped: bool = False + + +class SharedClientLeaseProvider: + """A single shared Copilot client for device (logged-in-user) auth. + + One global asyncio.Lock serialises all state mutations and client startup. + This is safe because: (a) there is exactly one shared client — serialising + startup is desirable, not costly; (b) the lock is async so other coroutines + run freely while awaiting ``client.start()``. + + Generation-based refresh: ``refresh()`` bumps ``_generation`` and marks the + live entry as retired. If active leases exist the entry moves to + ``_retired_entries`` and is stopped when the final lease releases; otherwise + it is stopped immediately. New leases after a refresh start a fresh client. + + Exactly-once stop: ``entry.stopped`` is set under the lock before any + ``stop()`` call, so neither a second ``close()`` nor a lagging ``_release`` + can issue a duplicate stop. + + Startup serialization: ``_acquire`` holds the async lock across + ``client.start()``. Because ``refresh()``/``close()`` also need that lock, + the generation cannot change while a start is in flight, so a freshly + started client is always the live generation — no post-start race handling + is required. + """ + + def __init__(self, factory: Callable[[], CopilotClientProtocol]): + self._factory = factory + self._lock = asyncio.Lock() + self._entry: _PoolEntry | None = None + self._retired_entries: dict[int, _PoolEntry] = {} + self._generation = 0 + self._closed = False + + @asynccontextmanager + async def lease(self, user_id: str) -> AsyncIterator[CopilotClientProtocol]: + entry = await self._acquire() + try: + yield entry.client + finally: + await self._release(entry) + + async def _acquire(self) -> _PoolEntry: + async with self._lock: + if self._closed: + raise RuntimeError("SharedClientLeaseProvider is closed") + if self._entry is not None and not self._entry.retired: + self._entry.active_leases += 1 + return self._entry + + # No live entry: start a new client while still holding the lock. + # Holding the async lock across ``start()`` serialises concurrent + # startups (correct — we want exactly one shared client) without + # blocking unrelated code, and prevents ``refresh()``/``close()`` + # from running until we finish, so the started client is always the + # current generation. + client = self._factory() + try: + await client.start() + except BaseException: + await self._stop_client(client) + raise + + entry = _PoolEntry(client=client, active_leases=1) + self._entry = entry + return entry + + async def _release(self, entry: _PoolEntry) -> None: + client_to_stop: Any = None + async with self._lock: + entry.active_leases -= 1 + if entry.active_leases == 0 and entry.retired and not entry.stopped: + self._retired_entries.pop(id(entry), None) + entry.stopped = True + client_to_stop = entry.client + if client_to_stop is not None: + await self._stop_client(client_to_stop) + + async def refresh(self) -> None: + """Retire the current client. + + If leases are active the old client keeps running until the last one + is released; otherwise it is stopped immediately. The next ``lease()`` + call will start a fresh client. + """ + client_to_stop: Any = None + async with self._lock: + self._generation += 1 + entry = self._entry + if entry is not None and not entry.retired: + self._entry = None + entry.retired = True + if entry.active_leases == 0 and not entry.stopped: + entry.stopped = True + client_to_stop = entry.client + elif entry.active_leases > 0: + self._retired_entries[id(entry)] = entry + if client_to_stop is not None: + await self._stop_client(client_to_stop) + + async def auth_status(self) -> Any: + """Probe authentication by starting or reusing the shared client. + + Uses the normal lease path so a fresh pool — or one just retired by + ``refresh()`` — starts a client, queries the SDK's ``get_auth_status``, + then releases the lease (leaving the client warm for reuse). Any + failure yields a fixed safe (unauthenticated) status without leaking + exception detail. Cancellation propagates and the lease is released. + """ + try: + async with self.lease(_AUTH_PROBE_USER) as client: + return await client.get_auth_status() + except asyncio.CancelledError: + raise + except Exception: + logger.warning("Copilot shared pool auth probe failed") + return _SAFE_AUTH_STATUS + + async def close(self) -> None: + """Stop all clients exactly once and prevent new leases.""" + async with self._lock: + if self._closed: + return + self._closed = True + self._generation += 1 + entries: list[_PoolEntry] = [] + if self._entry is not None: + entries.append(self._entry) + entries.extend(self._retired_entries.values()) + self._entry = None + self._retired_entries.clear() + clients_to_stop = [] + for entry in entries: + entry.retired = True + if not entry.stopped: + entry.stopped = True + clients_to_stop.append(entry.client) + for client in clients_to_stop: + await self._stop_client(client) + + @staticmethod + async def _stop_client(client: Any) -> None: + try: + await client.stop() + except Exception: + logger.warning("Copilot shared pool client stop failed") diff --git a/backend/openui/copilot/messages.py b/backend/openui/copilot/messages.py new file mode 100644 index 00000000..08631ebf --- /dev/null +++ b/backend/openui/copilot/messages.py @@ -0,0 +1,338 @@ +from __future__ import annotations + +import base64 +import binascii +import re +from dataclasses import dataclass + +from copilot import ModelInfo +from copilot.session import BlobAttachment + +from .errors import CopilotProviderError + + +DATA_URL = re.compile( + r"^data:(?Pimage/[a-zA-Z0-9.+-]+);base64,(?P.+)$", + re.DOTALL, +) +DISPLAY_EXTENSIONS = { + "image/png": "png", + "image/jpeg": "jpg", + "image/gif": "gif", + "image/webp": "webp", +} + +# SDK 1.0.6 declares ModelVisionLimits, and each of its individual fields, +# as Optional (defaulting to None). A vision-capable model that omits some +# or all of them must not be treated as unrestricted (unlimited image +# count/size, any MIME type). These fallbacks are used only when +# supports.vision is True and the corresponding SDK field is missing; +# SDK-provided non-None values are always preserved exactly. +DEFAULT_VISION_MEDIA_TYPES: tuple[str, ...] = ( + "image/png", + "image/jpeg", + "image/gif", + "image/webp", +) # matches DISPLAY_EXTENSIONS above +DEFAULT_MAX_PROMPT_IMAGES = 1 # matches OpenUI's single-screenshot request flow +DEFAULT_MAX_PROMPT_IMAGE_SIZE = 10 * 1024 * 1024 # 10 MiB decoded bytes + + +def _invalid(code: str, detail: str) -> CopilotProviderError: + return CopilotProviderError(400, code, detail) + + +def _max_encoded_length(max_bytes: int) -> int: + """Maximum canonical base64 character length that can decode to at + most ``max_bytes`` bytes (4 chars per 3-byte block, rounded up). + + This is a necessary but not sufficient bound: encoded lengths at or + below this value can still decode to fewer bytes than the maximum + depending on padding, so the exact decoded-length check must still + run after decoding. Uses integer-only arithmetic (equivalent to + ``4 * ceil(max_bytes / 3)``) to avoid float precision/overflow + behavior for arbitrarily large SDK-provided integers. + """ + return 4 * ((max_bytes + 2) // 3) + + +@dataclass(frozen=True) +class CopilotModel: + id: str + name: str + supports_vision: bool + supported_media_types: tuple[str, ...] + max_prompt_images: int | None + max_prompt_image_size: int | None + + @classmethod + def from_sdk(cls, info: ModelInfo) -> "CopilotModel": + supports_vision = info.capabilities.supports.vision + if not supports_vision: + return cls( + id=info.id, + name=info.name, + supports_vision=False, + supported_media_types=(), + max_prompt_images=None, + max_prompt_image_size=None, + ) + + vision = info.capabilities.limits.vision + sdk_media_types = vision.supported_media_types if vision is not None else None + sdk_max_images = vision.max_prompt_images if vision is not None else None + sdk_max_image_size = ( + vision.max_prompt_image_size if vision is not None else None + ) + + return cls( + id=info.id, + name=info.name, + supports_vision=True, + supported_media_types=( + tuple(media_type.lower() for media_type in sdk_media_types) + if sdk_media_types is not None + else DEFAULT_VISION_MEDIA_TYPES + ), + max_prompt_images=( + sdk_max_images + if sdk_max_images is not None + else DEFAULT_MAX_PROMPT_IMAGES + ), + max_prompt_image_size=( + sdk_max_image_size + if sdk_max_image_size is not None + else DEFAULT_MAX_PROMPT_IMAGE_SIZE + ), + ) + + def to_api(self) -> dict[str, object]: + return { + "id": f"copilot/{self.id}", + "name": self.name, + "capabilities": { + "vision": self.supports_vision, + "supported_media_types": list(self.supported_media_types), + "max_prompt_images": self.max_prompt_images, + "max_prompt_image_size": self.max_prompt_image_size, + }, + } + + +@dataclass(frozen=True) +class CopilotRequest: + model_id: str + system_prompt: str + user_prompt: str + attachments: list[BlobAttachment] + + +def _string_content(value: object, *, role: str) -> str: + if not isinstance(value, str): + raise _invalid( + "copilot_invalid_messages", + f"OpenUI requires string content for the {role} message.", + ) + return value.strip() + + +def _decode_image( + url: object, + *, + model: CopilotModel, + index: int, +) -> BlobAttachment: + if not isinstance(url, str): + raise _invalid( + "copilot_invalid_image", + "The screenshot must be an inline image data URL.", + ) + match = DATA_URL.fullmatch(url) + if match is None: + raise _invalid( + "copilot_invalid_image", + "Remote image URLs are not accepted; upload the screenshot directly.", + ) + mime_type = match.group("mime").lower() + # By this point the caller has already rejected images for non-vision + # models, so `model.supports_vision` is True here. That means + # `supported_media_types` is never an "omitted" placeholder — it is + # either the SDK's explicit allowlist (which may legitimately be an + # empty tuple, meaning "no MIME type is supported"; fail closed) or + # the non-empty fallback applied in `CopilotModel.from_sdk` when the + # SDK omitted the field entirely. Do not special-case emptiness here. + if mime_type not in model.supported_media_types: + raise _invalid( + "copilot_image_type_unsupported", + f"The selected Copilot model does not accept {mime_type} images.", + ) + raw_data = match.group("data") + if ( + model.max_prompt_image_size is not None + and len(raw_data) > _max_encoded_length(model.max_prompt_image_size) + ): + # Reject grossly oversized encoded payloads before ever calling + # base64.b64decode, so attacker-controlled data can't force + # avoidable memory/CPU work. This bound is necessary but not + # sufficient; the exact decoded-length check below still applies. + raise _invalid( + "copilot_image_too_large", + "The screenshot exceeds the selected Copilot model's image limit.", + ) + try: + decoded = base64.b64decode(raw_data, validate=True) + except (ValueError, binascii.Error) as exc: + raise _invalid( + "copilot_invalid_image", + "The screenshot data URL contains invalid base64 data.", + ) from exc + if base64.b64encode(decoded).decode("ascii") != raw_data: + # base64.b64decode(..., validate=True) only checks that characters + # come from the base64 alphabet; it does not reject non-canonical + # padding where unused bits in the final block are non-zero (e.g. + # "ZB==" decodes to the same byte as canonical "ZA=="). Comparing + # the round-tripped re-encoding catches these aliases. + raise _invalid( + "copilot_invalid_image", + "The screenshot data URL contains invalid base64 data.", + ) + if not decoded: + raise _invalid( + "copilot_invalid_image", + "The screenshot is empty.", + ) + if ( + model.max_prompt_image_size is not None + and len(decoded) > model.max_prompt_image_size + ): + raise _invalid( + "copilot_image_too_large", + "The screenshot exceeds the selected Copilot model's image limit.", + ) + encoded = raw_data + extension = DISPLAY_EXTENSIONS.get(mime_type, "img") + return { + "type": "blob", + "data": encoded, + "mimeType": mime_type, + "displayName": f"screenshot-{index + 1}.{extension}", + } + + +def parse_copilot_request( + data: dict[str, object], + model: CopilotModel, +) -> CopilotRequest: + if data.get("model") != f"copilot/{model.id}": + raise _invalid( + "copilot_model_unavailable", + "Refresh the model list and choose an available Copilot model.", + ) + messages = data.get("messages") + if not isinstance(messages, list) or not messages: + raise _invalid( + "copilot_invalid_messages", + "At least one OpenUI message is required.", + ) + + system_parts: list[str] = [] + user_parts: list[str] = [] + attachments: list[BlobAttachment] = [] + + for message in messages: + if not isinstance(message, dict): + raise _invalid( + "copilot_invalid_messages", + "Every OpenUI message must be an object.", + ) + role = message.get("role") + content = message.get("content") + if role == "system": + value = _string_content(content, role="system") + if value: + system_parts.append(value) + continue + if role != "user": + raise _invalid( + "copilot_invalid_messages", + "Copilot generation accepts only system and user messages.", + ) + if isinstance(content, str): + value = content.strip() + if value: + user_parts.append(value) + continue + if not isinstance(content, list): + raise _invalid( + "copilot_invalid_messages", + "The user message must contain text or an uploaded screenshot.", + ) + for part in content: + if not isinstance(part, dict): + raise _invalid( + "copilot_invalid_messages", + "Every user-content part must be an object.", + ) + part_type = part.get("type") + if part_type == "text": + text = part.get("text") + if not isinstance(text, str): + raise _invalid( + "copilot_invalid_messages", + "Text content must be a string.", + ) + if text.strip(): + user_parts.append(text.strip()) + elif part_type == "image_url": + # Validate cheap constraints (vision support, image count) before + # decoding attacker-controlled base64 data, so rejected requests + # never pay the cost of decoding oversized/excess payloads. + if not model.supports_vision: + raise _invalid( + "copilot_vision_unsupported", + "Choose a vision-capable Copilot model to use a screenshot.", + ) + if ( + model.max_prompt_images is not None + and len(attachments) >= model.max_prompt_images + ): + raise _invalid( + "copilot_too_many_images", + "Too many screenshots were supplied for the selected " + "Copilot model.", + ) + image_url = part.get("image_url") + if not isinstance(image_url, dict): + raise _invalid( + "copilot_invalid_image", + "The screenshot must use OpenAI image_url object syntax.", + ) + attachments.append( + _decode_image( + image_url.get("url"), + model=model, + index=len(attachments), + ) + ) + else: + raise _invalid( + "copilot_invalid_messages", + f"Unsupported user-content type: {part_type!r}.", + ) + + if not user_parts and not attachments: + raise _invalid( + "copilot_empty_request", + "Enter a prompt or upload a screenshot.", + ) + + return CopilotRequest( + model_id=model.id, + system_prompt="\n\n".join(system_parts), + user_prompt=( + "\n\n".join(user_parts) + if user_parts + else "Generate HTML matching the attached screenshot." + ), + attachments=attachments, + ) diff --git a/backend/openui/copilot/provider.py b/backend/openui/copilot/provider.py new file mode 100644 index 00000000..2ce141c6 --- /dev/null +++ b/backend/openui/copilot/provider.py @@ -0,0 +1,333 @@ +from __future__ import annotations + +import asyncio +import logging +import uuid +from collections.abc import AsyncIterator, Awaitable, Callable +from contextlib import AbstractAsyncContextManager +from typing import Any + +from copilot.rpc import PermissionDecisionReject +from copilot.session_events import ( + AssistantMessageData, + AssistantMessageDeltaData, + ModelCallFailureData, + SessionErrorData, + SessionIdleData, +) + +from .errors import ( + CopilotProviderError, + map_sdk_event, + map_sdk_exception, +) +from .messages import CopilotModel, CopilotRequest, parse_copilot_request + + +logger = logging.getLogger(__name__) + + +async def release_lease( + lease: AbstractAsyncContextManager[Any], + *, + correlation_id: str, +) -> None: + try: + await lease.__aexit__(None, None, None) + except Exception: + logger.warning( + "Copilot client lease release failed correlation_id=%s", + correlation_id, + ) + + +def reject_permission(request, invocation): + return PermissionDecisionReject( + feedback="OpenUI Copilot sessions do not allow tool execution" + ) + + +class CopilotGeneration: + def __init__( + self, + *, + client: Any, + session: Any, + request: CopilotRequest, + lease: AbstractAsyncContextManager[Any], + response_timeout_seconds: float, + disconnect_poll_seconds: float, + correlation_id: str, + ): + self.model_id = request.model_id + self._client = client + self._session = session + self._request = request + self._lease = lease + self._response_timeout_seconds = response_timeout_seconds + self._disconnect_poll_seconds = disconnect_poll_seconds + self._correlation_id = correlation_id + self._closed = False + self.disconnected = False + + async def _cleanup(self, *, abort: bool) -> None: + if self._closed: + return + self._closed = True + try: + if abort: + try: + await self._session.abort() + except Exception: + logger.warning( + "Copilot abort failed correlation_id=%s", + self._correlation_id, + ) + try: + await self._session.disconnect() + except Exception: + logger.warning( + "Copilot session disconnect failed correlation_id=%s", + self._correlation_id, + ) + try: + await self._client.delete_session(self._session.session_id) + except Exception: + logger.warning( + "Copilot session deletion failed correlation_id=%s", + self._correlation_id, + ) + finally: + # Release the lease even if abort/disconnect/delete raises a + # BaseException (e.g. a second CancelledError delivered while + # awaiting one of them); otherwise a cancelled request could pin + # an active lease. release_lease swallows its own errors, so any + # in-flight cancellation still propagates unchanged. + await release_lease( + self._lease, + correlation_id=self._correlation_id, + ) + + async def text_deltas( + self, + is_disconnected: Callable[[], Awaitable[bool]], + ) -> AsyncIterator[str]: + loop = asyncio.get_running_loop() + queue: asyncio.Queue[tuple[str, object | None]] = asyncio.Queue() + saw_delta = False + completed = False + # Guards against SDK callbacks that fire from another thread after we + # have unsubscribed or the event loop has shut down. It is flipped off + # under the loop thread before unsubscribe and re-read best-effort in + # the callback; a stale True at worst schedules one dropped put. + active = True + + def enqueue(item: tuple[str, object | None]) -> None: + if not active: + return + try: + loop.call_soon_threadsafe(queue.put_nowait, item) + except RuntimeError: + # Event loop already closed during shutdown; drop the late + # event rather than surface a raw runtime error. + pass + + def on_event(event) -> None: + nonlocal saw_delta + data = event.data + if isinstance(data, AssistantMessageDeltaData): + saw_delta = True + enqueue(("delta", data.delta_content)) + elif isinstance(data, AssistantMessageData) and not saw_delta: + enqueue(("delta", data.content)) + elif isinstance(data, (SessionErrorData, ModelCallFailureData)): + enqueue(("error", data)) + elif isinstance(data, SessionIdleData): + enqueue(("done", None)) + + unsubscribe = None + try: + unsubscribe = self._session.on(on_event) + await self._session.send( + self._request.user_prompt, + attachments=self._request.attachments or None, + ) + deadline = loop.time() + self._response_timeout_seconds + while True: + if await is_disconnected(): + self.disconnected = True + return + remaining = deadline - loop.time() + if remaining <= 0: + raise CopilotProviderError( + 502, + "copilot_response_timeout", + "GitHub Copilot did not finish the request in time.", + self._correlation_id, + ) + try: + kind, value = await asyncio.wait_for( + queue.get(), + timeout=min(self._disconnect_poll_seconds, remaining), + ) + except TimeoutError: + continue + if kind == "delta": + if value: + yield str(value) + elif kind == "error": + raise map_sdk_event( + value, + correlation_id=self._correlation_id, + ) + else: + completed = True + return + except asyncio.CancelledError: + raise + except CopilotProviderError: + raise + except Exception as exc: + raise map_sdk_exception( + exc, + correlation_id=self._correlation_id, + ) from exc + finally: + active = False + if unsubscribe is not None: + try: + unsubscribe() + except Exception: + logger.warning( + "Copilot event unsubscribe failed correlation_id=%s", + self._correlation_id, + ) + await self._cleanup(abort=not completed) + + +class CopilotProvider: + def __init__( + self, + leases, + *, + response_timeout_seconds: float, + disconnect_poll_seconds: float = 0.25, + ): + self._leases = leases + self._response_timeout_seconds = response_timeout_seconds + self._disconnect_poll_seconds = disconnect_poll_seconds + + async def list_models(self, user_id: str) -> list[CopilotModel]: + correlation_id = uuid.uuid4().hex + try: + async with self._leases.lease(user_id) as client: + models = await client.list_models() + except CopilotProviderError: + raise + except Exception as exc: + raise map_sdk_exception( + exc, + correlation_id=correlation_id, + runtime_phase=True, + ) from exc + return [ + CopilotModel.from_sdk(info) + for info in models + if info.policy is None or info.policy.state != "disabled" + ] + + async def start_generation( + self, + user_id: str, + data: dict[str, object], + ) -> CopilotGeneration: + correlation_id = uuid.uuid4().hex + lease = self._leases.lease(user_id) + try: + client = await lease.__aenter__() + except CopilotProviderError: + raise + except Exception as exc: + raise map_sdk_exception( + exc, + correlation_id=correlation_id, + runtime_phase=True, + ) from exc + + try: + sdk_models = await client.list_models() + models = { + info.id: CopilotModel.from_sdk(info) + for info in sdk_models + if info.policy is None or info.policy.state != "disabled" + } + selected_id = str(data.get("model", "")).removeprefix("copilot/") + model = models.get(selected_id) + if model is None: + raise CopilotProviderError( + 400, + "copilot_model_unavailable", + "Refresh the model list and choose an available Copilot model.", + ) + request = parse_copilot_request(data, model) + system_message: dict[str, object] = { + "mode": "customize", + "sections": {"environment_context": {"action": "remove"}}, + } + if request.system_prompt: + system_message["content"] = request.system_prompt + session = await client.create_session( + session_id=f"openui-{uuid.uuid4().hex}", + model=request.model_id, + on_permission_request=reject_permission, + tools=[], + available_tools=[], + system_message=system_message, + streaming=True, + mcp_servers={}, + mcp_oauth_token_storage="in-memory", + embedding_cache_storage="in-memory", + custom_agents=[], + skill_directories=[], + instruction_directories=[], + enable_config_discovery=False, + enable_on_demand_instruction_discovery=False, + enable_session_telemetry=False, + skip_embedding_retrieval=True, + enable_skills=False, + enable_file_hooks=False, + enable_host_git_operations=False, + enable_session_store=False, + skip_custom_instructions=True, + custom_agents_local_only=True, + coauthor_enabled=False, + manage_schedule_enabled=False, + memory={"enabled": False}, + ) + except CopilotProviderError: + await release_lease(lease, correlation_id=correlation_id) + raise + except asyncio.CancelledError: + # CancelledError is a BaseException and bypasses the ``except + # Exception`` handler below; release the lease deterministically so + # a cancelled request cannot pin an active lease until async- + # generator GC. release_lease swallows its own errors, so the + # original cancellation is always the exception that propagates. + await release_lease(lease, correlation_id=correlation_id) + raise + except Exception as exc: + await release_lease(lease, correlation_id=correlation_id) + raise map_sdk_exception( + exc, + correlation_id=correlation_id, + ) from exc + + return CopilotGeneration( + client=client, + session=session, + request=request, + lease=lease, + response_timeout_seconds=self._response_timeout_seconds, + disconnect_poll_seconds=self._disconnect_poll_seconds, + correlation_id=correlation_id, + ) diff --git a/backend/openui/copilot/registry.py b/backend/openui/copilot/registry.py new file mode 100644 index 00000000..fbc29b60 --- /dev/null +++ b/backend/openui/copilot/registry.py @@ -0,0 +1,385 @@ +from __future__ import annotations + +import asyncio +import hashlib +import logging +import os +import time +from collections.abc import AsyncIterator, Callable +from contextlib import asynccontextmanager, suppress +from dataclasses import dataclass +from pathlib import Path +from typing import Protocol + +from copilot import CopilotClient + +from openui import config + + +logger = logging.getLogger(__name__) + + +class CopilotClientProtocol(Protocol): + async def start(self) -> None: + pass + + async def stop(self) -> None: + pass + + +ClientFactory = Callable[[str, str], CopilotClientProtocol] + +# Explicit cross-platform allowlist of environment variables that every Copilot +# runtime process (device login subprocess, device SDK client, and OAuth +# per-user SDK client) may inherit. Everything else — including application +# secrets (GITHUB_CLIENT_SECRET, OPENUI_TOKEN_ENCRYPTION_KEY, OPENUI_SESSION_KEY, +# provider API keys, AWS keys), arbitrary COPILOT_* auth variables, and +# COPILOT_DISABLE_KEYTAR — is dropped. Only process/runtime essentials remain. +COPILOT_ALLOWED_ENV_KEYS: frozenset[str] = frozenset({ + # Home / per-user application data (needed for the OS keychain probe). + "HOME", + "USERPROFILE", + "APPDATA", + "LOCALAPPDATA", + # Executable lookup and OS roots. + "PATH", + "PATHEXT", + "SYSTEMROOT", + "WINDIR", + # Temp directories. + "TMPDIR", + "TMP", + "TEMP", + # Locale. + "LANG", + "LANGUAGE", + "LC_ALL", + "LC_CTYPE", + # XDG config/runtime dirs used by secure credential storage (libsecret). + "XDG_CONFIG_HOME", + "XDG_DATA_HOME", + "XDG_CACHE_HOME", + "XDG_RUNTIME_DIR", + # D-Bus session address is required for the Linux keychain (libsecret). + "DBUS_SESSION_BUS_ADDRESS", + # Proxy configuration required for GitHub connectivity. + "HTTP_PROXY", + "HTTPS_PROXY", + "NO_PROXY", + "ALL_PROXY", + "http_proxy", + "https_proxy", + "no_proxy", + "all_proxy", + # Certificate authority bundles for TLS to GitHub. + "SSL_CERT_FILE", + "SSL_CERT_DIR", + "REQUESTS_CA_BUNDLE", + "CURL_CA_BUNDLE", + "NODE_EXTRA_CA_CERTS", +}) + + +def sanitized_copilot_environment() -> dict[str, str]: + """Build the minimal environment for every Copilot runtime process. + + Applied to the device login subprocess, the device SDK client, and the + OAuth per-user SDK client. Starts from an explicit allowlist (never a + denylist) so newly introduced secrets can never leak by default, then sets + ``COPILOT_HOME`` (the SDK may subsequently override it with the per-user + ``base_directory``) and forces plugin isolation. + """ + env = { + key: value + for key, value in os.environ.items() + if key in COPILOT_ALLOWED_ENV_KEYS + } + env["COPILOT_HOME"] = str(config.COPILOT_HOME) + # Force the runtime to load only explicitly passed --plugin-dir directories + # (of which there are none), suppressing automatic discovery of ambient + # marketplace-installed plugins. This is the official runtime control; the + # Python SDK omits pluginDirectories when the list is empty, so it cannot be + # relied on to suppress ambient plugins. + env["COPILOT_PLUGIN_DIR_ONLY"] = "true" + return env + + +def create_device_client() -> CopilotClient: + return CopilotClient( + use_logged_in_user=True, + mode="copilot-cli", + env=sanitized_copilot_environment(), + base_directory=str(config.COPILOT_HOME), + session_idle_timeout_seconds=int(config.COPILOT_CLIENT_IDLE_SECONDS), + enable_remote_sessions=False, + ) + + +def create_local_client(user_id: str, token: str) -> CopilotClient: + user_home = Path(config.COPILOT_HOME) / user_id + user_home.mkdir(parents=True, exist_ok=True) + return CopilotClient( + github_token=token, + use_logged_in_user=False, + mode="empty", + env=sanitized_copilot_environment(), + base_directory=str(user_home), + session_idle_timeout_seconds=int(config.COPILOT_CLIENT_IDLE_SECONDS), + ) + + +@dataclass +class _Entry: + user_id: str + token_fingerprint: str + client: CopilotClientProtocol + active_leases: int + last_used: float + retired: bool = False + stopped: bool = False + + +class CopilotClientRegistry: + def __init__( + self, + factory: ClientFactory = create_local_client, + *, + idle_seconds: float, + sweep_seconds: float, + clock: Callable[[], float] = time.monotonic, + ): + self._factory = factory + self._idle_seconds = idle_seconds + self._sweep_seconds = sweep_seconds + self._clock = clock + self._entries: dict[tuple[str, str], _Entry] = {} + self._retired_entries: dict[int, _Entry] = {} + # Global lock guards the maps, flags, and per-user bookkeeping. It is + # never held across ``client.start()``/``client.stop()`` so unrelated + # users never serialize on client I/O. + self._lock = asyncio.Lock() + # Per-user lock serializes startup for a single user so concurrent + # same-user leases start at most one client and rotations stay ordered. + self._user_locks: dict[str, asyncio.Lock] = {} + # Per-user invalidation generation: bumped by invalidate/close so an + # in-flight start that lost the race is cleaned up, never registered. + self._generation: dict[str, int] = {} + self._sweeper: asyncio.Task[None] | None = None + self._closed = False + + @staticmethod + def _fingerprint(token: str) -> str: + return hashlib.sha256(token.encode("utf-8")).hexdigest() + + async def start(self) -> None: + async with self._lock: + if self._closed: + raise RuntimeError("Copilot client registry is closed") + if self._sweeper is None: + self._sweeper = asyncio.create_task(self._sweep_loop()) + + @staticmethod + async def _stop_client(client: CopilotClientProtocol) -> None: + try: + await client.stop() + except Exception: + logger.warning("Copilot client stop failed") + + def _retire_other_user_entries( + self, + user_id: str, + keep_key: tuple[str, str], + clients_to_stop: list[CopilotClientProtocol], + ) -> None: + """Retire every other token entry for ``user_id`` (token rotation). + + Must run under ``self._lock``. Inactive retired clients are queued for a + one-time stop; active ones move to ``_retired_entries`` and stop when + their final lease releases. + """ + for other_key, other in list(self._entries.items()): + if other.user_id == user_id and other_key != keep_key: + self._entries.pop(other_key) + other.retired = True + if other.active_leases == 0: + other.stopped = True + clients_to_stop.append(other.client) + else: + self._retired_entries[id(other)] = other + + async def _acquire( + self, + user_id: str, + token: str, + key: tuple[str, str], + fingerprint: str, + ) -> tuple[_Entry, list[CopilotClientProtocol]]: + clients_to_stop: list[CopilotClientProtocol] = [] + + # Fast path: reuse an existing client without touching the user lock. + async with self._lock: + if self._closed: + raise RuntimeError("Copilot client registry is closed") + entry = self._entries.get(key) + if entry is not None: + entry.active_leases += 1 + self._retire_other_user_entries(user_id, key, clients_to_stop) + return entry, clients_to_stop + user_lock = self._user_locks.get(user_id) + if user_lock is None: + user_lock = asyncio.Lock() + self._user_locks[user_id] = user_lock + + # Slow path: create+start a client. The per-user lock serializes same + # user startups (dedup + ordered rotation); the global lock is released + # around ``start()`` so unrelated users start concurrently. + async with user_lock: + async with self._lock: + if self._closed: + raise RuntimeError("Copilot client registry is closed") + entry = self._entries.get(key) + if entry is not None: + entry.active_leases += 1 + self._retire_other_user_entries( + user_id, key, clients_to_stop + ) + return entry, clients_to_stop + generation = self._generation.get(user_id, 0) + + client = self._factory(user_id, token) + try: + await client.start() + except BaseException: + await self._stop_client(client) + raise + + closed = False + invalidated = False + async with self._lock: + if self._closed: + closed = True + elif self._generation.get(user_id, 0) != generation: + invalidated = True + else: + entry = _Entry( + user_id=user_id, + token_fingerprint=fingerprint, + client=client, + active_leases=1, + last_used=self._clock(), + ) + self._entries[key] = entry + self._retire_other_user_entries( + user_id, key, clients_to_stop + ) + return entry, clients_to_stop + + # Lost the race to invalidate/close during start: clean up, never yield. + await self._stop_client(client) + if closed: + raise RuntimeError("Copilot client registry is closed") + if invalidated: + raise RuntimeError("Copilot client startup was invalidated") + raise AssertionError("unreachable") # pragma: no cover + + async def _release(self, entry: _Entry, key: tuple[str, str]) -> None: + client_to_stop: CopilotClientProtocol | None = None + async with self._lock: + entry.active_leases -= 1 + if entry.active_leases == 0: + # Idle is measured from the final release, not from checkout. + entry.last_used = self._clock() + if entry.retired and not entry.stopped: + if self._entries.get(key) is entry: + self._entries.pop(key) + self._retired_entries.pop(id(entry), None) + entry.stopped = True + client_to_stop = entry.client + if client_to_stop is not None: + await self._stop_client(client_to_stop) + + @asynccontextmanager + async def lease( + self, + user_id: str, + token: str, + ) -> AsyncIterator[CopilotClientProtocol]: + fingerprint = self._fingerprint(token) + key = (user_id, fingerprint) + + entry, clients_to_stop = await self._acquire( + user_id, token, key, fingerprint + ) + # The lease is held (active_leases incremented) before this point, so + # any cancellation from here on runs the finally and releases it. + try: + for client in clients_to_stop: + await self._stop_client(client) + yield entry.client + finally: + await self._release(entry, key) + + async def invalidate(self, user_id: str) -> None: + clients_to_stop: list[CopilotClientProtocol] = [] + async with self._lock: + self._generation[user_id] = self._generation.get(user_id, 0) + 1 + for key, entry in list(self._entries.items()): + if entry.user_id != user_id: + continue + self._entries.pop(key) + entry.retired = True + if entry.active_leases == 0: + entry.stopped = True + clients_to_stop.append(entry.client) + else: + self._retired_entries[id(entry)] = entry + for client in clients_to_stop: + await self._stop_client(client) + + async def evict_idle(self) -> None: + cutoff = self._clock() - self._idle_seconds + clients_to_stop: list[CopilotClientProtocol] = [] + async with self._lock: + for key, entry in list(self._entries.items()): + if entry.active_leases == 0 and entry.last_used <= cutoff: + self._entries.pop(key) + entry.retired = True + entry.stopped = True + clients_to_stop.append(entry.client) + for client in clients_to_stop: + await self._stop_client(client) + + async def _sweep_loop(self) -> None: + while True: + await asyncio.sleep(self._sweep_seconds) + await self.evict_idle() + + async def close(self) -> None: + sweeper = self._sweeper + self._sweeper = None + if sweeper is not None: + sweeper.cancel() + with suppress(asyncio.CancelledError): + await sweeper + + async with self._lock: + if self._closed: + return + self._closed = True + # Bump every generation so any in-flight start is cleaned up. + for user_id in list(self._generation): + self._generation[user_id] += 1 + entries = [ + *self._entries.values(), + *self._retired_entries.values(), + ] + self._entries.clear() + self._retired_entries.clear() + clients = [] + for entry in entries: + entry.retired = True + if not entry.stopped: + entry.stopped = True + clients.append(entry.client) + for client in clients: + await self._stop_client(client) diff --git a/backend/openui/copilot/sse.py b/backend/openui/copilot/sse.py new file mode 100644 index 00000000..86799dcb --- /dev/null +++ b/backend/openui/copilot/sse.py @@ -0,0 +1,65 @@ +from __future__ import annotations + +import json +import time +import uuid +from collections.abc import AsyncIterator, Awaitable, Callable + +from .errors import CopilotProviderError + + +def text_delta_event( + delta: str, + *, + stream_id: str, + model: str, + created: int, +) -> str: + payload = { + "id": stream_id, + "object": "chat.completion.chunk", + "created": created, + "model": model, + "choices": [ + { + "index": 0, + "delta": {"content": delta}, + "finish_reason": None, + } + ], + } + return f"data: {json.dumps(payload, separators=(',', ':'))}\n\n" + + +def error_event(error: CopilotProviderError) -> str: + return ( + "data: " + + json.dumps({"error": error.to_payload()}, separators=(",", ":")) + + "\n\n" + ) + + +def done_event() -> str: + return "data: [DONE]\n\n" + + +async def openai_sse_stream( + generation, + is_disconnected: Callable[[], Awaitable[bool]], +) -> AsyncIterator[str]: + stream_id = f"chatcmpl-{uuid.uuid4().hex}" + created = int(time.time()) + try: + async for delta in generation.text_deltas(is_disconnected): + yield text_delta_event( + delta, + stream_id=stream_id, + model=f"copilot/{generation.model_id}", + created=created, + ) + except CopilotProviderError as exc: + yield error_event(exc) + return + if generation.disconnected: + return + yield done_event() diff --git a/backend/openui/copilot/token_store.py b/backend/openui/copilot/token_store.py new file mode 100644 index 00000000..88ce153e --- /dev/null +++ b/backend/openui/copilot/token_store.py @@ -0,0 +1,172 @@ +from __future__ import annotations + +import base64 +import binascii +import os +import re +import uuid +from dataclasses import dataclass + +from cryptography.exceptions import InvalidTag +from cryptography.hazmat.primitives.ciphers.aead import AESGCM + +from openui.db.models import User + + +class TokenCipherConfigurationError(ValueError): + pass + + +class TokenDecryptionError(ValueError): + pass + + +class InvalidGitHubUserToken(ValueError): + pass + + +# Strict canonical Base64URL (RFC 4648 section 5) alphabet. Trailing '=' +# padding is accepted (some callers, e.g. ``base64.urlsafe_b64encode``'s +# default output, include it) but must be exactly the amount required for +# the body length -- anything else, including characters outside the +# alphabet, is rejected. +# +# ``base64.urlsafe_b64decode`` silently *discards* characters outside the +# base64 alphabet (per the stdlib's documented non-validating behavior) +# instead of rejecting them, so a naive decode can accept corrupted or +# tampered input and reconstruct unrelated bytes without ever raising. This +# regex plus an exact padding check rejects any such non-canonical input +# before decoding is attempted. +_BASE64URL_RE = re.compile(r"\A(?P[A-Za-z0-9_-]*)(?P={0,2})\Z") + + +def _b64encode(value: bytes) -> str: + return base64.urlsafe_b64encode(value).decode("ascii").rstrip("=") + + +def _b64decode(value: str) -> bytes: + match = _BASE64URL_RE.match(value) + if match is None: + raise binascii.Error("Non-canonical base64url characters") + body = match.group("body") + padding = match.group("padding") + required_padding = "=" * (-len(body) % 4) + if padding and padding != required_padding: + raise binascii.Error("Incorrect base64url padding") + translated = (body + required_padding).translate(str.maketrans("-_", "+/")) + decoded = base64.b64decode(translated, validate=True) + # ``validate=True`` only checks alphabet membership, not pad-bit + # canonicality: base64's final character can carry unused low-order + # bits that the RFC requires to be zero but most decoders (including + # this stdlib one) silently ignore. That means multiple distinct + # strings (the classic RFC 4648 "Zg=="/"Zh==" pair both decode to + # b"f") can represent the same bytes. Re-encoding the decoded bytes + # canonically and requiring an exact match on the original body + # rejects any such non-canonical encoding. + if _b64encode(decoded) != body: + raise binascii.Error("Non-canonical base64url encoding") + return decoded + + +def validate_github_user_token(token: str) -> None: + if not token.startswith(("gho_", "ghu_")): + raise InvalidGitHubUserToken( + "GitHub OAuth did not return a supported user access token" + ) + + +@dataclass(frozen=True) +class TokenCipher: + version: str + key: bytes + + @classmethod + def from_config(cls, value: str) -> "TokenCipher": + try: + version, encoded_key = value.split(":", 1) + key = _b64decode(encoded_key) + except (ValueError, binascii.Error) as exc: + raise TokenCipherConfigurationError( + "OPENUI_TOKEN_ENCRYPTION_KEY must use v1:" + ) from exc + if version != "v1" or len(key) != 32: + raise TokenCipherConfigurationError( + "OPENUI_TOKEN_ENCRYPTION_KEY must use v1:" + ) + return cls(version=version, key=key) + + def _associated_data(self, context: str) -> bytes: + return f"openui:github-oauth:{self.version}:{context}".encode("utf-8") + + def encrypt(self, plaintext: str, *, context: str) -> str: + nonce = os.urandom(12) + ciphertext = AESGCM(self.key).encrypt( + nonce, + plaintext.encode("utf-8"), + self._associated_data(context), + ) + return f"{self.version}:{_b64encode(nonce + ciphertext)}" + + def decrypt(self, payload: str, *, context: str) -> str: + try: + version, encoded_payload = payload.split(":", 1) + encrypted = _b64decode(encoded_payload) + nonce, ciphertext = encrypted[:12], encrypted[12:] + if version != self.version or len(nonce) != 12 or not ciphertext: + raise ValueError + plaintext = AESGCM(self.key).decrypt( + nonce, + ciphertext, + self._associated_data(context), + ) + return plaintext.decode("utf-8") + except (ValueError, UnicodeDecodeError, binascii.Error, InvalidTag) as exc: + raise TokenDecryptionError( + "Stored GitHub token could not be decrypted" + ) from exc + + +class OAuthTokenStore: + def __init__(self, cipher: TokenCipher): + self._cipher = cipher + + @staticmethod + def _normalize_user_id(user_id: str) -> tuple[bytes, str]: + """Parse ``user_id`` once and return its canonical form. + + Different spellings of the same UUID (upper/lower case, with or + without hyphens, URN form, ...) must resolve to the same database + row *and* the same AEAD associated data. Parsing once here and + reusing ``str(parsed)`` (the canonical lowercase-hyphenated form) + for both the row lookup key and the cipher context keeps encryption + and decryption in sync regardless of how the caller spelled the id. + """ + parsed = uuid.UUID(user_id) + return parsed.bytes, str(parsed) + + def set(self, user_id: str, token: str) -> None: + validate_github_user_token(token) + key_bytes, canonical_id = self._normalize_user_id(user_id) + ciphertext = self._cipher.encrypt(token, context=canonical_id) + updated = ( + User.update(github_oauth_token=ciphertext) + .where(User.id == key_bytes) + .execute() + ) + if updated != 1: + raise LookupError(f"OpenUI user {user_id} does not exist") + + def get(self, user_id: str) -> str | None: + key_bytes, canonical_id = self._normalize_user_id(user_id) + user = User.get_or_none(User.id == key_bytes) + if user is None or user.github_oauth_token is None: + return None + return self._cipher.decrypt(user.github_oauth_token, context=canonical_id) + + def delete(self, user_id: str) -> None: + key_bytes, _canonical_id = self._normalize_user_id(user_id) + ( + User.update(github_oauth_token=None) + .where(User.id == key_bytes) + .execute() + ) diff --git a/backend/openui/db/models.py b/backend/openui/db/models.py index 0e057842..d0fdbc42 100644 --- a/backend/openui/db/models.py +++ b/backend/openui/db/models.py @@ -9,6 +9,7 @@ DateTimeField, ForeignKeyField, OperationalError, + TextField, fn, ) import uuid @@ -42,6 +43,7 @@ class User(BaseModel): username = CharField(unique=True) email = CharField(null=True) created_at = DateTimeField() + github_oauth_token = TextField(null=True) class Credential(BaseModel): @@ -113,27 +115,36 @@ def tokens_since(cls, user_id: str, day: datetime.date) -> int: ) -CURRENT_VERSION = "2024-05-14" +CURRENT_VERSION = "2026-07-14" -def alter(schema: SchemaMigration, ops: list[list], version: str) -> bool: +class SchemaMigrationError(RuntimeError): + """Raised when the OpenUI database schema cannot be migrated safely. + + Covers both a failed ``ALTER TABLE`` (propagated from the underlying + :class:`OperationalError`) and an unrecognized/unsupported schema + version that no migration branch handles. Either case must stop + startup rather than silently leaving the database on a stale schema. + """ + + +def alter(schema: SchemaMigration, ops: list[list], version: str) -> None: try: migrate(*ops) - except OperationalError as e: - print("Migration failed", e) - return False + except OperationalError as exc: + raise SchemaMigrationError( + f"Failed to migrate OpenUI database schema to version {version}" + ) from exc schema.version = version schema.save() - print(f"Migrated {version}") - return version != CURRENT_VERSION -def perform_migration(schema: SchemaMigration) -> bool: +def perform_migration(schema: SchemaMigration) -> None: if schema.version == "2024-03-08": version = "2024-03-12" aaguid = CharField(null=True) user_verified = BooleanField(default=False) - altered = alter( + alter( schema, [ migrator.add_column("credential", "aaguid", aaguid), @@ -141,24 +152,55 @@ def perform_migration(schema: SchemaMigration) -> bool: ], version, ) - if altered: - perform_migration(schema) + perform_migration(schema) + return if schema.version == "2024-03-12": version = "2024-05-14" database.create_tables([Vote]) schema.version = version schema.save() - if version != CURRENT_VERSION: - perform_migration(schema) + perform_migration(schema) + return + if schema.version == "2024-05-14": + version = "2026-07-14" + alter( + schema, + [ + migrator.add_column( + "user", + "github_oauth_token", + TextField(null=True), + ) + ], + version, + ) + perform_migration(schema) + return + if schema.version != CURRENT_VERSION: + raise SchemaMigrationError( + f"OpenUI database schema version {schema.version!r} is not supported" + ) -def ensure_migrated(): - if not config.DB.exists(): +def ensure_migrated() -> None: + if not SchemaMigration.table_exists(): database.create_tables( [User, Credential, Session, Component, SchemaMigration, Usage, Vote] ) SchemaMigration.create(version=CURRENT_VERSION) - else: + return + + schema = SchemaMigration.select().first() + if schema is None: + raise RuntimeError("OpenUI database has no schema migration version") + if schema.version != CURRENT_VERSION: + perform_migration(schema) + # Defense in depth: perform_migration raises on any failure or + # unsupported version, but re-check here so ensure_migrated() can + # never return while the schema is still stale, even if a future + # migration branch is added that forgets to do so itself. schema = SchemaMigration.select().first() - if schema.version != CURRENT_VERSION: - perform_migration(schema) + if schema is None or schema.version != CURRENT_VERSION: + raise SchemaMigrationError( + "OpenUI database migration did not reach the current schema version" + ) diff --git a/backend/openui/dist/assets/CodeEditor-B9qhAAku.js b/backend/openui/dist/assets/CodeEditor--kCrJcJ3.js similarity index 99% rename from backend/openui/dist/assets/CodeEditor-B9qhAAku.js rename to backend/openui/dist/assets/CodeEditor--kCrJcJ3.js index 1b5a6bc5..e8fc95ca 100644 --- a/backend/openui/dist/assets/CodeEditor-B9qhAAku.js +++ b/backend/openui/dist/assets/CodeEditor--kCrJcJ3.js @@ -1,5 +1,5 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/html-B4dTfUY8.js","assets/index-B7PjGjI7.js","assets/index-CnQwS-Fb.css","assets/index-DnTpCebm.js","assets/javascript-BcV1SRi8.js","assets/typescript-BfKWl9Pr.js","assets/python-CsxvR8Mf.js","assets/yaml-DWuY8lcX.js","assets/cssMode-CMP9zKWk.js","assets/htmlMode-BZEeRbEQ.js","assets/jsonMode-CWFvP3uU.js","assets/tsMode-FcR9Jej8.js"])))=>i.map(i=>d[i]); -var AZ=Object.defineProperty;var MZ=(s,e,t)=>e in s?AZ(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var Q1=(s,e,t)=>MZ(s,typeof e!="symbol"?e+"":e,t);import{g as _t,W as Sm,_ as er,$ as RZ,a3 as PZ,a7 as FZ,N as OZ,M as BZ,L as WZ,a2 as HZ,a0 as VZ,a1 as zZ,aw as UZ,j as $Z}from"./index-B7PjGjI7.js";import{C as jZ}from"./index-DnTpCebm.js";function KZ(s,e,t){return e in s?Object.defineProperty(s,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):s[e]=t,s}function l5(s,e){var t=Object.keys(s);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(s);e&&(i=i.filter(function(n){return Object.getOwnPropertyDescriptor(s,n).enumerable})),t.push.apply(t,i)}return t}function d5(s){for(var e=1;e=0)&&(t[n]=s[n]);return t}function GZ(s,e){if(s==null)return{};var t=qZ(s,e),i,n;if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(s);for(n=0;n=0)&&Object.prototype.propertyIsEnumerable.call(s,i)&&(t[i]=s[i])}return t}function ZZ(s,e){return XZ(s)||YZ(s,e)||QZ(s,e)||JZ()}function XZ(s){if(Array.isArray(s))return s}function YZ(s,e){if(!(typeof Symbol>"u"||!(Symbol.iterator in Object(s)))){var t=[],i=!0,n=!1,o=void 0;try{for(var r=s[Symbol.iterator](),a;!(i=(a=r.next()).done)&&(t.push(a.value),!(e&&t.length===e));i=!0);}catch(l){n=!0,o=l}finally{try{!i&&r.return!=null&&r.return()}finally{if(n)throw o}}return t}}function QZ(s,e){if(s){if(typeof s=="string")return c5(s,e);var t=Object.prototype.toString.call(s).slice(8,-1);if(t==="Object"&&s.constructor&&(t=s.constructor.name),t==="Map"||t==="Set")return Array.from(s);if(t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t))return c5(s,e)}}function c5(s,e){(e==null||e>s.length)&&(e=s.length);for(var t=0,i=new Array(e);ti.map(i=>d[i]); +var AZ=Object.defineProperty;var MZ=(s,e,t)=>e in s?AZ(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var Q1=(s,e,t)=>MZ(s,typeof e!="symbol"?e+"":e,t);import{g as _t,W as Sm,_ as er,$ as RZ,a3 as PZ,a7 as FZ,N as OZ,M as BZ,L as WZ,a2 as HZ,a0 as VZ,a1 as zZ,aw as UZ,j as $Z}from"./index-CNOVY8Nm.js";import{C as jZ}from"./index-COqeckZP.js";function KZ(s,e,t){return e in s?Object.defineProperty(s,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):s[e]=t,s}function l5(s,e){var t=Object.keys(s);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(s);e&&(i=i.filter(function(n){return Object.getOwnPropertyDescriptor(s,n).enumerable})),t.push.apply(t,i)}return t}function d5(s){for(var e=1;e=0)&&(t[n]=s[n]);return t}function GZ(s,e){if(s==null)return{};var t=qZ(s,e),i,n;if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(s);for(n=0;n=0)&&Object.prototype.propertyIsEnumerable.call(s,i)&&(t[i]=s[i])}return t}function ZZ(s,e){return XZ(s)||YZ(s,e)||QZ(s,e)||JZ()}function XZ(s){if(Array.isArray(s))return s}function YZ(s,e){if(!(typeof Symbol>"u"||!(Symbol.iterator in Object(s)))){var t=[],i=!0,n=!1,o=void 0;try{for(var r=s[Symbol.iterator](),a;!(i=(a=r.next()).done)&&(t.push(a.value),!(e&&t.length===e));i=!0);}catch(l){n=!0,o=l}finally{try{!i&&r.return!=null&&r.return()}finally{if(n)throw o}}return t}}function QZ(s,e){if(s){if(typeof s=="string")return c5(s,e);var t=Object.prototype.toString.call(s).slice(8,-1);if(t==="Object"&&s.constructor&&(t=s.constructor.name),t==="Map"||t==="Set")return Array.from(s);if(t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t))return c5(s,e)}}function c5(s,e){(e==null||e>s.length)&&(e=s.length);for(var t=0,i=new Array(e);t=s.length?s.apply(this,n):function(){for(var r=arguments.length,a=new Array(r),l=0;l1&&arguments[1]!==void 0?arguments[1]:{};J1.initial(s),J1.handler(e);var t={current:s},i=dv(gX)(t,e),n=dv(hX)(t),o=dv(J1.changes)(s),r=dv(uX)(t);function a(){var d=arguments.length>0&&arguments[0]!==void 0?arguments[0]:function(c){return c};return J1.selector(d),d(t.current)}function l(d){tX(i,n,o,r)(d)}return[a,l]}function uX(s,e){return wb(e)?e(s.current):e}function hX(s,e){return s.current=h5(h5({},s.current),e),e}function gX(s,e,t){return wb(e)?e(s.current):Object.keys(t).forEach(function(i){var n;return(n=e[i])===null||n===void 0?void 0:n.call(e,s.current[i])}),t}var fX={create:cX},pX={paths:{vs:"https://cdn.jsdelivr.net/npm/monaco-editor@0.52.2/min/vs"}};function mX(s){return function e(){for(var t=this,i=arguments.length,n=new Array(i),o=0;o=s.length?s.apply(this,n):function(){for(var r=arguments.length,a=new Array(r),l=0;l{if(e&&typeof e=="object"||typeof e=="function")for(let n of VLe(e))!zLe.call(s,n)&&n!==t&&WLe(s,n,{get:()=>e[n],enumerable:!(i=HLe(e,n))||i.enumerable});return s},$Le=(s,e,t)=>(ULe(s,e,"default"),t),Iv={};$Le(Iv,_0);var BK={},tT={},jLe=class WK{static getOrCreate(e){return tT[e]||(tT[e]=new WK(e)),tT[e]}constructor(e){this._languageId=e,this._loadingTriggered=!1,this._lazyLoadPromise=new Promise((t,i)=>{this._lazyLoadPromiseResolve=t,this._lazyLoadPromiseReject=i})}load(){return this._loadingTriggered||(this._loadingTriggered=!0,BK[this._languageId].loader().then(e=>this._lazyLoadPromiseResolve(e),e=>this._lazyLoadPromiseReject(e))),this._lazyLoadPromise}};function pp(s){const e=s.id;BK[e]=s,Iv.languages.register(s);const t=jLe.getOrCreate(e);Iv.languages.registerTokensProviderFactory(e,{create:async()=>(await t.load()).language}),Iv.languages.onLanguageEncountered(e,async()=>{const i=await t.load();Iv.languages.setLanguageConfiguration(e,i.conf)})}pp({id:"css",extensions:[".css"],aliases:["CSS","css"],mimetypes:["text/css"],loader:()=>er(()=>import("./css-D1nB4Vcj.js"),[])});pp({id:"html",extensions:[".html",".htm",".shtml",".xhtml",".mdoc",".jsp",".asp",".aspx",".jshtm"],aliases:["HTML","htm","html","xhtml"],mimetypes:["text/html","text/x-jshtm","text/template","text/ng-template"],loader:()=>er(()=>import("./html-B4dTfUY8.js"),__vite__mapDeps([0,1,2,3]))});pp({id:"javascript",extensions:[".js",".es6",".jsx",".mjs",".cjs"],firstLine:"^#!.*\\bnode",filenames:["jakefile"],aliases:["JavaScript","javascript","js"],mimetypes:["text/javascript"],loader:()=>er(()=>import("./javascript-BcV1SRi8.js"),__vite__mapDeps([4,5,1,2,3]))});pp({id:"markdown",extensions:[".md",".markdown",".mdown",".mkdn",".mkd",".mdwn",".mdtxt",".mdtext"],aliases:["Markdown","markdown"],loader:()=>er(()=>import("./markdown-7fQo6M4U.js"),[])});pp({id:"python",extensions:[".py",".rpy",".pyw",".cpy",".gyp",".gypi"],aliases:["Python","py"],firstLine:"^#!/.*\\bpython[0-9.-]*\\b",loader:()=>er(()=>import("./python-CsxvR8Mf.js"),__vite__mapDeps([6,1,2,3]))});pp({id:"typescript",extensions:[".ts",".tsx",".cts",".mts"],aliases:["TypeScript","ts","typescript"],mimetypes:["text/typescript"],loader:()=>er(()=>import("./typescript-BfKWl9Pr.js"),__vite__mapDeps([5,1,2,3]))});pp({id:"yaml",extensions:[".yaml",".yml"],aliases:["YAML","yaml","YML","yml"],mimetypes:["application/x-yaml","text/x-yaml"],loader:()=>er(()=>import("./yaml-DWuY8lcX.js"),__vite__mapDeps([7,1,2,3]))});class KLe extends qs{constructor(){super({id:"diffEditor.toggleCollapseUnchangedRegions",title:Ve("toggleCollapseUnchangedRegions","Toggle Collapse Unchanged Regions"),icon:oe.map,toggled:G.has("config.diffEditor.hideUnchangedRegions.enabled"),precondition:G.has("isInDiffEditor"),menu:{when:G.has("isInDiffEditor"),id:E.EditorTitle,order:22,group:"navigation"}})}run(e,...t){const i=e.get(rt),n=!i.getValue("diffEditor.hideUnchangedRegions.enabled");i.updateValue("diffEditor.hideUnchangedRegions.enabled",n)}}class HK extends qs{constructor(){super({id:"diffEditor.toggleShowMovedCodeBlocks",title:Ve("toggleShowMovedCodeBlocks","Toggle Show Moved Code Blocks"),precondition:G.has("isInDiffEditor")})}run(e,...t){const i=e.get(rt),n=!i.getValue("diffEditor.experimental.showMoves");i.updateValue("diffEditor.experimental.showMoves",n)}}class VK extends qs{constructor(){super({id:"diffEditor.toggleUseInlineViewWhenSpaceIsLimited",title:Ve("toggleUseInlineViewWhenSpaceIsLimited","Toggle Use Inline View When Space Is Limited"),precondition:G.has("isInDiffEditor")})}run(e,...t){const i=e.get(rt),n=!i.getValue("diffEditor.useInlineViewWhenSpaceIsLimited");i.updateValue("diffEditor.useInlineViewWhenSpaceIsLimited",n)}}const B1=Ve("diffEditor","Diff Editor");class qLe extends fl{constructor(){super({id:"diffEditor.switchSide",title:Ve("switchSide","Switch Side"),icon:oe.arrowSwap,precondition:G.has("isInDiffEditor"),f1:!0,category:B1})}runEditorCommand(e,t,i){const n=b0(e);if(n instanceof $c){if(i&&i.dryRun)return{destinationSelection:n.mapToOtherSide().destinationSelection};n.switchSide()}}}class GLe extends fl{constructor(){super({id:"diffEditor.exitCompareMove",title:Ve("exitCompareMove","Exit Compare Move"),icon:oe.close,precondition:T.comparingMovedCode,f1:!1,category:B1,keybinding:{weight:1e4,primary:9}})}runEditorCommand(e,t,...i){const n=b0(e);n instanceof $c&&n.exitCompareMove()}}class ZLe extends fl{constructor(){super({id:"diffEditor.collapseAllUnchangedRegions",title:Ve("collapseAllUnchangedRegions","Collapse All Unchanged Regions"),icon:oe.fold,precondition:G.has("isInDiffEditor"),f1:!0,category:B1})}runEditorCommand(e,t,...i){const n=b0(e);n instanceof $c&&n.collapseAllUnchangedRegions()}}class XLe extends fl{constructor(){super({id:"diffEditor.showAllUnchangedRegions",title:Ve("showAllUnchangedRegions","Show All Unchanged Regions"),icon:oe.unfold,precondition:G.has("isInDiffEditor"),f1:!0,category:B1})}runEditorCommand(e,t,...i){const n=b0(e);n instanceof $c&&n.showAllUnchangedRegions()}}class TM extends qs{constructor(){super({id:"diffEditor.revert",title:Ve("revert","Revert"),f1:!1,category:B1})}run(e,t){var i;const n=YLe(e,t.originalUri,t.modifiedUri);n instanceof $c&&n.revertRangeMappings((i=t.mapping.innerChanges)!==null&&i!==void 0?i:[])}}const zK=Ve("accessibleDiffViewer","Accessible Diff Viewer");class v0 extends qs{constructor(){super({id:v0.id,title:Ve("editor.action.accessibleDiffViewer.next","Go to Next Difference"),category:zK,precondition:G.has("isInDiffEditor"),keybinding:{primary:65,weight:100},f1:!0})}run(e){const t=b0(e);t==null||t.accessibleDiffViewerNext()}}v0.id="editor.action.accessibleDiffViewer.next";class W1 extends qs{constructor(){super({id:W1.id,title:Ve("editor.action.accessibleDiffViewer.prev","Go to Previous Difference"),category:zK,precondition:G.has("isInDiffEditor"),keybinding:{primary:1089,weight:100},f1:!0})}run(e){const t=b0(e);t==null||t.accessibleDiffViewerPrev()}}W1.id="editor.action.accessibleDiffViewer.prev";function YLe(s,e,t){return s.get(xt).listDiffEditors().find(o=>{var r,a;const l=o.getModifiedEditor(),d=o.getOriginalEditor();return l&&((r=l.getModel())===null||r===void 0?void 0:r.uri.toString())===t.toString()&&d&&((a=d.getModel())===null||a===void 0?void 0:a.uri.toString())===e.toString()})||null}function b0(s){const t=s.get(xt).listDiffEditors(),i=Xn();if(i)for(const n of t){const o=n.getContainerDomNode();if(QLe(o,i))return n}return null}function QLe(s,e){let t=e;for(;t;){if(t===s)return!0;t=t.parentElement}return!1}qt(KLe);qt(HK);qt(VK);yn.appendMenuItem(E.EditorTitle,{command:{id:new VK().desc.id,title:p("useInlineViewWhenSpaceIsLimited","Use Inline View When Space Is Limited"),toggled:G.has("config.diffEditor.useInlineViewWhenSpaceIsLimited"),precondition:G.has("isInDiffEditor")},order:11,group:"1_diff",when:G.and(T.diffEditorRenderSideBySideInlineBreakpointReached,G.has("isInDiffEditor"))});yn.appendMenuItem(E.EditorTitle,{command:{id:new HK().desc.id,title:p("showMoves","Show Moved Code Blocks"),icon:oe.move,toggled:r0.create("config.diffEditor.experimental.showMoves",!0),precondition:G.has("isInDiffEditor")},order:10,group:"1_diff",when:G.has("isInDiffEditor")});qt(TM);for(const s of[{icon:oe.arrowRight,key:T.diffEditorInlineMode.toNegated()},{icon:oe.discard,key:T.diffEditorInlineMode}])yn.appendMenuItem(E.DiffEditorHunkToolbar,{command:{id:new TM().desc.id,title:p("revertHunk","Revert Block"),icon:s.icon},when:G.and(T.diffEditorModifiedWritable,s.key),order:5,group:"primary"}),yn.appendMenuItem(E.DiffEditorSelectionToolbar,{command:{id:new TM().desc.id,title:p("revertSelection","Revert Selection"),icon:s.icon},when:G.and(T.diffEditorModifiedWritable,s.key),order:5,group:"primary"});qt(qLe);qt(GLe);qt(ZLe);qt(XLe);yn.appendMenuItem(E.EditorTitle,{command:{id:v0.id,title:p("Open Accessible Diff Viewer","Open Accessible Diff Viewer"),precondition:G.has("isInDiffEditor")},order:10,group:"2_diff",when:G.and(T.accessibleDiffViewerVisible.negate(),G.has("isInDiffEditor"))});pt.registerCommandAlias("editor.action.diffReview.next",v0.id);qt(v0);pt.registerCommandAlias("editor.action.diffReview.prev",W1.id);qt(W1);var JLe=function(s,e,t,i){var n=arguments.length,o=n<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,r;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(s,e,t,i);else for(var a=s.length-1;a>=0;a--)(r=s[a])&&(o=(n<3?r(o):n>3?r(e,t,o):r(e,t))||o);return n>3&&o&&Object.defineProperty(e,t,o),o},exe=function(s,e){return function(t,i){e(t,i,s)}},NM;const fk=new ue("selectionAnchorSet",!1);let jc=NM=class{static get(e){return e.getContribution(NM.ID)}constructor(e,t){this.editor=e,this.selectionAnchorSetContextKey=fk.bindTo(t),this.modelChangeListener=e.onDidChangeModel(()=>this.selectionAnchorSetContextKey.reset())}setSelectionAnchor(){if(this.editor.hasModel()){const e=this.editor.getPosition();this.editor.changeDecorations(t=>{this.decorationId&&t.removeDecoration(this.decorationId),this.decorationId=t.addDecoration(we.fromPositions(e,e),{description:"selection-anchor",stickiness:1,hoverMessage:new ss().appendText(p("selectionAnchor","Selection Anchor")),className:"selection-anchor"})}),this.selectionAnchorSetContextKey.set(!!this.decorationId),fo(p("anchorSet","Anchor set at {0}:{1}",e.lineNumber,e.column))}}goToSelectionAnchor(){if(this.editor.hasModel()&&this.decorationId){const e=this.editor.getModel().getDecorationRange(this.decorationId);e&&this.editor.setPosition(e.getStartPosition())}}selectFromAnchorToCursor(){if(this.editor.hasModel()&&this.decorationId){const e=this.editor.getModel().getDecorationRange(this.decorationId);if(e){const t=this.editor.getPosition();this.editor.setSelection(we.fromPositions(e.getStartPosition(),t)),this.cancelSelectionAnchor()}}}cancelSelectionAnchor(){if(this.decorationId){const e=this.decorationId;this.editor.changeDecorations(t=>{t.removeDecoration(e),this.decorationId=void 0}),this.selectionAnchorSetContextKey.set(!1)}}dispose(){this.cancelSelectionAnchor(),this.modelChangeListener.dispose()}};jc.ID="editor.contrib.selectionAnchorController";jc=NM=JLe([exe(1,Be)],jc);class txe extends me{constructor(){super({id:"editor.action.setSelectionAnchor",label:p("setSelectionAnchor","Set Selection Anchor"),alias:"Set Selection Anchor",precondition:void 0,kbOpts:{kbExpr:T.editorTextFocus,primary:an(2089,2080),weight:100}})}async run(e,t){var i;(i=jc.get(t))===null||i===void 0||i.setSelectionAnchor()}}class ixe extends me{constructor(){super({id:"editor.action.goToSelectionAnchor",label:p("goToSelectionAnchor","Go to Selection Anchor"),alias:"Go to Selection Anchor",precondition:fk})}async run(e,t){var i;(i=jc.get(t))===null||i===void 0||i.goToSelectionAnchor()}}class nxe extends me{constructor(){super({id:"editor.action.selectFromAnchorToCursor",label:p("selectFromAnchorToCursor","Select from Anchor to Cursor"),alias:"Select from Anchor to Cursor",precondition:fk,kbOpts:{kbExpr:T.editorTextFocus,primary:an(2089,2089),weight:100}})}async run(e,t){var i;(i=jc.get(t))===null||i===void 0||i.selectFromAnchorToCursor()}}class sxe extends me{constructor(){super({id:"editor.action.cancelSelectionAnchor",label:p("cancelSelectionAnchor","Cancel Selection Anchor"),alias:"Cancel Selection Anchor",precondition:fk,kbOpts:{kbExpr:T.editorTextFocus,primary:9,weight:100}})}async run(e,t){var i;(i=jc.get(t))===null||i===void 0||i.cancelSelectionAnchor()}}kt(jc.ID,jc,4);te(txe);te(ixe);te(nxe);te(sxe);const oxe=N("editorOverviewRuler.bracketMatchForeground",{dark:"#A0A0A0",light:"#A0A0A0",hcDark:"#A0A0A0",hcLight:"#A0A0A0"},p("overviewRulerBracketMatchForeground","Overview ruler marker color for matching brackets."));class rxe extends me{constructor(){super({id:"editor.action.jumpToBracket",label:p("smartSelect.jumpBracket","Go to Bracket"),alias:"Go to Bracket",precondition:void 0,kbOpts:{kbExpr:T.editorTextFocus,primary:3165,weight:100}})}run(e,t){var i;(i=ga.get(t))===null||i===void 0||i.jumpToBracket()}}class axe extends me{constructor(){super({id:"editor.action.selectToBracket",label:p("smartSelect.selectToBracket","Select to Bracket"),alias:"Select to Bracket",precondition:void 0,metadata:{description:Ve("smartSelect.selectToBracketDescription","Select the text inside and including the brackets or curly braces"),args:[{name:"args",schema:{type:"object",properties:{selectBrackets:{type:"boolean",default:!0}}}}]}})}run(e,t,i){var n;let o=!0;i&&i.selectBrackets===!1&&(o=!1),(n=ga.get(t))===null||n===void 0||n.selectToBracket(o)}}class lxe extends me{constructor(){super({id:"editor.action.removeBrackets",label:p("smartSelect.removeBrackets","Remove Brackets"),alias:"Remove Brackets",precondition:void 0,kbOpts:{kbExpr:T.editorTextFocus,primary:2561,weight:100}})}run(e,t){var i;(i=ga.get(t))===null||i===void 0||i.removeBrackets(this.id)}}class dxe{constructor(e,t,i){this.position=e,this.brackets=t,this.options=i}}class ga extends H{static get(e){return e.getContribution(ga.ID)}constructor(e){super(),this._editor=e,this._lastBracketsData=[],this._lastVersionId=0,this._decorations=this._editor.createDecorationsCollection(),this._updateBracketsSoon=this._register(new Wt(()=>this._updateBrackets(),50)),this._matchBrackets=this._editor.getOption(72),this._updateBracketsSoon.schedule(),this._register(e.onDidChangeCursorPosition(t=>{this._matchBrackets!=="never"&&this._updateBracketsSoon.schedule()})),this._register(e.onDidChangeModelContent(t=>{this._updateBracketsSoon.schedule()})),this._register(e.onDidChangeModel(t=>{this._lastBracketsData=[],this._updateBracketsSoon.schedule()})),this._register(e.onDidChangeModelLanguageConfiguration(t=>{this._lastBracketsData=[],this._updateBracketsSoon.schedule()})),this._register(e.onDidChangeConfiguration(t=>{t.hasChanged(72)&&(this._matchBrackets=this._editor.getOption(72),this._decorations.clear(),this._lastBracketsData=[],this._lastVersionId=0,this._updateBracketsSoon.schedule())})),this._register(e.onDidBlurEditorWidget(()=>{this._updateBracketsSoon.schedule()})),this._register(e.onDidFocusEditorWidget(()=>{this._updateBracketsSoon.schedule()}))}jumpToBracket(){if(!this._editor.hasModel())return;const e=this._editor.getModel(),t=this._editor.getSelections().map(i=>{const n=i.getStartPosition(),o=e.bracketPairs.matchBracket(n);let r=null;if(o)o[0].containsPosition(n)&&!o[1].containsPosition(n)?r=o[1].getStartPosition():o[1].containsPosition(n)&&(r=o[0].getStartPosition());else{const a=e.bracketPairs.findEnclosingBrackets(n);if(a)r=a[1].getStartPosition();else{const l=e.bracketPairs.findNextBracket(n);l&&l.range&&(r=l.range.getStartPosition())}}return r?new we(r.lineNumber,r.column,r.lineNumber,r.column):new we(n.lineNumber,n.column,n.lineNumber,n.column)});this._editor.setSelections(t),this._editor.revealRange(t[0])}selectToBracket(e){if(!this._editor.hasModel())return;const t=this._editor.getModel(),i=[];this._editor.getSelections().forEach(n=>{const o=n.getStartPosition();let r=t.bracketPairs.matchBracket(o);if(!r&&(r=t.bracketPairs.findEnclosingBrackets(o),!r)){const d=t.bracketPairs.findNextBracket(o);d&&d.range&&(r=t.bracketPairs.matchBracket(d.range.getStartPosition()))}let a=null,l=null;if(r){r.sort(x.compareRangesUsingStarts);const[d,c]=r;if(a=e?d.getStartPosition():d.getEndPosition(),l=e?c.getEndPosition():c.getStartPosition(),c.containsPosition(o)){const u=a;a=l,l=u}}a&&l&&i.push(new we(a.lineNumber,a.column,l.lineNumber,l.column))}),i.length>0&&(this._editor.setSelections(i),this._editor.revealRange(i[0]))}removeBrackets(e){if(!this._editor.hasModel())return;const t=this._editor.getModel();this._editor.getSelections().forEach(i=>{const n=i.getPosition();let o=t.bracketPairs.matchBracket(n);o||(o=t.bracketPairs.findEnclosingBrackets(n)),o&&(this._editor.pushUndoStop(),this._editor.executeEdits(e,[{range:o[0],text:""},{range:o[1],text:""}]),this._editor.pushUndoStop())})}_updateBrackets(){if(this._matchBrackets==="never")return;this._recomputeBrackets();const e=[];let t=0;for(const i of this._lastBracketsData){const n=i.brackets;n&&(e[t++]={range:n[0],options:i.options},e[t++]={range:n[1],options:i.options})}this._decorations.set(e)}_recomputeBrackets(){if(!this._editor.hasModel()||!this._editor.hasWidgetFocus()){this._lastBracketsData=[],this._lastVersionId=0;return}const e=this._editor.getSelections();if(e.length>100){this._lastBracketsData=[],this._lastVersionId=0;return}const t=this._editor.getModel(),i=t.getVersionId();let n=[];this._lastVersionId===i&&(n=this._lastBracketsData);const o=[];let r=0;for(let u=0,h=e.length;u1&&o.sort(W.compare);const a=[];let l=0,d=0;const c=n.length;for(let u=0,h=o.length;u0&&(t.pushUndoStop(),t.executeCommands(this.id,n),t.pushUndoStop())}}te(gxe);const pk=function(){if(typeof crypto=="object"&&typeof crypto.randomUUID=="function")return crypto.randomUUID.bind(crypto);let s;typeof crypto=="object"&&typeof crypto.getRandomValues=="function"?s=crypto.getRandomValues.bind(crypto):s=function(i){for(let n=0;ns,asFile:()=>{},value:typeof s=="string"?s:void 0}}function fxe(s,e,t){const i={id:pk(),name:s,uri:e,data:t};return{asString:async()=>"",asFile:()=>i,value:void 0}}class $K{constructor(){this._entries=new Map}get size(){let e=0;for(const t of this._entries)e++;return e}has(e){return this._entries.has(this.toKey(e))}matches(e){const t=[...this._entries.keys()];return ft.some(this,([i,n])=>n.asFile())&&t.push("files"),KK(rL(e),t)}get(e){var t;return(t=this._entries.get(this.toKey(e)))===null||t===void 0?void 0:t[0]}append(e,t){const i=this._entries.get(e);i?i.push(t):this._entries.set(this.toKey(e),[t])}replace(e,t){this._entries.set(this.toKey(e),[t])}delete(e){this._entries.delete(this.toKey(e))}*[Symbol.iterator](){for(const[e,t]of this._entries)for(const i of t)yield[e,i]}toKey(e){return rL(e)}}function rL(s){return s.toLowerCase()}function jK(s,e){return KK(rL(s),e.map(rL))}function KK(s,e){if(s==="*/*")return e.length>0;if(e.includes(s))return!0;const t=s.match(/^([a-z]+)\/([a-z]+|\*)$/i);if(!t)return!1;const[i,n,o]=t;return o==="*"?e.some(r=>r.startsWith(n+"/")):!1}const mk=Object.freeze({create:s=>Wc(s.map(e=>e.toString())).join(`\r + *-----------------------------------------------------------------------------*/var WLe=Object.defineProperty,HLe=Object.getOwnPropertyDescriptor,VLe=Object.getOwnPropertyNames,zLe=Object.prototype.hasOwnProperty,ULe=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of VLe(e))!zLe.call(s,n)&&n!==t&&WLe(s,n,{get:()=>e[n],enumerable:!(i=HLe(e,n))||i.enumerable});return s},$Le=(s,e,t)=>(ULe(s,e,"default"),t),Iv={};$Le(Iv,_0);var BK={},tT={},jLe=class WK{static getOrCreate(e){return tT[e]||(tT[e]=new WK(e)),tT[e]}constructor(e){this._languageId=e,this._loadingTriggered=!1,this._lazyLoadPromise=new Promise((t,i)=>{this._lazyLoadPromiseResolve=t,this._lazyLoadPromiseReject=i})}load(){return this._loadingTriggered||(this._loadingTriggered=!0,BK[this._languageId].loader().then(e=>this._lazyLoadPromiseResolve(e),e=>this._lazyLoadPromiseReject(e))),this._lazyLoadPromise}};function pp(s){const e=s.id;BK[e]=s,Iv.languages.register(s);const t=jLe.getOrCreate(e);Iv.languages.registerTokensProviderFactory(e,{create:async()=>(await t.load()).language}),Iv.languages.onLanguageEncountered(e,async()=>{const i=await t.load();Iv.languages.setLanguageConfiguration(e,i.conf)})}pp({id:"css",extensions:[".css"],aliases:["CSS","css"],mimetypes:["text/css"],loader:()=>er(()=>import("./css-D1nB4Vcj.js"),[])});pp({id:"html",extensions:[".html",".htm",".shtml",".xhtml",".mdoc",".jsp",".asp",".aspx",".jshtm"],aliases:["HTML","htm","html","xhtml"],mimetypes:["text/html","text/x-jshtm","text/template","text/ng-template"],loader:()=>er(()=>import("./html-BdsSULgH.js"),__vite__mapDeps([0,1,2,3]))});pp({id:"javascript",extensions:[".js",".es6",".jsx",".mjs",".cjs"],firstLine:"^#!.*\\bnode",filenames:["jakefile"],aliases:["JavaScript","javascript","js"],mimetypes:["text/javascript"],loader:()=>er(()=>import("./javascript-CBjcvhSJ.js"),__vite__mapDeps([4,5,1,2,3]))});pp({id:"markdown",extensions:[".md",".markdown",".mdown",".mkdn",".mkd",".mdwn",".mdtxt",".mdtext"],aliases:["Markdown","markdown"],loader:()=>er(()=>import("./markdown-7fQo6M4U.js"),[])});pp({id:"python",extensions:[".py",".rpy",".pyw",".cpy",".gyp",".gypi"],aliases:["Python","py"],firstLine:"^#!/.*\\bpython[0-9.-]*\\b",loader:()=>er(()=>import("./python-BubfsCnB.js"),__vite__mapDeps([6,1,2,3]))});pp({id:"typescript",extensions:[".ts",".tsx",".cts",".mts"],aliases:["TypeScript","ts","typescript"],mimetypes:["text/typescript"],loader:()=>er(()=>import("./typescript-C194rtFh.js"),__vite__mapDeps([5,1,2,3]))});pp({id:"yaml",extensions:[".yaml",".yml"],aliases:["YAML","yaml","YML","yml"],mimetypes:["application/x-yaml","text/x-yaml"],loader:()=>er(()=>import("./yaml-CuZ8lk-T.js"),__vite__mapDeps([7,1,2,3]))});class KLe extends qs{constructor(){super({id:"diffEditor.toggleCollapseUnchangedRegions",title:Ve("toggleCollapseUnchangedRegions","Toggle Collapse Unchanged Regions"),icon:oe.map,toggled:G.has("config.diffEditor.hideUnchangedRegions.enabled"),precondition:G.has("isInDiffEditor"),menu:{when:G.has("isInDiffEditor"),id:E.EditorTitle,order:22,group:"navigation"}})}run(e,...t){const i=e.get(rt),n=!i.getValue("diffEditor.hideUnchangedRegions.enabled");i.updateValue("diffEditor.hideUnchangedRegions.enabled",n)}}class HK extends qs{constructor(){super({id:"diffEditor.toggleShowMovedCodeBlocks",title:Ve("toggleShowMovedCodeBlocks","Toggle Show Moved Code Blocks"),precondition:G.has("isInDiffEditor")})}run(e,...t){const i=e.get(rt),n=!i.getValue("diffEditor.experimental.showMoves");i.updateValue("diffEditor.experimental.showMoves",n)}}class VK extends qs{constructor(){super({id:"diffEditor.toggleUseInlineViewWhenSpaceIsLimited",title:Ve("toggleUseInlineViewWhenSpaceIsLimited","Toggle Use Inline View When Space Is Limited"),precondition:G.has("isInDiffEditor")})}run(e,...t){const i=e.get(rt),n=!i.getValue("diffEditor.useInlineViewWhenSpaceIsLimited");i.updateValue("diffEditor.useInlineViewWhenSpaceIsLimited",n)}}const B1=Ve("diffEditor","Diff Editor");class qLe extends fl{constructor(){super({id:"diffEditor.switchSide",title:Ve("switchSide","Switch Side"),icon:oe.arrowSwap,precondition:G.has("isInDiffEditor"),f1:!0,category:B1})}runEditorCommand(e,t,i){const n=b0(e);if(n instanceof $c){if(i&&i.dryRun)return{destinationSelection:n.mapToOtherSide().destinationSelection};n.switchSide()}}}class GLe extends fl{constructor(){super({id:"diffEditor.exitCompareMove",title:Ve("exitCompareMove","Exit Compare Move"),icon:oe.close,precondition:T.comparingMovedCode,f1:!1,category:B1,keybinding:{weight:1e4,primary:9}})}runEditorCommand(e,t,...i){const n=b0(e);n instanceof $c&&n.exitCompareMove()}}class ZLe extends fl{constructor(){super({id:"diffEditor.collapseAllUnchangedRegions",title:Ve("collapseAllUnchangedRegions","Collapse All Unchanged Regions"),icon:oe.fold,precondition:G.has("isInDiffEditor"),f1:!0,category:B1})}runEditorCommand(e,t,...i){const n=b0(e);n instanceof $c&&n.collapseAllUnchangedRegions()}}class XLe extends fl{constructor(){super({id:"diffEditor.showAllUnchangedRegions",title:Ve("showAllUnchangedRegions","Show All Unchanged Regions"),icon:oe.unfold,precondition:G.has("isInDiffEditor"),f1:!0,category:B1})}runEditorCommand(e,t,...i){const n=b0(e);n instanceof $c&&n.showAllUnchangedRegions()}}class TM extends qs{constructor(){super({id:"diffEditor.revert",title:Ve("revert","Revert"),f1:!1,category:B1})}run(e,t){var i;const n=YLe(e,t.originalUri,t.modifiedUri);n instanceof $c&&n.revertRangeMappings((i=t.mapping.innerChanges)!==null&&i!==void 0?i:[])}}const zK=Ve("accessibleDiffViewer","Accessible Diff Viewer");class v0 extends qs{constructor(){super({id:v0.id,title:Ve("editor.action.accessibleDiffViewer.next","Go to Next Difference"),category:zK,precondition:G.has("isInDiffEditor"),keybinding:{primary:65,weight:100},f1:!0})}run(e){const t=b0(e);t==null||t.accessibleDiffViewerNext()}}v0.id="editor.action.accessibleDiffViewer.next";class W1 extends qs{constructor(){super({id:W1.id,title:Ve("editor.action.accessibleDiffViewer.prev","Go to Previous Difference"),category:zK,precondition:G.has("isInDiffEditor"),keybinding:{primary:1089,weight:100},f1:!0})}run(e){const t=b0(e);t==null||t.accessibleDiffViewerPrev()}}W1.id="editor.action.accessibleDiffViewer.prev";function YLe(s,e,t){return s.get(xt).listDiffEditors().find(o=>{var r,a;const l=o.getModifiedEditor(),d=o.getOriginalEditor();return l&&((r=l.getModel())===null||r===void 0?void 0:r.uri.toString())===t.toString()&&d&&((a=d.getModel())===null||a===void 0?void 0:a.uri.toString())===e.toString()})||null}function b0(s){const t=s.get(xt).listDiffEditors(),i=Xn();if(i)for(const n of t){const o=n.getContainerDomNode();if(QLe(o,i))return n}return null}function QLe(s,e){let t=e;for(;t;){if(t===s)return!0;t=t.parentElement}return!1}qt(KLe);qt(HK);qt(VK);yn.appendMenuItem(E.EditorTitle,{command:{id:new VK().desc.id,title:p("useInlineViewWhenSpaceIsLimited","Use Inline View When Space Is Limited"),toggled:G.has("config.diffEditor.useInlineViewWhenSpaceIsLimited"),precondition:G.has("isInDiffEditor")},order:11,group:"1_diff",when:G.and(T.diffEditorRenderSideBySideInlineBreakpointReached,G.has("isInDiffEditor"))});yn.appendMenuItem(E.EditorTitle,{command:{id:new HK().desc.id,title:p("showMoves","Show Moved Code Blocks"),icon:oe.move,toggled:r0.create("config.diffEditor.experimental.showMoves",!0),precondition:G.has("isInDiffEditor")},order:10,group:"1_diff",when:G.has("isInDiffEditor")});qt(TM);for(const s of[{icon:oe.arrowRight,key:T.diffEditorInlineMode.toNegated()},{icon:oe.discard,key:T.diffEditorInlineMode}])yn.appendMenuItem(E.DiffEditorHunkToolbar,{command:{id:new TM().desc.id,title:p("revertHunk","Revert Block"),icon:s.icon},when:G.and(T.diffEditorModifiedWritable,s.key),order:5,group:"primary"}),yn.appendMenuItem(E.DiffEditorSelectionToolbar,{command:{id:new TM().desc.id,title:p("revertSelection","Revert Selection"),icon:s.icon},when:G.and(T.diffEditorModifiedWritable,s.key),order:5,group:"primary"});qt(qLe);qt(GLe);qt(ZLe);qt(XLe);yn.appendMenuItem(E.EditorTitle,{command:{id:v0.id,title:p("Open Accessible Diff Viewer","Open Accessible Diff Viewer"),precondition:G.has("isInDiffEditor")},order:10,group:"2_diff",when:G.and(T.accessibleDiffViewerVisible.negate(),G.has("isInDiffEditor"))});pt.registerCommandAlias("editor.action.diffReview.next",v0.id);qt(v0);pt.registerCommandAlias("editor.action.diffReview.prev",W1.id);qt(W1);var JLe=function(s,e,t,i){var n=arguments.length,o=n<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,r;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(s,e,t,i);else for(var a=s.length-1;a>=0;a--)(r=s[a])&&(o=(n<3?r(o):n>3?r(e,t,o):r(e,t))||o);return n>3&&o&&Object.defineProperty(e,t,o),o},exe=function(s,e){return function(t,i){e(t,i,s)}},NM;const fk=new ue("selectionAnchorSet",!1);let jc=NM=class{static get(e){return e.getContribution(NM.ID)}constructor(e,t){this.editor=e,this.selectionAnchorSetContextKey=fk.bindTo(t),this.modelChangeListener=e.onDidChangeModel(()=>this.selectionAnchorSetContextKey.reset())}setSelectionAnchor(){if(this.editor.hasModel()){const e=this.editor.getPosition();this.editor.changeDecorations(t=>{this.decorationId&&t.removeDecoration(this.decorationId),this.decorationId=t.addDecoration(we.fromPositions(e,e),{description:"selection-anchor",stickiness:1,hoverMessage:new ss().appendText(p("selectionAnchor","Selection Anchor")),className:"selection-anchor"})}),this.selectionAnchorSetContextKey.set(!!this.decorationId),fo(p("anchorSet","Anchor set at {0}:{1}",e.lineNumber,e.column))}}goToSelectionAnchor(){if(this.editor.hasModel()&&this.decorationId){const e=this.editor.getModel().getDecorationRange(this.decorationId);e&&this.editor.setPosition(e.getStartPosition())}}selectFromAnchorToCursor(){if(this.editor.hasModel()&&this.decorationId){const e=this.editor.getModel().getDecorationRange(this.decorationId);if(e){const t=this.editor.getPosition();this.editor.setSelection(we.fromPositions(e.getStartPosition(),t)),this.cancelSelectionAnchor()}}}cancelSelectionAnchor(){if(this.decorationId){const e=this.decorationId;this.editor.changeDecorations(t=>{t.removeDecoration(e),this.decorationId=void 0}),this.selectionAnchorSetContextKey.set(!1)}}dispose(){this.cancelSelectionAnchor(),this.modelChangeListener.dispose()}};jc.ID="editor.contrib.selectionAnchorController";jc=NM=JLe([exe(1,Be)],jc);class txe extends me{constructor(){super({id:"editor.action.setSelectionAnchor",label:p("setSelectionAnchor","Set Selection Anchor"),alias:"Set Selection Anchor",precondition:void 0,kbOpts:{kbExpr:T.editorTextFocus,primary:an(2089,2080),weight:100}})}async run(e,t){var i;(i=jc.get(t))===null||i===void 0||i.setSelectionAnchor()}}class ixe extends me{constructor(){super({id:"editor.action.goToSelectionAnchor",label:p("goToSelectionAnchor","Go to Selection Anchor"),alias:"Go to Selection Anchor",precondition:fk})}async run(e,t){var i;(i=jc.get(t))===null||i===void 0||i.goToSelectionAnchor()}}class nxe extends me{constructor(){super({id:"editor.action.selectFromAnchorToCursor",label:p("selectFromAnchorToCursor","Select from Anchor to Cursor"),alias:"Select from Anchor to Cursor",precondition:fk,kbOpts:{kbExpr:T.editorTextFocus,primary:an(2089,2089),weight:100}})}async run(e,t){var i;(i=jc.get(t))===null||i===void 0||i.selectFromAnchorToCursor()}}class sxe extends me{constructor(){super({id:"editor.action.cancelSelectionAnchor",label:p("cancelSelectionAnchor","Cancel Selection Anchor"),alias:"Cancel Selection Anchor",precondition:fk,kbOpts:{kbExpr:T.editorTextFocus,primary:9,weight:100}})}async run(e,t){var i;(i=jc.get(t))===null||i===void 0||i.cancelSelectionAnchor()}}kt(jc.ID,jc,4);te(txe);te(ixe);te(nxe);te(sxe);const oxe=N("editorOverviewRuler.bracketMatchForeground",{dark:"#A0A0A0",light:"#A0A0A0",hcDark:"#A0A0A0",hcLight:"#A0A0A0"},p("overviewRulerBracketMatchForeground","Overview ruler marker color for matching brackets."));class rxe extends me{constructor(){super({id:"editor.action.jumpToBracket",label:p("smartSelect.jumpBracket","Go to Bracket"),alias:"Go to Bracket",precondition:void 0,kbOpts:{kbExpr:T.editorTextFocus,primary:3165,weight:100}})}run(e,t){var i;(i=ga.get(t))===null||i===void 0||i.jumpToBracket()}}class axe extends me{constructor(){super({id:"editor.action.selectToBracket",label:p("smartSelect.selectToBracket","Select to Bracket"),alias:"Select to Bracket",precondition:void 0,metadata:{description:Ve("smartSelect.selectToBracketDescription","Select the text inside and including the brackets or curly braces"),args:[{name:"args",schema:{type:"object",properties:{selectBrackets:{type:"boolean",default:!0}}}}]}})}run(e,t,i){var n;let o=!0;i&&i.selectBrackets===!1&&(o=!1),(n=ga.get(t))===null||n===void 0||n.selectToBracket(o)}}class lxe extends me{constructor(){super({id:"editor.action.removeBrackets",label:p("smartSelect.removeBrackets","Remove Brackets"),alias:"Remove Brackets",precondition:void 0,kbOpts:{kbExpr:T.editorTextFocus,primary:2561,weight:100}})}run(e,t){var i;(i=ga.get(t))===null||i===void 0||i.removeBrackets(this.id)}}class dxe{constructor(e,t,i){this.position=e,this.brackets=t,this.options=i}}class ga extends H{static get(e){return e.getContribution(ga.ID)}constructor(e){super(),this._editor=e,this._lastBracketsData=[],this._lastVersionId=0,this._decorations=this._editor.createDecorationsCollection(),this._updateBracketsSoon=this._register(new Wt(()=>this._updateBrackets(),50)),this._matchBrackets=this._editor.getOption(72),this._updateBracketsSoon.schedule(),this._register(e.onDidChangeCursorPosition(t=>{this._matchBrackets!=="never"&&this._updateBracketsSoon.schedule()})),this._register(e.onDidChangeModelContent(t=>{this._updateBracketsSoon.schedule()})),this._register(e.onDidChangeModel(t=>{this._lastBracketsData=[],this._updateBracketsSoon.schedule()})),this._register(e.onDidChangeModelLanguageConfiguration(t=>{this._lastBracketsData=[],this._updateBracketsSoon.schedule()})),this._register(e.onDidChangeConfiguration(t=>{t.hasChanged(72)&&(this._matchBrackets=this._editor.getOption(72),this._decorations.clear(),this._lastBracketsData=[],this._lastVersionId=0,this._updateBracketsSoon.schedule())})),this._register(e.onDidBlurEditorWidget(()=>{this._updateBracketsSoon.schedule()})),this._register(e.onDidFocusEditorWidget(()=>{this._updateBracketsSoon.schedule()}))}jumpToBracket(){if(!this._editor.hasModel())return;const e=this._editor.getModel(),t=this._editor.getSelections().map(i=>{const n=i.getStartPosition(),o=e.bracketPairs.matchBracket(n);let r=null;if(o)o[0].containsPosition(n)&&!o[1].containsPosition(n)?r=o[1].getStartPosition():o[1].containsPosition(n)&&(r=o[0].getStartPosition());else{const a=e.bracketPairs.findEnclosingBrackets(n);if(a)r=a[1].getStartPosition();else{const l=e.bracketPairs.findNextBracket(n);l&&l.range&&(r=l.range.getStartPosition())}}return r?new we(r.lineNumber,r.column,r.lineNumber,r.column):new we(n.lineNumber,n.column,n.lineNumber,n.column)});this._editor.setSelections(t),this._editor.revealRange(t[0])}selectToBracket(e){if(!this._editor.hasModel())return;const t=this._editor.getModel(),i=[];this._editor.getSelections().forEach(n=>{const o=n.getStartPosition();let r=t.bracketPairs.matchBracket(o);if(!r&&(r=t.bracketPairs.findEnclosingBrackets(o),!r)){const d=t.bracketPairs.findNextBracket(o);d&&d.range&&(r=t.bracketPairs.matchBracket(d.range.getStartPosition()))}let a=null,l=null;if(r){r.sort(x.compareRangesUsingStarts);const[d,c]=r;if(a=e?d.getStartPosition():d.getEndPosition(),l=e?c.getEndPosition():c.getStartPosition(),c.containsPosition(o)){const u=a;a=l,l=u}}a&&l&&i.push(new we(a.lineNumber,a.column,l.lineNumber,l.column))}),i.length>0&&(this._editor.setSelections(i),this._editor.revealRange(i[0]))}removeBrackets(e){if(!this._editor.hasModel())return;const t=this._editor.getModel();this._editor.getSelections().forEach(i=>{const n=i.getPosition();let o=t.bracketPairs.matchBracket(n);o||(o=t.bracketPairs.findEnclosingBrackets(n)),o&&(this._editor.pushUndoStop(),this._editor.executeEdits(e,[{range:o[0],text:""},{range:o[1],text:""}]),this._editor.pushUndoStop())})}_updateBrackets(){if(this._matchBrackets==="never")return;this._recomputeBrackets();const e=[];let t=0;for(const i of this._lastBracketsData){const n=i.brackets;n&&(e[t++]={range:n[0],options:i.options},e[t++]={range:n[1],options:i.options})}this._decorations.set(e)}_recomputeBrackets(){if(!this._editor.hasModel()||!this._editor.hasWidgetFocus()){this._lastBracketsData=[],this._lastVersionId=0;return}const e=this._editor.getSelections();if(e.length>100){this._lastBracketsData=[],this._lastVersionId=0;return}const t=this._editor.getModel(),i=t.getVersionId();let n=[];this._lastVersionId===i&&(n=this._lastBracketsData);const o=[];let r=0;for(let u=0,h=e.length;u1&&o.sort(W.compare);const a=[];let l=0,d=0;const c=n.length;for(let u=0,h=o.length;u0&&(t.pushUndoStop(),t.executeCommands(this.id,n),t.pushUndoStop())}}te(gxe);const pk=function(){if(typeof crypto=="object"&&typeof crypto.randomUUID=="function")return crypto.randomUUID.bind(crypto);let s;typeof crypto=="object"&&typeof crypto.getRandomValues=="function"?s=crypto.getRandomValues.bind(crypto):s=function(i){for(let n=0;ns,asFile:()=>{},value:typeof s=="string"?s:void 0}}function fxe(s,e,t){const i={id:pk(),name:s,uri:e,data:t};return{asString:async()=>"",asFile:()=>i,value:void 0}}class $K{constructor(){this._entries=new Map}get size(){let e=0;for(const t of this._entries)e++;return e}has(e){return this._entries.has(this.toKey(e))}matches(e){const t=[...this._entries.keys()];return ft.some(this,([i,n])=>n.asFile())&&t.push("files"),KK(rL(e),t)}get(e){var t;return(t=this._entries.get(this.toKey(e)))===null||t===void 0?void 0:t[0]}append(e,t){const i=this._entries.get(e);i?i.push(t):this._entries.set(this.toKey(e),[t])}replace(e,t){this._entries.set(this.toKey(e),[t])}delete(e){this._entries.delete(this.toKey(e))}*[Symbol.iterator](){for(const[e,t]of this._entries)for(const i of t)yield[e,i]}toKey(e){return rL(e)}}function rL(s){return s.toLowerCase()}function jK(s,e){return KK(rL(s),e.map(rL))}function KK(s,e){if(s==="*/*")return e.length>0;if(e.includes(s))return!0;const t=s.match(/^([a-z]+)\/([a-z]+|\*)$/i);if(!t)return!1;const[i,n,o]=t;return o==="*"?e.some(r=>r.startsWith(n+"/")):!1}const mk=Object.freeze({create:s=>Wc(s.map(e=>e.toString())).join(`\r `),split:s=>s.split(`\r `),parse:s=>mk.split(s).filter(e=>!e.startsWith("#"))});class Bt{constructor(e){this.value=e}equals(e){return this.value===e.value}contains(e){return this.equals(e)||this.value===""||e.value.startsWith(this.value+Bt.sep)}intersects(e){return this.contains(e)||e.contains(this)}append(...e){return new Bt((this.value?[this.value,...e]:e).join(Bt.sep))}}Bt.sep=".";Bt.None=new Bt("@@none@@");Bt.Empty=new Bt("");const A7={EDITORS:"CodeEditors",FILES:"CodeFiles"};class pxe{}const mxe={DragAndDropContribution:"workbench.contributions.dragAndDrop"};Ji.add(mxe.DragAndDropContribution,new pxe);class IC{constructor(){}static getInstance(){return IC.INSTANCE}hasData(e){return e&&e===this.proto}getData(e){if(this.hasData(e))return this.data}}IC.INSTANCE=new IC;function qK(s){const e=new $K;for(const t of s.items){const i=t.type;if(t.kind==="string"){const n=new Promise(o=>t.getAsString(o));e.append(i,o4(n))}else if(t.kind==="file"){const n=t.getAsFile();n&&e.append(i,_xe(n))}}return e}function _xe(s){const e=s.path?Ae.parse(s.path):void 0;return fxe(s.name,e,async()=>new Uint8Array(await s.arrayBuffer()))}const vxe=Object.freeze([A7.EDITORS,A7.FILES,uC.RESOURCES,uC.INTERNAL_URI_LIST]);function GK(s,e=!1){const t=qK(s),i=t.get(uC.INTERNAL_URI_LIST);if(i)t.replace(Ti.uriList,i);else if(e||!t.has(Ti.uriList)){const n=[];for(const o of s.items){const r=o.getAsFile();if(r){const a=r.path;try{a?n.push(Ae.file(a).toString()):n.push(Ae.parse(r.name,!0).toString())}catch{}}}n.length&&t.replace(Ti.uriList,o4(mk.create(n)))}for(const n of vxe)t.delete(n);return t}var r4=function(s,e,t,i){var n=arguments.length,o=n<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,r;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(s,e,t,i);else for(var a=s.length-1;a>=0;a--)(r=s[a])&&(o=(n<3?r(o):n>3?r(e,t,o):r(e,t))||o);return n>3&&o&&Object.defineProperty(e,t,o),o},TC=function(s,e){return function(t,i){e(t,i,s)}};class a4{async provideDocumentPasteEdits(e,t,i,n,o){const r=await this.getEdit(i,o);if(r)return{dispose(){},edits:[{insertText:r.insertText,title:r.title,kind:r.kind,handledMimeType:r.handledMimeType,yieldTo:r.yieldTo}]}}async provideDocumentDropEdits(e,t,i,n){const o=await this.getEdit(i,n);return o?[{insertText:o.insertText,title:o.title,kind:o.kind,handledMimeType:o.handledMimeType,yieldTo:o.yieldTo}]:void 0}}class Kc extends a4{constructor(){super(...arguments),this.kind=Kc.kind,this.dropMimeTypes=[Ti.text],this.pasteMimeTypes=[Ti.text]}async getEdit(e,t){const i=e.get(Ti.text);if(!i||e.has(Ti.uriList))return;const n=await i.asString();return{handledMimeType:Ti.text,title:p("text.label","Insert Plain Text"),insertText:n,kind:this.kind}}}Kc.id="text";Kc.kind=new Bt("text.plain");class ZK extends a4{constructor(){super(...arguments),this.kind=new Bt("uri.absolute"),this.dropMimeTypes=[Ti.uriList],this.pasteMimeTypes=[Ti.uriList]}async getEdit(e,t){const i=await XK(e);if(!i.length||t.isCancellationRequested)return;let n=0;const o=i.map(({uri:a,originalText:l})=>a.scheme===Ge.file?a.fsPath:(n++,l)).join(" ");let r;return n>0?r=i.length>1?p("defaultDropProvider.uriList.uris","Insert Uris"):p("defaultDropProvider.uriList.uri","Insert Uri"):r=i.length>1?p("defaultDropProvider.uriList.paths","Insert Paths"):p("defaultDropProvider.uriList.path","Insert Path"),{handledMimeType:Ti.uriList,insertText:o,title:r,kind:this.kind}}}let aL=class extends a4{constructor(e){super(),this._workspaceContextService=e,this.kind=new Bt("uri.relative"),this.dropMimeTypes=[Ti.uriList],this.pasteMimeTypes=[Ti.uriList]}async getEdit(e,t){const i=await XK(e);if(!i.length||t.isCancellationRequested)return;const n=pd(i.map(({uri:o})=>{const r=this._workspaceContextService.getWorkspaceFolder(o);return r?Sme(r.uri,o):void 0}));if(n.length)return{handledMimeType:Ti.uriList,insertText:n.join(" "),title:i.length>1?p("defaultDropProvider.uriList.relativePaths","Insert Relative Paths"):p("defaultDropProvider.uriList.relativePath","Insert Relative Path"),kind:this.kind}}};aL=r4([TC(0,If)],aL);class bxe{constructor(){this.kind=new Bt("html"),this.pasteMimeTypes=["text/html"],this._yieldTo=[{mimeType:Ti.text}]}async provideDocumentPasteEdits(e,t,i,n,o){var r;if(n.triggerKind!==Nb.PasteAs&&!(!((r=n.only)===null||r===void 0)&&r.contains(this.kind)))return;const a=i.get("text/html"),l=await(a==null?void 0:a.asString());if(!(!l||o.isCancellationRequested))return{dispose(){},edits:[{insertText:l,yieldTo:this._yieldTo,title:p("pasteHtmlLabel","Insert HTML"),kind:this.kind}]}}}async function XK(s){const e=s.get(Ti.uriList);if(!e)return[];const t=await e.asString(),i=[];for(const n of mk.parse(t))try{i.push({uri:Ae.parse(n),originalText:n})}catch{}return i}let AM=class extends H{constructor(e,t){super(),this._register(e.documentDropEditProvider.register("*",new Kc)),this._register(e.documentDropEditProvider.register("*",new ZK)),this._register(e.documentDropEditProvider.register("*",new aL(t)))}};AM=r4([TC(0,Ce),TC(1,If)],AM);let MM=class extends H{constructor(e,t){super(),this._register(e.documentPasteEditProvider.register("*",new Kc)),this._register(e.documentPasteEditProvider.register("*",new ZK)),this._register(e.documentPasteEditProvider.register("*",new aL(t))),this._register(e.documentPasteEditProvider.register("*",new bxe))}};MM=r4([TC(0,Ce),TC(1,If)],MM);class ea{constructor(){this.value="",this.pos=0}static isDigitCharacter(e){return e>=48&&e<=57}static isVariableCharacter(e){return e===95||e>=97&&e<=122||e>=65&&e<=90}text(e){this.value=e,this.pos=0}tokenText(e){return this.value.substr(e.pos,e.len)}next(){if(this.pos>=this.value.length)return{type:14,pos:this.pos,len:0};const e=this.pos;let t=0,i=this.value.charCodeAt(e),n;if(n=ea._table[i],typeof n=="number")return this.pos+=1,{type:n,pos:e,len:1};if(ea.isDigitCharacter(i)){n=8;do t+=1,i=this.value.charCodeAt(e+t);while(ea.isDigitCharacter(i));return this.pos+=t,{type:n,pos:e,len:t}}if(ea.isVariableCharacter(i)){n=9;do i=this.value.charCodeAt(e+ ++t);while(ea.isVariableCharacter(i)||ea.isDigitCharacter(i));return this.pos+=t,{type:n,pos:e,len:t}}n=10;do t+=1,i=this.value.charCodeAt(e+t);while(!isNaN(i)&&typeof ea._table[i]>"u"&&!ea.isDigitCharacter(i)&&!ea.isVariableCharacter(i));return this.pos+=t,{type:n,pos:e,len:t}}}ea._table={36:0,58:1,44:2,123:3,125:4,92:5,47:6,124:7,43:11,45:12,63:13};class C0{constructor(){this._children=[]}appendChild(e){return e instanceof Ts&&this._children[this._children.length-1]instanceof Ts?this._children[this._children.length-1].value+=e.value:(e.parent=this,this._children.push(e)),this}replace(e,t){const{parent:i}=e,n=i.children.indexOf(e),o=i.children.slice(0);o.splice(n,1,...t),i._children=o,function r(a,l){for(const d of a)d.parent=l,r(d.children,d)}(t,i)}get children(){return this._children}get rightMostDescendant(){return this._children.length>0?this._children[this._children.length-1].rightMostDescendant:this}get snippet(){let e=this;for(;;){if(!e)return;if(e instanceof H1)return e;e=e.parent}}toString(){return this.children.reduce((e,t)=>e+t.toString(),"")}len(){return 0}}class Ts extends C0{constructor(e){super(),this.value=e}toString(){return this.value}len(){return this.value.length}clone(){return new Ts(this.value)}}class YK extends C0{}class yr extends YK{static compareByIndex(e,t){return e.index===t.index?0:e.isFinalTabstop?1:t.isFinalTabstop||e.indext.index?1:0}constructor(e){super(),this.index=e}get isFinalTabstop(){return this.index===0}get choice(){return this._children.length===1&&this._children[0]instanceof w0?this._children[0]:void 0}clone(){const e=new yr(this.index);return this.transform&&(e.transform=this.transform.clone()),e._children=this.children.map(t=>t.clone()),e}}class w0 extends C0{constructor(){super(...arguments),this.options=[]}appendChild(e){return e instanceof Ts&&(e.parent=this,this.options.push(e)),this}toString(){return this.options[0].value}len(){return this.options[0].len()}clone(){const e=new w0;return this.options.forEach(e.appendChild,e),e}}class l4 extends C0{constructor(){super(...arguments),this.regexp=new RegExp("")}resolve(e){const t=this;let i=!1,n=e.replace(this.regexp,function(){return i=!0,t._replace(Array.prototype.slice.call(arguments,0,-2))});return!i&&this._children.some(o=>o instanceof Oa&&!!o.elseValue)&&(n=this._replace([])),n}_replace(e){let t="";for(const i of this._children)if(i instanceof Oa){let n=e[i.index]||"";n=i.resolve(n),t+=n}else t+=i.toString();return t}toString(){return""}clone(){const e=new l4;return e.regexp=new RegExp(this.regexp.source,(this.regexp.ignoreCase?"i":"")+(this.regexp.global?"g":"")),e._children=this.children.map(t=>t.clone()),e}}class Oa extends C0{constructor(e,t,i,n){super(),this.index=e,this.shorthandName=t,this.ifValue=i,this.elseValue=n}resolve(e){return this.shorthandName==="upcase"?e?e.toLocaleUpperCase():"":this.shorthandName==="downcase"?e?e.toLocaleLowerCase():"":this.shorthandName==="capitalize"?e?e[0].toLocaleUpperCase()+e.substr(1):"":this.shorthandName==="pascalcase"?e?this._toPascalCase(e):"":this.shorthandName==="camelcase"?e?this._toCamelCase(e):"":e&&typeof this.ifValue=="string"?this.ifValue:!e&&typeof this.elseValue=="string"?this.elseValue:e||""}_toPascalCase(e){const t=e.match(/[a-z0-9]+/gi);return t?t.map(i=>i.charAt(0).toUpperCase()+i.substr(1)).join(""):e}_toCamelCase(e){const t=e.match(/[a-z0-9]+/gi);return t?t.map((i,n)=>n===0?i.charAt(0).toLowerCase()+i.substr(1):i.charAt(0).toUpperCase()+i.substr(1)).join(""):e}clone(){return new Oa(this.index,this.shorthandName,this.ifValue,this.elseValue)}}class NC extends YK{constructor(e){super(),this.name=e}resolve(e){let t=e.resolve(this);return this.transform&&(t=this.transform.resolve(t||"")),t!==void 0?(this._children=[new Ts(t)],!0):!1}clone(){const e=new NC(this.name);return this.transform&&(e.transform=this.transform.clone()),e._children=this.children.map(t=>t.clone()),e}}function M7(s,e){const t=[...s];for(;t.length>0;){const i=t.shift();if(!e(i))break;t.unshift(...i.children)}}class H1 extends C0{get placeholderInfo(){if(!this._placeholders){const e=[];let t;this.walk(function(i){return i instanceof yr&&(e.push(i),t=!t||t.indexn===e?(i=!0,!1):(t+=n.len(),!0)),i?t:-1}fullLen(e){let t=0;return M7([e],i=>(t+=i.len(),!0)),t}enclosingPlaceholders(e){const t=[];let{parent:i}=e;for(;i;)i instanceof yr&&t.push(i),i=i.parent;return t}resolveVariables(e){return this.walk(t=>(t instanceof NC&&t.resolve(e)&&(this._placeholders=void 0),!0)),this}appendChild(e){return this._placeholders=void 0,super.appendChild(e)}replace(e,t){return this._placeholders=void 0,super.replace(e,t)}clone(){const e=new H1;return this._children=this.children.map(t=>t.clone()),e}walk(e){M7(this.children,e)}}class Rf{constructor(){this._scanner=new ea,this._token={type:14,pos:0,len:0}}static escape(e){return e.replace(/\$|}|\\/g,"\\$&")}static guessNeedsClipboard(e){return/\${?CLIPBOARD/.test(e)}parse(e,t,i){const n=new H1;return this.parseFragment(e,n),this.ensureFinalTabstop(n,i??!1,t??!1),n}parseFragment(e,t){const i=t.children.length;for(this._scanner.text(e),this._token=this._scanner.next();this._parse(t););const n=new Map,o=[];t.walk(l=>(l instanceof yr&&(l.isFinalTabstop?n.set(0,void 0):!n.has(l.index)&&l.children.length>0?n.set(l.index,l.children):o.push(l)),!0));const r=(l,d)=>{const c=n.get(l.index);if(!c)return;const u=new yr(l.index);u.transform=l.transform;for(const h of c){const g=h.clone();u.appendChild(g),g instanceof yr&&n.has(g.index)&&!d.has(g.index)&&(d.add(g.index),r(g,d),d.delete(g.index))}t.replace(l,[u])},a=new Set;for(const l of o)r(l,a);return t.children.slice(i)}ensureFinalTabstop(e,t,i){(t||i&&e.placeholders.length>0)&&(e.placeholders.find(o=>o.index===0)||e.appendChild(new yr(0)))}_accept(e,t){if(e===void 0||this._token.type===e){const i=t?this._scanner.tokenText(this._token):!0;return this._token=this._scanner.next(),i}return!1}_backTo(e){return this._scanner.pos=e.pos+e.len,this._token=e,!1}_until(e){const t=this._token;for(;this._token.type!==e;){if(this._token.type===14)return!1;if(this._token.type===5){const n=this._scanner.next();if(n.type!==0&&n.type!==4&&n.type!==5)return!1}this._token=this._scanner.next()}const i=this._scanner.value.substring(t.pos,this._token.pos).replace(/\\(\$|}|\\)/g,"$1");return this._token=this._scanner.next(),i}_parse(e){return this._parseEscaped(e)||this._parseTabstopOrVariableName(e)||this._parseComplexPlaceholder(e)||this._parseComplexVariable(e)||this._parseAnything(e)}_parseEscaped(e){let t;return(t=this._accept(5,!0))?(t=this._accept(0,!0)||this._accept(4,!0)||this._accept(5,!0)||t,e.appendChild(new Ts(t)),!0):!1}_parseTabstopOrVariableName(e){let t;const i=this._token;return this._accept(0)&&(t=this._accept(9,!0)||this._accept(8,!0))?(e.appendChild(/^\d+$/.test(t)?new yr(Number(t)):new NC(t)),!0):this._backTo(i)}_parseComplexPlaceholder(e){let t;const i=this._token;if(!(this._accept(0)&&this._accept(3)&&(t=this._accept(8,!0))))return this._backTo(i);const o=new yr(Number(t));if(this._accept(1))for(;;){if(this._accept(4))return e.appendChild(o),!0;if(!this._parse(o))return e.appendChild(new Ts("${"+t+":")),o.children.forEach(e.appendChild,e),!0}else if(o.index>0&&this._accept(7)){const r=new w0;for(;;){if(this._parseChoiceElement(r)){if(this._accept(2))continue;if(this._accept(7)&&(o.appendChild(r),this._accept(4)))return e.appendChild(o),!0}return this._backTo(i),!1}}else return this._accept(6)?this._parseTransform(o)?(e.appendChild(o),!0):(this._backTo(i),!1):this._accept(4)?(e.appendChild(o),!0):this._backTo(i)}_parseChoiceElement(e){const t=this._token,i=[];for(;!(this._token.type===2||this._token.type===7);){let n;if((n=this._accept(5,!0))?n=this._accept(2,!0)||this._accept(7,!0)||this._accept(5,!0)||n:n=this._accept(void 0,!0),!n)return this._backTo(t),!1;i.push(n)}return i.length===0?(this._backTo(t),!1):(e.appendChild(new Ts(i.join(""))),!0)}_parseComplexVariable(e){let t;const i=this._token;if(!(this._accept(0)&&this._accept(3)&&(t=this._accept(9,!0))))return this._backTo(i);const o=new NC(t);if(this._accept(1))for(;;){if(this._accept(4))return e.appendChild(o),!0;if(!this._parse(o))return e.appendChild(new Ts("${"+t+":")),o.children.forEach(e.appendChild,e),!0}else return this._accept(6)?this._parseTransform(o)?(e.appendChild(o),!0):(this._backTo(i),!1):this._accept(4)?(e.appendChild(o),!0):this._backTo(i)}_parseTransform(e){const t=new l4;let i="",n="";for(;!this._accept(6);){let o;if(o=this._accept(5,!0)){o=this._accept(6,!0)||o,i+=o;continue}if(this._token.type!==14){i+=this._accept(void 0,!0);continue}return!1}for(;!this._accept(6);){let o;if(o=this._accept(5,!0)){o=this._accept(5,!0)||this._accept(6,!0)||o,t.appendChild(new Ts(o));continue}if(!(this._parseFormatString(t)||this._parseAnything(t)))return!1}for(;!this._accept(4);){if(this._token.type!==14){n+=this._accept(void 0,!0);continue}return!1}try{t.regexp=new RegExp(i,n)}catch{return!1}return e.transform=t,!0}_parseFormatString(e){const t=this._token;if(!this._accept(0))return!1;let i=!1;this._accept(3)&&(i=!0);const n=this._accept(8,!0);if(n)if(i){if(this._accept(4))return e.appendChild(new Oa(Number(n))),!0;if(!this._accept(1))return this._backTo(t),!1}else return e.appendChild(new Oa(Number(n))),!0;else return this._backTo(t),!1;if(this._accept(6)){const o=this._accept(9,!0);return!o||!this._accept(4)?(this._backTo(t),!1):(e.appendChild(new Oa(Number(n),o)),!0)}else if(this._accept(11)){const o=this._until(4);if(o)return e.appendChild(new Oa(Number(n),void 0,o,void 0)),!0}else if(this._accept(12)){const o=this._until(4);if(o)return e.appendChild(new Oa(Number(n),void 0,void 0,o)),!0}else if(this._accept(13)){const o=this._until(1);if(o){const r=this._until(4);if(r)return e.appendChild(new Oa(Number(n),void 0,o,r)),!0}}else{const o=this._until(4);if(o)return e.appendChild(new Oa(Number(n),void 0,void 0,o)),!0}return this._backTo(t),!1}_parseAnything(e){return this._token.type!==14?(e.appendChild(new Ts(this._scanner.tokenText(this._token))),this._accept(void 0),!0):!1}}function QK(s,e,t){var i,n,o,r;return(typeof t.insertText=="string"?t.insertText==="":t.insertText.snippet==="")?{edits:(n=(i=t.additionalEdit)===null||i===void 0?void 0:i.edits)!==null&&n!==void 0?n:[]}:{edits:[...e.map(a=>new dh(s,{range:a,text:typeof t.insertText=="string"?Rf.escape(t.insertText)+"$0":t.insertText.snippet,insertAsSnippet:!0})),...(r=(o=t.additionalEdit)===null||o===void 0?void 0:o.edits)!==null&&r!==void 0?r:[]]}}function JK(s){var e;function t(a,l){return"mimeType"in a?a.mimeType===l.handledMimeType:!!l.kind&&a.kind.contains(l.kind)}const i=new Map;for(const a of s)for(const l of(e=a.yieldTo)!==null&&e!==void 0?e:[])for(const d of s)if(d!==a&&t(l,d)){let c=i.get(a);c||(c=[],i.set(a,c)),c.push(d)}if(!i.size)return Array.from(s);const n=new Set,o=[];function r(a){if(!a.length)return[];const l=a[0];if(o.includes(l))return console.warn("Yield to cycle detected",l),a;if(n.has(l))return r(a.slice(1));let d=[];const c=i.get(l);return c&&(o.push(l),d=r(c),o.pop()),n.add(l),[...d,l,...r(a.slice(1))]}return r(Array.from(s))}var Cxe=function(s,e,t,i){var n=arguments.length,o=n<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,r;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(s,e,t,i);else for(var a=s.length-1;a>=0;a--)(r=s[a])&&(o=(n<3?r(o):n>3?r(e,t,o):r(e,t))||o);return n>3&&o&&Object.defineProperty(e,t,o),o},wxe=function(s,e){return function(t,i){e(t,i,s)}};const yxe=Ye.register({description:"inline-progress-widget",stickiness:1,showIfCollapsed:!0,after:{content:cz,inlineClassName:"inline-editor-progress-decoration",inlineClassNameAffectsLetterSpacing:!0}});class _k extends H{constructor(e,t,i,n,o){super(),this.typeId=e,this.editor=t,this.range=i,this.delegate=o,this.allowEditorOverflow=!1,this.suppressMouseDown=!0,this.create(n),this.editor.addContentWidget(this),this.editor.layoutContentWidget(this)}create(e){this.domNode=he(".inline-progress-widget"),this.domNode.role="button",this.domNode.title=e;const t=he("span.icon");this.domNode.append(t),t.classList.add(...Pe.asClassNameArray(oe.loading),"codicon-modifier-spin");const i=()=>{const n=this.editor.getOption(67);this.domNode.style.height=`${n}px`,this.domNode.style.width=`${Math.ceil(.8*n)}px`};i(),this._register(this.editor.onDidChangeConfiguration(n=>{(n.hasChanged(52)||n.hasChanged(67))&&i()})),this._register(K(this.domNode,ee.CLICK,n=>{this.delegate.cancel()}))}getId(){return _k.baseId+"."+this.typeId}getDomNode(){return this.domNode}getPosition(){return{position:{lineNumber:this.range.startLineNumber,column:this.range.startColumn},preference:[0]}}dispose(){super.dispose(),this.editor.removeContentWidget(this)}}_k.baseId="editor.widget.inlineProgressWidget";let lL=class extends H{constructor(e,t,i){super(),this.id=e,this._editor=t,this._instantiationService=i,this._showDelay=500,this._showPromise=this._register(new $n),this._currentWidget=new $n,this._operationIdPool=0,this._currentDecorations=t.createDecorationsCollection()}async showWhile(e,t,i){const n=this._operationIdPool++;this._currentOperation=n,this.clear(),this._showPromise.value=kh(()=>{const o=x.fromPositions(e);this._currentDecorations.set([{range:o,options:yxe}]).length>0&&(this._currentWidget.value=this._instantiationService.createInstance(_k,this.id,this._editor,o,t,i))},this._showDelay);try{return await i}finally{this._currentOperation===n&&(this.clear(),this._currentOperation=void 0)}}clear(){this._showPromise.clear(),this._currentDecorations.clear(),this._currentWidget.clear()}};lL=Cxe([wxe(2,Ne)],lL);var Sxe=function(s,e,t,i){var n=arguments.length,o=n<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,r;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(s,e,t,i);else for(var a=s.length-1;a>=0;a--)(r=s[a])&&(o=(n<3?r(o):n>3?r(e,t,o):r(e,t))||o);return n>3&&o&&Object.defineProperty(e,t,o),o},R7=function(s,e){return function(t,i){e(t,i,s)}},lS;let Vs=lS=class{static get(e){return e.getContribution(lS.ID)}constructor(e,t,i){this._openerService=i,this._messageWidget=new $n,this._messageListeners=new Y,this._mouseOverMessage=!1,this._editor=e,this._visible=lS.MESSAGE_VISIBLE.bindTo(t)}dispose(){var e;(e=this._message)===null||e===void 0||e.dispose(),this._messageListeners.dispose(),this._messageWidget.dispose(),this._visible.reset()}showMessage(e,t){fo(tl(e)?e.value:e),this._visible.set(!0),this._messageWidget.clear(),this._messageListeners.clear(),this._message=tl(e)?Hx(e,{actionHandler:{callback:n=>{this.closeMessage(),wO(this._openerService,n,tl(e)?e.isTrusted:void 0)},disposables:this._messageListeners}}):void 0,this._messageWidget.value=new P7(this._editor,t,typeof e=="string"?e:this._message.element),this._messageListeners.add(le.debounce(this._editor.onDidBlurEditorText,(n,o)=>o,0)(()=>{this._mouseOverMessage||this._messageWidget.value&&An(Xn(),this._messageWidget.value.getDomNode())||this.closeMessage()})),this._messageListeners.add(this._editor.onDidChangeCursorPosition(()=>this.closeMessage())),this._messageListeners.add(this._editor.onDidDispose(()=>this.closeMessage())),this._messageListeners.add(this._editor.onDidChangeModel(()=>this.closeMessage())),this._messageListeners.add(K(this._messageWidget.value.getDomNode(),ee.MOUSE_ENTER,()=>this._mouseOverMessage=!0,!0)),this._messageListeners.add(K(this._messageWidget.value.getDomNode(),ee.MOUSE_LEAVE,()=>this._mouseOverMessage=!1,!0));let i;this._messageListeners.add(this._editor.onMouseMove(n=>{n.target.position&&(i?i.containsPosition(n.target.position)||this.closeMessage():i=new x(t.lineNumber-3,1,n.target.position.lineNumber+3,1))}))}closeMessage(){this._visible.reset(),this._messageListeners.clear(),this._messageWidget.value&&this._messageListeners.add(P7.fadeOut(this._messageWidget.value))}};Vs.ID="editor.contrib.messageController";Vs.MESSAGE_VISIBLE=new ue("messageVisible",!1,p("messageVisible","Whether the editor is currently showing an inline message"));Vs=lS=Sxe([R7(1,Be),R7(2,Bo)],Vs);const Dxe=mn.bindToContribution(Vs.get);de(new Dxe({id:"leaveEditorMessage",precondition:Vs.MESSAGE_VISIBLE,handler:s=>s.closeMessage(),kbOpts:{weight:130,primary:9}}));let P7=class{static fadeOut(e){const t=()=>{e.dispose(),clearTimeout(i),e.getDomNode().removeEventListener("animationend",t)},i=setTimeout(t,110);return e.getDomNode().addEventListener("animationend",t),e.getDomNode().classList.add("fadeOut"),{dispose:t}}constructor(e,{lineNumber:t,column:i},n){this.allowEditorOverflow=!0,this.suppressMouseDown=!1,this._editor=e,this._editor.revealLinesInCenterIfOutsideViewport(t,t,0),this._position={lineNumber:t,column:i},this._domNode=document.createElement("div"),this._domNode.classList.add("monaco-editor-overlaymessage"),this._domNode.style.marginLeft="-6px";const o=document.createElement("div");o.classList.add("anchor","top"),this._domNode.appendChild(o);const r=document.createElement("div");typeof n=="string"?(r.classList.add("message"),r.textContent=n):(n.classList.add("message"),r.appendChild(n)),this._domNode.appendChild(r);const a=document.createElement("div");a.classList.add("anchor","below"),this._domNode.appendChild(a),this._editor.addContentWidget(this),this._domNode.classList.add("fadeIn")}dispose(){this._editor.removeContentWidget(this)}getId(){return"messageoverlay"}getDomNode(){return this._domNode}getPosition(){return{position:this._position,preference:[1,2],positionAffinity:1}}afterRender(e){this._domNode.classList.toggle("below",e===2)}};kt(Vs.ID,Vs,4);var eq=function(s,e,t,i){var n=arguments.length,o=n<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,r;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(s,e,t,i);else for(var a=s.length-1;a>=0;a--)(r=s[a])&&(o=(n<3?r(o):n>3?r(e,t,o):r(e,t))||o);return n>3&&o&&Object.defineProperty(e,t,o),o},ub=function(s,e){return function(t,i){e(t,i,s)}},RM;let dL=RM=class extends H{constructor(e,t,i,n,o,r,a,l,d,c){super(),this.typeId=e,this.editor=t,this.showCommand=n,this.range=o,this.edits=r,this.onSelectNewEdit=a,this._contextMenuService=l,this._keybindingService=c,this.allowEditorOverflow=!0,this.suppressMouseDown=!0,this.create(),this.visibleContext=i.bindTo(d),this.visibleContext.set(!0),this._register(Ie(()=>this.visibleContext.reset())),this.editor.addContentWidget(this),this.editor.layoutContentWidget(this),this._register(Ie(()=>this.editor.removeContentWidget(this))),this._register(this.editor.onDidChangeCursorPosition(u=>{o.containsPosition(u.position)||this.dispose()})),this._register(le.runAndSubscribe(c.onDidUpdateKeybindings,()=>{this._updateButtonTitle()}))}_updateButtonTitle(){var e;const t=(e=this._keybindingService.lookupKeybinding(this.showCommand.id))===null||e===void 0?void 0:e.getLabel();this.button.element.title=this.showCommand.label+(t?` (${t})`:"")}create(){this.domNode=he(".post-edit-widget"),this.button=this._register(new KD(this.domNode,{supportIcons:!0})),this.button.label="$(insert)",this._register(K(this.domNode,ee.CLICK,()=>this.showSelector()))}getId(){return RM.baseId+"."+this.typeId}getDomNode(){return this.domNode}getPosition(){return{position:this.range.getEndPosition(),preference:[2]}}showSelector(){this._contextMenuService.showContextMenu({getAnchor:()=>{const e=qi(this.button.element);return{x:e.left+e.width,y:e.top+e.height}},getActions:()=>this.edits.allEdits.map((e,t)=>af({id:"",label:e.title,checked:t===this.edits.activeEditIndex,run:()=>{if(t!==this.edits.activeEditIndex)return this.onSelectNewEdit(t)}}))})}};dL.baseId="editor.widget.postEditWidget";dL=RM=eq([ub(7,Oo),ub(8,Be),ub(9,At)],dL);let cL=class extends H{constructor(e,t,i,n,o,r){super(),this._id=e,this._editor=t,this._visibleContext=i,this._showCommand=n,this._instantiationService=o,this._bulkEditService=r,this._currentWidget=this._register(new $n),this._register(le.any(t.onDidChangeModel,t.onDidChangeModelContent)(()=>this.clear()))}async applyEditAndShowIfNeeded(e,t,i,n,o){const r=this._editor.getModel();if(!r||!e.length)return;const a=t.allEdits.at(t.activeEditIndex);if(!a)return;const l=await n(a,o);if(o.isCancellationRequested)return;const d=QK(r.uri,e,l),c=e[0],u=r.deltaDecorations([],[{range:c,options:{description:"paste-line-suffix",stickiness:0}}]);this._editor.focus();let h,g;try{h=await this._bulkEditService.apply(d,{editor:this._editor,token:o}),g=r.getDecorationRange(u[0])}finally{r.deltaDecorations(u,[])}o.isCancellationRequested||i&&h.isApplied&&t.allEdits.length>1&&this.show(g??c,t,async f=>{const m=this._editor.getModel();m&&(await m.undo(),this.applyEditAndShowIfNeeded(e,{activeEditIndex:f,allEdits:t.allEdits},i,n,o))})}show(e,t,i){this.clear(),this._editor.hasModel()&&(this._currentWidget.value=this._instantiationService.createInstance(dL,this._id,this._editor,this._visibleContext,this._showCommand,e,t,i))}clear(){this._currentWidget.clear()}tryShowSelector(){var e;(e=this._currentWidget.value)===null||e===void 0||e.showSelector()}};cL=eq([ub(4,Ne),ub(5,x1)],cL);var Lxe=function(s,e,t,i){var n=arguments.length,o=n<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,r;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(s,e,t,i);else for(var a=s.length-1;a>=0;a--)(r=s[a])&&(o=(n<3?r(o):n>3?r(e,t,o):r(e,t))||o);return n>3&&o&&Object.defineProperty(e,t,o),o},Mp=function(s,e){return function(t,i){e(t,i,s)}},Mg;const tq="editor.changePasteType",d4=new ue("pasteWidgetVisible",!1,p("pasteWidgetVisible","Whether the paste widget is showing")),iT="application/vnd.code.copyMetadata";let kd=Mg=class extends H{static get(e){return e.getContribution(Mg.ID)}constructor(e,t,i,n,o,r,a){super(),this._bulkEditService=i,this._clipboardService=n,this._languageFeaturesService=o,this._quickInputService=r,this._progressService=a,this._editor=e;const l=e.getContainerDomNode();this._register(K(l,"copy",d=>this.handleCopy(d))),this._register(K(l,"cut",d=>this.handleCopy(d))),this._register(K(l,"paste",d=>this.handlePaste(d),!0)),this._pasteProgressManager=this._register(new lL("pasteIntoEditor",e,t)),this._postPasteWidgetManager=this._register(t.createInstance(cL,"pasteIntoEditor",e,d4,{id:tq,label:p("postPasteWidgetTitle","Show paste options...")}))}changePasteType(){this._postPasteWidgetManager.tryShowSelector()}pasteAs(e){this._editor.focus();try{this._pasteAsActionContext={preferred:e},o0().execCommand("paste")}finally{this._pasteAsActionContext=void 0}}clearWidgets(){this._postPasteWidgetManager.clear()}isPasteAsEnabled(){return this._editor.getOption(85).enabled&&!this._editor.getOption(91)}async finishedPaste(){await this._currentPasteOperation}handleCopy(e){var t,i;if(!this._editor.hasTextFocus()||(Jh&&this._clipboardService.writeResources([]),!e.clipboardData||!this.isPasteAsEnabled()))return;const n=this._editor.getModel(),o=this._editor.getSelections();if(!n||!(o!=null&&o.length))return;const r=this._editor.getOption(37);let a=o;const l=o.length===1&&o[0].isEmpty();if(l){if(!r)return;a=[new x(a[0].startLineNumber,1,a[0].startLineNumber,1+n.getLineLength(a[0].startLineNumber))]}const d=(t=this._editor._getViewModel())===null||t===void 0?void 0:t.getPlainTextToCopy(o,r,as),u={multicursorText:Array.isArray(d)?d:null,pasteOnNewLine:l,mode:null},h=this._languageFeaturesService.documentPasteEditProvider.ordered(n).filter(v=>!!v.prepareDocumentPaste);if(!h.length){this.setCopyMetadata(e.clipboardData,{defaultPastePayload:u});return}const g=qK(e.clipboardData),f=h.flatMap(v=>{var b;return(b=v.copyMimeTypes)!==null&&b!==void 0?b:[]}),m=pk();this.setCopyMetadata(e.clipboardData,{id:m,providerCopyMimeTypes:f,defaultPastePayload:u});const _=Dn(async v=>{const b=pd(await Promise.all(h.map(async C=>{try{return await C.prepareDocumentPaste(n,a,g,v)}catch(w){console.error(w);return}})));b.reverse();for(const C of b)for(const[w,y]of C)g.replace(w,y);return g});(i=Mg._currentCopyOperation)===null||i===void 0||i.dataTransferPromise.cancel(),Mg._currentCopyOperation={handle:m,dataTransferPromise:_}}async handlePaste(e){var t,i,n,o;if(!e.clipboardData||!this._editor.hasTextFocus())return;(t=Vs.get(this._editor))===null||t===void 0||t.closeMessage(),(i=this._currentPasteOperation)===null||i===void 0||i.cancel(),this._currentPasteOperation=void 0;const r=this._editor.getModel(),a=this._editor.getSelections();if(!(a!=null&&a.length)||!r||!this.isPasteAsEnabled()&&!this._pasteAsActionContext)return;const l=this.fetchCopyMetadata(e),d=GK(e.clipboardData);d.delete(iT);const c=[...e.clipboardData.types,...(n=l==null?void 0:l.providerCopyMimeTypes)!==null&&n!==void 0?n:[],Ti.uriList],u=this._languageFeaturesService.documentPasteEditProvider.ordered(r).filter(h=>{var g,f;const m=(g=this._pasteAsActionContext)===null||g===void 0?void 0:g.preferred;return m&&h.providedPasteEditKinds&&!this.providerMatchesPreference(h,m)?!1:(f=h.pasteMimeTypes)===null||f===void 0?void 0:f.some(_=>jK(_,c))});if(!u.length){!((o=this._pasteAsActionContext)===null||o===void 0)&&o.preferred&&this.showPasteAsNoEditMessage(a,this._pasteAsActionContext.preferred);return}e.preventDefault(),e.stopImmediatePropagation(),this._pasteAsActionContext?this.showPasteAsPick(this._pasteAsActionContext.preferred,u,a,d,l):this.doPasteInline(u,a,d,l,e)}showPasteAsNoEditMessage(e,t){var i;(i=Vs.get(this._editor))===null||i===void 0||i.showMessage(p("pasteAsError","No paste edits for '{0}' found",t instanceof Bt?t.value:t.providerId),e[0].getStartPosition())}doPasteInline(e,t,i,n,o){const r=Dn(async a=>{const l=this._editor;if(!l.hasModel())return;const d=l.getModel(),c=new Bh(l,3,void 0,a);try{if(await this.mergeInDataFromCopy(i,n,c.token),c.token.isCancellationRequested)return;const u=e.filter(f=>this.isSupportedPasteProvider(f,i));if(!u.length||u.length===1&&u[0]instanceof Kc)return this.applyDefaultPasteHandler(i,n,c.token,o);const h={triggerKind:Nb.Automatic},g=await this.getPasteEdits(u,i,d,t,h,c.token);if(c.token.isCancellationRequested)return;if(g.length===1&&g[0].provider instanceof Kc)return this.applyDefaultPasteHandler(i,n,c.token,o);if(g.length){const f=l.getOption(85).showPasteSelector==="afterPaste";return this._postPasteWidgetManager.applyEditAndShowIfNeeded(t,{activeEditIndex:0,allEdits:g},f,async(m,_)=>{var v,b;const C=await((b=(v=m.provider).resolveDocumentPasteEdit)===null||b===void 0?void 0:b.call(v,m,_));return C&&(m.additionalEdit=C.additionalEdit),m},c.token)}await this.applyDefaultPasteHandler(i,n,c.token,o)}finally{c.dispose(),this._currentPasteOperation===r&&(this._currentPasteOperation=void 0)}});this._pasteProgressManager.showWhile(t[0].getEndPosition(),p("pasteIntoEditorProgress","Running paste handlers. Click to cancel"),r),this._currentPasteOperation=r}showPasteAsPick(e,t,i,n,o){const r=Dn(async a=>{const l=this._editor;if(!l.hasModel())return;const d=l.getModel(),c=new Bh(l,3,void 0,a);try{if(await this.mergeInDataFromCopy(n,o,c.token),c.token.isCancellationRequested)return;let u=t.filter(_=>this.isSupportedPasteProvider(_,n,e));e&&(u=u.filter(_=>this.providerMatchesPreference(_,e)));const h={triggerKind:Nb.PasteAs,only:e&&e instanceof Bt?e:void 0};let g=await this.getPasteEdits(u,n,d,i,h,c.token);if(c.token.isCancellationRequested)return;if(e&&(g=g.filter(_=>e instanceof Bt?e.contains(_.kind):e.providerId===_.provider.id)),!g.length){h.only&&this.showPasteAsNoEditMessage(i,h.only);return}let f;if(e)f=g.at(0);else{const _=await this._quickInputService.pick(g.map(v=>{var b;return{label:v.title,description:(b=v.kind)===null||b===void 0?void 0:b.value,edit:v}}),{placeHolder:p("pasteAsPickerPlaceholder","Select Paste Action")});f=_==null?void 0:_.edit}if(!f)return;const m=QK(d.uri,i,f);await this._bulkEditService.apply(m,{editor:this._editor})}finally{c.dispose(),this._currentPasteOperation===r&&(this._currentPasteOperation=void 0)}});this._progressService.withProgress({location:10,title:p("pasteAsProgress","Running paste handlers")},()=>r)}setCopyMetadata(e,t){e.setData(iT,JSON.stringify(t))}fetchCopyMetadata(e){var t;if(!e.clipboardData)return;const i=e.clipboardData.getData(iT);if(i)try{return JSON.parse(i)}catch{return}const[n,o]=AA.getTextData(e.clipboardData);if(o)return{defaultPastePayload:{mode:o.mode,multicursorText:(t=o.multicursorText)!==null&&t!==void 0?t:null,pasteOnNewLine:!!o.isFromEmptySelection}}}async mergeInDataFromCopy(e,t,i){var n;if(t!=null&&t.id&&((n=Mg._currentCopyOperation)===null||n===void 0?void 0:n.handle)===t.id){const o=await Mg._currentCopyOperation.dataTransferPromise;if(i.isCancellationRequested)return;for(const[r,a]of o)e.replace(r,a)}if(!e.has(Ti.uriList)){const o=await this._clipboardService.readResources();if(i.isCancellationRequested)return;o.length&&e.append(Ti.uriList,o4(mk.create(o)))}}async getPasteEdits(e,t,i,n,o,r){const a=await h1(Promise.all(e.map(async d=>{var c,u;try{const h=await((c=d.provideDocumentPasteEdits)===null||c===void 0?void 0:c.call(d,i,n,t,o,r));return(u=h==null?void 0:h.edits)===null||u===void 0?void 0:u.map(g=>({...g,provider:d}))}catch(h){console.error(h)}})),r),l=pd(a??[]).flat().filter(d=>!o.only||o.only.contains(d.kind));return JK(l)}async applyDefaultPasteHandler(e,t,i,n){var o,r,a,l;const d=(o=e.get(Ti.text))!==null&&o!==void 0?o:e.get("text"),c=(r=await(d==null?void 0:d.asString()))!==null&&r!==void 0?r:"";if(i.isCancellationRequested)return;const u={clipboardEvent:n,text:c,pasteOnNewLine:(a=t==null?void 0:t.defaultPastePayload.pasteOnNewLine)!==null&&a!==void 0?a:!1,multicursorText:(l=t==null?void 0:t.defaultPastePayload.multicursorText)!==null&&l!==void 0?l:null,mode:null};this._editor.trigger("keyboard","paste",u)}isSupportedPasteProvider(e,t,i){var n;return!((n=e.pasteMimeTypes)===null||n===void 0)&&n.some(o=>t.matches(o))?!i||this.providerMatchesPreference(e,i):!1}providerMatchesPreference(e,t){return t instanceof Bt?e.providedPasteEditKinds?e.providedPasteEditKinds.some(i=>t.contains(i)):!0:e.id===t.providerId}};kd.ID="editor.contrib.copyPasteActionController";kd=Mg=Lxe([Mp(1,Ne),Mp(2,x1),Mp(3,ru),Mp(4,Ce),Mp(5,hp),Mp(6,lj)],kd);const Pf="9_cutcopypaste",xxe=md||document.queryCommandSupported("cut"),iq=md||document.queryCommandSupported("copy"),kxe=typeof navigator.clipboard>"u"||Fr?document.queryCommandSupported("paste"):!0;function c4(s){return s.register(),s}const Exe=xxe?c4(new a0({id:"editor.action.clipboardCutAction",precondition:void 0,kbOpts:md?{primary:2102,win:{primary:2102,secondary:[1044]},weight:100}:void 0,menuOpts:[{menuId:E.MenubarEditMenu,group:"2_ccp",title:p({},"Cu&&t"),order:1},{menuId:E.EditorContext,group:Pf,title:p("actions.clipboard.cutLabel","Cut"),when:T.writable,order:1},{menuId:E.CommandPalette,group:"",title:p("actions.clipboard.cutLabel","Cut"),order:1},{menuId:E.SimpleEditorContext,group:Pf,title:p("actions.clipboard.cutLabel","Cut"),when:T.writable,order:1}]})):void 0,Ixe=iq?c4(new a0({id:"editor.action.clipboardCopyAction",precondition:void 0,kbOpts:md?{primary:2081,win:{primary:2081,secondary:[2067]},weight:100}:void 0,menuOpts:[{menuId:E.MenubarEditMenu,group:"2_ccp",title:p({},"&&Copy"),order:2},{menuId:E.EditorContext,group:Pf,title:p("actions.clipboard.copyLabel","Copy"),order:2},{menuId:E.CommandPalette,group:"",title:p("actions.clipboard.copyLabel","Copy"),order:1},{menuId:E.SimpleEditorContext,group:Pf,title:p("actions.clipboard.copyLabel","Copy"),order:2}]})):void 0;yn.appendMenuItem(E.MenubarEditMenu,{submenu:E.MenubarCopy,title:Ve("copy as","Copy As"),group:"2_ccp",order:3});yn.appendMenuItem(E.EditorContext,{submenu:E.EditorContextCopy,title:Ve("copy as","Copy As"),group:Pf,order:3});yn.appendMenuItem(E.EditorContext,{submenu:E.EditorContextShare,title:Ve("share","Share"),group:"11_share",order:-1,when:G.and(G.notEquals("resourceScheme","output"),T.editorTextFocus)});yn.appendMenuItem(E.EditorTitleContext,{submenu:E.EditorTitleContextShare,title:Ve("share","Share"),group:"11_share",order:-1});yn.appendMenuItem(E.ExplorerContext,{submenu:E.ExplorerContextShare,title:Ve("share","Share"),group:"11_share",order:-1});const nT=kxe?c4(new a0({id:"editor.action.clipboardPasteAction",precondition:void 0,kbOpts:md?{primary:2100,win:{primary:2100,secondary:[1043]},linux:{primary:2100,secondary:[1043]},weight:100}:void 0,menuOpts:[{menuId:E.MenubarEditMenu,group:"2_ccp",title:p({},"&&Paste"),order:4},{menuId:E.EditorContext,group:Pf,title:p("actions.clipboard.pasteLabel","Paste"),when:T.writable,order:4},{menuId:E.CommandPalette,group:"",title:p("actions.clipboard.pasteLabel","Paste"),order:1},{menuId:E.SimpleEditorContext,group:Pf,title:p("actions.clipboard.pasteLabel","Paste"),when:T.writable,order:4}]})):void 0;class Txe extends me{constructor(){super({id:"editor.action.clipboardCopyWithSyntaxHighlightingAction",label:p("actions.clipboard.copyWithSyntaxHighlightingLabel","Copy With Syntax Highlighting"),alias:"Copy With Syntax Highlighting",precondition:void 0,kbOpts:{kbExpr:T.textInputFocus,primary:0,weight:100}})}run(e,t){!t.hasModel()||!t.getOption(37)&&t.getSelection().isEmpty()||(TA.forceCopyWithSyntaxHighlighting=!0,t.focus(),t.getContainerDomNode().ownerDocument.execCommand("copy"),TA.forceCopyWithSyntaxHighlighting=!1)}}function nq(s,e){s&&(s.addImplementation(1e4,"code-editor",(t,i)=>{const n=t.get(xt).getFocusedCodeEditor();if(n&&n.hasTextFocus()){const o=n.getOption(37),r=n.getSelection();return r&&r.isEmpty()&&!o||n.getContainerDomNode().ownerDocument.execCommand(e),!0}return!1}),s.addImplementation(0,"generic-dom",(t,i)=>(o0().execCommand(e),!0)))}nq(Exe,"cut");nq(Ixe,"copy");nT&&(nT.addImplementation(1e4,"code-editor",(s,e)=>{var t,i;const n=s.get(xt),o=s.get(ru),r=n.getFocusedCodeEditor();return r&&r.hasTextFocus()?r.getContainerDomNode().ownerDocument.execCommand("paste")?(i=(t=kd.get(r))===null||t===void 0?void 0:t.finishedPaste())!==null&&i!==void 0?i:Promise.resolve():Jh?(async()=>{const l=await o.readText();if(l!==""){const d=Jb.INSTANCE.get(l);let c=!1,u=null,h=null;d&&(c=r.getOption(37)&&!!d.isFromEmptySelection,u=typeof d.multicursorText<"u"?d.multicursorText:null,h=d.mode),r.trigger("keyboard","paste",{text:l,pasteOnNewLine:c,multicursorText:u,mode:h})}})():!0:!1}),nT.addImplementation(0,"generic-dom",(s,e)=>(o0().execCommand("paste"),!0)));iq&&te(Txe);const li=new class{constructor(){this.QuickFix=new Bt("quickfix"),this.Refactor=new Bt("refactor"),this.RefactorExtract=this.Refactor.append("extract"),this.RefactorInline=this.Refactor.append("inline"),this.RefactorMove=this.Refactor.append("move"),this.RefactorRewrite=this.Refactor.append("rewrite"),this.Notebook=new Bt("notebook"),this.Source=new Bt("source"),this.SourceOrganizeImports=this.Source.append("organizeImports"),this.SourceFixAll=this.Source.append("fixAll"),this.SurroundWith=this.Refactor.append("surround")}};var Ro;(function(s){s.Refactor="refactor",s.RefactorPreview="refactor preview",s.Lightbulb="lightbulb",s.Default="other (default)",s.SourceAction="source action",s.QuickFix="quick fix action",s.FixAll="fix all",s.OrganizeImports="organize imports",s.AutoFix="auto fix",s.QuickFixHover="quick fix hover window",s.OnSave="save participants",s.ProblemsView="problems view"})(Ro||(Ro={}));function Nxe(s,e){return!(s.include&&!s.include.intersects(e)||s.excludes&&s.excludes.some(t=>sq(e,t,s.include))||!s.includeSourceActions&&li.Source.contains(e))}function Axe(s,e){const t=e.kind?new Bt(e.kind):void 0;return!(s.include&&(!t||!s.include.contains(t))||s.excludes&&t&&s.excludes.some(i=>sq(t,i,s.include))||!s.includeSourceActions&&t&&li.Source.contains(t)||s.onlyIncludePreferredActions&&!e.isPreferred)}function sq(s,e,t){return!(!e.contains(s)||t&&e.contains(t))}class Gl{static fromUser(e,t){return!e||typeof e!="object"?new Gl(t.kind,t.apply,!1):new Gl(Gl.getKindFromUser(e,t.kind),Gl.getApplyFromUser(e,t.apply),Gl.getPreferredUser(e))}static getApplyFromUser(e,t){switch(typeof e.apply=="string"?e.apply.toLowerCase():""){case"first":return"first";case"never":return"never";case"ifsingle":return"ifSingle";default:return t}}static getKindFromUser(e,t){return typeof e.kind=="string"?new Bt(e.kind):t}static getPreferredUser(e){return typeof e.preferred=="boolean"?e.preferred:!1}constructor(e,t,i){this.kind=e,this.apply=t,this.preferred=i}}class Mxe{constructor(e,t,i){this.action=e,this.provider=t,this.highlightRange=i}async resolve(e){var t;if(!((t=this.provider)===null||t===void 0)&&t.resolveCodeAction&&!this.action.edit){let i;try{i=await this.provider.resolveCodeAction(this.action,e)}catch(n){Ai(n)}i&&(this.action.edit=i.edit)}return this}}const oq="editor.action.codeAction",u4="editor.action.quickFix",rq="editor.action.autoFix",aq="editor.action.refactor",lq="editor.action.sourceAction",h4="editor.action.organizeImports",g4="editor.action.fixAll";class hb extends H{static codeActionsPreferredComparator(e,t){return e.isPreferred&&!t.isPreferred?-1:!e.isPreferred&&t.isPreferred?1:0}static codeActionsComparator({action:e},{action:t}){return e.isAI&&!t.isAI?1:!e.isAI&&t.isAI?-1:rs(e.diagnostics)?rs(t.diagnostics)?hb.codeActionsPreferredComparator(e,t):-1:rs(t.diagnostics)?1:hb.codeActionsPreferredComparator(e,t)}constructor(e,t,i){super(),this.documentation=t,this._register(i),this.allActions=[...e].sort(hb.codeActionsComparator),this.validActions=this.allActions.filter(({action:n})=>!n.disabled)}get hasAutoFix(){return this.validActions.some(({action:e})=>!!e.kind&&li.QuickFix.contains(new Bt(e.kind))&&!!e.isPreferred)}get hasAIFix(){return this.validActions.some(({action:e})=>!!e.isAI)}get allAIFixes(){return this.validActions.every(({action:e})=>!!e.isAI)}}const F7={actions:[],documentation:void 0};async function gb(s,e,t,i,n,o){var r;const a=i.filter||{},l={...a,excludes:[...a.excludes||[],li.Notebook]},d={only:(r=a.include)===null||r===void 0?void 0:r.value,trigger:i.type},c=new s4(e,o),u=i.type===2,h=Rxe(s,e,u?l:a),g=new Y,f=h.map(async _=>{try{n.report(_);const v=await _.provideCodeActions(e,t,d,c.token);if(v&&g.add(v),c.token.isCancellationRequested)return F7;const b=((v==null?void 0:v.actions)||[]).filter(w=>w&&Axe(a,w)),C=Fxe(_,b,a.include);return{actions:b.map(w=>new Mxe(w,_)),documentation:C}}catch(v){if(Id(v))throw v;return Ai(v),F7}}),m=s.onDidChange(()=>{const _=s.all(e);Ci(_,h)||c.cancel()});try{const _=await Promise.all(f),v=_.map(C=>C.actions).flat(),b=[...pd(_.map(C=>C.documentation)),...Pxe(s,e,i,v)];return new hb(v,b,g)}finally{m.dispose(),c.dispose()}}function Rxe(s,e,t){return s.all(e).filter(i=>i.providedCodeActionKinds?i.providedCodeActionKinds.some(n=>Nxe(t,new Bt(n))):!0)}function*Pxe(s,e,t,i){var n,o,r;if(e&&i.length)for(const a of s.all(e))a._getAdditionalMenuItems&&(yield*(n=a._getAdditionalMenuItems)===null||n===void 0?void 0:n.call(a,{trigger:t.type,only:(r=(o=t.filter)===null||o===void 0?void 0:o.include)===null||r===void 0?void 0:r.value},i.map(l=>l.action)))}function Fxe(s,e,t){if(!s.documentation)return;const i=s.documentation.map(n=>({kind:new Bt(n.kind),command:n.command}));if(t){let n;for(const o of i)o.kind.contains(t)&&(n?n.kind.contains(o.kind)&&(n=o):n=o);if(n)return n==null?void 0:n.command}for(const n of e)if(n.kind){for(const o of i)if(o.kind.contains(new Bt(n.kind)))return o.command}}var nf;(function(s){s.OnSave="onSave",s.FromProblemsView="fromProblemsView",s.FromCodeActions="fromCodeActions",s.FromAILightbulb="fromAILightbulb"})(nf||(nf={}));async function Oxe(s,e,t,i,n=dt.None){var o;const r=s.get(x1),a=s.get(gi),l=s.get(Gs),d=s.get(en);if(l.publicLog2("codeAction.applyCodeAction",{codeActionTitle:e.action.title,codeActionKind:e.action.kind,codeActionIsPreferred:!!e.action.isPreferred,reason:t}),await e.resolve(n),!n.isCancellationRequested&&!(!((o=e.action.edit)===null||o===void 0)&&o.edits.length&&!(await r.apply(e.action.edit,{editor:i==null?void 0:i.editor,label:e.action.title,quotableLabel:e.action.title,code:"undoredo.codeAction",respectAutoSaveConfig:t!==nf.OnSave,showPreview:i==null?void 0:i.preview})).isApplied)&&e.action.command)try{await a.executeCommand(e.action.command.id,...e.action.command.arguments||[])}catch(c){const u=Bxe(c);d.error(typeof u=="string"?u:p("applyCodeActionFailed","An unknown error occurred while applying the code action"))}}function Bxe(s){return typeof s=="string"?s:s instanceof Error&&typeof s.message=="string"?s.message:void 0}pt.registerCommand("_executeCodeActionProvider",async function(s,e,t,i,n){if(!(e instanceof Ae))throw Mr();const{codeActionProvider:o}=s.get(Ce),r=s.get(_i).getModel(e);if(!r)throw Mr();const a=we.isISelection(t)?we.liftSelection(t):x.isIRange(t)?r.validateRange(t):void 0;if(!a)throw Mr();const l=typeof i=="string"?new Bt(i):void 0,d=await gb(o,r,a,{type:1,triggerAction:Ro.Default,filter:{includeSourceActions:!0,include:l}},Nc.None,dt.None),c=[],u=Math.min(d.validActions.length,typeof n=="number"?n:0);for(let h=0;hh.action)}finally{setTimeout(()=>d.dispose(),100)}});var Wxe=function(s,e,t,i){var n=arguments.length,o=n<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,r;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(s,e,t,i);else for(var a=s.length-1;a>=0;a--)(r=s[a])&&(o=(n<3?r(o):n>3?r(e,t,o):r(e,t))||o);return n>3&&o&&Object.defineProperty(e,t,o),o},Hxe=function(s,e){return function(t,i){e(t,i,s)}},PM;let uL=PM=class{constructor(e){this.keybindingService=e}getResolver(){const e=new gl(()=>this.keybindingService.getKeybindings().filter(t=>PM.codeActionCommands.indexOf(t.command)>=0).filter(t=>t.resolvedKeybinding).map(t=>{let i=t.commandArgs;return t.command===h4?i={kind:li.SourceOrganizeImports.value}:t.command===g4&&(i={kind:li.SourceFixAll.value}),{resolvedKeybinding:t.resolvedKeybinding,...Gl.fromUser(i,{kind:Bt.None,apply:"never"})}}));return t=>{if(t.kind){const i=this.bestKeybindingForCodeAction(t,e.value);return i==null?void 0:i.resolvedKeybinding}}}bestKeybindingForCodeAction(e,t){if(!e.kind)return;const i=new Bt(e.kind);return t.filter(n=>n.kind.contains(i)).filter(n=>n.preferred?e.isPreferred:!0).reduceRight((n,o)=>n?n.kind.contains(o.kind)?o:n:o,void 0)}};uL.codeActionCommands=[aq,oq,lq,h4,g4];uL=PM=Wxe([Hxe(0,At)],uL);N("symbolIcon.arrayForeground",{dark:ae,light:ae,hcDark:ae,hcLight:ae},p("symbolIcon.arrayForeground","The foreground color for array symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));N("symbolIcon.booleanForeground",{dark:ae,light:ae,hcDark:ae,hcLight:ae},p("symbolIcon.booleanForeground","The foreground color for boolean symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));N("symbolIcon.classForeground",{dark:"#EE9D28",light:"#D67E00",hcDark:"#EE9D28",hcLight:"#D67E00"},p("symbolIcon.classForeground","The foreground color for class symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));N("symbolIcon.colorForeground",{dark:ae,light:ae,hcDark:ae,hcLight:ae},p("symbolIcon.colorForeground","The foreground color for color symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));N("symbolIcon.constantForeground",{dark:ae,light:ae,hcDark:ae,hcLight:ae},p("symbolIcon.constantForeground","The foreground color for constant symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));N("symbolIcon.constructorForeground",{dark:"#B180D7",light:"#652D90",hcDark:"#B180D7",hcLight:"#652D90"},p("symbolIcon.constructorForeground","The foreground color for constructor symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));N("symbolIcon.enumeratorForeground",{dark:"#EE9D28",light:"#D67E00",hcDark:"#EE9D28",hcLight:"#D67E00"},p("symbolIcon.enumeratorForeground","The foreground color for enumerator symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));N("symbolIcon.enumeratorMemberForeground",{dark:"#75BEFF",light:"#007ACC",hcDark:"#75BEFF",hcLight:"#007ACC"},p("symbolIcon.enumeratorMemberForeground","The foreground color for enumerator member symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));N("symbolIcon.eventForeground",{dark:"#EE9D28",light:"#D67E00",hcDark:"#EE9D28",hcLight:"#D67E00"},p("symbolIcon.eventForeground","The foreground color for event symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));N("symbolIcon.fieldForeground",{dark:"#75BEFF",light:"#007ACC",hcDark:"#75BEFF",hcLight:"#007ACC"},p("symbolIcon.fieldForeground","The foreground color for field symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));N("symbolIcon.fileForeground",{dark:ae,light:ae,hcDark:ae,hcLight:ae},p("symbolIcon.fileForeground","The foreground color for file symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));N("symbolIcon.folderForeground",{dark:ae,light:ae,hcDark:ae,hcLight:ae},p("symbolIcon.folderForeground","The foreground color for folder symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));N("symbolIcon.functionForeground",{dark:"#B180D7",light:"#652D90",hcDark:"#B180D7",hcLight:"#652D90"},p("symbolIcon.functionForeground","The foreground color for function symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));N("symbolIcon.interfaceForeground",{dark:"#75BEFF",light:"#007ACC",hcDark:"#75BEFF",hcLight:"#007ACC"},p("symbolIcon.interfaceForeground","The foreground color for interface symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));N("symbolIcon.keyForeground",{dark:ae,light:ae,hcDark:ae,hcLight:ae},p("symbolIcon.keyForeground","The foreground color for key symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));N("symbolIcon.keywordForeground",{dark:ae,light:ae,hcDark:ae,hcLight:ae},p("symbolIcon.keywordForeground","The foreground color for keyword symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));N("symbolIcon.methodForeground",{dark:"#B180D7",light:"#652D90",hcDark:"#B180D7",hcLight:"#652D90"},p("symbolIcon.methodForeground","The foreground color for method symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));N("symbolIcon.moduleForeground",{dark:ae,light:ae,hcDark:ae,hcLight:ae},p("symbolIcon.moduleForeground","The foreground color for module symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));N("symbolIcon.namespaceForeground",{dark:ae,light:ae,hcDark:ae,hcLight:ae},p("symbolIcon.namespaceForeground","The foreground color for namespace symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));N("symbolIcon.nullForeground",{dark:ae,light:ae,hcDark:ae,hcLight:ae},p("symbolIcon.nullForeground","The foreground color for null symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));N("symbolIcon.numberForeground",{dark:ae,light:ae,hcDark:ae,hcLight:ae},p("symbolIcon.numberForeground","The foreground color for number symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));N("symbolIcon.objectForeground",{dark:ae,light:ae,hcDark:ae,hcLight:ae},p("symbolIcon.objectForeground","The foreground color for object symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));N("symbolIcon.operatorForeground",{dark:ae,light:ae,hcDark:ae,hcLight:ae},p("symbolIcon.operatorForeground","The foreground color for operator symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));N("symbolIcon.packageForeground",{dark:ae,light:ae,hcDark:ae,hcLight:ae},p("symbolIcon.packageForeground","The foreground color for package symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));N("symbolIcon.propertyForeground",{dark:ae,light:ae,hcDark:ae,hcLight:ae},p("symbolIcon.propertyForeground","The foreground color for property symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));N("symbolIcon.referenceForeground",{dark:ae,light:ae,hcDark:ae,hcLight:ae},p("symbolIcon.referenceForeground","The foreground color for reference symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));N("symbolIcon.snippetForeground",{dark:ae,light:ae,hcDark:ae,hcLight:ae},p("symbolIcon.snippetForeground","The foreground color for snippet symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));N("symbolIcon.stringForeground",{dark:ae,light:ae,hcDark:ae,hcLight:ae},p("symbolIcon.stringForeground","The foreground color for string symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));N("symbolIcon.structForeground",{dark:ae,light:ae,hcDark:ae,hcLight:ae},p("symbolIcon.structForeground","The foreground color for struct symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));N("symbolIcon.textForeground",{dark:ae,light:ae,hcDark:ae,hcLight:ae},p("symbolIcon.textForeground","The foreground color for text symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));N("symbolIcon.typeParameterForeground",{dark:ae,light:ae,hcDark:ae,hcLight:ae},p("symbolIcon.typeParameterForeground","The foreground color for type parameter symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));N("symbolIcon.unitForeground",{dark:ae,light:ae,hcDark:ae,hcLight:ae},p("symbolIcon.unitForeground","The foreground color for unit symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));N("symbolIcon.variableForeground",{dark:"#75BEFF",light:"#007ACC",hcDark:"#75BEFF",hcLight:"#007ACC"},p("symbolIcon.variableForeground","The foreground color for variable symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));const dq=Object.freeze({kind:Bt.Empty,title:p("codeAction.widget.id.more","More Actions...")}),Vxe=Object.freeze([{kind:li.QuickFix,title:p("codeAction.widget.id.quickfix","Quick Fix")},{kind:li.RefactorExtract,title:p("codeAction.widget.id.extract","Extract"),icon:oe.wrench},{kind:li.RefactorInline,title:p("codeAction.widget.id.inline","Inline"),icon:oe.wrench},{kind:li.RefactorRewrite,title:p("codeAction.widget.id.convert","Rewrite"),icon:oe.wrench},{kind:li.RefactorMove,title:p("codeAction.widget.id.move","Move"),icon:oe.wrench},{kind:li.SurroundWith,title:p("codeAction.widget.id.surround","Surround With"),icon:oe.surroundWith},{kind:li.Source,title:p("codeAction.widget.id.source","Source Action"),icon:oe.symbolFile},dq]);function zxe(s,e,t){if(!e)return s.map(o=>{var r;return{kind:"action",item:o,group:dq,disabled:!!o.action.disabled,label:o.action.disabled||o.action.title,canPreview:!!(!((r=o.action.edit)===null||r===void 0)&&r.edits.length)}});const i=Vxe.map(o=>({group:o,actions:[]}));for(const o of s){const r=o.action.kind?new Bt(o.action.kind):Bt.None;for(const a of i)if(a.group.kind.contains(r)){a.actions.push(o);break}}const n=[];for(const o of i)if(o.actions.length){n.push({kind:"header",group:o.group});for(const r of o.actions){const a=o.group;n.push({kind:"action",item:r,group:r.action.isAI?{title:a.title,kind:a.kind,icon:oe.sparkle}:a,label:r.action.title,disabled:!!r.action.disabled,keybinding:t(r.action)})}}return n}var Uxe=function(s,e,t,i){var n=arguments.length,o=n<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,r;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(s,e,t,i);else for(var a=s.length-1;a>=0;a--)(r=s[a])&&(o=(n<3?r(o):n>3?r(e,t,o):r(e,t))||o);return n>3&&o&&Object.defineProperty(e,t,o),o},O7=function(s,e){return function(t,i){e(t,i,s)}},FM,bm;(function(s){s.Hidden={type:0};class e{constructor(i,n,o,r){this.actions=i,this.trigger=n,this.editorPosition=o,this.widgetPosition=r,this.type=1}}s.Showing=e})(bm||(bm={}));let Ff=FM=class extends H{constructor(e,t,i){super(),this._editor=e,this._keybindingService=t,this._onClick=this._register(new B),this.onClick=this._onClick.event,this._state=bm.Hidden,this._iconClasses=[],this._domNode=he("div.lightBulbWidget"),this._domNode.role="listbox",this._register(Gt.ignoreTarget(this._domNode)),this._editor.addContentWidget(this),this._register(this._editor.onDidChangeModelContent(n=>{const o=this._editor.getModel();(this.state.type!==1||!o||this.state.editorPosition.lineNumber>=o.getLineCount())&&this.hide()})),this._register(Pae(this._domNode,n=>{if(this.state.type!==1)return;this._editor.focus(),n.preventDefault();const{top:o,height:r}=qi(this._domNode),a=this._editor.getOption(67);let l=Math.floor(a/3);this.state.widgetPosition.position!==null&&this.state.widgetPosition.position.lineNumber{(n.buttons&1)===1&&this.hide()})),this._register(le.runAndSubscribe(this._keybindingService.onDidUpdateKeybindings,()=>{var n,o,r,a;this._preferredKbLabel=(o=(n=this._keybindingService.lookupKeybinding(rq))===null||n===void 0?void 0:n.getLabel())!==null&&o!==void 0?o:void 0,this._quickFixKbLabel=(a=(r=this._keybindingService.lookupKeybinding(u4))===null||r===void 0?void 0:r.getLabel())!==null&&a!==void 0?a:void 0,this._updateLightBulbTitleAndIcon()}))}dispose(){super.dispose(),this._editor.removeContentWidget(this)}getId(){return"LightBulbWidget"}getDomNode(){return this._domNode}getPosition(){return this._state.type===1?this._state.widgetPosition:null}update(e,t,i){if(e.validActions.length<=0)return this.hide();if(!this._editor.getOptions().get(65).enabled)return this.hide();const o=this._editor.getModel();if(!o)return this.hide();const{lineNumber:r,column:a}=o.validatePosition(i),l=o.getOptions().tabSize,d=this._editor.getOptions().get(50),c=o.getLineContent(r),u=Tx(c,l),h=d.spaceWidth*u>22,g=_=>_>2&&this._editor.getTopForLineNumber(_)===this._editor.getTopForLineNumber(_-1);let f=r,m=1;if(!h){if(r>1&&!g(r-1))f-=1;else if(r=0;a--)(r=s[a])&&(o=(n<3?r(o):n>3?r(e,t,o):r(e,t))||o);return n>3&&o&&Object.defineProperty(e,t,o),o},OM=function(s,e){return function(t,i){e(t,i,s)}};const uq="acceptSelectedCodeAction",hq="previewSelectedCodeAction";class $xe{get templateId(){return"header"}renderTemplate(e){e.classList.add("group-header");const t=document.createElement("span");return e.append(t),{container:e,text:t}}renderElement(e,t,i){var n,o;i.text.textContent=(o=(n=e.group)===null||n===void 0?void 0:n.title)!==null&&o!==void 0?o:""}disposeTemplate(e){}}let BM=class{get templateId(){return"action"}constructor(e,t){this._supportsPreview=e,this._keybindingService=t}renderTemplate(e){e.classList.add(this.templateId);const t=document.createElement("div");t.className="icon",e.append(t);const i=document.createElement("span");i.className="title",e.append(i);const n=new m0(e,Lo);return{container:e,icon:t,text:i,keybinding:n}}renderElement(e,t,i){var n,o,r;if(!((n=e.group)===null||n===void 0)&&n.icon?(i.icon.className=Pe.asClassName(e.group.icon),e.group.icon.color&&(i.icon.style.color=fe(e.group.icon.color.id))):(i.icon.className=Pe.asClassName(oe.lightBulb),i.icon.style.color="var(--vscode-editorLightBulb-foreground)"),!e.item||!e.label)return;i.text.textContent=gq(e.label),i.keybinding.set(e.keybinding),Xae(!!e.keybinding,i.keybinding.element);const a=(o=this._keybindingService.lookupKeybinding(uq))===null||o===void 0?void 0:o.getLabel(),l=(r=this._keybindingService.lookupKeybinding(hq))===null||r===void 0?void 0:r.getLabel();i.container.classList.toggle("option-disabled",e.disabled),e.disabled?i.container.title=e.label:a&&l?this._supportsPreview&&e.canPreview?i.container.title=p({},"{0} to Apply, {1} to Preview",a,l):i.container.title=p({},"{0} to Apply",a):i.container.title=""}disposeTemplate(e){e.keybinding.dispose()}};BM=cq([OM(1,At)],BM);class jxe extends UIEvent{constructor(){super("acceptSelectedAction")}}class B7 extends UIEvent{constructor(){super("previewSelectedAction")}}function Kxe(s){if(s.kind==="action")return s.label}let WM=class extends H{constructor(e,t,i,n,o,r){super(),this._delegate=n,this._contextViewService=o,this._keybindingService=r,this._actionLineHeight=24,this._headerLineHeight=26,this.cts=this._register(new Vi),this.domNode=document.createElement("div"),this.domNode.classList.add("actionList");const a={getHeight:l=>l.kind==="header"?this._headerLineHeight:this._actionLineHeight,getTemplateId:l=>l.kind};this._list=this._register(new pr(e,this.domNode,a,[new BM(t,this._keybindingService),new $xe],{keyboardSupport:!1,typeNavigationEnabled:!0,keyboardNavigationLabelProvider:{getKeyboardNavigationLabel:Kxe},accessibilityProvider:{getAriaLabel:l=>{if(l.kind==="action"){let d=l.label?gq(l==null?void 0:l.label):"";return l.disabled&&(d=p({},"{0}, Disabled Reason: {1}",d,l.disabled)),d}return null},getWidgetAriaLabel:()=>p({},"Action Widget"),getRole:l=>l.kind==="action"?"option":"separator",getWidgetRole:()=>"listbox"}})),this._list.style(cp),this._register(this._list.onMouseClick(l=>this.onListClick(l))),this._register(this._list.onMouseOver(l=>this.onListHover(l))),this._register(this._list.onDidChangeFocus(()=>this.onFocus())),this._register(this._list.onDidChangeSelection(l=>this.onListSelection(l))),this._allMenuItems=i,this._list.splice(0,this._list.length,this._allMenuItems),this._list.length&&this.focusNext()}focusCondition(e){return!e.disabled&&e.kind==="action"}hide(e){this._delegate.onHide(e),this.cts.cancel(),this._contextViewService.hideContextView()}layout(e){const t=this._allMenuItems.filter(l=>l.kind==="header").length,n=this._allMenuItems.length*this._actionLineHeight+t*this._headerLineHeight-t*this._actionLineHeight;this._list.layout(n);let o=e;if(this._allMenuItems.length>=50)o=380;else{const l=this._allMenuItems.map((d,c)=>{const u=this.domNode.ownerDocument.getElementById(this._list.getElementID(c));if(u){u.style.width="auto";const h=u.getBoundingClientRect().width;return u.style.width="",h}return 0});o=Math.max(...l,e)}const a=Math.min(n,this.domNode.ownerDocument.body.clientHeight*.7);return this._list.layout(a,o),this.domNode.style.height=`${a}px`,this._list.domFocus(),o}focusPrevious(){this._list.focusPrevious(1,!0,void 0,this.focusCondition)}focusNext(){this._list.focusNext(1,!0,void 0,this.focusCondition)}acceptSelected(e){const t=this._list.getFocus();if(t.length===0)return;const i=t[0],n=this._list.element(i);if(!this.focusCondition(n))return;const o=e?new B7:new jxe;this._list.setSelection([i],o)}onListSelection(e){if(!e.elements.length)return;const t=e.elements[0];t.item&&this.focusCondition(t)?this._delegate.onSelect(t.item,e.browserEvent instanceof B7):this._list.setSelection([])}onFocus(){var e,t;const i=this._list.getFocus();if(i.length===0)return;const n=i[0],o=this._list.element(n);(t=(e=this._delegate).onFocus)===null||t===void 0||t.call(e,o.item)}async onListHover(e){const t=e.element;if(t&&t.item&&this.focusCondition(t)){if(this._delegate.onHover&&!t.disabled&&t.kind==="action"){const i=await this._delegate.onHover(t.item,this.cts.token);t.canPreview=i?i.canPreview:void 0}e.index&&this._list.splice(e.index,1,[t])}this._list.setFocus(typeof e.index=="number"?[e.index]:[])}onListClick(e){e.element&&this.focusCondition(e.element)&&this._list.setFocus([])}};WM=cq([OM(4,nu),OM(5,At)],WM);function gq(s){return s.replace(/\r\n|\r|\n/g," ")}var qxe=function(s,e,t,i){var n=arguments.length,o=n<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,r;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(s,e,t,i);else for(var a=s.length-1;a>=0;a--)(r=s[a])&&(o=(n<3?r(o):n>3?r(e,t,o):r(e,t))||o);return n>3&&o&&Object.defineProperty(e,t,o),o},sT=function(s,e){return function(t,i){e(t,i,s)}};N("actionBar.toggledBackground",{dark:Zg,light:Zg,hcDark:Zg,hcLight:Zg},p("actionBar.toggledBackground","Background color for toggled action items in action bar."));const Of={Visible:new ue("codeActionMenuVisible",!1,p("codeActionMenuVisible","Whether the action widget list is visible"))},mp=ut("actionWidgetService");let Bf=class extends H{get isVisible(){return Of.Visible.getValue(this._contextKeyService)||!1}constructor(e,t,i){super(),this._contextViewService=e,this._contextKeyService=t,this._instantiationService=i,this._list=this._register(new $n)}show(e,t,i,n,o,r,a){const l=Of.Visible.bindTo(this._contextKeyService),d=this._instantiationService.createInstance(WM,e,t,i,n);this._contextViewService.showContextView({getAnchor:()=>o,render:c=>(l.set(!0),this._renderWidget(c,d,a??[])),onHide:c=>{l.reset(),this._onWidgetClosed(c)}},r,!1)}acceptSelected(e){var t;(t=this._list.value)===null||t===void 0||t.acceptSelected(e)}focusPrevious(){var e,t;(t=(e=this._list)===null||e===void 0?void 0:e.value)===null||t===void 0||t.focusPrevious()}focusNext(){var e,t;(t=(e=this._list)===null||e===void 0?void 0:e.value)===null||t===void 0||t.focusNext()}hide(e){var t;(t=this._list.value)===null||t===void 0||t.hide(e),this._list.clear()}_renderWidget(e,t,i){var n;const o=document.createElement("div");if(o.classList.add("action-widget"),e.appendChild(o),this._list.value=t,this._list.value)o.appendChild(this._list.value.domNode);else throw new Error("List has no value");const r=new Y,a=document.createElement("div"),l=e.appendChild(a);l.classList.add("context-view-block"),r.add(K(l,ee.MOUSE_DOWN,f=>f.stopPropagation()));const d=document.createElement("div"),c=e.appendChild(d);c.classList.add("context-view-pointerBlock"),r.add(K(c,ee.POINTER_MOVE,()=>c.remove())),r.add(K(c,ee.MOUSE_DOWN,()=>c.remove()));let u=0;if(i.length){const f=this._createActionBar(".action-widget-action-bar",i);f&&(o.appendChild(f.getContainer().parentElement),r.add(f),u=f.getContainer().offsetWidth)}const h=(n=this._list.value)===null||n===void 0?void 0:n.layout(u);o.style.width=`${h}px`;const g=r.add(ba(e));return r.add(g.onDidBlur(()=>this.hide(!0))),r}_createActionBar(e,t){if(!t.length)return;const i=he(e),n=new Vr(i);return n.push(t,{icon:!1,label:!0}),n}_onWidgetClosed(e){var t;(t=this._list.value)===null||t===void 0||t.hide(e)}};Bf=qxe([sT(0,nu),sT(1,Be),sT(2,Ne)],Bf);mt(mp,Bf,1);const V1=1100;qt(class extends qs{constructor(){super({id:"hideCodeActionWidget",title:Ve("hideCodeActionWidget.title","Hide action widget"),precondition:Of.Visible,keybinding:{weight:V1,primary:9,secondary:[1033]}})}run(s){s.get(mp).hide(!0)}});qt(class extends qs{constructor(){super({id:"selectPrevCodeAction",title:Ve("selectPrevCodeAction.title","Select previous action"),precondition:Of.Visible,keybinding:{weight:V1,primary:16,secondary:[2064],mac:{primary:16,secondary:[2064,302]}}})}run(s){const e=s.get(mp);e instanceof Bf&&e.focusPrevious()}});qt(class extends qs{constructor(){super({id:"selectNextCodeAction",title:Ve("selectNextCodeAction.title","Select next action"),precondition:Of.Visible,keybinding:{weight:V1,primary:18,secondary:[2066],mac:{primary:18,secondary:[2066,300]}}})}run(s){const e=s.get(mp);e instanceof Bf&&e.focusNext()}});qt(class extends qs{constructor(){super({id:uq,title:Ve("acceptSelected.title","Accept selected action"),precondition:Of.Visible,keybinding:{weight:V1,primary:3,secondary:[2137]}})}run(s){const e=s.get(mp);e instanceof Bf&&e.acceptSelected()}});qt(class extends qs{constructor(){super({id:hq,title:Ve("previewSelected.title","Preview selected action"),precondition:Of.Visible,keybinding:{weight:V1,primary:2051}})}run(s){const e=s.get(mp);e instanceof Bf&&e.acceptSelected(!0)}});const fq=new ue("supportedCodeAction",""),W7="_typescript.applyFixAllCodeAction";class Gxe extends H{constructor(e,t,i,n=250){super(),this._editor=e,this._markerService=t,this._signalChange=i,this._delay=n,this._autoTriggerTimer=this._register(new ya),this._register(this._markerService.onMarkerChanged(o=>this._onMarkerChanges(o))),this._register(this._editor.onDidChangeCursorPosition(()=>this._tryAutoTrigger()))}trigger(e){const t=this._getRangeOfSelectionUnlessWhitespaceEnclosed(e);this._signalChange(t?{trigger:e,selection:t}:void 0)}_onMarkerChanges(e){const t=this._editor.getModel();t&&e.some(i=>ZF(i,t.uri))&&this._tryAutoTrigger()}_tryAutoTrigger(){this._autoTriggerTimer.cancelAndSet(()=>{this.trigger({type:2,triggerAction:Ro.Default})},this._delay)}_getRangeOfSelectionUnlessWhitespaceEnclosed(e){if(!this._editor.hasModel())return;const t=this._editor.getSelection();if(e.type===1)return t;const i=this._editor.getOption(65).enabled;if(i!==ia.Off){{if(i===ia.On)return t;if(i===ia.OnCode){if(!t.isEmpty())return t;const o=this._editor.getModel(),{lineNumber:r,column:a}=t.getPosition(),l=o.getLineContent(r);if(l.length===0)return;if(a===1){if(/\s/.test(l[0]))return}else if(a===o.getLineMaxColumn(r)){if(/\s/.test(l[l.length-1]))return}else if(/\s/.test(l[a-2])&&/\s/.test(l[a-1]))return}}return t}}}var $g;(function(s){s.Empty={type:0};class e{constructor(i,n,o){this.trigger=i,this.position=n,this._cancellablePromise=o,this.type=1,this.actions=o.catch(r=>{if(Id(r))return pq;throw r})}cancel(){this._cancellablePromise.cancel()}}s.Triggered=e})($g||($g={}));const pq=Object.freeze({allActions:[],validActions:[],dispose:()=>{},documentation:[],hasAutoFix:!1,hasAIFix:!1,allAIFixes:!1});class Zxe extends H{constructor(e,t,i,n,o,r){super(),this._editor=e,this._registry=t,this._markerService=i,this._progressService=o,this._configurationService=r,this._codeActionOracle=this._register(new $n),this._state=$g.Empty,this._onDidChangeState=this._register(new B),this.onDidChangeState=this._onDidChangeState.event,this._disposed=!1,this._supportedCodeActions=fq.bindTo(n),this._register(this._editor.onDidChangeModel(()=>this._update())),this._register(this._editor.onDidChangeModelLanguage(()=>this._update())),this._register(this._registry.onDidChange(()=>this._update())),this._register(this._editor.onDidChangeConfiguration(a=>{a.hasChanged(65)&&this._update()})),this._update()}dispose(){this._disposed||(this._disposed=!0,super.dispose(),this.setState($g.Empty,!0))}_settingEnabledNearbyQuickfixes(){var e;const t=(e=this._editor)===null||e===void 0?void 0:e.getModel();return this._configurationService?this._configurationService.getValue("editor.codeActionWidget.includeNearbyQuickFixes",{resource:t==null?void 0:t.uri}):!1}_update(){if(this._disposed)return;this._codeActionOracle.value=void 0,this.setState($g.Empty);const e=this._editor.getModel();if(e&&this._registry.has(e)&&!this._editor.getOption(91)){const t=this._registry.all(e).flatMap(i=>{var n;return(n=i.providedCodeActionKinds)!==null&&n!==void 0?n:[]});this._supportedCodeActions.set(t.join(" ")),this._codeActionOracle.value=new Gxe(this._editor,this._markerService,i=>{var n;if(!i){this.setState($g.Empty);return}const o=i.selection.getStartPosition(),r=Dn(async d=>{var c,u,h,g,f,m,_,v,b,C;if(this._settingEnabledNearbyQuickfixes()&&i.trigger.type===1&&(i.trigger.triggerAction===Ro.QuickFix||!((u=(c=i.trigger.filter)===null||c===void 0?void 0:c.include)===null||u===void 0)&&u.contains(li.QuickFix))){const w=await gb(this._registry,e,i.selection,i.trigger,Nc.None,d),y=[...w.allActions];if(d.isCancellationRequested)return pq;const D=(h=w.validActions)===null||h===void 0?void 0:h.some(k=>k.action.kind?li.QuickFix.contains(new Bt(k.action.kind)):!1),L=this._markerService.read({resource:e.uri});if(D){for(const k of w.validActions)!((f=(g=k.action.command)===null||g===void 0?void 0:g.arguments)===null||f===void 0)&&f.some(I=>typeof I=="string"&&I.includes(W7))&&(k.action.diagnostics=[...L.filter(I=>I.relatedInformation)]);return{validActions:w.validActions,allActions:y,documentation:w.documentation,hasAutoFix:w.hasAutoFix,hasAIFix:w.hasAIFix,allAIFixes:w.allAIFixes,dispose:()=>{w.dispose()}}}else if(!D&&L.length>0){const k=i.selection.getPosition();let I=k,O=Number.MAX_VALUE;const R=[...w.validActions];for(const F of L){const V=F.endColumn,U=F.endLineNumber,J=F.startLineNumber;if(U===k.lineNumber||J===k.lineNumber){I=new W(U,V);const pe={type:i.trigger.type,triggerAction:i.trigger.triggerAction,filter:{include:!((m=i.trigger.filter)===null||m===void 0)&&m.include?(_=i.trigger.filter)===null||_===void 0?void 0:_.include:li.QuickFix},autoApply:i.trigger.autoApply,context:{notAvailableMessage:((v=i.trigger.context)===null||v===void 0?void 0:v.notAvailableMessage)||"",position:I}},De=new we(I.lineNumber,I.column,I.lineNumber,I.column),ge=await gb(this._registry,e,De,pe,Nc.None,d);if(ge.validActions.length!==0){for(const We of ge.validActions)!((C=(b=We.action.command)===null||b===void 0?void 0:b.arguments)===null||C===void 0)&&C.some(ye=>typeof ye=="string"&&ye.includes(W7))&&(We.action.diagnostics=[...L.filter(ye=>ye.relatedInformation)]);w.allActions.length===0&&y.push(...ge.allActions),Math.abs(k.column-V)U.findIndex(J=>J.action.title===F.action.title)===V);return P.sort((F,V)=>F.action.isPreferred&&!V.action.isPreferred?-1:!F.action.isPreferred&&V.action.isPreferred||F.action.isAI&&!V.action.isAI?1:!F.action.isAI&&V.action.isAI?-1:0),{validActions:P,allActions:y,documentation:w.documentation,hasAutoFix:w.hasAutoFix,hasAIFix:w.hasAIFix,allAIFixes:w.allAIFixes,dispose:()=>{w.dispose()}}}}return gb(this._registry,e,i.selection,i.trigger,Nc.None,d)});i.trigger.type===1&&((n=this._progressService)===null||n===void 0||n.showWhile(r,250));const a=new $g.Triggered(i.trigger,o,r);let l=!1;this._state.type===1&&(l=this._state.trigger.type===1&&a.type===1&&a.trigger.type===2&&this._state.position!==a.position),l?setTimeout(()=>{this.setState(a)},500):this.setState(a)},void 0),this._codeActionOracle.value.trigger({type:2,triggerAction:Ro.Default})}else this._supportedCodeActions.reset()}trigger(e){var t;(t=this._codeActionOracle.value)===null||t===void 0||t.trigger(e)}setState(e,t){e!==this._state&&(this._state.type===1&&this._state.cancel(),this._state=e,!t&&!this._disposed&&this._onDidChangeState.fire(e))}}var Xxe=function(s,e,t,i){var n=arguments.length,o=n<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,r;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(s,e,t,i);else for(var a=s.length-1;a>=0;a--)(r=s[a])&&(o=(n<3?r(o):n>3?r(e,t,o):r(e,t))||o);return n>3&&o&&Object.defineProperty(e,t,o),o},Dl=function(s,e){return function(t,i){e(t,i,s)}},jp;const Yxe="quickfix-edit-highlight";let Hh=jp=class extends H{static get(e){return e.getContribution(jp.ID)}constructor(e,t,i,n,o,r,a,l,d,c,u){super(),this._commandService=a,this._configurationService=l,this._actionWidgetService=d,this._instantiationService=c,this._telemetryService=u,this._activeCodeActions=this._register(new $n),this._showDisabled=!1,this._disposed=!1,this._editor=e,this._model=this._register(new Zxe(this._editor,o.codeActionProvider,t,i,r,l)),this._register(this._model.onDidChangeState(h=>this.update(h))),this._lightBulbWidget=new gl(()=>{const h=this._editor.getContribution(Ff.ID);return h&&this._register(h.onClick(g=>this.showCodeActionsFromLightbulb(g.actions,g))),h}),this._resolver=n.createInstance(uL),this._register(this._editor.onDidLayoutChange(()=>this._actionWidgetService.hide()))}dispose(){this._disposed=!0,super.dispose()}async showCodeActionsFromLightbulb(e,t){if(this._telemetryService.publicLog2("codeAction.showCodeActionsFromLightbulb",{codeActionListLength:e.validActions.length,codeActions:e.validActions.map(i=>i.action.title),codeActionProviders:e.validActions.map(i=>{var n,o;return(o=(n=i.provider)===null||n===void 0?void 0:n.displayName)!==null&&o!==void 0?o:""})}),e.allAIFixes&&e.validActions.length===1){const i=e.validActions[0],n=i.action.command;n&&n.id==="inlineChat.start"&&n.arguments&&n.arguments.length>=1&&(n.arguments[0]={...n.arguments[0],autoSend:!1}),await this._applyCodeAction(i,!1,!1,nf.FromAILightbulb);return}await this.showCodeActionList(e,t,{includeDisabledActions:!1,fromLightbulb:!0})}showCodeActions(e,t,i){return this.showCodeActionList(t,i,{includeDisabledActions:!1,fromLightbulb:!1})}manualTriggerAtCurrentPosition(e,t,i,n){var o;if(!this._editor.hasModel())return;(o=Vs.get(this._editor))===null||o===void 0||o.closeMessage();const r=this._editor.getPosition();this._trigger({type:1,triggerAction:t,filter:i,autoApply:n,context:{notAvailableMessage:e,position:r}})}_trigger(e){return this._model.trigger(e)}async _applyCodeAction(e,t,i,n){try{await this._instantiationService.invokeFunction(Oxe,e,n,{preview:i,editor:this._editor})}finally{t&&this._trigger({type:2,triggerAction:Ro.QuickFix,filter:{}})}}async update(e){var t,i,n,o,r,a,l;if(e.type!==1){(t=this._lightBulbWidget.rawValue)===null||t===void 0||t.hide();return}let d;try{d=await e.actions}catch(c){Xe(c);return}if(!this._disposed)if((i=this._lightBulbWidget.value)===null||i===void 0||i.update(d,e.trigger,e.position),e.trigger.type===1){if(!((n=e.trigger.filter)===null||n===void 0)&&n.include){const u=this.tryGetValidActionToApply(e.trigger,d);if(u){try{(o=this._lightBulbWidget.value)===null||o===void 0||o.hide(),await this._applyCodeAction(u,!1,!1,nf.FromCodeActions)}finally{d.dispose()}return}if(e.trigger.context){const h=this.getInvalidActionThatWouldHaveBeenApplied(e.trigger,d);if(h&&h.action.disabled){(r=Vs.get(this._editor))===null||r===void 0||r.showMessage(h.action.disabled,e.trigger.context.position),d.dispose();return}}}const c=!!(!((a=e.trigger.filter)===null||a===void 0)&&a.include);if(e.trigger.context&&(!d.allActions.length||!c&&!d.validActions.length)){(l=Vs.get(this._editor))===null||l===void 0||l.showMessage(e.trigger.context.notAvailableMessage,e.trigger.context.position),this._activeCodeActions.value=d,d.dispose();return}this._activeCodeActions.value=d,this.showCodeActionList(d,this.toCoords(e.position),{includeDisabledActions:c,fromLightbulb:!1})}else this._actionWidgetService.isVisible?d.dispose():this._activeCodeActions.value=d}getInvalidActionThatWouldHaveBeenApplied(e,t){if(t.allActions.length&&(e.autoApply==="first"&&t.validActions.length===0||e.autoApply==="ifSingle"&&t.allActions.length===1))return t.allActions.find(({action:i})=>i.disabled)}tryGetValidActionToApply(e,t){if(t.validActions.length&&(e.autoApply==="first"&&t.validActions.length>0||e.autoApply==="ifSingle"&&t.validActions.length===1))return t.validActions[0]}async showCodeActionList(e,t,i){const n=this._editor.createDecorationsCollection(),o=this._editor.getDomNode();if(!o)return;const r=i.includeDisabledActions&&(this._showDisabled||e.validActions.length===0)?e.allActions:e.validActions;if(!r.length)return;const a=W.isIPosition(t)?this.toCoords(t):t,l={onSelect:async(d,c)=>{this._applyCodeAction(d,!0,!!c,i.fromLightbulb?nf.FromAILightbulb:nf.FromCodeActions),this._actionWidgetService.hide(!1),n.clear()},onHide:d=>{var c;(c=this._editor)===null||c===void 0||c.focus(),n.clear(),i.fromLightbulb&&d!==void 0&&this._telemetryService.publicLog2("codeAction.showCodeActionList.onHide",{codeActionListLength:e.validActions.length,didCancel:d})},onHover:async(d,c)=>{var u;if(c.isCancellationRequested)return;let h=!1;const g=d.action.kind;if(g){const f=new Bt(g);h=[li.RefactorExtract,li.RefactorInline,li.RefactorRewrite,li.RefactorMove,li.Source].some(_=>_.contains(f))}return{canPreview:h||!!(!((u=d.action.edit)===null||u===void 0)&&u.edits.length)}},onFocus:d=>{var c,u;if(d&&d.action){const h=d.action.ranges,g=d.action.diagnostics;if(n.clear(),h&&h.length>0){const f=g&&(g==null?void 0:g.length)>1?g.map(m=>({range:m,options:jp.DECORATION})):h.map(m=>({range:m,options:jp.DECORATION}));n.set(f)}else if(g&&g.length>0){const f=g.map(_=>({range:_,options:jp.DECORATION}));n.set(f);const m=g[0];if(m.startLineNumber&&m.startColumn){const _=(u=(c=this._editor.getModel())===null||c===void 0?void 0:c.getWordAtPosition({lineNumber:m.startLineNumber,column:m.startColumn}))===null||u===void 0?void 0:u.word;Uc(p("editingNewSelection","Context: {0} at line {1} and column {2}.",_,m.startLineNumber,m.startColumn))}}}else n.clear()}};this._actionWidgetService.show("codeActionWidget",!0,zxe(r,this._shouldShowHeaders(),this._resolver.getResolver()),l,a,o,this._getActionBarActions(e,t,i))}toCoords(e){if(!this._editor.hasModel())return{x:0,y:0};this._editor.revealPosition(e,1),this._editor.render();const t=this._editor.getScrolledVisiblePosition(e),i=qi(this._editor.getDomNode()),n=i.left+t.left,o=i.top+t.top+t.height;return{x:n,y:o}}_shouldShowHeaders(){var e;const t=(e=this._editor)===null||e===void 0?void 0:e.getModel();return this._configurationService.getValue("editor.codeActionWidget.showHeaders",{resource:t==null?void 0:t.uri})}_getActionBarActions(e,t,i){if(i.fromLightbulb)return[];const n=e.documentation.map(o=>{var r;return{id:o.id,label:o.title,tooltip:(r=o.tooltip)!==null&&r!==void 0?r:"",class:void 0,enabled:!0,run:()=>{var a;return this._commandService.executeCommand(o.id,...(a=o.arguments)!==null&&a!==void 0?a:[])}}});return i.includeDisabledActions&&e.validActions.length>0&&e.allActions.length!==e.validActions.length&&n.push(this._showDisabled?{id:"hideMoreActions",label:p("hideMoreActions","Hide Disabled"),enabled:!0,tooltip:"",class:void 0,run:()=>(this._showDisabled=!1,this.showCodeActionList(e,t,i))}:{id:"showMoreActions",label:p("showMoreActions","Show Disabled"),enabled:!0,tooltip:"",class:void 0,run:()=>(this._showDisabled=!0,this.showCodeActionList(e,t,i))}),n}};Hh.ID="editor.contrib.codeActionController";Hh.DECORATION=Ye.register({description:"quickfix-highlight",className:Yxe});Hh=jp=Xxe([Dl(1,Pd),Dl(2,Be),Dl(3,Ne),Dl(4,Ce),Dl(5,sg),Dl(6,gi),Dl(7,rt),Dl(8,mp),Dl(9,Ne),Dl(10,Gs)],Hh);zr((s,e)=>{((n,o)=>{o&&e.addRule(`.monaco-editor ${n} { background-color: ${o}; }`)})(".quickfix-edit-highlight",s.getColor(pc));const i=s.getColor(zu);i&&e.addRule(`.monaco-editor .quickfix-edit-highlight { border: 1px ${dd(s.type)?"dotted":"solid"} ${i}; box-sizing: border-box; }`)});function z1(s){return G.regex(fq.keys()[0],new RegExp("(\\s|^)"+rr(s.value)+"\\b"))}const f4={type:"object",defaultSnippets:[{body:{kind:""}}],properties:{kind:{type:"string",description:p("args.schema.kind","Kind of the code action to run.")},apply:{type:"string",description:p("args.schema.apply","Controls when the returned actions are applied."),default:"ifSingle",enum:["first","ifSingle","never"],enumDescriptions:[p("args.schema.apply.first","Always apply the first returned code action."),p("args.schema.apply.ifSingle","Apply the first returned code action if it is the only one."),p("args.schema.apply.never","Do not apply the returned code actions.")]},preferred:{type:"boolean",default:!1,description:p("args.schema.preferred","Controls if only preferred code actions should be returned.")}}};function _p(s,e,t,i,n=Ro.Default){if(s.hasModel()){const o=Hh.get(s);o==null||o.manualTriggerAtCurrentPosition(e,n,t,i)}}class Qxe extends me{constructor(){super({id:u4,label:p("quickfix.trigger.label","Quick Fix..."),alias:"Quick Fix...",precondition:G.and(T.writable,T.hasCodeActionsProvider),kbOpts:{kbExpr:T.textInputFocus,primary:2137,weight:100}})}run(e,t){return _p(t,p("editor.action.quickFix.noneMessage","No code actions available"),void 0,void 0,Ro.QuickFix)}}class Jxe extends mn{constructor(){super({id:oq,precondition:G.and(T.writable,T.hasCodeActionsProvider),metadata:{description:"Trigger a code action",args:[{name:"args",schema:f4}]}})}runEditorCommand(e,t,i){const n=Gl.fromUser(i,{kind:Bt.Empty,apply:"ifSingle"});return _p(t,typeof(i==null?void 0:i.kind)=="string"?n.preferred?p("editor.action.codeAction.noneMessage.preferred.kind","No preferred code actions for '{0}' available",i.kind):p("editor.action.codeAction.noneMessage.kind","No code actions for '{0}' available",i.kind):n.preferred?p("editor.action.codeAction.noneMessage.preferred","No preferred code actions available"):p("editor.action.codeAction.noneMessage","No code actions available"),{include:n.kind,includeSourceActions:!0,onlyIncludePreferredActions:n.preferred},n.apply)}}class eke extends me{constructor(){super({id:aq,label:p("refactor.label","Refactor..."),alias:"Refactor...",precondition:G.and(T.writable,T.hasCodeActionsProvider),kbOpts:{kbExpr:T.textInputFocus,primary:3120,mac:{primary:1328},weight:100},contextMenuOpts:{group:"1_modification",order:2,when:G.and(T.writable,z1(li.Refactor))},metadata:{description:"Refactor...",args:[{name:"args",schema:f4}]}})}run(e,t,i){const n=Gl.fromUser(i,{kind:li.Refactor,apply:"never"});return _p(t,typeof(i==null?void 0:i.kind)=="string"?n.preferred?p("editor.action.refactor.noneMessage.preferred.kind","No preferred refactorings for '{0}' available",i.kind):p("editor.action.refactor.noneMessage.kind","No refactorings for '{0}' available",i.kind):n.preferred?p("editor.action.refactor.noneMessage.preferred","No preferred refactorings available"):p("editor.action.refactor.noneMessage","No refactorings available"),{include:li.Refactor.contains(n.kind)?n.kind:Bt.None,onlyIncludePreferredActions:n.preferred},n.apply,Ro.Refactor)}}class tke extends me{constructor(){super({id:lq,label:p("source.label","Source Action..."),alias:"Source Action...",precondition:G.and(T.writable,T.hasCodeActionsProvider),contextMenuOpts:{group:"1_modification",order:2.1,when:G.and(T.writable,z1(li.Source))},metadata:{description:"Source Action...",args:[{name:"args",schema:f4}]}})}run(e,t,i){const n=Gl.fromUser(i,{kind:li.Source,apply:"never"});return _p(t,typeof(i==null?void 0:i.kind)=="string"?n.preferred?p("editor.action.source.noneMessage.preferred.kind","No preferred source actions for '{0}' available",i.kind):p("editor.action.source.noneMessage.kind","No source actions for '{0}' available",i.kind):n.preferred?p("editor.action.source.noneMessage.preferred","No preferred source actions available"):p("editor.action.source.noneMessage","No source actions available"),{include:li.Source.contains(n.kind)?n.kind:Bt.None,includeSourceActions:!0,onlyIncludePreferredActions:n.preferred},n.apply,Ro.SourceAction)}}class ike extends me{constructor(){super({id:h4,label:p("organizeImports.label","Organize Imports"),alias:"Organize Imports",precondition:G.and(T.writable,z1(li.SourceOrganizeImports)),kbOpts:{kbExpr:T.textInputFocus,primary:1581,weight:100}})}run(e,t){return _p(t,p("editor.action.organize.noneMessage","No organize imports action available"),{include:li.SourceOrganizeImports,includeSourceActions:!0},"ifSingle",Ro.OrganizeImports)}}class nke extends me{constructor(){super({id:g4,label:p("fixAll.label","Fix All"),alias:"Fix All",precondition:G.and(T.writable,z1(li.SourceFixAll))})}run(e,t){return _p(t,p("fixAll.noneMessage","No fix all action available"),{include:li.SourceFixAll,includeSourceActions:!0},"ifSingle",Ro.FixAll)}}class ske extends me{constructor(){super({id:rq,label:p("autoFix.label","Auto Fix..."),alias:"Auto Fix...",precondition:G.and(T.writable,z1(li.QuickFix)),kbOpts:{kbExpr:T.textInputFocus,primary:1625,mac:{primary:2649},weight:100}})}run(e,t){return _p(t,p("editor.action.autoFix.noneMessage","No auto fixes available"),{include:li.QuickFix,onlyIncludePreferredActions:!0},"ifSingle",Ro.AutoFix)}}kt(Hh.ID,Hh,3);kt(Ff.ID,Ff,4);te(Qxe);te(eke);te(tke);te(ike);te(ske);te(nke);de(new Jxe);Ji.as(pl.Configuration).registerConfiguration({...Vx,properties:{"editor.codeActionWidget.showHeaders":{type:"boolean",scope:5,description:p("showCodeActionHeaders","Enable/disable showing group headers in the Code Action menu."),default:!0}}});Ji.as(pl.Configuration).registerConfiguration({...Vx,properties:{"editor.codeActionWidget.includeNearbyQuickFixes":{type:"boolean",scope:5,description:p("includeNearbyQuickFixes","Enable/disable showing nearest Quick Fix within a line when not currently on a diagnostic."),default:!0}}});class HM{constructor(){this.lenses=[],this._disposables=new Y}dispose(){this._disposables.dispose()}get isDisposed(){return this._disposables.isDisposed}add(e,t){this._disposables.add(e);for(const i of e.lenses)this.lenses.push({symbol:i,provider:t})}}async function mq(s,e,t){const i=s.ordered(e),n=new Map,o=new HM,r=i.map(async(a,l)=>{n.set(a,l);try{const d=await Promise.resolve(a.provideCodeLenses(e,t));d&&o.add(d,a)}catch(d){Ai(d)}});return await Promise.all(r),o.lenses=o.lenses.sort((a,l)=>a.symbol.range.startLineNumberl.symbol.range.startLineNumber?1:n.get(a.provider)n.get(l.provider)?1:a.symbol.range.startColumnl.symbol.range.startColumn?1:0),o}pt.registerCommand("_executeCodeLensProvider",function(s,...e){let[t,i]=e;yt(Ae.isUri(t)),yt(typeof i=="number"||!i);const{codeLensProvider:n}=s.get(Ce),o=s.get(_i).getModel(t);if(!o)throw Mr();const r=[],a=new Y;return mq(n,o,dt.None).then(l=>{a.add(l);const d=[];for(const c of l.lenses)i==null||c.symbol.command?r.push(c.symbol):i-- >0&&c.provider.resolveCodeLens&&d.push(Promise.resolve(c.provider.resolveCodeLens(o,c.symbol,dt.None)).then(u=>r.push(u||c.symbol)));return Promise.all(d)}).then(()=>r).finally(()=>{setTimeout(()=>a.dispose(),100)})});var oke=function(s,e,t,i){var n=arguments.length,o=n<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,r;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(s,e,t,i);else for(var a=s.length-1;a>=0;a--)(r=s[a])&&(o=(n<3?r(o):n>3?r(e,t,o):r(e,t))||o);return n>3&&o&&Object.defineProperty(e,t,o),o},rke=function(s,e){return function(t,i){e(t,i,s)}};const _q=ut("ICodeLensCache");class H7{constructor(e,t){this.lineCount=e,this.data=t}}let VM=class{constructor(e){this._fakeProvider=new class{provideCodeLenses(){throw new Error("not supported")}},this._cache=new iu(20,.75);const t="codelens/cache";uv(Ht,()=>e.remove(t,1));const i="codelens/cache2",n=e.get(i,1,"{}");this._deserialize(n),le.once(e.onWillSaveState)(o=>{o.reason===ED.SHUTDOWN&&e.store(i,this._serialize(),1,1)})}put(e,t){const i=t.lenses.map(r=>{var a;return{range:r.symbol.range,command:r.symbol.command&&{id:"",title:(a=r.symbol.command)===null||a===void 0?void 0:a.title}}}),n=new HM;n.add({lenses:i,dispose:()=>{}},this._fakeProvider);const o=new H7(e.getLineCount(),n);this._cache.set(e.uri.toString(),o)}get(e){const t=this._cache.get(e.uri.toString());return t&&t.lineCount===e.getLineCount()?t.data:void 0}delete(e){this._cache.delete(e.uri.toString())}_serialize(){const e=Object.create(null);for(const[t,i]of this._cache){const n=new Set;for(const o of i.data.lenses)n.add(o.symbol.range.startLineNumber);e[t]={lineCount:i.lineCount,lines:[...n.values()]}}return JSON.stringify(e)}_deserialize(e){try{const t=JSON.parse(e);for(const i in t){const n=t[i],o=[];for(const a of n.lines)o.push({range:new x(a,1,a,11)});const r=new HM;r.add({lenses:o,dispose(){}},this._fakeProvider),this._cache.set(i,new H7(n.lineCount,r))}}catch{}}};VM=oke([rke(0,Rd)],VM);mt(_q,VM,1);class ake{constructor(e,t,i){this.afterColumn=1073741824,this.afterLineNumber=e,this.heightInPx=t,this._onHeight=i,this.suppressMouseDown=!0,this.domNode=document.createElement("div")}onComputedHeight(e){this._lastHeight===void 0?this._lastHeight=e:this._lastHeight!==e&&(this._lastHeight=e,this._onHeight())}isVisible(){return this._lastHeight!==0&&this.domNode.hasAttribute("monaco-visible-view-zone")}}class AC{constructor(e,t){this.allowEditorOverflow=!1,this.suppressMouseDown=!0,this._commands=new Map,this._isEmpty=!0,this._editor=e,this._id=`codelens.widget-${AC._idPool++}`,this.updatePosition(t),this._domNode=document.createElement("span"),this._domNode.className="codelens-decoration"}withCommands(e,t){this._commands.clear();const i=[];let n=!1;for(let o=0;o{d.symbol.command&&l.push(d.symbol),i.addDecoration({range:d.symbol.range,options:V7},u=>this._decorationIds[c]=u),a?a=x.plusRange(a,d.symbol.range):a=x.lift(d.symbol.range)}),this._viewZone=new ake(a.startLineNumber-1,o,r),this._viewZoneId=n.addZone(this._viewZone),l.length>0&&(this._createContentWidgetIfNecessary(),this._contentWidget.withCommands(l,!1))}_createContentWidgetIfNecessary(){this._contentWidget?this._editor.layoutContentWidget(this._contentWidget):(this._contentWidget=new AC(this._editor,this._viewZone.afterLineNumber+1),this._editor.addContentWidget(this._contentWidget))}dispose(e,t){this._decorationIds.forEach(e.removeDecoration,e),this._decorationIds=[],t==null||t.removeZone(this._viewZoneId),this._contentWidget&&(this._editor.removeContentWidget(this._contentWidget),this._contentWidget=void 0),this._isDisposed=!0}isDisposed(){return this._isDisposed}isValid(){return this._decorationIds.some((e,t)=>{const i=this._editor.getModel().getDecorationRange(e),n=this._data[t].symbol;return!!(i&&x.isEmpty(n.range)===i.isEmpty())})}updateCodeLensSymbols(e,t){this._decorationIds.forEach(t.removeDecoration,t),this._decorationIds=[],this._data=e,this._data.forEach((i,n)=>{t.addDecoration({range:i.symbol.range,options:V7},o=>this._decorationIds[n]=o)})}updateHeight(e,t){this._viewZone.heightInPx=e,t.layoutZone(this._viewZoneId),this._contentWidget&&this._editor.layoutContentWidget(this._contentWidget)}computeIfNecessary(e){if(!this._viewZone.isVisible())return null;for(let t=0;t=0;a--)(r=s[a])&&(o=(n<3?r(o):n>3?r(e,t,o):r(e,t))||o);return n>3&&o&&Object.defineProperty(e,t,o),o},ev=function(s,e){return function(t,i){e(t,i,s)}};let W_=class{constructor(e,t,i,n,o,r){this._editor=e,this._languageFeaturesService=t,this._commandService=n,this._notificationService=o,this._codeLensCache=r,this._disposables=new Y,this._localToDispose=new Y,this._lenses=[],this._oldCodeLensModels=new Y,this._provideCodeLensDebounce=i.for(t.codeLensProvider,"CodeLensProvide",{min:250}),this._resolveCodeLensesDebounce=i.for(t.codeLensProvider,"CodeLensResolve",{min:250,salt:"resolve"}),this._resolveCodeLensesScheduler=new Wt(()=>this._resolveCodeLensesInViewport(),this._resolveCodeLensesDebounce.default()),this._disposables.add(this._editor.onDidChangeModel(()=>this._onModelChange())),this._disposables.add(this._editor.onDidChangeModelLanguage(()=>this._onModelChange())),this._disposables.add(this._editor.onDidChangeConfiguration(a=>{(a.hasChanged(50)||a.hasChanged(19)||a.hasChanged(18))&&this._updateLensStyle(),a.hasChanged(17)&&this._onModelChange()})),this._disposables.add(t.codeLensProvider.onDidChange(this._onModelChange,this)),this._onModelChange(),this._updateLensStyle()}dispose(){var e;this._localDispose(),this._disposables.dispose(),this._oldCodeLensModels.dispose(),(e=this._currentCodeLensModel)===null||e===void 0||e.dispose()}_getLayoutInfo(){const e=Math.max(1.3,this._editor.getOption(67)/this._editor.getOption(52));let t=this._editor.getOption(19);return(!t||t<5)&&(t=this._editor.getOption(52)*.9|0),{fontSize:t,codeLensHeight:t*e|0}}_updateLensStyle(){const{codeLensHeight:e,fontSize:t}=this._getLayoutInfo(),i=this._editor.getOption(18),n=this._editor.getOption(50),{style:o}=this._editor.getContainerDomNode();o.setProperty("--vscode-editorCodeLens-lineHeight",`${e}px`),o.setProperty("--vscode-editorCodeLens-fontSize",`${t}px`),o.setProperty("--vscode-editorCodeLens-fontFeatureSettings",n.fontFeatureSettings),i&&(o.setProperty("--vscode-editorCodeLens-fontFamily",i),o.setProperty("--vscode-editorCodeLens-fontFamilyDefault",co.fontFamily)),this._editor.changeViewZones(r=>{for(const a of this._lenses)a.updateHeight(e,r)})}_localDispose(){var e,t,i;(e=this._getCodeLensModelPromise)===null||e===void 0||e.cancel(),this._getCodeLensModelPromise=void 0,(t=this._resolveCodeLensesPromise)===null||t===void 0||t.cancel(),this._resolveCodeLensesPromise=void 0,this._localToDispose.clear(),this._oldCodeLensModels.clear(),(i=this._currentCodeLensModel)===null||i===void 0||i.dispose()}_onModelChange(){this._localDispose();const e=this._editor.getModel();if(!e||!this._editor.getOption(17)||e.isTooLargeForTokenization())return;const t=this._codeLensCache.get(e);if(t&&this._renderCodeLensSymbols(t),!this._languageFeaturesService.codeLensProvider.has(e)){t&&kh(()=>{const n=this._codeLensCache.get(e);t===n&&(this._codeLensCache.delete(e),this._onModelChange())},30*1e3,this._localToDispose);return}for(const n of this._languageFeaturesService.codeLensProvider.all(e))if(typeof n.onDidChange=="function"){const o=n.onDidChange(()=>i.schedule());this._localToDispose.add(o)}const i=new Wt(()=>{var n;const o=Date.now();(n=this._getCodeLensModelPromise)===null||n===void 0||n.cancel(),this._getCodeLensModelPromise=Dn(r=>mq(this._languageFeaturesService.codeLensProvider,e,r)),this._getCodeLensModelPromise.then(r=>{this._currentCodeLensModel&&this._oldCodeLensModels.add(this._currentCodeLensModel),this._currentCodeLensModel=r,this._codeLensCache.put(e,r);const a=this._provideCodeLensDebounce.update(e,Date.now()-o);i.delay=a,this._renderCodeLensSymbols(r),this._resolveCodeLensesInViewportSoon()},Xe)},this._provideCodeLensDebounce.get(e));this._localToDispose.add(i),this._localToDispose.add(Ie(()=>this._resolveCodeLensesScheduler.cancel())),this._localToDispose.add(this._editor.onDidChangeModelContent(()=>{var n;this._editor.changeDecorations(o=>{this._editor.changeViewZones(r=>{const a=[];let l=-1;this._lenses.forEach(c=>{!c.isValid()||l===c.getLineNumber()?a.push(c):(c.update(r),l=c.getLineNumber())});const d=new oT;a.forEach(c=>{c.dispose(d,r),this._lenses.splice(this._lenses.indexOf(c),1)}),d.commit(o)})}),i.schedule(),this._resolveCodeLensesScheduler.cancel(),(n=this._resolveCodeLensesPromise)===null||n===void 0||n.cancel(),this._resolveCodeLensesPromise=void 0})),this._localToDispose.add(this._editor.onDidFocusEditorWidget(()=>{i.schedule()})),this._localToDispose.add(this._editor.onDidBlurEditorText(()=>{i.cancel()})),this._localToDispose.add(this._editor.onDidScrollChange(n=>{n.scrollTopChanged&&this._lenses.length>0&&this._resolveCodeLensesInViewportSoon()})),this._localToDispose.add(this._editor.onDidLayoutChange(()=>{this._resolveCodeLensesInViewportSoon()})),this._localToDispose.add(Ie(()=>{if(this._editor.getModel()){const n=cl.capture(this._editor);this._editor.changeDecorations(o=>{this._editor.changeViewZones(r=>{this._disposeAllLenses(o,r)})}),n.restore(this._editor)}else this._disposeAllLenses(void 0,void 0)})),this._localToDispose.add(this._editor.onMouseDown(n=>{if(n.target.type!==9)return;let o=n.target.element;if((o==null?void 0:o.tagName)==="SPAN"&&(o=o.parentElement),(o==null?void 0:o.tagName)==="A")for(const r of this._lenses){const a=r.getCommand(o);if(a){this._commandService.executeCommand(a.id,...a.arguments||[]).catch(l=>this._notificationService.error(l));break}}})),i.schedule()}_disposeAllLenses(e,t){const i=new oT;for(const n of this._lenses)n.dispose(i,t);e&&i.commit(e),this._lenses.length=0}_renderCodeLensSymbols(e){if(!this._editor.hasModel())return;const t=this._editor.getModel().getLineCount(),i=[];let n;for(const a of e.lenses){const l=a.symbol.range.startLineNumber;l<1||l>t||(n&&n[n.length-1].symbol.range.startLineNumber===l?n.push(a):(n=[a],i.push(n)))}if(!i.length&&!this._lenses.length)return;const o=cl.capture(this._editor),r=this._getLayoutInfo();this._editor.changeDecorations(a=>{this._editor.changeViewZones(l=>{const d=new oT;let c=0,u=0;for(;uthis._resolveCodeLensesInViewportSoon())),c++,u++)}for(;cthis._resolveCodeLensesInViewportSoon())),u++;d.commit(a)})}),o.restore(this._editor)}_resolveCodeLensesInViewportSoon(){this._editor.getModel()&&this._resolveCodeLensesScheduler.schedule()}_resolveCodeLensesInViewport(){var e;(e=this._resolveCodeLensesPromise)===null||e===void 0||e.cancel(),this._resolveCodeLensesPromise=void 0;const t=this._editor.getModel();if(!t)return;const i=[],n=[];if(this._lenses.forEach(a=>{const l=a.computeIfNecessary(t);l&&(i.push(l),n.push(a))}),i.length===0)return;const o=Date.now(),r=Dn(a=>{const l=i.map((d,c)=>{const u=new Array(d.length),h=d.map((g,f)=>!g.symbol.command&&typeof g.provider.resolveCodeLens=="function"?Promise.resolve(g.provider.resolveCodeLens(t,g.symbol,a)).then(m=>{u[f]=m},Ai):(u[f]=g.symbol,Promise.resolve(void 0)));return Promise.all(h).then(()=>{!a.isCancellationRequested&&!n[c].isDisposed()&&n[c].updateCommands(u)})});return Promise.all(l)});this._resolveCodeLensesPromise=r,this._resolveCodeLensesPromise.then(()=>{const a=this._resolveCodeLensesDebounce.update(t,Date.now()-o);this._resolveCodeLensesScheduler.delay=a,this._currentCodeLensModel&&this._codeLensCache.put(t,this._currentCodeLensModel),this._oldCodeLensModels.clear(),r===this._resolveCodeLensesPromise&&(this._resolveCodeLensesPromise=void 0)},a=>{Xe(a),r===this._resolveCodeLensesPromise&&(this._resolveCodeLensesPromise=void 0)})}async getModel(){var e;return await this._getCodeLensModelPromise,await this._resolveCodeLensesPromise,!((e=this._currentCodeLensModel)===null||e===void 0)&&e.isDisposed?void 0:this._currentCodeLensModel}};W_.ID="css.editor.codeLens";W_=lke([ev(1,Ce),ev(2,Ur),ev(3,gi),ev(4,en),ev(5,_q)],W_);kt(W_.ID,W_,1);te(class extends me{constructor(){super({id:"codelens.showLensesInCurrentLine",precondition:T.hasCodeLensProvider,label:p("showLensOnLine","Show CodeLens Commands For Current Line"),alias:"Show CodeLens Commands For Current Line"})}async run(e,t){if(!t.hasModel())return;const i=e.get(hp),n=e.get(gi),o=e.get(en),r=t.getSelection().positionLineNumber,a=t.getContribution(W_.ID);if(!a)return;const l=await a.getModel();if(!l)return;const d=[];for(const h of l.lenses)h.symbol.command&&h.symbol.range.startLineNumber===r&&d.push({label:h.symbol.command.title,command:h.symbol.command});if(d.length===0)return;const c=await i.pick(d,{canPickMany:!1,placeHolder:p("placeHolder","Select a command")});if(!c)return;let u=c.command;if(l.isDisposed){const h=await a.getModel(),g=h==null?void 0:h.lenses.find(f=>{var m;return f.symbol.range.startLineNumber===r&&((m=f.symbol.command)===null||m===void 0?void 0:m.title)===u.title});if(!g||!g.symbol.command)return;u=g.symbol.command}try{await n.executeCommand(u.id,...u.arguments||[])}catch(h){o.error(h)}}});var dke=function(s,e,t,i){var n=arguments.length,o=n<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,r;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(s,e,t,i);else for(var a=s.length-1;a>=0;a--)(r=s[a])&&(o=(n<3?r(o):n>3?r(e,t,o):r(e,t))||o);return n>3&&o&&Object.defineProperty(e,t,o),o},rT=function(s,e){return function(t,i){e(t,i,s)}};class p4{constructor(e,t){this._editorWorkerClient=new LF(e,!1,"editorWorkerService",t)}async provideDocumentColors(e,t){return this._editorWorkerClient.computeDefaultDocumentColors(e.uri)}provideColorPresentations(e,t,i){const n=t.range,o=t.color,r=o.alpha,a=new $(new bt(Math.round(255*o.red),Math.round(255*o.green),Math.round(255*o.blue),r)),l=r?$.Format.CSS.formatRGB(a):$.Format.CSS.formatRGBA(a),d=r?$.Format.CSS.formatHSL(a):$.Format.CSS.formatHSLA(a),c=r?$.Format.CSS.formatHex(a):$.Format.CSS.formatHexA(a),u=[];return u.push({label:l,textEdit:{range:n,text:l}}),u.push({label:d,textEdit:{range:n,text:d}}),u.push({label:c,textEdit:{range:n,text:c}}),u}}let zM=class extends H{constructor(e,t,i){super(),this._register(i.colorProvider.register("*",new p4(e,t)))}};zM=dke([rT(0,_i),rT(1,Yt),rT(2,Ce)],zM);F1(zM);async function vq(s,e,t,i=!0){return m4(new cke,s,e,t,i)}function bq(s,e,t,i){return Promise.resolve(t.provideColorPresentations(s,e,i))}class cke{constructor(){}async compute(e,t,i,n){const o=await e.provideDocumentColors(t,i);if(Array.isArray(o))for(const r of o)n.push({colorInfo:r,provider:e});return Array.isArray(o)}}class uke{constructor(){}async compute(e,t,i,n){const o=await e.provideDocumentColors(t,i);if(Array.isArray(o))for(const r of o)n.push({range:r.range,color:[r.color.red,r.color.green,r.color.blue,r.color.alpha]});return Array.isArray(o)}}class hke{constructor(e){this.colorInfo=e}async compute(e,t,i,n){const o=await e.provideColorPresentations(t,this.colorInfo,dt.None);return Array.isArray(o)&&n.push(...o),Array.isArray(o)}}async function m4(s,e,t,i,n){let o=!1,r;const a=[],l=e.ordered(t);for(let d=l.length-1;d>=0;d--){const c=l[d];if(c instanceof p4)r=c;else try{await s.compute(c,t,i,a)&&(o=!0)}catch(u){Ai(u)}}return o?a:r&&n?(await s.compute(r,t,i,a),a):[]}function Cq(s,e){const{colorProvider:t}=s.get(Ce),i=s.get(_i).getModel(e);if(!i)throw Mr();const n=s.get(rt).getValue("editor.defaultColorDecorators",{resource:e});return{model:i,colorProviderRegistry:t,isDefaultColorDecoratorsEnabled:n}}pt.registerCommand("_executeDocumentColorProvider",function(s,...e){const[t]=e;if(!(t instanceof Ae))throw Mr();const{model:i,colorProviderRegistry:n,isDefaultColorDecoratorsEnabled:o}=Cq(s,t);return m4(new uke,n,i,dt.None,o)});pt.registerCommand("_executeColorPresentationProvider",function(s,...e){const[t,i]=e,{uri:n,range:o}=i;if(!(n instanceof Ae)||!Array.isArray(t)||t.length!==4||!x.isIRange(o))throw Mr();const{model:r,colorProviderRegistry:a,isDefaultColorDecoratorsEnabled:l}=Cq(s,n),[d,c,u,h]=t;return m4(new hke({range:o,color:{red:d,green:c,blue:u,alpha:h}}),a,r,dt.None,l)});var gke=function(s,e,t,i){var n=arguments.length,o=n<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,r;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(s,e,t,i);else for(var a=s.length-1;a>=0;a--)(r=s[a])&&(o=(n<3?r(o):n>3?r(e,t,o):r(e,t))||o);return n>3&&o&&Object.defineProperty(e,t,o),o},aT=function(s,e){return function(t,i){e(t,i,s)}},UM;const wq=Object.create({});let Vh=UM=class extends H{constructor(e,t,i,n){super(),this._editor=e,this._configurationService=t,this._languageFeaturesService=i,this._localToDispose=this._register(new Y),this._decorationsIds=[],this._colorDatas=new Map,this._colorDecoratorIds=this._editor.createDecorationsCollection(),this._ruleFactory=new v1(this._editor),this._decoratorLimitReporter=new fke,this._colorDecorationClassRefs=this._register(new Y),this._debounceInformation=n.for(i.colorProvider,"Document Colors",{min:UM.RECOMPUTE_TIME}),this._register(e.onDidChangeModel(()=>{this._isColorDecoratorsEnabled=this.isEnabled(),this.updateColors()})),this._register(e.onDidChangeModelLanguage(()=>this.updateColors())),this._register(i.colorProvider.onDidChange(()=>this.updateColors())),this._register(e.onDidChangeConfiguration(o=>{const r=this._isColorDecoratorsEnabled;this._isColorDecoratorsEnabled=this.isEnabled(),this._isDefaultColorDecoratorsEnabled=this._editor.getOption(147);const a=r!==this._isColorDecoratorsEnabled||o.hasChanged(21),l=o.hasChanged(147);(a||l)&&(this._isColorDecoratorsEnabled?this.updateColors():this.removeAllDecorations())})),this._timeoutTimer=null,this._computePromise=null,this._isColorDecoratorsEnabled=this.isEnabled(),this._isDefaultColorDecoratorsEnabled=this._editor.getOption(147),this.updateColors()}isEnabled(){const e=this._editor.getModel();if(!e)return!1;const t=e.getLanguageId(),i=this._configurationService.getValue(t);if(i&&typeof i=="object"){const n=i.colorDecorators;if(n&&n.enable!==void 0&&!n.enable)return n.enable}return this._editor.getOption(20)}static get(e){return e.getContribution(this.ID)}dispose(){this.stop(),this.removeAllDecorations(),super.dispose()}updateColors(){if(this.stop(),!this._isColorDecoratorsEnabled)return;const e=this._editor.getModel();!e||!this._languageFeaturesService.colorProvider.has(e)||(this._localToDispose.add(this._editor.onDidChangeModelContent(()=>{this._timeoutTimer||(this._timeoutTimer=new ya,this._timeoutTimer.cancelAndSet(()=>{this._timeoutTimer=null,this.beginCompute()},this._debounceInformation.get(e)))})),this.beginCompute())}async beginCompute(){this._computePromise=Dn(async e=>{const t=this._editor.getModel();if(!t)return[];const i=new Jn(!1),n=await vq(this._languageFeaturesService.colorProvider,t,e,this._isDefaultColorDecoratorsEnabled);return this._debounceInformation.update(t,i.elapsed()),n});try{const e=await this._computePromise;this.updateDecorations(e),this.updateColorDecorators(e),this._computePromise=null}catch(e){Xe(e)}}stop(){this._timeoutTimer&&(this._timeoutTimer.cancel(),this._timeoutTimer=null),this._computePromise&&(this._computePromise.cancel(),this._computePromise=null),this._localToDispose.clear()}updateDecorations(e){const t=e.map(i=>({range:{startLineNumber:i.colorInfo.range.startLineNumber,startColumn:i.colorInfo.range.startColumn,endLineNumber:i.colorInfo.range.endLineNumber,endColumn:i.colorInfo.range.endColumn},options:Ye.EMPTY}));this._editor.changeDecorations(i=>{this._decorationsIds=i.deltaDecorations(this._decorationsIds,t),this._colorDatas=new Map,this._decorationsIds.forEach((n,o)=>this._colorDatas.set(n,e[o]))})}updateColorDecorators(e){this._colorDecorationClassRefs.clear();const t=[],i=this._editor.getOption(21);for(let o=0;othis._colorDatas.has(n.id));return i.length===0?null:this._colorDatas.get(i[0].id)}isColorDecoration(e){return this._colorDecoratorIds.has(e)}};Vh.ID="editor.contrib.colorDetector";Vh.RECOMPUTE_TIME=1e3;Vh=UM=gke([aT(1,rt),aT(2,Ce),aT(3,Ur)],Vh);class fke{constructor(){this._onDidChange=new B,this._computed=0,this._limited=!1}update(e,t){(e!==this._computed||t!==this._limited)&&(this._computed=e,this._limited=t,this._onDidChange.fire())}}kt(Vh.ID,Vh,1);class pke{get color(){return this._color}set color(e){this._color.equals(e)||(this._color=e,this._onDidChangeColor.fire(e))}get presentation(){return this.colorPresentations[this.presentationIndex]}get colorPresentations(){return this._colorPresentations}set colorPresentations(e){this._colorPresentations=e,this.presentationIndex>e.length-1&&(this.presentationIndex=0),this._onDidChangePresentation.fire(this.presentation)}constructor(e,t,i){this.presentationIndex=i,this._onColorFlushed=new B,this.onColorFlushed=this._onColorFlushed.event,this._onDidChangeColor=new B,this.onDidChangeColor=this._onDidChangeColor.event,this._onDidChangePresentation=new B,this.onDidChangePresentation=this._onDidChangePresentation.event,this.originalColor=e,this._color=e,this._colorPresentations=t}selectNextColorPresentation(){this.presentationIndex=(this.presentationIndex+1)%this.colorPresentations.length,this.flushColor(),this._onDidChangePresentation.fire(this.presentation)}guessColorPresentation(e,t){let i=-1;for(let n=0;n{this.backgroundColor=r.getColor(iD)||$.white})),this._register(K(this._pickedColorNode,ee.CLICK,()=>this.model.selectNextColorPresentation())),this._register(K(this._originalColorNode,ee.CLICK,()=>{this.model.color=this.model.originalColor,this.model.flushColor()})),this._register(t.onDidChangeColor(this.onDidChangeColor,this)),this._register(t.onDidChangePresentation(this.onDidChangePresentation,this)),this._pickedColorNode.style.backgroundColor=$.Format.CSS.format(t.color)||"",this._pickedColorNode.classList.toggle("light",t.color.rgba.a<.5?this.backgroundColor.isLighter():t.color.isLighter()),this.onDidChangeColor(this.model.color),this.showingStandaloneColorPicker&&(this._domNode.classList.add("standalone-colorpicker"),this._closeButton=this._register(new _ke(this._domNode)))}get closeButton(){return this._closeButton}get pickedColorNode(){return this._pickedColorNode}get originalColorNode(){return this._originalColorNode}onDidChangeColor(e){this._pickedColorNode.style.backgroundColor=$.Format.CSS.format(e)||"",this._pickedColorNode.classList.toggle("light",e.rgba.a<.5?this.backgroundColor.isLighter():e.isLighter()),this.onDidChangePresentation()}onDidChangePresentation(){this._pickedColorPresentation.textContent=this.model.presentation?this.model.presentation.label:""}}class _ke extends H{constructor(e){super(),this._onClicked=this._register(new B),this.onClicked=this._onClicked.event,this._button=document.createElement("div"),this._button.classList.add("close-button"),Q(e,this._button);const t=document.createElement("div");t.classList.add("close-button-inner-div"),Q(this._button,t),Q(t,Yo(".button"+Pe.asCSSSelector(xi("color-picker-close",oe.close,p("closeIcon","Icon to close the color picker"))))).classList.add("close-icon"),this._register(K(this._button,ee.CLICK,()=>{this._onClicked.fire()}))}}class vke extends H{constructor(e,t,i,n=!1){super(),this.model=t,this.pixelRatio=i,this._insertButton=null,this._domNode=Yo(".colorpicker-body"),Q(e,this._domNode),this._saturationBox=new bke(this._domNode,this.model,this.pixelRatio),this._register(this._saturationBox),this._register(this._saturationBox.onDidChange(this.onDidSaturationValueChange,this)),this._register(this._saturationBox.onColorFlushed(this.flushColor,this)),this._opacityStrip=new Cke(this._domNode,this.model,n),this._register(this._opacityStrip),this._register(this._opacityStrip.onDidChange(this.onDidOpacityChange,this)),this._register(this._opacityStrip.onColorFlushed(this.flushColor,this)),this._hueStrip=new wke(this._domNode,this.model,n),this._register(this._hueStrip),this._register(this._hueStrip.onDidChange(this.onDidHueChange,this)),this._register(this._hueStrip.onColorFlushed(this.flushColor,this)),n&&(this._insertButton=this._register(new yke(this._domNode)),this._domNode.classList.add("standalone-colorpicker"))}flushColor(){this.model.flushColor()}onDidSaturationValueChange({s:e,v:t}){const i=this.model.color.hsva;this.model.color=new $(new Yl(i.h,e,t,i.a))}onDidOpacityChange(e){const t=this.model.color.hsva;this.model.color=new $(new Yl(t.h,t.s,t.v,e))}onDidHueChange(e){const t=this.model.color.hsva,i=(1-e)*360;this.model.color=new $(new Yl(i===360?0:i,t.s,t.v,t.a))}get domNode(){return this._domNode}get saturationBox(){return this._saturationBox}get enterButton(){return this._insertButton}layout(){this._saturationBox.layout(),this._opacityStrip.layout(),this._hueStrip.layout()}}class bke extends H{constructor(e,t,i){super(),this.model=t,this.pixelRatio=i,this._onDidChange=new B,this.onDidChange=this._onDidChange.event,this._onColorFlushed=new B,this.onColorFlushed=this._onColorFlushed.event,this._domNode=Yo(".saturation-wrap"),Q(e,this._domNode),this._canvas=document.createElement("canvas"),this._canvas.className="saturation-box",Q(this._domNode,this._canvas),this.selection=Yo(".saturation-selection"),Q(this._domNode,this.selection),this.layout(),this._register(K(this._domNode,ee.POINTER_DOWN,n=>this.onPointerDown(n))),this._register(this.model.onDidChangeColor(this.onDidChangeColor,this)),this.monitor=null}get domNode(){return this._domNode}onPointerDown(e){if(!e.target||!(e.target instanceof Element))return;this.monitor=this._register(new c0);const t=qi(this._domNode);e.target!==this.selection&&this.onDidChangePosition(e.offsetX,e.offsetY),this.monitor.startMonitoring(e.target,e.pointerId,e.buttons,n=>this.onDidChangePosition(n.pageX-t.left,n.pageY-t.top),()=>null);const i=K(e.target.ownerDocument,ee.POINTER_UP,()=>{this._onColorFlushed.fire(),i.dispose(),this.monitor&&(this.monitor.stopMonitoring(!0),this.monitor=null)},!0)}onDidChangePosition(e,t){const i=Math.max(0,Math.min(1,e/this.width)),n=Math.max(0,Math.min(1,1-t/this.height));this.paintSelection(i,n),this._onDidChange.fire({s:i,v:n})}layout(){this.width=this._domNode.offsetWidth,this.height=this._domNode.offsetHeight,this._canvas.width=this.width*this.pixelRatio,this._canvas.height=this.height*this.pixelRatio,this.paint();const e=this.model.color.hsva;this.paintSelection(e.s,e.v)}paint(){const e=this.model.color.hsva,t=new $(new Yl(e.h,1,1,1)),i=this._canvas.getContext("2d"),n=i.createLinearGradient(0,0,this._canvas.width,0);n.addColorStop(0,"rgba(255, 255, 255, 1)"),n.addColorStop(.5,"rgba(255, 255, 255, 0.5)"),n.addColorStop(1,"rgba(255, 255, 255, 0)");const o=i.createLinearGradient(0,0,0,this._canvas.height);o.addColorStop(0,"rgba(0, 0, 0, 0)"),o.addColorStop(1,"rgba(0, 0, 0, 1)"),i.rect(0,0,this._canvas.width,this._canvas.height),i.fillStyle=$.Format.CSS.format(t),i.fill(),i.fillStyle=n,i.fill(),i.fillStyle=o,i.fill()}paintSelection(e,t){this.selection.style.left=`${e*this.width}px`,this.selection.style.top=`${this.height-t*this.height}px`}onDidChangeColor(e){if(this.monitor&&this.monitor.isMonitoring())return;this.paint();const t=e.hsva;this.paintSelection(t.s,t.v)}}class yq extends H{constructor(e,t,i=!1){super(),this.model=t,this._onDidChange=new B,this.onDidChange=this._onDidChange.event,this._onColorFlushed=new B,this.onColorFlushed=this._onColorFlushed.event,i?(this.domNode=Q(e,Yo(".standalone-strip")),this.overlay=Q(this.domNode,Yo(".standalone-overlay"))):(this.domNode=Q(e,Yo(".strip")),this.overlay=Q(this.domNode,Yo(".overlay"))),this.slider=Q(this.domNode,Yo(".slider")),this.slider.style.top="0px",this._register(K(this.domNode,ee.POINTER_DOWN,n=>this.onPointerDown(n))),this._register(t.onDidChangeColor(this.onDidChangeColor,this)),this.layout()}layout(){this.height=this.domNode.offsetHeight-this.slider.offsetHeight;const e=this.getValue(this.model.color);this.updateSliderPosition(e)}onDidChangeColor(e){const t=this.getValue(e);this.updateSliderPosition(t)}onPointerDown(e){if(!e.target||!(e.target instanceof Element))return;const t=this._register(new c0),i=qi(this.domNode);this.domNode.classList.add("grabbing"),e.target!==this.slider&&this.onDidChangeTop(e.offsetY),t.startMonitoring(e.target,e.pointerId,e.buttons,o=>this.onDidChangeTop(o.pageY-i.top),()=>null);const n=K(e.target.ownerDocument,ee.POINTER_UP,()=>{this._onColorFlushed.fire(),n.dispose(),t.stopMonitoring(!0),this.domNode.classList.remove("grabbing")},!0)}onDidChangeTop(e){const t=Math.max(0,Math.min(1,1-e/this.height));this.updateSliderPosition(t),this._onDidChange.fire(t)}updateSliderPosition(e){this.slider.style.top=`${(1-e)*this.height}px`}}class Cke extends yq{constructor(e,t,i=!1){super(e,t,i),this.domNode.classList.add("opacity-strip"),this.onDidChangeColor(this.model.color)}onDidChangeColor(e){super.onDidChangeColor(e);const{r:t,g:i,b:n}=e.rgba,o=new $(new bt(t,i,n,1)),r=new $(new bt(t,i,n,0));this.overlay.style.background=`linear-gradient(to bottom, ${o} 0%, ${r} 100%)`}getValue(e){return e.hsva.a}}class wke extends yq{constructor(e,t,i=!1){super(e,t,i),this.domNode.classList.add("hue-strip")}getValue(e){return 1-e.hsva.h/360}}class yke extends H{constructor(e){super(),this._onClicked=this._register(new B),this.onClicked=this._onClicked.event,this._button=Q(e,document.createElement("button")),this._button.classList.add("insert-button"),this._button.textContent="Insert",this._register(K(this._button,ee.CLICK,()=>{this._onClicked.fire()}))}get button(){return this._button}}class Ske extends fr{constructor(e,t,i,n,o=!1){super(),this.model=t,this.pixelRatio=i,this._register(Ob.getInstance(Te(e)).onDidChange(()=>this.layout()));const r=Yo(".colorpicker-widget");e.appendChild(r),this.header=this._register(new mke(r,this.model,n,o)),this.body=this._register(new vke(r,this.model,this.pixelRatio,o))}layout(){this.body.layout()}}var Sq=function(s,e,t,i){var n=arguments.length,o=n<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,r;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(s,e,t,i);else for(var a=s.length-1;a>=0;a--)(r=s[a])&&(o=(n<3?r(o):n>3?r(e,t,o):r(e,t))||o);return n>3&&o&&Object.defineProperty(e,t,o),o},Dq=function(s,e){return function(t,i){e(t,i,s)}};class Dke{constructor(e,t,i,n){this.owner=e,this.range=t,this.model=i,this.provider=n,this.forceShowAtRange=!0}isValidForHoverAnchor(e){return e.type===1&&this.range.startColumn<=e.range.startColumn&&this.range.endColumn>=e.range.endColumn}}let hL=class{constructor(e,t){this._editor=e,this._themeService=t,this.hoverOrdinal=2}computeSync(e,t){return[]}computeAsync(e,t,i){return Xi.fromPromise(this._computeAsync(e,t,i))}async _computeAsync(e,t,i){if(!this._editor.hasModel())return[];const n=Vh.get(this._editor);if(!n)return[];for(const o of t){if(!n.isColorDecoration(o))continue;const r=n.getColorData(o.range.getStartPosition());if(r)return[await Lq(this,this._editor.getModel(),r.colorInfo,r.provider)]}return[]}renderHoverParts(e,t){return xq(this,this._editor,this._themeService,t,e)}};hL=Sq([Dq(1,_n)],hL);class Lke{constructor(e,t,i,n){this.owner=e,this.range=t,this.model=i,this.provider=n}}let MC=class{constructor(e,t){this._editor=e,this._themeService=t,this._color=null}async createColorHover(e,t,i){if(!this._editor.hasModel()||!Vh.get(this._editor))return null;const o=await vq(i,this._editor.getModel(),dt.None);let r=null,a=null;for(const u of o){const h=u.colorInfo;x.containsRange(h.range,e.range)&&(r=h,a=u.provider)}const l=r??e,d=a??t,c=!!r;return{colorHover:await Lq(this,this._editor.getModel(),l,d),foundInEditor:c}}async updateEditorModel(e){if(!this._editor.hasModel())return;const t=e.model;let i=new x(e.range.startLineNumber,e.range.startColumn,e.range.endLineNumber,e.range.endColumn);this._color&&(await dS(this._editor.getModel(),t,this._color,i,e),i=kq(this._editor,i,t))}renderHoverParts(e,t){return xq(this,this._editor,this._themeService,t,e)}set color(e){this._color=e}get color(){return this._color}};MC=Sq([Dq(1,_n)],MC);async function Lq(s,e,t,i){const n=e.getValueInRange(t.range),{red:o,green:r,blue:a,alpha:l}=t.color,d=new bt(Math.round(o*255),Math.round(r*255),Math.round(a*255),l),c=new $(d),u=await bq(e,t,i,dt.None),h=new pke(c,[],0);return h.colorPresentations=u||[],h.guessColorPresentation(c,n),s instanceof hL?new Dke(s,x.lift(t.range),h,i):new Lke(s,x.lift(t.range),h,i)}function xq(s,e,t,i,n){if(i.length===0||!e.hasModel())return H.None;if(n.setMinimumDimensions){const h=e.getOption(67)+8;n.setMinimumDimensions(new Dt(302,h))}const o=new Y,r=i[0],a=e.getModel(),l=r.model,d=o.add(new Ske(n.fragment,l,e.getOption(143),t,s instanceof MC));n.setColorPicker(d);let c=!1,u=new x(r.range.startLineNumber,r.range.startColumn,r.range.endLineNumber,r.range.endColumn);if(s instanceof MC){const h=i[0].model.color;s.color=h,dS(a,l,h,u,r),o.add(l.onColorFlushed(g=>{s.color=g}))}else o.add(l.onColorFlushed(async h=>{await dS(a,l,h,u,r),c=!0,u=kq(e,u,l)}));return o.add(l.onDidChangeColor(h=>{dS(a,l,h,u,r)})),o.add(e.onDidChangeModelContent(h=>{c?c=!1:(n.hide(),e.focus())})),o}function kq(s,e,t){var i,n;const o=[],r=(i=t.presentation.textEdit)!==null&&i!==void 0?i:{range:e,text:t.presentation.label,forceMoveMarkers:!1};o.push(r),t.presentation.additionalTextEdits&&o.push(...t.presentation.additionalTextEdits);const a=x.lift(r.range),l=s.getModel()._setTrackedRange(null,a,3);return s.executeEdits("colorpicker",o),s.pushUndoStop(),(n=s.getModel()._getTrackedRange(l))!==null&&n!==void 0?n:a}async function dS(s,e,t,i,n){const o=await bq(s,{range:i,color:{red:t.rgba.r/255,green:t.rgba.g/255,blue:t.rgba.b/255,alpha:t.rgba.a}},n.provider,dt.None);e.colorPresentations=o||[]}const Eq="editor.action.showHover",xke="editor.action.showDefinitionPreviewHover",kke="editor.action.scrollUpHover",Eke="editor.action.scrollDownHover",Ike="editor.action.scrollLeftHover",Tke="editor.action.scrollRightHover",Nke="editor.action.pageUpHover",Ake="editor.action.pageDownHover",Mke="editor.action.goToTopHover",Rke="editor.action.goToBottomHover",_4="editor.action.increaseHoverVerbosityLevel",v4="editor.action.decreaseHoverVerbosityLevel",Iq="editor.action.inlineSuggest.commit",Tq="editor.action.inlineSuggest.showPrevious",Nq="editor.action.inlineSuggest.showNext";var b4=function(s,e,t,i){var n=arguments.length,o=n<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,r;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(s,e,t,i);else for(var a=s.length-1;a>=0;a--)(r=s[a])&&(o=(n<3?r(o):n>3?r(e,t,o):r(e,t))||o);return n>3&&o&&Object.defineProperty(e,t,o),o},oa=function(s,e){return function(t,i){e(t,i,s)}},cS;let $M=class extends H{constructor(e,t,i){super(),this.editor=e,this.model=t,this.instantiationService=i,this.alwaysShowToolbar=Ot(this.editor.onDidChangeConfiguration,()=>this.editor.getOption(62).showToolbar==="always"),this.sessionPosition=void 0,this.position=je(this,n=>{var o,r,a;const l=(o=this.model.read(n))===null||o===void 0?void 0:o.primaryGhostText.read(n);if(!this.alwaysShowToolbar.read(n)||!l||l.parts.length===0)return this.sessionPosition=void 0,null;const d=l.parts[0].column;this.sessionPosition&&this.sessionPosition.lineNumber!==l.lineNumber&&(this.sessionPosition=void 0);const c=new W(l.lineNumber,Math.min(d,(a=(r=this.sessionPosition)===null||r===void 0?void 0:r.column)!==null&&a!==void 0?a:Number.MAX_SAFE_INTEGER));return this.sessionPosition=c,c}),this._register(Hr((n,o)=>{const r=this.model.read(n);if(!r||!this.alwaysShowToolbar.read(n))return;const a=o.add(this.instantiationService.createInstance(zh,this.editor,!0,this.position,r.selectedInlineCompletionIndex,r.inlineCompletionsCount,r.activeCommands));e.addContentWidget(a),o.add(Ie(()=>e.removeContentWidget(a))),o.add(st(l=>{this.position.read(l)&&r.lastTriggerKind.read(l)!==kc.Explicit&&r.triggerExplicitly()}))}))}};$M=b4([oa(2,Ne)],$M);const Pke=xi("inline-suggestion-hints-next",oe.chevronRight,p("parameterHintsNextIcon","Icon for show next parameter hint.")),Fke=xi("inline-suggestion-hints-previous",oe.chevronLeft,p("parameterHintsPreviousIcon","Icon for show previous parameter hint."));let zh=cS=class extends H{static get dropDownVisible(){return this._dropDownVisible}createCommandAction(e,t,i){const n=new Eo(e,t,i,!0,()=>this._commandService.executeCommand(e)),o=this.keybindingService.lookupKeybinding(e,this._contextKeyService);let r=t;return o&&(r=p({},"{0} ({1})",t,o.getLabel())),n.tooltip=r,n}constructor(e,t,i,n,o,r,a,l,d,c,u){super(),this.editor=e,this.withBorder=t,this._position=i,this._currentSuggestionIdx=n,this._suggestionCount=o,this._extraCommands=r,this._commandService=a,this.keybindingService=d,this._contextKeyService=c,this._menuService=u,this.id=`InlineSuggestionHintsContentWidget${cS.id++}`,this.allowEditorOverflow=!0,this.suppressMouseDown=!1,this.nodes=Nt("div.inlineSuggestionsHints",{className:this.withBorder?".withBorder":""},[Nt("div@toolBar")]),this.previousAction=this.createCommandAction(Tq,p("previous","Previous"),Pe.asClassName(Fke)),this.availableSuggestionCountAction=new Eo("inlineSuggestionHints.availableSuggestionCount","",void 0,!1),this.nextAction=this.createCommandAction(Nq,p("next","Next"),Pe.asClassName(Pke)),this.inlineCompletionsActionsMenus=this._register(this._menuService.createMenu(E.InlineCompletionsActions,this._contextKeyService)),this.clearAvailableSuggestionCountLabelDebounced=this._register(new Wt(()=>{this.availableSuggestionCountAction.label=""},100)),this.disableButtonsDebounced=this._register(new Wt(()=>{this.previousAction.enabled=this.nextAction.enabled=!1},100)),this.toolBar=this._register(l.createInstance(jM,this.nodes.toolBar,E.InlineSuggestionToolbar,{menuOptions:{renderShortTitle:!0},toolbarOptions:{primaryGroup:h=>h.startsWith("primary")},actionViewItemProvider:(h,g)=>{if(h instanceof Io)return l.createInstance(Bke,h,void 0);if(h===this.availableSuggestionCountAction){const f=new Oke(void 0,h,{label:!0,icon:!1});return f.setClass("availableSuggestionCount"),f}},telemetrySource:"InlineSuggestionToolbar"})),this.toolBar.setPrependedPrimaryActions([this.previousAction,this.availableSuggestionCountAction,this.nextAction]),this._register(this.toolBar.onDidChangeDropdownVisibility(h=>{cS._dropDownVisible=h})),this._register(st(h=>{this._position.read(h),this.editor.layoutContentWidget(this)})),this._register(st(h=>{const g=this._suggestionCount.read(h),f=this._currentSuggestionIdx.read(h);g!==void 0?(this.clearAvailableSuggestionCountLabelDebounced.cancel(),this.availableSuggestionCountAction.label=`${f+1}/${g}`):this.clearAvailableSuggestionCountLabelDebounced.schedule(),g!==void 0&&g>1?(this.disableButtonsDebounced.cancel(),this.previousAction.enabled=this.nextAction.enabled=!0):this.disableButtonsDebounced.schedule()})),this._register(st(h=>{const f=this._extraCommands.read(h).map(m=>({class:void 0,id:m.id,enabled:!0,tooltip:m.tooltip||"",label:m.title,run:_=>this._commandService.executeCommand(m.id)}));for(const[m,_]of this.inlineCompletionsActionsMenus.getActions())for(const v of _)v instanceof Io&&f.push(v);f.length>0&&f.unshift(new rn),this.toolBar.setAdditionalSecondaryActions(f)}))}getId(){return this.id}getDomNode(){return this.nodes.root}getPosition(){return{position:this._position.get(),preference:[1,2],positionAffinity:3}}};zh._dropDownVisible=!1;zh.id=0;zh=cS=b4([oa(6,gi),oa(7,Ne),oa(8,At),oa(9,Be),oa(10,hr)],zh);class Oke extends N_{constructor(){super(...arguments),this._className=void 0}setClass(e){this._className=e}render(e){super.render(e),this._className&&e.classList.add(this._className)}updateTooltip(){}}let Bke=class extends Fh{updateLabel(){const e=this._keybindingService.lookupKeybinding(this._action.id,this._contextKeyService);if(!e)return super.updateLabel();if(this.label){const t=Nt("div.keybinding").root;this._register(new m0(t,Lo,{disableTitle:!0,...tK})).set(e),this.label.textContent=this._action.label,this.label.appendChild(t),this.label.classList.add("inlineSuggestionStatusBarItemLabel")}}updateTooltip(){}},jM=class extends LC{constructor(e,t,i,n,o,r,a,l,d){super(e,{resetMenu:t,...i},n,o,r,a,l,d),this.menuId=t,this.options2=i,this.menuService=n,this.contextKeyService=o,this.menu=this._store.add(this.menuService.createMenu(this.menuId,this.contextKeyService,{emitEventsForSubmenuChanges:!0})),this.additionalActions=[],this.prependedPrimaryActions=[],this._store.add(this.menu.onDidChange(()=>this.updateToolbar())),this.updateToolbar()}updateToolbar(){var e,t,i,n,o,r,a;const l=[],d=[];Qx(this.menu,(e=this.options2)===null||e===void 0?void 0:e.menuOptions,{primary:l,secondary:d},(i=(t=this.options2)===null||t===void 0?void 0:t.toolbarOptions)===null||i===void 0?void 0:i.primaryGroup,(o=(n=this.options2)===null||n===void 0?void 0:n.toolbarOptions)===null||o===void 0?void 0:o.shouldInlineSubmenu,(a=(r=this.options2)===null||r===void 0?void 0:r.toolbarOptions)===null||a===void 0?void 0:a.useSeparatorsInPrimaryActions),d.push(...this.additionalActions),l.unshift(...this.prependedPrimaryActions),this.setActions(l,d)}setPrependedPrimaryActions(e){Ci(this.prependedPrimaryActions,e,(t,i)=>t===i)||(this.prependedPrimaryActions=e,this.updateToolbar())}setAdditionalSecondaryActions(e){Ci(this.additionalActions,e,(t,i)=>t===i)||(this.additionalActions=e,this.updateToolbar())}};jM=b4([oa(3,hr),oa(4,Be),oa(5,Oo),oa(6,At),oa(7,gi),oa(8,Gs)],jM);class C4{constructor(){this._onDidWillResize=new B,this.onDidWillResize=this._onDidWillResize.event,this._onDidResize=new B,this.onDidResize=this._onDidResize.event,this._sashListener=new Y,this._size=new Dt(0,0),this._minSize=new Dt(0,0),this._maxSize=new Dt(Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER),this.domNode=document.createElement("div"),this._eastSash=new is(this.domNode,{getVerticalSashLeft:()=>this._size.width},{orientation:0}),this._westSash=new is(this.domNode,{getVerticalSashLeft:()=>0},{orientation:0}),this._northSash=new is(this.domNode,{getHorizontalSashTop:()=>0},{orientation:1,orthogonalEdge:OD.North}),this._southSash=new is(this.domNode,{getHorizontalSashTop:()=>this._size.height},{orientation:1,orthogonalEdge:OD.South}),this._northSash.orthogonalStartSash=this._westSash,this._northSash.orthogonalEndSash=this._eastSash,this._southSash.orthogonalStartSash=this._westSash,this._southSash.orthogonalEndSash=this._eastSash;let e,t=0,i=0;this._sashListener.add(le.any(this._northSash.onDidStart,this._eastSash.onDidStart,this._southSash.onDidStart,this._westSash.onDidStart)(()=>{e===void 0&&(this._onDidWillResize.fire(),e=this._size,t=0,i=0)})),this._sashListener.add(le.any(this._northSash.onDidEnd,this._eastSash.onDidEnd,this._southSash.onDidEnd,this._westSash.onDidEnd)(()=>{e!==void 0&&(e=void 0,t=0,i=0,this._onDidResize.fire({dimension:this._size,done:!0}))})),this._sashListener.add(this._eastSash.onDidChange(n=>{e&&(i=n.currentX-n.startX,this.layout(e.height+t,e.width+i),this._onDidResize.fire({dimension:this._size,done:!1,east:!0}))})),this._sashListener.add(this._westSash.onDidChange(n=>{e&&(i=-(n.currentX-n.startX),this.layout(e.height+t,e.width+i),this._onDidResize.fire({dimension:this._size,done:!1,west:!0}))})),this._sashListener.add(this._northSash.onDidChange(n=>{e&&(t=-(n.currentY-n.startY),this.layout(e.height+t,e.width+i),this._onDidResize.fire({dimension:this._size,done:!1,north:!0}))})),this._sashListener.add(this._southSash.onDidChange(n=>{e&&(t=n.currentY-n.startY,this.layout(e.height+t,e.width+i),this._onDidResize.fire({dimension:this._size,done:!1,south:!0}))})),this._sashListener.add(le.any(this._eastSash.onDidReset,this._westSash.onDidReset)(n=>{this._preferredSize&&(this.layout(this._size.height,this._preferredSize.width),this._onDidResize.fire({dimension:this._size,done:!0}))})),this._sashListener.add(le.any(this._northSash.onDidReset,this._southSash.onDidReset)(n=>{this._preferredSize&&(this.layout(this._preferredSize.height,this._size.width),this._onDidResize.fire({dimension:this._size,done:!0}))}))}dispose(){this._northSash.dispose(),this._southSash.dispose(),this._eastSash.dispose(),this._westSash.dispose(),this._sashListener.dispose(),this._onDidResize.dispose(),this._onDidWillResize.dispose(),this.domNode.remove()}enableSashes(e,t,i,n){this._northSash.state=e?3:0,this._eastSash.state=t?3:0,this._southSash.state=i?3:0,this._westSash.state=n?3:0}layout(e=this.size.height,t=this.size.width){const{height:i,width:n}=this._minSize,{height:o,width:r}=this._maxSize;e=Math.max(i,Math.min(o,e)),t=Math.max(n,Math.min(r,t));const a=new Dt(t,e);Dt.equals(a,this._size)||(this.domNode.style.height=e+"px",this.domNode.style.width=t+"px",this._size=a,this._northSash.layout(),this._eastSash.layout(),this._southSash.layout(),this._westSash.layout())}clearSashHoverState(){this._eastSash.clearSashHoverState(),this._westSash.clearSashHoverState(),this._northSash.clearSashHoverState(),this._southSash.clearSashHoverState()}get size(){return this._size}set maxSize(e){this._maxSize=e}get maxSize(){return this._maxSize}set minSize(e){this._minSize=e}get minSize(){return this._minSize}set preferredSize(e){this._preferredSize=e}get preferredSize(){return this._preferredSize}}const Wke=30,Hke=24;class Vke extends H{constructor(e,t=new Dt(10,10)){super(),this._editor=e,this.allowEditorOverflow=!0,this.suppressMouseDown=!1,this._resizableNode=this._register(new C4),this._contentPosition=null,this._isResizing=!1,this._resizableNode.domNode.style.position="absolute",this._resizableNode.minSize=Dt.lift(t),this._resizableNode.layout(t.height,t.width),this._resizableNode.enableSashes(!0,!0,!0,!0),this._register(this._resizableNode.onDidResize(i=>{this._resize(new Dt(i.dimension.width,i.dimension.height)),i.done&&(this._isResizing=!1)})),this._register(this._resizableNode.onDidWillResize(()=>{this._isResizing=!0}))}get isResizing(){return this._isResizing}getDomNode(){return this._resizableNode.domNode}getPosition(){return this._contentPosition}get position(){var e;return!((e=this._contentPosition)===null||e===void 0)&&e.position?W.lift(this._contentPosition.position):void 0}_availableVerticalSpaceAbove(e){const t=this._editor.getDomNode(),i=this._editor.getScrolledVisiblePosition(e);return!t||!i?void 0:qi(t).top+i.top-Wke}_availableVerticalSpaceBelow(e){const t=this._editor.getDomNode(),i=this._editor.getScrolledVisiblePosition(e);if(!t||!i)return;const n=qi(t),o=Eh(t.ownerDocument.body),r=n.top+i.top+i.height;return o.height-r-Hke}_findPositionPreference(e,t){var i,n;const o=Math.min((i=this._availableVerticalSpaceBelow(t))!==null&&i!==void 0?i:1/0,e),r=Math.min((n=this._availableVerticalSpaceAbove(t))!==null&&n!==void 0?n:1/0,e),a=Math.min(Math.max(r,o),e),l=Math.min(e,a);let d;return this._editor.getOption(60).above?d=l<=r?1:2:d=l<=o?2:1,d===1?this._resizableNode.enableSashes(!0,!0,!1,!1):this._resizableNode.enableSashes(!1,!0,!0,!1),d}_resize(e){this._resizableNode.layout(e.height,e.width)}}var zke=function(s,e,t,i){var n=arguments.length,o=n<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,r;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(s,e,t,i);else for(var a=s.length-1;a>=0;a--)(r=s[a])&&(o=(n<3?r(o):n>3?r(e,t,o):r(e,t))||o);return n>3&&o&&Object.defineProperty(e,t,o),o},ny=function(s,e){return function(t,i){e(t,i,s)}},Nl;const U7=30,Uke=6;let H_=Nl=class extends Vke{get isColorPickerVisible(){var e;return!!(!((e=this._visibleData)===null||e===void 0)&&e.colorPicker)}get isVisibleFromKeyboard(){var e;return((e=this._visibleData)===null||e===void 0?void 0:e.source)===1}get isVisible(){var e;return(e=this._hoverVisibleKey.get())!==null&&e!==void 0?e:!1}get isFocused(){var e;return(e=this._hoverFocusedKey.get())!==null&&e!==void 0?e:!1}constructor(e,t,i,n,o){const r=e.getOption(67)+8,a=150,l=new Dt(a,r);super(e,l),this._configurationService=i,this._accessibilityService=n,this._keybindingService=o,this._hover=this._register(new gO),this._minimumSize=l,this._hoverVisibleKey=T.hoverVisible.bindTo(t),this._hoverFocusedKey=T.hoverFocused.bindTo(t),Q(this._resizableNode.domNode,this._hover.containerDomNode),this._resizableNode.domNode.style.zIndex="50",this._register(this._editor.onDidLayoutChange(()=>{this.isVisible&&this._updateMaxDimensions()})),this._register(this._editor.onDidChangeConfiguration(c=>{c.hasChanged(50)&&this._updateFont()}));const d=this._register(ba(this._resizableNode.domNode));this._register(d.onDidFocus(()=>{this._hoverFocusedKey.set(!0)})),this._register(d.onDidBlur(()=>{this._hoverFocusedKey.set(!1)})),this._setHoverData(void 0),this._editor.addContentWidget(this)}dispose(){var e;super.dispose(),(e=this._visibleData)===null||e===void 0||e.disposables.dispose(),this._editor.removeContentWidget(this)}getId(){return Nl.ID}static _applyDimensions(e,t,i){const n=typeof t=="number"?`${t}px`:t,o=typeof i=="number"?`${i}px`:i;e.style.width=n,e.style.height=o}_setContentsDomNodeDimensions(e,t){const i=this._hover.contentsDomNode;return Nl._applyDimensions(i,e,t)}_setContainerDomNodeDimensions(e,t){const i=this._hover.containerDomNode;return Nl._applyDimensions(i,e,t)}_setHoverWidgetDimensions(e,t){this._setContentsDomNodeDimensions(e,t),this._setContainerDomNodeDimensions(e,t),this._layoutContentWidget()}static _applyMaxDimensions(e,t,i){const n=typeof t=="number"?`${t}px`:t,o=typeof i=="number"?`${i}px`:i;e.style.maxWidth=n,e.style.maxHeight=o}_setHoverWidgetMaxDimensions(e,t){Nl._applyMaxDimensions(this._hover.contentsDomNode,e,t),Nl._applyMaxDimensions(this._hover.containerDomNode,e,t),this._hover.containerDomNode.style.setProperty("--vscode-hover-maxWidth",typeof e=="number"?`${e}px`:e),this._layoutContentWidget()}_setAdjustedHoverWidgetDimensions(e){this._setHoverWidgetMaxDimensions("none","none");const t=e.width,i=e.height;this._setHoverWidgetDimensions(t,i)}_updateResizableNodeMaxDimensions(){var e,t;const i=(e=this._findMaximumRenderingWidth())!==null&&e!==void 0?e:1/0,n=(t=this._findMaximumRenderingHeight())!==null&&t!==void 0?t:1/0;this._resizableNode.maxSize=new Dt(i,n),this._setHoverWidgetMaxDimensions(i,n)}_resize(e){var t,i;Nl._lastDimensions=new Dt(e.width,e.height),this._setAdjustedHoverWidgetDimensions(e),this._resizableNode.layout(e.height,e.width),this._updateResizableNodeMaxDimensions(),this._hover.scrollbar.scanDomNode(),this._editor.layoutContentWidget(this),(i=(t=this._visibleData)===null||t===void 0?void 0:t.colorPicker)===null||i===void 0||i.layout()}_findAvailableSpaceVertically(){var e;const t=(e=this._visibleData)===null||e===void 0?void 0:e.showAtPosition;if(t)return this._positionPreference===1?this._availableVerticalSpaceAbove(t):this._availableVerticalSpaceBelow(t)}_findMaximumRenderingHeight(){const e=this._findAvailableSpaceVertically();if(!e)return;let t=Uke;return Array.from(this._hover.contentsDomNode.children).forEach(i=>{t+=i.clientHeight}),Math.min(e,t)}_isHoverTextOverflowing(){this._hover.containerDomNode.style.setProperty("--vscode-hover-whiteSpace","nowrap"),this._hover.containerDomNode.style.setProperty("--vscode-hover-sourceWhiteSpace","nowrap");const e=Array.from(this._hover.contentsDomNode.children).some(t=>t.scrollWidth>t.clientWidth);return this._hover.containerDomNode.style.removeProperty("--vscode-hover-whiteSpace"),this._hover.containerDomNode.style.removeProperty("--vscode-hover-sourceWhiteSpace"),e}_findMaximumRenderingWidth(){if(!this._editor||!this._editor.hasModel())return;const e=this._isHoverTextOverflowing(),t=typeof this._contentWidth>"u"?0:this._contentWidth-2;return e||this._hover.containerDomNode.clientWidth"u"||typeof this._visibleData.initialMousePosY>"u")return this._visibleData.initialMousePosX=e,this._visibleData.initialMousePosY=t,!1;const i=qi(this.getDomNode());typeof this._visibleData.closestMouseDistance>"u"&&(this._visibleData.closestMouseDistance=$7(this._visibleData.initialMousePosX,this._visibleData.initialMousePosY,i.left,i.top,i.width,i.height));const n=$7(e,t,i.left,i.top,i.width,i.height);return n>this._visibleData.closestMouseDistance+4?!1:(this._visibleData.closestMouseDistance=Math.min(this._visibleData.closestMouseDistance,n),!0)}_setHoverData(e){var t;(t=this._visibleData)===null||t===void 0||t.disposables.dispose(),this._visibleData=e,this._hoverVisibleKey.set(!!e),this._hover.containerDomNode.classList.toggle("hidden",!e)}_updateFont(){const{fontSize:e,lineHeight:t}=this._editor.getOption(50),i=this._hover.contentsDomNode;i.style.fontSize=`${e}px`,i.style.lineHeight=`${t/e}`,Array.prototype.slice.call(this._hover.contentsDomNode.getElementsByClassName("code")).forEach(o=>this._editor.applyFontInfo(o))}_updateContent(e){const t=this._hover.contentsDomNode;t.style.paddingBottom="",t.textContent="",t.appendChild(e)}_layoutContentWidget(){this._editor.layoutContentWidget(this),this._hover.onContentsChanged()}_updateMaxDimensions(){const e=Math.max(this._editor.getLayoutInfo().height/4,250,Nl._lastDimensions.height),t=Math.max(this._editor.getLayoutInfo().width*.66,500,Nl._lastDimensions.width);this._setHoverWidgetMaxDimensions(t,e)}_render(e,t){this._setHoverData(t),this._updateFont(),this._updateContent(e),this._updateMaxDimensions(),this.onContentsChanged(),this._editor.render()}getPosition(){var e;return this._visibleData?{position:this._visibleData.showAtPosition,secondaryPosition:this._visibleData.showAtSecondaryPosition,positionAffinity:this._visibleData.isBeforeContent?3:void 0,preference:[(e=this._positionPreference)!==null&&e!==void 0?e:1]}:null}showAt(e,t){var i,n,o,r;if(!this._editor||!this._editor.hasModel())return;this._render(e,t);const a=uc(this._hover.containerDomNode),l=t.showAtPosition;this._positionPreference=(i=this._findPositionPreference(a,l))!==null&&i!==void 0?i:1,this.onContentsChanged(),t.stoleFocus&&this._hover.containerDomNode.focus(),(n=t.colorPicker)===null||n===void 0||n.layout();const c=this._hover.containerDomNode.ownerDocument.activeElement===this._hover.containerDomNode&&q$(this._configurationService.getValue("accessibility.verbosity.hover")===!0&&this._accessibilityService.isScreenReaderOptimized(),(r=(o=this._keybindingService.lookupKeybinding("editor.action.accessibleView"))===null||o===void 0?void 0:o.getAriaLabel())!==null&&r!==void 0?r:"");c&&(this._hover.contentsDomNode.ariaLabel=this._hover.contentsDomNode.textContent+", "+c)}hide(){if(!this._visibleData)return;const e=this._visibleData.stoleFocus||this._hoverFocusedKey.get();this._setHoverData(void 0),this._resizableNode.maxSize=new Dt(1/0,1/0),this._resizableNode.clearSashHoverState(),this._hoverFocusedKey.set(!1),this._editor.layoutContentWidget(this),e&&this._editor.focus()}_removeConstraintsRenderNormally(){const e=this._editor.getLayoutInfo();this._resizableNode.layout(e.height,e.width),this._setHoverWidgetDimensions("auto","auto")}setMinimumDimensions(e){this._minimumSize=new Dt(Math.max(this._minimumSize.width,e.width),Math.max(this._minimumSize.height,e.height)),this._updateMinimumWidth()}_updateMinimumWidth(){const e=typeof this._contentWidth>"u"?this._minimumSize.width:Math.min(this._contentWidth,this._minimumSize.width);this._resizableNode.minSize=new Dt(e,this._minimumSize.height)}onContentsChanged(){var e;this._removeConstraintsRenderNormally();const t=this._hover.containerDomNode;let i=uc(t),n=wo(t);if(this._resizableNode.layout(i,n),this._setHoverWidgetDimensions(n,i),i=uc(t),n=wo(t),this._contentWidth=n,this._updateMinimumWidth(),this._resizableNode.layout(i,n),!((e=this._visibleData)===null||e===void 0)&&e.showAtPosition){const o=uc(this._hover.containerDomNode);this._positionPreference=this._findPositionPreference(o,this._visibleData.showAtPosition)}this._layoutContentWidget()}focus(){this._hover.containerDomNode.focus()}scrollUp(){const e=this._hover.scrollbar.getScrollPosition().scrollTop,t=this._editor.getOption(50);this._hover.scrollbar.setScrollPosition({scrollTop:e-t.lineHeight})}scrollDown(){const e=this._hover.scrollbar.getScrollPosition().scrollTop,t=this._editor.getOption(50);this._hover.scrollbar.setScrollPosition({scrollTop:e+t.lineHeight})}scrollLeft(){const e=this._hover.scrollbar.getScrollPosition().scrollLeft;this._hover.scrollbar.setScrollPosition({scrollLeft:e-U7})}scrollRight(){const e=this._hover.scrollbar.getScrollPosition().scrollLeft;this._hover.scrollbar.setScrollPosition({scrollLeft:e+U7})}pageUp(){const e=this._hover.scrollbar.getScrollPosition().scrollTop,t=this._hover.scrollbar.getScrollDimensions().height;this._hover.scrollbar.setScrollPosition({scrollTop:e-t})}pageDown(){const e=this._hover.scrollbar.getScrollPosition().scrollTop,t=this._hover.scrollbar.getScrollDimensions().height;this._hover.scrollbar.setScrollPosition({scrollTop:e+t})}goToTop(){this._hover.scrollbar.setScrollPosition({scrollTop:0})}goToBottom(){this._hover.scrollbar.setScrollPosition({scrollTop:this._hover.scrollbar.getScrollDimensions().scrollHeight})}};H_.ID="editor.contrib.resizableContentHoverWidget";H_._lastDimensions=new Dt(0,0);H_=Nl=zke([ny(1,Be),ny(2,rt),ny(3,gr),ny(4,At)],H_);function $7(s,e,t,i,n,o){const r=t+n/2,a=i+o/2,l=Math.max(Math.abs(s-r)-n/2,0),d=Math.max(Math.abs(e-a)-o/2,0);return Math.sqrt(l*l+d*d)}let $ke=class{constructor(e,t,i){this.value=e,this.isComplete=t,this.hasLoadingMessage=i}};class Aq extends H{constructor(e,t){super(),this._editor=e,this._computer=t,this._onResult=this._register(new B),this.onResult=this._onResult.event,this._firstWaitScheduler=this._register(new Wt(()=>this._triggerAsyncComputation(),0)),this._secondWaitScheduler=this._register(new Wt(()=>this._triggerSyncComputation(),0)),this._loadingMessageScheduler=this._register(new Wt(()=>this._triggerLoadingMessage(),0)),this._state=0,this._asyncIterable=null,this._asyncIterableDone=!1,this._result=[]}dispose(){this._asyncIterable&&(this._asyncIterable.cancel(),this._asyncIterable=null),super.dispose()}get _hoverTime(){return this._editor.getOption(60).delay}get _firstWaitTime(){return this._hoverTime/2}get _secondWaitTime(){return this._hoverTime-this._firstWaitTime}get _loadingMessageTime(){return 3*this._hoverTime}_setState(e,t=!0){this._state=e,t&&this._fireResult()}_triggerAsyncComputation(){this._setState(2),this._secondWaitScheduler.schedule(this._secondWaitTime),this._computer.computeAsync?(this._asyncIterableDone=!1,this._asyncIterable=iae(e=>this._computer.computeAsync(e)),(async()=>{try{for await(const e of this._asyncIterable)e&&(this._result.push(e),this._fireResult());this._asyncIterableDone=!0,(this._state===3||this._state===4)&&this._setState(0)}catch(e){Xe(e)}})()):this._asyncIterableDone=!0}_triggerSyncComputation(){this._computer.computeSync&&(this._result=this._result.concat(this._computer.computeSync())),this._setState(this._asyncIterableDone?0:3)}_triggerLoadingMessage(){this._state===3&&this._setState(4)}_fireResult(){if(this._state===1||this._state===2)return;const e=this._state===0,t=this._state===4;this._onResult.fire(new $ke(this._result.slice(0),e,t))}start(e){if(e===0)this._state===0&&(this._setState(1),this._firstWaitScheduler.schedule(this._firstWaitTime),this._loadingMessageScheduler.schedule(this._loadingMessageTime));else switch(this._state){case 0:this._triggerAsyncComputation(),this._secondWaitScheduler.cancel(),this._triggerSyncComputation();break;case 2:this._secondWaitScheduler.cancel(),this._triggerSyncComputation();break}}cancel(){this._firstWaitScheduler.cancel(),this._secondWaitScheduler.cancel(),this._loadingMessageScheduler.cancel(),this._asyncIterable&&(this._asyncIterable.cancel(),this._asyncIterable=null),this._result=[],this._setState(0,!1)}}class lT{constructor(e,t,i,n){this.priority=e,this.range=t,this.initialMousePosX=i,this.initialMousePosY=n,this.type=1}equals(e){return e.type===1&&this.range.equalsRange(e.range)}canAdoptVisibleHover(e,t){return e.type===1&&t.lineNumber===this.range.startLineNumber}}class hf{constructor(e,t,i,n,o,r){this.priority=e,this.owner=t,this.range=i,this.initialMousePosX=n,this.initialMousePosY=o,this.supportsMarkerHover=r,this.type=2}equals(e){return e.type===2&&this.owner===e.owner}canAdoptVisibleHover(e,t){return e.type===2&&this.owner===e.owner}}const ag=new class{constructor(){this._participants=[]}register(e){this._participants.push(e)}getAll(){return this._participants}};class jke{constructor(e,t,i){this.provider=e,this.hover=t,this.ordinal=i}}async function Kke(s,e,t,i,n){const o=await Promise.resolve(s.provideHover(t,i,n)).catch(Ai);if(!(!o||!Gke(o)))return new jke(s,o,e)}function w4(s,e,t,i){const o=s.ordered(e).map((r,a)=>Kke(r,a,e,t,i));return Xi.fromPromises(o).coalesce()}function qke(s,e,t,i){return w4(s,e,t,i).map(n=>n.hover).toPromise()}Ad("_executeHoverProvider",(s,e,t)=>{const i=s.get(Ce);return qke(i.hoverProvider,e,t,dt.None)});function Gke(s){const e=typeof s.range<"u",t=typeof s.contents<"u"&&s.contents&&s.contents.length>0;return e&&t}var Zke=function(s,e,t,i){var n=arguments.length,o=n<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,r;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(s,e,t,i);else for(var a=s.length-1;a>=0;a--)(r=s[a])&&(o=(n<3?r(o):n>3?r(e,t,o):r(e,t))||o);return n>3&&o&&Object.defineProperty(e,t,o),o},Rp=function(s,e){return function(t,i){e(t,i,s)}};const Cm=he,Xke=xi("hover-increase-verbosity",oe.add,p("increaseHoverVerbosity","Icon for increaseing hover verbosity.")),Yke=xi("hover-decrease-verbosity",oe.remove,p("decreaseHoverVerbosity","Icon for decreasing hover verbosity."));class Ka{constructor(e,t,i,n,o,r=void 0){this.owner=e,this.range=t,this.contents=i,this.isBeforeContent=n,this.ordinal=o,this.source=r}isValidForHoverAnchor(e){return e.type===1&&this.range.startColumn<=e.range.startColumn&&this.range.endColumn>=e.range.endColumn}}class Mq{constructor(e,t,i){this.hover=e,this.hoverProvider=t,this.hoverPosition=i}supportsVerbosityAction(e){var t,i;switch(e){case ja.Increase:return(t=this.hover.canIncreaseVerbosity)!==null&&t!==void 0?t:!1;case ja.Decrease:return(i=this.hover.canDecreaseVerbosity)!==null&&i!==void 0?i:!1}}}let RC=class{constructor(e,t,i,n,o,r,a){this._editor=e,this._languageService=t,this._openerService=i,this._configurationService=n,this._languageFeaturesService=o,this._keybindingService=r,this._hoverService=a,this.hoverOrdinal=3}createLoadingMessage(e){return new Ka(this,e.range,[new ss().appendText(p("modesContentHover.loading","Loading..."))],!1,2e3)}computeSync(e,t){if(!this._editor.hasModel()||e.type!==1)return[];const i=this._editor.getModel(),n=e.range.startLineNumber,o=i.getLineMaxColumn(n),r=[];let a=1e3;const l=i.getLineLength(n),d=i.getLanguageIdAtPosition(e.range.startLineNumber,e.range.startColumn),c=this._editor.getOption(117),u=this._configurationService.getValue("editor.maxTokenizationLineLength",{overrideIdentifier:d});let h=!1;c>=0&&l>c&&e.range.startColumn>=c&&(h=!0,r.push(new Ka(this,e.range,[{value:p("stopped rendering","Rendering paused for long line for performance reasons. This can be configured via `editor.stopRenderingLineAfter`.")}],!1,a++))),!h&&typeof u=="number"&&l>=u&&r.push(new Ka(this,e.range,[{value:p("too many characters","Tokenization is skipped for long lines for performance reasons. This can be configured via `editor.maxTokenizationLineLength`.")}],!1,a++));let g=!1;for(const f of t){const m=f.range.startLineNumber===n?f.range.startColumn:1,_=f.range.endLineNumber===n?f.range.endColumn:o,v=f.options.hoverMessage;if(!v||L_(v))continue;f.options.beforeContentClassName&&(g=!0);const b=new x(e.range.startLineNumber,m,e.range.startLineNumber,_);r.push(new Ka(this,b,OP(v),g,a++))}return r}computeAsync(e,t,i){if(!this._editor.hasModel()||e.type!==1)return Xi.EMPTY;const n=this._editor.getModel(),o=this._languageFeaturesService.hoverProvider;return o.has(n)?this._getMarkdownHovers(o,n,e,i):Xi.EMPTY}_getMarkdownHovers(e,t,i,n){const o=i.range.getStartPosition();return w4(e,t,o,n).filter(l=>!L_(l.hover.contents)).map(l=>{const d=l.hover.range?x.lift(l.hover.range):i.range,c=new Mq(l.hover,l.provider,o);return new Ka(this,d,l.hover.contents,!1,l.ordinal,c)})}renderHoverParts(e,t){return this._renderedHoverParts=new Qke(t,e.fragment,this._editor,this._languageService,this._openerService,this._keybindingService,this._hoverService,this._configurationService,e.onContentsChanged),this._renderedHoverParts}updateFocusedMarkdownHoverPartVerbosityLevel(e){var t;(t=this._renderedHoverParts)===null||t===void 0||t.updateFocusedHoverPartVerbosityLevel(e)}};RC=Zke([Rp(1,vi),Rp(2,Bo),Rp(3,rt),Rp(4,Ce),Rp(5,At),Rp(6,Md)],RC);class Qke extends H{constructor(e,t,i,n,o,r,a,l,d){super(),this._editor=i,this._languageService=n,this._openerService=o,this._keybindingService=r,this._hoverService=a,this._configurationService=l,this._onFinishedRendering=d,this._hoverFocusInfo={hoverPartIndex:-1,focusRemains:!1},this._renderedHoverParts=this._renderHoverParts(e,t,this._onFinishedRendering),this._register(Ie(()=>{this._renderedHoverParts.forEach(c=>{c.disposables.dispose()})}))}_renderHoverParts(e,t,i){return e.sort(ao(n=>n.ordinal,ua)),e.map((n,o)=>{const r=this._renderHoverPart(o,n.contents,n.source,i);return t.appendChild(r.renderedMarkdown),r})}_renderHoverPart(e,t,i,n){const{renderedMarkdown:o,disposables:r}=this._renderMarkdownContent(t,n);if(!i)return{renderedMarkdown:o,disposables:r};const a=i.supportsVerbosityAction(ja.Increase),l=i.supportsVerbosityAction(ja.Decrease);if(!a&&!l)return{renderedMarkdown:o,disposables:r,hoverSource:i};const d=Cm("div.verbosity-actions");o.prepend(d),r.add(this._renderHoverExpansionAction(d,ja.Increase,a)),r.add(this._renderHoverExpansionAction(d,ja.Decrease,l));const c=r.add(ba(o));return r.add(c.onDidFocus(()=>{this._hoverFocusInfo={hoverPartIndex:e,focusRemains:!0}})),r.add(c.onDidBlur(()=>{var u;if(!((u=this._hoverFocusInfo)===null||u===void 0)&&u.focusRemains){this._hoverFocusInfo.focusRemains=!1;return}})),{renderedMarkdown:o,disposables:r,hoverSource:i}}_renderMarkdownContent(e,t){const i=Cm("div.hover-row");i.tabIndex=0;const n=Cm("div.hover-row-contents");i.appendChild(n);const o=new Y;return o.add(Rq(this._editor,n,e,this._languageService,this._openerService,t)),{renderedMarkdown:i,disposables:o}}_renderHoverExpansionAction(e,t,i){const n=new Y,o=t===ja.Increase,r=Q(e,Cm(Pe.asCSSSelector(o?Xke:Yke)));r.tabIndex=0;const a=new S_("mouse",!1,{target:e,position:{hoverPosition:0}},this._configurationService,this._hoverService);if(o){const d=this._keybindingService.lookupKeybinding(_4);n.add(this._hoverService.setupUpdatableHover(a,r,d?p("increaseVerbosityWithKb","Increase Verbosity ({0})",d.getLabel()):p("increaseVerbosity","Increase Verbosity")))}else{const d=this._keybindingService.lookupKeybinding(v4);n.add(this._hoverService.setupUpdatableHover(a,r,d?p("decreaseVerbosityWithKb","Decrease Verbosity ({0})",d.getLabel()):p("decreaseVerbosity","Decrease Verbosity")))}if(!i)return r.classList.add("disabled"),n;r.classList.add("enabled");const l=()=>this.updateFocusedHoverPartVerbosityLevel(t);return n.add(new G$(r,l)),n.add(new Z$(r,l,[3,10])),n}async updateFocusedHoverPartVerbosityLevel(e){var t;const i=this._editor.getModel();if(!i)return;const n=this._hoverFocusInfo.hoverPartIndex,o=this._getRenderedHoverPartAtIndex(n);if(!o||!(!((t=o.hoverSource)===null||t===void 0)&&t.supportsVerbosityAction(e)))return;const r=o.hoverSource.hoverPosition,a=o.hoverSource.hoverProvider,l=o.hoverSource.hover,d={verbosityRequest:{action:e,previousHover:l}};let c;try{c=await Promise.resolve(a.provideHover(i,r,dt.None,d))}catch(g){Ai(g)}if(!c)return;const u=new Mq(c,a,r),h=this._renderHoverPart(n,c.contents,u,this._onFinishedRendering);this._replaceRenderedHoverPartAtIndex(n,h),this._focusOnHoverPartWithIndex(n),this._onFinishedRendering()}_replaceRenderedHoverPartAtIndex(e,t){if(e>=this._renderHoverParts.length||e<0)return;const i=this._renderedHoverParts[e];i.renderedMarkdown.replaceWith(t.renderedMarkdown),i.disposables.dispose(),this._renderedHoverParts[e]=t}_focusOnHoverPartWithIndex(e){this._renderedHoverParts[e].renderedMarkdown.focus(),this._hoverFocusInfo.focusRemains=!0}_getRenderedHoverPartAtIndex(e){return this._renderedHoverParts[e]}}function Jke(s,e,t,i,n){e.sort(ao(r=>r.ordinal,ua));const o=new Y;for(const r of e)o.add(Rq(t,s.fragment,r.contents,i,n,s.onContentsChanged));return o}function Rq(s,e,t,i,n,o){const r=new Y;for(const a of t){if(L_(a))continue;const l=Cm("div.markdown-hover"),d=Q(l,Cm("div.hover-contents")),c=r.add(new yd({editor:s},i,n));r.add(c.onDidRenderAsync(()=>{d.className="hover-contents code-hover-contents",o()}));const u=r.add(c.render(a));d.appendChild(u.element),e.appendChild(l)}return r}function KM(s,e){return!!s[e]}class dT{constructor(e,t){this.target=e.target,this.isLeftClick=e.event.leftButton,this.isMiddleClick=e.event.middleButton,this.isRightClick=e.event.rightButton,this.hasTriggerModifier=KM(e.event,t.triggerModifier),this.hasSideBySideModifier=KM(e.event,t.triggerSideBySideModifier),this.isNoneOrSingleMouseDown=e.event.detail<=1}}class j7{constructor(e,t){this.keyCodeIsTriggerKey=e.keyCode===t.triggerKey,this.keyCodeIsSideBySideKey=e.keyCode===t.triggerSideBySideKey,this.hasTriggerModifier=KM(e,t.triggerModifier)}}class sy{constructor(e,t,i,n){this.triggerKey=e,this.triggerModifier=t,this.triggerSideBySideKey=i,this.triggerSideBySideModifier=n}equals(e){return this.triggerKey===e.triggerKey&&this.triggerModifier===e.triggerModifier&&this.triggerSideBySideKey===e.triggerSideBySideKey&&this.triggerSideBySideModifier===e.triggerSideBySideModifier}}function K7(s){return s==="altKey"?lt?new sy(57,"metaKey",6,"altKey"):new sy(5,"ctrlKey",6,"altKey"):lt?new sy(6,"altKey",57,"metaKey"):new sy(6,"altKey",5,"ctrlKey")}class vk extends H{constructor(e,t){var i;super(),this._onMouseMoveOrRelevantKeyDown=this._register(new B),this.onMouseMoveOrRelevantKeyDown=this._onMouseMoveOrRelevantKeyDown.event,this._onExecute=this._register(new B),this.onExecute=this._onExecute.event,this._onCancel=this._register(new B),this.onCancel=this._onCancel.event,this._editor=e,this._extractLineNumberFromMouseEvent=(i=t==null?void 0:t.extractLineNumberFromMouseEvent)!==null&&i!==void 0?i:n=>n.target.position?n.target.position.lineNumber:0,this._opts=K7(this._editor.getOption(78)),this._lastMouseMoveEvent=null,this._hasTriggerKeyOnMouseDown=!1,this._lineNumberOnMouseDown=0,this._register(this._editor.onDidChangeConfiguration(n=>{if(n.hasChanged(78)){const o=K7(this._editor.getOption(78));if(this._opts.equals(o))return;this._opts=o,this._lastMouseMoveEvent=null,this._hasTriggerKeyOnMouseDown=!1,this._lineNumberOnMouseDown=0,this._onCancel.fire()}})),this._register(this._editor.onMouseMove(n=>this._onEditorMouseMove(new dT(n,this._opts)))),this._register(this._editor.onMouseDown(n=>this._onEditorMouseDown(new dT(n,this._opts)))),this._register(this._editor.onMouseUp(n=>this._onEditorMouseUp(new dT(n,this._opts)))),this._register(this._editor.onKeyDown(n=>this._onEditorKeyDown(new j7(n,this._opts)))),this._register(this._editor.onKeyUp(n=>this._onEditorKeyUp(new j7(n,this._opts)))),this._register(this._editor.onMouseDrag(()=>this._resetHandler())),this._register(this._editor.onDidChangeCursorSelection(n=>this._onDidChangeCursorSelection(n))),this._register(this._editor.onDidChangeModel(n=>this._resetHandler())),this._register(this._editor.onDidChangeModelContent(()=>this._resetHandler())),this._register(this._editor.onDidScrollChange(n=>{(n.scrollTopChanged||n.scrollLeftChanged)&&this._resetHandler()}))}_onDidChangeCursorSelection(e){e.selection&&e.selection.startColumn!==e.selection.endColumn&&this._resetHandler()}_onEditorMouseMove(e){this._lastMouseMoveEvent=e,this._onMouseMoveOrRelevantKeyDown.fire([e,null])}_onEditorMouseDown(e){this._hasTriggerKeyOnMouseDown=e.hasTriggerModifier,this._lineNumberOnMouseDown=this._extractLineNumberFromMouseEvent(e)}_onEditorMouseUp(e){const t=this._extractLineNumberFromMouseEvent(e);this._hasTriggerKeyOnMouseDown&&this._lineNumberOnMouseDown&&this._lineNumberOnMouseDown===t&&this._onExecute.fire(e)}_onEditorKeyDown(e){this._lastMouseMoveEvent&&(e.keyCodeIsTriggerKey||e.keyCodeIsSideBySideKey&&e.hasTriggerModifier)?this._onMouseMoveOrRelevantKeyDown.fire([this._lastMouseMoveEvent,e]):e.hasTriggerModifier&&this._onCancel.fire()}_onEditorKeyUp(e){e.keyCodeIsTriggerKey&&this._onCancel.fire()}_resetHandler(){this._lastMouseMoveEvent=null,this._hasTriggerKeyOnMouseDown=!1,this._onCancel.fire()}}class Pq{constructor(e,t){this.range=e,this.direction=t}}class y4{constructor(e,t,i){this.hint=e,this.anchor=t,this.provider=i,this._isResolved=!1}with(e){const t=new y4(this.hint,e.anchor,this.provider);return t._isResolved=this._isResolved,t._currentResolve=this._currentResolve,t}async resolve(e){if(typeof this.provider.resolveInlayHint=="function"){if(this._currentResolve)return await this._currentResolve,e.isCancellationRequested?void 0:this.resolve(e);this._isResolved||(this._currentResolve=this._doResolve(e).finally(()=>this._currentResolve=void 0)),await this._currentResolve}}async _doResolve(e){var t,i,n;try{const o=await Promise.resolve(this.provider.resolveInlayHint(this.hint,e));this.hint.tooltip=(t=o==null?void 0:o.tooltip)!==null&&t!==void 0?t:this.hint.tooltip,this.hint.label=(i=o==null?void 0:o.label)!==null&&i!==void 0?i:this.hint.label,this.hint.textEdits=(n=o==null?void 0:o.textEdits)!==null&&n!==void 0?n:this.hint.textEdits,this._isResolved=!0}catch(o){Ai(o),this._isResolved=!1}}}class gf{static async create(e,t,i,n){const o=[],r=e.ordered(t).reverse().map(a=>i.map(async l=>{try{const d=await a.provideInlayHints(t,l,n);(d!=null&&d.hints.length||a.onDidChangeInlayHints)&&o.push([d??gf._emptyInlayHintList,a])}catch(d){Ai(d)}}));if(await Promise.all(r.flat()),n.isCancellationRequested||t.isDisposed())throw new sl;return new gf(i,o,t)}constructor(e,t,i){this._disposables=new Y,this.ranges=e,this.provider=new Set;const n=[];for(const[o,r]of t){this._disposables.add(o),this.provider.add(r);for(const a of o.hints){const l=i.validatePosition(a.position);let d="before";const c=gf._getRangeAtPosition(i,l);let u;c.getStartPosition().isBefore(l)?(u=x.fromPositions(c.getStartPosition(),l),d="after"):(u=x.fromPositions(l,c.getEndPosition()),d="before"),n.push(new y4(a,new Pq(u,d),r))}}this.items=n.sort((o,r)=>W.compare(o.hint.position,r.hint.position))}dispose(){this._disposables.dispose()}static _getRangeAtPosition(e,t){const i=t.lineNumber,n=e.getWordAtPosition(t);if(n)return new x(i,n.startColumn,i,n.endColumn);e.tokenization.tokenizeIfCheap(i);const o=e.tokenization.getLineTokens(i),r=t.column-1,a=o.findTokenIndexAtOffset(r);let l=o.getStartOffset(a),d=o.getEndOffset(a);return d-l===1&&(l===r&&a>1?(l=o.getStartOffset(a-1),d=o.getEndOffset(a-1)):d===r&&a=0;a--)(r=s[a])&&(o=(n<3?r(o):n>3?r(e,t,o):r(e,t))||o);return n>3&&o&&Object.defineProperty(e,t,o),o},Ud=function(s,e){return function(t,i){e(t,i,s)}};let Uh=class extends y_{constructor(e,t,i,n,o,r,a,l,d,c,u,h,g){super(e,{...n.getRawOptions(),overflowWidgetsDomNode:n.getOverflowWidgetsDomNode()},i,o,r,a,l,d,c,u,h,g),this._parentEditor=n,this._overwriteOptions=t,super.updateOptions(this._overwriteOptions),this._register(n.onDidChangeConfiguration(f=>this._onParentConfigurationChanged(f)))}getParentEditor(){return this._parentEditor}_onParentConfigurationChanged(e){super.updateOptions(this._parentEditor.getRawOptions()),super.updateOptions(this._overwriteOptions)}updateOptions(e){UL(this._overwriteOptions,e,!0),super.updateOptions(this._overwriteOptions)}};Uh=tEe([Ud(4,Ne),Ud(5,xt),Ud(6,gi),Ud(7,Be),Ud(8,_n),Ud(9,en),Ud(10,gr),Ud(11,Yt),Ud(12,Ce)],Uh);const q7=new $(new bt(0,122,204)),iEe={showArrow:!0,showFrame:!0,className:"",frameColor:q7,arrowColor:q7,keepEditorSelection:!1},nEe="vs.editor.contrib.zoneWidget";class sEe{constructor(e,t,i,n,o,r,a,l){this.id="",this.domNode=e,this.afterLineNumber=t,this.afterColumn=i,this.heightInLines=n,this.showInHiddenAreas=a,this.ordinal=l,this._onDomNodeTop=o,this._onComputedHeight=r}onDomNodeTop(e){this._onDomNodeTop(e)}onComputedHeight(e){this._onComputedHeight(e)}}class oEe{constructor(e,t){this._id=e,this._domNode=t}getId(){return this._id}getDomNode(){return this._domNode}getPosition(){return null}}class bk{constructor(e){this._editor=e,this._ruleName=bk._IdGenerator.nextId(),this._decorations=this._editor.createDecorationsCollection(),this._color=null,this._height=-1}dispose(){this.hide(),oA(this._ruleName)}set color(e){this._color!==e&&(this._color=e,this._updateStyle())}set height(e){this._height!==e&&(this._height=e,this._updateStyle())}_updateStyle(){oA(this._ruleName),$S(`.monaco-editor ${this._ruleName}`,`border-style: solid; border-color: transparent; border-bottom-color: ${this._color}; border-width: ${this._height}px; bottom: -${this._height}px !important; margin-left: -${this._height}px; `)}show(e){e.column===1&&(e={lineNumber:e.lineNumber,column:2}),this._decorations.set([{range:x.fromPositions(e),options:{description:"zone-widget-arrow",className:this._ruleName,stickiness:1}}])}hide(){this._decorations.clear()}}bk._IdGenerator=new bO(".arrow-decoration-");class rEe{constructor(e,t={}){this._arrow=null,this._overlayWidget=null,this._resizeSash=null,this._viewZone=null,this._disposables=new Y,this.container=null,this._isShowing=!1,this.editor=e,this._positionMarkerId=this.editor.createDecorationsCollection(),this.options=Jd(t),UL(this.options,iEe,!1),this.domNode=document.createElement("div"),this.options.isAccessible||(this.domNode.setAttribute("aria-hidden","true"),this.domNode.setAttribute("role","presentation")),this._disposables.add(this.editor.onDidLayoutChange(i=>{const n=this._getWidth(i);this.domNode.style.width=n+"px",this.domNode.style.left=this._getLeft(i)+"px",this._onWidth(n)}))}dispose(){this._overlayWidget&&(this.editor.removeOverlayWidget(this._overlayWidget),this._overlayWidget=null),this._viewZone&&this.editor.changeViewZones(e=>{this._viewZone&&e.removeZone(this._viewZone.id),this._viewZone=null}),this._positionMarkerId.clear(),this._disposables.dispose()}create(){this.domNode.classList.add("zone-widget"),this.options.className&&this.domNode.classList.add(this.options.className),this.container=document.createElement("div"),this.container.classList.add("zone-widget-container"),this.domNode.appendChild(this.container),this.options.showArrow&&(this._arrow=new bk(this.editor),this._disposables.add(this._arrow)),this._fillContainer(this.container),this._initSash(),this._applyStyles()}style(e){e.frameColor&&(this.options.frameColor=e.frameColor),e.arrowColor&&(this.options.arrowColor=e.arrowColor),this._applyStyles()}_applyStyles(){if(this.container&&this.options.frameColor){const e=this.options.frameColor.toString();this.container.style.borderTopColor=e,this.container.style.borderBottomColor=e}if(this._arrow&&this.options.arrowColor){const e=this.options.arrowColor.toString();this._arrow.color=e}}_getWidth(e){return e.width-e.minimap.minimapWidth-e.verticalScrollbarWidth}_getLeft(e){return e.minimap.minimapWidth>0&&e.minimap.minimapLeft===0?e.minimap.minimapWidth:0}_onViewZoneTop(e){this.domNode.style.top=e+"px"}_onViewZoneHeight(e){var t;if(this.domNode.style.height=`${e}px`,this.container){const i=e-this._decoratingElementsHeight();this.container.style.height=`${i}px`;const n=this.editor.getLayoutInfo();this._doLayout(i,this._getWidth(n))}(t=this._resizeSash)===null||t===void 0||t.layout()}get position(){const e=this._positionMarkerId.getRange(0);if(e)return e.getStartPosition()}show(e,t){const i=x.isIRange(e)?x.lift(e):x.fromPositions(e);this._isShowing=!0,this._showImpl(i,t),this._isShowing=!1,this._positionMarkerId.set([{range:i,options:Ye.EMPTY}])}hide(){var e;this._viewZone&&(this.editor.changeViewZones(t=>{this._viewZone&&t.removeZone(this._viewZone.id)}),this._viewZone=null),this._overlayWidget&&(this.editor.removeOverlayWidget(this._overlayWidget),this._overlayWidget=null),(e=this._arrow)===null||e===void 0||e.hide(),this._positionMarkerId.clear()}_decoratingElementsHeight(){const e=this.editor.getOption(67);let t=0;if(this.options.showArrow){const i=Math.round(e/3);t+=2*i}if(this.options.showFrame){const i=Math.round(e/9);t+=2*i}return t}_showImpl(e,t){const i=e.getStartPosition(),n=this.editor.getLayoutInfo(),o=this._getWidth(n);this.domNode.style.width=`${o}px`,this.domNode.style.left=this._getLeft(n)+"px";const r=document.createElement("div");r.style.overflow="hidden";const a=this.editor.getOption(67);if(!this.options.allowUnlimitedHeight){const h=Math.max(12,this.editor.getLayoutInfo().height/a*.8);t=Math.min(t,h)}let l=0,d=0;if(this._arrow&&this.options.showArrow&&(l=Math.round(a/3),this._arrow.height=l,this._arrow.show(i)),this.options.showFrame&&(d=Math.round(a/9)),this.editor.changeViewZones(h=>{this._viewZone&&h.removeZone(this._viewZone.id),this._overlayWidget&&(this.editor.removeOverlayWidget(this._overlayWidget),this._overlayWidget=null),this.domNode.style.top="-1000px",this._viewZone=new sEe(r,i.lineNumber,i.column,t,g=>this._onViewZoneTop(g),g=>this._onViewZoneHeight(g),this.options.showInHiddenAreas,this.options.ordinal),this._viewZone.id=h.addZone(this._viewZone),this._overlayWidget=new oEe(nEe+this._viewZone.id,this.domNode),this.editor.addOverlayWidget(this._overlayWidget)}),this.container&&this.options.showFrame){const h=this.options.frameWidth?this.options.frameWidth:d;this.container.style.borderTopWidth=h+"px",this.container.style.borderBottomWidth=h+"px"}const c=t*a-this._decoratingElementsHeight();this.container&&(this.container.style.top=l+"px",this.container.style.height=c+"px",this.container.style.overflow="hidden"),this._doLayout(c,o),this.options.keepEditorSelection||this.editor.setSelection(e);const u=this.editor.getModel();if(u){const h=u.validateRange(new x(e.startLineNumber,1,e.endLineNumber+1,1));this.revealRange(h,h.startLineNumber===u.getLineCount())}}revealRange(e,t){t?this.editor.revealLineNearTop(e.endLineNumber,0):this.editor.revealRange(e,0)}setCssClass(e,t){this.container&&(t&&this.container.classList.remove(t),this.container.classList.add(e))}_onWidth(e){}_doLayout(e,t){}_relayout(e){this._viewZone&&this._viewZone.heightInLines!==e&&this.editor.changeViewZones(t=>{this._viewZone&&(this._viewZone.heightInLines=e,t.layoutZone(this._viewZone.id))})}_initSash(){if(this._resizeSash)return;this._resizeSash=this._disposables.add(new is(this.domNode,this,{orientation:1})),this.options.isResizeable||(this._resizeSash.state=0);let e;this._disposables.add(this._resizeSash.onDidStart(t=>{this._viewZone&&(e={startY:t.startY,heightInLines:this._viewZone.heightInLines})})),this._disposables.add(this._resizeSash.onDidEnd(()=>{e=void 0})),this._disposables.add(this._resizeSash.onDidChange(t=>{if(e){const i=(t.currentY-e.startY)/this.editor.getOption(67),n=i<0?Math.ceil(i):Math.floor(i),o=e.heightInLines+n;o>5&&o<35&&this._relayout(o)}}))}getHorizontalSashLeft(){return 0}getHorizontalSashTop(){return(this.domNode.style.height===null?0:parseInt(this.domNode.style.height))-this._decoratingElementsHeight()/2}getHorizontalSashWidth(){const e=this.editor.getLayoutInfo();return e.width-e.minimap.minimapWidth}}var Fq=function(s,e,t,i){var n=arguments.length,o=n<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,r;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(s,e,t,i);else for(var a=s.length-1;a>=0;a--)(r=s[a])&&(o=(n<3?r(o):n>3?r(e,t,o):r(e,t))||o);return n>3&&o&&Object.defineProperty(e,t,o),o},Oq=function(s,e){return function(t,i){e(t,i,s)}};const Bq=ut("IPeekViewService");mt(Bq,class{constructor(){this._widgets=new Map}addExclusiveWidget(s,e){const t=this._widgets.get(s);t&&(t.listener.dispose(),t.widget.dispose());const i=()=>{const n=this._widgets.get(s);n&&n.widget===e&&(n.listener.dispose(),this._widgets.delete(s))};this._widgets.set(s,{widget:e,listener:e.onDidClose(i)})}},1);var po;(function(s){s.inPeekEditor=new ue("inReferenceSearchEditor",!0,p("inReferenceSearchEditor","Whether the current code editor is embedded inside peek")),s.notInPeekEditor=s.inPeekEditor.toNegated()})(po||(po={}));let PC=class{constructor(e,t){e instanceof Uh&&po.inPeekEditor.bindTo(t)}dispose(){}};PC.ID="editor.contrib.referenceController";PC=Fq([Oq(1,Be)],PC);kt(PC.ID,PC,0);function aEe(s){const e=s.get(xt).getFocusedCodeEditor();return e instanceof Uh?e.getParentEditor():e}const lEe={headerBackgroundColor:$.white,primaryHeadingColor:$.fromHex("#333333"),secondaryHeadingColor:$.fromHex("#6c6c6cb3")};let gL=class extends rEe{constructor(e,t,i){super(e,t),this.instantiationService=i,this._onDidClose=new B,this.onDidClose=this._onDidClose.event,UL(this.options,lEe,!1)}dispose(){this.disposed||(this.disposed=!0,super.dispose(),this._onDidClose.fire(this))}style(e){const t=this.options;e.headerBackgroundColor&&(t.headerBackgroundColor=e.headerBackgroundColor),e.primaryHeadingColor&&(t.primaryHeadingColor=e.primaryHeadingColor),e.secondaryHeadingColor&&(t.secondaryHeadingColor=e.secondaryHeadingColor),super.style(e)}_applyStyles(){super._applyStyles();const e=this.options;this._headElement&&e.headerBackgroundColor&&(this._headElement.style.backgroundColor=e.headerBackgroundColor.toString()),this._primaryHeading&&e.primaryHeadingColor&&(this._primaryHeading.style.color=e.primaryHeadingColor.toString()),this._secondaryHeading&&e.secondaryHeadingColor&&(this._secondaryHeading.style.color=e.secondaryHeadingColor.toString()),this._bodyElement&&e.frameColor&&(this._bodyElement.style.borderColor=e.frameColor.toString())}_fillContainer(e){this.setCssClass("peekview-widget"),this._headElement=he(".head"),this._bodyElement=he(".body"),this._fillHead(this._headElement),this._fillBody(this._bodyElement),e.appendChild(this._headElement),e.appendChild(this._bodyElement)}_fillHead(e,t){this._titleElement=he(".peekview-title"),this.options.supportOnTitleClick&&(this._titleElement.classList.add("clickable"),Ni(this._titleElement,"click",o=>this._onTitleClick(o))),Q(this._headElement,this._titleElement),this._fillTitleIcon(this._titleElement),this._primaryHeading=he("span.filename"),this._secondaryHeading=he("span.dirname"),this._metaHeading=he("span.meta"),Q(this._titleElement,this._primaryHeading,this._secondaryHeading,this._metaHeading);const i=he(".peekview-actions");Q(this._headElement,i);const n=this._getActionBarOptions();this._actionbarWidget=new Vr(i,n),this._disposables.add(this._actionbarWidget),t||this._actionbarWidget.push(new Eo("peekview.close",p("label.close","Close"),Pe.asClassName(oe.close),!0,()=>(this.dispose(),Promise.resolve())),{label:!1,icon:!0})}_fillTitleIcon(e){}_getActionBarOptions(){return{actionViewItemProvider:kj.bind(void 0,this.instantiationService),orientation:0}}_onTitleClick(e){}setTitle(e,t){this._primaryHeading&&this._secondaryHeading&&(this._primaryHeading.innerText=e,this._primaryHeading.setAttribute("title",e),t?this._secondaryHeading.innerText=t:zn(this._secondaryHeading))}setMetaTitle(e){this._metaHeading&&(e?(this._metaHeading.innerText=e,Do(this._metaHeading)):Es(this._metaHeading))}_doLayout(e,t){if(!this._isShowing&&e<0){this.dispose();return}const i=Math.ceil(this.editor.getOption(67)*1.2),n=Math.round(e-(i+2));this._doLayoutHead(i,t),this._doLayoutBody(n,t)}_doLayoutHead(e,t){this._headElement&&(this._headElement.style.height=`${e}px`,this._headElement.style.lineHeight=this._headElement.style.height)}_doLayoutBody(e,t){this._bodyElement&&(this._bodyElement.style.height=`${e}px`)}};gL=Fq([Oq(2,Ne)],gL);const dEe=N("peekViewTitle.background",{dark:"#252526",light:"#F3F3F3",hcDark:$.black,hcLight:$.white},p("peekViewTitleBackground","Background color of the peek view title area.")),Wq=N("peekViewTitleLabel.foreground",{dark:$.white,light:$.black,hcDark:$.white,hcLight:Tr},p("peekViewTitleForeground","Color of the peek view title.")),Hq=N("peekViewTitleDescription.foreground",{dark:"#ccccccb3",light:"#616161",hcDark:"#FFFFFF99",hcLight:"#292929"},p("peekViewTitleInfoForeground","Color of the peek view title info.")),cEe=N("peekView.border",{dark:ro,light:ro,hcDark:gt,hcLight:gt},p("peekViewBorder","Color of the peek view borders and arrow.")),uEe=N("peekViewResult.background",{dark:"#252526",light:"#F3F3F3",hcDark:$.black,hcLight:$.white},p("peekViewResultsBackground","Background color of the peek view result list."));N("peekViewResult.lineForeground",{dark:"#bbbbbb",light:"#646465",hcDark:$.white,hcLight:Tr},p("peekViewResultsMatchForeground","Foreground color for line nodes in the peek view result list."));N("peekViewResult.fileForeground",{dark:$.white,light:"#1E1E1E",hcDark:$.white,hcLight:Tr},p("peekViewResultsFileForeground","Foreground color for file nodes in the peek view result list."));N("peekViewResult.selectionBackground",{dark:"#3399ff33",light:"#3399ff33",hcDark:null,hcLight:null},p("peekViewResultsSelectionBackground","Background color of the selected entry in the peek view result list."));N("peekViewResult.selectionForeground",{dark:$.white,light:"#6C6C6C",hcDark:$.white,hcLight:Tr},p("peekViewResultsSelectionForeground","Foreground color of the selected entry in the peek view result list."));const Yu=N("peekViewEditor.background",{dark:"#001F33",light:"#F2F8FC",hcDark:$.black,hcLight:$.white},p("peekViewEditorBackground","Background color of the peek view editor."));N("peekViewEditorGutter.background",{dark:Yu,light:Yu,hcDark:Yu,hcLight:Yu},p("peekViewEditorGutterBackground","Background color of the gutter in the peek view editor."));N("peekViewEditorStickyScroll.background",{dark:Yu,light:Yu,hcDark:Yu,hcLight:Yu},p("peekViewEditorStickScrollBackground","Background color of sticky scroll in the peek view editor."));N("peekViewResult.matchHighlightBackground",{dark:"#ea5c004d",light:"#ea5c004d",hcDark:null,hcLight:null},p("peekViewResultsMatchHighlight","Match highlight color in the peek view result list."));N("peekViewEditor.matchHighlightBackground",{dark:"#ff8f0099",light:"#f5d802de",hcDark:null,hcLight:null},p("peekViewEditorMatchHighlight","Match highlight color in the peek view editor."));N("peekViewEditor.matchHighlightBorder",{dark:null,light:null,hcDark:di,hcLight:di},p("peekViewEditorMatchHighlightBorder","Match highlight border in the peek view editor."));class $h{constructor(e,t,i,n){this.isProviderFirst=e,this.parent=t,this.link=i,this._rangeCallback=n,this.id=c2.nextId()}get uri(){return this.link.uri}get range(){var e,t;return(t=(e=this._range)!==null&&e!==void 0?e:this.link.targetSelectionRange)!==null&&t!==void 0?t:this.link.range}set range(e){this._range=e,this._rangeCallback(this)}get ariaMessage(){var e;const t=(e=this.parent.getPreview(this))===null||e===void 0?void 0:e.preview(this.range);return t?p({},"{0} in {1} on line {2} at column {3}",t.value,Wr(this.uri),this.range.startLineNumber,this.range.startColumn):p("aria.oneReference","in {0} on line {1} at column {2}",Wr(this.uri),this.range.startLineNumber,this.range.startColumn)}}class hEe{constructor(e){this._modelReference=e}dispose(){this._modelReference.dispose()}preview(e,t=8){const i=this._modelReference.object.textEditorModel;if(!i)return;const{startLineNumber:n,startColumn:o,endLineNumber:r,endColumn:a}=e,l=i.getWordUntilPosition({lineNumber:n,column:o-t}),d=new x(n,l.startColumn,n,o),c=new x(r,a,r,1073741824),u=i.getValueInRange(d).replace(/^\s+/,""),h=i.getValueInRange(e),g=i.getValueInRange(c).replace(/\s+$/,"");return{value:u+h+g,highlight:{start:u.length,end:u.length+h.length}}}}class FC{constructor(e,t){this.parent=e,this.uri=t,this.children=[],this._previews=new Wi}dispose(){jt(this._previews.values()),this._previews.clear()}getPreview(e){return this._previews.get(e.uri)}get ariaMessage(){const e=this.children.length;return e===1?p("aria.fileReferences.1","1 symbol in {0}, full path {1}",Wr(this.uri),this.uri.fsPath):p("aria.fileReferences.N","{0} symbols in {1}, full path {2}",e,Wr(this.uri),this.uri.fsPath)}async resolve(e){if(this._previews.size!==0)return this;for(const t of this.children)if(!this._previews.has(t.uri))try{const i=await e.createModelReference(t.uri);this._previews.set(t.uri,new hEe(i))}catch(i){Xe(i)}return this}}class To{constructor(e,t){this.groups=[],this.references=[],this._onDidChangeReferenceRange=new B,this.onDidChangeReferenceRange=this._onDidChangeReferenceRange.event,this._links=e,this._title=t;const[i]=e;e.sort(To._compareReferences);let n;for(const o of e)if((!n||!ci.isEqual(n.uri,o.uri,!0))&&(n=new FC(this,o.uri),this.groups.push(n)),n.children.length===0||To._compareReferences(o,n.children[n.children.length-1])!==0){const r=new $h(i===o,n,o,a=>this._onDidChangeReferenceRange.fire(a));this.references.push(r),n.children.push(r)}}dispose(){jt(this.groups),this._onDidChangeReferenceRange.dispose(),this.groups.length=0}clone(){return new To(this._links,this._title)}get title(){return this._title}get isEmpty(){return this.groups.length===0}get ariaMessage(){return this.isEmpty?p("aria.result.0","No results found"):this.references.length===1?p("aria.result.1","Found 1 symbol in {0}",this.references[0].uri.fsPath):this.groups.length===1?p("aria.result.n1","Found {0} symbols in {1}",this.references.length,this.groups[0].uri.fsPath):p("aria.result.nm","Found {0} symbols in {1} files",this.references.length,this.groups.length)}nextOrPreviousReference(e,t){const{parent:i}=e;let n=i.children.indexOf(e);const o=i.children.length,r=i.parent.groups.length;return r===1||t&&n+10?(t?n=(n+1)%o:n=(n+o-1)%o,i.children[n]):(n=i.parent.groups.indexOf(i),t?(n=(n+1)%r,i.parent.groups[n].children[0]):(n=(n+r-1)%r,i.parent.groups[n].children[i.parent.groups[n].children.length-1]))}nearestReference(e,t){const i=this.references.map((n,o)=>({idx:o,prefixLen:Sh(n.uri.toString(),e.toString()),offsetDist:Math.abs(n.range.startLineNumber-t.lineNumber)*100+Math.abs(n.range.startColumn-t.column)})).sort((n,o)=>n.prefixLen>o.prefixLen?-1:n.prefixLeno.offsetDist?1:0)[0];if(i)return this.references[i.idx]}referenceAt(e,t){for(const i of this.references)if(i.uri.toString()===e.toString()&&x.containsPosition(i.range,t))return i}firstReference(){for(const e of this.references)if(e.isProviderFirst)return e;return this.references[0]}static _compareReferences(e,t){return ci.compare(e.uri,t.uri)||x.compareRangesUsingStarts(e.range,t.range)}}var Ck=function(s,e,t,i){var n=arguments.length,o=n<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,r;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(s,e,t,i);else for(var a=s.length-1;a>=0;a--)(r=s[a])&&(o=(n<3?r(o):n>3?r(e,t,o):r(e,t))||o);return n>3&&o&&Object.defineProperty(e,t,o),o},wk=function(s,e){return function(t,i){e(t,i,s)}},qM;let GM=class{constructor(e){this._resolverService=e}hasChildren(e){return e instanceof To||e instanceof FC}getChildren(e){if(e instanceof To)return e.groups;if(e instanceof FC)return e.resolve(this._resolverService).then(t=>t.children);throw new Error("bad tree")}};GM=Ck([wk(0,mo)],GM);class gEe{getHeight(){return 23}getTemplateId(e){return e instanceof FC?OC.id:U1.id}}let ZM=class{constructor(e){this._keybindingService=e}getKeyboardNavigationLabel(e){var t;if(e instanceof $h){const i=(t=e.parent.getPreview(e))===null||t===void 0?void 0:t.preview(e.range);if(i)return i.value}return Wr(e.uri)}};ZM=Ck([wk(0,At)],ZM);class fEe{getId(e){return e instanceof $h?e.id:e.uri}}let XM=class extends H{constructor(e,t){super(),this._labelService=t;const i=document.createElement("div");i.classList.add("reference-file"),this.file=this._register(new jD(i,{supportHighlights:!0})),this.badge=new K2(Q(i,he(".count")),{},Lj),e.appendChild(i)}set(e,t){const i=Ax(e.uri);this.file.setLabel(this._labelService.getUriBasenameLabel(e.uri),this._labelService.getUriLabel(i,{relative:!0}),{title:this._labelService.getUriLabel(e.uri),matches:t});const n=e.children.length;this.badge.setCount(n),n>1?this.badge.setTitleFormat(p("referencesCount","{0} references",n)):this.badge.setTitleFormat(p("referenceCount","{0} reference",n))}};XM=Ck([wk(1,k_)],XM);let OC=qM=class{constructor(e){this._instantiationService=e,this.templateId=qM.id}renderTemplate(e){return this._instantiationService.createInstance(XM,e)}renderElement(e,t,i){i.set(e.element,Bx(e.filterData))}disposeTemplate(e){e.dispose()}};OC.id="FileReferencesRenderer";OC=qM=Ck([wk(0,Ne)],OC);class pEe extends H{constructor(e){super(),this.label=this._register(new uh(e))}set(e,t){var i;const n=(i=e.parent.getPreview(e))===null||i===void 0?void 0:i.preview(e.range);if(!n||!n.value)this.label.set(`${Wr(e.uri)}:${e.range.startLineNumber+1}:${e.range.startColumn+1}`);else{const{value:o,highlight:r}=n;t&&!el.isDefault(t)?(this.label.element.classList.toggle("referenceMatch",!1),this.label.set(o,Bx(t))):(this.label.element.classList.toggle("referenceMatch",!0),this.label.set(o,[r]))}}}class U1{constructor(){this.templateId=U1.id}renderTemplate(e){return new pEe(e)}renderElement(e,t,i){i.set(e.element,e.filterData)}disposeTemplate(e){e.dispose()}}U1.id="OneReferenceRenderer";class mEe{getWidgetAriaLabel(){return p("treeAriaLabel","References")}getAriaLabel(e){return e.ariaMessage}}var _Ee=function(s,e,t,i){var n=arguments.length,o=n<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,r;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(s,e,t,i);else for(var a=s.length-1;a>=0;a--)(r=s[a])&&(o=(n<3?r(o):n>3?r(e,t,o):r(e,t))||o);return n>3&&o&&Object.defineProperty(e,t,o),o},$d=function(s,e){return function(t,i){e(t,i,s)}};class yk{constructor(e,t){this._editor=e,this._model=t,this._decorations=new Map,this._decorationIgnoreSet=new Set,this._callOnDispose=new Y,this._callOnModelChange=new Y,this._callOnDispose.add(this._editor.onDidChangeModel(()=>this._onModelChanged())),this._onModelChanged()}dispose(){this._callOnModelChange.dispose(),this._callOnDispose.dispose(),this.removeDecorations()}_onModelChanged(){this._callOnModelChange.clear();const e=this._editor.getModel();if(e){for(const t of this._model.references)if(t.uri.toString()===e.uri.toString()){this._addDecorations(t.parent);return}}}_addDecorations(e){if(!this._editor.hasModel())return;this._callOnModelChange.add(this._editor.getModel().onDidChangeDecorations(()=>this._onDecorationChanged()));const t=[],i=[];for(let n=0,o=e.children.length;n{const o=n.deltaDecorations([],t);for(let r=0;r{o.equals(9)&&(this._keybindingService.dispatchEvent(o,o.target),o.stopPropagation())},!0)),this._tree=this._instantiationService.createInstance(bEe,"ReferencesWidget",this._treeContainer,new gEe,[this._instantiationService.createInstance(OC),this._instantiationService.createInstance(U1)],this._instantiationService.createInstance(GM),i),this._splitView.addView({onDidChange:le.None,element:this._previewContainer,minimumSize:200,maximumSize:Number.MAX_VALUE,layout:o=>{this._preview.layout({height:this._dim.height,width:o})}},WD.Distribute),this._splitView.addView({onDidChange:le.None,element:this._treeContainer,minimumSize:100,maximumSize:Number.MAX_VALUE,layout:o=>{this._treeContainer.style.height=`${this._dim.height}px`,this._treeContainer.style.width=`${o}px`,this._tree.layout(this._dim.height,o)}},WD.Distribute),this._disposables.add(this._splitView.onDidSashChange(()=>{this._dim.width&&(this.layoutData.ratio=this._splitView.getViewSize(0)/this._dim.width)},void 0));const n=(o,r)=>{o instanceof $h&&(r==="show"&&this._revealReference(o,!1),this._onDidSelectReference.fire({element:o,kind:r,source:"tree"}))};this._tree.onDidOpen(o=>{o.sideBySide?n(o.element,"side"):o.editorOptions.pinned?n(o.element,"goto"):n(o.element,"show")}),Es(this._treeContainer)}_onWidth(e){this._dim&&this._doLayoutBody(this._dim.height,e)}_doLayoutBody(e,t){super._doLayoutBody(e,t),this._dim=new Dt(t,e),this.layoutData.heightInLines=this._viewZone?this._viewZone.heightInLines:this.layoutData.heightInLines,this._splitView.layout(t),this._splitView.resizeView(0,t*this.layoutData.ratio)}setSelection(e){return this._revealReference(e,!0).then(()=>{this._model&&(this._tree.setSelection([e]),this._tree.setFocus([e]))})}setModel(e){return this._disposeOnNewModel.clear(),this._model=e,this._model?this._onNewModel():Promise.resolve()}_onNewModel(){return this._model?this._model.isEmpty?(this.setTitle(""),this._messageContainer.innerText=p("noResults","No results"),Do(this._messageContainer),Promise.resolve(void 0)):(Es(this._messageContainer),this._decorationsManager=new yk(this._preview,this._model),this._disposeOnNewModel.add(this._decorationsManager),this._disposeOnNewModel.add(this._model.onDidChangeReferenceRange(e=>this._tree.rerender(e))),this._disposeOnNewModel.add(this._preview.onMouseDown(e=>{const{event:t,target:i}=e;if(t.detail!==2)return;const n=this._getFocusedReference();n&&this._onDidSelectReference.fire({element:{uri:n.uri,range:i.range},kind:t.ctrlKey||t.metaKey||t.altKey?"side":"open",source:"editor"})})),this.container.classList.add("results-loaded"),Do(this._treeContainer),Do(this._previewContainer),this._splitView.layout(this._dim.width),this.focusOnReferenceTree(),this._tree.setInput(this._model.groups.length===1?this._model.groups[0]:this._model)):Promise.resolve(void 0)}_getFocusedReference(){const[e]=this._tree.getFocus();if(e instanceof $h)return e;if(e instanceof FC&&e.children.length>0)return e.children[0]}async revealReference(e){await this._revealReference(e,!1),this._onDidSelectReference.fire({element:e,kind:"goto",source:"tree"})}async _revealReference(e,t){if(this._revealedReference===e)return;this._revealedReference=e,e.uri.scheme!==Ge.inMemory?this.setTitle(bme(e.uri),this._uriLabel.getUriLabel(Ax(e.uri))):this.setTitle(p("peekView.alternateTitle","References"));const i=this._textModelResolverService.createModelReference(e.uri);this._tree.getInput()===e.parent?this._tree.reveal(e):(t&&this._tree.reveal(e.parent),await this._tree.expand(e.parent),this._tree.reveal(e));const n=await i;if(!this._model){n.dispose();return}jt(this._previewModelReference);const o=n.object;if(o){const r=this._preview.getModel()===o.textEditorModel?0:1,a=x.lift(e.range).collapseToStart();this._previewModelReference=n,this._preview.setModel(o.textEditorModel),this._preview.setSelection(a),this._preview.revealRangeInCenter(a,r)}else this._preview.setModel(this._previewNotAvailableMessage),n.dispose()}};YM=_Ee([$d(3,_n),$d(4,mo),$d(5,Ne),$d(6,Bq),$d(7,k_),$d(8,Mx),$d(9,At),$d(10,vi),$d(11,Yt)],YM);var CEe=function(s,e,t,i){var n=arguments.length,o=n<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,r;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(s,e,t,i);else for(var a=s.length-1;a>=0;a--)(r=s[a])&&(o=(n<3?r(o):n>3?r(e,t,o):r(e,t))||o);return n>3&&o&&Object.defineProperty(e,t,o),o},Pp=function(s,e){return function(t,i){e(t,i,s)}},uS;const vp=new ue("referenceSearchVisible",!1,p("referenceSearchVisible","Whether reference peek is visible, like 'Peek References' or 'Peek Definition'"));let V_=uS=class{static get(e){return e.getContribution(uS.ID)}constructor(e,t,i,n,o,r,a,l){this._defaultTreeKeyboardSupport=e,this._editor=t,this._editorService=n,this._notificationService=o,this._instantiationService=r,this._storageService=a,this._configurationService=l,this._disposables=new Y,this._requestIdPool=0,this._ignoreModelChangeEvent=!1,this._referenceSearchVisible=vp.bindTo(i)}dispose(){var e,t;this._referenceSearchVisible.reset(),this._disposables.dispose(),(e=this._widget)===null||e===void 0||e.dispose(),(t=this._model)===null||t===void 0||t.dispose(),this._widget=void 0,this._model=void 0}toggleWidget(e,t,i){let n;if(this._widget&&(n=this._widget.position),this.closeWidget(),n&&e.containsPosition(n))return;this._peekMode=i,this._referenceSearchVisible.set(!0),this._disposables.add(this._editor.onDidChangeModelLanguage(()=>{this.closeWidget()})),this._disposables.add(this._editor.onDidChangeModel(()=>{this._ignoreModelChangeEvent||this.closeWidget()}));const o="peekViewLayout",r=vEe.fromJSON(this._storageService.get(o,0,"{}"));this._widget=this._instantiationService.createInstance(YM,this._editor,this._defaultTreeKeyboardSupport,r),this._widget.setTitle(p("labelLoading","Loading...")),this._widget.show(e),this._disposables.add(this._widget.onDidClose(()=>{t.cancel(),this._widget&&(this._storageService.store(o,JSON.stringify(this._widget.layoutData),0,1),this._widget=void 0),this.closeWidget()})),this._disposables.add(this._widget.onDidSelectReference(l=>{const{element:d,kind:c}=l;if(d)switch(c){case"open":(l.source!=="editor"||!this._configurationService.getValue("editor.stablePeek"))&&this.openReference(d,!1,!1);break;case"side":this.openReference(d,!0,!1);break;case"goto":i?this._gotoReference(d,!0):this.openReference(d,!1,!0);break}}));const a=++this._requestIdPool;t.then(l=>{var d;if(a!==this._requestIdPool||!this._widget){l.dispose();return}return(d=this._model)===null||d===void 0||d.dispose(),this._model=l,this._widget.setModel(this._model).then(()=>{if(this._widget&&this._model&&this._editor.hasModel()){this._model.isEmpty?this._widget.setMetaTitle(""):this._widget.setMetaTitle(p("metaTitle.N","{0} ({1})",this._model.title,this._model.references.length));const c=this._editor.getModel().uri,u=new W(e.startLineNumber,e.startColumn),h=this._model.nearestReference(c,u);if(h)return this._widget.setSelection(h).then(()=>{this._widget&&this._editor.getOption(87)==="editor"&&this._widget.focusOnPreviewEditor()})}})},l=>{this._notificationService.error(l)})}changeFocusBetweenPreviewAndReferences(){this._widget&&(this._widget.isPreviewEditorFocused()?this._widget.focusOnReferenceTree():this._widget.focusOnPreviewEditor())}async goToNextOrPreviousReference(e){if(!this._editor.hasModel()||!this._model||!this._widget)return;const t=this._widget.position;if(!t)return;const i=this._model.nearestReference(this._editor.getModel().uri,t);if(!i)return;const n=this._model.nextOrPreviousReference(i,e),o=this._editor.hasTextFocus(),r=this._widget.isPreviewEditorFocused();await this._widget.setSelection(n),await this._gotoReference(n,!1),o?this._editor.focus():this._widget&&r&&this._widget.focusOnPreviewEditor()}async revealReference(e){!this._editor.hasModel()||!this._model||!this._widget||await this._widget.revealReference(e)}closeWidget(e=!0){var t,i;(t=this._widget)===null||t===void 0||t.dispose(),(i=this._model)===null||i===void 0||i.dispose(),this._referenceSearchVisible.reset(),this._disposables.clear(),this._widget=void 0,this._model=void 0,e&&this._editor.focus(),this._requestIdPool+=1}_gotoReference(e,t){var i;(i=this._widget)===null||i===void 0||i.hide(),this._ignoreModelChangeEvent=!0;const n=x.lift(e.range).collapseToStart();return this._editorService.openCodeEditor({resource:e.uri,options:{selection:n,selectionSource:"code.jump",pinned:t}},this._editor).then(o=>{var r;if(this._ignoreModelChangeEvent=!1,!o||!this._widget){this.closeWidget();return}if(this._editor===o)this._widget.show(n),this._widget.focusOnReferenceTree();else{const a=uS.get(o),l=this._model.clone();this.closeWidget(),o.focus(),a==null||a.toggleWidget(n,Dn(d=>Promise.resolve(l)),(r=this._peekMode)!==null&&r!==void 0?r:!1)}},o=>{this._ignoreModelChangeEvent=!1,Xe(o)})}openReference(e,t,i){t||this.closeWidget();const{uri:n,range:o}=e;this._editorService.openCodeEditor({resource:n,options:{selection:o,selectionSource:"code.jump",pinned:i}},this._editor,t)}};V_.ID="editor.contrib.referencesController";V_=uS=CEe([Pp(2,Be),Pp(3,xt),Pp(4,en),Pp(5,Ne),Pp(6,Rd),Pp(7,rt)],V_);function bp(s,e){const t=aEe(s);if(!t)return;const i=V_.get(t);i&&e(i)}go.registerCommandAndKeybindingRule({id:"togglePeekWidgetFocus",weight:100,primary:an(2089,60),when:G.or(vp,po.inPeekEditor),handler(s){bp(s,e=>{e.changeFocusBetweenPreviewAndReferences()})}});go.registerCommandAndKeybindingRule({id:"goToNextReference",weight:90,primary:62,secondary:[70],when:G.or(vp,po.inPeekEditor),handler(s){bp(s,e=>{e.goToNextOrPreviousReference(!0)})}});go.registerCommandAndKeybindingRule({id:"goToPreviousReference",weight:90,primary:1086,secondary:[1094],when:G.or(vp,po.inPeekEditor),handler(s){bp(s,e=>{e.goToNextOrPreviousReference(!1)})}});pt.registerCommandAlias("goToNextReferenceFromEmbeddedEditor","goToNextReference");pt.registerCommandAlias("goToPreviousReferenceFromEmbeddedEditor","goToPreviousReference");pt.registerCommandAlias("closeReferenceSearchEditor","closeReferenceSearch");pt.registerCommand("closeReferenceSearch",s=>bp(s,e=>e.closeWidget()));go.registerKeybindingRule({id:"closeReferenceSearch",weight:-1,primary:9,secondary:[1033],when:G.and(po.inPeekEditor,G.not("config.editor.stablePeek"))});go.registerKeybindingRule({id:"closeReferenceSearch",weight:250,primary:9,secondary:[1033],when:G.and(vp,G.not("config.editor.stablePeek"),G.or(T.editorTextFocus,wwe.negate()))});go.registerCommandAndKeybindingRule({id:"revealReference",weight:200,primary:3,mac:{primary:3,secondary:[2066]},when:G.and(vp,Zj,HO.negate(),VO.negate()),handler(s){var e;const i=(e=s.get(Kr).lastFocusedList)===null||e===void 0?void 0:e.getFocus();Array.isArray(i)&&i[0]instanceof $h&&bp(s,n=>n.revealReference(i[0]))}});go.registerCommandAndKeybindingRule({id:"openReferenceToSide",weight:100,primary:2051,mac:{primary:259},when:G.and(vp,Zj,HO.negate(),VO.negate()),handler(s){var e;const i=(e=s.get(Kr).lastFocusedList)===null||e===void 0?void 0:e.getFocus();Array.isArray(i)&&i[0]instanceof $h&&bp(s,n=>n.openReference(i[0],!0,!0))}});pt.registerCommand("openReference",s=>{var e;const i=(e=s.get(Kr).lastFocusedList)===null||e===void 0?void 0:e.getFocus();Array.isArray(i)&&i[0]instanceof $h&&bp(s,n=>n.openReference(i[0],!1,!0))});var Vq=function(s,e,t,i){var n=arguments.length,o=n<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,r;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(s,e,t,i);else for(var a=s.length-1;a>=0;a--)(r=s[a])&&(o=(n<3?r(o):n>3?r(e,t,o):r(e,t))||o);return n>3&&o&&Object.defineProperty(e,t,o),o},Tv=function(s,e){return function(t,i){e(t,i,s)}};const S4=new ue("hasSymbols",!1,p("hasSymbols","Whether there are symbol locations that can be navigated via keyboard-only.")),Sk=ut("ISymbolNavigationService");let QM=class{constructor(e,t,i,n){this._editorService=t,this._notificationService=i,this._keybindingService=n,this._currentModel=void 0,this._currentIdx=-1,this._ignoreEditorChange=!1,this._ctxHasSymbols=S4.bindTo(e)}reset(){var e,t;this._ctxHasSymbols.reset(),(e=this._currentState)===null||e===void 0||e.dispose(),(t=this._currentMessage)===null||t===void 0||t.dispose(),this._currentModel=void 0,this._currentIdx=-1}put(e){const t=e.parent.parent;if(t.references.length<=1){this.reset();return}this._currentModel=t,this._currentIdx=t.references.indexOf(e),this._ctxHasSymbols.set(!0),this._showMessage();const i=new JM(this._editorService),n=i.onDidChange(o=>{if(this._ignoreEditorChange)return;const r=this._editorService.getActiveCodeEditor();if(!r)return;const a=r.getModel(),l=r.getPosition();if(!a||!l)return;let d=!1,c=!1;for(const u of t.references)if(ZF(u.uri,a.uri))d=!0,c=c||x.containsPosition(u.range,l);else if(d)break;(!d||!c)&&this.reset()});this._currentState=ha(i,n)}revealNext(e){if(!this._currentModel)return Promise.resolve();this._currentIdx+=1,this._currentIdx%=this._currentModel.references.length;const t=this._currentModel.references[this._currentIdx];return this._showMessage(),this._ignoreEditorChange=!0,this._editorService.openCodeEditor({resource:t.uri,options:{selection:x.collapseToStart(t.range),selectionRevealType:3}},e).finally(()=>{this._ignoreEditorChange=!1})}_showMessage(){var e;(e=this._currentMessage)===null||e===void 0||e.dispose();const t=this._keybindingService.lookupKeybinding("editor.gotoNextSymbolFromResult"),i=t?p("location.kb","Symbol {0} of {1}, {2} for next",this._currentIdx+1,this._currentModel.references.length,t.getLabel()):p("location","Symbol {0} of {1}",this._currentIdx+1,this._currentModel.references.length);this._currentMessage=this._notificationService.status(i)}};QM=Vq([Tv(0,Be),Tv(1,xt),Tv(2,en),Tv(3,At)],QM);mt(Sk,QM,1);de(new class extends mn{constructor(){super({id:"editor.gotoNextSymbolFromResult",precondition:S4,kbOpts:{weight:100,primary:70}})}runEditorCommand(s,e){return s.get(Sk).revealNext(e)}});go.registerCommandAndKeybindingRule({id:"editor.gotoNextSymbolFromResult.cancel",weight:100,when:S4,primary:9,handler(s){s.get(Sk).reset()}});let JM=class{constructor(e){this._listener=new Map,this._disposables=new Y,this._onDidChange=new B,this.onDidChange=this._onDidChange.event,this._disposables.add(e.onCodeEditorRemove(this._onDidRemoveEditor,this)),this._disposables.add(e.onCodeEditorAdd(this._onDidAddEditor,this)),e.listCodeEditors().forEach(this._onDidAddEditor,this)}dispose(){this._disposables.dispose(),this._onDidChange.dispose(),jt(this._listener.values())}_onDidAddEditor(e){this._listener.set(e,ha(e.onDidChangeCursorPosition(t=>this._onDidChange.fire({editor:e})),e.onDidChangeModelContent(t=>this._onDidChange.fire({editor:e}))))}_onDidRemoveEditor(e){var t;(t=this._listener.get(e))===null||t===void 0||t.dispose(),this._listener.delete(e)}};JM=Vq([Tv(0,xt)],JM);async function $1(s,e,t,i){const o=t.ordered(s).map(a=>Promise.resolve(i(a,s,e)).then(void 0,l=>{Ai(l)})),r=await Promise.all(o);return pd(r.flat())}function Dk(s,e,t,i){return $1(e,t,s,(n,o,r)=>n.provideDefinition(o,r,i))}function zq(s,e,t,i){return $1(e,t,s,(n,o,r)=>n.provideDeclaration(o,r,i))}function Uq(s,e,t,i){return $1(e,t,s,(n,o,r)=>n.provideImplementation(o,r,i))}function $q(s,e,t,i){return $1(e,t,s,(n,o,r)=>n.provideTypeDefinition(o,r,i))}function Lk(s,e,t,i,n){return $1(e,t,s,async(o,r,a)=>{const l=await o.provideReferences(r,a,{includeDeclaration:!0},n);if(!i||!l||l.length!==2)return l;const d=await o.provideReferences(r,a,{includeDeclaration:!1},n);return d&&d.length===1?d:l})}async function j1(s){const e=await s(),t=new To(e,""),i=t.references.map(n=>n.link);return t.dispose(),i}Ad("_executeDefinitionProvider",(s,e,t)=>{const i=s.get(Ce),n=Dk(i.definitionProvider,e,t,dt.None);return j1(()=>n)});Ad("_executeTypeDefinitionProvider",(s,e,t)=>{const i=s.get(Ce),n=$q(i.typeDefinitionProvider,e,t,dt.None);return j1(()=>n)});Ad("_executeDeclarationProvider",(s,e,t)=>{const i=s.get(Ce),n=zq(i.declarationProvider,e,t,dt.None);return j1(()=>n)});Ad("_executeReferenceProvider",(s,e,t)=>{const i=s.get(Ce),n=Lk(i.referenceProvider,e,t,!1,dt.None);return j1(()=>n)});Ad("_executeImplementationProvider",(s,e,t)=>{const i=s.get(Ce),n=Uq(i.implementationProvider,e,t,dt.None);return j1(()=>n)});var tv,iv,nv,oy,ry,ay,ly,dy;yn.appendMenuItem(E.EditorContext,{submenu:E.EditorContextPeek,title:p("peek.submenu","Peek"),group:"navigation",order:100});class z_{static is(e){return!e||typeof e!="object"?!1:!!(e instanceof z_||W.isIPosition(e.position)&&e.model)}constructor(e,t){this.model=e,this.position=t}}class _s extends fl{static all(){return _s._allSymbolNavigationCommands.values()}static _patchConfig(e){const t={...e,f1:!0};if(t.menu)for(const i of ft.wrap(t.menu))(i.id===E.EditorContext||i.id===E.EditorContextPeek)&&(i.when=G.and(e.precondition,i.when));return t}constructor(e,t){super(_s._patchConfig(t)),this.configuration=e,_s._allSymbolNavigationCommands.set(t.id,this)}runEditorCommand(e,t,i,n){if(!t.hasModel())return Promise.resolve(void 0);const o=e.get(en),r=e.get(xt),a=e.get(sg),l=e.get(Sk),d=e.get(Ce),c=e.get(Ne),u=t.getModel(),h=t.getPosition(),g=z_.is(i)?i:new z_(u,h),f=new Bh(t,5),m=h1(this._getLocationModel(d,g.model,g.position,f.token),f.token).then(async _=>{var v;if(!_||f.token.isCancellationRequested)return;fo(_.ariaMessage);let b;if(_.referenceAt(u.uri,h)){const w=this._getAlternativeCommand(t);!_s._activeAlternativeCommands.has(w)&&_s._allSymbolNavigationCommands.has(w)&&(b=_s._allSymbolNavigationCommands.get(w))}const C=_.references.length;if(C===0){if(!this.configuration.muteMessage){const w=u.getWordAtPosition(h);(v=Vs.get(t))===null||v===void 0||v.showMessage(this._getNoResultFoundMessage(w),h)}}else if(C===1&&b)_s._activeAlternativeCommands.add(this.desc.id),c.invokeFunction(w=>b.runEditorCommand(w,t,i,n).finally(()=>{_s._activeAlternativeCommands.delete(this.desc.id)}));else return this._onResult(r,l,t,_,n)},_=>{o.error(_)}).finally(()=>{f.dispose()});return a.showWhile(m,250),m}async _onResult(e,t,i,n,o){const r=this._getGoToPreference(i);if(!(i instanceof Uh)&&(this.configuration.openInPeek||r==="peek"&&n.references.length>1))this._openInPeek(i,n,o);else{const a=n.firstReference(),l=n.references.length>1&&r==="gotoAndPeek",d=await this._openReference(i,e,a,this.configuration.openToSide,!l);l&&d?this._openInPeek(d,n,o):n.dispose(),r==="goto"&&t.put(a)}}async _openReference(e,t,i,n,o){let r;if(wre(i)&&(r=i.targetSelectionRange),r||(r=i.range),!r)return;const a=await t.openCodeEditor({resource:i.uri,options:{selection:x.collapseToStart(r),selectionRevealType:3,selectionSource:"code.jump"}},e,n);if(a){if(o){const l=a.getModel(),d=a.createDecorationsCollection([{range:r,options:{description:"symbol-navigate-action-highlight",className:"symbolHighlight"}}]);setTimeout(()=>{a.getModel()===l&&d.clear()},350)}return a}}_openInPeek(e,t,i){const n=V_.get(e);n&&e.hasModel()?n.toggleWidget(i??e.getSelection(),Dn(o=>Promise.resolve(t)),this.configuration.openInPeek):t.dispose()}}_s._allSymbolNavigationCommands=new Map;_s._activeAlternativeCommands=new Set;class K1 extends _s{async _getLocationModel(e,t,i,n){return new To(await Dk(e.definitionProvider,t,i,n),p("def.title","Definitions"))}_getNoResultFoundMessage(e){return e&&e.word?p("noResultWord","No definition found for '{0}'",e.word):p("generic.noResults","No definition found")}_getAlternativeCommand(e){return e.getOption(58).alternativeDefinitionCommand}_getGoToPreference(e){return e.getOption(58).multipleDefinitions}}qt((tv=class extends K1{constructor(){super({openToSide:!1,openInPeek:!1,muteMessage:!1},{id:tv.id,title:{...Ve("actions.goToDecl.label","Go to Definition"),mnemonicTitle:p({},"Go to &&Definition")},precondition:T.hasDefinitionProvider,keybinding:[{when:T.editorTextFocus,primary:70,weight:100},{when:G.and(T.editorTextFocus,jj),primary:2118,weight:100}],menu:[{id:E.EditorContext,group:"navigation",order:1.1},{id:E.MenubarGoMenu,precondition:null,group:"4_symbol_nav",order:2}]}),pt.registerCommandAlias("editor.action.goToDeclaration",tv.id)}},tv.id="editor.action.revealDefinition",tv));qt((iv=class extends K1{constructor(){super({openToSide:!0,openInPeek:!1,muteMessage:!1},{id:iv.id,title:Ve("actions.goToDeclToSide.label","Open Definition to the Side"),precondition:G.and(T.hasDefinitionProvider,T.isInEmbeddedEditor.toNegated()),keybinding:[{when:T.editorTextFocus,primary:an(2089,70),weight:100},{when:G.and(T.editorTextFocus,jj),primary:an(2089,2118),weight:100}]}),pt.registerCommandAlias("editor.action.openDeclarationToTheSide",iv.id)}},iv.id="editor.action.revealDefinitionAside",iv));qt((nv=class extends K1{constructor(){super({openToSide:!1,openInPeek:!0,muteMessage:!1},{id:nv.id,title:Ve("actions.previewDecl.label","Peek Definition"),precondition:G.and(T.hasDefinitionProvider,po.notInPeekEditor,T.isInEmbeddedEditor.toNegated()),keybinding:{when:T.editorTextFocus,primary:582,linux:{primary:3140},weight:100},menu:{id:E.EditorContextPeek,group:"peek",order:2}}),pt.registerCommandAlias("editor.action.previewDeclaration",nv.id)}},nv.id="editor.action.peekDefinition",nv));class jq extends _s{async _getLocationModel(e,t,i,n){return new To(await zq(e.declarationProvider,t,i,n),p("decl.title","Declarations"))}_getNoResultFoundMessage(e){return e&&e.word?p("decl.noResultWord","No declaration found for '{0}'",e.word):p("decl.generic.noResults","No declaration found")}_getAlternativeCommand(e){return e.getOption(58).alternativeDeclarationCommand}_getGoToPreference(e){return e.getOption(58).multipleDeclarations}}qt((oy=class extends jq{constructor(){super({openToSide:!1,openInPeek:!1,muteMessage:!1},{id:oy.id,title:{...Ve("actions.goToDeclaration.label","Go to Declaration"),mnemonicTitle:p({},"Go to &&Declaration")},precondition:G.and(T.hasDeclarationProvider,T.isInEmbeddedEditor.toNegated()),menu:[{id:E.EditorContext,group:"navigation",order:1.3},{id:E.MenubarGoMenu,precondition:null,group:"4_symbol_nav",order:3}]})}_getNoResultFoundMessage(e){return e&&e.word?p("decl.noResultWord","No declaration found for '{0}'",e.word):p("decl.generic.noResults","No declaration found")}},oy.id="editor.action.revealDeclaration",oy));qt(class extends jq{constructor(){super({openToSide:!1,openInPeek:!0,muteMessage:!1},{id:"editor.action.peekDeclaration",title:Ve("actions.peekDecl.label","Peek Declaration"),precondition:G.and(T.hasDeclarationProvider,po.notInPeekEditor,T.isInEmbeddedEditor.toNegated()),menu:{id:E.EditorContextPeek,group:"peek",order:3}})}});class Kq extends _s{async _getLocationModel(e,t,i,n){return new To(await $q(e.typeDefinitionProvider,t,i,n),p("typedef.title","Type Definitions"))}_getNoResultFoundMessage(e){return e&&e.word?p("goToTypeDefinition.noResultWord","No type definition found for '{0}'",e.word):p("goToTypeDefinition.generic.noResults","No type definition found")}_getAlternativeCommand(e){return e.getOption(58).alternativeTypeDefinitionCommand}_getGoToPreference(e){return e.getOption(58).multipleTypeDefinitions}}qt((ry=class extends Kq{constructor(){super({openToSide:!1,openInPeek:!1,muteMessage:!1},{id:ry.ID,title:{...Ve("actions.goToTypeDefinition.label","Go to Type Definition"),mnemonicTitle:p({},"Go to &&Type Definition")},precondition:T.hasTypeDefinitionProvider,keybinding:{when:T.editorTextFocus,primary:0,weight:100},menu:[{id:E.EditorContext,group:"navigation",order:1.4},{id:E.MenubarGoMenu,precondition:null,group:"4_symbol_nav",order:3}]})}},ry.ID="editor.action.goToTypeDefinition",ry));qt((ay=class extends Kq{constructor(){super({openToSide:!1,openInPeek:!0,muteMessage:!1},{id:ay.ID,title:Ve("actions.peekTypeDefinition.label","Peek Type Definition"),precondition:G.and(T.hasTypeDefinitionProvider,po.notInPeekEditor,T.isInEmbeddedEditor.toNegated()),menu:{id:E.EditorContextPeek,group:"peek",order:4}})}},ay.ID="editor.action.peekTypeDefinition",ay));class qq extends _s{async _getLocationModel(e,t,i,n){return new To(await Uq(e.implementationProvider,t,i,n),p("impl.title","Implementations"))}_getNoResultFoundMessage(e){return e&&e.word?p("goToImplementation.noResultWord","No implementation found for '{0}'",e.word):p("goToImplementation.generic.noResults","No implementation found")}_getAlternativeCommand(e){return e.getOption(58).alternativeImplementationCommand}_getGoToPreference(e){return e.getOption(58).multipleImplementations}}qt((ly=class extends qq{constructor(){super({openToSide:!1,openInPeek:!1,muteMessage:!1},{id:ly.ID,title:{...Ve("actions.goToImplementation.label","Go to Implementations"),mnemonicTitle:p({},"Go to &&Implementations")},precondition:T.hasImplementationProvider,keybinding:{when:T.editorTextFocus,primary:2118,weight:100},menu:[{id:E.EditorContext,group:"navigation",order:1.45},{id:E.MenubarGoMenu,precondition:null,group:"4_symbol_nav",order:4}]})}},ly.ID="editor.action.goToImplementation",ly));qt((dy=class extends qq{constructor(){super({openToSide:!1,openInPeek:!0,muteMessage:!1},{id:dy.ID,title:Ve("actions.peekImplementation.label","Peek Implementations"),precondition:G.and(T.hasImplementationProvider,po.notInPeekEditor,T.isInEmbeddedEditor.toNegated()),keybinding:{when:T.editorTextFocus,primary:3142,weight:100},menu:{id:E.EditorContextPeek,group:"peek",order:5}})}},dy.ID="editor.action.peekImplementation",dy));class Gq extends _s{_getNoResultFoundMessage(e){return e?p("references.no","No references found for '{0}'",e.word):p("references.noGeneric","No references found")}_getAlternativeCommand(e){return e.getOption(58).alternativeReferenceCommand}_getGoToPreference(e){return e.getOption(58).multipleReferences}}qt(class extends Gq{constructor(){super({openToSide:!1,openInPeek:!1,muteMessage:!1},{id:"editor.action.goToReferences",title:{...Ve("goToReferences.label","Go to References"),mnemonicTitle:p({},"Go to &&References")},precondition:G.and(T.hasReferenceProvider,po.notInPeekEditor,T.isInEmbeddedEditor.toNegated()),keybinding:{when:T.editorTextFocus,primary:1094,weight:100},menu:[{id:E.EditorContext,group:"navigation",order:1.45},{id:E.MenubarGoMenu,precondition:null,group:"4_symbol_nav",order:5}]})}async _getLocationModel(e,t,i,n){return new To(await Lk(e.referenceProvider,t,i,!0,n),p("ref.title","References"))}});qt(class extends Gq{constructor(){super({openToSide:!1,openInPeek:!0,muteMessage:!1},{id:"editor.action.referenceSearch.trigger",title:Ve("references.action.label","Peek References"),precondition:G.and(T.hasReferenceProvider,po.notInPeekEditor,T.isInEmbeddedEditor.toNegated()),menu:{id:E.EditorContextPeek,group:"peek",order:6}})}async _getLocationModel(e,t,i,n){return new To(await Lk(e.referenceProvider,t,i,!1,n),p("ref.title","References"))}});class wEe extends _s{constructor(e,t,i){super(e,{id:"editor.action.goToLocation",title:Ve("label.generic","Go to Any Symbol"),precondition:G.and(po.notInPeekEditor,T.isInEmbeddedEditor.toNegated())}),this._references=t,this._gotoMultipleBehaviour=i}async _getLocationModel(e,t,i,n){return new To(this._references,p("generic.title","Locations"))}_getNoResultFoundMessage(e){return e&&p("generic.noResult","No results for '{0}'",e.word)||""}_getGoToPreference(e){var t;return(t=this._gotoMultipleBehaviour)!==null&&t!==void 0?t:e.getOption(58).multipleReferences}_getAlternativeCommand(){return""}}pt.registerCommand({id:"editor.action.goToLocations",metadata:{description:"Go to locations from a position in a file",args:[{name:"uri",description:"The text document in which to start",constraint:Ae},{name:"position",description:"The position at which to start",constraint:W.isIPosition},{name:"locations",description:"An array of locations.",constraint:Array},{name:"multiple",description:"Define what to do when having multiple results, either `peek`, `gotoAndPeek`, or `goto`"},{name:"noResultsMessage",description:"Human readable message that shows when locations is empty."}]},handler:async(s,e,t,i,n,o,r)=>{yt(Ae.isUri(e)),yt(W.isIPosition(t)),yt(Array.isArray(i)),yt(typeof n>"u"||typeof n=="string"),yt(typeof r>"u"||typeof r=="boolean");const a=s.get(xt),l=await a.openCodeEditor({resource:e},a.getFocusedCodeEditor());if(Wh(l))return l.setPosition(t),l.revealPositionInCenterIfOutsideViewport(t,0),l.invokeWithinContext(d=>{const c=new class extends wEe{_getNoResultFoundMessage(u){return o||super._getNoResultFoundMessage(u)}}({muteMessage:!o,openInPeek:!!r,openToSide:!1},i,n);d.get(Ne).invokeFunction(c.run.bind(c),l)})}});pt.registerCommand({id:"editor.action.peekLocations",metadata:{description:"Peek locations from a position in a file",args:[{name:"uri",description:"The text document in which to start",constraint:Ae},{name:"position",description:"The position at which to start",constraint:W.isIPosition},{name:"locations",description:"An array of locations.",constraint:Array},{name:"multiple",description:"Define what to do when having multiple results, either `peek`, `gotoAndPeek`, or `goto`"}]},handler:async(s,e,t,i,n)=>{s.get(gi).executeCommand("editor.action.goToLocations",e,t,i,n,void 0,!0)}});pt.registerCommand({id:"editor.action.findReferences",handler:(s,e,t)=>{yt(Ae.isUri(e)),yt(W.isIPosition(t));const i=s.get(Ce),n=s.get(xt);return n.openCodeEditor({resource:e},n.getFocusedCodeEditor()).then(o=>{if(!Wh(o)||!o.hasModel())return;const r=V_.get(o);if(!r)return;const a=Dn(d=>Lk(i.referenceProvider,o.getModel(),W.lift(t),!1,d).then(c=>new To(c,p("ref.title","References")))),l=new x(t.lineNumber,t.column,t.lineNumber,t.column);return Promise.resolve(r.toggleWidget(l,a,!1))})}});pt.registerCommandAlias("editor.action.showReferences","editor.action.peekLocations");async function yEe(s,e,t,i){var n;const o=s.get(mo),r=s.get(Oo),a=s.get(gi),l=s.get(Ne),d=s.get(en);if(await i.item.resolve(dt.None),!i.part.location)return;const c=i.part.location,u=[],h=new Set(yn.getMenuItems(E.EditorContext).map(f=>tm(f)?f.command.id:pk()));for(const f of _s.all())h.has(f.desc.id)&&u.push(new Eo(f.desc.id,Io.label(f.desc,{renderShortTitle:!0}),void 0,!0,async()=>{const m=await o.createModelReference(c.uri);try{const _=new z_(m.object.textEditorModel,x.getStartPosition(c.range)),v=i.item.anchor.range;await l.invokeFunction(f.runEditorCommand.bind(f),e,_,v)}finally{m.dispose()}}));if(i.part.command){const{command:f}=i.part;u.push(new rn),u.push(new Eo(f.id,f.title,void 0,!0,async()=>{var m;try{await a.executeCommand(f.id,...(m=f.arguments)!==null&&m!==void 0?m:[])}catch(_){d.notify({severity:Rx.Error,source:i.item.provider.displayName,message:_})}}))}const g=e.getOption(127);r.showContextMenu({domForShadowRoot:g&&(n=e.getDomNode())!==null&&n!==void 0?n:void 0,getAnchor:()=>{const f=qi(t);return{x:f.left,y:f.top+f.height+8}},getActions:()=>u,onHide:()=>{e.focus()},autoSelectFirstItem:!0})}async function Zq(s,e,t,i){const o=await s.get(mo).createModelReference(i.uri);await t.invokeWithinContext(async r=>{const a=e.hasSideBySideModifier,l=r.get(Be),d=po.inPeekEditor.getValue(l),c=!a&&t.getOption(88)&&!d;return new K1({openToSide:a,openInPeek:c,muteMessage:!0},{title:{value:"",original:""},id:"",precondition:void 0}).run(r,new z_(o.object.textEditorModel,x.getStartPosition(i.range)),x.lift(i.range))}),o.dispose()}var SEe=function(s,e,t,i){var n=arguments.length,o=n<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,r;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(s,e,t,i);else for(var a=s.length-1;a>=0;a--)(r=s[a])&&(o=(n<3?r(o):n>3?r(e,t,o):r(e,t))||o);return n>3&&o&&Object.defineProperty(e,t,o),o},Fp=function(s,e){return function(t,i){e(t,i,s)}},Kp;class fL{constructor(){this._entries=new iu(50)}get(e){const t=fL._key(e);return this._entries.get(t)}set(e,t){const i=fL._key(e);this._entries.set(i,t)}static _key(e){return`${e.uri.toString()}/${e.getVersionId()}`}}const Xq=ut("IInlayHintsCache");mt(Xq,fL,1);class eR{constructor(e,t){this.item=e,this.index=t}get part(){const e=this.item.hint.label;return typeof e=="string"?{label:e}:e[this.index]}}class DEe{constructor(e,t){this.part=e,this.hasTriggerModifier=t}}let jh=Kp=class{static get(e){var t;return(t=e.getContribution(Kp.ID))!==null&&t!==void 0?t:void 0}constructor(e,t,i,n,o,r,a){this._editor=e,this._languageFeaturesService=t,this._inlayHintsCache=n,this._commandService=o,this._notificationService=r,this._instaService=a,this._disposables=new Y,this._sessionDisposables=new Y,this._decorationsMetadata=new Map,this._ruleFactory=new v1(this._editor),this._activeRenderMode=0,this._debounceInfo=i.for(t.inlayHintsProvider,"InlayHint",{min:25}),this._disposables.add(t.inlayHintsProvider.onDidChange(()=>this._update())),this._disposables.add(e.onDidChangeModel(()=>this._update())),this._disposables.add(e.onDidChangeModelLanguage(()=>this._update())),this._disposables.add(e.onDidChangeConfiguration(l=>{l.hasChanged(141)&&this._update()})),this._update()}dispose(){this._sessionDisposables.dispose(),this._removeAllDecorations(),this._disposables.dispose()}_update(){this._sessionDisposables.clear(),this._removeAllDecorations();const e=this._editor.getOption(141);if(e.enabled==="off")return;const t=this._editor.getModel();if(!t||!this._languageFeaturesService.inlayHintsProvider.has(t))return;if(e.enabled==="on")this._activeRenderMode=0;else{let a,l;e.enabled==="onUnlessPressed"?(a=0,l=1):(a=1,l=0),this._activeRenderMode=a,this._sessionDisposables.add(hc.getInstance().event(d=>{if(!this._editor.hasModel())return;const c=d.altKey&&d.ctrlKey&&!(d.shiftKey||d.metaKey)?l:a;if(c!==this._activeRenderMode){this._activeRenderMode=c;const u=this._editor.getModel(),h=this._copyInlayHintsWithCurrentAnchor(u);this._updateHintsDecorators([u.getFullModelRange()],h),r.schedule(0)}}))}const i=this._inlayHintsCache.get(t);i&&this._updateHintsDecorators([t.getFullModelRange()],i),this._sessionDisposables.add(Ie(()=>{t.isDisposed()||this._cacheHintsForFastRestore(t)}));let n;const o=new Set,r=new Wt(async()=>{const a=Date.now();n==null||n.dispose(!0),n=new Vi;const l=t.onWillDispose(()=>n==null?void 0:n.cancel());try{const d=n.token,c=await gf.create(this._languageFeaturesService.inlayHintsProvider,t,this._getHintsRanges(),d);if(r.delay=this._debounceInfo.update(t,Date.now()-a),d.isCancellationRequested){c.dispose();return}for(const u of c.provider)typeof u.onDidChangeInlayHints=="function"&&!o.has(u)&&(o.add(u),this._sessionDisposables.add(u.onDidChangeInlayHints(()=>{r.isScheduled()||r.schedule()})));this._sessionDisposables.add(c),this._updateHintsDecorators(c.ranges,c.items),this._cacheHintsForFastRestore(t)}catch(d){Xe(d)}finally{n.dispose(),l.dispose()}},this._debounceInfo.get(t));this._sessionDisposables.add(r),this._sessionDisposables.add(Ie(()=>n==null?void 0:n.dispose(!0))),r.schedule(0),this._sessionDisposables.add(this._editor.onDidScrollChange(a=>{(a.scrollTopChanged||!r.isScheduled())&&r.schedule()})),this._sessionDisposables.add(this._editor.onDidChangeModelContent(a=>{n==null||n.cancel();const l=Math.max(r.delay,1250);r.schedule(l)})),this._sessionDisposables.add(this._installDblClickGesture(()=>r.schedule(0))),this._sessionDisposables.add(this._installLinkGesture()),this._sessionDisposables.add(this._installContextMenu())}_installLinkGesture(){const e=new Y,t=e.add(new vk(this._editor)),i=new Y;return e.add(i),e.add(t.onMouseMoveOrRelevantKeyDown(n=>{const[o]=n,r=this._getInlayHintLabelPart(o),a=this._editor.getModel();if(!r||!a){i.clear();return}const l=new Vi;i.add(Ie(()=>l.dispose(!0))),r.item.resolve(l.token),this._activeInlayHintPart=r.part.command||r.part.location?new DEe(r,o.hasTriggerModifier):void 0;const d=a.validatePosition(r.item.hint.position).lineNumber,c=new x(d,1,d,a.getLineMaxColumn(d)),u=this._getInlineHintsForRange(c);this._updateHintsDecorators([c],u),i.add(Ie(()=>{this._activeInlayHintPart=void 0,this._updateHintsDecorators([c],u)}))})),e.add(t.onCancel(()=>i.clear())),e.add(t.onExecute(async n=>{const o=this._getInlayHintLabelPart(n);if(o){const r=o.part;r.location?this._instaService.invokeFunction(Zq,n,this._editor,r.location):sN.is(r.command)&&await this._invokeCommand(r.command,o.item)}})),e}_getInlineHintsForRange(e){const t=new Set;for(const i of this._decorationsMetadata.values())e.containsRange(i.item.anchor.range)&&t.add(i.item);return Array.from(t)}_installDblClickGesture(e){return this._editor.onMouseUp(async t=>{if(t.event.detail!==2)return;const i=this._getInlayHintLabelPart(t);if(i&&(t.event.preventDefault(),await i.item.resolve(dt.None),rs(i.item.hint.textEdits))){const n=i.item.hint.textEdits.map(o=>pi.replace(x.lift(o.range),o.text));this._editor.executeEdits("inlayHint.default",n),e()}})}_installContextMenu(){return this._editor.onContextMenu(async e=>{if(!(e.event.target instanceof HTMLElement))return;const t=this._getInlayHintLabelPart(e);t&&await this._instaService.invokeFunction(yEe,this._editor,e.event.target,t)})}_getInlayHintLabelPart(e){var t;if(e.target.type!==6)return;const i=(t=e.target.detail.injectedText)===null||t===void 0?void 0:t.options;if(i instanceof Ph&&(i==null?void 0:i.attachedData)instanceof eR)return i.attachedData}async _invokeCommand(e,t){var i;try{await this._commandService.executeCommand(e.id,...(i=e.arguments)!==null&&i!==void 0?i:[])}catch(n){this._notificationService.notify({severity:Rx.Error,source:t.provider.displayName,message:n})}}_cacheHintsForFastRestore(e){const t=this._copyInlayHintsWithCurrentAnchor(e);this._inlayHintsCache.set(e,t)}_copyInlayHintsWithCurrentAnchor(e){const t=new Map;for(const[i,n]of this._decorationsMetadata){if(t.has(n.item))continue;const o=e.getDecorationRange(i);if(o){const r=new Pq(o,n.item.anchor.direction),a=n.item.with({anchor:r});t.set(n.item,a)}}return Array.from(t.values())}_getHintsRanges(){const t=this._editor.getModel(),i=this._editor.getVisibleRangesPlusViewportAboveBelow(),n=[];for(const o of i.sort(x.compareRangesUsingStarts)){const r=t.validateRange(new x(o.startLineNumber-30,o.startColumn,o.endLineNumber+30,o.endColumn));n.length===0||!x.areIntersectingOrTouching(n[n.length-1],r)?n.push(r):n[n.length-1]=x.plusRange(n[n.length-1],r)}return n}_updateHintsDecorators(e,t){var i,n;const o=[],r=(_,v,b,C,w)=>{const y={content:b,inlineClassNameAffectsLetterSpacing:!0,inlineClassName:v.className,cursorStops:C,attachedData:w};o.push({item:_,classNameRef:v,decoration:{range:_.anchor.range,options:{description:"InlayHint",showIfCollapsed:_.anchor.range.isEmpty(),collapseOnReplaceEdit:!_.anchor.range.isEmpty(),stickiness:0,[_.anchor.direction]:this._activeRenderMode===0?y:void 0}}})},a=(_,v)=>{const b=this._ruleFactory.createClassNameRef({width:`${l/3|0}px`,display:"inline-block"});r(_,b," ",v?aa.Right:aa.None)},{fontSize:l,fontFamily:d,padding:c,isUniform:u}=this._getLayoutInfo(),h="--code-editorInlayHintsFontFamily";this._editor.getContainerDomNode().style.setProperty(h,d);let g={line:0,totalLen:0};for(const _ of t){if(g.line!==_.anchor.range.startLineNumber&&(g={line:_.anchor.range.startLineNumber,totalLen:0}),g.totalLen>Kp._MAX_LABEL_LEN)continue;_.hint.paddingLeft&&a(_,!1);const v=typeof _.hint.label=="string"?[{label:_.hint.label}]:_.hint.label;for(let b=0;b0&&(L=L.slice(0,-I)+"…",k=!0),r(_,this._ruleFactory.createClassNameRef(D),LEe(L),y&&!_.hint.paddingRight?aa.Right:aa.None,new eR(_,b)),k)break}if(_.hint.paddingRight&&a(_,!0),o.length>Kp._MAX_DECORATORS)break}const f=[];for(const[_,v]of this._decorationsMetadata){const b=(n=this._editor.getModel())===null||n===void 0?void 0:n.getDecorationRange(_);b&&e.some(C=>C.containsRange(b))&&(f.push(_),v.classNameRef.dispose(),this._decorationsMetadata.delete(_))}const m=cl.capture(this._editor);this._editor.changeDecorations(_=>{const v=_.deltaDecorations(f,o.map(b=>b.decoration));for(let b=0;bi)&&(o=i);const r=e.fontFamily||n;return{fontSize:o,fontFamily:r,padding:t,isUniform:!t&&r===n&&o===i}}_removeAllDecorations(){this._editor.removeDecorations(Array.from(this._decorationsMetadata.keys()));for(const e of this._decorationsMetadata.values())e.classNameRef.dispose();this._decorationsMetadata.clear()}};jh.ID="editor.contrib.InlayHints";jh._MAX_DECORATORS=1500;jh._MAX_LABEL_LEN=43;jh=Kp=SEe([Fp(1,Ce),Fp(2,Ur),Fp(3,Xq),Fp(4,gi),Fp(5,en),Fp(6,Ne)],jh);function LEe(s){return s.replace(/[ \t]/g," ")}pt.registerCommand("_executeInlayHintProvider",async(s,...e)=>{const[t,i]=e;yt(Ae.isUri(t)),yt(x.isIRange(i));const{inlayHintsProvider:n}=s.get(Ce),o=await s.get(mo).createModelReference(t);try{const r=await gf.create(n,o.object.textEditorModel,[x.lift(i)],dt.None),a=r.items.map(l=>l.hint);return setTimeout(()=>r.dispose(),0),a}finally{o.dispose()}});var xEe=function(s,e,t,i){var n=arguments.length,o=n<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,r;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(s,e,t,i);else for(var a=s.length-1;a>=0;a--)(r=s[a])&&(o=(n<3?r(o):n>3?r(e,t,o):r(e,t))||o);return n>3&&o&&Object.defineProperty(e,t,o),o},Dg=function(s,e){return function(t,i){e(t,i,s)}};class G7 extends hf{constructor(e,t,i,n){super(10,t,e.item.anchor.range,i,n,!0),this.part=e}}let pL=class extends RC{constructor(e,t,i,n,o,r,a,l){super(e,t,i,r,l,n,o),this._resolverService=a,this.hoverOrdinal=6}suggestHoverAnchor(e){var t;if(!jh.get(this._editor)||e.target.type!==6)return null;const n=(t=e.target.detail.injectedText)===null||t===void 0?void 0:t.options;return n instanceof Ph&&n.attachedData instanceof eR?new G7(n.attachedData,this,e.event.posx,e.event.posy):null}computeSync(){return[]}computeAsync(e,t,i){return e instanceof G7?new Xi(async n=>{const{part:o}=e;if(await o.item.resolve(i),i.isCancellationRequested)return;let r;typeof o.item.hint.tooltip=="string"?r=new ss().appendText(o.item.hint.tooltip):o.item.hint.tooltip&&(r=o.item.hint.tooltip),r&&n.emitOne(new Ka(this,e.range,[r],!1,0)),rs(o.item.hint.textEdits)&&n.emitOne(new Ka(this,e.range,[new ss().appendText(p("hint.dbl","Double-click to insert"))],!1,10001));let a;if(typeof o.part.tooltip=="string"?a=new ss().appendText(o.part.tooltip):o.part.tooltip&&(a=o.part.tooltip),a&&n.emitOne(new Ka(this,e.range,[a],!1,1)),o.part.location||o.part.command){let d;const u=this._editor.getOption(78)==="altKey"?lt?p("links.navigate.kb.meta.mac","cmd + click"):p("links.navigate.kb.meta","ctrl + click"):lt?p("links.navigate.kb.alt.mac","option + click"):p("links.navigate.kb.alt","alt + click");o.part.location&&o.part.command?d=new ss().appendText(p("hint.defAndCommand","Go to Definition ({0}), right click for more",u)):o.part.location?d=new ss().appendText(p("hint.def","Go to Definition ({0})",u)):o.part.command&&(d=new ss(`[${p("hint.cmd","Execute Command")}](${eEe(o.part.command)} "${o.part.command.title}") (${u})`,{isTrusted:!0})),d&&n.emitOne(new Ka(this,e.range,[d],!1,1e4))}const l=await this._resolveInlayHintLabelPartHover(o,i);for await(const d of l)n.emitOne(d)}):Xi.EMPTY}async _resolveInlayHintLabelPartHover(e,t){if(!e.part.location)return Xi.EMPTY;const{uri:i,range:n}=e.part.location,o=await this._resolverService.createModelReference(i);try{const r=o.object.textEditorModel;return this._languageFeaturesService.hoverProvider.has(r)?w4(this._languageFeaturesService.hoverProvider,r,new W(n.startLineNumber,n.startColumn),t).filter(a=>!L_(a.hover.contents)).map(a=>new Ka(this,e.item.anchor.range,a.hover.contents,!1,2+a.ordinal)):Xi.EMPTY}finally{o.dispose()}}};pL=xEe([Dg(1,vi),Dg(2,Bo),Dg(3,At),Dg(4,Md),Dg(5,rt),Dg(6,mo),Dg(7,Ce)],pL);class mL{get anchor(){return this._anchor}set anchor(e){this._anchor=e}get shouldFocus(){return this._shouldFocus}set shouldFocus(e){this._shouldFocus=e}get source(){return this._source}set source(e){this._source=e}get insistOnKeepingHoverVisible(){return this._insistOnKeepingHoverVisible}set insistOnKeepingHoverVisible(e){this._insistOnKeepingHoverVisible=e}constructor(e,t){this._editor=e,this._participants=t,this._anchor=null,this._shouldFocus=!1,this._source=0,this._insistOnKeepingHoverVisible=!1}static _getLineDecorations(e,t){if(t.type!==1&&!t.supportsMarkerHover)return[];const i=e.getModel(),n=t.range.startLineNumber;if(n>i.getLineCount())return[];const o=i.getLineMaxColumn(n);return e.getLineDecorations(n).filter(r=>{if(r.options.isWholeLine)return!0;const a=r.range.startLineNumber===n?r.range.startColumn:1,l=r.range.endLineNumber===n?r.range.endColumn:o;if(r.options.showIfCollapsed){if(a>t.range.startColumn+1||t.range.endColumn-1>l)return!1}else if(a>t.range.startColumn||t.range.endColumn>l)return!1;return!0})}computeAsync(e){const t=this._anchor;if(!this._editor.hasModel()||!t)return Xi.EMPTY;const i=mL._getLineDecorations(this._editor,t);return Xi.merge(this._participants.map(n=>n.computeAsync?n.computeAsync(t,i,e):Xi.EMPTY))}computeSync(){if(!this._editor.hasModel()||!this._anchor)return[];const e=mL._getLineDecorations(this._editor,this._anchor);let t=[];for(const i of this._participants)t=t.concat(i.computeSync(this._anchor,e));return pd(t)}}class Yq{constructor(e,t,i){this.anchor=e,this.messages=t,this.isComplete=i}filter(e){const t=this.messages.filter(i=>i.isValidForHoverAnchor(e));return t.length===this.messages.length?this:new kEe(this,this.anchor,t,this.isComplete)}}class kEe extends Yq{constructor(e,t,i,n){super(t,i,n),this.original=e}filter(e){return this.original.filter(e)}}class EEe{constructor(e,t,i,n,o,r,a,l,d,c){this.initialMousePosX=e,this.initialMousePosY=t,this.colorPicker=i,this.showAtPosition=n,this.showAtSecondaryPosition=o,this.preferAbove=r,this.stoleFocus=a,this.source=l,this.isBeforeContent=d,this.disposables=c,this.closestMouseDistance=void 0}}var IEe=function(s,e,t,i){var n=arguments.length,o=n<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,r;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(s,e,t,i);else for(var a=s.length-1;a>=0;a--)(r=s[a])&&(o=(n<3?r(o):n>3?r(e,t,o):r(e,t))||o);return n>3&&o&&Object.defineProperty(e,t,o),o},TEe=function(s,e){return function(t,i){e(t,i,s)}};const Z7=he;let _L=class extends H{get hasContent(){return this._hasContent}constructor(e){super(),this._keybindingService=e,this._hasContent=!1,this.hoverElement=Z7("div.hover-row.status-bar"),this.hoverElement.tabIndex=0,this.actionsElement=Q(this.hoverElement,Z7("div.actions"))}addAction(e){const t=this._keybindingService.lookupKeybinding(e.commandId),i=t?t.getLabel():null;return this._hasContent=!0,this._register(Fx.render(this.actionsElement,e,i))}append(e){const t=Q(this.actionsElement,e);return this._hasContent=!0,t}};_L=IEe([TEe(0,At)],_L);var NEe=function(s,e,t,i){var n=arguments.length,o=n<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,r;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(s,e,t,i);else for(var a=s.length-1;a>=0;a--)(r=s[a])&&(o=(n<3?r(o):n>3?r(e,t,o):r(e,t))||o);return n>3&&o&&Object.defineProperty(e,t,o),o},X7=function(s,e){return function(t,i){e(t,i,s)}},hS;let vL=hS=class extends H{constructor(e,t,i){super(),this._editor=e,this._instantiationService=t,this._keybindingService=i,this._currentResult=null,this._widget=this._register(this._instantiationService.createInstance(H_,this._editor)),this._participants=[];for(const n of ag.getAll()){const o=this._instantiationService.createInstance(n,this._editor);o instanceof RC&&!(o instanceof pL)&&(this._markdownHoverParticipant=o),this._participants.push(o)}this._participants.sort((n,o)=>n.hoverOrdinal-o.hoverOrdinal),this._computer=new mL(this._editor,this._participants),this._hoverOperation=this._register(new Aq(this._editor,this._computer)),this._register(this._hoverOperation.onResult(n=>{if(!this._computer.anchor)return;const o=n.hasLoadingMessage?this._addLoadingMessage(n.value):n.value;this._withResult(new Yq(this._computer.anchor,o,n.isComplete))})),this._register(Ni(this._widget.getDomNode(),"keydown",n=>{n.equals(9)&&this.hide()})),this._register(Ki.onDidChange(()=>{this._widget.position&&this._currentResult&&this._setCurrentResult(this._currentResult)}))}_startShowingOrUpdateHover(e,t,i,n,o){return!this._widget.position||!this._currentResult?e?(this._startHoverOperationIfNecessary(e,t,i,n,!1),!0):!1:this._editor.getOption(60).sticky&&o&&this._widget.isMouseGettingCloser(o.event.posx,o.event.posy)?(e&&this._startHoverOperationIfNecessary(e,t,i,n,!0),!0):e?e&&this._currentResult.anchor.equals(e)?!0:e.canAdoptVisibleHover(this._currentResult.anchor,this._widget.position)?(this._setCurrentResult(this._currentResult.filter(e)),this._startHoverOperationIfNecessary(e,t,i,n,!1),!0):(this._setCurrentResult(null),this._startHoverOperationIfNecessary(e,t,i,n,!1),!0):(this._setCurrentResult(null),!1)}_startHoverOperationIfNecessary(e,t,i,n,o){this._computer.anchor&&this._computer.anchor.equals(e)||(this._hoverOperation.cancel(),this._computer.anchor=e,this._computer.shouldFocus=n,this._computer.source=i,this._computer.insistOnKeepingHoverVisible=o,this._hoverOperation.start(t))}_setCurrentResult(e){this._currentResult!==e&&(e&&e.messages.length===0&&(e=null),this._currentResult=e,this._currentResult?this._renderMessages(this._currentResult.anchor,this._currentResult.messages):this._widget.hide())}_addLoadingMessage(e){if(this._computer.anchor){for(const t of this._participants)if(t.createLoadingMessage){const i=t.createLoadingMessage(this._computer.anchor);if(i)return e.slice(0).concat([i])}}return e}_withResult(e){this._widget.position&&this._currentResult&&this._currentResult.isComplete&&(!e.isComplete||this._computer.insistOnKeepingHoverVisible&&e.messages.length===0)||this._setCurrentResult(e)}_renderMessages(e,t){const{showAtPosition:i,showAtSecondaryPosition:n,highlightRange:o}=hS.computeHoverRanges(this._editor,e.range,t),r=new Y,a=r.add(new _L(this._keybindingService)),l=document.createDocumentFragment();let d=null;const c={fragment:l,statusBar:a,setColorPicker:h=>d=h,onContentsChanged:()=>this._widget.onContentsChanged(),setMinimumDimensions:h=>this._widget.setMinimumDimensions(h),hide:()=>this.hide()};for(const h of this._participants){const g=t.filter(f=>f.owner===h);g.length>0&&r.add(h.renderHoverParts(c,g))}const u=t.some(h=>h.isBeforeContent);if(a.hasContent&&l.appendChild(a.hoverElement),l.hasChildNodes()){if(o){const h=this._editor.createDecorationsCollection();h.set([{range:o,options:hS._DECORATION_OPTIONS}]),r.add(Ie(()=>{h.clear()}))}this._widget.showAt(l,new EEe(e.initialMousePosX,e.initialMousePosY,d,i,n,this._editor.getOption(60).above,this._computer.shouldFocus,this._computer.source,u,r))}else r.dispose()}static computeHoverRanges(e,t,i){let n=1;if(e.hasModel()){const u=e._getViewModel(),h=u.coordinatesConverter,g=h.convertModelRangeToViewRange(t),f=new W(g.startLineNumber,u.getLineMinColumn(g.startLineNumber));n=h.convertViewPositionToModelPosition(f).column}const o=t.startLineNumber;let r=t.startColumn,a=i[0].range,l=null;for(const u of i)a=x.plusRange(a,u.range),u.range.startLineNumber===o&&u.range.endLineNumber===o&&(r=Math.max(Math.min(r,u.range.startColumn),n)),u.forceShowAtRange&&(l=u.range);const d=l?l.getStartPosition():new W(o,t.startColumn),c=l?l.getStartPosition():new W(o,r);return{showAtPosition:d,showAtSecondaryPosition:c,highlightRange:a}}showsOrWillShow(e){if(this._widget.isResizing)return!0;const t=[];for(const n of this._participants)if(n.suggestHoverAnchor){const o=n.suggestHoverAnchor(e);o&&t.push(o)}const i=e.target;if(i.type===6&&t.push(new lT(0,i.range,e.event.posx,e.event.posy)),i.type===7){const n=this._editor.getOption(50).typicalHalfwidthCharacterWidth/2;!i.detail.isAfterLines&&typeof i.detail.horizontalDistanceToText=="number"&&i.detail.horizontalDistanceToTexto.priority-n.priority),this._startShowingOrUpdateHover(t[0],0,0,!1,e))}startShowingAtRange(e,t,i,n){this._startShowingOrUpdateHover(new lT(0,e,void 0,void 0),t,i,n,null)}async updateFocusedMarkdownHoverVerbosityLevel(e){var t;(t=this._markdownHoverParticipant)===null||t===void 0||t.updateFocusedMarkdownHoverPartVerbosityLevel(e)}containsNode(e){return e?this._widget.getDomNode().contains(e):!1}focus(){this._widget.focus()}scrollUp(){this._widget.scrollUp()}scrollDown(){this._widget.scrollDown()}scrollLeft(){this._widget.scrollLeft()}scrollRight(){this._widget.scrollRight()}pageUp(){this._widget.pageUp()}pageDown(){this._widget.pageDown()}goToTop(){this._widget.goToTop()}goToBottom(){this._widget.goToBottom()}hide(){this._computer.anchor=null,this._hoverOperation.cancel(),this._setCurrentResult(null)}get isColorPickerVisible(){return this._widget.isColorPickerVisible}get isVisibleFromKeyboard(){return this._widget.isVisibleFromKeyboard}get isVisible(){return this._widget.isVisible}get isFocused(){return this._widget.isFocused}get isResizing(){return this._widget.isResizing}get widget(){return this._widget}};vL._DECORATION_OPTIONS=Ye.register({description:"content-hover-highlight",className:"hoverHighlight"});vL=hS=NEe([X7(1,Ne),X7(2,At)],vL);class AEe{get lineNumber(){return this._lineNumber}set lineNumber(e){this._lineNumber=e}get lane(){return this._laneOrLine}set lane(e){this._laneOrLine=e}constructor(e){this._editor=e,this._lineNumber=-1,this._laneOrLine=bd.Center}computeSync(){var e,t;const i=a=>({value:a}),n=this._editor.getLineDecorations(this._lineNumber),o=[],r=this._laneOrLine==="lineNo";if(!n)return o;for(const a of n){const l=(t=(e=a.options.glyphMargin)===null||e===void 0?void 0:e.position)!==null&&t!==void 0?t:bd.Center;if(!r&&l!==this._laneOrLine)continue;const d=r?a.options.lineNumberHoverMessage:a.options.glyphMarginHoverMessage;!d||L_(d)||o.push(...OP(d).map(i))}return o}}const Y7=he;class BC extends H{constructor(e,t,i){super(),this._renderDisposeables=this._register(new Y),this._editor=e,this._isVisible=!1,this._messages=[],this._hover=this._register(new gO),this._hover.containerDomNode.classList.toggle("hidden",!this._isVisible),this._markdownRenderer=this._register(new yd({editor:this._editor},t,i)),this._computer=new AEe(this._editor),this._hoverOperation=this._register(new Aq(this._editor,this._computer)),this._register(this._hoverOperation.onResult(n=>{this._withResult(n.value)})),this._register(this._editor.onDidChangeModelDecorations(()=>this._onModelDecorationsChanged())),this._register(this._editor.onDidChangeConfiguration(n=>{n.hasChanged(50)&&this._updateFont()})),this._editor.addOverlayWidget(this)}dispose(){this._editor.removeOverlayWidget(this),super.dispose()}getId(){return BC.ID}getDomNode(){return this._hover.containerDomNode}getPosition(){return null}_updateFont(){Array.prototype.slice.call(this._hover.contentsDomNode.getElementsByClassName("code")).forEach(t=>this._editor.applyFontInfo(t))}_onModelDecorationsChanged(){this._isVisible&&(this._hoverOperation.cancel(),this._hoverOperation.start(0))}showsOrWillShow(e){const t=e.target;return t.type===2&&t.detail.glyphMarginLane?(this._startShowingAt(t.position.lineNumber,t.detail.glyphMarginLane),!0):t.type===3?(this._startShowingAt(t.position.lineNumber,"lineNo"),!0):!1}_startShowingAt(e,t){this._computer.lineNumber===e&&this._computer.lane===t||(this._hoverOperation.cancel(),this.hide(),this._computer.lineNumber=e,this._computer.lane=t,this._hoverOperation.start(0))}hide(){this._computer.lineNumber=-1,this._hoverOperation.cancel(),this._isVisible&&(this._isVisible=!1,this._hover.containerDomNode.classList.toggle("hidden",!this._isVisible))}_withResult(e){this._messages=e,this._messages.length>0?this._renderMessages(this._computer.lineNumber,this._messages):this.hide()}_renderMessages(e,t){this._renderDisposeables.clear();const i=document.createDocumentFragment();for(const n of t){const o=Y7("div.hover-row.markdown-hover"),r=Q(o,Y7("div.hover-contents")),a=this._renderDisposeables.add(this._markdownRenderer.render(n.value));r.appendChild(a.element),i.appendChild(o)}this._updateContents(i),this._showAt(e)}_updateContents(e){this._hover.contentsDomNode.textContent="",this._hover.contentsDomNode.appendChild(e),this._updateFont()}_showAt(e){this._isVisible||(this._isVisible=!0,this._hover.containerDomNode.classList.toggle("hidden",!this._isVisible));const t=this._editor.getLayoutInfo(),i=this._editor.getTopForLineNumber(e),n=this._editor.getScrollTop(),o=this._editor.getOption(67),r=this._hover.containerDomNode.clientHeight,a=i-n-(r-o)/2,l=t.glyphMarginLeft+t.glyphMarginWidth+(this._computer.lane==="lineNo"?t.lineNumbersWidth:0);this._hover.containerDomNode.style.left=`${l}px`,this._hover.containerDomNode.style.top=`${Math.max(Math.round(a),0)}px`}}BC.ID="editor.contrib.modesGlyphHoverWidget";var MEe=function(s,e,t,i){var n=arguments.length,o=n<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,r;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(s,e,t,i);else for(var a=s.length-1;a>=0;a--)(r=s[a])&&(o=(n<3?r(o):n>3?r(e,t,o):r(e,t))||o);return n>3&&o&&Object.defineProperty(e,t,o),o},Q7=function(s,e){return function(t,i){e(t,i,s)}},tR;let ws=tR=class extends H{constructor(e,t,i){super(),this._editor=e,this._instantiationService=t,this._keybindingService=i,this._listenersStore=new Y,this._hoverState={mouseDown:!1,activatedByDecoratorClick:!1},this._reactToEditorMouseMoveRunner=this._register(new Wt(()=>this._reactToEditorMouseMove(this._mouseMoveEvent),0)),this._hookListeners(),this._register(this._editor.onDidChangeConfiguration(n=>{n.hasChanged(60)&&(this._unhookListeners(),this._hookListeners())}))}static get(e){return e.getContribution(tR.ID)}_hookListeners(){const e=this._editor.getOption(60);this._hoverSettings={enabled:e.enabled,sticky:e.sticky,hidingDelay:e.delay},e.enabled?(this._listenersStore.add(this._editor.onMouseDown(t=>this._onEditorMouseDown(t))),this._listenersStore.add(this._editor.onMouseUp(()=>this._onEditorMouseUp())),this._listenersStore.add(this._editor.onMouseMove(t=>this._onEditorMouseMove(t))),this._listenersStore.add(this._editor.onKeyDown(t=>this._onKeyDown(t)))):(this._listenersStore.add(this._editor.onMouseMove(t=>this._onEditorMouseMove(t))),this._listenersStore.add(this._editor.onKeyDown(t=>this._onKeyDown(t)))),this._listenersStore.add(this._editor.onMouseLeave(t=>this._onEditorMouseLeave(t))),this._listenersStore.add(this._editor.onDidChangeModel(()=>{this._cancelScheduler(),this._hideWidgets()})),this._listenersStore.add(this._editor.onDidChangeModelContent(()=>this._cancelScheduler())),this._listenersStore.add(this._editor.onDidScrollChange(t=>this._onEditorScrollChanged(t)))}_unhookListeners(){this._listenersStore.clear()}_cancelScheduler(){this._mouseMoveEvent=void 0,this._reactToEditorMouseMoveRunner.cancel()}_onEditorScrollChanged(e){(e.scrollTopChanged||e.scrollLeftChanged)&&this._hideWidgets()}_onEditorMouseDown(e){this._hoverState.mouseDown=!0,!this._shouldNotHideCurrentHoverWidget(e)&&this._hideWidgets()}_shouldNotHideCurrentHoverWidget(e){return!!(this._isMouseOnContentHoverWidget(e)||this._isMouseOnMarginHoverWidget(e)||this._isContentWidgetResizing())}_isMouseOnMarginHoverWidget(e){const t=e.target;return t?t.type===12&&t.detail===BC.ID:!1}_isMouseOnContentHoverWidget(e){const t=e.target;return t?t.type===9&&t.detail===H_.ID:!1}_onEditorMouseUp(){this._hoverState.mouseDown=!1}_onEditorMouseLeave(e){this._cancelScheduler(),!this._shouldNotHideCurrentHoverWidget(e)&&this._hideWidgets()}_shouldNotRecomputeCurrentHoverWidget(e){const t=this._hoverSettings.sticky,i=(a,l)=>{const d=this._isMouseOnMarginHoverWidget(a);return l&&d},n=(a,l)=>{const d=this._isMouseOnContentHoverWidget(a);return l&&d},o=a=>{var l;const d=this._isMouseOnContentHoverWidget(a),c=(l=this._contentWidget)===null||l===void 0?void 0:l.isColorPickerVisible;return d&&c},r=(a,l)=>{var d,c,u,h;return l&&((d=this._contentWidget)===null||d===void 0?void 0:d.containsNode((c=a.event.browserEvent.view)===null||c===void 0?void 0:c.document.activeElement))&&!(!((h=(u=a.event.browserEvent.view)===null||u===void 0?void 0:u.getSelection())===null||h===void 0)&&h.isCollapsed)};return!!(i(e,t)||n(e,t)||o(e)||r(e,t))}_onEditorMouseMove(e){var t,i,n,o;if(this._mouseMoveEvent=e,!((t=this._contentWidget)===null||t===void 0)&&t.isFocused||!((i=this._contentWidget)===null||i===void 0)&&i.isResizing)return;const r=this._hoverSettings.sticky;if(r&&(!((n=this._contentWidget)===null||n===void 0)&&n.isVisibleFromKeyboard))return;if(this._shouldNotRecomputeCurrentHoverWidget(e)){this._reactToEditorMouseMoveRunner.cancel();return}const l=this._hoverSettings.hidingDelay;if(((o=this._contentWidget)===null||o===void 0?void 0:o.isVisible)&&r&&l>0){this._reactToEditorMouseMoveRunner.isScheduled()||this._reactToEditorMouseMoveRunner.schedule(l);return}this._reactToEditorMouseMove(e)}_reactToEditorMouseMove(e){var t;if(!e)return;const n=(t=e.target.element)===null||t===void 0?void 0:t.classList.contains("colorpicker-color-decoration"),o=this._editor.getOption(148),r=this._hoverSettings.enabled,a=this._hoverState.activatedByDecoratorClick;if(n&&(o==="click"&&!a||o==="hover"&&!r||o==="clickAndHover"&&!r&&!a)||!n&&!r&&!a){this._hideWidgets();return}this._tryShowHoverWidget(e,0)||this._tryShowHoverWidget(e,1)||this._hideWidgets()}_tryShowHoverWidget(e,t){const i=this._getOrCreateContentWidget(),n=this._getOrCreateGlyphWidget();let o,r;switch(t){case 0:o=i,r=n;break;case 1:o=n,r=i;break;default:throw new Error(`HoverWidgetType ${t} is unrecognized`)}const a=o.showsOrWillShow(e);return a&&r.hide(),a}_onKeyDown(e){var t;if(!this._editor.hasModel())return;const i=this._keybindingService.softDispatch(e,this._editor.getDomNode()),n=i.kind===1||i.kind===2&&(i.commandId===Eq||i.commandId===_4||i.commandId===v4)&&((t=this._contentWidget)===null||t===void 0?void 0:t.isVisible);e.keyCode===5||e.keyCode===6||e.keyCode===57||e.keyCode===4||n||this._hideWidgets()}_hideWidgets(){var e,t,i;this._hoverState.mouseDown&&(!((e=this._contentWidget)===null||e===void 0)&&e.isColorPickerVisible)||zh.dropDownVisible||(this._hoverState.activatedByDecoratorClick=!1,(t=this._glyphWidget)===null||t===void 0||t.hide(),(i=this._contentWidget)===null||i===void 0||i.hide())}_getOrCreateContentWidget(){return this._contentWidget||(this._contentWidget=this._instantiationService.createInstance(vL,this._editor)),this._contentWidget}_getOrCreateGlyphWidget(){return this._glyphWidget||(this._glyphWidget=this._instantiationService.createInstance(BC,this._editor)),this._glyphWidget}showContentHover(e,t,i,n,o=!1){this._hoverState.activatedByDecoratorClick=o,this._getOrCreateContentWidget().startShowingAtRange(e,t,i,n)}_isContentWidgetResizing(){var e;return((e=this._contentWidget)===null||e===void 0?void 0:e.widget.isResizing)||!1}updateFocusedMarkdownHoverVerbosityLevel(e){this._getOrCreateContentWidget().updateFocusedMarkdownHoverVerbosityLevel(e)}focus(){var e;(e=this._contentWidget)===null||e===void 0||e.focus()}scrollUp(){var e;(e=this._contentWidget)===null||e===void 0||e.scrollUp()}scrollDown(){var e;(e=this._contentWidget)===null||e===void 0||e.scrollDown()}scrollLeft(){var e;(e=this._contentWidget)===null||e===void 0||e.scrollLeft()}scrollRight(){var e;(e=this._contentWidget)===null||e===void 0||e.scrollRight()}pageUp(){var e;(e=this._contentWidget)===null||e===void 0||e.pageUp()}pageDown(){var e;(e=this._contentWidget)===null||e===void 0||e.pageDown()}goToTop(){var e;(e=this._contentWidget)===null||e===void 0||e.goToTop()}goToBottom(){var e;(e=this._contentWidget)===null||e===void 0||e.goToBottom()}get isColorPickerVisible(){var e;return(e=this._contentWidget)===null||e===void 0?void 0:e.isColorPickerVisible}get isHoverVisible(){var e;return(e=this._contentWidget)===null||e===void 0?void 0:e.isVisible}dispose(){var e,t;super.dispose(),this._unhookListeners(),this._listenersStore.dispose(),(e=this._glyphWidget)===null||e===void 0||e.dispose(),(t=this._contentWidget)===null||t===void 0||t.dispose()}};ws.ID="editor.contrib.hover";ws=tR=MEe([Q7(1,Ne),Q7(2,At)],ws);class iR extends H{constructor(e){super(),this._editor=e,this._register(e.onMouseDown(t=>this.onMouseDown(t)))}dispose(){super.dispose()}onMouseDown(e){const t=this._editor.getOption(148);if(t!=="click"&&t!=="clickAndHover")return;const i=e.target;if(i.type!==6||!i.detail.injectedText||i.detail.injectedText.options.attachedData!==wq||!i.range)return;const n=this._editor.getContribution(ws.ID);if(n&&!n.isColorPickerVisible){const o=new x(i.range.startLineNumber,i.range.startColumn+1,i.range.endLineNumber,i.range.endColumn+1);n.showContentHover(o,1,0,!1,!0)}}}iR.ID="editor.contrib.colorContribution";kt(iR.ID,iR,2);ag.register(hL);var Qq=function(s,e,t,i){var n=arguments.length,o=n<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,r;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(s,e,t,i);else for(var a=s.length-1;a>=0;a--)(r=s[a])&&(o=(n<3?r(o):n>3?r(e,t,o):r(e,t))||o);return n>3&&o&&Object.defineProperty(e,t,o),o},za=function(s,e){return function(t,i){e(t,i,s)}},nR,sR;let Kh=nR=class extends H{constructor(e,t,i,n,o,r,a){super(),this._editor=e,this._modelService=i,this._keybindingService=n,this._instantiationService=o,this._languageFeatureService=r,this._languageConfigurationService=a,this._standaloneColorPickerWidget=null,this._standaloneColorPickerVisible=T.standaloneColorPickerVisible.bindTo(t),this._standaloneColorPickerFocused=T.standaloneColorPickerFocused.bindTo(t)}showOrFocus(){var e;this._editor.hasModel()&&(this._standaloneColorPickerVisible.get()?this._standaloneColorPickerFocused.get()||(e=this._standaloneColorPickerWidget)===null||e===void 0||e.focus():this._standaloneColorPickerWidget=new bL(this._editor,this._standaloneColorPickerVisible,this._standaloneColorPickerFocused,this._instantiationService,this._modelService,this._keybindingService,this._languageFeatureService,this._languageConfigurationService))}hide(){var e;this._standaloneColorPickerFocused.set(!1),this._standaloneColorPickerVisible.set(!1),(e=this._standaloneColorPickerWidget)===null||e===void 0||e.hide(),this._editor.focus()}insertColor(){var e;(e=this._standaloneColorPickerWidget)===null||e===void 0||e.updateEditor(),this.hide()}static get(e){return e.getContribution(nR.ID)}};Kh.ID="editor.contrib.standaloneColorPickerController";Kh=nR=Qq([za(1,Be),za(2,_i),za(3,At),za(4,Ne),za(5,Ce),za(6,Yt)],Kh);kt(Kh.ID,Kh,1);const J7=8,REe=22;let bL=sR=class extends H{constructor(e,t,i,n,o,r,a,l){var d;super(),this._editor=e,this._standaloneColorPickerVisible=t,this._standaloneColorPickerFocused=i,this._modelService=o,this._keybindingService=r,this._languageFeaturesService=a,this._languageConfigurationService=l,this.allowEditorOverflow=!0,this._position=void 0,this._body=document.createElement("div"),this._colorHover=null,this._selectionSetInEditor=!1,this._onResult=this._register(new B),this.onResult=this._onResult.event,this._standaloneColorPickerVisible.set(!0),this._standaloneColorPickerParticipant=n.createInstance(MC,this._editor),this._position=(d=this._editor._getViewModel())===null||d===void 0?void 0:d.getPrimaryCursorState().modelState.position;const c=this._editor.getSelection(),u=c?{startLineNumber:c.startLineNumber,startColumn:c.startColumn,endLineNumber:c.endLineNumber,endColumn:c.endColumn}:{startLineNumber:0,endLineNumber:0,endColumn:0,startColumn:0},h=this._register(ba(this._body));this._register(h.onDidBlur(g=>{this.hide()})),this._register(h.onDidFocus(g=>{this.focus()})),this._register(this._editor.onDidChangeCursorPosition(()=>{this._selectionSetInEditor?this._selectionSetInEditor=!1:this.hide()})),this._register(this._editor.onMouseMove(g=>{var f;const m=(f=g.target.element)===null||f===void 0?void 0:f.classList;m&&m.contains("colorpicker-color-decoration")&&this.hide()})),this._register(this.onResult(g=>{this._render(g.value,g.foundInEditor)})),this._start(u),this._body.style.zIndex="50",this._editor.addContentWidget(this)}updateEditor(){this._colorHover&&this._standaloneColorPickerParticipant.updateEditorModel(this._colorHover)}getId(){return sR.ID}getDomNode(){return this._body}getPosition(){if(!this._position)return null;const e=this._editor.getOption(60).above;return{position:this._position,secondaryPosition:this._position,preference:e?[1,2]:[2,1],positionAffinity:2}}hide(){this.dispose(),this._standaloneColorPickerVisible.set(!1),this._standaloneColorPickerFocused.set(!1),this._editor.removeContentWidget(this),this._editor.focus()}focus(){this._standaloneColorPickerFocused.set(!0),this._body.focus()}async _start(e){const t=await this._computeAsync(e);t&&this._onResult.fire(new PEe(t.result,t.foundInEditor))}async _computeAsync(e){if(!this._editor.hasModel())return null;const t={range:e,color:{red:0,green:0,blue:0,alpha:1}},i=await this._standaloneColorPickerParticipant.createColorHover(t,new p4(this._modelService,this._languageConfigurationService),this._languageFeaturesService.colorProvider);return i?{result:i.colorHover,foundInEditor:i.foundInEditor}:null}_render(e,t){const i=document.createDocumentFragment(),n=this._register(new _L(this._keybindingService));let o;const r={fragment:i,statusBar:n,setColorPicker:m=>o=m,onContentsChanged:()=>{},hide:()=>this.hide()};if(this._colorHover=e,this._register(this._standaloneColorPickerParticipant.renderHoverParts(r,[e])),o===void 0)return;this._body.classList.add("standalone-colorpicker-body"),this._body.style.maxHeight=Math.max(this._editor.getLayoutInfo().height/4,250)+"px",this._body.style.maxWidth=Math.max(this._editor.getLayoutInfo().width*.66,500)+"px",this._body.tabIndex=0,this._body.appendChild(i),o.layout();const a=o.body,l=a.saturationBox.domNode.clientWidth,d=a.domNode.clientWidth-l-REe-J7,c=o.body.enterButton;c==null||c.onClicked(()=>{this.updateEditor(),this.hide()});const u=o.header,h=u.pickedColorNode;h.style.width=l+J7+"px";const g=u.originalColorNode;g.style.width=d+"px";const f=o.header.closeButton;f==null||f.onClicked(()=>{this.hide()}),t&&(c&&(c.button.textContent="Replace"),this._selectionSetInEditor=!0,this._editor.setSelection(e.range)),this._editor.layoutContentWidget(this)}};bL.ID="editor.contrib.standaloneColorPickerWidget";bL=sR=Qq([za(3,Ne),za(4,_i),za(5,At),za(6,Ce),za(7,Yt)],bL);class PEe{constructor(e,t){this.value=e,this.foundInEditor=t}}class FEe extends fl{constructor(){super({id:"editor.action.showOrFocusStandaloneColorPicker",title:{...Ve("showOrFocusStandaloneColorPicker","Show or Focus Standalone Color Picker"),mnemonicTitle:p({},"&&Show or Focus Standalone Color Picker")},precondition:void 0,menu:[{id:E.CommandPalette}],metadata:{description:Ve("showOrFocusStandaloneColorPickerDescription","Show or focus a standalone color picker which uses the default color provider. It displays hex/rgb/hsl colors.")}})}runEditorCommand(e,t){var i;(i=Kh.get(t))===null||i===void 0||i.showOrFocus()}}class OEe extends me{constructor(){super({id:"editor.action.hideColorPicker",label:p({},"Hide the Color Picker"),alias:"Hide the Color Picker",precondition:T.standaloneColorPickerVisible.isEqualTo(!0),kbOpts:{primary:9,weight:100},metadata:{description:Ve("hideColorPickerDescription","Hide the standalone color picker.")}})}run(e,t){var i;(i=Kh.get(t))===null||i===void 0||i.hide()}}class BEe extends me{constructor(){super({id:"editor.action.insertColorWithStandaloneColorPicker",label:p({},"Insert Color with Standalone Color Picker"),alias:"Insert Color with Standalone Color Picker",precondition:T.standaloneColorPickerFocused.isEqualTo(!0),kbOpts:{primary:3,weight:100},metadata:{description:Ve("insertColorWithStandaloneColorPickerDescription","Insert hex/rgb/hsl colors with the focused standalone color picker.")}})}run(e,t){var i;(i=Kh.get(t))===null||i===void 0||i.insertColor()}}te(OEe);te(BEe);qt(FEe);class Qu{constructor(e,t,i){this.languageConfigurationService=i,this._selection=e,this._insertSpace=t,this._usedEndToken=null}static _haystackHasNeedleAtOffset(e,t,i){if(i<0)return!1;const n=t.length,o=e.length;if(i+n>o)return!1;for(let r=0;r=65&&a<=90&&a+32===l)&&!(l>=65&&l<=90&&l+32===a))return!1}return!0}_createOperationsForBlockComment(e,t,i,n,o,r){const a=e.startLineNumber,l=e.startColumn,d=e.endLineNumber,c=e.endColumn,u=o.getLineContent(a),h=o.getLineContent(d);let g=u.lastIndexOf(t,l-1+t.length),f=h.indexOf(i,c-1-i.length);if(g!==-1&&f!==-1)if(a===d)u.substring(g+t.length,f).indexOf(i)>=0&&(g=-1,f=-1);else{const _=u.substring(g+t.length),v=h.substring(0,f);(_.indexOf(i)>=0||v.indexOf(i)>=0)&&(g=-1,f=-1)}let m;g!==-1&&f!==-1?(n&&g+t.length0&&h.charCodeAt(f-1)===32&&(i=" "+i,f-=1),m=Qu._createRemoveBlockCommentOperations(new x(a,g+t.length+1,d,f+1),t,i)):(m=Qu._createAddBlockCommentOperations(e,t,i,this._insertSpace),this._usedEndToken=m.length===1?i:null);for(const _ of m)r.addTrackedEditOperation(_.range,_.text)}static _createRemoveBlockCommentOperations(e,t,i){const n=[];return x.isEmpty(e)?n.push(pi.delete(new x(e.startLineNumber,e.startColumn-t.length,e.endLineNumber,e.endColumn+i.length))):(n.push(pi.delete(new x(e.startLineNumber,e.startColumn-t.length,e.startLineNumber,e.startColumn))),n.push(pi.delete(new x(e.endLineNumber,e.endColumn,e.endLineNumber,e.endColumn+i.length)))),n}static _createAddBlockCommentOperations(e,t,i,n){const o=[];return x.isEmpty(e)?o.push(pi.replace(new x(e.startLineNumber,e.startColumn,e.endLineNumber,e.endColumn),t+" "+i)):(o.push(pi.insert(new W(e.startLineNumber,e.startColumn),t+(n?" ":""))),o.push(pi.insert(new W(e.endLineNumber,e.endColumn),(n?" ":"")+i))),o}getEditOperations(e,t){const i=this._selection.startLineNumber,n=this._selection.startColumn;e.tokenization.tokenizeIfCheap(i);const o=e.getLanguageIdAtPosition(i,n),r=this.languageConfigurationService.getLanguageConfiguration(o).comments;!r||!r.blockCommentStartToken||!r.blockCommentEndToken||this._createOperationsForBlockComment(this._selection,r.blockCommentStartToken,r.blockCommentEndToken,this._insertSpace,e,t)}computeCursorState(e,t){const i=t.getInverseEditOperations();if(i.length===2){const n=i[0],o=i[1];return new we(n.range.endLineNumber,n.range.endColumn,o.range.startLineNumber,o.range.startColumn)}else{const n=i[0].range,o=this._usedEndToken?-this._usedEndToken.length-1:0;return new we(n.endLineNumber,n.endColumn+o,n.endLineNumber,n.endColumn+o)}}}class Qd{constructor(e,t,i,n,o,r,a){this.languageConfigurationService=e,this._selection=t,this._indentSize=i,this._type=n,this._insertSpace=o,this._selectionId=null,this._deltaColumn=0,this._moveEndPositionDown=!1,this._ignoreEmptyLines=r,this._ignoreFirstLine=a||!1}static _gatherPreflightCommentStrings(e,t,i,n){e.tokenization.tokenizeIfCheap(t);const o=e.getLanguageIdAtPosition(t,1),r=n.getLanguageConfiguration(o).comments,a=r?r.lineCommentToken:null;if(!a)return null;const l=[];for(let d=0,c=i-t+1;do?t[l].commentStrOffset=r-1:t[l].commentStrOffset=r}}}class D4 extends me{constructor(e,t){super(t),this._type=e}run(e,t){const i=e.get(Yt);if(!t.hasModel())return;const n=t.getModel(),o=[],r=n.getOptions(),a=t.getOption(23),l=t.getSelections().map((c,u)=>({selection:c,index:u,ignoreFirstLine:!1}));l.sort((c,u)=>x.compareRangesUsingStarts(c.selection,u.selection));let d=l[0];for(let c=1;c=0;a--)(r=s[a])&&(o=(n<3?r(o):n>3?r(e,t,o):r(e,t))||o);return n>3&&o&&Object.defineProperty(e,t,o),o},Lg=function(s,e){return function(t,i){e(t,i,s)}},oR;let U_=oR=class{static get(e){return e.getContribution(oR.ID)}constructor(e,t,i,n,o,r,a,l){this._contextMenuService=t,this._contextViewService=i,this._contextKeyService=n,this._keybindingService=o,this._menuService=r,this._configurationService=a,this._workspaceContextService=l,this._toDispose=new Y,this._contextMenuIsBeingShownCount=0,this._editor=e,this._toDispose.add(this._editor.onContextMenu(d=>this._onContextMenu(d))),this._toDispose.add(this._editor.onMouseWheel(d=>{if(this._contextMenuIsBeingShownCount>0){const c=this._contextViewService.getContextViewElement(),u=d.srcElement;u.shadowRoot&&Sf(c)===u.shadowRoot||this._contextViewService.hideContextView()}})),this._toDispose.add(this._editor.onKeyDown(d=>{this._editor.getOption(24)&&d.keyCode===58&&(d.preventDefault(),d.stopPropagation(),this.showContextMenu())}))}_onContextMenu(e){if(!this._editor.hasModel())return;if(!this._editor.getOption(24)){this._editor.focus(),e.target.position&&!this._editor.getSelection().containsPosition(e.target.position)&&this._editor.setPosition(e.target.position);return}if(e.target.type===12||e.target.type===6&&e.target.detail.injectedText)return;if(e.event.preventDefault(),e.event.stopPropagation(),e.target.type===11)return this._showScrollbarContextMenu(e.event);if(e.target.type!==6&&e.target.type!==7&&e.target.type!==1)return;if(this._editor.focus(),e.target.position){let i=!1;for(const n of this._editor.getSelections())if(n.containsPosition(e.target.position)){i=!0;break}i||this._editor.setPosition(e.target.position)}let t=null;e.target.type!==1&&(t=e.event),this.showContextMenu(t)}showContextMenu(e){if(!this._editor.getOption(24)||!this._editor.hasModel())return;const t=this._getMenuActions(this._editor.getModel(),this._editor.contextMenuId);t.length>0&&this._doShowContextMenu(t,e)}_getMenuActions(e,t){const i=[],n=this._menuService.createMenu(t,this._contextKeyService),o=n.getActions({arg:e.uri});n.dispose();for(const r of o){const[,a]=r;let l=0;for(const d of a)if(d instanceof Em){const c=this._getMenuActions(e,d.item.submenu);c.length>0&&(i.push(new c_(d.id,d.label,c)),l++)}else i.push(d),l++;l&&i.push(new rn)}return i.length&&i.pop(),i}_doShowContextMenu(e,t=null){if(!this._editor.hasModel())return;const i=this._editor.getOption(60);this._editor.updateOptions({hover:{enabled:!1}});let n=t;if(!n){this._editor.revealPosition(this._editor.getPosition(),1),this._editor.render();const r=this._editor.getScrolledVisiblePosition(this._editor.getPosition()),a=qi(this._editor.getDomNode()),l=a.left+r.left,d=a.top+r.top+r.height;n={x:l,y:d}}const o=this._editor.getOption(127)&&!_d;this._contextMenuIsBeingShownCount++,this._contextMenuService.showContextMenu({domForShadowRoot:o?this._editor.getDomNode():void 0,getAnchor:()=>n,getActions:()=>e,getActionViewItem:r=>{const a=this._keybindingFor(r);if(a)return new N_(r,r,{label:!0,keybinding:a.getLabel(),isMenu:!0});const l=r;return typeof l.getActionViewItem=="function"?l.getActionViewItem():new N_(r,r,{icon:!0,label:!0,isMenu:!0})},getKeyBinding:r=>this._keybindingFor(r),onHide:r=>{this._contextMenuIsBeingShownCount--,this._editor.updateOptions({hover:i})}})}_showScrollbarContextMenu(e){if(!this._editor.hasModel()||Fbe(this._workspaceContextService.getWorkspace()))return;const t=this._editor.getOption(73);let i=0;const n=d=>({id:`menu-action-${++i}`,label:d.label,tooltip:"",class:void 0,enabled:typeof d.enabled>"u"?!0:d.enabled,checked:d.checked,run:d.run}),o=(d,c)=>new c_(`menu-action-${++i}`,d,c,void 0),r=(d,c,u,h,g)=>{if(!c)return n({label:d,enabled:c,run:()=>{}});const f=_=>()=>{this._configurationService.updateValue(u,_)},m=[];for(const _ of g)m.push(n({label:_.label,checked:h===_.value,run:f(_.value)}));return o(d,m)},a=[];a.push(n({label:p("context.minimap.minimap","Minimap"),checked:t.enabled,run:()=>{this._configurationService.updateValue("editor.minimap.enabled",!t.enabled)}})),a.push(new rn),a.push(n({label:p("context.minimap.renderCharacters","Render Characters"),enabled:t.enabled,checked:t.renderCharacters,run:()=>{this._configurationService.updateValue("editor.minimap.renderCharacters",!t.renderCharacters)}})),a.push(r(p("context.minimap.size","Vertical size"),t.enabled,"editor.minimap.size",t.size,[{label:p("context.minimap.size.proportional","Proportional"),value:"proportional"},{label:p("context.minimap.size.fill","Fill"),value:"fill"},{label:p("context.minimap.size.fit","Fit"),value:"fit"}])),a.push(r(p("context.minimap.slider","Slider"),t.enabled,"editor.minimap.showSlider",t.showSlider,[{label:p("context.minimap.slider.mouseover","Mouse Over"),value:"mouseover"},{label:p("context.minimap.slider.always","Always"),value:"always"}]));const l=this._editor.getOption(127)&&!_d;this._contextMenuIsBeingShownCount++,this._contextMenuService.showContextMenu({domForShadowRoot:l?this._editor.getDomNode():void 0,getAnchor:()=>e,getActions:()=>a,onHide:d=>{this._contextMenuIsBeingShownCount--,this._editor.focus()}})}_keybindingFor(e){return this._keybindingService.lookupKeybinding(e.id)}dispose(){this._contextMenuIsBeingShownCount>0&&this._contextViewService.hideContextView(),this._toDispose.dispose()}};U_.ID="editor.contrib.contextmenu";U_=oR=UEe([Lg(1,Oo),Lg(2,nu),Lg(3,Be),Lg(4,At),Lg(5,hr),Lg(6,rt),Lg(7,If)],U_);class $Ee extends me{constructor(){super({id:"editor.action.showContextMenu",label:p("action.showContextMenu.label","Show Editor Context Menu"),alias:"Show Editor Context Menu",precondition:void 0,kbOpts:{kbExpr:T.textInputFocus,primary:1092,weight:100}})}run(e,t){var i;(i=U_.get(t))===null||i===void 0||i.showContextMenu()}}kt(U_.ID,U_,2);te($Ee);class cT{constructor(e){this.selections=e}equals(e){const t=this.selections.length,i=e.selections.length;if(t!==i)return!1;for(let n=0;n{this._undoStack=[],this._redoStack=[]})),this._register(e.onDidChangeModelContent(t=>{this._undoStack=[],this._redoStack=[]})),this._register(e.onDidChangeCursorSelection(t=>{if(this._isCursorUndoRedo||!t.oldSelections||t.oldModelVersionId!==t.modelVersionId)return;const i=new cT(t.oldSelections);this._undoStack.length>0&&this._undoStack[this._undoStack.length-1].cursorState.equals(i)||(this._undoStack.push(new uT(i,e.getScrollTop(),e.getScrollLeft())),this._redoStack=[],this._undoStack.length>50&&this._undoStack.shift())}))}cursorUndo(){!this._editor.hasModel()||this._undoStack.length===0||(this._redoStack.push(new uT(new cT(this._editor.getSelections()),this._editor.getScrollTop(),this._editor.getScrollLeft())),this._applyState(this._undoStack.pop()))}cursorRedo(){!this._editor.hasModel()||this._redoStack.length===0||(this._undoStack.push(new uT(new cT(this._editor.getSelections()),this._editor.getScrollTop(),this._editor.getScrollLeft())),this._applyState(this._redoStack.pop()))}_applyState(e){this._isCursorUndoRedo=!0,this._editor.setSelections(e.cursorState.selections),this._editor.setScrollPosition({scrollTop:e.scrollTop,scrollLeft:e.scrollLeft}),this._isCursorUndoRedo=!1}}Wf.ID="editor.contrib.cursorUndoRedoController";class jEe extends me{constructor(){super({id:"cursorUndo",label:p("cursor.undo","Cursor Undo"),alias:"Cursor Undo",precondition:void 0,kbOpts:{kbExpr:T.textInputFocus,primary:2099,weight:100}})}run(e,t,i){var n;(n=Wf.get(t))===null||n===void 0||n.cursorUndo()}}class KEe extends me{constructor(){super({id:"cursorRedo",label:p("cursor.redo","Cursor Redo"),alias:"Cursor Redo",precondition:void 0})}run(e,t,i){var n;(n=Wf.get(t))===null||n===void 0||n.cursorRedo()}}kt(Wf.ID,Wf,0);te(jEe);te(KEe);class qEe{constructor(e,t,i){this.selection=e,this.targetPosition=t,this.copy=i,this.targetSelection=null}getEditOperations(e,t){const i=e.getValueInRange(this.selection);if(this.copy||t.addEditOperation(this.selection,null),t.addEditOperation(new x(this.targetPosition.lineNumber,this.targetPosition.column,this.targetPosition.lineNumber,this.targetPosition.column),i),this.selection.containsPosition(this.targetPosition)&&!(this.copy&&(this.selection.getEndPosition().equals(this.targetPosition)||this.selection.getStartPosition().equals(this.targetPosition)))){this.targetSelection=this.selection;return}if(this.copy){this.targetSelection=new we(this.targetPosition.lineNumber,this.targetPosition.column,this.selection.endLineNumber-this.selection.startLineNumber+this.targetPosition.lineNumber,this.selection.startLineNumber===this.selection.endLineNumber?this.targetPosition.column+this.selection.endColumn-this.selection.startColumn:this.selection.endColumn);return}if(this.targetPosition.lineNumber>this.selection.endLineNumber){this.targetSelection=new we(this.targetPosition.lineNumber-this.selection.endLineNumber+this.selection.startLineNumber,this.targetPosition.column,this.targetPosition.lineNumber,this.selection.startLineNumber===this.selection.endLineNumber?this.targetPosition.column+this.selection.endColumn-this.selection.startColumn:this.selection.endColumn);return}if(this.targetPosition.lineNumberthis._onEditorMouseDown(t))),this._register(this._editor.onMouseUp(t=>this._onEditorMouseUp(t))),this._register(this._editor.onMouseDrag(t=>this._onEditorMouseDrag(t))),this._register(this._editor.onMouseDrop(t=>this._onEditorMouseDrop(t))),this._register(this._editor.onMouseDropCanceled(()=>this._onEditorMouseDropCanceled())),this._register(this._editor.onKeyDown(t=>this.onEditorKeyDown(t))),this._register(this._editor.onKeyUp(t=>this.onEditorKeyUp(t))),this._register(this._editor.onDidBlurEditorWidget(()=>this.onEditorBlur())),this._register(this._editor.onDidBlurEditorText(()=>this.onEditorBlur())),this._mouseDown=!1,this._modifierPressed=!1,this._dragSelection=null}onEditorBlur(){this._removeDecoration(),this._dragSelection=null,this._mouseDown=!1,this._modifierPressed=!1}onEditorKeyDown(e){!this._editor.getOption(35)||this._editor.getOption(22)||(Op(e)&&(this._modifierPressed=!0),this._mouseDown&&Op(e)&&this._editor.updateOptions({mouseStyle:"copy"}))}onEditorKeyUp(e){!this._editor.getOption(35)||this._editor.getOption(22)||(Op(e)&&(this._modifierPressed=!1),this._mouseDown&&e.keyCode===Ac.TRIGGER_KEY_VALUE&&this._editor.updateOptions({mouseStyle:"default"}))}_onEditorMouseDown(e){this._mouseDown=!0}_onEditorMouseUp(e){this._mouseDown=!1,this._editor.updateOptions({mouseStyle:"text"})}_onEditorMouseDrag(e){const t=e.target;if(this._dragSelection===null){const n=(this._editor.getSelections()||[]).filter(o=>t.position&&o.containsPosition(t.position));if(n.length===1)this._dragSelection=n[0];else return}Op(e.event)?this._editor.updateOptions({mouseStyle:"copy"}):this._editor.updateOptions({mouseStyle:"default"}),t.position&&(this._dragSelection.containsPosition(t.position)?this._removeDecoration():this.showAt(t.position))}_onEditorMouseDropCanceled(){this._editor.updateOptions({mouseStyle:"text"}),this._removeDecoration(),this._dragSelection=null,this._mouseDown=!1}_onEditorMouseDrop(e){if(e.target&&(this._hitContent(e.target)||this._hitMargin(e.target))&&e.target.position){const t=new W(e.target.position.lineNumber,e.target.position.column);if(this._dragSelection===null){let i=null;if(e.event.shiftKey){const n=this._editor.getSelection();if(n){const{selectionStartLineNumber:o,selectionStartColumn:r}=n;i=[new we(o,r,t.lineNumber,t.column)]}}else i=(this._editor.getSelections()||[]).map(n=>n.containsPosition(t)?new we(t.lineNumber,t.column,t.lineNumber,t.column):n);this._editor.setSelections(i||[],"mouse",3)}else(!this._dragSelection.containsPosition(t)||(Op(e.event)||this._modifierPressed)&&(this._dragSelection.getEndPosition().equals(t)||this._dragSelection.getStartPosition().equals(t)))&&(this._editor.pushUndoStop(),this._editor.executeCommand(Ac.ID,new qEe(this._dragSelection,t,Op(e.event)||this._modifierPressed)),this._editor.pushUndoStop())}this._editor.updateOptions({mouseStyle:"text"}),this._removeDecoration(),this._dragSelection=null,this._mouseDown=!1}showAt(e){this._dndDecorationIds.set([{range:new x(e.lineNumber,e.column,e.lineNumber,e.column),options:Ac._DECORATION_OPTIONS}]),this._editor.revealPosition(e,1)}_removeDecoration(){this._dndDecorationIds.clear()}_hitContent(e){return e.type===6||e.type===7}_hitMargin(e){return e.type===2||e.type===3||e.type===4}dispose(){this._removeDecoration(),this._dragSelection=null,this._mouseDown=!1,this._modifierPressed=!1,super.dispose()}}Ac.ID="editor.contrib.dragAndDrop";Ac.TRIGGER_KEY_VALUE=lt?6:5;Ac._DECORATION_OPTIONS=Ye.register({description:"dnd-target",className:"dnd-target"});kt(Ac.ID,Ac,2);var cy;kt(kd.ID,kd,0);F1(MM);de(new class extends mn{constructor(){super({id:tq,precondition:d4,kbOpts:{weight:100,primary:2137}})}runEditorCommand(s,e){var t;return(t=kd.get(e))===null||t===void 0?void 0:t.changePasteType()}});de(new class extends mn{constructor(){super({id:"editor.hidePasteWidget",precondition:d4,kbOpts:{weight:100,primary:9}})}runEditorCommand(s,e){var t;(t=kd.get(e))===null||t===void 0||t.clearWidgets()}});te((cy=class extends me{constructor(){super({id:"editor.action.pasteAs",label:p("pasteAs","Paste As..."),alias:"Paste As...",precondition:T.writable,metadata:{description:"Paste as",args:[{name:"args",schema:cy.argsSchema}]}})}run(e,t,i){var n;let o=typeof(i==null?void 0:i.kind)=="string"?i.kind:void 0;return!o&&i&&(o=typeof i.id=="string"?i.id:void 0),(n=kd.get(t))===null||n===void 0?void 0:n.pasteAs(o?new Bt(o):void 0)}},cy.argsSchema={type:"object",properties:{kind:{type:"string",description:p("pasteAs.kind","The kind of the paste edit to try applying. If not provided or there are multiple edits for this kind, the editor will show a picker.")}}},cy));te(class extends me{constructor(){super({id:"editor.action.pasteAsText",label:p("pasteAsText","Paste as Text"),alias:"Paste as Text",precondition:T.writable})}run(s,e){var t;return(t=kd.get(e))===null||t===void 0?void 0:t.pasteAs({providerId:Kc.id})}});class GEe{constructor(){this._dragOperations=new Map}removeDragOperationTransfer(e){if(e&&this._dragOperations.has(e)){const t=this._dragOperations.get(e);return this._dragOperations.delete(e),t}}}class e9{constructor(e){this.identifier=e}}const Jq=ut("treeViewsDndService");mt(Jq,GEe,1);var ZEe=function(s,e,t,i){var n=arguments.length,o=n<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,r;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(s,e,t,i);else for(var a=s.length-1;a>=0;a--)(r=s[a])&&(o=(n<3?r(o):n>3?r(e,t,o):r(e,t))||o);return n>3&&o&&Object.defineProperty(e,t,o),o},uy=function(s,e){return function(t,i){e(t,i,s)}},rR;const eG="editor.experimental.dropIntoEditor.defaultProvider",tG="editor.changeDropType",L4=new ue("dropWidgetVisible",!1,p("dropWidgetVisible","Whether the drop widget is showing"));let Hf=rR=class extends H{static get(e){return e.getContribution(rR.ID)}constructor(e,t,i,n,o){super(),this._configService=i,this._languageFeaturesService=n,this._treeViewsDragAndDropService=o,this.treeItemsTransfer=IC.getInstance(),this._dropProgressManager=this._register(t.createInstance(lL,"dropIntoEditor",e)),this._postDropWidgetManager=this._register(t.createInstance(cL,"dropIntoEditor",e,L4,{id:tG,label:p("postDropWidgetTitle","Show drop options...")})),this._register(e.onDropIntoEditor(r=>this.onDropIntoEditor(e,r.position,r.event)))}clearWidgets(){this._postDropWidgetManager.clear()}changeDropType(){this._postDropWidgetManager.tryShowSelector()}async onDropIntoEditor(e,t,i){var n;if(!i.dataTransfer||!e.hasModel())return;(n=this._currentOperation)===null||n===void 0||n.cancel(),e.focus(),e.setPosition(t);const o=Dn(async r=>{const a=new Bh(e,1,void 0,r);try{const l=await this.extractDataTransferData(i);if(l.size===0||a.token.isCancellationRequested)return;const d=e.getModel();if(!d)return;const c=this._languageFeaturesService.documentDropEditProvider.ordered(d).filter(h=>h.dropMimeTypes?h.dropMimeTypes.some(g=>l.matches(g)):!0),u=await this.getDropEdits(c,d,t,l,a);if(a.token.isCancellationRequested)return;if(u.length){const h=this.getInitialActiveEditIndex(d,u),g=e.getOption(36).showDropSelector==="afterDrop";await this._postDropWidgetManager.applyEditAndShowIfNeeded([x.fromPositions(t)],{activeEditIndex:h,allEdits:u},g,async f=>f,r)}}finally{a.dispose(),this._currentOperation===o&&(this._currentOperation=void 0)}});this._dropProgressManager.showWhile(t,p("dropIntoEditorProgress","Running drop handlers. Click to cancel"),o),this._currentOperation=o}async getDropEdits(e,t,i,n,o){const r=await h1(Promise.all(e.map(async l=>{try{const d=await l.provideDocumentDropEdits(t,i,n,o.token);return d==null?void 0:d.map(c=>({...c,providerId:l.id}))}catch(d){console.error(d)}})),o.token),a=pd(r??[]).flat();return JK(a)}getInitialActiveEditIndex(e,t){const i=this._configService.getValue(eG,{resource:e.uri});for(const[n,o]of Object.entries(i)){const r=new Bt(o),a=t.findIndex(l=>r.value===l.providerId&&l.handledMimeType&&jK(n,[l.handledMimeType]));if(a>=0)return a}return 0}async extractDataTransferData(e){if(!e.dataTransfer)return new $K;const t=GK(e.dataTransfer);if(this.treeItemsTransfer.hasData(e9.prototype)){const i=this.treeItemsTransfer.getData(e9.prototype);if(Array.isArray(i))for(const n of i){const o=await this._treeViewsDragAndDropService.removeDragOperationTransfer(n.identifier);if(o)for(const[r,a]of o)t.replace(r,a)}}return t}};Hf.ID="editor.contrib.dropIntoEditorController";Hf=rR=ZEe([uy(1,Ne),uy(2,rt),uy(3,Ce),uy(4,Jq)],Hf);kt(Hf.ID,Hf,2);F1(AM);de(new class extends mn{constructor(){super({id:tG,precondition:L4,kbOpts:{weight:100,primary:2137}})}runEditorCommand(s,e,t){var i;(i=Hf.get(e))===null||i===void 0||i.changeDropType()}});de(new class extends mn{constructor(){super({id:"editor.hideDropWidget",precondition:L4,kbOpts:{weight:100,primary:9}})}runEditorCommand(s,e,t){var i;(i=Hf.get(e))===null||i===void 0||i.clearWidgets()}});Ji.as(pl.Configuration).registerConfiguration({...Vx,properties:{[eG]:{type:"object",scope:5,description:p("defaultProviderDescription","Configures the default drop provider to use for content of a given mime type."),default:{},additionalProperties:{type:"string"}}}});class ps{constructor(e){this._editor=e,this._decorations=[],this._overviewRulerApproximateDecorations=[],this._findScopeDecorationIds=[],this._rangeHighlightDecorationId=null,this._highlightedDecorationId=null,this._startPosition=this._editor.getPosition()}dispose(){this._editor.removeDecorations(this._allDecorations()),this._decorations=[],this._overviewRulerApproximateDecorations=[],this._findScopeDecorationIds=[],this._rangeHighlightDecorationId=null,this._highlightedDecorationId=null}reset(){this._decorations=[],this._overviewRulerApproximateDecorations=[],this._findScopeDecorationIds=[],this._rangeHighlightDecorationId=null,this._highlightedDecorationId=null}getCount(){return this._decorations.length}getFindScope(){return this._findScopeDecorationIds[0]?this._editor.getModel().getDecorationRange(this._findScopeDecorationIds[0]):null}getFindScopes(){if(this._findScopeDecorationIds.length){const e=this._findScopeDecorationIds.map(t=>this._editor.getModel().getDecorationRange(t)).filter(t=>!!t);if(e.length)return e}return null}getStartPosition(){return this._startPosition}setStartPosition(e){this._startPosition=e,this.setCurrentFindMatch(null)}_getDecorationIndex(e){const t=this._decorations.indexOf(e);return t>=0?t+1:1}getDecorationRangeAt(e){const t=e{if(this._highlightedDecorationId!==null&&(n.changeDecorationOptions(this._highlightedDecorationId,ps._FIND_MATCH_DECORATION),this._highlightedDecorationId=null),t!==null&&(this._highlightedDecorationId=t,n.changeDecorationOptions(this._highlightedDecorationId,ps._CURRENT_FIND_MATCH_DECORATION)),this._rangeHighlightDecorationId!==null&&(n.removeDecoration(this._rangeHighlightDecorationId),this._rangeHighlightDecorationId=null),t!==null){let o=this._editor.getModel().getDecorationRange(t);if(o.startLineNumber!==o.endLineNumber&&o.endColumn===1){const r=o.endLineNumber-1,a=this._editor.getModel().getLineMaxColumn(r);o=new x(o.startLineNumber,o.startColumn,r,a)}this._rangeHighlightDecorationId=n.addDecoration(o,ps._RANGE_HIGHLIGHT_DECORATION)}}),i}set(e,t){this._editor.changeDecorations(i=>{let n=ps._FIND_MATCH_DECORATION;const o=[];if(e.length>1e3){n=ps._FIND_MATCH_NO_OVERVIEW_DECORATION;const a=this._editor.getModel().getLineCount(),d=this._editor.getLayoutInfo().height/a,c=Math.max(2,Math.ceil(3/d));let u=e[0].range.startLineNumber,h=e[0].range.endLineNumber;for(let g=1,f=e.length;g=m.startLineNumber?m.endLineNumber>h&&(h=m.endLineNumber):(o.push({range:new x(u,1,h,1),options:ps._FIND_MATCH_ONLY_OVERVIEW_DECORATION}),u=m.startLineNumber,h=m.endLineNumber)}o.push({range:new x(u,1,h,1),options:ps._FIND_MATCH_ONLY_OVERVIEW_DECORATION})}const r=new Array(e.length);for(let a=0,l=e.length;ai.removeDecoration(a)),this._findScopeDecorationIds=[]),t!=null&&t.length&&(this._findScopeDecorationIds=t.map(a=>i.addDecoration(a,ps._FIND_SCOPE_DECORATION)))})}matchBeforePosition(e){if(this._decorations.length===0)return null;for(let t=this._decorations.length-1;t>=0;t--){const i=this._decorations[t],n=this._editor.getModel().getDecorationRange(i);if(!(!n||n.endLineNumber>e.lineNumber)){if(n.endLineNumbere.column))return n}}return this._editor.getModel().getDecorationRange(this._decorations[this._decorations.length-1])}matchAfterPosition(e){if(this._decorations.length===0)return null;for(let t=0,i=this._decorations.length;te.lineNumber)return o;if(!(o.startColumn0){const i=[];for(let r=0;rx.compareRangesUsingStarts(r.range,a.range));const n=[];let o=i[0];for(let r=1;r0?e[0].toUpperCase()+e.substr(1):s[0][0].toUpperCase()!==s[0][0]&&e.length>0?e[0].toLowerCase()+e.substr(1):e}else return e}function t9(s,e,t){return s[0].indexOf(t)!==-1&&e.indexOf(t)!==-1&&s[0].split(t).length===e.split(t).length}function i9(s,e,t){const i=e.split(t),n=s[0].split(t);let o="";return i.forEach((r,a)=>{o+=iG([n[a]],r)+t}),o.slice(0,-1)}class n9{constructor(e){this.staticValue=e,this.kind=0}}class YEe{constructor(e){this.pieces=e,this.kind=1}}class $_{static fromStaticValue(e){return new $_([ff.staticValue(e)])}get hasReplacementPatterns(){return this._state.kind===1}constructor(e){!e||e.length===0?this._state=new n9(""):e.length===1&&e[0].staticValue!==null?this._state=new n9(e[0].staticValue):this._state=new YEe(e)}buildReplaceString(e,t){if(this._state.kind===0)return t?iG(e,this._state.staticValue):this._state.staticValue;let i="";for(let n=0,o=this._state.pieces.length;n0){const l=[],d=r.caseOps.length;let c=0;for(let u=0,h=a.length;u=d){l.push(a.slice(u));break}switch(r.caseOps[c]){case"U":l.push(a[u].toUpperCase());break;case"u":l.push(a[u].toUpperCase()),c++;break;case"L":l.push(a[u].toLowerCase());break;case"l":l.push(a[u].toLowerCase()),c++;break;default:l.push(a[u])}}a=l.join("")}i+=a}return i}static _substitute(e,t){if(t===null)return"";if(e===0)return t[0];let i="";for(;e>0;){if(e=n)break;const r=s.charCodeAt(i);switch(r){case 92:t.emitUnchanged(i-1),t.emitStatic("\\",i+1);break;case 110:t.emitUnchanged(i-1),t.emitStatic(` @@ -884,14 +884,14 @@ ${e.toString()}`}}class XD{constructor(e=new L1,t=!1,i,n=xye){var o;this._servic * Version: 0.49.0(383fdf3fc0e1e1a024068b8d0fd4f3dcbae74d04) * Released under the MIT license * https://github.com/microsoft/monaco-editor/blob/main/LICENSE.txt - *-----------------------------------------------------------------------------*/var VRe=Object.defineProperty,zRe=Object.getOwnPropertyDescriptor,URe=Object.getOwnPropertyNames,$Re=Object.prototype.hasOwnProperty,jRe=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of URe(e))!$Re.call(s,n)&&n!==t&&VRe(s,n,{get:()=>e[n],enumerable:!(i=zRe(e,n))||i.enumerable});return s},KRe=(s,e,t)=>(jRe(s,e,"default"),t),E0={};KRe(E0,_0);var J4=class{constructor(e,t,i){this._onDidChange=new E0.Emitter,this._languageId=e,this.setOptions(t),this.setModeConfiguration(i)}get onDidChange(){return this._onDidChange.event}get languageId(){return this._languageId}get modeConfiguration(){return this._modeConfiguration}get diagnosticsOptions(){return this.options}get options(){return this._options}setOptions(e){this._options=e||Object.create(null),this._onDidChange.fire(this)}setDiagnosticsOptions(e){this.setOptions(e)}setModeConfiguration(e){this._modeConfiguration=e||Object.create(null),this._onDidChange.fire(this)}},e5={validate:!0,lint:{compatibleVendorPrefixes:"ignore",vendorPrefix:"warning",duplicateProperties:"warning",emptyRules:"warning",importStatement:"ignore",boxModel:"ignore",universalSelector:"ignore",zeroUnits:"ignore",fontFaceProperties:"warning",hexColorLength:"error",argumentsInColorFunction:"error",unknownProperties:"warning",ieHack:"ignore",unknownVendorSpecificProperties:"ignore",propertyIgnoredDueToDisplay:"warning",important:"ignore",float:"ignore",idSelector:"ignore"},data:{useDefaultDataProvider:!0},format:{newlineBetweenSelectors:!0,newlineBetweenRules:!0,spaceAroundSelectorSeparator:!1,braceStyle:"collapse",maxPreserveNewLines:void 0,preserveNewLines:!0}},t5={completionItems:!0,hovers:!0,documentSymbols:!0,definitions:!0,references:!0,documentHighlights:!0,rename:!0,colors:!0,foldingRanges:!0,diagnostics:!0,selectionRanges:!0,documentFormattingEdits:!0,documentRangeFormattingEdits:!0},gZ=new J4("css",e5,t5),fZ=new J4("scss",e5,t5),pZ=new J4("less",e5,t5);E0.languages.css={cssDefaults:gZ,lessDefaults:pZ,scssDefaults:fZ};function i5(){return er(()=>import("./cssMode-CMP9zKWk.js"),__vite__mapDeps([8,1,2,3]))}E0.languages.onLanguage("less",()=>{i5().then(s=>s.setupMode(pZ))});E0.languages.onLanguage("scss",()=>{i5().then(s=>s.setupMode(fZ))});E0.languages.onLanguage("css",()=>{i5().then(s=>s.setupMode(gZ))});/*!----------------------------------------------------------------------------- + *-----------------------------------------------------------------------------*/var VRe=Object.defineProperty,zRe=Object.getOwnPropertyDescriptor,URe=Object.getOwnPropertyNames,$Re=Object.prototype.hasOwnProperty,jRe=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of URe(e))!$Re.call(s,n)&&n!==t&&VRe(s,n,{get:()=>e[n],enumerable:!(i=zRe(e,n))||i.enumerable});return s},KRe=(s,e,t)=>(jRe(s,e,"default"),t),E0={};KRe(E0,_0);var J4=class{constructor(e,t,i){this._onDidChange=new E0.Emitter,this._languageId=e,this.setOptions(t),this.setModeConfiguration(i)}get onDidChange(){return this._onDidChange.event}get languageId(){return this._languageId}get modeConfiguration(){return this._modeConfiguration}get diagnosticsOptions(){return this.options}get options(){return this._options}setOptions(e){this._options=e||Object.create(null),this._onDidChange.fire(this)}setDiagnosticsOptions(e){this.setOptions(e)}setModeConfiguration(e){this._modeConfiguration=e||Object.create(null),this._onDidChange.fire(this)}},e5={validate:!0,lint:{compatibleVendorPrefixes:"ignore",vendorPrefix:"warning",duplicateProperties:"warning",emptyRules:"warning",importStatement:"ignore",boxModel:"ignore",universalSelector:"ignore",zeroUnits:"ignore",fontFaceProperties:"warning",hexColorLength:"error",argumentsInColorFunction:"error",unknownProperties:"warning",ieHack:"ignore",unknownVendorSpecificProperties:"ignore",propertyIgnoredDueToDisplay:"warning",important:"ignore",float:"ignore",idSelector:"ignore"},data:{useDefaultDataProvider:!0},format:{newlineBetweenSelectors:!0,newlineBetweenRules:!0,spaceAroundSelectorSeparator:!1,braceStyle:"collapse",maxPreserveNewLines:void 0,preserveNewLines:!0}},t5={completionItems:!0,hovers:!0,documentSymbols:!0,definitions:!0,references:!0,documentHighlights:!0,rename:!0,colors:!0,foldingRanges:!0,diagnostics:!0,selectionRanges:!0,documentFormattingEdits:!0,documentRangeFormattingEdits:!0},gZ=new J4("css",e5,t5),fZ=new J4("scss",e5,t5),pZ=new J4("less",e5,t5);E0.languages.css={cssDefaults:gZ,lessDefaults:pZ,scssDefaults:fZ};function i5(){return er(()=>import("./cssMode-KOxPoCwD.js"),__vite__mapDeps([8,1,2,3]))}E0.languages.onLanguage("less",()=>{i5().then(s=>s.setupMode(pZ))});E0.languages.onLanguage("scss",()=>{i5().then(s=>s.setupMode(fZ))});E0.languages.onLanguage("css",()=>{i5().then(s=>s.setupMode(gZ))});/*!----------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Version: 0.49.0(383fdf3fc0e1e1a024068b8d0fd4f3dcbae74d04) * Released under the MIT license * https://github.com/microsoft/monaco-editor/blob/main/LICENSE.txt - *-----------------------------------------------------------------------------*/var qRe=Object.defineProperty,GRe=Object.getOwnPropertyDescriptor,ZRe=Object.getOwnPropertyNames,XRe=Object.prototype.hasOwnProperty,YRe=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ZRe(e))!XRe.call(s,n)&&n!==t&&qRe(s,n,{get:()=>e[n],enumerable:!(i=GRe(e,n))||i.enumerable});return s},QRe=(s,e,t)=>(YRe(s,e,"default"),t),iE={};QRe(iE,_0);var JRe=class{constructor(e,t,i){this._onDidChange=new iE.Emitter,this._languageId=e,this.setOptions(t),this.setModeConfiguration(i)}get onDidChange(){return this._onDidChange.event}get languageId(){return this._languageId}get options(){return this._options}get modeConfiguration(){return this._modeConfiguration}setOptions(e){this._options=e||Object.create(null),this._onDidChange.fire(this)}setModeConfiguration(e){this._modeConfiguration=e||Object.create(null),this._onDidChange.fire(this)}},ePe={tabSize:4,insertSpaces:!1,wrapLineLength:120,unformatted:'default": "a, abbr, acronym, b, bdo, big, br, button, cite, code, dfn, em, i, img, input, kbd, label, map, object, q, samp, select, small, span, strong, sub, sup, textarea, tt, var',contentUnformatted:"pre",indentInnerHtml:!1,preserveNewLines:!0,maxPreserveNewLines:void 0,indentHandlebars:!1,endWithNewline:!1,extraLiners:"head, body, /html",wrapAttributes:"auto"},nE={format:ePe,suggest:{},data:{useDefaultDataProvider:!0}};function sE(s){return{completionItems:!0,hovers:!0,documentSymbols:!0,links:!0,documentHighlights:!0,rename:!0,colors:!0,foldingRanges:!0,selectionRanges:!0,diagnostics:s===Cb,documentFormattingEdits:s===Cb,documentRangeFormattingEdits:s===Cb}}var Cb="html",tW="handlebars",iW="razor",mZ=oE(Cb,nE,sE(Cb)),tPe=mZ.defaults,_Z=oE(tW,nE,sE(tW)),iPe=_Z.defaults,vZ=oE(iW,nE,sE(iW)),nPe=vZ.defaults;iE.languages.html={htmlDefaults:tPe,razorDefaults:nPe,handlebarDefaults:iPe,htmlLanguageService:mZ,handlebarLanguageService:_Z,razorLanguageService:vZ,registerHTMLLanguageService:oE};function sPe(){return er(()=>import("./htmlMode-BZEeRbEQ.js"),__vite__mapDeps([9,1,2,3]))}function oE(s,e=nE,t=sE(s)){const i=new JRe(s,e,t);let n;const o=iE.languages.onLanguage(s,async()=>{n=(await sPe()).setupMode(i)});return{defaults:i,dispose(){o.dispose(),n==null||n.dispose(),n=void 0}}}var oPe=class{constructor(e,t,i){this._onDidChange=new OK,this._languageId=e,this.setDiagnosticsOptions(t),this.setModeConfiguration(i)}get onDidChange(){return this._onDidChange.event}get languageId(){return this._languageId}get modeConfiguration(){return this._modeConfiguration}get diagnosticsOptions(){return this._diagnosticsOptions}setDiagnosticsOptions(e){this._diagnosticsOptions=e||Object.create(null),this._onDidChange.fire(this)}setModeConfiguration(e){this._modeConfiguration=e||Object.create(null),this._onDidChange.fire(this)}},rPe={validate:!0,allowComments:!0,schemas:[],enableSchemaRequest:!1,schemaRequest:"warning",schemaValidation:"warning",comments:"error",trailingCommas:"error"},aPe={documentFormattingEdits:!0,documentRangeFormattingEdits:!0,completionItems:!0,hovers:!0,documentSymbols:!0,tokens:!0,colors:!0,foldingRanges:!0,diagnostics:!0,selectionRanges:!0},bZ=new oPe("json",rPe,aPe),lPe=()=>CZ().then(s=>s.getWorker());O1.json={jsonDefaults:bZ,getWorker:lPe};function CZ(){return er(()=>import("./jsonMode-CWFvP3uU.js"),__vite__mapDeps([10,1,2,3]))}O1.register({id:"json",extensions:[".json",".bowerrc",".jshintrc",".jscsrc",".eslintrc",".babelrc",".har"],aliases:["JSON","json"],mimetypes:["application/json"]});O1.onLanguage("json",()=>{CZ().then(s=>s.setupMode(bZ))});/*!----------------------------------------------------------------------------- + *-----------------------------------------------------------------------------*/var qRe=Object.defineProperty,GRe=Object.getOwnPropertyDescriptor,ZRe=Object.getOwnPropertyNames,XRe=Object.prototype.hasOwnProperty,YRe=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ZRe(e))!XRe.call(s,n)&&n!==t&&qRe(s,n,{get:()=>e[n],enumerable:!(i=GRe(e,n))||i.enumerable});return s},QRe=(s,e,t)=>(YRe(s,e,"default"),t),iE={};QRe(iE,_0);var JRe=class{constructor(e,t,i){this._onDidChange=new iE.Emitter,this._languageId=e,this.setOptions(t),this.setModeConfiguration(i)}get onDidChange(){return this._onDidChange.event}get languageId(){return this._languageId}get options(){return this._options}get modeConfiguration(){return this._modeConfiguration}setOptions(e){this._options=e||Object.create(null),this._onDidChange.fire(this)}setModeConfiguration(e){this._modeConfiguration=e||Object.create(null),this._onDidChange.fire(this)}},ePe={tabSize:4,insertSpaces:!1,wrapLineLength:120,unformatted:'default": "a, abbr, acronym, b, bdo, big, br, button, cite, code, dfn, em, i, img, input, kbd, label, map, object, q, samp, select, small, span, strong, sub, sup, textarea, tt, var',contentUnformatted:"pre",indentInnerHtml:!1,preserveNewLines:!0,maxPreserveNewLines:void 0,indentHandlebars:!1,endWithNewline:!1,extraLiners:"head, body, /html",wrapAttributes:"auto"},nE={format:ePe,suggest:{},data:{useDefaultDataProvider:!0}};function sE(s){return{completionItems:!0,hovers:!0,documentSymbols:!0,links:!0,documentHighlights:!0,rename:!0,colors:!0,foldingRanges:!0,selectionRanges:!0,diagnostics:s===Cb,documentFormattingEdits:s===Cb,documentRangeFormattingEdits:s===Cb}}var Cb="html",tW="handlebars",iW="razor",mZ=oE(Cb,nE,sE(Cb)),tPe=mZ.defaults,_Z=oE(tW,nE,sE(tW)),iPe=_Z.defaults,vZ=oE(iW,nE,sE(iW)),nPe=vZ.defaults;iE.languages.html={htmlDefaults:tPe,razorDefaults:nPe,handlebarDefaults:iPe,htmlLanguageService:mZ,handlebarLanguageService:_Z,razorLanguageService:vZ,registerHTMLLanguageService:oE};function sPe(){return er(()=>import("./htmlMode-CPOPgsaN.js"),__vite__mapDeps([9,1,2,3]))}function oE(s,e=nE,t=sE(s)){const i=new JRe(s,e,t);let n;const o=iE.languages.onLanguage(s,async()=>{n=(await sPe()).setupMode(i)});return{defaults:i,dispose(){o.dispose(),n==null||n.dispose(),n=void 0}}}var oPe=class{constructor(e,t,i){this._onDidChange=new OK,this._languageId=e,this.setDiagnosticsOptions(t),this.setModeConfiguration(i)}get onDidChange(){return this._onDidChange.event}get languageId(){return this._languageId}get modeConfiguration(){return this._modeConfiguration}get diagnosticsOptions(){return this._diagnosticsOptions}setDiagnosticsOptions(e){this._diagnosticsOptions=e||Object.create(null),this._onDidChange.fire(this)}setModeConfiguration(e){this._modeConfiguration=e||Object.create(null),this._onDidChange.fire(this)}},rPe={validate:!0,allowComments:!0,schemas:[],enableSchemaRequest:!1,schemaRequest:"warning",schemaValidation:"warning",comments:"error",trailingCommas:"error"},aPe={documentFormattingEdits:!0,documentRangeFormattingEdits:!0,completionItems:!0,hovers:!0,documentSymbols:!0,tokens:!0,colors:!0,foldingRanges:!0,diagnostics:!0,selectionRanges:!0},bZ=new oPe("json",rPe,aPe),lPe=()=>CZ().then(s=>s.getWorker());O1.json={jsonDefaults:bZ,getWorker:lPe};function CZ(){return er(()=>import("./jsonMode-D38T_BtH.js"),__vite__mapDeps([10,1,2,3]))}O1.register({id:"json",extensions:[".json",".bowerrc",".jshintrc",".jscsrc",".eslintrc",".babelrc",".har"],aliases:["JSON","json"],mimetypes:["application/json"]});O1.onLanguage("json",()=>{CZ().then(s=>s.setupMode(bZ))});/*!----------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Version: 0.49.0(383fdf3fc0e1e1a024068b8d0fd4f3dcbae74d04) * Released under the MIT license * https://github.com/microsoft/monaco-editor/blob/main/LICENSE.txt - *-----------------------------------------------------------------------------*/var dPe=Object.defineProperty,cPe=Object.getOwnPropertyDescriptor,uPe=Object.getOwnPropertyNames,hPe=Object.prototype.hasOwnProperty,gPe=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of uPe(e))!hPe.call(s,n)&&n!==t&&dPe(s,n,{get:()=>e[n],enumerable:!(i=cPe(e,n))||i.enumerable});return s},fPe=(s,e,t)=>(gPe(s,e,"default"),t),pPe="5.0.2",X_={};fPe(X_,_0);var wZ=(s=>(s[s.None=0]="None",s[s.CommonJS=1]="CommonJS",s[s.AMD=2]="AMD",s[s.UMD=3]="UMD",s[s.System=4]="System",s[s.ES2015=5]="ES2015",s[s.ESNext=99]="ESNext",s))(wZ||{}),yZ=(s=>(s[s.None=0]="None",s[s.Preserve=1]="Preserve",s[s.React=2]="React",s[s.ReactNative=3]="ReactNative",s[s.ReactJSX=4]="ReactJSX",s[s.ReactJSXDev=5]="ReactJSXDev",s))(yZ||{}),SZ=(s=>(s[s.CarriageReturnLineFeed=0]="CarriageReturnLineFeed",s[s.LineFeed=1]="LineFeed",s))(SZ||{}),DZ=(s=>(s[s.ES3=0]="ES3",s[s.ES5=1]="ES5",s[s.ES2015=2]="ES2015",s[s.ES2016=3]="ES2016",s[s.ES2017=4]="ES2017",s[s.ES2018=5]="ES2018",s[s.ES2019=6]="ES2019",s[s.ES2020=7]="ES2020",s[s.ESNext=99]="ESNext",s[s.JSON=100]="JSON",s[s.Latest=99]="Latest",s))(DZ||{}),LZ=(s=>(s[s.Classic=1]="Classic",s[s.NodeJs=2]="NodeJs",s))(LZ||{}),xZ=class{constructor(s,e,t,i,n){this._onDidChange=new X_.Emitter,this._onDidExtraLibsChange=new X_.Emitter,this._extraLibs=Object.create(null),this._removedExtraLibs=Object.create(null),this._eagerModelSync=!1,this.setCompilerOptions(s),this.setDiagnosticsOptions(e),this.setWorkerOptions(t),this.setInlayHintsOptions(i),this.setModeConfiguration(n),this._onDidExtraLibsChangeTimeout=-1}get onDidChange(){return this._onDidChange.event}get onDidExtraLibsChange(){return this._onDidExtraLibsChange.event}get modeConfiguration(){return this._modeConfiguration}get workerOptions(){return this._workerOptions}get inlayHintsOptions(){return this._inlayHintsOptions}getExtraLibs(){return this._extraLibs}addExtraLib(s,e){let t;if(typeof e>"u"?t=`ts:extralib-${Math.random().toString(36).substring(2,15)}`:t=e,this._extraLibs[t]&&this._extraLibs[t].content===s)return{dispose:()=>{}};let i=1;return this._removedExtraLibs[t]&&(i=this._removedExtraLibs[t]+1),this._extraLibs[t]&&(i=this._extraLibs[t].version+1),this._extraLibs[t]={content:s,version:i},this._fireOnDidExtraLibsChangeSoon(),{dispose:()=>{let n=this._extraLibs[t];n&&n.version===i&&(delete this._extraLibs[t],this._removedExtraLibs[t]=i,this._fireOnDidExtraLibsChangeSoon())}}}setExtraLibs(s){for(const e in this._extraLibs)this._removedExtraLibs[e]=this._extraLibs[e].version;if(this._extraLibs=Object.create(null),s&&s.length>0)for(const e of s){const t=e.filePath||`ts:extralib-${Math.random().toString(36).substring(2,15)}`,i=e.content;let n=1;this._removedExtraLibs[t]&&(n=this._removedExtraLibs[t]+1),this._extraLibs[t]={content:i,version:n}}this._fireOnDidExtraLibsChangeSoon()}_fireOnDidExtraLibsChangeSoon(){this._onDidExtraLibsChangeTimeout===-1&&(this._onDidExtraLibsChangeTimeout=window.setTimeout(()=>{this._onDidExtraLibsChangeTimeout=-1,this._onDidExtraLibsChange.fire(void 0)},0))}getCompilerOptions(){return this._compilerOptions}setCompilerOptions(s){this._compilerOptions=s||Object.create(null),this._onDidChange.fire(void 0)}getDiagnosticsOptions(){return this._diagnosticsOptions}setDiagnosticsOptions(s){this._diagnosticsOptions=s||Object.create(null),this._onDidChange.fire(void 0)}setWorkerOptions(s){this._workerOptions=s||Object.create(null),this._onDidChange.fire(void 0)}setInlayHintsOptions(s){this._inlayHintsOptions=s||Object.create(null),this._onDidChange.fire(void 0)}setMaximumWorkerIdleTime(s){}setEagerModelSync(s){this._eagerModelSync=s}getEagerModelSync(){return this._eagerModelSync}setModeConfiguration(s){this._modeConfiguration=s||Object.create(null),this._onDidChange.fire(void 0)}},mPe=pPe,kZ={completionItems:!0,hovers:!0,documentSymbols:!0,definitions:!0,references:!0,documentHighlights:!0,rename:!0,diagnostics:!0,documentRangeFormattingEdits:!0,signatureHelp:!0,onTypeFormattingEdits:!0,codeActions:!0,inlayHints:!0},EZ=new xZ({allowNonTsExtensions:!0,target:99},{noSemanticValidation:!1,noSyntaxValidation:!1,onlyVisible:!1},{},{},kZ),IZ=new xZ({allowNonTsExtensions:!0,allowJs:!0,target:99},{noSemanticValidation:!0,noSyntaxValidation:!1,onlyVisible:!1},{},{},kZ),_Pe=()=>rE().then(s=>s.getTypeScriptWorker()),vPe=()=>rE().then(s=>s.getJavaScriptWorker());X_.languages.typescript={ModuleKind:wZ,JsxEmit:yZ,NewLineKind:SZ,ScriptTarget:DZ,ModuleResolutionKind:LZ,typescriptVersion:mPe,typescriptDefaults:EZ,javascriptDefaults:IZ,getTypeScriptWorker:_Pe,getJavaScriptWorker:vPe};function rE(){return er(()=>import("./tsMode-FcR9Jej8.js"),__vite__mapDeps([11,1,2,3]))}X_.languages.onLanguage("typescript",()=>rE().then(s=>s.setupTypeScript(EZ)));X_.languages.onLanguage("javascript",()=>rE().then(s=>s.setupJavaScript(IZ)));globalThis.jotaiAtomCache=globalThis.jotaiAtomCache||{cache:new Map,get(s,e){return this.cache.has(s)?this.cache.get(s):(this.cache.set(s,e),e)}};O1.css.cssDefaults.setOptions({data:{dataProviders:{tailwindcssData:sQ}}});rQ(_0,{tailwindConfig:{darkMode:["class"],theme:{extend:{colors:{border:"hsl(var(--border))",input:"hsl(var(--input))",ring:"hsl(var(--ring))",background:"hsl(var(--background))",foreground:"hsl(var(--foreground))",primary:{DEFAULT:"hsl(var(--primary))",foreground:"hsl(var(--primary-foreground))"},secondary:{DEFAULT:"hsl(var(--secondary))",foreground:"hsl(var(--secondary-foreground))"},destructive:{DEFAULT:"hsl(var(--destructive))",foreground:"hsl(var(--destructive-foreground))"},muted:{DEFAULT:"hsl(var(--muted))",foreground:"hsl(var(--muted-foreground))"},accent:{DEFAULT:"hsl(var(--accent))",foreground:"hsl(var(--accent-foreground))"},popover:{DEFAULT:"hsl(var(--popover))",foreground:"hsl(var(--popover-foreground))"},card:{DEFAULT:"hsl(var(--card))",foreground:"hsl(var(--card-foreground))"}}}}}});NL.config({monaco:_0});NL.init().catch(s=>{console.error("Unable to initialize monaco",s)});const bPe=s=>{f5.base="vs-dark",s.editor.defineTheme("openui",f5)};function CPe({code:s,framework:e}){const o=RZ().id??"new",r=_t.useContext(jZ),[a,l]=_t.useState(e!=="html"),d=_t.useRef(),[c,u]=_t.useState(),[h,g]=_t.useState(""),[f,m]=_t.useState(""),_=_t.useRef(),[v,b]=_t.useState(!1),C=PZ(s),w=FZ(),[y,D]=OZ(BZ({id:o})),L=WZ(HZ),k=_t.useMemo(()=>new VZ(y,D,w),[y,D,w]),[I,O]=zZ(k);_t.useEffect(()=>{if(c){if(!k.version(I).includes(".")){const V=k.editChapter(h,I);O(V),setTimeout(()=>{var U;(U=d.current)==null||U.setPosition(c)},100)}u(void 0)}},[c,u,I,O]);const R=(F,V)=>{V.editor.setTheme("openui"),d.current=F;let U,J=!1;F.onDidChangeModelContent(()=>{U&&(U=void 0)}),F.onDidChangeCursorPosition(pe=>{J&&(U=pe.position,J=!1,u(U))}),F.onDidFocusEditorWidget(()=>{J=!0}),d.current.setValue(h.trim())};_t.useEffect(()=>{l(e!=="html")},[e]);const P=_t.useMemo(()=>{const[F]=UZ(e);return`${o}.${I}${F}`},[o,I,e]);return _t.useEffect(()=>{m(""),b(!1)},[P]),_t.useEffect(()=>{clearTimeout(_.current),f!==""&&(_.current=setTimeout(()=>{r.emit("ui-state",{editedHTML:f}),k.editChapter(f,I)},2e3))},[f,I]),_t.useEffect(()=>{d.current&&!v&&d.current.setValue(h.trim())},[L.rendering,v,h,P]),_t.useEffect(()=>{(async()=>{const V=await er(()=>import("./standalone-BS_cqyLa.js"),[]),J=[await er(()=>import("./html-B2LDEzWk.js"),[])];if(e!=="html"){const De=await er(()=>import("./babel-CqqbTYm7.js"),[]);J.unshift(De),J.unshift(Cse)}const pe=await V.format(s,{plugins:J,parser:e==="html"?"html":"babel",semi:!1,singleQuote:!0,trailingComma:"all",jsxBracketSameLine:!0,tabWidth:2,printWidth:200});g(pe)})().catch(()=>{console.warn("Unable to format code"),g(s)})},[C,e]),$Z.jsx(YX,{defaultValue:h.trim(),path:P,options:{readOnly:a,lineNumbers:"off",minimap:{enabled:!1},overviewRulerLanes:0,scrollBeyondLastLine:!1},className:"h-[calc(100vh-364px)] pt-2",beforeMount:bPe,onMount:R,onChange:F=>{F&&e==="html"&&!L.rendering&&F!==h.trim()&&(console.log("Edit mode enabled for code editor"),b(!0),m(F))}},P)}const d3e=Object.freeze(Object.defineProperty({__proto__:null,default:CPe},Symbol.toStringTag,{value:"Module"}));export{d3e as C,_0 as m,EZ as t}; + *-----------------------------------------------------------------------------*/var dPe=Object.defineProperty,cPe=Object.getOwnPropertyDescriptor,uPe=Object.getOwnPropertyNames,hPe=Object.prototype.hasOwnProperty,gPe=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of uPe(e))!hPe.call(s,n)&&n!==t&&dPe(s,n,{get:()=>e[n],enumerable:!(i=cPe(e,n))||i.enumerable});return s},fPe=(s,e,t)=>(gPe(s,e,"default"),t),pPe="5.0.2",X_={};fPe(X_,_0);var wZ=(s=>(s[s.None=0]="None",s[s.CommonJS=1]="CommonJS",s[s.AMD=2]="AMD",s[s.UMD=3]="UMD",s[s.System=4]="System",s[s.ES2015=5]="ES2015",s[s.ESNext=99]="ESNext",s))(wZ||{}),yZ=(s=>(s[s.None=0]="None",s[s.Preserve=1]="Preserve",s[s.React=2]="React",s[s.ReactNative=3]="ReactNative",s[s.ReactJSX=4]="ReactJSX",s[s.ReactJSXDev=5]="ReactJSXDev",s))(yZ||{}),SZ=(s=>(s[s.CarriageReturnLineFeed=0]="CarriageReturnLineFeed",s[s.LineFeed=1]="LineFeed",s))(SZ||{}),DZ=(s=>(s[s.ES3=0]="ES3",s[s.ES5=1]="ES5",s[s.ES2015=2]="ES2015",s[s.ES2016=3]="ES2016",s[s.ES2017=4]="ES2017",s[s.ES2018=5]="ES2018",s[s.ES2019=6]="ES2019",s[s.ES2020=7]="ES2020",s[s.ESNext=99]="ESNext",s[s.JSON=100]="JSON",s[s.Latest=99]="Latest",s))(DZ||{}),LZ=(s=>(s[s.Classic=1]="Classic",s[s.NodeJs=2]="NodeJs",s))(LZ||{}),xZ=class{constructor(s,e,t,i,n){this._onDidChange=new X_.Emitter,this._onDidExtraLibsChange=new X_.Emitter,this._extraLibs=Object.create(null),this._removedExtraLibs=Object.create(null),this._eagerModelSync=!1,this.setCompilerOptions(s),this.setDiagnosticsOptions(e),this.setWorkerOptions(t),this.setInlayHintsOptions(i),this.setModeConfiguration(n),this._onDidExtraLibsChangeTimeout=-1}get onDidChange(){return this._onDidChange.event}get onDidExtraLibsChange(){return this._onDidExtraLibsChange.event}get modeConfiguration(){return this._modeConfiguration}get workerOptions(){return this._workerOptions}get inlayHintsOptions(){return this._inlayHintsOptions}getExtraLibs(){return this._extraLibs}addExtraLib(s,e){let t;if(typeof e>"u"?t=`ts:extralib-${Math.random().toString(36).substring(2,15)}`:t=e,this._extraLibs[t]&&this._extraLibs[t].content===s)return{dispose:()=>{}};let i=1;return this._removedExtraLibs[t]&&(i=this._removedExtraLibs[t]+1),this._extraLibs[t]&&(i=this._extraLibs[t].version+1),this._extraLibs[t]={content:s,version:i},this._fireOnDidExtraLibsChangeSoon(),{dispose:()=>{let n=this._extraLibs[t];n&&n.version===i&&(delete this._extraLibs[t],this._removedExtraLibs[t]=i,this._fireOnDidExtraLibsChangeSoon())}}}setExtraLibs(s){for(const e in this._extraLibs)this._removedExtraLibs[e]=this._extraLibs[e].version;if(this._extraLibs=Object.create(null),s&&s.length>0)for(const e of s){const t=e.filePath||`ts:extralib-${Math.random().toString(36).substring(2,15)}`,i=e.content;let n=1;this._removedExtraLibs[t]&&(n=this._removedExtraLibs[t]+1),this._extraLibs[t]={content:i,version:n}}this._fireOnDidExtraLibsChangeSoon()}_fireOnDidExtraLibsChangeSoon(){this._onDidExtraLibsChangeTimeout===-1&&(this._onDidExtraLibsChangeTimeout=window.setTimeout(()=>{this._onDidExtraLibsChangeTimeout=-1,this._onDidExtraLibsChange.fire(void 0)},0))}getCompilerOptions(){return this._compilerOptions}setCompilerOptions(s){this._compilerOptions=s||Object.create(null),this._onDidChange.fire(void 0)}getDiagnosticsOptions(){return this._diagnosticsOptions}setDiagnosticsOptions(s){this._diagnosticsOptions=s||Object.create(null),this._onDidChange.fire(void 0)}setWorkerOptions(s){this._workerOptions=s||Object.create(null),this._onDidChange.fire(void 0)}setInlayHintsOptions(s){this._inlayHintsOptions=s||Object.create(null),this._onDidChange.fire(void 0)}setMaximumWorkerIdleTime(s){}setEagerModelSync(s){this._eagerModelSync=s}getEagerModelSync(){return this._eagerModelSync}setModeConfiguration(s){this._modeConfiguration=s||Object.create(null),this._onDidChange.fire(void 0)}},mPe=pPe,kZ={completionItems:!0,hovers:!0,documentSymbols:!0,definitions:!0,references:!0,documentHighlights:!0,rename:!0,diagnostics:!0,documentRangeFormattingEdits:!0,signatureHelp:!0,onTypeFormattingEdits:!0,codeActions:!0,inlayHints:!0},EZ=new xZ({allowNonTsExtensions:!0,target:99},{noSemanticValidation:!1,noSyntaxValidation:!1,onlyVisible:!1},{},{},kZ),IZ=new xZ({allowNonTsExtensions:!0,allowJs:!0,target:99},{noSemanticValidation:!0,noSyntaxValidation:!1,onlyVisible:!1},{},{},kZ),_Pe=()=>rE().then(s=>s.getTypeScriptWorker()),vPe=()=>rE().then(s=>s.getJavaScriptWorker());X_.languages.typescript={ModuleKind:wZ,JsxEmit:yZ,NewLineKind:SZ,ScriptTarget:DZ,ModuleResolutionKind:LZ,typescriptVersion:mPe,typescriptDefaults:EZ,javascriptDefaults:IZ,getTypeScriptWorker:_Pe,getJavaScriptWorker:vPe};function rE(){return er(()=>import("./tsMode-C8-SHbsH.js"),__vite__mapDeps([11,1,2,3]))}X_.languages.onLanguage("typescript",()=>rE().then(s=>s.setupTypeScript(EZ)));X_.languages.onLanguage("javascript",()=>rE().then(s=>s.setupJavaScript(IZ)));globalThis.jotaiAtomCache=globalThis.jotaiAtomCache||{cache:new Map,get(s,e){return this.cache.has(s)?this.cache.get(s):(this.cache.set(s,e),e)}};O1.css.cssDefaults.setOptions({data:{dataProviders:{tailwindcssData:sQ}}});rQ(_0,{tailwindConfig:{darkMode:["class"],theme:{extend:{colors:{border:"hsl(var(--border))",input:"hsl(var(--input))",ring:"hsl(var(--ring))",background:"hsl(var(--background))",foreground:"hsl(var(--foreground))",primary:{DEFAULT:"hsl(var(--primary))",foreground:"hsl(var(--primary-foreground))"},secondary:{DEFAULT:"hsl(var(--secondary))",foreground:"hsl(var(--secondary-foreground))"},destructive:{DEFAULT:"hsl(var(--destructive))",foreground:"hsl(var(--destructive-foreground))"},muted:{DEFAULT:"hsl(var(--muted))",foreground:"hsl(var(--muted-foreground))"},accent:{DEFAULT:"hsl(var(--accent))",foreground:"hsl(var(--accent-foreground))"},popover:{DEFAULT:"hsl(var(--popover))",foreground:"hsl(var(--popover-foreground))"},card:{DEFAULT:"hsl(var(--card))",foreground:"hsl(var(--card-foreground))"}}}}}});NL.config({monaco:_0});NL.init().catch(s=>{console.error("Unable to initialize monaco",s)});const bPe=s=>{f5.base="vs-dark",s.editor.defineTheme("openui",f5)};function CPe({code:s,framework:e}){const o=RZ().id??"new",r=_t.useContext(jZ),[a,l]=_t.useState(e!=="html"),d=_t.useRef(),[c,u]=_t.useState(),[h,g]=_t.useState(""),[f,m]=_t.useState(""),_=_t.useRef(),[v,b]=_t.useState(!1),C=PZ(s),w=FZ(),[y,D]=OZ(BZ({id:o})),L=WZ(HZ),k=_t.useMemo(()=>new VZ(y,D,w),[y,D,w]),[I,O]=zZ(k);_t.useEffect(()=>{if(c){if(!k.version(I).includes(".")){const V=k.editChapter(h,I);O(V),setTimeout(()=>{var U;(U=d.current)==null||U.setPosition(c)},100)}u(void 0)}},[c,u,I,O]);const R=(F,V)=>{V.editor.setTheme("openui"),d.current=F;let U,J=!1;F.onDidChangeModelContent(()=>{U&&(U=void 0)}),F.onDidChangeCursorPosition(pe=>{J&&(U=pe.position,J=!1,u(U))}),F.onDidFocusEditorWidget(()=>{J=!0}),d.current.setValue(h.trim())};_t.useEffect(()=>{l(e!=="html")},[e]);const P=_t.useMemo(()=>{const[F]=UZ(e);return`${o}.${I}${F}`},[o,I,e]);return _t.useEffect(()=>{m(""),b(!1)},[P]),_t.useEffect(()=>{clearTimeout(_.current),f!==""&&(_.current=setTimeout(()=>{r.emit("ui-state",{editedHTML:f}),k.editChapter(f,I)},2e3))},[f,I]),_t.useEffect(()=>{d.current&&!v&&d.current.setValue(h.trim())},[L.rendering,v,h,P]),_t.useEffect(()=>{(async()=>{const V=await er(()=>import("./standalone-BS_cqyLa.js"),[]),J=[await er(()=>import("./html-B2LDEzWk.js"),[])];if(e!=="html"){const De=await er(()=>import("./babel-CqqbTYm7.js"),[]);J.unshift(De),J.unshift(Cse)}const pe=await V.format(s,{plugins:J,parser:e==="html"?"html":"babel",semi:!1,singleQuote:!0,trailingComma:"all",jsxBracketSameLine:!0,tabWidth:2,printWidth:200});g(pe)})().catch(()=>{console.warn("Unable to format code"),g(s)})},[C,e]),$Z.jsx(YX,{defaultValue:h.trim(),path:P,options:{readOnly:a,lineNumbers:"off",minimap:{enabled:!1},overviewRulerLanes:0,scrollBeyondLastLine:!1},className:"h-[calc(100vh-364px)] pt-2",beforeMount:bPe,onMount:R,onChange:F=>{F&&e==="html"&&!L.rendering&&F!==h.trim()&&(console.log("Edit mode enabled for code editor"),b(!0),m(F))}},P)}const d3e=Object.freeze(Object.defineProperty({__proto__:null,default:CPe},Symbol.toStringTag,{value:"Module"}));export{d3e as C,_0 as m,EZ as t}; diff --git a/backend/openui/dist/assets/cssMode-CMP9zKWk.js b/backend/openui/dist/assets/cssMode-KOxPoCwD.js similarity index 99% rename from backend/openui/dist/assets/cssMode-CMP9zKWk.js rename to backend/openui/dist/assets/cssMode-KOxPoCwD.js index 2dcea9cc..ba1a2053 100644 --- a/backend/openui/dist/assets/cssMode-CMP9zKWk.js +++ b/backend/openui/dist/assets/cssMode-KOxPoCwD.js @@ -1,4 +1,4 @@ -import{m as Le}from"./CodeEditor-B9qhAAku.js";import"./index-B7PjGjI7.js";import"./index-DnTpCebm.js";/*!----------------------------------------------------------------------------- +import{m as Le}from"./CodeEditor--kCrJcJ3.js";import"./index-CNOVY8Nm.js";import"./index-COqeckZP.js";/*!----------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Version: 0.49.0(383fdf3fc0e1e1a024068b8d0fd4f3dcbae74d04) * Released under the MIT license diff --git a/backend/openui/dist/assets/html-B4dTfUY8.js b/backend/openui/dist/assets/html-BdsSULgH.js similarity index 97% rename from backend/openui/dist/assets/html-B4dTfUY8.js rename to backend/openui/dist/assets/html-BdsSULgH.js index 399fc7e8..52a07aff 100644 --- a/backend/openui/dist/assets/html-B4dTfUY8.js +++ b/backend/openui/dist/assets/html-BdsSULgH.js @@ -1,4 +1,4 @@ -import{m as s}from"./CodeEditor-B9qhAAku.js";import"./index-B7PjGjI7.js";import"./index-DnTpCebm.js";/*!----------------------------------------------------------------------------- +import{m as s}from"./CodeEditor--kCrJcJ3.js";import"./index-CNOVY8Nm.js";import"./index-COqeckZP.js";/*!----------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Version: 0.49.0(383fdf3fc0e1e1a024068b8d0fd4f3dcbae74d04) * Released under the MIT license diff --git a/backend/openui/dist/assets/htmlMode-BZEeRbEQ.js b/backend/openui/dist/assets/htmlMode-CPOPgsaN.js similarity index 99% rename from backend/openui/dist/assets/htmlMode-BZEeRbEQ.js rename to backend/openui/dist/assets/htmlMode-CPOPgsaN.js index 9c9b13ec..9a165738 100644 --- a/backend/openui/dist/assets/htmlMode-BZEeRbEQ.js +++ b/backend/openui/dist/assets/htmlMode-CPOPgsaN.js @@ -1,4 +1,4 @@ -import{m as $e}from"./CodeEditor-B9qhAAku.js";import"./index-B7PjGjI7.js";import"./index-DnTpCebm.js";/*!----------------------------------------------------------------------------- +import{m as $e}from"./CodeEditor--kCrJcJ3.js";import"./index-CNOVY8Nm.js";import"./index-COqeckZP.js";/*!----------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Version: 0.49.0(383fdf3fc0e1e1a024068b8d0fd4f3dcbae74d04) * Released under the MIT license diff --git a/backend/openui/dist/assets/index-B7PjGjI7.js b/backend/openui/dist/assets/index-CNOVY8Nm.js similarity index 79% rename from backend/openui/dist/assets/index-B7PjGjI7.js rename to backend/openui/dist/assets/index-CNOVY8Nm.js index 8a57d0b8..45ac1170 100644 --- a/backend/openui/dist/assets/index-B7PjGjI7.js +++ b/backend/openui/dist/assets/index-CNOVY8Nm.js @@ -6,7 +6,7 @@ var cE=Object.defineProperty;var ug=e=>{throw TypeError(e)};var fE=(e,t,n)=>t in * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - */var el=Symbol.for("react.element"),dE=Symbol.for("react.portal"),hE=Symbol.for("react.fragment"),pE=Symbol.for("react.strict_mode"),mE=Symbol.for("react.profiler"),gE=Symbol.for("react.provider"),yE=Symbol.for("react.context"),vE=Symbol.for("react.forward_ref"),wE=Symbol.for("react.suspense"),xE=Symbol.for("react.memo"),SE=Symbol.for("react.lazy"),cg=Symbol.iterator;function bE(e){return e===null||typeof e!="object"?null:(e=cg&&e[cg]||e["@@iterator"],typeof e=="function"?e:null)}var Uw={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Bw=Object.assign,Hw={};function wo(e,t,n){this.props=e,this.context=t,this.refs=Hw,this.updater=n||Uw}wo.prototype.isReactComponent={};wo.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};wo.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function Vw(){}Vw.prototype=wo.prototype;function ip(e,t,n){this.props=e,this.context=t,this.refs=Hw,this.updater=n||Uw}var sp=ip.prototype=new Vw;sp.constructor=ip;Bw(sp,wo.prototype);sp.isPureReactComponent=!0;var fg=Array.isArray,Ww=Object.prototype.hasOwnProperty,op={current:null},Qw={key:!0,ref:!0,__self:!0,__source:!0};function Kw(e,t,n){var r,i={},s=null,o=null;if(t!=null)for(r in t.ref!==void 0&&(o=t.ref),t.key!==void 0&&(s=""+t.key),t)Ww.call(t,r)&&!Qw.hasOwnProperty(r)&&(i[r]=t[r]);var a=arguments.length-2;if(a===1)i.children=n;else if(1{throw TypeError(e)};var fE=(e,t,n)=>t in * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - */var PE=_,RE=Symbol.for("react.element"),AE=Symbol.for("react.fragment"),TE=Object.prototype.hasOwnProperty,OE=PE.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,IE={key:!0,ref:!0,__self:!0,__source:!0};function Gw(e,t,n){var r,i={},s=null,o=null;n!==void 0&&(s=""+n),t.key!==void 0&&(s=""+t.key),t.ref!==void 0&&(o=t.ref);for(r in t)TE.call(t,r)&&!IE.hasOwnProperty(r)&&(i[r]=t[r]);if(e&&e.defaultProps)for(r in t=e.defaultProps,t)i[r]===void 0&&(i[r]=t[r]);return{$$typeof:RE,type:e,key:s,ref:o,props:i,_owner:OE.current}}gc.Fragment=AE;gc.jsx=Gw;gc.jsxs=Gw;jw.exports=gc;var Y=jw.exports,yc=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},vc=typeof window>"u"||"Deno"in globalThis;function _n(){}function LE(e,t){return typeof e=="function"?e(t):e}function ME(e){return typeof e=="number"&&e>=0&&e!==1/0}function NE(e,t){return Math.max(e+(t||0)-Date.now(),0)}function hg(e,t){return typeof e=="function"?e(t):e}function FE(e,t){return typeof e=="function"?e(t):e}function pg(e,t){const{type:n="all",exact:r,fetchStatus:i,predicate:s,queryKey:o,stale:a}=e;if(o){if(r){if(t.queryHash!==lp(o,t.options))return!1}else if(!Ca(t.queryKey,o))return!1}if(n!=="all"){const l=t.isActive();if(n==="active"&&!l||n==="inactive"&&l)return!1}return!(typeof a=="boolean"&&t.isStale()!==a||i&&i!==t.state.fetchStatus||s&&!s(t))}function mg(e,t){const{exact:n,status:r,predicate:i,mutationKey:s}=e;if(s){if(!t.options.mutationKey)return!1;if(n){if(_a(t.options.mutationKey)!==_a(s))return!1}else if(!Ca(t.options.mutationKey,s))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function lp(e,t){return((t==null?void 0:t.queryKeyHashFn)||_a)(e)}function _a(e){return JSON.stringify(e,(t,n)=>Cd(n)?Object.keys(n).sort().reduce((r,i)=>(r[i]=n[i],r),{}):n)}function Ca(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>Ca(e[n],t[n])):!1}function Xw(e,t){if(e===t)return e;const n=gg(e)&&gg(t);if(n||Cd(e)&&Cd(t)){const r=n?e:Object.keys(e),i=r.length,s=n?t:Object.keys(t),o=s.length,a=n?[]:{};let l=0;for(let u=0;u{setTimeout(t,e)})}function $E(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?Xw(e,t):t}function jE(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function zE(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var up=Symbol();function Yw(e,t){return!e.queryFn&&(t!=null&&t.initialPromise)?()=>t.initialPromise:!e.queryFn||e.queryFn===up?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}var Bi,Xr,Xs,Tw,UE=(Tw=class extends yc{constructor(){super();Se(this,Bi);Se(this,Xr);Se(this,Xs);ue(this,Xs,t=>{if(!vc&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){D(this,Xr)||this.setEventListener(D(this,Xs))}onUnsubscribe(){var t;this.hasListeners()||((t=D(this,Xr))==null||t.call(this),ue(this,Xr,void 0))}setEventListener(t){var n;ue(this,Xs,t),(n=D(this,Xr))==null||n.call(this),ue(this,Xr,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){D(this,Bi)!==t&&(ue(this,Bi,t),this.onFocus())}onFocus(){const t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){var t;return typeof D(this,Bi)=="boolean"?D(this,Bi):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},Bi=new WeakMap,Xr=new WeakMap,Xs=new WeakMap,Tw),Zw=new UE,Ys,Yr,Zs,Ow,BE=(Ow=class extends yc{constructor(){super();Se(this,Ys,!0);Se(this,Yr);Se(this,Zs);ue(this,Zs,t=>{if(!vc&&window.addEventListener){const n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){D(this,Yr)||this.setEventListener(D(this,Zs))}onUnsubscribe(){var t;this.hasListeners()||((t=D(this,Yr))==null||t.call(this),ue(this,Yr,void 0))}setEventListener(t){var n;ue(this,Zs,t),(n=D(this,Yr))==null||n.call(this),ue(this,Yr,t(this.setOnline.bind(this)))}setOnline(t){D(this,Ys)!==t&&(ue(this,Ys,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return D(this,Ys)}},Ys=new WeakMap,Yr=new WeakMap,Zs=new WeakMap,Ow),ku=new BE;function HE(){let e,t;const n=new Promise((i,s)=>{e=i,t=s});n.status="pending",n.catch(()=>{});function r(i){Object.assign(n,i),delete n.resolve,delete n.reject}return n.resolve=i=>{r({status:"fulfilled",value:i}),e(i)},n.reject=i=>{r({status:"rejected",reason:i}),t(i)},n}function VE(e){return Math.min(1e3*2**e,3e4)}function e0(e){return(e??"online")==="online"?ku.isOnline():!0}var t0=class extends Error{constructor(e){super("CancelledError"),this.revert=e==null?void 0:e.revert,this.silent=e==null?void 0:e.silent}};function gf(e){return e instanceof t0}function n0(e){let t=!1,n=0,r=!1,i;const s=HE(),o=v=>{var x;r||(d(new t0(v)),(x=e.abort)==null||x.call(e))},a=()=>{t=!0},l=()=>{t=!1},u=()=>Zw.isFocused()&&(e.networkMode==="always"||ku.isOnline())&&e.canRun(),f=()=>e0(e.networkMode)&&e.canRun(),c=v=>{var x;r||(r=!0,(x=e.onSuccess)==null||x.call(e,v),i==null||i(),s.resolve(v))},d=v=>{var x;r||(r=!0,(x=e.onError)==null||x.call(e,v),i==null||i(),s.reject(v))},h=()=>new Promise(v=>{var x;i=m=>{(r||u())&&v(m)},(x=e.onPause)==null||x.call(e)}).then(()=>{var v;i=void 0,r||(v=e.onContinue)==null||v.call(e)}),g=()=>{if(r)return;let v;const x=n===0?e.initialPromise:void 0;try{v=x??e.fn()}catch(m){v=Promise.reject(m)}Promise.resolve(v).then(c).catch(m=>{var E;if(r)return;const p=e.retry??(vc?0:3),w=e.retryDelay??VE,S=typeof w=="function"?w(n,m):w,k=p===!0||typeof p=="number"&&nu()?void 0:h()).then(()=>{t?d(m):g()})})};return{promise:s,cancel:o,continue:()=>(i==null||i(),s),cancelRetry:a,continueRetry:l,canStart:f,start:()=>(f()?g():h().then(g),s)}}var WE=e=>setTimeout(e,0);function QE(){let e=[],t=0,n=a=>{a()},r=a=>{a()},i=WE;const s=a=>{t?e.push(a):i(()=>{n(a)})},o=()=>{const a=e;e=[],a.length&&i(()=>{r(()=>{a.forEach(l=>{n(l)})})})};return{batch:a=>{let l;t++;try{l=a()}finally{t--,t||o()}return l},batchCalls:a=>(...l)=>{s(()=>{a(...l)})},schedule:s,setNotifyFunction:a=>{n=a},setBatchNotifyFunction:a=>{r=a},setScheduler:a=>{i=a}}}var It=QE(),Hi,Iw,r0=(Iw=class{constructor(){Se(this,Hi)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),ME(this.gcTime)&&ue(this,Hi,setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(vc?1/0:5*60*1e3))}clearGcTimeout(){D(this,Hi)&&(clearTimeout(D(this,Hi)),ue(this,Hi,void 0))}},Hi=new WeakMap,Iw),eo,to,un,Vi,Ct,Ya,Wi,Pn,vr,Lw,KE=(Lw=class extends r0{constructor(t){super();Se(this,Pn);Se(this,eo);Se(this,to);Se(this,un);Se(this,Vi);Se(this,Ct);Se(this,Ya);Se(this,Wi);ue(this,Wi,!1),ue(this,Ya,t.defaultOptions),this.setOptions(t.options),this.observers=[],ue(this,Vi,t.client),ue(this,un,D(this,Vi).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,ue(this,eo,JE(this.options)),this.state=t.state??D(this,eo),this.scheduleGc()}get meta(){return this.options.meta}get promise(){var t;return(t=D(this,Ct))==null?void 0:t.promise}setOptions(t){this.options={...D(this,Ya),...t},this.updateGcTime(this.options.gcTime)}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&D(this,un).remove(this)}setData(t,n){const r=$E(this.state.data,t,this.options);return St(this,Pn,vr).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t,n){St(this,Pn,vr).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){var r,i;const n=(r=D(this,Ct))==null?void 0:r.promise;return(i=D(this,Ct))==null||i.cancel(t),n?n.then(_n).catch(_n):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(D(this,eo))}isActive(){return this.observers.some(t=>FE(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===up||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStale(){return this.state.isInvalidated?!0:this.getObserversCount()>0?this.observers.some(t=>t.getCurrentResult().isStale):this.state.data===void 0}isStaleByTime(t=0){return this.state.isInvalidated||this.state.data===void 0||!NE(this.state.dataUpdatedAt,t)}onFocus(){var n;const t=this.observers.find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(n=D(this,Ct))==null||n.continue()}onOnline(){var n;const t=this.observers.find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(n=D(this,Ct))==null||n.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),D(this,un).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(D(this,Ct)&&(D(this,Wi)?D(this,Ct).cancel({revert:!0}):D(this,Ct).cancelRetry()),this.scheduleGc()),D(this,un).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||St(this,Pn,vr).call(this,{type:"invalidate"})}fetch(t,n){var l,u,f;if(this.state.fetchStatus!=="idle"){if(this.state.data!==void 0&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(D(this,Ct))return D(this,Ct).continueRetry(),D(this,Ct).promise}if(t&&this.setOptions(t),!this.options.queryFn){const c=this.observers.find(d=>d.options.queryFn);c&&this.setOptions(c.options)}const r=new AbortController,i=c=>{Object.defineProperty(c,"signal",{enumerable:!0,get:()=>(ue(this,Wi,!0),r.signal)})},s=()=>{const c=Yw(this.options,n),d={client:D(this,Vi),queryKey:this.queryKey,meta:this.meta};return i(d),ue(this,Wi,!1),this.options.persister?this.options.persister(c,d,this):c(d)},o={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:D(this,Vi),state:this.state,fetchFn:s};i(o),(l=this.options.behavior)==null||l.onFetch(o,this),ue(this,to,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((u=o.fetchOptions)==null?void 0:u.meta))&&St(this,Pn,vr).call(this,{type:"fetch",meta:(f=o.fetchOptions)==null?void 0:f.meta});const a=c=>{var d,h,g,v;gf(c)&&c.silent||St(this,Pn,vr).call(this,{type:"error",error:c}),gf(c)||((h=(d=D(this,un).config).onError)==null||h.call(d,c,this),(v=(g=D(this,un).config).onSettled)==null||v.call(g,this.state.data,c,this)),this.scheduleGc()};return ue(this,Ct,n0({initialPromise:n==null?void 0:n.initialPromise,fn:o.fetchFn,abort:r.abort.bind(r),onSuccess:c=>{var d,h,g,v;if(c===void 0){a(new Error(`${this.queryHash} data is undefined`));return}try{this.setData(c)}catch(x){a(x);return}(h=(d=D(this,un).config).onSuccess)==null||h.call(d,c,this),(v=(g=D(this,un).config).onSettled)==null||v.call(g,c,this.state.error,this),this.scheduleGc()},onError:a,onFail:(c,d)=>{St(this,Pn,vr).call(this,{type:"failed",failureCount:c,error:d})},onPause:()=>{St(this,Pn,vr).call(this,{type:"pause"})},onContinue:()=>{St(this,Pn,vr).call(this,{type:"continue"})},retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:()=>!0})),D(this,Ct).start()}},eo=new WeakMap,to=new WeakMap,un=new WeakMap,Vi=new WeakMap,Ct=new WeakMap,Ya=new WeakMap,Wi=new WeakMap,Pn=new WeakSet,vr=function(t){const n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,...qE(r.data,this.options),fetchMeta:t.meta??null};case"success":return{...r,data:t.data,dataUpdateCount:r.dataUpdateCount+1,dataUpdatedAt:t.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const i=t.error;return gf(i)&&i.revert&&D(this,to)?{...D(this,to),fetchStatus:"idle"}:{...r,error:i,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error"};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),It.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),D(this,un).notify({query:this,type:"updated",action:t})})},Lw);function qE(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:e0(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function JE(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var Jn,Mw,GE=(Mw=class extends yc{constructor(t={}){super();Se(this,Jn);this.config=t,ue(this,Jn,new Map)}build(t,n,r){const i=n.queryKey,s=n.queryHash??lp(i,n);let o=this.get(s);return o||(o=new KE({client:t,queryKey:i,queryHash:s,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(i)}),this.add(o)),o}add(t){D(this,Jn).has(t.queryHash)||(D(this,Jn).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=D(this,Jn).get(t.queryHash);n&&(t.destroy(),n===t&&D(this,Jn).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){It.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return D(this,Jn).get(t)}getAll(){return[...D(this,Jn).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>pg(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>pg(t,r)):n}notify(t){It.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){It.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){It.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Jn=new WeakMap,Mw),Gn,Tt,Qi,Xn,Wr,Nw,XE=(Nw=class extends r0{constructor(t){super();Se(this,Xn);Se(this,Gn);Se(this,Tt);Se(this,Qi);this.mutationId=t.mutationId,ue(this,Tt,t.mutationCache),ue(this,Gn,[]),this.state=t.state||YE(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){D(this,Gn).includes(t)||(D(this,Gn).push(t),this.clearGcTimeout(),D(this,Tt).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){ue(this,Gn,D(this,Gn).filter(n=>n!==t)),this.scheduleGc(),D(this,Tt).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){D(this,Gn).length||(this.state.status==="pending"?this.scheduleGc():D(this,Tt).remove(this))}continue(){var t;return((t=D(this,Qi))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var s,o,a,l,u,f,c,d,h,g,v,x,m,p,w,S,k,E,y,R;const n=()=>{St(this,Xn,Wr).call(this,{type:"continue"})};ue(this,Qi,n0({fn:()=>this.options.mutationFn?this.options.mutationFn(t):Promise.reject(new Error("No mutationFn found")),onFail:(T,A)=>{St(this,Xn,Wr).call(this,{type:"failed",failureCount:T,error:A})},onPause:()=>{St(this,Xn,Wr).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>D(this,Tt).canRun(this)}));const r=this.state.status==="pending",i=!D(this,Qi).canStart();try{if(r)n();else{St(this,Xn,Wr).call(this,{type:"pending",variables:t,isPaused:i}),await((o=(s=D(this,Tt).config).onMutate)==null?void 0:o.call(s,t,this));const A=await((l=(a=this.options).onMutate)==null?void 0:l.call(a,t));A!==this.state.context&&St(this,Xn,Wr).call(this,{type:"pending",context:A,variables:t,isPaused:i})}const T=await D(this,Qi).start();return await((f=(u=D(this,Tt).config).onSuccess)==null?void 0:f.call(u,T,t,this.state.context,this)),await((d=(c=this.options).onSuccess)==null?void 0:d.call(c,T,t,this.state.context)),await((g=(h=D(this,Tt).config).onSettled)==null?void 0:g.call(h,T,null,this.state.variables,this.state.context,this)),await((x=(v=this.options).onSettled)==null?void 0:x.call(v,T,null,t,this.state.context)),St(this,Xn,Wr).call(this,{type:"success",data:T}),T}catch(T){try{throw await((p=(m=D(this,Tt).config).onError)==null?void 0:p.call(m,T,t,this.state.context,this)),await((S=(w=this.options).onError)==null?void 0:S.call(w,T,t,this.state.context)),await((E=(k=D(this,Tt).config).onSettled)==null?void 0:E.call(k,void 0,T,this.state.variables,this.state.context,this)),await((R=(y=this.options).onSettled)==null?void 0:R.call(y,void 0,T,t,this.state.context)),T}finally{St(this,Xn,Wr).call(this,{type:"error",error:T})}}finally{D(this,Tt).runNext(this)}}},Gn=new WeakMap,Tt=new WeakMap,Qi=new WeakMap,Xn=new WeakSet,Wr=function(t){const n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),It.batch(()=>{D(this,Gn).forEach(r=>{r.onMutationUpdate(t)}),D(this,Tt).notify({mutation:this,type:"updated",action:t})})},Nw);function YE(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Er,Rn,Za,Fw,ZE=(Fw=class extends yc{constructor(t={}){super();Se(this,Er);Se(this,Rn);Se(this,Za);this.config=t,ue(this,Er,new Set),ue(this,Rn,new Map),ue(this,Za,0)}build(t,n,r){const i=new XE({mutationCache:this,mutationId:++bl(this,Za)._,options:t.defaultMutationOptions(n),state:r});return this.add(i),i}add(t){D(this,Er).add(t);const n=_l(t);if(typeof n=="string"){const r=D(this,Rn).get(n);r?r.push(t):D(this,Rn).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(D(this,Er).delete(t)){const n=_l(t);if(typeof n=="string"){const r=D(this,Rn).get(n);if(r)if(r.length>1){const i=r.indexOf(t);i!==-1&&r.splice(i,1)}else r[0]===t&&D(this,Rn).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){const n=_l(t);if(typeof n=="string"){const r=D(this,Rn).get(n),i=r==null?void 0:r.find(s=>s.state.status==="pending");return!i||i===t}else return!0}runNext(t){var r;const n=_l(t);if(typeof n=="string"){const i=(r=D(this,Rn).get(n))==null?void 0:r.find(s=>s!==t&&s.state.isPaused);return(i==null?void 0:i.continue())??Promise.resolve()}else return Promise.resolve()}clear(){It.batch(()=>{D(this,Er).forEach(t=>{this.notify({type:"removed",mutation:t})}),D(this,Er).clear(),D(this,Rn).clear()})}getAll(){return Array.from(D(this,Er))}find(t){const n={exact:!0,...t};return this.getAll().find(r=>mg(n,r))}findAll(t={}){return this.getAll().filter(n=>mg(t,n))}notify(t){It.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){const t=this.getAll().filter(n=>n.state.isPaused);return It.batch(()=>Promise.all(t.map(n=>n.continue().catch(_n))))}},Er=new WeakMap,Rn=new WeakMap,Za=new WeakMap,Fw);function _l(e){var t;return(t=e.options.scope)==null?void 0:t.id}function vg(e){return{onFetch:(t,n)=>{var f,c,d,h,g;const r=t.options,i=(d=(c=(f=t.fetchOptions)==null?void 0:f.meta)==null?void 0:c.fetchMore)==null?void 0:d.direction,s=((h=t.state.data)==null?void 0:h.pages)||[],o=((g=t.state.data)==null?void 0:g.pageParams)||[];let a={pages:[],pageParams:[]},l=0;const u=async()=>{let v=!1;const x=w=>{Object.defineProperty(w,"signal",{enumerable:!0,get:()=>(t.signal.aborted?v=!0:t.signal.addEventListener("abort",()=>{v=!0}),t.signal)})},m=Yw(t.options,t.fetchOptions),p=async(w,S,k)=>{if(v)return Promise.reject();if(S==null&&w.pages.length)return Promise.resolve(w);const E={client:t.client,queryKey:t.queryKey,pageParam:S,direction:k?"backward":"forward",meta:t.options.meta};x(E);const y=await m(E),{maxPages:R}=t.options,T=k?zE:jE;return{pages:T(w.pages,y,R),pageParams:T(w.pageParams,S,R)}};if(i&&s.length){const w=i==="backward",S=w?e_:wg,k={pages:s,pageParams:o},E=S(r,k);a=await p(k,E,w)}else{const w=e??s.length;do{const S=l===0?o[0]??r.initialPageParam:wg(r,a);if(l>0&&S==null)break;a=await p(a,S),l++}while(l{var v,x;return(x=(v=t.options).persister)==null?void 0:x.call(v,u,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=u}}}function wg(e,{pages:t,pageParams:n}){const r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function e_(e,{pages:t,pageParams:n}){var r;return t.length>0?(r=e.getPreviousPageParam)==null?void 0:r.call(e,t[0],t,n[0],n):void 0}var We,Zr,ei,no,ro,ti,io,so,Dw,t_=(Dw=class{constructor(e={}){Se(this,We);Se(this,Zr);Se(this,ei);Se(this,no);Se(this,ro);Se(this,ti);Se(this,io);Se(this,so);ue(this,We,e.queryCache||new GE),ue(this,Zr,e.mutationCache||new ZE),ue(this,ei,e.defaultOptions||{}),ue(this,no,new Map),ue(this,ro,new Map),ue(this,ti,0)}mount(){bl(this,ti)._++,D(this,ti)===1&&(ue(this,io,Zw.subscribe(async e=>{e&&(await this.resumePausedMutations(),D(this,We).onFocus())})),ue(this,so,ku.subscribe(async e=>{e&&(await this.resumePausedMutations(),D(this,We).onOnline())})))}unmount(){var e,t;bl(this,ti)._--,D(this,ti)===0&&((e=D(this,io))==null||e.call(this),ue(this,io,void 0),(t=D(this,so))==null||t.call(this),ue(this,so,void 0))}isFetching(e){return D(this,We).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return D(this,Zr).findAll({...e,status:"pending"}).length}getQueryData(e){var n;const t=this.defaultQueryOptions({queryKey:e});return(n=D(this,We).get(t.queryHash))==null?void 0:n.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=D(this,We).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(hg(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return D(this,We).findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=this.defaultQueryOptions({queryKey:e}),i=D(this,We).get(r.queryHash),s=i==null?void 0:i.state.data,o=LE(t,s);if(o!==void 0)return D(this,We).build(this,r).setData(o,{...n,manual:!0})}setQueriesData(e,t,n){return It.batch(()=>D(this,We).findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){var n;const t=this.defaultQueryOptions({queryKey:e});return(n=D(this,We).get(t.queryHash))==null?void 0:n.state}removeQueries(e){const t=D(this,We);It.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=D(this,We);return It.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},r=It.batch(()=>D(this,We).findAll(e).map(i=>i.cancel(n)));return Promise.all(r).then(_n).catch(_n)}invalidateQueries(e,t={}){return It.batch(()=>(D(this,We).findAll(e).forEach(n=>{n.invalidate()}),(e==null?void 0:e.refetchType)==="none"?Promise.resolve():this.refetchQueries({...e,type:(e==null?void 0:e.refetchType)??(e==null?void 0:e.type)??"active"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},r=It.batch(()=>D(this,We).findAll(e).filter(i=>!i.isDisabled()).map(i=>{let s=i.fetch(void 0,n);return n.throwOnError||(s=s.catch(_n)),i.state.fetchStatus==="paused"?Promise.resolve():s}));return Promise.all(r).then(_n)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=D(this,We).build(this,t);return n.isStaleByTime(hg(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(_n).catch(_n)}fetchInfiniteQuery(e){return e.behavior=vg(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(_n).catch(_n)}ensureInfiniteQueryData(e){return e.behavior=vg(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return ku.isOnline()?D(this,Zr).resumePausedMutations():Promise.resolve()}getQueryCache(){return D(this,We)}getMutationCache(){return D(this,Zr)}getDefaultOptions(){return D(this,ei)}setDefaultOptions(e){ue(this,ei,e)}setQueryDefaults(e,t){D(this,no).set(_a(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...D(this,no).values()],n={};return t.forEach(r=>{Ca(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){D(this,ro).set(_a(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...D(this,ro).values()],n={};return t.forEach(r=>{Ca(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...D(this,ei).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=lp(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===up&&(t.enabled=!1),t}defaultMutationOptions(e){return e!=null&&e._defaulted?e:{...D(this,ei).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){D(this,We).clear(),D(this,Zr).clear()}},We=new WeakMap,Zr=new WeakMap,ei=new WeakMap,no=new WeakMap,ro=new WeakMap,ti=new WeakMap,io=new WeakMap,so=new WeakMap,Dw),i0=_.createContext(void 0),w2=e=>{const t=_.useContext(i0);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},n_=({client:e,children:t})=>(_.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),Y.jsx(i0.Provider,{value:e,children:t}));const r_="modulepreload",i_=function(e){return"/"+e},xg={},s_=function(t,n,r){let i=Promise.resolve();if(n&&n.length>0){document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),a=(o==null?void 0:o.nonce)||(o==null?void 0:o.getAttribute("nonce"));i=Promise.allSettled(n.map(l=>{if(l=i_(l),l in xg)return;xg[l]=!0;const u=l.endsWith(".css"),f=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${l}"]${f}`))return;const c=document.createElement("link");if(c.rel=u?"stylesheet":r_,u||(c.as="script"),c.crossOrigin="",c.href=l,a&&c.setAttribute("nonce",a),document.head.appendChild(c),u)return new Promise((d,h)=>{c.addEventListener("load",d),c.addEventListener("error",()=>h(new Error(`Unable to preload CSS for ${l}`)))})}))}function s(o){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=o,window.dispatchEvent(a),!a.defaultPrevented)throw o}return i.then(o=>{for(const a of o||[])a.status==="rejected"&&s(a.reason);return t().catch(s)})};globalThis.jotaiAtomCache=globalThis.jotaiAtomCache||{cache:new Map,get(e,t){return this.cache.has(e)?this.cache.get(e):(this.cache.set(e,t),t)}};class s0 extends Ki.Component{constructor(){super(...arguments);ln(this,"state",{error:void 0})}static getDerivedStateFromError(n){return{error:n}}componentDidCatch(n,r){console.error("Encountered ErrorBoundary:",n,r);const{onError:i}=this.props;i==null||i(n)}render(){const{error:n}=this.state;if(n!==void 0){const{renderError:i}=this.props;return i(n)}const{children:r}=this.props;return r}}ln(s0,"defaultProps",{children:void 0,onError:void 0});globalThis.jotaiAtomCache=globalThis.jotaiAtomCache||{cache:new Map,get(e,t){return this.cache.has(e)?this.cache.get(e):(this.cache.set(e,t),t)}};function Sg({error:e}){return Y.jsxs("div",{className:"flex min-h-screen flex-col items-center justify-center",children:[Y.jsx("h1",{className:"text-xl","data-testid":"LoadingOrError",children:e?e.message:Y.jsx("div",{role:"status",className:"h-16 w-16 animate-spin rounded-full bg-gradient-to-r from-purple-500 via-pink-500 to-red-500"})}),e?Y.jsx("a",{href:"/",className:"mt-5 text-lg text-blue-500 underline",onClick:t=>{t.preventDefault(),document.location.reload()},children:"Reload"}):void 0]})}function Sr(e,t,{checkForDefaultPrevented:n=!0}={}){return function(i){if(e==null||e(i),n===!1||!i.defaultPrevented)return t==null?void 0:t(i)}}function bg(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function o0(...e){return t=>{let n=!1;const r=e.map(i=>{const s=bg(i,t);return!n&&typeof s=="function"&&(n=!0),s});if(n)return()=>{for(let i=0;i{const{children:o,...a}=s,l=_.useMemo(()=>a,Object.values(a));return Y.jsx(n.Provider,{value:l,children:o})};r.displayName=e+"Provider";function i(s){const o=_.useContext(n);if(o)return o;if(t!==void 0)return t;throw new Error(`\`${s}\` must be used within \`${e}\``)}return[r,i]}function a0(e,t=[]){let n=[];function r(s,o){const a=_.createContext(o),l=n.length;n=[...n,o];const u=c=>{var m;const{scope:d,children:h,...g}=c,v=((m=d==null?void 0:d[e])==null?void 0:m[l])||a,x=_.useMemo(()=>g,Object.values(g));return Y.jsx(v.Provider,{value:x,children:h})};u.displayName=s+"Provider";function f(c,d){var v;const h=((v=d==null?void 0:d[e])==null?void 0:v[l])||a,g=_.useContext(h);if(g)return g;if(o!==void 0)return o;throw new Error(`\`${c}\` must be used within \`${s}\``)}return[u,f]}const i=()=>{const s=n.map(o=>_.createContext(o));return function(a){const l=(a==null?void 0:a[e])||s;return _.useMemo(()=>({[`__scope${e}`]:{...a,[e]:l}}),[a,l])}};return i.scopeName=e,[r,o_(i,...t)]}function o_(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(i=>({useScope:i(),scopeName:i.scopeName}));return function(s){const o=r.reduce((a,{useScope:l,scopeName:u})=>{const c=l(s)[`__scope${u}`];return{...a,...c}},{});return _.useMemo(()=>({[`__scope${t.scopeName}`]:o}),[o])}};return n.scopeName=t.scopeName,n}var l0={exports:{}},rn={},u0={exports:{}},c0={};/** + */var PE=C,RE=Symbol.for("react.element"),AE=Symbol.for("react.fragment"),TE=Object.prototype.hasOwnProperty,OE=PE.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,IE={key:!0,ref:!0,__self:!0,__source:!0};function Gw(e,t,n){var r,i={},s=null,o=null;n!==void 0&&(s=""+n),t.key!==void 0&&(s=""+t.key),t.ref!==void 0&&(o=t.ref);for(r in t)TE.call(t,r)&&!IE.hasOwnProperty(r)&&(i[r]=t[r]);if(e&&e.defaultProps)for(r in t=e.defaultProps,t)i[r]===void 0&&(i[r]=t[r]);return{$$typeof:RE,type:e,key:s,ref:o,props:i,_owner:OE.current}}gc.Fragment=AE;gc.jsx=Gw;gc.jsxs=Gw;jw.exports=gc;var Y=jw.exports,yc=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},vc=typeof window>"u"||"Deno"in globalThis;function Cn(){}function LE(e,t){return typeof e=="function"?e(t):e}function ME(e){return typeof e=="number"&&e>=0&&e!==1/0}function NE(e,t){return Math.max(e+(t||0)-Date.now(),0)}function hg(e,t){return typeof e=="function"?e(t):e}function FE(e,t){return typeof e=="function"?e(t):e}function pg(e,t){const{type:n="all",exact:r,fetchStatus:i,predicate:s,queryKey:o,stale:a}=e;if(o){if(r){if(t.queryHash!==lp(o,t.options))return!1}else if(!_a(t.queryKey,o))return!1}if(n!=="all"){const l=t.isActive();if(n==="active"&&!l||n==="inactive"&&l)return!1}return!(typeof a=="boolean"&&t.isStale()!==a||i&&i!==t.state.fetchStatus||s&&!s(t))}function mg(e,t){const{exact:n,status:r,predicate:i,mutationKey:s}=e;if(s){if(!t.options.mutationKey)return!1;if(n){if(Ca(t.options.mutationKey)!==Ca(s))return!1}else if(!_a(t.options.mutationKey,s))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function lp(e,t){return((t==null?void 0:t.queryKeyHashFn)||Ca)(e)}function Ca(e){return JSON.stringify(e,(t,n)=>_d(n)?Object.keys(n).sort().reduce((r,i)=>(r[i]=n[i],r),{}):n)}function _a(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>_a(e[n],t[n])):!1}function Xw(e,t){if(e===t)return e;const n=gg(e)&&gg(t);if(n||_d(e)&&_d(t)){const r=n?e:Object.keys(e),i=r.length,s=n?t:Object.keys(t),o=s.length,a=n?[]:{};let l=0;for(let u=0;u{setTimeout(t,e)})}function $E(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?Xw(e,t):t}function jE(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function zE(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var up=Symbol();function Yw(e,t){return!e.queryFn&&(t!=null&&t.initialPromise)?()=>t.initialPromise:!e.queryFn||e.queryFn===up?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}var Bi,Xr,Xs,Tw,UE=(Tw=class extends yc{constructor(){super();Se(this,Bi);Se(this,Xr);Se(this,Xs);ue(this,Xs,t=>{if(!vc&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){D(this,Xr)||this.setEventListener(D(this,Xs))}onUnsubscribe(){var t;this.hasListeners()||((t=D(this,Xr))==null||t.call(this),ue(this,Xr,void 0))}setEventListener(t){var n;ue(this,Xs,t),(n=D(this,Xr))==null||n.call(this),ue(this,Xr,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){D(this,Bi)!==t&&(ue(this,Bi,t),this.onFocus())}onFocus(){const t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){var t;return typeof D(this,Bi)=="boolean"?D(this,Bi):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},Bi=new WeakMap,Xr=new WeakMap,Xs=new WeakMap,Tw),Zw=new UE,Ys,Yr,Zs,Ow,BE=(Ow=class extends yc{constructor(){super();Se(this,Ys,!0);Se(this,Yr);Se(this,Zs);ue(this,Zs,t=>{if(!vc&&window.addEventListener){const n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){D(this,Yr)||this.setEventListener(D(this,Zs))}onUnsubscribe(){var t;this.hasListeners()||((t=D(this,Yr))==null||t.call(this),ue(this,Yr,void 0))}setEventListener(t){var n;ue(this,Zs,t),(n=D(this,Yr))==null||n.call(this),ue(this,Yr,t(this.setOnline.bind(this)))}setOnline(t){D(this,Ys)!==t&&(ue(this,Ys,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return D(this,Ys)}},Ys=new WeakMap,Yr=new WeakMap,Zs=new WeakMap,Ow),ku=new BE;function HE(){let e,t;const n=new Promise((i,s)=>{e=i,t=s});n.status="pending",n.catch(()=>{});function r(i){Object.assign(n,i),delete n.resolve,delete n.reject}return n.resolve=i=>{r({status:"fulfilled",value:i}),e(i)},n.reject=i=>{r({status:"rejected",reason:i}),t(i)},n}function VE(e){return Math.min(1e3*2**e,3e4)}function e0(e){return(e??"online")==="online"?ku.isOnline():!0}var t0=class extends Error{constructor(e){super("CancelledError"),this.revert=e==null?void 0:e.revert,this.silent=e==null?void 0:e.silent}};function gf(e){return e instanceof t0}function n0(e){let t=!1,n=0,r=!1,i;const s=HE(),o=v=>{var x;r||(d(new t0(v)),(x=e.abort)==null||x.call(e))},a=()=>{t=!0},l=()=>{t=!1},u=()=>Zw.isFocused()&&(e.networkMode==="always"||ku.isOnline())&&e.canRun(),f=()=>e0(e.networkMode)&&e.canRun(),c=v=>{var x;r||(r=!0,(x=e.onSuccess)==null||x.call(e,v),i==null||i(),s.resolve(v))},d=v=>{var x;r||(r=!0,(x=e.onError)==null||x.call(e,v),i==null||i(),s.reject(v))},h=()=>new Promise(v=>{var x;i=m=>{(r||u())&&v(m)},(x=e.onPause)==null||x.call(e)}).then(()=>{var v;i=void 0,r||(v=e.onContinue)==null||v.call(e)}),g=()=>{if(r)return;let v;const x=n===0?e.initialPromise:void 0;try{v=x??e.fn()}catch(m){v=Promise.reject(m)}Promise.resolve(v).then(c).catch(m=>{var E;if(r)return;const p=e.retry??(vc?0:3),w=e.retryDelay??VE,S=typeof w=="function"?w(n,m):w,k=p===!0||typeof p=="number"&&nu()?void 0:h()).then(()=>{t?d(m):g()})})};return{promise:s,cancel:o,continue:()=>(i==null||i(),s),cancelRetry:a,continueRetry:l,canStart:f,start:()=>(f()?g():h().then(g),s)}}var WE=e=>setTimeout(e,0);function QE(){let e=[],t=0,n=a=>{a()},r=a=>{a()},i=WE;const s=a=>{t?e.push(a):i(()=>{n(a)})},o=()=>{const a=e;e=[],a.length&&i(()=>{r(()=>{a.forEach(l=>{n(l)})})})};return{batch:a=>{let l;t++;try{l=a()}finally{t--,t||o()}return l},batchCalls:a=>(...l)=>{s(()=>{a(...l)})},schedule:s,setNotifyFunction:a=>{n=a},setBatchNotifyFunction:a=>{r=a},setScheduler:a=>{i=a}}}var It=QE(),Hi,Iw,r0=(Iw=class{constructor(){Se(this,Hi)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),ME(this.gcTime)&&ue(this,Hi,setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(vc?1/0:5*60*1e3))}clearGcTimeout(){D(this,Hi)&&(clearTimeout(D(this,Hi)),ue(this,Hi,void 0))}},Hi=new WeakMap,Iw),eo,to,un,Vi,_t,Ya,Wi,Pn,vr,Lw,KE=(Lw=class extends r0{constructor(t){super();Se(this,Pn);Se(this,eo);Se(this,to);Se(this,un);Se(this,Vi);Se(this,_t);Se(this,Ya);Se(this,Wi);ue(this,Wi,!1),ue(this,Ya,t.defaultOptions),this.setOptions(t.options),this.observers=[],ue(this,Vi,t.client),ue(this,un,D(this,Vi).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,ue(this,eo,JE(this.options)),this.state=t.state??D(this,eo),this.scheduleGc()}get meta(){return this.options.meta}get promise(){var t;return(t=D(this,_t))==null?void 0:t.promise}setOptions(t){this.options={...D(this,Ya),...t},this.updateGcTime(this.options.gcTime)}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&D(this,un).remove(this)}setData(t,n){const r=$E(this.state.data,t,this.options);return St(this,Pn,vr).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t,n){St(this,Pn,vr).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){var r,i;const n=(r=D(this,_t))==null?void 0:r.promise;return(i=D(this,_t))==null||i.cancel(t),n?n.then(Cn).catch(Cn):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(D(this,eo))}isActive(){return this.observers.some(t=>FE(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===up||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStale(){return this.state.isInvalidated?!0:this.getObserversCount()>0?this.observers.some(t=>t.getCurrentResult().isStale):this.state.data===void 0}isStaleByTime(t=0){return this.state.isInvalidated||this.state.data===void 0||!NE(this.state.dataUpdatedAt,t)}onFocus(){var n;const t=this.observers.find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(n=D(this,_t))==null||n.continue()}onOnline(){var n;const t=this.observers.find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(n=D(this,_t))==null||n.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),D(this,un).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(D(this,_t)&&(D(this,Wi)?D(this,_t).cancel({revert:!0}):D(this,_t).cancelRetry()),this.scheduleGc()),D(this,un).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||St(this,Pn,vr).call(this,{type:"invalidate"})}fetch(t,n){var l,u,f;if(this.state.fetchStatus!=="idle"){if(this.state.data!==void 0&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(D(this,_t))return D(this,_t).continueRetry(),D(this,_t).promise}if(t&&this.setOptions(t),!this.options.queryFn){const c=this.observers.find(d=>d.options.queryFn);c&&this.setOptions(c.options)}const r=new AbortController,i=c=>{Object.defineProperty(c,"signal",{enumerable:!0,get:()=>(ue(this,Wi,!0),r.signal)})},s=()=>{const c=Yw(this.options,n),d={client:D(this,Vi),queryKey:this.queryKey,meta:this.meta};return i(d),ue(this,Wi,!1),this.options.persister?this.options.persister(c,d,this):c(d)},o={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:D(this,Vi),state:this.state,fetchFn:s};i(o),(l=this.options.behavior)==null||l.onFetch(o,this),ue(this,to,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((u=o.fetchOptions)==null?void 0:u.meta))&&St(this,Pn,vr).call(this,{type:"fetch",meta:(f=o.fetchOptions)==null?void 0:f.meta});const a=c=>{var d,h,g,v;gf(c)&&c.silent||St(this,Pn,vr).call(this,{type:"error",error:c}),gf(c)||((h=(d=D(this,un).config).onError)==null||h.call(d,c,this),(v=(g=D(this,un).config).onSettled)==null||v.call(g,this.state.data,c,this)),this.scheduleGc()};return ue(this,_t,n0({initialPromise:n==null?void 0:n.initialPromise,fn:o.fetchFn,abort:r.abort.bind(r),onSuccess:c=>{var d,h,g,v;if(c===void 0){a(new Error(`${this.queryHash} data is undefined`));return}try{this.setData(c)}catch(x){a(x);return}(h=(d=D(this,un).config).onSuccess)==null||h.call(d,c,this),(v=(g=D(this,un).config).onSettled)==null||v.call(g,c,this.state.error,this),this.scheduleGc()},onError:a,onFail:(c,d)=>{St(this,Pn,vr).call(this,{type:"failed",failureCount:c,error:d})},onPause:()=>{St(this,Pn,vr).call(this,{type:"pause"})},onContinue:()=>{St(this,Pn,vr).call(this,{type:"continue"})},retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:()=>!0})),D(this,_t).start()}},eo=new WeakMap,to=new WeakMap,un=new WeakMap,Vi=new WeakMap,_t=new WeakMap,Ya=new WeakMap,Wi=new WeakMap,Pn=new WeakSet,vr=function(t){const n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,...qE(r.data,this.options),fetchMeta:t.meta??null};case"success":return{...r,data:t.data,dataUpdateCount:r.dataUpdateCount+1,dataUpdatedAt:t.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const i=t.error;return gf(i)&&i.revert&&D(this,to)?{...D(this,to),fetchStatus:"idle"}:{...r,error:i,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error"};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),It.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),D(this,un).notify({query:this,type:"updated",action:t})})},Lw);function qE(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:e0(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function JE(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var Jn,Mw,GE=(Mw=class extends yc{constructor(t={}){super();Se(this,Jn);this.config=t,ue(this,Jn,new Map)}build(t,n,r){const i=n.queryKey,s=n.queryHash??lp(i,n);let o=this.get(s);return o||(o=new KE({client:t,queryKey:i,queryHash:s,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(i)}),this.add(o)),o}add(t){D(this,Jn).has(t.queryHash)||(D(this,Jn).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=D(this,Jn).get(t.queryHash);n&&(t.destroy(),n===t&&D(this,Jn).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){It.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return D(this,Jn).get(t)}getAll(){return[...D(this,Jn).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>pg(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>pg(t,r)):n}notify(t){It.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){It.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){It.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Jn=new WeakMap,Mw),Gn,Tt,Qi,Xn,Wr,Nw,XE=(Nw=class extends r0{constructor(t){super();Se(this,Xn);Se(this,Gn);Se(this,Tt);Se(this,Qi);this.mutationId=t.mutationId,ue(this,Tt,t.mutationCache),ue(this,Gn,[]),this.state=t.state||YE(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){D(this,Gn).includes(t)||(D(this,Gn).push(t),this.clearGcTimeout(),D(this,Tt).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){ue(this,Gn,D(this,Gn).filter(n=>n!==t)),this.scheduleGc(),D(this,Tt).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){D(this,Gn).length||(this.state.status==="pending"?this.scheduleGc():D(this,Tt).remove(this))}continue(){var t;return((t=D(this,Qi))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var s,o,a,l,u,f,c,d,h,g,v,x,m,p,w,S,k,E,y,R;const n=()=>{St(this,Xn,Wr).call(this,{type:"continue"})};ue(this,Qi,n0({fn:()=>this.options.mutationFn?this.options.mutationFn(t):Promise.reject(new Error("No mutationFn found")),onFail:(T,A)=>{St(this,Xn,Wr).call(this,{type:"failed",failureCount:T,error:A})},onPause:()=>{St(this,Xn,Wr).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>D(this,Tt).canRun(this)}));const r=this.state.status==="pending",i=!D(this,Qi).canStart();try{if(r)n();else{St(this,Xn,Wr).call(this,{type:"pending",variables:t,isPaused:i}),await((o=(s=D(this,Tt).config).onMutate)==null?void 0:o.call(s,t,this));const A=await((l=(a=this.options).onMutate)==null?void 0:l.call(a,t));A!==this.state.context&&St(this,Xn,Wr).call(this,{type:"pending",context:A,variables:t,isPaused:i})}const T=await D(this,Qi).start();return await((f=(u=D(this,Tt).config).onSuccess)==null?void 0:f.call(u,T,t,this.state.context,this)),await((d=(c=this.options).onSuccess)==null?void 0:d.call(c,T,t,this.state.context)),await((g=(h=D(this,Tt).config).onSettled)==null?void 0:g.call(h,T,null,this.state.variables,this.state.context,this)),await((x=(v=this.options).onSettled)==null?void 0:x.call(v,T,null,t,this.state.context)),St(this,Xn,Wr).call(this,{type:"success",data:T}),T}catch(T){try{throw await((p=(m=D(this,Tt).config).onError)==null?void 0:p.call(m,T,t,this.state.context,this)),await((S=(w=this.options).onError)==null?void 0:S.call(w,T,t,this.state.context)),await((E=(k=D(this,Tt).config).onSettled)==null?void 0:E.call(k,void 0,T,this.state.variables,this.state.context,this)),await((R=(y=this.options).onSettled)==null?void 0:R.call(y,void 0,T,t,this.state.context)),T}finally{St(this,Xn,Wr).call(this,{type:"error",error:T})}}finally{D(this,Tt).runNext(this)}}},Gn=new WeakMap,Tt=new WeakMap,Qi=new WeakMap,Xn=new WeakSet,Wr=function(t){const n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),It.batch(()=>{D(this,Gn).forEach(r=>{r.onMutationUpdate(t)}),D(this,Tt).notify({mutation:this,type:"updated",action:t})})},Nw);function YE(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Er,Rn,Za,Fw,ZE=(Fw=class extends yc{constructor(t={}){super();Se(this,Er);Se(this,Rn);Se(this,Za);this.config=t,ue(this,Er,new Set),ue(this,Rn,new Map),ue(this,Za,0)}build(t,n,r){const i=new XE({mutationCache:this,mutationId:++bl(this,Za)._,options:t.defaultMutationOptions(n),state:r});return this.add(i),i}add(t){D(this,Er).add(t);const n=Cl(t);if(typeof n=="string"){const r=D(this,Rn).get(n);r?r.push(t):D(this,Rn).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(D(this,Er).delete(t)){const n=Cl(t);if(typeof n=="string"){const r=D(this,Rn).get(n);if(r)if(r.length>1){const i=r.indexOf(t);i!==-1&&r.splice(i,1)}else r[0]===t&&D(this,Rn).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){const n=Cl(t);if(typeof n=="string"){const r=D(this,Rn).get(n),i=r==null?void 0:r.find(s=>s.state.status==="pending");return!i||i===t}else return!0}runNext(t){var r;const n=Cl(t);if(typeof n=="string"){const i=(r=D(this,Rn).get(n))==null?void 0:r.find(s=>s!==t&&s.state.isPaused);return(i==null?void 0:i.continue())??Promise.resolve()}else return Promise.resolve()}clear(){It.batch(()=>{D(this,Er).forEach(t=>{this.notify({type:"removed",mutation:t})}),D(this,Er).clear(),D(this,Rn).clear()})}getAll(){return Array.from(D(this,Er))}find(t){const n={exact:!0,...t};return this.getAll().find(r=>mg(n,r))}findAll(t={}){return this.getAll().filter(n=>mg(t,n))}notify(t){It.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){const t=this.getAll().filter(n=>n.state.isPaused);return It.batch(()=>Promise.all(t.map(n=>n.continue().catch(Cn))))}},Er=new WeakMap,Rn=new WeakMap,Za=new WeakMap,Fw);function Cl(e){var t;return(t=e.options.scope)==null?void 0:t.id}function vg(e){return{onFetch:(t,n)=>{var f,c,d,h,g;const r=t.options,i=(d=(c=(f=t.fetchOptions)==null?void 0:f.meta)==null?void 0:c.fetchMore)==null?void 0:d.direction,s=((h=t.state.data)==null?void 0:h.pages)||[],o=((g=t.state.data)==null?void 0:g.pageParams)||[];let a={pages:[],pageParams:[]},l=0;const u=async()=>{let v=!1;const x=w=>{Object.defineProperty(w,"signal",{enumerable:!0,get:()=>(t.signal.aborted?v=!0:t.signal.addEventListener("abort",()=>{v=!0}),t.signal)})},m=Yw(t.options,t.fetchOptions),p=async(w,S,k)=>{if(v)return Promise.reject();if(S==null&&w.pages.length)return Promise.resolve(w);const E={client:t.client,queryKey:t.queryKey,pageParam:S,direction:k?"backward":"forward",meta:t.options.meta};x(E);const y=await m(E),{maxPages:R}=t.options,T=k?zE:jE;return{pages:T(w.pages,y,R),pageParams:T(w.pageParams,S,R)}};if(i&&s.length){const w=i==="backward",S=w?eC:wg,k={pages:s,pageParams:o},E=S(r,k);a=await p(k,E,w)}else{const w=e??s.length;do{const S=l===0?o[0]??r.initialPageParam:wg(r,a);if(l>0&&S==null)break;a=await p(a,S),l++}while(l{var v,x;return(x=(v=t.options).persister)==null?void 0:x.call(v,u,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=u}}}function wg(e,{pages:t,pageParams:n}){const r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function eC(e,{pages:t,pageParams:n}){var r;return t.length>0?(r=e.getPreviousPageParam)==null?void 0:r.call(e,t[0],t,n[0],n):void 0}var We,Zr,ei,no,ro,ti,io,so,Dw,tC=(Dw=class{constructor(e={}){Se(this,We);Se(this,Zr);Se(this,ei);Se(this,no);Se(this,ro);Se(this,ti);Se(this,io);Se(this,so);ue(this,We,e.queryCache||new GE),ue(this,Zr,e.mutationCache||new ZE),ue(this,ei,e.defaultOptions||{}),ue(this,no,new Map),ue(this,ro,new Map),ue(this,ti,0)}mount(){bl(this,ti)._++,D(this,ti)===1&&(ue(this,io,Zw.subscribe(async e=>{e&&(await this.resumePausedMutations(),D(this,We).onFocus())})),ue(this,so,ku.subscribe(async e=>{e&&(await this.resumePausedMutations(),D(this,We).onOnline())})))}unmount(){var e,t;bl(this,ti)._--,D(this,ti)===0&&((e=D(this,io))==null||e.call(this),ue(this,io,void 0),(t=D(this,so))==null||t.call(this),ue(this,so,void 0))}isFetching(e){return D(this,We).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return D(this,Zr).findAll({...e,status:"pending"}).length}getQueryData(e){var n;const t=this.defaultQueryOptions({queryKey:e});return(n=D(this,We).get(t.queryHash))==null?void 0:n.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=D(this,We).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(hg(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return D(this,We).findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=this.defaultQueryOptions({queryKey:e}),i=D(this,We).get(r.queryHash),s=i==null?void 0:i.state.data,o=LE(t,s);if(o!==void 0)return D(this,We).build(this,r).setData(o,{...n,manual:!0})}setQueriesData(e,t,n){return It.batch(()=>D(this,We).findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){var n;const t=this.defaultQueryOptions({queryKey:e});return(n=D(this,We).get(t.queryHash))==null?void 0:n.state}removeQueries(e){const t=D(this,We);It.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=D(this,We);return It.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},r=It.batch(()=>D(this,We).findAll(e).map(i=>i.cancel(n)));return Promise.all(r).then(Cn).catch(Cn)}invalidateQueries(e,t={}){return It.batch(()=>(D(this,We).findAll(e).forEach(n=>{n.invalidate()}),(e==null?void 0:e.refetchType)==="none"?Promise.resolve():this.refetchQueries({...e,type:(e==null?void 0:e.refetchType)??(e==null?void 0:e.type)??"active"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},r=It.batch(()=>D(this,We).findAll(e).filter(i=>!i.isDisabled()).map(i=>{let s=i.fetch(void 0,n);return n.throwOnError||(s=s.catch(Cn)),i.state.fetchStatus==="paused"?Promise.resolve():s}));return Promise.all(r).then(Cn)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=D(this,We).build(this,t);return n.isStaleByTime(hg(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Cn).catch(Cn)}fetchInfiniteQuery(e){return e.behavior=vg(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Cn).catch(Cn)}ensureInfiniteQueryData(e){return e.behavior=vg(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return ku.isOnline()?D(this,Zr).resumePausedMutations():Promise.resolve()}getQueryCache(){return D(this,We)}getMutationCache(){return D(this,Zr)}getDefaultOptions(){return D(this,ei)}setDefaultOptions(e){ue(this,ei,e)}setQueryDefaults(e,t){D(this,no).set(Ca(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...D(this,no).values()],n={};return t.forEach(r=>{_a(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){D(this,ro).set(Ca(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...D(this,ro).values()],n={};return t.forEach(r=>{_a(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...D(this,ei).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=lp(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===up&&(t.enabled=!1),t}defaultMutationOptions(e){return e!=null&&e._defaulted?e:{...D(this,ei).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){D(this,We).clear(),D(this,Zr).clear()}},We=new WeakMap,Zr=new WeakMap,ei=new WeakMap,no=new WeakMap,ro=new WeakMap,ti=new WeakMap,io=new WeakMap,so=new WeakMap,Dw),i0=C.createContext(void 0),xD=e=>{const t=C.useContext(i0);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},nC=({client:e,children:t})=>(C.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),Y.jsx(i0.Provider,{value:e,children:t}));const rC="modulepreload",iC=function(e){return"/"+e},xg={},sC=function(t,n,r){let i=Promise.resolve();if(n&&n.length>0){document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),a=(o==null?void 0:o.nonce)||(o==null?void 0:o.getAttribute("nonce"));i=Promise.allSettled(n.map(l=>{if(l=iC(l),l in xg)return;xg[l]=!0;const u=l.endsWith(".css"),f=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${l}"]${f}`))return;const c=document.createElement("link");if(c.rel=u?"stylesheet":rC,u||(c.as="script"),c.crossOrigin="",c.href=l,a&&c.setAttribute("nonce",a),document.head.appendChild(c),u)return new Promise((d,h)=>{c.addEventListener("load",d),c.addEventListener("error",()=>h(new Error(`Unable to preload CSS for ${l}`)))})}))}function s(o){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=o,window.dispatchEvent(a),!a.defaultPrevented)throw o}return i.then(o=>{for(const a of o||[])a.status==="rejected"&&s(a.reason);return t().catch(s)})};globalThis.jotaiAtomCache=globalThis.jotaiAtomCache||{cache:new Map,get(e,t){return this.cache.has(e)?this.cache.get(e):(this.cache.set(e,t),t)}};class s0 extends Ki.Component{constructor(){super(...arguments);ln(this,"state",{error:void 0})}static getDerivedStateFromError(n){return{error:n}}componentDidCatch(n,r){console.error("Encountered ErrorBoundary:",n,r);const{onError:i}=this.props;i==null||i(n)}render(){const{error:n}=this.state;if(n!==void 0){const{renderError:i}=this.props;return i(n)}const{children:r}=this.props;return r}}ln(s0,"defaultProps",{children:void 0,onError:void 0});globalThis.jotaiAtomCache=globalThis.jotaiAtomCache||{cache:new Map,get(e,t){return this.cache.has(e)?this.cache.get(e):(this.cache.set(e,t),t)}};function Sg({error:e}){return Y.jsxs("div",{className:"flex min-h-screen flex-col items-center justify-center",children:[Y.jsx("h1",{className:"text-xl","data-testid":"LoadingOrError",children:e?e.message:Y.jsx("div",{role:"status",className:"h-16 w-16 animate-spin rounded-full bg-gradient-to-r from-purple-500 via-pink-500 to-red-500"})}),e?Y.jsx("a",{href:"/",className:"mt-5 text-lg text-blue-500 underline",onClick:t=>{t.preventDefault(),document.location.reload()},children:"Reload"}):void 0]})}function Sr(e,t,{checkForDefaultPrevented:n=!0}={}){return function(i){if(e==null||e(i),n===!1||!i.defaultPrevented)return t==null?void 0:t(i)}}function bg(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function o0(...e){return t=>{let n=!1;const r=e.map(i=>{const s=bg(i,t);return!n&&typeof s=="function"&&(n=!0),s});if(n)return()=>{for(let i=0;i{const{children:o,...a}=s,l=C.useMemo(()=>a,Object.values(a));return Y.jsx(n.Provider,{value:l,children:o})};r.displayName=e+"Provider";function i(s){const o=C.useContext(n);if(o)return o;if(t!==void 0)return t;throw new Error(`\`${s}\` must be used within \`${e}\``)}return[r,i]}function a0(e,t=[]){let n=[];function r(s,o){const a=C.createContext(o),l=n.length;n=[...n,o];const u=c=>{var m;const{scope:d,children:h,...g}=c,v=((m=d==null?void 0:d[e])==null?void 0:m[l])||a,x=C.useMemo(()=>g,Object.values(g));return Y.jsx(v.Provider,{value:x,children:h})};u.displayName=s+"Provider";function f(c,d){var v;const h=((v=d==null?void 0:d[e])==null?void 0:v[l])||a,g=C.useContext(h);if(g)return g;if(o!==void 0)return o;throw new Error(`\`${c}\` must be used within \`${s}\``)}return[u,f]}const i=()=>{const s=n.map(o=>C.createContext(o));return function(a){const l=(a==null?void 0:a[e])||s;return C.useMemo(()=>({[`__scope${e}`]:{...a,[e]:l}}),[a,l])}};return i.scopeName=e,[r,oC(i,...t)]}function oC(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(i=>({useScope:i(),scopeName:i.scopeName}));return function(s){const o=r.reduce((a,{useScope:l,scopeName:u})=>{const c=l(s)[`__scope${u}`];return{...a,...c}},{});return C.useMemo(()=>({[`__scope${t.scopeName}`]:o}),[o])}};return n.scopeName=t.scopeName,n}var l0={exports:{}},rn={},u0={exports:{}},c0={};/** * @license React * scheduler.production.min.js * @@ -22,7 +22,7 @@ var cE=Object.defineProperty;var ug=e=>{throw TypeError(e)};var fE=(e,t,n)=>t in * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - */(function(e){function t(M,U){var b=M.length;M.push(U);e:for(;0>>1,pe=M[Z];if(0>>1;Zi(Le,b))yei(qe,Le)?(M[Z]=qe,M[ye]=b,Z=ye):(M[Z]=Le,M[Ae]=b,Z=Ae);else if(yei(qe,b))M[Z]=qe,M[ye]=b,Z=ye;else break e}}return U}function i(M,U){var b=M.sortIndex-U.sortIndex;return b!==0?b:M.id-U.id}if(typeof performance=="object"&&typeof performance.now=="function"){var s=performance;e.unstable_now=function(){return s.now()}}else{var o=Date,a=o.now();e.unstable_now=function(){return o.now()-a}}var l=[],u=[],f=1,c=null,d=3,h=!1,g=!1,v=!1,x=typeof setTimeout=="function"?setTimeout:null,m=typeof clearTimeout=="function"?clearTimeout:null,p=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function w(M){for(var U=n(u);U!==null;){if(U.callback===null)r(u);else if(U.startTime<=M)r(u),U.sortIndex=U.expirationTime,t(l,U);else break;U=n(u)}}function S(M){if(v=!1,w(M),!g)if(n(l)!==null)g=!0,G(k);else{var U=n(u);U!==null&&Q(S,U.startTime-M)}}function k(M,U){g=!1,v&&(v=!1,m(R),R=-1),h=!0;var b=d;try{for(w(U),c=n(l);c!==null&&(!(c.expirationTime>U)||M&&!O());){var Z=c.callback;if(typeof Z=="function"){c.callback=null,d=c.priorityLevel;var pe=Z(c.expirationTime<=U);U=e.unstable_now(),typeof pe=="function"?c.callback=pe:c===n(l)&&r(l),w(U)}else r(l);c=n(l)}if(c!==null)var C=!0;else{var Ae=n(u);Ae!==null&&Q(S,Ae.startTime-U),C=!1}return C}finally{c=null,d=b,h=!1}}var E=!1,y=null,R=-1,T=5,A=-1;function O(){return!(e.unstable_now()-AM||125Z?(M.sortIndex=b,t(u,M),n(l)===null&&M===n(u)&&(v?(m(R),R=-1):v=!0,Q(S,b-Z))):(M.sortIndex=pe,t(l,M),g||h||(g=!0,G(k))),M},e.unstable_shouldYield=O,e.unstable_wrapCallback=function(M){var U=d;return function(){var b=d;d=U;try{return M.apply(this,arguments)}finally{d=b}}}})(c0);u0.exports=c0;var a_=u0.exports;/** + */(function(e){function t(M,U){var b=M.length;M.push(U);e:for(;0>>1,pe=M[Z];if(0>>1;Z<_;){var Ae=2*(Z+1)-1,Le=M[Ae],ye=Ae+1,qe=M[ye];if(0>i(Le,b))yei(qe,Le)?(M[Z]=qe,M[ye]=b,Z=ye):(M[Z]=Le,M[Ae]=b,Z=Ae);else if(yei(qe,b))M[Z]=qe,M[ye]=b,Z=ye;else break e}}return U}function i(M,U){var b=M.sortIndex-U.sortIndex;return b!==0?b:M.id-U.id}if(typeof performance=="object"&&typeof performance.now=="function"){var s=performance;e.unstable_now=function(){return s.now()}}else{var o=Date,a=o.now();e.unstable_now=function(){return o.now()-a}}var l=[],u=[],f=1,c=null,d=3,h=!1,g=!1,v=!1,x=typeof setTimeout=="function"?setTimeout:null,m=typeof clearTimeout=="function"?clearTimeout:null,p=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function w(M){for(var U=n(u);U!==null;){if(U.callback===null)r(u);else if(U.startTime<=M)r(u),U.sortIndex=U.expirationTime,t(l,U);else break;U=n(u)}}function S(M){if(v=!1,w(M),!g)if(n(l)!==null)g=!0,G(k);else{var U=n(u);U!==null&&Q(S,U.startTime-M)}}function k(M,U){g=!1,v&&(v=!1,m(R),R=-1),h=!0;var b=d;try{for(w(U),c=n(l);c!==null&&(!(c.expirationTime>U)||M&&!O());){var Z=c.callback;if(typeof Z=="function"){c.callback=null,d=c.priorityLevel;var pe=Z(c.expirationTime<=U);U=e.unstable_now(),typeof pe=="function"?c.callback=pe:c===n(l)&&r(l),w(U)}else r(l);c=n(l)}if(c!==null)var _=!0;else{var Ae=n(u);Ae!==null&&Q(S,Ae.startTime-U),_=!1}return _}finally{c=null,d=b,h=!1}}var E=!1,y=null,R=-1,T=5,A=-1;function O(){return!(e.unstable_now()-AM||125Z?(M.sortIndex=b,t(u,M),n(l)===null&&M===n(u)&&(v?(m(R),R=-1):v=!0,Q(S,b-Z))):(M.sortIndex=pe,t(l,M),g||h||(g=!0,G(k))),M},e.unstable_shouldYield=O,e.unstable_wrapCallback=function(M){var U=d;return function(){var b=d;d=U;try{return M.apply(this,arguments)}finally{d=b}}}})(c0);u0.exports=c0;var aC=u0.exports;/** * @license React * react-dom.production.min.js * @@ -30,14 +30,14 @@ var cE=Object.defineProperty;var ug=e=>{throw TypeError(e)};var fE=(e,t,n)=>t in * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - */var l_=_,nn=a_;function j(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),kd=Object.prototype.hasOwnProperty,u_=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,Eg={},_g={};function c_(e){return kd.call(_g,e)?!0:kd.call(Eg,e)?!1:u_.test(e)?_g[e]=!0:(Eg[e]=!0,!1)}function f_(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function d_(e,t,n,r){if(t===null||typeof t>"u"||f_(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function Nt(e,t,n,r,i,s,o){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=i,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=s,this.removeEmptyString=o}var pt={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){pt[e]=new Nt(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];pt[t]=new Nt(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){pt[e]=new Nt(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){pt[e]=new Nt(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){pt[e]=new Nt(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){pt[e]=new Nt(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){pt[e]=new Nt(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){pt[e]=new Nt(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){pt[e]=new Nt(e,5,!1,e.toLowerCase(),null,!1,!1)});var cp=/[\-:]([a-z])/g;function fp(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(cp,fp);pt[t]=new Nt(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(cp,fp);pt[t]=new Nt(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(cp,fp);pt[t]=new Nt(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){pt[e]=new Nt(e,1,!1,e.toLowerCase(),null,!1,!1)});pt.xlinkHref=new Nt("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){pt[e]=new Nt(e,1,!1,e.toLowerCase(),null,!0,!0)});function dp(e,t,n,r){var i=pt.hasOwnProperty(t)?pt[t]:null;(i!==null?i.type!==0:r||!(2"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),kd=Object.prototype.hasOwnProperty,uC=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,Eg={},Cg={};function cC(e){return kd.call(Cg,e)?!0:kd.call(Eg,e)?!1:uC.test(e)?Cg[e]=!0:(Eg[e]=!0,!1)}function fC(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function dC(e,t,n,r){if(t===null||typeof t>"u"||fC(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function Nt(e,t,n,r,i,s,o){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=i,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=s,this.removeEmptyString=o}var pt={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){pt[e]=new Nt(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];pt[t]=new Nt(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){pt[e]=new Nt(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){pt[e]=new Nt(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){pt[e]=new Nt(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){pt[e]=new Nt(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){pt[e]=new Nt(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){pt[e]=new Nt(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){pt[e]=new Nt(e,5,!1,e.toLowerCase(),null,!1,!1)});var cp=/[\-:]([a-z])/g;function fp(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(cp,fp);pt[t]=new Nt(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(cp,fp);pt[t]=new Nt(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(cp,fp);pt[t]=new Nt(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){pt[e]=new Nt(e,1,!1,e.toLowerCase(),null,!1,!1)});pt.xlinkHref=new Nt("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){pt[e]=new Nt(e,1,!1,e.toLowerCase(),null,!0,!0)});function dp(e,t,n,r){var i=pt.hasOwnProperty(t)?pt[t]:null;(i!==null?i.type!==0:r||!(2a||i[o]!==s[a]){var l=` -`+i[o].replace(" at new "," at ");return e.displayName&&l.includes("")&&(l=l.replace("",e.displayName)),l}while(1<=o&&0<=a);break}}}finally{vf=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?Xo(e):""}function h_(e){switch(e.tag){case 5:return Xo(e.type);case 16:return Xo("Lazy");case 13:return Xo("Suspense");case 19:return Xo("SuspenseList");case 0:case 2:case 15:return e=wf(e.type,!1),e;case 11:return e=wf(e.type.render,!1),e;case 1:return e=wf(e.type,!0),e;default:return""}}function Td(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case Ps:return"Fragment";case ks:return"Portal";case Pd:return"Profiler";case hp:return"StrictMode";case Rd:return"Suspense";case Ad:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case h0:return(e.displayName||"Context")+".Consumer";case d0:return(e._context.displayName||"Context")+".Provider";case pp:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case mp:return t=e.displayName||null,t!==null?t:Td(e.type)||"Memo";case Kr:t=e._payload,e=e._init;try{return Td(e(t))}catch{}}return null}function p_(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return Td(t);case 8:return t===hp?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function pi(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function m0(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function m_(e){var t=m0(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var i=n.get,s=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return i.call(this)},set:function(o){r=""+o,s.call(this,o)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(o){r=""+o},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function kl(e){e._valueTracker||(e._valueTracker=m_(e))}function g0(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=m0(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function Pu(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function Od(e,t){var n=t.checked;return Be({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function kg(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=pi(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function y0(e,t){t=t.checked,t!=null&&dp(e,"checked",t,!1)}function Id(e,t){y0(e,t);var n=pi(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?Ld(e,t.type,n):t.hasOwnProperty("defaultValue")&&Ld(e,t.type,pi(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function Pg(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function Ld(e,t,n){(t!=="number"||Pu(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var Yo=Array.isArray;function js(e,t,n,r){if(e=e.options,t){t={};for(var i=0;i"+t.valueOf().toString()+"",t=Pl.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Pa(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var ca={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},g_=["Webkit","ms","Moz","O"];Object.keys(ca).forEach(function(e){g_.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),ca[t]=ca[e]})});function S0(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||ca.hasOwnProperty(e)&&ca[e]?(""+t).trim():t+"px"}function b0(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,i=S0(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,i):e[n]=i}}var y_=Be({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function Fd(e,t){if(t){if(y_[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(j(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(j(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(j(61))}if(t.style!=null&&typeof t.style!="object")throw Error(j(62))}}function Dd(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var $d=null;function gp(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var jd=null,zs=null,Us=null;function Tg(e){if(e=rl(e)){if(typeof jd!="function")throw Error(j(280));var t=e.stateNode;t&&(t=Ec(t),jd(e.stateNode,e.type,t))}}function E0(e){zs?Us?Us.push(e):Us=[e]:zs=e}function _0(){if(zs){var e=zs,t=Us;if(Us=zs=null,Tg(e),t)for(e=0;e>>=0,e===0?32:31-(R_(e)/A_|0)|0}var Rl=64,Al=4194304;function Zo(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function Ou(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,i=e.suspendedLanes,s=e.pingedLanes,o=n&268435455;if(o!==0){var a=o&~i;a!==0?r=Zo(a):(s&=o,s!==0&&(r=Zo(s)))}else o=n&~i,o!==0?r=Zo(o):s!==0&&(r=Zo(s));if(r===0)return 0;if(t!==0&&t!==r&&!(t&i)&&(i=r&-r,s=t&-t,i>=s||i===16&&(s&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function tl(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-Mn(t),e[t]=n}function L_(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=da),jg=" ",zg=!1;function V0(e,t){switch(e){case"keyup":return aC.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function W0(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Rs=!1;function uC(e,t){switch(e){case"compositionend":return W0(t);case"keypress":return t.which!==32?null:(zg=!0,jg);case"textInput":return e=t.data,e===jg&&zg?null:e;default:return null}}function cC(e,t){if(Rs)return e==="compositionend"||!_p&&V0(e,t)?(e=B0(),ou=Sp=ni=null,Rs=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=Vg(n)}}function J0(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?J0(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function G0(){for(var e=window,t=Pu();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=Pu(e.document)}return t}function Cp(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function wC(e){var t=G0(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&J0(n.ownerDocument.documentElement,n)){if(r!==null&&Cp(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var i=n.textContent.length,s=Math.min(r.start,i);r=r.end===void 0?s:Math.min(r.end,i),!e.extend&&s>r&&(i=r,r=s,s=i),i=Wg(n,s);var o=Wg(n,r);i&&o&&(e.rangeCount!==1||e.anchorNode!==i.node||e.anchorOffset!==i.offset||e.focusNode!==o.node||e.focusOffset!==o.offset)&&(t=t.createRange(),t.setStart(i.node,i.offset),e.removeAllRanges(),s>r?(e.addRange(t),e.extend(o.node,o.offset)):(t.setEnd(o.node,o.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,As=null,Wd=null,pa=null,Qd=!1;function Qg(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Qd||As==null||As!==Pu(r)||(r=As,"selectionStart"in r&&Cp(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),pa&&La(pa,r)||(pa=r,r=Mu(Wd,"onSelect"),0Is||(e.current=Yd[Is],Yd[Is]=null,Is--)}function Oe(e,t){Is++,Yd[Is]=e.current,e.current=t}var mi={},Pt=bi(mi),Bt=bi(!1),Gi=mi;function ao(e,t){var n=e.type.contextTypes;if(!n)return mi;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var i={},s;for(s in n)i[s]=t[s];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=i),i}function Ht(e){return e=e.childContextTypes,e!=null}function Fu(){Fe(Bt),Fe(Pt)}function Zg(e,t,n){if(Pt.current!==mi)throw Error(j(168));Oe(Pt,t),Oe(Bt,n)}function sx(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var i in r)if(!(i in t))throw Error(j(108,p_(e)||"Unknown",i));return Be({},n,r)}function Du(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||mi,Gi=Pt.current,Oe(Pt,e),Oe(Bt,Bt.current),!0}function ey(e,t,n){var r=e.stateNode;if(!r)throw Error(j(169));n?(e=sx(e,t,Gi),r.__reactInternalMemoizedMergedChildContext=e,Fe(Bt),Fe(Pt),Oe(Pt,e)):Fe(Bt),Oe(Bt,n)}var br=null,_c=!1,Lf=!1;function ox(e){br===null?br=[e]:br.push(e)}function OC(e){_c=!0,ox(e)}function Ei(){if(!Lf&&br!==null){Lf=!0;var e=0,t=Pe;try{var n=br;for(Pe=1;e>=o,i-=o,_r=1<<32-Mn(t)+i|n<R?(T=y,y=null):T=y.sibling;var A=d(m,y,w[R],S);if(A===null){y===null&&(y=T);break}e&&y&&A.alternate===null&&t(m,y),p=s(A,p,R),E===null?k=A:E.sibling=A,E=A,y=T}if(R===w.length)return n(m,y),$e&&Ii(m,R),k;if(y===null){for(;RR?(T=y,y=null):T=y.sibling;var O=d(m,y,A.value,S);if(O===null){y===null&&(y=T);break}e&&y&&O.alternate===null&&t(m,y),p=s(O,p,R),E===null?k=O:E.sibling=O,E=O,y=T}if(A.done)return n(m,y),$e&&Ii(m,R),k;if(y===null){for(;!A.done;R++,A=w.next())A=c(m,A.value,S),A!==null&&(p=s(A,p,R),E===null?k=A:E.sibling=A,E=A);return $e&&Ii(m,R),k}for(y=r(m,y);!A.done;R++,A=w.next())A=h(y,m,R,A.value,S),A!==null&&(e&&A.alternate!==null&&y.delete(A.key===null?R:A.key),p=s(A,p,R),E===null?k=A:E.sibling=A,E=A);return e&&y.forEach(function(I){return t(m,I)}),$e&&Ii(m,R),k}function x(m,p,w,S){if(typeof w=="object"&&w!==null&&w.type===Ps&&w.key===null&&(w=w.props.children),typeof w=="object"&&w!==null){switch(w.$$typeof){case Cl:e:{for(var k=w.key,E=p;E!==null;){if(E.key===k){if(k=w.type,k===Ps){if(E.tag===7){n(m,E.sibling),p=i(E,w.props.children),p.return=m,m=p;break e}}else if(E.elementType===k||typeof k=="object"&&k!==null&&k.$$typeof===Kr&&ry(k)===E.type){n(m,E.sibling),p=i(E,w.props),p.ref=zo(m,E,w),p.return=m,m=p;break e}n(m,E);break}else t(m,E);E=E.sibling}w.type===Ps?(p=Ji(w.props.children,m.mode,S,w.key),p.return=m,m=p):(S=pu(w.type,w.key,w.props,null,m.mode,S),S.ref=zo(m,p,w),S.return=m,m=S)}return o(m);case ks:e:{for(E=w.key;p!==null;){if(p.key===E)if(p.tag===4&&p.stateNode.containerInfo===w.containerInfo&&p.stateNode.implementation===w.implementation){n(m,p.sibling),p=i(p,w.children||[]),p.return=m,m=p;break e}else{n(m,p);break}else t(m,p);p=p.sibling}p=Uf(w,m.mode,S),p.return=m,m=p}return o(m);case Kr:return E=w._init,x(m,p,E(w._payload),S)}if(Yo(w))return g(m,p,w,S);if(No(w))return v(m,p,w,S);Fl(m,w)}return typeof w=="string"&&w!==""||typeof w=="number"?(w=""+w,p!==null&&p.tag===6?(n(m,p.sibling),p=i(p,w),p.return=m,m=p):(n(m,p),p=zf(w,m.mode,S),p.return=m,m=p),o(m)):n(m,p)}return x}var uo=cx(!0),fx=cx(!1),zu=bi(null),Uu=null,Ns=null,Ap=null;function Tp(){Ap=Ns=Uu=null}function Op(e){var t=zu.current;Fe(zu),e._currentValue=t}function th(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function Hs(e,t){Uu=e,Ap=Ns=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(Ut=!0),e.firstContext=null)}function gn(e){var t=e._currentValue;if(Ap!==e)if(e={context:e,memoizedValue:t,next:null},Ns===null){if(Uu===null)throw Error(j(308));Ns=e,Uu.dependencies={lanes:0,firstContext:e}}else Ns=Ns.next=e;return t}var $i=null;function Ip(e){$i===null?$i=[e]:$i.push(e)}function dx(e,t,n,r){var i=t.interleaved;return i===null?(n.next=n,Ip(t)):(n.next=i.next,i.next=n),t.interleaved=n,Ar(e,r)}function Ar(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var qr=!1;function Lp(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function hx(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function kr(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function ui(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,we&2){var i=r.pending;return i===null?t.next=t:(t.next=i.next,i.next=t),r.pending=t,Ar(e,n)}return i=r.interleaved,i===null?(t.next=t,Ip(r)):(t.next=i.next,i.next=t),r.interleaved=t,Ar(e,n)}function lu(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,vp(e,n)}}function iy(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var i=null,s=null;if(n=n.firstBaseUpdate,n!==null){do{var o={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};s===null?i=s=o:s=s.next=o,n=n.next}while(n!==null);s===null?i=s=t:s=s.next=t}else i=s=t;n={baseState:r.baseState,firstBaseUpdate:i,lastBaseUpdate:s,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function Bu(e,t,n,r){var i=e.updateQueue;qr=!1;var s=i.firstBaseUpdate,o=i.lastBaseUpdate,a=i.shared.pending;if(a!==null){i.shared.pending=null;var l=a,u=l.next;l.next=null,o===null?s=u:o.next=u,o=l;var f=e.alternate;f!==null&&(f=f.updateQueue,a=f.lastBaseUpdate,a!==o&&(a===null?f.firstBaseUpdate=u:a.next=u,f.lastBaseUpdate=l))}if(s!==null){var c=i.baseState;o=0,f=u=l=null,a=s;do{var d=a.lane,h=a.eventTime;if((r&d)===d){f!==null&&(f=f.next={eventTime:h,lane:0,tag:a.tag,payload:a.payload,callback:a.callback,next:null});e:{var g=e,v=a;switch(d=t,h=n,v.tag){case 1:if(g=v.payload,typeof g=="function"){c=g.call(h,c,d);break e}c=g;break e;case 3:g.flags=g.flags&-65537|128;case 0:if(g=v.payload,d=typeof g=="function"?g.call(h,c,d):g,d==null)break e;c=Be({},c,d);break e;case 2:qr=!0}}a.callback!==null&&a.lane!==0&&(e.flags|=64,d=i.effects,d===null?i.effects=[a]:d.push(a))}else h={eventTime:h,lane:d,tag:a.tag,payload:a.payload,callback:a.callback,next:null},f===null?(u=f=h,l=c):f=f.next=h,o|=d;if(a=a.next,a===null){if(a=i.shared.pending,a===null)break;d=a,a=d.next,d.next=null,i.lastBaseUpdate=d,i.shared.pending=null}}while(!0);if(f===null&&(l=c),i.baseState=l,i.firstBaseUpdate=u,i.lastBaseUpdate=f,t=i.shared.interleaved,t!==null){i=t;do o|=i.lane,i=i.next;while(i!==t)}else s===null&&(i.shared.lanes=0);Zi|=o,e.lanes=o,e.memoizedState=c}}function sy(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=Nf.transition;Nf.transition={};try{e(!1),t()}finally{Pe=n,Nf.transition=r}}function Tx(){return yn().memoizedState}function NC(e,t,n){var r=fi(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Ox(e))Ix(t,n);else if(n=dx(e,t,n,r),n!==null){var i=Lt();Nn(n,e,r,i),Lx(n,t,r)}}function FC(e,t,n){var r=fi(e),i={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Ox(e))Ix(t,i);else{var s=e.alternate;if(e.lanes===0&&(s===null||s.lanes===0)&&(s=t.lastRenderedReducer,s!==null))try{var o=t.lastRenderedState,a=s(o,n);if(i.hasEagerState=!0,i.eagerState=a,Fn(a,o)){var l=t.interleaved;l===null?(i.next=i,Ip(t)):(i.next=l.next,l.next=i),t.interleaved=i;return}}catch{}finally{}n=dx(e,t,i,r),n!==null&&(i=Lt(),Nn(n,e,r,i),Lx(n,t,r))}}function Ox(e){var t=e.alternate;return e===Ue||t!==null&&t===Ue}function Ix(e,t){ma=Vu=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Lx(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,vp(e,n)}}var Wu={readContext:gn,useCallback:bt,useContext:bt,useEffect:bt,useImperativeHandle:bt,useInsertionEffect:bt,useLayoutEffect:bt,useMemo:bt,useReducer:bt,useRef:bt,useState:bt,useDebugValue:bt,useDeferredValue:bt,useTransition:bt,useMutableSource:bt,useSyncExternalStore:bt,useId:bt,unstable_isNewReconciler:!1},DC={readContext:gn,useCallback:function(e,t){return Wn().memoizedState=[e,t===void 0?null:t],e},useContext:gn,useEffect:ay,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,cu(4194308,4,Cx.bind(null,t,e),n)},useLayoutEffect:function(e,t){return cu(4194308,4,e,t)},useInsertionEffect:function(e,t){return cu(4,2,e,t)},useMemo:function(e,t){var n=Wn();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Wn();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=NC.bind(null,Ue,e),[r.memoizedState,e]},useRef:function(e){var t=Wn();return e={current:e},t.memoizedState=e},useState:oy,useDebugValue:Up,useDeferredValue:function(e){return Wn().memoizedState=e},useTransition:function(){var e=oy(!1),t=e[0];return e=MC.bind(null,e[1]),Wn().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=Ue,i=Wn();if($e){if(n===void 0)throw Error(j(407));n=n()}else{if(n=t(),lt===null)throw Error(j(349));Yi&30||yx(r,t,n)}i.memoizedState=n;var s={value:n,getSnapshot:t};return i.queue=s,ay(wx.bind(null,r,s,e),[e]),r.flags|=2048,Ua(9,vx.bind(null,r,s,n,t),void 0,null),n},useId:function(){var e=Wn(),t=lt.identifierPrefix;if($e){var n=Cr,r=_r;n=(r&~(1<<32-Mn(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=ja++,0")&&(l=l.replace("",e.displayName)),l}while(1<=o&&0<=a);break}}}finally{vf=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?Xo(e):""}function hC(e){switch(e.tag){case 5:return Xo(e.type);case 16:return Xo("Lazy");case 13:return Xo("Suspense");case 19:return Xo("SuspenseList");case 0:case 2:case 15:return e=wf(e.type,!1),e;case 11:return e=wf(e.type.render,!1),e;case 1:return e=wf(e.type,!0),e;default:return""}}function Td(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case Ps:return"Fragment";case ks:return"Portal";case Pd:return"Profiler";case hp:return"StrictMode";case Rd:return"Suspense";case Ad:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case h0:return(e.displayName||"Context")+".Consumer";case d0:return(e._context.displayName||"Context")+".Provider";case pp:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case mp:return t=e.displayName||null,t!==null?t:Td(e.type)||"Memo";case Kr:t=e._payload,e=e._init;try{return Td(e(t))}catch{}}return null}function pC(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return Td(t);case 8:return t===hp?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function pi(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function m0(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function mC(e){var t=m0(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var i=n.get,s=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return i.call(this)},set:function(o){r=""+o,s.call(this,o)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(o){r=""+o},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function kl(e){e._valueTracker||(e._valueTracker=mC(e))}function g0(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=m0(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function Pu(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function Od(e,t){var n=t.checked;return Be({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function kg(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=pi(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function y0(e,t){t=t.checked,t!=null&&dp(e,"checked",t,!1)}function Id(e,t){y0(e,t);var n=pi(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?Ld(e,t.type,n):t.hasOwnProperty("defaultValue")&&Ld(e,t.type,pi(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function Pg(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function Ld(e,t,n){(t!=="number"||Pu(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var Yo=Array.isArray;function js(e,t,n,r){if(e=e.options,t){t={};for(var i=0;i"+t.valueOf().toString()+"",t=Pl.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Pa(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var ca={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},gC=["Webkit","ms","Moz","O"];Object.keys(ca).forEach(function(e){gC.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),ca[t]=ca[e]})});function S0(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||ca.hasOwnProperty(e)&&ca[e]?(""+t).trim():t+"px"}function b0(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,i=S0(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,i):e[n]=i}}var yC=Be({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function Fd(e,t){if(t){if(yC[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(j(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(j(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(j(61))}if(t.style!=null&&typeof t.style!="object")throw Error(j(62))}}function Dd(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var $d=null;function gp(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var jd=null,zs=null,Us=null;function Tg(e){if(e=rl(e)){if(typeof jd!="function")throw Error(j(280));var t=e.stateNode;t&&(t=Ec(t),jd(e.stateNode,e.type,t))}}function E0(e){zs?Us?Us.push(e):Us=[e]:zs=e}function C0(){if(zs){var e=zs,t=Us;if(Us=zs=null,Tg(e),t)for(e=0;e>>=0,e===0?32:31-(RC(e)/AC|0)|0}var Rl=64,Al=4194304;function Zo(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function Ou(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,i=e.suspendedLanes,s=e.pingedLanes,o=n&268435455;if(o!==0){var a=o&~i;a!==0?r=Zo(a):(s&=o,s!==0&&(r=Zo(s)))}else o=n&~i,o!==0?r=Zo(o):s!==0&&(r=Zo(s));if(r===0)return 0;if(t!==0&&t!==r&&!(t&i)&&(i=r&-r,s=t&-t,i>=s||i===16&&(s&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function tl(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-Mn(t),e[t]=n}function LC(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=da),jg=" ",zg=!1;function V0(e,t){switch(e){case"keyup":return a_.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function W0(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Rs=!1;function u_(e,t){switch(e){case"compositionend":return W0(t);case"keypress":return t.which!==32?null:(zg=!0,jg);case"textInput":return e=t.data,e===jg&&zg?null:e;default:return null}}function c_(e,t){if(Rs)return e==="compositionend"||!Cp&&V0(e,t)?(e=B0(),ou=Sp=ni=null,Rs=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=Vg(n)}}function J0(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?J0(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function G0(){for(var e=window,t=Pu();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=Pu(e.document)}return t}function _p(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function w_(e){var t=G0(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&J0(n.ownerDocument.documentElement,n)){if(r!==null&&_p(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var i=n.textContent.length,s=Math.min(r.start,i);r=r.end===void 0?s:Math.min(r.end,i),!e.extend&&s>r&&(i=r,r=s,s=i),i=Wg(n,s);var o=Wg(n,r);i&&o&&(e.rangeCount!==1||e.anchorNode!==i.node||e.anchorOffset!==i.offset||e.focusNode!==o.node||e.focusOffset!==o.offset)&&(t=t.createRange(),t.setStart(i.node,i.offset),e.removeAllRanges(),s>r?(e.addRange(t),e.extend(o.node,o.offset)):(t.setEnd(o.node,o.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,As=null,Wd=null,pa=null,Qd=!1;function Qg(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Qd||As==null||As!==Pu(r)||(r=As,"selectionStart"in r&&_p(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),pa&&La(pa,r)||(pa=r,r=Mu(Wd,"onSelect"),0Is||(e.current=Yd[Is],Yd[Is]=null,Is--)}function Oe(e,t){Is++,Yd[Is]=e.current,e.current=t}var mi={},Pt=bi(mi),Bt=bi(!1),Gi=mi;function ao(e,t){var n=e.type.contextTypes;if(!n)return mi;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var i={},s;for(s in n)i[s]=t[s];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=i),i}function Ht(e){return e=e.childContextTypes,e!=null}function Fu(){Fe(Bt),Fe(Pt)}function Zg(e,t,n){if(Pt.current!==mi)throw Error(j(168));Oe(Pt,t),Oe(Bt,n)}function sx(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var i in r)if(!(i in t))throw Error(j(108,pC(e)||"Unknown",i));return Be({},n,r)}function Du(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||mi,Gi=Pt.current,Oe(Pt,e),Oe(Bt,Bt.current),!0}function ey(e,t,n){var r=e.stateNode;if(!r)throw Error(j(169));n?(e=sx(e,t,Gi),r.__reactInternalMemoizedMergedChildContext=e,Fe(Bt),Fe(Pt),Oe(Pt,e)):Fe(Bt),Oe(Bt,n)}var br=null,Cc=!1,Lf=!1;function ox(e){br===null?br=[e]:br.push(e)}function O_(e){Cc=!0,ox(e)}function Ei(){if(!Lf&&br!==null){Lf=!0;var e=0,t=Pe;try{var n=br;for(Pe=1;e>=o,i-=o,Cr=1<<32-Mn(t)+i|n<R?(T=y,y=null):T=y.sibling;var A=d(m,y,w[R],S);if(A===null){y===null&&(y=T);break}e&&y&&A.alternate===null&&t(m,y),p=s(A,p,R),E===null?k=A:E.sibling=A,E=A,y=T}if(R===w.length)return n(m,y),$e&&Ii(m,R),k;if(y===null){for(;RR?(T=y,y=null):T=y.sibling;var O=d(m,y,A.value,S);if(O===null){y===null&&(y=T);break}e&&y&&O.alternate===null&&t(m,y),p=s(O,p,R),E===null?k=O:E.sibling=O,E=O,y=T}if(A.done)return n(m,y),$e&&Ii(m,R),k;if(y===null){for(;!A.done;R++,A=w.next())A=c(m,A.value,S),A!==null&&(p=s(A,p,R),E===null?k=A:E.sibling=A,E=A);return $e&&Ii(m,R),k}for(y=r(m,y);!A.done;R++,A=w.next())A=h(y,m,R,A.value,S),A!==null&&(e&&A.alternate!==null&&y.delete(A.key===null?R:A.key),p=s(A,p,R),E===null?k=A:E.sibling=A,E=A);return e&&y.forEach(function(I){return t(m,I)}),$e&&Ii(m,R),k}function x(m,p,w,S){if(typeof w=="object"&&w!==null&&w.type===Ps&&w.key===null&&(w=w.props.children),typeof w=="object"&&w!==null){switch(w.$$typeof){case _l:e:{for(var k=w.key,E=p;E!==null;){if(E.key===k){if(k=w.type,k===Ps){if(E.tag===7){n(m,E.sibling),p=i(E,w.props.children),p.return=m,m=p;break e}}else if(E.elementType===k||typeof k=="object"&&k!==null&&k.$$typeof===Kr&&ry(k)===E.type){n(m,E.sibling),p=i(E,w.props),p.ref=zo(m,E,w),p.return=m,m=p;break e}n(m,E);break}else t(m,E);E=E.sibling}w.type===Ps?(p=Ji(w.props.children,m.mode,S,w.key),p.return=m,m=p):(S=pu(w.type,w.key,w.props,null,m.mode,S),S.ref=zo(m,p,w),S.return=m,m=S)}return o(m);case ks:e:{for(E=w.key;p!==null;){if(p.key===E)if(p.tag===4&&p.stateNode.containerInfo===w.containerInfo&&p.stateNode.implementation===w.implementation){n(m,p.sibling),p=i(p,w.children||[]),p.return=m,m=p;break e}else{n(m,p);break}else t(m,p);p=p.sibling}p=Uf(w,m.mode,S),p.return=m,m=p}return o(m);case Kr:return E=w._init,x(m,p,E(w._payload),S)}if(Yo(w))return g(m,p,w,S);if(No(w))return v(m,p,w,S);Fl(m,w)}return typeof w=="string"&&w!==""||typeof w=="number"?(w=""+w,p!==null&&p.tag===6?(n(m,p.sibling),p=i(p,w),p.return=m,m=p):(n(m,p),p=zf(w,m.mode,S),p.return=m,m=p),o(m)):n(m,p)}return x}var uo=cx(!0),fx=cx(!1),zu=bi(null),Uu=null,Ns=null,Ap=null;function Tp(){Ap=Ns=Uu=null}function Op(e){var t=zu.current;Fe(zu),e._currentValue=t}function th(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function Hs(e,t){Uu=e,Ap=Ns=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(Ut=!0),e.firstContext=null)}function gn(e){var t=e._currentValue;if(Ap!==e)if(e={context:e,memoizedValue:t,next:null},Ns===null){if(Uu===null)throw Error(j(308));Ns=e,Uu.dependencies={lanes:0,firstContext:e}}else Ns=Ns.next=e;return t}var $i=null;function Ip(e){$i===null?$i=[e]:$i.push(e)}function dx(e,t,n,r){var i=t.interleaved;return i===null?(n.next=n,Ip(t)):(n.next=i.next,i.next=n),t.interleaved=n,Ar(e,r)}function Ar(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var qr=!1;function Lp(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function hx(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function kr(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function ui(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,we&2){var i=r.pending;return i===null?t.next=t:(t.next=i.next,i.next=t),r.pending=t,Ar(e,n)}return i=r.interleaved,i===null?(t.next=t,Ip(r)):(t.next=i.next,i.next=t),r.interleaved=t,Ar(e,n)}function lu(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,vp(e,n)}}function iy(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var i=null,s=null;if(n=n.firstBaseUpdate,n!==null){do{var o={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};s===null?i=s=o:s=s.next=o,n=n.next}while(n!==null);s===null?i=s=t:s=s.next=t}else i=s=t;n={baseState:r.baseState,firstBaseUpdate:i,lastBaseUpdate:s,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function Bu(e,t,n,r){var i=e.updateQueue;qr=!1;var s=i.firstBaseUpdate,o=i.lastBaseUpdate,a=i.shared.pending;if(a!==null){i.shared.pending=null;var l=a,u=l.next;l.next=null,o===null?s=u:o.next=u,o=l;var f=e.alternate;f!==null&&(f=f.updateQueue,a=f.lastBaseUpdate,a!==o&&(a===null?f.firstBaseUpdate=u:a.next=u,f.lastBaseUpdate=l))}if(s!==null){var c=i.baseState;o=0,f=u=l=null,a=s;do{var d=a.lane,h=a.eventTime;if((r&d)===d){f!==null&&(f=f.next={eventTime:h,lane:0,tag:a.tag,payload:a.payload,callback:a.callback,next:null});e:{var g=e,v=a;switch(d=t,h=n,v.tag){case 1:if(g=v.payload,typeof g=="function"){c=g.call(h,c,d);break e}c=g;break e;case 3:g.flags=g.flags&-65537|128;case 0:if(g=v.payload,d=typeof g=="function"?g.call(h,c,d):g,d==null)break e;c=Be({},c,d);break e;case 2:qr=!0}}a.callback!==null&&a.lane!==0&&(e.flags|=64,d=i.effects,d===null?i.effects=[a]:d.push(a))}else h={eventTime:h,lane:d,tag:a.tag,payload:a.payload,callback:a.callback,next:null},f===null?(u=f=h,l=c):f=f.next=h,o|=d;if(a=a.next,a===null){if(a=i.shared.pending,a===null)break;d=a,a=d.next,d.next=null,i.lastBaseUpdate=d,i.shared.pending=null}}while(!0);if(f===null&&(l=c),i.baseState=l,i.firstBaseUpdate=u,i.lastBaseUpdate=f,t=i.shared.interleaved,t!==null){i=t;do o|=i.lane,i=i.next;while(i!==t)}else s===null&&(i.shared.lanes=0);Zi|=o,e.lanes=o,e.memoizedState=c}}function sy(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=Nf.transition;Nf.transition={};try{e(!1),t()}finally{Pe=n,Nf.transition=r}}function Tx(){return yn().memoizedState}function N_(e,t,n){var r=fi(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Ox(e))Ix(t,n);else if(n=dx(e,t,n,r),n!==null){var i=Lt();Nn(n,e,r,i),Lx(n,t,r)}}function F_(e,t,n){var r=fi(e),i={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Ox(e))Ix(t,i);else{var s=e.alternate;if(e.lanes===0&&(s===null||s.lanes===0)&&(s=t.lastRenderedReducer,s!==null))try{var o=t.lastRenderedState,a=s(o,n);if(i.hasEagerState=!0,i.eagerState=a,Fn(a,o)){var l=t.interleaved;l===null?(i.next=i,Ip(t)):(i.next=l.next,l.next=i),t.interleaved=i;return}}catch{}finally{}n=dx(e,t,i,r),n!==null&&(i=Lt(),Nn(n,e,r,i),Lx(n,t,r))}}function Ox(e){var t=e.alternate;return e===Ue||t!==null&&t===Ue}function Ix(e,t){ma=Vu=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Lx(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,vp(e,n)}}var Wu={readContext:gn,useCallback:bt,useContext:bt,useEffect:bt,useImperativeHandle:bt,useInsertionEffect:bt,useLayoutEffect:bt,useMemo:bt,useReducer:bt,useRef:bt,useState:bt,useDebugValue:bt,useDeferredValue:bt,useTransition:bt,useMutableSource:bt,useSyncExternalStore:bt,useId:bt,unstable_isNewReconciler:!1},D_={readContext:gn,useCallback:function(e,t){return Wn().memoizedState=[e,t===void 0?null:t],e},useContext:gn,useEffect:ay,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,cu(4194308,4,_x.bind(null,t,e),n)},useLayoutEffect:function(e,t){return cu(4194308,4,e,t)},useInsertionEffect:function(e,t){return cu(4,2,e,t)},useMemo:function(e,t){var n=Wn();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Wn();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=N_.bind(null,Ue,e),[r.memoizedState,e]},useRef:function(e){var t=Wn();return e={current:e},t.memoizedState=e},useState:oy,useDebugValue:Up,useDeferredValue:function(e){return Wn().memoizedState=e},useTransition:function(){var e=oy(!1),t=e[0];return e=M_.bind(null,e[1]),Wn().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=Ue,i=Wn();if($e){if(n===void 0)throw Error(j(407));n=n()}else{if(n=t(),lt===null)throw Error(j(349));Yi&30||yx(r,t,n)}i.memoizedState=n;var s={value:n,getSnapshot:t};return i.queue=s,ay(wx.bind(null,r,s,e),[e]),r.flags|=2048,Ua(9,vx.bind(null,r,s,n,t),void 0,null),n},useId:function(){var e=Wn(),t=lt.identifierPrefix;if($e){var n=_r,r=Cr;n=(r&~(1<<32-Mn(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=ja++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=o.createElement(n,{is:r.is}):(e=o.createElement(n),n==="select"&&(o=e,r.multiple?o.multiple=!0:r.size&&(o.size=r.size))):e=o.createElementNS(e,n),e[Yn]=t,e[Fa]=r,Hx(e,t,!1,!1),t.stateNode=e;e:{switch(o=Dd(n,r),n){case"dialog":Ne("cancel",e),Ne("close",e),i=r;break;case"iframe":case"object":case"embed":Ne("load",e),i=r;break;case"video":case"audio":for(i=0;iho&&(t.flags|=128,r=!0,Uo(s,!1),t.lanes=4194304)}else{if(!r)if(e=Hu(o),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),Uo(s,!0),s.tail===null&&s.tailMode==="hidden"&&!o.alternate&&!$e)return Et(t),null}else 2*Je()-s.renderingStartTime>ho&&n!==1073741824&&(t.flags|=128,r=!0,Uo(s,!1),t.lanes=4194304);s.isBackwards?(o.sibling=t.child,t.child=o):(n=s.last,n!==null?n.sibling=o:t.child=o,s.last=o)}return s.tail!==null?(t=s.tail,s.rendering=t,s.tail=t.sibling,s.renderingStartTime=Je(),t.sibling=null,n=ze.current,Oe(ze,r?n&1|2:n&1),t):(Et(t),null);case 22:case 23:return Kp(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?Gt&1073741824&&(Et(t),t.subtreeFlags&6&&(t.flags|=8192)):Et(t),null;case 24:return null;case 25:return null}throw Error(j(156,t.tag))}function WC(e,t){switch(Pp(t),t.tag){case 1:return Ht(t.type)&&Fu(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return co(),Fe(Bt),Fe(Pt),Fp(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Np(t),null;case 13:if(Fe(ze),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(j(340));lo()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return Fe(ze),null;case 4:return co(),null;case 10:return Op(t.type._context),null;case 22:case 23:return Kp(),null;case 24:return null;default:return null}}var $l=!1,kt=!1,QC=typeof WeakSet=="function"?WeakSet:Set,K=null;function Fs(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){Qe(e,t,r)}else n.current=null}function ch(e,t,n){try{n()}catch(r){Qe(e,t,r)}}var vy=!1;function KC(e,t){if(Kd=Iu,e=G0(),Cp(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var i=r.anchorOffset,s=r.focusNode;r=r.focusOffset;try{n.nodeType,s.nodeType}catch{n=null;break e}var o=0,a=-1,l=-1,u=0,f=0,c=e,d=null;t:for(;;){for(var h;c!==n||i!==0&&c.nodeType!==3||(a=o+i),c!==s||r!==0&&c.nodeType!==3||(l=o+r),c.nodeType===3&&(o+=c.nodeValue.length),(h=c.firstChild)!==null;)d=c,c=h;for(;;){if(c===e)break t;if(d===n&&++u===i&&(a=o),d===s&&++f===r&&(l=o),(h=c.nextSibling)!==null)break;c=d,d=c.parentNode}c=h}n=a===-1||l===-1?null:{start:a,end:l}}else n=null}n=n||{start:0,end:0}}else n=null;for(qd={focusedElem:e,selectionRange:n},Iu=!1,K=t;K!==null;)if(t=K,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,K=e;else for(;K!==null;){t=K;try{var g=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(g!==null){var v=g.memoizedProps,x=g.memoizedState,m=t.stateNode,p=m.getSnapshotBeforeUpdate(t.elementType===t.type?v:Cn(t.type,v),x);m.__reactInternalSnapshotBeforeUpdate=p}break;case 3:var w=t.stateNode.containerInfo;w.nodeType===1?w.textContent="":w.nodeType===9&&w.documentElement&&w.removeChild(w.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(j(163))}}catch(S){Qe(t,t.return,S)}if(e=t.sibling,e!==null){e.return=t.return,K=e;break}K=t.return}return g=vy,vy=!1,g}function ga(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var i=r=r.next;do{if((i.tag&e)===e){var s=i.destroy;i.destroy=void 0,s!==void 0&&ch(t,n,s)}i=i.next}while(i!==r)}}function Pc(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function fh(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function Qx(e){var t=e.alternate;t!==null&&(e.alternate=null,Qx(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Yn],delete t[Fa],delete t[Xd],delete t[AC],delete t[TC])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function Kx(e){return e.tag===5||e.tag===3||e.tag===4}function wy(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Kx(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function dh(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=Nu));else if(r!==4&&(e=e.child,e!==null))for(dh(e,t,n),e=e.sibling;e!==null;)dh(e,t,n),e=e.sibling}function hh(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(hh(e,t,n),e=e.sibling;e!==null;)hh(e,t,n),e=e.sibling}var ft=null,An=!1;function $r(e,t,n){for(n=n.child;n!==null;)qx(e,t,n),n=n.sibling}function qx(e,t,n){if(nr&&typeof nr.onCommitFiberUnmount=="function")try{nr.onCommitFiberUnmount(wc,n)}catch{}switch(n.tag){case 5:kt||Fs(n,t);case 6:var r=ft,i=An;ft=null,$r(e,t,n),ft=r,An=i,ft!==null&&(An?(e=ft,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):ft.removeChild(n.stateNode));break;case 18:ft!==null&&(An?(e=ft,n=n.stateNode,e.nodeType===8?If(e.parentNode,n):e.nodeType===1&&If(e,n),Oa(e)):If(ft,n.stateNode));break;case 4:r=ft,i=An,ft=n.stateNode.containerInfo,An=!0,$r(e,t,n),ft=r,An=i;break;case 0:case 11:case 14:case 15:if(!kt&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){i=r=r.next;do{var s=i,o=s.destroy;s=s.tag,o!==void 0&&(s&2||s&4)&&ch(n,t,o),i=i.next}while(i!==r)}$r(e,t,n);break;case 1:if(!kt&&(Fs(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(a){Qe(n,t,a)}$r(e,t,n);break;case 21:$r(e,t,n);break;case 22:n.mode&1?(kt=(r=kt)||n.memoizedState!==null,$r(e,t,n),kt=r):$r(e,t,n);break;default:$r(e,t,n)}}function xy(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new QC),t.forEach(function(r){var i=nk.bind(null,e,r);n.has(r)||(n.add(r),r.then(i,i))})}}function bn(e,t){var n=t.deletions;if(n!==null)for(var r=0;ri&&(i=o),r&=~s}if(r=i,r=Je()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*JC(r/1960))-r,10e?16:e,ri===null)var r=!1;else{if(e=ri,ri=null,qu=0,we&6)throw Error(j(331));var i=we;for(we|=4,K=e.current;K!==null;){var s=K,o=s.child;if(K.flags&16){var a=s.deletions;if(a!==null){for(var l=0;lJe()-Wp?qi(e,0):Vp|=n),Vt(e,t)}function nS(e,t){t===0&&(e.mode&1?(t=Al,Al<<=1,!(Al&130023424)&&(Al=4194304)):t=1);var n=Lt();e=Ar(e,t),e!==null&&(tl(e,t,n),Vt(e,n))}function tk(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),nS(e,n)}function nk(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,i=e.memoizedState;i!==null&&(n=i.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(j(314))}r!==null&&r.delete(t),nS(e,n)}var rS;rS=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||Bt.current)Ut=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return Ut=!1,HC(e,t,n);Ut=!!(e.flags&131072)}else Ut=!1,$e&&t.flags&1048576&&ax(t,ju,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;fu(e,t),e=t.pendingProps;var i=ao(t,Pt.current);Hs(t,n),i=$p(null,t,r,e,i,n);var s=jp();return t.flags|=1,typeof i=="object"&&i!==null&&typeof i.render=="function"&&i.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,Ht(r)?(s=!0,Du(t)):s=!1,t.memoizedState=i.state!==null&&i.state!==void 0?i.state:null,Lp(t),i.updater=kc,t.stateNode=i,i._reactInternals=t,rh(t,r,e,n),t=oh(null,t,r,!0,s,n)):(t.tag=0,$e&&s&&kp(t),Ot(null,t,i,n),t=t.child),t;case 16:r=t.elementType;e:{switch(fu(e,t),e=t.pendingProps,i=r._init,r=i(r._payload),t.type=r,i=t.tag=ik(r),e=Cn(r,e),i){case 0:t=sh(null,t,r,e,n);break e;case 1:t=my(null,t,r,e,n);break e;case 11:t=hy(null,t,r,e,n);break e;case 14:t=py(null,t,r,Cn(r.type,e),n);break e}throw Error(j(306,r,""))}return t;case 0:return r=t.type,i=t.pendingProps,i=t.elementType===r?i:Cn(r,i),sh(e,t,r,i,n);case 1:return r=t.type,i=t.pendingProps,i=t.elementType===r?i:Cn(r,i),my(e,t,r,i,n);case 3:e:{if(zx(t),e===null)throw Error(j(387));r=t.pendingProps,s=t.memoizedState,i=s.element,hx(e,t),Bu(t,r,null,n);var o=t.memoizedState;if(r=o.element,s.isDehydrated)if(s={element:r,isDehydrated:!1,cache:o.cache,pendingSuspenseBoundaries:o.pendingSuspenseBoundaries,transitions:o.transitions},t.updateQueue.baseState=s,t.memoizedState=s,t.flags&256){i=fo(Error(j(423)),t),t=gy(e,t,r,n,i);break e}else if(r!==i){i=fo(Error(j(424)),t),t=gy(e,t,r,n,i);break e}else for(Zt=li(t.stateNode.containerInfo.firstChild),en=t,$e=!0,On=null,n=fx(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(lo(),r===i){t=Tr(e,t,n);break e}Ot(e,t,r,n)}t=t.child}return t;case 5:return px(t),e===null&&eh(t),r=t.type,i=t.pendingProps,s=e!==null?e.memoizedProps:null,o=i.children,Jd(r,i)?o=null:s!==null&&Jd(r,s)&&(t.flags|=32),jx(e,t),Ot(e,t,o,n),t.child;case 6:return e===null&&eh(t),null;case 13:return Ux(e,t,n);case 4:return Mp(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=uo(t,null,r,n):Ot(e,t,r,n),t.child;case 11:return r=t.type,i=t.pendingProps,i=t.elementType===r?i:Cn(r,i),hy(e,t,r,i,n);case 7:return Ot(e,t,t.pendingProps,n),t.child;case 8:return Ot(e,t,t.pendingProps.children,n),t.child;case 12:return Ot(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,i=t.pendingProps,s=t.memoizedProps,o=i.value,Oe(zu,r._currentValue),r._currentValue=o,s!==null)if(Fn(s.value,o)){if(s.children===i.children&&!Bt.current){t=Tr(e,t,n);break e}}else for(s=t.child,s!==null&&(s.return=t);s!==null;){var a=s.dependencies;if(a!==null){o=s.child;for(var l=a.firstContext;l!==null;){if(l.context===r){if(s.tag===1){l=kr(-1,n&-n),l.tag=2;var u=s.updateQueue;if(u!==null){u=u.shared;var f=u.pending;f===null?l.next=l:(l.next=f.next,f.next=l),u.pending=l}}s.lanes|=n,l=s.alternate,l!==null&&(l.lanes|=n),th(s.return,n,t),a.lanes|=n;break}l=l.next}}else if(s.tag===10)o=s.type===t.type?null:s.child;else if(s.tag===18){if(o=s.return,o===null)throw Error(j(341));o.lanes|=n,a=o.alternate,a!==null&&(a.lanes|=n),th(o,n,t),o=s.sibling}else o=s.child;if(o!==null)o.return=s;else for(o=s;o!==null;){if(o===t){o=null;break}if(s=o.sibling,s!==null){s.return=o.return,o=s;break}o=o.return}s=o}Ot(e,t,i.children,n),t=t.child}return t;case 9:return i=t.type,r=t.pendingProps.children,Hs(t,n),i=gn(i),r=r(i),t.flags|=1,Ot(e,t,r,n),t.child;case 14:return r=t.type,i=Cn(r,t.pendingProps),i=Cn(r.type,i),py(e,t,r,i,n);case 15:return Dx(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,i=t.pendingProps,i=t.elementType===r?i:Cn(r,i),fu(e,t),t.tag=1,Ht(r)?(e=!0,Du(t)):e=!1,Hs(t,n),Mx(t,r,i),rh(t,r,i,n),oh(null,t,r,!0,e,n);case 19:return Bx(e,t,n);case 22:return $x(e,t,n)}throw Error(j(156,t.tag))};function iS(e,t){return O0(e,t)}function rk(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function hn(e,t,n,r){return new rk(e,t,n,r)}function Jp(e){return e=e.prototype,!(!e||!e.isReactComponent)}function ik(e){if(typeof e=="function")return Jp(e)?1:0;if(e!=null){if(e=e.$$typeof,e===pp)return 11;if(e===mp)return 14}return 2}function di(e,t){var n=e.alternate;return n===null?(n=hn(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function pu(e,t,n,r,i,s){var o=2;if(r=e,typeof e=="function")Jp(e)&&(o=1);else if(typeof e=="string")o=5;else e:switch(e){case Ps:return Ji(n.children,i,s,t);case hp:o=8,i|=8;break;case Pd:return e=hn(12,n,t,i|2),e.elementType=Pd,e.lanes=s,e;case Rd:return e=hn(13,n,t,i),e.elementType=Rd,e.lanes=s,e;case Ad:return e=hn(19,n,t,i),e.elementType=Ad,e.lanes=s,e;case p0:return Ac(n,i,s,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case d0:o=10;break e;case h0:o=9;break e;case pp:o=11;break e;case mp:o=14;break e;case Kr:o=16,r=null;break e}throw Error(j(130,e==null?e:typeof e,""))}return t=hn(o,n,t,i),t.elementType=e,t.type=r,t.lanes=s,t}function Ji(e,t,n,r){return e=hn(7,e,r,t),e.lanes=n,e}function Ac(e,t,n,r){return e=hn(22,e,r,t),e.elementType=p0,e.lanes=n,e.stateNode={isHidden:!1},e}function zf(e,t,n){return e=hn(6,e,null,t),e.lanes=n,e}function Uf(e,t,n){return t=hn(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function sk(e,t,n,r,i){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Sf(0),this.expirationTimes=Sf(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Sf(0),this.identifierPrefix=r,this.onRecoverableError=i,this.mutableSourceEagerHydrationData=null}function Gp(e,t,n,r,i,s,o,a,l){return e=new sk(e,t,n,a,l),t===1?(t=1,s===!0&&(t|=8)):t=0,s=hn(3,null,null,t),e.current=s,s.stateNode=e,s.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Lp(s),e}function ok(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(lS)}catch(e){console.error(e)}}lS(),l0.exports=rn;var sl=l0.exports;const fk=rp(sl),dk=$w({__proto__:null,default:fk},[sl]);function uS(e){const t=hk(e),n=_.forwardRef((r,i)=>{const{children:s,...o}=r,a=_.Children.toArray(s),l=a.find(mk);if(l){const u=l.props.children,f=a.map(c=>c===l?_.Children.count(u)>1?_.Children.only(null):_.isValidElement(u)?u.props.children:null:c);return Y.jsx(t,{...o,ref:i,children:_.isValidElement(u)?_.cloneElement(u,void 0,f):null})}return Y.jsx(t,{...o,ref:i,children:s})});return n.displayName=`${e}.Slot`,n}var S2=uS("Slot");function hk(e){const t=_.forwardRef((n,r)=>{const{children:i,...s}=n;if(_.isValidElement(i)){const o=yk(i),a=gk(s,i.props);return i.type!==_.Fragment&&(a.ref=r?o0(r,o):o),_.cloneElement(i,a)}return _.Children.count(i)>1?_.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var cS=Symbol("radix.slottable");function pk(e){const t=({children:n})=>Y.jsx(Y.Fragment,{children:n});return t.displayName=`${e}.Slottable`,t.__radixId=cS,t}function mk(e){return _.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===cS}function gk(e,t){const n={...t};for(const r in t){const i=e[r],s=t[r];/^on[A-Z]/.test(r)?i&&s?n[r]=(...a)=>{s(...a),i(...a)}:i&&(n[r]=i):r==="style"?n[r]={...i,...s}:r==="className"&&(n[r]=[i,s].filter(Boolean).join(" "))}return{...e,...n}}function yk(e){var r,i;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(i=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:i.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var vk=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],os=vk.reduce((e,t)=>{const n=uS(`Primitive.${t}`),r=_.forwardRef((i,s)=>{const{asChild:o,...a}=i,l=o?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),Y.jsx(l,{...a,ref:s})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function wk(e,t){e&&sl.flushSync(()=>e.dispatchEvent(t))}function bo(e){const t=_.useRef(e);return _.useEffect(()=>{t.current=e}),_.useMemo(()=>(...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[])}function xk(e,t=globalThis==null?void 0:globalThis.document){const n=bo(e);_.useEffect(()=>{const r=i=>{i.key==="Escape"&&n(i)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[n,t])}var Sk="DismissableLayer",vh="dismissableLayer.update",bk="dismissableLayer.pointerDownOutside",Ek="dismissableLayer.focusOutside",Ry,fS=_.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),dS=_.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:i,onFocusOutside:s,onInteractOutside:o,onDismiss:a,...l}=e,u=_.useContext(fS),[f,c]=_.useState(null),d=(f==null?void 0:f.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,h]=_.useState({}),g=rs(t,y=>c(y)),v=Array.from(u.layers),[x]=[...u.layersWithOutsidePointerEventsDisabled].slice(-1),m=v.indexOf(x),p=f?v.indexOf(f):-1,w=u.layersWithOutsidePointerEventsDisabled.size>0,S=p>=m,k=kk(y=>{const R=y.target,T=[...u.branches].some(A=>A.contains(R));!S||T||(i==null||i(y),o==null||o(y),y.defaultPrevented||a==null||a())},d),E=Pk(y=>{const R=y.target;[...u.branches].some(A=>A.contains(R))||(s==null||s(y),o==null||o(y),y.defaultPrevented||a==null||a())},d);return xk(y=>{p===u.layers.size-1&&(r==null||r(y),!y.defaultPrevented&&a&&(y.preventDefault(),a()))},d),_.useEffect(()=>{if(f)return n&&(u.layersWithOutsidePointerEventsDisabled.size===0&&(Ry=d.body.style.pointerEvents,d.body.style.pointerEvents="none"),u.layersWithOutsidePointerEventsDisabled.add(f)),u.layers.add(f),Ay(),()=>{n&&u.layersWithOutsidePointerEventsDisabled.size===1&&(d.body.style.pointerEvents=Ry)}},[f,d,n,u]),_.useEffect(()=>()=>{f&&(u.layers.delete(f),u.layersWithOutsidePointerEventsDisabled.delete(f),Ay())},[f,u]),_.useEffect(()=>{const y=()=>h({});return document.addEventListener(vh,y),()=>document.removeEventListener(vh,y)},[]),Y.jsx(os.div,{...l,ref:g,style:{pointerEvents:w?S?"auto":"none":void 0,...e.style},onFocusCapture:Sr(e.onFocusCapture,E.onFocusCapture),onBlurCapture:Sr(e.onBlurCapture,E.onBlurCapture),onPointerDownCapture:Sr(e.onPointerDownCapture,k.onPointerDownCapture)})});dS.displayName=Sk;var _k="DismissableLayerBranch",Ck=_.forwardRef((e,t)=>{const n=_.useContext(fS),r=_.useRef(null),i=rs(t,r);return _.useEffect(()=>{const s=r.current;if(s)return n.branches.add(s),()=>{n.branches.delete(s)}},[n.branches]),Y.jsx(os.div,{...e,ref:i})});Ck.displayName=_k;function kk(e,t=globalThis==null?void 0:globalThis.document){const n=bo(e),r=_.useRef(!1),i=_.useRef(()=>{});return _.useEffect(()=>{const s=a=>{if(a.target&&!r.current){let l=function(){hS(bk,n,u,{discrete:!0})};const u={originalEvent:a};a.pointerType==="touch"?(t.removeEventListener("click",i.current),i.current=l,t.addEventListener("click",i.current,{once:!0})):l()}else t.removeEventListener("click",i.current);r.current=!1},o=window.setTimeout(()=>{t.addEventListener("pointerdown",s)},0);return()=>{window.clearTimeout(o),t.removeEventListener("pointerdown",s),t.removeEventListener("click",i.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function Pk(e,t=globalThis==null?void 0:globalThis.document){const n=bo(e),r=_.useRef(!1);return _.useEffect(()=>{const i=s=>{s.target&&!r.current&&hS(Ek,n,{originalEvent:s},{discrete:!1})};return t.addEventListener("focusin",i),()=>t.removeEventListener("focusin",i)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function Ay(){const e=new CustomEvent(vh);document.dispatchEvent(e)}function hS(e,t,n,{discrete:r}){const i=n.originalEvent.target,s=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&i.addEventListener(e,t,{once:!0}),r?wk(i,s):i.dispatchEvent(s)}var po=globalThis!=null&&globalThis.document?_.useLayoutEffect:()=>{},Rk=Jw[" useId ".trim().toString()]||(()=>{}),Ak=0;function Tk(e){const[t,n]=_.useState(Rk());return po(()=>{n(r=>r??String(Ak++))},[e]),e||(t?`radix-${t}`:"")}const Ok=["top","right","bottom","left"],gi=Math.min,Yt=Math.max,Xu=Math.round,Ul=Math.floor,ir=e=>({x:e,y:e}),Ik={left:"right",right:"left",bottom:"top",top:"bottom"},Lk={start:"end",end:"start"};function wh(e,t,n){return Yt(e,gi(t,n))}function Or(e,t){return typeof e=="function"?e(t):e}function Ir(e){return e.split("-")[0]}function Eo(e){return e.split("-")[1]}function em(e){return e==="x"?"y":"x"}function tm(e){return e==="y"?"height":"width"}function yi(e){return["top","bottom"].includes(Ir(e))?"y":"x"}function nm(e){return em(yi(e))}function Mk(e,t,n){n===void 0&&(n=!1);const r=Eo(e),i=nm(e),s=tm(i);let o=i==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[s]>t.floating[s]&&(o=Yu(o)),[o,Yu(o)]}function Nk(e){const t=Yu(e);return[xh(e),t,xh(t)]}function xh(e){return e.replace(/start|end/g,t=>Lk[t])}function Fk(e,t,n){const r=["left","right"],i=["right","left"],s=["top","bottom"],o=["bottom","top"];switch(e){case"top":case"bottom":return n?t?i:r:t?r:i;case"left":case"right":return t?s:o;default:return[]}}function Dk(e,t,n,r){const i=Eo(e);let s=Fk(Ir(e),n==="start",r);return i&&(s=s.map(o=>o+"-"+i),t&&(s=s.concat(s.map(xh)))),s}function Yu(e){return e.replace(/left|right|bottom|top/g,t=>Ik[t])}function $k(e){return{top:0,right:0,bottom:0,left:0,...e}}function pS(e){return typeof e!="number"?$k(e):{top:e,right:e,bottom:e,left:e}}function Zu(e){const{x:t,y:n,width:r,height:i}=e;return{width:r,height:i,top:n,left:t,right:t+r,bottom:n+i,x:t,y:n}}function Ty(e,t,n){let{reference:r,floating:i}=e;const s=yi(t),o=nm(t),a=tm(o),l=Ir(t),u=s==="y",f=r.x+r.width/2-i.width/2,c=r.y+r.height/2-i.height/2,d=r[a]/2-i[a]/2;let h;switch(l){case"top":h={x:f,y:r.y-i.height};break;case"bottom":h={x:f,y:r.y+r.height};break;case"right":h={x:r.x+r.width,y:c};break;case"left":h={x:r.x-i.width,y:c};break;default:h={x:r.x,y:r.y}}switch(Eo(t)){case"start":h[o]-=d*(n&&u?-1:1);break;case"end":h[o]+=d*(n&&u?-1:1);break}return h}const jk=async(e,t,n)=>{const{placement:r="bottom",strategy:i="absolute",middleware:s=[],platform:o}=n,a=s.filter(Boolean),l=await(o.isRTL==null?void 0:o.isRTL(t));let u=await o.getElementRects({reference:e,floating:t,strategy:i}),{x:f,y:c}=Ty(u,r,l),d=r,h={},g=0;for(let v=0;v({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:i,rects:s,platform:o,elements:a,middlewareData:l}=t,{element:u,padding:f=0}=Or(e,t)||{};if(u==null)return{};const c=pS(f),d={x:n,y:r},h=nm(i),g=tm(h),v=await o.getDimensions(u),x=h==="y",m=x?"top":"left",p=x?"bottom":"right",w=x?"clientHeight":"clientWidth",S=s.reference[g]+s.reference[h]-d[h]-s.floating[g],k=d[h]-s.reference[h],E=await(o.getOffsetParent==null?void 0:o.getOffsetParent(u));let y=E?E[w]:0;(!y||!await(o.isElement==null?void 0:o.isElement(E)))&&(y=a.floating[w]||s.floating[g]);const R=S/2-k/2,T=y/2-v[g]/2-1,A=gi(c[m],T),O=gi(c[p],T),I=A,z=y-v[g]-O,B=y/2-v[g]/2+R,V=wh(I,B,z),G=!l.arrow&&Eo(i)!=null&&B!==V&&s.reference[g]/2-(BB<=0)){var O,I;const B=(((O=s.flip)==null?void 0:O.index)||0)+1,V=y[B];if(V)return{data:{index:B,overflows:A},reset:{placement:V}};let G=(I=A.filter(Q=>Q.overflows[0]<=0).sort((Q,M)=>Q.overflows[1]-M.overflows[1])[0])==null?void 0:I.placement;if(!G)switch(h){case"bestFit":{var z;const Q=(z=A.filter(M=>{if(E){const U=yi(M.placement);return U===p||U==="y"}return!0}).map(M=>[M.placement,M.overflows.filter(U=>U>0).reduce((U,b)=>U+b,0)]).sort((M,U)=>M[1]-U[1])[0])==null?void 0:z[0];Q&&(G=Q);break}case"initialPlacement":G=a;break}if(i!==G)return{reset:{placement:G}}}return{}}}};function Oy(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function Iy(e){return Ok.some(t=>e[t]>=0)}const Bk=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...i}=Or(e,t);switch(r){case"referenceHidden":{const s=await Ha(t,{...i,elementContext:"reference"}),o=Oy(s,n.reference);return{data:{referenceHiddenOffsets:o,referenceHidden:Iy(o)}}}case"escaped":{const s=await Ha(t,{...i,altBoundary:!0}),o=Oy(s,n.floating);return{data:{escapedOffsets:o,escaped:Iy(o)}}}default:return{}}}}};async function Hk(e,t){const{placement:n,platform:r,elements:i}=e,s=await(r.isRTL==null?void 0:r.isRTL(i.floating)),o=Ir(n),a=Eo(n),l=yi(n)==="y",u=["left","top"].includes(o)?-1:1,f=s&&l?-1:1,c=Or(t,e);let{mainAxis:d,crossAxis:h,alignmentAxis:g}=typeof c=="number"?{mainAxis:c,crossAxis:0,alignmentAxis:null}:{mainAxis:c.mainAxis||0,crossAxis:c.crossAxis||0,alignmentAxis:c.alignmentAxis};return a&&typeof g=="number"&&(h=a==="end"?g*-1:g),l?{x:h*f,y:d*u}:{x:d*u,y:h*f}}const Vk=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:i,y:s,placement:o,middlewareData:a}=t,l=await Hk(t,e);return o===((n=a.offset)==null?void 0:n.placement)&&(r=a.arrow)!=null&&r.alignmentOffset?{}:{x:i+l.x,y:s+l.y,data:{...l,placement:o}}}}},Wk=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:i}=t,{mainAxis:s=!0,crossAxis:o=!1,limiter:a={fn:x=>{let{x:m,y:p}=x;return{x:m,y:p}}},...l}=Or(e,t),u={x:n,y:r},f=await Ha(t,l),c=yi(Ir(i)),d=em(c);let h=u[d],g=u[c];if(s){const x=d==="y"?"top":"left",m=d==="y"?"bottom":"right",p=h+f[x],w=h-f[m];h=wh(p,h,w)}if(o){const x=c==="y"?"top":"left",m=c==="y"?"bottom":"right",p=g+f[x],w=g-f[m];g=wh(p,g,w)}const v=a.fn({...t,[d]:h,[c]:g});return{...v,data:{x:v.x-n,y:v.y-r,enabled:{[d]:s,[c]:o}}}}}},Qk=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:i,rects:s,middlewareData:o}=t,{offset:a=0,mainAxis:l=!0,crossAxis:u=!0}=Or(e,t),f={x:n,y:r},c=yi(i),d=em(c);let h=f[d],g=f[c];const v=Or(a,t),x=typeof v=="number"?{mainAxis:v,crossAxis:0}:{mainAxis:0,crossAxis:0,...v};if(l){const w=d==="y"?"height":"width",S=s.reference[d]-s.floating[w]+x.mainAxis,k=s.reference[d]+s.reference[w]-x.mainAxis;hk&&(h=k)}if(u){var m,p;const w=d==="y"?"width":"height",S=["top","left"].includes(Ir(i)),k=s.reference[c]-s.floating[w]+(S&&((m=o.offset)==null?void 0:m[c])||0)+(S?0:x.crossAxis),E=s.reference[c]+s.reference[w]+(S?0:((p=o.offset)==null?void 0:p[c])||0)-(S?x.crossAxis:0);gE&&(g=E)}return{[d]:h,[c]:g}}}},Kk=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var n,r;const{placement:i,rects:s,platform:o,elements:a}=t,{apply:l=()=>{},...u}=Or(e,t),f=await Ha(t,u),c=Ir(i),d=Eo(i),h=yi(i)==="y",{width:g,height:v}=s.floating;let x,m;c==="top"||c==="bottom"?(x=c,m=d===(await(o.isRTL==null?void 0:o.isRTL(a.floating))?"start":"end")?"left":"right"):(m=c,x=d==="end"?"top":"bottom");const p=v-f.top-f.bottom,w=g-f.left-f.right,S=gi(v-f[x],p),k=gi(g-f[m],w),E=!t.middlewareData.shift;let y=S,R=k;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(R=w),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(y=p),E&&!d){const A=Yt(f.left,0),O=Yt(f.right,0),I=Yt(f.top,0),z=Yt(f.bottom,0);h?R=g-2*(A!==0||O!==0?A+O:Yt(f.left,f.right)):y=v-2*(I!==0||z!==0?I+z:Yt(f.top,f.bottom))}await l({...t,availableWidth:R,availableHeight:y});const T=await o.getDimensions(a.floating);return g!==T.width||v!==T.height?{reset:{rects:!0}}:{}}}};function Mc(){return typeof window<"u"}function _o(e){return mS(e)?(e.nodeName||"").toLowerCase():"#document"}function tn(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function lr(e){var t;return(t=(mS(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function mS(e){return Mc()?e instanceof Node||e instanceof tn(e).Node:!1}function Dn(e){return Mc()?e instanceof Element||e instanceof tn(e).Element:!1}function or(e){return Mc()?e instanceof HTMLElement||e instanceof tn(e).HTMLElement:!1}function Ly(e){return!Mc()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof tn(e).ShadowRoot}function ol(e){const{overflow:t,overflowX:n,overflowY:r,display:i}=$n(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!["inline","contents"].includes(i)}function qk(e){return["table","td","th"].includes(_o(e))}function Nc(e){return[":popover-open",":modal"].some(t=>{try{return e.matches(t)}catch{return!1}})}function rm(e){const t=im(),n=Dn(e)?$n(e):e;return["transform","translate","scale","rotate","perspective"].some(r=>n[r]?n[r]!=="none":!1)||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||["transform","translate","scale","rotate","perspective","filter"].some(r=>(n.willChange||"").includes(r))||["paint","layout","strict","content"].some(r=>(n.contain||"").includes(r))}function Jk(e){let t=vi(e);for(;or(t)&&!mo(t);){if(rm(t))return t;if(Nc(t))return null;t=vi(t)}return null}function im(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function mo(e){return["html","body","#document"].includes(_o(e))}function $n(e){return tn(e).getComputedStyle(e)}function Fc(e){return Dn(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function vi(e){if(_o(e)==="html")return e;const t=e.assignedSlot||e.parentNode||Ly(e)&&e.host||lr(e);return Ly(t)?t.host:t}function gS(e){const t=vi(e);return mo(t)?e.ownerDocument?e.ownerDocument.body:e.body:or(t)&&ol(t)?t:gS(t)}function Va(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const i=gS(e),s=i===((r=e.ownerDocument)==null?void 0:r.body),o=tn(i);if(s){const a=Sh(o);return t.concat(o,o.visualViewport||[],ol(i)?i:[],a&&n?Va(a):[])}return t.concat(i,Va(i,[],n))}function Sh(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function yS(e){const t=$n(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const i=or(e),s=i?e.offsetWidth:n,o=i?e.offsetHeight:r,a=Xu(n)!==s||Xu(r)!==o;return a&&(n=s,r=o),{width:n,height:r,$:a}}function sm(e){return Dn(e)?e:e.contextElement}function Ws(e){const t=sm(e);if(!or(t))return ir(1);const n=t.getBoundingClientRect(),{width:r,height:i,$:s}=yS(t);let o=(s?Xu(n.width):n.width)/r,a=(s?Xu(n.height):n.height)/i;return(!o||!Number.isFinite(o))&&(o=1),(!a||!Number.isFinite(a))&&(a=1),{x:o,y:a}}const Gk=ir(0);function vS(e){const t=tn(e);return!im()||!t.visualViewport?Gk:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function Xk(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==tn(e)?!1:t}function ts(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const i=e.getBoundingClientRect(),s=sm(e);let o=ir(1);t&&(r?Dn(r)&&(o=Ws(r)):o=Ws(e));const a=Xk(s,n,r)?vS(s):ir(0);let l=(i.left+a.x)/o.x,u=(i.top+a.y)/o.y,f=i.width/o.x,c=i.height/o.y;if(s){const d=tn(s),h=r&&Dn(r)?tn(r):r;let g=d,v=Sh(g);for(;v&&r&&h!==g;){const x=Ws(v),m=v.getBoundingClientRect(),p=$n(v),w=m.left+(v.clientLeft+parseFloat(p.paddingLeft))*x.x,S=m.top+(v.clientTop+parseFloat(p.paddingTop))*x.y;l*=x.x,u*=x.y,f*=x.x,c*=x.y,l+=w,u+=S,g=tn(v),v=Sh(g)}}return Zu({width:f,height:c,x:l,y:u})}function om(e,t){const n=Fc(e).scrollLeft;return t?t.left+n:ts(lr(e)).left+n}function wS(e,t,n){n===void 0&&(n=!1);const r=e.getBoundingClientRect(),i=r.left+t.scrollLeft-(n?0:om(e,r)),s=r.top+t.scrollTop;return{x:i,y:s}}function Yk(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e;const s=i==="fixed",o=lr(r),a=t?Nc(t.floating):!1;if(r===o||a&&s)return n;let l={scrollLeft:0,scrollTop:0},u=ir(1);const f=ir(0),c=or(r);if((c||!c&&!s)&&((_o(r)!=="body"||ol(o))&&(l=Fc(r)),or(r))){const h=ts(r);u=Ws(r),f.x=h.x+r.clientLeft,f.y=h.y+r.clientTop}const d=o&&!c&&!s?wS(o,l,!0):ir(0);return{width:n.width*u.x,height:n.height*u.y,x:n.x*u.x-l.scrollLeft*u.x+f.x+d.x,y:n.y*u.y-l.scrollTop*u.y+f.y+d.y}}function Zk(e){return Array.from(e.getClientRects())}function eP(e){const t=lr(e),n=Fc(e),r=e.ownerDocument.body,i=Yt(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),s=Yt(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let o=-n.scrollLeft+om(e);const a=-n.scrollTop;return $n(r).direction==="rtl"&&(o+=Yt(t.clientWidth,r.clientWidth)-i),{width:i,height:s,x:o,y:a}}function tP(e,t){const n=tn(e),r=lr(e),i=n.visualViewport;let s=r.clientWidth,o=r.clientHeight,a=0,l=0;if(i){s=i.width,o=i.height;const u=im();(!u||u&&t==="fixed")&&(a=i.offsetLeft,l=i.offsetTop)}return{width:s,height:o,x:a,y:l}}function nP(e,t){const n=ts(e,!0,t==="fixed"),r=n.top+e.clientTop,i=n.left+e.clientLeft,s=or(e)?Ws(e):ir(1),o=e.clientWidth*s.x,a=e.clientHeight*s.y,l=i*s.x,u=r*s.y;return{width:o,height:a,x:l,y:u}}function My(e,t,n){let r;if(t==="viewport")r=tP(e,n);else if(t==="document")r=eP(lr(e));else if(Dn(t))r=nP(t,n);else{const i=vS(e);r={x:t.x-i.x,y:t.y-i.y,width:t.width,height:t.height}}return Zu(r)}function xS(e,t){const n=vi(e);return n===t||!Dn(n)||mo(n)?!1:$n(n).position==="fixed"||xS(n,t)}function rP(e,t){const n=t.get(e);if(n)return n;let r=Va(e,[],!1).filter(a=>Dn(a)&&_o(a)!=="body"),i=null;const s=$n(e).position==="fixed";let o=s?vi(e):e;for(;Dn(o)&&!mo(o);){const a=$n(o),l=rm(o);!l&&a.position==="fixed"&&(i=null),(s?!l&&!i:!l&&a.position==="static"&&!!i&&["absolute","fixed"].includes(i.position)||ol(o)&&!l&&xS(e,o))?r=r.filter(f=>f!==o):i=a,o=vi(o)}return t.set(e,r),r}function iP(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e;const o=[...n==="clippingAncestors"?Nc(t)?[]:rP(t,this._c):[].concat(n),r],a=o[0],l=o.reduce((u,f)=>{const c=My(t,f,i);return u.top=Yt(c.top,u.top),u.right=gi(c.right,u.right),u.bottom=gi(c.bottom,u.bottom),u.left=Yt(c.left,u.left),u},My(t,a,i));return{width:l.right-l.left,height:l.bottom-l.top,x:l.left,y:l.top}}function sP(e){const{width:t,height:n}=yS(e);return{width:t,height:n}}function oP(e,t,n){const r=or(t),i=lr(t),s=n==="fixed",o=ts(e,!0,s,t);let a={scrollLeft:0,scrollTop:0};const l=ir(0);if(r||!r&&!s)if((_o(t)!=="body"||ol(i))&&(a=Fc(t)),r){const d=ts(t,!0,s,t);l.x=d.x+t.clientLeft,l.y=d.y+t.clientTop}else i&&(l.x=om(i));const u=i&&!r&&!s?wS(i,a):ir(0),f=o.left+a.scrollLeft-l.x-u.x,c=o.top+a.scrollTop-l.y-u.y;return{x:f,y:c,width:o.width,height:o.height}}function Bf(e){return $n(e).position==="static"}function Ny(e,t){if(!or(e)||$n(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return lr(e)===n&&(n=n.ownerDocument.body),n}function SS(e,t){const n=tn(e);if(Nc(e))return n;if(!or(e)){let i=vi(e);for(;i&&!mo(i);){if(Dn(i)&&!Bf(i))return i;i=vi(i)}return n}let r=Ny(e,t);for(;r&&qk(r)&&Bf(r);)r=Ny(r,t);return r&&mo(r)&&Bf(r)&&!rm(r)?n:r||Jk(e)||n}const aP=async function(e){const t=this.getOffsetParent||SS,n=this.getDimensions,r=await n(e.floating);return{reference:oP(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function lP(e){return $n(e).direction==="rtl"}const uP={convertOffsetParentRelativeRectToViewportRelativeRect:Yk,getDocumentElement:lr,getClippingRect:iP,getOffsetParent:SS,getElementRects:aP,getClientRects:Zk,getDimensions:sP,getScale:Ws,isElement:Dn,isRTL:lP};function bS(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function cP(e,t){let n=null,r;const i=lr(e);function s(){var a;clearTimeout(r),(a=n)==null||a.disconnect(),n=null}function o(a,l){a===void 0&&(a=!1),l===void 0&&(l=1),s();const u=e.getBoundingClientRect(),{left:f,top:c,width:d,height:h}=u;if(a||t(),!d||!h)return;const g=Ul(c),v=Ul(i.clientWidth-(f+d)),x=Ul(i.clientHeight-(c+h)),m=Ul(f),w={rootMargin:-g+"px "+-v+"px "+-x+"px "+-m+"px",threshold:Yt(0,gi(1,l))||1};let S=!0;function k(E){const y=E[0].intersectionRatio;if(y!==l){if(!S)return o();y?o(!1,y):r=setTimeout(()=>{o(!1,1e-7)},1e3)}y===1&&!bS(u,e.getBoundingClientRect())&&o(),S=!1}try{n=new IntersectionObserver(k,{...w,root:i.ownerDocument})}catch{n=new IntersectionObserver(k,w)}n.observe(e)}return o(!0),s}function fP(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:i=!0,ancestorResize:s=!0,elementResize:o=typeof ResizeObserver=="function",layoutShift:a=typeof IntersectionObserver=="function",animationFrame:l=!1}=r,u=sm(e),f=i||s?[...u?Va(u):[],...Va(t)]:[];f.forEach(m=>{i&&m.addEventListener("scroll",n,{passive:!0}),s&&m.addEventListener("resize",n)});const c=u&&a?cP(u,n):null;let d=-1,h=null;o&&(h=new ResizeObserver(m=>{let[p]=m;p&&p.target===u&&h&&(h.unobserve(t),cancelAnimationFrame(d),d=requestAnimationFrame(()=>{var w;(w=h)==null||w.observe(t)})),n()}),u&&!l&&h.observe(u),h.observe(t));let g,v=l?ts(e):null;l&&x();function x(){const m=ts(e);v&&!bS(v,m)&&n(),v=m,g=requestAnimationFrame(x)}return n(),()=>{var m;f.forEach(p=>{i&&p.removeEventListener("scroll",n),s&&p.removeEventListener("resize",n)}),c==null||c(),(m=h)==null||m.disconnect(),h=null,l&&cancelAnimationFrame(g)}}const dP=Vk,hP=Wk,pP=Uk,mP=Kk,gP=Bk,Fy=zk,yP=Qk,vP=(e,t,n)=>{const r=new Map,i={platform:uP,...n},s={...i.platform,_c:r};return jk(e,t,{...i,platform:s})};var mu=typeof document<"u"?_.useLayoutEffect:_.useEffect;function ec(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,i;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!ec(e[r],t[r]))return!1;return!0}if(i=Object.keys(e),n=i.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,i[r]))return!1;for(r=n;r--!==0;){const s=i[r];if(!(s==="_owner"&&e.$$typeof)&&!ec(e[s],t[s]))return!1}return!0}return e!==e&&t!==t}function ES(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function Dy(e,t){const n=ES(e);return Math.round(t*n)/n}function Hf(e){const t=_.useRef(e);return mu(()=>{t.current=e}),t}function wP(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:i,elements:{reference:s,floating:o}={},transform:a=!0,whileElementsMounted:l,open:u}=e,[f,c]=_.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[d,h]=_.useState(r);ec(d,r)||h(r);const[g,v]=_.useState(null),[x,m]=_.useState(null),p=_.useCallback(M=>{M!==E.current&&(E.current=M,v(M))},[]),w=_.useCallback(M=>{M!==y.current&&(y.current=M,m(M))},[]),S=s||g,k=o||x,E=_.useRef(null),y=_.useRef(null),R=_.useRef(f),T=l!=null,A=Hf(l),O=Hf(i),I=Hf(u),z=_.useCallback(()=>{if(!E.current||!y.current)return;const M={placement:t,strategy:n,middleware:d};O.current&&(M.platform=O.current),vP(E.current,y.current,M).then(U=>{const b={...U,isPositioned:I.current!==!1};B.current&&!ec(R.current,b)&&(R.current=b,sl.flushSync(()=>{c(b)}))})},[d,t,n,O,I]);mu(()=>{u===!1&&R.current.isPositioned&&(R.current.isPositioned=!1,c(M=>({...M,isPositioned:!1})))},[u]);const B=_.useRef(!1);mu(()=>(B.current=!0,()=>{B.current=!1}),[]),mu(()=>{if(S&&(E.current=S),k&&(y.current=k),S&&k){if(A.current)return A.current(S,k,z);z()}},[S,k,z,A,T]);const V=_.useMemo(()=>({reference:E,floating:y,setReference:p,setFloating:w}),[p,w]),G=_.useMemo(()=>({reference:S,floating:k}),[S,k]),Q=_.useMemo(()=>{const M={position:n,left:0,top:0};if(!G.floating)return M;const U=Dy(G.floating,f.x),b=Dy(G.floating,f.y);return a?{...M,transform:"translate("+U+"px, "+b+"px)",...ES(G.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:U,top:b}},[n,a,G.floating,f.x,f.y]);return _.useMemo(()=>({...f,update:z,refs:V,elements:G,floatingStyles:Q}),[f,z,V,G,Q])}const xP=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:i}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?Fy({element:r.current,padding:i}).fn(n):{}:r?Fy({element:r,padding:i}).fn(n):{}}}},SP=(e,t)=>({...dP(e),options:[e,t]}),bP=(e,t)=>({...hP(e),options:[e,t]}),EP=(e,t)=>({...yP(e),options:[e,t]}),_P=(e,t)=>({...pP(e),options:[e,t]}),CP=(e,t)=>({...mP(e),options:[e,t]}),kP=(e,t)=>({...gP(e),options:[e,t]}),PP=(e,t)=>({...xP(e),options:[e,t]});var RP="Arrow",_S=_.forwardRef((e,t)=>{const{children:n,width:r=10,height:i=5,...s}=e;return Y.jsx(os.svg,{...s,ref:t,width:r,height:i,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:Y.jsx("polygon",{points:"0,0 30,0 15,10"})})});_S.displayName=RP;var AP=_S;function TP(e){const[t,n]=_.useState(void 0);return po(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(i=>{if(!Array.isArray(i)||!i.length)return;const s=i[0];let o,a;if("borderBoxSize"in s){const l=s.borderBoxSize,u=Array.isArray(l)?l[0]:l;o=u.inlineSize,a=u.blockSize}else o=e.offsetWidth,a=e.offsetHeight;n({width:o,height:a})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}var am="Popper",[CS,kS]=a0(am),[OP,PS]=CS(am),RS=e=>{const{__scopePopper:t,children:n}=e,[r,i]=_.useState(null);return Y.jsx(OP,{scope:t,anchor:r,onAnchorChange:i,children:n})};RS.displayName=am;var AS="PopperAnchor",TS=_.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...i}=e,s=PS(AS,n),o=_.useRef(null),a=rs(t,o);return _.useEffect(()=>{s.onAnchorChange((r==null?void 0:r.current)||o.current)}),r?null:Y.jsx(os.div,{...i,ref:a})});TS.displayName=AS;var lm="PopperContent",[IP,LP]=CS(lm),OS=_.forwardRef((e,t)=>{var qe,vt,xn,Sn,dr,Ge;const{__scopePopper:n,side:r="bottom",sideOffset:i=0,align:s="center",alignOffset:o=0,arrowPadding:a=0,avoidCollisions:l=!0,collisionBoundary:u=[],collisionPadding:f=0,sticky:c="partial",hideWhenDetached:d=!1,updatePositionStrategy:h="optimized",onPlaced:g,...v}=e,x=PS(lm,n),[m,p]=_.useState(null),w=rs(t,Ft=>p(Ft)),[S,k]=_.useState(null),E=TP(S),y=(E==null?void 0:E.width)??0,R=(E==null?void 0:E.height)??0,T=r+(s!=="center"?"-"+s:""),A=typeof f=="number"?f:{top:0,right:0,bottom:0,left:0,...f},O=Array.isArray(u)?u:[u],I=O.length>0,z={padding:A,boundary:O.filter(NP),altBoundary:I},{refs:B,floatingStyles:V,placement:G,isPositioned:Q,middlewareData:M}=wP({strategy:"fixed",placement:T,whileElementsMounted:(...Ft)=>fP(...Ft,{animationFrame:h==="always"}),elements:{reference:x.anchor},middleware:[SP({mainAxis:i+R,alignmentAxis:o}),l&&bP({mainAxis:!0,crossAxis:!1,limiter:c==="partial"?EP():void 0,...z}),l&&_P({...z}),CP({...z,apply:({elements:Ft,rects:Ri,availableWidth:us,availableHeight:on})=>{const{width:cs,height:Oo}=Ri.reference,Un=Ft.floating.style;Un.setProperty("--radix-popper-available-width",`${us}px`),Un.setProperty("--radix-popper-available-height",`${on}px`),Un.setProperty("--radix-popper-anchor-width",`${cs}px`),Un.setProperty("--radix-popper-anchor-height",`${Oo}px`)}}),S&&PP({element:S,padding:a}),FP({arrowWidth:y,arrowHeight:R}),d&&kP({strategy:"referenceHidden",...z})]}),[U,b]=MS(G),Z=bo(g);po(()=>{Q&&(Z==null||Z())},[Q,Z]);const pe=(qe=M.arrow)==null?void 0:qe.x,C=(vt=M.arrow)==null?void 0:vt.y,Ae=((xn=M.arrow)==null?void 0:xn.centerOffset)!==0,[Le,ye]=_.useState();return po(()=>{m&&ye(window.getComputedStyle(m).zIndex)},[m]),Y.jsx("div",{ref:B.setFloating,"data-radix-popper-content-wrapper":"",style:{...V,transform:Q?V.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Le,"--radix-popper-transform-origin":[(Sn=M.transformOrigin)==null?void 0:Sn.x,(dr=M.transformOrigin)==null?void 0:dr.y].join(" "),...((Ge=M.hide)==null?void 0:Ge.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:Y.jsx(IP,{scope:n,placedSide:U,onArrowChange:k,arrowX:pe,arrowY:C,shouldHideArrow:Ae,children:Y.jsx(os.div,{"data-side":U,"data-align":b,...v,ref:w,style:{...v.style,animation:Q?void 0:"none"}})})})});OS.displayName=lm;var IS="PopperArrow",MP={top:"bottom",right:"left",bottom:"top",left:"right"},LS=_.forwardRef(function(t,n){const{__scopePopper:r,...i}=t,s=LP(IS,r),o=MP[s.placedSide];return Y.jsx("span",{ref:s.onArrowChange,style:{position:"absolute",left:s.arrowX,top:s.arrowY,[o]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[s.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[s.placedSide],visibility:s.shouldHideArrow?"hidden":void 0},children:Y.jsx(AP,{...i,ref:n,style:{...i.style,display:"block"}})})});LS.displayName=IS;function NP(e){return e!==null}var FP=e=>({name:"transformOrigin",options:e,fn(t){var x,m,p;const{placement:n,rects:r,middlewareData:i}=t,o=((x=i.arrow)==null?void 0:x.centerOffset)!==0,a=o?0:e.arrowWidth,l=o?0:e.arrowHeight,[u,f]=MS(n),c={start:"0%",center:"50%",end:"100%"}[f],d=(((m=i.arrow)==null?void 0:m.x)??0)+a/2,h=(((p=i.arrow)==null?void 0:p.y)??0)+l/2;let g="",v="";return u==="bottom"?(g=o?c:`${d}px`,v=`${-l}px`):u==="top"?(g=o?c:`${d}px`,v=`${r.floating.height+l}px`):u==="right"?(g=`${-l}px`,v=o?c:`${h}px`):u==="left"&&(g=`${r.floating.width+l}px`,v=o?c:`${h}px`),{data:{x:g,y:v}}}});function MS(e){const[t,n="center"]=e.split("-");return[t,n]}var DP=RS,$P=TS,jP=OS,zP=LS;function UP(e,t){return _.useReducer((n,r)=>t[n][r]??n,e)}var NS=e=>{const{present:t,children:n}=e,r=BP(t),i=typeof n=="function"?n({present:r.isPresent}):_.Children.only(n),s=rs(r.ref,HP(i));return typeof n=="function"||r.isPresent?_.cloneElement(i,{ref:s}):null};NS.displayName="Presence";function BP(e){const[t,n]=_.useState(),r=_.useRef({}),i=_.useRef(e),s=_.useRef("none"),o=e?"mounted":"unmounted",[a,l]=UP(o,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return _.useEffect(()=>{const u=Bl(r.current);s.current=a==="mounted"?u:"none"},[a]),po(()=>{const u=r.current,f=i.current;if(f!==e){const d=s.current,h=Bl(u);e?l("MOUNT"):h==="none"||(u==null?void 0:u.display)==="none"?l("UNMOUNT"):l(f&&d!==h?"ANIMATION_OUT":"UNMOUNT"),i.current=e}},[e,l]),po(()=>{if(t){let u;const f=t.ownerDocument.defaultView??window,c=h=>{const v=Bl(r.current).includes(h.animationName);if(h.target===t&&v&&(l("ANIMATION_END"),!i.current)){const x=t.style.animationFillMode;t.style.animationFillMode="forwards",u=f.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=x)})}},d=h=>{h.target===t&&(s.current=Bl(r.current))};return t.addEventListener("animationstart",d),t.addEventListener("animationcancel",c),t.addEventListener("animationend",c),()=>{f.clearTimeout(u),t.removeEventListener("animationstart",d),t.removeEventListener("animationcancel",c),t.removeEventListener("animationend",c)}}else l("ANIMATION_END")},[t,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:_.useCallback(u=>{u&&(r.current=getComputedStyle(u)),n(u)},[])}}function Bl(e){return(e==null?void 0:e.animationName)||"none"}function HP(e){var r,i;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(i=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:i.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}function VP({prop:e,defaultProp:t,onChange:n=()=>{}}){const[r,i]=WP({defaultProp:t,onChange:n}),s=e!==void 0,o=s?e:r,a=bo(n),l=_.useCallback(u=>{if(s){const c=typeof u=="function"?u(e):u;c!==e&&a(c)}else i(u)},[s,e,i,a]);return[o,l]}function WP({defaultProp:e,onChange:t}){const n=_.useState(e),[r]=n,i=_.useRef(r),s=bo(t);return _.useEffect(()=>{i.current!==r&&(s(r),i.current=r)},[r,i,s]),n}var QP="VisuallyHidden",FS=_.forwardRef((e,t)=>Y.jsx(os.span,{...e,ref:t,style:{position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal",...e.style}}));FS.displayName=QP;var KP=FS,[Dc,b2]=a0("Tooltip",[kS]),$c=kS(),DS="TooltipProvider",qP=700,bh="tooltip.open",[JP,um]=Dc(DS),$S=e=>{const{__scopeTooltip:t,delayDuration:n=qP,skipDelayDuration:r=300,disableHoverableContent:i=!1,children:s}=e,o=_.useRef(!0),a=_.useRef(!1),l=_.useRef(0);return _.useEffect(()=>{const u=l.current;return()=>window.clearTimeout(u)},[]),Y.jsx(JP,{scope:t,isOpenDelayedRef:o,delayDuration:n,onOpen:_.useCallback(()=>{window.clearTimeout(l.current),o.current=!1},[]),onClose:_.useCallback(()=>{window.clearTimeout(l.current),l.current=window.setTimeout(()=>o.current=!0,r)},[r]),isPointerInTransitRef:a,onPointerInTransitChange:_.useCallback(u=>{a.current=u},[]),disableHoverableContent:i,children:s})};$S.displayName=DS;var jc="Tooltip",[GP,zc]=Dc(jc),jS=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:i=!1,onOpenChange:s,disableHoverableContent:o,delayDuration:a}=e,l=um(jc,e.__scopeTooltip),u=$c(t),[f,c]=_.useState(null),d=Tk(),h=_.useRef(0),g=o??l.disableHoverableContent,v=a??l.delayDuration,x=_.useRef(!1),[m=!1,p]=VP({prop:r,defaultProp:i,onChange:y=>{y?(l.onOpen(),document.dispatchEvent(new CustomEvent(bh))):l.onClose(),s==null||s(y)}}),w=_.useMemo(()=>m?x.current?"delayed-open":"instant-open":"closed",[m]),S=_.useCallback(()=>{window.clearTimeout(h.current),h.current=0,x.current=!1,p(!0)},[p]),k=_.useCallback(()=>{window.clearTimeout(h.current),h.current=0,p(!1)},[p]),E=_.useCallback(()=>{window.clearTimeout(h.current),h.current=window.setTimeout(()=>{x.current=!0,p(!0),h.current=0},v)},[v,p]);return _.useEffect(()=>()=>{h.current&&(window.clearTimeout(h.current),h.current=0)},[]),Y.jsx(DP,{...u,children:Y.jsx(GP,{scope:t,contentId:d,open:m,stateAttribute:w,trigger:f,onTriggerChange:c,onTriggerEnter:_.useCallback(()=>{l.isOpenDelayedRef.current?E():S()},[l.isOpenDelayedRef,E,S]),onTriggerLeave:_.useCallback(()=>{g?k():(window.clearTimeout(h.current),h.current=0)},[k,g]),onOpen:S,onClose:k,disableHoverableContent:g,children:n})})};jS.displayName=jc;var Eh="TooltipTrigger",zS=_.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,i=zc(Eh,n),s=um(Eh,n),o=$c(n),a=_.useRef(null),l=rs(t,a,i.onTriggerChange),u=_.useRef(!1),f=_.useRef(!1),c=_.useCallback(()=>u.current=!1,[]);return _.useEffect(()=>()=>document.removeEventListener("pointerup",c),[c]),Y.jsx($P,{asChild:!0,...o,children:Y.jsx(os.button,{"aria-describedby":i.open?i.contentId:void 0,"data-state":i.stateAttribute,...r,ref:l,onPointerMove:Sr(e.onPointerMove,d=>{d.pointerType!=="touch"&&!f.current&&!s.isPointerInTransitRef.current&&(i.onTriggerEnter(),f.current=!0)}),onPointerLeave:Sr(e.onPointerLeave,()=>{i.onTriggerLeave(),f.current=!1}),onPointerDown:Sr(e.onPointerDown,()=>{i.open&&i.onClose(),u.current=!0,document.addEventListener("pointerup",c,{once:!0})}),onFocus:Sr(e.onFocus,()=>{u.current||i.onOpen()}),onBlur:Sr(e.onBlur,i.onClose),onClick:Sr(e.onClick,i.onClose)})})});zS.displayName=Eh;var XP="TooltipPortal",[E2,YP]=Dc(XP,{forceMount:void 0}),go="TooltipContent",US=_.forwardRef((e,t)=>{const n=YP(go,e.__scopeTooltip),{forceMount:r=n.forceMount,side:i="top",...s}=e,o=zc(go,e.__scopeTooltip);return Y.jsx(NS,{present:r||o.open,children:o.disableHoverableContent?Y.jsx(BS,{side:i,...s,ref:t}):Y.jsx(ZP,{side:i,...s,ref:t})})}),ZP=_.forwardRef((e,t)=>{const n=zc(go,e.__scopeTooltip),r=um(go,e.__scopeTooltip),i=_.useRef(null),s=rs(t,i),[o,a]=_.useState(null),{trigger:l,onClose:u}=n,f=i.current,{onPointerInTransitChange:c}=r,d=_.useCallback(()=>{a(null),c(!1)},[c]),h=_.useCallback((g,v)=>{const x=g.currentTarget,m={x:g.clientX,y:g.clientY},p=iR(m,x.getBoundingClientRect()),w=sR(m,p),S=oR(v.getBoundingClientRect()),k=lR([...w,...S]);a(k),c(!0)},[c]);return _.useEffect(()=>()=>d(),[d]),_.useEffect(()=>{if(l&&f){const g=x=>h(x,f),v=x=>h(x,l);return l.addEventListener("pointerleave",g),f.addEventListener("pointerleave",v),()=>{l.removeEventListener("pointerleave",g),f.removeEventListener("pointerleave",v)}}},[l,f,h,d]),_.useEffect(()=>{if(o){const g=v=>{const x=v.target,m={x:v.clientX,y:v.clientY},p=(l==null?void 0:l.contains(x))||(f==null?void 0:f.contains(x)),w=!aR(m,o);p?d():w&&(d(),u())};return document.addEventListener("pointermove",g),()=>document.removeEventListener("pointermove",g)}},[l,f,o,u,d]),Y.jsx(BS,{...e,ref:s})}),[eR,tR]=Dc(jc,{isInside:!1}),nR=pk("TooltipContent"),BS=_.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":i,onEscapeKeyDown:s,onPointerDownOutside:o,...a}=e,l=zc(go,n),u=$c(n),{onClose:f}=l;return _.useEffect(()=>(document.addEventListener(bh,f),()=>document.removeEventListener(bh,f)),[f]),_.useEffect(()=>{if(l.trigger){const c=d=>{const h=d.target;h!=null&&h.contains(l.trigger)&&f()};return window.addEventListener("scroll",c,{capture:!0}),()=>window.removeEventListener("scroll",c,{capture:!0})}},[l.trigger,f]),Y.jsx(dS,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:s,onPointerDownOutside:o,onFocusOutside:c=>c.preventDefault(),onDismiss:f,children:Y.jsxs(jP,{"data-state":l.stateAttribute,...u,...a,ref:t,style:{...a.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[Y.jsx(nR,{children:r}),Y.jsx(eR,{scope:n,isInside:!0,children:Y.jsx(KP,{id:l.contentId,role:"tooltip",children:i||r})})]})})});US.displayName=go;var HS="TooltipArrow",rR=_.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,i=$c(n);return tR(HS,n).isInside?null:Y.jsx(zP,{...i,...r,ref:t})});rR.displayName=HS;function iR(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),i=Math.abs(t.right-e.x),s=Math.abs(t.left-e.x);switch(Math.min(n,r,i,s)){case s:return"left";case i:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function sR(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}function oR(e){const{top:t,right:n,bottom:r,left:i}=e;return[{x:i,y:t},{x:n,y:t},{x:n,y:r},{x:i,y:r}]}function aR(e,t){const{x:n,y:r}=e;let i=!1;for(let s=0,o=t.length-1;sr!=f>r&&n<(u-a)*(r-l)/(f-l)+a&&(i=!i)}return i}function lR(e){const t=e.slice();return t.sort((n,r)=>n.xr.x?1:n.yr.y?1:0),uR(t)}function uR(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r=2;){const s=t[t.length-1],o=t[t.length-2];if((s.x-o.x)*(i.y-o.y)>=(s.y-o.y)*(i.x-o.x))t.pop();else break}t.push(i)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const i=e[r];for(;n.length>=2;){const s=n[n.length-1],o=n[n.length-2];if((s.x-o.x)*(i.y-o.y)>=(s.y-o.y)*(i.x-o.x))n.pop();else break}n.push(i)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}var cR=$S,fR=jS,dR=zS,VS=US;function WS(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e)){var i=e.length;for(t=0;t{const t=gR(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:o=>{const a=o.split(cm);return a[0]===""&&a.length!==1&&a.shift(),QS(a,t)||mR(o)},getConflictingClassGroupIds:(o,a)=>{const l=n[o]||[];return a&&r[o]?[...l,...r[o]]:l}}},QS=(e,t)=>{var o;if(e.length===0)return t.classGroupId;const n=e[0],r=t.nextPart.get(n),i=r?QS(e.slice(1),r):void 0;if(i)return i;if(t.validators.length===0)return;const s=e.join(cm);return(o=t.validators.find(({validator:a})=>a(s)))==null?void 0:o.classGroupId},$y=/^\[(.+)\]$/,mR=e=>{if($y.test(e)){const t=$y.exec(e)[1],n=t==null?void 0:t.substring(0,t.indexOf(":"));if(n)return"arbitrary.."+n}},gR=e=>{const{theme:t,prefix:n}=e,r={nextPart:new Map,validators:[]};return vR(Object.entries(e.classGroups),n).forEach(([s,o])=>{_h(o,r,s,t)}),r},_h=(e,t,n,r)=>{e.forEach(i=>{if(typeof i=="string"){const s=i===""?t:jy(t,i);s.classGroupId=n;return}if(typeof i=="function"){if(yR(i)){_h(i(r),t,n,r);return}t.validators.push({validator:i,classGroupId:n});return}Object.entries(i).forEach(([s,o])=>{_h(o,jy(t,s),n,r)})})},jy=(e,t)=>{let n=e;return t.split(cm).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n},yR=e=>e.isThemeGetter,vR=(e,t)=>t?e.map(([n,r])=>{const i=r.map(s=>typeof s=="string"?t+s:typeof s=="object"?Object.fromEntries(Object.entries(s).map(([o,a])=>[t+o,a])):s);return[n,i]}):e,wR=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=new Map,r=new Map;const i=(s,o)=>{n.set(s,o),t++,t>e&&(t=0,r=n,n=new Map)};return{get(s){let o=n.get(s);if(o!==void 0)return o;if((o=r.get(s))!==void 0)return i(s,o),o},set(s,o){n.has(s)?n.set(s,o):i(s,o)}}},KS="!",xR=e=>{const{separator:t,experimentalParseClassName:n}=e,r=t.length===1,i=t[0],s=t.length,o=a=>{const l=[];let u=0,f=0,c;for(let x=0;xf?c-f:void 0;return{modifiers:l,hasImportantModifier:h,baseClassName:g,maybePostfixModifierPosition:v}};return n?a=>n({className:a,parseClassName:o}):o},SR=e=>{if(e.length<=1)return e;const t=[];let n=[];return e.forEach(r=>{r[0]==="["?(t.push(...n.sort(),r),n=[]):n.push(r)}),t.push(...n.sort()),t},bR=e=>({cache:wR(e.cacheSize),parseClassName:xR(e),...pR(e)}),ER=/\s+/,_R=(e,t)=>{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:i}=t,s=[],o=e.trim().split(ER);let a="";for(let l=o.length-1;l>=0;l-=1){const u=o[l],{modifiers:f,hasImportantModifier:c,baseClassName:d,maybePostfixModifierPosition:h}=n(u);let g=!!h,v=r(g?d.substring(0,h):d);if(!v){if(!g){a=u+(a.length>0?" "+a:a);continue}if(v=r(d),!v){a=u+(a.length>0?" "+a:a);continue}g=!1}const x=SR(f).join(":"),m=c?x+KS:x,p=m+v;if(s.includes(p))continue;s.push(p);const w=i(v,g);for(let S=0;S0?" "+a:a)}return a};function CR(){let e=0,t,n,r="";for(;e{if(typeof e=="string")return e;let t,n="";for(let r=0;rc(f),e());return n=bR(u),r=n.cache.get,i=n.cache.set,s=a,a(l)}function a(l){const u=r(l);if(u)return u;const f=_R(l,n);return i(l,f),f}return function(){return s(CR.apply(null,arguments))}}const Me=e=>{const t=n=>n[e]||[];return t.isThemeGetter=!0,t},JS=/^\[(?:([a-z-]+):)?(.+)\]$/i,PR=/^\d+\/\d+$/,RR=new Set(["px","full","screen"]),AR=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,TR=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,OR=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,IR=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,LR=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,gr=e=>Qs(e)||RR.has(e)||PR.test(e),jr=e=>Co(e,"length",UR),Qs=e=>!!e&&!Number.isNaN(Number(e)),Vf=e=>Co(e,"number",Qs),Ho=e=>!!e&&Number.isInteger(Number(e)),MR=e=>e.endsWith("%")&&Qs(e.slice(0,-1)),de=e=>JS.test(e),zr=e=>AR.test(e),NR=new Set(["length","size","percentage"]),FR=e=>Co(e,NR,GS),DR=e=>Co(e,"position",GS),$R=new Set(["image","url"]),jR=e=>Co(e,$R,HR),zR=e=>Co(e,"",BR),Vo=()=>!0,Co=(e,t,n)=>{const r=JS.exec(e);return r?r[1]?typeof t=="string"?r[1]===t:t.has(r[1]):n(r[2]):!1},UR=e=>TR.test(e)&&!OR.test(e),GS=()=>!1,BR=e=>IR.test(e),HR=e=>LR.test(e),VR=()=>{const e=Me("colors"),t=Me("spacing"),n=Me("blur"),r=Me("brightness"),i=Me("borderColor"),s=Me("borderRadius"),o=Me("borderSpacing"),a=Me("borderWidth"),l=Me("contrast"),u=Me("grayscale"),f=Me("hueRotate"),c=Me("invert"),d=Me("gap"),h=Me("gradientColorStops"),g=Me("gradientColorStopPositions"),v=Me("inset"),x=Me("margin"),m=Me("opacity"),p=Me("padding"),w=Me("saturate"),S=Me("scale"),k=Me("sepia"),E=Me("skew"),y=Me("space"),R=Me("translate"),T=()=>["auto","contain","none"],A=()=>["auto","hidden","clip","visible","scroll"],O=()=>["auto",de,t],I=()=>[de,t],z=()=>["",gr,jr],B=()=>["auto",Qs,de],V=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],G=()=>["solid","dashed","dotted","double","none"],Q=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],M=()=>["start","end","center","between","around","evenly","stretch"],U=()=>["","0",de],b=()=>["auto","avoid","all","avoid-page","page","left","right","column"],Z=()=>[Qs,de];return{cacheSize:500,separator:":",theme:{colors:[Vo],spacing:[gr,jr],blur:["none","",zr,de],brightness:Z(),borderColor:[e],borderRadius:["none","","full",zr,de],borderSpacing:I(),borderWidth:z(),contrast:Z(),grayscale:U(),hueRotate:Z(),invert:U(),gap:I(),gradientColorStops:[e],gradientColorStopPositions:[MR,jr],inset:O(),margin:O(),opacity:Z(),padding:I(),saturate:Z(),scale:Z(),sepia:U(),skew:Z(),space:I(),translate:I()},classGroups:{aspect:[{aspect:["auto","square","video",de]}],container:["container"],columns:[{columns:[zr]}],"break-after":[{"break-after":b()}],"break-before":[{"break-before":b()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...V(),de]}],overflow:[{overflow:A()}],"overflow-x":[{"overflow-x":A()}],"overflow-y":[{"overflow-y":A()}],overscroll:[{overscroll:T()}],"overscroll-x":[{"overscroll-x":T()}],"overscroll-y":[{"overscroll-y":T()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[v]}],"inset-x":[{"inset-x":[v]}],"inset-y":[{"inset-y":[v]}],start:[{start:[v]}],end:[{end:[v]}],top:[{top:[v]}],right:[{right:[v]}],bottom:[{bottom:[v]}],left:[{left:[v]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",Ho,de]}],basis:[{basis:O()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",de]}],grow:[{grow:U()}],shrink:[{shrink:U()}],order:[{order:["first","last","none",Ho,de]}],"grid-cols":[{"grid-cols":[Vo]}],"col-start-end":[{col:["auto",{span:["full",Ho,de]},de]}],"col-start":[{"col-start":B()}],"col-end":[{"col-end":B()}],"grid-rows":[{"grid-rows":[Vo]}],"row-start-end":[{row:["auto",{span:[Ho,de]},de]}],"row-start":[{"row-start":B()}],"row-end":[{"row-end":B()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",de]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",de]}],gap:[{gap:[d]}],"gap-x":[{"gap-x":[d]}],"gap-y":[{"gap-y":[d]}],"justify-content":[{justify:["normal",...M()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...M(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...M(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[p]}],px:[{px:[p]}],py:[{py:[p]}],ps:[{ps:[p]}],pe:[{pe:[p]}],pt:[{pt:[p]}],pr:[{pr:[p]}],pb:[{pb:[p]}],pl:[{pl:[p]}],m:[{m:[x]}],mx:[{mx:[x]}],my:[{my:[x]}],ms:[{ms:[x]}],me:[{me:[x]}],mt:[{mt:[x]}],mr:[{mr:[x]}],mb:[{mb:[x]}],ml:[{ml:[x]}],"space-x":[{"space-x":[y]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[y]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",de,t]}],"min-w":[{"min-w":[de,t,"min","max","fit"]}],"max-w":[{"max-w":[de,t,"none","full","min","max","fit","prose",{screen:[zr]},zr]}],h:[{h:[de,t,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[de,t,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[de,t,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[de,t,"auto","min","max","fit"]}],"font-size":[{text:["base",zr,jr]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",Vf]}],"font-family":[{font:[Vo]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",de]}],"line-clamp":[{"line-clamp":["none",Qs,Vf]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",gr,de]}],"list-image":[{"list-image":["none",de]}],"list-style-type":[{list:["none","disc","decimal",de]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[e]}],"placeholder-opacity":[{"placeholder-opacity":[m]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[e]}],"text-opacity":[{"text-opacity":[m]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...G(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",gr,jr]}],"underline-offset":[{"underline-offset":["auto",gr,de]}],"text-decoration-color":[{decoration:[e]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:I()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",de]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",de]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[m]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...V(),DR]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",FR]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},jR]}],"bg-color":[{bg:[e]}],"gradient-from-pos":[{from:[g]}],"gradient-via-pos":[{via:[g]}],"gradient-to-pos":[{to:[g]}],"gradient-from":[{from:[h]}],"gradient-via":[{via:[h]}],"gradient-to":[{to:[h]}],rounded:[{rounded:[s]}],"rounded-s":[{"rounded-s":[s]}],"rounded-e":[{"rounded-e":[s]}],"rounded-t":[{"rounded-t":[s]}],"rounded-r":[{"rounded-r":[s]}],"rounded-b":[{"rounded-b":[s]}],"rounded-l":[{"rounded-l":[s]}],"rounded-ss":[{"rounded-ss":[s]}],"rounded-se":[{"rounded-se":[s]}],"rounded-ee":[{"rounded-ee":[s]}],"rounded-es":[{"rounded-es":[s]}],"rounded-tl":[{"rounded-tl":[s]}],"rounded-tr":[{"rounded-tr":[s]}],"rounded-br":[{"rounded-br":[s]}],"rounded-bl":[{"rounded-bl":[s]}],"border-w":[{border:[a]}],"border-w-x":[{"border-x":[a]}],"border-w-y":[{"border-y":[a]}],"border-w-s":[{"border-s":[a]}],"border-w-e":[{"border-e":[a]}],"border-w-t":[{"border-t":[a]}],"border-w-r":[{"border-r":[a]}],"border-w-b":[{"border-b":[a]}],"border-w-l":[{"border-l":[a]}],"border-opacity":[{"border-opacity":[m]}],"border-style":[{border:[...G(),"hidden"]}],"divide-x":[{"divide-x":[a]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[a]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[m]}],"divide-style":[{divide:G()}],"border-color":[{border:[i]}],"border-color-x":[{"border-x":[i]}],"border-color-y":[{"border-y":[i]}],"border-color-s":[{"border-s":[i]}],"border-color-e":[{"border-e":[i]}],"border-color-t":[{"border-t":[i]}],"border-color-r":[{"border-r":[i]}],"border-color-b":[{"border-b":[i]}],"border-color-l":[{"border-l":[i]}],"divide-color":[{divide:[i]}],"outline-style":[{outline:["",...G()]}],"outline-offset":[{"outline-offset":[gr,de]}],"outline-w":[{outline:[gr,jr]}],"outline-color":[{outline:[e]}],"ring-w":[{ring:z()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[e]}],"ring-opacity":[{"ring-opacity":[m]}],"ring-offset-w":[{"ring-offset":[gr,jr]}],"ring-offset-color":[{"ring-offset":[e]}],shadow:[{shadow:["","inner","none",zr,zR]}],"shadow-color":[{shadow:[Vo]}],opacity:[{opacity:[m]}],"mix-blend":[{"mix-blend":[...Q(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":Q()}],filter:[{filter:["","none"]}],blur:[{blur:[n]}],brightness:[{brightness:[r]}],contrast:[{contrast:[l]}],"drop-shadow":[{"drop-shadow":["","none",zr,de]}],grayscale:[{grayscale:[u]}],"hue-rotate":[{"hue-rotate":[f]}],invert:[{invert:[c]}],saturate:[{saturate:[w]}],sepia:[{sepia:[k]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[n]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[l]}],"backdrop-grayscale":[{"backdrop-grayscale":[u]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[f]}],"backdrop-invert":[{"backdrop-invert":[c]}],"backdrop-opacity":[{"backdrop-opacity":[m]}],"backdrop-saturate":[{"backdrop-saturate":[w]}],"backdrop-sepia":[{"backdrop-sepia":[k]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[o]}],"border-spacing-x":[{"border-spacing-x":[o]}],"border-spacing-y":[{"border-spacing-y":[o]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",de]}],duration:[{duration:Z()}],ease:[{ease:["linear","in","out","in-out",de]}],delay:[{delay:Z()}],animate:[{animate:["none","spin","ping","pulse","bounce",de]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[S]}],"scale-x":[{"scale-x":[S]}],"scale-y":[{"scale-y":[S]}],rotate:[{rotate:[Ho,de]}],"translate-x":[{"translate-x":[R]}],"translate-y":[{"translate-y":[R]}],"skew-x":[{"skew-x":[E]}],"skew-y":[{"skew-y":[E]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",de]}],accent:[{accent:["auto",e]}],appearance:[{appearance:["none","auto"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",de]}],"caret-color":[{caret:[e]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":I()}],"scroll-mx":[{"scroll-mx":I()}],"scroll-my":[{"scroll-my":I()}],"scroll-ms":[{"scroll-ms":I()}],"scroll-me":[{"scroll-me":I()}],"scroll-mt":[{"scroll-mt":I()}],"scroll-mr":[{"scroll-mr":I()}],"scroll-mb":[{"scroll-mb":I()}],"scroll-ml":[{"scroll-ml":I()}],"scroll-p":[{"scroll-p":I()}],"scroll-px":[{"scroll-px":I()}],"scroll-py":[{"scroll-py":I()}],"scroll-ps":[{"scroll-ps":I()}],"scroll-pe":[{"scroll-pe":I()}],"scroll-pt":[{"scroll-pt":I()}],"scroll-pr":[{"scroll-pr":I()}],"scroll-pb":[{"scroll-pb":I()}],"scroll-pl":[{"scroll-pl":I()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",de]}],fill:[{fill:[e,"none"]}],"stroke-w":[{stroke:[gr,jr,Vf]}],stroke:[{stroke:[e,"none"]}],sr:["sr-only","not-sr-only"],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]}}},WR=kR(VR);globalThis.jotaiAtomCache=globalThis.jotaiAtomCache||{cache:new Map,get(e,t){return this.cache.has(e)?this.cache.get(e):(this.cache.set(e,t),t)}};function QR(...e){return WR(hR(e))}async function _2(e){const t=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",t);return[...new Uint8Array(n)].map(s=>s.toString(16).padStart(2,"0")).join("")}function C2(e){let t=e==="html"?".html":".js",n=e==="html"?"text/html":"application/javascript";return e==="streamlit"&&(t=".py",n="text/python"),[t,n]}function k2(e,t,n){const r=new Blob([e],{type:t}),i=URL.createObjectURL(r),s=document.createElement("a");s.href=i,s.download=n,document.body.append(s),s.click(),s.remove(),URL.revokeObjectURL(i)}async function P2(e,t){const n=new Image,r=new Promise((i,s)=>{n.addEventListener("load",()=>{let{width:o,height:a}=n;(o>t||a>t)&&(o>a?(a*=t/o,o=t):(o*=t/a,a=t));const l=document.querySelector("#resizer"),u=l.getContext("2d");l.width=o,l.height=a,u.drawImage(n,0,0,o,a);const f=l.toDataURL("image/jpeg");i({url:f,width:o,height:a,createdAt:new Date})}),n.addEventListener("error",o=>{s(new Error(`Failed to resize image: ${o.message}`))})});return n.src=e,r}const R2=580;globalThis.jotaiAtomCache=globalThis.jotaiAtomCache||{cache:new Map,get(e,t){return this.cache.has(e)?this.cache.get(e):(this.cache.set(e,t),t)}};const KR=cR,A2=fR,T2=dR,qR=_.forwardRef(({className:e,sideOffset:t=4,...n},r)=>Y.jsx(VS,{ref:r,sideOffset:t,className:QR("z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...n}));qR.displayName=VS.displayName;globalThis.jotaiAtomCache=globalThis.jotaiAtomCache||{cache:new Map,get(e,t){return this.cache.has(e)?this.cache.get(e):(this.cache.set(e,t),t)}};const JR=500;function O2(e,t=JR){const[n,r]=Ki.useState(e),i=Ki.useRef(null);return Ki.useEffect(()=>{const s=Date.now();if(i.current&&s>=i.current+t)i.current=s,r(e);else{const o=window.setTimeout(()=>{i.current=s,r(e)},t);return()=>window.clearTimeout(o)}return()=>{}},[e,t]),n}function GR(e){const[t,n]=_.useState(()=>matchMedia(e).matches);return _.useLayoutEffect(()=>{const r=matchMedia(e);function i(){n(r.matches)}return r.addEventListener("change",i),()=>{r.removeEventListener("change",i)}},[e]),t}function XR(){const[e,t]=_.useState(()=>window.location.hash),n=_.useCallback(()=>{t(window.location.hash)},[]);_.useEffect(()=>(window.addEventListener("hashchange",n),()=>{window.removeEventListener("hashchange",n)}),[n]);const r=_.useCallback(i=>{i!==e&&(window.location.hash=i)},[e]);return[e,r]}function I2(e){const[t,n]=XR(),r=_.useCallback(s=>s<0?n(""):n(`#v${s}`),[n]),i=_.useMemo(()=>t.includes("#v")?Math.min(Number.parseInt(t.replace("#v",""),10),e.latestVersion):e.latestVersion,[t,e.latestVersion]);return _.useEffect(()=>{i>e.latestVersion&&r(e.latestVersion)},[i,e.latestVersion,r]),[i,r]}/** +`+s.stack}return{value:e,source:t,stack:i,digest:null}}function $f(e,t,n){return{value:e,source:null,stack:n??null,digest:t??null}}function ih(e,t){try{console.error(t.value)}catch(n){setTimeout(function(){throw n})}}var z_=typeof WeakMap=="function"?WeakMap:Map;function Nx(e,t,n){n=kr(-1,n),n.tag=3,n.payload={element:null};var r=t.value;return n.callback=function(){Ku||(Ku=!0,ph=r),ih(e,t)},n}function Fx(e,t,n){n=kr(-1,n),n.tag=3;var r=e.type.getDerivedStateFromError;if(typeof r=="function"){var i=t.value;n.payload=function(){return r(i)},n.callback=function(){ih(e,t)}}var s=e.stateNode;return s!==null&&typeof s.componentDidCatch=="function"&&(n.callback=function(){ih(e,t),typeof r!="function"&&(ci===null?ci=new Set([this]):ci.add(this));var o=t.stack;this.componentDidCatch(t.value,{componentStack:o!==null?o:""})}),n}function cy(e,t,n){var r=e.pingCache;if(r===null){r=e.pingCache=new z_;var i=new Set;r.set(t,i)}else i=r.get(t),i===void 0&&(i=new Set,r.set(t,i));i.has(n)||(i.add(n),e=ek.bind(null,e,t,n),t.then(e,e))}function fy(e){do{var t;if((t=e.tag===13)&&(t=e.memoizedState,t=t!==null?t.dehydrated!==null:!0),t)return e;e=e.return}while(e!==null);return null}function dy(e,t,n,r,i){return e.mode&1?(e.flags|=65536,e.lanes=i,e):(e===t?e.flags|=65536:(e.flags|=128,n.flags|=131072,n.flags&=-52805,n.tag===1&&(n.alternate===null?n.tag=17:(t=kr(-1,1),t.tag=2,ui(n,t,1))),n.lanes|=1),e)}var U_=Lr.ReactCurrentOwner,Ut=!1;function Ot(e,t,n,r){t.child=e===null?fx(t,null,n,r):uo(t,e.child,n,r)}function hy(e,t,n,r,i){n=n.render;var s=t.ref;return Hs(t,i),r=$p(e,t,n,r,s,i),n=jp(),e!==null&&!Ut?(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~i,Tr(e,t,i)):($e&&n&&kp(t),t.flags|=1,Ot(e,t,r,i),t.child)}function py(e,t,n,r,i){if(e===null){var s=n.type;return typeof s=="function"&&!Jp(s)&&s.defaultProps===void 0&&n.compare===null&&n.defaultProps===void 0?(t.tag=15,t.type=s,Dx(e,t,s,r,i)):(e=pu(n.type,null,r,t,t.mode,i),e.ref=t.ref,e.return=t,t.child=e)}if(s=e.child,!(e.lanes&i)){var o=s.memoizedProps;if(n=n.compare,n=n!==null?n:La,n(o,r)&&e.ref===t.ref)return Tr(e,t,i)}return t.flags|=1,e=di(s,r),e.ref=t.ref,e.return=t,t.child=e}function Dx(e,t,n,r,i){if(e!==null){var s=e.memoizedProps;if(La(s,r)&&e.ref===t.ref)if(Ut=!1,t.pendingProps=r=s,(e.lanes&i)!==0)e.flags&131072&&(Ut=!0);else return t.lanes=e.lanes,Tr(e,t,i)}return sh(e,t,n,r,i)}function $x(e,t,n){var r=t.pendingProps,i=r.children,s=e!==null?e.memoizedState:null;if(r.mode==="hidden")if(!(t.mode&1))t.memoizedState={baseLanes:0,cachePool:null,transitions:null},Oe(Ds,Gt),Gt|=n;else{if(!(n&1073741824))return e=s!==null?s.baseLanes|n:n,t.lanes=t.childLanes=1073741824,t.memoizedState={baseLanes:e,cachePool:null,transitions:null},t.updateQueue=null,Oe(Ds,Gt),Gt|=e,null;t.memoizedState={baseLanes:0,cachePool:null,transitions:null},r=s!==null?s.baseLanes:n,Oe(Ds,Gt),Gt|=r}else s!==null?(r=s.baseLanes|n,t.memoizedState=null):r=n,Oe(Ds,Gt),Gt|=r;return Ot(e,t,i,n),t.child}function jx(e,t){var n=t.ref;(e===null&&n!==null||e!==null&&e.ref!==n)&&(t.flags|=512,t.flags|=2097152)}function sh(e,t,n,r,i){var s=Ht(n)?Gi:Pt.current;return s=ao(t,s),Hs(t,i),n=$p(e,t,n,r,s,i),r=jp(),e!==null&&!Ut?(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~i,Tr(e,t,i)):($e&&r&&kp(t),t.flags|=1,Ot(e,t,n,i),t.child)}function my(e,t,n,r,i){if(Ht(n)){var s=!0;Du(t)}else s=!1;if(Hs(t,i),t.stateNode===null)fu(e,t),Mx(t,n,r),rh(t,n,r,i),r=!0;else if(e===null){var o=t.stateNode,a=t.memoizedProps;o.props=a;var l=o.context,u=n.contextType;typeof u=="object"&&u!==null?u=gn(u):(u=Ht(n)?Gi:Pt.current,u=ao(t,u));var f=n.getDerivedStateFromProps,c=typeof f=="function"||typeof o.getSnapshotBeforeUpdate=="function";c||typeof o.UNSAFE_componentWillReceiveProps!="function"&&typeof o.componentWillReceiveProps!="function"||(a!==r||l!==u)&&uy(t,o,r,u),qr=!1;var d=t.memoizedState;o.state=d,Bu(t,r,o,i),l=t.memoizedState,a!==r||d!==l||Bt.current||qr?(typeof f=="function"&&(nh(t,n,f,r),l=t.memoizedState),(a=qr||ly(t,n,a,r,d,l,u))?(c||typeof o.UNSAFE_componentWillMount!="function"&&typeof o.componentWillMount!="function"||(typeof o.componentWillMount=="function"&&o.componentWillMount(),typeof o.UNSAFE_componentWillMount=="function"&&o.UNSAFE_componentWillMount()),typeof o.componentDidMount=="function"&&(t.flags|=4194308)):(typeof o.componentDidMount=="function"&&(t.flags|=4194308),t.memoizedProps=r,t.memoizedState=l),o.props=r,o.state=l,o.context=u,r=a):(typeof o.componentDidMount=="function"&&(t.flags|=4194308),r=!1)}else{o=t.stateNode,hx(e,t),a=t.memoizedProps,u=t.type===t.elementType?a:_n(t.type,a),o.props=u,c=t.pendingProps,d=o.context,l=n.contextType,typeof l=="object"&&l!==null?l=gn(l):(l=Ht(n)?Gi:Pt.current,l=ao(t,l));var h=n.getDerivedStateFromProps;(f=typeof h=="function"||typeof o.getSnapshotBeforeUpdate=="function")||typeof o.UNSAFE_componentWillReceiveProps!="function"&&typeof o.componentWillReceiveProps!="function"||(a!==c||d!==l)&&uy(t,o,r,l),qr=!1,d=t.memoizedState,o.state=d,Bu(t,r,o,i);var g=t.memoizedState;a!==c||d!==g||Bt.current||qr?(typeof h=="function"&&(nh(t,n,h,r),g=t.memoizedState),(u=qr||ly(t,n,u,r,d,g,l)||!1)?(f||typeof o.UNSAFE_componentWillUpdate!="function"&&typeof o.componentWillUpdate!="function"||(typeof o.componentWillUpdate=="function"&&o.componentWillUpdate(r,g,l),typeof o.UNSAFE_componentWillUpdate=="function"&&o.UNSAFE_componentWillUpdate(r,g,l)),typeof o.componentDidUpdate=="function"&&(t.flags|=4),typeof o.getSnapshotBeforeUpdate=="function"&&(t.flags|=1024)):(typeof o.componentDidUpdate!="function"||a===e.memoizedProps&&d===e.memoizedState||(t.flags|=4),typeof o.getSnapshotBeforeUpdate!="function"||a===e.memoizedProps&&d===e.memoizedState||(t.flags|=1024),t.memoizedProps=r,t.memoizedState=g),o.props=r,o.state=g,o.context=l,r=u):(typeof o.componentDidUpdate!="function"||a===e.memoizedProps&&d===e.memoizedState||(t.flags|=4),typeof o.getSnapshotBeforeUpdate!="function"||a===e.memoizedProps&&d===e.memoizedState||(t.flags|=1024),r=!1)}return oh(e,t,n,r,s,i)}function oh(e,t,n,r,i,s){jx(e,t);var o=(t.flags&128)!==0;if(!r&&!o)return i&&ey(t,n,!1),Tr(e,t,s);r=t.stateNode,U_.current=t;var a=o&&typeof n.getDerivedStateFromError!="function"?null:r.render();return t.flags|=1,e!==null&&o?(t.child=uo(t,e.child,null,s),t.child=uo(t,null,a,s)):Ot(e,t,a,s),t.memoizedState=r.state,i&&ey(t,n,!0),t.child}function zx(e){var t=e.stateNode;t.pendingContext?Zg(e,t.pendingContext,t.pendingContext!==t.context):t.context&&Zg(e,t.context,!1),Mp(e,t.containerInfo)}function gy(e,t,n,r,i){return lo(),Rp(i),t.flags|=256,Ot(e,t,n,r),t.child}var ah={dehydrated:null,treeContext:null,retryLane:0};function lh(e){return{baseLanes:e,cachePool:null,transitions:null}}function Ux(e,t,n){var r=t.pendingProps,i=ze.current,s=!1,o=(t.flags&128)!==0,a;if((a=o)||(a=e!==null&&e.memoizedState===null?!1:(i&2)!==0),a?(s=!0,t.flags&=-129):(e===null||e.memoizedState!==null)&&(i|=1),Oe(ze,i&1),e===null)return eh(t),e=t.memoizedState,e!==null&&(e=e.dehydrated,e!==null)?(t.mode&1?e.data==="$!"?t.lanes=8:t.lanes=1073741824:t.lanes=1,null):(o=r.children,e=r.fallback,s?(r=t.mode,s=t.child,o={mode:"hidden",children:o},!(r&1)&&s!==null?(s.childLanes=0,s.pendingProps=o):s=Ac(o,r,0,null),e=Ji(e,r,n,null),s.return=t,e.return=t,s.sibling=e,t.child=s,t.child.memoizedState=lh(n),t.memoizedState=ah,e):Bp(t,o));if(i=e.memoizedState,i!==null&&(a=i.dehydrated,a!==null))return B_(e,t,o,r,a,i,n);if(s){s=r.fallback,o=t.mode,i=e.child,a=i.sibling;var l={mode:"hidden",children:r.children};return!(o&1)&&t.child!==i?(r=t.child,r.childLanes=0,r.pendingProps=l,t.deletions=null):(r=di(i,l),r.subtreeFlags=i.subtreeFlags&14680064),a!==null?s=di(a,s):(s=Ji(s,o,n,null),s.flags|=2),s.return=t,r.return=t,r.sibling=s,t.child=r,r=s,s=t.child,o=e.child.memoizedState,o=o===null?lh(n):{baseLanes:o.baseLanes|n,cachePool:null,transitions:o.transitions},s.memoizedState=o,s.childLanes=e.childLanes&~n,t.memoizedState=ah,r}return s=e.child,e=s.sibling,r=di(s,{mode:"visible",children:r.children}),!(t.mode&1)&&(r.lanes=n),r.return=t,r.sibling=null,e!==null&&(n=t.deletions,n===null?(t.deletions=[e],t.flags|=16):n.push(e)),t.child=r,t.memoizedState=null,r}function Bp(e,t){return t=Ac({mode:"visible",children:t},e.mode,0,null),t.return=e,e.child=t}function Dl(e,t,n,r){return r!==null&&Rp(r),uo(t,e.child,null,n),e=Bp(t,t.pendingProps.children),e.flags|=2,t.memoizedState=null,e}function B_(e,t,n,r,i,s,o){if(n)return t.flags&256?(t.flags&=-257,r=$f(Error(j(422))),Dl(e,t,o,r)):t.memoizedState!==null?(t.child=e.child,t.flags|=128,null):(s=r.fallback,i=t.mode,r=Ac({mode:"visible",children:r.children},i,0,null),s=Ji(s,i,o,null),s.flags|=2,r.return=t,s.return=t,r.sibling=s,t.child=r,t.mode&1&&uo(t,e.child,null,o),t.child.memoizedState=lh(o),t.memoizedState=ah,s);if(!(t.mode&1))return Dl(e,t,o,null);if(i.data==="$!"){if(r=i.nextSibling&&i.nextSibling.dataset,r)var a=r.dgst;return r=a,s=Error(j(419)),r=$f(s,r,void 0),Dl(e,t,o,r)}if(a=(o&e.childLanes)!==0,Ut||a){if(r=lt,r!==null){switch(o&-o){case 4:i=2;break;case 16:i=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:i=32;break;case 536870912:i=268435456;break;default:i=0}i=i&(r.suspendedLanes|o)?0:i,i!==0&&i!==s.retryLane&&(s.retryLane=i,Ar(e,i),Nn(r,e,i,-1))}return qp(),r=$f(Error(j(421))),Dl(e,t,o,r)}return i.data==="$?"?(t.flags|=128,t.child=e.child,t=tk.bind(null,e),i._reactRetry=t,null):(e=s.treeContext,Zt=li(i.nextSibling),en=t,$e=!0,On=null,e!==null&&(cn[fn++]=Cr,cn[fn++]=_r,cn[fn++]=Xi,Cr=e.id,_r=e.overflow,Xi=t),t=Bp(t,r.children),t.flags|=4096,t)}function yy(e,t,n){e.lanes|=t;var r=e.alternate;r!==null&&(r.lanes|=t),th(e.return,t,n)}function jf(e,t,n,r,i){var s=e.memoizedState;s===null?e.memoizedState={isBackwards:t,rendering:null,renderingStartTime:0,last:r,tail:n,tailMode:i}:(s.isBackwards=t,s.rendering=null,s.renderingStartTime=0,s.last=r,s.tail=n,s.tailMode=i)}function Bx(e,t,n){var r=t.pendingProps,i=r.revealOrder,s=r.tail;if(Ot(e,t,r.children,n),r=ze.current,r&2)r=r&1|2,t.flags|=128;else{if(e!==null&&e.flags&128)e:for(e=t.child;e!==null;){if(e.tag===13)e.memoizedState!==null&&yy(e,n,t);else if(e.tag===19)yy(e,n,t);else if(e.child!==null){e.child.return=e,e=e.child;continue}if(e===t)break e;for(;e.sibling===null;){if(e.return===null||e.return===t)break e;e=e.return}e.sibling.return=e.return,e=e.sibling}r&=1}if(Oe(ze,r),!(t.mode&1))t.memoizedState=null;else switch(i){case"forwards":for(n=t.child,i=null;n!==null;)e=n.alternate,e!==null&&Hu(e)===null&&(i=n),n=n.sibling;n=i,n===null?(i=t.child,t.child=null):(i=n.sibling,n.sibling=null),jf(t,!1,i,n,s);break;case"backwards":for(n=null,i=t.child,t.child=null;i!==null;){if(e=i.alternate,e!==null&&Hu(e)===null){t.child=i;break}e=i.sibling,i.sibling=n,n=i,i=e}jf(t,!0,n,null,s);break;case"together":jf(t,!1,null,null,void 0);break;default:t.memoizedState=null}return t.child}function fu(e,t){!(t.mode&1)&&e!==null&&(e.alternate=null,t.alternate=null,t.flags|=2)}function Tr(e,t,n){if(e!==null&&(t.dependencies=e.dependencies),Zi|=t.lanes,!(n&t.childLanes))return null;if(e!==null&&t.child!==e.child)throw Error(j(153));if(t.child!==null){for(e=t.child,n=di(e,e.pendingProps),t.child=n,n.return=t;e.sibling!==null;)e=e.sibling,n=n.sibling=di(e,e.pendingProps),n.return=t;n.sibling=null}return t.child}function H_(e,t,n){switch(t.tag){case 3:zx(t),lo();break;case 5:px(t);break;case 1:Ht(t.type)&&Du(t);break;case 4:Mp(t,t.stateNode.containerInfo);break;case 10:var r=t.type._context,i=t.memoizedProps.value;Oe(zu,r._currentValue),r._currentValue=i;break;case 13:if(r=t.memoizedState,r!==null)return r.dehydrated!==null?(Oe(ze,ze.current&1),t.flags|=128,null):n&t.child.childLanes?Ux(e,t,n):(Oe(ze,ze.current&1),e=Tr(e,t,n),e!==null?e.sibling:null);Oe(ze,ze.current&1);break;case 19:if(r=(n&t.childLanes)!==0,e.flags&128){if(r)return Bx(e,t,n);t.flags|=128}if(i=t.memoizedState,i!==null&&(i.rendering=null,i.tail=null,i.lastEffect=null),Oe(ze,ze.current),r)break;return null;case 22:case 23:return t.lanes=0,$x(e,t,n)}return Tr(e,t,n)}var Hx,uh,Vx,Wx;Hx=function(e,t){for(var n=t.child;n!==null;){if(n.tag===5||n.tag===6)e.appendChild(n.stateNode);else if(n.tag!==4&&n.child!==null){n.child.return=n,n=n.child;continue}if(n===t)break;for(;n.sibling===null;){if(n.return===null||n.return===t)return;n=n.return}n.sibling.return=n.return,n=n.sibling}};uh=function(){};Vx=function(e,t,n,r){var i=e.memoizedProps;if(i!==r){e=t.stateNode,ji(rr.current);var s=null;switch(n){case"input":i=Od(e,i),r=Od(e,r),s=[];break;case"select":i=Be({},i,{value:void 0}),r=Be({},r,{value:void 0}),s=[];break;case"textarea":i=Md(e,i),r=Md(e,r),s=[];break;default:typeof i.onClick!="function"&&typeof r.onClick=="function"&&(e.onclick=Nu)}Fd(n,r);var o;n=null;for(u in i)if(!r.hasOwnProperty(u)&&i.hasOwnProperty(u)&&i[u]!=null)if(u==="style"){var a=i[u];for(o in a)a.hasOwnProperty(o)&&(n||(n={}),n[o]="")}else u!=="dangerouslySetInnerHTML"&&u!=="children"&&u!=="suppressContentEditableWarning"&&u!=="suppressHydrationWarning"&&u!=="autoFocus"&&(ka.hasOwnProperty(u)?s||(s=[]):(s=s||[]).push(u,null));for(u in r){var l=r[u];if(a=i!=null?i[u]:void 0,r.hasOwnProperty(u)&&l!==a&&(l!=null||a!=null))if(u==="style")if(a){for(o in a)!a.hasOwnProperty(o)||l&&l.hasOwnProperty(o)||(n||(n={}),n[o]="");for(o in l)l.hasOwnProperty(o)&&a[o]!==l[o]&&(n||(n={}),n[o]=l[o])}else n||(s||(s=[]),s.push(u,n)),n=l;else u==="dangerouslySetInnerHTML"?(l=l?l.__html:void 0,a=a?a.__html:void 0,l!=null&&a!==l&&(s=s||[]).push(u,l)):u==="children"?typeof l!="string"&&typeof l!="number"||(s=s||[]).push(u,""+l):u!=="suppressContentEditableWarning"&&u!=="suppressHydrationWarning"&&(ka.hasOwnProperty(u)?(l!=null&&u==="onScroll"&&Ne("scroll",e),s||a===l||(s=[])):(s=s||[]).push(u,l))}n&&(s=s||[]).push("style",n);var u=s;(t.updateQueue=u)&&(t.flags|=4)}};Wx=function(e,t,n,r){n!==r&&(t.flags|=4)};function Uo(e,t){if(!$e)switch(e.tailMode){case"hidden":t=e.tail;for(var n=null;t!==null;)t.alternate!==null&&(n=t),t=t.sibling;n===null?e.tail=null:n.sibling=null;break;case"collapsed":n=e.tail;for(var r=null;n!==null;)n.alternate!==null&&(r=n),n=n.sibling;r===null?t||e.tail===null?e.tail=null:e.tail.sibling=null:r.sibling=null}}function Et(e){var t=e.alternate!==null&&e.alternate.child===e.child,n=0,r=0;if(t)for(var i=e.child;i!==null;)n|=i.lanes|i.childLanes,r|=i.subtreeFlags&14680064,r|=i.flags&14680064,i.return=e,i=i.sibling;else for(i=e.child;i!==null;)n|=i.lanes|i.childLanes,r|=i.subtreeFlags,r|=i.flags,i.return=e,i=i.sibling;return e.subtreeFlags|=r,e.childLanes=n,t}function V_(e,t,n){var r=t.pendingProps;switch(Pp(t),t.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Et(t),null;case 1:return Ht(t.type)&&Fu(),Et(t),null;case 3:return r=t.stateNode,co(),Fe(Bt),Fe(Pt),Fp(),r.pendingContext&&(r.context=r.pendingContext,r.pendingContext=null),(e===null||e.child===null)&&(Nl(t)?t.flags|=4:e===null||e.memoizedState.isDehydrated&&!(t.flags&256)||(t.flags|=1024,On!==null&&(yh(On),On=null))),uh(e,t),Et(t),null;case 5:Np(t);var i=ji($a.current);if(n=t.type,e!==null&&t.stateNode!=null)Vx(e,t,n,r,i),e.ref!==t.ref&&(t.flags|=512,t.flags|=2097152);else{if(!r){if(t.stateNode===null)throw Error(j(166));return Et(t),null}if(e=ji(rr.current),Nl(t)){r=t.stateNode,n=t.type;var s=t.memoizedProps;switch(r[Yn]=t,r[Fa]=s,e=(t.mode&1)!==0,n){case"dialog":Ne("cancel",r),Ne("close",r);break;case"iframe":case"object":case"embed":Ne("load",r);break;case"video":case"audio":for(i=0;i<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=o.createElement(n,{is:r.is}):(e=o.createElement(n),n==="select"&&(o=e,r.multiple?o.multiple=!0:r.size&&(o.size=r.size))):e=o.createElementNS(e,n),e[Yn]=t,e[Fa]=r,Hx(e,t,!1,!1),t.stateNode=e;e:{switch(o=Dd(n,r),n){case"dialog":Ne("cancel",e),Ne("close",e),i=r;break;case"iframe":case"object":case"embed":Ne("load",e),i=r;break;case"video":case"audio":for(i=0;iho&&(t.flags|=128,r=!0,Uo(s,!1),t.lanes=4194304)}else{if(!r)if(e=Hu(o),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),Uo(s,!0),s.tail===null&&s.tailMode==="hidden"&&!o.alternate&&!$e)return Et(t),null}else 2*Je()-s.renderingStartTime>ho&&n!==1073741824&&(t.flags|=128,r=!0,Uo(s,!1),t.lanes=4194304);s.isBackwards?(o.sibling=t.child,t.child=o):(n=s.last,n!==null?n.sibling=o:t.child=o,s.last=o)}return s.tail!==null?(t=s.tail,s.rendering=t,s.tail=t.sibling,s.renderingStartTime=Je(),t.sibling=null,n=ze.current,Oe(ze,r?n&1|2:n&1),t):(Et(t),null);case 22:case 23:return Kp(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?Gt&1073741824&&(Et(t),t.subtreeFlags&6&&(t.flags|=8192)):Et(t),null;case 24:return null;case 25:return null}throw Error(j(156,t.tag))}function W_(e,t){switch(Pp(t),t.tag){case 1:return Ht(t.type)&&Fu(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return co(),Fe(Bt),Fe(Pt),Fp(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Np(t),null;case 13:if(Fe(ze),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(j(340));lo()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return Fe(ze),null;case 4:return co(),null;case 10:return Op(t.type._context),null;case 22:case 23:return Kp(),null;case 24:return null;default:return null}}var $l=!1,kt=!1,Q_=typeof WeakSet=="function"?WeakSet:Set,K=null;function Fs(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){Qe(e,t,r)}else n.current=null}function ch(e,t,n){try{n()}catch(r){Qe(e,t,r)}}var vy=!1;function K_(e,t){if(Kd=Iu,e=G0(),_p(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var i=r.anchorOffset,s=r.focusNode;r=r.focusOffset;try{n.nodeType,s.nodeType}catch{n=null;break e}var o=0,a=-1,l=-1,u=0,f=0,c=e,d=null;t:for(;;){for(var h;c!==n||i!==0&&c.nodeType!==3||(a=o+i),c!==s||r!==0&&c.nodeType!==3||(l=o+r),c.nodeType===3&&(o+=c.nodeValue.length),(h=c.firstChild)!==null;)d=c,c=h;for(;;){if(c===e)break t;if(d===n&&++u===i&&(a=o),d===s&&++f===r&&(l=o),(h=c.nextSibling)!==null)break;c=d,d=c.parentNode}c=h}n=a===-1||l===-1?null:{start:a,end:l}}else n=null}n=n||{start:0,end:0}}else n=null;for(qd={focusedElem:e,selectionRange:n},Iu=!1,K=t;K!==null;)if(t=K,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,K=e;else for(;K!==null;){t=K;try{var g=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(g!==null){var v=g.memoizedProps,x=g.memoizedState,m=t.stateNode,p=m.getSnapshotBeforeUpdate(t.elementType===t.type?v:_n(t.type,v),x);m.__reactInternalSnapshotBeforeUpdate=p}break;case 3:var w=t.stateNode.containerInfo;w.nodeType===1?w.textContent="":w.nodeType===9&&w.documentElement&&w.removeChild(w.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(j(163))}}catch(S){Qe(t,t.return,S)}if(e=t.sibling,e!==null){e.return=t.return,K=e;break}K=t.return}return g=vy,vy=!1,g}function ga(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var i=r=r.next;do{if((i.tag&e)===e){var s=i.destroy;i.destroy=void 0,s!==void 0&&ch(t,n,s)}i=i.next}while(i!==r)}}function Pc(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function fh(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function Qx(e){var t=e.alternate;t!==null&&(e.alternate=null,Qx(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Yn],delete t[Fa],delete t[Xd],delete t[A_],delete t[T_])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function Kx(e){return e.tag===5||e.tag===3||e.tag===4}function wy(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Kx(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function dh(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=Nu));else if(r!==4&&(e=e.child,e!==null))for(dh(e,t,n),e=e.sibling;e!==null;)dh(e,t,n),e=e.sibling}function hh(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(hh(e,t,n),e=e.sibling;e!==null;)hh(e,t,n),e=e.sibling}var ft=null,An=!1;function $r(e,t,n){for(n=n.child;n!==null;)qx(e,t,n),n=n.sibling}function qx(e,t,n){if(nr&&typeof nr.onCommitFiberUnmount=="function")try{nr.onCommitFiberUnmount(wc,n)}catch{}switch(n.tag){case 5:kt||Fs(n,t);case 6:var r=ft,i=An;ft=null,$r(e,t,n),ft=r,An=i,ft!==null&&(An?(e=ft,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):ft.removeChild(n.stateNode));break;case 18:ft!==null&&(An?(e=ft,n=n.stateNode,e.nodeType===8?If(e.parentNode,n):e.nodeType===1&&If(e,n),Oa(e)):If(ft,n.stateNode));break;case 4:r=ft,i=An,ft=n.stateNode.containerInfo,An=!0,$r(e,t,n),ft=r,An=i;break;case 0:case 11:case 14:case 15:if(!kt&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){i=r=r.next;do{var s=i,o=s.destroy;s=s.tag,o!==void 0&&(s&2||s&4)&&ch(n,t,o),i=i.next}while(i!==r)}$r(e,t,n);break;case 1:if(!kt&&(Fs(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(a){Qe(n,t,a)}$r(e,t,n);break;case 21:$r(e,t,n);break;case 22:n.mode&1?(kt=(r=kt)||n.memoizedState!==null,$r(e,t,n),kt=r):$r(e,t,n);break;default:$r(e,t,n)}}function xy(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new Q_),t.forEach(function(r){var i=nk.bind(null,e,r);n.has(r)||(n.add(r),r.then(i,i))})}}function bn(e,t){var n=t.deletions;if(n!==null)for(var r=0;ri&&(i=o),r&=~s}if(r=i,r=Je()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*J_(r/1960))-r,10e?16:e,ri===null)var r=!1;else{if(e=ri,ri=null,qu=0,we&6)throw Error(j(331));var i=we;for(we|=4,K=e.current;K!==null;){var s=K,o=s.child;if(K.flags&16){var a=s.deletions;if(a!==null){for(var l=0;lJe()-Wp?qi(e,0):Vp|=n),Vt(e,t)}function nS(e,t){t===0&&(e.mode&1?(t=Al,Al<<=1,!(Al&130023424)&&(Al=4194304)):t=1);var n=Lt();e=Ar(e,t),e!==null&&(tl(e,t,n),Vt(e,n))}function tk(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),nS(e,n)}function nk(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,i=e.memoizedState;i!==null&&(n=i.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(j(314))}r!==null&&r.delete(t),nS(e,n)}var rS;rS=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||Bt.current)Ut=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return Ut=!1,H_(e,t,n);Ut=!!(e.flags&131072)}else Ut=!1,$e&&t.flags&1048576&&ax(t,ju,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;fu(e,t),e=t.pendingProps;var i=ao(t,Pt.current);Hs(t,n),i=$p(null,t,r,e,i,n);var s=jp();return t.flags|=1,typeof i=="object"&&i!==null&&typeof i.render=="function"&&i.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,Ht(r)?(s=!0,Du(t)):s=!1,t.memoizedState=i.state!==null&&i.state!==void 0?i.state:null,Lp(t),i.updater=kc,t.stateNode=i,i._reactInternals=t,rh(t,r,e,n),t=oh(null,t,r,!0,s,n)):(t.tag=0,$e&&s&&kp(t),Ot(null,t,i,n),t=t.child),t;case 16:r=t.elementType;e:{switch(fu(e,t),e=t.pendingProps,i=r._init,r=i(r._payload),t.type=r,i=t.tag=ik(r),e=_n(r,e),i){case 0:t=sh(null,t,r,e,n);break e;case 1:t=my(null,t,r,e,n);break e;case 11:t=hy(null,t,r,e,n);break e;case 14:t=py(null,t,r,_n(r.type,e),n);break e}throw Error(j(306,r,""))}return t;case 0:return r=t.type,i=t.pendingProps,i=t.elementType===r?i:_n(r,i),sh(e,t,r,i,n);case 1:return r=t.type,i=t.pendingProps,i=t.elementType===r?i:_n(r,i),my(e,t,r,i,n);case 3:e:{if(zx(t),e===null)throw Error(j(387));r=t.pendingProps,s=t.memoizedState,i=s.element,hx(e,t),Bu(t,r,null,n);var o=t.memoizedState;if(r=o.element,s.isDehydrated)if(s={element:r,isDehydrated:!1,cache:o.cache,pendingSuspenseBoundaries:o.pendingSuspenseBoundaries,transitions:o.transitions},t.updateQueue.baseState=s,t.memoizedState=s,t.flags&256){i=fo(Error(j(423)),t),t=gy(e,t,r,n,i);break e}else if(r!==i){i=fo(Error(j(424)),t),t=gy(e,t,r,n,i);break e}else for(Zt=li(t.stateNode.containerInfo.firstChild),en=t,$e=!0,On=null,n=fx(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(lo(),r===i){t=Tr(e,t,n);break e}Ot(e,t,r,n)}t=t.child}return t;case 5:return px(t),e===null&&eh(t),r=t.type,i=t.pendingProps,s=e!==null?e.memoizedProps:null,o=i.children,Jd(r,i)?o=null:s!==null&&Jd(r,s)&&(t.flags|=32),jx(e,t),Ot(e,t,o,n),t.child;case 6:return e===null&&eh(t),null;case 13:return Ux(e,t,n);case 4:return Mp(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=uo(t,null,r,n):Ot(e,t,r,n),t.child;case 11:return r=t.type,i=t.pendingProps,i=t.elementType===r?i:_n(r,i),hy(e,t,r,i,n);case 7:return Ot(e,t,t.pendingProps,n),t.child;case 8:return Ot(e,t,t.pendingProps.children,n),t.child;case 12:return Ot(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,i=t.pendingProps,s=t.memoizedProps,o=i.value,Oe(zu,r._currentValue),r._currentValue=o,s!==null)if(Fn(s.value,o)){if(s.children===i.children&&!Bt.current){t=Tr(e,t,n);break e}}else for(s=t.child,s!==null&&(s.return=t);s!==null;){var a=s.dependencies;if(a!==null){o=s.child;for(var l=a.firstContext;l!==null;){if(l.context===r){if(s.tag===1){l=kr(-1,n&-n),l.tag=2;var u=s.updateQueue;if(u!==null){u=u.shared;var f=u.pending;f===null?l.next=l:(l.next=f.next,f.next=l),u.pending=l}}s.lanes|=n,l=s.alternate,l!==null&&(l.lanes|=n),th(s.return,n,t),a.lanes|=n;break}l=l.next}}else if(s.tag===10)o=s.type===t.type?null:s.child;else if(s.tag===18){if(o=s.return,o===null)throw Error(j(341));o.lanes|=n,a=o.alternate,a!==null&&(a.lanes|=n),th(o,n,t),o=s.sibling}else o=s.child;if(o!==null)o.return=s;else for(o=s;o!==null;){if(o===t){o=null;break}if(s=o.sibling,s!==null){s.return=o.return,o=s;break}o=o.return}s=o}Ot(e,t,i.children,n),t=t.child}return t;case 9:return i=t.type,r=t.pendingProps.children,Hs(t,n),i=gn(i),r=r(i),t.flags|=1,Ot(e,t,r,n),t.child;case 14:return r=t.type,i=_n(r,t.pendingProps),i=_n(r.type,i),py(e,t,r,i,n);case 15:return Dx(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,i=t.pendingProps,i=t.elementType===r?i:_n(r,i),fu(e,t),t.tag=1,Ht(r)?(e=!0,Du(t)):e=!1,Hs(t,n),Mx(t,r,i),rh(t,r,i,n),oh(null,t,r,!0,e,n);case 19:return Bx(e,t,n);case 22:return $x(e,t,n)}throw Error(j(156,t.tag))};function iS(e,t){return O0(e,t)}function rk(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function hn(e,t,n,r){return new rk(e,t,n,r)}function Jp(e){return e=e.prototype,!(!e||!e.isReactComponent)}function ik(e){if(typeof e=="function")return Jp(e)?1:0;if(e!=null){if(e=e.$$typeof,e===pp)return 11;if(e===mp)return 14}return 2}function di(e,t){var n=e.alternate;return n===null?(n=hn(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function pu(e,t,n,r,i,s){var o=2;if(r=e,typeof e=="function")Jp(e)&&(o=1);else if(typeof e=="string")o=5;else e:switch(e){case Ps:return Ji(n.children,i,s,t);case hp:o=8,i|=8;break;case Pd:return e=hn(12,n,t,i|2),e.elementType=Pd,e.lanes=s,e;case Rd:return e=hn(13,n,t,i),e.elementType=Rd,e.lanes=s,e;case Ad:return e=hn(19,n,t,i),e.elementType=Ad,e.lanes=s,e;case p0:return Ac(n,i,s,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case d0:o=10;break e;case h0:o=9;break e;case pp:o=11;break e;case mp:o=14;break e;case Kr:o=16,r=null;break e}throw Error(j(130,e==null?e:typeof e,""))}return t=hn(o,n,t,i),t.elementType=e,t.type=r,t.lanes=s,t}function Ji(e,t,n,r){return e=hn(7,e,r,t),e.lanes=n,e}function Ac(e,t,n,r){return e=hn(22,e,r,t),e.elementType=p0,e.lanes=n,e.stateNode={isHidden:!1},e}function zf(e,t,n){return e=hn(6,e,null,t),e.lanes=n,e}function Uf(e,t,n){return t=hn(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function sk(e,t,n,r,i){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Sf(0),this.expirationTimes=Sf(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Sf(0),this.identifierPrefix=r,this.onRecoverableError=i,this.mutableSourceEagerHydrationData=null}function Gp(e,t,n,r,i,s,o,a,l){return e=new sk(e,t,n,a,l),t===1?(t=1,s===!0&&(t|=8)):t=0,s=hn(3,null,null,t),e.current=s,s.stateNode=e,s.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Lp(s),e}function ok(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(lS)}catch(e){console.error(e)}}lS(),l0.exports=rn;var sl=l0.exports;const fk=rp(sl),dk=$w({__proto__:null,default:fk},[sl]);function uS(e){const t=hk(e),n=C.forwardRef((r,i)=>{const{children:s,...o}=r,a=C.Children.toArray(s),l=a.find(mk);if(l){const u=l.props.children,f=a.map(c=>c===l?C.Children.count(u)>1?C.Children.only(null):C.isValidElement(u)?u.props.children:null:c);return Y.jsx(t,{...o,ref:i,children:C.isValidElement(u)?C.cloneElement(u,void 0,f):null})}return Y.jsx(t,{...o,ref:i,children:s})});return n.displayName=`${e}.Slot`,n}var bD=uS("Slot");function hk(e){const t=C.forwardRef((n,r)=>{const{children:i,...s}=n;if(C.isValidElement(i)){const o=yk(i),a=gk(s,i.props);return i.type!==C.Fragment&&(a.ref=r?o0(r,o):o),C.cloneElement(i,a)}return C.Children.count(i)>1?C.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var cS=Symbol("radix.slottable");function pk(e){const t=({children:n})=>Y.jsx(Y.Fragment,{children:n});return t.displayName=`${e}.Slottable`,t.__radixId=cS,t}function mk(e){return C.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===cS}function gk(e,t){const n={...t};for(const r in t){const i=e[r],s=t[r];/^on[A-Z]/.test(r)?i&&s?n[r]=(...a)=>{s(...a),i(...a)}:i&&(n[r]=i):r==="style"?n[r]={...i,...s}:r==="className"&&(n[r]=[i,s].filter(Boolean).join(" "))}return{...e,...n}}function yk(e){var r,i;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(i=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:i.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var vk=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],os=vk.reduce((e,t)=>{const n=uS(`Primitive.${t}`),r=C.forwardRef((i,s)=>{const{asChild:o,...a}=i,l=o?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),Y.jsx(l,{...a,ref:s})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function wk(e,t){e&&sl.flushSync(()=>e.dispatchEvent(t))}function bo(e){const t=C.useRef(e);return C.useEffect(()=>{t.current=e}),C.useMemo(()=>(...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[])}function xk(e,t=globalThis==null?void 0:globalThis.document){const n=bo(e);C.useEffect(()=>{const r=i=>{i.key==="Escape"&&n(i)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[n,t])}var Sk="DismissableLayer",vh="dismissableLayer.update",bk="dismissableLayer.pointerDownOutside",Ek="dismissableLayer.focusOutside",Ry,fS=C.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),dS=C.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:i,onFocusOutside:s,onInteractOutside:o,onDismiss:a,...l}=e,u=C.useContext(fS),[f,c]=C.useState(null),d=(f==null?void 0:f.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,h]=C.useState({}),g=rs(t,y=>c(y)),v=Array.from(u.layers),[x]=[...u.layersWithOutsidePointerEventsDisabled].slice(-1),m=v.indexOf(x),p=f?v.indexOf(f):-1,w=u.layersWithOutsidePointerEventsDisabled.size>0,S=p>=m,k=kk(y=>{const R=y.target,T=[...u.branches].some(A=>A.contains(R));!S||T||(i==null||i(y),o==null||o(y),y.defaultPrevented||a==null||a())},d),E=Pk(y=>{const R=y.target;[...u.branches].some(A=>A.contains(R))||(s==null||s(y),o==null||o(y),y.defaultPrevented||a==null||a())},d);return xk(y=>{p===u.layers.size-1&&(r==null||r(y),!y.defaultPrevented&&a&&(y.preventDefault(),a()))},d),C.useEffect(()=>{if(f)return n&&(u.layersWithOutsidePointerEventsDisabled.size===0&&(Ry=d.body.style.pointerEvents,d.body.style.pointerEvents="none"),u.layersWithOutsidePointerEventsDisabled.add(f)),u.layers.add(f),Ay(),()=>{n&&u.layersWithOutsidePointerEventsDisabled.size===1&&(d.body.style.pointerEvents=Ry)}},[f,d,n,u]),C.useEffect(()=>()=>{f&&(u.layers.delete(f),u.layersWithOutsidePointerEventsDisabled.delete(f),Ay())},[f,u]),C.useEffect(()=>{const y=()=>h({});return document.addEventListener(vh,y),()=>document.removeEventListener(vh,y)},[]),Y.jsx(os.div,{...l,ref:g,style:{pointerEvents:w?S?"auto":"none":void 0,...e.style},onFocusCapture:Sr(e.onFocusCapture,E.onFocusCapture),onBlurCapture:Sr(e.onBlurCapture,E.onBlurCapture),onPointerDownCapture:Sr(e.onPointerDownCapture,k.onPointerDownCapture)})});dS.displayName=Sk;var Ck="DismissableLayerBranch",_k=C.forwardRef((e,t)=>{const n=C.useContext(fS),r=C.useRef(null),i=rs(t,r);return C.useEffect(()=>{const s=r.current;if(s)return n.branches.add(s),()=>{n.branches.delete(s)}},[n.branches]),Y.jsx(os.div,{...e,ref:i})});_k.displayName=Ck;function kk(e,t=globalThis==null?void 0:globalThis.document){const n=bo(e),r=C.useRef(!1),i=C.useRef(()=>{});return C.useEffect(()=>{const s=a=>{if(a.target&&!r.current){let l=function(){hS(bk,n,u,{discrete:!0})};const u={originalEvent:a};a.pointerType==="touch"?(t.removeEventListener("click",i.current),i.current=l,t.addEventListener("click",i.current,{once:!0})):l()}else t.removeEventListener("click",i.current);r.current=!1},o=window.setTimeout(()=>{t.addEventListener("pointerdown",s)},0);return()=>{window.clearTimeout(o),t.removeEventListener("pointerdown",s),t.removeEventListener("click",i.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function Pk(e,t=globalThis==null?void 0:globalThis.document){const n=bo(e),r=C.useRef(!1);return C.useEffect(()=>{const i=s=>{s.target&&!r.current&&hS(Ek,n,{originalEvent:s},{discrete:!1})};return t.addEventListener("focusin",i),()=>t.removeEventListener("focusin",i)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function Ay(){const e=new CustomEvent(vh);document.dispatchEvent(e)}function hS(e,t,n,{discrete:r}){const i=n.originalEvent.target,s=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&i.addEventListener(e,t,{once:!0}),r?wk(i,s):i.dispatchEvent(s)}var po=globalThis!=null&&globalThis.document?C.useLayoutEffect:()=>{},Rk=Jw[" useId ".trim().toString()]||(()=>{}),Ak=0;function Tk(e){const[t,n]=C.useState(Rk());return po(()=>{n(r=>r??String(Ak++))},[e]),e||(t?`radix-${t}`:"")}const Ok=["top","right","bottom","left"],gi=Math.min,Yt=Math.max,Xu=Math.round,Ul=Math.floor,ir=e=>({x:e,y:e}),Ik={left:"right",right:"left",bottom:"top",top:"bottom"},Lk={start:"end",end:"start"};function wh(e,t,n){return Yt(e,gi(t,n))}function Or(e,t){return typeof e=="function"?e(t):e}function Ir(e){return e.split("-")[0]}function Eo(e){return e.split("-")[1]}function em(e){return e==="x"?"y":"x"}function tm(e){return e==="y"?"height":"width"}function yi(e){return["top","bottom"].includes(Ir(e))?"y":"x"}function nm(e){return em(yi(e))}function Mk(e,t,n){n===void 0&&(n=!1);const r=Eo(e),i=nm(e),s=tm(i);let o=i==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[s]>t.floating[s]&&(o=Yu(o)),[o,Yu(o)]}function Nk(e){const t=Yu(e);return[xh(e),t,xh(t)]}function xh(e){return e.replace(/start|end/g,t=>Lk[t])}function Fk(e,t,n){const r=["left","right"],i=["right","left"],s=["top","bottom"],o=["bottom","top"];switch(e){case"top":case"bottom":return n?t?i:r:t?r:i;case"left":case"right":return t?s:o;default:return[]}}function Dk(e,t,n,r){const i=Eo(e);let s=Fk(Ir(e),n==="start",r);return i&&(s=s.map(o=>o+"-"+i),t&&(s=s.concat(s.map(xh)))),s}function Yu(e){return e.replace(/left|right|bottom|top/g,t=>Ik[t])}function $k(e){return{top:0,right:0,bottom:0,left:0,...e}}function pS(e){return typeof e!="number"?$k(e):{top:e,right:e,bottom:e,left:e}}function Zu(e){const{x:t,y:n,width:r,height:i}=e;return{width:r,height:i,top:n,left:t,right:t+r,bottom:n+i,x:t,y:n}}function Ty(e,t,n){let{reference:r,floating:i}=e;const s=yi(t),o=nm(t),a=tm(o),l=Ir(t),u=s==="y",f=r.x+r.width/2-i.width/2,c=r.y+r.height/2-i.height/2,d=r[a]/2-i[a]/2;let h;switch(l){case"top":h={x:f,y:r.y-i.height};break;case"bottom":h={x:f,y:r.y+r.height};break;case"right":h={x:r.x+r.width,y:c};break;case"left":h={x:r.x-i.width,y:c};break;default:h={x:r.x,y:r.y}}switch(Eo(t)){case"start":h[o]-=d*(n&&u?-1:1);break;case"end":h[o]+=d*(n&&u?-1:1);break}return h}const jk=async(e,t,n)=>{const{placement:r="bottom",strategy:i="absolute",middleware:s=[],platform:o}=n,a=s.filter(Boolean),l=await(o.isRTL==null?void 0:o.isRTL(t));let u=await o.getElementRects({reference:e,floating:t,strategy:i}),{x:f,y:c}=Ty(u,r,l),d=r,h={},g=0;for(let v=0;v({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:i,rects:s,platform:o,elements:a,middlewareData:l}=t,{element:u,padding:f=0}=Or(e,t)||{};if(u==null)return{};const c=pS(f),d={x:n,y:r},h=nm(i),g=tm(h),v=await o.getDimensions(u),x=h==="y",m=x?"top":"left",p=x?"bottom":"right",w=x?"clientHeight":"clientWidth",S=s.reference[g]+s.reference[h]-d[h]-s.floating[g],k=d[h]-s.reference[h],E=await(o.getOffsetParent==null?void 0:o.getOffsetParent(u));let y=E?E[w]:0;(!y||!await(o.isElement==null?void 0:o.isElement(E)))&&(y=a.floating[w]||s.floating[g]);const R=S/2-k/2,T=y/2-v[g]/2-1,A=gi(c[m],T),O=gi(c[p],T),I=A,z=y-v[g]-O,B=y/2-v[g]/2+R,V=wh(I,B,z),G=!l.arrow&&Eo(i)!=null&&B!==V&&s.reference[g]/2-(BB<=0)){var O,I;const B=(((O=s.flip)==null?void 0:O.index)||0)+1,V=y[B];if(V)return{data:{index:B,overflows:A},reset:{placement:V}};let G=(I=A.filter(Q=>Q.overflows[0]<=0).sort((Q,M)=>Q.overflows[1]-M.overflows[1])[0])==null?void 0:I.placement;if(!G)switch(h){case"bestFit":{var z;const Q=(z=A.filter(M=>{if(E){const U=yi(M.placement);return U===p||U==="y"}return!0}).map(M=>[M.placement,M.overflows.filter(U=>U>0).reduce((U,b)=>U+b,0)]).sort((M,U)=>M[1]-U[1])[0])==null?void 0:z[0];Q&&(G=Q);break}case"initialPlacement":G=a;break}if(i!==G)return{reset:{placement:G}}}return{}}}};function Oy(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function Iy(e){return Ok.some(t=>e[t]>=0)}const Bk=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...i}=Or(e,t);switch(r){case"referenceHidden":{const s=await Ha(t,{...i,elementContext:"reference"}),o=Oy(s,n.reference);return{data:{referenceHiddenOffsets:o,referenceHidden:Iy(o)}}}case"escaped":{const s=await Ha(t,{...i,altBoundary:!0}),o=Oy(s,n.floating);return{data:{escapedOffsets:o,escaped:Iy(o)}}}default:return{}}}}};async function Hk(e,t){const{placement:n,platform:r,elements:i}=e,s=await(r.isRTL==null?void 0:r.isRTL(i.floating)),o=Ir(n),a=Eo(n),l=yi(n)==="y",u=["left","top"].includes(o)?-1:1,f=s&&l?-1:1,c=Or(t,e);let{mainAxis:d,crossAxis:h,alignmentAxis:g}=typeof c=="number"?{mainAxis:c,crossAxis:0,alignmentAxis:null}:{mainAxis:c.mainAxis||0,crossAxis:c.crossAxis||0,alignmentAxis:c.alignmentAxis};return a&&typeof g=="number"&&(h=a==="end"?g*-1:g),l?{x:h*f,y:d*u}:{x:d*u,y:h*f}}const Vk=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:i,y:s,placement:o,middlewareData:a}=t,l=await Hk(t,e);return o===((n=a.offset)==null?void 0:n.placement)&&(r=a.arrow)!=null&&r.alignmentOffset?{}:{x:i+l.x,y:s+l.y,data:{...l,placement:o}}}}},Wk=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:i}=t,{mainAxis:s=!0,crossAxis:o=!1,limiter:a={fn:x=>{let{x:m,y:p}=x;return{x:m,y:p}}},...l}=Or(e,t),u={x:n,y:r},f=await Ha(t,l),c=yi(Ir(i)),d=em(c);let h=u[d],g=u[c];if(s){const x=d==="y"?"top":"left",m=d==="y"?"bottom":"right",p=h+f[x],w=h-f[m];h=wh(p,h,w)}if(o){const x=c==="y"?"top":"left",m=c==="y"?"bottom":"right",p=g+f[x],w=g-f[m];g=wh(p,g,w)}const v=a.fn({...t,[d]:h,[c]:g});return{...v,data:{x:v.x-n,y:v.y-r,enabled:{[d]:s,[c]:o}}}}}},Qk=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:i,rects:s,middlewareData:o}=t,{offset:a=0,mainAxis:l=!0,crossAxis:u=!0}=Or(e,t),f={x:n,y:r},c=yi(i),d=em(c);let h=f[d],g=f[c];const v=Or(a,t),x=typeof v=="number"?{mainAxis:v,crossAxis:0}:{mainAxis:0,crossAxis:0,...v};if(l){const w=d==="y"?"height":"width",S=s.reference[d]-s.floating[w]+x.mainAxis,k=s.reference[d]+s.reference[w]-x.mainAxis;hk&&(h=k)}if(u){var m,p;const w=d==="y"?"width":"height",S=["top","left"].includes(Ir(i)),k=s.reference[c]-s.floating[w]+(S&&((m=o.offset)==null?void 0:m[c])||0)+(S?0:x.crossAxis),E=s.reference[c]+s.reference[w]+(S?0:((p=o.offset)==null?void 0:p[c])||0)-(S?x.crossAxis:0);gE&&(g=E)}return{[d]:h,[c]:g}}}},Kk=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var n,r;const{placement:i,rects:s,platform:o,elements:a}=t,{apply:l=()=>{},...u}=Or(e,t),f=await Ha(t,u),c=Ir(i),d=Eo(i),h=yi(i)==="y",{width:g,height:v}=s.floating;let x,m;c==="top"||c==="bottom"?(x=c,m=d===(await(o.isRTL==null?void 0:o.isRTL(a.floating))?"start":"end")?"left":"right"):(m=c,x=d==="end"?"top":"bottom");const p=v-f.top-f.bottom,w=g-f.left-f.right,S=gi(v-f[x],p),k=gi(g-f[m],w),E=!t.middlewareData.shift;let y=S,R=k;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(R=w),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(y=p),E&&!d){const A=Yt(f.left,0),O=Yt(f.right,0),I=Yt(f.top,0),z=Yt(f.bottom,0);h?R=g-2*(A!==0||O!==0?A+O:Yt(f.left,f.right)):y=v-2*(I!==0||z!==0?I+z:Yt(f.top,f.bottom))}await l({...t,availableWidth:R,availableHeight:y});const T=await o.getDimensions(a.floating);return g!==T.width||v!==T.height?{reset:{rects:!0}}:{}}}};function Mc(){return typeof window<"u"}function Co(e){return mS(e)?(e.nodeName||"").toLowerCase():"#document"}function tn(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function lr(e){var t;return(t=(mS(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function mS(e){return Mc()?e instanceof Node||e instanceof tn(e).Node:!1}function Dn(e){return Mc()?e instanceof Element||e instanceof tn(e).Element:!1}function or(e){return Mc()?e instanceof HTMLElement||e instanceof tn(e).HTMLElement:!1}function Ly(e){return!Mc()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof tn(e).ShadowRoot}function ol(e){const{overflow:t,overflowX:n,overflowY:r,display:i}=$n(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!["inline","contents"].includes(i)}function qk(e){return["table","td","th"].includes(Co(e))}function Nc(e){return[":popover-open",":modal"].some(t=>{try{return e.matches(t)}catch{return!1}})}function rm(e){const t=im(),n=Dn(e)?$n(e):e;return["transform","translate","scale","rotate","perspective"].some(r=>n[r]?n[r]!=="none":!1)||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||["transform","translate","scale","rotate","perspective","filter"].some(r=>(n.willChange||"").includes(r))||["paint","layout","strict","content"].some(r=>(n.contain||"").includes(r))}function Jk(e){let t=vi(e);for(;or(t)&&!mo(t);){if(rm(t))return t;if(Nc(t))return null;t=vi(t)}return null}function im(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function mo(e){return["html","body","#document"].includes(Co(e))}function $n(e){return tn(e).getComputedStyle(e)}function Fc(e){return Dn(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function vi(e){if(Co(e)==="html")return e;const t=e.assignedSlot||e.parentNode||Ly(e)&&e.host||lr(e);return Ly(t)?t.host:t}function gS(e){const t=vi(e);return mo(t)?e.ownerDocument?e.ownerDocument.body:e.body:or(t)&&ol(t)?t:gS(t)}function Va(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const i=gS(e),s=i===((r=e.ownerDocument)==null?void 0:r.body),o=tn(i);if(s){const a=Sh(o);return t.concat(o,o.visualViewport||[],ol(i)?i:[],a&&n?Va(a):[])}return t.concat(i,Va(i,[],n))}function Sh(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function yS(e){const t=$n(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const i=or(e),s=i?e.offsetWidth:n,o=i?e.offsetHeight:r,a=Xu(n)!==s||Xu(r)!==o;return a&&(n=s,r=o),{width:n,height:r,$:a}}function sm(e){return Dn(e)?e:e.contextElement}function Ws(e){const t=sm(e);if(!or(t))return ir(1);const n=t.getBoundingClientRect(),{width:r,height:i,$:s}=yS(t);let o=(s?Xu(n.width):n.width)/r,a=(s?Xu(n.height):n.height)/i;return(!o||!Number.isFinite(o))&&(o=1),(!a||!Number.isFinite(a))&&(a=1),{x:o,y:a}}const Gk=ir(0);function vS(e){const t=tn(e);return!im()||!t.visualViewport?Gk:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function Xk(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==tn(e)?!1:t}function ts(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const i=e.getBoundingClientRect(),s=sm(e);let o=ir(1);t&&(r?Dn(r)&&(o=Ws(r)):o=Ws(e));const a=Xk(s,n,r)?vS(s):ir(0);let l=(i.left+a.x)/o.x,u=(i.top+a.y)/o.y,f=i.width/o.x,c=i.height/o.y;if(s){const d=tn(s),h=r&&Dn(r)?tn(r):r;let g=d,v=Sh(g);for(;v&&r&&h!==g;){const x=Ws(v),m=v.getBoundingClientRect(),p=$n(v),w=m.left+(v.clientLeft+parseFloat(p.paddingLeft))*x.x,S=m.top+(v.clientTop+parseFloat(p.paddingTop))*x.y;l*=x.x,u*=x.y,f*=x.x,c*=x.y,l+=w,u+=S,g=tn(v),v=Sh(g)}}return Zu({width:f,height:c,x:l,y:u})}function om(e,t){const n=Fc(e).scrollLeft;return t?t.left+n:ts(lr(e)).left+n}function wS(e,t,n){n===void 0&&(n=!1);const r=e.getBoundingClientRect(),i=r.left+t.scrollLeft-(n?0:om(e,r)),s=r.top+t.scrollTop;return{x:i,y:s}}function Yk(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e;const s=i==="fixed",o=lr(r),a=t?Nc(t.floating):!1;if(r===o||a&&s)return n;let l={scrollLeft:0,scrollTop:0},u=ir(1);const f=ir(0),c=or(r);if((c||!c&&!s)&&((Co(r)!=="body"||ol(o))&&(l=Fc(r)),or(r))){const h=ts(r);u=Ws(r),f.x=h.x+r.clientLeft,f.y=h.y+r.clientTop}const d=o&&!c&&!s?wS(o,l,!0):ir(0);return{width:n.width*u.x,height:n.height*u.y,x:n.x*u.x-l.scrollLeft*u.x+f.x+d.x,y:n.y*u.y-l.scrollTop*u.y+f.y+d.y}}function Zk(e){return Array.from(e.getClientRects())}function eP(e){const t=lr(e),n=Fc(e),r=e.ownerDocument.body,i=Yt(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),s=Yt(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let o=-n.scrollLeft+om(e);const a=-n.scrollTop;return $n(r).direction==="rtl"&&(o+=Yt(t.clientWidth,r.clientWidth)-i),{width:i,height:s,x:o,y:a}}function tP(e,t){const n=tn(e),r=lr(e),i=n.visualViewport;let s=r.clientWidth,o=r.clientHeight,a=0,l=0;if(i){s=i.width,o=i.height;const u=im();(!u||u&&t==="fixed")&&(a=i.offsetLeft,l=i.offsetTop)}return{width:s,height:o,x:a,y:l}}function nP(e,t){const n=ts(e,!0,t==="fixed"),r=n.top+e.clientTop,i=n.left+e.clientLeft,s=or(e)?Ws(e):ir(1),o=e.clientWidth*s.x,a=e.clientHeight*s.y,l=i*s.x,u=r*s.y;return{width:o,height:a,x:l,y:u}}function My(e,t,n){let r;if(t==="viewport")r=tP(e,n);else if(t==="document")r=eP(lr(e));else if(Dn(t))r=nP(t,n);else{const i=vS(e);r={x:t.x-i.x,y:t.y-i.y,width:t.width,height:t.height}}return Zu(r)}function xS(e,t){const n=vi(e);return n===t||!Dn(n)||mo(n)?!1:$n(n).position==="fixed"||xS(n,t)}function rP(e,t){const n=t.get(e);if(n)return n;let r=Va(e,[],!1).filter(a=>Dn(a)&&Co(a)!=="body"),i=null;const s=$n(e).position==="fixed";let o=s?vi(e):e;for(;Dn(o)&&!mo(o);){const a=$n(o),l=rm(o);!l&&a.position==="fixed"&&(i=null),(s?!l&&!i:!l&&a.position==="static"&&!!i&&["absolute","fixed"].includes(i.position)||ol(o)&&!l&&xS(e,o))?r=r.filter(f=>f!==o):i=a,o=vi(o)}return t.set(e,r),r}function iP(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e;const o=[...n==="clippingAncestors"?Nc(t)?[]:rP(t,this._c):[].concat(n),r],a=o[0],l=o.reduce((u,f)=>{const c=My(t,f,i);return u.top=Yt(c.top,u.top),u.right=gi(c.right,u.right),u.bottom=gi(c.bottom,u.bottom),u.left=Yt(c.left,u.left),u},My(t,a,i));return{width:l.right-l.left,height:l.bottom-l.top,x:l.left,y:l.top}}function sP(e){const{width:t,height:n}=yS(e);return{width:t,height:n}}function oP(e,t,n){const r=or(t),i=lr(t),s=n==="fixed",o=ts(e,!0,s,t);let a={scrollLeft:0,scrollTop:0};const l=ir(0);if(r||!r&&!s)if((Co(t)!=="body"||ol(i))&&(a=Fc(t)),r){const d=ts(t,!0,s,t);l.x=d.x+t.clientLeft,l.y=d.y+t.clientTop}else i&&(l.x=om(i));const u=i&&!r&&!s?wS(i,a):ir(0),f=o.left+a.scrollLeft-l.x-u.x,c=o.top+a.scrollTop-l.y-u.y;return{x:f,y:c,width:o.width,height:o.height}}function Bf(e){return $n(e).position==="static"}function Ny(e,t){if(!or(e)||$n(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return lr(e)===n&&(n=n.ownerDocument.body),n}function SS(e,t){const n=tn(e);if(Nc(e))return n;if(!or(e)){let i=vi(e);for(;i&&!mo(i);){if(Dn(i)&&!Bf(i))return i;i=vi(i)}return n}let r=Ny(e,t);for(;r&&qk(r)&&Bf(r);)r=Ny(r,t);return r&&mo(r)&&Bf(r)&&!rm(r)?n:r||Jk(e)||n}const aP=async function(e){const t=this.getOffsetParent||SS,n=this.getDimensions,r=await n(e.floating);return{reference:oP(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function lP(e){return $n(e).direction==="rtl"}const uP={convertOffsetParentRelativeRectToViewportRelativeRect:Yk,getDocumentElement:lr,getClippingRect:iP,getOffsetParent:SS,getElementRects:aP,getClientRects:Zk,getDimensions:sP,getScale:Ws,isElement:Dn,isRTL:lP};function bS(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function cP(e,t){let n=null,r;const i=lr(e);function s(){var a;clearTimeout(r),(a=n)==null||a.disconnect(),n=null}function o(a,l){a===void 0&&(a=!1),l===void 0&&(l=1),s();const u=e.getBoundingClientRect(),{left:f,top:c,width:d,height:h}=u;if(a||t(),!d||!h)return;const g=Ul(c),v=Ul(i.clientWidth-(f+d)),x=Ul(i.clientHeight-(c+h)),m=Ul(f),w={rootMargin:-g+"px "+-v+"px "+-x+"px "+-m+"px",threshold:Yt(0,gi(1,l))||1};let S=!0;function k(E){const y=E[0].intersectionRatio;if(y!==l){if(!S)return o();y?o(!1,y):r=setTimeout(()=>{o(!1,1e-7)},1e3)}y===1&&!bS(u,e.getBoundingClientRect())&&o(),S=!1}try{n=new IntersectionObserver(k,{...w,root:i.ownerDocument})}catch{n=new IntersectionObserver(k,w)}n.observe(e)}return o(!0),s}function fP(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:i=!0,ancestorResize:s=!0,elementResize:o=typeof ResizeObserver=="function",layoutShift:a=typeof IntersectionObserver=="function",animationFrame:l=!1}=r,u=sm(e),f=i||s?[...u?Va(u):[],...Va(t)]:[];f.forEach(m=>{i&&m.addEventListener("scroll",n,{passive:!0}),s&&m.addEventListener("resize",n)});const c=u&&a?cP(u,n):null;let d=-1,h=null;o&&(h=new ResizeObserver(m=>{let[p]=m;p&&p.target===u&&h&&(h.unobserve(t),cancelAnimationFrame(d),d=requestAnimationFrame(()=>{var w;(w=h)==null||w.observe(t)})),n()}),u&&!l&&h.observe(u),h.observe(t));let g,v=l?ts(e):null;l&&x();function x(){const m=ts(e);v&&!bS(v,m)&&n(),v=m,g=requestAnimationFrame(x)}return n(),()=>{var m;f.forEach(p=>{i&&p.removeEventListener("scroll",n),s&&p.removeEventListener("resize",n)}),c==null||c(),(m=h)==null||m.disconnect(),h=null,l&&cancelAnimationFrame(g)}}const dP=Vk,hP=Wk,pP=Uk,mP=Kk,gP=Bk,Fy=zk,yP=Qk,vP=(e,t,n)=>{const r=new Map,i={platform:uP,...n},s={...i.platform,_c:r};return jk(e,t,{...i,platform:s})};var mu=typeof document<"u"?C.useLayoutEffect:C.useEffect;function ec(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,i;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!ec(e[r],t[r]))return!1;return!0}if(i=Object.keys(e),n=i.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,i[r]))return!1;for(r=n;r--!==0;){const s=i[r];if(!(s==="_owner"&&e.$$typeof)&&!ec(e[s],t[s]))return!1}return!0}return e!==e&&t!==t}function ES(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function Dy(e,t){const n=ES(e);return Math.round(t*n)/n}function Hf(e){const t=C.useRef(e);return mu(()=>{t.current=e}),t}function wP(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:i,elements:{reference:s,floating:o}={},transform:a=!0,whileElementsMounted:l,open:u}=e,[f,c]=C.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[d,h]=C.useState(r);ec(d,r)||h(r);const[g,v]=C.useState(null),[x,m]=C.useState(null),p=C.useCallback(M=>{M!==E.current&&(E.current=M,v(M))},[]),w=C.useCallback(M=>{M!==y.current&&(y.current=M,m(M))},[]),S=s||g,k=o||x,E=C.useRef(null),y=C.useRef(null),R=C.useRef(f),T=l!=null,A=Hf(l),O=Hf(i),I=Hf(u),z=C.useCallback(()=>{if(!E.current||!y.current)return;const M={placement:t,strategy:n,middleware:d};O.current&&(M.platform=O.current),vP(E.current,y.current,M).then(U=>{const b={...U,isPositioned:I.current!==!1};B.current&&!ec(R.current,b)&&(R.current=b,sl.flushSync(()=>{c(b)}))})},[d,t,n,O,I]);mu(()=>{u===!1&&R.current.isPositioned&&(R.current.isPositioned=!1,c(M=>({...M,isPositioned:!1})))},[u]);const B=C.useRef(!1);mu(()=>(B.current=!0,()=>{B.current=!1}),[]),mu(()=>{if(S&&(E.current=S),k&&(y.current=k),S&&k){if(A.current)return A.current(S,k,z);z()}},[S,k,z,A,T]);const V=C.useMemo(()=>({reference:E,floating:y,setReference:p,setFloating:w}),[p,w]),G=C.useMemo(()=>({reference:S,floating:k}),[S,k]),Q=C.useMemo(()=>{const M={position:n,left:0,top:0};if(!G.floating)return M;const U=Dy(G.floating,f.x),b=Dy(G.floating,f.y);return a?{...M,transform:"translate("+U+"px, "+b+"px)",...ES(G.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:U,top:b}},[n,a,G.floating,f.x,f.y]);return C.useMemo(()=>({...f,update:z,refs:V,elements:G,floatingStyles:Q}),[f,z,V,G,Q])}const xP=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:i}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?Fy({element:r.current,padding:i}).fn(n):{}:r?Fy({element:r,padding:i}).fn(n):{}}}},SP=(e,t)=>({...dP(e),options:[e,t]}),bP=(e,t)=>({...hP(e),options:[e,t]}),EP=(e,t)=>({...yP(e),options:[e,t]}),CP=(e,t)=>({...pP(e),options:[e,t]}),_P=(e,t)=>({...mP(e),options:[e,t]}),kP=(e,t)=>({...gP(e),options:[e,t]}),PP=(e,t)=>({...xP(e),options:[e,t]});var RP="Arrow",CS=C.forwardRef((e,t)=>{const{children:n,width:r=10,height:i=5,...s}=e;return Y.jsx(os.svg,{...s,ref:t,width:r,height:i,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:Y.jsx("polygon",{points:"0,0 30,0 15,10"})})});CS.displayName=RP;var AP=CS;function TP(e){const[t,n]=C.useState(void 0);return po(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(i=>{if(!Array.isArray(i)||!i.length)return;const s=i[0];let o,a;if("borderBoxSize"in s){const l=s.borderBoxSize,u=Array.isArray(l)?l[0]:l;o=u.inlineSize,a=u.blockSize}else o=e.offsetWidth,a=e.offsetHeight;n({width:o,height:a})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}var am="Popper",[_S,kS]=a0(am),[OP,PS]=_S(am),RS=e=>{const{__scopePopper:t,children:n}=e,[r,i]=C.useState(null);return Y.jsx(OP,{scope:t,anchor:r,onAnchorChange:i,children:n})};RS.displayName=am;var AS="PopperAnchor",TS=C.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...i}=e,s=PS(AS,n),o=C.useRef(null),a=rs(t,o);return C.useEffect(()=>{s.onAnchorChange((r==null?void 0:r.current)||o.current)}),r?null:Y.jsx(os.div,{...i,ref:a})});TS.displayName=AS;var lm="PopperContent",[IP,LP]=_S(lm),OS=C.forwardRef((e,t)=>{var qe,vt,xn,Sn,dr,Ge;const{__scopePopper:n,side:r="bottom",sideOffset:i=0,align:s="center",alignOffset:o=0,arrowPadding:a=0,avoidCollisions:l=!0,collisionBoundary:u=[],collisionPadding:f=0,sticky:c="partial",hideWhenDetached:d=!1,updatePositionStrategy:h="optimized",onPlaced:g,...v}=e,x=PS(lm,n),[m,p]=C.useState(null),w=rs(t,Ft=>p(Ft)),[S,k]=C.useState(null),E=TP(S),y=(E==null?void 0:E.width)??0,R=(E==null?void 0:E.height)??0,T=r+(s!=="center"?"-"+s:""),A=typeof f=="number"?f:{top:0,right:0,bottom:0,left:0,...f},O=Array.isArray(u)?u:[u],I=O.length>0,z={padding:A,boundary:O.filter(NP),altBoundary:I},{refs:B,floatingStyles:V,placement:G,isPositioned:Q,middlewareData:M}=wP({strategy:"fixed",placement:T,whileElementsMounted:(...Ft)=>fP(...Ft,{animationFrame:h==="always"}),elements:{reference:x.anchor},middleware:[SP({mainAxis:i+R,alignmentAxis:o}),l&&bP({mainAxis:!0,crossAxis:!1,limiter:c==="partial"?EP():void 0,...z}),l&&CP({...z}),_P({...z,apply:({elements:Ft,rects:Ri,availableWidth:us,availableHeight:on})=>{const{width:cs,height:Oo}=Ri.reference,Un=Ft.floating.style;Un.setProperty("--radix-popper-available-width",`${us}px`),Un.setProperty("--radix-popper-available-height",`${on}px`),Un.setProperty("--radix-popper-anchor-width",`${cs}px`),Un.setProperty("--radix-popper-anchor-height",`${Oo}px`)}}),S&&PP({element:S,padding:a}),FP({arrowWidth:y,arrowHeight:R}),d&&kP({strategy:"referenceHidden",...z})]}),[U,b]=MS(G),Z=bo(g);po(()=>{Q&&(Z==null||Z())},[Q,Z]);const pe=(qe=M.arrow)==null?void 0:qe.x,_=(vt=M.arrow)==null?void 0:vt.y,Ae=((xn=M.arrow)==null?void 0:xn.centerOffset)!==0,[Le,ye]=C.useState();return po(()=>{m&&ye(window.getComputedStyle(m).zIndex)},[m]),Y.jsx("div",{ref:B.setFloating,"data-radix-popper-content-wrapper":"",style:{...V,transform:Q?V.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Le,"--radix-popper-transform-origin":[(Sn=M.transformOrigin)==null?void 0:Sn.x,(dr=M.transformOrigin)==null?void 0:dr.y].join(" "),...((Ge=M.hide)==null?void 0:Ge.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:Y.jsx(IP,{scope:n,placedSide:U,onArrowChange:k,arrowX:pe,arrowY:_,shouldHideArrow:Ae,children:Y.jsx(os.div,{"data-side":U,"data-align":b,...v,ref:w,style:{...v.style,animation:Q?void 0:"none"}})})})});OS.displayName=lm;var IS="PopperArrow",MP={top:"bottom",right:"left",bottom:"top",left:"right"},LS=C.forwardRef(function(t,n){const{__scopePopper:r,...i}=t,s=LP(IS,r),o=MP[s.placedSide];return Y.jsx("span",{ref:s.onArrowChange,style:{position:"absolute",left:s.arrowX,top:s.arrowY,[o]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[s.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[s.placedSide],visibility:s.shouldHideArrow?"hidden":void 0},children:Y.jsx(AP,{...i,ref:n,style:{...i.style,display:"block"}})})});LS.displayName=IS;function NP(e){return e!==null}var FP=e=>({name:"transformOrigin",options:e,fn(t){var x,m,p;const{placement:n,rects:r,middlewareData:i}=t,o=((x=i.arrow)==null?void 0:x.centerOffset)!==0,a=o?0:e.arrowWidth,l=o?0:e.arrowHeight,[u,f]=MS(n),c={start:"0%",center:"50%",end:"100%"}[f],d=(((m=i.arrow)==null?void 0:m.x)??0)+a/2,h=(((p=i.arrow)==null?void 0:p.y)??0)+l/2;let g="",v="";return u==="bottom"?(g=o?c:`${d}px`,v=`${-l}px`):u==="top"?(g=o?c:`${d}px`,v=`${r.floating.height+l}px`):u==="right"?(g=`${-l}px`,v=o?c:`${h}px`):u==="left"&&(g=`${r.floating.width+l}px`,v=o?c:`${h}px`),{data:{x:g,y:v}}}});function MS(e){const[t,n="center"]=e.split("-");return[t,n]}var DP=RS,$P=TS,jP=OS,zP=LS;function UP(e,t){return C.useReducer((n,r)=>t[n][r]??n,e)}var NS=e=>{const{present:t,children:n}=e,r=BP(t),i=typeof n=="function"?n({present:r.isPresent}):C.Children.only(n),s=rs(r.ref,HP(i));return typeof n=="function"||r.isPresent?C.cloneElement(i,{ref:s}):null};NS.displayName="Presence";function BP(e){const[t,n]=C.useState(),r=C.useRef({}),i=C.useRef(e),s=C.useRef("none"),o=e?"mounted":"unmounted",[a,l]=UP(o,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return C.useEffect(()=>{const u=Bl(r.current);s.current=a==="mounted"?u:"none"},[a]),po(()=>{const u=r.current,f=i.current;if(f!==e){const d=s.current,h=Bl(u);e?l("MOUNT"):h==="none"||(u==null?void 0:u.display)==="none"?l("UNMOUNT"):l(f&&d!==h?"ANIMATION_OUT":"UNMOUNT"),i.current=e}},[e,l]),po(()=>{if(t){let u;const f=t.ownerDocument.defaultView??window,c=h=>{const v=Bl(r.current).includes(h.animationName);if(h.target===t&&v&&(l("ANIMATION_END"),!i.current)){const x=t.style.animationFillMode;t.style.animationFillMode="forwards",u=f.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=x)})}},d=h=>{h.target===t&&(s.current=Bl(r.current))};return t.addEventListener("animationstart",d),t.addEventListener("animationcancel",c),t.addEventListener("animationend",c),()=>{f.clearTimeout(u),t.removeEventListener("animationstart",d),t.removeEventListener("animationcancel",c),t.removeEventListener("animationend",c)}}else l("ANIMATION_END")},[t,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:C.useCallback(u=>{u&&(r.current=getComputedStyle(u)),n(u)},[])}}function Bl(e){return(e==null?void 0:e.animationName)||"none"}function HP(e){var r,i;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(i=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:i.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}function VP({prop:e,defaultProp:t,onChange:n=()=>{}}){const[r,i]=WP({defaultProp:t,onChange:n}),s=e!==void 0,o=s?e:r,a=bo(n),l=C.useCallback(u=>{if(s){const c=typeof u=="function"?u(e):u;c!==e&&a(c)}else i(u)},[s,e,i,a]);return[o,l]}function WP({defaultProp:e,onChange:t}){const n=C.useState(e),[r]=n,i=C.useRef(r),s=bo(t);return C.useEffect(()=>{i.current!==r&&(s(r),i.current=r)},[r,i,s]),n}var QP="VisuallyHidden",FS=C.forwardRef((e,t)=>Y.jsx(os.span,{...e,ref:t,style:{position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal",...e.style}}));FS.displayName=QP;var KP=FS,[Dc,ED]=a0("Tooltip",[kS]),$c=kS(),DS="TooltipProvider",qP=700,bh="tooltip.open",[JP,um]=Dc(DS),$S=e=>{const{__scopeTooltip:t,delayDuration:n=qP,skipDelayDuration:r=300,disableHoverableContent:i=!1,children:s}=e,o=C.useRef(!0),a=C.useRef(!1),l=C.useRef(0);return C.useEffect(()=>{const u=l.current;return()=>window.clearTimeout(u)},[]),Y.jsx(JP,{scope:t,isOpenDelayedRef:o,delayDuration:n,onOpen:C.useCallback(()=>{window.clearTimeout(l.current),o.current=!1},[]),onClose:C.useCallback(()=>{window.clearTimeout(l.current),l.current=window.setTimeout(()=>o.current=!0,r)},[r]),isPointerInTransitRef:a,onPointerInTransitChange:C.useCallback(u=>{a.current=u},[]),disableHoverableContent:i,children:s})};$S.displayName=DS;var jc="Tooltip",[GP,zc]=Dc(jc),jS=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:i=!1,onOpenChange:s,disableHoverableContent:o,delayDuration:a}=e,l=um(jc,e.__scopeTooltip),u=$c(t),[f,c]=C.useState(null),d=Tk(),h=C.useRef(0),g=o??l.disableHoverableContent,v=a??l.delayDuration,x=C.useRef(!1),[m=!1,p]=VP({prop:r,defaultProp:i,onChange:y=>{y?(l.onOpen(),document.dispatchEvent(new CustomEvent(bh))):l.onClose(),s==null||s(y)}}),w=C.useMemo(()=>m?x.current?"delayed-open":"instant-open":"closed",[m]),S=C.useCallback(()=>{window.clearTimeout(h.current),h.current=0,x.current=!1,p(!0)},[p]),k=C.useCallback(()=>{window.clearTimeout(h.current),h.current=0,p(!1)},[p]),E=C.useCallback(()=>{window.clearTimeout(h.current),h.current=window.setTimeout(()=>{x.current=!0,p(!0),h.current=0},v)},[v,p]);return C.useEffect(()=>()=>{h.current&&(window.clearTimeout(h.current),h.current=0)},[]),Y.jsx(DP,{...u,children:Y.jsx(GP,{scope:t,contentId:d,open:m,stateAttribute:w,trigger:f,onTriggerChange:c,onTriggerEnter:C.useCallback(()=>{l.isOpenDelayedRef.current?E():S()},[l.isOpenDelayedRef,E,S]),onTriggerLeave:C.useCallback(()=>{g?k():(window.clearTimeout(h.current),h.current=0)},[k,g]),onOpen:S,onClose:k,disableHoverableContent:g,children:n})})};jS.displayName=jc;var Eh="TooltipTrigger",zS=C.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,i=zc(Eh,n),s=um(Eh,n),o=$c(n),a=C.useRef(null),l=rs(t,a,i.onTriggerChange),u=C.useRef(!1),f=C.useRef(!1),c=C.useCallback(()=>u.current=!1,[]);return C.useEffect(()=>()=>document.removeEventListener("pointerup",c),[c]),Y.jsx($P,{asChild:!0,...o,children:Y.jsx(os.button,{"aria-describedby":i.open?i.contentId:void 0,"data-state":i.stateAttribute,...r,ref:l,onPointerMove:Sr(e.onPointerMove,d=>{d.pointerType!=="touch"&&!f.current&&!s.isPointerInTransitRef.current&&(i.onTriggerEnter(),f.current=!0)}),onPointerLeave:Sr(e.onPointerLeave,()=>{i.onTriggerLeave(),f.current=!1}),onPointerDown:Sr(e.onPointerDown,()=>{i.open&&i.onClose(),u.current=!0,document.addEventListener("pointerup",c,{once:!0})}),onFocus:Sr(e.onFocus,()=>{u.current||i.onOpen()}),onBlur:Sr(e.onBlur,i.onClose),onClick:Sr(e.onClick,i.onClose)})})});zS.displayName=Eh;var XP="TooltipPortal",[CD,YP]=Dc(XP,{forceMount:void 0}),go="TooltipContent",US=C.forwardRef((e,t)=>{const n=YP(go,e.__scopeTooltip),{forceMount:r=n.forceMount,side:i="top",...s}=e,o=zc(go,e.__scopeTooltip);return Y.jsx(NS,{present:r||o.open,children:o.disableHoverableContent?Y.jsx(BS,{side:i,...s,ref:t}):Y.jsx(ZP,{side:i,...s,ref:t})})}),ZP=C.forwardRef((e,t)=>{const n=zc(go,e.__scopeTooltip),r=um(go,e.__scopeTooltip),i=C.useRef(null),s=rs(t,i),[o,a]=C.useState(null),{trigger:l,onClose:u}=n,f=i.current,{onPointerInTransitChange:c}=r,d=C.useCallback(()=>{a(null),c(!1)},[c]),h=C.useCallback((g,v)=>{const x=g.currentTarget,m={x:g.clientX,y:g.clientY},p=iR(m,x.getBoundingClientRect()),w=sR(m,p),S=oR(v.getBoundingClientRect()),k=lR([...w,...S]);a(k),c(!0)},[c]);return C.useEffect(()=>()=>d(),[d]),C.useEffect(()=>{if(l&&f){const g=x=>h(x,f),v=x=>h(x,l);return l.addEventListener("pointerleave",g),f.addEventListener("pointerleave",v),()=>{l.removeEventListener("pointerleave",g),f.removeEventListener("pointerleave",v)}}},[l,f,h,d]),C.useEffect(()=>{if(o){const g=v=>{const x=v.target,m={x:v.clientX,y:v.clientY},p=(l==null?void 0:l.contains(x))||(f==null?void 0:f.contains(x)),w=!aR(m,o);p?d():w&&(d(),u())};return document.addEventListener("pointermove",g),()=>document.removeEventListener("pointermove",g)}},[l,f,o,u,d]),Y.jsx(BS,{...e,ref:s})}),[eR,tR]=Dc(jc,{isInside:!1}),nR=pk("TooltipContent"),BS=C.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":i,onEscapeKeyDown:s,onPointerDownOutside:o,...a}=e,l=zc(go,n),u=$c(n),{onClose:f}=l;return C.useEffect(()=>(document.addEventListener(bh,f),()=>document.removeEventListener(bh,f)),[f]),C.useEffect(()=>{if(l.trigger){const c=d=>{const h=d.target;h!=null&&h.contains(l.trigger)&&f()};return window.addEventListener("scroll",c,{capture:!0}),()=>window.removeEventListener("scroll",c,{capture:!0})}},[l.trigger,f]),Y.jsx(dS,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:s,onPointerDownOutside:o,onFocusOutside:c=>c.preventDefault(),onDismiss:f,children:Y.jsxs(jP,{"data-state":l.stateAttribute,...u,...a,ref:t,style:{...a.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[Y.jsx(nR,{children:r}),Y.jsx(eR,{scope:n,isInside:!0,children:Y.jsx(KP,{id:l.contentId,role:"tooltip",children:i||r})})]})})});US.displayName=go;var HS="TooltipArrow",rR=C.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,i=$c(n);return tR(HS,n).isInside?null:Y.jsx(zP,{...i,...r,ref:t})});rR.displayName=HS;function iR(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),i=Math.abs(t.right-e.x),s=Math.abs(t.left-e.x);switch(Math.min(n,r,i,s)){case s:return"left";case i:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function sR(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}function oR(e){const{top:t,right:n,bottom:r,left:i}=e;return[{x:i,y:t},{x:n,y:t},{x:n,y:r},{x:i,y:r}]}function aR(e,t){const{x:n,y:r}=e;let i=!1;for(let s=0,o=t.length-1;sr!=f>r&&n<(u-a)*(r-l)/(f-l)+a&&(i=!i)}return i}function lR(e){const t=e.slice();return t.sort((n,r)=>n.xr.x?1:n.yr.y?1:0),uR(t)}function uR(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r=2;){const s=t[t.length-1],o=t[t.length-2];if((s.x-o.x)*(i.y-o.y)>=(s.y-o.y)*(i.x-o.x))t.pop();else break}t.push(i)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const i=e[r];for(;n.length>=2;){const s=n[n.length-1],o=n[n.length-2];if((s.x-o.x)*(i.y-o.y)>=(s.y-o.y)*(i.x-o.x))n.pop();else break}n.push(i)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}var cR=$S,fR=jS,dR=zS,VS=US;function WS(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e)){var i=e.length;for(t=0;t{const t=gR(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:o=>{const a=o.split(cm);return a[0]===""&&a.length!==1&&a.shift(),QS(a,t)||mR(o)},getConflictingClassGroupIds:(o,a)=>{const l=n[o]||[];return a&&r[o]?[...l,...r[o]]:l}}},QS=(e,t)=>{var o;if(e.length===0)return t.classGroupId;const n=e[0],r=t.nextPart.get(n),i=r?QS(e.slice(1),r):void 0;if(i)return i;if(t.validators.length===0)return;const s=e.join(cm);return(o=t.validators.find(({validator:a})=>a(s)))==null?void 0:o.classGroupId},$y=/^\[(.+)\]$/,mR=e=>{if($y.test(e)){const t=$y.exec(e)[1],n=t==null?void 0:t.substring(0,t.indexOf(":"));if(n)return"arbitrary.."+n}},gR=e=>{const{theme:t,prefix:n}=e,r={nextPart:new Map,validators:[]};return vR(Object.entries(e.classGroups),n).forEach(([s,o])=>{Ch(o,r,s,t)}),r},Ch=(e,t,n,r)=>{e.forEach(i=>{if(typeof i=="string"){const s=i===""?t:jy(t,i);s.classGroupId=n;return}if(typeof i=="function"){if(yR(i)){Ch(i(r),t,n,r);return}t.validators.push({validator:i,classGroupId:n});return}Object.entries(i).forEach(([s,o])=>{Ch(o,jy(t,s),n,r)})})},jy=(e,t)=>{let n=e;return t.split(cm).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n},yR=e=>e.isThemeGetter,vR=(e,t)=>t?e.map(([n,r])=>{const i=r.map(s=>typeof s=="string"?t+s:typeof s=="object"?Object.fromEntries(Object.entries(s).map(([o,a])=>[t+o,a])):s);return[n,i]}):e,wR=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=new Map,r=new Map;const i=(s,o)=>{n.set(s,o),t++,t>e&&(t=0,r=n,n=new Map)};return{get(s){let o=n.get(s);if(o!==void 0)return o;if((o=r.get(s))!==void 0)return i(s,o),o},set(s,o){n.has(s)?n.set(s,o):i(s,o)}}},KS="!",xR=e=>{const{separator:t,experimentalParseClassName:n}=e,r=t.length===1,i=t[0],s=t.length,o=a=>{const l=[];let u=0,f=0,c;for(let x=0;xf?c-f:void 0;return{modifiers:l,hasImportantModifier:h,baseClassName:g,maybePostfixModifierPosition:v}};return n?a=>n({className:a,parseClassName:o}):o},SR=e=>{if(e.length<=1)return e;const t=[];let n=[];return e.forEach(r=>{r[0]==="["?(t.push(...n.sort(),r),n=[]):n.push(r)}),t.push(...n.sort()),t},bR=e=>({cache:wR(e.cacheSize),parseClassName:xR(e),...pR(e)}),ER=/\s+/,CR=(e,t)=>{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:i}=t,s=[],o=e.trim().split(ER);let a="";for(let l=o.length-1;l>=0;l-=1){const u=o[l],{modifiers:f,hasImportantModifier:c,baseClassName:d,maybePostfixModifierPosition:h}=n(u);let g=!!h,v=r(g?d.substring(0,h):d);if(!v){if(!g){a=u+(a.length>0?" "+a:a);continue}if(v=r(d),!v){a=u+(a.length>0?" "+a:a);continue}g=!1}const x=SR(f).join(":"),m=c?x+KS:x,p=m+v;if(s.includes(p))continue;s.push(p);const w=i(v,g);for(let S=0;S0?" "+a:a)}return a};function _R(){let e=0,t,n,r="";for(;e{if(typeof e=="string")return e;let t,n="";for(let r=0;rc(f),e());return n=bR(u),r=n.cache.get,i=n.cache.set,s=a,a(l)}function a(l){const u=r(l);if(u)return u;const f=CR(l,n);return i(l,f),f}return function(){return s(_R.apply(null,arguments))}}const Me=e=>{const t=n=>n[e]||[];return t.isThemeGetter=!0,t},JS=/^\[(?:([a-z-]+):)?(.+)\]$/i,PR=/^\d+\/\d+$/,RR=new Set(["px","full","screen"]),AR=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,TR=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,OR=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,IR=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,LR=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,gr=e=>Qs(e)||RR.has(e)||PR.test(e),jr=e=>_o(e,"length",UR),Qs=e=>!!e&&!Number.isNaN(Number(e)),Vf=e=>_o(e,"number",Qs),Ho=e=>!!e&&Number.isInteger(Number(e)),MR=e=>e.endsWith("%")&&Qs(e.slice(0,-1)),de=e=>JS.test(e),zr=e=>AR.test(e),NR=new Set(["length","size","percentage"]),FR=e=>_o(e,NR,GS),DR=e=>_o(e,"position",GS),$R=new Set(["image","url"]),jR=e=>_o(e,$R,HR),zR=e=>_o(e,"",BR),Vo=()=>!0,_o=(e,t,n)=>{const r=JS.exec(e);return r?r[1]?typeof t=="string"?r[1]===t:t.has(r[1]):n(r[2]):!1},UR=e=>TR.test(e)&&!OR.test(e),GS=()=>!1,BR=e=>IR.test(e),HR=e=>LR.test(e),VR=()=>{const e=Me("colors"),t=Me("spacing"),n=Me("blur"),r=Me("brightness"),i=Me("borderColor"),s=Me("borderRadius"),o=Me("borderSpacing"),a=Me("borderWidth"),l=Me("contrast"),u=Me("grayscale"),f=Me("hueRotate"),c=Me("invert"),d=Me("gap"),h=Me("gradientColorStops"),g=Me("gradientColorStopPositions"),v=Me("inset"),x=Me("margin"),m=Me("opacity"),p=Me("padding"),w=Me("saturate"),S=Me("scale"),k=Me("sepia"),E=Me("skew"),y=Me("space"),R=Me("translate"),T=()=>["auto","contain","none"],A=()=>["auto","hidden","clip","visible","scroll"],O=()=>["auto",de,t],I=()=>[de,t],z=()=>["",gr,jr],B=()=>["auto",Qs,de],V=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],G=()=>["solid","dashed","dotted","double","none"],Q=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],M=()=>["start","end","center","between","around","evenly","stretch"],U=()=>["","0",de],b=()=>["auto","avoid","all","avoid-page","page","left","right","column"],Z=()=>[Qs,de];return{cacheSize:500,separator:":",theme:{colors:[Vo],spacing:[gr,jr],blur:["none","",zr,de],brightness:Z(),borderColor:[e],borderRadius:["none","","full",zr,de],borderSpacing:I(),borderWidth:z(),contrast:Z(),grayscale:U(),hueRotate:Z(),invert:U(),gap:I(),gradientColorStops:[e],gradientColorStopPositions:[MR,jr],inset:O(),margin:O(),opacity:Z(),padding:I(),saturate:Z(),scale:Z(),sepia:U(),skew:Z(),space:I(),translate:I()},classGroups:{aspect:[{aspect:["auto","square","video",de]}],container:["container"],columns:[{columns:[zr]}],"break-after":[{"break-after":b()}],"break-before":[{"break-before":b()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...V(),de]}],overflow:[{overflow:A()}],"overflow-x":[{"overflow-x":A()}],"overflow-y":[{"overflow-y":A()}],overscroll:[{overscroll:T()}],"overscroll-x":[{"overscroll-x":T()}],"overscroll-y":[{"overscroll-y":T()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[v]}],"inset-x":[{"inset-x":[v]}],"inset-y":[{"inset-y":[v]}],start:[{start:[v]}],end:[{end:[v]}],top:[{top:[v]}],right:[{right:[v]}],bottom:[{bottom:[v]}],left:[{left:[v]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",Ho,de]}],basis:[{basis:O()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",de]}],grow:[{grow:U()}],shrink:[{shrink:U()}],order:[{order:["first","last","none",Ho,de]}],"grid-cols":[{"grid-cols":[Vo]}],"col-start-end":[{col:["auto",{span:["full",Ho,de]},de]}],"col-start":[{"col-start":B()}],"col-end":[{"col-end":B()}],"grid-rows":[{"grid-rows":[Vo]}],"row-start-end":[{row:["auto",{span:[Ho,de]},de]}],"row-start":[{"row-start":B()}],"row-end":[{"row-end":B()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",de]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",de]}],gap:[{gap:[d]}],"gap-x":[{"gap-x":[d]}],"gap-y":[{"gap-y":[d]}],"justify-content":[{justify:["normal",...M()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...M(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...M(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[p]}],px:[{px:[p]}],py:[{py:[p]}],ps:[{ps:[p]}],pe:[{pe:[p]}],pt:[{pt:[p]}],pr:[{pr:[p]}],pb:[{pb:[p]}],pl:[{pl:[p]}],m:[{m:[x]}],mx:[{mx:[x]}],my:[{my:[x]}],ms:[{ms:[x]}],me:[{me:[x]}],mt:[{mt:[x]}],mr:[{mr:[x]}],mb:[{mb:[x]}],ml:[{ml:[x]}],"space-x":[{"space-x":[y]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[y]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",de,t]}],"min-w":[{"min-w":[de,t,"min","max","fit"]}],"max-w":[{"max-w":[de,t,"none","full","min","max","fit","prose",{screen:[zr]},zr]}],h:[{h:[de,t,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[de,t,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[de,t,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[de,t,"auto","min","max","fit"]}],"font-size":[{text:["base",zr,jr]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",Vf]}],"font-family":[{font:[Vo]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",de]}],"line-clamp":[{"line-clamp":["none",Qs,Vf]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",gr,de]}],"list-image":[{"list-image":["none",de]}],"list-style-type":[{list:["none","disc","decimal",de]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[e]}],"placeholder-opacity":[{"placeholder-opacity":[m]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[e]}],"text-opacity":[{"text-opacity":[m]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...G(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",gr,jr]}],"underline-offset":[{"underline-offset":["auto",gr,de]}],"text-decoration-color":[{decoration:[e]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:I()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",de]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",de]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[m]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...V(),DR]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",FR]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},jR]}],"bg-color":[{bg:[e]}],"gradient-from-pos":[{from:[g]}],"gradient-via-pos":[{via:[g]}],"gradient-to-pos":[{to:[g]}],"gradient-from":[{from:[h]}],"gradient-via":[{via:[h]}],"gradient-to":[{to:[h]}],rounded:[{rounded:[s]}],"rounded-s":[{"rounded-s":[s]}],"rounded-e":[{"rounded-e":[s]}],"rounded-t":[{"rounded-t":[s]}],"rounded-r":[{"rounded-r":[s]}],"rounded-b":[{"rounded-b":[s]}],"rounded-l":[{"rounded-l":[s]}],"rounded-ss":[{"rounded-ss":[s]}],"rounded-se":[{"rounded-se":[s]}],"rounded-ee":[{"rounded-ee":[s]}],"rounded-es":[{"rounded-es":[s]}],"rounded-tl":[{"rounded-tl":[s]}],"rounded-tr":[{"rounded-tr":[s]}],"rounded-br":[{"rounded-br":[s]}],"rounded-bl":[{"rounded-bl":[s]}],"border-w":[{border:[a]}],"border-w-x":[{"border-x":[a]}],"border-w-y":[{"border-y":[a]}],"border-w-s":[{"border-s":[a]}],"border-w-e":[{"border-e":[a]}],"border-w-t":[{"border-t":[a]}],"border-w-r":[{"border-r":[a]}],"border-w-b":[{"border-b":[a]}],"border-w-l":[{"border-l":[a]}],"border-opacity":[{"border-opacity":[m]}],"border-style":[{border:[...G(),"hidden"]}],"divide-x":[{"divide-x":[a]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[a]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[m]}],"divide-style":[{divide:G()}],"border-color":[{border:[i]}],"border-color-x":[{"border-x":[i]}],"border-color-y":[{"border-y":[i]}],"border-color-s":[{"border-s":[i]}],"border-color-e":[{"border-e":[i]}],"border-color-t":[{"border-t":[i]}],"border-color-r":[{"border-r":[i]}],"border-color-b":[{"border-b":[i]}],"border-color-l":[{"border-l":[i]}],"divide-color":[{divide:[i]}],"outline-style":[{outline:["",...G()]}],"outline-offset":[{"outline-offset":[gr,de]}],"outline-w":[{outline:[gr,jr]}],"outline-color":[{outline:[e]}],"ring-w":[{ring:z()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[e]}],"ring-opacity":[{"ring-opacity":[m]}],"ring-offset-w":[{"ring-offset":[gr,jr]}],"ring-offset-color":[{"ring-offset":[e]}],shadow:[{shadow:["","inner","none",zr,zR]}],"shadow-color":[{shadow:[Vo]}],opacity:[{opacity:[m]}],"mix-blend":[{"mix-blend":[...Q(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":Q()}],filter:[{filter:["","none"]}],blur:[{blur:[n]}],brightness:[{brightness:[r]}],contrast:[{contrast:[l]}],"drop-shadow":[{"drop-shadow":["","none",zr,de]}],grayscale:[{grayscale:[u]}],"hue-rotate":[{"hue-rotate":[f]}],invert:[{invert:[c]}],saturate:[{saturate:[w]}],sepia:[{sepia:[k]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[n]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[l]}],"backdrop-grayscale":[{"backdrop-grayscale":[u]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[f]}],"backdrop-invert":[{"backdrop-invert":[c]}],"backdrop-opacity":[{"backdrop-opacity":[m]}],"backdrop-saturate":[{"backdrop-saturate":[w]}],"backdrop-sepia":[{"backdrop-sepia":[k]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[o]}],"border-spacing-x":[{"border-spacing-x":[o]}],"border-spacing-y":[{"border-spacing-y":[o]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",de]}],duration:[{duration:Z()}],ease:[{ease:["linear","in","out","in-out",de]}],delay:[{delay:Z()}],animate:[{animate:["none","spin","ping","pulse","bounce",de]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[S]}],"scale-x":[{"scale-x":[S]}],"scale-y":[{"scale-y":[S]}],rotate:[{rotate:[Ho,de]}],"translate-x":[{"translate-x":[R]}],"translate-y":[{"translate-y":[R]}],"skew-x":[{"skew-x":[E]}],"skew-y":[{"skew-y":[E]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",de]}],accent:[{accent:["auto",e]}],appearance:[{appearance:["none","auto"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",de]}],"caret-color":[{caret:[e]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":I()}],"scroll-mx":[{"scroll-mx":I()}],"scroll-my":[{"scroll-my":I()}],"scroll-ms":[{"scroll-ms":I()}],"scroll-me":[{"scroll-me":I()}],"scroll-mt":[{"scroll-mt":I()}],"scroll-mr":[{"scroll-mr":I()}],"scroll-mb":[{"scroll-mb":I()}],"scroll-ml":[{"scroll-ml":I()}],"scroll-p":[{"scroll-p":I()}],"scroll-px":[{"scroll-px":I()}],"scroll-py":[{"scroll-py":I()}],"scroll-ps":[{"scroll-ps":I()}],"scroll-pe":[{"scroll-pe":I()}],"scroll-pt":[{"scroll-pt":I()}],"scroll-pr":[{"scroll-pr":I()}],"scroll-pb":[{"scroll-pb":I()}],"scroll-pl":[{"scroll-pl":I()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",de]}],fill:[{fill:[e,"none"]}],"stroke-w":[{stroke:[gr,jr,Vf]}],stroke:[{stroke:[e,"none"]}],sr:["sr-only","not-sr-only"],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]}}},WR=kR(VR);globalThis.jotaiAtomCache=globalThis.jotaiAtomCache||{cache:new Map,get(e,t){return this.cache.has(e)?this.cache.get(e):(this.cache.set(e,t),t)}};function QR(...e){return WR(hR(e))}async function _D(e){const t=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",t);return[...new Uint8Array(n)].map(s=>s.toString(16).padStart(2,"0")).join("")}function kD(e){let t=e==="html"?".html":".js",n=e==="html"?"text/html":"application/javascript";return e==="streamlit"&&(t=".py",n="text/python"),[t,n]}function PD(e,t,n){const r=new Blob([e],{type:t}),i=URL.createObjectURL(r),s=document.createElement("a");s.href=i,s.download=n,document.body.append(s),s.click(),s.remove(),URL.revokeObjectURL(i)}async function RD(e,t){const n=new Image,r=new Promise((i,s)=>{n.addEventListener("load",()=>{let{width:o,height:a}=n;(o>t||a>t)&&(o>a?(a*=t/o,o=t):(o*=t/a,a=t));const l=document.querySelector("#resizer"),u=l.getContext("2d");l.width=o,l.height=a,u.drawImage(n,0,0,o,a);const f=l.toDataURL("image/jpeg");i({url:f,width:o,height:a,createdAt:new Date})}),n.addEventListener("error",o=>{s(new Error(`Failed to resize image: ${o.message}`))})});return n.src=e,r}const AD=580;globalThis.jotaiAtomCache=globalThis.jotaiAtomCache||{cache:new Map,get(e,t){return this.cache.has(e)?this.cache.get(e):(this.cache.set(e,t),t)}};const KR=cR,TD=fR,OD=dR,qR=C.forwardRef(({className:e,sideOffset:t=4,...n},r)=>Y.jsx(VS,{ref:r,sideOffset:t,className:QR("z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...n}));qR.displayName=VS.displayName;globalThis.jotaiAtomCache=globalThis.jotaiAtomCache||{cache:new Map,get(e,t){return this.cache.has(e)?this.cache.get(e):(this.cache.set(e,t),t)}};const JR=500;function ID(e,t=JR){const[n,r]=Ki.useState(e),i=Ki.useRef(null);return Ki.useEffect(()=>{const s=Date.now();if(i.current&&s>=i.current+t)i.current=s,r(e);else{const o=window.setTimeout(()=>{i.current=s,r(e)},t);return()=>window.clearTimeout(o)}return()=>{}},[e,t]),n}function GR(e){const[t,n]=C.useState(()=>matchMedia(e).matches);return C.useLayoutEffect(()=>{const r=matchMedia(e);function i(){n(r.matches)}return r.addEventListener("change",i),()=>{r.removeEventListener("change",i)}},[e]),t}function XR(){const[e,t]=C.useState(()=>window.location.hash),n=C.useCallback(()=>{t(window.location.hash)},[]);C.useEffect(()=>(window.addEventListener("hashchange",n),()=>{window.removeEventListener("hashchange",n)}),[n]);const r=C.useCallback(i=>{i!==e&&(window.location.hash=i)},[e]);return[e,r]}function LD(e){const[t,n]=XR(),r=C.useCallback(s=>s<0?n(""):n(`#v${s}`),[n]),i=C.useMemo(()=>t.includes("#v")?Math.min(Number.parseInt(t.replace("#v",""),10),e.latestVersion):e.latestVersion,[t,e.latestVersion]);return C.useEffect(()=>{i>e.latestVersion&&r(e.latestVersion)},[i,e.latestVersion,r]),[i,r]}/** * @remix-run/router v1.23.0 * * Copyright (c) Remix Software Inc. @@ -46,8 +46,8 @@ Error generating stack: `+s.message+` * LICENSE.md file in the root directory of this source tree. * * @license MIT - */function De(){return De=Object.assign?Object.assign.bind():function(e){for(var t=1;t"u")throw new Error(t)}function yo(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function ZR(){return Math.random().toString(36).substr(2,8)}function Uy(e,t){return{usr:e.state,key:e.key,idx:t}}function Wa(e,t,n,r){return n===void 0&&(n=null),De({pathname:typeof e=="string"?e:e.pathname,search:"",hash:""},typeof t=="string"?_i(t):t,{state:n,key:t&&t.key||r||ZR()})}function wi(e){let{pathname:t="/",search:n="",hash:r=""}=e;return n&&n!=="?"&&(t+=n.charAt(0)==="?"?n:"?"+n),r&&r!=="#"&&(t+=r.charAt(0)==="#"?r:"#"+r),t}function _i(e){let t={};if(e){let n=e.indexOf("#");n>=0&&(t.hash=e.substr(n),e=e.substr(0,n));let r=e.indexOf("?");r>=0&&(t.search=e.substr(r),e=e.substr(0,r)),e&&(t.pathname=e)}return t}function eA(e,t,n,r){r===void 0&&(r={});let{window:i=document.defaultView,v5Compat:s=!1}=r,o=i.history,a=Ye.Pop,l=null,u=f();u==null&&(u=0,o.replaceState(De({},o.state,{idx:u}),""));function f(){return(o.state||{idx:null}).idx}function c(){a=Ye.Pop;let x=f(),m=x==null?null:x-u;u=x,l&&l({action:a,location:v.location,delta:m})}function d(x,m){a=Ye.Push;let p=Wa(v.location,x,m);u=f()+1;let w=Uy(p,u),S=v.createHref(p);try{o.pushState(w,"",S)}catch(k){if(k instanceof DOMException&&k.name==="DataCloneError")throw k;i.location.assign(S)}s&&l&&l({action:a,location:v.location,delta:1})}function h(x,m){a=Ye.Replace;let p=Wa(v.location,x,m);u=f();let w=Uy(p,u),S=v.createHref(p);o.replaceState(w,"",S),s&&l&&l({action:a,location:v.location,delta:0})}function g(x){let m=i.location.origin!=="null"?i.location.origin:i.location.href,p=typeof x=="string"?x:wi(x);return p=p.replace(/ $/,"%20"),ce(m,"No window.location.(origin|href) available to create URL for href: "+p),new URL(p,m)}let v={get action(){return a},get location(){return e(i,o)},listen(x){if(l)throw new Error("A history only accepts one active listener");return i.addEventListener(zy,c),l=x,()=>{i.removeEventListener(zy,c),l=null}},createHref(x){return t(i,x)},createURL:g,encodeLocation(x){let m=g(x);return{pathname:m.pathname,search:m.search,hash:m.hash}},push:d,replace:h,go(x){return o.go(x)}};return v}var ke;(function(e){e.data="data",e.deferred="deferred",e.redirect="redirect",e.error="error"})(ke||(ke={}));const tA=new Set(["lazy","caseSensitive","path","id","index","children"]);function nA(e){return e.index===!0}function tc(e,t,n,r){return n===void 0&&(n=[]),r===void 0&&(r={}),e.map((i,s)=>{let o=[...n,String(s)],a=typeof i.id=="string"?i.id:o.join("-");if(ce(i.index!==!0||!i.children,"Cannot specify children on an index route"),ce(!r[a],'Found a route id collision on id "'+a+`". Route id's must be globally unique within Data Router usages`),nA(i)){let l=De({},i,t(i),{id:a});return r[a]=l,l}else{let l=De({},i,t(i),{id:a,children:void 0});return r[a]=l,i.children&&(l.children=tc(i.children,t,o,r)),l}})}function Mi(e,t,n){return n===void 0&&(n="/"),gu(e,t,n,!1)}function gu(e,t,n,r){let i=typeof t=="string"?_i(t):t,s=xi(i.pathname||"/",n);if(s==null)return null;let o=XS(e);iA(o);let a=null;for(let l=0;a==null&&l{let l={relativePath:a===void 0?s.path||"":a,caseSensitive:s.caseSensitive===!0,childrenIndex:o,route:s};l.relativePath.startsWith("/")&&(ce(l.relativePath.startsWith(r),'Absolute route path "'+l.relativePath+'" nested under path '+('"'+r+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),l.relativePath=l.relativePath.slice(r.length));let u=sr([r,l.relativePath]),f=n.concat(l);s.children&&s.children.length>0&&(ce(s.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+u+'".')),XS(s.children,t,f,u)),!(s.path==null&&!s.index)&&t.push({path:u,score:fA(u,s.index),routesMeta:f})};return e.forEach((s,o)=>{var a;if(s.path===""||!((a=s.path)!=null&&a.includes("?")))i(s,o);else for(let l of YS(s.path))i(s,o,l)}),t}function YS(e){let t=e.split("/");if(t.length===0)return[];let[n,...r]=t,i=n.endsWith("?"),s=n.replace(/\?$/,"");if(r.length===0)return i?[s,""]:[s];let o=YS(r.join("/")),a=[];return a.push(...o.map(l=>l===""?s:[s,l].join("/"))),i&&a.push(...o),a.map(l=>e.startsWith("/")&&l===""?"/":l)}function iA(e){e.sort((t,n)=>t.score!==n.score?n.score-t.score:dA(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}const sA=/^:[\w-]+$/,oA=3,aA=2,lA=1,uA=10,cA=-2,By=e=>e==="*";function fA(e,t){let n=e.split("/"),r=n.length;return n.some(By)&&(r+=cA),t&&(r+=aA),n.filter(i=>!By(i)).reduce((i,s)=>i+(sA.test(s)?oA:s===""?lA:uA),r)}function dA(e,t){return e.length===t.length&&e.slice(0,-1).every((r,i)=>r===t[i])?e[e.length-1]-t[t.length-1]:0}function hA(e,t,n){n===void 0&&(n=!1);let{routesMeta:r}=e,i={},s="/",o=[];for(let a=0;a{let{paramName:d,isOptional:h}=f;if(d==="*"){let v=a[c]||"";o=s.slice(0,s.length-v.length).replace(/(.)\/+$/,"$1")}const g=a[c];return h&&!g?u[d]=void 0:u[d]=(g||"").replace(/%2F/g,"/"),u},{}),pathname:s,pathnameBase:o,pattern:e}}function pA(e,t,n){t===void 0&&(t=!1),n===void 0&&(n=!0),yo(e==="*"||!e.endsWith("*")||e.endsWith("/*"),'Route path "'+e+'" will be treated as if it were '+('"'+e.replace(/\*$/,"/*")+'" because the `*` character must ')+"always follow a `/` in the pattern. To get rid of this warning, "+('please change the route path to "'+e.replace(/\*$/,"/*")+'".'));let r=[],i="^"+e.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(o,a,l)=>(r.push({paramName:a,isOptional:l!=null}),l?"/?([^\\/]+)?":"/([^\\/]+)"));return e.endsWith("*")?(r.push({paramName:"*"}),i+=e==="*"||e==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?i+="\\/*$":e!==""&&e!=="/"&&(i+="(?:(?=\\/|$))"),[new RegExp(i,t?void 0:"i"),r]}function mA(e){try{return e.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return yo(!1,'The URL path "'+e+'" could not be decoded because it is is a malformed URL segment. This is probably due to a bad percent '+("encoding ("+t+").")),e}}function xi(e,t){if(t==="/")return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith("/")?t.length-1:t.length,r=e.charAt(n);return r&&r!=="/"?null:e.slice(n)||"/"}function gA(e,t){t===void 0&&(t="/");let{pathname:n,search:r="",hash:i=""}=typeof e=="string"?_i(e):e;return{pathname:n?n.startsWith("/")?n:yA(n,t):t,search:wA(r),hash:xA(i)}}function yA(e,t){let n=t.replace(/\/+$/,"").split("/");return e.split("/").forEach(i=>{i===".."?n.length>1&&n.pop():i!=="."&&n.push(i)}),n.length>1?n.join("/"):"/"}function Wf(e,t,n,r){return"Cannot include a '"+e+"' character in a manually specified "+("`to."+t+"` field ["+JSON.stringify(r)+"]. Please separate it out to the ")+("`to."+n+"` field. Alternatively you may provide the full path as ")+'a string in and the router will parse it for you.'}function ZS(e){return e.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function Uc(e,t){let n=ZS(e);return t?n.map((r,i)=>i===n.length-1?r.pathname:r.pathnameBase):n.map(r=>r.pathnameBase)}function Bc(e,t,n,r){r===void 0&&(r=!1);let i;typeof e=="string"?i=_i(e):(i=De({},e),ce(!i.pathname||!i.pathname.includes("?"),Wf("?","pathname","search",i)),ce(!i.pathname||!i.pathname.includes("#"),Wf("#","pathname","hash",i)),ce(!i.search||!i.search.includes("#"),Wf("#","search","hash",i)));let s=e===""||i.pathname==="",o=s?"/":i.pathname,a;if(o==null)a=n;else{let c=t.length-1;if(!r&&o.startsWith("..")){let d=o.split("/");for(;d[0]==="..";)d.shift(),c-=1;i.pathname=d.join("/")}a=c>=0?t[c]:"/"}let l=gA(i,a),u=o&&o!=="/"&&o.endsWith("/"),f=(s||o===".")&&n.endsWith("/");return!l.pathname.endsWith("/")&&(u||f)&&(l.pathname+="/"),l}const sr=e=>e.join("/").replace(/\/\/+/g,"/"),vA=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),wA=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,xA=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e;class nc{constructor(t,n,r,i){i===void 0&&(i=!1),this.status=t,this.statusText=n||"",this.internal=i,r instanceof Error?(this.data=r.toString(),this.error=r):this.data=r}}function Qa(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}const e1=["post","put","patch","delete"],SA=new Set(e1),bA=["get",...e1],EA=new Set(bA),_A=new Set([301,302,303,307,308]),CA=new Set([307,308]),Qf={state:"idle",location:void 0,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0},kA={state:"idle",data:void 0,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0},Wo={state:"unblocked",proceed:void 0,reset:void 0,location:void 0},fm=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,PA=e=>({hasErrorBoundary:!!e.hasErrorBoundary}),t1="remix-router-transitions";function RA(e){const t=e.window?e.window:typeof window<"u"?window:void 0,n=typeof t<"u"&&typeof t.document<"u"&&typeof t.document.createElement<"u",r=!n;ce(e.routes.length>0,"You must provide a non-empty routes array to createRouter");let i;if(e.mapRouteProperties)i=e.mapRouteProperties;else if(e.detectErrorBoundary){let P=e.detectErrorBoundary;i=L=>({hasErrorBoundary:P(L)})}else i=PA;let s={},o=tc(e.routes,i,void 0,s),a,l=e.basename||"/",u=e.dataStrategy||IA,f=e.patchRoutesOnNavigation,c=De({v7_fetcherPersist:!1,v7_normalizeFormMethod:!1,v7_partialHydration:!1,v7_prependBasename:!1,v7_relativeSplatPath:!1,v7_skipActionErrorRevalidation:!1},e.future),d=null,h=new Set,g=null,v=null,x=null,m=e.hydrationData!=null,p=Mi(o,e.history.location,l),w=!1,S=null;if(p==null&&!f){let P=jt(404,{pathname:e.history.location.pathname}),{matches:L,route:N}=ev(o);p=L,S={[N.id]:P}}p&&!e.hydrationData&&vl(p,o,e.history.location.pathname).active&&(p=null);let k;if(p)if(p.some(P=>P.route.lazy))k=!1;else if(!p.some(P=>P.route.loader))k=!0;else if(c.v7_partialHydration){let P=e.hydrationData?e.hydrationData.loaderData:null,L=e.hydrationData?e.hydrationData.errors:null;if(L){let N=p.findIndex($=>L[$.route.id]!==void 0);k=p.slice(0,N+1).every($=>!kh($.route,P,L))}else k=p.every(N=>!kh(N.route,P,L))}else k=e.hydrationData!=null;else if(k=!1,p=[],c.v7_partialHydration){let P=vl(null,o,e.history.location.pathname);P.active&&P.matches&&(w=!0,p=P.matches)}let E,y={historyAction:e.history.action,location:e.history.location,matches:p,initialized:k,navigation:Qf,restoreScrollPosition:e.hydrationData!=null?!1:null,preventScrollReset:!1,revalidation:"idle",loaderData:e.hydrationData&&e.hydrationData.loaderData||{},actionData:e.hydrationData&&e.hydrationData.actionData||null,errors:e.hydrationData&&e.hydrationData.errors||S,fetchers:new Map,blockers:new Map},R=Ye.Pop,T=!1,A,O=!1,I=new Map,z=null,B=!1,V=!1,G=[],Q=new Set,M=new Map,U=0,b=-1,Z=new Map,pe=new Set,C=new Map,Ae=new Map,Le=new Set,ye=new Map,qe=new Map,vt;function xn(){if(d=e.history.listen(P=>{let{action:L,location:N,delta:$}=P;if(vt){vt(),vt=void 0;return}yo(qe.size===0||$!=null,"You are trying to use a blocker on a POP navigation to a location that was not created by @remix-run/router. This will fail silently in production. This can happen if you are navigating outside the router via `window.history.pushState`/`window.location.hash` instead of using router navigation APIs. This can also happen if you are using createHashRouter and the user manually changes the URL.");let W=sg({currentLocation:y.location,nextLocation:N,historyAction:L});if(W&&$!=null){let ne=new Promise(oe=>{vt=oe});e.history.go($*-1),yl(W,{state:"blocked",location:N,proceed(){yl(W,{state:"proceeding",proceed:void 0,reset:void 0,location:N}),ne.then(()=>e.history.go($))},reset(){let oe=new Map(y.blockers);oe.set(W,Wo),Ge({blockers:oe})}});return}return on(L,N)}),n){QA(t,I);let P=()=>KA(t,I);t.addEventListener("pagehide",P),z=()=>t.removeEventListener("pagehide",P)}return y.initialized||on(Ye.Pop,y.location,{initialHydration:!0}),E}function Sn(){d&&d(),z&&z(),h.clear(),A&&A.abort(),y.fetchers.forEach((P,L)=>wt(L)),y.blockers.forEach((P,L)=>an(L))}function dr(P){return h.add(P),()=>h.delete(P)}function Ge(P,L){L===void 0&&(L={}),y=De({},y,P);let N=[],$=[];c.v7_fetcherPersist&&y.fetchers.forEach((W,ne)=>{W.state==="idle"&&(Le.has(ne)?$.push(ne):N.push(ne))}),Le.forEach(W=>{!y.fetchers.has(W)&&!M.has(W)&&$.push(W)}),[...h].forEach(W=>W(y,{deletedFetchers:$,viewTransitionOpts:L.viewTransitionOpts,flushSync:L.flushSync===!0})),c.v7_fetcherPersist?(N.forEach(W=>y.fetchers.delete(W)),$.forEach(W=>wt(W))):$.forEach(W=>Le.delete(W))}function Ft(P,L,N){var $,W;let{flushSync:ne}=N===void 0?{}:N,oe=y.actionData!=null&&y.navigation.formMethod!=null&&Tn(y.navigation.formMethod)&&y.navigation.state==="loading"&&(($=P.state)==null?void 0:$._isRedirect)!==!0,J;L.actionData?Object.keys(L.actionData).length>0?J=L.actionData:J=null:oe?J=y.actionData:J=null;let X=L.loaderData?Yy(y.loaderData,L.loaderData,L.matches||[],L.errors):y.loaderData,q=y.blockers;q.size>0&&(q=new Map(q),q.forEach((ve,ct)=>q.set(ct,Wo)));let ee=T===!0||y.navigation.formMethod!=null&&Tn(y.navigation.formMethod)&&((W=P.state)==null?void 0:W._isRedirect)!==!0;a&&(o=a,a=void 0),B||R===Ye.Pop||(R===Ye.Push?e.history.push(P,P.state):R===Ye.Replace&&e.history.replace(P,P.state));let fe;if(R===Ye.Pop){let ve=I.get(y.location.pathname);ve&&ve.has(P.pathname)?fe={currentLocation:y.location,nextLocation:P}:I.has(P.pathname)&&(fe={currentLocation:P,nextLocation:y.location})}else if(O){let ve=I.get(y.location.pathname);ve?ve.add(P.pathname):(ve=new Set([P.pathname]),I.set(y.location.pathname,ve)),fe={currentLocation:y.location,nextLocation:P}}Ge(De({},L,{actionData:J,loaderData:X,historyAction:R,location:P,initialized:!0,navigation:Qf,revalidation:"idle",restoreScrollPosition:ag(P,L.matches||y.matches),preventScrollReset:ee,blockers:q}),{viewTransitionOpts:fe,flushSync:ne===!0}),R=Ye.Pop,T=!1,O=!1,B=!1,V=!1,G=[]}async function Ri(P,L){if(typeof P=="number"){e.history.go(P);return}let N=Ch(y.location,y.matches,l,c.v7_prependBasename,P,c.v7_relativeSplatPath,L==null?void 0:L.fromRouteId,L==null?void 0:L.relative),{path:$,submission:W,error:ne}=Vy(c.v7_normalizeFormMethod,!1,N,L),oe=y.location,J=Wa(y.location,$,L&&L.state);J=De({},J,e.history.encodeLocation(J));let X=L&&L.replace!=null?L.replace:void 0,q=Ye.Push;X===!0?q=Ye.Replace:X===!1||W!=null&&Tn(W.formMethod)&&W.formAction===y.location.pathname+y.location.search&&(q=Ye.Replace);let ee=L&&"preventScrollReset"in L?L.preventScrollReset===!0:void 0,fe=(L&&L.flushSync)===!0,ve=sg({currentLocation:oe,nextLocation:J,historyAction:q});if(ve){yl(ve,{state:"blocked",location:J,proceed(){yl(ve,{state:"proceeding",proceed:void 0,reset:void 0,location:J}),Ri(P,L)},reset(){let ct=new Map(y.blockers);ct.set(ve,Wo),Ge({blockers:ct})}});return}return await on(q,J,{submission:W,pendingError:ne,preventScrollReset:ee,replace:L&&L.replace,enableViewTransition:L&&L.viewTransition,flushSync:fe})}function us(){if(H(),Ge({revalidation:"loading"}),y.navigation.state!=="submitting"){if(y.navigation.state==="idle"){on(y.historyAction,y.location,{startUninterruptedRevalidation:!0});return}on(R||y.historyAction,y.navigation.location,{overrideNavigation:y.navigation,enableViewTransition:O===!0})}}async function on(P,L,N){A&&A.abort(),A=null,R=P,B=(N&&N.startUninterruptedRevalidation)===!0,oE(y.location,y.matches),T=(N&&N.preventScrollReset)===!0,O=(N&&N.enableViewTransition)===!0;let $=a||o,W=N&&N.overrideNavigation,ne=N!=null&&N.initialHydration&&y.matches&&y.matches.length>0&&!w?y.matches:Mi($,L,l),oe=(N&&N.flushSync)===!0;if(ne&&y.initialized&&!V&&$A(y.location,L)&&!(N&&N.submission&&Tn(N.submission.formMethod))){Ft(L,{matches:ne},{flushSync:oe});return}let J=vl(ne,$,L.pathname);if(J.active&&J.matches&&(ne=J.matches),!ne){let{error:Te,notFoundMatches:be,route:He}=ff(L.pathname);Ft(L,{matches:be,loaderData:{},errors:{[He.id]:Te}},{flushSync:oe});return}A=new AbortController;let X=ms(e.history,L,A.signal,N&&N.submission),q;if(N&&N.pendingError)q=[Ni(ne).route.id,{type:ke.error,error:N.pendingError}];else if(N&&N.submission&&Tn(N.submission.formMethod)){let Te=await cs(X,L,N.submission,ne,J.active,{replace:N.replace,flushSync:oe});if(Te.shortCircuited)return;if(Te.pendingActionResult){let[be,He]=Te.pendingActionResult;if(Xt(He)&&Qa(He.error)&&He.error.status===404){A=null,Ft(L,{matches:Te.matches,loaderData:{},errors:{[be]:He.error}});return}}ne=Te.matches||ne,q=Te.pendingActionResult,W=Kf(L,N.submission),oe=!1,J.active=!1,X=ms(e.history,X.url,X.signal)}let{shortCircuited:ee,matches:fe,loaderData:ve,errors:ct}=await Oo(X,L,ne,J.active,W,N&&N.submission,N&&N.fetcherSubmission,N&&N.replace,N&&N.initialHydration===!0,oe,q);ee||(A=null,Ft(L,De({matches:fe||ne},Zy(q),{loaderData:ve,errors:ct})))}async function cs(P,L,N,$,W,ne){ne===void 0&&(ne={}),H();let oe=VA(L,N);if(Ge({navigation:oe},{flushSync:ne.flushSync===!0}),W){let q=await wl($,L.pathname,P.signal);if(q.type==="aborted")return{shortCircuited:!0};if(q.type==="error"){let ee=Ni(q.partialMatches).route.id;return{matches:q.partialMatches,pendingActionResult:[ee,{type:ke.error,error:q.error}]}}else if(q.matches)$=q.matches;else{let{notFoundMatches:ee,error:fe,route:ve}=ff(L.pathname);return{matches:ee,pendingActionResult:[ve.id,{type:ke.error,error:fe}]}}}let J,X=ta($,L);if(!X.route.action&&!X.route.lazy)J={type:ke.error,error:jt(405,{method:P.method,pathname:L.pathname,routeId:X.route.id})};else if(J=(await Ai("action",y,P,[X],$,null))[X.route.id],P.signal.aborted)return{shortCircuited:!0};if(zi(J)){let q;return ne&&ne.replace!=null?q=ne.replace:q=Jy(J.response.headers.get("Location"),new URL(P.url),l)===y.location.pathname+y.location.search,await hr(P,J,!0,{submission:N,replace:q}),{shortCircuited:!0}}if(ii(J))throw jt(400,{type:"defer-action"});if(Xt(J)){let q=Ni($,X.route.id);return(ne&&ne.replace)!==!0&&(R=Ye.Push),{matches:$,pendingActionResult:[q.route.id,J]}}return{matches:$,pendingActionResult:[X.route.id,J]}}async function Oo(P,L,N,$,W,ne,oe,J,X,q,ee){let fe=W||Kf(L,ne),ve=ne||oe||nv(fe),ct=!B&&(!c.v7_partialHydration||!X);if($){if(ct){let Ve=Un(ee);Ge(De({navigation:fe},Ve!==void 0?{actionData:Ve}:{}),{flushSync:q})}let xe=await wl(N,L.pathname,P.signal);if(xe.type==="aborted")return{shortCircuited:!0};if(xe.type==="error"){let Ve=Ni(xe.partialMatches).route.id;return{matches:xe.partialMatches,loaderData:{},errors:{[Ve]:xe.error}}}else if(xe.matches)N=xe.matches;else{let{error:Ve,notFoundMatches:ds,route:Mo}=ff(L.pathname);return{matches:ds,loaderData:{},errors:{[Mo.id]:Ve}}}}let Te=a||o,[be,He]=Qy(e.history,y,N,ve,L,c.v7_partialHydration&&X===!0,c.v7_skipActionErrorRevalidation,V,G,Q,Le,C,pe,Te,l,ee);if(df(xe=>!(N&&N.some(Ve=>Ve.route.id===xe))||be&&be.some(Ve=>Ve.route.id===xe)),b=++U,be.length===0&&He.length===0){let xe=Fr();return Ft(L,De({matches:N,loaderData:{},errors:ee&&Xt(ee[1])?{[ee[0]]:ee[1].error}:null},Zy(ee),xe?{fetchers:new Map(y.fetchers)}:{}),{flushSync:q}),{shortCircuited:!0}}if(ct){let xe={};if(!$){xe.navigation=fe;let Ve=Un(ee);Ve!==void 0&&(xe.actionData=Ve)}He.length>0&&(xe.fetchers=gl(He)),Ge(xe,{flushSync:q})}He.forEach(xe=>{it(xe.key),xe.controller&&M.set(xe.key,xe.controller)});let fs=()=>He.forEach(xe=>it(xe.key));A&&A.signal.addEventListener("abort",fs);let{loaderResults:Io,fetcherResults:mr}=await F(y,N,be,He,P);if(P.signal.aborted)return{shortCircuited:!0};A&&A.signal.removeEventListener("abort",fs),He.forEach(xe=>M.delete(xe.key));let Bn=Hl(Io);if(Bn)return await hr(P,Bn.result,!0,{replace:J}),{shortCircuited:!0};if(Bn=Hl(mr),Bn)return pe.add(Bn.key),await hr(P,Bn.result,!0,{replace:J}),{shortCircuited:!0};let{loaderData:hf,errors:Lo}=Xy(y,N,Io,ee,He,mr,ye);ye.forEach((xe,Ve)=>{xe.subscribe(ds=>{(ds||xe.done)&&ye.delete(Ve)})}),c.v7_partialHydration&&X&&y.errors&&(Lo=De({},y.errors,Lo));let Ti=Fr(),xl=xt(b),Sl=Ti||xl||He.length>0;return De({matches:N,loaderData:hf,errors:Lo},Sl?{fetchers:new Map(y.fetchers)}:{})}function Un(P){if(P&&!Xt(P[1]))return{[P[0]]:P[1].data};if(y.actionData)return Object.keys(y.actionData).length===0?null:y.actionData}function gl(P){return P.forEach(L=>{let N=y.fetchers.get(L.key),$=Qo(void 0,N?N.data:void 0);y.fetchers.set(L.key,$)}),new Map(y.fetchers)}function lf(P,L,N,$){if(r)throw new Error("router.fetch() was called during the server render, but it shouldn't be. You are likely calling a useFetcher() method in the body of your component. Try moving it to a useEffect or a callback.");it(P);let W=($&&$.flushSync)===!0,ne=a||o,oe=Ch(y.location,y.matches,l,c.v7_prependBasename,N,c.v7_relativeSplatPath,L,$==null?void 0:$.relative),J=Mi(ne,oe,l),X=vl(J,ne,oe);if(X.active&&X.matches&&(J=X.matches),!J){ae(P,L,jt(404,{pathname:oe}),{flushSync:W});return}let{path:q,submission:ee,error:fe}=Vy(c.v7_normalizeFormMethod,!0,oe,$);if(fe){ae(P,L,fe,{flushSync:W});return}let ve=ta(J,q),ct=($&&$.preventScrollReset)===!0;if(ee&&Tn(ee.formMethod)){uf(P,L,q,ve,J,X.active,W,ct,ee);return}C.set(P,{routeId:L,path:q}),cf(P,L,q,ve,J,X.active,W,ct,ee)}async function uf(P,L,N,$,W,ne,oe,J,X){H(),C.delete(P);function q(Xe){if(!Xe.route.action&&!Xe.route.lazy){let hs=jt(405,{method:X.formMethod,pathname:N,routeId:L});return ae(P,L,hs,{flushSync:oe}),!0}return!1}if(!ne&&q($))return;let ee=y.fetchers.get(P);re(P,WA(X,ee),{flushSync:oe});let fe=new AbortController,ve=ms(e.history,N,fe.signal,X);if(ne){let Xe=await wl(W,new URL(ve.url).pathname,ve.signal,P);if(Xe.type==="aborted")return;if(Xe.type==="error"){ae(P,L,Xe.error,{flushSync:oe});return}else if(Xe.matches){if(W=Xe.matches,$=ta(W,N),q($))return}else{ae(P,L,jt(404,{pathname:N}),{flushSync:oe});return}}M.set(P,fe);let ct=U,be=(await Ai("action",y,ve,[$],W,P))[$.route.id];if(ve.signal.aborted){M.get(P)===fe&&M.delete(P);return}if(c.v7_fetcherPersist&&Le.has(P)){if(zi(be)||Xt(be)){re(P,Qr(void 0));return}}else{if(zi(be))if(M.delete(P),b>ct){re(P,Qr(void 0));return}else return pe.add(P),re(P,Qo(X)),hr(ve,be,!1,{fetcherSubmission:X,preventScrollReset:J});if(Xt(be)){ae(P,L,be.error);return}}if(ii(be))throw jt(400,{type:"defer-action"});let He=y.navigation.location||y.location,fs=ms(e.history,He,fe.signal),Io=a||o,mr=y.navigation.state!=="idle"?Mi(Io,y.navigation.location,l):y.matches;ce(mr,"Didn't find any matches after fetcher action");let Bn=++U;Z.set(P,Bn);let hf=Qo(X,be.data);y.fetchers.set(P,hf);let[Lo,Ti]=Qy(e.history,y,mr,X,He,!1,c.v7_skipActionErrorRevalidation,V,G,Q,Le,C,pe,Io,l,[$.route.id,be]);Ti.filter(Xe=>Xe.key!==P).forEach(Xe=>{let hs=Xe.key,lg=y.fetchers.get(hs),uE=Qo(void 0,lg?lg.data:void 0);y.fetchers.set(hs,uE),it(hs),Xe.controller&&M.set(hs,Xe.controller)}),Ge({fetchers:new Map(y.fetchers)});let xl=()=>Ti.forEach(Xe=>it(Xe.key));fe.signal.addEventListener("abort",xl);let{loaderResults:Sl,fetcherResults:xe}=await F(y,mr,Lo,Ti,fs);if(fe.signal.aborted)return;fe.signal.removeEventListener("abort",xl),Z.delete(P),M.delete(P),Ti.forEach(Xe=>M.delete(Xe.key));let Ve=Hl(Sl);if(Ve)return hr(fs,Ve.result,!1,{preventScrollReset:J});if(Ve=Hl(xe),Ve)return pe.add(Ve.key),hr(fs,Ve.result,!1,{preventScrollReset:J});let{loaderData:ds,errors:Mo}=Xy(y,mr,Sl,void 0,Ti,xe,ye);if(y.fetchers.has(P)){let Xe=Qr(be.data);y.fetchers.set(P,Xe)}xt(Bn),y.navigation.state==="loading"&&Bn>b?(ce(R,"Expected pending action"),A&&A.abort(),Ft(y.navigation.location,{matches:mr,loaderData:ds,errors:Mo,fetchers:new Map(y.fetchers)})):(Ge({errors:Mo,loaderData:Yy(y.loaderData,ds,mr,Mo),fetchers:new Map(y.fetchers)}),V=!1)}async function cf(P,L,N,$,W,ne,oe,J,X){let q=y.fetchers.get(P);re(P,Qo(X,q?q.data:void 0),{flushSync:oe});let ee=new AbortController,fe=ms(e.history,N,ee.signal);if(ne){let be=await wl(W,new URL(fe.url).pathname,fe.signal,P);if(be.type==="aborted")return;if(be.type==="error"){ae(P,L,be.error,{flushSync:oe});return}else if(be.matches)W=be.matches,$=ta(W,N);else{ae(P,L,jt(404,{pathname:N}),{flushSync:oe});return}}M.set(P,ee);let ve=U,Te=(await Ai("loader",y,fe,[$],W,P))[$.route.id];if(ii(Te)&&(Te=await dm(Te,fe.signal,!0)||Te),M.get(P)===ee&&M.delete(P),!fe.signal.aborted){if(Le.has(P)){re(P,Qr(void 0));return}if(zi(Te))if(b>ve){re(P,Qr(void 0));return}else{pe.add(P),await hr(fe,Te,!1,{preventScrollReset:J});return}if(Xt(Te)){ae(P,L,Te.error);return}ce(!ii(Te),"Unhandled fetcher deferred data"),re(P,Qr(Te.data))}}async function hr(P,L,N,$){let{submission:W,fetcherSubmission:ne,preventScrollReset:oe,replace:J}=$===void 0?{}:$;L.response.headers.has("X-Remix-Revalidate")&&(V=!0);let X=L.response.headers.get("Location");ce(X,"Expected a Location header on the redirect Response"),X=Jy(X,new URL(P.url),l);let q=Wa(y.location,X,{_isRedirect:!0});if(n){let be=!1;if(L.response.headers.has("X-Remix-Reload-Document"))be=!0;else if(fm.test(X)){const He=e.history.createURL(X);be=He.origin!==t.location.origin||xi(He.pathname,l)==null}if(be){J?t.location.replace(X):t.location.assign(X);return}}A=null;let ee=J===!0||L.response.headers.has("X-Remix-Replace")?Ye.Replace:Ye.Push,{formMethod:fe,formAction:ve,formEncType:ct}=y.navigation;!W&&!ne&&fe&&ve&&ct&&(W=nv(y.navigation));let Te=W||ne;if(CA.has(L.response.status)&&Te&&Tn(Te.formMethod))await on(ee,q,{submission:De({},Te,{formAction:X}),preventScrollReset:oe||T,enableViewTransition:N?O:void 0});else{let be=Kf(q,W);await on(ee,q,{overrideNavigation:be,fetcherSubmission:ne,preventScrollReset:oe||T,enableViewTransition:N?O:void 0})}}async function Ai(P,L,N,$,W,ne){let oe,J={};try{oe=await LA(u,P,L,N,$,W,ne,s,i)}catch(X){return $.forEach(q=>{J[q.route.id]={type:ke.error,error:X}}),J}for(let[X,q]of Object.entries(oe))if(jA(q)){let ee=q.result;J[X]={type:ke.redirect,response:FA(ee,N,X,W,l,c.v7_relativeSplatPath)}}else J[X]=await NA(q);return J}async function F(P,L,N,$,W){let ne=P.matches,oe=Ai("loader",P,W,N,L,null),J=Promise.all($.map(async ee=>{if(ee.matches&&ee.match&&ee.controller){let ve=(await Ai("loader",P,ms(e.history,ee.path,ee.controller.signal),[ee.match],ee.matches,ee.key))[ee.match.route.id];return{[ee.key]:ve}}else return Promise.resolve({[ee.key]:{type:ke.error,error:jt(404,{pathname:ee.path})}})})),X=await oe,q=(await J).reduce((ee,fe)=>Object.assign(ee,fe),{});return await Promise.all([BA(L,X,W.signal,ne,P.loaderData),HA(L,q,$)]),{loaderResults:X,fetcherResults:q}}function H(){V=!0,G.push(...df()),C.forEach((P,L)=>{M.has(L)&&Q.add(L),it(L)})}function re(P,L,N){N===void 0&&(N={}),y.fetchers.set(P,L),Ge({fetchers:new Map(y.fetchers)},{flushSync:(N&&N.flushSync)===!0})}function ae(P,L,N,$){$===void 0&&($={});let W=Ni(y.matches,L);wt(P),Ge({errors:{[W.route.id]:N},fetchers:new Map(y.fetchers)},{flushSync:($&&$.flushSync)===!0})}function Ce(P){return Ae.set(P,(Ae.get(P)||0)+1),Le.has(P)&&Le.delete(P),y.fetchers.get(P)||kA}function wt(P){let L=y.fetchers.get(P);M.has(P)&&!(L&&L.state==="loading"&&Z.has(P))&&it(P),C.delete(P),Z.delete(P),pe.delete(P),c.v7_fetcherPersist&&Le.delete(P),Q.delete(P),y.fetchers.delete(P)}function pr(P){let L=(Ae.get(P)||0)-1;L<=0?(Ae.delete(P),Le.add(P),c.v7_fetcherPersist||wt(P)):Ae.set(P,L),Ge({fetchers:new Map(y.fetchers)})}function it(P){let L=M.get(P);L&&(L.abort(),M.delete(P))}function Nr(P){for(let L of P){let N=Ce(L),$=Qr(N.data);y.fetchers.set(L,$)}}function Fr(){let P=[],L=!1;for(let N of pe){let $=y.fetchers.get(N);ce($,"Expected fetcher: "+N),$.state==="loading"&&(pe.delete(N),P.push(N),L=!0)}return Nr(P),L}function xt(P){let L=[];for(let[N,$]of Z)if($0}function Dr(P,L){let N=y.blockers.get(P)||Wo;return qe.get(P)!==L&&qe.set(P,L),N}function an(P){y.blockers.delete(P),qe.delete(P)}function yl(P,L){let N=y.blockers.get(P)||Wo;ce(N.state==="unblocked"&&L.state==="blocked"||N.state==="blocked"&&L.state==="blocked"||N.state==="blocked"&&L.state==="proceeding"||N.state==="blocked"&&L.state==="unblocked"||N.state==="proceeding"&&L.state==="unblocked","Invalid blocker state transition: "+N.state+" -> "+L.state);let $=new Map(y.blockers);$.set(P,L),Ge({blockers:$})}function sg(P){let{currentLocation:L,nextLocation:N,historyAction:$}=P;if(qe.size===0)return;qe.size>1&&yo(!1,"A router only supports one blocker at a time");let W=Array.from(qe.entries()),[ne,oe]=W[W.length-1],J=y.blockers.get(ne);if(!(J&&J.state==="proceeding")&&oe({currentLocation:L,nextLocation:N,historyAction:$}))return ne}function ff(P){let L=jt(404,{pathname:P}),N=a||o,{matches:$,route:W}=ev(N);return df(),{notFoundMatches:$,route:W,error:L}}function df(P){let L=[];return ye.forEach((N,$)=>{(!P||P($))&&(N.cancel(),L.push($),ye.delete($))}),L}function sE(P,L,N){if(g=P,x=L,v=N||null,!m&&y.navigation===Qf){m=!0;let $=ag(y.location,y.matches);$!=null&&Ge({restoreScrollPosition:$})}return()=>{g=null,x=null,v=null}}function og(P,L){return v&&v(P,L.map($=>rA($,y.loaderData)))||P.key}function oE(P,L){if(g&&x){let N=og(P,L);g[N]=x()}}function ag(P,L){if(g){let N=og(P,L),$=g[N];if(typeof $=="number")return $}return null}function vl(P,L,N){if(f)if(P){if(Object.keys(P[0].params).length>0)return{active:!0,matches:gu(L,N,l,!0)}}else return{active:!0,matches:gu(L,N,l,!0)||[]};return{active:!1,matches:null}}async function wl(P,L,N,$){if(!f)return{type:"success",matches:P};let W=P;for(;;){let ne=a==null,oe=a||o,J=s;try{await f({signal:N,path:L,matches:W,fetcherKey:$,patch:(ee,fe)=>{N.aborted||qy(ee,fe,oe,J,i)}})}catch(ee){return{type:"error",error:ee,partialMatches:W}}finally{ne&&!N.aborted&&(o=[...o])}if(N.aborted)return{type:"aborted"};let X=Mi(oe,L,l);if(X)return{type:"success",matches:X};let q=gu(oe,L,l,!0);if(!q||W.length===q.length&&W.every((ee,fe)=>ee.route.id===q[fe].route.id))return{type:"success",matches:null};W=q}}function aE(P){s={},a=tc(P,i,void 0,s)}function lE(P,L){let N=a==null;qy(P,L,a||o,s,i),N&&(o=[...o],Ge({}))}return E={get basename(){return l},get future(){return c},get state(){return y},get routes(){return o},get window(){return t},initialize:xn,subscribe:dr,enableScrollRestoration:sE,navigate:Ri,fetch:lf,revalidate:us,createHref:P=>e.history.createHref(P),encodeLocation:P=>e.history.encodeLocation(P),getFetcher:Ce,deleteFetcher:pr,dispose:Sn,getBlocker:Dr,deleteBlocker:an,patchRoutes:lE,_internalFetchControllers:M,_internalActiveDeferreds:ye,_internalSetRoutes:aE},E}function AA(e){return e!=null&&("formData"in e&&e.formData!=null||"body"in e&&e.body!==void 0)}function Ch(e,t,n,r,i,s,o,a){let l,u;if(o){l=[];for(let c of t)if(l.push(c),c.route.id===o){u=c;break}}else l=t,u=t[t.length-1];let f=Bc(i||".",Uc(l,s),xi(e.pathname,n)||e.pathname,a==="path");if(i==null&&(f.search=e.search,f.hash=e.hash),(i==null||i===""||i===".")&&u){let c=hm(f.search);if(u.route.index&&!c)f.search=f.search?f.search.replace(/^\?/,"?index&"):"?index";else if(!u.route.index&&c){let d=new URLSearchParams(f.search),h=d.getAll("index");d.delete("index"),h.filter(v=>v).forEach(v=>d.append("index",v));let g=d.toString();f.search=g?"?"+g:""}}return r&&n!=="/"&&(f.pathname=f.pathname==="/"?n:sr([n,f.pathname])),wi(f)}function Vy(e,t,n,r){if(!r||!AA(r))return{path:n};if(r.formMethod&&!UA(r.formMethod))return{path:n,error:jt(405,{method:r.formMethod})};let i=()=>({path:n,error:jt(400,{type:"invalid-body"})}),s=r.formMethod||"get",o=e?s.toUpperCase():s.toLowerCase(),a=i1(n);if(r.body!==void 0){if(r.formEncType==="text/plain"){if(!Tn(o))return i();let d=typeof r.body=="string"?r.body:r.body instanceof FormData||r.body instanceof URLSearchParams?Array.from(r.body.entries()).reduce((h,g)=>{let[v,x]=g;return""+h+v+"="+x+` -`},""):String(r.body);return{path:n,submission:{formMethod:o,formAction:a,formEncType:r.formEncType,formData:void 0,json:void 0,text:d}}}else if(r.formEncType==="application/json"){if(!Tn(o))return i();try{let d=typeof r.body=="string"?JSON.parse(r.body):r.body;return{path:n,submission:{formMethod:o,formAction:a,formEncType:r.formEncType,formData:void 0,json:d,text:void 0}}}catch{return i()}}}ce(typeof FormData=="function","FormData is not available in this environment");let l,u;if(r.formData)l=Ph(r.formData),u=r.formData;else if(r.body instanceof FormData)l=Ph(r.body),u=r.body;else if(r.body instanceof URLSearchParams)l=r.body,u=Gy(l);else if(r.body==null)l=new URLSearchParams,u=new FormData;else try{l=new URLSearchParams(r.body),u=Gy(l)}catch{return i()}let f={formMethod:o,formAction:a,formEncType:r&&r.formEncType||"application/x-www-form-urlencoded",formData:u,json:void 0,text:void 0};if(Tn(f.formMethod))return{path:n,submission:f};let c=_i(n);return t&&c.search&&hm(c.search)&&l.append("index",""),c.search="?"+l,{path:wi(c),submission:f}}function Wy(e,t,n){n===void 0&&(n=!1);let r=e.findIndex(i=>i.route.id===t);return r>=0?e.slice(0,n?r+1:r):e}function Qy(e,t,n,r,i,s,o,a,l,u,f,c,d,h,g,v){let x=v?Xt(v[1])?v[1].error:v[1].data:void 0,m=e.createURL(t.location),p=e.createURL(i),w=n;s&&t.errors?w=Wy(n,Object.keys(t.errors)[0],!0):v&&Xt(v[1])&&(w=Wy(n,v[0]));let S=v?v[1].statusCode:void 0,k=o&&S&&S>=400,E=w.filter((R,T)=>{let{route:A}=R;if(A.lazy)return!0;if(A.loader==null)return!1;if(s)return kh(A,t.loaderData,t.errors);if(TA(t.loaderData,t.matches[T],R)||l.some(z=>z===R.route.id))return!0;let O=t.matches[T],I=R;return Ky(R,De({currentUrl:m,currentParams:O.params,nextUrl:p,nextParams:I.params},r,{actionResult:x,actionStatus:S,defaultShouldRevalidate:k?!1:a||m.pathname+m.search===p.pathname+p.search||m.search!==p.search||n1(O,I)}))}),y=[];return c.forEach((R,T)=>{if(s||!n.some(B=>B.route.id===R.routeId)||f.has(T))return;let A=Mi(h,R.path,g);if(!A){y.push({key:T,routeId:R.routeId,path:R.path,matches:null,match:null,controller:null});return}let O=t.fetchers.get(T),I=ta(A,R.path),z=!1;d.has(T)?z=!1:u.has(T)?(u.delete(T),z=!0):O&&O.state!=="idle"&&O.data===void 0?z=a:z=Ky(I,De({currentUrl:m,currentParams:t.matches[t.matches.length-1].params,nextUrl:p,nextParams:n[n.length-1].params},r,{actionResult:x,actionStatus:S,defaultShouldRevalidate:k?!1:a})),z&&y.push({key:T,routeId:R.routeId,path:R.path,matches:A,match:I,controller:new AbortController})}),[E,y]}function kh(e,t,n){if(e.lazy)return!0;if(!e.loader)return!1;let r=t!=null&&t[e.id]!==void 0,i=n!=null&&n[e.id]!==void 0;return!r&&i?!1:typeof e.loader=="function"&&e.loader.hydrate===!0?!0:!r&&!i}function TA(e,t,n){let r=!t||n.route.id!==t.route.id,i=e[n.route.id]===void 0;return r||i}function n1(e,t){let n=e.route.path;return e.pathname!==t.pathname||n!=null&&n.endsWith("*")&&e.params["*"]!==t.params["*"]}function Ky(e,t){if(e.route.shouldRevalidate){let n=e.route.shouldRevalidate(t);if(typeof n=="boolean")return n}return t.defaultShouldRevalidate}function qy(e,t,n,r,i){var s;let o;if(e){let u=r[e];ce(u,"No route found to patch children into: routeId = "+e),u.children||(u.children=[]),o=u.children}else o=n;let a=t.filter(u=>!o.some(f=>r1(u,f))),l=tc(a,i,[e||"_","patch",String(((s=o)==null?void 0:s.length)||"0")],r);o.push(...l)}function r1(e,t){return"id"in e&&"id"in t&&e.id===t.id?!0:e.index===t.index&&e.path===t.path&&e.caseSensitive===t.caseSensitive?(!e.children||e.children.length===0)&&(!t.children||t.children.length===0)?!0:e.children.every((n,r)=>{var i;return(i=t.children)==null?void 0:i.some(s=>r1(n,s))}):!1}async function OA(e,t,n){if(!e.lazy)return;let r=await e.lazy();if(!e.lazy)return;let i=n[e.id];ce(i,"No route found in manifest");let s={};for(let o in r){let l=i[o]!==void 0&&o!=="hasErrorBoundary";yo(!l,'Route "'+i.id+'" has a static property "'+o+'" defined but its lazy function is also returning a value for this property. '+('The lazy route property "'+o+'" will be ignored.')),!l&&!tA.has(o)&&(s[o]=r[o])}Object.assign(i,s),Object.assign(i,De({},t(i),{lazy:void 0}))}async function IA(e){let{matches:t}=e,n=t.filter(i=>i.shouldLoad);return(await Promise.all(n.map(i=>i.resolve()))).reduce((i,s,o)=>Object.assign(i,{[n[o].route.id]:s}),{})}async function LA(e,t,n,r,i,s,o,a,l,u){let f=s.map(h=>h.route.lazy?OA(h.route,l,a):void 0),c=s.map((h,g)=>{let v=f[g],x=i.some(p=>p.route.id===h.route.id);return De({},h,{shouldLoad:x,resolve:async p=>(p&&r.method==="GET"&&(h.route.lazy||h.route.loader)&&(x=!0),x?MA(t,r,h,v,p,u):Promise.resolve({type:ke.data,result:void 0}))})}),d=await e({matches:c,request:r,params:s[0].params,fetcherKey:o,context:u});try{await Promise.all(f)}catch{}return d}async function MA(e,t,n,r,i,s){let o,a,l=u=>{let f,c=new Promise((g,v)=>f=v);a=()=>f(),t.signal.addEventListener("abort",a);let d=g=>typeof u!="function"?Promise.reject(new Error("You cannot call the handler for a route which defines a boolean "+('"'+e+'" [routeId: '+n.route.id+"]"))):u({request:t,params:n.params,context:s},...g!==void 0?[g]:[]),h=(async()=>{try{return{type:"data",result:await(i?i(v=>d(v)):d())}}catch(g){return{type:"error",result:g}}})();return Promise.race([h,c])};try{let u=n.route[e];if(r)if(u){let f,[c]=await Promise.all([l(u).catch(d=>{f=d}),r]);if(f!==void 0)throw f;o=c}else if(await r,u=n.route[e],u)o=await l(u);else if(e==="action"){let f=new URL(t.url),c=f.pathname+f.search;throw jt(405,{method:t.method,pathname:c,routeId:n.route.id})}else return{type:ke.data,result:void 0};else if(u)o=await l(u);else{let f=new URL(t.url),c=f.pathname+f.search;throw jt(404,{pathname:c})}ce(o.result!==void 0,"You defined "+(e==="action"?"an action":"a loader")+" for route "+('"'+n.route.id+"\" but didn't return anything from your `"+e+"` ")+"function. Please return a value or `null`.")}catch(u){return{type:ke.error,result:u}}finally{a&&t.signal.removeEventListener("abort",a)}return o}async function NA(e){let{result:t,type:n}=e;if(s1(t)){let c;try{let d=t.headers.get("Content-Type");d&&/\bapplication\/json\b/.test(d)?t.body==null?c=null:c=await t.json():c=await t.text()}catch(d){return{type:ke.error,error:d}}return n===ke.error?{type:ke.error,error:new nc(t.status,t.statusText,c),statusCode:t.status,headers:t.headers}:{type:ke.data,data:c,statusCode:t.status,headers:t.headers}}if(n===ke.error){if(tv(t)){var r,i;if(t.data instanceof Error){var s,o;return{type:ke.error,error:t.data,statusCode:(s=t.init)==null?void 0:s.status,headers:(o=t.init)!=null&&o.headers?new Headers(t.init.headers):void 0}}return{type:ke.error,error:new nc(((r=t.init)==null?void 0:r.status)||500,void 0,t.data),statusCode:Qa(t)?t.status:void 0,headers:(i=t.init)!=null&&i.headers?new Headers(t.init.headers):void 0}}return{type:ke.error,error:t,statusCode:Qa(t)?t.status:void 0}}if(zA(t)){var a,l;return{type:ke.deferred,deferredData:t,statusCode:(a=t.init)==null?void 0:a.status,headers:((l=t.init)==null?void 0:l.headers)&&new Headers(t.init.headers)}}if(tv(t)){var u,f;return{type:ke.data,data:t.data,statusCode:(u=t.init)==null?void 0:u.status,headers:(f=t.init)!=null&&f.headers?new Headers(t.init.headers):void 0}}return{type:ke.data,data:t}}function FA(e,t,n,r,i,s){let o=e.headers.get("Location");if(ce(o,"Redirects returned/thrown from loaders/actions must have a Location header"),!fm.test(o)){let a=r.slice(0,r.findIndex(l=>l.route.id===n)+1);o=Ch(new URL(t.url),a,i,!0,o,s),e.headers.set("Location",o)}return e}function Jy(e,t,n){if(fm.test(e)){let r=e,i=r.startsWith("//")?new URL(t.protocol+r):new URL(r),s=xi(i.pathname,n)!=null;if(i.origin===t.origin&&s)return i.pathname+i.search+i.hash}return e}function ms(e,t,n,r){let i=e.createURL(i1(t)).toString(),s={signal:n};if(r&&Tn(r.formMethod)){let{formMethod:o,formEncType:a}=r;s.method=o.toUpperCase(),a==="application/json"?(s.headers=new Headers({"Content-Type":a}),s.body=JSON.stringify(r.json)):a==="text/plain"?s.body=r.text:a==="application/x-www-form-urlencoded"&&r.formData?s.body=Ph(r.formData):s.body=r.formData}return new Request(i,s)}function Ph(e){let t=new URLSearchParams;for(let[n,r]of e.entries())t.append(n,typeof r=="string"?r:r.name);return t}function Gy(e){let t=new FormData;for(let[n,r]of e.entries())t.append(n,r);return t}function DA(e,t,n,r,i){let s={},o=null,a,l=!1,u={},f=n&&Xt(n[1])?n[1].error:void 0;return e.forEach(c=>{if(!(c.route.id in t))return;let d=c.route.id,h=t[d];if(ce(!zi(h),"Cannot handle redirect results in processLoaderData"),Xt(h)){let g=h.error;f!==void 0&&(g=f,f=void 0),o=o||{};{let v=Ni(e,d);o[v.route.id]==null&&(o[v.route.id]=g)}s[d]=void 0,l||(l=!0,a=Qa(h.error)?h.error.status:500),h.headers&&(u[d]=h.headers)}else ii(h)?(r.set(d,h.deferredData),s[d]=h.deferredData.data,h.statusCode!=null&&h.statusCode!==200&&!l&&(a=h.statusCode),h.headers&&(u[d]=h.headers)):(s[d]=h.data,h.statusCode&&h.statusCode!==200&&!l&&(a=h.statusCode),h.headers&&(u[d]=h.headers))}),f!==void 0&&n&&(o={[n[0]]:f},s[n[0]]=void 0),{loaderData:s,errors:o,statusCode:a||200,loaderHeaders:u}}function Xy(e,t,n,r,i,s,o){let{loaderData:a,errors:l}=DA(t,n,r,o);return i.forEach(u=>{let{key:f,match:c,controller:d}=u,h=s[f];if(ce(h,"Did not find corresponding fetcher result"),!(d&&d.signal.aborted))if(Xt(h)){let g=Ni(e.matches,c==null?void 0:c.route.id);l&&l[g.route.id]||(l=De({},l,{[g.route.id]:h.error})),e.fetchers.delete(f)}else if(zi(h))ce(!1,"Unhandled fetcher revalidation redirect");else if(ii(h))ce(!1,"Unhandled fetcher deferred data");else{let g=Qr(h.data);e.fetchers.set(f,g)}}),{loaderData:a,errors:l}}function Yy(e,t,n,r){let i=De({},t);for(let s of n){let o=s.route.id;if(t.hasOwnProperty(o)?t[o]!==void 0&&(i[o]=t[o]):e[o]!==void 0&&s.route.loader&&(i[o]=e[o]),r&&r.hasOwnProperty(o))break}return i}function Zy(e){return e?Xt(e[1])?{actionData:{}}:{actionData:{[e[0]]:e[1].data}}:{}}function Ni(e,t){return(t?e.slice(0,e.findIndex(r=>r.route.id===t)+1):[...e]).reverse().find(r=>r.route.hasErrorBoundary===!0)||e[0]}function ev(e){let t=e.length===1?e[0]:e.find(n=>n.index||!n.path||n.path==="/")||{id:"__shim-error-route__"};return{matches:[{params:{},pathname:"",pathnameBase:"",route:t}],route:t}}function jt(e,t){let{pathname:n,routeId:r,method:i,type:s,message:o}=t===void 0?{}:t,a="Unknown Server Error",l="Unknown @remix-run/router error";return e===400?(a="Bad Request",i&&n&&r?l="You made a "+i+' request to "'+n+'" but '+('did not provide a `loader` for route "'+r+'", ')+"so there is no way to handle the request.":s==="defer-action"?l="defer() is not supported in actions":s==="invalid-body"&&(l="Unable to encode submission body")):e===403?(a="Forbidden",l='Route "'+r+'" does not match URL "'+n+'"'):e===404?(a="Not Found",l='No route matches URL "'+n+'"'):e===405&&(a="Method Not Allowed",i&&n&&r?l="You made a "+i.toUpperCase()+' request to "'+n+'" but '+('did not provide an `action` for route "'+r+'", ')+"so there is no way to handle the request.":i&&(l='Invalid request method "'+i.toUpperCase()+'"')),new nc(e||500,a,new Error(l),!0)}function Hl(e){let t=Object.entries(e);for(let n=t.length-1;n>=0;n--){let[r,i]=t[n];if(zi(i))return{key:r,result:i}}}function i1(e){let t=typeof e=="string"?_i(e):e;return wi(De({},t,{hash:""}))}function $A(e,t){return e.pathname!==t.pathname||e.search!==t.search?!1:e.hash===""?t.hash!=="":e.hash===t.hash?!0:t.hash!==""}function jA(e){return s1(e.result)&&_A.has(e.result.status)}function ii(e){return e.type===ke.deferred}function Xt(e){return e.type===ke.error}function zi(e){return(e&&e.type)===ke.redirect}function tv(e){return typeof e=="object"&&e!=null&&"type"in e&&"data"in e&&"init"in e&&e.type==="DataWithResponseInit"}function zA(e){let t=e;return t&&typeof t=="object"&&typeof t.data=="object"&&typeof t.subscribe=="function"&&typeof t.cancel=="function"&&typeof t.resolveData=="function"}function s1(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.headers=="object"&&typeof e.body<"u"}function UA(e){return EA.has(e.toLowerCase())}function Tn(e){return SA.has(e.toLowerCase())}async function BA(e,t,n,r,i){let s=Object.entries(t);for(let o=0;o(d==null?void 0:d.route.id)===a);if(!u)continue;let f=r.find(d=>d.route.id===u.route.id),c=f!=null&&!n1(f,u)&&(i&&i[u.route.id])!==void 0;ii(l)&&c&&await dm(l,n,!1).then(d=>{d&&(t[a]=d)})}}async function HA(e,t,n){for(let r=0;r(u==null?void 0:u.route.id)===s)&&ii(a)&&(ce(o,"Expected an AbortController for revalidating fetcher deferred result"),await dm(a,o.signal,!0).then(u=>{u&&(t[i]=u)}))}}async function dm(e,t,n){if(n===void 0&&(n=!1),!await e.deferredData.resolveData(t)){if(n)try{return{type:ke.data,data:e.deferredData.unwrappedData}}catch(i){return{type:ke.error,error:i}}return{type:ke.data,data:e.deferredData.data}}}function hm(e){return new URLSearchParams(e).getAll("index").some(t=>t==="")}function ta(e,t){let n=typeof t=="string"?_i(t).search:t.search;if(e[e.length-1].route.index&&hm(n||""))return e[e.length-1];let r=ZS(e);return r[r.length-1]}function nv(e){let{formMethod:t,formAction:n,formEncType:r,text:i,formData:s,json:o}=e;if(!(!t||!n||!r)){if(i!=null)return{formMethod:t,formAction:n,formEncType:r,formData:void 0,json:void 0,text:i};if(s!=null)return{formMethod:t,formAction:n,formEncType:r,formData:s,json:void 0,text:void 0};if(o!==void 0)return{formMethod:t,formAction:n,formEncType:r,formData:void 0,json:o,text:void 0}}}function Kf(e,t){return t?{state:"loading",location:e,formMethod:t.formMethod,formAction:t.formAction,formEncType:t.formEncType,formData:t.formData,json:t.json,text:t.text}:{state:"loading",location:e,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0}}function VA(e,t){return{state:"submitting",location:e,formMethod:t.formMethod,formAction:t.formAction,formEncType:t.formEncType,formData:t.formData,json:t.json,text:t.text}}function Qo(e,t){return e?{state:"loading",formMethod:e.formMethod,formAction:e.formAction,formEncType:e.formEncType,formData:e.formData,json:e.json,text:e.text,data:t}:{state:"loading",formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0,data:t}}function WA(e,t){return{state:"submitting",formMethod:e.formMethod,formAction:e.formAction,formEncType:e.formEncType,formData:e.formData,json:e.json,text:e.text,data:t?t.data:void 0}}function Qr(e){return{state:"idle",formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0,data:e}}function QA(e,t){try{let n=e.sessionStorage.getItem(t1);if(n){let r=JSON.parse(n);for(let[i,s]of Object.entries(r||{}))s&&Array.isArray(s)&&t.set(i,new Set(s||[]))}}catch{}}function KA(e,t){if(t.size>0){let n={};for(let[r,i]of t)n[r]=[...i];try{e.sessionStorage.setItem(t1,JSON.stringify(n))}catch(r){yo(!1,"Failed to save applied view transitions in sessionStorage ("+r+").")}}}/** + */function De(){return De=Object.assign?Object.assign.bind():function(e){for(var t=1;t"u")throw new Error(t)}function yo(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function ZR(){return Math.random().toString(36).substr(2,8)}function Uy(e,t){return{usr:e.state,key:e.key,idx:t}}function Wa(e,t,n,r){return n===void 0&&(n=null),De({pathname:typeof e=="string"?e:e.pathname,search:"",hash:""},typeof t=="string"?Ci(t):t,{state:n,key:t&&t.key||r||ZR()})}function wi(e){let{pathname:t="/",search:n="",hash:r=""}=e;return n&&n!=="?"&&(t+=n.charAt(0)==="?"?n:"?"+n),r&&r!=="#"&&(t+=r.charAt(0)==="#"?r:"#"+r),t}function Ci(e){let t={};if(e){let n=e.indexOf("#");n>=0&&(t.hash=e.substr(n),e=e.substr(0,n));let r=e.indexOf("?");r>=0&&(t.search=e.substr(r),e=e.substr(0,r)),e&&(t.pathname=e)}return t}function eA(e,t,n,r){r===void 0&&(r={});let{window:i=document.defaultView,v5Compat:s=!1}=r,o=i.history,a=Ye.Pop,l=null,u=f();u==null&&(u=0,o.replaceState(De({},o.state,{idx:u}),""));function f(){return(o.state||{idx:null}).idx}function c(){a=Ye.Pop;let x=f(),m=x==null?null:x-u;u=x,l&&l({action:a,location:v.location,delta:m})}function d(x,m){a=Ye.Push;let p=Wa(v.location,x,m);u=f()+1;let w=Uy(p,u),S=v.createHref(p);try{o.pushState(w,"",S)}catch(k){if(k instanceof DOMException&&k.name==="DataCloneError")throw k;i.location.assign(S)}s&&l&&l({action:a,location:v.location,delta:1})}function h(x,m){a=Ye.Replace;let p=Wa(v.location,x,m);u=f();let w=Uy(p,u),S=v.createHref(p);o.replaceState(w,"",S),s&&l&&l({action:a,location:v.location,delta:0})}function g(x){let m=i.location.origin!=="null"?i.location.origin:i.location.href,p=typeof x=="string"?x:wi(x);return p=p.replace(/ $/,"%20"),ce(m,"No window.location.(origin|href) available to create URL for href: "+p),new URL(p,m)}let v={get action(){return a},get location(){return e(i,o)},listen(x){if(l)throw new Error("A history only accepts one active listener");return i.addEventListener(zy,c),l=x,()=>{i.removeEventListener(zy,c),l=null}},createHref(x){return t(i,x)},createURL:g,encodeLocation(x){let m=g(x);return{pathname:m.pathname,search:m.search,hash:m.hash}},push:d,replace:h,go(x){return o.go(x)}};return v}var ke;(function(e){e.data="data",e.deferred="deferred",e.redirect="redirect",e.error="error"})(ke||(ke={}));const tA=new Set(["lazy","caseSensitive","path","id","index","children"]);function nA(e){return e.index===!0}function tc(e,t,n,r){return n===void 0&&(n=[]),r===void 0&&(r={}),e.map((i,s)=>{let o=[...n,String(s)],a=typeof i.id=="string"?i.id:o.join("-");if(ce(i.index!==!0||!i.children,"Cannot specify children on an index route"),ce(!r[a],'Found a route id collision on id "'+a+`". Route id's must be globally unique within Data Router usages`),nA(i)){let l=De({},i,t(i),{id:a});return r[a]=l,l}else{let l=De({},i,t(i),{id:a,children:void 0});return r[a]=l,i.children&&(l.children=tc(i.children,t,o,r)),l}})}function Mi(e,t,n){return n===void 0&&(n="/"),gu(e,t,n,!1)}function gu(e,t,n,r){let i=typeof t=="string"?Ci(t):t,s=xi(i.pathname||"/",n);if(s==null)return null;let o=XS(e);iA(o);let a=null;for(let l=0;a==null&&l{let l={relativePath:a===void 0?s.path||"":a,caseSensitive:s.caseSensitive===!0,childrenIndex:o,route:s};l.relativePath.startsWith("/")&&(ce(l.relativePath.startsWith(r),'Absolute route path "'+l.relativePath+'" nested under path '+('"'+r+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),l.relativePath=l.relativePath.slice(r.length));let u=sr([r,l.relativePath]),f=n.concat(l);s.children&&s.children.length>0&&(ce(s.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+u+'".')),XS(s.children,t,f,u)),!(s.path==null&&!s.index)&&t.push({path:u,score:fA(u,s.index),routesMeta:f})};return e.forEach((s,o)=>{var a;if(s.path===""||!((a=s.path)!=null&&a.includes("?")))i(s,o);else for(let l of YS(s.path))i(s,o,l)}),t}function YS(e){let t=e.split("/");if(t.length===0)return[];let[n,...r]=t,i=n.endsWith("?"),s=n.replace(/\?$/,"");if(r.length===0)return i?[s,""]:[s];let o=YS(r.join("/")),a=[];return a.push(...o.map(l=>l===""?s:[s,l].join("/"))),i&&a.push(...o),a.map(l=>e.startsWith("/")&&l===""?"/":l)}function iA(e){e.sort((t,n)=>t.score!==n.score?n.score-t.score:dA(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}const sA=/^:[\w-]+$/,oA=3,aA=2,lA=1,uA=10,cA=-2,By=e=>e==="*";function fA(e,t){let n=e.split("/"),r=n.length;return n.some(By)&&(r+=cA),t&&(r+=aA),n.filter(i=>!By(i)).reduce((i,s)=>i+(sA.test(s)?oA:s===""?lA:uA),r)}function dA(e,t){return e.length===t.length&&e.slice(0,-1).every((r,i)=>r===t[i])?e[e.length-1]-t[t.length-1]:0}function hA(e,t,n){n===void 0&&(n=!1);let{routesMeta:r}=e,i={},s="/",o=[];for(let a=0;a{let{paramName:d,isOptional:h}=f;if(d==="*"){let v=a[c]||"";o=s.slice(0,s.length-v.length).replace(/(.)\/+$/,"$1")}const g=a[c];return h&&!g?u[d]=void 0:u[d]=(g||"").replace(/%2F/g,"/"),u},{}),pathname:s,pathnameBase:o,pattern:e}}function pA(e,t,n){t===void 0&&(t=!1),n===void 0&&(n=!0),yo(e==="*"||!e.endsWith("*")||e.endsWith("/*"),'Route path "'+e+'" will be treated as if it were '+('"'+e.replace(/\*$/,"/*")+'" because the `*` character must ')+"always follow a `/` in the pattern. To get rid of this warning, "+('please change the route path to "'+e.replace(/\*$/,"/*")+'".'));let r=[],i="^"+e.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(o,a,l)=>(r.push({paramName:a,isOptional:l!=null}),l?"/?([^\\/]+)?":"/([^\\/]+)"));return e.endsWith("*")?(r.push({paramName:"*"}),i+=e==="*"||e==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?i+="\\/*$":e!==""&&e!=="/"&&(i+="(?:(?=\\/|$))"),[new RegExp(i,t?void 0:"i"),r]}function mA(e){try{return e.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return yo(!1,'The URL path "'+e+'" could not be decoded because it is is a malformed URL segment. This is probably due to a bad percent '+("encoding ("+t+").")),e}}function xi(e,t){if(t==="/")return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith("/")?t.length-1:t.length,r=e.charAt(n);return r&&r!=="/"?null:e.slice(n)||"/"}function gA(e,t){t===void 0&&(t="/");let{pathname:n,search:r="",hash:i=""}=typeof e=="string"?Ci(e):e;return{pathname:n?n.startsWith("/")?n:yA(n,t):t,search:wA(r),hash:xA(i)}}function yA(e,t){let n=t.replace(/\/+$/,"").split("/");return e.split("/").forEach(i=>{i===".."?n.length>1&&n.pop():i!=="."&&n.push(i)}),n.length>1?n.join("/"):"/"}function Wf(e,t,n,r){return"Cannot include a '"+e+"' character in a manually specified "+("`to."+t+"` field ["+JSON.stringify(r)+"]. Please separate it out to the ")+("`to."+n+"` field. Alternatively you may provide the full path as ")+'a string in and the router will parse it for you.'}function ZS(e){return e.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function Uc(e,t){let n=ZS(e);return t?n.map((r,i)=>i===n.length-1?r.pathname:r.pathnameBase):n.map(r=>r.pathnameBase)}function Bc(e,t,n,r){r===void 0&&(r=!1);let i;typeof e=="string"?i=Ci(e):(i=De({},e),ce(!i.pathname||!i.pathname.includes("?"),Wf("?","pathname","search",i)),ce(!i.pathname||!i.pathname.includes("#"),Wf("#","pathname","hash",i)),ce(!i.search||!i.search.includes("#"),Wf("#","search","hash",i)));let s=e===""||i.pathname==="",o=s?"/":i.pathname,a;if(o==null)a=n;else{let c=t.length-1;if(!r&&o.startsWith("..")){let d=o.split("/");for(;d[0]==="..";)d.shift(),c-=1;i.pathname=d.join("/")}a=c>=0?t[c]:"/"}let l=gA(i,a),u=o&&o!=="/"&&o.endsWith("/"),f=(s||o===".")&&n.endsWith("/");return!l.pathname.endsWith("/")&&(u||f)&&(l.pathname+="/"),l}const sr=e=>e.join("/").replace(/\/\/+/g,"/"),vA=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),wA=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,xA=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e;class nc{constructor(t,n,r,i){i===void 0&&(i=!1),this.status=t,this.statusText=n||"",this.internal=i,r instanceof Error?(this.data=r.toString(),this.error=r):this.data=r}}function Qa(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}const e1=["post","put","patch","delete"],SA=new Set(e1),bA=["get",...e1],EA=new Set(bA),CA=new Set([301,302,303,307,308]),_A=new Set([307,308]),Qf={state:"idle",location:void 0,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0},kA={state:"idle",data:void 0,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0},Wo={state:"unblocked",proceed:void 0,reset:void 0,location:void 0},fm=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,PA=e=>({hasErrorBoundary:!!e.hasErrorBoundary}),t1="remix-router-transitions";function RA(e){const t=e.window?e.window:typeof window<"u"?window:void 0,n=typeof t<"u"&&typeof t.document<"u"&&typeof t.document.createElement<"u",r=!n;ce(e.routes.length>0,"You must provide a non-empty routes array to createRouter");let i;if(e.mapRouteProperties)i=e.mapRouteProperties;else if(e.detectErrorBoundary){let P=e.detectErrorBoundary;i=L=>({hasErrorBoundary:P(L)})}else i=PA;let s={},o=tc(e.routes,i,void 0,s),a,l=e.basename||"/",u=e.dataStrategy||IA,f=e.patchRoutesOnNavigation,c=De({v7_fetcherPersist:!1,v7_normalizeFormMethod:!1,v7_partialHydration:!1,v7_prependBasename:!1,v7_relativeSplatPath:!1,v7_skipActionErrorRevalidation:!1},e.future),d=null,h=new Set,g=null,v=null,x=null,m=e.hydrationData!=null,p=Mi(o,e.history.location,l),w=!1,S=null;if(p==null&&!f){let P=jt(404,{pathname:e.history.location.pathname}),{matches:L,route:N}=ev(o);p=L,S={[N.id]:P}}p&&!e.hydrationData&&vl(p,o,e.history.location.pathname).active&&(p=null);let k;if(p)if(p.some(P=>P.route.lazy))k=!1;else if(!p.some(P=>P.route.loader))k=!0;else if(c.v7_partialHydration){let P=e.hydrationData?e.hydrationData.loaderData:null,L=e.hydrationData?e.hydrationData.errors:null;if(L){let N=p.findIndex($=>L[$.route.id]!==void 0);k=p.slice(0,N+1).every($=>!kh($.route,P,L))}else k=p.every(N=>!kh(N.route,P,L))}else k=e.hydrationData!=null;else if(k=!1,p=[],c.v7_partialHydration){let P=vl(null,o,e.history.location.pathname);P.active&&P.matches&&(w=!0,p=P.matches)}let E,y={historyAction:e.history.action,location:e.history.location,matches:p,initialized:k,navigation:Qf,restoreScrollPosition:e.hydrationData!=null?!1:null,preventScrollReset:!1,revalidation:"idle",loaderData:e.hydrationData&&e.hydrationData.loaderData||{},actionData:e.hydrationData&&e.hydrationData.actionData||null,errors:e.hydrationData&&e.hydrationData.errors||S,fetchers:new Map,blockers:new Map},R=Ye.Pop,T=!1,A,O=!1,I=new Map,z=null,B=!1,V=!1,G=[],Q=new Set,M=new Map,U=0,b=-1,Z=new Map,pe=new Set,_=new Map,Ae=new Map,Le=new Set,ye=new Map,qe=new Map,vt;function xn(){if(d=e.history.listen(P=>{let{action:L,location:N,delta:$}=P;if(vt){vt(),vt=void 0;return}yo(qe.size===0||$!=null,"You are trying to use a blocker on a POP navigation to a location that was not created by @remix-run/router. This will fail silently in production. This can happen if you are navigating outside the router via `window.history.pushState`/`window.location.hash` instead of using router navigation APIs. This can also happen if you are using createHashRouter and the user manually changes the URL.");let W=sg({currentLocation:y.location,nextLocation:N,historyAction:L});if(W&&$!=null){let ne=new Promise(oe=>{vt=oe});e.history.go($*-1),yl(W,{state:"blocked",location:N,proceed(){yl(W,{state:"proceeding",proceed:void 0,reset:void 0,location:N}),ne.then(()=>e.history.go($))},reset(){let oe=new Map(y.blockers);oe.set(W,Wo),Ge({blockers:oe})}});return}return on(L,N)}),n){QA(t,I);let P=()=>KA(t,I);t.addEventListener("pagehide",P),z=()=>t.removeEventListener("pagehide",P)}return y.initialized||on(Ye.Pop,y.location,{initialHydration:!0}),E}function Sn(){d&&d(),z&&z(),h.clear(),A&&A.abort(),y.fetchers.forEach((P,L)=>wt(L)),y.blockers.forEach((P,L)=>an(L))}function dr(P){return h.add(P),()=>h.delete(P)}function Ge(P,L){L===void 0&&(L={}),y=De({},y,P);let N=[],$=[];c.v7_fetcherPersist&&y.fetchers.forEach((W,ne)=>{W.state==="idle"&&(Le.has(ne)?$.push(ne):N.push(ne))}),Le.forEach(W=>{!y.fetchers.has(W)&&!M.has(W)&&$.push(W)}),[...h].forEach(W=>W(y,{deletedFetchers:$,viewTransitionOpts:L.viewTransitionOpts,flushSync:L.flushSync===!0})),c.v7_fetcherPersist?(N.forEach(W=>y.fetchers.delete(W)),$.forEach(W=>wt(W))):$.forEach(W=>Le.delete(W))}function Ft(P,L,N){var $,W;let{flushSync:ne}=N===void 0?{}:N,oe=y.actionData!=null&&y.navigation.formMethod!=null&&Tn(y.navigation.formMethod)&&y.navigation.state==="loading"&&(($=P.state)==null?void 0:$._isRedirect)!==!0,J;L.actionData?Object.keys(L.actionData).length>0?J=L.actionData:J=null:oe?J=y.actionData:J=null;let X=L.loaderData?Yy(y.loaderData,L.loaderData,L.matches||[],L.errors):y.loaderData,q=y.blockers;q.size>0&&(q=new Map(q),q.forEach((ve,ct)=>q.set(ct,Wo)));let ee=T===!0||y.navigation.formMethod!=null&&Tn(y.navigation.formMethod)&&((W=P.state)==null?void 0:W._isRedirect)!==!0;a&&(o=a,a=void 0),B||R===Ye.Pop||(R===Ye.Push?e.history.push(P,P.state):R===Ye.Replace&&e.history.replace(P,P.state));let fe;if(R===Ye.Pop){let ve=I.get(y.location.pathname);ve&&ve.has(P.pathname)?fe={currentLocation:y.location,nextLocation:P}:I.has(P.pathname)&&(fe={currentLocation:P,nextLocation:y.location})}else if(O){let ve=I.get(y.location.pathname);ve?ve.add(P.pathname):(ve=new Set([P.pathname]),I.set(y.location.pathname,ve)),fe={currentLocation:y.location,nextLocation:P}}Ge(De({},L,{actionData:J,loaderData:X,historyAction:R,location:P,initialized:!0,navigation:Qf,revalidation:"idle",restoreScrollPosition:ag(P,L.matches||y.matches),preventScrollReset:ee,blockers:q}),{viewTransitionOpts:fe,flushSync:ne===!0}),R=Ye.Pop,T=!1,O=!1,B=!1,V=!1,G=[]}async function Ri(P,L){if(typeof P=="number"){e.history.go(P);return}let N=_h(y.location,y.matches,l,c.v7_prependBasename,P,c.v7_relativeSplatPath,L==null?void 0:L.fromRouteId,L==null?void 0:L.relative),{path:$,submission:W,error:ne}=Vy(c.v7_normalizeFormMethod,!1,N,L),oe=y.location,J=Wa(y.location,$,L&&L.state);J=De({},J,e.history.encodeLocation(J));let X=L&&L.replace!=null?L.replace:void 0,q=Ye.Push;X===!0?q=Ye.Replace:X===!1||W!=null&&Tn(W.formMethod)&&W.formAction===y.location.pathname+y.location.search&&(q=Ye.Replace);let ee=L&&"preventScrollReset"in L?L.preventScrollReset===!0:void 0,fe=(L&&L.flushSync)===!0,ve=sg({currentLocation:oe,nextLocation:J,historyAction:q});if(ve){yl(ve,{state:"blocked",location:J,proceed(){yl(ve,{state:"proceeding",proceed:void 0,reset:void 0,location:J}),Ri(P,L)},reset(){let ct=new Map(y.blockers);ct.set(ve,Wo),Ge({blockers:ct})}});return}return await on(q,J,{submission:W,pendingError:ne,preventScrollReset:ee,replace:L&&L.replace,enableViewTransition:L&&L.viewTransition,flushSync:fe})}function us(){if(H(),Ge({revalidation:"loading"}),y.navigation.state!=="submitting"){if(y.navigation.state==="idle"){on(y.historyAction,y.location,{startUninterruptedRevalidation:!0});return}on(R||y.historyAction,y.navigation.location,{overrideNavigation:y.navigation,enableViewTransition:O===!0})}}async function on(P,L,N){A&&A.abort(),A=null,R=P,B=(N&&N.startUninterruptedRevalidation)===!0,oE(y.location,y.matches),T=(N&&N.preventScrollReset)===!0,O=(N&&N.enableViewTransition)===!0;let $=a||o,W=N&&N.overrideNavigation,ne=N!=null&&N.initialHydration&&y.matches&&y.matches.length>0&&!w?y.matches:Mi($,L,l),oe=(N&&N.flushSync)===!0;if(ne&&y.initialized&&!V&&$A(y.location,L)&&!(N&&N.submission&&Tn(N.submission.formMethod))){Ft(L,{matches:ne},{flushSync:oe});return}let J=vl(ne,$,L.pathname);if(J.active&&J.matches&&(ne=J.matches),!ne){let{error:Te,notFoundMatches:be,route:He}=ff(L.pathname);Ft(L,{matches:be,loaderData:{},errors:{[He.id]:Te}},{flushSync:oe});return}A=new AbortController;let X=ms(e.history,L,A.signal,N&&N.submission),q;if(N&&N.pendingError)q=[Ni(ne).route.id,{type:ke.error,error:N.pendingError}];else if(N&&N.submission&&Tn(N.submission.formMethod)){let Te=await cs(X,L,N.submission,ne,J.active,{replace:N.replace,flushSync:oe});if(Te.shortCircuited)return;if(Te.pendingActionResult){let[be,He]=Te.pendingActionResult;if(Xt(He)&&Qa(He.error)&&He.error.status===404){A=null,Ft(L,{matches:Te.matches,loaderData:{},errors:{[be]:He.error}});return}}ne=Te.matches||ne,q=Te.pendingActionResult,W=Kf(L,N.submission),oe=!1,J.active=!1,X=ms(e.history,X.url,X.signal)}let{shortCircuited:ee,matches:fe,loaderData:ve,errors:ct}=await Oo(X,L,ne,J.active,W,N&&N.submission,N&&N.fetcherSubmission,N&&N.replace,N&&N.initialHydration===!0,oe,q);ee||(A=null,Ft(L,De({matches:fe||ne},Zy(q),{loaderData:ve,errors:ct})))}async function cs(P,L,N,$,W,ne){ne===void 0&&(ne={}),H();let oe=VA(L,N);if(Ge({navigation:oe},{flushSync:ne.flushSync===!0}),W){let q=await wl($,L.pathname,P.signal);if(q.type==="aborted")return{shortCircuited:!0};if(q.type==="error"){let ee=Ni(q.partialMatches).route.id;return{matches:q.partialMatches,pendingActionResult:[ee,{type:ke.error,error:q.error}]}}else if(q.matches)$=q.matches;else{let{notFoundMatches:ee,error:fe,route:ve}=ff(L.pathname);return{matches:ee,pendingActionResult:[ve.id,{type:ke.error,error:fe}]}}}let J,X=ta($,L);if(!X.route.action&&!X.route.lazy)J={type:ke.error,error:jt(405,{method:P.method,pathname:L.pathname,routeId:X.route.id})};else if(J=(await Ai("action",y,P,[X],$,null))[X.route.id],P.signal.aborted)return{shortCircuited:!0};if(zi(J)){let q;return ne&&ne.replace!=null?q=ne.replace:q=Jy(J.response.headers.get("Location"),new URL(P.url),l)===y.location.pathname+y.location.search,await hr(P,J,!0,{submission:N,replace:q}),{shortCircuited:!0}}if(ii(J))throw jt(400,{type:"defer-action"});if(Xt(J)){let q=Ni($,X.route.id);return(ne&&ne.replace)!==!0&&(R=Ye.Push),{matches:$,pendingActionResult:[q.route.id,J]}}return{matches:$,pendingActionResult:[X.route.id,J]}}async function Oo(P,L,N,$,W,ne,oe,J,X,q,ee){let fe=W||Kf(L,ne),ve=ne||oe||nv(fe),ct=!B&&(!c.v7_partialHydration||!X);if($){if(ct){let Ve=Un(ee);Ge(De({navigation:fe},Ve!==void 0?{actionData:Ve}:{}),{flushSync:q})}let xe=await wl(N,L.pathname,P.signal);if(xe.type==="aborted")return{shortCircuited:!0};if(xe.type==="error"){let Ve=Ni(xe.partialMatches).route.id;return{matches:xe.partialMatches,loaderData:{},errors:{[Ve]:xe.error}}}else if(xe.matches)N=xe.matches;else{let{error:Ve,notFoundMatches:ds,route:Mo}=ff(L.pathname);return{matches:ds,loaderData:{},errors:{[Mo.id]:Ve}}}}let Te=a||o,[be,He]=Qy(e.history,y,N,ve,L,c.v7_partialHydration&&X===!0,c.v7_skipActionErrorRevalidation,V,G,Q,Le,_,pe,Te,l,ee);if(df(xe=>!(N&&N.some(Ve=>Ve.route.id===xe))||be&&be.some(Ve=>Ve.route.id===xe)),b=++U,be.length===0&&He.length===0){let xe=Fr();return Ft(L,De({matches:N,loaderData:{},errors:ee&&Xt(ee[1])?{[ee[0]]:ee[1].error}:null},Zy(ee),xe?{fetchers:new Map(y.fetchers)}:{}),{flushSync:q}),{shortCircuited:!0}}if(ct){let xe={};if(!$){xe.navigation=fe;let Ve=Un(ee);Ve!==void 0&&(xe.actionData=Ve)}He.length>0&&(xe.fetchers=gl(He)),Ge(xe,{flushSync:q})}He.forEach(xe=>{it(xe.key),xe.controller&&M.set(xe.key,xe.controller)});let fs=()=>He.forEach(xe=>it(xe.key));A&&A.signal.addEventListener("abort",fs);let{loaderResults:Io,fetcherResults:mr}=await F(y,N,be,He,P);if(P.signal.aborted)return{shortCircuited:!0};A&&A.signal.removeEventListener("abort",fs),He.forEach(xe=>M.delete(xe.key));let Bn=Hl(Io);if(Bn)return await hr(P,Bn.result,!0,{replace:J}),{shortCircuited:!0};if(Bn=Hl(mr),Bn)return pe.add(Bn.key),await hr(P,Bn.result,!0,{replace:J}),{shortCircuited:!0};let{loaderData:hf,errors:Lo}=Xy(y,N,Io,ee,He,mr,ye);ye.forEach((xe,Ve)=>{xe.subscribe(ds=>{(ds||xe.done)&&ye.delete(Ve)})}),c.v7_partialHydration&&X&&y.errors&&(Lo=De({},y.errors,Lo));let Ti=Fr(),xl=xt(b),Sl=Ti||xl||He.length>0;return De({matches:N,loaderData:hf,errors:Lo},Sl?{fetchers:new Map(y.fetchers)}:{})}function Un(P){if(P&&!Xt(P[1]))return{[P[0]]:P[1].data};if(y.actionData)return Object.keys(y.actionData).length===0?null:y.actionData}function gl(P){return P.forEach(L=>{let N=y.fetchers.get(L.key),$=Qo(void 0,N?N.data:void 0);y.fetchers.set(L.key,$)}),new Map(y.fetchers)}function lf(P,L,N,$){if(r)throw new Error("router.fetch() was called during the server render, but it shouldn't be. You are likely calling a useFetcher() method in the body of your component. Try moving it to a useEffect or a callback.");it(P);let W=($&&$.flushSync)===!0,ne=a||o,oe=_h(y.location,y.matches,l,c.v7_prependBasename,N,c.v7_relativeSplatPath,L,$==null?void 0:$.relative),J=Mi(ne,oe,l),X=vl(J,ne,oe);if(X.active&&X.matches&&(J=X.matches),!J){ae(P,L,jt(404,{pathname:oe}),{flushSync:W});return}let{path:q,submission:ee,error:fe}=Vy(c.v7_normalizeFormMethod,!0,oe,$);if(fe){ae(P,L,fe,{flushSync:W});return}let ve=ta(J,q),ct=($&&$.preventScrollReset)===!0;if(ee&&Tn(ee.formMethod)){uf(P,L,q,ve,J,X.active,W,ct,ee);return}_.set(P,{routeId:L,path:q}),cf(P,L,q,ve,J,X.active,W,ct,ee)}async function uf(P,L,N,$,W,ne,oe,J,X){H(),_.delete(P);function q(Xe){if(!Xe.route.action&&!Xe.route.lazy){let hs=jt(405,{method:X.formMethod,pathname:N,routeId:L});return ae(P,L,hs,{flushSync:oe}),!0}return!1}if(!ne&&q($))return;let ee=y.fetchers.get(P);re(P,WA(X,ee),{flushSync:oe});let fe=new AbortController,ve=ms(e.history,N,fe.signal,X);if(ne){let Xe=await wl(W,new URL(ve.url).pathname,ve.signal,P);if(Xe.type==="aborted")return;if(Xe.type==="error"){ae(P,L,Xe.error,{flushSync:oe});return}else if(Xe.matches){if(W=Xe.matches,$=ta(W,N),q($))return}else{ae(P,L,jt(404,{pathname:N}),{flushSync:oe});return}}M.set(P,fe);let ct=U,be=(await Ai("action",y,ve,[$],W,P))[$.route.id];if(ve.signal.aborted){M.get(P)===fe&&M.delete(P);return}if(c.v7_fetcherPersist&&Le.has(P)){if(zi(be)||Xt(be)){re(P,Qr(void 0));return}}else{if(zi(be))if(M.delete(P),b>ct){re(P,Qr(void 0));return}else return pe.add(P),re(P,Qo(X)),hr(ve,be,!1,{fetcherSubmission:X,preventScrollReset:J});if(Xt(be)){ae(P,L,be.error);return}}if(ii(be))throw jt(400,{type:"defer-action"});let He=y.navigation.location||y.location,fs=ms(e.history,He,fe.signal),Io=a||o,mr=y.navigation.state!=="idle"?Mi(Io,y.navigation.location,l):y.matches;ce(mr,"Didn't find any matches after fetcher action");let Bn=++U;Z.set(P,Bn);let hf=Qo(X,be.data);y.fetchers.set(P,hf);let[Lo,Ti]=Qy(e.history,y,mr,X,He,!1,c.v7_skipActionErrorRevalidation,V,G,Q,Le,_,pe,Io,l,[$.route.id,be]);Ti.filter(Xe=>Xe.key!==P).forEach(Xe=>{let hs=Xe.key,lg=y.fetchers.get(hs),uE=Qo(void 0,lg?lg.data:void 0);y.fetchers.set(hs,uE),it(hs),Xe.controller&&M.set(hs,Xe.controller)}),Ge({fetchers:new Map(y.fetchers)});let xl=()=>Ti.forEach(Xe=>it(Xe.key));fe.signal.addEventListener("abort",xl);let{loaderResults:Sl,fetcherResults:xe}=await F(y,mr,Lo,Ti,fs);if(fe.signal.aborted)return;fe.signal.removeEventListener("abort",xl),Z.delete(P),M.delete(P),Ti.forEach(Xe=>M.delete(Xe.key));let Ve=Hl(Sl);if(Ve)return hr(fs,Ve.result,!1,{preventScrollReset:J});if(Ve=Hl(xe),Ve)return pe.add(Ve.key),hr(fs,Ve.result,!1,{preventScrollReset:J});let{loaderData:ds,errors:Mo}=Xy(y,mr,Sl,void 0,Ti,xe,ye);if(y.fetchers.has(P)){let Xe=Qr(be.data);y.fetchers.set(P,Xe)}xt(Bn),y.navigation.state==="loading"&&Bn>b?(ce(R,"Expected pending action"),A&&A.abort(),Ft(y.navigation.location,{matches:mr,loaderData:ds,errors:Mo,fetchers:new Map(y.fetchers)})):(Ge({errors:Mo,loaderData:Yy(y.loaderData,ds,mr,Mo),fetchers:new Map(y.fetchers)}),V=!1)}async function cf(P,L,N,$,W,ne,oe,J,X){let q=y.fetchers.get(P);re(P,Qo(X,q?q.data:void 0),{flushSync:oe});let ee=new AbortController,fe=ms(e.history,N,ee.signal);if(ne){let be=await wl(W,new URL(fe.url).pathname,fe.signal,P);if(be.type==="aborted")return;if(be.type==="error"){ae(P,L,be.error,{flushSync:oe});return}else if(be.matches)W=be.matches,$=ta(W,N);else{ae(P,L,jt(404,{pathname:N}),{flushSync:oe});return}}M.set(P,ee);let ve=U,Te=(await Ai("loader",y,fe,[$],W,P))[$.route.id];if(ii(Te)&&(Te=await dm(Te,fe.signal,!0)||Te),M.get(P)===ee&&M.delete(P),!fe.signal.aborted){if(Le.has(P)){re(P,Qr(void 0));return}if(zi(Te))if(b>ve){re(P,Qr(void 0));return}else{pe.add(P),await hr(fe,Te,!1,{preventScrollReset:J});return}if(Xt(Te)){ae(P,L,Te.error);return}ce(!ii(Te),"Unhandled fetcher deferred data"),re(P,Qr(Te.data))}}async function hr(P,L,N,$){let{submission:W,fetcherSubmission:ne,preventScrollReset:oe,replace:J}=$===void 0?{}:$;L.response.headers.has("X-Remix-Revalidate")&&(V=!0);let X=L.response.headers.get("Location");ce(X,"Expected a Location header on the redirect Response"),X=Jy(X,new URL(P.url),l);let q=Wa(y.location,X,{_isRedirect:!0});if(n){let be=!1;if(L.response.headers.has("X-Remix-Reload-Document"))be=!0;else if(fm.test(X)){const He=e.history.createURL(X);be=He.origin!==t.location.origin||xi(He.pathname,l)==null}if(be){J?t.location.replace(X):t.location.assign(X);return}}A=null;let ee=J===!0||L.response.headers.has("X-Remix-Replace")?Ye.Replace:Ye.Push,{formMethod:fe,formAction:ve,formEncType:ct}=y.navigation;!W&&!ne&&fe&&ve&&ct&&(W=nv(y.navigation));let Te=W||ne;if(_A.has(L.response.status)&&Te&&Tn(Te.formMethod))await on(ee,q,{submission:De({},Te,{formAction:X}),preventScrollReset:oe||T,enableViewTransition:N?O:void 0});else{let be=Kf(q,W);await on(ee,q,{overrideNavigation:be,fetcherSubmission:ne,preventScrollReset:oe||T,enableViewTransition:N?O:void 0})}}async function Ai(P,L,N,$,W,ne){let oe,J={};try{oe=await LA(u,P,L,N,$,W,ne,s,i)}catch(X){return $.forEach(q=>{J[q.route.id]={type:ke.error,error:X}}),J}for(let[X,q]of Object.entries(oe))if(jA(q)){let ee=q.result;J[X]={type:ke.redirect,response:FA(ee,N,X,W,l,c.v7_relativeSplatPath)}}else J[X]=await NA(q);return J}async function F(P,L,N,$,W){let ne=P.matches,oe=Ai("loader",P,W,N,L,null),J=Promise.all($.map(async ee=>{if(ee.matches&&ee.match&&ee.controller){let ve=(await Ai("loader",P,ms(e.history,ee.path,ee.controller.signal),[ee.match],ee.matches,ee.key))[ee.match.route.id];return{[ee.key]:ve}}else return Promise.resolve({[ee.key]:{type:ke.error,error:jt(404,{pathname:ee.path})}})})),X=await oe,q=(await J).reduce((ee,fe)=>Object.assign(ee,fe),{});return await Promise.all([BA(L,X,W.signal,ne,P.loaderData),HA(L,q,$)]),{loaderResults:X,fetcherResults:q}}function H(){V=!0,G.push(...df()),_.forEach((P,L)=>{M.has(L)&&Q.add(L),it(L)})}function re(P,L,N){N===void 0&&(N={}),y.fetchers.set(P,L),Ge({fetchers:new Map(y.fetchers)},{flushSync:(N&&N.flushSync)===!0})}function ae(P,L,N,$){$===void 0&&($={});let W=Ni(y.matches,L);wt(P),Ge({errors:{[W.route.id]:N},fetchers:new Map(y.fetchers)},{flushSync:($&&$.flushSync)===!0})}function _e(P){return Ae.set(P,(Ae.get(P)||0)+1),Le.has(P)&&Le.delete(P),y.fetchers.get(P)||kA}function wt(P){let L=y.fetchers.get(P);M.has(P)&&!(L&&L.state==="loading"&&Z.has(P))&&it(P),_.delete(P),Z.delete(P),pe.delete(P),c.v7_fetcherPersist&&Le.delete(P),Q.delete(P),y.fetchers.delete(P)}function pr(P){let L=(Ae.get(P)||0)-1;L<=0?(Ae.delete(P),Le.add(P),c.v7_fetcherPersist||wt(P)):Ae.set(P,L),Ge({fetchers:new Map(y.fetchers)})}function it(P){let L=M.get(P);L&&(L.abort(),M.delete(P))}function Nr(P){for(let L of P){let N=_e(L),$=Qr(N.data);y.fetchers.set(L,$)}}function Fr(){let P=[],L=!1;for(let N of pe){let $=y.fetchers.get(N);ce($,"Expected fetcher: "+N),$.state==="loading"&&(pe.delete(N),P.push(N),L=!0)}return Nr(P),L}function xt(P){let L=[];for(let[N,$]of Z)if($0}function Dr(P,L){let N=y.blockers.get(P)||Wo;return qe.get(P)!==L&&qe.set(P,L),N}function an(P){y.blockers.delete(P),qe.delete(P)}function yl(P,L){let N=y.blockers.get(P)||Wo;ce(N.state==="unblocked"&&L.state==="blocked"||N.state==="blocked"&&L.state==="blocked"||N.state==="blocked"&&L.state==="proceeding"||N.state==="blocked"&&L.state==="unblocked"||N.state==="proceeding"&&L.state==="unblocked","Invalid blocker state transition: "+N.state+" -> "+L.state);let $=new Map(y.blockers);$.set(P,L),Ge({blockers:$})}function sg(P){let{currentLocation:L,nextLocation:N,historyAction:$}=P;if(qe.size===0)return;qe.size>1&&yo(!1,"A router only supports one blocker at a time");let W=Array.from(qe.entries()),[ne,oe]=W[W.length-1],J=y.blockers.get(ne);if(!(J&&J.state==="proceeding")&&oe({currentLocation:L,nextLocation:N,historyAction:$}))return ne}function ff(P){let L=jt(404,{pathname:P}),N=a||o,{matches:$,route:W}=ev(N);return df(),{notFoundMatches:$,route:W,error:L}}function df(P){let L=[];return ye.forEach((N,$)=>{(!P||P($))&&(N.cancel(),L.push($),ye.delete($))}),L}function sE(P,L,N){if(g=P,x=L,v=N||null,!m&&y.navigation===Qf){m=!0;let $=ag(y.location,y.matches);$!=null&&Ge({restoreScrollPosition:$})}return()=>{g=null,x=null,v=null}}function og(P,L){return v&&v(P,L.map($=>rA($,y.loaderData)))||P.key}function oE(P,L){if(g&&x){let N=og(P,L);g[N]=x()}}function ag(P,L){if(g){let N=og(P,L),$=g[N];if(typeof $=="number")return $}return null}function vl(P,L,N){if(f)if(P){if(Object.keys(P[0].params).length>0)return{active:!0,matches:gu(L,N,l,!0)}}else return{active:!0,matches:gu(L,N,l,!0)||[]};return{active:!1,matches:null}}async function wl(P,L,N,$){if(!f)return{type:"success",matches:P};let W=P;for(;;){let ne=a==null,oe=a||o,J=s;try{await f({signal:N,path:L,matches:W,fetcherKey:$,patch:(ee,fe)=>{N.aborted||qy(ee,fe,oe,J,i)}})}catch(ee){return{type:"error",error:ee,partialMatches:W}}finally{ne&&!N.aborted&&(o=[...o])}if(N.aborted)return{type:"aborted"};let X=Mi(oe,L,l);if(X)return{type:"success",matches:X};let q=gu(oe,L,l,!0);if(!q||W.length===q.length&&W.every((ee,fe)=>ee.route.id===q[fe].route.id))return{type:"success",matches:null};W=q}}function aE(P){s={},a=tc(P,i,void 0,s)}function lE(P,L){let N=a==null;qy(P,L,a||o,s,i),N&&(o=[...o],Ge({}))}return E={get basename(){return l},get future(){return c},get state(){return y},get routes(){return o},get window(){return t},initialize:xn,subscribe:dr,enableScrollRestoration:sE,navigate:Ri,fetch:lf,revalidate:us,createHref:P=>e.history.createHref(P),encodeLocation:P=>e.history.encodeLocation(P),getFetcher:_e,deleteFetcher:pr,dispose:Sn,getBlocker:Dr,deleteBlocker:an,patchRoutes:lE,_internalFetchControllers:M,_internalActiveDeferreds:ye,_internalSetRoutes:aE},E}function AA(e){return e!=null&&("formData"in e&&e.formData!=null||"body"in e&&e.body!==void 0)}function _h(e,t,n,r,i,s,o,a){let l,u;if(o){l=[];for(let c of t)if(l.push(c),c.route.id===o){u=c;break}}else l=t,u=t[t.length-1];let f=Bc(i||".",Uc(l,s),xi(e.pathname,n)||e.pathname,a==="path");if(i==null&&(f.search=e.search,f.hash=e.hash),(i==null||i===""||i===".")&&u){let c=hm(f.search);if(u.route.index&&!c)f.search=f.search?f.search.replace(/^\?/,"?index&"):"?index";else if(!u.route.index&&c){let d=new URLSearchParams(f.search),h=d.getAll("index");d.delete("index"),h.filter(v=>v).forEach(v=>d.append("index",v));let g=d.toString();f.search=g?"?"+g:""}}return r&&n!=="/"&&(f.pathname=f.pathname==="/"?n:sr([n,f.pathname])),wi(f)}function Vy(e,t,n,r){if(!r||!AA(r))return{path:n};if(r.formMethod&&!UA(r.formMethod))return{path:n,error:jt(405,{method:r.formMethod})};let i=()=>({path:n,error:jt(400,{type:"invalid-body"})}),s=r.formMethod||"get",o=e?s.toUpperCase():s.toLowerCase(),a=i1(n);if(r.body!==void 0){if(r.formEncType==="text/plain"){if(!Tn(o))return i();let d=typeof r.body=="string"?r.body:r.body instanceof FormData||r.body instanceof URLSearchParams?Array.from(r.body.entries()).reduce((h,g)=>{let[v,x]=g;return""+h+v+"="+x+` +`},""):String(r.body);return{path:n,submission:{formMethod:o,formAction:a,formEncType:r.formEncType,formData:void 0,json:void 0,text:d}}}else if(r.formEncType==="application/json"){if(!Tn(o))return i();try{let d=typeof r.body=="string"?JSON.parse(r.body):r.body;return{path:n,submission:{formMethod:o,formAction:a,formEncType:r.formEncType,formData:void 0,json:d,text:void 0}}}catch{return i()}}}ce(typeof FormData=="function","FormData is not available in this environment");let l,u;if(r.formData)l=Ph(r.formData),u=r.formData;else if(r.body instanceof FormData)l=Ph(r.body),u=r.body;else if(r.body instanceof URLSearchParams)l=r.body,u=Gy(l);else if(r.body==null)l=new URLSearchParams,u=new FormData;else try{l=new URLSearchParams(r.body),u=Gy(l)}catch{return i()}let f={formMethod:o,formAction:a,formEncType:r&&r.formEncType||"application/x-www-form-urlencoded",formData:u,json:void 0,text:void 0};if(Tn(f.formMethod))return{path:n,submission:f};let c=Ci(n);return t&&c.search&&hm(c.search)&&l.append("index",""),c.search="?"+l,{path:wi(c),submission:f}}function Wy(e,t,n){n===void 0&&(n=!1);let r=e.findIndex(i=>i.route.id===t);return r>=0?e.slice(0,n?r+1:r):e}function Qy(e,t,n,r,i,s,o,a,l,u,f,c,d,h,g,v){let x=v?Xt(v[1])?v[1].error:v[1].data:void 0,m=e.createURL(t.location),p=e.createURL(i),w=n;s&&t.errors?w=Wy(n,Object.keys(t.errors)[0],!0):v&&Xt(v[1])&&(w=Wy(n,v[0]));let S=v?v[1].statusCode:void 0,k=o&&S&&S>=400,E=w.filter((R,T)=>{let{route:A}=R;if(A.lazy)return!0;if(A.loader==null)return!1;if(s)return kh(A,t.loaderData,t.errors);if(TA(t.loaderData,t.matches[T],R)||l.some(z=>z===R.route.id))return!0;let O=t.matches[T],I=R;return Ky(R,De({currentUrl:m,currentParams:O.params,nextUrl:p,nextParams:I.params},r,{actionResult:x,actionStatus:S,defaultShouldRevalidate:k?!1:a||m.pathname+m.search===p.pathname+p.search||m.search!==p.search||n1(O,I)}))}),y=[];return c.forEach((R,T)=>{if(s||!n.some(B=>B.route.id===R.routeId)||f.has(T))return;let A=Mi(h,R.path,g);if(!A){y.push({key:T,routeId:R.routeId,path:R.path,matches:null,match:null,controller:null});return}let O=t.fetchers.get(T),I=ta(A,R.path),z=!1;d.has(T)?z=!1:u.has(T)?(u.delete(T),z=!0):O&&O.state!=="idle"&&O.data===void 0?z=a:z=Ky(I,De({currentUrl:m,currentParams:t.matches[t.matches.length-1].params,nextUrl:p,nextParams:n[n.length-1].params},r,{actionResult:x,actionStatus:S,defaultShouldRevalidate:k?!1:a})),z&&y.push({key:T,routeId:R.routeId,path:R.path,matches:A,match:I,controller:new AbortController})}),[E,y]}function kh(e,t,n){if(e.lazy)return!0;if(!e.loader)return!1;let r=t!=null&&t[e.id]!==void 0,i=n!=null&&n[e.id]!==void 0;return!r&&i?!1:typeof e.loader=="function"&&e.loader.hydrate===!0?!0:!r&&!i}function TA(e,t,n){let r=!t||n.route.id!==t.route.id,i=e[n.route.id]===void 0;return r||i}function n1(e,t){let n=e.route.path;return e.pathname!==t.pathname||n!=null&&n.endsWith("*")&&e.params["*"]!==t.params["*"]}function Ky(e,t){if(e.route.shouldRevalidate){let n=e.route.shouldRevalidate(t);if(typeof n=="boolean")return n}return t.defaultShouldRevalidate}function qy(e,t,n,r,i){var s;let o;if(e){let u=r[e];ce(u,"No route found to patch children into: routeId = "+e),u.children||(u.children=[]),o=u.children}else o=n;let a=t.filter(u=>!o.some(f=>r1(u,f))),l=tc(a,i,[e||"_","patch",String(((s=o)==null?void 0:s.length)||"0")],r);o.push(...l)}function r1(e,t){return"id"in e&&"id"in t&&e.id===t.id?!0:e.index===t.index&&e.path===t.path&&e.caseSensitive===t.caseSensitive?(!e.children||e.children.length===0)&&(!t.children||t.children.length===0)?!0:e.children.every((n,r)=>{var i;return(i=t.children)==null?void 0:i.some(s=>r1(n,s))}):!1}async function OA(e,t,n){if(!e.lazy)return;let r=await e.lazy();if(!e.lazy)return;let i=n[e.id];ce(i,"No route found in manifest");let s={};for(let o in r){let l=i[o]!==void 0&&o!=="hasErrorBoundary";yo(!l,'Route "'+i.id+'" has a static property "'+o+'" defined but its lazy function is also returning a value for this property. '+('The lazy route property "'+o+'" will be ignored.')),!l&&!tA.has(o)&&(s[o]=r[o])}Object.assign(i,s),Object.assign(i,De({},t(i),{lazy:void 0}))}async function IA(e){let{matches:t}=e,n=t.filter(i=>i.shouldLoad);return(await Promise.all(n.map(i=>i.resolve()))).reduce((i,s,o)=>Object.assign(i,{[n[o].route.id]:s}),{})}async function LA(e,t,n,r,i,s,o,a,l,u){let f=s.map(h=>h.route.lazy?OA(h.route,l,a):void 0),c=s.map((h,g)=>{let v=f[g],x=i.some(p=>p.route.id===h.route.id);return De({},h,{shouldLoad:x,resolve:async p=>(p&&r.method==="GET"&&(h.route.lazy||h.route.loader)&&(x=!0),x?MA(t,r,h,v,p,u):Promise.resolve({type:ke.data,result:void 0}))})}),d=await e({matches:c,request:r,params:s[0].params,fetcherKey:o,context:u});try{await Promise.all(f)}catch{}return d}async function MA(e,t,n,r,i,s){let o,a,l=u=>{let f,c=new Promise((g,v)=>f=v);a=()=>f(),t.signal.addEventListener("abort",a);let d=g=>typeof u!="function"?Promise.reject(new Error("You cannot call the handler for a route which defines a boolean "+('"'+e+'" [routeId: '+n.route.id+"]"))):u({request:t,params:n.params,context:s},...g!==void 0?[g]:[]),h=(async()=>{try{return{type:"data",result:await(i?i(v=>d(v)):d())}}catch(g){return{type:"error",result:g}}})();return Promise.race([h,c])};try{let u=n.route[e];if(r)if(u){let f,[c]=await Promise.all([l(u).catch(d=>{f=d}),r]);if(f!==void 0)throw f;o=c}else if(await r,u=n.route[e],u)o=await l(u);else if(e==="action"){let f=new URL(t.url),c=f.pathname+f.search;throw jt(405,{method:t.method,pathname:c,routeId:n.route.id})}else return{type:ke.data,result:void 0};else if(u)o=await l(u);else{let f=new URL(t.url),c=f.pathname+f.search;throw jt(404,{pathname:c})}ce(o.result!==void 0,"You defined "+(e==="action"?"an action":"a loader")+" for route "+('"'+n.route.id+"\" but didn't return anything from your `"+e+"` ")+"function. Please return a value or `null`.")}catch(u){return{type:ke.error,result:u}}finally{a&&t.signal.removeEventListener("abort",a)}return o}async function NA(e){let{result:t,type:n}=e;if(s1(t)){let c;try{let d=t.headers.get("Content-Type");d&&/\bapplication\/json\b/.test(d)?t.body==null?c=null:c=await t.json():c=await t.text()}catch(d){return{type:ke.error,error:d}}return n===ke.error?{type:ke.error,error:new nc(t.status,t.statusText,c),statusCode:t.status,headers:t.headers}:{type:ke.data,data:c,statusCode:t.status,headers:t.headers}}if(n===ke.error){if(tv(t)){var r,i;if(t.data instanceof Error){var s,o;return{type:ke.error,error:t.data,statusCode:(s=t.init)==null?void 0:s.status,headers:(o=t.init)!=null&&o.headers?new Headers(t.init.headers):void 0}}return{type:ke.error,error:new nc(((r=t.init)==null?void 0:r.status)||500,void 0,t.data),statusCode:Qa(t)?t.status:void 0,headers:(i=t.init)!=null&&i.headers?new Headers(t.init.headers):void 0}}return{type:ke.error,error:t,statusCode:Qa(t)?t.status:void 0}}if(zA(t)){var a,l;return{type:ke.deferred,deferredData:t,statusCode:(a=t.init)==null?void 0:a.status,headers:((l=t.init)==null?void 0:l.headers)&&new Headers(t.init.headers)}}if(tv(t)){var u,f;return{type:ke.data,data:t.data,statusCode:(u=t.init)==null?void 0:u.status,headers:(f=t.init)!=null&&f.headers?new Headers(t.init.headers):void 0}}return{type:ke.data,data:t}}function FA(e,t,n,r,i,s){let o=e.headers.get("Location");if(ce(o,"Redirects returned/thrown from loaders/actions must have a Location header"),!fm.test(o)){let a=r.slice(0,r.findIndex(l=>l.route.id===n)+1);o=_h(new URL(t.url),a,i,!0,o,s),e.headers.set("Location",o)}return e}function Jy(e,t,n){if(fm.test(e)){let r=e,i=r.startsWith("//")?new URL(t.protocol+r):new URL(r),s=xi(i.pathname,n)!=null;if(i.origin===t.origin&&s)return i.pathname+i.search+i.hash}return e}function ms(e,t,n,r){let i=e.createURL(i1(t)).toString(),s={signal:n};if(r&&Tn(r.formMethod)){let{formMethod:o,formEncType:a}=r;s.method=o.toUpperCase(),a==="application/json"?(s.headers=new Headers({"Content-Type":a}),s.body=JSON.stringify(r.json)):a==="text/plain"?s.body=r.text:a==="application/x-www-form-urlencoded"&&r.formData?s.body=Ph(r.formData):s.body=r.formData}return new Request(i,s)}function Ph(e){let t=new URLSearchParams;for(let[n,r]of e.entries())t.append(n,typeof r=="string"?r:r.name);return t}function Gy(e){let t=new FormData;for(let[n,r]of e.entries())t.append(n,r);return t}function DA(e,t,n,r,i){let s={},o=null,a,l=!1,u={},f=n&&Xt(n[1])?n[1].error:void 0;return e.forEach(c=>{if(!(c.route.id in t))return;let d=c.route.id,h=t[d];if(ce(!zi(h),"Cannot handle redirect results in processLoaderData"),Xt(h)){let g=h.error;f!==void 0&&(g=f,f=void 0),o=o||{};{let v=Ni(e,d);o[v.route.id]==null&&(o[v.route.id]=g)}s[d]=void 0,l||(l=!0,a=Qa(h.error)?h.error.status:500),h.headers&&(u[d]=h.headers)}else ii(h)?(r.set(d,h.deferredData),s[d]=h.deferredData.data,h.statusCode!=null&&h.statusCode!==200&&!l&&(a=h.statusCode),h.headers&&(u[d]=h.headers)):(s[d]=h.data,h.statusCode&&h.statusCode!==200&&!l&&(a=h.statusCode),h.headers&&(u[d]=h.headers))}),f!==void 0&&n&&(o={[n[0]]:f},s[n[0]]=void 0),{loaderData:s,errors:o,statusCode:a||200,loaderHeaders:u}}function Xy(e,t,n,r,i,s,o){let{loaderData:a,errors:l}=DA(t,n,r,o);return i.forEach(u=>{let{key:f,match:c,controller:d}=u,h=s[f];if(ce(h,"Did not find corresponding fetcher result"),!(d&&d.signal.aborted))if(Xt(h)){let g=Ni(e.matches,c==null?void 0:c.route.id);l&&l[g.route.id]||(l=De({},l,{[g.route.id]:h.error})),e.fetchers.delete(f)}else if(zi(h))ce(!1,"Unhandled fetcher revalidation redirect");else if(ii(h))ce(!1,"Unhandled fetcher deferred data");else{let g=Qr(h.data);e.fetchers.set(f,g)}}),{loaderData:a,errors:l}}function Yy(e,t,n,r){let i=De({},t);for(let s of n){let o=s.route.id;if(t.hasOwnProperty(o)?t[o]!==void 0&&(i[o]=t[o]):e[o]!==void 0&&s.route.loader&&(i[o]=e[o]),r&&r.hasOwnProperty(o))break}return i}function Zy(e){return e?Xt(e[1])?{actionData:{}}:{actionData:{[e[0]]:e[1].data}}:{}}function Ni(e,t){return(t?e.slice(0,e.findIndex(r=>r.route.id===t)+1):[...e]).reverse().find(r=>r.route.hasErrorBoundary===!0)||e[0]}function ev(e){let t=e.length===1?e[0]:e.find(n=>n.index||!n.path||n.path==="/")||{id:"__shim-error-route__"};return{matches:[{params:{},pathname:"",pathnameBase:"",route:t}],route:t}}function jt(e,t){let{pathname:n,routeId:r,method:i,type:s,message:o}=t===void 0?{}:t,a="Unknown Server Error",l="Unknown @remix-run/router error";return e===400?(a="Bad Request",i&&n&&r?l="You made a "+i+' request to "'+n+'" but '+('did not provide a `loader` for route "'+r+'", ')+"so there is no way to handle the request.":s==="defer-action"?l="defer() is not supported in actions":s==="invalid-body"&&(l="Unable to encode submission body")):e===403?(a="Forbidden",l='Route "'+r+'" does not match URL "'+n+'"'):e===404?(a="Not Found",l='No route matches URL "'+n+'"'):e===405&&(a="Method Not Allowed",i&&n&&r?l="You made a "+i.toUpperCase()+' request to "'+n+'" but '+('did not provide an `action` for route "'+r+'", ')+"so there is no way to handle the request.":i&&(l='Invalid request method "'+i.toUpperCase()+'"')),new nc(e||500,a,new Error(l),!0)}function Hl(e){let t=Object.entries(e);for(let n=t.length-1;n>=0;n--){let[r,i]=t[n];if(zi(i))return{key:r,result:i}}}function i1(e){let t=typeof e=="string"?Ci(e):e;return wi(De({},t,{hash:""}))}function $A(e,t){return e.pathname!==t.pathname||e.search!==t.search?!1:e.hash===""?t.hash!=="":e.hash===t.hash?!0:t.hash!==""}function jA(e){return s1(e.result)&&CA.has(e.result.status)}function ii(e){return e.type===ke.deferred}function Xt(e){return e.type===ke.error}function zi(e){return(e&&e.type)===ke.redirect}function tv(e){return typeof e=="object"&&e!=null&&"type"in e&&"data"in e&&"init"in e&&e.type==="DataWithResponseInit"}function zA(e){let t=e;return t&&typeof t=="object"&&typeof t.data=="object"&&typeof t.subscribe=="function"&&typeof t.cancel=="function"&&typeof t.resolveData=="function"}function s1(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.headers=="object"&&typeof e.body<"u"}function UA(e){return EA.has(e.toLowerCase())}function Tn(e){return SA.has(e.toLowerCase())}async function BA(e,t,n,r,i){let s=Object.entries(t);for(let o=0;o(d==null?void 0:d.route.id)===a);if(!u)continue;let f=r.find(d=>d.route.id===u.route.id),c=f!=null&&!n1(f,u)&&(i&&i[u.route.id])!==void 0;ii(l)&&c&&await dm(l,n,!1).then(d=>{d&&(t[a]=d)})}}async function HA(e,t,n){for(let r=0;r(u==null?void 0:u.route.id)===s)&&ii(a)&&(ce(o,"Expected an AbortController for revalidating fetcher deferred result"),await dm(a,o.signal,!0).then(u=>{u&&(t[i]=u)}))}}async function dm(e,t,n){if(n===void 0&&(n=!1),!await e.deferredData.resolveData(t)){if(n)try{return{type:ke.data,data:e.deferredData.unwrappedData}}catch(i){return{type:ke.error,error:i}}return{type:ke.data,data:e.deferredData.data}}}function hm(e){return new URLSearchParams(e).getAll("index").some(t=>t==="")}function ta(e,t){let n=typeof t=="string"?Ci(t).search:t.search;if(e[e.length-1].route.index&&hm(n||""))return e[e.length-1];let r=ZS(e);return r[r.length-1]}function nv(e){let{formMethod:t,formAction:n,formEncType:r,text:i,formData:s,json:o}=e;if(!(!t||!n||!r)){if(i!=null)return{formMethod:t,formAction:n,formEncType:r,formData:void 0,json:void 0,text:i};if(s!=null)return{formMethod:t,formAction:n,formEncType:r,formData:s,json:void 0,text:void 0};if(o!==void 0)return{formMethod:t,formAction:n,formEncType:r,formData:void 0,json:o,text:void 0}}}function Kf(e,t){return t?{state:"loading",location:e,formMethod:t.formMethod,formAction:t.formAction,formEncType:t.formEncType,formData:t.formData,json:t.json,text:t.text}:{state:"loading",location:e,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0}}function VA(e,t){return{state:"submitting",location:e,formMethod:t.formMethod,formAction:t.formAction,formEncType:t.formEncType,formData:t.formData,json:t.json,text:t.text}}function Qo(e,t){return e?{state:"loading",formMethod:e.formMethod,formAction:e.formAction,formEncType:e.formEncType,formData:e.formData,json:e.json,text:e.text,data:t}:{state:"loading",formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0,data:t}}function WA(e,t){return{state:"submitting",formMethod:e.formMethod,formAction:e.formAction,formEncType:e.formEncType,formData:e.formData,json:e.json,text:e.text,data:t?t.data:void 0}}function Qr(e){return{state:"idle",formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0,data:e}}function QA(e,t){try{let n=e.sessionStorage.getItem(t1);if(n){let r=JSON.parse(n);for(let[i,s]of Object.entries(r||{}))s&&Array.isArray(s)&&t.set(i,new Set(s||[]))}}catch{}}function KA(e,t){if(t.size>0){let n={};for(let[r,i]of t)n[r]=[...i];try{e.sessionStorage.setItem(t1,JSON.stringify(n))}catch(r){yo(!1,"Failed to save applied view transitions in sessionStorage ("+r+").")}}}/** * React Router v6.30.0 * * Copyright (c) Remix Software Inc. @@ -56,7 +56,7 @@ Error generating stack: `+s.message+` * LICENSE.md file in the root directory of this source tree. * * @license MIT - */function rc(){return rc=Object.assign?Object.assign.bind():function(e){for(var t=1;t{a.current=!0}),_.useCallback(function(u,f){if(f===void 0&&(f={}),!a.current)return;if(typeof u=="number"){r.go(u);return}let c=Bc(u,JSON.parse(o),s,f.relative==="path");e==null&&t!=="/"&&(c.pathname=c.pathname==="/"?t:sr([t,c.pathname])),(f.replace?r.replace:r.push)(c,f.state,f)},[t,r,o,s,e])}function L2(){let{matches:e}=_.useContext(cr),t=e[e.length-1];return t?t.params:{}}function gm(e,t){let{relative:n}=t===void 0?{}:t,{future:r}=_.useContext(ur),{matches:i}=_.useContext(cr),{pathname:s}=as(),o=JSON.stringify(Uc(i,r.v7_relativeSplatPath));return _.useMemo(()=>Bc(e,JSON.parse(o),s,n==="path"),[e,o,s,n])}function GA(e,t,n,r){ko()||ce(!1);let{navigator:i,static:s}=_.useContext(ur),{matches:o}=_.useContext(cr),a=o[o.length-1],l=a?a.params:{};a&&a.pathname;let u=a?a.pathnameBase:"/";a&&a.route;let f=as(),c;c=f;let d=c.pathname||"/",h=d;if(u!=="/"){let x=u.replace(/^\//,"").split("/");h="/"+d.replace(/^\//,"").split("/").slice(x.length).join("/")}let g=!s&&n&&n.matches&&n.matches.length>0?n.matches:Mi(e,{pathname:h});return tT(g&&g.map(x=>Object.assign({},x,{params:Object.assign({},l,x.params),pathname:sr([u,i.encodeLocation?i.encodeLocation(x.pathname).pathname:x.pathname]),pathnameBase:x.pathnameBase==="/"?u:sr([u,i.encodeLocation?i.encodeLocation(x.pathnameBase).pathname:x.pathnameBase])})),o,n,r)}function XA(){let e=oT(),t=Qa(e)?e.status+" "+e.statusText:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,i={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return _.createElement(_.Fragment,null,_.createElement("h2",null,"Unexpected Application Error!"),_.createElement("h3",{style:{fontStyle:"italic"}},t),n?_.createElement("pre",{style:i},n):null,null)}const YA=_.createElement(XA,null);class ZA extends _.Component{constructor(t){super(t),this.state={location:t.location,revalidation:t.revalidation,error:t.error}}static getDerivedStateFromError(t){return{error:t}}static getDerivedStateFromProps(t,n){return n.location!==t.location||n.revalidation!=="idle"&&t.revalidation==="idle"?{error:t.error,location:t.location,revalidation:t.revalidation}:{error:t.error!==void 0?t.error:n.error,location:n.location,revalidation:t.revalidation||n.revalidation}}componentDidCatch(t,n){console.error("React Router caught the following error during render",t,n)}render(){return this.state.error!==void 0?_.createElement(cr.Provider,{value:this.props.routeContext},_.createElement(a1.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function eT(e){let{routeContext:t,match:n,children:r}=e,i=_.useContext(al);return i&&i.static&&i.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(i.staticContext._deepestRenderedBoundaryId=n.route.id),_.createElement(cr.Provider,{value:t},r)}function tT(e,t,n,r){var i;if(t===void 0&&(t=[]),n===void 0&&(n=null),r===void 0&&(r=null),e==null){var s;if(!n)return null;if(n.errors)e=n.matches;else if((s=r)!=null&&s.v7_partialHydration&&t.length===0&&!n.initialized&&n.matches.length>0)e=n.matches;else return null}let o=e,a=(i=n)==null?void 0:i.errors;if(a!=null){let f=o.findIndex(c=>c.route.id&&(a==null?void 0:a[c.route.id])!==void 0);f>=0||ce(!1),o=o.slice(0,Math.min(o.length,f+1))}let l=!1,u=-1;if(n&&r&&r.v7_partialHydration)for(let f=0;f=0?o=o.slice(0,u+1):o=[o[0]];break}}}return o.reduceRight((f,c,d)=>{let h,g=!1,v=null,x=null;n&&(h=a&&c.route.id?a[c.route.id]:void 0,v=c.route.errorElement||YA,l&&(u<0&&d===0?(lT("route-fallback"),g=!0,x=null):u===d&&(g=!0,x=c.route.hydrateFallbackElement||null)));let m=t.concat(o.slice(0,d+1)),p=()=>{let w;return h?w=v:g?w=x:c.route.Component?w=_.createElement(c.route.Component,null):c.route.element?w=c.route.element:w=f,_.createElement(eT,{match:c,routeContext:{outlet:f,matches:m,isDataRoute:n!=null},children:w})};return n&&(c.route.ErrorBoundary||c.route.errorElement||d===0)?_.createElement(ZA,{location:n.location,revalidation:n.revalidation,component:v,error:h,children:p(),routeContext:{outlet:null,matches:m,isDataRoute:!0}}):p()},null)}var u1=function(e){return e.UseBlocker="useBlocker",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e}(u1||{}),c1=function(e){return e.UseBlocker="useBlocker",e.UseLoaderData="useLoaderData",e.UseActionData="useActionData",e.UseRouteError="useRouteError",e.UseNavigation="useNavigation",e.UseRouteLoaderData="useRouteLoaderData",e.UseMatches="useMatches",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e.UseRouteId="useRouteId",e}(c1||{});function nT(e){let t=_.useContext(al);return t||ce(!1),t}function rT(e){let t=_.useContext(o1);return t||ce(!1),t}function iT(e){let t=_.useContext(cr);return t||ce(!1),t}function ym(e){let t=iT(),n=t.matches[t.matches.length-1];return n.route.id||ce(!1),n.route.id}function sT(){return ym()}function oT(){var e;let t=_.useContext(a1),n=rT(),r=ym();return t!==void 0?t:(e=n.errors)==null?void 0:e[r]}function aT(){let{router:e}=nT(u1.UseNavigateStable),t=ym(c1.UseNavigateStable),n=_.useRef(!1);return l1(()=>{n.current=!0}),_.useCallback(function(i,s){s===void 0&&(s={}),n.current&&(typeof i=="number"?e.navigate(i):e.navigate(i,rc({fromRouteId:t},s)))},[e,t])}const rv={};function lT(e,t,n){rv[e]||(rv[e]=!0)}function uT(e,t){e==null||e.v7_startTransition,(e==null?void 0:e.v7_relativeSplatPath)===void 0&&(!t||t.v7_relativeSplatPath),t&&(t.v7_fetcherPersist,t.v7_normalizeFormMethod,t.v7_partialHydration,t.v7_skipActionErrorRevalidation)}function cT(e){let{to:t,replace:n,state:r,relative:i}=e;ko()||ce(!1);let{future:s,static:o}=_.useContext(ur),{matches:a}=_.useContext(cr),{pathname:l}=as(),u=mm(),f=Bc(t,Uc(a,s.v7_relativeSplatPath),l,i==="path"),c=JSON.stringify(f);return _.useEffect(()=>u(JSON.parse(c),{replace:n,state:r,relative:i}),[u,c,i,n,r]),null}function na(e){ce(!1)}function fT(e){let{basename:t="/",children:n=null,location:r,navigationType:i=Ye.Pop,navigator:s,static:o=!1,future:a}=e;ko()&&ce(!1);let l=t.replace(/^\/*/,"/"),u=_.useMemo(()=>({basename:l,navigator:s,static:o,future:rc({v7_relativeSplatPath:!1},a)}),[l,a,s,o]);typeof r=="string"&&(r=_i(r));let{pathname:f="/",search:c="",hash:d="",state:h=null,key:g="default"}=r,v=_.useMemo(()=>{let x=xi(f,l);return x==null?null:{location:{pathname:x,search:c,hash:d,state:h,key:g},navigationType:i}},[l,f,c,d,h,g,i]);return v==null?null:_.createElement(ur.Provider,{value:u},_.createElement(pm.Provider,{children:n,value:v}))}new Promise(()=>{});function Rh(e,t){t===void 0&&(t=[]);let n=[];return _.Children.forEach(e,(r,i)=>{if(!_.isValidElement(r))return;let s=[...t,i];if(r.type===_.Fragment){n.push.apply(n,Rh(r.props.children,s));return}r.type!==na&&ce(!1),!r.props.index||!r.props.children||ce(!1);let o={id:r.props.id||s.join("-"),caseSensitive:r.props.caseSensitive,element:r.props.element,Component:r.props.Component,index:r.props.index,path:r.props.path,loader:r.props.loader,action:r.props.action,errorElement:r.props.errorElement,ErrorBoundary:r.props.ErrorBoundary,hasErrorBoundary:r.props.ErrorBoundary!=null||r.props.errorElement!=null,shouldRevalidate:r.props.shouldRevalidate,handle:r.props.handle,lazy:r.props.lazy};r.props.children&&(o.children=Rh(r.props.children,s)),n.push(o)}),n}function dT(e){let t={hasErrorBoundary:e.ErrorBoundary!=null||e.errorElement!=null};return e.Component&&Object.assign(t,{element:_.createElement(e.Component),Component:void 0}),e.HydrateFallback&&Object.assign(t,{hydrateFallbackElement:_.createElement(e.HydrateFallback),HydrateFallback:void 0}),e.ErrorBoundary&&Object.assign(t,{errorElement:_.createElement(e.ErrorBoundary),ErrorBoundary:void 0}),t}/** + */function rc(){return rc=Object.assign?Object.assign.bind():function(e){for(var t=1;t{a.current=!0}),C.useCallback(function(u,f){if(f===void 0&&(f={}),!a.current)return;if(typeof u=="number"){r.go(u);return}let c=Bc(u,JSON.parse(o),s,f.relative==="path");e==null&&t!=="/"&&(c.pathname=c.pathname==="/"?t:sr([t,c.pathname])),(f.replace?r.replace:r.push)(c,f.state,f)},[t,r,o,s,e])}function MD(){let{matches:e}=C.useContext(cr),t=e[e.length-1];return t?t.params:{}}function gm(e,t){let{relative:n}=t===void 0?{}:t,{future:r}=C.useContext(ur),{matches:i}=C.useContext(cr),{pathname:s}=as(),o=JSON.stringify(Uc(i,r.v7_relativeSplatPath));return C.useMemo(()=>Bc(e,JSON.parse(o),s,n==="path"),[e,o,s,n])}function GA(e,t,n,r){ko()||ce(!1);let{navigator:i,static:s}=C.useContext(ur),{matches:o}=C.useContext(cr),a=o[o.length-1],l=a?a.params:{};a&&a.pathname;let u=a?a.pathnameBase:"/";a&&a.route;let f=as(),c;c=f;let d=c.pathname||"/",h=d;if(u!=="/"){let x=u.replace(/^\//,"").split("/");h="/"+d.replace(/^\//,"").split("/").slice(x.length).join("/")}let g=!s&&n&&n.matches&&n.matches.length>0?n.matches:Mi(e,{pathname:h});return tT(g&&g.map(x=>Object.assign({},x,{params:Object.assign({},l,x.params),pathname:sr([u,i.encodeLocation?i.encodeLocation(x.pathname).pathname:x.pathname]),pathnameBase:x.pathnameBase==="/"?u:sr([u,i.encodeLocation?i.encodeLocation(x.pathnameBase).pathname:x.pathnameBase])})),o,n,r)}function XA(){let e=oT(),t=Qa(e)?e.status+" "+e.statusText:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,i={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return C.createElement(C.Fragment,null,C.createElement("h2",null,"Unexpected Application Error!"),C.createElement("h3",{style:{fontStyle:"italic"}},t),n?C.createElement("pre",{style:i},n):null,null)}const YA=C.createElement(XA,null);class ZA extends C.Component{constructor(t){super(t),this.state={location:t.location,revalidation:t.revalidation,error:t.error}}static getDerivedStateFromError(t){return{error:t}}static getDerivedStateFromProps(t,n){return n.location!==t.location||n.revalidation!=="idle"&&t.revalidation==="idle"?{error:t.error,location:t.location,revalidation:t.revalidation}:{error:t.error!==void 0?t.error:n.error,location:n.location,revalidation:t.revalidation||n.revalidation}}componentDidCatch(t,n){console.error("React Router caught the following error during render",t,n)}render(){return this.state.error!==void 0?C.createElement(cr.Provider,{value:this.props.routeContext},C.createElement(a1.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function eT(e){let{routeContext:t,match:n,children:r}=e,i=C.useContext(al);return i&&i.static&&i.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(i.staticContext._deepestRenderedBoundaryId=n.route.id),C.createElement(cr.Provider,{value:t},r)}function tT(e,t,n,r){var i;if(t===void 0&&(t=[]),n===void 0&&(n=null),r===void 0&&(r=null),e==null){var s;if(!n)return null;if(n.errors)e=n.matches;else if((s=r)!=null&&s.v7_partialHydration&&t.length===0&&!n.initialized&&n.matches.length>0)e=n.matches;else return null}let o=e,a=(i=n)==null?void 0:i.errors;if(a!=null){let f=o.findIndex(c=>c.route.id&&(a==null?void 0:a[c.route.id])!==void 0);f>=0||ce(!1),o=o.slice(0,Math.min(o.length,f+1))}let l=!1,u=-1;if(n&&r&&r.v7_partialHydration)for(let f=0;f=0?o=o.slice(0,u+1):o=[o[0]];break}}}return o.reduceRight((f,c,d)=>{let h,g=!1,v=null,x=null;n&&(h=a&&c.route.id?a[c.route.id]:void 0,v=c.route.errorElement||YA,l&&(u<0&&d===0?(lT("route-fallback"),g=!0,x=null):u===d&&(g=!0,x=c.route.hydrateFallbackElement||null)));let m=t.concat(o.slice(0,d+1)),p=()=>{let w;return h?w=v:g?w=x:c.route.Component?w=C.createElement(c.route.Component,null):c.route.element?w=c.route.element:w=f,C.createElement(eT,{match:c,routeContext:{outlet:f,matches:m,isDataRoute:n!=null},children:w})};return n&&(c.route.ErrorBoundary||c.route.errorElement||d===0)?C.createElement(ZA,{location:n.location,revalidation:n.revalidation,component:v,error:h,children:p(),routeContext:{outlet:null,matches:m,isDataRoute:!0}}):p()},null)}var u1=function(e){return e.UseBlocker="useBlocker",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e}(u1||{}),c1=function(e){return e.UseBlocker="useBlocker",e.UseLoaderData="useLoaderData",e.UseActionData="useActionData",e.UseRouteError="useRouteError",e.UseNavigation="useNavigation",e.UseRouteLoaderData="useRouteLoaderData",e.UseMatches="useMatches",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e.UseRouteId="useRouteId",e}(c1||{});function nT(e){let t=C.useContext(al);return t||ce(!1),t}function rT(e){let t=C.useContext(o1);return t||ce(!1),t}function iT(e){let t=C.useContext(cr);return t||ce(!1),t}function ym(e){let t=iT(),n=t.matches[t.matches.length-1];return n.route.id||ce(!1),n.route.id}function sT(){return ym()}function oT(){var e;let t=C.useContext(a1),n=rT(),r=ym();return t!==void 0?t:(e=n.errors)==null?void 0:e[r]}function aT(){let{router:e}=nT(u1.UseNavigateStable),t=ym(c1.UseNavigateStable),n=C.useRef(!1);return l1(()=>{n.current=!0}),C.useCallback(function(i,s){s===void 0&&(s={}),n.current&&(typeof i=="number"?e.navigate(i):e.navigate(i,rc({fromRouteId:t},s)))},[e,t])}const rv={};function lT(e,t,n){rv[e]||(rv[e]=!0)}function uT(e,t){e==null||e.v7_startTransition,(e==null?void 0:e.v7_relativeSplatPath)===void 0&&(!t||t.v7_relativeSplatPath),t&&(t.v7_fetcherPersist,t.v7_normalizeFormMethod,t.v7_partialHydration,t.v7_skipActionErrorRevalidation)}function cT(e){let{to:t,replace:n,state:r,relative:i}=e;ko()||ce(!1);let{future:s,static:o}=C.useContext(ur),{matches:a}=C.useContext(cr),{pathname:l}=as(),u=mm(),f=Bc(t,Uc(a,s.v7_relativeSplatPath),l,i==="path"),c=JSON.stringify(f);return C.useEffect(()=>u(JSON.parse(c),{replace:n,state:r,relative:i}),[u,c,i,n,r]),null}function na(e){ce(!1)}function fT(e){let{basename:t="/",children:n=null,location:r,navigationType:i=Ye.Pop,navigator:s,static:o=!1,future:a}=e;ko()&&ce(!1);let l=t.replace(/^\/*/,"/"),u=C.useMemo(()=>({basename:l,navigator:s,static:o,future:rc({v7_relativeSplatPath:!1},a)}),[l,a,s,o]);typeof r=="string"&&(r=Ci(r));let{pathname:f="/",search:c="",hash:d="",state:h=null,key:g="default"}=r,v=C.useMemo(()=>{let x=xi(f,l);return x==null?null:{location:{pathname:x,search:c,hash:d,state:h,key:g},navigationType:i}},[l,f,c,d,h,g,i]);return v==null?null:C.createElement(ur.Provider,{value:u},C.createElement(pm.Provider,{children:n,value:v}))}new Promise(()=>{});function Rh(e,t){t===void 0&&(t=[]);let n=[];return C.Children.forEach(e,(r,i)=>{if(!C.isValidElement(r))return;let s=[...t,i];if(r.type===C.Fragment){n.push.apply(n,Rh(r.props.children,s));return}r.type!==na&&ce(!1),!r.props.index||!r.props.children||ce(!1);let o={id:r.props.id||s.join("-"),caseSensitive:r.props.caseSensitive,element:r.props.element,Component:r.props.Component,index:r.props.index,path:r.props.path,loader:r.props.loader,action:r.props.action,errorElement:r.props.errorElement,ErrorBoundary:r.props.ErrorBoundary,hasErrorBoundary:r.props.ErrorBoundary!=null||r.props.errorElement!=null,shouldRevalidate:r.props.shouldRevalidate,handle:r.props.handle,lazy:r.props.lazy};r.props.children&&(o.children=Rh(r.props.children,s)),n.push(o)}),n}function dT(e){let t={hasErrorBoundary:e.ErrorBoundary!=null||e.errorElement!=null};return e.Component&&Object.assign(t,{element:C.createElement(e.Component),Component:void 0}),e.HydrateFallback&&Object.assign(t,{hydrateFallbackElement:C.createElement(e.HydrateFallback),HydrateFallback:void 0}),e.ErrorBoundary&&Object.assign(t,{errorElement:C.createElement(e.ErrorBoundary),ErrorBoundary:void 0}),t}/** * React Router DOM v6.30.0 * * Copyright (c) Remix Software Inc. @@ -65,7 +65,7 @@ Error generating stack: `+s.message+` * LICENSE.md file in the root directory of this source tree. * * @license MIT - */function ns(){return ns=Object.assign?Object.assign.bind():function(e){for(var t=1;t=0)&&(n[i]=e[i]);return n}const yu="get",qf="application/x-www-form-urlencoded";function Hc(e){return e!=null&&typeof e.tagName=="string"}function hT(e){return Hc(e)&&e.tagName.toLowerCase()==="button"}function pT(e){return Hc(e)&&e.tagName.toLowerCase()==="form"}function mT(e){return Hc(e)&&e.tagName.toLowerCase()==="input"}function gT(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function yT(e,t){return e.button===0&&(!t||t==="_self")&&!gT(e)}function Ah(e){return e===void 0&&(e=""),new URLSearchParams(typeof e=="string"||Array.isArray(e)||e instanceof URLSearchParams?e:Object.keys(e).reduce((t,n)=>{let r=e[n];return t.concat(Array.isArray(r)?r.map(i=>[n,i]):[[n,r]])},[]))}function vT(e,t){let n=Ah(e);return t&&t.forEach((r,i)=>{n.has(i)||t.getAll(i).forEach(s=>{n.append(i,s)})}),n}let Vl=null;function wT(){if(Vl===null)try{new FormData(document.createElement("form"),0),Vl=!1}catch{Vl=!0}return Vl}const xT=new Set(["application/x-www-form-urlencoded","multipart/form-data","text/plain"]);function Jf(e){return e!=null&&!xT.has(e)?null:e}function ST(e,t){let n,r,i,s,o;if(pT(e)){let a=e.getAttribute("action");r=a?xi(a,t):null,n=e.getAttribute("method")||yu,i=Jf(e.getAttribute("enctype"))||qf,s=new FormData(e)}else if(hT(e)||mT(e)&&(e.type==="submit"||e.type==="image")){let a=e.form;if(a==null)throw new Error('Cannot submit a + + + + Connect GitHub Copilot + {isPending && ( + + Enter the code below on the GitHub device activation page. + + )} + + + {isPending && ( +
+ {/* Code rendered as plain text — never innerHTML */} +

+ {status.user_code} +

+ {/* Only the hardcoded, trusted GitHub URL is rendered as a link */} + + Open GitHub device activation + +
+ +
+
+ )} + + {isStartingState && ( +

+ Starting GitHub sign-in... +

+ )} + + {isError && ( +

+ {FIXED_ERROR_MESSAGE} +

+ )} +
+
+ + ) +} diff --git a/frontend/src/components/Prompt.tsx b/frontend/src/components/Prompt.tsx index c6d97eb5..bde34d9f 100644 --- a/frontend/src/components/Prompt.tsx +++ b/frontend/src/components/Prompt.tsx @@ -1,4 +1,5 @@ import { convert, createOrRefine, systemPrompt, type Action } from 'api/openai' +import { formatGenerationError } from 'api/errors' import { Tooltip, TooltipContent, TooltipTrigger } from 'components/ui/tooltip' import { useThrottle, useVersion } from 'hooks' import { useAtom, useAtomValue, useSetAtom } from 'jotai' @@ -166,7 +167,7 @@ export default function Prompt({ setScreenshot('') setLiveMarkdown('') console.error(error) - let { message } = error as Error + let message = formatGenerationError(error) // Ollama vision error if ( message.includes('Object of type bytes is not JSON serializable') diff --git a/frontend/src/components/Settings.tsx b/frontend/src/components/Settings.tsx index ebb66171..161f7bf6 100644 --- a/frontend/src/components/Settings.tsx +++ b/frontend/src/components/Settings.tsx @@ -1,5 +1,5 @@ -import { useQuery } from '@tanstack/react-query' -import { getModels } from 'api/models' +import { useQuery, useQueryClient } from '@tanstack/react-query' +import { findCopilotModel, getModels, supportsImages } from 'api/models' import { Button } from 'components/ui/button' import { Dialog, @@ -43,6 +43,7 @@ import { systemPromptAtom, temperatureAtom } from 'state' +import CopilotDeviceLogin from './CopilotDeviceLogin' import { Textarea } from './ui/textarea' function slugToNiceName(slug?: string, float = true) { @@ -76,6 +77,9 @@ export default function Settings({ trigger }: { trigger: JSX.Element }) { queryKey: ['models'], queryFn: getModels }) + const queryClient = useQueryClient() + const refreshModels = () => + void queryClient.invalidateQueries({ queryKey: ['models'] }) const [language, setLanguage] = useState(i18n.language) const [searchParams] = useSearchParams() const [model, setModel] = useAtom(modelAtom) @@ -94,6 +98,8 @@ export default function Settings({ trigger }: { trigger: JSX.Element }) { } }, [error]) + const selectedCopilotModel = data ? findCopilotModel(data, model) : undefined + // Default to another model if no OpenAI models are available useEffect(() => { if (searchParams.get('dummy')) { @@ -102,23 +108,30 @@ export default function Settings({ trigger }: { trigger: JSX.Element }) { `dummy/${available.includes(searchParams.get('dummy') ?? '') ? searchParams.get('dummy') : 'good'}` ) } else if (data && data.openai.length === 0 && model.startsWith('gpt')) { - if (data.groq.length > 0) { - // Defaulting to the 3rd model which is currently llama3-70b - setModel(`groq/${data.groq[2].id}`) - } else if (data.ollama.length > 0) { - setModel(`ollama/${data.ollama[0].model}`) - } else if (data.litellm.length > 0) { - setModel(`litellm/${data.litellm[0].id}`) + if (data.copilot.length > 0) { + setModel(data.copilot[0].id) + } else { + const preferredGroq = data.groq[2] ?? data.groq[0] + if (preferredGroq) { + setModel(`groq/${preferredGroq.id}`) + } else if (data.ollama.length > 0) { + setModel(`ollama/${data.ollama[0].model}`) + } else if (data.litellm.length > 0) { + setModel(`litellm/${data.litellm[0].id}`) + } } } + + const copilotVision = data ? supportsImages(data, model) : undefined const override = modelSupportsImagesOverrides[model] - if (override === undefined) { + if (copilotVision !== undefined) { + setModelSupportsImages(copilotVision) + } else if (override === undefined) { setModelSupportsImages( knownImageModels.some(regex => { - let cleanName = model - if (cleanName.includes('/')) { - cleanName = model.split('/').slice(1).join('/') - } + const cleanName = model.includes('/') + ? model.split('/').slice(1).join('/') + : model return regex.test(cleanName) }) ) @@ -171,7 +184,7 @@ export default function Settings({ trigger }: { trigger: JSX.Element }) { setModel(val) }} > - + {isPending ? ( @@ -205,6 +218,22 @@ export default function Settings({ trigger }: { trigger: JSX.Element }) { ))} )} + {data.copilot.length > 0 && ( + + GitHub Copilot + {data.copilot.map(copilotModel => ( + + {copilotModel.capabilities.vision && ( + + )} + {copilotModel.name} + + ))} + + )} {data.groq.length > 0 && ( Groq @@ -238,15 +267,43 @@ export default function Settings({ trigger }: { trigger: JSX.Element }) { ) : undefined} + {data?.copilotStatus.authMode === 'device' && + (data.copilotStatus.state === 'signed_out' || + data.copilotStatus.state === 'reauthenticate') && ( +
+ +
+ )} + {data?.copilotStatus.state === 'reauthenticate' && + data.copilotStatus.authMode !== 'device' && ( +
+ {data.copilotStatus.message}{' '} + + Reconnect GitHub + +
+ )} + {(data?.copilotStatus.state === 'no_entitlement' || + data?.copilotStatus.state === 'rate_limited' || + data?.copilotStatus.state === 'unavailable') && ( +
+ {data?.copilotStatus.message} +
+ )}
{ setModelSupportsImagesOverrides({ ...modelSupportsImagesOverrides, @@ -256,14 +313,20 @@ export default function Settings({ trigger }: { trigger: JSX.Element }) { onCheckedChange={checked => setModelSupportsImages(checked)} />
- We attempt to detect if the model has vision capabilities. You can - override this if you're sure it does. - {model === 'gpt-3.5-turbo' && ( - - {' '} - We'll automatically use gpt-4o for any requests with - images. - + {selectedCopilotModel ? ( + 'Vision capability is reported by GitHub Copilot.' + ) : ( + <> + We attempt to detect if the model has vision capabilities. You + can override this if you're sure it does. + {model === 'gpt-3.5-turbo' && ( + + {' '} + We'll automatically use gpt-4o for any requests with + images. + + )} + )}
diff --git a/frontend/src/components/__tests__/CopilotDeviceLogin.tsx b/frontend/src/components/__tests__/CopilotDeviceLogin.tsx new file mode 100644 index 00000000..27de95ce --- /dev/null +++ b/frontend/src/components/__tests__/CopilotDeviceLogin.tsx @@ -0,0 +1,429 @@ +import { http, HttpResponse } from 'msw' +import { render, screen, waitFor } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import server from 'mocks/server' +import CopilotDeviceLogin from '../CopilotDeviceLogin' +import type { DeviceAuthStatus } from 'api/copilot' + +const pendingStatus: DeviceAuthStatus = { + state: 'pending', + message: null, + verification_uri: 'https://github.com/login/device', + user_code: 'ABCD-EFGH', + expires_at: '2099-01-01T00:00:00Z' +} + +const authenticatedStatus: DeviceAuthStatus = { + state: 'authenticated', + message: null, + verification_uri: null, + user_code: null, + expires_at: null +} + +const cancelledStatus: DeviceAuthStatus = { + state: 'cancelled', + message: null, + verification_uri: null, + user_code: null, + expires_at: null +} + +const expiredStatus: DeviceAuthStatus = { + state: 'expired', + message: null, + verification_uri: null, + user_code: null, + expires_at: null +} + +const startingStatus: DeviceAuthStatus = { + state: 'starting', + message: 'Starting GitHub sign-in...', + verification_uri: null, + user_code: null, + expires_at: null +} + +describe('', () => { + beforeEach(() => { + // Only fake setInterval/clearInterval so the component's 2-second poll + // is controlled by vi.advanceTimersByTimeAsync while userEvent's internal + // setTimeout-based pointer delays keep using real timers. + vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] }) + }) + + afterEach(() => { + vi.useRealTimers() + }) + + it('shows the device code and refreshes models after authentication', async () => { + server.use( + http.post('/v1/copilot/device/start', () => + HttpResponse.json(pendingStatus) + ), + http.get('/v1/copilot/device/status', () => + HttpResponse.json(authenticatedStatus) + ) + ) + const onAuthenticated = vi.fn() + render() + await userEvent.click( + screen.getByRole('button', { name: 'Connect GitHub Copilot' }) + ) + expect(await screen.findByText('ABCD-EFGH')).toBeInTheDocument() + expect( + screen.getByRole('link', { name: 'Open GitHub device activation' }) + ).toHaveAttribute('href', 'https://github.com/login/device') + await vi.advanceTimersByTimeAsync(2000) + await waitFor(() => expect(onAuthenticated).toHaveBeenCalledOnce()) + }) + + it('keeps polling after a slow "starting" start and later renders the code', async () => { + server.use( + http.post('/v1/copilot/device/start', () => + HttpResponse.json(startingStatus) + ), + http.get('/v1/copilot/device/status', () => + HttpResponse.json(pendingStatus) + ) + ) + render() + await userEvent.click( + screen.getByRole('button', { name: 'Connect GitHub Copilot' }) + ) + // Non-error "starting" message is shown, not the fixed error message. + expect( + await screen.findByText('Starting GitHub sign-in...') + ).toBeInTheDocument() + expect( + screen.queryByText('GitHub Copilot connection could not be updated.') + ).not.toBeInTheDocument() + // Polling continues while "starting"; the next poll surfaces the code. + await vi.advanceTimersByTimeAsync(2000) + expect(await screen.findByText('ABCD-EFGH')).toBeInTheDocument() + }) + + it('does not treat "starting" as a terminal error state', async () => { + server.use( + http.post('/v1/copilot/device/start', () => + HttpResponse.json(startingStatus) + ), + http.get('/v1/copilot/device/status', () => + HttpResponse.json(startingStatus) + ) + ) + render() + await userEvent.click( + screen.getByRole('button', { name: 'Connect GitHub Copilot' }) + ) + expect( + await screen.findByText('Starting GitHub sign-in...') + ).toBeInTheDocument() + // Still starting after a poll — no error, still no code. + await vi.advanceTimersByTimeAsync(2000) + expect( + screen.queryByText('GitHub Copilot connection could not be updated.') + ).not.toBeInTheDocument() + expect(screen.getByText('Starting GitHub sign-in...')).toBeInTheDocument() + }) + + it('calls the cancel endpoint when the user cancels', async () => { + let cancelCalled = false + server.use( + http.post('/v1/copilot/device/start', () => + HttpResponse.json(pendingStatus) + ), + http.get('/v1/copilot/device/status', () => + HttpResponse.json(pendingStatus) + ), + http.post('/v1/copilot/device/cancel', () => { + cancelCalled = true + return HttpResponse.json(cancelledStatus) + }) + ) + + render() + await userEvent.click( + screen.getByRole('button', { name: 'Connect GitHub Copilot' }) + ) + expect(await screen.findByText('ABCD-EFGH')).toBeInTheDocument() + await userEvent.click(screen.getByRole('button', { name: 'Cancel' })) + await waitFor(() => expect(cancelCalled).toBe(true)) + expect(screen.queryByText('ABCD-EFGH')).not.toBeInTheDocument() + }) + + it('stops polling when the dialog close button is clicked', async () => { + let statusCallCount = 0 + server.use( + http.post('/v1/copilot/device/start', () => + HttpResponse.json(pendingStatus) + ), + http.get('/v1/copilot/device/status', () => { + statusCallCount++ + return HttpResponse.json(pendingStatus) + }) + ) + + render() + await userEvent.click( + screen.getByRole('button', { name: 'Connect GitHub Copilot' }) + ) + expect(await screen.findByText('ABCD-EFGH')).toBeInTheDocument() + + // First poll + await vi.advanceTimersByTimeAsync(2000) + await waitFor(() => expect(statusCallCount).toBe(1)) + + // Close dialog + await userEvent.click(screen.getByRole('button', { name: 'Close' })) + + // No more polls after close + await vi.advanceTimersByTimeAsync(4000) + expect(statusCallCount).toBe(1) + }) + + it('stops polling on unmount', async () => { + let statusCallCount = 0 + server.use( + http.post('/v1/copilot/device/start', () => + HttpResponse.json(pendingStatus) + ), + http.get('/v1/copilot/device/status', () => { + statusCallCount++ + return HttpResponse.json(pendingStatus) + }) + ) + + const { unmount } = render() + await userEvent.click( + screen.getByRole('button', { name: 'Connect GitHub Copilot' }) + ) + expect(await screen.findByText('ABCD-EFGH')).toBeInTheDocument() + + // First poll + await vi.advanceTimersByTimeAsync(2000) + await waitFor(() => expect(statusCallCount).toBe(1)) + + unmount() + + // No more polls after unmount + await vi.advanceTimersByTimeAsync(4000) + expect(statusCallCount).toBe(1) + }) + + it('shows a fixed error state when the device code expires', async () => { + server.use( + http.post('/v1/copilot/device/start', () => + HttpResponse.json(pendingStatus) + ), + http.get('/v1/copilot/device/status', () => + HttpResponse.json(expiredStatus) + ) + ) + + render() + await userEvent.click( + screen.getByRole('button', { name: 'Connect GitHub Copilot' }) + ) + expect(await screen.findByText('ABCD-EFGH')).toBeInTheDocument() + + await vi.advanceTimersByTimeAsync(2000) + await waitFor(() => + expect(screen.queryByText('ABCD-EFGH')).not.toBeInTheDocument() + ) + expect( + screen.getByText('GitHub Copilot connection could not be updated.') + ).toBeInTheDocument() + }) + + it('shows a fixed error state for unsupported_storage from start', async () => { + const unsupportedStatus: DeviceAuthStatus = { + state: 'unsupported_storage', + message: 'Raw server storage message', + verification_uri: null, + user_code: null, + expires_at: null + } + server.use( + http.post('/v1/copilot/device/start', () => + HttpResponse.json(unsupportedStatus) + ) + ) + + render() + await userEvent.click( + screen.getByRole('button', { name: 'Connect GitHub Copilot' }) + ) + + expect( + await screen.findByText('GitHub Copilot connection could not be updated.') + ).toBeInTheDocument() + // Must not reflect raw server message + expect( + screen.queryByText('Raw server storage message') + ).not.toBeInTheDocument() + }) + + it('shows a fixed error message when the start request returns non-2xx', async () => { + server.use( + http.post('/v1/copilot/device/start', () => + HttpResponse.json({ detail: 'raw server error' }, { status: 500 }) + ) + ) + + render() + await userEvent.click( + screen.getByRole('button', { name: 'Connect GitHub Copilot' }) + ) + + expect( + await screen.findByText('GitHub Copilot connection could not be updated.') + ).toBeInTheDocument() + expect(screen.queryByText('raw server error')).not.toBeInTheDocument() + }) + + it('does not poll after reaching a terminal state', async () => { + let statusCallCount = 0 + server.use( + http.post('/v1/copilot/device/start', () => + HttpResponse.json(pendingStatus) + ), + http.get('/v1/copilot/device/status', () => { + statusCallCount++ + return HttpResponse.json(cancelledStatus) + }) + ) + + render() + await userEvent.click( + screen.getByRole('button', { name: 'Connect GitHub Copilot' }) + ) + + // First poll reaches cancelled → terminal state + await vi.advanceTimersByTimeAsync(2000) + await waitFor(() => expect(statusCallCount).toBe(1)) + + // Advance again — must NOT trigger a second poll + await vi.advanceTimersByTimeAsync(4000) + expect(statusCallCount).toBe(1) + }) + + it('only renders the hardcoded GitHub URL, not an untrusted verification_uri', async () => { + const maliciousStatus: DeviceAuthStatus = { + state: 'pending', + message: null, + verification_uri: 'https://evil.example.com/device', + user_code: 'ABCD-EFGH', + expires_at: '2099-01-01T00:00:00Z' + } + server.use( + http.post('/v1/copilot/device/start', () => + HttpResponse.json(maliciousStatus) + ), + http.get('/v1/copilot/device/status', () => + HttpResponse.json(pendingStatus) + ) + ) + + render() + await userEvent.click( + screen.getByRole('button', { name: 'Connect GitHub Copilot' }) + ) + + // Unexpected URI → component replaces device flow with fixed failure state + expect( + await screen.findByText('GitHub Copilot connection could not be updated.') + ).toBeInTheDocument() + // The malicious link must never be rendered + expect( + screen.queryByRole('link', { name: 'Open GitHub device activation' }) + ).not.toBeInTheDocument() + expect( + screen.queryByText('https://evil.example.com/device') + ).not.toBeInTheDocument() + }) + + it('calls onAuthenticated exactly once on success', async () => { + server.use( + http.post('/v1/copilot/device/start', () => + HttpResponse.json(pendingStatus) + ), + http.get('/v1/copilot/device/status', () => + HttpResponse.json(authenticatedStatus) + ) + ) + const onAuthenticated = vi.fn() + render() + await userEvent.click( + screen.getByRole('button', { name: 'Connect GitHub Copilot' }) + ) + + await vi.advanceTimersByTimeAsync(2000) + await waitFor(() => expect(onAuthenticated).toHaveBeenCalledOnce()) + + // Advance more — must not call again + await vi.advanceTimersByTimeAsync(4000) + expect(onAuthenticated).toHaveBeenCalledOnce() + }) + + it('in-flight poll resolving after dialog close does not resurrect state or invoke onAuthenticated', async () => { + // This test exercises the race: the interval fires, the fetch starts + // (in-flight), the dialog is closed (cleanup: cancelled=true), then the + // fetch resolves. Without the cancellation flag the resolved .then() would + // call setStatus(pending) → restart the interval → eventually fire + // onAuthenticated. With the fix the guard must block all state/callback + // updates. + + let resolveInFlight!: () => void + const block = new Promise(resolve => { + resolveInFlight = resolve + }) + + server.use( + http.post('/v1/copilot/device/start', () => + HttpResponse.json(pendingStatus) + ), + // Async MSW handler: hangs until resolveInFlight() is called. + http.get('/v1/copilot/device/status', async () => { + await block + return HttpResponse.json(authenticatedStatus) + }) + ) + + const onAuthenticated = vi.fn() + render() + + await userEvent.click( + screen.getByRole('button', { name: 'Connect GitHub Copilot' }) + ) + expect(await screen.findByText('ABCD-EFGH')).toBeInTheDocument() + + // Synchronously fire the interval so the in-flight fetch starts but + // stays pending (MSW handler is blocked on `block`). + vi.advanceTimersByTime(2000) + + // Close the dialog while the fetch is still in-flight. + // Effect cleanup must run: cancelled = true, clearInterval. + await userEvent.click(screen.getByRole('button', { name: 'Close' })) + expect(screen.queryByText('ABCD-EFGH')).not.toBeInTheDocument() + + // Now unblock the fetch — it resolves with authenticatedStatus. + resolveInFlight() + // Wait a full event-loop turn so every microtask in the chain settles. + // setTimeout is NOT faked (only setInterval is), so this is a real delay. + await new Promise(resolve => { + setTimeout(resolve, 0) + }) + + // The cancellation guard must have prevented the callback and state update. + expect(onAuthenticated).not.toHaveBeenCalled() + + // Advancing the clock must not trigger a new poll. + vi.advanceTimersByTime(4000) + await new Promise(resolve => { + setTimeout(resolve, 0) + }) + expect(onAuthenticated).not.toHaveBeenCalled() + }) +}) diff --git a/frontend/src/components/__tests__/Settings.tsx b/frontend/src/components/__tests__/Settings.tsx new file mode 100644 index 00000000..e5b62082 --- /dev/null +++ b/frontend/src/components/__tests__/Settings.tsx @@ -0,0 +1,298 @@ +import { http, HttpResponse } from 'msw' +import { screen, waitFor } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { getDefaultStore } from 'jotai' +import server from 'mocks/server' +import renderWithProviders from 'testUtils' +import { + modelAtom, + modelSupportsImagesAtom, + modelSupportsImagesOverridesAtom +} from 'state' +import Settings from '../Settings' + +const catalog = { + models: { + openai: [], + groq: [], + ollama: [], + litellm: [], + copilot: [ + { + id: 'copilot/gpt-test', + name: 'GPT Test', + capabilities: { + vision: true, + supported_media_types: ['image/png'], + max_prompt_images: 1, + max_prompt_image_size: 1024 + } + } + ] + }, + copilot_status: { state: 'connected', message: null } +} + +describe(' Copilot', () => { + beforeEach(() => { + localStorage.clear() + const store = getDefaultStore() + store.set(modelAtom, 'gpt-3.5-turbo') + store.set(modelSupportsImagesAtom, false) + store.set(modelSupportsImagesOverridesAtom, {}) + }) + + it('prefers the first Copilot model when OpenAI is unavailable', async () => { + server.use(http.get('/v1/models', () => HttpResponse.json(catalog))) + const user = userEvent.setup() + renderWithProviders( + Open settings} /> + ) + + await user.click(screen.getByRole('button', { name: 'Open settings' })) + + await waitFor(() => { + expect(screen.getByRole('combobox', { name: 'Model' })).toHaveTextContent( + 'GPT Test' + ) + }) + }) + + it('lists Copilot models and marks provider vision metadata read-only', async () => { + server.use(http.get('/v1/models', () => HttpResponse.json(catalog))) + const user = userEvent.setup() + renderWithProviders( + Open settings} /> + ) + + await user.click(screen.getByRole('button', { name: 'Open settings' })) + await user.click(screen.getByRole('combobox', { name: 'Model' })) + + expect(await screen.findByText('GitHub Copilot')).toBeInTheDocument() + expect(screen.getByRole('option', { name: 'GPT Test' })).toBeInTheDocument() + + await user.click(screen.getByRole('option', { name: 'GPT Test' })) + expect( + screen.getByRole('switch', { name: 'Supports Vision' }) + ).toBeChecked() + expect( + screen.getByRole('switch', { name: 'Supports Vision' }) + ).toBeDisabled() + expect( + screen.getByText('Vision capability is reported by GitHub Copilot.') + ).toBeInTheDocument() + }) + + it('shows a reconnect action for expired authentication', async () => { + server.use( + http.get('/v1/models', () => + HttpResponse.json({ + ...catalog, + models: { ...catalog.models, copilot: [] }, + copilot_status: { + state: 'reauthenticate', + message: 'Reconnect your GitHub account.' + } + }) + ) + ) + const user = userEvent.setup() + renderWithProviders( + Open settings} /> + ) + + await user.click(screen.getByRole('button', { name: 'Open settings' })) + + const reconnect = await screen.findByRole('link', { + name: 'Reconnect GitHub' + }) + expect(reconnect).toHaveAttribute('href', '/v1/login?redirect=%2Fai%2Fnew') + }) + + it.each([ + ['no_entitlement', 'This account has no Copilot entitlement.'], + ['rate_limited', 'The Copilot allowance has been reached.'], + ['unavailable', 'The local Copilot runtime is unavailable.'] + ])('shows the %s provider state', async (state, message) => { + server.use( + http.get('/v1/models', () => + HttpResponse.json({ + ...catalog, + models: { ...catalog.models, copilot: [] }, + copilot_status: { state, message } + }) + ) + ) + const user = userEvent.setup() + renderWithProviders( + Open settings} /> + ) + + await user.click(screen.getByRole('button', { name: 'Open settings' })) + + expect(await screen.findByText(message)).toBeInTheDocument() + }) +}) + +describe(' Device Mode', () => { + beforeEach(() => { + localStorage.clear() + const store = getDefaultStore() + store.set(modelAtom, 'gpt-3.5-turbo') + store.set(modelSupportsImagesAtom, false) + store.set(modelSupportsImagesOverridesAtom, {}) + }) + + it('renders the device login component when auth_mode is device and state is signed_out', async () => { + server.use( + http.get('/v1/models', () => + HttpResponse.json({ + models: { + openai: [], + groq: [], + ollama: [], + litellm: [], + copilot: [] + }, + copilot_status: { + state: 'signed_out', + message: null, + auth_mode: 'device' + } + }) + ) + ) + const user = userEvent.setup() + renderWithProviders( + Open settings} /> + ) + + await user.click(screen.getByRole('button', { name: 'Open settings' })) + + await waitFor(() => + expect( + screen.getByRole('button', { name: 'Connect GitHub Copilot' }) + ).toBeInTheDocument() + ) + }) + + it('renders the device login component when auth_mode is device and state is reauthenticate', async () => { + server.use( + http.get('/v1/models', () => + HttpResponse.json({ + models: { + openai: [], + groq: [], + ollama: [], + litellm: [], + copilot: [] + }, + copilot_status: { + state: 'reauthenticate', + message: 'Please reconnect.', + auth_mode: 'device' + } + }) + ) + ) + const user = userEvent.setup() + renderWithProviders( + Open settings} /> + ) + + await user.click(screen.getByRole('button', { name: 'Open settings' })) + + await waitFor(() => + expect( + screen.getByRole('button', { name: 'Connect GitHub Copilot' }) + ).toBeInTheDocument() + ) + // Must NOT show the OAuth reconnect link + expect( + screen.queryByRole('link', { name: 'Reconnect GitHub' }) + ).not.toBeInTheDocument() + }) + + it('keeps the OAuth reconnect link when auth_mode is not device', async () => { + server.use( + http.get('/v1/models', () => + HttpResponse.json({ + models: { + openai: [], + groq: [], + ollama: [], + litellm: [], + copilot: [] + }, + copilot_status: { + state: 'reauthenticate', + message: 'Reconnect your GitHub account.' + // no auth_mode → OAuth + } + }) + ) + ) + const user = userEvent.setup() + renderWithProviders( + Open settings} /> + ) + + await user.click(screen.getByRole('button', { name: 'Open settings' })) + + const reconnect = await screen.findByRole('link', { + name: 'Reconnect GitHub' + }) + expect(reconnect).toHaveAttribute('href', '/v1/login?redirect=%2Fai%2Fnew') + expect( + screen.queryByRole('button', { name: 'Connect GitHub Copilot' }) + ).not.toBeInTheDocument() + }) + + it('lists models normally when connected in device mode', async () => { + server.use( + http.get('/v1/models', () => + HttpResponse.json({ + models: { + openai: [], + groq: [], + ollama: [], + litellm: [], + copilot: [ + { + id: 'copilot/gpt-device', + name: 'GPT Device', + capabilities: { + vision: false, + supported_media_types: [], + max_prompt_images: null, + max_prompt_image_size: null + } + } + ] + }, + copilot_status: { + state: 'connected', + message: null, + auth_mode: 'device' + } + }) + ) + ) + const user = userEvent.setup() + renderWithProviders( + Open settings} /> + ) + + await user.click(screen.getByRole('button', { name: 'Open settings' })) + await user.click(screen.getByRole('combobox', { name: 'Model' })) + + expect(await screen.findByText('GitHub Copilot')).toBeInTheDocument() + expect( + screen.getByRole('option', { name: 'GPT Device' }) + ).toBeInTheDocument() + // No device login button when connected + expect( + screen.queryByRole('button', { name: 'Connect GitHub Copilot' }) + ).not.toBeInTheDocument() + }) +}) diff --git a/frontend/src/lib/__tests__/preloadRecovery.ts b/frontend/src/lib/__tests__/preloadRecovery.ts new file mode 100644 index 00000000..255bbe95 --- /dev/null +++ b/frontend/src/lib/__tests__/preloadRecovery.ts @@ -0,0 +1,22 @@ +import { describe, expect, test, vi } from 'vitest' + +import { installPreloadErrorRecovery } from 'lib/preloadRecovery' + +describe('installPreloadErrorRecovery', () => { + test('prevents a stale dynamic import error and reloads once', () => { + const target = new EventTarget() + const reload = vi.fn() + const uninstall = installPreloadErrorRecovery(target, reload) + const first = new Event('vite:preloadError', { cancelable: true }) + const second = new Event('vite:preloadError', { cancelable: true }) + + target.dispatchEvent(first) + target.dispatchEvent(second) + + expect(first.defaultPrevented).toBe(true) + expect(second.defaultPrevented).toBe(true) + expect(reload).toHaveBeenCalledTimes(1) + + uninstall() + }) +}) diff --git a/frontend/src/lib/playwrightContainer.ts b/frontend/src/lib/playwrightContainer.ts new file mode 100644 index 00000000..3d96b694 --- /dev/null +++ b/frontend/src/lib/playwrightContainer.ts @@ -0,0 +1,16 @@ +type ContainerEnvironment = { + [name: string]: string | undefined + REGISTRY?: string + IMAGE_NAME?: string + DOCKER_TAG?: string +} + +export function resolveContainerImage( + environment: ContainerEnvironment = process.env +): string { + const registry = environment.REGISTRY ?? 'ghcr.io' + const imageName = (environment.IMAGE_NAME ?? 'wandb/openui').toLowerCase() + const tag = environment.DOCKER_TAG ?? 'latest' + + return `${registry}/${imageName}:${tag}` +} diff --git a/frontend/src/lib/preloadRecovery.ts b/frontend/src/lib/preloadRecovery.ts new file mode 100644 index 00000000..b6c51e65 --- /dev/null +++ b/frontend/src/lib/preloadRecovery.ts @@ -0,0 +1,16 @@ +export function installPreloadErrorRecovery( + target: EventTarget = window, + reload: () => void = () => window.location.reload() +): () => void { + let reloading = false + const handlePreloadError = (event: Event) => { + event.preventDefault() + if (reloading) return + reloading = true + reload() + } + + target.addEventListener('vite:preloadError', handlePreloadError) + return () => + target.removeEventListener('vite:preloadError', handlePreloadError) +} diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx index 7d7f98f0..f2d05c5b 100644 --- a/frontend/src/main.tsx +++ b/frontend/src/main.tsx @@ -1,10 +1,13 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import App from 'App' import 'lib/i18n' +import { installPreloadErrorRecovery } from 'lib/preloadRecovery' import { StrictMode } from 'react' import { createRoot } from 'react-dom/client' import './index.css' +installPreloadErrorRecovery() + const MAX_RETRIES = 1 const queryClient = new QueryClient({ defaultOptions: { diff --git a/frontend/src/mocks/handlers.ts b/frontend/src/mocks/handlers.ts index 00ef54a5..79f771df 100644 --- a/frontend/src/mocks/handlers.ts +++ b/frontend/src/mocks/handlers.ts @@ -1,8 +1,50 @@ import { http, HttpResponse } from 'msw' const handlers = [ + http.get('/v1/models', () => + HttpResponse.json({ + models: { + openai: [], + groq: [], + ollama: [], + litellm: [], + copilot: [] + }, + copilot_status: { + state: 'disabled', + message: null + } + }) + ), http.get('https://614c99f03c438c00179faa84.mockapi.io/fruits', () => HttpResponse.json({}) + ), + http.get('/v1/copilot/device/status', () => + HttpResponse.json({ + state: 'unauthenticated', + message: null, + verification_uri: null, + user_code: null, + expires_at: null + }) + ), + http.post('/v1/copilot/device/start', () => + HttpResponse.json({ + state: 'unauthenticated', + message: null, + verification_uri: null, + user_code: null, + expires_at: null + }) + ), + http.post('/v1/copilot/device/cancel', () => + HttpResponse.json({ + state: 'cancelled', + message: null, + verification_uri: null, + user_code: null, + expires_at: null + }) ) ] diff --git a/frontend/src/setupTests.ts b/frontend/src/setupTests.ts index 11fd7f8a..4141b2e1 100644 --- a/frontend/src/setupTests.ts +++ b/frontend/src/setupTests.ts @@ -4,6 +4,21 @@ import server from 'mocks/server' import { DESKTOP_RESOLUTION_HEIGHT, DESKTOP_RESOLUTION_WIDTH } from 'testUtils' import 'whatwg-fetch' +// Mock ResizeObserver (required by Radix UI Select in jsdom) +global.ResizeObserver = class ResizeObserver { + observe() {} + unobserve() {} + disconnect() {} +} + +// Mock pointer capture APIs (required by Radix UI in jsdom) +Element.prototype.hasPointerCapture = () => false +Element.prototype.setPointerCapture = () => {} +Element.prototype.releasePointerCapture = () => {} + +// Mock scrollIntoView (required by Radix UI Select in jsdom) +window.HTMLElement.prototype.scrollIntoView = () => {} + // Mock indexedDB const indexedDB = { open: () => ({ diff --git a/frontend/src/testEnvironment.ts b/frontend/src/testEnvironment.ts new file mode 100644 index 00000000..6dd4fb3b --- /dev/null +++ b/frontend/src/testEnvironment.ts @@ -0,0 +1,62 @@ +/** + * Custom Vitest environment: jsdom with native AbortController/AbortSignal restored. + * + * Root cause of App test failure + * ───────────────────────────── + * jsdom replaces globalThis.AbortController (and AbortSignal) with its own + * WebIDL-generated classes when Vitest calls `populateGlobal`. Node.js's + * bundled undici captures the *native* AbortSignal at its own startup—before + * jsdom runs—and validates every Request signal with: + * + * FunctionPrototypeSymbolHasInstance(capturedNativeAbortSignal, signal) + * // equivalent to: signal instanceof + * + * React Router's createBrowserRouter calls `new AbortController()` during + * navigation, which—in the jsdom context—produces a jsdom AbortSignal. When + * MSW's recordRawHeaders proxy intercepts `new Request(url, { signal })` and + * Reflect.constructs the native undici Request, undici rejects the jsdom signal + * with "TypeError: RequestInit: Expected signal … to be an instance of + * AbortSignal." This error aborts the navigation, so the AI page never renders + * and Testing Library cannot find role="navigation". + * + * Fix + * ─── + * Capture the native AbortController/AbortSignal *before* jsdom's setup runs, + * then write them back through Vitest's populateGlobal setter so that all code + * running in the test uses native signals that pass undici's instanceof check. + */ + +import { builtinEnvironments } from 'vitest/environments' + +export default { + ...builtinEnvironments.jsdom, + name: 'custom-jsdom', + + async setup(global: typeof globalThis, options: Record) { + // 1. Save the native implementations before jsdom overwrites them. + // At this point the test-worker global is still a plain Node.js + // global, so these are the classes undici already captured. + const NativeAbortController = global.AbortController + const NativeAbortSignal = global.AbortSignal + + // 2. Run the standard jsdom environment setup. + // Internally this calls Vitest's populateGlobal(), which installs + // jsdom's AbortController/AbortSignal via configurable getters: + // + // Object.defineProperty(global, 'AbortController', { + // get() { return overrideObject.has(key) ? overrideObject.get(key) : win[key] }, + // set(v) { overrideObject.set(key, v) }, + // configurable: true, + // }) + const env = await builtinEnvironments.jsdom.setup(global, options) + + // 3. Re-install the native implementations via the setter above. + // overrideObject.set() takes precedence over win[key] in the getter, + // so every subsequent `new AbortController()` in test code returns a + // native instance whose .signal passes undici's instanceof check. + global.AbortController = NativeAbortController + global.AbortSignal = NativeAbortSignal + + return env + } +} diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts index e4ede8e7..37f3f6f8 100644 --- a/frontend/vite.config.ts +++ b/frontend/vite.config.ts @@ -32,12 +32,12 @@ export default defineConfig(({ mode }) => ({ css: false, include: ['src/**/__tests__/*'], globals: true, - environment: 'jsdom', + environment: './src/testEnvironment', setupFiles: 'src/setupTests.ts', clearMocks: true, coverage: { include: ['src/**/*'], - exclude: ['src/main.tsx'], + exclude: ['src/main.tsx', 'src/testEnvironment.ts'], thresholds: { '100': true },