diff --git a/src/loadpath/architecture/__init__.py b/src/loadpath/architecture/__init__.py index e549953..3912e72 100644 --- a/src/loadpath/architecture/__init__.py +++ b/src/loadpath/architecture/__init__.py @@ -1,4 +1,4 @@ from loadpath.architecture.rules import Finding, evaluate -from loadpath.architecture.snapshot import architecture_report, summarize_index +from loadpath.architecture.snapshot import architecture_report, persist_findings, summarize_index -__all__ = ["Finding", "evaluate", "architecture_report", "summarize_index"] +__all__ = ["Finding", "evaluate", "architecture_report", "summarize_index", "persist_findings"] diff --git a/src/loadpath/architecture/depth.py b/src/loadpath/architecture/depth.py index 8187db7..9826ff6 100644 --- a/src/loadpath/architecture/depth.py +++ b/src/loadpath/architecture/depth.py @@ -136,10 +136,10 @@ def _leaked_seams(store: GraphStore) -> list[Finding]: ] queries_by_src: dict[str, set[str]] = {} called_by_view: dict[str, set[str]] = {v: set() for v in views} - for edge in store.edges(): - if edge["type"] == EdgeType.QUERIES_MODEL.value: - queries_by_src.setdefault(edge["src"], set()).add(edge["dst"]) - elif edge["type"] == EdgeType.CALLS.value and edge["src"] in called_by_view: + for edge in store.edges_of_type([EdgeType.QUERIES_MODEL.value]): + queries_by_src.setdefault(edge["src"], set()).add(edge["dst"]) + for edge in store.edges_of_type([EdgeType.CALLS.value]): + if edge["src"] in called_by_view: called_by_view[edge["src"]].add(edge["dst"]) modules_by_ctx: dict[str, list[dict]] = {} for svc in services: @@ -149,9 +149,7 @@ def _leaked_seams(store: GraphStore) -> list[Finding]: modules_by_ctx.setdefault(ctx, []).append(svc) out: list[Finding] = [] seen: set[tuple[str, str]] = set() - for edge in store.edges(): - if edge["type"] != EdgeType.QUERIES_MODEL.value: - continue + for edge in store.edges_of_type([EdgeType.QUERIES_MODEL.value]): view = views.get(edge["src"]) model = models.get(edge["dst"]) if not view or not model: @@ -222,13 +220,12 @@ def _tests_bypass_interface(store: GraphStore) -> list[Finding]: views = {n["id"]: n for n in store.nodes([NodeType.VIEW])} serializers = {n["id"]: n for n in store.nodes([NodeType.SERIALIZER])} tested_src: set[str] = set() - for edge in store.edges(): - if edge["type"] == EdgeType.TESTED_BY.value: - tested_src.add(edge["src"]) + for edge in store.edges_of_type([EdgeType.TESTED_BY.value]): + tested_src.add(edge["src"]) view_of_route: dict[str, str] = {} ser_of_view: dict[str, str] = {} page_of_route: dict[str, str] = {} - for edge in store.edges(): + for edge in store.edges_of_type([EdgeType.PUBLISHES_ROUTE.value, EdgeType.USES_SERIALIZER.value]): if edge["type"] == EdgeType.PUBLISHES_ROUTE.value and edge["src"] in routes: if edge["dst"] in views: view_of_route[edge["src"]] = edge["dst"] diff --git a/src/loadpath/architecture/rules.py b/src/loadpath/architecture/rules.py index f15e4f3..c32443c 100644 --- a/src/loadpath/architecture/rules.py +++ b/src/loadpath/architecture/rules.py @@ -108,9 +108,7 @@ def _views_foreign_models(store: GraphStore, config: LoadpathConfig) -> list[Fin out: list[Finding] = [] views = {n["id"]: n for n in store.nodes([NodeType.VIEW, NodeType.SERVICE])} models = {n["id"]: n for n in store.nodes([NodeType.MODEL])} - for edge in store.edges(): - if edge["type"] != EdgeType.QUERIES_MODEL.value: - continue + for edge in store.edges_of_type([EdgeType.QUERIES_MODEL.value]): view = views.get(edge["src"]) model = models.get(edge["dst"]) or store.get_node(edge["dst"]) if not view or not model: @@ -158,9 +156,7 @@ def _react_own_api(store: GraphStore, config: LoadpathConfig) -> list[Finding]: allowed_by_context[name].add(path) allowed_by_context[name].add(normalize_url_template(path)) - for edge in store.edges(): - if edge["type"] not in {EdgeType.CALLS.value, EdgeType.CONSUMED_BY_CLIENT.value}: - continue + for edge in store.edges_of_type([EdgeType.CALLS.value, EdgeType.CONSUMED_BY_CLIENT.value]): src = features.get(edge["src"]) dst = clients.get(edge["dst"]) if not src or not dst: @@ -214,9 +210,7 @@ def _contract_drift(store: GraphStore, config: LoadpathConfig) -> list[Finding]: fields = {n["id"]: n for n in store.nodes([NodeType.SERIALIZER_FIELD])} serializers = {n["id"]: n for n in store.nodes([NodeType.SERIALIZER])} matched_serializers: dict[str, list[dict]] = {} - for edge in store.edges(): - if edge["type"] != EdgeType.MATCHES_SCHEMA.value: - continue + for edge in store.edges_of_type([EdgeType.MATCHES_SCHEMA.value]): ser = serializers.get(edge["src"]) schema = schemas.get(edge["dst"]) if ser and schema: @@ -427,9 +421,7 @@ def _cascade_crosses_context(store: GraphStore, config: LoadpathConfig) -> list[ out: list[Finding] = [] fields = {n["id"]: n for n in store.nodes([NodeType.FIELD])} models = {n["id"]: n for n in store.nodes([NodeType.MODEL])} - for edge in store.edges(): - if edge["type"] != EdgeType.RELATES_TO.value: - continue + for edge in store.edges_of_type([EdgeType.RELATES_TO.value]): if (edge.get("extra") or {}).get("on_delete") != "CASCADE": continue field = fields.get(edge["src"]) @@ -518,14 +510,12 @@ def _remaining_field_refs(store: GraphStore, app: str, model: str, field: str) - model_ids = _ids_for(store, NodeType.MODEL, f"{app}.{model}") serializer_ids: set[str] = set() want_model = f"{app}.{model}".lower() - for edge in store.edges(): - if edge["type"] != EdgeType.SERIALIZES.value: - continue + for edge in store.edges_of_type([EdgeType.SERIALIZES.value]): dst = (edge.get("dst") or "").lower() if edge["dst"] in model_ids or dst.endswith(":" + want_model): serializer_ids.add(edge["src"]) - for edge in store.edges(): - if edge["type"] != EdgeType.HAS_FIELD.value or edge["src"] not in serializer_ids: + for edge in store.edges_of_type([EdgeType.HAS_FIELD.value]): + if edge["src"] not in serializer_ids: continue child = store.get_node(edge["dst"]) if child and child.get("name") == field: @@ -537,16 +527,13 @@ def _remaining_model_refs(store: GraphStore, app: str, model: str) -> list[dict] still = list(_qnames(store, NodeType.MODEL, f"{app}.{model}")) model_ids = _ids_for(store, NodeType.MODEL, f"{app}.{model}") want = f"{app}.{model}".lower() - for edge in store.edges(): + for edge in store.edges_of_type( + [EdgeType.SERIALIZES.value, EdgeType.QUERIES_MODEL.value, EdgeType.RELATES_TO.value] + ): dst = (edge.get("dst") or "").lower() if edge["dst"] not in model_ids and not dst.endswith(":" + want): continue - if edge["type"] in { - EdgeType.SERIALIZES.value, - EdgeType.QUERIES_MODEL.value, - EdgeType.RELATES_TO.value, - }: - src = store.get_node(edge["src"]) - if src: - still.append(src) + src = store.get_node(edge["src"]) + if src: + still.append(src) return still diff --git a/src/loadpath/architecture/snapshot.py b/src/loadpath/architecture/snapshot.py index 9103b88..a9a839a 100644 --- a/src/loadpath/architecture/snapshot.py +++ b/src/loadpath/architecture/snapshot.py @@ -2,6 +2,7 @@ from __future__ import annotations +import json from pathlib import Path from typing import Any @@ -46,9 +47,32 @@ } +def persist_findings(store: GraphStore, config: LoadpathConfig) -> list[dict[str, Any]]: + """Run architecture rules once and store the result for cheap workspace loads.""" + raw = evaluate(store, config) + findings = [f.to_dict() for f in raw] + store.set_meta("findings_json", json.dumps(findings)) + return findings + + +def _load_cached_findings(store: GraphStore) -> list[dict[str, Any]] | None: + raw = store.get_meta("findings_json") + if not raw: + return None + try: + payload = json.loads(raw) + except json.JSONDecodeError: + return None + if not isinstance(payload, list): + return None + return payload + + def summarize_index(store: GraphStore, config: LoadpathConfig, *, hash_drift: bool = False) -> dict[str, Any]: - raw_findings = evaluate(store, config) - findings = [f.to_dict() for f in raw_findings] + drift = index_drift(store, config.repo_root, config, hash_contents=hash_drift) + findings = None if drift.get("config_changed") else _load_cached_findings(store) + if findings is None: + findings = persist_findings(store, config) residuals = [line for line in (store.get_meta("residuals") or "").splitlines() if line] contexts = { name: { @@ -60,7 +84,6 @@ def summarize_index(store: GraphStore, config: LoadpathConfig, *, hash_drift: bo } for name, ctx in config.contexts.items() } - drift = index_drift(store, config.repo_root, config, hash_contents=hash_drift) boot_residuals = [line for line in residuals if "django.setup()" in line] return { "ok": True, @@ -82,7 +105,7 @@ def summarize_index(store: GraphStore, config: LoadpathConfig, *, hash_drift: bo "contexts": contexts, "rules": list(config.rules), "findings": findings, - "deepening": deepening_candidates(raw_findings), + "deepening": deepening_candidates(findings), "residuals": residuals[:40], "boot_residuals": boot_residuals, "has_config": (config.repo_root / "loadpath.yml").is_file(), diff --git a/src/loadpath/detect.py b/src/loadpath/detect.py index 315b7a9..2bd4535 100644 --- a/src/loadpath/detect.py +++ b/src/loadpath/detect.py @@ -9,26 +9,9 @@ import yaml from loadpath.config import DEFAULT_RULES, LoadpathConfig, find_config +from loadpath.scan import SKIP_DIR_NAMES, iter_named_files, skip_dir_name -SKIP_DIRS = { - ".git", - "node_modules", - ".venv", - "venv", - "__pycache__", - ".loadpath", - "dist", - "build", - ".mypy_cache", - ".pytest_cache", - "site-packages", - "docs", - "documentation", - "website", - "docusaurus", - "storybook", - "starlight_help", -} +SKIP_DIRS = SKIP_DIR_NAMES TESTISH_PARTS = {"test", "tests", "testing"} @@ -41,7 +24,7 @@ def _rel_parts(path: Path, repo_root: Path) -> tuple[str, ...]: def _skip(path: Path, repo_root: Path) -> bool: - return any(part in SKIP_DIRS or part.startswith(".") for part in _rel_parts(path, repo_root)) + return any(skip_dir_name(part) for part in _rel_parts(path, repo_root)) def detect_layout(repo_root: Path) -> dict[str, Any]: @@ -121,9 +104,7 @@ def ensure_config(repo_root: Path) -> LoadpathConfig: def _first(repo_root: Path, name: str) -> str | None: - for path in repo_root.rglob(name): - if _skip(path, repo_root): - continue + for path in iter_named_files(repo_root, (name,)): try: return path.relative_to(repo_root).as_posix() except ValueError: @@ -138,9 +119,7 @@ def _is_testish(rel: Path) -> bool: def _detect_django_root(repo_root: Path) -> str: """Prefer the package that holds real apps, not a nested test project's manage.py.""" parents: list[tuple[str, ...]] = [] - for marker in repo_root.rglob("apps.py"): - if _skip(marker, repo_root): - continue + for marker in iter_named_files(repo_root, ("apps.py",)): app_dir = marker.parent if app_dir.name in {"migrations", "tests", "management"}: continue @@ -157,7 +136,7 @@ def _detect_django_root(repo_root: Path) -> str: break return "/".join(common) if common else "." - manages = [p for p in repo_root.rglob("manage.py") if not _skip(p, repo_root)] + manages = [p for p in iter_named_files(repo_root, ("manage.py",))] manages.sort(key=lambda p: (_is_testish(p.relative_to(repo_root)), len(p.relative_to(repo_root).parts))) if manages: rel = manages[0].parent.relative_to(repo_root) @@ -223,9 +202,7 @@ def _detect_react_root(repo_root: Path) -> str: return candidate scored: list[tuple[int, str]] = [] - for pkg in repo_root.rglob("package.json"): - if _skip(pkg, repo_root): - continue + for pkg in iter_named_files(repo_root, ("package.json",)): if _skip_react_tree(pkg, repo_root): continue if not _package_has_react(pkg): @@ -250,7 +227,7 @@ def _django_apps(repo_root: Path, django_root: str) -> list[str]: if not root.is_dir(): root = repo_root apps: list[str] = [] - for marker in root.rglob("apps.py"): + for marker in iter_named_files(root, ("apps.py",)): if _skip(marker, repo_root): continue rel = marker.relative_to(repo_root) @@ -260,7 +237,7 @@ def _django_apps(repo_root: Path, django_root: str) -> list[str]: if name not in apps and name not in {"config", "project", "settings"}: apps.append(name) if not apps: - for marker in root.rglob("models.py"): + for marker in iter_named_files(root, ("models.py",)): if _skip(marker, repo_root) or _is_testish(marker.relative_to(repo_root)): continue name = marker.parent.name diff --git a/src/loadpath/extractors/django.py b/src/loadpath/extractors/django.py index 9a37982..c884d52 100644 --- a/src/loadpath/extractors/django.py +++ b/src/loadpath/extractors/django.py @@ -116,6 +116,25 @@ ON_DELETE_ATTRS = {"CASCADE", "PROTECT", "RESTRICT", "SET_NULL", "SET_DEFAULT", "DO_NOTHING", "SET"} +def _uppercase_name(node: ast.AST | None) -> str | None: + """First ClassName-looking identifier in an AST fragment (queryset = Model.objects...).""" + if node is None: + return None + for child in ast.walk(node): + if isinstance(child, ast.Name) and child.id[:1].isupper(): + return child.id + return None + + +def _mentions_queryset(node: ast.AST) -> bool: + for child in ast.walk(node): + if isinstance(child, ast.Name) and child.id == "queryset": + return True + if isinstance(child, ast.Attribute) and child.attr == "objects": + return True + return False + + def _name(node: ast.AST | None) -> str | None: if node is None: return None @@ -631,7 +650,7 @@ def _serializer( fname = stmt.targets[0].id if not fname.startswith("_") and fname[0].islower(): declared.append((fname, stmt.lineno)) - if isinstance(stmt, ast.FunctionDef) and "queryset" in ast.dump(stmt): + if isinstance(stmt, ast.FunctionDef) and _mentions_queryset(stmt): queryset_in_serializer = True nested_by_name = self._nested_serializer_fields(node) method_fields = self._method_field_names(node) @@ -703,10 +722,7 @@ def _view(self, node: ast.ClassDef) -> None: elif key == "throttle_classes": extra["throttles"] = _list_names(stmt.value) elif key == "queryset": - dumped = ast.dump(stmt.value) - m = re.search(r"id='([A-Z][A-Za-z0-9_]+)'", dumped) - if m: - queryset_model = m.group(1) + queryset_model = _uppercase_name(stmt.value) elif key == "filterset_class": extra["filterset"] = _name(stmt.value) elif key == "authentication_classes": @@ -717,10 +733,9 @@ def _view(self, node: ast.ClassDef) -> None: extra["template"] = _const_str(stmt.value) if isinstance(stmt, ast.FunctionDef) and stmt.name == "get_queryset": extra["get_queryset"] = True - dumped = ast.dump(stmt) - m = re.search(r"id='([A-Z][A-Za-z0-9_]+)'", dumped) - if m and not queryset_model: - queryset_model = m.group(1) + found = _uppercase_name(stmt) + if found and not queryset_model: + queryset_model = found if isinstance(stmt, ast.FunctionDef) and stmt.name == "get_serializer_class": dynamic_serializer = True extra["get_serializer_class"] = True diff --git a/src/loadpath/extractors/django_boot.py b/src/loadpath/extractors/django_boot.py index a71aa4a..907d883 100644 --- a/src/loadpath/extractors/django_boot.py +++ b/src/loadpath/extractors/django_boot.py @@ -9,6 +9,7 @@ from pathlib import Path from loadpath.config import LoadpathConfig +from loadpath.scan import iter_named_files from loadpath.types import Edge, EdgeType, ExtractedGraph, Node, NodeType, node_id BOOT_JSON_MARKER = "__LOADPATH_BOOT_JSON__" @@ -251,12 +252,7 @@ def _discover_settings_module(repo_root: Path, django_root: str = "backend") -> return env django_path = (repo_root / django_root).resolve() candidates: list[Path] = [] - for settings in repo_root.rglob("settings.py"): - rel = settings.relative_to(repo_root) - if any(part.startswith(".") for part in rel.parts): - continue - if "site-packages" in rel.parts: - continue + for settings in iter_named_files(repo_root, ("settings.py",)): candidates.append(settings) if not candidates: return None diff --git a/src/loadpath/extractors/react.py b/src/loadpath/extractors/react.py index 741a41e..de0cafe 100644 --- a/src/loadpath/extractors/react.py +++ b/src/loadpath/extractors/react.py @@ -4,6 +4,7 @@ from pathlib import Path from loadpath.config import LoadpathConfig +from loadpath.extractors.text import line_at, newline_starts from loadpath.types import Edge, EdgeType, ExtractedGraph, Node, NodeType, node_id IMPORT_RE = re.compile( @@ -289,6 +290,7 @@ def extract_react_file(rel_path: str, source: str, config: LoadpathConfig) -> Ex e2e = is_e2e_file(rel) stem = Path(rel).stem graphql_file = Path(rel).suffix.lower() in {".graphql", ".gql"} + lines = newline_starts(source) def add(ntype: NodeType, name: str, qname: str, line: int = 1, extra: dict | None = None) -> Node: n = Node( @@ -362,7 +364,7 @@ def edge(src: str, dst: str, etype: EdgeType, confidence: float = 1.0, extra: di name = m.group(1) if name in HTTP_VERBS: continue - line = source[: m.start()].count("\n") + 1 + line = line_at(lines, m.start()) is_page = ( name.endswith("Page") or "pages/" in rel @@ -392,7 +394,7 @@ def edge(src: str, dst: str, etype: EdgeType, confidence: float = 1.0, extra: di hooks: list[Node] = [] for m in HOOK_RE.finditer(source): name = m.group(1) - line = source[: m.start()].count("\n") + 1 + line = line_at(lines, m.start()) n = add(NodeType.HOOK, name, f"{feature or 'app'}.{name}", line, {"feature": feature}) hooks.append(n) if feature: @@ -412,7 +414,7 @@ def edge(src: str, dst: str, etype: EdgeType, confidence: float = 1.0, extra: di for m in USE_QUERY_RE.finditer(source): body = m.group("body") - line = source[: m.start()].count("\n") + 1 + line = line_at(lines, m.start()) km = QUERY_KEY_RE.search(body) key_raw = km.group(1) if km else None if key_raw: @@ -432,7 +434,7 @@ def edge(src: str, dst: str, etype: EdgeType, confidence: float = 1.0, extra: di for m in INVALIDATE_RE.finditer(source): key_raw = m.group(1) - line = source[: m.start()].count("\n") + 1 + line = line_at(lines, m.start()) key_name = re.sub(r"""\s+""", "", key_raw) qn = add( NodeType.QUERY_KEY, @@ -450,7 +452,7 @@ def edge(src: str, dst: str, etype: EdgeType, confidence: float = 1.0, extra: di continue if "/api/" not in url and not url.startswith("/"): continue - line = source[: m.start()].count("\n") + 1 + line = line_at(lines, m.start()) norm = normalize_url_template(url) generated_file = "/generated/" in f"/{rel}/" or "openapi" in Path(rel).stem.lower() qname = f"client:{rel}:{norm}" @@ -477,7 +479,7 @@ def edge(src: str, dst: str, etype: EdgeType, confidence: float = 1.0, extra: di # also catch fetch(`/api/...`) missed by grouping for m in re.finditer(r"""[`'"](/api/[^`'"]+)[`'"]""", source): url = m.group(1) - line = source[: m.start()].count("\n") + 1 + line = line_at(lines, m.start()) norm = normalize_url_template(url) generated_file = "/generated/" in f"/{rel}/" or "openapi" in Path(rel).stem.lower() qname = f"client:{rel}:{norm}" @@ -504,7 +506,7 @@ def edge(src: str, dst: str, etype: EdgeType, confidence: float = 1.0, extra: di if not path_m: continue rpath = path_m.group(1) or "/" - line = source[: m.start()].count("\n") + 1 + line = line_at(lines, m.start()) page_name = el_m.group(1) if el_m else rpath rn = add(NodeType.REACT_ROUTE, rpath, f"react.route:{rpath}", line, {"element": page_name}) if el_m: @@ -515,13 +517,13 @@ def edge(src: str, dst: str, etype: EdgeType, confidence: float = 1.0, extra: di for m in PATH_OBJ_RE.finditer(source): rpath, page_name = m.group(1) or "/", m.group(2) - line = source[: m.start()].count("\n") + 1 + line = line_at(lines, m.start()) rn = add(NodeType.REACT_ROUTE, rpath, f"react.route:{rpath}", line, {"element": page_name}) edge(rn.id, node_id(NodeType.PAGE, f"{feature or 'app'}.{page_name}"), EdgeType.PUBLISHES_ROUTE) for m in GQL_DOC_RE.finditer(source): body = m.group(1) - line = source[: m.start()].count("\n") + 1 + line = line_at(lines, m.start()) ops = GQL_OP_RE.findall(body) if not ops: ops = [("query", f"{stem}Query")] @@ -547,7 +549,7 @@ def edge(src: str, dst: str, etype: EdgeType, confidence: float = 1.0, extra: di for m in ZOD_RE.finditer(source): name, body = m.group(1), m.group(2) - line = source[: m.start()].count("\n") + 1 + line = line_at(lines, m.start()) fields = ZOD_FIELD_RE.findall(body) schema = add( NodeType.FORM_SCHEMA, @@ -562,7 +564,7 @@ def edge(src: str, dst: str, etype: EdgeType, confidence: float = 1.0, extra: di if CONTEXT_RE.search(source): for m in PROVIDER_RE.finditer(source): name = m.group(1) - line = source[: m.start()].count("\n") + 1 + line = line_at(lines, m.start()) add(NodeType.CONTEXT_PROVIDER, name, f"{feature or 'app'}.{name}", line) if is_test: @@ -700,6 +702,7 @@ def _extract_next_routes(add, edge, graph, rel, source, feature, app_info, pages def _extract_typed_clients(add, edge, graph, rel, source, feature, hooks, components) -> None: + lines = newline_starts(source) if RTK_RE.search(source) or "injectEndpoints" in source: base = "" bm = RTK_BASE_URL_RE.search(source) @@ -715,7 +718,7 @@ def _extract_typed_clients(add, edge, graph, rel, source, feature, hooks, compon if raw.startswith("http") and "/api/" not in raw and not raw.startswith("/"): continue url = _join_base(base, raw) - line = source[: m.start()].count("\n") + 1 + line = line_at(lines, m.start()) _add_client( add, edge, @@ -739,7 +742,7 @@ def _extract_typed_clients(add, edge, graph, rel, source, feature, hooks, compon method, raw = m.group(1), m.group(2) if not raw.startswith("/") and "/api/" not in raw: continue - line = source[: m.start()].count("\n") + 1 + line = line_at(lines, m.start()) _add_client( add, edge, @@ -762,7 +765,7 @@ def _extract_typed_clients(add, edge, graph, rel, source, feature, hooks, compon raw = m.group(1) or m.group(2) or "" if not raw.startswith("/") and "/api/" not in raw: continue - line = source[: m.start()].count("\n") + 1 + line = line_at(lines, m.start()) _add_client( add, edge, @@ -777,7 +780,7 @@ def _extract_typed_clients(add, edge, graph, rel, source, feature, hooks, compon ) for m in TRPC_RE.finditer(source): proc = m.group(1).rstrip(".") - line = source[: m.start()].count("\n") + 1 + line = line_at(lines, m.start()) qname = f"client:{rel}:trpc.{proc}" if any(n.qualified_name == qname for n in graph.nodes): continue @@ -805,11 +808,12 @@ def _extract_typed_clients(add, edge, graph, rel, source, feature, hooks, compon def _extract_server_actions(add, edge, rel, source, feature, components) -> None: if '"use server"' not in source and "'use server'" not in source: return + lines = newline_starts(source) for m in SERVER_ACTION_FN_RE.finditer(source): name = m.group(1) or m.group(2) if not name or name in HTTP_VERBS: continue - line = source[: m.start()].count("\n") + 1 + line = line_at(lines, m.start()) action = add( NodeType.SERVER_ACTION, name, @@ -824,6 +828,7 @@ def _extract_server_actions(add, edge, rel, source, feature, components) -> None def _extract_graphql_codegen(add, edge, source, feature, components) -> None: + lines = newline_starts(source) for m in CODEGEN_TYPE_RE.finditer(source): name = m.group(1) start = m.end() @@ -839,7 +844,7 @@ def _extract_graphql_codegen(add, edge, source, feature, components) -> None: fields = [f for f in CODEGEN_FIELD_RE.findall(body) if f not in {"__typename", "Query", "Mutation", "Subscription"}] if not fields: continue - line = source[: m.start()].count("\n") + 1 + line = line_at(lines, m.start()) schema = add( NodeType.FORM_SCHEMA, name, diff --git a/src/loadpath/extractors/templates.py b/src/loadpath/extractors/templates.py index a332647..97ec539 100644 --- a/src/loadpath/extractors/templates.py +++ b/src/loadpath/extractors/templates.py @@ -6,6 +6,7 @@ from pathlib import Path from loadpath.config import LoadpathConfig +from loadpath.extractors.text import line_at, newline_starts from loadpath.types import Edge, EdgeType, ExtractedGraph, Node, NodeType, node_id HTMX_RE = re.compile( @@ -47,6 +48,7 @@ def extract_template_file(rel_path: str, source: str, config: LoadpathConfig) -> graph = ExtractedGraph() app = _app_from_template(rel) context = config.context_for_django_app(app) + lines = newline_starts(source) name = Path(rel).name qname = template_qname(rel) extra = { @@ -97,7 +99,7 @@ def extract_template_file(rel_path: str, source: str, config: LoadpathConfig) -> name=call_name, qualified_name=f"{rel}:{call_name}", file_path=rel, - start_line=source[: match.start()].count("\n") + 1, + start_line=line_at(lines, match.start()), context=context, extra={"app": app, "method": method, "url": url}, ) diff --git a/src/loadpath/extractors/text.py b/src/loadpath/extractors/text.py new file mode 100644 index 0000000..12c45d7 --- /dev/null +++ b/src/loadpath/extractors/text.py @@ -0,0 +1,21 @@ +"""Cheap line lookups for extractors (avoid `source[:pos].count('\\n')` per match).""" + +from __future__ import annotations + +import bisect + + +def newline_starts(source: str) -> list[int]: + starts = [0] + idx = 0 + while True: + found = source.find("\n", idx) + if found < 0: + break + starts.append(found + 1) + idx = found + 1 + return starts + + +def line_at(starts: list[int], pos: int) -> int: + return bisect.bisect_right(starts, pos) diff --git a/src/loadpath/graph/store.py b/src/loadpath/graph/store.py index 7a2e152..c7d9d1e 100644 --- a/src/loadpath/graph/store.py +++ b/src/loadpath/graph/store.py @@ -76,7 +76,7 @@ def __init__(self, db_path: Path) -> None: self.conn.execute("PRAGMA synchronous = NORMAL") self.conn.execute("PRAGMA temp_store = MEMORY") self.conn.execute("PRAGMA mmap_size = 268435456") - self.conn.execute("PRAGMA cache_size = -8000") + self.conn.execute("PRAGMA cache_size = -32000") self.conn.executescript(SCHEMA) self.conn.commit() self._nodes_cache: list[dict[str, Any]] | None = None @@ -108,6 +108,9 @@ def get_meta(self, key: str) -> str | None: row = self.conn.execute("SELECT value FROM meta WHERE key=?", (key,)).fetchone() return row["value"] if row else None + def file_hashes(self) -> dict[str, str]: + return {r["path"]: r["hash"] for r in self.conn.execute("SELECT path, hash FROM files")} + def file_hash(self, path: str) -> str | None: row = self.conn.execute("SELECT hash FROM files WHERE path=?", (path,)).fetchone() return row["hash"] if row else None @@ -148,37 +151,54 @@ def prune_dangling_edges(self) -> None: self._invalidate() def upsert_graph(self, graph: ExtractedGraph, *, commit: bool = True) -> None: + if not graph.nodes and not graph.edges: + if commit: + self.conn.commit() + return + existing: dict[str, dict[str, Any]] = {} + ids = [node.id for node in graph.nodes] + for chunk in _chunks(ids, 400): + placeholders = ",".join("?" * len(chunk)) + for row in self.conn.execute( + f"SELECT * FROM nodes WHERE id IN ({placeholders})", chunk + ): + existing[row["id"]] = self._node_from_row(row) for node in graph.nodes: - self.upsert_node(node) - for edge in graph.edges: - self.upsert_edge(edge) + existing[node.id] = self._merged_node(node, existing.get(node.id)) + unique_ids = list(dict.fromkeys(ids)) + self.conn.executemany( + """ + INSERT INTO nodes(id, type, name, qualified_name, file_path, start_line, end_line, context, extra) + VALUES(?,?,?,?,?,?,?,?,?) + ON CONFLICT(id) DO UPDATE SET + type=excluded.type, + name=excluded.name, + qualified_name=excluded.qualified_name, + file_path=excluded.file_path, + start_line=excluded.start_line, + end_line=excluded.end_line, + context=excluded.context, + extra=excluded.extra + """, + [self._node_sql_row(existing[nid]) for nid in unique_ids], + ) + self.conn.executemany( + """ + INSERT INTO edges(id, src, dst, type, weight, confidence, extra) + VALUES(?,?,?,?,?,?,?) + ON CONFLICT(id) DO UPDATE SET + weight=excluded.weight, + confidence=excluded.confidence, + extra=excluded.extra + """, + [self._edge_row(edge) for edge in graph.edges], + ) if commit: self.conn.commit() self._invalidate() def upsert_node(self, node: Node) -> None: existing = self.get_node(node.id) - extra = dict(node.extra or {}) - file_path = node.file_path - start_line = node.start_line - context = node.context - if existing: - merged = dict(existing.get("extra") or {}) - merged.update(extra) - extra = merged - new_is_ref = bool(node.extra.get("referenced")) - old_is_ref = bool((existing.get("extra") or {}).get("referenced")) - # A definition (tasks.py / @actor) wins over a call-site placeholder. - if new_is_ref and not old_is_ref: - extra["referenced"] = False - for k, v in (existing.get("extra") or {}).items(): - if k not in node.extra or node.extra.get(k) is None: - extra[k] = v - file_path = existing.get("file_path") or file_path - start_line = existing.get("start_line") if existing.get("start_line") is not None else start_line - context = existing.get("context") or context - elif not new_is_ref and old_is_ref: - extra["referenced"] = False self.conn.execute( """ INSERT INTO nodes(id, type, name, qualified_name, file_path, start_line, end_line, context, extra) @@ -193,22 +213,11 @@ def upsert_node(self, node: Node) -> None: context=excluded.context, extra=excluded.extra """, - ( - node.id, - node.type.value, - node.name, - node.qualified_name, - file_path, - start_line, - node.end_line, - context, - json.dumps(extra), - ), + self._node_sql_row(self._merged_node(node, existing)), ) self._invalidate() def upsert_edge(self, edge: Edge) -> None: - row = edge.to_row() self.conn.execute( """ INSERT INTO edges(id, src, dst, type, weight, confidence, extra) @@ -218,15 +227,7 @@ def upsert_edge(self, edge: Edge) -> None: confidence=excluded.confidence, extra=excluded.extra """, - ( - row["id"], - row["src"], - row["dst"], - row["type"], - row["weight"], - row["confidence"], - json.dumps(row["extra"]), - ), + self._edge_row(edge), ) self._invalidate() @@ -274,6 +275,18 @@ def edges_between_types(self, types: Iterable[str]) -> list[dict[str, Any]]: ).fetchall() return [self._edge_from_row(r) for r in rows] + def edges_of_type(self, types: Iterable[str]) -> list[dict[str, Any]]: + want = {str(t) for t in types} + if not want: + return [] + if self._edges_cache is not None: + return [e for e in self._edges_cache if e["type"] in want] + placeholders = ",".join("?" * len(want)) + rows = self.conn.execute( + f"SELECT * FROM edges WHERE type IN ({placeholders})", tuple(want) + ).fetchall() + return [self._edge_from_row(r) for r in rows] + def neighbors(self, node_id: str, direction: str = "both") -> list[dict[str, Any]]: clauses = [] args: list[str] = [] @@ -380,9 +393,73 @@ def file_count(self) -> int: def indexed_paths(self) -> list[str]: return [r["path"] for r in self.conn.execute("SELECT path FROM files").fetchall()] + def _merged_node(self, node: Node, existing: dict[str, Any] | None) -> dict[str, Any]: + extra = dict(node.extra or {}) + file_path = node.file_path + start_line = node.start_line + context = node.context + if existing: + merged = dict(existing.get("extra") or {}) + merged.update(extra) + extra = merged + new_is_ref = bool(node.extra.get("referenced")) + old_is_ref = bool((existing.get("extra") or {}).get("referenced")) + # A definition (tasks.py / @actor) wins over a call-site placeholder. + if new_is_ref and not old_is_ref: + extra["referenced"] = False + for k, v in (existing.get("extra") or {}).items(): + if k not in node.extra or node.extra.get(k) is None: + extra[k] = v + file_path = existing.get("file_path") or file_path + start_line = existing.get("start_line") if existing.get("start_line") is not None else start_line + context = existing.get("context") or context + elif not new_is_ref and old_is_ref: + extra["referenced"] = False + return { + "id": node.id, + "type": node.type.value, + "name": node.name, + "qualified_name": node.qualified_name, + "file_path": file_path, + "start_line": start_line, + "end_line": node.end_line, + "context": context, + "extra": extra, + } + + @staticmethod + def _node_sql_row(merged: dict[str, Any]) -> tuple[Any, ...]: + extra = merged.get("extra") or {} + return ( + merged["id"], + merged["type"], + merged["name"], + merged["qualified_name"], + merged["file_path"], + merged["start_line"], + merged["end_line"], + merged["context"], + "{}" if not extra else json.dumps(extra), + ) + + @staticmethod + def _edge_row(edge: Edge) -> tuple[Any, ...]: + row = edge.to_row() + extra = row["extra"] + return ( + row["id"], + row["src"], + row["dst"], + row["type"], + row["weight"], + row["confidence"], + "{}" if not extra else json.dumps(extra), + ) + @staticmethod def _node_from_row(row: sqlite3.Row) -> dict[str, Any]: - extra = json.loads(row["extra"] or "{}") + raw = row["extra"] or "{}" + extra = {} if raw == "{}" else json.loads(raw) return { "id": row["id"], "type": row["type"], @@ -397,7 +474,8 @@ def _node_from_row(row: sqlite3.Row) -> dict[str, Any]: @staticmethod def _edge_from_row(row: sqlite3.Row) -> dict[str, Any]: - extra = json.loads(row["extra"] or "{}") + raw = row["extra"] or "{}" + extra = {} if raw == "{}" else json.loads(raw) return { "id": row["id"], "src": row["src"], @@ -407,3 +485,8 @@ def _edge_from_row(row: sqlite3.Row) -> dict[str, Any]: "confidence": row["confidence"], "extra": extra, } + + +def _chunks(values: list[str], size: int) -> Iterable[list[str]]: + for i in range(0, len(values), size): + yield values[i : i + size] diff --git a/src/loadpath/index.py b/src/loadpath/index.py index b7f5460..ff30f82 100644 --- a/src/loadpath/index.py +++ b/src/loadpath/index.py @@ -17,14 +17,14 @@ from loadpath.extractors.templates import extract_template_file from loadpath.extractors.django_boot import try_boot_models from loadpath.graph.store import GraphStore +from loadpath.scan import MAX_SOURCE_BYTES, iter_source_paths from loadpath.stitch.openapi import stitch -from loadpath.types import GENERATED_PATH_MARKERS, ExtractedGraph, Node, NodeType, node_id +from loadpath.types import ExtractedGraph, Node, NodeType, node_id PY_SKIP = {"migrations"} # still extract migrations, just not skip -INDEX_EXTENSIONS = {".py", ".ts", ".tsx", ".js", ".jsx", ".html", ".htm", ".graphql", ".gql"} # Bump when extractor/stitch node identity changes so incremental indexes rebuild. -INDEX_REVISION = "16" -_UPSERT_BATCH = 25 +INDEX_REVISION = "17" +_UPSERT_BATCH = 200 ProgressCallback = Callable[[dict[str, Any]], None] @@ -44,38 +44,11 @@ def default_db_path(repo_root: Path) -> Path: def iter_source_files(repo_root: Path, config: LoadpathConfig) -> list[Path]: files: list[Path] = [] - skip_dirs = { - ".git", - "node_modules", - ".venv", - "venv", - "__pycache__", - ".loadpath", - "dist", - "build", - ".mypy_cache", - ".pytest_cache", - "docs", - "documentation", - "website", - "docusaurus", - "storybook", - "starlight_help", - "collected_static", - "staticfiles", - "locale", - } - for path in repo_root.rglob("*"): - if not path.is_file() or path.suffix not in INDEX_EXTENSIONS: - continue - rel_path = path.relative_to(repo_root) - rel = rel_path.as_posix() - if any(part in skip_dirs for part in rel_path.parts): - continue - if any(m in rel for m in GENERATED_PATH_MARKERS if m.endswith("/") and m not in {"generated/"}): - # still index generated clients - pass - if path.name in {"package-lock.json"}: + for path in iter_source_paths(repo_root): + try: + if path.stat().st_size > MAX_SOURCE_BYTES: + continue + except OSError: continue files.append(path) return files @@ -249,7 +222,8 @@ def index_drift( else: files = files if files is not None else list_source_files(repo_root, config) present = {src.rel for src in files} - changed = [src.rel for src in files if store.file_hash(src.rel) != src.digest] + hashes = store.file_hashes() + changed = [src.rel for src in files if hashes.get(src.rel) != src.digest] added = sorted(present - indexed) deleted = sorted(indexed - present) return { @@ -459,8 +433,9 @@ def index_repo( store.delete_file_nodes(stale) to_extract: list[SourceFile] = [] + hashes = store.file_hashes() if incremental and not revision_changed else {} for src in files: - if incremental and not revision_changed and store.file_hash(src.rel) == src.digest: + if incremental and not revision_changed and hashes.get(src.rel) == src.digest: skipped.add(src.rel) continue to_extract.append(src) @@ -557,6 +532,9 @@ def index_repo( _ensure_context_nodes(store, config) stitch_residuals = stitch(store, config, repo_root) store.prune_dangling_edges() + from loadpath.architecture.snapshot import persist_findings + + persist_findings(store, config) if incremental: old = [line for line in (store.get_meta("residuals") or "").splitlines() if line] changed = present - skipped diff --git a/src/loadpath/scan.py b/src/loadpath/scan.py new file mode 100644 index 0000000..08828b1 --- /dev/null +++ b/src/loadpath/scan.py @@ -0,0 +1,87 @@ +"""Pruned filesystem walks for index and detect. + +`Path.rglob("*")` descends into `node_modules` / `.git` / `dist` before any +per-file filter runs. On an installed JS app that walk dominates both +`loadpath index` and every architecture load (mtime drift). +""" + +from __future__ import annotations + +import os +from collections.abc import Iterable, Iterator +from pathlib import Path + +# Directory names that never contain first-party Django/React we want to overlay. +SKIP_DIR_NAMES = { + ".git", + "node_modules", + ".venv", + "venv", + "__pycache__", + ".loadpath", + "dist", + "build", + ".mypy_cache", + ".pytest_cache", + "docs", + "documentation", + "website", + "docusaurus", + "storybook", + "starlight_help", + "collected_static", + "staticfiles", + "locale", + "site-packages", + ".next", + ".nuxt", + ".turbo", + ".cache", + "coverage", + "htmlcov", + ".tox", + ".nox", + ".yarn", + ".pnpm-store", +} + +INDEX_EXTENSIONS = {".py", ".ts", ".tsx", ".js", ".jsx", ".html", ".htm", ".graphql", ".gql"} +SKIP_INDEX_NAMES = {"package-lock.json", "yarn.lock", "pnpm-lock.yaml"} +MAX_SOURCE_BYTES = 1_048_576 + + +def skip_dir_name(name: str) -> bool: + return name in SKIP_DIR_NAMES or name.startswith(".") + + +def is_minified_name(name: str) -> bool: + lowered = name.lower() + return ".min." in lowered or lowered.endswith(".bundle.js") or lowered.endswith(".d.ts") + + +def walk_files(root: Path) -> Iterator[Path]: + """Yield files under `root`, never descending into skip directories.""" + root = Path(root) + for dirpath, dirnames, filenames in os.walk(root, topdown=True, followlinks=False): + dirnames[:] = [name for name in dirnames if not skip_dir_name(name)] + base = Path(dirpath) + for name in filenames: + yield base / name + + +def iter_named_files(root: Path, names: Iterable[str]) -> Iterator[Path]: + want = {n.lower() for n in names} + for path in walk_files(root): + if path.name.lower() in want: + yield path + + +def iter_source_paths(root: Path, *, extensions: set[str] | None = None) -> Iterator[Path]: + """First-party source files Loadpath will extract.""" + want = extensions if extensions is not None else INDEX_EXTENSIONS + for path in walk_files(root): + if path.suffix not in want: + continue + if path.name in SKIP_INDEX_NAMES or is_minified_name(path.name): + continue + yield path diff --git a/src/loadpath/static/assets/LayeredGraph3D-kVQDQ1-J.js b/src/loadpath/static/assets/LayeredGraph3D-CXyrC80G.js similarity index 99% rename from src/loadpath/static/assets/LayeredGraph3D-kVQDQ1-J.js rename to src/loadpath/static/assets/LayeredGraph3D-CXyrC80G.js index 08695a5..e2e19f7 100644 --- a/src/loadpath/static/assets/LayeredGraph3D-kVQDQ1-J.js +++ b/src/loadpath/static/assets/LayeredGraph3D-CXyrC80G.js @@ -1,4 +1,4 @@ -import{a as e,c as t,i as n,l as r,n as i,o as a,r as o,s,t as c}from"./index-DhJte9z9.js";var l=r(t(),1),u={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2},d={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},f=1e3,p=1001,m=1002,h=1003,g=1004,_=1005,v=1006,y=1007,b=1008,x=1009,S=1010,C=1011,w=1012,T=1013,E=1014,D=1015,O=1016,k=1017,A=1018,ee=1020,j=35902,M=35899,te=1021,N=1022,ne=1023,re=1026,ie=1027,ae=1028,oe=1029,se=1030,ce=1031,le=1033,P=33776,F=33777,ue=33778,de=33779,fe=35840,pe=35841,me=35842,he=35843,ge=36196,_e=37492,ve=37496,ye=37488,be=37489,xe=37490,Se=37491,Ce=37808,we=37809,Te=37810,Ee=37811,De=37812,Oe=37813,ke=37814,Ae=37815,je=37816,Me=37817,I=37818,Ne=37819,L=37820,Pe=37821,R=36492,Fe=36494,z=36495,B=36283,Ie=36284,Le=36285,Re=36286,ze=2300,Be=2301,Ve=2302,He=2303,Ue=2400,We=2401,Ge=2402,Ke=3200,qe=`srgb`,Je=`srgb-linear`,Ye=`linear`,Xe=`srgb`,Ze=7680,Qe=35044,$e=2e3;function et(e){for(let t=e.length-1;t>=0;--t)if(e[t]>=65535)return!0;return!1}function tt(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function V(e){return document.createElementNS(`http://www.w3.org/1999/xhtml`,e)}function nt(){let e=V(`canvas`);return e.style.display=`block`,e}var rt={};function it(...e){let t=`THREE.`+e.shift();console.log(t,...e)}function at(e){let t=e[0];if(typeof t==`string`&&t.startsWith(`TSL:`)){let t=e[1];t&&t.isStackTrace?e[0]+=` `+t.getLocation():e[1]=`Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.`}return e}function H(...e){e=at(e);let t=`THREE.`+e.shift();{let n=e[0];n&&n.isStackTrace?console.warn(n.getError(t)):console.warn(t,...e)}}function U(...e){e=at(e);let t=`THREE.`+e.shift();{let n=e[0];n&&n.isStackTrace?console.error(n.getError(t)):console.error(t,...e)}}function ot(...e){let t=e.join(` `);t in rt||(rt[t]=!0,H(...e))}function st(e,t,n){return new Promise(function(r,i){function a(){switch(e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0)){case e.WAIT_FAILED:i();break;case e.TIMEOUT_EXPIRED:setTimeout(a,n);break;default:r()}}setTimeout(a,n)})}var ct={0:1,2:6,4:7,3:5,1:0,6:2,7:4,5:3},lt=class{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});let n=this._listeners;n[e]===void 0&&(n[e]=[]),n[e].indexOf(t)===-1&&n[e].push(t)}hasEventListener(e,t){let n=this._listeners;return n!==void 0&&n[e]!==void 0&&n[e].indexOf(t)!==-1}removeEventListener(e,t){let n=this._listeners;if(n===void 0)return;let r=n[e];if(r!==void 0){let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}dispatchEvent(e){let t=this._listeners;if(t===void 0)return;let n=t[e.type];if(n!==void 0){e.target=this;let t=n.slice(0);for(let n=0,r=t.length;n>8&255]+ut[e>>16&255]+ut[e>>24&255]+`-`+ut[t&255]+ut[t>>8&255]+`-`+ut[t>>16&15|64]+ut[t>>24&255]+`-`+ut[n&63|128]+ut[n>>8&255]+`-`+ut[n>>16&255]+ut[n>>24&255]+ut[r&255]+ut[r>>8&255]+ut[r>>16&255]+ut[r>>24&255]).toLowerCase()}function W(e,t,n){return Math.max(t,Math.min(n,e))}function ht(e,t){return(e%t+t)%t}function gt(e,t,n,r,i){return r+(e-t)*(i-r)/(n-t)}function _t(e,t,n){return e===t?0:(n-e)/(t-e)}function vt(e,t,n){return(1-n)*e+n*t}function yt(e,t,n,r){return vt(e,t,1-Math.exp(-n*r))}function bt(e,t=1){return t-Math.abs(ht(e,t*2)-t)}function xt(e,t,n){return e<=t?0:e>=n?1:(e=(e-t)/(n-t),e*e*(3-2*e))}function St(e,t,n){return e<=t?0:e>=n?1:(e=(e-t)/(n-t),e*e*e*(e*(e*6-15)+10))}function Ct(e,t){return e+Math.floor(Math.random()*(t-e+1))}function wt(e,t){return e+Math.random()*(t-e)}function Tt(e){return e*(.5-Math.random())}function Et(e){e!==void 0&&(dt=e);let t=dt+=1831565813;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}function Dt(e){return e*ft}function Ot(e){return e*pt}function kt(e){return!(e&e-1)&&e!==0}function At(e){return 2**Math.ceil(Math.log(e)/Math.LN2)}function jt(e){return 2**Math.floor(Math.log(e)/Math.LN2)}function Mt(e,t,n,r,i){let a=Math.cos,o=Math.sin,s=a(n/2),c=o(n/2),l=a((t+r)/2),u=o((t+r)/2),d=a((t-r)/2),f=o((t-r)/2),p=a((r-t)/2),m=o((r-t)/2);switch(i){case`XYX`:e.set(s*u,c*d,c*f,s*l);break;case`YZY`:e.set(c*f,s*u,c*d,s*l);break;case`ZXZ`:e.set(c*d,c*f,s*u,s*l);break;case`XZX`:e.set(s*u,c*m,c*p,s*l);break;case`YXY`:e.set(c*p,s*u,c*m,s*l);break;case`ZYZ`:e.set(c*m,c*p,s*u,s*l);break;default:H(`MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: `+i)}}function Nt(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return e/4294967295;case Uint16Array:return e/65535;case Uint8Array:return e/255;case Int32Array:return Math.max(e/2147483647,-1);case Int16Array:return Math.max(e/32767,-1);case Int8Array:return Math.max(e/127,-1);default:throw Error(`THREE.MathUtils: Invalid component type.`)}}function G(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return Math.round(e*4294967295);case Uint16Array:return Math.round(e*65535);case Uint8Array:return Math.round(e*255);case Int32Array:return Math.round(e*2147483647);case Int16Array:return Math.round(e*32767);case Int8Array:return Math.round(e*127);default:throw Error(`THREE.MathUtils: Invalid component type.`)}}var Pt={DEG2RAD:ft,RAD2DEG:pt,generateUUID:mt,clamp:W,euclideanModulo:ht,mapLinear:gt,inverseLerp:_t,lerp:vt,damp:yt,pingpong:bt,smoothstep:xt,smootherstep:St,randInt:Ct,randFloat:wt,randFloatSpread:Tt,seededRandom:Et,degToRad:Dt,radToDeg:Ot,isPowerOfTwo:kt,ceilPowerOfTwo:At,floorPowerOfTwo:jt,setQuaternionFromProperEuler:Mt,normalize:G,denormalize:Nt},K=class e{static{e.prototype.isVector2=!0}constructor(e=0,t=0){this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw Error(`THREE.Vector2: index is out of range: `+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw Error(`THREE.Vector2: index is out of range: `+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){let t=this.x,n=this.y,r=e.elements;return this.x=r[0]*t+r[3]*n+r[6],this.y=r[1]*t+r[4]*n+r[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=W(this.x,e.x,t.x),this.y=W(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=W(this.x,e,t),this.y=W(this.y,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(W(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let n=this.dot(e)/t;return Math.acos(W(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,n=this.y-e.y;return t*t+n*n}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){let n=Math.cos(t),r=Math.sin(t),i=this.x-e.x,a=this.y-e.y;return this.x=i*n-a*r+e.x,this.y=i*r+a*n+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}},Ft=class{constructor(e=0,t=0,n=0,r=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=n,this._w=r}static slerpFlat(e,t,n,r,i,a,o){let s=n[r+0],c=n[r+1],l=n[r+2],u=n[r+3],d=i[a+0],f=i[a+1],p=i[a+2],m=i[a+3];if(u!==m||s!==d||c!==f||l!==p){let e=s*d+c*f+l*p+u*m;e<0&&(d=-d,f=-f,p=-p,m=-m,e=-e);let t=1-o;if(e<.9995){let n=Math.acos(e),r=Math.sin(n);t=Math.sin(t*n)/r,o=Math.sin(o*n)/r,s=s*t+d*o,c=c*t+f*o,l=l*t+p*o,u=u*t+m*o}else{s=s*t+d*o,c=c*t+f*o,l=l*t+p*o,u=u*t+m*o;let e=1/Math.sqrt(s*s+c*c+l*l+u*u);s*=e,c*=e,l*=e,u*=e}}e[t]=s,e[t+1]=c,e[t+2]=l,e[t+3]=u}static multiplyQuaternionsFlat(e,t,n,r,i,a){let o=n[r],s=n[r+1],c=n[r+2],l=n[r+3],u=i[a],d=i[a+1],f=i[a+2],p=i[a+3];return e[t]=o*p+l*u+s*f-c*d,e[t+1]=s*p+l*d+c*u-o*f,e[t+2]=c*p+l*f+o*d-s*u,e[t+3]=l*p-o*u-s*d-c*f,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,n,r){return this._x=e,this._y=t,this._z=n,this._w=r,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){let n=e._x,r=e._y,i=e._z,a=e._order,o=Math.cos,s=Math.sin,c=o(n/2),l=o(r/2),u=o(i/2),d=s(n/2),f=s(r/2),p=s(i/2);switch(a){case`XYZ`:this._x=d*l*u+c*f*p,this._y=c*f*u-d*l*p,this._z=c*l*p+d*f*u,this._w=c*l*u-d*f*p;break;case`YXZ`:this._x=d*l*u+c*f*p,this._y=c*f*u-d*l*p,this._z=c*l*p-d*f*u,this._w=c*l*u+d*f*p;break;case`ZXY`:this._x=d*l*u-c*f*p,this._y=c*f*u+d*l*p,this._z=c*l*p+d*f*u,this._w=c*l*u-d*f*p;break;case`ZYX`:this._x=d*l*u-c*f*p,this._y=c*f*u+d*l*p,this._z=c*l*p-d*f*u,this._w=c*l*u+d*f*p;break;case`YZX`:this._x=d*l*u+c*f*p,this._y=c*f*u+d*l*p,this._z=c*l*p-d*f*u,this._w=c*l*u-d*f*p;break;case`XZY`:this._x=d*l*u-c*f*p,this._y=c*f*u-d*l*p,this._z=c*l*p+d*f*u,this._w=c*l*u+d*f*p;break;default:H(`Quaternion: .setFromEuler() encountered an unknown order: `+a)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){let n=t/2,r=Math.sin(n);return this._x=e.x*r,this._y=e.y*r,this._z=e.z*r,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(e){let t=e.elements,n=t[0],r=t[4],i=t[8],a=t[1],o=t[5],s=t[9],c=t[2],l=t[6],u=t[10],d=n+o+u;if(d>0){let e=.5/Math.sqrt(d+1);this._w=.25/e,this._x=(l-s)*e,this._y=(i-c)*e,this._z=(a-r)*e}else if(n>o&&n>u){let e=2*Math.sqrt(1+n-o-u);this._w=(l-s)/e,this._x=.25*e,this._y=(r+a)/e,this._z=(i+c)/e}else if(o>u){let e=2*Math.sqrt(1+o-n-u);this._w=(i-c)/e,this._x=(r+a)/e,this._y=.25*e,this._z=(s+l)/e}else{let e=2*Math.sqrt(1+u-n-o);this._w=(a-r)/e,this._x=(i+c)/e,this._y=(s+l)/e,this._z=.25*e}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let n=e.dot(t)+1;return n<1e-8?(n=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=n):(this._x=0,this._y=-e.z,this._z=e.y,this._w=n)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=n),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(W(this.dot(e),-1,1)))}rotateTowards(e,t){let n=this.angleTo(e);if(n===0)return this;let r=Math.min(1,t/n);return this.slerp(e,r),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x*=e,this._y*=e,this._z*=e,this._w*=e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){let n=e._x,r=e._y,i=e._z,a=e._w,o=t._x,s=t._y,c=t._z,l=t._w;return this._x=n*l+a*o+r*c-i*s,this._y=r*l+a*s+i*o-n*c,this._z=i*l+a*c+n*s-r*o,this._w=a*l-n*o-r*s-i*c,this._onChangeCallback(),this}slerp(e,t){let n=e._x,r=e._y,i=e._z,a=e._w,o=this.dot(e);o<0&&(n=-n,r=-r,i=-i,a=-a,o=-o);let s=1-t;if(o<.9995){let e=Math.acos(o),c=Math.sin(e);s=Math.sin(s*e)/c,t=Math.sin(t*e)/c,this._x=this._x*s+n*t,this._y=this._y*s+r*t,this._z=this._z*s+i*t,this._w=this._w*s+a*t,this._onChangeCallback()}else this._x=this._x*s+n*t,this._y=this._y*s+r*t,this._z=this._z*s+i*t,this._w=this._w*s+a*t,this.normalize();return this}slerpQuaternions(e,t,n){return this.copy(e).slerp(t,n)}random(){let e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),n=Math.random(),r=Math.sqrt(1-n),i=Math.sqrt(n);return this.set(r*Math.sin(e),r*Math.cos(e),i*Math.sin(t),i*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}},q=class e{static{e.prototype.isVector3=!0}constructor(e=0,t=0,n=0){this.x=e,this.y=t,this.z=n}set(e,t,n){return n===void 0&&(n=this.z),this.x=e,this.y=t,this.z=n,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw Error(`THREE.Vector3: index is out of range: `+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw Error(`THREE.Vector3: index is out of range: `+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(Lt.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(Lt.setFromAxisAngle(e,t))}applyMatrix3(e){let t=this.x,n=this.y,r=this.z,i=e.elements;return this.x=i[0]*t+i[3]*n+i[6]*r,this.y=i[1]*t+i[4]*n+i[7]*r,this.z=i[2]*t+i[5]*n+i[8]*r,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){let t=this.x,n=this.y,r=this.z,i=e.elements,a=1/(i[3]*t+i[7]*n+i[11]*r+i[15]);return this.x=(i[0]*t+i[4]*n+i[8]*r+i[12])*a,this.y=(i[1]*t+i[5]*n+i[9]*r+i[13])*a,this.z=(i[2]*t+i[6]*n+i[10]*r+i[14])*a,this}applyQuaternion(e){let t=this.x,n=this.y,r=this.z,i=e.x,a=e.y,o=e.z,s=e.w,c=2*(a*r-o*n),l=2*(o*t-i*r),u=2*(i*n-a*t);return this.x=t+s*c+a*u-o*l,this.y=n+s*l+o*c-i*u,this.z=r+s*u+i*l-a*c,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){let t=this.x,n=this.y,r=this.z,i=e.elements;return this.x=i[0]*t+i[4]*n+i[8]*r,this.y=i[1]*t+i[5]*n+i[9]*r,this.z=i[2]*t+i[6]*n+i[10]*r,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=W(this.x,e.x,t.x),this.y=W(this.y,e.y,t.y),this.z=W(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=W(this.x,e,t),this.y=W(this.y,e,t),this.z=W(this.z,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(W(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){let n=e.x,r=e.y,i=e.z,a=t.x,o=t.y,s=t.z;return this.x=r*s-i*o,this.y=i*a-n*s,this.z=n*o-r*a,this}projectOnVector(e){let t=e.lengthSq();if(t===0)return this.set(0,0,0);let n=e.dot(this)/t;return this.copy(e).multiplyScalar(n)}projectOnPlane(e){return It.copy(this).projectOnVector(e),this.sub(It)}reflect(e){return this.sub(It.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let n=this.dot(e)/t;return Math.acos(W(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,n=this.y-e.y,r=this.z-e.z;return t*t+n*n+r*r}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,n){let r=Math.sin(t)*e;return this.x=r*Math.sin(n),this.y=Math.cos(t)*e,this.z=r*Math.cos(n),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,n){return this.x=e*Math.sin(t),this.y=n,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){let t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){let t=this.setFromMatrixColumn(e,0).length(),n=this.setFromMatrixColumn(e,1).length(),r=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=n,this.z=r,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){let e=Math.random()*Math.PI*2,t=Math.random()*2-1,n=Math.sqrt(1-t*t);return this.x=n*Math.cos(e),this.y=t,this.z=n*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}},It=new q,Lt=new Ft,J=class e{static{e.prototype.isMatrix3=!0}constructor(e,t,n,r,i,a,o,s,c){this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,n,r,i,a,o,s,c)}set(e,t,n,r,i,a,o,s,c){let l=this.elements;return l[0]=e,l[1]=r,l[2]=o,l[3]=t,l[4]=i,l[5]=s,l[6]=n,l[7]=a,l[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){let t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],this}extractBasis(e,t,n){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(e){let t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){let n=e.elements,r=t.elements,i=this.elements,a=n[0],o=n[3],s=n[6],c=n[1],l=n[4],u=n[7],d=n[2],f=n[5],p=n[8],m=r[0],h=r[3],g=r[6],_=r[1],v=r[4],y=r[7],b=r[2],x=r[5],S=r[8];return i[0]=a*m+o*_+s*b,i[3]=a*h+o*v+s*x,i[6]=a*g+o*y+s*S,i[1]=c*m+l*_+u*b,i[4]=c*h+l*v+u*x,i[7]=c*g+l*y+u*S,i[2]=d*m+f*_+p*b,i[5]=d*h+f*v+p*x,i[8]=d*g+f*y+p*S,this}multiplyScalar(e){let t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){let e=this.elements,t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8];return t*a*l-t*o*c-n*i*l+n*o*s+r*i*c-r*a*s}invert(){let e=this.elements,t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8],u=l*a-o*c,d=o*s-l*i,f=c*i-a*s,p=t*u+n*d+r*f;if(p===0)return this.set(0,0,0,0,0,0,0,0,0);let m=1/p;return e[0]=u*m,e[1]=(r*c-l*n)*m,e[2]=(o*n-r*a)*m,e[3]=d*m,e[4]=(l*t-r*s)*m,e[5]=(r*i-o*t)*m,e[6]=f*m,e[7]=(n*s-c*t)*m,e[8]=(a*t-n*i)*m,this}transpose(){let e,t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){let t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,n,r,i,a,o){let s=Math.cos(i),c=Math.sin(i);return this.set(n*s,n*c,-n*(s*a+c*o)+a+e,-r*c,r*s,-r*(-c*a+s*o)+o+t,0,0,1),this}scale(e,t){return ot(`Matrix3: .scale() is deprecated. Use .makeScale() instead.`),this.premultiply(Rt.makeScale(e,t)),this}rotate(e){return ot(`Matrix3: .rotate() is deprecated. Use .makeRotation() instead.`),this.premultiply(Rt.makeRotation(-e)),this}translate(e,t){return ot(`Matrix3: .translate() is deprecated. Use .makeTranslation() instead.`),this.premultiply(Rt.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,n,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){let t=this.elements,n=e.elements;for(let e=0;e<9;e++)if(t[e]!==n[e])return!1;return!0}fromArray(e,t=0){for(let n=0;n<9;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){let n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e}clone(){return new this.constructor().fromArray(this.elements)}},Rt=new J,zt=new J().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),Bt=new J().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function Vt(){let e={enabled:!0,workingColorSpace:Je,spaces:{},convert:function(e,t,n){return this.enabled===!1||t===n||!t||!n?e:(this.spaces[t].transfer===`srgb`&&(e.r=Ht(e.r),e.g=Ht(e.g),e.b=Ht(e.b)),this.spaces[t].primaries!==this.spaces[n].primaries&&(e.applyMatrix3(this.spaces[t].toXYZ),e.applyMatrix3(this.spaces[n].fromXYZ)),this.spaces[n].transfer===`srgb`&&(e.r=Ut(e.r),e.g=Ut(e.g),e.b=Ut(e.b)),e)},workingToColorSpace:function(e,t){return this.convert(e,this.workingColorSpace,t)},colorSpaceToWorking:function(e,t){return this.convert(e,t,this.workingColorSpace)},getPrimaries:function(e){return this.spaces[e].primaries},getTransfer:function(e){return e===``?Ye:this.spaces[e].transfer},getToneMappingMode:function(e){return this.spaces[e].outputColorSpaceConfig.toneMappingMode||`standard`},getLuminanceCoefficients:function(e,t=this.workingColorSpace){return e.fromArray(this.spaces[t].luminanceCoefficients)},define:function(e){Object.assign(this.spaces,e)},_getMatrix:function(e,t,n){return e.copy(this.spaces[t].toXYZ).multiply(this.spaces[n].fromXYZ)},_getDrawingBufferColorSpace:function(e){return this.spaces[e].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(e=this.workingColorSpace){return this.spaces[e].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(t,n){return ot(`ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace().`),e.workingToColorSpace(t,n)},toWorkingColorSpace:function(t,n){return ot(`ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking().`),e.colorSpaceToWorking(t,n)}},t=[.64,.33,.3,.6,.15,.06],n=[.2126,.7152,.0722],r=[.3127,.329];return e.define({[Je]:{primaries:t,whitePoint:r,transfer:Ye,toXYZ:zt,fromXYZ:Bt,luminanceCoefficients:n,workingColorSpaceConfig:{unpackColorSpace:qe},outputColorSpaceConfig:{drawingBufferColorSpace:qe}},[qe]:{primaries:t,whitePoint:r,transfer:Xe,toXYZ:zt,fromXYZ:Bt,luminanceCoefficients:n,outputColorSpaceConfig:{drawingBufferColorSpace:qe}}}),e}var Y=Vt();function Ht(e){return e<.04045?e*.0773993808:(e*.9478672986+.0521327014)**2.4}function Ut(e){return e<.0031308?e*12.92:1.055*e**.41666-.055}var Wt,Gt=class{static getDataURL(e,t=`image/png`){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>`u`)return e.src;let n;if(e instanceof HTMLCanvasElement)n=e;else{Wt===void 0&&(Wt=V(`canvas`)),Wt.width=e.width,Wt.height=e.height;let t=Wt.getContext(`2d`);e instanceof ImageData?t.putImageData(e,0,0):t.drawImage(e,0,0,e.width,e.height),n=Wt}return n.toDataURL(t)}static sRGBToLinear(e){if(typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap){let t=V(`canvas`);t.width=e.width,t.height=e.height;let n=t.getContext(`2d`);n.drawImage(e,0,0,e.width,e.height);let r=n.getImageData(0,0,e.width,e.height),i=r.data;for(let e=0;e1),this.pmremVersion=0,this.normalized=!1}get width(){return this.source.getSize(Xt).x}get height(){return this.source.getSize(Xt).y}get depth(){return this.source.getSize(Xt).z}get image(){return this.source.data}set image(e){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.normalized=e.normalized,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(let t in e){let n=e[t];if(n===void 0){H(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}let r=this[t];if(r===void 0){H(`Texture.setValues(): property '${t}' does not exist.`);continue}r&&n&&r.isVector2&&n.isVector2||r&&n&&r.isVector3&&n.isVector3||r&&n&&r.isMatrix3&&n.isMatrix3?r.copy(n):this[t]=n}}toJSON(e){let t=e===void 0||typeof e==`string`;if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];let n={metadata:{version:4.7,type:`Texture`,generator:`Texture.toJSON`},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,normalized:this.normalized,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(n.userData=this.userData),t||(e.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:`dispose`})}transformUv(e){if(this.mapping!==300)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case f:e.x-=Math.floor(e.x);break;case p:e.x=e.x<0?0:1;break;case m:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x-=Math.floor(e.x)}if(e.y<0||e.y>1)switch(this.wrapT){case f:e.y-=Math.floor(e.y);break;case p:e.y=e.y<0?0:1;break;case m:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y-=Math.floor(e.y)}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}};Zt.DEFAULT_IMAGE=null,Zt.DEFAULT_MAPPING=300,Zt.DEFAULT_ANISOTROPY=1;var Qt=class e{static{e.prototype.isVector4=!0}constructor(e=0,t=0,n=0,r=1){this.x=e,this.y=t,this.z=n,this.w=r}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,n,r){return this.x=e,this.y=t,this.z=n,this.w=r,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw Error(`THREE.Vector4: index is out of range: `+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw Error(`THREE.Vector4: index is out of range: `+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w===void 0?1:e.w,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){let t=this.x,n=this.y,r=this.z,i=this.w,a=e.elements;return this.x=a[0]*t+a[4]*n+a[8]*r+a[12]*i,this.y=a[1]*t+a[5]*n+a[9]*r+a[13]*i,this.z=a[2]*t+a[6]*n+a[10]*r+a[14]*i,this.w=a[3]*t+a[7]*n+a[11]*r+a[15]*i,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);let t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,n,r,i,a=.01,o=.1,s=e.elements,c=s[0],l=s[4],u=s[8],d=s[1],f=s[5],p=s[9],m=s[2],h=s[6],g=s[10];if(Math.abs(l-d)s&&e>_?e_?s1);this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,n=e.textures.length;t>>0}enable(e){this.mask|=1<1){for(let e=0;e1){for(let e=0;e0&&(r.userData=this.userData),r.layers=this.layers.mask,r.matrix=this.matrix.toArray(),r.up=this.up.toArray(),this.pivot!==null&&(r.pivot=this.pivot.toArray()),this.matrixAutoUpdate===!1&&(r.matrixAutoUpdate=!1),this.morphTargetDictionary!==void 0&&(r.morphTargetDictionary=Object.assign({},this.morphTargetDictionary)),this.morphTargetInfluences!==void 0&&(r.morphTargetInfluences=this.morphTargetInfluences.slice()),this.isInstancedMesh&&(r.type=`InstancedMesh`,r.count=this.count,r.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(r.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(r.type=`BatchedMesh`,r.perObjectFrustumCulled=this.perObjectFrustumCulled,r.sortObjects=this.sortObjects,r.drawRanges=this._drawRanges,r.reservedRanges=this._reservedRanges,r.geometryInfo=this._geometryInfo.map(e=>({...e,boundingBox:e.boundingBox?e.boundingBox.toJSON():void 0,boundingSphere:e.boundingSphere?e.boundingSphere.toJSON():void 0})),r.instanceInfo=this._instanceInfo.map(e=>({...e})),r.availableInstanceIds=this._availableInstanceIds.slice(),r.availableGeometryIds=this._availableGeometryIds.slice(),r.nextIndexStart=this._nextIndexStart,r.nextVertexStart=this._nextVertexStart,r.geometryCount=this._geometryCount,r.maxInstanceCount=this._maxInstanceCount,r.maxVertexCount=this._maxVertexCount,r.maxIndexCount=this._maxIndexCount,r.geometryInitialized=this._geometryInitialized,r.matricesTexture=this._matricesTexture.toJSON(e),r.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(r.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(r.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(r.boundingBox=this.boundingBox.toJSON()));function i(t,n){return t[n.uuid]===void 0&&(t[n.uuid]=n.toJSON(e)),n.uuid}if(this.isScene)this.background&&(this.background.isColor?r.background=this.background.toJSON():this.background.isTexture&&(r.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(r.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){r.geometry=i(e.geometries,this.geometry);let t=this.geometry.parameters;if(t!==void 0&&t.shapes!==void 0){let n=t.shapes;if(Array.isArray(n))for(let t=0,r=n.length;t0){r.children=[];for(let t=0;t0){r.animations=[];for(let t=0;t0&&(n.geometries=t),r.length>0&&(n.materials=r),i.length>0&&(n.textures=i),o.length>0&&(n.images=o),s.length>0&&(n.shapes=s),c.length>0&&(n.skeletons=c),l.length>0&&(n.animations=l),u.length>0&&(n.nodes=u)}return n.object=r,n;function a(e){let t=[];for(let n in e){let r=e[n];delete r.metadata,t.push(r)}return t}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.pivot=e.pivot===null?null:e.pivot.clone(),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.static=e.static,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let t=0;t.025?(c.inputState.pinching=!1,this.dispatchEvent({type:`pinchend`,handedness:e.handedness,target:this})):!c.inputState.pinching&&o<=.015&&(c.inputState.pinching=!0,this.dispatchEvent({type:`pinchstart`,handedness:e.handedness,target:this}))}else s!==null&&e.gripSpace&&(i=t.getPose(e.gripSpace,n),i!==null&&(s.matrix.fromArray(i.transform.matrix),s.matrix.decompose(s.position,s.rotation,s.scale),s.matrixWorldNeedsUpdate=!0,i.linearVelocity?(s.hasLinearVelocity=!0,s.linearVelocity.copy(i.linearVelocity)):s.hasLinearVelocity=!1,i.angularVelocity?(s.hasAngularVelocity=!0,s.angularVelocity.copy(i.angularVelocity)):s.hasAngularVelocity=!1,s.eventsEnabled&&s.dispatchEvent({type:`gripUpdated`,data:e,target:this})));o!==null&&(r=t.getPose(e.targetRaySpace,n),r===null&&i!==null&&(r=i),r!==null&&(o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,r.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(r.linearVelocity)):o.hasLinearVelocity=!1,r.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(r.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(Nn)))}return o!==null&&(o.visible=r!==null),s!==null&&(s.visible=i!==null),c!==null&&(c.visible=a!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){let n=new Mn;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}},Fn={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},In={h:0,s:0,l:0},Ln={h:0,s:0,l:0};function Rn(e,t,n){return n<0&&(n+=1),n>1&&--n,n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*6*(2/3-n):e}var X=class{constructor(e,t,n){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,n)}set(e,t,n){if(t===void 0&&n===void 0){let t=e;t&&t.isColor?this.copy(t):typeof t==`number`?this.setHex(t):typeof t==`string`&&this.setStyle(t)}else this.setRGB(e,t,n);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=qe){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,Y.colorSpaceToWorking(this,t),this}setRGB(e,t,n,r=Y.workingColorSpace){return this.r=e,this.g=t,this.b=n,Y.colorSpaceToWorking(this,r),this}setHSL(e,t,n,r=Y.workingColorSpace){if(e=ht(e,1),t=W(t,0,1),n=W(n,0,1),t===0)this.r=this.g=this.b=n;else{let r=n<=.5?n*(1+t):n+t-n*t,i=2*n-r;this.r=Rn(i,r,e+1/3),this.g=Rn(i,r,e),this.b=Rn(i,r,e-1/3)}return Y.colorSpaceToWorking(this,r),this}setStyle(e,t=qe){function n(t){t!==void 0&&parseFloat(t)<1&&H(`Color: Alpha component of `+e+` will be ignored.`)}let r;if(r=/^(\w+)\(([^\)]*)\)/.exec(e)){let i,a=r[1],o=r[2];switch(a){case`rgb`:case`rgba`:if(i=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(i[4]),this.setRGB(Math.min(255,parseInt(i[1],10))/255,Math.min(255,parseInt(i[2],10))/255,Math.min(255,parseInt(i[3],10))/255,t);if(i=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(i[4]),this.setRGB(Math.min(100,parseInt(i[1],10))/100,Math.min(100,parseInt(i[2],10))/100,Math.min(100,parseInt(i[3],10))/100,t);break;case`hsl`:case`hsla`:if(i=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(i[4]),this.setHSL(parseFloat(i[1])/360,parseFloat(i[2])/100,parseFloat(i[3])/100,t);break;default:H(`Color: Unknown color model `+e)}}else if(r=/^\#([A-Fa-f\d]+)$/.exec(e)){let n=r[1],i=n.length;if(i===3)return this.setRGB(parseInt(n.charAt(0),16)/15,parseInt(n.charAt(1),16)/15,parseInt(n.charAt(2),16)/15,t);if(i===6)return this.setHex(parseInt(n,16),t);H(`Color: Invalid hex color `+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=qe){let n=Fn[e.toLowerCase()];return n===void 0?H(`Color: Unknown color `+e):this.setHex(n,t),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=Ht(e.r),this.g=Ht(e.g),this.b=Ht(e.b),this}copyLinearToSRGB(e){return this.r=Ut(e.r),this.g=Ut(e.g),this.b=Ut(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=qe){return Y.workingToColorSpace(zn.copy(this),e),Math.round(W(zn.r*255,0,255))*65536+Math.round(W(zn.g*255,0,255))*256+Math.round(W(zn.b*255,0,255))}getHexString(e=qe){return(`000000`+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=Y.workingColorSpace){Y.workingToColorSpace(zn.copy(this),t);let n=zn.r,r=zn.g,i=zn.b,a=Math.max(n,r,i),o=Math.min(n,r,i),s,c,l=(o+a)/2;if(o===a)s=0,c=0;else{let e=a-o;switch(c=l<=.5?e/(a+o):e/(2-a-o),a){case n:s=(r-i)/e+(r0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}},Hn=new q,Un=new q,Wn=new q,Gn=new q,Kn=new q,qn=new q,Jn=new q,Yn=new q,Xn=new q,Zn=new q,Qn=new Qt,$n=new Qt,er=new Qt,tr=class e{constructor(e=new q,t=new q,n=new q){this.a=e,this.b=t,this.c=n}static getNormal(e,t,n,r){r.subVectors(n,t),Hn.subVectors(e,t),r.cross(Hn);let i=r.lengthSq();return i>0?r.multiplyScalar(1/Math.sqrt(i)):r.set(0,0,0)}static getBarycoord(e,t,n,r,i){Hn.subVectors(r,t),Un.subVectors(n,t),Wn.subVectors(e,t);let a=Hn.dot(Hn),o=Hn.dot(Un),s=Hn.dot(Wn),c=Un.dot(Un),l=Un.dot(Wn),u=a*c-o*o;if(u===0)return i.set(0,0,0),null;let d=1/u,f=(c*s-o*l)*d,p=(a*l-o*s)*d;return i.set(1-f-p,p,f)}static containsPoint(e,t,n,r){return this.getBarycoord(e,t,n,r,Gn)!==null&&Gn.x>=0&&Gn.y>=0&&Gn.x+Gn.y<=1}static getInterpolation(e,t,n,r,i,a,o,s){return this.getBarycoord(e,t,n,r,Gn)===null?(s.x=0,s.y=0,`z`in s&&(s.z=0),`w`in s&&(s.w=0),null):(s.setScalar(0),s.addScaledVector(i,Gn.x),s.addScaledVector(a,Gn.y),s.addScaledVector(o,Gn.z),s)}static getInterpolatedAttribute(e,t,n,r,i,a){return Qn.setScalar(0),$n.setScalar(0),er.setScalar(0),Qn.fromBufferAttribute(e,t),$n.fromBufferAttribute(e,n),er.fromBufferAttribute(e,r),a.setScalar(0),a.addScaledVector(Qn,i.x),a.addScaledVector($n,i.y),a.addScaledVector(er,i.z),a}static isFrontFacing(e,t,n,r){return Hn.subVectors(n,t),Un.subVectors(e,t),Hn.cross(Un).dot(r)<0}set(e,t,n){return this.a.copy(e),this.b.copy(t),this.c.copy(n),this}setFromPointsAndIndices(e,t,n,r){return this.a.copy(e[t]),this.b.copy(e[n]),this.c.copy(e[r]),this}setFromAttributeAndIndices(e,t,n,r){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,n),this.c.fromBufferAttribute(e,r),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return Hn.subVectors(this.c,this.b),Un.subVectors(this.a,this.b),Hn.cross(Un).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(t){return e.getNormal(this.a,this.b,this.c,t)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(t,n){return e.getBarycoord(t,this.a,this.b,this.c,n)}getInterpolation(t,n,r,i,a){return e.getInterpolation(t,this.a,this.b,this.c,n,r,i,a)}containsPoint(t){return e.containsPoint(t,this.a,this.b,this.c)}isFrontFacing(t){return e.isFrontFacing(this.a,this.b,this.c,t)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){let n=this.a,r=this.b,i=this.c,a,o;Kn.subVectors(r,n),qn.subVectors(i,n),Yn.subVectors(e,n);let s=Kn.dot(Yn),c=qn.dot(Yn);if(s<=0&&c<=0)return t.copy(n);Xn.subVectors(e,r);let l=Kn.dot(Xn),u=qn.dot(Xn);if(l>=0&&u<=l)return t.copy(r);let d=s*u-l*c;if(d<=0&&s>=0&&l<=0)return a=s/(s-l),t.copy(n).addScaledVector(Kn,a);Zn.subVectors(e,i);let f=Kn.dot(Zn),p=qn.dot(Zn);if(p>=0&&f<=p)return t.copy(i);let m=f*c-s*p;if(m<=0&&c>=0&&p<=0)return o=c/(c-p),t.copy(n).addScaledVector(qn,o);let h=l*p-f*u;if(h<=0&&u-l>=0&&f-p>=0)return Jn.subVectors(i,r),o=(u-l)/(u-l+(f-p)),t.copy(r).addScaledVector(Jn,o);let g=1/(h+m+d);return a=m*g,o=d*g,t.copy(n).addScaledVector(Kn,a).addScaledVector(qn,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}},nr=class{constructor(e=new q(1/0,1/0,1/0),t=new q(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,n=e.length;t=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,ir),ir.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,n;return e.normal.x>0?(t=e.normal.x*this.min.x,n=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,n=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,n+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,n+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,n+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,n+=e.normal.z*this.min.z),t<=-e.constant&&n>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(fr),pr.subVectors(this.max,fr),or.subVectors(e.a,fr),sr.subVectors(e.b,fr),cr.subVectors(e.c,fr),lr.subVectors(sr,or),ur.subVectors(cr,sr),dr.subVectors(or,cr);let t=[0,-lr.z,lr.y,0,-ur.z,ur.y,0,-dr.z,dr.y,lr.z,0,-lr.x,ur.z,0,-ur.x,dr.z,0,-dr.x,-lr.y,lr.x,0,-ur.y,ur.x,0,-dr.y,dr.x,0];return!gr(t,or,sr,cr,pr)||(t=[1,0,0,0,1,0,0,0,1],!gr(t,or,sr,cr,pr))?!1:(mr.crossVectors(lr,ur),t=[mr.x,mr.y,mr.z],gr(t,or,sr,cr,pr))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,ir).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(ir).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(rr[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),rr[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),rr[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),rr[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),rr[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),rr[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),rr[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),rr[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(rr),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(e){return this.min.fromArray(e.min),this.max.fromArray(e.max),this}},rr=[new q,new q,new q,new q,new q,new q,new q,new q],ir=new q,ar=new nr,or=new q,sr=new q,cr=new q,lr=new q,ur=new q,dr=new q,fr=new q,pr=new q,mr=new q,hr=new q;function gr(e,t,n,r,i){for(let a=0,o=e.length-3;a<=o;a+=3){hr.fromArray(e,a);let o=i.x*Math.abs(hr.x)+i.y*Math.abs(hr.y)+i.z*Math.abs(hr.z),s=t.dot(hr),c=n.dot(hr),l=r.dot(hr);if(Math.max(-Math.max(s,c,l),Math.min(s,c,l))>o)return!1}return!0}var _r=new q,vr=new K,yr=0,br=class extends lt{constructor(e,t,n=!1){if(super(),Array.isArray(e))throw TypeError(`THREE.BufferAttribute: array should be a Typed Array.`);this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:yr++}),this.name=``,this.array=e,this.itemSize=t,this.count=e===void 0?0:e.length/t,this.normalized=n,this.usage=Qe,this.updateRanges=[],this.gpuType=D,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,n){e*=this.itemSize,n*=t.itemSize;for(let r=0,i=this.itemSize;rthis.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius*=e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;Tr.subVectors(e,this.center);let t=Tr.lengthSq();if(t>this.radius*this.radius){let e=Math.sqrt(t),n=(e-this.radius)*.5;this.center.addScaledVector(Tr,n/e),this.radius+=n}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(Er.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Tr.copy(e.center).add(Er)),this.expandByPoint(Tr.copy(e.center).sub(Er))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(e){return this.radius=e.radius,this.center.fromArray(e.center),this}},Or=0,kr=new rn,Ar=new jn,jr=new q,Mr=new nr,Nr=new nr,Pr=new q,Fr=class e extends lt{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:Or++}),this.uuid=mt(),this.name=``,this.type=`BufferGeometry`,this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={},this._transformed=!1}getIndex(){return this.index}setIndex(e){return this.index=Array.isArray(e)?new(et(e)?Sr:xr)(e,1):e,this}setIndirect(e,t=0){return this.indirect=e,this.indirectOffset=t,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return this.attributes[e]!==void 0}addGroup(e,t,n=0){this.groups.push({start:e,count:t,materialIndex:n})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){let t=this.attributes.position;t!==void 0&&(t.applyMatrix4(e),t.needsUpdate=!0);let n=this.attributes.normal;if(n!==void 0){let t=new J().getNormalMatrix(e);n.applyNormalMatrix(t),n.needsUpdate=!0}let r=this.attributes.tangent;return r!==void 0&&(r.transformDirection(e),r.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this._transformed=!0,this}applyQuaternion(e){return kr.makeRotationFromQuaternion(e),this.applyMatrix4(kr),this}rotateX(e){return kr.makeRotationX(e),this.applyMatrix4(kr),this}rotateY(e){return kr.makeRotationY(e),this.applyMatrix4(kr),this}rotateZ(e){return kr.makeRotationZ(e),this.applyMatrix4(kr),this}translate(e,t,n){return kr.makeTranslation(e,t,n),this.applyMatrix4(kr),this}scale(e,t,n){return kr.makeScale(e,t,n),this.applyMatrix4(kr),this}lookAt(e){return Ar.lookAt(e),Ar.updateMatrix(),this.applyMatrix4(Ar.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(jr).negate(),this.translate(jr.x,jr.y,jr.z),this}setFromPoints(e){let t=this.getAttribute(`position`);if(t===void 0){let t=[];for(let n=0,r=e.length;nt.count&&H(`BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.`),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new nr);let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){U(`BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.`,this),this.boundingBox.set(new q(-1/0,-1/0,-1/0),new q(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let e=0,n=t.length;e0&&(e.userData=this.userData),this.parameters!==void 0&&this._transformed!==!0){let t=this.parameters;for(let n in t)t[n]!==void 0&&(e[n]=t[n]);return e}e.data={attributes:{}};let t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});let n=this.attributes;for(let t in n){let r=n[t];e.data.attributes[t]=r.toJSON(e.data)}let r={},i=!1;for(let t in this.morphAttributes){let n=this.morphAttributes[t],a=[];for(let t=0,r=n.length;t0&&(r[t]=a,i=!0)}i&&(e.data.morphAttributes=r,e.data.morphTargetsRelative=this.morphTargetsRelative);let a=this.groups;a.length>0&&(e.data.groups=JSON.parse(JSON.stringify(a)));let o=this.boundingSphere;return o!==null&&(e.data.boundingSphere=o.toJSON()),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;let t={};this.name=e.name;let n=e.index;n!==null&&this.setIndex(n.clone());let r=e.attributes;for(let e in r){let n=r[e];this.setAttribute(e,n.clone(t))}let i=e.morphAttributes;for(let e in i){let n=[],r=i[e];for(let e=0,i=r.length;e0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(let t in e){let n=e[t];if(n===void 0){H(`Material: parameter '${t}' has value of undefined.`);continue}let r=this[t];if(r===void 0){H(`Material: '${t}' is not a property of THREE.${this.type}.`);continue}r&&r.isColor?r.set(n):r&&r.isVector2&&n&&n.isVector2||r&&r.isEuler&&n&&n.isEuler||r&&r.isVector3&&n&&n.isVector3?r.copy(n):this[t]=n}}toJSON(e){let t=e===void 0||typeof e==`string`;t&&(e={textures:{},images:{}});let n={metadata:{version:4.7,type:`Material`,generator:`Material.toJSON`}};n.uuid=this.uuid,n.type=this.type,this.name!==``&&(n.name=this.name),this.color&&this.color.isColor&&(n.color=this.color.getHex()),this.roughness!==void 0&&(n.roughness=this.roughness),this.metalness!==void 0&&(n.metalness=this.metalness),this.sheen!==void 0&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(n.shininess=this.shininess),this.clearcoat!==void 0&&(n.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(n.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(n.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),this.dispersion!==void 0&&(n.dispersion=this.dispersion),this.iridescence!==void 0&&(n.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(n.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(n.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(n.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(n.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(n.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(n.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(e).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(e).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(e).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(e).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(e).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(n.combine=this.combine)),this.envMapRotation!==void 0&&(n.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(n.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(n.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(n.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(n.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(n.size=this.size),this.shadowSide!==null&&(n.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(n.sizeAttenuation=this.sizeAttenuation),this.blending!==1&&(n.blending=this.blending),this.side!==0&&(n.side=this.side),this.vertexColors===!0&&(n.vertexColors=!0),this.opacity<1&&(n.opacity=this.opacity),this.transparent===!0&&(n.transparent=!0),this.blendSrc!==204&&(n.blendSrc=this.blendSrc),this.blendDst!==205&&(n.blendDst=this.blendDst),this.blendEquation!==100&&(n.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(n.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(n.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(n.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(n.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(n.blendAlpha=this.blendAlpha),this.depthFunc!==3&&(n.depthFunc=this.depthFunc),this.depthTest===!1&&(n.depthTest=this.depthTest),this.depthWrite===!1&&(n.depthWrite=this.depthWrite),this.colorWrite===!1&&(n.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(n.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==519&&(n.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(n.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(n.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==7680&&(n.stencilFail=this.stencilFail),this.stencilZFail!==7680&&(n.stencilZFail=this.stencilZFail),this.stencilZPass!==7680&&(n.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(n.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(n.rotation=this.rotation),this.polygonOffset===!0&&(n.polygonOffset=!0),this.polygonOffsetFactor!==0&&(n.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(n.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(n.linewidth=this.linewidth),this.dashSize!==void 0&&(n.dashSize=this.dashSize),this.gapSize!==void 0&&(n.gapSize=this.gapSize),this.scale!==void 0&&(n.scale=this.scale),this.dithering===!0&&(n.dithering=!0),this.alphaTest>0&&(n.alphaTest=this.alphaTest),this.alphaHash===!0&&(n.alphaHash=!0),this.alphaToCoverage===!0&&(n.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(n.premultipliedAlpha=!0),this.forceSinglePass===!0&&(n.forceSinglePass=!0),this.allowOverride===!1&&(n.allowOverride=!1),this.wireframe===!0&&(n.wireframe=!0),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!==`round`&&(n.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!==`round`&&(n.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(n.flatShading=!0),this.visible===!1&&(n.visible=!1),this.toneMapped===!1&&(n.toneMapped=!1),this.fog===!1&&(n.fog=!1),Object.keys(this.userData).length>0&&(n.userData=this.userData);function r(e){let t=[];for(let n in e){let r=e[n];delete r.metadata,t.push(r)}return t}if(t){let t=r(e.textures),i=r(e.images);t.length>0&&(n.textures=t),i.length>0&&(n.images=i)}return n}fromJSON(e,t){if(e.uuid!==void 0&&(this.uuid=e.uuid),e.name!==void 0&&(this.name=e.name),e.color!==void 0&&this.color!==void 0&&this.color.setHex(e.color),e.roughness!==void 0&&(this.roughness=e.roughness),e.metalness!==void 0&&(this.metalness=e.metalness),e.sheen!==void 0&&(this.sheen=e.sheen),e.sheenColor!==void 0&&(this.sheenColor=new X().setHex(e.sheenColor)),e.sheenRoughness!==void 0&&(this.sheenRoughness=e.sheenRoughness),e.emissive!==void 0&&this.emissive!==void 0&&this.emissive.setHex(e.emissive),e.specular!==void 0&&this.specular!==void 0&&this.specular.setHex(e.specular),e.specularIntensity!==void 0&&(this.specularIntensity=e.specularIntensity),e.specularColor!==void 0&&this.specularColor!==void 0&&this.specularColor.setHex(e.specularColor),e.shininess!==void 0&&(this.shininess=e.shininess),e.clearcoat!==void 0&&(this.clearcoat=e.clearcoat),e.clearcoatRoughness!==void 0&&(this.clearcoatRoughness=e.clearcoatRoughness),e.dispersion!==void 0&&(this.dispersion=e.dispersion),e.iridescence!==void 0&&(this.iridescence=e.iridescence),e.iridescenceIOR!==void 0&&(this.iridescenceIOR=e.iridescenceIOR),e.iridescenceThicknessRange!==void 0&&(this.iridescenceThicknessRange=e.iridescenceThicknessRange),e.transmission!==void 0&&(this.transmission=e.transmission),e.thickness!==void 0&&(this.thickness=e.thickness),e.attenuationDistance!==void 0&&(this.attenuationDistance=e.attenuationDistance),e.attenuationColor!==void 0&&this.attenuationColor!==void 0&&this.attenuationColor.setHex(e.attenuationColor),e.anisotropy!==void 0&&(this.anisotropy=e.anisotropy),e.anisotropyRotation!==void 0&&(this.anisotropyRotation=e.anisotropyRotation),e.fog!==void 0&&(this.fog=e.fog),e.flatShading!==void 0&&(this.flatShading=e.flatShading),e.blending!==void 0&&(this.blending=e.blending),e.combine!==void 0&&(this.combine=e.combine),e.side!==void 0&&(this.side=e.side),e.shadowSide!==void 0&&(this.shadowSide=e.shadowSide),e.opacity!==void 0&&(this.opacity=e.opacity),e.transparent!==void 0&&(this.transparent=e.transparent),e.alphaTest!==void 0&&(this.alphaTest=e.alphaTest),e.alphaHash!==void 0&&(this.alphaHash=e.alphaHash),e.depthFunc!==void 0&&(this.depthFunc=e.depthFunc),e.depthTest!==void 0&&(this.depthTest=e.depthTest),e.depthWrite!==void 0&&(this.depthWrite=e.depthWrite),e.colorWrite!==void 0&&(this.colorWrite=e.colorWrite),e.blendSrc!==void 0&&(this.blendSrc=e.blendSrc),e.blendDst!==void 0&&(this.blendDst=e.blendDst),e.blendEquation!==void 0&&(this.blendEquation=e.blendEquation),e.blendSrcAlpha!==void 0&&(this.blendSrcAlpha=e.blendSrcAlpha),e.blendDstAlpha!==void 0&&(this.blendDstAlpha=e.blendDstAlpha),e.blendEquationAlpha!==void 0&&(this.blendEquationAlpha=e.blendEquationAlpha),e.blendColor!==void 0&&this.blendColor!==void 0&&this.blendColor.setHex(e.blendColor),e.blendAlpha!==void 0&&(this.blendAlpha=e.blendAlpha),e.stencilWriteMask!==void 0&&(this.stencilWriteMask=e.stencilWriteMask),e.stencilFunc!==void 0&&(this.stencilFunc=e.stencilFunc),e.stencilRef!==void 0&&(this.stencilRef=e.stencilRef),e.stencilFuncMask!==void 0&&(this.stencilFuncMask=e.stencilFuncMask),e.stencilFail!==void 0&&(this.stencilFail=e.stencilFail),e.stencilZFail!==void 0&&(this.stencilZFail=e.stencilZFail),e.stencilZPass!==void 0&&(this.stencilZPass=e.stencilZPass),e.stencilWrite!==void 0&&(this.stencilWrite=e.stencilWrite),e.wireframe!==void 0&&(this.wireframe=e.wireframe),e.wireframeLinewidth!==void 0&&(this.wireframeLinewidth=e.wireframeLinewidth),e.wireframeLinecap!==void 0&&(this.wireframeLinecap=e.wireframeLinecap),e.wireframeLinejoin!==void 0&&(this.wireframeLinejoin=e.wireframeLinejoin),e.rotation!==void 0&&(this.rotation=e.rotation),e.linewidth!==void 0&&(this.linewidth=e.linewidth),e.dashSize!==void 0&&(this.dashSize=e.dashSize),e.gapSize!==void 0&&(this.gapSize=e.gapSize),e.scale!==void 0&&(this.scale=e.scale),e.polygonOffset!==void 0&&(this.polygonOffset=e.polygonOffset),e.polygonOffsetFactor!==void 0&&(this.polygonOffsetFactor=e.polygonOffsetFactor),e.polygonOffsetUnits!==void 0&&(this.polygonOffsetUnits=e.polygonOffsetUnits),e.dithering!==void 0&&(this.dithering=e.dithering),e.alphaToCoverage!==void 0&&(this.alphaToCoverage=e.alphaToCoverage),e.premultipliedAlpha!==void 0&&(this.premultipliedAlpha=e.premultipliedAlpha),e.forceSinglePass!==void 0&&(this.forceSinglePass=e.forceSinglePass),e.allowOverride!==void 0&&(this.allowOverride=e.allowOverride),e.visible!==void 0&&(this.visible=e.visible),e.toneMapped!==void 0&&(this.toneMapped=e.toneMapped),e.userData!==void 0&&(this.userData=e.userData),e.vertexColors!==void 0&&(this.vertexColors=typeof e.vertexColors==`number`?e.vertexColors>0:e.vertexColors),e.size!==void 0&&(this.size=e.size),e.sizeAttenuation!==void 0&&(this.sizeAttenuation=e.sizeAttenuation),e.map!==void 0&&(this.map=t[e.map]||null),e.matcap!==void 0&&(this.matcap=t[e.matcap]||null),e.alphaMap!==void 0&&(this.alphaMap=t[e.alphaMap]||null),e.bumpMap!==void 0&&(this.bumpMap=t[e.bumpMap]||null),e.bumpScale!==void 0&&(this.bumpScale=e.bumpScale),e.normalMap!==void 0&&(this.normalMap=t[e.normalMap]||null),e.normalMapType!==void 0&&(this.normalMapType=e.normalMapType),e.normalScale!==void 0){let t=e.normalScale;Array.isArray(t)===!1&&(t=[t,t]),this.normalScale=new K().fromArray(t)}return e.displacementMap!==void 0&&(this.displacementMap=t[e.displacementMap]||null),e.displacementScale!==void 0&&(this.displacementScale=e.displacementScale),e.displacementBias!==void 0&&(this.displacementBias=e.displacementBias),e.roughnessMap!==void 0&&(this.roughnessMap=t[e.roughnessMap]||null),e.metalnessMap!==void 0&&(this.metalnessMap=t[e.metalnessMap]||null),e.emissiveMap!==void 0&&(this.emissiveMap=t[e.emissiveMap]||null),e.emissiveIntensity!==void 0&&(this.emissiveIntensity=e.emissiveIntensity),e.specularMap!==void 0&&(this.specularMap=t[e.specularMap]||null),e.specularIntensityMap!==void 0&&(this.specularIntensityMap=t[e.specularIntensityMap]||null),e.specularColorMap!==void 0&&(this.specularColorMap=t[e.specularColorMap]||null),e.envMap!==void 0&&(this.envMap=t[e.envMap]||null),e.envMapRotation!==void 0&&this.envMapRotation.fromArray(e.envMapRotation),e.envMapIntensity!==void 0&&(this.envMapIntensity=e.envMapIntensity),e.reflectivity!==void 0&&(this.reflectivity=e.reflectivity),e.refractionRatio!==void 0&&(this.refractionRatio=e.refractionRatio),e.lightMap!==void 0&&(this.lightMap=t[e.lightMap]||null),e.lightMapIntensity!==void 0&&(this.lightMapIntensity=e.lightMapIntensity),e.aoMap!==void 0&&(this.aoMap=t[e.aoMap]||null),e.aoMapIntensity!==void 0&&(this.aoMapIntensity=e.aoMapIntensity),e.gradientMap!==void 0&&(this.gradientMap=t[e.gradientMap]||null),e.clearcoatMap!==void 0&&(this.clearcoatMap=t[e.clearcoatMap]||null),e.clearcoatRoughnessMap!==void 0&&(this.clearcoatRoughnessMap=t[e.clearcoatRoughnessMap]||null),e.clearcoatNormalMap!==void 0&&(this.clearcoatNormalMap=t[e.clearcoatNormalMap]||null),e.clearcoatNormalScale!==void 0&&(this.clearcoatNormalScale=new K().fromArray(e.clearcoatNormalScale)),e.iridescenceMap!==void 0&&(this.iridescenceMap=t[e.iridescenceMap]||null),e.iridescenceThicknessMap!==void 0&&(this.iridescenceThicknessMap=t[e.iridescenceThicknessMap]||null),e.transmissionMap!==void 0&&(this.transmissionMap=t[e.transmissionMap]||null),e.thicknessMap!==void 0&&(this.thicknessMap=t[e.thicknessMap]||null),e.anisotropyMap!==void 0&&(this.anisotropyMap=t[e.anisotropyMap]||null),e.sheenColorMap!==void 0&&(this.sheenColorMap=t[e.sheenColorMap]||null),e.sheenRoughnessMap!==void 0&&(this.sheenRoughnessMap=t[e.sheenRoughnessMap]||null),this}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;let t=e.clippingPlanes,n=null;if(t!==null){let e=t.length;n=Array(e);for(let r=0;r!==e;++r)n[r]=t[r].clone()}return this.clippingPlanes=n,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.allowOverride=e.allowOverride,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:`dispose`})}set needsUpdate(e){e===!0&&this.version++}},Vr=class extends Br{constructor(e){super(),this.isSpriteMaterial=!0,this.type=`SpriteMaterial`,this.color=new X(16777215),this.map=null,this.alphaMap=null,this.rotation=0,this.sizeAttenuation=!0,this.transparent=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.rotation=e.rotation,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}},Hr,Ur=new q,Wr=new q,Gr=new q,Kr=new K,qr=new K,Jr=new rn,Yr=new q,Xr=new q,Zr=new q,Qr=new K,$r=new K,ei=new K,ti=class extends jn{constructor(e=new Vr){if(super(),this.isSprite=!0,this.type=`Sprite`,Hr===void 0){Hr=new Fr;let e=new Ir(new Float32Array([-.5,-.5,0,0,0,.5,-.5,0,1,0,.5,.5,0,1,1,-.5,.5,0,0,1]),5);Hr.setIndex([0,1,2,0,2,3]),Hr.setAttribute(`position`,new Rr(e,3,0,!1)),Hr.setAttribute(`uv`,new Rr(e,2,3,!1))}this.geometry=Hr,this.material=e,this.center=new K(.5,.5),this.count=1}raycast(e,t){e.camera===null&&U(`Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.`),Wr.setFromMatrixScale(this.matrixWorld),Jr.copy(e.camera.matrixWorld),this.modelViewMatrix.multiplyMatrices(e.camera.matrixWorldInverse,this.matrixWorld),Gr.setFromMatrixPosition(this.modelViewMatrix),e.camera.isPerspectiveCamera&&this.material.sizeAttenuation===!1&&Wr.multiplyScalar(-Gr.z);let n=this.material.rotation,r,i;n!==0&&(i=Math.cos(n),r=Math.sin(n));let a=this.center;ni(Yr.set(-.5,-.5,0),Gr,a,Wr,r,i),ni(Xr.set(.5,-.5,0),Gr,a,Wr,r,i),ni(Zr.set(.5,.5,0),Gr,a,Wr,r,i),Qr.set(0,0),$r.set(1,0),ei.set(1,1);let o=e.ray.intersectTriangle(Yr,Xr,Zr,!1,Ur);if(o===null&&(ni(Xr.set(-.5,.5,0),Gr,a,Wr,r,i),$r.set(0,1),o=e.ray.intersectTriangle(Yr,Zr,Xr,!1,Ur),o===null))return;let s=e.ray.origin.distanceTo(Ur);se.far||t.push({distance:s,point:Ur.clone(),uv:tr.getInterpolation(Ur,Yr,Xr,Zr,Qr,$r,ei,new K),face:null,object:this})}copy(e,t){return super.copy(e,t),e.center!==void 0&&this.center.copy(e.center),this.material=e.material,this}};function ni(e,t,n,r,i,a){Kr.subVectors(e,n).addScalar(.5).multiply(r),i===void 0?qr.copy(Kr):(qr.x=a*Kr.x-i*Kr.y,qr.y=i*Kr.x+a*Kr.y),e.copy(t),e.x+=qr.x,e.y+=qr.y,e.applyMatrix4(Jr)}var ri=new q,ii=new q,ai=new q,oi=new q,si=new q,ci=new q,li=new q,ui=class{constructor(e=new q,t=new q(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,ri)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);let n=t.dot(this.direction);return n<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,n)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){let t=ri.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(ri.copy(this.origin).addScaledVector(this.direction,t),ri.distanceToSquared(e))}distanceSqToSegment(e,t,n,r){ii.copy(e).add(t).multiplyScalar(.5),ai.copy(t).sub(e).normalize(),oi.copy(this.origin).sub(ii);let i=e.distanceTo(t)*.5,a=-this.direction.dot(ai),o=oi.dot(this.direction),s=-oi.dot(ai),c=oi.lengthSq(),l=Math.abs(1-a*a),u,d,f,p;if(l>0){if(u=a*s-o,d=a*o-s,p=i*l,u>=0){if(d>=-p){if(d<=p){let e=1/l;u*=e,d*=e,f=u*(u+a*d+2*o)+d*(a*u+d+2*s)+c}else d=i,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*s)+c}else d=-i,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*s)+c}else d<=-p?(u=Math.max(0,-(-a*i+o)),d=u>0?-i:Math.min(Math.max(-i,-s),i),f=-u*u+d*(d+2*s)+c):d<=p?(u=0,d=Math.min(Math.max(-i,-s),i),f=d*(d+2*s)+c):(u=Math.max(0,-(a*i+o)),d=u>0?i:Math.min(Math.max(-i,-s),i),f=-u*u+d*(d+2*s)+c)}else d=a>0?-i:i,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*s)+c;return n&&n.copy(this.origin).addScaledVector(this.direction,u),r&&r.copy(ii).addScaledVector(ai,d),f}intersectSphere(e,t){ri.subVectors(e.center,this.origin);let n=ri.dot(this.direction),r=ri.dot(ri)-n*n,i=e.radius*e.radius;if(r>i)return null;let a=Math.sqrt(i-r),o=n-a,s=n+a;return s<0?null:o<0?this.at(s,t):this.at(o,t)}intersectsSphere(e){return e.radius<0?!1:this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){let t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;let n=-(this.origin.dot(e.normal)+e.constant)/t;return n>=0?n:null}intersectPlane(e,t){let n=this.distanceToPlane(e);return n===null?null:this.at(n,t)}intersectsPlane(e){let t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let n,r,i,a,o,s,c=1/this.direction.x,l=1/this.direction.y,u=1/this.direction.z,d=this.origin;return c>=0?(n=(e.min.x-d.x)*c,r=(e.max.x-d.x)*c):(n=(e.max.x-d.x)*c,r=(e.min.x-d.x)*c),l>=0?(i=(e.min.y-d.y)*l,a=(e.max.y-d.y)*l):(i=(e.max.y-d.y)*l,a=(e.min.y-d.y)*l),n>a||i>r||((i>n||isNaN(n))&&(n=i),(a=0?(o=(e.min.z-d.z)*u,s=(e.max.z-d.z)*u):(o=(e.max.z-d.z)*u,s=(e.min.z-d.z)*u),n>s||o>r)||((o>n||n!==n)&&(n=o),(s=0?n:r,t)}intersectsBox(e){return this.intersectBox(e,ri)!==null}intersectTriangle(e,t,n,r,i){si.subVectors(t,e),ci.subVectors(n,e),li.crossVectors(si,ci);let a=this.direction.dot(li),o;if(a>0){if(r)return null;o=1}else if(a<0)o=-1,a=-a;else return null;oi.subVectors(this.origin,e);let s=o*this.direction.dot(ci.crossVectors(oi,ci));if(s<0)return null;let c=o*this.direction.dot(si.cross(oi));if(c<0||s+c>a)return null;let l=-o*oi.dot(li);return l<0?null:this.at(l/a,i)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}},di=class extends Br{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type=`MeshBasicMaterial`,this.color=new X(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new mn,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap=`round`,this.wireframeLinejoin=`round`,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}},fi=new rn,pi=new ui,mi=new Dr,hi=new q,gi=new q,_i=new q,vi=new q,yi=new q,bi=new q,xi=new q,Si=new q,Ci=class extends jn{constructor(e=new Fr,t=new di){super(),this.isMesh=!0,this.type=`Mesh`,this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),e.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=e.morphTargetInfluences.slice()),e.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}updateMorphTargets(){let e=this.geometry.morphAttributes,t=Object.keys(e);if(t.length>0){let n=e[t[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e(e.far-e.near)**2))&&(fi.copy(i).invert(),pi.copy(e.ray).applyMatrix4(fi),(n.boundingBox===null||pi.intersectsBox(n.boundingBox)!==!1)&&this._computeIntersections(e,t,pi)))}_computeIntersections(e,t,n){let r,i=this.geometry,a=this.material,o=i.index,s=i.attributes.position,c=i.attributes.uv,l=i.attributes.uv1,u=i.attributes.normal,d=i.groups,f=i.drawRange;if(o!==null){if(Array.isArray(a))for(let i=0,s=d.length;in.far?null:{distance:l,point:Si.clone(),object:e}}function Ti(e,t,n,r,i,a,o,s,c,l){e.getVertexPosition(s,gi),e.getVertexPosition(c,_i),e.getVertexPosition(l,vi);let u=wi(e,t,n,r,gi,_i,vi,xi);if(u){let e=new q;tr.getBarycoord(xi,gi,_i,vi,e),i&&(u.uv=tr.getInterpolatedAttribute(i,s,c,l,e,new K)),a&&(u.uv1=tr.getInterpolatedAttribute(a,s,c,l,e,new K)),o&&(u.normal=tr.getInterpolatedAttribute(o,s,c,l,e,new q),u.normal.dot(r.direction)>0&&u.normal.multiplyScalar(-1));let t={a:s,b:c,c:l,normal:new q,materialIndex:0};tr.getNormal(gi,_i,vi,t.normal),u.face=t,u.barycoord=e}return u}var Ei=class extends Zt{constructor(e=null,t=1,n=1,r,i,a,o,s,c=h,l=h,u,d){super(null,a,o,s,c,l,r,i,u,d),this.isDataTexture=!0,this.image={data:e,width:t,height:n},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}},Di=new q,Oi=new q,ki=new J,Ai=class{constructor(e=new q(1,0,0),t=0){this.isPlane=!0,this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,n,r){return this.normal.set(e,t,n),this.constant=r,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,n){let r=Di.subVectors(n,t).cross(Oi.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(r,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){let e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t,n=!0){let r=e.delta(Di),i=this.normal.dot(r);if(i===0)return this.distanceToPoint(e.start)===0?t.copy(e.start):null;let a=-(e.start.dot(this.normal)+this.constant)/i;return n===!0&&(a<0||a>1)?null:t.copy(e.start).addScaledVector(r,a)}intersectsLine(e){let t=this.distanceToPoint(e.start),n=this.distanceToPoint(e.end);return t<0&&n>0||n<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){let n=t||ki.getNormalMatrix(e),r=this.coplanarPoint(Di).applyMatrix4(e),i=this.normal.applyMatrix3(n).normalize();return this.constant=-r.dot(i),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}},ji=new Dr,Mi=new K(.5,.5),Ni=new q,Pi=class{constructor(e=new Ai,t=new Ai,n=new Ai,r=new Ai,i=new Ai,a=new Ai){this.planes=[e,t,n,r,i,a]}set(e,t,n,r,i,a){let o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(n),o[3].copy(r),o[4].copy(i),o[5].copy(a),this}copy(e){let t=this.planes;for(let n=0;n<6;n++)t[n].copy(e.planes[n]);return this}setFromProjectionMatrix(e,t=$e,n=!1){let r=this.planes,i=e.elements,a=i[0],o=i[1],s=i[2],c=i[3],l=i[4],u=i[5],d=i[6],f=i[7],p=i[8],m=i[9],h=i[10],g=i[11],_=i[12],v=i[13],y=i[14],b=i[15];if(r[0].setComponents(c-a,f-l,g-p,b-_).normalize(),r[1].setComponents(c+a,f+l,g+p,b+_).normalize(),r[2].setComponents(c+o,f+u,g+m,b+v).normalize(),r[3].setComponents(c-o,f-u,g-m,b-v).normalize(),n)r[4].setComponents(s,d,h,y).normalize(),r[5].setComponents(c-s,f-d,g-h,b-y).normalize();else if(r[4].setComponents(c-s,f-d,g-h,b-y).normalize(),t===2e3)r[5].setComponents(c+s,f+d,g+h,b+y).normalize();else if(t===2001)r[5].setComponents(s,d,h,y).normalize();else throw Error(`THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: `+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),ji.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{let t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),ji.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(ji)}intersectsSprite(e){return ji.center.set(0,0,0),ji.radius=.7071067811865476+Mi.distanceTo(e.center),ji.applyMatrix4(e.matrixWorld),this.intersectsSphere(ji)}intersectsSphere(e){let t=this.planes,n=e.center,r=-e.radius;for(let e=0;e<6;e++)if(t[e].distanceToPoint(n)0?e.max.x:e.min.x,Ni.y=r.normal.y>0?e.max.y:e.min.y,Ni.z=r.normal.z>0?e.max.z:e.min.z,r.distanceToPoint(Ni)<0)return!1}return!0}containsPoint(e){let t=this.planes;for(let n=0;n<6;n++)if(t[n].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}},Fi=class extends Br{constructor(e){super(),this.isLineBasicMaterial=!0,this.type=`LineBasicMaterial`,this.color=new X(16777215),this.map=null,this.linewidth=1,this.linecap=`round`,this.linejoin=`round`,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.linewidth=e.linewidth,this.linecap=e.linecap,this.linejoin=e.linejoin,this.fog=e.fog,this}},Ii=new q,Li=new q,Ri=new rn,zi=new ui,Bi=new Dr,Vi=new q,Hi=new q,Ui=class extends jn{constructor(e=new Fr,t=new Fi){super(),this.isLine=!0,this.type=`Line`,this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}computeLineDistances(){let e=this.geometry;if(e.index===null){let t=e.attributes.position,n=[0];for(let e=1,r=t.count;e0){let n=e[t[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;er)return;Vi.applyMatrix4(e.matrixWorld);let c=t.ray.origin.distanceTo(Vi);if(!(ct.far))return{distance:c,point:Hi.clone().applyMatrix4(e.matrixWorld),index:o,face:null,faceIndex:null,barycoord:null,object:e}}var Gi=new q,Ki=new q,qi=class extends Ui{constructor(e,t){super(e,t),this.isLineSegments=!0,this.type=`LineSegments`}computeLineDistances(){let e=this.geometry;if(e.index===null){let t=e.attributes.position,n=[];for(let e=0,r=t.count;e0?1:-1,l.push(D.x,D.y,D.z),u.push(s/h),u.push(1-a/g),T+=1}for(let e=0;e0&&v(!0),t>0&&v(!1)),this.setIndex(l),this.setAttribute(`position`,new Cr(u,3)),this.setAttribute(`normal`,new Cr(d,3)),this.setAttribute(`uv`,new Cr(f,2));function _(){let a=new q,_=new q,v=0,y=(t-e)/n;for(let c=0;c<=i;c++){let l=[],g=c/i,v=g*(t-e)+e;for(let e=0;e<=r;e++){let t=e/r,i=t*s+o,c=Math.sin(i),m=Math.cos(i);_.x=v*c,_.y=-g*n+h,_.z=v*m,u.push(_.x,_.y,_.z),a.set(c,y,m).normalize(),d.push(a.x,a.y,a.z),f.push(t,1-g),l.push(p++)}m.push(l)}for(let n=0;n0||r!==0)&&(l.push(a,o,c),v+=3),(t>0||r!==i-1)&&(l.push(o,s,c),v+=3)}c.addGroup(g,v,0),g+=v}function v(n){let i=p,a=new K,m=new q,_=0,v=n===!0?e:t,y=n===!0?1:-1;for(let e=1;e<=r;e++)u.push(0,h*y,0),d.push(0,y,0),f.push(.5,.5),p++;let b=p;for(let e=0;e<=r;e++){let t=e/r*s+o,n=Math.cos(t),i=Math.sin(t);m.x=v*i,m.y=h*y,m.z=v*n,u.push(m.x,m.y,m.z),d.push(0,y,0),a.x=n*.5+.5,a.y=i*.5*y+.5,f.push(a.x,a.y),p++}for(let e=0;e0)&&f.push(t,i,c),(e!==n-1||s=0;--t)if(e[t]>=65535)return!0;return!1}function tt(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function V(e){return document.createElementNS(`http://www.w3.org/1999/xhtml`,e)}function nt(){let e=V(`canvas`);return e.style.display=`block`,e}var rt={};function it(...e){let t=`THREE.`+e.shift();console.log(t,...e)}function at(e){let t=e[0];if(typeof t==`string`&&t.startsWith(`TSL:`)){let t=e[1];t&&t.isStackTrace?e[0]+=` `+t.getLocation():e[1]=`Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.`}return e}function H(...e){e=at(e);let t=`THREE.`+e.shift();{let n=e[0];n&&n.isStackTrace?console.warn(n.getError(t)):console.warn(t,...e)}}function U(...e){e=at(e);let t=`THREE.`+e.shift();{let n=e[0];n&&n.isStackTrace?console.error(n.getError(t)):console.error(t,...e)}}function ot(...e){let t=e.join(` `);t in rt||(rt[t]=!0,H(...e))}function st(e,t,n){return new Promise(function(r,i){function a(){switch(e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0)){case e.WAIT_FAILED:i();break;case e.TIMEOUT_EXPIRED:setTimeout(a,n);break;default:r()}}setTimeout(a,n)})}var ct={0:1,2:6,4:7,3:5,1:0,6:2,7:4,5:3},lt=class{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});let n=this._listeners;n[e]===void 0&&(n[e]=[]),n[e].indexOf(t)===-1&&n[e].push(t)}hasEventListener(e,t){let n=this._listeners;return n!==void 0&&n[e]!==void 0&&n[e].indexOf(t)!==-1}removeEventListener(e,t){let n=this._listeners;if(n===void 0)return;let r=n[e];if(r!==void 0){let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}dispatchEvent(e){let t=this._listeners;if(t===void 0)return;let n=t[e.type];if(n!==void 0){e.target=this;let t=n.slice(0);for(let n=0,r=t.length;n>8&255]+ut[e>>16&255]+ut[e>>24&255]+`-`+ut[t&255]+ut[t>>8&255]+`-`+ut[t>>16&15|64]+ut[t>>24&255]+`-`+ut[n&63|128]+ut[n>>8&255]+`-`+ut[n>>16&255]+ut[n>>24&255]+ut[r&255]+ut[r>>8&255]+ut[r>>16&255]+ut[r>>24&255]).toLowerCase()}function W(e,t,n){return Math.max(t,Math.min(n,e))}function ht(e,t){return(e%t+t)%t}function gt(e,t,n,r,i){return r+(e-t)*(i-r)/(n-t)}function _t(e,t,n){return e===t?0:(n-e)/(t-e)}function vt(e,t,n){return(1-n)*e+n*t}function yt(e,t,n,r){return vt(e,t,1-Math.exp(-n*r))}function bt(e,t=1){return t-Math.abs(ht(e,t*2)-t)}function xt(e,t,n){return e<=t?0:e>=n?1:(e=(e-t)/(n-t),e*e*(3-2*e))}function St(e,t,n){return e<=t?0:e>=n?1:(e=(e-t)/(n-t),e*e*e*(e*(e*6-15)+10))}function Ct(e,t){return e+Math.floor(Math.random()*(t-e+1))}function wt(e,t){return e+Math.random()*(t-e)}function Tt(e){return e*(.5-Math.random())}function Et(e){e!==void 0&&(dt=e);let t=dt+=1831565813;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}function Dt(e){return e*ft}function Ot(e){return e*pt}function kt(e){return!(e&e-1)&&e!==0}function At(e){return 2**Math.ceil(Math.log(e)/Math.LN2)}function jt(e){return 2**Math.floor(Math.log(e)/Math.LN2)}function Mt(e,t,n,r,i){let a=Math.cos,o=Math.sin,s=a(n/2),c=o(n/2),l=a((t+r)/2),u=o((t+r)/2),d=a((t-r)/2),f=o((t-r)/2),p=a((r-t)/2),m=o((r-t)/2);switch(i){case`XYX`:e.set(s*u,c*d,c*f,s*l);break;case`YZY`:e.set(c*f,s*u,c*d,s*l);break;case`ZXZ`:e.set(c*d,c*f,s*u,s*l);break;case`XZX`:e.set(s*u,c*m,c*p,s*l);break;case`YXY`:e.set(c*p,s*u,c*m,s*l);break;case`ZYZ`:e.set(c*m,c*p,s*u,s*l);break;default:H(`MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: `+i)}}function Nt(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return e/4294967295;case Uint16Array:return e/65535;case Uint8Array:return e/255;case Int32Array:return Math.max(e/2147483647,-1);case Int16Array:return Math.max(e/32767,-1);case Int8Array:return Math.max(e/127,-1);default:throw Error(`THREE.MathUtils: Invalid component type.`)}}function G(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return Math.round(e*4294967295);case Uint16Array:return Math.round(e*65535);case Uint8Array:return Math.round(e*255);case Int32Array:return Math.round(e*2147483647);case Int16Array:return Math.round(e*32767);case Int8Array:return Math.round(e*127);default:throw Error(`THREE.MathUtils: Invalid component type.`)}}var Pt={DEG2RAD:ft,RAD2DEG:pt,generateUUID:mt,clamp:W,euclideanModulo:ht,mapLinear:gt,inverseLerp:_t,lerp:vt,damp:yt,pingpong:bt,smoothstep:xt,smootherstep:St,randInt:Ct,randFloat:wt,randFloatSpread:Tt,seededRandom:Et,degToRad:Dt,radToDeg:Ot,isPowerOfTwo:kt,ceilPowerOfTwo:At,floorPowerOfTwo:jt,setQuaternionFromProperEuler:Mt,normalize:G,denormalize:Nt},K=class e{static{e.prototype.isVector2=!0}constructor(e=0,t=0){this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw Error(`THREE.Vector2: index is out of range: `+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw Error(`THREE.Vector2: index is out of range: `+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){let t=this.x,n=this.y,r=e.elements;return this.x=r[0]*t+r[3]*n+r[6],this.y=r[1]*t+r[4]*n+r[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=W(this.x,e.x,t.x),this.y=W(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=W(this.x,e,t),this.y=W(this.y,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(W(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let n=this.dot(e)/t;return Math.acos(W(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,n=this.y-e.y;return t*t+n*n}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){let n=Math.cos(t),r=Math.sin(t),i=this.x-e.x,a=this.y-e.y;return this.x=i*n-a*r+e.x,this.y=i*r+a*n+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}},Ft=class{constructor(e=0,t=0,n=0,r=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=n,this._w=r}static slerpFlat(e,t,n,r,i,a,o){let s=n[r+0],c=n[r+1],l=n[r+2],u=n[r+3],d=i[a+0],f=i[a+1],p=i[a+2],m=i[a+3];if(u!==m||s!==d||c!==f||l!==p){let e=s*d+c*f+l*p+u*m;e<0&&(d=-d,f=-f,p=-p,m=-m,e=-e);let t=1-o;if(e<.9995){let n=Math.acos(e),r=Math.sin(n);t=Math.sin(t*n)/r,o=Math.sin(o*n)/r,s=s*t+d*o,c=c*t+f*o,l=l*t+p*o,u=u*t+m*o}else{s=s*t+d*o,c=c*t+f*o,l=l*t+p*o,u=u*t+m*o;let e=1/Math.sqrt(s*s+c*c+l*l+u*u);s*=e,c*=e,l*=e,u*=e}}e[t]=s,e[t+1]=c,e[t+2]=l,e[t+3]=u}static multiplyQuaternionsFlat(e,t,n,r,i,a){let o=n[r],s=n[r+1],c=n[r+2],l=n[r+3],u=i[a],d=i[a+1],f=i[a+2],p=i[a+3];return e[t]=o*p+l*u+s*f-c*d,e[t+1]=s*p+l*d+c*u-o*f,e[t+2]=c*p+l*f+o*d-s*u,e[t+3]=l*p-o*u-s*d-c*f,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,n,r){return this._x=e,this._y=t,this._z=n,this._w=r,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){let n=e._x,r=e._y,i=e._z,a=e._order,o=Math.cos,s=Math.sin,c=o(n/2),l=o(r/2),u=o(i/2),d=s(n/2),f=s(r/2),p=s(i/2);switch(a){case`XYZ`:this._x=d*l*u+c*f*p,this._y=c*f*u-d*l*p,this._z=c*l*p+d*f*u,this._w=c*l*u-d*f*p;break;case`YXZ`:this._x=d*l*u+c*f*p,this._y=c*f*u-d*l*p,this._z=c*l*p-d*f*u,this._w=c*l*u+d*f*p;break;case`ZXY`:this._x=d*l*u-c*f*p,this._y=c*f*u+d*l*p,this._z=c*l*p+d*f*u,this._w=c*l*u-d*f*p;break;case`ZYX`:this._x=d*l*u-c*f*p,this._y=c*f*u+d*l*p,this._z=c*l*p-d*f*u,this._w=c*l*u+d*f*p;break;case`YZX`:this._x=d*l*u+c*f*p,this._y=c*f*u+d*l*p,this._z=c*l*p-d*f*u,this._w=c*l*u-d*f*p;break;case`XZY`:this._x=d*l*u-c*f*p,this._y=c*f*u-d*l*p,this._z=c*l*p+d*f*u,this._w=c*l*u+d*f*p;break;default:H(`Quaternion: .setFromEuler() encountered an unknown order: `+a)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){let n=t/2,r=Math.sin(n);return this._x=e.x*r,this._y=e.y*r,this._z=e.z*r,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(e){let t=e.elements,n=t[0],r=t[4],i=t[8],a=t[1],o=t[5],s=t[9],c=t[2],l=t[6],u=t[10],d=n+o+u;if(d>0){let e=.5/Math.sqrt(d+1);this._w=.25/e,this._x=(l-s)*e,this._y=(i-c)*e,this._z=(a-r)*e}else if(n>o&&n>u){let e=2*Math.sqrt(1+n-o-u);this._w=(l-s)/e,this._x=.25*e,this._y=(r+a)/e,this._z=(i+c)/e}else if(o>u){let e=2*Math.sqrt(1+o-n-u);this._w=(i-c)/e,this._x=(r+a)/e,this._y=.25*e,this._z=(s+l)/e}else{let e=2*Math.sqrt(1+u-n-o);this._w=(a-r)/e,this._x=(i+c)/e,this._y=(s+l)/e,this._z=.25*e}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let n=e.dot(t)+1;return n<1e-8?(n=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=n):(this._x=0,this._y=-e.z,this._z=e.y,this._w=n)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=n),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(W(this.dot(e),-1,1)))}rotateTowards(e,t){let n=this.angleTo(e);if(n===0)return this;let r=Math.min(1,t/n);return this.slerp(e,r),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x*=e,this._y*=e,this._z*=e,this._w*=e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){let n=e._x,r=e._y,i=e._z,a=e._w,o=t._x,s=t._y,c=t._z,l=t._w;return this._x=n*l+a*o+r*c-i*s,this._y=r*l+a*s+i*o-n*c,this._z=i*l+a*c+n*s-r*o,this._w=a*l-n*o-r*s-i*c,this._onChangeCallback(),this}slerp(e,t){let n=e._x,r=e._y,i=e._z,a=e._w,o=this.dot(e);o<0&&(n=-n,r=-r,i=-i,a=-a,o=-o);let s=1-t;if(o<.9995){let e=Math.acos(o),c=Math.sin(e);s=Math.sin(s*e)/c,t=Math.sin(t*e)/c,this._x=this._x*s+n*t,this._y=this._y*s+r*t,this._z=this._z*s+i*t,this._w=this._w*s+a*t,this._onChangeCallback()}else this._x=this._x*s+n*t,this._y=this._y*s+r*t,this._z=this._z*s+i*t,this._w=this._w*s+a*t,this.normalize();return this}slerpQuaternions(e,t,n){return this.copy(e).slerp(t,n)}random(){let e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),n=Math.random(),r=Math.sqrt(1-n),i=Math.sqrt(n);return this.set(r*Math.sin(e),r*Math.cos(e),i*Math.sin(t),i*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}},q=class e{static{e.prototype.isVector3=!0}constructor(e=0,t=0,n=0){this.x=e,this.y=t,this.z=n}set(e,t,n){return n===void 0&&(n=this.z),this.x=e,this.y=t,this.z=n,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw Error(`THREE.Vector3: index is out of range: `+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw Error(`THREE.Vector3: index is out of range: `+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(Lt.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(Lt.setFromAxisAngle(e,t))}applyMatrix3(e){let t=this.x,n=this.y,r=this.z,i=e.elements;return this.x=i[0]*t+i[3]*n+i[6]*r,this.y=i[1]*t+i[4]*n+i[7]*r,this.z=i[2]*t+i[5]*n+i[8]*r,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){let t=this.x,n=this.y,r=this.z,i=e.elements,a=1/(i[3]*t+i[7]*n+i[11]*r+i[15]);return this.x=(i[0]*t+i[4]*n+i[8]*r+i[12])*a,this.y=(i[1]*t+i[5]*n+i[9]*r+i[13])*a,this.z=(i[2]*t+i[6]*n+i[10]*r+i[14])*a,this}applyQuaternion(e){let t=this.x,n=this.y,r=this.z,i=e.x,a=e.y,o=e.z,s=e.w,c=2*(a*r-o*n),l=2*(o*t-i*r),u=2*(i*n-a*t);return this.x=t+s*c+a*u-o*l,this.y=n+s*l+o*c-i*u,this.z=r+s*u+i*l-a*c,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){let t=this.x,n=this.y,r=this.z,i=e.elements;return this.x=i[0]*t+i[4]*n+i[8]*r,this.y=i[1]*t+i[5]*n+i[9]*r,this.z=i[2]*t+i[6]*n+i[10]*r,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=W(this.x,e.x,t.x),this.y=W(this.y,e.y,t.y),this.z=W(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=W(this.x,e,t),this.y=W(this.y,e,t),this.z=W(this.z,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(W(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){let n=e.x,r=e.y,i=e.z,a=t.x,o=t.y,s=t.z;return this.x=r*s-i*o,this.y=i*a-n*s,this.z=n*o-r*a,this}projectOnVector(e){let t=e.lengthSq();if(t===0)return this.set(0,0,0);let n=e.dot(this)/t;return this.copy(e).multiplyScalar(n)}projectOnPlane(e){return It.copy(this).projectOnVector(e),this.sub(It)}reflect(e){return this.sub(It.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let n=this.dot(e)/t;return Math.acos(W(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,n=this.y-e.y,r=this.z-e.z;return t*t+n*n+r*r}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,n){let r=Math.sin(t)*e;return this.x=r*Math.sin(n),this.y=Math.cos(t)*e,this.z=r*Math.cos(n),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,n){return this.x=e*Math.sin(t),this.y=n,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){let t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){let t=this.setFromMatrixColumn(e,0).length(),n=this.setFromMatrixColumn(e,1).length(),r=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=n,this.z=r,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){let e=Math.random()*Math.PI*2,t=Math.random()*2-1,n=Math.sqrt(1-t*t);return this.x=n*Math.cos(e),this.y=t,this.z=n*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}},It=new q,Lt=new Ft,J=class e{static{e.prototype.isMatrix3=!0}constructor(e,t,n,r,i,a,o,s,c){this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,n,r,i,a,o,s,c)}set(e,t,n,r,i,a,o,s,c){let l=this.elements;return l[0]=e,l[1]=r,l[2]=o,l[3]=t,l[4]=i,l[5]=s,l[6]=n,l[7]=a,l[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){let t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],this}extractBasis(e,t,n){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(e){let t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){let n=e.elements,r=t.elements,i=this.elements,a=n[0],o=n[3],s=n[6],c=n[1],l=n[4],u=n[7],d=n[2],f=n[5],p=n[8],m=r[0],h=r[3],g=r[6],_=r[1],v=r[4],y=r[7],b=r[2],x=r[5],S=r[8];return i[0]=a*m+o*_+s*b,i[3]=a*h+o*v+s*x,i[6]=a*g+o*y+s*S,i[1]=c*m+l*_+u*b,i[4]=c*h+l*v+u*x,i[7]=c*g+l*y+u*S,i[2]=d*m+f*_+p*b,i[5]=d*h+f*v+p*x,i[8]=d*g+f*y+p*S,this}multiplyScalar(e){let t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){let e=this.elements,t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8];return t*a*l-t*o*c-n*i*l+n*o*s+r*i*c-r*a*s}invert(){let e=this.elements,t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8],u=l*a-o*c,d=o*s-l*i,f=c*i-a*s,p=t*u+n*d+r*f;if(p===0)return this.set(0,0,0,0,0,0,0,0,0);let m=1/p;return e[0]=u*m,e[1]=(r*c-l*n)*m,e[2]=(o*n-r*a)*m,e[3]=d*m,e[4]=(l*t-r*s)*m,e[5]=(r*i-o*t)*m,e[6]=f*m,e[7]=(n*s-c*t)*m,e[8]=(a*t-n*i)*m,this}transpose(){let e,t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){let t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,n,r,i,a,o){let s=Math.cos(i),c=Math.sin(i);return this.set(n*s,n*c,-n*(s*a+c*o)+a+e,-r*c,r*s,-r*(-c*a+s*o)+o+t,0,0,1),this}scale(e,t){return ot(`Matrix3: .scale() is deprecated. Use .makeScale() instead.`),this.premultiply(Rt.makeScale(e,t)),this}rotate(e){return ot(`Matrix3: .rotate() is deprecated. Use .makeRotation() instead.`),this.premultiply(Rt.makeRotation(-e)),this}translate(e,t){return ot(`Matrix3: .translate() is deprecated. Use .makeTranslation() instead.`),this.premultiply(Rt.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,n,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){let t=this.elements,n=e.elements;for(let e=0;e<9;e++)if(t[e]!==n[e])return!1;return!0}fromArray(e,t=0){for(let n=0;n<9;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){let n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e}clone(){return new this.constructor().fromArray(this.elements)}},Rt=new J,zt=new J().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),Bt=new J().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function Vt(){let e={enabled:!0,workingColorSpace:Je,spaces:{},convert:function(e,t,n){return this.enabled===!1||t===n||!t||!n?e:(this.spaces[t].transfer===`srgb`&&(e.r=Ht(e.r),e.g=Ht(e.g),e.b=Ht(e.b)),this.spaces[t].primaries!==this.spaces[n].primaries&&(e.applyMatrix3(this.spaces[t].toXYZ),e.applyMatrix3(this.spaces[n].fromXYZ)),this.spaces[n].transfer===`srgb`&&(e.r=Ut(e.r),e.g=Ut(e.g),e.b=Ut(e.b)),e)},workingToColorSpace:function(e,t){return this.convert(e,this.workingColorSpace,t)},colorSpaceToWorking:function(e,t){return this.convert(e,t,this.workingColorSpace)},getPrimaries:function(e){return this.spaces[e].primaries},getTransfer:function(e){return e===``?Ye:this.spaces[e].transfer},getToneMappingMode:function(e){return this.spaces[e].outputColorSpaceConfig.toneMappingMode||`standard`},getLuminanceCoefficients:function(e,t=this.workingColorSpace){return e.fromArray(this.spaces[t].luminanceCoefficients)},define:function(e){Object.assign(this.spaces,e)},_getMatrix:function(e,t,n){return e.copy(this.spaces[t].toXYZ).multiply(this.spaces[n].fromXYZ)},_getDrawingBufferColorSpace:function(e){return this.spaces[e].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(e=this.workingColorSpace){return this.spaces[e].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(t,n){return ot(`ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace().`),e.workingToColorSpace(t,n)},toWorkingColorSpace:function(t,n){return ot(`ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking().`),e.colorSpaceToWorking(t,n)}},t=[.64,.33,.3,.6,.15,.06],n=[.2126,.7152,.0722],r=[.3127,.329];return e.define({[Je]:{primaries:t,whitePoint:r,transfer:Ye,toXYZ:zt,fromXYZ:Bt,luminanceCoefficients:n,workingColorSpaceConfig:{unpackColorSpace:qe},outputColorSpaceConfig:{drawingBufferColorSpace:qe}},[qe]:{primaries:t,whitePoint:r,transfer:Xe,toXYZ:zt,fromXYZ:Bt,luminanceCoefficients:n,outputColorSpaceConfig:{drawingBufferColorSpace:qe}}}),e}var Y=Vt();function Ht(e){return e<.04045?e*.0773993808:(e*.9478672986+.0521327014)**2.4}function Ut(e){return e<.0031308?e*12.92:1.055*e**.41666-.055}var Wt,Gt=class{static getDataURL(e,t=`image/png`){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>`u`)return e.src;let n;if(e instanceof HTMLCanvasElement)n=e;else{Wt===void 0&&(Wt=V(`canvas`)),Wt.width=e.width,Wt.height=e.height;let t=Wt.getContext(`2d`);e instanceof ImageData?t.putImageData(e,0,0):t.drawImage(e,0,0,e.width,e.height),n=Wt}return n.toDataURL(t)}static sRGBToLinear(e){if(typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap){let t=V(`canvas`);t.width=e.width,t.height=e.height;let n=t.getContext(`2d`);n.drawImage(e,0,0,e.width,e.height);let r=n.getImageData(0,0,e.width,e.height),i=r.data;for(let e=0;e1),this.pmremVersion=0,this.normalized=!1}get width(){return this.source.getSize(Xt).x}get height(){return this.source.getSize(Xt).y}get depth(){return this.source.getSize(Xt).z}get image(){return this.source.data}set image(e){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.normalized=e.normalized,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(let t in e){let n=e[t];if(n===void 0){H(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}let r=this[t];if(r===void 0){H(`Texture.setValues(): property '${t}' does not exist.`);continue}r&&n&&r.isVector2&&n.isVector2||r&&n&&r.isVector3&&n.isVector3||r&&n&&r.isMatrix3&&n.isMatrix3?r.copy(n):this[t]=n}}toJSON(e){let t=e===void 0||typeof e==`string`;if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];let n={metadata:{version:4.7,type:`Texture`,generator:`Texture.toJSON`},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,normalized:this.normalized,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(n.userData=this.userData),t||(e.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:`dispose`})}transformUv(e){if(this.mapping!==300)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case f:e.x-=Math.floor(e.x);break;case p:e.x=e.x<0?0:1;break;case m:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x-=Math.floor(e.x)}if(e.y<0||e.y>1)switch(this.wrapT){case f:e.y-=Math.floor(e.y);break;case p:e.y=e.y<0?0:1;break;case m:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y-=Math.floor(e.y)}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}};Zt.DEFAULT_IMAGE=null,Zt.DEFAULT_MAPPING=300,Zt.DEFAULT_ANISOTROPY=1;var Qt=class e{static{e.prototype.isVector4=!0}constructor(e=0,t=0,n=0,r=1){this.x=e,this.y=t,this.z=n,this.w=r}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,n,r){return this.x=e,this.y=t,this.z=n,this.w=r,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw Error(`THREE.Vector4: index is out of range: `+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw Error(`THREE.Vector4: index is out of range: `+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w===void 0?1:e.w,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){let t=this.x,n=this.y,r=this.z,i=this.w,a=e.elements;return this.x=a[0]*t+a[4]*n+a[8]*r+a[12]*i,this.y=a[1]*t+a[5]*n+a[9]*r+a[13]*i,this.z=a[2]*t+a[6]*n+a[10]*r+a[14]*i,this.w=a[3]*t+a[7]*n+a[11]*r+a[15]*i,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);let t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,n,r,i,a=.01,o=.1,s=e.elements,c=s[0],l=s[4],u=s[8],d=s[1],f=s[5],p=s[9],m=s[2],h=s[6],g=s[10];if(Math.abs(l-d)s&&e>_?e_?s1);this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,n=e.textures.length;t>>0}enable(e){this.mask|=1<1){for(let e=0;e1){for(let e=0;e0&&(r.userData=this.userData),r.layers=this.layers.mask,r.matrix=this.matrix.toArray(),r.up=this.up.toArray(),this.pivot!==null&&(r.pivot=this.pivot.toArray()),this.matrixAutoUpdate===!1&&(r.matrixAutoUpdate=!1),this.morphTargetDictionary!==void 0&&(r.morphTargetDictionary=Object.assign({},this.morphTargetDictionary)),this.morphTargetInfluences!==void 0&&(r.morphTargetInfluences=this.morphTargetInfluences.slice()),this.isInstancedMesh&&(r.type=`InstancedMesh`,r.count=this.count,r.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(r.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(r.type=`BatchedMesh`,r.perObjectFrustumCulled=this.perObjectFrustumCulled,r.sortObjects=this.sortObjects,r.drawRanges=this._drawRanges,r.reservedRanges=this._reservedRanges,r.geometryInfo=this._geometryInfo.map(e=>({...e,boundingBox:e.boundingBox?e.boundingBox.toJSON():void 0,boundingSphere:e.boundingSphere?e.boundingSphere.toJSON():void 0})),r.instanceInfo=this._instanceInfo.map(e=>({...e})),r.availableInstanceIds=this._availableInstanceIds.slice(),r.availableGeometryIds=this._availableGeometryIds.slice(),r.nextIndexStart=this._nextIndexStart,r.nextVertexStart=this._nextVertexStart,r.geometryCount=this._geometryCount,r.maxInstanceCount=this._maxInstanceCount,r.maxVertexCount=this._maxVertexCount,r.maxIndexCount=this._maxIndexCount,r.geometryInitialized=this._geometryInitialized,r.matricesTexture=this._matricesTexture.toJSON(e),r.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(r.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(r.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(r.boundingBox=this.boundingBox.toJSON()));function i(t,n){return t[n.uuid]===void 0&&(t[n.uuid]=n.toJSON(e)),n.uuid}if(this.isScene)this.background&&(this.background.isColor?r.background=this.background.toJSON():this.background.isTexture&&(r.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(r.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){r.geometry=i(e.geometries,this.geometry);let t=this.geometry.parameters;if(t!==void 0&&t.shapes!==void 0){let n=t.shapes;if(Array.isArray(n))for(let t=0,r=n.length;t0){r.children=[];for(let t=0;t0){r.animations=[];for(let t=0;t0&&(n.geometries=t),r.length>0&&(n.materials=r),i.length>0&&(n.textures=i),o.length>0&&(n.images=o),s.length>0&&(n.shapes=s),c.length>0&&(n.skeletons=c),l.length>0&&(n.animations=l),u.length>0&&(n.nodes=u)}return n.object=r,n;function a(e){let t=[];for(let n in e){let r=e[n];delete r.metadata,t.push(r)}return t}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.pivot=e.pivot===null?null:e.pivot.clone(),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.static=e.static,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let t=0;t.025?(c.inputState.pinching=!1,this.dispatchEvent({type:`pinchend`,handedness:e.handedness,target:this})):!c.inputState.pinching&&o<=.015&&(c.inputState.pinching=!0,this.dispatchEvent({type:`pinchstart`,handedness:e.handedness,target:this}))}else s!==null&&e.gripSpace&&(i=t.getPose(e.gripSpace,n),i!==null&&(s.matrix.fromArray(i.transform.matrix),s.matrix.decompose(s.position,s.rotation,s.scale),s.matrixWorldNeedsUpdate=!0,i.linearVelocity?(s.hasLinearVelocity=!0,s.linearVelocity.copy(i.linearVelocity)):s.hasLinearVelocity=!1,i.angularVelocity?(s.hasAngularVelocity=!0,s.angularVelocity.copy(i.angularVelocity)):s.hasAngularVelocity=!1,s.eventsEnabled&&s.dispatchEvent({type:`gripUpdated`,data:e,target:this})));o!==null&&(r=t.getPose(e.targetRaySpace,n),r===null&&i!==null&&(r=i),r!==null&&(o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,r.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(r.linearVelocity)):o.hasLinearVelocity=!1,r.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(r.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(Nn)))}return o!==null&&(o.visible=r!==null),s!==null&&(s.visible=i!==null),c!==null&&(c.visible=a!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){let n=new Mn;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}},Fn={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},In={h:0,s:0,l:0},Ln={h:0,s:0,l:0};function Rn(e,t,n){return n<0&&(n+=1),n>1&&--n,n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*6*(2/3-n):e}var X=class{constructor(e,t,n){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,n)}set(e,t,n){if(t===void 0&&n===void 0){let t=e;t&&t.isColor?this.copy(t):typeof t==`number`?this.setHex(t):typeof t==`string`&&this.setStyle(t)}else this.setRGB(e,t,n);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=qe){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,Y.colorSpaceToWorking(this,t),this}setRGB(e,t,n,r=Y.workingColorSpace){return this.r=e,this.g=t,this.b=n,Y.colorSpaceToWorking(this,r),this}setHSL(e,t,n,r=Y.workingColorSpace){if(e=ht(e,1),t=W(t,0,1),n=W(n,0,1),t===0)this.r=this.g=this.b=n;else{let r=n<=.5?n*(1+t):n+t-n*t,i=2*n-r;this.r=Rn(i,r,e+1/3),this.g=Rn(i,r,e),this.b=Rn(i,r,e-1/3)}return Y.colorSpaceToWorking(this,r),this}setStyle(e,t=qe){function n(t){t!==void 0&&parseFloat(t)<1&&H(`Color: Alpha component of `+e+` will be ignored.`)}let r;if(r=/^(\w+)\(([^\)]*)\)/.exec(e)){let i,a=r[1],o=r[2];switch(a){case`rgb`:case`rgba`:if(i=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(i[4]),this.setRGB(Math.min(255,parseInt(i[1],10))/255,Math.min(255,parseInt(i[2],10))/255,Math.min(255,parseInt(i[3],10))/255,t);if(i=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(i[4]),this.setRGB(Math.min(100,parseInt(i[1],10))/100,Math.min(100,parseInt(i[2],10))/100,Math.min(100,parseInt(i[3],10))/100,t);break;case`hsl`:case`hsla`:if(i=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(i[4]),this.setHSL(parseFloat(i[1])/360,parseFloat(i[2])/100,parseFloat(i[3])/100,t);break;default:H(`Color: Unknown color model `+e)}}else if(r=/^\#([A-Fa-f\d]+)$/.exec(e)){let n=r[1],i=n.length;if(i===3)return this.setRGB(parseInt(n.charAt(0),16)/15,parseInt(n.charAt(1),16)/15,parseInt(n.charAt(2),16)/15,t);if(i===6)return this.setHex(parseInt(n,16),t);H(`Color: Invalid hex color `+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=qe){let n=Fn[e.toLowerCase()];return n===void 0?H(`Color: Unknown color `+e):this.setHex(n,t),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=Ht(e.r),this.g=Ht(e.g),this.b=Ht(e.b),this}copyLinearToSRGB(e){return this.r=Ut(e.r),this.g=Ut(e.g),this.b=Ut(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=qe){return Y.workingToColorSpace(zn.copy(this),e),Math.round(W(zn.r*255,0,255))*65536+Math.round(W(zn.g*255,0,255))*256+Math.round(W(zn.b*255,0,255))}getHexString(e=qe){return(`000000`+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=Y.workingColorSpace){Y.workingToColorSpace(zn.copy(this),t);let n=zn.r,r=zn.g,i=zn.b,a=Math.max(n,r,i),o=Math.min(n,r,i),s,c,l=(o+a)/2;if(o===a)s=0,c=0;else{let e=a-o;switch(c=l<=.5?e/(a+o):e/(2-a-o),a){case n:s=(r-i)/e+(r0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}},Hn=new q,Un=new q,Wn=new q,Gn=new q,Kn=new q,qn=new q,Jn=new q,Yn=new q,Xn=new q,Zn=new q,Qn=new Qt,$n=new Qt,er=new Qt,tr=class e{constructor(e=new q,t=new q,n=new q){this.a=e,this.b=t,this.c=n}static getNormal(e,t,n,r){r.subVectors(n,t),Hn.subVectors(e,t),r.cross(Hn);let i=r.lengthSq();return i>0?r.multiplyScalar(1/Math.sqrt(i)):r.set(0,0,0)}static getBarycoord(e,t,n,r,i){Hn.subVectors(r,t),Un.subVectors(n,t),Wn.subVectors(e,t);let a=Hn.dot(Hn),o=Hn.dot(Un),s=Hn.dot(Wn),c=Un.dot(Un),l=Un.dot(Wn),u=a*c-o*o;if(u===0)return i.set(0,0,0),null;let d=1/u,f=(c*s-o*l)*d,p=(a*l-o*s)*d;return i.set(1-f-p,p,f)}static containsPoint(e,t,n,r){return this.getBarycoord(e,t,n,r,Gn)!==null&&Gn.x>=0&&Gn.y>=0&&Gn.x+Gn.y<=1}static getInterpolation(e,t,n,r,i,a,o,s){return this.getBarycoord(e,t,n,r,Gn)===null?(s.x=0,s.y=0,`z`in s&&(s.z=0),`w`in s&&(s.w=0),null):(s.setScalar(0),s.addScaledVector(i,Gn.x),s.addScaledVector(a,Gn.y),s.addScaledVector(o,Gn.z),s)}static getInterpolatedAttribute(e,t,n,r,i,a){return Qn.setScalar(0),$n.setScalar(0),er.setScalar(0),Qn.fromBufferAttribute(e,t),$n.fromBufferAttribute(e,n),er.fromBufferAttribute(e,r),a.setScalar(0),a.addScaledVector(Qn,i.x),a.addScaledVector($n,i.y),a.addScaledVector(er,i.z),a}static isFrontFacing(e,t,n,r){return Hn.subVectors(n,t),Un.subVectors(e,t),Hn.cross(Un).dot(r)<0}set(e,t,n){return this.a.copy(e),this.b.copy(t),this.c.copy(n),this}setFromPointsAndIndices(e,t,n,r){return this.a.copy(e[t]),this.b.copy(e[n]),this.c.copy(e[r]),this}setFromAttributeAndIndices(e,t,n,r){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,n),this.c.fromBufferAttribute(e,r),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return Hn.subVectors(this.c,this.b),Un.subVectors(this.a,this.b),Hn.cross(Un).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(t){return e.getNormal(this.a,this.b,this.c,t)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(t,n){return e.getBarycoord(t,this.a,this.b,this.c,n)}getInterpolation(t,n,r,i,a){return e.getInterpolation(t,this.a,this.b,this.c,n,r,i,a)}containsPoint(t){return e.containsPoint(t,this.a,this.b,this.c)}isFrontFacing(t){return e.isFrontFacing(this.a,this.b,this.c,t)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){let n=this.a,r=this.b,i=this.c,a,o;Kn.subVectors(r,n),qn.subVectors(i,n),Yn.subVectors(e,n);let s=Kn.dot(Yn),c=qn.dot(Yn);if(s<=0&&c<=0)return t.copy(n);Xn.subVectors(e,r);let l=Kn.dot(Xn),u=qn.dot(Xn);if(l>=0&&u<=l)return t.copy(r);let d=s*u-l*c;if(d<=0&&s>=0&&l<=0)return a=s/(s-l),t.copy(n).addScaledVector(Kn,a);Zn.subVectors(e,i);let f=Kn.dot(Zn),p=qn.dot(Zn);if(p>=0&&f<=p)return t.copy(i);let m=f*c-s*p;if(m<=0&&c>=0&&p<=0)return o=c/(c-p),t.copy(n).addScaledVector(qn,o);let h=l*p-f*u;if(h<=0&&u-l>=0&&f-p>=0)return Jn.subVectors(i,r),o=(u-l)/(u-l+(f-p)),t.copy(r).addScaledVector(Jn,o);let g=1/(h+m+d);return a=m*g,o=d*g,t.copy(n).addScaledVector(Kn,a).addScaledVector(qn,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}},nr=class{constructor(e=new q(1/0,1/0,1/0),t=new q(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,n=e.length;t=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,ir),ir.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,n;return e.normal.x>0?(t=e.normal.x*this.min.x,n=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,n=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,n+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,n+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,n+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,n+=e.normal.z*this.min.z),t<=-e.constant&&n>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(fr),pr.subVectors(this.max,fr),or.subVectors(e.a,fr),sr.subVectors(e.b,fr),cr.subVectors(e.c,fr),lr.subVectors(sr,or),ur.subVectors(cr,sr),dr.subVectors(or,cr);let t=[0,-lr.z,lr.y,0,-ur.z,ur.y,0,-dr.z,dr.y,lr.z,0,-lr.x,ur.z,0,-ur.x,dr.z,0,-dr.x,-lr.y,lr.x,0,-ur.y,ur.x,0,-dr.y,dr.x,0];return!gr(t,or,sr,cr,pr)||(t=[1,0,0,0,1,0,0,0,1],!gr(t,or,sr,cr,pr))?!1:(mr.crossVectors(lr,ur),t=[mr.x,mr.y,mr.z],gr(t,or,sr,cr,pr))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,ir).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(ir).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(rr[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),rr[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),rr[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),rr[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),rr[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),rr[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),rr[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),rr[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(rr),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(e){return this.min.fromArray(e.min),this.max.fromArray(e.max),this}},rr=[new q,new q,new q,new q,new q,new q,new q,new q],ir=new q,ar=new nr,or=new q,sr=new q,cr=new q,lr=new q,ur=new q,dr=new q,fr=new q,pr=new q,mr=new q,hr=new q;function gr(e,t,n,r,i){for(let a=0,o=e.length-3;a<=o;a+=3){hr.fromArray(e,a);let o=i.x*Math.abs(hr.x)+i.y*Math.abs(hr.y)+i.z*Math.abs(hr.z),s=t.dot(hr),c=n.dot(hr),l=r.dot(hr);if(Math.max(-Math.max(s,c,l),Math.min(s,c,l))>o)return!1}return!0}var _r=new q,vr=new K,yr=0,br=class extends lt{constructor(e,t,n=!1){if(super(),Array.isArray(e))throw TypeError(`THREE.BufferAttribute: array should be a Typed Array.`);this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:yr++}),this.name=``,this.array=e,this.itemSize=t,this.count=e===void 0?0:e.length/t,this.normalized=n,this.usage=Qe,this.updateRanges=[],this.gpuType=D,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,n){e*=this.itemSize,n*=t.itemSize;for(let r=0,i=this.itemSize;rthis.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius*=e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;Tr.subVectors(e,this.center);let t=Tr.lengthSq();if(t>this.radius*this.radius){let e=Math.sqrt(t),n=(e-this.radius)*.5;this.center.addScaledVector(Tr,n/e),this.radius+=n}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(Er.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Tr.copy(e.center).add(Er)),this.expandByPoint(Tr.copy(e.center).sub(Er))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(e){return this.radius=e.radius,this.center.fromArray(e.center),this}},Or=0,kr=new rn,Ar=new jn,jr=new q,Mr=new nr,Nr=new nr,Pr=new q,Fr=class e extends lt{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:Or++}),this.uuid=mt(),this.name=``,this.type=`BufferGeometry`,this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={},this._transformed=!1}getIndex(){return this.index}setIndex(e){return this.index=Array.isArray(e)?new(et(e)?Sr:xr)(e,1):e,this}setIndirect(e,t=0){return this.indirect=e,this.indirectOffset=t,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return this.attributes[e]!==void 0}addGroup(e,t,n=0){this.groups.push({start:e,count:t,materialIndex:n})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){let t=this.attributes.position;t!==void 0&&(t.applyMatrix4(e),t.needsUpdate=!0);let n=this.attributes.normal;if(n!==void 0){let t=new J().getNormalMatrix(e);n.applyNormalMatrix(t),n.needsUpdate=!0}let r=this.attributes.tangent;return r!==void 0&&(r.transformDirection(e),r.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this._transformed=!0,this}applyQuaternion(e){return kr.makeRotationFromQuaternion(e),this.applyMatrix4(kr),this}rotateX(e){return kr.makeRotationX(e),this.applyMatrix4(kr),this}rotateY(e){return kr.makeRotationY(e),this.applyMatrix4(kr),this}rotateZ(e){return kr.makeRotationZ(e),this.applyMatrix4(kr),this}translate(e,t,n){return kr.makeTranslation(e,t,n),this.applyMatrix4(kr),this}scale(e,t,n){return kr.makeScale(e,t,n),this.applyMatrix4(kr),this}lookAt(e){return Ar.lookAt(e),Ar.updateMatrix(),this.applyMatrix4(Ar.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(jr).negate(),this.translate(jr.x,jr.y,jr.z),this}setFromPoints(e){let t=this.getAttribute(`position`);if(t===void 0){let t=[];for(let n=0,r=e.length;nt.count&&H(`BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.`),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new nr);let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){U(`BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.`,this),this.boundingBox.set(new q(-1/0,-1/0,-1/0),new q(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let e=0,n=t.length;e0&&(e.userData=this.userData),this.parameters!==void 0&&this._transformed!==!0){let t=this.parameters;for(let n in t)t[n]!==void 0&&(e[n]=t[n]);return e}e.data={attributes:{}};let t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});let n=this.attributes;for(let t in n){let r=n[t];e.data.attributes[t]=r.toJSON(e.data)}let r={},i=!1;for(let t in this.morphAttributes){let n=this.morphAttributes[t],a=[];for(let t=0,r=n.length;t0&&(r[t]=a,i=!0)}i&&(e.data.morphAttributes=r,e.data.morphTargetsRelative=this.morphTargetsRelative);let a=this.groups;a.length>0&&(e.data.groups=JSON.parse(JSON.stringify(a)));let o=this.boundingSphere;return o!==null&&(e.data.boundingSphere=o.toJSON()),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;let t={};this.name=e.name;let n=e.index;n!==null&&this.setIndex(n.clone());let r=e.attributes;for(let e in r){let n=r[e];this.setAttribute(e,n.clone(t))}let i=e.morphAttributes;for(let e in i){let n=[],r=i[e];for(let e=0,i=r.length;e0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(let t in e){let n=e[t];if(n===void 0){H(`Material: parameter '${t}' has value of undefined.`);continue}let r=this[t];if(r===void 0){H(`Material: '${t}' is not a property of THREE.${this.type}.`);continue}r&&r.isColor?r.set(n):r&&r.isVector2&&n&&n.isVector2||r&&r.isEuler&&n&&n.isEuler||r&&r.isVector3&&n&&n.isVector3?r.copy(n):this[t]=n}}toJSON(e){let t=e===void 0||typeof e==`string`;t&&(e={textures:{},images:{}});let n={metadata:{version:4.7,type:`Material`,generator:`Material.toJSON`}};n.uuid=this.uuid,n.type=this.type,this.name!==``&&(n.name=this.name),this.color&&this.color.isColor&&(n.color=this.color.getHex()),this.roughness!==void 0&&(n.roughness=this.roughness),this.metalness!==void 0&&(n.metalness=this.metalness),this.sheen!==void 0&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(n.shininess=this.shininess),this.clearcoat!==void 0&&(n.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(n.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(n.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),this.dispersion!==void 0&&(n.dispersion=this.dispersion),this.iridescence!==void 0&&(n.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(n.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(n.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(n.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(n.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(n.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(n.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(e).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(e).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(e).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(e).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(e).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(n.combine=this.combine)),this.envMapRotation!==void 0&&(n.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(n.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(n.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(n.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(n.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(n.size=this.size),this.shadowSide!==null&&(n.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(n.sizeAttenuation=this.sizeAttenuation),this.blending!==1&&(n.blending=this.blending),this.side!==0&&(n.side=this.side),this.vertexColors===!0&&(n.vertexColors=!0),this.opacity<1&&(n.opacity=this.opacity),this.transparent===!0&&(n.transparent=!0),this.blendSrc!==204&&(n.blendSrc=this.blendSrc),this.blendDst!==205&&(n.blendDst=this.blendDst),this.blendEquation!==100&&(n.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(n.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(n.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(n.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(n.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(n.blendAlpha=this.blendAlpha),this.depthFunc!==3&&(n.depthFunc=this.depthFunc),this.depthTest===!1&&(n.depthTest=this.depthTest),this.depthWrite===!1&&(n.depthWrite=this.depthWrite),this.colorWrite===!1&&(n.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(n.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==519&&(n.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(n.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(n.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==7680&&(n.stencilFail=this.stencilFail),this.stencilZFail!==7680&&(n.stencilZFail=this.stencilZFail),this.stencilZPass!==7680&&(n.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(n.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(n.rotation=this.rotation),this.polygonOffset===!0&&(n.polygonOffset=!0),this.polygonOffsetFactor!==0&&(n.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(n.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(n.linewidth=this.linewidth),this.dashSize!==void 0&&(n.dashSize=this.dashSize),this.gapSize!==void 0&&(n.gapSize=this.gapSize),this.scale!==void 0&&(n.scale=this.scale),this.dithering===!0&&(n.dithering=!0),this.alphaTest>0&&(n.alphaTest=this.alphaTest),this.alphaHash===!0&&(n.alphaHash=!0),this.alphaToCoverage===!0&&(n.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(n.premultipliedAlpha=!0),this.forceSinglePass===!0&&(n.forceSinglePass=!0),this.allowOverride===!1&&(n.allowOverride=!1),this.wireframe===!0&&(n.wireframe=!0),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!==`round`&&(n.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!==`round`&&(n.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(n.flatShading=!0),this.visible===!1&&(n.visible=!1),this.toneMapped===!1&&(n.toneMapped=!1),this.fog===!1&&(n.fog=!1),Object.keys(this.userData).length>0&&(n.userData=this.userData);function r(e){let t=[];for(let n in e){let r=e[n];delete r.metadata,t.push(r)}return t}if(t){let t=r(e.textures),i=r(e.images);t.length>0&&(n.textures=t),i.length>0&&(n.images=i)}return n}fromJSON(e,t){if(e.uuid!==void 0&&(this.uuid=e.uuid),e.name!==void 0&&(this.name=e.name),e.color!==void 0&&this.color!==void 0&&this.color.setHex(e.color),e.roughness!==void 0&&(this.roughness=e.roughness),e.metalness!==void 0&&(this.metalness=e.metalness),e.sheen!==void 0&&(this.sheen=e.sheen),e.sheenColor!==void 0&&(this.sheenColor=new X().setHex(e.sheenColor)),e.sheenRoughness!==void 0&&(this.sheenRoughness=e.sheenRoughness),e.emissive!==void 0&&this.emissive!==void 0&&this.emissive.setHex(e.emissive),e.specular!==void 0&&this.specular!==void 0&&this.specular.setHex(e.specular),e.specularIntensity!==void 0&&(this.specularIntensity=e.specularIntensity),e.specularColor!==void 0&&this.specularColor!==void 0&&this.specularColor.setHex(e.specularColor),e.shininess!==void 0&&(this.shininess=e.shininess),e.clearcoat!==void 0&&(this.clearcoat=e.clearcoat),e.clearcoatRoughness!==void 0&&(this.clearcoatRoughness=e.clearcoatRoughness),e.dispersion!==void 0&&(this.dispersion=e.dispersion),e.iridescence!==void 0&&(this.iridescence=e.iridescence),e.iridescenceIOR!==void 0&&(this.iridescenceIOR=e.iridescenceIOR),e.iridescenceThicknessRange!==void 0&&(this.iridescenceThicknessRange=e.iridescenceThicknessRange),e.transmission!==void 0&&(this.transmission=e.transmission),e.thickness!==void 0&&(this.thickness=e.thickness),e.attenuationDistance!==void 0&&(this.attenuationDistance=e.attenuationDistance),e.attenuationColor!==void 0&&this.attenuationColor!==void 0&&this.attenuationColor.setHex(e.attenuationColor),e.anisotropy!==void 0&&(this.anisotropy=e.anisotropy),e.anisotropyRotation!==void 0&&(this.anisotropyRotation=e.anisotropyRotation),e.fog!==void 0&&(this.fog=e.fog),e.flatShading!==void 0&&(this.flatShading=e.flatShading),e.blending!==void 0&&(this.blending=e.blending),e.combine!==void 0&&(this.combine=e.combine),e.side!==void 0&&(this.side=e.side),e.shadowSide!==void 0&&(this.shadowSide=e.shadowSide),e.opacity!==void 0&&(this.opacity=e.opacity),e.transparent!==void 0&&(this.transparent=e.transparent),e.alphaTest!==void 0&&(this.alphaTest=e.alphaTest),e.alphaHash!==void 0&&(this.alphaHash=e.alphaHash),e.depthFunc!==void 0&&(this.depthFunc=e.depthFunc),e.depthTest!==void 0&&(this.depthTest=e.depthTest),e.depthWrite!==void 0&&(this.depthWrite=e.depthWrite),e.colorWrite!==void 0&&(this.colorWrite=e.colorWrite),e.blendSrc!==void 0&&(this.blendSrc=e.blendSrc),e.blendDst!==void 0&&(this.blendDst=e.blendDst),e.blendEquation!==void 0&&(this.blendEquation=e.blendEquation),e.blendSrcAlpha!==void 0&&(this.blendSrcAlpha=e.blendSrcAlpha),e.blendDstAlpha!==void 0&&(this.blendDstAlpha=e.blendDstAlpha),e.blendEquationAlpha!==void 0&&(this.blendEquationAlpha=e.blendEquationAlpha),e.blendColor!==void 0&&this.blendColor!==void 0&&this.blendColor.setHex(e.blendColor),e.blendAlpha!==void 0&&(this.blendAlpha=e.blendAlpha),e.stencilWriteMask!==void 0&&(this.stencilWriteMask=e.stencilWriteMask),e.stencilFunc!==void 0&&(this.stencilFunc=e.stencilFunc),e.stencilRef!==void 0&&(this.stencilRef=e.stencilRef),e.stencilFuncMask!==void 0&&(this.stencilFuncMask=e.stencilFuncMask),e.stencilFail!==void 0&&(this.stencilFail=e.stencilFail),e.stencilZFail!==void 0&&(this.stencilZFail=e.stencilZFail),e.stencilZPass!==void 0&&(this.stencilZPass=e.stencilZPass),e.stencilWrite!==void 0&&(this.stencilWrite=e.stencilWrite),e.wireframe!==void 0&&(this.wireframe=e.wireframe),e.wireframeLinewidth!==void 0&&(this.wireframeLinewidth=e.wireframeLinewidth),e.wireframeLinecap!==void 0&&(this.wireframeLinecap=e.wireframeLinecap),e.wireframeLinejoin!==void 0&&(this.wireframeLinejoin=e.wireframeLinejoin),e.rotation!==void 0&&(this.rotation=e.rotation),e.linewidth!==void 0&&(this.linewidth=e.linewidth),e.dashSize!==void 0&&(this.dashSize=e.dashSize),e.gapSize!==void 0&&(this.gapSize=e.gapSize),e.scale!==void 0&&(this.scale=e.scale),e.polygonOffset!==void 0&&(this.polygonOffset=e.polygonOffset),e.polygonOffsetFactor!==void 0&&(this.polygonOffsetFactor=e.polygonOffsetFactor),e.polygonOffsetUnits!==void 0&&(this.polygonOffsetUnits=e.polygonOffsetUnits),e.dithering!==void 0&&(this.dithering=e.dithering),e.alphaToCoverage!==void 0&&(this.alphaToCoverage=e.alphaToCoverage),e.premultipliedAlpha!==void 0&&(this.premultipliedAlpha=e.premultipliedAlpha),e.forceSinglePass!==void 0&&(this.forceSinglePass=e.forceSinglePass),e.allowOverride!==void 0&&(this.allowOverride=e.allowOverride),e.visible!==void 0&&(this.visible=e.visible),e.toneMapped!==void 0&&(this.toneMapped=e.toneMapped),e.userData!==void 0&&(this.userData=e.userData),e.vertexColors!==void 0&&(this.vertexColors=typeof e.vertexColors==`number`?e.vertexColors>0:e.vertexColors),e.size!==void 0&&(this.size=e.size),e.sizeAttenuation!==void 0&&(this.sizeAttenuation=e.sizeAttenuation),e.map!==void 0&&(this.map=t[e.map]||null),e.matcap!==void 0&&(this.matcap=t[e.matcap]||null),e.alphaMap!==void 0&&(this.alphaMap=t[e.alphaMap]||null),e.bumpMap!==void 0&&(this.bumpMap=t[e.bumpMap]||null),e.bumpScale!==void 0&&(this.bumpScale=e.bumpScale),e.normalMap!==void 0&&(this.normalMap=t[e.normalMap]||null),e.normalMapType!==void 0&&(this.normalMapType=e.normalMapType),e.normalScale!==void 0){let t=e.normalScale;Array.isArray(t)===!1&&(t=[t,t]),this.normalScale=new K().fromArray(t)}return e.displacementMap!==void 0&&(this.displacementMap=t[e.displacementMap]||null),e.displacementScale!==void 0&&(this.displacementScale=e.displacementScale),e.displacementBias!==void 0&&(this.displacementBias=e.displacementBias),e.roughnessMap!==void 0&&(this.roughnessMap=t[e.roughnessMap]||null),e.metalnessMap!==void 0&&(this.metalnessMap=t[e.metalnessMap]||null),e.emissiveMap!==void 0&&(this.emissiveMap=t[e.emissiveMap]||null),e.emissiveIntensity!==void 0&&(this.emissiveIntensity=e.emissiveIntensity),e.specularMap!==void 0&&(this.specularMap=t[e.specularMap]||null),e.specularIntensityMap!==void 0&&(this.specularIntensityMap=t[e.specularIntensityMap]||null),e.specularColorMap!==void 0&&(this.specularColorMap=t[e.specularColorMap]||null),e.envMap!==void 0&&(this.envMap=t[e.envMap]||null),e.envMapRotation!==void 0&&this.envMapRotation.fromArray(e.envMapRotation),e.envMapIntensity!==void 0&&(this.envMapIntensity=e.envMapIntensity),e.reflectivity!==void 0&&(this.reflectivity=e.reflectivity),e.refractionRatio!==void 0&&(this.refractionRatio=e.refractionRatio),e.lightMap!==void 0&&(this.lightMap=t[e.lightMap]||null),e.lightMapIntensity!==void 0&&(this.lightMapIntensity=e.lightMapIntensity),e.aoMap!==void 0&&(this.aoMap=t[e.aoMap]||null),e.aoMapIntensity!==void 0&&(this.aoMapIntensity=e.aoMapIntensity),e.gradientMap!==void 0&&(this.gradientMap=t[e.gradientMap]||null),e.clearcoatMap!==void 0&&(this.clearcoatMap=t[e.clearcoatMap]||null),e.clearcoatRoughnessMap!==void 0&&(this.clearcoatRoughnessMap=t[e.clearcoatRoughnessMap]||null),e.clearcoatNormalMap!==void 0&&(this.clearcoatNormalMap=t[e.clearcoatNormalMap]||null),e.clearcoatNormalScale!==void 0&&(this.clearcoatNormalScale=new K().fromArray(e.clearcoatNormalScale)),e.iridescenceMap!==void 0&&(this.iridescenceMap=t[e.iridescenceMap]||null),e.iridescenceThicknessMap!==void 0&&(this.iridescenceThicknessMap=t[e.iridescenceThicknessMap]||null),e.transmissionMap!==void 0&&(this.transmissionMap=t[e.transmissionMap]||null),e.thicknessMap!==void 0&&(this.thicknessMap=t[e.thicknessMap]||null),e.anisotropyMap!==void 0&&(this.anisotropyMap=t[e.anisotropyMap]||null),e.sheenColorMap!==void 0&&(this.sheenColorMap=t[e.sheenColorMap]||null),e.sheenRoughnessMap!==void 0&&(this.sheenRoughnessMap=t[e.sheenRoughnessMap]||null),this}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;let t=e.clippingPlanes,n=null;if(t!==null){let e=t.length;n=Array(e);for(let r=0;r!==e;++r)n[r]=t[r].clone()}return this.clippingPlanes=n,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.allowOverride=e.allowOverride,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:`dispose`})}set needsUpdate(e){e===!0&&this.version++}},Vr=class extends Br{constructor(e){super(),this.isSpriteMaterial=!0,this.type=`SpriteMaterial`,this.color=new X(16777215),this.map=null,this.alphaMap=null,this.rotation=0,this.sizeAttenuation=!0,this.transparent=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.rotation=e.rotation,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}},Hr,Ur=new q,Wr=new q,Gr=new q,Kr=new K,qr=new K,Jr=new rn,Yr=new q,Xr=new q,Zr=new q,Qr=new K,$r=new K,ei=new K,ti=class extends jn{constructor(e=new Vr){if(super(),this.isSprite=!0,this.type=`Sprite`,Hr===void 0){Hr=new Fr;let e=new Ir(new Float32Array([-.5,-.5,0,0,0,.5,-.5,0,1,0,.5,.5,0,1,1,-.5,.5,0,0,1]),5);Hr.setIndex([0,1,2,0,2,3]),Hr.setAttribute(`position`,new Rr(e,3,0,!1)),Hr.setAttribute(`uv`,new Rr(e,2,3,!1))}this.geometry=Hr,this.material=e,this.center=new K(.5,.5),this.count=1}raycast(e,t){e.camera===null&&U(`Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.`),Wr.setFromMatrixScale(this.matrixWorld),Jr.copy(e.camera.matrixWorld),this.modelViewMatrix.multiplyMatrices(e.camera.matrixWorldInverse,this.matrixWorld),Gr.setFromMatrixPosition(this.modelViewMatrix),e.camera.isPerspectiveCamera&&this.material.sizeAttenuation===!1&&Wr.multiplyScalar(-Gr.z);let n=this.material.rotation,r,i;n!==0&&(i=Math.cos(n),r=Math.sin(n));let a=this.center;ni(Yr.set(-.5,-.5,0),Gr,a,Wr,r,i),ni(Xr.set(.5,-.5,0),Gr,a,Wr,r,i),ni(Zr.set(.5,.5,0),Gr,a,Wr,r,i),Qr.set(0,0),$r.set(1,0),ei.set(1,1);let o=e.ray.intersectTriangle(Yr,Xr,Zr,!1,Ur);if(o===null&&(ni(Xr.set(-.5,.5,0),Gr,a,Wr,r,i),$r.set(0,1),o=e.ray.intersectTriangle(Yr,Zr,Xr,!1,Ur),o===null))return;let s=e.ray.origin.distanceTo(Ur);se.far||t.push({distance:s,point:Ur.clone(),uv:tr.getInterpolation(Ur,Yr,Xr,Zr,Qr,$r,ei,new K),face:null,object:this})}copy(e,t){return super.copy(e,t),e.center!==void 0&&this.center.copy(e.center),this.material=e.material,this}};function ni(e,t,n,r,i,a){Kr.subVectors(e,n).addScalar(.5).multiply(r),i===void 0?qr.copy(Kr):(qr.x=a*Kr.x-i*Kr.y,qr.y=i*Kr.x+a*Kr.y),e.copy(t),e.x+=qr.x,e.y+=qr.y,e.applyMatrix4(Jr)}var ri=new q,ii=new q,ai=new q,oi=new q,si=new q,ci=new q,li=new q,ui=class{constructor(e=new q,t=new q(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,ri)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);let n=t.dot(this.direction);return n<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,n)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){let t=ri.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(ri.copy(this.origin).addScaledVector(this.direction,t),ri.distanceToSquared(e))}distanceSqToSegment(e,t,n,r){ii.copy(e).add(t).multiplyScalar(.5),ai.copy(t).sub(e).normalize(),oi.copy(this.origin).sub(ii);let i=e.distanceTo(t)*.5,a=-this.direction.dot(ai),o=oi.dot(this.direction),s=-oi.dot(ai),c=oi.lengthSq(),l=Math.abs(1-a*a),u,d,f,p;if(l>0){if(u=a*s-o,d=a*o-s,p=i*l,u>=0){if(d>=-p){if(d<=p){let e=1/l;u*=e,d*=e,f=u*(u+a*d+2*o)+d*(a*u+d+2*s)+c}else d=i,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*s)+c}else d=-i,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*s)+c}else d<=-p?(u=Math.max(0,-(-a*i+o)),d=u>0?-i:Math.min(Math.max(-i,-s),i),f=-u*u+d*(d+2*s)+c):d<=p?(u=0,d=Math.min(Math.max(-i,-s),i),f=d*(d+2*s)+c):(u=Math.max(0,-(a*i+o)),d=u>0?i:Math.min(Math.max(-i,-s),i),f=-u*u+d*(d+2*s)+c)}else d=a>0?-i:i,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*s)+c;return n&&n.copy(this.origin).addScaledVector(this.direction,u),r&&r.copy(ii).addScaledVector(ai,d),f}intersectSphere(e,t){ri.subVectors(e.center,this.origin);let n=ri.dot(this.direction),r=ri.dot(ri)-n*n,i=e.radius*e.radius;if(r>i)return null;let a=Math.sqrt(i-r),o=n-a,s=n+a;return s<0?null:o<0?this.at(s,t):this.at(o,t)}intersectsSphere(e){return e.radius<0?!1:this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){let t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;let n=-(this.origin.dot(e.normal)+e.constant)/t;return n>=0?n:null}intersectPlane(e,t){let n=this.distanceToPlane(e);return n===null?null:this.at(n,t)}intersectsPlane(e){let t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let n,r,i,a,o,s,c=1/this.direction.x,l=1/this.direction.y,u=1/this.direction.z,d=this.origin;return c>=0?(n=(e.min.x-d.x)*c,r=(e.max.x-d.x)*c):(n=(e.max.x-d.x)*c,r=(e.min.x-d.x)*c),l>=0?(i=(e.min.y-d.y)*l,a=(e.max.y-d.y)*l):(i=(e.max.y-d.y)*l,a=(e.min.y-d.y)*l),n>a||i>r||((i>n||isNaN(n))&&(n=i),(a=0?(o=(e.min.z-d.z)*u,s=(e.max.z-d.z)*u):(o=(e.max.z-d.z)*u,s=(e.min.z-d.z)*u),n>s||o>r)||((o>n||n!==n)&&(n=o),(s=0?n:r,t)}intersectsBox(e){return this.intersectBox(e,ri)!==null}intersectTriangle(e,t,n,r,i){si.subVectors(t,e),ci.subVectors(n,e),li.crossVectors(si,ci);let a=this.direction.dot(li),o;if(a>0){if(r)return null;o=1}else if(a<0)o=-1,a=-a;else return null;oi.subVectors(this.origin,e);let s=o*this.direction.dot(ci.crossVectors(oi,ci));if(s<0)return null;let c=o*this.direction.dot(si.cross(oi));if(c<0||s+c>a)return null;let l=-o*oi.dot(li);return l<0?null:this.at(l/a,i)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}},di=class extends Br{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type=`MeshBasicMaterial`,this.color=new X(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new mn,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap=`round`,this.wireframeLinejoin=`round`,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}},fi=new rn,pi=new ui,mi=new Dr,hi=new q,gi=new q,_i=new q,vi=new q,yi=new q,bi=new q,xi=new q,Si=new q,Ci=class extends jn{constructor(e=new Fr,t=new di){super(),this.isMesh=!0,this.type=`Mesh`,this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),e.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=e.morphTargetInfluences.slice()),e.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}updateMorphTargets(){let e=this.geometry.morphAttributes,t=Object.keys(e);if(t.length>0){let n=e[t[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e(e.far-e.near)**2))&&(fi.copy(i).invert(),pi.copy(e.ray).applyMatrix4(fi),(n.boundingBox===null||pi.intersectsBox(n.boundingBox)!==!1)&&this._computeIntersections(e,t,pi)))}_computeIntersections(e,t,n){let r,i=this.geometry,a=this.material,o=i.index,s=i.attributes.position,c=i.attributes.uv,l=i.attributes.uv1,u=i.attributes.normal,d=i.groups,f=i.drawRange;if(o!==null){if(Array.isArray(a))for(let i=0,s=d.length;in.far?null:{distance:l,point:Si.clone(),object:e}}function Ti(e,t,n,r,i,a,o,s,c,l){e.getVertexPosition(s,gi),e.getVertexPosition(c,_i),e.getVertexPosition(l,vi);let u=wi(e,t,n,r,gi,_i,vi,xi);if(u){let e=new q;tr.getBarycoord(xi,gi,_i,vi,e),i&&(u.uv=tr.getInterpolatedAttribute(i,s,c,l,e,new K)),a&&(u.uv1=tr.getInterpolatedAttribute(a,s,c,l,e,new K)),o&&(u.normal=tr.getInterpolatedAttribute(o,s,c,l,e,new q),u.normal.dot(r.direction)>0&&u.normal.multiplyScalar(-1));let t={a:s,b:c,c:l,normal:new q,materialIndex:0};tr.getNormal(gi,_i,vi,t.normal),u.face=t,u.barycoord=e}return u}var Ei=class extends Zt{constructor(e=null,t=1,n=1,r,i,a,o,s,c=h,l=h,u,d){super(null,a,o,s,c,l,r,i,u,d),this.isDataTexture=!0,this.image={data:e,width:t,height:n},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}},Di=new q,Oi=new q,ki=new J,Ai=class{constructor(e=new q(1,0,0),t=0){this.isPlane=!0,this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,n,r){return this.normal.set(e,t,n),this.constant=r,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,n){let r=Di.subVectors(n,t).cross(Oi.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(r,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){let e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t,n=!0){let r=e.delta(Di),i=this.normal.dot(r);if(i===0)return this.distanceToPoint(e.start)===0?t.copy(e.start):null;let a=-(e.start.dot(this.normal)+this.constant)/i;return n===!0&&(a<0||a>1)?null:t.copy(e.start).addScaledVector(r,a)}intersectsLine(e){let t=this.distanceToPoint(e.start),n=this.distanceToPoint(e.end);return t<0&&n>0||n<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){let n=t||ki.getNormalMatrix(e),r=this.coplanarPoint(Di).applyMatrix4(e),i=this.normal.applyMatrix3(n).normalize();return this.constant=-r.dot(i),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}},ji=new Dr,Mi=new K(.5,.5),Ni=new q,Pi=class{constructor(e=new Ai,t=new Ai,n=new Ai,r=new Ai,i=new Ai,a=new Ai){this.planes=[e,t,n,r,i,a]}set(e,t,n,r,i,a){let o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(n),o[3].copy(r),o[4].copy(i),o[5].copy(a),this}copy(e){let t=this.planes;for(let n=0;n<6;n++)t[n].copy(e.planes[n]);return this}setFromProjectionMatrix(e,t=$e,n=!1){let r=this.planes,i=e.elements,a=i[0],o=i[1],s=i[2],c=i[3],l=i[4],u=i[5],d=i[6],f=i[7],p=i[8],m=i[9],h=i[10],g=i[11],_=i[12],v=i[13],y=i[14],b=i[15];if(r[0].setComponents(c-a,f-l,g-p,b-_).normalize(),r[1].setComponents(c+a,f+l,g+p,b+_).normalize(),r[2].setComponents(c+o,f+u,g+m,b+v).normalize(),r[3].setComponents(c-o,f-u,g-m,b-v).normalize(),n)r[4].setComponents(s,d,h,y).normalize(),r[5].setComponents(c-s,f-d,g-h,b-y).normalize();else if(r[4].setComponents(c-s,f-d,g-h,b-y).normalize(),t===2e3)r[5].setComponents(c+s,f+d,g+h,b+y).normalize();else if(t===2001)r[5].setComponents(s,d,h,y).normalize();else throw Error(`THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: `+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),ji.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{let t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),ji.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(ji)}intersectsSprite(e){return ji.center.set(0,0,0),ji.radius=.7071067811865476+Mi.distanceTo(e.center),ji.applyMatrix4(e.matrixWorld),this.intersectsSphere(ji)}intersectsSphere(e){let t=this.planes,n=e.center,r=-e.radius;for(let e=0;e<6;e++)if(t[e].distanceToPoint(n)0?e.max.x:e.min.x,Ni.y=r.normal.y>0?e.max.y:e.min.y,Ni.z=r.normal.z>0?e.max.z:e.min.z,r.distanceToPoint(Ni)<0)return!1}return!0}containsPoint(e){let t=this.planes;for(let n=0;n<6;n++)if(t[n].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}},Fi=class extends Br{constructor(e){super(),this.isLineBasicMaterial=!0,this.type=`LineBasicMaterial`,this.color=new X(16777215),this.map=null,this.linewidth=1,this.linecap=`round`,this.linejoin=`round`,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.linewidth=e.linewidth,this.linecap=e.linecap,this.linejoin=e.linejoin,this.fog=e.fog,this}},Ii=new q,Li=new q,Ri=new rn,zi=new ui,Bi=new Dr,Vi=new q,Hi=new q,Ui=class extends jn{constructor(e=new Fr,t=new Fi){super(),this.isLine=!0,this.type=`Line`,this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}computeLineDistances(){let e=this.geometry;if(e.index===null){let t=e.attributes.position,n=[0];for(let e=1,r=t.count;e0){let n=e[t[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;er)return;Vi.applyMatrix4(e.matrixWorld);let c=t.ray.origin.distanceTo(Vi);if(!(ct.far))return{distance:c,point:Hi.clone().applyMatrix4(e.matrixWorld),index:o,face:null,faceIndex:null,barycoord:null,object:e}}var Gi=new q,Ki=new q,qi=class extends Ui{constructor(e,t){super(e,t),this.isLineSegments=!0,this.type=`LineSegments`}computeLineDistances(){let e=this.geometry;if(e.index===null){let t=e.attributes.position,n=[];for(let e=0,r=t.count;e0?1:-1,l.push(D.x,D.y,D.z),u.push(s/h),u.push(1-a/g),T+=1}for(let e=0;e0&&v(!0),t>0&&v(!1)),this.setIndex(l),this.setAttribute(`position`,new Cr(u,3)),this.setAttribute(`normal`,new Cr(d,3)),this.setAttribute(`uv`,new Cr(f,2));function _(){let a=new q,_=new q,v=0,y=(t-e)/n;for(let c=0;c<=i;c++){let l=[],g=c/i,v=g*(t-e)+e;for(let e=0;e<=r;e++){let t=e/r,i=t*s+o,c=Math.sin(i),m=Math.cos(i);_.x=v*c,_.y=-g*n+h,_.z=v*m,u.push(_.x,_.y,_.z),a.set(c,y,m).normalize(),d.push(a.x,a.y,a.z),f.push(t,1-g),l.push(p++)}m.push(l)}for(let n=0;n0||r!==0)&&(l.push(a,o,c),v+=3),(t>0||r!==i-1)&&(l.push(o,s,c),v+=3)}c.addGroup(g,v,0),g+=v}function v(n){let i=p,a=new K,m=new q,_=0,v=n===!0?e:t,y=n===!0?1:-1;for(let e=1;e<=r;e++)u.push(0,h*y,0),d.push(0,y,0),f.push(.5,.5),p++;let b=p;for(let e=0;e<=r;e++){let t=e/r*s+o,n=Math.cos(t),i=Math.sin(t);m.x=v*i,m.y=h*y,m.z=v*n,u.push(m.x,m.y,m.z),d.push(0,y,0),a.x=n*.5+.5,a.y=i*.5*y+.5,f.push(a.x,a.y),p++}for(let e=0;e0)&&f.push(t,i,c),(e!==n-1||se.concat(...t),[])]}return[[],[]]},[e]);return(0,_.useEffect)(()=>{let n=t?.target??dl,c=t?.actInsideInputWithModifier??!0;if(e!==null){let e=e=>{if(i.current=e.ctrlKey||e.metaKey||e.shiftKey||e.altKey,(!i.current||i.current&&!c)&&Vo(e))return!1;let n=ml(e.code,s);if(a.current.add(e[n]),pl(o,a.current,!1)){let n=e.composedPath?.()?.[0]||e.target,a=n?.nodeName===`BUTTON`||n?.nodeName===`A`;t.preventDefault!==!1&&(i.current||!a)&&e.preventDefault(),r(!0)}},l=e=>{let t=ml(e.code,s);pl(o,a.current,!0)?(r(!1),a.current.clear()):a.current.delete(e[t]),e.key===`Meta`&&a.current.clear(),i.current=!1},u=()=>{a.current.clear(),r(!1)};return n?.addEventListener(`keydown`,e),n?.addEventListener(`keyup`,l),window.addEventListener(`blur`,u),window.addEventListener(`contextmenu`,u),()=>{n?.removeEventListener(`keydown`,e),n?.removeEventListener(`keyup`,l),window.removeEventListener(`blur`,u),window.removeEventListener(`contextmenu`,u)}}},[e,r]),n}function pl(e,t,n){return e.filter(e=>n||e.length===t.size).some(e=>e.every(e=>t.has(e)))}function ml(e,t){return t.includes(e)?`code`:`key`}var hl=()=>{let e=Rc();return(0,_.useMemo)(()=>({zoomIn:async t=>{let{panZoom:n}=e.getState();return n?n.scaleBy(1.2,t):!1},zoomOut:async t=>{let{panZoom:n}=e.getState();return n?n.scaleBy(1/1.2,t):!1},zoomTo:async(t,n)=>{let{panZoom:r}=e.getState();return r?r.scaleTo(t,n):!1},getZoom:()=>e.getState().transform[2],setViewport:async(t,n)=>{let{transform:[r,i,a],panZoom:o}=e.getState();return o?(await o.setViewport({x:t.x??r,y:t.y??i,zoom:t.zoom??a},n),!0):!1},getViewport:()=>{let[t,n,r]=e.getState().transform;return{x:t,y:n,zoom:r}},setCenter:async(t,n,r)=>e.getState().setCenter(t,n,r),fitBounds:async(t,n)=>{let{width:r,height:i,minZoom:a,maxZoom:o,panZoom:s}=e.getState(),c=Oo(t,r,i,a,o,n?.padding??.1);return s?(await s.setViewport(c,{duration:n?.duration,ease:n?.ease,interpolate:n?.interpolate}),!0):!1},screenToFlowPosition:(t,n={})=>{let{transform:r,snapGrid:i,snapToGrid:a,domNode:o}=e.getState();if(!o)return t;let{x:s,y:c}=o.getBoundingClientRect(),l={x:t.x-s,y:t.y-c},u=n.snapGrid??i;return Co(l,r,n.snapToGrid??a,u)},flowToScreenPosition:t=>{let{transform:n,domNode:r}=e.getState();if(!r)return t;let{x:i,y:a}=r.getBoundingClientRect(),o=wo(t,n);return{x:o.x+i,y:o.y+a}}}),[])};function gl(e,t){let n=[],r=new Map,i=[];for(let t of e)if(t.type===`add`){i.push(t);continue}else if(t.type===`remove`||t.type===`replace`)r.set(t.id,[t]);else{let e=r.get(t.id);e?e.push(t):r.set(t.id,[t])}for(let e of t){let t=r.get(e.id);if(!t){n.push(e);continue}if(t[0].type===`remove`)continue;if(t[0].type===`replace`){n.push({...t[0].item});continue}let i={...e};for(let e of t)_l(e,i);n.push(i)}return i.length&&i.forEach(e=>{e.index===void 0?n.push({...e.item}):n.splice(e.index,0,{...e.item})}),n}function _l(e,t){switch(e.type){case`select`:t.selected=e.selected;break;case`position`:e.position!==void 0&&(t.position=e.position),e.dragging!==void 0&&(t.dragging=e.dragging);break;case`dimensions`:e.dimensions!==void 0&&(t.measured={...e.dimensions},e.setAttributes&&((e.setAttributes===!0||e.setAttributes===`width`)&&(t.width=e.dimensions.width),(e.setAttributes===!0||e.setAttributes===`height`)&&(t.height=e.dimensions.height))),typeof e.resizing==`boolean`&&(t.resizing=e.resizing)}}function vl(e,t){return gl(e,t)}function yl(e,t){return gl(e,t)}function bl(e,t){return{id:e,type:`select`,selected:t}}function xl(e,t=new Set,n=!1){let r=[];for(let[i,a]of e){let e=t.has(i);!(a.selected===void 0&&!e)&&a.selected!==e&&(n&&(a.selected=e),r.push(bl(a.id,e)))}return r}function Sl({items:e=[],lookup:t}){let n=[],r=new Map(e.map(e=>[e.id,e]));for(let[r,i]of e.entries()){let e=t.get(i.id),a=e?.internals?.userNode??e;a!==void 0&&a!==i&&n.push({id:i.id,item:i,type:`replace`}),a===void 0&&n.push({item:i,type:`add`,index:r})}for(let[e]of t)r.get(e)===void 0&&n.push({id:e,type:`remove`});return n}function Cl(e){return{id:e.id,type:`remove`}}var wl=xo(`React Flow`,`https://reactflow.dev/`);function Tl(e,t,n={}){return es(e,t,{...n,onError:n.onError??wl})}var El=e=>Xa(e),Dl=e=>Ya(e);function Ol(e){return(0,_.forwardRef)(e)}var kl=typeof window<`u`?_.useLayoutEffect:_.useEffect;function Al(e){let[t,n]=(0,_.useState)(BigInt(0)),[r]=(0,_.useState)(()=>jl(()=>n(e=>e+BigInt(1))));return kl(()=>{let t=r.get();t.length&&(e(t),r.reset())},[t]),r}function jl(e){let t=[];return{get:()=>t,reset:()=>{t=[]},push:n=>{t.push(n),e()}}}var Ml=(0,_.createContext)(null);function Nl({children:e}){let t=Rc(),n=Al((0,_.useCallback)(e=>{let{nodes:n=[],setNodes:r,hasDefaultNodes:i,onNodesChange:a,nodeLookup:o,fitViewQueued:s,onNodesChangeMiddlewareMap:c}=t.getState(),l=n;for(let t of e)l=typeof t==`function`?t(l):t;let u=Sl({items:l,lookup:o});for(let e of c.values())u=e(u);i&&r(l),u.length>0?a?.(u):s&&window.requestAnimationFrame(()=>{let{fitViewQueued:e,nodes:n,setNodes:r}=t.getState();e&&r(n)})},[])),r=Al((0,_.useCallback)(e=>{let{edges:n=[],setEdges:r,hasDefaultEdges:i,onEdgesChange:a,edgeLookup:o}=t.getState(),s=n;for(let t of e)s=typeof t==`function`?t(s):t;i?r(s):a&&a(Sl({items:s,lookup:o}))},[])),i=(0,_.useMemo)(()=>({nodeQueue:n,edgeQueue:r}),[]);return(0,T.jsx)(Ml.Provider,{value:i,children:e})}function Pl(){let e=(0,_.useContext)(Ml);if(!e)throw Error(`useBatchContext must be used within a BatchProvider`);return e}var Fl=e=>!!e.panZoom;function Il(){let e=hl(),t=Rc(),n=Pl(),r=q(Fl),i=(0,_.useMemo)(()=>{let e=e=>t.getState().nodeLookup.get(e),r=e=>{n.nodeQueue.push(e)},i=e=>{n.edgeQueue.push(e)},a=e=>{let{nodeLookup:n,nodeOrigin:r}=t.getState(),i=El(e)?e:n.get(e.id),a=i.parentId?No(i.position,i.measured,i.parentId,n,r):i.position;return mo({...i,position:a,width:i.measured?.width??i.width,height:i.measured?.height??i.height})},o=(e,t,n={replace:!1})=>{r(r=>r.map(r=>{if(r.id===e){let e=typeof t==`function`?t(r):t;return n.replace&&El(e)?e:{...r,...e}}return r}))},s=(e,t,n={replace:!1})=>{i(r=>r.map(r=>{if(r.id===e){let e=typeof t==`function`?t(r):t;return n.replace&&Dl(e)?e:{...r,...e}}return r}))};return{getNodes:()=>t.getState().nodes.map(e=>({...e})),getNode:t=>e(t)?.internals.userNode,getInternalNode:e,getEdges:()=>{let{edges:e=[]}=t.getState();return e.map(e=>({...e}))},getEdge:e=>t.getState().edgeLookup.get(e),setNodes:r,setEdges:i,addNodes:e=>{let t=Array.isArray(e)?e:[e];n.nodeQueue.push(e=>[...e,...t])},addEdges:e=>{let t=Array.isArray(e)?e:[e];n.edgeQueue.push(e=>[...e,...t])},toObject:()=>{let{nodes:e=[],edges:n=[],transform:r}=t.getState(),[i,a,o]=r;return{nodes:e.map(e=>({...e})),edges:n.map(e=>({...e})),viewport:{x:i,y:a,zoom:o}}},deleteElements:async({nodes:e=[],edges:n=[]})=>{let{nodes:r,edges:i,onNodesDelete:a,onEdgesDelete:o,triggerNodeChanges:s,triggerEdgeChanges:c,onDelete:l,onBeforeDelete:u}=t.getState(),{nodes:d,edges:f}=await oo({nodesToRemove:e,edgesToRemove:n,nodes:r,edges:i,onBeforeDelete:u}),p=f.length>0,m=d.length>0;if(p){let e=f.map(Cl);o?.(f),c(e)}if(m){let e=d.map(Cl);a?.(d),s(e)}return(m||p)&&l?.({nodes:d,edges:f}),{deletedNodes:d,deletedEdges:f}},getIntersectingNodes:(e,n=!0,r)=>{let i=yo(e),o=i?e:a(e),s=r!==void 0;return o?(r||t.getState().nodes).filter(r=>{let a=t.getState().nodeLookup.get(r.id);if(a&&!i&&(r.id===e.id||!a.internals.positionAbsolute))return!1;let c=mo(s?r:a),l=vo(c,o);return n&&l>0||l>=c.width*c.height||l>=o.width*o.height}):[]},isNodeIntersecting:(e,t,n=!0)=>{let r=yo(e)?e:a(e);if(!r)return!1;let i=vo(r,t);return n&&i>0||i>=t.width*t.height||i>=r.width*r.height},updateNode:o,updateNodeData:(e,t,n={replace:!1})=>{o(e,e=>{let r=typeof t==`function`?t(e):t;return n.replace?{...e,data:r}:{...e,data:{...e.data,...r}}},n)},updateEdge:s,updateEdgeData:(e,t,n={replace:!1})=>{s(e,e=>{let r=typeof t==`function`?t(e):t;return n.replace?{...e,data:r}:{...e,data:{...e.data,...r}}},n)},getNodesBounds:e=>{let{nodeLookup:n,nodeOrigin:r}=t.getState();return $a(e,{nodeLookup:n,nodeOrigin:r})},getHandleConnections:({type:e,id:n,nodeId:r})=>Array.from(t.getState().connectionLookup.get(`${r}-${e}${n?`-${n}`:``}`)?.values()??[]),getNodeConnections:({type:e,handleId:n,nodeId:r})=>Array.from(t.getState().connectionLookup.get(`${r}${e?n?`-${e}-${n}`:`-${e}`:``}`)?.values()??[]),fitView:async e=>{let r=t.getState().fitViewResolver??Fo();return t.setState({fitViewQueued:!0,fitViewOptions:e,fitViewResolver:r}),n.nodeQueue.push(e=>[...e]),r.promise}}},[]);return(0,_.useMemo)(()=>({...i,...e,viewportInitialized:r}),[r])}var J=e=>e.selected,Ll=typeof window<`u`?window:void 0;function Y({deleteKeyCode:e,multiSelectionKeyCode:t}){let n=Rc(),{deleteElements:r}=Il(),i=fl(e,{actInsideInputWithModifier:!1}),a=fl(t,{target:Ll});(0,_.useEffect)(()=>{if(i){let{edges:e,nodes:t}=n.getState();r({nodes:t.filter(J),edges:e.filter(J)}),n.setState({nodesSelectionActive:!1})}},[i]),(0,_.useEffect)(()=>{n.setState({multiSelectionActive:a})},[a])}function X(e){let t=Rc();(0,_.useEffect)(()=>{let n=()=>{if(!e.current||!(e.current.checkVisibility?.()??!0))return!1;let n=Ro(e.current);(n.height===0||n.width===0)&&t.getState().onError?.(`004`,La.error004()),t.setState({width:n.width||500,height:n.height||500})};if(e.current){n(),window.addEventListener(`resize`,n);let t=new ResizeObserver(()=>n());return t.observe(e.current),()=>{window.removeEventListener(`resize`,n),t&&e.current&&t.unobserve(e.current)}}},[])}var Z={position:`absolute`,width:`100%`,height:`100%`,top:0,left:0},Rl=e=>({userSelectionActive:e.userSelectionActive,lib:e.lib,connectionInProgress:e.connection.inProgress});function zl({onPaneContextMenu:e,zoomOnScroll:t=!0,zoomOnPinch:n=!0,panOnScroll:r=!1,panActivationKeyPressed:i,panOnScrollSpeed:a=.5,panOnScrollMode:o=Ha.Free,zoomOnDoubleClick:s=!0,panOnDrag:c=!0,defaultViewport:l,translateExtent:u,minZoom:d,maxZoom:f,zoomActivationKeyCode:p,preventScrolling:m=!0,children:h,noWheelClassName:g,noPanClassName:v,onViewportChange:y,isControlledViewport:b,paneClickDistance:x,selectionOnDrag:S}){let C=Rc(),w=(0,_.useRef)(null),{userSelectionActive:E,lib:D,connectionInProgress:O}=q(Rl,Pc),k=fl(p),A=(0,_.useRef)();X(w);let j=(0,_.useCallback)(e=>{y?.({x:e[0],y:e[1],zoom:e[2]}),b||C.setState({transform:e})},[y,b]);return(0,_.useEffect)(()=>{if(w.current){A.current=lc({domNode:w.current,minZoom:d,maxZoom:f,translateExtent:u,viewport:l,onDraggingChange:e=>C.setState(t=>t.paneDragging===e?t:{paneDragging:e}),onPanZoomStart:(e,t)=>{let{onViewportChangeStart:n,onMoveStart:r}=C.getState();r?.(e,t),n?.(t)},onPanZoom:(e,t)=>{let{onViewportChange:n,onMove:r}=C.getState();r?.(e,t),n?.(t)},onPanZoomEnd:(e,t)=>{let{onViewportChangeEnd:n,onMoveEnd:r}=C.getState();r?.(e,t),n?.(t)}});let{x:e,y:t,zoom:n}=A.current.getViewport();return C.setState({panZoom:A.current,transform:[e,t,n],domNode:w.current.closest(`.react-flow`)}),()=>{A.current?.destroy()}}},[]),(0,_.useEffect)(()=>{A.current?.update({onPaneContextMenu:e,zoomOnScroll:t,zoomOnPinch:n,panOnScroll:r,panActivationKeyPressed:i,panOnScrollSpeed:a,panOnScrollMode:o,zoomOnDoubleClick:s,panOnDrag:c,zoomActivationKeyPressed:k,preventScrolling:m,noPanClassName:v,userSelectionActive:E,noWheelClassName:g,lib:D,onTransformChange:j,connectionInProgress:O,selectionOnDrag:S,paneClickDistance:x})},[e,t,n,r,i,a,o,s,c,k,m,v,E,g,D,j,O,S,x]),(0,T.jsx)(`div`,{className:`react-flow__renderer`,ref:w,style:Z,children:h})}var Bl=e=>({userSelectionActive:e.userSelectionActive,userSelectionRect:e.userSelectionRect});function Vl(){let{userSelectionActive:e,userSelectionRect:t}=q(Bl,Pc);return e&&t?(0,T.jsx)(`div`,{className:`react-flow__selection react-flow__container`,style:{width:t.width,height:t.height,transform:`translate(${t.x}px, ${t.y}px)`}}):null}var Hl=(e,t)=>n=>{n.target===t.current&&e?.(n)},Ul=e=>({userSelectionActive:e.userSelectionActive,elementsSelectable:e.elementsSelectable,dragging:e.paneDragging,panBy:e.panBy,autoPanSpeed:e.autoPanSpeed});function Wl({isSelecting:e,selectionKeyPressed:t,selectionMode:n=Ua.Full,panOnDrag:r,autoPanOnSelection:i,paneClickDistance:a,selectionOnDrag:o,onSelectionStart:s,onSelectionEnd:c,onPaneClick:l,onPaneContextMenu:u,onPaneScroll:d,onPaneMouseEnter:f,onPaneMouseMove:p,onPaneMouseLeave:m,children:h}){let g=(0,_.useRef)(0),v=Rc(),{userSelectionActive:y,elementsSelectable:b,dragging:x,panBy:S,autoPanSpeed:C}=q(Ul,Pc),w=b&&(e||y),E=(0,_.useRef)(null),D=(0,_.useRef)(),O=(0,_.useRef)(new Set),k=(0,_.useRef)(new Set),A=(0,_.useRef)(!1),j=(0,_.useRef)(!1),M=(0,_.useRef)({x:0,y:0}),ee=(0,_.useRef)(!1),N=e=>{if(j.current||A.current||v.getState().connection.inProgress){j.current=!1,A.current=!1;return}l?.(e),v.getState().resetSelectedElements(),v.setState({nodesSelectionActive:!1})},P=e=>{if(Array.isArray(r)&&r?.includes(2)){e.preventDefault();return}u?.(e)},F=d?e=>d(e):void 0,I=e=>{j.current&&=(e.stopPropagation(),!1)},te=n=>{if(n.pointerType===`touch`&&r!==!1&&!t)return;let{domNode:i,transform:a}=v.getState();if(D.current=i?.getBoundingClientRect(),!D.current)return;let s=n.target===E.current;if(!s&&n.target.closest(`.nokey`)||!e||!(o&&s||t)||n.button!==0||!n.isPrimary)return;n.target?.setPointerCapture?.(n.pointerId),j.current=!1;let{x:c,y:l}=Uo(n.nativeEvent,D.current),u=Co({x:c,y:l},a);v.setState({userSelectionRect:{width:0,height:0,startX:u.x,startY:u.y,x:c,y:l}}),s||(n.stopPropagation(),n.preventDefault())};function ne(e,t){let{userSelectionRect:r}=v.getState();if(!r)return;let{transform:i,nodeLookup:a,edgeLookup:o,connectionLookup:s,triggerNodeChanges:c,triggerEdgeChanges:l,defaultEdgeOptions:u}=v.getState(),d={x:r.startX,y:r.startY},{x:f,y:p}=wo(d,i),m={startX:d.x,startY:d.y,x:ee.id)),k.current=new Set;let _=u?.selectable??!0;for(let e of O.current){let t=s.get(e);if(t)for(let{edgeId:e}of t.values()){let t=o.get(e);t&&(t.selectable??_)&&k.current.add(e)}}Po(h,O.current)||c(xl(a,O.current,!0)),Po(g,k.current)||l(xl(o,k.current)),v.setState({userSelectionRect:m,userSelectionActive:!0,nodesSelectionActive:!1})}function L(){if(!i||!D.current)return;let[e,t]=lo(M.current,D.current,C);S({x:e,y:t}).then(e=>{if(!j.current||!e){g.current=requestAnimationFrame(L);return}let{x:t,y:n}=M.current;ne(t,n),g.current=requestAnimationFrame(L)})}let re=()=>{cancelAnimationFrame(g.current),g.current=0,ee.current=!1};(0,_.useEffect)(()=>()=>re(),[]);let R=e=>{let{userSelectionRect:n,transform:r,resetSelectedElements:i}=v.getState();if(!D.current||!n)return;let{x:o,y:c}=Uo(e.nativeEvent,D.current);M.current={x:o,y:c};let l=wo({x:n.startX,y:n.startY},r);if(!j.current){let n=t?0:a;if(Math.hypot(o-l.x,c-l.y)<=n)return;i(),s?.(e)}j.current=!0,ee.current||=(L(),!0),ne(o,c)},B=e=>{if(!w){e.target===E.current&&v.getState().connection.inProgress&&(A.current=!0);return}e.button===0&&(e.target?.releasePointerCapture?.(e.pointerId),!y&&e.target===E.current&&v.getState().userSelectionRect&&N?.(e),v.setState({userSelectionActive:!1,userSelectionRect:null}),j.current&&(c?.(e),v.setState({nodesSelectionActive:O.current.size>0})),re())},V=e=>{e.target?.releasePointerCapture?.(e.pointerId),re()},ie=r===!0||Array.isArray(r)&&r.includes(0);return(0,T.jsxs)(`div`,{className:z([`react-flow__pane`,{draggable:ie,dragging:x,selection:e}]),onClick:w?void 0:Hl(N,E),onContextMenu:Hl(P,E),onWheel:Hl(F,E),onPointerEnter:w?void 0:f,onPointerMove:w?R:p,onPointerUp:B,onPointerCancel:w?V:void 0,onPointerDownCapture:w?te:void 0,onClickCapture:w?I:void 0,onPointerLeave:m,ref:E,style:Z,children:[h,(0,T.jsx)(Vl,{})]})}function Gl({id:e,store:t,unselect:n=!1,nodeRef:r}){let{addSelectedNodes:i,unselectNodesAndEdges:a,multiSelectionActive:o,nodeLookup:s,onError:c}=t.getState(),l=s.get(e);if(!l){c?.(`012`,La.error012(e));return}t.setState({nodesSelectionActive:!1}),l.selected?(n||l.selected&&o)&&(a({nodes:[l],edges:[]}),requestAnimationFrame(()=>r?.current?.blur())):i([e])}function Kl({nodeRef:e,disabled:t=!1,noDragClassName:n,handleSelector:r,nodeId:i,isSelectable:a,nodeClickDistance:o}){let s=Rc(),[c,l]=(0,_.useState)(!1),u=(0,_.useRef)();return(0,_.useEffect)(()=>{if(!t)return u.current=Rs({getStoreItems:()=>s.getState(),onNodeMouseDown:t=>{Gl({id:t,store:s,nodeRef:e})},onDragStart:()=>{l(!0)},onDragStop:()=>{l(!1)}}),()=>{u.current?.destroy(),u.current=void 0}},[t,s,e]),(0,_.useEffect)(()=>{t||!e.current||!u.current||u.current.update({noDragClassName:n,handleSelector:r,domNode:e.current,isSelectable:a,nodeId:i,nodeClickDistance:o})},[n,r,t,a,e,i,o]),c}var ql=e=>t=>t.selected&&(t.draggable||e&&t.draggable===void 0);function Jl(){let e=Rc();return(0,_.useCallback)(t=>{let{nodeExtent:n,snapToGrid:r,snapGrid:i,nodesDraggable:a,onError:o,updateNodePositions:s,nodeLookup:c,nodeOrigin:l}=e.getState(),u=new Map,d=ql(a),f=r?i[0]:5,p=r?i[1]:5,m=t.direction.x*f*t.factor,h=t.direction.y*p*t.factor;for(let[,e]of c){if(!d(e))continue;let t={x:e.internals.positionAbsolute.x+m,y:e.internals.positionAbsolute.y+h};r&&(t=So(t,i));let{position:a,positionAbsolute:s}=ao({nodeId:e.id,nextPosition:t,nodeLookup:c,nodeExtent:n,nodeOrigin:l,onError:o});e.position=a,e.internals.positionAbsolute=s,u.set(e.id,e)}s(u)},[])}var Yl=(0,_.createContext)(null),Xl=Yl.Provider;Yl.Consumer;var Zl=()=>(0,_.useContext)(Yl),Ql=e=>({connectOnClick:e.connectOnClick,noPanClassName:e.noPanClassName,rfId:e.rfId}),$l=(0,_.createContext)(null);function eu({children:e}){let t=q(Ql,Pc);return(0,T.jsx)($l.Provider,{value:t,children:e})}function tu(){let e=(0,_.useContext)($l);if(!e)throw Error(`useHandleConfig must be used within a HandleConfigProvider`);return e}var nu={connectingFrom:!1,connectingTo:!1,clickConnecting:!1,isPossibleEndHandle:!0,connectionInProcess:!1,clickConnectionInProcess:!1,valid:!1},ru=(e,t,n)=>r=>{let{connectionClickStartHandle:i,connectionMode:a,connection:o}=r,{fromHandle:s,toHandle:c,isValid:l}=o;if(!s&&!i)return nu;let u=c?.nodeId===e&&c?.id===t&&c?.type===n;return{connectingFrom:s?.nodeId===e&&s?.id===t&&s?.type===n,connectingTo:u,clickConnecting:i?.nodeId===e&&i?.id===t&&i?.type===n,isPossibleEndHandle:a===Va.Strict?s?.type!==n:e!==s?.nodeId||t!==s?.id,connectionInProcess:!!s,clickConnectionInProcess:!!i,valid:u&&l}};function iu({type:e=`source`,position:t=W.Top,isValidConnection:n,isConnectable:r=!0,isConnectableStart:i=!0,isConnectableEnd:a=!0,id:o,onConnect:s,children:c,className:l,onMouseDown:u,onTouchStart:d,...f},p){let m=o||null,h=e===`target`,g=Rc(),_=Zl(),{connectOnClick:v,noPanClassName:y,rfId:b}=tu(),{connectingFrom:x,connectingTo:S,clickConnecting:C,isPossibleEndHandle:w,connectionInProcess:E,clickConnectionInProcess:D,valid:O}=q(ru(_,m,e),Pc);_||g.getState().onError?.(`010`,La.error010());let k=e=>{let{defaultEdgeOptions:t,onConnect:n,hasDefaultEdges:r}=g.getState(),i={...t,...e};if(r){let{edges:e,setEdges:t,onError:n}=g.getState();t(Tl(i,e,{onError:n}))}n?.(i),s?.(i)},A=e=>{if(!_)return;let t=Ho(e.nativeEvent);if(i&&(t&&e.button===0||!t)){let t=g.getState();Js.onPointerDown(e.nativeEvent,{handleDomNode:e.currentTarget,autoPanOnConnect:t.autoPanOnConnect,connectionMode:t.connectionMode,connectionRadius:t.connectionRadius,domNode:t.domNode,nodeLookup:t.nodeLookup,lib:t.lib,isTarget:h,handleId:m,nodeId:_,flowId:t.rfId,panBy:t.panBy,cancelConnection:t.cancelConnection,onConnectStart:t.onConnectStart,onConnectEnd:(...e)=>g.getState().onConnectEnd?.(...e),updateConnection:t.updateConnection,onConnect:k,isValidConnection:n||((...e)=>g.getState().isValidConnection?.(...e)??!0),getTransform:()=>g.getState().transform,getFromHandle:()=>g.getState().connection.fromHandle,autoPanSpeed:t.autoPanSpeed,dragThreshold:t.connectionDragThreshold})}t?u?.(e):d?.(e)};return(0,T.jsx)(`div`,{"data-handleid":m,"data-nodeid":_,"data-handlepos":t,"data-id":`${b}-${_}-${m}-${e}`,className:z([`react-flow__handle`,`react-flow__handle-${t}`,`nodrag`,y,l,{source:!h,target:h,connectable:r,connectablestart:i,connectableend:a,clickconnecting:C,connectingfrom:x,connectingto:S,valid:O,connectionindicator:r&&(!E||w)&&(E||D?a:i)}]),onMouseDown:A,onTouchStart:A,onClick:v?t=>{let{onClickConnectStart:r,onClickConnectEnd:a,connectionClickStartHandle:o,connectionMode:s,isValidConnection:c,lib:l,rfId:u,nodeLookup:d,connection:f}=g.getState();if(!_||!o&&!i)return;if(!o){r?.(t.nativeEvent,{nodeId:_,handleId:m,handleType:e}),g.setState({connectionClickStartHandle:{nodeId:_,type:e,id:m}});return}let p=zo(t.target),h=n||c,{connection:v,isValid:y}=Js.isValid(t.nativeEvent,{handle:{nodeId:_,id:m,type:e},connectionMode:s,fromNodeId:o.nodeId,fromHandleId:o.id||null,fromType:o.type,isValidConnection:h,flowId:u,doc:p,lib:l,nodeLookup:d});y&&v&&k(v);let b=structuredClone(f);delete b.inProgress,b.toPosition=b.toHandle?b.toHandle.position:null,a?.(t,b),g.setState({connectionClickStartHandle:null})}:void 0,ref:p,...f,children:c})}var au=(0,_.memo)(Ol(iu));function ou({data:e,isConnectable:t,sourcePosition:n=W.Bottom}){return(0,T.jsxs)(T.Fragment,{children:[e?.label,(0,T.jsx)(au,{type:`source`,position:n,isConnectable:t})]})}function su({data:e,isConnectable:t,targetPosition:n=W.Top,sourcePosition:r=W.Bottom}){return(0,T.jsxs)(T.Fragment,{children:[(0,T.jsx)(au,{type:`target`,position:n,isConnectable:t}),e?.label,(0,T.jsx)(au,{type:`source`,position:r,isConnectable:t})]})}function cu(){return null}function lu({data:e,isConnectable:t,targetPosition:n=W.Top}){return(0,T.jsxs)(T.Fragment,{children:[(0,T.jsx)(au,{type:`target`,position:n,isConnectable:t}),e?.label]})}var uu={ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1},ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0}},du={input:ou,default:su,output:lu,group:cu};function fu(e){return e.internals.handleBounds===void 0?{width:e.width??e.initialWidth??e.style?.width,height:e.height??e.initialHeight??e.style?.height}:{width:e.width??e.style?.width,height:e.height??e.style?.height}}var pu=e=>{let{width:t,height:n,x:r,y:i}=eo(e.nodeLookup,{filter:e=>!!e.selected});return{width:bo(t)?t:null,height:bo(n)?n:null,userSelectionActive:e.userSelectionActive,transformString:`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]}) translate(${r}px,${i}px)`}};function mu({onSelectionContextMenu:e,noPanClassName:t,disableKeyboardA11y:n}){let r=Rc(),{width:i,height:a,transformString:o,userSelectionActive:s}=q(pu,Pc),c=Jl(),l=(0,_.useRef)(null);(0,_.useEffect)(()=>{n||l.current?.focus({preventScroll:!0})},[n]);let u=!s&&i!==null&&a!==null;if(Kl({nodeRef:l,disabled:!u}),!u)return null;let d=e?t=>{e(t,r.getState().nodes.filter(e=>e.selected))}:void 0;return(0,T.jsx)(`div`,{className:z([`react-flow__nodesselection`,`react-flow__container`,t]),style:{transform:o},children:(0,T.jsx)(`div`,{ref:l,className:`react-flow__nodesselection-rect`,onContextMenu:d,tabIndex:n?void 0:-1,onKeyDown:n?void 0:e=>{Object.prototype.hasOwnProperty.call(uu,e.key)&&(e.preventDefault(),c({direction:uu[e.key],factor:e.shiftKey?4:1}))},style:{width:i,height:a}})})}var hu=typeof window<`u`?window:void 0,gu=e=>({nodesSelectionActive:e.nodesSelectionActive,userSelectionActive:e.userSelectionActive});function _u({children:e,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:i,onPaneContextMenu:a,onPaneScroll:o,paneClickDistance:s,deleteKeyCode:c,selectionKeyCode:l,selectionOnDrag:u,selectionMode:d,onSelectionStart:f,onSelectionEnd:p,multiSelectionKeyCode:m,panActivationKeyCode:h,zoomActivationKeyCode:g,elementsSelectable:_,zoomOnScroll:v,zoomOnPinch:y,panOnScroll:b,panOnScrollSpeed:x,panOnScrollMode:S,zoomOnDoubleClick:C,panOnDrag:w,autoPanOnSelection:E,defaultViewport:D,translateExtent:O,minZoom:k,maxZoom:A,preventScrolling:j,onSelectionContextMenu:M,noWheelClassName:ee,noPanClassName:N,disableKeyboardA11y:P,onViewportChange:F,isControlledViewport:I}){let{nodesSelectionActive:te,userSelectionActive:ne}=q(gu,Pc),L=fl(l,{target:hu}),re=fl(h,{target:hu}),R=re||w,z=re||b,B=u&&R!==!0,V=L||ne||B;return Y({deleteKeyCode:c,multiSelectionKeyCode:m}),(0,T.jsx)(zl,{onPaneContextMenu:a,elementsSelectable:_,zoomOnScroll:v,zoomOnPinch:y,panOnScroll:z,panActivationKeyPressed:re,panOnScrollSpeed:x,panOnScrollMode:S,zoomOnDoubleClick:C,panOnDrag:!L&&R,defaultViewport:D,translateExtent:O,minZoom:k,maxZoom:A,zoomActivationKeyCode:g,preventScrolling:j,noWheelClassName:ee,noPanClassName:N,onViewportChange:F,isControlledViewport:I,paneClickDistance:s,selectionOnDrag:B,children:(0,T.jsxs)(Wl,{onSelectionStart:f,onSelectionEnd:p,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:i,onPaneContextMenu:a,onPaneScroll:o,panOnDrag:R,autoPanOnSelection:E,isSelecting:!!V,selectionMode:d,selectionKeyPressed:L,paneClickDistance:s,selectionOnDrag:B,children:[e,te&&(0,T.jsx)(mu,{onSelectionContextMenu:M,noPanClassName:N,disableKeyboardA11y:P})]})})}_u.displayName=`FlowRenderer`;var vu=(0,_.memo)(_u),yu=e=>t=>e?to(t.nodeLookup,{x:0,y:0,width:t.width,height:t.height},t.transform,!0).map(e=>e.id):Array.from(t.nodeLookup.keys());function bu(e){return q((0,_.useCallback)(yu(e),[e]),Pc)}var xu=e=>e.updateNodeInternals;function Su(){let e=q(xu),[t]=(0,_.useState)(()=>typeof ResizeObserver>`u`?null:new ResizeObserver(t=>{let n=new Map;t.forEach(e=>{let t=e.target.getAttribute(`data-id`);n.set(t,{id:t,nodeElement:e.target,force:!0})}),e(n)}));return(0,_.useEffect)(()=>()=>{t?.disconnect()},[t]),t}function Cu({node:e,nodeType:t,hasDimensions:n,resizeObserver:r}){let i=Rc(),a=(0,_.useRef)(null),o=(0,_.useRef)(null),s=(0,_.useRef)(e.sourcePosition),c=(0,_.useRef)(e.targetPosition),l=(0,_.useRef)(t),u=n&&!!e.internals.handleBounds;return(0,_.useEffect)(()=>{a.current&&!e.hidden&&(!u||o.current!==a.current)&&(o.current&&r?.unobserve(o.current),r?.observe(a.current),o.current=a.current)},[u,e.hidden]),(0,_.useEffect)(()=>()=>{o.current&&=(r?.unobserve(o.current),null)},[]),(0,_.useEffect)(()=>{if(a.current){let n=l.current!==t,r=s.current!==e.sourcePosition,o=c.current!==e.targetPosition;(n||r||o)&&(l.current=t,s.current=e.sourcePosition,c.current=e.targetPosition,i.getState().updateNodeInternals(new Map([[e.id,{id:e.id,nodeElement:a.current,force:!0}]])))}},[e.id,t,e.sourcePosition,e.targetPosition]),a}function wu({id:e,onClick:t,onMouseEnter:n,onMouseMove:r,onMouseLeave:i,onContextMenu:a,onDoubleClick:o,nodesDraggable:s,elementsSelectable:c,nodesConnectable:l,nodesFocusable:u,resizeObserver:d,noDragClassName:f,noPanClassName:p,disableKeyboardA11y:m,rfId:h,nodeTypes:g,nodeClickDistance:_,onError:v}){let{node:y,internals:b,isParent:x}=q(t=>{let n=t.nodeLookup.get(e),r=t.parentLookup.has(e);return{node:n,internals:n.internals,isParent:r}},Pc),S=y.type||`default`,C=g?.[S]||du[S];C===void 0&&(v?.(`003`,La.error003(S)),S=`default`,C=g?.default||du.default);let w=!!(y.draggable||s&&y.draggable===void 0),E=!!(y.selectable||c&&y.selectable===void 0),D=!!(y.connectable||l&&y.connectable===void 0),O=!!(y.focusable||u&&y.focusable===void 0),k=Rc(),A=Mo(y),j=Cu({node:y,nodeType:S,hasDimensions:A,resizeObserver:d}),M=Kl({nodeRef:j,disabled:y.hidden||!w,noDragClassName:f,handleSelector:y.dragHandle,nodeId:e,isSelectable:E,nodeClickDistance:_}),ee=Jl();if(y.hidden)return null;let N=jo(y),P=fu(y),F=E||w||t||n||r||i,I=n?e=>n(e,{...b.userNode}):void 0,te=r?e=>r(e,{...b.userNode}):void 0,ne=i?e=>i(e,{...b.userNode}):void 0,L=a?e=>a(e,{...b.userNode}):void 0,re=o?e=>o(e,{...b.userNode}):void 0,R=n=>{let{selectNodesOnDrag:r,nodeDragThreshold:i}=k.getState();E&&(!r||!w||i>0)&&Gl({id:e,store:k,nodeRef:j}),t&&t(n,{...b.userNode})},B=t=>{if(!(Vo(t.nativeEvent)||m)){if(za.includes(t.key)&&E){let n=t.key===`Escape`;Gl({id:e,store:k,unselect:n,nodeRef:j})}else if(w&&y.selected&&Object.prototype.hasOwnProperty.call(uu,t.key)){t.preventDefault();let{ariaLabelConfig:e}=k.getState();k.setState({ariaLiveMessage:e[`node.a11yDescription.ariaLiveMessage`]({direction:t.key.replace(`Arrow`,``).toLowerCase(),x:~~b.positionAbsolute.x,y:~~b.positionAbsolute.y})}),ee({direction:uu[t.key],factor:t.shiftKey?4:1})}}},V=()=>{if(m||!j.current?.matches(`:focus-visible`))return;let{transform:t,width:n,height:r,autoPanOnNodeFocus:i,setCenter:a}=k.getState();i&&(to(new Map([[e,y]]),{x:0,y:0,width:n,height:r},t,!0).length>0||a(y.position.x+N.width/2,y.position.y+N.height/2,{zoom:t[2]}))};return(0,T.jsx)(`div`,{className:z([`react-flow__node`,`react-flow__node-${S}`,{[p]:w},y.className,{selected:y.selected,selectable:E,parent:x,draggable:w,dragging:M}]),ref:j,style:{zIndex:b.z,transform:`translate(${b.positionAbsolute.x}px,${b.positionAbsolute.y}px)`,pointerEvents:F?`all`:`none`,visibility:A?`visible`:`hidden`,...y.style,...P},"data-id":e,"data-testid":`rf__node-${e}`,onMouseEnter:I,onMouseMove:te,onMouseLeave:ne,onContextMenu:L,onClick:R,onDoubleClick:re,onKeyDown:O?B:void 0,tabIndex:O?0:void 0,onFocus:O?V:void 0,role:y.ariaRole??(O?`group`:void 0),"aria-roledescription":`node`,"aria-describedby":m?void 0:`${Vc}-${h}`,"aria-label":y.ariaLabel,...y.domAttributes,children:(0,T.jsx)(Xl,{value:e,children:(0,T.jsx)(C,{id:e,data:y.data,type:S,positionAbsoluteX:b.positionAbsolute.x,positionAbsoluteY:b.positionAbsolute.y,selected:y.selected??!1,selectable:E,draggable:w,deletable:y.deletable??!0,isConnectable:D,sourcePosition:y.sourcePosition,targetPosition:y.targetPosition,dragging:M,dragHandle:y.dragHandle,zIndex:b.z,parentId:y.parentId,...N})})})}var Tu=(0,_.memo)(wu),Eu=e=>({nodesConnectable:e.nodesConnectable,nodesFocusable:e.nodesFocusable,elementsSelectable:e.elementsSelectable,onError:e.onError});function Du(e){let{nodesConnectable:t,nodesFocusable:n,elementsSelectable:r,onError:i}=q(Eu,Pc),a=bu(e.onlyRenderVisibleElements),o=Su();return(0,T.jsx)(`div`,{className:`react-flow__nodes`,style:Z,children:a.map(a=>(0,T.jsx)(Tu,{id:a,nodeTypes:e.nodeTypes,nodeExtent:e.nodeExtent,onClick:e.onNodeClick,onMouseEnter:e.onNodeMouseEnter,onMouseMove:e.onNodeMouseMove,onMouseLeave:e.onNodeMouseLeave,onContextMenu:e.onNodeContextMenu,onDoubleClick:e.onNodeDoubleClick,noDragClassName:e.noDragClassName,noPanClassName:e.noPanClassName,rfId:e.rfId,disableKeyboardA11y:e.disableKeyboardA11y,resizeObserver:o,nodesDraggable:e.nodesDraggable??!0,nodesConnectable:t,nodesFocusable:n,elementsSelectable:r,nodeClickDistance:e.nodeClickDistance,onError:i},a))})}Du.displayName=`NodeRenderer`;var Ou=(0,_.memo)(Du);function ku(e){return q((0,_.useCallback)(t=>{if(!e)return t.edges.map(e=>e.id);let n=[];if(t.width&&t.height)for(let e of t.edges){let r=t.nodeLookup.get(e.source),i=t.nodeLookup.get(e.target);r&&i&&Zo({sourceNode:r,targetNode:i,width:t.width,height:t.height,transform:t.transform})&&n.push(e.id)}return n},[e]),Pc)}var Au=({color:e=`none`,strokeWidth:t=1})=>{let n={strokeWidth:t,...e&&{stroke:e}};return(0,T.jsx)(`polyline`,{className:`arrow`,style:n,strokeLinecap:`round`,fill:`none`,strokeLinejoin:`round`,points:`-5,-4 0,0 -5,4`})},ju=({color:e=`none`,strokeWidth:t=1})=>{let n={strokeWidth:t,...e&&{stroke:e,fill:e}};return(0,T.jsx)(`polyline`,{className:`arrowclosed`,style:n,strokeLinecap:`round`,strokeLinejoin:`round`,points:`-5,-4 0,0 -5,4 -5,-4`})},Mu={[Ka.Arrow]:Au,[Ka.ArrowClosed]:ju};function Nu(e){let t=Rc();return(0,_.useMemo)(()=>Object.prototype.hasOwnProperty.call(Mu,e)?Mu[e]:(t.getState().onError?.(`009`,La.error009(e)),null),[e])}var Pu=({id:e,type:t,color:n,width:r=12.5,height:i=12.5,markerUnits:a=`strokeWidth`,strokeWidth:o,orient:s=`auto-start-reverse`})=>{let c=Nu(t);return c?(0,T.jsx)(`marker`,{className:`react-flow__arrowhead`,id:e,markerWidth:`${r}`,markerHeight:`${i}`,viewBox:`-10 -10 20 20`,markerUnits:a,orient:s,refX:`0`,refY:`0`,children:(0,T.jsx)(c,{color:n,strokeWidth:o})}):null},Fu=({defaultColor:e,rfId:t})=>{let n=q(e=>e.edges),r=q(e=>e.defaultEdgeOptions),i=(0,_.useMemo)(()=>ms(n,{id:t,defaultColor:e,defaultMarkerStart:r?.markerStart,defaultMarkerEnd:r?.markerEnd}),[n,r,t,e]);return i.length?(0,T.jsx)(`svg`,{className:`react-flow__marker`,"aria-hidden":`true`,children:(0,T.jsx)(`defs`,{children:i.map(e=>(0,T.jsx)(Pu,{id:e.id,type:e.type,color:e.color,width:e.width,height:e.height,markerUnits:e.markerUnits,strokeWidth:e.strokeWidth,orient:e.orient},e.id))})}):null};Fu.displayName=`MarkerDefinitions`;var Iu=(0,_.memo)(Fu);function Lu({x:e,y:t,label:n,labelStyle:r,labelShowBg:i=!0,labelBgStyle:a,labelBgPadding:o=[2,4],labelBgBorderRadius:s=2,children:c,className:l,...u}){let[d,f]=(0,_.useState)({x:1,y:0,width:0,height:0}),p=z([`react-flow__edge-textwrapper`,l]),m=(0,_.useRef)(null);return(0,_.useEffect)(()=>{if(m.current){let e=m.current.getBBox();f({x:e.x,y:e.y,width:e.width,height:e.height})}},[n]),n?(0,T.jsxs)(`g`,{transform:`translate(${e-d.width/2} ${t-d.height/2})`,className:p,visibility:d.width?`visible`:`hidden`,...u,children:[i&&(0,T.jsx)(`rect`,{width:d.width+2*o[0],x:-o[0],y:-o[1],height:d.height+2*o[1],className:`react-flow__edge-textbg`,style:a,rx:s,ry:s}),(0,T.jsx)(`text`,{className:`react-flow__edge-text`,y:d.height/2,dy:`0.3em`,ref:m,style:r,children:n}),c]}):null}Lu.displayName=`EdgeText`;var Ru=(0,_.memo)(Lu);function zu({path:e,labelX:t,labelY:n,label:r,labelStyle:i,labelShowBg:a,labelBgStyle:o,labelBgPadding:s,labelBgBorderRadius:c,interactionWidth:l=20,...u}){return(0,T.jsxs)(T.Fragment,{children:[(0,T.jsx)(`path`,{...u,d:e,fill:`none`,className:z([`react-flow__edge-path`,u.className])}),l?(0,T.jsx)(`path`,{d:e,fill:`none`,strokeOpacity:0,strokeWidth:l,className:`react-flow__edge-interaction`}):null,r&&bo(t)&&bo(n)?(0,T.jsx)(Ru,{x:t,y:n,label:r,labelStyle:i,labelShowBg:a,labelBgStyle:o,labelBgPadding:s,labelBgBorderRadius:c}):null]})}function Bu({pos:e,x1:t,y1:n,x2:r,y2:i}){return e===W.Left||e===W.Right?[.5*(t+r),n]:[t,.5*(n+i)]}function Vu({sourceX:e,sourceY:t,sourcePosition:n=W.Bottom,targetX:r,targetY:i,targetPosition:a=W.Top}){let[o,s]=Bu({pos:n,x1:e,y1:t,x2:r,y2:i}),[c,l]=Bu({pos:a,x1:r,y1:i,x2:e,y2:t}),[u,d,f,p]=Go({sourceX:e,sourceY:t,targetX:r,targetY:i,sourceControlX:o,sourceControlY:s,targetControlX:c,targetControlY:l});return[`M${e},${t} C${o},${s} ${c},${l} ${r},${i}`,u,d,f,p]}function Hu(e){return(0,_.memo)(({id:t,sourceX:n,sourceY:r,targetX:i,targetY:a,sourcePosition:o,targetPosition:s,label:c,labelStyle:l,labelShowBg:u,labelBgStyle:d,labelBgPadding:f,labelBgBorderRadius:p,style:m,markerEnd:h,markerStart:g,interactionWidth:_})=>{let[v,y,b]=Vu({sourceX:n,sourceY:r,sourcePosition:o,targetX:i,targetY:a,targetPosition:s}),x=e.isInternal?void 0:t;return(0,T.jsx)(zu,{id:x,path:v,labelX:y,labelY:b,label:c,labelStyle:l,labelShowBg:u,labelBgStyle:d,labelBgPadding:f,labelBgBorderRadius:p,style:m,markerEnd:h,markerStart:g,interactionWidth:_})})}var Uu=Hu({isInternal:!1}),Q=Hu({isInternal:!0});Uu.displayName=`SimpleBezierEdge`,Q.displayName=`SimpleBezierEdgeInternal`;function Wu(e){return(0,_.memo)(({id:t,sourceX:n,sourceY:r,targetX:i,targetY:a,label:o,labelStyle:s,labelShowBg:c,labelBgStyle:l,labelBgPadding:u,labelBgBorderRadius:d,style:f,sourcePosition:p=W.Bottom,targetPosition:m=W.Top,markerEnd:h,markerStart:g,pathOptions:_,interactionWidth:v})=>{let[y,b,x]=ss({sourceX:n,sourceY:r,sourcePosition:p,targetX:i,targetY:a,targetPosition:m,borderRadius:_?.borderRadius,offset:_?.offset,stepPosition:_?.stepPosition}),S=e.isInternal?void 0:t;return(0,T.jsx)(zu,{id:S,path:y,labelX:b,labelY:x,label:o,labelStyle:s,labelShowBg:c,labelBgStyle:l,labelBgPadding:u,labelBgBorderRadius:d,style:f,markerEnd:h,markerStart:g,interactionWidth:v})})}var Gu=Wu({isInternal:!1}),Ku=Wu({isInternal:!0});Gu.displayName=`SmoothStepEdge`,Ku.displayName=`SmoothStepEdgeInternal`;function qu(e){return(0,_.memo)(({id:t,...n})=>{let r=e.isInternal?void 0:t;return(0,T.jsx)(Gu,{...n,id:r,pathOptions:(0,_.useMemo)(()=>({borderRadius:0,offset:n.pathOptions?.offset}),[n.pathOptions?.offset])})})}var Ju=qu({isInternal:!1}),Yu=qu({isInternal:!0});Ju.displayName=`StepEdge`,Yu.displayName=`StepEdgeInternal`;function Xu(e){return(0,_.memo)(({id:t,sourceX:n,sourceY:r,targetX:i,targetY:a,label:o,labelStyle:s,labelShowBg:c,labelBgStyle:l,labelBgPadding:u,labelBgBorderRadius:d,style:f,markerEnd:p,markerStart:m,interactionWidth:h})=>{let[g,_,v]=ts({sourceX:n,sourceY:r,targetX:i,targetY:a}),y=e.isInternal?void 0:t;return(0,T.jsx)(zu,{id:y,path:g,labelX:_,labelY:v,label:o,labelStyle:s,labelShowBg:c,labelBgStyle:l,labelBgPadding:u,labelBgBorderRadius:d,style:f,markerEnd:p,markerStart:m,interactionWidth:h})})}var Zu=Xu({isInternal:!1}),Qu=Xu({isInternal:!0});Zu.displayName=`StraightEdge`,Qu.displayName=`StraightEdgeInternal`;function $u(e){return(0,_.memo)(({id:t,sourceX:n,sourceY:r,targetX:i,targetY:a,sourcePosition:o=W.Bottom,targetPosition:s=W.Top,label:c,labelStyle:l,labelShowBg:u,labelBgStyle:d,labelBgPadding:f,labelBgBorderRadius:p,style:m,markerEnd:h,markerStart:g,pathOptions:_,interactionWidth:v})=>{let[y,b,x]=Jo({sourceX:n,sourceY:r,sourcePosition:o,targetX:i,targetY:a,targetPosition:s,curvature:_?.curvature}),S=e.isInternal?void 0:t;return(0,T.jsx)(zu,{id:S,path:y,labelX:b,labelY:x,label:c,labelStyle:l,labelShowBg:u,labelBgStyle:d,labelBgPadding:f,labelBgBorderRadius:p,style:m,markerEnd:h,markerStart:g,interactionWidth:v})})}var ed=$u({isInternal:!1}),td=$u({isInternal:!0});ed.displayName=`BezierEdge`,td.displayName=`BezierEdgeInternal`;var nd={default:td,straight:Qu,step:Yu,smoothstep:Ku,simplebezier:Q},rd={sourceX:null,sourceY:null,targetX:null,targetY:null,sourcePosition:null,targetPosition:null,zIndex:void 0},id=(e,t,n)=>n===W.Left?e-t:n===W.Right?e+t:e,ad=(e,t,n)=>n===W.Top?e-t:n===W.Bottom?e+t:e,od=`react-flow__edgeupdater`;function sd({position:e,centerX:t,centerY:n,radius:r=10,onMouseDown:i,onMouseEnter:a,onMouseOut:o,type:s}){return(0,T.jsx)(`circle`,{onMouseDown:i,onMouseEnter:a,onMouseOut:o,className:z([od,`${od}-${s}`]),cx:id(t,r,e),cy:ad(n,r,e),r,stroke:`transparent`,fill:`transparent`})}function cd({isReconnectable:e,reconnectRadius:t,edge:n,sourceX:r,sourceY:i,targetX:a,targetY:o,sourcePosition:s,targetPosition:c,onReconnect:l,onReconnectStart:u,onReconnectEnd:d,setReconnecting:f,setUpdateHover:p}){let m=Rc(),h=(e,t)=>{if(e.button!==0)return;let{autoPanOnConnect:r,domNode:i,connectionMode:a,connectionRadius:o,lib:s,onConnectStart:c,cancelConnection:p,nodeLookup:h,rfId:g,panBy:_,updateConnection:v}=m.getState(),y=t.type===`target`;Js.onPointerDown(e.nativeEvent,{autoPanOnConnect:r,connectionMode:a,connectionRadius:o,domNode:i,handleId:t.id,nodeId:t.nodeId,nodeLookup:h,isTarget:y,edgeUpdaterType:t.type,lib:s,flowId:g,cancelConnection:p,panBy:_,isValidConnection:(...e)=>m.getState().isValidConnection?.(...e)??!0,onConnect:e=>l?.(n,e),onConnectStart:(r,i)=>{f(!0),u?.(e,n,t.type),c?.(r,i)},onConnectEnd:(...e)=>m.getState().onConnectEnd?.(...e),onReconnectEnd:(e,r)=>{f(!1),d?.(e,n,t.type,r)},updateConnection:v,getTransform:()=>m.getState().transform,getFromHandle:()=>m.getState().connection.fromHandle,dragThreshold:m.getState().connectionDragThreshold,handleDomNode:e.currentTarget})},g=e=>h(e,{nodeId:n.target,id:n.targetHandle??null,type:`target`}),_=e=>h(e,{nodeId:n.source,id:n.sourceHandle??null,type:`source`}),v=()=>p(!0),y=()=>p(!1);return(0,T.jsxs)(T.Fragment,{children:[(e===!0||e===`source`)&&(0,T.jsx)(sd,{position:s,centerX:r,centerY:i,radius:t,onMouseDown:g,onMouseEnter:v,onMouseOut:y,type:`source`}),(e===!0||e===`target`)&&(0,T.jsx)(sd,{position:c,centerX:a,centerY:o,radius:t,onMouseDown:_,onMouseEnter:v,onMouseOut:y,type:`target`})]})}function ld({id:e,edgesFocusable:t,edgesReconnectable:n,elementsSelectable:r,onClick:i,onDoubleClick:a,onContextMenu:o,onMouseEnter:s,onMouseMove:c,onMouseLeave:l,reconnectRadius:u,onReconnect:d,onReconnectStart:f,onReconnectEnd:p,rfId:m,edgeTypes:h,noPanClassName:g,onError:v,disableKeyboardA11y:y}){let b=q(t=>t.edgeLookup.get(e)),x=q(e=>e.defaultEdgeOptions);b=x?{...x,...b}:b;let S=b.type||`default`,C=h?.[S]||nd[S];C===void 0&&(v?.(`011`,La.error011(S)),S=`default`,C=h?.default||nd.default);let w=!!(b.focusable||t&&b.focusable===void 0),E=d!==void 0&&(b.reconnectable||n&&b.reconnectable===void 0),D=!!(b.selectable||r&&b.selectable===void 0),O=(0,_.useRef)(null),[k,A]=(0,_.useState)(!1),[j,M]=(0,_.useState)(!1),ee=Rc(),{zIndex:N=b.zIndex,sourceX:P,sourceY:F,targetX:I,targetY:te,sourcePosition:ne,targetPosition:L}=q((0,_.useCallback)(t=>{let n=t.nodeLookup.get(b.source),r=t.nodeLookup.get(b.target);if(!n||!r)return rd;let i=ls({id:e,sourceNode:n,targetNode:r,sourceHandle:b.sourceHandle||null,targetHandle:b.targetHandle||null,connectionMode:t.connectionMode,onError:v}),a=Xo({selected:b.selected,zIndex:b.zIndex,sourceNode:n,targetNode:r,elevateOnSelect:t.elevateEdgesOnSelect,zIndexMode:t.zIndexMode});return{...i||rd,zIndex:a}},[b.source,b.target,b.sourceHandle,b.targetHandle,b.selected,b.zIndex,v]),Pc),re=(0,_.useMemo)(()=>b.markerStart?`url('#${ps(b.markerStart,m)}')`:void 0,[b.markerStart,m]),R=(0,_.useMemo)(()=>b.markerEnd?`url('#${ps(b.markerEnd,m)}')`:void 0,[b.markerEnd,m]);if(b.hidden||P===null||F===null||I===null||te===null)return null;let B=t=>{let{addSelectedEdges:n,unselectNodesAndEdges:r,multiSelectionActive:a}=ee.getState();D&&(ee.setState({nodesSelectionActive:!1}),b.selected&&a?(r({nodes:[],edges:[b]}),O.current?.blur()):n([e])),i&&i(t,b)},V=a?e=>{a(e,{...b})}:void 0,ie=o?e=>{o(e,{...b})}:void 0,ae=s?e=>{s(e,{...b})}:void 0,oe=c?e=>{c(e,{...b})}:void 0,se=l?e=>{l(e,{...b})}:void 0;return(0,T.jsx)(`svg`,{style:{zIndex:N},children:(0,T.jsxs)(`g`,{className:z([`react-flow__edge`,`react-flow__edge-${S}`,b.className,g,{selected:b.selected,animated:b.animated,inactive:!D&&!i,updating:k,selectable:D}]),onClick:B,onDoubleClick:V,onContextMenu:ie,onMouseEnter:ae,onMouseMove:oe,onMouseLeave:se,onKeyDown:w?t=>{if(!y&&za.includes(t.key)&&D){let{unselectNodesAndEdges:n,addSelectedEdges:r}=ee.getState();t.key===`Escape`?(O.current?.blur(),n({edges:[b]})):r([e])}}:void 0,tabIndex:w?0:void 0,role:b.ariaRole??(w?`group`:`img`),"aria-roledescription":`edge`,"data-id":e,"data-testid":`rf__edge-${e}`,"aria-label":b.ariaLabel===null?void 0:b.ariaLabel||`Edge from ${b.source} to ${b.target}`,"aria-describedby":w?`${Hc}-${m}`:void 0,ref:O,...b.domAttributes,children:[!j&&(0,T.jsx)(C,{id:e,source:b.source,target:b.target,type:b.type,selected:b.selected,animated:b.animated,selectable:D,deletable:b.deletable??!0,label:b.label,labelStyle:b.labelStyle,labelShowBg:b.labelShowBg,labelBgStyle:b.labelBgStyle,labelBgPadding:b.labelBgPadding,labelBgBorderRadius:b.labelBgBorderRadius,sourceX:P,sourceY:F,targetX:I,targetY:te,sourcePosition:ne,targetPosition:L,data:b.data,style:b.style,sourceHandleId:b.sourceHandle,targetHandleId:b.targetHandle,markerStart:re,markerEnd:R,pathOptions:`pathOptions`in b?b.pathOptions:void 0,interactionWidth:b.interactionWidth}),E&&(0,T.jsx)(cd,{edge:b,isReconnectable:E,reconnectRadius:u,onReconnect:d,onReconnectStart:f,onReconnectEnd:p,sourceX:P,sourceY:F,targetX:I,targetY:te,sourcePosition:ne,targetPosition:L,setUpdateHover:A,setReconnecting:M})]})})}var ud=(0,_.memo)(ld),dd=e=>({edgesFocusable:e.edgesFocusable,edgesReconnectable:e.edgesReconnectable,elementsSelectable:e.elementsSelectable,connectionMode:e.connectionMode,onError:e.onError});function fd({defaultMarkerColor:e,onlyRenderVisibleElements:t,rfId:n,edgeTypes:r,noPanClassName:i,onReconnect:a,onEdgeContextMenu:o,onEdgeMouseEnter:s,onEdgeMouseMove:c,onEdgeMouseLeave:l,onEdgeClick:u,reconnectRadius:d,onEdgeDoubleClick:f,onReconnectStart:p,onReconnectEnd:m,disableKeyboardA11y:h}){let{edgesFocusable:g,edgesReconnectable:_,elementsSelectable:v,onError:y}=q(dd,Pc),b=ku(t);return(0,T.jsxs)(`div`,{className:`react-flow__edges`,children:[(0,T.jsx)(Iu,{defaultColor:e,rfId:n}),b.map(e=>(0,T.jsx)(ud,{id:e,edgesFocusable:g,edgesReconnectable:_,elementsSelectable:v,noPanClassName:i,onReconnect:a,onContextMenu:o,onMouseEnter:s,onMouseMove:c,onMouseLeave:l,onClick:u,reconnectRadius:d,onDoubleClick:f,onReconnectStart:p,onReconnectEnd:m,rfId:n,onError:y,edgeTypes:r,disableKeyboardA11y:h},e))]})}fd.displayName=`EdgeRenderer`;var pd=(0,_.memo)(fd),md=e=>`translate(${e[0]}px,${e[1]}px) scale(${e[2]})`;function hd({children:e}){let t=Rc(),n=(0,_.useRef)(null),[r]=(0,_.useState)(()=>t.getState().transform);return kl(()=>{let e=null,r=()=>{let r=t.getState().transform;e&&r[0]===e[0]&&r[1]===e[1]&&r[2]===e[2]||(e=r,n.current&&(n.current.style.transform=md(r)))};return r(),t.subscribe(r)},[t]),(0,T.jsx)(`div`,{ref:n,className:`react-flow__viewport xyflow__viewport react-flow__container`,style:{transform:md(r)},children:e})}function gd(e){let t=Il(),n=(0,_.useRef)(!1);(0,_.useEffect)(()=>{!n.current&&t.viewportInitialized&&e&&(setTimeout(()=>e(t),1),n.current=!0)},[e,t.viewportInitialized])}var _d=e=>e.panZoom?.syncViewport;function vd(e){let t=q(_d),n=Rc();return(0,_.useEffect)(()=>{e&&(t?.(e),n.setState({transform:[e.x,e.y,e.zoom]}))},[e,t]),null}function $(e){return e.connection.inProgress?{...e.connection,to:Co(e.connection.to,e.transform)}:{...e.connection}}function yd(e){return e?t=>e($(t)):$}function bd(e){return q(yd(e),Pc)}var xd=e=>({nodesConnectable:e.nodesConnectable,isValid:e.connection.isValid,inProgress:e.connection.inProgress,width:e.width,height:e.height});function Sd({containerStyle:e,style:t,type:n,component:r}){let{nodesConnectable:i,width:a,height:o,isValid:s,inProgress:c}=q(xd,Pc);return a&&i&&c?(0,T.jsx)(`svg`,{style:e,width:a,height:o,className:`react-flow__connectionline react-flow__container`,children:(0,T.jsx)(`g`,{className:z([`react-flow__connection`,Ja(s)]),children:(0,T.jsx)(Cd,{style:t,type:n,CustomComponent:r,isValid:s})})}):null}var Cd=({style:e,type:t=Ga.Bezier,CustomComponent:n,isValid:r})=>{let{inProgress:i,from:a,fromNode:o,fromHandle:s,fromPosition:c,to:l,toNode:u,toHandle:d,toPosition:f,pointer:p}=bd();if(!i)return;if(n)return(0,T.jsx)(n,{connectionLineType:t,connectionLineStyle:e,fromNode:o,fromHandle:s,fromX:a.x,fromY:a.y,toX:l.x,toY:l.y,fromPosition:c,toPosition:f,connectionStatus:Ja(r),toNode:u,toHandle:d,pointer:p});let m=``,h={sourceX:a.x,sourceY:a.y,sourcePosition:c,targetX:l.x,targetY:l.y,targetPosition:f};switch(t){case Ga.Bezier:[m]=Jo(h);break;case Ga.SimpleBezier:[m]=Vu(h);break;case Ga.Step:[m]=ss({...h,borderRadius:0});break;case Ga.SmoothStep:[m]=ss(h);break;default:[m]=ts(h)}return(0,T.jsx)(`path`,{d:m,fill:`none`,className:`react-flow__connection-path`,style:e})};Cd.displayName=`ConnectionLine`;var wd={};function Td(e=wd){(0,_.useRef)(e),Rc(),(0,_.useEffect)(()=>{},[e])}function Ed(){Rc(),(0,_.useRef)(!1),(0,_.useEffect)(()=>{},[])}function Dd({nodeTypes:e,edgeTypes:t,onInit:n,onNodeClick:r,onEdgeClick:i,onNodeDoubleClick:a,onEdgeDoubleClick:o,onNodeMouseEnter:s,onNodeMouseMove:c,onNodeMouseLeave:l,onNodeContextMenu:u,onSelectionContextMenu:d,onSelectionStart:f,onSelectionEnd:p,connectionLineType:m,connectionLineStyle:h,connectionLineComponent:g,connectionLineContainerStyle:_,selectionKeyCode:v,selectionOnDrag:y,selectionMode:b,multiSelectionKeyCode:x,panActivationKeyCode:S,zoomActivationKeyCode:C,deleteKeyCode:w,onlyRenderVisibleElements:E,elementsSelectable:D,defaultViewport:O,translateExtent:k,minZoom:A,maxZoom:j,preventScrolling:M,defaultMarkerColor:ee,zoomOnScroll:N,zoomOnPinch:P,panOnScroll:F,panOnScrollSpeed:I,panOnScrollMode:te,zoomOnDoubleClick:ne,panOnDrag:L,autoPanOnSelection:re,onPaneClick:R,onPaneMouseEnter:z,onPaneMouseMove:B,onPaneMouseLeave:V,onPaneScroll:ie,onPaneContextMenu:ae,paneClickDistance:oe,nodeClickDistance:se,onEdgeContextMenu:ce,onEdgeMouseEnter:le,onEdgeMouseMove:ue,onEdgeMouseLeave:de,reconnectRadius:fe,onReconnect:pe,onReconnectStart:me,onReconnectEnd:he,noDragClassName:ge,noWheelClassName:_e,noPanClassName:ve,disableKeyboardA11y:ye,nodeExtent:be,rfId:xe,viewport:Se,onViewportChange:Ce,nodesDraggable:we}){return Td(e),Td(t),Ed(),gd(n),vd(Se),(0,T.jsx)(vu,{onPaneClick:R,onPaneMouseEnter:z,onPaneMouseMove:B,onPaneMouseLeave:V,onPaneContextMenu:ae,onPaneScroll:ie,paneClickDistance:oe,deleteKeyCode:w,selectionKeyCode:v,selectionOnDrag:y,selectionMode:b,onSelectionStart:f,onSelectionEnd:p,multiSelectionKeyCode:x,panActivationKeyCode:S,zoomActivationKeyCode:C,elementsSelectable:D,zoomOnScroll:N,zoomOnPinch:P,zoomOnDoubleClick:ne,panOnScroll:F,panOnScrollSpeed:I,panOnScrollMode:te,panOnDrag:L,autoPanOnSelection:re,defaultViewport:O,translateExtent:k,minZoom:A,maxZoom:j,onSelectionContextMenu:d,preventScrolling:M,noDragClassName:ge,noWheelClassName:_e,noPanClassName:ve,disableKeyboardA11y:ye,onViewportChange:Ce,isControlledViewport:!!Se,children:(0,T.jsxs)(hd,{children:[(0,T.jsx)(pd,{edgeTypes:t,onEdgeClick:i,onEdgeDoubleClick:o,onReconnect:pe,onReconnectStart:me,onReconnectEnd:he,onlyRenderVisibleElements:E,onEdgeContextMenu:ce,onEdgeMouseEnter:le,onEdgeMouseMove:ue,onEdgeMouseLeave:de,reconnectRadius:fe,defaultMarkerColor:ee,noPanClassName:ve,disableKeyboardA11y:ye,rfId:xe}),(0,T.jsx)(Sd,{style:h,type:m,component:g,containerStyle:_}),(0,T.jsx)(`div`,{className:`react-flow__edgelabel-renderer`}),(0,T.jsx)(Ou,{nodeTypes:e,onNodeClick:r,onNodeDoubleClick:a,onNodeMouseEnter:s,onNodeMouseMove:c,onNodeMouseLeave:l,onNodeContextMenu:u,nodeClickDistance:se,onlyRenderVisibleElements:E,noPanClassName:ve,noDragClassName:ge,disableKeyboardA11y:ye,nodeExtent:be,rfId:xe,nodesDraggable:we}),(0,T.jsx)(`div`,{className:`react-flow__viewport-portal`})]})})}Dd.displayName=`GraphView`;var Od=(0,_.memo)(Dd),kd=xo(`React Flow`,`https://reactflow.dev/`),Ad=({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:i,height:a,fitView:o,fitViewOptions:s,minZoom:c=.5,maxZoom:l=2,nodeOrigin:u,nodeExtent:d,zIndexMode:f=`basic`}={})=>{let p=new Map,m=new Map,h=new Map,g=new Map,_=r??t??[],v=n??e??[],y=u??[0,0],b=d??Ra;Ms(h,g,_);let{nodesInitialized:x}=Cs(v,p,m,{nodeOrigin:y,nodeExtent:b,zIndexMode:f}),S=[0,0,1];if(o&&i&&a){let{x:e,y:t,zoom:n}=Oo(eo(p,{filter:e=>!!((e.width||e.initialWidth)&&(e.height||e.initialHeight))}),i,a,c,l,s?.padding??.1);S=[e,t,n]}return{rfId:`1`,width:i??0,height:a??0,transform:S,nodes:v,nodesInitialized:x,nodeLookup:p,parentLookup:m,edges:_,edgeLookup:g,connectionLookup:h,onNodesChange:null,onEdgesChange:null,hasDefaultNodes:n!==void 0,hasDefaultEdges:r!==void 0,panZoom:null,minZoom:c,maxZoom:l,translateExtent:Ra,nodeExtent:b,nodesSelectionActive:!1,userSelectionActive:!1,userSelectionRect:null,connectionMode:Va.Strict,domNode:null,paneDragging:!1,noPanClassName:`nopan`,nodeOrigin:y,nodeDragThreshold:1,connectionDragThreshold:1,snapGrid:[15,15],snapToGrid:!1,nodesDraggable:!0,nodesConnectable:!0,nodesFocusable:!0,edgesFocusable:!0,edgesReconnectable:!0,elementsSelectable:!0,elevateNodesOnSelect:!0,elevateEdgesOnSelect:!0,selectNodesOnDrag:!0,multiSelectionActive:!1,fitViewQueued:o??!1,fitViewOptions:s,fitViewResolver:null,connection:{...Wa},connectionClickStartHandle:null,connectOnClick:!0,ariaLiveMessage:``,autoPanOnConnect:!0,autoPanOnNodeDrag:!0,autoPanOnNodeFocus:!0,autoPanSpeed:15,connectionRadius:20,onError:kd,isValidConnection:void 0,onSelectionChangeHandlers:[],lib:`react`,debug:!1,ariaLabelConfig:Ba,zIndexMode:f,onNodesChangeMiddlewareMap:new Map,onEdgesChangeMiddlewareMap:new Map}},jd=({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:i,height:a,fitView:o,fitViewOptions:s,minZoom:c,maxZoom:l,nodeOrigin:u,nodeExtent:d,zIndexMode:f})=>Nc((p,m)=>{async function h(){let{nodeLookup:e,panZoom:t,fitViewOptions:n,fitViewResolver:r,width:i,height:a,minZoom:o,maxZoom:s}=m();t&&(await io({nodes:e,width:i,height:a,panZoom:t,minZoom:o,maxZoom:s},n),r?.resolve(!0),p({fitViewResolver:null}))}return{...Ad({nodes:e,edges:t,width:i,height:a,fitView:o,fitViewOptions:s,minZoom:c,maxZoom:l,nodeOrigin:u,nodeExtent:d,defaultNodes:n,defaultEdges:r,zIndexMode:f}),setNodes:e=>{let{nodeLookup:t,parentLookup:n,nodeOrigin:r,nodeExtent:i,elevateNodesOnSelect:a,fitViewQueued:o,zIndexMode:s,nodesSelectionActive:c}=m(),{nodesInitialized:l,hasSelectedNodes:u}=Cs(e,t,n,{nodeOrigin:r,nodeExtent:i,elevateNodesOnSelect:a,checkEquality:!0,zIndexMode:s}),d=c&&u;o&&l?(h(),p({nodes:e,nodesInitialized:l,fitViewQueued:!1,fitViewOptions:void 0,nodesSelectionActive:d})):p({nodes:e,nodesInitialized:l,nodesSelectionActive:d})},setEdges:e=>{let{connectionLookup:t,edgeLookup:n}=m();Ms(t,n,e),p({edges:e})},setDefaultNodesAndEdges:(e,t)=>{if(e){let{setNodes:t}=m();t(e),p({hasDefaultNodes:!0})}if(t){let{setEdges:e}=m();e(t),p({hasDefaultEdges:!0})}},updateNodeInternals:e=>{let{triggerNodeChanges:t,nodeLookup:n,parentLookup:r,domNode:i,nodeOrigin:a,nodeExtent:o,debug:s,fitViewQueued:c,zIndexMode:l}=m(),{changes:u,updatedInternals:d}=ks(e,n,r,i,a,o,l);d&&(bs(n,r,{nodeOrigin:a,nodeExtent:o,zIndexMode:l}),c?(h(),p({fitViewQueued:!1,fitViewOptions:void 0})):p({}),u?.length>0&&(s&&console.log(`React Flow: trigger node changes`,u),t?.(u)))},updateNodePositions:(e,t=!1)=>{let n=[],r=[],{nodeLookup:i,triggerNodeChanges:a,connection:o,updateConnection:s,onNodesChangeMiddlewareMap:c}=m();for(let[a,c]of e){let e=i.get(a),l=!!(e?.expandParent&&e?.parentId&&c?.position),u={id:a,type:`position`,position:l?{x:Math.max(0,c.position.x),y:Math.max(0,c.position.y)}:c.position,dragging:t};if(e&&o.inProgress&&o.fromNode.id===e.id){let t=ds(e,o.fromHandle,W.Left,!0);s({...o,from:t})}l&&e.parentId&&n.push({id:a,parentId:e.parentId,rect:{...c.internals.positionAbsolute,width:c.measured.width??0,height:c.measured.height??0}}),r.push(u)}if(n.length>0){let{parentLookup:e,nodeOrigin:t}=m(),a=Os(n,i,e,t);r.push(...a)}for(let e of c.values())r=e(r);a(r)},triggerNodeChanges:e=>{let{onNodesChange:t,setNodes:n,nodes:r,hasDefaultNodes:i,debug:a}=m();e?.length&&(i&&n(vl(e,r)),a&&console.log(`React Flow: trigger node changes`,e),t?.(e))},triggerEdgeChanges:e=>{let{onEdgesChange:t,setEdges:n,edges:r,hasDefaultEdges:i,debug:a}=m();e?.length&&(i&&n(yl(e,r)),a&&console.log(`React Flow: trigger edge changes`,e),t?.(e))},addSelectedNodes:e=>{let{multiSelectionActive:t,edgeLookup:n,nodeLookup:r,triggerNodeChanges:i,triggerEdgeChanges:a}=m();if(t){i(e.map(e=>bl(e,!0)));return}i(xl(r,new Set([...e]),!0)),a(xl(n))},addSelectedEdges:e=>{let{multiSelectionActive:t,edgeLookup:n,nodeLookup:r,triggerNodeChanges:i,triggerEdgeChanges:a}=m();if(t){a(e.map(e=>bl(e,!0)));return}a(xl(n,new Set([...e]))),i(xl(r,new Set,!0))},unselectNodesAndEdges:({nodes:e,edges:t}={})=>{let{edges:n,nodes:r,nodeLookup:i,triggerNodeChanges:a,triggerEdgeChanges:o}=m(),s=e||r,c=t||n,l=[];for(let e of s){if(!e.selected)continue;let t=i.get(e.id);t&&(t.selected=!1),l.push(bl(e.id,!1))}let u=[];for(let e of c)e.selected&&u.push(bl(e.id,!1));a(l),o(u)},setMinZoom:e=>{let{panZoom:t,maxZoom:n}=m();t?.setScaleExtent([e,n]),p({minZoom:e})},setMaxZoom:e=>{let{panZoom:t,minZoom:n}=m();t?.setScaleExtent([n,e]),p({maxZoom:e})},setTranslateExtent:e=>{m().panZoom?.setTranslateExtent(e),p({translateExtent:e})},resetSelectedElements:()=>{let{edges:e,nodes:t,triggerNodeChanges:n,triggerEdgeChanges:r,elementsSelectable:i}=m();if(!i)return;let a=t.reduce((e,t)=>t.selected?[...e,bl(t.id,!1)]:e,[]),o=e.reduce((e,t)=>t.selected?[...e,bl(t.id,!1)]:e,[]);n(a),r(o)},setNodeExtent:e=>{let{nodes:t,nodeLookup:n,parentLookup:r,nodeOrigin:i,elevateNodesOnSelect:a,nodeExtent:o,zIndexMode:s}=m();(e[0][0]!==o[0][0]||e[0][1]!==o[0][1]||e[1][0]!==o[1][0]||e[1][1]!==o[1][1])&&(Cs(t,n,r,{nodeOrigin:i,nodeExtent:e,elevateNodesOnSelect:a,checkEquality:!1,zIndexMode:s}),p({nodeExtent:e}))},panBy:e=>{let{transform:t,width:n,height:r,panZoom:i,translateExtent:a}=m();return As({delta:e,panZoom:i,transform:t,translateExtent:a,width:n,height:r})},setCenter:async(e,t,n)=>{let{width:r,height:i,maxZoom:a,panZoom:o}=m();if(!o)return!1;let s=n?.zoom===void 0?a:n.zoom;return await o.setViewport({x:r/2-e*s,y:i/2-t*s,zoom:s},{duration:n?.duration,ease:n?.ease,interpolate:n?.interpolate}),!0},cancelConnection:()=>{p({connection:{...Wa}})},updateConnection:e=>{p({connection:e})},reset:()=>p({...Ad()})}},Object.is);function Md({initialNodes:e,initialEdges:t,defaultNodes:n,defaultEdges:r,initialWidth:i,initialHeight:a,initialMinZoom:o,initialMaxZoom:s,initialFitViewOptions:c,fitView:l,nodeOrigin:u,nodeExtent:d,zIndexMode:f,children:p}){let[m]=(0,_.useState)(()=>jd({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:i,height:a,fitView:l,minZoom:o,maxZoom:s,fitViewOptions:c,nodeOrigin:u,nodeExtent:d,zIndexMode:f}));return(0,T.jsx)(Ic,{value:m,children:(0,T.jsx)(Nl,{children:(0,T.jsx)(eu,{children:p})})})}function Nd({children:e,nodes:t,edges:n,defaultNodes:r,defaultEdges:i,width:a,height:o,fitView:s,fitViewOptions:c,minZoom:l,maxZoom:u,nodeOrigin:d,nodeExtent:f,zIndexMode:p}){return(0,_.useContext)(Fc)?(0,T.jsx)(T.Fragment,{children:e}):(0,T.jsx)(Md,{initialNodes:t,initialEdges:n,defaultNodes:r,defaultEdges:i,initialWidth:a,initialHeight:o,fitView:s,initialFitViewOptions:c,initialMinZoom:l,initialMaxZoom:u,nodeOrigin:d,nodeExtent:f,zIndexMode:p,children:e})}var Pd={width:`100%`,height:`100%`,overflow:`hidden`,position:`relative`,zIndex:0};function Fd({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,className:i,nodeTypes:a,edgeTypes:o,onNodeClick:s,onEdgeClick:c,onInit:l,onMove:u,onMoveStart:d,onMoveEnd:f,onConnect:p,onConnectStart:m,onConnectEnd:h,onClickConnectStart:g,onClickConnectEnd:v,onNodeMouseEnter:y,onNodeMouseMove:b,onNodeMouseLeave:x,onNodeContextMenu:S,onNodeDoubleClick:C,onNodeDragStart:w,onNodeDrag:E,onNodeDragStop:D,onNodesDelete:O,onEdgesDelete:k,onDelete:A,onSelectionChange:j,onSelectionDragStart:M,onSelectionDrag:ee,onSelectionDragStop:N,onSelectionContextMenu:P,onSelectionStart:F,onSelectionEnd:I,onBeforeDelete:te,connectionMode:ne,connectionLineType:L=Ga.Bezier,connectionLineStyle:re,connectionLineComponent:R,connectionLineContainerStyle:B,deleteKeyCode:V=`Backspace`,selectionKeyCode:ie=`Shift`,selectionOnDrag:ae=!1,selectionMode:oe=Ua.Full,panActivationKeyCode:se=`Space`,multiSelectionKeyCode:ce=ko()?`Meta`:`Control`,zoomActivationKeyCode:le=ko()?`Meta`:`Control`,snapToGrid:ue,snapGrid:de,onlyRenderVisibleElements:fe=!1,selectNodesOnDrag:pe,nodesDraggable:me,autoPanOnNodeFocus:he,nodesConnectable:ge,nodesFocusable:_e,nodeOrigin:ve=rl,edgesFocusable:ye,edgesReconnectable:be,elementsSelectable:xe=!0,defaultViewport:Se=il,minZoom:Ce=.5,maxZoom:we=2,translateExtent:Te=Ra,preventScrolling:Ee=!0,nodeExtent:De,defaultMarkerColor:Oe=`#b1b1b7`,zoomOnScroll:ke=!0,zoomOnPinch:Ae=!0,panOnScroll:je=!1,panOnScrollSpeed:Me=.5,panOnScrollMode:Ne=Ha.Free,zoomOnDoubleClick:Pe=!0,panOnDrag:Fe=!0,onPaneClick:Ie,onPaneMouseEnter:Le,onPaneMouseMove:Re,onPaneMouseLeave:ze,onPaneScroll:Be,onPaneContextMenu:Ve,paneClickDistance:He=1,nodeClickDistance:Ue=0,children:We,onReconnect:Ge,onReconnectStart:Ke,onReconnectEnd:qe,onEdgeContextMenu:Je,onEdgeDoubleClick:Ye,onEdgeMouseEnter:Xe,onEdgeMouseMove:Ze,onEdgeMouseLeave:Qe,reconnectRadius:$e=10,onNodesChange:et,onEdgesChange:tt,noDragClassName:H=`nodrag`,noWheelClassName:nt=`nowheel`,noPanClassName:rt=`nopan`,fitView:it,fitViewOptions:at,connectOnClick:ot,attributionPosition:st,proOptions:ct,defaultEdgeOptions:lt,elevateNodesOnSelect:ut=!0,elevateEdgesOnSelect:dt=!1,disableKeyboardA11y:ft=!1,autoPanOnConnect:pt,autoPanOnNodeDrag:mt,autoPanOnSelection:ht=!0,autoPanSpeed:gt,connectionRadius:_t,isValidConnection:vt,onError:yt,style:bt,id:xt,nodeDragThreshold:St,connectionDragThreshold:Ct,viewport:wt,onViewportChange:Tt,width:Et,height:Dt,colorMode:Ot=`light`,debug:kt,onScroll:At,ariaLabelConfig:jt,zIndexMode:Mt=`basic`,...Nt},Pt){let Ft=xt||`1`,It=ul(Ot),Lt=(0,_.useCallback)(e=>{e.currentTarget.scrollTo({top:0,left:0,behavior:`instant`}),At?.(e)},[At]);return(0,T.jsx)(`div`,{"data-testid":`rf__wrapper`,...Nt,onScroll:Lt,style:{...bt,...Pd},ref:Pt,className:z([`react-flow`,i,It]),id:xt,role:`application`,children:(0,T.jsxs)(Nd,{nodes:e,edges:t,width:Et,height:Dt,fitView:it,fitViewOptions:at,minZoom:Ce,maxZoom:we,nodeOrigin:ve,nodeExtent:De,zIndexMode:Mt,children:[(0,T.jsx)(cl,{nodes:e,edges:t,defaultNodes:n,defaultEdges:r,onConnect:p,onConnectStart:m,onConnectEnd:h,onClickConnectStart:g,onClickConnectEnd:v,nodesDraggable:me,autoPanOnNodeFocus:he,nodesConnectable:ge,nodesFocusable:_e,edgesFocusable:ye,edgesReconnectable:be,elementsSelectable:xe,elevateNodesOnSelect:ut,elevateEdgesOnSelect:dt,minZoom:Ce,maxZoom:we,nodeExtent:De,onNodesChange:et,onEdgesChange:tt,snapToGrid:ue,snapGrid:de,connectionMode:ne,translateExtent:Te,connectOnClick:ot,defaultEdgeOptions:lt,fitView:it,fitViewOptions:at,onNodesDelete:O,onEdgesDelete:k,onDelete:A,onNodeDragStart:w,onNodeDrag:E,onNodeDragStop:D,onSelectionDrag:ee,onSelectionDragStart:M,onSelectionDragStop:N,onMove:u,onMoveStart:d,onMoveEnd:f,noPanClassName:rt,nodeOrigin:ve,rfId:Ft,autoPanOnConnect:pt,autoPanOnNodeDrag:mt,autoPanSpeed:gt,onError:yt,connectionRadius:_t,isValidConnection:vt,selectNodesOnDrag:pe,nodeDragThreshold:St,connectionDragThreshold:Ct,onBeforeDelete:te,debug:kt,ariaLabelConfig:jt,zIndexMode:Mt}),(0,T.jsx)(Od,{onInit:l,onNodeClick:s,onEdgeClick:c,onNodeMouseEnter:y,onNodeMouseMove:b,onNodeMouseLeave:x,onNodeContextMenu:S,onNodeDoubleClick:C,nodeTypes:a,edgeTypes:o,connectionLineType:L,connectionLineStyle:re,connectionLineComponent:R,connectionLineContainerStyle:B,selectionKeyCode:ie,selectionOnDrag:ae,selectionMode:oe,deleteKeyCode:V,multiSelectionKeyCode:ce,panActivationKeyCode:se,zoomActivationKeyCode:le,onlyRenderVisibleElements:fe,defaultViewport:Se,translateExtent:Te,minZoom:Ce,maxZoom:we,preventScrolling:Ee,zoomOnScroll:ke,zoomOnPinch:Ae,zoomOnDoubleClick:Pe,panOnScroll:je,panOnScrollSpeed:Me,panOnScrollMode:Ne,panOnDrag:Fe,autoPanOnSelection:ht,onPaneClick:Ie,onPaneMouseEnter:Le,onPaneMouseMove:Re,onPaneMouseLeave:ze,onPaneScroll:Be,onPaneContextMenu:Ve,paneClickDistance:He,nodeClickDistance:Ue,onSelectionContextMenu:P,onSelectionStart:F,onSelectionEnd:I,onReconnect:Ge,onReconnectStart:Ke,onReconnectEnd:qe,onEdgeContextMenu:Je,onEdgeDoubleClick:Ye,onEdgeMouseEnter:Xe,onEdgeMouseMove:Ze,onEdgeMouseLeave:Qe,reconnectRadius:$e,defaultMarkerColor:Oe,noDragClassName:H,noWheelClassName:nt,noPanClassName:rt,rfId:Ft,disableKeyboardA11y:ft,nodeExtent:De,viewport:wt,onViewportChange:Tt,nodesDraggable:me}),(0,T.jsx)(nl,{onSelectionChange:j}),We,(0,T.jsx)(Xc,{proOptions:ct,position:st}),(0,T.jsx)(qc,{rfId:Ft,disableKeyboardA11y:ft})]})})}var Id=Ol(Fd);La.error014();function Ld({dimensions:e,lineWidth:t,variant:n,className:r}){return(0,T.jsx)(`path`,{strokeWidth:t,d:`M${e[0]/2} 0 V${e[1]} M0 ${e[1]/2} H${e[0]}`,className:z([`react-flow__background-pattern`,n,r])})}function Rd({radius:e,className:t}){return(0,T.jsx)(`circle`,{cx:e,cy:e,r:e,className:z([`react-flow__background-pattern`,`dots`,t])})}var zd;(function(e){e.Lines=`lines`,e.Dots=`dots`,e.Cross=`cross`})(zd||={});var Bd={[zd.Dots]:1,[zd.Lines]:1,[zd.Cross]:6},Vd=e=>({transform:e.transform,patternId:`pattern-${e.rfId}`});function Hd({id:e,variant:t=zd.Dots,gap:n=20,size:r,lineWidth:i=1,offset:a=0,color:o,bgColor:s,style:c,className:l,patternClassName:u}){let d=(0,_.useRef)(null),{transform:f,patternId:p}=q(Vd,Pc),m=r||Bd[t],h=t===zd.Dots,g=t===zd.Cross,v=Array.isArray(n)?n:[n,n],y=[v[0]*f[2]||1,v[1]*f[2]||1],b=m*f[2],x=Array.isArray(a)?a:[a,a],S=g?[b,b]:y,C=[x[0]*f[2]+S[0]/2,x[1]*f[2]+S[1]/2],w=`${p}${e||``}`;return(0,T.jsxs)(`svg`,{className:z([`react-flow__background`,l]),style:{...c,...Z,"--xy-background-color-props":s,"--xy-background-pattern-color-props":o},ref:d,"data-testid":`rf__background`,children:[(0,T.jsx)(`pattern`,{id:w,x:f[0]%y[0],y:f[1]%y[1],width:y[0],height:y[1],patternUnits:`userSpaceOnUse`,patternTransform:`translate(-${C[0]},-${C[1]})`,children:h?(0,T.jsx)(Rd,{radius:b/2,className:u}):(0,T.jsx)(Ld,{dimensions:S,lineWidth:i,variant:t,className:u})}),(0,T.jsx)(`rect`,{x:`0`,y:`0`,width:`100%`,height:`100%`,fill:`url(#${w})`})]})}Hd.displayName=`Background`;var Ud=(0,_.memo)(Hd);function Wd(){return(0,T.jsx)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 32 32`,children:(0,T.jsx)(`path`,{d:`M32 18.133H18.133V32h-4.266V18.133H0v-4.266h13.867V0h4.266v13.867H32z`})})}function Gd(){return(0,T.jsx)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 32 5`,children:(0,T.jsx)(`path`,{d:`M0 0h32v4.2H0z`})})}function Kd(){return(0,T.jsx)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 32 30`,children:(0,T.jsx)(`path`,{d:`M3.692 4.63c0-.53.4-.938.939-.938h5.215V0H4.708C2.13 0 0 2.054 0 4.63v5.216h3.692V4.631zM27.354 0h-5.2v3.692h5.17c.53 0 .984.4.984.939v5.215H32V4.631A4.624 4.624 0 0027.354 0zm.954 24.83c0 .532-.4.94-.939.94h-5.215v3.768h5.215c2.577 0 4.631-2.13 4.631-4.707v-5.139h-3.692v5.139zm-23.677.94c-.531 0-.939-.4-.939-.94v-5.138H0v5.139c0 2.577 2.13 4.707 4.708 4.707h5.138V25.77H4.631z`})})}function qd(){return(0,T.jsx)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 25 32`,children:(0,T.jsx)(`path`,{d:`M21.333 10.667H19.81V7.619C19.81 3.429 16.38 0 12.19 0 8 0 4.571 3.429 4.571 7.619v3.048H3.048A3.056 3.056 0 000 13.714v15.238A3.056 3.056 0 003.048 32h18.285a3.056 3.056 0 003.048-3.048V13.714a3.056 3.056 0 00-3.048-3.047zM12.19 24.533a3.056 3.056 0 01-3.047-3.047 3.056 3.056 0 013.047-3.048 3.056 3.056 0 013.048 3.048 3.056 3.056 0 01-3.048 3.047zm4.724-13.866H7.467V7.619c0-2.59 2.133-4.724 4.723-4.724 2.591 0 4.724 2.133 4.724 4.724v3.048z`})})}function Jd(){return(0,T.jsx)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 25 32`,children:(0,T.jsx)(`path`,{d:`M21.333 10.667H19.81V7.619C19.81 3.429 16.38 0 12.19 0c-4.114 1.828-1.37 2.133.305 2.438 1.676.305 4.42 2.59 4.42 5.181v3.048H3.047A3.056 3.056 0 000 13.714v15.238A3.056 3.056 0 003.048 32h18.285a3.056 3.056 0 003.048-3.048V13.714a3.056 3.056 0 00-3.048-3.047zM12.19 24.533a3.056 3.056 0 01-3.047-3.047 3.056 3.056 0 013.047-3.048 3.056 3.056 0 013.048 3.048 3.056 3.056 0 01-3.048 3.047z`})})}function Yd({children:e,className:t,...n}){return(0,T.jsx)(`button`,{type:`button`,className:z([`react-flow__controls-button`,t]),...n,children:e})}var Xd=e=>({isInteractive:e.nodesDraggable||e.nodesConnectable||e.elementsSelectable,minZoomReached:e.transform[2]<=e.minZoom,maxZoomReached:e.transform[2]>=e.maxZoom,ariaLabelConfig:e.ariaLabelConfig});function Zd({style:e,showZoom:t=!0,showFitView:n=!0,showInteractive:r=!0,fitViewOptions:i,onZoomIn:a,onZoomOut:o,onFitView:s,onInteractiveChange:c,className:l,children:u,position:d=`bottom-left`,orientation:f=`vertical`,"aria-label":p}){let m=Rc(),{isInteractive:h,minZoomReached:g,maxZoomReached:_,ariaLabelConfig:v}=q(Xd,Pc),{zoomIn:y,zoomOut:b,fitView:x}=Il();return(0,T.jsxs)(Jc,{className:z([`react-flow__controls`,f===`horizontal`?`horizontal`:`vertical`,l]),position:d,style:e,"data-testid":`rf__controls`,"aria-label":p??v[`controls.ariaLabel`],children:[t&&(0,T.jsxs)(T.Fragment,{children:[(0,T.jsx)(Yd,{onClick:()=>{y(),a?.()},className:`react-flow__controls-zoomin`,title:v[`controls.zoomIn.ariaLabel`],"aria-label":v[`controls.zoomIn.ariaLabel`],disabled:_,children:(0,T.jsx)(Wd,{})}),(0,T.jsx)(Yd,{onClick:()=>{b(),o?.()},className:`react-flow__controls-zoomout`,title:v[`controls.zoomOut.ariaLabel`],"aria-label":v[`controls.zoomOut.ariaLabel`],disabled:g,children:(0,T.jsx)(Gd,{})})]}),n&&(0,T.jsx)(Yd,{className:`react-flow__controls-fitview`,onClick:()=>{x(i),s?.()},title:v[`controls.fitView.ariaLabel`],"aria-label":v[`controls.fitView.ariaLabel`],children:(0,T.jsx)(Kd,{})}),r&&(0,T.jsx)(Yd,{className:`react-flow__controls-interactive`,onClick:()=>{m.setState({nodesDraggable:!h,nodesConnectable:!h,elementsSelectable:!h}),c?.(!h)},title:v[`controls.interactive.ariaLabel`],"aria-label":v[`controls.interactive.ariaLabel`],children:h?(0,T.jsx)(Jd,{}):(0,T.jsx)(qd,{})}),u]})}Zd.displayName=`Controls`;var Qd=(0,_.memo)(Zd);function $d({id:e,x:t,y:n,width:r,height:i,style:a,color:o,strokeColor:s,strokeWidth:c,className:l,borderRadius:u,shapeRendering:d,selected:f,onClick:p}){let{background:m,backgroundColor:h}=a||{},g=o||m||h;return(0,T.jsx)(`rect`,{className:z([`react-flow__minimap-node`,{selected:f},l]),x:t,y:n,rx:u,ry:u,width:r,height:i,style:{fill:g,stroke:s,strokeWidth:c},shapeRendering:d,onClick:p?t=>p(t,e):void 0})}var ef=(0,_.memo)($d),tf=e=>e.nodes.map(e=>e.id),nf=e=>e instanceof Function?e:()=>e;function rf({nodeStrokeColor:e,nodeColor:t,nodeClassName:n=``,nodeBorderRadius:r=5,nodeStrokeWidth:i,nodeComponent:a=ef,onClick:o}){let s=q(tf,Pc),c=nf(t),l=nf(e),u=nf(n),d=typeof window>`u`||window.chrome?`crispEdges`:`geometricPrecision`;return(0,T.jsx)(T.Fragment,{children:s.map(e=>(0,T.jsx)(of,{id:e,nodeColorFunc:c,nodeStrokeColorFunc:l,nodeClassNameFunc:u,nodeBorderRadius:r,nodeStrokeWidth:i,NodeComponent:a,onClick:o,shapeRendering:d},e))})}function af({id:e,nodeColorFunc:t,nodeStrokeColorFunc:n,nodeClassNameFunc:r,nodeBorderRadius:i,nodeStrokeWidth:a,shapeRendering:o,NodeComponent:s,onClick:c}){let{node:l,x:u,y:d,width:f,height:p}=q(t=>{let n=t.nodeLookup.get(e);if(!n)return{node:void 0,x:0,y:0,width:0,height:0};let r=n.internals.userNode,{x:i,y:a}=n.internals.positionAbsolute,{width:o,height:s}=jo(r);return{node:r,x:i,y:a,width:o,height:s}},Pc);return!l||l.hidden||!Mo(l)?null:(0,T.jsx)(s,{x:u,y:d,width:f,height:p,style:l.style,selected:!!l.selected,className:r(l),color:t(l),borderRadius:i,strokeColor:n(l),strokeWidth:a,shapeRendering:o,onClick:c,id:l.id})}var of=(0,_.memo)(af),sf=(0,_.memo)(rf),cf=200,lf=150,uf=e=>!e.hidden,df=e=>{let t={x:-e.transform[0]/e.transform[2],y:-e.transform[1]/e.transform[2],width:e.width/e.transform[2],height:e.height/e.transform[2]};return{viewBB:t,boundingRect:e.nodeLookup.size>0?go(eo(e.nodeLookup,{filter:uf}),t):t,rfId:e.rfId,panZoom:e.panZoom,translateExtent:e.translateExtent,flowWidth:e.width,flowHeight:e.height,ariaLabelConfig:e.ariaLabelConfig}},ff=(e,t)=>e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height,pf=(e,t)=>ff(e.viewBB,t.viewBB)&&ff(e.boundingRect,t.boundingRect)&&e.rfId===t.rfId&&e.panZoom===t.panZoom&&e.translateExtent===t.translateExtent&&e.flowWidth===t.flowWidth&&e.flowHeight===t.flowHeight&&e.ariaLabelConfig===t.ariaLabelConfig,mf=`react-flow__minimap-desc`;function hf({style:e,className:t,nodeStrokeColor:n,nodeColor:r,nodeClassName:i=``,nodeBorderRadius:a=5,nodeStrokeWidth:o,nodeComponent:s,bgColor:c,maskColor:l,maskStrokeColor:u,maskStrokeWidth:d,position:f=`bottom-right`,onClick:p,onNodeClick:m,pannable:h=!1,zoomable:g=!1,ariaLabel:v,inversePan:y,zoomStep:b=1,offsetScale:x=5}){let S=Rc(),C=(0,_.useRef)(null),{boundingRect:w,viewBB:E,rfId:D,panZoom:O,translateExtent:k,flowWidth:A,flowHeight:j,ariaLabelConfig:M}=q(df,pf),ee=e?.width??cf,N=e?.height??lf,P=w.width/ee,F=w.height/N,I=Math.max(P,F),te=I*ee,ne=I*N,L=x*I,re=w.x-(te-w.width)/2-L,R=w.y-(ne-w.height)/2-L,B=te+L*2,V=ne+L*2,ie=`${mf}-${D}`,ae=(0,_.useRef)(0),oe=(0,_.useRef)();ae.current=I,(0,_.useEffect)(()=>{if(C.current&&O)return oe.current=Ys({domNode:C.current,panZoom:O,getTransform:()=>S.getState().transform,getViewScale:()=>ae.current}),()=>{oe.current?.destroy()}},[O]),(0,_.useEffect)(()=>{oe.current?.update({translateExtent:k,width:A,height:j,inversePan:y,pannable:h,zoomStep:b,zoomable:g})},[h,g,y,b,k,A,j]);let se=p?e=>{let[t,n]=oe.current?.pointer(e)||[0,0];p(e,{x:t,y:n})}:void 0,ce=m?(0,_.useCallback)((e,t)=>{let n=S.getState().nodeLookup.get(t).internals.userNode;m(e,n)},[]):void 0,le=v??M[`minimap.ariaLabel`];return(0,T.jsx)(Jc,{position:f,style:{...e,"--xy-minimap-background-color-props":typeof c==`string`?c:void 0,"--xy-minimap-mask-background-color-props":typeof l==`string`?l:void 0,"--xy-minimap-mask-stroke-color-props":typeof u==`string`?u:void 0,"--xy-minimap-mask-stroke-width-props":typeof d==`number`?d*I:void 0,"--xy-minimap-node-background-color-props":typeof r==`string`?r:void 0,"--xy-minimap-node-stroke-color-props":typeof n==`string`?n:void 0,"--xy-minimap-node-stroke-width-props":typeof o==`number`?o:void 0},className:z([`react-flow__minimap`,t]),"data-testid":`rf__minimap`,children:(0,T.jsxs)(`svg`,{width:ee,height:N,viewBox:`${re} ${R} ${B} ${V}`,className:`react-flow__minimap-svg`,role:`img`,"aria-labelledby":ie,ref:C,onClick:se,children:[le&&(0,T.jsx)(`title`,{id:ie,children:le}),(0,T.jsx)(sf,{onClick:ce,nodeColor:r,nodeStrokeColor:n,nodeBorderRadius:a,nodeClassName:i,nodeStrokeWidth:o,nodeComponent:s}),(0,T.jsx)(`path`,{className:`react-flow__minimap-mask`,d:`M${re-L},${R-L}h${B+L*2}v${V+L*2}h${-B-L*2}z - M${E.x},${E.y}h${E.width}v${E.height}h${-E.width}z`,fillRule:`evenodd`,pointerEvents:`none`})]})})}hf.displayName=`MiniMap`;var gf=(0,_.memo)(hf),_f=e=>t=>e?`${Math.max(1/t.transform[2],1)}`:void 0,vf={[uc.Line]:`right`,[uc.Handle]:`bottom-right`};function yf({nodeId:e,position:t,variant:n=uc.Handle,className:r,style:i=void 0,children:a,color:o,minWidth:s=10,minHeight:c=10,maxWidth:l=Number.MAX_VALUE,maxHeight:u=Number.MAX_VALUE,keepAspectRatio:d=!1,resizeDirection:f,autoScale:p=!0,shouldResize:m,onResizeStart:h,onResize:g,onResizeEnd:v}){let y=Zl(),b=typeof e==`string`?e:y,x=Rc(),S=(0,_.useRef)(null),C=n===uc.Handle,w=q((0,_.useCallback)(_f(C&&p),[C,p]),Pc),E=(0,_.useRef)(null),D=t??vf[n];(0,_.useEffect)(()=>{if(!(!S.current||!b))return E.current||=xc({domNode:S.current,nodeId:b,getStoreItems:()=>{let{nodeLookup:e,transform:t,snapGrid:n,snapToGrid:r,nodeOrigin:i,domNode:a}=x.getState();return{nodeLookup:e,transform:t,snapGrid:n,snapToGrid:r,nodeOrigin:i,paneDomNode:a}},onChange:(e,t)=>{let{triggerNodeChanges:n,nodeLookup:r,parentLookup:i,nodeOrigin:a}=x.getState(),o=[],s={x:e.x,y:e.y},c=r.get(b);if(c&&c.expandParent&&c.parentId){let t=c.origin??a,n=e.width??c.measured.width??0,l=e.height??c.measured.height??0,u=Os([{id:c.id,parentId:c.parentId,rect:{width:n,height:l,...No({x:e.x??c.position.x,y:e.y??c.position.y},{width:n,height:l},c.parentId,r,t)}}],r,i,a);o.push(...u),s.x=e.x?Math.max(t[0]*n,e.x):void 0,s.y=e.y?Math.max(t[1]*l,e.y):void 0}if(s.x!==void 0&&s.y!==void 0){let e={id:b,type:`position`,position:{...s}};o.push(e)}if(e.width!==void 0&&e.height!==void 0){let t={id:b,type:`dimensions`,resizing:!0,setAttributes:f?f===`horizontal`?`width`:`height`:!0,dimensions:{width:e.width,height:e.height}};o.push(t)}for(let e of t){let t={...e,type:`position`};o.push(t)}n(o)},onEnd:({width:e,height:t})=>{let n={id:b,type:`dimensions`,resizing:!1,dimensions:{width:e,height:t}};x.getState().triggerNodeChanges([n])}}),E.current.update({controlPosition:D,boundaries:{minWidth:s,minHeight:c,maxWidth:l,maxHeight:u},keepAspectRatio:d,resizeDirection:f,onResizeStart:h,onResize:g,onResizeEnd:v,shouldResize:m}),()=>{E.current?.destroy()}},[D,s,c,l,u,d,h,g,v,m]);let O=D.split(`-`);return(0,T.jsx)(`div`,{className:z([`react-flow__resize-control`,`nodrag`,...O,n,r]),ref:S,style:{...i,scale:w,...o&&{[C?`backgroundColor`:`borderColor`]:o}},children:a})}(0,_.memo)(yf);var bf={"arch.context":0,"django.app":0,"django.route":1,"django.websocket_route":1,"fastapi.route":1,"django.url_name":2,"django.view":3,"django.viewset_action":3,"django.permission":3,"django.throttle":3,"django.serializer":4,"django.form":4,"graphql.type":4,"fastapi.model":4,"django.serializer_field":5,"django.service":5,"graphql.field":5,"django.model":6,"django.field":7,"django.relation":7,"django.task":8,"django.receiver":8,"django.signal":8,"django.test":8,"django.migration_op":8,"django.admin":8,"django.management_command":8,"django.consumer":8,"django.cache_key":8,"django.feature_flag":8,"django.side_effect":8,"openapi.path":9,"graphql.operation":9,"react.api_client":10,"django.htmx":10,"react.query_key":11,"react.hook":11,"react.feature":11,"react.route":12,"react.page":12,"react.server_action":12,"django.template":12,"react.component":13,"react.context":13,"react.form_schema":14,"react.test":14};function xf(e){return bf[e]??8}var Sf=8;function Cf(e){if(!e.length)return NaN;let t=[...e].sort((e,t)=>e-t),n=Math.floor(t.length/2);return t.length%2?t[n]:(t[n-1]+t[n])/2}function wf(e,t=[]){let n=new Map;if(!e.length)return n;let r=new Map;for(let t of e){let e=xf(t.type),n=r.get(e)??[];n.push(t),r.set(e,n)}let i=[...r.keys()].sort((e,t)=>e-t).map(e=>[...r.get(e)??[]].sort((e,t)=>e.name.localeCompare(t.name)||e.id.localeCompare(t.id))),a=new Set(e.map(e=>e.id)),o=new Map,s=new Map;for(let t of e)o.set(t.id,[]),s.set(t.id,[]);for(let e of t)!a.has(e.src)||!a.has(e.dst)||e.src===e.dst||(s.get(e.src).push(e.dst),o.get(e.dst).push(e.src));let c=new Map;i.forEach((e,t)=>{for(let n of e)c.set(n.id,t)});let l=new Map,u=()=>{for(let e of i)e.forEach((e,t)=>l.set(e.id,t))};u();let d=(e,t)=>{let n=e.map((e,n)=>{let r=Cf(t(e.id).map(e=>l.get(e)).filter(e=>e!==void 0));return{n:e,bary:Number.isNaN(r)?n:r,name:e.name,id:e.id}});return n.sort((e,t)=>e.bary-t.bary||e.name.localeCompare(t.name)||e.id.localeCompare(t.id)),n.map(e=>e.n)},f=e=>t=>c.get(t)===e;for(let e=0;e(o.get(t)??[]).filter(f(e-1))),u();for(let e=i.length-2;e>=0;e--)i[e]=d(i[e],t=>(s.get(t)??[]).filter(f(e+1))),u()}let p=Math.max(...i.map(e=>e.length),1),m=[],h=0;for(let e=0;ee.id)),r=new Set((i[e+1]??[]).map(e=>e.id)),a=0;if(r.size)for(let e of t)n.has(e.src)&&r.has(e.dst)&&(a+=1);let o=Math.min(120,Math.max(0,(a-2)*12));h+=296+o}return i.forEach((e,t)=>{let r=(p-e.length)*92/2;e.forEach((e,i)=>{n.set(e.id,{x:m[t]??0,y:r+i*92})})}),n}var Tf=[{id:`layers`,label:`Architecture layers`},{id:`flow`,label:`Edge flow`},{id:`tree`,label:`Spanning tree`},{id:`radial`,label:`Radial`},{id:`concentric`,label:`Concentric layers`},{id:`circle`,label:`Circle`},{id:`clusters`,label:`Type clusters`},{id:`grid`,label:`Compact grid`},{id:`force`,label:`Force directed`}],Ef=new Set(Tf.map(e=>e.id)),Df=`loadpath.graphLayout`,Of=8,kf=64,Af=240,jf=296,Mf=92,Nf=new Set([`django.route`,`react.route`,`react.page`,`react.server_action`,`django.task`,`django.migration_op`,`django.permission`,`openapi.path`,`django.consumer`,`django.websocket_route`,`django.template`,`graphql.operation`,`fastapi.route`]);function Pf(e=()=>document.createElement(`canvas`)){try{let t=e(),n=t.getContext(`webgl2`)||t.getContext(`webgl`)||t.getContext(`experimental-webgl`);return n?((n.getExtension?.(`WEBGL_lose_context`))?.loseContext(),!0):!1}catch{return!1}}function Ff(e,t,n){return e===`3d`&&t==null&&n!==!0?`2d`:e}var If=new Set([`django.field`,`django.serializer_field`,`django.relation`,`django.test`,`react.test`,`graphql.field`,`django.url_name`,`django.throttle`]),Lf={"arch.context":`#edf2f4`,"django.app":`#8d99ae`,"django.route":`#4cc9f0`,"django.url_name":`#4cc9f0`,"django.view":`#4895ef`,"django.viewset_action":`#4361ee`,"django.permission":`#7b8cde`,"django.serializer":`#f4a261`,"django.form":`#e9c46a`,"django.serializer_field":`#e9c46a`,"django.service":`#90be6d`,"django.model":`#2a9d8f`,"django.field":`#8ac926`,"django.task":`#e76f51`,"django.receiver":`#e85d04`,"django.signal":`#f4a261`,"django.test":`#6c757d`,"django.admin":`#adb5bd`,"django.migration_op":`#9d4edd`,"django.consumer":`#e76f51`,"django.websocket_route":`#4cc9f0`,"django.template":`#c77dff`,"django.htmx":`#ff6b6b`,"django.cache_key":`#6c757d`,"django.feature_flag":`#f4a261`,"django.side_effect":`#e85d04`,"graphql.type":`#00bbf9`,"graphql.operation":`#00bbf9`,"fastapi.route":`#4cc9f0`,"fastapi.model":`#f4a261`,"openapi.path":`#00bbf9`,"react.api_client":`#ff6b6b`,"react.query_key":`#adb5bd`,"react.hook":`#7b2cbf`,"react.feature":`#9d4edd`,"react.route":`#c77dff`,"react.page":`#c77dff`,"react.server_action":`#e76f51`,"react.component":`#9d4edd`,"react.form_schema":`#ffd166`,"react.test":`#6c757d`},Rf=160,zf=.42,Bf=100,Vf=.45,Hf=.8,Uf={0:`context`,1:`routes`,2:`url names`,3:`views`,4:`serializers`,5:`services`,6:`models`,7:`fields`,8:`jobs / signals`,9:`openapi`,10:`api client`,11:`hooks`,12:`pages`,13:`components`,14:`forms / tests`};function Wf(e){return e.startsWith(`react.`)?`react`:e.startsWith(`openapi.`)||e.startsWith(`graphql.`)||e.startsWith(`fastapi.`)?`stitch`:e.startsWith(`arch.`)?`arch`:`django`}function Gf(e){return Lf[e]?Lf[e]:e.startsWith(`react.`)?`#9d4edd`:e.startsWith(`openapi.`)?`#00bbf9`:`#4a5568`}function Kf(e,t=typeof navigator<`u`&&!!navigator.webdriver){return t?`2d`:e>=90?`3d`:`2d`}function qf(e){return e>=90?`overview`:`full`}function Jf(e,t,n=1){let r=new Set([e]),i=new Set([e]);for(let e=0;en.families.has(Wf(e.type)));n.detail===`overview`&&(r=r.filter(e=>!If.has(e.type)));let i=new Set(r.map(e=>e.id)),a=t.filter(e=>i.has(e.src)&&i.has(e.dst)),o=n.focusId?Jf(n.focusId,a,1):new Set;if(n.neighborhoodOnly&&n.focusId&&o.size){r=r.filter(e=>o.has(e.id));let e=new Set(r.map(e=>e.id));return{nodes:r,edges:a.filter(t=>e.has(t.src)&&e.has(t.dst)),neighborIds:o}}return{nodes:r,edges:a,neighborIds:o}}function Xf(e,t){let n=t.trim().toLowerCase();return n?e.filter(e=>`${e.name} ${e.qualified_name} ${e.type} ${e.file_path||``} ${e.context||``}`.toLowerCase().includes(n)).slice(0,24):[]}function Zf(e,t,n,r){let i=new Set(e.map(e=>e.id));if(!i.has(n))return{nodeIds:new Set,edgeIds:new Set};let a=new Map,o=new Map;for(let e of t){if(!i.has(e.src)||!i.has(e.dst))continue;let t=a.get(e.src)??[];t.push({dst:e.dst,id:e.id}),a.set(e.src,t);let n=o.get(e.dst)??[];n.push({src:e.src,id:e.id}),o.set(e.dst,n)}let s=new Set(e.filter(e=>Nf.has(e.type)).map(e=>e.id)),c=r&&i.has(r)?new Set([r]):s.size?s:i,l=new Set,u=[n];for(;u.length;){let e=u.pop();if(!l.has(e)){l.add(e);for(let t of a.get(e)??[])l.has(t.dst)||u.push(t.dst)}}let d=new Set([n]),f=[...c].filter(e=>l.has(e)),p=new Set(f);for(;f.length;){let e=f.pop();d.add(e);for(let t of o.get(e)??[])l.has(t.src)&&!p.has(t.src)&&(p.add(t.src),f.push(t.src))}let m=new Set;for(let e of t)d.has(e.src)&&d.has(e.dst)&&m.add(e.id);return{nodeIds:d,edgeIds:m}}var Qf=16,$f=28;function ep(e){return(e.context||``).trim()}function tp(e){return e.confidence!e&&t?1:e&&!t?-1:e.localeCompare(t));let s=new Map(a.map((e,t)=>[e,t])),c=(a.length-1)/2,l=dp(n),u=[...new Set([...r.values()].map(e=>e.x))].sort((e,t)=>e-t),d=new Map(u.map((e,t)=>[e,t]));for(let t of e){let e=r.get(t.id)??{x:0,y:0},n=((s.get(ep(t))??0)-c)*Bf;if(l){let r=d.get(e.x)??0;i.set(t.id,{x:r*Rf,y:-e.y*zf,z:n})}else i.set(t.id,{x:e.x*Vf,y:-e.y*Vf,z:n})}return i}function ip(e){return e===`layers`||e===`flow`?`slab`:e===`radial`||e===`concentric`||e===`circle`?`ring`:`none`}function ap(e,t,n=`layers`){if(!e.length)return[];let r=ip(n);if(r===`none`)return[];if(r===`ring`)return cp(e,t);let i=new Map;for(let n of e){let e=Math.round((t.get(n.id)?.x??0)*10)/10,r=i.get(e)??[];r.push(n),i.set(e,r)}return[...i.entries()].sort((e,t)=>e[0]-t[0]).map(([,e])=>sp(e,t,n))}function op(e,t){let n=new Map;for(let t of e){let e=xf(t.type);n.set(e,(n.get(e)||0)+1)}let r=-1,i=0;for(let[e,t]of n)t>i&&(r=e,i=t);return t===`flow`&&ie[0]-t[0]).map(([,e])=>{let n=0,r=0;for(let i of e){let e=t.get(i.id)??{x:0,y:0,z:0};n+=Math.hypot(e.x,e.y),r+=e.z}let i=n/e.length;return{shape:`ring`,x:0,y:0,z:r/e.length,extentY:0,extentZ:0,radius:i,label:i<12?``:op(e,`radial`),count:e.length}}).filter(e=>e.radius>=12)}function lp(){try{if(typeof localStorage>`u`)return`layers`;let e=localStorage.getItem(Df);return e&&Ef.has(e)?e:`layers`}catch{return`layers`}}function up(e){try{if(typeof localStorage>`u`)return;localStorage.setItem(Df,e)}catch{}}function dp(e){return e===`layers`||e===`flow`}function fp(e){if(!e.length)return NaN;let t=[...e].sort((e,t)=>e-t),n=Math.floor(t.length/2);return t.length%2?t[n]:(t[n-1]+t[n])/2}function pp(e,t){return e.name.localeCompare(t.name)||e.id.localeCompare(t.id)}function mp(e,t){return xf(e.type)-xf(t.type)||pp(e,t)}function hp(e,t,n){e.forEach((r,i)=>{let a=-Math.PI/2+2*Math.PI*i/Math.max(e.length,1);n.set(r.id,{x:Math.cos(a)*t,y:Math.sin(a)*t})})}function gp(e,t){return Math.max(t*jf,e<=1?t===0?0:208:e*Af/(2*Math.PI))}function _p(e,t){let n=new Map;if(!e.length)return n;let r=new Set(e.flat().map(e=>e.id)),i=new Map,a=new Map;for(let t of e.flat())i.set(t.id,[]),a.set(t.id,[]);for(let e of t)!r.has(e.src)||!r.has(e.dst)||e.src===e.dst||(a.get(e.src).push(e.dst),i.get(e.dst).push(e.src));let o=new Map;e.forEach((e,t)=>{for(let n of e)o.set(n.id,t)});let s=new Map,c=()=>{for(let t of e)t.forEach((e,t)=>s.set(e.id,t))};c();let l=(e,t)=>{let n=e.map((e,n)=>{let r=fp(t(e.id).map(e=>s.get(e)).filter(e=>e!==void 0));return{n:e,bary:Number.isNaN(r)?n:r,name:e.name,id:e.id}});return n.sort((e,t)=>e.bary-t.bary||e.name.localeCompare(t.name)||e.id.localeCompare(t.id)),n.map(e=>e.n)},u=e=>t=>o.get(t)===e;for(let t=0;t(i.get(e)??[]).filter(u(t-1))),c();for(let t=e.length-2;t>=0;t--)e[t]=l(e[t],e=>(a.get(e)??[]).filter(u(t+1))),c()}let d=Math.max(...e.map(e=>e.length),1);return e.forEach((e,t)=>{let r=(d-e.length)*92/2;e.forEach((e,i)=>{n.set(e.id,{x:t*296,y:r+i*92})})}),n}function vp(e,t){let n=new Set(e.map(e=>e.id)),r=Math.max(e.length-1,0),i=new Map;for(let t of e)i.set(t.id,0);for(let a=0;a(i.get(a.dst)||0)&&(i.set(a.dst,t),e=!0)}if(!e)break}let a=new Map;for(let t of e){let e=i.get(t.id)||0,n=a.get(e)??[];n.push(t),a.set(e,n)}return _p([...a.keys()].sort((e,t)=>e-t).map(e=>(a.get(e)??[]).sort(pp)),t)}function yp(e,t){let n=new Map;if(!e.length)return n;let r=new Set(e.map(e=>e.id)),i=new Map,a=new Map;for(let t of e)i.set(t.id,[]),a.set(t.id,0);for(let e of t)!r.has(e.src)||!r.has(e.dst)||e.src===e.dst||(i.get(e.src).push(e.dst),i.get(e.dst).push(e.src),a.set(e.src,(a.get(e.src)||0)+1),a.set(e.dst,(a.get(e.dst)||0)+1));let o=[...e].sort((e,t)=>(a.get(t.id)||0)-(a.get(e.id)||0)||pp(e,t))[0]??e[0],s=new Map,c=[[o]];s.set(o.id,0);let l=[o];for(;l.length;){let t=l.shift(),n=s.get(t.id)||0,r=(i.get(t.id)??[]).map(t=>e.find(e=>e.id===t)).filter(e=>!!e).sort(pp);for(let e of r){if(s.has(e.id))continue;s.set(e.id,n+1);let t=c[n+1]??[];t.push(e),c[n+1]=t,l.push(e)}}let u=e.filter(e=>!s.has(e.id)).sort(pp);return u.length&&c.push(u),c.forEach((e,t)=>{if(t===0&&e.length===1){n.set(e[0].id,{x:0,y:0});return}let r=Math.max(t*296,e.length<=1?208:e.length*240/(2*Math.PI));e.forEach((t,i)=>{let a=-Math.PI/2+2*Math.PI*i/e.length;n.set(t.id,{x:Math.cos(a)*r,y:Math.sin(a)*r})})}),n}function bp(e){let t=new Map,n=[...e].sort((e,t)=>xf(e.type)-xf(t.type)||pp(e,t)),r=Math.max(1,Math.ceil(Math.sqrt(n.length)));return n.forEach((e,n)=>{t.set(e.id,{x:n%r*296,y:Math.floor(n/r)*92})}),t}function xp(e){let t=new Map,n=[...e].sort(mp);return n.length<=1?(n[0]&&t.set(n[0].id,{x:0,y:0}),t):(hp(n,gp(n.length,1),t),t)}function Sp(e){let t=new Map;if(!e.length)return t;let n=new Map;for(let t of e){let e=xf(t.type),r=n.get(e)??[];r.push(t),n.set(e,r)}return[...n.keys()].sort((e,t)=>e-t).forEach((e,r)=>{let i=(n.get(e)??[]).sort(pp);if(r===0&&i.length===1){t.set(i[0].id,{x:0,y:0});return}hp(i,gp(i.length,r===0?1:r),t)}),t}function Cp(e){let t=new Map;if(!e.length)return t;let n=new Map;for(let t of e){let e=n.get(t.type)??[];e.push(t),n.set(t.type,e)}let r=[...n.keys()].sort((e,t)=>xf(e)-xf(t)||e.localeCompare(t)).map(e=>{let t=(n.get(e)??[]).sort(pp),r=Math.max(1,Math.ceil(Math.sqrt(t.length))),i=Math.ceil(t.length/r);return{members:t,cols:r,width:Math.max(0,r-1)*jf,height:Math.max(0,i-1)*Mf}}),i=Math.max(...r.map(e=>Math.hypot(e.width,e.height)/2+208),208),a=r.length<=1?0:Math.max(jf,r.length*(i*2+88)/(2*Math.PI));return r.forEach((e,n)=>{let i=r.length===1?0:-Math.PI/2+2*Math.PI*n/r.length,o=Math.cos(i)*a,s=Math.sin(i)*a;e.members.forEach((n,r)=>{let i=r%e.cols,a=Math.floor(r/e.cols);t.set(n.id,{x:o-e.width/2+i*jf,y:s-e.height/2+a*Mf})})}),t}function wp(e,t){let n=new Map;if(!e.length)return n;let r=new Map(e.map(e=>[e.id,e])),i=new Set(r.keys()),a=new Map,o=new Map;for(let t of e)a.set(t.id,[]),o.set(t.id,0);for(let e of t)!i.has(e.src)||!i.has(e.dst)||e.src===e.dst||(a.get(e.src).push(e.dst),o.set(e.dst,(o.get(e.dst)||0)+1));for(let[e,t]of a){let n=[...new Set(t)];n.sort((e,t)=>pp(r.get(e),r.get(t))),a.set(e,n)}let s=e.filter(e=>(o.get(e.id)||0)===0).sort(pp);if(!s.length){let t=[...e].sort((e,t)=>(a.get(t.id)?.length||0)-(a.get(e.id)?.length||0)||pp(e,t))[0];s.push(t)}let c=new Set,l=new Map;for(let t of e)l.set(t.id,[]);let u=e=>{c.add(e);for(let t of a.get(e)??[])c.has(t)||(l.get(e).push(t),u(t))};for(let e of s)c.has(e.id)||u(e.id);for(let t of[...e].sort(pp))c.has(t.id)||(s.push(t),u(t.id));let d=0,f=(e,t)=>{let r=l.get(e)??[];if(!r.length){n.set(e,{x:d*jf,y:t*Mf}),d+=1;return}let i=d;for(let e of r)f(e,t+1);n.set(e,{x:(i+d-1)/2*jf,y:t*Mf})};for(let e of s)n.has(e.id)||f(e.id,0);return n}function Tp(e,t){for(let n=0;n<8;n++)for(let n=0;ne.id)),s=[],c=new Set;for(let e of t){if(!o.has(e.src)||!o.has(e.dst)||e.src===e.dst)continue;let t=e.src[e.id,e])),i=[];Ap.has(e.type)&&i.push(`sink`),jp.has(e.type)&&i.push(`contract`);let a=e.extra??{};a.inferred&&i.push(`inferred`),a.generated&&i.push(`generated`),a.mutation&&i.push(`mutation`),a.fbv&&i.push(`function view`),a.ninja&&i.push(`ninja`),a.ninja_schema&&i.push(`ninja schema`),a.next_app&&i.push(`app router`),a.typed_client&&i.push(String(a.typed_client)),a.e2e&&i.push(`e2e`),a.filterset===!0&&i.push(`filterset`);let o=n.filter(t=>t.dst===e.id),s=n.filter(t=>t.src===e.id),c=o.slice(0,Op).map(e=>Hp(e,r,e.src)),l=s.slice(0,Op).map(e=>Hp(e,r,e.dst)),u=e.file_path?`${e.file_path}${e.start_line?`:${e.start_line}`:``}`:void 0,d={type:e.type,typeLabel:k(j(e.type)),layer:Uf[xf(e.type)]??`other`,purpose:Rp(e.type),name:e.name,qualifiedName:e.qualified_name,file:u,context:e.context,roles:i,facts:Up(a).filter(t=>t.key!==`app`||t.value!==e.context),inputs:c,outputs:l,extraInputs:Math.max(0,o.length-Op),extraOutputs:Math.max(0,s.length-Op),degreeIn:o.length,degreeOut:s.length,inputKinds:Bp(o.map(e=>Hp(e,r,e.src))),outputKinds:Bp(s.map(e=>Hp(e,r,e.dst))),pathSummary:``};return d.pathSummary=Vp(d),d}function Bp(e){let t=new Map;for(let n of e){let e=n.edgeLabel||n.edgeType.replaceAll(`_`,` `);t.set(e,(t.get(e)||0)+1)}return[...t.entries()].sort((e,t)=>t[1]-e[1]||e[0].localeCompare(t[0])).map(([e,t])=>({label:e,count:t}))}function Vp(e){let t=e.inputKinds.map(e=>`${e.label} ×${e.count}`).join(`, `),n=e.outputKinds.map(e=>`${e.label} ×${e.count}`).join(`, `);return t&&n?`${t} → this → ${n}`:n?`this → ${n}`:t?`${t} → this`:``}function Hp(e,t,n){let r=t.get(n),i=n.includes(`:`)?n.slice(n.indexOf(`:`)+1):n;return{id:n,name:r?.name||i,type:r?.type||``,typeLabel:r?k(j(r.type)):``,edgeType:e.type,edgeLabel:k(e.type),inferred:e.confidence<.8}}function Up(e){let t=[...Pp.filter(t=>t in e),...Object.keys(e).filter(e=>!Pp.includes(e)&&!Fp.has(e))],n=[],r=new Set;for(let i of t){if(r.has(i)||Fp.has(i)||Lp.has(i))continue;r.add(i);let t=Wp(i,e[i]);t!=null&&n.push({key:i,label:Np[i]??k(i),value:t})}return n}function Wp(e,t){if(t==null)return null;if(typeof t==`boolean`)return!t&&!Ip.has(e)?null:t?`yes`:`no`;if(typeof t==`number`)return String(t);if(typeof t==`string`)return t.trim()||null;if(Array.isArray(t)){if(t.some(e=>e&&typeof e==`object`))return Gp(e,t);let n=t.map(e=>typeof e==`string`||typeof e==`number`?String(e):``).filter(Boolean);if(!n.length)return null;let r=n.slice(0,kp),i=n.length-r.length;return i>0?`${r.join(`, `)} +${i} more`:r.join(`, `)}return null}function Gp(e,t){let n=t.slice(0,4).map(t=>{if(e===`nplusone`){let e=String(t.queryset||`queryset`),n=Array.isArray(t.accessed)?t.accessed.join(`.`):``,r=t.line?` L${t.line}`:``;return n?`${e} → ${n}${r}`:`${e}${r}`}if(e===`lookups`){let e=Array.isArray(t.fields)?t.fields.join(`, `):``,n=String(t.kind||`filter`);return e?`${n} ${e}`:n}return Object.entries(t).filter(([,e])=>e!=null&&(typeof e==`string`||typeof e==`number`)).slice(0,3).map(([e,t])=>`${e}=${t}`).join(` `)});if(!n.some(Boolean))return null;let r=t.length-n.length;return r>0?`${n.join(`; `)} +${r} more`:n.join(`; `)}var Kp=12,qp=.2,Jp=20,Yp=64;function Xp(e,t,n){let r=n??wf(e,t),i=[...new Set([...r.values()].map(e=>e.x))].sort((e,t)=>e-t),a=[];for(let e of t){let t=r.get(e.src),n=r.get(e.dst);if(!t||!n)continue;let i=t.y+32,o=n.y+32;if(Math.abs(i-o)e.y0-t.y0||e.y1-t.y1||e.id.localeCompare(t.id)),n=$p(t),r=Math.max(0,...n.values())+1,a=t[0].sourceX,o=Zp(i,a);for(let e of t){let t=em(n.get(e.id)??0,r),i=a+Jp+Math.max(1,o-40)*t;s.set(e.id,Qp(e.sourceX,e.targetX,i))}}return s}function Zp(e,t){let n=t-208,r=e.find(e=>e>n+1);return r===void 0?88:Math.max(88,r-t)}function Qp(e,t,n){let r=t-e-40;return r<1?.5:Math.min(1,Math.max(0,(n-e-Jp)/r))}function $p(e){let t=[],n=new Map;for(let r of e){let e=-1;for(let n=0;nt[n]+Yp){e=n;break}e<0?(e=t.length,t.push(r.y1)):t[e]=Math.max(t[e],r.y1),n.set(r.id,e)}return n}function em(e,t){return t<=1?.5:qp+.6000000000000001*e/(t-1)}var tm=`modulepreload`,nm=function(e,t){return new URL(e,t).href},rm={},im=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?import.meta.resolve(e):new URL(e,import.meta.url).href}r=o(t.map(t=>{if(t=nm(t,n),t=s(t),t in rm)return;rm[t]=!0;let r=t.endsWith(`.css`);for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}let i=document.createElement(`link`);if(i.rel=r?`stylesheet`:tm,r||(i.as=`script`),i.crossOrigin=``,i.href=t,a&&i.setAttribute(`nonce`,a),document.head.appendChild(i),r)return new Promise((e,n)=>{i.addEventListener(`load`,e),i.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},am=new Set,om=(0,_.lazy)(()=>im(()=>import(`./LayeredGraph3D-kVQDQ1-J.js`).then(e=>({default:e.LayeredGraph3D})),[],import.meta.url)),sm=class extends _.Component{state={failed:!1};static getDerivedStateFromError(){return{failed:!0}}render(){return this.state.failed?this.props.fallback:this.props.children}},cm=(0,T.jsx)(`p`,{className:`muted graph-3d-hint`,"data-testid":`graph-3d-fallback`,children:`WebGL is unavailable in this browser, so the 3D view cannot start. Switch back to 2D map.`}),lm={cheap:`var(--edge-cheap)`,expensive:`var(--edge-expensive)`,critical:`var(--edge-critical)`},um={n:W.Top,e:W.Right,s:W.Bottom,w:W.Left};function dm(e,t){let n=t.x-e.x,r=t.y-e.y;return Math.abs(n)>=Math.abs(r)?n>=0?{source:`e`,target:`w`}:{source:`w`,target:`e`}:r>=0?{source:`s`,target:`n`}:{source:`n`,target:`s`}}function fm({data:e,selected:t}){let n=(e.roles||[]).map(e=>`role-${e}`).join(` `);return(0,T.jsxs)(`div`,{className:[`lp-node`,t?`selected`:``,e.dim?`dim`:``,n].filter(Boolean).join(` `),children:[[`n`,`e`,`s`,`w`].map(e=>(0,T.jsx)(au,{id:`tgt-${e}`,type:`target`,position:um[e],isConnectable:!1},`tgt-${e}`)),(0,T.jsx)(`div`,{className:`t`,children:j(e.type)}),(0,T.jsx)(`div`,{className:`n`,title:e.name,children:N(e.name)}),[`n`,`e`,`s`,`w`].map(e=>(0,T.jsx)(au,{id:`src-${e}`,type:`source`,position:um[e],isConnectable:!1},`src-${e}`))]})}var pm={load:fm},mm=new Set([`django`,`react`,`stitch`,`arch`]);function hm({id:e,sourceX:t,sourceY:n,targetX:r,targetY:i,sourcePosition:a,targetPosition:o,style:s,markerEnd:c,markerStart:l,label:u,labelStyle:d,labelShowBg:f,labelBgStyle:p,labelBgPadding:m,labelBgBorderRadius:h,data:g,interactionWidth:_}){let[v,y,b]=ss({sourceX:t,sourceY:n,sourcePosition:a,targetX:r,targetY:i,targetPosition:o,borderRadius:8,stepPosition:g?.stepPosition??.5});return(0,T.jsx)(zu,{id:e,path:v,labelX:y,labelY:b,label:u,labelStyle:d,labelShowBg:f,labelBgStyle:p,labelBgPadding:m,labelBgBorderRadius:h,style:s,markerEnd:c,markerStart:l,interactionWidth:_})}var gm={loadstep:hm};function _m({topologyKey:e}){let{fitView:t}=Il();return(0,_.useEffect)(()=>{let e=0,n=requestAnimationFrame(()=>{e=requestAnimationFrame(()=>{t({padding:.2,maxZoom:1.15})})});return()=>{cancelAnimationFrame(n),cancelAnimationFrame(e)}},[t,e]),null}function vm(e,t,n=null,r={}){let i=new Map(e.map(e=>[e.id,e])),a=r.layout??`layers`,o=dp(a),s=Dp(e,t,a),c=Xp(e,t,s);return{rfNodes:e.map(e=>{let t=r.roles?.[e.id]||[],i=!!r.testOverlay&&!t.includes(`tested`)&&!t.includes(`untested`)&&!t.includes(`test`)&&!t.includes(`seed`);return{id:e.id,type:`load`,position:s.get(e.id)??{x:0,y:0},data:{name:e.name,type:e.type,file:e.file_path,roles:t,dim:i},selected:n===e.id,sourcePosition:W.Right,targetPosition:W.Left,width:208,height:64,style:{width:208,height:64}}}),rfEdges:t.filter(e=>i.has(e.src)&&i.has(e.dst)).map(e=>{let t=lm[e.weight]||`var(--edge-cheap)`,r=!!(n&&(e.src===n||e.dst===n)),i=s.get(e.src)??{x:0,y:0},a=s.get(e.dst)??{x:0,y:0},l=o?{source:`e`,target:`w`}:dm(i,a);return{id:e.id,source:e.src,target:e.dst,sourceHandle:`src-${l.source}`,targetHandle:`tgt-${l.target}`,sourcePosition:um[l.source],targetPosition:um[l.target],type:o?`loadstep`:`default`,animated:e.weight===`critical`,data:{stepPosition:c.get(e.id)??.5},style:{stroke:t,strokeWidth:e.weight===`critical`?2.4:1.2,strokeDasharray:e.confidence<.8?`6 4`:void 0},markerEnd:{type:Ka.ArrowClosed,width:14,height:14,color:t},label:r?e.type.replaceAll(`_`,` `):void 0,labelStyle:r?{fill:`var(--ink)`,fontSize:10,fontWeight:600}:void 0,labelBgStyle:r?{fill:`var(--graph-bg)`,fillOpacity:.92}:void 0,labelBgPadding:r?[3,5]:void 0,labelBgBorderRadius:r?4:void 0}})}}function ym({node:e,nodes:t,edges:n,onClose:r,onWhatIf:i,onSelect:a,onOpenFile:o,pinned:s,onPin:c,onIsolate:l}){let u=zp(e,t,n);return(0,_.useEffect)(()=>{let e=e=>{e.key===`Escape`&&r()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[r]),(0,T.jsxs)(`aside`,{className:`inspector`,"data-testid":`graph-inspector`,children:[(0,T.jsxs)(`div`,{className:`inspector-head`,children:[(0,T.jsx)(`div`,{className:`t`,children:u.typeLabel}),(0,T.jsx)(`div`,{className:`inspector-roles`,children:u.roles.map(e=>(0,T.jsx)(`span`,{className:`inspector-chip`,children:e},e))}),(0,T.jsx)(`button`,{type:`button`,className:`inspector-close`,"data-testid":`graph-inspector-close`,"aria-label":`Close inspector`,onClick:r,children:`×`})]}),(0,T.jsx)(`div`,{className:`n`,children:N(u.name)}),(0,T.jsx)(`p`,{className:`inspector-purpose`,"data-testid":`graph-inspector-purpose`,children:u.purpose}),u.context?(0,T.jsx)(`div`,{className:`muted`,children:N(u.context)}):null,u.file?(0,T.jsxs)(`div`,{className:`file-row`,children:[(0,T.jsx)(`div`,{className:`file`,children:N(u.file)}),o&&e.file_path?(0,T.jsx)(`button`,{type:`button`,className:`btn`,"data-testid":`btn-open-editor`,onClick:()=>o(e.file_path,e.start_line),children:`Open in editor`}):null]}):null,(0,T.jsx)(`div`,{className:`muted`,children:N(u.qualifiedName)}),(0,T.jsxs)(`div`,{className:`muted inspector-layer`,children:[`layer · `,u.layer]}),(0,T.jsxs)(`div`,{className:`muted inspector-degree`,"data-testid":`graph-inspector-degree`,children:[u.degreeIn,` in · `,u.degreeOut,` out`]}),u.pathSummary?(0,T.jsx)(`p`,{className:`inspector-path`,"data-testid":`graph-inspector-path`,children:u.pathSummary}):null,u.facts.length?(0,T.jsx)(`dl`,{className:`inspector-facts`,"data-testid":`graph-inspector-facts`,children:u.facts.map(e=>(0,T.jsxs)(`div`,{className:`inspector-fact`,children:[(0,T.jsx)(`dt`,{children:e.label}),(0,T.jsx)(`dd`,{children:N(e.value)})]},e.key))}):null,(0,T.jsx)(bm,{title:`Inputs`,testId:`graph-inspector-inputs`,links:u.inputs,extra:u.extraInputs,empty:`Nothing in this graph points here.`,onSelect:a}),(0,T.jsx)(bm,{title:`Outputs`,testId:`graph-inspector-outputs`,links:u.outputs,extra:u.extraOutputs,empty:`This node does not point at anything in this graph.`,onSelect:a}),i?(0,T.jsx)(`p`,{className:`whatif-hint`,"data-testid":`whatif-hint`,children:l?`Walks a new path from this node with no git range. Isolate (next) only hides the rest of this map.`:`Walks a new path from this node with no git range — as if this changed, regardless of Base/Head.`}):null,(0,T.jsxs)(`div`,{className:`btn-row`,children:[i?(0,T.jsx)(`button`,{type:`button`,className:`btn`,"data-testid":`btn-whatif`,title:`Start a hypothetical walk from this node. Does not use Base/Head.`,onClick:()=>i(e.id),children:`What if this changes`}):null,l?(0,T.jsx)(`button`,{type:`button`,className:`btn`,"data-testid":`btn-isolate`,title:`Hide nodes that are not on a path from here to a sink. Does not start a new walk.`,onClick:()=>l(e.id),children:`Isolate path to sinks`}):null,c?(0,T.jsx)(`button`,{type:`button`,className:s?`btn primary`:`btn`,"data-testid":`btn-pin-node`,onClick:()=>c(s?null:e.id),children:s?`Unpin`:`Pin`}):null]})]})}function bm({title:e,testId:t,links:n,extra:r,empty:i,onSelect:a}){return(0,T.jsxs)(`section`,{className:`inspector-section`,"data-testid":t,children:[(0,T.jsxs)(`h3`,{children:[e,(0,T.jsx)(`span`,{className:`count`,children:n.length+r})]}),n.length?(0,T.jsx)(`ul`,{children:n.map((e,t)=>(0,T.jsx)(`li`,{children:a?(0,T.jsxs)(`button`,{type:`button`,className:`inspector-link`,onClick:()=>a(e.id),children:[(0,T.jsx)(`span`,{className:`inspector-link-name`,title:e.name,children:N(e.name)}),(0,T.jsxs)(`span`,{className:`inspector-link-meta`,children:[e.typeLabel?`${e.typeLabel} · `:``,e.edgeLabel,e.inferred?` · inferred`:``]})]}):(0,T.jsxs)(T.Fragment,{children:[(0,T.jsx)(`span`,{className:`inspector-link-name`,title:e.name,children:N(e.name)}),(0,T.jsxs)(`span`,{className:`inspector-link-meta`,children:[e.typeLabel?`${e.typeLabel} · `:``,e.edgeLabel,e.inferred?` · inferred`:``]})]})},`${e.edgeType}:${e.id}:${t}`))}):(0,T.jsx)(`p`,{className:`muted`,children:i}),r?(0,T.jsxs)(`p`,{className:`muted`,children:[`+`,r,` more`]}):null]})}function xm({nodes:e,edges:t,onWhatIf:n,focusPath:r,selectedId:i,onSelect:a,nodeRoles:o,testOverlay:s=!1,isolateSource:c,onIsolate:l,repoPath:u,onOpenFile:d,pinnedId:f,onPin:p}){let[m,h]=(0,_.useState)(null),g=i===void 0?m:i,v=e=>{i===void 0&&h(e),a?.(e)},[y,b]=(0,_.useState)(null),[x,S]=(0,_.useState)(null),[C,w]=(0,_.useState)(()=>lp()),[E,D]=(0,_.useState)(new Set(mm)),[O,k]=(0,_.useState)(!1),[A,M]=(0,_.useState)(``),[ee,N]=(0,_.useState)(!1),[P,F]=(0,_.useState)(null),I=typeof window<`u`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches;(0,_.useEffect)(()=>{let e=()=>F(Pf());if(typeof window.requestIdleCallback==`function`){let t=window.requestIdleCallback(e);return()=>window.cancelIdleCallback(t)}let t=window.setTimeout(e,0);return()=>window.clearTimeout(t)},[]);let te=Ff(y??Kf(e.length),y,P),ne=x??qf(e.length),L=O?g:null,re=(0,_.useMemo)(()=>c?Zf(e,t,c):null,[e,t,c]),R=re?e.filter(e=>re.nodeIds.has(e.id)):e,z=re?t.filter(e=>re.edgeIds.has(e.id)):t,B=(0,_.useMemo)(()=>Yf(R,z,{detail:ne,families:E,focusId:L,neighborhoodOnly:!!L}),[R,z,ne,E,L]),V=(0,_.useMemo)(()=>`${C}|${B.nodes.map(e=>e.id).join(`\0`)}|${B.edges.map(e=>e.id).join(`\0`)}`,[C,B.nodes,B.edges]),ie=g?e.find(e=>e.id===g)??null:null,{rfNodes:ae,rfEdges:oe}=(0,_.useMemo)(()=>{let e=vm(B.nodes,B.edges,g,{roles:o,testOverlay:s,layout:C});return I&&(e.rfEdges=e.rfEdges.map(e=>({...e,animated:!1}))),e},[B.nodes,B.edges,g,I,o,s,C]);(0,_.useEffect)(()=>{if(!r)return;let t=e.find(e=>e.file_path===r);t&&v(t.id)},[r,e]);let se=(0,_.useMemo)(()=>Xf(e,A),[e,A]),ce=(e,t)=>{v(t.id)},le=()=>{v(null),k(!1)},ue=ie?(0,T.jsx)(ym,{node:ie,nodes:e,edges:t,onClose:le,onWhatIf:n,onSelect:v,onOpenFile:d,pinned:f===ie.id,onPin:p,onIsolate:l?e=>{l(c===e?null:e)}:void 0}):null,de=e=>{D(t=>{let n=new Set(t);if(n.has(e)){if(n.size===1)return t;n.delete(e)}else n.add(e);return n})},fe=(0,_.useMemo)(()=>{let t=new Set;for(let n of e)t.add(Wf(n.type));return t},[e]),pe=e.length-B.nodes.length;return(0,T.jsxs)(`div`,{className:`impact-graph`,style:{flex:1,minHeight:0,position:`relative`,display:`flex`,flexDirection:`column`},children:[(0,T.jsxs)(`div`,{className:`graph-toolbar`,"data-testid":`graph-toolbar`,children:[(0,T.jsxs)(`div`,{className:`seg`,"aria-label":`Graph projection`,children:[(0,T.jsx)(`button`,{type:`button`,"data-testid":`graph-view-2d`,className:te===`2d`?`active`:``,"aria-pressed":te===`2d`,onClick:()=>b(`2d`),children:`2D map`}),(0,T.jsx)(`button`,{type:`button`,"data-testid":`graph-view-3d`,className:te===`3d`?`active`:``,"aria-pressed":te===`3d`,onClick:()=>b(`3d`),children:`3D layers`})]}),(0,T.jsxs)(`div`,{className:`seg`,"aria-label":`Graph detail`,children:[(0,T.jsx)(`button`,{type:`button`,"data-testid":`graph-detail-overview`,className:ne===`overview`?`active`:``,"aria-pressed":ne===`overview`,onClick:()=>S(`overview`),children:`Overview`}),(0,T.jsx)(`button`,{type:`button`,"data-testid":`graph-detail-full`,className:ne===`full`?`active`:``,"aria-pressed":ne===`full`,onClick:()=>S(`full`),children:`Full`})]}),(0,T.jsx)(`div`,{className:`seg`,"aria-label":`Graph families`,children:[`django`,`stitch`,`react`].filter(e=>fe.has(e)).map(e=>(0,T.jsx)(`button`,{type:`button`,"data-testid":`graph-family-${e}`,className:E.has(e)?`active`:``,"aria-pressed":E.has(e),onClick:()=>de(e),children:e},e))}),(0,T.jsxs)(`label`,{className:`graph-layout`,children:[`Layout`,(0,T.jsx)(`select`,{id:`graph-layout`,"data-testid":`graph-layout`,value:C,"aria-label":`Graph layout algorithm`,onChange:e=>{let t=Tf.find(t=>t.id===e.target.value)?.id;t&&(w(t),up(t))},children:Tf.map(e=>(0,T.jsx)(`option`,{value:e.id,children:e.label},e.id))})]}),(0,T.jsx)(`button`,{type:`button`,className:O?`chip-btn active`:`chip-btn`,"data-testid":`graph-neighborhood`,disabled:!g,onClick:()=>k(e=>!e),children:O?`Neighborhood`:`Focus neighbors`}),c?(0,T.jsx)(`button`,{type:`button`,className:`chip-btn active`,"data-testid":`graph-isolate-clear`,onClick:()=>l?.(null),children:`Path isolate`}):null,(0,T.jsxs)(`label`,{className:`graph-search`,children:[(0,T.jsx)(`span`,{className:`sr-only`,children:`Search nodes`}),(0,T.jsx)(`input`,{"data-testid":`graph-search`,placeholder:`Find a node`,value:A,onChange:e=>{M(e.target.value),N(!0)},onFocus:()=>N(!0),onBlur:()=>window.setTimeout(()=>N(!1),150)}),ee&&A.trim()&&se.length?(0,T.jsx)(`ul`,{className:`graph-search-hits`,"data-testid":`graph-search-hits`,children:se.map(e=>(0,T.jsx)(`li`,{children:(0,T.jsxs)(`button`,{type:`button`,onMouseDown:e=>e.preventDefault(),onClick:()=>{v(e.id),M(``),N(!1)},children:[e.name,(0,T.jsx)(`span`,{className:`muted`,children:j(e.type)})]})},e.id))}):null]}),(0,T.jsxs)(`span`,{className:`muted graph-count`,children:[B.nodes.length,` nodes · `,B.edges.length,` edges`,pe?` · ${pe} hidden`:``]})]}),(0,T.jsx)(`div`,{className:`graph-stage`,children:e.length===0?(0,T.jsxs)(`div`,{className:`empty graph-walk-empty`,"data-testid":`graph-walk-empty`,children:[(0,T.jsx)(`h2`,{children:`No typed nodes on this walk`}),(0,T.jsx)(`p`,{children:`This range did not hit models, views, routes, or React pages Loadpath extracts. Open the architecture map for the indexed graph.`})]}):te===`3d`?(0,T.jsxs)(`div`,{className:`graph-3d`,"data-testid":`graph-3d`,children:[(0,T.jsx)(`p`,{className:`graph-3d-hint`,children:`Same layout as the 2D map, with bounded context on the depth axis. Dashed edges are inferred. Drag to orbit, scroll to zoom, click a node to inspect it.`}),P===!1?cm:P===null?(0,T.jsx)(`p`,{className:`muted graph-3d-hint`,children:`Loading 3D layers…`}):(0,T.jsx)(sm,{fallback:cm,children:(0,T.jsx)(_.Suspense,{fallback:(0,T.jsx)(`p`,{className:`muted graph-3d-hint`,children:`Loading 3D layers…`}),children:(0,T.jsx)(om,{nodes:B.nodes,edges:B.edges,selectedId:g,neighborIds:L?B.neighborIds:am,layout:C,nodeRoles:o,testOverlay:s,onSelect:e=>{v(e),e||k(!1)}})})}),ue]}):(0,T.jsxs)(Md,{children:[(0,T.jsxs)(Id,{nodes:ae,edges:oe,nodeTypes:pm,edgeTypes:gm,fitView:!1,minZoom:.25,nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!0,deleteKeyCode:null,onNodeClick:ce,onPaneClick:le,proOptions:{hideAttribution:!1},"data-testid":`impact-graph`,children:[(0,T.jsx)(_m,{topologyKey:V}),(0,T.jsx)(Ud,{}),(0,T.jsx)(gf,{pannable:!0,zoomable:!0,ariaLabel:`Impact graph overview`,nodeColor:`var(--muted)`,nodeStrokeColor:`transparent`,nodeStrokeWidth:0,maskColor:`rgba(0, 0, 0, 0.45)`,maskStrokeColor:`var(--accent)`,maskStrokeWidth:1.4,bgColor:`var(--graph-bg)`,style:{width:184,height:128}}),(0,T.jsx)(Qd,{})]}),ue]})})]})}function Sm(e){return(0,T.jsx)(sm,{fallback:(0,T.jsx)(`p`,{className:`muted graph-3d-hint`,"data-testid":`graph-crash-fallback`,children:`The graph failed to render. Switch to 2D map or another layout.`}),children:(0,T.jsx)(xm,{...e})})}function Cm(){let e=localStorage.getItem(`loadpath.editor`)||`auto`;return e===`cursor`||e===`vscode`||e===`system`?e:`auto`}function wm(e){localStorage.setItem(`loadpath.editor`,e)}async function Tm(e,t,n,r=Cm()){try{let i=await S.openEditor(e,t,n??void 0,r);if(i.ok)return{ok:!0,message:`Opened ${t} in ${i.opened_with||`editor`}`};let a=i.urls||{},o=r===`vscode`?a.vscode:r===`cursor`?a.cursor:a.cursor||a.vscode;return o?(window.open(o,`_blank`,`noopener,noreferrer`),{ok:!0,message:`Opening ${t} via editor URL`}):{ok:!1,message:i.error||`Could not open editor`}}catch(e){return{ok:!1,message:e instanceof Error?e.message:String(e)}}}var Em=[{value:`HEAD`,label:`HEAD`,group:`preset`},{value:`HEAD~1`,label:`HEAD~1`,group:`preset`}],Dm=[`preset`,`branch`,`tag`,`commit`];function Om(e){if(!e?.git)return[...Em];let t=(e.presets?.length?e.presets:Em.map(e=>e.value)).map(e=>({value:e,label:e,group:`preset`})),n=new Set(t.map(e=>e.value)),r=[...t];for(let t of e.branches||[])n.has(t.name)||(n.add(t.name),r.push({value:t.name,label:t.current?`${t.name} (current)`:t.name,detail:t.subject,group:`branch`}));for(let t of e.tags||[])n.has(t.name)||(n.add(t.name),r.push({value:t.name,label:t.name,detail:t.subject,group:`tag`}));for(let t of e.commits||[])n.has(t.sha)||(n.add(t.sha),r.push({value:t.sha,label:t.short,detail:t.subject,group:`commit`}));return r}function km(e,t){let n=t.trim().toLowerCase();return n?e.filter(e=>e.value.toLowerCase().includes(n)||e.label.toLowerCase().includes(n)||(e.detail||``).toLowerCase().includes(n)):e}function Am(e){return Dm.map(t=>({group:t,items:e.filter(e=>e.group===t)})).filter(e=>e.items.length>0)}function jm(e){return e===`preset`?`Common`:e===`branch`?`Branches`:e===`tag`?`Tags`:`Recent commits`}function Mm({value:e,onChange:t,placeholder:n,testId:r,menuTestId:i,refs:a,onNeedRefs:o}){let s=(0,_.useId)(),c=(0,_.useRef)(null),[l,u]=(0,_.useState)(!1),[d,f]=(0,_.useState)(null),[p,m]=(0,_.useState)(0),h=(0,_.useMemo)(()=>{let e=Om(a);return d===null?e:km(e,d)},[a,d]),g=(0,_.useMemo)(()=>Am(h),[h]);(0,_.useEffect)(()=>{l&&o()},[l,o]),(0,_.useEffect)(()=>{m(0)},[d,l]);let v=()=>{u(!1),f(null)},y=e=>{t(e.value),v()};return(0,T.jsxs)(`div`,{className:`combo`,ref:c,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||v()},children:[(0,T.jsxs)(`div`,{className:`combo-row`,children:[(0,T.jsx)(`input`,{"data-testid":r,value:e,placeholder:n,spellCheck:!1,role:`combobox`,"aria-expanded":l,"aria-controls":s,"aria-autocomplete":`list`,onChange:e=>{t(e.target.value),l&&f(e.target.value)},onKeyDown:e=>{if(e.key===`ArrowDown`){if(e.preventDefault(),!l){u(!0);return}m(e=>Math.min(e+1,Math.max(h.length-1,0)))}else if(e.key===`ArrowUp`){if(e.preventDefault(),!l)return;m(e=>Math.max(e-1,0))}else if(e.key===`Enter`&&l){e.preventDefault();let t=h[p];t&&y(t)}else e.key===`Escape`&&l&&(e.preventDefault(),v())}}),(0,T.jsx)(`button`,{type:`button`,className:`icon-btn combo-toggle`,"data-testid":`${r}-toggle`,"aria-label":`Show recent refs`,"aria-expanded":l,onMouseDown:e=>e.preventDefault(),onClick:()=>l?v():u(!0),children:(0,T.jsx)(R,{})})]}),l?(0,T.jsx)(`div`,{className:`combo-menu`,id:s,role:`listbox`,"data-testid":i,children:g.length===0?(0,T.jsx)(`div`,{className:`combo-empty muted`,children:`No matching refs — the typed value is kept`}):g.map(e=>(0,T.jsxs)(`div`,{className:`combo-group`,children:[(0,T.jsx)(`div`,{className:`combo-heading`,children:jm(e.group)}),e.items.map(e=>{let t=h.indexOf(e);return(0,T.jsxs)(`button`,{type:`button`,role:`option`,"aria-selected":t===p,className:t===p?`combo-option active`:`combo-option`,"data-testid":`ref-option-${e.group}`,onMouseDown:e=>e.preventDefault(),onMouseEnter:()=>m(t),onClick:()=>y(e),children:[(0,T.jsx)(`span`,{className:`combo-label`,children:e.label}),e.detail?(0,T.jsx)(`span`,{className:`combo-detail`,children:e.detail}):null]},`${e.group}:${e.value}`)})]},e.group))}):null]})}function Nm({initialPath:e,onSelect:t,onClose:n}){let[r,i]=(0,_.useState)(null),[a,o]=(0,_.useState)(e),[s,c]=(0,_.useState)(null),[l,u]=(0,_.useState)(``),[d,f]=(0,_.useState)(!1),p=(0,_.useRef)(null),m=(0,_.useRef)(0),h=async e=>{let t=m.current+1;m.current=t,f(!0);try{let n=await S.browse(e);if(m.current!==t)return;i(n),o(n.path),c(n.is_git?n.path:null),u(``)}catch(e){if(m.current!==t)return;u(e instanceof Error?e.message:String(e))}finally{m.current===t&&f(!1)}};(0,_.useEffect)(()=>{h(e),p.current?.focus(),p.current?.select()},[e]);let g=s||r?.path||a,v=s&&s!==r?.path?s.split(/[\\/]/).filter(Boolean).pop():r?.is_git?`this repository`:`this folder`;return(0,T.jsx)(`div`,{className:`modal-backdrop`,"data-testid":`repo-explorer`,"data-overlay":`true`,onClick:n,onKeyDown:e=>{e.key===`Escape`&&(e.preventDefault(),n())},children:(0,T.jsxs)(`div`,{className:`modal`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`explorer-title`,onClick:e=>e.stopPropagation(),children:[(0,T.jsxs)(`div`,{className:`modal-head`,children:[(0,T.jsxs)(`div`,{children:[(0,T.jsx)(`h2`,{id:`explorer-title`,children:`Select repository`}),(0,T.jsx)(`p`,{className:`muted`,children:`Browse to a git root, or paste the full path.`})]}),(0,T.jsx)(`button`,{type:`button`,className:`btn ghost`,"data-testid":`explorer-cancel`,onClick:n,children:`Cancel`})]}),(0,T.jsxs)(`form`,{className:`explorer-path`,onSubmit:e=>{e.preventDefault(),h(a)},children:[(0,T.jsx)(`input`,{ref:p,"data-testid":`explorer-path`,value:a,onChange:e=>o(e.target.value),spellCheck:!1,"aria-label":`Directory path`}),(0,T.jsx)(`button`,{type:`button`,className:`btn`,disabled:!r?.parent,onClick:()=>r?.parent&&void h(r.parent),children:`Up`}),(0,T.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>r&&void h(r.home),children:`Home`}),(0,T.jsx)(`button`,{type:`submit`,className:`btn`,children:`Go`})]}),l?(0,T.jsx)(`div`,{className:`error`,role:`alert`,children:l}):null,(0,T.jsx)(`div`,{className:`explorer-list`,role:`listbox`,"aria-label":`Folders`,"aria-busy":d,children:r?.entries.length?r.entries.map(e=>{let t=s===e.path;return(0,T.jsxs)(`button`,{type:`button`,role:`option`,"aria-selected":t,className:t?`explorer-row active`:`explorer-row`,"data-testid":`explorer-entry`,"data-path":e.path,onClick:()=>c(e.path),onDoubleClick:()=>void h(e.path),children:[(0,T.jsx)(re,{}),(0,T.jsx)(`span`,{className:`explorer-name`,children:e.name}),e.is_git?(0,T.jsx)(`span`,{className:`chip git-badge`,children:`git`}):null]},e.path)}):(0,T.jsx)(`div`,{className:`muted explorer-empty`,children:d?`Loading…`:`No folders here`})}),(0,T.jsxs)(`div`,{className:`modal-foot`,children:[(0,T.jsx)(`span`,{className:`muted explorer-current`,title:g,children:g}),(0,T.jsxs)(`button`,{type:`button`,className:`btn primary`,"data-testid":`explorer-use`,disabled:!g,onClick:()=>g&&t(g),children:[`Use `,v]})]})]})})}var Pm={scan:{start:0,end:20},extract:{start:20,end:88},boot:{start:88,end:94},stitch:{start:94,end:99},skipped:{start:100,end:100},done:{start:100,end:100}},Fm=new Set([`scan`,`extract`,`boot`,`stitch`]);function Im(e){let t=e.phase||``;if(!t||t===`idle`)return null;let n=Pm[t];if(!n)return null;if(n.start===n.end)return n.end;let r=e.total||0;if(r<=0)return n.start;let i=Math.min(1,Math.max(0,(e.done||0)/r));return Math.round(n.start+(n.end-n.start)*i)}function Lm(e){return!e.phase||e.phase===`idle`?null:typeof e.percent==`number`&&Number.isFinite(e.percent)?Math.max(0,Math.min(100,Math.round(e.percent))):Im(e)}var Rm=[{id:`obsidian`,label:`Obsidian`,group:`dark`},{id:`nord`,label:`Nord`,group:`dark`},{id:`solarized-dark`,label:`Solarized Dark`,group:`dark`},{id:`forest`,label:`Forest`,group:`dark`},{id:`rose`,label:`Rose Pine`,group:`dark`},{id:`amber`,label:`Midnight Amber`,group:`dark`},{id:`volcano`,label:`Volcano`,group:`dark`},{id:`lavender`,label:`Lavender`,group:`dark`},{id:`neon-noir`,label:`Neon Noir`,group:`dark`},{id:`synthwave`,label:`Synthwave`,group:`dark`},{id:`phosphor`,label:`Phosphor`,group:`dark`},{id:`aurora`,label:`Aurora`,group:`dark`},{id:`biolume`,label:`Biolume`,group:`dark`},{id:`carbon`,label:`Carbon`,group:`dark`},{id:`paper`,label:`Paper`,group:`light`},{id:`solarized-light`,label:`Solarized Light`,group:`light`},{id:`seafoam`,label:`Seafoam`,group:`light`},{id:`high-contrast`,label:`High Contrast`,group:`light`},{id:`sakura`,label:`Sakura`,group:`light`},{id:`citrus`,label:`Citrus`,group:`light`},{id:`peach`,label:`Peach Fuzz`,group:`light`},{id:`candy`,label:`Cotton Candy`,group:`light`},{id:`sky`,label:`Clear Sky`,group:`light`},{id:`coral`,label:`Coral Reef`,group:`light`}],zm=`obsidian`,Bm=`loadpath.theme`;function Vm(e){return Rm.some(t=>t.id===e)}function Hm(){try{let e=localStorage.getItem(Bm)||``;if(Vm(e))return e}catch{}return zm}function Um(e){return Rm.find(t=>t.id===e)?.group===`light`?`light`:`dark`}function Wm(e){document.documentElement.dataset.theme=e,document.documentElement.style.colorScheme=Um(e);try{localStorage.setItem(Bm,e)}catch{}}var Gm=[{id:`review`,label:`Review`,testId:`tab-review`,shortcut:`1`,icon:F},{id:`architecture`,label:`Architecture`,testId:`tab-architecture`,shortcut:`2`,icon:I},{id:`graph`,label:`Impact graph`,testId:`tab-graph`,shortcut:`3`,icon:te},{id:`prs`,label:`Pull requests`,testId:`tab-prs`,shortcut:`4`,icon:ne},{id:`settings`,label:`Settings`,testId:`tab-settings`,shortcut:`5`,icon:L}];function Km(e,t,n){let r;try{r=new URL(e)}catch{return}if(r.protocol!==`https:`||r.username||r.password)return;let i=r.hostname.toLowerCase();i!==t&&!i.endsWith(`.${t}`)||r.pathname.startsWith(n)&&window.open(r.toString(),`_blank`,`noopener,noreferrer`)}function qm(){let[e,t]=(0,_.useState)(`review`),[n,r]=(0,_.useState)(localStorage.getItem(`loadpath.repo`)||``),[i,a]=(0,_.useState)(localStorage.getItem(`loadpath.base`)||`HEAD~1`),[o,s]=(0,_.useState)(localStorage.getItem(`loadpath.head`)||`HEAD`),[c,l]=(0,_.useState)(null),[u,d]=(0,_.useState)(null),[f,p]=(0,_.useState)(null),[m,h]=(0,_.useState)([]),[g,v]=(0,_.useState)(`review`),[y,b]=(0,_.useState)(``),[x,C]=(0,_.useState)(``),[w,E]=(0,_.useState)(null),[O,k]=(0,_.useState)(!1),[A,M]=(0,_.useState)(!1),[N,P]=(0,_.useState)(``),[F,I]=(0,_.useState)({}),[te,ne]=(0,_.useState)([]),[L,R]=(0,_.useState)([]),[z,B]=(0,_.useState)(localStorage.getItem(`loadpath.scmRepo`)||``),[V,ie]=(0,_.useState)(localStorage.getItem(`loadpath.provider`)||`github`),[ae,oe]=(0,_.useState)(localStorage.getItem(`loadpath.prNumber`)||``),[se,ce]=(0,_.useState)(localStorage.getItem(`loadpath.dirty`)===`1`),[le,ue]=(0,_.useState)(0),[de,fe]=(0,_.useState)(``),[pe,me]=(0,_.useState)(Hm),[he,ge]=(0,_.useState)(!1),[_e,ve]=(0,_.useState)(!1),[ye,be]=(0,_.useState)(!1),[xe,Se]=(0,_.useState)(null),[Ce,we]=(0,_.useState)(null),[Te,Ee]=(0,_.useState)(localStorage.getItem(`loadpath.testOverlay`)===`1`),[De,Oe]=(0,_.useState)(null),[ke,Ae]=(0,_.useState)(localStorage.getItem(`loadpath.watch`)===`1`),[je,Me]=(0,_.useState)([]),[Ne,Pe]=(0,_.useState)(null),[Fe,Ie]=(0,_.useState)(null),[Le,Re]=(0,_.useState)(null),[ze,Be]=(0,_.useState)(()=>{try{return!!(localStorage.getItem(`loadpath.lastReviewId`)&&(localStorage.getItem(`loadpath.repo`)||``).trim())}catch{return!1}}),[Ve,He]=(0,_.useState)(null),[Ue,We]=(0,_.useState)(null),[Ge,Ke]=(0,_.useState)(!1),[qe,Je]=(0,_.useState)(!1),Ye=(0,_.useRef)(n);Ye.current=n;let Xe=(0,_.useRef)(se);Xe.current=se;let Ze=(0,_.useRef)(!1);Ze.current=_e;let Qe=(0,_.useRef)(``),$e=(0,_.useRef)(``),et=e=>{me(e),Wm(e)},tt=(0,_.useRef)(``),H=e=>{tt.current=e,C(e)},nt=e=>{let t=0,n=!1;E(0);let r=()=>{S.indexProgress(e).then(e=>{if(!tt.current)return;if(e.phase&&e.phase!==`idle`&&e.message&&H(e.message),Fm.has(e.phase))n=!0;else if(!n)return;let r=Lm(e);r!=null&&(t=e.phase===`scan`&&!e.done?r:Math.max(t,r),E(t))}).catch(()=>void 0)};r();let i=window.setInterval(r,250);return()=>{window.clearInterval(i),E(null)}};(0,_.useEffect)(()=>{S.settings().then(I).catch(()=>void 0).finally(()=>ge(!0)),S.repos().then(e=>h(e.repos)).catch(()=>void 0)},[]);let rt=()=>n.trim()?!0:(b(`Point at a local repository path first.`),!1);(0,_.useEffect)(()=>{if(e!==`architecture`||!n.trim())return;let t=n,r=!1;return $e.current!==t&&pt(t),S.config(t).then(e=>{!r&&Ye.current===t&&Ie(e)}).catch(()=>void 0),S.architectureHealth(t).then(e=>{!r&&Ye.current===t&&Re(e)}).catch(()=>void 0),()=>{r=!0}},[e,n]);let it=e=>{Ye.current=e,r(e),localStorage.setItem(`loadpath.repo`,e),e.trim()!==Qe.current&&(Qe.current=``,He(null))},at=(0,_.useCallback)(e=>{let t=(e??Ye.current).trim();return!t||Qe.current===t?Promise.resolve():(Qe.current=t,S.gitRefs(t).then(e=>{Ye.current.trim()===t&&He(e)}).catch(()=>{Qe.current===t&&(Qe.current=``,He(null))}))},[]),ot=(e,t)=>{a(e),s(t),localStorage.setItem(`loadpath.base`,e),localStorage.setItem(`loadpath.head`,t)},st=(e,t,n)=>{ie(e),B(t),localStorage.setItem(`loadpath.provider`,e),localStorage.setItem(`loadpath.scmRepo`,t),n!==void 0&&(oe(n),localStorage.setItem(`loadpath.prNumber`,n))},ct=e=>{l(e),ue(0),Se(Ce&&e.nodes.some(e=>e.id===Ce)?Ce:null),Oe(null),Pe(null),e.what_if||(d(e),e.id&&localStorage.setItem(`loadpath.lastReviewId`,e.id))},lt=async e=>{try{let t=await S.reviews(e);Me(t.reviews)}catch{Me([])}},ut=async e=>{try{Re(await S.architectureHealth(e))}catch{Re(null)}},dt=e=>e===`github`?!!F.github_token_set:e===`gitlab`?!!F.gitlab_token_set:!!F.bitbucket_token_set,ft=(0,_.useCallback)(async(e=V)=>{try{let t=await S.scmRepos(e);R(t.repos),t.user?.login&&I(n=>({...n,...e===`github`?{github_user:t.user.login}:e===`gitlab`?{gitlab_user:t.user.login}:{bitbucket_user:t.user.login}}))}catch{R([])}},[V]);(0,_.useEffect)(()=>{if(e!==`prs`)return;let t=!1;return ft(V).catch(()=>{t||R([])}),()=>{t=!0}},[e,V,ft]),(0,_.useEffect)(()=>{if(!Ue)return;let e=!1,t=0,n=async()=>{try{let r=await S.githubOAuthPoll(Ue.flow_id);if(e)return;if(r.status===`complete`){We(null);let e=await S.settings();I(e),P(r.user?`Signed in to GitHub as ${r.user}`:`Signed in to GitHub`),ft(`github`);return}if(r.status===`pending`||r.status===`slow_down`){t=window.setTimeout(n,Math.max(r.interval||Ue.interval,5)*1e3);return}We(null),b(r.status===`denied`?`GitHub sign-in was denied.`:`GitHub sign-in expired. Try again.`)}catch(t){if(e)return;We(null),b(t instanceof Error?t.message:String(t))}};return t=window.setTimeout(n,Math.max(Ue.interval,5)*1e3),()=>{e=!0,window.clearTimeout(t)}},[Ue,ft]),(0,_.useEffect)(()=>{if(!Ge)return;let e=!1,t=0,n=Date.now(),r=async()=>{try{let i=await S.oauthStatus();if(e)return;if(i.bitbucket.connected){Ke(!1);let e=await S.settings();I(e),P(i.bitbucket.user?`Signed in to Bitbucket as ${i.bitbucket.user}`:`Signed in to Bitbucket`),ft(`bitbucket`);return}if(Date.now()-n>18e4){Ke(!1),b(`Bitbucket sign-in timed out. Finish in the browser, or try again.`);return}t=window.setTimeout(r,1500)}catch(t){if(e)return;Ke(!1),b(t instanceof Error?t.message:String(t))}};return t=window.setTimeout(r,1500),()=>{e=!0,window.clearTimeout(t)}},[Ge,ft]),(0,_.useEffect)(()=>{if(!qe)return;let e=!1,t=0,n=Date.now(),r=async()=>{try{let i=await S.oauthStatus();if(e)return;if(i.gitlab.connected){Je(!1);let e=await S.settings();I(e),P(i.gitlab.user?`Signed in to GitLab as ${i.gitlab.user}`:`Signed in to GitLab`),ft(`gitlab`);return}if(Date.now()-n>18e4){Je(!1),b(`GitLab sign-in timed out. Finish in the browser, or try again.`);return}t=window.setTimeout(r,1500)}catch(t){if(e)return;Je(!1),b(t instanceof Error?t.message:String(t))}};return t=window.setTimeout(r,1500),()=>{e=!0,window.clearTimeout(t)}},[qe,ft]);let pt=async(e=n,t=!1)=>{if(!e.trim())return null;$e.current=e,M(!0);try{let n=await S.architecture(e,!1);Ye.current===e&&p(n);let r=S.architectureGraph(e).then(t=>{Ye.current===e&&p(e=>e&&{...e,nodes:t.nodes,edges:t.edges,graph_pending:!1})});return r.catch(()=>{p(t=>t&&Ye.current===e?{...t,graph_pending:!1}:t)}).finally(()=>{$e.current===e&&M(!1)}),t&&await r,n}catch(t){throw Ye.current===e&&M(!1),t}},mt=async e=>{let t=e.trim();if(!(!t||t===Ye.current)){if(tt.current){b(`Wait for the current job to finish before switching workspace.`);return}b(``),P(``),l(null),d(null),p(null),v(`architecture`),it(t),k(!0),H(`Loading ${ee(t)}…`);try{await Promise.all([pt(t),at(t)])}catch(e){Ye.current===t&&b(e instanceof Error?e.message:String(e))}finally{Ye.current===t&&(H(``),k(!1))}}},ht=async()=>{if(tt.current||!rt())return;b(``),P(``),H(`Tracing load path…`),it(n),ot(i,o);let e=nt(n);try{let e=await S.review(n,i,o,!0,Xe.current);ct(e),v(`review`),t(`review`),await S.repos().then(e=>h(e.repos)).catch(()=>void 0),await Promise.all([pt(n),lt(n),ut(n)])}catch(e){b(e instanceof Error?e.message:String(e))}finally{e(),H(``)}},gt=async(e=!0)=>{if(tt.current||!rt())return;b(``),P(``),H(e?`Indexing…`:`Full reindex…`),it(n);let r=nt(n);try{await S.index(n,e);let r=await pt(n);await S.repos().then(e=>h(e.repos)).catch(()=>void 0),r?.indexed&&(v(`architecture`),t(`architecture`))}catch(e){b(e instanceof Error?e.message:String(e))}finally{r(),H(``)}},_t=async()=>{if(!tt.current&&rt()){b(``),P(``),H(`Detecting layout…`),it(n);try{let e=await S.init(n);P(e.message),await S.repos().then(e=>h(e.repos)).catch(()=>void 0)}catch(e){b(e instanceof Error?e.message:String(e))}finally{H(``)}}},vt=async()=>{if(c?.markdown)try{await navigator.clipboard.writeText(c.markdown),P(`Copied markdown brief`)}catch(e){b(e instanceof Error?e.message:String(e))}},yt=async()=>{if(!tt.current){if(c?.what_if){b(`What-if walks are hypothetical — they are not posted to a pull request. Restore the git-range walk first.`);return}if(!c?.markdown||!z||!ae){b(`Pick a pull request first (Pull requests tab), then post the brief.`);return}H(`Posting Loadpath brief…`);try{let e=await S.postComment(V,z,Number(ae),c.markdown);P(e.updated?`Updated the Loadpath PR comment`:`Posted the Loadpath PR comment`)}catch(e){b(e instanceof Error?e.message:String(e))}finally{H(``)}}},bt=async()=>{if(!tt.current){b(``),H(`Fetching pull requests…`);try{let e=await S.prs(V,z,`open`,n.trim()||void 0);ne(e.pull_requests);let t=L.find(e=>e.slug.toLowerCase()===z.trim().toLowerCase());t?.local_path&&it(t.local_path)}catch(e){b(e instanceof Error?e.message:String(e))}finally{H(``)}}},xt=async()=>{b(``);try{let e=await S.githubOAuthStart();We(e),Km(e.verification_uri_complete,`github.com`,`/login/device`)}catch(e){b(e instanceof Error?e.message:String(e))}},St=async()=>{b(``);try{let e=await S.bitbucketOAuthStart();Ke(!0),Km(e.authorize_url,`bitbucket.org`,`/site/oauth2/authorize`)}catch(e){Ke(!1),b(e instanceof Error?e.message:String(e))}},Ct=async()=>{b(``);try{let e=await S.gitlabOAuthStart();Je(!0),Km(e.authorize_url,new URL(e.authorize_url).hostname,`/oauth/authorize`)}catch(e){Je(!1),b(e instanceof Error?e.message:String(e))}},wt=async e=>{if(!(tt.current||!n.trim())){b(``),H(`Walking what-if path…`);try{let r=await S.whatIf(n,e);P(`${r.title} — ${r.confidence.level} · ${(r.sinks||[]).length} sinks`),ct({...r,markdown:r.markdown||``,index:r.index||c?.index,workspace:r.workspace||c?.workspace}),v(`review`),t(`review`)}catch(e){b(e instanceof Error?e.message:String(e))}finally{H(``)}}},Tt=()=>{if(u){ct(u),v(`review`),t(`review`),P(`Restored the last git-range walk`);return}l(null),ue(0),Se(null),Oe(null),Pe(null),v(`architecture`),t(`architecture`),P(``)},Et=async e=>{if(tt.current)return;st(e.provider,e.repo,String(e.number));let r=L.find(t=>t.slug.toLowerCase()===e.repo.toLowerCase());r?.local_path&&it(r.local_path),b(``),H(`Fetching ${e.provider} #${e.number}…`);let i=r?.local_path||n,a=i?nt(i):()=>void 0;try{let i=await S.reviewPr(e.provider,e.repo,e.number,r?.local_path||n||void 0);ct(i),i.pull_request&&typeof i.pull_request.repo_path==`string`&&it(i.pull_request.repo_path),ot(String(i.base||e.target_branch),String(i.head||e.source_branch)),v(`review`),t(`review`),typeof i.pull_request?.repo_path==`string`&<(i.pull_request.repo_path)}catch(n){ot(e.base_sha||e.target_branch,e.head_sha||e.source_branch),t(`review`),b(n instanceof Error?n.message:String(n))}finally{a(),H(``)}},Dt=async e=>{b(``);try{I(await S.oauthDisconnect(e)),V===e&&R([]),P(`Disconnected ${e}`)}catch(e){b(e instanceof Error?e.message:String(e))}},Ot=async e=>{e.preventDefault();let t=new FormData(e.currentTarget),n={github_token:String(t.get(`github_token`)||``),github_oauth_client_id:String(t.get(`github_oauth_client_id`)||``),github_host:String(t.get(`github_host`)||``),gitlab_token:String(t.get(`gitlab_token`)||``),gitlab_host:String(t.get(`gitlab_host`)||``),gitlab_oauth_client_id:String(t.get(`gitlab_oauth_client_id`)||``),gitlab_oauth_client_secret:String(t.get(`gitlab_oauth_client_secret`)||``),bitbucket_token:String(t.get(`bitbucket_token`)||``),bitbucket_username:String(t.get(`bitbucket_username`)||``),bitbucket_oauth_client_id:String(t.get(`bitbucket_oauth_client_id`)||``),bitbucket_oauth_client_secret:String(t.get(`bitbucket_oauth_client_secret`)||``),ai_provider:String(t.get(`ai_provider`)||`none`),ai_api_key:String(t.get(`ai_api_key`)||``),ai_model:String(t.get(`ai_model`)||``),ai_base_url:String(t.get(`ai_base_url`)||``)},r=m.length?{...n,workspaces:m.map(e=>({path:e.path,name:e.name}))}:n;try{I(await S.saveSettings(r)),P(`Settings saved on this machine`)}catch(e){b(e instanceof Error?e.message:String(e))}},kt=async()=>{if(!(!c||tt.current)){H(`Residual analysis…`);try{let e=await S.residual(c);fe(e.note)}catch(e){b(e instanceof Error?e.message:String(e))}finally{H(``)}}},At=(0,_.useRef)(ht);At.current=ht;let jt=(0,_.useRef)(e);jt.current=e;let Mt=(0,_.useRef)(!1);Mt.current=ye;let Nt=(0,_.useRef)(c);Nt.current=c;let Pt=(0,_.useRef)(le);Pt.current=le,(0,_.useEffect)(()=>{let e=localStorage.getItem(`loadpath.lastReviewId`),t=(localStorage.getItem(`loadpath.repo`)||``).trim();if(!e||!t){Be(!1);return}let n=!1;return S.getReview(t,e).then(e=>{n||(ct(e),ot(e.base||localStorage.getItem(`loadpath.base`)||`HEAD~1`,e.head||localStorage.getItem(`loadpath.head`)||`HEAD`),lt(t),ut(t))}).catch(()=>void 0).finally(()=>{n||Be(!1)}),()=>{n=!0}},[]);let Ft=(0,_.useRef)(``);(0,_.useEffect)(()=>{if(!ke||!n.trim())return;let e=!1,t=async()=>{try{let t=await S.workspaceStatus(n);if(e)return;Ft.current&&t.fingerprint!==Ft.current&&!tt.current&&(ce(!0),Xe.current=!0,localStorage.setItem(`loadpath.dirty`,`1`),At.current()),Ft.current=t.fingerprint}catch{}};t();let r=window.setInterval(t,2e3);return()=>{e=!0,window.clearInterval(r)}},[ke,n]),(0,_.useEffect)(()=>{let e=e=>{if((e.metaKey||e.ctrlKey)&&e.key.toLowerCase()===`k`){e.preventDefault(),be(e=>!e);return}if(Mt.current){e.key===`Escape`&&(e.preventDefault(),be(!1));return}if(Ze.current){e.key===`Escape`&&(e.preventDefault(),ve(!1));return}let n=e.target;if(n&&(n.tagName===`INPUT`||n.tagName===`TEXTAREA`||n.tagName===`SELECT`||n.isContentEditable)){e.key===`Escape`&&n.blur();return}if(e.key===`Escape`){b(``),P(``),Se(Ce),Oe(null);return}if(e.key===`j`||e.key===`k`){let t=Nt.current?.read_order||[];if(!t.length)return;e.preventDefault();let n=Pt.current,r=e.key===`j`?Math.min(t.length-1,n+1):Math.max(0,n-1);ue(r);return}let r=Gm.find(t=>t.shortcut===e.key);if(r&&!e.metaKey&&!e.ctrlKey&&!e.altKey&&t(r.id),(e.metaKey||e.ctrlKey)&&e.key===`Enter`){if(jt.current===`settings`||jt.current===`prs`||tt.current)return;e.preventDefault(),At.current()}};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[Ce]);let It=async(e,t)=>{if(!n.trim())return;let r=await Tm(n,e,t);r.ok?P(r.message):b(r.message)},Lt=async()=>{if(c)try{let e=await S.exportHtml(c),t=URL.createObjectURL(e),n=document.createElement(`a`);n.href=t,n.download=`loadpath-${(c.id||`review`).slice(0,8)}.html`,n.click(),URL.revokeObjectURL(t),P(`Saved HTML brief`)}catch(e){b(e instanceof Error?e.message:String(e))}},Rt=async e=>{if(n.trim()){H(`Loading stored review…`);try{let r=await S.getReview(n,e);ct(r),ot(r.base||i,r.head||o),v(`review`),t(`review`);let a=je.findIndex(t=>t.id===e),s=a>=0?je[a+1]:void 0;if(s)try{Pe(await S.reviewDiff(n,e,s.id))}catch{Pe(null)}}catch(e){b(e instanceof Error?e.message:String(e))}finally{H(``)}}},zt={selectedId:xe,onSelect:Se,nodeRoles:c?.node_roles,testOverlay:Te,isolateSource:De,onIsolate:Oe,repoPath:n,onOpenFile:It,pinnedId:Ce,onPin:we},Bt=[{id:`review`,group:`Run`,label:`Review this range`,hint:`⌘/Ctrl+Enter`,run:()=>void ht()},...c?.what_if?[{id:`exit-whatif`,group:`Review`,label:u?`Back to git-range walk`:`Exit what-if walk`,run:Tt}]:[],{id:`index`,group:`Run`,label:`Index repository`,run:()=>void gt(!0)},{id:`watch`,group:`Run`,label:ke?`Stop watching working tree`:`Watch working tree`,run:()=>{let e=!ke;Ae(e),localStorage.setItem(`loadpath.watch`,e?`1`:`0`)}},{id:`tests`,group:`Graph`,label:Te?`Hide test overlay`:`Show test overlay`,run:()=>{let e=!Te;Ee(e),localStorage.setItem(`loadpath.testOverlay`,e?`1`:`0`)}},{id:`export`,group:`Review`,label:`Export HTML brief`,run:()=>void Lt()},...Gm.map(e=>({id:`tab-${e.id}`,group:`Tabs`,label:`Go to ${e.label}`,hint:e.shortcut,run:()=>t(e.id)})),...(c?.nodes||[]).slice(0,30).map(e=>({id:`node-${e.id}`,group:`Nodes`,label:e.name,hint:j(e.type),run:()=>{Se(e.id),t(`graph`)}})),...je.slice(0,12).map(e=>({id:`hist-${e.id}`,group:`History`,label:e.title||e.id,hint:`${e.level||``} ${e.created_at||``}`.trim(),run:()=>void Rt(e.id)}))],Vt=(0,_.useMemo)(()=>g===`architecture`?f?.nodes??[]:c?.nodes??[],[g,f,c]),Ht=(0,_.useMemo)(()=>g===`architecture`?f?.edges??[]:c?.edges??[],[g,f,c]),Ut=c?.index?`${c.index.counts.nodes} nodes · ${c.index.counts.edges} edges`:f?.indexed?`${f.counts.nodes} nodes · ${f.counts.edges} edges`:`Not indexed`,Wt=(c?.findings||[]).filter(e=>!e.waived);return(0,T.jsxs)(`div`,{className:`app`,children:[(0,T.jsx)(`a`,{className:`skip`,href:`#main`,children:`Skip to content`}),(0,T.jsxs)(`nav`,{className:`rail`,"data-testid":`rail`,"aria-label":`Primary`,children:[(0,T.jsxs)(`div`,{className:`brand`,children:[(0,T.jsx)(`div`,{className:`brand-mark`,children:`Loadpath`}),(0,T.jsx)(`div`,{className:`brand-sub`,children:`Load-path review`})]}),Gm.map(n=>{let r=n.icon,i=e===n.id;return(0,T.jsxs)(`button`,{type:`button`,"data-testid":n.testId,className:i?`nav-item active`:`nav-item`,"aria-current":i?`page`:void 0,"aria-label":n.label,onClick:()=>t(n.id),children:[(0,T.jsx)(r,{}),(0,T.jsx)(`span`,{children:n.label})]},n.id)}),(0,T.jsxs)(`div`,{className:`theme-pick`,children:[(0,T.jsx)(`label`,{htmlFor:`theme-select`,children:`Theme`}),(0,T.jsx)(`select`,{id:`theme-select`,"data-testid":`theme-select`,value:pe,onChange:e=>et(e.target.value),children:[`dark`,`light`].map(e=>(0,T.jsx)(`optgroup`,{label:e===`dark`?`Dark`:`Light`,children:Rm.filter(t=>t.group===e).map(e=>(0,T.jsx)(`option`,{value:e.id,children:e.label},e.id))},e))})]}),(0,T.jsxs)(`div`,{className:`rail-foot`,children:[(0,T.jsx)(`div`,{className:`muted`,role:`status`,children:x||Ut}),(0,T.jsxs)(`div`,{className:`kbd-hint`,children:[(0,T.jsx)(`kbd`,{children:`1`}),`–`,(0,T.jsx)(`kbd`,{children:`5`}),` tabs · `,(0,T.jsx)(`kbd`,{children:`⌘`}),(0,T.jsx)(`kbd`,{children:`K`}),` palette · `,(0,T.jsx)(`kbd`,{children:`j`}),`/`,(0,T.jsx)(`kbd`,{children:`k`}),` read order`]})]})]}),(0,T.jsxs)(`div`,{className:`main`,id:`main`,children:[x?(0,T.jsxs)(`div`,{className:w==null?`progress`:`progress determinate`,role:w==null?`status`:`progressbar`,"aria-label":x,"aria-live":`polite`,"aria-busy":`true`,"aria-valuemin":w==null?void 0:0,"aria-valuemax":w==null?void 0:100,"aria-valuenow":w??void 0,"data-testid":`progress`,children:[(0,T.jsx)(`i`,{style:w==null?void 0:{width:`${w}%`}}),(0,T.jsx)(`span`,{className:`sr-only`,children:x})]}):null,(0,T.jsxs)(`header`,{className:`topbar`,"data-testid":`topbar`,children:[m.length>0?(0,T.jsxs)(`label`,{className:`field workspace`,children:[(0,T.jsx)(`span`,{children:`Workspace`}),(0,T.jsxs)(`select`,{"data-testid":`workspace-select`,value:m.some(e=>e.path===n)?n:``,disabled:!!x,"aria-busy":O,onChange:e=>{e.target.value&&mt(e.target.value)},children:[(0,T.jsx)(`option`,{value:``,children:`Indexed repos…`}),m.map(e=>(0,T.jsxs)(`option`,{value:e.path,children:[e.name,e.indexed?` (${e.counts.nodes})`:``]},e.path))]})]}):null,(0,T.jsxs)(`label`,{className:`field path`,children:[(0,T.jsx)(`span`,{children:`Repository`}),(0,T.jsxs)(`div`,{className:`path-row`,children:[(0,T.jsx)(`input`,{"data-testid":`repo-path`,placeholder:`Local monorepo path`,value:n,onChange:e=>{let t=e.target.value;r(t),t.trim()!==Qe.current&&(Qe.current=``,He(null))},spellCheck:!1}),(0,T.jsx)(`button`,{type:`button`,className:`icon-btn`,"data-testid":`btn-browse-repo`,"aria-label":`Browse for a local repository`,onClick:()=>ve(!0),children:(0,T.jsx)(re,{})})]})]}),(0,T.jsxs)(`label`,{className:`field ref`,children:[(0,T.jsx)(`span`,{children:`Base`}),(0,T.jsx)(Mm,{testId:`base-ref`,menuTestId:`base-ref-menu`,value:i,onChange:e=>ot(e,o),placeholder:`base`,refs:Ve,onNeedRefs:at})]}),(0,T.jsxs)(`label`,{className:`field ref`,children:[(0,T.jsx)(`span`,{children:`Head`}),(0,T.jsx)(Mm,{testId:`head-ref`,menuTestId:`head-ref-menu`,value:o,onChange:e=>ot(i,e),placeholder:`head`,refs:Ve,onNeedRefs:at})]}),(0,T.jsxs)(`label`,{className:`field dirty`,children:[(0,T.jsx)(`span`,{children:`Working tree`}),(0,T.jsx)(`button`,{type:`button`,className:se?`chip-btn active`:`chip-btn`,"data-testid":`btn-dirty`,"aria-pressed":se,onClick:()=>{let e=!se;ce(e),localStorage.setItem(`loadpath.dirty`,e?`1`:`0`)},children:se?`Include uncommitted`:`Committed range`})]}),(0,T.jsxs)(`label`,{className:`field dirty`,children:[(0,T.jsx)(`span`,{children:`Watch`}),(0,T.jsx)(`button`,{type:`button`,className:ke?`chip-btn active`:`chip-btn`,"data-testid":`btn-watch`,"aria-pressed":ke,onClick:()=>{let e=!ke;Ae(e),localStorage.setItem(`loadpath.watch`,e?`1`:`0`)},children:ke?`Watching`:`Paused`})]}),c?(0,T.jsxs)(`div`,{className:`merge-box compact ${c.confidence.level}`,"data-testid":`merge-box`,children:[(0,T.jsx)(`div`,{className:`level ${c.confidence.level}`,children:c.confidence.level.toUpperCase()}),(0,T.jsxs)(`div`,{className:`muted`,children:[c.what_if?`what-if · `:``,c.confidence.covered_sinks,`/`,c.confidence.sinks,` sinks`]})]}):null,(0,T.jsxs)(`div`,{className:`topbar-actions`,children:[(0,T.jsx)(`button`,{type:`button`,"data-testid":`btn-init`,disabled:!!x,onClick:_t,children:`Draft config`}),(0,T.jsx)(`button`,{type:`button`,"data-testid":`btn-index`,disabled:!!x,onClick:()=>gt(!0),children:`Index`}),(0,T.jsx)(`button`,{type:`button`,"data-testid":`btn-review`,className:`btn primary`,disabled:!!x,onClick:ht,children:`Review`})]})]}),(0,T.jsxs)(`div`,{className:`alerts`,children:[y?(0,T.jsxs)(`div`,{className:`error`,"data-testid":`error`,role:`alert`,children:[(0,T.jsx)(`span`,{children:y}),(0,T.jsx)(`button`,{type:`button`,className:`dismiss`,onClick:()=>b(``),"aria-label":`Dismiss error`,children:`×`})]}):null,N?(0,T.jsxs)(`div`,{className:`banner`,"data-testid":`status-note`,children:[(0,T.jsx)(`span`,{children:N}),(0,T.jsx)(`button`,{type:`button`,className:`dismiss`,onClick:()=>P(``),"aria-label":`Dismiss`,children:`×`})]}):null,(c?.index?.stale||f?.stale)&&(e===`review`||e===`architecture`)?(0,T.jsx)(`div`,{className:`banner stale`,"data-testid":`index-stale`,children:`Index is stale — files changed since the last extract. Index again before trusting this walk.`}):null,c?.index?.django_boot===`failed`||f?.django_boot===`failed`?(0,T.jsx)(`div`,{className:`banner warn`,"data-testid":`django-boot-failed`,children:c?.index?.django_boot_detail||f?.django_boot_detail||`django.setup() failed`}):null,c?.workspace?.dirty_overlaps_review&&e===`review`?(0,T.jsxs)(`div`,{className:`banner warn`,"data-testid":`dirty-tree`,children:[`Uncommitted files overlap this review: `,(c.workspace.dirty_overlap||[]).slice(0,6).join(`, `)]}):null,c?.what_if?(0,T.jsxs)(`div`,{className:`banner whatif`,"data-testid":`whatif-banner`,children:[(0,T.jsxs)(`span`,{children:[`Hypothetical walk from`,` `,(0,T.jsx)(`strong`,{children:c.node?.name||`this node`}),`. Loadpath ignored Base/Head and asked which sinks would feel this node change — not a filter of the current map.`]}),(0,T.jsx)(`button`,{type:`button`,className:`btn`,"data-testid":`btn-exit-whatif`,onClick:Tt,children:u?`Back to git range`:`Back to architecture`})]}):null,O?(0,T.jsx)(`div`,{className:`banner`,"data-testid":`workspace-loading`,children:x||`Loading workspace…`}):null]}),(0,T.jsxs)(`div`,{className:`stage`,"aria-busy":O||A,children:[e===`review`&&(0,T.jsxs)(`div`,{className:`content`,"data-testid":`review-layout`,children:[(0,T.jsx)(`aside`,{className:`brief`,"data-testid":`brief`,children:c?(0,T.jsx)(Jm,{review:c,findings:Wt,aiNote:de,busy:!!x,tourIndex:le,onTour:ue,onAskAi:kt,onCopy:vt,onPost:yt,onSelect:Se,onOpenFile:It,onExport:Lt,history:je,diff:Ne,onReopen:Rt,onWaiver:(e,t)=>{n.trim()&&S.addWaiver(n,e,t||void 0,`from review`).then(t=>{Ie(t),P(`Waived ${e} in loadpath.yml`)})}}):ze?(0,T.jsxs)(`div`,{className:`empty`,"data-testid":`review-restoring`,children:[(0,T.jsx)(`h2`,{children:`Restoring last review`}),(0,T.jsx)(`p`,{children:`Loading the walk this machine stored last time Loadpath was open.`})]}):(0,T.jsxs)(`div`,{className:`empty`,"data-testid":`review-empty`,children:[(0,T.jsx)(`h2`,{children:`Trace the force of this diff`}),(0,T.jsx)(`p`,{children:`The graph is the architecture. The brief is where this change travels — not a hunk list.`}),(0,T.jsxs)(`ol`,{children:[(0,T.jsx)(`li`,{children:`Point at a Django + React monorepo, or pick an indexed workspace.`}),(0,T.jsxs)(`li`,{children:[`Index it. Missing `,(0,T.jsx)(`code`,{children:`loadpath.yml`}),` is drafted from `,(0,T.jsx)(`code`,{children:`manage.py`}),` and`,` `,(0,T.jsx)(`code`,{children:`src/features`}),`.`]}),(0,T.jsx)(`li`,{children:`Review a git range, or open a pull request so base/head become a three-dot merge-base.`})]})]})}),(0,T.jsx)(`div`,{className:`graph-wrap`,"data-testid":`review-graph`,children:c?(0,T.jsx)(Sm,{nodes:c.nodes,edges:c.edges,onWhatIf:wt,focusPath:c.read_order[le]?.path,...zt}):null})]}),e===`architecture`&&(0,T.jsxs)(`div`,{className:`content`,"data-testid":`architecture-panel`,children:[(0,T.jsx)(`aside`,{className:`brief`,"data-testid":`architecture-brief`,children:f?.indexed?(0,T.jsx)(Ym,{architecture:f,busy:!!x,onReindex:()=>gt(!1),onReview:ht,onSelect:Se,config:Fe,health:Le,onSaveConfig:e=>{S.saveConfig(n,e).then(e=>{Ie(e),P(`Wrote loadpath.yml`)})},onWaiver:(e,t,r)=>{S.addWaiver(n,e,t,r).then(t=>{Ie(t),P(`Waived ${e}`)})}}):O?(0,T.jsx)(`p`,{className:`muted`,"data-testid":`architecture-loading`,children:`Loading the index summary…`}):(0,T.jsx)(`p`,{className:`muted`,"data-testid":`architecture-empty`,children:`Index this repo to build the architecture graph. Review then walks that same graph for a git range — it does not start from a hunk list.`})}),(0,T.jsx)(`div`,{className:`graph-wrap`,"data-testid":`architecture-graph`,children:(A||f?.graph_pending)&&!(f?.nodes||[]).length?(0,T.jsxs)(`div`,{className:`empty graph-loading`,"data-testid":`graph-loading`,children:[(0,T.jsx)(`h2`,{children:`Drawing the architecture map…`}),(0,T.jsx)(`p`,{children:f?.counts?.nodes?`${f.counts.nodes} indexed nodes. The brief is ready while the graph loads.`:`Fetching the indexed graph.`})]}):f?.indexed?(0,T.jsx)(Sm,{nodes:f.nodes,edges:f.edges,onWhatIf:wt,...zt,isolateSource:null,onIsolate:void 0}):null})]}),e===`graph`&&(0,T.jsxs)(`div`,{className:`graph-wrap`,"data-testid":`graph-full`,style:{height:`100%`},children:[(0,T.jsxs)(`div`,{className:`graph-modes`,children:[(0,T.jsxs)(`div`,{className:`seg`,"aria-label":`Graph scope`,children:[(0,T.jsx)(`button`,{type:`button`,"aria-pressed":g===`review`,"data-testid":`graph-mode-review`,className:g===`review`?`active`:``,onClick:()=>v(`review`),children:`This review`}),(0,T.jsx)(`button`,{type:`button`,"aria-pressed":g===`architecture`,"data-testid":`graph-mode-architecture`,className:g===`architecture`?`active`:``,onClick:()=>v(`architecture`),children:`Indexed architecture`})]}),(0,T.jsxs)(`div`,{className:`legend`,"aria-hidden":`true`,children:[(0,T.jsxs)(`span`,{children:[(0,T.jsx)(`i`,{}),` cheap`]}),(0,T.jsxs)(`span`,{children:[(0,T.jsx)(`i`,{className:`exp`}),` expensive`]}),(0,T.jsxs)(`span`,{children:[(0,T.jsx)(`i`,{className:`crit`}),` critical`]}),(0,T.jsxs)(`span`,{children:[(0,T.jsx)(`i`,{className:`dash`}),` inferred`]}),(0,T.jsxs)(`span`,{children:[(0,T.jsx)(`i`,{className:`seed`}),` changed`]}),(0,T.jsxs)(`span`,{children:[(0,T.jsx)(`i`,{className:`down`}),` downstream`]})]}),(0,T.jsx)(`button`,{type:`button`,className:Te?`chip-btn active`:`chip-btn`,"data-testid":`graph-test-overlay`,"aria-pressed":Te,onClick:()=>{let e=!Te;Ee(e),localStorage.setItem(`loadpath.testOverlay`,e?`1`:`0`)},children:`Tests`})]}),Vt.length||g===`review`&&c||f?.indexed&&!(A||f?.graph_pending)?(0,T.jsx)(Sm,{nodes:Vt,edges:Ht,onWhatIf:wt,...zt,...g===`architecture`?{isolateSource:null,onIsolate:void 0,nodeRoles:void 0,testOverlay:!1}:{}}):A||f?.graph_pending?(0,T.jsx)(`p`,{className:`empty`,"data-testid":`graph-loading`,children:`Drawing the architecture map…`}):(0,T.jsx)(`p`,{className:`empty`,"data-testid":`graph-empty`,children:`Index the repo or run a review first. Click a node to inspect it.`})]}),e===`prs`&&(0,T.jsxs)(`div`,{className:`pr-list`,"data-testid":`pr-list`,children:[(0,T.jsxs)(`div`,{className:`pr-toolbar`,children:[(0,T.jsxs)(`label`,{className:`field provider`,children:[(0,T.jsx)(`span`,{children:`Provider`}),(0,T.jsxs)(`select`,{"data-testid":`pr-provider`,value:V,onChange:e=>st(e.target.value,z,ae),children:[(0,T.jsx)(`option`,{value:`github`,children:`GitHub`}),(0,T.jsx)(`option`,{value:`gitlab`,children:`GitLab`}),(0,T.jsx)(`option`,{value:`bitbucket`,children:`Bitbucket`})]})]}),(0,T.jsxs)(`label`,{className:`field`,children:[(0,T.jsx)(`span`,{children:`Repository`}),(0,T.jsx)(`input`,{"data-testid":`pr-repo`,placeholder:L.length?`Search your repos`:`owner/repo`,value:z,onChange:e=>st(V,e.target.value,ae),list:`scm-repos`,spellCheck:!1}),(0,T.jsx)(`datalist`,{id:`scm-repos`,children:L.map(e=>(0,T.jsxs)(`option`,{value:e.slug,children:[e.private?`private`:`public`,e.local_path?` · local`:``]},e.slug))})]}),(0,T.jsx)(`button`,{type:`button`,"data-testid":`btn-refresh-repos`,className:`btn`,disabled:!!x||!dt(V),onClick:()=>{ft(V)},children:`My repos`}),(0,T.jsx)(`button`,{type:`button`,"data-testid":`btn-list-prs`,className:`btn`,disabled:!!x,onClick:bt,children:`List PRs`})]}),L.length>0?(0,T.jsxs)(`p`,{className:`muted scm-count`,"data-testid":`scm-repo-count`,children:[L.length,` `,V,` repositor`,L.length===1?`y`:`ies`,V===`github`&&F.github_user?` · @${String(F.github_user)}`:``,V===`gitlab`&&F.gitlab_user?` · @${String(F.gitlab_user)}`:``,V===`bitbucket`&&F.bitbucket_user?` · ${String(F.bitbucket_user)}`:``]}):null,te.length===0?(0,T.jsxs)(`div`,{className:`empty`,"data-testid":`pr-empty`,children:[(0,T.jsx)(`h2`,{children:`No pull requests loaded`}),(0,T.jsx)(`p`,{children:`Sign in under Settings (or paste a token), load your repositories, then list open PRs. Reviewing a PR fills base and head from its SHAs.`})]}):te.map(e=>(0,T.jsxs)(`article`,{className:`pr`,"data-testid":`pr-${e.number}`,children:[(0,T.jsxs)(`h3`,{children:[`#`,e.number,` `,e.title]}),(0,T.jsxs)(`div`,{className:`pr-meta muted`,children:[(0,T.jsx)(`span`,{className:`chip ${e.draft?``:`open`}`,children:e.draft?`draft`:e.state}),(0,T.jsx)(`span`,{children:e.author}),(0,T.jsxs)(`span`,{children:[e.source_branch,` → `,e.target_branch]}),e.loadpath?(0,T.jsxs)(`span`,{className:`chip ${e.loadpath.level||``}`,"data-testid":`pr-loadpath-${e.number}`,children:[e.loadpath.level?.toUpperCase()||`REVIEWED`,e.loadpath.contract_break&&e.loadpath.contract_break!==`none`?` · ${e.loadpath.contract_break}`:``]}):(0,T.jsx)(`span`,{className:`muted`,children:`no Loadpath walk yet`})]}),(0,T.jsxs)(`div`,{className:`pr-actions`,children:[(0,T.jsxs)(`a`,{href:e.url,target:`_blank`,rel:`noreferrer`,children:[`Open on `,e.provider]}),(0,T.jsx)(`button`,{type:`button`,className:`btn primary`,"data-testid":`pr-review-${e.number}`,onClick:()=>void Et(e),children:`Review this PR`})]})]},`${e.provider}-${e.number}`))]}),e===`settings`&&he&&(0,T.jsxs)(`form`,{className:`settings`,"data-testid":`settings-form`,onSubmit:Ot,children:[(0,T.jsxs)(`div`,{children:[(0,T.jsx)(`h1`,{children:`Settings`}),(0,T.jsx)(`p`,{className:`muted`,children:`Tokens stay on this machine in ~/.loadpath/settings.json. AI runs only on residual uncertainty the graph could not close.`})]}),(0,T.jsxs)(`section`,{className:`settings-card`,children:[(0,T.jsx)(`h2`,{children:`Appearance`}),(0,T.jsx)(`p`,{className:`muted`,children:`Local to this browser. High contrast is a first-class theme, not an afterthought.`}),(0,T.jsx)(`div`,{className:`theme-grid`,"data-testid":`theme-grid`,children:Rm.map(e=>(0,T.jsxs)(`button`,{type:`button`,"data-theme":e.id,className:pe===e.id?`theme-swatch active`:`theme-swatch`,"data-testid":`theme-${e.id}`,onClick:()=>et(e.id),children:[(0,T.jsx)(`div`,{className:`swatch-bar`,"aria-hidden":`true`}),(0,T.jsx)(`div`,{className:`name`,children:e.label}),(0,T.jsx)(`div`,{className:`group`,children:e.group})]},e.id))})]}),(0,T.jsxs)(`section`,{className:`settings-card`,children:[(0,T.jsx)(`h2`,{children:`Editor`}),(0,T.jsx)(`p`,{className:`muted`,children:`Open files from the inspector and read-order in Cursor, VS Code, or the system handler.`}),(0,T.jsx)(`label`,{htmlFor:`editor-pref`,children:`Preferred editor`}),(0,T.jsxs)(`select`,{id:`editor-pref`,"data-testid":`editor-pref`,defaultValue:Cm(),onChange:e=>wm(e.target.value),children:[(0,T.jsx)(`option`,{value:`auto`,children:`Auto (Cursor, then VS Code)`}),(0,T.jsx)(`option`,{value:`cursor`,children:`Cursor`}),(0,T.jsx)(`option`,{value:`vscode`,children:`VS Code`}),(0,T.jsx)(`option`,{value:`system`,children:`System default`})]})]}),(0,T.jsxs)(`section`,{className:`settings-card`,children:[(0,T.jsx)(`h2`,{children:`Source control`}),(0,T.jsx)(`p`,{className:`muted`,children:`Sign in with OAuth to list every repository the account can access. Tokens stay in ~/.loadpath/settings.json. A classic PAT still works if you prefer not to register an OAuth app.`}),(0,T.jsxs)(`div`,{className:`scm-login`,"data-testid":`scm-github`,children:[(0,T.jsxs)(`div`,{children:[(0,T.jsx)(`strong`,{children:`GitHub`}),(0,T.jsx)(`p`,{className:`muted`,children:F.github_token_set?F.github_user?`Signed in as @${String(F.github_user)}`:`Token saved on this machine`:`Not connected`})]}),(0,T.jsx)(`div`,{className:`btn-row`,children:F.github_token_set?(0,T.jsx)(`button`,{type:`button`,className:`btn`,"data-testid":`btn-github-disconnect`,onClick:()=>void Dt(`github`),children:`Disconnect`}):(0,T.jsx)(`button`,{type:`button`,className:`btn primary`,"data-testid":`btn-github-login`,disabled:!!Ue||!F.github_oauth_ready,onClick:()=>void xt(),children:Ue?`Waiting for GitHub…`:`Sign in with GitHub`})})]}),Ue?(0,T.jsxs)(`p`,{className:`oauth-code`,"data-testid":`github-user-code`,children:[`Enter `,(0,T.jsx)(`code`,{children:Ue.user_code}),` at GitHub if the browser did not fill it in.`]}):null,F.github_oauth_ready?null:(0,T.jsx)(`p`,{className:`muted`,children:`Sign-in needs a GitHub OAuth App with Device Flow enabled. Set LOADPATH_GITHUB_CLIENT_ID or paste the client ID below.`}),(0,T.jsx)(`label`,{htmlFor:`github_oauth_client_id`,children:`GitHub OAuth client ID`}),(0,T.jsx)(`input`,{id:`github_oauth_client_id`,name:`github_oauth_client_id`,"data-testid":`github-oauth-client-id`,placeholder:`Ov23…`,defaultValue:String(F.github_oauth_client_id||``),autoComplete:`off`}),(0,T.jsx)(`label`,{htmlFor:`github_token`,children:`GitHub token (optional PAT)`}),(0,T.jsx)(`input`,{id:`github_token`,name:`github_token`,type:`password`,placeholder:`ghp_…`,autoComplete:`off`}),(0,T.jsx)(`label`,{htmlFor:`github_host`,children:`GitHub host (Enterprise)`}),(0,T.jsx)(`input`,{id:`github_host`,name:`github_host`,"data-testid":`github-host`,placeholder:`github.com`,defaultValue:String(F.github_host||``),autoComplete:`off`}),(0,T.jsxs)(`div`,{className:`scm-login`,"data-testid":`scm-gitlab`,children:[(0,T.jsxs)(`div`,{children:[(0,T.jsx)(`strong`,{children:`GitLab`}),(0,T.jsx)(`p`,{className:`muted`,children:F.gitlab_token_set?F.gitlab_user?`Signed in as @${String(F.gitlab_user)}`:`Token saved on this machine`:`Not connected`})]}),(0,T.jsx)(`div`,{className:`btn-row`,children:F.gitlab_token_set?(0,T.jsx)(`button`,{type:`button`,className:`btn`,"data-testid":`btn-gitlab-disconnect`,onClick:()=>void Dt(`gitlab`),children:`Disconnect`}):(0,T.jsx)(`button`,{type:`button`,className:`btn primary`,"data-testid":`btn-gitlab-login`,disabled:qe||!F.gitlab_oauth_ready,onClick:()=>void Ct(),children:qe?`Waiting for GitLab…`:`Sign in with GitLab`})})]}),(0,T.jsx)(`label`,{htmlFor:`gitlab_host`,children:`GitLab host`}),(0,T.jsx)(`input`,{id:`gitlab_host`,name:`gitlab_host`,"data-testid":`gitlab-host`,placeholder:`gitlab.com`,defaultValue:String(F.gitlab_host||``),autoComplete:`off`}),(0,T.jsx)(`label`,{htmlFor:`gitlab_oauth_client_id`,children:`GitLab OAuth application ID`}),(0,T.jsx)(`input`,{id:`gitlab_oauth_client_id`,name:`gitlab_oauth_client_id`,"data-testid":`gitlab-oauth-client-id`,defaultValue:String(F.gitlab_oauth_client_id||``),autoComplete:`off`}),(0,T.jsx)(`label`,{htmlFor:`gitlab_oauth_client_secret`,children:`GitLab OAuth secret`}),(0,T.jsx)(`input`,{id:`gitlab_oauth_client_secret`,name:`gitlab_oauth_client_secret`,type:`password`,autoComplete:`off`}),(0,T.jsx)(`label`,{htmlFor:`gitlab_token`,children:`GitLab token (optional PAT)`}),(0,T.jsx)(`input`,{id:`gitlab_token`,name:`gitlab_token`,type:`password`,placeholder:`glpat-…`,autoComplete:`off`}),(0,T.jsxs)(`div`,{className:`scm-login`,"data-testid":`scm-bitbucket`,children:[(0,T.jsxs)(`div`,{children:[(0,T.jsx)(`strong`,{children:`Bitbucket`}),(0,T.jsx)(`p`,{className:`muted`,children:F.bitbucket_token_set?F.bitbucket_user?`Signed in as ${String(F.bitbucket_user)}`:`Token saved on this machine`:`Not connected`})]}),(0,T.jsx)(`div`,{className:`btn-row`,children:F.bitbucket_token_set?(0,T.jsx)(`button`,{type:`button`,className:`btn`,"data-testid":`btn-bitbucket-disconnect`,onClick:()=>void Dt(`bitbucket`),children:`Disconnect`}):(0,T.jsx)(`button`,{type:`button`,className:`btn primary`,"data-testid":`btn-bitbucket-login`,disabled:Ge||!F.bitbucket_oauth_ready,onClick:()=>void St(),children:Ge?`Waiting for Bitbucket…`:`Sign in with Bitbucket`})})]}),F.bitbucket_oauth_ready?null:(0,T.jsxs)(`p`,{className:`muted`,children:[`Sign-in needs a Bitbucket OAuth consumer (key + secret). Callback URL:`,` `,(0,T.jsx)(`code`,{children:`/api/oauth/bitbucket/callback`}),` on this app origin.`]}),(0,T.jsx)(`label`,{htmlFor:`bitbucket_oauth_client_id`,children:`Bitbucket OAuth key`}),(0,T.jsx)(`input`,{id:`bitbucket_oauth_client_id`,name:`bitbucket_oauth_client_id`,"data-testid":`bitbucket-oauth-client-id`,defaultValue:String(F.bitbucket_oauth_client_id||``),autoComplete:`off`}),(0,T.jsx)(`label`,{htmlFor:`bitbucket_oauth_client_secret`,children:`Bitbucket OAuth secret`}),(0,T.jsx)(`input`,{id:`bitbucket_oauth_client_secret`,name:`bitbucket_oauth_client_secret`,type:`password`,autoComplete:`off`}),(0,T.jsx)(`label`,{htmlFor:`bitbucket_token`,children:`Bitbucket token (optional app password)`}),(0,T.jsx)(`input`,{id:`bitbucket_token`,name:`bitbucket_token`,type:`password`,autoComplete:`off`}),(0,T.jsx)(`label`,{htmlFor:`bitbucket_username`,children:`Bitbucket username (app passwords)`}),(0,T.jsx)(`input`,{id:`bitbucket_username`,name:`bitbucket_username`,defaultValue:String(F.bitbucket_username||``)})]}),(0,T.jsxs)(`section`,{className:`settings-card`,children:[(0,T.jsx)(`h2`,{children:`Residual AI`}),(0,T.jsx)(`label`,{htmlFor:`ai_provider`,children:`Provider`}),(0,T.jsxs)(`select`,{id:`ai_provider`,name:`ai_provider`,defaultValue:String(F.ai?.provider||`none`),children:[(0,T.jsx)(`option`,{value:`none`,children:`none (graph only)`}),(0,T.jsx)(`option`,{value:`anthropic`,children:`Anthropic`}),(0,T.jsx)(`option`,{value:`openai`,children:`OpenAI`}),(0,T.jsx)(`option`,{value:`grok`,children:`Grok / xAI`}),(0,T.jsx)(`option`,{value:`deepseek`,children:`DeepSeek`}),(0,T.jsx)(`option`,{value:`cursor`,children:`Cursor-compatible (OpenAI protocol)`}),(0,T.jsx)(`option`,{value:`ollama`,children:`Ollama local`})]}),(0,T.jsx)(`label`,{htmlFor:`ai_api_key`,children:`API key`}),(0,T.jsx)(`input`,{id:`ai_api_key`,name:`ai_api_key`,type:`password`,autoComplete:`off`}),(0,T.jsx)(`label`,{htmlFor:`ai_model`,children:`Model`}),(0,T.jsx)(`input`,{id:`ai_model`,name:`ai_model`,"data-testid":`ai-model`,placeholder:`optional override`,defaultValue:String(F.ai?.model||``)}),(0,T.jsx)(`label`,{htmlFor:`ai_base_url`,children:`Base URL`}),(0,T.jsx)(`input`,{id:`ai_base_url`,name:`ai_base_url`,"data-testid":`ai-base-url`,placeholder:`optional, OpenAI-compatible`,defaultValue:String(F.ai?.base_url||``)}),(0,T.jsx)(`button`,{className:`btn primary`,type:`submit`,"data-testid":`btn-save-settings`,children:`Save`})]})]})]})]}),(0,T.jsx)(D,{open:ye,actions:Bt,onClose:()=>be(!1)}),_e?(0,T.jsx)(Nm,{initialPath:n,onClose:()=>ve(!1),onSelect:e=>{if(tt.current){b(`Wait for the current job to finish before switching workspace.`);return}ve(!1),mt(e)}}):null]})}function Jm({review:e,findings:t,aiNote:n,busy:r,tourIndex:i,onTour:a,onAskAi:o,onCopy:s,onPost:c,onSelect:l,onOpenFile:u,onExport:d,history:f,diff:p,onReopen:m,onWaiver:h}){let g=[...new Set(e.confidence.reasons||[])];return(0,T.jsxs)(T.Fragment,{children:[(0,T.jsxs)(`div`,{className:`merge-box ${e.confidence.level}`,children:[(0,T.jsxs)(`div`,{className:`level ${e.confidence.level}`,children:[e.confidence.level.toUpperCase(),` — `,e.title]}),g.length?(0,T.jsx)(`ul`,{className:`reasons`,children:g.map(e=>(0,T.jsx)(`li`,{children:e},e))}):null,e.what_if?(0,T.jsx)(`span`,{className:`chip whatif`,"data-testid":`whatif-chip`,children:`what-if`}):null,e.low_risk?(0,T.jsx)(`span`,{className:`chip`,children:`low-risk`}):null,e.change_kinds.map(e=>(0,T.jsx)(`span`,{className:`chip`,children:k(e)},e)),e.contract_break?.kind&&e.contract_break.kind!==`none`?(0,T.jsxs)(`span`,{className:`chip ${e.contract_break.kind===`breaking`?`blocker`:``}`,"data-testid":`contract-kind`,children:[`contract `,e.contract_break.kind]}):null]}),(0,T.jsxs)(`div`,{className:`metrics`,children:[(0,T.jsxs)(`div`,{className:`metric`,children:[(0,T.jsxs)(`div`,{className:`n`,children:[e.confidence.covered_sinks,`/`,e.confidence.sinks]}),(0,T.jsx)(`div`,{className:`l`,children:`Sinks tested`})]}),(0,T.jsxs)(`div`,{className:`metric`,children:[(0,T.jsx)(`div`,{className:`n`,children:t.length}),(0,T.jsx)(`div`,{className:`l`,children:`Findings`})]}),(0,T.jsxs)(`div`,{className:`metric`,children:[(0,T.jsx)(`div`,{className:`n`,children:e.residuals.length}),(0,T.jsx)(`div`,{className:`l`,children:`Residuals`})]})]}),(0,T.jsx)(`pre`,{className:`headline`,children:e.headline}),(e.checklist||[]).length?(0,T.jsxs)(`details`,{className:`section`,open:!0,"data-testid":`merge-checklist`,children:[(0,T.jsxs)(`summary`,{children:[`Merge checklist`,` `,(0,T.jsx)(`span`,{className:`count`,children:(e.checklist||[]).filter(e=>e.status===`todo`).length})]}),(e.checklist||[]).map(e=>(0,T.jsxs)(`div`,{className:`check-item ${e.status}`,children:[(0,T.jsxs)(`button`,{type:`button`,className:`linkish`,onClick:()=>e.node_id&&l(e.node_id),children:[(0,T.jsx)(`span`,{className:`chip ${e.status}`,children:e.status}),e.title]}),e.detail?(0,T.jsx)(`div`,{className:`why`,children:e.detail}):null,e.body?(0,T.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>{navigator.clipboard.writeText(e.body||``)},children:`Copy test`}):null,e.kind===`finding`&&e.status===`todo`&&e.rule?(0,T.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>h(e.rule,e.node_id),children:`Waive in loadpath.yml`}):null]},e.id))]}):null,e.index?(0,T.jsxs)(`details`,{className:`section`,open:!0,children:[(0,T.jsxs)(`summary`,{children:[`Index `,(0,T.jsx)(`span`,{className:`count`,children:e.index.counts.nodes})]}),(0,T.jsxs)(`div`,{className:`muted`,children:[`Walked `,e.index.counts.nodes,` nodes / `,e.index.counts.edges,` edges`,e.index.reindex_skipped?` from an unchanged index`:e.index.reindexed?` after an incremental refresh`:` from the existing index`,e.index.django_boot&&e.index.django_boot!==`off`?` · Django boot ${e.index.django_boot}`:``,e.workspace?.three_dot?` · three-dot range`:``]})]}):null,(0,T.jsxs)(`details`,{className:`section`,open:!0,children:[(0,T.jsxs)(`summary`,{children:[`Read this `,(0,T.jsx)(`span`,{className:`count`,children:e.read_order.length})]}),e.read_order.map((e,t)=>(0,T.jsxs)(`div`,{className:t===i?`read-item tour-current`:`read-item`,children:[(0,T.jsxs)(`button`,{type:`button`,className:`linkish file`,onClick:()=>a(t),children:[t+1,`. `,e.path]}),(0,T.jsx)(`div`,{className:`why`,children:e.why}),(0,T.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>u(e.path),children:`Open`})]},e.path)),e.read_order.length>0?(0,T.jsxs)(`div`,{className:`btn-row tour-row`,children:[(0,T.jsx)(`button`,{type:`button`,className:`btn`,"data-testid":`btn-tour-prev`,disabled:i<=0,onClick:()=>a(Math.max(0,i-1)),children:`Previous`}),(0,T.jsx)(`button`,{type:`button`,className:`btn primary`,"data-testid":`btn-tour-next`,disabled:i>=e.read_order.length-1,onClick:()=>a(Math.min(e.read_order.length-1,i+1)),children:`Next in read order`}),(0,T.jsxs)(`span`,{className:`muted`,children:[i+1,`/`,e.read_order.length]})]}):null]}),(0,T.jsxs)(`details`,{className:`section`,children:[(0,T.jsxs)(`summary`,{children:[`Clusters `,(0,T.jsx)(`span`,{className:`count`,children:e.clusters.length})]}),e.clusters.map(e=>(0,T.jsxs)(`div`,{className:`muted`,children:[(0,T.jsx)(`strong`,{children:e.title}),` — `,e.files.join(`, `)]},e.id))]}),(0,T.jsxs)(`details`,{className:`section`,open:!0,children:[(0,T.jsxs)(`summary`,{children:[`Architecture `,(0,T.jsx)(`span`,{className:`count`,children:t.length})]}),t.length===0?(0,T.jsx)(`div`,{className:`muted`,children:e.architecture_note}):t.map(e=>(0,T.jsx)(`div`,{className:`finding`,children:(0,T.jsxs)(`button`,{type:`button`,className:`linkish`,onClick:()=>e.node_id&&l(e.node_id),children:[(0,T.jsx)(`span`,{className:`chip ${e.severity}`,children:e.severity}),e.message]})},e.rule+e.message))]}),(0,T.jsx)(Xm,{cards:e.deepening}),e.contract_break?.reasons?.length?(0,T.jsxs)(`details`,{className:`section`,open:!0,children:[(0,T.jsxs)(`summary`,{children:[`Contract `,(0,T.jsx)(`span`,{className:`count`,children:e.contract_break.kind})]}),e.contract_break.reasons.map(e=>(0,T.jsx)(`div`,{className:`muted`,children:e},e)),e.contract_break.sides?.rows?.length?(0,T.jsxs)(`table`,{className:`type-table`,"data-testid":`contract-sides`,children:[(0,T.jsx)(`thead`,{children:(0,T.jsxs)(`tr`,{children:[(0,T.jsx)(`th`,{children:`Field`}),(0,T.jsx)(`th`,{children:`Serializer`}),(0,T.jsx)(`th`,{children:`Zod`}),(0,T.jsx)(`th`,{children:`GraphQL`})]})}),(0,T.jsx)(`tbody`,{children:e.contract_break.sides.rows.map(e=>(0,T.jsxs)(`tr`,{className:e.status,children:[(0,T.jsx)(`td`,{children:e.field}),(0,T.jsx)(`td`,{children:e.serializer?`yes`:`—`}),(0,T.jsx)(`td`,{children:e.zod?`yes`:`—`}),(0,T.jsx)(`td`,{children:e.graphql?`yes`:`—`})]},e.field))})]}):null]}):null,e.auth?.note?(0,T.jsxs)(`details`,{className:`section`,open:!0,children:[(0,T.jsx)(`summary`,{children:`Auth`}),(0,T.jsx)(`div`,{className:`muted`,children:e.auth.note}),(e.auth.missing_permissions||[]).map(e=>(0,T.jsxs)(`div`,{className:`finding`,children:[(0,T.jsx)(`span`,{className:`chip warning`,children:`missing`}),e.name]},e.id))]}):null,(e.suggested_tests||[]).length?(0,T.jsxs)(`details`,{className:`section`,open:!0,children:[(0,T.jsxs)(`summary`,{children:[`Suggested tests `,(0,T.jsx)(`span`,{className:`count`,children:e.suggested_tests?.length})]}),(e.suggested_tests||[]).map(e=>(0,T.jsxs)(`div`,{className:`residual`,children:[(0,T.jsx)(`strong`,{children:e.title}),(0,T.jsx)(`pre`,{className:`headline`,children:e.body}),(0,T.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>{navigator.clipboard.writeText(e.body)},children:`Copy sketch`})]},e.title))]}):null,e.trend?.note?(0,T.jsxs)(`details`,{className:`section`,children:[(0,T.jsx)(`summary`,{children:`Confidence trend`}),(0,T.jsx)(`div`,{className:`muted`,children:e.trend.note}),(e.trend.points||[]).slice(0,6).map(e=>(0,T.jsxs)(`div`,{className:`muted`,children:[e.level,` · `,M(e.created_at),e.sinks==null?``:` · ${e.sinks} sinks`]},e.id))]}):null,(0,T.jsxs)(`details`,{className:`section`,open:!0,children:[(0,T.jsxs)(`summary`,{children:[`Residual `,(0,T.jsx)(`span`,{className:`count`,children:e.residuals.length})]}),(0,T.jsx)(`p`,{className:`muted`,children:`AI is only used here, on what the graph could not close.`}),e.residuals.map(e=>(0,T.jsx)(`div`,{className:`residual muted`,children:e},e))]}),f.length?(0,T.jsxs)(`details`,{className:`section`,"data-testid":`review-history`,children:[(0,T.jsxs)(`summary`,{children:[`History `,(0,T.jsx)(`span`,{className:`count`,children:f.length})]}),p?(0,T.jsx)(`div`,{className:`muted`,children:p.note}):null,f.slice(0,12).map(t=>(0,T.jsxs)(`button`,{type:`button`,className:t.id===e.id?`history-item current`:`history-item`,onClick:()=>m(t.id),children:[(0,T.jsx)(`span`,{className:`chip ${t.level||``}`,children:t.level||`walk`}),t.title||t.id.slice(0,8),(0,T.jsx)(`span`,{className:`muted`,children:t.created_at?M(t.created_at):``})]},t.id))]}):null,e.evolution?.notes?.length||e.evolution?.hotspots?.some(e=>e.commits)?(0,T.jsxs)(`details`,{className:`section`,children:[(0,T.jsx)(`summary`,{children:`Churn & coupling`}),(e.evolution?.notes||[]).map(e=>(0,T.jsx)(`div`,{className:`muted`,children:e},e)),(e.evolution?.hotspots||[]).filter(e=>e.commits).slice(0,6).map(e=>(0,T.jsxs)(`div`,{className:`muted`,children:[(0,T.jsx)(`span`,{className:`file`,children:e.path}),` — `,e.commits,` commits, bus factor `,e.bus_factor]},e.path))]}):null,(0,T.jsxs)(`div`,{className:`btn-row`,children:[(0,T.jsx)(`button`,{type:`button`,className:`btn`,disabled:r,onClick:o,children:`Ask configured model`}),(0,T.jsx)(`button`,{type:`button`,className:`btn`,"data-testid":`btn-copy-markdown`,onClick:s,children:`Copy markdown`}),(0,T.jsx)(`button`,{type:`button`,className:`btn`,"data-testid":`btn-export-html`,onClick:d,children:`Save HTML`}),(0,T.jsx)(`button`,{type:`button`,className:`btn`,"data-testid":`btn-post-comment`,disabled:r||!!e.what_if,title:e.what_if?`Hypothetical walks are not posted to a pull request`:void 0,onClick:c,children:`Post to PR`})]}),n?(0,T.jsx)(`pre`,{className:`headline`,children:n}):null,(0,T.jsx)(`div`,{className:`kicker`,children:`Reviewers`}),(0,T.jsx)(`div`,{className:`muted`,children:e.suggested_reviewers.join(`, `)||`—`}),e.codeowners_reviewers?.length?(0,T.jsxs)(`div`,{className:`muted`,children:[`CODEOWNERS: `,e.codeowners_reviewers.join(`, `)]}):null,e.knowledge_owners?.length?(0,T.jsxs)(`div`,{className:`muted`,children:[`Knowledge: `,e.knowledge_owners.join(`, `)]}):null]})}function Ym({architecture:e,busy:t,onReindex:n,onReview:r,onSelect:i,config:a,health:o,onSaveConfig:s,onWaiver:c}){let l=e.findings.filter(e=>!e.waived);return(0,T.jsxs)(T.Fragment,{children:[(0,T.jsxs)(`div`,{className:`merge-box high`,children:[(0,T.jsxs)(`div`,{className:`level high`,children:[`INDEXED — `,e.counts.nodes,` nodes`]}),(0,T.jsxs)(`div`,{className:`muted`,style:{marginTop:8},children:[e.indexed_at?`Last index ${M(e.indexed_at)}`:`Indexed`,e.incremental?` · incremental`:` · full`,e.stale?` · stale`:``,e.django_boot&&e.django_boot!==`off`?` · Django boot ${e.django_boot}`:``]}),(0,T.jsxs)(`span`,{className:`chip`,children:[e.counts.edges,` edges`]}),e.has_config?(0,T.jsx)(`span`,{className:`chip`,children:`loadpath.yml`}):null]}),(0,T.jsxs)(`details`,{className:`section`,open:!0,children:[(0,T.jsx)(`summary`,{children:`Bounded contexts`}),Object.values(e.contexts).map(e=>(0,T.jsxs)(`div`,{className:`muted`,children:[(0,T.jsx)(`strong`,{children:e.name}),` — `,(e.django_apps||[]).join(`, `)||`no apps`,` ·`,` `,(e.owners||[]).join(`, `)||`unowned`]},e.name))]}),(0,T.jsxs)(`details`,{className:`section`,children:[(0,T.jsxs)(`summary`,{children:[`Rules `,(0,T.jsx)(`span`,{className:`count`,children:(e.rules||[]).length})]}),(e.rules||[]).map(e=>(0,T.jsx)(`div`,{className:`muted`,children:e},e))]}),(0,T.jsxs)(`details`,{className:`section`,open:!0,children:[(0,T.jsxs)(`summary`,{children:[`Findings `,(0,T.jsx)(`span`,{className:`count`,children:l.length})]}),l.length===0?(0,T.jsx)(`div`,{className:`muted`,children:`No architecture rule hits on the full graph.`}):l.map(e=>(0,T.jsx)(`div`,{className:`finding`,children:(0,T.jsxs)(`button`,{type:`button`,className:`linkish`,onClick:()=>e.node_id&&i(e.node_id),children:[(0,T.jsx)(`span`,{className:`chip ${e.severity}`,children:e.severity}),e.message]})},e.rule+e.message))]}),(0,T.jsx)(Xm,{cards:e.deepening}),o?.points?.length?(0,T.jsxs)(`details`,{className:`section`,open:!0,"data-testid":`architecture-health`,children:[(0,T.jsxs)(`summary`,{children:[`Health over time `,(0,T.jsx)(`span`,{className:`count`,children:o.points.length})]}),(0,T.jsx)(`div`,{className:`sparkline`,"aria-hidden":`true`,children:o.points.map(e=>(0,T.jsx)(`i`,{className:e.level||``,title:`${e.level} · ${e.findings} findings`,style:{height:`${8+Math.min(24,(e.findings||0)*4)}px`}},e.id||e.created_at))}),Object.entries(o.contexts).map(([e,t])=>(0,T.jsxs)(`div`,{className:`muted`,children:[(0,T.jsx)(`strong`,{children:e}),` — last `,t[t.length-1]?.findings??0,` findings`]},e))]}):null,a?(0,T.jsxs)(`details`,{className:`section`,open:!0,children:[(0,T.jsx)(`summary`,{children:`loadpath.yml`}),(0,T.jsx)(O,{config:a,busy:t,onSave:s,onWaiver:c})]}):null,(0,T.jsxs)(`details`,{className:`section`,open:!0,children:[(0,T.jsx)(`summary`,{children:`Types`}),(0,T.jsx)(`table`,{className:`type-table`,children:(0,T.jsx)(`tbody`,{children:Object.entries(e.type_counts||{}).sort((e,t)=>t[1]-e[1]).slice(0,12).map(([e,t])=>(0,T.jsxs)(`tr`,{children:[(0,T.jsx)(`td`,{children:j(e)}),(0,T.jsx)(`td`,{children:t})]},e))})})]}),(0,T.jsxs)(`div`,{className:`btn-row`,children:[(0,T.jsx)(`button`,{type:`button`,className:`btn`,disabled:t,onClick:n,"data-testid":`btn-full-reindex`,children:`Full reindex`}),(0,T.jsx)(`button`,{type:`button`,className:`btn primary`,disabled:t,onClick:r,children:`Review against this index`})]})]})}function Xm({cards:e}){let t=e||[];return t.length?(0,T.jsxs)(`details`,{className:`section`,open:!0,"data-testid":`deepening-list`,children:[(0,T.jsxs)(`summary`,{children:[`Depth `,(0,T.jsx)(`span`,{className:`count`,children:t.length})]}),(0,T.jsx)(`p`,{className:`muted`,children:`Deepening opportunities: more behaviour behind a smaller interface, at a real seam.`}),t.map(e=>(0,T.jsxs)(`div`,{className:`finding`,"data-testid":`deepening-card`,children:[(0,T.jsx)(`span`,{className:`chip ${e.strength}`,children:A(e.strength)}),e.top?(0,T.jsx)(`span`,{className:`chip`,children:`top`}):null,(0,T.jsx)(`strong`,{children:e.title}),(0,T.jsx)(`div`,{className:`why`,children:e.message}),e.deletion_test?(0,T.jsxs)(`div`,{className:`muted`,children:[`Deletion test: `,e.deletion_test]}):null,e.before&&e.after?(0,T.jsxs)(`div`,{className:`muted`,children:[e.before,` → `,e.after]}):null]},e.rule+e.title))]}):null}Wm(Hm()),(0,v.createRoot)(document.getElementById(`root`)).render((0,T.jsx)(_.StrictMode,{children:(0,T.jsx)(qm,{})}));export{np as a,u as c,rp as i,c as l,tp as n,j as o,ap as r,w as s,Gf as t}; \ No newline at end of file + M${E.x},${E.y}h${E.width}v${E.height}h${-E.width}z`,fillRule:`evenodd`,pointerEvents:`none`})]})})}hf.displayName=`MiniMap`;var gf=(0,_.memo)(hf),_f=e=>t=>e?`${Math.max(1/t.transform[2],1)}`:void 0,vf={[uc.Line]:`right`,[uc.Handle]:`bottom-right`};function yf({nodeId:e,position:t,variant:n=uc.Handle,className:r,style:i=void 0,children:a,color:o,minWidth:s=10,minHeight:c=10,maxWidth:l=Number.MAX_VALUE,maxHeight:u=Number.MAX_VALUE,keepAspectRatio:d=!1,resizeDirection:f,autoScale:p=!0,shouldResize:m,onResizeStart:h,onResize:g,onResizeEnd:v}){let y=Zl(),b=typeof e==`string`?e:y,x=Rc(),S=(0,_.useRef)(null),C=n===uc.Handle,w=q((0,_.useCallback)(_f(C&&p),[C,p]),Pc),E=(0,_.useRef)(null),D=t??vf[n];(0,_.useEffect)(()=>{if(!(!S.current||!b))return E.current||=xc({domNode:S.current,nodeId:b,getStoreItems:()=>{let{nodeLookup:e,transform:t,snapGrid:n,snapToGrid:r,nodeOrigin:i,domNode:a}=x.getState();return{nodeLookup:e,transform:t,snapGrid:n,snapToGrid:r,nodeOrigin:i,paneDomNode:a}},onChange:(e,t)=>{let{triggerNodeChanges:n,nodeLookup:r,parentLookup:i,nodeOrigin:a}=x.getState(),o=[],s={x:e.x,y:e.y},c=r.get(b);if(c&&c.expandParent&&c.parentId){let t=c.origin??a,n=e.width??c.measured.width??0,l=e.height??c.measured.height??0,u=Os([{id:c.id,parentId:c.parentId,rect:{width:n,height:l,...No({x:e.x??c.position.x,y:e.y??c.position.y},{width:n,height:l},c.parentId,r,t)}}],r,i,a);o.push(...u),s.x=e.x?Math.max(t[0]*n,e.x):void 0,s.y=e.y?Math.max(t[1]*l,e.y):void 0}if(s.x!==void 0&&s.y!==void 0){let e={id:b,type:`position`,position:{...s}};o.push(e)}if(e.width!==void 0&&e.height!==void 0){let t={id:b,type:`dimensions`,resizing:!0,setAttributes:f?f===`horizontal`?`width`:`height`:!0,dimensions:{width:e.width,height:e.height}};o.push(t)}for(let e of t){let t={...e,type:`position`};o.push(t)}n(o)},onEnd:({width:e,height:t})=>{let n={id:b,type:`dimensions`,resizing:!1,dimensions:{width:e,height:t}};x.getState().triggerNodeChanges([n])}}),E.current.update({controlPosition:D,boundaries:{minWidth:s,minHeight:c,maxWidth:l,maxHeight:u},keepAspectRatio:d,resizeDirection:f,onResizeStart:h,onResize:g,onResizeEnd:v,shouldResize:m}),()=>{E.current?.destroy()}},[D,s,c,l,u,d,h,g,v,m]);let O=D.split(`-`);return(0,T.jsx)(`div`,{className:z([`react-flow__resize-control`,`nodrag`,...O,n,r]),ref:S,style:{...i,scale:w,...o&&{[C?`backgroundColor`:`borderColor`]:o}},children:a})}(0,_.memo)(yf);var bf={"arch.context":0,"django.app":0,"django.route":1,"django.websocket_route":1,"fastapi.route":1,"django.url_name":2,"django.view":3,"django.viewset_action":3,"django.permission":3,"django.throttle":3,"django.serializer":4,"django.form":4,"graphql.type":4,"fastapi.model":4,"django.serializer_field":5,"django.service":5,"graphql.field":5,"django.model":6,"django.field":7,"django.relation":7,"django.task":8,"django.receiver":8,"django.signal":8,"django.test":8,"django.migration_op":8,"django.admin":8,"django.management_command":8,"django.consumer":8,"django.cache_key":8,"django.feature_flag":8,"django.side_effect":8,"openapi.path":9,"graphql.operation":9,"react.api_client":10,"django.htmx":10,"react.query_key":11,"react.hook":11,"react.feature":11,"react.route":12,"react.page":12,"react.server_action":12,"django.template":12,"react.component":13,"react.context":13,"react.form_schema":14,"react.test":14};function xf(e){return bf[e]??8}var Sf=8;function Cf(e){if(!e.length)return NaN;let t=[...e].sort((e,t)=>e-t),n=Math.floor(t.length/2);return t.length%2?t[n]:(t[n-1]+t[n])/2}function wf(e,t=[]){let n=new Map;if(!e.length)return n;let r=new Map;for(let t of e){let e=xf(t.type),n=r.get(e)??[];n.push(t),r.set(e,n)}let i=[...r.keys()].sort((e,t)=>e-t).map(e=>[...r.get(e)??[]].sort((e,t)=>e.name.localeCompare(t.name)||e.id.localeCompare(t.id))),a=new Set(e.map(e=>e.id)),o=new Map,s=new Map;for(let t of e)o.set(t.id,[]),s.set(t.id,[]);for(let e of t)!a.has(e.src)||!a.has(e.dst)||e.src===e.dst||(s.get(e.src).push(e.dst),o.get(e.dst).push(e.src));let c=new Map;i.forEach((e,t)=>{for(let n of e)c.set(n.id,t)});let l=new Map,u=()=>{for(let e of i)e.forEach((e,t)=>l.set(e.id,t))};u();let d=(e,t)=>{let n=e.map((e,n)=>{let r=Cf(t(e.id).map(e=>l.get(e)).filter(e=>e!==void 0));return{n:e,bary:Number.isNaN(r)?n:r,name:e.name,id:e.id}});return n.sort((e,t)=>e.bary-t.bary||e.name.localeCompare(t.name)||e.id.localeCompare(t.id)),n.map(e=>e.n)},f=e=>t=>c.get(t)===e,p=e.length>400?2:e.length>120?4:Sf;for(let e=0;e(o.get(t)??[]).filter(f(e-1))),u();for(let e=i.length-2;e>=0;e--)i[e]=d(i[e],t=>(s.get(t)??[]).filter(f(e+1))),u()}let m=Math.max(...i.map(e=>e.length),1),h=[],g=0;for(let e=0;ee.id)),r=new Set((i[e+1]??[]).map(e=>e.id)),a=0;if(r.size)for(let e of t)n.has(e.src)&&r.has(e.dst)&&(a+=1);let o=Math.min(120,Math.max(0,(a-2)*12));g+=296+o}return i.forEach((e,t)=>{let r=(m-e.length)*92/2;e.forEach((e,i)=>{n.set(e.id,{x:h[t]??0,y:r+i*92})})}),n}var Tf=[{id:`layers`,label:`Architecture layers`},{id:`flow`,label:`Edge flow`},{id:`tree`,label:`Spanning tree`},{id:`radial`,label:`Radial`},{id:`concentric`,label:`Concentric layers`},{id:`circle`,label:`Circle`},{id:`clusters`,label:`Type clusters`},{id:`grid`,label:`Compact grid`},{id:`force`,label:`Force directed`}],Ef=new Set(Tf.map(e=>e.id)),Df=`loadpath.graphLayout`,Of=8,kf=64,Af=240,jf=296,Mf=92,Nf=new Set([`django.route`,`react.route`,`react.page`,`react.server_action`,`django.task`,`django.migration_op`,`django.permission`,`openapi.path`,`django.consumer`,`django.websocket_route`,`django.template`,`graphql.operation`,`fastapi.route`]);function Pf(e=()=>document.createElement(`canvas`)){try{let t=e(),n=t.getContext(`webgl2`)||t.getContext(`webgl`)||t.getContext(`experimental-webgl`);return n?((n.getExtension?.(`WEBGL_lose_context`))?.loseContext(),!0):!1}catch{return!1}}function Ff(e,t,n){return e===`3d`&&t==null&&n!==!0?`2d`:e}var If=new Set([`django.field`,`django.serializer_field`,`django.relation`,`django.test`,`react.test`,`graphql.field`,`django.url_name`,`django.throttle`]),Lf={"arch.context":`#edf2f4`,"django.app":`#8d99ae`,"django.route":`#4cc9f0`,"django.url_name":`#4cc9f0`,"django.view":`#4895ef`,"django.viewset_action":`#4361ee`,"django.permission":`#7b8cde`,"django.serializer":`#f4a261`,"django.form":`#e9c46a`,"django.serializer_field":`#e9c46a`,"django.service":`#90be6d`,"django.model":`#2a9d8f`,"django.field":`#8ac926`,"django.task":`#e76f51`,"django.receiver":`#e85d04`,"django.signal":`#f4a261`,"django.test":`#6c757d`,"django.admin":`#adb5bd`,"django.migration_op":`#9d4edd`,"django.consumer":`#e76f51`,"django.websocket_route":`#4cc9f0`,"django.template":`#c77dff`,"django.htmx":`#ff6b6b`,"django.cache_key":`#6c757d`,"django.feature_flag":`#f4a261`,"django.side_effect":`#e85d04`,"graphql.type":`#00bbf9`,"graphql.operation":`#00bbf9`,"fastapi.route":`#4cc9f0`,"fastapi.model":`#f4a261`,"openapi.path":`#00bbf9`,"react.api_client":`#ff6b6b`,"react.query_key":`#adb5bd`,"react.hook":`#7b2cbf`,"react.feature":`#9d4edd`,"react.route":`#c77dff`,"react.page":`#c77dff`,"react.server_action":`#e76f51`,"react.component":`#9d4edd`,"react.form_schema":`#ffd166`,"react.test":`#6c757d`},Rf=160,zf=.42,Bf=100,Vf=.45,Hf=.8,Uf={0:`context`,1:`routes`,2:`url names`,3:`views`,4:`serializers`,5:`services`,6:`models`,7:`fields`,8:`jobs / signals`,9:`openapi`,10:`api client`,11:`hooks`,12:`pages`,13:`components`,14:`forms / tests`};function Wf(e){return e.startsWith(`react.`)?`react`:e.startsWith(`openapi.`)||e.startsWith(`graphql.`)||e.startsWith(`fastapi.`)?`stitch`:e.startsWith(`arch.`)?`arch`:`django`}function Gf(e){return Lf[e]?Lf[e]:e.startsWith(`react.`)?`#9d4edd`:e.startsWith(`openapi.`)?`#00bbf9`:`#4a5568`}function Kf(e,t=typeof navigator<`u`&&!!navigator.webdriver){return t?`2d`:e>=90?`3d`:`2d`}function qf(e){return e>=90?`overview`:`full`}function Jf(e,t,n=1){let r=new Set([e]),i=new Set([e]);for(let e=0;en.families.has(Wf(e.type)));n.detail===`overview`&&(r=r.filter(e=>!If.has(e.type)));let i=new Set(r.map(e=>e.id)),a=t.filter(e=>i.has(e.src)&&i.has(e.dst)),o=n.focusId?Jf(n.focusId,a,1):new Set;if(n.neighborhoodOnly&&n.focusId&&o.size){r=r.filter(e=>o.has(e.id));let e=new Set(r.map(e=>e.id));return{nodes:r,edges:a.filter(t=>e.has(t.src)&&e.has(t.dst)),neighborIds:o}}return{nodes:r,edges:a,neighborIds:o}}function Xf(e,t){let n=t.trim().toLowerCase();return n?e.filter(e=>`${e.name} ${e.qualified_name} ${e.type} ${e.file_path||``} ${e.context||``}`.toLowerCase().includes(n)).slice(0,24):[]}function Zf(e,t,n,r){let i=new Set(e.map(e=>e.id));if(!i.has(n))return{nodeIds:new Set,edgeIds:new Set};let a=new Map,o=new Map;for(let e of t){if(!i.has(e.src)||!i.has(e.dst))continue;let t=a.get(e.src)??[];t.push({dst:e.dst,id:e.id}),a.set(e.src,t);let n=o.get(e.dst)??[];n.push({src:e.src,id:e.id}),o.set(e.dst,n)}let s=new Set(e.filter(e=>Nf.has(e.type)).map(e=>e.id)),c=r&&i.has(r)?new Set([r]):s.size?s:i,l=new Set,u=[n];for(;u.length;){let e=u.pop();if(!l.has(e)){l.add(e);for(let t of a.get(e)??[])l.has(t.dst)||u.push(t.dst)}}let d=new Set([n]),f=[...c].filter(e=>l.has(e)),p=new Set(f);for(;f.length;){let e=f.pop();d.add(e);for(let t of o.get(e)??[])l.has(t.src)&&!p.has(t.src)&&(p.add(t.src),f.push(t.src))}let m=new Set;for(let e of t)d.has(e.src)&&d.has(e.dst)&&m.add(e.id);return{nodeIds:d,edgeIds:m}}var Qf=16,$f=28;function ep(e){return(e.context||``).trim()}function tp(e){return e.confidence!e&&t?1:e&&!t?-1:e.localeCompare(t));let s=new Map(a.map((e,t)=>[e,t])),c=(a.length-1)/2,l=dp(n),u=[...new Set([...r.values()].map(e=>e.x))].sort((e,t)=>e-t),d=new Map(u.map((e,t)=>[e,t]));for(let t of e){let e=r.get(t.id)??{x:0,y:0},n=((s.get(ep(t))??0)-c)*Bf;if(l){let r=d.get(e.x)??0;i.set(t.id,{x:r*Rf,y:-e.y*zf,z:n})}else i.set(t.id,{x:e.x*Vf,y:-e.y*Vf,z:n})}return i}function ip(e){return e===`layers`||e===`flow`?`slab`:e===`radial`||e===`concentric`||e===`circle`?`ring`:`none`}function ap(e,t,n=`layers`){if(!e.length)return[];let r=ip(n);if(r===`none`)return[];if(r===`ring`)return cp(e,t);let i=new Map;for(let n of e){let e=Math.round((t.get(n.id)?.x??0)*10)/10,r=i.get(e)??[];r.push(n),i.set(e,r)}return[...i.entries()].sort((e,t)=>e[0]-t[0]).map(([,e])=>sp(e,t,n))}function op(e,t){let n=new Map;for(let t of e){let e=xf(t.type);n.set(e,(n.get(e)||0)+1)}let r=-1,i=0;for(let[e,t]of n)t>i&&(r=e,i=t);return t===`flow`&&ie[0]-t[0]).map(([,e])=>{let n=0,r=0;for(let i of e){let e=t.get(i.id)??{x:0,y:0,z:0};n+=Math.hypot(e.x,e.y),r+=e.z}let i=n/e.length;return{shape:`ring`,x:0,y:0,z:r/e.length,extentY:0,extentZ:0,radius:i,label:i<12?``:op(e,`radial`),count:e.length}}).filter(e=>e.radius>=12)}function lp(){try{if(typeof localStorage>`u`)return`layers`;let e=localStorage.getItem(Df);return e&&Ef.has(e)?e:`layers`}catch{return`layers`}}function up(e){try{if(typeof localStorage>`u`)return;localStorage.setItem(Df,e)}catch{}}function dp(e){return e===`layers`||e===`flow`}function fp(e){if(!e.length)return NaN;let t=[...e].sort((e,t)=>e-t),n=Math.floor(t.length/2);return t.length%2?t[n]:(t[n-1]+t[n])/2}function pp(e,t){return e.name.localeCompare(t.name)||e.id.localeCompare(t.id)}function mp(e,t){return xf(e.type)-xf(t.type)||pp(e,t)}function hp(e,t,n){e.forEach((r,i)=>{let a=-Math.PI/2+2*Math.PI*i/Math.max(e.length,1);n.set(r.id,{x:Math.cos(a)*t,y:Math.sin(a)*t})})}function gp(e,t){return Math.max(t*jf,e<=1?t===0?0:208:e*Af/(2*Math.PI))}function _p(e,t){let n=new Map;if(!e.length)return n;let r=new Set(e.flat().map(e=>e.id)),i=new Map,a=new Map;for(let t of e.flat())i.set(t.id,[]),a.set(t.id,[]);for(let e of t)!r.has(e.src)||!r.has(e.dst)||e.src===e.dst||(a.get(e.src).push(e.dst),i.get(e.dst).push(e.src));let o=new Map;e.forEach((e,t)=>{for(let n of e)o.set(n.id,t)});let s=new Map,c=()=>{for(let t of e)t.forEach((e,t)=>s.set(e.id,t))};c();let l=(e,t)=>{let n=e.map((e,n)=>{let r=fp(t(e.id).map(e=>s.get(e)).filter(e=>e!==void 0));return{n:e,bary:Number.isNaN(r)?n:r,name:e.name,id:e.id}});return n.sort((e,t)=>e.bary-t.bary||e.name.localeCompare(t.name)||e.id.localeCompare(t.id)),n.map(e=>e.n)},u=e=>t=>o.get(t)===e;for(let t=0;t(i.get(e)??[]).filter(u(t-1))),c();for(let t=e.length-2;t>=0;t--)e[t]=l(e[t],e=>(a.get(e)??[]).filter(u(t+1))),c()}let d=Math.max(...e.map(e=>e.length),1);return e.forEach((e,t)=>{let r=(d-e.length)*92/2;e.forEach((e,i)=>{n.set(e.id,{x:t*296,y:r+i*92})})}),n}function vp(e,t){let n=new Set(e.map(e=>e.id)),r=Math.max(e.length-1,0),i=new Map;for(let t of e)i.set(t.id,0);for(let a=0;a(i.get(a.dst)||0)&&(i.set(a.dst,t),e=!0)}if(!e)break}let a=new Map;for(let t of e){let e=i.get(t.id)||0,n=a.get(e)??[];n.push(t),a.set(e,n)}return _p([...a.keys()].sort((e,t)=>e-t).map(e=>(a.get(e)??[]).sort(pp)),t)}function yp(e,t){let n=new Map;if(!e.length)return n;let r=new Set(e.map(e=>e.id)),i=new Map,a=new Map;for(let t of e)i.set(t.id,[]),a.set(t.id,0);for(let e of t)!r.has(e.src)||!r.has(e.dst)||e.src===e.dst||(i.get(e.src).push(e.dst),i.get(e.dst).push(e.src),a.set(e.src,(a.get(e.src)||0)+1),a.set(e.dst,(a.get(e.dst)||0)+1));let o=[...e].sort((e,t)=>(a.get(t.id)||0)-(a.get(e.id)||0)||pp(e,t))[0]??e[0],s=new Map,c=[[o]];s.set(o.id,0);let l=[o];for(;l.length;){let t=l.shift(),n=s.get(t.id)||0,r=(i.get(t.id)??[]).map(t=>e.find(e=>e.id===t)).filter(e=>!!e).sort(pp);for(let e of r){if(s.has(e.id))continue;s.set(e.id,n+1);let t=c[n+1]??[];t.push(e),c[n+1]=t,l.push(e)}}let u=e.filter(e=>!s.has(e.id)).sort(pp);return u.length&&c.push(u),c.forEach((e,t)=>{if(t===0&&e.length===1){n.set(e[0].id,{x:0,y:0});return}let r=Math.max(t*296,e.length<=1?208:e.length*240/(2*Math.PI));e.forEach((t,i)=>{let a=-Math.PI/2+2*Math.PI*i/e.length;n.set(t.id,{x:Math.cos(a)*r,y:Math.sin(a)*r})})}),n}function bp(e){let t=new Map,n=[...e].sort((e,t)=>xf(e.type)-xf(t.type)||pp(e,t)),r=Math.max(1,Math.ceil(Math.sqrt(n.length)));return n.forEach((e,n)=>{t.set(e.id,{x:n%r*296,y:Math.floor(n/r)*92})}),t}function xp(e){let t=new Map,n=[...e].sort(mp);return n.length<=1?(n[0]&&t.set(n[0].id,{x:0,y:0}),t):(hp(n,gp(n.length,1),t),t)}function Sp(e){let t=new Map;if(!e.length)return t;let n=new Map;for(let t of e){let e=xf(t.type),r=n.get(e)??[];r.push(t),n.set(e,r)}return[...n.keys()].sort((e,t)=>e-t).forEach((e,r)=>{let i=(n.get(e)??[]).sort(pp);if(r===0&&i.length===1){t.set(i[0].id,{x:0,y:0});return}hp(i,gp(i.length,r===0?1:r),t)}),t}function Cp(e){let t=new Map;if(!e.length)return t;let n=new Map;for(let t of e){let e=n.get(t.type)??[];e.push(t),n.set(t.type,e)}let r=[...n.keys()].sort((e,t)=>xf(e)-xf(t)||e.localeCompare(t)).map(e=>{let t=(n.get(e)??[]).sort(pp),r=Math.max(1,Math.ceil(Math.sqrt(t.length))),i=Math.ceil(t.length/r);return{members:t,cols:r,width:Math.max(0,r-1)*jf,height:Math.max(0,i-1)*Mf}}),i=Math.max(...r.map(e=>Math.hypot(e.width,e.height)/2+208),208),a=r.length<=1?0:Math.max(jf,r.length*(i*2+88)/(2*Math.PI));return r.forEach((e,n)=>{let i=r.length===1?0:-Math.PI/2+2*Math.PI*n/r.length,o=Math.cos(i)*a,s=Math.sin(i)*a;e.members.forEach((n,r)=>{let i=r%e.cols,a=Math.floor(r/e.cols);t.set(n.id,{x:o-e.width/2+i*jf,y:s-e.height/2+a*Mf})})}),t}function wp(e,t){let n=new Map;if(!e.length)return n;let r=new Map(e.map(e=>[e.id,e])),i=new Set(r.keys()),a=new Map,o=new Map;for(let t of e)a.set(t.id,[]),o.set(t.id,0);for(let e of t)!i.has(e.src)||!i.has(e.dst)||e.src===e.dst||(a.get(e.src).push(e.dst),o.set(e.dst,(o.get(e.dst)||0)+1));for(let[e,t]of a){let n=[...new Set(t)];n.sort((e,t)=>pp(r.get(e),r.get(t))),a.set(e,n)}let s=e.filter(e=>(o.get(e.id)||0)===0).sort(pp);if(!s.length){let t=[...e].sort((e,t)=>(a.get(t.id)?.length||0)-(a.get(e.id)?.length||0)||pp(e,t))[0];s.push(t)}let c=new Set,l=new Map;for(let t of e)l.set(t.id,[]);let u=e=>{c.add(e);for(let t of a.get(e)??[])c.has(t)||(l.get(e).push(t),u(t))};for(let e of s)c.has(e.id)||u(e.id);for(let t of[...e].sort(pp))c.has(t.id)||(s.push(t),u(t.id));let d=0,f=(e,t)=>{let r=l.get(e)??[];if(!r.length){n.set(e,{x:d*jf,y:t*Mf}),d+=1;return}let i=d;for(let e of r)f(e,t+1);n.set(e,{x:(i+d-1)/2*jf,y:t*Mf})};for(let e of s)n.has(e.id)||f(e.id,0);return n}function Tp(e,t){for(let n=0;n<8;n++)for(let n=0;ne.id)),s=[],c=new Set;for(let e of t){if(!o.has(e.src)||!o.has(e.dst)||e.src===e.dst)continue;let t=e.src[e.id,e])),i=[];Ap.has(e.type)&&i.push(`sink`),jp.has(e.type)&&i.push(`contract`);let a=e.extra??{};a.inferred&&i.push(`inferred`),a.generated&&i.push(`generated`),a.mutation&&i.push(`mutation`),a.fbv&&i.push(`function view`),a.ninja&&i.push(`ninja`),a.ninja_schema&&i.push(`ninja schema`),a.next_app&&i.push(`app router`),a.typed_client&&i.push(String(a.typed_client)),a.e2e&&i.push(`e2e`),a.filterset===!0&&i.push(`filterset`);let o=n.filter(t=>t.dst===e.id),s=n.filter(t=>t.src===e.id),c=o.slice(0,Op).map(e=>Hp(e,r,e.src)),l=s.slice(0,Op).map(e=>Hp(e,r,e.dst)),u=e.file_path?`${e.file_path}${e.start_line?`:${e.start_line}`:``}`:void 0,d={type:e.type,typeLabel:k(j(e.type)),layer:Uf[xf(e.type)]??`other`,purpose:Rp(e.type),name:e.name,qualifiedName:e.qualified_name,file:u,context:e.context,roles:i,facts:Up(a).filter(t=>t.key!==`app`||t.value!==e.context),inputs:c,outputs:l,extraInputs:Math.max(0,o.length-Op),extraOutputs:Math.max(0,s.length-Op),degreeIn:o.length,degreeOut:s.length,inputKinds:Bp(o.map(e=>Hp(e,r,e.src))),outputKinds:Bp(s.map(e=>Hp(e,r,e.dst))),pathSummary:``};return d.pathSummary=Vp(d),d}function Bp(e){let t=new Map;for(let n of e){let e=n.edgeLabel||n.edgeType.replaceAll(`_`,` `);t.set(e,(t.get(e)||0)+1)}return[...t.entries()].sort((e,t)=>t[1]-e[1]||e[0].localeCompare(t[0])).map(([e,t])=>({label:e,count:t}))}function Vp(e){let t=e.inputKinds.map(e=>`${e.label} ×${e.count}`).join(`, `),n=e.outputKinds.map(e=>`${e.label} ×${e.count}`).join(`, `);return t&&n?`${t} → this → ${n}`:n?`this → ${n}`:t?`${t} → this`:``}function Hp(e,t,n){let r=t.get(n),i=n.includes(`:`)?n.slice(n.indexOf(`:`)+1):n;return{id:n,name:r?.name||i,type:r?.type||``,typeLabel:r?k(j(r.type)):``,edgeType:e.type,edgeLabel:k(e.type),inferred:e.confidence<.8}}function Up(e){let t=[...Pp.filter(t=>t in e),...Object.keys(e).filter(e=>!Pp.includes(e)&&!Fp.has(e))],n=[],r=new Set;for(let i of t){if(r.has(i)||Fp.has(i)||Lp.has(i))continue;r.add(i);let t=Wp(i,e[i]);t!=null&&n.push({key:i,label:Np[i]??k(i),value:t})}return n}function Wp(e,t){if(t==null)return null;if(typeof t==`boolean`)return!t&&!Ip.has(e)?null:t?`yes`:`no`;if(typeof t==`number`)return String(t);if(typeof t==`string`)return t.trim()||null;if(Array.isArray(t)){if(t.some(e=>e&&typeof e==`object`))return Gp(e,t);let n=t.map(e=>typeof e==`string`||typeof e==`number`?String(e):``).filter(Boolean);if(!n.length)return null;let r=n.slice(0,kp),i=n.length-r.length;return i>0?`${r.join(`, `)} +${i} more`:r.join(`, `)}return null}function Gp(e,t){let n=t.slice(0,4).map(t=>{if(e===`nplusone`){let e=String(t.queryset||`queryset`),n=Array.isArray(t.accessed)?t.accessed.join(`.`):``,r=t.line?` L${t.line}`:``;return n?`${e} → ${n}${r}`:`${e}${r}`}if(e===`lookups`){let e=Array.isArray(t.fields)?t.fields.join(`, `):``,n=String(t.kind||`filter`);return e?`${n} ${e}`:n}return Object.entries(t).filter(([,e])=>e!=null&&(typeof e==`string`||typeof e==`number`)).slice(0,3).map(([e,t])=>`${e}=${t}`).join(` `)});if(!n.some(Boolean))return null;let r=t.length-n.length;return r>0?`${n.join(`; `)} +${r} more`:n.join(`; `)}var Kp=12,qp=.2,Jp=20,Yp=64;function Xp(e,t,n){let r=n??wf(e,t),i=[...new Set([...r.values()].map(e=>e.x))].sort((e,t)=>e-t),a=[];for(let e of t){let t=r.get(e.src),n=r.get(e.dst);if(!t||!n)continue;let i=t.y+32,o=n.y+32;if(Math.abs(i-o)e.y0-t.y0||e.y1-t.y1||e.id.localeCompare(t.id)),n=$p(t),r=Math.max(0,...n.values())+1,a=t[0].sourceX,o=Zp(i,a);for(let e of t){let t=em(n.get(e.id)??0,r),i=a+Jp+Math.max(1,o-40)*t;s.set(e.id,Qp(e.sourceX,e.targetX,i))}}return s}function Zp(e,t){let n=t-208,r=e.find(e=>e>n+1);return r===void 0?88:Math.max(88,r-t)}function Qp(e,t,n){let r=t-e-40;return r<1?.5:Math.min(1,Math.max(0,(n-e-Jp)/r))}function $p(e){let t=[],n=new Map;for(let r of e){let e=-1;for(let n=0;nt[n]+Yp){e=n;break}e<0?(e=t.length,t.push(r.y1)):t[e]=Math.max(t[e],r.y1),n.set(r.id,e)}return n}function em(e,t){return t<=1?.5:qp+.6000000000000001*e/(t-1)}var tm=`modulepreload`,nm=function(e,t){return new URL(e,t).href},rm={},im=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?import.meta.resolve(e):new URL(e,import.meta.url).href}r=o(t.map(t=>{if(t=nm(t,n),t=s(t),t in rm)return;rm[t]=!0;let r=t.endsWith(`.css`);for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}let i=document.createElement(`link`);if(i.rel=r?`stylesheet`:tm,r||(i.as=`script`),i.crossOrigin=``,i.href=t,a&&i.setAttribute(`nonce`,a),document.head.appendChild(i),r)return new Promise((e,n)=>{i.addEventListener(`load`,e),i.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},am=new Set,om=(0,_.lazy)(()=>im(()=>import(`./LayeredGraph3D-CXyrC80G.js`).then(e=>({default:e.LayeredGraph3D})),[],import.meta.url)),sm=class extends _.Component{state={failed:!1};static getDerivedStateFromError(){return{failed:!0}}render(){return this.state.failed?this.props.fallback:this.props.children}},cm=(0,T.jsx)(`p`,{className:`muted graph-3d-hint`,"data-testid":`graph-3d-fallback`,children:`WebGL is unavailable in this browser, so the 3D view cannot start. Switch back to 2D map.`}),lm={cheap:`var(--edge-cheap)`,expensive:`var(--edge-expensive)`,critical:`var(--edge-critical)`},um={n:W.Top,e:W.Right,s:W.Bottom,w:W.Left};function dm(e,t){let n=t.x-e.x,r=t.y-e.y;return Math.abs(n)>=Math.abs(r)?n>=0?{source:`e`,target:`w`}:{source:`w`,target:`e`}:r>=0?{source:`s`,target:`n`}:{source:`n`,target:`s`}}function fm({data:e,selected:t}){let n=(e.roles||[]).map(e=>`role-${e}`).join(` `);return(0,T.jsxs)(`div`,{className:[`lp-node`,t?`selected`:``,e.dim?`dim`:``,n].filter(Boolean).join(` `),children:[[`n`,`e`,`s`,`w`].map(e=>(0,T.jsx)(au,{id:`tgt-${e}`,type:`target`,position:um[e],isConnectable:!1},`tgt-${e}`)),(0,T.jsx)(`div`,{className:`t`,children:j(e.type)}),(0,T.jsx)(`div`,{className:`n`,title:e.name,children:N(e.name)}),[`n`,`e`,`s`,`w`].map(e=>(0,T.jsx)(au,{id:`src-${e}`,type:`source`,position:um[e],isConnectable:!1},`src-${e}`))]})}var pm={load:fm},mm=new Set([`django`,`react`,`stitch`,`arch`]);function hm({id:e,sourceX:t,sourceY:n,targetX:r,targetY:i,sourcePosition:a,targetPosition:o,style:s,markerEnd:c,markerStart:l,label:u,labelStyle:d,labelShowBg:f,labelBgStyle:p,labelBgPadding:m,labelBgBorderRadius:h,data:g,interactionWidth:_}){let[v,y,b]=ss({sourceX:t,sourceY:n,sourcePosition:a,targetX:r,targetY:i,targetPosition:o,borderRadius:8,stepPosition:g?.stepPosition??.5});return(0,T.jsx)(zu,{id:e,path:v,labelX:y,labelY:b,label:u,labelStyle:d,labelShowBg:f,labelBgStyle:p,labelBgPadding:m,labelBgBorderRadius:h,style:s,markerEnd:c,markerStart:l,interactionWidth:_})}var gm={loadstep:hm};function _m({topologyKey:e}){let{fitView:t}=Il();return(0,_.useEffect)(()=>{let e=0,n=requestAnimationFrame(()=>{e=requestAnimationFrame(()=>{t({padding:.2,maxZoom:1.15})})});return()=>{cancelAnimationFrame(n),cancelAnimationFrame(e)}},[t,e]),null}function vm(e,t,n=null,r={}){let i=new Map(e.map(e=>[e.id,e])),a=r.layout??`layers`,o=dp(a),s=Dp(e,t,a),c=Xp(e,t,s);return{rfNodes:e.map(e=>{let t=r.roles?.[e.id]||[],i=!!r.testOverlay&&!t.includes(`tested`)&&!t.includes(`untested`)&&!t.includes(`test`)&&!t.includes(`seed`);return{id:e.id,type:`load`,position:s.get(e.id)??{x:0,y:0},data:{name:e.name,type:e.type,file:e.file_path,roles:t,dim:i},selected:n===e.id,sourcePosition:W.Right,targetPosition:W.Left,width:208,height:64,style:{width:208,height:64}}}),rfEdges:t.filter(e=>i.has(e.src)&&i.has(e.dst)).map(e=>{let t=lm[e.weight]||`var(--edge-cheap)`,r=!!(n&&(e.src===n||e.dst===n)),i=s.get(e.src)??{x:0,y:0},a=s.get(e.dst)??{x:0,y:0},l=o?{source:`e`,target:`w`}:dm(i,a);return{id:e.id,source:e.src,target:e.dst,sourceHandle:`src-${l.source}`,targetHandle:`tgt-${l.target}`,sourcePosition:um[l.source],targetPosition:um[l.target],type:o?`loadstep`:`default`,animated:e.weight===`critical`,data:{stepPosition:c.get(e.id)??.5},style:{stroke:t,strokeWidth:e.weight===`critical`?2.4:1.2,strokeDasharray:e.confidence<.8?`6 4`:void 0},markerEnd:{type:Ka.ArrowClosed,width:14,height:14,color:t},label:r?e.type.replaceAll(`_`,` `):void 0,labelStyle:r?{fill:`var(--ink)`,fontSize:10,fontWeight:600}:void 0,labelBgStyle:r?{fill:`var(--graph-bg)`,fillOpacity:.92}:void 0,labelBgPadding:r?[3,5]:void 0,labelBgBorderRadius:r?4:void 0}})}}function ym({node:e,nodes:t,edges:n,onClose:r,onWhatIf:i,onSelect:a,onOpenFile:o,pinned:s,onPin:c,onIsolate:l}){let u=zp(e,t,n);return(0,_.useEffect)(()=>{let e=e=>{e.key===`Escape`&&r()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[r]),(0,T.jsxs)(`aside`,{className:`inspector`,"data-testid":`graph-inspector`,children:[(0,T.jsxs)(`div`,{className:`inspector-head`,children:[(0,T.jsx)(`div`,{className:`t`,children:u.typeLabel}),(0,T.jsx)(`div`,{className:`inspector-roles`,children:u.roles.map(e=>(0,T.jsx)(`span`,{className:`inspector-chip`,children:e},e))}),(0,T.jsx)(`button`,{type:`button`,className:`inspector-close`,"data-testid":`graph-inspector-close`,"aria-label":`Close inspector`,onClick:r,children:`×`})]}),(0,T.jsx)(`div`,{className:`n`,children:N(u.name)}),(0,T.jsx)(`p`,{className:`inspector-purpose`,"data-testid":`graph-inspector-purpose`,children:u.purpose}),u.context?(0,T.jsx)(`div`,{className:`muted`,children:N(u.context)}):null,u.file?(0,T.jsxs)(`div`,{className:`file-row`,children:[(0,T.jsx)(`div`,{className:`file`,children:N(u.file)}),o&&e.file_path?(0,T.jsx)(`button`,{type:`button`,className:`btn`,"data-testid":`btn-open-editor`,onClick:()=>o(e.file_path,e.start_line),children:`Open in editor`}):null]}):null,(0,T.jsx)(`div`,{className:`muted`,children:N(u.qualifiedName)}),(0,T.jsxs)(`div`,{className:`muted inspector-layer`,children:[`layer · `,u.layer]}),(0,T.jsxs)(`div`,{className:`muted inspector-degree`,"data-testid":`graph-inspector-degree`,children:[u.degreeIn,` in · `,u.degreeOut,` out`]}),u.pathSummary?(0,T.jsx)(`p`,{className:`inspector-path`,"data-testid":`graph-inspector-path`,children:u.pathSummary}):null,u.facts.length?(0,T.jsx)(`dl`,{className:`inspector-facts`,"data-testid":`graph-inspector-facts`,children:u.facts.map(e=>(0,T.jsxs)(`div`,{className:`inspector-fact`,children:[(0,T.jsx)(`dt`,{children:e.label}),(0,T.jsx)(`dd`,{children:N(e.value)})]},e.key))}):null,(0,T.jsx)(bm,{title:`Inputs`,testId:`graph-inspector-inputs`,links:u.inputs,extra:u.extraInputs,empty:`Nothing in this graph points here.`,onSelect:a}),(0,T.jsx)(bm,{title:`Outputs`,testId:`graph-inspector-outputs`,links:u.outputs,extra:u.extraOutputs,empty:`This node does not point at anything in this graph.`,onSelect:a}),i?(0,T.jsx)(`p`,{className:`whatif-hint`,"data-testid":`whatif-hint`,children:l?`Walks a new path from this node with no git range. Isolate (next) only hides the rest of this map.`:`Walks a new path from this node with no git range — as if this changed, regardless of Base/Head.`}):null,(0,T.jsxs)(`div`,{className:`btn-row`,children:[i?(0,T.jsx)(`button`,{type:`button`,className:`btn`,"data-testid":`btn-whatif`,title:`Start a hypothetical walk from this node. Does not use Base/Head.`,onClick:()=>i(e.id),children:`What if this changes`}):null,l?(0,T.jsx)(`button`,{type:`button`,className:`btn`,"data-testid":`btn-isolate`,title:`Hide nodes that are not on a path from here to a sink. Does not start a new walk.`,onClick:()=>l(e.id),children:`Isolate path to sinks`}):null,c?(0,T.jsx)(`button`,{type:`button`,className:s?`btn primary`:`btn`,"data-testid":`btn-pin-node`,onClick:()=>c(s?null:e.id),children:s?`Unpin`:`Pin`}):null]})]})}function bm({title:e,testId:t,links:n,extra:r,empty:i,onSelect:a}){return(0,T.jsxs)(`section`,{className:`inspector-section`,"data-testid":t,children:[(0,T.jsxs)(`h3`,{children:[e,(0,T.jsx)(`span`,{className:`count`,children:n.length+r})]}),n.length?(0,T.jsx)(`ul`,{children:n.map((e,t)=>(0,T.jsx)(`li`,{children:a?(0,T.jsxs)(`button`,{type:`button`,className:`inspector-link`,onClick:()=>a(e.id),children:[(0,T.jsx)(`span`,{className:`inspector-link-name`,title:e.name,children:N(e.name)}),(0,T.jsxs)(`span`,{className:`inspector-link-meta`,children:[e.typeLabel?`${e.typeLabel} · `:``,e.edgeLabel,e.inferred?` · inferred`:``]})]}):(0,T.jsxs)(T.Fragment,{children:[(0,T.jsx)(`span`,{className:`inspector-link-name`,title:e.name,children:N(e.name)}),(0,T.jsxs)(`span`,{className:`inspector-link-meta`,children:[e.typeLabel?`${e.typeLabel} · `:``,e.edgeLabel,e.inferred?` · inferred`:``]})]})},`${e.edgeType}:${e.id}:${t}`))}):(0,T.jsx)(`p`,{className:`muted`,children:i}),r?(0,T.jsxs)(`p`,{className:`muted`,children:[`+`,r,` more`]}):null]})}function xm({nodes:e,edges:t,onWhatIf:n,focusPath:r,selectedId:i,onSelect:a,nodeRoles:o,testOverlay:s=!1,isolateSource:c,onIsolate:l,repoPath:u,onOpenFile:d,pinnedId:f,onPin:p}){let[m,h]=(0,_.useState)(null),g=i===void 0?m:i,v=e=>{i===void 0&&h(e),a?.(e)},[y,b]=(0,_.useState)(null),[x,S]=(0,_.useState)(null),[C,w]=(0,_.useState)(()=>lp()),[E,D]=(0,_.useState)(new Set(mm)),[O,k]=(0,_.useState)(!1),[A,M]=(0,_.useState)(``),[ee,N]=(0,_.useState)(!1),[P,F]=(0,_.useState)(null),I=typeof window<`u`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches;(0,_.useEffect)(()=>{let e=()=>F(Pf());if(typeof window.requestIdleCallback==`function`){let t=window.requestIdleCallback(e);return()=>window.cancelIdleCallback(t)}let t=window.setTimeout(e,0);return()=>window.clearTimeout(t)},[]);let te=Ff(y??Kf(e.length),y,P),ne=x??qf(e.length),L=O?g:null,re=(0,_.useMemo)(()=>c?Zf(e,t,c):null,[e,t,c]),R=re?e.filter(e=>re.nodeIds.has(e.id)):e,z=re?t.filter(e=>re.edgeIds.has(e.id)):t,B=(0,_.useMemo)(()=>Yf(R,z,{detail:ne,families:E,focusId:L,neighborhoodOnly:!!L}),[R,z,ne,E,L]),V=(0,_.useMemo)(()=>`${C}|${B.nodes.map(e=>e.id).join(`\0`)}|${B.edges.map(e=>e.id).join(`\0`)}`,[C,B.nodes,B.edges]),ie=g?e.find(e=>e.id===g)??null:null,{rfNodes:ae,rfEdges:oe}=(0,_.useMemo)(()=>{let e=vm(B.nodes,B.edges,g,{roles:o,testOverlay:s,layout:C});return I&&(e.rfEdges=e.rfEdges.map(e=>({...e,animated:!1}))),e},[B.nodes,B.edges,g,I,o,s,C]);(0,_.useEffect)(()=>{if(!r)return;let t=e.find(e=>e.file_path===r);t&&v(t.id)},[r,e]);let se=(0,_.useMemo)(()=>Xf(e,A),[e,A]),ce=(e,t)=>{v(t.id)},le=()=>{v(null),k(!1)},ue=ie?(0,T.jsx)(ym,{node:ie,nodes:e,edges:t,onClose:le,onWhatIf:n,onSelect:v,onOpenFile:d,pinned:f===ie.id,onPin:p,onIsolate:l?e=>{l(c===e?null:e)}:void 0}):null,de=e=>{D(t=>{let n=new Set(t);if(n.has(e)){if(n.size===1)return t;n.delete(e)}else n.add(e);return n})},fe=(0,_.useMemo)(()=>{let t=new Set;for(let n of e)t.add(Wf(n.type));return t},[e]),pe=e.length-B.nodes.length;return(0,T.jsxs)(`div`,{className:`impact-graph`,style:{flex:1,minHeight:0,position:`relative`,display:`flex`,flexDirection:`column`},children:[(0,T.jsxs)(`div`,{className:`graph-toolbar`,"data-testid":`graph-toolbar`,children:[(0,T.jsxs)(`div`,{className:`seg`,"aria-label":`Graph projection`,children:[(0,T.jsx)(`button`,{type:`button`,"data-testid":`graph-view-2d`,className:te===`2d`?`active`:``,"aria-pressed":te===`2d`,onClick:()=>b(`2d`),children:`2D map`}),(0,T.jsx)(`button`,{type:`button`,"data-testid":`graph-view-3d`,className:te===`3d`?`active`:``,"aria-pressed":te===`3d`,onClick:()=>b(`3d`),children:`3D layers`})]}),(0,T.jsxs)(`div`,{className:`seg`,"aria-label":`Graph detail`,children:[(0,T.jsx)(`button`,{type:`button`,"data-testid":`graph-detail-overview`,className:ne===`overview`?`active`:``,"aria-pressed":ne===`overview`,onClick:()=>S(`overview`),children:`Overview`}),(0,T.jsx)(`button`,{type:`button`,"data-testid":`graph-detail-full`,className:ne===`full`?`active`:``,"aria-pressed":ne===`full`,onClick:()=>S(`full`),children:`Full`})]}),(0,T.jsx)(`div`,{className:`seg`,"aria-label":`Graph families`,children:[`django`,`stitch`,`react`].filter(e=>fe.has(e)).map(e=>(0,T.jsx)(`button`,{type:`button`,"data-testid":`graph-family-${e}`,className:E.has(e)?`active`:``,"aria-pressed":E.has(e),onClick:()=>de(e),children:e},e))}),(0,T.jsxs)(`label`,{className:`graph-layout`,children:[`Layout`,(0,T.jsx)(`select`,{id:`graph-layout`,"data-testid":`graph-layout`,value:C,"aria-label":`Graph layout algorithm`,onChange:e=>{let t=Tf.find(t=>t.id===e.target.value)?.id;t&&(w(t),up(t))},children:Tf.map(e=>(0,T.jsx)(`option`,{value:e.id,children:e.label},e.id))})]}),(0,T.jsx)(`button`,{type:`button`,className:O?`chip-btn active`:`chip-btn`,"data-testid":`graph-neighborhood`,disabled:!g,onClick:()=>k(e=>!e),children:O?`Neighborhood`:`Focus neighbors`}),c?(0,T.jsx)(`button`,{type:`button`,className:`chip-btn active`,"data-testid":`graph-isolate-clear`,onClick:()=>l?.(null),children:`Path isolate`}):null,(0,T.jsxs)(`label`,{className:`graph-search`,children:[(0,T.jsx)(`span`,{className:`sr-only`,children:`Search nodes`}),(0,T.jsx)(`input`,{"data-testid":`graph-search`,placeholder:`Find a node`,value:A,onChange:e=>{M(e.target.value),N(!0)},onFocus:()=>N(!0),onBlur:()=>window.setTimeout(()=>N(!1),150)}),ee&&A.trim()&&se.length?(0,T.jsx)(`ul`,{className:`graph-search-hits`,"data-testid":`graph-search-hits`,children:se.map(e=>(0,T.jsx)(`li`,{children:(0,T.jsxs)(`button`,{type:`button`,onMouseDown:e=>e.preventDefault(),onClick:()=>{v(e.id),M(``),N(!1)},children:[e.name,(0,T.jsx)(`span`,{className:`muted`,children:j(e.type)})]})},e.id))}):null]}),(0,T.jsxs)(`span`,{className:`muted graph-count`,children:[B.nodes.length,` nodes · `,B.edges.length,` edges`,pe?` · ${pe} hidden`:``]})]}),(0,T.jsx)(`div`,{className:`graph-stage`,children:e.length===0?(0,T.jsxs)(`div`,{className:`empty graph-walk-empty`,"data-testid":`graph-walk-empty`,children:[(0,T.jsx)(`h2`,{children:`No typed nodes on this walk`}),(0,T.jsx)(`p`,{children:`This range did not hit models, views, routes, or React pages Loadpath extracts. Open the architecture map for the indexed graph.`})]}):te===`3d`?(0,T.jsxs)(`div`,{className:`graph-3d`,"data-testid":`graph-3d`,children:[(0,T.jsx)(`p`,{className:`graph-3d-hint`,children:`Same layout as the 2D map, with bounded context on the depth axis. Dashed edges are inferred. Drag to orbit, scroll to zoom, click a node to inspect it.`}),P===!1?cm:P===null?(0,T.jsx)(`p`,{className:`muted graph-3d-hint`,children:`Loading 3D layers…`}):(0,T.jsx)(sm,{fallback:cm,children:(0,T.jsx)(_.Suspense,{fallback:(0,T.jsx)(`p`,{className:`muted graph-3d-hint`,children:`Loading 3D layers…`}),children:(0,T.jsx)(om,{nodes:B.nodes,edges:B.edges,selectedId:g,neighborIds:L?B.neighborIds:am,layout:C,nodeRoles:o,testOverlay:s,onSelect:e=>{v(e),e||k(!1)}})})}),ue]}):(0,T.jsxs)(Md,{children:[(0,T.jsxs)(Id,{nodes:ae,edges:oe,nodeTypes:pm,edgeTypes:gm,fitView:!1,minZoom:.25,nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!0,deleteKeyCode:null,onNodeClick:ce,onPaneClick:le,onlyRenderVisibleElements:ae.length>=90,proOptions:{hideAttribution:!1},"data-testid":`impact-graph`,children:[(0,T.jsx)(_m,{topologyKey:V}),(0,T.jsx)(Ud,{}),(0,T.jsx)(gf,{pannable:!0,zoomable:!0,ariaLabel:`Impact graph overview`,nodeColor:`var(--muted)`,nodeStrokeColor:`transparent`,nodeStrokeWidth:0,maskColor:`rgba(0, 0, 0, 0.45)`,maskStrokeColor:`var(--accent)`,maskStrokeWidth:1.4,bgColor:`var(--graph-bg)`,style:{width:184,height:128}}),(0,T.jsx)(Qd,{})]}),ue]})})]})}function Sm(e){return(0,T.jsx)(sm,{fallback:(0,T.jsx)(`p`,{className:`muted graph-3d-hint`,"data-testid":`graph-crash-fallback`,children:`The graph failed to render. Switch to 2D map or another layout.`}),children:(0,T.jsx)(xm,{...e})})}function Cm(){let e=localStorage.getItem(`loadpath.editor`)||`auto`;return e===`cursor`||e===`vscode`||e===`system`?e:`auto`}function wm(e){localStorage.setItem(`loadpath.editor`,e)}async function Tm(e,t,n,r=Cm()){try{let i=await S.openEditor(e,t,n??void 0,r);if(i.ok)return{ok:!0,message:`Opened ${t} in ${i.opened_with||`editor`}`};let a=i.urls||{},o=r===`vscode`?a.vscode:r===`cursor`?a.cursor:a.cursor||a.vscode;return o?(window.open(o,`_blank`,`noopener,noreferrer`),{ok:!0,message:`Opening ${t} via editor URL`}):{ok:!1,message:i.error||`Could not open editor`}}catch(e){return{ok:!1,message:e instanceof Error?e.message:String(e)}}}var Em=[{value:`HEAD`,label:`HEAD`,group:`preset`},{value:`HEAD~1`,label:`HEAD~1`,group:`preset`}],Dm=[`preset`,`branch`,`tag`,`commit`];function Om(e){if(!e?.git)return[...Em];let t=(e.presets?.length?e.presets:Em.map(e=>e.value)).map(e=>({value:e,label:e,group:`preset`})),n=new Set(t.map(e=>e.value)),r=[...t];for(let t of e.branches||[])n.has(t.name)||(n.add(t.name),r.push({value:t.name,label:t.current?`${t.name} (current)`:t.name,detail:t.subject,group:`branch`}));for(let t of e.tags||[])n.has(t.name)||(n.add(t.name),r.push({value:t.name,label:t.name,detail:t.subject,group:`tag`}));for(let t of e.commits||[])n.has(t.sha)||(n.add(t.sha),r.push({value:t.sha,label:t.short,detail:t.subject,group:`commit`}));return r}function km(e,t){let n=t.trim().toLowerCase();return n?e.filter(e=>e.value.toLowerCase().includes(n)||e.label.toLowerCase().includes(n)||(e.detail||``).toLowerCase().includes(n)):e}function Am(e){return Dm.map(t=>({group:t,items:e.filter(e=>e.group===t)})).filter(e=>e.items.length>0)}function jm(e){return e===`preset`?`Common`:e===`branch`?`Branches`:e===`tag`?`Tags`:`Recent commits`}function Mm({value:e,onChange:t,placeholder:n,testId:r,menuTestId:i,refs:a,onNeedRefs:o}){let s=(0,_.useId)(),c=(0,_.useRef)(null),[l,u]=(0,_.useState)(!1),[d,f]=(0,_.useState)(null),[p,m]=(0,_.useState)(0),h=(0,_.useMemo)(()=>{let e=Om(a);return d===null?e:km(e,d)},[a,d]),g=(0,_.useMemo)(()=>Am(h),[h]);(0,_.useEffect)(()=>{l&&o()},[l,o]),(0,_.useEffect)(()=>{m(0)},[d,l]);let v=()=>{u(!1),f(null)},y=e=>{t(e.value),v()};return(0,T.jsxs)(`div`,{className:`combo`,ref:c,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||v()},children:[(0,T.jsxs)(`div`,{className:`combo-row`,children:[(0,T.jsx)(`input`,{"data-testid":r,value:e,placeholder:n,spellCheck:!1,role:`combobox`,"aria-expanded":l,"aria-controls":s,"aria-autocomplete":`list`,onChange:e=>{t(e.target.value),l&&f(e.target.value)},onKeyDown:e=>{if(e.key===`ArrowDown`){if(e.preventDefault(),!l){u(!0);return}m(e=>Math.min(e+1,Math.max(h.length-1,0)))}else if(e.key===`ArrowUp`){if(e.preventDefault(),!l)return;m(e=>Math.max(e-1,0))}else if(e.key===`Enter`&&l){e.preventDefault();let t=h[p];t&&y(t)}else e.key===`Escape`&&l&&(e.preventDefault(),v())}}),(0,T.jsx)(`button`,{type:`button`,className:`icon-btn combo-toggle`,"data-testid":`${r}-toggle`,"aria-label":`Show recent refs`,"aria-expanded":l,onMouseDown:e=>e.preventDefault(),onClick:()=>l?v():u(!0),children:(0,T.jsx)(R,{})})]}),l?(0,T.jsx)(`div`,{className:`combo-menu`,id:s,role:`listbox`,"data-testid":i,children:g.length===0?(0,T.jsx)(`div`,{className:`combo-empty muted`,children:`No matching refs — the typed value is kept`}):g.map(e=>(0,T.jsxs)(`div`,{className:`combo-group`,children:[(0,T.jsx)(`div`,{className:`combo-heading`,children:jm(e.group)}),e.items.map(e=>{let t=h.indexOf(e);return(0,T.jsxs)(`button`,{type:`button`,role:`option`,"aria-selected":t===p,className:t===p?`combo-option active`:`combo-option`,"data-testid":`ref-option-${e.group}`,onMouseDown:e=>e.preventDefault(),onMouseEnter:()=>m(t),onClick:()=>y(e),children:[(0,T.jsx)(`span`,{className:`combo-label`,children:e.label}),e.detail?(0,T.jsx)(`span`,{className:`combo-detail`,children:e.detail}):null]},`${e.group}:${e.value}`)})]},e.group))}):null]})}function Nm({initialPath:e,onSelect:t,onClose:n}){let[r,i]=(0,_.useState)(null),[a,o]=(0,_.useState)(e),[s,c]=(0,_.useState)(null),[l,u]=(0,_.useState)(``),[d,f]=(0,_.useState)(!1),p=(0,_.useRef)(null),m=(0,_.useRef)(0),h=async e=>{let t=m.current+1;m.current=t,f(!0);try{let n=await S.browse(e);if(m.current!==t)return;i(n),o(n.path),c(n.is_git?n.path:null),u(``)}catch(e){if(m.current!==t)return;u(e instanceof Error?e.message:String(e))}finally{m.current===t&&f(!1)}};(0,_.useEffect)(()=>{h(e),p.current?.focus(),p.current?.select()},[e]);let g=s||r?.path||a,v=s&&s!==r?.path?s.split(/[\\/]/).filter(Boolean).pop():r?.is_git?`this repository`:`this folder`;return(0,T.jsx)(`div`,{className:`modal-backdrop`,"data-testid":`repo-explorer`,"data-overlay":`true`,onClick:n,onKeyDown:e=>{e.key===`Escape`&&(e.preventDefault(),n())},children:(0,T.jsxs)(`div`,{className:`modal`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`explorer-title`,onClick:e=>e.stopPropagation(),children:[(0,T.jsxs)(`div`,{className:`modal-head`,children:[(0,T.jsxs)(`div`,{children:[(0,T.jsx)(`h2`,{id:`explorer-title`,children:`Select repository`}),(0,T.jsx)(`p`,{className:`muted`,children:`Browse to a git root, or paste the full path.`})]}),(0,T.jsx)(`button`,{type:`button`,className:`btn ghost`,"data-testid":`explorer-cancel`,onClick:n,children:`Cancel`})]}),(0,T.jsxs)(`form`,{className:`explorer-path`,onSubmit:e=>{e.preventDefault(),h(a)},children:[(0,T.jsx)(`input`,{ref:p,"data-testid":`explorer-path`,value:a,onChange:e=>o(e.target.value),spellCheck:!1,"aria-label":`Directory path`}),(0,T.jsx)(`button`,{type:`button`,className:`btn`,disabled:!r?.parent,onClick:()=>r?.parent&&void h(r.parent),children:`Up`}),(0,T.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>r&&void h(r.home),children:`Home`}),(0,T.jsx)(`button`,{type:`submit`,className:`btn`,children:`Go`})]}),l?(0,T.jsx)(`div`,{className:`error`,role:`alert`,children:l}):null,(0,T.jsx)(`div`,{className:`explorer-list`,role:`listbox`,"aria-label":`Folders`,"aria-busy":d,children:r?.entries.length?r.entries.map(e=>{let t=s===e.path;return(0,T.jsxs)(`button`,{type:`button`,role:`option`,"aria-selected":t,className:t?`explorer-row active`:`explorer-row`,"data-testid":`explorer-entry`,"data-path":e.path,onClick:()=>c(e.path),onDoubleClick:()=>void h(e.path),children:[(0,T.jsx)(re,{}),(0,T.jsx)(`span`,{className:`explorer-name`,children:e.name}),e.is_git?(0,T.jsx)(`span`,{className:`chip git-badge`,children:`git`}):null]},e.path)}):(0,T.jsx)(`div`,{className:`muted explorer-empty`,children:d?`Loading…`:`No folders here`})}),(0,T.jsxs)(`div`,{className:`modal-foot`,children:[(0,T.jsx)(`span`,{className:`muted explorer-current`,title:g,children:g}),(0,T.jsxs)(`button`,{type:`button`,className:`btn primary`,"data-testid":`explorer-use`,disabled:!g,onClick:()=>g&&t(g),children:[`Use `,v]})]})]})})}var Pm={scan:{start:0,end:20},extract:{start:20,end:88},boot:{start:88,end:94},stitch:{start:94,end:99},skipped:{start:100,end:100},done:{start:100,end:100}},Fm=new Set([`scan`,`extract`,`boot`,`stitch`]);function Im(e){let t=e.phase||``;if(!t||t===`idle`)return null;let n=Pm[t];if(!n)return null;if(n.start===n.end)return n.end;let r=e.total||0;if(r<=0)return n.start;let i=Math.min(1,Math.max(0,(e.done||0)/r));return Math.round(n.start+(n.end-n.start)*i)}function Lm(e){return!e.phase||e.phase===`idle`?null:typeof e.percent==`number`&&Number.isFinite(e.percent)?Math.max(0,Math.min(100,Math.round(e.percent))):Im(e)}var Rm=[{id:`obsidian`,label:`Obsidian`,group:`dark`},{id:`nord`,label:`Nord`,group:`dark`},{id:`solarized-dark`,label:`Solarized Dark`,group:`dark`},{id:`forest`,label:`Forest`,group:`dark`},{id:`rose`,label:`Rose Pine`,group:`dark`},{id:`amber`,label:`Midnight Amber`,group:`dark`},{id:`volcano`,label:`Volcano`,group:`dark`},{id:`lavender`,label:`Lavender`,group:`dark`},{id:`neon-noir`,label:`Neon Noir`,group:`dark`},{id:`synthwave`,label:`Synthwave`,group:`dark`},{id:`phosphor`,label:`Phosphor`,group:`dark`},{id:`aurora`,label:`Aurora`,group:`dark`},{id:`biolume`,label:`Biolume`,group:`dark`},{id:`carbon`,label:`Carbon`,group:`dark`},{id:`paper`,label:`Paper`,group:`light`},{id:`solarized-light`,label:`Solarized Light`,group:`light`},{id:`seafoam`,label:`Seafoam`,group:`light`},{id:`high-contrast`,label:`High Contrast`,group:`light`},{id:`sakura`,label:`Sakura`,group:`light`},{id:`citrus`,label:`Citrus`,group:`light`},{id:`peach`,label:`Peach Fuzz`,group:`light`},{id:`candy`,label:`Cotton Candy`,group:`light`},{id:`sky`,label:`Clear Sky`,group:`light`},{id:`coral`,label:`Coral Reef`,group:`light`}],zm=`obsidian`,Bm=`loadpath.theme`;function Vm(e){return Rm.some(t=>t.id===e)}function Hm(){try{let e=localStorage.getItem(Bm)||``;if(Vm(e))return e}catch{}return zm}function Um(e){return Rm.find(t=>t.id===e)?.group===`light`?`light`:`dark`}function Wm(e){document.documentElement.dataset.theme=e,document.documentElement.style.colorScheme=Um(e);try{localStorage.setItem(Bm,e)}catch{}}var Gm=[{id:`review`,label:`Review`,testId:`tab-review`,shortcut:`1`,icon:F},{id:`architecture`,label:`Architecture`,testId:`tab-architecture`,shortcut:`2`,icon:I},{id:`graph`,label:`Impact graph`,testId:`tab-graph`,shortcut:`3`,icon:te},{id:`prs`,label:`Pull requests`,testId:`tab-prs`,shortcut:`4`,icon:ne},{id:`settings`,label:`Settings`,testId:`tab-settings`,shortcut:`5`,icon:L}];function Km(e,t,n){let r;try{r=new URL(e)}catch{return}if(r.protocol!==`https:`||r.username||r.password)return;let i=r.hostname.toLowerCase();i!==t&&!i.endsWith(`.${t}`)||r.pathname.startsWith(n)&&window.open(r.toString(),`_blank`,`noopener,noreferrer`)}function qm(){let[e,t]=(0,_.useState)(`review`),[n,r]=(0,_.useState)(localStorage.getItem(`loadpath.repo`)||``),[i,a]=(0,_.useState)(localStorage.getItem(`loadpath.base`)||`HEAD~1`),[o,s]=(0,_.useState)(localStorage.getItem(`loadpath.head`)||`HEAD`),[c,l]=(0,_.useState)(null),[u,d]=(0,_.useState)(null),[f,p]=(0,_.useState)(null),[m,h]=(0,_.useState)([]),[g,v]=(0,_.useState)(`review`),[y,b]=(0,_.useState)(``),[x,C]=(0,_.useState)(``),[w,E]=(0,_.useState)(null),[O,k]=(0,_.useState)(!1),[A,M]=(0,_.useState)(!1),[N,P]=(0,_.useState)(``),[F,I]=(0,_.useState)({}),[te,ne]=(0,_.useState)([]),[L,R]=(0,_.useState)([]),[z,B]=(0,_.useState)(localStorage.getItem(`loadpath.scmRepo`)||``),[V,ie]=(0,_.useState)(localStorage.getItem(`loadpath.provider`)||`github`),[ae,oe]=(0,_.useState)(localStorage.getItem(`loadpath.prNumber`)||``),[se,ce]=(0,_.useState)(localStorage.getItem(`loadpath.dirty`)===`1`),[le,ue]=(0,_.useState)(0),[de,fe]=(0,_.useState)(``),[pe,me]=(0,_.useState)(Hm),[he,ge]=(0,_.useState)(!1),[_e,ve]=(0,_.useState)(!1),[ye,be]=(0,_.useState)(!1),[xe,Se]=(0,_.useState)(null),[Ce,we]=(0,_.useState)(null),[Te,Ee]=(0,_.useState)(localStorage.getItem(`loadpath.testOverlay`)===`1`),[De,Oe]=(0,_.useState)(null),[ke,Ae]=(0,_.useState)(localStorage.getItem(`loadpath.watch`)===`1`),[je,Me]=(0,_.useState)([]),[Ne,Pe]=(0,_.useState)(null),[Fe,Ie]=(0,_.useState)(null),[Le,Re]=(0,_.useState)(null),[ze,Be]=(0,_.useState)(()=>{try{return!!(localStorage.getItem(`loadpath.lastReviewId`)&&(localStorage.getItem(`loadpath.repo`)||``).trim())}catch{return!1}}),[Ve,He]=(0,_.useState)(null),[Ue,We]=(0,_.useState)(null),[Ge,Ke]=(0,_.useState)(!1),[qe,Je]=(0,_.useState)(!1),Ye=(0,_.useRef)(n);Ye.current=n;let Xe=(0,_.useRef)(se);Xe.current=se;let Ze=(0,_.useRef)(!1);Ze.current=_e;let Qe=(0,_.useRef)(``),$e=(0,_.useRef)(``),et=e=>{me(e),Wm(e)},tt=(0,_.useRef)(``),H=e=>{tt.current=e,C(e)},nt=e=>{let t=0,n=!1;E(0);let r=()=>{S.indexProgress(e).then(e=>{if(!tt.current)return;if(e.phase&&e.phase!==`idle`&&e.message&&H(e.message),Fm.has(e.phase))n=!0;else if(!n)return;let r=Lm(e);r!=null&&(t=e.phase===`scan`&&!e.done?r:Math.max(t,r),E(t))}).catch(()=>void 0)};r();let i=window.setInterval(r,250);return()=>{window.clearInterval(i),E(null)}};(0,_.useEffect)(()=>{S.settings().then(I).catch(()=>void 0).finally(()=>ge(!0)),S.repos().then(e=>h(e.repos)).catch(()=>void 0)},[]);let rt=()=>n.trim()?!0:(b(`Point at a local repository path first.`),!1);(0,_.useEffect)(()=>{if(e!==`architecture`||!n.trim())return;let t=n,r=!1;return $e.current!==t&&pt(t),S.config(t).then(e=>{!r&&Ye.current===t&&Ie(e)}).catch(()=>void 0),S.architectureHealth(t).then(e=>{!r&&Ye.current===t&&Re(e)}).catch(()=>void 0),()=>{r=!0}},[e,n]);let it=e=>{Ye.current=e,r(e),localStorage.setItem(`loadpath.repo`,e),e.trim()!==Qe.current&&(Qe.current=``,He(null))},at=(0,_.useCallback)(e=>{let t=(e??Ye.current).trim();return!t||Qe.current===t?Promise.resolve():(Qe.current=t,S.gitRefs(t).then(e=>{Ye.current.trim()===t&&He(e)}).catch(()=>{Qe.current===t&&(Qe.current=``,He(null))}))},[]),ot=(e,t)=>{a(e),s(t),localStorage.setItem(`loadpath.base`,e),localStorage.setItem(`loadpath.head`,t)},st=(e,t,n)=>{ie(e),B(t),localStorage.setItem(`loadpath.provider`,e),localStorage.setItem(`loadpath.scmRepo`,t),n!==void 0&&(oe(n),localStorage.setItem(`loadpath.prNumber`,n))},ct=e=>{l(e),ue(0),Se(Ce&&e.nodes.some(e=>e.id===Ce)?Ce:null),Oe(null),Pe(null),e.what_if||(d(e),e.id&&localStorage.setItem(`loadpath.lastReviewId`,e.id))},lt=async e=>{try{let t=await S.reviews(e);Me(t.reviews)}catch{Me([])}},ut=async e=>{try{Re(await S.architectureHealth(e))}catch{Re(null)}},dt=e=>e===`github`?!!F.github_token_set:e===`gitlab`?!!F.gitlab_token_set:!!F.bitbucket_token_set,ft=(0,_.useCallback)(async(e=V)=>{try{let t=await S.scmRepos(e);R(t.repos),t.user?.login&&I(n=>({...n,...e===`github`?{github_user:t.user.login}:e===`gitlab`?{gitlab_user:t.user.login}:{bitbucket_user:t.user.login}}))}catch{R([])}},[V]);(0,_.useEffect)(()=>{if(e!==`prs`)return;let t=!1;return ft(V).catch(()=>{t||R([])}),()=>{t=!0}},[e,V,ft]),(0,_.useEffect)(()=>{if(!Ue)return;let e=!1,t=0,n=async()=>{try{let r=await S.githubOAuthPoll(Ue.flow_id);if(e)return;if(r.status===`complete`){We(null);let e=await S.settings();I(e),P(r.user?`Signed in to GitHub as ${r.user}`:`Signed in to GitHub`),ft(`github`);return}if(r.status===`pending`||r.status===`slow_down`){t=window.setTimeout(n,Math.max(r.interval||Ue.interval,5)*1e3);return}We(null),b(r.status===`denied`?`GitHub sign-in was denied.`:`GitHub sign-in expired. Try again.`)}catch(t){if(e)return;We(null),b(t instanceof Error?t.message:String(t))}};return t=window.setTimeout(n,Math.max(Ue.interval,5)*1e3),()=>{e=!0,window.clearTimeout(t)}},[Ue,ft]),(0,_.useEffect)(()=>{if(!Ge)return;let e=!1,t=0,n=Date.now(),r=async()=>{try{let i=await S.oauthStatus();if(e)return;if(i.bitbucket.connected){Ke(!1);let e=await S.settings();I(e),P(i.bitbucket.user?`Signed in to Bitbucket as ${i.bitbucket.user}`:`Signed in to Bitbucket`),ft(`bitbucket`);return}if(Date.now()-n>18e4){Ke(!1),b(`Bitbucket sign-in timed out. Finish in the browser, or try again.`);return}t=window.setTimeout(r,1500)}catch(t){if(e)return;Ke(!1),b(t instanceof Error?t.message:String(t))}};return t=window.setTimeout(r,1500),()=>{e=!0,window.clearTimeout(t)}},[Ge,ft]),(0,_.useEffect)(()=>{if(!qe)return;let e=!1,t=0,n=Date.now(),r=async()=>{try{let i=await S.oauthStatus();if(e)return;if(i.gitlab.connected){Je(!1);let e=await S.settings();I(e),P(i.gitlab.user?`Signed in to GitLab as ${i.gitlab.user}`:`Signed in to GitLab`),ft(`gitlab`);return}if(Date.now()-n>18e4){Je(!1),b(`GitLab sign-in timed out. Finish in the browser, or try again.`);return}t=window.setTimeout(r,1500)}catch(t){if(e)return;Je(!1),b(t instanceof Error?t.message:String(t))}};return t=window.setTimeout(r,1500),()=>{e=!0,window.clearTimeout(t)}},[qe,ft]);let pt=async(e=n,t=!1)=>{if(!e.trim())return null;$e.current=e,M(!0);try{let n=await S.architecture(e,!1);Ye.current===e&&p(n);let r=S.architectureGraph(e).then(t=>{Ye.current===e&&p(e=>e&&{...e,nodes:t.nodes,edges:t.edges,graph_pending:!1})});return r.catch(()=>{p(t=>t&&Ye.current===e?{...t,graph_pending:!1}:t)}).finally(()=>{$e.current===e&&M(!1)}),t&&await r,n}catch(t){throw Ye.current===e&&M(!1),t}},mt=async e=>{let t=e.trim();if(!(!t||t===Ye.current)){if(tt.current){b(`Wait for the current job to finish before switching workspace.`);return}b(``),P(``),l(null),d(null),p(null),v(`architecture`),it(t),k(!0),H(`Loading ${ee(t)}…`);try{await Promise.all([pt(t),at(t)])}catch(e){Ye.current===t&&b(e instanceof Error?e.message:String(e))}finally{Ye.current===t&&(H(``),k(!1))}}},ht=async()=>{if(tt.current||!rt())return;b(``),P(``),H(`Tracing load path…`),it(n),ot(i,o);let e=nt(n);try{let e=await S.review(n,i,o,!0,Xe.current);ct(e),v(`review`),t(`review`),await S.repos().then(e=>h(e.repos)).catch(()=>void 0),await Promise.all([pt(n),lt(n),ut(n)])}catch(e){b(e instanceof Error?e.message:String(e))}finally{e(),H(``)}},gt=async(e=!0)=>{if(tt.current||!rt())return;b(``),P(``),H(e?`Indexing…`:`Full reindex…`),it(n);let r=nt(n);try{await S.index(n,e);let r=await pt(n);await S.repos().then(e=>h(e.repos)).catch(()=>void 0),r?.indexed&&(v(`architecture`),t(`architecture`))}catch(e){b(e instanceof Error?e.message:String(e))}finally{r(),H(``)}},_t=async()=>{if(!tt.current&&rt()){b(``),P(``),H(`Detecting layout…`),it(n);try{let e=await S.init(n);P(e.message),await S.repos().then(e=>h(e.repos)).catch(()=>void 0)}catch(e){b(e instanceof Error?e.message:String(e))}finally{H(``)}}},vt=async()=>{if(c?.markdown)try{await navigator.clipboard.writeText(c.markdown),P(`Copied markdown brief`)}catch(e){b(e instanceof Error?e.message:String(e))}},yt=async()=>{if(!tt.current){if(c?.what_if){b(`What-if walks are hypothetical — they are not posted to a pull request. Restore the git-range walk first.`);return}if(!c?.markdown||!z||!ae){b(`Pick a pull request first (Pull requests tab), then post the brief.`);return}H(`Posting Loadpath brief…`);try{let e=await S.postComment(V,z,Number(ae),c.markdown);P(e.updated?`Updated the Loadpath PR comment`:`Posted the Loadpath PR comment`)}catch(e){b(e instanceof Error?e.message:String(e))}finally{H(``)}}},bt=async()=>{if(!tt.current){b(``),H(`Fetching pull requests…`);try{let e=await S.prs(V,z,`open`,n.trim()||void 0);ne(e.pull_requests);let t=L.find(e=>e.slug.toLowerCase()===z.trim().toLowerCase());t?.local_path&&it(t.local_path)}catch(e){b(e instanceof Error?e.message:String(e))}finally{H(``)}}},xt=async()=>{b(``);try{let e=await S.githubOAuthStart();We(e),Km(e.verification_uri_complete,`github.com`,`/login/device`)}catch(e){b(e instanceof Error?e.message:String(e))}},St=async()=>{b(``);try{let e=await S.bitbucketOAuthStart();Ke(!0),Km(e.authorize_url,`bitbucket.org`,`/site/oauth2/authorize`)}catch(e){Ke(!1),b(e instanceof Error?e.message:String(e))}},Ct=async()=>{b(``);try{let e=await S.gitlabOAuthStart();Je(!0),Km(e.authorize_url,new URL(e.authorize_url).hostname,`/oauth/authorize`)}catch(e){Je(!1),b(e instanceof Error?e.message:String(e))}},wt=async e=>{if(!(tt.current||!n.trim())){b(``),H(`Walking what-if path…`);try{let r=await S.whatIf(n,e);P(`${r.title} — ${r.confidence.level} · ${(r.sinks||[]).length} sinks`),ct({...r,markdown:r.markdown||``,index:r.index||c?.index,workspace:r.workspace||c?.workspace}),v(`review`),t(`review`)}catch(e){b(e instanceof Error?e.message:String(e))}finally{H(``)}}},Tt=()=>{if(u){ct(u),v(`review`),t(`review`),P(`Restored the last git-range walk`);return}l(null),ue(0),Se(null),Oe(null),Pe(null),v(`architecture`),t(`architecture`),P(``)},Et=async e=>{if(tt.current)return;st(e.provider,e.repo,String(e.number));let r=L.find(t=>t.slug.toLowerCase()===e.repo.toLowerCase());r?.local_path&&it(r.local_path),b(``),H(`Fetching ${e.provider} #${e.number}…`);let i=r?.local_path||n,a=i?nt(i):()=>void 0;try{let i=await S.reviewPr(e.provider,e.repo,e.number,r?.local_path||n||void 0);ct(i),i.pull_request&&typeof i.pull_request.repo_path==`string`&&it(i.pull_request.repo_path),ot(String(i.base||e.target_branch),String(i.head||e.source_branch)),v(`review`),t(`review`),typeof i.pull_request?.repo_path==`string`&<(i.pull_request.repo_path)}catch(n){ot(e.base_sha||e.target_branch,e.head_sha||e.source_branch),t(`review`),b(n instanceof Error?n.message:String(n))}finally{a(),H(``)}},Dt=async e=>{b(``);try{I(await S.oauthDisconnect(e)),V===e&&R([]),P(`Disconnected ${e}`)}catch(e){b(e instanceof Error?e.message:String(e))}},Ot=async e=>{e.preventDefault();let t=new FormData(e.currentTarget),n={github_token:String(t.get(`github_token`)||``),github_oauth_client_id:String(t.get(`github_oauth_client_id`)||``),github_host:String(t.get(`github_host`)||``),gitlab_token:String(t.get(`gitlab_token`)||``),gitlab_host:String(t.get(`gitlab_host`)||``),gitlab_oauth_client_id:String(t.get(`gitlab_oauth_client_id`)||``),gitlab_oauth_client_secret:String(t.get(`gitlab_oauth_client_secret`)||``),bitbucket_token:String(t.get(`bitbucket_token`)||``),bitbucket_username:String(t.get(`bitbucket_username`)||``),bitbucket_oauth_client_id:String(t.get(`bitbucket_oauth_client_id`)||``),bitbucket_oauth_client_secret:String(t.get(`bitbucket_oauth_client_secret`)||``),ai_provider:String(t.get(`ai_provider`)||`none`),ai_api_key:String(t.get(`ai_api_key`)||``),ai_model:String(t.get(`ai_model`)||``),ai_base_url:String(t.get(`ai_base_url`)||``)},r=m.length?{...n,workspaces:m.map(e=>({path:e.path,name:e.name}))}:n;try{I(await S.saveSettings(r)),P(`Settings saved on this machine`)}catch(e){b(e instanceof Error?e.message:String(e))}},kt=async()=>{if(!(!c||tt.current)){H(`Residual analysis…`);try{let e=await S.residual(c);fe(e.note)}catch(e){b(e instanceof Error?e.message:String(e))}finally{H(``)}}},At=(0,_.useRef)(ht);At.current=ht;let jt=(0,_.useRef)(e);jt.current=e;let Mt=(0,_.useRef)(!1);Mt.current=ye;let Nt=(0,_.useRef)(c);Nt.current=c;let Pt=(0,_.useRef)(le);Pt.current=le,(0,_.useEffect)(()=>{let e=localStorage.getItem(`loadpath.lastReviewId`),t=(localStorage.getItem(`loadpath.repo`)||``).trim();if(!e||!t){Be(!1);return}let n=!1;return S.getReview(t,e).then(e=>{n||(ct(e),ot(e.base||localStorage.getItem(`loadpath.base`)||`HEAD~1`,e.head||localStorage.getItem(`loadpath.head`)||`HEAD`),lt(t),ut(t))}).catch(()=>void 0).finally(()=>{n||Be(!1)}),()=>{n=!0}},[]);let Ft=(0,_.useRef)(``);(0,_.useEffect)(()=>{if(!ke||!n.trim())return;let e=!1,t=async()=>{try{let t=await S.workspaceStatus(n);if(e)return;Ft.current&&t.fingerprint!==Ft.current&&!tt.current&&(ce(!0),Xe.current=!0,localStorage.setItem(`loadpath.dirty`,`1`),At.current()),Ft.current=t.fingerprint}catch{}};t();let r=window.setInterval(t,2e3);return()=>{e=!0,window.clearInterval(r)}},[ke,n]),(0,_.useEffect)(()=>{let e=e=>{if((e.metaKey||e.ctrlKey)&&e.key.toLowerCase()===`k`){e.preventDefault(),be(e=>!e);return}if(Mt.current){e.key===`Escape`&&(e.preventDefault(),be(!1));return}if(Ze.current){e.key===`Escape`&&(e.preventDefault(),ve(!1));return}let n=e.target;if(n&&(n.tagName===`INPUT`||n.tagName===`TEXTAREA`||n.tagName===`SELECT`||n.isContentEditable)){e.key===`Escape`&&n.blur();return}if(e.key===`Escape`){b(``),P(``),Se(Ce),Oe(null);return}if(e.key===`j`||e.key===`k`){let t=Nt.current?.read_order||[];if(!t.length)return;e.preventDefault();let n=Pt.current,r=e.key===`j`?Math.min(t.length-1,n+1):Math.max(0,n-1);ue(r);return}let r=Gm.find(t=>t.shortcut===e.key);if(r&&!e.metaKey&&!e.ctrlKey&&!e.altKey&&t(r.id),(e.metaKey||e.ctrlKey)&&e.key===`Enter`){if(jt.current===`settings`||jt.current===`prs`||tt.current)return;e.preventDefault(),At.current()}};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[Ce]);let It=async(e,t)=>{if(!n.trim())return;let r=await Tm(n,e,t);r.ok?P(r.message):b(r.message)},Lt=async()=>{if(c)try{let e=await S.exportHtml(c),t=URL.createObjectURL(e),n=document.createElement(`a`);n.href=t,n.download=`loadpath-${(c.id||`review`).slice(0,8)}.html`,n.click(),URL.revokeObjectURL(t),P(`Saved HTML brief`)}catch(e){b(e instanceof Error?e.message:String(e))}},Rt=async e=>{if(n.trim()){H(`Loading stored review…`);try{let r=await S.getReview(n,e);ct(r),ot(r.base||i,r.head||o),v(`review`),t(`review`);let a=je.findIndex(t=>t.id===e),s=a>=0?je[a+1]:void 0;if(s)try{Pe(await S.reviewDiff(n,e,s.id))}catch{Pe(null)}}catch(e){b(e instanceof Error?e.message:String(e))}finally{H(``)}}},zt={selectedId:xe,onSelect:Se,nodeRoles:c?.node_roles,testOverlay:Te,isolateSource:De,onIsolate:Oe,repoPath:n,onOpenFile:It,pinnedId:Ce,onPin:we},Bt=[{id:`review`,group:`Run`,label:`Review this range`,hint:`⌘/Ctrl+Enter`,run:()=>void ht()},...c?.what_if?[{id:`exit-whatif`,group:`Review`,label:u?`Back to git-range walk`:`Exit what-if walk`,run:Tt}]:[],{id:`index`,group:`Run`,label:`Index repository`,run:()=>void gt(!0)},{id:`watch`,group:`Run`,label:ke?`Stop watching working tree`:`Watch working tree`,run:()=>{let e=!ke;Ae(e),localStorage.setItem(`loadpath.watch`,e?`1`:`0`)}},{id:`tests`,group:`Graph`,label:Te?`Hide test overlay`:`Show test overlay`,run:()=>{let e=!Te;Ee(e),localStorage.setItem(`loadpath.testOverlay`,e?`1`:`0`)}},{id:`export`,group:`Review`,label:`Export HTML brief`,run:()=>void Lt()},...Gm.map(e=>({id:`tab-${e.id}`,group:`Tabs`,label:`Go to ${e.label}`,hint:e.shortcut,run:()=>t(e.id)})),...(c?.nodes||[]).slice(0,30).map(e=>({id:`node-${e.id}`,group:`Nodes`,label:e.name,hint:j(e.type),run:()=>{Se(e.id),t(`graph`)}})),...je.slice(0,12).map(e=>({id:`hist-${e.id}`,group:`History`,label:e.title||e.id,hint:`${e.level||``} ${e.created_at||``}`.trim(),run:()=>void Rt(e.id)}))],Vt=(0,_.useMemo)(()=>g===`architecture`?f?.nodes??[]:c?.nodes??[],[g,f,c]),Ht=(0,_.useMemo)(()=>g===`architecture`?f?.edges??[]:c?.edges??[],[g,f,c]),Ut=c?.index?`${c.index.counts.nodes} nodes · ${c.index.counts.edges} edges`:f?.indexed?`${f.counts.nodes} nodes · ${f.counts.edges} edges`:`Not indexed`,Wt=(c?.findings||[]).filter(e=>!e.waived);return(0,T.jsxs)(`div`,{className:`app`,children:[(0,T.jsx)(`a`,{className:`skip`,href:`#main`,children:`Skip to content`}),(0,T.jsxs)(`nav`,{className:`rail`,"data-testid":`rail`,"aria-label":`Primary`,children:[(0,T.jsxs)(`div`,{className:`brand`,children:[(0,T.jsx)(`div`,{className:`brand-mark`,children:`Loadpath`}),(0,T.jsx)(`div`,{className:`brand-sub`,children:`Load-path review`})]}),Gm.map(n=>{let r=n.icon,i=e===n.id;return(0,T.jsxs)(`button`,{type:`button`,"data-testid":n.testId,className:i?`nav-item active`:`nav-item`,"aria-current":i?`page`:void 0,"aria-label":n.label,onClick:()=>t(n.id),children:[(0,T.jsx)(r,{}),(0,T.jsx)(`span`,{children:n.label})]},n.id)}),(0,T.jsxs)(`div`,{className:`theme-pick`,children:[(0,T.jsx)(`label`,{htmlFor:`theme-select`,children:`Theme`}),(0,T.jsx)(`select`,{id:`theme-select`,"data-testid":`theme-select`,value:pe,onChange:e=>et(e.target.value),children:[`dark`,`light`].map(e=>(0,T.jsx)(`optgroup`,{label:e===`dark`?`Dark`:`Light`,children:Rm.filter(t=>t.group===e).map(e=>(0,T.jsx)(`option`,{value:e.id,children:e.label},e.id))},e))})]}),(0,T.jsxs)(`div`,{className:`rail-foot`,children:[(0,T.jsx)(`div`,{className:`muted`,role:`status`,children:x||Ut}),(0,T.jsxs)(`div`,{className:`kbd-hint`,children:[(0,T.jsx)(`kbd`,{children:`1`}),`–`,(0,T.jsx)(`kbd`,{children:`5`}),` tabs · `,(0,T.jsx)(`kbd`,{children:`⌘`}),(0,T.jsx)(`kbd`,{children:`K`}),` palette · `,(0,T.jsx)(`kbd`,{children:`j`}),`/`,(0,T.jsx)(`kbd`,{children:`k`}),` read order`]})]})]}),(0,T.jsxs)(`div`,{className:`main`,id:`main`,children:[x?(0,T.jsxs)(`div`,{className:w==null?`progress`:`progress determinate`,role:w==null?`status`:`progressbar`,"aria-label":x,"aria-live":`polite`,"aria-busy":`true`,"aria-valuemin":w==null?void 0:0,"aria-valuemax":w==null?void 0:100,"aria-valuenow":w??void 0,"data-testid":`progress`,children:[(0,T.jsx)(`i`,{style:w==null?void 0:{width:`${w}%`}}),(0,T.jsx)(`span`,{className:`sr-only`,children:x})]}):null,(0,T.jsxs)(`header`,{className:`topbar`,"data-testid":`topbar`,children:[m.length>0?(0,T.jsxs)(`label`,{className:`field workspace`,children:[(0,T.jsx)(`span`,{children:`Workspace`}),(0,T.jsxs)(`select`,{"data-testid":`workspace-select`,value:m.some(e=>e.path===n)?n:``,disabled:!!x,"aria-busy":O,onChange:e=>{e.target.value&&mt(e.target.value)},children:[(0,T.jsx)(`option`,{value:``,children:`Indexed repos…`}),m.map(e=>(0,T.jsxs)(`option`,{value:e.path,children:[e.name,e.indexed?` (${e.counts.nodes})`:``]},e.path))]})]}):null,(0,T.jsxs)(`label`,{className:`field path`,children:[(0,T.jsx)(`span`,{children:`Repository`}),(0,T.jsxs)(`div`,{className:`path-row`,children:[(0,T.jsx)(`input`,{"data-testid":`repo-path`,placeholder:`Local monorepo path`,value:n,onChange:e=>{let t=e.target.value;r(t),t.trim()!==Qe.current&&(Qe.current=``,He(null))},spellCheck:!1}),(0,T.jsx)(`button`,{type:`button`,className:`icon-btn`,"data-testid":`btn-browse-repo`,"aria-label":`Browse for a local repository`,onClick:()=>ve(!0),children:(0,T.jsx)(re,{})})]})]}),(0,T.jsxs)(`label`,{className:`field ref`,children:[(0,T.jsx)(`span`,{children:`Base`}),(0,T.jsx)(Mm,{testId:`base-ref`,menuTestId:`base-ref-menu`,value:i,onChange:e=>ot(e,o),placeholder:`base`,refs:Ve,onNeedRefs:at})]}),(0,T.jsxs)(`label`,{className:`field ref`,children:[(0,T.jsx)(`span`,{children:`Head`}),(0,T.jsx)(Mm,{testId:`head-ref`,menuTestId:`head-ref-menu`,value:o,onChange:e=>ot(i,e),placeholder:`head`,refs:Ve,onNeedRefs:at})]}),(0,T.jsxs)(`label`,{className:`field dirty`,children:[(0,T.jsx)(`span`,{children:`Working tree`}),(0,T.jsx)(`button`,{type:`button`,className:se?`chip-btn active`:`chip-btn`,"data-testid":`btn-dirty`,"aria-pressed":se,onClick:()=>{let e=!se;ce(e),localStorage.setItem(`loadpath.dirty`,e?`1`:`0`)},children:se?`Include uncommitted`:`Committed range`})]}),(0,T.jsxs)(`label`,{className:`field dirty`,children:[(0,T.jsx)(`span`,{children:`Watch`}),(0,T.jsx)(`button`,{type:`button`,className:ke?`chip-btn active`:`chip-btn`,"data-testid":`btn-watch`,"aria-pressed":ke,onClick:()=>{let e=!ke;Ae(e),localStorage.setItem(`loadpath.watch`,e?`1`:`0`)},children:ke?`Watching`:`Paused`})]}),c?(0,T.jsxs)(`div`,{className:`merge-box compact ${c.confidence.level}`,"data-testid":`merge-box`,children:[(0,T.jsx)(`div`,{className:`level ${c.confidence.level}`,children:c.confidence.level.toUpperCase()}),(0,T.jsxs)(`div`,{className:`muted`,children:[c.what_if?`what-if · `:``,c.confidence.covered_sinks,`/`,c.confidence.sinks,` sinks`]})]}):null,(0,T.jsxs)(`div`,{className:`topbar-actions`,children:[(0,T.jsx)(`button`,{type:`button`,"data-testid":`btn-init`,disabled:!!x,onClick:_t,children:`Draft config`}),(0,T.jsx)(`button`,{type:`button`,"data-testid":`btn-index`,disabled:!!x,onClick:()=>gt(!0),children:`Index`}),(0,T.jsx)(`button`,{type:`button`,"data-testid":`btn-review`,className:`btn primary`,disabled:!!x,onClick:ht,children:`Review`})]})]}),(0,T.jsxs)(`div`,{className:`alerts`,children:[y?(0,T.jsxs)(`div`,{className:`error`,"data-testid":`error`,role:`alert`,children:[(0,T.jsx)(`span`,{children:y}),(0,T.jsx)(`button`,{type:`button`,className:`dismiss`,onClick:()=>b(``),"aria-label":`Dismiss error`,children:`×`})]}):null,N?(0,T.jsxs)(`div`,{className:`banner`,"data-testid":`status-note`,children:[(0,T.jsx)(`span`,{children:N}),(0,T.jsx)(`button`,{type:`button`,className:`dismiss`,onClick:()=>P(``),"aria-label":`Dismiss`,children:`×`})]}):null,(c?.index?.stale||f?.stale)&&(e===`review`||e===`architecture`)?(0,T.jsx)(`div`,{className:`banner stale`,"data-testid":`index-stale`,children:`Index is stale — files changed since the last extract. Index again before trusting this walk.`}):null,c?.index?.django_boot===`failed`||f?.django_boot===`failed`?(0,T.jsx)(`div`,{className:`banner warn`,"data-testid":`django-boot-failed`,children:c?.index?.django_boot_detail||f?.django_boot_detail||`django.setup() failed`}):null,c?.workspace?.dirty_overlaps_review&&e===`review`?(0,T.jsxs)(`div`,{className:`banner warn`,"data-testid":`dirty-tree`,children:[`Uncommitted files overlap this review: `,(c.workspace.dirty_overlap||[]).slice(0,6).join(`, `)]}):null,c?.what_if?(0,T.jsxs)(`div`,{className:`banner whatif`,"data-testid":`whatif-banner`,children:[(0,T.jsxs)(`span`,{children:[`Hypothetical walk from`,` `,(0,T.jsx)(`strong`,{children:c.node?.name||`this node`}),`. Loadpath ignored Base/Head and asked which sinks would feel this node change — not a filter of the current map.`]}),(0,T.jsx)(`button`,{type:`button`,className:`btn`,"data-testid":`btn-exit-whatif`,onClick:Tt,children:u?`Back to git range`:`Back to architecture`})]}):null,O?(0,T.jsx)(`div`,{className:`banner`,"data-testid":`workspace-loading`,children:x||`Loading workspace…`}):null]}),(0,T.jsxs)(`div`,{className:`stage`,"aria-busy":O||A,children:[e===`review`&&(0,T.jsxs)(`div`,{className:`content`,"data-testid":`review-layout`,children:[(0,T.jsx)(`aside`,{className:`brief`,"data-testid":`brief`,children:c?(0,T.jsx)(Jm,{review:c,findings:Wt,aiNote:de,busy:!!x,tourIndex:le,onTour:ue,onAskAi:kt,onCopy:vt,onPost:yt,onSelect:Se,onOpenFile:It,onExport:Lt,history:je,diff:Ne,onReopen:Rt,onWaiver:(e,t)=>{n.trim()&&S.addWaiver(n,e,t||void 0,`from review`).then(t=>{Ie(t),P(`Waived ${e} in loadpath.yml`)})}}):ze?(0,T.jsxs)(`div`,{className:`empty`,"data-testid":`review-restoring`,children:[(0,T.jsx)(`h2`,{children:`Restoring last review`}),(0,T.jsx)(`p`,{children:`Loading the walk this machine stored last time Loadpath was open.`})]}):(0,T.jsxs)(`div`,{className:`empty`,"data-testid":`review-empty`,children:[(0,T.jsx)(`h2`,{children:`Trace the force of this diff`}),(0,T.jsx)(`p`,{children:`The graph is the architecture. The brief is where this change travels — not a hunk list.`}),(0,T.jsxs)(`ol`,{children:[(0,T.jsx)(`li`,{children:`Point at a Django + React monorepo, or pick an indexed workspace.`}),(0,T.jsxs)(`li`,{children:[`Index it. Missing `,(0,T.jsx)(`code`,{children:`loadpath.yml`}),` is drafted from `,(0,T.jsx)(`code`,{children:`manage.py`}),` and`,` `,(0,T.jsx)(`code`,{children:`src/features`}),`.`]}),(0,T.jsx)(`li`,{children:`Review a git range, or open a pull request so base/head become a three-dot merge-base.`})]})]})}),(0,T.jsx)(`div`,{className:`graph-wrap`,"data-testid":`review-graph`,children:c?(0,T.jsx)(Sm,{nodes:c.nodes,edges:c.edges,onWhatIf:wt,focusPath:c.read_order[le]?.path,...zt}):null})]}),e===`architecture`&&(0,T.jsxs)(`div`,{className:`content`,"data-testid":`architecture-panel`,children:[(0,T.jsx)(`aside`,{className:`brief`,"data-testid":`architecture-brief`,children:f?.indexed?(0,T.jsx)(Ym,{architecture:f,busy:!!x,onReindex:()=>gt(!1),onReview:ht,onSelect:Se,config:Fe,health:Le,onSaveConfig:e=>{S.saveConfig(n,e).then(e=>{Ie(e),P(`Wrote loadpath.yml`)})},onWaiver:(e,t,r)=>{S.addWaiver(n,e,t,r).then(t=>{Ie(t),P(`Waived ${e}`)})}}):O?(0,T.jsx)(`p`,{className:`muted`,"data-testid":`architecture-loading`,children:`Loading the index summary…`}):(0,T.jsx)(`p`,{className:`muted`,"data-testid":`architecture-empty`,children:`Index this repo to build the architecture graph. Review then walks that same graph for a git range — it does not start from a hunk list.`})}),(0,T.jsx)(`div`,{className:`graph-wrap`,"data-testid":`architecture-graph`,children:(A||f?.graph_pending)&&!(f?.nodes||[]).length?(0,T.jsxs)(`div`,{className:`empty graph-loading`,"data-testid":`graph-loading`,children:[(0,T.jsx)(`h2`,{children:`Drawing the architecture map…`}),(0,T.jsx)(`p`,{children:f?.counts?.nodes?`${f.counts.nodes} indexed nodes. The brief is ready while the graph loads.`:`Fetching the indexed graph.`})]}):f?.indexed?(0,T.jsx)(Sm,{nodes:f.nodes,edges:f.edges,onWhatIf:wt,...zt,isolateSource:null,onIsolate:void 0}):null})]}),e===`graph`&&(0,T.jsxs)(`div`,{className:`graph-wrap`,"data-testid":`graph-full`,style:{height:`100%`},children:[(0,T.jsxs)(`div`,{className:`graph-modes`,children:[(0,T.jsxs)(`div`,{className:`seg`,"aria-label":`Graph scope`,children:[(0,T.jsx)(`button`,{type:`button`,"aria-pressed":g===`review`,"data-testid":`graph-mode-review`,className:g===`review`?`active`:``,onClick:()=>v(`review`),children:`This review`}),(0,T.jsx)(`button`,{type:`button`,"aria-pressed":g===`architecture`,"data-testid":`graph-mode-architecture`,className:g===`architecture`?`active`:``,onClick:()=>v(`architecture`),children:`Indexed architecture`})]}),(0,T.jsxs)(`div`,{className:`legend`,"aria-hidden":`true`,children:[(0,T.jsxs)(`span`,{children:[(0,T.jsx)(`i`,{}),` cheap`]}),(0,T.jsxs)(`span`,{children:[(0,T.jsx)(`i`,{className:`exp`}),` expensive`]}),(0,T.jsxs)(`span`,{children:[(0,T.jsx)(`i`,{className:`crit`}),` critical`]}),(0,T.jsxs)(`span`,{children:[(0,T.jsx)(`i`,{className:`dash`}),` inferred`]}),(0,T.jsxs)(`span`,{children:[(0,T.jsx)(`i`,{className:`seed`}),` changed`]}),(0,T.jsxs)(`span`,{children:[(0,T.jsx)(`i`,{className:`down`}),` downstream`]})]}),(0,T.jsx)(`button`,{type:`button`,className:Te?`chip-btn active`:`chip-btn`,"data-testid":`graph-test-overlay`,"aria-pressed":Te,onClick:()=>{let e=!Te;Ee(e),localStorage.setItem(`loadpath.testOverlay`,e?`1`:`0`)},children:`Tests`})]}),Vt.length||g===`review`&&c||f?.indexed&&!(A||f?.graph_pending)?(0,T.jsx)(Sm,{nodes:Vt,edges:Ht,onWhatIf:wt,...zt,...g===`architecture`?{isolateSource:null,onIsolate:void 0,nodeRoles:void 0,testOverlay:!1}:{}}):A||f?.graph_pending?(0,T.jsx)(`p`,{className:`empty`,"data-testid":`graph-loading`,children:`Drawing the architecture map…`}):(0,T.jsx)(`p`,{className:`empty`,"data-testid":`graph-empty`,children:`Index the repo or run a review first. Click a node to inspect it.`})]}),e===`prs`&&(0,T.jsxs)(`div`,{className:`pr-list`,"data-testid":`pr-list`,children:[(0,T.jsxs)(`div`,{className:`pr-toolbar`,children:[(0,T.jsxs)(`label`,{className:`field provider`,children:[(0,T.jsx)(`span`,{children:`Provider`}),(0,T.jsxs)(`select`,{"data-testid":`pr-provider`,value:V,onChange:e=>st(e.target.value,z,ae),children:[(0,T.jsx)(`option`,{value:`github`,children:`GitHub`}),(0,T.jsx)(`option`,{value:`gitlab`,children:`GitLab`}),(0,T.jsx)(`option`,{value:`bitbucket`,children:`Bitbucket`})]})]}),(0,T.jsxs)(`label`,{className:`field`,children:[(0,T.jsx)(`span`,{children:`Repository`}),(0,T.jsx)(`input`,{"data-testid":`pr-repo`,placeholder:L.length?`Search your repos`:`owner/repo`,value:z,onChange:e=>st(V,e.target.value,ae),list:`scm-repos`,spellCheck:!1}),(0,T.jsx)(`datalist`,{id:`scm-repos`,children:L.map(e=>(0,T.jsxs)(`option`,{value:e.slug,children:[e.private?`private`:`public`,e.local_path?` · local`:``]},e.slug))})]}),(0,T.jsx)(`button`,{type:`button`,"data-testid":`btn-refresh-repos`,className:`btn`,disabled:!!x||!dt(V),onClick:()=>{ft(V)},children:`My repos`}),(0,T.jsx)(`button`,{type:`button`,"data-testid":`btn-list-prs`,className:`btn`,disabled:!!x,onClick:bt,children:`List PRs`})]}),L.length>0?(0,T.jsxs)(`p`,{className:`muted scm-count`,"data-testid":`scm-repo-count`,children:[L.length,` `,V,` repositor`,L.length===1?`y`:`ies`,V===`github`&&F.github_user?` · @${String(F.github_user)}`:``,V===`gitlab`&&F.gitlab_user?` · @${String(F.gitlab_user)}`:``,V===`bitbucket`&&F.bitbucket_user?` · ${String(F.bitbucket_user)}`:``]}):null,te.length===0?(0,T.jsxs)(`div`,{className:`empty`,"data-testid":`pr-empty`,children:[(0,T.jsx)(`h2`,{children:`No pull requests loaded`}),(0,T.jsx)(`p`,{children:`Sign in under Settings (or paste a token), load your repositories, then list open PRs. Reviewing a PR fills base and head from its SHAs.`})]}):te.map(e=>(0,T.jsxs)(`article`,{className:`pr`,"data-testid":`pr-${e.number}`,children:[(0,T.jsxs)(`h3`,{children:[`#`,e.number,` `,e.title]}),(0,T.jsxs)(`div`,{className:`pr-meta muted`,children:[(0,T.jsx)(`span`,{className:`chip ${e.draft?``:`open`}`,children:e.draft?`draft`:e.state}),(0,T.jsx)(`span`,{children:e.author}),(0,T.jsxs)(`span`,{children:[e.source_branch,` → `,e.target_branch]}),e.loadpath?(0,T.jsxs)(`span`,{className:`chip ${e.loadpath.level||``}`,"data-testid":`pr-loadpath-${e.number}`,children:[e.loadpath.level?.toUpperCase()||`REVIEWED`,e.loadpath.contract_break&&e.loadpath.contract_break!==`none`?` · ${e.loadpath.contract_break}`:``]}):(0,T.jsx)(`span`,{className:`muted`,children:`no Loadpath walk yet`})]}),(0,T.jsxs)(`div`,{className:`pr-actions`,children:[(0,T.jsxs)(`a`,{href:e.url,target:`_blank`,rel:`noreferrer`,children:[`Open on `,e.provider]}),(0,T.jsx)(`button`,{type:`button`,className:`btn primary`,"data-testid":`pr-review-${e.number}`,onClick:()=>void Et(e),children:`Review this PR`})]})]},`${e.provider}-${e.number}`))]}),e===`settings`&&he&&(0,T.jsxs)(`form`,{className:`settings`,"data-testid":`settings-form`,onSubmit:Ot,children:[(0,T.jsxs)(`div`,{children:[(0,T.jsx)(`h1`,{children:`Settings`}),(0,T.jsx)(`p`,{className:`muted`,children:`Tokens stay on this machine in ~/.loadpath/settings.json. AI runs only on residual uncertainty the graph could not close.`})]}),(0,T.jsxs)(`section`,{className:`settings-card`,children:[(0,T.jsx)(`h2`,{children:`Appearance`}),(0,T.jsx)(`p`,{className:`muted`,children:`Local to this browser. High contrast is a first-class theme, not an afterthought.`}),(0,T.jsx)(`div`,{className:`theme-grid`,"data-testid":`theme-grid`,children:Rm.map(e=>(0,T.jsxs)(`button`,{type:`button`,"data-theme":e.id,className:pe===e.id?`theme-swatch active`:`theme-swatch`,"data-testid":`theme-${e.id}`,onClick:()=>et(e.id),children:[(0,T.jsx)(`div`,{className:`swatch-bar`,"aria-hidden":`true`}),(0,T.jsx)(`div`,{className:`name`,children:e.label}),(0,T.jsx)(`div`,{className:`group`,children:e.group})]},e.id))})]}),(0,T.jsxs)(`section`,{className:`settings-card`,children:[(0,T.jsx)(`h2`,{children:`Editor`}),(0,T.jsx)(`p`,{className:`muted`,children:`Open files from the inspector and read-order in Cursor, VS Code, or the system handler.`}),(0,T.jsx)(`label`,{htmlFor:`editor-pref`,children:`Preferred editor`}),(0,T.jsxs)(`select`,{id:`editor-pref`,"data-testid":`editor-pref`,defaultValue:Cm(),onChange:e=>wm(e.target.value),children:[(0,T.jsx)(`option`,{value:`auto`,children:`Auto (Cursor, then VS Code)`}),(0,T.jsx)(`option`,{value:`cursor`,children:`Cursor`}),(0,T.jsx)(`option`,{value:`vscode`,children:`VS Code`}),(0,T.jsx)(`option`,{value:`system`,children:`System default`})]})]}),(0,T.jsxs)(`section`,{className:`settings-card`,children:[(0,T.jsx)(`h2`,{children:`Source control`}),(0,T.jsx)(`p`,{className:`muted`,children:`Sign in with OAuth to list every repository the account can access. Tokens stay in ~/.loadpath/settings.json. A classic PAT still works if you prefer not to register an OAuth app.`}),(0,T.jsxs)(`div`,{className:`scm-login`,"data-testid":`scm-github`,children:[(0,T.jsxs)(`div`,{children:[(0,T.jsx)(`strong`,{children:`GitHub`}),(0,T.jsx)(`p`,{className:`muted`,children:F.github_token_set?F.github_user?`Signed in as @${String(F.github_user)}`:`Token saved on this machine`:`Not connected`})]}),(0,T.jsx)(`div`,{className:`btn-row`,children:F.github_token_set?(0,T.jsx)(`button`,{type:`button`,className:`btn`,"data-testid":`btn-github-disconnect`,onClick:()=>void Dt(`github`),children:`Disconnect`}):(0,T.jsx)(`button`,{type:`button`,className:`btn primary`,"data-testid":`btn-github-login`,disabled:!!Ue||!F.github_oauth_ready,onClick:()=>void xt(),children:Ue?`Waiting for GitHub…`:`Sign in with GitHub`})})]}),Ue?(0,T.jsxs)(`p`,{className:`oauth-code`,"data-testid":`github-user-code`,children:[`Enter `,(0,T.jsx)(`code`,{children:Ue.user_code}),` at GitHub if the browser did not fill it in.`]}):null,F.github_oauth_ready?null:(0,T.jsx)(`p`,{className:`muted`,children:`Sign-in needs a GitHub OAuth App with Device Flow enabled. Set LOADPATH_GITHUB_CLIENT_ID or paste the client ID below.`}),(0,T.jsx)(`label`,{htmlFor:`github_oauth_client_id`,children:`GitHub OAuth client ID`}),(0,T.jsx)(`input`,{id:`github_oauth_client_id`,name:`github_oauth_client_id`,"data-testid":`github-oauth-client-id`,placeholder:`Ov23…`,defaultValue:String(F.github_oauth_client_id||``),autoComplete:`off`}),(0,T.jsx)(`label`,{htmlFor:`github_token`,children:`GitHub token (optional PAT)`}),(0,T.jsx)(`input`,{id:`github_token`,name:`github_token`,type:`password`,placeholder:`ghp_…`,autoComplete:`off`}),(0,T.jsx)(`label`,{htmlFor:`github_host`,children:`GitHub host (Enterprise)`}),(0,T.jsx)(`input`,{id:`github_host`,name:`github_host`,"data-testid":`github-host`,placeholder:`github.com`,defaultValue:String(F.github_host||``),autoComplete:`off`}),(0,T.jsxs)(`div`,{className:`scm-login`,"data-testid":`scm-gitlab`,children:[(0,T.jsxs)(`div`,{children:[(0,T.jsx)(`strong`,{children:`GitLab`}),(0,T.jsx)(`p`,{className:`muted`,children:F.gitlab_token_set?F.gitlab_user?`Signed in as @${String(F.gitlab_user)}`:`Token saved on this machine`:`Not connected`})]}),(0,T.jsx)(`div`,{className:`btn-row`,children:F.gitlab_token_set?(0,T.jsx)(`button`,{type:`button`,className:`btn`,"data-testid":`btn-gitlab-disconnect`,onClick:()=>void Dt(`gitlab`),children:`Disconnect`}):(0,T.jsx)(`button`,{type:`button`,className:`btn primary`,"data-testid":`btn-gitlab-login`,disabled:qe||!F.gitlab_oauth_ready,onClick:()=>void Ct(),children:qe?`Waiting for GitLab…`:`Sign in with GitLab`})})]}),(0,T.jsx)(`label`,{htmlFor:`gitlab_host`,children:`GitLab host`}),(0,T.jsx)(`input`,{id:`gitlab_host`,name:`gitlab_host`,"data-testid":`gitlab-host`,placeholder:`gitlab.com`,defaultValue:String(F.gitlab_host||``),autoComplete:`off`}),(0,T.jsx)(`label`,{htmlFor:`gitlab_oauth_client_id`,children:`GitLab OAuth application ID`}),(0,T.jsx)(`input`,{id:`gitlab_oauth_client_id`,name:`gitlab_oauth_client_id`,"data-testid":`gitlab-oauth-client-id`,defaultValue:String(F.gitlab_oauth_client_id||``),autoComplete:`off`}),(0,T.jsx)(`label`,{htmlFor:`gitlab_oauth_client_secret`,children:`GitLab OAuth secret`}),(0,T.jsx)(`input`,{id:`gitlab_oauth_client_secret`,name:`gitlab_oauth_client_secret`,type:`password`,autoComplete:`off`}),(0,T.jsx)(`label`,{htmlFor:`gitlab_token`,children:`GitLab token (optional PAT)`}),(0,T.jsx)(`input`,{id:`gitlab_token`,name:`gitlab_token`,type:`password`,placeholder:`glpat-…`,autoComplete:`off`}),(0,T.jsxs)(`div`,{className:`scm-login`,"data-testid":`scm-bitbucket`,children:[(0,T.jsxs)(`div`,{children:[(0,T.jsx)(`strong`,{children:`Bitbucket`}),(0,T.jsx)(`p`,{className:`muted`,children:F.bitbucket_token_set?F.bitbucket_user?`Signed in as ${String(F.bitbucket_user)}`:`Token saved on this machine`:`Not connected`})]}),(0,T.jsx)(`div`,{className:`btn-row`,children:F.bitbucket_token_set?(0,T.jsx)(`button`,{type:`button`,className:`btn`,"data-testid":`btn-bitbucket-disconnect`,onClick:()=>void Dt(`bitbucket`),children:`Disconnect`}):(0,T.jsx)(`button`,{type:`button`,className:`btn primary`,"data-testid":`btn-bitbucket-login`,disabled:Ge||!F.bitbucket_oauth_ready,onClick:()=>void St(),children:Ge?`Waiting for Bitbucket…`:`Sign in with Bitbucket`})})]}),F.bitbucket_oauth_ready?null:(0,T.jsxs)(`p`,{className:`muted`,children:[`Sign-in needs a Bitbucket OAuth consumer (key + secret). Callback URL:`,` `,(0,T.jsx)(`code`,{children:`/api/oauth/bitbucket/callback`}),` on this app origin.`]}),(0,T.jsx)(`label`,{htmlFor:`bitbucket_oauth_client_id`,children:`Bitbucket OAuth key`}),(0,T.jsx)(`input`,{id:`bitbucket_oauth_client_id`,name:`bitbucket_oauth_client_id`,"data-testid":`bitbucket-oauth-client-id`,defaultValue:String(F.bitbucket_oauth_client_id||``),autoComplete:`off`}),(0,T.jsx)(`label`,{htmlFor:`bitbucket_oauth_client_secret`,children:`Bitbucket OAuth secret`}),(0,T.jsx)(`input`,{id:`bitbucket_oauth_client_secret`,name:`bitbucket_oauth_client_secret`,type:`password`,autoComplete:`off`}),(0,T.jsx)(`label`,{htmlFor:`bitbucket_token`,children:`Bitbucket token (optional app password)`}),(0,T.jsx)(`input`,{id:`bitbucket_token`,name:`bitbucket_token`,type:`password`,autoComplete:`off`}),(0,T.jsx)(`label`,{htmlFor:`bitbucket_username`,children:`Bitbucket username (app passwords)`}),(0,T.jsx)(`input`,{id:`bitbucket_username`,name:`bitbucket_username`,defaultValue:String(F.bitbucket_username||``)})]}),(0,T.jsxs)(`section`,{className:`settings-card`,children:[(0,T.jsx)(`h2`,{children:`Residual AI`}),(0,T.jsx)(`label`,{htmlFor:`ai_provider`,children:`Provider`}),(0,T.jsxs)(`select`,{id:`ai_provider`,name:`ai_provider`,defaultValue:String(F.ai?.provider||`none`),children:[(0,T.jsx)(`option`,{value:`none`,children:`none (graph only)`}),(0,T.jsx)(`option`,{value:`anthropic`,children:`Anthropic`}),(0,T.jsx)(`option`,{value:`openai`,children:`OpenAI`}),(0,T.jsx)(`option`,{value:`grok`,children:`Grok / xAI`}),(0,T.jsx)(`option`,{value:`deepseek`,children:`DeepSeek`}),(0,T.jsx)(`option`,{value:`cursor`,children:`Cursor-compatible (OpenAI protocol)`}),(0,T.jsx)(`option`,{value:`ollama`,children:`Ollama local`})]}),(0,T.jsx)(`label`,{htmlFor:`ai_api_key`,children:`API key`}),(0,T.jsx)(`input`,{id:`ai_api_key`,name:`ai_api_key`,type:`password`,autoComplete:`off`}),(0,T.jsx)(`label`,{htmlFor:`ai_model`,children:`Model`}),(0,T.jsx)(`input`,{id:`ai_model`,name:`ai_model`,"data-testid":`ai-model`,placeholder:`optional override`,defaultValue:String(F.ai?.model||``)}),(0,T.jsx)(`label`,{htmlFor:`ai_base_url`,children:`Base URL`}),(0,T.jsx)(`input`,{id:`ai_base_url`,name:`ai_base_url`,"data-testid":`ai-base-url`,placeholder:`optional, OpenAI-compatible`,defaultValue:String(F.ai?.base_url||``)}),(0,T.jsx)(`button`,{className:`btn primary`,type:`submit`,"data-testid":`btn-save-settings`,children:`Save`})]})]})]})]}),(0,T.jsx)(D,{open:ye,actions:Bt,onClose:()=>be(!1)}),_e?(0,T.jsx)(Nm,{initialPath:n,onClose:()=>ve(!1),onSelect:e=>{if(tt.current){b(`Wait for the current job to finish before switching workspace.`);return}ve(!1),mt(e)}}):null]})}function Jm({review:e,findings:t,aiNote:n,busy:r,tourIndex:i,onTour:a,onAskAi:o,onCopy:s,onPost:c,onSelect:l,onOpenFile:u,onExport:d,history:f,diff:p,onReopen:m,onWaiver:h}){let g=[...new Set(e.confidence.reasons||[])];return(0,T.jsxs)(T.Fragment,{children:[(0,T.jsxs)(`div`,{className:`merge-box ${e.confidence.level}`,children:[(0,T.jsxs)(`div`,{className:`level ${e.confidence.level}`,children:[e.confidence.level.toUpperCase(),` — `,e.title]}),g.length?(0,T.jsx)(`ul`,{className:`reasons`,children:g.map(e=>(0,T.jsx)(`li`,{children:e},e))}):null,e.what_if?(0,T.jsx)(`span`,{className:`chip whatif`,"data-testid":`whatif-chip`,children:`what-if`}):null,e.low_risk?(0,T.jsx)(`span`,{className:`chip`,children:`low-risk`}):null,e.change_kinds.map(e=>(0,T.jsx)(`span`,{className:`chip`,children:k(e)},e)),e.contract_break?.kind&&e.contract_break.kind!==`none`?(0,T.jsxs)(`span`,{className:`chip ${e.contract_break.kind===`breaking`?`blocker`:``}`,"data-testid":`contract-kind`,children:[`contract `,e.contract_break.kind]}):null]}),(0,T.jsxs)(`div`,{className:`metrics`,children:[(0,T.jsxs)(`div`,{className:`metric`,children:[(0,T.jsxs)(`div`,{className:`n`,children:[e.confidence.covered_sinks,`/`,e.confidence.sinks]}),(0,T.jsx)(`div`,{className:`l`,children:`Sinks tested`})]}),(0,T.jsxs)(`div`,{className:`metric`,children:[(0,T.jsx)(`div`,{className:`n`,children:t.length}),(0,T.jsx)(`div`,{className:`l`,children:`Findings`})]}),(0,T.jsxs)(`div`,{className:`metric`,children:[(0,T.jsx)(`div`,{className:`n`,children:e.residuals.length}),(0,T.jsx)(`div`,{className:`l`,children:`Residuals`})]})]}),(0,T.jsx)(`pre`,{className:`headline`,children:e.headline}),(e.checklist||[]).length?(0,T.jsxs)(`details`,{className:`section`,open:!0,"data-testid":`merge-checklist`,children:[(0,T.jsxs)(`summary`,{children:[`Merge checklist`,` `,(0,T.jsx)(`span`,{className:`count`,children:(e.checklist||[]).filter(e=>e.status===`todo`).length})]}),(e.checklist||[]).map(e=>(0,T.jsxs)(`div`,{className:`check-item ${e.status}`,children:[(0,T.jsxs)(`button`,{type:`button`,className:`linkish`,onClick:()=>e.node_id&&l(e.node_id),children:[(0,T.jsx)(`span`,{className:`chip ${e.status}`,children:e.status}),e.title]}),e.detail?(0,T.jsx)(`div`,{className:`why`,children:e.detail}):null,e.body?(0,T.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>{navigator.clipboard.writeText(e.body||``)},children:`Copy test`}):null,e.kind===`finding`&&e.status===`todo`&&e.rule?(0,T.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>h(e.rule,e.node_id),children:`Waive in loadpath.yml`}):null]},e.id))]}):null,e.index?(0,T.jsxs)(`details`,{className:`section`,open:!0,children:[(0,T.jsxs)(`summary`,{children:[`Index `,(0,T.jsx)(`span`,{className:`count`,children:e.index.counts.nodes})]}),(0,T.jsxs)(`div`,{className:`muted`,children:[`Walked `,e.index.counts.nodes,` nodes / `,e.index.counts.edges,` edges`,e.index.reindex_skipped?` from an unchanged index`:e.index.reindexed?` after an incremental refresh`:` from the existing index`,e.index.django_boot&&e.index.django_boot!==`off`?` · Django boot ${e.index.django_boot}`:``,e.workspace?.three_dot?` · three-dot range`:``]})]}):null,(0,T.jsxs)(`details`,{className:`section`,open:!0,children:[(0,T.jsxs)(`summary`,{children:[`Read this `,(0,T.jsx)(`span`,{className:`count`,children:e.read_order.length})]}),e.read_order.map((e,t)=>(0,T.jsxs)(`div`,{className:t===i?`read-item tour-current`:`read-item`,children:[(0,T.jsxs)(`button`,{type:`button`,className:`linkish file`,onClick:()=>a(t),children:[t+1,`. `,e.path]}),(0,T.jsx)(`div`,{className:`why`,children:e.why}),(0,T.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>u(e.path),children:`Open`})]},e.path)),e.read_order.length>0?(0,T.jsxs)(`div`,{className:`btn-row tour-row`,children:[(0,T.jsx)(`button`,{type:`button`,className:`btn`,"data-testid":`btn-tour-prev`,disabled:i<=0,onClick:()=>a(Math.max(0,i-1)),children:`Previous`}),(0,T.jsx)(`button`,{type:`button`,className:`btn primary`,"data-testid":`btn-tour-next`,disabled:i>=e.read_order.length-1,onClick:()=>a(Math.min(e.read_order.length-1,i+1)),children:`Next in read order`}),(0,T.jsxs)(`span`,{className:`muted`,children:[i+1,`/`,e.read_order.length]})]}):null]}),(0,T.jsxs)(`details`,{className:`section`,children:[(0,T.jsxs)(`summary`,{children:[`Clusters `,(0,T.jsx)(`span`,{className:`count`,children:e.clusters.length})]}),e.clusters.map(e=>(0,T.jsxs)(`div`,{className:`muted`,children:[(0,T.jsx)(`strong`,{children:e.title}),` — `,e.files.join(`, `)]},e.id))]}),(0,T.jsxs)(`details`,{className:`section`,open:!0,children:[(0,T.jsxs)(`summary`,{children:[`Architecture `,(0,T.jsx)(`span`,{className:`count`,children:t.length})]}),t.length===0?(0,T.jsx)(`div`,{className:`muted`,children:e.architecture_note}):t.map(e=>(0,T.jsx)(`div`,{className:`finding`,children:(0,T.jsxs)(`button`,{type:`button`,className:`linkish`,onClick:()=>e.node_id&&l(e.node_id),children:[(0,T.jsx)(`span`,{className:`chip ${e.severity}`,children:e.severity}),e.message]})},e.rule+e.message))]}),(0,T.jsx)(Xm,{cards:e.deepening}),e.contract_break?.reasons?.length?(0,T.jsxs)(`details`,{className:`section`,open:!0,children:[(0,T.jsxs)(`summary`,{children:[`Contract `,(0,T.jsx)(`span`,{className:`count`,children:e.contract_break.kind})]}),e.contract_break.reasons.map(e=>(0,T.jsx)(`div`,{className:`muted`,children:e},e)),e.contract_break.sides?.rows?.length?(0,T.jsxs)(`table`,{className:`type-table`,"data-testid":`contract-sides`,children:[(0,T.jsx)(`thead`,{children:(0,T.jsxs)(`tr`,{children:[(0,T.jsx)(`th`,{children:`Field`}),(0,T.jsx)(`th`,{children:`Serializer`}),(0,T.jsx)(`th`,{children:`Zod`}),(0,T.jsx)(`th`,{children:`GraphQL`})]})}),(0,T.jsx)(`tbody`,{children:e.contract_break.sides.rows.map(e=>(0,T.jsxs)(`tr`,{className:e.status,children:[(0,T.jsx)(`td`,{children:e.field}),(0,T.jsx)(`td`,{children:e.serializer?`yes`:`—`}),(0,T.jsx)(`td`,{children:e.zod?`yes`:`—`}),(0,T.jsx)(`td`,{children:e.graphql?`yes`:`—`})]},e.field))})]}):null]}):null,e.auth?.note?(0,T.jsxs)(`details`,{className:`section`,open:!0,children:[(0,T.jsx)(`summary`,{children:`Auth`}),(0,T.jsx)(`div`,{className:`muted`,children:e.auth.note}),(e.auth.missing_permissions||[]).map(e=>(0,T.jsxs)(`div`,{className:`finding`,children:[(0,T.jsx)(`span`,{className:`chip warning`,children:`missing`}),e.name]},e.id))]}):null,(e.suggested_tests||[]).length?(0,T.jsxs)(`details`,{className:`section`,open:!0,children:[(0,T.jsxs)(`summary`,{children:[`Suggested tests `,(0,T.jsx)(`span`,{className:`count`,children:e.suggested_tests?.length})]}),(e.suggested_tests||[]).map(e=>(0,T.jsxs)(`div`,{className:`residual`,children:[(0,T.jsx)(`strong`,{children:e.title}),(0,T.jsx)(`pre`,{className:`headline`,children:e.body}),(0,T.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>{navigator.clipboard.writeText(e.body)},children:`Copy sketch`})]},e.title))]}):null,e.trend?.note?(0,T.jsxs)(`details`,{className:`section`,children:[(0,T.jsx)(`summary`,{children:`Confidence trend`}),(0,T.jsx)(`div`,{className:`muted`,children:e.trend.note}),(e.trend.points||[]).slice(0,6).map(e=>(0,T.jsxs)(`div`,{className:`muted`,children:[e.level,` · `,M(e.created_at),e.sinks==null?``:` · ${e.sinks} sinks`]},e.id))]}):null,(0,T.jsxs)(`details`,{className:`section`,open:!0,children:[(0,T.jsxs)(`summary`,{children:[`Residual `,(0,T.jsx)(`span`,{className:`count`,children:e.residuals.length})]}),(0,T.jsx)(`p`,{className:`muted`,children:`AI is only used here, on what the graph could not close.`}),e.residuals.map(e=>(0,T.jsx)(`div`,{className:`residual muted`,children:e},e))]}),f.length?(0,T.jsxs)(`details`,{className:`section`,"data-testid":`review-history`,children:[(0,T.jsxs)(`summary`,{children:[`History `,(0,T.jsx)(`span`,{className:`count`,children:f.length})]}),p?(0,T.jsx)(`div`,{className:`muted`,children:p.note}):null,f.slice(0,12).map(t=>(0,T.jsxs)(`button`,{type:`button`,className:t.id===e.id?`history-item current`:`history-item`,onClick:()=>m(t.id),children:[(0,T.jsx)(`span`,{className:`chip ${t.level||``}`,children:t.level||`walk`}),t.title||t.id.slice(0,8),(0,T.jsx)(`span`,{className:`muted`,children:t.created_at?M(t.created_at):``})]},t.id))]}):null,e.evolution?.notes?.length||e.evolution?.hotspots?.some(e=>e.commits)?(0,T.jsxs)(`details`,{className:`section`,children:[(0,T.jsx)(`summary`,{children:`Churn & coupling`}),(e.evolution?.notes||[]).map(e=>(0,T.jsx)(`div`,{className:`muted`,children:e},e)),(e.evolution?.hotspots||[]).filter(e=>e.commits).slice(0,6).map(e=>(0,T.jsxs)(`div`,{className:`muted`,children:[(0,T.jsx)(`span`,{className:`file`,children:e.path}),` — `,e.commits,` commits, bus factor `,e.bus_factor]},e.path))]}):null,(0,T.jsxs)(`div`,{className:`btn-row`,children:[(0,T.jsx)(`button`,{type:`button`,className:`btn`,disabled:r,onClick:o,children:`Ask configured model`}),(0,T.jsx)(`button`,{type:`button`,className:`btn`,"data-testid":`btn-copy-markdown`,onClick:s,children:`Copy markdown`}),(0,T.jsx)(`button`,{type:`button`,className:`btn`,"data-testid":`btn-export-html`,onClick:d,children:`Save HTML`}),(0,T.jsx)(`button`,{type:`button`,className:`btn`,"data-testid":`btn-post-comment`,disabled:r||!!e.what_if,title:e.what_if?`Hypothetical walks are not posted to a pull request`:void 0,onClick:c,children:`Post to PR`})]}),n?(0,T.jsx)(`pre`,{className:`headline`,children:n}):null,(0,T.jsx)(`div`,{className:`kicker`,children:`Reviewers`}),(0,T.jsx)(`div`,{className:`muted`,children:e.suggested_reviewers.join(`, `)||`—`}),e.codeowners_reviewers?.length?(0,T.jsxs)(`div`,{className:`muted`,children:[`CODEOWNERS: `,e.codeowners_reviewers.join(`, `)]}):null,e.knowledge_owners?.length?(0,T.jsxs)(`div`,{className:`muted`,children:[`Knowledge: `,e.knowledge_owners.join(`, `)]}):null]})}function Ym({architecture:e,busy:t,onReindex:n,onReview:r,onSelect:i,config:a,health:o,onSaveConfig:s,onWaiver:c}){let l=e.findings.filter(e=>!e.waived);return(0,T.jsxs)(T.Fragment,{children:[(0,T.jsxs)(`div`,{className:`merge-box high`,children:[(0,T.jsxs)(`div`,{className:`level high`,children:[`INDEXED — `,e.counts.nodes,` nodes`]}),(0,T.jsxs)(`div`,{className:`muted`,style:{marginTop:8},children:[e.indexed_at?`Last index ${M(e.indexed_at)}`:`Indexed`,e.incremental?` · incremental`:` · full`,e.stale?` · stale`:``,e.django_boot&&e.django_boot!==`off`?` · Django boot ${e.django_boot}`:``]}),(0,T.jsxs)(`span`,{className:`chip`,children:[e.counts.edges,` edges`]}),e.has_config?(0,T.jsx)(`span`,{className:`chip`,children:`loadpath.yml`}):null]}),(0,T.jsxs)(`details`,{className:`section`,open:!0,children:[(0,T.jsx)(`summary`,{children:`Bounded contexts`}),Object.values(e.contexts).map(e=>(0,T.jsxs)(`div`,{className:`muted`,children:[(0,T.jsx)(`strong`,{children:e.name}),` — `,(e.django_apps||[]).join(`, `)||`no apps`,` ·`,` `,(e.owners||[]).join(`, `)||`unowned`]},e.name))]}),(0,T.jsxs)(`details`,{className:`section`,children:[(0,T.jsxs)(`summary`,{children:[`Rules `,(0,T.jsx)(`span`,{className:`count`,children:(e.rules||[]).length})]}),(e.rules||[]).map(e=>(0,T.jsx)(`div`,{className:`muted`,children:e},e))]}),(0,T.jsxs)(`details`,{className:`section`,open:!0,children:[(0,T.jsxs)(`summary`,{children:[`Findings `,(0,T.jsx)(`span`,{className:`count`,children:l.length})]}),l.length===0?(0,T.jsx)(`div`,{className:`muted`,children:`No architecture rule hits on the full graph.`}):l.map(e=>(0,T.jsx)(`div`,{className:`finding`,children:(0,T.jsxs)(`button`,{type:`button`,className:`linkish`,onClick:()=>e.node_id&&i(e.node_id),children:[(0,T.jsx)(`span`,{className:`chip ${e.severity}`,children:e.severity}),e.message]})},e.rule+e.message))]}),(0,T.jsx)(Xm,{cards:e.deepening}),o?.points?.length?(0,T.jsxs)(`details`,{className:`section`,open:!0,"data-testid":`architecture-health`,children:[(0,T.jsxs)(`summary`,{children:[`Health over time `,(0,T.jsx)(`span`,{className:`count`,children:o.points.length})]}),(0,T.jsx)(`div`,{className:`sparkline`,"aria-hidden":`true`,children:o.points.map(e=>(0,T.jsx)(`i`,{className:e.level||``,title:`${e.level} · ${e.findings} findings`,style:{height:`${8+Math.min(24,(e.findings||0)*4)}px`}},e.id||e.created_at))}),Object.entries(o.contexts).map(([e,t])=>(0,T.jsxs)(`div`,{className:`muted`,children:[(0,T.jsx)(`strong`,{children:e}),` — last `,t[t.length-1]?.findings??0,` findings`]},e))]}):null,a?(0,T.jsxs)(`details`,{className:`section`,open:!0,children:[(0,T.jsx)(`summary`,{children:`loadpath.yml`}),(0,T.jsx)(O,{config:a,busy:t,onSave:s,onWaiver:c})]}):null,(0,T.jsxs)(`details`,{className:`section`,open:!0,children:[(0,T.jsx)(`summary`,{children:`Types`}),(0,T.jsx)(`table`,{className:`type-table`,children:(0,T.jsx)(`tbody`,{children:Object.entries(e.type_counts||{}).sort((e,t)=>t[1]-e[1]).slice(0,12).map(([e,t])=>(0,T.jsxs)(`tr`,{children:[(0,T.jsx)(`td`,{children:j(e)}),(0,T.jsx)(`td`,{children:t})]},e))})})]}),(0,T.jsxs)(`div`,{className:`btn-row`,children:[(0,T.jsx)(`button`,{type:`button`,className:`btn`,disabled:t,onClick:n,"data-testid":`btn-full-reindex`,children:`Full reindex`}),(0,T.jsx)(`button`,{type:`button`,className:`btn primary`,disabled:t,onClick:r,children:`Review against this index`})]})]})}function Xm({cards:e}){let t=e||[];return t.length?(0,T.jsxs)(`details`,{className:`section`,open:!0,"data-testid":`deepening-list`,children:[(0,T.jsxs)(`summary`,{children:[`Depth `,(0,T.jsx)(`span`,{className:`count`,children:t.length})]}),(0,T.jsx)(`p`,{className:`muted`,children:`Deepening opportunities: more behaviour behind a smaller interface, at a real seam.`}),t.map(e=>(0,T.jsxs)(`div`,{className:`finding`,"data-testid":`deepening-card`,children:[(0,T.jsx)(`span`,{className:`chip ${e.strength}`,children:A(e.strength)}),e.top?(0,T.jsx)(`span`,{className:`chip`,children:`top`}):null,(0,T.jsx)(`strong`,{children:e.title}),(0,T.jsx)(`div`,{className:`why`,children:e.message}),e.deletion_test?(0,T.jsxs)(`div`,{className:`muted`,children:[`Deletion test: `,e.deletion_test]}):null,e.before&&e.after?(0,T.jsxs)(`div`,{className:`muted`,children:[e.before,` → `,e.after]}):null]},e.rule+e.title))]}):null}Wm(Hm()),(0,v.createRoot)(document.getElementById(`root`)).render((0,T.jsx)(_.StrictMode,{children:(0,T.jsx)(qm,{})}));export{np as a,u as c,rp as i,c as l,tp as n,j as o,ap as r,w as s,Gf as t}; \ No newline at end of file diff --git a/src/loadpath/static/index.html b/src/loadpath/static/index.html index 5adfabf..9c9dc55 100644 --- a/src/loadpath/static/index.html +++ b/src/loadpath/static/index.html @@ -17,7 +17,7 @@ - + diff --git a/src/loadpath/stitch/openapi.py b/src/loadpath/stitch/openapi.py index b6aab0e..a655e9d 100644 --- a/src/loadpath/stitch/openapi.py +++ b/src/loadpath/stitch/openapi.py @@ -7,6 +7,7 @@ from loadpath.config import LoadpathConfig from loadpath.extractors.react import normalize_url_template from loadpath.graph.store import GraphStore +from loadpath.scan import iter_named_files from loadpath.types import Edge, EdgeType, Node, NodeType, node_id DJANGO_PATH_PARAM = re.compile(r"""<(?:(?:int|str|slug|uuid|path):)?([^>]+)>""") @@ -59,16 +60,16 @@ def load_openapi(repo_root: Path, config: LoadpathConfig) -> list[dict]: paths: list[dict] = [] candidates = list(config.openapi_paths) if not candidates: - for pattern in ( - "**/schema.yml", - "**/schema.yaml", - "**/openapi.yaml", - "**/openapi.yml", - "**/openapi.json", - "**/schema.json", - "**/swagger.json", - ): - candidates.extend(str(p.relative_to(repo_root)) for p in repo_root.glob(pattern)) + names = { + "schema.yml", + "schema.yaml", + "openapi.yaml", + "openapi.yml", + "openapi.json", + "schema.json", + "swagger.json", + } + candidates.extend(str(p.relative_to(repo_root)) for p in iter_named_files(repo_root, names)) for rel in candidates: path = repo_root / rel if not path.is_file(): @@ -180,7 +181,7 @@ def stitch(store: GraphStore, config: LoadpathConfig, repo_root: Path) -> list[s serializers = [n for n in store.nodes([NodeType.SERIALIZER])] ser_fields = [n for n in store.nodes([NodeType.SERIALIZER_FIELD])] schemas = [n for n in store.nodes([NodeType.FORM_SCHEMA])] - generated_files = _generated_client_files(repo_root, config) + generated_files = _generated_client_files(config, store.indexed_paths()) generated_templates: set[str] = set() for client in clients: raw = (client.get("extra") or {}).get("raw") or client["name"] @@ -189,48 +190,57 @@ def stitch(store: GraphStore, config: LoadpathConfig, repo_root: Path) -> list[s generated_templates.add(tmpl) # Clients consumed_by matching routes / openapi + routes_by_tmpl: dict[str, list[dict]] = {} + prepared_routes: list[tuple[dict, str]] = [] + for route in routes: + extra = route.get("extra") or {} + if extra.get("include"): + continue + rtmpl = django_route_to_template(str(published_route(route))) + prepared_routes.append((route, rtmpl)) + routes_by_tmpl.setdefault(rtmpl, []).append(route) + for client in clients: raw = (client.get("extra") or {}).get("raw") or client["name"] tmpl = normalize_url_template(str(raw)) matched = False generated = _client_is_generated(client, generated_files) - for route in routes: + hits = routes_by_tmpl.get(tmpl) + if hits is None: + hits = [route for route, rtmpl in prepared_routes if _paths_match(tmpl, rtmpl)] + for route in hits: extra = route.get("extra") or {} - if extra.get("include"): - continue - rraw = published_route(route) - rtmpl = django_route_to_template(str(rraw)) - if _paths_match(tmpl, rtmpl): - if generated: - conf = 0.95 - elif tmpl in generated_templates: - conf = 0.4 - else: - conf = 0.55 - store.upsert_edge( - Edge( - src=route["id"], - dst=client["id"], - type=EdgeType.CONSUMED_BY_CLIENT, - confidence=conf, - extra={ - "match": "url_template", - "generated_client": generated, - "django": rtmpl, - "react": tmpl, - "superseded_by_generated": bool(not generated and tmpl in generated_templates), - }, - ) + rtmpl = django_route_to_template(str(published_route(route))) + if generated: + conf = 0.95 + elif tmpl in generated_templates: + conf = 0.4 + else: + conf = 0.55 + store.upsert_edge( + Edge( + src=route["id"], + dst=client["id"], + type=EdgeType.CONSUMED_BY_CLIENT, + confidence=conf, + extra={ + "match": "url_template", + "generated_client": generated, + "django": rtmpl, + "react": tmpl, + "superseded_by_generated": bool(not generated and tmpl in generated_templates), + }, ) - matched = True - if not generated: - note = f"Inferred client stitch {tmpl} ↔ {rtmpl} from string URL in {client.get('file_path')}" - if tmpl in generated_templates: - note += " (generated OpenAPI client already covers this URL)" - else: - note += " (not a generated OpenAPI client)" - residuals.append(note) + ) + matched = True + if not generated: + note = f"Inferred client stitch {tmpl} ↔ {rtmpl} from string URL in {client.get('file_path')}" + if tmpl in generated_templates: + note += " (generated OpenAPI client already covers this URL)" + else: + note += " (not a generated OpenAPI client)" + residuals.append(note) for op in openapi_by_path.get(tmpl, []): store.upsert_edge( Edge( @@ -617,16 +627,27 @@ def _client_is_generated(client: dict, generated_files: list[str]) -> bool: return generated or "/generated/" in f"/{fp}/" or "openapi" in Path(fp).name.lower() -def _generated_client_files(repo_root: Path, config: LoadpathConfig) -> list[str]: - found: list[str] = [] +def _generated_client_files(config: LoadpathConfig, indexed_rels: list[str]) -> list[str]: + """Match already-indexed paths against generated-client globs (no tree walk).""" + from fnmatch import fnmatch + + patterns: list[str] = [] for pattern in config.generated_client_globs: - # pathlib doesn't expand {ts,tsx} if "{" in pattern: pre, rest = pattern.split("{", 1) exts = rest.split("}", 1)[0].split(",") suffix = rest.split("}", 1)[1] if "}" in rest else "" for ext in exts: - found.extend(str(p.relative_to(repo_root)) for p in repo_root.glob(pre + ext + suffix)) + patterns.append(_glob_to_fnmatch(pre + ext + suffix)) else: - found.extend(str(p.relative_to(repo_root)) for p in repo_root.glob(pattern)) + patterns.append(_glob_to_fnmatch(pattern)) + found: list[str] = [] + for rel in indexed_rels: + path = rel.replace("\\", "/") + if any(fnmatch(path, pat) for pat in patterns): + found.append(rel) return found + + +def _glob_to_fnmatch(pattern: str) -> str: + return pattern.replace("\\", "/").replace("**/", "*").replace("**", "*") diff --git a/tests/unit/test_index_scan.py b/tests/unit/test_index_scan.py new file mode 100644 index 0000000..a9bdc32 --- /dev/null +++ b/tests/unit/test_index_scan.py @@ -0,0 +1,109 @@ +from __future__ import annotations + +import time +from pathlib import Path + +from loadpath.architecture.snapshot import architecture_report +from loadpath.config import LoadpathConfig +from loadpath.index import index_repo, iter_source_files +from loadpath.scan import is_minified_name, skip_dir_name + + +def test_skip_dir_names_cover_install_trees(): + assert skip_dir_name("node_modules") + assert skip_dir_name(".git") + assert skip_dir_name(".next") + assert not skip_dir_name("frontend") + assert not skip_dir_name("cypress") + + +def test_minified_and_dts_are_not_source(): + assert is_minified_name("vendor.min.js") + assert is_minified_name("app.bundle.js") + assert is_minified_name("types.d.ts") + assert not is_minified_name("App.tsx") + assert not is_minified_name("models.py") + + +def test_iter_source_files_prunes_node_modules_and_minified(tmp_path: Path): + (tmp_path / "backend").mkdir() + (tmp_path / "backend" / "views.py").write_text("def hello():\n return 1\n") + junk = tmp_path / "node_modules" / "pkg" / "dist" + junk.mkdir(parents=True) + (junk / "index.js").write_text("export const x = 1;\n") + (tmp_path / "frontend" / "src").mkdir(parents=True) + (tmp_path / "frontend" / "src" / "vendor.min.js").write_text("const a=1;\n" * 1000) + (tmp_path / "frontend" / "src" / "App.tsx").write_text("export function App() { return
; }\n") + + cfg = LoadpathConfig(repo_root=tmp_path) + files = iter_source_files(tmp_path, cfg) + rels = {p.relative_to(tmp_path).as_posix() for p in files} + assert "backend/views.py" in rels + assert "frontend/src/App.tsx" in rels + assert not any("node_modules" in rel for rel in rels) + assert not any(rel.endswith(".min.js") for rel in rels) + + +def test_pruned_walk_does_not_stat_skipped_trees(tmp_path: Path): + (tmp_path / "app.py").write_text("x = 1\n") + nested = tmp_path / "node_modules" / "pkg" + nested.mkdir(parents=True) + (nested / "index.js").write_text("export default 1;\n") + + seen: list[str] = [] + original_stat = Path.stat + + def wrapped(self, *args, **kwargs): + seen.append(str(self)) + return original_stat(self, *args, **kwargs) + + Path.stat = wrapped # type: ignore[method-assign] + try: + from loadpath.config import LoadpathConfig + from loadpath.index import iter_source_files + + iter_source_files(tmp_path, LoadpathConfig(repo_root=tmp_path)) + finally: + Path.stat = original_stat # type: ignore[method-assign] + + assert not any("node_modules" in path for path in seen) + + +def test_architecture_report_uses_cached_findings(tmp_path: Path, monkeypatch): + from loadpath.architecture import snapshot as snap + from tests.conftest import prepare_review_repo + + repo = prepare_review_repo(tmp_path) + store = index_repo(repo, incremental=False, workers=1) + assert store.get_meta("findings_json") + store.close() + + calls = {"n": 0} + real = snap.evaluate + + def wrapped(store, config, changed_ids=None): + calls["n"] += 1 + return real(store, config, changed_ids=changed_ids) + + monkeypatch.setattr(snap, "evaluate", wrapped) + monkeypatch.setattr("loadpath.architecture.rules.evaluate", wrapped) + report = architecture_report(repo, include_graph=False) + assert report["indexed"] is True + assert calls["n"] == 0 + assert isinstance(report["findings"], list) + + +def test_large_junk_tree_scan_stays_cheap(tmp_path: Path): + (tmp_path / "backend").mkdir() + (tmp_path / "backend" / "models.py").write_text("class M:\n pass\n") + for i in range(80): + pkg = tmp_path / "node_modules" / f"pkg{i}" / "dist" + pkg.mkdir(parents=True) + for j in range(40): + (pkg / f"f{j}.js").write_text("export const x = 1;\n") + cfg = LoadpathConfig(repo_root=tmp_path) + t0 = time.monotonic() + files = iter_source_files(tmp_path, cfg) + elapsed = time.monotonic() - t0 + assert len(files) == 1 + assert elapsed < 0.4 diff --git a/ui/src/ImpactGraph.tsx b/ui/src/ImpactGraph.tsx index b62fccb..6e1804e 100644 --- a/ui/src/ImpactGraph.tsx +++ b/ui/src/ImpactGraph.tsx @@ -820,6 +820,7 @@ function ImpactGraphView({ deleteKeyCode={null} onNodeClick={onNodeClick} onPaneClick={clearSelection} + onlyRenderVisibleElements={rfNodes.length >= 90} proOptions={{ hideAttribution: false }} data-testid="impact-graph" > diff --git a/ui/src/types.ts b/ui/src/types.ts index ccaa8b7..76c043d 100644 --- a/ui/src/types.ts +++ b/ui/src/types.ts @@ -498,7 +498,8 @@ export function layoutNodes( const inColumn = (colIndex: number) => (nbr: string) => colOf.get(nbr) === colIndex; - for (let pass = 0; pass < LAYOUT_PASSES; pass++) { + const passes = nodes.length > 400 ? 2 : nodes.length > 120 ? 4 : LAYOUT_PASSES; + for (let pass = 0; pass < passes; pass++) { for (let i = 1; i < order.length; i++) { order[i] = sortByBarycenter(order[i]!, (id) => (preds.get(id) ?? []).filter(inColumn(i - 1))); refreshRanks();