Skip to content

🎯 The ultimate OSINT toolkit: investigation graph, confidence scoring, alias families, map, timeline and reports. 49 modules, 400+ sites, no API keys required.

OsintHunter v1.0.0

letox43dc8357fcab8
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..5800aa5
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,7 @@
+.venv/
+build/
+dist/
+*.spec
+data/
+__pycache__/
+*.pyc
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..744ea64
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 letox4
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..330c475
--- /dev/null
+++ b/README.md
@@ -0,0 +1,184 @@
+<div align="center">
+
+<img src="docs/banner.svg" alt="OsintHunter" width="100%">
+
+<br>
+
+[![Release](https://img.shields.io/github/v/release/letox4/OsintHunter?style=for-the-badge&color=ff7a1a&labelColor=0d0a07&logo=github)](https://github.com/letox4/OsintHunter/releases/latest)
+[![Downloads](https://img.shields.io/github/downloads/letox4/OsintHunter/total?style=for-the-badge&color=ff7a1a&labelColor=0d0a07&logo=windows)](https://github.com/letox4/OsintHunter/releases)
+[![Python](https://img.shields.io/badge/Python-3.11+-ff7a1a?style=for-the-badge&labelColor=0d0a07&logo=python&logoColor=ffb066)](https://www.python.org/)
+[![FastAPI](https://img.shields.io/badge/FastAPI-backend-ff7a1a?style=for-the-badge&labelColor=0d0a07&logo=fastapi&logoColor=ffb066)](https://fastapi.tiangolo.com/)
+[![License](https://img.shields.io/badge/licencia-MIT-ff7a1a?style=for-the-badge&labelColor=0d0a07)](LICENSE)
+
+[![Módulos](https://img.shields.io/badge/m%C3%B3dulos-49-ffb066?style=flat-square&labelColor=1c1209)](#-módulos)
+[![Sitios](https://img.shields.io/badge/sitios_por_usuario-400+-ffb066?style=flat-square&labelColor=1c1209)](#-módulos)
+[![Sin claves](https://img.shields.io/badge/funciona_sin_API_keys-s%C3%AD-ffb066?style=flat-square&labelColor=1c1209)](#-claves-de-api-opcionales)
+[![Idiomas](https://img.shields.io/badge/UI-ES%20%7C%20EN-ffb066?style=flat-square&labelColor=1c1209)](#)
+[![Local](https://img.shields.io/badge/100%25-local-ffb066?style=flat-square&labelColor=1c1209)](#-privacidad)
+
+### ${\color{#ff7a1a}\textsf{Encuentra.\ Conecta.\ Confirma.}}$
+
+**Plataforma OSINT de escritorio** que parte de un usuario, email, teléfono, nombre, dominio, IP o RUT<br>
+y construye un **grafo de investigación** con puntuación de confianza, mapa, línea de tiempo e informe.
+
+[**⬇️ Descargar .exe**](https://github.com/letox4/OsintHunter/releases/latest) ·
+[**🚀 Inicio rápido**](#-inicio-rápido) ·
+[**🧩 Módulos**](#-módulos) ·
+[**📸 Capturas**](#-capturas) ·
+[**🇬🇧 English**](#-english)
+
+</div>
+
+---
+
+<div align="center">
+<img src="docs/screenshots/graph.png" alt="Grafo de investigación" width="100%">
+<sub><i>Grafo de un caso de demostración. Todas las capturas usan una persona <b>ficticia</b> y dominios <code>.example</code>.</i></sub>
+</div>
+
+## ✨ Qué lo hace distinto
+
+| | |
+|---|---|
+| 🕸️ **Grafo vivo** | Cada hallazgo es un nodo; las relaciones se dibujan solas. Agrupa en burbujas por tipo, plataforma o **familia de alias**. |
+| 🎯 **Puntuación de confianza** | Cada cuenta recibe una nota 0-100 según nombre, foto, ubicación y enlaces cruzados. Separa a la persona real de sus **homónimos**. |
+| 🧬 **Familias de alias** | Detecta que `nyxaluna`, `nyxa.lun4` y `xnyxax` son la misma raíz (leet, repeticiones, prefijos) y prueba variantes. |
+| 🔁 **Reintento inteligente** | Cuando Instagram, TikTok o un WAF bloquean, reintenta con pausas y te deja una lista para comprobar a mano. |
+| 🇨🇱 **Fuentes de Chile** | RUT, patentes, NIC Chile, InfoProbidad, empresas por RUT y tesis universitarias. |
+| 🗺️ **Mapa y línea de tiempo** | Geocodifica ubicaciones y ordena cronológicamente creaciones de cuentas, commits, filtraciones y archivos. |
+| 📄 **Informe** | Exporta el caso a HTML/PDF listo para entregar. |
+| 🤖 **IA opcional** | Resumen y análisis del caso con Ollama local o un proveedor compatible con OpenAI. |
+| 🔒 **Todo local** | Una sola `.exe`, base de datos SQLite a su lado, nada sale de tu equipo salvo las consultas a las fuentes. |
+
+## 📸 Capturas
+
+<table>
+ <tr>
+ <td width="50%"><img src="docs/screenshots/confidence.png" alt="Confianza"><br><b>${\color{#ff7a1a}\textsf{Confianza}}$</b> · por qué una cuenta es (o no) la persona</td>
+ <td width="50%"><img src="docs/screenshots/alias.png" alt="Alias"><br><b>${\color{#ff7a1a}\textsf{Familias\ de\ alias}}$</b> · raíz común y variantes probadas</td>
+ </tr>
+ <tr>
+ <td><img src="docs/screenshots/bubbles.png" alt="Burbujas"><br><b>${\color{#ff7a1a}\textsf{Burbujas}}$</b> · el grafo agrupado por familia de alias</td>
+ <td><img src="docs/screenshots/map.png" alt="Mapa"><br><b>${\color{#ff7a1a}\textsf{Mapa}}$</b> · ubicaciones geocodificadas</td>
+ </tr>
+ <tr>
+ <td><img src="docs/screenshots/timeline.png" alt="Línea de tiempo"><br><b>${\color{#ff7a1a}\textsf{Línea\ de\ tiempo}}$</b> · la historia digital en orden</td>
+ <td><img src="docs/screenshots/list.png" alt="Lista"><br><b>${\color{#ff7a1a}\textsf{Lista}}$</b> · todas las entidades con filtros</td>
+ </tr>
+ <tr>
+ <td><img src="docs/screenshots/report.png" alt="Informe"><br><b>${\color{#ff7a1a}\textsf{Informe}}$</b> · exportable a HTML/PDF</td>
+ <td><img src="docs/screenshots/english.png" alt="English UI"><br><b>${\color{#ff7a1a}\textsf{English\ UI}}$</b> · interfaz bilingüe ES / EN</td>
+ </tr>
+</table>
+
+## 🚀 Inicio rápido
+
+### Opción 1 · Ejecutable (Windows)
+
+1. Descarga **`OsintHunter.exe`** desde [Releases](https://github.com/letox4/OsintHunter/releases/latest).
+2. Ponlo en cualquier carpeta y ábrelo. Se abre el navegador en `http://127.0.0.1:8787`.
+3. Crea un caso, escribe un usuario / email / teléfono / nombre y pulsa **Investigar**.
+
+> [!NOTE]
+> Los datos se guardan en una carpeta `data` junto al `.exe`. Windows SmartScreen puede avisar porque el ejecutable no está firmado: *Más información → Ejecutar de todas formas*.
+
+### Opción 2 · Desde el código
+
+```bash
+git clone https://github.com/letox4/OsintHunter.git
+cd OsintHunter
+start.bat # crea el entorno, instala dependencias y arranca
+```
+
+En Linux / macOS:
+
+```bash
+python3 -m venv .venv && source .venv/bin/activate
+pip install -r requirements.txt
+python -m app
+```
+
+### Generar tu propio .exe
+
+```bash
+build_exe.bat # deja el resultado en dist\OsintHunter.exe
+```
+
+## 🧩 Módulos
+
+<details open>
+<summary><b>${\color{#ff7a1a}\textsf{49\ módulos}}$</b> organizados por tipo de dato</summary>
+
+<br>
+
+| Entrada | Módulos |
+|---|---|
+| 👤 **Usuario** | Perfiles detallados (Instagram, TikTok, GitHub, Reddit…), barrido en **400+ sitios** (base de Sherlock), variantes y familias de alias, reintento de bloqueados, GitHub a fondo, perfiles archivados en Wayback, menciones en foros, lectura de la página del perfil |
+| 📧 **Email** | Validación MX, Gravatar, filtraciones (XposedOrNot, HIBP), cuentas registradas en apps, Hunter.io |
+| 📱 **Teléfono** | Operador, país y tipo de línea, Numverify |
+| 🧑 **Persona** | Búsqueda web (DuckDuckGo, Bing, Serper, Brave), dorks, Wikidata, publicaciones académicas |
+| 🌐 **Dominio / URL** | DNS, RDAP/WHOIS, subdominios (crt.sh), análisis del sitio, Wayback, VirusTotal, URLScan, URLhaus |
+| 🖥️ **IP** | Geolocalización, Shodan InternetDB, DNS inverso, Shodan, AbuseIPDB, GreyNoise |
+| 🇨🇱 **Chile** | RUT, patentes, NIC Chile, InfoProbidad / lobby, empresas por RUT, tesis |
+| 📎 **Otros** | Metadatos de documentos e imágenes (EXIF/GPS), hashes, MalwareBazaar, carteras cripto, invitaciones de Discord, Flickr geo |
+
+</details>
+
+## 🔑 Claves de API opcionales
+
+OsintHunter **funciona sin ninguna clave**. Si añades alguna en *Ajustes*, se activan más fuentes:
+
+<details>
+<summary>Ver las 13 integraciones</summary>
+
+<br>
+
+| Servicio | Para qué |
+|---|---|
+| Serper.dev / Brave Search | Búsqueda web más fiable (Google) |
+| GitHub token | Sube el límite de 60 a 5000 peticiones/h |
+| Have I Been Pwned | Filtraciones de un email |
+| Hunter.io | Verificación de emails |
+| Numverify | Datos del teléfono |
+| Shodan · AbuseIPDB · GreyNoise | Reputación de IPs |
+| VirusTotal · URLScan · abuse.ch | Reputación de dominios y URLs |
+| Proveedor de IA | Análisis con IA (no hace falta con Ollama local) |
+
+</details>
+
+## 🔒 Privacidad
+
+- Todo se ejecuta en **tu equipo** (`127.0.0.1`); no hay servidores intermedios ni telemetría.
+- Los casos, ajustes y claves se guardan en `data/`, que está excluido del repositorio.
+
+## ⚖️ Uso responsable
+
+> [!WARNING]
+> OsintHunter consulta **solo fuentes públicas**. Está pensado para investigación legítima: ciberseguridad, periodismo, verificación de identidad, búsqueda de personas desaparecidas o auditar tu propia huella digital.
+> **No lo uses para acosar, acechar ni vulnerar la privacidad de nadie.** Respeta las leyes de protección de datos de tu país y los términos de cada servicio. El autor no se hace responsable del mal uso.
+
+---
+
+## 🇬🇧 English
+
+**OsintHunter** is a local, desktop OSINT platform. Start from a username, email, phone, name, domain, IP or Chilean RUT and it builds an **investigation graph** with **confidence scoring**, alias-family detection, a map, a timeline and an exportable report. 49 modules, 400+ username sites, works with **zero API keys**, single Windows `.exe`, bilingual UI.
+
+```bash
+git clone https://github.com/letox4/OsintHunter.git && cd OsintHunter
+start.bat # Windows
+python -m app # Linux / macOS (after pip install -r requirements.txt)
+```
+
+Use it ethically and only for lawful purposes.
+
+---
+
+<div align="center">
+
+### ${\color{#ff7a1a}\textsf{Hecho\ por\ letox4}}$
+
+Si te sirve, deja una ⭐. Ayuda mucho.
+
+<sub>MIT © 2026 letox4</sub>
+
+</div>
diff --git a/app/__init__.py b/app/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/app/__main__.py b/app/__main__.py
new file mode 100644
index 0000000..f734c45
--- /dev/null
+++ b/app/__main__.py
@@ -0,0 +1,35 @@
+import os
+import socket
+import sys
+import threading
+import webbrowser
+
+import uvicorn
+
+
+def _in_use(host: str, port: int) -> bool:
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
+ s.settimeout(0.5)
+ return s.connect_ex((host, port)) == 0
+
+
+def main() -> None:
+ host = "127.0.0.1"
+ port = int(os.environ.get("OSINT_PORT", "8787"))
+ url = f"http://{host}:{port}"
+ open_browser = "--no-browser" not in sys.argv
+ if _in_use(host, port):
+ print(f"\n OsintHunter ya está abierto en {url}\n")
+ if open_browser:
+ webbrowser.open(url)
+ return
+ from app.main import app
+
+ if open_browser:
+ threading.Timer(1.5, lambda: webbrowser.open(url)).start()
+ print(f"\n OsintHunter funcionando en {url}\n Cierra esta ventana para detenerlo.\n")
+ uvicorn.run(app, host=host, port=port, log_level="warning")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/app/analysis.py b/app/analysis.py
new file mode 100644
index 0000000..d47e720
--- /dev/null
+++ b/app/analysis.py
@@ -0,0 +1,378 @@
+"""Análisis a nivel de caso: fotos de perfil repetidas, confianza de identidad y verificación con IA."""
+
+import asyncio
+import io
+import json
+import re
+import time
+import unicodedata
+from collections import Counter, defaultdict
+
+import httpx
+from PIL import Image, ImageStat
+
+from .config import settings
+from .db import db
+from .models import ENTITY_TYPES
+
+CASE_EID = "case"
+PHOTO_REL = "misma foto de perfil"
+DEFAULT_AVATAR = re.compile(
+ r"default|placeholder|no[-_]?avatar|blank|anonymous|silhouette|/avatar_default|d=mp|d=identicon|sticky/default_profile",
+ re.I,
+)
+NAME_KEYS = ("Nombre", "Nombre visible", "Nombre real")
+
+
+def _emit_entity(job, ent: dict | None) -> None:
+ if ent:
+ job.emit({"type": "entity", "entity": ent, "created": False})
+
+
+def _record(job, module: str, status: str, message: str, found: int, started: float) -> None:
+ run = db.add_run(job.case_id, CASE_EID, module, status, message, found, started)
+ job.emit({"type": "run", "run": run})
+
+
+# ---------------------------------------------------------------- fotos
+
+
+def dhash(data: bytes) -> int | None:
+ img = Image.open(io.BytesIO(data))
+ img.seek(0)
+ gray = img.convert("L")
+ if ImageStat.Stat(gray).stddev[0] < 6: # imagen casi plana: avatar genérico
+ return None
+ px = list(gray.resize((9, 8), Image.LANCZOS).getdata())
+ bits = 0
+ for row in range(8):
+ for col in range(8):
+ bits = (bits << 1) | int(px[row * 9 + col] > px[row * 9 + col + 1])
+ return bits
+
+
+async def _hash_avatar(http: httpx.AsyncClient, url: str) -> str:
+ try:
+ r = await http.get(url, timeout=12)
+ if r.status_code != 200 or len(r.content) > 6_000_000 or "image" not in r.headers.get("content-type", "image"):
+ return ""
+ h = dhash(r.content)
+ return f"{h:016x}" if h is not None else ""
+ except Exception: # noqa: BLE001 (formatos no soportados, errores de red...)
+ return ""
+
+
+async def photo_match(engine, job) -> None:
+ started = time.time()
+ graph = db.graph(job.case_id)
+ targets = [
+ e for e in graph["entities"]
+ if isinstance(e["attrs"].get("_avatar"), str) and e["attrs"]["_avatar"].startswith("http")
+ and not DEFAULT_AVATAR.search(e["attrs"]["_avatar"])
+ ]
+ todo = [e for e in targets if e["attrs"].get("_phash_src") != e["attrs"]["_avatar"]]
+ sem = asyncio.Semaphore(8)
+
+ async def one(e):
+ async with sem:
+ h = await _hash_avatar(engine.http, e["attrs"]["_avatar"])
+ ent = db.update_attrs(job.case_id, e["id"], {"_phash": h, "_phash_src": e["attrs"]["_avatar"]}, replace=True)
+ e["attrs"]["_phash"] = h
+ _emit_entity(job, ent)
+
+ await asyncio.gather(*(one(e) for e in todo))
+ hashed = [(e, int(e["attrs"]["_phash"], 16)) for e in targets if e["attrs"].get("_phash")]
+ if len(hashed) < 2:
+ if todo:
+ _record(job, "photo_match", "empty", f"{len(hashed)} fotos comparables", 0, started)
+ return
+ # Un mismo hash repetido en muchísimas cuentas suele ser una imagen genérica de la plataforma.
+ counts = Counter(h for _, h in hashed)
+ pairs = []
+ for i in range(len(hashed)):
+ for j in range(i + 1, len(hashed)):
+ (a, ha), (b, hb) = hashed[i], hashed[j]
+ if counts[ha] > 6 or counts[hb] > 6:
+ continue
+ # la misma URL de imagen en dos usuarios distintos de un sitio es la imagen genérica de ese sitio
+ if a["attrs"]["_avatar"] == b["attrs"]["_avatar"] and a["attrs"].get("Plataforma") == b["attrs"].get("Plataforma"):
+ continue
+ dist = bin(ha ^ hb).count("1")
+ if dist <= 6:
+ pairs.append((a, b, dist))
+ new = 0
+ for a, b, dist in pairs:
+ if db.add_edge(job.case_id, a["id"], b["id"], PHOTO_REL, "photo_match"):
+ new += 1
+ job.emit({"type": "edge", "edge": {"src": a["id"], "dst": b["id"], "label": PHOTO_REL, "source": "photo_match"}})
+ sim = round(100 - dist * 100 / 64)
+ for x, y in ((a, b), (b, a)):
+ ent = db.update_attrs(job.case_id, x["id"], {"Foto coincide con": [f"{y['label']} ({sim}%)"]})
+ _emit_entity(job, ent)
+ if todo or new:
+ _record(job, "photo_match", "ok" if pairs else "empty",
+ f"{len(hashed)} fotos comparadas · {len(pairs)} coincidencias" + (f" ({new} nuevas)" if new else ""),
+ len(pairs), started)
+
+
+# ---------------------------------------------------------------- confianza de identidad
+
+
+def _tokens(name: str) -> set[str]:
+ name = unicodedata.normalize("NFKC", name or "")
+ return {t for t in re.findall(r"[a-záéíóúñüçàèìòùâêîôûäëïöü]+", name.lower()) if len(t) >= 3}
+
+
+def _overlap(toks: set[str], ref: set[str]) -> bool:
+ """Palabras en común; un apodo cuenta si es el comienzo de la otra palabra («santi» → «santiago»)."""
+ return any(t == r or (min(len(t), len(r)) >= 4 and (t.startswith(r) or r.startswith(t))) for t in toks for r in ref)
+
+
+def score_identities(job) -> int:
+ graph = db.graph(job.case_id)
+ ents = {e["id"]: e for e in graph["entities"]}
+ adj: dict[str, set[tuple[str, str]]] = defaultdict(set)
+ for ed in graph["edges"]:
+ adj[ed["src"]].add((ed["dst"], ed["label"]))
+ adj[ed["dst"]].add((ed["src"], ed["label"]))
+ accounts = [e for e in ents.values() if e["type"] == "account"]
+ usernames = {e["value"].lower() for e in ents.values() if e["type"] == "username"}
+
+ confirmed = {a["id"] for a in accounts if a["attrs"].get("_verdict") == "confirmada"}
+ discarded = {a["id"] for a in accounts if a["attrs"].get("_verdict") == "descartada"}
+
+ names: dict[str, tuple[str, set[str]]] = {}
+ for a in accounts:
+ for k in NAME_KEYS + ("Nombres en commits",):
+ v = a["attrs"].get(k)
+ if isinstance(v, list):
+ v = v[0] if v else None
+ if isinstance(v, str) and v.strip():
+ toks = _tokens(v) - usernames
+ if toks:
+ names[a["id"]] = (v.strip(), toks)
+ break
+ token_accounts = Counter(t for aid, (_, toks) in names.items() if aid not in discarded for t in toks)
+ ref_tokens = {t for t, n in token_accounts.items() if n >= 2}
+ ref_tokens |= {t for e in ents.values() if e["type"] == "person" and e.get("root") for t in _tokens(e["value"])}
+ confirmed_tokens = {t for aid in confirmed if aid in names for t in names[aid][1]}
+ linked_from = {ed["dst"]: ed["src"] for ed in graph["edges"] if ed["label"] in ("enlaza a", "misma clave SSH")}
+ marks = {"confirmed": confirmed, "discarded": discarded, "confirmed_tokens": confirmed_tokens}
+
+ scores: dict[str, int] = {}
+ reasons: dict[str, list[str]] = {}
+ # Dos pasadas: una cuenta enlazada desde otra hereda la confianza de la que la enlaza.
+ for _ in range(2):
+ for a in accounts:
+ scores[a["id"]], reasons[a["id"]] = _score_account(a, ents, adj, names, ref_tokens, linked_from, scores, marks)
+
+ changed = 0
+ for a in accounts:
+ at = a["attrs"]
+ score, why = scores[a["id"]], reasons[a["id"]]
+ level = "Alta" if score >= 70 else "Media" if score >= 40 else "Baja"
+ if at.get("Confianza") != score or at.get("Señales") != why:
+ ent = db.update_attrs(job.case_id, a["id"], {"Confianza": score, "Nivel de confianza": level, "Señales": why},
+ replace=True)
+ _emit_entity(job, ent)
+ changed += 1
+ return changed
+
+
+def _score_account(a, ents, adj, names, ref_tokens, linked_from, prev_scores, marks) -> tuple[int, list[str]]:
+ at = a["attrs"]
+ if at.get("_verdict") == "confirmada":
+ return 100, ["Confirmada por ti como cuenta de la persona investigada"]
+ if at.get("_verdict") == "descartada":
+ return 0, ["Descartada por ti: no es la persona investigada"]
+ confirmed, discarded = marks["confirmed"], marks["discarded"]
+ verif = str(at.get("Verificación") or "")
+ why: list[str] = []
+ if at.get("Registro"):
+ score = 80
+ why.append("El email investigado está registrado en este servicio")
+ elif verif.startswith("Indicada en Wikidata"):
+ score = 80
+ why.append("Cuenta oficial según Wikidata")
+ elif verif.startswith(("Enlazada desde", "Misma clave")) and a["id"] in linked_from:
+ base = prev_scores.get(linked_from[a["id"]], 35)
+ score = base + 10
+ how = "comparten clave SSH" if verif.startswith("Misma clave") else "el propio dueño puso el enlace"
+ src = linked_from[a["id"]]
+ state = ("la confirmaste" if src in confirmed else "la descartaste" if src in discarded
+ else f"tiene confianza {base}")
+ why.append(f"{verif} ({how}; esa cuenta {state})")
+ elif verif.startswith("Existe"):
+ score = 25
+ why.append("Sólo se comprobó que el nombre de usuario existe")
+ elif verif.startswith("Búsqueda web: perfil con el nombre completo"):
+ score = 35
+ why.append("Encontrada buscando el nombre completo: puede ser un homónimo")
+ elif verif.startswith("Búsqueda web: coincidencia parcial"):
+ score = 20
+ why.append("Sólo coincide parte del nombre: revisa que sea la misma persona")
+ elif verif.startswith("Sólo vista en archivo"):
+ score = 25
+ why.append("Sólo aparece en Internet Archive")
+ else:
+ score = 35
+ why.append("Perfil con datos públicos")
+ if a["id"] in names:
+ v, toks = names[a["id"]]
+ conf_toks = marks["confirmed_tokens"]
+ if conf_toks and _overlap(toks, conf_toks):
+ score += 25
+ why.append(f"El nombre «{v}» coincide con el de una cuenta confirmada")
+ elif conf_toks and len(toks) >= 2 and not _overlap(toks, ref_tokens):
+ score -= 30
+ why.append(f"El nombre «{v}» no coincide con el de las cuentas confirmadas")
+ elif ref_tokens and _overlap(toks, ref_tokens):
+ score += 20
+ why.append(f"El nombre «{v}» coincide con otras cuentas")
+ elif ref_tokens and len(toks) >= 2:
+ score -= 25
+ why.append(f"El nombre «{v}» no coincide con el resto de cuentas")
+ if str(at.get("Página del perfil") or "").startswith("No existe"):
+ score -= 15
+ why.append("La página del perfil responde «no existe»: puede ser un falso positivo")
+ photo_peers = [x for x, lbl in adj[a["id"]] if lbl == PHOTO_REL and x not in discarded]
+ if any(x in confirmed for x in photo_peers):
+ score += 40
+ why.append("Usa la misma foto de perfil que una cuenta confirmada")
+ elif photo_peers:
+ score += 30
+ why.append("Usa la misma foto de perfil que otra cuenta")
+ shared, shared_confirmed = [], []
+ for nb, _ in adj[a["id"]]:
+ ne = ents.get(nb)
+ if not ne or ne["type"] not in ("email", "url", "domain", "location", "phone"):
+ continue
+ others = [x for x, _ in adj[nb]
+ if x != a["id"] and x not in discarded and ents.get(x, {}).get("type") == "account"]
+ label = f"{ENTITY_TYPES[ne['type']]['label'].lower()} {ne['label']}"
+ if any(x in confirmed for x in others):
+ shared_confirmed.append(label)
+ elif others:
+ shared.append(label)
+ if shared_confirmed:
+ score += min(40, 25 * len(shared_confirmed))
+ why.append("Comparte " + ", ".join(shared_confirmed[:3]) + " con una cuenta confirmada")
+ if shared:
+ score += min(20, 10 * len(shared))
+ why.append("Comparte " + ", ".join(shared[:3]) + " con otras cuentas")
+ verdict = str(at.get("IA: veredicto") or "").lower()
+ if verdict:
+ if "otra persona" in verdict:
+ score -= 30
+ elif "misma persona" in verdict:
+ score += 15
+ why.append(f"IA: {at['IA: veredicto']}")
+ # 100 queda reservado a lo que confirma el analista
+ return max(0, min(95, score)), why
+
+
+# ---------------------------------------------------------------- IA
+
+
+AI_SYSTEM = (
+ "Eres un analista OSINT riguroso. Recibes un objetivo y una lista de cuentas encontradas en Internet que podrían "
+ "pertenecerle. Decide para cada cuenta si es la misma persona basándote sólo en los datos dados (nombre, bio, "
+ "ubicación, fechas, enlaces, señales). Un nombre de usuario igual NO basta: es frecuente que otras personas usen el "
+ "mismo alias. Las cuentas con confirmada_por_el_analista son de la persona con seguridad: úsalas como referencia "
+ "para juzgar las demás. Responde exclusivamente con JSON válido, sin texto adicional, con esta forma: "
+ '{"resumen": "perfil breve de la persona en {idioma} con lo que se puede afirmar con seguridad", '
+ '"cuentas": [{"n": 0, "veredicto": "misma persona|probable|dudosa|otra persona", "motivo": "frase corta en {idioma}"}]}'
+ " Los valores de «veredicto» van siempre tal cual, en español."
+)
+
+
+def _ai_system() -> str:
+ return AI_SYSTEM.replace("{idioma}", "inglés" if settings.get("lang") == "en" else "español")
+
+
+def _extract_json(text: str) -> dict:
+ text = re.sub(r"^```(?:json)?|```$", "", text.strip(), flags=re.M)
+ start, end = text.find("{"), text.rfind("}")
+ if start < 0 or end <= start:
+ raise ValueError("La IA no devolvió JSON")
+ return json.loads(text[start:end + 1])
+
+
+async def ai_verify(engine, job) -> None:
+ started = time.time()
+ base = (settings.get("ai_base_url") or "").strip().rstrip("/")
+ model = (settings.get("ai_model") or "").strip()
+ if not base or not model:
+ _record(job, "ai_verify", "skipped", "Configura un proveedor de IA en Ajustes (Ollama local, Groq, Gemini, OpenAI…)", 0, started)
+ return
+ graph = db.graph(job.case_id)
+ roots = [e for e in graph["entities"] if e["root"]]
+ accounts = sorted((e for e in graph["entities"] if e["type"] == "account" and e["attrs"].get("_verdict") != "descartada"),
+ key=lambda e: -(e["attrs"].get("Confianza") or 0))[:60]
+ if not accounts:
+ _record(job, "ai_verify", "empty", "No hay cuentas que verificar", 0, started)
+ return
+
+ def clip(v, n=220):
+ return str(v)[:n] if v not in (None, "", []) else None
+
+ items = []
+ for i, a in enumerate(accounts):
+ at = a["attrs"]
+ item = {
+ "n": i, "plataforma": at.get("Plataforma"), "usuario": at.get("Usuario"),
+ "nombre": clip(at.get("Nombre") or at.get("Nombre visible") or at.get("Nombre real"), 80),
+ "bio": clip(at.get("Bio") or at.get("Resumen")), "creada": clip(at.get("Creada") or at.get("Miembro desde"), 20),
+ "señales": at.get("Señales"), "confianza_reglas": at.get("Confianza"),
+ "fotos_iguales": at.get("Foto coincide con"),
+ "confirmada_por_el_analista": True if at.get("_verdict") == "confirmada" else None,
+ }
+ items.append({k: v for k, v in item.items() if v not in (None, "", [])})
+ target = [{"tipo": ENTITY_TYPES[r["type"]]["label"], "valor": r["value"]} for r in roots]
+ persons = sorted({e["value"] for e in graph["entities"] if e["type"] == "person"})[:10]
+ locations = sorted({e["value"] for e in graph["entities"] if e["type"] == "location"})[:10]
+ user_msg = json.dumps({"objetivo": target, "nombres_vistos": persons, "ubicaciones_vistas": locations, "cuentas": items},
+ ensure_ascii=False)
+ headers = {"Authorization": f"Bearer {settings.key('ai')}"} if settings.key("ai") else {}
+ try:
+ r = await engine.http.post(f"{base}/chat/completions", headers=headers, timeout=180, json={
+ "model": model, "temperature": 0.1,
+ "messages": [{"role": "system", "content": _ai_system()}, {"role": "user", "content": user_msg}],
+ })
+ except httpx.HTTPError as e:
+ _record(job, "ai_verify", "error", f"No se pudo contactar con la IA ({type(e).__name__}). ¿Está en marcha?", 0, started)
+ return
+ if r.status_code != 200:
+ _record(job, "ai_verify", "error", f"La IA respondió {r.status_code}: {r.text[:200]}", 0, started)
+ return
+ try:
+ data = _extract_json(r.json()["choices"][0]["message"]["content"])
+ except (ValueError, KeyError, IndexError, TypeError) as e:
+ _record(job, "ai_verify", "error", f"Respuesta de IA no válida: {e}", 0, started)
+ return
+ n = 0
+ for c in data.get("cuentas") or []:
+ try:
+ a = accounts[int(c.get("n"))]
+ except (TypeError, ValueError, IndexError):
+ continue
+ ent = db.update_attrs(job.case_id, a["id"], {"IA: veredicto": str(c.get("veredicto") or "")[:40],
+ "IA: motivo": str(c.get("motivo") or "")[:300]}, replace=True)
+ _emit_entity(job, ent)
+ n += 1
+ if data.get("resumen") and roots:
+ ent = db.update_attrs(job.case_id, roots[0]["id"], {"IA: resumen": str(data["resumen"])[:2000], "IA: modelo": model},
+ replace=True)
+ _emit_entity(job, ent)
+ _record(job, "ai_verify", "ok", f"{n} cuentas evaluadas por {model}", n, started)
+
+
+# ---------------------------------------------------------------- orquestación
+
+
+async def run(engine, job, use_ai: bool) -> None:
+ await photo_match(engine, job)
+ score_identities(job)
+ if use_ai:
+ await ai_verify(engine, job)
+ score_identities(job)
diff --git a/app/config.py b/app/config.py
new file mode 100644
index 0000000..676304e
--- /dev/null
+++ b/app/config.py
@@ -0,0 +1,115 @@
+import json
+import os
+import sys
+import threading
+from pathlib import Path
+
+if getattr(sys, "frozen", False):
+ # ejecutable de PyInstaller: los ficheros empaquetados están en _MEIPASS y los datos junto al .exe
+ BUNDLE = Path(sys._MEIPASS)
+ ROOT = Path(sys.executable).resolve().parent
+ WEB_DIR = BUNDLE / "web"
+ RESOURCES_DIR = BUNDLE / "app" / "resources"
+else:
+ ROOT = Path(__file__).resolve().parent.parent
+ WEB_DIR = ROOT / "web"
+ RESOURCES_DIR = Path(__file__).resolve().parent / "resources"
+
+
+def _data_dir() -> Path:
+ for d in (ROOT / "data", Path(os.environ.get("LOCALAPPDATA") or Path.home()) / "OsintHunter" / "data"):
+ try:
+ d.mkdir(parents=True, exist_ok=True)
+ probe = d / ".write-test"
+ probe.write_text("ok")
+ probe.unlink()
+ return d
+ except OSError:
+ continue
+ raise RuntimeError("No hay ninguna carpeta con permiso de escritura para guardar los datos")
+
+
+DATA_DIR = _data_dir()
+
+SETTINGS_FILE = DATA_DIR / "settings.json"
+
+# clave -> (nombre visible, dónde conseguirla)
+API_KEYS: dict[str, tuple[str, str]] = {
+ "shodan": ("Shodan", "https://account.shodan.io/"),
+ "virustotal": ("VirusTotal", "https://www.virustotal.com/gui/my-apikey"),
+ "hunter": ("Hunter.io", "https://hunter.io/api-keys"),
+ "abuseipdb": ("AbuseIPDB", "https://www.abuseipdb.com/account/api"),
+ "abusech": ("abuse.ch Auth-Key (URLhaus, ThreatFox, MalwareBazaar)", "https://auth.abuse.ch/"),
+ "urlscan": ("URLScan.io", "https://urlscan.io/user/profile/"),
+ "greynoise": ("GreyNoise Community", "https://viz.greynoise.io/account/api-key"),
+ "github": ("GitHub token (sube el límite de 60 a 5000 peticiones/h)", "https://github.com/settings/tokens"),
+ "numverify": ("Numverify", "https://numverify.com/product"),
+ "hibp": ("Have I Been Pwned (de pago)", "https://haveibeenpwned.com/API/Key"),
+ "serper": ("Serper.dev (Google; 2500 búsquedas gratis, mejora la búsqueda de personas)", "https://serper.dev/api-key"),
+ "brave": ("Brave Search API (alternativa a Serper)", "https://api-dashboard.search.brave.com/app/keys"),
+ "ai": ("Clave del proveedor de IA (no hace falta con Ollama local)", "https://console.groq.com/keys"),
+}
+
+DEFAULT_SETTINGS = {
+ "api_keys": {},
+ "ai_base_url": "",
+ "ai_model": "",
+ "default_region": "",
+ "sherlock_db": True,
+ "include_nsfw": False,
+ "username_timeout": 15,
+ "max_pivot_entities": 25,
+ "lang": "es",
+}
+
+
+class Settings:
+ def __init__(self, path: Path = SETTINGS_FILE):
+ self.path = path
+ self._lock = threading.Lock()
+ self.data = dict(DEFAULT_SETTINGS)
+ if path.exists():
+ try:
+ self.data.update(json.loads(path.read_text(encoding="utf-8")))
+ except (OSError, ValueError):
+ pass
+
+ def get(self, name: str, default=None):
+ return self.data.get(name, default)
+
+ def key(self, name: str) -> str | None:
+ return (self.data.get("api_keys") or {}).get(name) or None
+
+ def update(self, changes: dict) -> None:
+ with self._lock:
+ keys = dict(self.data.get("api_keys") or {})
+ for k, v in (changes.pop("api_keys", None) or {}).items():
+ if k not in API_KEYS:
+ continue
+ v = (v or "").strip()
+ if v:
+ keys[k] = v
+ else:
+ keys.pop(k, None)
+ self.data["api_keys"] = keys
+ for k, v in changes.items():
+ if k in DEFAULT_SETTINGS and k != "api_keys":
+ self.data[k] = v
+ self.path.write_text(json.dumps(self.data, indent=2, ensure_ascii=False), encoding="utf-8")
+
+ def public(self) -> dict:
+ keys = self.data.get("api_keys") or {}
+ out = {k: v for k, v in self.data.items() if k != "api_keys"}
+ out["api_keys"] = {
+ k: {
+ "label": label,
+ "url": url,
+ "set": bool(keys.get(k)),
+ "masked": (keys[k][:3] + "…" + keys[k][-3:]) if len(keys.get(k) or "") > 8 else ("•••" if keys.get(k) else ""),
+ }
+ for k, (label, url) in API_KEYS.items()
+ }
+ return out
+
+
+settings = Settings()
diff --git a/app/db.py b/app/db.py
new file mode 100644
index 0000000..f682750
--- /dev/null
+++ b/app/db.py
@@ -0,0 +1,261 @@
+import json
+import sqlite3
+import threading
+import time
+
+from .config import DATA_DIR
+from .models import display_label, entity_id, normalize
+
+SCHEMA = """
+CREATE TABLE IF NOT EXISTS cases(
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ name TEXT NOT NULL,
+ notes TEXT DEFAULT '',
+ created REAL,
+ updated REAL
+);
+CREATE TABLE IF NOT EXISTS entities(
+ case_id INTEGER,
+ id TEXT,
+ type TEXT,
+ value TEXT,
+ attrs TEXT,
+ root INTEGER DEFAULT 0,
+ pivot INTEGER DEFAULT 1,
+ created REAL,
+ PRIMARY KEY(case_id, id)
+);
+CREATE TABLE IF NOT EXISTS edges(
+ case_id INTEGER,
+ src TEXT,
+ dst TEXT,
+ label TEXT,
+ source TEXT,
+ PRIMARY KEY(case_id, src, dst, label)
+);
+CREATE TABLE IF NOT EXISTS runs(
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ case_id INTEGER,
+ entity_id TEXT,
+ module TEXT,
+ status TEXT,
+ message TEXT,
+ found INTEGER,
+ started REAL,
+ finished REAL
+);
+CREATE INDEX IF NOT EXISTS runs_case ON runs(case_id, entity_id);
+"""
+
+
+def merge_attrs(old: dict, new: dict) -> dict:
+ out = dict(old)
+ for k, v in (new or {}).items():
+ if v is None or v == "" or v == [] or v == {}:
+ continue
+ cur = out.get(k)
+ if isinstance(v, list) and isinstance(cur, list):
+ seen = {json.dumps(x, sort_keys=True, default=str) for x in cur}
+ merged = list(cur)
+ for x in v:
+ s = json.dumps(x, sort_keys=True, default=str)
+ if s not in seen:
+ seen.add(s)
+ merged.append(x)
+ out[k] = merged
+ elif isinstance(v, dict) and isinstance(cur, dict):
+ out[k] = {**cur, **v}
+ else:
+ out[k] = v
+ return out
+
+
+class DB:
+ def __init__(self, path=DATA_DIR / "osint.db"):
+ self.conn = sqlite3.connect(path, check_same_thread=False)
+ self.conn.row_factory = sqlite3.Row
+ self.lock = threading.RLock()
+ with self.lock:
+ self.conn.execute("PRAGMA journal_mode=WAL")
+ self.conn.executescript(SCHEMA)
+ cols = {r[1] for r in self.conn.execute("PRAGMA table_info(cases)")}
+ if "layout" not in cols:
+ self.conn.execute("ALTER TABLE cases ADD COLUMN layout TEXT DEFAULT '{}'")
+ self.conn.commit()
+
+ # ---------- casos ----------
+ def list_cases(self) -> list[dict]:
+ with self.lock:
+ rows = self.conn.execute(
+ "SELECT c.*, (SELECT COUNT(*) FROM entities e WHERE e.case_id = c.id) AS entities "
+ "FROM cases c ORDER BY updated DESC"
+ ).fetchall()
+ return [{k: v for k, v in dict(r).items() if k != "layout"} for r in rows]
+
+ def create_case(self, name: str) -> dict:
+ now = time.time()
+ with self.lock:
+ cur = self.conn.execute(
+ "INSERT INTO cases(name, created, updated) VALUES(?,?,?)", (name.strip() or "Caso sin nombre", now, now)
+ )
+ self.conn.commit()
+ return self.get_case(cur.lastrowid)
+
+ def get_case(self, case_id: int) -> dict | None:
+ with self.lock:
+ row = self.conn.execute("SELECT * FROM cases WHERE id=?", (case_id,)).fetchone()
+ if not row:
+ return None
+ case = dict(row)
+ try:
+ case["layout"] = json.loads(case.get("layout") or "{}")
+ except ValueError:
+ case["layout"] = {}
+ return case
+
+ def update_case(self, case_id: int, name: str | None = None, notes: str | None = None,
+ layout: dict | None = None) -> dict | None:
+ with self.lock:
+ if layout is not None:
+ self.conn.execute("UPDATE cases SET layout=? WHERE id=?", (json.dumps(layout, ensure_ascii=False), case_id))
+ if name is not None:
+ self.conn.execute("UPDATE cases SET name=? WHERE id=?", (name.strip() or "Caso sin nombre", case_id))
+ if notes is not None:
+ self.conn.execute("UPDATE cases SET notes=? WHERE id=?", (notes, case_id))
+ self.touch(case_id)
+ return self.get_case(case_id)
+
+ def touch(self, case_id: int) -> None:
+ with self.lock:
+ self.conn.execute("UPDATE cases SET updated=? WHERE id=?", (time.time(), case_id))
+ self.conn.commit()
+
+ def delete_case(self, case_id: int) -> None:
+ with self.lock:
+ for table in ("entities", "edges", "runs"):
+ self.conn.execute(f"DELETE FROM {table} WHERE case_id=?", (case_id,))
+ self.conn.execute("DELETE FROM cases WHERE id=?", (case_id,))
+ self.conn.commit()
+
+ # ---------- entidades ----------
+ @staticmethod
+ def _entity(row) -> dict:
+ attrs = json.loads(row["attrs"] or "{}")
+ return {
+ "id": row["id"],
+ "type": row["type"],
+ "value": row["value"],
+ "attrs": attrs,
+ "root": bool(row["root"]),
+ "pivot": bool(row["pivot"]),
+ "label": display_label(row["type"], row["value"], attrs),
+ }
+
+ def get_entity(self, case_id: int, eid: str) -> dict | None:
+ with self.lock:
+ row = self.conn.execute("SELECT * FROM entities WHERE case_id=? AND id=?", (case_id, eid)).fetchone()
+ return self._entity(row) if row else None
+
+ def upsert_entity(
+ self, case_id: int, etype: str, value: str, attrs: dict | None = None, root: bool = False, pivot: bool = True
+ ) -> tuple[dict, bool]:
+ value = normalize(etype, value)
+ eid = entity_id(etype, value)
+ with self.lock:
+ row = self.conn.execute("SELECT * FROM entities WHERE case_id=? AND id=?", (case_id, eid)).fetchone()
+ if row:
+ merged = merge_attrs(json.loads(row["attrs"] or "{}"), attrs or {})
+ self.conn.execute(
+ "UPDATE entities SET attrs=?, root=MAX(root, ?), pivot=MAX(pivot, ?) WHERE case_id=? AND id=?",
+ (json.dumps(merged, ensure_ascii=False), int(root), int(pivot), case_id, eid),
+ )
+ created = False
+ else:
+ self.conn.execute(
+ "INSERT INTO entities(case_id, id, type, value, attrs, root, pivot, created) VALUES(?,?,?,?,?,?,?,?)",
+ (case_id, eid, etype, value, json.dumps(attrs or {}, ensure_ascii=False), int(root), int(pivot), time.time()),
+ )
+ created = True
+ self.conn.commit()
+ return self.get_entity(case_id, eid), created
+
+ def update_attrs(self, case_id: int, eid: str, attrs: dict, replace: bool = False) -> dict | None:
+ """Fusiona atributos; con replace=True las claves dadas se sobrescriben (o se borran si valen None)."""
+ with self.lock:
+ row = self.conn.execute("SELECT attrs FROM entities WHERE case_id=? AND id=?", (case_id, eid)).fetchone()
+ if not row:
+ return None
+ current = json.loads(row["attrs"] or "{}")
+ if replace:
+ merged = dict(current)
+ for k, v in attrs.items():
+ if v is None:
+ merged.pop(k, None)
+ else:
+ merged[k] = v
+ else:
+ merged = merge_attrs(current, attrs)
+ self.conn.execute(
+ "UPDATE entities SET attrs=? WHERE case_id=? AND id=?", (json.dumps(merged, ensure_ascii=False), case_id, eid)
+ )
+ self.conn.commit()
+ return self.get_entity(case_id, eid)
+
+ def delete_entity(self, case_id: int, eid: str) -> None:
+ with self.lock:
+ self.conn.execute("DELETE FROM entities WHERE case_id=? AND id=?", (case_id, eid))
+ self.conn.execute("DELETE FROM edges WHERE case_id=? AND (src=? OR dst=?)", (case_id, eid, eid))
+ self.conn.execute("DELETE FROM runs WHERE case_id=? AND entity_id=?", (case_id, eid))
+ self.conn.commit()
+
+ def delete_entities(self, case_id: int, ids: list[str]) -> int:
+ n = 0
+ with self.lock:
+ for eid in ids:
+ n += self.conn.execute("DELETE FROM entities WHERE case_id=? AND id=?", (case_id, eid)).rowcount
+ self.conn.execute("DELETE FROM edges WHERE case_id=? AND (src=? OR dst=?)", (case_id, eid, eid))
+ self.conn.execute("DELETE FROM runs WHERE case_id=? AND entity_id=?", (case_id, eid))
+ self.conn.commit()
+ return n
+
+ # ---------- relaciones y ejecuciones ----------
+ def add_edge(self, case_id: int, src: str, dst: str, label: str, source: str) -> bool:
+ with self.lock:
+ cur = self.conn.execute(
+ "INSERT OR IGNORE INTO edges(case_id, src, dst, label, source) VALUES(?,?,?,?,?)",
+ (case_id, src, dst, label, source),
+ )
+ self.conn.commit()
+ return cur.rowcount > 0
+
+ def delete_edge(self, case_id: int, src: str, dst: str, label: str) -> bool:
+ with self.lock:
+ cur = self.conn.execute("DELETE FROM edges WHERE case_id=? AND src=? AND dst=? AND label=?",
+ (case_id, src, dst, label))
+ self.conn.commit()
+ return cur.rowcount > 0
+
+ def add_run(self, case_id: int, eid: str, module: str, status: str, message: str, found: int, started: float) -> dict:
+ now = time.time()
+ with self.lock:
+ cur = self.conn.execute(
+ "INSERT INTO runs(case_id, entity_id, module, status, message, found, started, finished) VALUES(?,?,?,?,?,?,?,?)",
+ (case_id, eid, module, status, message, found, started, now),
+ )
+ self.conn.commit()
+ row = self.conn.execute("SELECT * FROM runs WHERE id=?", (cur.lastrowid,)).fetchone()
+ return dict(row)
+
+ def graph(self, case_id: int) -> dict:
+ with self.lock:
+ ents = self.conn.execute("SELECT * FROM entities WHERE case_id=? ORDER BY created", (case_id,)).fetchall()
+ edges = self.conn.execute("SELECT src, dst, label, source FROM edges WHERE case_id=?", (case_id,)).fetchall()
+ runs = self.conn.execute("SELECT * FROM runs WHERE case_id=? ORDER BY id", (case_id,)).fetchall()
+ return {
+ "entities": [self._entity(r) for r in ents],
+ "edges": [dict(r) for r in edges],
+ "runs": [dict(r) for r in runs],
+ }
+
+
+db = DB()
diff --git a/app/engine.py b/app/engine.py
new file mode 100644
index 0000000..51e7f86
--- /dev/null
+++ b/app/engine.py
@@ -0,0 +1,315 @@
+import asyncio
+import logging
+import time
+import traceback
+import uuid
+
+import httpx
+
+from .config import API_KEYS, settings
+from .db import db
+from .models import AUTO_PIVOT_TYPES
+from .modules import REGISTRY, Module, Skip
+
+log = logging.getLogger("osint")
+
+USER_AGENT = (
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36"
+)
+
+
+def make_client() -> httpx.AsyncClient:
+ return httpx.AsyncClient(
+ timeout=httpx.Timeout(20.0, connect=10.0),
+ follow_redirects=True,
+ headers={"User-Agent": USER_AGENT, "Accept-Language": "es-ES,es;q=0.9,en;q=0.8"},
+ limits=httpx.Limits(max_connections=80, max_keepalive_connections=40),
+ )
+
+
+class Job:
+ def __init__(self, case_id: int):
+ self.id = uuid.uuid4().hex[:12]
+ self.case_id = case_id
+ self.events: list[dict] = []
+ self.created: list[str] = []
+ self.done = False
+ self._new = asyncio.Event()
+ self.task: asyncio.Task | None = None
+
+ def emit(self, event: dict) -> None:
+ self.events.append(event)
+ self._new.set()
+
+ def finish(self) -> None:
+ self.done = True
+ self._new.set()
+
+ async def stream(self):
+ i = 0
+ while True:
+ if i < len(self.events):
+ ev = self.events[i]
+ i += 1
+ yield ev
+ continue
+ if self.done:
+ return
+ self._new.clear()
+ try:
+ await asyncio.wait_for(self._new.wait(), 15)
+ except asyncio.TimeoutError:
+ yield None # keep-alive
+
+
+class Context:
+ """Lo que ve un módulo mientras se ejecuta sobre una entidad."""
+
+ def __init__(self, engine: "Engine", job: Job, entity: dict, module: Module):
+ self.engine = engine
+ self.job = job
+ self.case_id = job.case_id
+ self.entity = entity
+ self.value: str = entity["value"]
+ self.module = module
+ self.http = engine.http
+ self.settings = settings
+ self.found = 0
+ self.enriched = False
+ self.message = ""
+ self.new_pivots: list[str] = []
+
+ def key(self, name: str) -> str | None:
+ return settings.key(name)
+
+ def require_key(self, name: str) -> str:
+ k = settings.key(name)
+ if not k:
+ label, url = API_KEYS[name]
+ raise Skip(f"Requiere clave de {label}: añádela en Ajustes ({url})")
+ return k
+
+ def add(
+ self,
+ etype: str,
+ value: str,
+ attrs: dict | None = None,
+ rel: str = "relacionado",
+ parent: str | None = None,
+ pivot: bool = True,
+ ) -> str | None:
+ if not value or not str(value).strip():
+ return None
+ attrs = dict(attrs or {})
+ attrs["_fuentes"] = [self.module.title]
+ ent, created = db.upsert_entity(self.case_id, etype, str(value), attrs, pivot=pivot)
+ self.job.emit({"type": "entity", "entity": ent, "created": created})
+ if created:
+ self.job.created.append(ent["id"])
+ src = parent or self.entity["id"]
+ if src != ent["id"] and db.add_edge(self.case_id, src, ent["id"], rel, self.module.name):
+ self.job.emit({"type": "edge", "edge": {"src": src, "dst": ent["id"], "label": rel, "source": self.module.name}})
+ self.found += 1
+ if pivot and etype in AUTO_PIVOT_TYPES:
+ self.new_pivots.append(ent["id"])
+ return ent["id"]
+
+ def enrich(self, attrs: dict, eid: str | None = None, replace: bool = False) -> None:
+ """Con replace=True las claves dadas se sobrescriben tal cual (las que valen None se borran)."""
+ if replace:
+ ent = db.update_attrs(self.case_id, eid or self.entity["id"], attrs, replace=True)
+ if ent:
+ self.job.emit({"type": "entity", "entity": ent, "created": False})
+ return
+ attrs = {k: v for k, v in attrs.items() if v not in (None, "", [], {})}
+ if not attrs:
+ return
+ attrs["_fuentes"] = [self.module.title]
+ ent = db.update_attrs(self.case_id, eid or self.entity["id"], attrs)
+ if ent:
+ self.job.emit({"type": "entity", "entity": ent, "created": False})
+ self.enriched = True
+
+ async def get_json(self, url: str, **kw):
+ """GET que devuelve (status, json o None) sin lanzar excepción por códigos HTTP."""
+ r = await self.http.get(url, **kw)
+ try:
+ data = r.json()
+ except ValueError:
+ data = None
+ return r.status_code, data
+
+
+class Engine:
+ def __init__(self):
+ self.http: httpx.AsyncClient | None = None
+ self.jobs: dict[str, Job] = {}
+
+ async def start(self) -> None:
+ self.http = make_client()
+
+ async def stop(self) -> None:
+ if self.http:
+ await self.http.aclose()
+
+ def modules_for(self, entity: dict) -> list[Module]:
+ return [m for m in REGISTRY.values() if m.applies(entity)]
+
+ def _new_job(self, case_id: int) -> Job:
+ job = Job(case_id)
+ self.jobs[job.id] = job
+ for jid in [j for j, jb in self.jobs.items() if jb.done and jb is not job][:-20]:
+ self.jobs.pop(jid, None)
+ return job
+
+ def start_scan(self, case_id: int, entity_id: str, modules: list[str] | None, depth: int) -> Job:
+ job = self._new_job(case_id)
+ job.task = asyncio.create_task(self._scan(job, entity_id, modules, max(0, min(depth, 3))))
+ return job
+
+ def start_batch(self, case_id: int, module: str) -> Job:
+ job = self._new_job(case_id)
+ job.task = asyncio.create_task(self._batch(job, REGISTRY[module]))
+ return job
+
+ async def _batch(self, job: Job, m: Module) -> None:
+ """Pasa un módulo por todas las entidades del caso a las que aplica y que aún no lo tienen; luego reanaliza."""
+ from . import analysis
+
+ try:
+ graph = db.graph(job.case_id)
+ done = {r["entity_id"] for r in graph["runs"] if r["module"] == m.name and r["status"] in ("ok", "empty", "skipped")}
+ ents = [e for e in graph["entities"] if m.applies(e) and e["id"] not in done]
+ sem = asyncio.Semaphore(8)
+
+ async def one(e):
+ async with sem:
+ await self._run_module(job, e, m)
+
+ await asyncio.gather(*(one(e) for e in ents))
+ await analysis.run(self, job, use_ai=False)
+ job.emit({"type": "done", "scanned": len(ents)})
+ except Exception as e: # noqa: BLE001
+ log.error("batch failed: %s", traceback.format_exc())
+ job.emit({"type": "error", "message": str(e)})
+ finally:
+ db.touch(job.case_id)
+ job.finish()
+
+ def start_analysis(self, case_id: int, use_ai: bool) -> Job:
+ job = self._new_job(case_id)
+ job.task = asyncio.create_task(self._analysis_job(job, use_ai))
+ return job
+
+ async def _analysis_job(self, job: Job, use_ai: bool) -> None:
+ from . import analysis
+
+ try:
+ await analysis.run(self, job, use_ai=use_ai)
+ job.emit({"type": "done", "scanned": 0, "analysis": True})
+ except Exception as e: # noqa: BLE001
+ log.error("analysis failed: %s", traceback.format_exc())
+ job.emit({"type": "error", "message": str(e)})
+ finally:
+ db.touch(job.case_id)
+ job.finish()
+
+ async def _enrich_new(self, job: Job) -> None:
+ """Ejecuta los enriquecedores automáticos sobre las entidades creadas en este trabajo."""
+ auto = [m for m in REGISTRY.values() if m.auto]
+ done: set[str] = set()
+ for _ in range(2):
+ pending = [eid for eid in job.created if eid not in done]
+ if not pending:
+ return
+ tasks = []
+ for eid in pending:
+ done.add(eid)
+ ent = db.get_entity(job.case_id, eid)
+ if not ent:
+ continue
+ tasks += [self._run_module(job, ent, m) for m in auto if m.applies(ent)]
+ if tasks:
+ await asyncio.gather(*tasks)
+
+ async def _scan(self, job: Job, entity_id: str, modules: list[str] | None, depth: int) -> None:
+ try:
+ limit = int(settings.get("max_pivot_entities", 25))
+ queue: list[tuple[str, int]] = [(entity_id, 0)]
+ seen = {entity_id}
+ while queue:
+ # cada nivel se procesa en paralelo
+ level = queue
+ queue = []
+ results = await asyncio.gather(
+ *(self._scan_entity(job, eid, modules if d == 0 else None, rerun=d == 0) for eid, d in level)
+ )
+ for (eid, d), new in zip(level, results):
+ if d >= depth:
+ continue
+ for n in new:
+ if n not in seen and len(seen) < limit:
+ seen.add(n)
+ queue.append((n, d + 1))
+ await self._enrich_new(job)
+ from . import analysis
+
+ await analysis.run(self, job, use_ai=False)
+ job.emit({"type": "done", "scanned": len(seen)})
+ except Exception as e: # noqa: BLE001
+ log.error("scan failed: %s", traceback.format_exc())
+ job.emit({"type": "error", "message": str(e)})
+ finally:
+ db.touch(job.case_id)
+ job.finish()
+
+ async def _scan_entity(self, job: Job, eid: str, modules: list[str] | None, rerun: bool) -> list[str]:
+ ent = db.get_entity(job.case_id, eid)
+ if not ent:
+ return []
+ mods = self.modules_for(ent)
+ if modules is not None:
+ mods = [m for m in mods if m.name in modules]
+ else:
+ mods = [m for m in mods if not m.deep]
+ if not rerun:
+ done = {
+ r["module"]
+ for r in db.graph(job.case_id)["runs"]
+ if r["entity_id"] == eid and r["status"] in ("ok", "empty")
+ }
+ mods = [m for m in mods if m.name not in done]
+ if not mods:
+ return []
+ job.emit({"type": "scan_entity", "entity_id": eid, "modules": [m.name for m in mods]})
+ ctxs = await asyncio.gather(*(self._run_module(job, ent, m) for m in mods))
+ new: list[str] = []
+ for c in ctxs:
+ new.extend(x for x in c.new_pivots if x not in new and x != eid)
+ return new
+
+ async def _run_module(self, job: Job, ent: dict, m: Module) -> Context:
+ ctx = Context(self, job, ent, m)
+ job.emit({"type": "run_start", "entity_id": ent["id"], "module": m.name})
+ started = time.time()
+ try:
+ for k in m.keys:
+ ctx.require_key(k)
+ await asyncio.wait_for(m.run(ctx), m.timeout)
+ status = "ok" if (ctx.found or ctx.enriched) else "empty"
+ msg = ctx.message or (f"{ctx.found} hallazgos" if ctx.found else ("Datos añadidos" if ctx.enriched else "Sin resultados"))
+ except Skip as e:
+ status, msg = "skipped", str(e)
+ except asyncio.TimeoutError:
+ status, msg = "error", f"Tiempo agotado ({int(m.timeout)} s)" + (f" · {ctx.found} hallazgos parciales" if ctx.found else "")
+ except httpx.HTTPError as e:
+ status, msg = "error", f"Error de red: {type(e).__name__}"
+ except Exception as e: # noqa: BLE001
+ log.error("module %s failed: %s", m.name, traceback.format_exc())
+ status, msg = "error", f"{type(e).__name__}: {e}"
+ run = db.add_run(job.case_id, ent["id"], m.name, status, msg, ctx.found, started)
+ job.emit({"type": "run", "run": run})
+ return ctx
+
+
+engine = Engine()
diff --git a/app/exif.py b/app/exif.py
new file mode 100644
index 0000000..9a2c6a9
--- /dev/null
+++ b/app/exif.py
@@ -0,0 +1,76 @@
+import hashlib
+import io
+
+from PIL import ExifTags, Image
+
+WANTED = {
+ "Make": "Marca cámara", "Model": "Modelo cámara", "LensModel": "Objetivo", "Software": "Software",
+ "DateTime": "Fecha modificación", "DateTimeOriginal": "Fecha captura", "Artist": "Autor",
+ "Copyright": "Copyright", "ImageDescription": "Descripción", "BodySerialNumber": "Nº serie cámara",
+ "CameraOwnerName": "Propietario cámara", "XPAuthor": "Autor (Windows)", "XPComment": "Comentario (Windows)",
+ "HostComputer": "Equipo",
+}
+
+
+def _ratio(x) -> float:
+ try:
+ return float(x)
+ except (TypeError, ValueError, ZeroDivisionError):
+ return 0.0
+
+
+def _dms(vals, ref) -> float | None:
+ try:
+ d, m, s = (_ratio(v) for v in vals)
+ except (TypeError, ValueError):
+ return None
+ out = d + m / 60 + s / 3600
+ return -out if ref in ("S", "W") else out
+
+
+def _clean(v):
+ if isinstance(v, bytes):
+ try:
+ return v.decode("utf-16-le" if b"\x00" in v else "utf-8", "ignore").strip("\x00 ").strip()
+ except UnicodeDecodeError:
+ return None
+ return str(v).strip("\x00 ").strip() if v is not None else None
+
+
+def analyze_image(data: bytes, filename: str) -> dict:
+ """Devuelve metadatos, hashes y coordenadas GPS (si existen) de una imagen."""
+ out: dict = {
+ "Archivo": filename,
+ "Tamaño (bytes)": len(data),
+ "SHA256": hashlib.sha256(data).hexdigest(),
+ "MD5": hashlib.md5(data).hexdigest(),
+ }
+ img = Image.open(io.BytesIO(data))
+ out["Formato"] = img.format
+ out["Dimensiones"] = f"{img.width}×{img.height}"
+ exif = img.getexif()
+ tags = {ExifTags.TAGS.get(k, str(k)): v for k, v in exif.items()}
+ try:
+ tags.update({ExifTags.TAGS.get(k, str(k)): v for k, v in exif.get_ifd(0x8769).items()})
+ except (KeyError, AttributeError):
+ pass
+ for k, label in WANTED.items():
+ v = _clean(tags.get(k))
+ if v:
+ out[label] = v
+ try:
+ gps = {ExifTags.GPSTAGS.get(k, str(k)): v for k, v in exif.get_ifd(0x8825).items()}
+ except (KeyError, AttributeError):
+ gps = {}
+ if gps.get("GPSLatitude") and gps.get("GPSLongitude"):
+ lat = _dms(gps["GPSLatitude"], gps.get("GPSLatitudeRef"))
+ lon = _dms(gps["GPSLongitude"], gps.get("GPSLongitudeRef"))
+ if lat is not None and lon is not None and (lat or lon):
+ out["_lat"], out["_lon"] = round(lat, 6), round(lon, 6)
+ if gps.get("GPSAltitude") is not None:
+ out["Altitud (m)"] = round(_ratio(gps["GPSAltitude"]), 1)
+ if "xmp" in img.info or b"<x:xmpmeta" in data[:200_000]:
+ out["XMP"] = "Contiene metadatos XMP (posible historial de edición)"
+ if len(out) <= 8 and "_lat" not in out:
+ out["Aviso"] = "Sin metadatos EXIF: probablemente se subió a una red social que los elimina"
+ return out
diff --git a/app/main.py b/app/main.py
new file mode 100644
index 0000000..f4c6ba6
--- /dev/null
+++ b/app/main.py
@@ -0,0 +1,366 @@
+import json
+import time
+from contextlib import asynccontextmanager
+
+from fastapi import FastAPI, File, HTTPException, UploadFile
+from fastapi.responses import Response, StreamingResponse
+from fastapi.staticfiles import StaticFiles
+from pydantic import BaseModel
+
+from .analysis import score_identities
+from .config import WEB_DIR, settings
+from .db import db
+from .engine import engine
+from .exif import analyze_image
+from .models import ENTITY_TYPES, detect_type
+from .modules import REGISTRY
+from .modules.username import PROFILE_URLS as MANUAL_PROFILE_URLS
+
+
+@asynccontextmanager
+async def lifespan(_app: FastAPI):
+ await engine.start()
+ yield
+ await engine.stop()
+
+
+app = FastAPI(title="OsintHunter", lifespan=lifespan)
+
+
+class CaseIn(BaseModel):
+ name: str = ""
+ notes: str | None = None
+ layout: dict | None = None
+
+
+class EntityIn(BaseModel):
+ value: str
+ type: str | None = None
+ parent: str | None = None
+ rel: str | None = None
+ attrs: dict | None = None
+
+
+class EdgeIn(BaseModel):
+ src: str
+ dst: str
+ label: str = "relacionado"
+
+
+class IdsIn(BaseModel):
+ ids: list[str]
+
+
+class VerdictIn(BaseModel):
+ verdict: str | None = None
+
+
+class ManualCheckIn(BaseModel):
+ site: str
+ exists: bool
+
+
+class _Collector:
+ """Recoge los eventos de un cálculo síncrono para devolverlos en la respuesta HTTP."""
+
+ def __init__(self, case_id: int):
+ self.case_id = case_id
+ self.entities: dict[str, dict] = {}
+
+ def emit(self, ev: dict) -> None:
+ if ev.get("type") == "entity" and ev.get("entity"):
+ self.entities[ev["entity"]["id"]] = ev["entity"]
+
+
+class ScanIn(BaseModel):
+ entity_id: str
+ modules: list[str] | None = None
+ depth: int = 0
+
+
+class DetectIn(BaseModel):
+ value: str
+
+
+class AnalyzeIn(BaseModel):
+ ai: bool = False
+
+
+def _case(case_id: int) -> dict:
+ c = db.get_case(case_id)
+ if not c:
+ raise HTTPException(404, "Caso no encontrado")
+ return c
+
+
[email protected]("/api/meta")
+def meta():
+ return {
+ "entity_types": ENTITY_TYPES,
+ "modules": [
+ {**m.meta(), "ready": all(settings.key(k) for k in m.keys)}
+ for m in REGISTRY.values()
+ ] + [
+ {"name": "photo_match", "title": "Comparación de fotos de perfil", "description": "", "inputs": [],
+ "keys": [], "optional_keys": [], "sources": [], "ready": True},
+ {"name": "ai_verify", "title": "Verificación con IA", "description": "", "inputs": [],
+ "keys": [], "optional_keys": [], "sources": [], "ready": True},
+ ],
+ "ai_ready": bool(settings.get("ai_base_url") and settings.get("ai_model")),
+ }
+
+
[email protected]("/api/detect")
+def detect(body: DetectIn):
+ return {"type": detect_type(body.value)}
+
+
[email protected]("/api/settings")
+def get_settings():
+ return settings.public()
+
+
[email protected]("/api/settings")
+def put_settings(body: dict):
+ settings.update(dict(body))
+ return settings.public()
+
+
[email protected]("/api/cases")
+def list_cases():
+ return db.list_cases()
+
+
[email protected]("/api/cases")
+def create_case(body: CaseIn):
+ return db.create_case(body.name)
+
+
[email protected]("/api/cases/{case_id}")
+def get_case(case_id: int):
+ return {"case": _case(case_id), **db.graph(case_id)}
+
+
[email protected]("/api/cases/{case_id}")
+def update_case(case_id: int, body: CaseIn):
+ _case(case_id)
+ return db.update_case(case_id, name=body.name or None, notes=body.notes, layout=body.layout)
+
+
[email protected]("/api/cases/{case_id}")
+def delete_case(case_id: int):
+ db.delete_case(case_id)
+ return {"ok": True}
+
+
[email protected]("/api/cases/{case_id}/entities")
+def add_entity(case_id: int, body: EntityIn):
+ _case(case_id)
+ value = body.value.strip()
+ if not value:
+ raise HTTPException(400, "Valor vacío")
+ etype = body.type or detect_type(value)
+ if etype not in ENTITY_TYPES:
+ raise HTTPException(400, "Tipo desconocido")
+ parent = db.get_entity(case_id, body.parent) if body.parent else None
+ ent, _ = db.upsert_entity(case_id, etype, value, body.attrs or {}, root=not parent)
+ if parent:
+ db.add_edge(case_id, parent["id"], ent["id"], body.rel or "relacionado", "manual")
+ db.touch(case_id)
+ return ent
+
+
[email protected]("/api/cases/{case_id}/entities/delete")
+def delete_entities(case_id: int, body: IdsIn):
+ _case(case_id)
+ n = db.delete_entities(case_id, body.ids[:20000])
+ db.touch(case_id)
+ return {"deleted": n}
+
+
[email protected]("/api/cases/{case_id}/edges")
+def add_manual_edge(case_id: int, body: EdgeIn):
+ _case(case_id)
+ label = " ".join(body.label.split())[:60] or "relacionado"
+ if body.src == body.dst or not db.get_entity(case_id, body.src) or not db.get_entity(case_id, body.dst):
+ raise HTTPException(400, "Entidades no válidas")
+ db.add_edge(case_id, body.src, body.dst, label, "manual")
+ db.touch(case_id)
+ return {"src": body.src, "dst": body.dst, "label": label, "source": "manual"}
+
+
[email protected]("/api/cases/{case_id}/edges/delete")
+def delete_manual_edge(case_id: int, body: EdgeIn):
+ _case(case_id)
+ return {"ok": db.delete_edge(case_id, body.src, body.dst, body.label)}
+
+
[email protected]("/api/cases/{case_id}/verdict/{eid:path}")
+def set_verdict(case_id: int, eid: str, body: VerdictIn):
+ _case(case_id)
+ if body.verdict not in (None, "confirmada", "descartada"):
+ raise HTTPException(400, "Veredicto no válido")
+ ent = db.update_attrs(case_id, eid, {"_verdict": body.verdict}, replace=True)
+ if not ent:
+ raise HTTPException(404, "Entidad no encontrada")
+ job = _Collector(case_id)
+ score_identities(job)
+ job.entities.setdefault(ent["id"], db.get_entity(case_id, ent["id"]))
+ db.touch(case_id)
+ return {"entities": list(job.entities.values())}
+
+
[email protected]("/api/cases/{case_id}/manual-check/{eid:path}")
+def manual_check(case_id: int, eid: str, body: ManualCheckIn):
+ """Resultado de un sitio bloqueado que el usuario comprobó en su navegador."""
+ _case(case_id)
+ ent = db.get_entity(case_id, eid)
+ if not ent or ent["type"] != "username":
+ raise HTTPException(404, "Entidad no encontrada")
+ a = ent["attrs"]
+ if body.site == "*":
+ out = db.update_attrs(case_id, eid, {"_bloq_sitios": {}, "_bloq_perfiles": []}, replace=True)
+ return {"entities": [out], "edge": None}
+ sites = dict(a.get("_bloq_sitios") or {})
+ url = sites.pop(body.site, None)
+ platforms = [p for p in a.get("_bloq_perfiles") or [] if p != body.site]
+ if url is None and body.site in (a.get("_bloq_perfiles") or []):
+ url = MANUAL_PROFILE_URLS.get(body.site, "").format(ent["value"]) or None
+ out = [db.update_attrs(case_id, eid, {"_bloq_sitios": sites, "_bloq_perfiles": platforms}, replace=True)]
+ edge = None
+ if body.exists and url:
+ acc, _ = db.upsert_entity(case_id, "account", url, {
+ "Plataforma": body.site, "Usuario": ent["value"], "Verificación": "Comprobado a mano en el navegador",
+ "_links": [["Abrir perfil", url]], "_fuentes": ["Comprobación manual"]}, pivot=False)
+ db.add_edge(case_id, eid, acc["id"], "cuenta", "manual")
+ edge = {"src": eid, "dst": acc["id"], "label": "cuenta", "source": "manual"}
+ out.append(acc)
+ db.touch(case_id)
+ return {"entities": out, "edge": edge}
+
+
[email protected]("/api/cases/{case_id}/entities/{eid:path}")
+def delete_entity(case_id: int, eid: str):
+ db.delete_entity(case_id, eid)
+ return {"ok": True}
+
+
[email protected]("/api/cases/{case_id}/scan")
+async def scan(case_id: int, body: ScanIn):
+ _case(case_id)
+ if not db.get_entity(case_id, body.entity_id):
+ raise HTTPException(404, "Entidad no encontrada")
+ job = engine.start_scan(case_id, body.entity_id, body.modules, body.depth)
+ return {"job_id": job.id}
+
+
[email protected]("/api/cases/{case_id}/read-accounts")
+async def read_accounts(case_id: int):
+ _case(case_id)
+ return {"job_id": engine.start_batch(case_id, "account_page").id}
+
+
[email protected]("/api/cases/{case_id}/analyze")
+async def analyze(case_id: int, body: AnalyzeIn):
+ _case(case_id)
+ job = engine.start_analysis(case_id, body.ai)
+ return {"job_id": job.id}
+
+
[email protected]("/api/jobs/{job_id}/events")
+async def job_events(job_id: str):
+ job = engine.jobs.get(job_id)
+ if not job:
+ raise HTTPException(404, "Trabajo no encontrado")
+
+ async def gen():
+ async for ev in job.stream():
+ if ev is None:
+ yield ": ping\n\n"
+ else:
+ yield f"data: {json.dumps(ev, ensure_ascii=False, default=str)}\n\n"
+
+ return StreamingResponse(gen(), media_type="text/event-stream", headers={"Cache-Control": "no-cache"})
+
+
[email protected]("/api/cases/{case_id}/image")
+async def upload_image(case_id: int, file: UploadFile = File(...)):
+ _case(case_id)
+ data = await file.read()
+ if len(data) > 40 * 1024 * 1024:
+ raise HTTPException(413, "Imagen demasiado grande (máx. 40 MB)")
+ try:
+ info = analyze_image(data, file.filename or "imagen")
+ except Exception as e: # noqa: BLE001
+ raise HTTPException(400, f"No se pudo leer la imagen: {e}") from e
+ info["_fuentes"] = ["Metadatos EXIF"]
+ img, _ = db.upsert_entity(case_id, "image", info["SHA256"], info, root=True)
+ h, _ = db.upsert_entity(case_id, "hash", info["SHA256"], {"_fuentes": ["Metadatos EXIF"]})
+ db.add_edge(case_id, img["id"], h["id"], "sha256", "exif")
+ if "_lat" in info:
+ lat, lon = info["_lat"], info["_lon"]
+ loc, _ = db.upsert_entity(case_id, "location", f"{lat}, {lon}", {
+ "_lat": lat, "_lon": lon, "Precisión": "GPS de la foto",
+ "_links": [["Google Maps", f"https://www.google.com/maps?q={lat},{lon}"],
+ ["OpenStreetMap", f"https://www.openstreetmap.org/?mlat={lat}&mlon={lon}#map=17/{lat}/{lon}"]],
+ "_fuentes": ["Metadatos EXIF"],
+ }, pivot=False)
+ db.add_edge(case_id, img["id"], loc["id"], "tomada en", "exif")
+ for key, rel in (("Autor", "autor"), ("Propietario cámara", "propietario"), ("Autor (Windows)", "autor")):
+ if info.get(key) and len(info[key]) > 2:
+ p, _ = db.upsert_entity(case_id, "person", info[key], {"_fuentes": ["Metadatos EXIF"]}, pivot=False)
+ db.add_edge(case_id, img["id"], p["id"], rel, "exif")
+ db.touch(case_id)
+ return {"entity": img}
+
+
[email protected]("/api/cases/{case_id}/export")
+def export_case(case_id: int):
+ case = _case(case_id)
+ payload = {"exported": time.strftime("%Y-%m-%d %H:%M:%S"), "case": case, **db.graph(case_id)}
+ name = "".join(ch if ch.isalnum() else "_" for ch in case["name"])[:40] or "caso"
+ return Response(
+ json.dumps(payload, ensure_ascii=False, indent=2),
+ media_type="application/json",
+ headers={"Content-Disposition": f'attachment; filename="osint_{name}.json"'},
+ )
+
+
[email protected]("/api/import")
+async def import_case(file: UploadFile = File(...)):
+ try:
+ data = json.loads(await file.read())
+ src_case = data["case"]
+ except (ValueError, KeyError) as e:
+ raise HTTPException(400, "Archivo no válido") from e
+ case = db.create_case(src_case.get("name", "Importado") + " (importado)")
+ for e in data.get("entities", []):
+ db.upsert_entity(case["id"], e["type"], e["value"], e.get("attrs") or {}, root=e.get("root", False),
+ pivot=e.get("pivot", True))
+ for ed in data.get("edges", []):
+ db.add_edge(case["id"], ed["src"], ed["dst"], ed["label"], ed.get("source", "import"))
+ if src_case.get("notes"):
+ db.update_case(case["id"], notes=src_case["notes"])
+ if isinstance(src_case.get("layout"), dict):
+ db.update_case(case["id"], layout=src_case["layout"])
+ return case
+
+
+def index():
+ html = (WEB_DIR / "index.html").read_text(encoding="utf-8")
+ for asset in ("app.js", "style.css", "i18n.js", "i18n-en.js"):
+ version = int((WEB_DIR / asset).stat().st_mtime)
+ html = html.replace(f'"{asset}"', f'"{asset}?v={version}"')
+ return Response(html, media_type="text/html", headers={"Cache-Control": "no-cache"})
+
+
+async def revalidate_static(request, call_next):
+ response = await call_next(request)
+ if not request.url.path.startswith(("/api/", "/vendor/")):
+ response.headers.setdefault("Cache-Control", "no-cache")
+ return response
+
+
+app.mount("/", StaticFiles(directory=WEB_DIR), name="web")
diff --git a/app/models.py b/app/models.py
new file mode 100644
index 0000000..6bc42a7
--- /dev/null
+++ b/app/models.py
@@ -0,0 +1,135 @@
+import ipaddress
+import re
+
+# tipo -> (nombre visible, color, forma en el grafo, ¿se puede investigar directamente?)
+ENTITY_TYPES: dict[str, dict] = {
+ "username": {"label": "Usuario", "color": "#4fc3f7", "shape": "ellipse", "input": True},
+ "email": {"label": "Email", "color": "#ffb74d", "shape": "round-rectangle", "input": True},
+ "phone": {"label": "Teléfono", "color": "#81c784", "shape": "round-rectangle", "input": True},
+ "person": {"label": "Persona", "color": "#f06292", "shape": "ellipse", "input": True},
+ "domain": {"label": "Dominio", "color": "#ba68c8", "shape": "hexagon", "input": True},
+ "ip": {"label": "IP", "color": "#e57373", "shape": "diamond", "input": True},
+ "url": {"label": "URL", "color": "#90a4ae", "shape": "round-tag", "input": True},
+ "hash": {"label": "Hash", "color": "#a1887f", "shape": "rectangle", "input": True},
+ "crypto": {"label": "Cripto", "color": "#ffd54f", "shape": "octagon", "input": True},
+ "rut": {"label": "RUT", "color": "#ff8a65", "shape": "round-pentagon", "input": True},
+ "plate": {"label": "Patente", "color": "#dce775", "shape": "cut-rectangle", "input": True},
+ "account": {"label": "Cuenta", "color": "#4db6ac", "shape": "round-rectangle", "input": False},
+ "location": {"label": "Ubicación", "color": "#aed581", "shape": "triangle", "input": False},
+ "organization": {"label": "Organización", "color": "#7986cb", "shape": "barrel", "input": False},
+ "asn": {"label": "ASN", "color": "#9575cd", "shape": "barrel", "input": False},
+ "breach": {"label": "Filtración", "color": "#ef5350", "shape": "star", "input": False},
+ "image": {"label": "Imagen", "color": "#4dd0e1", "shape": "rectangle", "input": False},
+}
+
+# Tipos que el pivotado automático (profundidad > 0) vuelve a investigar.
+AUTO_PIVOT_TYPES = {"username", "email", "phone", "domain", "ip", "crypto", "rut"}
+
+_RUT = re.compile(r"^\d{1,2}(?:\.\d{3}){2}-?[\dkK]$|^\d{7,8}-[\dkK]$")
+_PLATE_SEP = re.compile(r"^[A-Za-z]{2}[\s.\-·•][A-Za-z]{2}[\s.\-·•]?\d{2}$|^[A-Za-z]{2,4}[\s.\-·•]\d{2,4}$")
+
+_EMAIL = re.compile(r"^[^@\s]+@[^@\s]+\.[a-z]{2,}$", re.I)
+_DOMAIN = re.compile(r"^(?=.{4,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$", re.I)
+_PHONE = re.compile(r"^\+?[\d\s().\-]{7,22}$")
+_HEX = re.compile(r"^[a-f0-9]+$", re.I)
+
+CRYPTO_PATTERNS = {
+ "btc": re.compile(r"^(?:bc1[ac-hj-np-z02-9]{25,62}|[13][a-km-zA-HJ-NP-Z1-9]{25,34})$"),
+ "eth": re.compile(r"^0x[a-fA-F0-9]{40}$"),
+ "ltc": re.compile(r"^(?:ltc1[ac-hj-np-z02-9]{25,62}|[LM][a-km-zA-HJ-NP-Z1-9]{26,33})$"),
+ "doge": re.compile(r"^D[5-9A-HJ-NP-U][1-9A-HJ-NP-Za-km-z]{32}$"),
+ "trx": re.compile(r"^T[1-9A-HJ-NP-Za-km-z]{33}$"),
+}
+CRYPTO_NAMES = {"btc": "Bitcoin", "eth": "Ethereum / EVM", "ltc": "Litecoin", "doge": "Dogecoin", "trx": "Tron"}
+
+
+def crypto_chain(value: str) -> str | None:
+ for chain, rx in CRYPTO_PATTERNS.items():
+ if rx.match(value):
+ return chain
+ return None
+
+
+def detect_type(value: str) -> str:
+ v = value.strip()
+ if re.match(r"^https?://", v, re.I):
+ return "url"
+ if _EMAIL.match(v):
+ return "email"
+ try:
+ ipaddress.ip_address(v)
+ return "ip"
+ except ValueError:
+ pass
+ if crypto_chain(v):
+ return "crypto"
+ if _HEX.match(v) and len(v) in (32, 40, 56, 64, 96, 128):
+ return "hash"
+ from .modules.chile import plate_kind
+
+ if _RUT.match(v):
+ return "rut"
+ # sin separadores sólo en mayúsculas, para no confundir con usuarios tipo «abcd12»
+ if plate_kind(v) and (_PLATE_SEP.match(v) or (v.isupper() and re.fullmatch(r"[A-Z]{4}\d{2}|[A-Z]{2}\d{4}", v))):
+ return "plate"
+ digits = re.sub(r"\D", "", v)
+ if _PHONE.match(v) and 7 <= len(digits) <= 15 and (v.startswith("+") or not re.search(r"[a-z]", v, re.I)):
+ return "phone"
+ if _DOMAIN.match(v):
+ return "domain"
+ if " " in v:
+ return "person"
+ return "username"
+
+
+def normalize(etype: str, value: str) -> str:
+ v = (value or "").strip()
+ if etype in ("email", "domain", "username", "hash"):
+ v = v.lower()
+ if etype == "domain":
+ v = v.rstrip(".")
+ elif etype == "username":
+ v = v.lstrip("@")
+ elif etype == "ip":
+ try:
+ v = str(ipaddress.ip_address(v))
+ except ValueError:
+ pass
+ elif etype == "phone":
+ v = re.sub(r"[^\d+]", "", v)
+ elif etype == "person":
+ v = " ".join(v.split()).title()
+ elif etype == "account":
+ v = v.rstrip("/")
+ elif etype == "rut":
+ from .modules.chile import rut_fmt, rut_parts
+
+ p = rut_parts(v)
+ v = rut_fmt(*p) if p else v.upper()
+ elif etype == "plate":
+ from .modules.chile import plate_clean
+
+ v = plate_clean(v)
+ return v
+
+
+def entity_id(etype: str, value: str) -> str:
+ key = value.lower() if etype in ("account", "url", "location", "organization", "person") else value
+ return f"{etype}:{key}"
+
+
+def display_label(etype: str, value: str, attrs: dict) -> str:
+ if etype == "account":
+ platform = attrs.get("Plataforma") or ""
+ user = attrs.get("Usuario") or ""
+ if platform:
+ return f"{platform}: {user}" if user else platform
+ if etype == "asn" and attrs.get("Organización"):
+ return f"{value} {attrs['Organización']}"
+ if etype == "image" and attrs.get("Archivo"):
+ return attrs["Archivo"]
+ if etype == "plate":
+ from .modules.chile import plate_display
+
+ return plate_display(value)
+ return value
diff --git a/app/modules/__init__.py b/app/modules/__init__.py
new file mode 100644
index 0000000..8460606
--- /dev/null
+++ b/app/modules/__init__.py
@@ -0,0 +1,4 @@
+from .base import REGISTRY, Module, Skip, register
+from . import username, email, phone, domain, ip, web, misc, enrich, deep, documents, people, websearch, chile, chile_data # noqa: F401,E402 (registran módulos)
+
+__all__ = ["REGISTRY", "Module", "Skip", "register"]
diff --git a/app/modules/base.py b/app/modules/base.py
new file mode 100644
index 0000000..168bc7c
--- /dev/null
+++ b/app/modules/base.py
@@ -0,0 +1,54 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from ..engine import Context
+
+
+class Skip(Exception):
+ """El módulo no se puede ejecutar (falta una clave, la entrada no aplica, etc.)."""
+
+
+class Module:
+ name: str = ""
+ title: str = ""
+ description: str = ""
+ inputs: tuple[str, ...] = ()
+ # claves obligatorias; si falta alguna el módulo se marca como omitido
+ keys: tuple[str, ...] = ()
+ # claves que mejoran el resultado pero no son necesarias
+ optional_keys: tuple[str, ...] = ()
+ sources: tuple[str, ...] = ()
+ timeout: float = 60
+ # Enriquecedor: se ejecuta solo sobre cada entidad nueva que encaje, aunque no se pivote sobre ella.
+ auto: bool = False
+ # Búsqueda a fondo: nunca entra en la investigación normal ni en el pivotado; sólo se lanza a petición.
+ deep: bool = False
+
+ def applies(self, entity: dict) -> bool:
+ return entity["type"] in self.inputs
+
+ async def run(self, ctx: "Context") -> None:
+ raise NotImplementedError
+
+ def meta(self) -> dict:
+ return {
+ "name": self.name,
+ "title": self.title,
+ "description": self.description,
+ "inputs": list(self.inputs),
+ "keys": list(self.keys),
+ "optional_keys": list(self.optional_keys),
+ "sources": list(self.sources),
+ "deep": self.deep,
+ }
+
+
+REGISTRY: dict[str, Module] = {}
+
+
+def register(cls):
+ inst = cls()
+ REGISTRY[inst.name] = inst
+ return cls
diff --git a/app/modules/chile.py b/app/modules/chile.py
new file mode 100644
index 0000000..ad08b11
--- /dev/null
+++ b/app/modules/chile.py
@@ -0,0 +1,225 @@
+"""Fuentes y tipos de dato chilenos: RUT, patentes de vehículos y WHOIS de NIC Chile (.cl)."""
+import html
+import re
+
+from .base import Module, register
+
+# ---------------------------------------------------------------- RUT
+
+
+def rut_dv(num: int) -> str:
+ s, m = 0, 2
+ for d in reversed(str(num)):
+ s += int(d) * m
+ m = 2 if m == 7 else m + 1
+ r = 11 - s % 11
+ return {11: "0", 10: "K"}.get(r, str(r))
+
+
+def rut_parts(value: str) -> tuple[int, str] | None:
+ v = re.sub(r"[.\s]", "", value or "").upper()
+ m = re.fullmatch(r"(\d{6,9})-?([\dK])", v)
+ return (int(m.group(1)), m.group(2)) if m else None
+
+
+def rut_fmt(num: int, dv: str) -> str:
+ return f"{num:,}".replace(",", ".") + f"-{dv}"
+
+
+def rut_valid(value: str) -> bool:
+ p = rut_parts(value)
+ return bool(p) and rut_dv(p[0]) == p[1]
+
+
+# con guion obligatorio: sin él hay demasiados números que pasan por RUT
+RUT_TEXT_RE = re.compile(r"(?<![\d.\-])(\d{1,2}\.\d{3}\.\d{3}|\d{7,8})\s?-\s?([\dkK])(?![\w])")
+
+
+def find_ruts(text: str, limit: int = 40) -> list[tuple[str, str]]:
+ """[(rut formateado, contexto)] de los RUT válidos que aparecen en un texto."""
+ out: dict[str, str] = {}
+ for m in RUT_TEXT_RE.finditer(text or ""):
+ num = int(m.group(1).replace(".", ""))
+ dv = m.group(2).upper()
+ if num < 1_000_000 or rut_dv(num) != dv:
+ continue
+ rut = rut_fmt(num, dv)
+ if rut not in out:
+ ctx = " ".join(text[max(0, m.start() - 70):m.end() + 40].split())
+ out[rut] = ctx
+ if len(out) >= limit:
+ break
+ return list(out.items())
+
+
+def rut_kind(num: int) -> str:
+ if 60_000_000 <= num < 62_000_000:
+ return "Persona jurídica: probablemente organismo o servicio público"
+ if num >= 50_000_000:
+ return "Persona jurídica (empresa, sociedad u organización)"
+ return "Persona natural"
+
+
+@register
+class RutInfo(Module):
+ name = "rut_info"
+ title = "RUT chileno"
+ description = ("Valida el dígito verificador, indica si es persona natural o jurídica y prepara las consultas "
+ "en SII, Registro de Empresas, Poder Judicial, Mercado Público y otras fuentes oficiales")
+ inputs = ("rut",)
+ sources = ("Local",)
+ auto = True
+
+ async def run(self, ctx):
+ p = rut_parts(ctx.value)
+ if not p:
+ ctx.message = "No tiene formato de RUT"
+ return
+ num, dv = p
+ good = rut_dv(num)
+ if good != dv:
+ ctx.enrich({"Dígito verificador": f"Inválido: con {num} el dígito correcto es {good}"})
+ ctx.message = f"Dígito verificador inválido (debería ser {good})"
+ return
+ plain = f"{num}-{dv}"
+ split = [["RUT sin dígito", str(num)], ["Dígito", dv]]
+ links = [
+ ["SII · situación tributaria de terceros (nombre o razón social, actividades)", "https://zeus.sii.cl/cvc/stc/stc.html", split],
+ ["Registro de Empresas y Sociedades", "https://www.registrodeempresasysociedades.cl/", [["RUT", plain]]],
+ ["Poder Judicial · consulta unificada de causas", "https://oficinajudicialvirtual.pjud.cl/indexN.php", split],
+ ["Mercado Público (proveedores del Estado)", "https://www.mercadopublico.cl/Home", [["RUT", rut_fmt(num, dv)]]],
+ ]
+ if num >= 50_000_000:
+ links.append(["CMF · entidades fiscalizadas", "https://www.cmfchile.cl/portal/principal/613/w3-channel.html",
+ [["RUT sin dígito", str(num)]]])
+ ctx.enrich({
+ "Dígito verificador": "Válido",
+ "Tipo": rut_kind(num),
+ "Formas de escribirlo": [rut_fmt(num, dv), plain, f"{num}{dv}", str(num)],
+ "_links": links,
+ })
+ ctx.found += 1
+
+
+# ---------------------------------------------------------------- patentes
+
+PLATE_LETTERS = "BCDFGHJKLPRSTVWXYZ"
+PLATE_NEW = re.compile(rf"^[{PLATE_LETTERS}]{{4}}\d{{2}}$")
+PLATE_OLD = re.compile(r"^[A-Z]{2}\d{4}$")
+PLATE_MOTO_NEW = re.compile(rf"^[{PLATE_LETTERS}]{{3}}\d{{2}}$")
+PLATE_MOTO_OLD = re.compile(r"^[A-Z]{2}\d{3}$")
+
+
+def plate_clean(value: str) -> str:
+ return re.sub(r"[\s.\-·•]", "", value or "").upper()
+
+
+def plate_kind(value: str) -> str | None:
+ p = plate_clean(value)
+ if PLATE_NEW.match(p):
+ return "Vehículo, formato nuevo (desde 2007): 4 letras y 2 números"
+ if PLATE_OLD.match(p):
+ return "Vehículo, formato antiguo (antes de 2007): 2 letras y 4 números"
+ if PLATE_MOTO_NEW.match(p):
+ return "Motocicleta, formato nuevo: 3 letras y 2 números"
+ if PLATE_MOTO_OLD.match(p):
+ return "Motocicleta, formato antiguo: 2 letras y 3 números"
+ return None
+
+
+def plate_display(value: str) -> str:
+ p = plate_clean(value)
+ if PLATE_NEW.match(p):
+ return f"{p[:2]}·{p[2:4]}·{p[4:]}"
+ if PLATE_OLD.match(p):
+ return f"{p[:2]}·{p[2:]}"
+ return f"{p[:-2]}·{p[-2:]}" if len(p) > 3 else p
+
+
+@register
+class PlateInfo(Module):
+ name = "plate_info"
+ title = "Patente de vehículo (Chile)"
+ description = ("Reconoce el formato de la placa y prepara las consultas oficiales (encargo por robo, multas "
+ "impagas, certificado de anotaciones) y búsquedas en avisos y redes")
+ inputs = ("plate",)
+ sources = ("Local",)
+ auto = True
+
+ async def run(self, ctx):
+ kind = plate_kind(ctx.value)
+ if not kind:
+ ctx.message = "No coincide con ningún formato de patente chilena"
+ return
+ fill = [["Patente", plate_clean(ctx.value)]]
+ ctx.enrich({
+ "Formato": kind,
+ "Escrita": plate_display(ctx.value),
+ "_links": [
+ ["Autoseguro · ¿tiene encargo por robo?", "https://www.autoseguro.gob.cl/", fill],
+ ["Registro Civil · multas de tránsito impagas", "https://consultamultas.srcei.cl/ConsultaMultas/", fill],
+ ["Registro Civil · certificado de anotaciones vigentes (dueño; de pago)", "https://www.registrocivil.cl/principal/servicios-en-linea", fill],
+ ],
+ })
+ ctx.found += 1
+
+
+# ---------------------------------------------------------------- NIC Chile
+
+NIC_FIELD = re.compile(r"<b>\s*([^<:]+?)\s*:\s*</b>\s*</div>\s*<div[^>]*>(.*?)</div>", re.S | re.I)
+
+
+def _nic_text(s: str) -> str:
+ return " ".join(html.unescape(re.sub(r"<[^>]+>", " ", s)).split())
+
+
+def clean_holder(s: str) -> str:
+ """«Servicio Nacional del Consumidor (SERNAC) (SERVICIO NACIONAL DEL CONSUMIDOR)» -> sin la repetición en mayúsculas."""
+ m = re.match(r"^(.*\S)\s*\(([^()]*)\)$", s)
+ if m and m.group(2).isupper() and m.group(2).lower() in m.group(1).lower():
+ return m.group(1).strip()
+ return s
+
+
+@register
+class NicChile(Module):
+ name = "nic_chile"
+ title = "WHOIS .cl (NIC Chile)"
+ description = "Titular del dominio .cl (persona u organización), agente registrador, fechas y servidores DNS"
+ inputs = ("domain",)
+ sources = ("nic.cl",)
+
+ def applies(self, entity: dict) -> bool:
+ return entity["type"] == "domain" and entity["value"].lower().endswith(".cl")
+
+ async def run(self, ctx):
+ from .documents import classify_author
+
+ d = ctx.value.lower()
+ r = await ctx.http.get("https://www.nic.cl/registry/Whois.do", params={"d": d}, timeout=25)
+ if r.status_code != 200:
+ raise RuntimeError(f"NIC Chile respondió {r.status_code}")
+ fields: dict[str, list[str]] = {}
+ for label, val in NIC_FIELD.findall(r.text):
+ fields.setdefault(_nic_text(label), []).append(_nic_text(val))
+ if not fields.get("Titular"):
+ ctx.message = "El dominio no está inscrito en NIC Chile" if "no existe" in r.text.lower() or "disponible" in r.text.lower() else "NIC Chile no devolvió titular"
+ return
+ holder = clean_holder(fields["Titular"][0])
+ first = lambda k: (fields.get(k) or [None])[0] # noqa: E731
+ ctx.enrich({
+ "Titular (NIC Chile)": holder,
+ "Agente registrador": first("Agente Registrador"),
+ "Alta (NIC Chile)": first("Fecha de creación"),
+ "Última modificación (NIC Chile)": first("Fecha de última modificación"),
+ "Caduca (NIC Chile)": first("Fecha de expiración"),
+ "Servidores DNS (NIC Chile)": fields.get("Servidor de Nombre"),
+ "_links": [["Ficha en NIC Chile", f"https://www.nic.cl/registry/Whois.do?d={d}"],
+ ["Otros dominios .cl que contengan el nombre (marca «Contenga»)", "https://www.nic.cl/registry/BuscarDominio.do",
+ [["Nombre", d.removesuffix(".cl").split(".")[-1]]]]],
+ })
+ kind = classify_author(holder)
+ etype = "person" if kind and kind[0] == "person" else "organization"
+ ctx.add(etype, kind[1] if kind and kind[0] == "person" else holder,
+ {"Rol": "Titular de dominio .cl"}, rel="titular (NIC Chile)", pivot=False)
+ ctx.found += 1
diff --git a/app/modules/chile_data.py b/app/modules/chile_data.py
new file mode 100644
index 0000000..5c34562
--- /dev/null
+++ b/app/modules/chile_data.py
@@ -0,0 +1,470 @@
+"""Fuentes públicas chilenas con datos descargables: InfoProbidad, Registro de Empresas y Sociedades, tesis."""
+
+import asyncio
+import csv
+import io
+import json
+import re
+import sqlite3
+import time
+from collections import defaultdict
+
+import httpx
+
+from ..config import DATA_DIR
+from .base import Module, Skip, register
+from .chile import rut_fmt, rut_parts
+from .people import name_match, name_variants, same_name, tokens
+
+UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0 Safari/537.36"}
+RESERVED = {"", "RESERVADO", "NO APLICA", "NINGUNO", "NINGUNA", "0"}
+
+
+def _ok(v) -> bool:
+ return isinstance(v, str) and v.strip().upper() not in RESERVED
+
+
+def _name(d: dict | None) -> str | None:
+ return (d or {}).get("nombre") if isinstance(d, dict) else None
+
+
+def _date(s: str | None) -> str | None:
+ m = re.match(r"(\d{4})[/-](\d{2})[/-](\d{2})", s or "")
+ return f"{m.group(3)}-{m.group(2)}-{m.group(1)}" if m and m.group(1) != "0001" else None
+
+
+def _title(s: str) -> str:
+ small = {"de", "del", "y", "e"}
+ return " ".join(w.lower() if w.lower() in small and i else w.capitalize() for i, w in enumerate((s or "").split()))
+
+
+# ---------------------------------------------------------------- InfoProbidad
+
+IP_LIST = "https://www.infoprobidad.cl/Home/Listado"
+IP_JSON = "https://www.infoprobidad.cl/Declaracion/descargarDeclaracionJSon"
+IP_PAGE = "https://www.infoprobidad.cl/Declaracion/Declaracion?ID={}"
+_ip_lock = asyncio.Lock()
+_ip_cache: tuple[float, list] | None = None
+
+
+async def infoprobidad_index(http) -> list[dict]:
+ """Listado completo de declaraciones (≈120.000); se descarga una vez por semana."""
+ global _ip_cache
+ async with _ip_lock:
+ if _ip_cache and time.time() - _ip_cache[0] < 3600:
+ return _ip_cache[1]
+ path = DATA_DIR / "infoprobidad.json"
+ if not path.exists() or time.time() - path.stat().st_mtime > 7 * 86400:
+ try:
+ r = await http.get(IP_LIST, headers=UA, timeout=180)
+ start = r.text.find("[", r.text.find("var datos ="))
+ rows, _ = json.JSONDecoder().raw_decode(r.text, start)
+ keep = ("IdDeclaracion", "FechaDeclaracion", "TipoDeclaracion", "Nombres", "ApellidoPaterno",
+ "ApellidoMaterno", "ServicioEntidad", "Cargo")
+ path.write_text(json.dumps([{k: d.get(k) for k in keep} for d in rows], ensure_ascii=False),
+ encoding="utf-8")
+ except Exception:
+ if not path.exists():
+ raise
+ rows = json.loads(path.read_text(encoding="utf-8"))
+ for d in rows:
+ d["_full"] = " ".join(x for x in (d.get("Nombres"), d.get("ApellidoPaterno"), d.get("ApellidoMaterno")) if x)
+ d["_tok"] = tokens(d["_full"])
+ _ip_cache = (time.time(), rows)
+ return rows
+
+
+def _razones(obj, out: list, path: str = ""):
+ """Recorre la declaración y junta toda entidad con razón social (empresas, empleadores, sociedades)."""
+ if isinstance(obj, dict):
+ razon = next((v for k, v in obj.items() if "Razon_Social" in k and _ok(v)), None)
+ if razon:
+ rut = obj.get("RUT") or obj.get("Rut") or obj.get("RUT_Sociedad")
+ rubro = _name(obj.get("Rubro")) or _name(obj.get("Titulo_Documento")) or _name(obj.get("Tipo_Obligacion_Deuda"))
+ out.append((razon.strip(), rut if _ok(rut) else None, rubro, path))
+ for k, v in obj.items():
+ _razones(v, out, k if not path else path)
+ elif isinstance(obj, list):
+ for x in obj:
+ _razones(x, out, path)
+
+
+SECTION_REL = {
+ "Actividades_Profesionales_A_La_Fecha": "trabaja en (InfoProbidad)",
+ "Actividades_Profesionales_Ultimos_12_Meses": "trabajó en (InfoProbidad)",
+ "Actividades_Profesionales_Conyuge": "cónyuge trabaja en (InfoProbidad)",
+ "Derechos_Acciones_Chile": "socio o accionista (InfoProbidad)",
+ "Acciones_Derechos_Chile": "socio o accionista (InfoProbidad)",
+ "Instrumentos_Valor_TransableChile": "inversiones en (InfoProbidad)",
+ "Pasivos": "deuda con (InfoProbidad)",
+ "Patrimonio_Conyuge": "cónyuge relacionado con (InfoProbidad)",
+}
+
+
+@register
+class InfoProbidad(Module):
+ name = "infoprobidad"
+ title = "InfoProbidad (declaraciones de patrimonio, Chile)"
+ description = ("Funcionarios, autoridades y candidatos chilenos: cargo, institución, cónyuge, empresas, "
+ "propiedades, vehículos y deudas según su declaración de patrimonio e intereses")
+ inputs = ("person",)
+ sources = ("infoprobidad.cl",)
+ timeout = 240
+
+ async def run(self, ctx):
+ name = ctx.value.strip()
+ qt = tokens(name)
+ if len(qt) < 2:
+ raise Skip("Hace falta nombre y apellido")
+ rows = await infoprobidad_index(ctx.http)
+ exact, compatible, similar = defaultdict(list), defaultdict(list), defaultdict(list)
+ variants = name_variants(name)
+ for d in rows:
+ dt = d["_tok"]
+ if dt == qt or (len(qt) >= 3 and set(qt) <= set(dt) and dt[0] == qt[0]):
+ exact[d["_full"]].append(d)
+ elif same_name(name, d["_full"]):
+ compatible[d["_full"]].append(d)
+ elif name_match(d["_full"], name, variants):
+ similar[d["_full"]].append(d)
+ if not exact and len(compatible) == 1:
+ exact = compatible
+ else:
+ similar.update(compatible)
+ if not exact and not similar:
+ ctx.message = f"No aparece entre las {len(rows):,} declaraciones".replace(",", ".")
+ return
+ if similar:
+ items = sorted(similar.items(), key=lambda kv: -len(kv[1]))[:15]
+ ctx.enrich({"InfoProbidad: nombres parecidos": [
+ f"{_title(n)} · {_title(ds[-1]['Cargo'])} · {_title(ds[-1]['ServicioEntidad'])} ({ds[-1]['FechaDeclaracion'][:4]})"
+ for n, ds in items]})
+ if len(exact) > 3:
+ ctx.enrich({"InfoProbidad: homónimos": [f"{_title(n)} · {_title(ds[-1]['Cargo'])}" for n, ds in exact.items()]})
+ ctx.message = f"{len(exact)} declarantes con ese nombre: agrega el segundo apellido para distinguirlos"
+ return
+ for full, decls in exact.items():
+ decls.sort(key=lambda d: d["FechaDeclaracion"] or "")
+ await self._declarant(ctx, full, decls, own=len(exact) == 1)
+ ctx.message = (f"{sum(len(v) for v in exact.values())} declaraciones de {len(exact)} persona(s)"
+ + (f" · {len(similar)} con nombre parecido" if similar else ""))
+
+ async def _declarant(self, ctx, full, decls, own):
+ last = decls[-1]
+ cargos = list(dict.fromkeys(f"{_title(d['Cargo'])} — {_title(d['ServicioEntidad'])} ({(d['FechaDeclaracion'] or '')[:4]})"
+ for d in reversed(decls)))
+ pid = ctx.entity["id"] if own else ctx.add("person", _title(full), {"Fuente": "InfoProbidad"},
+ rel="mismo nombre (InfoProbidad)", pivot=False)
+ if not pid:
+ return
+ r = await ctx.http.post(IP_JSON, data={"ID": last["IdDeclaracion"]}, headers=UA, timeout=60)
+ try:
+ dec = r.json()
+ except ValueError:
+ dec = {}
+ who = dec.get("Datos_del_Declarante") or {}
+ ent = dec.get("Datos_Entidad_Por_La_Que_Declara") or {}
+ vehicles = [" ".join(x for x in (_name(v.get("Tipo_Vehiculo")), _name(v.get("Marca")), v.get("Modelo"),
+ v.get("Annio_Fabricacion")) if _ok(x))
+ for v in dec.get("Vehiculos_Motorizados") or []]
+ pas = dec.get("Pasivos") or {}
+ ctx.enrich({
+ "Cargo (InfoProbidad)": f"{_title(last['Cargo'])} — {_title(last['ServicioEntidad'])}",
+ "Historial de cargos": cargos[:20],
+ "Profesión": _title(_name(who.get("Profesion_Oficio")) or ""),
+ "Estado civil": _title(_name(who.get("Estado_Civil")) or ""),
+ "Renta o grado": ent.get("Grado_Renta_Mensual") if _ok(ent.get("Grado_Renta_Mensual")) else None,
+ "Asumió el cargo": _date(ent.get("Fecha_Asuncion_Cargo")),
+ "Comuna declarada": _title(", ".join(x for x in (_name(who.get("Comuna")), _name(who.get("Region"))) if x)),
+ "Vehículos declarados": [_title(v) for v in vehicles if v],
+ "Deudas declaradas": f"${int(pas['Monto_Global_Pesos']):,}".replace(",", ".") if str(pas.get("Monto_Global_Pesos", "")).isdigit() and int(pas["Monto_Global_Pesos"]) else None,
+ "_links": [["Declaración en InfoProbidad", IP_PAGE.format(last["IdDeclaracion"])]]
+ + [[f"Declaración {d['FechaDeclaracion'][:10]}", IP_PAGE.format(d["IdDeclaracion"])] for d in reversed(decls[:-1][-5:])],
+ }, eid=pid)
+ ctx.found += 1
+ if rut_parts(who.get("RUN") or ""):
+ ctx.add("rut", who["RUN"], {"Fuente": "InfoProbidad"}, rel="RUT (InfoProbidad)", parent=pid, pivot=False)
+ org = ctx.add("organization", _title(last["ServicioEntidad"]), {"Tipo": "Institución pública"},
+ rel=f"{_title(last['Cargo']).lower()} (InfoProbidad)", parent=pid, pivot=False)
+ spouse = dec.get("Datos_del_Conyuge") or {}
+ sname = " ".join(x for x in (spouse.get("nombre"), spouse.get("Apellido_Paterno"), spouse.get("Apellido_Materno")) if _ok(x))
+ sid = None
+ if len(sname.split()) >= 2:
+ sid = ctx.add("person", _title(sname), {"Fuente": "InfoProbidad"}, rel="cónyuge (InfoProbidad)", parent=pid, pivot=False)
+ for prop in (dec.get("Bienes_Inmuebles_Situados_En_Chile") or [])[:15]:
+ addr = ", ".join(x for x in (prop.get("Direccion"), _name(prop.get("Comuna")), _name(prop.get("Region"))) if _ok(x))
+ if addr and _ok(prop.get("Direccion")):
+ ctx.add("location", _title(addr) + ", Chile", {"Rol de avalúo": prop.get("Rol_Avaluo"),
+ "Inscripción": prop.get("Annio")},
+ rel="propiedad declarada (InfoProbidad)", parent=pid, pivot=False)
+ found: list = []
+ _razones(dec, found)
+ seen = set()
+ for razon, rut, rubro, section in found:
+ key = razon.lower()
+ if key in seen or (org and key == _title(last["ServicioEntidad"]).lower()):
+ continue
+ seen.add(key)
+ # trabajo independiente: la «razón social» es la propia persona o su cónyuge, y el RUT es el personal
+ rt = set(tokens(razon))
+ owner = (pid if len(rt) >= 2 and rt <= set(tokens(full))
+ else sid if sid and len(rt) >= 2 and rt <= set(tokens(sname)) else None)
+ if owner:
+ if rut and rut_parts(rut):
+ ctx.add("rut", rut, {"Fuente": "InfoProbidad"}, rel="RUT (InfoProbidad)", parent=owner, pivot=False)
+ continue
+ attrs = {"RUT": rut_fmt(*rut_parts(rut)) if rut and rut_parts(rut) else None, "Rubro": _title(rubro or "")}
+ oid = ctx.add("organization", razon, attrs, rel=SECTION_REL.get(section, "relacionado (InfoProbidad)"),
+ parent=pid, pivot=False)
+ if oid and rut and rut_parts(rut):
+ ctx.add("rut", rut, {}, rel="RUT", parent=oid, pivot=False)
+
+
+# ---------------------------------------------------------------- Registro de Empresas y Sociedades
+
+RES_DATASET = "https://datos.gob.cl/api/3/action/package_show?id=363edd60-4919-4ff1-b85f-f8e14d61285a"
+_res_lock = asyncio.Lock()
+
+
+def _res_db() -> sqlite3.Connection:
+ con = sqlite3.connect(DATA_DIR / "empresas_cl.db")
+ con.executescript("""
+ CREATE TABLE IF NOT EXISTS archivo (n INTEGER PRIMARY KEY, id TEXT UNIQUE, modificado TEXT);
+ CREATE TABLE IF NOT EXISTS actuacion (rut INTEGER, dv TEXT, razon TEXT, tipo TEXT, actuacion TEXT,
+ fecha TEXT, comuna TEXT, capital INTEGER, archivo INTEGER);
+ CREATE INDEX IF NOT EXISTS ix_rut ON actuacion(rut);
+ CREATE VIRTUAL TABLE IF NOT EXISTS razon_fts USING fts5(razon, content='actuacion', content_rowid='rowid',
+ tokenize='unicode61 remove_diacritics 2');
+ """)
+ return con
+
+
+def _search(con, query: str, limit: int) -> list[tuple[int, str]]:
+ return con.execute("SELECT a.rut, a.razon FROM razon_fts JOIN actuacion a ON a.rowid = razon_fts.rowid "
+ "WHERE razon_fts MATCH ? LIMIT ?", (query, limit)).fetchall()
+
+
+async def empresas_ready(http) -> tuple[sqlite3.Connection, list[str]]:
+ """Descarga (una vez) los archivos anuales del Registro de Empresas y Sociedades a una base local."""
+ async with _res_lock:
+ con = _res_db()
+ have = dict(con.execute("SELECT id, modificado FROM archivo"))
+ checked = have.get("_check")
+ if checked and checked >= time.strftime("%Y-%m-%d", time.localtime(time.time() - 7 * 86400)):
+ return con, []
+ try:
+ r = await http.get(RES_DATASET, headers=UA, timeout=60)
+ resources = [x for x in r.json()["result"]["resources"] if (x.get("format") or "").lower() == "csv"]
+ except (httpx.HTTPError, ValueError, KeyError):
+ if have:
+ return con, []
+ raise
+ changed = False
+ missing: list[str] = []
+ for res in resources:
+ if have.get(res["id"]) == res.get("last_modified"):
+ continue
+ changed = True
+ con.execute("INSERT OR IGNORE INTO archivo (id) VALUES (?)", (res["id"],))
+ n = con.execute("SELECT n FROM archivo WHERE id = ?", (res["id"],)).fetchone()[0]
+ raw = None
+ for attempt in range(4):
+ try:
+ async with http.stream("GET", res["url"], headers=UA, timeout=600, follow_redirects=True) as resp:
+ if resp.status_code == 200:
+ raw = b"".join([c async for c in resp.aiter_bytes()])
+ except httpx.HTTPError:
+ pass
+ if raw:
+ break
+ await asyncio.sleep(3 * (attempt + 1))
+ if not raw:
+ missing.append(res.get("name") or res["id"])
+ continue
+ text = raw.decode("utf-8-sig", errors="replace")
+ rows = []
+ for row in csv.DictReader(io.StringIO(text), delimiter=";"):
+ p = rut_parts(row.get("RUT") or "")
+ if not p:
+ continue
+ cap = re.sub(r"\D", "", row.get("Capital") or "")
+ rows.append((p[0], p[1], (row.get("Razon Social") or "").strip(), row.get("Codigo de sociedad"),
+ row.get("Tipo de actuacion"), row.get("Fecha de registro (ultima firma)") or row.get("Fecha de actuacion (1era firma)"),
+ (row.get("Comuna Social") or row.get("Comuna Tributaria") or "").strip(), int(cap) if cap else None, n))
+ if not rows:
+ missing.append(res.get("name") or res["id"])
+ continue
+ con.execute("DELETE FROM actuacion WHERE archivo = ?", (n,))
+ con.executemany("INSERT INTO actuacion VALUES (?,?,?,?,?,?,?,?,?)", rows)
+ con.execute("UPDATE archivo SET modificado = ? WHERE n = ?", (res.get("last_modified"), n))
+ con.commit()
+ if changed:
+ con.execute("INSERT INTO razon_fts (razon_fts) VALUES ('rebuild')")
+ if not missing:
+ con.execute("INSERT OR REPLACE INTO archivo (n, id, modificado) VALUES "
+ "((SELECT n FROM archivo WHERE id = '_check'), '_check', ?)", (time.strftime("%Y-%m-%d"),))
+ con.commit()
+ return con, missing
+
+
+def _company(con, num: int) -> dict | None:
+ acts = con.execute("SELECT dv, razon, tipo, actuacion, fecha, comuna, capital FROM actuacion WHERE rut = ? "
+ "ORDER BY substr(fecha,7,4)||substr(fecha,4,2)||substr(fecha,1,2)", (num,)).fetchall()
+ if not acts:
+ return None
+ first, last = acts[0], acts[-1]
+ return {
+ "rut": rut_fmt(num, first[0]),
+ "razon": last[1],
+ "attrs": {
+ "RUT": rut_fmt(num, first[0]),
+ "Tipo de sociedad": last[2],
+ "Constituida": next((a[4] for a in acts if "CONSTITU" in (a[3] or "").upper()), first[4]),
+ "Comuna": _title(last[5]),
+ "Capital": f"${last[6]:,}".replace(",", ".") if last[6] else None,
+ "Disuelta": next((a[4] for a in acts if "DISOLU" in (a[3] or "").upper()), None),
+ "Historial (Registro de Empresas)": [f"{a[4]} · {_title(a[3] or '')}" for a in acts][-20:] if len(acts) > 1 else None,
+ "Nombres anteriores": list(dict.fromkeys(a[1] for a in acts if a[1] != last[1])) or None,
+ "_links": [["Registro de Empresas y Sociedades", "https://www.registrodeempresasysociedades.cl/",
+ [["RUT", f"{num}-{first[0]}"]]]],
+ },
+ }
+
+
+@register
+class EmpresasChile(Module):
+ name = "empresas_cl"
+ title = "Empresas chilenas (Registro de Empresas y Sociedades)"
+ description = ("Razón social, tipo, fecha de constitución, comuna, capital e historial de una empresa por su RUT; "
+ "para personas, sociedades con su nombre completo o sus dos apellidos (empresas creadas desde 2013)")
+ inputs = ("rut", "person", "organization")
+ sources = ("datos.gob.cl",)
+ timeout = 900
+
+ async def run(self, ctx):
+ first_time = not (DATA_DIR / "empresas_cl.db").exists()
+ con, missing = await empresas_ready(ctx.http)
+ try:
+ t = ctx.entity["type"]
+ if t == "rut":
+ p = rut_parts(ctx.value)
+ if not p or p[0] < 50_000_000:
+ raise Skip("Sólo aplica a RUT de empresas (50 millones o más)")
+ c = _company(con, p[0])
+ if not c:
+ ctx.message = "No figura entre las empresas creadas por el Registro (desde 2013)"
+ return
+ ctx.add("organization", c["razon"], c["attrs"], rel="razón social", pivot=False)
+ ctx.found += 1
+ elif t == "organization":
+ q = " ".join(f'"{w}"' for w in tokens(ctx.value) if len(w) > 1)
+ if not q:
+ return
+ for num, _ in _search(con, q, 5):
+ c = _company(con, num)
+ if c and tokens(c["razon"]) == tokens(ctx.value):
+ ctx.enrich({k: v for k, v in c["attrs"].items() if k != "_links"})
+ ctx.add("rut", c["rut"], {}, rel="RUT", pivot=False)
+ ctx.found += 1
+ break
+ else:
+ await self._person(ctx, con)
+ finally:
+ con.close()
+ if missing:
+ ctx.message = ((ctx.message + " · ") if ctx.message else "") + \
+ f"datos.gob.cl no entregó {len(missing)} de los archivos anuales; se reintentará en la próxima búsqueda"
+ elif first_time and not ctx.message:
+ ctx.message = "Base de empresas descargada (sólo la primera vez)"
+
+ async def _person(self, ctx, con):
+ parts = [w for w in tokens(ctx.value) if len(w) > 1]
+ if len(parts) < 2:
+ raise Skip("Hace falta nombre y apellido")
+ full_q = " ".join(f'"{w}"' for w in parts)
+ named = [(n, r) for n, r in _search(con, full_q, 40) if name_match(r, ctx.value, [])]
+ surname = []
+ if len(parts) >= 3:
+ sq = f'"{parts[-2]}" "{parts[-1]}"'
+ surname = [(n, r) for n, r in _search(con, sq, 60)
+ if (n, r) not in named and re.search(rf"\b{parts[-2]}\W+{parts[-1]}\b", " ".join(tokens(r)))]
+ for num, _ in named[:10]:
+ c = _company(con, num)
+ if c:
+ c["attrs"]["Verificación"] = "Su nombre completo está en la razón social"
+ oid = ctx.add("organization", c["razon"], c["attrs"], rel="empresa con su nombre", pivot=False)
+ if oid:
+ ctx.add("rut", c["rut"], {}, rel="RUT", parent=oid, pivot=False)
+ ctx.found += 1
+ if surname:
+ ctx.enrich({"Sociedades con sus dos apellidos (posibles familiares)": [
+ f"{r} · {_company(con, n)['rut']}" for n, r in surname[:20]]})
+ ctx.message = (f"{len(named)} empresa(s) con su nombre completo"
+ + (f" · {len(surname)} sociedades con sus dos apellidos (posibles familiares)" if surname else ""))
+
+
+# ---------------------------------------------------------------- Tesis (LA Referencia)
+
+@register
+class TesisLatam(Module):
+ name = "tesis_latam"
+ title = "Tesis y publicaciones (LA Referencia)"
+ description = ("Tesis de pregrado, magíster y doctorado, y artículos de repositorios universitarios de Chile y "
+ "Latinoamérica firmados con ese nombre: universidad, año, tema y enlace")
+ inputs = ("person",)
+ sources = ("lareferencia.info",)
+
+ async def run(self, ctx):
+ name = ctx.value.strip()
+ if len(tokens(name)) < 2:
+ raise Skip("Hace falta nombre y apellido")
+ variants = name_variants(name)[:2]
+ records = {}
+ for q in [name] + variants:
+ st, d = await ctx.get_json("https://buscador.lareferencia.info/api/v1/search", params={
+ "lookfor": q, "type": "Author", "limit": 40,
+ "field[]": ["id", "title", "primaryAuthors", "secondaryAuthors", "formats", "publicationDates", "urls",
+ "institutions", "subjects", "rawData"]}, headers=UA, timeout=40)
+ for rec in (d or {}).get("records") or []:
+ records.setdefault(rec["id"], rec)
+ kinds = {"bachelorThesis": "Tesis de pregrado", "masterThesis": "Tesis de magíster", "doctoralThesis": "Tesis de doctorado",
+ "article": "Artículo", "book": "Libro", "conferenceObject": "Ponencia", "report": "Informe"}
+ exact, partial = [], []
+ for rec in records.values():
+ authors = [" ".join(reversed([p.strip() for p in a.split(",", 1)])) for a in rec.get("primaryAuthors") or []]
+ match = next((m for m in (name_match(a, name, variants) for a in authors) if m), None)
+ if not match:
+ continue
+ if match[0] == "exacta" and not any(same_name(a, name) for a in authors):
+ match = ("parcial", match[1])
+ raw = rec.get("rawData") or {}
+ item = {
+ "title": rec.get("title"),
+ "kind": kinds.get((rec.get("formats") or [""])[0], (rec.get("formats") or ["Documento"])[0]),
+ "year": (rec.get("publicationDates") or [None])[0],
+ "inst": (rec.get("institutions") or [None])[0],
+ "country": raw.get("network_name_str"),
+ "url": next((u.get("url") for u in rec.get("urls") or [] if u.get("url")), None),
+ "advisor": [" ".join(reversed([p.strip() for p in a.split(",", 1)])) for a in rec.get("secondaryAuthors") or []][:2],
+ "subjects": [s[0] for s in rec.get("subjects") or [] if s][:5],
+ }
+ (exact if match[0] == "exacta" else partial).append(item)
+ if not exact and not partial:
+ ctx.message = "Sin tesis ni publicaciones con ese nombre"
+ return
+ line = lambda it: f"{it['title']} · {it['kind']} · {it['inst'] or ''} ({it['year'] or 's/f'})" # noqa: E731
+ theses = [it for it in exact if it["kind"].startswith("Tesis") and it["url"]]
+ for it in theses[:15]:
+ ctx.add("url", it["url"], {
+ "Título": it["title"], "Tipo": it["kind"], "Año": it["year"], "Institución": it["inst"],
+ "País": it["country"], "Profesor guía": it["advisor"] or None, "Temas": it["subjects"] or None,
+ "_links": [["Abrir tesis", it["url"]]],
+ }, rel=it["kind"].lower(), pivot=False)
+ if it["inst"] and not it["inst"].startswith("Agencia Nacional"):
+ ctx.add("organization", it["inst"], {"Tipo": "Universidad"},
+ rel=f"estudió en ({it['year']})" if it["year"] else "estudió en", pivot=False)
+ others = [it for it in exact if it not in theses]
+ ctx.enrich({"Publicaciones (LA Referencia)": [line(it) for it in others[:25]],
+ "Tesis con nombre parecido": [line(it) for it in partial[:15]]})
+ ctx.message = (f"{len(theses)} tesis y {len(others)} publicaciones con su nombre completo"
+ + (f" · {len(partial)} con nombre parecido" if partial else ""))
diff --git a/app/modules/deep.py b/app/modules/deep.py
new file mode 100644
index 0000000..0f83d5d
--- /dev/null
+++ b/app/modules/deep.py
@@ -0,0 +1,302 @@
+import asyncio
+import base64
+import hashlib
+import html
+import re
+from collections import Counter
+
+import httpx
+
+from ..db import db
+from .base import Module, Skip, register
+from .username import PROFILE_URLS, add_profile
+
+
+def _gh_headers(ctx) -> dict:
+ h = {"Accept": "application/vnd.github+json"}
+ if ctx.key("github"):
+ h["Authorization"] = f"Bearer {ctx.key('github')}"
+ return h
+
+
+def ssh_fingerprints(text: str) -> dict[str, str]:
+ """{huella SHA256: tipo} de un fichero tipo authorized_keys."""
+ out = {}
+ for line in (text or "").splitlines():
+ parts = line.split()
+ if len(parts) < 2 or not parts[0].startswith(("ssh-", "ecdsa-", "sk-")):
+ continue
+ try:
+ blob = base64.b64decode(parts[1])
+ except ValueError:
+ continue
+ fp = "SHA256:" + base64.b64encode(hashlib.sha256(blob).digest()).decode().rstrip("=")
+ out[fp] = parts[0]
+ return out
+
+
+def find_account(case_id: int, platform: str, user: str) -> dict | None:
+ user = user.lower()
+ for e in db.graph(case_id)["entities"]:
+ a = e["attrs"]
+ if e["type"] == "account" and a.get("Plataforma") == platform and str(a.get("Usuario") or "").lower() == user:
+ return e
+ return None
+
+
+@register
+class GithubDeep(Module):
+ name = "github_deep"
+ title = "GitHub a fondo"
+ description = ("Organizaciones, repositorios y lenguajes, cuentas enlazadas, emails de sus claves GPG y "
+ "claves SSH (si GitLab tiene la misma clave, es la misma persona)")
+ inputs = ("username",)
+ optional_keys = ("github",)
+ sources = ("api.github.com",)
+
+ async def run(self, ctx):
+ h = _gh_headers(ctx)
+ st, user = await ctx.get_json(f"https://api.github.com/users/{ctx.value.strip().lstrip('@')}", headers=h)
+ if st in (403, 429):
+ raise Skip("Límite de la API de GitHub alcanzado (60/hora sin clave): añade un token gratuito en Ajustes")
+ if st != 200 or not isinstance(user, dict):
+ return
+ login = user["login"]
+ api = f"https://api.github.com/users/{login}"
+ (st_s, social), (st_o, orgs), (st_r, repos), (st_g, gpg) = await asyncio.gather(
+ ctx.get_json(f"{api}/social_accounts", headers=h),
+ ctx.get_json(f"{api}/orgs", headers=h),
+ ctx.get_json(f"{api}/repos?per_page=100&sort=pushed&type=owner", headers=h),
+ ctx.get_json(f"{api}/gpg_keys", headers=h),
+ )
+ gh_keys, gl_keys = await asyncio.gather(
+ self._text(ctx, f"https://github.com/{login}.keys"),
+ self._text(ctx, f"https://gitlab.com/{login}.keys"),
+ )
+
+ attrs: dict = {"_avatar": user.get("avatar_url")}
+ urls = [x.get("url") for x in social if isinstance(x, dict)] if st_s == 200 and isinstance(social, list) else []
+
+ if st_r == 200 and isinstance(repos, list):
+ own = [r for r in repos if not r.get("fork")]
+ langs = Counter(r["language"] for r in own if r.get("language"))
+ top = sorted(own, key=lambda r: -(r.get("stargazers_count") or 0))[:6]
+ attrs.update({
+ "Repos propios (últimos 100)": len(own),
+ "Forks": len(repos) - len(own) or None,
+ "Estrellas recibidas": sum(r.get("stargazers_count") or 0 for r in own) or None,
+ "Lenguajes": [f"{lang} ({n})" for lang, n in langs.most_common(8)] or None,
+ "Repos destacados": [f"{r['name']} ★{r.get('stargazers_count', 0)}"
+ + (f" — {r['description'][:90]}" if r.get("description") else "") for r in top] or None,
+ "Último push": (own[0].get("pushed_at") or "")[:10] or None if own else None,
+ })
+ urls += [r.get("homepage") for r in own if r.get("homepage")][:15]
+
+ gpg_emails: list[str] = []
+ if st_g == 200 and isinstance(gpg, list) and gpg:
+ for k in gpg:
+ for sub in [k] + (k.get("subkeys") or []):
+ gpg_emails += [e["email"] for e in sub.get("emails") or [] if e.get("email")]
+ attrs["Claves GPG"] = [k.get("key_id") for k in gpg if k.get("key_id")]
+
+ fps = ssh_fingerprints(gh_keys)
+ if fps:
+ attrs["Claves SSH"] = [f"{t} {fp}" for fp, t in fps.items()]
+
+ acc = add_profile(ctx, {
+ "platform": "GitHub", "user": login, "url": user["html_url"], "attrs": attrs,
+ "emails": gpg_emails, "urls": urls,
+ })
+ if not acc:
+ return
+
+ if st_o == 200 and isinstance(orgs, list):
+ for o in orgs:
+ ctx.add("organization", f"GitHub: {o['login']}", {
+ "Descripción": o.get("description"), "_avatar": o.get("avatar_url"),
+ "_links": [["Abrir en GitHub", f"https://github.com/{o['login']}"]],
+ }, rel="miembro de", parent=acc, pivot=False)
+
+ shared = set(fps) & set(ssh_fingerprints(gl_keys))
+ if shared:
+ url = f"https://gitlab.com/{login}"
+ ctx.add("account", url, {
+ "Plataforma": "GitLab", "Usuario": login, "_links": [["Abrir perfil", url]],
+ "Verificación": "Misma clave SSH que GitHub",
+ "Claves SSH en común": sorted(shared),
+ }, rel="misma clave SSH", parent=acc, pivot=False)
+
+ @staticmethod
+ async def _text(ctx, url: str) -> str:
+ try:
+ r = await ctx.http.get(url, timeout=15)
+ except httpx.HTTPError:
+ return ""
+ return r.text if r.status_code == 200 and "<html" not in r.text[:200].lower() else ""
+
+
+# ---------------------------------------------------------------- Wayback: perfiles archivados
+
+ARCHIVE_TARGETS = [
+ ("X/Twitter", "twitter.com/{}"), ("Instagram", "instagram.com/{}/"), ("TikTok", "tiktok.com/@{}"),
+ ("Facebook", "facebook.com/{}"), ("Reddit", "reddit.com/user/{}"), ("YouTube", "youtube.com/@{}"),
+ ("Twitch", "twitch.tv/{}"), ("Telegram", "t.me/{}"), ("GitHub", "github.com/{}"),
+ ("LinkedIn", "linkedin.com/in/{}"), ("Pinterest", "pinterest.com/{}/"), ("Tumblr", "{}.tumblr.com"),
+ ("Threads", "threads.net/@{}"), ("Medium", "medium.com/@{}"),
+]
+
+
+# compartido entre todos los usuarios investigados a la vez: Internet Archive limita las consultas
+_CDX_SEM = asyncio.Semaphore(4)
+
+
+def _ts(ts: str) -> str:
+ return f"{ts[:4]}-{ts[4:6]}-{ts[6:8]}"
+
+
+async def wait_for_module(ctx, module: str, limit: float = 90) -> None:
+ """Espera a que otro módulo que corre en paralelo sobre la misma entidad termine."""
+ eid = ctx.entity["id"]
+
+ def running() -> bool:
+ started = done = False
+ for e in ctx.job.events:
+ if e.get("type") == "run_start" and e.get("entity_id") == eid and e.get("module") == module:
+ started = True
+ elif e.get("type") == "run" and e["run"]["entity_id"] == eid and e["run"]["module"] == module:
+ done = True
+ return started and not done
+
+ for _ in range(int(limit * 2)):
+ if not running():
+ return
+ await asyncio.sleep(0.5)
+
+
+@register
+class WaybackProfiles(Module):
+ name = "wayback_profiles"
+ title = "Perfiles archivados (Wayback)"
+ description = ("Busca copias de sus perfiles en Internet Archive: sirve para ver cuentas borradas o "
+ "cómo eran antes")
+ inputs = ("username",)
+ sources = ("web.archive.org",)
+ timeout = 180
+
+ async def run(self, ctx):
+ u = ctx.value.strip().lstrip("@")
+ if not re.fullmatch(r"[\w.\-]{2,40}", u):
+ raise Skip("El usuario tiene caracteres que no forman parte de una URL de perfil")
+
+ async def one(platform, tpl):
+ target = tpl.format(u)
+ async with _CDX_SEM:
+ for attempt in range(2):
+ try:
+ r = await ctx.http.get("https://web.archive.org/cdx/search/cdx", timeout=40, params={
+ "url": target, "output": "json", "fl": "timestamp", "filter": "statuscode:200",
+ "collapse": "timestamp:6", "limit": "2000",
+ })
+ except httpx.HTTPError:
+ return platform, target, None
+ if r.status_code in (429, 503) and attempt == 0:
+ await asyncio.sleep(4)
+ continue
+ break
+ if r.status_code != 200:
+ return platform, target, None
+ try:
+ rows = r.json()[1:]
+ except ValueError:
+ return platform, target, None
+ return platform, target, [x[0] for x in rows]
+
+ results = await asyncio.gather(*(one(p, t) for p, t in ARCHIVE_TARGETS))
+ # si a la vez se están comprobando los perfiles en vivo, hay que saber cuáles existen antes de marcar
+ # una cuenta como "sólo vista en archivo"
+ await wait_for_module(ctx, "username_profiles")
+ failed = [p for p, _, s in results if s is None]
+ found = [(p, t, s) for p, t, s in results if s]
+ for platform, target, stamps in found:
+ first, last = stamps[0], stamps[-1]
+ attrs = {
+ "Wayback: primera captura": _ts(first),
+ "Wayback: última captura": _ts(last),
+ "Wayback: meses con capturas": len(stamps),
+ "_links": [["Primera copia archivada", f"https://web.archive.org/web/{first}/https://{target}"],
+ ["Última copia archivada", f"https://web.archive.org/web/{last}/https://{target}"],
+ ["Todas las copias", f"https://web.archive.org/web/*/{target}*"]],
+ }
+ existing = find_account(ctx.case_id, platform, u)
+ if existing:
+ ctx.enrich(attrs, existing["id"])
+ continue
+ url = PROFILE_URLS.get(platform, "https://{}").format(u) if platform in PROFILE_URLS else f"https://{target}"
+ attrs.update({"Plataforma": platform, "Usuario": u,
+ "Verificación": "Sólo vista en archivo (puede estar borrada o no se comprobó en vivo)"})
+ ctx.add("account", url, attrs, rel="archivada", pivot=False)
+ if failed and not found:
+ raise Skip(f"Internet Archive no respondió ({len(failed)} consultas fallidas); prueba más tarde")
+ ctx.message = f"Copias en {len(found)} plataformas" + (f": {', '.join(p for p, _, _ in found)}" if found else "") \
+ + (f" · sin respuesta: {', '.join(failed)}" if failed else "")
+
+
+# ---------------------------------------------------------------- menciones en foros
+
+def _snippet(text: str, term: str, n: int = 160) -> str:
+ text = re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", html.unescape(text or ""))).strip()
+ i = text.lower().find(term.lower())
+ if i < 0:
+ return text[:n]
+ start = max(0, i - n // 3)
+ return ("…" if start else "") + text[start:start + n] + ("…" if start + n < len(text) else "")
+
+
+@register
+class ForumMentions(Module):
+ name = "forum_mentions"
+ title = "Menciones en foros (Hacker News)"
+ description = "Comentarios y publicaciones de Hacker News que mencionan el dato, con autor, fecha y enlace"
+ inputs = ("username", "email", "person", "domain")
+ sources = ("hn.algolia.com",)
+
+ async def run(self, ctx):
+ term = ctx.value.strip().lstrip("@")
+ if len(term) < 4:
+ raise Skip("Término demasiado corto para buscar menciones sin ruido")
+ base = "https://hn.algolia.com/api/v1/search"
+ if ctx.entity["type"] == "domain":
+ params = {"query": term, "restrictSearchableAttributes": "url", "tags": "story", "hitsPerPage": 50}
+ else:
+ params = {"query": f'"{term}"', "tags": "(comment,story)", "hitsPerPage": 50, "typoTolerance": "false"}
+ st, d = await ctx.get_json(base, params=params)
+ if st != 200 or not isinstance(d, dict):
+ raise RuntimeError(f"Hacker News respondió {st}")
+ hits = []
+ for h in d.get("hits") or []:
+ text = " ".join(str(h.get(k) or "") for k in ("comment_text", "story_text", "title", "url"))
+ if term.lower() not in text.lower():
+ continue
+ if ctx.entity["type"] == "username" and (h.get("author") or "").lower() == term.lower():
+ continue
+ hits.append(h)
+ if not hits:
+ return
+ hits.sort(key=lambda h: -(h.get("created_at_i") or 0))
+ lines, links = [], []
+ for h in hits[:12]:
+ item = f"https://news.ycombinator.com/item?id={h['objectID']}"
+ date = (h.get("created_at") or "")[:10]
+ what = h.get("title") or _snippet(h.get("comment_text") or h.get("story_text") or "", term)
+ lines.append(f"{date} · {h.get('author')}: {what}")
+ links.append([f"HN {date} · {h.get('author')}", item])
+ authors = Counter(h.get("author") for h in hits if h.get("author"))
+ ctx.message = f"{d.get('nbHits') or len(hits)} menciones en Hacker News"
+ ctx.enrich({
+ "Menciones en Hacker News": d.get("nbHits") or len(hits),
+ "Menciones recientes (HN)": lines,
+ "Quién lo menciona más (HN)": [f"{a} ({n})" for a, n in authors.most_common(5)] if len(authors) > 1 else None,
+ "Primera mención (HN)": min((h.get("created_at") or "")[:10] for h in hits),
+ "_links": links[:8],
+ })
+ ctx.found += len(hits)
diff --git a/app/modules/documents.py b/app/modules/documents.py
new file mode 100644
index 0000000..667a10f
--- /dev/null
+++ b/app/modules/documents.py
@@ -0,0 +1,376 @@
+"""Metadatos de documentos publicados por un dominio (estilo FOCA): autores, usuarios internos y software."""
+import asyncio
+import io
+import json
+import re
+import unicodedata
+import zipfile
+import xml.etree.ElementTree as ET
+from collections import Counter
+from urllib.parse import unquote, urlparse
+
+import httpx
+
+from ..util import EMAIL_RE
+from .chile import find_ruts
+from .base import Module, register
+
+DOC_MIME = r"application/(pdf|msword|vnd\.ms-excel|vnd\.ms-powerpoint|vnd\.openxmlformats-officedocument\..*)"
+EXT_BY_MIME = {
+ "application/pdf": "pdf", "application/msword": "doc", "application/vnd.ms-excel": "xls",
+ "application/vnd.ms-powerpoint": "ppt",
+}
+MAX_DOCS = 30
+MAX_BYTES = 20 * 1024 * 1024
+
+# autores genéricos que no identifican a nadie
+GENERIC_AUTHORS = {
+ "admin", "administrator", "administrador", "user", "usuario", "owner", "propietario", "default", "unknown",
+ "author", "autor", "test", "pc", "hp", "dell", "lenovo", "acer", "asus", "windows user", "usuario de windows",
+ "microsoft office user", "usuario de microsoft office", "utilisateur", "guest", "invitado", "home", "casa",
+ "oficina", "office", "compaq", "toshiba", "samsung", "sony", "pc1", "user1", "usuario1", "",
+}
+
+
+def _ext(url: str, mime: str) -> str:
+ path = urlparse(url).path.lower()
+ m = re.search(r"\.(pdf|docx?|xlsx?|pptx?)$", path)
+ if m:
+ return m.group(1)
+ if "wordprocessingml" in mime:
+ return "docx"
+ if "spreadsheetml" in mime:
+ return "xlsx"
+ if "presentationml" in mime:
+ return "pptx"
+ return EXT_BY_MIME.get(mime, "pdf")
+
+
+def _pdf_date(v) -> str | None:
+ m = re.search(r"(\d{4})(\d{2})(\d{2})", str(v or ""))
+ return f"{m.group(1)}-{m.group(2)}-{m.group(3)}" if m else None
+
+
+def _clean(v) -> str | None:
+ if v is None:
+ return None
+ s = re.sub(r"\s+", " ", str(v)).strip().strip("\x00").strip()
+ return s or None
+
+
+def meta_pdf(data: bytes) -> dict:
+ from pypdf import PdfReader
+
+ r = PdfReader(io.BytesIO(data), strict=False)
+ if r.is_encrypted:
+ try:
+ r.decrypt("")
+ except Exception: # noqa: BLE001
+ return {}
+ m = r.metadata or {}
+ out = {
+ "author": _clean(m.get("/Author")), "creator_tool": _clean(m.get("/Creator")),
+ "producer": _clean(m.get("/Producer")), "title": _clean(m.get("/Title")),
+ "created": _pdf_date(m.get("/CreationDate")), "modified": _pdf_date(m.get("/ModDate")),
+ "company": _clean(m.get("/Company")), "last_modified_by": _clean(m.get("/LastModifiedBy")),
+ }
+ try:
+ x = r.xmp_metadata
+ if x is not None:
+ if not out["author"] and x.dc_creator:
+ out["author"] = _clean(", ".join(x.dc_creator))
+ out["creator_tool"] = out["creator_tool"] or _clean(x.xmp_creator_tool)
+ except Exception: # noqa: BLE001
+ pass
+ parts = []
+ for page in r.pages[:8]:
+ try:
+ parts.append(page.extract_text() or "")
+ except Exception: # noqa: BLE001
+ break
+ out["text"] = "\n".join(parts)[:200_000]
+ return out
+
+
+OOXML_TEXT_PARTS = re.compile(r"^(word/document\.xml|xl/sharedStrings\.xml|ppt/slides/slide\d+\.xml)$")
+
+
+def _ooxml_text(z: zipfile.ZipFile) -> str:
+ parts = []
+ for n in [n for n in z.namelist() if OOXML_TEXT_PARTS.match(n)][:30]:
+ xml = z.read(n).decode("utf-8", "replace")
+ parts.append(re.sub(r"<[^>]+>", " ", re.sub(r"</w:p>|</a:p>|</si>", "\n", xml)))
+ return " ".join(parts)[:200_000]
+
+
+NS = {
+ "cp": "http://schemas.openxmlformats.org/package/2006/metadata/core-properties",
+ "dc": "http://purl.org/dc/elements/1.1/",
+ "dcterms": "http://purl.org/dc/terms/",
+ "ep": "http://schemas.openxmlformats.org/officeDocument/2006/extended-properties",
+}
+
+
+def meta_ooxml(data: bytes) -> dict:
+ z = zipfile.ZipFile(io.BytesIO(data))
+ out: dict = {}
+ if "docProps/core.xml" in z.namelist():
+ core = ET.fromstring(z.read("docProps/core.xml"))
+ g = lambda p: _clean(core.findtext(p, namespaces=NS)) # noqa: E731
+ out.update({"author": g("dc:creator"), "last_modified_by": g("cp:lastModifiedBy"), "title": g("dc:title"),
+ "created": (g("dcterms:created") or "")[:10] or None,
+ "modified": (g("dcterms:modified") or "")[:10] or None})
+ if "docProps/app.xml" in z.namelist():
+ app = ET.fromstring(z.read("docProps/app.xml"))
+ g = lambda p: _clean(app.findtext(f"ep:{p}", namespaces=NS)) # noqa: E731
+ tool = g("Application")
+ if tool and g("AppVersion"):
+ tool = f"{tool} {g('AppVersion')}"
+ out.update({"creator_tool": tool, "company": g("Company"), "manager": g("Manager"), "template": g("Template")})
+ try:
+ out["text"] = _ooxml_text(z)
+ except Exception: # noqa: BLE001
+ pass
+ return out
+
+
+def meta_ole(data: bytes) -> dict:
+ import olefile
+
+ ole = olefile.OleFileIO(io.BytesIO(data))
+ try:
+ m = ole.get_metadata()
+ finally:
+ ole.close()
+ dec = lambda v: _clean(v.decode("latin-1", "replace") if isinstance(v, bytes) else v) # noqa: E731
+ date = lambda v: v.strftime("%Y-%m-%d") if hasattr(v, "strftime") else None # noqa: E731
+ return {
+ "author": dec(m.author), "last_modified_by": dec(m.last_saved_by), "title": dec(m.title),
+ "creator_tool": dec(m.creating_application), "company": dec(m.company), "manager": dec(m.manager),
+ "template": dec(m.template), "created": date(m.create_time), "modified": date(m.last_saved_time),
+ }
+
+
+def extract(data: bytes, ext: str) -> dict:
+ try:
+ if data[:5] == b"%PDF-":
+ return meta_pdf(data)
+ if data[:2] == b"PK":
+ return meta_ooxml(data)
+ if data[:8] == b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1":
+ return meta_ole(data)
+ except Exception: # noqa: BLE001 documentos corruptos o raros: se ignoran
+ return {}
+ return {}
+
+
+COMPANY_RE = re.compile(r"\b(limitada|ltda|spa|s\.?a\.?|s\.?r\.?l\.?|inc|llc|ltd|gmbh|corp|eirl|consultores|"
+ r"asociados|ministerio|municipalidad|universidad|servicio|subsecretar[ií]a)\b\.?", re.I)
+
+
+def _fold(s: str) -> str:
+ return unicodedata.normalize("NFKD", s).encode("ascii", "ignore").decode().lower()
+
+
+def classify_author(s: str) -> tuple[str, str] | None:
+ """('person'|'organization'|'username'|'email', valor) o None si el autor es genérico."""
+ s = s.strip().strip("'\"")
+ if not s or s.lower() in GENERIC_AUTHORS or len(s) > 60:
+ return None
+ if COMPANY_RE.search(s):
+ return "organization", s
+ if re.search(r"microsoft|office|adobe|writer|word|excel|acrobat|pdf|printer|impresora|scanner|canon|xerox|ricoh", s, re.I):
+ return None
+ em = EMAIL_RE.search(s)
+ if em:
+ return "email", em.group(0).lower()
+ if "\\" in s: # DOMINIO\usuario
+ s = s.split("\\")[-1]
+ tokens = s.split()
+ if len(tokens) >= 2 and all(re.fullmatch(r"[A-Za-zÁÉÍÓÚÜÑáéíóúüñ.'\-]+", t) for t in tokens) and len(tokens) <= 5:
+ return "person", " ".join(t.capitalize() if t.isupper() or t.islower() else t for t in tokens)
+ if len(tokens) == 1 and re.fullmatch(r"[A-Za-z][\w.\-]{2,30}", s) and not s.isdigit():
+ return "username", s.lower()
+ return None
+
+
+@register
+class DocMetadata(Module):
+ name = "doc_metadata"
+ title = "Metadatos de documentos"
+ description = ("Busca PDF, Word, Excel y PowerPoint publicados por el dominio (vía Internet Archive y Common "
+ "Crawl), los descarga y extrae autores, usuarios internos, empresa y software usado")
+ inputs = ("domain",)
+ sources = ("web.archive.org", "index.commoncrawl.org")
+ timeout = 240
+
+ async def run(self, ctx):
+ domain = ctx.value.lower()
+ docs = await self._find_wayback(ctx, domain)
+ source = "Internet Archive"
+ if not docs:
+ docs = await self._find_commoncrawl(ctx, domain)
+ source = "Common Crawl"
+ if not docs:
+ ctx.message = "No se encontraron documentos publicados en este dominio"
+ return
+
+ sem = asyncio.Semaphore(4)
+
+ async def fetch(doc):
+ async with sem:
+ for url in doc["fetch"]:
+ try:
+ async with ctx.http.stream("GET", url, timeout=45) as r:
+ if r.status_code != 200:
+ continue
+ buf = bytearray()
+ async for chunk in r.aiter_bytes():
+ buf += chunk
+ if len(buf) > MAX_BYTES:
+ break
+ if len(buf) > MAX_BYTES:
+ return doc, None
+ return doc, bytes(buf)
+ except httpx.HTTPError:
+ continue
+ return doc, None
+
+ results = await asyncio.gather(*(fetch(d) for d in docs))
+ analysed = []
+ for doc, data in results:
+ if not data:
+ continue
+ meta = await asyncio.to_thread(extract, data, doc["ext"])
+ if any(meta.values()):
+ analysed.append((doc, meta))
+ if not analysed:
+ ctx.message = f"{len(docs)} documentos encontrados en {source}, pero ninguno se pudo descargar o no tenían metadatos"
+ return
+
+ people: dict[str, list[str]] = {}
+ users: dict[str, list[str]] = {}
+ emails: dict[str, list[str]] = {}
+ tools, companies = Counter(), Counter()
+ ruts: dict[str, dict] = {}
+ dates = []
+ shown: dict[str, str] = {} # nombre sin tildes -> forma a mostrar (la que lleva tildes si existe)
+ domain_label = domain.split(".")[0]
+ for doc, meta in analysed:
+ name = unquote(urlparse(doc["url"]).path.rsplit("/", 1)[-1])[:80] or doc["url"]
+ for field in ("author", "last_modified_by", "manager"):
+ for part in re.split(r"[;,]| y | and ", meta.get(field) or ""):
+ c = classify_author(part)
+ if not c:
+ continue
+ kind, value = c
+ if kind == "organization":
+ companies[value] += 1
+ continue
+ if kind == "username" and value == domain_label:
+ continue
+ if kind == "person":
+ key = _fold(value)
+ if key not in shown or value.lower() != key:
+ shown[key] = value
+ value = key
+ bucket = {"person": people, "username": users, "email": emails}[kind]
+ bucket.setdefault(value, [])
+ if name not in bucket[value]:
+ bucket[value].append(name)
+ for k in ("creator_tool", "producer"):
+ if meta.get(k):
+ tools[meta[k]] += 1
+ if meta.get("company"):
+ companies[meta["company"]] += 1
+ for rut, context in find_ruts(meta.get("text") or "", limit=60):
+ entry = ruts.setdefault(rut, {"files": [], "context": []})
+ if name not in entry["files"]:
+ entry["files"].append(name)
+ entry["context"].append(f"{name}: …{context}…")
+ dates += [d for d in (meta.get("created"), meta.get("modified")) if d and d[:4].isdigit() and 1990 < int(d[:4]) < 2100]
+ people = {shown[k]: v for k, v in people.items()}
+
+ for value, files in people.items():
+ ctx.add("person", value, {"Documentos firmados": files[:15]}, rel="autor de documentos", pivot=False)
+ for value, files in users.items():
+ ctx.add("username", value, {"Aparece en documentos": files[:15], "Origen": "Usuario interno en metadatos"},
+ rel="usuario en metadatos", pivot=False)
+ for value, files in emails.items():
+ ctx.add("email", value, {"Aparece en documentos": files[:15]}, rel="email en metadatos", pivot=False)
+ for rut, entry in sorted(ruts.items(), key=lambda kv: -len(kv[1]["files"]))[:80]:
+ ctx.add("rut", rut, {"Aparece en documentos": entry["files"][:15], "Contexto en documentos": entry["context"][:5]},
+ rel="RUT en documentos", pivot=False)
+ for company in companies:
+ if company.lower() not in GENERIC_AUTHORS and len(company) > 2:
+ ctx.add("organization", company, {"Documentos": companies[company]}, rel="empresa en metadatos", pivot=False)
+
+ ctx.enrich({
+ "Documentos analizados": len(analysed),
+ "Software de los documentos": [f"{t} ({n})" for t, n in tools.most_common(10)] or None,
+ "Autores en metadatos": sorted(people) or None,
+ "Usuarios internos en metadatos": sorted(users) or None,
+ "Periodo de los documentos": f"{min(dates)} → {max(dates)}" if dates else None,
+ "_links": [[f"Doc: {unquote(urlparse(d['url']).path.rsplit('/', 1)[-1])[:60]}", d["view"]] for d, _ in analysed[:12]],
+ })
+ ctx.message = (f"{len(analysed)} documentos analizados ({source}) · {len(people)} autores · "
+ f"{len(users)} usuarios internos · {len(emails)} emails · {len(ruts)} RUT")
+
+ async def _find_wayback(self, ctx, domain: str) -> list[dict]:
+ try:
+ st, rows = await ctx.get_json("https://web.archive.org/cdx/search/cdx", timeout=75, params={
+ "url": domain, "matchType": "domain", "output": "json", "fl": "original,mimetype,timestamp",
+ "filter": [f"mimetype:{DOC_MIME}", "statuscode:200"], "collapse": "urlkey", "limit": "400",
+ })
+ except httpx.HTTPError:
+ return []
+ if st != 200 or not isinstance(rows, list) or len(rows) < 2:
+ return []
+ rows = sorted(rows[1:], key=lambda r: r[2], reverse=True)
+ return self._pick([{
+ "url": url, "ext": _ext(url, mime),
+ "fetch": [f"https://web.archive.org/web/{ts}id_/{url}", url],
+ "view": f"https://web.archive.org/web/{ts}/{url}",
+ } for url, mime, ts in rows])
+
+ async def _find_commoncrawl(self, ctx, domain: str) -> list[dict]:
+ try:
+ st, colls = await ctx.get_json("https://index.commoncrawl.org/collinfo.json", timeout=20)
+ if st != 200 or not colls:
+ return []
+ api = colls[0]["cdx-api"]
+ r = await ctx.http.get(api, timeout=75, params={
+ "url": f"*.{domain}", "output": "json", "filter": ["mime:application/(pdf|msword|vnd\\..*)", "status:200"],
+ "limit": "300",
+ })
+ except (httpx.HTTPError, KeyError, IndexError):
+ return []
+ if r.status_code != 200:
+ return []
+ rows = []
+ for line in r.text.splitlines():
+ try:
+ rows.append(json.loads(line))
+ except ValueError:
+ continue
+ seen, docs = set(), []
+ for x in rows:
+ url = x.get("url")
+ if not url or url in seen:
+ continue
+ seen.add(url)
+ docs.append({"url": url, "ext": _ext(url, x.get("mime", "")), "fetch": [url], "view": url})
+ return self._pick(docs)
+
+ @staticmethod
+ def _pick(docs: list[dict]) -> list[dict]:
+ """Hasta MAX_DOCS, repartidos entre formatos para no quedarse sólo con PDF."""
+ by_ext: dict[str, list[dict]] = {}
+ for d in docs:
+ by_ext.setdefault(d["ext"], []).append(d)
+ out: list[dict] = []
+ while len(out) < MAX_DOCS and any(by_ext.values()):
+ for ext in list(by_ext):
+ if by_ext[ext] and len(out) < MAX_DOCS:
+ out.append(by_ext[ext].pop(0))
+ return out
diff --git a/app/modules/domain.py b/app/modules/domain.py
new file mode 100644
index 0000000..c6af7de
--- /dev/null
+++ b/app/modules/domain.py
@@ -0,0 +1,229 @@
+import asyncio
+import ipaddress
+import re
+
+import httpx
+
+from ..util import find_analytics_ids, parse_page, resolve, tech_from_response
+from .base import Module, register
+
+
+def _vcard(entity: dict) -> dict:
+ out = {}
+ for item in (entity.get("vcardArray") or [None, []])[1]:
+ if len(item) >= 4 and item[0] in ("fn", "org", "email", "tel", "adr"):
+ val = item[3]
+ if item[0] == "adr" and isinstance(val, list):
+ val = ", ".join(str(x) for x in val if x)
+ if val and not re.search(r"redacted|privacy|withheld|not disclosed", str(val), re.I):
+ out[item[0]] = val
+ return out
+
+
+ROLE_NAMES = {"registrant": "Titular", "administrative": "Administrativo", "technical": "Técnico",
+ "registrar": "Registrador", "abuse": "Abuso", "billing": "Facturación"}
+
+
+def add_page(ctx, page: dict, headers, html: str, parent: str | None = None) -> None:
+ """Vuelca lo encontrado en una página web al grafo."""
+ from .username import PROFILE_URLS
+
+ ctx.enrich({
+ "Título web": page["title"],
+ "Descripción web": page["description"],
+ "Tecnologías": tech_from_response(headers, html) + ([page["generator"]] if page["generator"] else []),
+ "IDs de analítica/publicidad": find_analytics_ids(html),
+ }, eid=parent)
+ from .enrich import DISCORD_INVITE
+
+ for e in page["emails"][:30]:
+ ctx.add("email", e, rel="email en la web", parent=parent)
+ for rut, context in page.get("ruts", [])[:20]:
+ ctx.add("rut", rut, {"Contexto en la web": [context]}, rel="RUT en la web", parent=parent, pivot=False)
+ for l in [l for l in page["external_links"] if DISCORD_INVITE.match(l)][:5]:
+ ctx.add("url", l, {"_links": [["Abrir", l]]}, rel="invitación de Discord", parent=parent, pivot=False)
+ for platform, user, url in page["socials"][:30]:
+ tpl = PROFILE_URLS.get(platform)
+ acc = ctx.add("account", tpl.format(user) if tpl else url,
+ {"Plataforma": platform, "Usuario": user, "_links": [["Abrir perfil", url]]},
+ rel="red social en la web", parent=parent, pivot=False)
+ if acc and platform not in ("LinkedIn", "Facebook"):
+ ctx.add("username", user, rel="usuario", parent=acc, pivot=False)
+
+
+@register
+class DnsRecords(Module):
+ name = "dns_records"
+ title = "Registros DNS"
+ description = "A, AAAA, MX, NS, TXT, SOA, CAA y DMARC; extrae IPs, servidores y servicios verificados en TXT."
+ inputs = ("domain",)
+ sources = ("DNS",)
+
+ async def run(self, ctx):
+ d = ctx.value
+ types = ("A", "AAAA", "MX", "NS", "TXT", "SOA", "CAA", "CNAME")
+ results = dict(zip(types, await asyncio.gather(*(resolve(d, t) for t in types))))
+ dmarc = await resolve(f"_dmarc.{d}", "TXT")
+ ctx.enrich({f"DNS {t}": v for t, v in results.items() if v} | ({"DMARC": dmarc} if dmarc else {}))
+ for ip in results["A"] + results["AAAA"]:
+ ctx.add("ip", ip, rel="resuelve a")
+ for mx in results["MX"]:
+ host = mx.split()[-1].rstrip(".")
+ if host and host != d:
+ ctx.add("domain", host, {"Rol": "Servidor de correo"}, rel="MX", pivot=False)
+ for ns in results["NS"]:
+ ctx.add("domain", ns.rstrip("."), {"Rol": "Servidor DNS"}, rel="NS", pivot=False)
+ verified = []
+ for txt in results["TXT"]:
+ m = re.match(r"^([a-z0-9\-_]+)-(?:site-)?verification=", txt, re.I)
+ if m:
+ verified.append(m.group(1))
+ for inc in re.findall(r"include:([^\s]+)", txt):
+ ctx.add("domain", inc, {"Rol": "Proveedor autorizado en SPF"}, rel="SPF", pivot=False)
+ if verified:
+ ctx.enrich({"Servicios verificados (TXT)": sorted(set(verified))})
+ for rec in dmarc:
+ for mail in re.findall(r"mailto:([^,;\s!]+)", rec):
+ ctx.add("email", mail.lower(), {"Rol": "Recibe informes DMARC"}, rel="DMARC", pivot=False)
+
+
+@register
+class Rdap(Module):
+ name = "rdap"
+ title = "WHOIS (RDAP)"
+ description = "Registrador, fechas de alta y caducidad, estado y contactos no ocultos."
+ inputs = ("domain",)
+ sources = ("RDAP (rdap.org)",)
+
+ async def run(self, ctx):
+ st, d = await ctx.get_json(f"https://rdap.org/domain/{ctx.value}")
+ if st != 200 or not isinstance(d, dict):
+ ctx.message = "El registro no publica RDAP para este dominio" if st == 404 else f"RDAP respondió {st}"
+ return
+ events = {e.get("eventAction"): (e.get("eventDate") or "")[:10] for e in d.get("events") or []}
+ attrs = {
+ "Alta": events.get("registration"),
+ "Caduca": events.get("expiration"),
+ "Última modificación": events.get("last changed"),
+ "Estado": d.get("status"),
+ "DNSSEC": "Sí" if (d.get("secureDNS") or {}).get("delegationSigned") else None,
+ }
+ for ent in d.get("entities") or []:
+ roles = ent.get("roles") or []
+ card = _vcard(ent)
+ nested = [_vcard(x) for x in ent.get("entities") or []]
+ if "registrar" in roles:
+ attrs["Registrador"] = card.get("fn") or card.get("org")
+ for n in nested:
+ if n.get("email"):
+ attrs["Email abuso registrador"] = n["email"]
+ continue
+ label = "/".join(ROLE_NAMES.get(r, r) for r in roles)
+ org = card.get("org") or card.get("fn")
+ if org:
+ ctx.add("organization", org, {"Rol WHOIS": label, "Dirección": card.get("adr"), "Teléfono": card.get("tel")},
+ rel=f"WHOIS {label}")
+ if card.get("email"):
+ ctx.add("email", card["email"], {"Rol WHOIS": label}, rel=f"WHOIS {label}")
+ ctx.enrich(attrs)
+
+
+@register
+class Subdomains(Module):
+ name = "subdomains"
+ title = "Subdominios (certificados)"
+ description = "Subdominios descubiertos en los registros públicos de certificados TLS."
+ inputs = ("domain",)
+ sources = ("crt.sh", "CertSpotter")
+ timeout = 90
+
+ async def run(self, ctx):
+ d = ctx.value
+ names: set[str] = set()
+ try:
+ r = await ctx.http.get("https://crt.sh/", params={"q": f"%.{d}", "output": "json"}, timeout=60)
+ if r.status_code == 200:
+ for row in r.json():
+ for n in (row.get("name_value") or "").split("\n"):
+ names.add(n.strip().lower().lstrip("*."))
+ except (httpx.HTTPError, ValueError):
+ pass
+ if not names:
+ st, data = await ctx.get_json(
+ "https://api.certspotter.com/v1/issuances",
+ params={"domain": d, "include_subdomains": "true", "expand": "dns_names"},
+ )
+ if st == 200 and isinstance(data, list):
+ for row in data:
+ for n in row.get("dns_names") or []:
+ names.add(n.lower().lstrip("*."))
+ subs = sorted(n for n in names if n.endswith("." + d) and n != d and " " not in n)
+ if not subs:
+ return
+ ctx.enrich({"Subdominios": subs, "Nº subdominios": len(subs)})
+ interesting = re.compile(r"(admin|vpn|dev|test|stag|intranet|mail|portal|api|panel|git|jenkins|old|backup|beta|internal)")
+ ordered = sorted(subs, key=lambda s: (not interesting.search(s), s))
+ for s in ordered[:60]:
+ ctx.add("domain", s, {"Rol": "Subdominio"}, rel="subdominio", pivot=False)
+ if len(subs) > 60:
+ ctx.message = f"{len(subs)} subdominios (60 en el grafo, lista completa en la ficha)"
+
+
+@register
+class Website(Module):
+ name = "website"
+ title = "Sitio web"
+ description = "Título, tecnologías, emails, redes sociales e IDs de analítica de la web del dominio."
+ inputs = ("domain",)
+ sources = ("HTTP directo",)
+
+ async def run(self, ctx):
+ r = None
+ for scheme in ("https", "http"):
+ try:
+ r = await ctx.http.get(f"{scheme}://{ctx.value}", timeout=20)
+ break
+ except httpx.HTTPError:
+ continue
+ if r is None:
+ ctx.message = "La web no responde"
+ return
+ html = r.text[:2_000_000]
+ page = parse_page(html, str(r.url))
+ ctx.enrich({"Web: estado HTTP": r.status_code, "Web: URL final": str(r.url)})
+ add_page(ctx, page, r.headers, html)
+
+
+@register
+class Wayback(Module):
+ name = "wayback"
+ title = "Archivo histórico (Wayback)"
+ description = "Primera y última captura en archive.org y número de capturas."
+ inputs = ("domain", "url")
+ sources = ("Internet Archive",)
+ timeout = 45
+
+ async def run(self, ctx):
+ target = ctx.value
+ params = {"url": target, "output": "json", "fl": "timestamp", "collapse": "timestamp:6"}
+ st, rows = await ctx.get_json("https://web.archive.org/cdx/search/cdx", params=params, timeout=40)
+ if st != 200 or not isinstance(rows, list) or len(rows) < 2:
+ return
+ stamps = [r[0] for r in rows[1:]]
+ fmt = lambda s: f"{s[:4]}-{s[4:6]}-{s[6:8]}" # noqa: E731
+ ctx.enrich({
+ "Wayback: primera captura": fmt(stamps[0]),
+ "Wayback: última captura": fmt(stamps[-1]),
+ "Wayback: meses con capturas": len(stamps),
+ "_links": [
+ ["Primera captura", f"https://web.archive.org/web/{stamps[0]}/{target}"],
+ ["Todas las capturas", f"https://web.archive.org/web/*/{target}*"],
+ ],
+ })
+
+
+def is_public_ip(ip: str) -> bool:
+ try:
+ return ipaddress.ip_address(ip).is_global
+ except ValueError:
+ return False
diff --git a/app/modules/email.py b/app/modules/email.py
new file mode 100644
index 0000000..265b176
--- /dev/null
+++ b/app/modules/email.py
@@ -0,0 +1,452 @@
+import asyncio
+import hashlib
+import random
+import string
+import time
+
+import httpx
+
+from ..config import DATA_DIR, settings
+from ..util import FREE_EMAIL_PROVIDERS, resolve
+from .base import Module, register
+from .username import _txt, add_profile
+
+DISPOSABLE_URL = "https://raw.githubusercontent.com/disposable-email-domains/disposable-email-domains/main/disposable_email_blocklist.conf"
+_disposable: set[str] | None = None
+
+
+async def disposable_domains(http: httpx.AsyncClient) -> set[str]:
+ global _disposable
+ if _disposable is not None:
+ return _disposable
+ cache = DATA_DIR / "disposable.txt"
+ if not cache.exists() or time.time() - cache.stat().st_mtime > 7 * 86400:
+ try:
+ r = await http.get(DISPOSABLE_URL, timeout=20)
+ if r.status_code == 200:
+ cache.write_text(r.text, encoding="utf-8")
+ except httpx.HTTPError:
+ pass
+ base = {"mailinator.com", "10minutemail.com", "guerrillamail.com", "tempmail.com", "yopmail.com", "trashmail.com"}
+ if cache.exists():
+ base |= {l.strip().lower() for l in cache.read_text(encoding="utf-8").splitlines() if l.strip()}
+ _disposable = base
+ return base
+
+
+@register
+class EmailBasics(Module):
+ name = "email_basics"
+ title = "Análisis del email"
+ description = "Valida el dominio (MX), detecta proveedores gratuitos y desechables y extrae dominio y posible usuario."
+ inputs = ("email",)
+ sources = ("DNS", "Lista de dominios desechables")
+
+ async def run(self, ctx):
+ local, _, domain = ctx.value.partition("@")
+ mx = await resolve(domain, "MX")
+ mx_hosts = sorted({m.split()[-1].rstrip(".") for m in mx if m})
+ free = domain in FREE_EMAIL_PROVIDERS
+ disposable = domain in await disposable_domains(ctx.http)
+ provider = None
+ joined = " ".join(mx_hosts).lower()
+ for needle, name in (("google", "Google Workspace / Gmail"), ("outlook", "Microsoft 365 / Outlook"),
+ ("protection.outlook", "Microsoft 365"), ("zoho", "Zoho Mail"), ("proton", "Proton Mail"),
+ ("yahoodns", "Yahoo"), ("icloud", "iCloud"), ("mimecast", "Mimecast"),
+ ("pphosted", "Proofpoint"), ("secureserver", "GoDaddy"), ("ovh", "OVH")):
+ if needle in joined:
+ provider = name
+ break
+ ctx.enrich({
+ "Dominio": domain,
+ "Acepta correo (MX)": "Sí" if mx_hosts else "No: el dominio no tiene servidores de correo",
+ "Servidores MX": mx_hosts,
+ "Proveedor de correo": provider,
+ "Tipo": "Desechable/temporal" if disposable else ("Proveedor gratuito" if free else "Dominio propio/corporativo"),
+ })
+ if not free and not disposable:
+ ctx.add("domain", domain, rel="dominio")
+ if len(local) >= 3:
+ ctx.add("username", local.split("+")[0], {"Origen": "Parte local del email"}, rel="posible usuario")
+
+
+@register
+class Gravatar(Module):
+ name = "gravatar"
+ title = "Gravatar"
+ description = "Perfil público asociado al email: nombre, foto, ubicación y cuentas verificadas."
+ inputs = ("email",)
+ sources = ("Gravatar",)
+
+ async def run(self, ctx):
+ email = ctx.value.strip().lower()
+ sha = hashlib.sha256(email.encode()).hexdigest()
+ md5 = hashlib.md5(email.encode()).hexdigest()
+ st, d = await ctx.get_json(f"https://api.gravatar.com/v3/profiles/{sha}")
+ if st == 200 and isinstance(d, dict) and d.get("profile_url"):
+ res = {
+ "platform": "Gravatar",
+ "user": d.get("display_name"),
+ "url": d["profile_url"],
+ "attrs": {
+ "Nombre": d.get("display_name"),
+ "Bio": d.get("description"),
+ "Puesto": d.get("job_title"),
+ "Empresa": d.get("company"),
+ "Pronombres": d.get("pronouns"),
+ "_avatar": d.get("avatar_url"),
+ },
+ "name": d.get("display_name"),
+ "location": d.get("location"),
+ "urls": [a.get("url") for a in d.get("verified_accounts") or []] + [l.get("url") for l in d.get("links") or []],
+ }
+ add_profile(ctx, res)
+ return
+ st, d = await ctx.get_json(f"https://en.gravatar.com/{md5}.json")
+ entry = ((d or {}).get("entry") or [None])[0] if isinstance(d, dict) else None
+ if st != 200 or not entry:
+ r = await ctx.http.get(f"https://gravatar.com/avatar/{md5}?d=404&s=200")
+ if r.status_code == 200:
+ ctx.enrich({"Gravatar": "Tiene foto de perfil", "_avatar": f"https://gravatar.com/avatar/{md5}?s=200"})
+ return
+ name = (entry.get("name") or {}).get("formatted") or entry.get("displayName")
+ add_profile(ctx, {
+ "platform": "Gravatar",
+ "user": entry.get("preferredUsername"),
+ "url": entry.get("profileUrl") or f"https://gravatar.com/{md5}",
+ "attrs": {"Nombre": name, "Bio": _txt(entry.get("aboutMe")), "_avatar": entry.get("thumbnailUrl")},
+ "name": name,
+ "location": entry.get("currentLocation"),
+ "urls": [a.get("url") for a in entry.get("accounts") or []] + [u.get("value") for u in entry.get("urls") or []],
+ })
+
+
+@register
+class XposedOrNot(Module):
+ name = "xposedornot"
+ title = "Filtraciones (XposedOrNot)"
+ description = "Comprueba si el email aparece en brechas de datos públicas y qué tipo de datos se filtraron."
+ inputs = ("email",)
+ sources = ("XposedOrNot",)
+
+ async def run(self, ctx):
+ st, d = await ctx.get_json(f"https://api.xposedornot.com/v1/breach-analytics?email={ctx.value}")
+ if st == 404 or not isinstance(d, dict):
+ return
+ exposed = d.get("ExposedBreaches") or {}
+ details = exposed.get("breaches_details") or []
+ for b in details:
+ ctx.add("breach", b.get("breach") or "Desconocida", {
+ "Fecha": b.get("xposed_date"),
+ "Datos expuestos": [x.strip() for x in (b.get("xposed_data") or "").split(";") if x.strip()],
+ "Registros": b.get("xposed_records"),
+ "Dominio": b.get("domain"),
+ "Sector": b.get("industry"),
+ "Riesgo contraseña": b.get("password_risk"),
+ "Descripción": b.get("details"),
+ "_avatar": b.get("logo"),
+ }, rel="aparece en", pivot=False)
+ metrics = d.get("BreachMetrics") or {}
+ risk = (metrics.get("risk") or [{}])[0] if isinstance(metrics.get("risk"), list) else {}
+ if details:
+ ctx.enrich({"Filtraciones": len(details), "Riesgo (XposedOrNot)": risk.get("risk_label")})
+
+
+# ---------------------------------------------------------------------------
+# ¿En qué servicios está registrado el email? Sólo endpoints que NO avisan al dueño
+# (nada de "recuperar contraseña"). Cada uno devuelve (existe: bool | None, extras).
+# ---------------------------------------------------------------------------
+
+
+async def c_twitter(http, em):
+ r = await http.get("https://api.twitter.com/i/users/email_available.json", params={"email": em})
+ d = r.json() if r.status_code == 200 else {}
+ return (bool(d["taken"]) if "taken" in d else None), {}
+
+
+async def c_wordpress(http, em):
+ r = await http.get(f"https://public-api.wordpress.com/rest/v1.1/users/{em}/auth-options", params={"http_envelope": 1})
+ d = r.json() if r.status_code == 200 else {}
+ err = (d.get("body") or {}).get("error")
+ if err == "unknown_user":
+ return False, {}
+ if d.get("code") in (200, 403):
+ return True, {}
+ return None, {}
+
+
+async def c_duolingo(http, em):
+ r = await http.get("https://www.duolingo.com/2017-06-30/users", params={"email": em})
+ if r.status_code != 200:
+ return None, {}
+ users = r.json().get("users") or []
+ if not users:
+ return False, {}
+ u = users[0]
+ return True, {"Usuario": u.get("username"), "Nombre": u.get("name")}
+
+
+async def c_chesscom(http, em):
+ r = await http.get("https://www.chess.com/callback/email/available", params={"email": em})
+ d = r.json() if r.status_code in (200, 226) else {}
+ return (not d["isEmailAvailable"] if "isEmailAvailable" in d else None), {}
+
+
+async def c_lastpass(http, em):
+ r = await http.get("https://lastpass.com/create_account.php",
+ params={"check": "avail", "skipcontent": 1, "mistype": 1, "username": em})
+ t = r.text.strip()
+ return ({"no": True, "ok": False}.get(t)), {}
+
+
+async def c_spotify(http, em):
+ r = await http.get("https://spclient.wg.spotify.com/signup/public/v1/account", params={"validate": 1, "email": em})
+ st = (r.json() if r.status_code == 200 else {}).get("status")
+ return ({20: True, 1: False}.get(st)), {}
+
+
+async def c_microsoft(http, em):
+ r = await http.post("https://login.microsoftonline.com/common/GetCredentialType", json={"Username": em})
+ d = r.json() if r.status_code == 200 else {}
+ if d.get("ThrottleStatus") == 1:
+ return None, {}
+ res = d.get("IfExistsResult")
+ if res in (0, 5, 6):
+ return True, {"Tipo": "Cuenta corporativa federada" if res in (5, 6) else "Cuenta Microsoft / Office 365"}
+ return (False if res == 1 else None), {}
+
+
+def _json(r):
+ try:
+ return r.json()
+ except ValueError:
+ return None
+
+
+async def c_adobe(http, em):
+ r = await http.post("https://auth.services.adobe.com/signin/v2/users/accounts",
+ headers={"X-IMS-ClientId": "adobedotcom2"}, json={"username": em})
+ d = _json(r)
+ if not isinstance(d, list):
+ return None, {}
+ if not d:
+ return False, {}
+ acc = d[0]
+ kinds = {"individual": "Personal", "enterprise": "Empresa", "federated": "Empresa (federada)"}
+ login = {"password": "contraseña", "google": "Google", "apple": "Apple", "facebook": "Facebook", "otp": "código por email"}
+ methods = [login.get(m.get("id"), m.get("id")) for m in acc.get("authenticationMethods") or [] if m.get("id")]
+ return True, {"Tipo": kinds.get(acc.get("type"), acc.get("type")),
+ "Inicio de sesión": ", ".join(methods) or None,
+ "Incluye": "Behance, Photoshop, Acrobat y demás servicios de Adobe"}
+
+
+async def c_freelancer(http, em):
+ r = await http.post("https://www.freelancer.com/api/users/0.1/users/check?compact=true&new_errors=true",
+ json={"user": {"email": em}})
+ return {409: True, 200: False}.get(r.status_code), {}
+
+
+async def c_snapchat(http, em):
+ r = await http.post("https://bitmoji.api.snapchat.com/api/user/find", data={"email": em})
+ if r.status_code == 204:
+ return False, {}
+ d = _json(r) if r.status_code == 200 else None
+ if not isinstance(d, dict) or "account_type" not in d:
+ return None, {}
+ return True, {"Tipo": "Snapchat con Bitmoji" if d["account_type"] == "bitmoji" else d["account_type"]}
+
+
+async def c_mewe(http, em):
+ r = await http.get("https://mewe.com/api/v2/auth/checkEmail", params={"email": em})
+ d = _json(r) if r.status_code == 200 else None
+ if not isinstance(d, dict):
+ return None, {}
+ if d.get("errorCode") == 109:
+ return True, {}
+ return (False if d.get("message") == "ok" else None), {}
+
+
+async def c_myfitnesspal(http, em):
+ r = await http.get("https://www.myfitnesspal.com/api/idm/user-exists", params={"email": em})
+ d = _json(r) if r.status_code == 200 else None
+ return (d.get("emailExists") if isinstance(d, dict) else None), {}
+
+
+async def c_plurk(http, em):
+ r = await http.post("https://www.plurk.com/Users/isEmailFound", data={"email": em})
+ return {"True": True, "False": False}.get(r.text.strip()), {}
+
+
+async def c_anydo(http, em):
+ r = await http.post("https://sm-prod2.any.do/check_email", json={"email": em})
+ d = _json(r) if r.status_code == 200 else None
+ return (d.get("user_exists") if isinstance(d, dict) else None), {}
+
+
+async def c_bandlab(http, em):
+ r = await http.get("https://www.bandlab.com/api/v1.3/validation/user", params={"email": em})
+ d = _json(r) if r.status_code == 200 else None
+ return ((not d["isAvailable"]) if isinstance(d, dict) and "isAvailable" in d else None), {}
+
+
+async def c_vrbo(http, em):
+ r = await http.post("https://www.vrbo.com/auth/aam/v3/status", json={"emailAddress": em, "country": "US"})
+ d = _json(r) if r.status_code == 200 else None
+ types = (d or {}).get("authType") if isinstance(d, dict) else None
+ if not types:
+ return None, {}
+ if types == ["SIGNUP"]:
+ return False, {}
+ login = {"LOGIN_UMS": "contraseña", "LOGIN_GOOGLE": "Google", "LOGIN_APPLE": "Apple", "LOGIN_FACEBOOK": "Facebook"}
+ return True, {"Inicio de sesión": ", ".join(login.get(t, t) for t in types),
+ "Incluye": "Cuenta compartida con Expedia y Hotels.com"}
+
+
+async def c_kahoot(http, em):
+ r = await http.get("https://create.kahoot.it/rest/users/emailavailable", params={"email": em})
+ d = _json(r) if r.status_code == 200 else None
+ return ((not d["isEmailAvailable"]) if isinstance(d, dict) and "isEmailAvailable" in d else None), {}
+
+
+async def c_disney(http, em):
+ base = "https://registerdisney.go.com/jgc/v8/client/ESPN-ONESITE.WEB-PROD"
+ r = await http.post(f"{base}/api-key?langPref=es-CL")
+ key = r.headers.get("api-key")
+ if not key:
+ return None, {}
+ r = await http.post(f"{base}/guest-flow?langPref=es-CL", json={"email": em}, headers={"Authorization": f"APIKEY {key}"})
+ flow = (((_json(r) or {}).get("data") or {}).get("guestFlow")) if r.status_code == 200 else None
+ found = {"LOGIN_FLOW": True, "REGISTRATION_FLOW": False}.get(flow)
+ return found, ({"Incluye": "Disney+, ESPN y demás servicios de Disney"} if found else {})
+
+
+async def c_deezer(http, em):
+ params = {"input": 3, "api_version": "1.0"}
+ r = await http.post("https://www.deezer.com/ajax/gw-light.php", params={**params, "method": "deezer.getUserData", "api_token": ""})
+ token = (((_json(r) or {}).get("results") or {}).get("checkForm"))
+ if not token:
+ return None, {}
+ r = await http.post("https://www.deezer.com/ajax/gw-light.php",
+ params={**params, "method": "deezer.emailCheck", "api_token": token}, json={"EMAIL": em})
+ res = (_json(r) or {}).get("results") or {}
+ return ((not res["availability"]) if "availability" in res else None), {}
+
+
+async def c_xvideos(http, em):
+ r = await http.get("https://www.xvideos.com/account/checkemail", params={"email": em})
+ d = _json(r) if r.status_code == 200 else None
+ if not isinstance(d, dict) or "result" not in d:
+ return None, {}
+ return (not d["result"]), {}
+
+
+EMAIL_CHECKS = {
+ "X/Twitter": c_twitter, "WordPress.com": c_wordpress, "Duolingo": c_duolingo, "Chess.com": c_chesscom,
+ "LastPass": c_lastpass, "Spotify": c_spotify, "Microsoft": c_microsoft,
+ "Adobe": c_adobe, "Snapchat": c_snapchat, "Disney": c_disney, "Deezer": c_deezer, "Vrbo / Expedia": c_vrbo,
+ "Freelancer": c_freelancer, "MyFitnessPal": c_myfitnesspal, "Kahoot!": c_kahoot, "BandLab": c_bandlab,
+ "Any.do": c_anydo, "MeWe": c_mewe, "Plurk": c_plurk,
+}
+ADULT_EMAIL_CHECKS = {"XVideos": c_xvideos}
+
+
+@register
+class EmailAccounts(Module):
+ name = "email_accounts"
+ title = "Servicios donde está registrado"
+ description = "Comprueba en qué servicios hay una cuenta con este email, sin enviar ningún aviso a su dueño."
+ inputs = ("email",)
+ sources = tuple(EMAIL_CHECKS)
+ timeout = 75
+
+ async def run(self, ctx):
+ email = ctx.value
+ fake = "zq" + "".join(random.choices(string.ascii_lowercase, k=12)) + "@" + email.split("@")[1]
+
+ async def safe(check, em):
+ try:
+ return await check(ctx.http, em)
+ except (httpx.HTTPError, ValueError, KeyError, TypeError, AttributeError):
+ return None, {}
+
+ checks = {**EMAIL_CHECKS, **(ADULT_EMAIL_CHECKS if settings.get("include_nsfw", False) else {})}
+ names = list(checks)
+ results = await asyncio.gather(*(safe(checks[n], email) for n in names))
+ controls = await asyncio.gather(*(safe(checks[n], fake) for n in names))
+ yes, no, unknown = [], [], []
+ for name, (exists, extra), (ctrl, _) in zip(names, results, controls):
+ if exists is None or (exists and ctrl):
+ unknown.append(name)
+ continue
+ if not exists:
+ no.append(name)
+ continue
+ yes.append(name)
+ attrs = {"Plataforma": name, "Registro": "Email registrado",
+ "Verificación": "Registro confirmado (contrastado con un email inventado)",
+ **{k: v for k, v in extra.items() if k not in ("Usuario",)}}
+ if extra.get("Usuario"):
+ attrs["Usuario"] = extra["Usuario"]
+ acc = ctx.add("account", f"{name} · {email}", attrs, rel="registrado en", pivot=False)
+ if extra.get("Usuario") and acc:
+ ctx.add("username", extra["Usuario"], rel=f"usuario en {name}", parent=acc)
+ ctx.enrich({"Registrado en": yes, "No registrado en": no})
+ ctx.message = (f"Registrado en {len(yes)}: {', '.join(yes) or '—'}"
+ + (f" · sin respuesta fiable: {', '.join(unknown)}" if unknown else ""))
+
+
+@register
+class HIBP(Module):
+ name = "hibp"
+ title = "Have I Been Pwned"
+ description = "Brechas en las que aparece el email según HIBP (requiere clave de pago)."
+ inputs = ("email",)
+ keys = ("hibp",)
+ sources = ("Have I Been Pwned",)
+
+ async def run(self, ctx):
+ r = await ctx.http.get(
+ f"https://haveibeenpwned.com/api/v3/breachedaccount/{ctx.value}?truncateResponse=false",
+ headers={"hibp-api-key": ctx.key("hibp"), "user-agent": "OsintHunter"},
+ )
+ if r.status_code == 404:
+ return
+ r.raise_for_status()
+ for b in r.json():
+ ctx.add("breach", b.get("Title") or b.get("Name"), {
+ "Fecha": b.get("BreachDate"),
+ "Datos expuestos": b.get("DataClasses"),
+ "Registros": b.get("PwnCount"),
+ "Dominio": b.get("Domain"),
+ "Descripción": _txt(b.get("Description")),
+ "_avatar": b.get("LogoPath"),
+ }, rel="aparece en", pivot=False)
+
+
+@register
+class HunterVerify(Module):
+ name = "hunter_verify"
+ title = "Hunter.io verificador"
+ description = "Comprueba si el buzón existe y cuántas fuentes web publican el email."
+ inputs = ("email",)
+ keys = ("hunter",)
+ sources = ("Hunter.io",)
+
+ async def run(self, ctx):
+ st, d = await ctx.get_json(
+ "https://api.hunter.io/v2/email-verifier", params={"email": ctx.value, "api_key": ctx.key("hunter")}
+ )
+ data = (d or {}).get("data") if isinstance(d, dict) else None
+ if st != 200 or not data:
+ ctx.message = f"Hunter respondió {st}"
+ return
+ ctx.enrich({
+ "Hunter: estado": data.get("status"),
+ "Hunter: puntuación": data.get("score"),
+ "Hunter: SMTP válido": data.get("smtp_check"),
+ "Hunter: acepta todo": data.get("accept_all"),
+ })
+ for s in data.get("sources") or []:
+ if s.get("uri"):
+ ctx.add("url", s["uri"], {"Visto": s.get("last_seen_on"), "_links": [["Abrir", s["uri"]]]},
+ rel="publicado en", pivot=False)
diff --git a/app/modules/enrich.py b/app/modules/enrich.py
new file mode 100644
index 0000000..48cfaaf
--- /dev/null
+++ b/app/modules/enrich.py
@@ -0,0 +1,310 @@
+"""Enriquecedores automáticos: se ejecutan solos sobre cada entidad nueva que encaje."""
+
+import asyncio
+import html
+import json
+import re
+import time
+from urllib.parse import urlparse
+
+import httpx
+
+from ..config import DATA_DIR
+from .base import Module, Skip, register
+
+DISCORD_INVITE = re.compile(r"^https?://(?:www\.)?(?:discord\.gg|discord(?:app)?\.com/invite)/([A-Za-z0-9\-]{2,32})/?$", re.I)
+DISCORD_EPOCH_MS = 1420070400000
+
+
+def snowflake_date(sid) -> str | None:
+ try:
+ return time.strftime("%Y-%m-%d", time.gmtime(((int(sid) >> 22) + DISCORD_EPOCH_MS) / 1000))
+ except (TypeError, ValueError):
+ return None
+
+
+@register
+class DiscordInvite(Module):
+ name = "discord_invite"
+ title = "Invitación de Discord"
+ description = "Servidor, número de miembros, fecha de creación y quién creó la invitación."
+ inputs = ("url",)
+ sources = ("API pública de Discord",)
+ auto = True
+
+ def applies(self, entity):
+ return entity["type"] == "url" and bool(DISCORD_INVITE.match(entity["value"]))
+
+ async def run(self, ctx):
+ code = DISCORD_INVITE.match(ctx.value).group(1)
+ st, d = await ctx.get_json(f"https://discord.com/api/v10/invites/{code}",
+ params={"with_counts": "true", "with_expiration": "true"})
+ if st == 404 or not isinstance(d, dict) or not d.get("guild"):
+ ctx.message = "Invitación caducada o inválida"
+ return
+ g = d["guild"]
+ icon = f"https://cdn.discordapp.com/icons/{g['id']}/{g['icon']}.png" if g.get("icon") else None
+ ctx.enrich({
+ "Servidor": g.get("name"),
+ "Miembros": d.get("approximate_member_count"),
+ "En línea": d.get("approximate_presence_count"),
+ "Caduca": (d.get("expires_at") or "")[:10] or "Nunca",
+ })
+ org = ctx.add("organization", f"Discord: {g.get('name')}", {
+ "ID del servidor": g["id"],
+ "Descripción": g.get("description"),
+ "Servidor creado": snowflake_date(g["id"]),
+ "Miembros": d.get("approximate_member_count"),
+ "URL personalizada": g.get("vanity_url_code"),
+ "_avatar": icon,
+ }, rel="servidor", pivot=False)
+ inv = d.get("inviter")
+ if inv and org:
+ avatar = f"https://cdn.discordapp.com/avatars/{inv['id']}/{inv['avatar']}.png" if inv.get("avatar") else None
+ acc = ctx.add("account", f"https://discord.com/users/{inv['id']}", {
+ "Plataforma": "Discord", "Usuario": inv.get("username"), "Nombre visible": inv.get("global_name"),
+ "ID": inv["id"], "Creada": snowflake_date(inv["id"]), "Verificación": "Creó la invitación",
+ "_avatar": avatar, "_links": [["Perfil", f"https://discord.com/users/{inv['id']}"]],
+ }, rel="invitación creada por", pivot=False)
+ if acc and inv.get("username"):
+ ctx.add("username", inv["username"], rel="usuario", parent=acc, pivot=False)
+
+
+_geo_lock = asyncio.Lock()
+_geo_last = 0.0
+_GEO_CACHE = DATA_DIR / "geocache.json"
+_COORDS = re.compile(r"^\s*(-?\d{1,2}(?:\.\d+)?)\s*,\s*(-?\d{1,3}(?:\.\d+)?)\s*$")
+
+
+def _load_cache() -> dict:
+ try:
+ return json.loads(_GEO_CACHE.read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ return {}
+
+
+@register
+class Geocode(Module):
+ name = "geocode"
+ title = "Geolocalizar ubicación"
+ description = "Convierte el texto de una ubicación en coordenadas para mostrarla en el mapa."
+ inputs = ("location",)
+ sources = ("OpenStreetMap Nominatim",)
+ timeout = 180
+ auto = True
+
+ def applies(self, entity):
+ return entity["type"] == "location" and entity["attrs"].get("_lat") is None
+
+ async def run(self, ctx):
+ global _geo_last
+ q = " ".join(ctx.value.split())
+ m = _COORDS.match(q)
+ if m:
+ lat, lon = float(m.group(1)), float(m.group(2))
+ ctx.enrich({"_lat": lat, "_lon": lon})
+ return
+ if len(q) < 2:
+ return
+ key = q.lower()
+ cache = _load_cache()
+ if key not in cache:
+ async with _geo_lock:
+ # Política de uso de Nominatim: como máximo una petición por segundo.
+ wait = 1.1 - (time.time() - _geo_last)
+ if wait > 0:
+ await asyncio.sleep(wait)
+ st, d = await ctx.get_json(
+ "https://nominatim.openstreetmap.org/search",
+ params={"q": q, "format": "json", "limit": 1, "accept-language": "es"},
+ headers={"User-Agent": "OsintHunter/1.0 (herramienta OSINT local)"},
+ )
+ _geo_last = time.time()
+ if st != 200 or not isinstance(d, list):
+ ctx.message = f"Nominatim respondió {st}"
+ return
+ cache = _load_cache()
+ cache[key] = d[0] if d else None
+ _GEO_CACHE.write_text(json.dumps(cache, ensure_ascii=False), encoding="utf-8")
+ hit = cache.get(key)
+ if not hit:
+ ctx.message = "No se encontró en el mapa"
+ return
+ lat, lon = float(hit["lat"]), float(hit["lon"])
+ ctx.enrich({
+ "_lat": lat, "_lon": lon,
+ "Lugar (OpenStreetMap)": hit.get("display_name"),
+ "_links": [["Ver en mapa", f"https://www.openstreetmap.org/?mlat={lat}&mlon={lon}#map=10/{lat}/{lon}"]],
+ })
+
+
+# Flickr sólo deja consultar fotos públicas sin clave a través del feed, y el feed pide el ID interno (NSID)
+FLICKR_NSID = re.compile(r"(?:flickr\.com/(?:photos|people)/)?(\d{5,12}@N\d{2})\b", re.I)
+
+
+@register
+class FlickrGeo(Module):
+ name = "flickr_geo"
+ title = "Flickr: fotos con ubicación"
+ description = ("Lee las últimas fotos públicas de un usuario de Flickr (por su ID tipo 12345678@N04) y "
+ "pone en el mapa las que guardan coordenadas GPS")
+ inputs = ("url", "username")
+ sources = ("Feed público de Flickr",)
+ auto = True
+
+ def applies(self, entity):
+ return entity["type"] in self.inputs and bool(FLICKR_NSID.search(entity["value"]))
+
+ async def run(self, ctx):
+ nsid = FLICKR_NSID.search(ctx.value).group(1).upper()
+ r = await ctx.http.get("https://www.flickr.com/services/feeds/photos_public.gne",
+ params={"id": nsid, "format": "rss2", "georss": "1"}, timeout=30)
+ if r.status_code != 200 or "<item>" not in r.text:
+ ctx.message = "Sin fotos públicas o el usuario no existe"
+ return
+ xml = r.text
+ owner = re.search(r"<title>Uploads from ([^<]+)</title>", xml)
+ items = re.findall(r"<item>(.*?)</item>", xml, re.S)
+ clusters: dict[tuple[float, float], dict] = {}
+ taken = []
+ for it in items:
+ date = re.search(r"<dc:date\.Taken>([^<]+)", it)
+ if date:
+ taken.append(date.group(1)[:10])
+ pt = re.search(r"<georss:point>\s*([-\d.]+)\s+([-\d.]+)", it)
+ if not pt:
+ continue
+ lat, lon = float(pt.group(1)), float(pt.group(2))
+ key = (round(lat, 2), round(lon, 2))
+ c = clusters.setdefault(key, {"n": 0, "lat": lat, "lon": lon, "dates": [], "links": []})
+ c["n"] += 1
+ link = re.search(r"<link>([^<]+)</link>", it)
+ title = re.search(r"<title>([^<]*)</title>", it)
+ if link:
+ c["links"].append([f"Foto: {(title.group(1) if title else '')[:50] or 'sin título'}", link.group(1)])
+ if date:
+ c["dates"].append(date.group(1)[:10])
+ url = f"https://www.flickr.com/photos/{nsid}/"
+ acc = ctx.add("account", url, {
+ "Plataforma": "Flickr", "Usuario": nsid, "Nombre visible": owner.group(1).strip() if owner else None,
+ "Fotos públicas recientes": len(items), "Fotos con GPS": sum(c["n"] for c in clusters.values()),
+ "Primera foto reciente": min(taken) if taken else None, "Última foto": max(taken) if taken else None,
+ "_links": [["Abrir perfil", url]],
+ }, rel="cuenta", pivot=False)
+ for c in sorted(clusters.values(), key=lambda c: -c["n"])[:15]:
+ ctx.add("location", f"{c['lat']:.4f}, {c['lon']:.4f}", {
+ "_lat": c["lat"], "_lon": c["lon"], "Fotos tomadas aquí": c["n"],
+ "Fechas": sorted(set(c["dates"]))[:10] or None, "_links": c["links"][:5],
+ }, rel="foto tomada en", parent=acc)
+ ctx.message = f"{len(items)} fotos recientes · {len(clusters)} lugares con GPS"
+
+
+# ---------------------------------------------------------------- perfil público de cuentas sin datos
+
+META_TAG = re.compile(r"<meta\b[^>]*>", re.I)
+META_KEY = re.compile(r'(?:property|name)\s*=\s*["\']((?:og|twitter):(?:title|description|image))["\']', re.I)
+META_VAL = re.compile(r'content\s*=\s*"([^"]*)"|content\s*=\s*\'([^\']*)\'', re.I)
+TITLE_TAG = re.compile(r"<title[^>]*>(.*?)</title>", re.S | re.I)
+WALL_TITLES = re.compile(r"just a moment|client challenge|attention required|access denied|captcha|log ?in|sign ?in|sign ?up|"
+ r"iniciar sesi[oó]n|reg[ií]strate|not found|no encontrad|page not|404|error", re.I)
+GENERIC_IMAGE = re.compile(r"default|placeholder|logo|/static/|og[-_]?image|web-capture|share|banner|-og-|_og_|"
+ r"opengraph|social[-_]?(?:card|preview)|favicon|sprite|brand", re.I)
+GENERIC_WORDS = re.compile(r"\b(live|stream|profile|perfil|photos|videos|watch|home|official|user|usuario|page|"
+ r"p[aá]gina|account|cuenta|channel|canal|games?)\b", re.I)
+NO_PAGE_PLATFORMS = {"Facebook", "LinkedIn", "Instagram", "TikTok", "X/Twitter", "Pinterest"}
+_home_cache: dict[str, dict] = {}
+
+
+def page_meta(page: str) -> dict:
+ out: dict[str, str] = {}
+ for tag in META_TAG.findall(page[:500_000]):
+ k, v = META_KEY.search(tag), META_VAL.search(tag)
+ if k and v and k.group(1).lower() not in out:
+ out[k.group(1).lower()] = html.unescape(v.group(1) or v.group(2) or "").strip()
+ t = TITLE_TAG.search(page[:500_000])
+ out["title"] = html.unescape(re.sub(r"\s+", " ", t.group(1))).strip() if t else ""
+ return out
+
+
+async def _home(http, url: str) -> dict:
+ """Metadatos de la portada del sitio: lo que se repite ahí es genérico, no del perfil."""
+ p = urlparse(url)
+ host = f"{p.scheme}://{p.netloc}/"
+ if host not in _home_cache:
+ try:
+ r = await http.get(host, timeout=12)
+ _home_cache[host] = page_meta(r.text) if r.status_code == 200 else {}
+ except httpx.HTTPError:
+ _home_cache[host] = {}
+ return _home_cache[host]
+
+
+def name_from_title(title: str, user: str, platform: str, host: str) -> str | None:
+ """Nombre visible a partir del título de la página («Ana (@anita_r) | Snapchat» → «Ana»)."""
+ if not title or WALL_TITLES.search(title):
+ return None
+ u = user.lower()
+ site = {platform.lower(), host.split(".")[-2] if host.count(".") else host}
+ m = re.match(r"^(.*?)\s*\(@?([\w.\-]+)\)", title)
+ if m and m.group(2).lower() == u:
+ cand = m.group(1)
+ else:
+ parts = [p for p in re.split(r"\s+[|\-–—·•:]\s+", title) if p.strip()]
+ cand = next((p for p in parts if not any(s and s in p.lower() for s in site)), "")
+ cand = re.sub(r"\s+(?:en|on|at|auf|sur|na|no)\s+\S+$", "", cand.strip())
+ cand = re.sub(r"(?i)^(?:perfil de|profile of|perfil|profile)\s+|['’]s?\s+(?:profile|page)$", "", cand).strip(" -|·•")
+ if (not cand or len(cand) > 60 or u in cand.lower() or not re.search(r"[^\W\d_]", cand)
+ or GENERIC_WORDS.search(cand) or any(s and s in cand.lower() for s in site)):
+ return None
+ return cand
+
+
+@register
+class AccountPage(Module):
+ name = "account_page"
+ title = "Leer el perfil público"
+ description = ("Abre la página de la cuenta y saca el nombre visible, la foto y la descripción que muestra a cualquiera. "
+ "Sirve para las cuentas de las que sólo se sabía que existen: con eso se pueden puntuar y comparar.")
+ inputs = ("account",)
+ sources = ("Página pública del perfil",)
+ timeout = 40
+ auto = True
+
+ def applies(self, entity: dict) -> bool:
+ a = entity.get("attrs") or {}
+ return (entity["type"] == "account" and a.get("Plataforma") not in NO_PAGE_PLATFORMS
+ and not any(a.get(k) for k in ("Nombre", "Nombre visible", "Nombre real", "_avatar")))
+
+ async def run(self, ctx):
+ url = ctx.value if ctx.value.startswith("http") else None
+ if not url:
+ raise Skip("La cuenta no tiene una URL que abrir")
+ a = ctx.entity.get("attrs") or {}
+ user, platform = str(a.get("Usuario") or ""), str(a.get("Plataforma") or "")
+ r = await ctx.http.get(url, timeout=15)
+ if r.status_code in (404, 410):
+ ctx.enrich({"Página del perfil": "No existe (error 404): puede ser un falso positivo"})
+ ctx.message = "La página del perfil no existe"
+ return
+ meta = page_meta(r.text)
+ if r.status_code != 200 or WALL_TITLES.search(meta["title"]) and not meta.get("og:title"):
+ raise Skip(f"La página no deja leer el perfil sin navegador (respuesta {r.status_code})")
+ home = await _home(ctx.http, url)
+ host = (urlparse(str(r.url)).hostname or "").removeprefix("www.")
+ same = lambda k: meta.get(k) and meta.get(k) == home.get(k) # noqa: E731
+ name = None
+ for t in (meta["title"], meta.get("og:title"), meta.get("twitter:title")):
+ if t and t != home.get("title") and t != home.get("og:title"):
+ name = name_from_title(t, user, platform, host)
+ if name:
+ break
+ img = meta.get("og:image") or meta.get("twitter:image")
+ if img and (same("og:image") or GENERIC_IMAGE.search(img) or not img.startswith("http")):
+ img = None
+ desc = meta.get("og:description") or ""
+ if same("og:description") or platform.lower() in desc.lower() or (user and user.lower() in desc.lower()
+ and len(desc) < 160):
+ desc = ""
+ ctx.enrich({"Nombre visible": name, "Descripción": desc[:400] or None, "_avatar": img})
+ got = [x for x, v in (("nombre", name), ("foto", img), ("descripción", desc)) if v]
+ ctx.message = ("Leído: " + ", ".join(got)) if got else "La página no muestra nombre ni foto"
diff --git a/app/modules/ip.py b/app/modules/ip.py
new file mode 100644
index 0000000..8359054
--- /dev/null
+++ b/app/modules/ip.py
@@ -0,0 +1,168 @@
+from ..util import reverse_dns
+from .base import Module, Skip, register
+from .domain import is_public_ip
+
+
+def _public(ctx):
+ if not is_public_ip(ctx.value):
+ raise Skip("IP privada o reservada: no hay datos públicos")
+
+
+@register
+class IpGeo(Module):
+ name = "ip_geo"
+ title = "Geolocalización e ISP"
+ description = "País, ciudad, coordenadas aproximadas, ASN, ISP y si es proxy/VPN/hosting."
+ inputs = ("ip",)
+ sources = ("ipwho.is", "ip-api.com")
+
+ async def run(self, ctx):
+ _public(ctx)
+ st, d = await ctx.get_json(f"https://ipwho.is/{ctx.value}")
+ if st == 200 and isinstance(d, dict) and d.get("success"):
+ conn = d.get("connection") or {}
+ geo = {"country": d.get("country"), "region": d.get("region"), "city": d.get("city"),
+ "lat": d.get("latitude"), "lon": d.get("longitude"), "asn": conn.get("asn"),
+ "org": conn.get("org") or conn.get("isp"), "isp": conn.get("isp"), "tz": (d.get("timezone") or {}).get("id")}
+ else:
+ st, d = await ctx.get_json(
+ f"http://ip-api.com/json/{ctx.value}?fields=status,country,regionName,city,lat,lon,timezone,isp,org,as,proxy,hosting,mobile"
+ )
+ if not isinstance(d, dict) or d.get("status") != "success":
+ return
+ asn = (d.get("as") or "").split(" ")[0].lstrip("AS")
+ geo = {"country": d.get("country"), "region": d.get("regionName"), "city": d.get("city"), "lat": d.get("lat"),
+ "lon": d.get("lon"), "asn": int(asn) if asn.isdigit() else None, "org": d.get("org"), "isp": d.get("isp"),
+ "tz": d.get("timezone"), "proxy": d.get("proxy"), "hosting": d.get("hosting"), "mobile": d.get("mobile")}
+ ctx.enrich({
+ "País": geo["country"], "Región": geo["region"], "Ciudad": geo["city"], "ISP": geo["isp"],
+ "Zona horaria": geo["tz"],
+ "Proxy/VPN": "Sí" if geo.get("proxy") else None,
+ "Hosting/centro de datos": "Sí" if geo.get("hosting") else None,
+ "Red móvil": "Sí" if geo.get("mobile") else None,
+ })
+ loc = ", ".join(x for x in (geo["city"], geo["region"], geo["country"]) if x)
+ if loc:
+ ctx.add("location", loc, {"_lat": geo["lat"], "_lon": geo["lon"], "Precisión": "Aproximada (ciudad)",
+ "_links": [["Ver en mapa", f"https://www.openstreetmap.org/?mlat={geo['lat']}&mlon={geo['lon']}#map=11/{geo['lat']}/{geo['lon']}"]]},
+ rel="geolocalizada en", pivot=False)
+ if geo["asn"]:
+ ctx.add("asn", f"AS{geo['asn']}", {"Organización": geo["org"],
+ "_links": [["bgp.he.net", f"https://bgp.he.net/AS{geo['asn']}"]]},
+ rel="red", pivot=False)
+
+
+@register
+class InternetDB(Module):
+ name = "internetdb"
+ title = "Puertos y vulnerabilidades (InternetDB)"
+ description = "Puertos abiertos, software, CVEs y nombres de host según el escaneo pasivo gratuito de Shodan."
+ inputs = ("ip",)
+ sources = ("Shodan InternetDB",)
+
+ async def run(self, ctx):
+ _public(ctx)
+ st, d = await ctx.get_json(f"https://internetdb.shodan.io/{ctx.value}")
+ if st != 200 or not isinstance(d, dict):
+ return
+ ctx.enrich({
+ "Puertos abiertos": d.get("ports"),
+ "Software (CPE)": d.get("cpes"),
+ "Etiquetas": d.get("tags"),
+ "Vulnerabilidades (CVE)": d.get("vulns"),
+ })
+ for h in (d.get("hostnames") or [])[:30]:
+ ctx.add("domain", h, rel="nombre de host", pivot=False)
+
+
+@register
+class ReverseDns(Module):
+ name = "reverse_dns"
+ title = "DNS inverso"
+ description = "Nombre de host asociado a la IP (registro PTR)."
+ inputs = ("ip",)
+ sources = ("DNS",)
+
+ async def run(self, ctx):
+ for h in await reverse_dns(ctx.value):
+ ctx.add("domain", h, {"Rol": "PTR"}, rel="DNS inverso", pivot=False)
+
+
+@register
+class ShodanHost(Module):
+ name = "shodan_host"
+ title = "Shodan"
+ description = "Servicios, banners, organización y sistema operativo vistos por Shodan."
+ inputs = ("ip",)
+ keys = ("shodan",)
+ sources = ("Shodan",)
+
+ async def run(self, ctx):
+ _public(ctx)
+ st, d = await ctx.get_json(f"https://api.shodan.io/shodan/host/{ctx.value}", params={"key": ctx.key("shodan")})
+ if st == 404:
+ return
+ if st != 200 or not isinstance(d, dict):
+ ctx.message = (d or {}).get("error", f"Shodan respondió {st}") if isinstance(d, dict) else f"Shodan respondió {st}"
+ return
+ services = [f"{s.get('port')}/{s.get('transport')} {s.get('product') or ''} {s.get('version') or ''}".strip()
+ for s in d.get("data") or []]
+ ctx.enrich({"Shodan: organización": d.get("org"), "Shodan: SO": d.get("os"), "Shodan: servicios": services,
+ "Shodan: última vez": (d.get("last_update") or "")[:10],
+ "_links": [["Shodan", f"https://www.shodan.io/host/{ctx.value}"]]})
+ for dom in d.get("domains") or []:
+ ctx.add("domain", dom, rel="dominio (Shodan)", pivot=False)
+
+
+@register
+class AbuseIPDB(Module):
+ name = "abuseipdb"
+ title = "AbuseIPDB"
+ description = "Reportes de abuso (spam, ataques, escaneos) y puntuación de confianza."
+ inputs = ("ip",)
+ keys = ("abuseipdb",)
+ sources = ("AbuseIPDB",)
+
+ async def run(self, ctx):
+ _public(ctx)
+ st, d = await ctx.get_json(
+ "https://api.abuseipdb.com/api/v2/check",
+ params={"ipAddress": ctx.value, "maxAgeInDays": 365},
+ headers={"Key": ctx.key("abuseipdb"), "Accept": "application/json"},
+ )
+ data = (d or {}).get("data") if isinstance(d, dict) else None
+ if not data:
+ ctx.message = f"AbuseIPDB respondió {st}"
+ return
+ ctx.enrich({
+ "AbuseIPDB: puntuación": f"{data.get('abuseConfidenceScore')}%",
+ "AbuseIPDB: reportes (1 año)": data.get("totalReports"),
+ "AbuseIPDB: uso": data.get("usageType"),
+ "AbuseIPDB: último reporte": (data.get("lastReportedAt") or "")[:10] or None,
+ "Nodo Tor": "Sí" if data.get("isTor") else None,
+ })
+
+
+@register
+class GreyNoise(Module):
+ name = "greynoise"
+ title = "GreyNoise"
+ description = "Indica si la IP escanea Internet de forma masiva o pertenece a un servicio conocido."
+ inputs = ("ip",)
+ optional_keys = ("greynoise",)
+ sources = ("GreyNoise Community",)
+
+ async def run(self, ctx):
+ _public(ctx)
+ headers = {"key": ctx.key("greynoise")} if ctx.key("greynoise") else {}
+ st, d = await ctx.get_json(f"https://api.greynoise.io/v3/community/{ctx.value}", headers=headers)
+ if st == 429:
+ raise Skip("Límite de GreyNoise alcanzado; añade una clave gratuita en Ajustes")
+ if st not in (200, 404) or not isinstance(d, dict) or "noise" not in d:
+ return
+ ctx.enrich({
+ "GreyNoise: escáner masivo": "Sí" if d.get("noise") else "No",
+ "GreyNoise: servicio conocido": d.get("name") if d.get("riot") else None,
+ "GreyNoise: clasificación": d.get("classification"),
+ "GreyNoise: visto": d.get("last_seen"),
+ })
diff --git a/app/modules/misc.py b/app/modules/misc.py
new file mode 100644
index 0000000..b60c972
--- /dev/null
+++ b/app/modules/misc.py
@@ -0,0 +1,446 @@
+import re
+import time
+import unicodedata
+from urllib.parse import quote_plus
+
+from ..config import settings
+from ..db import db
+from ..models import CRYPTO_NAMES, crypto_chain
+from .base import Module, register
+from .people import name_variants
+
+# ---------------------------------------------------------------------------
+# Hashes
+# ---------------------------------------------------------------------------
+
+HASH_TYPES = {
+ 32: ["MD5", "NTLM", "MD4"],
+ 40: ["SHA-1", "RIPEMD-160"],
+ 56: ["SHA-224", "SHA3-224"],
+ 64: ["SHA-256", "SHA3-256", "BLAKE2s"],
+ 96: ["SHA-384", "SHA3-384"],
+ 128: ["SHA-512", "SHA3-512", "BLAKE2b", "Whirlpool"],
+}
+
+
+@register
+class HashIdentify(Module):
+ name = "hash_identify"
+ title = "Identificar hash"
+ description = "Algoritmos posibles según la longitud y enlaces para buscarlo."
+ inputs = ("hash",)
+ sources = ("Local",)
+
+ async def run(self, ctx):
+ h = ctx.value
+ ctx.enrich({
+ "Algoritmos posibles": HASH_TYPES.get(len(h), ["Desconocido"]),
+ "_links": [
+ ["Buscar en Google", f'https://www.google.com/search?q="{h}"'],
+ ["VirusTotal", f"https://www.virustotal.com/gui/search/{h}"],
+ ["MalwareBazaar", f"https://bazaar.abuse.ch/browse.php?search=sha256%3A{h}"],
+ ["Hashes.com (contraseñas)", f"https://hashes.com/en/decrypt/hash"],
+ ],
+ })
+
+
+@register
+class MalwareBazaar(Module):
+ name = "malwarebazaar"
+ title = "MalwareBazaar"
+ description = "Busca el hash en la base de muestras de malware de abuse.ch."
+ inputs = ("hash",)
+ keys = ("abusech",)
+ sources = ("MalwareBazaar",)
+
+ async def run(self, ctx):
+ r = await ctx.http.post("https://mb-api.abuse.ch/api/v1/", data={"query": "get_info", "hash": ctx.value},
+ headers={"Auth-Key": ctx.key("abusech")})
+ d = r.json() if r.status_code == 200 else {}
+ if d.get("query_status") != "ok" or not d.get("data"):
+ return
+ s = d["data"][0]
+ ctx.enrich({
+ "Malware: familia": s.get("signature"),
+ "Malware: archivo": s.get("file_name"),
+ "Malware: tipo": s.get("file_type"),
+ "Malware: visto": s.get("first_seen"),
+ "Malware: etiquetas": s.get("tags"),
+ "_links": [["MalwareBazaar", f"https://bazaar.abuse.ch/sample/{s.get('sha256_hash')}/"]],
+ })
+
+
+# ---------------------------------------------------------------------------
+# Criptomonedas
+# ---------------------------------------------------------------------------
+
+EXPLORERS = {
+ "btc": "https://mempool.space/address/{}",
+ "eth": "https://etherscan.io/address/{}",
+ "ltc": "https://blockchair.com/litecoin/address/{}",
+ "doge": "https://blockchair.com/dogecoin/address/{}",
+ "trx": "https://tronscan.org/#/address/{}",
+}
+
+
+@register
+class CryptoWallet(Module):
+ name = "crypto_wallet"
+ title = "Cartera de criptomonedas"
+ description = "Saldo, número de transacciones, fechas y principales contrapartes de una dirección."
+ inputs = ("crypto",)
+ sources = ("mempool.space", "Ethplorer", "Blockchair")
+
+ async def run(self, ctx):
+ a = ctx.value
+ chain = crypto_chain(a)
+ links = [["Explorador", EXPLORERS[chain].format(a)]] if chain else []
+ ctx.enrich({"Red": CRYPTO_NAMES.get(chain, "Desconocida"), "_links": links})
+ if chain == "btc":
+ await self._btc(ctx, a)
+ elif chain == "eth":
+ await self._eth(ctx, a)
+ elif chain in ("ltc", "doge"):
+ await self._blockchair(ctx, a, {"ltc": "litecoin", "doge": "dogecoin"}[chain], 1e8)
+
+ async def _btc(self, ctx, a):
+ st, d = await ctx.get_json(f"https://mempool.space/api/address/{a}")
+ if st != 200 or not isinstance(d, dict):
+ return
+ cs = d.get("chain_stats") or {}
+ bal = (cs.get("funded_txo_sum", 0) - cs.get("spent_txo_sum", 0)) / 1e8
+ ctx.enrich({"Saldo": f"{bal:.8f} BTC", "Recibido total": f"{cs.get('funded_txo_sum', 0) / 1e8:.8f} BTC",
+ "Transacciones": cs.get("tx_count")})
+ if not cs.get("tx_count"):
+ return
+ st, txs = await ctx.get_json(f"https://mempool.space/api/address/{a}/txs")
+ if st != 200 or not isinstance(txs, list):
+ return
+ times = [t["status"]["block_time"] for t in txs if (t.get("status") or {}).get("block_time")]
+ counter: dict[str, int] = {}
+ for t in txs:
+ addrs = {(v.get("prevout") or {}).get("scriptpubkey_address") for v in t.get("vin") or []}
+ addrs |= {v.get("scriptpubkey_address") for v in t.get("vout") or []}
+ for x in addrs:
+ if x and x != a:
+ counter[x] = counter.get(x, 0) + 1
+ if times:
+ ctx.enrich({"Última actividad (muestra)": time.strftime("%Y-%m-%d", time.gmtime(max(times)))})
+ for x, n in sorted(counter.items(), key=lambda kv: -kv[1])[:8]:
+ ctx.add("crypto", x, {"Red": "Bitcoin", "Transacciones en común (muestra)": n,
+ "_links": [["Explorador", EXPLORERS["btc"].format(x)]]},
+ rel=f"contraparte ×{n}", pivot=False)
+
+ async def _eth(self, ctx, a):
+ st, d = await ctx.get_json(f"https://api.ethplorer.io/getAddressInfo/{a}?apiKey=freekey")
+ if st != 200 or not isinstance(d, dict) or d.get("error"):
+ return
+ tokens = [f"{(t.get('tokenInfo') or {}).get('symbol') or '?'}" for t in d.get("tokens") or []]
+ ctx.enrich({
+ "Saldo": f"{(d.get('ETH') or {}).get('balance', 0):.6f} ETH",
+ "Transacciones": d.get("countTxs"),
+ "Tokens": tokens[:40] or None,
+ "Es contrato": "Sí" if d.get("contractInfo") else None,
+ })
+
+ async def _blockchair(self, ctx, a, chain, unit):
+ st, d = await ctx.get_json(f"https://api.blockchair.com/{chain}/dashboards/address/{a}")
+ data = ((d or {}).get("data") or {}).get(a) if isinstance(d, dict) else None
+ if st != 200 or not data:
+ return
+ ad = data.get("address") or {}
+ sym = chain[:4].upper() if chain != "litecoin" else "LTC"
+ ctx.enrich({
+ "Saldo": f"{(ad.get('balance') or 0) / unit:.8f} {sym}",
+ "Recibido total": f"{(ad.get('received') or 0) / unit:.8f} {sym}",
+ "Transacciones": ad.get("transaction_count"),
+ "Primera actividad": (ad.get("first_seen_receiving") or "")[:10] or None,
+ "Última actividad": (ad.get("last_seen_receiving") or "")[:10] or None,
+ })
+
+
+# ---------------------------------------------------------------------------
+# Personas y dorks
+# ---------------------------------------------------------------------------
+
+def _ascii(s: str) -> str:
+ return unicodedata.normalize("NFKD", s).encode("ascii", "ignore").decode().lower()
+
+
+def username_candidates(full_name: str) -> list[str]:
+ parts = [re.sub(r"[^a-z0-9]", "", _ascii(p)) for p in full_name.split()]
+ parts = [p for p in parts if p]
+ if len(parts) < 2:
+ return parts
+ f = parts[0]
+ # En nombres hispanos de 4 partes el apellido principal es el penúltimo;
+ # con 3 partes puede ser segundo nombre o dos apellidos, así que se prueban ambos.
+ if len(parts) >= 4:
+ surnames = [parts[-2], parts[-1]]
+ elif len(parts) == 3:
+ surnames = [parts[-1], parts[1]]
+ else:
+ surnames = [parts[-1]]
+ c = []
+ for l in surnames:
+ c += [f + l, f + "." + l, f + "_" + l, f[0] + l, f[0] + "." + l, f + l[0], l + f, l + "." + f, l + f[0], f + "-" + l]
+ if len(parts) >= 3:
+ s1, s2 = parts[-2], parts[-1]
+ c += [f + s1 + s2, f[0] + s1 + s2, f + s1[0] + s2[0], f[0] + s1 + s2[0], f + s1 + s2[0]]
+ if len(parts) >= 4:
+ m, s1, s2 = parts[1], parts[-2], parts[-1]
+ c += [f[0] + m[0] + s1, f + m + s1, f[0] + m[0] + s1 + s2[0]]
+ return list(dict.fromkeys(c))
+
+
+@register
+class PersonSearch(Module):
+ name = "person_search"
+ title = "Persona: usuarios probables"
+ description = "Genera los nombres de usuario más probables a partir del nombre para investigarlos con un clic."
+ inputs = ("person",)
+ sources = ("Local",)
+
+ async def run(self, ctx):
+ ctx.enrich({"_candidatos": username_candidates(ctx.value)})
+
+
+def _g(q: str) -> str:
+ return f"https://www.google.com/search?q={quote_plus(q)}"
+
+
+PASTE_SITES = " OR ".join(f"site:{s}" for s in (
+ "pastebin.com", "rentry.co", "justpaste.it", "controlc.com", "paste.ee", "ghostbin.co", "dpaste.org",
+ "throwbin.io", "pastes.io", "hastebin.com", "privatebin.net",
+))
+
+
+def _sites(*sites: str) -> str:
+ return " OR ".join(f"site:{s}" for s in sites)
+
+
+def _bing(q: str) -> str:
+ return f"https://www.bing.com/search?q={quote_plus(q)}"
+
+
+def _yandex(q: str) -> str:
+ return f"https://yandex.com/search/?text={quote_plus(q)}"
+
+
+def _ddg(q: str) -> str:
+ return f"https://duckduckgo.com/?q={quote_plus(q)}"
+
+
+CLOUD_SITES = _sites("drive.google.com", "docs.google.com", "1drv.ms", "onedrive.live.com", "dropbox.com",
+ "s3.amazonaws.com", "blob.core.windows.net", "storage.googleapis.com", "notion.site", "trello.com")
+INTERNAL_SITES = _sites("atlassian.net", "postman.com", "swaggerhub.com", "app.swaggerhub.com", "readme.io",
+ "gitbook.io", "airtable.com", "miro.com", "figma.com")
+DOC_SITES = _sites("scribd.com", "issuu.com", "slideshare.net", "calameo.com", "academia.edu", "researchgate.net",
+ "yumpu.com", "studocu.com")
+CV_SITES = _sites("linkedin.com/in", "computrabajo.com", "laborum.cl", "bumeran.com.ar", "zonajobs.com.ar",
+ "trabajando.com", "indeed.com", "about.me")
+
+# registros oficiales por país (código ISO del ajuste «país por defecto»)
+REGIONAL = {
+ "CL": [
+ ["Chile · Diario Oficial", _sites("diariooficial.interior.gob.cl")],
+ ["Chile · Mercado Público (licitaciones)", _sites("mercadopublico.cl")],
+ ["Chile · Poder Judicial y causas", _sites("pjud.cl", "tribunalconstitucional.cl")],
+ ["Chile · Transparencia (plantas y sueldos públicos)", _sites("portaltransparencia.cl", "transparencia.cl", "gob.cl") + " (planta OR contrata OR honorarios)"],
+ ["Chile · Empresas y sociedades", _sites("tuempresaenundia.cl", "registrodeempresasysociedades.cl", "genealog.cl")],
+ ["Chile · Congreso y Contraloría", _sites("bcn.cl", "camara.cl", "senado.cl", "contraloria.cl")],
+ ],
+ "AR": [
+ ["Argentina · Boletín Oficial", _sites("boletinoficial.gob.ar")],
+ ["Argentina · Compras públicas", _sites("comprar.gob.ar", "contrataciones.gob.ar")],
+ ["Argentina · Poder Judicial", _sites("pjn.gov.ar", "csjn.gov.ar", "cij.gov.ar")],
+ ["Argentina · Organismos públicos", _sites("argentina.gob.ar", "gob.ar")],
+ ["Argentina · Boletines provinciales", _sites("boletinoficial.gba.gob.ar", "boletinoficial.cba.gov.ar", "boletinoficial.buenosaires.gob.ar")],
+ ],
+ "ES": [
+ ["España · BOE y boletines", _sites("boe.es", "borme.es")],
+ ["España · Empresas (BORME)", _sites("librebor.me", "infoempresa.com", "empresia.es")],
+ ],
+ "MX": [
+ ["México · DOF", _sites("dof.gob.mx")],
+ ["México · Compras y gobierno", _sites("compranet.hacienda.gob.mx", "gob.mx")],
+ ],
+}
+
+
+def _regional(q: str) -> list[list[str]]:
+ region = (settings.get("default_region") or "").upper()
+ groups = REGIONAL.get(region) or (REGIONAL["CL"] + REGIONAL["AR"])
+ return [[label, _g(f"{q} {sites}"), "Registros oficiales"] for label, sites in groups]
+
+
+def dorks_for(t: str, v: str) -> list[list[str]]:
+ """[etiqueta, url, grupo] de búsquedas preparadas para el dato."""
+ q = f'"{v}"'
+ out: list[list[str]] = []
+
+ def add(group: str, *items):
+ out.extend([label, url, group] for label, url in items)
+
+ if t == "username":
+ add("Básicos",
+ ["Menciones exactas", _g(q)],
+ ["En redes sociales", _g(f'{q} {_sites("twitter.com", "x.com", "instagram.com", "tiktok.com", "facebook.com", "threads.net")}')],
+ ["En foros", _g(f'{q} inurl:forum OR inurl:thread OR inurl:member OR inurl:profile OR inurl:showthread')],
+ ["Con email", _g(f'{q} "@gmail.com" OR "@hotmail.com" OR "@outlook.com" OR "@yahoo.com"')],
+ ["Imágenes", f"https://www.google.com/search?tbm=isch&q={quote_plus(q)}"])
+ add("Filtraciones y código",
+ ["Pastes", _g(f"{q} {PASTE_SITES}")],
+ ["Código", _g(f'{q} {_sites("github.com", "gist.github.com", "gitlab.com", "bitbucket.org")}')],
+ ["Credenciales o combos", _g(f'{q} (password OR passwd OR contraseña OR "user:pass")')],
+ ["Telegram", _g(f'{q} {_sites("t.me", "tgstat.com", "telemetr.io")}')])
+ add("Poco comunes",
+ ["Listas de juegos y Discord", _g(f'{q} {_sites("discord.me", "disboard.org", "top.gg", "steamcommunity.com", "namemc.com")}')],
+ ["Tiendas y reseñas", _g(f'{q} {_sites("mercadolibre.cl", "mercadolibre.com.ar", "ebay.com", "etsy.com", "wallapop.com")}')],
+ ["Música y creadores", _g(f'{q} {_sites("soundcloud.com", "bandcamp.com", "patreon.com", "ko-fi.com", "linktr.ee", "beacons.ai")}')],
+ ["Citas y comunidades", _g(f'{q} {_sites("badoo.com", "tinder.com", "okcupid.com", "meetup.com")}')])
+ add("Otros buscadores",
+ ["Bing", _bing(q)], ["Yandex (mejor para alias y foros rusos)", _yandex(q)], ["DuckDuckGo", _ddg(q)])
+ elif t == "email":
+ user, _, dom = v.partition("@")
+ add("Básicos",
+ ["Menciones exactas", _g(q)],
+ ["Sólo la parte local", _g(f'"{user}" -"{v}"')],
+ ["En redes y perfiles", _g(f'{q} {_sites("facebook.com", "linkedin.com", "twitter.com", "x.com", "instagram.com")}')])
+ add("Documentos y nube",
+ ["Documentos", _g(f"{q} filetype:pdf OR filetype:xlsx OR filetype:docx OR filetype:csv OR filetype:txt")],
+ ["Nube expuesta (Drive, OneDrive, S3…)", _g(f"{q} {CLOUD_SITES}")],
+ ["Plataformas de documentos", _g(f"{q} {DOC_SITES}")],
+ ["CV y empleo", _g(f"{q} {CV_SITES}")])
+ add("Filtraciones y código",
+ ["Pastes", _g(f"{q} {PASTE_SITES}")],
+ ["Código y tableros", _g(f"{q} {_sites('github.com', 'gitlab.com', 'trello.com', 'bitbucket.org')}")],
+ ["Herramientas internas (Jira, Postman…)", _g(f"{q} {INTERNAL_SITES}")],
+ ["Con contraseña cerca", _g(f'{q} (password OR contraseña OR pass OR pwd)')])
+ add("Otros buscadores", ["Bing", _bing(q)], ["Yandex", _yandex(q)], ["DuckDuckGo", _ddg(q)])
+ elif t == "phone":
+ digits = re.sub(r"\D", "", v)
+ local = digits[-9:] if len(digits) > 9 else digits
+ add("Básicos",
+ ["Menciones", _g(f'"{v}" OR "{digits}" OR "{local}"')],
+ ["Anuncios y perfiles", _g(f'"{local}" {_sites("facebook.com", "instagram.com", "linkedin.com", "mercadolibre.cl", "yapo.cl", "olx.com")}')],
+ ["WhatsApp y Telegram públicos", _g(f'"{digits}" (wa.me OR "chat.whatsapp.com" OR t.me)')],
+ ["Documentos", _g(f'"{local}" filetype:pdf OR filetype:xlsx OR filetype:csv')],
+ ["Nube expuesta", _g(f'"{local}" {CLOUD_SITES}')])
+ add("Otros buscadores", ["Bing", _bing(f'"{local}"')], ["Yandex", _yandex(f'"{local}"')])
+ elif t == "domain":
+ add("Básicos",
+ ["Páginas indexadas", _g(f"site:{v}")],
+ ["Subdominios", _g(f"site:*.{v} -site:www.{v}")],
+ ["Emails del dominio", _g(f'"@{v}" -site:{v}')],
+ ["Empleados en LinkedIn", _g(f'"{v}" site:linkedin.com/in')])
+ add("Documentos y nube",
+ ["Documentos expuestos", _g(f"site:{v} filetype:pdf OR filetype:docx OR filetype:xlsx OR filetype:pptx OR filetype:csv")],
+ ["Documentos internos", _g(f'site:{v} (confidencial OR "uso interno" OR "internal use" OR confidential) filetype:pdf OR filetype:docx')],
+ ["Nube expuesta (Drive, S3, Azure…)", _g(f'"{v}" {CLOUD_SITES}')],
+ ["Plataformas de documentos", _g(f'"{v}" {DOC_SITES}')])
+ add("Seguridad",
+ ["Paneles de acceso", _g(f"site:{v} inurl:login OR inurl:admin OR inurl:panel OR intitle:login OR inurl:wp-admin")],
+ ["Ficheros de configuración", _g(f"site:{v} ext:env OR ext:log OR ext:sql OR ext:bak OR ext:conf OR ext:ini OR ext:yml")],
+ ["Listados de directorios", _g(f'site:{v} intitle:"index of"')],
+ ["Errores y trazas", _g(f'site:{v} ("SQL syntax" OR "Warning: mysql" OR "stack trace" OR "Traceback" OR "Fatal error")')],
+ ["APIs y Swagger", _g(f'site:{v} inurl:swagger OR inurl:api-docs OR inurl:graphql OR intitle:"Swagger UI"')],
+ ["Herramientas internas filtradas", _g(f'"{v}" {INTERNAL_SITES}')],
+ ["Secretos en código", _g(f'"{v}" (password OR api_key OR apikey OR secret OR token) {_sites("github.com", "gitlab.com", "gist.github.com")}')],
+ ["Menciones en pastes", _g(f'"{v}" {PASTE_SITES}')])
+ add("Otros buscadores", ["Bing", _bing(f"site:{v}")], ["Yandex", _yandex(f"site:{v}")])
+ elif t == "person":
+ add("Básicos",
+ ["Menciones exactas", _g(q)],
+ ["LinkedIn", _g(f"{q} site:linkedin.com/in")],
+ ["Redes sociales", _g(f"{q} {_sites('facebook.com', 'instagram.com', 'twitter.com', 'x.com', 'tiktok.com', 'threads.net')}")],
+ ["Imágenes", f"https://www.google.com/search?tbm=isch&q={quote_plus(q)}"],
+ ["Noticias", f"https://www.google.com/search?tbm=nws&q={quote_plus(q)}"])
+ add("Documentos y nube",
+ ["Documentos y CV", _g(f"{q} filetype:pdf OR filetype:doc OR filetype:docx OR filetype:xlsx")],
+ ["Currículum", _g(f'{q} ("curriculum vitae" OR currículum OR CV OR "experiencia laboral")')],
+ ["CV y portales de empleo", _g(f"{q} {CV_SITES}")],
+ ["Plataformas de documentos", _g(f"{q} {DOC_SITES}")],
+ ["Nube expuesta", _g(f"{q} {CLOUD_SITES}")],
+ ["Tesis y trabajos académicos", _g(f'{q} (tesis OR memoria OR "trabajo de título" OR thesis) filetype:pdf')],
+ ["Su RUT en documentos públicos (Chile)", _g(f'{q} ("RUT" OR "R.U.T." OR "RUN") filetype:pdf OR filetype:xlsx OR filetype:xls OR filetype:csv')])
+ add("Chile: Estado y justicia",
+ ["Audiencias de lobby (como lobista o autoridad)", _g(f"{q} site:leylobby.gob.cl")],
+ ["Declaraciones de patrimonio", _g(f"{q} site:infoprobidad.cl")],
+ ["Causas judiciales publicadas", _g(f"{q} {_sites('pjud.cl', 'tribunalconstitucional.cl', 'diarioconstitucional.cl')}")],
+ ["Diario Oficial (sociedades, notificaciones)", _g(f"{q} site:diariooficial.interior.gob.cl")],
+ ["Sueldos y contratos públicos (Transparencia)", _g(f"{q} {_sites('portaltransparencia.cl', 'transparencia.gob.cl', 'mercadopublico.cl')}")],
+ ["Tesis en repositorios chilenos", _g(f"{q} {_sites('repositorio.uchile.cl', 'repositorio.uc.cl', 'repositorio.usm.cl', 'repositorio.udec.cl', 'repositorio.uv.cl', 'bibliotecadigital.uach.cl')}")])
+ variants = name_variants(v)
+ if variants:
+ anyq = " OR ".join(f'"{x}"' for x in [v] + variants[:4])
+ group = "Variantes del nombre (coincidencias parciales)"
+ add(group,
+ ["Todas las variantes a la vez", _g(anyq)],
+ ["LinkedIn con cualquier variante", _g(f"({anyq}) site:linkedin.com/in")],
+ ["Facebook e Instagram con cualquier variante", _g(f"({anyq}) {_sites('facebook.com', 'instagram.com')}")])
+ for x in variants[:4]:
+ add(group, [f"«{x}» en redes", _g(f'"{x}" {_sites("linkedin.com/in", "facebook.com", "instagram.com", "x.com", "tiktok.com")}')])
+ out.extend(_regional(q))
+ add("Otros buscadores",
+ ["Bing", _bing(q)], ["Yandex (mejor para caras y nombres)", _yandex(q)], ["DuckDuckGo", _ddg(q)])
+ elif t == "rut":
+ from .chile import rut_parts
+
+ num, dv = rut_parts(v)
+ forms = f'"{v}" OR "{num}-{dv}" OR "{num}{dv}"'
+ add("Básicos",
+ ["Menciones (todas las formas de escribirlo)", _g(forms)],
+ ["Documentos (PDF, Excel, Word)", _g(f"({forms}) filetype:pdf OR filetype:xlsx OR filetype:xls OR filetype:docx OR filetype:csv")],
+ ["Nube expuesta", _g(f"({forms}) {CLOUD_SITES}")])
+ add("Registros oficiales",
+ ["Poder Judicial y Tribunal Constitucional", _g(f"({forms}) {_sites('pjud.cl', 'tribunalconstitucional.cl', 'tdlc.cl')}")],
+ ["Diario Oficial (sociedades, notificaciones)", _g(f"({forms}) {_sites('diariooficial.interior.gob.cl')}")],
+ ["Mercado Público y compras del Estado", _g(f"({forms}) {_sites('mercadopublico.cl', 'chilecompra.cl')}")],
+ ["Transparencia, plantas y sueldos públicos", _g(f"({forms}) {_sites('portaltransparencia.cl', 'transparencia.cl', 'gob.cl')}")],
+ ["Empresas (registro, CMF, SII)", _g(f"({forms}) {_sites('registrodeempresasysociedades.cl', 'tuempresaenundia.cl', 'cmfchile.cl', 'sii.cl')}")],
+ ["Universidades y colegios (listas, resultados)", _g(f"({forms}) site:cl (lista OR nómina OR seleccionados OR resultados)")])
+ add("Otros buscadores", ["Bing", _bing(forms)], ["DuckDuckGo", _ddg(forms)])
+ elif t == "plate":
+ from .chile import plate_display
+
+ shown = plate_display(v)
+ dashed = shown.replace("·", "-")
+ forms = f'"{v}" OR "{dashed}" OR "{shown.replace("·", " ")}"'
+ add("Básicos",
+ ["Menciones de la patente", _g(forms)],
+ ["Avisos de venta (Chileautos, MercadoLibre, Yapo…)", _g(f"({forms}) {_sites('chileautos.cl', 'mercadolibre.cl', 'autos.mercadolibre.cl', 'yapo.cl', 'autocosmos.cl', 'olx.cl')}")],
+ ["En redes (grupos, denuncias, robos)", _g(f"({forms}) {_sites('facebook.com', 'instagram.com', 'x.com', 'twitter.com', 'tiktok.com')}")],
+ ["Robos y denuncias", _g(f"({forms}) (robado OR robada OR encargo OR portonazo OR denuncia)")],
+ ["Imágenes", f"https://www.google.com/search?tbm=isch&q={quote_plus(forms)}"])
+ add("Sitios no oficiales (verifica lo que digan)",
+ ["Buscadores de patentes", _g(f"({forms}) {_sites('patentechile.com', 'volanteomaleta.com', 'autofact.cl')}")])
+ elif t == "ip":
+ add("Básicos", ["Menciones", _g(q)], ["Censys", f"https://search.censys.io/hosts/{v}"],
+ ["Shodan", f"https://www.shodan.io/host/{v}"], ["En pastes y listas negras", _g(f"{q} {PASTE_SITES} OR site:abuseipdb.com")])
+ elif t == "url":
+ add("Básicos", ["Enlaces a la URL", _g(q)], ["Archive.today", f"https://archive.ph/{v}"],
+ ["Wayback", f"https://web.archive.org/web/*/{v}"])
+ elif t == "crypto":
+ add("Básicos", ["Menciones", _g(q)],
+ ["En foros y pastes", _g(f"{q} site:bitcointalk.org OR site:reddit.com OR {PASTE_SITES}")],
+ ["Donaciones en perfiles", _g(f'{q} (donate OR donación OR tip) {_sites("github.com", "twitter.com", "x.com")}')])
+ else:
+ add("Básicos", ["Menciones", _g(q)])
+ return out
+
+
+@register
+class Dorks(Module):
+ name = "dorks"
+ title = "Dorks de búsqueda"
+ description = "Búsquedas avanzadas de Google preparadas para el objetivo (se abren en tu navegador)."
+ inputs = ("username", "email", "phone", "domain", "person", "ip", "url", "crypto", "rut", "plate")
+ sources = ("Local",)
+
+ async def run(self, ctx):
+ ent = db.update_attrs(ctx.case_id, ctx.entity["id"], {"_dorks": dorks_for(ctx.entity["type"], ctx.value)},
+ replace=True)
+ if ent:
+ ctx.job.emit({"type": "entity", "entity": ent, "created": False})
+ ctx.enriched = True
diff --git a/app/modules/people.py b/app/modules/people.py
new file mode 100644
index 0000000..7722e3d
--- /dev/null
+++ b/app/modules/people.py
@@ -0,0 +1,316 @@
+"""Persona en fuentes públicas estructuradas: publicaciones académicas (OpenAlex, ORCID) y Wikidata."""
+import asyncio
+import re
+import unicodedata
+from collections import Counter
+
+from .base import Module, register
+from .username import PROFILE_URLS
+
+# Wikimedia exige un User-Agent que identifique la herramienta
+WIKI_UA = {"User-Agent": "OsintHunter/1.0 (https://github.com/osinthunter; herramienta OSINT local de escritorio)",
+ "Accept": "application/json"}
+
+
+def tokens(s: str) -> list[str]:
+ s = unicodedata.normalize("NFKD", s or "").encode("ascii", "ignore").decode().lower()
+ return re.sub(r"[^a-z ]+", " ", s).split()
+
+
+def same_name(a: str, b: str) -> bool:
+ """Mismo nombre ignorando tildes y mayúsculas; admite que uno omita el segundo nombre o apellido."""
+ ta, tb = tokens(a), tokens(b)
+ if not ta or not tb:
+ return False
+ if ta == tb:
+ return True
+ short, long_ = sorted((ta, tb), key=len)
+ return len(short) >= 2 and short[0] == long_[0] and all(t in long_ for t in short)
+
+
+PARTICLES = {"de", "del", "la", "las", "los", "y", "da", "das", "do", "dos", "di", "van", "von", "der", "san"}
+
+
+def name_parts(full: str) -> list[str]:
+ """Palabras del nombre con las partículas pegadas al apellido siguiente («de la Fuente»)."""
+ out, pending = [], []
+ for w in full.split():
+ if w.lower() in PARTICLES:
+ pending.append(w)
+ continue
+ out.append(" ".join(pending + [w]))
+ pending = []
+ if pending and out:
+ out[-1] += " " + " ".join(pending)
+ return out
+
+
+def name_variants(full: str) -> list[str]:
+ """Formas abreviadas con las que la gente suele aparecer en redes (sin segundo nombre o apellido)."""
+ p = name_parts(full)
+ n = len(p)
+ if n < 3:
+ return []
+ f, s1, s2 = p[0], p[-2], p[-1]
+ if n == 3:
+ # «Nombre Apellido Apellido» o «Nombre SegundoNombre Apellido»
+ v = [f"{f} {p[1]}", f"{f} {s2}", f"{p[1]} {s2}"]
+ else:
+ mids = p[1:-2]
+ v = [f"{f} {s1} {s2}", f"{f} {s1}", f"{f} {' '.join(mids)} {s1}", f"{mids[0]} {s1} {s2}",
+ f"{mids[0]} {s1}", f"{f} {mids[0][0]}. {s1}", f"{f} {s2}"]
+ full_t = tokens(full)
+ return [x for x in dict.fromkeys(v) if tokens(x) != full_t]
+
+
+def _contains_seq(hay: list[str], seq: list[str]) -> bool:
+ n = len(seq)
+ return any(hay[i:i + n] == seq for i in range(len(hay) - n + 1))
+
+
+def name_match(text: str, full: str, variants: list[str] | None = None) -> tuple[str, str] | None:
+ """('exacta', nombre) si el texto trae el nombre completo, ('parcial', variante) si sólo una forma corta."""
+ hay = tokens(text)
+ ft = tokens(full)
+ if _contains_seq(hay, ft) or (len(ft) >= 3 and all(t in hay for t in ft)):
+ return "exacta", full
+ for v in variants if variants is not None else name_variants(full):
+ vt = [t for t in tokens(v) if len(t) > 1]
+ if len(vt) >= 2 and _contains_seq([t for t in hay if len(t) > 1], vt):
+ return "parcial", v
+ return None
+
+
+@register
+class Academic(Module):
+ name = "academic"
+ title = "Publicaciones académicas (OpenAlex, ORCID)"
+ description = "Artículos, tesis y patentes firmados con ese nombre: afiliación, coautores, temas y ORCID"
+ inputs = ("person",)
+ sources = ("api.openalex.org", "pub.orcid.org")
+
+ async def run(self, ctx):
+ name = ctx.value.strip()
+ if len(tokens(name)) < 2:
+ ctx.message = "Hace falta nombre y apellido"
+ return
+ await asyncio.gather(self._openalex(ctx, name), self._orcid(ctx, name))
+
+ async def _openalex(self, ctx, name):
+ for query in [name] + name_variants(name)[:2]:
+ st, d = await ctx.get_json("https://api.openalex.org/authors", params={"search": query, "per-page": 15})
+ if st != 200 or not isinstance(d, dict):
+ return
+ matches = [a for a in d.get("results") or []
+ if same_name(a.get("display_name", ""), name)
+ or any(same_name(x, name) for x in a.get("display_name_alternatives") or [])]
+ if matches:
+ break
+ else:
+ return
+ matches.sort(key=lambda a: -(a.get("works_count") or 0))
+ if query != name:
+ ctx.enrich({
+ "OpenAlex: autores con nombre parecido": [
+ f"{a['display_name']} · {a.get('works_count', 0)} trabajos · "
+ + ", ".join(i.get("display_name", "") for i in a.get("last_known_institutions") or [])[:80]
+ for a in matches[:8]],
+ "_links": [[f"OpenAlex {a['display_name']}", f"https://openalex.org/authors/{a['id'].rsplit('/', 1)[-1]}"]
+ for a in matches[:5]],
+ })
+ ctx.found += len(matches)
+ return
+ if len(matches) > 1:
+ ctx.enrich({"OpenAlex: autores con este nombre": [
+ f"{a['display_name']} · {a.get('works_count', 0)} trabajos · "
+ + ", ".join(i.get("display_name", "") for i in a.get("last_known_institutions") or [])[:80]
+ for a in matches[:8]]})
+ best = matches[0]
+ aid = best["id"].rsplit("/", 1)[-1]
+ insts = [i for i in best.get("last_known_institutions") or [] if i.get("display_name")]
+ attrs = {
+ "OpenAlex: trabajos": best.get("works_count"),
+ "OpenAlex: citas": best.get("cited_by_count"),
+ "OpenAlex: índice h": (best.get("summary_stats") or {}).get("h_index"),
+ "Temas de investigación": [t["display_name"] for t in (best.get("topics") or [])[:6]] or None,
+ "Afiliación (OpenAlex)": [f"{i['display_name']} ({i.get('country_code') or '?'})" for i in insts] or None,
+ "_links": [["Perfil en OpenAlex", f"https://openalex.org/authors/{aid}"]],
+ }
+ if best.get("orcid"):
+ attrs["ORCID"] = best["orcid"].rsplit("/", 1)[-1]
+ attrs["_links"].append(["ORCID", best["orcid"]])
+ st, w = await ctx.get_json("https://api.openalex.org/works", params={
+ "filter": f"author.id:{aid}", "sort": "cited_by_count:desc", "per-page": 8,
+ "select": "title,publication_year,doi,authorships,primary_location",
+ })
+ coauthors = Counter()
+ if st == 200 and isinstance(w, dict):
+ works = w.get("results") or []
+ attrs["Publicaciones destacadas"] = list(dict.fromkeys(
+ f"{x.get('publication_year')} · {x.get('title')}" for x in works if x.get("title"))) or None
+ for x in works:
+ for au in x.get("authorships") or []:
+ nm = (au.get("author") or {}).get("display_name")
+ if nm and not same_name(nm, name):
+ coauthors[nm] += 1
+ attrs["Coautores frecuentes"] = [f"{n} ({c})" for n, c in coauthors.most_common(8)] or None
+ ctx.enrich(attrs)
+ if len(matches) == 1:
+ for i in insts[:3]:
+ ctx.add("organization", i["display_name"], {"País": i.get("country_code"), "Tipo": i.get("type")},
+ rel="afiliación académica", pivot=False)
+ ctx.found += 1
+
+ async def _orcid(self, ctx, name):
+ t = name.split()
+ given, family = t[0], t[1] if len(t) >= 3 else t[-1]
+ q = f'given-names:"{given}" AND family-names:"{family}"'
+ st, d = await ctx.get_json("https://pub.orcid.org/v3.0/expanded-search/", params={"q": q, "rows": 20},
+ headers={"Accept": "application/json"})
+ if st != 200 or not isinstance(d, dict):
+ return
+ hits = [h for h in d.get("expanded-result") or []
+ if same_name(f"{h.get('given-names') or ''} {h.get('family-names') or ''}", name)
+ or same_name(h.get("credit-name") or "", name)]
+ if not hits:
+ return
+ lines, links = [], []
+ for h in hits[:10]:
+ inst = ", ".join((h.get("institution-name") or [])[:2])
+ full = f"{h.get('given-names') or ''} {h.get('family-names') or ''}".strip()
+ lines.append(f"{h['orcid-id']} · {full}" + (f" · {inst}" if inst else ""))
+ links.append([f"ORCID {full}", f"https://orcid.org/{h['orcid-id']}"])
+ ctx.enrich({"ORCID: perfiles con este nombre": lines, "_links": links[:5]})
+ if len(hits) == 1:
+ for e in hits[0].get("email") or []:
+ ctx.add("email", e, rel="email en ORCID", pivot=True)
+ for inst in (hits[0].get("institution-name") or [])[:3]:
+ ctx.add("organization", inst, rel="institución (ORCID)", pivot=False)
+ ctx.found += len(hits)
+
+
+# ---------------------------------------------------------------- Wikidata
+
+WD_ITEM_PROPS = {
+ "P19": "Lugar de nacimiento", "P27": "Nacionalidad", "P106": "Ocupación", "P39": "Cargos",
+ "P108": "Empleadores", "P69": "Estudios", "P102": "Partido político", "P26": "Cónyuge", "P22": "Padre",
+ "P25": "Madre", "P40": "Hijos", "P3373": "Hermanos",
+}
+WD_SOCIAL = {
+ "P2002": ("X/Twitter", None), "P2003": ("Instagram", None), "P2013": ("Facebook", None),
+ "P6634": ("LinkedIn", None), "P2037": ("GitHub", None), "P7085": ("TikTok", None),
+ "P2397": ("YouTube", "https://www.youtube.com/channel/{}"), "P11892": ("Threads", None),
+}
+
+
+def _claims(entity: dict, pid: str) -> list:
+ out = []
+ for c in entity.get("claims", {}).get(pid, []):
+ v = ((c.get("mainsnak") or {}).get("datavalue") or {}).get("value")
+ if v is not None:
+ out.append(v)
+ return out
+
+
+@register
+class Wikidata(Module):
+ name = "wikidata"
+ title = "Wikidata / Wikipedia"
+ description = ("Si la persona es pública: fecha y lugar de nacimiento, cargos, estudios, familia, "
+ "web y redes oficiales")
+ inputs = ("person",)
+ sources = ("wikidata.org",)
+
+ async def run(self, ctx):
+ name = ctx.value.strip()
+ for query in [name] + name_variants(name)[:2]:
+ st, d = await ctx.get_json("https://www.wikidata.org/w/api.php", headers=WIKI_UA, params={
+ "action": "wbsearchentities", "search": query, "language": "es", "uselang": "es", "type": "item",
+ "limit": 10, "format": "json",
+ })
+ if st != 200 or not isinstance(d, dict):
+ raise RuntimeError(f"Wikidata respondió {st}")
+ cands = [c["id"] for c in d.get("search") or []
+ if same_name(c.get("label", ""), name) or any(same_name(a, name) for a in c.get("aliases") or [])][:5]
+ if cands:
+ break
+ else:
+ return
+ partial = query != name
+ st, ents = await ctx.get_json("https://www.wikidata.org/w/api.php", headers=WIKI_UA, params={
+ "action": "wbgetentities", "ids": "|".join(cands), "props": "claims|sitelinks|descriptions|labels",
+ "languages": "es|en", "format": "json",
+ })
+ if st != 200 or not isinstance(ents, dict):
+ return
+ humans = [e for e in (ents.get("entities") or {}).values()
+ if any(v.get("id") == "Q5" for v in _claims(e, "P31") if isinstance(v, dict))]
+ if not humans:
+ return
+ desc = lambda e: ((e.get("descriptions") or {}).get("es") or (e.get("descriptions") or {}).get("en") or {}).get("value", "") # noqa: E731
+ if len(humans) > 1 or partial:
+ label = lambda e: ((e.get("labels") or {}).get("es") or (e.get("labels") or {}).get("en") or {}).get("value", "") # noqa: E731
+ key = "Wikidata: personas con nombre parecido" if partial else "Wikidata: personas con este nombre"
+ ctx.enrich({key: [f"{e['id']} · {label(e)} · {desc(e)}" for e in humans],
+ "_links": [[f"Wikidata {e['id']}", f"https://www.wikidata.org/wiki/{e['id']}"] for e in humans]})
+ ctx.message = (f"Sólo con «{query}»: puede ser otra persona" if partial else
+ f"{len(humans)} personas públicas con este nombre: revisa cuál es antes de atribuir datos")
+ ctx.found += len(humans)
+ return
+ e = humans[0]
+ ref_ids = {v["id"] for pid in WD_ITEM_PROPS for v in _claims(e, pid) if isinstance(v, dict) and "id" in v}
+ labels = await self._labels(ctx, ref_ids)
+ attrs = {"Descripción (Wikidata)": desc(e), "Wikidata": e["id"]}
+ birth = [v.get("time", "")[1:11] for v in _claims(e, "P569") if isinstance(v, dict)]
+ death = [v.get("time", "")[1:11] for v in _claims(e, "P570") if isinstance(v, dict)]
+ attrs["Fecha de nacimiento"] = birth[0].replace("-00", "") if birth else None
+ attrs["Fecha de fallecimiento"] = death[0].replace("-00", "") if death else None
+ for pid, label in WD_ITEM_PROPS.items():
+ vals = list(dict.fromkeys(labels.get(v["id"], v["id"]) for v in _claims(e, pid) if isinstance(v, dict) and "id" in v))
+ if vals:
+ attrs[label] = vals if len(vals) > 1 else vals[0]
+ links = [["Wikidata", f"https://www.wikidata.org/wiki/{e['id']}"]]
+ for site, base in (("eswiki", "https://es.wikipedia.org/wiki/"), ("enwiki", "https://en.wikipedia.org/wiki/")):
+ title = ((e.get("sitelinks") or {}).get(site) or {}).get("title")
+ if title:
+ links.append([f"Wikipedia ({site[:2]})", base + title.replace(" ", "_")])
+ attrs["_links"] = links
+ images = _claims(e, "P18")
+ if images:
+ attrs["_avatar"] = f"https://commons.wikimedia.org/wiki/Special:FilePath/{images[0].replace(' ', '_')}?width=300"
+ ctx.enrich(attrs)
+
+ place = attrs.get("Lugar de nacimiento")
+ if isinstance(place, str):
+ ctx.add("location", place, rel="lugar de nacimiento")
+ for site in _claims(e, "P856")[:3]:
+ if isinstance(site, str):
+ ctx.add("url", site, {"_links": [["Abrir", site]]}, rel="web oficial", pivot=False)
+ for pid, (platform, tpl) in WD_SOCIAL.items():
+ for handle in _claims(e, pid)[:2]:
+ if not isinstance(handle, str):
+ continue
+ url = (tpl or PROFILE_URLS.get(platform, "")).format(handle)
+ if not url:
+ continue
+ acc = ctx.add("account", url, {
+ "Plataforma": platform, "Usuario": handle, "_links": [["Abrir perfil", url]],
+ "Verificación": "Indicada en Wikidata (cuenta oficial)",
+ }, rel="cuenta oficial", pivot=False)
+ if acc and platform != "YouTube" and re.fullmatch(r"[\w.\-]{2,40}", handle):
+ ctx.add("username", handle, rel="usuario", parent=acc)
+ ctx.found += 1
+
+ async def _labels(self, ctx, ids: set[str]) -> dict[str, str]:
+ out: dict[str, str] = {}
+ ids_l = sorted(ids)
+ for i in range(0, len(ids_l), 50):
+ st, d = await ctx.get_json("https://www.wikidata.org/w/api.php", headers=WIKI_UA, params={
+ "action": "wbgetentities", "ids": "|".join(ids_l[i:i + 50]), "props": "labels",
+ "languages": "es|en", "format": "json",
+ })
+ if st == 200 and isinstance(d, dict):
+ for qid, ent in (d.get("entities") or {}).items():
+ lab = ent.get("labels") or {}
+ out[qid] = (lab.get("es") or lab.get("en") or {}).get("value", qid)
+ return out
diff --git a/app/modules/phone.py b/app/modules/phone.py
new file mode 100644
index 0000000..9508be2
--- /dev/null
+++ b/app/modules/phone.py
@@ -0,0 +1,94 @@
+import phonenumbers
+from phonenumbers import carrier, geocoder, timezone
+from phonenumbers.phonenumberutil import NumberParseException, PhoneNumberType
+
+from .base import Module, Skip, register
+
+TYPE_NAMES = {
+ PhoneNumberType.MOBILE: "Móvil",
+ PhoneNumberType.FIXED_LINE: "Fijo",
+ PhoneNumberType.FIXED_LINE_OR_MOBILE: "Fijo o móvil",
+ PhoneNumberType.TOLL_FREE: "Gratuito",
+ PhoneNumberType.PREMIUM_RATE: "Tarificación especial",
+ PhoneNumberType.SHARED_COST: "Coste compartido",
+ PhoneNumberType.VOIP: "VoIP",
+ PhoneNumberType.PERSONAL_NUMBER: "Número personal",
+ PhoneNumberType.PAGER: "Buscapersonas",
+ PhoneNumberType.UAN: "UAN",
+ PhoneNumberType.VOICEMAIL: "Buzón de voz",
+}
+
+
+def parse(ctx) -> phonenumbers.PhoneNumber:
+ region = (ctx.settings.get("default_region") or "").upper() or None
+ raw = ctx.value
+ try:
+ return phonenumbers.parse(raw, None if raw.startswith("+") else region)
+ except NumberParseException as e:
+ raise Skip(
+ "No se pudo interpretar el número. Escríbelo con prefijo internacional (+34…, +54…) "
+ "o define tu país por defecto en Ajustes."
+ ) from e
+
+
+@register
+class PhoneInfo(Module):
+ name = "phone_info"
+ title = "Análisis del teléfono"
+ description = "País, región, operador original, tipo de línea y zona horaria (sin conexión, base de Google libphonenumber)."
+ inputs = ("phone",)
+ sources = ("libphonenumber",)
+
+ async def run(self, ctx):
+ n = parse(ctx)
+ e164 = phonenumbers.format_number(n, phonenumbers.PhoneNumberFormat.E164)
+ digits = e164.lstrip("+")
+ region = phonenumbers.region_code_for_number(n)
+ country = geocoder.country_name_for_number(n, "es")
+ place = geocoder.description_for_number(n, "es")
+ ctx.enrich({
+ "Válido": "Sí" if phonenumbers.is_valid_number(n) else "No (formato posible pero no asignado)",
+ "E.164": e164,
+ "Internacional": phonenumbers.format_number(n, phonenumbers.PhoneNumberFormat.INTERNATIONAL),
+ "Nacional": phonenumbers.format_number(n, phonenumbers.PhoneNumberFormat.NATIONAL),
+ "País": f"{country} ({region})" if country else region,
+ "Zona": place if place and place != country else None,
+ "Operador original": carrier.name_for_number(n, "es") or None,
+ "Tipo de línea": TYPE_NAMES.get(phonenumbers.number_type(n), "Desconocido"),
+ "Zona horaria": list(timezone.time_zones_for_number(n)) or None,
+ "_links": [
+ ["WhatsApp", f"https://wa.me/{digits}"],
+ ["Telegram", f"https://t.me/+{digits}"],
+ ["Buscar en Google", f'https://www.google.com/search?q="{e164}" OR "{digits}"'],
+ ["Sync.me", f"https://sync.me/search/?number={digits}"],
+ ],
+ })
+ loc = ", ".join(x for x in (place if place != country else None, country) if x)
+ if loc:
+ ctx.add("location", loc, rel="ubicación del prefijo", pivot=False)
+
+
+@register
+class Numverify(Module):
+ name = "numverify"
+ title = "Numverify"
+ description = "Validación en línea del número y operador actual."
+ inputs = ("phone",)
+ keys = ("numverify",)
+ sources = ("Numverify",)
+
+ async def run(self, ctx):
+ n = parse(ctx)
+ e164 = phonenumbers.format_number(n, phonenumbers.PhoneNumberFormat.E164)
+ st, d = await ctx.get_json(
+ "http://apilayer.net/api/validate", params={"access_key": ctx.key("numverify"), "number": e164.lstrip("+")}
+ )
+ if not isinstance(d, dict) or d.get("error"):
+ ctx.message = str((d or {}).get("error", {}).get("info", f"Respuesta {st}"))
+ return
+ ctx.enrich({
+ "Numverify: válido": d.get("valid"),
+ "Numverify: operador": d.get("carrier"),
+ "Numverify: tipo": d.get("line_type"),
+ "Numverify: ubicación": d.get("location"),
+ })
diff --git a/app/modules/username.py b/app/modules/username.py
new file mode 100644
index 0000000..b841c50
--- /dev/null
+++ b/app/modules/username.py
@@ -0,0 +1,1339 @@
+import asyncio
+import html
+import json
+import random
+import re
+import string
+import time
+import unicodedata
+import xml.etree.ElementTree as ET
+from collections import Counter
+
+import httpx
+
+from ..config import DATA_DIR, RESOURCES_DIR, settings
+from ..db import db
+from ..util import URL_RE, clean_emails, social_from_url
+from .base import Module, Skip, register
+
+# ---------------------------------------------------------------------------
+# Perfiles enriquecidos: plataformas con API pública de las que sacamos datos
+# ---------------------------------------------------------------------------
+
+PROFILE_URLS = {
+ "X/Twitter": "https://x.com/{}",
+ "GitHub": "https://github.com/{}",
+ "Reddit": "https://www.reddit.com/user/{}",
+ "Instagram": "https://www.instagram.com/{}",
+ "Facebook": "https://www.facebook.com/{}",
+ "LinkedIn": "https://www.linkedin.com/in/{}",
+ "YouTube": "https://www.youtube.com/@{}",
+ "TikTok": "https://www.tiktok.com/@{}",
+ "Telegram": "https://t.me/{}",
+ "Twitch": "https://www.twitch.tv/{}",
+ "Bluesky": "https://bsky.app/profile/{}",
+ "Hacker News": "https://news.ycombinator.com/user?id={}",
+ "Mastodon": "{}",
+ "Threads": "https://www.threads.net/@{}",
+}
+
+
+class Blocked(Exception):
+ """La plataforma ha limitado o bloqueado la consulta: no sabemos si la cuenta existe."""
+
+
+def _txt(html: str | None) -> str:
+ return re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", html or "")).strip()
+
+
+def _date(ts) -> str | None:
+ if ts in (None, ""):
+ return None
+ if isinstance(ts, (int, float)):
+ if ts > 1e11:
+ ts /= 1000
+ return time.strftime("%Y-%m-%d", time.gmtime(ts))
+ return str(ts)[:10]
+
+
+async def p_github(ctx, u):
+ h = {"Accept": "application/vnd.github+json"}
+ if ctx.key("github"):
+ h["Authorization"] = f"Bearer {ctx.key('github')}"
+ st, d = await ctx.get_json(f"https://api.github.com/users/{u}", headers=h)
+ if st != 200 or not isinstance(d, dict):
+ return None
+ login = d["login"]
+ emails: list[str] = [d.get("email") or ""]
+ names: list[str] = []
+ own_names = {login.lower(), (d.get("name") or "").strip().lower()} - {""}
+ # emails de commits públicos: primero eventos, después commits de sus repos.
+ # Un push puede incluir commits de otras personas: sólo cuentan los del propio usuario.
+ st, ev = await ctx.get_json(f"https://api.github.com/users/{login}/events/public?per_page=100", headers=h)
+ if st == 200 and isinstance(ev, list):
+ for e in ev:
+ for c in (e.get("payload") or {}).get("commits") or []:
+ a = c.get("author") or {}
+ em, nm = (a.get("email") or "").lower(), (a.get("name") or "").strip()
+ if nm.lower() in own_names or login.lower() in em.split("@")[0]:
+ emails.append(em)
+ names.append(nm)
+ if not [e for e in emails if e and "noreply" not in e]:
+ st, repos = await ctx.get_json(
+ f"https://api.github.com/users/{login}/repos?sort=pushed&per_page=10&type=owner", headers=h
+ )
+ if st == 200 and isinstance(repos, list):
+ own = [r for r in repos if not r.get("fork")][:3]
+ for r in own:
+ st, commits = await ctx.get_json(
+ f"https://api.github.com/repos/{login}/{r['name']}/commits?author={login}&per_page=5", headers=h
+ )
+ if st == 200 and isinstance(commits, list):
+ for c in commits:
+ a = (c.get("commit") or {}).get("author") or {}
+ emails.append(a.get("email") or "")
+ names.append(a.get("name") or "")
+ emails = [e.lower() for e in emails if e and "noreply" not in e.lower() and "@" in e]
+ return {
+ "platform": "GitHub",
+ "user": login,
+ "url": d["html_url"],
+ "attrs": {
+ "Nombre": d.get("name"),
+ "Bio": d.get("bio"),
+ "Empresa": d.get("company"),
+ "Web": d.get("blog"),
+ "Repos públicos": d.get("public_repos"),
+ "Seguidores": d.get("followers"),
+ "Creada": _date(d.get("created_at")),
+ "Nombres en commits": sorted({n for n in names if n}) or None,
+ "_avatar": d.get("avatar_url"),
+ },
+ "name": d.get("name"),
+ "location": d.get("location"),
+ "emails": emails,
+ "urls": [d.get("blog")],
+ "linked": [("X/Twitter", d.get("twitter_username"))],
+ }
+
+
+async def p_gitlab(ctx, u):
+ st, d = await ctx.get_json(f"https://gitlab.com/api/v4/users?username={u}")
+ if st != 200 or not d:
+ return None
+ base = d[0]
+ st, full = await ctx.get_json(f"https://gitlab.com/api/v4/users/{base['id']}")
+ full = full if st == 200 and isinstance(full, dict) else base
+ return {
+ "platform": "GitLab",
+ "user": base["username"],
+ "url": base["web_url"],
+ "attrs": {
+ "Nombre": full.get("name"),
+ "Bio": full.get("bio"),
+ "Organización": full.get("organization"),
+ "Puesto": full.get("job_title"),
+ "Creada": _date(full.get("created_at")),
+ "_avatar": full.get("avatar_url"),
+ },
+ "name": full.get("name"),
+ "location": full.get("location"),
+ "emails": [full.get("public_email")],
+ "urls": [full.get("website_url")],
+ "linked": [("X/Twitter", full.get("twitter")), ("LinkedIn", full.get("linkedin"))],
+ }
+
+
+async def p_keybase(ctx, u):
+ st, d = await ctx.get_json(
+ f"https://keybase.io/_/api/1.0/user/lookup.json?usernames={u}&fields=basics,profile,proofs_summary,pictures"
+ )
+ them = (d or {}).get("them") if isinstance(d, dict) else None
+ if st != 200 or not them or not them[0]:
+ return None
+ t = them[0]
+ prof = t.get("profile") or {}
+ linked, urls = [], []
+ for p in (t.get("proofs_summary") or {}).get("all") or []:
+ kind, tag, surl = p.get("proof_type"), p.get("nametag"), p.get("service_url")
+ mapping = {"twitter": "X/Twitter", "github": "GitHub", "reddit": "Reddit", "hackernews": "Hacker News",
+ "facebook": "Facebook", "mastodon": "Mastodon"}
+ if kind in mapping:
+ linked.append((mapping[kind], tag))
+ elif kind in ("dns", "generic_web_site", "https", "http"):
+ urls.append(surl or f"https://{tag}")
+ pic = ((t.get("pictures") or {}).get("primary") or {}).get("url")
+ return {
+ "platform": "Keybase",
+ "user": t["basics"]["username"],
+ "url": f"https://keybase.io/{t['basics']['username']}",
+ "attrs": {"Nombre": prof.get("full_name"), "Bio": prof.get("bio"), "_avatar": pic},
+ "name": prof.get("full_name"),
+ "location": prof.get("location"),
+ "urls": urls,
+ "linked": linked,
+ }
+
+
+async def p_hackernews(ctx, u):
+ st, d = await ctx.get_json(f"https://hacker-news.firebaseio.com/v0/user/{u}.json")
+ if st != 200 or not isinstance(d, dict):
+ return None
+ about = _txt(d.get("about"))
+ return {
+ "platform": "Hacker News",
+ "user": d["id"],
+ "url": f"https://news.ycombinator.com/user?id={d['id']}",
+ "attrs": {"Bio": about, "Karma": d.get("karma"), "Creada": _date(d.get("created"))},
+ "bio": about,
+ }
+
+
+async def p_bluesky(ctx, u):
+ actor = u if "." in u else f"{u}.bsky.social"
+ st, d = await ctx.get_json(f"https://public.api.bsky.app/xrpc/app.bsky.actor.getProfile?actor={actor}")
+ if st != 200 or not isinstance(d, dict) or not d.get("handle"):
+ return None
+ return {
+ "platform": "Bluesky",
+ "user": d["handle"],
+ "url": f"https://bsky.app/profile/{d['handle']}",
+ "attrs": {
+ "Nombre": d.get("displayName"),
+ "Bio": d.get("description"),
+ "Seguidores": d.get("followersCount"),
+ "Publicaciones": d.get("postsCount"),
+ "Creada": _date(d.get("createdAt")),
+ "DID": d.get("did"),
+ "_avatar": d.get("avatar"),
+ },
+ "name": d.get("displayName"),
+ "bio": d.get("description"),
+ }
+
+
+async def p_mastodon(ctx, u):
+ st, d = await ctx.get_json(f"https://mastodon.social/api/v1/accounts/lookup?acct={u}")
+ if st != 200 or not isinstance(d, dict) or not d.get("url"):
+ return None
+ fields = {f["name"]: _txt(f.get("value")) for f in d.get("fields") or []}
+ note = _txt(d.get("note"))
+ return {
+ "platform": "Mastodon",
+ "user": d.get("acct"),
+ "url": d["url"],
+ "attrs": {
+ "Nombre": d.get("display_name"),
+ "Bio": note,
+ "Seguidores": d.get("followers_count"),
+ "Creada": _date(d.get("created_at")),
+ "Campos": fields or None,
+ "_avatar": d.get("avatar"),
+ },
+ "name": d.get("display_name"),
+ "bio": note + " " + " ".join(fields.values()),
+ }
+
+
+async def p_telegram(ctx, u):
+ if not re.match(r"^[A-Za-z][A-Za-z0-9_]{4,31}$", u):
+ return None
+ r = await ctx.http.get(f"https://t.me/{u}")
+ html = r.text
+ if r.status_code != 200 or "tgme_page_title" not in html:
+ return None
+ title = re.search(r'<div class="tgme_page_title"[^>]*>\s*<span[^>]*>(.*?)</span>', html, re.S)
+ desc = re.search(r'<div class="tgme_page_description[^"]*"[^>]*>(.*?)</div>', html, re.S)
+ extra = re.search(r'<div class="tgme_page_extra">(.*?)</div>', html, re.S)
+ photo = re.search(r'<img class="tgme_page_photo_image" src="([^"]+)"', html)
+ bio = _txt(desc.group(1)) if desc else ""
+ attrs = {
+ "Nombre": _txt(title.group(1)) if title else None,
+ "Bio": bio,
+ "Info": _txt(extra.group(1)) if extra else None,
+ "_avatar": photo.group(1) if photo else None,
+ }
+ # Los canales públicos tienen vista previa con las últimas publicaciones.
+ posts_text = ""
+ r2 = await ctx.http.get(f"https://t.me/s/{u}")
+ if r2.status_code == 200 and "tgme_widget_message" in r2.text:
+ page = r2.text
+ counters = dict((t, v) for v, t in re.findall(
+ r'<span class="counter_value">([^<]+)</span>\s*<span class="counter_type">([^<]+)</span>', page))
+ posts = [_txt(p) for p in re.findall(r'<div class="tgme_widget_message_text[^"]*"[^>]*>(.*?)</div>', page, re.S)]
+ dates = re.findall(r'<time datetime="([^"]+)"', page)
+ attrs.update({
+ "Tipo": "Canal público",
+ "Suscriptores": counters.get("subscribers") or counters.get("members"),
+ "Última publicación": dates[-1][:10] if dates else None,
+ "Publicaciones recientes": [p[:280] for p in posts[-5:]][::-1] or None,
+ })
+ posts_text = " ".join(posts[-20:])
+ return {
+ "platform": "Telegram",
+ "user": u,
+ "url": f"https://t.me/{u}",
+ "attrs": attrs,
+ "name": attrs["Nombre"],
+ "bio": bio,
+ "emails": clean_emails(posts_text),
+ }
+
+
+async def p_twitter(ctx, u):
+ if not re.match(r"^[A-Za-z0-9_]{1,15}$", u):
+ return None
+ st, d = await ctx.get_json(f"https://api.fxtwitter.com/{u}")
+ user = (d or {}).get("user") if isinstance(d, dict) else None
+ if st != 200 or not user:
+ return None
+ joined = None
+ try:
+ joined = time.strftime("%Y-%m-%d", time.strptime(user.get("joined") or "", "%a %b %d %H:%M:%S %z %Y"))
+ except ValueError:
+ pass
+ site = user.get("website")
+ site = site.get("url") if isinstance(site, dict) else site
+ return {
+ "platform": "X/Twitter",
+ "user": user.get("screen_name") or u,
+ "url": user.get("url") or f"https://x.com/{u}",
+ "attrs": {
+ "Nombre": user.get("name"),
+ "Bio": user.get("description"),
+ "Seguidores": user.get("followers"),
+ "Siguiendo": user.get("following"),
+ "Publicaciones": user.get("tweets"),
+ "Creada": joined,
+ "Verificada": "Sí" if (user.get("verification") or {}).get("verified") else None,
+ "Protegida": "Sí" if user.get("protected") else None,
+ "_avatar": (user.get("avatar_url") or "").replace("_normal.", "_400x400.") or None,
+ },
+ "name": user.get("name"),
+ "location": (user.get("location") or "").strip() or None,
+ "urls": [site],
+ "bio": user.get("description"),
+ }
+
+
+def _sleep_window(hours: Counter) -> str | None:
+ """Estima la zona horaria buscando las 6 horas seguidas con menos actividad (se asume que duerme de 1 a 7)."""
+ total = sum(hours.values())
+ if total < 30:
+ return None
+ start = min(range(24), key=lambda s: sum(hours[(s + i) % 24] for i in range(6)))
+ offset = (1 - start + 12) % 24 - 12
+ return f"UTC{offset:+d} aprox. (inactivo entre las {start:02d}h y {(start + 6) % 24:02d}h UTC, {total} comentarios)"
+
+
+async def p_reddit(ctx, u):
+ if not re.match(r"^[A-Za-z0-9_\-]{3,20}$", u):
+ return None
+ base = "https://arctic-shift.photon-reddit.com/api"
+ st, d = await ctx.get_json(f"{base}/users/search", params={"author": u, "limit": 1})
+ rows = (d or {}).get("data") if isinstance(d, dict) else None
+ if st != 200 or not rows or (rows[0].get("author") or "").lower() != u.lower():
+ return None
+ name = rows[0]["author"]
+ meta = rows[0].get("_meta") or {}
+ first = [x for x in (meta.get("earliest_comment_at"), meta.get("earliest_post_at")) if x]
+ last = [x for x in (meta.get("last_comment_at"), meta.get("last_post_at")) if x]
+ attrs = {
+ "Karma": meta.get("total_karma"),
+ "Comentarios": meta.get("num_comments"),
+ "Publicaciones": meta.get("num_posts"),
+ "Primera actividad": _date(min(first)) if first else None,
+ "Última actividad": _date(max(last)) if last else None,
+ }
+ emails: list[str] = []
+ st, c = await ctx.get_json(f"{base}/comments/search",
+ params={"author": name, "limit": 100, "fields": "subreddit,created_utc,body"})
+ comments = (c or {}).get("data") if isinstance(c, dict) else None
+ if st == 200 and comments:
+ subs = Counter(x.get("subreddit") for x in comments if x.get("subreddit"))
+ hours = Counter(time.gmtime(x["created_utc"]).tm_hour for x in comments if x.get("created_utc"))
+ attrs["Subreddits frecuentes"] = [f"r/{s} ({n})" for s, n in subs.most_common(10)]
+ attrs["Horas más activas (UTC)"] = [f"{h:02d}h" for h, _ in hours.most_common(3)]
+ attrs["Zona horaria estimada"] = _sleep_window(hours)
+ emails = clean_emails(" ".join(x.get("body") or "" for x in comments))
+ return {
+ "platform": "Reddit",
+ "user": name,
+ "url": f"https://www.reddit.com/user/{name}",
+ "attrs": attrs,
+ "emails": emails,
+ }
+
+
+async def p_youtube(ctx, u):
+ if not re.match(r"^[A-Za-z0-9_.\-]{3,30}$", u):
+ return None
+ r = await ctx.http.get(f"https://www.youtube.com/@{u}", headers={"Cookie": "CONSENT=YES+1; SOCS=CAI"})
+ marker = '"channelMetadataRenderer":'
+ i = r.text.find(marker)
+ if r.status_code != 200 or i < 0:
+ return None
+ try:
+ meta, _ = json.JSONDecoder().raw_decode(r.text, i + len(marker))
+ except ValueError:
+ return None
+ subs = re.search(r'"content":"([^"]{1,30}(?:suscriptores|subscribers))"', r.text)
+ thumbs = (meta.get("avatar") or {}).get("thumbnails") or []
+ return {
+ "platform": "YouTube",
+ "user": u,
+ "url": meta.get("vanityChannelUrl") or f"https://www.youtube.com/@{u}",
+ "attrs": {
+ "Nombre": meta.get("title"),
+ "Bio": meta.get("description"),
+ "ID del canal": meta.get("externalId"),
+ "Suscriptores": subs.group(1) if subs else None,
+ "_avatar": thumbs[-1]["url"] if thumbs else None,
+ },
+ "bio": meta.get("description"),
+ }
+
+
+async def p_twitch(ctx, u):
+ if not re.match(r"^[A-Za-z0-9_]{3,25}$", u):
+ return None
+ q = ("query($l:String!){user(login:$l){login displayName description createdAt profileImageURL(width:300) "
+ "followers{totalCount} lastBroadcast{startedAt title}}}")
+ r = await ctx.http.post("https://gql.twitch.tv/gql", headers={"Client-Id": "kimne78kx3ncx6brgo4mv6wki5h1ko"},
+ json={"query": q, "variables": {"l": u.lower()}})
+ user = ((r.json() if r.status_code == 200 else {}).get("data") or {}).get("user")
+ if not user:
+ return None
+ lb = user.get("lastBroadcast") or {}
+ return {
+ "platform": "Twitch",
+ "user": user["login"],
+ "url": f"https://www.twitch.tv/{user['login']}",
+ "attrs": {
+ "Nombre visible": user.get("displayName"),
+ "Bio": user.get("description"),
+ "Seguidores": (user.get("followers") or {}).get("totalCount"),
+ "Creada": _date(user.get("createdAt")),
+ "Última emisión": _date(lb.get("startedAt")),
+ "Título última emisión": lb.get("title"),
+ "_avatar": user.get("profileImageURL"),
+ },
+ "bio": user.get("description"),
+ }
+
+
+IG_META = re.compile(r'<meta property="og:(title|description|image)" content="([^"]*)"')
+IG_COUNTS = re.compile(r"^([\d.,]+[KMB]?) Followers, ([\d.,]+[KMB]?) Following, ([\d.,]+[KMB]?) Posts")
+
+
+async def _instagram_preview(ctx, u):
+ """La API limita por IP muy rápido; la vista previa para enlaces (la que leen Facebook o WhatsApp) sigue respondiendo."""
+ r = await ctx.http.get(f"https://www.instagram.com/{u}/", headers={"User-Agent": "facebookexternalhit/1.1"})
+ page = re.search(r'"pageID":"(\w+)"', r.text) if r.status_code == 200 else None
+ if page and page.group(1) == "httpErrorPage":
+ return None
+ meta = {k: html.unescape(v) for k, v in IG_META.findall(r.text)}
+ if not page or page.group(1) != "profilePage" or "title" not in meta:
+ raise Blocked("Instagram")
+ m = re.match(r"^(.*?)\s*\(@([A-Za-z0-9_.]+)\)", meta["title"])
+ name, user = (m.group(1).strip(), m.group(2)) if m else (None, u)
+ counts = IG_COUNTS.match(meta.get("description", ""))
+ pid = re.search(r'"profile_id":"(\d+)"', r.text)
+ return {
+ "platform": "Instagram",
+ "user": user,
+ "url": f"https://www.instagram.com/{user}",
+ "attrs": {
+ "Nombre": name if name and name != user else None,
+ "Seguidores": counts and counts.group(1),
+ "Siguiendo": counts and counts.group(2),
+ "Publicaciones": counts and counts.group(3),
+ "ID de Instagram": pid and pid.group(1),
+ "Nota": "Datos de la vista previa pública (Instagram limitó su API): sin bio ni enlaces",
+ "_avatar": meta.get("image"),
+ },
+ "name": name,
+ }
+
+
+_PACE: dict[str, list] = {}
+
+
+async def _paced(platform: str, gap: float) -> None:
+ """Espacia las consultas a redes que limitan por IP en cuanto reciben varias seguidas."""
+ slot = _PACE.setdefault(platform, [asyncio.Lock(), 0.0])
+ async with slot[0]:
+ wait = slot[1] + gap - time.monotonic()
+ if wait > 0:
+ await asyncio.sleep(wait)
+ slot[1] = time.monotonic()
+
+
+async def p_instagram(ctx, u):
+ if not re.match(r"^[A-Za-z0-9_.]{1,30}$", u):
+ return None
+ await _paced("Instagram", 1.5)
+ r = await ctx.http.get(f"https://i.instagram.com/api/v1/users/web_profile_info/?username={u}",
+ headers={"x-ig-app-id": "936619743392459"})
+ if r.status_code == 404:
+ return None
+ if r.status_code != 200:
+ return await _instagram_preview(ctx, u)
+ user = ((r.json() or {}).get("data") or {}).get("user")
+ if not user:
+ return None
+ links = [l.get("url") for l in user.get("bio_links") or [] if l.get("url")] + [user.get("external_url")]
+ return {
+ "platform": "Instagram",
+ "user": user.get("username") or u,
+ "url": f"https://www.instagram.com/{user.get('username') or u}",
+ "attrs": {
+ "Nombre": user.get("full_name"),
+ "Bio": user.get("biography"),
+ "Seguidores": (user.get("edge_followed_by") or {}).get("count"),
+ "Siguiendo": (user.get("edge_follow") or {}).get("count"),
+ "Publicaciones": (user.get("edge_owner_to_timeline_media") or {}).get("count"),
+ "Privada": "Sí" if user.get("is_private") else None,
+ "Verificada": "Sí" if user.get("is_verified") else None,
+ "Categoría": user.get("category_name"),
+ "Teléfono de empresa": user.get("business_phone_number"),
+ "_avatar": user.get("profile_pic_url_hd") or user.get("profile_pic_url"),
+ },
+ "name": user.get("full_name"),
+ "emails": [user.get("business_email")],
+ "urls": links,
+ "bio": user.get("biography"),
+ }
+
+
+MOBILE_UA = ("Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 "
+ "(KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1")
+
+
+async def _tiktok_oembed(ctx, u):
+ """Respaldo: el servicio de incrustación sólo dice si el perfil existe y su nombre visible."""
+ r = await ctx.http.get("https://www.tiktok.com/oembed", params={"url": f"https://www.tiktok.com/@{u}"})
+ if r.status_code == 400:
+ return None
+ try:
+ d = r.json() if r.status_code == 200 else None
+ except ValueError:
+ d = None
+ if not isinstance(d, dict) or not d.get("author_url"):
+ raise Blocked("TikTok")
+ user = d["author_url"].rstrip("/").rsplit("@", 1)[-1] or u
+ return {
+ "platform": "TikTok",
+ "user": user,
+ "url": f"https://www.tiktok.com/@{user}",
+ "attrs": {"Nombre": d.get("author_name"), "Nota": "Datos mínimos (TikTok no dejó ver el perfil completo)"},
+ "name": d.get("author_name"),
+ }
+
+
+async def p_tiktok(ctx, u):
+ if not re.match(r"^[A-Za-z0-9_.]{2,24}$", u):
+ return None
+ await _paced("TikTok", 1.0)
+ # a un navegador de escritorio le sale el muro anti-bots; la versión móvil trae los datos del perfil
+ r = await ctx.http.get(f"https://www.tiktok.com/@{u}", headers={"User-Agent": MOBILE_UA})
+ m = re.search(r'<script id="__UNIVERSAL_DATA_FOR_REHYDRATION__"[^>]*>(.*?)</script>', r.text, re.S)
+ detail = None
+ if m:
+ try:
+ detail = json.loads(m.group(1))["__DEFAULT_SCOPE__"]["webapp.user-detail"]
+ except (ValueError, KeyError):
+ detail = None
+ if detail is None:
+ return await _tiktok_oembed(ctx, u)
+ if detail.get("statusCode") != 0:
+ return None
+ user = (detail.get("userInfo") or {}).get("user") or {}
+ stats = (detail.get("userInfo") or {}).get("stats") or {}
+ return {
+ "platform": "TikTok",
+ "user": user.get("uniqueId") or u,
+ "url": f"https://www.tiktok.com/@{user.get('uniqueId') or u}",
+ "attrs": {
+ "Nombre": user.get("nickname"),
+ "Bio": user.get("signature"),
+ "Seguidores": stats.get("followerCount"),
+ "Siguiendo": stats.get("followingCount"),
+ "Me gusta": stats.get("heartCount"),
+ "Vídeos": stats.get("videoCount"),
+ "Creada": _date(user.get("createTime")),
+ "Región": user.get("region"),
+ "Verificada": "Sí" if user.get("verified") else None,
+ "Privada": "Sí" if user.get("privateAccount") else None,
+ "_avatar": user.get("avatarLarger"),
+ },
+ "name": user.get("nickname"),
+ "bio": user.get("signature"),
+ }
+
+
+async def p_chesscom(ctx, u):
+ st, d = await ctx.get_json(f"https://api.chess.com/pub/player/{u.lower()}")
+ if st != 200 or not isinstance(d, dict) or not d.get("username"):
+ return None
+ return {
+ "platform": "Chess.com",
+ "user": d["username"],
+ "url": d.get("url") or f"https://www.chess.com/member/{d['username']}",
+ "attrs": {
+ "Nombre": d.get("name"),
+ "País": (d.get("country") or "").rsplit("/", 1)[-1] or None,
+ "Seguidores": d.get("followers"),
+ "Creada": _date(d.get("joined")),
+ "Última conexión": _date(d.get("last_online")),
+ "_avatar": d.get("avatar"),
+ },
+ "name": d.get("name"),
+ "location": d.get("location"),
+ }
+
+
+async def p_lichess(ctx, u):
+ st, d = await ctx.get_json(f"https://lichess.org/api/user/{u}")
+ if st != 200 or not isinstance(d, dict) or not d.get("username") or d.get("disabled"):
+ return None
+ prof = d.get("profile") or {}
+ name = prof.get("realName") or " ".join(x for x in (prof.get("firstName"), prof.get("lastName")) if x) or None
+ return {
+ "platform": "Lichess",
+ "user": d["username"],
+ "url": d.get("url") or f"https://lichess.org/@/{d['username']}",
+ "attrs": {"Nombre": name, "Bio": prof.get("bio"), "País": prof.get("flag") or prof.get("country"),
+ "Creada": _date(d.get("createdAt")), "Última conexión": _date(d.get("seenAt"))},
+ "name": name,
+ "location": prof.get("location"),
+ "bio": (prof.get("bio") or "") + " " + (prof.get("links") or ""),
+ }
+
+
+async def p_duolingo(ctx, u):
+ st, d = await ctx.get_json(f"https://www.duolingo.com/2017-06-30/users?username={u}")
+ users = (d or {}).get("users") if isinstance(d, dict) else None
+ match = [x for x in users or [] if (x.get("username") or "").lower() == u.lower()]
+ if st != 200 or not match:
+ return None
+ x = match[0]
+ pic = x.get("picture")
+ return {
+ "platform": "Duolingo",
+ "user": x["username"],
+ "url": f"https://www.duolingo.com/profile/{x['username']}",
+ "attrs": {
+ "Nombre": x.get("name"),
+ "Bio": x.get("bio"),
+ "Racha": x.get("streak"),
+ "XP total": x.get("totalXp"),
+ "Idiomas": [c.get("title") for c in x.get("courses") or [] if c.get("title")] or None,
+ "Creada": _date(x.get("creationDate")),
+ "_avatar": f"https:{pic}/xlarge" if pic and pic.startswith("//") else None,
+ },
+ "name": x.get("name"),
+ }
+
+
+async def p_roblox(ctx, u):
+ r = await ctx.http.post(
+ "https://users.roblox.com/v1/usernames/users", json={"usernames": [u], "excludeBannedUsers": False}
+ )
+ data = (r.json() or {}).get("data") if r.status_code == 200 else None
+ if not data:
+ return None
+ uid = data[0]["id"]
+ st, full = await ctx.get_json(f"https://users.roblox.com/v1/users/{uid}")
+ full = full if st == 200 and isinstance(full, dict) else {}
+ return {
+ "platform": "Roblox",
+ "user": data[0]["name"],
+ "url": f"https://www.roblox.com/users/{uid}/profile",
+ "attrs": {"Nombre visible": data[0].get("displayName"), "Bio": full.get("description"),
+ "Creada": _date(full.get("created")), "Baneado": full.get("isBanned") or None, "ID": uid},
+ "bio": full.get("description"),
+ }
+
+
+async def p_minecraft(ctx, u):
+ st, d = await ctx.get_json(f"https://api.mojang.com/users/profiles/minecraft/{u}")
+ if st != 200 or not isinstance(d, dict) or not d.get("id"):
+ return None
+ return {
+ "platform": "Minecraft",
+ "user": d["name"],
+ "url": f"https://namemc.com/profile/{d['name']}",
+ "attrs": {"UUID": d["id"], "_avatar": f"https://mc-heads.net/avatar/{d['id']}"},
+ }
+
+
+async def p_steam(ctx, u):
+ r = await ctx.http.get(f"https://steamcommunity.com/id/{u}/?xml=1")
+ if r.status_code != 200 or "<steamID64>" not in r.text:
+ return None
+ try:
+ root = ET.fromstring(r.text)
+ except ET.ParseError:
+ return None
+ g = lambda tag: (root.findtext(tag) or "").strip() or None # noqa: E731
+ return {
+ "platform": "Steam",
+ "user": u,
+ "url": f"https://steamcommunity.com/id/{u}",
+ "attrs": {
+ "Nombre visible": g("steamID"),
+ "Nombre real": g("realname"),
+ "SteamID64": g("steamID64"),
+ "Miembro desde": g("memberSince"),
+ "Resumen": _txt(g("summary")),
+ "_avatar": g("avatarFull"),
+ },
+ "name": g("realname"),
+ "location": g("location"),
+ "bio": _txt(g("summary")),
+ }
+
+
+async def p_devto(ctx, u):
+ st, d = await ctx.get_json(f"https://dev.to/api/users/by_username?url={u}")
+ if st != 200 or not isinstance(d, dict) or not d.get("username"):
+ return None
+ return {
+ "platform": "Dev.to",
+ "user": d["username"],
+ "url": f"https://dev.to/{d['username']}",
+ "attrs": {"Nombre": d.get("name"), "Bio": d.get("summary"), "Creada": d.get("joined_at"),
+ "_avatar": d.get("profile_image")},
+ "name": d.get("name"),
+ "location": d.get("location"),
+ "urls": [d.get("website_url")],
+ "linked": [("X/Twitter", d.get("twitter_username")), ("GitHub", d.get("github_username"))],
+ }
+
+
+async def p_dockerhub(ctx, u):
+ st, d = await ctx.get_json(f"https://hub.docker.com/v2/users/{u}/")
+ if st != 200 or not isinstance(d, dict) or not d.get("username"):
+ return None
+ return {
+ "platform": "Docker Hub",
+ "user": d["username"],
+ "url": f"https://hub.docker.com/u/{d['username']}",
+ "attrs": {"Nombre": d.get("full_name"), "Empresa": d.get("company"), "Creada": _date(d.get("date_joined")),
+ "_avatar": d.get("gravatar_url")},
+ "name": d.get("full_name"),
+ "location": d.get("location"),
+ "urls": [d.get("profile_url")],
+ }
+
+
+async def p_lobsters(ctx, u):
+ st, d = await ctx.get_json(f"https://lobste.rs/~{u}.json")
+ if st != 200 or not isinstance(d, dict) or not d.get("username"):
+ return None
+ avatar = d.get("avatar_url")
+ return {
+ "platform": "Lobsters",
+ "user": d["username"],
+ "url": f"https://lobste.rs/~{d['username']}",
+ "attrs": {"Bio": _txt(d.get("about")), "Karma": d.get("karma"), "Creada": _date(d.get("created_at")),
+ "Invitado por": d.get("invited_by_user"),
+ "_avatar": f"https://lobste.rs{avatar}" if avatar and avatar.startswith("/") else avatar},
+ "bio": _txt(d.get("about")),
+ "linked": [("GitHub", d.get("github_username")), ("X/Twitter", d.get("twitter_username"))],
+ }
+
+
+async def p_stackoverflow(ctx, u):
+ st, d = await ctx.get_json(
+ "https://api.stackexchange.com/2.3/users",
+ params={"inname": u, "site": "stackoverflow", "pagesize": 30, "order": "desc", "sort": "reputation"},
+ )
+ if st != 200 or not isinstance(d, dict):
+ return None
+ exact = [x for x in d.get("items") or [] if (x.get("display_name") or "").lower() == u.lower()]
+ if not exact:
+ return None
+ x = exact[0]
+ return {
+ "platform": "Stack Overflow",
+ "user": x.get("display_name"),
+ "url": x.get("link") or f"https://stackoverflow.com/users/{x['user_id']}",
+ "attrs": {"Reputación": x.get("reputation"), "Creada": _date(x.get("creation_date")),
+ "Última conexión": _date(x.get("last_access_date")), "ID": x.get("user_id"),
+ "Otros con el mismo nombre": len(exact) - 1 or None, "_avatar": x.get("profile_image")},
+ "location": x.get("location"),
+ "urls": [x.get("website_url")],
+ }
+
+
+PROFILE_CHECKS = {
+ "GitHub": p_github, "GitLab": p_gitlab, "Keybase": p_keybase,
+ "Hacker News": p_hackernews, "Bluesky": p_bluesky, "Mastodon": p_mastodon, "Telegram": p_telegram,
+ "Chess.com": p_chesscom, "Lichess": p_lichess, "Duolingo": p_duolingo, "Roblox": p_roblox,
+ "Minecraft": p_minecraft, "Steam": p_steam, "Dev.to": p_devto, "Docker Hub": p_dockerhub,
+ "X/Twitter": p_twitter, "Reddit": p_reddit, "YouTube": p_youtube, "Twitch": p_twitch,
+ "Instagram": p_instagram, "TikTok": p_tiktok, "Lobsters": p_lobsters, "Stack Overflow": p_stackoverflow,
+}
+# nombres equivalentes en la base de Sherlock, para no repetirlos en el barrido
+COVERED_BY_PROFILES = {n.lower() for n in PROFILE_CHECKS} | {
+ "hackernews", "chess", "docker hub", "devto", "dev community", "mastodon.social", "mastodon (mastodon.social)",
+ "steam community (user)", "steamid", "minecraft", "roblox", "lichess", "bluesky", "twitter", "x",
+ "lobsters", "stackoverflow", "stack overflow",
+}
+
+
+def _norm_url(u: str | None) -> str | None:
+ if not u or not isinstance(u, str):
+ return None
+ u = u.strip()
+ if not u:
+ return None
+ if not u.startswith("http"):
+ u = "https://" + u
+ return u
+
+
+def add_profile(ctx, res: dict, parent: str | None = None) -> str | None:
+ attrs = {k: v for k, v in res.get("attrs", {}).items()}
+ attrs.update({"Plataforma": res["platform"], "Usuario": res.get("user"), "_links": [["Abrir perfil", res["url"]]]})
+ acc = ctx.add("account", res["url"], attrs, rel="cuenta", parent=parent, pivot=False)
+ if not acc:
+ return None
+ if res.get("name") and len(res["name"]) > 2 and " " in res["name"].strip():
+ ctx.add("person", res["name"], rel="nombre", parent=acc, pivot=False)
+ if res.get("location"):
+ ctx.add("location", res["location"], rel="ubicación declarada", parent=acc)
+ text = " ".join(str(x) for x in (res.get("bio"), attrs.get("Bio")) if x)
+ for e in list(res.get("emails") or []) + clean_emails(text):
+ if e and "@" in e:
+ ctx.add("email", e, rel="email", parent=acc)
+ urls = [_norm_url(u) for u in (res.get("urls") or [])] + URL_RE.findall(text)
+ linked = [(p, x) for p, x in res.get("linked") or [] if x]
+ for u in dict.fromkeys(u for u in urls if u):
+ s = social_from_url(u)
+ if s:
+ linked.append(s)
+ else:
+ ctx.add("url", u, {"_links": [["Abrir", u]]}, rel="web", parent=acc, pivot=False)
+ current = (ctx.value or "").lower()
+ for platform, user in linked:
+ user = user.strip().lstrip("@")
+ tpl = PROFILE_URLS.get(platform)
+ if not tpl or platform == "Mastodon":
+ continue
+ url = tpl.format(user)
+ other = ctx.add("account", url, {"Plataforma": platform, "Usuario": user, "_links": [["Abrir perfil", url]],
+ "Verificación": f"Enlazada desde {res['platform']}"},
+ rel="enlaza a", parent=acc, pivot=False)
+ if user.lower() != current and other:
+ ctx.add("username", user, rel="usuario", parent=other)
+ return acc
+
+
+@register
+class UsernameProfiles(Module):
+ name = "username_profiles"
+ title = "Perfiles con datos"
+ description = "Busca el usuario en plataformas con API pública y extrae nombre, bio, ubicación, emails de commits y cuentas enlazadas."
+ inputs = ("username",)
+ optional_keys = ("github",)
+ sources = tuple(PROFILE_CHECKS)
+ timeout = 60
+
+ async def run(self, ctx):
+ u = ctx.value
+ results = await asyncio.gather(*(f(ctx, u) for f in PROFILE_CHECKS.values()), return_exceptions=True)
+ found, blocked = [], []
+ for res in results:
+ if isinstance(res, dict):
+ add_profile(ctx, res)
+ found.append(res["platform"])
+ elif isinstance(res, Blocked):
+ blocked.append(str(res))
+ ctx.enrich({"_bloq_perfiles": blocked}, replace=True)
+ msg = f"Encontrado en {len(found)} de {len(PROFILE_CHECKS)}: {', '.join(found)}" if found else "Sin perfiles"
+ if blocked:
+ msg += f" · no se pudo comprobar (limitado): {', '.join(blocked)}"
+ ctx.message = msg
+
+
+# ---------------------------------------------------------------------------
+# Barrido masivo (formato de datos compatible con Sherlock)
+# ---------------------------------------------------------------------------
+
+SHERLOCK_URL = "https://raw.githubusercontent.com/sherlock-project/sherlock/master/sherlock_project/resources/data.json"
+WAF_MARKERS = (
+ ".loading-spinner{visibility:hidden}body.no-js .challenge-running{display:none}",
+ '<span id="challenge-error-text">',
+ "AwsWafIntegration.forceRefreshToken",
+ "perimeterxIdentifiers",
+ "_cf_chl_opt",
+ "cf-browser-verification",
+)
+_sites_cache: tuple[float, dict] | None = None
+
+
+async def load_sites(http: httpx.AsyncClient) -> dict:
+ global _sites_cache
+ if _sites_cache and time.time() - _sites_cache[0] < 3600:
+ return _sites_cache[1]
+ sites: dict = {}
+ if settings.get("sherlock_db", True):
+ cache = DATA_DIR / "sherlock.json"
+ stale = not cache.exists() or time.time() - cache.stat().st_mtime > 7 * 86400
+ if stale:
+ try:
+ r = await http.get(SHERLOCK_URL, timeout=30)
+ if r.status_code == 200 and isinstance(r.json(), dict):
+ cache.write_text(r.text, encoding="utf-8")
+ except (httpx.HTTPError, ValueError):
+ pass
+ if cache.exists():
+ try:
+ data = json.loads(cache.read_text(encoding="utf-8"))
+ sites.update({k: v for k, v in data.items() if not k.startswith("$") and isinstance(v, dict) and "url" in v})
+ except ValueError:
+ pass
+ sites.update(json.loads((RESOURCES_DIR / "sites.json").read_text(encoding="utf-8")))
+ _sites_cache = (time.time(), sites)
+ return sites
+
+
+def _as_list(x):
+ if x is None:
+ return []
+ return x if isinstance(x, list) else [x]
+
+
+async def check_site(http: httpx.AsyncClient, site: dict, username: str, timeout: float) -> str:
+ rx = site.get("regexCheck")
+ if rx:
+ try:
+ if not re.search(rx, username):
+ return "invalid"
+ except re.error:
+ pass
+ probe = (site.get("urlProbe") or site["url"]).replace("{}", username)
+ payload = site.get("request_payload")
+ if payload is not None:
+ payload = json.loads(json.dumps(payload).replace("{}", username))
+ types = _as_list(site.get("errorType"))
+ method = (site.get("request_method") or "GET").upper()
+ try:
+ r = await http.request(
+ method, probe, json=payload, headers=site.get("headers") or None, timeout=timeout,
+ follow_redirects="response_url" not in types,
+ )
+ except (httpx.HTTPError, ValueError):
+ return "error"
+ text = r.text if len(r.content) < 3_000_000 else r.text[:3_000_000]
+ if r.status_code == 429 or any(m in text for m in WAF_MARKERS):
+ return "blocked"
+ for t in types:
+ if t == "message":
+ if any(m and m in text for m in _as_list(site.get("errorMsg"))):
+ return "missing"
+ elif t == "status_code":
+ codes = _as_list(site.get("errorCode"))
+ if r.status_code in codes or not 200 <= r.status_code < 300:
+ return "missing"
+ elif t == "response_url":
+ if not 200 <= r.status_code < 300:
+ return "missing"
+ return "found"
+
+
+def _random_username(site: dict) -> str | None:
+ rx = site.get("regexCheck")
+ for _ in range(5):
+ cand = "zq" + "".join(random.choices(string.ascii_lowercase, k=10))
+ try:
+ if not rx or re.search(rx, cand):
+ return cand
+ except re.error:
+ return cand
+ return None
+
+
+def sweep_targets(sites: dict) -> dict:
+ nsfw = settings.get("include_nsfw", False)
+ return {
+ name: s for name, s in sites.items()
+ if (nsfw or not s.get("isNSFW")) and name.lower() not in COVERED_BY_PROFILES
+ }
+
+
+async def sweep_sites(ctx, sites: dict, u: str, concurrency: int, timeout: float, pause: float = 0) -> dict:
+ """Comprueba el usuario en cada sitio; lo que no se pudo comprobar queda en stats["pending"] (sitio → URL)."""
+ sem = asyncio.Semaphore(concurrency)
+ stats = {"found": 0, "blocked": 0, "error": 0, "false_positive": 0, "pending": {}}
+
+ async def one(name, site):
+ async with sem:
+ if pause:
+ await asyncio.sleep(pause)
+ res = await check_site(ctx.http, site, u, timeout)
+ url = site["url"].replace("{}", u)
+ if res == "found":
+ fake = _random_username(site)
+ if fake and await check_site(ctx.http, site, fake, timeout) == "found":
+ stats["false_positive"] += 1
+ return
+ stats["found"] += 1
+ ctx.add(
+ "account", url,
+ {"Plataforma": name, "Usuario": u, "_links": [["Abrir perfil", url]],
+ "Verificación": "Existe (comprobado contra usuario inventado)"},
+ rel="cuenta", pivot=False,
+ )
+ elif res in ("blocked", "error"):
+ stats[res] += 1
+ stats["pending"][name] = url
+
+ await asyncio.gather(*(one(n, s) for n, s in sites.items()))
+ return stats
+
+
+@register
+class UsernameSweep(Module):
+ name = "username_sweep"
+ title = "Barrido de usuario (400+ sitios)"
+ description = "Comprueba si el usuario existe en cientos de webs y descarta falsos positivos repitiendo la prueba con un usuario inventado."
+ inputs = ("username",)
+ sources = ("Base de sitios de Sherlock", "Lista propia")
+ timeout = 300
+
+ async def run(self, ctx):
+ u = ctx.value
+ if not re.match(r"^[\w.\-]{2,40}$", u, re.UNICODE):
+ raise Skip("El usuario contiene caracteres que las webs no aceptan")
+ selected = sweep_targets(await load_sites(ctx.http))
+ stats = await sweep_sites(ctx, selected, u, 48, float(settings.get("username_timeout", 15)))
+ ctx.enrich({"_bloq_sitios": stats["pending"]}, replace=True)
+ ctx.message = (
+ f"{stats['found']} perfiles en {len(selected)} sitios · {stats['false_positive']} falsos positivos descartados"
+ f" · {stats['blocked']} bloqueados · {stats['error']} sin respuesta"
+ )
+
+
+@register
+class RetryBlocked(Module):
+ name = "retry_blocked"
+ title = "Reintentar lo bloqueado"
+ description = ("Vuelve a probar, más despacio y en varias rondas, las redes y sitios que limitaron o bloquearon la "
+ "búsqueda. Lo que siga bloqueado (protecciones anti-bots) queda en una lista para que lo abras tú.")
+ inputs = ("username",)
+ sources = ("Perfiles con datos", "Barrido de usuario (400+ sitios)")
+ timeout = 300
+ deep = True
+
+ async def run(self, ctx):
+ u = ctx.value
+ a = ctx.entity.get("attrs") or {}
+ before = set(ctx.job.created)
+ # sin registro de lo bloqueado (casos analizados con versiones anteriores) se repite todo
+
+ async def profiles():
+ pending = [p for p in (a["_bloq_perfiles"] if "_bloq_perfiles" in a else PROFILE_CHECKS) if p in PROFILE_CHECKS]
+ for wait in (0, 8, 20):
+ if not pending:
+ break
+ await asyncio.sleep(wait)
+ res = await asyncio.gather(*(PROFILE_CHECKS[p](ctx, u) for p in pending), return_exceptions=True)
+ still = []
+ for p, r in zip(pending, res):
+ if isinstance(r, dict):
+ add_profile(ctx, r)
+ elif isinstance(r, Blocked):
+ still.append(p)
+ pending = still
+ return pending
+
+ async def sites():
+ if not re.match(r"^[\w.\-]{2,40}$", u, re.UNICODE):
+ return {}
+ every = sweep_targets(await load_sites(ctx.http))
+ if "_bloq_sitios" in a:
+ pending = {n: s for n, s in every.items() if n in a["_bloq_sitios"]}
+ else:
+ pending = {n: every[n] for n in (await sweep_sites(ctx, every, u, 48, 15))["pending"]}
+ await asyncio.sleep(5)
+ return (await sweep_sites(ctx, pending, u, 6, 25, pause=0.3))["pending"] if pending else {}
+
+ left_profiles, left_sites = await asyncio.gather(profiles(), sites())
+ ctx.enrich({"_bloq_perfiles": left_profiles, "_bloq_sitios": left_sites}, replace=True)
+ new = [x for x in ctx.job.created if x not in before and x.startswith("account:")]
+ msg = [f"{len(new)} cuentas nuevas" if new else "Nada nuevo"]
+ if left_profiles:
+ msg.append(f"siguen limitando: {', '.join(left_profiles)}")
+ if left_sites:
+ msg.append(f"{len(left_sites)} sitios con protección anti-bots: revísalos a mano en el panel")
+ ctx.message = " · ".join(msg)
+
+
+# ---------------------------------------------------------------------------
+# Variantes del usuario (búsqueda a fondo, a petición)
+# ---------------------------------------------------------------------------
+
+STRIP_PREFIXES = ("private", "priv", "official", "oficial", "real", "its", "iam", "the", "soy", "not")
+STRIP_SUFFIXES = ("private", "priv", "official", "oficial", "real", "backup", "bkp", "alt", "spam", "fake", "xx")
+EXPANSIONS = (
+ "{c}_", "_{c}", "{c}__", "priv.{c}", "priv_{c}", "{c}.priv", "{c}_priv", "{c}priv", "real{c}", "real.{c}",
+ "its{c}", "{c}.oficial", "{c}_oficial", "{c}official", "{c}.official", "{c}2", "{c}_2", "{c}x", "x{c}", "the{c}",
+)
+VARIANT_CHECKS = {
+ "Instagram": p_instagram, "TikTok": p_tiktok, "X/Twitter": p_twitter,
+ "Telegram": p_telegram, "Twitch": p_twitch, "YouTube": p_youtube,
+}
+VALID_USER = re.compile(r"^(?!.*\.\.)[a-z0-9_][a-z0-9_.]{1,29}(?<!\.)$")
+
+
+def _strip_once(c: str, digits: bool = True) -> set[str]:
+ out = set()
+ for p in STRIP_PREFIXES:
+ for sep in (".", "_", "-", ""):
+ rest = c[len(p + sep):]
+ if c.startswith(p + sep) and len(rest) >= 3 and (sep or len(p) >= 4):
+ out.add(rest)
+ for s in STRIP_SUFFIXES:
+ for sep in (".", "_", "-", ""):
+ rest = c[: -len(sep + s)]
+ if c.endswith(sep + s) and len(rest) >= 3 and (sep or len(s) >= 4):
+ out.add(rest)
+ if digits and re.search(r"[a-z]\d{1,4}$", c):
+ out.add(re.sub(r"\d+$", "", c))
+ return {x.strip("._-") for x in out if len(x.strip("._-")) >= 3}
+
+
+# ---- familias de alias: el mismo apodo escrito de distintas formas (xxlunaxx, luunna, lun4_…)
+
+LEET = {"0": "o", "1": "i", "3": "e", "4": "a", "5": "s", "7": "t", "@": "a", "$": "s"}
+TO_LEET = {v: k for k, v in LEET.items() if k.isdigit()}
+
+
+def alias_key(u: str) -> str:
+ """Esqueleto del alias: sin «priv.», separadores, números de adorno, números en lugar de letras ni letras repetidas."""
+ s = u.lower().strip().lstrip("@")
+ for _ in range(2):
+ st = _strip_once(s, digits=False)
+ if st:
+ s = min(st, key=len)
+ s = re.sub(r"[^a-z0-9@$]", "", s)
+ s = re.sub(r"\d{2,}$", "", s)
+ s = "".join(LEET.get(c, c) for c in s)
+ return re.sub(r"\d", "", re.sub(r"(.)\1+", r"\1", s))
+
+
+def _common(a: str, b: str) -> str:
+ best = ""
+ for i in range(len(a)):
+ for j in range(i + len(best) + 1, len(a) + 1):
+ if a[i:j] not in b:
+ break
+ best = a[i:j]
+ return best
+
+
+def alias_related(a: str, b: str) -> bool:
+ ka, kb = alias_key(a), alias_key(b)
+ n = len(_common(ka, kb))
+ return n >= 4 and n >= 0.6 * min(len(ka), len(kb))
+
+
+def alias_root(members: list[str]) -> str:
+ keys = [alias_key(m) for m in members]
+ root = keys[0]
+ for k in keys[1:]:
+ root = _common(root, k)
+ return root if len(root) >= 3 else min(keys, key=len)
+
+
+def alias_families(names: list[str]) -> list[list[str]]:
+ names = list(dict.fromkeys(n for n in names if alias_key(n)))
+ parent = list(range(len(names)))
+
+ def find(i):
+ while parent[i] != i:
+ parent[i] = parent[parent[i]]
+ i = parent[i]
+ return i
+
+ for i in range(len(names)):
+ for j in range(i + 1, len(names)):
+ if alias_related(names[i], names[j]):
+ parent[find(i)] = find(j)
+ groups: dict[int, list[str]] = {}
+ for i, n in enumerate(names):
+ groups.setdefault(find(i), []).append(n)
+ return [g for g in groups.values() if len(g) >= 2]
+
+
+def family_variants(members: list[str]) -> list[str]:
+ """Combina lo que se repite en la familia: raíz + los prefijos/sufijos vistos + su forma de escribir (0 por o, letras dobles)."""
+ root = alias_root(members)
+ if len(root) < 3:
+ return []
+ pres, sufs = {""}, {""}
+ for k in (alias_key(m) for m in members):
+ i = k.find(root)
+ if i >= 0:
+ pres.add(k[:i])
+ sufs.add(k[i + len(root):])
+ low = [m.lower() for m in members]
+ leet = {LEET[d] for m in low for d in m if d in LEET and d.isdigit()}
+ doubles = {c for m in low for c in re.findall(r"([a-z])\1", m)}
+ out: list[str] = []
+ for b in sorted({p + root + s for p in pres for s in sufs}, key=lambda x: (len(x), x)):
+ forms = [b, "".join(TO_LEET[c] if c in leet else c for c in b)]
+ for f in dict.fromkeys(forms):
+ out.append(f)
+ out += [f[:i] + d + f[i:] for d in sorted(doubles) if (i := f.find(d, 1)) > 0]
+ return out
+
+
+def _mutations(u: str) -> list[str]:
+ """Cambios de una letra típicos de los alias: quitar o duplicar letras y números en lugar de letras."""
+ out = [re.sub(r"(.)\1+", r"\1", u), "".join(LEET.get(c, c) if c.isdigit() else c for c in u)]
+ for i, c in enumerate(u):
+ if c in TO_LEET:
+ out.append(u[:i] + TO_LEET[c] + u[i + 1:])
+ elif c in LEET and c.isdigit():
+ out.append(u[:i] + LEET[c] + u[i + 1:])
+ for i, c in enumerate(u):
+ if i and c.isalpha() and (i + 1 >= len(u) or u[i + 1] != c) and u[i - 1] != c:
+ out.append(u[:i + 1] + c + u[i + 1:])
+ return out
+
+
+def _name_tokens(s: str | None) -> list[str]:
+ """Palabras de un nombre visible, sin letras decorativas (𝔉𝔯𝔞𝔫𝔫𝔶 → frany), tildes ni letras repetidas."""
+ s = unicodedata.normalize("NFKD", unicodedata.normalize("NFKC", s or "")).lower()
+ s = "".join(c if c.isalpha() else " " for c in s if not unicodedata.combining(c))
+ return [re.sub(r"(.)\1+", r"\1", t) for t in s.split()]
+
+
+def known_names(entities: list[dict]) -> dict[str, str]:
+ """Palabras de los nombres ya reunidos en el caso (personas y nombres de sus cuentas) → nombre original."""
+ out: dict[str, str] = {}
+ for e in entities:
+ a = e.get("attrs") or {}
+ if a.get("_verdict") == "descartada":
+ continue
+ if e["type"] == "person" or (e["type"] == "username" and not re.match(r"^[\w.\-]+$", e["value"])):
+ names = [e["value"]] # un «usuario» con espacios o símbolos es en realidad un nombre visible
+ elif e["type"] == "account":
+ names = [a.get(k) for k in ("Nombre", "Nombre visible", "Nombre real")]
+ else:
+ names = []
+ for n in names:
+ if isinstance(n, str):
+ for t in _name_tokens(n):
+ if len(t) >= 4:
+ out.setdefault(t, n.strip())
+ return out
+
+
+def name_match(name: str | None, known: dict[str, str], ignore: str) -> str | None:
+ """Nombre del caso con el que coincide el nombre visible; no cuenta lo que sólo repite el propio alias."""
+ for t in _name_tokens(name):
+ if len(t) < 4 or t in ignore:
+ continue
+ for k, orig in known.items():
+ if k not in ignore and (k == t or (min(len(k), len(t)) >= 5 and (k in t or t in k))):
+ return orig
+ return None
+
+
+def username_variants(u: str, limit: int = 36, family: list[str] | None = None, skip: set[str] | None = None) -> list[str]:
+ """Formas en que la misma persona pudo escribir su usuario en otra red (o antes de cambiarlo)."""
+ u = u.lower().strip().lstrip("@")
+ cores = [u]
+ for _ in range(2):
+ for c in list(cores):
+ cores += [x for x in sorted(_strip_once(c)) if x not in cores]
+ stripped = cores[1:]
+ ordered: list[str] = family_variants(family)[:30] if family else []
+ ordered += stripped
+ ordered += _mutations(stripped[0] if stripped else u)
+ for c in cores:
+ parts = [p for p in re.split(r"[._\-]+", c) if p]
+ if len(parts) > 1:
+ for seq in (parts, parts[::-1]):
+ ordered += [".".join(seq), "_".join(seq), "".join(seq)]
+ base = stripped[:2] or [re.sub(r"[._\-]", "", u)]
+ for c in base:
+ ordered += [t.format(c=c) for t in EXPANSIONS]
+ seen, out = {u} | (skip or set()), []
+ for v in ordered:
+ if v not in seen and VALID_USER.match(v):
+ seen.add(v)
+ out.append(v)
+ return out[:limit]
+
+
+@register
+class UsernameVariants(Module):
+ name = "username_variants"
+ title = "Variantes del usuario"
+ description = ("Prueba formas parecidas del usuario (sin «priv.», con guion bajo, con puntos, letras dobles, 0 por o…) "
+ "en Instagram, TikTok, X, Telegram, Twitch y YouTube. Si en el caso hay otros alias de la misma familia, "
+ "combina lo que tienen en común. No llena el grafo: deja la lista en el panel para que añadas sólo las que "
+ "te interesen.")
+ inputs = ("username",)
+ sources = tuple(VARIANT_CHECKS)
+ timeout = 240
+ deep = True
+
+ async def run(self, ctx):
+ entities = db.graph(ctx.case_id)["entities"]
+ in_case = {e["value"].lower() for e in entities if e["type"] == "username"}
+ family = next((f for f in alias_families(sorted(in_case)) if ctx.value.lower() in f), None)
+ known = known_names(entities)
+ root = alias_root(family) if family else alias_key(ctx.value)
+ variants = username_variants(ctx.value, 48, family, in_case)
+ if not variants:
+ raise Skip("No se me ocurren variantes para este usuario")
+ sems = {p: asyncio.Semaphore(3) for p in VARIANT_CHECKS}
+ found: dict[str, list] = {}
+ blocked: set[str] = set()
+
+ async def one(v, platform, check):
+ async with sems[platform]:
+ try:
+ res = await check(ctx, v)
+ except Blocked:
+ blocked.add(platform)
+ return
+ except (httpx.HTTPError, ValueError, KeyError, TypeError, AttributeError):
+ return
+ if not isinstance(res, dict):
+ return
+ a = res.get("attrs") or {}
+ name = a.get("Nombre") or a.get("Nombre visible") or res.get("name")
+ found.setdefault(v, []).append({
+ "platform": platform, "url": res["url"], "user": res.get("user") or v, "name": name,
+ "followers": a.get("Seguidores") or a.get("Suscriptores"),
+ "private": a.get("Privada"), "avatar": a.get("_avatar"),
+ "match": name_match(name, known, f"{alias_key(v)}|{root}"),
+ })
+
+ await asyncio.gather(*(one(v, p, f) for v in variants for p, f in VARIANT_CHECKS.items()))
+ hits = {v: sorted(found[v], key=lambda x: (not x["match"], x["platform"])) for v in variants if v in found}
+ likely = [v for v, h in hits.items() if any(x["match"] for x in h)]
+ hits = {v: hits[v] for v in likely + [v for v in hits if v not in likely]}
+ ctx.enrich({
+ "_variantes": hits or None,
+ "_variantes_probadas": len(variants),
+ "_variantes_bloqueadas": sorted(blocked) or None,
+ }, replace=True)
+ ctx.enriched = bool(hits)
+ ctx.message = (f"{len(hits)} de {len(variants)} variantes existen en alguna red" if hits
+ else f"Ninguna de las {len(variants)} variantes existe en las redes probadas")
+ if likely:
+ ctx.message += f" · {len(likely)} con un nombre que ya está en el caso"
+ if family:
+ ctx.message += f" · familia «{root}» ({len(family)} alias)"
+ if blocked:
+ ctx.message += f" · limitado: {', '.join(sorted(blocked))}"
diff --git a/app/modules/web.py b/app/modules/web.py
new file mode 100644
index 0000000..62c294c
--- /dev/null
+++ b/app/modules/web.py
@@ -0,0 +1,163 @@
+import base64
+import time
+from urllib.parse import urlparse
+
+from ..util import parse_page
+from .base import Module, register
+from .domain import add_page
+
+SHORTENERS = {"bit.ly", "t.co", "tinyurl.com", "goo.gl", "ow.ly", "is.gd", "buff.ly", "cutt.ly", "rebrand.ly",
+ "shorturl.at", "tiny.cc", "rb.gy", "lnkd.in", "s.id", "t.ly"}
+
+
+@register
+class UrlFetch(Module):
+ name = "url_fetch"
+ title = "Análisis de la URL"
+ description = "Sigue las redirecciones (desacorta enlaces) y extrae título, emails y redes sociales de la página."
+ inputs = ("url",)
+ sources = ("HTTP directo",)
+
+ async def run(self, ctx):
+ r = await ctx.http.get(ctx.value, timeout=20)
+ chain = [str(h.url) for h in r.history] + [str(r.url)]
+ host = urlparse(str(r.url)).hostname or ""
+ orig_host = urlparse(ctx.value).hostname or ""
+ ctx.enrich({
+ "Estado HTTP": r.status_code,
+ "Acortador": "Sí" if orig_host in SHORTENERS else None,
+ "Redirecciones": chain if len(chain) > 1 else None,
+ "URL final": str(r.url) if len(chain) > 1 else None,
+ "Tipo de contenido": r.headers.get("content-type"),
+ })
+ if host:
+ ctx.add("domain", host.removeprefix("www."), rel="alojada en")
+ if len(chain) > 1:
+ ctx.add("url", str(r.url), {"_links": [["Abrir", str(r.url)]]}, rel="redirige a", pivot=False)
+ if "html" in (r.headers.get("content-type") or ""):
+ html = r.text[:2_000_000]
+ add_page(ctx, parse_page(html, str(r.url)), r.headers, html)
+
+
+def _vt_stats(attrs: dict) -> dict:
+ s = attrs.get("last_analysis_stats") or {}
+ total = sum(v for v in s.values() if isinstance(v, int))
+ return {
+ "VirusTotal: detecciones": f"{s.get('malicious', 0)} maliciosos, {s.get('suspicious', 0)} sospechosos de {total}" if total else None,
+ "VirusTotal: reputación": attrs.get("reputation"),
+ }
+
+
+@register
+class VirusTotal(Module):
+ name = "virustotal"
+ title = "VirusTotal"
+ description = "Detecciones de antivirus y reputación para dominios, IPs, URLs y archivos (hash)."
+ inputs = ("domain", "ip", "url", "hash")
+ keys = ("virustotal",)
+ sources = ("VirusTotal",)
+
+ async def run(self, ctx):
+ t, v = ctx.entity["type"], ctx.value
+ path = {
+ "domain": f"domains/{v}",
+ "ip": f"ip_addresses/{v}",
+ "url": "urls/" + base64.urlsafe_b64encode(v.encode()).decode().rstrip("="),
+ "hash": f"files/{v}",
+ }[t]
+ st, d = await ctx.get_json(f"https://www.virustotal.com/api/v3/{path}", headers={"x-apikey": ctx.key("virustotal")})
+ if st == 404:
+ ctx.message = "VirusTotal no lo conoce"
+ return
+ if st != 200 or not isinstance(d, dict):
+ ctx.message = f"VirusTotal respondió {st}"
+ return
+ a = (d.get("data") or {}).get("attributes") or {}
+ out = _vt_stats(a)
+ gui = {"domain": f"domain/{v}", "ip": f"ip-address/{v}", "url": f"url/{path.split('/')[1]}", "hash": f"file/{v}"}[t]
+ out["_links"] = [["Ver en VirusTotal", f"https://www.virustotal.com/gui/{gui}"]]
+ if t == "domain":
+ out["VirusTotal: categorías"] = sorted(set((a.get("categories") or {}).values())) or None
+ if t == "hash":
+ out.update({
+ "Nombre de archivo": a.get("meaningful_name"),
+ "Otros nombres": (a.get("names") or [])[:10] or None,
+ "Tipo de archivo": a.get("type_description"),
+ "Tamaño (bytes)": a.get("size"),
+ "Clasificación": ((a.get("popular_threat_classification") or {}).get("suggested_threat_label")),
+ "MD5": a.get("md5"), "SHA1": a.get("sha1"), "SHA256": a.get("sha256"),
+ "Primera vez visto": a.get("first_submission_date")
+ and time.strftime("%Y-%m-%d", time.gmtime(a["first_submission_date"])),
+ })
+ ctx.enrich(out)
+
+
+@register
+class UrlScan(Module):
+ name = "urlscan"
+ title = "URLScan.io"
+ description = "Escaneos públicos anteriores del dominio: capturas, IPs y páginas vistas."
+ inputs = ("domain", "url")
+ optional_keys = ("urlscan",)
+ sources = ("URLScan.io",)
+
+ async def run(self, ctx):
+ if ctx.entity["type"] == "domain":
+ query = f"domain:{ctx.value}"
+ else:
+ query = 'task.url:"' + ctx.value.replace('"', "") + '"'
+ headers = {"API-Key": ctx.key("urlscan")} if ctx.key("urlscan") else {}
+ st, d = await ctx.get_json("https://urlscan.io/api/v1/search/", params={"q": query, "size": 20},
+ headers=headers)
+ if st in (401, 403, 429):
+ ctx.message = "URLScan requiere clave o se superó el límite"
+ return
+ results = (d or {}).get("results") if isinstance(d, dict) else None
+ if not results:
+ return
+ ips, links = set(), []
+ for res in results:
+ page = res.get("page") or {}
+ if page.get("ip"):
+ ips.add(page["ip"])
+ if res.get("result") and len(links) < 5:
+ links.append([f"Escaneo {(res.get('task') or {}).get('time', '')[:10]}",
+ res["result"].replace("/api/v1/result/", "/result/")])
+ ctx.enrich({"URLScan: escaneos": (d or {}).get("total"), "_links": links})
+ for ip in list(ips)[:10]:
+ ctx.add("ip", ip, rel="visto en (URLScan)", pivot=False)
+
+
+@register
+class AbuseCh(Module):
+ name = "abusech"
+ title = "abuse.ch (URLhaus/ThreatFox)"
+ description = "Comprueba si el dominio, IP o URL distribuye malware o es infraestructura de botnets."
+ inputs = ("domain", "ip", "url")
+ keys = ("abusech",)
+ sources = ("URLhaus", "ThreatFox")
+
+ async def run(self, ctx):
+ h = {"Auth-Key": ctx.key("abusech")}
+ t, v = ctx.entity["type"], ctx.value
+ if t == "url":
+ r = await ctx.http.post("https://urlhaus-api.abuse.ch/v1/url/", data={"url": v}, headers=h)
+ else:
+ r = await ctx.http.post("https://urlhaus-api.abuse.ch/v1/host/", data={"host": v}, headers=h)
+ uh = r.json() if r.status_code == 200 else {}
+ out = {}
+ if uh.get("query_status") == "ok":
+ out["URLhaus: URLs maliciosas"] = uh.get("url_count") or 1
+ out["URLhaus: amenaza"] = uh.get("threat") or None
+ tags = {tag for u in uh.get("urls") or [] for tag in (u.get("tags") or [])}
+ out["URLhaus: etiquetas"] = sorted(tags) or None
+ r = await ctx.http.post("https://threatfox-api.abuse.ch/api/v1/", json={"query": "search_ioc", "search_term": v},
+ headers=h)
+ tf = r.json() if r.status_code == 200 else {}
+ if tf.get("query_status") == "ok" and isinstance(tf.get("data"), list):
+ out["ThreatFox: IOCs"] = len(tf["data"])
+ out["ThreatFox: malware"] = sorted({x.get("malware_printable") for x in tf["data"] if x.get("malware_printable")})
+ if out:
+ ctx.enrich(out)
+ else:
+ ctx.message = "Sin rastro en URLhaus ni ThreatFox"
diff --git a/app/modules/websearch.py b/app/modules/websearch.py
new file mode 100644
index 0000000..a4bc088
--- /dev/null
+++ b/app/modules/websearch.py
@@ -0,0 +1,280 @@
+"""Búsqueda web real por nombre de persona, con el nombre completo y sus formas abreviadas."""
+import asyncio
+import base64
+import html
+import re
+from urllib.parse import parse_qs, unquote, urlparse
+
+import httpx
+
+from ..config import settings
+from ..db import db
+from .base import Module, register
+from .people import name_match, name_variants
+
+UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
+ "Chrome/130.0 Safari/537.36", "Accept-Language": "es-CL,es;q=0.9,en;q=0.5"}
+
+SOCIAL = "(site:linkedin.com/in OR site:facebook.com OR site:instagram.com OR site:x.com OR site:tiktok.com)"
+
+PROFILE_PATTERNS = [
+ ("LinkedIn", re.compile(r"^(?:[a-z]{2,3}\.)?linkedin\.com/in/([^/]+)$"), "https://www.linkedin.com/in/{}"),
+ ("Facebook", re.compile(r"^(?:[a-z\-]+\.)?facebook\.com/people/[^/]+/(\d+)$"), "https://www.facebook.com/profile.php?id={}"),
+ ("Facebook", re.compile(r"^(?:[a-z\-]+\.)?facebook\.com/(?!public|pages|groups|events|watch|hashtag|share|story|photo|"
+ r"permalink|login|marketplace|reel|profile\.php)([A-Za-z0-9.\-]{3,})$"), "https://www.facebook.com/{}"),
+ ("Instagram", re.compile(r"^(?:www\.)?instagram\.com/(?!p/|reel|explore|stories|accounts)([A-Za-z0-9._]{2,30})$"),
+ "https://www.instagram.com/{}"),
+ ("X/Twitter", re.compile(r"^(?:www\.|mobile\.)?(?:twitter|x)\.com/(?!search|hashtag|i$|intent|home)([A-Za-z0-9_]{2,15})$"),
+ "https://x.com/{}"),
+ ("TikTok", re.compile(r"^(?:www\.)?tiktok\.com/@([A-Za-z0-9._]{2,24})$"), "https://www.tiktok.com/@{}"),
+]
+
+REGION_CODES = {"CL": ("cl", "cl-es"), "AR": ("ar", "ar-es"), "ES": ("es", "es-es"), "MX": ("mx", "mx-es"),
+ "CO": ("co", "co-es"), "PE": ("pe", "pe-es"), "US": ("us", "us-en")}
+
+
+class RateLimited(Exception):
+ pass
+
+
+def profile_of(url: str) -> tuple[str, str, str] | None:
+ """(plataforma, usuario, url canónica) si el resultado es un perfil personal."""
+ p = urlparse(url)
+ if (p.hostname or "").endswith("facebook.com") and p.path.rstrip("/") == "/profile.php":
+ uid = (parse_qs(p.query).get("id") or [""])[0]
+ return ("Facebook", uid, f"https://www.facebook.com/profile.php?id={uid}") if uid.isdigit() else None
+ path = f"{(p.hostname or '').lower()}{p.path}".rstrip("/")
+ for platform, rx, tpl in PROFILE_PATTERNS:
+ m = rx.match(path)
+ if m:
+ user = unquote(m.group(1))
+ return platform, user, tpl.format(user)
+ return None
+
+
+def _clean(s: str) -> str:
+ return html.unescape(re.sub(r"<[^>]+>", "", s or "")).strip()
+
+
+async def _serper(http, q, gl):
+ r = await http.post("https://google.serper.dev/search", json={"q": q, "gl": gl, "hl": "es", "num": 20},
+ headers={"X-API-KEY": settings.key("serper")})
+ if r.status_code == 429:
+ raise RateLimited("Serper: cuota agotada")
+ r.raise_for_status()
+ return [(x.get("title", ""), x.get("link", ""), x.get("snippet", "")) for x in r.json().get("organic") or []]
+
+
+async def _brave(http, q, gl):
+ r = await http.get("https://api.search.brave.com/res/v1/web/search", params={"q": q, "count": 20, "country": gl},
+ headers={"X-Subscription-Token": settings.key("brave"), "Accept": "application/json"})
+ if r.status_code == 429:
+ raise RateLimited("Brave: límite de peticiones")
+ r.raise_for_status()
+ return [(_clean(x.get("title")), x.get("url", ""), _clean(x.get("description")))
+ for x in (r.json().get("web") or {}).get("results") or []]
+
+
+DDG_LINK = re.compile(r'<a\b([^>]*class="result__a"[^>]*)>(.*?)</a>', re.S)
+DDG_HREF = re.compile(r'href="([^"]+)"')
+DDG_SNIPPET = re.compile(r'class="result__snippet"[^>]*>(.*?)</(?:a|td|div)>', re.S)
+
+
+async def _ddg(http, q, kl):
+ r = await http.post("https://html.duckduckgo.com/html/", data={"q": q, "kl": kl}, headers=UA)
+ if r.status_code != 200 or "anomaly" in r.text[:5000].lower():
+ raise RateLimited("DuckDuckGo limitó las búsquedas automáticas")
+ return parse_ddg(r.text)
+
+
+def parse_ddg(page: str) -> list[tuple[str, str, str]]:
+ out = []
+ links = list(DDG_LINK.finditer(page))
+ for i, m in enumerate(links):
+ h = DDG_HREF.search(m.group(1))
+ if not h:
+ continue
+ href = html.unescape(h.group(1))
+ title = m.group(2)
+ rest = page[m.end():links[i + 1].start() if i + 1 < len(links) else len(page)]
+ if "uddg=" in href:
+ href = unquote(parse_qs(urlparse(href).query).get("uddg", [""])[0])
+ if href.startswith("//"):
+ href = "https:" + href
+ if "duckduckgo.com/y.js" in href or not href.startswith("http"):
+ continue
+ sn = DDG_SNIPPET.search(rest)
+ out.append((_clean(title), href, _clean(sn.group(1)) if sn else ""))
+ return out
+
+
+LITE_LINK = re.compile(r"<a\b[^>]*href=\"([^\"]+)\"[^>]*class='result-link'[^>]*>(.*?)</a>", re.S)
+LITE_SNIPPET = re.compile(r"<td class='result-snippet'>(.*?)</td>", re.S)
+
+
+async def _ddg_lite(http, q, kl):
+ r = await http.post("https://lite.duckduckgo.com/lite/", data={"q": q, "kl": kl}, headers=UA)
+ if r.status_code != 200 or "anomaly" in r.text[:5000].lower():
+ raise RateLimited("DuckDuckGo Lite limitó las búsquedas automáticas")
+ return parse_ddg_lite(r.text)
+
+
+def parse_ddg_lite(page: str) -> list[tuple[str, str, str]]:
+ out = []
+ links = list(LITE_LINK.finditer(page))
+ for i, m in enumerate(links):
+ href = html.unescape(m.group(1))
+ if "uddg=" in href:
+ href = unquote(parse_qs(urlparse(href).query).get("uddg", [""])[0])
+ if not href.startswith("http") or "duckduckgo.com/y.js" in href:
+ continue
+ rest = page[m.end():links[i + 1].start() if i + 1 < len(links) else len(page)]
+ sn = LITE_SNIPPET.search(rest)
+ out.append((_clean(m.group(2)), href, _clean(sn.group(1)) if sn else ""))
+ return out
+
+
+BING_ITEM = re.compile(r'<li class="b_algo"(.*?)</li>', re.S)
+BING_TITLE = re.compile(r'<h2[^>]*>\s*<a\b[^>]*href="([^"]+)"[^>]*>(.*?)</a>', re.S)
+BING_SNIPPET = re.compile(r"<p\b[^>]*>(.*?)</p>", re.S)
+
+
+def _bing_target(href: str) -> str:
+ """Bing envuelve los enlaces en /ck/a?…&u=a1<url en base64>."""
+ href = html.unescape(href)
+ if "bing.com/ck/a" in href:
+ u = (parse_qs(urlparse(href).query).get("u") or [""])[0]
+ if u.startswith("a1"):
+ try:
+ return base64.urlsafe_b64decode(u[2:] + "=" * (-len(u[2:]) % 4)).decode("utf-8", "replace")
+ except ValueError:
+ return ""
+ return href
+
+
+async def _bing(http, q, gl):
+ r = await http.get("https://www.bing.com/search", params={"q": q, "cc": gl, "setlang": "es", "count": 30}, headers=UA)
+ if r.status_code != 200 or ('class="b_algo"' not in r.text and "captcha" in r.text.lower()):
+ raise RateLimited("Bing limitó las búsquedas automáticas")
+ return parse_bing(r.text)
+
+
+def parse_bing(page: str) -> list[tuple[str, str, str]]:
+ out = []
+ for item in BING_ITEM.finditer(page):
+ t = BING_TITLE.search(item.group(1))
+ if not t:
+ continue
+ url = _bing_target(t.group(1))
+ if not url.startswith("http"):
+ continue
+ sn = BING_SNIPPET.search(item.group(1))
+ snippet = re.sub(r"^.*?&nbsp;·&#32;|^.*?\u00a0·\u00a0", "", sn.group(1)) if sn else ""
+ out.append((_clean(t.group(2)), url, _clean(snippet)))
+ return out
+
+
+# Sin clave: si un buscador bloquea, la misma consulta sigue en el siguiente.
+FREE_ENGINES = (("DuckDuckGo", _ddg, 1), ("DuckDuckGo Lite", _ddg_lite, 1), ("Bing", _bing, 0))
+
+
+async def free_search(http, queries: list[str], region: tuple[str, str]):
+ """(resultados, buscadores usados, aviso si todos bloquearon)."""
+ results, used, i = [], [], 0
+ for n, q in enumerate(queries):
+ while i < len(FREE_ENGINES):
+ name, call, arg = FREE_ENGINES[i]
+ try:
+ results += await call(http, q, region[arg])
+ except RateLimited:
+ i += 1
+ continue
+ except httpx.HTTPError:
+ i += 1
+ continue
+ if name not in used:
+ used.append(name)
+ break
+ if i >= len(FREE_ENGINES):
+ return results, used, "Los buscadores gratuitos (DuckDuckGo y Bing) limitaron las búsquedas automáticas"
+ if n < len(queries) - 1:
+ await asyncio.sleep(1.5)
+ return results, used, None
+
+
+@register
+class WebSearch(Module):
+ name = "web_search"
+ title = "Búsqueda web del nombre (completo y abreviado)"
+ description = ("Busca el nombre en la web y en LinkedIn, Facebook, Instagram, X y TikTok, también sin el segundo "
+ "nombre o apellido. Con clave de Serper o Brave es más fiable; sin clave usa DuckDuckGo y, si "
+ "bloquea, sigue con Bing.")
+ inputs = ("person",)
+ optional_keys = ("serper", "brave")
+ sources = ("Serper (Google)", "Brave Search", "DuckDuckGo")
+ timeout = 120
+
+ async def run(self, ctx):
+ full = " ".join(ctx.value.split())
+ variants = name_variants(full)
+ region = REGION_CODES.get((settings.get("default_region") or "CL").upper(), ("cl", "cl-es"))
+ gl = region[0]
+ queries = [f'"{full}"', f'"{full}" {SOCIAL}'] + [f'"{v}" {SOCIAL}' for v in variants[:3]]
+ if variants:
+ queries.append(f'"{variants[0]}"')
+
+ if settings.key("serper"):
+ engine, call = "Google (Serper)", _serper
+ elif settings.key("brave"):
+ engine, call = "Brave Search", _brave
+ else:
+ engine, call = None, None
+
+ results, limited = [], None
+ if call is None:
+ results, used, limited = await free_search(ctx.http, queries, region)
+ engine = " + ".join(used) or FREE_ENGINES[0][0]
+ else:
+ for res in await asyncio.gather(*(call(ctx.http, q, gl) for q in queries), return_exceptions=True):
+ if isinstance(res, RateLimited):
+ limited = str(res)
+ elif isinstance(res, list):
+ results += res
+
+ hits, seen = [], set()
+ for title, url, snippet in results:
+ prof = profile_of(url)
+ key = (prof[2] if prof else url).lower()
+ if key in seen:
+ continue
+ m = name_match(title, full, variants) or (None if prof else name_match(snippet, full, variants))
+ if not m:
+ continue
+ seen.add(key)
+ hits.append({"kind": m[0], "variant": m[1], "title": title, "url": prof[2] if prof else url,
+ "snippet": snippet[:240], "platform": prof[0] if prof else None,
+ "user": prof[1] if prof else None})
+ hits.sort(key=lambda h: (h["kind"] != "exacta", h["platform"] is None))
+
+ added = 0
+ for h in hits:
+ if h["kind"] == "exacta" and h["platform"] and added < 12:
+ ctx.add("account", h["url"], {
+ "Plataforma": h["platform"], "Usuario": h["user"], "Título": h["title"],
+ "Descripción": h["snippet"] or None, "_links": [["Abrir perfil", h["url"]]],
+ "Verificación": "Búsqueda web: perfil con el nombre completo",
+ }, rel="posible perfil (nombre completo)", pivot=False)
+ added += 1
+
+ ent = db.update_attrs(ctx.case_id, ctx.entity["id"], {"_web": hits[:60], "_web_engine": engine}, replace=True)
+ if ent:
+ ctx.job.emit({"type": "entity", "entity": ent, "created": False})
+ ctx.enriched = True
+ exact = sum(h["kind"] == "exacta" for h in hits)
+ ctx.found = len(hits)
+ parts = [f"{exact} con el nombre completo", f"{len(hits) - exact} parciales"]
+ if limited:
+ parts.append(f"{limited}: añade una clave gratuita de Serper o Brave en Ajustes, o usa los dorks")
+ ctx.message = f"{engine}: " + ", ".join(parts)
+ if not hits and limited and not results:
+ raise RuntimeError(parts[-1])
diff --git a/app/resources/sites.json b/app/resources/sites.json
new file mode 100644
index 0000000..0e750a2
--- /dev/null
+++ b/app/resources/sites.json
@@ -0,0 +1,32 @@
+{
+ "PyPI": {"url": "https://pypi.org/user/{}/", "errorType": "status_code"},
+ "npm": {"url": "https://www.npmjs.com/~{}", "errorType": "status_code"},
+ "Codeberg": {"url": "https://codeberg.org/{}", "urlProbe": "https://codeberg.org/api/v1/users/{}", "errorType": "status_code"},
+ "Replit": {"url": "https://replit.com/@{}", "errorType": "status_code"},
+ "Hugging Face": {"url": "https://huggingface.co/{}", "errorType": "status_code"},
+ "Codewars": {"url": "https://www.codewars.com/users/{}", "urlProbe": "https://www.codewars.com/api/v1/users/{}", "errorType": "status_code"},
+ "Speedrun.com": {"url": "https://www.speedrun.com/users/{}", "urlProbe": "https://www.speedrun.com/api/v1/users/{}", "errorType": "status_code"},
+ "Wikipedia": {"url": "https://en.wikipedia.org/wiki/User:{}", "urlProbe": "https://en.wikipedia.org/w/api.php?action=query&list=users&ususers={}&format=json", "errorType": "message", "errorMsg": "\"missing\""},
+ "SoundCloud": {"url": "https://soundcloud.com/{}", "errorType": "status_code"},
+ "Linktree": {"url": "https://linktr.ee/{}", "errorType": "status_code"},
+ "Last.fm": {"url": "https://www.last.fm/user/{}", "errorType": "status_code"},
+ "Letterboxd": {"url": "https://letterboxd.com/{}/", "errorType": "status_code"},
+ "Pastebin": {"url": "https://pastebin.com/u/{}", "errorType": "status_code"},
+ "Itch.io": {"url": "https://{}.itch.io/", "errorType": "status_code", "regexCheck": "^[a-zA-Z0-9_-]{2,40}$"},
+ "YouTube": {"url": "https://www.youtube.com/@{}", "errorType": "status_code"},
+ "Snapchat": {"url": "https://www.snapchat.com/add/{}", "errorType": "status_code", "regexCheck": "^[a-z][a-z-_.]{3,15}$"},
+ "Gravatar": {"url": "https://gravatar.com/{}", "urlProbe": "https://en.gravatar.com/{}.json", "errorType": "status_code"},
+ "Mastodon (mastodon.social)": {"url": "https://mastodon.social/@{}", "urlProbe": "https://mastodon.social/api/v1/accounts/lookup?acct={}", "errorType": "status_code"},
+ "Mastodon (mastodon.online)": {"url": "https://mastodon.online/@{}", "urlProbe": "https://mastodon.online/api/v1/accounts/lookup?acct={}", "errorType": "status_code"},
+ "Mastodon (mstdn.social)": {"url": "https://mstdn.social/@{}", "urlProbe": "https://mstdn.social/api/v1/accounts/lookup?acct={}", "errorType": "status_code"},
+ "Mastodon (infosec.exchange)": {"url": "https://infosec.exchange/@{}", "urlProbe": "https://infosec.exchange/api/v1/accounts/lookup?acct={}", "errorType": "status_code"},
+ "Imgur": {"url": "https://imgur.com/user/{}", "urlProbe": "https://api.imgur.com/account/v1/accounts/{}?client_id=546c25a59c58ad7", "errorType": "status_code"},
+ "Disqus": {"url": "https://disqus.com/by/{}/", "errorType": "status_code"},
+ "SourceForge": {"url": "https://sourceforge.net/u/{}/profile", "errorType": "status_code"},
+ "osu!": {"url": "https://osu.ppy.sh/users/{}", "errorType": "status_code"},
+ "Flickr": {"url": "https://www.flickr.com/people/{}", "errorType": "status_code"},
+ "Vimeo": {"url": "https://vimeo.com/{}", "errorType": "status_code"},
+ "BuyMeACoffee": {"url": "https://buymeacoffee.com/{}", "errorType": "status_code", "regexCheck": "^[a-zA-Z0-9]{3,15}$"},
+ "Medium": {"url": "https://medium.com/@{}", "errorType": "status_code"},
+ "Kaggle": {"url": "https://www.kaggle.com/{}", "errorType": "status_code"}
+}
diff --git a/app/util.py b/app/util.py
new file mode 100644
index 0000000..3ae1c01
--- /dev/null
+++ b/app/util.py
@@ -0,0 +1,153 @@
+import asyncio
+import html as htmllib
+import re
+from urllib.parse import urljoin, urlparse
+
+import dns.exception
+import dns.resolver
+import dns.reversename
+
+EMAIL_RE = re.compile(r"[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,24}")
+URL_RE = re.compile(r"https?://[^\s\"'<>()\[\]{}]+", re.I)
+_IGNORED_EMAIL_SUFFIX = (".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg", ".css", ".js")
+
+SOCIAL_PATTERNS: list[tuple[str, re.Pattern]] = [
+ ("X/Twitter", re.compile(r"^https?://(?:www\.|mobile\.)?(?:twitter|x)\.com/(?!share|intent|home|search|hashtag|i/|privacy|tos)([A-Za-z0-9_]{1,15})/?$", re.I)),
+ ("Instagram", re.compile(r"^https?://(?:www\.)?instagram\.com/(?!p/|reel/|explore/|accounts/)([A-Za-z0-9_.]{1,30})/?$", re.I)),
+ ("Facebook", re.compile(r"^https?://(?:www\.|m\.|es-la\.)?facebook\.com/(?!sharer|share|dialog|plugins|tr\b|groups/|events/|pages/)([A-Za-z0-9.\-]{2,50})/?$", re.I)),
+ ("LinkedIn", re.compile(r"^https?://(?:[a-z]{2,3}\.)?linkedin\.com/(?:in|company)/([A-Za-z0-9\-_%]{2,100})/?$", re.I)),
+ ("GitHub", re.compile(r"^https?://(?:www\.)?github\.com/(?!sponsors|orgs|features|about|login|topics|marketplace)([A-Za-z0-9\-]{1,39})/?$", re.I)),
+ ("YouTube", re.compile(r"^https?://(?:www\.)?youtube\.com/@([A-Za-z0-9_\-.]{2,100})/?$", re.I)),
+ ("TikTok", re.compile(r"^https?://(?:www\.)?tiktok\.com/@([A-Za-z0-9_.]{2,24})/?$", re.I)),
+ ("Telegram", re.compile(r"^https?://(?:t\.me|telegram\.me)/(?!share|joinchat|s/|\+)([A-Za-z0-9_]{5,32})/?$", re.I)),
+ ("Twitch", re.compile(r"^https?://(?:www\.)?twitch\.tv/([A-Za-z0-9_]{3,25})/?$", re.I)),
+ ("Reddit", re.compile(r"^https?://(?:www\.|old\.)?reddit\.com/(?:u|user)/([A-Za-z0-9_\-]{3,20})/?$", re.I)),
+ ("Bluesky", re.compile(r"^https?://bsky\.app/profile/([A-Za-z0-9.\-]{3,100})/?$", re.I)),
+ ("Threads", re.compile(r"^https?://(?:www\.)?threads\.net/@([A-Za-z0-9_.]{1,30})/?$", re.I)),
+]
+
+
+def social_from_url(url: str) -> tuple[str, str] | None:
+ u = url.split("?")[0].split("#")[0]
+ for platform, rx in SOCIAL_PATTERNS:
+ m = rx.match(u)
+ if m:
+ return platform, m.group(1)
+ return None
+
+
+def clean_emails(text: str) -> list[str]:
+ out = []
+ for e in EMAIL_RE.findall(text or ""):
+ e = e.strip(".").lower()
+ if e.endswith(_IGNORED_EMAIL_SUFFIX) or "example." in e or e in out:
+ continue
+ out.append(e)
+ return out
+
+
+def _meta(html: str, name: str) -> str | None:
+ m = re.search(
+ rf'<meta[^>]+(?:name|property)=["\']{re.escape(name)}["\'][^>]*content=["\']([^"\']*)["\']', html, re.I
+ ) or re.search(rf'<meta[^>]+content=["\']([^"\']*)["\'][^>]*(?:name|property)=["\']{re.escape(name)}["\']', html, re.I)
+ return htmllib.unescape(m.group(1)).strip() if m else None
+
+
+def parse_page(html: str, base_url: str) -> dict:
+ """Extrae título, metadatos, emails, redes sociales y enlaces externos de un HTML."""
+ title = re.search(r"<title[^>]*>(.*?)</title>", html, re.I | re.S)
+ hrefs = re.findall(r'href=["\']([^"\']+)["\']', html, re.I)
+ links = []
+ for h in hrefs:
+ h = htmllib.unescape(h)
+ if h.startswith("mailto:"):
+ continue
+ full = urljoin(base_url, h)
+ if full.startswith("http") and full not in links:
+ links.append(full)
+ mailtos = [htmllib.unescape(m).split("?")[0] for m in re.findall(r'mailto:([^"\'>\s]+)', html, re.I)]
+ socials = []
+ for l in links:
+ s = social_from_url(l)
+ if s and (s[0], s[1].lower()) not in {(p, u.lower()) for p, u, _ in socials}:
+ socials.append((s[0], s[1], l))
+ base_host = urlparse(base_url).hostname or ""
+ from .modules.chile import find_ruts
+
+ text = htmllib.unescape(re.sub(r"<script.*?</script>|<style.*?</style>", " ", html, flags=re.S | re.I))
+ text = re.sub(r"<[^>]+>", " ", text)
+ return {
+ "ruts": find_ruts(text, limit=20),
+ "title": htmllib.unescape(" ".join(title.group(1).split()))[:200] if title else None,
+ "description": _meta(html, "description") or _meta(html, "og:description"),
+ "generator": _meta(html, "generator"),
+ "emails": clean_emails(" ".join(mailtos) + " " + re.sub(r"<[^>]+>", " ", html)),
+ "socials": socials,
+ "external_links": [l for l in links if (urlparse(l).hostname or "") != base_host][:200],
+ }
+
+
+def tech_from_response(headers, html: str) -> list[str]:
+ tech = []
+ for h in ("server", "x-powered-by", "x-generator", "x-aspnet-version"):
+ if headers.get(h):
+ tech.append(f"{h}: {headers[h]}")
+ lower = html.lower()
+ hints = {
+ "WordPress": "wp-content/",
+ "Shopify": "cdn.shopify.com",
+ "Wix": "wix.com",
+ "Squarespace": "squarespace",
+ "Drupal": "drupal-settings-json",
+ "Joomla": "/media/jui/",
+ "Next.js": "__next_data__",
+ "React": "data-reactroot",
+ "Google Analytics": "google-analytics.com",
+ "Google Tag Manager": "googletagmanager.com",
+ "Cloudflare": "cdn-cgi/",
+ }
+ tech += [name for name, needle in hints.items() if needle in lower]
+ if "cf-ray" in headers:
+ tech.append("Cloudflare")
+ return list(dict.fromkeys(tech))
+
+
+def find_analytics_ids(html: str) -> list[str]:
+ """IDs de Google Analytics/AdSense/GTM: sirven para encontrar webs del mismo dueño."""
+ ids = set(re.findall(r"\b(UA-\d{4,10}-\d{1,4}|G-[A-Z0-9]{6,12}|GTM-[A-Z0-9]{4,9}|ca-pub-\d{10,20}|pub-\d{10,20})\b", html))
+ return sorted(ids)
+
+
+_resolver = dns.resolver.Resolver(configure=True)
+if not _resolver.nameservers:
+ _resolver.nameservers = ["1.1.1.1", "8.8.8.8"]
+_resolver.lifetime = 8.0
+
+
+def _resolve(name: str, rtype: str) -> list[str]:
+ try:
+ return [r.to_text().strip('"') for r in _resolver.resolve(name, rtype)]
+ except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer, dns.resolver.NoNameservers, dns.exception.Timeout,
+ dns.name.EmptyLabel, dns.name.LabelTooLong):
+ return []
+
+
+async def resolve(name: str, rtype: str) -> list[str]:
+ return await asyncio.to_thread(_resolve, name, rtype)
+
+
+async def reverse_dns(ip: str) -> list[str]:
+ try:
+ name = dns.reversename.from_address(ip).to_text()
+ except (dns.exception.SyntaxError, ValueError):
+ return []
+ return [h.rstrip(".") for h in await resolve(name, "PTR")]
+
+
+FREE_EMAIL_PROVIDERS = {
+ "gmail.com", "googlemail.com", "outlook.com", "outlook.es", "hotmail.com", "hotmail.es", "hotmail.com.ar",
+ "live.com", "live.com.ar", "msn.com", "yahoo.com", "yahoo.es", "yahoo.com.ar", "yahoo.com.mx", "ymail.com",
+ "icloud.com", "me.com", "mac.com", "aol.com", "proton.me", "protonmail.com", "pm.me", "gmx.com", "gmx.net",
+ "gmx.es", "mail.com", "yandex.com", "yandex.ru", "zoho.com", "tutanota.com", "tuta.io", "mail.ru", "qq.com",
+ "163.com", "126.com", "fastmail.com", "hey.com", "terra.com.br", "uol.com.br", "bol.com.br", "inbox.ru",
+}
diff --git a/build_exe.bat b/build_exe.bat
new file mode 100644
index 0000000..cf939bd
--- /dev/null
+++ b/build_exe.bat
@@ -0,0 +1,38 @@
+@echo off
+setlocal
+cd /d "%~dp0"
+set PYTHONUTF8=1
+
+if not exist ".venv\Scripts\python.exe" (
+ echo Creando entorno de Python...
+ py -3 -m venv .venv 2>nul || python -m venv .venv
+)
+echo Instalando dependencias y PyInstaller...
+".venv\Scripts\python.exe" -m pip install -q -r requirements.txt pyinstaller || goto :error
+
+".venv\Scripts\python.exe" tools\make_icon.py || goto :error
+
+echo Generando OsintHunter.exe (tarda un par de minutos)...
+".venv\Scripts\python.exe" -m PyInstaller --noconfirm --clean --onefile --console ^
+ --name OsintHunter ^
+ --icon build\osinthunter.ico ^
+ --add-data "web;web" ^
+ --add-data "app\resources;app\resources" ^
+ --collect-submodules uvicorn ^
+ --collect-submodules dns ^
+ --collect-submodules phonenumbers ^
+ --collect-submodules pypdf ^
+ --collect-submodules app ^
+ osinthunter.py || goto :error
+
+echo.
+echo Listo: dist\OsintHunter.exe
+echo Puedes copiarlo a cualquier carpeta; guardara sus datos en una carpeta "data" a su lado.
+pause
+exit /b 0
+
+:error
+echo.
+echo Ha fallado la generacion del ejecutable.
+pause
+exit /b 1
diff --git a/docs/banner.svg b/docs/banner.svg
new file mode 100644
index 0000000..fd76bd9
--- /dev/null
+++ b/docs/banner.svg
@@ -0,0 +1,41 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1200 300" width="1200" height="300">
+ <defs>
+ <linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">
+ <stop offset="0" stop-color="#0d0a07"/>
+ <stop offset="1" stop-color="#1c1209"/>
+ </linearGradient>
+ <linearGradient id="txt" x1="0" y1="0" x2="1" y2="0">
+ <stop offset="0" stop-color="#ffb066"/>
+ <stop offset="1" stop-color="#ff7a1a"/>
+ </linearGradient>
+ <radialGradient id="glow" cx=".18" cy=".5" r=".35">
+ <stop offset="0" stop-color="#ff7a1a" stop-opacity=".35"/>
+ <stop offset="1" stop-color="#ff7a1a" stop-opacity="0"/>
+ </radialGradient>
+ <pattern id="grid" width="32" height="32" patternUnits="userSpaceOnUse">
+ <path d="M32 0H0V32" fill="none" stroke="#ff7a1a" stroke-opacity=".07" stroke-width="1"/>
+ </pattern>
+ </defs>
+ <rect width="1200" height="300" rx="22" fill="url(#bg)"/>
+ <rect width="1200" height="300" rx="22" fill="url(#grid)"/>
+ <rect width="1200" height="300" rx="22" fill="url(#glow)"/>
+ <g stroke="#ff7a1a" stroke-opacity=".35" stroke-width="2">
+ <line x1="820" y1="80" x2="930" y2="140"/><line x1="930" y1="140" x2="1060" y2="95"/>
+ <line x1="930" y1="140" x2="980" y2="235"/><line x1="930" y1="140" x2="850" y2="215"/>
+ <line x1="1060" y1="95" x2="1120" y2="190"/><line x1="980" y1="235" x2="1120" y2="190"/>
+ </g>
+ <g fill="#ff7a1a">
+ <circle cx="930" cy="140" r="14"/><circle cx="820" cy="80" r="8" opacity=".8"/>
+ <circle cx="1060" cy="95" r="10" opacity=".85"/><circle cx="980" cy="235" r="9" opacity=".75"/>
+ <circle cx="850" cy="215" r="7" opacity=".6"/><circle cx="1120" cy="190" r="8" opacity=".7"/>
+ </g>
+ <g transform="translate(110 70) scale(2.5)">
+ <circle cx="32" cy="32" r="19" fill="none" stroke="#ff7a1a" stroke-width="4"/>
+ <circle cx="32" cy="32" r="9" fill="none" stroke="#ff7a1a" stroke-width="3" opacity=".7"/>
+ <circle cx="32" cy="32" r="3.5" fill="#ffb066"/>
+ <path d="M32 6v12M32 46v12M6 32h12M46 32h12" stroke="#ff7a1a" stroke-width="4" stroke-linecap="round"/>
+ </g>
+ <text x="300" y="150" font-family="Segoe UI, Helvetica, Arial, sans-serif" font-size="78" font-weight="800" fill="url(#txt)">OsintHunter</text>
+ <text x="304" y="196" font-family="Segoe UI, Helvetica, Arial, sans-serif" font-size="25" fill="#e8d9c8">La herramienta OSINT definitiva &#183; grafo &#183; confianza &#183; informes</text>
+ <text x="304" y="234" font-family="Consolas, Menlo, monospace" font-size="18" fill="#ff7a1a" fill-opacity=".8">&gt; usuario &#183; email &#183; tel&#233;fono &#183; nombre &#183; dominio &#183; RUT_</text>
+</svg>
diff --git a/docs/screenshots/alias.png b/docs/screenshots/alias.png
new file mode 100644
index 0000000..e13f4aa
Binary files /dev/null and b/docs/screenshots/alias.png differ
diff --git a/docs/screenshots/bubbles.png b/docs/screenshots/bubbles.png
new file mode 100644
index 0000000..2c4608b
Binary files /dev/null and b/docs/screenshots/bubbles.png differ
diff --git a/docs/screenshots/confidence.png b/docs/screenshots/confidence.png
new file mode 100644
index 0000000..d33da41
Binary files /dev/null and b/docs/screenshots/confidence.png differ
diff --git a/docs/screenshots/english.png b/docs/screenshots/english.png
new file mode 100644
index 0000000..f258fe0
Binary files /dev/null and b/docs/screenshots/english.png differ
diff --git a/docs/screenshots/graph.png b/docs/screenshots/graph.png
new file mode 100644
index 0000000..ca5e068
Binary files /dev/null and b/docs/screenshots/graph.png differ
diff --git a/docs/screenshots/list.png b/docs/screenshots/list.png
new file mode 100644
index 0000000..c869dbe
Binary files /dev/null and b/docs/screenshots/list.png differ
diff --git a/docs/screenshots/map.png b/docs/screenshots/map.png
new file mode 100644
index 0000000..30a734f
Binary files /dev/null and b/docs/screenshots/map.png differ
diff --git a/docs/screenshots/report.png b/docs/screenshots/report.png
new file mode 100644
index 0000000..4ebb594
Binary files /dev/null and b/docs/screenshots/report.png differ
diff --git a/docs/screenshots/timeline.png b/docs/screenshots/timeline.png
new file mode 100644
index 0000000..84b0825
Binary files /dev/null and b/docs/screenshots/timeline.png differ
diff --git a/osinthunter.py b/osinthunter.py
new file mode 100644
index 0000000..253cb09
--- /dev/null
+++ b/osinthunter.py
@@ -0,0 +1,4 @@
+from app.__main__ import main
+
+if __name__ == "__main__":
+ main()
diff --git a/requirements.txt b/requirements.txt
new file mode 100644
index 0000000..db19b0e
--- /dev/null
+++ b/requirements.txt
@@ -0,0 +1,9 @@
+fastapi>=0.115
+uvicorn>=0.30
+httpx>=0.27
+dnspython>=2.6
+phonenumbers>=8.13
+pillow>=10.4
+python-multipart>=0.0.9
+pypdf>=5.0
+olefile>=0.47
diff --git a/start.bat b/start.bat
new file mode 100644
index 0000000..4293f13
--- /dev/null
+++ b/start.bat
@@ -0,0 +1,26 @@
+@echo off
+setlocal
+cd /d "%~dp0"
+title OsintHunter
+set PYTHONUTF8=1
+
+if not exist ".venv\Scripts\python.exe" (
+ echo [OsintHunter] Creando entorno virtual...
+ py -3 -m venv .venv 2>nul || python -m venv .venv
+ if errorlevel 1 (
+ echo No se encontro Python 3. Instalalo desde https://www.python.org/downloads/
+ pause
+ exit /b 1
+ )
+)
+
+echo [OsintHunter] Comprobando dependencias...
+".venv\Scripts\python.exe" -m pip install --disable-pip-version-check -q -r requirements.txt
+if errorlevel 1 (
+ echo Error instalando dependencias.
+ pause
+ exit /b 1
+)
+
+".venv\Scripts\python.exe" -m app %*
+pause
diff --git a/tools/make_icon.py b/tools/make_icon.py
new file mode 100644
index 0000000..9ad1c4e
--- /dev/null
+++ b/tools/make_icon.py
@@ -0,0 +1,21 @@
+"""Genera build/osinthunter.ico (una mira naranja sobre fondo negro) para el ejecutable."""
+from pathlib import Path
+
+from PIL import Image, ImageDraw
+
+out = Path(__file__).resolve().parent.parent / "build" / "osinthunter.ico"
+out.parent.mkdir(exist_ok=True)
+
+ORANGE = (255, 122, 26, 255)
+S = 256
+img = Image.new("RGBA", (S, S), (0, 0, 0, 0))
+d = ImageDraw.Draw(img)
+d.rounded_rectangle((8, 8, S - 8, S - 8), radius=56, fill=(13, 10, 7, 255), outline=(58, 42, 26, 255), width=8)
+c = S // 2
+d.ellipse((c - 76, c - 76, c + 76, c + 76), outline=ORANGE, width=16)
+d.ellipse((c - 36, c - 36, c + 36, c + 36), outline=(255, 122, 26, 180), width=12)
+d.ellipse((c - 14, c - 14, c + 14, c + 14), fill=(255, 176, 102, 255))
+for x0, y0, x1, y1 in ((c - 8, 24, c + 8, 72), (c - 8, S - 72, c + 8, S - 24), (24, c - 8, 72, c + 8), (S - 72, c - 8, S - 24, c + 8)):
+ d.rounded_rectangle((x0, y0, x1, y1), radius=8, fill=ORANGE)
+img.save(out, sizes=[(16, 16), (24, 24), (32, 32), (48, 48), (64, 64), (128, 128), (256, 256)])
+print(f"Icono: {out}")
diff --git a/web/app.js b/web/app.js
new file mode 100644
index 0000000..3d2ecb9
--- /dev/null
+++ b/web/app.js
@@ -0,0 +1,1813 @@
+"use strict";
+
+const $ = (s) => document.querySelector(s);
+const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]));
+const safeUrl = (u) => (typeof u === "string" && /^https?:\/\//i.test(u) ? u : null);
+async function copyText(text) {
+ try {
+ await navigator.clipboard.writeText(text);
+ return true;
+ } catch {
+ const ta = document.createElement("textarea");
+ ta.value = text;
+ document.body.append(ta);
+ ta.select();
+ const ok = document.execCommand("copy");
+ ta.remove();
+ return ok;
+ }
+}
+const link = (url, text) => {
+ const u = safeUrl(url);
+ return u ? `<a href="${esc(u)}" target="_blank" rel="noopener noreferrer">${esc(text ?? u)}</a>` : esc(text ?? url);
+};
+
+async function api(path, opts = {}) {
+ const isForm = opts.body instanceof FormData;
+ const res = await fetch(path, {
+ ...opts,
+ headers: opts.body && !isForm ? { "Content-Type": "application/json" } : {},
+ body: opts.body && !isForm ? JSON.stringify(opts.body) : opts.body,
+ });
+ if (!res.ok) {
+ let msg = res.statusText;
+ try { msg = (await res.json()).detail || msg; } catch { /* sin cuerpo */ }
+ throw new Error(msg);
+ }
+ return res.json();
+}
+
+const S = {
+ meta: null,
+ types: {},
+ modules: {},
+ cases: [],
+ caseId: null,
+ entities: new Map(),
+ edges: [],
+ runs: [],
+ running: new Map(), // "eid|module" -> true
+ selected: null,
+ hidden: new Set(),
+ jobs: new Map(), // jobId -> caseId
+ tab: "graph",
+ hideLow: false,
+ listSel: new Set(),
+ layout: { groups: [], collapsed: [] },
+ fold: new Map(), // nodo plegado -> nº de nodos escondidos
+ hiddenBy: new Map(), // nodo escondido -> nodo o burbuja que lo representa
+};
+let cy = null;
+
+// ---------------------------------------------------------------- utilidades UI
+let toastTimer;
+function toast(msg, isErr = false) {
+ const t = $("#toast");
+ t.textContent = msg;
+ t.className = "toast show" + (isErr ? " err" : "");
+ clearTimeout(toastTimer);
+ toastTimer = setTimeout(() => (t.className = "toast"), 3500);
+}
+const debounce = (fn, ms) => { let t; return (...a) => { clearTimeout(t); t = setTimeout(() => fn(...a), ms); }; };
+const typeInfo = (t) => S.types[t] || { label: t, color: "#999", shape: "ellipse" };
+const badge = (t) => `<span class="badge" style="background:${typeInfo(t).color}">${esc(typeInfo(t).label)}</span>`;
+const short = (s, n = 30) => (s.length > n ? s.slice(0, n - 1) + "…" : s);
+
+// ---------------------------------------------------------------- grafo
+function initGraph() {
+ cy = cytoscape({
+ container: $("#cy"),
+ wheelSensitivity: 0.25,
+ minZoom: 0.08,
+ maxZoom: 3,
+ boxSelectionEnabled: true,
+ style: [
+ { selector: "node", style: {
+ "background-color": "data(color)", shape: "data(shape)", label: "data(short)", color: "#e6dace",
+ "font-size": 10, "text-valign": "bottom", "text-margin-y": 4, width: "data(size)", height: "data(size)",
+ "text-outline-color": "#0a0806", "text-outline-width": 2, "border-width": 0, "min-zoomed-font-size": 6 } },
+ { selector: 'node[conf = "Alta"]', style: { "border-width": 3, "border-color": "#4caf50" } },
+ { selector: 'node[conf = "Media"]', style: { "border-width": 2, "border-color": "#ffb300" } },
+ { selector: 'node[conf = "Baja"]', style: { "border-width": 1.5, "border-color": "#6e3b2c", opacity: 0.72 } },
+ { selector: 'node[verdict = "confirmada"]', style: { "border-width": 4, "border-color": "#3ddc84", opacity: 1,
+ color: "#9ff0c0", "underlay-color": "#3ddc84", "underlay-opacity": 0.22, "underlay-padding": 6 } },
+ { selector: 'node[verdict = "descartada"]', style: { "border-width": 2, "border-color": "#5a5048", "border-style": "dashed",
+ opacity: 0.3, color: "#8a7f75" } },
+ { selector: "node.folded", style: { "border-width": 5, "border-style": "double", "border-color": "#ffd166" } },
+ { selector: "node[?root]", style: { "border-width": 4, "border-color": "#ff7a1a", "font-weight": "bold", "font-size": 12,
+ color: "#ffb066", "underlay-color": "#ff7a1a", "underlay-opacity": 0.18, "underlay-padding": 10, "underlay-shape": "ellipse" } },
+ { selector: "node.scanning", style: { "border-width": 3, "border-color": "#ffd166", "border-style": "dashed" } },
+ { selector: "node[?isGroup]", style: { shape: "round-rectangle", "background-color": "data(color)", "background-opacity": 0.07,
+ "border-width": 1.5, "border-style": "dashed", "border-color": "data(color)", "border-opacity": 0.8, label: "data(short)",
+ color: "data(color)", "font-size": 14, "font-weight": "bold", "text-valign": "top", "text-halign": "center", "text-margin-y": -6,
+ padding: 24, "compound-sizing-wrt-labels": "include", "underlay-opacity": 0 } },
+ { selector: "node[?isGroup].grp-collapsed", style: { "background-opacity": 0.4, "border-style": "double", "border-width": 5,
+ "text-valign": "bottom", "text-margin-y": 6, "font-size": 12 } },
+ { selector: "node:selected", style: { "border-width": 4, "border-color": "#ffa04d", "border-style": "solid",
+ "underlay-color": "#ff7a1a", "underlay-opacity": 0.3, "underlay-padding": 8 } },
+ { selector: "node[?isGroup]:selected", style: { "underlay-opacity": 0, "border-width": 3, "border-color": "data(color)", "background-opacity": 0.14 } },
+ { selector: "edge", style: {
+ width: 1.2, "line-color": "#3d2f22", "target-arrow-color": "#3d2f22", "target-arrow-shape": "triangle",
+ "arrow-scale": 0.7, "curve-style": "bezier", label: "data(label)", "font-size": 8, color: "#c9a383",
+ "text-rotation": "autorotate", "text-opacity": 0, "text-outline-color": "#0a0806", "text-outline-width": 2 } },
+ { selector: "edge.hl", style: { "line-color": "#ff7a1a", "target-arrow-color": "#ff7a1a", "text-opacity": 1, width: 2 } },
+ { selector: ".faded", style: { opacity: 0.12 } },
+ { selector: "edge.meta", style: { "line-style": "dashed", "line-color": "#6b4a2c", "target-arrow-color": "#6b4a2c", width: 1.6 } },
+ { selector: ".type-hidden, .low-hidden, .fold-hidden", style: { display: "none" } },
+ ],
+ });
+ cy.on("tap", "node", (e) => {
+ const oe = e.originalEvent;
+ if (oe && (oe.ctrlKey || oe.metaKey || oe.shiftKey)) return;
+ select(e.target.id());
+ });
+ cy.on("tap", (e) => { if (e.target === cy && !(e.originalEvent?.shiftKey || e.originalEvent?.ctrlKey)) select(null); });
+ cy.on("select unselect", "node", () => updateSelBarSoon());
+ let lastDbl = null;
+ cy.on("dbltap", "node", (e) => {
+ if (e.originalEvent && e.originalEvent === lastDbl) return;
+ lastDbl = e.originalEvent;
+ if (e.target.data("isGroup")) toggleGroup(e.target.id().slice(4));
+ else openPivot(e.target.id());
+ });
+ cy.on("mouseover", "node", (e) => {
+ if (e.target.data("isGroup")) return;
+ const n = e.target.closedNeighborhood();
+ cy.elements().not(n).addClass("faded");
+ n.edges().addClass("hl");
+ });
+ cy.on("mouseout", "node", () => cy.elements().removeClass("faded hl"));
+ new ResizeObserver(() => cy.resize()).observe($("#cy"));
+}
+
+function nodeData(ent) {
+ const t = typeInfo(ent.type);
+ const size = ent.root ? 46 : ent.type === "account" ? 24 : ent.type === "breach" ? 26 : 32;
+ const conf = ent.attrs?.["Nivel de confianza"] || "";
+ const verdict = ent.attrs?._verdict || "";
+ const folded = S.fold.get(ent.id);
+ const label = (verdict === "confirmada" ? "✔ " : "") + short(ent.label, 28) + (folded ? ` ⊕${folded}` : "");
+ return { id: ent.id, color: t.color, shape: t.shape, short: label, size, root: ent.root, etype: ent.type, conf, verdict };
+}
+
+const applyLowFilter = (n) => n.toggleClass("low-hidden",
+ S.hideLow && (n.data("conf") === "Baja" || n.data("verdict") === "descartada"));
+
+function upsertNode(ent, parentHint) {
+ S.entities.set(ent.id, ent);
+ const existing = cy.getElementById(ent.id);
+ if (existing.length) {
+ existing.data(nodeData(ent));
+ applyLowFilter(existing);
+ return false;
+ }
+ let pos = { x: 0, y: 0 };
+ const parent = parentHint && cy.getElementById(parentHint);
+ if (parent && parent.length) {
+ const p = parent.position();
+ pos = { x: p.x + (Math.random() - 0.5) * 160, y: p.y + (Math.random() - 0.5) * 160 };
+ } else if (cy.nodes().length) {
+ const bb = cy.nodes().boundingBox();
+ pos = { x: bb.x1 + Math.random() * bb.w, y: bb.y1 + Math.random() * bb.h };
+ }
+ const n = cy.add({ group: "nodes", data: nodeData(ent), position: pos });
+ if (S.hidden.has(ent.type)) n.addClass("type-hidden");
+ applyLowFilter(n);
+ if (S.layout.groups.length || S.layout.collapsed.length) applyGroupingSoon();
+ return true;
+}
+
+$("#hideLowChk").addEventListener("change", (ev) => {
+ S.hideLow = ev.target.checked;
+ cy.nodes().forEach(applyLowFilter);
+ if (S.tab === "map") renderMap();
+ if (S.tab === "timeline") renderTimeline();
+});
+
+function addEdge(e) {
+ const id = `${e.src}→${e.dst}|${e.label}`;
+ if (!S.edges.some((x) => `${x.src}→${x.dst}|${x.label}` === id)) S.edges.push(e);
+ if (cy.getElementById(id).length) return;
+ if (!cy.getElementById(e.src).length || !cy.getElementById(e.dst).length) return;
+ cy.add({ group: "edges", data: { id, source: e.src, target: e.dst, label: I18N.tr(e.label) } });
+}
+
+let firstLayout = true;
+const hasFcose = typeof cytoscapeFcose !== "undefined";
+if (hasFcose) cytoscape.use(cytoscapeFcose);
+
+function runLayout(fit, randomize = false) {
+ const shown = cy.nodes().not(".fold-hidden, .type-hidden, .low-hidden");
+ if (!shown.length) return;
+ const many = shown.length > 300;
+ const common = { animate: !many, animationDuration: 600, fit: fit ?? (firstLayout || shown.length < 40), padding: 40 };
+ const layout = shown.union(shown.edgesWith(shown)).layout(hasFcose ? {
+ ...common,
+ name: "fcose",
+ quality: many ? "draft" : "default",
+ randomize,
+ nodeSeparation: 90,
+ nodeRepulsion: () => 9000,
+ idealEdgeLength: (e) => (e.target().data("etype") === "account" ? 70 : 110),
+ edgeElasticity: () => 0.45,
+ gravity: 0.25,
+ gravityRangeCompound: 1.5,
+ numIter: 2500,
+ packComponents: true,
+ } : { ...common, name: "cose", randomize, nodeRepulsion: () => 12000, idealEdgeLength: () => 80 });
+ cy.one("layoutstop", () => { if (cy.zoom() > 1.6) { cy.zoom(1.6); cy.center(); } });
+ layout.run();
+ firstLayout = false;
+}
+const scheduleLayout = debounce(() => runLayout(), 700);
+
+function renderLegend() {
+ const counts = {};
+ for (const e of S.entities.values()) counts[e.type] = (counts[e.type] || 0) + 1;
+ $("#legend").innerHTML = Object.entries(counts)
+ .sort((a, b) => b[1] - a[1])
+ .map(([t, n]) => `<span class="chip ${S.hidden.has(t) ? "off" : ""}" data-type="${esc(t)}"><span class="dot" style="background:${typeInfo(t).color}"></span><span>${esc(typeInfo(t).label)}</span> ${n}</span>`)
+ .join("");
+ $("#emptyState").classList.toggle("hidden", S.entities.size > 0);
+}
+const renderLegendSoon = debounce(renderLegend, 200);
+
+$("#legend").addEventListener("click", (ev) => {
+ const chip = ev.target.closest(".chip");
+ if (!chip) return;
+ const t = chip.dataset.type;
+ S.hidden.has(t) ? S.hidden.delete(t) : S.hidden.add(t);
+ cy.nodes().filter((n) => n.data("etype") === t).toggleClass("type-hidden", S.hidden.has(t));
+ renderLegend();
+});
+
+// ---------------------------------------------------------------- casos
+async function loadCases(selectId) {
+ S.cases = await api("/api/cases");
+ const sel = $("#caseSelect");
+ sel.innerHTML = S.cases.length
+ ? S.cases.map((c) => `<option value="${c.id}">${esc(c.name)} (${c.entities})</option>`).join("")
+ : `<option value="">— Sin casos —</option>`;
+ if (selectId) sel.value = String(selectId);
+ else if (S.caseId) sel.value = String(S.caseId);
+}
+
+async function openCase(id) {
+ S.caseId = id ? Number(id) : null;
+ localStorage.setItem("osint-case", S.caseId ?? "");
+ cy.elements().remove();
+ S.entities.clear(); S.edges = []; S.runs = []; S.running.clear(); S.selected = null; S.listSel.clear();
+ S.layout = { groups: [], collapsed: [] };
+ firstLayout = true;
+ mapFitted = false;
+ renderDetails();
+ if (!S.caseId) { renderAll(); return; }
+ const data = await api(`/api/cases/${S.caseId}`);
+ $("#caseSelect").value = String(S.caseId);
+ $("#notesArea").value = data.case.notes || "";
+ S.layout = { groups: [], collapsed: [], ...(data.case.layout || {}) };
+ S.fold = new Map();
+ S.hiddenBy = new Map();
+ data.entities.forEach((e) => upsertNode(e));
+ data.edges.forEach(addEdge);
+ S.runs = data.runs;
+ applyGrouping();
+ renderAll();
+ runLayout(true, true);
+}
+
+function renderAll() {
+ renderLegend();
+ renderSources();
+ refreshView();
+}
+
+/** Cuentas de las que sólo se sabe que existen y cuya página aún no se leyó (misma regla que AccountPage.applies). */
+const NO_PAGE_PLATFORMS = new Set(["Facebook", "LinkedIn", "Instagram", "TikTok", "X/Twitter", "Pinterest"]);
+function unreadAccounts() {
+ const done = new Set(S.runs.filter((r) => r.module === "account_page" && r.status !== "error").map((r) => r.entity_id));
+ return [...S.entities.values()].filter((e) => e.type === "account" && !done.has(e.id)
+ && !NO_PAGE_PLATFORMS.has(e.attrs?.Plataforma)
+ && !["Nombre", "Nombre visible", "Nombre real", "_avatar"].some((k) => e.attrs?.[k]));
+}
+function updateReadBtn() {
+ const n = S.caseId ? unreadAccounts().length : 0;
+ const busy = [...S.running.keys()].some((k) => k.endsWith("|account_page"));
+ $("#readBtn").classList.toggle("hidden", !n && !busy);
+ $("#readBtn").disabled = busy;
+ $("#readBtn").textContent = busy ? "Leyendo perfiles…" : `Leer perfiles (${n})`;
+}
+
+function refreshView() {
+ updateReadBtn();
+ if (S.tab === "list") renderList();
+ if (S.tab === "map") renderMap();
+ if (S.tab === "timeline") renderTimeline();
+}
+const refreshViewSoon = debounce(refreshView, 400);
+
+async function ensureCase(defaultName) {
+ if (S.caseId) return S.caseId;
+ const c = await api("/api/cases", { method: "POST", body: { name: defaultName } });
+ await loadCases(c.id);
+ await openCase(c.id);
+ return c.id;
+}
+
+$("#caseSelect").addEventListener("change", (e) => openCase(e.target.value));
+$("#newCaseBtn").addEventListener("click", async () => {
+ const name = prompt("Nombre del nuevo caso:", "Investigación " + new Date().toLocaleDateString());
+ if (name === null) return;
+ const c = await api("/api/cases", { method: "POST", body: { name } });
+ await loadCases(c.id);
+ await openCase(c.id);
+ $("#searchInput").focus();
+});
+$("#renameCaseBtn").addEventListener("click", async () => {
+ if (!S.caseId) return;
+ const cur = S.cases.find((c) => c.id === S.caseId);
+ const name = prompt("Nuevo nombre:", cur?.name || "");
+ if (!name) return;
+ await api(`/api/cases/${S.caseId}`, { method: "PATCH", body: { name } });
+ await loadCases();
+});
+$("#deleteCaseBtn").addEventListener("click", async () => {
+ if (!S.caseId) return;
+ const cur = S.cases.find((c) => c.id === S.caseId);
+ if (!confirm(`¿Eliminar el caso «${cur?.name}» y todos sus datos?`)) return;
+ await api(`/api/cases/${S.caseId}`, { method: "DELETE" });
+ await loadCases();
+ await openCase(S.cases[0]?.id ?? null);
+});
+
+// ---------------------------------------------------------------- búsqueda
+function fillTypeSelect(detected) {
+ const opts = Object.entries(S.types).filter(([, v]) => v.input);
+ const autoLabel = detected ? `Auto: ${typeInfo(detected).label}` : "Tipo: automático";
+ const cur = $("#typeSelect").value;
+ $("#typeSelect").innerHTML = `<option value="">${esc(autoLabel)}</option>` +
+ opts.map(([k, v]) => `<option value="${k}">${esc(v.label)}</option>`).join("");
+ $("#typeSelect").value = cur;
+}
+const detectSoon = debounce(async () => {
+ const v = $("#searchInput").value.trim();
+ if (!v) return fillTypeSelect(null);
+ try { fillTypeSelect((await api("/api/detect", { method: "POST", body: { value: v } })).type); } catch { /* ignorar */ }
+}, 250);
+$("#searchInput").addEventListener("input", detectSoon);
+
+$("#searchForm").addEventListener("submit", async (ev) => {
+ ev.preventDefault();
+ const value = $("#searchInput").value.trim();
+ if (!value) return;
+ try {
+ await ensureCase(value);
+ const ent = await api(`/api/cases/${S.caseId}/entities`, { method: "POST", body: { value, type: $("#typeSelect").value || null } });
+ upsertNode(ent);
+ renderLegend();
+ select(ent.id);
+ scheduleLayout();
+ await startScan(ent.id, null, Number($("#depthSelect").value));
+ $("#searchInput").value = "";
+ fillTypeSelect(null);
+ loadCases();
+ } catch (e) { toast(e.message, true); }
+});
+
+$("#imageInput").addEventListener("change", async (ev) => {
+ const file = ev.target.files[0];
+ ev.target.value = "";
+ if (!file) return;
+ try {
+ await ensureCase("Imagen " + file.name);
+ const fd = new FormData();
+ fd.append("file", file);
+ const { entity } = await api(`/api/cases/${S.caseId}/image`, { method: "POST", body: fd });
+ await openCase(S.caseId);
+ select(entity.id);
+ toast("Imagen analizada");
+ } catch (e) { toast(e.message, true); }
+});
+
+// ---------------------------------------------------------------- escaneos en vivo
+async function startScan(eid, modules, depth) {
+ const { job_id } = await api(`/api/cases/${S.caseId}/scan`, { method: "POST", body: { entity_id: eid, modules, depth } });
+ followJob(job_id);
+}
+
+function followJob(job_id) {
+ S.jobs.set(job_id, S.caseId);
+ updateJobStatus();
+ const es = new EventSource(`/api/jobs/${job_id}/events`);
+ const end = () => { es.close(); S.jobs.delete(job_id); updateJobStatus(); };
+ es.onmessage = (m) => {
+ const ev = JSON.parse(m.data);
+ if (S.jobs.get(job_id) === S.caseId) handleEvent(ev);
+ if (ev.type === "done") {
+ end();
+ toast(ev.analysis ? "Análisis del caso terminado"
+ : `Investigación terminada (${ev.scanned} ${ev.scanned === 1 ? "entidad analizada" : "entidades analizadas"})`);
+ loadCases();
+ }
+ if (ev.type === "error") { end(); toast("Error: " + ev.message, true); }
+ };
+ es.onerror = end;
+}
+
+$("#readBtn").addEventListener("click", async () => {
+ if (!S.caseId) return;
+ try {
+ const { job_id } = await api(`/api/cases/${S.caseId}/read-accounts`, { method: "POST" });
+ toast("Leyendo la página pública de cada cuenta sin datos…");
+ followJob(job_id);
+ } catch (e) { toast(e.message, true); }
+});
+
+$("#aiBtn").addEventListener("click", async () => {
+ if (!S.caseId || !S.entities.size) return toast("Primero investiga algo");
+ if (!S.meta.ai_ready) { toast("Configura un proveedor de IA en Ajustes (Ollama local, Groq o Gemini son gratis)"); return openSettings(); }
+ try {
+ const { job_id } = await api(`/api/cases/${S.caseId}/analyze`, { method: "POST", body: { ai: true } });
+ toast("La IA está comparando las cuentas…");
+ followJob(job_id);
+ } catch (e) { toast(e.message, true); }
+});
+
+function updateJobStatus() {
+ $("#jobStatus").innerHTML = S.jobs.size ? `<span class="st-running">● trabajando</span>` : "";
+}
+
+function handleEvent(ev) {
+ switch (ev.type) {
+ case "entity": {
+ const created = upsertNode(ev.entity, S.lastParent);
+ if (created) { scheduleLayout(); renderLegendSoon(); }
+ if (S.selected === ev.entity.id) renderDetails();
+ refreshViewSoon();
+ break;
+ }
+ case "edge":
+ addEdge(ev.edge);
+ if (S.selected === ev.edge.src || S.selected === ev.edge.dst) renderDetailsSoon();
+ break;
+ case "scan_entity":
+ S.lastParent = ev.entity_id;
+ cy.getElementById(ev.entity_id).addClass("scanning");
+ break;
+ case "run_start":
+ S.running.set(`${ev.entity_id}|${ev.module}`, true);
+ renderSourcesSoon();
+ break;
+ case "run": {
+ const r = ev.run;
+ S.running.delete(`${r.entity_id}|${r.module}`);
+ S.runs.push(r);
+ if (![...S.running.keys()].some((k) => k.startsWith(r.entity_id + "|"))) cy.getElementById(r.entity_id).removeClass("scanning");
+ renderSourcesSoon();
+ if (S.selected === r.entity_id) renderDetailsSoon();
+ if (r.module === "account_page") refreshViewSoon();
+ break;
+ }
+ }
+}
+
+// ---------------------------------------------------------------- panel de fuentes
+const STATUS = {
+ ok: ["✔", "st-ok"], empty: ["○", "st-empty"], skipped: ["!", "st-skipped"], error: ["✖", "st-error"], running: ["●", "st-running"],
+};
+function renderSources() {
+ const groups = new Map();
+ const add = (eid, item) => { if (!groups.has(eid)) groups.set(eid, new Map()); groups.get(eid).set(item.module, item); };
+ for (const r of S.runs) add(r.entity_id, r);
+ for (const k of S.running.keys()) { const [eid, module] = splitKey(k); add(eid, { module, status: "running", message: "Consultando…" }); }
+ if (!groups.size) { $("#sourcesList").innerHTML = `<div class="muted small">Aún no hay consultas.</div>`; return; }
+ const order = [...groups.keys()].reverse();
+ $("#sourcesList").innerHTML = order.map((eid) => {
+ const ent = S.entities.get(eid);
+ const items = [...groups.get(eid).values()].sort((a, b) => (a.status === "running" ? -1 : 0) - (b.status === "running" ? -1 : 0));
+ const title = ent ? badge(ent.type) + " " + esc(ent.label) : eid === "case" ? "Análisis del caso" : esc(eid);
+ return `<div><div class="src-group-title" data-eid="${esc(eid)}">${title}</div>` +
+ items.map((r) => {
+ const [icon, cls] = STATUS[r.status] || ["?", ""];
+ const title = S.modules[r.module]?.title || r.module;
+ return `<div class="src"><span class="${cls}">${icon}</span><span>${esc(title)}</span><span class="msg">${esc(r.message || "")}</span></div>`;
+ }).join("") + `</div>`;
+ }).join("");
+}
+function splitKey(k) { const i = k.lastIndexOf("|"); return [k.slice(0, i), k.slice(i + 1)]; }
+const renderSourcesSoon = debounce(renderSources, 150);
+$("#sourcesList").addEventListener("click", (ev) => {
+ const t = ev.target.closest(".src-group-title");
+ if (t && S.entities.has(t.dataset.eid)) select(t.dataset.eid, true);
+});
+
+// ---------------------------------------------------------------- panel de detalles
+function select(id, center = false) {
+ if (id && !isGroupId(id)) reveal(id);
+ S.selected = id;
+ cy.nodes().unselect();
+ if (id) {
+ const n = cy.getElementById(id);
+ n.select();
+ if (center && n.length) cy.animate({ center: { eles: n }, zoom: Math.max(cy.zoom(), 1) }, { duration: 300 });
+ }
+ renderDetails();
+}
+
+function fmtValue(v) {
+ if (Array.isArray(v)) {
+ if (!v.length) return "";
+ const items = v.map((x) => `<li>${fmtValue(x)}</li>`).join("");
+ return v.length > 12 ? `<details><summary>${v.length} elementos</summary><ul>${items}</ul></details>` : `<ul>${items}</ul>`;
+ }
+ if (v && typeof v === "object") return `<ul>${Object.entries(v).map(([k, x]) => `<li><b>${esc(k)}:</b> ${fmtValue(x)}</li>`).join("")}</ul>`;
+ if (typeof v === "string" && safeUrl(v)) return link(v);
+ return esc(v);
+}
+
+const ANALYSIS_KEYS = new Set(["Confianza", "Nivel de confianza", "Señales", "IA: veredicto", "IA: motivo", "IA: resumen", "IA: modelo"]);
+const REVERSE_SEARCH = [
+ ["Google Lens", "https://lens.google.com/uploadbyurl?url="],
+ ["Yandex Imágenes (el mejor para caras)", "https://yandex.com/images/search?rpt=imageview&url="],
+ ["Bing Visual Search", "https://www.bing.com/images/search?view=detailv2&iss=sbi&q=imgurl:"],
+ ["TinEye", "https://tineye.com/search?url="],
+];
+
+function renderDorks(dorks) {
+ const groups = new Map();
+ for (const [label, url, group] of dorks) {
+ const g = group || "Búsquedas";
+ if (!groups.has(g)) groups.set(g, []);
+ groups.get(g).push(link(url, label));
+ }
+ return [...groups].map(([g, links], i) =>
+ `<details class="dork-group"${i === 0 ? " open" : ""}><summary>${esc(g)} <span class="muted">(${links.length})</span></summary><div class="linklist">${links.join("")}</div></details>`).join("");
+}
+
+const LINK_RELS = ["usa el alias", "alias de", "su cuenta", "es cuenta de", "es la misma persona", "familiar de",
+ "pareja de", "amigo de", "trabaja en", "estudió en", "vive en", "relacionado con"];
+
+function defaultRel(from, to) {
+ if (!to) return "relacionado con";
+ const pair = `${from.type}>${to.type}`;
+ return { "person>username": "usa el alias", "username>person": "alias de", "person>account": "su cuenta",
+ "account>person": "es cuenta de", "account>username": "es cuenta de", "person>person": "relacionado con",
+ "person>organization": "trabaja en", "person>location": "vive en", "username>username": "es la misma persona" }[pair] || "relacionado con";
+}
+
+function linkBox(ent) {
+ const others = [...S.entities.values()].filter((e) => e.id !== ent.id)
+ .sort((a, b) => (b.root - a.root) || a.type.localeCompare(b.type) || a.label.localeCompare(b.label));
+ if (!others.length) return "";
+ const opts = others.map((e) => `<option value="${esc(e.id)}">${e.root ? "★ " : ""}${esc(typeInfo(e.type).label)} · ${esc(short(e.label, 50))}</option>`).join("");
+ return `<details class="dork-group link-box"><summary>Vincular con otra entidad</summary>
+ <div class="muted small" style="margin-bottom:6px">Une a mano dos nodos que sabes que están relacionados (por ejemplo, el nombre con su alias).</div>
+ <label class="small">Con<select id="linkTarget">${opts}</select></label>
+ <label class="small">Relación<input id="linkRel" list="linkRels" value="${esc(defaultRel(ent, others[0]))}"></label>
+ <datalist id="linkRels">${LINK_RELS.map((r) => `<option value="${esc(r)}">`).join("")}</datalist>
+ <button class="primary small" data-act="link" style="margin-top:6px">Vincular</button></details>`;
+}
+
+function verdictBox(verdict, isAccount) {
+ const btn = (v, text, cls) => `<button class="small ${verdict === v ? `on ${cls}` : "ghost"}" data-verdict="${v}">${text}</button>`;
+ const note = verdict === "confirmada"
+ ? (isAccount ? "Confirmada: cuenta con 100 de confianza y referencia para juzgar las demás." : "Confirmado por ti.")
+ : verdict === "descartada" ? "Descartada: queda atenuada y no cuenta en el análisis."
+ : "¿Es de la persona que investigas? Tu decisión manda sobre la puntuación automática.";
+ return `<div class="section verdict ${esc(verdict || "")}">
+ <div class="verdict-btns">${btn("confirmada", "✔ Es la persona", "yes")}${btn("descartada", "✕ No es", "no")}${btn("", "Sin revisar", "")}</div>
+ <div class="muted small">${note}</div></div>`;
+}
+
+function renderWebHits(hits, engine) {
+ const exact = hits.filter((h) => h.kind === "exacta");
+ const partial = hits.filter((h) => h.kind !== "exacta");
+ const item = (h, i) => {
+ const inGraph = h.platform && S.entities.has(`account:${h.url.replace(/\/+$/, "").toLowerCase()}`);
+ return `<div class="web-hit">
+ <div>${h.platform ? `<span class="tag">${esc(h.platform)}</span> ` : ""}${link(h.url, h.title || h.url)}</div>
+ ${h.snippet ? `<div class="muted small">${esc(h.snippet)}</div>` : ""}
+ <div class="web-hit-foot">
+ ${h.kind !== "exacta" ? `<span class="muted small">Coincide: «${esc(h.variant)}»</span>` : "<span></span>"}
+ ${h.platform ? (inGraph ? `<span class="muted small">En el grafo</span>`
+ : `<button class="ghost small" data-webadd="${i}">Añadir al caso</button>`) : ""}
+ </div></div>`;
+ };
+ const group = (title, list, note, open) => list.length ? `<details class="dork-group"${open ? " open" : ""}>
+ <summary>${esc(title)} <span class="muted">(${list.length})</span></summary>
+ ${note ? `<div class="muted small" style="margin:4px 0">${esc(note)}</div>` : ""}
+ ${list.map((h) => item(h, hits.indexOf(h))).join("")}</details>` : "";
+ return `<div class="section"><h4>Resultados web (${hits.length})</h4>
+ ${group("Con el nombre completo", exact, "", true)}
+ ${group("Coincidencias parciales", partial, "Aparece sólo una parte del nombre (por ejemplo, sin el segundo nombre). Puede ser la persona o un homónimo: revísalo antes de añadirlo.", !exact.length)}
+ ${engine ? `<div class="muted small" style="margin-top:4px">Buscado con ${esc(engine)}</div>` : ""}</div>`;
+}
+
+function renderDetails() {
+ const box = $("#details");
+ if (isGroupId(S.selected) && groupById(S.selected.slice(4))) return renderGroupDetails(box, groupById(S.selected.slice(4)));
+ const ent = S.selected && S.entities.get(S.selected);
+ if (!ent) { box.innerHTML = `<div class="placeholder muted">Selecciona un nodo para ver sus datos.</div>`; return; }
+ const a = ent.attrs || {};
+ const avatar = safeUrl(a._avatar);
+ const canScan = typeInfo(ent.type).input;
+ const rows = Object.entries(a).filter(([k, v]) => !k.startsWith("_") && !ANALYSIS_KEYS.has(k) && v !== null && v !== "")
+ .map(([k, v]) => `<tr><td>${esc(k)}</td><td>${fmtValue(v)}</td></tr>`).join("");
+ const level = a["Nivel de confianza"];
+ const confBox = a.Confianza != null ? `<div class="section"><h4>¿Es la misma persona?</h4>
+ <div>Confianza <b>${esc(a.Confianza)}</b>/100 <span class="conf ${esc(level)}">${esc(level)}</span></div>
+ ${(a["Señales"] || []).length ? `<ul class="signals">${a["Señales"].map((s) => `<li>${esc(s)}</li>`).join("")}</ul>` : ""}
+ ${a["IA: veredicto"] ? `<div class="ai-box" style="margin-top:6px"><b>IA:</b> ${esc(a["IA: veredicto"])}${a["IA: motivo"] ? ` — ${esc(a["IA: motivo"])}` : ""}</div>` : ""}
+ </div>` : "";
+ const aiSummary = a["IA: resumen"] ? `<div class="section"><h4>Resumen de la IA</h4><div class="ai-box">${esc(a["IA: resumen"])}
+ ${a["IA: modelo"] ? `<div class="muted small" style="margin-top:4px">Modelo: ${esc(a["IA: modelo"])}</div>` : ""}</div></div>` : "";
+ const reverse = avatar ? REVERSE_SEARCH.map(([name, base]) => link(base + encodeURIComponent(avatar), name)).join("") : "";
+ const links = [...(a._links || [])];
+ if (ent.type === "url" || ent.type === "account") links.unshift(["Abrir", ent.value]);
+ if (a._lat != null && a._lon != null) links.push(["Ver en Google Maps", `https://www.google.com/maps?q=${a._lat},${a._lon}`]);
+ const uniqLinks = links.filter((l, i) => safeUrl(l[1]) && links.findIndex((x) => x[1] === l[1]) === i);
+ const plainLinks = uniqLinks.filter((l) => !(l[2] || []).length);
+ const fillLinks = uniqLinks.filter((l) => (l[2] || []).length);
+ const fillBox = fillLinks.length ? `<div class="section"><h4>Consultas con captcha</h4>
+ <div class="muted small">Al abrir el sitio se copia el dato: pégalo con Ctrl+V, resuelve el captcha y consulta.</div>
+ ${fillLinks.map((l) => `<div class="fill-link">
+ <a href="${esc(safeUrl(l[1]))}" target="_blank" rel="noopener noreferrer" data-fillcopy="${esc(l[2][0][1])}">${esc(l[0])}</a>
+ <div class="fill-vals">${l[2].map(([k, v]) => `<button class="fill-val" data-copyval="${esc(v)}" title="Copiar">${esc(k)}: <b>${esc(v)}</b></button>`).join("")}</div>
+ </div>`).join("")}</div>` : "";
+
+ const conns = [];
+ for (const e of S.edges) {
+ if (e.src === ent.id && S.entities.has(e.dst)) conns.push(["→", e.label, S.entities.get(e.dst), e]);
+ else if (e.dst === ent.id && S.entities.has(e.src)) conns.push(["←", e.label, S.entities.get(e.src), e]);
+ }
+ const runs = S.runs.filter((r) => r.entity_id === ent.id);
+ const latest = new Map(runs.map((r) => [r.module, r]));
+ const isFolded = S.layout.collapsed.includes(ent.id);
+ const nFound = isFolded ? S.fold.get(ent.id) || 0 : foundBy(ent.id, true).length;
+ const myGroup = S.layout.groups.find((g) => g.members?.includes(ent.id));
+ const deepMods = Object.values(S.modules).filter((m) => m.deep && m.inputs.includes(ent.type));
+ const manual = ent.type === "username" ? manualChecks(ent) : [];
+ const nUsers = [...S.entities.values()].filter((e) => e.type === "username").length;
+ const deepBox = deepMods.length ? `<div class="section deep-box"><h4>¿No encontraste mucho? Buscar a fondo</h4>
+ ${deepMods.map((m) => {
+ const r = latest.get(m.name);
+ const busy = S.running.has(`${ent.id}|${m.name}`);
+ const retry = m.name === "retry_blocked";
+ const label = retry && manual.length && !r ? `${m.title} (${manual.length})` : m.title;
+ return `<div class="deep-item"><button class="small" data-deep="${esc(m.name)}" ${busy ? "disabled" : ""}>${busy ? "Buscando…" : esc(label)}</button>
+ <span class="muted small">${esc(r ? r.message || "" : m.description)}</span>
+ ${retry && nUsers > 1 ? `<button class="ghost small" data-deepall="${esc(m.name)}" title="Lo lanza a la vez en cada usuario del caso">En los ${nUsers} usuarios del caso</button>` : ""}</div>`;
+ }).join("")}</div>` : "";
+ const manualBox = manual.length ? `<div class="section"><details class="dork-group">
+ <summary>Revisar a mano (${manual.length})</summary>
+ <div class="muted small" style="margin:4px 0">Estos sitios bloquean a los programas, pero no a tu navegador. Ábrelos y marca si el perfil existe.</div>
+ <div class="variant-btns"><button class="ghost small" data-mcheck="*" data-exists="0">Descartar toda la lista</button></div>
+ ${manual.map(([site, url]) => `<div class="manual-check">${link(url, site)}
+ <span class="variant-btns"><button class="ghost small" data-mcheck="${esc(site)}" data-exists="1">Existe</button><button class="ghost small" data-mcheck="${esc(site)}" data-exists="0">No existe</button></span></div>`).join("")}
+ </details></div>` : "";
+ const fam = ent.type === "username" ? aliasFamilies().find((f) => f.ids.includes(ent.id)) : null;
+ const famBox = fam ? `<div class="section"><h4>Familia de alias «${esc(fam.root)}» (${fam.ids.length})</h4>
+ <div class="muted small">Parecen el mismo apodo escrito de distintas formas. «Variantes del usuario» prueba las combinaciones que faltan.</div>
+ ${fam.ids.filter((id) => id !== ent.id).map((id) => `<div class="conn" data-goto="${esc(id)}"><span class="dot" style="background:${typeInfo("username").color}"></span>${esc(S.entities.get(id).label)}</div>`).join("")}
+ <div class="variant-btns"><button class="ghost small" data-act="aliasgroup">Agrupar la familia en una burbuja</button></div></div>` : "";
+ const variants = Object.entries(a._variantes || {});
+ const variantItem = ([v, hits]) => {
+ const inGraph = S.entities.has(`username:${v}`);
+ const match = hits.map((h) => h.match).find(Boolean);
+ const who = hits.map((h) => h.name).find(Boolean);
+ return `<div class="variant">
+ <div class="variant-h"><b>${esc(v)}</b>${who ? ` <span class="muted">· ${esc(who)}</span>` : ""}
+ ${match ? `<div class="small" style="color:var(--accent)">El nombre coincide con «${esc(match)}», que ya está en el caso</div>` : ""}</div>
+ <div class="linklist">${hits.map((h) => link(h.url, (h.match ? "★ " : "") + h.platform + (h.followers != null ? ` (${h.followers} seguidores)` : "") + (h.private ? " · privada" : ""))).join("")}</div>
+ <div class="variant-btns">${inGraph ? `<span class="muted small">Ya está en el grafo</span>`
+ : `<button class="ghost small" data-varadd="${esc(v)}">Añadir al caso</button><button class="primary small" data-varscan="${esc(v)}">Investigar</button>`}</div>
+ </div>`;
+ };
+ const likelyVars = variants.filter(([, hits]) => hits.some((h) => h.match));
+ const otherVars = variants.filter(([, hits]) => !hits.some((h) => h.match));
+ const variantBox = a._variantes_probadas ? `<div class="section"><h4>Variantes que existen (${variants.length} de ${esc(a._variantes_probadas)} probadas)</h4>
+ ${!variants.length ? `<div class="muted small">Ninguna existe en las redes probadas.</div>`
+ : likelyVars.length ? `${likelyVars.map(variantItem).join("")}
+ ${otherVars.length ? `<details class="dork-group"><summary>Otras, con nombres que no aparecen en el caso <span class="muted">(${otherVars.length})</span></summary>
+ ${otherVars.map(variantItem).join("")}</details>` : ""}`
+ : otherVars.map(variantItem).join("")}
+ ${(a._variantes_bloqueadas || []).length ? `<div class="muted small">No se pudo comprobar (la red limitó las consultas): ${esc(a._variantes_bloqueadas.join(", "))}. Reintenta más tarde.</div>` : ""}
+ <div class="muted small">Una variante puede ser de otra persona: compara el nombre y la foto antes de darla por buena.</div></div>` : "";
+ const foldBtn = isFolded
+ ? `<button class="small" data-act="fold" title="Vuelve a mostrar lo que salió de este nodo">Desplegar resultados (${nFound})</button>`
+ : nFound >= 2 ? `<button class="ghost small" data-act="fold" title="Esconde lo que salió de este nodo y lo deja como un solo nodo marcado con ⊕">Plegar resultados (${nFound})</button>` : "";
+
+ box.innerHTML = `
+ <div class="det-head">
+ ${avatar ? `<img src="${esc(avatar)}" referrerpolicy="no-referrer" alt="" onerror="this.remove()">` : ""}
+ <div style="min-width:0">
+ ${badge(ent.type)}
+ <div class="det-title">${esc(ent.label)}</div>
+ ${ent.label !== ent.value ? `<div class="det-value">${esc(ent.value)}</div>` : ""}
+ </div>
+ </div>
+ <div class="det-actions">
+ ${canScan ? `<button class="primary small" data-act="scan">Investigar…</button>` : ""}
+ <button class="ghost small" data-act="copy">Copiar</button>
+ <button class="ghost small" data-act="focus">Centrar</button>
+ <button class="ghost small danger" data-act="delete">Eliminar</button>
+ ${conns.some((c) => c[0] === "→") ? `<button class="ghost small" data-act="selfound" title="Selecciona todo lo que salió de este nodo y no está conectado con nada más, para borrarlo de una vez">Seleccionar sus resultados</button>` : ""}
+ ${foldBtn}
+ ${myGroup ? `<button class="ghost small" data-act="leavegroup">Sacar de «${esc(short(myGroup.name, 24))}»</button>` : ""}
+ </div>
+ ${ent.root ? "" : verdictBox(a._verdict, ent.type === "account")}
+ ${famBox}
+ ${variantBox}
+ ${deepBox}
+ ${manualBox}
+ ${aiSummary}
+ ${confBox}
+ ${rows ? `<div class="section"><h4>Datos</h4><table class="attrs">${rows}</table></div>` : ""}
+ ${plainLinks.length ? `<div class="section"><h4>Enlaces</h4><div class="linklist">${plainLinks.map((l) => link(l[1], l[0])).join("")}</div></div>` : ""}
+ ${fillBox}
+ ${reverse ? `<div class="section"><h4>Buscar esta foto en otros sitios</h4><div class="linklist">${reverse}</div></div>` : ""}
+ ${(a._web || []).length ? renderWebHits(a._web, a._web_engine) : ""}
+ ${(a._candidatos || []).length ? `<div class="section"><h4>Usuarios probables</h4>${a._candidatos.map((c) =>
+ `<div class="cand"><span>${esc(c)}</span><button class="ghost small" data-cand="${esc(c)}">Investigar</button></div>`).join("")}</div>` : ""}
+ ${(a._dorks || []).length ? `<div class="section"><h4>Dorks de búsqueda (${a._dorks.length})</h4>${renderDorks(a._dorks)}</div>` : ""}
+ ${conns.length ? `<div class="section"><h4>Conexiones (${conns.length})</h4>${conns.slice(0, 150).map(([dir, rel, o, e]) =>
+ `<div class="conn" data-goto="${esc(o.id)}">${dir} <span class="dot" style="background:${typeInfo(o.type).color}"></span>${esc(short(o.label, 44))} <span class="rel">${esc(rel)}</span>${e.source === "manual"
+ ? `<button class="ghost small unlink" title="Quitar este vínculo" data-unlink="${S.edges.indexOf(e)}">✕</button>` : ""}</div>`).join("")}</div>` : ""}
+ ${linkBox(ent)}
+ ${latest.size ? `<div class="section"><h4>Fuentes consultadas</h4>${[...latest.values()].map((r) => {
+ const [icon, cls] = STATUS[r.status] || ["?", ""];
+ return `<div class="src"><span class="${cls}">${icon}</span><span>${esc(S.modules[r.module]?.title || r.module)}</span><span class="msg">${esc(r.message || "")}</span></div>`;
+ }).join("")}</div>` : ""}
+ ${(a._fuentes || []).length ? `<div class="section muted small">Datos aportados por: ${esc(a._fuentes.join(", "))}</div>` : ""}
+ `;
+}
+const renderDetailsSoon = debounce(renderDetails, 200);
+
+$("#details").addEventListener("change", (ev) => {
+ if (ev.target.id !== "linkTarget") return;
+ const ent = S.selected && S.entities.get(S.selected);
+ if (ent) $("#linkRel").value = defaultRel(ent, S.entities.get(ev.target.value));
+});
+
+$("#details").addEventListener("click", async (ev) => {
+ if (isGroupId(S.selected)) {
+ const goto = ev.target.closest("[data-goto]")?.dataset.goto;
+ if (goto) return select(goto, true);
+ const gact = ev.target.closest("[data-gact]")?.dataset.gact;
+ if (gact) groupAction(S.selected.slice(4), gact);
+ return;
+ }
+ const ent = S.selected && S.entities.get(S.selected);
+ if (!ent) return;
+ const fillCopy = ev.target.closest("[data-fillcopy]")?.dataset.fillcopy;
+ if (fillCopy) {
+ return toast(await copyText(fillCopy) ? `Copiado «${fillCopy}»: pégalo en el formulario con Ctrl+V` : "No se pudo copiar");
+ }
+ const copyVal = ev.target.closest("[data-copyval]")?.dataset.copyval;
+ if (copyVal != null) return toast(await copyText(copyVal) ? `Copiado «${copyVal}»` : "No se pudo copiar");
+ const act = ev.target.closest("[data-act]")?.dataset.act;
+ const goto = ev.target.closest("[data-goto]")?.dataset.goto;
+ const cand = ev.target.closest("[data-cand]")?.dataset.cand;
+ const unlink = ev.target.closest("[data-unlink]")?.dataset.unlink;
+ if (unlink != null) {
+ const e = S.edges[+unlink];
+ if (!e) return;
+ await api(`/api/cases/${S.caseId}/edges/delete`, { method: "POST", body: { src: e.src, dst: e.dst, label: e.label } });
+ S.edges.splice(+unlink, 1);
+ cy.getElementById(`${e.src}→${e.dst}|${e.label}`).remove();
+ renderDetails();
+ return toast("Vínculo quitado");
+ }
+ if (goto) return select(goto, true);
+ if (act === "link") {
+ const dst = $("#linkTarget").value;
+ const label = $("#linkRel").value.trim() || "relacionado con";
+ const e = await api(`/api/cases/${S.caseId}/edges`, { method: "POST", body: { src: ent.id, dst, label } });
+ addEdge(e);
+ scheduleLayout();
+ renderDetails();
+ return toast(`Vinculado: ${short(ent.label, 30)} ${label} ${short(S.entities.get(dst)?.label || "", 30)}`);
+ }
+ const verdictBtn = ev.target.closest("[data-verdict]");
+ if (verdictBtn) {
+ const v = verdictBtn.dataset.verdict || null;
+ if ((ent.attrs._verdict || null) === v) return;
+ const res = await api(`/api/cases/${S.caseId}/verdict/${encodeURIComponent(ent.id)}`, { method: "PUT", body: { verdict: v } });
+ for (const e2 of res.entities) upsertNode(e2);
+ renderDetails();
+ refreshViewSoon();
+ const others = res.entities.filter((e2) => e2.id !== ent.id).length;
+ return toast(v ? `Marcada como ${v === "confirmada" ? "suya" : "de otra persona"}` + (others ? ` · ${others} cuentas recalculadas` : "") : "Marca quitada");
+ }
+ const webadd = ev.target.closest("[data-webadd]")?.dataset.webadd;
+ if (webadd != null) {
+ const h = (ent.attrs._web || [])[+webadd];
+ if (!h) return;
+ const exact = h.kind === "exacta";
+ const rel = exact ? "posible perfil (nombre completo)" : "posible perfil (nombre parcial)";
+ const e2 = await api(`/api/cases/${S.caseId}/entities`, { method: "POST", body: {
+ value: h.url, type: "account", parent: ent.id, rel,
+ attrs: { Plataforma: h.platform, Usuario: h.user, "Título": h.title, "Descripción": h.snippet || null,
+ "Verificación": exact ? "Búsqueda web: perfil con el nombre completo" : `Búsqueda web: coincidencia parcial («${h.variant}»)`,
+ _links: [["Abrir perfil", h.url]], _fuentes: ["Añadido a mano desde la búsqueda web"] },
+ } });
+ upsertNode(e2, ent.id);
+ addEdge({ src: ent.id, dst: e2.id, label: rel, source: "manual" });
+ renderLegend();
+ scheduleLayout();
+ renderDetails();
+ return toast("Perfil añadido al caso");
+ }
+ const deep = ev.target.closest("[data-deep]")?.dataset.deep;
+ if (deep) {
+ try { await startScan(ent.id, [deep], 0); } catch (e) { toast(e.message, true); }
+ return renderDetails();
+ }
+ const deepAll = ev.target.closest("[data-deepall]")?.dataset.deepall;
+ if (deepAll) {
+ const users = [...S.entities.values()].filter((e) => e.type === "username" && !S.running.has(`${e.id}|${deepAll}`));
+ if (!users.length || !confirm(`¿Reintentar lo bloqueado en los ${users.length} usuarios? Puede tardar unos minutos.`)) return;
+ for (const u of users) { try { await startScan(u.id, [deepAll], 0); } catch (e) { toast(e.message, true); } }
+ toast(`Reintentando en ${users.length} usuarios`);
+ return renderDetails();
+ }
+ const mcheck = ev.target.closest("[data-mcheck]");
+ if (mcheck) {
+ const exists = mcheck.dataset.exists === "1";
+ if (mcheck.dataset.mcheck === "*" && !confirm(`¿Quitar los ${manualChecks(ent).length} sitios de la lista?`)) return;
+ const res = await api(`/api/cases/${S.caseId}/manual-check/${encodeURIComponent(ent.id)}`,
+ { method: "POST", body: { site: mcheck.dataset.mcheck, exists } });
+ for (const e2 of res.entities) upsertNode(e2, ent.id);
+ if (res.edge) { addEdge(res.edge); renderLegend(); scheduleLayout(); }
+ renderDetails();
+ if (mcheck.dataset.mcheck === "*") return toast("Lista vaciada");
+ return toast(exists ? `Cuenta de ${mcheck.dataset.mcheck} añadida al caso` : `${mcheck.dataset.mcheck} descartado`);
+ }
+ const variant = ev.target.closest("[data-varadd], [data-varscan]");
+ if (variant) {
+ const v = variant.dataset.varadd ?? variant.dataset.varscan;
+ const hits = (ent.attrs._variantes || {})[v] || [];
+ const rel = "posible variante";
+ const e2 = await api(`/api/cases/${S.caseId}/entities`, { method: "POST", body: {
+ value: v, type: "username", parent: ent.id, rel,
+ attrs: { "Variante de": ent.value, "Existe en": hits.map((h) => h.platform).join(", ") || null,
+ _fuentes: ["Variantes del usuario"] },
+ } });
+ upsertNode(e2, ent.id);
+ addEdge({ src: ent.id, dst: e2.id, label: rel, source: "manual" });
+ renderLegend();
+ scheduleLayout();
+ renderDetails();
+ if (variant.dataset.varscan == null) return toast(`«${v}» añadido al caso`);
+ return startScan(e2.id, null, 0);
+ }
+ if (cand) {
+ const e2 = await api(`/api/cases/${S.caseId}/entities`, { method: "POST", body: { value: cand, type: "username" } });
+ upsertNode(e2, ent.id);
+ renderLegend();
+ scheduleLayout();
+ return startScan(e2.id, null, 0);
+ }
+ if (act === "scan") openPivot(ent.id);
+ if (act === "copy") toast(await copyText(ent.value) ? "Copiado" : "No se pudo copiar");
+ if (act === "focus") select(ent.id, true);
+ if (act === "delete") return deleteMany([ent.id]);
+ if (act === "fold") return toggleFold(ent.id);
+ if (act === "aliasgroup") {
+ const fam = aliasFamilies().find((f) => f.ids.includes(ent.id));
+ if (!fam) return;
+ const g = aliasGroup(fam);
+ return layoutChanged(`Burbuja «${g.name}» creada`);
+ }
+ if (act === "leavegroup") {
+ for (const g of S.layout.groups) if (g.members) g.members = g.members.filter((x) => x !== ent.id);
+ return layoutChanged("Sacado de la burbuja");
+ }
+ if (act === "selfound") {
+ const ids = foundBy(ent.id);
+ if (!ids.length) return toast("No hay resultados que dependan sólo de este nodo");
+ cy.nodes().unselect();
+ ids.forEach((id) => cy.getElementById(id).select());
+ return toast(`${ids.length} nodos seleccionados: pulsa «Eliminar» en la barra o la tecla Supr`);
+ }
+});
+
+// ---------------------------------------------------------------- borrado en lote
+function degreeMap() {
+ const d = {};
+ for (const e of S.edges) { d[e.src] = (d[e.src] || 0) + 1; d[e.dst] = (d[e.dst] || 0) + 1; }
+ return d;
+}
+
+/** Nodos que salieron de este (siguiendo sus flechas) y que no están conectados con nada más del caso. */
+function foundBy(startId, includeConfirmed = false) {
+ const out = new Map(), nb = new Map();
+ for (const e of S.edges) {
+ if (!out.has(e.src)) out.set(e.src, []);
+ out.get(e.src).push(e.dst);
+ for (const [a, b] of [[e.src, e.dst], [e.dst, e.src]]) {
+ if (!nb.has(a)) nb.set(a, new Set());
+ nb.get(a).add(b);
+ }
+ }
+ const keep = (id) => { const e = S.entities.get(id); return !e || e.root || (!includeConfirmed && e.attrs?._verdict === "confirmada"); };
+ const set = new Set();
+ const queue = [startId];
+ while (queue.length) {
+ for (const d of out.get(queue.shift()) || []) {
+ if (d === startId || set.has(d) || keep(d)) continue;
+ set.add(d);
+ queue.push(d);
+ }
+ }
+ let changed = true;
+ while (changed) {
+ changed = false;
+ for (const id of [...set]) {
+ if ([...(nb.get(id) || [])].some((o) => o !== startId && !set.has(o))) { set.delete(id); changed = true; }
+ }
+ }
+ return [...set];
+}
+
+async function deleteMany(ids) {
+ ids = [...new Set(ids)].filter((id) => S.entities.has(id));
+ if (!ids.length) return toast("No hay nada que eliminar");
+ const ents = ids.map((id) => S.entities.get(id));
+ const roots = ents.filter((e) => e.root).length;
+ const confirmed = ents.filter((e) => e.attrs?._verdict === "confirmada").length;
+ const warn = [roots && `${roots} objetivo(s) que buscaste`, confirmed && `${confirmed} confirmada(s) por ti`].filter(Boolean);
+ const msg = ids.length === 1 ? `¿Eliminar «${ents[0].label}» del caso?`
+ : `¿Eliminar ${ids.length} nodos del caso?` + (warn.length ? `\n\nIncluye ${warn.join(" y ")}.` : "");
+ if (!confirm(msg)) return;
+ const { deleted } = await api(`/api/cases/${S.caseId}/entities/delete`, { method: "POST", body: { ids } });
+ const gone = new Set(ids);
+ cy.batch(() => ids.forEach((id) => cy.getElementById(id).remove()));
+ ids.forEach((id) => { S.entities.delete(id); S.listSel.delete(id); });
+ S.edges = S.edges.filter((e) => !gone.has(e.src) && !gone.has(e.dst));
+ S.runs = S.runs.filter((r) => !gone.has(r.entity_id));
+ S.layout.collapsed = S.layout.collapsed.filter((id) => !gone.has(id));
+ applyGrouping();
+ saveLayout();
+ select(null);
+ renderAll();
+ updateSelBar();
+ toast(`${deleted} nodos eliminados`);
+}
+
+function updateSelBar() {
+ const n = cy ? cy.nodes(":selected").length : 0;
+ $("#selBar").classList.toggle("hidden", n < 2);
+ $("#selHint").classList.toggle("hidden", n >= 2);
+ $("#selCount").textContent = `${n} seleccionados`;
+}
+let selBarTimer;
+function updateSelBarSoon() { clearTimeout(selBarTimer); selBarTimer = setTimeout(updateSelBar, 50); }
+
+$("#selDelete").addEventListener("click", () => deleteMany(cy.nodes(":selected").map((n) => n.id())));
+$("#selClear").addEventListener("click", () => { cy.nodes().unselect(); updateSelBar(); });
+document.addEventListener("keydown", (ev) => {
+ if (ev.key !== "Delete" || ev.target.closest("input, textarea, select, dialog") || S.tab !== "graph" || !cy) return;
+ const ids = cy.nodes(":selected").map((n) => n.id());
+ if (ids.length) deleteMany(ids);
+});
+
+// ---------------------------------------------------------------- burbujas y nodos plegados
+const GROUP_COLORS = ["#ff9f43", "#4fc3f7", "#b388ff", "#69f0ae", "#ff6e9c", "#ffd54f", "#80cbc4", "#f48fb1"];
+const grpNode = (gid) => `grp:${gid}`;
+const isGroupId = (id) => typeof id === "string" && id.startsWith("grp:");
+const groupById = (gid) => S.layout.groups.find((g) => g.id === gid);
+const saveLayout = debounce(() => {
+ if (S.caseId) api(`/api/cases/${S.caseId}`, { method: "PATCH", body: { layout: S.layout } }).catch(() => {});
+}, 500);
+
+/** Cuentas que salieron sólo de este usuario. */
+function accountsOf(uid) {
+ const inc = new Map();
+ for (const e of S.edges) { if (!inc.has(e.dst)) inc.set(e.dst, new Set()); inc.get(e.dst).add(e.src); }
+ return [...new Set(S.edges.filter((e) => e.src === uid && S.entities.get(e.dst)?.type === "account"
+ && [...inc.get(e.dst)].every((s) => s === uid)).map((e) => e.dst))];
+}
+
+/** Para cada nodo, la búsqueda (raíz) de la que salió; null si salió de varias. */
+function treeOwners() {
+ const out = new Map();
+ for (const e of S.edges) { if (!out.has(e.src)) out.set(e.src, []); out.get(e.src).push(e.dst); }
+ const owner = new Map();
+ for (const r of [...S.entities.values()].filter((e) => e.root)) {
+ const seen = new Set([r.id]);
+ const queue = [r.id];
+ while (queue.length) {
+ for (const d of out.get(queue.shift()) || []) {
+ const ent = S.entities.get(d);
+ if (seen.has(d) || !ent || ent.root) continue;
+ seen.add(d);
+ queue.push(d);
+ owner.set(d, owner.has(d) && owner.get(d) !== r.id ? null : r.id);
+ }
+ }
+ }
+ return owner;
+}
+
+/** Miembros de cada burbuja: las hechas a mano mandan sobre las automáticas. */
+function groupMembers() {
+ const of = new Map();
+ const members = new Map(S.layout.groups.map((g) => [g.id, []]));
+ const put = (eid, gid) => { if (!of.has(eid) && S.entities.has(eid)) { of.set(eid, gid); members.get(gid).push(eid); } };
+ for (const g of S.layout.groups) (g.members || []).forEach((id) => put(id, g.id));
+ for (const g of S.layout.groups) if (g.kind === "accounts") accountsOf(g.anchor).forEach((id) => put(id, g.id));
+ const trees = S.layout.groups.filter((g) => g.kind === "tree");
+ if (trees.length) {
+ const owner = treeOwners();
+ for (const g of trees) {
+ put(g.anchor, g.id);
+ for (const [id, r] of owner) if (r === g.anchor) put(id, g.id);
+ }
+ }
+ return { of, members };
+}
+
+function centroid(ids) {
+ const ps = ids.map((id) => cy.getElementById(id)).filter((n) => n.length).map((n) => n.position());
+ if (!ps.length) return { x: 0, y: 0 };
+ return { x: ps.reduce((s, p) => s + p.x, 0) / ps.length, y: ps.reduce((s, p) => s + p.y, 0) / ps.length };
+}
+
+function applyGrouping() {
+ if (!cy) return;
+ for (const g of S.layout.groups) if (g.members) g.members = g.members.filter((id) => S.entities.has(id));
+ S.layout.groups = S.layout.groups.filter((g) => (g.members ? g.members.length : S.entities.has(g.anchor)));
+ const { of, members } = groupMembers();
+ const hiddenBy = new Map();
+ const rep = (id) => {
+ const seen = new Set();
+ while (hiddenBy.has(id) && !seen.has(id)) { seen.add(id); id = hiddenBy.get(id); }
+ return id;
+ };
+ S.fold = new Map();
+ for (const id of S.layout.collapsed) {
+ if (!S.entities.has(id)) continue;
+ const ids = foundBy(id, true);
+ S.fold.set(id, ids.length);
+ for (const d of ids) if (!hiddenBy.has(d) && rep(id) !== d) hiddenBy.set(d, id);
+ }
+ const live = S.layout.groups.filter((g) => members.get(g.id).length);
+ for (const g of live) {
+ const gn = grpNode(g.id);
+ const mem = members.get(g.id);
+ if (mem.every((m) => hiddenBy.has(m))) hiddenBy.set(gn, mem[0]);
+ else if (g.collapsed) mem.forEach((m) => { if (!hiddenBy.has(m)) hiddenBy.set(m, gn); });
+ }
+ S.hiddenBy = hiddenBy;
+
+ cy.batch(() => {
+ cy.edges(".meta").remove();
+ const wanted = new Set(live.map((g) => grpNode(g.id)));
+ cy.nodes("[?isGroup]").forEach((n) => {
+ if (wanted.has(n.id())) return;
+ n.children().move({ parent: null });
+ n.remove();
+ });
+ for (const g of live) {
+ const gn = grpNode(g.id);
+ const mem = members.get(g.id);
+ const data = { id: gn, isGroup: true, color: g.color, shape: "round-rectangle", size: 64,
+ short: g.collapsed ? `${short(I18N.tr(g.name), 30)} · ${mem.length}` : short(I18N.tr(g.name), 40) };
+ const n = cy.getElementById(gn);
+ if (n.length) n.data(data);
+ else cy.add({ group: "nodes", data, position: centroid(mem) });
+ cy.getElementById(gn).toggleClass("grp-collapsed", !!g.collapsed);
+ }
+ cy.nodes().not("[?isGroup]").forEach((n) => {
+ const g = groupById(of.get(n.id()));
+ const parent = g && !g.collapsed ? grpNode(g.id) : null;
+ const cur = n.parent().length ? n.parent().id() : null;
+ if (cur !== parent) n.move({ parent });
+ });
+ cy.nodes().forEach((n) => {
+ n.toggleClass("fold-hidden", hiddenBy.has(n.id()));
+ if (n.data("isGroup")) return;
+ n.toggleClass("folded", (S.fold.get(n.id()) || 0) > 0);
+ const ent = S.entities.get(n.id());
+ if (ent) n.data("short", nodeData(ent).short);
+ });
+ const meta = new Map();
+ for (const e of S.edges) {
+ if (!hiddenBy.has(e.src) && !hiddenBy.has(e.dst)) continue;
+ const a = rep(e.src), b = rep(e.dst);
+ if (a === b || hiddenBy.has(a) || hiddenBy.has(b) || !cy.getElementById(a).length || !cy.getElementById(b).length) continue;
+ const k = `meta:${a}→${b}`;
+ meta.set(k, { a, b, n: (meta.get(k)?.n || 0) + 1 });
+ }
+ for (const [id, m] of meta) {
+ cy.add({ group: "edges", classes: "meta", data: { id, source: m.a, target: m.b, label: I18N.tr(m.n > 1 ? `${m.n} vínculos` : "vínculo") } });
+ }
+ });
+ if (isGroupId(S.selected) && !groupById(S.selected.slice(4))) select(null);
+}
+const applyGroupingSoon = debounce(applyGrouping, 300);
+
+/** Si el nodo está escondido dentro de algo plegado, lo despliega. */
+function reveal(id) {
+ let changed = false;
+ for (let guard = 0; S.hiddenBy.has(id) && guard < 20; guard++) {
+ const r = S.hiddenBy.get(id);
+ if (isGroupId(r)) { const g = groupById(r.slice(4)); if (g) g.collapsed = false; }
+ else S.layout.collapsed = S.layout.collapsed.filter((x) => x !== r);
+ changed = true;
+ applyGrouping();
+ }
+ if (changed) { saveLayout(); scheduleLayout(); }
+}
+
+function layoutChanged(msg) {
+ applyGrouping();
+ saveLayout();
+ runLayout(false);
+ renderDetails();
+ if (msg) toast(msg);
+}
+
+function toggleFold(id) {
+ const i = S.layout.collapsed.indexOf(id);
+ if (i >= 0) S.layout.collapsed.splice(i, 1);
+ else S.layout.collapsed.push(id);
+ layoutChanged(i >= 0 ? "Resultados desplegados" : "Resultados plegados: el nodo queda marcado con ⊕");
+}
+
+function toggleGroup(gid) {
+ const g = groupById(gid);
+ if (!g) return;
+ g.collapsed = !g.collapsed;
+ layoutChanged(g.collapsed ? `Burbuja «${g.name}» plegada` : `Burbuja «${g.name}» desplegada`);
+}
+
+function newGroup(props) {
+ const used = new Set(S.layout.groups.map((g) => g.color));
+ const color = GROUP_COLORS.find((c) => !used.has(c)) || GROUP_COLORS[S.layout.groups.length % GROUP_COLORS.length];
+ const g = { id: Math.random().toString(36).slice(2, 9), color, collapsed: false, ...props };
+ S.layout.groups.push(g);
+ return g;
+}
+
+const GROUP_KIND = {
+ tree: "Todo lo que salió de esta búsqueda; se actualiza sola con los nuevos resultados.",
+ accounts: "Cuentas encontradas sólo para este usuario; se actualiza sola.",
+ alias: "Alias que parecen el mismo apodo escrito de distintas formas, con sus cuentas.",
+};
+
+// ---------------------------------------------------------------- familias de alias (misma lógica que app/modules/username.py)
+const ALIAS_PRE = ["private", "priv", "official", "oficial", "real", "its", "iam", "the", "soy", "not"];
+const ALIAS_SUF = ["private", "priv", "official", "oficial", "real", "backup", "bkp", "alt", "spam", "fake", "xx"];
+const ALIAS_LEET = { 0: "o", 1: "i", 3: "e", 4: "a", 5: "s", 7: "t", "@": "a", $: "s" };
+
+function aliasStrip(c) {
+ const out = [];
+ for (const sep of [".", "_", "-", ""]) {
+ for (const p of ALIAS_PRE) {
+ const rest = c.slice((p + sep).length);
+ if (c.startsWith(p + sep) && rest.length >= 3 && (sep || p.length >= 4)) out.push(rest);
+ }
+ for (const s of ALIAS_SUF) {
+ const rest = c.slice(0, c.length - (sep + s).length);
+ if (c.endsWith(sep + s) && rest.length >= 3 && (sep || s.length >= 4)) out.push(rest);
+ }
+ }
+ return out.map((x) => x.replace(/^[._-]+|[._-]+$/g, "")).filter((x) => x.length >= 3);
+}
+
+function aliasKey(u) {
+ let s = u.toLowerCase().trim().replace(/^@/, "");
+ for (let k = 0; k < 2; k++) {
+ const st = aliasStrip(s);
+ if (st.length) s = st.reduce((a, b) => (b.length < a.length ? b : a));
+ }
+ s = s.replace(/[^a-z0-9@$]/g, "").replace(/\d{2,}$/, "");
+ s = [...s].map((c) => ALIAS_LEET[c] || c).join("");
+ return s.replace(/(.)\1+/g, "$1").replace(/\d/g, "");
+}
+
+function aliasCommon(a, b) {
+ let best = "";
+ for (let i = 0; i < a.length; i++) {
+ for (let j = i + best.length + 1; j <= a.length; j++) {
+ if (!b.includes(a.slice(i, j))) break;
+ best = a.slice(i, j);
+ }
+ }
+ return best;
+}
+
+/** Familias (de 2 o más) entre los usuarios del caso: [{root, ids}]. */
+function aliasFamilies() {
+ const users = [...S.entities.values()].filter((e) => e.type === "username" && aliasKey(e.value));
+ const keys = users.map((e) => aliasKey(e.value));
+ const parent = users.map((_, i) => i);
+ const find = (i) => { while (parent[i] !== i) i = parent[i] = parent[parent[i]]; return i; };
+ for (let i = 0; i < users.length; i++) {
+ for (let j = i + 1; j < users.length; j++) {
+ const n = aliasCommon(keys[i], keys[j]).length;
+ if (n >= 4 && n >= 0.6 * Math.min(keys[i].length, keys[j].length)) parent[find(i)] = find(j);
+ }
+ }
+ const groups = new Map();
+ users.forEach((_, i) => { const r = find(i); if (!groups.has(r)) groups.set(r, []); groups.get(r).push(i); });
+ return [...groups.values()].filter((g) => g.length >= 2).map((g) => {
+ let root = keys[g[0]];
+ for (const i of g.slice(1)) root = aliasCommon(root, keys[i]);
+ if (root.length < 3) root = g.map((i) => keys[i]).reduce((a, b) => (b.length < a.length ? b : a));
+ return { root, ids: g.map((i) => users[i].id) };
+ });
+}
+
+function aliasGroup(fam) {
+ const ids = [...new Set(fam.ids.flatMap((id) => [id, ...accountsOf(id)]))];
+ const set = new Set(ids);
+ for (const g of S.layout.groups) if (g.members) g.members = g.members.filter((x) => !set.has(x));
+ return newGroup({ name: `Alias «${fam.root}»`, kind: "alias", members: ids });
+}
+
+const BLOCKED_PROFILE_URLS = { Instagram: "https://www.instagram.com/{}/", TikTok: "https://www.tiktok.com/@{}" };
+
+/** Sitios que no se pudieron comprobar solos: [[sitio, url]]. */
+function manualChecks(ent) {
+ const a = ent.attrs || {};
+ const prof = (a._bloq_perfiles || []).filter((p) => BLOCKED_PROFILE_URLS[p])
+ .map((p) => [p, BLOCKED_PROFILE_URLS[p].replace("{}", ent.value)]);
+ const rank = (s) => { const i = MANUAL_FIRST.indexOf(s.toLowerCase()); return i < 0 ? 999 : i; };
+ return [...prof, ...Object.entries(a._bloq_sitios || {}).sort((x, y) => rank(x[0]) - rank(y[0]) || x[0].localeCompare(y[0]))];
+}
+/** Redes donde suele estar una persona corriente: van primero en «Revisar a mano». */
+const MANUAL_FIRST = ["pinterest", "tumblr", "vsco", "wattpad", "spotify", "soundcloud", "linktree", "deviantart", "letterboxd",
+ "archive of our own", "fandom", "9gag", "smule", "mydramalist", "artstation", "behance", "kofi", "redbubble", "xbox gamertag",
+ "psnprofiles.com", "fortnitetracker", "osu!", "exophase", "curseforge", "musescore", "discogs", "rate your music", "rumble",
+ "academia.edu", "untappd", "codepen", "gamefaqs"];
+
+function renderGroupDetails(box, g) {
+ const mem = groupMembers().members.get(g.id) || [];
+ const ents = mem.map((id) => S.entities.get(id)).filter(Boolean)
+ .sort((a, b) => (b.root - a.root) || a.type.localeCompare(b.type) || a.label.localeCompare(b.label));
+ const counts = {};
+ ents.forEach((e) => (counts[e.type] = (counts[e.type] || 0) + 1));
+ box.innerHTML = `
+ <div class="det-head"><div style="min-width:0">
+ <span class="badge" style="background:${esc(g.color)}">Burbuja</span>
+ <div class="det-title">${esc(g.name)}</div>
+ <div class="det-value">${ents.length} nodos${g.collapsed ? " · plegada" : ""}</div></div></div>
+ <div class="det-actions">
+ <button class="primary small" data-gact="toggle">${g.collapsed ? "Desplegar" : "Plegar"}</button>
+ <button class="ghost small" data-gact="rename">Renombrar</button>
+ <button class="ghost small" data-gact="select">Seleccionar sus nodos</button>
+ <button class="ghost small danger" data-gact="ungroup">Quitar burbuja</button>
+ </div>
+ <div class="section muted small">${esc(GROUP_KIND[g.kind] || "Creada a mano: añade nodos seleccionándolos y pulsando «Agrupar en burbuja».")}
+ Doble clic en la burbuja la pliega o despliega.</div>
+ <div class="section"><h4>Contenido</h4><div>${Object.entries(counts).sort((a, b) => b[1] - a[1])
+ .map(([t, n]) => `${badge(t)} ${n}`).join(" &nbsp;")}</div></div>
+ <div class="section"><h4>Nodos (${ents.length})</h4>${ents.slice(0, 200).map((o) =>
+ `<div class="conn" data-goto="${esc(o.id)}"><span class="dot" style="background:${typeInfo(o.type).color}"></span>${o.root ? "★ " : ""}${esc(short(o.label, 50))}</div>`).join("")}</div>`;
+}
+
+function groupAction(gid, act) {
+ const g = groupById(gid);
+ if (!g) return;
+ if (act === "toggle") return toggleGroup(gid);
+ if (act === "rename") {
+ const name = prompt("Nombre de la burbuja:", g.name);
+ if (!name?.trim()) return;
+ g.name = name.trim();
+ return layoutChanged();
+ }
+ if (act === "select") {
+ if (g.collapsed) { g.collapsed = false; layoutChanged(); }
+ const mem = groupMembers().members.get(gid) || [];
+ cy.nodes().unselect();
+ mem.forEach((id) => cy.getElementById(id).select());
+ return toast(`${mem.length} nodos seleccionados`);
+ }
+ if (act === "ungroup") {
+ S.layout.groups = S.layout.groups.filter((x) => x.id !== gid);
+ S.selected = null;
+ return layoutChanged(`Burbuja «${g.name}» quitada (los nodos siguen en el caso)`);
+ }
+}
+
+$("#selGroup").addEventListener("click", () => {
+ const ids = cy.nodes(":selected").map((n) => n.id()).filter((id) => S.entities.has(id));
+ if (!ids.length) return;
+ const ents = ids.map((id) => S.entities.get(id));
+ const hint = ents.find((e) => e.root) || ents.find((e) => e.type === "person") || ents.find((e) => e.type === "username");
+ const name = prompt(`Nombre de la burbuja (${ids.length} nodos):`, hint ? hint.label : `Grupo ${S.layout.groups.length + 1}`);
+ if (!name?.trim()) return;
+ const set = new Set(ids);
+ for (const g of S.layout.groups) if (g.members) g.members = g.members.filter((x) => !set.has(x));
+ const g = newGroup({ name: name.trim(), members: ids });
+ cy.nodes().unselect();
+ updateSelBar();
+ layoutChanged(`Burbuja «${g.name}» creada: doble clic sobre ella para plegarla`);
+});
+
+$("#groupSel").addEventListener("change", (ev) => {
+ const how = ev.target.value;
+ ev.target.value = "";
+ if (!how || !S.entities.size) return;
+ const ents = [...S.entities.values()];
+ let msg = "";
+ if (how === "roots") {
+ S.layout.groups = S.layout.groups.filter((g) => g.kind !== "tree");
+ const owner = treeOwners();
+ const roots = ents.filter((e) => e.root && [...owner.values()].includes(e.id));
+ roots.forEach((r) => newGroup({ name: short(r.label, 40), kind: "tree", anchor: r.id }));
+ const shared = [...owner.values()].filter((v) => v === null).length;
+ msg = roots.length ? `${roots.length} burbuja(s), una por búsqueda` + (shared ? ` · ${shared} nodos compartidos quedan fuera, entre ellas` : "")
+ : "Aún no hay resultados que agrupar";
+ } else if (how === "platform") {
+ S.layout.groups = S.layout.groups.filter((g) => g.kind !== "accounts");
+ const users = ents.filter((e) => e.type === "username" && accountsOf(e.id).length >= 3);
+ users.forEach((u) => newGroup({ name: `Cuentas de ${short(u.label, 30)}`, kind: "accounts", anchor: u.id }));
+ msg = users.length ? `${users.length} burbuja(s) de cuentas` : "Ningún usuario tiene 3 o más cuentas propias";
+ } else if (how === "alias") {
+ S.layout.groups = S.layout.groups.filter((g) => g.kind !== "alias");
+ const fams = aliasFamilies();
+ fams.forEach(aliasGroup);
+ msg = fams.length ? `${fams.length} familia(s) de alias: ${fams.map((f) => `«${f.root}»`).join(", ")}`
+ : "No hay alias parecidos entre sí en el caso";
+ } else if (how === "collapseBig") {
+ const big = (list) => list.filter((e) => !S.layout.collapsed.includes(e.id) && foundBy(e.id, true).length >= 8);
+ let pick = big(ents.filter((e) => !e.root));
+ if (!pick.length) pick = big(ents.filter((e) => e.root));
+ S.layout.collapsed.push(...pick.map((e) => e.id));
+ msg = pick.length ? `${pick.length} nodo(s) plegados (marcados con ⊕): selecciónalos y pulsa «Desplegar resultados»`
+ : "No hay nodos con 8 o más resultados propios";
+ } else if (how === "collapseGroups") {
+ S.layout.groups.forEach((g) => (g.collapsed = true));
+ msg = S.layout.groups.length ? "Burbujas plegadas" : "No hay burbujas: crea una primero";
+ } else if (how === "expand") {
+ S.layout.collapsed = [];
+ S.layout.groups.forEach((g) => (g.collapsed = false));
+ msg = "Todo desplegado";
+ } else if (how === "ungroup") {
+ S.layout.groups = [];
+ msg = "Burbujas quitadas";
+ }
+ layoutChanged(msg);
+});
+
+$("#cleanSel").addEventListener("change", (ev) => {
+ const how = ev.target.value;
+ ev.target.value = "";
+ if (!how) return;
+ const deg = degreeMap();
+ const all = [...S.entities.values()].filter((e) => !e.root);
+ const notConfirmed = (e) => e.attrs?._verdict !== "confirmada";
+ const pick = {
+ low: (e) => e.attrs?.["Nivel de confianza"] === "Baja" && notConfirmed(e),
+ discarded: (e) => e.attrs?._verdict === "descartada",
+ orphans: (e) => !deg[e.id] && notConfirmed(e),
+ unreviewed: (e) => e.type === "account" && !e.attrs?._verdict,
+ }[how];
+ deleteMany(all.filter(pick).map((e) => e.id));
+});
+
+// ---------------------------------------------------------------- diálogo de pivotado
+let pivotTarget = null;
+function openPivot(eid) {
+ const ent = S.entities.get(eid);
+ if (!ent || !typeInfo(ent.type).input) return toast("Este tipo de nodo no se investiga directamente");
+ pivotTarget = eid;
+ const mods = Object.values(S.modules).filter((m) => m.inputs.includes(ent.type));
+ $("#pivotTitle").textContent = `Investigar ${typeInfo(ent.type).label.toLowerCase()}: ${short(ent.label, 50)}`;
+ const row = (m) => {
+ const missing = m.keys.filter(() => !m.ready);
+ return `<label><input type="checkbox" value="${esc(m.name)}" ${!m.ready ? "disabled" : m.deep ? "" : "checked"}>
+ <span><b>${esc(m.title)}</b>${missing.length ? ` <span class="st-skipped small">(falta clave en Ajustes)</span>` : ""}</span>
+ <small>${esc(m.description)}</small></label>`;
+ };
+ const deep = mods.filter((m) => m.deep);
+ $("#pivotModules").innerHTML = mods.filter((m) => !m.deep).map(row).join("") + (deep.length
+ ? `<div class="pivot-deep muted small">A fondo (márcalas sólo si lo normal encontró poco: pueden sumar muchos resultados)</div>${deep.map(row).join("")}` : "");
+ $("#pivotDlg").showModal();
+}
+$("#pivotRunBtn").addEventListener("click", async (ev) => {
+ ev.preventDefault();
+ const modules = [...$("#pivotModules").querySelectorAll("input:checked")].map((i) => i.value);
+ $("#pivotDlg").close();
+ if (!modules.length || !pivotTarget) return;
+ try { await startScan(pivotTarget, modules, Number($("#pivotDepth").value)); } catch (e) { toast(e.message, true); }
+});
+
+// ---------------------------------------------------------------- pestañas, lista y notas
+document.querySelectorAll(".tab").forEach((b) => b.addEventListener("click", () => {
+ S.tab = b.dataset.tab;
+ document.querySelectorAll(".tab").forEach((x) => x.classList.toggle("active", x === b));
+ for (const v of ["graph", "list", "map", "timeline", "notes"]) $(`#${v}View`).classList.toggle("hidden", S.tab !== v);
+ if (S.tab === "graph") cy.resize();
+ refreshView();
+}));
+
+// ---------------------------------------------------------------- mapa
+let map = null, mapLayer = null, mapFitted = false;
+const visibleEnt = (e) => !(S.hideLow && (e.attrs?.["Nivel de confianza"] === "Baja" || e.attrs?._verdict === "descartada"));
+
+function neighbours(id) {
+ const out = [];
+ for (const e of S.edges) {
+ const o = e.src === id ? e.dst : e.dst === id ? e.src : null;
+ if (o && S.entities.has(o) && !out.some((x) => x[0].id === o)) out.push([S.entities.get(o), e.label]);
+ }
+ return out;
+}
+
+function renderMap() {
+ if (typeof L === "undefined") return;
+ if (!map) {
+ map = L.map("map", { worldCopyJump: true, zoomControl: true }).setView([20, 0], 2);
+ L.tileLayer("https://tile.openstreetmap.org/{z}/{x}/{y}.png", {
+ maxZoom: 19, className: "dark-tiles",
+ attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>',
+ }).addTo(map);
+ mapLayer = L.featureGroup().addTo(map);
+ map.on("popupopen", (e) => e.popup.getElement().addEventListener("click", (ev) => {
+ const id = ev.target.closest("[data-goto]")?.dataset.goto;
+ if (id) select(id);
+ }));
+ }
+ map.invalidateSize();
+ mapLayer.clearLayers();
+ let n = 0;
+ for (const ent of S.entities.values()) {
+ const lat = Number(ent.attrs?._lat), lon = Number(ent.attrs?._lon);
+ if (!Number.isFinite(lat) || !Number.isFinite(lon) || ent.attrs._lat == null || !visibleEnt(ent)) continue;
+ const near = neighbours(ent.id).filter(([o]) => visibleEnt(o));
+ const color = typeInfo(ent.type).color;
+ const pop = `<div class="map-pop"><b data-goto="${esc(ent.id)}">${esc(ent.label)}</b>
+ <div class="muted small">${esc(typeInfo(ent.type).label)} · ${lat.toFixed(4)}, ${lon.toFixed(4)}</div>
+ ${near.length ? `<ul>${near.slice(0, 40).map(([o, rel]) => `<li data-goto="${esc(o.id)}">${esc(short(o.label, 40))} <span class="muted small">${esc(rel)}</span></li>`).join("")}</ul>` : ""}</div>`;
+ L.circleMarker([lat, lon], { radius: 7 + Math.min(near.length, 8), color: "#ff7a1a", fillColor: color, fillOpacity: 0.7, weight: 2 })
+ .bindPopup(pop).bindTooltip(ent.label).on("click", () => select(ent.id)).addTo(mapLayer);
+ n++;
+ }
+ $("#mapEmpty").classList.toggle("hidden", n > 0);
+ if (n && !mapFitted) { map.fitBounds(mapLayer.getBounds().pad(0.3), { maxZoom: 6 }); mapFitted = true; }
+}
+
+// ---------------------------------------------------------------- cronología
+const DATE_KEY = /^(Creada|Alta|Caduca|Última modificación|Wayback: (primera|última) captura|Servidor creado|Última publicación|Primera actividad|Última actividad.*|Última emisión|Última conexión|Miembro desde|Fecha.*|Primera vez visto|Último push|Primera mención.*|Fecha de nacimiento|Fecha de fallecimiento|Primera foto reciente|Última foto)$/i;
+
+function parseDate(v) {
+ if (typeof v === "number") { const d = new Date(v > 1e11 ? v : v * 1000); return { d, txt: d.toISOString().slice(0, 10) }; }
+ if (typeof v !== "string") return null;
+ const s = v.trim();
+ let m;
+ if ((m = s.match(/^(\d{4})$/))) return { d: new Date(Date.UTC(+m[1], 0, 1)), txt: m[1] };
+ if ((m = s.match(/^(\d{4})[-:](\d{2})(?:[-:](\d{2}))?/))) return { d: new Date(Date.UTC(+m[1], +m[2] - 1, +(m[3] || 1))), txt: m[3] ? `${m[1]}-${m[2]}-${m[3]}` : `${m[1]}-${m[2]}` };
+ if ((m = s.match(/^(\d{4})(\d{2})(\d{2})\d{0,6}$/))) return { d: new Date(Date.UTC(+m[1], +m[2] - 1, +m[3])), txt: `${m[1]}-${m[2]}-${m[3]}` };
+ if ((m = s.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})/))) return { d: new Date(Date.UTC(+m[3], +m[2] - 1, +m[1])), txt: `${m[3]}-${m[2].padStart(2, "0")}-${m[1].padStart(2, "0")}` };
+ const t = Date.parse(s);
+ if (Number.isNaN(t)) return null;
+ const d = new Date(t);
+ return { d, txt: d.toISOString().slice(0, 10) };
+}
+
+function timelineEvents() {
+ const evs = [];
+ const now = Date.now();
+ for (const ent of S.entities.values()) {
+ if (!visibleEnt(ent)) continue;
+ for (const [k, v] of Object.entries(ent.attrs || {})) {
+ if (!DATE_KEY.test(k)) continue;
+ const p = parseDate(v);
+ if (!p || Number.isNaN(p.d.getTime())) continue;
+ const y = p.d.getUTCFullYear();
+ if (y < 1985 || p.d.getTime() > now + 20 * 365 * 864e5) continue;
+ evs.push({ ...p, key: k, ent });
+ }
+ }
+ return evs.sort((a, b) => a.d - b.d);
+}
+
+function renderTimeline() {
+ const evs = timelineEvents();
+ if (!evs.length) {
+ $("#timeline").innerHTML = `<div class="muted" style="text-align:center;margin-top:40px">Aún no hay fechas en este caso (creación de cuentas, dominios, filtraciones, actividad…).</div>`;
+ return;
+ }
+ let year = null;
+ const now = Date.now();
+ $("#timeline").innerHTML = evs.map((e) => {
+ const y = e.d.getUTCFullYear();
+ const head = y !== year ? `<div class="tl-year">${y}</div>` : "";
+ year = y;
+ const future = e.d.getTime() > now ? ` <span class="muted">(futuro)</span>` : "";
+ return `${head}<div class="tl-item" data-goto="${esc(e.ent.id)}">
+ <div class="tl-date">${esc(e.txt)}</div><span class="dot" style="background:${typeInfo(e.ent.type).color}"></span>
+ <div class="tl-what">${esc(e.key)}${future}: <b>${esc(e.ent.label)}</b> <span class="muted">${esc(typeInfo(e.ent.type).label)}</span></div></div>`;
+ }).join("");
+}
+$("#timeline").addEventListener("click", (ev) => {
+ const id = ev.target.closest("[data-goto]")?.dataset.goto;
+ if (id) select(id);
+});
+
+function renderList() {
+ const q = $("#listFilter").value.trim().toLowerCase();
+ const degree = {};
+ for (const e of S.edges) { degree[e.src] = (degree[e.src] || 0) + 1; degree[e.dst] = (degree[e.dst] || 0) + 1; }
+ const rows = [...S.entities.values()]
+ .filter((e) => !q || e.label.toLowerCase().includes(q) || e.value.toLowerCase().includes(q) || typeInfo(e.type).label.toLowerCase().includes(q))
+ .sort((a, b) => a.type.localeCompare(b.type) || a.label.localeCompare(b.label));
+ S.listRows = rows.map((e) => e.id);
+ const allOn = rows.length && rows.every((e) => S.listSel.has(e.id));
+ $("#entityTable").innerHTML = `<thead><tr><th><input type="checkbox" data-selall title="Marcar todas las filas visibles"${allOn ? " checked" : ""}></th><th>Tipo</th><th>Entidad</th><th>Conexiones</th><th>Fuentes</th></tr></thead><tbody>` +
+ rows.map((e) => `<tr data-id="${esc(e.id)}"${e.attrs._verdict === "descartada" ? ' style="opacity:.45"' : ""}><td><input type="checkbox" data-sel="${esc(e.id)}"${S.listSel.has(e.id) ? " checked" : ""}></td><td>${badge(e.type)}</td><td>${e.attrs._verdict === "confirmada" ? '<span class="conf Alta">✔ Confirmada</span> ' : e.attrs._verdict === "descartada" ? '<span class="conf">Descartada</span> ' : ""}${esc(e.label)}${e.label !== e.value ? `<div class="muted small">${esc(short(e.value, 80))}</div>` : ""}</td>
+ <td>${degree[e.id] || 0}</td><td class="muted small">${esc((e.attrs._fuentes || []).join(", "))}</td></tr>`).join("") + "</tbody>";
+ updateListDelete();
+}
+const renderListSoon = debounce(renderList, 300);
+$("#listFilter").addEventListener("input", renderListSoon);
+function updateListDelete() {
+ for (const id of [...S.listSel]) if (!S.entities.has(id)) S.listSel.delete(id);
+ const n = S.listSel.size;
+ $("#listDelete").disabled = !n;
+ $("#listDelete").textContent = n ? `Eliminar marcadas (${n})` : "Eliminar marcadas";
+}
+$("#listDelete").addEventListener("click", () => deleteMany([...S.listSel]));
+$("#entityTable").addEventListener("change", (ev) => {
+ if (ev.target.matches("[data-selall]")) {
+ for (const id of S.listRows || []) ev.target.checked ? S.listSel.add(id) : S.listSel.delete(id);
+ document.querySelectorAll("#entityTable [data-sel]").forEach((c) => { c.checked = ev.target.checked; });
+ } else if (ev.target.matches("[data-sel]")) {
+ ev.target.checked ? S.listSel.add(ev.target.dataset.sel) : S.listSel.delete(ev.target.dataset.sel);
+ }
+ updateListDelete();
+});
+$("#entityTable").addEventListener("click", (ev) => {
+ if (ev.target.matches("input[type=checkbox]")) return;
+ const tr = ev.target.closest("tr[data-id]");
+ if (tr) select(tr.dataset.id);
+});
+
+const saveNotes = debounce(() => {
+ if (S.caseId) api(`/api/cases/${S.caseId}`, { method: "PATCH", body: { notes: $("#notesArea").value } }).catch(() => {});
+}, 600);
+$("#notesArea").addEventListener("input", saveNotes);
+
+// ---------------------------------------------------------------- herramientas del grafo
+$("#fitBtn").addEventListener("click", () => cy.fit(undefined, 40));
+$("#layoutBtn").addEventListener("click", () => runLayout(true, true));
+$("#pngBtn").addEventListener("click", () => {
+ if (!cy.nodes().length) return;
+ const a = document.createElement("a");
+ a.href = cy.png({ full: true, scale: 2, bg: "#0a0806" });
+ a.download = "osint-grafo.png";
+ a.click();
+});
+$("#exportBtn").addEventListener("click", () => { if (S.caseId) window.location = `/api/cases/${S.caseId}/export`; });
+$("#langBtn").textContent = I18N.lang === "en" ? "🌐 Español" : "🌐 English";
+$("#langBtn").addEventListener("click", () => I18N.setLang(I18N.lang === "en" ? "es" : "en"));
+
+// ---------------------------------------------------------------- informe
+const REPORT_SECTIONS = [
+ ["person", "Personas"], ["email", "Emails"], ["phone", "Teléfonos"], ["rut", "RUT"], ["plate", "Patentes"],
+ ["username", "Usuarios"], ["organization", "Organizaciones y empresas"], ["location", "Ubicaciones"],
+ ["domain", "Dominios"], ["ip", "Direcciones IP"], ["url", "Webs y documentos"], ["crypto", "Criptomonedas"],
+ ["hash", "Hashes"], ["breach", "Filtraciones"], ["image", "Imágenes"], ["asn", "Redes (ASN)"],
+];
+
+function reportValue(v) {
+ if (Array.isArray(v)) return v.map((x) => (Array.isArray(x) ? x.join(" · ") : typeof x === "object" ? JSON.stringify(x) : String(x))).join("; ");
+ return typeof v === "object" && v !== null ? JSON.stringify(v) : String(v);
+}
+
+function reportAttrs(ent, max = 12) {
+ const rows = Object.entries(ent.attrs || {})
+ .filter(([k, v]) => !k.startsWith("_") && !ANALYSIS_KEYS.has(k) && v !== null && v !== "" && !(Array.isArray(v) && !v.length))
+ .slice(0, max);
+ return rows.length ? `<table class="kv">${rows.map(([k, v]) => `<tr><td>${esc(k)}</td><td>${esc(short(reportValue(v), 400))}</td></tr>`).join("")}</table>` : "";
+}
+
+function reportOrigin(ent) {
+ const e = S.edges.find((x) => x.dst === ent.id && S.entities.has(x.src));
+ return e ? `${e.label} ← ${S.entities.get(e.src).label}` : ent.root ? "investigado" : "";
+}
+
+function buildReport() {
+ const ents = [...S.entities.values()].filter((e) => e.attrs?._verdict !== "descartada" && visibleEnt(e));
+ const discarded = [...S.entities.values()].filter((e) => e.attrs?._verdict === "descartada");
+ const kase = S.cases.find((c) => c.id === S.caseId);
+ const roots = ents.filter((e) => e.root);
+ const accounts = ents.filter((e) => e.type === "account")
+ .sort((a, b) => (b.attrs?._verdict === "confirmada") - (a.attrs?._verdict === "confirmada") || (b.attrs?.Confianza ?? -1) - (a.attrs?.Confianza ?? -1));
+ const confirmed = accounts.filter((a) => a.attrs?._verdict === "confirmada");
+ const byType = (t) => ents.filter((e) => e.type === t);
+ const counts = REPORT_SECTIONS.map(([t, label]) => [label, byType(t).length]).filter(([, n]) => n);
+ const ai = roots.map((r) => r.attrs?.["IA: resumen"]).filter(Boolean);
+ const sources = [...new Set(ents.flatMap((e) => e.attrs?._fuentes || []))].sort();
+ const notes = $("#notesArea").value.trim();
+ const img = cy.nodes().length ? cy.png({ full: true, scale: 1.6, bg: "#0a0806", maxWidth: 2200, maxHeight: 2200 }) : "";
+ const now = new Date();
+
+ const highConf = accounts.filter((a) => a.attrs?.["Nivel de confianza"] === "Alta" && a.attrs?._verdict !== "confirmada").length;
+ const keyFacts = [
+ confirmed.length && `${confirmed.length} cuenta(s) confirmada(s) por el analista`,
+ highConf && `${highConf} cuenta(s)${confirmed.length ? " más" : ""} con confianza alta`,
+ byType("email").length && `${byType("email").length} email(s)`,
+ byType("phone").length && `${byType("phone").length} teléfono(s)`,
+ byType("rut").length && `${byType("rut").length} RUT`,
+ byType("location").length && `${byType("location").length} ubicación(es)`,
+ byType("organization").length && `${byType("organization").length} organización(es) o empresa(s) relacionadas`,
+ byType("breach").length && `aparece en ${byType("breach").length} filtración(es) de datos`,
+ ].filter(Boolean);
+
+ const accRows = accounts.map((a) => {
+ const at = a.attrs || {};
+ const verdict = at._verdict === "confirmada" ? `<span class="ok">✔ Confirmada</span>` : at["Nivel de confianza"] ? `${esc(at["Nivel de confianza"])} (${esc(at.Confianza ?? "?")})` : "—";
+ const url = safeUrl(a.value);
+ return `<tr><td>${esc(at.Plataforma || "")}</td><td>${esc(at.Usuario || "")}</td>
+ <td>${url ? `<a href="${esc(url)}">${esc(short(url, 60))}</a>` : esc(short(a.label, 60))}</td><td>${verdict}</td>
+ <td class="small">${esc((at["Señales"] || []).slice(0, 2).join(" · "))}</td></tr>`;
+ }).join("");
+
+ const sections = REPORT_SECTIONS.filter(([t]) => t !== "account").map(([t, label]) => {
+ const list = byType(t).filter((e) => !e.root || t === "person");
+ if (!list.length) return "";
+ return `<section><h2>${esc(label)} <span class="muted">(${list.length})</span></h2>
+ ${list.slice(0, 80).map((e) => `<div class="item"><div class="item-h"><b>${esc(e.label)}</b>
+ <span class="muted small">${esc(reportOrigin(e))}</span></div>${reportAttrs(e, t === "person" ? 30 : 10)}</div>`).join("")}
+ ${list.length > 80 ? `<p class="muted">… y ${list.length - 80} más.</p>` : ""}</section>`;
+ }).join("");
+
+ const tl = timelineEvents().filter((e) => e.ent.attrs?._verdict !== "descartada");
+ const tlRows = tl.slice(0, 200).map((e) => `<tr><td>${esc(e.txt)}</td><td>${esc(e.key)}</td><td>${esc(e.ent.label)}</td><td class="muted">${esc(typeInfo(e.ent.type).label)}</td></tr>`).join("");
+
+ return `<!doctype html><html lang="es"><head><meta charset="utf-8"><title>Informe · ${esc(kase?.name || "Caso")}</title>
+<style>
+ :root { --acc: #e8650a; }
+ * { box-sizing: border-box; }
+ body { font: 13px/1.45 "Segoe UI", system-ui, sans-serif; color: #1d1712; margin: 0; background: #fff; }
+ .page { max-width: 980px; margin: 0 auto; padding: 32px 40px; }
+ header { border-bottom: 3px solid var(--acc); padding-bottom: 12px; margin-bottom: 18px; display: flex; justify-content: space-between; align-items: flex-end; }
+ header h1 { margin: 0; font-size: 24px; } header .brand { color: var(--acc); font-weight: 800; letter-spacing: 2px; font-size: 12px; }
+ h2 { font-size: 16px; color: var(--acc); border-bottom: 1px solid #eadfd5; padding-bottom: 4px; margin: 26px 0 10px; break-after: avoid; }
+ .muted { color: #8a7f75; } .small { font-size: 11px; } .ok { color: #1f9d55; font-weight: 600; }
+ .facts { display: flex; flex-wrap: wrap; gap: 6px; margin: 8px 0; padding: 0; list-style: none; }
+ .facts li { background: #fff3e8; border: 1px solid #f5cfa9; border-radius: 12px; padding: 3px 10px; }
+ table { border-collapse: collapse; width: 100%; } td, th { text-align: left; vertical-align: top; padding: 4px 6px; border-bottom: 1px solid #f0e8e0; }
+ th { font-size: 11px; text-transform: uppercase; color: #8a7f75; } a { color: #b44d00; word-break: break-all; }
+ table.kv td:first-child { width: 32%; color: #6b6058; } table.kv { margin: 4px 0 0; font-size: 12px; }
+ .item { padding: 8px 10px; border: 1px solid #eadfd5; border-radius: 6px; margin-bottom: 8px; break-inside: avoid; }
+ .item-h { display: flex; justify-content: space-between; gap: 10px; }
+ .graph { width: 100%; border-radius: 6px; margin-top: 6px; }
+ .ai { background: #f7f3ef; border-left: 3px solid var(--acc); padding: 8px 12px; white-space: pre-wrap; }
+ .notes { white-space: pre-wrap; background: #fafafa; border: 1px solid #eee; padding: 10px; border-radius: 6px; }
+ .toolbar { position: sticky; top: 0; background: #1d1712; padding: 8px 40px; display: flex; gap: 8px; justify-content: flex-end; }
+ .toolbar button { background: var(--acc); color: #fff; border: 0; padding: 7px 14px; border-radius: 6px; font-weight: 600; cursor: pointer; }
+ .toolbar span { color: #c9b8a8; margin-right: auto; align-self: center; font-size: 12px; }
+ @media print { .toolbar { display: none; } .page { padding: 0; } h2 { margin-top: 18px; } @page { margin: 16mm; } }
+</style></head><body>
+<div class="toolbar"><span>Revisa el informe y guárdalo como PDF desde el diálogo de impresión.</span><button onclick="window.print()">Guardar como PDF / Imprimir</button></div>
+<div class="page">
+<header><div><div class="brand">OSINT HUNTER · INFORME</div><h1>${esc(kase?.name || "Caso")}</h1>
+ <div class="muted">Investigado: ${roots.map((r) => `<b>${esc(r.label)}</b> (${esc(typeInfo(r.type).label)})`).join(", ") || "—"}</div></div>
+ <div class="muted small" style="text-align:right">${esc(now.toLocaleDateString(I18N.locale, { dateStyle: "long" }))}<br>${esc(now.toLocaleTimeString(I18N.locale, { timeStyle: "short" }))}<br>${ents.length} entidades</div></header>
+
+<h2>Resumen</h2>
+${keyFacts.length ? `<ul class="facts">${keyFacts.map((f) => `<li>${esc(f)}</li>`).join("")}</ul>` : `<p class="muted">Sin hallazgos todavía.</p>`}
+<p class="muted small">${counts.map(([l, n]) => `${esc(l)}: ${n}`).join(" · ")}</p>
+${ai.length ? `<h2>Resumen de la IA</h2>${ai.map((x) => `<div class="ai">${esc(x)}</div>`).join("")}` : ""}
+${notes ? `<h2>Notas del analista</h2><div class="notes">${esc(notes)}</div>` : ""}
+
+${accounts.length ? `<h2>Cuentas <span class="muted">(${accounts.length})</span></h2>
+<table><thead><tr><th>Plataforma</th><th>Usuario</th><th>Enlace</th><th>¿Es la persona?</th><th>Señales</th></tr></thead><tbody>${accRows}</tbody></table>` : ""}
+
+${sections}
+
+${tlRows ? `<h2>Cronología</h2><table><thead><tr><th>Fecha</th><th>Qué</th><th>Entidad</th><th>Tipo</th></tr></thead><tbody>${tlRows}</tbody></table>` : ""}
+
+${img ? `<h2 style="break-before: page">Grafo del caso</h2><img class="graph" src="${img}" alt="Grafo">` : ""}
+
+${discarded.length ? `<h2>Descartadas por el analista <span class="muted">(${discarded.length})</span></h2><p class="small muted">${discarded.map((d) => esc(d.label)).join(" · ")}</p>` : ""}
+<h2>Fuentes consultadas</h2><p class="small muted">${sources.map(esc).join(" · ") || "—"}</p>
+<p class="small muted">Informe generado con OsintHunter a partir de fuentes abiertas. La confianza de cada cuenta es una estimación automática; las marcadas «Confirmada» fueron verificadas por el analista.</p>
+</div></body></html>`;
+}
+
+$("#reportBtn").addEventListener("click", () => {
+ if (!S.caseId || !S.entities.size) return toast("Primero investiga algo");
+ const html = I18N.translateHtml(buildReport());
+ const w = window.open("", "_blank");
+ if (w) {
+ w.document.open();
+ w.document.write(html);
+ w.document.close();
+ return;
+ }
+ const name = (S.cases.find((c) => c.id === S.caseId)?.name || "caso").replace(/[^\p{L}\p{N}]+/gu, "_").slice(0, 40);
+ const a = document.createElement("a");
+ a.href = URL.createObjectURL(new Blob([html], { type: "text/html" }));
+ a.download = `informe_${name}.html`;
+ a.click();
+ setTimeout(() => URL.revokeObjectURL(a.href), 5000);
+ toast("Informe descargado: ábrelo y pulsa «Guardar como PDF / Imprimir»");
+});
+$("#importBtn").addEventListener("click", () => $("#importFile").click());
+$("#importFile").addEventListener("change", async (ev) => {
+ const file = ev.target.files[0];
+ ev.target.value = "";
+ if (!file) return;
+ const fd = new FormData();
+ fd.append("file", file);
+ try {
+ const c = await api("/api/import", { method: "POST", body: fd });
+ await loadCases(c.id);
+ await openCase(c.id);
+ toast("Caso importado");
+ } catch (e) { toast(e.message, true); }
+});
+
+// ---------------------------------------------------------------- ajustes
+async function openSettings() {
+ const s = await api("/api/settings");
+ const f = $("#settingsForm");
+ f.default_region.value = s.default_region || "";
+ f.username_timeout.value = s.username_timeout;
+ f.max_pivot_entities.value = s.max_pivot_entities;
+ f.sherlock_db.checked = !!s.sherlock_db;
+ f.include_nsfw.checked = !!s.include_nsfw;
+ f.ai_base_url.value = s.ai_base_url || "";
+ f.ai_model.value = s.ai_model || "";
+ syncAiPreset();
+ $("#keysList").innerHTML = Object.entries(s.api_keys).map(([k, v]) => `
+ <div class="key-row">
+ <div class="lbl">${esc(v.label)} <small>${link(v.url, "Conseguir clave")}</small></div>
+ <input type="password" data-key="${esc(k)}" placeholder="${v.set ? "Configurada " + esc(v.masked) : "Sin configurar"}" autocomplete="off">
+ ${v.set ? `<button type="button" class="ghost small danger" data-clear="${esc(k)}">Borrar</button>` : "<span></span>"}
+ </div>`).join("");
+ $("#settingsDlg").showModal();
+}
+$("#settingsBtn").addEventListener("click", openSettings);
+function syncAiPreset() {
+ const f = $("#settingsForm");
+ const cur = `${f.ai_base_url.value.trim()}|${f.ai_model.value.trim()}`;
+ $("#aiPreset").value = [...$("#aiPreset").options].some((o) => o.value === cur) ? cur : "";
+}
+$("#aiPreset").addEventListener("change", (ev) => {
+ if (!ev.target.value) return;
+ const [base, model] = ev.target.value.split("|");
+ const f = $("#settingsForm");
+ f.ai_base_url.value = base;
+ f.ai_model.value = model;
+});
+$("#settingsForm").ai_base_url.addEventListener("input", syncAiPreset);
+$("#settingsForm").ai_model.addEventListener("input", syncAiPreset);
+$("#keysList").addEventListener("click", (ev) => {
+ const k = ev.target.closest("[data-clear]")?.dataset.clear;
+ if (!k) return;
+ const input = $(`#keysList input[data-key="${k}"]`);
+ input.dataset.clearIt = "1";
+ input.placeholder = "Se borrará al guardar";
+ ev.target.remove();
+});
+$("#saveSettingsBtn").addEventListener("click", async (ev) => {
+ ev.preventDefault();
+ const f = $("#settingsForm");
+ const api_keys = {};
+ f.querySelectorAll("input[data-key]").forEach((i) => {
+ if (i.value.trim()) api_keys[i.dataset.key] = i.value.trim();
+ else if (i.dataset.clearIt) api_keys[i.dataset.key] = "";
+ });
+ try {
+ await api("/api/settings", { method: "PUT", body: {
+ default_region: f.default_region.value.trim().toUpperCase(),
+ username_timeout: Number(f.username_timeout.value) || 15,
+ max_pivot_entities: Number(f.max_pivot_entities.value) || 25,
+ sherlock_db: f.sherlock_db.checked,
+ include_nsfw: f.include_nsfw.checked,
+ ai_base_url: f.ai_base_url.value.trim(),
+ ai_model: f.ai_model.value.trim(),
+ api_keys,
+ } });
+ await loadMeta();
+ $("#settingsDlg").close();
+ toast("Ajustes guardados");
+ } catch (e) { toast(e.message, true); }
+});
+
+// ---------------------------------------------------------------- arranque
+async function loadMeta() {
+ S.meta = await api("/api/meta");
+ S.types = S.meta.entity_types;
+ S.modules = Object.fromEntries(S.meta.modules.map((m) => [m.name, m]));
+}
+
+(async function init() {
+ initGraph();
+ await loadMeta();
+ fillTypeSelect(null);
+ await loadCases();
+ const last = Number(localStorage.getItem("osint-case"));
+ const target = S.cases.find((c) => c.id === last) ? last : S.cases[0]?.id;
+ await openCase(target ?? null);
+ $("#searchInput").focus();
+})().catch((e) => toast("No se pudo iniciar: " + e.message, true));
diff --git a/web/favicon.svg b/web/favicon.svg
new file mode 100644
index 0000000..c6c5351
--- /dev/null
+++ b/web/favicon.svg
@@ -0,0 +1,7 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
+ <rect x="2" y="2" width="60" height="60" rx="14" fill="#0d0a07" stroke="#3a2a1a" stroke-width="2"/>
+ <circle cx="32" cy="32" r="19" fill="none" stroke="#ff7a1a" stroke-width="4"/>
+ <circle cx="32" cy="32" r="9" fill="none" stroke="#ff7a1a" stroke-width="3" opacity=".7"/>
+ <circle cx="32" cy="32" r="3.5" fill="#ffb066"/>
+ <path d="M32 6v12M32 46v12M6 32h12M46 32h12" stroke="#ff7a1a" stroke-width="4" stroke-linecap="round"/>
+</svg>
diff --git a/web/i18n-en.js b/web/i18n-en.js
new file mode 100644
index 0000000..d973c6f
--- /dev/null
+++ b/web/i18n-en.js
@@ -0,0 +1,1115 @@
+"use strict";
+
+// Diccionario español -> inglés. «{}» marca una parte variable (número, nombre…), que se traduce aparte si se puede.
+// «text» vale para cualquier texto; «keys» son nombres de campos (columna izquierda de las tablas de datos).
+const I18N_EN = {
+ text: {
+ // ------------------------------------------------------------ barra superior y búsqueda
+ "+ Nuevo caso": "+ New case",
+ "Importar caso": "Import case",
+ "Ajustes y claves API": "Settings & API keys",
+ "Caso abierto": "Open case",
+ "Renombrar caso": "Rename case",
+ "Eliminar caso": "Delete case",
+ "Nueva búsqueda": "New search",
+ "usuario, email, teléfono, nombre, RUT, patente, dominio, IP, URL…": "username, email, phone, name, RUT, plate, domain, IP, URL…",
+ "Tipo de dato": "Data type",
+ "Tipo: automático": "Type: automatic",
+ "Auto: {}": "Auto: {}",
+ "Sólo el objetivo": "Target only",
+ "+1 salto automático": "+1 automatic hop",
+ "+2 saltos automáticos": "+2 automatic hops",
+ "Investigar": "Investigate",
+ "Investigar…": "Investigate…",
+ "Analizar imagen (EXIF / GPS)": "Analyze image (EXIF / GPS)",
+ "Fuentes consultadas": "Sources checked",
+ "Aún no hay consultas.": "No lookups yet.",
+ "— Sin casos —": "— No cases —",
+ "Nombre del nuevo caso:": "Name of the new case:",
+ "Investigación {}": "Investigation {}",
+ "Nuevo nombre:": "New name:",
+ "¿Eliminar el caso «{}» y todos sus datos?": "Delete the case “{}” and all its data?",
+ "Caso importado": "Case imported",
+ "Imagen {}": "Image {}",
+ "Imagen analizada": "Image analyzed",
+
+ // ------------------------------------------------------------ pestañas y herramientas
+ "Grafo": "Graph",
+ "Lista": "List",
+ "Mapa": "Map",
+ "Cronología": "Timeline",
+ "Notas": "Notes",
+ "Ocultar confianza baja": "Hide low confidence",
+ "Oculta las cuentas cuya confianza es baja (posibles homónimos)": "Hides accounts with low confidence (possible namesakes)",
+ "Verificar con IA": "Verify with AI",
+ "Compara las cuentas con IA para descartar homónimos": "Compares the accounts with AI to rule out namesakes",
+ "Limpiar…": "Clean up…",
+ "Borrar varios nodos de una vez": "Delete several nodes at once",
+ "Eliminar confianza baja": "Delete low confidence",
+ "Eliminar descartadas": "Delete discarded",
+ "Eliminar nodos sueltos (sin conexiones)": "Delete loose nodes (no connections)",
+ "Eliminar cuentas sin revisar (deja confirmadas)": "Delete unreviewed accounts (keeps confirmed)",
+ "Agrupar…": "Group…",
+ "Ordenar un grafo grande: burbujas y nodos plegados": "Tidy a large graph: bubbles and folded nodes",
+ "Una burbuja por cada búsqueda": "One bubble per search",
+ "Burbujas de cuentas por usuario": "Account bubbles per username",
+ "Plegar nodos con muchos resultados": "Fold nodes with many results",
+ "Plegar todas las burbujas": "Fold all bubbles",
+ "Desplegar todo": "Unfold everything",
+ "Quitar todas las burbujas": "Remove all bubbles",
+ "Encuadrar": "Fit",
+ "Reordenar": "Re-layout",
+ "Informe": "Report",
+ "Informe del caso para imprimir o guardar como PDF": "Case report to print or save as PDF",
+ "Exportar JSON": "Export JSON",
+ "Agrupar en burbuja": "Group into bubble",
+ "Mete los nodos seleccionados en una burbuja con nombre": "Puts the selected nodes in a named bubble",
+ "Eliminar": "Delete",
+ "Quitar selección": "Clear selection",
+ "{} seleccionados": "{} selected",
+ "Ctrl+clic suma nodos · Shift+arrastrar selecciona un área · Supr borra la selección · doble clic en una burbuja la pliega":
+ "Ctrl+click adds nodes · Shift+drag selects an area · Del deletes the selection · double-click a bubble to fold it",
+ "Empieza la cacería": "Start the hunt",
+ "Escribe un usuario, email, teléfono, nombre completo, RUT, patente, dominio, IP, URL, hash o cartera de criptomonedas. El tipo se detecta solo.":
+ "Type a username, email, phone, full name, RUT, license plate, domain, IP, URL, hash or crypto wallet. The type is detected automatically.",
+ "Haz clic en un nodo para ver sus datos, doble clic para investigarlo, y pasa el ratón por encima para ver sus conexiones.":
+ "Click a node to see its data, double-click to investigate it, and hover over it to see its connections.",
+ "Filtrar entidades… (ej. «steam», «cuenta», «sherlock»)": "Filter entities… (e.g. “steam”, “account”, “sherlock”)",
+ "Eliminar marcadas": "Delete checked",
+ "Eliminar marcadas ({})": "Delete checked ({})",
+ "Aún no hay ubicaciones con coordenadas en este caso.": "There are no locations with coordinates in this case yet.",
+ "Notas del caso (se guardan solas)…": "Case notes (saved automatically)…",
+ "Tipo": "Type",
+ "Entidad": "Entity",
+ "Conexiones": "Connections",
+ "Fuentes": "Sources",
+ "Valor": "Value",
+ "Aún no hay fechas en este caso (creación de cuentas, dominios, filtraciones, actividad…).":
+ "There are no dates in this case yet (account creation, domains, breaches, activity…).",
+ "(futuro)": "(future)",
+
+ // ------------------------------------------------------------ ajustes
+ "Ajustes": "Settings",
+ "País por defecto para teléfonos (código ISO, ej. AR, ES, MX)": "Default country for phone numbers (ISO code, e.g. AR, ES, MX)",
+ "Tiempo máximo por web en el barrido de usuario (s)": "Maximum time per site in the username sweep (s)",
+ "Máximo de entidades en el pivotado automático": "Maximum entities in automatic pivoting",
+ "Usar la base ampliada de Sherlock (400+ sitios)": "Use the extended Sherlock database (400+ sites)",
+ "Incluir sitios para adultos en el barrido": "Include adult sites in the sweep",
+ "Inteligencia artificial": "Artificial intelligence",
+ "Opcional, para «Verificar con IA». Funciona con cualquier proveedor compatible con OpenAI. Ollama corre en tu PC sin clave; Groq y Gemini tienen capa gratuita (pon su clave en «Clave del proveedor de IA», abajo).":
+ "Optional, for “Verify with AI”. Works with any OpenAI-compatible provider. Ollama runs on your PC without a key; Groq and Gemini have a free tier (put their key in “AI provider key”, below).",
+ "Proveedor": "Provider",
+ "Personalizado": "Custom",
+ "Ollama (local, gratis)": "Ollama (local, free)",
+ "Groq (gratis con clave)": "Groq (free with key)",
+ "Google Gemini (gratis con clave)": "Google Gemini (free with key)",
+ "URL base": "Base URL",
+ "Modelo": "Model",
+ "Claves API": "API keys",
+ "Todas opcionales. Se guardan sólo en tu PC (carpeta": "All optional. They are stored only on your PC (folder",
+ "). Sin clave, esa fuente se omite y se indica en «Fuentes consultadas».": "). Without a key, that source is skipped and shown in “Sources checked”.",
+ "Cancelar": "Cancel",
+ "Guardar": "Save",
+ "Conseguir clave": "Get key",
+ "Configurada": "Configured",
+ "Sin configurar": "Not configured",
+ "Se borrará al guardar": "Will be deleted on save",
+ "Ajustes guardados": "Settings saved",
+ "Idioma": "Language",
+ "GitHub token (sube el límite de 60 a 5000 peticiones/h)": "GitHub token (raises the limit from 60 to 5000 requests/h)",
+ "Have I Been Pwned (de pago)": "Have I Been Pwned (paid)",
+ "Serper.dev (Google; 2500 búsquedas gratis, mejora la búsqueda de personas)": "Serper.dev (Google; 2500 free searches, improves people search)",
+ "Brave Search API (alternativa a Serper)": "Brave Search API (alternative to Serper)",
+ "Clave del proveedor de IA (no hace falta con Ollama local)": "AI provider key (not needed with local Ollama)",
+
+ // ------------------------------------------------------------ investigar (diálogo)
+ "Pivotado automático": "Automatic pivoting",
+ "Sólo esta entidad": "This entity only",
+ "Investigar {}: {}": "Investigate {}: {}",
+ "(falta clave en Ajustes)": "(key missing in Settings)",
+ "A fondo (márcalas sólo si lo normal encontró poco: pueden sumar muchos resultados)":
+ "Deep (check them only if the normal search found little: they can add many results)",
+ "Este tipo de nodo no se investiga directamente": "This node type can't be investigated directly",
+
+ // ------------------------------------------------------------ progreso y avisos
+ "Análisis del caso terminado": "Case analysis finished",
+ "entidad analizada": "entity analyzed",
+ "entidades analizadas": "entities analyzed",
+ "Investigación terminada ({} {})": "Investigation finished ({} {})",
+ "Primero investiga algo": "Investigate something first",
+ "Configura un proveedor de IA en Ajustes (Ollama local, Groq o Gemini son gratis)": "Set up an AI provider in Settings (local Ollama, Groq or Gemini are free)",
+ "La IA está comparando las cuentas…": "The AI is comparing the accounts…",
+ "● trabajando": "● working",
+ "Consultando…": "Querying…",
+ "Análisis del caso": "Case analysis",
+ "No se pudo iniciar: {}": "Could not start: {}",
+ "No se pudo copiar": "Could not copy",
+ "Copiado": "Copied",
+ "Copiado «{}»": "Copied “{}”",
+ "Copiado «{}»: pégalo en el formulario con Ctrl+V": "Copied “{}”: paste it into the form with Ctrl+V",
+
+ // ------------------------------------------------------------ panel de detalles
+ "Selecciona un nodo para ver sus datos.": "Select a node to see its data.",
+ "{} elementos": "{} items",
+ "Copiar": "Copy",
+ "Centrar": "Center",
+ "Seleccionar sus resultados": "Select its results",
+ "Selecciona todo lo que salió de este nodo y no está conectado con nada más, para borrarlo de una vez":
+ "Selects everything that came from this node and isn't connected to anything else, to delete it at once",
+ "Datos": "Data",
+ "Enlaces": "Links",
+ "Abrir": "Open",
+ "Ver en Google Maps": "View on Google Maps",
+ "Buscar esta foto en otros sitios": "Search this photo on other sites",
+ "Yandex Imágenes (el mejor para caras)": "Yandex Images (best for faces)",
+ "Usuarios probables": "Likely usernames",
+ "Dorks de búsqueda ({})": "Search dorks ({})",
+ "Búsquedas": "Searches",
+ "Conexiones ({})": "Connections ({})",
+ "Quitar este vínculo": "Remove this link",
+ "Datos aportados por: {}": "Data provided by: {}",
+ "¿Es la misma persona?": "Is it the same person?",
+ "Confianza": "Confidence",
+ "Alta": "High",
+ "Media": "Medium",
+ "Baja": "Low",
+ "Resumen de la IA": "AI summary",
+ "Modelo: {}": "Model: {}",
+ "Consultas con captcha": "Lookups with captcha",
+ "Al abrir el sitio se copia el dato: pégalo con Ctrl+V, resuelve el captcha y consulta.":
+ "Opening the site copies the value: paste it with Ctrl+V, solve the captcha and search.",
+ "Vincular con otra entidad": "Link to another entity",
+ "Une a mano dos nodos que sabes que están relacionados (por ejemplo, el nombre con su alias).":
+ "Manually join two nodes you know are related (for example, the name with its alias).",
+ "Con": "With",
+ "Relación": "Relationship",
+ "Vincular": "Link",
+ "Vinculado: {}": "Linked: {}",
+ "Vínculo quitado": "Link removed",
+ "✔ Es la persona": "✔ It's the person",
+ "✕ No es": "✕ It isn't",
+ "Sin revisar": "Unreviewed",
+ "Confirmada: cuenta con 100 de confianza y referencia para juzgar las demás.": "Confirmed: account with 100 confidence, used as reference to judge the others.",
+ "Confirmado por ti.": "Confirmed by you.",
+ "Descartada: queda atenuada y no cuenta en el análisis.": "Discarded: it's dimmed and doesn't count in the analysis.",
+ "¿Es de la persona que investigas? Tu decisión manda sobre la puntuación automática.": "Does it belong to the person you're investigating? Your decision overrides the automatic score.",
+ "Marcada como suya": "Marked as theirs",
+ "Marcada como de otra persona": "Marked as someone else's",
+ "Marca quitada": "Mark removed",
+ "{} cuentas recalculadas": "{} accounts recalculated",
+ "Resultados web ({})": "Web results ({})",
+ "Con el nombre completo": "With the full name",
+ "Coincidencias parciales": "Partial matches",
+ "Aparece sólo una parte del nombre (por ejemplo, sin el segundo nombre). Puede ser la persona o un homónimo: revísalo antes de añadirlo.":
+ "Only part of the name appears (for example, without the middle name). It may be the person or a namesake: check it before adding it.",
+ "Coincide: «{}»": "Matches: “{}”",
+ "En el grafo": "In the graph",
+ "Buscado con {}": "Searched with {}",
+ "Perfil añadido al caso": "Profile added to the case",
+ "¿No encontraste mucho? Buscar a fondo": "Didn't find much? Deep search",
+ "Buscando…": "Searching…",
+ "Variantes que existen ({} de {} probadas)": "Variants that exist ({} of {} tried)",
+ "{} ({} seguidores)": "{} ({} followers)",
+ "privada": "private",
+ "Ya está en el grafo": "Already in the graph",
+ "Añadir al caso": "Add to case",
+ "Ninguna existe en las redes probadas.": "None exist on the networks tried.",
+ "No se pudo comprobar (la red limitó las consultas): {}. Reintenta más tarde.": "Couldn't check (the network rate-limited the lookups): {}. Try again later.",
+ "Una variante puede ser de otra persona: compara el nombre y la foto antes de darla por buena.":
+ "A variant may belong to someone else: compare the name and photo before accepting it.",
+ "«{}» añadido al caso": "“{}” added to the case",
+ "Desplegar resultados ({})": "Unfold results ({})",
+ "Plegar resultados ({})": "Fold results ({})",
+ "Vuelve a mostrar lo que salió de este nodo": "Shows again what came from this node",
+ "Esconde lo que salió de este nodo y lo deja como un solo nodo marcado con ⊕": "Hides what came from this node and leaves it as a single node marked with ⊕",
+ "Sacar de «{}»": "Remove from “{}”",
+ "Sacado de la burbuja": "Removed from the bubble",
+ "No hay resultados que dependan sólo de este nodo": "No results depend only on this node",
+ "{} nodos seleccionados: pulsa «Eliminar» en la barra o la tecla Supr": "{} nodes selected: press “Delete” in the bar or the Del key",
+ "No hay nada que eliminar": "Nothing to delete",
+ "¿Eliminar «{}» del caso?": "Delete “{}” from the case?",
+ "¿Eliminar {} nodos del caso?": "Delete {} nodes from the case?",
+ "Incluye {}.": "Includes {}.",
+ "{} objetivo(s) que buscaste": "{} target(s) you searched",
+ "{} confirmada(s) por ti": "{} confirmed by you",
+ "{} y {}": "{} and {}",
+ "{} nodos eliminados": "{} nodes deleted",
+
+ // ------------------------------------------------------------ burbujas
+ "Burbuja": "Bubble",
+ "{} nodos": "{} nodes",
+ "plegada": "folded",
+ "Desplegar": "Unfold",
+ "Plegar": "Fold",
+ "Renombrar": "Rename",
+ "Seleccionar sus nodos": "Select its nodes",
+ "Quitar burbuja": "Remove bubble",
+ "Contenido": "Contents",
+ "Nodos ({})": "Nodes ({})",
+ "Todo lo que salió de esta búsqueda; se actualiza sola con los nuevos resultados.": "Everything that came from this search; it updates itself with new results.",
+ "Cuentas encontradas sólo para este usuario; se actualiza sola.": "Accounts found only for this username; it updates itself.",
+ "Alias que parecen el mismo apodo escrito de distintas formas, con sus cuentas.": "Aliases that look like the same nickname written in different ways, with their accounts.",
+ "Burbujas por familia de alias": "Bubbles by alias family",
+ "Alias «{}»": "Alias “{}”",
+ "Burbuja «{}» creada": "Bubble “{}” created",
+ "{} familia(s) de alias: {}": "{} alias family(ies): {}",
+ "No hay alias parecidos entre sí en el caso": "There are no similar aliases in the case",
+ "Familia de alias «{}» ({})": "Alias family “{}” ({})",
+ "Parecen el mismo apodo escrito de distintas formas. «Variantes del usuario» prueba las combinaciones que faltan.":
+ "They look like the same nickname written in different ways. “Username variants” tries the missing combinations.",
+ "Agrupar la familia en una burbuja": "Group the family into a bubble",
+ "Revisar a mano ({})": "Check by hand ({})",
+ "Estos sitios bloquean a los programas, pero no a tu navegador. Ábrelos y marca si el perfil existe.":
+ "These sites block programs, but not your browser. Open them and mark whether the profile exists.",
+ "Existe": "Exists",
+ "No existe": "Doesn't exist",
+ "Cuenta de {} añadida al caso": "{} account added to the case",
+ "{} descartado": "{} ruled out",
+ "En los {} usuarios del caso": "On the case's {} usernames",
+ "Lo lanza a la vez en cada usuario del caso": "Runs it on every username in the case at once",
+ "¿Reintentar lo bloqueado en los {} usuarios? Puede tardar unos minutos.": "Retry what was blocked on the {} usernames? It may take a few minutes.",
+ "Reintentando en {} usuarios": "Retrying on {} usernames",
+ "★ {}": "★ {}",
+ "Descartar toda la lista": "Dismiss the whole list",
+ "¿Quitar los {} sitios de la lista?": "Remove the {} sites from the list?",
+ "Lista vaciada": "List cleared",
+ "El nombre coincide con «{}», que ya está en el caso": "The name matches “{}”, which is already in the case",
+ "Otras, con nombres que no aparecen en el caso": "Others, with names that don't appear in the case",
+ "{} con un nombre que ya está en el caso": "{} with a name already in the case",
+ "Creada a mano: añade nodos seleccionándolos y pulsando «Agrupar en burbuja».": "Created by hand: add nodes by selecting them and pressing “Group into bubble”.",
+ "Doble clic en la burbuja la pliega o despliega.": "Double-click the bubble to fold or unfold it.",
+ "Nombre de la burbuja:": "Bubble name:",
+ "Nombre de la burbuja ({} nodos):": "Bubble name ({} nodes):",
+ "Grupo {}": "Group {}",
+ "Cuentas de {}": "Accounts of {}",
+ "Burbuja «{}» creada: doble clic sobre ella para plegarla": "Bubble “{}” created: double-click it to fold it",
+ "Burbuja «{}» plegada": "Bubble “{}” folded",
+ "Burbuja «{}» desplegada": "Bubble “{}” unfolded",
+ "Burbuja «{}» quitada (los nodos siguen en el caso)": "Bubble “{}” removed (the nodes stay in the case)",
+ "{} burbuja(s), una por búsqueda": "{} bubble(s), one per search",
+ "{} nodos compartidos quedan fuera, entre ellas": "{} shared nodes stay outside, between them",
+ "Aún no hay resultados que agrupar": "No results to group yet",
+ "{} burbuja(s) de cuentas": "{} account bubble(s)",
+ "Ningún usuario tiene 3 o más cuentas propias": "No username has 3 or more accounts of its own",
+ "{} nodo(s) plegados (marcados con ⊕): selecciónalos y pulsa «Desplegar resultados»": "{} node(s) folded (marked with ⊕): select them and press “Unfold results”",
+ "No hay nodos con 8 o más resultados propios": "No nodes with 8 or more results of their own",
+ "Burbujas plegadas": "Bubbles folded",
+ "No hay burbujas: crea una primero": "No bubbles: create one first",
+ "Todo desplegado": "Everything unfolded",
+ "Burbujas quitadas": "Bubbles removed",
+ "Resultados desplegados": "Results unfolded",
+ "Resultados plegados: el nodo queda marcado con ⊕": "Results folded: the node is marked with ⊕",
+ "vínculo": "link",
+ "{} vínculos": "{} links",
+
+ // ------------------------------------------------------------ informe
+ "Informe · {}": "Report · {}",
+ "Caso": "Case",
+ "Revisa el informe y guárdalo como PDF desde el diálogo de impresión.": "Review the report and save it as PDF from the print dialog.",
+ "Guardar como PDF / Imprimir": "Save as PDF / Print",
+ "OSINT HUNTER · INFORME": "OSINT HUNTER · REPORT",
+ "Investigado:": "Investigated:",
+ "investigado": "investigated",
+ "{} entidades": "{} entities",
+ "Resumen": "Summary",
+ "Sin hallazgos todavía.": "No findings yet.",
+ "Notas del analista": "Analyst notes",
+ "Cuentas ({})": "Accounts ({})",
+ "Plataforma": "Platform",
+ "Usuario": "Username",
+ "Enlace": "Link",
+ "¿Es la persona?": "Is it the person?",
+ "Señales": "Signals",
+ "✔ Confirmada": "✔ Confirmed",
+ "Fecha": "Date",
+ "Qué": "What",
+ "Grafo del caso": "Case graph",
+ "Descartadas por el analista": "Discarded by the analyst",
+ "y {} más.": "and {} more.",
+ "Informe generado con OsintHunter a partir de fuentes abiertas. La confianza de cada cuenta es una estimación automática; las marcadas «Confirmada» fueron verificadas por el analista.":
+ "Report generated with OsintHunter from open sources. Each account's confidence is an automatic estimate; those marked “Confirmed” were verified by the analyst.",
+ "Informe descargado: ábrelo y pulsa «Guardar como PDF / Imprimir»": "Report downloaded: open it and press “Save as PDF / Print”",
+ "El navegador bloqueó la ventana del informe: permite las ventanas emergentes": "The browser blocked the report window: allow pop-ups",
+ "Personas": "People",
+ "Emails": "Emails",
+ "Teléfonos": "Phones",
+ "Patentes": "License plates",
+ "Usuarios": "Usernames",
+ "Organizaciones y empresas": "Organizations and companies",
+ "Ubicaciones": "Locations",
+ "Dominios": "Domains",
+ "Direcciones IP": "IP addresses",
+ "Webs y documentos": "Websites and documents",
+ "Criptomonedas": "Cryptocurrencies",
+ "Hashes": "Hashes",
+ "Filtraciones": "Breaches",
+ "Imágenes": "Images",
+ "Redes (ASN)": "Networks (ASN)",
+ "{} cuenta(s) confirmada(s) por el analista": "{} account(s) confirmed by the analyst",
+ "{} cuenta(s) más con confianza alta": "{} more account(s) with high confidence",
+ "{} cuenta(s) con confianza alta": "{} account(s) with high confidence",
+ "{} email(s)": "{} email(s)",
+ "{} teléfono(s)": "{} phone(s)",
+ "{} RUT": "{} RUT",
+ "{} ubicación(es)": "{} location(s)",
+ "{} organización(es) o empresa(s) relacionadas": "{} related organization(s) or company(ies)",
+ "aparece en {} filtración(es) de datos": "appears in {} data breach(es)",
+ "Personas: {}": "People: {}",
+
+ // ------------------------------------------------------------ tipos de entidad
+ "Cuenta": "Account",
+ "Email": "Email",
+ "Teléfono": "Phone",
+ "Persona": "Person",
+ "Dominio": "Domain",
+ "Cripto": "Crypto",
+ "Patente": "License plate",
+ "Ubicación": "Location",
+ "Organización": "Organization",
+ "Filtración": "Breach",
+ "Imagen": "Image",
+
+ // ------------------------------------------------------------ relaciones
+ "usa el alias": "uses the alias",
+ "alias de": "alias of",
+ "su cuenta": "their account",
+ "es cuenta de": "is account of",
+ "es la misma persona": "is the same person",
+ "familiar de": "relative of",
+ "pareja de": "partner of",
+ "amigo de": "friend of",
+ "trabaja en": "works at",
+ "estudió en": "studied at",
+ "estudió en ({})": "studied at ({})",
+ "vive en": "lives in",
+ "relacionado con": "related to",
+ "relacionado": "related",
+ "posible variante": "possible variant",
+ "posible perfil (nombre completo)": "possible profile (full name)",
+ "posible perfil (nombre parcial)": "possible profile (partial name)",
+ "misma foto de perfil": "same profile photo",
+ "titular (NIC Chile)": "holder (NIC Chile)",
+ "mismo nombre (InfoProbidad)": "same name (InfoProbidad)",
+ "RUT (InfoProbidad)": "RUT (InfoProbidad)",
+ "cónyuge (InfoProbidad)": "spouse (InfoProbidad)",
+ "propiedad declarada (InfoProbidad)": "declared property (InfoProbidad)",
+ "razón social": "legal name",
+ "empresa con su nombre": "company with their name",
+ "misma clave SSH": "same SSH key",
+ "archivada": "archived",
+ "miembro de": "member of",
+ "autor de documentos": "document author",
+ "usuario en metadatos": "username in metadata",
+ "email en metadatos": "email in metadata",
+ "RUT en documentos": "RUT in documents",
+ "empresa en metadatos": "company in metadata",
+ "email en la web": "email on the website",
+ "RUT en la web": "RUT on the website",
+ "invitación de Discord": "Discord invite",
+ "red social en la web": "social network on the website",
+ "usuario": "username",
+ "resuelve a": "resolves to",
+ "subdominio": "subdomain",
+ "dominio": "domain",
+ "posible usuario": "possible username",
+ "aparece en": "appears in",
+ "registrado en": "registered on",
+ "publicado en": "published on",
+ "servidor": "server",
+ "cuenta": "account",
+ "invitación creada por": "invite created by",
+ "foto tomada en": "photo taken at",
+ "geolocalizada en": "geolocated at",
+ "red": "network",
+ "nombre de host": "hostname",
+ "DNS inverso": "Reverse DNS",
+ "dominio (Shodan)": "domain (Shodan)",
+ "lugar de nacimiento": "place of birth",
+ "afiliación académica": "academic affiliation",
+ "email en ORCID": "email on ORCID",
+ "institución (ORCID)": "institution (ORCID)",
+ "web oficial": "official website",
+ "cuenta oficial": "official account",
+ "ubicación del prefijo": "prefix location",
+ "nombre": "name",
+ "ubicación declarada": "stated location",
+ "enlaza a": "links to",
+ "web": "website",
+ "alojada en": "hosted on",
+ "redirige a": "redirects to",
+ "visto en (URLScan)": "seen on (URLScan)",
+ "ubicación": "location",
+ "registrado en {}": "registered on {}",
+ "usuario en {}": "username on {}",
+
+ // ------------------------------------------------------------ módulos: títulos y descripciones
+ "Comparación de fotos de perfil": "Profile photo comparison",
+ "Verificación con IA": "AI verification",
+ "RUT chileno": "Chilean RUT",
+ "Valida el dígito verificador, indica si es persona natural o jurídica y prepara las consultas en SII, Registro de Empresas, Poder Judicial, Mercado Público y otras fuentes oficiales":
+ "Validates the check digit, tells whether it's an individual or a company, and prepares lookups in SII, Company Registry, Judiciary, Mercado Público and other official sources",
+ "Patente de vehículo (Chile)": "Vehicle license plate (Chile)",
+ "Reconoce el formato de la placa y prepara las consultas oficiales (encargo por robo, multas impagas, certificado de anotaciones) y búsquedas en avisos y redes":
+ "Recognizes the plate format and prepares the official lookups (theft report, unpaid fines, registration certificate) and searches in listings and social networks",
+ "WHOIS .cl (NIC Chile)": "WHOIS .cl (NIC Chile)",
+ "Titular del dominio .cl (persona u organización), agente registrador, fechas y servidores DNS": "Holder of the .cl domain (person or organization), registrar, dates and DNS servers",
+ "InfoProbidad (declaraciones de patrimonio, Chile)": "InfoProbidad (asset declarations, Chile)",
+ "Funcionarios, autoridades y candidatos chilenos: cargo, institución, cónyuge, empresas, propiedades, vehículos y deudas según su declaración de patrimonio e intereses":
+ "Chilean officials, authorities and candidates: position, institution, spouse, companies, properties, vehicles and debts according to their asset and interest declaration",
+ "Empresas chilenas (Registro de Empresas y Sociedades)": "Chilean companies (Company Registry)",
+ "Razón social, tipo, fecha de constitución, comuna, capital e historial de una empresa por su RUT; para personas, sociedades con su nombre completo o sus dos apellidos (empresas creadas desde 2013)":
+ "Legal name, type, incorporation date, district, capital and history of a company by its RUT; for people, companies with their full name or both surnames (companies created since 2013)",
+ "Tesis y publicaciones (LA Referencia)": "Theses and publications (LA Referencia)",
+ "Tesis de pregrado, magíster y doctorado, y artículos de repositorios universitarios de Chile y Latinoamérica firmados con ese nombre: universidad, año, tema y enlace":
+ "Undergraduate, master's and doctoral theses, and articles from university repositories in Chile and Latin America signed with that name: university, year, topic and link",
+ "GitHub a fondo": "GitHub in depth",
+ "Organizaciones, repositorios y lenguajes, cuentas enlazadas, emails de sus claves GPG y claves SSH (si GitLab tiene la misma clave, es la misma persona)":
+ "Organizations, repositories and languages, linked accounts, emails from their GPG keys and SSH keys (if GitLab has the same key, it's the same person)",
+ "Perfiles archivados (Wayback)": "Archived profiles (Wayback)",
+ "Busca copias de sus perfiles en Internet Archive: sirve para ver cuentas borradas o cómo eran antes":
+ "Looks for copies of their profiles on the Internet Archive: useful to see deleted accounts or how they looked before",
+ "Menciones en foros (Hacker News)": "Forum mentions (Hacker News)",
+ "Comentarios y publicaciones de Hacker News que mencionan el dato, con autor, fecha y enlace": "Hacker News comments and posts that mention the value, with author, date and link",
+ "Metadatos de documentos": "Document metadata",
+ "Busca PDF, Word, Excel y PowerPoint publicados por el dominio (vía Internet Archive y Common Crawl), los descarga y extrae autores, usuarios internos, empresa y software usado":
+ "Finds PDF, Word, Excel and PowerPoint files published by the domain (via Internet Archive and Common Crawl), downloads them and extracts authors, internal usernames, company and software used",
+ "Registros DNS": "DNS records",
+ "A, AAAA, MX, NS, TXT, SOA, CAA y DMARC; extrae IPs, servidores y servicios verificados en TXT.": "A, AAAA, MX, NS, TXT, SOA, CAA and DMARC; extracts IPs, servers and services verified in TXT.",
+ "Registrador, fechas de alta y caducidad, estado y contactos no ocultos.": "Registrar, creation and expiry dates, status and non-redacted contacts.",
+ "Subdominios (certificados)": "Subdomains (certificates)",
+ "Subdominios descubiertos en los registros públicos de certificados TLS.": "Subdomains found in public TLS certificate logs.",
+ "Sitio web": "Website",
+ "Título, tecnologías, emails, redes sociales e IDs de analítica de la web del dominio.": "Title, technologies, emails, social networks and analytics IDs of the domain's website.",
+ "Archivo histórico (Wayback)": "Historical archive (Wayback)",
+ "Primera y última captura en archive.org y número de capturas.": "First and last capture on archive.org and number of captures.",
+ "Análisis del email": "Email analysis",
+ "Valida el dominio (MX), detecta proveedores gratuitos y desechables y extrae dominio y posible usuario.": "Validates the domain (MX), detects free and disposable providers and extracts domain and possible username.",
+ "Perfil público asociado al email: nombre, foto, ubicación y cuentas verificadas.": "Public profile linked to the email: name, photo, location and verified accounts.",
+ "Filtraciones (XposedOrNot)": "Breaches (XposedOrNot)",
+ "Comprueba si el email aparece en brechas de datos públicas y qué tipo de datos se filtraron.": "Checks whether the email appears in public data breaches and what kind of data leaked.",
+ "Servicios donde está registrado": "Services where it's registered",
+ "Comprueba en qué servicios hay una cuenta con este email, sin enviar ningún aviso a su dueño.": "Checks which services have an account with this email, without notifying its owner.",
+ "Brechas en las que aparece el email según HIBP (requiere clave de pago).": "Breaches where the email appears according to HIBP (requires a paid key).",
+ "Hunter.io verificador": "Hunter.io verifier",
+ "Comprueba si el buzón existe y cuántas fuentes web publican el email.": "Checks whether the mailbox exists and how many web sources publish the email.",
+ "Invitación de Discord": "Discord invite",
+ "Servidor, número de miembros, fecha de creación y quién creó la invitación.": "Server, member count, creation date and who created the invite.",
+ "Geolocalizar ubicación": "Geocode location",
+ "Convierte el texto de una ubicación en coordenadas para mostrarla en el mapa.": "Turns a location text into coordinates to show it on the map.",
+ "Flickr: fotos con ubicación": "Flickr: photos with location",
+ "Lee las últimas fotos públicas de un usuario de Flickr (por su ID tipo 12345678@N04) y pone en el mapa las que guardan coordenadas GPS":
+ "Reads a Flickr user's latest public photos (by their ID like 12345678@N04) and maps those that keep GPS coordinates",
+ "Geolocalización e ISP": "Geolocation and ISP",
+ "País, ciudad, coordenadas aproximadas, ASN, ISP y si es proxy/VPN/hosting.": "Country, city, approximate coordinates, ASN, ISP and whether it's a proxy/VPN/hosting.",
+ "Puertos y vulnerabilidades (InternetDB)": "Ports and vulnerabilities (InternetDB)",
+ "Puertos abiertos, software, CVEs y nombres de host según el escaneo pasivo gratuito de Shodan.": "Open ports, software, CVEs and hostnames from Shodan's free passive scan.",
+ "Nombre de host asociado a la IP (registro PTR).": "Hostname linked to the IP (PTR record).",
+ "Servicios, banners, organización y sistema operativo vistos por Shodan.": "Services, banners, organization and operating system seen by Shodan.",
+ "Reportes de abuso (spam, ataques, escaneos) y puntuación de confianza.": "Abuse reports (spam, attacks, scans) and confidence score.",
+ "Indica si la IP escanea Internet de forma masiva o pertenece a un servicio conocido.": "Tells whether the IP mass-scans the Internet or belongs to a known service.",
+ "Identificar hash": "Identify hash",
+ "Algoritmos posibles según la longitud y enlaces para buscarlo.": "Possible algorithms by length and links to look it up.",
+ "Busca el hash en la base de muestras de malware de abuse.ch.": "Looks up the hash in abuse.ch's malware sample database.",
+ "Cartera de criptomonedas": "Crypto wallet",
+ "Saldo, número de transacciones, fechas y principales contrapartes de una dirección.": "Balance, number of transactions, dates and main counterparties of an address.",
+ "Persona: usuarios probables": "Person: likely usernames",
+ "Genera los nombres de usuario más probables a partir del nombre para investigarlos con un clic.": "Generates the most likely usernames from the name so you can investigate them with one click.",
+ "Dorks de búsqueda": "Search dorks",
+ "Búsquedas avanzadas de Google preparadas para el objetivo (se abren en tu navegador).": "Advanced Google searches prepared for the target (they open in your browser).",
+ "Publicaciones académicas (OpenAlex, ORCID)": "Academic publications (OpenAlex, ORCID)",
+ "Artículos, tesis y patentes firmados con ese nombre: afiliación, coautores, temas y ORCID": "Articles, theses and patents signed with that name: affiliation, co-authors, topics and ORCID",
+ "Si la persona es pública: fecha y lugar de nacimiento, cargos, estudios, familia, web y redes oficiales": "If the person is public: date and place of birth, positions, education, family, website and official accounts",
+ "Análisis del teléfono": "Phone analysis",
+ "País, región, operador original, tipo de línea y zona horaria (sin conexión, base de Google libphonenumber).": "Country, region, original carrier, line type and time zone (offline, Google libphonenumber database).",
+ "Validación en línea del número y operador actual.": "Online validation of the number and current carrier.",
+ "Perfiles con datos": "Profiles with data",
+ "Busca el usuario en plataformas con API pública y extrae nombre, bio, ubicación, emails de commits y cuentas enlazadas.": "Looks up the username on platforms with a public API and extracts name, bio, location, commit emails and linked accounts.",
+ "Barrido de usuario (400+ sitios)": "Username sweep (400+ sites)",
+ "Comprueba si el usuario existe en cientos de webs y descarta falsos positivos repitiendo la prueba con un usuario inventado.": "Checks whether the username exists on hundreds of sites and rules out false positives by repeating the test with a made-up username.",
+ "Variantes del usuario": "Username variants",
+ "Prueba formas parecidas del usuario (sin «priv.», con guion bajo, con puntos, letras dobles, 0 por o…) en Instagram, TikTok, X, Telegram, Twitch y YouTube. Si en el caso hay otros alias de la misma familia, combina lo que tienen en común. No llena el grafo: deja la lista en el panel para que añadas sólo las que te interesen.":
+ "Tries similar forms of the username (without “priv.”, with underscores, with dots, doubled letters, 0 for o…) on Instagram, TikTok, X, Telegram, Twitch and YouTube. If the case has other aliases from the same family, it combines what they have in common. It doesn't fill the graph: it leaves the list in the panel so you add only the ones you want.",
+ "Reintentar lo bloqueado": "Retry what was blocked",
+ "Reintentar lo bloqueado ({})": "Retry what was blocked ({})",
+ "Vuelve a probar, más despacio y en varias rondas, las redes y sitios que limitaron o bloquearon la búsqueda. Lo que siga bloqueado (protecciones anti-bots) queda en una lista para que lo abras tú.":
+ "Tries again, more slowly and in several rounds, the networks and sites that rate-limited or blocked the search. Whatever stays blocked (anti-bot protection) is left in a list for you to open yourself.",
+ "Perfiles con datos": "Profiles with data",
+ "Análisis de la URL": "URL analysis",
+ "Sigue las redirecciones (desacorta enlaces) y extrae título, emails y redes sociales de la página.": "Follows redirects (unshortens links) and extracts title, emails and social networks from the page.",
+ "Detecciones de antivirus y reputación para dominios, IPs, URLs y archivos (hash).": "Antivirus detections and reputation for domains, IPs, URLs and files (hash).",
+ "Escaneos públicos anteriores del dominio: capturas, IPs y páginas vistas.": "Previous public scans of the domain: screenshots, IPs and pages seen.",
+ "Comprueba si el dominio, IP o URL distribuye malware o es infraestructura de botnets.": "Checks whether the domain, IP or URL distributes malware or is botnet infrastructure.",
+ "Búsqueda web del nombre (completo y abreviado)": "Web search of the name (full and shortened)",
+ "Busca el nombre en la web y en LinkedIn, Facebook, Instagram, X y TikTok, también sin el segundo nombre o apellido. Con clave de Serper o Brave es más fiable; sin clave usa DuckDuckGo y, si bloquea, sigue con Bing.":
+ "Searches the name on the web and on LinkedIn, Facebook, Instagram, X and TikTok, also without the middle name or second surname. With a Serper or Brave key it's more reliable; without a key it uses DuckDuckGo and, if it blocks, continues with Bing.",
+ "Los buscadores gratuitos (DuckDuckGo y Bing) limitaron las búsquedas automáticas": "The free search engines (DuckDuckGo and Bing) rate-limited automated searches",
+ "Leer el perfil público": "Read the public profile",
+ "Abre la página de la cuenta y saca el nombre visible, la foto y la descripción que muestra a cualquiera. Sirve para las cuentas de las que sólo se sabía que existen: con eso se pueden puntuar y comparar.":
+ "Opens the account's page and extracts the display name, photo and description it shows to anyone. Useful for accounts that were only known to exist: with that they can be scored and compared.",
+ "Página pública del perfil": "Public profile page",
+ "Leído: {}": "Read: {}",
+ "nombre": "name",
+ "foto": "photo",
+ "descripción": "description",
+ "La página no muestra nombre ni foto": "The page shows no name or photo",
+ "La página del perfil no existe": "The profile page doesn't exist",
+ "No existe (error 404): puede ser un falso positivo": "Doesn't exist (error 404): it may be a false positive",
+ "La página no deja leer el perfil sin navegador (respuesta {})": "The page doesn't let the profile be read without a browser (response {})",
+ "La cuenta no tiene una URL que abrir": "The account has no URL to open",
+ "La página del perfil responde «no existe»: puede ser un falso positivo": "The profile page answers “doesn't exist”: it may be a false positive",
+ "Leer perfiles": "Read profiles",
+ "Leer perfiles ({})": "Read profiles ({})",
+ "Leyendo perfiles…": "Reading profiles…",
+ "Abre la página de cada cuenta de la que sólo se sabe que existe y saca nombre, foto y descripción para poder puntuarla":
+ "Opens the page of every account only known to exist and extracts name, photo and description so it can be scored",
+ "Leyendo la página pública de cada cuenta sin datos…": "Reading the public page of every account without data…",
+ "Base de sitios de Sherlock": "Sherlock site database",
+ "Lista propia": "Own list",
+
+ // ------------------------------------------------------------ mensajes de los módulos
+ "{} hallazgos": "{} findings",
+ "Datos añadidos": "Data added",
+ "Sin resultados": "No results",
+ "Tiempo agotado ({} s)": "Timed out ({} s)",
+ "{} hallazgos parciales": "{} partial findings",
+ "Error de red: {}": "Network error: {}",
+ "Requiere clave de {}: añádela en Ajustes ({})": "Requires a {} key: add it in Settings ({})",
+ "{} fotos comparables": "{} comparable photos",
+ "{} fotos comparadas": "{} photos compared",
+ "{} coincidencias": "{} matches",
+ "{} coincidencias ({} nuevas)": "{} matches ({} new)",
+ "No hay cuentas que verificar": "There are no accounts to verify",
+ "Configura un proveedor de IA en Ajustes (Ollama local, Groq, Gemini, OpenAI…)": "Set up an AI provider in Settings (local Ollama, Groq, Gemini, OpenAI…)",
+ "No se pudo contactar con la IA ({}). ¿Está en marcha?": "Couldn't reach the AI ({}). Is it running?",
+ "La IA respondió {}: {}": "The AI answered {}: {}",
+ "Respuesta de IA no válida: {}": "Invalid AI response: {}",
+ "La IA no devolvió JSON": "The AI didn't return JSON",
+ "{} cuentas evaluadas por {}": "{} accounts evaluated by {}",
+ "No se pudo leer la imagen: {}": "Couldn't read the image: {}",
+ "No tiene formato de RUT": "Not in RUT format",
+ "Dígito verificador inválido (debería ser {})": "Invalid check digit (should be {})",
+ "No coincide con ningún formato de patente chilena": "Doesn't match any Chilean plate format",
+ "El dominio no está inscrito en NIC Chile": "The domain isn't registered at NIC Chile",
+ "Inválido: con {} el dígito correcto es {}": "Invalid: with {} the correct digit is {}",
+ "NIC Chile respondió {}": "NIC Chile answered {}",
+ "Hace falta nombre y apellido": "First name and surname are needed",
+ "No aparece entre las {} declaraciones": "Doesn't appear among the {} declarations",
+ "{} declarantes con ese nombre: agrega el segundo apellido para distinguirlos": "{} declarants with that name: add the second surname to tell them apart",
+ "{} declaraciones de {} persona(s)": "{} declarations from {} person(s)",
+ "Sólo aplica a RUT de empresas (50 millones o más)": "Only applies to company RUTs (50 million or more)",
+ "No figura entre las empresas creadas por el Registro (desde 2013)": "Not among the companies created through the Registry (since 2013)",
+ "Base de empresas descargada (sólo la primera vez)": "Company database downloaded (first time only)",
+ "{} empresa(s) con su nombre completo": "{} company(ies) with their full name",
+ "{} sociedades con sus dos apellidos (posibles familiares)": "{} companies with both their surnames (possible relatives)",
+ "Sin tesis ni publicaciones con ese nombre": "No theses or publications with that name",
+ "{} tesis y {} publicaciones con su nombre completo": "{} theses and {} publications with their full name",
+ "{} con nombre parecido": "{} with a similar name",
+ "datos.gob.cl no entregó {} de los archivos anuales; se reintentará en la próxima búsqueda": "datos.gob.cl didn't deliver {} of the yearly files; it will retry on the next search",
+ "Límite de la API de GitHub alcanzado (60/hora sin clave): añade un token gratuito en Ajustes": "GitHub API limit reached (60/hour without a key): add a free token in Settings",
+ "El usuario tiene caracteres que no forman parte de una URL de perfil": "The username has characters that can't be part of a profile URL",
+ "Internet Archive no respondió ({} consultas fallidas); prueba más tarde": "Internet Archive didn't answer ({} failed lookups); try later",
+ "Copias en {} plataformas": "Copies on {} platforms",
+ "Término demasiado corto para buscar menciones sin ruido": "Term too short to search mentions without noise",
+ "{} menciones en Hacker News": "{} mentions on Hacker News",
+ "sin respuesta: {}": "no answer: {}",
+ "Hacker News respondió {}": "Hacker News answered {}",
+ "No se encontraron documentos publicados en este dominio": "No documents published on this domain were found",
+ "{} documentos encontrados en {}, pero ninguno se pudo descargar o no tenían metadatos": "{} documents found on {}, but none could be downloaded or they had no metadata",
+ "{} documentos analizados ({})": "{} documents analyzed ({})",
+ "{} autores": "{} authors",
+ "{} usuarios internos": "{} internal usernames",
+ "{} emails": "{} emails",
+ "El registro no publica RDAP para este dominio": "The registry doesn't publish RDAP for this domain",
+ "{} subdominios (60 en el grafo, lista completa en la ficha)": "{} subdomains (60 in the graph, full list in the details)",
+ "La web no responde": "The website doesn't respond",
+ "Registrado en {}: {}": "Registered on {}: {}",
+ "Hunter respondió {}": "Hunter answered {}",
+ "sin respuesta fiable: {}": "no reliable answer: {}",
+ "Invitación caducada o inválida": "Expired or invalid invite",
+ "Nominatim respondió {}": "Nominatim answered {}",
+ "No se encontró en el mapa": "Not found on the map",
+ "Sin fotos públicas o el usuario no existe": "No public photos or the user doesn't exist",
+ "{} fotos recientes": "{} recent photos",
+ "{} lugares con GPS": "{} places with GPS",
+ "IP privada o reservada: no hay datos públicos": "Private or reserved IP: no public data",
+ "AbuseIPDB respondió {}": "AbuseIPDB answered {}",
+ "Límite de GreyNoise alcanzado; añade una clave gratuita en Ajustes": "GreyNoise limit reached; add a free key in Settings",
+ "Shodan respondió {}": "Shodan answered {}",
+ "Sólo con «{}»: puede ser otra persona": "Only with “{}”: may be someone else",
+ "Wikidata respondió {}": "Wikidata answered {}",
+ "{} personas públicas con este nombre: revisa cuál es antes de atribuir datos": "{} public people with this name: check which one before attributing data",
+ "No se pudo interpretar el número. Escríbelo con prefijo internacional (+34…, +54…)": "Couldn't parse the number. Write it with the international prefix (+34…, +54…)",
+ "El usuario contiene caracteres que las webs no aceptan": "The username contains characters websites don't accept",
+ "{} perfiles en {} sitios": "{} profiles on {} sites",
+ "{} falsos positivos descartados": "{} false positives ruled out",
+ "{} bloqueados": "{} blocked",
+ "{} sin respuesta": "{} without answer",
+ "No se me ocurren variantes para este usuario": "No variants come to mind for this username",
+ "{} de {} variantes existen en alguna red": "{} of {} variants exist on some network",
+ "Ninguna de las {} variantes existe en las redes probadas": "None of the {} variants exist on the networks tried",
+ "limitado: {}": "rate-limited: {}",
+ "familia «{}» ({} alias)": "family “{}” ({} aliases)",
+ "{} cuentas nuevas": "{} new accounts",
+ "Nada nuevo": "Nothing new",
+ "siguen limitando: {}": "still rate-limiting: {}",
+ "{} sitios con protección anti-bots: revísalos a mano en el panel": "{} sites with anti-bot protection: check them by hand in the panel",
+ "Datos mínimos (TikTok no dejó ver el perfil completo)": "Minimal data (TikTok didn't show the full profile)",
+ "Comprobado a mano en el navegador": "Checked by hand in the browser",
+ "Comprobación manual": "Manual check",
+ "Encontrado en {} de {}: {}": "Found on {} of {}: {}",
+ "Sin perfiles": "No profiles",
+ "no se pudo comprobar (limitado): {}": "couldn't check (rate-limited): {}",
+ "VirusTotal no lo conoce": "VirusTotal doesn't know it",
+ "VirusTotal respondió {}": "VirusTotal answered {}",
+ "URLScan requiere clave o se superó el límite": "URLScan requires a key or the limit was exceeded",
+ "Sin rastro en URLhaus ni ThreatFox": "No trace in URLhaus or ThreatFox",
+ "{} maliciosos, {} sospechosos de {}": "{} malicious, {} suspicious out of {}",
+ "{} con el nombre completo": "{} with the full name",
+ "{}: añade una clave gratuita de Serper o Brave en Ajustes, o usa los dorks": "{}: add a free Serper or Brave key in Settings, or use the dorks",
+ "UTC{} aprox. (inactivo entre las {}h y {}h UTC, {} comentarios)": "UTC{} approx. (inactive between {}h and {}h UTC, {} comments)",
+
+ // ------------------------------------------------------------ señales del análisis y verificaciones
+ "El email investigado está registrado en este servicio": "The investigated email is registered on this service",
+ "Cuenta oficial según Wikidata": "Official account according to Wikidata",
+ "Sólo se comprobó que el nombre de usuario existe": "It was only checked that the username exists",
+ "Encontrada buscando el nombre completo: puede ser un homónimo": "Found by searching the full name: may be a namesake",
+ "Sólo coincide parte del nombre: revisa que sea la misma persona": "Only part of the name matches: check that it's the same person",
+ "Sólo aparece en Internet Archive": "Only appears on the Internet Archive",
+ "Perfil con datos públicos": "Profile with public data",
+ "El nombre «{}» coincide con el de una cuenta confirmada": "The name “{}” matches that of a confirmed account",
+ "El nombre «{}» no coincide con el de las cuentas confirmadas": "The name “{}” doesn't match that of the confirmed accounts",
+ "El nombre «{}» coincide con otras cuentas": "The name “{}” matches other accounts",
+ "El nombre «{}» no coincide con el resto de cuentas": "The name “{}” doesn't match the other accounts",
+ "Usa la misma foto de perfil que una cuenta confirmada": "Uses the same profile photo as a confirmed account",
+ "Usa la misma foto de perfil que otra cuenta": "Uses the same profile photo as another account",
+ "Comparte {} con una cuenta confirmada": "Shares {} with a confirmed account",
+ "Comparte {} con otras cuentas": "Shares {} with other accounts",
+ "{} ({}; esa cuenta {})": "{} ({}; that account {})",
+ "comparten clave SSH": "they share an SSH key",
+ "el propio dueño puso el enlace": "the owner posted the link",
+ "está confirmada": "is confirmed",
+ "tiene confianza {}": "has confidence {}",
+ "IA: {}": "AI: {}",
+ "Existe (comprobado contra usuario inventado)": "Exists (checked against a made-up username)",
+ "Enlazada desde {}": "Linked from {}",
+ "Búsqueda web: perfil con el nombre completo": "Web search: profile with the full name",
+ "Búsqueda web: coincidencia parcial («{}»)": "Web search: partial match (“{}”)",
+ "Añadido a mano desde la búsqueda web": "Added by hand from the web search",
+ "Datos de la vista previa pública (Instagram limitó su API): sin bio ni enlaces": "Data from the public preview (Instagram rate-limited its API): no bio or links",
+ "misma persona": "same person",
+ "probable": "likely",
+ "dudosa": "doubtful",
+ "otra persona": "someone else",
+ "Sí": "Yes",
+ "No": "No",
+ "Canal público": "Public channel",
+ "Persona natural": "Individual",
+ "Persona jurídica": "Company",
+
+ // ------------------------------------------------------------ enlaces y grupos de dorks
+ "Abrir perfil": "Open profile",
+ "Abrir en GitHub": "Open on GitHub",
+ "Abrir tesis": "Open thesis",
+ "Primera copia archivada": "First archived copy",
+ "Última copia archivada": "Last archived copy",
+ "Todas las copias": "All copies",
+ "Primera captura": "First capture",
+ "Todas las capturas": "All captures",
+ "Ver en mapa": "View on map",
+ "Ver en VirusTotal": "View on VirusTotal",
+ "Perfil en OpenAlex": "OpenAlex profile",
+ "Declaración en InfoProbidad": "Declaration on InfoProbidad",
+ "Ficha en NIC Chile": "NIC Chile record",
+ "Otros dominios .cl que contengan el nombre (marca «Contenga»)": "Other .cl domains containing the name (check “Contenga”)",
+ "RUT sin dígito": "RUT without digit",
+ "Dígito": "Digit",
+ "Nombre": "Name",
+ "SII · situación tributaria de terceros (nombre o razón social, actividades)": "SII · third-party tax status (name or legal name, activities)",
+ "Registro de Empresas y Sociedades": "Company Registry",
+ "Poder Judicial · consulta unificada de causas": "Judiciary · unified case search",
+ "Mercado Público (proveedores del Estado)": "Mercado Público (government suppliers)",
+ "CMF · entidades fiscalizadas": "CMF · supervised entities",
+ "Autoseguro · ¿tiene encargo por robo?": "Autoseguro · is it reported stolen?",
+ "Registro Civil · multas de tránsito impagas": "Civil Registry · unpaid traffic fines",
+ "Registro Civil · certificado de anotaciones vigentes (dueño; de pago)": "Civil Registry · current registration certificate (owner; paid)",
+ "Menciones exactas": "Exact mentions",
+ "En redes sociales": "On social networks",
+ "En foros": "On forums",
+ "Con email": "With email",
+ "Credenciales o combos": "Credentials or combos",
+ "Listas de juegos y Discord": "Game lists and Discord",
+ "Tiendas y reseñas": "Stores and reviews",
+ "Música y creadores": "Music and creators",
+ "Citas y comunidades": "Dating and communities",
+ "Yandex (mejor para alias y foros rusos)": "Yandex (best for aliases and Russian forums)",
+ "Sólo la parte local": "Local part only",
+ "En redes y perfiles": "On networks and profiles",
+ "Nube expuesta (Drive, OneDrive, S3…)": "Exposed cloud (Drive, OneDrive, S3…)",
+ "Plataformas de documentos": "Document platforms",
+ "CV y empleo": "Resumes and jobs",
+ "Código y tableros": "Code and boards",
+ "Herramientas internas (Jira, Postman…)": "Internal tools (Jira, Postman…)",
+ "Con contraseña cerca": "With a password nearby",
+ "Buscar en Google": "Search on Google",
+ "Hashes.com (contraseñas)": "Hashes.com (passwords)",
+ "Anuncios y perfiles": "Listings and profiles",
+ "WhatsApp y Telegram públicos": "Public WhatsApp and Telegram",
+ "Nube expuesta": "Exposed cloud",
+ "Páginas indexadas": "Indexed pages",
+ "Emails del dominio": "Domain emails",
+ "Empleados en LinkedIn": "Employees on LinkedIn",
+ "Documentos expuestos": "Exposed documents",
+ "Documentos internos": "Internal documents",
+ "Nube expuesta (Drive, S3, Azure…)": "Exposed cloud (Drive, S3, Azure…)",
+ "Paneles de acceso": "Login panels",
+ "Ficheros de configuración": "Configuration files",
+ "Listados de directorios": "Directory listings",
+ "Errores y trazas": "Errors and stack traces",
+ "APIs y Swagger": "APIs and Swagger",
+ "Herramientas internas filtradas": "Leaked internal tools",
+ "Secretos en código": "Secrets in code",
+ "Menciones en pastes": "Mentions in pastes",
+ "Redes sociales": "Social networks",
+ "Documentos y CV": "Documents and resumes",
+ "CV y portales de empleo": "Resumes and job portals",
+ "Tesis y trabajos académicos": "Theses and academic work",
+ "Su RUT en documentos públicos (Chile)": "Their RUT in public documents (Chile)",
+ "Audiencias de lobby (como lobista o autoridad)": "Lobbying meetings (as lobbyist or authority)",
+ "Declaraciones de patrimonio": "Asset declarations",
+ "Causas judiciales publicadas": "Published court cases",
+ "Diario Oficial (sociedades, notificaciones)": "Official Gazette (companies, notices)",
+ "Sueldos y contratos públicos (Transparencia)": "Public salaries and contracts (Transparency)",
+ "Tesis en repositorios chilenos": "Theses in Chilean repositories",
+ "Yandex (mejor para caras y nombres)": "Yandex (best for faces and names)",
+ "Todas las variantes a la vez": "All variants at once",
+ "LinkedIn con cualquier variante": "LinkedIn with any variant",
+ "Facebook e Instagram con cualquier variante": "Facebook and Instagram with any variant",
+ "Menciones (todas las formas de escribirlo)": "Mentions (all ways of writing it)",
+ "Documentos (PDF, Excel, Word)": "Documents (PDF, Excel, Word)",
+ "Poder Judicial y Tribunal Constitucional": "Judiciary and Constitutional Court",
+ "Mercado Público y compras del Estado": "Mercado Público and government purchases",
+ "Transparencia, plantas y sueldos públicos": "Transparency, staff lists and public salaries",
+ "Empresas (registro, CMF, SII)": "Companies (registry, CMF, SII)",
+ "Universidades y colegios (listas, resultados)": "Universities and schools (lists, results)",
+ "Menciones de la patente": "Mentions of the plate",
+ "Avisos de venta (Chileautos, MercadoLibre, Yapo…)": "Sale listings (Chileautos, MercadoLibre, Yapo…)",
+ "En redes (grupos, denuncias, robos)": "On social networks (groups, reports, thefts)",
+ "Robos y denuncias": "Thefts and reports",
+ "Buscadores de patentes": "Plate search engines",
+ "En pastes y listas negras": "In pastes and blacklists",
+ "Enlaces a la URL": "Links to the URL",
+ "En foros y pastes": "In forums and pastes",
+ "Donaciones en perfiles": "Donations on profiles",
+ "Chile: Estado y justicia": "Chile: government and courts",
+ "Chile · Diario Oficial": "Chile · Official Gazette",
+ "Chile · Mercado Público (licitaciones)": "Chile · Mercado Público (tenders)",
+ "Chile · Poder Judicial y causas": "Chile · Judiciary and cases",
+ "Chile · Transparencia (plantas y sueldos públicos)": "Chile · Transparency (staff lists and public salaries)",
+ "Chile · Empresas y sociedades": "Chile · Companies",
+ "Chile · Congreso y Contraloría": "Chile · Congress and Comptroller",
+ "Argentina · Boletín Oficial": "Argentina · Official Gazette",
+ "Argentina · Compras públicas": "Argentina · Public procurement",
+ "Argentina · Poder Judicial": "Argentina · Judiciary",
+ "Argentina · Organismos públicos": "Argentina · Public agencies",
+ "Argentina · Boletines provinciales": "Argentina · Provincial gazettes",
+ "España · BOE y boletines": "Spain · BOE and gazettes",
+ "España · Empresas (BORME)": "Spain · Companies (BORME)",
+ "México · DOF": "Mexico · DOF",
+ "México · Compras y gobierno": "Mexico · Procurement and government",
+ "Básicos": "Basics",
+ "Código": "Code",
+ "Filtraciones y código": "Breaches and code",
+ "Currículum": "Resume",
+ "Documentos y nube": "Documents and cloud",
+ "Menciones": "Mentions",
+ "Noticias": "News",
+ "Otros buscadores": "Other search engines",
+ "Perfil": "Profile",
+ "Poco comunes": "Less common",
+ "Registros oficiales": "Official records",
+ "Seguridad": "Security",
+ "Sitios no oficiales (verifica lo que digan)": "Unofficial sites (verify what they say)",
+ "Cuentas": "Accounts",
+ "{} ← {}": "{} ← {}",
+ "Parte local del email": "Local part of the email",
+ "Registro confirmado (contrastado con un email inventado)": "Registration confirmed (checked against a made-up email)",
+ "contraseña": "password",
+ "código por email": "code by email",
+ "Behance, Photoshop, Acrobat y demás servicios de Adobe": "Behance, Photoshop, Acrobat and other Adobe services",
+ "Snapchat con Bitmoji": "Snapchat with Bitmoji",
+ "Cuenta compartida con Expedia y Hotels.com": "Account shared with Expedia and Hotels.com",
+ "Disney+, ESPN y demás servicios de Disney": "Disney+, ESPN and other Disney services",
+ "Cuenta corporativa federada": "Federated corporate account",
+ "Desechable/temporal": "Disposable/temporary",
+ "Creó la invitación": "Created the invite",
+ "Indicada en Wikidata (cuenta oficial)": "Listed on Wikidata (official account)",
+ "Institución pública": "Public institution",
+ "Misma clave SSH que GitHub": "Same SSH key as GitHub",
+ "Proveedor autorizado en SPF": "Authorized provider in SPF",
+ "Recibe informes DMARC": "Receives DMARC reports",
+ "Servidor DNS": "DNS server",
+ "Servidor de correo": "Mail server",
+ "Subdominio": "Subdomain",
+ "Sólo vista en archivo (puede estar borrada o no se comprobó en vivo)": "Only seen in the archive (may be deleted or wasn't checked live)",
+ "Titular de dominio .cl": ".cl domain holder",
+ "Universidad": "University",
+ "Usuario interno en metadatos": "Internal username in metadata",
+ "Proveedor gratuito": "Free provider",
+ "Dominio propio/corporativo": "Own/corporate domain",
+ "Cuenta Microsoft / Office 365": "Microsoft / Office 365 account",
+ },
+
+ keys: {
+ "Foto coincide con": "Photo matches",
+ "Nivel de confianza": "Confidence level",
+ "IA: veredicto": "AI: verdict",
+ "IA: motivo": "AI: reason",
+ "IA: resumen": "AI: summary",
+ "IA: modelo": "AI: model",
+ "Archivo": "File",
+ "Tamaño (bytes)": "Size (bytes)",
+ "Precisión": "Accuracy",
+ "Dígito verificador": "Check digit",
+ "Tipo": "Type",
+ "Formas de escribirlo": "Ways of writing it",
+ "Formato": "Format",
+ "Escrita": "Written",
+ "Titular (NIC Chile)": "Holder (NIC Chile)",
+ "Agente registrador": "Registrar",
+ "Alta (NIC Chile)": "Created (NIC Chile)",
+ "Última modificación (NIC Chile)": "Last modified (NIC Chile)",
+ "Caduca (NIC Chile)": "Expires (NIC Chile)",
+ "Servidores DNS (NIC Chile)": "DNS servers (NIC Chile)",
+ "Rol": "Role",
+ "Pasivos": "Liabilities",
+ "Patrimonio_Conyuge": "Spouse assets",
+ "Tipo de sociedad": "Company type",
+ "Constituida": "Incorporated",
+ "Comuna": "District",
+ "Capital": "Capital",
+ "Disuelta": "Dissolved",
+ "Historial (Registro de Empresas)": "History (Company Registry)",
+ "Nombres anteriores": "Former names",
+ "Cargo (InfoProbidad)": "Position (InfoProbidad)",
+ "Historial de cargos": "Position history",
+ "Profesión": "Profession",
+ "Estado civil": "Marital status",
+ "Renta o grado": "Salary or grade",
+ "Asumió el cargo": "Took office",
+ "Comuna declarada": "Declared district",
+ "Vehículos declarados": "Declared vehicles",
+ "Deudas declaradas": "Declared debts",
+ "Rubro": "Industry",
+ "Publicaciones (LA Referencia)": "Publications (LA Referencia)",
+ "Tesis con nombre parecido": "Theses with a similar name",
+ "InfoProbidad: nombres parecidos": "InfoProbidad: similar names",
+ "InfoProbidad: homónimos": "InfoProbidad: namesakes",
+ "Fuente": "Source",
+ "Sociedades con sus dos apellidos (posibles familiares)": "Companies with both their surnames (possible relatives)",
+ "Título": "Title",
+ "Año": "Year",
+ "Institución": "Institution",
+ "País": "Country",
+ "Profesor guía": "Advisor",
+ "Temas": "Topics",
+ "Rol de avalúo": "Property tax ID",
+ "Inscripción": "Registration",
+ "Wayback: primera captura": "Wayback: first capture",
+ "Wayback: última captura": "Wayback: last capture",
+ "Wayback: meses con capturas": "Wayback: months with captures",
+ "Menciones en Hacker News": "Mentions on Hacker News",
+ "Menciones recientes (HN)": "Recent mentions (HN)",
+ "Quién lo menciona más (HN)": "Who mentions it most (HN)",
+ "Primera mención (HN)": "First mention (HN)",
+ "Repos propios (últimos 100)": "Own repos (last 100)",
+ "Estrellas recibidas": "Stars received",
+ "Lenguajes": "Languages",
+ "Repos destacados": "Featured repos",
+ "Último push": "Last push",
+ "Plataforma": "Platform",
+ "Usuario": "Username",
+ "Verificación": "Verification",
+ "Claves SSH en común": "Shared SSH keys",
+ "Descripción": "Description",
+ "Documentos analizados": "Documents analyzed",
+ "Software de los documentos": "Document software",
+ "Autores en metadatos": "Authors in metadata",
+ "Usuarios internos en metadatos": "Internal usernames in metadata",
+ "Periodo de los documentos": "Document period",
+ "Documentos firmados": "Signed documents",
+ "Aparece en documentos": "Appears in documents",
+ "Origen": "Origin",
+ "Contexto en documentos": "Context in documents",
+ "Documentos": "Documents",
+ "Título web": "Web title",
+ "Descripción web": "Web description",
+ "Tecnologías": "Technologies",
+ "IDs de analítica/publicidad": "Analytics/ad IDs",
+ "Alta": "Created",
+ "Caduca": "Expires",
+ "Última modificación": "Last modified",
+ "Estado": "Status",
+ "Contexto en la web": "Context on the web",
+ "Subdominios": "Subdomains",
+ "Nº subdominios": "No. of subdomains",
+ "Web: estado HTTP": "Web: HTTP status",
+ "Web: URL final": "Web: final URL",
+ "Servicios verificados (TXT)": "Verified services (TXT)",
+ "Rol WHOIS": "WHOIS role",
+ "Dirección": "Address",
+ "Teléfono": "Phone",
+ "Nombre": "Name",
+ "Inicio de sesión": "Sign-in",
+ "Incluye": "Includes",
+ "Dominio": "Domain",
+ "Acepta correo (MX)": "Accepts mail (MX)",
+ "Servidores MX": "MX servers",
+ "Proveedor de correo": "Mail provider",
+ "Registro": "Registration",
+ "Registrado en": "Registered on",
+ "No registrado en": "Not registered on",
+ "Hunter: estado": "Hunter: status",
+ "Hunter: puntuación": "Hunter: score",
+ "Hunter: SMTP válido": "Hunter: valid SMTP",
+ "Hunter: acepta todo": "Hunter: accept-all",
+ "Puesto": "Job title",
+ "Empresa": "Company",
+ "Pronombres": "Pronouns",
+ "Fecha": "Date",
+ "Datos expuestos": "Exposed data",
+ "Registros": "Records",
+ "Sector": "Industry",
+ "Riesgo contraseña": "Password risk",
+ "Filtraciones": "Breaches",
+ "Riesgo (XposedOrNot)": "Risk (XposedOrNot)",
+ "Visto": "Seen",
+ "Servidor": "Server",
+ "Miembros": "Members",
+ "En línea": "Online",
+ "ID del servidor": "Server ID",
+ "Servidor creado": "Server created",
+ "URL personalizada": "Custom URL",
+ "Lugar (OpenStreetMap)": "Place (OpenStreetMap)",
+ "Nombre visible": "Display name",
+ "Página del perfil": "Profile page",
+ "Fotos públicas recientes": "Recent public photos",
+ "Fotos con GPS": "Photos with GPS",
+ "Primera foto reciente": "First recent photo",
+ "Última foto": "Last photo",
+ "Creada": "Created",
+ "Fotos tomadas aquí": "Photos taken here",
+ "Fechas": "Dates",
+ "Región": "Region",
+ "Ciudad": "City",
+ "Zona horaria": "Time zone",
+ "Red móvil": "Mobile network",
+ "Puertos abiertos": "Open ports",
+ "Etiquetas": "Tags",
+ "Vulnerabilidades (CVE)": "Vulnerabilities (CVE)",
+ "Shodan: organización": "Shodan: organization",
+ "Shodan: SO": "Shodan: OS",
+ "Shodan: servicios": "Shodan: services",
+ "Shodan: última vez": "Shodan: last seen",
+ "AbuseIPDB: puntuación": "AbuseIPDB: score",
+ "AbuseIPDB: reportes (1 año)": "AbuseIPDB: reports (1 year)",
+ "AbuseIPDB: uso": "AbuseIPDB: usage",
+ "AbuseIPDB: último reporte": "AbuseIPDB: last report",
+ "Nodo Tor": "Tor node",
+ "GreyNoise: escáner masivo": "GreyNoise: mass scanner",
+ "GreyNoise: servicio conocido": "GreyNoise: known service",
+ "GreyNoise: clasificación": "GreyNoise: classification",
+ "GreyNoise: visto": "GreyNoise: seen",
+ "Organización": "Organization",
+ "Algoritmos posibles": "Possible algorithms",
+ "Malware: familia": "Malware: family",
+ "Malware: archivo": "Malware: file",
+ "Malware: tipo": "Malware: type",
+ "Malware: visto": "Malware: seen",
+ "Malware: etiquetas": "Malware: tags",
+ "Red": "Network",
+ "Saldo": "Balance",
+ "Recibido total": "Total received",
+ "Transacciones": "Transactions",
+ "Es contrato": "Is contract",
+ "Primera actividad": "First activity",
+ "Última actividad": "Last activity",
+ "Última actividad (muestra)": "Last activity (sample)",
+ "Transacciones en común (muestra)": "Shared transactions (sample)",
+ "OpenAlex: trabajos": "OpenAlex: works",
+ "OpenAlex: citas": "OpenAlex: citations",
+ "OpenAlex: índice h": "OpenAlex: h-index",
+ "Temas de investigación": "Research topics",
+ "Afiliación (OpenAlex)": "Affiliation (OpenAlex)",
+ "Descripción (Wikidata)": "Description (Wikidata)",
+ "ORCID: perfiles con este nombre": "ORCID: profiles with this name",
+ "OpenAlex: autores con nombre parecido": "OpenAlex: authors with a similar name",
+ "OpenAlex: autores con este nombre": "OpenAlex: authors with this name",
+ "Válido": "Valid",
+ "Internacional": "International",
+ "Nacional": "National",
+ "Zona": "Area",
+ "Operador original": "Original carrier",
+ "Tipo de línea": "Line type",
+ "Numverify: válido": "Numverify: valid",
+ "Numverify: operador": "Numverify: carrier",
+ "Numverify: tipo": "Numverify: type",
+ "Numverify: ubicación": "Numverify: location",
+ "Comentarios": "Comments",
+ "Publicaciones": "Posts",
+ "Repos públicos": "Public repos",
+ "Seguidores": "Followers",
+ "Nombres en commits": "Names in commits",
+ "Campos": "Fields",
+ "Siguiendo": "Following",
+ "Verificada": "Verified",
+ "Protegida": "Protected",
+ "ID del canal": "Channel ID",
+ "Suscriptores": "Subscribers",
+ "Última emisión": "Last stream",
+ "Título última emisión": "Last stream title",
+ "ID de Instagram": "Instagram ID",
+ "Nota": "Note",
+ "Privada": "Private",
+ "Categoría": "Category",
+ "Teléfono de empresa": "Business phone",
+ "Me gusta": "Likes",
+ "Vídeos": "Videos",
+ "Última conexión": "Last seen",
+ "Racha": "Streak",
+ "XP total": "Total XP",
+ "Idiomas": "Languages",
+ "Baneado": "Banned",
+ "Nombre real": "Real name",
+ "Miembro desde": "Member since",
+ "Resumen": "Summary",
+ "Invitado por": "Invited by",
+ "Reputación": "Reputation",
+ "Otros con el mismo nombre": "Others with the same name",
+ "Última publicación": "Last post",
+ "Publicaciones recientes": "Recent posts",
+ "VirusTotal: detecciones": "VirusTotal: detections",
+ "VirusTotal: reputación": "VirusTotal: reputation",
+ "Estado HTTP": "HTTP status",
+ "Acortador": "Shortener",
+ "Redirecciones": "Redirects",
+ "URL final": "Final URL",
+ "Tipo de contenido": "Content type",
+ "URLScan: escaneos": "URLScan: scans",
+ "Nombre de archivo": "File name",
+ "Otros nombres": "Other names",
+ "Tipo de archivo": "File type",
+ "Clasificación": "Classification",
+ "Primera vez visto": "First seen",
+ "Variante de": "Variant of",
+ "Existe en": "Exists on",
+ "Horas más activas (UTC)": "Most active hours (UTC)",
+ "Subreddits frecuentes": "Frequent subreddits",
+ "Zona horaria estimada": "Estimated time zone",
+ "Tipo de cuenta": "Account type",
+ "Info": "Info",
+ "Web": "Website",
+ },
+};
+
+I18N.load(I18N_EN);
+I18N.start();
diff --git a/web/i18n.js b/web/i18n.js
new file mode 100644
index 0000000..558a054
--- /dev/null
+++ b/web/i18n.js
@@ -0,0 +1,154 @@
+"use strict";
+
+// Traducción de la interfaz. El código y los módulos escriben en español; en inglés se traduce lo que se muestra
+// (texto del DOM, atributos, diálogos, etiquetas del grafo e informe) con el diccionario de i18n-en.js.
+const I18N = (() => {
+ const lang = localStorage.getItem("osint-lang") === "en" ? "en" : "es";
+ const locale = lang === "en" ? "en-US" : "es-CL";
+ const exact = new Map(), keys = new Map(), patterns = [];
+ const missing = new Set();
+ const SPANISH = /[áéíóúñ¿¡]|\b(de|del|los|las|una|con|sin|para|que|por|sus|nodos?|cuentas?|buscar|investigar|caso)\b/i;
+ const SKIP = "textarea, input, script, style, code, [data-notr], .det-title, .det-value, .leaflet-attribution-flag";
+
+ const escRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+ function compile(es, en) {
+ const parts = es.split("{}");
+ const re = new RegExp("^" + parts.map(escRe).join("(.+?)") + "$", "s");
+ patterns.push({ re, en, lit: parts.reduce((n, p) => n + p.length, 0) });
+ }
+ function load(dict) {
+ for (const [es, en] of Object.entries(dict.text || {})) (es.includes("{}") ? compile(es, en) : exact.set(es, en));
+ for (const [es, en] of Object.entries(dict.keys || {})) keys.set(es, en);
+ patterns.sort((a, b) => b.lit - a.lit);
+ }
+
+ function lookup(s) {
+ if (exact.has(s)) return exact.get(s);
+ const low = s.charAt(0).toUpperCase() + s.slice(1);
+ if (low !== s && exact.has(low)) { const t = exact.get(low); return t.charAt(0).toLowerCase() + t.slice(1); }
+ if (keys.has(s)) return keys.get(s);
+ return null;
+ }
+
+ function fill(p, m, depth) {
+ let i = 1;
+ return p.en.replace(/\{\}/g, () => { const v = m[i++] ?? ""; return (v.trim() && trCore(v.trim(), depth + 1)) ?? v; });
+ }
+
+ function trCore(s, depth = 0) {
+ const hit = lookup(s);
+ if (hit != null) return hit;
+ if (/\s{2,}|\n/.test(s) && depth === 0) {
+ const flat = trCore(s.replace(/\s+/g, " "), 1);
+ if (flat != null) return flat;
+ }
+ if (s.length > 1 && s.endsWith(":")) {
+ const t = trCore(s.slice(0, -1), depth + 1);
+ if (t != null) return t + ":";
+ }
+ for (const p of patterns) {
+ const m = s.match(p.re);
+ if (m) return fill(p, m, depth);
+ }
+ if (depth < 3) {
+ for (const sep of [" · ", "\n", "; ", ", "]) {
+ if (!s.includes(sep)) continue;
+ const segs = s.split(sep);
+ const out = segs.map((x) => (x.trim() ? trCore(x.trim(), depth + 1) ?? x : x));
+ if (!out.some((x, i) => x !== segs[i])) continue;
+ // en listas con comas sólo vale si no queda nada en español (evita traducir frases a medias)
+ if (sep === ", " && out.some((x, i) => x === segs[i] && SPANISH.test(x))) continue;
+ return out.join(sep);
+ }
+ }
+ return null;
+ }
+
+ /** Traduce un texto completo; conserva los espacios de los extremos. */
+ function tr(text) {
+ if (lang === "es" || text == null) return text;
+ const s = String(text);
+ const core = s.trim();
+ if (!core || !/[A-Za-zÁ-ú]/.test(core)) return s;
+ const out = trCore(core);
+ if (out == null) {
+ if (SPANISH.test(core) && core.length < 400) missing.add(core);
+ return s;
+ }
+ return s.replace(core, out);
+ }
+
+ /** Nombres de campos (la columna izquierda de las tablas de datos). */
+ function trKey(text) {
+ if (lang === "es") return text;
+ const core = String(text).trim();
+ return keys.has(core) ? keys.get(core) : tr(text);
+ }
+
+ const isKeyCell = (el) => el && el.tagName === "TD" && !el.previousElementSibling && el.closest("table.attrs, table.kv");
+
+ function translateNode(node) {
+ if (node.nodeType === 3) {
+ const parent = node.parentElement;
+ if (!parent || parent.closest(SKIP)) return;
+ const t = isKeyCell(parent) ? trKey(node.nodeValue) : tr(node.nodeValue);
+ if (t !== node.nodeValue) node.nodeValue = t;
+ return;
+ }
+ if (node.nodeType !== 1 || node.closest("[data-notr]")) return;
+ for (const a of ["title", "placeholder", "aria-label"]) {
+ const v = node.getAttribute(a);
+ if (v) { const t = tr(v); if (t !== v) node.setAttribute(a, t); }
+ }
+ if (node.matches(SKIP)) return;
+ for (const c of node.childNodes) translateNode(c);
+ }
+
+ function translateTree(root) {
+ if (lang === "es" || !root) return;
+ translateNode(root);
+ }
+
+ function start() {
+ if (lang === "es") return;
+ document.documentElement.lang = "en";
+ document.title = tr(document.title);
+ translateTree(document.body);
+ new MutationObserver((muts) => {
+ for (const m of muts) {
+ if (m.type === "childList") m.addedNodes.forEach(translateNode);
+ else if (m.type === "characterData") translateNode(m.target);
+ else if (m.type === "attributes") {
+ const v = m.target.getAttribute(m.attributeName);
+ if (v && !m.target.closest("[data-notr]")) { const t = tr(v); if (t !== v) m.target.setAttribute(m.attributeName, t); }
+ }
+ }
+ }).observe(document.body, { childList: true, subtree: true, characterData: true, attributes: true,
+ attributeFilter: ["title", "placeholder", "aria-label"] });
+ const multi = (m) => String(m ?? "").split("\n").map((l) => tr(l)).join("\n");
+ const p = window.prompt.bind(window), c = window.confirm.bind(window), a = window.alert.bind(window);
+ window.prompt = (m, d) => p(multi(m), d);
+ window.confirm = (m) => c(multi(m));
+ window.alert = (m) => a(multi(m));
+ }
+
+ /** Traduce un documento HTML completo (el informe). */
+ function translateHtml(html) {
+ if (lang === "es") return html;
+ const doc = new DOMParser().parseFromString(html, "text/html");
+ doc.documentElement.lang = "en";
+ doc.title = tr(doc.title);
+ translateTree(doc.body);
+ return "<!doctype html>" + doc.documentElement.outerHTML;
+ }
+
+ async function setLang(l) {
+ localStorage.setItem("osint-lang", l);
+ try {
+ await fetch("/api/settings", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ lang: l }) });
+ } catch { /* el idioma de la IA se sincroniza la próxima vez */ }
+ location.reload();
+ }
+
+ return { lang, locale, load, tr, trKey, translateTree, translateHtml, start, setLang, missing };
+})();
diff --git a/web/index.html b/web/index.html
new file mode 100644
index 0000000..3c99e8f
--- /dev/null
+++ b/web/index.html
@@ -0,0 +1,203 @@
+<!doctype html>
+<html lang="es">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <title>OsintHunter</title>
+ <link rel="icon" href="favicon.svg" type="image/svg+xml">
+ <meta name="theme-color" content="#0a0806">
+ <link rel="stylesheet" href="vendor/leaflet.css">
+ <link rel="stylesheet" href="style.css">
+</head>
+<body>
+<header class="topbar">
+ <div class="brand"><img class="logo" src="favicon.svg" alt=""><span>OSINT</span><b>HUNTER</b></div>
+ <div class="case-bar">
+ <select id="caseSelect" title="Caso abierto"></select>
+ <button id="newCaseBtn" class="ghost">+ Nuevo caso</button>
+ <button id="renameCaseBtn" class="ghost icon" title="Renombrar caso">✎</button>
+ <button id="deleteCaseBtn" class="ghost icon danger" title="Eliminar caso">✕</button>
+ </div>
+ <div class="top-actions">
+ <button id="importBtn" class="ghost">Importar caso</button>
+ <input type="file" id="importFile" accept=".json" hidden>
+ <button id="langBtn" class="ghost" data-notr title="Idioma / Language"></button>
+ <button id="settingsBtn">Ajustes y claves API</button>
+ </div>
+</header>
+
+<main class="layout">
+ <aside class="left">
+ <form id="searchForm" class="card">
+ <div class="card-title">Nueva búsqueda</div>
+ <input id="searchInput" autocomplete="off" spellcheck="false"
+ placeholder="usuario, email, teléfono, nombre, RUT, patente, dominio, IP, URL…">
+ <div class="row">
+ <select id="typeSelect" title="Tipo de dato"></select>
+ <select id="depthSelect" title="Pivotado automático">
+ <option value="0">Sólo el objetivo</option>
+ <option value="1">+1 salto automático</option>
+ <option value="2">+2 saltos automáticos</option>
+ </select>
+ </div>
+ <button type="submit" class="primary">Investigar</button>
+ <label class="upload-btn">Analizar imagen (EXIF / GPS)
+ <input type="file" id="imageInput" accept="image/*" hidden>
+ </label>
+ </form>
+ <div class="card sources">
+ <div class="card-title">Fuentes consultadas <span id="jobStatus"></span></div>
+ <div id="sourcesList" class="sources-list"><div class="muted small">Aún no hay consultas.</div></div>
+ </div>
+ </aside>
+
+ <section class="center">
+ <div class="tabs">
+ <button data-tab="graph" class="tab active">Grafo</button>
+ <button data-tab="list" class="tab">Lista</button>
+ <button data-tab="map" class="tab">Mapa</button>
+ <button data-tab="timeline" class="tab">Cronología</button>
+ <button data-tab="notes" class="tab">Notas</button>
+ <div class="spacer"></div>
+ <label class="small muted check-inline" title="Oculta las cuentas cuya confianza es baja (posibles homónimos)">
+ <input type="checkbox" id="hideLowChk"> Ocultar confianza baja</label>
+ <button id="readBtn" class="ghost small hidden" title="Abre la página de cada cuenta de la que sólo se sabe que existe y saca nombre, foto y descripción para poder puntuarla">Leer perfiles</button>
+ <button id="aiBtn" class="ghost small" title="Compara las cuentas con IA para descartar homónimos">Verificar con IA</button>
+ <select id="cleanSel" class="small" title="Borrar varios nodos de una vez">
+ <option value="">Limpiar…</option>
+ <option value="low">Eliminar confianza baja</option>
+ <option value="discarded">Eliminar descartadas</option>
+ <option value="orphans">Eliminar nodos sueltos (sin conexiones)</option>
+ <option value="unreviewed">Eliminar cuentas sin revisar (deja confirmadas)</option>
+ </select>
+ <select id="groupSel" class="small" title="Ordenar un grafo grande: burbujas y nodos plegados">
+ <option value="">Agrupar…</option>
+ <option value="roots">Una burbuja por cada búsqueda</option>
+ <option value="platform">Burbujas de cuentas por usuario</option>
+ <option value="alias">Burbujas por familia de alias</option>
+ <option value="collapseBig">Plegar nodos con muchos resultados</option>
+ <option value="collapseGroups">Plegar todas las burbujas</option>
+ <option value="expand">Desplegar todo</option>
+ <option value="ungroup">Quitar todas las burbujas</option>
+ </select>
+ <button id="fitBtn" class="ghost small">Encuadrar</button>
+ <button id="layoutBtn" class="ghost small">Reordenar</button>
+ <button id="reportBtn" class="small" title="Informe del caso para imprimir o guardar como PDF">Informe</button>
+ <button id="pngBtn" class="ghost small">PNG</button>
+ <button id="exportBtn" class="ghost small">Exportar JSON</button>
+ </div>
+ <div id="graphView" class="view">
+ <div id="cy"></div>
+ <div id="selBar" class="selbar hidden">
+ <span id="selCount"></span>
+ <button id="selGroup" class="small" title="Mete los nodos seleccionados en una burbuja con nombre">Agrupar en burbuja</button>
+ <button id="selDelete" class="small danger-solid">Eliminar</button>
+ <button id="selClear" class="ghost small">Quitar selección</button>
+ </div>
+ <div id="selHint" class="selhint muted small">Ctrl+clic suma nodos · Shift+arrastrar selecciona un área · Supr borra la selección · doble clic en una burbuja la pliega</div>
+ <div id="legend" class="legend"></div>
+ <div id="emptyState" class="empty">
+ <img class="empty-logo" src="favicon.svg" alt="">
+ <h2>Empieza la cacería</h2>
+ <p>Escribe un usuario, email, teléfono, nombre completo, RUT, patente, dominio, IP, URL, hash o cartera de criptomonedas.
+ El tipo se detecta solo.</p>
+ <p class="muted">Haz clic en un nodo para ver sus datos, doble clic para investigarlo, y pasa el ratón por encima para ver sus conexiones.</p>
+ </div>
+ </div>
+ <div id="listView" class="view hidden">
+ <div class="list-tools"><input id="listFilter" placeholder="Filtrar entidades… (ej. «steam», «cuenta», «sherlock»)">
+ <button id="listDelete" class="small danger-solid" disabled>Eliminar marcadas</button></div>
+ <div class="table-wrap"><table id="entityTable"></table></div>
+ </div>
+ <div id="mapView" class="view hidden">
+ <div id="map"></div>
+ <div id="mapEmpty" class="empty"><p class="muted">Aún no hay ubicaciones con coordenadas en este caso.</p></div>
+ </div>
+ <div id="timelineView" class="view hidden">
+ <div id="timeline" class="timeline"></div>
+ </div>
+ <div id="notesView" class="view hidden">
+ <textarea id="notesArea" placeholder="Notas del caso (se guardan solas)…"></textarea>
+ </div>
+ </section>
+
+ <aside class="right" id="details">
+ <div class="placeholder muted">Selecciona un nodo para ver sus datos.</div>
+ </aside>
+</main>
+
+<dialog id="settingsDlg">
+ <form method="dialog" id="settingsForm">
+ <h2>Ajustes</h2>
+ <div class="settings-grid">
+ <label>País por defecto para teléfonos (código ISO, ej. AR, ES, MX)
+ <input name="default_region" maxlength="2" style="text-transform:uppercase">
+ </label>
+ <label>Tiempo máximo por web en el barrido de usuario (s)
+ <input name="username_timeout" type="number" min="5" max="60">
+ </label>
+ <label>Máximo de entidades en el pivotado automático
+ <input name="max_pivot_entities" type="number" min="1" max="200">
+ </label>
+ <label class="check"><input type="checkbox" name="sherlock_db"> Usar la base ampliada de Sherlock (400+ sitios)</label>
+ <label class="check"><input type="checkbox" name="include_nsfw"> Incluir sitios para adultos en el barrido</label>
+ </div>
+ <h3>Inteligencia artificial</h3>
+ <p class="muted small">Opcional, para «Verificar con IA». Funciona con cualquier proveedor compatible con OpenAI.
+ Ollama corre en tu PC sin clave; Groq y Gemini tienen capa gratuita (pon su clave en «Clave del proveedor de IA», abajo).</p>
+ <div class="settings-grid">
+ <label>Proveedor
+ <select id="aiPreset">
+ <option value="">Personalizado</option>
+ <option value="http://localhost:11434/v1|llama3.1">Ollama (local, gratis)</option>
+ <option value="https://api.groq.com/openai/v1|llama-3.3-70b-versatile">Groq (gratis con clave)</option>
+ <option value="https://generativelanguage.googleapis.com/v1beta/openai|gemini-2.0-flash">Google Gemini (gratis con clave)</option>
+ <option value="https://openrouter.ai/api/v1|meta-llama/llama-3.3-70b-instruct:free">OpenRouter</option>
+ <option value="https://api.openai.com/v1|gpt-4o-mini">OpenAI</option>
+ </select>
+ </label>
+ <div class="row">
+ <label>URL base <input name="ai_base_url" placeholder="http://localhost:11434/v1"></label>
+ <label>Modelo <input name="ai_model" placeholder="llama3.1"></label>
+ </div>
+ </div>
+ <h3>Claves API</h3>
+ <p class="muted small">Todas opcionales. Se guardan sólo en tu PC (carpeta <code>data</code>). Sin clave, esa fuente se omite y se indica en «Fuentes consultadas».</p>
+ <div id="keysList" class="keys-list"></div>
+ <div class="dlg-actions">
+ <button value="cancel" class="ghost">Cancelar</button>
+ <button id="saveSettingsBtn" value="save" class="primary">Guardar</button>
+ </div>
+ </form>
+</dialog>
+
+<dialog id="pivotDlg">
+ <form method="dialog">
+ <h2 id="pivotTitle">Investigar</h2>
+ <div id="pivotModules" class="pivot-modules"></div>
+ <label>Pivotado automático
+ <select id="pivotDepth">
+ <option value="0">Sólo esta entidad</option>
+ <option value="1">+1 salto automático</option>
+ <option value="2">+2 saltos automáticos</option>
+ </select>
+ </label>
+ <div class="dlg-actions">
+ <button value="cancel" class="ghost">Cancelar</button>
+ <button id="pivotRunBtn" value="run" class="primary">Investigar</button>
+ </div>
+ </form>
+</dialog>
+
+<div id="toast" class="toast"></div>
+
+<script src="vendor/cytoscape.min.js"></script>
+<script src="vendor/layout-base.js"></script>
+<script src="vendor/cose-base.js"></script>
+<script src="vendor/cytoscape-fcose.js"></script>
+<script src="vendor/leaflet.js"></script>
+<script src="i18n.js"></script>
+<script src="i18n-en.js"></script>
+<script src="app.js"></script>
+</body>
+</html>
diff --git a/web/style.css b/web/style.css
new file mode 100644
index 0000000..72a1e45
--- /dev/null
+++ b/web/style.css
@@ -0,0 +1,244 @@
+:root {
+ --bg: #0a0806;
+ --panel: #110e0b;
+ --panel2: #1a1510;
+ --border: #2e2419;
+ --border2: #4a3420;
+ --text: #efe6dc;
+ --muted: #94857a;
+ --accent: #ff7a1a;
+ --accent-hi: #ffa04d;
+ --accent2: #c4520a;
+ --glow: rgba(255, 122, 26, .35);
+ --ok: #5cc26a;
+ --warn: #ffc94a;
+ --err: #ff5a4f;
+ --display: "Bahnschrift", "Segoe UI Semibold", "Segoe UI", system-ui, sans-serif;
+ font-family: "Segoe UI", system-ui, -apple-system, sans-serif;
+ font-size: 14px;
+ color-scheme: dark;
+ accent-color: var(--accent);
+}
+* { box-sizing: border-box; }
+html, body { margin: 0; height: 100%; background: var(--bg); color: var(--text); }
+::selection { background: var(--accent); color: #140a02; }
+button, input, select, textarea { font: inherit; color: inherit; }
+a { color: var(--accent-hi); text-decoration: none; }
+a:hover { color: var(--accent); text-decoration: underline; }
+code { background: var(--panel2); padding: 1px 5px; border-radius: 4px; color: var(--accent-hi); }
+.muted { color: var(--muted); }
+.small { font-size: 12px; }
+.hidden { display: none !important; }
+
+button {
+ background: var(--accent2); color: #fff4ea; border: 1px solid transparent; border-radius: 6px; padding: 6px 12px; cursor: pointer;
+ transition: background .15s, border-color .15s, box-shadow .15s, color .15s;
+}
+button:hover { filter: brightness(1.12); }
+button.primary {
+ background: linear-gradient(180deg, var(--accent-hi), var(--accent) 55%, #e8620a); color: #170b02; font-weight: 700;
+ letter-spacing: .3px; box-shadow: 0 0 0 1px rgba(255, 160, 77, .35), 0 4px 16px -6px var(--glow);
+}
+button.primary:hover { filter: none; box-shadow: 0 0 0 1px var(--accent-hi), 0 4px 22px -4px var(--glow); }
+button.ghost { background: transparent; border-color: var(--border); color: var(--text); }
+button.ghost:hover { background: var(--panel2); border-color: var(--border2); color: var(--accent-hi); filter: none; }
+button.icon { padding: 6px 9px; }
+button.danger:hover { border-color: var(--err); color: var(--err); }
+button.small { padding: 3px 9px; font-size: 12px; }
+button:disabled { opacity: .45; cursor: not-allowed; }
+input, select, textarea {
+ background: var(--bg); border: 1px solid var(--border); border-radius: 6px; padding: 7px 9px; outline: none;
+}
+input:focus, select:focus, textarea:focus { border-color: var(--accent); box-shadow: 0 0 0 3px rgba(255, 122, 26, .15); }
+input::placeholder, textarea::placeholder { color: #6f6258; }
+
+.topbar {
+ height: 52px; display: flex; align-items: center; gap: 18px; padding: 0 14px; position: relative;
+ background: linear-gradient(180deg, #17110b, var(--panel)); border-bottom: 1px solid var(--border);
+}
+.topbar::after {
+ content: ""; position: absolute; left: 0; right: 0; bottom: -1px; height: 1px;
+ background: linear-gradient(90deg, transparent, var(--accent) 20%, var(--accent) 50%, transparent 85%); opacity: .7;
+}
+.brand { display: flex; align-items: center; gap: 2px; font-family: var(--display); font-size: 19px; letter-spacing: 2px; white-space: nowrap; }
+.brand span { font-weight: 400; color: var(--text); }
+.brand b { font-weight: 700; color: var(--accent); text-shadow: 0 0 14px var(--glow); }
+.logo { width: 28px; height: 28px; margin-right: 8px; filter: drop-shadow(0 0 6px var(--glow)); }
+.case-bar { display: flex; gap: 6px; align-items: center; flex: 1; }
+.case-bar select { min-width: 240px; max-width: 380px; }
+.top-actions { display: flex; gap: 8px; }
+
+.layout { display: grid; grid-template-columns: minmax(250px, 320px) minmax(0, 1fr) minmax(280px, 380px); height: calc(100% - 52px); overflow: hidden; }
+.left, .right { background: var(--panel); overflow: auto; }
+.left { border-right: 1px solid var(--border); display: flex; flex-direction: column; gap: 10px; padding: 10px; }
+.right { border-left: 1px solid var(--border); padding: 14px; }
+.card { background: var(--panel2); border: 1px solid var(--border); border-top: 2px solid var(--accent2); border-radius: 8px; padding: 10px; display: flex; flex-direction: column; gap: 8px; }
+.card-title { font-family: var(--display); font-weight: 600; font-size: 13px; text-transform: uppercase; letter-spacing: 1.5px; color: var(--accent-hi); display: flex; justify-content: space-between; }
+.row { display: flex; gap: 6px; }
+.row > * { flex: 1; min-width: 0; }
+.upload-btn { text-align: center; border: 1px dashed var(--border); border-radius: 6px; padding: 6px; cursor: pointer; color: var(--muted); font-size: 13px; }
+.upload-btn:hover { border-color: var(--accent); color: var(--accent-hi); }
+
+.sources { flex: 1; min-height: 0; }
+.sources-list { overflow: auto; display: flex; flex-direction: column; gap: 10px; }
+.src-group-title { font-size: 12px; font-weight: 600; cursor: pointer; margin-bottom: 3px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.src-group-title:hover { color: var(--accent); }
+.src { display: grid; grid-template-columns: 16px 1fr; gap: 0 6px; font-size: 12px; padding: 2px 0; }
+.src .msg { grid-column: 2; color: var(--muted); font-size: 11px; word-break: break-word; }
+.st-ok { color: var(--ok); }
+.st-empty { color: var(--muted); }
+.st-skipped { color: var(--warn); }
+.st-error { color: var(--err); }
+.st-running { color: var(--accent); animation: pulse 1s infinite; }
+@keyframes pulse { 50% { opacity: .3; } }
+
+.center { display: flex; flex-direction: column; min-width: 0; overflow: hidden; }
+.tabs { display: flex; gap: 4px; align-items: center; padding: 6px 10px; background: var(--panel); border-bottom: 1px solid var(--border); flex-wrap: wrap; }
+.tabs > * { flex: none; white-space: nowrap; }
+.tabs > .spacer { flex: 1; }
+.tab { background: transparent; border-radius: 6px 6px 0 0; color: var(--muted); font-family: var(--display); letter-spacing: .5px; border-bottom: 2px solid transparent; }
+.tab:hover { color: var(--text); filter: none; }
+.tab.active { color: var(--accent-hi); border-bottom-color: var(--accent); background: linear-gradient(0deg, rgba(255, 122, 26, .1), transparent); }
+.spacer { flex: 1; }
+.view { flex: 1; position: relative; min-height: 0; overflow: hidden; }
+#graphView {
+ background:
+ radial-gradient(ellipse at 50% 45%, rgba(255, 122, 26, .07), transparent 60%),
+ linear-gradient(rgba(255, 140, 50, .035) 1px, transparent 1px) 0 0 / 40px 40px,
+ linear-gradient(90deg, rgba(255, 140, 50, .035) 1px, transparent 1px) 0 0 / 40px 40px,
+ var(--bg);
+}
+#cy { position: absolute; inset: 0; }
+.empty { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; text-align: center; padding: 40px; pointer-events: none; }
+.empty h2 { margin: 0 0 8px; font-family: var(--display); letter-spacing: 1px; color: var(--accent-hi); }
+.empty-logo { width: 88px; height: 88px; margin-bottom: 14px; opacity: .9; filter: drop-shadow(0 0 18px var(--glow)); animation: scan 4s ease-in-out infinite; }
+@keyframes scan { 50% { transform: rotate(90deg) scale(.94); opacity: .65; } }
+.empty p { max-width: 520px; margin: 4px 0; }
+.legend { position: absolute; left: 10px; bottom: 10px; display: flex; flex-wrap: wrap; gap: 5px; max-width: 70%; z-index: 2; }
+.chip { display: inline-flex; align-items: center; gap: 5px; background: rgba(20,15,10,.92); border: 1px solid var(--border); border-radius: 12px; padding: 2px 9px; font-size: 11px; cursor: pointer; user-select: none; }
+.chip.off { opacity: .35; }
+.dot { width: 9px; height: 9px; border-radius: 50%; display: inline-block; flex: none; }
+
+.list-tools { padding: 8px 10px; }
+.list-tools input { width: 100%; }
+.table-wrap { position: absolute; inset: 50px 0 0 0; overflow: auto; }
+table { width: 100%; border-collapse: collapse; font-size: 13px; }
+th, td { text-align: left; padding: 6px 10px; border-bottom: 1px solid var(--border); vertical-align: top; }
+th { position: sticky; top: 0; background: var(--panel); color: var(--accent-hi); font-weight: 600; font-family: var(--display); letter-spacing: .5px; }
+tr:hover td { background: var(--panel2); cursor: pointer; }
+.check-inline { display: inline-flex; align-items: center; gap: 4px; margin-right: 6px; cursor: pointer; white-space: nowrap; }
+.check-inline input { margin: 0; }
+#map { position: absolute; inset: 0; background: var(--bg); }
+#mapEmpty { z-index: 500; }
+.dark-tiles { filter: invert(1) hue-rotate(180deg) grayscale(.7) sepia(.5) brightness(.78) contrast(1.05); }
+.leaflet-popup-content-wrapper, .leaflet-popup-tip { background: var(--panel2); color: var(--text); }
+.leaflet-popup-content { font-size: 13px; }
+.leaflet-container a.leaflet-popup-close-button { color: var(--muted); }
+.map-pop b { cursor: pointer; color: var(--accent); }
+.map-pop ul { margin: 4px 0 0; padding-left: 16px; max-height: 160px; overflow: auto; }
+.map-pop li { cursor: pointer; }
+.map-pop li:hover { color: var(--accent); }
+.timeline { position: absolute; inset: 0; overflow: auto; padding: 16px 20px 30px; }
+.tl-year { font-family: var(--display); font-size: 20px; font-weight: 700; letter-spacing: 1px; color: var(--accent); margin: 18px 0 6px; padding-bottom: 4px; border-bottom: 1px solid var(--border); text-shadow: 0 0 12px var(--glow); }
+.tl-year:first-child { margin-top: 0; }
+.tl-item { display: grid; grid-template-columns: 110px 14px 1fr; gap: 10px; align-items: start; padding: 5px 0; cursor: pointer; border-radius: 6px; }
+.tl-item:hover { background: var(--panel2); }
+.tl-date { color: var(--muted); font-size: 12px; text-align: right; padding-top: 1px; }
+.tl-item .dot { margin-top: 4px; width: 11px; height: 11px; }
+.tl-what { font-size: 13px; }
+.tl-what .muted { font-size: 12px; }
+.conf { display: inline-block; border-radius: 4px; padding: 1px 7px; font-size: 11px; font-weight: 600; color: #0b0f14; margin-left: 4px; }
+.conf.Alta { background: var(--ok); }
+.conf.Media { background: var(--warn); }
+.conf.Baja { background: var(--err); }
+.selbar { position: absolute; top: 10px; left: 50%; transform: translateX(-50%); z-index: 5; display: flex; gap: 8px; align-items: center;
+ background: var(--panel); border: 1px solid var(--accent); border-radius: 8px; padding: 6px 10px; box-shadow: 0 6px 24px -6px #000, 0 0 18px -8px var(--glow); font-size: 13px; }
+.selbar #selCount { font-weight: 700; color: var(--accent-hi); }
+.selhint { position: absolute; top: 8px; right: 10px; z-index: 4; pointer-events: none; opacity: .7; }
+button.danger-solid { background: #b3261e; border-color: #e0463d; color: #fff; }
+button.danger-solid:hover { background: #d0362c; }
+button.danger-solid:disabled { opacity: .4; cursor: default; }
+select#cleanSel, select#groupSel { width: 96px; flex: 0 0 auto; padding: 3px 8px; font-size: 12px; }
+.list-tools { display: flex; gap: 8px; align-items: center; }
+.list-tools input { flex: 1; }
+#entityTable td:first-child, #entityTable th:first-child { width: 26px; }
+.link-box { margin-top: 10px; }
+.link-box label { display: flex; flex-direction: column; gap: 3px; margin-bottom: 6px; color: var(--muted); }
+.link-box select, .link-box input { width: 100%; }
+.conn .unlink { margin-left: auto; padding: 0 6px; line-height: 16px; }
+.verdict { border: 1px solid var(--border); border-radius: 8px; padding: 8px; background: var(--panel2); }
+.verdict.confirmada { border-color: #3ddc84; box-shadow: inset 3px 0 0 #3ddc84; }
+.verdict.descartada { border-color: #5a5048; box-shadow: inset 3px 0 0 #5a5048; }
+.verdict-btns { display: flex; gap: 6px; margin-bottom: 6px; flex-wrap: wrap; }
+.verdict-btns button.on { background: var(--panel); border-color: var(--border2); color: var(--text); }
+.verdict-btns button.on.yes { background: #1f6b43; border-color: #3ddc84; color: #e8fff1; }
+.verdict-btns button.on.no { background: #3a2f28; border-color: #8a7f75; color: #e6dace; }
+.signals { margin: 0; padding-left: 16px; font-size: 12px; color: var(--muted); }
+.ai-box { background: var(--panel2); border: 1px solid var(--border); border-radius: 8px; padding: 8px 10px; font-size: 13px; }
+#notesArea { position: absolute; inset: 10px; width: calc(100% - 20px); height: calc(100% - 20px); resize: none; line-height: 1.5; }
+
+.badge { display: inline-block; border-radius: 4px; padding: 1px 7px; font-size: 11px; font-weight: 600; color: #0b0f14; }
+.det-head { display: flex; gap: 12px; align-items: flex-start; margin-bottom: 10px; }
+.det-head img { width: 64px; height: 64px; border-radius: 8px; object-fit: cover; background: var(--panel2); flex: none; border: 1px solid var(--border2); box-shadow: 0 0 14px -4px var(--glow); }
+.det-title { font-family: var(--display); font-size: 17px; font-weight: 600; word-break: break-all; margin-top: 4px; }
+.det-value { font-size: 12px; color: var(--muted); word-break: break-all; }
+.det-actions { display: flex; gap: 6px; flex-wrap: wrap; margin: 8px 0 12px; }
+.section { margin-top: 14px; }
+.section h4 { margin: 0 0 6px; padding-left: 8px; border-left: 2px solid var(--accent); font-family: var(--display); font-size: 12px; text-transform: uppercase; color: var(--accent-hi); letter-spacing: 1.2px; }
+.attrs { width: 100%; font-size: 13px; }
+.attrs td { padding: 4px 6px; border-bottom: 1px solid var(--border); word-break: break-word; }
+.attrs td:first-child { color: var(--muted); width: 38%; }
+.attrs tr:hover td { background: transparent; cursor: default; }
+.attrs ul { margin: 0; padding-left: 16px; }
+.linklist { display: flex; flex-direction: column; gap: 4px; font-size: 13px; }
+.fill-link { margin-top: 8px; font-size: 13px; }
+.fill-vals { display: flex; flex-wrap: wrap; gap: 4px; margin-top: 3px; }
+button.fill-val { font-size: 11px; padding: 2px 7px; border-radius: 10px; background: var(--panel2, #1d1712); border: 1px solid var(--border); color: var(--muted); cursor: copy; }
+button.fill-val b { color: var(--text, #f3e9df); font-family: ui-monospace, Consolas, monospace; }
+button.fill-val:hover { border-color: var(--accent); }
+.deep-box { border: 1px dashed var(--accent); border-radius: 8px; padding: 8px 10px; background: rgba(255, 122, 26, .05); }
+.deep-item { display: flex; flex-wrap: wrap; gap: 4px 8px; align-items: baseline; margin-top: 4px; }
+.deep-item button { flex: none; }
+.deep-item .muted { flex: 1 1 160px; }
+.manual-check { display: flex; justify-content: space-between; align-items: center; gap: 6px; padding: 3px 0; border-bottom: 1px solid var(--border); font-size: 13px; }
+.variant { padding: 6px 0; border-bottom: 1px solid var(--border); font-size: 13px; }
+.variant:last-of-type { border-bottom: 0; }
+.variant .linklist { margin: 3px 0; }
+.variant-btns { display: flex; gap: 6px; justify-content: flex-end; }
+.pivot-deep { margin: 10px 0 4px; padding-top: 8px; border-top: 1px solid var(--border); }
+.cand { display: flex; justify-content: space-between; align-items: center; padding: 3px 0; border-bottom: 1px solid var(--border); font-size: 13px; }
+.conn { font-size: 13px; padding: 3px 0; cursor: pointer; display: flex; gap: 6px; align-items: center; }
+.conn:hover { color: var(--accent); }
+.conn .rel { color: var(--muted); font-size: 11px; }
+details summary { cursor: pointer; color: var(--accent); font-size: 12px; }
+.dork-group { border: 1px solid var(--border); border-radius: 6px; padding: 5px 8px; margin-bottom: 5px; background: var(--panel2); }
+.dork-group summary { font-size: 13px; font-weight: 600; color: var(--text); }
+.dork-group[open] summary { color: var(--accent-hi); margin-bottom: 5px; }
+.web-hit { padding: 6px 0; border-bottom: 1px solid var(--border); font-size: 13px; overflow-wrap: anywhere; }
+.web-hit:last-child { border-bottom: 0; }
+.web-hit .tag { display: inline-block; font-size: 10px; font-weight: 700; padding: 1px 6px; border-radius: 4px; background: var(--accent); color: #0a0806; vertical-align: 1px; }
+.web-hit-foot { display: flex; justify-content: space-between; align-items: center; margin-top: 3px; gap: 6px; }
+
+dialog { background: var(--panel); color: var(--text); border: 1px solid var(--border2); border-top: 3px solid var(--accent); border-radius: 10px; width: min(680px, 94vw); max-height: 88vh; padding: 20px; box-shadow: 0 20px 60px -10px #000, 0 0 40px -20px var(--glow); }
+dialog::backdrop { background: rgba(5,3,1,.72); backdrop-filter: blur(2px); }
+dialog h2 { margin: 0 0 12px; font-family: var(--display); letter-spacing: 1px; color: var(--accent-hi); }
+dialog h3 { margin: 18px 0 4px; font-family: var(--display); letter-spacing: .5px; color: var(--accent-hi); }
+.settings-grid { display: flex; flex-direction: column; gap: 10px; }
+.settings-grid label { display: flex; flex-direction: column; gap: 4px; font-size: 13px; }
+.settings-grid label.check { flex-direction: row; align-items: center; gap: 8px; }
+.keys-list { display: flex; flex-direction: column; gap: 8px; margin-top: 8px; }
+.key-row { display: grid; grid-template-columns: 1fr 220px auto; gap: 8px; align-items: center; font-size: 13px; }
+.key-row .lbl small { display: block; }
+.dlg-actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 18px; }
+.pivot-modules { display: flex; flex-direction: column; gap: 6px; margin-bottom: 12px; max-height: 50vh; overflow: auto; }
+.pivot-modules label { display: grid; grid-template-columns: 20px 1fr; gap: 6px; font-size: 13px; padding: 4px 0; border-bottom: 1px solid var(--border); }
+.pivot-modules label small { grid-column: 2; color: var(--muted); }
+
+.toast { position: fixed; bottom: 18px; left: 50%; transform: translateX(-50%) translateY(80px); background: var(--panel2); border: 1px solid var(--border2); border-left: 3px solid var(--accent); box-shadow: 0 8px 30px -8px #000; padding: 10px 16px; border-radius: 8px; transition: transform .25s; z-index: 50; max-width: 80vw; }
+.toast.show { transform: translateX(-50%) translateY(0); }
+.toast.err { border-color: var(--err); }
+
+::-webkit-scrollbar { width: 10px; height: 10px; }
+::-webkit-scrollbar-thumb { background: #3a2c1f; border-radius: 6px; border: 2px solid var(--panel); }
+::-webkit-scrollbar-thumb:hover { background: var(--accent2); }
+::-webkit-scrollbar-track { background: transparent; }
diff --git a/web/vendor/cose-base.js b/web/vendor/cose-base.js
new file mode 100644
index 0000000..49ccc66
--- /dev/null
+++ b/web/vendor/cose-base.js
@@ -0,0 +1,3214 @@
+(function webpackUniversalModuleDefinition(root, factory) {
+ if(typeof exports === 'object' && typeof module === 'object')
+ module.exports = factory(require("layout-base"));
+ else if(typeof define === 'function' && define.amd)
+ define(["layout-base"], factory);
+ else if(typeof exports === 'object')
+ exports["coseBase"] = factory(require("layout-base"));
+ else
+ root["coseBase"] = factory(root["layoutBase"]);
+})(this, function(__WEBPACK_EXTERNAL_MODULE__551__) {
+return /******/ (() => { // webpackBootstrap
+/******/ "use strict";
+/******/ var __webpack_modules__ = ({
+
+/***/ 45:
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+
+
+var coseBase = {};
+
+coseBase.layoutBase = __webpack_require__(551);
+coseBase.CoSEConstants = __webpack_require__(806);
+coseBase.CoSEEdge = __webpack_require__(767);
+coseBase.CoSEGraph = __webpack_require__(880);
+coseBase.CoSEGraphManager = __webpack_require__(578);
+coseBase.CoSELayout = __webpack_require__(765);
+coseBase.CoSENode = __webpack_require__(991);
+coseBase.ConstraintHandler = __webpack_require__(902);
+
+module.exports = coseBase;
+
+/***/ }),
+
+/***/ 806:
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+
+
+var FDLayoutConstants = __webpack_require__(551).FDLayoutConstants;
+
+function CoSEConstants() {}
+
+//CoSEConstants inherits static props in FDLayoutConstants
+for (var prop in FDLayoutConstants) {
+ CoSEConstants[prop] = FDLayoutConstants[prop];
+}
+
+CoSEConstants.DEFAULT_USE_MULTI_LEVEL_SCALING = false;
+CoSEConstants.DEFAULT_RADIAL_SEPARATION = FDLayoutConstants.DEFAULT_EDGE_LENGTH;
+CoSEConstants.DEFAULT_COMPONENT_SEPERATION = 60;
+CoSEConstants.TILE = true;
+CoSEConstants.TILING_PADDING_VERTICAL = 10;
+CoSEConstants.TILING_PADDING_HORIZONTAL = 10;
+CoSEConstants.TRANSFORM_ON_CONSTRAINT_HANDLING = true;
+CoSEConstants.ENFORCE_CONSTRAINTS = true;
+CoSEConstants.APPLY_LAYOUT = true;
+CoSEConstants.RELAX_MOVEMENT_ON_CONSTRAINTS = true;
+CoSEConstants.TREE_REDUCTION_ON_INCREMENTAL = true; // this should be set to false if there will be a constraint
+// This constant is for differentiating whether actual layout algorithm that uses cose-base wants to apply only incremental layout or
+// an incremental layout on top of a randomized layout. If it is only incremental layout, then this constant should be true.
+CoSEConstants.PURE_INCREMENTAL = CoSEConstants.DEFAULT_INCREMENTAL;
+
+module.exports = CoSEConstants;
+
+/***/ }),
+
+/***/ 767:
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+
+
+var FDLayoutEdge = __webpack_require__(551).FDLayoutEdge;
+
+function CoSEEdge(source, target, vEdge) {
+ FDLayoutEdge.call(this, source, target, vEdge);
+}
+
+CoSEEdge.prototype = Object.create(FDLayoutEdge.prototype);
+for (var prop in FDLayoutEdge) {
+ CoSEEdge[prop] = FDLayoutEdge[prop];
+}
+
+module.exports = CoSEEdge;
+
+/***/ }),
+
+/***/ 880:
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+
+
+var LGraph = __webpack_require__(551).LGraph;
+
+function CoSEGraph(parent, graphMgr, vGraph) {
+ LGraph.call(this, parent, graphMgr, vGraph);
+}
+
+CoSEGraph.prototype = Object.create(LGraph.prototype);
+for (var prop in LGraph) {
+ CoSEGraph[prop] = LGraph[prop];
+}
+
+module.exports = CoSEGraph;
+
+/***/ }),
+
+/***/ 578:
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+
+
+var LGraphManager = __webpack_require__(551).LGraphManager;
+
+function CoSEGraphManager(layout) {
+ LGraphManager.call(this, layout);
+}
+
+CoSEGraphManager.prototype = Object.create(LGraphManager.prototype);
+for (var prop in LGraphManager) {
+ CoSEGraphManager[prop] = LGraphManager[prop];
+}
+
+module.exports = CoSEGraphManager;
+
+/***/ }),
+
+/***/ 765:
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+
+
+var FDLayout = __webpack_require__(551).FDLayout;
+var CoSEGraphManager = __webpack_require__(578);
+var CoSEGraph = __webpack_require__(880);
+var CoSENode = __webpack_require__(991);
+var CoSEEdge = __webpack_require__(767);
+var CoSEConstants = __webpack_require__(806);
+var ConstraintHandler = __webpack_require__(902);
+var FDLayoutConstants = __webpack_require__(551).FDLayoutConstants;
+var LayoutConstants = __webpack_require__(551).LayoutConstants;
+var Point = __webpack_require__(551).Point;
+var PointD = __webpack_require__(551).PointD;
+var DimensionD = __webpack_require__(551).DimensionD;
+var Layout = __webpack_require__(551).Layout;
+var Integer = __webpack_require__(551).Integer;
+var IGeometry = __webpack_require__(551).IGeometry;
+var LGraph = __webpack_require__(551).LGraph;
+var Transform = __webpack_require__(551).Transform;
+var LinkedList = __webpack_require__(551).LinkedList;
+
+function CoSELayout() {
+ FDLayout.call(this);
+
+ this.toBeTiled = {}; // Memorize if a node is to be tiled or is tiled
+ this.constraints = {}; // keep layout constraints
+}
+
+CoSELayout.prototype = Object.create(FDLayout.prototype);
+
+for (var prop in FDLayout) {
+ CoSELayout[prop] = FDLayout[prop];
+}
+
+CoSELayout.prototype.newGraphManager = function () {
+ var gm = new CoSEGraphManager(this);
+ this.graphManager = gm;
+ return gm;
+};
+
+CoSELayout.prototype.newGraph = function (vGraph) {
+ return new CoSEGraph(null, this.graphManager, vGraph);
+};
+
+CoSELayout.prototype.newNode = function (vNode) {
+ return new CoSENode(this.graphManager, vNode);
+};
+
+CoSELayout.prototype.newEdge = function (vEdge) {
+ return new CoSEEdge(null, null, vEdge);
+};
+
+CoSELayout.prototype.initParameters = function () {
+ FDLayout.prototype.initParameters.call(this, arguments);
+ if (!this.isSubLayout) {
+ if (CoSEConstants.DEFAULT_EDGE_LENGTH < 10) {
+ this.idealEdgeLength = 10;
+ } else {
+ this.idealEdgeLength = CoSEConstants.DEFAULT_EDGE_LENGTH;
+ }
+
+ this.useSmartIdealEdgeLengthCalculation = CoSEConstants.DEFAULT_USE_SMART_IDEAL_EDGE_LENGTH_CALCULATION;
+ this.gravityConstant = FDLayoutConstants.DEFAULT_GRAVITY_STRENGTH;
+ this.compoundGravityConstant = FDLayoutConstants.DEFAULT_COMPOUND_GRAVITY_STRENGTH;
+ this.gravityRangeFactor = FDLayoutConstants.DEFAULT_GRAVITY_RANGE_FACTOR;
+ this.compoundGravityRangeFactor = FDLayoutConstants.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR;
+
+ // variables for tree reduction support
+ this.prunedNodesAll = [];
+ this.growTreeIterations = 0;
+ this.afterGrowthIterations = 0;
+ this.isTreeGrowing = false;
+ this.isGrowthFinished = false;
+ }
+};
+
+// This method is used to set CoSE related parameters used by spring embedder.
+CoSELayout.prototype.initSpringEmbedder = function () {
+ FDLayout.prototype.initSpringEmbedder.call(this);
+
+ // variables for cooling
+ this.coolingCycle = 0;
+ this.maxCoolingCycle = this.maxIterations / FDLayoutConstants.CONVERGENCE_CHECK_PERIOD;
+ this.finalTemperature = 0.04;
+ this.coolingAdjuster = 1;
+};
+
+CoSELayout.prototype.layout = function () {
+ var createBendsAsNeeded = LayoutConstants.DEFAULT_CREATE_BENDS_AS_NEEDED;
+ if (createBendsAsNeeded) {
+ this.createBendpoints();
+ this.graphManager.resetAllEdges();
+ }
+
+ this.level = 0;
+ return this.classicLayout();
+};
+
+CoSELayout.prototype.classicLayout = function () {
+ this.nodesWithGravity = this.calculateNodesToApplyGravitationTo();
+ this.graphManager.setAllNodesToApplyGravitation(this.nodesWithGravity);
+ this.calcNoOfChildrenForAllNodes();
+ this.graphManager.calcLowestCommonAncestors();
+ this.graphManager.calcInclusionTreeDepths();
+ this.graphManager.getRoot().calcEstimatedSize();
+ this.calcIdealEdgeLengths();
+
+ if (!this.incremental) {
+ var forest = this.getFlatForest();
+
+ // The graph associated with this layout is flat and a forest
+ if (forest.length > 0) {
+ this.positionNodesRadially(forest);
+ }
+ // The graph associated with this layout is not flat or a forest
+ else {
+ // Reduce the trees when incremental mode is not enabled and graph is not a forest
+ this.reduceTrees();
+ // Update nodes that gravity will be applied
+ this.graphManager.resetAllNodesToApplyGravitation();
+ var allNodes = new Set(this.getAllNodes());
+ var intersection = this.nodesWithGravity.filter(function (x) {
+ return allNodes.has(x);
+ });
+ this.graphManager.setAllNodesToApplyGravitation(intersection);
+
+ this.positionNodesRandomly();
+ }
+ } else {
+ if (CoSEConstants.TREE_REDUCTION_ON_INCREMENTAL) {
+ // Reduce the trees in incremental mode if only this constant is set to true
+ this.reduceTrees();
+ // Update nodes that gravity will be applied
+ this.graphManager.resetAllNodesToApplyGravitation();
+ var allNodes = new Set(this.getAllNodes());
+ var intersection = this.nodesWithGravity.filter(function (x) {
+ return allNodes.has(x);
+ });
+ this.graphManager.setAllNodesToApplyGravitation(intersection);
+ }
+ }
+
+ if (Object.keys(this.constraints).length > 0) {
+ ConstraintHandler.handleConstraints(this);
+ this.initConstraintVariables();
+ }
+
+ this.initSpringEmbedder();
+ if (CoSEConstants.APPLY_LAYOUT) {
+ this.runSpringEmbedder();
+ }
+
+ return true;
+};
+
+CoSELayout.prototype.tick = function () {
+ this.totalIterations++;
+
+ if (this.totalIterations === this.maxIterations && !this.isTreeGrowing && !this.isGrowthFinished) {
+ if (this.prunedNodesAll.length > 0) {
+ this.isTreeGrowing = true;
+ } else {
+ return true;
+ }
+ }
+
+ if (this.totalIterations % FDLayoutConstants.CONVERGENCE_CHECK_PERIOD == 0 && !this.isTreeGrowing && !this.isGrowthFinished) {
+ if (this.isConverged()) {
+ if (this.prunedNodesAll.length > 0) {
+ this.isTreeGrowing = true;
+ } else {
+ return true;
+ }
+ }
+
+ this.coolingCycle++;
+
+ if (this.layoutQuality == 0) {
+ // quality - "draft"
+ this.coolingAdjuster = this.coolingCycle;
+ } else if (this.layoutQuality == 1) {
+ // quality - "default"
+ this.coolingAdjuster = this.coolingCycle / 3;
+ }
+
+ // cooling schedule is based on http://www.btluke.com/simanf1.html -> cooling schedule 3
+ this.coolingFactor = Math.max(this.initialCoolingFactor - Math.pow(this.coolingCycle, Math.log(100 * (this.initialCoolingFactor - this.finalTemperature)) / Math.log(this.maxCoolingCycle)) / 100 * this.coolingAdjuster, this.finalTemperature);
+ this.animationPeriod = Math.ceil(this.initialAnimationPeriod * Math.sqrt(this.coolingFactor));
+ }
+ // Operations while tree is growing again
+ if (this.isTreeGrowing) {
+ if (this.growTreeIterations % 10 == 0) {
+ if (this.prunedNodesAll.length > 0) {
+ this.graphManager.updateBounds();
+ this.updateGrid();
+ this.growTree(this.prunedNodesAll);
+ // Update nodes that gravity will be applied
+ this.graphManager.resetAllNodesToApplyGravitation();
+ var allNodes = new Set(this.getAllNodes());
+ var intersection = this.nodesWithGravity.filter(function (x) {
+ return allNodes.has(x);
+ });
+ this.graphManager.setAllNodesToApplyGravitation(intersection);
+
+ this.graphManager.updateBounds();
+ this.updateGrid();
+ if (CoSEConstants.PURE_INCREMENTAL) this.coolingFactor = FDLayoutConstants.DEFAULT_COOLING_FACTOR_INCREMENTAL / 2;else this.coolingFactor = FDLayoutConstants.DEFAULT_COOLING_FACTOR_INCREMENTAL;
+ } else {
+ this.isTreeGrowing = false;
+ this.isGrowthFinished = true;
+ }
+ }
+ this.growTreeIterations++;
+ }
+ // Operations after growth is finished
+ if (this.isGrowthFinished) {
+ if (this.isConverged()) {
+ return true;
+ }
+ if (this.afterGrowthIterations % 10 == 0) {
+ this.graphManager.updateBounds();
+ this.updateGrid();
+ }
+ if (CoSEConstants.PURE_INCREMENTAL) this.coolingFactor = FDLayoutConstants.DEFAULT_COOLING_FACTOR_INCREMENTAL / 2 * ((100 - this.afterGrowthIterations) / 100);else this.coolingFactor = FDLayoutConstants.DEFAULT_COOLING_FACTOR_INCREMENTAL * ((100 - this.afterGrowthIterations) / 100);
+ this.afterGrowthIterations++;
+ }
+
+ var gridUpdateAllowed = !this.isTreeGrowing && !this.isGrowthFinished;
+ var forceToNodeSurroundingUpdate = this.growTreeIterations % 10 == 1 && this.isTreeGrowing || this.afterGrowthIterations % 10 == 1 && this.isGrowthFinished;
+
+ this.totalDisplacement = 0;
+ this.graphManager.updateBounds();
+ this.calcSpringForces();
+ this.calcRepulsionForces(gridUpdateAllowed, forceToNodeSurroundingUpdate);
+ this.calcGravitationalForces();
+ this.moveNodes();
+ this.animate();
+
+ return false; // Layout is not ended yet return false
+};
+
+CoSELayout.prototype.getPositionsData = function () {
+ var allNodes = this.graphManager.getAllNodes();
+ var pData = {};
+ for (var i = 0; i < allNodes.length; i++) {
+ var rect = allNodes[i].rect;
+ var id = allNodes[i].id;
+ pData[id] = {
+ id: id,
+ x: rect.getCenterX(),
+ y: rect.getCenterY(),
+ w: rect.width,
+ h: rect.height
+ };
+ }
+
+ return pData;
+};
+
+CoSELayout.prototype.runSpringEmbedder = function () {
+ this.initialAnimationPeriod = 25;
+ this.animationPeriod = this.initialAnimationPeriod;
+ var layoutEnded = false;
+
+ // If aminate option is 'during' signal that layout is supposed to start iterating
+ if (FDLayoutConstants.ANIMATE === 'during') {
+ this.emit('layoutstarted');
+ } else {
+ // If aminate option is 'during' tick() function will be called on index.js
+ while (!layoutEnded) {
+ layoutEnded = this.tick();
+ }
+
+ this.graphManager.updateBounds();
+ }
+};
+
+// overrides moveNodes method in FDLayout
+CoSELayout.prototype.moveNodes = function () {
+ var lNodes = this.getAllNodes();
+ var node;
+
+ // calculate displacement for each node
+ for (var i = 0; i < lNodes.length; i++) {
+ node = lNodes[i];
+ node.calculateDisplacement();
+ }
+
+ if (Object.keys(this.constraints).length > 0) {
+ this.updateDisplacements();
+ }
+
+ // move each node
+ for (var i = 0; i < lNodes.length; i++) {
+ node = lNodes[i];
+ node.move();
+ }
+};
+
+// constraint related methods: initConstraintVariables and updateDisplacements
+
+// initialize constraint related variables
+CoSELayout.prototype.initConstraintVariables = function () {
+ var self = this;
+ this.idToNodeMap = new Map();
+ this.fixedNodeSet = new Set();
+
+ var allNodes = this.graphManager.getAllNodes();
+
+ // fill idToNodeMap
+ for (var i = 0; i < allNodes.length; i++) {
+ var node = allNodes[i];
+ this.idToNodeMap.set(node.id, node);
+ }
+
+ // calculate fixed node weight for given compound node
+ var calculateCompoundWeight = function calculateCompoundWeight(compoundNode) {
+ var nodes = compoundNode.getChild().getNodes();
+ var node;
+ var fixedNodeWeight = 0;
+ for (var i = 0; i < nodes.length; i++) {
+ node = nodes[i];
+ if (node.getChild() == null) {
+ if (self.fixedNodeSet.has(node.id)) {
+ fixedNodeWeight += 100;
+ }
+ } else {
+ fixedNodeWeight += calculateCompoundWeight(node);
+ }
+ }
+ return fixedNodeWeight;
+ };
+
+ if (this.constraints.fixedNodeConstraint) {
+ // fill fixedNodeSet
+ this.constraints.fixedNodeConstraint.forEach(function (nodeData) {
+ self.fixedNodeSet.add(nodeData.nodeId);
+ });
+
+ // assign fixed node weights to compounds if they contain fixed nodes
+ var allNodes = this.graphManager.getAllNodes();
+ var node;
+
+ for (var i = 0; i < allNodes.length; i++) {
+ node = allNodes[i];
+ if (node.getChild() != null) {
+ var fixedNodeWeight = calculateCompoundWeight(node);
+ if (fixedNodeWeight > 0) {
+ node.fixedNodeWeight = fixedNodeWeight;
+ }
+ }
+ }
+ }
+
+ if (this.constraints.relativePlacementConstraint) {
+ var nodeToDummyForVerticalAlignment = new Map();
+ var nodeToDummyForHorizontalAlignment = new Map();
+ this.dummyToNodeForVerticalAlignment = new Map();
+ this.dummyToNodeForHorizontalAlignment = new Map();
+ this.fixedNodesOnHorizontal = new Set();
+ this.fixedNodesOnVertical = new Set();
+
+ // fill maps and sets
+ this.fixedNodeSet.forEach(function (nodeId) {
+ self.fixedNodesOnHorizontal.add(nodeId);
+ self.fixedNodesOnVertical.add(nodeId);
+ });
+
+ if (this.constraints.alignmentConstraint) {
+ if (this.constraints.alignmentConstraint.vertical) {
+ var verticalAlignment = this.constraints.alignmentConstraint.vertical;
+ for (var i = 0; i < verticalAlignment.length; i++) {
+ this.dummyToNodeForVerticalAlignment.set("dummy" + i, []);
+ verticalAlignment[i].forEach(function (nodeId) {
+ nodeToDummyForVerticalAlignment.set(nodeId, "dummy" + i);
+ self.dummyToNodeForVerticalAlignment.get("dummy" + i).push(nodeId);
+ if (self.fixedNodeSet.has(nodeId)) {
+ self.fixedNodesOnHorizontal.add("dummy" + i);
+ }
+ });
+ }
+ }
+ if (this.constraints.alignmentConstraint.horizontal) {
+ var horizontalAlignment = this.constraints.alignmentConstraint.horizontal;
+ for (var i = 0; i < horizontalAlignment.length; i++) {
+ this.dummyToNodeForHorizontalAlignment.set("dummy" + i, []);
+ horizontalAlignment[i].forEach(function (nodeId) {
+ nodeToDummyForHorizontalAlignment.set(nodeId, "dummy" + i);
+ self.dummyToNodeForHorizontalAlignment.get("dummy" + i).push(nodeId);
+ if (self.fixedNodeSet.has(nodeId)) {
+ self.fixedNodesOnVertical.add("dummy" + i);
+ }
+ });
+ }
+ }
+ }
+
+ if (CoSEConstants.RELAX_MOVEMENT_ON_CONSTRAINTS) {
+
+ this.shuffle = function (array) {
+ var j, x, i;
+ for (i = array.length - 1; i >= 2 * array.length / 3; i--) {
+ j = Math.floor(Math.random() * (i + 1));
+ x = array[i];
+ array[i] = array[j];
+ array[j] = x;
+ }
+ return array;
+ };
+
+ this.nodesInRelativeHorizontal = [];
+ this.nodesInRelativeVertical = [];
+ this.nodeToRelativeConstraintMapHorizontal = new Map();
+ this.nodeToRelativeConstraintMapVertical = new Map();
+ this.nodeToTempPositionMapHorizontal = new Map();
+ this.nodeToTempPositionMapVertical = new Map();
+
+ // fill arrays and maps
+ this.constraints.relativePlacementConstraint.forEach(function (constraint) {
+ if (constraint.left) {
+ var nodeIdLeft = nodeToDummyForVerticalAlignment.has(constraint.left) ? nodeToDummyForVerticalAlignment.get(constraint.left) : constraint.left;
+ var nodeIdRight = nodeToDummyForVerticalAlignment.has(constraint.right) ? nodeToDummyForVerticalAlignment.get(constraint.right) : constraint.right;
+
+ if (!self.nodesInRelativeHorizontal.includes(nodeIdLeft)) {
+ self.nodesInRelativeHorizontal.push(nodeIdLeft);
+ self.nodeToRelativeConstraintMapHorizontal.set(nodeIdLeft, []);
+ if (self.dummyToNodeForVerticalAlignment.has(nodeIdLeft)) {
+ self.nodeToTempPositionMapHorizontal.set(nodeIdLeft, self.idToNodeMap.get(self.dummyToNodeForVerticalAlignment.get(nodeIdLeft)[0]).getCenterX());
+ } else {
+ self.nodeToTempPositionMapHorizontal.set(nodeIdLeft, self.idToNodeMap.get(nodeIdLeft).getCenterX());
+ }
+ }
+ if (!self.nodesInRelativeHorizontal.includes(nodeIdRight)) {
+ self.nodesInRelativeHorizontal.push(nodeIdRight);
+ self.nodeToRelativeConstraintMapHorizontal.set(nodeIdRight, []);
+ if (self.dummyToNodeForVerticalAlignment.has(nodeIdRight)) {
+ self.nodeToTempPositionMapHorizontal.set(nodeIdRight, self.idToNodeMap.get(self.dummyToNodeForVerticalAlignment.get(nodeIdRight)[0]).getCenterX());
+ } else {
+ self.nodeToTempPositionMapHorizontal.set(nodeIdRight, self.idToNodeMap.get(nodeIdRight).getCenterX());
+ }
+ }
+
+ self.nodeToRelativeConstraintMapHorizontal.get(nodeIdLeft).push({ right: nodeIdRight, gap: constraint.gap });
+ self.nodeToRelativeConstraintMapHorizontal.get(nodeIdRight).push({ left: nodeIdLeft, gap: constraint.gap });
+ } else {
+ var nodeIdTop = nodeToDummyForHorizontalAlignment.has(constraint.top) ? nodeToDummyForHorizontalAlignment.get(constraint.top) : constraint.top;
+ var nodeIdBottom = nodeToDummyForHorizontalAlignment.has(constraint.bottom) ? nodeToDummyForHorizontalAlignment.get(constraint.bottom) : constraint.bottom;
+
+ if (!self.nodesInRelativeVertical.includes(nodeIdTop)) {
+ self.nodesInRelativeVertical.push(nodeIdTop);
+ self.nodeToRelativeConstraintMapVertical.set(nodeIdTop, []);
+ if (self.dummyToNodeForHorizontalAlignment.has(nodeIdTop)) {
+ self.nodeToTempPositionMapVertical.set(nodeIdTop, self.idToNodeMap.get(self.dummyToNodeForHorizontalAlignment.get(nodeIdTop)[0]).getCenterY());
+ } else {
+ self.nodeToTempPositionMapVertical.set(nodeIdTop, self.idToNodeMap.get(nodeIdTop).getCenterY());
+ }
+ }
+ if (!self.nodesInRelativeVertical.includes(nodeIdBottom)) {
+ self.nodesInRelativeVertical.push(nodeIdBottom);
+ self.nodeToRelativeConstraintMapVertical.set(nodeIdBottom, []);
+ if (self.dummyToNodeForHorizontalAlignment.has(nodeIdBottom)) {
+ self.nodeToTempPositionMapVertical.set(nodeIdBottom, self.idToNodeMap.get(self.dummyToNodeForHorizontalAlignment.get(nodeIdBottom)[0]).getCenterY());
+ } else {
+ self.nodeToTempPositionMapVertical.set(nodeIdBottom, self.idToNodeMap.get(nodeIdBottom).getCenterY());
+ }
+ }
+ self.nodeToRelativeConstraintMapVertical.get(nodeIdTop).push({ bottom: nodeIdBottom, gap: constraint.gap });
+ self.nodeToRelativeConstraintMapVertical.get(nodeIdBottom).push({ top: nodeIdTop, gap: constraint.gap });
+ }
+ });
+ } else {
+ var subGraphOnHorizontal = new Map(); // subgraph from vertical RP constraints
+ var subGraphOnVertical = new Map(); // subgraph from vertical RP constraints
+
+ // construct subgraphs from relative placement constraints
+ this.constraints.relativePlacementConstraint.forEach(function (constraint) {
+ if (constraint.left) {
+ var left = nodeToDummyForVerticalAlignment.has(constraint.left) ? nodeToDummyForVerticalAlignment.get(constraint.left) : constraint.left;
+ var right = nodeToDummyForVerticalAlignment.has(constraint.right) ? nodeToDummyForVerticalAlignment.get(constraint.right) : constraint.right;
+ if (subGraphOnHorizontal.has(left)) {
+ subGraphOnHorizontal.get(left).push(right);
+ } else {
+ subGraphOnHorizontal.set(left, [right]);
+ }
+ if (subGraphOnHorizontal.has(right)) {
+ subGraphOnHorizontal.get(right).push(left);
+ } else {
+ subGraphOnHorizontal.set(right, [left]);
+ }
+ } else {
+ var top = nodeToDummyForHorizontalAlignment.has(constraint.top) ? nodeToDummyForHorizontalAlignment.get(constraint.top) : constraint.top;
+ var bottom = nodeToDummyForHorizontalAlignment.has(constraint.bottom) ? nodeToDummyForHorizontalAlignment.get(constraint.bottom) : constraint.bottom;
+ if (subGraphOnVertical.has(top)) {
+ subGraphOnVertical.get(top).push(bottom);
+ } else {
+ subGraphOnVertical.set(top, [bottom]);
+ }
+ if (subGraphOnVertical.has(bottom)) {
+ subGraphOnVertical.get(bottom).push(top);
+ } else {
+ subGraphOnVertical.set(bottom, [top]);
+ }
+ }
+ });
+
+ // function to construct components from a given graph
+ // also returns an array that keeps whether each component contains fixed node
+ var constructComponents = function constructComponents(graph, fixedNodes) {
+ var components = [];
+ var isFixed = [];
+ var queue = new LinkedList();
+ var visited = new Set();
+ var count = 0;
+
+ graph.forEach(function (value, key) {
+ if (!visited.has(key)) {
+ components[count] = [];
+ isFixed[count] = false;
+ var currentNode = key;
+ queue.push(currentNode);
+ visited.add(currentNode);
+ components[count].push(currentNode);
+
+ while (queue.length != 0) {
+ currentNode = queue.shift();
+ if (fixedNodes.has(currentNode)) {
+ isFixed[count] = true;
+ }
+ var neighbors = graph.get(currentNode);
+ neighbors.forEach(function (neighbor) {
+ if (!visited.has(neighbor)) {
+ queue.push(neighbor);
+ visited.add(neighbor);
+ components[count].push(neighbor);
+ }
+ });
+ }
+ count++;
+ }
+ });
+
+ return { components: components, isFixed: isFixed };
+ };
+
+ var resultOnHorizontal = constructComponents(subGraphOnHorizontal, self.fixedNodesOnHorizontal);
+ this.componentsOnHorizontal = resultOnHorizontal.components;
+ this.fixedComponentsOnHorizontal = resultOnHorizontal.isFixed;
+ var resultOnVertical = constructComponents(subGraphOnVertical, self.fixedNodesOnVertical);
+ this.componentsOnVertical = resultOnVertical.components;
+ this.fixedComponentsOnVertical = resultOnVertical.isFixed;
+ }
+ }
+};
+
+// updates node displacements based on constraints
+CoSELayout.prototype.updateDisplacements = function () {
+ var self = this;
+ if (this.constraints.fixedNodeConstraint) {
+ this.constraints.fixedNodeConstraint.forEach(function (nodeData) {
+ var fixedNode = self.idToNodeMap.get(nodeData.nodeId);
+ fixedNode.displacementX = 0;
+ fixedNode.displacementY = 0;
+ });
+ }
+
+ if (this.constraints.alignmentConstraint) {
+ if (this.constraints.alignmentConstraint.vertical) {
+ var allVerticalAlignments = this.constraints.alignmentConstraint.vertical;
+ for (var i = 0; i < allVerticalAlignments.length; i++) {
+ var totalDisplacementX = 0;
+ for (var j = 0; j < allVerticalAlignments[i].length; j++) {
+ if (this.fixedNodeSet.has(allVerticalAlignments[i][j])) {
+ totalDisplacementX = 0;
+ break;
+ }
+ totalDisplacementX += this.idToNodeMap.get(allVerticalAlignments[i][j]).displacementX;
+ }
+ var averageDisplacementX = totalDisplacementX / allVerticalAlignments[i].length;
+ for (var j = 0; j < allVerticalAlignments[i].length; j++) {
+ this.idToNodeMap.get(allVerticalAlignments[i][j]).displacementX = averageDisplacementX;
+ }
+ }
+ }
+ if (this.constraints.alignmentConstraint.horizontal) {
+ var allHorizontalAlignments = this.constraints.alignmentConstraint.horizontal;
+ for (var i = 0; i < allHorizontalAlignments.length; i++) {
+ var totalDisplacementY = 0;
+ for (var j = 0; j < allHorizontalAlignments[i].length; j++) {
+ if (this.fixedNodeSet.has(allHorizontalAlignments[i][j])) {
+ totalDisplacementY = 0;
+ break;
+ }
+ totalDisplacementY += this.idToNodeMap.get(allHorizontalAlignments[i][j]).displacementY;
+ }
+ var averageDisplacementY = totalDisplacementY / allHorizontalAlignments[i].length;
+ for (var j = 0; j < allHorizontalAlignments[i].length; j++) {
+ this.idToNodeMap.get(allHorizontalAlignments[i][j]).displacementY = averageDisplacementY;
+ }
+ }
+ }
+ }
+
+ if (this.constraints.relativePlacementConstraint) {
+
+ if (CoSEConstants.RELAX_MOVEMENT_ON_CONSTRAINTS) {
+ // shuffle array to randomize node processing order
+ if (this.totalIterations % 10 == 0) {
+ this.shuffle(this.nodesInRelativeHorizontal);
+ this.shuffle(this.nodesInRelativeVertical);
+ }
+
+ this.nodesInRelativeHorizontal.forEach(function (nodeId) {
+ if (!self.fixedNodesOnHorizontal.has(nodeId)) {
+ var displacement = 0;
+ if (self.dummyToNodeForVerticalAlignment.has(nodeId)) {
+ displacement = self.idToNodeMap.get(self.dummyToNodeForVerticalAlignment.get(nodeId)[0]).displacementX;
+ } else {
+ displacement = self.idToNodeMap.get(nodeId).displacementX;
+ }
+ self.nodeToRelativeConstraintMapHorizontal.get(nodeId).forEach(function (constraint) {
+ if (constraint.right) {
+ var diff = self.nodeToTempPositionMapHorizontal.get(constraint.right) - self.nodeToTempPositionMapHorizontal.get(nodeId) - displacement;
+ if (diff < constraint.gap) {
+ displacement -= constraint.gap - diff;
+ }
+ } else {
+ var diff = self.nodeToTempPositionMapHorizontal.get(nodeId) - self.nodeToTempPositionMapHorizontal.get(constraint.left) + displacement;
+ if (diff < constraint.gap) {
+ displacement += constraint.gap - diff;
+ }
+ }
+ });
+ self.nodeToTempPositionMapHorizontal.set(nodeId, self.nodeToTempPositionMapHorizontal.get(nodeId) + displacement);
+ if (self.dummyToNodeForVerticalAlignment.has(nodeId)) {
+ self.dummyToNodeForVerticalAlignment.get(nodeId).forEach(function (nodeId) {
+ self.idToNodeMap.get(nodeId).displacementX = displacement;
+ });
+ } else {
+ self.idToNodeMap.get(nodeId).displacementX = displacement;
+ }
+ }
+ });
+
+ this.nodesInRelativeVertical.forEach(function (nodeId) {
+ if (!self.fixedNodesOnHorizontal.has(nodeId)) {
+ var displacement = 0;
+ if (self.dummyToNodeForHorizontalAlignment.has(nodeId)) {
+ displacement = self.idToNodeMap.get(self.dummyToNodeForHorizontalAlignment.get(nodeId)[0]).displacementY;
+ } else {
+ displacement = self.idToNodeMap.get(nodeId).displacementY;
+ }
+ self.nodeToRelativeConstraintMapVertical.get(nodeId).forEach(function (constraint) {
+ if (constraint.bottom) {
+ var diff = self.nodeToTempPositionMapVertical.get(constraint.bottom) - self.nodeToTempPositionMapVertical.get(nodeId) - displacement;
+ if (diff < constraint.gap) {
+ displacement -= constraint.gap - diff;
+ }
+ } else {
+ var diff = self.nodeToTempPositionMapVertical.get(nodeId) - self.nodeToTempPositionMapVertical.get(constraint.top) + displacement;
+ if (diff < constraint.gap) {
+ displacement += constraint.gap - diff;
+ }
+ }
+ });
+ self.nodeToTempPositionMapVertical.set(nodeId, self.nodeToTempPositionMapVertical.get(nodeId) + displacement);
+ if (self.dummyToNodeForHorizontalAlignment.has(nodeId)) {
+ self.dummyToNodeForHorizontalAlignment.get(nodeId).forEach(function (nodeId) {
+ self.idToNodeMap.get(nodeId).displacementY = displacement;
+ });
+ } else {
+ self.idToNodeMap.get(nodeId).displacementY = displacement;
+ }
+ }
+ });
+ } else {
+ for (var i = 0; i < this.componentsOnHorizontal.length; i++) {
+ var component = this.componentsOnHorizontal[i];
+ if (this.fixedComponentsOnHorizontal[i]) {
+ for (var j = 0; j < component.length; j++) {
+ if (this.dummyToNodeForVerticalAlignment.has(component[j])) {
+ this.dummyToNodeForVerticalAlignment.get(component[j]).forEach(function (nodeId) {
+ self.idToNodeMap.get(nodeId).displacementX = 0;
+ });
+ } else {
+ this.idToNodeMap.get(component[j]).displacementX = 0;
+ }
+ }
+ } else {
+ var sum = 0;
+ var count = 0;
+ for (var j = 0; j < component.length; j++) {
+ if (this.dummyToNodeForVerticalAlignment.has(component[j])) {
+ var actualNodes = this.dummyToNodeForVerticalAlignment.get(component[j]);
+ sum += actualNodes.length * this.idToNodeMap.get(actualNodes[0]).displacementX;
+ count += actualNodes.length;
+ } else {
+ sum += this.idToNodeMap.get(component[j]).displacementX;
+ count++;
+ }
+ }
+ var averageDisplacement = sum / count;
+ for (var j = 0; j < component.length; j++) {
+ if (this.dummyToNodeForVerticalAlignment.has(component[j])) {
+ this.dummyToNodeForVerticalAlignment.get(component[j]).forEach(function (nodeId) {
+ self.idToNodeMap.get(nodeId).displacementX = averageDisplacement;
+ });
+ } else {
+ this.idToNodeMap.get(component[j]).displacementX = averageDisplacement;
+ }
+ }
+ }
+ }
+
+ for (var i = 0; i < this.componentsOnVertical.length; i++) {
+ var component = this.componentsOnVertical[i];
+ if (this.fixedComponentsOnVertical[i]) {
+ for (var j = 0; j < component.length; j++) {
+ if (this.dummyToNodeForHorizontalAlignment.has(component[j])) {
+ this.dummyToNodeForHorizontalAlignment.get(component[j]).forEach(function (nodeId) {
+ self.idToNodeMap.get(nodeId).displacementY = 0;
+ });
+ } else {
+ this.idToNodeMap.get(component[j]).displacementY = 0;
+ }
+ }
+ } else {
+ var sum = 0;
+ var count = 0;
+ for (var j = 0; j < component.length; j++) {
+ if (this.dummyToNodeForHorizontalAlignment.has(component[j])) {
+ var actualNodes = this.dummyToNodeForHorizontalAlignment.get(component[j]);
+ sum += actualNodes.length * this.idToNodeMap.get(actualNodes[0]).displacementY;
+ count += actualNodes.length;
+ } else {
+ sum += this.idToNodeMap.get(component[j]).displacementY;
+ count++;
+ }
+ }
+ var averageDisplacement = sum / count;
+ for (var j = 0; j < component.length; j++) {
+ if (this.dummyToNodeForHorizontalAlignment.has(component[j])) {
+ this.dummyToNodeForHorizontalAlignment.get(component[j]).forEach(function (nodeId) {
+ self.idToNodeMap.get(nodeId).displacementY = averageDisplacement;
+ });
+ } else {
+ this.idToNodeMap.get(component[j]).displacementY = averageDisplacement;
+ }
+ }
+ }
+ }
+ }
+ }
+};
+
+CoSELayout.prototype.calculateNodesToApplyGravitationTo = function () {
+ var nodeList = [];
+ var graph;
+
+ var graphs = this.graphManager.getGraphs();
+ var size = graphs.length;
+ var i;
+ for (i = 0; i < size; i++) {
+ graph = graphs[i];
+
+ graph.updateConnected();
+
+ if (!graph.isConnected) {
+ nodeList = nodeList.concat(graph.getNodes());
+ }
+ }
+
+ return nodeList;
+};
+
+CoSELayout.prototype.createBendpoints = function () {
+ var edges = [];
+ edges = edges.concat(this.graphManager.getAllEdges());
+ var visited = new Set();
+ var i;
+ for (i = 0; i < edges.length; i++) {
+ var edge = edges[i];
+
+ if (!visited.has(edge)) {
+ var source = edge.getSource();
+ var target = edge.getTarget();
+
+ if (source == target) {
+ edge.getBendpoints().push(new PointD());
+ edge.getBendpoints().push(new PointD());
+ this.createDummyNodesForBendpoints(edge);
+ visited.add(edge);
+ } else {
+ var edgeList = [];
+
+ edgeList = edgeList.concat(source.getEdgeListToNode(target));
+ edgeList = edgeList.concat(target.getEdgeListToNode(source));
+
+ if (!visited.has(edgeList[0])) {
+ if (edgeList.length > 1) {
+ var k;
+ for (k = 0; k < edgeList.length; k++) {
+ var multiEdge = edgeList[k];
+ multiEdge.getBendpoints().push(new PointD());
+ this.createDummyNodesForBendpoints(multiEdge);
+ }
+ }
+ edgeList.forEach(function (edge) {
+ visited.add(edge);
+ });
+ }
+ }
+ }
+
+ if (visited.size == edges.length) {
+ break;
+ }
+ }
+};
+
+CoSELayout.prototype.positionNodesRadially = function (forest) {
+ // We tile the trees to a grid row by row; first tree starts at (0,0)
+ var currentStartingPoint = new Point(0, 0);
+ var numberOfColumns = Math.ceil(Math.sqrt(forest.length));
+ var height = 0;
+ var currentY = 0;
+ var currentX = 0;
+ var point = new PointD(0, 0);
+
+ for (var i = 0; i < forest.length; i++) {
+ if (i % numberOfColumns == 0) {
+ // Start of a new row, make the x coordinate 0, increment the
+ // y coordinate with the max height of the previous row
+ currentX = 0;
+ currentY = height;
+
+ if (i != 0) {
+ currentY += CoSEConstants.DEFAULT_COMPONENT_SEPERATION;
+ }
+
+ height = 0;
+ }
+
+ var tree = forest[i];
+
+ // Find the center of the tree
+ var centerNode = Layout.findCenterOfTree(tree);
+
+ // Set the staring point of the next tree
+ currentStartingPoint.x = currentX;
+ currentStartingPoint.y = currentY;
+
+ // Do a radial layout starting with the center
+ point = CoSELayout.radialLayout(tree, centerNode, currentStartingPoint);
+
+ if (point.y > height) {
+ height = Math.floor(point.y);
+ }
+
+ currentX = Math.floor(point.x + CoSEConstants.DEFAULT_COMPONENT_SEPERATION);
+ }
+
+ this.transform(new PointD(LayoutConstants.WORLD_CENTER_X - point.x / 2, LayoutConstants.WORLD_CENTER_Y - point.y / 2));
+};
+
+CoSELayout.radialLayout = function (tree, centerNode, startingPoint) {
+ var radialSep = Math.max(this.maxDiagonalInTree(tree), CoSEConstants.DEFAULT_RADIAL_SEPARATION);
+ CoSELayout.branchRadialLayout(centerNode, null, 0, 359, 0, radialSep);
+ var bounds = LGraph.calculateBounds(tree);
+
+ var transform = new Transform();
+ transform.setDeviceOrgX(bounds.getMinX());
+ transform.setDeviceOrgY(bounds.getMinY());
+ transform.setWorldOrgX(startingPoint.x);
+ transform.setWorldOrgY(startingPoint.y);
+
+ for (var i = 0; i < tree.length; i++) {
+ var node = tree[i];
+ node.transform(transform);
+ }
+
+ var bottomRight = new PointD(bounds.getMaxX(), bounds.getMaxY());
+
+ return transform.inverseTransformPoint(bottomRight);
+};
+
+CoSELayout.branchRadialLayout = function (node, parentOfNode, startAngle, endAngle, distance, radialSeparation) {
+ // First, position this node by finding its angle.
+ var halfInterval = (endAngle - startAngle + 1) / 2;
+
+ if (halfInterval < 0) {
+ halfInterval += 180;
+ }
+
+ var nodeAngle = (halfInterval + startAngle) % 360;
+ var teta = nodeAngle * IGeometry.TWO_PI / 360;
+
+ // Make polar to java cordinate conversion.
+ var cos_teta = Math.cos(teta);
+ var x_ = distance * Math.cos(teta);
+ var y_ = distance * Math.sin(teta);
+
+ node.setCenter(x_, y_);
+
+ // Traverse all neighbors of this node and recursively call this
+ // function.
+ var neighborEdges = [];
+ neighborEdges = neighborEdges.concat(node.getEdges());
+ var childCount = neighborEdges.length;
+
+ if (parentOfNode != null) {
+ childCount--;
+ }
+
+ var branchCount = 0;
+
+ var incEdgesCount = neighborEdges.length;
+ var startIndex;
+
+ var edges = node.getEdgesBetween(parentOfNode);
+
+ // If there are multiple edges, prune them until there remains only one
+ // edge.
+ while (edges.length > 1) {
+ //neighborEdges.remove(edges.remove(0));
+ var temp = edges[0];
+ edges.splice(0, 1);
+ var index = neighborEdges.indexOf(temp);
+ if (index >= 0) {
+ neighborEdges.splice(index, 1);
+ }
+ incEdgesCount--;
+ childCount--;
+ }
+
+ if (parentOfNode != null) {
+ //assert edges.length == 1;
+ startIndex = (neighborEdges.indexOf(edges[0]) + 1) % incEdgesCount;
+ } else {
+ startIndex = 0;
+ }
+
+ var stepAngle = Math.abs(endAngle - startAngle) / childCount;
+
+ for (var i = startIndex; branchCount != childCount; i = ++i % incEdgesCount) {
+ var currentNeighbor = neighborEdges[i].getOtherEnd(node);
+
+ // Don't back traverse to root node in current tree.
+ if (currentNeighbor == parentOfNode) {
+ continue;
+ }
+
+ var childStartAngle = (startAngle + branchCount * stepAngle) % 360;
+ var childEndAngle = (childStartAngle + stepAngle) % 360;
+
+ CoSELayout.branchRadialLayout(currentNeighbor, node, childStartAngle, childEndAngle, distance + radialSeparation, radialSeparation);
+
+ branchCount++;
+ }
+};
+
+CoSELayout.maxDiagonalInTree = function (tree) {
+ var maxDiagonal = Integer.MIN_VALUE;
+
+ for (var i = 0; i < tree.length; i++) {
+ var node = tree[i];
+ var diagonal = node.getDiagonal();
+
+ if (diagonal > maxDiagonal) {
+ maxDiagonal = diagonal;
+ }
+ }
+
+ return maxDiagonal;
+};
+
+CoSELayout.prototype.calcRepulsionRange = function () {
+ // formula is 2 x (level + 1) x idealEdgeLength
+ return 2 * (this.level + 1) * this.idealEdgeLength;
+};
+
+// Tiling methods
+
+// Group zero degree members whose parents are not to be tiled, create dummy parents where needed and fill memberGroups by their dummp parent id's
+CoSELayout.prototype.groupZeroDegreeMembers = function () {
+ var self = this;
+ // array of [parent_id x oneDegreeNode_id]
+ var tempMemberGroups = {}; // A temporary map of parent node and its zero degree members
+ this.memberGroups = {}; // A map of dummy parent node and its zero degree members whose parents are not to be tiled
+ this.idToDummyNode = {}; // A map of id to dummy node
+
+ var zeroDegree = []; // List of zero degree nodes whose parents are not to be tiled
+ var allNodes = this.graphManager.getAllNodes();
+
+ // Fill zero degree list
+ for (var i = 0; i < allNodes.length; i++) {
+ var node = allNodes[i];
+ var parent = node.getParent();
+ // If a node has zero degree and its parent is not to be tiled if exists add that node to zeroDegres list
+ if (this.getNodeDegreeWithChildren(node) === 0 && (parent.id == undefined || !this.getToBeTiled(parent))) {
+ zeroDegree.push(node);
+ }
+ }
+
+ // Create a map of parent node and its zero degree members
+ for (var i = 0; i < zeroDegree.length; i++) {
+ var node = zeroDegree[i]; // Zero degree node itself
+ var p_id = node.getParent().id; // Parent id
+
+ if (typeof tempMemberGroups[p_id] === "undefined") tempMemberGroups[p_id] = [];
+
+ tempMemberGroups[p_id] = tempMemberGroups[p_id].concat(node); // Push node to the list belongs to its parent in tempMemberGroups
+ }
+
+ // If there are at least two nodes at a level, create a dummy compound for them
+ Object.keys(tempMemberGroups).forEach(function (p_id) {
+ if (tempMemberGroups[p_id].length > 1) {
+ var dummyCompoundId = "DummyCompound_" + p_id; // The id of dummy compound which will be created soon
+ self.memberGroups[dummyCompoundId] = tempMemberGroups[p_id]; // Add dummy compound to memberGroups
+
+ var parent = tempMemberGroups[p_id][0].getParent(); // The parent of zero degree nodes will be the parent of new dummy compound
+
+ // Create a dummy compound with calculated id
+ var dummyCompound = new CoSENode(self.graphManager);
+ dummyCompound.id = dummyCompoundId;
+ dummyCompound.paddingLeft = parent.paddingLeft || 0;
+ dummyCompound.paddingRight = parent.paddingRight || 0;
+ dummyCompound.paddingBottom = parent.paddingBottom || 0;
+ dummyCompound.paddingTop = parent.paddingTop || 0;
+
+ self.idToDummyNode[dummyCompoundId] = dummyCompound;
+
+ var dummyParentGraph = self.getGraphManager().add(self.newGraph(), dummyCompound);
+ var parentGraph = parent.getChild();
+
+ // Add dummy compound to parent the graph
+ parentGraph.add(dummyCompound);
+
+ // For each zero degree node in this level remove it from its parent graph and add it to the graph of dummy parent
+ for (var i = 0; i < tempMemberGroups[p_id].length; i++) {
+ var node = tempMemberGroups[p_id][i];
+
+ parentGraph.remove(node);
+ dummyParentGraph.add(node);
+ }
+ }
+ });
+};
+
+CoSELayout.prototype.clearCompounds = function () {
+ var childGraphMap = {};
+ var idToNode = {};
+
+ // Get compound ordering by finding the inner one first
+ this.performDFSOnCompounds();
+
+ for (var i = 0; i < this.compoundOrder.length; i++) {
+
+ idToNode[this.compoundOrder[i].id] = this.compoundOrder[i];
+ childGraphMap[this.compoundOrder[i].id] = [].concat(this.compoundOrder[i].getChild().getNodes());
+
+ // Remove children of compounds
+ this.graphManager.remove(this.compoundOrder[i].getChild());
+ this.compoundOrder[i].child = null;
+ }
+
+ this.graphManager.resetAllNodes();
+
+ // Tile the removed children
+ this.tileCompoundMembers(childGraphMap, idToNode);
+};
+
+CoSELayout.prototype.clearZeroDegreeMembers = function () {
+ var self = this;
+ var tiledZeroDegreePack = this.tiledZeroDegreePack = [];
+
+ Object.keys(this.memberGroups).forEach(function (id) {
+ var compoundNode = self.idToDummyNode[id]; // Get the dummy compound
+
+ tiledZeroDegreePack[id] = self.tileNodes(self.memberGroups[id], compoundNode.paddingLeft + compoundNode.paddingRight);
+
+ // Set the width and height of the dummy compound as calculated
+ compoundNode.rect.width = tiledZeroDegreePack[id].width;
+ compoundNode.rect.height = tiledZeroDegreePack[id].height;
+ compoundNode.setCenter(tiledZeroDegreePack[id].centerX, tiledZeroDegreePack[id].centerY);
+
+ // compound left and top margings for labels
+ // when node labels are included, these values may be set to different values below and are used in tilingPostLayout,
+ // otherwise they stay as zero
+ compoundNode.labelMarginLeft = 0;
+ compoundNode.labelMarginTop = 0;
+
+ // Update compound bounds considering its label properties and set label margins for left and top
+ if (CoSEConstants.NODE_DIMENSIONS_INCLUDE_LABELS) {
+
+ var width = compoundNode.rect.width;
+ var height = compoundNode.rect.height;
+
+ if (compoundNode.labelWidth) {
+ if (compoundNode.labelPosHorizontal == "left") {
+ compoundNode.rect.x -= compoundNode.labelWidth;
+ compoundNode.setWidth(width + compoundNode.labelWidth);
+ compoundNode.labelMarginLeft = compoundNode.labelWidth;
+ } else if (compoundNode.labelPosHorizontal == "center" && compoundNode.labelWidth > width) {
+ compoundNode.rect.x -= (compoundNode.labelWidth - width) / 2;
+ compoundNode.setWidth(compoundNode.labelWidth);
+ compoundNode.labelMarginLeft = (compoundNode.labelWidth - width) / 2;
+ } else if (compoundNode.labelPosHorizontal == "right") {
+ compoundNode.setWidth(width + compoundNode.labelWidth);
+ }
+ }
+
+ if (compoundNode.labelHeight) {
+ if (compoundNode.labelPosVertical == "top") {
+ compoundNode.rect.y -= compoundNode.labelHeight;
+ compoundNode.setHeight(height + compoundNode.labelHeight);
+ compoundNode.labelMarginTop = compoundNode.labelHeight;
+ } else if (compoundNode.labelPosVertical == "center" && compoundNode.labelHeight > height) {
+ compoundNode.rect.y -= (compoundNode.labelHeight - height) / 2;
+ compoundNode.setHeight(compoundNode.labelHeight);
+ compoundNode.labelMarginTop = (compoundNode.labelHeight - height) / 2;
+ } else if (compoundNode.labelPosVertical == "bottom") {
+ compoundNode.setHeight(height + compoundNode.labelHeight);
+ }
+ }
+ }
+ });
+};
+
+CoSELayout.prototype.repopulateCompounds = function () {
+ for (var i = this.compoundOrder.length - 1; i >= 0; i--) {
+ var lCompoundNode = this.compoundOrder[i];
+ var id = lCompoundNode.id;
+ var horizontalMargin = lCompoundNode.paddingLeft;
+ var verticalMargin = lCompoundNode.paddingTop;
+ var labelMarginLeft = lCompoundNode.labelMarginLeft;
+ var labelMarginTop = lCompoundNode.labelMarginTop;
+
+ this.adjustLocations(this.tiledMemberPack[id], lCompoundNode.rect.x, lCompoundNode.rect.y, horizontalMargin, verticalMargin, labelMarginLeft, labelMarginTop);
+ }
+};
+
+CoSELayout.prototype.repopulateZeroDegreeMembers = function () {
+ var self = this;
+ var tiledPack = this.tiledZeroDegreePack;
+
+ Object.keys(tiledPack).forEach(function (id) {
+ var compoundNode = self.idToDummyNode[id]; // Get the dummy compound by its id
+ var horizontalMargin = compoundNode.paddingLeft;
+ var verticalMargin = compoundNode.paddingTop;
+ var labelMarginLeft = compoundNode.labelMarginLeft;
+ var labelMarginTop = compoundNode.labelMarginTop;
+
+ // Adjust the positions of nodes wrt its compound
+ self.adjustLocations(tiledPack[id], compoundNode.rect.x, compoundNode.rect.y, horizontalMargin, verticalMargin, labelMarginLeft, labelMarginTop);
+ });
+};
+
+CoSELayout.prototype.getToBeTiled = function (node) {
+ var id = node.id;
+ //firstly check the previous results
+ if (this.toBeTiled[id] != null) {
+ return this.toBeTiled[id];
+ }
+
+ //only compound nodes are to be tiled
+ var childGraph = node.getChild();
+ if (childGraph == null) {
+ this.toBeTiled[id] = false;
+ return false;
+ }
+
+ var children = childGraph.getNodes(); // Get the children nodes
+
+ //a compound node is not to be tiled if all of its compound children are not to be tiled
+ for (var i = 0; i < children.length; i++) {
+ var theChild = children[i];
+
+ if (this.getNodeDegree(theChild) > 0) {
+ this.toBeTiled[id] = false;
+ return false;
+ }
+
+ //pass the children not having the compound structure
+ if (theChild.getChild() == null) {
+ this.toBeTiled[theChild.id] = false;
+ continue;
+ }
+
+ if (!this.getToBeTiled(theChild)) {
+ this.toBeTiled[id] = false;
+ return false;
+ }
+ }
+ this.toBeTiled[id] = true;
+ return true;
+};
+
+// Get degree of a node depending of its edges and independent of its children
+CoSELayout.prototype.getNodeDegree = function (node) {
+ var id = node.id;
+ var edges = node.getEdges();
+ var degree = 0;
+
+ // For the edges connected
+ for (var i = 0; i < edges.length; i++) {
+ var edge = edges[i];
+ if (edge.getSource().id !== edge.getTarget().id) {
+ degree = degree + 1;
+ }
+ }
+ return degree;
+};
+
+// Get degree of a node with its children
+CoSELayout.prototype.getNodeDegreeWithChildren = function (node) {
+ var degree = this.getNodeDegree(node);
+ if (node.getChild() == null) {
+ return degree;
+ }
+ var children = node.getChild().getNodes();
+ for (var i = 0; i < children.length; i++) {
+ var child = children[i];
+ degree += this.getNodeDegreeWithChildren(child);
+ }
+ return degree;
+};
+
+CoSELayout.prototype.performDFSOnCompounds = function () {
+ this.compoundOrder = [];
+ this.fillCompexOrderByDFS(this.graphManager.getRoot().getNodes());
+};
+
+CoSELayout.prototype.fillCompexOrderByDFS = function (children) {
+ for (var i = 0; i < children.length; i++) {
+ var child = children[i];
+ if (child.getChild() != null) {
+ this.fillCompexOrderByDFS(child.getChild().getNodes());
+ }
+ if (this.getToBeTiled(child)) {
+ this.compoundOrder.push(child);
+ }
+ }
+};
+
+/**
+* This method places each zero degree member wrt given (x,y) coordinates (top left).
+*/
+CoSELayout.prototype.adjustLocations = function (organization, x, y, compoundHorizontalMargin, compoundVerticalMargin, compoundLabelMarginLeft, compoundLabelMarginTop) {
+ x += compoundHorizontalMargin + compoundLabelMarginLeft;
+ y += compoundVerticalMargin + compoundLabelMarginTop;
+
+ var left = x;
+
+ for (var i = 0; i < organization.rows.length; i++) {
+ var row = organization.rows[i];
+ x = left;
+ var maxHeight = 0;
+
+ for (var j = 0; j < row.length; j++) {
+ var lnode = row[j];
+
+ lnode.rect.x = x; // + lnode.rect.width / 2;
+ lnode.rect.y = y; // + lnode.rect.height / 2;
+
+ x += lnode.rect.width + organization.horizontalPadding;
+
+ if (lnode.rect.height > maxHeight) maxHeight = lnode.rect.height;
+ }
+
+ y += maxHeight + organization.verticalPadding;
+ }
+};
+
+CoSELayout.prototype.tileCompoundMembers = function (childGraphMap, idToNode) {
+ var self = this;
+ this.tiledMemberPack = [];
+
+ Object.keys(childGraphMap).forEach(function (id) {
+ // Get the compound node
+ var compoundNode = idToNode[id];
+
+ self.tiledMemberPack[id] = self.tileNodes(childGraphMap[id], compoundNode.paddingLeft + compoundNode.paddingRight);
+
+ compoundNode.rect.width = self.tiledMemberPack[id].width;
+ compoundNode.rect.height = self.tiledMemberPack[id].height;
+ compoundNode.setCenter(self.tiledMemberPack[id].centerX, self.tiledMemberPack[id].centerY);
+
+ // compound left and top margings for labels
+ // when node labels are included, these values may be set to different values below and are used in tilingPostLayout,
+ // otherwise they stay as zero
+ compoundNode.labelMarginLeft = 0;
+ compoundNode.labelMarginTop = 0;
+
+ // Update compound bounds considering its label properties and set label margins for left and top
+ if (CoSEConstants.NODE_DIMENSIONS_INCLUDE_LABELS) {
+
+ var width = compoundNode.rect.width;
+ var height = compoundNode.rect.height;
+
+ if (compoundNode.labelWidth) {
+ if (compoundNode.labelPosHorizontal == "left") {
+ compoundNode.rect.x -= compoundNode.labelWidth;
+ compoundNode.setWidth(width + compoundNode.labelWidth);
+ compoundNode.labelMarginLeft = compoundNode.labelWidth;
+ } else if (compoundNode.labelPosHorizontal == "center" && compoundNode.labelWidth > width) {
+ compoundNode.rect.x -= (compoundNode.labelWidth - width) / 2;
+ compoundNode.setWidth(compoundNode.labelWidth);
+ compoundNode.labelMarginLeft = (compoundNode.labelWidth - width) / 2;
+ } else if (compoundNode.labelPosHorizontal == "right") {
+ compoundNode.setWidth(width + compoundNode.labelWidth);
+ }
+ }
+
+ if (compoundNode.labelHeight) {
+ if (compoundNode.labelPosVertical == "top") {
+ compoundNode.rect.y -= compoundNode.labelHeight;
+ compoundNode.setHeight(height + compoundNode.labelHeight);
+ compoundNode.labelMarginTop = compoundNode.labelHeight;
+ } else if (compoundNode.labelPosVertical == "center" && compoundNode.labelHeight > height) {
+ compoundNode.rect.y -= (compoundNode.labelHeight - height) / 2;
+ compoundNode.setHeight(compoundNode.labelHeight);
+ compoundNode.labelMarginTop = (compoundNode.labelHeight - height) / 2;
+ } else if (compoundNode.labelPosVertical == "bottom") {
+ compoundNode.setHeight(height + compoundNode.labelHeight);
+ }
+ }
+ }
+ });
+};
+
+CoSELayout.prototype.tileNodes = function (nodes, minWidth) {
+ var horizontalOrg = this.tileNodesByFavoringDim(nodes, minWidth, true);
+ var verticalOrg = this.tileNodesByFavoringDim(nodes, minWidth, false);
+
+ var horizontalRatio = this.getOrgRatio(horizontalOrg);
+ var verticalRatio = this.getOrgRatio(verticalOrg);
+ var bestOrg;
+
+ // the best ratio is the one that is closer to 1 since the ratios are already normalized
+ // and the best organization is the one that has the best ratio
+ if (verticalRatio < horizontalRatio) {
+ bestOrg = verticalOrg;
+ } else {
+ bestOrg = horizontalOrg;
+ }
+
+ return bestOrg;
+};
+
+// get the width/height ratio of the organization that is normalized so that it will not be less than 1
+CoSELayout.prototype.getOrgRatio = function (organization) {
+ // get dimensions and calculate the initial ratio
+ var width = organization.width;
+ var height = organization.height;
+ var ratio = width / height;
+
+ // if the initial ratio is less then 1 then inverse it
+ if (ratio < 1) {
+ ratio = 1 / ratio;
+ }
+
+ // return the normalized ratio
+ return ratio;
+};
+
+/*
+ * Calculates the ideal width for the rows. This method assumes that
+ * each node has the same sizes and calculates the ideal row width that
+ * approximates a square shaped complex accordingly. However, since nodes would
+ * have different sizes some rows would have different sizes and the resulting
+ * shape would not be an exact square.
+ */
+CoSELayout.prototype.calcIdealRowWidth = function (members, favorHorizontalDim) {
+ // To approximate a square shaped complex we need to make complex width equal to complex height.
+ // To achieve this we need to solve the following equation system for hc:
+ // (x + bx) * hc - bx = (y + by) * vc - by, hc * vc = n
+ // where x is the avarage width of the nodes, y is the avarage height of nodes
+ // bx and by are the buffer sizes in horizontal and vertical dimensions accordingly,
+ // hc and vc are the number of rows in horizontal and vertical dimensions
+ // n is number of members.
+
+ var verticalPadding = CoSEConstants.TILING_PADDING_VERTICAL;
+ var horizontalPadding = CoSEConstants.TILING_PADDING_HORIZONTAL;
+
+ // number of members
+ var membersSize = members.length;
+
+ // sum of the width of all members
+ var totalWidth = 0;
+
+ // sum of the height of all members
+ var totalHeight = 0;
+
+ var maxWidth = 0;
+
+ // traverse all members to calculate total width and total height and get the maximum members width
+ members.forEach(function (node) {
+ totalWidth += node.getWidth();
+ totalHeight += node.getHeight();
+
+ if (node.getWidth() > maxWidth) {
+ maxWidth = node.getWidth();
+ }
+ });
+
+ // average width of the members
+ var averageWidth = totalWidth / membersSize;
+
+ // average height of the members
+ var averageHeight = totalHeight / membersSize;
+
+ // solving the initial equation system for the hc yields the following second degree equation:
+ // hc^2 * (x+bx) + hc * (by - bx) - n * (y + by) = 0
+
+ // the delta value to solve the equation above for hc
+ var delta = Math.pow(verticalPadding - horizontalPadding, 2) + 4 * (averageWidth + horizontalPadding) * (averageHeight + verticalPadding) * membersSize;
+
+ // solve the equation using delta value to calculate the horizontal count
+ // that represents the number of nodes in an ideal row
+ var horizontalCountDouble = (horizontalPadding - verticalPadding + Math.sqrt(delta)) / (2 * (averageWidth + horizontalPadding));
+ // round the calculated horizontal count up or down according to the favored dimension
+ var horizontalCount;
+
+ if (favorHorizontalDim) {
+ horizontalCount = Math.ceil(horizontalCountDouble);
+ // if horizontalCount count is not a float value then both of rounding to floor and ceil
+ // will yield the same values. Instead of repeating the same calculation try going up
+ // while favoring horizontal dimension in such cases
+ if (horizontalCount == horizontalCountDouble) {
+ horizontalCount++;
+ }
+ } else {
+ horizontalCount = Math.floor(horizontalCountDouble);
+ }
+
+ // ideal width to be calculated
+ var idealWidth = horizontalCount * (averageWidth + horizontalPadding) - horizontalPadding;
+
+ // if max width is bigger than calculated ideal width reset ideal width to it
+ if (maxWidth > idealWidth) {
+ idealWidth = maxWidth;
+ }
+
+ // add the left-right margins to the ideal row width
+ idealWidth += horizontalPadding * 2;
+
+ // return the ideal row width1
+ return idealWidth;
+};
+
+CoSELayout.prototype.tileNodesByFavoringDim = function (nodes, minWidth, favorHorizontalDim) {
+ var verticalPadding = CoSEConstants.TILING_PADDING_VERTICAL;
+ var horizontalPadding = CoSEConstants.TILING_PADDING_HORIZONTAL;
+ var tilingCompareBy = CoSEConstants.TILING_COMPARE_BY;
+ var organization = {
+ rows: [],
+ rowWidth: [],
+ rowHeight: [],
+ width: 0,
+ height: minWidth, // assume minHeight equals to minWidth
+ verticalPadding: verticalPadding,
+ horizontalPadding: horizontalPadding,
+ centerX: 0,
+ centerY: 0
+ };
+
+ if (tilingCompareBy) {
+ organization.idealRowWidth = this.calcIdealRowWidth(nodes, favorHorizontalDim);
+ }
+
+ var getNodeArea = function getNodeArea(n) {
+ return n.rect.width * n.rect.height;
+ };
+
+ var areaCompareFcn = function areaCompareFcn(n1, n2) {
+ return getNodeArea(n2) - getNodeArea(n1);
+ };
+
+ // Sort the nodes in descending order of their areas
+ nodes.sort(function (n1, n2) {
+ var cmpBy = areaCompareFcn;
+ if (organization.idealRowWidth) {
+ cmpBy = tilingCompareBy;
+ return cmpBy(n1.id, n2.id);
+ }
+ return cmpBy(n1, n2);
+ });
+
+ // Create the organization -> calculate compound center
+ var sumCenterX = 0;
+ var sumCenterY = 0;
+ for (var i = 0; i < nodes.length; i++) {
+ var lNode = nodes[i];
+
+ sumCenterX += lNode.getCenterX();
+ sumCenterY += lNode.getCenterY();
+ }
+
+ organization.centerX = sumCenterX / nodes.length;
+ organization.centerY = sumCenterY / nodes.length;
+
+ // Create the organization -> tile members
+ for (var i = 0; i < nodes.length; i++) {
+ var lNode = nodes[i];
+
+ if (organization.rows.length == 0) {
+ this.insertNodeToRow(organization, lNode, 0, minWidth);
+ } else if (this.canAddHorizontal(organization, lNode.rect.width, lNode.rect.height)) {
+ var rowIndex = organization.rows.length - 1;
+ if (!organization.idealRowWidth) {
+ rowIndex = this.getShortestRowIndex(organization);
+ }
+ this.insertNodeToRow(organization, lNode, rowIndex, minWidth);
+ } else {
+ this.insertNodeToRow(organization, lNode, organization.rows.length, minWidth);
+ }
+
+ this.shiftToLastRow(organization);
+ }
+
+ return organization;
+};
+
+CoSELayout.prototype.insertNodeToRow = function (organization, node, rowIndex, minWidth) {
+ var minCompoundSize = minWidth;
+
+ // Add new row if needed
+ if (rowIndex == organization.rows.length) {
+ var secondDimension = [];
+
+ organization.rows.push(secondDimension);
+ organization.rowWidth.push(minCompoundSize);
+ organization.rowHeight.push(0);
+ }
+
+ // Update row width
+ var w = organization.rowWidth[rowIndex] + node.rect.width;
+
+ if (organization.rows[rowIndex].length > 0) {
+ w += organization.horizontalPadding;
+ }
+
+ organization.rowWidth[rowIndex] = w;
+ // Update compound width
+ if (organization.width < w) {
+ organization.width = w;
+ }
+
+ // Update height
+ var h = node.rect.height;
+ if (rowIndex > 0) h += organization.verticalPadding;
+
+ var extraHeight = 0;
+ if (h > organization.rowHeight[rowIndex]) {
+ extraHeight = organization.rowHeight[rowIndex];
+ organization.rowHeight[rowIndex] = h;
+ extraHeight = organization.rowHeight[rowIndex] - extraHeight;
+ }
+
+ organization.height += extraHeight;
+
+ // Insert node
+ organization.rows[rowIndex].push(node);
+};
+
+//Scans the rows of an organization and returns the one with the min width
+CoSELayout.prototype.getShortestRowIndex = function (organization) {
+ var r = -1;
+ var min = Number.MAX_VALUE;
+
+ for (var i = 0; i < organization.rows.length; i++) {
+ if (organization.rowWidth[i] < min) {
+ r = i;
+ min = organization.rowWidth[i];
+ }
+ }
+ return r;
+};
+
+//Scans the rows of an organization and returns the one with the max width
+CoSELayout.prototype.getLongestRowIndex = function (organization) {
+ var r = -1;
+ var max = Number.MIN_VALUE;
+
+ for (var i = 0; i < organization.rows.length; i++) {
+
+ if (organization.rowWidth[i] > max) {
+ r = i;
+ max = organization.rowWidth[i];
+ }
+ }
+
+ return r;
+};
+
+/**
+* This method checks whether adding extra width to the organization violates
+* the aspect ratio(1) or not.
+*/
+CoSELayout.prototype.canAddHorizontal = function (organization, extraWidth, extraHeight) {
+
+ // if there is an ideal row width specified use it instead of checking the aspect ratio
+ if (organization.idealRowWidth) {
+ var lastRowIndex = organization.rows.length - 1;
+ var lastRowWidth = organization.rowWidth[lastRowIndex];
+
+ // check and return if ideal row width will be exceed if the node is added to the row
+ return lastRowWidth + extraWidth + organization.horizontalPadding <= organization.idealRowWidth;
+ }
+
+ var sri = this.getShortestRowIndex(organization);
+
+ if (sri < 0) {
+ return true;
+ }
+
+ var min = organization.rowWidth[sri];
+
+ if (min + organization.horizontalPadding + extraWidth <= organization.width) return true;
+
+ var hDiff = 0;
+
+ // Adding to an existing row
+ if (organization.rowHeight[sri] < extraHeight) {
+ if (sri > 0) hDiff = extraHeight + organization.verticalPadding - organization.rowHeight[sri];
+ }
+
+ var add_to_row_ratio;
+ if (organization.width - min >= extraWidth + organization.horizontalPadding) {
+ add_to_row_ratio = (organization.height + hDiff) / (min + extraWidth + organization.horizontalPadding);
+ } else {
+ add_to_row_ratio = (organization.height + hDiff) / organization.width;
+ }
+
+ // Adding a new row for this node
+ hDiff = extraHeight + organization.verticalPadding;
+ var add_new_row_ratio;
+ if (organization.width < extraWidth) {
+ add_new_row_ratio = (organization.height + hDiff) / extraWidth;
+ } else {
+ add_new_row_ratio = (organization.height + hDiff) / organization.width;
+ }
+
+ if (add_new_row_ratio < 1) add_new_row_ratio = 1 / add_new_row_ratio;
+
+ if (add_to_row_ratio < 1) add_to_row_ratio = 1 / add_to_row_ratio;
+
+ return add_to_row_ratio < add_new_row_ratio;
+};
+
+//If moving the last node from the longest row and adding it to the last
+//row makes the bounding box smaller, do it.
+CoSELayout.prototype.shiftToLastRow = function (organization) {
+ var longest = this.getLongestRowIndex(organization);
+ var last = organization.rowWidth.length - 1;
+ var row = organization.rows[longest];
+ var node = row[row.length - 1];
+
+ var diff = node.width + organization.horizontalPadding;
+
+ // Check if there is enough space on the last row
+ if (organization.width - organization.rowWidth[last] > diff && longest != last) {
+ // Remove the last element of the longest row
+ row.splice(-1, 1);
+
+ // Push it to the last row
+ organization.rows[last].push(node);
+
+ organization.rowWidth[longest] = organization.rowWidth[longest] - diff;
+ organization.rowWidth[last] = organization.rowWidth[last] + diff;
+ organization.width = organization.rowWidth[instance.getLongestRowIndex(organization)];
+
+ // Update heights of the organization
+ var maxHeight = Number.MIN_VALUE;
+ for (var i = 0; i < row.length; i++) {
+ if (row[i].height > maxHeight) maxHeight = row[i].height;
+ }
+ if (longest > 0) maxHeight += organization.verticalPadding;
+
+ var prevTotal = organization.rowHeight[longest] + organization.rowHeight[last];
+
+ organization.rowHeight[longest] = maxHeight;
+ if (organization.rowHeight[last] < node.height + organization.verticalPadding) organization.rowHeight[last] = node.height + organization.verticalPadding;
+
+ var finalTotal = organization.rowHeight[longest] + organization.rowHeight[last];
+ organization.height += finalTotal - prevTotal;
+
+ this.shiftToLastRow(organization);
+ }
+};
+
+CoSELayout.prototype.tilingPreLayout = function () {
+ if (CoSEConstants.TILE) {
+ // Find zero degree nodes and create a compound for each level
+ this.groupZeroDegreeMembers();
+ // Tile and clear children of each compound
+ this.clearCompounds();
+ // Separately tile and clear zero degree nodes for each level
+ this.clearZeroDegreeMembers();
+ }
+};
+
+CoSELayout.prototype.tilingPostLayout = function () {
+ if (CoSEConstants.TILE) {
+ this.repopulateZeroDegreeMembers();
+ this.repopulateCompounds();
+ }
+};
+
+// -----------------------------------------------------------------------------
+// Section: Tree Reduction methods
+// -----------------------------------------------------------------------------
+// Reduce trees
+CoSELayout.prototype.reduceTrees = function () {
+ var prunedNodesAll = [];
+ var containsLeaf = true;
+ var node;
+
+ while (containsLeaf) {
+ var allNodes = this.graphManager.getAllNodes();
+ var prunedNodesInStepTemp = [];
+ containsLeaf = false;
+
+ for (var i = 0; i < allNodes.length; i++) {
+ node = allNodes[i];
+ if (node.getEdges().length == 1 && !node.getEdges()[0].isInterGraph && node.getChild() == null) {
+ if (CoSEConstants.PURE_INCREMENTAL) {
+ var otherEnd = node.getEdges()[0].getOtherEnd(node);
+ var relativePosition = new DimensionD(node.getCenterX() - otherEnd.getCenterX(), node.getCenterY() - otherEnd.getCenterY());
+ prunedNodesInStepTemp.push([node, node.getEdges()[0], node.getOwner(), relativePosition]);
+ } else {
+ prunedNodesInStepTemp.push([node, node.getEdges()[0], node.getOwner()]);
+ }
+ containsLeaf = true;
+ }
+ }
+ if (containsLeaf == true) {
+ var prunedNodesInStep = [];
+ for (var j = 0; j < prunedNodesInStepTemp.length; j++) {
+ if (prunedNodesInStepTemp[j][0].getEdges().length == 1) {
+ prunedNodesInStep.push(prunedNodesInStepTemp[j]);
+ prunedNodesInStepTemp[j][0].getOwner().remove(prunedNodesInStepTemp[j][0]);
+ }
+ }
+ prunedNodesAll.push(prunedNodesInStep);
+ this.graphManager.resetAllNodes();
+ this.graphManager.resetAllEdges();
+ }
+ }
+ this.prunedNodesAll = prunedNodesAll;
+};
+
+// Grow tree one step
+CoSELayout.prototype.growTree = function (prunedNodesAll) {
+ var lengthOfPrunedNodesInStep = prunedNodesAll.length;
+ var prunedNodesInStep = prunedNodesAll[lengthOfPrunedNodesInStep - 1];
+
+ var nodeData;
+ for (var i = 0; i < prunedNodesInStep.length; i++) {
+ nodeData = prunedNodesInStep[i];
+
+ this.findPlaceforPrunedNode(nodeData);
+
+ nodeData[2].add(nodeData[0]);
+ nodeData[2].add(nodeData[1], nodeData[1].source, nodeData[1].target);
+ }
+
+ prunedNodesAll.splice(prunedNodesAll.length - 1, 1);
+ this.graphManager.resetAllNodes();
+ this.graphManager.resetAllEdges();
+};
+
+// Find an appropriate position to replace pruned node, this method can be improved
+CoSELayout.prototype.findPlaceforPrunedNode = function (nodeData) {
+
+ var gridForPrunedNode;
+ var nodeToConnect;
+ var prunedNode = nodeData[0];
+ if (prunedNode == nodeData[1].source) {
+ nodeToConnect = nodeData[1].target;
+ } else {
+ nodeToConnect = nodeData[1].source;
+ }
+
+ if (CoSEConstants.PURE_INCREMENTAL) {
+ prunedNode.setCenter(nodeToConnect.getCenterX() + nodeData[3].getWidth(), nodeToConnect.getCenterY() + nodeData[3].getHeight());
+ } else {
+ var startGridX = nodeToConnect.startX;
+ var finishGridX = nodeToConnect.finishX;
+ var startGridY = nodeToConnect.startY;
+ var finishGridY = nodeToConnect.finishY;
+
+ var upNodeCount = 0;
+ var downNodeCount = 0;
+ var rightNodeCount = 0;
+ var leftNodeCount = 0;
+ var controlRegions = [upNodeCount, rightNodeCount, downNodeCount, leftNodeCount];
+
+ if (startGridY > 0) {
+ for (var i = startGridX; i <= finishGridX; i++) {
+ controlRegions[0] += this.grid[i][startGridY - 1].length + this.grid[i][startGridY].length - 1;
+ }
+ }
+ if (finishGridX < this.grid.length - 1) {
+ for (var i = startGridY; i <= finishGridY; i++) {
+ controlRegions[1] += this.grid[finishGridX + 1][i].length + this.grid[finishGridX][i].length - 1;
+ }
+ }
+ if (finishGridY < this.grid[0].length - 1) {
+ for (var i = startGridX; i <= finishGridX; i++) {
+ controlRegions[2] += this.grid[i][finishGridY + 1].length + this.grid[i][finishGridY].length - 1;
+ }
+ }
+ if (startGridX > 0) {
+ for (var i = startGridY; i <= finishGridY; i++) {
+ controlRegions[3] += this.grid[startGridX - 1][i].length + this.grid[startGridX][i].length - 1;
+ }
+ }
+ var min = Integer.MAX_VALUE;
+ var minCount;
+ var minIndex;
+ for (var j = 0; j < controlRegions.length; j++) {
+ if (controlRegions[j] < min) {
+ min = controlRegions[j];
+ minCount = 1;
+ minIndex = j;
+ } else if (controlRegions[j] == min) {
+ minCount++;
+ }
+ }
+
+ if (minCount == 3 && min == 0) {
+ if (controlRegions[0] == 0 && controlRegions[1] == 0 && controlRegions[2] == 0) {
+ gridForPrunedNode = 1;
+ } else if (controlRegions[0] == 0 && controlRegions[1] == 0 && controlRegions[3] == 0) {
+ gridForPrunedNode = 0;
+ } else if (controlRegions[0] == 0 && controlRegions[2] == 0 && controlRegions[3] == 0) {
+ gridForPrunedNode = 3;
+ } else if (controlRegions[1] == 0 && controlRegions[2] == 0 && controlRegions[3] == 0) {
+ gridForPrunedNode = 2;
+ }
+ } else if (minCount == 2 && min == 0) {
+ var random = Math.floor(Math.random() * 2);
+ if (controlRegions[0] == 0 && controlRegions[1] == 0) {
+ ;
+ if (random == 0) {
+ gridForPrunedNode = 0;
+ } else {
+ gridForPrunedNode = 1;
+ }
+ } else if (controlRegions[0] == 0 && controlRegions[2] == 0) {
+ if (random == 0) {
+ gridForPrunedNode = 0;
+ } else {
+ gridForPrunedNode = 2;
+ }
+ } else if (controlRegions[0] == 0 && controlRegions[3] == 0) {
+ if (random == 0) {
+ gridForPrunedNode = 0;
+ } else {
+ gridForPrunedNode = 3;
+ }
+ } else if (controlRegions[1] == 0 && controlRegions[2] == 0) {
+ if (random == 0) {
+ gridForPrunedNode = 1;
+ } else {
+ gridForPrunedNode = 2;
+ }
+ } else if (controlRegions[1] == 0 && controlRegions[3] == 0) {
+ if (random == 0) {
+ gridForPrunedNode = 1;
+ } else {
+ gridForPrunedNode = 3;
+ }
+ } else {
+ if (random == 0) {
+ gridForPrunedNode = 2;
+ } else {
+ gridForPrunedNode = 3;
+ }
+ }
+ } else if (minCount == 4 && min == 0) {
+ var random = Math.floor(Math.random() * 4);
+ gridForPrunedNode = random;
+ } else {
+ gridForPrunedNode = minIndex;
+ }
+
+ if (gridForPrunedNode == 0) {
+ prunedNode.setCenter(nodeToConnect.getCenterX(), nodeToConnect.getCenterY() - nodeToConnect.getHeight() / 2 - FDLayoutConstants.DEFAULT_EDGE_LENGTH - prunedNode.getHeight() / 2);
+ } else if (gridForPrunedNode == 1) {
+ prunedNode.setCenter(nodeToConnect.getCenterX() + nodeToConnect.getWidth() / 2 + FDLayoutConstants.DEFAULT_EDGE_LENGTH + prunedNode.getWidth() / 2, nodeToConnect.getCenterY());
+ } else if (gridForPrunedNode == 2) {
+ prunedNode.setCenter(nodeToConnect.getCenterX(), nodeToConnect.getCenterY() + nodeToConnect.getHeight() / 2 + FDLayoutConstants.DEFAULT_EDGE_LENGTH + prunedNode.getHeight() / 2);
+ } else {
+ prunedNode.setCenter(nodeToConnect.getCenterX() - nodeToConnect.getWidth() / 2 - FDLayoutConstants.DEFAULT_EDGE_LENGTH - prunedNode.getWidth() / 2, nodeToConnect.getCenterY());
+ }
+ }
+};
+
+module.exports = CoSELayout;
+
+/***/ }),
+
+/***/ 991:
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+
+
+var FDLayoutNode = __webpack_require__(551).FDLayoutNode;
+var IMath = __webpack_require__(551).IMath;
+
+function CoSENode(gm, loc, size, vNode) {
+ FDLayoutNode.call(this, gm, loc, size, vNode);
+}
+
+CoSENode.prototype = Object.create(FDLayoutNode.prototype);
+for (var prop in FDLayoutNode) {
+ CoSENode[prop] = FDLayoutNode[prop];
+}
+
+CoSENode.prototype.calculateDisplacement = function () {
+ var layout = this.graphManager.getLayout();
+ // this check is for compound nodes that contain fixed nodes
+ if (this.getChild() != null && this.fixedNodeWeight) {
+ this.displacementX += layout.coolingFactor * (this.springForceX + this.repulsionForceX + this.gravitationForceX) / this.fixedNodeWeight;
+ this.displacementY += layout.coolingFactor * (this.springForceY + this.repulsionForceY + this.gravitationForceY) / this.fixedNodeWeight;
+ } else {
+ this.displacementX += layout.coolingFactor * (this.springForceX + this.repulsionForceX + this.gravitationForceX) / this.noOfChildren;
+ this.displacementY += layout.coolingFactor * (this.springForceY + this.repulsionForceY + this.gravitationForceY) / this.noOfChildren;
+ }
+
+ if (Math.abs(this.displacementX) > layout.coolingFactor * layout.maxNodeDisplacement) {
+ this.displacementX = layout.coolingFactor * layout.maxNodeDisplacement * IMath.sign(this.displacementX);
+ }
+
+ if (Math.abs(this.displacementY) > layout.coolingFactor * layout.maxNodeDisplacement) {
+ this.displacementY = layout.coolingFactor * layout.maxNodeDisplacement * IMath.sign(this.displacementY);
+ }
+
+ // non-empty compound node, propogate movement to children as well
+ if (this.child && this.child.getNodes().length > 0) {
+ this.propogateDisplacementToChildren(this.displacementX, this.displacementY);
+ }
+};
+
+CoSENode.prototype.propogateDisplacementToChildren = function (dX, dY) {
+ var nodes = this.getChild().getNodes();
+ var node;
+ for (var i = 0; i < nodes.length; i++) {
+ node = nodes[i];
+ if (node.getChild() == null) {
+ node.displacementX += dX;
+ node.displacementY += dY;
+ } else {
+ node.propogateDisplacementToChildren(dX, dY);
+ }
+ }
+};
+
+CoSENode.prototype.move = function () {
+ var layout = this.graphManager.getLayout();
+
+ // a simple node or an empty compound node, move it
+ if (this.child == null || this.child.getNodes().length == 0) {
+ this.moveBy(this.displacementX, this.displacementY);
+
+ layout.totalDisplacement += Math.abs(this.displacementX) + Math.abs(this.displacementY);
+ }
+
+ this.springForceX = 0;
+ this.springForceY = 0;
+ this.repulsionForceX = 0;
+ this.repulsionForceY = 0;
+ this.gravitationForceX = 0;
+ this.gravitationForceY = 0;
+ this.displacementX = 0;
+ this.displacementY = 0;
+};
+
+CoSENode.prototype.setPred1 = function (pred1) {
+ this.pred1 = pred1;
+};
+
+CoSENode.prototype.getPred1 = function () {
+ return pred1;
+};
+
+CoSENode.prototype.getPred2 = function () {
+ return pred2;
+};
+
+CoSENode.prototype.setNext = function (next) {
+ this.next = next;
+};
+
+CoSENode.prototype.getNext = function () {
+ return next;
+};
+
+CoSENode.prototype.setProcessed = function (processed) {
+ this.processed = processed;
+};
+
+CoSENode.prototype.isProcessed = function () {
+ return processed;
+};
+
+module.exports = CoSENode;
+
+/***/ }),
+
+/***/ 902:
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+
+
+function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
+
+var CoSEConstants = __webpack_require__(806);
+var LinkedList = __webpack_require__(551).LinkedList;
+var Matrix = __webpack_require__(551).Matrix;
+var SVD = __webpack_require__(551).SVD;
+
+function ConstraintHandler() {}
+
+ConstraintHandler.handleConstraints = function (layout) {
+ // let layout = this.graphManager.getLayout();
+
+ // get constraints from layout
+ var constraints = {};
+ constraints.fixedNodeConstraint = layout.constraints.fixedNodeConstraint;
+ constraints.alignmentConstraint = layout.constraints.alignmentConstraint;
+ constraints.relativePlacementConstraint = layout.constraints.relativePlacementConstraint;
+
+ var idToNodeMap = new Map();
+ var nodeIndexes = new Map();
+ var xCoords = [];
+ var yCoords = [];
+
+ var allNodes = layout.getAllNodes();
+ var index = 0;
+ // fill index map and coordinates
+ for (var i = 0; i < allNodes.length; i++) {
+ var node = allNodes[i];
+ if (node.getChild() == null) {
+ nodeIndexes.set(node.id, index++);
+ xCoords.push(node.getCenterX());
+ yCoords.push(node.getCenterY());
+ idToNodeMap.set(node.id, node);
+ }
+ }
+
+ // if there exists relative placement constraint without gap value, set it to default
+ if (constraints.relativePlacementConstraint) {
+ constraints.relativePlacementConstraint.forEach(function (constraint) {
+ if (!constraint.gap && constraint.gap != 0) {
+ if (constraint.left) {
+ constraint.gap = CoSEConstants.DEFAULT_EDGE_LENGTH + idToNodeMap.get(constraint.left).getWidth() / 2 + idToNodeMap.get(constraint.right).getWidth() / 2;
+ } else {
+ constraint.gap = CoSEConstants.DEFAULT_EDGE_LENGTH + idToNodeMap.get(constraint.top).getHeight() / 2 + idToNodeMap.get(constraint.bottom).getHeight() / 2;
+ }
+ }
+ });
+ }
+
+ /* auxiliary functions */
+
+ // calculate difference between two position objects
+ var calculatePositionDiff = function calculatePositionDiff(pos1, pos2) {
+ return { x: pos1.x - pos2.x, y: pos1.y - pos2.y };
+ };
+
+ // calculate average position of the nodes
+ var calculateAvgPosition = function calculateAvgPosition(nodeIdSet) {
+ var xPosSum = 0;
+ var yPosSum = 0;
+ nodeIdSet.forEach(function (nodeId) {
+ xPosSum += xCoords[nodeIndexes.get(nodeId)];
+ yPosSum += yCoords[nodeIndexes.get(nodeId)];
+ });
+
+ return { x: xPosSum / nodeIdSet.size, y: yPosSum / nodeIdSet.size };
+ };
+
+ // find an appropriate positioning for the nodes in a given graph according to relative placement constraints
+ // this function also takes the fixed nodes and alignment constraints into account
+ // graph: dag to be evaluated, direction: "horizontal" or "vertical",
+ // fixedNodes: set of fixed nodes to consider during evaluation, dummyPositions: appropriate coordinates of the dummy nodes
+ var findAppropriatePositionForRelativePlacement = function findAppropriatePositionForRelativePlacement(graph, direction, fixedNodes, dummyPositions, componentSources) {
+
+ // find union of two sets
+ function setUnion(setA, setB) {
+ var union = new Set(setA);
+ var _iteratorNormalCompletion = true;
+ var _didIteratorError = false;
+ var _iteratorError = undefined;
+
+ try {
+ for (var _iterator = setB[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
+ var elem = _step.value;
+
+ union.add(elem);
+ }
+ } catch (err) {
+ _didIteratorError = true;
+ _iteratorError = err;
+ } finally {
+ try {
+ if (!_iteratorNormalCompletion && _iterator.return) {
+ _iterator.return();
+ }
+ } finally {
+ if (_didIteratorError) {
+ throw _iteratorError;
+ }
+ }
+ }
+
+ return union;
+ }
+
+ // find indegree count for each node
+ var inDegrees = new Map();
+
+ graph.forEach(function (value, key) {
+ inDegrees.set(key, 0);
+ });
+ graph.forEach(function (value, key) {
+ value.forEach(function (adjacent) {
+ inDegrees.set(adjacent.id, inDegrees.get(adjacent.id) + 1);
+ });
+ });
+
+ var positionMap = new Map(); // keeps the position for each node
+ var pastMap = new Map(); // keeps the predecessors(past) of a node
+ var queue = new LinkedList();
+ inDegrees.forEach(function (value, key) {
+ if (value == 0) {
+ queue.push(key);
+ if (!fixedNodes) {
+ if (direction == "horizontal") {
+ positionMap.set(key, nodeIndexes.has(key) ? xCoords[nodeIndexes.get(key)] : dummyPositions.get(key));
+ } else {
+ positionMap.set(key, nodeIndexes.has(key) ? yCoords[nodeIndexes.get(key)] : dummyPositions.get(key));
+ }
+ }
+ } else {
+ positionMap.set(key, Number.NEGATIVE_INFINITY);
+ }
+ if (fixedNodes) {
+ pastMap.set(key, new Set([key]));
+ }
+ });
+
+ // align sources of each component in enforcement phase
+ if (fixedNodes) {
+ componentSources.forEach(function (component) {
+ var fixedIds = [];
+ component.forEach(function (nodeId) {
+ if (fixedNodes.has(nodeId)) {
+ fixedIds.push(nodeId);
+ }
+ });
+ if (fixedIds.length > 0) {
+ var position = 0;
+ fixedIds.forEach(function (fixedId) {
+ if (direction == "horizontal") {
+ positionMap.set(fixedId, nodeIndexes.has(fixedId) ? xCoords[nodeIndexes.get(fixedId)] : dummyPositions.get(fixedId));
+ position += positionMap.get(fixedId);
+ } else {
+ positionMap.set(fixedId, nodeIndexes.has(fixedId) ? yCoords[nodeIndexes.get(fixedId)] : dummyPositions.get(fixedId));
+ position += positionMap.get(fixedId);
+ }
+ });
+ position = position / fixedIds.length;
+ component.forEach(function (nodeId) {
+ if (!fixedNodes.has(nodeId)) {
+ positionMap.set(nodeId, position);
+ }
+ });
+ } else {
+ var _position = 0;
+ component.forEach(function (nodeId) {
+ if (direction == "horizontal") {
+ _position += nodeIndexes.has(nodeId) ? xCoords[nodeIndexes.get(nodeId)] : dummyPositions.get(nodeId);
+ } else {
+ _position += nodeIndexes.has(nodeId) ? yCoords[nodeIndexes.get(nodeId)] : dummyPositions.get(nodeId);
+ }
+ });
+ _position = _position / component.length;
+ component.forEach(function (nodeId) {
+ positionMap.set(nodeId, _position);
+ });
+ }
+ });
+ }
+
+ // calculate positions of the nodes
+
+ var _loop = function _loop() {
+ var currentNode = queue.shift();
+ var neighbors = graph.get(currentNode);
+ neighbors.forEach(function (neighbor) {
+ if (positionMap.get(neighbor.id) < positionMap.get(currentNode) + neighbor.gap) {
+ if (fixedNodes && fixedNodes.has(neighbor.id)) {
+ var fixedPosition = void 0;
+ if (direction == "horizontal") {
+ fixedPosition = nodeIndexes.has(neighbor.id) ? xCoords[nodeIndexes.get(neighbor.id)] : dummyPositions.get(neighbor.id);
+ } else {
+ fixedPosition = nodeIndexes.has(neighbor.id) ? yCoords[nodeIndexes.get(neighbor.id)] : dummyPositions.get(neighbor.id);
+ }
+ positionMap.set(neighbor.id, fixedPosition); // TODO: may do unnecessary work
+ if (fixedPosition < positionMap.get(currentNode) + neighbor.gap) {
+ var diff = positionMap.get(currentNode) + neighbor.gap - fixedPosition;
+ pastMap.get(currentNode).forEach(function (nodeId) {
+ positionMap.set(nodeId, positionMap.get(nodeId) - diff);
+ });
+ }
+ } else {
+ positionMap.set(neighbor.id, positionMap.get(currentNode) + neighbor.gap);
+ }
+ }
+ inDegrees.set(neighbor.id, inDegrees.get(neighbor.id) - 1);
+ if (inDegrees.get(neighbor.id) == 0) {
+ queue.push(neighbor.id);
+ }
+ if (fixedNodes) {
+ pastMap.set(neighbor.id, setUnion(pastMap.get(currentNode), pastMap.get(neighbor.id)));
+ }
+ });
+ };
+
+ while (queue.length != 0) {
+ _loop();
+ }
+
+ // readjust position of the nodes after enforcement
+ if (fixedNodes) {
+ // find indegree count for each node
+ var sinkNodes = new Set();
+
+ graph.forEach(function (value, key) {
+ if (value.length == 0) {
+ sinkNodes.add(key);
+ }
+ });
+
+ var _components = [];
+ pastMap.forEach(function (value, key) {
+ if (sinkNodes.has(key)) {
+ var isFixedComponent = false;
+ var _iteratorNormalCompletion2 = true;
+ var _didIteratorError2 = false;
+ var _iteratorError2 = undefined;
+
+ try {
+ for (var _iterator2 = value[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
+ var nodeId = _step2.value;
+
+ if (fixedNodes.has(nodeId)) {
+ isFixedComponent = true;
+ }
+ }
+ } catch (err) {
+ _didIteratorError2 = true;
+ _iteratorError2 = err;
+ } finally {
+ try {
+ if (!_iteratorNormalCompletion2 && _iterator2.return) {
+ _iterator2.return();
+ }
+ } finally {
+ if (_didIteratorError2) {
+ throw _iteratorError2;
+ }
+ }
+ }
+
+ if (!isFixedComponent) {
+ var isExist = false;
+ var existAt = void 0;
+ _components.forEach(function (component, index) {
+ if (component.has([].concat(_toConsumableArray(value))[0])) {
+ isExist = true;
+ existAt = index;
+ }
+ });
+ if (!isExist) {
+ _components.push(new Set(value));
+ } else {
+ value.forEach(function (ele) {
+ _components[existAt].add(ele);
+ });
+ }
+ }
+ }
+ });
+
+ _components.forEach(function (component, index) {
+ var minBefore = Number.POSITIVE_INFINITY;
+ var minAfter = Number.POSITIVE_INFINITY;
+ var maxBefore = Number.NEGATIVE_INFINITY;
+ var maxAfter = Number.NEGATIVE_INFINITY;
+
+ var _iteratorNormalCompletion3 = true;
+ var _didIteratorError3 = false;
+ var _iteratorError3 = undefined;
+
+ try {
+ for (var _iterator3 = component[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
+ var nodeId = _step3.value;
+
+ var posBefore = void 0;
+ if (direction == "horizontal") {
+ posBefore = nodeIndexes.has(nodeId) ? xCoords[nodeIndexes.get(nodeId)] : dummyPositions.get(nodeId);
+ } else {
+ posBefore = nodeIndexes.has(nodeId) ? yCoords[nodeIndexes.get(nodeId)] : dummyPositions.get(nodeId);
+ }
+ var posAfter = positionMap.get(nodeId);
+ if (posBefore < minBefore) {
+ minBefore = posBefore;
+ }
+ if (posBefore > maxBefore) {
+ maxBefore = posBefore;
+ }
+ if (posAfter < minAfter) {
+ minAfter = posAfter;
+ }
+ if (posAfter > maxAfter) {
+ maxAfter = posAfter;
+ }
+ }
+ } catch (err) {
+ _didIteratorError3 = true;
+ _iteratorError3 = err;
+ } finally {
+ try {
+ if (!_iteratorNormalCompletion3 && _iterator3.return) {
+ _iterator3.return();
+ }
+ } finally {
+ if (_didIteratorError3) {
+ throw _iteratorError3;
+ }
+ }
+ }
+
+ var diff = (minBefore + maxBefore) / 2 - (minAfter + maxAfter) / 2;
+
+ var _iteratorNormalCompletion4 = true;
+ var _didIteratorError4 = false;
+ var _iteratorError4 = undefined;
+
+ try {
+ for (var _iterator4 = component[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
+ var _nodeId = _step4.value;
+
+ positionMap.set(_nodeId, positionMap.get(_nodeId) + diff);
+ }
+ } catch (err) {
+ _didIteratorError4 = true;
+ _iteratorError4 = err;
+ } finally {
+ try {
+ if (!_iteratorNormalCompletion4 && _iterator4.return) {
+ _iterator4.return();
+ }
+ } finally {
+ if (_didIteratorError4) {
+ throw _iteratorError4;
+ }
+ }
+ }
+ });
+ }
+
+ return positionMap;
+ };
+
+ // find transformation based on rel. placement constraints if there are both alignment and rel. placement constraints
+ // or if there are only rel. placement contraints where the largest component isn't sufficiently large
+ var applyReflectionForRelativePlacement = function applyReflectionForRelativePlacement(relativePlacementConstraints) {
+ // variables to count votes
+ var reflectOnY = 0,
+ notReflectOnY = 0;
+ var reflectOnX = 0,
+ notReflectOnX = 0;
+
+ relativePlacementConstraints.forEach(function (constraint) {
+ if (constraint.left) {
+ xCoords[nodeIndexes.get(constraint.left)] - xCoords[nodeIndexes.get(constraint.right)] >= 0 ? reflectOnY++ : notReflectOnY++;
+ } else {
+ yCoords[nodeIndexes.get(constraint.top)] - yCoords[nodeIndexes.get(constraint.bottom)] >= 0 ? reflectOnX++ : notReflectOnX++;
+ }
+ });
+
+ if (reflectOnY > notReflectOnY && reflectOnX > notReflectOnX) {
+ for (var _i = 0; _i < nodeIndexes.size; _i++) {
+ xCoords[_i] = -1 * xCoords[_i];
+ yCoords[_i] = -1 * yCoords[_i];
+ }
+ } else if (reflectOnY > notReflectOnY) {
+ for (var _i2 = 0; _i2 < nodeIndexes.size; _i2++) {
+ xCoords[_i2] = -1 * xCoords[_i2];
+ }
+ } else if (reflectOnX > notReflectOnX) {
+ for (var _i3 = 0; _i3 < nodeIndexes.size; _i3++) {
+ yCoords[_i3] = -1 * yCoords[_i3];
+ }
+ }
+ };
+
+ // find weakly connected components in undirected graph
+ var findComponents = function findComponents(graph) {
+ // find weakly connected components in dag
+ var components = [];
+ var queue = new LinkedList();
+ var visited = new Set();
+ var count = 0;
+
+ graph.forEach(function (value, key) {
+ if (!visited.has(key)) {
+ components[count] = [];
+ var _currentNode = key;
+ queue.push(_currentNode);
+ visited.add(_currentNode);
+ components[count].push(_currentNode);
+
+ while (queue.length != 0) {
+ _currentNode = queue.shift();
+ var neighbors = graph.get(_currentNode);
+ neighbors.forEach(function (neighbor) {
+ if (!visited.has(neighbor.id)) {
+ queue.push(neighbor.id);
+ visited.add(neighbor.id);
+ components[count].push(neighbor.id);
+ }
+ });
+ }
+ count++;
+ }
+ });
+ return components;
+ };
+
+ // return undirected version of given dag
+ var dagToUndirected = function dagToUndirected(dag) {
+ var undirected = new Map();
+
+ dag.forEach(function (value, key) {
+ undirected.set(key, []);
+ });
+
+ dag.forEach(function (value, key) {
+ value.forEach(function (adjacent) {
+ undirected.get(key).push(adjacent);
+ undirected.get(adjacent.id).push({ id: key, gap: adjacent.gap, direction: adjacent.direction });
+ });
+ });
+
+ return undirected;
+ };
+
+ // return reversed (directions inverted) version of given dag
+ var dagToReversed = function dagToReversed(dag) {
+ var reversed = new Map();
+
+ dag.forEach(function (value, key) {
+ reversed.set(key, []);
+ });
+
+ dag.forEach(function (value, key) {
+ value.forEach(function (adjacent) {
+ reversed.get(adjacent.id).push({ id: key, gap: adjacent.gap, direction: adjacent.direction });
+ });
+ });
+
+ return reversed;
+ };
+
+ /**** apply transformation to the initial draft layout to better align with constrained nodes ****/
+ // solve the Orthogonal Procrustean Problem to rotate and/or reflect initial draft layout
+ // here we follow the solution in Chapter 20.2 of Borg, I. & Groenen, P. (2005) Modern Multidimensional Scaling: Theory and Applications
+
+ /* construct source and target configurations */
+
+ var targetMatrix = []; // A - target configuration
+ var sourceMatrix = []; // B - source configuration
+ var standardTransformation = false; // false for no transformation, true for standart (Procrustes) transformation (rotation and/or reflection)
+ var reflectionType = false; // false/true for reflection check, 'reflectOnX', 'reflectOnY' or 'reflectOnBoth' for reflection type if necessary
+ var fixedNodes = new Set();
+ var dag = new Map(); // adjacency list to keep directed acyclic graph (dag) that consists of relative placement constraints
+ var dagUndirected = new Map(); // undirected version of the dag
+ var components = []; // weakly connected components
+
+ // fill fixedNodes collection to use later
+ if (constraints.fixedNodeConstraint) {
+ constraints.fixedNodeConstraint.forEach(function (nodeData) {
+ fixedNodes.add(nodeData.nodeId);
+ });
+ }
+
+ // construct dag from relative placement constraints
+ if (constraints.relativePlacementConstraint) {
+ // construct both directed and undirected version of the dag
+ constraints.relativePlacementConstraint.forEach(function (constraint) {
+ if (constraint.left) {
+ if (dag.has(constraint.left)) {
+ dag.get(constraint.left).push({ id: constraint.right, gap: constraint.gap, direction: "horizontal" });
+ } else {
+ dag.set(constraint.left, [{ id: constraint.right, gap: constraint.gap, direction: "horizontal" }]);
+ }
+ if (!dag.has(constraint.right)) {
+ dag.set(constraint.right, []);
+ }
+ } else {
+ if (dag.has(constraint.top)) {
+ dag.get(constraint.top).push({ id: constraint.bottom, gap: constraint.gap, direction: "vertical" });
+ } else {
+ dag.set(constraint.top, [{ id: constraint.bottom, gap: constraint.gap, direction: "vertical" }]);
+ }
+ if (!dag.has(constraint.bottom)) {
+ dag.set(constraint.bottom, []);
+ }
+ }
+ });
+
+ dagUndirected = dagToUndirected(dag);
+ components = findComponents(dagUndirected);
+ }
+
+ if (CoSEConstants.TRANSFORM_ON_CONSTRAINT_HANDLING) {
+ // first check fixed node constraint
+ if (constraints.fixedNodeConstraint && constraints.fixedNodeConstraint.length > 1) {
+ constraints.fixedNodeConstraint.forEach(function (nodeData, i) {
+ targetMatrix[i] = [nodeData.position.x, nodeData.position.y];
+ sourceMatrix[i] = [xCoords[nodeIndexes.get(nodeData.nodeId)], yCoords[nodeIndexes.get(nodeData.nodeId)]];
+ });
+ standardTransformation = true;
+ } else if (constraints.alignmentConstraint) {
+ (function () {
+ // then check alignment constraint
+ var count = 0;
+ if (constraints.alignmentConstraint.vertical) {
+ var verticalAlign = constraints.alignmentConstraint.vertical;
+
+ var _loop2 = function _loop2(_i4) {
+ var alignmentSet = new Set();
+ verticalAlign[_i4].forEach(function (nodeId) {
+ alignmentSet.add(nodeId);
+ });
+ var intersection = new Set([].concat(_toConsumableArray(alignmentSet)).filter(function (x) {
+ return fixedNodes.has(x);
+ }));
+ var xPos = void 0;
+ if (intersection.size > 0) xPos = xCoords[nodeIndexes.get(intersection.values().next().value)];else xPos = calculateAvgPosition(alignmentSet).x;
+
+ verticalAlign[_i4].forEach(function (nodeId) {
+ targetMatrix[count] = [xPos, yCoords[nodeIndexes.get(nodeId)]];
+ sourceMatrix[count] = [xCoords[nodeIndexes.get(nodeId)], yCoords[nodeIndexes.get(nodeId)]];
+ count++;
+ });
+ };
+
+ for (var _i4 = 0; _i4 < verticalAlign.length; _i4++) {
+ _loop2(_i4);
+ }
+ standardTransformation = true;
+ }
+ if (constraints.alignmentConstraint.horizontal) {
+ var horizontalAlign = constraints.alignmentConstraint.horizontal;
+
+ var _loop3 = function _loop3(_i5) {
+ var alignmentSet = new Set();
+ horizontalAlign[_i5].forEach(function (nodeId) {
+ alignmentSet.add(nodeId);
+ });
+ var intersection = new Set([].concat(_toConsumableArray(alignmentSet)).filter(function (x) {
+ return fixedNodes.has(x);
+ }));
+ var yPos = void 0;
+ if (intersection.size > 0) yPos = xCoords[nodeIndexes.get(intersection.values().next().value)];else yPos = calculateAvgPosition(alignmentSet).y;
+
+ horizontalAlign[_i5].forEach(function (nodeId) {
+ targetMatrix[count] = [xCoords[nodeIndexes.get(nodeId)], yPos];
+ sourceMatrix[count] = [xCoords[nodeIndexes.get(nodeId)], yCoords[nodeIndexes.get(nodeId)]];
+ count++;
+ });
+ };
+
+ for (var _i5 = 0; _i5 < horizontalAlign.length; _i5++) {
+ _loop3(_i5);
+ }
+ standardTransformation = true;
+ }
+ if (constraints.relativePlacementConstraint) {
+ reflectionType = true;
+ }
+ })();
+ } else if (constraints.relativePlacementConstraint) {
+ // finally check relative placement constraint
+ // find largest component in dag
+ var largestComponentSize = 0;
+ var largestComponentIndex = 0;
+ for (var _i6 = 0; _i6 < components.length; _i6++) {
+ if (components[_i6].length > largestComponentSize) {
+ largestComponentSize = components[_i6].length;
+ largestComponentIndex = _i6;
+ }
+ }
+ // if largest component isn't dominant, then take the votes for reflection
+ if (largestComponentSize < dagUndirected.size / 2) {
+ applyReflectionForRelativePlacement(constraints.relativePlacementConstraint);
+ standardTransformation = false;
+ reflectionType = false;
+ } else {
+ // use largest component for transformation
+ // construct horizontal and vertical subgraphs in the largest component
+ var subGraphOnHorizontal = new Map();
+ var subGraphOnVertical = new Map();
+ var constraintsInlargestComponent = [];
+
+ components[largestComponentIndex].forEach(function (nodeId) {
+ dag.get(nodeId).forEach(function (adjacent) {
+ if (adjacent.direction == "horizontal") {
+ if (subGraphOnHorizontal.has(nodeId)) {
+ subGraphOnHorizontal.get(nodeId).push(adjacent);
+ } else {
+ subGraphOnHorizontal.set(nodeId, [adjacent]);
+ }
+ if (!subGraphOnHorizontal.has(adjacent.id)) {
+ subGraphOnHorizontal.set(adjacent.id, []);
+ }
+ constraintsInlargestComponent.push({ left: nodeId, right: adjacent.id });
+ } else {
+ if (subGraphOnVertical.has(nodeId)) {
+ subGraphOnVertical.get(nodeId).push(adjacent);
+ } else {
+ subGraphOnVertical.set(nodeId, [adjacent]);
+ }
+ if (!subGraphOnVertical.has(adjacent.id)) {
+ subGraphOnVertical.set(adjacent.id, []);
+ }
+ constraintsInlargestComponent.push({ top: nodeId, bottom: adjacent.id });
+ }
+ });
+ });
+
+ applyReflectionForRelativePlacement(constraintsInlargestComponent);
+ reflectionType = false;
+
+ // calculate appropriate positioning for subgraphs
+ var positionMapHorizontal = findAppropriatePositionForRelativePlacement(subGraphOnHorizontal, "horizontal");
+ var positionMapVertical = findAppropriatePositionForRelativePlacement(subGraphOnVertical, "vertical");
+
+ // construct source and target configuration
+ components[largestComponentIndex].forEach(function (nodeId, i) {
+ sourceMatrix[i] = [xCoords[nodeIndexes.get(nodeId)], yCoords[nodeIndexes.get(nodeId)]];
+ targetMatrix[i] = [];
+ if (positionMapHorizontal.has(nodeId)) {
+ targetMatrix[i][0] = positionMapHorizontal.get(nodeId);
+ } else {
+ targetMatrix[i][0] = xCoords[nodeIndexes.get(nodeId)];
+ }
+ if (positionMapVertical.has(nodeId)) {
+ targetMatrix[i][1] = positionMapVertical.get(nodeId);
+ } else {
+ targetMatrix[i][1] = yCoords[nodeIndexes.get(nodeId)];
+ }
+ });
+
+ standardTransformation = true;
+ }
+ }
+
+ // if transformation is required, then calculate and apply transformation matrix
+ if (standardTransformation) {
+ /* calculate transformation matrix */
+ var transformationMatrix = void 0;
+ var targetMatrixTranspose = Matrix.transpose(targetMatrix); // A'
+ var sourceMatrixTranspose = Matrix.transpose(sourceMatrix); // B'
+
+ // centralize transpose matrices
+ for (var _i7 = 0; _i7 < targetMatrixTranspose.length; _i7++) {
+ targetMatrixTranspose[_i7] = Matrix.multGamma(targetMatrixTranspose[_i7]);
+ sourceMatrixTranspose[_i7] = Matrix.multGamma(sourceMatrixTranspose[_i7]);
+ }
+
+ // do actual calculation for transformation matrix
+ var tempMatrix = Matrix.multMat(targetMatrixTranspose, Matrix.transpose(sourceMatrixTranspose)); // tempMatrix = A'B
+ var SVDResult = SVD.svd(tempMatrix); // SVD(A'B) = USV', svd function returns U, S and V
+ transformationMatrix = Matrix.multMat(SVDResult.V, Matrix.transpose(SVDResult.U)); // transformationMatrix = T = VU'
+
+ /* apply found transformation matrix to obtain final draft layout */
+ for (var _i8 = 0; _i8 < nodeIndexes.size; _i8++) {
+ var temp1 = [xCoords[_i8], yCoords[_i8]];
+ var temp2 = [transformationMatrix[0][0], transformationMatrix[1][0]];
+ var temp3 = [transformationMatrix[0][1], transformationMatrix[1][1]];
+ xCoords[_i8] = Matrix.dotProduct(temp1, temp2);
+ yCoords[_i8] = Matrix.dotProduct(temp1, temp3);
+ }
+
+ // applied only both alignment and rel. placement constraints exist
+ if (reflectionType) {
+ applyReflectionForRelativePlacement(constraints.relativePlacementConstraint);
+ }
+ }
+ }
+
+ if (CoSEConstants.ENFORCE_CONSTRAINTS) {
+ /**** enforce constraints on the transformed draft layout ****/
+
+ /* first enforce fixed node constraint */
+
+ if (constraints.fixedNodeConstraint && constraints.fixedNodeConstraint.length > 0) {
+ var translationAmount = { x: 0, y: 0 };
+ constraints.fixedNodeConstraint.forEach(function (nodeData, i) {
+ var posInTheory = { x: xCoords[nodeIndexes.get(nodeData.nodeId)], y: yCoords[nodeIndexes.get(nodeData.nodeId)] };
+ var posDesired = nodeData.position;
+ var posDiff = calculatePositionDiff(posDesired, posInTheory);
+ translationAmount.x += posDiff.x;
+ translationAmount.y += posDiff.y;
+ });
+ translationAmount.x /= constraints.fixedNodeConstraint.length;
+ translationAmount.y /= constraints.fixedNodeConstraint.length;
+
+ xCoords.forEach(function (value, i) {
+ xCoords[i] += translationAmount.x;
+ });
+
+ yCoords.forEach(function (value, i) {
+ yCoords[i] += translationAmount.y;
+ });
+
+ constraints.fixedNodeConstraint.forEach(function (nodeData) {
+ xCoords[nodeIndexes.get(nodeData.nodeId)] = nodeData.position.x;
+ yCoords[nodeIndexes.get(nodeData.nodeId)] = nodeData.position.y;
+ });
+ }
+
+ /* then enforce alignment constraint */
+
+ if (constraints.alignmentConstraint) {
+ if (constraints.alignmentConstraint.vertical) {
+ var xAlign = constraints.alignmentConstraint.vertical;
+
+ var _loop4 = function _loop4(_i9) {
+ var alignmentSet = new Set();
+ xAlign[_i9].forEach(function (nodeId) {
+ alignmentSet.add(nodeId);
+ });
+ var intersection = new Set([].concat(_toConsumableArray(alignmentSet)).filter(function (x) {
+ return fixedNodes.has(x);
+ }));
+ var xPos = void 0;
+ if (intersection.size > 0) xPos = xCoords[nodeIndexes.get(intersection.values().next().value)];else xPos = calculateAvgPosition(alignmentSet).x;
+
+ alignmentSet.forEach(function (nodeId) {
+ if (!fixedNodes.has(nodeId)) xCoords[nodeIndexes.get(nodeId)] = xPos;
+ });
+ };
+
+ for (var _i9 = 0; _i9 < xAlign.length; _i9++) {
+ _loop4(_i9);
+ }
+ }
+ if (constraints.alignmentConstraint.horizontal) {
+ var yAlign = constraints.alignmentConstraint.horizontal;
+
+ var _loop5 = function _loop5(_i10) {
+ var alignmentSet = new Set();
+ yAlign[_i10].forEach(function (nodeId) {
+ alignmentSet.add(nodeId);
+ });
+ var intersection = new Set([].concat(_toConsumableArray(alignmentSet)).filter(function (x) {
+ return fixedNodes.has(x);
+ }));
+ var yPos = void 0;
+ if (intersection.size > 0) yPos = yCoords[nodeIndexes.get(intersection.values().next().value)];else yPos = calculateAvgPosition(alignmentSet).y;
+
+ alignmentSet.forEach(function (nodeId) {
+ if (!fixedNodes.has(nodeId)) yCoords[nodeIndexes.get(nodeId)] = yPos;
+ });
+ };
+
+ for (var _i10 = 0; _i10 < yAlign.length; _i10++) {
+ _loop5(_i10);
+ }
+ }
+ }
+
+ /* finally enforce relative placement constraint */
+
+ if (constraints.relativePlacementConstraint) {
+ (function () {
+ var nodeToDummyForVerticalAlignment = new Map();
+ var nodeToDummyForHorizontalAlignment = new Map();
+ var dummyToNodeForVerticalAlignment = new Map();
+ var dummyToNodeForHorizontalAlignment = new Map();
+ var dummyPositionsForVerticalAlignment = new Map();
+ var dummyPositionsForHorizontalAlignment = new Map();
+ var fixedNodesOnHorizontal = new Set();
+ var fixedNodesOnVertical = new Set();
+
+ // fill maps and sets
+ fixedNodes.forEach(function (nodeId) {
+ fixedNodesOnHorizontal.add(nodeId);
+ fixedNodesOnVertical.add(nodeId);
+ });
+
+ if (constraints.alignmentConstraint) {
+ if (constraints.alignmentConstraint.vertical) {
+ var verticalAlignment = constraints.alignmentConstraint.vertical;
+
+ var _loop6 = function _loop6(_i11) {
+ dummyToNodeForVerticalAlignment.set("dummy" + _i11, []);
+ verticalAlignment[_i11].forEach(function (nodeId) {
+ nodeToDummyForVerticalAlignment.set(nodeId, "dummy" + _i11);
+ dummyToNodeForVerticalAlignment.get("dummy" + _i11).push(nodeId);
+ if (fixedNodes.has(nodeId)) {
+ fixedNodesOnHorizontal.add("dummy" + _i11);
+ }
+ });
+ dummyPositionsForVerticalAlignment.set("dummy" + _i11, xCoords[nodeIndexes.get(verticalAlignment[_i11][0])]);
+ };
+
+ for (var _i11 = 0; _i11 < verticalAlignment.length; _i11++) {
+ _loop6(_i11);
+ }
+ }
+ if (constraints.alignmentConstraint.horizontal) {
+ var horizontalAlignment = constraints.alignmentConstraint.horizontal;
+
+ var _loop7 = function _loop7(_i12) {
+ dummyToNodeForHorizontalAlignment.set("dummy" + _i12, []);
+ horizontalAlignment[_i12].forEach(function (nodeId) {
+ nodeToDummyForHorizontalAlignment.set(nodeId, "dummy" + _i12);
+ dummyToNodeForHorizontalAlignment.get("dummy" + _i12).push(nodeId);
+ if (fixedNodes.has(nodeId)) {
+ fixedNodesOnVertical.add("dummy" + _i12);
+ }
+ });
+ dummyPositionsForHorizontalAlignment.set("dummy" + _i12, yCoords[nodeIndexes.get(horizontalAlignment[_i12][0])]);
+ };
+
+ for (var _i12 = 0; _i12 < horizontalAlignment.length; _i12++) {
+ _loop7(_i12);
+ }
+ }
+ }
+
+ // construct horizontal and vertical dags (subgraphs) from overall dag
+ var dagOnHorizontal = new Map();
+ var dagOnVertical = new Map();
+
+ var _loop8 = function _loop8(nodeId) {
+ dag.get(nodeId).forEach(function (adjacent) {
+ var sourceId = void 0;
+ var targetNode = void 0;
+ if (adjacent["direction"] == "horizontal") {
+ sourceId = nodeToDummyForVerticalAlignment.get(nodeId) ? nodeToDummyForVerticalAlignment.get(nodeId) : nodeId;
+ if (nodeToDummyForVerticalAlignment.get(adjacent.id)) {
+ targetNode = { id: nodeToDummyForVerticalAlignment.get(adjacent.id), gap: adjacent.gap, direction: adjacent.direction };
+ } else {
+ targetNode = adjacent;
+ }
+ if (dagOnHorizontal.has(sourceId)) {
+ dagOnHorizontal.get(sourceId).push(targetNode);
+ } else {
+ dagOnHorizontal.set(sourceId, [targetNode]);
+ }
+ if (!dagOnHorizontal.has(targetNode.id)) {
+ dagOnHorizontal.set(targetNode.id, []);
+ }
+ } else {
+ sourceId = nodeToDummyForHorizontalAlignment.get(nodeId) ? nodeToDummyForHorizontalAlignment.get(nodeId) : nodeId;
+ if (nodeToDummyForHorizontalAlignment.get(adjacent.id)) {
+ targetNode = { id: nodeToDummyForHorizontalAlignment.get(adjacent.id), gap: adjacent.gap, direction: adjacent.direction };
+ } else {
+ targetNode = adjacent;
+ }
+ if (dagOnVertical.has(sourceId)) {
+ dagOnVertical.get(sourceId).push(targetNode);
+ } else {
+ dagOnVertical.set(sourceId, [targetNode]);
+ }
+ if (!dagOnVertical.has(targetNode.id)) {
+ dagOnVertical.set(targetNode.id, []);
+ }
+ }
+ });
+ };
+
+ var _iteratorNormalCompletion5 = true;
+ var _didIteratorError5 = false;
+ var _iteratorError5 = undefined;
+
+ try {
+ for (var _iterator5 = dag.keys()[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {
+ var nodeId = _step5.value;
+
+ _loop8(nodeId);
+ }
+
+ // find source nodes of each component in horizontal and vertical dags
+ } catch (err) {
+ _didIteratorError5 = true;
+ _iteratorError5 = err;
+ } finally {
+ try {
+ if (!_iteratorNormalCompletion5 && _iterator5.return) {
+ _iterator5.return();
+ }
+ } finally {
+ if (_didIteratorError5) {
+ throw _iteratorError5;
+ }
+ }
+ }
+
+ var undirectedOnHorizontal = dagToUndirected(dagOnHorizontal);
+ var undirectedOnVertical = dagToUndirected(dagOnVertical);
+ var componentsOnHorizontal = findComponents(undirectedOnHorizontal);
+ var componentsOnVertical = findComponents(undirectedOnVertical);
+ var reversedDagOnHorizontal = dagToReversed(dagOnHorizontal);
+ var reversedDagOnVertical = dagToReversed(dagOnVertical);
+ var componentSourcesOnHorizontal = [];
+ var componentSourcesOnVertical = [];
+
+ componentsOnHorizontal.forEach(function (component, index) {
+ componentSourcesOnHorizontal[index] = [];
+ component.forEach(function (nodeId) {
+ if (reversedDagOnHorizontal.get(nodeId).length == 0) {
+ componentSourcesOnHorizontal[index].push(nodeId);
+ }
+ });
+ });
+
+ componentsOnVertical.forEach(function (component, index) {
+ componentSourcesOnVertical[index] = [];
+ component.forEach(function (nodeId) {
+ if (reversedDagOnVertical.get(nodeId).length == 0) {
+ componentSourcesOnVertical[index].push(nodeId);
+ }
+ });
+ });
+
+ // calculate appropriate positioning for subgraphs
+ var positionMapHorizontal = findAppropriatePositionForRelativePlacement(dagOnHorizontal, "horizontal", fixedNodesOnHorizontal, dummyPositionsForVerticalAlignment, componentSourcesOnHorizontal);
+ var positionMapVertical = findAppropriatePositionForRelativePlacement(dagOnVertical, "vertical", fixedNodesOnVertical, dummyPositionsForHorizontalAlignment, componentSourcesOnVertical);
+
+ // update positions of the nodes based on relative placement constraints
+
+ var _loop9 = function _loop9(key) {
+ if (dummyToNodeForVerticalAlignment.get(key)) {
+ dummyToNodeForVerticalAlignment.get(key).forEach(function (nodeId) {
+ xCoords[nodeIndexes.get(nodeId)] = positionMapHorizontal.get(key);
+ });
+ } else {
+ xCoords[nodeIndexes.get(key)] = positionMapHorizontal.get(key);
+ }
+ };
+
+ var _iteratorNormalCompletion6 = true;
+ var _didIteratorError6 = false;
+ var _iteratorError6 = undefined;
+
+ try {
+ for (var _iterator6 = positionMapHorizontal.keys()[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) {
+ var key = _step6.value;
+
+ _loop9(key);
+ }
+ } catch (err) {
+ _didIteratorError6 = true;
+ _iteratorError6 = err;
+ } finally {
+ try {
+ if (!_iteratorNormalCompletion6 && _iterator6.return) {
+ _iterator6.return();
+ }
+ } finally {
+ if (_didIteratorError6) {
+ throw _iteratorError6;
+ }
+ }
+ }
+
+ var _loop10 = function _loop10(key) {
+ if (dummyToNodeForHorizontalAlignment.get(key)) {
+ dummyToNodeForHorizontalAlignment.get(key).forEach(function (nodeId) {
+ yCoords[nodeIndexes.get(nodeId)] = positionMapVertical.get(key);
+ });
+ } else {
+ yCoords[nodeIndexes.get(key)] = positionMapVertical.get(key);
+ }
+ };
+
+ var _iteratorNormalCompletion7 = true;
+ var _didIteratorError7 = false;
+ var _iteratorError7 = undefined;
+
+ try {
+ for (var _iterator7 = positionMapVertical.keys()[Symbol.iterator](), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) {
+ var key = _step7.value;
+
+ _loop10(key);
+ }
+ } catch (err) {
+ _didIteratorError7 = true;
+ _iteratorError7 = err;
+ } finally {
+ try {
+ if (!_iteratorNormalCompletion7 && _iterator7.return) {
+ _iterator7.return();
+ }
+ } finally {
+ if (_didIteratorError7) {
+ throw _iteratorError7;
+ }
+ }
+ }
+ })();
+ }
+ }
+
+ // assign new coordinates to nodes after constraint handling
+ for (var _i13 = 0; _i13 < allNodes.length; _i13++) {
+ var _node = allNodes[_i13];
+ if (_node.getChild() == null) {
+ _node.setCenter(xCoords[nodeIndexes.get(_node.id)], yCoords[nodeIndexes.get(_node.id)]);
+ }
+ }
+};
+
+module.exports = ConstraintHandler;
+
+/***/ }),
+
+/***/ 551:
+/***/ ((module) => {
+
+module.exports = __WEBPACK_EXTERNAL_MODULE__551__;
+
+/***/ })
+
+/******/ });
+/************************************************************************/
+/******/ // The module cache
+/******/ var __webpack_module_cache__ = {};
+/******/
+/******/ // The require function
+/******/ function __webpack_require__(moduleId) {
+/******/ // Check if module is in cache
+/******/ var cachedModule = __webpack_module_cache__[moduleId];
+/******/ if (cachedModule !== undefined) {
+/******/ return cachedModule.exports;
+/******/ }
+/******/ // Create a new module (and put it into the cache)
+/******/ var module = __webpack_module_cache__[moduleId] = {
+/******/ // no module.id needed
+/******/ // no module.loaded needed
+/******/ exports: {}
+/******/ };
+/******/
+/******/ // Execute the module function
+/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
+/******/
+/******/ // Return the exports of the module
+/******/ return module.exports;
+/******/ }
+/******/
+/************************************************************************/
+/******/
+/******/ // startup
+/******/ // Load entry module and return exports
+/******/ // This entry module is referenced by other modules so it can't be inlined
+/******/ var __webpack_exports__ = __webpack_require__(45);
+/******/
+/******/ return __webpack_exports__;
+/******/ })()
+;
+});
\ No newline at end of file
diff --git a/web/vendor/cytoscape-fcose.js b/web/vendor/cytoscape-fcose.js
new file mode 100644
index 0000000..9ad4f6e
--- /dev/null
+++ b/web/vendor/cytoscape-fcose.js
@@ -0,0 +1,1549 @@
+(function webpackUniversalModuleDefinition(root, factory) {
+ if(typeof exports === 'object' && typeof module === 'object')
+ module.exports = factory(require("cose-base"));
+ else if(typeof define === 'function' && define.amd)
+ define(["cose-base"], factory);
+ else if(typeof exports === 'object')
+ exports["cytoscapeFcose"] = factory(require("cose-base"));
+ else
+ root["cytoscapeFcose"] = factory(root["coseBase"]);
+})(this, function(__WEBPACK_EXTERNAL_MODULE__140__) {
+return /******/ (() => { // webpackBootstrap
+/******/ "use strict";
+/******/ var __webpack_modules__ = ({
+
+/***/ 658:
+/***/ ((module) => {
+
+
+
+// Simple, internal Object.assign() polyfill for options objects etc.
+
+module.exports = Object.assign != null ? Object.assign.bind(Object) : function (tgt) {
+ for (var _len = arguments.length, srcs = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
+ srcs[_key - 1] = arguments[_key];
+ }
+
+ srcs.forEach(function (src) {
+ Object.keys(src).forEach(function (k) {
+ return tgt[k] = src[k];
+ });
+ });
+
+ return tgt;
+};
+
+/***/ }),
+
+/***/ 548:
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+
+
+var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
+
+/*
+ * Auxiliary functions
+ */
+
+var LinkedList = __webpack_require__(140).layoutBase.LinkedList;
+
+var auxiliary = {};
+
+// get the top most nodes
+auxiliary.getTopMostNodes = function (nodes) {
+ var nodesMap = {};
+ for (var i = 0; i < nodes.length; i++) {
+ nodesMap[nodes[i].id()] = true;
+ }
+ var roots = nodes.filter(function (ele, i) {
+ if (typeof ele === "number") {
+ ele = i;
+ }
+ var parent = ele.parent()[0];
+ while (parent != null) {
+ if (nodesMap[parent.id()]) {
+ return false;
+ }
+ parent = parent.parent()[0];
+ }
+ return true;
+ });
+
+ return roots;
+};
+
+// find disconnected components and create dummy nodes that connect them
+auxiliary.connectComponents = function (cy, eles, topMostNodes, dummyNodes) {
+ var queue = new LinkedList();
+ var visited = new Set();
+ var visitedTopMostNodes = [];
+ var currentNeighbor = void 0;
+ var minDegreeNode = void 0;
+ var minDegree = void 0;
+
+ var isConnected = false;
+ var count = 1;
+ var nodesConnectedToDummy = [];
+ var components = [];
+
+ var _loop = function _loop() {
+ var cmpt = cy.collection();
+ components.push(cmpt);
+
+ var currentNode = topMostNodes[0];
+ var childrenOfCurrentNode = cy.collection();
+ childrenOfCurrentNode.merge(currentNode).merge(currentNode.descendants().intersection(eles));
+ visitedTopMostNodes.push(currentNode);
+
+ childrenOfCurrentNode.forEach(function (node) {
+ queue.push(node);
+ visited.add(node);
+ cmpt.merge(node);
+ });
+
+ var _loop2 = function _loop2() {
+ currentNode = queue.shift();
+
+ // Traverse all neighbors of this node
+ var neighborNodes = cy.collection();
+ currentNode.neighborhood().nodes().forEach(function (node) {
+ if (eles.intersection(currentNode.edgesWith(node)).length > 0) {
+ neighborNodes.merge(node);
+ }
+ });
+
+ for (var i = 0; i < neighborNodes.length; i++) {
+ var neighborNode = neighborNodes[i];
+ currentNeighbor = topMostNodes.intersection(neighborNode.union(neighborNode.ancestors()));
+ if (currentNeighbor != null && !visited.has(currentNeighbor[0])) {
+ var childrenOfNeighbor = currentNeighbor.union(currentNeighbor.descendants());
+
+ childrenOfNeighbor.forEach(function (node) {
+ queue.push(node);
+ visited.add(node);
+ cmpt.merge(node);
+ if (topMostNodes.has(node)) {
+ visitedTopMostNodes.push(node);
+ }
+ });
+ }
+ }
+ };
+
+ while (queue.length != 0) {
+ _loop2();
+ }
+
+ cmpt.forEach(function (node) {
+ eles.intersection(node.connectedEdges()).forEach(function (e) {
+ // connectedEdges() usually cached
+ if (cmpt.has(e.source()) && cmpt.has(e.target())) {
+ // has() is cheap
+ cmpt.merge(e);
+ }
+ });
+ });
+
+ if (visitedTopMostNodes.length == topMostNodes.length) {
+ isConnected = true;
+ }
+
+ if (!isConnected || isConnected && count > 1) {
+ minDegreeNode = visitedTopMostNodes[0];
+ minDegree = minDegreeNode.connectedEdges().length;
+ visitedTopMostNodes.forEach(function (node) {
+ if (node.connectedEdges().length < minDegree) {
+ minDegree = node.connectedEdges().length;
+ minDegreeNode = node;
+ }
+ });
+ nodesConnectedToDummy.push(minDegreeNode.id());
+ // TO DO: Check efficiency of this part
+ var temp = cy.collection();
+ temp.merge(visitedTopMostNodes[0]);
+ visitedTopMostNodes.forEach(function (node) {
+ temp.merge(node);
+ });
+ visitedTopMostNodes = [];
+ topMostNodes = topMostNodes.difference(temp);
+ count++;
+ }
+ };
+
+ do {
+ _loop();
+ } while (!isConnected);
+
+ if (dummyNodes) {
+ if (nodesConnectedToDummy.length > 0) {
+ dummyNodes.set('dummy' + (dummyNodes.size + 1), nodesConnectedToDummy);
+ }
+ }
+ return components;
+};
+
+// relocates componentResult to originalCenter if there is no fixedNodeConstraint
+auxiliary.relocateComponent = function (originalCenter, componentResult, options) {
+ if (!options.fixedNodeConstraint) {
+ var minXCoord = Number.POSITIVE_INFINITY;
+ var maxXCoord = Number.NEGATIVE_INFINITY;
+ var minYCoord = Number.POSITIVE_INFINITY;
+ var maxYCoord = Number.NEGATIVE_INFINITY;
+ if (options.quality == "draft") {
+ // calculate current bounding box
+ var _iteratorNormalCompletion = true;
+ var _didIteratorError = false;
+ var _iteratorError = undefined;
+
+ try {
+ for (var _iterator = componentResult.nodeIndexes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
+ var _ref = _step.value;
+
+ var _ref2 = _slicedToArray(_ref, 2);
+
+ var key = _ref2[0];
+ var value = _ref2[1];
+
+ var cyNode = options.cy.getElementById(key);
+ if (cyNode) {
+ var nodeBB = cyNode.boundingBox();
+ var leftX = componentResult.xCoords[value] - nodeBB.w / 2;
+ var rightX = componentResult.xCoords[value] + nodeBB.w / 2;
+ var topY = componentResult.yCoords[value] - nodeBB.h / 2;
+ var bottomY = componentResult.yCoords[value] + nodeBB.h / 2;
+
+ if (leftX < minXCoord) minXCoord = leftX;
+ if (rightX > maxXCoord) maxXCoord = rightX;
+ if (topY < minYCoord) minYCoord = topY;
+ if (bottomY > maxYCoord) maxYCoord = bottomY;
+ }
+ }
+ // find difference between current and original center
+ } catch (err) {
+ _didIteratorError = true;
+ _iteratorError = err;
+ } finally {
+ try {
+ if (!_iteratorNormalCompletion && _iterator.return) {
+ _iterator.return();
+ }
+ } finally {
+ if (_didIteratorError) {
+ throw _iteratorError;
+ }
+ }
+ }
+
+ var diffOnX = originalCenter.x - (maxXCoord + minXCoord) / 2;
+ var diffOnY = originalCenter.y - (maxYCoord + minYCoord) / 2;
+ // move component to original center
+ componentResult.xCoords = componentResult.xCoords.map(function (x) {
+ return x + diffOnX;
+ });
+ componentResult.yCoords = componentResult.yCoords.map(function (y) {
+ return y + diffOnY;
+ });
+ } else {
+ // calculate current bounding box
+ Object.keys(componentResult).forEach(function (item) {
+ var node = componentResult[item];
+ var leftX = node.getRect().x;
+ var rightX = node.getRect().x + node.getRect().width;
+ var topY = node.getRect().y;
+ var bottomY = node.getRect().y + node.getRect().height;
+
+ if (leftX < minXCoord) minXCoord = leftX;
+ if (rightX > maxXCoord) maxXCoord = rightX;
+ if (topY < minYCoord) minYCoord = topY;
+ if (bottomY > maxYCoord) maxYCoord = bottomY;
+ });
+ // find difference between current and original center
+ var _diffOnX = originalCenter.x - (maxXCoord + minXCoord) / 2;
+ var _diffOnY = originalCenter.y - (maxYCoord + minYCoord) / 2;
+ // move component to original center
+ Object.keys(componentResult).forEach(function (item) {
+ var node = componentResult[item];
+ node.setCenter(node.getCenterX() + _diffOnX, node.getCenterY() + _diffOnY);
+ });
+ }
+ }
+};
+
+auxiliary.calcBoundingBox = function (parentNode, xCoords, yCoords, nodeIndexes) {
+ // calculate bounds
+ var left = Number.MAX_SAFE_INTEGER;
+ var right = Number.MIN_SAFE_INTEGER;
+ var top = Number.MAX_SAFE_INTEGER;
+ var bottom = Number.MIN_SAFE_INTEGER;
+ var nodeLeft = void 0;
+ var nodeRight = void 0;
+ var nodeTop = void 0;
+ var nodeBottom = void 0;
+
+ var nodes = parentNode.descendants().not(":parent");
+ var s = nodes.length;
+ for (var i = 0; i < s; i++) {
+ var node = nodes[i];
+
+ nodeLeft = xCoords[nodeIndexes.get(node.id())] - node.width() / 2;
+ nodeRight = xCoords[nodeIndexes.get(node.id())] + node.width() / 2;
+ nodeTop = yCoords[nodeIndexes.get(node.id())] - node.height() / 2;
+ nodeBottom = yCoords[nodeIndexes.get(node.id())] + node.height() / 2;
+
+ if (left > nodeLeft) {
+ left = nodeLeft;
+ }
+
+ if (right < nodeRight) {
+ right = nodeRight;
+ }
+
+ if (top > nodeTop) {
+ top = nodeTop;
+ }
+
+ if (bottom < nodeBottom) {
+ bottom = nodeBottom;
+ }
+ }
+
+ var boundingBox = {};
+ boundingBox.topLeftX = left;
+ boundingBox.topLeftY = top;
+ boundingBox.width = right - left;
+ boundingBox.height = bottom - top;
+ return boundingBox;
+};
+
+// This function finds and returns parent nodes whose all children are hidden
+auxiliary.calcParentsWithoutChildren = function (cy, eles) {
+ var parentsWithoutChildren = cy.collection();
+ eles.nodes(':parent').forEach(function (parent) {
+ var check = false;
+ parent.children().forEach(function (child) {
+ if (child.css('display') != 'none') {
+ check = true;
+ }
+ });
+ if (!check) {
+ parentsWithoutChildren.merge(parent);
+ }
+ });
+
+ return parentsWithoutChildren;
+};
+
+module.exports = auxiliary;
+
+/***/ }),
+
+/***/ 816:
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+
+
+/**
+ The implementation of the postprocessing part that applies CoSE layout over the spectral layout
+*/
+
+var aux = __webpack_require__(548);
+var CoSELayout = __webpack_require__(140).CoSELayout;
+var CoSENode = __webpack_require__(140).CoSENode;
+var PointD = __webpack_require__(140).layoutBase.PointD;
+var DimensionD = __webpack_require__(140).layoutBase.DimensionD;
+var LayoutConstants = __webpack_require__(140).layoutBase.LayoutConstants;
+var FDLayoutConstants = __webpack_require__(140).layoutBase.FDLayoutConstants;
+var CoSEConstants = __webpack_require__(140).CoSEConstants;
+
+// main function that cose layout is processed
+var coseLayout = function coseLayout(options, spectralResult) {
+
+ var cy = options.cy;
+ var eles = options.eles;
+ var nodes = eles.nodes();
+ var edges = eles.edges();
+
+ var nodeIndexes = void 0;
+ var xCoords = void 0;
+ var yCoords = void 0;
+ var idToLNode = {};
+
+ if (options.randomize) {
+ nodeIndexes = spectralResult["nodeIndexes"];
+ xCoords = spectralResult["xCoords"];
+ yCoords = spectralResult["yCoords"];
+ }
+
+ var isFn = function isFn(fn) {
+ return typeof fn === 'function';
+ };
+
+ var optFn = function optFn(opt, ele) {
+ if (isFn(opt)) {
+ return opt(ele);
+ } else {
+ return opt;
+ }
+ };
+
+ /**** Postprocessing functions ****/
+
+ var parentsWithoutChildren = aux.calcParentsWithoutChildren(cy, eles);
+
+ // transfer cytoscape nodes to cose nodes
+ var processChildrenList = function processChildrenList(parent, children, layout, options) {
+ var size = children.length;
+ for (var i = 0; i < size; i++) {
+ var theChild = children[i];
+ var children_of_children = null;
+ if (theChild.intersection(parentsWithoutChildren).length == 0) {
+ children_of_children = theChild.children();
+ }
+ var theNode = void 0;
+
+ var dimensions = theChild.layoutDimensions({
+ nodeDimensionsIncludeLabels: options.nodeDimensionsIncludeLabels
+ });
+
+ if (theChild.outerWidth() != null && theChild.outerHeight() != null) {
+ if (options.randomize) {
+ if (!theChild.isParent()) {
+ theNode = parent.add(new CoSENode(layout.graphManager, new PointD(xCoords[nodeIndexes.get(theChild.id())] - dimensions.w / 2, yCoords[nodeIndexes.get(theChild.id())] - dimensions.h / 2), new DimensionD(parseFloat(dimensions.w), parseFloat(dimensions.h))));
+ } else {
+ var parentInfo = aux.calcBoundingBox(theChild, xCoords, yCoords, nodeIndexes);
+ if (theChild.intersection(parentsWithoutChildren).length == 0) {
+ theNode = parent.add(new CoSENode(layout.graphManager, new PointD(parentInfo.topLeftX, parentInfo.topLeftY), new DimensionD(parentInfo.width, parentInfo.height)));
+ } else {
+ // for the parentsWithoutChildren
+ theNode = parent.add(new CoSENode(layout.graphManager, new PointD(parentInfo.topLeftX, parentInfo.topLeftY), new DimensionD(parseFloat(dimensions.w), parseFloat(dimensions.h))));
+ }
+ }
+ } else {
+ theNode = parent.add(new CoSENode(layout.graphManager, new PointD(theChild.position('x') - dimensions.w / 2, theChild.position('y') - dimensions.h / 2), new DimensionD(parseFloat(dimensions.w), parseFloat(dimensions.h))));
+ }
+ } else {
+ theNode = parent.add(new CoSENode(this.graphManager));
+ }
+ // Attach id to the layout node and repulsion value
+ theNode.id = theChild.data("id");
+ theNode.nodeRepulsion = optFn(options.nodeRepulsion, theChild);
+ // Attach the paddings of cy node to layout node
+ theNode.paddingLeft = parseInt(theChild.css('padding'));
+ theNode.paddingTop = parseInt(theChild.css('padding'));
+ theNode.paddingRight = parseInt(theChild.css('padding'));
+ theNode.paddingBottom = parseInt(theChild.css('padding'));
+
+ //Attach the label properties to both compound and simple nodes if labels will be included in node dimensions
+ //These properties will be used while updating bounds of compounds during iterations or tiling
+ //and will be used for simple nodes while transferring final positions to cytoscape
+ if (options.nodeDimensionsIncludeLabels) {
+ theNode.labelWidth = theChild.boundingBox({ includeLabels: true, includeNodes: false, includeOverlays: false }).w;
+ theNode.labelHeight = theChild.boundingBox({ includeLabels: true, includeNodes: false, includeOverlays: false }).h;
+ theNode.labelPosVertical = theChild.css("text-valign");
+ theNode.labelPosHorizontal = theChild.css("text-halign");
+ }
+
+ // Map the layout node
+ idToLNode[theChild.data("id")] = theNode;
+
+ if (isNaN(theNode.rect.x)) {
+ theNode.rect.x = 0;
+ }
+
+ if (isNaN(theNode.rect.y)) {
+ theNode.rect.y = 0;
+ }
+
+ if (children_of_children != null && children_of_children.length > 0) {
+ var theNewGraph = void 0;
+ theNewGraph = layout.getGraphManager().add(layout.newGraph(), theNode);
+ processChildrenList(theNewGraph, children_of_children, layout, options);
+ }
+ }
+ };
+
+ // transfer cytoscape edges to cose edges
+ var processEdges = function processEdges(layout, gm, edges) {
+ var idealLengthTotal = 0;
+ var edgeCount = 0;
+ for (var i = 0; i < edges.length; i++) {
+ var edge = edges[i];
+ var sourceNode = idToLNode[edge.data("source")];
+ var targetNode = idToLNode[edge.data("target")];
+ if (sourceNode && targetNode && sourceNode !== targetNode && sourceNode.getEdgesBetween(targetNode).length == 0) {
+ var e1 = gm.add(layout.newEdge(), sourceNode, targetNode);
+ e1.id = edge.id();
+ e1.idealLength = optFn(options.idealEdgeLength, edge);
+ e1.edgeElasticity = optFn(options.edgeElasticity, edge);
+ idealLengthTotal += e1.idealLength;
+ edgeCount++;
+ }
+ }
+ // we need to update the ideal edge length constant with the avg. ideal length value after processing edges
+ // in case there is no edge, use other options
+ if (options.idealEdgeLength != null) {
+ if (edgeCount > 0) CoSEConstants.DEFAULT_EDGE_LENGTH = FDLayoutConstants.DEFAULT_EDGE_LENGTH = idealLengthTotal / edgeCount;else if (!isFn(options.idealEdgeLength)) // in case there is no edge, but option gives a value to use
+ CoSEConstants.DEFAULT_EDGE_LENGTH = FDLayoutConstants.DEFAULT_EDGE_LENGTH = options.idealEdgeLength;else // in case there is no edge and we cannot get a value from option (because it's a function)
+ CoSEConstants.DEFAULT_EDGE_LENGTH = FDLayoutConstants.DEFAULT_EDGE_LENGTH = 50;
+ // we need to update these constant values based on the ideal edge length constant
+ CoSEConstants.MIN_REPULSION_DIST = FDLayoutConstants.MIN_REPULSION_DIST = FDLayoutConstants.DEFAULT_EDGE_LENGTH / 10.0;
+ CoSEConstants.DEFAULT_RADIAL_SEPARATION = FDLayoutConstants.DEFAULT_EDGE_LENGTH;
+ }
+ };
+
+ // transfer cytoscape constraints to cose layout
+ var processConstraints = function processConstraints(layout, options) {
+ // get nodes to be fixed
+ if (options.fixedNodeConstraint) {
+ layout.constraints["fixedNodeConstraint"] = options.fixedNodeConstraint;
+ }
+ // get nodes to be aligned
+ if (options.alignmentConstraint) {
+ layout.constraints["alignmentConstraint"] = options.alignmentConstraint;
+ }
+ // get nodes to be relatively placed
+ if (options.relativePlacementConstraint) {
+ layout.constraints["relativePlacementConstraint"] = options.relativePlacementConstraint;
+ }
+ };
+
+ /**** Apply postprocessing ****/
+ if (options.nestingFactor != null) CoSEConstants.PER_LEVEL_IDEAL_EDGE_LENGTH_FACTOR = FDLayoutConstants.PER_LEVEL_IDEAL_EDGE_LENGTH_FACTOR = options.nestingFactor;
+ if (options.gravity != null) CoSEConstants.DEFAULT_GRAVITY_STRENGTH = FDLayoutConstants.DEFAULT_GRAVITY_STRENGTH = options.gravity;
+ if (options.numIter != null) CoSEConstants.MAX_ITERATIONS = FDLayoutConstants.MAX_ITERATIONS = options.numIter;
+ if (options.gravityRange != null) CoSEConstants.DEFAULT_GRAVITY_RANGE_FACTOR = FDLayoutConstants.DEFAULT_GRAVITY_RANGE_FACTOR = options.gravityRange;
+ if (options.gravityCompound != null) CoSEConstants.DEFAULT_COMPOUND_GRAVITY_STRENGTH = FDLayoutConstants.DEFAULT_COMPOUND_GRAVITY_STRENGTH = options.gravityCompound;
+ if (options.gravityRangeCompound != null) CoSEConstants.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR = FDLayoutConstants.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR = options.gravityRangeCompound;
+ if (options.initialEnergyOnIncremental != null) CoSEConstants.DEFAULT_COOLING_FACTOR_INCREMENTAL = FDLayoutConstants.DEFAULT_COOLING_FACTOR_INCREMENTAL = options.initialEnergyOnIncremental;
+
+ if (options.tilingCompareBy != null) CoSEConstants.TILING_COMPARE_BY = options.tilingCompareBy;
+
+ if (options.quality == 'proof') LayoutConstants.QUALITY = 2;else LayoutConstants.QUALITY = 0;
+
+ CoSEConstants.NODE_DIMENSIONS_INCLUDE_LABELS = FDLayoutConstants.NODE_DIMENSIONS_INCLUDE_LABELS = LayoutConstants.NODE_DIMENSIONS_INCLUDE_LABELS = options.nodeDimensionsIncludeLabels;
+ CoSEConstants.DEFAULT_INCREMENTAL = FDLayoutConstants.DEFAULT_INCREMENTAL = LayoutConstants.DEFAULT_INCREMENTAL = !options.randomize;
+ CoSEConstants.ANIMATE = FDLayoutConstants.ANIMATE = LayoutConstants.ANIMATE = options.animate;
+ CoSEConstants.TILE = options.tile;
+ CoSEConstants.TILING_PADDING_VERTICAL = typeof options.tilingPaddingVertical === 'function' ? options.tilingPaddingVertical.call() : options.tilingPaddingVertical;
+ CoSEConstants.TILING_PADDING_HORIZONTAL = typeof options.tilingPaddingHorizontal === 'function' ? options.tilingPaddingHorizontal.call() : options.tilingPaddingHorizontal;
+
+ CoSEConstants.DEFAULT_INCREMENTAL = FDLayoutConstants.DEFAULT_INCREMENTAL = LayoutConstants.DEFAULT_INCREMENTAL = true;
+ CoSEConstants.PURE_INCREMENTAL = !options.randomize;
+ LayoutConstants.DEFAULT_UNIFORM_LEAF_NODE_SIZES = options.uniformNodeDimensions;
+
+ // This part is for debug/demo purpose
+ if (options.step == "transformed") {
+ CoSEConstants.TRANSFORM_ON_CONSTRAINT_HANDLING = true;
+ CoSEConstants.ENFORCE_CONSTRAINTS = false;
+ CoSEConstants.APPLY_LAYOUT = false;
+ }
+ if (options.step == "enforced") {
+ CoSEConstants.TRANSFORM_ON_CONSTRAINT_HANDLING = false;
+ CoSEConstants.ENFORCE_CONSTRAINTS = true;
+ CoSEConstants.APPLY_LAYOUT = false;
+ }
+ if (options.step == "cose") {
+ CoSEConstants.TRANSFORM_ON_CONSTRAINT_HANDLING = false;
+ CoSEConstants.ENFORCE_CONSTRAINTS = false;
+ CoSEConstants.APPLY_LAYOUT = true;
+ }
+ if (options.step == "all") {
+ if (options.randomize) CoSEConstants.TRANSFORM_ON_CONSTRAINT_HANDLING = true;else CoSEConstants.TRANSFORM_ON_CONSTRAINT_HANDLING = false;
+ CoSEConstants.ENFORCE_CONSTRAINTS = true;
+ CoSEConstants.APPLY_LAYOUT = true;
+ }
+
+ if (options.fixedNodeConstraint || options.alignmentConstraint || options.relativePlacementConstraint) {
+ CoSEConstants.TREE_REDUCTION_ON_INCREMENTAL = false;
+ } else {
+ CoSEConstants.TREE_REDUCTION_ON_INCREMENTAL = true;
+ }
+
+ var coseLayout = new CoSELayout();
+ var gm = coseLayout.newGraphManager();
+
+ processChildrenList(gm.addRoot(), aux.getTopMostNodes(nodes), coseLayout, options);
+ processEdges(coseLayout, gm, edges);
+ processConstraints(coseLayout, options);
+
+ coseLayout.runLayout();
+
+ return idToLNode;
+};
+
+module.exports = { coseLayout: coseLayout };
+
+/***/ }),
+
+/***/ 212:
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+
+
+var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
+
+function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
+
+/**
+ The implementation of the fcose layout algorithm
+*/
+
+var assign = __webpack_require__(658);
+var aux = __webpack_require__(548);
+
+var _require = __webpack_require__(657),
+ spectralLayout = _require.spectralLayout;
+
+var _require2 = __webpack_require__(816),
+ coseLayout = _require2.coseLayout;
+
+var defaults = Object.freeze({
+
+ // 'draft', 'default' or 'proof'
+ // - 'draft' only applies spectral layout
+ // - 'default' improves the quality with subsequent CoSE layout (fast cooling rate)
+ // - 'proof' improves the quality with subsequent CoSE layout (slow cooling rate)
+ quality: "default",
+ // Use random node positions at beginning of layout
+ // if this is set to false, then quality option must be "proof"
+ randomize: true,
+ // Whether or not to animate the layout
+ animate: true,
+ // Duration of animation in ms, if enabled
+ animationDuration: 1000,
+ // Easing of animation, if enabled
+ animationEasing: undefined,
+ // Fit the viewport to the repositioned nodes
+ fit: true,
+ // Padding around layout
+ padding: 30,
+ // Whether to include labels in node dimensions. Valid in "proof" quality
+ nodeDimensionsIncludeLabels: false,
+ // Whether or not simple nodes (non-compound nodes) are of uniform dimensions
+ uniformNodeDimensions: false,
+ // Whether to pack disconnected components - valid only if randomize: true
+ packComponents: true,
+ // Layout step - all, transformed, enforced, cose - for debug purpose only
+ step: "all",
+
+ /* spectral layout options */
+
+ // False for random, true for greedy
+ samplingType: true,
+ // Sample size to construct distance matrix
+ sampleSize: 25,
+ // Separation amount between nodes
+ nodeSeparation: 75,
+ // Power iteration tolerance
+ piTol: 0.0000001,
+
+ /* CoSE layout options */
+
+ // Node repulsion (non overlapping) multiplier
+ nodeRepulsion: function nodeRepulsion(node) {
+ return 4500;
+ },
+ // Ideal edge (non nested) length
+ idealEdgeLength: function idealEdgeLength(edge) {
+ return 50;
+ },
+ // Divisor to compute edge forces
+ edgeElasticity: function edgeElasticity(edge) {
+ return 0.45;
+ },
+ // Nesting factor (multiplier) to compute ideal edge length for nested edges
+ nestingFactor: 0.1,
+ // Gravity force (constant)
+ gravity: 0.25,
+ // Maximum number of iterations to perform
+ numIter: 2500,
+ // For enabling tiling
+ tile: true,
+ // The function that specifies the criteria for comparing nodes while sorting them during tiling operation.
+ // Takes the node id as a parameter and the default tiling operation is perfomed when this option is not set.
+ tilingCompareBy: undefined,
+ // Represents the amount of the vertical space to put between the zero degree members during the tiling operation(can also be a function)
+ tilingPaddingVertical: 10,
+ // Represents the amount of the horizontal space to put between the zero degree members during the tiling operation(can also be a function)
+ tilingPaddingHorizontal: 10,
+ // Gravity range (constant) for compounds
+ gravityRangeCompound: 1.5,
+ // Gravity force (constant) for compounds
+ gravityCompound: 1.0,
+ // Gravity range (constant)
+ gravityRange: 3.8,
+ // Initial cooling factor for incremental layout
+ initialEnergyOnIncremental: 0.3,
+
+ /* constraint options */
+
+ // Fix required nodes to predefined positions
+ // [{nodeId: 'n1', position: {x: 100, y: 200}, {...}]
+ fixedNodeConstraint: undefined,
+ // Align required nodes in vertical/horizontal direction
+ // {vertical: [['n1', 'n2')], ['n3', 'n4']], horizontal: ['n2', 'n4']}
+ alignmentConstraint: undefined,
+ // Place two nodes relatively in vertical/horizontal direction
+ // [{top: 'n1', bottom: 'n2', gap: 100}, {left: 'n3', right: 'n4', gap: 75}]
+ relativePlacementConstraint: undefined,
+
+ /* layout event callbacks */
+ ready: function ready() {}, // on layoutready
+ stop: function stop() {} // on layoutstop
+});
+
+var Layout = function () {
+ function Layout(options) {
+ _classCallCheck(this, Layout);
+
+ this.options = assign({}, defaults, options);
+ }
+
+ _createClass(Layout, [{
+ key: 'run',
+ value: function run() {
+ var layout = this;
+ var options = this.options;
+ var cy = options.cy;
+ var eles = options.eles;
+
+ var spectralResult = [];
+ var xCoords = void 0;
+ var yCoords = void 0;
+ var coseResult = [];
+ var components = void 0;
+ var componentCenters = [];
+
+ // basic validity check for constraint inputs
+ if (options.fixedNodeConstraint && (!Array.isArray(options.fixedNodeConstraint) || options.fixedNodeConstraint.length == 0)) {
+ options.fixedNodeConstraint = undefined;
+ }
+
+ if (options.alignmentConstraint) {
+ if (options.alignmentConstraint.vertical && (!Array.isArray(options.alignmentConstraint.vertical) || options.alignmentConstraint.vertical.length == 0)) {
+ options.alignmentConstraint.vertical = undefined;
+ }
+ if (options.alignmentConstraint.horizontal && (!Array.isArray(options.alignmentConstraint.horizontal) || options.alignmentConstraint.horizontal.length == 0)) {
+ options.alignmentConstraint.horizontal = undefined;
+ }
+ }
+
+ if (options.relativePlacementConstraint && (!Array.isArray(options.relativePlacementConstraint) || options.relativePlacementConstraint.length == 0)) {
+ options.relativePlacementConstraint = undefined;
+ }
+
+ // if any constraint exists, set some options
+ var constraintExist = options.fixedNodeConstraint || options.alignmentConstraint || options.relativePlacementConstraint;
+ if (constraintExist) {
+ // constraints work with these options
+ options.tile = false;
+ options.packComponents = false;
+ }
+
+ // decide component packing is enabled or not
+ var layUtil = void 0;
+ var packingEnabled = false;
+ if (cy.layoutUtilities && options.packComponents) {
+ layUtil = cy.layoutUtilities("get");
+ if (!layUtil) layUtil = cy.layoutUtilities();
+ packingEnabled = true;
+ }
+
+ if (eles.nodes().length > 0) {
+ // if packing is not enabled, perform layout on the whole graph
+ if (!packingEnabled) {
+ // store component center
+ var boundingBox = options.eles.boundingBox();
+ componentCenters.push({ x: boundingBox.x1 + boundingBox.w / 2, y: boundingBox.y1 + boundingBox.h / 2 });
+ // apply spectral layout
+ if (options.randomize) {
+ var result = spectralLayout(options);
+ spectralResult.push(result);
+ }
+ // apply cose layout as postprocessing
+ if (options.quality == "default" || options.quality == "proof") {
+ coseResult.push(coseLayout(options, spectralResult[0]));
+ aux.relocateComponent(componentCenters[0], coseResult[0], options); // relocate center to original position
+ } else {
+ aux.relocateComponent(componentCenters[0], spectralResult[0], options); // relocate center to original position
+ }
+ } else {
+ // packing is enabled
+ var topMostNodes = aux.getTopMostNodes(options.eles.nodes());
+ components = aux.connectComponents(cy, options.eles, topMostNodes);
+ // store component centers
+ components.forEach(function (component) {
+ var boundingBox = component.boundingBox();
+ componentCenters.push({ x: boundingBox.x1 + boundingBox.w / 2, y: boundingBox.y1 + boundingBox.h / 2 });
+ });
+
+ //send each component to spectral layout if randomized
+ if (options.randomize) {
+ components.forEach(function (component) {
+ options.eles = component;
+ spectralResult.push(spectralLayout(options));
+ });
+ }
+
+ if (options.quality == "default" || options.quality == "proof") {
+ var toBeTiledNodes = cy.collection();
+ if (options.tile) {
+ // behave nodes to be tiled as one component
+ var nodeIndexes = new Map();
+ var _xCoords = [];
+ var _yCoords = [];
+ var count = 0;
+ var tempSpectralResult = { nodeIndexes: nodeIndexes, xCoords: _xCoords, yCoords: _yCoords };
+ var indexesToBeDeleted = [];
+ components.forEach(function (component, index) {
+ if (component.edges().length == 0) {
+ component.nodes().forEach(function (node, i) {
+ toBeTiledNodes.merge(component.nodes()[i]);
+ if (!node.isParent()) {
+ tempSpectralResult.nodeIndexes.set(component.nodes()[i].id(), count++);
+ tempSpectralResult.xCoords.push(component.nodes()[0].position().x);
+ tempSpectralResult.yCoords.push(component.nodes()[0].position().y);
+ }
+ });
+ indexesToBeDeleted.push(index);
+ }
+ });
+ if (toBeTiledNodes.length > 1) {
+ var _boundingBox = toBeTiledNodes.boundingBox();
+ componentCenters.push({ x: _boundingBox.x1 + _boundingBox.w / 2, y: _boundingBox.y1 + _boundingBox.h / 2 });
+ components.push(toBeTiledNodes);
+ spectralResult.push(tempSpectralResult);
+ for (var i = indexesToBeDeleted.length - 1; i >= 0; i--) {
+ components.splice(indexesToBeDeleted[i], 1);
+ spectralResult.splice(indexesToBeDeleted[i], 1);
+ componentCenters.splice(indexesToBeDeleted[i], 1);
+ };
+ }
+ }
+ components.forEach(function (component, index) {
+ // send each component to cose layout
+ options.eles = component;
+ coseResult.push(coseLayout(options, spectralResult[index]));
+ aux.relocateComponent(componentCenters[index], coseResult[index], options); // relocate center to original position
+ });
+ } else {
+ components.forEach(function (component, index) {
+ aux.relocateComponent(componentCenters[index], spectralResult[index], options); // relocate center to original position
+ });
+ }
+
+ // packing
+ var componentsEvaluated = new Set();
+ if (components.length > 1) {
+ var subgraphs = [];
+ var hiddenEles = eles.filter(function (ele) {
+ return ele.css('display') == 'none';
+ });
+ components.forEach(function (component, index) {
+ var nodeIndexes = void 0;
+ if (options.quality == "draft") {
+ nodeIndexes = spectralResult[index].nodeIndexes;
+ }
+
+ if (component.nodes().not(hiddenEles).length > 0) {
+ var subgraph = {};
+ subgraph.edges = [];
+ subgraph.nodes = [];
+ var nodeIndex = void 0;
+ component.nodes().not(hiddenEles).forEach(function (node) {
+ if (options.quality == "draft") {
+ if (!node.isParent()) {
+ nodeIndex = nodeIndexes.get(node.id());
+ subgraph.nodes.push({ x: spectralResult[index].xCoords[nodeIndex] - node.boundingbox().w / 2, y: spectralResult[index].yCoords[nodeIndex] - node.boundingbox().h / 2, width: node.boundingbox().w, height: node.boundingbox().h });
+ } else {
+ var parentInfo = aux.calcBoundingBox(node, spectralResult[index].xCoords, spectralResult[index].yCoords, nodeIndexes);
+ subgraph.nodes.push({ x: parentInfo.topLeftX, y: parentInfo.topLeftY, width: parentInfo.width, height: parentInfo.height });
+ }
+ } else {
+ if (coseResult[index][node.id()]) {
+ subgraph.nodes.push({ x: coseResult[index][node.id()].getLeft(), y: coseResult[index][node.id()].getTop(), width: coseResult[index][node.id()].getWidth(), height: coseResult[index][node.id()].getHeight() });
+ }
+ }
+ });
+ component.edges().forEach(function (edge) {
+ var source = edge.source();
+ var target = edge.target();
+ if (source.css("display") != "none" && target.css("display") != "none") {
+ if (options.quality == "draft") {
+ var sourceNodeIndex = nodeIndexes.get(source.id());
+ var targetNodeIndex = nodeIndexes.get(target.id());
+ var sourceCenter = [];
+ var targetCenter = [];
+ if (source.isParent()) {
+ var parentInfo = aux.calcBoundingBox(source, spectralResult[index].xCoords, spectralResult[index].yCoords, nodeIndexes);
+ sourceCenter.push(parentInfo.topLeftX + parentInfo.width / 2);
+ sourceCenter.push(parentInfo.topLeftY + parentInfo.height / 2);
+ } else {
+ sourceCenter.push(spectralResult[index].xCoords[sourceNodeIndex]);
+ sourceCenter.push(spectralResult[index].yCoords[sourceNodeIndex]);
+ }
+ if (target.isParent()) {
+ var _parentInfo = aux.calcBoundingBox(target, spectralResult[index].xCoords, spectralResult[index].yCoords, nodeIndexes);
+ targetCenter.push(_parentInfo.topLeftX + _parentInfo.width / 2);
+ targetCenter.push(_parentInfo.topLeftY + _parentInfo.height / 2);
+ } else {
+ targetCenter.push(spectralResult[index].xCoords[targetNodeIndex]);
+ targetCenter.push(spectralResult[index].yCoords[targetNodeIndex]);
+ }
+ subgraph.edges.push({ startX: sourceCenter[0], startY: sourceCenter[1], endX: targetCenter[0], endY: targetCenter[1] });
+ } else {
+ if (coseResult[index][source.id()] && coseResult[index][target.id()]) {
+ subgraph.edges.push({ startX: coseResult[index][source.id()].getCenterX(), startY: coseResult[index][source.id()].getCenterY(), endX: coseResult[index][target.id()].getCenterX(), endY: coseResult[index][target.id()].getCenterY() });
+ }
+ }
+ }
+ });
+ if (subgraph.nodes.length > 0) {
+ subgraphs.push(subgraph);
+ componentsEvaluated.add(index);
+ }
+ }
+ });
+ var shiftResult = layUtil.packComponents(subgraphs, options.randomize).shifts;
+ if (options.quality == "draft") {
+ spectralResult.forEach(function (result, index) {
+ var newXCoords = result.xCoords.map(function (x) {
+ return x + shiftResult[index].dx;
+ });
+ var newYCoords = result.yCoords.map(function (y) {
+ return y + shiftResult[index].dy;
+ });
+ result.xCoords = newXCoords;
+ result.yCoords = newYCoords;
+ });
+ } else {
+ var _count = 0;
+ componentsEvaluated.forEach(function (index) {
+ Object.keys(coseResult[index]).forEach(function (item) {
+ var nodeRectangle = coseResult[index][item];
+ nodeRectangle.setCenter(nodeRectangle.getCenterX() + shiftResult[_count].dx, nodeRectangle.getCenterY() + shiftResult[_count].dy);
+ });
+ _count++;
+ });
+ }
+ }
+ }
+ }
+
+ // get each element's calculated position
+ var getPositions = function getPositions(ele, i) {
+ if (options.quality == "default" || options.quality == "proof") {
+ if (typeof ele === "number") {
+ ele = i;
+ }
+ var pos = void 0;
+ var node = void 0;
+ var theId = ele.data('id');
+ coseResult.forEach(function (result) {
+ if (theId in result) {
+ pos = { x: result[theId].getRect().getCenterX(), y: result[theId].getRect().getCenterY() };
+ node = result[theId];
+ }
+ });
+ if (options.nodeDimensionsIncludeLabels) {
+ if (node.labelWidth) {
+ if (node.labelPosHorizontal == "left") {
+ pos.x += node.labelWidth / 2;
+ } else if (node.labelPosHorizontal == "right") {
+ pos.x -= node.labelWidth / 2;
+ }
+ }
+ if (node.labelHeight) {
+ if (node.labelPosVertical == "top") {
+ pos.y += node.labelHeight / 2;
+ } else if (node.labelPosVertical == "bottom") {
+ pos.y -= node.labelHeight / 2;
+ }
+ }
+ }
+ if (pos == undefined) pos = { x: ele.position("x"), y: ele.position("y") };
+ return {
+ x: pos.x,
+ y: pos.y
+ };
+ } else {
+ var _pos = void 0;
+ spectralResult.forEach(function (result) {
+ var index = result.nodeIndexes.get(ele.id());
+ if (index != undefined) {
+ _pos = { x: result.xCoords[index], y: result.yCoords[index] };
+ }
+ });
+ if (_pos == undefined) _pos = { x: ele.position("x"), y: ele.position("y") };
+ return {
+ x: _pos.x,
+ y: _pos.y
+ };
+ }
+ };
+
+ // quality = "draft" and randomize = false are contradictive so in that case positions don't change
+ if (options.quality == "default" || options.quality == "proof" || options.randomize) {
+ // transfer calculated positions to nodes (positions of only simple nodes are evaluated, compounds are positioned automatically)
+ var parentsWithoutChildren = aux.calcParentsWithoutChildren(cy, eles);
+ var _hiddenEles = eles.filter(function (ele) {
+ return ele.css('display') == 'none';
+ });
+ options.eles = eles.not(_hiddenEles);
+
+ eles.nodes().not(":parent").not(_hiddenEles).layoutPositions(layout, options, getPositions);
+
+ if (parentsWithoutChildren.length > 0) {
+ parentsWithoutChildren.forEach(function (ele) {
+ ele.position(getPositions(ele));
+ });
+ }
+ } else {
+ console.log("If randomize option is set to false, then quality option must be 'default' or 'proof'.");
+ }
+ }
+ }]);
+
+ return Layout;
+}();
+
+module.exports = Layout;
+
+/***/ }),
+
+/***/ 657:
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+
+
+/**
+ The implementation of the spectral layout that is the first part of the fcose layout algorithm
+*/
+
+var aux = __webpack_require__(548);
+var Matrix = __webpack_require__(140).layoutBase.Matrix;
+var SVD = __webpack_require__(140).layoutBase.SVD;
+
+// main function that spectral layout is processed
+var spectralLayout = function spectralLayout(options) {
+
+ var cy = options.cy;
+ var eles = options.eles;
+ var nodes = eles.nodes();
+ var parentNodes = eles.nodes(":parent");
+
+ var dummyNodes = new Map(); // map to keep dummy nodes and their neighbors
+ var nodeIndexes = new Map(); // map to keep indexes to nodes
+ var parentChildMap = new Map(); // mapping btw. compound and its representative node
+ var allNodesNeighborhood = []; // array to keep neighborhood of all nodes
+ var xCoords = [];
+ var yCoords = [];
+
+ var samplesColumn = []; // sampled vertices
+ var minDistancesColumn = [];
+ var C = []; // column sampling matrix
+ var PHI = []; // intersection of column and row sampling matrices
+ var INV = []; // inverse of PHI
+
+ var firstSample = void 0; // the first sampled node
+ var nodeSize = void 0;
+
+ var infinity = 100000000;
+ var small = 0.000000001;
+
+ var piTol = options.piTol;
+ var samplingType = options.samplingType; // false for random, true for greedy
+ var nodeSeparation = options.nodeSeparation;
+ var sampleSize = void 0;
+
+ /**** Spectral-preprocessing functions ****/
+
+ /**** Spectral layout functions ****/
+
+ // determine which columns to be sampled
+ var randomSampleCR = function randomSampleCR() {
+ var sample = 0;
+ var count = 0;
+ var flag = false;
+
+ while (count < sampleSize) {
+ sample = Math.floor(Math.random() * nodeSize);
+
+ flag = false;
+ for (var i = 0; i < count; i++) {
+ if (samplesColumn[i] == sample) {
+ flag = true;
+ break;
+ }
+ }
+
+ if (!flag) {
+ samplesColumn[count] = sample;
+ count++;
+ } else {
+ continue;
+ }
+ }
+ };
+
+ // takes the index of the node(pivot) to initiate BFS as a parameter
+ var BFS = function BFS(pivot, index, samplingMethod) {
+ var path = []; // the front of the path
+ var front = 0; // the back of the path
+ var back = 0;
+ var current = 0;
+ var temp = void 0;
+ var distance = [];
+
+ var max_dist = 0; // the furthest node to be returned
+ var max_ind = 1;
+
+ for (var i = 0; i < nodeSize; i++) {
+ distance[i] = infinity;
+ }
+
+ path[back] = pivot;
+ distance[pivot] = 0;
+
+ while (back >= front) {
+ current = path[front++];
+ var neighbors = allNodesNeighborhood[current];
+ for (var _i = 0; _i < neighbors.length; _i++) {
+ temp = nodeIndexes.get(neighbors[_i]);
+ if (distance[temp] == infinity) {
+ distance[temp] = distance[current] + 1;
+ path[++back] = temp;
+ }
+ }
+ C[current][index] = distance[current] * nodeSeparation;
+ }
+
+ if (samplingMethod) {
+ for (var _i2 = 0; _i2 < nodeSize; _i2++) {
+ if (C[_i2][index] < minDistancesColumn[_i2]) minDistancesColumn[_i2] = C[_i2][index];
+ }
+
+ for (var _i3 = 0; _i3 < nodeSize; _i3++) {
+ if (minDistancesColumn[_i3] > max_dist) {
+ max_dist = minDistancesColumn[_i3];
+ max_ind = _i3;
+ }
+ }
+ }
+ return max_ind;
+ };
+
+ // apply BFS to all nodes or selected samples
+ var allBFS = function allBFS(samplingMethod) {
+
+ var sample = void 0;
+
+ if (!samplingMethod) {
+ randomSampleCR();
+
+ // call BFS
+ for (var i = 0; i < sampleSize; i++) {
+ BFS(samplesColumn[i], i, samplingMethod, false);
+ }
+ } else {
+ sample = Math.floor(Math.random() * nodeSize);
+ firstSample = sample;
+
+ for (var _i4 = 0; _i4 < nodeSize; _i4++) {
+ minDistancesColumn[_i4] = infinity;
+ }
+
+ for (var _i5 = 0; _i5 < sampleSize; _i5++) {
+ samplesColumn[_i5] = sample;
+ sample = BFS(sample, _i5, samplingMethod);
+ }
+ }
+
+ // form the squared distances for C
+ for (var _i6 = 0; _i6 < nodeSize; _i6++) {
+ for (var j = 0; j < sampleSize; j++) {
+ C[_i6][j] *= C[_i6][j];
+ }
+ }
+
+ // form PHI
+ for (var _i7 = 0; _i7 < sampleSize; _i7++) {
+ PHI[_i7] = [];
+ }
+
+ for (var _i8 = 0; _i8 < sampleSize; _i8++) {
+ for (var _j = 0; _j < sampleSize; _j++) {
+ PHI[_i8][_j] = C[samplesColumn[_j]][_i8];
+ }
+ }
+ };
+
+ // perform the SVD algorithm and apply a regularization step
+ var sample = function sample() {
+
+ var SVDResult = SVD.svd(PHI);
+
+ var a_q = SVDResult.S;
+ var a_u = SVDResult.U;
+ var a_v = SVDResult.V;
+
+ var max_s = a_q[0] * a_q[0] * a_q[0];
+
+ var a_Sig = [];
+
+ // regularization
+ for (var i = 0; i < sampleSize; i++) {
+ a_Sig[i] = [];
+ for (var j = 0; j < sampleSize; j++) {
+ a_Sig[i][j] = 0;
+ if (i == j) {
+ a_Sig[i][j] = a_q[i] / (a_q[i] * a_q[i] + max_s / (a_q[i] * a_q[i]));
+ }
+ }
+ }
+
+ INV = Matrix.multMat(Matrix.multMat(a_v, a_Sig), Matrix.transpose(a_u));
+ };
+
+ // calculate final coordinates
+ var powerIteration = function powerIteration() {
+ // two largest eigenvalues
+ var theta1 = void 0;
+ var theta2 = void 0;
+
+ // initial guesses for eigenvectors
+ var Y1 = [];
+ var Y2 = [];
+
+ var V1 = [];
+ var V2 = [];
+
+ for (var i = 0; i < nodeSize; i++) {
+ Y1[i] = Math.random();
+ Y2[i] = Math.random();
+ }
+
+ Y1 = Matrix.normalize(Y1);
+ Y2 = Matrix.normalize(Y2);
+
+ var count = 0;
+ // to keep track of the improvement ratio in power iteration
+ var current = small;
+ var previous = small;
+
+ var temp = void 0;
+
+ while (true) {
+ count++;
+
+ for (var _i9 = 0; _i9 < nodeSize; _i9++) {
+ V1[_i9] = Y1[_i9];
+ }
+
+ Y1 = Matrix.multGamma(Matrix.multL(Matrix.multGamma(V1), C, INV));
+ theta1 = Matrix.dotProduct(V1, Y1);
+ Y1 = Matrix.normalize(Y1);
+
+ current = Matrix.dotProduct(V1, Y1);
+
+ temp = Math.abs(current / previous);
+
+ if (temp <= 1 + piTol && temp >= 1) {
+ break;
+ }
+
+ previous = current;
+ }
+
+ for (var _i10 = 0; _i10 < nodeSize; _i10++) {
+ V1[_i10] = Y1[_i10];
+ }
+
+ count = 0;
+ previous = small;
+ while (true) {
+ count++;
+
+ for (var _i11 = 0; _i11 < nodeSize; _i11++) {
+ V2[_i11] = Y2[_i11];
+ }
+
+ V2 = Matrix.minusOp(V2, Matrix.multCons(V1, Matrix.dotProduct(V1, V2)));
+ Y2 = Matrix.multGamma(Matrix.multL(Matrix.multGamma(V2), C, INV));
+ theta2 = Matrix.dotProduct(V2, Y2);
+ Y2 = Matrix.normalize(Y2);
+
+ current = Matrix.dotProduct(V2, Y2);
+
+ temp = Math.abs(current / previous);
+
+ if (temp <= 1 + piTol && temp >= 1) {
+ break;
+ }
+
+ previous = current;
+ }
+
+ for (var _i12 = 0; _i12 < nodeSize; _i12++) {
+ V2[_i12] = Y2[_i12];
+ }
+
+ // theta1 now contains dominant eigenvalue
+ // theta2 now contains the second-largest eigenvalue
+ // V1 now contains theta1's eigenvector
+ // V2 now contains theta2's eigenvector
+
+ //populate the two vectors
+ xCoords = Matrix.multCons(V1, Math.sqrt(Math.abs(theta1)));
+ yCoords = Matrix.multCons(V2, Math.sqrt(Math.abs(theta2)));
+ };
+
+ /**** Preparation for spectral layout (Preprocessing) ****/
+
+ // connect disconnected components (first top level, then inside of each compound node)
+ aux.connectComponents(cy, eles, aux.getTopMostNodes(nodes), dummyNodes);
+
+ parentNodes.forEach(function (ele) {
+ aux.connectComponents(cy, eles, aux.getTopMostNodes(ele.descendants().intersection(eles)), dummyNodes);
+ });
+
+ // assign indexes to nodes (first real, then dummy nodes)
+ var index = 0;
+ for (var i = 0; i < nodes.length; i++) {
+ if (!nodes[i].isParent()) {
+ nodeIndexes.set(nodes[i].id(), index++);
+ }
+ }
+
+ var _iteratorNormalCompletion = true;
+ var _didIteratorError = false;
+ var _iteratorError = undefined;
+
+ try {
+ for (var _iterator = dummyNodes.keys()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
+ var key = _step.value;
+
+ nodeIndexes.set(key, index++);
+ }
+
+ // instantiate the neighborhood matrix
+ } catch (err) {
+ _didIteratorError = true;
+ _iteratorError = err;
+ } finally {
+ try {
+ if (!_iteratorNormalCompletion && _iterator.return) {
+ _iterator.return();
+ }
+ } finally {
+ if (_didIteratorError) {
+ throw _iteratorError;
+ }
+ }
+ }
+
+ for (var _i13 = 0; _i13 < nodeIndexes.size; _i13++) {
+ allNodesNeighborhood[_i13] = [];
+ }
+
+ // form a parent-child map to keep representative node of each compound node
+ parentNodes.forEach(function (ele) {
+ var children = ele.children().intersection(eles);
+
+ // let random = 0;
+ while (children.nodes(":childless").length == 0) {
+ // random = Math.floor(Math.random() * children.nodes().length); // if all children are compound then proceed randomly
+ children = children.nodes()[0].children().intersection(eles);
+ }
+ // select the representative node - we can apply different methods here
+ // random = Math.floor(Math.random() * children.nodes(":childless").length);
+ var index = 0;
+ var min = children.nodes(":childless")[0].connectedEdges().length;
+ children.nodes(":childless").forEach(function (ele2, i) {
+ if (ele2.connectedEdges().length < min) {
+ min = ele2.connectedEdges().length;
+ index = i;
+ }
+ });
+ parentChildMap.set(ele.id(), children.nodes(":childless")[index].id());
+ });
+
+ // add neighborhood relations (first real, then dummy nodes)
+ nodes.forEach(function (ele) {
+ var eleIndex = void 0;
+
+ if (ele.isParent()) eleIndex = nodeIndexes.get(parentChildMap.get(ele.id()));else eleIndex = nodeIndexes.get(ele.id());
+
+ ele.neighborhood().nodes().forEach(function (node) {
+ if (eles.intersection(ele.edgesWith(node)).length > 0) {
+ if (node.isParent()) allNodesNeighborhood[eleIndex].push(parentChildMap.get(node.id()));else allNodesNeighborhood[eleIndex].push(node.id());
+ }
+ });
+ });
+
+ var _loop = function _loop(_key) {
+ var eleIndex = nodeIndexes.get(_key);
+ var disconnectedId = void 0;
+ dummyNodes.get(_key).forEach(function (id) {
+ if (cy.getElementById(id).isParent()) disconnectedId = parentChildMap.get(id);else disconnectedId = id;
+
+ allNodesNeighborhood[eleIndex].push(disconnectedId);
+ allNodesNeighborhood[nodeIndexes.get(disconnectedId)].push(_key);
+ });
+ };
+
+ var _iteratorNormalCompletion2 = true;
+ var _didIteratorError2 = false;
+ var _iteratorError2 = undefined;
+
+ try {
+ for (var _iterator2 = dummyNodes.keys()[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
+ var _key = _step2.value;
+
+ _loop(_key);
+ }
+
+ // nodeSize now only considers the size of transformed graph
+ } catch (err) {
+ _didIteratorError2 = true;
+ _iteratorError2 = err;
+ } finally {
+ try {
+ if (!_iteratorNormalCompletion2 && _iterator2.return) {
+ _iterator2.return();
+ }
+ } finally {
+ if (_didIteratorError2) {
+ throw _iteratorError2;
+ }
+ }
+ }
+
+ nodeSize = nodeIndexes.size;
+
+ var spectralResult = void 0;
+
+ // If number of nodes in transformed graph is 1 or 2, either SVD or powerIteration causes problem
+ // So skip spectral and layout the graph with cose
+ if (nodeSize > 2) {
+ // if # of nodes in transformed graph is smaller than sample size,
+ // then use # of nodes as sample size
+ sampleSize = nodeSize < options.sampleSize ? nodeSize : options.sampleSize;
+
+ // instantiates the partial matrices that will be used in spectral layout
+ for (var _i14 = 0; _i14 < nodeSize; _i14++) {
+ C[_i14] = [];
+ }
+ for (var _i15 = 0; _i15 < sampleSize; _i15++) {
+ INV[_i15] = [];
+ }
+
+ /**** Apply spectral layout ****/
+
+ if (options.quality == "draft" || options.step == "all") {
+ allBFS(samplingType);
+ sample();
+ powerIteration();
+
+ spectralResult = { nodeIndexes: nodeIndexes, xCoords: xCoords, yCoords: yCoords };
+ } else {
+ nodeIndexes.forEach(function (value, key) {
+ xCoords.push(cy.getElementById(key).position("x"));
+ yCoords.push(cy.getElementById(key).position("y"));
+ });
+ spectralResult = { nodeIndexes: nodeIndexes, xCoords: xCoords, yCoords: yCoords };
+ }
+ return spectralResult;
+ } else {
+ var iterator = nodeIndexes.keys();
+ var firstNode = cy.getElementById(iterator.next().value);
+ var firstNodePos = firstNode.position();
+ var firstNodeWidth = firstNode.outerWidth();
+ xCoords.push(firstNodePos.x);
+ yCoords.push(firstNodePos.y);
+ if (nodeSize == 2) {
+ var secondNode = cy.getElementById(iterator.next().value);
+ var secondNodeWidth = secondNode.outerWidth();
+ xCoords.push(firstNodePos.x + firstNodeWidth / 2 + secondNodeWidth / 2 + options.idealEdgeLength);
+ yCoords.push(firstNodePos.y);
+ }
+
+ spectralResult = { nodeIndexes: nodeIndexes, xCoords: xCoords, yCoords: yCoords };
+ return spectralResult;
+ }
+};
+
+module.exports = { spectralLayout: spectralLayout };
+
+/***/ }),
+
+/***/ 579:
+/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
+
+
+
+var impl = __webpack_require__(212);
+
+// registers the extension on a cytoscape lib ref
+var register = function register(cytoscape) {
+ if (!cytoscape) {
+ return;
+ } // can't register if cytoscape unspecified
+
+ cytoscape('layout', 'fcose', impl); // register with cytoscape.js
+};
+
+if (typeof cytoscape !== 'undefined') {
+ // expose to global cytoscape (i.e. window.cytoscape)
+ register(cytoscape);
+}
+
+module.exports = register;
+
+/***/ }),
+
+/***/ 140:
+/***/ ((module) => {
+
+module.exports = __WEBPACK_EXTERNAL_MODULE__140__;
+
+/***/ })
+
+/******/ });
+/************************************************************************/
+/******/ // The module cache
+/******/ var __webpack_module_cache__ = {};
+/******/
+/******/ // The require function
+/******/ function __webpack_require__(moduleId) {
+/******/ // Check if module is in cache
+/******/ var cachedModule = __webpack_module_cache__[moduleId];
+/******/ if (cachedModule !== undefined) {
+/******/ return cachedModule.exports;
+/******/ }
+/******/ // Create a new module (and put it into the cache)
+/******/ var module = __webpack_module_cache__[moduleId] = {
+/******/ // no module.id needed
+/******/ // no module.loaded needed
+/******/ exports: {}
+/******/ };
+/******/
+/******/ // Execute the module function
+/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
+/******/
+/******/ // Return the exports of the module
+/******/ return module.exports;
+/******/ }
+/******/
+/************************************************************************/
+/******/
+/******/ // startup
+/******/ // Load entry module and return exports
+/******/ // This entry module is referenced by other modules so it can't be inlined
+/******/ var __webpack_exports__ = __webpack_require__(579);
+/******/
+/******/ return __webpack_exports__;
+/******/ })()
+;
+});
\ No newline at end of file
diff --git a/web/vendor/cytoscape.min.js b/web/vendor/cytoscape.min.js
new file mode 100644
index 0000000..ff0d7c1
--- /dev/null
+++ b/web/vendor/cytoscape.min.js
@@ -0,0 +1,32 @@
+/**
+ * Copyright (c) 2016-2024, The Cytoscape Consortium.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of
+ * this software and associated documentation files (the “Software”), to deal in
+ * the Software without restriction, including without limitation the rights to
+ * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+ * of the Software, and to permit persons to whom the Software is furnished to do
+ * so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).cytoscape=t()}(this,(function(){"use strict";function e(t){return(e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(t)}function t(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function r(e,t,r){return t&&n(e.prototype,t),r&&n(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null==n)return;var r,i,a=[],o=!0,s=!1;try{for(n=n.call(e);!(o=(r=n.next()).done)&&(a.push(r.value),!t||a.length!==t);o=!0);}catch(e){s=!0,i=e}finally{try{o||null==n.return||n.return()}finally{if(s)throw i}}return a}(e,t)||o(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function o(e,t){if(e){if("string"==typeof e)return s(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?s(e,t):void 0}}function s(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function l(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=o(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,i=function(){};return{s:i,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,s=!0,l=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){l=!0,a=e},f:function(){try{s||null==n.return||n.return()}finally{if(l)throw a}}}}var u="undefined"==typeof window?null:window,c=u?u.navigator:null;u&&u.document;var d=e(""),h=e({}),p=e((function(){})),f="undefined"==typeof HTMLElement?"undefined":e(HTMLElement),g=function(e){return e&&e.instanceString&&y(e.instanceString)?e.instanceString():null},v=function(t){return null!=t&&e(t)==d},y=function(t){return null!=t&&e(t)===p},m=function(e){return!E(e)&&(Array.isArray?Array.isArray(e):null!=e&&e instanceof Array)},b=function(t){return null!=t&&e(t)===h&&!m(t)&&t.constructor===Object},x=function(t){return null!=t&&e(t)===e(1)&&!isNaN(t)},w=function(e){return"undefined"===f?void 0:null!=e&&e instanceof HTMLElement},E=function(e){return k(e)||C(e)},k=function(e){return"collection"===g(e)&&e._private.single},C=function(e){return"collection"===g(e)&&!e._private.single},S=function(e){return"core"===g(e)},P=function(e){return"stylesheet"===g(e)},D=function(e){return null==e||!(""!==e&&!e.match(/^\s+$/))},T=function(t){return function(t){return null!=t&&e(t)===h}(t)&&y(t.then)},_=function(e,t){t||(t=function(){if(1===arguments.length)return arguments[0];if(0===arguments.length)return"undefined";for(var e=[],t=0;t<arguments.length;t++)e.push(arguments[t]);return e.join("$")});var n=function n(){var r,i=this,a=arguments,o=t.apply(i,a),s=n.cache;return(r=s[o])||(r=s[o]=e.apply(i,a)),r};return n.cache={},n},M=_((function(e){return e.replace(/([A-Z])/g,(function(e){return"-"+e.toLowerCase()}))})),B=_((function(e){return e.replace(/(-\w)/g,(function(e){return e[1].toUpperCase()}))})),N=_((function(e,t){return e+t[0].toUpperCase()+t.substring(1)}),(function(e,t){return e+"$"+t})),z=function(e){return D(e)?e:e.charAt(0).toUpperCase()+e.substring(1)},I="(?:[-+]?(?:(?:\\d+|\\d*\\.\\d+)(?:[Ee][+-]?\\d+)?))",A=function(e,t){return e<t?-1:e>t?1:0},L=null!=Object.assign?Object.assign.bind(Object):function(e){for(var t=arguments,n=1;n<t.length;n++){var r=t[n];if(null!=r)for(var i=Object.keys(r),a=0;a<i.length;a++){var o=i[a];e[o]=r[o]}}return e},O=function(e){return(m(e)?e:null)||function(e){return R[e.toLowerCase()]}(e)||function(e){if((4===e.length||7===e.length)&&"#"===e[0]){var t,n,r;return 4===e.length?(t=parseInt(e[1]+e[1],16),n=parseInt(e[2]+e[2],16),r=parseInt(e[3]+e[3],16)):(t=parseInt(e[1]+e[2],16),n=parseInt(e[3]+e[4],16),r=parseInt(e[5]+e[6],16)),[t,n,r]}}(e)||function(e){var t,n=new RegExp("^rgb[a]?\\(((?:[-+]?(?:(?:\\d+|\\d*\\.\\d+)(?:[Ee][+-]?\\d+)?))[%]?)\\s*,\\s*((?:[-+]?(?:(?:\\d+|\\d*\\.\\d+)(?:[Ee][+-]?\\d+)?))[%]?)\\s*,\\s*((?:[-+]?(?:(?:\\d+|\\d*\\.\\d+)(?:[Ee][+-]?\\d+)?))[%]?)(?:\\s*,\\s*((?:[-+]?(?:(?:\\d+|\\d*\\.\\d+)(?:[Ee][+-]?\\d+)?))))?\\)$").exec(e);if(n){t=[];for(var r=[],i=1;i<=3;i++){var a=n[i];if("%"===a[a.length-1]&&(r[i]=!0),a=parseFloat(a),r[i]&&(a=a/100*255),a<0||a>255)return;t.push(Math.floor(a))}var o=r[1]||r[2]||r[3],s=r[1]&&r[2]&&r[3];if(o&&!s)return;var l=n[4];if(void 0!==l){if((l=parseFloat(l))<0||l>1)return;t.push(l)}}return t}(e)||function(e){var t,n,r,i,a,o,s,l;function u(e,t,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?e+6*(t-e)*n:n<.5?t:n<2/3?e+(t-e)*(2/3-n)*6:e}var c=new RegExp("^hsl[a]?\\(((?:[-+]?(?:(?:\\d+|\\d*\\.\\d+)(?:[Ee][+-]?\\d+)?)))\\s*,\\s*((?:[-+]?(?:(?:\\d+|\\d*\\.\\d+)(?:[Ee][+-]?\\d+)?))[%])\\s*,\\s*((?:[-+]?(?:(?:\\d+|\\d*\\.\\d+)(?:[Ee][+-]?\\d+)?))[%])(?:\\s*,\\s*((?:[-+]?(?:(?:\\d+|\\d*\\.\\d+)(?:[Ee][+-]?\\d+)?))))?\\)$").exec(e);if(c){if((n=parseInt(c[1]))<0?n=(360- -1*n%360)%360:n>360&&(n%=360),n/=360,(r=parseFloat(c[2]))<0||r>100)return;if(r/=100,(i=parseFloat(c[3]))<0||i>100)return;if(i/=100,void 0!==(a=c[4])&&((a=parseFloat(a))<0||a>1))return;if(0===r)o=s=l=Math.round(255*i);else{var d=i<.5?i*(1+r):i+r-i*r,h=2*i-d;o=Math.round(255*u(h,d,n+1/3)),s=Math.round(255*u(h,d,n)),l=Math.round(255*u(h,d,n-1/3))}t=[o,s,l,a]}return t}(e)},R={transparent:[0,0,0,0],aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],grey:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]},V=function(e){for(var t=e.map,n=e.keys,r=n.length,i=0;i<r;i++){var a=n[i];if(b(a))throw Error("Tried to set map with object key");i<n.length-1?(null==t[a]&&(t[a]={}),t=t[a]):t[a]=e.value}},F=function(e){for(var t=e.map,n=e.keys,r=n.length,i=0;i<r;i++){var a=n[i];if(b(a))throw Error("Tried to get map with object key");if(null==(t=t[a]))return t}return t};var j=function(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)},q="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};var Y="object"==typeof q&&q&&q.Object===Object&&q,X="object"==typeof self&&self&&self.Object===Object&&self,W=Y||X||Function("return this")(),H=function(){return W.Date.now()},K=/\s/;var G=function(e){for(var t=e.length;t--&&K.test(e.charAt(t)););return t},U=/^\s+/;var Z=function(e){return e?e.slice(0,G(e)+1).replace(U,""):e},$=W.Symbol,Q=Object.prototype,J=Q.hasOwnProperty,ee=Q.toString,te=$?$.toStringTag:void 0;var ne=function(e){var t=J.call(e,te),n=e[te];try{e[te]=void 0;var r=!0}catch(e){}var i=ee.call(e);return r&&(t?e[te]=n:delete e[te]),i},re=Object.prototype.toString;var ie=function(e){return re.call(e)},ae=$?$.toStringTag:void 0;var oe=function(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":ae&&ae in Object(e)?ne(e):ie(e)};var se=function(e){return null!=e&&"object"==typeof e};var le=function(e){return"symbol"==typeof e||se(e)&&"[object Symbol]"==oe(e)},ue=/^[-+]0x[0-9a-f]+$/i,ce=/^0b[01]+$/i,de=/^0o[0-7]+$/i,he=parseInt;var pe=function(e){if("number"==typeof e)return e;if(le(e))return NaN;if(j(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=j(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=Z(e);var n=ce.test(e);return n||de.test(e)?he(e.slice(2),n?2:8):ue.test(e)?NaN:+e},fe=Math.max,ge=Math.min;var ve=function(e,t,n){var r,i,a,o,s,l,u=0,c=!1,d=!1,h=!0;if("function"!=typeof e)throw new TypeError("Expected a function");function p(t){var n=r,a=i;return r=i=void 0,u=t,o=e.apply(a,n)}function f(e){return u=e,s=setTimeout(v,t),c?p(e):o}function g(e){var n=e-l;return void 0===l||n>=t||n<0||d&&e-u>=a}function v(){var e=H();if(g(e))return y(e);s=setTimeout(v,function(e){var n=t-(e-l);return d?ge(n,a-(e-u)):n}(e))}function y(e){return s=void 0,h&&r?p(e):(r=i=void 0,o)}function m(){var e=H(),n=g(e);if(r=arguments,i=this,l=e,n){if(void 0===s)return f(l);if(d)return clearTimeout(s),s=setTimeout(v,t),p(l)}return void 0===s&&(s=setTimeout(v,t)),o}return t=pe(t)||0,j(n)&&(c=!!n.leading,a=(d="maxWait"in n)?fe(pe(n.maxWait)||0,t):a,h="trailing"in n?!!n.trailing:h),m.cancel=function(){void 0!==s&&clearTimeout(s),u=0,r=l=i=s=void 0},m.flush=function(){return void 0===s?o:y(H())},m},ye=u?u.performance:null,me=ye&&ye.now?function(){return ye.now()}:function(){return Date.now()},be=function(){if(u){if(u.requestAnimationFrame)return function(e){u.requestAnimationFrame(e)};if(u.mozRequestAnimationFrame)return function(e){u.mozRequestAnimationFrame(e)};if(u.webkitRequestAnimationFrame)return function(e){u.webkitRequestAnimationFrame(e)};if(u.msRequestAnimationFrame)return function(e){u.msRequestAnimationFrame(e)}}return function(e){e&&setTimeout((function(){e(me())}),1e3/60)}}(),xe=function(e){return be(e)},we=me,Ee=65599,ke=function(e){for(var t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:9261,r=n;!(t=e.next()).done;)r=r*Ee+t.value|0;return r},Ce=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:9261;return t*Ee+e|0},Se=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5381;return(t<<5)+t+e|0},Pe=function(e){return 2097152*e[0]+e[1]},De=function(e,t){return[Ce(e[0],t[0]),Se(e[1],t[1])]},Te=function(e,t){var n={value:0,done:!1},r=0,i=e.length;return ke({next:function(){return r<i?n.value=e.charCodeAt(r++):n.done=!0,n}},t)},_e=function(){return Me(arguments)},Me=function(e){for(var t,n=0;n<e.length;n++){var r=e[n];t=0===n?Te(r):Te(r,t)}return t},Be=!0,Ne=null!=console.warn,ze=null!=console.trace,Ie=Number.MAX_SAFE_INTEGER||9007199254740991,Ae=function(){return!0},Le=function(){return!1},Oe=function(){return 0},Re=function(){},Ve=function(e){throw new Error(e)},Fe=function(e){if(void 0===e)return Be;Be=!!e},je=function(e){Fe()&&(Ne?console.warn(e):(console.log(e),ze&&console.trace()))},qe=function(e){return null==e?e:m(e)?e.slice():b(e)?function(e){return L({},e)}(e):e},Ye=function(e,t){for(t=e="";e++<36;t+=51*e&52?(15^e?8^Math.random()*(20^e?16:4):4).toString(16):"-");return t},Xe={},We=function(){return Xe},He=function(e){var t=Object.keys(e);return function(n){for(var r={},i=0;i<t.length;i++){var a=t[i],o=null==n?void 0:n[a];r[a]=void 0===o?e[a]:o}return r}},Ke=function(e,t,n){for(var r=e.length-1;r>=0&&(e[r]!==t||(e.splice(r,1),!n));r--);},Ge=function(e){e.splice(0,e.length)},Ue=function(e,t,n){return n&&(t=N(n,t)),e[t]},Ze=function(e,t,n,r){n&&(t=N(n,t)),e[t]=r},$e="undefined"!=typeof Map?Map:function(){function e(){t(this,e),this._obj={}}return r(e,[{key:"set",value:function(e,t){return this._obj[e]=t,this}},{key:"delete",value:function(e){return this._obj[e]=void 0,this}},{key:"clear",value:function(){this._obj={}}},{key:"has",value:function(e){return void 0!==this._obj[e]}},{key:"get",value:function(e){return this._obj[e]}}]),e}(),Qe=function(){function e(n){if(t(this,e),this._obj=Object.create(null),this.size=0,null!=n){var r;r=null!=n.instanceString&&n.instanceString()===this.instanceString()?n.toArray():n;for(var i=0;i<r.length;i++)this.add(r[i])}}return r(e,[{key:"instanceString",value:function(){return"set"}},{key:"add",value:function(e){var t=this._obj;1!==t[e]&&(t[e]=1,this.size++)}},{key:"delete",value:function(e){var t=this._obj;1===t[e]&&(t[e]=0,this.size--)}},{key:"clear",value:function(){this._obj=Object.create(null)}},{key:"has",value:function(e){return 1===this._obj[e]}},{key:"toArray",value:function(){var e=this;return Object.keys(this._obj).filter((function(t){return e.has(t)}))}},{key:"forEach",value:function(e,t){return this.toArray().forEach(e,t)}}]),e}(),Je="undefined"!==("undefined"==typeof Set?"undefined":e(Set))?Set:Qe,et=function(e,t){var n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];if(void 0!==e&&void 0!==t&&S(e)){var r=t.group;if(null==r&&(r=t.data&&null!=t.data.source&&null!=t.data.target?"edges":"nodes"),"nodes"===r||"edges"===r){this.length=1,this[0]=this;var i=this._private={cy:e,single:!0,data:t.data||{},position:t.position||{x:0,y:0},autoWidth:void 0,autoHeight:void 0,autoPadding:void 0,compoundBoundsClean:!1,listeners:[],group:r,style:{},rstyle:{},styleCxts:[],styleKeys:{},removed:!0,selected:!!t.selected,selectable:void 0===t.selectable||!!t.selectable,locked:!!t.locked,grabbed:!1,grabbable:void 0===t.grabbable||!!t.grabbable,pannable:void 0===t.pannable?"edges"===r:!!t.pannable,active:!1,classes:new Je,animation:{current:[],queue:[]},rscratch:{},scratch:t.scratch||{},edges:[],children:[],parent:t.parent&&t.parent.isNode()?t.parent:null,traversalCache:{},backgrounding:!1,bbCache:null,bbCacheShift:{x:0,y:0},bodyBounds:null,overlayBounds:null,labelBounds:{all:null,source:null,target:null,main:null},arrowBounds:{source:null,target:null,"mid-source":null,"mid-target":null}};if(null==i.position.x&&(i.position.x=0),null==i.position.y&&(i.position.y=0),t.renderedPosition){var a=t.renderedPosition,o=e.pan(),s=e.zoom();i.position={x:(a.x-o.x)/s,y:(a.y-o.y)/s}}var l=[];m(t.classes)?l=t.classes:v(t.classes)&&(l=t.classes.split(/\s+/));for(var u=0,c=l.length;u<c;u++){var d=l[u];d&&""!==d&&i.classes.add(d)}this.createEmitter();var h=t.style||t.css;h&&(je("Setting a `style` bypass at element creation should be done only when absolutely necessary. Try to use the stylesheet instead."),this.style(h)),(void 0===n||n)&&this.restore()}else Ve("An element must be of type `nodes` or `edges`; you specified `"+r+"`")}else Ve("An element must have a core reference and parameters set")},tt=function(e){return e={bfs:e.bfs||!e.dfs,dfs:e.dfs||!e.bfs},function(t,n,r){var i;b(t)&&!E(t)&&(t=(i=t).roots||i.root,n=i.visit,r=i.directed),r=2!==arguments.length||y(n)?r:n,n=y(n)?n:function(){};for(var a,o=this._private.cy,s=t=v(t)?this.filter(t):t,l=[],u=[],c={},d={},h={},p=0,f=this.byGroup(),g=f.nodes,m=f.edges,x=0;x<s.length;x++){var w=s[x],k=w.id();w.isNode()&&(l.unshift(w),e.bfs&&(h[k]=!0,u.push(w)),d[k]=0)}for(var C=function(){var t=e.bfs?l.shift():l.pop(),i=t.id();if(e.dfs){if(h[i])return"continue";h[i]=!0,u.push(t)}var o,s=d[i],f=c[i],v=null!=f?f.source():null,y=null!=f?f.target():null,b=null==f?void 0:t.same(v)?y[0]:v[0];if(!0===(o=n(t,f,b,p++,s)))return a=t,"break";if(!1===o)return"break";for(var x=t.connectedEdges().filter((function(e){return(!r||e.source().same(t))&&m.has(e)})),w=0;w<x.length;w++){var E=x[w],k=E.connectedNodes().filter((function(e){return!e.same(t)&&g.has(e)})),C=k.id();0===k.length||h[C]||(k=k[0],l.push(k),e.bfs&&(h[C]=!0,u.push(k)),c[C]=E,d[C]=d[i]+1)}};0!==l.length;){var S=C();if("continue"!==S&&"break"===S)break}for(var P=o.collection(),D=0;D<u.length;D++){var T=u[D],_=c[T.id()];null!=_&&P.push(_),P.push(T)}return{path:o.collection(P),found:o.collection(a)}}},nt={breadthFirstSearch:tt({bfs:!0}),depthFirstSearch:tt({dfs:!0})};nt.bfs=nt.breadthFirstSearch,nt.dfs=nt.depthFirstSearch;var rt=function(e,t){return e(t={exports:{}},t.exports),t.exports}((function(e,t){(function(){var t,n,r,i,a,o,s,l,u,c,d,h,p,f,g;r=Math.floor,c=Math.min,n=function(e,t){return e<t?-1:e>t?1:0},u=function(e,t,i,a,o){var s;if(null==i&&(i=0),null==o&&(o=n),i<0)throw new Error("lo must be non-negative");for(null==a&&(a=e.length);i<a;)o(t,e[s=r((i+a)/2)])<0?a=s:i=s+1;return[].splice.apply(e,[i,i-i].concat(t)),t},o=function(e,t,r){return null==r&&(r=n),e.push(t),f(e,0,e.length-1,r)},a=function(e,t){var r,i;return null==t&&(t=n),r=e.pop(),e.length?(i=e[0],e[0]=r,g(e,0,t)):i=r,i},l=function(e,t,r){var i;return null==r&&(r=n),i=e[0],e[0]=t,g(e,0,r),i},s=function(e,t,r){var i;return null==r&&(r=n),e.length&&r(e[0],t)<0&&(t=(i=[e[0],t])[0],e[0]=i[1],g(e,0,r)),t},i=function(e,t){var i,a,o,s,l,u;for(null==t&&(t=n),l=[],a=0,o=(s=function(){u=[];for(var t=0,n=r(e.length/2);0<=n?t<n:t>n;0<=n?t++:t--)u.push(t);return u}.apply(this).reverse()).length;a<o;a++)i=s[a],l.push(g(e,i,t));return l},p=function(e,t,r){var i;if(null==r&&(r=n),-1!==(i=e.indexOf(t)))return f(e,0,i,r),g(e,i,r)},d=function(e,t,r){var a,o,l,u,c;if(null==r&&(r=n),!(o=e.slice(0,t)).length)return o;for(i(o,r),l=0,u=(c=e.slice(t)).length;l<u;l++)a=c[l],s(o,a,r);return o.sort(r).reverse()},h=function(e,t,r){var o,s,l,d,h,p,f,g,v;if(null==r&&(r=n),10*t<=e.length){if(!(l=e.slice(0,t).sort(r)).length)return l;for(s=l[l.length-1],d=0,p=(f=e.slice(t)).length;d<p;d++)r(o=f[d],s)<0&&(u(l,o,0,null,r),l.pop(),s=l[l.length-1]);return l}for(i(e,r),v=[],h=0,g=c(t,e.length);0<=g?h<g:h>g;0<=g?++h:--h)v.push(a(e,r));return v},f=function(e,t,r,i){var a,o,s;for(null==i&&(i=n),a=e[r];r>t&&i(a,o=e[s=r-1>>1])<0;)e[r]=o,r=s;return e[r]=a},g=function(e,t,r){var i,a,o,s,l;for(null==r&&(r=n),a=e.length,l=t,o=e[t],i=2*t+1;i<a;)(s=i+1)<a&&!(r(e[i],e[s])<0)&&(i=s),e[t]=e[i],i=2*(t=i)+1;return e[t]=o,f(e,l,t,r)},t=function(){function e(e){this.cmp=null!=e?e:n,this.nodes=[]}return e.push=o,e.pop=a,e.replace=l,e.pushpop=s,e.heapify=i,e.updateItem=p,e.nlargest=d,e.nsmallest=h,e.prototype.push=function(e){return o(this.nodes,e,this.cmp)},e.prototype.pop=function(){return a(this.nodes,this.cmp)},e.prototype.peek=function(){return this.nodes[0]},e.prototype.contains=function(e){return-1!==this.nodes.indexOf(e)},e.prototype.replace=function(e){return l(this.nodes,e,this.cmp)},e.prototype.pushpop=function(e){return s(this.nodes,e,this.cmp)},e.prototype.heapify=function(){return i(this.nodes,this.cmp)},e.prototype.updateItem=function(e){return p(this.nodes,e,this.cmp)},e.prototype.clear=function(){return this.nodes=[]},e.prototype.empty=function(){return 0===this.nodes.length},e.prototype.size=function(){return this.nodes.length},e.prototype.clone=function(){var t;return(t=new e).nodes=this.nodes.slice(0),t},e.prototype.toArray=function(){return this.nodes.slice(0)},e.prototype.insert=e.prototype.push,e.prototype.top=e.prototype.peek,e.prototype.front=e.prototype.peek,e.prototype.has=e.prototype.contains,e.prototype.copy=e.prototype.clone,e}(),e.exports=t}).call(q)})),it=He({root:null,weight:function(e){return 1},directed:!1}),at={dijkstra:function(e){if(!b(e)){var t=arguments;e={root:t[0],weight:t[1],directed:t[2]}}var n=it(e),r=n.root,i=n.weight,a=n.directed,o=this,s=i,l=v(r)?this.filter(r)[0]:r[0],u={},c={},d={},h=this.byGroup(),p=h.nodes,f=h.edges;f.unmergeBy((function(e){return e.isLoop()}));for(var g=function(e){return u[e.id()]},y=function(e,t){u[e.id()]=t,m.updateItem(e)},m=new rt((function(e,t){return g(e)-g(t)})),x=0;x<p.length;x++){var w=p[x];u[w.id()]=w.same(l)?0:1/0,m.push(w)}for(var E=function(e,t){for(var n,r=(a?e.edgesTo(t):e.edgesWith(t)).intersect(f),i=1/0,o=0;o<r.length;o++){var l=r[o],u=s(l);(u<i||!n)&&(i=u,n=l)}return{edge:n,dist:i}};m.size()>0;){var k=m.pop(),C=g(k),S=k.id();if(d[S]=C,C!==1/0)for(var P=k.neighborhood().intersect(p),D=0;D<P.length;D++){var T=P[D],_=T.id(),M=E(k,T),B=C+M.dist;B<g(T)&&(y(T,B),c[_]={node:k,edge:M.edge})}}return{distanceTo:function(e){var t=v(e)?p.filter(e)[0]:e[0];return d[t.id()]},pathTo:function(e){var t=v(e)?p.filter(e)[0]:e[0],n=[],r=t,i=r.id();if(t.length>0)for(n.unshift(t);c[i];){var a=c[i];n.unshift(a.edge),n.unshift(a.node),i=(r=a.node).id()}return o.spawn(n)}}}},ot={kruskal:function(e){e=e||function(e){return 1};for(var t=this.byGroup(),n=t.nodes,r=t.edges,i=n.length,a=new Array(i),o=n,s=function(e){for(var t=0;t<a.length;t++){if(a[t].has(e))return t}},l=0;l<i;l++)a[l]=this.spawn(n[l]);for(var u=r.sort((function(t,n){return e(t)-e(n)})),c=0;c<u.length;c++){var d=u[c],h=d.source()[0],p=d.target()[0],f=s(h),g=s(p),v=a[f],y=a[g];f!==g&&(o.merge(d),v.merge(y),a.splice(g,1))}return o}},st=He({root:null,goal:null,weight:function(e){return 1},heuristic:function(e){return 0},directed:!1}),lt={aStar:function(e){var t=this.cy(),n=st(e),r=n.root,i=n.goal,a=n.heuristic,o=n.directed,s=n.weight;r=t.collection(r)[0],i=t.collection(i)[0];var l,u,c=r.id(),d=i.id(),h={},p={},f={},g=new rt((function(e,t){return p[e.id()]-p[t.id()]})),v=new Je,y={},m={},b=function(e,t){g.push(e),v.add(t)};b(r,c),h[c]=0,p[c]=a(r);for(var x,w=0;g.size()>0;){if(l=g.pop(),u=l.id(),v.delete(u),w++,u===d){for(var E=[],k=i,C=d,S=m[C];E.unshift(k),null!=S&&E.unshift(S),null!=(k=y[C]);)S=m[C=k.id()];return{found:!0,distance:h[u],path:this.spawn(E),steps:w}}f[u]=!0;for(var P=l._private.edges,D=0;D<P.length;D++){var T=P[D];if(this.hasElementWithId(T.id())&&(!o||T.data("source")===u)){var _=T.source(),M=T.target(),B=_.id()!==u?_:M,N=B.id();if(this.hasElementWithId(N)&&!f[N]){var z=h[u]+s(T);x=N,v.has(x)?z<h[N]&&(h[N]=z,p[N]=z+a(B),y[N]=l,m[N]=T):(h[N]=z,p[N]=z+a(B),b(B,N),y[N]=l,m[N]=T)}}}}return{found:!1,distance:void 0,path:void 0,steps:w}}},ut=He({weight:function(e){return 1},directed:!1}),ct={floydWarshall:function(e){for(var t=this.cy(),n=ut(e),r=n.weight,i=n.directed,a=r,o=this.byGroup(),s=o.nodes,l=o.edges,u=s.length,c=u*u,d=function(e){return s.indexOf(e)},h=function(e){return s[e]},p=new Array(c),f=0;f<c;f++){var g=f%u,y=(f-g)/u;p[f]=y===g?0:1/0}for(var m=new Array(c),b=new Array(c),x=0;x<l.length;x++){var w=l[x],E=w.source()[0],k=w.target()[0];if(E!==k){var C=d(E),S=d(k),P=C*u+S,D=a(w);if(p[P]>D&&(p[P]=D,m[P]=S,b[P]=w),!i){var T=S*u+C;!i&&p[T]>D&&(p[T]=D,m[T]=C,b[T]=w)}}}for(var _=0;_<u;_++)for(var M=0;M<u;M++)for(var B=M*u+_,N=0;N<u;N++){var z=M*u+N,I=_*u+N;p[B]+p[I]<p[z]&&(p[z]=p[B]+p[I],m[z]=m[B])}var A=function(e){return d(function(e){return(v(e)?t.filter(e):e)[0]}(e))};return{distance:function(e,t){var n=A(e),r=A(t);return p[n*u+r]},path:function(e,n){var r=A(e),i=A(n),a=h(r);if(r===i)return a.collection();if(null==m[r*u+i])return t.collection();var o,s=t.collection(),l=r;for(s.merge(a);r!==i;)l=r,r=m[r*u+i],o=b[l*u+r],s.merge(o),s.merge(h(r));return s}}}},dt=He({weight:function(e){return 1},directed:!1,root:null}),ht={bellmanFord:function(e){var t=this,n=dt(e),r=n.weight,i=n.directed,a=n.root,o=r,s=this,l=this.cy(),u=this.byGroup(),c=u.edges,d=u.nodes,h=d.length,p=new $e,f=!1,g=[];a=l.collection(a)[0],c.unmergeBy((function(e){return e.isLoop()}));for(var y=c.length,m=function(e){var t=p.get(e.id());return t||(t={},p.set(e.id(),t)),t},b=function(e){return(v(e)?l.$(e):e)[0]},x=0;x<h;x++){var w=d[x],E=m(w);w.same(a)?E.dist=0:E.dist=1/0,E.pred=null,E.edge=null}for(var k=!1,C=function(e,t,n,r,i,a){var o=r.dist+a;o<i.dist&&!n.same(r.edge)&&(i.dist=o,i.pred=e,i.edge=n,k=!0)},S=1;S<h;S++){k=!1;for(var P=0;P<y;P++){var D=c[P],T=D.source(),_=D.target(),M=o(D),B=m(T),N=m(_);C(T,0,D,B,N,M),i||C(_,0,D,N,B,M)}if(!k)break}if(k)for(var z=[],I=0;I<y;I++){var A=c[I],L=A.source(),O=A.target(),R=o(A),V=m(L).dist,F=m(O).dist;if(V+R<F||!i&&F+R<V){if(f||(je("Graph contains a negative weight cycle for Bellman-Ford"),f=!0),!1===e.findNegativeWeightCycles)break;var j=[];V+R<F&&j.push(L),!i&&F+R<V&&j.push(O);for(var q=j.length,Y=0;Y<q;Y++){var X=j[Y],W=[X];W.push(m(X).edge);for(var H=m(X).pred;-1===W.indexOf(H);)W.push(H),W.push(m(H).edge),H=m(H).pred;for(var K=(W=W.slice(W.indexOf(H)))[0].id(),G=0,U=2;U<W.length;U+=2)W[U].id()<K&&(K=W[U].id(),G=U);(W=W.slice(G).concat(W.slice(0,G))).push(W[0]);var Z=W.map((function(e){return e.id()})).join(",");-1===z.indexOf(Z)&&(g.push(s.spawn(W)),z.push(Z))}}}return{distanceTo:function(e){return m(b(e)).dist},pathTo:function(e){for(var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:a,r=b(e),i=[],o=r;;){if(null==o)return t.spawn();var l=m(o),u=l.edge,c=l.pred;if(i.unshift(o[0]),o.same(n)&&i.length>0)break;null!=u&&i.unshift(u),o=c}return s.spawn(i)},hasNegativeWeightCycle:f,negativeWeightCycles:g}}},pt=Math.sqrt(2),ft=function(e,t,n){0===n.length&&Ve("Karger-Stein must be run on a connected (sub)graph");for(var r=n[e],i=r[1],a=r[2],o=t[i],s=t[a],l=n,u=l.length-1;u>=0;u--){var c=l[u],d=c[1],h=c[2];(t[d]===o&&t[h]===s||t[d]===s&&t[h]===o)&&l.splice(u,1)}for(var p=0;p<l.length;p++){var f=l[p];f[1]===s?(l[p]=f.slice(),l[p][1]=o):f[2]===s&&(l[p]=f.slice(),l[p][2]=o)}for(var g=0;g<t.length;g++)t[g]===s&&(t[g]=o);return l},gt=function(e,t,n,r){for(;n>r;){var i=Math.floor(Math.random()*t.length);t=ft(i,e,t),n--}return t},vt={kargerStein:function(){var e=this,t=this.byGroup(),n=t.nodes,r=t.edges;r.unmergeBy((function(e){return e.isLoop()}));var i=n.length,a=r.length,o=Math.ceil(Math.pow(Math.log(i)/Math.LN2,2)),s=Math.floor(i/pt);if(!(i<2)){for(var l=[],u=0;u<a;u++){var c=r[u];l.push([u,n.indexOf(c.source()),n.indexOf(c.target())])}for(var d=1/0,h=[],p=new Array(i),f=new Array(i),g=new Array(i),v=function(e,t){for(var n=0;n<i;n++)t[n]=e[n]},y=0;y<=o;y++){for(var m=0;m<i;m++)f[m]=m;var b=gt(f,l.slice(),i,s),x=b.slice();v(f,g);var w=gt(f,b,s,2),E=gt(g,x,s,2);w.length<=E.length&&w.length<d?(d=w.length,h=w,v(f,p)):E.length<=w.length&&E.length<d&&(d=E.length,h=E,v(g,p))}for(var k=this.spawn(h.map((function(e){return r[e[0]]}))),C=this.spawn(),S=this.spawn(),P=p[0],D=0;D<p.length;D++){var T=p[D],_=n[D];T===P?C.merge(_):S.merge(_)}var M=function(t){var n=e.spawn();return t.forEach((function(t){n.merge(t),t.connectedEdges().forEach((function(t){e.contains(t)&&!k.contains(t)&&n.merge(t)}))})),n},B=[M(C),M(S)];return{cut:k,components:B,partition1:C,partition2:S}}Ve("At least 2 nodes are required for Karger-Stein algorithm")}},yt=function(e,t,n){return{x:e.x*t+n.x,y:e.y*t+n.y}},mt=function(e,t,n){return{x:(e.x-n.x)/t,y:(e.y-n.y)/t}},bt=function(e){return{x:e[0],y:e[1]}},xt=function(e,t){return Math.atan2(t,e)-Math.PI/2},wt=Math.log2||function(e){return Math.log(e)/Math.log(2)},Et=function(e){return e>0?1:e<0?-1:0},kt=function(e,t){return Math.sqrt(Ct(e,t))},Ct=function(e,t){var n=t.x-e.x,r=t.y-e.y;return n*n+r*r},St=function(e){for(var t=e.length,n=0,r=0;r<t;r++)n+=e[r];for(var i=0;i<t;i++)e[i]=e[i]/n;return e},Pt=function(e,t,n,r){return(1-r)*(1-r)*e+2*(1-r)*r*t+r*r*n},Dt=function(e,t,n,r){return{x:Pt(e.x,t.x,n.x,r),y:Pt(e.y,t.y,n.y,r)}},Tt=function(e,t,n){return Math.max(e,Math.min(n,t))},_t=function(e){if(null==e)return{x1:1/0,y1:1/0,x2:-1/0,y2:-1/0,w:0,h:0};if(null!=e.x1&&null!=e.y1){if(null!=e.x2&&null!=e.y2&&e.x2>=e.x1&&e.y2>=e.y1)return{x1:e.x1,y1:e.y1,x2:e.x2,y2:e.y2,w:e.x2-e.x1,h:e.y2-e.y1};if(null!=e.w&&null!=e.h&&e.w>=0&&e.h>=0)return{x1:e.x1,y1:e.y1,x2:e.x1+e.w,y2:e.y1+e.h,w:e.w,h:e.h}}},Mt=function(e,t){e.x1=Math.min(e.x1,t.x1),e.x2=Math.max(e.x2,t.x2),e.w=e.x2-e.x1,e.y1=Math.min(e.y1,t.y1),e.y2=Math.max(e.y2,t.y2),e.h=e.y2-e.y1},Bt=function(e,t,n){e.x1=Math.min(e.x1,t),e.x2=Math.max(e.x2,t),e.w=e.x2-e.x1,e.y1=Math.min(e.y1,n),e.y2=Math.max(e.y2,n),e.h=e.y2-e.y1},Nt=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return e.x1-=t,e.x2+=t,e.y1-=t,e.y2+=t,e.w=e.x2-e.x1,e.h=e.y2-e.y1,e},zt=function(e){var t,n,r,i,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[0];if(1===o.length)t=n=r=i=o[0];else if(2===o.length)t=r=o[0],i=n=o[1];else if(4===o.length){var s=a(o,4);t=s[0],n=s[1],r=s[2],i=s[3]}return e.x1-=i,e.x2+=n,e.y1-=t,e.y2+=r,e.w=e.x2-e.x1,e.h=e.y2-e.y1,e},It=function(e,t){e.x1=t.x1,e.y1=t.y1,e.x2=t.x2,e.y2=t.y2,e.w=e.x2-e.x1,e.h=e.y2-e.y1},At=function(e,t){return!(e.x1>t.x2)&&(!(t.x1>e.x2)&&(!(e.x2<t.x1)&&(!(t.x2<e.x1)&&(!(e.y2<t.y1)&&(!(t.y2<e.y1)&&(!(e.y1>t.y2)&&!(t.y1>e.y2)))))))},Lt=function(e,t,n){return e.x1<=t&&t<=e.x2&&e.y1<=n&&n<=e.y2},Ot=function(e,t){return Lt(e,t.x1,t.y1)&&Lt(e,t.x2,t.y2)},Rt=function(e,t,n,r,i,a,o){var s,l,u=arguments.length>7&&void 0!==arguments[7]?arguments[7]:"auto",c="auto"===u?nn(i,a):u,d=i/2,h=a/2,p=(c=Math.min(c,d,h))!==d,f=c!==h;if(p){var g=n-d+c-o,v=r-h-o,y=n+d-c+o,m=v;if((s=Zt(e,t,n,r,g,v,y,m,!1)).length>0)return s}if(f){var b=n+d+o,x=r-h+c-o,w=b,E=r+h-c+o;if((s=Zt(e,t,n,r,b,x,w,E,!1)).length>0)return s}if(p){var k=n-d+c-o,C=r+h+o,S=n+d-c+o,P=C;if((s=Zt(e,t,n,r,k,C,S,P,!1)).length>0)return s}if(f){var D=n-d-o,T=r-h+c-o,_=D,M=r+h-c+o;if((s=Zt(e,t,n,r,D,T,_,M,!1)).length>0)return s}var B=n-d+c,N=r-h+c;if((l=Gt(e,t,n,r,B,N,c+o)).length>0&&l[0]<=B&&l[1]<=N)return[l[0],l[1]];var z=n+d-c,I=r-h+c;if((l=Gt(e,t,n,r,z,I,c+o)).length>0&&l[0]>=z&&l[1]<=I)return[l[0],l[1]];var A=n+d-c,L=r+h-c;if((l=Gt(e,t,n,r,A,L,c+o)).length>0&&l[0]>=A&&l[1]>=L)return[l[0],l[1]];var O=n-d+c,R=r+h-c;return(l=Gt(e,t,n,r,O,R,c+o)).length>0&&l[0]<=O&&l[1]>=R?[l[0],l[1]]:[]},Vt=function(e,t,n,r,i,a,o){var s=o,l=Math.min(n,i),u=Math.max(n,i),c=Math.min(r,a),d=Math.max(r,a);return l-s<=e&&e<=u+s&&c-s<=t&&t<=d+s},Ft=function(e,t,n,r,i,a,o,s,l){var u=Math.min(n,o,i)-l,c=Math.max(n,o,i)+l,d=Math.min(r,s,a)-l,h=Math.max(r,s,a)+l;return!(e<u||e>c||t<d||t>h)},jt=function(e,t,n,r,i,a,o,s){var l=[];!function(e,t,n,r,i){var a,o,s,l,u,c,d,h;0===e&&(e=1e-5),s=-27*(r/=e)+(t/=e)*(9*(n/=e)-t*t*2),a=(o=(3*n-t*t)/9)*o*o+(s/=54)*s,i[1]=0,d=t/3,a>0?(u=(u=s+Math.sqrt(a))<0?-Math.pow(-u,1/3):Math.pow(u,1/3),c=(c=s-Math.sqrt(a))<0?-Math.pow(-c,1/3):Math.pow(c,1/3),i[0]=-d+u+c,d+=(u+c)/2,i[4]=i[2]=-d,d=Math.sqrt(3)*(-c+u)/2,i[3]=d,i[5]=-d):(i[5]=i[3]=0,0===a?(h=s<0?-Math.pow(-s,1/3):Math.pow(s,1/3),i[0]=2*h-d,i[4]=i[2]=-(h+d)):(l=(o=-o)*o*o,l=Math.acos(s/Math.sqrt(l)),h=2*Math.sqrt(o),i[0]=-d+h*Math.cos(l/3),i[2]=-d+h*Math.cos((l+2*Math.PI)/3),i[4]=-d+h*Math.cos((l+4*Math.PI)/3)))}(1*n*n-4*n*i+2*n*o+4*i*i-4*i*o+o*o+r*r-4*r*a+2*r*s+4*a*a-4*a*s+s*s,9*n*i-3*n*n-3*n*o-6*i*i+3*i*o+9*r*a-3*r*r-3*r*s-6*a*a+3*a*s,3*n*n-6*n*i+n*o-n*e+2*i*i+2*i*e-o*e+3*r*r-6*r*a+r*s-r*t+2*a*a+2*a*t-s*t,1*n*i-n*n+n*e-i*e+r*a-r*r+r*t-a*t,l);for(var u=[],c=0;c<6;c+=2)Math.abs(l[c+1])<1e-7&&l[c]>=0&&l[c]<=1&&u.push(l[c]);u.push(1),u.push(0);for(var d,h,p,f=-1,g=0;g<u.length;g++)d=Math.pow(1-u[g],2)*n+2*(1-u[g])*u[g]*i+u[g]*u[g]*o,h=Math.pow(1-u[g],2)*r+2*(1-u[g])*u[g]*a+u[g]*u[g]*s,p=Math.pow(d-e,2)+Math.pow(h-t,2),f>=0?p<f&&(f=p):f=p;return f},qt=function(e,t,n,r,i,a){var o=[e-n,t-r],s=[i-n,a-r],l=s[0]*s[0]+s[1]*s[1],u=o[0]*o[0]+o[1]*o[1],c=o[0]*s[0]+o[1]*s[1],d=c*c/l;return c<0?u:d>l?(e-i)*(e-i)+(t-a)*(t-a):u-d},Yt=function(e,t,n){for(var r,i,a,o,s=0,l=0;l<n.length/2;l++)if(r=n[2*l],i=n[2*l+1],l+1<n.length/2?(a=n[2*(l+1)],o=n[2*(l+1)+1]):(a=n[2*(l+1-n.length/2)],o=n[2*(l+1-n.length/2)+1]),r==e&&a==e);else{if(!(r>=e&&e>=a||r<=e&&e<=a))continue;(e-r)/(a-r)*(o-i)+i>t&&s++}return s%2!=0},Xt=function(e,t,n,r,i,a,o,s,l){var u,c=new Array(n.length);null!=s[0]?(u=Math.atan(s[1]/s[0]),s[0]<0?u+=Math.PI/2:u=-u-Math.PI/2):u=s;for(var d,h=Math.cos(-u),p=Math.sin(-u),f=0;f<c.length/2;f++)c[2*f]=a/2*(n[2*f]*h-n[2*f+1]*p),c[2*f+1]=o/2*(n[2*f+1]*h+n[2*f]*p),c[2*f]+=r,c[2*f+1]+=i;if(l>0){var g=Ht(c,-l);d=Wt(g)}else d=c;return Yt(e,t,d)},Wt=function(e){for(var t,n,r,i,a,o,s,l,u=new Array(e.length/2),c=0;c<e.length/4;c++){t=e[4*c],n=e[4*c+1],r=e[4*c+2],i=e[4*c+3],c<e.length/4-1?(a=e[4*(c+1)],o=e[4*(c+1)+1],s=e[4*(c+1)+2],l=e[4*(c+1)+3]):(a=e[0],o=e[1],s=e[2],l=e[3]);var d=Zt(t,n,r,i,a,o,s,l,!0);u[2*c]=d[0],u[2*c+1]=d[1]}return u},Ht=function(e,t){for(var n,r,i,a,o=new Array(2*e.length),s=0;s<e.length/2;s++){n=e[2*s],r=e[2*s+1],s<e.length/2-1?(i=e[2*(s+1)],a=e[2*(s+1)+1]):(i=e[0],a=e[1]);var l=a-r,u=-(i-n),c=Math.sqrt(l*l+u*u),d=l/c,h=u/c;o[4*s]=n+d*t,o[4*s+1]=r+h*t,o[4*s+2]=i+d*t,o[4*s+3]=a+h*t}return o},Kt=function(e,t,n,r,i,a,o){return e-=i,t-=a,(e/=n/2+o)*e+(t/=r/2+o)*t<=1},Gt=function(e,t,n,r,i,a,o){var s=[n-e,r-t],l=[e-i,t-a],u=s[0]*s[0]+s[1]*s[1],c=2*(l[0]*s[0]+l[1]*s[1]),d=c*c-4*u*(l[0]*l[0]+l[1]*l[1]-o*o);if(d<0)return[];var h=(-c+Math.sqrt(d))/(2*u),p=(-c-Math.sqrt(d))/(2*u),f=Math.min(h,p),g=Math.max(h,p),v=[];if(f>=0&&f<=1&&v.push(f),g>=0&&g<=1&&v.push(g),0===v.length)return[];var y=v[0]*s[0]+e,m=v[0]*s[1]+t;return v.length>1?v[0]==v[1]?[y,m]:[y,m,v[1]*s[0]+e,v[1]*s[1]+t]:[y,m]},Ut=function(e,t,n){return t<=e&&e<=n||n<=e&&e<=t?e:e<=t&&t<=n||n<=t&&t<=e?t:n},Zt=function(e,t,n,r,i,a,o,s,l){var u=e-i,c=n-e,d=o-i,h=t-a,p=r-t,f=s-a,g=d*h-f*u,v=c*h-p*u,y=f*c-d*p;if(0!==y){var m=g/y,b=v/y;return-.001<=m&&m<=1.001&&-.001<=b&&b<=1.001||l?[e+m*c,t+m*p]:[]}return 0===g||0===v?Ut(e,n,o)===o?[o,s]:Ut(e,n,i)===i?[i,a]:Ut(i,o,n)===n?[n,r]:[]:[]},$t=function(e,t,n,r,i,a,o,s){var l,u,c,d,h,p,f=[],g=new Array(n.length),v=!0;if(null==a&&(v=!1),v){for(var y=0;y<g.length/2;y++)g[2*y]=n[2*y]*a+r,g[2*y+1]=n[2*y+1]*o+i;if(s>0){var m=Ht(g,-s);u=Wt(m)}else u=g}else u=n;for(var b=0;b<u.length/2;b++)c=u[2*b],d=u[2*b+1],b<u.length/2-1?(h=u[2*(b+1)],p=u[2*(b+1)+1]):(h=u[0],p=u[1]),0!==(l=Zt(e,t,r,i,c,d,h,p)).length&&f.push(l[0],l[1]);return f},Qt=function(e,t,n){var r=[e[0]-t[0],e[1]-t[1]],i=Math.sqrt(r[0]*r[0]+r[1]*r[1]),a=(i-n)/i;return a<0&&(a=1e-5),[t[0]+a*r[0],t[1]+a*r[1]]},Jt=function(e,t){var n=tn(e,t);return n=en(n)},en=function(e){for(var t,n,r=e.length/2,i=1/0,a=1/0,o=-1/0,s=-1/0,l=0;l<r;l++)t=e[2*l],n=e[2*l+1],i=Math.min(i,t),o=Math.max(o,t),a=Math.min(a,n),s=Math.max(s,n);for(var u=2/(o-i),c=2/(s-a),d=0;d<r;d++)t=e[2*d]=e[2*d]*u,n=e[2*d+1]=e[2*d+1]*c,i=Math.min(i,t),o=Math.max(o,t),a=Math.min(a,n),s=Math.max(s,n);if(a<-1)for(var h=0;h<r;h++)n=e[2*h+1]=e[2*h+1]+(-1-a);return e},tn=function(e,t){var n=1/e*2*Math.PI,r=e%2==0?Math.PI/2+n/2:Math.PI/2;r+=t;for(var i,a=new Array(2*e),o=0;o<e;o++)i=o*n+r,a[2*o]=Math.cos(i),a[2*o+1]=Math.sin(-i);return a},nn=function(e,t){return Math.min(e/4,t/4,8)},rn=function(e,t){return Math.min(e/10,t/10,8)},an=function(e,t){return{heightOffset:Math.min(15,.05*t),widthOffset:Math.min(100,.25*e),ctrlPtOffsetPct:.05}},on=He({dampingFactor:.8,precision:1e-6,iterations:200,weight:function(e){return 1}}),sn={pageRank:function(e){for(var t=on(e),n=t.dampingFactor,r=t.precision,i=t.iterations,a=t.weight,o=this._private.cy,s=this.byGroup(),l=s.nodes,u=s.edges,c=l.length,d=c*c,h=u.length,p=new Array(d),f=new Array(c),g=(1-n)/c,v=0;v<c;v++){for(var y=0;y<c;y++){p[v*c+y]=0}f[v]=0}for(var m=0;m<h;m++){var b=u[m],x=b.data("source"),w=b.data("target");if(x!==w){var E=l.indexOfId(x),k=l.indexOfId(w),C=a(b);p[k*c+E]+=C,f[E]+=C}}for(var S=1/c+g,P=0;P<c;P++)if(0===f[P])for(var D=0;D<c;D++){p[D*c+P]=S}else for(var T=0;T<c;T++){var _=T*c+P;p[_]=p[_]/f[P]+g}for(var M,B=new Array(c),N=new Array(c),z=0;z<c;z++)B[z]=1;for(var I=0;I<i;I++){for(var A=0;A<c;A++)N[A]=0;for(var L=0;L<c;L++)for(var O=0;O<c;O++){var R=L*c+O;N[L]+=p[R]*B[O]}St(N),M=B,B=N,N=M;for(var V=0,F=0;F<c;F++){var j=M[F]-B[F];V+=j*j}if(V<r)break}return{rank:function(e){return e=o.collection(e)[0],B[l.indexOf(e)]}}}},ln=He({root:null,weight:function(e){return 1},directed:!1,alpha:0}),un={degreeCentralityNormalized:function(e){e=ln(e);var t=this.cy(),n=this.nodes(),r=n.length;if(e.directed){for(var i={},a={},o=0,s=0,l=0;l<r;l++){var u=n[l],c=u.id();e.root=u;var d=this.degreeCentrality(e);o<d.indegree&&(o=d.indegree),s<d.outdegree&&(s=d.outdegree),i[c]=d.indegree,a[c]=d.outdegree}return{indegree:function(e){return 0==o?0:(v(e)&&(e=t.filter(e)),i[e.id()]/o)},outdegree:function(e){return 0===s?0:(v(e)&&(e=t.filter(e)),a[e.id()]/s)}}}for(var h={},p=0,f=0;f<r;f++){var g=n[f];e.root=g;var y=this.degreeCentrality(e);p<y.degree&&(p=y.degree),h[g.id()]=y.degree}return{degree:function(e){return 0===p?0:(v(e)&&(e=t.filter(e)),h[e.id()]/p)}}},degreeCentrality:function(e){e=ln(e);var t=this.cy(),n=this,r=e,i=r.root,a=r.weight,o=r.directed,s=r.alpha;if(i=t.collection(i)[0],o){for(var l=i.connectedEdges(),u=l.filter((function(e){return e.target().same(i)&&n.has(e)})),c=l.filter((function(e){return e.source().same(i)&&n.has(e)})),d=u.length,h=c.length,p=0,f=0,g=0;g<u.length;g++)p+=a(u[g]);for(var v=0;v<c.length;v++)f+=a(c[v]);return{indegree:Math.pow(d,1-s)*Math.pow(p,s),outdegree:Math.pow(h,1-s)*Math.pow(f,s)}}for(var y=i.connectedEdges().intersection(n),m=y.length,b=0,x=0;x<y.length;x++)b+=a(y[x]);return{degree:Math.pow(m,1-s)*Math.pow(b,s)}}};un.dc=un.degreeCentrality,un.dcn=un.degreeCentralityNormalised=un.degreeCentralityNormalized;var cn=He({harmonic:!0,weight:function(){return 1},directed:!1,root:null}),dn={closenessCentralityNormalized:function(e){for(var t=cn(e),n=t.harmonic,r=t.weight,i=t.directed,a=this.cy(),o={},s=0,l=this.nodes(),u=this.floydWarshall({weight:r,directed:i}),c=0;c<l.length;c++){for(var d=0,h=l[c],p=0;p<l.length;p++)if(c!==p){var f=u.distance(h,l[p]);d+=n?1/f:f}n||(d=1/d),s<d&&(s=d),o[h.id()]=d}return{closeness:function(e){return 0==s?0:(e=v(e)?a.filter(e)[0].id():e.id(),o[e]/s)}}},closenessCentrality:function(e){var t=cn(e),n=t.root,r=t.weight,i=t.directed,a=t.harmonic;n=this.filter(n)[0];for(var o=this.dijkstra({root:n,weight:r,directed:i}),s=0,l=this.nodes(),u=0;u<l.length;u++){var c=l[u];if(!c.same(n)){var d=o.distanceTo(c);s+=a?1/d:d}}return a?s:1/s}};dn.cc=dn.closenessCentrality,dn.ccn=dn.closenessCentralityNormalised=dn.closenessCentralityNormalized;var hn=He({weight:null,directed:!1}),pn={betweennessCentrality:function(e){for(var t=hn(e),n=t.directed,r=t.weight,i=null!=r,a=this.cy(),o=this.nodes(),s={},l={},u=0,c=function(e,t){l[e]=t,t>u&&(u=t)},d=function(e){return l[e]},h=0;h<o.length;h++){var p=o[h],f=p.id();s[f]=n?p.outgoers().nodes():p.openNeighborhood().nodes(),c(f,0)}for(var g=function(e){for(var t=o[e].id(),n=[],l={},u={},h={},p=new rt((function(e,t){return h[e]-h[t]})),f=0;f<o.length;f++){var g=o[f].id();l[g]=[],u[g]=0,h[g]=1/0}for(u[t]=1,h[t]=0,p.push(t);!p.empty();){var v=p.pop();if(n.push(v),i)for(var y=0;y<s[v].length;y++){var m=s[v][y],b=a.getElementById(v),x=void 0;x=b.edgesTo(m).length>0?b.edgesTo(m)[0]:m.edgesTo(b)[0];var w=r(x);m=m.id(),h[m]>h[v]+w&&(h[m]=h[v]+w,p.nodes.indexOf(m)<0?p.push(m):p.updateItem(m),u[m]=0,l[m]=[]),h[m]==h[v]+w&&(u[m]=u[m]+u[v],l[m].push(v))}else for(var E=0;E<s[v].length;E++){var k=s[v][E].id();h[k]==1/0&&(p.push(k),h[k]=h[v]+1),h[k]==h[v]+1&&(u[k]=u[k]+u[v],l[k].push(v))}}for(var C={},S=0;S<o.length;S++)C[o[S].id()]=0;for(;n.length>0;){for(var P=n.pop(),D=0;D<l[P].length;D++){var T=l[P][D];C[T]=C[T]+u[T]/u[P]*(1+C[P])}P!=o[e].id()&&c(P,d(P)+C[P])}},v=0;v<o.length;v++)g(v);var y={betweenness:function(e){var t=a.collection(e).id();return d(t)},betweennessNormalized:function(e){if(0==u)return 0;var t=a.collection(e).id();return d(t)/u}};return y.betweennessNormalised=y.betweennessNormalized,y}};pn.bc=pn.betweennessCentrality;var fn=He({expandFactor:2,inflateFactor:2,multFactor:1,maxIterations:20,attributes:[function(e){return 1}]}),gn=function(e,t){for(var n=0,r=0;r<t.length;r++)n+=t[r](e);return n},vn=function(e,t){for(var n,r=0;r<t;r++){n=0;for(var i=0;i<t;i++)n+=e[i*t+r];for(var a=0;a<t;a++)e[a*t+r]=e[a*t+r]/n}},yn=function(e,t,n){for(var r=new Array(n*n),i=0;i<n;i++){for(var a=0;a<n;a++)r[i*n+a]=0;for(var o=0;o<n;o++)for(var s=0;s<n;s++)r[i*n+s]+=e[i*n+o]*t[o*n+s]}return r},mn=function(e,t,n){for(var r=e.slice(0),i=1;i<n;i++)e=yn(e,r,t);return e},bn=function(e,t,n){for(var r=new Array(t*t),i=0;i<t*t;i++)r[i]=Math.pow(e[i],n);return vn(r,t),r},xn=function(e,t,n,r){for(var i=0;i<n;i++){if(Math.round(e[i]*Math.pow(10,r))/Math.pow(10,r)!==Math.round(t[i]*Math.pow(10,r))/Math.pow(10,r))return!1}return!0},wn=function(e,t){for(var n=0;n<e.length;n++)if(!t[n]||e[n].id()!==t[n].id())return!1;return!0},En=function(e){for(var t=this.nodes(),n=this.edges(),r=this.cy(),i=function(e){return fn(e)}(e),a={},o=0;o<t.length;o++)a[t[o].id()]=o;for(var s,l=t.length,u=l*l,c=new Array(u),d=0;d<u;d++)c[d]=0;for(var h=0;h<n.length;h++){var p=n[h],f=a[p.source().id()],g=a[p.target().id()],v=gn(p,i.attributes);c[f*l+g]+=v,c[g*l+f]+=v}!function(e,t,n){for(var r=0;r<t;r++)e[r*t+r]=n}(c,l,i.multFactor),vn(c,l);for(var y=!0,m=0;y&&m<i.maxIterations;)y=!1,s=mn(c,l,i.expandFactor),c=bn(s,l,i.inflateFactor),xn(c,s,u,4)||(y=!0),m++;var b=function(e,t,n,r){for(var i=[],a=0;a<t;a++){for(var o=[],s=0;s<t;s++)Math.round(1e3*e[a*t+s])/1e3>0&&o.push(n[s]);0!==o.length&&i.push(r.collection(o))}return i}(c,l,t,r);return b=function(e){for(var t=0;t<e.length;t++)for(var n=0;n<e.length;n++)t!=n&&wn(e[t],e[n])&&e.splice(n,1);return e}(b)},kn={markovClustering:En,mcl:En},Cn=function(e){return e},Sn=function(e,t){return Math.abs(t-e)},Pn=function(e,t,n){return e+Sn(t,n)},Dn=function(e,t,n){return e+Math.pow(n-t,2)},Tn=function(e){return Math.sqrt(e)},_n=function(e,t,n){return Math.max(e,Sn(t,n))},Mn=function(e,t,n,r,i){for(var a=arguments.length>5&&void 0!==arguments[5]?arguments[5]:Cn,o=r,s=0;s<e;s++)o=i(o,t(s),n(s));return a(o)},Bn={euclidean:function(e,t,n){return e>=2?Mn(e,t,n,0,Dn,Tn):Mn(e,t,n,0,Pn)},squaredEuclidean:function(e,t,n){return Mn(e,t,n,0,Dn)},manhattan:function(e,t,n){return Mn(e,t,n,0,Pn)},max:function(e,t,n){return Mn(e,t,n,-1/0,_n)}};function Nn(e,t,n,r,i,a){var o;return o=y(e)?e:Bn[e]||Bn.euclidean,0===t&&y(e)?o(i,a):o(t,n,r,i,a)}Bn["squared-euclidean"]=Bn.squaredEuclidean,Bn.squaredeuclidean=Bn.squaredEuclidean;var zn=He({k:2,m:2,sensitivityThreshold:1e-4,distance:"euclidean",maxIterations:10,attributes:[],testMode:!1,testCentroids:null}),In=function(e){return zn(e)},An=function(e,t,n,r,i){var a="kMedoids"!==i?function(e){return n[e]}:function(e){return r[e](n)},o=n,s=t;return Nn(e,r.length,a,(function(e){return r[e](t)}),o,s)},Ln=function(e,t,n){for(var r=n.length,i=new Array(r),a=new Array(r),o=new Array(t),s=null,l=0;l<r;l++)i[l]=e.min(n[l]).value,a[l]=e.max(n[l]).value;for(var u=0;u<t;u++){s=[];for(var c=0;c<r;c++)s[c]=Math.random()*(a[c]-i[c])+i[c];o[u]=s}return o},On=function(e,t,n,r,i){for(var a=1/0,o=0,s=0;s<t.length;s++){var l=An(n,e,t[s],r,i);l<a&&(a=l,o=s)}return o},Rn=function(e,t,n){for(var r=[],i=null,a=0;a<t.length;a++)n[(i=t[a]).id()]===e&&r.push(i);return r},Vn=function(e,t,n){return Math.abs(t-e)<=n},Fn=function(e,t,n){for(var r=0;r<e.length;r++)for(var i=0;i<e[r].length;i++){if(Math.abs(e[r][i]-t[r][i])>n)return!1}return!0},jn=function(e,t,n){for(var r=0;r<n;r++)if(e===t[r])return!0;return!1},qn=function(e,t){var n=new Array(t);if(e.length<50)for(var r=0;r<t;r++){for(var i=e[Math.floor(Math.random()*e.length)];jn(i,n,r);)i=e[Math.floor(Math.random()*e.length)];n[r]=i}else for(var a=0;a<t;a++)n[a]=e[Math.floor(Math.random()*e.length)];return n},Yn=function(e,t,n){for(var r=0,i=0;i<t.length;i++)r+=An("manhattan",t[i],e,n,"kMedoids");return r},Xn=function(e,t,n,r,i){for(var a,o,s=0;s<t.length;s++)for(var l=0;l<e.length;l++)r[s][l]=Math.pow(n[s][l],i.m);for(var u=0;u<e.length;u++)for(var c=0;c<i.attributes.length;c++){a=0,o=0;for(var d=0;d<t.length;d++)a+=r[d][u]*i.attributes[c](t[d]),o+=r[d][u];e[u][c]=a/o}},Wn=function(e,t,n,r,i){for(var a=0;a<e.length;a++)t[a]=e[a].slice();for(var o,s,l,u=2/(i.m-1),c=0;c<n.length;c++)for(var d=0;d<r.length;d++){o=0;for(var h=0;h<n.length;h++)s=An(i.distance,r[d],n[c],i.attributes,"cmeans"),l=An(i.distance,r[d],n[h],i.attributes,"cmeans"),o+=Math.pow(s/l,u);e[d][c]=1/o}},Hn=function(e){var t,n,r,i,a=this.cy(),o=this.nodes(),s=In(e);r=new Array(o.length);for(var l=0;l<o.length;l++)r[l]=new Array(s.k);n=new Array(o.length);for(var u=0;u<o.length;u++)n[u]=new Array(s.k);for(var c=0;c<o.length;c++){for(var d=0,h=0;h<s.k;h++)n[c][h]=Math.random(),d+=n[c][h];for(var p=0;p<s.k;p++)n[c][p]=n[c][p]/d}t=new Array(s.k);for(var f=0;f<s.k;f++)t[f]=new Array(s.attributes.length);i=new Array(o.length);for(var g=0;g<o.length;g++)i[g]=new Array(s.k);for(var v=!0,y=0;v&&y<s.maxIterations;)v=!1,Xn(t,o,n,i,s),Wn(n,r,t,o,s),Fn(n,r,s.sensitivityThreshold)||(v=!0),y++;return{clusters:function(e,t,n,r){for(var i,a,o=new Array(n.k),s=0;s<o.length;s++)o[s]=[];for(var l=0;l<t.length;l++){i=-1/0,a=-1;for(var u=0;u<t[0].length;u++)t[l][u]>i&&(i=t[l][u],a=u);o[a].push(e[l])}for(var c=0;c<o.length;c++)o[c]=r.collection(o[c]);return o}(o,n,s,a),degreeOfMembership:n}},Kn={kMeans:function(t){var n,r=this.cy(),i=this.nodes(),a=null,o=In(t),s=new Array(o.k),l={};o.testMode?"number"==typeof o.testCentroids?(o.testCentroids,n=Ln(i,o.k,o.attributes)):n="object"===e(o.testCentroids)?o.testCentroids:Ln(i,o.k,o.attributes):n=Ln(i,o.k,o.attributes);for(var u=!0,c=0;u&&c<o.maxIterations;){for(var d=0;d<i.length;d++)l[(a=i[d]).id()]=On(a,n,o.distance,o.attributes,"kMeans");u=!1;for(var h=0;h<o.k;h++){var p=Rn(h,i,l);if(0!==p.length){for(var f=o.attributes.length,g=n[h],v=new Array(f),y=new Array(f),m=0;m<f;m++){y[m]=0;for(var b=0;b<p.length;b++)a=p[b],y[m]+=o.attributes[m](a);v[m]=y[m]/p.length,Vn(v[m],g[m],o.sensitivityThreshold)||(u=!0)}n[h]=v,s[h]=r.collection(p)}}c++}return s},kMedoids:function(t){var n,r,i=this.cy(),a=this.nodes(),o=null,s=In(t),l=new Array(s.k),u={},c=new Array(s.k);s.testMode?"number"==typeof s.testCentroids||(n="object"===e(s.testCentroids)?s.testCentroids:qn(a,s.k)):n=qn(a,s.k);for(var d=!0,h=0;d&&h<s.maxIterations;){for(var p=0;p<a.length;p++)u[(o=a[p]).id()]=On(o,n,s.distance,s.attributes,"kMedoids");d=!1;for(var f=0;f<n.length;f++){var g=Rn(f,a,u);if(0!==g.length){c[f]=Yn(n[f],g,s.attributes);for(var v=0;v<g.length;v++)(r=Yn(g[v],g,s.attributes))<c[f]&&(c[f]=r,n[f]=g[v],d=!0);l[f]=i.collection(g)}}h++}return l},fuzzyCMeans:Hn,fcm:Hn},Gn=He({distance:"euclidean",linkage:"min",mode:"threshold",threshold:1/0,addDendrogram:!1,dendrogramDepth:0,attributes:[]}),Un={single:"min",complete:"max"},Zn=function(e,t,n,r,i){for(var a,o=0,s=1/0,l=i.attributes,u=function(e,t){return Nn(i.distance,l.length,(function(t){return l[t](e)}),(function(e){return l[e](t)}),e,t)},c=0;c<e.length;c++){var d=e[c].key,h=n[d][r[d]];h<s&&(o=d,s=h)}if("threshold"===i.mode&&s>=i.threshold||"dendrogram"===i.mode&&1===e.length)return!1;var p,f=t[o],g=t[r[o]];p="dendrogram"===i.mode?{left:f,right:g,key:f.key}:{value:f.value.concat(g.value),key:f.key},e[f.index]=p,e.splice(g.index,1),t[f.key]=p;for(var v=0;v<e.length;v++){var y=e[v];f.key===y.key?a=1/0:"min"===i.linkage?(a=n[f.key][y.key],n[f.key][y.key]>n[g.key][y.key]&&(a=n[g.key][y.key])):"max"===i.linkage?(a=n[f.key][y.key],n[f.key][y.key]<n[g.key][y.key]&&(a=n[g.key][y.key])):a="mean"===i.linkage?(n[f.key][y.key]*f.size+n[g.key][y.key]*g.size)/(f.size+g.size):"dendrogram"===i.mode?u(y.value,f.value):u(y.value[0],f.value[0]),n[f.key][y.key]=n[y.key][f.key]=a}for(var m=0;m<e.length;m++){var b=e[m].key;if(r[b]===f.key||r[b]===g.key){for(var x=b,w=0;w<e.length;w++){var E=e[w].key;n[b][E]<n[b][x]&&(x=E)}r[b]=x}e[m].index=m}return f.key=g.key=f.index=g.index=null,!0},$n=function e(t,n,r){t&&(t.value?n.push(t.value):(t.left&&e(t.left,n),t.right&&e(t.right,n)))},Qn=function(e){for(var t=this.cy(),n=this.nodes(),r=function(e){var t=Gn(e),n=Un[t.linkage];return null!=n&&(t.linkage=n),t}(e),i=r.attributes,a=function(e,t){return Nn(r.distance,i.length,(function(t){return i[t](e)}),(function(e){return i[e](t)}),e,t)},o=[],s=[],l=[],u=[],c=0;c<n.length;c++){var d={value:"dendrogram"===r.mode?n[c]:[n[c]],key:c,index:c};o[c]=d,u[c]=d,s[c]=[],l[c]=0}for(var h=0;h<o.length;h++)for(var p=0;p<=h;p++){var f=void 0;f="dendrogram"===r.mode?h===p?1/0:a(o[h].value,o[p].value):h===p?1/0:a(o[h].value[0],o[p].value[0]),s[h][p]=f,s[p][h]=f,f<s[h][l[h]]&&(l[h]=p)}for(var g,v=Zn(o,u,s,l,r);v;)v=Zn(o,u,s,l,r);return"dendrogram"===r.mode?(g=function e(t,n,r){if(!t)return[];var i=[],a=[],o=[];return 0===n?(t.left&&$n(t.left,i),t.right&&$n(t.right,a),o=i.concat(a),[r.collection(o)]):1===n?t.value?[r.collection(t.value)]:(t.left&&$n(t.left,i),t.right&&$n(t.right,a),[r.collection(i),r.collection(a)]):t.value?[r.collection(t.value)]:(t.left&&(i=e(t.left,n-1,r)),t.right&&(a=e(t.right,n-1,r)),i.concat(a))}(o[0],r.dendrogramDepth,t),r.addDendrogram&&function e(t,n){if(!t)return"";if(t.left&&t.right){var r=e(t.left,n),i=e(t.right,n),a=n.add({group:"nodes",data:{id:r+","+i}});return n.add({group:"edges",data:{source:r,target:a.id()}}),n.add({group:"edges",data:{source:i,target:a.id()}}),a.id()}return t.value?t.value.id():void 0}(o[0],t)):(g=new Array(o.length),o.forEach((function(e,n){e.key=e.index=null,g[n]=t.collection(e.value)}))),g},Jn={hierarchicalClustering:Qn,hca:Qn},er=He({distance:"euclidean",preference:"median",damping:.8,maxIterations:1e3,minIterations:100,attributes:[]}),tr=function(e,t,n,r){var i=function(e,t){return r[t](e)};return-Nn(e,r.length,(function(e){return i(t,e)}),(function(e){return i(n,e)}),t,n)},nr=function(e,t){return"median"===t?function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e.length,r=!(arguments.length>3&&void 0!==arguments[3])||arguments[3],i=!(arguments.length>4&&void 0!==arguments[4])||arguments[4],a=!(arguments.length>5&&void 0!==arguments[5])||arguments[5];r?e=e.slice(t,n):(n<e.length&&e.splice(n,e.length-n),t>0&&e.splice(0,t));for(var o=0,s=e.length-1;s>=0;s--){var l=e[s];a?isFinite(l)||(e[s]=-1/0,o++):e.splice(s,1)}i&&e.sort((function(e,t){return e-t}));var u=e.length,c=Math.floor(u/2);return u%2!=0?e[c+1+o]:(e[c-1+o]+e[c+o])/2}(e):"mean"===t?function(e){for(var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e.length,r=0,i=0,a=t;a<n;a++){var o=e[a];isFinite(o)&&(r+=o,i++)}return r/i}(e):"min"===t?function(e){for(var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e.length,r=1/0,i=t;i<n;i++){var a=e[i];isFinite(a)&&(r=Math.min(a,r))}return r}(e):"max"===t?function(e){for(var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e.length,r=-1/0,i=t;i<n;i++){var a=e[i];isFinite(a)&&(r=Math.max(a,r))}return r}(e):t},rr=function(e,t,n){for(var r=[],i=0;i<e;i++){for(var a=-1,o=-1/0,s=0;s<n.length;s++){var l=n[s];t[i*e+l]>o&&(a=l,o=t[i*e+l])}a>0&&r.push(a)}for(var u=0;u<n.length;u++)r[n[u]]=n[u];return r},ir=function(e){for(var t,n,r,i,a,o,s=this.cy(),l=this.nodes(),u=function(e){var t=e.damping,n=e.preference;.5<=t&&t<1||Ve("Damping must range on [0.5, 1). Got: ".concat(t));var r=["median","mean","min","max"];return r.some((function(e){return e===n}))||x(n)||Ve("Preference must be one of [".concat(r.map((function(e){return"'".concat(e,"'")})).join(", "),"] or a number. Got: ").concat(n)),er(e)}(e),c={},d=0;d<l.length;d++)c[l[d].id()]=d;n=(t=l.length)*t,r=new Array(n);for(var h=0;h<n;h++)r[h]=-1/0;for(var p=0;p<t;p++)for(var f=0;f<t;f++)p!==f&&(r[p*t+f]=tr(u.distance,l[p],l[f],u.attributes));i=nr(r,u.preference);for(var g=0;g<t;g++)r[g*t+g]=i;a=new Array(n);for(var v=0;v<n;v++)a[v]=0;o=new Array(n);for(var y=0;y<n;y++)o[y]=0;for(var m=new Array(t),b=new Array(t),w=new Array(t),E=0;E<t;E++)m[E]=0,b[E]=0,w[E]=0;for(var k,C=new Array(t*u.minIterations),S=0;S<C.length;S++)C[S]=0;for(k=0;k<u.maxIterations;k++){for(var P=0;P<t;P++){for(var D=-1/0,T=-1/0,_=-1,M=0,B=0;B<t;B++)m[B]=a[P*t+B],(M=o[P*t+B]+r[P*t+B])>=D?(T=D,D=M,_=B):M>T&&(T=M);for(var N=0;N<t;N++)a[P*t+N]=(1-u.damping)*(r[P*t+N]-D)+u.damping*m[N];a[P*t+_]=(1-u.damping)*(r[P*t+_]-T)+u.damping*m[_]}for(var z=0;z<t;z++){for(var I=0,A=0;A<t;A++)m[A]=o[A*t+z],b[A]=Math.max(0,a[A*t+z]),I+=b[A];I-=b[z],b[z]=a[z*t+z],I+=b[z];for(var L=0;L<t;L++)o[L*t+z]=(1-u.damping)*Math.min(0,I-b[L])+u.damping*m[L];o[z*t+z]=(1-u.damping)*(I-b[z])+u.damping*m[z]}for(var O=0,R=0;R<t;R++){var V=o[R*t+R]+a[R*t+R]>0?1:0;C[k%u.minIterations*t+R]=V,O+=V}if(O>0&&(k>=u.minIterations-1||k==u.maxIterations-1)){for(var F=0,j=0;j<t;j++){w[j]=0;for(var q=0;q<u.minIterations;q++)w[j]+=C[q*t+j];0!==w[j]&&w[j]!==u.minIterations||F++}if(F===t)break}}for(var Y=function(e,t,n){for(var r=[],i=0;i<e;i++)t[i*e+i]+n[i*e+i]>0&&r.push(i);return r}(t,a,o),X=function(e,t,n){for(var r=rr(e,t,n),i=0;i<n.length;i++){for(var a=[],o=0;o<r.length;o++)r[o]===n[i]&&a.push(o);for(var s=-1,l=-1/0,u=0;u<a.length;u++){for(var c=0,d=0;d<a.length;d++)c+=t[a[d]*e+a[u]];c>l&&(s=u,l=c)}n[i]=a[s]}return r=rr(e,t,n)}(t,r,Y),W={},H=0;H<Y.length;H++)W[Y[H]]=[];for(var K=0;K<l.length;K++){var G=X[c[l[K].id()]];null!=G&&W[G].push(l[K])}for(var U=new Array(Y.length),Z=0;Z<Y.length;Z++)U[Z]=s.collection(W[Y[Z]]);return U},ar={affinityPropagation:ir,ap:ir},or=He({root:void 0,directed:!1}),sr=function(){var e=this,t={},n=0,r=0,i=[],a=[],o={},s=function s(l,u,c){l===c&&(r+=1),t[u]={id:n,low:n++,cutVertex:!1};var d,h,p,f,g=e.getElementById(u).connectedEdges().intersection(e);0===g.size()?i.push(e.spawn(e.getElementById(u))):g.forEach((function(n){d=n.source().id(),h=n.target().id(),(p=d===u?h:d)!==c&&(f=n.id(),o[f]||(o[f]=!0,a.push({x:u,y:p,edge:n})),p in t?t[u].low=Math.min(t[u].low,t[p].id):(s(l,p,u),t[u].low=Math.min(t[u].low,t[p].low),t[u].id<=t[p].low&&(t[u].cutVertex=!0,function(n,r){for(var o=a.length-1,s=[],l=e.spawn();a[o].x!=n||a[o].y!=r;)s.push(a.pop().edge),o--;s.push(a.pop().edge),s.forEach((function(n){var r=n.connectedNodes().intersection(e);l.merge(n),r.forEach((function(n){var r=n.id(),i=n.connectedEdges().intersection(e);l.merge(n),t[r].cutVertex?l.merge(i.filter((function(e){return e.isLoop()}))):l.merge(i)}))})),i.push(l)}(u,p))))}))};e.forEach((function(e){if(e.isNode()){var n=e.id();n in t||(r=0,s(n,n),t[n].cutVertex=r>1)}}));var l=Object.keys(t).filter((function(e){return t[e].cutVertex})).map((function(t){return e.getElementById(t)}));return{cut:e.spawn(l),components:i}},lr=function(){var e=this,t={},n=0,r=[],i=[],a=e.spawn(e);return e.forEach((function(o){if(o.isNode()){var s=o.id();s in t||function o(s){if(i.push(s),t[s]={index:n,low:n++,explored:!1},e.getElementById(s).connectedEdges().intersection(e).forEach((function(e){var n=e.target().id();n!==s&&(n in t||o(n),t[n].explored||(t[s].low=Math.min(t[s].low,t[n].low)))})),t[s].index===t[s].low){for(var l=e.spawn();;){var u=i.pop();if(l.merge(e.getElementById(u)),t[u].low=t[s].index,t[u].explored=!0,u===s)break}var c=l.edgesWith(l),d=l.merge(c);r.push(d),a=a.difference(d)}}(s)}})),{cut:a,components:r}},ur={};[nt,at,ot,lt,ct,ht,vt,sn,un,dn,pn,kn,Kn,Jn,ar,{hierholzer:function(e){if(!b(e)){var t=arguments;e={root:t[0],directed:t[1]}}var n,r,i,a=or(e),o=a.root,s=a.directed,l=this,u=!1;o&&(i=v(o)?this.filter(o)[0].id():o[0].id());var c={},d={};s?l.forEach((function(e){var t=e.id();if(e.isNode()){var i=e.indegree(!0),a=e.outdegree(!0),o=i-a,s=a-i;1==o?n?u=!0:n=t:1==s?r?u=!0:r=t:(s>1||o>1)&&(u=!0),c[t]=[],e.outgoers().forEach((function(e){e.isEdge()&&c[t].push(e.id())}))}else d[t]=[void 0,e.target().id()]})):l.forEach((function(e){var t=e.id();e.isNode()?(e.degree(!0)%2&&(n?r?u=!0:r=t:n=t),c[t]=[],e.connectedEdges().forEach((function(e){return c[t].push(e.id())}))):d[t]=[e.source().id(),e.target().id()]}));var h={found:!1,trail:void 0};if(u)return h;if(r&&n)if(s){if(i&&r!=i)return h;i=r}else{if(i&&r!=i&&n!=i)return h;i||(i=r)}else i||(i=l[0].id());var p=function(e){for(var t,n,r,i=e,a=[e];c[i].length;)t=c[i].shift(),n=d[t][0],i!=(r=d[t][1])?(c[r]=c[r].filter((function(e){return e!=t})),i=r):s||i==n||(c[n]=c[n].filter((function(e){return e!=t})),i=n),a.unshift(t),a.unshift(i);return a},f=[],g=[];for(g=p(i);1!=g.length;)0==c[g[0]].length?(f.unshift(l.getElementById(g.shift())),f.unshift(l.getElementById(g.shift()))):g=p(g.shift()).concat(g);for(var y in f.unshift(l.getElementById(g.shift())),c)if(c[y].length)return h;return h.found=!0,h.trail=this.spawn(f,!0),h}},{hopcroftTarjanBiconnected:sr,htbc:sr,htb:sr,hopcroftTarjanBiconnectedComponents:sr},{tarjanStronglyConnected:lr,tsc:lr,tscc:lr,tarjanStronglyConnectedComponents:lr}].forEach((function(e){L(ur,e)}));
+/*!
+ Embeddable Minimum Strictly-Compliant Promises/A+ 1.1.1 Thenable
+ Copyright (c) 2013-2014 Ralf S. Engelschall (http://engelschall.com)
+ Licensed under The MIT License (http://opensource.org/licenses/MIT)
+ */
+var cr=function e(t){if(!(this instanceof e))return new e(t);this.id="Thenable/1.0.7",this.state=0,this.fulfillValue=void 0,this.rejectReason=void 0,this.onFulfilled=[],this.onRejected=[],this.proxy={then:this.then.bind(this)},"function"==typeof t&&t.call(this,this.fulfill.bind(this),this.reject.bind(this))};cr.prototype={fulfill:function(e){return dr(this,1,"fulfillValue",e)},reject:function(e){return dr(this,2,"rejectReason",e)},then:function(e,t){var n=new cr;return this.onFulfilled.push(fr(e,n,"fulfill")),this.onRejected.push(fr(t,n,"reject")),hr(this),n.proxy}};var dr=function(e,t,n,r){return 0===e.state&&(e.state=t,e[n]=r,hr(e)),e},hr=function(e){1===e.state?pr(e,"onFulfilled",e.fulfillValue):2===e.state&&pr(e,"onRejected",e.rejectReason)},pr=function(e,t,n){if(0!==e[t].length){var r=e[t];e[t]=[];var i=function(){for(var e=0;e<r.length;e++)r[e](n)};"function"==typeof setImmediate?setImmediate(i):setTimeout(i,0)}},fr=function(e,t,n){return function(r){if("function"!=typeof e)t[n].call(t,r);else{var i;try{i=e(r)}catch(e){return void t.reject(e)}gr(t,i)}}},gr=function t(n,r){if(n!==r&&n.proxy!==r){var i;if("object"===e(r)&&null!==r||"function"==typeof r)try{i=r.then}catch(e){return void n.reject(e)}if("function"!=typeof i)n.fulfill(r);else{var a=!1;try{i.call(r,(function(e){a||(a=!0,e===r?n.reject(new TypeError("circular thenable chain")):t(n,e))}),(function(e){a||(a=!0,n.reject(e))}))}catch(e){a||n.reject(e)}}}else n.reject(new TypeError("cannot resolve promise with itself"))};cr.all=function(e){return new cr((function(t,n){for(var r=new Array(e.length),i=0,a=function(n,a){r[n]=a,++i===e.length&&t(r)},o=0;o<e.length;o++)!function(t){var r=e[t];null!=r&&null!=r.then?r.then((function(e){a(t,e)}),(function(e){n(e)})):a(t,r)}(o)}))},cr.resolve=function(e){return new cr((function(t,n){t(e)}))},cr.reject=function(e){return new cr((function(t,n){n(e)}))};var vr="undefined"!=typeof Promise?Promise:cr,yr=function(e,t,n){var r=S(e),i=!r,a=this._private=L({duration:1e3},t,n);if(a.target=e,a.style=a.style||a.css,a.started=!1,a.playing=!1,a.hooked=!1,a.applying=!1,a.progress=0,a.completes=[],a.frames=[],a.complete&&y(a.complete)&&a.completes.push(a.complete),i){var o=e.position();a.startPosition=a.startPosition||{x:o.x,y:o.y},a.startStyle=a.startStyle||e.cy().style().getAnimationStartStyle(e,a.style)}if(r){var s=e.pan();a.startPan={x:s.x,y:s.y},a.startZoom=e.zoom()}this.length=1,this[0]=this},mr=yr.prototype;L(mr,{instanceString:function(){return"animation"},hook:function(){var e=this._private;if(!e.hooked){var t=e.target._private.animation;(e.queue?t.queue:t.current).push(this),E(e.target)&&e.target.cy().addToAnimationPool(e.target),e.hooked=!0}return this},play:function(){var e=this._private;return 1===e.progress&&(e.progress=0),e.playing=!0,e.started=!1,e.stopped=!1,this.hook(),this},playing:function(){return this._private.playing},apply:function(){var e=this._private;return e.applying=!0,e.started=!1,e.stopped=!1,this.hook(),this},applying:function(){return this._private.applying},pause:function(){var e=this._private;return e.playing=!1,e.started=!1,this},stop:function(){var e=this._private;return e.playing=!1,e.started=!1,e.stopped=!0,this},rewind:function(){return this.progress(0)},fastforward:function(){return this.progress(1)},time:function(e){var t=this._private;return void 0===e?t.progress*t.duration:this.progress(e/t.duration)},progress:function(e){var t=this._private,n=t.playing;return void 0===e?t.progress:(n&&this.pause(),t.progress=e,t.started=!1,n&&this.play(),this)},completed:function(){return 1===this._private.progress},reverse:function(){var e=this._private,t=e.playing;t&&this.pause(),e.progress=1-e.progress,e.started=!1;var n=function(t,n){var r=e[t];null!=r&&(e[t]=e[n],e[n]=r)};if(n("zoom","startZoom"),n("pan","startPan"),n("position","startPosition"),e.style)for(var r=0;r<e.style.length;r++){var i=e.style[r],a=i.name,o=e.startStyle[a];e.startStyle[a]=i,e.style[r]=o}return t&&this.play(),this},promise:function(e){var t,n=this._private;switch(e){case"frame":t=n.frames;break;default:case"complete":case"completed":t=n.completes}return new vr((function(e,n){t.push((function(){e()}))}))}}),mr.complete=mr.completed,mr.run=mr.play,mr.running=mr.playing;var br={animated:function(){return function(){var e=void 0!==this.length?this:[this];if(!(this._private.cy||this).styleEnabled())return!1;var t=e[0];return t?t._private.animation.current.length>0:void 0}},clearQueue:function(){return function(){var e=void 0!==this.length?this:[this];if(!(this._private.cy||this).styleEnabled())return this;for(var t=0;t<e.length;t++){e[t]._private.animation.queue=[]}return this}},delay:function(){return function(e,t){return(this._private.cy||this).styleEnabled()?this.animate({delay:e,duration:e,complete:t}):this}},delayAnimation:function(){return function(e,t){return(this._private.cy||this).styleEnabled()?this.animation({delay:e,duration:e,complete:t}):this}},animation:function(){return function(e,t){var n=void 0!==this.length,r=n?this:[this],i=this._private.cy||this,a=!n,o=!a;if(!i.styleEnabled())return this;var s=i.style();if(e=L({},e,t),0===Object.keys(e).length)return new yr(r[0],e);switch(void 0===e.duration&&(e.duration=400),e.duration){case"slow":e.duration=600;break;case"fast":e.duration=200}if(o&&(e.style=s.getPropsList(e.style||e.css),e.css=void 0),o&&null!=e.renderedPosition){var l=e.renderedPosition,u=i.pan(),c=i.zoom();e.position=mt(l,c,u)}if(a&&null!=e.panBy){var d=e.panBy,h=i.pan();e.pan={x:h.x+d.x,y:h.y+d.y}}var p=e.center||e.centre;if(a&&null!=p){var f=i.getCenterPan(p.eles,e.zoom);null!=f&&(e.pan=f)}if(a&&null!=e.fit){var g=e.fit,v=i.getFitViewport(g.eles||g.boundingBox,g.padding);null!=v&&(e.pan=v.pan,e.zoom=v.zoom)}if(a&&b(e.zoom)){var y=i.getZoomedViewport(e.zoom);null!=y?(y.zoomed&&(e.zoom=y.zoom),y.panned&&(e.pan=y.pan)):e.zoom=null}return new yr(r[0],e)}},animate:function(){return function(e,t){var n=void 0!==this.length?this:[this];if(!(this._private.cy||this).styleEnabled())return this;t&&(e=L({},e,t));for(var r=0;r<n.length;r++){var i=n[r],a=i.animated()&&(void 0===e.queue||e.queue);i.animation(e,a?{queue:!0}:void 0).play()}return this}},stop:function(){return function(e,t){var n=void 0!==this.length?this:[this],r=this._private.cy||this;if(!r.styleEnabled())return this;for(var i=0;i<n.length;i++){for(var a=n[i]._private,o=a.animation.current,s=0;s<o.length;s++){var l=o[s]._private;t&&(l.duration=0)}e&&(a.animation.queue=[]),t||(a.animation.current=[])}return r.notify("draw"),this}}},xr=Array.isArray,wr=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Er=/^\w*$/;var kr=function(e,t){if(xr(e))return!1;var n=typeof e;return!("number"!=n&&"symbol"!=n&&"boolean"!=n&&null!=e&&!le(e))||(Er.test(e)||!wr.test(e)||null!=t&&e in Object(t))};var Cr,Sr=function(e){if(!j(e))return!1;var t=oe(e);return"[object Function]"==t||"[object GeneratorFunction]"==t||"[object AsyncFunction]"==t||"[object Proxy]"==t},Pr=W["__core-js_shared__"],Dr=(Cr=/[^.]+$/.exec(Pr&&Pr.keys&&Pr.keys.IE_PROTO||""))?"Symbol(src)_1."+Cr:"";var Tr=function(e){return!!Dr&&Dr in e},_r=Function.prototype.toString;var Mr=function(e){if(null!=e){try{return _r.call(e)}catch(e){}try{return e+""}catch(e){}}return""},Br=/^\[object .+?Constructor\]$/,Nr=Function.prototype,zr=Object.prototype,Ir=Nr.toString,Ar=zr.hasOwnProperty,Lr=RegExp("^"+Ir.call(Ar).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");var Or=function(e){return!(!j(e)||Tr(e))&&(Sr(e)?Lr:Br).test(Mr(e))};var Rr=function(e,t){return null==e?void 0:e[t]};var Vr=function(e,t){var n=Rr(e,t);return Or(n)?n:void 0},Fr=Vr(Object,"create");var jr=function(){this.__data__=Fr?Fr(null):{},this.size=0};var qr=function(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t},Yr=Object.prototype.hasOwnProperty;var Xr=function(e){var t=this.__data__;if(Fr){var n=t[e];return"__lodash_hash_undefined__"===n?void 0:n}return Yr.call(t,e)?t[e]:void 0},Wr=Object.prototype.hasOwnProperty;var Hr=function(e){var t=this.__data__;return Fr?void 0!==t[e]:Wr.call(t,e)};var Kr=function(e,t){var n=this.__data__;return this.size+=this.has(e)?0:1,n[e]=Fr&&void 0===t?"__lodash_hash_undefined__":t,this};function Gr(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}Gr.prototype.clear=jr,Gr.prototype.delete=qr,Gr.prototype.get=Xr,Gr.prototype.has=Hr,Gr.prototype.set=Kr;var Ur=Gr;var Zr=function(){this.__data__=[],this.size=0};var $r=function(e,t){return e===t||e!=e&&t!=t};var Qr=function(e,t){for(var n=e.length;n--;)if($r(e[n][0],t))return n;return-1},Jr=Array.prototype.splice;var ei=function(e){var t=this.__data__,n=Qr(t,e);return!(n<0)&&(n==t.length-1?t.pop():Jr.call(t,n,1),--this.size,!0)};var ti=function(e){var t=this.__data__,n=Qr(t,e);return n<0?void 0:t[n][1]};var ni=function(e){return Qr(this.__data__,e)>-1};var ri=function(e,t){var n=this.__data__,r=Qr(n,e);return r<0?(++this.size,n.push([e,t])):n[r][1]=t,this};function ii(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}ii.prototype.clear=Zr,ii.prototype.delete=ei,ii.prototype.get=ti,ii.prototype.has=ni,ii.prototype.set=ri;var ai=ii,oi=Vr(W,"Map");var si=function(){this.size=0,this.__data__={hash:new Ur,map:new(oi||ai),string:new Ur}};var li=function(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e};var ui=function(e,t){var n=e.__data__;return li(t)?n["string"==typeof t?"string":"hash"]:n.map};var ci=function(e){var t=ui(this,e).delete(e);return this.size-=t?1:0,t};var di=function(e){return ui(this,e).get(e)};var hi=function(e){return ui(this,e).has(e)};var pi=function(e,t){var n=ui(this,e),r=n.size;return n.set(e,t),this.size+=n.size==r?0:1,this};function fi(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}fi.prototype.clear=si,fi.prototype.delete=ci,fi.prototype.get=di,fi.prototype.has=hi,fi.prototype.set=pi;var gi=fi;function vi(e,t){if("function"!=typeof e||null!=t&&"function"!=typeof t)throw new TypeError("Expected a function");var n=function(){var r=arguments,i=t?t.apply(this,r):r[0],a=n.cache;if(a.has(i))return a.get(i);var o=e.apply(this,r);return n.cache=a.set(i,o)||a,o};return n.cache=new(vi.Cache||gi),n}vi.Cache=gi;var yi=vi;var mi=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,bi=/\\(\\)?/g,xi=function(e){var t=yi(e,(function(e){return 500===n.size&&n.clear(),e})),n=t.cache;return t}((function(e){var t=[];return 46===e.charCodeAt(0)&&t.push(""),e.replace(mi,(function(e,n,r,i){t.push(r?i.replace(bi,"$1"):n||e)})),t}));var wi=function(e,t){for(var n=-1,r=null==e?0:e.length,i=Array(r);++n<r;)i[n]=t(e[n],n,e);return i},Ei=$?$.prototype:void 0,ki=Ei?Ei.toString:void 0;var Ci=function e(t){if("string"==typeof t)return t;if(xr(t))return wi(t,e)+"";if(le(t))return ki?ki.call(t):"";var n=t+"";return"0"==n&&1/t==-1/0?"-0":n};var Si=function(e){return null==e?"":Ci(e)};var Pi=function(e,t){return xr(e)?e:kr(e,t)?[e]:xi(Si(e))};var Di=function(e){if("string"==typeof e||le(e))return e;var t=e+"";return"0"==t&&1/e==-1/0?"-0":t};var Ti=function(e,t){for(var n=0,r=(t=Pi(t,e)).length;null!=e&&n<r;)e=e[Di(t[n++])];return n&&n==r?e:void 0};var _i=function(e,t,n){var r=null==e?void 0:Ti(e,t);return void 0===r?n:r},Mi=function(){try{var e=Vr(Object,"defineProperty");return e({},"",{}),e}catch(e){}}();var Bi=function(e,t,n){"__proto__"==t&&Mi?Mi(e,t,{configurable:!0,enumerable:!0,value:n,writable:!0}):e[t]=n},Ni=Object.prototype.hasOwnProperty;var zi=function(e,t,n){var r=e[t];Ni.call(e,t)&&$r(r,n)&&(void 0!==n||t in e)||Bi(e,t,n)},Ii=/^(?:0|[1-9]\d*)$/;var Ai=function(e,t){var n=typeof e;return!!(t=null==t?9007199254740991:t)&&("number"==n||"symbol"!=n&&Ii.test(e))&&e>-1&&e%1==0&&e<t};var Li=function(e,t,n,r){if(!j(e))return e;for(var i=-1,a=(t=Pi(t,e)).length,o=a-1,s=e;null!=s&&++i<a;){var l=Di(t[i]),u=n;if("__proto__"===l||"constructor"===l||"prototype"===l)return e;if(i!=o){var c=s[l];void 0===(u=r?r(c,l,s):void 0)&&(u=j(c)?c:Ai(t[i+1])?[]:{})}zi(s,l,u),s=s[l]}return e};var Oi=function(e,t,n){return null==e?e:Li(e,t,n)};var Ri=function(e,t){var n=-1,r=e.length;for(t||(t=Array(r));++n<r;)t[n]=e[n];return t};var Vi=function(e){return xr(e)?wi(e,Di):le(e)?[e]:Ri(xi(Si(e)))},Fi={};[br,{data:function(e){return e=L({},{field:"data",bindingEvent:"data",allowBinding:!1,allowSetting:!1,allowGetting:!1,settingEvent:"data",settingTriggersEvent:!1,triggerFnName:"trigger",immutableKeys:{},updateStyle:!1,beforeGet:function(e){},beforeSet:function(e,t){},onSet:function(e){},canSet:function(e){return!0}},e),function(t,n){var r=e,a=void 0!==this.length,o=a?this:[this],s=a?this[0]:this;if(v(t)){var l,u=-1!==t.indexOf(".")&&Vi(t);if(r.allowGetting&&void 0===n)return s&&(r.beforeGet(s),l=u&&void 0===s._private[r.field][t]?_i(s._private[r.field],u):s._private[r.field][t]),l;if(r.allowSetting&&void 0!==n&&!r.immutableKeys[t]){var c=i({},t,n);r.beforeSet(this,c);for(var d=0,h=o.length;d<h;d++){var p=o[d];r.canSet(p)&&(u&&void 0===s._private[r.field][t]?Oi(p._private[r.field],u,n):p._private[r.field][t]=n)}r.updateStyle&&this.updateStyle(),r.onSet(this),r.settingTriggersEvent&&this[r.triggerFnName](r.settingEvent)}}else if(r.allowSetting&&b(t)){var f,g,m=t,x=Object.keys(m);r.beforeSet(this,m);for(var w=0;w<x.length;w++){if(g=m[f=x[w]],!r.immutableKeys[f])for(var E=0;E<o.length;E++){var k=o[E];r.canSet(k)&&(k._private[r.field][f]=g)}}r.updateStyle&&this.updateStyle(),r.onSet(this),r.settingTriggersEvent&&this[r.triggerFnName](r.settingEvent)}else if(r.allowBinding&&y(t)){var C=t;this.on(r.bindingEvent,C)}else if(r.allowGetting&&void 0===t){var S;return s&&(r.beforeGet(s),S=s._private[r.field]),S}return this}},removeData:function(e){return e=L({},{field:"data",event:"data",triggerFnName:"trigger",triggerEvent:!1,immutableKeys:{}},e),function(t){var n=e,r=void 0!==this.length?this:[this];if(v(t)){for(var i=t.split(/\s+/),a=i.length,o=0;o<a;o++){var s=i[o];if(!D(s))if(!n.immutableKeys[s])for(var l=0,u=r.length;l<u;l++)r[l]._private[n.field][s]=void 0}n.triggerEvent&&this[n.triggerFnName](n.event)}else if(void 0===t){for(var c=0,d=r.length;c<d;c++)for(var h=r[c]._private[n.field],p=Object.keys(h),f=0;f<p.length;f++){var g=p[f];!n.immutableKeys[g]&&(h[g]=void 0)}n.triggerEvent&&this[n.triggerFnName](n.event)}return this}}},{eventAliasesOn:function(e){var t=e;t.addListener=t.listen=t.bind=t.on,t.unlisten=t.unbind=t.off=t.removeListener,t.trigger=t.emit,t.pon=t.promiseOn=function(e,t){var n=this,r=Array.prototype.slice.call(arguments,0);return new vr((function(e,t){var i=r.concat([function(t){n.off.apply(n,a),e(t)}]),a=i.concat([]);n.on.apply(n,i)}))}}}].forEach((function(e){L(Fi,e)}));var ji={animate:Fi.animate(),animation:Fi.animation(),animated:Fi.animated(),clearQueue:Fi.clearQueue(),delay:Fi.delay(),delayAnimation:Fi.delayAnimation(),stop:Fi.stop()},qi={classes:function(e){if(void 0===e){var t=[];return this[0]._private.classes.forEach((function(e){return t.push(e)})),t}m(e)||(e=(e||"").match(/\S+/g)||[]);for(var n=[],r=new Je(e),i=0;i<this.length;i++){for(var a=this[i],o=a._private,s=o.classes,l=!1,u=0;u<e.length;u++){var c=e[u];if(!s.has(c)){l=!0;break}}l||(l=s.size!==e.length),l&&(o.classes=r,n.push(a))}return n.length>0&&this.spawn(n).updateStyle().emit("class"),this},addClass:function(e){return this.toggleClass(e,!0)},hasClass:function(e){var t=this[0];return null!=t&&t._private.classes.has(e)},toggleClass:function(e,t){m(e)||(e=e.match(/\S+/g)||[]);for(var n=void 0===t,r=[],i=0,a=this.length;i<a;i++)for(var o=this[i],s=o._private.classes,l=!1,u=0;u<e.length;u++){var c=e[u],d=s.has(c),h=!1;t||n&&!d?(s.add(c),h=!0):(!t||n&&d)&&(s.delete(c),h=!0),!l&&h&&(r.push(o),l=!0)}return r.length>0&&this.spawn(r).updateStyle().emit("class"),this},removeClass:function(e){return this.toggleClass(e,!1)},flashClass:function(e,t){var n=this;if(null==t)t=250;else if(0===t)return n;return n.addClass(e),setTimeout((function(){n.removeClass(e)}),t),n}};qi.className=qi.classNames=qi.classes;var Yi={metaChar:"[\\!\\\"\\#\\$\\%\\&\\'\\(\\)\\*\\+\\,\\.\\/\\:\\;\\<\\=\\>\\?\\@\\[\\]\\^\\`\\{\\|\\}\\~]",comparatorOp:"=|\\!=|>|>=|<|<=|\\$=|\\^=|\\*=",boolOp:"\\?|\\!|\\^",string:"\"(?:\\\\\"|[^\"])*\"|'(?:\\\\'|[^'])*'",number:I,meta:"degree|indegree|outdegree",separator:"\\s*,\\s*",descendant:"\\s+",child:"\\s+>\\s+",subject:"\\$",group:"node|edge|\\*",directedEdge:"\\s+->\\s+",undirectedEdge:"\\s+<->\\s+"};Yi.variable="(?:[\\w-.]|(?:\\\\"+Yi.metaChar+"))+",Yi.className="(?:[\\w-]|(?:\\\\"+Yi.metaChar+"))+",Yi.value=Yi.string+"|"+Yi.number,Yi.id=Yi.variable,function(){var e,t,n;for(e=Yi.comparatorOp.split("|"),n=0;n<e.length;n++)t=e[n],Yi.comparatorOp+="|@"+t;for(e=Yi.comparatorOp.split("|"),n=0;n<e.length;n++)(t=e[n]).indexOf("!")>=0||"="!==t&&(Yi.comparatorOp+="|\\!"+t)}();var Xi=0,Wi=1,Hi=2,Ki=3,Gi=4,Ui=5,Zi=6,$i=7,Qi=8,Ji=9,ea=10,ta=11,na=12,ra=13,ia=14,aa=15,oa=16,sa=17,la=18,ua=19,ca=20,da=[{selector:":selected",matches:function(e){return e.selected()}},{selector:":unselected",matches:function(e){return!e.selected()}},{selector:":selectable",matches:function(e){return e.selectable()}},{selector:":unselectable",matches:function(e){return!e.selectable()}},{selector:":locked",matches:function(e){return e.locked()}},{selector:":unlocked",matches:function(e){return!e.locked()}},{selector:":visible",matches:function(e){return e.visible()}},{selector:":hidden",matches:function(e){return!e.visible()}},{selector:":transparent",matches:function(e){return e.transparent()}},{selector:":grabbed",matches:function(e){return e.grabbed()}},{selector:":free",matches:function(e){return!e.grabbed()}},{selector:":removed",matches:function(e){return e.removed()}},{selector:":inside",matches:function(e){return!e.removed()}},{selector:":grabbable",matches:function(e){return e.grabbable()}},{selector:":ungrabbable",matches:function(e){return!e.grabbable()}},{selector:":animated",matches:function(e){return e.animated()}},{selector:":unanimated",matches:function(e){return!e.animated()}},{selector:":parent",matches:function(e){return e.isParent()}},{selector:":childless",matches:function(e){return e.isChildless()}},{selector:":child",matches:function(e){return e.isChild()}},{selector:":orphan",matches:function(e){return e.isOrphan()}},{selector:":nonorphan",matches:function(e){return e.isChild()}},{selector:":compound",matches:function(e){return e.isNode()?e.isParent():e.source().isParent()||e.target().isParent()}},{selector:":loop",matches:function(e){return e.isLoop()}},{selector:":simple",matches:function(e){return e.isSimple()}},{selector:":active",matches:function(e){return e.active()}},{selector:":inactive",matches:function(e){return!e.active()}},{selector:":backgrounding",matches:function(e){return e.backgrounding()}},{selector:":nonbackgrounding",matches:function(e){return!e.backgrounding()}}].sort((function(e,t){return function(e,t){return-1*A(e,t)}(e.selector,t.selector)})),ha=function(){for(var e,t={},n=0;n<da.length;n++)t[(e=da[n]).selector]=e.matches;return t}(),pa="("+da.map((function(e){return e.selector})).join("|")+")",fa=function(e){return e.replace(new RegExp("\\\\("+Yi.metaChar+")","g"),(function(e,t){return t}))},ga=function(e,t,n){e[e.length-1]=n},va=[{name:"group",query:!0,regex:"("+Yi.group+")",populate:function(e,t,n){var r=a(n,1)[0];t.checks.push({type:Xi,value:"*"===r?r:r+"s"})}},{name:"state",query:!0,regex:pa,populate:function(e,t,n){var r=a(n,1)[0];t.checks.push({type:$i,value:r})}},{name:"id",query:!0,regex:"\\#("+Yi.id+")",populate:function(e,t,n){var r=a(n,1)[0];t.checks.push({type:Qi,value:fa(r)})}},{name:"className",query:!0,regex:"\\.("+Yi.className+")",populate:function(e,t,n){var r=a(n,1)[0];t.checks.push({type:Ji,value:fa(r)})}},{name:"dataExists",query:!0,regex:"\\[\\s*("+Yi.variable+")\\s*\\]",populate:function(e,t,n){var r=a(n,1)[0];t.checks.push({type:Gi,field:fa(r)})}},{name:"dataCompare",query:!0,regex:"\\[\\s*("+Yi.variable+")\\s*("+Yi.comparatorOp+")\\s*("+Yi.value+")\\s*\\]",populate:function(e,t,n){var r=a(n,3),i=r[0],o=r[1],s=r[2];s=null!=new RegExp("^"+Yi.string+"$").exec(s)?s.substring(1,s.length-1):parseFloat(s),t.checks.push({type:Ki,field:fa(i),operator:o,value:s})}},{name:"dataBool",query:!0,regex:"\\[\\s*("+Yi.boolOp+")\\s*("+Yi.variable+")\\s*\\]",populate:function(e,t,n){var r=a(n,2),i=r[0],o=r[1];t.checks.push({type:Ui,field:fa(o),operator:i})}},{name:"metaCompare",query:!0,regex:"\\[\\[\\s*("+Yi.meta+")\\s*("+Yi.comparatorOp+")\\s*("+Yi.number+")\\s*\\]\\]",populate:function(e,t,n){var r=a(n,3),i=r[0],o=r[1],s=r[2];t.checks.push({type:Zi,field:fa(i),operator:o,value:parseFloat(s)})}},{name:"nextQuery",separator:!0,regex:Yi.separator,populate:function(e,t){var n=e.currentSubject,r=e.edgeCount,i=e.compoundCount,a=e[e.length-1];return null!=n&&(a.subject=n,e.currentSubject=null),a.edgeCount=r,a.compoundCount=i,e.edgeCount=0,e.compoundCount=0,e[e.length++]={checks:[]}}},{name:"directedEdge",separator:!0,regex:Yi.directedEdge,populate:function(e,t){if(null==e.currentSubject){var n={checks:[]},r=t,i={checks:[]};return n.checks.push({type:ta,source:r,target:i}),ga(e,0,n),e.edgeCount++,i}var a={checks:[]},o=t,s={checks:[]};return a.checks.push({type:na,source:o,target:s}),ga(e,0,a),e.edgeCount++,s}},{name:"undirectedEdge",separator:!0,regex:Yi.undirectedEdge,populate:function(e,t){if(null==e.currentSubject){var n={checks:[]},r=t,i={checks:[]};return n.checks.push({type:ea,nodes:[r,i]}),ga(e,0,n),e.edgeCount++,i}var a={checks:[]},o=t,s={checks:[]};return a.checks.push({type:ia,node:o,neighbor:s}),ga(e,0,a),s}},{name:"child",separator:!0,regex:Yi.child,populate:function(e,t){if(null==e.currentSubject){var n={checks:[]},r={checks:[]},i=e[e.length-1];return n.checks.push({type:aa,parent:i,child:r}),ga(e,0,n),e.compoundCount++,r}if(e.currentSubject===t){var a={checks:[]},o=e[e.length-1],s={checks:[]},l={checks:[]},u={checks:[]},c={checks:[]};return a.checks.push({type:ua,left:o,right:s,subject:l}),l.checks=t.checks,t.checks=[{type:ca}],c.checks.push({type:ca}),s.checks.push({type:sa,parent:c,child:u}),ga(e,0,a),e.currentSubject=l,e.compoundCount++,u}var d={checks:[]},h={checks:[]},p=[{type:sa,parent:d,child:h}];return d.checks=t.checks,t.checks=p,e.compoundCount++,h}},{name:"descendant",separator:!0,regex:Yi.descendant,populate:function(e,t){if(null==e.currentSubject){var n={checks:[]},r={checks:[]},i=e[e.length-1];return n.checks.push({type:oa,ancestor:i,descendant:r}),ga(e,0,n),e.compoundCount++,r}if(e.currentSubject===t){var a={checks:[]},o=e[e.length-1],s={checks:[]},l={checks:[]},u={checks:[]},c={checks:[]};return a.checks.push({type:ua,left:o,right:s,subject:l}),l.checks=t.checks,t.checks=[{type:ca}],c.checks.push({type:ca}),s.checks.push({type:la,ancestor:c,descendant:u}),ga(e,0,a),e.currentSubject=l,e.compoundCount++,u}var d={checks:[]},h={checks:[]},p=[{type:la,ancestor:d,descendant:h}];return d.checks=t.checks,t.checks=p,e.compoundCount++,h}},{name:"subject",modifier:!0,regex:Yi.subject,populate:function(e,t){if(null!=e.currentSubject&&e.currentSubject!==t)return je("Redefinition of subject in selector `"+e.toString()+"`"),!1;e.currentSubject=t;var n=e[e.length-1].checks[0],r=null==n?null:n.type;r===ta?n.type=ra:r===ea&&(n.type=ia,n.node=n.nodes[1],n.neighbor=n.nodes[0],n.nodes=null)}}];va.forEach((function(e){return e.regexObj=new RegExp("^"+e.regex)}));var ya=function(e){for(var t,n,r,i=0;i<va.length;i++){var a=va[i],o=a.name,s=e.match(a.regexObj);if(null!=s){n=s,t=a,r=o;var l=s[0];e=e.substring(l.length);break}}return{expr:t,match:n,name:r,remaining:e}},ma={parse:function(e){var t=this.inputText=e,n=this[0]={checks:[]};for(this.length=1,t=function(e){var t=e.match(/^\s+/);if(t){var n=t[0];e=e.substring(n.length)}return e}(t);;){var r=ya(t);if(null==r.expr)return je("The selector `"+e+"`is invalid"),!1;var i=r.match.slice(1),a=r.expr.populate(this,n,i);if(!1===a)return!1;if(null!=a&&(n=a),(t=r.remaining).match(/^\s*$/))break}var o=this[this.length-1];null!=this.currentSubject&&(o.subject=this.currentSubject),o.edgeCount=this.edgeCount,o.compoundCount=this.compoundCount;for(var s=0;s<this.length;s++){var l=this[s];if(l.compoundCount>0&&l.edgeCount>0)return je("The selector `"+e+"` is invalid because it uses both a compound selector and an edge selector"),!1;if(l.edgeCount>1)return je("The selector `"+e+"` is invalid because it uses multiple edge selectors"),!1;1===l.edgeCount&&je("The selector `"+e+"` is deprecated. Edge selectors do not take effect on changes to source and target nodes after an edge is added, for performance reasons. Use a class or data selector on edges instead, updating the class or data of an edge when your app detects a change in source or target nodes.")}return!0},toString:function(){if(null!=this.toStringCache)return this.toStringCache;for(var e=function(e){return null==e?"":e},t=function(t){return v(t)?'"'+t+'"':e(t)},n=function(e){return" "+e+" "},r=function(r,a){var o=r.type,s=r.value;switch(o){case Xi:var l=e(s);return l.substring(0,l.length-1);case Ki:var u=r.field,c=r.operator;return"["+u+n(e(c))+t(s)+"]";case Ui:var d=r.operator,h=r.field;return"["+e(d)+h+"]";case Gi:return"["+r.field+"]";case Zi:var p=r.operator;return"[["+r.field+n(e(p))+t(s)+"]]";case $i:return s;case Qi:return"#"+s;case Ji:return"."+s;case sa:case aa:return i(r.parent,a)+n(">")+i(r.child,a);case la:case oa:return i(r.ancestor,a)+" "+i(r.descendant,a);case ua:var f=i(r.left,a),g=i(r.subject,a),v=i(r.right,a);return f+(f.length>0?" ":"")+g+v;case ca:return""}},i=function(e,t){return e.checks.reduce((function(n,i,a){return n+(t===e&&0===a?"$":"")+r(i,t)}),"")},a="",o=0;o<this.length;o++){var s=this[o];a+=i(s,s.subject),this.length>1&&o<this.length-1&&(a+=", ")}return this.toStringCache=a,a}},ba=function(e,t,n){var r,i,a,o=v(e),s=x(e),l=v(n),u=!1,c=!1,d=!1;switch(t.indexOf("!")>=0&&(t=t.replace("!",""),c=!0),t.indexOf("@")>=0&&(t=t.replace("@",""),u=!0),(o||l||u)&&(i=o||s?""+e:"",a=""+n),u&&(e=i=i.toLowerCase(),n=a=a.toLowerCase()),t){case"*=":r=i.indexOf(a)>=0;break;case"$=":r=i.indexOf(a,i.length-a.length)>=0;break;case"^=":r=0===i.indexOf(a);break;case"=":r=e===n;break;case">":d=!0,r=e>n;break;case">=":d=!0,r=e>=n;break;case"<":d=!0,r=e<n;break;case"<=":d=!0,r=e<=n;break;default:r=!1}return!c||null==e&&d||(r=!r),r},xa=function(e,t){return e.data(t)},wa=[],Ea=function(e,t){return e.checks.every((function(e){return wa[e.type](e,t)}))};wa[Xi]=function(e,t){var n=e.value;return"*"===n||n===t.group()},wa[$i]=function(e,t){return function(e,t){return ha[e](t)}(e.value,t)},wa[Qi]=function(e,t){var n=e.value;return t.id()===n},wa[Ji]=function(e,t){var n=e.value;return t.hasClass(n)},wa[Zi]=function(e,t){var n=e.field,r=e.operator,i=e.value;return ba(function(e,t){return e[t]()}(t,n),r,i)},wa[Ki]=function(e,t){var n=e.field,r=e.operator,i=e.value;return ba(xa(t,n),r,i)},wa[Ui]=function(e,t){var n=e.field,r=e.operator;return function(e,t){switch(t){case"?":return!!e;case"!":return!e;case"^":return void 0===e}}(xa(t,n),r)},wa[Gi]=function(e,t){var n=e.field;return e.operator,void 0!==xa(t,n)},wa[ea]=function(e,t){var n=e.nodes[0],r=e.nodes[1],i=t.source(),a=t.target();return Ea(n,i)&&Ea(r,a)||Ea(r,i)&&Ea(n,a)},wa[ia]=function(e,t){return Ea(e.node,t)&&t.neighborhood().some((function(t){return t.isNode()&&Ea(e.neighbor,t)}))},wa[ta]=function(e,t){return Ea(e.source,t.source())&&Ea(e.target,t.target())},wa[na]=function(e,t){return Ea(e.source,t)&&t.outgoers().some((function(t){return t.isNode()&&Ea(e.target,t)}))},wa[ra]=function(e,t){return Ea(e.target,t)&&t.incomers().some((function(t){return t.isNode()&&Ea(e.source,t)}))},wa[aa]=function(e,t){return Ea(e.child,t)&&Ea(e.parent,t.parent())},wa[sa]=function(e,t){return Ea(e.parent,t)&&t.children().some((function(t){return Ea(e.child,t)}))},wa[oa]=function(e,t){return Ea(e.descendant,t)&&t.ancestors().some((function(t){return Ea(e.ancestor,t)}))},wa[la]=function(e,t){return Ea(e.ancestor,t)&&t.descendants().some((function(t){return Ea(e.descendant,t)}))},wa[ua]=function(e,t){return Ea(e.subject,t)&&Ea(e.left,t)&&Ea(e.right,t)},wa[ca]=function(){return!0},wa[Wi]=function(e,t){return e.value.has(t)},wa[Hi]=function(e,t){return(0,e.value)(t)};var ka=function(e){this.inputText=e,this.currentSubject=null,this.compoundCount=0,this.edgeCount=0,this.length=0,null==e||v(e)&&e.match(/^\s*$/)||(E(e)?this.addQuery({checks:[{type:Wi,value:e.collection()}]}):y(e)?this.addQuery({checks:[{type:Hi,value:e}]}):v(e)?this.parse(e)||(this.invalid=!0):Ve("A selector must be created from a string; found "))},Ca=ka.prototype;[ma,{matches:function(e){for(var t=0;t<this.length;t++){var n=this[t];if(Ea(n,e))return!0}return!1},filter:function(e){var t=this;if(1===t.length&&1===t[0].checks.length&&t[0].checks[0].type===Qi)return e.getElementById(t[0].checks[0].value).collection();var n=function(e){for(var n=0;n<t.length;n++){var r=t[n];if(Ea(r,e))return!0}return!1};return null==t.text()&&(n=function(){return!0}),e.filter(n)}}].forEach((function(e){return L(Ca,e)})),Ca.text=function(){return this.inputText},Ca.size=function(){return this.length},Ca.eq=function(e){return this[e]},Ca.sameText=function(e){return!this.invalid&&!e.invalid&&this.text()===e.text()},Ca.addQuery=function(e){this[this.length++]=e},Ca.selector=Ca.toString;var Sa={allAre:function(e){var t=new ka(e);return this.every((function(e){return t.matches(e)}))},is:function(e){var t=new ka(e);return this.some((function(e){return t.matches(e)}))},some:function(e,t){for(var n=0;n<this.length;n++){if(t?e.apply(t,[this[n],n,this]):e(this[n],n,this))return!0}return!1},every:function(e,t){for(var n=0;n<this.length;n++){if(!(t?e.apply(t,[this[n],n,this]):e(this[n],n,this)))return!1}return!0},same:function(e){if(this===e)return!0;e=this.cy().collection(e);var t=this.length;return t===e.length&&(1===t?this[0]===e[0]:this.every((function(t){return e.hasElementWithId(t.id())})))},anySame:function(e){return e=this.cy().collection(e),this.some((function(t){return e.hasElementWithId(t.id())}))},allAreNeighbors:function(e){e=this.cy().collection(e);var t=this.neighborhood();return e.every((function(e){return t.hasElementWithId(e.id())}))},contains:function(e){e=this.cy().collection(e);var t=this;return e.every((function(e){return t.hasElementWithId(e.id())}))}};Sa.allAreNeighbours=Sa.allAreNeighbors,Sa.has=Sa.contains,Sa.equal=Sa.equals=Sa.same;var Pa,Da,Ta=function(e,t){return function(n,r,i,a){var o,s=n;if(null==s?o="":E(s)&&1===s.length&&(o=s.id()),1===this.length&&o){var l=this[0]._private,u=l.traversalCache=l.traversalCache||{},c=u[t]=u[t]||[],d=Te(o),h=c[d];return h||(c[d]=e.call(this,n,r,i,a))}return e.call(this,n,r,i,a)}},_a={parent:function(e){var t=[];if(1===this.length){var n=this[0]._private.parent;if(n)return n}for(var r=0;r<this.length;r++){var i=this[r]._private.parent;i&&t.push(i)}return this.spawn(t,!0).filter(e)},parents:function(e){for(var t=[],n=this.parent();n.nonempty();){for(var r=0;r<n.length;r++){var i=n[r];t.push(i)}n=n.parent()}return this.spawn(t,!0).filter(e)},commonAncestors:function(e){for(var t,n=0;n<this.length;n++){var r=this[n].parents();t=(t=t||r).intersect(r)}return t.filter(e)},orphans:function(e){return this.stdFilter((function(e){return e.isOrphan()})).filter(e)},nonorphans:function(e){return this.stdFilter((function(e){return e.isChild()})).filter(e)},children:Ta((function(e){for(var t=[],n=0;n<this.length;n++)for(var r=this[n]._private.children,i=0;i<r.length;i++)t.push(r[i]);return this.spawn(t,!0).filter(e)}),"children"),siblings:function(e){return this.parent().children().not(this).filter(e)},isParent:function(){var e=this[0];if(e)return e.isNode()&&0!==e._private.children.length},isChildless:function(){var e=this[0];if(e)return e.isNode()&&0===e._private.children.length},isChild:function(){var e=this[0];if(e)return e.isNode()&&null!=e._private.parent},isOrphan:function(){var e=this[0];if(e)return e.isNode()&&null==e._private.parent},descendants:function(e){var t=[];return function e(n){for(var r=0;r<n.length;r++){var i=n[r];t.push(i),i.children().nonempty()&&e(i.children())}}(this.children()),this.spawn(t,!0).filter(e)}};function Ma(e,t,n,r){for(var i=[],a=new Je,o=e.cy().hasCompoundNodes(),s=0;s<e.length;s++){var l=e[s];n?i.push(l):o&&r(i,a,l)}for(;i.length>0;){var u=i.shift();t(u),a.add(u.id()),o&&r(i,a,u)}return e}function Ba(e,t,n){if(n.isParent())for(var r=n._private.children,i=0;i<r.length;i++){var a=r[i];t.has(a.id())||e.push(a)}}function Na(e,t,n){if(n.isChild()){var r=n._private.parent;t.has(r.id())||e.push(r)}}function za(e,t,n){Na(e,t,n),Ba(e,t,n)}_a.forEachDown=function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return Ma(this,e,t,Ba)},_a.forEachUp=function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return Ma(this,e,t,Na)},_a.forEachUpAndDown=function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return Ma(this,e,t,za)},_a.ancestors=_a.parents,(Pa=Da={data:Fi.data({field:"data",bindingEvent:"data",allowBinding:!0,allowSetting:!0,settingEvent:"data",settingTriggersEvent:!0,triggerFnName:"trigger",allowGetting:!0,immutableKeys:{id:!0,source:!0,target:!0,parent:!0},updateStyle:!0}),removeData:Fi.removeData({field:"data",event:"data",triggerFnName:"trigger",triggerEvent:!0,immutableKeys:{id:!0,source:!0,target:!0,parent:!0},updateStyle:!0}),scratch:Fi.data({field:"scratch",bindingEvent:"scratch",allowBinding:!0,allowSetting:!0,settingEvent:"scratch",settingTriggersEvent:!0,triggerFnName:"trigger",allowGetting:!0,updateStyle:!0}),removeScratch:Fi.removeData({field:"scratch",event:"scratch",triggerFnName:"trigger",triggerEvent:!0,updateStyle:!0}),rscratch:Fi.data({field:"rscratch",allowBinding:!1,allowSetting:!0,settingTriggersEvent:!1,allowGetting:!0}),removeRscratch:Fi.removeData({field:"rscratch",triggerEvent:!1}),id:function(){var e=this[0];if(e)return e._private.data.id}}).attr=Pa.data,Pa.removeAttr=Pa.removeData;var Ia,Aa,La=Da,Oa={};function Ra(e){return function(t){if(void 0===t&&(t=!0),0!==this.length&&this.isNode()&&!this.removed()){for(var n=0,r=this[0],i=r._private.edges,a=0;a<i.length;a++){var o=i[a];!t&&o.isLoop()||(n+=e(r,o))}return n}}}function Va(e,t){return function(n){for(var r,i=this.nodes(),a=0;a<i.length;a++){var o=i[a][e](n);void 0===o||void 0!==r&&!t(o,r)||(r=o)}return r}}L(Oa,{degree:Ra((function(e,t){return t.source().same(t.target())?2:1})),indegree:Ra((function(e,t){return t.target().same(e)?1:0})),outdegree:Ra((function(e,t){return t.source().same(e)?1:0}))}),L(Oa,{minDegree:Va("degree",(function(e,t){return e<t})),maxDegree:Va("degree",(function(e,t){return e>t})),minIndegree:Va("indegree",(function(e,t){return e<t})),maxIndegree:Va("indegree",(function(e,t){return e>t})),minOutdegree:Va("outdegree",(function(e,t){return e<t})),maxOutdegree:Va("outdegree",(function(e,t){return e>t}))}),L(Oa,{totalDegree:function(e){for(var t=0,n=this.nodes(),r=0;r<n.length;r++)t+=n[r].degree(e);return t}});var Fa=function(e,t,n){for(var r=0;r<e.length;r++){var i=e[r];if(!i.locked()){var a=i._private.position,o={x:null!=t.x?t.x-a.x:0,y:null!=t.y?t.y-a.y:0};!i.isParent()||0===o.x&&0===o.y||i.children().shift(o,n),i.dirtyBoundingBoxCache()}}},ja={field:"position",bindingEvent:"position",allowBinding:!0,allowSetting:!0,settingEvent:"position",settingTriggersEvent:!0,triggerFnName:"emitAndNotify",allowGetting:!0,validKeys:["x","y"],beforeGet:function(e){e.updateCompoundBounds()},beforeSet:function(e,t){Fa(e,t,!1)},onSet:function(e){e.dirtyCompoundBoundsCache()},canSet:function(e){return!e.locked()}};(Ia=Aa={position:Fi.data(ja),silentPosition:Fi.data(L({},ja,{allowBinding:!1,allowSetting:!0,settingTriggersEvent:!1,allowGetting:!1,beforeSet:function(e,t){Fa(e,t,!0)},onSet:function(e){e.dirtyCompoundBoundsCache()}})),positions:function(e,t){if(b(e))t?this.silentPosition(e):this.position(e);else if(y(e)){var n=e,r=this.cy();r.startBatch();for(var i=0;i<this.length;i++){var a,o=this[i];(a=n(o,i))&&(t?o.silentPosition(a):o.position(a))}r.endBatch()}return this},silentPositions:function(e){return this.positions(e,!0)},shift:function(e,t,n){var r;if(b(e)?(r={x:x(e.x)?e.x:0,y:x(e.y)?e.y:0},n=t):v(e)&&x(t)&&((r={x:0,y:0})[e]=t),null!=r){var i=this.cy();i.startBatch();for(var a=0;a<this.length;a++){var o=this[a];if(!(i.hasCompoundNodes()&&o.isChild()&&o.ancestors().anySame(this))){var s=o.position(),l={x:s.x+r.x,y:s.y+r.y};n?o.silentPosition(l):o.position(l)}}i.endBatch()}return this},silentShift:function(e,t){return b(e)?this.shift(e,!0):v(e)&&x(t)&&this.shift(e,t,!0),this},renderedPosition:function(e,t){var n=this[0],r=this.cy(),i=r.zoom(),a=r.pan(),o=b(e)?e:void 0,s=void 0!==o||void 0!==t&&v(e);if(n&&n.isNode()){if(!s){var l=n.position();return o=yt(l,i,a),void 0===e?o:o[e]}for(var u=0;u<this.length;u++){var c=this[u];void 0!==t?c.position(e,(t-a[e])/i):void 0!==o&&c.position(mt(o,i,a))}}else if(!s)return;return this},relativePosition:function(e,t){var n=this[0],r=this.cy(),i=b(e)?e:void 0,a=void 0!==i||void 0!==t&&v(e),o=r.hasCompoundNodes();if(n&&n.isNode()){if(!a){var s=n.position(),l=o?n.parent():null,u=l&&l.length>0,c=u;u&&(l=l[0]);var d=c?l.position():{x:0,y:0};return i={x:s.x-d.x,y:s.y-d.y},void 0===e?i:i[e]}for(var h=0;h<this.length;h++){var p=this[h],f=o?p.parent():null,g=f&&f.length>0,y=g;g&&(f=f[0]);var m=y?f.position():{x:0,y:0};void 0!==t?p.position(e,t+m[e]):void 0!==i&&p.position({x:i.x+m.x,y:i.y+m.y})}}else if(!a)return;return this}}).modelPosition=Ia.point=Ia.position,Ia.modelPositions=Ia.points=Ia.positions,Ia.renderedPoint=Ia.renderedPosition,Ia.relativePoint=Ia.relativePosition;var qa,Ya,Xa=Aa;qa=Ya={},Ya.renderedBoundingBox=function(e){var t=this.boundingBox(e),n=this.cy(),r=n.zoom(),i=n.pan(),a=t.x1*r+i.x,o=t.x2*r+i.x,s=t.y1*r+i.y,l=t.y2*r+i.y;return{x1:a,x2:o,y1:s,y2:l,w:o-a,h:l-s}},Ya.dirtyCompoundBoundsCache=function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=this.cy();return t.styleEnabled()&&t.hasCompoundNodes()?(this.forEachUp((function(t){if(t.isParent()){var n=t._private;n.compoundBoundsClean=!1,n.bbCache=null,e||t.emitAndNotify("bounds")}})),this):this},Ya.updateCompoundBounds=function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=this.cy();if(!t.styleEnabled()||!t.hasCompoundNodes())return this;if(!e&&t.batching())return this;function n(e){if(e.isParent()){var t=e._private,n=e.children(),r="include"===e.pstyle("compound-sizing-wrt-labels").value,i={width:{val:e.pstyle("min-width").pfValue,left:e.pstyle("min-width-bias-left"),right:e.pstyle("min-width-bias-right")},height:{val:e.pstyle("min-height").pfValue,top:e.pstyle("min-height-bias-top"),bottom:e.pstyle("min-height-bias-bottom")}},a=n.boundingBox({includeLabels:r,includeOverlays:!1,useCache:!1}),o=t.position;0!==a.w&&0!==a.h||((a={w:e.pstyle("width").pfValue,h:e.pstyle("height").pfValue}).x1=o.x-a.w/2,a.x2=o.x+a.w/2,a.y1=o.y-a.h/2,a.y2=o.y+a.h/2);var s=i.width.left.value;"px"===i.width.left.units&&i.width.val>0&&(s=100*s/i.width.val);var l=i.width.right.value;"px"===i.width.right.units&&i.width.val>0&&(l=100*l/i.width.val);var u=i.height.top.value;"px"===i.height.top.units&&i.height.val>0&&(u=100*u/i.height.val);var c=i.height.bottom.value;"px"===i.height.bottom.units&&i.height.val>0&&(c=100*c/i.height.val);var d=y(i.width.val-a.w,s,l),h=d.biasDiff,p=d.biasComplementDiff,f=y(i.height.val-a.h,u,c),g=f.biasDiff,v=f.biasComplementDiff;t.autoPadding=function(e,t,n,r){if("%"!==n.units)return"px"===n.units?n.pfValue:0;switch(r){case"width":return e>0?n.pfValue*e:0;case"height":return t>0?n.pfValue*t:0;case"average":return e>0&&t>0?n.pfValue*(e+t)/2:0;case"min":return e>0&&t>0?e>t?n.pfValue*t:n.pfValue*e:0;case"max":return e>0&&t>0?e>t?n.pfValue*e:n.pfValue*t:0;default:return 0}}(a.w,a.h,e.pstyle("padding"),e.pstyle("padding-relative-to").value),t.autoWidth=Math.max(a.w,i.width.val),o.x=(-h+a.x1+a.x2+p)/2,t.autoHeight=Math.max(a.h,i.height.val),o.y=(-g+a.y1+a.y2+v)/2}function y(e,t,n){var r=0,i=0,a=t+n;return e>0&&a>0&&(r=t/a*e,i=n/a*e),{biasDiff:r,biasComplementDiff:i}}}for(var r=0;r<this.length;r++){var i=this[r],a=i._private;a.compoundBoundsClean&&!e||(n(i),t.batching()||(a.compoundBoundsClean=!0))}return this};var Wa=function(e){return e===1/0||e===-1/0?0:e},Ha=function(e,t,n,r,i){r-t!=0&&i-n!=0&&null!=t&&null!=n&&null!=r&&null!=i&&(e.x1=t<e.x1?t:e.x1,e.x2=r>e.x2?r:e.x2,e.y1=n<e.y1?n:e.y1,e.y2=i>e.y2?i:e.y2,e.w=e.x2-e.x1,e.h=e.y2-e.y1)},Ka=function(e,t){return null==t?e:Ha(e,t.x1,t.y1,t.x2,t.y2)},Ga=function(e,t,n){return Ue(e,t,n)},Ua=function(e,t,n){if(!t.cy().headless()){var r,i,a=t._private,o=a.rstyle,s=o.arrowWidth/2;if("none"!==t.pstyle(n+"-arrow-shape").value){"source"===n?(r=o.srcX,i=o.srcY):"target"===n?(r=o.tgtX,i=o.tgtY):(r=o.midX,i=o.midY);var l=a.arrowBounds=a.arrowBounds||{},u=l[n]=l[n]||{};u.x1=r-s,u.y1=i-s,u.x2=r+s,u.y2=i+s,u.w=u.x2-u.x1,u.h=u.y2-u.y1,Nt(u,1),Ha(e,u.x1,u.y1,u.x2,u.y2)}}},Za=function(e,t,n){if(!t.cy().headless()){var r;r=n?n+"-":"";var i=t._private,a=i.rstyle;if(t.pstyle(r+"label").strValue){var o,s,l,u,c=t.pstyle("text-halign"),d=t.pstyle("text-valign"),h=Ga(a,"labelWidth",n),p=Ga(a,"labelHeight",n),f=Ga(a,"labelX",n),g=Ga(a,"labelY",n),v=t.pstyle(r+"text-margin-x").pfValue,y=t.pstyle(r+"text-margin-y").pfValue,m=t.isEdge(),b=t.pstyle(r+"text-rotation"),x=t.pstyle("text-outline-width").pfValue,w=t.pstyle("text-border-width").pfValue/2,E=t.pstyle("text-background-padding").pfValue,k=p,C=h,S=C/2,P=k/2;if(m)o=f-S,s=f+S,l=g-P,u=g+P;else{switch(c.value){case"left":o=f-C,s=f;break;case"center":o=f-S,s=f+S;break;case"right":o=f,s=f+C}switch(d.value){case"top":l=g-k,u=g;break;case"center":l=g-P,u=g+P;break;case"bottom":l=g,u=g+k}}o+=v-Math.max(x,w)-E-2,s+=v+Math.max(x,w)+E+2,l+=y-Math.max(x,w)-E-2,u+=y+Math.max(x,w)+E+2;var D=n||"main",T=i.labelBounds,_=T[D]=T[D]||{};_.x1=o,_.y1=l,_.x2=s,_.y2=u,_.w=s-o,_.h=u-l;var M=m&&"autorotate"===b.strValue,B=null!=b.pfValue&&0!==b.pfValue;if(M||B){var N=M?Ga(i.rstyle,"labelAngle",n):b.pfValue,z=Math.cos(N),I=Math.sin(N),A=(o+s)/2,L=(l+u)/2;if(!m){switch(c.value){case"left":A=s;break;case"right":A=o}switch(d.value){case"top":L=u;break;case"bottom":L=l}}var O=function(e,t){return{x:(e-=A)*z-(t-=L)*I+A,y:e*I+t*z+L}},R=O(o,l),V=O(o,u),F=O(s,l),j=O(s,u);o=Math.min(R.x,V.x,F.x,j.x),s=Math.max(R.x,V.x,F.x,j.x),l=Math.min(R.y,V.y,F.y,j.y),u=Math.max(R.y,V.y,F.y,j.y)}var q=D+"Rot",Y=T[q]=T[q]||{};Y.x1=o,Y.y1=l,Y.x2=s,Y.y2=u,Y.w=s-o,Y.h=u-l,Ha(e,o,l,s,u),Ha(i.labelBounds.all,o,l,s,u)}return e}},$a=function(e,t){var n,r,i,a,o,s,l,u=e._private.cy,c=u.styleEnabled(),d=u.headless(),h=_t(),p=e._private,f=e.isNode(),g=e.isEdge(),v=p.rstyle,y=f&&c?e.pstyle("bounds-expansion").pfValue:[0],m=function(e){return"none"!==e.pstyle("display").value},b=!c||m(e)&&(!g||m(e.source())&&m(e.target()));if(b){var x=0;c&&t.includeOverlays&&0!==e.pstyle("overlay-opacity").value&&(x=e.pstyle("overlay-padding").value);var w=0;c&&t.includeUnderlays&&0!==e.pstyle("underlay-opacity").value&&(w=e.pstyle("underlay-padding").value);var E=Math.max(x,w),k=0;if(c&&(k=e.pstyle("width").pfValue/2),f&&t.includeNodes){var C=e.position();o=C.x,s=C.y;var S=e.outerWidth()/2,P=e.outerHeight()/2;Ha(h,n=o-S,i=s-P,r=o+S,a=s+P),c&&t.includeOutlines&&function(e,t){if(!t.cy().headless()){var n,r,i,a=t.pstyle("outline-opacity").value,o=t.pstyle("outline-width").value;if(a>0&&o>0){var s=t.pstyle("outline-offset").value,l=t.pstyle("shape").value,u=o+s,c=(e.w+2*u)/e.w,d=(e.h+2*u)/e.h,h=0;["diamond","pentagon","round-triangle"].includes(l)?(c=(e.w+2.4*u)/e.w,h=-u/3.6):["concave-hexagon","rhomboid","right-rhomboid"].includes(l)?c=(e.w+2.4*u)/e.w:"star"===l?(c=(e.w+2.8*u)/e.w,d=(e.h+2.6*u)/e.h,h=-u/3.8):"triangle"===l?(c=(e.w+2.8*u)/e.w,d=(e.h+2.4*u)/e.h,h=-u/1.4):"vee"===l&&(c=(e.w+4.4*u)/e.w,d=(e.h+3.8*u)/e.h,h=.5*-u);var p=e.h*d-e.h,f=e.w*c-e.w;if(zt(e,[Math.ceil(p/2),Math.ceil(f/2)]),0!==h){var g=(r=0,i=h,{x1:(n=e).x1+r,x2:n.x2+r,y1:n.y1+i,y2:n.y2+i,w:n.w,h:n.h});Mt(e,g)}}}}(h,e)}else if(g&&t.includeEdges)if(c&&!d){var D=e.pstyle("curve-style").strValue;if(n=Math.min(v.srcX,v.midX,v.tgtX),r=Math.max(v.srcX,v.midX,v.tgtX),i=Math.min(v.srcY,v.midY,v.tgtY),a=Math.max(v.srcY,v.midY,v.tgtY),Ha(h,n-=k,i-=k,r+=k,a+=k),"haystack"===D){var T=v.haystackPts;if(T&&2===T.length){if(n=T[0].x,i=T[0].y,n>(r=T[1].x)){var _=n;n=r,r=_}if(i>(a=T[1].y)){var M=i;i=a,a=M}Ha(h,n-k,i-k,r+k,a+k)}}else if("bezier"===D||"unbundled-bezier"===D||D.endsWith("segments")||D.endsWith("taxi")){var B;switch(D){case"bezier":case"unbundled-bezier":B=v.bezierPts;break;case"segments":case"taxi":case"round-segments":case"round-taxi":B=v.linePts}if(null!=B)for(var N=0;N<B.length;N++){var z=B[N];n=z.x-k,r=z.x+k,i=z.y-k,a=z.y+k,Ha(h,n,i,r,a)}}}else{var I=e.source().position(),A=e.target().position();if((n=I.x)>(r=A.x)){var L=n;n=r,r=L}if((i=I.y)>(a=A.y)){var O=i;i=a,a=O}Ha(h,n-=k,i-=k,r+=k,a+=k)}if(c&&t.includeEdges&&g&&(Ua(h,e,"mid-source"),Ua(h,e,"mid-target"),Ua(h,e,"source"),Ua(h,e,"target")),c)if("yes"===e.pstyle("ghost").value){var R=e.pstyle("ghost-offset-x").pfValue,V=e.pstyle("ghost-offset-y").pfValue;Ha(h,h.x1+R,h.y1+V,h.x2+R,h.y2+V)}var F=p.bodyBounds=p.bodyBounds||{};It(F,h),zt(F,y),Nt(F,1),c&&(n=h.x1,r=h.x2,i=h.y1,a=h.y2,Ha(h,n-E,i-E,r+E,a+E));var j=p.overlayBounds=p.overlayBounds||{};It(j,h),zt(j,y),Nt(j,1);var q=p.labelBounds=p.labelBounds||{};null!=q.all?((l=q.all).x1=1/0,l.y1=1/0,l.x2=-1/0,l.y2=-1/0,l.w=0,l.h=0):q.all=_t(),c&&t.includeLabels&&(t.includeMainLabels&&Za(h,e,null),g&&(t.includeSourceLabels&&Za(h,e,"source"),t.includeTargetLabels&&Za(h,e,"target")))}return h.x1=Wa(h.x1),h.y1=Wa(h.y1),h.x2=Wa(h.x2),h.y2=Wa(h.y2),h.w=Wa(h.x2-h.x1),h.h=Wa(h.y2-h.y1),h.w>0&&h.h>0&&b&&(zt(h,y),Nt(h,1)),h},Qa=function(e){var t=0,n=function(e){return(e?1:0)<<t++},r=0;return r+=n(e.incudeNodes),r+=n(e.includeEdges),r+=n(e.includeLabels),r+=n(e.includeMainLabels),r+=n(e.includeSourceLabels),r+=n(e.includeTargetLabels),r+=n(e.includeOverlays),r+=n(e.includeOutlines)},Ja=function(e){if(e.isEdge()){var t=e.source().position(),n=e.target().position(),r=function(e){return Math.round(e)};return function(e,t){var n={value:0,done:!1},r=0,i=e.length;return ke({next:function(){return r<i?n.value=e[r++]:n.done=!0,n}},t)}([r(t.x),r(t.y),r(n.x),r(n.y)])}return 0},eo=function(e,t){var n,r=e._private,i=e.isEdge(),a=(null==t?no:Qa(t))===no,o=Ja(e),s=r.bbCachePosKey===o,l=t.useCache&&s,u=function(e){return null==e._private.bbCache||e._private.styleDirty};if(!l||u(e)||i&&u(e.source())||u(e.target())?(s||e.recalculateRenderedStyle(l),n=$a(e,to),r.bbCache=n,r.bbCachePosKey=o):n=r.bbCache,!a){var c=e.isNode();n=_t(),(t.includeNodes&&c||t.includeEdges&&!c)&&(t.includeOverlays?Ka(n,r.overlayBounds):Ka(n,r.bodyBounds)),t.includeLabels&&(t.includeMainLabels&&(!i||t.includeSourceLabels&&t.includeTargetLabels)?Ka(n,r.labelBounds.all):(t.includeMainLabels&&Ka(n,r.labelBounds.mainRot),t.includeSourceLabels&&Ka(n,r.labelBounds.sourceRot),t.includeTargetLabels&&Ka(n,r.labelBounds.targetRot))),n.w=n.x2-n.x1,n.h=n.y2-n.y1}return n},to={includeNodes:!0,includeEdges:!0,includeLabels:!0,includeMainLabels:!0,includeSourceLabels:!0,includeTargetLabels:!0,includeOverlays:!0,includeUnderlays:!0,includeOutlines:!0,useCache:!0},no=Qa(to),ro=He(to);Ya.boundingBox=function(e){var t;if(1!==this.length||null==this[0]._private.bbCache||this[0]._private.styleDirty||void 0!==e&&void 0!==e.useCache&&!0!==e.useCache){t=_t();var n=ro(e=e||to);if(this.cy().styleEnabled())for(var r=0;r<this.length;r++){var i=this[r],a=i._private,o=Ja(i),s=a.bbCachePosKey===o,l=n.useCache&&s&&!a.styleDirty;i.recalculateRenderedStyle(l)}this.updateCompoundBounds(!e.useCache);for(var u=0;u<this.length;u++){var c=this[u];Ka(t,eo(c,n))}}else e=void 0===e?to:ro(e),t=eo(this[0],e);return t.x1=Wa(t.x1),t.y1=Wa(t.y1),t.x2=Wa(t.x2),t.y2=Wa(t.y2),t.w=Wa(t.x2-t.x1),t.h=Wa(t.y2-t.y1),t},Ya.dirtyBoundingBoxCache=function(){for(var e=0;e<this.length;e++){var t=this[e]._private;t.bbCache=null,t.bbCachePosKey=null,t.bodyBounds=null,t.overlayBounds=null,t.labelBounds.all=null,t.labelBounds.source=null,t.labelBounds.target=null,t.labelBounds.main=null,t.labelBounds.sourceRot=null,t.labelBounds.targetRot=null,t.labelBounds.mainRot=null,t.arrowBounds.source=null,t.arrowBounds.target=null,t.arrowBounds["mid-source"]=null,t.arrowBounds["mid-target"]=null}return this.emitAndNotify("bounds"),this},Ya.boundingBoxAt=function(e){var t=this.nodes(),n=this.cy(),r=n.hasCompoundNodes(),i=n.collection();if(r&&(i=t.filter((function(e){return e.isParent()})),t=t.not(i)),b(e)){var a=e;e=function(){return a}}n.startBatch(),t.forEach((function(t,n){return t._private.bbAtOldPos=e(t,n)})).silentPositions(e),r&&(i.dirtyCompoundBoundsCache(),i.dirtyBoundingBoxCache(),i.updateCompoundBounds(!0));var o=function(e){return{x1:e.x1,x2:e.x2,w:e.w,y1:e.y1,y2:e.y2,h:e.h}}(this.boundingBox({useCache:!1}));return t.silentPositions((function(e){return e._private.bbAtOldPos})),r&&(i.dirtyCompoundBoundsCache(),i.dirtyBoundingBoxCache(),i.updateCompoundBounds(!0)),n.endBatch(),o},qa.boundingbox=qa.bb=qa.boundingBox,qa.renderedBoundingbox=qa.renderedBoundingBox;var io,ao,oo=Ya;io=ao={};var so=function(e){e.uppercaseName=z(e.name),e.autoName="auto"+e.uppercaseName,e.labelName="label"+e.uppercaseName,e.outerName="outer"+e.uppercaseName,e.uppercaseOuterName=z(e.outerName),io[e.name]=function(){var t=this[0],n=t._private,r=n.cy._private.styleEnabled;if(t){if(!r)return 1;if(t.isParent())return t.updateCompoundBounds(),n[e.autoName]||0;var i=t.pstyle(e.name);switch(i.strValue){case"label":return t.recalculateRenderedStyle(),n.rstyle[e.labelName]||0;default:return i.pfValue}}},io["outer"+e.uppercaseName]=function(){var t=this[0],n=t._private.cy._private.styleEnabled;if(t)return n?t[e.name]()+t.pstyle("border-width").pfValue+2*t.padding():1},io["rendered"+e.uppercaseName]=function(){var t=this[0];if(t)return t[e.name]()*this.cy().zoom()},io["rendered"+e.uppercaseOuterName]=function(){var t=this[0];if(t)return t[e.outerName]()*this.cy().zoom()}};so({name:"width"}),so({name:"height"}),ao.padding=function(){var e=this[0],t=e._private;return e.isParent()?(e.updateCompoundBounds(),void 0!==t.autoPadding?t.autoPadding:e.pstyle("padding").pfValue):e.pstyle("padding").pfValue},ao.paddedHeight=function(){var e=this[0];return e.height()+2*e.padding()},ao.paddedWidth=function(){var e=this[0];return e.width()+2*e.padding()};var lo=ao,uo={controlPoints:{get:function(e){return e.renderer().getControlPoints(e)},mult:!0},segmentPoints:{get:function(e){return e.renderer().getSegmentPoints(e)},mult:!0},sourceEndpoint:{get:function(e){return e.renderer().getSourceEndpoint(e)}},targetEndpoint:{get:function(e){return e.renderer().getTargetEndpoint(e)}},midpoint:{get:function(e){return e.renderer().getEdgeMidpoint(e)}}},co=Object.keys(uo).reduce((function(e,t){var n=uo[t],r=function(e){return"rendered"+e[0].toUpperCase()+e.substr(1)}(t);return e[t]=function(){return function(e,t){if(e.isEdge())return t(e)}(this,n.get)},n.mult?e[r]=function(){return function(e,t){if(e.isEdge()){var n=e.cy(),r=n.pan(),i=n.zoom();return t(e).map((function(e){return yt(e,i,r)}))}}(this,n.get)}:e[r]=function(){return function(e,t){if(e.isEdge()){var n=e.cy();return yt(t(e),n.zoom(),n.pan())}}(this,n.get)},e}),{}),ho=L({},Xa,oo,lo,co),po=function(e,t){this.recycle(e,t)};function fo(){return!1}function go(){return!0}po.prototype={instanceString:function(){return"event"},recycle:function(e,t){if(this.isImmediatePropagationStopped=this.isPropagationStopped=this.isDefaultPrevented=fo,null!=e&&e.preventDefault?(this.type=e.type,this.isDefaultPrevented=e.defaultPrevented?go:fo):null!=e&&e.type?t=e:this.type=e,null!=t&&(this.originalEvent=t.originalEvent,this.type=null!=t.type?t.type:this.type,this.cy=t.cy,this.target=t.target,this.position=t.position,this.renderedPosition=t.renderedPosition,this.namespace=t.namespace,this.layout=t.layout),null!=this.cy&&null!=this.position&&null==this.renderedPosition){var n=this.position,r=this.cy.zoom(),i=this.cy.pan();this.renderedPosition={x:n.x*r+i.x,y:n.y*r+i.y}}this.timeStamp=e&&e.timeStamp||Date.now()},preventDefault:function(){this.isDefaultPrevented=go;var e=this.originalEvent;e&&e.preventDefault&&e.preventDefault()},stopPropagation:function(){this.isPropagationStopped=go;var e=this.originalEvent;e&&e.stopPropagation&&e.stopPropagation()},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=go,this.stopPropagation()},isDefaultPrevented:fo,isPropagationStopped:fo,isImmediatePropagationStopped:fo};var vo=/^([^.]+)(\.(?:[^.]+))?$/,yo={qualifierCompare:function(e,t){return e===t},eventMatches:function(){return!0},addEventFields:function(){},callbackContext:function(e){return e},beforeEmit:function(){},afterEmit:function(){},bubble:function(){return!1},parent:function(){return null},context:null},mo=Object.keys(yo),bo={};function xo(){for(var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:bo,t=arguments.length>1?arguments[1]:void 0,n=0;n<mo.length;n++){var r=mo[n];this[r]=e[r]||yo[r]}this.context=t||this.context,this.listeners=[],this.emitting=0}var wo=xo.prototype,Eo=function(e,t,n,r,i,a,o){y(r)&&(i=r,r=null),o&&(a=null==a?o:L({},a,o));for(var s=m(n)?n:n.split(/\s+/),l=0;l<s.length;l++){var u=s[l];if(!D(u)){var c=u.match(vo);if(c)if(!1===t(e,u,c[1],c[2]?c[2]:null,r,i,a))break}}},ko=function(e,t){return e.addEventFields(e.context,t),new po(t.type,t)},Co=function(e,t,n){if("event"!==g(n))if(b(n))t(e,ko(e,n));else for(var r=m(n)?n:n.split(/\s+/),i=0;i<r.length;i++){var a=r[i];if(!D(a)){var o=a.match(vo);if(o){var s=o[1],l=o[2]?o[2]:null;t(e,ko(e,{type:s,namespace:l,target:e.context}))}}}else t(e,n)};wo.on=wo.addListener=function(e,t,n,r,i){return Eo(this,(function(e,t,n,r,i,a,o){y(a)&&e.listeners.push({event:t,callback:a,type:n,namespace:r,qualifier:i,conf:o})}),e,t,n,r,i),this},wo.one=function(e,t,n,r){return this.on(e,t,n,r,{one:!0})},wo.removeListener=wo.off=function(e,t,n,r){var i=this;0!==this.emitting&&(this.listeners=this.listeners.slice());for(var a=this.listeners,o=function(o){var s=a[o];Eo(i,(function(t,n,r,i,l,u){if((s.type===r||"*"===e)&&(!i&&".*"!==s.namespace||s.namespace===i)&&(!l||t.qualifierCompare(s.qualifier,l))&&(!u||s.callback===u))return a.splice(o,1),!1}),e,t,n,r)},s=a.length-1;s>=0;s--)o(s);return this},wo.removeAllListeners=function(){return this.removeListener("*")},wo.emit=wo.trigger=function(e,t,n){var r=this.listeners,i=r.length;return this.emitting++,m(t)||(t=[t]),Co(this,(function(e,a){null!=n&&(r=[{event:a.event,type:a.type,namespace:a.namespace,callback:n}],i=r.length);for(var o=function(n){var i=r[n];if(i.type===a.type&&(!i.namespace||i.namespace===a.namespace||".*"===i.namespace)&&e.eventMatches(e.context,i,a)){var o=[a];null!=t&&function(e,t){for(var n=0;n<t.length;n++){var r=t[n];e.push(r)}}(o,t),e.beforeEmit(e.context,i,a),i.conf&&i.conf.one&&(e.listeners=e.listeners.filter((function(e){return e!==i})));var s=e.callbackContext(e.context,i,a),l=i.callback.apply(s,o);e.afterEmit(e.context,i,a),!1===l&&(a.stopPropagation(),a.preventDefault())}},s=0;s<i;s++)o(s);e.bubble(e.context)&&!a.isPropagationStopped()&&e.parent(e.context).emit(a,t)}),e),this.emitting--,this};var So={qualifierCompare:function(e,t){return null==e||null==t?null==e&&null==t:e.sameText(t)},eventMatches:function(e,t,n){var r=t.qualifier;return null==r||e!==n.target&&k(n.target)&&r.matches(n.target)},addEventFields:function(e,t){t.cy=e.cy(),t.target=e},callbackContext:function(e,t,n){return null!=t.qualifier?n.target:e},beforeEmit:function(e,t){t.conf&&t.conf.once&&t.conf.onceCollection.removeListener(t.event,t.qualifier,t.callback)},bubble:function(){return!0},parent:function(e){return e.isChild()?e.parent():e.cy()}},Po=function(e){return v(e)?new ka(e):e},Do={createEmitter:function(){for(var e=0;e<this.length;e++){var t=this[e],n=t._private;n.emitter||(n.emitter=new xo(So,t))}return this},emitter:function(){return this._private.emitter},on:function(e,t,n){for(var r=Po(t),i=0;i<this.length;i++){this[i].emitter().on(e,r,n)}return this},removeListener:function(e,t,n){for(var r=Po(t),i=0;i<this.length;i++){this[i].emitter().removeListener(e,r,n)}return this},removeAllListeners:function(){for(var e=0;e<this.length;e++){this[e].emitter().removeAllListeners()}return this},one:function(e,t,n){for(var r=Po(t),i=0;i<this.length;i++){this[i].emitter().one(e,r,n)}return this},once:function(e,t,n){for(var r=Po(t),i=0;i<this.length;i++){this[i].emitter().on(e,r,n,{once:!0,onceCollection:this})}},emit:function(e,t){for(var n=0;n<this.length;n++){this[n].emitter().emit(e,t)}return this},emitAndNotify:function(e,t){if(0!==this.length)return this.cy().notify(e,this),this.emit(e,t),this}};Fi.eventAliasesOn(Do);var To={nodes:function(e){return this.filter((function(e){return e.isNode()})).filter(e)},edges:function(e){return this.filter((function(e){return e.isEdge()})).filter(e)},byGroup:function(){for(var e=this.spawn(),t=this.spawn(),n=0;n<this.length;n++){var r=this[n];r.isNode()?e.push(r):t.push(r)}return{nodes:e,edges:t}},filter:function(e,t){if(void 0===e)return this;if(v(e)||E(e))return new ka(e).filter(this);if(y(e)){for(var n=this.spawn(),r=0;r<this.length;r++){var i=this[r];(t?e.apply(t,[i,r,this]):e(i,r,this))&&n.push(i)}return n}return this.spawn()},not:function(e){if(e){v(e)&&(e=this.filter(e));for(var t=this.spawn(),n=0;n<this.length;n++){var r=this[n];e.has(r)||t.push(r)}return t}return this},absoluteComplement:function(){return this.cy().mutableElements().not(this)},intersect:function(e){if(v(e)){var t=e;return this.filter(t)}for(var n=this.spawn(),r=e,i=this.length<e.length,a=i?this:r,o=i?r:this,s=0;s<a.length;s++){var l=a[s];o.has(l)&&n.push(l)}return n},xor:function(e){var t=this._private.cy;v(e)&&(e=t.$(e));var n=this.spawn(),r=e,i=function(e,t){for(var r=0;r<e.length;r++){var i=e[r],a=i._private.data.id;t.hasElementWithId(a)||n.push(i)}};return i(this,r),i(r,this),n},diff:function(e){var t=this._private.cy;v(e)&&(e=t.$(e));var n=this.spawn(),r=this.spawn(),i=this.spawn(),a=e,o=function(e,t,n){for(var r=0;r<e.length;r++){var a=e[r],o=a._private.data.id;t.hasElementWithId(o)?i.merge(a):n.push(a)}};return o(this,a,n),o(a,this,r),{left:n,right:r,both:i}},add:function(e){var t=this._private.cy;if(!e)return this;if(v(e)){var n=e;e=t.mutableElements().filter(n)}for(var r=this.spawnSelf(),i=0;i<e.length;i++){var a=e[i],o=!this.has(a);o&&r.push(a)}return r},merge:function(e){var t=this._private,n=t.cy;if(!e)return this;if(e&&v(e)){var r=e;e=n.mutableElements().filter(r)}for(var i=t.map,a=0;a<e.length;a++){var o=e[a],s=o._private.data.id;if(!i.has(s)){var l=this.length++;this[l]=o,i.set(s,{ele:o,index:l})}}return this},unmergeAt:function(e){var t=this[e].id(),n=this._private.map;this[e]=void 0,n.delete(t);var r=e===this.length-1;if(this.length>1&&!r){var i=this.length-1,a=this[i],o=a._private.data.id;this[i]=void 0,this[e]=a,n.set(o,{ele:a,index:e})}return this.length--,this},unmergeOne:function(e){e=e[0];var t=this._private,n=e._private.data.id,r=t.map.get(n);if(!r)return this;var i=r.index;return this.unmergeAt(i),this},unmerge:function(e){var t=this._private.cy;if(!e)return this;if(e&&v(e)){var n=e;e=t.mutableElements().filter(n)}for(var r=0;r<e.length;r++)this.unmergeOne(e[r]);return this},unmergeBy:function(e){for(var t=this.length-1;t>=0;t--){e(this[t])&&this.unmergeAt(t)}return this},map:function(e,t){for(var n=[],r=0;r<this.length;r++){var i=this[r],a=t?e.apply(t,[i,r,this]):e(i,r,this);n.push(a)}return n},reduce:function(e,t){for(var n=t,r=0;r<this.length;r++)n=e(n,this[r],r,this);return n},max:function(e,t){for(var n,r=-1/0,i=0;i<this.length;i++){var a=this[i],o=t?e.apply(t,[a,i,this]):e(a,i,this);o>r&&(r=o,n=a)}return{value:r,ele:n}},min:function(e,t){for(var n,r=1/0,i=0;i<this.length;i++){var a=this[i],o=t?e.apply(t,[a,i,this]):e(a,i,this);o<r&&(r=o,n=a)}return{value:r,ele:n}}},_o=To;_o.u=_o["|"]=_o["+"]=_o.union=_o.or=_o.add,_o["\\"]=_o["!"]=_o["-"]=_o.difference=_o.relativeComplement=_o.subtract=_o.not,_o.n=_o["&"]=_o["."]=_o.and=_o.intersection=_o.intersect,_o["^"]=_o["(+)"]=_o["(-)"]=_o.symmetricDifference=_o.symdiff=_o.xor,_o.fnFilter=_o.filterFn=_o.stdFilter=_o.filter,_o.complement=_o.abscomp=_o.absoluteComplement;var Mo=function(e,t){var n=e.cy().hasCompoundNodes();function r(e){var t=e.pstyle("z-compound-depth");return"auto"===t.value?n?e.zDepth():0:"bottom"===t.value?-1:"top"===t.value?Ie:0}var i=r(e)-r(t);if(0!==i)return i;function a(e){return"auto"===e.pstyle("z-index-compare").value&&e.isNode()?1:0}var o=a(e)-a(t);if(0!==o)return o;var s=e.pstyle("z-index").value-t.pstyle("z-index").value;return 0!==s?s:e.poolIndex()-t.poolIndex()},Bo={forEach:function(e,t){if(y(e))for(var n=this.length,r=0;r<n;r++){var i=this[r];if(!1===(t?e.apply(t,[i,r,this]):e(i,r,this)))break}return this},toArray:function(){for(var e=[],t=0;t<this.length;t++)e.push(this[t]);return e},slice:function(e,t){var n=[],r=this.length;null==t&&(t=r),null==e&&(e=0),e<0&&(e=r+e),t<0&&(t=r+t);for(var i=e;i>=0&&i<t&&i<r;i++)n.push(this[i]);return this.spawn(n)},size:function(){return this.length},eq:function(e){return this[e]||this.spawn()},first:function(){return this[0]||this.spawn()},last:function(){return this[this.length-1]||this.spawn()},empty:function(){return 0===this.length},nonempty:function(){return!this.empty()},sort:function(e){if(!y(e))return this;var t=this.toArray().sort(e);return this.spawn(t)},sortByZIndex:function(){return this.sort(Mo)},zDepth:function(){var e=this[0];if(e){var t=e._private;if("nodes"===t.group){var n=t.data.parent?e.parents().size():0;return e.isParent()?n:Ie-1}var r=t.source,i=t.target,a=r.zDepth(),o=i.zDepth();return Math.max(a,o,0)}}};Bo.each=Bo.forEach;"undefined"!=("undefined"==typeof Symbol?"undefined":e(Symbol))&&"undefined"!=e(Symbol.iterator)&&(Bo[Symbol.iterator]=function(){var e=this,t={value:void 0,done:!1},n=0,r=this.length;return i({next:function(){return n<r?t.value=e[n++]:(t.value=void 0,t.done=!0),t}},Symbol.iterator,(function(){return this}))});var No=He({nodeDimensionsIncludeLabels:!1}),zo={layoutDimensions:function(e){var t;if(e=No(e),this.takesUpSpace())if(e.nodeDimensionsIncludeLabels){var n=this.boundingBox();t={w:n.w,h:n.h}}else t={w:this.outerWidth(),h:this.outerHeight()};else t={w:0,h:0};return 0!==t.w&&0!==t.h||(t.w=t.h=1),t},layoutPositions:function(e,t,n){var r=this.nodes().filter((function(e){return!e.isParent()})),i=this.cy(),a=t.eles,o=function(e){return e.id()},s=_(n,o);e.emit({type:"layoutstart",layout:e}),e.animations=[];var l=t.spacingFactor&&1!==t.spacingFactor,u=function(){if(!l)return null;for(var e=_t(),t=0;t<r.length;t++){var n=r[t],i=s(n,t);Bt(e,i.x,i.y)}return e}(),c=_((function(e,n){var r=s(e,n);l&&(r=function(e,t,n){var r=t.x1+t.w/2,i=t.y1+t.h/2;return{x:r+(n.x-r)*e,y:i+(n.y-i)*e}}(Math.abs(t.spacingFactor),u,r));return null!=t.transform&&(r=t.transform(e,r)),r}),o);if(t.animate){for(var d=0;d<r.length;d++){var h=r[d],p=c(h,d);if(null==t.animateFilter||t.animateFilter(h,d)){var f=h.animation({position:p,duration:t.animationDuration,easing:t.animationEasing});e.animations.push(f)}else h.position(p)}if(t.fit){var g=i.animation({fit:{boundingBox:a.boundingBoxAt(c),padding:t.padding},duration:t.animationDuration,easing:t.animationEasing});e.animations.push(g)}else if(void 0!==t.zoom&&void 0!==t.pan){var v=i.animation({zoom:t.zoom,pan:t.pan,duration:t.animationDuration,easing:t.animationEasing});e.animations.push(v)}e.animations.forEach((function(e){return e.play()})),e.one("layoutready",t.ready),e.emit({type:"layoutready",layout:e}),vr.all(e.animations.map((function(e){return e.promise()}))).then((function(){e.one("layoutstop",t.stop),e.emit({type:"layoutstop",layout:e})}))}else r.positions(c),t.fit&&i.fit(t.eles,t.padding),null!=t.zoom&&i.zoom(t.zoom),t.pan&&i.pan(t.pan),e.one("layoutready",t.ready),e.emit({type:"layoutready",layout:e}),e.one("layoutstop",t.stop),e.emit({type:"layoutstop",layout:e});return this},layout:function(e){return this.cy().makeLayout(L({},e,{eles:this}))}};function Io(e,t,n){var r,i=n._private,a=i.styleCache=i.styleCache||[];return null!=(r=a[e])?r:r=a[e]=t(n)}function Ao(e,t){return e=Te(e),function(n){return Io(e,t,n)}}function Lo(e,t){e=Te(e);var n=function(e){return t.call(e)};return function(){var t=this[0];if(t)return Io(e,n,t)}}zo.createLayout=zo.makeLayout=zo.layout;var Oo={recalculateRenderedStyle:function(e){var t=this.cy(),n=t.renderer(),r=t.styleEnabled();return n&&r&&n.recalculateRenderedStyle(this,e),this},dirtyStyleCache:function(){var e,t=this.cy(),n=function(e){return e._private.styleCache=null};t.hasCompoundNodes()?((e=this.spawnSelf().merge(this.descendants()).merge(this.parents())).merge(e.connectedEdges()),e.forEach(n)):this.forEach((function(e){n(e),e.connectedEdges().forEach(n)}));return this},updateStyle:function(e){var t=this._private.cy;if(!t.styleEnabled())return this;if(t.batching())return t._private.batchStyleEles.merge(this),this;var n=this;e=!(!e&&void 0!==e),t.hasCompoundNodes()&&(n=this.spawnSelf().merge(this.descendants()).merge(this.parents()));var r=n;return e?r.emitAndNotify("style"):r.emit("style"),n.forEach((function(e){return e._private.styleDirty=!0})),this},cleanStyle:function(){var e=this.cy();if(e.styleEnabled())for(var t=0;t<this.length;t++){var n=this[t];n._private.styleDirty&&(n._private.styleDirty=!1,e.style().apply(n))}},parsedStyle:function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],n=this[0],r=n.cy();if(r.styleEnabled()&&n){this.cleanStyle();var i=n._private.style[e];return null!=i?i:t?r.style().getDefaultProperty(e):null}},numericStyle:function(e){var t=this[0];if(t.cy().styleEnabled()&&t){var n=t.pstyle(e);return void 0!==n.pfValue?n.pfValue:n.value}},numericStyleUnits:function(e){var t=this[0];if(t.cy().styleEnabled())return t?t.pstyle(e).units:void 0},renderedStyle:function(e){var t=this.cy();if(!t.styleEnabled())return this;var n=this[0];return n?t.style().getRenderedStyle(n,e):void 0},style:function(e,t){var n=this.cy();if(!n.styleEnabled())return this;var r=n.style();if(b(e)){var i=e;r.applyBypass(this,i,!1),this.emitAndNotify("style")}else if(v(e)){if(void 0===t){var a=this[0];return a?r.getStylePropertyValue(a,e):void 0}r.applyBypass(this,e,t,!1),this.emitAndNotify("style")}else if(void 0===e){var o=this[0];return o?r.getRawStyle(o):void 0}return this},removeStyle:function(e){var t=this.cy();if(!t.styleEnabled())return this;var n=t.style();if(void 0===e)for(var r=0;r<this.length;r++){var i=this[r];n.removeAllBypasses(i,!1)}else{e=e.split(/\s+/);for(var a=0;a<this.length;a++){var o=this[a];n.removeBypasses(o,e,!1)}}return this.emitAndNotify("style"),this},show:function(){return this.css("display","element"),this},hide:function(){return this.css("display","none"),this},effectiveOpacity:function(){var e=this.cy();if(!e.styleEnabled())return 1;var t=e.hasCompoundNodes(),n=this[0];if(n){var r=n._private,i=n.pstyle("opacity").value;if(!t)return i;var a=r.data.parent?n.parents():null;if(a)for(var o=0;o<a.length;o++){i*=a[o].pstyle("opacity").value}return i}},transparent:function(){if(!this.cy().styleEnabled())return!1;var e=this[0],t=e.cy().hasCompoundNodes();return e?t?0===e.effectiveOpacity():0===e.pstyle("opacity").value:void 0},backgrounding:function(){return!!this.cy().styleEnabled()&&!!this[0]._private.backgrounding}};function Ro(e,t){var n=e._private.data.parent?e.parents():null;if(n)for(var r=0;r<n.length;r++){if(!t(n[r]))return!1}return!0}function Vo(e){var t=e.ok,n=e.edgeOkViaNode||e.ok,r=e.parentOk||e.ok;return function(){var e=this.cy();if(!e.styleEnabled())return!0;var i=this[0],a=e.hasCompoundNodes();if(i){var o=i._private;if(!t(i))return!1;if(i.isNode())return!a||Ro(i,r);var s=o.source,l=o.target;return n(s)&&(!a||Ro(s,n))&&(s===l||n(l)&&(!a||Ro(l,n)))}}}var Fo=Ao("eleTakesUpSpace",(function(e){return"element"===e.pstyle("display").value&&0!==e.width()&&(!e.isNode()||0!==e.height())}));Oo.takesUpSpace=Lo("takesUpSpace",Vo({ok:Fo}));var jo=Ao("eleInteractive",(function(e){return"yes"===e.pstyle("events").value&&"visible"===e.pstyle("visibility").value&&Fo(e)})),qo=Ao("parentInteractive",(function(e){return"visible"===e.pstyle("visibility").value&&Fo(e)}));Oo.interactive=Lo("interactive",Vo({ok:jo,parentOk:qo,edgeOkViaNode:Fo})),Oo.noninteractive=function(){var e=this[0];if(e)return!e.interactive()};var Yo=Ao("eleVisible",(function(e){return"visible"===e.pstyle("visibility").value&&0!==e.pstyle("opacity").pfValue&&Fo(e)})),Xo=Fo;Oo.visible=Lo("visible",Vo({ok:Yo,edgeOkViaNode:Xo})),Oo.hidden=function(){var e=this[0];if(e)return!e.visible()},Oo.isBundledBezier=Lo("isBundledBezier",(function(){return!!this.cy().styleEnabled()&&(!this.removed()&&"bezier"===this.pstyle("curve-style").value&&this.takesUpSpace())})),Oo.bypass=Oo.css=Oo.style,Oo.renderedCss=Oo.renderedStyle,Oo.removeBypass=Oo.removeCss=Oo.removeStyle,Oo.pstyle=Oo.parsedStyle;var Wo={};function Ho(e){return function(){var t=arguments,n=[];if(2===t.length){var r=t[0],i=t[1];this.on(e.event,r,i)}else if(1===t.length&&y(t[0])){var a=t[0];this.on(e.event,a)}else if(0===t.length||1===t.length&&m(t[0])){for(var o=1===t.length?t[0]:null,s=0;s<this.length;s++){var l=this[s],u=!e.ableField||l._private[e.ableField],c=l._private[e.field]!=e.value;if(e.overrideAble){var d=e.overrideAble(l);if(void 0!==d&&(u=d,!d))return this}u&&(l._private[e.field]=e.value,c&&n.push(l))}var h=this.spawn(n);h.updateStyle(),h.emit(e.event),o&&h.emit(o)}return this}}function Ko(e){Wo[e.field]=function(){var t=this[0];if(t){if(e.overrideField){var n=e.overrideField(t);if(void 0!==n)return n}return t._private[e.field]}},Wo[e.on]=Ho({event:e.on,field:e.field,ableField:e.ableField,overrideAble:e.overrideAble,value:!0}),Wo[e.off]=Ho({event:e.off,field:e.field,ableField:e.ableField,overrideAble:e.overrideAble,value:!1})}Ko({field:"locked",overrideField:function(e){return!!e.cy().autolock()||void 0},on:"lock",off:"unlock"}),Ko({field:"grabbable",overrideField:function(e){return!e.cy().autoungrabify()&&!e.pannable()&&void 0},on:"grabify",off:"ungrabify"}),Ko({field:"selected",ableField:"selectable",overrideAble:function(e){return!e.cy().autounselectify()&&void 0},on:"select",off:"unselect"}),Ko({field:"selectable",overrideField:function(e){return!e.cy().autounselectify()&&void 0},on:"selectify",off:"unselectify"}),Wo.deselect=Wo.unselect,Wo.grabbed=function(){var e=this[0];if(e)return e._private.grabbed},Ko({field:"active",on:"activate",off:"unactivate"}),Ko({field:"pannable",on:"panify",off:"unpanify"}),Wo.inactive=function(){var e=this[0];if(e)return!e._private.active};var Go={},Uo=function(e){return function(t){for(var n=[],r=0;r<this.length;r++){var i=this[r];if(i.isNode()){for(var a=!1,o=i.connectedEdges(),s=0;s<o.length;s++){var l=o[s],u=l.source(),c=l.target();if(e.noIncomingEdges&&c===i&&u!==i||e.noOutgoingEdges&&u===i&&c!==i){a=!0;break}}a||n.push(i)}}return this.spawn(n,!0).filter(t)}},Zo=function(e){return function(t){for(var n=[],r=0;r<this.length;r++){var i=this[r];if(i.isNode())for(var a=i.connectedEdges(),o=0;o<a.length;o++){var s=a[o],l=s.source(),u=s.target();e.outgoing&&l===i?(n.push(s),n.push(u)):e.incoming&&u===i&&(n.push(s),n.push(l))}}return this.spawn(n,!0).filter(t)}},$o=function(e){return function(t){for(var n=this,r=[],i={};;){var a=e.outgoing?n.outgoers():n.incomers();if(0===a.length)break;for(var o=!1,s=0;s<a.length;s++){var l=a[s],u=l.id();i[u]||(i[u]=!0,r.push(l),o=!0)}if(!o)break;n=a}return this.spawn(r,!0).filter(t)}};function Qo(e){return function(t){for(var n=[],r=0;r<this.length;r++){var i=this[r]._private[e.attr];i&&n.push(i)}return this.spawn(n,!0).filter(t)}}function Jo(e){return function(t){var n=[],r=this._private.cy,i=e||{};v(t)&&(t=r.$(t));for(var a=0;a<t.length;a++)for(var o=t[a]._private.edges,s=0;s<o.length;s++){var l=o[s],u=l._private.data,c=this.hasElementWithId(u.source)&&t.hasElementWithId(u.target),d=t.hasElementWithId(u.source)&&this.hasElementWithId(u.target);if(c||d){if(i.thisIsSrc||i.thisIsTgt){if(i.thisIsSrc&&!c)continue;if(i.thisIsTgt&&!d)continue}n.push(l)}}return this.spawn(n,!0)}}function es(e){return e=L({},{codirected:!1},e),function(t){for(var n=[],r=this.edges(),i=e,a=0;a<r.length;a++)for(var o=r[a]._private,s=o.source,l=s._private.data.id,u=o.data.target,c=s._private.edges,d=0;d<c.length;d++){var h=c[d],p=h._private.data,f=p.target,g=p.source,v=f===u&&g===l,y=l===f&&u===g;(i.codirected&&v||!i.codirected&&(v||y))&&n.push(h)}return this.spawn(n,!0).filter(t)}}Go.clearTraversalCache=function(){for(var e=0;e<this.length;e++)this[e]._private.traversalCache=null},L(Go,{roots:Uo({noIncomingEdges:!0}),leaves:Uo({noOutgoingEdges:!0}),outgoers:Ta(Zo({outgoing:!0}),"outgoers"),successors:$o({outgoing:!0}),incomers:Ta(Zo({incoming:!0}),"incomers"),predecessors:$o({incoming:!0})}),L(Go,{neighborhood:Ta((function(e){for(var t=[],n=this.nodes(),r=0;r<n.length;r++)for(var i=n[r],a=i.connectedEdges(),o=0;o<a.length;o++){var s=a[o],l=s.source(),u=s.target(),c=i===l?u:l;c.length>0&&t.push(c[0]),t.push(s[0])}return this.spawn(t,!0).filter(e)}),"neighborhood"),closedNeighborhood:function(e){return this.neighborhood().add(this).filter(e)},openNeighborhood:function(e){return this.neighborhood(e)}}),Go.neighbourhood=Go.neighborhood,Go.closedNeighbourhood=Go.closedNeighborhood,Go.openNeighbourhood=Go.openNeighborhood,L(Go,{source:Ta((function(e){var t,n=this[0];return n&&(t=n._private.source||n.cy().collection()),t&&e?t.filter(e):t}),"source"),target:Ta((function(e){var t,n=this[0];return n&&(t=n._private.target||n.cy().collection()),t&&e?t.filter(e):t}),"target"),sources:Qo({attr:"source"}),targets:Qo({attr:"target"})}),L(Go,{edgesWith:Ta(Jo(),"edgesWith"),edgesTo:Ta(Jo({thisIsSrc:!0}),"edgesTo")}),L(Go,{connectedEdges:Ta((function(e){for(var t=[],n=0;n<this.length;n++){var r=this[n];if(r.isNode())for(var i=r._private.edges,a=0;a<i.length;a++){var o=i[a];t.push(o)}}return this.spawn(t,!0).filter(e)}),"connectedEdges"),connectedNodes:Ta((function(e){for(var t=[],n=0;n<this.length;n++){var r=this[n];r.isEdge()&&(t.push(r.source()[0]),t.push(r.target()[0]))}return this.spawn(t,!0).filter(e)}),"connectedNodes"),parallelEdges:Ta(es(),"parallelEdges"),codirectedEdges:Ta(es({codirected:!0}),"codirectedEdges")}),L(Go,{components:function(e){var t=this,n=t.cy(),r=n.collection(),i=null==e?t.nodes():e.nodes(),a=[];null!=e&&i.empty()&&(i=e.sources());var o=function(e,t){r.merge(e),i.unmerge(e),t.merge(e)};if(i.empty())return t.spawn();var s=function(){var e=n.collection();a.push(e);var r=i[0];o(r,e),t.bfs({directed:!1,roots:r,visit:function(t){return o(t,e)}}),e.forEach((function(n){n.connectedEdges().forEach((function(n){t.has(n)&&e.has(n.source())&&e.has(n.target())&&e.merge(n)}))}))};do{s()}while(i.length>0);return a},component:function(){var e=this[0];return e.cy().mutableElements().components(e)[0]}}),Go.componentsOf=Go.components;var ts=function(e,t){var n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(void 0!==e){var i=new $e,a=!1;if(t){if(t.length>0&&b(t[0])&&!k(t[0])){a=!0;for(var o=[],s=new Je,l=0,u=t.length;l<u;l++){var c=t[l];null==c.data&&(c.data={});var d=c.data;if(null==d.id)d.id=Ye();else if(e.hasElementWithId(d.id)||s.has(d.id))continue;var h=new et(e,c,!1);o.push(h),s.add(d.id)}t=o}}else t=[];this.length=0;for(var p=0,f=t.length;p<f;p++){var g=t[p][0];if(null!=g){var v=g._private.data.id;n&&i.has(v)||(n&&i.set(v,{index:this.length,ele:g}),this[this.length]=g,this.length++)}}this._private={eles:this,cy:e,get map(){return null==this.lazyMap&&this.rebuildMap(),this.lazyMap},set map(e){this.lazyMap=e},rebuildMap:function(){for(var e=this.lazyMap=new $e,t=this.eles,n=0;n<t.length;n++){var r=t[n];e.set(r.id(),{index:n,ele:r})}}},n&&(this._private.map=i),a&&!r&&this.restore()}else Ve("A collection must have a reference to the core")},ns=et.prototype=ts.prototype=Object.create(Array.prototype);ns.instanceString=function(){return"collection"},ns.spawn=function(e,t){return new ts(this.cy(),e,t)},ns.spawnSelf=function(){return this.spawn(this)},ns.cy=function(){return this._private.cy},ns.renderer=function(){return this._private.cy.renderer()},ns.element=function(){return this[0]},ns.collection=function(){return C(this)?this:new ts(this._private.cy,[this])},ns.unique=function(){return new ts(this._private.cy,this,!0)},ns.hasElementWithId=function(e){return e=""+e,this._private.map.has(e)},ns.getElementById=function(e){e=""+e;var t=this._private.cy,n=this._private.map.get(e);return n?n.ele:new ts(t)},ns.$id=ns.getElementById,ns.poolIndex=function(){var e=this._private.cy._private.elements,t=this[0]._private.data.id;return e._private.map.get(t).index},ns.indexOf=function(e){var t=e[0]._private.data.id;return this._private.map.get(t).index},ns.indexOfId=function(e){return e=""+e,this._private.map.get(e).index},ns.json=function(e){var t=this.element(),n=this.cy();if(null==t&&e)return this;if(null!=t){var r=t._private;if(b(e)){if(n.startBatch(),e.data){t.data(e.data);var i=r.data;if(t.isEdge()){var a=!1,o={},s=e.data.source,l=e.data.target;null!=s&&s!=i.source&&(o.source=""+s,a=!0),null!=l&&l!=i.target&&(o.target=""+l,a=!0),a&&(t=t.move(o))}else{var u="parent"in e.data,c=e.data.parent;!u||null==c&&null==i.parent||c==i.parent||(void 0===c&&(c=null),null!=c&&(c=""+c),t=t.move({parent:c}))}}e.position&&t.position(e.position);var d=function(n,i,a){var o=e[n];null!=o&&o!==r[n]&&(o?t[i]():t[a]())};return d("removed","remove","restore"),d("selected","select","unselect"),d("selectable","selectify","unselectify"),d("locked","lock","unlock"),d("grabbable","grabify","ungrabify"),d("pannable","panify","unpanify"),null!=e.classes&&t.classes(e.classes),n.endBatch(),this}if(void 0===e){var h={data:qe(r.data),position:qe(r.position),group:r.group,removed:r.removed,selected:r.selected,selectable:r.selectable,locked:r.locked,grabbable:r.grabbable,pannable:r.pannable,classes:null};h.classes="";var p=0;return r.classes.forEach((function(e){return h.classes+=0==p++?e:" "+e})),h}}},ns.jsons=function(){for(var e=[],t=0;t<this.length;t++){var n=this[t].json();e.push(n)}return e},ns.clone=function(){for(var e=this.cy(),t=[],n=0;n<this.length;n++){var r=this[n].json(),i=new et(e,r,!1);t.push(i)}return new ts(e,t)},ns.copy=ns.clone,ns.restore=function(){for(var e,t,n=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],r=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],i=this,a=i.cy(),o=a._private,s=[],l=[],u=0,c=i.length;u<c;u++){var d=i[u];r&&!d.removed()||(d.isNode()?s.push(d):l.push(d))}e=s.concat(l);var h=function(){e.splice(t,1),t--};for(t=0;t<e.length;t++){var p=e[t],f=p._private,g=f.data;if(p.clearTraversalCache(),r||f.removed)if(void 0===g.id)g.id=Ye();else if(x(g.id))g.id=""+g.id;else{if(D(g.id)||!v(g.id)){Ve("Can not create element with invalid string ID `"+g.id+"`"),h();continue}if(a.hasElementWithId(g.id)){Ve("Can not create second element with ID `"+g.id+"`"),h();continue}}else;var y=g.id;if(p.isNode()){var m=f.position;null==m.x&&(m.x=0),null==m.y&&(m.y=0)}if(p.isEdge()){for(var b=p,w=["source","target"],E=w.length,k=!1,C=0;C<E;C++){var S=w[C],P=g[S];x(P)&&(P=g[S]=""+g[S]),null==P||""===P?(Ve("Can not create edge `"+y+"` with unspecified "+S),k=!0):a.hasElementWithId(P)||(Ve("Can not create edge `"+y+"` with nonexistant "+S+" `"+P+"`"),k=!0)}if(k){h();continue}var T=a.getElementById(g.source),_=a.getElementById(g.target);T.same(_)?T._private.edges.push(b):(T._private.edges.push(b),_._private.edges.push(b)),b._private.source=T,b._private.target=_}f.map=new $e,f.map.set(y,{ele:p,index:0}),f.removed=!1,r&&a.addToPool(p)}for(var M=0;M<s.length;M++){var B=s[M],N=B._private.data;x(N.parent)&&(N.parent=""+N.parent);var z=N.parent,I=null!=z;if(I||B._private.parent){var A=B._private.parent?a.collection().merge(B._private.parent):a.getElementById(z);if(A.empty())N.parent=void 0;else if(A[0].removed())je("Node added with missing parent, reference to parent removed"),N.parent=void 0,B._private.parent=null;else{for(var L=!1,O=A;!O.empty();){if(B.same(O)){L=!0,N.parent=void 0;break}O=O.parent()}L||(A[0]._private.children.push(B),B._private.parent=A[0],o.hasCompoundNodes=!0)}}}if(e.length>0){for(var R=e.length===i.length?i:new ts(a,e),V=0;V<R.length;V++){var F=R[V];F.isNode()||(F.parallelEdges().clearTraversalCache(),F.source().clearTraversalCache(),F.target().clearTraversalCache())}(o.hasCompoundNodes?a.collection().merge(R).merge(R.connectedNodes()).merge(R.parent()):R).dirtyCompoundBoundsCache().dirtyBoundingBoxCache().updateStyle(n),n?R.emitAndNotify("add"):r&&R.emit("add")}return i},ns.removed=function(){var e=this[0];return e&&e._private.removed},ns.inside=function(){var e=this[0];return e&&!e._private.removed},ns.remove=function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],n=this,r=[],i={},a=n._private.cy;function o(e){for(var t=e._private.edges,n=0;n<t.length;n++)l(t[n])}function s(e){for(var t=e._private.children,n=0;n<t.length;n++)l(t[n])}function l(e){var n=i[e.id()];t&&e.removed()||n||(i[e.id()]=!0,e.isNode()?(r.push(e),o(e),s(e)):r.unshift(e))}for(var u=0,c=n.length;u<c;u++){var d=n[u];l(d)}function h(e,t){var n=e._private.edges;Ke(n,t),e.clearTraversalCache()}function p(e){e.clearTraversalCache()}var f=[];function g(e,t){t=t[0];var n=(e=e[0])._private.children,r=e.id();Ke(n,t),t._private.parent=null,f.ids[r]||(f.ids[r]=!0,f.push(e))}f.ids={},n.dirtyCompoundBoundsCache(),t&&a.removeFromPool(r);for(var v=0;v<r.length;v++){var y=r[v];if(y.isEdge()){var m=y.source()[0],b=y.target()[0];h(m,y),h(b,y);for(var x=y.parallelEdges(),w=0;w<x.length;w++){var E=x[w];p(E),E.isBundledBezier()&&E.dirtyBoundingBoxCache()}}else{var k=y.parent();0!==k.length&&g(k,y)}t&&(y._private.removed=!0)}var C=a._private.elements;a._private.hasCompoundNodes=!1;for(var S=0;S<C.length;S++){var P=C[S];if(P.isParent()){a._private.hasCompoundNodes=!0;break}}var D=new ts(this.cy(),r);D.size()>0&&(e?D.emitAndNotify("remove"):t&&D.emit("remove"));for(var T=0;T<f.length;T++){var _=f[T];t&&_.removed()||_.updateStyle()}return D},ns.move=function(e){var t=this._private.cy,n=this,r=function(e){return null==e?e:""+e};if(void 0!==e.source||void 0!==e.target){var i=r(e.source),a=r(e.target),o=null!=i&&t.hasElementWithId(i),s=null!=a&&t.hasElementWithId(a);(o||s)&&(t.batch((function(){n.remove(!1,!1),n.emitAndNotify("moveout");for(var e=0;e<n.length;e++){var t=n[e],r=t._private.data;t.isEdge()&&(o&&(r.source=i),s&&(r.target=a))}n.restore(!1,!1)})),n.emitAndNotify("move"))}else if(void 0!==e.parent){var l=r(e.parent);if(null===l||t.hasElementWithId(l)){var u=null===l?void 0:l;t.batch((function(){var e=n.remove(!1,!1);e.emitAndNotify("moveout");for(var t=0;t<n.length;t++){var r=n[t],i=r._private.data;r.isNode()&&(i.parent=u)}e.restore(!1,!1)})),n.emitAndNotify("move")}}return this},[ur,ji,qi,Sa,_a,La,Oa,ho,Do,To,{isNode:function(){return"nodes"===this.group()},isEdge:function(){return"edges"===this.group()},isLoop:function(){return this.isEdge()&&this.source()[0]===this.target()[0]},isSimple:function(){return this.isEdge()&&this.source()[0]!==this.target()[0]},group:function(){var e=this[0];if(e)return e._private.group}},Bo,zo,Oo,Wo,Go].forEach((function(e){L(ns,e)}));var rs={add:function(e){var t,n=this;if(E(e)){var r=e;if(r._private.cy===n)t=r.restore();else{for(var i=[],a=0;a<r.length;a++){var o=r[a];i.push(o.json())}t=new ts(n,i)}}else if(m(e)){t=new ts(n,e)}else if(b(e)&&(m(e.nodes)||m(e.edges))){for(var s=e,l=[],u=["nodes","edges"],c=0,d=u.length;c<d;c++){var h=u[c],p=s[h];if(m(p))for(var f=0,g=p.length;f<g;f++){var v=L({group:h},p[f]);l.push(v)}}t=new ts(n,l)}else{t=new et(n,e).collection()}return t},remove:function(e){if(E(e));else if(v(e)){var t=e;e=this.$(t)}return e.remove()}};
+/*! Bezier curve function generator. Copyright Gaetan Renaudeau. MIT License: http://en.wikipedia.org/wiki/MIT_License */
+/*! Runge-Kutta spring physics function generator. Adapted from Framer.js, copyright Koen Bok. MIT License: http://en.wikipedia.org/wiki/MIT_License */
+var is=function(){function e(e){return-e.tension*e.x-e.friction*e.v}function t(t,n,r){var i={x:t.x+r.dx*n,v:t.v+r.dv*n,tension:t.tension,friction:t.friction};return{dx:i.v,dv:e(i)}}function n(n,r){var i={dx:n.v,dv:e(n)},a=t(n,.5*r,i),o=t(n,.5*r,a),s=t(n,r,o),l=1/6*(i.dx+2*(a.dx+o.dx)+s.dx),u=1/6*(i.dv+2*(a.dv+o.dv)+s.dv);return n.x=n.x+l*r,n.v=n.v+u*r,n}return function e(t,r,i){var a,o,s,l={x:-1,v:0,tension:null,friction:null},u=[0],c=0;for(t=parseFloat(t)||500,r=parseFloat(r)||20,i=i||null,l.tension=t,l.friction=r,o=(a=null!==i)?(c=e(t,r))/i*.016:.016;s=n(s||l,o),u.push(1+s.x),c+=16,Math.abs(s.x)>1e-4&&Math.abs(s.v)>1e-4;);return a?function(e){return u[e*(u.length-1)|0]}:c}}(),as=function(e,t,n,r){var i=function(e,t,n,r){var i=4,a=.001,o=1e-7,s=10,l=11,u=1/(l-1),c="undefined"!=typeof Float32Array;if(4!==arguments.length)return!1;for(var d=0;d<4;++d)if("number"!=typeof arguments[d]||isNaN(arguments[d])||!isFinite(arguments[d]))return!1;e=Math.min(e,1),n=Math.min(n,1),e=Math.max(e,0),n=Math.max(n,0);var h=c?new Float32Array(l):new Array(l);function p(e,t){return 1-3*t+3*e}function f(e,t){return 3*t-6*e}function g(e){return 3*e}function v(e,t,n){return((p(t,n)*e+f(t,n))*e+g(t))*e}function y(e,t,n){return 3*p(t,n)*e*e+2*f(t,n)*e+g(t)}function m(t,r){for(var a=0;a<i;++a){var o=y(r,e,n);if(0===o)return r;r-=(v(r,e,n)-t)/o}return r}function b(){for(var t=0;t<l;++t)h[t]=v(t*u,e,n)}function x(t,r,i){var a,l,u=0;do{(a=v(l=r+(i-r)/2,e,n)-t)>0?i=l:r=l}while(Math.abs(a)>o&&++u<s);return l}function w(t){for(var r=0,i=1,o=l-1;i!==o&&h[i]<=t;++i)r+=u;--i;var s=r+(t-h[i])/(h[i+1]-h[i])*u,c=y(s,e,n);return c>=a?m(t,s):0===c?s:x(t,r,r+u)}var E=!1;function k(){E=!0,e===t&&n===r||b()}var C=function(i){return E||k(),e===t&&n===r?i:0===i?0:1===i?1:v(w(i),t,r)};C.getControlPoints=function(){return[{x:e,y:t},{x:n,y:r}]};var S="generateBezier("+[e,t,n,r]+")";return C.toString=function(){return S},C}(e,t,n,r);return function(e,t,n){return e+(t-e)*i(n)}},os={linear:function(e,t,n){return e+(t-e)*n},ease:as(.25,.1,.25,1),"ease-in":as(.42,0,1,1),"ease-out":as(0,0,.58,1),"ease-in-out":as(.42,0,.58,1),"ease-in-sine":as(.47,0,.745,.715),"ease-out-sine":as(.39,.575,.565,1),"ease-in-out-sine":as(.445,.05,.55,.95),"ease-in-quad":as(.55,.085,.68,.53),"ease-out-quad":as(.25,.46,.45,.94),"ease-in-out-quad":as(.455,.03,.515,.955),"ease-in-cubic":as(.55,.055,.675,.19),"ease-out-cubic":as(.215,.61,.355,1),"ease-in-out-cubic":as(.645,.045,.355,1),"ease-in-quart":as(.895,.03,.685,.22),"ease-out-quart":as(.165,.84,.44,1),"ease-in-out-quart":as(.77,0,.175,1),"ease-in-quint":as(.755,.05,.855,.06),"ease-out-quint":as(.23,1,.32,1),"ease-in-out-quint":as(.86,0,.07,1),"ease-in-expo":as(.95,.05,.795,.035),"ease-out-expo":as(.19,1,.22,1),"ease-in-out-expo":as(1,0,0,1),"ease-in-circ":as(.6,.04,.98,.335),"ease-out-circ":as(.075,.82,.165,1),"ease-in-out-circ":as(.785,.135,.15,.86),spring:function(e,t,n){if(0===n)return os.linear;var r=is(e,t,n);return function(e,t,n){return e+(t-e)*r(n)}},"cubic-bezier":as};function ss(e,t,n,r,i){if(1===r)return n;if(t===n)return n;var a=i(t,n,r);return null==e||((e.roundValue||e.color)&&(a=Math.round(a)),void 0!==e.min&&(a=Math.max(a,e.min)),void 0!==e.max&&(a=Math.min(a,e.max))),a}function ls(e,t){return null!=e.pfValue||null!=e.value?null==e.pfValue||null!=t&&"%"===t.type.units?e.value:e.pfValue:e}function us(e,t,n,r,i){var a=null!=i?i.type:null;n<0?n=0:n>1&&(n=1);var o=ls(e,i),s=ls(t,i);if(x(o)&&x(s))return ss(a,o,s,n,r);if(m(o)&&m(s)){for(var l=[],u=0;u<s.length;u++){var c=o[u],d=s[u];if(null!=c&&null!=d){var h=ss(a,c,d,n,r);l.push(h)}else l.push(d)}return l}}function cs(e,t,n,r){var i=!r,a=e._private,o=t._private,s=o.easing,l=o.startTime,u=(r?e:e.cy()).style();if(!o.easingImpl)if(null==s)o.easingImpl=os.linear;else{var c,d,h;if(v(s))c=u.parse("transition-timing-function",s).value;else c=s;v(c)?(d=c,h=[]):(d=c[1],h=c.slice(2).map((function(e){return+e}))),h.length>0?("spring"===d&&h.push(o.duration),o.easingImpl=os[d].apply(null,h)):o.easingImpl=os[d]}var p,f=o.easingImpl;if(p=0===o.duration?1:(n-l)/o.duration,o.applying&&(p=o.progress),p<0?p=0:p>1&&(p=1),null==o.delay){var g=o.startPosition,y=o.position;if(y&&i&&!e.locked()){var m={};ds(g.x,y.x)&&(m.x=us(g.x,y.x,p,f)),ds(g.y,y.y)&&(m.y=us(g.y,y.y,p,f)),e.position(m)}var b=o.startPan,x=o.pan,w=a.pan,E=null!=x&&r;E&&(ds(b.x,x.x)&&(w.x=us(b.x,x.x,p,f)),ds(b.y,x.y)&&(w.y=us(b.y,x.y,p,f)),e.emit("pan"));var k=o.startZoom,C=o.zoom,S=null!=C&&r;S&&(ds(k,C)&&(a.zoom=Tt(a.minZoom,us(k,C,p,f),a.maxZoom)),e.emit("zoom")),(E||S)&&e.emit("viewport");var P=o.style;if(P&&P.length>0&&i){for(var D=0;D<P.length;D++){var T=P[D],_=T.name,M=T,B=o.startStyle[_],N=us(B,M,p,f,u.properties[B.name]);u.overrideBypass(e,_,N)}e.emit("style")}}return o.progress=p,p}function ds(e,t){return null!=e&&null!=t&&(!(!x(e)||!x(t))||!(!e||!t))}function hs(e,t,n,r){var i=t._private;i.started=!0,i.startTime=n-i.progress*i.duration}function ps(e,t){var n=t._private.aniEles,r=[];function i(t,n){var i=t._private,a=i.animation.current,o=i.animation.queue,s=!1;if(0===a.length){var l=o.shift();l&&a.push(l)}for(var u=function(e){for(var t=e.length-1;t>=0;t--){(0,e[t])()}e.splice(0,e.length)},c=a.length-1;c>=0;c--){var d=a[c],h=d._private;h.stopped?(a.splice(c,1),h.hooked=!1,h.playing=!1,h.started=!1,u(h.frames)):(h.playing||h.applying)&&(h.playing&&h.applying&&(h.applying=!1),h.started||hs(0,d,e),cs(t,d,e,n),h.applying&&(h.applying=!1),u(h.frames),null!=h.step&&h.step(e),d.completed()&&(a.splice(c,1),h.hooked=!1,h.playing=!1,h.started=!1,u(h.completes)),s=!0)}return n||0!==a.length||0!==o.length||r.push(t),s}for(var a=!1,o=0;o<n.length;o++){var s=i(n[o]);a=a||s}var l=i(t,!0);(a||l)&&(n.length>0?t.notify("draw",n):t.notify("draw")),n.unmerge(r),t.emit("step")}var fs={animate:Fi.animate(),animation:Fi.animation(),animated:Fi.animated(),clearQueue:Fi.clearQueue(),delay:Fi.delay(),delayAnimation:Fi.delayAnimation(),stop:Fi.stop(),addToAnimationPool:function(e){this.styleEnabled()&&this._private.aniEles.merge(e)},stopAnimationLoop:function(){this._private.animationsRunning=!1},startAnimationLoop:function(){var e=this;if(e._private.animationsRunning=!0,e.styleEnabled()){var t=e.renderer();t&&t.beforeRender?t.beforeRender((function(t,n){ps(n,e)}),t.beforeRenderPriorities.animations):function t(){e._private.animationsRunning&&xe((function(n){ps(n,e),t()}))}()}}},gs={qualifierCompare:function(e,t){return null==e||null==t?null==e&&null==t:e.sameText(t)},eventMatches:function(e,t,n){var r=t.qualifier;return null==r||e!==n.target&&k(n.target)&&r.matches(n.target)},addEventFields:function(e,t){t.cy=e,t.target=e},callbackContext:function(e,t,n){return null!=t.qualifier?n.target:e}},vs=function(e){return v(e)?new ka(e):e},ys={createEmitter:function(){var e=this._private;return e.emitter||(e.emitter=new xo(gs,this)),this},emitter:function(){return this._private.emitter},on:function(e,t,n){return this.emitter().on(e,vs(t),n),this},removeListener:function(e,t,n){return this.emitter().removeListener(e,vs(t),n),this},removeAllListeners:function(){return this.emitter().removeAllListeners(),this},one:function(e,t,n){return this.emitter().one(e,vs(t),n),this},once:function(e,t,n){return this.emitter().one(e,vs(t),n),this},emit:function(e,t){return this.emitter().emit(e,t),this},emitAndNotify:function(e,t){return this.emit(e),this.notify(e,t),this}};Fi.eventAliasesOn(ys);var ms={png:function(e){return e=e||{},this._private.renderer.png(e)},jpg:function(e){var t=this._private.renderer;return(e=e||{}).bg=e.bg||"#fff",t.jpg(e)}};ms.jpeg=ms.jpg;var bs={layout:function(e){if(null!=e)if(null!=e.name){var t=e.name,n=this.extension("layout",t);if(null!=n){var r;r=v(e.eles)?this.$(e.eles):null!=e.eles?e.eles:this.$();var i=new n(L({},e,{cy:this,eles:r}));return i}Ve("No such layout `"+t+"` found. Did you forget to import it and `cytoscape.use()` it?")}else Ve("A `name` must be specified to make a layout");else Ve("Layout options must be specified to make a layout")}};bs.createLayout=bs.makeLayout=bs.layout;var xs={notify:function(e,t){var n=this._private;if(this.batching()){n.batchNotifications=n.batchNotifications||{};var r=n.batchNotifications[e]=n.batchNotifications[e]||this.collection();null!=t&&r.merge(t)}else if(n.notificationsEnabled){var i=this.renderer();!this.destroyed()&&i&&i.notify(e,t)}},notifications:function(e){var t=this._private;return void 0===e?t.notificationsEnabled:(t.notificationsEnabled=!!e,this)},noNotifications:function(e){this.notifications(!1),e(),this.notifications(!0)},batching:function(){return this._private.batchCount>0},startBatch:function(){var e=this._private;return null==e.batchCount&&(e.batchCount=0),0===e.batchCount&&(e.batchStyleEles=this.collection(),e.batchNotifications={}),e.batchCount++,this},endBatch:function(){var e=this._private;if(0===e.batchCount)return this;if(e.batchCount--,0===e.batchCount){e.batchStyleEles.updateStyle();var t=this.renderer();Object.keys(e.batchNotifications).forEach((function(n){var r=e.batchNotifications[n];r.empty()?t.notify(n):t.notify(n,r)}))}return this},batch:function(e){return this.startBatch(),e(),this.endBatch(),this},batchData:function(e){var t=this;return this.batch((function(){for(var n=Object.keys(e),r=0;r<n.length;r++){var i=n[r],a=e[i];t.getElementById(i).data(a)}}))}},ws=He({hideEdgesOnViewport:!1,textureOnViewport:!1,motionBlur:!1,motionBlurOpacity:.05,pixelRatio:void 0,desktopTapThreshold:4,touchTapThreshold:8,wheelSensitivity:1,debug:!1,showFps:!1}),Es={renderTo:function(e,t,n,r){return this._private.renderer.renderTo(e,t,n,r),this},renderer:function(){return this._private.renderer},forceRender:function(){return this.notify("draw"),this},resize:function(){return this.invalidateSize(),this.emitAndNotify("resize"),this},initRenderer:function(e){var t=this.extension("renderer",e.name);if(null!=t){void 0!==e.wheelSensitivity&&je("You have set a custom wheel sensitivity. This will make your app zoom unnaturally when using mainstream mice. You should change this value from the default only if you can guarantee that all your users will use the same hardware and OS configuration as your current machine.");var n=ws(e);n.cy=this,this._private.renderer=new t(n),this.notify("init")}else Ve("Can not initialise: No such renderer `".concat(e.name,"` found. Did you forget to import it and `cytoscape.use()` it?"))},destroyRenderer:function(){this.notify("destroy");var e=this.container();if(e)for(e._cyreg=null;e.childNodes.length>0;)e.removeChild(e.childNodes[0]);this._private.renderer=null,this.mutableElements().forEach((function(e){var t=e._private;t.rscratch={},t.rstyle={},t.animation.current=[],t.animation.queue=[]}))},onRender:function(e){return this.on("render",e)},offRender:function(e){return this.off("render",e)}};Es.invalidateDimensions=Es.resize;var ks={collection:function(e,t){return v(e)?this.$(e):E(e)?e.collection():m(e)?(t||(t={}),new ts(this,e,t.unique,t.removed)):new ts(this)},nodes:function(e){var t=this.$((function(e){return e.isNode()}));return e?t.filter(e):t},edges:function(e){var t=this.$((function(e){return e.isEdge()}));return e?t.filter(e):t},$:function(e){var t=this._private.elements;return e?t.filter(e):t.spawnSelf()},mutableElements:function(){return this._private.elements}};ks.elements=ks.filter=ks.$;var Cs={};Cs.apply=function(e){for(var t=this._private.cy.collection(),n=0;n<e.length;n++){var r=e[n],i=this.getContextMeta(r);if(!i.empty){var a=this.getContextStyle(i),o=this.applyContextStyle(i,a,r);r._private.appliedInitStyle?this.updateTransitions(r,o.diffProps):r._private.appliedInitStyle=!0,this.updateStyleHints(r)&&t.push(r)}}return t},Cs.getPropertiesDiff=function(e,t){var n=this._private.propDiffs=this._private.propDiffs||{},r=e+"-"+t,i=n[r];if(i)return i;for(var a=[],o={},s=0;s<this.length;s++){var l=this[s],u="t"===e[s],c="t"===t[s],d=u!==c,h=l.mappedProperties.length>0;if(d||c&&h){var p=void 0;d&&h||d?p=l.properties:h&&(p=l.mappedProperties);for(var f=0;f<p.length;f++){for(var g=p[f],v=g.name,y=!1,m=s+1;m<this.length;m++){var b=this[m];if("t"===t[m]&&(y=null!=b.properties[g.name]))break}o[v]||y||(o[v]=!0,a.push(v))}}}return n[r]=a,a},Cs.getContextMeta=function(e){for(var t,n="",r=e._private.styleCxtKey||"",i=0;i<this.length;i++){var a=this[i];n+=a.selector&&a.selector.matches(e)?"t":"f"}return t=this.getPropertiesDiff(r,n),e._private.styleCxtKey=n,{key:n,diffPropNames:t,empty:0===t.length}},Cs.getContextStyle=function(e){var t=e.key,n=this._private.contextStyles=this._private.contextStyles||{};if(n[t])return n[t];for(var r={_private:{key:t}},i=0;i<this.length;i++){var a=this[i];if("t"===t[i])for(var o=0;o<a.properties.length;o++){var s=a.properties[o];r[s.name]=s}}return n[t]=r,r},Cs.applyContextStyle=function(e,t,n){for(var r=e.diffPropNames,i={},a=this.types,o=0;o<r.length;o++){var s=r[o],l=t[s],u=n.pstyle(s);if(!l){if(!u)continue;l=u.bypass?{name:s,deleteBypassed:!0}:{name:s,delete:!0}}if(u!==l){if(l.mapped===a.fn&&null!=u&&null!=u.mapping&&u.mapping.value===l.value){var c=u.mapping;if((c.fnValue=l.value(n))===c.prevFnValue)continue}var d=i[s]={prev:u};this.applyParsedProperty(n,l),d.next=n.pstyle(s),d.next&&d.next.bypass&&(d.next=d.next.bypassed)}}return{diffProps:i}},Cs.updateStyleHints=function(e){var t=e._private,n=this,r=n.propertyGroupNames,i=n.propertyGroupKeys,a=function(e,t,r){return n.getPropertiesHash(e,t,r)},o=t.styleKey;if(e.removed())return!1;var s="nodes"===t.group,l=e._private.style;r=Object.keys(l);for(var u=0;u<i.length;u++){var c=i[u];t.styleKeys[c]=[9261,5381]}for(var d,h=function(e,n){return t.styleKeys[n][0]=Ce(e,t.styleKeys[n][0])},p=function(e,n){return t.styleKeys[n][1]=Se(e,t.styleKeys[n][1])},f=function(e,t){h(e,t),p(e,t)},g=function(e,t){for(var n=0;n<e.length;n++){var r=e.charCodeAt(n);h(r,t),p(r,t)}},v=0;v<r.length;v++){var y=r[v],m=l[y];if(null!=m){var b=this.properties[y],x=b.type,w=b.groupKey,E=void 0;null!=b.hashOverride?E=b.hashOverride(e,m):null!=m.pfValue&&(E=m.pfValue);var k=null==b.enums?m.value:null,C=null!=E,S=C||null!=k,P=m.units;if(x.number&&S&&!x.multiple)f(-128<(d=C?E:k)&&d<128&&Math.floor(d)!==d?2e9-(1024*d|0):d,w),C||null==P||g(P,w);else g(m.strValue,w)}}for(var D,T,_=[9261,5381],M=0;M<i.length;M++){var B=i[M],N=t.styleKeys[B];_[0]=Ce(N[0],_[0]),_[1]=Se(N[1],_[1])}t.styleKey=(D=_[0],T=_[1],2097152*D+T);var z=t.styleKeys;t.labelDimsKey=Pe(z.labelDimensions);var I=a(e,["label"],z.labelDimensions);if(t.labelKey=Pe(I),t.labelStyleKey=Pe(De(z.commonLabel,I)),!s){var A=a(e,["source-label"],z.labelDimensions);t.sourceLabelKey=Pe(A),t.sourceLabelStyleKey=Pe(De(z.commonLabel,A));var L=a(e,["target-label"],z.labelDimensions);t.targetLabelKey=Pe(L),t.targetLabelStyleKey=Pe(De(z.commonLabel,L))}if(s){var O=t.styleKeys,R=O.nodeBody,V=O.nodeBorder,F=O.nodeOutline,j=O.backgroundImage,q=O.compound,Y=O.pie,X=[R,V,F,j,q,Y].filter((function(e){return null!=e})).reduce(De,[9261,5381]);t.nodeKey=Pe(X),t.hasPie=null!=Y&&9261!==Y[0]&&5381!==Y[1]}return o!==t.styleKey},Cs.clearStyleHints=function(e){var t=e._private;t.styleCxtKey="",t.styleKeys={},t.styleKey=null,t.labelKey=null,t.labelStyleKey=null,t.sourceLabelKey=null,t.sourceLabelStyleKey=null,t.targetLabelKey=null,t.targetLabelStyleKey=null,t.nodeKey=null,t.hasPie=null},Cs.applyParsedProperty=function(e,t){var n,r=this,i=t,a=e._private.style,o=r.types,s=r.properties[i.name].type,l=i.bypass,u=a[i.name],c=u&&u.bypass,d=e._private,h=function(e){return null==e?null:null!=e.pfValue?e.pfValue:e.value},p=function(){var t=h(u),n=h(i);r.checkTriggers(e,i.name,t,n)};if("curve-style"===t.name&&e.isEdge()&&("bezier"!==t.value&&e.isLoop()||"haystack"===t.value&&(e.source().isParent()||e.target().isParent()))&&(i=t=this.parse(t.name,"bezier",l)),i.delete)return a[i.name]=void 0,p(),!0;if(i.deleteBypassed)return u?!!u.bypass&&(u.bypassed=void 0,p(),!0):(p(),!0);if(i.deleteBypass)return u?!!u.bypass&&(a[i.name]=u.bypassed,p(),!0):(p(),!0);var f=function(){je("Do not assign mappings to elements without corresponding data (i.e. ele `"+e.id()+"` has no mapping for property `"+i.name+"` with data field `"+i.field+"`); try a `["+i.field+"]` selector to limit scope to elements with `"+i.field+"` defined")};switch(i.mapped){case o.mapData:for(var g,v=i.field.split("."),y=d.data,m=0;m<v.length&&y;m++){y=y[v[m]]}if(null==y)return f(),!1;if(!x(y))return je("Do not use continuous mappers without specifying numeric data (i.e. `"+i.field+": "+y+"` for `"+e.id()+"` is non-numeric)"),!1;var b=i.fieldMax-i.fieldMin;if((g=0===b?0:(y-i.fieldMin)/b)<0?g=0:g>1&&(g=1),s.color){var w=i.valueMin[0],E=i.valueMax[0],k=i.valueMin[1],C=i.valueMax[1],S=i.valueMin[2],P=i.valueMax[2],D=null==i.valueMin[3]?1:i.valueMin[3],T=null==i.valueMax[3]?1:i.valueMax[3],_=[Math.round(w+(E-w)*g),Math.round(k+(C-k)*g),Math.round(S+(P-S)*g),Math.round(D+(T-D)*g)];n={bypass:i.bypass,name:i.name,value:_,strValue:"rgb("+_[0]+", "+_[1]+", "+_[2]+")"}}else{if(!s.number)return!1;var M=i.valueMin+(i.valueMax-i.valueMin)*g;n=this.parse(i.name,M,i.bypass,"mapping")}if(!n)return f(),!1;n.mapping=i,i=n;break;case o.data:for(var B=i.field.split("."),N=d.data,z=0;z<B.length&&N;z++){N=N[B[z]]}if(null!=N&&(n=this.parse(i.name,N,i.bypass,"mapping")),!n)return f(),!1;n.mapping=i,i=n;break;case o.fn:var I=i.value,A=null!=i.fnValue?i.fnValue:I(e);if(i.prevFnValue=A,null==A)return je("Custom function mappers may not return null (i.e. `"+i.name+"` for ele `"+e.id()+"` is null)"),!1;if(!(n=this.parse(i.name,A,i.bypass,"mapping")))return je("Custom function mappers may not return invalid values for the property type (i.e. `"+i.name+"` for ele `"+e.id()+"` is invalid)"),!1;n.mapping=qe(i),i=n;break;case void 0:break;default:return!1}return l?(i.bypassed=c?u.bypassed:u,a[i.name]=i):c?u.bypassed=i:a[i.name]=i,p(),!0},Cs.cleanElements=function(e,t){for(var n=0;n<e.length;n++){var r=e[n];if(this.clearStyleHints(r),r.dirtyCompoundBoundsCache(),r.dirtyBoundingBoxCache(),t)for(var i=r._private.style,a=Object.keys(i),o=0;o<a.length;o++){var s=a[o],l=i[s];null!=l&&(l.bypass?l.bypassed=null:i[s]=null)}else r._private.style={}}},Cs.update=function(){this._private.cy.mutableElements().updateStyle()},Cs.updateTransitions=function(e,t){var n=this,r=e._private,i=e.pstyle("transition-property").value,a=e.pstyle("transition-duration").pfValue,o=e.pstyle("transition-delay").pfValue;if(i.length>0&&a>0){for(var s={},l=!1,u=0;u<i.length;u++){var c=i[u],d=e.pstyle(c),h=t[c];if(h){var p=h.prev,f=null!=h.next?h.next:d,g=!1,v=void 0;p&&(x(p.pfValue)&&x(f.pfValue)?(g=f.pfValue-p.pfValue,v=p.pfValue+1e-6*g):x(p.value)&&x(f.value)?(g=f.value-p.value,v=p.value+1e-6*g):m(p.value)&&m(f.value)&&(g=p.value[0]!==f.value[0]||p.value[1]!==f.value[1]||p.value[2]!==f.value[2],v=p.strValue),g&&(s[c]=f.strValue,this.applyBypass(e,c,v),l=!0))}}if(!l)return;r.transitioning=!0,new vr((function(t){o>0?e.delayAnimation(o).play().promise().then(t):t()})).then((function(){return e.animation({style:s,duration:a,easing:e.pstyle("transition-timing-function").value,queue:!1}).play().promise()})).then((function(){n.removeBypasses(e,i),e.emitAndNotify("style"),r.transitioning=!1}))}else r.transitioning&&(this.removeBypasses(e,i),e.emitAndNotify("style"),r.transitioning=!1)},Cs.checkTrigger=function(e,t,n,r,i,a){var o=this.properties[t],s=i(o);null!=s&&s(n,r)&&a(o)},Cs.checkZOrderTrigger=function(e,t,n,r){var i=this;this.checkTrigger(e,t,n,r,(function(e){return e.triggersZOrder}),(function(){i._private.cy.notify("zorder",e)}))},Cs.checkBoundsTrigger=function(e,t,n,r){this.checkTrigger(e,t,n,r,(function(e){return e.triggersBounds}),(function(i){e.dirtyCompoundBoundsCache(),e.dirtyBoundingBoxCache(),!i.triggersBoundsOfParallelBeziers||"curve-style"!==t||"bezier"!==n&&"bezier"!==r||e.parallelEdges().forEach((function(e){e.isBundledBezier()&&e.dirtyBoundingBoxCache()})),!i.triggersBoundsOfConnectedEdges||"display"!==t||"none"!==n&&"none"!==r||e.connectedEdges().forEach((function(e){e.dirtyBoundingBoxCache()}))}))},Cs.checkTriggers=function(e,t,n,r){e.dirtyStyleCache(),this.checkZOrderTrigger(e,t,n,r),this.checkBoundsTrigger(e,t,n,r)};var Ss={applyBypass:function(e,t,n,r){var i=[];if("*"===t||"**"===t){if(void 0!==n)for(var a=0;a<this.properties.length;a++){var o=this.properties[a].name,s=this.parse(o,n,!0);s&&i.push(s)}}else if(v(t)){var l=this.parse(t,n,!0);l&&i.push(l)}else{if(!b(t))return!1;var u=t;r=n;for(var c=Object.keys(u),d=0;d<c.length;d++){var h=c[d],p=u[h];if(void 0===p&&(p=u[B(h)]),void 0!==p){var f=this.parse(h,p,!0);f&&i.push(f)}}}if(0===i.length)return!1;for(var g=!1,y=0;y<e.length;y++){for(var m=e[y],x={},w=void 0,E=0;E<i.length;E++){var k=i[E];if(r){var C=m.pstyle(k.name);w=x[k.name]={prev:C}}g=this.applyParsedProperty(m,qe(k))||g,r&&(w.next=m.pstyle(k.name))}g&&this.updateStyleHints(m),r&&this.updateTransitions(m,x,!0)}return g},overrideBypass:function(e,t,n){t=M(t);for(var r=0;r<e.length;r++){var i=e[r],a=i._private.style[t],o=this.properties[t].type,s=o.color,l=o.mutiple,u=a?null!=a.pfValue?a.pfValue:a.value:null;a&&a.bypass?(a.value=n,null!=a.pfValue&&(a.pfValue=n),a.strValue=s?"rgb("+n.join(",")+")":l?n.join(" "):""+n,this.updateStyleHints(i)):this.applyBypass(i,t,n),this.checkTriggers(i,t,u,n)}},removeAllBypasses:function(e,t){return this.removeBypasses(e,this.propertyNames,t)},removeBypasses:function(e,t,n){for(var r=0;r<e.length;r++){for(var i=e[r],a={},o=0;o<t.length;o++){var s=t[o],l=this.properties[s],u=i.pstyle(l.name);if(u&&u.bypass){var c=this.parse(s,"",!0),d=a[l.name]={prev:u};this.applyParsedProperty(i,c),d.next=i.pstyle(l.name)}}this.updateStyleHints(i),n&&this.updateTransitions(i,a,!0)}}},Ps={getEmSizeInPixels:function(){var e=this.containerCss("font-size");return null!=e?parseFloat(e):1},containerCss:function(e){var t=this._private.cy,n=t.container(),r=t.window();if(r&&n&&r.getComputedStyle)return r.getComputedStyle(n).getPropertyValue(e)}},Ds={getRenderedStyle:function(e,t){return t?this.getStylePropertyValue(e,t,!0):this.getRawStyle(e,!0)},getRawStyle:function(e,t){if(e=e[0]){for(var n={},r=0;r<this.properties.length;r++){var i=this.properties[r],a=this.getStylePropertyValue(e,i.name,t);null!=a&&(n[i.name]=a,n[B(i.name)]=a)}return n}},getIndexedStyle:function(e,t,n,r){var i=e.pstyle(t)[n][r];return null!=i?i:e.cy().style().getDefaultProperty(t)[n][0]},getStylePropertyValue:function(e,t,n){if(e=e[0]){var r=this.properties[t];r.alias&&(r=r.pointsTo);var i=r.type,a=e.pstyle(r.name);if(a){var o=a.value,s=a.units,l=a.strValue;if(n&&i.number&&null!=o&&x(o)){var u=e.cy().zoom(),c=function(e){return e*u},d=function(e,t){return c(e)+t},h=m(o);return(h?s.every((function(e){return null!=e})):null!=s)?h?o.map((function(e,t){return d(e,s[t])})).join(" "):d(o,s):h?o.map((function(e){return v(e)?e:""+c(e)})).join(" "):""+c(o)}if(null!=l)return l}return null}},getAnimationStartStyle:function(e,t){for(var n={},r=0;r<t.length;r++){var i=t[r].name,a=e.pstyle(i);void 0!==a&&(a=b(a)?this.parse(i,a.strValue):this.parse(i,a)),a&&(n[i]=a)}return n},getPropsList:function(e){var t=[],n=e,r=this.properties;if(n)for(var i=Object.keys(n),a=0;a<i.length;a++){var o=i[a],s=n[o],l=r[o]||r[M(o)],u=this.parse(l.name,s);u&&t.push(u)}return t},getNonDefaultPropertiesHash:function(e,t,n){var r,i,a,o,s,l,u=n.slice();for(s=0;s<t.length;s++)if(r=t[s],null!=(i=e.pstyle(r,!1)))if(null!=i.pfValue)u[0]=Ce(o,u[0]),u[1]=Se(o,u[1]);else for(a=i.strValue,l=0;l<a.length;l++)o=a.charCodeAt(l),u[0]=Ce(o,u[0]),u[1]=Se(o,u[1]);return u}};Ds.getPropertiesHash=Ds.getNonDefaultPropertiesHash;var Ts={appendFromJson:function(e){for(var t=0;t<e.length;t++){var n=e[t],r=n.selector,i=n.style||n.css,a=Object.keys(i);this.selector(r);for(var o=0;o<a.length;o++){var s=a[o],l=i[s];this.css(s,l)}}return this},fromJson:function(e){return this.resetToDefault(),this.appendFromJson(e),this},json:function(){for(var e=[],t=this.defaultLength;t<this.length;t++){for(var n=this[t],r=n.selector,i=n.properties,a={},o=0;o<i.length;o++){var s=i[o];a[s.name]=s.strValue}e.push({selector:r?r.toString():"core",style:a})}return e}},_s={appendFromString:function(e){var t,n,r,i=""+e;function a(){i=i.length>t.length?i.substr(t.length):""}function o(){n=n.length>r.length?n.substr(r.length):""}for(i=i.replace(/[/][*](\s|.)+?[*][/]/g,"");;){if(i.match(/^\s*$/))break;var s=i.match(/^\s*((?:.|\s)+?)\s*\{((?:.|\s)+?)\}/);if(!s){je("Halting stylesheet parsing: String stylesheet contains more to parse but no selector and block found in: "+i);break}t=s[0];var l=s[1];if("core"!==l)if(new ka(l).invalid){je("Skipping parsing of block: Invalid selector found in string stylesheet: "+l),a();continue}var u=s[2],c=!1;n=u;for(var d=[];;){if(n.match(/^\s*$/))break;var h=n.match(/^\s*(.+?)\s*:\s*(.+?)(?:\s*;|\s*$)/);if(!h){je("Skipping parsing of block: Invalid formatting of style property and value definitions found in:"+u),c=!0;break}r=h[0];var p=h[1],f=h[2];if(this.properties[p])this.parse(p,f)?(d.push({name:p,val:f}),o()):(je("Skipping property: Invalid property definition in: "+r),o());else je("Skipping property: Invalid property name in: "+r),o()}if(c){a();break}this.selector(l);for(var g=0;g<d.length;g++){var v=d[g];this.css(v.name,v.val)}a()}return this},fromString:function(e){return this.resetToDefault(),this.appendFromString(e),this}},Ms={};!function(){var e=I,t=function(e){return"^"+e+"\\s*\\(\\s*([\\w\\.]+)\\s*\\)$"},n=function(t){var n=e+"|\\w+|rgb[a]?\\((?:(?:[-+]?(?:(?:\\d+|\\d*\\.\\d+)(?:[Ee][+-]?\\d+)?))[%]?)\\s*,\\s*(?:(?:[-+]?(?:(?:\\d+|\\d*\\.\\d+)(?:[Ee][+-]?\\d+)?))[%]?)\\s*,\\s*(?:(?:[-+]?(?:(?:\\d+|\\d*\\.\\d+)(?:[Ee][+-]?\\d+)?))[%]?)(?:\\s*,\\s*(?:(?:[-+]?(?:(?:\\d+|\\d*\\.\\d+)(?:[Ee][+-]?\\d+)?))))?\\)|hsl[a]?\\((?:(?:[-+]?(?:(?:\\d+|\\d*\\.\\d+)(?:[Ee][+-]?\\d+)?)))\\s*,\\s*(?:(?:[-+]?(?:(?:\\d+|\\d*\\.\\d+)(?:[Ee][+-]?\\d+)?))[%])\\s*,\\s*(?:(?:[-+]?(?:(?:\\d+|\\d*\\.\\d+)(?:[Ee][+-]?\\d+)?))[%])(?:\\s*,\\s*(?:(?:[-+]?(?:(?:\\d+|\\d*\\.\\d+)(?:[Ee][+-]?\\d+)?))))?\\)|\\#[0-9a-fA-F]{3}|\\#[0-9a-fA-F]{6}";return"^"+t+"\\s*\\(([\\w\\.]+)\\s*\\,\\s*("+e+")\\s*\\,\\s*("+e+")\\s*,\\s*("+n+")\\s*\\,\\s*("+n+")\\)$"},r=["^url\\s*\\(\\s*['\"]?(.+?)['\"]?\\s*\\)$","^(none)$","^(.+)$"];Ms.types={time:{number:!0,min:0,units:"s|ms",implicitUnits:"ms"},percent:{number:!0,min:0,max:100,units:"%",implicitUnits:"%"},percentages:{number:!0,min:0,max:100,units:"%",implicitUnits:"%",multiple:!0},zeroOneNumber:{number:!0,min:0,max:1,unitless:!0},zeroOneNumbers:{number:!0,min:0,max:1,unitless:!0,multiple:!0},nOneOneNumber:{number:!0,min:-1,max:1,unitless:!0},nonNegativeInt:{number:!0,min:0,integer:!0,unitless:!0},nonNegativeNumber:{number:!0,min:0,unitless:!0},position:{enums:["parent","origin"]},nodeSize:{number:!0,min:0,enums:["label"]},number:{number:!0,unitless:!0},numbers:{number:!0,unitless:!0,multiple:!0},positiveNumber:{number:!0,unitless:!0,min:0,strictMin:!0},size:{number:!0,min:0},bidirectionalSize:{number:!0},bidirectionalSizeMaybePercent:{number:!0,allowPercent:!0},bidirectionalSizes:{number:!0,multiple:!0},sizeMaybePercent:{number:!0,min:0,allowPercent:!0},axisDirection:{enums:["horizontal","leftward","rightward","vertical","upward","downward","auto"]},paddingRelativeTo:{enums:["width","height","average","min","max"]},bgWH:{number:!0,min:0,allowPercent:!0,enums:["auto"],multiple:!0},bgPos:{number:!0,allowPercent:!0,multiple:!0},bgRelativeTo:{enums:["inner","include-padding"],multiple:!0},bgRepeat:{enums:["repeat","repeat-x","repeat-y","no-repeat"],multiple:!0},bgFit:{enums:["none","contain","cover"],multiple:!0},bgCrossOrigin:{enums:["anonymous","use-credentials","null"],multiple:!0},bgClip:{enums:["none","node"],multiple:!0},bgContainment:{enums:["inside","over"],multiple:!0},color:{color:!0},colors:{color:!0,multiple:!0},fill:{enums:["solid","linear-gradient","radial-gradient"]},bool:{enums:["yes","no"]},bools:{enums:["yes","no"],multiple:!0},lineStyle:{enums:["solid","dotted","dashed"]},lineCap:{enums:["butt","round","square"]},linePosition:{enums:["center","inside","outside"]},lineJoin:{enums:["round","bevel","miter"]},borderStyle:{enums:["solid","dotted","dashed","double"]},curveStyle:{enums:["bezier","unbundled-bezier","haystack","segments","straight","straight-triangle","taxi","round-segments","round-taxi"]},radiusType:{enums:["arc-radius","influence-radius"],multiple:!0},fontFamily:{regex:'^([\\w- \\"]+(?:\\s*,\\s*[\\w- \\"]+)*)$'},fontStyle:{enums:["italic","normal","oblique"]},fontWeight:{enums:["normal","bold","bolder","lighter","100","200","300","400","500","600","800","900",100,200,300,400,500,600,700,800,900]},textDecoration:{enums:["none","underline","overline","line-through"]},textTransform:{enums:["none","uppercase","lowercase"]},textWrap:{enums:["none","wrap","ellipsis"]},textOverflowWrap:{enums:["whitespace","anywhere"]},textBackgroundShape:{enums:["rectangle","roundrectangle","round-rectangle"]},nodeShape:{enums:["rectangle","roundrectangle","round-rectangle","cutrectangle","cut-rectangle","bottomroundrectangle","bottom-round-rectangle","barrel","ellipse","triangle","round-triangle","square","pentagon","round-pentagon","hexagon","round-hexagon","concavehexagon","concave-hexagon","heptagon","round-heptagon","octagon","round-octagon","tag","round-tag","star","diamond","round-diamond","vee","rhomboid","right-rhomboid","polygon"]},overlayShape:{enums:["roundrectangle","round-rectangle","ellipse"]},cornerRadius:{number:!0,min:0,units:"px|em",implicitUnits:"px",enums:["auto"]},compoundIncludeLabels:{enums:["include","exclude"]},arrowShape:{enums:["tee","triangle","triangle-tee","circle-triangle","triangle-cross","triangle-backcurve","vee","square","circle","diamond","chevron","none"]},arrowFill:{enums:["filled","hollow"]},arrowWidth:{number:!0,units:"%|px|em",implicitUnits:"px",enums:["match-line"]},display:{enums:["element","none"]},visibility:{enums:["hidden","visible"]},zCompoundDepth:{enums:["bottom","orphan","auto","top"]},zIndexCompare:{enums:["auto","manual"]},valign:{enums:["top","center","bottom"]},halign:{enums:["left","center","right"]},justification:{enums:["left","center","right","auto"]},text:{string:!0},data:{mapping:!0,regex:t("data")},layoutData:{mapping:!0,regex:t("layoutData")},scratch:{mapping:!0,regex:t("scratch")},mapData:{mapping:!0,regex:n("mapData")},mapLayoutData:{mapping:!0,regex:n("mapLayoutData")},mapScratch:{mapping:!0,regex:n("mapScratch")},fn:{mapping:!0,fn:!0},url:{regexes:r,singleRegexMatchValue:!0},urls:{regexes:r,singleRegexMatchValue:!0,multiple:!0},propList:{propList:!0},angle:{number:!0,units:"deg|rad",implicitUnits:"rad"},textRotation:{number:!0,units:"deg|rad",implicitUnits:"rad",enums:["none","autorotate"]},polygonPointList:{number:!0,multiple:!0,evenMultiple:!0,min:-1,max:1,unitless:!0},edgeDistances:{enums:["intersection","node-position","endpoints"]},edgeEndpoint:{number:!0,multiple:!0,units:"%|px|em|deg|rad",implicitUnits:"px",enums:["inside-to-node","outside-to-node","outside-to-node-or-label","outside-to-line","outside-to-line-or-label"],singleEnum:!0,validate:function(e,t){switch(e.length){case 2:return"deg"!==t[0]&&"rad"!==t[0]&&"deg"!==t[1]&&"rad"!==t[1];case 1:return v(e[0])||"deg"===t[0]||"rad"===t[0];default:return!1}}},easing:{regexes:["^(spring)\\s*\\(\\s*("+e+")\\s*,\\s*("+e+")\\s*\\)$","^(cubic-bezier)\\s*\\(\\s*("+e+")\\s*,\\s*("+e+")\\s*,\\s*("+e+")\\s*,\\s*("+e+")\\s*\\)$"],enums:["linear","ease","ease-in","ease-out","ease-in-out","ease-in-sine","ease-out-sine","ease-in-out-sine","ease-in-quad","ease-out-quad","ease-in-out-quad","ease-in-cubic","ease-out-cubic","ease-in-out-cubic","ease-in-quart","ease-out-quart","ease-in-out-quart","ease-in-quint","ease-out-quint","ease-in-out-quint","ease-in-expo","ease-out-expo","ease-in-out-expo","ease-in-circ","ease-out-circ","ease-in-out-circ"]},gradientDirection:{enums:["to-bottom","to-top","to-left","to-right","to-bottom-right","to-bottom-left","to-top-right","to-top-left","to-right-bottom","to-left-bottom","to-right-top","to-left-top"]},boundsExpansion:{number:!0,multiple:!0,min:0,validate:function(e){var t=e.length;return 1===t||2===t||4===t}}};var i={zeroNonZero:function(e,t){return(null==e||null==t)&&e!==t||(0==e&&0!=t||0!=e&&0==t)},any:function(e,t){return e!=t},emptyNonEmpty:function(e,t){var n=D(e),r=D(t);return n&&!r||!n&&r}},a=Ms.types,o=[{name:"label",type:a.text,triggersBounds:i.any,triggersZOrder:i.emptyNonEmpty},{name:"text-rotation",type:a.textRotation,triggersBounds:i.any},{name:"text-margin-x",type:a.bidirectionalSize,triggersBounds:i.any},{name:"text-margin-y",type:a.bidirectionalSize,triggersBounds:i.any}],s=[{name:"source-label",type:a.text,triggersBounds:i.any},{name:"source-text-rotation",type:a.textRotation,triggersBounds:i.any},{name:"source-text-margin-x",type:a.bidirectionalSize,triggersBounds:i.any},{name:"source-text-margin-y",type:a.bidirectionalSize,triggersBounds:i.any},{name:"source-text-offset",type:a.size,triggersBounds:i.any}],l=[{name:"target-label",type:a.text,triggersBounds:i.any},{name:"target-text-rotation",type:a.textRotation,triggersBounds:i.any},{name:"target-text-margin-x",type:a.bidirectionalSize,triggersBounds:i.any},{name:"target-text-margin-y",type:a.bidirectionalSize,triggersBounds:i.any},{name:"target-text-offset",type:a.size,triggersBounds:i.any}],u=[{name:"font-family",type:a.fontFamily,triggersBounds:i.any},{name:"font-style",type:a.fontStyle,triggersBounds:i.any},{name:"font-weight",type:a.fontWeight,triggersBounds:i.any},{name:"font-size",type:a.size,triggersBounds:i.any},{name:"text-transform",type:a.textTransform,triggersBounds:i.any},{name:"text-wrap",type:a.textWrap,triggersBounds:i.any},{name:"text-overflow-wrap",type:a.textOverflowWrap,triggersBounds:i.any},{name:"text-max-width",type:a.size,triggersBounds:i.any},{name:"text-outline-width",type:a.size,triggersBounds:i.any},{name:"line-height",type:a.positiveNumber,triggersBounds:i.any}],c=[{name:"text-valign",type:a.valign,triggersBounds:i.any},{name:"text-halign",type:a.halign,triggersBounds:i.any},{name:"color",type:a.color},{name:"text-outline-color",type:a.color},{name:"text-outline-opacity",type:a.zeroOneNumber},{name:"text-background-color",type:a.color},{name:"text-background-opacity",type:a.zeroOneNumber},{name:"text-background-padding",type:a.size,triggersBounds:i.any},{name:"text-border-opacity",type:a.zeroOneNumber},{name:"text-border-color",type:a.color},{name:"text-border-width",type:a.size,triggersBounds:i.any},{name:"text-border-style",type:a.borderStyle,triggersBounds:i.any},{name:"text-background-shape",type:a.textBackgroundShape,triggersBounds:i.any},{name:"text-justification",type:a.justification}],d=[{name:"events",type:a.bool,triggersZOrder:i.any},{name:"text-events",type:a.bool,triggersZOrder:i.any}],h=[{name:"display",type:a.display,triggersZOrder:i.any,triggersBounds:i.any,triggersBoundsOfConnectedEdges:!0},{name:"visibility",type:a.visibility,triggersZOrder:i.any},{name:"opacity",type:a.zeroOneNumber,triggersZOrder:i.zeroNonZero},{name:"text-opacity",type:a.zeroOneNumber},{name:"min-zoomed-font-size",type:a.size},{name:"z-compound-depth",type:a.zCompoundDepth,triggersZOrder:i.any},{name:"z-index-compare",type:a.zIndexCompare,triggersZOrder:i.any},{name:"z-index",type:a.number,triggersZOrder:i.any}],p=[{name:"overlay-padding",type:a.size,triggersBounds:i.any},{name:"overlay-color",type:a.color},{name:"overlay-opacity",type:a.zeroOneNumber,triggersBounds:i.zeroNonZero},{name:"overlay-shape",type:a.overlayShape,triggersBounds:i.any},{name:"overlay-corner-radius",type:a.cornerRadius}],f=[{name:"underlay-padding",type:a.size,triggersBounds:i.any},{name:"underlay-color",type:a.color},{name:"underlay-opacity",type:a.zeroOneNumber,triggersBounds:i.zeroNonZero},{name:"underlay-shape",type:a.overlayShape,triggersBounds:i.any},{name:"underlay-corner-radius",type:a.cornerRadius}],g=[{name:"transition-property",type:a.propList},{name:"transition-duration",type:a.time},{name:"transition-delay",type:a.time},{name:"transition-timing-function",type:a.easing}],y=function(e,t){return"label"===t.value?-e.poolIndex():t.pfValue},m=[{name:"height",type:a.nodeSize,triggersBounds:i.any,hashOverride:y},{name:"width",type:a.nodeSize,triggersBounds:i.any,hashOverride:y},{name:"shape",type:a.nodeShape,triggersBounds:i.any},{name:"shape-polygon-points",type:a.polygonPointList,triggersBounds:i.any},{name:"corner-radius",type:a.cornerRadius},{name:"background-color",type:a.color},{name:"background-fill",type:a.fill},{name:"background-opacity",type:a.zeroOneNumber},{name:"background-blacken",type:a.nOneOneNumber},{name:"background-gradient-stop-colors",type:a.colors},{name:"background-gradient-stop-positions",type:a.percentages},{name:"background-gradient-direction",type:a.gradientDirection},{name:"padding",type:a.sizeMaybePercent,triggersBounds:i.any},{name:"padding-relative-to",type:a.paddingRelativeTo,triggersBounds:i.any},{name:"bounds-expansion",type:a.boundsExpansion,triggersBounds:i.any}],b=[{name:"border-color",type:a.color},{name:"border-opacity",type:a.zeroOneNumber},{name:"border-width",type:a.size,triggersBounds:i.any},{name:"border-style",type:a.borderStyle},{name:"border-cap",type:a.lineCap},{name:"border-join",type:a.lineJoin},{name:"border-dash-pattern",type:a.numbers},{name:"border-dash-offset",type:a.number},{name:"border-position",type:a.linePosition}],x=[{name:"outline-color",type:a.color},{name:"outline-opacity",type:a.zeroOneNumber},{name:"outline-width",type:a.size,triggersBounds:i.any},{name:"outline-style",type:a.borderStyle},{name:"outline-offset",type:a.size,triggersBounds:i.any}],w=[{name:"background-image",type:a.urls},{name:"background-image-crossorigin",type:a.bgCrossOrigin},{name:"background-image-opacity",type:a.zeroOneNumbers},{name:"background-image-containment",type:a.bgContainment},{name:"background-image-smoothing",type:a.bools},{name:"background-position-x",type:a.bgPos},{name:"background-position-y",type:a.bgPos},{name:"background-width-relative-to",type:a.bgRelativeTo},{name:"background-height-relative-to",type:a.bgRelativeTo},{name:"background-repeat",type:a.bgRepeat},{name:"background-fit",type:a.bgFit},{name:"background-clip",type:a.bgClip},{name:"background-width",type:a.bgWH},{name:"background-height",type:a.bgWH},{name:"background-offset-x",type:a.bgPos},{name:"background-offset-y",type:a.bgPos}],E=[{name:"position",type:a.position,triggersBounds:i.any},{name:"compound-sizing-wrt-labels",type:a.compoundIncludeLabels,triggersBounds:i.any},{name:"min-width",type:a.size,triggersBounds:i.any},{name:"min-width-bias-left",type:a.sizeMaybePercent,triggersBounds:i.any},{name:"min-width-bias-right",type:a.sizeMaybePercent,triggersBounds:i.any},{name:"min-height",type:a.size,triggersBounds:i.any},{name:"min-height-bias-top",type:a.sizeMaybePercent,triggersBounds:i.any},{name:"min-height-bias-bottom",type:a.sizeMaybePercent,triggersBounds:i.any}],k=[{name:"line-style",type:a.lineStyle},{name:"line-color",type:a.color},{name:"line-fill",type:a.fill},{name:"line-cap",type:a.lineCap},{name:"line-opacity",type:a.zeroOneNumber},{name:"line-dash-pattern",type:a.numbers},{name:"line-dash-offset",type:a.number},{name:"line-outline-width",type:a.size},{name:"line-outline-color",type:a.color},{name:"line-gradient-stop-colors",type:a.colors},{name:"line-gradient-stop-positions",type:a.percentages},{name:"curve-style",type:a.curveStyle,triggersBounds:i.any,triggersBoundsOfParallelBeziers:!0},{name:"haystack-radius",type:a.zeroOneNumber,triggersBounds:i.any},{name:"source-endpoint",type:a.edgeEndpoint,triggersBounds:i.any},{name:"target-endpoint",type:a.edgeEndpoint,triggersBounds:i.any},{name:"control-point-step-size",type:a.size,triggersBounds:i.any},{name:"control-point-distances",type:a.bidirectionalSizes,triggersBounds:i.any},{name:"control-point-weights",type:a.numbers,triggersBounds:i.any},{name:"segment-distances",type:a.bidirectionalSizes,triggersBounds:i.any},{name:"segment-weights",type:a.numbers,triggersBounds:i.any},{name:"segment-radii",type:a.numbers,triggersBounds:i.any},{name:"radius-type",type:a.radiusType,triggersBounds:i.any},{name:"taxi-turn",type:a.bidirectionalSizeMaybePercent,triggersBounds:i.any},{name:"taxi-turn-min-distance",type:a.size,triggersBounds:i.any},{name:"taxi-direction",type:a.axisDirection,triggersBounds:i.any},{name:"taxi-radius",type:a.number,triggersBounds:i.any},{name:"edge-distances",type:a.edgeDistances,triggersBounds:i.any},{name:"arrow-scale",type:a.positiveNumber,triggersBounds:i.any},{name:"loop-direction",type:a.angle,triggersBounds:i.any},{name:"loop-sweep",type:a.angle,triggersBounds:i.any},{name:"source-distance-from-node",type:a.size,triggersBounds:i.any},{name:"target-distance-from-node",type:a.size,triggersBounds:i.any}],C=[{name:"ghost",type:a.bool,triggersBounds:i.any},{name:"ghost-offset-x",type:a.bidirectionalSize,triggersBounds:i.any},{name:"ghost-offset-y",type:a.bidirectionalSize,triggersBounds:i.any},{name:"ghost-opacity",type:a.zeroOneNumber}],S=[{name:"selection-box-color",type:a.color},{name:"selection-box-opacity",type:a.zeroOneNumber},{name:"selection-box-border-color",type:a.color},{name:"selection-box-border-width",type:a.size},{name:"active-bg-color",type:a.color},{name:"active-bg-opacity",type:a.zeroOneNumber},{name:"active-bg-size",type:a.size},{name:"outside-texture-bg-color",type:a.color},{name:"outside-texture-bg-opacity",type:a.zeroOneNumber}],P=[];Ms.pieBackgroundN=16,P.push({name:"pie-size",type:a.sizeMaybePercent});for(var T=1;T<=Ms.pieBackgroundN;T++)P.push({name:"pie-"+T+"-background-color",type:a.color}),P.push({name:"pie-"+T+"-background-size",type:a.percent}),P.push({name:"pie-"+T+"-background-opacity",type:a.zeroOneNumber});var _=[],M=Ms.arrowPrefixes=["source","mid-source","target","mid-target"];[{name:"arrow-shape",type:a.arrowShape,triggersBounds:i.any},{name:"arrow-color",type:a.color},{name:"arrow-fill",type:a.arrowFill},{name:"arrow-width",type:a.arrowWidth}].forEach((function(e){M.forEach((function(t){var n=t+"-"+e.name,r=e.type,i=e.triggersBounds;_.push({name:n,type:r,triggersBounds:i})}))}),{});var B=Ms.properties=[].concat(d,g,h,p,f,C,c,u,o,s,l,m,b,x,w,P,E,k,_,S),N=Ms.propertyGroups={behavior:d,transition:g,visibility:h,overlay:p,underlay:f,ghost:C,commonLabel:c,labelDimensions:u,mainLabel:o,sourceLabel:s,targetLabel:l,nodeBody:m,nodeBorder:b,nodeOutline:x,backgroundImage:w,pie:P,compound:E,edgeLine:k,edgeArrow:_,core:S},z=Ms.propertyGroupNames={};(Ms.propertyGroupKeys=Object.keys(N)).forEach((function(e){z[e]=N[e].map((function(e){return e.name})),N[e].forEach((function(t){return t.groupKey=e}))}));var A=Ms.aliases=[{name:"content",pointsTo:"label"},{name:"control-point-distance",pointsTo:"control-point-distances"},{name:"control-point-weight",pointsTo:"control-point-weights"},{name:"segment-distance",pointsTo:"segment-distances"},{name:"segment-weight",pointsTo:"segment-weights"},{name:"segment-radius",pointsTo:"segment-radii"},{name:"edge-text-rotation",pointsTo:"text-rotation"},{name:"padding-left",pointsTo:"padding"},{name:"padding-right",pointsTo:"padding"},{name:"padding-top",pointsTo:"padding"},{name:"padding-bottom",pointsTo:"padding"}];Ms.propertyNames=B.map((function(e){return e.name}));for(var L=0;L<B.length;L++){var O=B[L];B[O.name]=O}for(var R=0;R<A.length;R++){var V=A[R],F=B[V.pointsTo],j={name:V.name,alias:!0,pointsTo:F};B.push(j),B[V.name]=j}}(),Ms.getDefaultProperty=function(e){return this.getDefaultProperties()[e]},Ms.getDefaultProperties=function(){var e=this._private;if(null!=e.defaultProperties)return e.defaultProperties;for(var t=L({"selection-box-color":"#ddd","selection-box-opacity":.65,"selection-box-border-color":"#aaa","selection-box-border-width":1,"active-bg-color":"black","active-bg-opacity":.15,"active-bg-size":30,"outside-texture-bg-color":"#000","outside-texture-bg-opacity":.125,events:"yes","text-events":"no","text-valign":"top","text-halign":"center","text-justification":"auto","line-height":1,color:"#000","text-outline-color":"#000","text-outline-width":0,"text-outline-opacity":1,"text-opacity":1,"text-decoration":"none","text-transform":"none","text-wrap":"none","text-overflow-wrap":"whitespace","text-max-width":9999,"text-background-color":"#000","text-background-opacity":0,"text-background-shape":"rectangle","text-background-padding":0,"text-border-opacity":0,"text-border-width":0,"text-border-style":"solid","text-border-color":"#000","font-family":"Helvetica Neue, Helvetica, sans-serif","font-style":"normal","font-weight":"normal","font-size":16,"min-zoomed-font-size":0,"text-rotation":"none","source-text-rotation":"none","target-text-rotation":"none",visibility:"visible",display:"element",opacity:1,"z-compound-depth":"auto","z-index-compare":"auto","z-index":0,label:"","text-margin-x":0,"text-margin-y":0,"source-label":"","source-text-offset":0,"source-text-margin-x":0,"source-text-margin-y":0,"target-label":"","target-text-offset":0,"target-text-margin-x":0,"target-text-margin-y":0,"overlay-opacity":0,"overlay-color":"#000","overlay-padding":10,"overlay-shape":"round-rectangle","overlay-corner-radius":"auto","underlay-opacity":0,"underlay-color":"#000","underlay-padding":10,"underlay-shape":"round-rectangle","underlay-corner-radius":"auto","transition-property":"none","transition-duration":0,"transition-delay":0,"transition-timing-function":"linear","background-blacken":0,"background-color":"#999","background-fill":"solid","background-opacity":1,"background-image":"none","background-image-crossorigin":"anonymous","background-image-opacity":1,"background-image-containment":"inside","background-image-smoothing":"yes","background-position-x":"50%","background-position-y":"50%","background-offset-x":0,"background-offset-y":0,"background-width-relative-to":"include-padding","background-height-relative-to":"include-padding","background-repeat":"no-repeat","background-fit":"none","background-clip":"node","background-width":"auto","background-height":"auto","border-color":"#000","border-opacity":1,"border-width":0,"border-style":"solid","border-dash-pattern":[4,2],"border-dash-offset":0,"border-cap":"butt","border-join":"miter","border-position":"center","outline-color":"#999","outline-opacity":1,"outline-width":0,"outline-offset":0,"outline-style":"solid",height:30,width:30,shape:"ellipse","shape-polygon-points":"-1, -1, 1, -1, 1, 1, -1, 1","corner-radius":"auto","bounds-expansion":0,"background-gradient-direction":"to-bottom","background-gradient-stop-colors":"#999","background-gradient-stop-positions":"0%",ghost:"no","ghost-offset-y":0,"ghost-offset-x":0,"ghost-opacity":0,padding:0,"padding-relative-to":"width",position:"origin","compound-sizing-wrt-labels":"include","min-width":0,"min-width-bias-left":0,"min-width-bias-right":0,"min-height":0,"min-height-bias-top":0,"min-height-bias-bottom":0},{"pie-size":"100%"},[{name:"pie-{{i}}-background-color",value:"black"},{name:"pie-{{i}}-background-size",value:"0%"},{name:"pie-{{i}}-background-opacity",value:1}].reduce((function(e,t){for(var n=1;n<=Ms.pieBackgroundN;n++){var r=t.name.replace("{{i}}",n),i=t.value;e[r]=i}return e}),{}),{"line-style":"solid","line-color":"#999","line-fill":"solid","line-cap":"butt","line-opacity":1,"line-outline-width":0,"line-outline-color":"#000","line-gradient-stop-colors":"#999","line-gradient-stop-positions":"0%","control-point-step-size":40,"control-point-weights":.5,"segment-weights":.5,"segment-distances":20,"segment-radii":15,"radius-type":"arc-radius","taxi-turn":"50%","taxi-radius":15,"taxi-turn-min-distance":10,"taxi-direction":"auto","edge-distances":"intersection","curve-style":"haystack","haystack-radius":0,"arrow-scale":1,"loop-direction":"-45deg","loop-sweep":"-90deg","source-distance-from-node":0,"target-distance-from-node":0,"source-endpoint":"outside-to-node","target-endpoint":"outside-to-node","line-dash-pattern":[6,3],"line-dash-offset":0},[{name:"arrow-shape",value:"none"},{name:"arrow-color",value:"#999"},{name:"arrow-fill",value:"filled"},{name:"arrow-width",value:1}].reduce((function(e,t){return Ms.arrowPrefixes.forEach((function(n){var r=n+"-"+t.name,i=t.value;e[r]=i})),e}),{})),n={},r=0;r<this.properties.length;r++){var i=this.properties[r];if(!i.pointsTo){var a=i.name,o=t[a],s=this.parse(a,o);n[a]=s}}return e.defaultProperties=n,e.defaultProperties},Ms.addDefaultStylesheet=function(){this.selector(":parent").css({shape:"rectangle",padding:10,"background-color":"#eee","border-color":"#ccc","border-width":1}).selector("edge").css({width:3}).selector(":loop").css({"curve-style":"bezier"}).selector("edge:compound").css({"curve-style":"bezier","source-endpoint":"outside-to-line","target-endpoint":"outside-to-line"}).selector(":selected").css({"background-color":"#0169D9","line-color":"#0169D9","source-arrow-color":"#0169D9","target-arrow-color":"#0169D9","mid-source-arrow-color":"#0169D9","mid-target-arrow-color":"#0169D9"}).selector(":parent:selected").css({"background-color":"#CCE1F9","border-color":"#aec8e5"}).selector(":active").css({"overlay-color":"black","overlay-padding":10,"overlay-opacity":.25}),this.defaultLength=this.length};var Bs={parse:function(e,t,n,r){if(y(t))return this.parseImplWarn(e,t,n,r);var i,a=_e(e,""+t,n?"t":"f","mapping"===r||!0===r||!1===r||null==r?"dontcare":r),o=this.propCache=this.propCache||[];return(i=o[a])||(i=o[a]=this.parseImplWarn(e,t,n,r)),(n||"mapping"===r)&&(i=qe(i))&&(i.value=qe(i.value)),i},parseImplWarn:function(e,t,n,r){var i=this.parseImpl(e,t,n,r);return i||null==t||je("The style property `".concat(e,": ").concat(t,"` is invalid")),!i||"width"!==i.name&&"height"!==i.name||"label"!==t||je("The style value of `label` is deprecated for `"+i.name+"`"),i}};Bs.parseImpl=function(e,t,n,r){e=M(e);var i=this.properties[e],a=t,o=this.types;if(!i)return null;if(void 0===t)return null;i.alias&&(i=i.pointsTo,e=i.name);var s=v(t);s&&(t=t.trim());var l,u,c=i.type;if(!c)return null;if(n&&(""===t||null===t))return{name:e,value:t,bypass:!0,deleteBypass:!0};if(y(t))return{name:e,value:t,strValue:"fn",mapped:o.fn,bypass:n};if(!s||r||t.length<7||"a"!==t[1]);else{if(t.length>=7&&"d"===t[0]&&(l=new RegExp(o.data.regex).exec(t))){if(n)return!1;var d=o.data;return{name:e,value:l,strValue:""+t,mapped:d,field:l[1],bypass:n}}if(t.length>=10&&"m"===t[0]&&(u=new RegExp(o.mapData.regex).exec(t))){if(n)return!1;if(c.multiple)return!1;var h=o.mapData;if(!c.color&&!c.number)return!1;var p=this.parse(e,u[4]);if(!p||p.mapped)return!1;var f=this.parse(e,u[5]);if(!f||f.mapped)return!1;if(p.pfValue===f.pfValue||p.strValue===f.strValue)return je("`"+e+": "+t+"` is not a valid mapper because the output range is zero; converting to `"+e+": "+p.strValue+"`"),this.parse(e,p.strValue);if(c.color){var g=p.value,b=f.value;if(!(g[0]!==b[0]||g[1]!==b[1]||g[2]!==b[2]||g[3]!==b[3]&&(null!=g[3]&&1!==g[3]||null!=b[3]&&1!==b[3])))return!1}return{name:e,value:u,strValue:""+t,mapped:h,field:u[1],fieldMin:parseFloat(u[2]),fieldMax:parseFloat(u[3]),valueMin:p.value,valueMax:f.value,bypass:n}}}if(c.multiple&&"multiple"!==r){var w;if(w=s?t.split(/\s+/):m(t)?t:[t],c.evenMultiple&&w.length%2!=0)return null;for(var E=[],k=[],C=[],S="",P=!1,D=0;D<w.length;D++){var T=this.parse(e,w[D],n,"multiple");P=P||v(T.value),E.push(T.value),C.push(null!=T.pfValue?T.pfValue:T.value),k.push(T.units),S+=(D>0?" ":"")+T.strValue}return c.validate&&!c.validate(E,k)?null:c.singleEnum&&P?1===E.length&&v(E[0])?{name:e,value:E[0],strValue:E[0],bypass:n}:null:{name:e,value:E,pfValue:C,strValue:S,bypass:n,units:k}}var _,B,N=function(){for(var r=0;r<c.enums.length;r++){if(c.enums[r]===t)return{name:e,value:t,strValue:""+t,bypass:n}}return null};if(c.number){var z,A="px";if(c.units&&(z=c.units),c.implicitUnits&&(A=c.implicitUnits),!c.unitless)if(s){var L="px|em"+(c.allowPercent?"|\\%":"");z&&(L=z);var R=t.match("^("+I+")("+L+")?$");R&&(t=R[1],z=R[2]||A)}else z&&!c.implicitUnits||(z=A);if(t=parseFloat(t),isNaN(t)&&void 0===c.enums)return null;if(isNaN(t)&&void 0!==c.enums)return t=a,N();if(c.integer&&(!x(B=t)||Math.floor(B)!==B))return null;if(void 0!==c.min&&(t<c.min||c.strictMin&&t===c.min)||void 0!==c.max&&(t>c.max||c.strictMax&&t===c.max))return null;var V={name:e,value:t,strValue:""+t+(z||""),units:z,bypass:n};return c.unitless||"px"!==z&&"em"!==z?V.pfValue=t:V.pfValue="px"!==z&&z?this.getEmSizeInPixels()*t:t,"ms"!==z&&"s"!==z||(V.pfValue="ms"===z?t:1e3*t),"deg"!==z&&"rad"!==z||(V.pfValue="rad"===z?t:(_=t,Math.PI*_/180)),"%"===z&&(V.pfValue=t/100),V}if(c.propList){var F=[],j=""+t;if("none"===j);else{for(var q=j.split(/\s*,\s*|\s+/),Y=0;Y<q.length;Y++){var X=q[Y].trim();this.properties[X]?F.push(X):je("`"+X+"` is not a valid property name")}if(0===F.length)return null}return{name:e,value:F,strValue:0===F.length?"none":F.join(" "),bypass:n}}if(c.color){var W=O(t);return W?{name:e,value:W,pfValue:W,strValue:"rgb("+W[0]+","+W[1]+","+W[2]+")",bypass:n}:null}if(c.regex||c.regexes){if(c.enums){var H=N();if(H)return H}for(var K=c.regexes?c.regexes:[c.regex],G=0;G<K.length;G++){var U=new RegExp(K[G]).exec(t);if(U)return{name:e,value:c.singleRegexMatchValue?U[1]:U,strValue:""+t,bypass:n}}return null}return c.string?{name:e,value:""+t,strValue:""+t,bypass:n}:c.enums?N():null};var Ns=function e(t){if(!(this instanceof e))return new e(t);S(t)?(this._private={cy:t,coreStyle:{}},this.length=0,this.resetToDefault()):Ve("A style must have a core reference")},zs=Ns.prototype;zs.instanceString=function(){return"style"},zs.clear=function(){for(var e=this._private,t=e.cy.elements(),n=0;n<this.length;n++)this[n]=void 0;return this.length=0,e.contextStyles={},e.propDiffs={},this.cleanElements(t,!0),t.forEach((function(e){var t=e[0]._private;t.styleDirty=!0,t.appliedInitStyle=!1})),this},zs.resetToDefault=function(){return this.clear(),this.addDefaultStylesheet(),this},zs.core=function(e){return this._private.coreStyle[e]||this.getDefaultProperty(e)},zs.selector=function(e){var t="core"===e?null:new ka(e),n=this.length++;return this[n]={selector:t,properties:[],mappedProperties:[],index:n},this},zs.css=function(){var e=this,t=arguments;if(1===t.length)for(var n=t[0],r=0;r<e.properties.length;r++){var i=e.properties[r],a=n[i.name];void 0===a&&(a=n[B(i.name)]),void 0!==a&&this.cssRule(i.name,a)}else 2===t.length&&this.cssRule(t[0],t[1]);return this},zs.style=zs.css,zs.cssRule=function(e,t){var n=this.parse(e,t);if(n){var r=this.length-1;this[r].properties.push(n),this[r].properties[n.name]=n,n.name.match(/pie-(\d+)-background-size/)&&n.value&&(this._private.hasPie=!0),n.mapped&&this[r].mappedProperties.push(n),!this[r].selector&&(this._private.coreStyle[n.name]=n)}return this},zs.append=function(e){return P(e)?e.appendToStyle(this):m(e)?this.appendFromJson(e):v(e)&&this.appendFromString(e),this},Ns.fromJson=function(e,t){var n=new Ns(e);return n.fromJson(t),n},Ns.fromString=function(e,t){return new Ns(e).fromString(t)},[Cs,Ss,Ps,Ds,Ts,_s,Ms,Bs].forEach((function(e){L(zs,e)})),Ns.types=zs.types,Ns.properties=zs.properties,Ns.propertyGroups=zs.propertyGroups,Ns.propertyGroupNames=zs.propertyGroupNames,Ns.propertyGroupKeys=zs.propertyGroupKeys;var Is={style:function(e){e&&this.setStyle(e).update();return this._private.style},setStyle:function(e){var t=this._private;return P(e)?t.style=e.generateStyle(this):m(e)?t.style=Ns.fromJson(this,e):v(e)?t.style=Ns.fromString(this,e):t.style=Ns(this),t.style},updateStyle:function(){this.mutableElements().updateStyle()}},As={autolock:function(e){return void 0===e?this._private.autolock:(this._private.autolock=!!e,this)},autoungrabify:function(e){return void 0===e?this._private.autoungrabify:(this._private.autoungrabify=!!e,this)},autounselectify:function(e){return void 0===e?this._private.autounselectify:(this._private.autounselectify=!!e,this)},selectionType:function(e){var t=this._private;return null==t.selectionType&&(t.selectionType="single"),void 0===e?t.selectionType:("additive"!==e&&"single"!==e||(t.selectionType=e),this)},panningEnabled:function(e){return void 0===e?this._private.panningEnabled:(this._private.panningEnabled=!!e,this)},userPanningEnabled:function(e){return void 0===e?this._private.userPanningEnabled:(this._private.userPanningEnabled=!!e,this)},zoomingEnabled:function(e){return void 0===e?this._private.zoomingEnabled:(this._private.zoomingEnabled=!!e,this)},userZoomingEnabled:function(e){return void 0===e?this._private.userZoomingEnabled:(this._private.userZoomingEnabled=!!e,this)},boxSelectionEnabled:function(e){return void 0===e?this._private.boxSelectionEnabled:(this._private.boxSelectionEnabled=!!e,this)},pan:function(){var e,t,n,r,i,a=arguments,o=this._private.pan;switch(a.length){case 0:return o;case 1:if(v(a[0]))return o[e=a[0]];if(b(a[0])){if(!this._private.panningEnabled)return this;r=(n=a[0]).x,i=n.y,x(r)&&(o.x=r),x(i)&&(o.y=i),this.emit("pan viewport")}break;case 2:if(!this._private.panningEnabled)return this;e=a[0],t=a[1],"x"!==e&&"y"!==e||!x(t)||(o[e]=t),this.emit("pan viewport")}return this.notify("viewport"),this},panBy:function(e,t){var n,r,i,a,o,s=arguments,l=this._private.pan;if(!this._private.panningEnabled)return this;switch(s.length){case 1:b(e)&&(a=(i=s[0]).x,o=i.y,x(a)&&(l.x+=a),x(o)&&(l.y+=o),this.emit("pan viewport"));break;case 2:r=t,"x"!==(n=e)&&"y"!==n||!x(r)||(l[n]+=r),this.emit("pan viewport")}return this.notify("viewport"),this},fit:function(e,t){var n=this.getFitViewport(e,t);if(n){var r=this._private;r.zoom=n.zoom,r.pan=n.pan,this.emit("pan zoom viewport"),this.notify("viewport")}return this},getFitViewport:function(e,t){if(x(e)&&void 0===t&&(t=e,e=void 0),this._private.panningEnabled&&this._private.zoomingEnabled){var n,r;if(v(e)){var i=e;e=this.$(i)}else if(b(r=e)&&x(r.x1)&&x(r.x2)&&x(r.y1)&&x(r.y2)){var a=e;(n={x1:a.x1,y1:a.y1,x2:a.x2,y2:a.y2}).w=n.x2-n.x1,n.h=n.y2-n.y1}else E(e)||(e=this.mutableElements());if(!E(e)||!e.empty()){n=n||e.boundingBox();var o,s=this.width(),l=this.height();if(t=x(t)?t:0,!isNaN(s)&&!isNaN(l)&&s>0&&l>0&&!isNaN(n.w)&&!isNaN(n.h)&&n.w>0&&n.h>0)return{zoom:o=(o=(o=Math.min((s-2*t)/n.w,(l-2*t)/n.h))>this._private.maxZoom?this._private.maxZoom:o)<this._private.minZoom?this._private.minZoom:o,pan:{x:(s-o*(n.x1+n.x2))/2,y:(l-o*(n.y1+n.y2))/2}}}}},zoomRange:function(e,t){var n=this._private;if(null==t){var r=e;e=r.min,t=r.max}return x(e)&&x(t)&&e<=t?(n.minZoom=e,n.maxZoom=t):x(e)&&void 0===t&&e<=n.maxZoom?n.minZoom=e:x(t)&&void 0===e&&t>=n.minZoom&&(n.maxZoom=t),this},minZoom:function(e){return void 0===e?this._private.minZoom:this.zoomRange({min:e})},maxZoom:function(e){return void 0===e?this._private.maxZoom:this.zoomRange({max:e})},getZoomedViewport:function(e){var t,n,r=this._private,i=r.pan,a=r.zoom,o=!1;if(r.zoomingEnabled||(o=!0),x(e)?n=e:b(e)&&(n=e.level,null!=e.position?t=yt(e.position,a,i):null!=e.renderedPosition&&(t=e.renderedPosition),null==t||r.panningEnabled||(o=!0)),n=(n=n>r.maxZoom?r.maxZoom:n)<r.minZoom?r.minZoom:n,o||!x(n)||n===a||null!=t&&(!x(t.x)||!x(t.y)))return null;if(null!=t){var s=i,l=a,u=n;return{zoomed:!0,panned:!0,zoom:u,pan:{x:-u/l*(t.x-s.x)+t.x,y:-u/l*(t.y-s.y)+t.y}}}return{zoomed:!0,panned:!1,zoom:n,pan:i}},zoom:function(e){if(void 0===e)return this._private.zoom;var t=this.getZoomedViewport(e),n=this._private;return null!=t&&t.zoomed?(n.zoom=t.zoom,t.panned&&(n.pan.x=t.pan.x,n.pan.y=t.pan.y),this.emit("zoom"+(t.panned?" pan":"")+" viewport"),this.notify("viewport"),this):this},viewport:function(e){var t=this._private,n=!0,r=!0,i=[],a=!1,o=!1;if(!e)return this;if(x(e.zoom)||(n=!1),b(e.pan)||(r=!1),!n&&!r)return this;if(n){var s=e.zoom;s<t.minZoom||s>t.maxZoom||!t.zoomingEnabled?a=!0:(t.zoom=s,i.push("zoom"))}if(r&&(!a||!e.cancelOnFailedZoom)&&t.panningEnabled){var l=e.pan;x(l.x)&&(t.pan.x=l.x,o=!1),x(l.y)&&(t.pan.y=l.y,o=!1),o||i.push("pan")}return i.length>0&&(i.push("viewport"),this.emit(i.join(" ")),this.notify("viewport")),this},center:function(e){var t=this.getCenterPan(e);return t&&(this._private.pan=t,this.emit("pan viewport"),this.notify("viewport")),this},getCenterPan:function(e,t){if(this._private.panningEnabled){if(v(e)){var n=e;e=this.mutableElements().filter(n)}else E(e)||(e=this.mutableElements());if(0!==e.length){var r=e.boundingBox(),i=this.width(),a=this.height();return{x:(i-(t=void 0===t?this._private.zoom:t)*(r.x1+r.x2))/2,y:(a-t*(r.y1+r.y2))/2}}}},reset:function(){return this._private.panningEnabled&&this._private.zoomingEnabled?(this.viewport({pan:{x:0,y:0},zoom:1}),this):this},invalidateSize:function(){this._private.sizeCache=null},size:function(){var e,t,n=this._private,r=n.container,i=this;return n.sizeCache=n.sizeCache||(r?(e=i.window().getComputedStyle(r),t=function(t){return parseFloat(e.getPropertyValue(t))},{width:r.clientWidth-t("padding-left")-t("padding-right"),height:r.clientHeight-t("padding-top")-t("padding-bottom")}):{width:1,height:1})},width:function(){return this.size().width},height:function(){return this.size().height},extent:function(){var e=this._private.pan,t=this._private.zoom,n=this.renderedExtent(),r={x1:(n.x1-e.x)/t,x2:(n.x2-e.x)/t,y1:(n.y1-e.y)/t,y2:(n.y2-e.y)/t};return r.w=r.x2-r.x1,r.h=r.y2-r.y1,r},renderedExtent:function(){var e=this.width(),t=this.height();return{x1:0,y1:0,x2:e,y2:t,w:e,h:t}},multiClickDebounceTime:function(e){return e?(this._private.multiClickDebounceTime=e,this):this._private.multiClickDebounceTime}};As.centre=As.center,As.autolockNodes=As.autolock,As.autoungrabifyNodes=As.autoungrabify;var Ls={data:Fi.data({field:"data",bindingEvent:"data",allowBinding:!0,allowSetting:!0,settingEvent:"data",settingTriggersEvent:!0,triggerFnName:"trigger",allowGetting:!0,updateStyle:!0}),removeData:Fi.removeData({field:"data",event:"data",triggerFnName:"trigger",triggerEvent:!0,updateStyle:!0}),scratch:Fi.data({field:"scratch",bindingEvent:"scratch",allowBinding:!0,allowSetting:!0,settingEvent:"scratch",settingTriggersEvent:!0,triggerFnName:"trigger",allowGetting:!0,updateStyle:!0}),removeScratch:Fi.removeData({field:"scratch",event:"scratch",triggerFnName:"trigger",triggerEvent:!0,updateStyle:!0})};Ls.attr=Ls.data,Ls.removeAttr=Ls.removeData;var Os=function(e){var t=this,n=(e=L({},e)).container;n&&!w(n)&&w(n[0])&&(n=n[0]);var r=n?n._cyreg:null;(r=r||{})&&r.cy&&(r.cy.destroy(),r={});var i=r.readies=r.readies||[];n&&(n._cyreg=r),r.cy=t;var a=void 0!==u&&void 0!==n&&!e.headless,o=e;o.layout=L({name:a?"grid":"null"},o.layout),o.renderer=L({name:a?"canvas":"null"},o.renderer);var s=function(e,t,n){return void 0!==t?t:void 0!==n?n:e},l=this._private={container:n,ready:!1,options:o,elements:new ts(this),listeners:[],aniEles:new ts(this),data:o.data||{},scratch:{},layout:null,renderer:null,destroyed:!1,notificationsEnabled:!0,minZoom:1e-50,maxZoom:1e50,zoomingEnabled:s(!0,o.zoomingEnabled),userZoomingEnabled:s(!0,o.userZoomingEnabled),panningEnabled:s(!0,o.panningEnabled),userPanningEnabled:s(!0,o.userPanningEnabled),boxSelectionEnabled:s(!0,o.boxSelectionEnabled),autolock:s(!1,o.autolock,o.autolockNodes),autoungrabify:s(!1,o.autoungrabify,o.autoungrabifyNodes),autounselectify:s(!1,o.autounselectify),styleEnabled:void 0===o.styleEnabled?a:o.styleEnabled,zoom:x(o.zoom)?o.zoom:1,pan:{x:b(o.pan)&&x(o.pan.x)?o.pan.x:0,y:b(o.pan)&&x(o.pan.y)?o.pan.y:0},animation:{current:[],queue:[]},hasCompoundNodes:!1,multiClickDebounceTime:s(250,o.multiClickDebounceTime)};this.createEmitter(),this.selectionType(o.selectionType),this.zoomRange({min:o.minZoom,max:o.maxZoom});l.styleEnabled&&t.setStyle([]);var c=L({},o,o.renderer);t.initRenderer(c);!function(e,t){if(e.some(T))return vr.all(e).then(t);t(e)}([o.style,o.elements],(function(e){var n=e[0],a=e[1];l.styleEnabled&&t.style().append(n),function(e,n,r){t.notifications(!1);var i=t.mutableElements();i.length>0&&i.remove(),null!=e&&(b(e)||m(e))&&t.add(e),t.one("layoutready",(function(e){t.notifications(!0),t.emit(e),t.one("load",n),t.emitAndNotify("load")})).one("layoutstop",(function(){t.one("done",r),t.emit("done")}));var a=L({},t._private.options.layout);a.eles=t.elements(),t.layout(a).run()}(a,(function(){t.startAnimationLoop(),l.ready=!0,y(o.ready)&&t.on("ready",o.ready);for(var e=0;e<i.length;e++){var n=i[e];t.on("ready",n)}r&&(r.readies=[]),t.emit("ready")}),o.done)}))},Rs=Os.prototype;L(Rs,{instanceString:function(){return"core"},isReady:function(){return this._private.ready},destroyed:function(){return this._private.destroyed},ready:function(e){return this.isReady()?this.emitter().emit("ready",[],e):this.on("ready",e),this},destroy:function(){var e=this;if(!e.destroyed())return e.stopAnimationLoop(),e.destroyRenderer(),this.emit("destroy"),e._private.destroyed=!0,e},hasElementWithId:function(e){return this._private.elements.hasElementWithId(e)},getElementById:function(e){return this._private.elements.getElementById(e)},hasCompoundNodes:function(){return this._private.hasCompoundNodes},headless:function(){return this._private.renderer.isHeadless()},styleEnabled:function(){return this._private.styleEnabled},addToPool:function(e){return this._private.elements.merge(e),this},removeFromPool:function(e){return this._private.elements.unmerge(e),this},container:function(){return this._private.container||null},window:function(){if(null==this._private.container)return u;var e=this._private.container.ownerDocument;return void 0===e||null==e?u:e.defaultView||u},mount:function(e){if(null!=e){var t=this,n=t._private,r=n.options;return!w(e)&&w(e[0])&&(e=e[0]),t.stopAnimationLoop(),t.destroyRenderer(),n.container=e,n.styleEnabled=!0,t.invalidateSize(),t.initRenderer(L({},r,r.renderer,{name:"null"===r.renderer.name?"canvas":r.renderer.name})),t.startAnimationLoop(),t.style(r.style),t.emit("mount"),t}},unmount:function(){var e=this;return e.stopAnimationLoop(),e.destroyRenderer(),e.initRenderer({name:"null"}),e.emit("unmount"),e},options:function(){return qe(this._private.options)},json:function(e){var t=this,n=t._private,r=t.mutableElements();if(b(e)){if(t.startBatch(),e.elements){var i={},a=function(e,n){for(var r=[],a=[],o=0;o<e.length;o++){var s=e[o];if(s.data.id){var l=""+s.data.id,u=t.getElementById(l);i[l]=!0,0!==u.length?a.push({ele:u,json:s}):n?(s.group=n,r.push(s)):r.push(s)}else je("cy.json() cannot handle elements without an ID attribute")}t.add(r);for(var c=0;c<a.length;c++){var d=a[c],h=d.ele,p=d.json;h.json(p)}};if(m(e.elements))a(e.elements);else for(var o=["nodes","edges"],s=0;s<o.length;s++){var l=o[s],u=e.elements[l];m(u)&&a(u,l)}var c=t.collection();r.filter((function(e){return!i[e.id()]})).forEach((function(e){e.isParent()?c.merge(e):e.remove()})),c.forEach((function(e){return e.children().move({parent:null})})),c.forEach((function(e){return function(e){return t.getElementById(e.id())}(e).remove()}))}e.style&&t.style(e.style),null!=e.zoom&&e.zoom!==n.zoom&&t.zoom(e.zoom),e.pan&&(e.pan.x===n.pan.x&&e.pan.y===n.pan.y||t.pan(e.pan)),e.data&&t.data(e.data);for(var d=["minZoom","maxZoom","zoomingEnabled","userZoomingEnabled","panningEnabled","userPanningEnabled","boxSelectionEnabled","autolock","autoungrabify","autounselectify","multiClickDebounceTime"],h=0;h<d.length;h++){var p=d[h];null!=e[p]&&t[p](e[p])}return t.endBatch(),this}var f={};!!e?f.elements=this.elements().map((function(e){return e.json()})):(f.elements={},r.forEach((function(e){var t=e.group();f.elements[t]||(f.elements[t]=[]),f.elements[t].push(e.json())}))),this._private.styleEnabled&&(f.style=t.style().json()),f.data=qe(t.data());var g=n.options;return f.zoomingEnabled=n.zoomingEnabled,f.userZoomingEnabled=n.userZoomingEnabled,f.zoom=n.zoom,f.minZoom=n.minZoom,f.maxZoom=n.maxZoom,f.panningEnabled=n.panningEnabled,f.userPanningEnabled=n.userPanningEnabled,f.pan=qe(n.pan),f.boxSelectionEnabled=n.boxSelectionEnabled,f.renderer=qe(g.renderer),f.hideEdgesOnViewport=g.hideEdgesOnViewport,f.textureOnViewport=g.textureOnViewport,f.wheelSensitivity=g.wheelSensitivity,f.motionBlur=g.motionBlur,f.multiClickDebounceTime=g.multiClickDebounceTime,f}}),Rs.$id=Rs.getElementById,[rs,fs,ys,ms,bs,xs,Es,ks,Is,As,Ls].forEach((function(e){L(Rs,e)}));var Vs={fit:!0,directed:!1,padding:30,circle:!1,grid:!1,spacingFactor:1.75,boundingBox:void 0,avoidOverlap:!0,nodeDimensionsIncludeLabels:!1,roots:void 0,depthSort:void 0,animate:!1,animationDuration:500,animationEasing:void 0,animateFilter:function(e,t){return!0},ready:void 0,stop:void 0,transform:function(e,t){return t}},Fs={maximal:!1,acyclic:!1},js=function(e){return e.scratch("breadthfirst")},qs=function(e,t){return e.scratch("breadthfirst",t)};function Ys(e){this.options=L({},Vs,Fs,e)}Ys.prototype.run=function(){var e,t=this.options,n=t,r=t.cy,i=n.eles,a=i.nodes().filter((function(e){return!e.isParent()})),o=i,s=n.directed,l=n.acyclic||n.maximal||n.maximalAdjustments>0,u=_t(n.boundingBox?n.boundingBox:{x1:0,y1:0,w:r.width(),h:r.height()});if(E(n.roots))e=n.roots;else if(m(n.roots)){for(var c=[],d=0;d<n.roots.length;d++){var h=n.roots[d],p=r.getElementById(h);c.push(p)}e=r.collection(c)}else if(v(n.roots))e=r.$(n.roots);else if(s)e=a.roots();else{var f=i.components();e=r.collection();for(var g=function(t){var n=f[t],r=n.maxDegree(!1),i=n.filter((function(e){return e.degree(!1)===r}));e=e.add(i)},y=0;y<f.length;y++)g(y)}var b=[],x={},w=function(e,t){null==b[t]&&(b[t]=[]);var n=b[t].length;b[t].push(e),qs(e,{index:n,depth:t})};o.bfs({roots:e,directed:n.directed,visit:function(e,t,n,r,i){var a=e[0],o=a.id();w(a,i),x[o]=!0}});for(var k=[],C=0;C<a.length;C++){var S=a[C];x[S.id()]||k.push(S)}var P=function(e){for(var t=b[e],n=0;n<t.length;n++){var r=t[n];null!=r?qs(r,{depth:e,index:n}):(t.splice(n,1),n--)}},D=function(){for(var e=0;e<b.length;e++)P(e)},T=function(e,t){for(var r=js(e),a=e.incomers().filter((function(e){return e.isNode()&&i.has(e)})),o=-1,s=e.id(),l=0;l<a.length;l++){var u=a[l],c=js(u);o=Math.max(o,c.depth)}if(r.depth<=o){if(!n.acyclic&&t[s])return null;var d=o+1;return function(e,t){var n=js(e),r=n.depth,i=n.index;b[r][i]=null,w(e,t)}(e,d),t[s]=d,!0}return!1};if(s&&l){var _=[],M={},B=function(e){return _.push(e)};for(a.forEach((function(e){return _.push(e)}));_.length>0;){var N=_.shift(),z=T(N,M);if(z)N.outgoers().filter((function(e){return e.isNode()&&i.has(e)})).forEach(B);else if(null===z){je("Detected double maximal shift for node `"+N.id()+"`. Bailing maximal adjustment due to cycle. Use `options.maximal: true` only on DAGs.");break}}}D();var I=0;if(n.avoidOverlap)for(var L=0;L<a.length;L++){var O=a[L].layoutDimensions(n),R=O.w,V=O.h;I=Math.max(I,R,V)}var F={},j=function(e){if(F[e.id()])return F[e.id()];for(var t=js(e).depth,n=e.neighborhood(),r=0,i=0,o=0;o<n.length;o++){var s=n[o];if(!s.isEdge()&&!s.isParent()&&a.has(s)){var l=js(s);if(null!=l){var u=l.index,c=l.depth;if(null!=u&&null!=c){var d=b[c].length;c<t&&(r+=u/d,i++)}}}}return r/=i=Math.max(1,i),0===i&&(r=0),F[e.id()]=r,r},q=function(e,t){var n=j(e)-j(t);return 0===n?A(e.id(),t.id()):n};void 0!==n.depthSort&&(q=n.depthSort);for(var Y=0;Y<b.length;Y++)b[Y].sort(q),P(Y);for(var X=[],W=0;W<k.length;W++)X.push(k[W]);b.unshift(X),D();for(var H=0,K=0;K<b.length;K++)H=Math.max(b[K].length,H);var G=u.x1+u.w/2,U=u.x1+u.h/2,Z=b.reduce((function(e,t){return Math.max(e,t.length)}),0);return i.nodes().layoutPositions(this,n,(function(e){var t=js(e),r=t.depth,i=t.index,a=b[r].length,o=Math.max(u.w/((n.grid?Z:a)+1),I),s=Math.max(u.h/(b.length+1),I),l=Math.min(u.w/2/b.length,u.h/2/b.length);if(l=Math.max(l,I),n.circle){var c=l*r+l-(b.length>0&&b[0].length<=3?l/2:0),d=2*Math.PI/b[r].length*i;return 0===r&&1===b[0].length&&(c=1),{x:G+c*Math.cos(d),y:U+c*Math.sin(d)}}return{x:G+(i+1-(a+1)/2)*o,y:(r+1)*s}})),this};var Xs={fit:!0,padding:30,boundingBox:void 0,avoidOverlap:!0,nodeDimensionsIncludeLabels:!1,spacingFactor:void 0,radius:void 0,startAngle:1.5*Math.PI,sweep:void 0,clockwise:!0,sort:void 0,animate:!1,animationDuration:500,animationEasing:void 0,animateFilter:function(e,t){return!0},ready:void 0,stop:void 0,transform:function(e,t){return t}};function Ws(e){this.options=L({},Xs,e)}Ws.prototype.run=function(){var e=this.options,t=e,n=e.cy,r=t.eles,i=void 0!==t.counterclockwise?!t.counterclockwise:t.clockwise,a=r.nodes().not(":parent");t.sort&&(a=a.sort(t.sort));for(var o,s=_t(t.boundingBox?t.boundingBox:{x1:0,y1:0,w:n.width(),h:n.height()}),l=s.x1+s.w/2,u=s.y1+s.h/2,c=(void 0===t.sweep?2*Math.PI-2*Math.PI/a.length:t.sweep)/Math.max(1,a.length-1),d=0,h=0;h<a.length;h++){var p=a[h].layoutDimensions(t),f=p.w,g=p.h;d=Math.max(d,f,g)}if(o=x(t.radius)?t.radius:a.length<=1?0:Math.min(s.h,s.w)/2-d,a.length>1&&t.avoidOverlap){d*=1.75;var v=Math.cos(c)-Math.cos(0),y=Math.sin(c)-Math.sin(0),m=Math.sqrt(d*d/(v*v+y*y));o=Math.max(m,o)}return r.nodes().layoutPositions(this,t,(function(e,n){var r=t.startAngle+n*c*(i?1:-1),a=o*Math.cos(r),s=o*Math.sin(r);return{x:l+a,y:u+s}})),this};var Hs,Ks={fit:!0,padding:30,startAngle:1.5*Math.PI,sweep:void 0,clockwise:!0,equidistant:!1,minNodeSpacing:10,boundingBox:void 0,avoidOverlap:!0,nodeDimensionsIncludeLabels:!1,height:void 0,width:void 0,spacingFactor:void 0,concentric:function(e){return e.degree()},levelWidth:function(e){return e.maxDegree()/4},animate:!1,animationDuration:500,animationEasing:void 0,animateFilter:function(e,t){return!0},ready:void 0,stop:void 0,transform:function(e,t){return t}};function Gs(e){this.options=L({},Ks,e)}Gs.prototype.run=function(){for(var e=this.options,t=e,n=void 0!==t.counterclockwise?!t.counterclockwise:t.clockwise,r=e.cy,i=t.eles,a=i.nodes().not(":parent"),o=_t(t.boundingBox?t.boundingBox:{x1:0,y1:0,w:r.width(),h:r.height()}),s=o.x1+o.w/2,l=o.y1+o.h/2,u=[],c=0,d=0;d<a.length;d++){var h,p=a[d];h=t.concentric(p),u.push({value:h,node:p}),p._private.scratch.concentric=h}a.updateStyle();for(var f=0;f<a.length;f++){var g=a[f].layoutDimensions(t);c=Math.max(c,g.w,g.h)}u.sort((function(e,t){return t.value-e.value}));for(var v=t.levelWidth(a),y=[[]],m=y[0],b=0;b<u.length;b++){var x=u[b];if(m.length>0)Math.abs(m[0].value-x.value)>=v&&(m=[],y.push(m));m.push(x)}var w=c+t.minNodeSpacing;if(!t.avoidOverlap){var E=y.length>0&&y[0].length>1,k=(Math.min(o.w,o.h)/2-w)/(y.length+E?1:0);w=Math.min(w,k)}for(var C=0,S=0;S<y.length;S++){var P=y[S],D=void 0===t.sweep?2*Math.PI-2*Math.PI/P.length:t.sweep,T=P.dTheta=D/Math.max(1,P.length-1);if(P.length>1&&t.avoidOverlap){var _=Math.cos(T)-Math.cos(0),M=Math.sin(T)-Math.sin(0),B=Math.sqrt(w*w/(_*_+M*M));C=Math.max(B,C)}P.r=C,C+=w}if(t.equidistant){for(var N=0,z=0,I=0;I<y.length;I++){var A=y[I].r-z;N=Math.max(N,A)}z=0;for(var L=0;L<y.length;L++){var O=y[L];0===L&&(z=O.r),O.r=z,z+=N}}for(var R={},V=0;V<y.length;V++)for(var F=y[V],j=F.dTheta,q=F.r,Y=0;Y<F.length;Y++){var X=F[Y],W=t.startAngle+(n?1:-1)*j*Y,H={x:s+q*Math.cos(W),y:l+q*Math.sin(W)};R[X.node.id()]=H}return i.nodes().layoutPositions(this,t,(function(e){var t=e.id();return R[t]})),this};var Us={ready:function(){},stop:function(){},animate:!0,animationEasing:void 0,animationDuration:void 0,animateFilter:function(e,t){return!0},animationThreshold:250,refresh:20,fit:!0,padding:30,boundingBox:void 0,nodeDimensionsIncludeLabels:!1,randomize:!1,componentSpacing:40,nodeRepulsion:function(e){return 2048},nodeOverlap:4,idealEdgeLength:function(e){return 32},edgeElasticity:function(e){return 32},nestingFactor:1.2,gravity:1,numIter:1e3,initialTemp:1e3,coolingFactor:.99,minTemp:1};function Zs(e){this.options=L({},Us,e),this.options.layout=this;var t=this.options.eles.nodes(),n=this.options.eles.edges().filter((function(e){var n=e.source().data("id"),r=e.target().data("id"),i=t.some((function(e){return e.data("id")===n})),a=t.some((function(e){return e.data("id")===r}));return!i||!a}));this.options.eles=this.options.eles.not(n)}Zs.prototype.run=function(){var e=this.options,t=e.cy,n=this;n.stopped=!1,!0!==e.animate&&!1!==e.animate||n.emit({type:"layoutstart",layout:n}),Hs=!0===e.debug;var r=$s(t,n,e);Hs&&(void 0)(r),e.randomize&&el(r);var i=we(),a=function(){nl(r,t,e),!0===e.fit&&t.fit(e.padding)},o=function(t){return!(n.stopped||t>=e.numIter)&&(rl(r,e),r.temperature=r.temperature*e.coolingFactor,!(r.temperature<e.minTemp))},s=function(){if(!0===e.animate||!1===e.animate)a(),n.one("layoutstop",e.stop),n.emit({type:"layoutstop",layout:n});else{var t=e.eles.nodes(),i=tl(r,e,t);t.layoutPositions(n,e,i)}},l=0,u=!0;if(!0===e.animate){!function t(){for(var n=0;u&&n<e.refresh;)u=o(l),l++,n++;u?(we()-i>=e.animationThreshold&&a(),xe(t)):(gl(r,e),s())}()}else{for(;u;)u=o(l),l++;gl(r,e),s()}return this},Zs.prototype.stop=function(){return this.stopped=!0,this.thread&&this.thread.stop(),this.emit("layoutstop"),this},Zs.prototype.destroy=function(){return this.thread&&this.thread.stop(),this};var $s=function(e,t,n){for(var r=n.eles.edges(),i=n.eles.nodes(),a=_t(n.boundingBox?n.boundingBox:{x1:0,y1:0,w:e.width(),h:e.height()}),o={isCompound:e.hasCompoundNodes(),layoutNodes:[],idToIndex:{},nodeSize:i.size(),graphSet:[],indexToGraph:[],layoutEdges:[],edgeSize:r.size(),temperature:n.initialTemp,clientWidth:a.w,clientHeight:a.h,boundingBox:a},s=n.eles.components(),l={},u=0;u<s.length;u++)for(var c=s[u],d=0;d<c.length;d++){l[c[d].id()]=u}for(u=0;u<o.nodeSize;u++){var h=(m=i[u]).layoutDimensions(n);(I={}).isLocked=m.locked(),I.id=m.data("id"),I.parentId=m.data("parent"),I.cmptId=l[m.id()],I.children=[],I.positionX=m.position("x"),I.positionY=m.position("y"),I.offsetX=0,I.offsetY=0,I.height=h.w,I.width=h.h,I.maxX=I.positionX+I.width/2,I.minX=I.positionX-I.width/2,I.maxY=I.positionY+I.height/2,I.minY=I.positionY-I.height/2,I.padLeft=parseFloat(m.style("padding")),I.padRight=parseFloat(m.style("padding")),I.padTop=parseFloat(m.style("padding")),I.padBottom=parseFloat(m.style("padding")),I.nodeRepulsion=y(n.nodeRepulsion)?n.nodeRepulsion(m):n.nodeRepulsion,o.layoutNodes.push(I),o.idToIndex[I.id]=u}var p=[],f=0,g=-1,v=[];for(u=0;u<o.nodeSize;u++){var m,b=(m=o.layoutNodes[u]).parentId;null!=b?o.layoutNodes[o.idToIndex[b]].children.push(m.id):(p[++g]=m.id,v.push(m.id))}for(o.graphSet.push(v);f<=g;){var x=p[f++],w=o.idToIndex[x],E=o.layoutNodes[w].children;if(E.length>0){o.graphSet.push(E);for(u=0;u<E.length;u++)p[++g]=E[u]}}for(u=0;u<o.graphSet.length;u++){var k=o.graphSet[u];for(d=0;d<k.length;d++){var C=o.idToIndex[k[d]];o.indexToGraph[C]=u}}for(u=0;u<o.edgeSize;u++){var S=r[u],P={};P.id=S.data("id"),P.sourceId=S.data("source"),P.targetId=S.data("target");var D=y(n.idealEdgeLength)?n.idealEdgeLength(S):n.idealEdgeLength,T=y(n.edgeElasticity)?n.edgeElasticity(S):n.edgeElasticity,_=o.idToIndex[P.sourceId],M=o.idToIndex[P.targetId];if(o.indexToGraph[_]!=o.indexToGraph[M]){for(var B=Qs(P.sourceId,P.targetId,o),N=o.graphSet[B],z=0,I=o.layoutNodes[_];-1===N.indexOf(I.id);)I=o.layoutNodes[o.idToIndex[I.parentId]],z++;for(I=o.layoutNodes[M];-1===N.indexOf(I.id);)I=o.layoutNodes[o.idToIndex[I.parentId]],z++;D*=z*n.nestingFactor}P.idealLength=D,P.elasticity=T,o.layoutEdges.push(P)}return o},Qs=function(e,t,n){var r=Js(e,t,0,n);return 2>r.count?0:r.graph},Js=function e(t,n,r,i){var a=i.graphSet[r];if(-1<a.indexOf(t)&&-1<a.indexOf(n))return{count:2,graph:r};for(var o=0,s=0;s<a.length;s++){var l=a[s],u=i.idToIndex[l],c=i.layoutNodes[u].children;if(0!==c.length){var d=e(t,n,i.indexToGraph[i.idToIndex[c[0]]],i);if(0!==d.count){if(1!==d.count)return d;if(2===++o)break}}}return{count:o,graph:r}},el=function(e,t){for(var n=e.clientWidth,r=e.clientHeight,i=0;i<e.nodeSize;i++){var a=e.layoutNodes[i];0!==a.children.length||a.isLocked||(a.positionX=Math.random()*n,a.positionY=Math.random()*r)}},tl=function(e,t,n){var r=e.boundingBox,i={x1:1/0,x2:-1/0,y1:1/0,y2:-1/0};return t.boundingBox&&(n.forEach((function(t){var n=e.layoutNodes[e.idToIndex[t.data("id")]];i.x1=Math.min(i.x1,n.positionX),i.x2=Math.max(i.x2,n.positionX),i.y1=Math.min(i.y1,n.positionY),i.y2=Math.max(i.y2,n.positionY)})),i.w=i.x2-i.x1,i.h=i.y2-i.y1),function(n,a){var o=e.layoutNodes[e.idToIndex[n.data("id")]];if(t.boundingBox){var s=(o.positionX-i.x1)/i.w,l=(o.positionY-i.y1)/i.h;return{x:r.x1+s*r.w,y:r.y1+l*r.h}}return{x:o.positionX,y:o.positionY}}},nl=function(e,t,n){var r=n.layout,i=n.eles.nodes(),a=tl(e,n,i);i.positions(a),!0!==e.ready&&(e.ready=!0,r.one("layoutready",n.ready),r.emit({type:"layoutready",layout:this}))},rl=function(e,t,n){il(e,t),ul(e),cl(e,t),dl(e),hl(e)},il=function(e,t){for(var n=0;n<e.graphSet.length;n++)for(var r=e.graphSet[n],i=r.length,a=0;a<i;a++)for(var o=e.layoutNodes[e.idToIndex[r[a]]],s=a+1;s<i;s++){var l=e.layoutNodes[e.idToIndex[r[s]]];ol(o,l,e,t)}},al=function(e){return-e+2*e*Math.random()},ol=function(e,t,n,r){if(e.cmptId===t.cmptId||n.isCompound){var i=t.positionX-e.positionX,a=t.positionY-e.positionY;0===i&&0===a&&(i=al(1),a=al(1));var o=sl(e,t,i,a);if(o>0)var s=(u=r.nodeOverlap*o)*i/(g=Math.sqrt(i*i+a*a)),l=u*a/g;else{var u,c=ll(e,i,a),d=ll(t,-1*i,-1*a),h=d.x-c.x,p=d.y-c.y,f=h*h+p*p,g=Math.sqrt(f);s=(u=(e.nodeRepulsion+t.nodeRepulsion)/f)*h/g,l=u*p/g}e.isLocked||(e.offsetX-=s,e.offsetY-=l),t.isLocked||(t.offsetX+=s,t.offsetY+=l)}},sl=function(e,t,n,r){if(n>0)var i=e.maxX-t.minX;else i=t.maxX-e.minX;if(r>0)var a=e.maxY-t.minY;else a=t.maxY-e.minY;return i>=0&&a>=0?Math.sqrt(i*i+a*a):0},ll=function(e,t,n){var r=e.positionX,i=e.positionY,a=e.height||1,o=e.width||1,s=n/t,l=a/o,u={};return 0===t&&0<n||0===t&&0>n?(u.x=r,u.y=i+a/2,u):0<t&&-1*l<=s&&s<=l?(u.x=r+o/2,u.y=i+o*n/2/t,u):0>t&&-1*l<=s&&s<=l?(u.x=r-o/2,u.y=i-o*n/2/t,u):0<n&&(s<=-1*l||s>=l)?(u.x=r+a*t/2/n,u.y=i+a/2,u):0>n&&(s<=-1*l||s>=l)?(u.x=r-a*t/2/n,u.y=i-a/2,u):u},ul=function(e,t){for(var n=0;n<e.edgeSize;n++){var r=e.layoutEdges[n],i=e.idToIndex[r.sourceId],a=e.layoutNodes[i],o=e.idToIndex[r.targetId],s=e.layoutNodes[o],l=s.positionX-a.positionX,u=s.positionY-a.positionY;if(0!==l||0!==u){var c=ll(a,l,u),d=ll(s,-1*l,-1*u),h=d.x-c.x,p=d.y-c.y,f=Math.sqrt(h*h+p*p),g=Math.pow(r.idealLength-f,2)/r.elasticity;if(0!==f)var v=g*h/f,y=g*p/f;else v=0,y=0;a.isLocked||(a.offsetX+=v,a.offsetY+=y),s.isLocked||(s.offsetX-=v,s.offsetY-=y)}}},cl=function(e,t){if(0!==t.gravity)for(var n=0;n<e.graphSet.length;n++){var r=e.graphSet[n],i=r.length;if(0===n)var a=e.clientHeight/2,o=e.clientWidth/2;else{var s=e.layoutNodes[e.idToIndex[r[0]]],l=e.layoutNodes[e.idToIndex[s.parentId]];a=l.positionX,o=l.positionY}for(var u=0;u<i;u++){var c=e.layoutNodes[e.idToIndex[r[u]]];if(!c.isLocked){var d=a-c.positionX,h=o-c.positionY,p=Math.sqrt(d*d+h*h);if(p>1){var f=t.gravity*d/p,g=t.gravity*h/p;c.offsetX+=f,c.offsetY+=g}}}}},dl=function(e,t){var n=[],r=0,i=-1;for(n.push.apply(n,e.graphSet[0]),i+=e.graphSet[0].length;r<=i;){var a=n[r++],o=e.idToIndex[a],s=e.layoutNodes[o],l=s.children;if(0<l.length&&!s.isLocked){for(var u=s.offsetX,c=s.offsetY,d=0;d<l.length;d++){var h=e.layoutNodes[e.idToIndex[l[d]]];h.offsetX+=u,h.offsetY+=c,n[++i]=l[d]}s.offsetX=0,s.offsetY=0}}},hl=function(e,t){for(var n=0;n<e.nodeSize;n++){0<(i=e.layoutNodes[n]).children.length&&(i.maxX=void 0,i.minX=void 0,i.maxY=void 0,i.minY=void 0)}for(n=0;n<e.nodeSize;n++){if(!(0<(i=e.layoutNodes[n]).children.length||i.isLocked)){var r=pl(i.offsetX,i.offsetY,e.temperature);i.positionX+=r.x,i.positionY+=r.y,i.offsetX=0,i.offsetY=0,i.minX=i.positionX-i.width,i.maxX=i.positionX+i.width,i.minY=i.positionY-i.height,i.maxY=i.positionY+i.height,fl(i,e)}}for(n=0;n<e.nodeSize;n++){var i;0<(i=e.layoutNodes[n]).children.length&&!i.isLocked&&(i.positionX=(i.maxX+i.minX)/2,i.positionY=(i.maxY+i.minY)/2,i.width=i.maxX-i.minX,i.height=i.maxY-i.minY)}},pl=function(e,t,n){var r=Math.sqrt(e*e+t*t);if(r>n)var i={x:n*e/r,y:n*t/r};else i={x:e,y:t};return i},fl=function e(t,n){var r=t.parentId;if(null!=r){var i=n.layoutNodes[n.idToIndex[r]],a=!1;return(null==i.maxX||t.maxX+i.padRight>i.maxX)&&(i.maxX=t.maxX+i.padRight,a=!0),(null==i.minX||t.minX-i.padLeft<i.minX)&&(i.minX=t.minX-i.padLeft,a=!0),(null==i.maxY||t.maxY+i.padBottom>i.maxY)&&(i.maxY=t.maxY+i.padBottom,a=!0),(null==i.minY||t.minY-i.padTop<i.minY)&&(i.minY=t.minY-i.padTop,a=!0),a?e(i,n):void 0}},gl=function(e,t){for(var n=e.layoutNodes,r=[],i=0;i<n.length;i++){var a=n[i],o=a.cmptId;(r[o]=r[o]||[]).push(a)}var s=0;for(i=0;i<r.length;i++){if(g=r[i]){g.x1=1/0,g.x2=-1/0,g.y1=1/0,g.y2=-1/0;for(var l=0;l<g.length;l++){var u=g[l];g.x1=Math.min(g.x1,u.positionX-u.width/2),g.x2=Math.max(g.x2,u.positionX+u.width/2),g.y1=Math.min(g.y1,u.positionY-u.height/2),g.y2=Math.max(g.y2,u.positionY+u.height/2)}g.w=g.x2-g.x1,g.h=g.y2-g.y1,s+=g.w*g.h}}r.sort((function(e,t){return t.w*t.h-e.w*e.h}));var c=0,d=0,h=0,p=0,f=Math.sqrt(s)*e.clientWidth/e.clientHeight;for(i=0;i<r.length;i++){var g;if(g=r[i]){for(l=0;l<g.length;l++){(u=g[l]).isLocked||(u.positionX+=c-g.x1,u.positionY+=d-g.y1)}c+=g.w+t.componentSpacing,h+=g.w+t.componentSpacing,p=Math.max(p,g.h),h>f&&(d+=p+t.componentSpacing,c=0,h=0,p=0)}}},vl={fit:!0,padding:30,boundingBox:void 0,avoidOverlap:!0,avoidOverlapPadding:10,nodeDimensionsIncludeLabels:!1,spacingFactor:void 0,condense:!1,rows:void 0,cols:void 0,position:function(e){},sort:void 0,animate:!1,animationDuration:500,animationEasing:void 0,animateFilter:function(e,t){return!0},ready:void 0,stop:void 0,transform:function(e,t){return t}};function yl(e){this.options=L({},vl,e)}yl.prototype.run=function(){var e=this.options,t=e,n=e.cy,r=t.eles,i=r.nodes().not(":parent");t.sort&&(i=i.sort(t.sort));var a=_t(t.boundingBox?t.boundingBox:{x1:0,y1:0,w:n.width(),h:n.height()});if(0===a.h||0===a.w)r.nodes().layoutPositions(this,t,(function(e){return{x:a.x1,y:a.y1}}));else{var o=i.size(),s=Math.sqrt(o*a.h/a.w),l=Math.round(s),u=Math.round(a.w/a.h*s),c=function(e){if(null==e)return Math.min(l,u);Math.min(l,u)==l?l=e:u=e},d=function(e){if(null==e)return Math.max(l,u);Math.max(l,u)==l?l=e:u=e},h=t.rows,p=null!=t.cols?t.cols:t.columns;if(null!=h&&null!=p)l=h,u=p;else if(null!=h&&null==p)l=h,u=Math.ceil(o/l);else if(null==h&&null!=p)u=p,l=Math.ceil(o/u);else if(u*l>o){var f=c(),g=d();(f-1)*g>=o?c(f-1):(g-1)*f>=o&&d(g-1)}else for(;u*l<o;){var v=c(),y=d();(y+1)*v>=o?d(y+1):c(v+1)}var m=a.w/u,b=a.h/l;if(t.condense&&(m=0,b=0),t.avoidOverlap)for(var x=0;x<i.length;x++){var w=i[x],E=w._private.position;null!=E.x&&null!=E.y||(E.x=0,E.y=0);var k=w.layoutDimensions(t),C=t.avoidOverlapPadding,S=k.w+C,P=k.h+C;m=Math.max(m,S),b=Math.max(b,P)}for(var D={},T=function(e,t){return!!D["c-"+e+"-"+t]},_=function(e,t){D["c-"+e+"-"+t]=!0},M=0,B=0,N=function(){++B>=u&&(B=0,M++)},z={},I=0;I<i.length;I++){var A=i[I],L=t.position(A);if(L&&(void 0!==L.row||void 0!==L.col)){var O={row:L.row,col:L.col};if(void 0===O.col)for(O.col=0;T(O.row,O.col);)O.col++;else if(void 0===O.row)for(O.row=0;T(O.row,O.col);)O.row++;z[A.id()]=O,_(O.row,O.col)}}i.layoutPositions(this,t,(function(e,t){var n,r;if(e.locked()||e.isParent())return!1;var i=z[e.id()];if(i)n=i.col*m+m/2+a.x1,r=i.row*b+b/2+a.y1;else{for(;T(M,B);)N();n=B*m+m/2+a.x1,r=M*b+b/2+a.y1,_(M,B),N()}return{x:n,y:r}}))}return this};var ml={ready:function(){},stop:function(){}};function bl(e){this.options=L({},ml,e)}bl.prototype.run=function(){var e=this.options,t=e.eles;return e.cy,this.emit("layoutstart"),t.nodes().positions((function(){return{x:0,y:0}})),this.one("layoutready",e.ready),this.emit("layoutready"),this.one("layoutstop",e.stop),this.emit("layoutstop"),this},bl.prototype.stop=function(){return this};var xl={positions:void 0,zoom:void 0,pan:void 0,fit:!0,padding:30,spacingFactor:void 0,animate:!1,animationDuration:500,animationEasing:void 0,animateFilter:function(e,t){return!0},ready:void 0,stop:void 0,transform:function(e,t){return t}};function wl(e){this.options=L({},xl,e)}wl.prototype.run=function(){var e=this.options,t=e.eles.nodes(),n=y(e.positions);return t.layoutPositions(this,e,(function(t,r){var i=function(t){if(null==e.positions)return function(e){return{x:e.x,y:e.y}}(t.position());if(n)return e.positions(t);var r=e.positions[t._private.data.id];return null==r?null:r}(t);return!t.locked()&&null!=i&&i})),this};var El={fit:!0,padding:30,boundingBox:void 0,animate:!1,animationDuration:500,animationEasing:void 0,animateFilter:function(e,t){return!0},ready:void 0,stop:void 0,transform:function(e,t){return t}};function kl(e){this.options=L({},El,e)}kl.prototype.run=function(){var e=this.options,t=e.cy,n=e.eles,r=_t(e.boundingBox?e.boundingBox:{x1:0,y1:0,w:t.width(),h:t.height()});return n.nodes().layoutPositions(this,e,(function(e,t){return{x:r.x1+Math.round(Math.random()*r.w),y:r.y1+Math.round(Math.random()*r.h)}})),this};var Cl=[{name:"breadthfirst",impl:Ys},{name:"circle",impl:Ws},{name:"concentric",impl:Gs},{name:"cose",impl:Zs},{name:"grid",impl:yl},{name:"null",impl:bl},{name:"preset",impl:wl},{name:"random",impl:kl}];function Sl(e){this.options=e,this.notifications=0}var Pl=function(){},Dl=function(){throw new Error("A headless instance can not render images")};Sl.prototype={recalculateRenderedStyle:Pl,notify:function(){this.notifications++},init:Pl,isHeadless:function(){return!0},png:Dl,jpg:Dl};var Tl={arrowShapeWidth:.3,registerArrowShapes:function(){var e=this.arrowShapes={},t=this,n=function(e,t,n,r,i,a,o){var s=i.x-n/2-o,l=i.x+n/2+o,u=i.y-n/2-o,c=i.y+n/2+o;return s<=e&&e<=l&&u<=t&&t<=c},r=function(e,t,n,r,i){var a=e*Math.cos(r)-t*Math.sin(r),o=(e*Math.sin(r)+t*Math.cos(r))*n;return{x:a*n+i.x,y:o+i.y}},i=function(e,t,n,i){for(var a=[],o=0;o<e.length;o+=2){var s=e[o],l=e[o+1];a.push(r(s,l,t,n,i))}return a},a=function(e){for(var t=[],n=0;n<e.length;n++){var r=e[n];t.push(r.x,r.y)}return t},o=function(e){return e.pstyle("width").pfValue*e.pstyle("arrow-scale").pfValue*2},s=function(r,s){v(s)&&(s=e[s]),e[r]=L({name:r,points:[-.15,-.3,.15,-.3,.15,.3,-.15,.3],collide:function(e,t,n,r,o,s){var l=a(i(this.points,n+2*s,r,o));return Yt(e,t,l)},roughCollide:n,draw:function(e,n,r,a){var o=i(this.points,n,r,a);t.arrowShapeImpl("polygon")(e,o)},spacing:function(e){return 0},gap:o},s)};s("none",{collide:Le,roughCollide:Le,draw:Re,spacing:Oe,gap:Oe}),s("triangle",{points:[-.15,-.3,0,0,.15,-.3]}),s("arrow","triangle"),s("triangle-backcurve",{points:e.triangle.points,controlPoint:[0,-.15],roughCollide:n,draw:function(e,n,a,o,s){var l=i(this.points,n,a,o),u=this.controlPoint,c=r(u[0],u[1],n,a,o);t.arrowShapeImpl(this.name)(e,l,c)},gap:function(e){return.8*o(e)}}),s("triangle-tee",{points:[0,0,.15,-.3,-.15,-.3,0,0],pointsTee:[-.15,-.4,-.15,-.5,.15,-.5,.15,-.4],collide:function(e,t,n,r,o,s,l){var u=a(i(this.points,n+2*l,r,o)),c=a(i(this.pointsTee,n+2*l,r,o));return Yt(e,t,u)||Yt(e,t,c)},draw:function(e,n,r,a,o){var s=i(this.points,n,r,a),l=i(this.pointsTee,n,r,a);t.arrowShapeImpl(this.name)(e,s,l)}}),s("circle-triangle",{radius:.15,pointsTr:[0,-.15,.15,-.45,-.15,-.45,0,-.15],collide:function(e,t,n,r,o,s,l){var u=o,c=Math.pow(u.x-e,2)+Math.pow(u.y-t,2)<=Math.pow((n+2*l)*this.radius,2),d=a(i(this.points,n+2*l,r,o));return Yt(e,t,d)||c},draw:function(e,n,r,a,o){var s=i(this.pointsTr,n,r,a);t.arrowShapeImpl(this.name)(e,s,a.x,a.y,this.radius*n)},spacing:function(e){return t.getArrowWidth(e.pstyle("width").pfValue,e.pstyle("arrow-scale").value)*this.radius}}),s("triangle-cross",{points:[0,0,.15,-.3,-.15,-.3,0,0],baseCrossLinePts:[-.15,-.4,-.15,-.4,.15,-.4,.15,-.4],crossLinePts:function(e,t){var n=this.baseCrossLinePts.slice(),r=t/e;return n[3]=n[3]-r,n[5]=n[5]-r,n},collide:function(e,t,n,r,o,s,l){var u=a(i(this.points,n+2*l,r,o)),c=a(i(this.crossLinePts(n,s),n+2*l,r,o));return Yt(e,t,u)||Yt(e,t,c)},draw:function(e,n,r,a,o){var s=i(this.points,n,r,a),l=i(this.crossLinePts(n,o),n,r,a);t.arrowShapeImpl(this.name)(e,s,l)}}),s("vee",{points:[-.15,-.3,0,0,.15,-.3,0,-.15],gap:function(e){return.525*o(e)}}),s("circle",{radius:.15,collide:function(e,t,n,r,i,a,o){var s=i;return Math.pow(s.x-e,2)+Math.pow(s.y-t,2)<=Math.pow((n+2*o)*this.radius,2)},draw:function(e,n,r,i,a){t.arrowShapeImpl(this.name)(e,i.x,i.y,this.radius*n)},spacing:function(e){return t.getArrowWidth(e.pstyle("width").pfValue,e.pstyle("arrow-scale").value)*this.radius}}),s("tee",{points:[-.15,0,-.15,-.1,.15,-.1,.15,0],spacing:function(e){return 1},gap:function(e){return 1}}),s("square",{points:[-.15,0,.15,0,.15,-.3,-.15,-.3]}),s("diamond",{points:[-.15,-.15,0,-.3,.15,-.15,0,0],gap:function(e){return e.pstyle("width").pfValue*e.pstyle("arrow-scale").value}}),s("chevron",{points:[0,0,-.15,-.15,-.1,-.2,0,-.1,.1,-.2,.15,-.15],gap:function(e){return.95*e.pstyle("width").pfValue*e.pstyle("arrow-scale").value}})}},_l={projectIntoViewport:function(e,t){var n=this.cy,r=this.findContainerClientCoords(),i=r[0],a=r[1],o=r[4],s=n.pan(),l=n.zoom();return[((e-i)/o-s.x)/l,((t-a)/o-s.y)/l]},findContainerClientCoords:function(){if(this.containerBB)return this.containerBB;var e=this.container,t=e.getBoundingClientRect(),n=this.cy.window().getComputedStyle(e),r=function(e){return parseFloat(n.getPropertyValue(e))},i=r("padding-left"),a=r("padding-right"),o=r("padding-top"),s=r("padding-bottom"),l=r("border-left-width"),u=r("border-right-width"),c=r("border-top-width"),d=(r("border-bottom-width"),e.clientWidth),h=e.clientHeight,p=i+a,f=o+s,g=l+u,v=t.width/(d+g),y=d-p,m=h-f,b=t.left+i+l,x=t.top+o+c;return this.containerBB=[b,x,y,m,v]},invalidateContainerClientCoordsCache:function(){this.containerBB=null},findNearestElement:function(e,t,n,r){return this.findNearestElements(e,t,n,r)[0]},findNearestElements:function(e,t,n,r){var i,a,o=this,s=this,l=s.getCachedZSortedEles(),u=[],c=s.cy.zoom(),d=s.cy.hasCompoundNodes(),h=(r?24:8)/c,p=(r?8:2)/c,f=(r?8:2)/c,g=1/0;function v(e,t){if(e.isNode()){if(a)return;a=e,u.push(e)}if(e.isEdge()&&(null==t||t<g))if(i){if(i.pstyle("z-compound-depth").value===e.pstyle("z-compound-depth").value&&i.pstyle("z-compound-depth").value===e.pstyle("z-compound-depth").value)for(var n=0;n<u.length;n++)if(u[n].isEdge()){u[n]=e,i=e,g=null!=t?t:g;break}}else u.push(e),i=e,g=null!=t?t:g}function y(n){var r=n.outerWidth()+2*p,i=n.outerHeight()+2*p,a=r/2,l=i/2,u=n.position(),c="auto"===n.pstyle("corner-radius").value?"auto":n.pstyle("corner-radius").pfValue,d=n._private.rscratch;if(u.x-a<=e&&e<=u.x+a&&u.y-l<=t&&t<=u.y+l&&s.nodeShapes[o.getNodeShape(n)].checkPoint(e,t,0,r,i,u.x,u.y,c,d))return v(n,0),!0}function m(n){var r,i=n._private,a=i.rscratch,l=n.pstyle("width").pfValue,c=n.pstyle("arrow-scale").value,p=l/2+h,f=p*p,g=2*p,m=i.source,b=i.target;if("segments"===a.edgeType||"straight"===a.edgeType||"haystack"===a.edgeType){for(var x=a.allpts,w=0;w+3<x.length;w+=2)if(Vt(e,t,x[w],x[w+1],x[w+2],x[w+3],g)&&f>(r=qt(e,t,x[w],x[w+1],x[w+2],x[w+3])))return v(n,r),!0}else if("bezier"===a.edgeType||"multibezier"===a.edgeType||"self"===a.edgeType||"compound"===a.edgeType)for(x=a.allpts,w=0;w+5<a.allpts.length;w+=4)if(Ft(e,t,x[w],x[w+1],x[w+2],x[w+3],x[w+4],x[w+5],g)&&f>(r=jt(e,t,x[w],x[w+1],x[w+2],x[w+3],x[w+4],x[w+5])))return v(n,r),!0;m=m||i.source,b=b||i.target;var E=o.getArrowWidth(l,c),k=[{name:"source",x:a.arrowStartX,y:a.arrowStartY,angle:a.srcArrowAngle},{name:"target",x:a.arrowEndX,y:a.arrowEndY,angle:a.tgtArrowAngle},{name:"mid-source",x:a.midX,y:a.midY,angle:a.midsrcArrowAngle},{name:"mid-target",x:a.midX,y:a.midY,angle:a.midtgtArrowAngle}];for(w=0;w<k.length;w++){var C=k[w],S=s.arrowShapes[n.pstyle(C.name+"-arrow-shape").value],P=n.pstyle("width").pfValue;if(S.roughCollide(e,t,E,C.angle,{x:C.x,y:C.y},P,h)&&S.collide(e,t,E,C.angle,{x:C.x,y:C.y},P,h))return v(n),!0}d&&u.length>0&&(y(m),y(b))}function b(e,t,n){return Ue(e,t,n)}function x(n,r){var i,a=n._private,o=f;i=r?r+"-":"",n.boundingBox();var s=a.labelBounds[r||"main"],l=n.pstyle(i+"label").value;if("yes"===n.pstyle("text-events").strValue&&l){var u=b(a.rscratch,"labelX",r),c=b(a.rscratch,"labelY",r),d=b(a.rscratch,"labelAngle",r),h=n.pstyle(i+"text-margin-x").pfValue,p=n.pstyle(i+"text-margin-y").pfValue,g=s.x1-o-h,y=s.x2+o-h,m=s.y1-o-p,x=s.y2+o-p;if(d){var w=Math.cos(d),E=Math.sin(d),k=function(e,t){return{x:(e-=u)*w-(t-=c)*E+u,y:e*E+t*w+c}},C=k(g,m),S=k(g,x),P=k(y,m),D=k(y,x),T=[C.x+h,C.y+p,P.x+h,P.y+p,D.x+h,D.y+p,S.x+h,S.y+p];if(Yt(e,t,T))return v(n),!0}else if(Lt(s,e,t))return v(n),!0}}n&&(l=l.interactive);for(var w=l.length-1;w>=0;w--){var E=l[w];E.isNode()?y(E)||x(E):m(E)||x(E)||x(E,"source")||x(E,"target")}return u},getAllInBox:function(e,t,n,r){for(var i,a,o=this.getCachedZSortedEles().interactive,s=[],l=Math.min(e,n),u=Math.max(e,n),c=Math.min(t,r),d=Math.max(t,r),h=_t({x1:e=l,y1:t=c,x2:n=u,y2:r=d}),p=0;p<o.length;p++){var f=o[p];if(f.isNode()){var g=f,v=g.boundingBox({includeNodes:!0,includeEdges:!1,includeLabels:!1});At(h,v)&&!Ot(v,h)&&s.push(g)}else{var y=f,m=y._private,b=m.rscratch;if(null!=b.startX&&null!=b.startY&&!Lt(h,b.startX,b.startY))continue;if(null!=b.endX&&null!=b.endY&&!Lt(h,b.endX,b.endY))continue;if("bezier"===b.edgeType||"multibezier"===b.edgeType||"self"===b.edgeType||"compound"===b.edgeType||"segments"===b.edgeType||"haystack"===b.edgeType){for(var x=m.rstyle.bezierPts||m.rstyle.linePts||m.rstyle.haystackPts,w=!0,E=0;E<x.length;E++)if(i=h,a=x[E],!Lt(i,a.x,a.y)){w=!1;break}w&&s.push(y)}else"haystack"!==b.edgeType&&"straight"!==b.edgeType||s.push(y)}}return s}},Ml={calculateArrowAngles:function(e){var t,n,r,i,a,o,s=e._private.rscratch,l="haystack"===s.edgeType,u="bezier"===s.edgeType,c="multibezier"===s.edgeType,d="segments"===s.edgeType,h="compound"===s.edgeType,p="self"===s.edgeType;if(l?(r=s.haystackPts[0],i=s.haystackPts[1],a=s.haystackPts[2],o=s.haystackPts[3]):(r=s.arrowStartX,i=s.arrowStartY,a=s.arrowEndX,o=s.arrowEndY),g=s.midX,v=s.midY,d)t=r-s.segpts[0],n=i-s.segpts[1];else if(c||h||p||u){var f=s.allpts;t=r-Pt(f[0],f[2],f[4],.1),n=i-Pt(f[1],f[3],f[5],.1)}else t=r-g,n=i-v;s.srcArrowAngle=xt(t,n);var g=s.midX,v=s.midY;if(l&&(g=(r+a)/2,v=(i+o)/2),t=a-r,n=o-i,d)if((f=s.allpts).length/2%2==0){var y=(S=f.length/2)-2;t=f[S]-f[y],n=f[S+1]-f[y+1]}else if(s.isRound)t=s.midVector[1],n=-s.midVector[0];else{y=(S=f.length/2-1)-2;t=f[S]-f[y],n=f[S+1]-f[y+1]}else if(c||h||p){var m,b,x,w,f=s.allpts;if(s.ctrlpts.length/2%2==0){var E=(k=(C=f.length/2-1)+2)+2;m=Pt(f[C],f[k],f[E],0),b=Pt(f[C+1],f[k+1],f[E+1],0),x=Pt(f[C],f[k],f[E],1e-4),w=Pt(f[C+1],f[k+1],f[E+1],1e-4)}else{var k,C;E=(k=f.length/2-1)+2;m=Pt(f[C=k-2],f[k],f[E],.4999),b=Pt(f[C+1],f[k+1],f[E+1],.4999),x=Pt(f[C],f[k],f[E],.5),w=Pt(f[C+1],f[k+1],f[E+1],.5)}t=x-m,n=w-b}if(s.midtgtArrowAngle=xt(t,n),s.midDispX=t,s.midDispY=n,t*=-1,n*=-1,d)if((f=s.allpts).length/2%2==0);else if(!s.isRound){var S,P=(S=f.length/2-1)+2;t=-(f[P]-f[S]),n=-(f[P+1]-f[S+1])}if(s.midsrcArrowAngle=xt(t,n),d)t=a-s.segpts[s.segpts.length-2],n=o-s.segpts[s.segpts.length-1];else if(c||h||p||u){var D=(f=s.allpts).length;t=a-Pt(f[D-6],f[D-4],f[D-2],.9),n=o-Pt(f[D-5],f[D-3],f[D-1],.9)}else t=a-g,n=o-v;s.tgtArrowAngle=xt(t,n)}};Ml.getArrowWidth=Ml.getArrowHeight=function(e,t){var n=this.arrowWidthCache=this.arrowWidthCache||{},r=n[e+", "+t];return r||(r=Math.max(Math.pow(13.37*e,.9),29)*t,n[e+", "+t]=r,r)};var Bl,Nl,zl,Il,Al,Ll,Ol,Rl,Vl,Fl,jl,ql,Yl,Xl,Wl,Hl,Kl,Gl={},Ul={},Zl=function(e,t,n){n.x=t.x-e.x,n.y=t.y-e.y,n.len=Math.sqrt(n.x*n.x+n.y*n.y),n.nx=n.x/n.len,n.ny=n.y/n.len,n.ang=Math.atan2(n.ny,n.nx)},$l=function(e,t,n,r,i){var a,o;if(e!==Kl?Zl(t,e,Gl):((o=Gl).x=-1*(a=Ul).x,o.y=-1*a.y,o.nx=-1*a.nx,o.ny=-1*a.ny,o.ang=a.ang>0?-(Math.PI-a.ang):Math.PI+a.ang),Zl(t,n,Ul),zl=Gl.nx*Ul.ny-Gl.ny*Ul.nx,Il=Gl.nx*Ul.nx-Gl.ny*-Ul.ny,Ol=Math.asin(Math.max(-1,Math.min(1,zl))),Math.abs(Ol)<1e-6)return Bl=t.x,Nl=t.y,void(Vl=jl=0);Al=1,Ll=!1,Il<0?Ol<0?Ol=Math.PI+Ol:(Ol=Math.PI-Ol,Al=-1,Ll=!0):Ol>0&&(Al=-1,Ll=!0),jl=void 0!==t.radius?t.radius:r,Rl=Ol/2,ql=Math.min(Gl.len/2,Ul.len/2),i?(Fl=Math.abs(Math.cos(Rl)*jl/Math.sin(Rl)))>ql?(Fl=ql,Vl=Math.abs(Fl*Math.sin(Rl)/Math.cos(Rl))):Vl=jl:(Fl=Math.min(ql,jl),Vl=Math.abs(Fl*Math.sin(Rl)/Math.cos(Rl))),Wl=t.x+Ul.nx*Fl,Hl=t.y+Ul.ny*Fl,Bl=Wl-Ul.ny*Vl*Al,Nl=Hl+Ul.nx*Vl*Al,Yl=t.x+Gl.nx*Fl,Xl=t.y+Gl.ny*Fl,Kl=t};function Ql(e,t){0===t.radius?e.lineTo(t.cx,t.cy):e.arc(t.cx,t.cy,t.radius,t.startAngle,t.endAngle,t.counterClockwise)}function Jl(e,t,n,r){var i=!(arguments.length>4&&void 0!==arguments[4])||arguments[4];return 0===r||0===t.radius?{cx:t.x,cy:t.y,radius:0,startX:t.x,startY:t.y,stopX:t.x,stopY:t.y,startAngle:void 0,endAngle:void 0,counterClockwise:void 0}:($l(e,t,n,r,i),{cx:Bl,cy:Nl,radius:Vl,startX:Yl,startY:Xl,stopX:Wl,stopY:Hl,startAngle:Gl.ang+Math.PI/2*Al,endAngle:Ul.ang-Math.PI/2*Al,counterClockwise:Ll})}var eu={};function tu(e){var t=[];if(null!=e){for(var n=0;n<e.length;n+=2){var r=e[n],i=e[n+1];t.push({x:r,y:i})}return t}}eu.findMidptPtsEtc=function(e,t){var n,r=t.posPts,i=t.intersectionPts,o=t.vectorNormInverse,s=e.pstyle("source-endpoint"),l=e.pstyle("target-endpoint"),u=null!=s.units&&null!=l.units;switch(e.pstyle("edge-distances").value){case"node-position":n=r;break;case"intersection":n=i;break;case"endpoints":if(u){var c=a(this.manualEndptToPx(e.source()[0],s),2),d=c[0],h=c[1],p=a(this.manualEndptToPx(e.target()[0],l),2),f=p[0],g=p[1],v={x1:d,y1:h,x2:f,y2:g};o=function(e,t,n,r){var i=r-t,a=n-e,o=Math.sqrt(a*a+i*i);return{x:-i/o,y:a/o}}(d,h,f,g),n=v}else je("Edge ".concat(e.id()," has edge-distances:endpoints specified without manual endpoints specified via source-endpoint and target-endpoint. Falling back on edge-distances:intersection (default).")),n=i}return{midptPts:n,vectorNormInverse:o}},eu.findHaystackPoints=function(e){for(var t=0;t<e.length;t++){var n=e[t],r=n._private,i=r.rscratch;if(!i.haystack){var a=2*Math.random()*Math.PI;i.source={x:Math.cos(a),y:Math.sin(a)},a=2*Math.random()*Math.PI,i.target={x:Math.cos(a),y:Math.sin(a)}}var o=r.source,s=r.target,l=o.position(),u=s.position(),c=o.width(),d=s.width(),h=o.height(),p=s.height(),f=n.pstyle("haystack-radius").value/2;i.haystackPts=i.allpts=[i.source.x*c*f+l.x,i.source.y*h*f+l.y,i.target.x*d*f+u.x,i.target.y*p*f+u.y],i.midX=(i.allpts[0]+i.allpts[2])/2,i.midY=(i.allpts[1]+i.allpts[3])/2,i.edgeType="haystack",i.haystack=!0,this.storeEdgeProjections(n),this.calculateArrowAngles(n),this.recalculateEdgeLabelProjections(n),this.calculateLabelAngles(n)}},eu.findSegmentsPoints=function(e,t){var n=e._private.rscratch,r=e.pstyle("segment-weights"),i=e.pstyle("segment-distances"),a=e.pstyle("segment-radii"),o=e.pstyle("radius-type"),s=Math.min(r.pfValue.length,i.pfValue.length),l=a.pfValue[a.pfValue.length-1],u=o.pfValue[o.pfValue.length-1];n.edgeType="segments",n.segpts=[],n.radii=[],n.isArcRadius=[];for(var c=0;c<s;c++){var d=r.pfValue[c],h=i.pfValue[c],p=1-d,f=d,g=this.findMidptPtsEtc(e,t),v=g.midptPts,y=g.vectorNormInverse,m={x:v.x1*p+v.x2*f,y:v.y1*p+v.y2*f};n.segpts.push(m.x+y.x*h,m.y+y.y*h),n.radii.push(void 0!==a.pfValue[c]?a.pfValue[c]:l),n.isArcRadius.push("arc-radius"===(void 0!==o.pfValue[c]?o.pfValue[c]:u))}},eu.findLoopPoints=function(e,t,n,r){var i=e._private.rscratch,a=t.dirCounts,o=t.srcPos,s=e.pstyle("control-point-distances"),l=s?s.pfValue[0]:void 0,u=e.pstyle("loop-direction").pfValue,c=e.pstyle("loop-sweep").pfValue,d=e.pstyle("control-point-step-size").pfValue;i.edgeType="self";var h=n,p=d;r&&(h=0,p=l);var f=u-Math.PI/2,g=f-c/2,v=f+c/2,y=String(u+"_"+c);h=void 0===a[y]?a[y]=0:++a[y],i.ctrlpts=[o.x+1.4*Math.cos(g)*p*(h/3+1),o.y+1.4*Math.sin(g)*p*(h/3+1),o.x+1.4*Math.cos(v)*p*(h/3+1),o.y+1.4*Math.sin(v)*p*(h/3+1)]},eu.findCompoundLoopPoints=function(e,t,n,r){var i=e._private.rscratch;i.edgeType="compound";var a=t.srcPos,o=t.tgtPos,s=t.srcW,l=t.srcH,u=t.tgtW,c=t.tgtH,d=e.pstyle("control-point-step-size").pfValue,h=e.pstyle("control-point-distances"),p=h?h.pfValue[0]:void 0,f=n,g=d;r&&(f=0,g=p);var v={x:a.x-s/2,y:a.y-l/2},y={x:o.x-u/2,y:o.y-c/2},m={x:Math.min(v.x,y.x),y:Math.min(v.y,y.y)},b=Math.max(.5,Math.log(.01*s)),x=Math.max(.5,Math.log(.01*u));i.ctrlpts=[m.x,m.y-(1+Math.pow(50,1.12)/100)*g*(f/3+1)*b,m.x-(1+Math.pow(50,1.12)/100)*g*(f/3+1)*x,m.y]},eu.findStraightEdgePoints=function(e){e._private.rscratch.edgeType="straight"},eu.findBezierPoints=function(e,t,n,r,i){var a=e._private.rscratch,o=e.pstyle("control-point-step-size").pfValue,s=e.pstyle("control-point-distances"),l=e.pstyle("control-point-weights"),u=s&&l?Math.min(s.value.length,l.value.length):1,c=s?s.pfValue[0]:void 0,d=l.value[0],h=r;a.edgeType=h?"multibezier":"bezier",a.ctrlpts=[];for(var p=0;p<u;p++){var f=(.5-t.eles.length/2+n)*o*(i?-1:1),g=void 0,v=Et(f);h&&(c=s?s.pfValue[p]:o,d=l.value[p]);var y=void 0!==(g=r?c:void 0!==c?v*c:void 0)?g:f,m=1-d,b=d,x=this.findMidptPtsEtc(e,t),w=x.midptPts,E=x.vectorNormInverse,k={x:w.x1*m+w.x2*b,y:w.y1*m+w.y2*b};a.ctrlpts.push(k.x+E.x*y,k.y+E.y*y)}},eu.findTaxiPoints=function(e,t){var n=e._private.rscratch;n.edgeType="segments";var r=t.posPts,i=t.srcW,a=t.srcH,o=t.tgtW,s=t.tgtH,l="node-position"!==e.pstyle("edge-distances").value,u=e.pstyle("taxi-direction").value,c=u,d=e.pstyle("taxi-turn"),h="%"===d.units,p=d.pfValue,f=p<0,g=e.pstyle("taxi-turn-min-distance").pfValue,v=l?(i+o)/2:0,y=l?(a+s)/2:0,m=r.x2-r.x1,b=r.y2-r.y1,x=function(e,t){return e>0?Math.max(e-t,0):Math.min(e+t,0)},w=x(m,v),E=x(b,y),k=!1;"auto"===c?u=Math.abs(w)>Math.abs(E)?"horizontal":"vertical":"upward"===c||"downward"===c?(u="vertical",k=!0):"leftward"!==c&&"rightward"!==c||(u="horizontal",k=!0);var C,S="vertical"===u,P=S?E:w,D=S?b:m,T=Et(D),_=!1;(k&&(h||f)||!("downward"===c&&D<0||"upward"===c&&D>0||"leftward"===c&&D>0||"rightward"===c&&D<0)||(P=(T*=-1)*Math.abs(P),_=!0),h)?C=(p<0?1+p:p)*P:C=(p<0?P:0)+p*T;var M=function(e){return Math.abs(e)<g||Math.abs(e)>=Math.abs(P)},B=M(C),N=M(Math.abs(P)-Math.abs(C));if((B||N)&&!_)if(S){var z=Math.abs(D)<=a/2,I=Math.abs(m)<=o/2;if(z){var A=(r.x1+r.x2)/2,L=r.y1,O=r.y2;n.segpts=[A,L,A,O]}else if(I){var R=(r.y1+r.y2)/2,V=r.x1,F=r.x2;n.segpts=[V,R,F,R]}else n.segpts=[r.x1,r.y2]}else{var j=Math.abs(D)<=i/2,q=Math.abs(b)<=s/2;if(j){var Y=(r.y1+r.y2)/2,X=r.x1,W=r.x2;n.segpts=[X,Y,W,Y]}else if(q){var H=(r.x1+r.x2)/2,K=r.y1,G=r.y2;n.segpts=[H,K,H,G]}else n.segpts=[r.x2,r.y1]}else if(S){var U=r.y1+C+(l?a/2*T:0),Z=r.x1,$=r.x2;n.segpts=[Z,U,$,U]}else{var Q=r.x1+C+(l?i/2*T:0),J=r.y1,ee=r.y2;n.segpts=[Q,J,Q,ee]}if(n.isRound){var te=e.pstyle("taxi-radius").value,ne="arc-radius"===e.pstyle("radius-type").value[0];n.radii=new Array(n.segpts.length/2).fill(te),n.isArcRadius=new Array(n.segpts.length/2).fill(ne)}},eu.tryToCorrectInvalidPoints=function(e,t){var n=e._private.rscratch;if("bezier"===n.edgeType){var r=t.srcPos,i=t.tgtPos,a=t.srcW,o=t.srcH,s=t.tgtW,l=t.tgtH,u=t.srcShape,c=t.tgtShape,d=t.srcCornerRadius,h=t.tgtCornerRadius,p=t.srcRs,f=t.tgtRs,g=!x(n.startX)||!x(n.startY),v=!x(n.arrowStartX)||!x(n.arrowStartY),y=!x(n.endX)||!x(n.endY),m=!x(n.arrowEndX)||!x(n.arrowEndY),b=3*(this.getArrowWidth(e.pstyle("width").pfValue,e.pstyle("arrow-scale").value)*this.arrowShapeWidth),w=kt({x:n.ctrlpts[0],y:n.ctrlpts[1]},{x:n.startX,y:n.startY}),E=w<b,k=kt({x:n.ctrlpts[0],y:n.ctrlpts[1]},{x:n.endX,y:n.endY}),C=k<b,S=!1;if(g||v||E){S=!0;var P={x:n.ctrlpts[0]-r.x,y:n.ctrlpts[1]-r.y},D=Math.sqrt(P.x*P.x+P.y*P.y),T={x:P.x/D,y:P.y/D},_=Math.max(a,o),M={x:n.ctrlpts[0]+2*T.x*_,y:n.ctrlpts[1]+2*T.y*_},B=u.intersectLine(r.x,r.y,a,o,M.x,M.y,0,d,p);E?(n.ctrlpts[0]=n.ctrlpts[0]+T.x*(b-w),n.ctrlpts[1]=n.ctrlpts[1]+T.y*(b-w)):(n.ctrlpts[0]=B[0]+T.x*b,n.ctrlpts[1]=B[1]+T.y*b)}if(y||m||C){S=!0;var N={x:n.ctrlpts[0]-i.x,y:n.ctrlpts[1]-i.y},z=Math.sqrt(N.x*N.x+N.y*N.y),I={x:N.x/z,y:N.y/z},A=Math.max(a,o),L={x:n.ctrlpts[0]+2*I.x*A,y:n.ctrlpts[1]+2*I.y*A},O=c.intersectLine(i.x,i.y,s,l,L.x,L.y,0,h,f);C?(n.ctrlpts[0]=n.ctrlpts[0]+I.x*(b-k),n.ctrlpts[1]=n.ctrlpts[1]+I.y*(b-k)):(n.ctrlpts[0]=O[0]+I.x*b,n.ctrlpts[1]=O[1]+I.y*b)}S&&this.findEndpoints(e)}},eu.storeAllpts=function(e){var t=e._private.rscratch;if("multibezier"===t.edgeType||"bezier"===t.edgeType||"self"===t.edgeType||"compound"===t.edgeType){t.allpts=[],t.allpts.push(t.startX,t.startY);for(var n=0;n+1<t.ctrlpts.length;n+=2)t.allpts.push(t.ctrlpts[n],t.ctrlpts[n+1]),n+3<t.ctrlpts.length&&t.allpts.push((t.ctrlpts[n]+t.ctrlpts[n+2])/2,(t.ctrlpts[n+1]+t.ctrlpts[n+3])/2);var r;t.allpts.push(t.endX,t.endY),t.ctrlpts.length/2%2==0?(r=t.allpts.length/2-1,t.midX=t.allpts[r],t.midY=t.allpts[r+1]):(r=t.allpts.length/2-3,.5,t.midX=Pt(t.allpts[r],t.allpts[r+2],t.allpts[r+4],.5),t.midY=Pt(t.allpts[r+1],t.allpts[r+3],t.allpts[r+5],.5))}else if("straight"===t.edgeType)t.allpts=[t.startX,t.startY,t.endX,t.endY],t.midX=(t.startX+t.endX+t.arrowStartX+t.arrowEndX)/4,t.midY=(t.startY+t.endY+t.arrowStartY+t.arrowEndY)/4;else if("segments"===t.edgeType){if(t.allpts=[],t.allpts.push(t.startX,t.startY),t.allpts.push.apply(t.allpts,t.segpts),t.allpts.push(t.endX,t.endY),t.isRound){t.roundCorners=[];for(var i=2;i+3<t.allpts.length;i+=2){var a=t.radii[i/2-1],o=t.isArcRadius[i/2-1];t.roundCorners.push(Jl({x:t.allpts[i-2],y:t.allpts[i-1]},{x:t.allpts[i],y:t.allpts[i+1],radius:a},{x:t.allpts[i+2],y:t.allpts[i+3]},a,o))}}if(t.segpts.length%4==0){var s=t.segpts.length/2,l=s-2;t.midX=(t.segpts[l]+t.segpts[s])/2,t.midY=(t.segpts[l+1]+t.segpts[s+1])/2}else{var u=t.segpts.length/2-1;if(t.isRound){var c={x:t.segpts[u],y:t.segpts[u+1]},d=t.roundCorners[u/2],h=[c.x-d.cx,c.y-d.cy],p=d.radius/Math.sqrt(Math.pow(h[0],2)+Math.pow(h[1],2));h=h.map((function(e){return e*p})),t.midX=d.cx+h[0],t.midY=d.cy+h[1],t.midVector=h}else t.midX=t.segpts[u],t.midY=t.segpts[u+1]}}},eu.checkForInvalidEdgeWarning=function(e){var t=e[0]._private.rscratch;t.nodesOverlap||x(t.startX)&&x(t.startY)&&x(t.endX)&&x(t.endY)?t.loggedErr=!1:t.loggedErr||(t.loggedErr=!0,je("Edge `"+e.id()+"` has invalid endpoints and so it is impossible to draw. Adjust your edge style (e.g. control points) accordingly or use an alternative edge type. This is expected behaviour when the source node and the target node overlap."))},eu.findEdgeControlPoints=function(e){var t=this;if(e&&0!==e.length){for(var n=this,r=n.cy.hasCompoundNodes(),i={map:new $e,get:function(e){var t=this.map.get(e[0]);return null!=t?t.get(e[1]):null},set:function(e,t){var n=this.map.get(e[0]);null==n&&(n=new $e,this.map.set(e[0],n)),n.set(e[1],t)}},a=[],o=[],s=0;s<e.length;s++){var l=e[s],u=l._private,c=l.pstyle("curve-style").value;if(!l.removed()&&l.takesUpSpace())if("haystack"!==c){var d="unbundled-bezier"===c||c.endsWith("segments")||"straight"===c||"straight-triangle"===c||c.endsWith("taxi"),h="unbundled-bezier"===c||"bezier"===c,p=u.source,f=u.target,g=[p.poolIndex(),f.poolIndex()].sort(),v=i.get(g);null==v&&(v={eles:[]},i.set(g,v),a.push(g)),v.eles.push(l),d&&(v.hasUnbundled=!0),h&&(v.hasBezier=!0)}else o.push(l)}for(var y=function(e){var o=a[e],s=i.get(o),l=void 0;if(!s.hasUnbundled){var u=s.eles[0].parallelEdges().filter((function(e){return e.isBundledBezier()}));Ge(s.eles),u.forEach((function(e){return s.eles.push(e)})),s.eles.sort((function(e,t){return e.poolIndex()-t.poolIndex()}))}var c=s.eles[0],d=c.source(),h=c.target();if(d.poolIndex()>h.poolIndex()){var p=d;d=h,h=p}var f=s.srcPos=d.position(),g=s.tgtPos=h.position(),v=s.srcW=d.outerWidth(),y=s.srcH=d.outerHeight(),m=s.tgtW=h.outerWidth(),b=s.tgtH=h.outerHeight(),w=s.srcShape=n.nodeShapes[t.getNodeShape(d)],E=s.tgtShape=n.nodeShapes[t.getNodeShape(h)],k=s.srcCornerRadius="auto"===d.pstyle("corner-radius").value?"auto":d.pstyle("corner-radius").pfValue,C=s.tgtCornerRadius="auto"===h.pstyle("corner-radius").value?"auto":h.pstyle("corner-radius").pfValue,S=s.tgtRs=h._private.rscratch,P=s.srcRs=d._private.rscratch;s.dirCounts={north:0,west:0,south:0,east:0,northwest:0,southwest:0,northeast:0,southeast:0};for(var D=0;D<s.eles.length;D++){var T=s.eles[D],_=T[0]._private.rscratch,M=T.pstyle("curve-style").value,B="unbundled-bezier"===M||M.endsWith("segments")||M.endsWith("taxi"),N=!d.same(T.source());if(!s.calculatedIntersection&&d!==h&&(s.hasBezier||s.hasUnbundled)){s.calculatedIntersection=!0;var z=w.intersectLine(f.x,f.y,v,y,g.x,g.y,0,k,P),I=s.srcIntn=z,A=E.intersectLine(g.x,g.y,m,b,f.x,f.y,0,C,S),L=s.tgtIntn=A,O=s.intersectionPts={x1:z[0],x2:A[0],y1:z[1],y2:A[1]},R=s.posPts={x1:f.x,x2:g.x,y1:f.y,y2:g.y},V=A[1]-z[1],F=A[0]-z[0],j=Math.sqrt(F*F+V*V),q=s.vector={x:F,y:V},Y=s.vectorNorm={x:q.x/j,y:q.y/j},X={x:-Y.y,y:Y.x};s.nodesOverlap=!x(j)||E.checkPoint(z[0],z[1],0,m,b,g.x,g.y,C,S)||w.checkPoint(A[0],A[1],0,v,y,f.x,f.y,k,P),s.vectorNormInverse=X,l={nodesOverlap:s.nodesOverlap,dirCounts:s.dirCounts,calculatedIntersection:!0,hasBezier:s.hasBezier,hasUnbundled:s.hasUnbundled,eles:s.eles,srcPos:g,tgtPos:f,srcW:m,srcH:b,tgtW:v,tgtH:y,srcIntn:L,tgtIntn:I,srcShape:E,tgtShape:w,posPts:{x1:R.x2,y1:R.y2,x2:R.x1,y2:R.y1},intersectionPts:{x1:O.x2,y1:O.y2,x2:O.x1,y2:O.y1},vector:{x:-q.x,y:-q.y},vectorNorm:{x:-Y.x,y:-Y.y},vectorNormInverse:{x:-X.x,y:-X.y}}}var W=N?l:s;_.nodesOverlap=W.nodesOverlap,_.srcIntn=W.srcIntn,_.tgtIntn=W.tgtIntn,_.isRound=M.startsWith("round"),r&&(d.isParent()||d.isChild()||h.isParent()||h.isChild())&&(d.parents().anySame(h)||h.parents().anySame(d)||d.same(h)&&d.isParent())?t.findCompoundLoopPoints(T,W,D,B):d===h?t.findLoopPoints(T,W,D,B):M.endsWith("segments")?t.findSegmentsPoints(T,W):M.endsWith("taxi")?t.findTaxiPoints(T,W):"straight"===M||!B&&s.eles.length%2==1&&D===Math.floor(s.eles.length/2)?t.findStraightEdgePoints(T):t.findBezierPoints(T,W,D,B,N),t.findEndpoints(T),t.tryToCorrectInvalidPoints(T,W),t.checkForInvalidEdgeWarning(T),t.storeAllpts(T),t.storeEdgeProjections(T),t.calculateArrowAngles(T),t.recalculateEdgeLabelProjections(T),t.calculateLabelAngles(T)}},m=0;m<a.length;m++)y(m);this.findHaystackPoints(o)}},eu.getSegmentPoints=function(e){var t=e[0]._private.rscratch;if("segments"===t.edgeType)return this.recalculateRenderedStyle(e),tu(t.segpts)},eu.getControlPoints=function(e){var t=e[0]._private.rscratch,n=t.edgeType;if("bezier"===n||"multibezier"===n||"self"===n||"compound"===n)return this.recalculateRenderedStyle(e),tu(t.ctrlpts)},eu.getEdgeMidpoint=function(e){var t=e[0]._private.rscratch;return this.recalculateRenderedStyle(e),{x:t.midX,y:t.midY}};var nu={manualEndptToPx:function(e,t){var n=e.position(),r=e.outerWidth(),i=e.outerHeight(),a=e._private.rscratch;if(2===t.value.length){var o=[t.pfValue[0],t.pfValue[1]];return"%"===t.units[0]&&(o[0]=o[0]*r),"%"===t.units[1]&&(o[1]=o[1]*i),o[0]+=n.x,o[1]+=n.y,o}var s=t.pfValue[0];s=-Math.PI/2+s;var l=2*Math.max(r,i),u=[n.x+Math.cos(s)*l,n.y+Math.sin(s)*l];return this.nodeShapes[this.getNodeShape(e)].intersectLine(n.x,n.y,r,i,u[0],u[1],0,"auto"===e.pstyle("corner-radius").value?"auto":e.pstyle("corner-radius").pfValue,a)},findEndpoints:function(e){var t,n,r,i,a,o=this,s=e.source()[0],l=e.target()[0],u=s.position(),c=l.position(),d=e.pstyle("target-arrow-shape").value,h=e.pstyle("source-arrow-shape").value,p=e.pstyle("target-distance-from-node").pfValue,f=e.pstyle("source-distance-from-node").pfValue,g=s._private.rscratch,v=l._private.rscratch,y=e.pstyle("curve-style").value,m=e._private.rscratch,b=m.edgeType,w="self"===b||"compound"===b,E="bezier"===b||"multibezier"===b||w,k="bezier"!==b,C="straight"===b||"segments"===b,S="segments"===b,P=E||k||C,D=w||"taxi"===y,T=e.pstyle("source-endpoint"),_=D?"outside-to-node":T.value,M="auto"===s.pstyle("corner-radius").value?"auto":s.pstyle("corner-radius").pfValue,B=e.pstyle("target-endpoint"),N=D?"outside-to-node":B.value,z="auto"===l.pstyle("corner-radius").value?"auto":l.pstyle("corner-radius").pfValue;if(m.srcManEndpt=T,m.tgtManEndpt=B,E){var I=[m.ctrlpts[0],m.ctrlpts[1]];n=k?[m.ctrlpts[m.ctrlpts.length-2],m.ctrlpts[m.ctrlpts.length-1]]:I,r=I}else if(C){var A=S?m.segpts.slice(0,2):[c.x,c.y];n=S?m.segpts.slice(m.segpts.length-2):[u.x,u.y],r=A}if("inside-to-node"===N)t=[c.x,c.y];else if(B.units)t=this.manualEndptToPx(l,B);else if("outside-to-line"===N)t=m.tgtIntn;else if("outside-to-node"===N||"outside-to-node-or-label"===N?i=n:"outside-to-line"!==N&&"outside-to-line-or-label"!==N||(i=[u.x,u.y]),t=o.nodeShapes[this.getNodeShape(l)].intersectLine(c.x,c.y,l.outerWidth(),l.outerHeight(),i[0],i[1],0,z,v),"outside-to-node-or-label"===N||"outside-to-line-or-label"===N){var L=l._private.rscratch,O=L.labelWidth,R=L.labelHeight,V=L.labelX,F=L.labelY,j=O/2,q=R/2,Y=l.pstyle("text-valign").value;"top"===Y?F-=q:"bottom"===Y&&(F+=q);var X=l.pstyle("text-halign").value;"left"===X?V-=j:"right"===X&&(V+=j);var W=$t(i[0],i[1],[V-j,F-q,V+j,F-q,V+j,F+q,V-j,F+q],c.x,c.y);if(W.length>0){var H=u,K=Ct(H,bt(t)),G=Ct(H,bt(W)),U=K;if(G<K&&(t=W,U=G),W.length>2)Ct(H,{x:W[2],y:W[3]})<U&&(t=[W[2],W[3]])}}var Z=Qt(t,n,o.arrowShapes[d].spacing(e)+p),$=Qt(t,n,o.arrowShapes[d].gap(e)+p);if(m.endX=$[0],m.endY=$[1],m.arrowEndX=Z[0],m.arrowEndY=Z[1],"inside-to-node"===_)t=[u.x,u.y];else if(T.units)t=this.manualEndptToPx(s,T);else if("outside-to-line"===_)t=m.srcIntn;else if("outside-to-node"===_||"outside-to-node-or-label"===_?a=r:"outside-to-line"!==_&&"outside-to-line-or-label"!==_||(a=[c.x,c.y]),t=o.nodeShapes[this.getNodeShape(s)].intersectLine(u.x,u.y,s.outerWidth(),s.outerHeight(),a[0],a[1],0,M,g),"outside-to-node-or-label"===_||"outside-to-line-or-label"===_){var Q=s._private.rscratch,J=Q.labelWidth,ee=Q.labelHeight,te=Q.labelX,ne=Q.labelY,re=J/2,ie=ee/2,ae=s.pstyle("text-valign").value;"top"===ae?ne-=ie:"bottom"===ae&&(ne+=ie);var oe=s.pstyle("text-halign").value;"left"===oe?te-=re:"right"===oe&&(te+=re);var se=$t(a[0],a[1],[te-re,ne-ie,te+re,ne-ie,te+re,ne+ie,te-re,ne+ie],u.x,u.y);if(se.length>0){var le=c,ue=Ct(le,bt(t)),ce=Ct(le,bt(se)),de=ue;if(ce<ue&&(t=[se[0],se[1]],de=ce),se.length>2)Ct(le,{x:se[2],y:se[3]})<de&&(t=[se[2],se[3]])}}var he=Qt(t,r,o.arrowShapes[h].spacing(e)+f),pe=Qt(t,r,o.arrowShapes[h].gap(e)+f);m.startX=pe[0],m.startY=pe[1],m.arrowStartX=he[0],m.arrowStartY=he[1],P&&(x(m.startX)&&x(m.startY)&&x(m.endX)&&x(m.endY)?m.badLine=!1:m.badLine=!0)},getSourceEndpoint:function(e){var t=e[0]._private.rscratch;switch(this.recalculateRenderedStyle(e),t.edgeType){case"haystack":return{x:t.haystackPts[0],y:t.haystackPts[1]};default:return{x:t.arrowStartX,y:t.arrowStartY}}},getTargetEndpoint:function(e){var t=e[0]._private.rscratch;switch(this.recalculateRenderedStyle(e),t.edgeType){case"haystack":return{x:t.haystackPts[2],y:t.haystackPts[3]};default:return{x:t.arrowEndX,y:t.arrowEndY}}}},ru={};function iu(e,t,n){for(var r=function(e,t,n,r){return Pt(e,t,n,r)},i=t._private.rstyle.bezierPts,a=0;a<e.bezierProjPcts.length;a++){var o=e.bezierProjPcts[a];i.push({x:r(n[0],n[2],n[4],o),y:r(n[1],n[3],n[5],o)})}}ru.storeEdgeProjections=function(e){var t=e._private,n=t.rscratch,r=n.edgeType;if(t.rstyle.bezierPts=null,t.rstyle.linePts=null,t.rstyle.haystackPts=null,"multibezier"===r||"bezier"===r||"self"===r||"compound"===r){t.rstyle.bezierPts=[];for(var i=0;i+5<n.allpts.length;i+=4)iu(this,e,n.allpts.slice(i,i+6))}else if("segments"===r){var a=t.rstyle.linePts=[];for(i=0;i+1<n.allpts.length;i+=2)a.push({x:n.allpts[i],y:n.allpts[i+1]})}else if("haystack"===r){var o=n.haystackPts;t.rstyle.haystackPts=[{x:o[0],y:o[1]},{x:o[2],y:o[3]}]}t.rstyle.arrowWidth=this.getArrowWidth(e.pstyle("width").pfValue,e.pstyle("arrow-scale").value)*this.arrowShapeWidth},ru.recalculateEdgeProjections=function(e){this.findEdgeControlPoints(e)};var au={recalculateNodeLabelProjection:function(e){var t=e.pstyle("label").strValue;if(!D(t)){var n,r,i=e._private,a=e.width(),o=e.height(),s=e.padding(),l=e.position(),u=e.pstyle("text-halign").strValue,c=e.pstyle("text-valign").strValue,d=i.rscratch,h=i.rstyle;switch(u){case"left":n=l.x-a/2-s;break;case"right":n=l.x+a/2+s;break;default:n=l.x}switch(c){case"top":r=l.y-o/2-s;break;case"bottom":r=l.y+o/2+s;break;default:r=l.y}d.labelX=n,d.labelY=r,h.labelX=n,h.labelY=r,this.calculateLabelAngles(e),this.applyLabelDimensions(e)}}},ou=function(e,t){var n=Math.atan(t/e);return 0===e&&n<0&&(n*=-1),n},su=function(e,t){var n=t.x-e.x,r=t.y-e.y;return ou(n,r)};au.recalculateEdgeLabelProjections=function(e){var t,n=e._private,r=n.rscratch,i=this,a={mid:e.pstyle("label").strValue,source:e.pstyle("source-label").strValue,target:e.pstyle("target-label").strValue};if(a.mid||a.source||a.target){t={x:r.midX,y:r.midY};var o=function(e,t,r){Ze(n.rscratch,e,t,r),Ze(n.rstyle,e,t,r)};o("labelX",null,t.x),o("labelY",null,t.y);var s=ou(r.midDispX,r.midDispY);o("labelAutoAngle",null,s);var l=function(s){var l,u="source"===s;if(a[s]){var c=e.pstyle(s+"-text-offset").pfValue;switch(r.edgeType){case"self":case"compound":case"bezier":case"multibezier":for(var d,h=function e(){if(e.cache)return e.cache;for(var t=[],a=0;a+5<r.allpts.length;a+=4){var o={x:r.allpts[a],y:r.allpts[a+1]},s={x:r.allpts[a+2],y:r.allpts[a+3]},l={x:r.allpts[a+4],y:r.allpts[a+5]};t.push({p0:o,p1:s,p2:l,startDist:0,length:0,segments:[]})}var u=n.rstyle.bezierPts,c=i.bezierProjPcts.length;function d(e,t,n,r,i){var a=kt(t,n),o=e.segments[e.segments.length-1],s={p0:t,p1:n,t0:r,t1:i,startDist:o?o.startDist+o.length:0,length:a};e.segments.push(s),e.length+=a}for(var h=0;h<t.length;h++){var p=t[h],f=t[h-1];f&&(p.startDist=f.startDist+f.length),d(p,p.p0,u[h*c],0,i.bezierProjPcts[0]);for(var g=0;g<c-1;g++)d(p,u[h*c+g],u[h*c+g+1],i.bezierProjPcts[g],i.bezierProjPcts[g+1]);d(p,u[h*c+c-1],p.p2,i.bezierProjPcts[c-1],1)}return e.cache=t}(),p=0,f=0,g=0;g<h.length;g++){for(var v=h[u?g:h.length-1-g],y=0;y<v.segments.length;y++){var m=v.segments[u?y:v.segments.length-1-y],b=g===h.length-1&&y===v.segments.length-1;if(p=f,(f+=m.length)>=c||b){d={cp:v,segment:m};break}}if(d)break}var x=d.cp,w=d.segment,E=(c-p)/w.length,k=w.t1-w.t0,C=u?w.t0+k*E:w.t1-k*E;C=Tt(0,C,1),t=Dt(x.p0,x.p1,x.p2,C),l=function(e,t,n,r){var i=Tt(0,r-.001,1),a=Tt(0,r+.001,1),o=Dt(e,t,n,i),s=Dt(e,t,n,a);return su(o,s)}(x.p0,x.p1,x.p2,C);break;case"straight":case"segments":case"haystack":for(var S,P,D,T,_=0,M=r.allpts.length,B=0;B+3<M&&(u?(D={x:r.allpts[B],y:r.allpts[B+1]},T={x:r.allpts[B+2],y:r.allpts[B+3]}):(D={x:r.allpts[M-2-B],y:r.allpts[M-1-B]},T={x:r.allpts[M-4-B],y:r.allpts[M-3-B]}),P=_,!((_+=S=kt(D,T))>=c));B+=2);var N=(c-P)/S;N=Tt(0,N,1),t=function(e,t,n,r){var i=t.x-e.x,a=t.y-e.y,o=kt(e,t),s=i/o,l=a/o;return n=null==n?0:n,r=null!=r?r:n*o,{x:e.x+s*r,y:e.y+l*r}}(D,T,N),l=su(D,T)}o("labelX",s,t.x),o("labelY",s,t.y),o("labelAutoAngle",s,l)}};l("source"),l("target"),this.applyLabelDimensions(e)}},au.applyLabelDimensions=function(e){this.applyPrefixedLabelDimensions(e),e.isEdge()&&(this.applyPrefixedLabelDimensions(e,"source"),this.applyPrefixedLabelDimensions(e,"target"))},au.applyPrefixedLabelDimensions=function(e,t){var n=e._private,r=this.getLabelText(e,t),i=this.calculateLabelDimensions(e,r),a=e.pstyle("line-height").pfValue,o=e.pstyle("text-wrap").strValue,s=Ue(n.rscratch,"labelWrapCachedLines",t)||[],l="wrap"!==o?1:Math.max(s.length,1),u=i.height/l,c=u*a,d=i.width,h=i.height+(l-1)*(a-1)*u;Ze(n.rstyle,"labelWidth",t,d),Ze(n.rscratch,"labelWidth",t,d),Ze(n.rstyle,"labelHeight",t,h),Ze(n.rscratch,"labelHeight",t,h),Ze(n.rscratch,"labelLineHeight",t,c)},au.getLabelText=function(e,t){var n=e._private,r=t?t+"-":"",i=e.pstyle(r+"label").strValue,a=e.pstyle("text-transform").value,o=function(e,r){return r?(Ze(n.rscratch,e,t,r),r):Ue(n.rscratch,e,t)};if(!i)return"";"none"==a||("uppercase"==a?i=i.toUpperCase():"lowercase"==a&&(i=i.toLowerCase()));var s=e.pstyle("text-wrap").value;if("wrap"===s){var u=o("labelKey");if(null!=u&&o("labelWrapKey")===u)return o("labelWrapCachedText");for(var c=i.split("\n"),d=e.pstyle("text-max-width").pfValue,h="anywhere"===e.pstyle("text-overflow-wrap").value,p=[],f=/[\s\u200b]+|$/g,g=0;g<c.length;g++){var v=c[g],y=this.calculateLabelDimensions(e,v).width;if(h){var m=v.split("").join("​");v=m}if(y>d){var b,x="",w=0,E=l(v.matchAll(f));try{for(E.s();!(b=E.n()).done;){var k=b.value,C=k[0],S=v.substring(w,k.index);w=k.index+C.length;var P=0===x.length?S:x+S+C;this.calculateLabelDimensions(e,P).width<=d?x+=S+C:(x&&p.push(x),x=S+C)}}catch(e){E.e(e)}finally{E.f()}x.match(/^[\s\u200b]+$/)||p.push(x)}else p.push(v)}o("labelWrapCachedLines",p),i=o("labelWrapCachedText",p.join("\n")),o("labelWrapKey",u)}else if("ellipsis"===s){var D=e.pstyle("text-max-width").pfValue,T="",_=!1;if(this.calculateLabelDimensions(e,i).width<D)return i;for(var M=0;M<i.length;M++){if(this.calculateLabelDimensions(e,T+i[M]+"…").width>D)break;T+=i[M],M===i.length-1&&(_=!0)}return _||(T+="…"),T}return i},au.getLabelJustification=function(e){var t=e.pstyle("text-justification").strValue,n=e.pstyle("text-halign").strValue;if("auto"!==t)return t;if(!e.isNode())return"center";switch(n){case"left":return"right";case"right":return"left";default:return"center"}},au.calculateLabelDimensions=function(e,t){var n=this,r=n.cy.window().document,i=Te(t,e._private.labelDimsKey),a=n.labelDimCache||(n.labelDimCache=[]),o=a[i];if(null!=o)return o;var s=e.pstyle("font-style").strValue,l=e.pstyle("font-size").pfValue,u=e.pstyle("font-family").strValue,c=e.pstyle("font-weight").strValue,d=this.labelCalcCanvas,h=this.labelCalcCanvasContext;if(!d){d=this.labelCalcCanvas=r.createElement("canvas"),h=this.labelCalcCanvasContext=d.getContext("2d");var p=d.style;p.position="absolute",p.left="-9999px",p.top="-9999px",p.zIndex="-1",p.visibility="hidden",p.pointerEvents="none"}h.font="".concat(s," ").concat(c," ").concat(l,"px ").concat(u);for(var f=0,g=0,v=t.split("\n"),y=0;y<v.length;y++){var m=v[y],b=h.measureText(m),x=Math.ceil(b.width),w=l;f=Math.max(x,f),g+=w}return f+=0,g+=0,a[i]={width:f,height:g}},au.calculateLabelAngle=function(e,t){var n=e._private.rscratch,r=e.isEdge(),i=t?t+"-":"",a=e.pstyle(i+"text-rotation"),o=a.strValue;return"none"===o?0:r&&"autorotate"===o?n.labelAutoAngle:"autorotate"===o?0:a.pfValue},au.calculateLabelAngles=function(e){var t=this,n=e.isEdge(),r=e._private.rscratch;r.labelAngle=t.calculateLabelAngle(e),n&&(r.sourceLabelAngle=t.calculateLabelAngle(e,"source"),r.targetLabelAngle=t.calculateLabelAngle(e,"target"))};var lu={},uu=!1;lu.getNodeShape=function(e){var t=e.pstyle("shape").value;if("cutrectangle"===t&&(e.width()<28||e.height()<28))return uu||(je("The `cutrectangle` node shape can not be used at small sizes so `rectangle` is used instead"),uu=!0),"rectangle";if(e.isParent())return"rectangle"===t||"roundrectangle"===t||"round-rectangle"===t||"cutrectangle"===t||"cut-rectangle"===t||"barrel"===t?t:"rectangle";if("polygon"===t){var n=e.pstyle("shape-polygon-points").value;return this.nodeShapes.makePolygon(n).name}return t};var cu={registerCalculationListeners:function(){var e=this.cy,t=e.collection(),n=this,r=function(e){var n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(t.merge(e),n)for(var r=0;r<e.length;r++){var i=e[r],a=i._private,o=a.rstyle;o.clean=!1,o.cleanConnected=!1}};n.binder(e).on("bounds.* dirty.*",(function(e){var t=e.target;r(t)})).on("style.* background.*",(function(e){var t=e.target;r(t,!1)}));var i=function(i){if(i){var a=n.onUpdateEleCalcsFns;t.cleanStyle();for(var o=0;o<t.length;o++){var s=t[o],l=s._private.rstyle;s.isNode()&&!l.cleanConnected&&(r(s.connectedEdges()),l.cleanConnected=!0)}if(a)for(var u=0;u<a.length;u++){(0,a[u])(i,t)}n.recalculateRenderedStyle(t),t=e.collection()}};n.flushRenderedStyleQueue=function(){i(!0)},n.beforeRender(i,n.beforeRenderPriorities.eleCalcs)},onUpdateEleCalcs:function(e){(this.onUpdateEleCalcsFns=this.onUpdateEleCalcsFns||[]).push(e)},recalculateRenderedStyle:function(e,t){var n=function(e){return e._private.rstyle.cleanConnected},r=[],i=[];if(!this.destroyed){void 0===t&&(t=!0);for(var a=0;a<e.length;a++){var o=e[a],s=o._private,l=s.rstyle;!o.isEdge()||n(o.source())&&n(o.target())||(l.clean=!1),t&&l.clean||o.removed()||"none"!==o.pstyle("display").value&&("nodes"===s.group?i.push(o):r.push(o),l.clean=!0)}for(var u=0;u<i.length;u++){var c=i[u],d=c._private.rstyle,h=c.position();this.recalculateNodeLabelProjection(c),d.nodeX=h.x,d.nodeY=h.y,d.nodeW=c.pstyle("width").pfValue,d.nodeH=c.pstyle("height").pfValue}this.recalculateEdgeProjections(r);for(var p=0;p<r.length;p++){var f=r[p]._private,g=f.rstyle,v=f.rscratch;g.srcX=v.arrowStartX,g.srcY=v.arrowStartY,g.tgtX=v.arrowEndX,g.tgtY=v.arrowEndY,g.midX=v.midX,g.midY=v.midY,g.labelAngle=v.labelAngle,g.sourceLabelAngle=v.sourceLabelAngle,g.targetLabelAngle=v.targetLabelAngle}}}},du={updateCachedGrabbedEles:function(){var e=this.cachedZSortedEles;if(e){e.drag=[],e.nondrag=[];for(var t=[],n=0;n<e.length;n++){var r=(i=e[n])._private.rscratch;i.grabbed()&&!i.isParent()?t.push(i):r.inDragLayer?e.drag.push(i):e.nondrag.push(i)}for(n=0;n<t.length;n++){var i=t[n];e.drag.push(i)}}},invalidateCachedZSortedEles:function(){this.cachedZSortedEles=null},getCachedZSortedEles:function(e){if(e||!this.cachedZSortedEles){var t=this.cy.mutableElements().toArray();t.sort(Mo),t.interactive=t.filter((function(e){return e.interactive()})),this.cachedZSortedEles=t,this.updateCachedGrabbedEles()}else t=this.cachedZSortedEles;return t}},hu={};[_l,Ml,eu,nu,ru,au,lu,cu,du].forEach((function(e){L(hu,e)}));var pu={getCachedImage:function(e,t,n){var r=this.imageCache=this.imageCache||{},i=r[e];if(i)return i.image.complete||i.image.addEventListener("load",n),i.image;var a=(i=r[e]=r[e]||{}).image=new Image;a.addEventListener("load",n),a.addEventListener("error",(function(){a.error=!0}));return"data:"===e.substring(0,"data:".length).toLowerCase()||(t="null"===t?null:t,a.crossOrigin=t),a.src=e,a}},fu={registerBinding:function(e,t,n,r){var i=Array.prototype.slice.apply(arguments,[1]),a=this.binder(e);return a.on.apply(a,i)}};fu.binder=function(e){var t,n=this,r=n.cy.window(),i=e===r||e===r.document||e===r.document.body||(t=e,"undefined"!=typeof HTMLElement&&t instanceof HTMLElement);if(null==n.supportsPassiveEvents){var a=!1;try{var o=Object.defineProperty({},"passive",{get:function(){return a=!0,!0}});r.addEventListener("test",null,o)}catch(e){}n.supportsPassiveEvents=a}var s=function(t,r,a){var o=Array.prototype.slice.call(arguments);return i&&n.supportsPassiveEvents&&(o[2]={capture:null!=a&&a,passive:!1,once:!1}),n.bindings.push({target:e,args:o}),(e.addEventListener||e.on).apply(e,o),this};return{on:s,addEventListener:s,addListener:s,bind:s}},fu.nodeIsDraggable=function(e){return e&&e.isNode()&&!e.locked()&&e.grabbable()},fu.nodeIsGrabbable=function(e){return this.nodeIsDraggable(e)&&e.interactive()},fu.load=function(){var e=this,t=e.cy.window(),n=function(e){return e.selected()},r=function(t,n,r,i){null==t&&(t=e.cy);for(var a=0;a<n.length;a++){var o=n[a];t.emit({originalEvent:r,type:o,position:i})}},i=function(e){return e.shiftKey||e.metaKey||e.ctrlKey},a=function(t,n){var r=!0;if(e.cy.hasCompoundNodes()&&t&&t.pannable())for(var i=0;n&&i<n.length;i++){if((t=n[i]).isNode()&&t.isParent()&&!t.pannable()){r=!1;break}}else r=!0;return r},o=function(e){e[0]._private.rscratch.inDragLayer=!0},s=function(e){e[0]._private.rscratch.isGrabTarget=!0},l=function(e,t){var n=t.addToList;n.has(e)||!e.grabbable()||e.locked()||(n.merge(e),function(e){e[0]._private.grabbed=!0}(e))},u=function(t,n){n=n||{};var r=t.cy().hasCompoundNodes();n.inDragLayer&&(t.forEach(o),t.neighborhood().stdFilter((function(e){return!r||e.isEdge()})).forEach(o)),n.addToList&&t.forEach((function(e){l(e,n)})),function(e,t){if(e.cy().hasCompoundNodes()&&(null!=t.inDragLayer||null!=t.addToList)){var n=e.descendants();t.inDragLayer&&(n.forEach(o),n.connectedEdges().forEach(o)),t.addToList&&l(n,t)}}(t,n),h(t,{inDragLayer:n.inDragLayer}),e.updateCachedGrabbedEles()},c=u,d=function(t){t&&(e.getCachedZSortedEles().forEach((function(e){!function(e){e[0]._private.grabbed=!1}(e),function(e){e[0]._private.rscratch.inDragLayer=!1}(e),function(e){e[0]._private.rscratch.isGrabTarget=!1}(e)})),e.updateCachedGrabbedEles())},h=function(e,t){if((null!=t.inDragLayer||null!=t.addToList)&&e.cy().hasCompoundNodes()){var n=e.ancestors().orphans();if(!n.same(e)){var r=n.descendants().spawnSelf().merge(n).unmerge(e).unmerge(e.descendants()),i=r.connectedEdges();t.inDragLayer&&(i.forEach(o),r.forEach(o)),t.addToList&&r.forEach((function(e){l(e,t)}))}}},p=function(){null!=document.activeElement&&null!=document.activeElement.blur&&document.activeElement.blur()},f="undefined"!=typeof MutationObserver,g="undefined"!=typeof ResizeObserver;f?(e.removeObserver=new MutationObserver((function(t){for(var n=0;n<t.length;n++){var r=t[n].removedNodes;if(r)for(var i=0;i<r.length;i++){if(r[i]===e.container){e.destroy();break}}}})),e.container.parentNode&&e.removeObserver.observe(e.container.parentNode,{childList:!0})):e.registerBinding(e.container,"DOMNodeRemoved",(function(t){e.destroy()}));var v=ve((function(){e.cy.resize()}),100);f&&(e.styleObserver=new MutationObserver(v),e.styleObserver.observe(e.container,{attributes:!0})),e.registerBinding(t,"resize",v),g&&(e.resizeObserver=new ResizeObserver(v),e.resizeObserver.observe(e.container));var y=function(){e.invalidateContainerClientCoordsCache()};!function(e,t){for(;null!=e;)t(e),e=e.parentNode}(e.container,(function(t){e.registerBinding(t,"transitionend",y),e.registerBinding(t,"animationend",y),e.registerBinding(t,"scroll",y)})),e.registerBinding(e.container,"contextmenu",(function(e){e.preventDefault()}));var m,b,w,E=function(t){for(var n=e.findContainerClientCoords(),r=n[0],i=n[1],a=n[2],o=n[3],s=t.touches?t.touches:[t],l=!1,u=0;u<s.length;u++){var c=s[u];if(r<=c.clientX&&c.clientX<=r+a&&i<=c.clientY&&c.clientY<=i+o){l=!0;break}}if(!l)return!1;for(var d=e.container,h=t.target.parentNode,p=!1;h;){if(h===d){p=!0;break}h=h.parentNode}return!!p};e.registerBinding(e.container,"mousedown",(function(t){if(E(t)&&(1!==e.hoverData.which||1===t.which)){t.preventDefault(),p(),e.hoverData.capture=!0,e.hoverData.which=t.which;var n=e.cy,i=[t.clientX,t.clientY],a=e.projectIntoViewport(i[0],i[1]),o=e.selection,l=e.findNearestElements(a[0],a[1],!0,!1),d=l[0],h=e.dragData.possibleDragElements;e.hoverData.mdownPos=a,e.hoverData.mdownGPos=i;if(3==t.which){e.hoverData.cxtStarted=!0;var f={originalEvent:t,type:"cxttapstart",position:{x:a[0],y:a[1]}};d?(d.activate(),d.emit(f),e.hoverData.down=d):n.emit(f),e.hoverData.downTime=(new Date).getTime(),e.hoverData.cxtDragged=!1}else if(1==t.which){if(d&&d.activate(),null!=d&&e.nodeIsGrabbable(d)){var g=function(e){return{originalEvent:t,type:e,position:{x:a[0],y:a[1]}}};if(s(d),d.selected()){h=e.dragData.possibleDragElements=n.collection();var v=n.$((function(t){return t.isNode()&&t.selected()&&e.nodeIsGrabbable(t)}));u(v,{addToList:h}),d.emit(g("grabon")),v.forEach((function(e){e.emit(g("grab"))}))}else h=e.dragData.possibleDragElements=n.collection(),c(d,{addToList:h}),d.emit(g("grabon")).emit(g("grab"));e.redrawHint("eles",!0),e.redrawHint("drag",!0)}e.hoverData.down=d,e.hoverData.downs=l,e.hoverData.downTime=(new Date).getTime(),r(d,["mousedown","tapstart","vmousedown"],t,{x:a[0],y:a[1]}),null==d?(o[4]=1,e.data.bgActivePosistion={x:a[0],y:a[1]},e.redrawHint("select",!0),e.redraw()):d.pannable()&&(o[4]=1),e.hoverData.tapholdCancelled=!1,clearTimeout(e.hoverData.tapholdTimeout),e.hoverData.tapholdTimeout=setTimeout((function(){if(!e.hoverData.tapholdCancelled){var r=e.hoverData.down;r?r.emit({originalEvent:t,type:"taphold",position:{x:a[0],y:a[1]}}):n.emit({originalEvent:t,type:"taphold",position:{x:a[0],y:a[1]}})}}),e.tapholdDuration)}o[0]=o[2]=a[0],o[1]=o[3]=a[1]}}),!1),e.registerBinding(t,"mousemove",(function(t){if(e.hoverData.capture||E(t)){var n=!1,o=e.cy,s=o.zoom(),l=[t.clientX,t.clientY],c=e.projectIntoViewport(l[0],l[1]),h=e.hoverData.mdownPos,p=e.hoverData.mdownGPos,f=e.selection,g=null;e.hoverData.draggingEles||e.hoverData.dragging||e.hoverData.selecting||(g=e.findNearestElement(c[0],c[1],!0,!1));var v,y=e.hoverData.last,m=e.hoverData.down,b=[c[0]-f[2],c[1]-f[3]],w=e.dragData.possibleDragElements;if(p){var k=l[0]-p[0],C=k*k,S=l[1]-p[1],P=C+S*S;e.hoverData.isOverThresholdDrag=v=P>=e.desktopTapThreshold2}var D=i(t);v&&(e.hoverData.tapholdCancelled=!0);n=!0,r(g,["mousemove","vmousemove","tapdrag"],t,{x:c[0],y:c[1]});var T=function(){e.data.bgActivePosistion=void 0,e.hoverData.selecting||o.emit({originalEvent:t,type:"boxstart",position:{x:c[0],y:c[1]}}),f[4]=1,e.hoverData.selecting=!0,e.redrawHint("select",!0),e.redraw()};if(3===e.hoverData.which){if(v){var _={originalEvent:t,type:"cxtdrag",position:{x:c[0],y:c[1]}};m?m.emit(_):o.emit(_),e.hoverData.cxtDragged=!0,e.hoverData.cxtOver&&g===e.hoverData.cxtOver||(e.hoverData.cxtOver&&e.hoverData.cxtOver.emit({originalEvent:t,type:"cxtdragout",position:{x:c[0],y:c[1]}}),e.hoverData.cxtOver=g,g&&g.emit({originalEvent:t,type:"cxtdragover",position:{x:c[0],y:c[1]}}))}}else if(e.hoverData.dragging){if(n=!0,o.panningEnabled()&&o.userPanningEnabled()){var M;if(e.hoverData.justStartedPan){var B=e.hoverData.mdownPos;M={x:(c[0]-B[0])*s,y:(c[1]-B[1])*s},e.hoverData.justStartedPan=!1}else M={x:b[0]*s,y:b[1]*s};o.panBy(M),o.emit("dragpan"),e.hoverData.dragged=!0}c=e.projectIntoViewport(t.clientX,t.clientY)}else if(1!=f[4]||null!=m&&!m.pannable()){if(m&&m.pannable()&&m.active()&&m.unactivate(),m&&m.grabbed()||g==y||(y&&r(y,["mouseout","tapdragout"],t,{x:c[0],y:c[1]}),g&&r(g,["mouseover","tapdragover"],t,{x:c[0],y:c[1]}),e.hoverData.last=g),m)if(v){if(o.boxSelectionEnabled()&&D)m&&m.grabbed()&&(d(w),m.emit("freeon"),w.emit("free"),e.dragData.didDrag&&(m.emit("dragfreeon"),w.emit("dragfree"))),T();else if(m&&m.grabbed()&&e.nodeIsDraggable(m)){var N=!e.dragData.didDrag;N&&e.redrawHint("eles",!0),e.dragData.didDrag=!0,e.hoverData.draggingEles||u(w,{inDragLayer:!0});var z={x:0,y:0};if(x(b[0])&&x(b[1])&&(z.x+=b[0],z.y+=b[1],N)){var I=e.hoverData.dragDelta;I&&x(I[0])&&x(I[1])&&(z.x+=I[0],z.y+=I[1])}e.hoverData.draggingEles=!0,w.silentShift(z).emit("position drag"),e.redrawHint("drag",!0),e.redraw()}}else!function(){var t=e.hoverData.dragDelta=e.hoverData.dragDelta||[];0===t.length?(t.push(b[0]),t.push(b[1])):(t[0]+=b[0],t[1]+=b[1])}();n=!0}else if(v){if(e.hoverData.dragging||!o.boxSelectionEnabled()||!D&&o.panningEnabled()&&o.userPanningEnabled()){if(!e.hoverData.selecting&&o.panningEnabled()&&o.userPanningEnabled()){a(m,e.hoverData.downs)&&(e.hoverData.dragging=!0,e.hoverData.justStartedPan=!0,f[4]=0,e.data.bgActivePosistion=bt(h),e.redrawHint("select",!0),e.redraw())}}else T();m&&m.pannable()&&m.active()&&m.unactivate()}return f[2]=c[0],f[3]=c[1],n?(t.stopPropagation&&t.stopPropagation(),t.preventDefault&&t.preventDefault(),!1):void 0}}),!1),e.registerBinding(t,"mouseup",(function(t){if((1!==e.hoverData.which||1===t.which||!e.hoverData.capture)&&e.hoverData.capture){e.hoverData.capture=!1;var a=e.cy,o=e.projectIntoViewport(t.clientX,t.clientY),s=e.selection,l=e.findNearestElement(o[0],o[1],!0,!1),u=e.dragData.possibleDragElements,c=e.hoverData.down,h=i(t);if(e.data.bgActivePosistion&&(e.redrawHint("select",!0),e.redraw()),e.hoverData.tapholdCancelled=!0,e.data.bgActivePosistion=void 0,c&&c.unactivate(),3===e.hoverData.which){var p={originalEvent:t,type:"cxttapend",position:{x:o[0],y:o[1]}};if(c?c.emit(p):a.emit(p),!e.hoverData.cxtDragged){var f={originalEvent:t,type:"cxttap",position:{x:o[0],y:o[1]}};c?c.emit(f):a.emit(f)}e.hoverData.cxtDragged=!1,e.hoverData.which=null}else if(1===e.hoverData.which){if(r(l,["mouseup","tapend","vmouseup"],t,{x:o[0],y:o[1]}),e.dragData.didDrag||e.hoverData.dragged||e.hoverData.selecting||e.hoverData.isOverThresholdDrag||(r(c,["click","tap","vclick"],t,{x:o[0],y:o[1]}),b=!1,t.timeStamp-w<=a.multiClickDebounceTime()?(m&&clearTimeout(m),b=!0,w=null,r(c,["dblclick","dbltap","vdblclick"],t,{x:o[0],y:o[1]})):(m=setTimeout((function(){b||r(c,["oneclick","onetap","voneclick"],t,{x:o[0],y:o[1]})}),a.multiClickDebounceTime()),w=t.timeStamp)),null!=c||e.dragData.didDrag||e.hoverData.selecting||e.hoverData.dragged||i(t)||(a.$(n).unselect(["tapunselect"]),u.length>0&&e.redrawHint("eles",!0),e.dragData.possibleDragElements=u=a.collection()),l!=c||e.dragData.didDrag||e.hoverData.selecting||null!=l&&l._private.selectable&&(e.hoverData.dragging||("additive"===a.selectionType()||h?l.selected()?l.unselect(["tapunselect"]):l.select(["tapselect"]):h||(a.$(n).unmerge(l).unselect(["tapunselect"]),l.select(["tapselect"]))),e.redrawHint("eles",!0)),e.hoverData.selecting){var g=a.collection(e.getAllInBox(s[0],s[1],s[2],s[3]));e.redrawHint("select",!0),g.length>0&&e.redrawHint("eles",!0),a.emit({type:"boxend",originalEvent:t,position:{x:o[0],y:o[1]}});var v=function(e){return e.selectable()&&!e.selected()};"additive"===a.selectionType()||h||a.$(n).unmerge(g).unselect(),g.emit("box").stdFilter(v).select().emit("boxselect"),e.redraw()}if(e.hoverData.dragging&&(e.hoverData.dragging=!1,e.redrawHint("select",!0),e.redrawHint("eles",!0),e.redraw()),!s[4]){e.redrawHint("drag",!0),e.redrawHint("eles",!0);var y=c&&c.grabbed();d(u),y&&(c.emit("freeon"),u.emit("free"),e.dragData.didDrag&&(c.emit("dragfreeon"),u.emit("dragfree")))}}s[4]=0,e.hoverData.down=null,e.hoverData.cxtStarted=!1,e.hoverData.draggingEles=!1,e.hoverData.selecting=!1,e.hoverData.isOverThresholdDrag=!1,e.dragData.didDrag=!1,e.hoverData.dragged=!1,e.hoverData.dragDelta=[],e.hoverData.mdownPos=null,e.hoverData.mdownGPos=null,e.hoverData.which=null}}),!1);var k,C,S,P,D,T,_,M,B,N,z,I,A,L=function(t){if(!e.scrollingPage){var n=e.cy,r=n.zoom(),i=n.pan(),a=e.projectIntoViewport(t.clientX,t.clientY),o=[a[0]*r+i.x,a[1]*r+i.y];if(e.hoverData.draggingEles||e.hoverData.dragging||e.hoverData.cxtStarted||0!==e.selection[4])t.preventDefault();else if(n.panningEnabled()&&n.userPanningEnabled()&&n.zoomingEnabled()&&n.userZoomingEnabled()){var s;t.preventDefault(),e.data.wheelZooming=!0,clearTimeout(e.data.wheelTimeout),e.data.wheelTimeout=setTimeout((function(){e.data.wheelZooming=!1,e.redrawHint("eles",!0),e.redraw()}),150),s=null!=t.deltaY?t.deltaY/-250:null!=t.wheelDeltaY?t.wheelDeltaY/1e3:t.wheelDelta/1e3,s*=e.wheelSensitivity,1===t.deltaMode&&(s*=33);var l=n.zoom()*Math.pow(10,s);"gesturechange"===t.type&&(l=e.gestureStartZoom*t.scale),n.zoom({level:l,renderedPosition:{x:o[0],y:o[1]}}),n.emit("gesturechange"===t.type?"pinchzoom":"scrollzoom")}}};e.registerBinding(e.container,"wheel",L,!0),e.registerBinding(t,"scroll",(function(t){e.scrollingPage=!0,clearTimeout(e.scrollingPageTimeout),e.scrollingPageTimeout=setTimeout((function(){e.scrollingPage=!1}),250)}),!0),e.registerBinding(e.container,"gesturestart",(function(t){e.gestureStartZoom=e.cy.zoom(),e.hasTouchStarted||t.preventDefault()}),!0),e.registerBinding(e.container,"gesturechange",(function(t){e.hasTouchStarted||L(t)}),!0),e.registerBinding(e.container,"mouseout",(function(t){var n=e.projectIntoViewport(t.clientX,t.clientY);e.cy.emit({originalEvent:t,type:"mouseout",position:{x:n[0],y:n[1]}})}),!1),e.registerBinding(e.container,"mouseover",(function(t){var n=e.projectIntoViewport(t.clientX,t.clientY);e.cy.emit({originalEvent:t,type:"mouseover",position:{x:n[0],y:n[1]}})}),!1);var O,R,V,F,j,q,Y,X=function(e,t,n,r){return Math.sqrt((n-e)*(n-e)+(r-t)*(r-t))},W=function(e,t,n,r){return(n-e)*(n-e)+(r-t)*(r-t)};if(e.registerBinding(e.container,"touchstart",O=function(t){if(e.hasTouchStarted=!0,E(t)){p(),e.touchData.capture=!0,e.data.bgActivePosistion=void 0;var n=e.cy,i=e.touchData.now,a=e.touchData.earlier;if(t.touches[0]){var o=e.projectIntoViewport(t.touches[0].clientX,t.touches[0].clientY);i[0]=o[0],i[1]=o[1]}if(t.touches[1]){o=e.projectIntoViewport(t.touches[1].clientX,t.touches[1].clientY);i[2]=o[0],i[3]=o[1]}if(t.touches[2]){o=e.projectIntoViewport(t.touches[2].clientX,t.touches[2].clientY);i[4]=o[0],i[5]=o[1]}if(t.touches[1]){e.touchData.singleTouchMoved=!0,d(e.dragData.touchDragEles);var l=e.findContainerClientCoords();B=l[0],N=l[1],z=l[2],I=l[3],k=t.touches[0].clientX-B,C=t.touches[0].clientY-N,S=t.touches[1].clientX-B,P=t.touches[1].clientY-N,A=0<=k&&k<=z&&0<=S&&S<=z&&0<=C&&C<=I&&0<=P&&P<=I;var h=n.pan(),f=n.zoom();D=X(k,C,S,P),T=W(k,C,S,P),M=[((_=[(k+S)/2,(C+P)/2])[0]-h.x)/f,(_[1]-h.y)/f];if(T<4e4&&!t.touches[2]){var g=e.findNearestElement(i[0],i[1],!0,!0),v=e.findNearestElement(i[2],i[3],!0,!0);return g&&g.isNode()?(g.activate().emit({originalEvent:t,type:"cxttapstart",position:{x:i[0],y:i[1]}}),e.touchData.start=g):v&&v.isNode()?(v.activate().emit({originalEvent:t,type:"cxttapstart",position:{x:i[0],y:i[1]}}),e.touchData.start=v):n.emit({originalEvent:t,type:"cxttapstart",position:{x:i[0],y:i[1]}}),e.touchData.start&&(e.touchData.start._private.grabbed=!1),e.touchData.cxt=!0,e.touchData.cxtDragged=!1,e.data.bgActivePosistion=void 0,void e.redraw()}}if(t.touches[2])n.boxSelectionEnabled()&&t.preventDefault();else if(t.touches[1]);else if(t.touches[0]){var y=e.findNearestElements(i[0],i[1],!0,!0),m=y[0];if(null!=m&&(m.activate(),e.touchData.start=m,e.touchData.starts=y,e.nodeIsGrabbable(m))){var b=e.dragData.touchDragEles=n.collection(),x=null;e.redrawHint("eles",!0),e.redrawHint("drag",!0),m.selected()?(x=n.$((function(t){return t.selected()&&e.nodeIsGrabbable(t)})),u(x,{addToList:b})):c(m,{addToList:b}),s(m);var w=function(e){return{originalEvent:t,type:e,position:{x:i[0],y:i[1]}}};m.emit(w("grabon")),x?x.forEach((function(e){e.emit(w("grab"))})):m.emit(w("grab"))}r(m,["touchstart","tapstart","vmousedown"],t,{x:i[0],y:i[1]}),null==m&&(e.data.bgActivePosistion={x:o[0],y:o[1]},e.redrawHint("select",!0),e.redraw()),e.touchData.singleTouchMoved=!1,e.touchData.singleTouchStartTime=+new Date,clearTimeout(e.touchData.tapholdTimeout),e.touchData.tapholdTimeout=setTimeout((function(){!1!==e.touchData.singleTouchMoved||e.pinching||e.touchData.selecting||r(e.touchData.start,["taphold"],t,{x:i[0],y:i[1]})}),e.tapholdDuration)}if(t.touches.length>=1){for(var L=e.touchData.startPosition=[null,null,null,null,null,null],O=0;O<i.length;O++)L[O]=a[O]=i[O];var R=t.touches[0];e.touchData.startGPosition=[R.clientX,R.clientY]}}},!1),e.registerBinding(t,"touchmove",R=function(t){var n=e.touchData.capture;if(n||E(t)){var i=e.selection,o=e.cy,s=e.touchData.now,l=e.touchData.earlier,c=o.zoom();if(t.touches[0]){var h=e.projectIntoViewport(t.touches[0].clientX,t.touches[0].clientY);s[0]=h[0],s[1]=h[1]}if(t.touches[1]){h=e.projectIntoViewport(t.touches[1].clientX,t.touches[1].clientY);s[2]=h[0],s[3]=h[1]}if(t.touches[2]){h=e.projectIntoViewport(t.touches[2].clientX,t.touches[2].clientY);s[4]=h[0],s[5]=h[1]}var p,f=e.touchData.startGPosition;if(n&&t.touches[0]&&f){for(var g=[],v=0;v<s.length;v++)g[v]=s[v]-l[v];var y=t.touches[0].clientX-f[0],m=y*y,b=t.touches[0].clientY-f[1];p=m+b*b>=e.touchTapThreshold2}if(n&&e.touchData.cxt){t.preventDefault();var w=t.touches[0].clientX-B,_=t.touches[0].clientY-N,z=t.touches[1].clientX-B,I=t.touches[1].clientY-N,L=W(w,_,z,I);if(L/T>=2.25||L>=22500){e.touchData.cxt=!1,e.data.bgActivePosistion=void 0,e.redrawHint("select",!0);var O={originalEvent:t,type:"cxttapend",position:{x:s[0],y:s[1]}};e.touchData.start?(e.touchData.start.unactivate().emit(O),e.touchData.start=null):o.emit(O)}}if(n&&e.touchData.cxt){O={originalEvent:t,type:"cxtdrag",position:{x:s[0],y:s[1]}};e.data.bgActivePosistion=void 0,e.redrawHint("select",!0),e.touchData.start?e.touchData.start.emit(O):o.emit(O),e.touchData.start&&(e.touchData.start._private.grabbed=!1),e.touchData.cxtDragged=!0;var R=e.findNearestElement(s[0],s[1],!0,!0);e.touchData.cxtOver&&R===e.touchData.cxtOver||(e.touchData.cxtOver&&e.touchData.cxtOver.emit({originalEvent:t,type:"cxtdragout",position:{x:s[0],y:s[1]}}),e.touchData.cxtOver=R,R&&R.emit({originalEvent:t,type:"cxtdragover",position:{x:s[0],y:s[1]}}))}else if(n&&t.touches[2]&&o.boxSelectionEnabled())t.preventDefault(),e.data.bgActivePosistion=void 0,this.lastThreeTouch=+new Date,e.touchData.selecting||o.emit({originalEvent:t,type:"boxstart",position:{x:s[0],y:s[1]}}),e.touchData.selecting=!0,e.touchData.didSelect=!0,i[4]=1,i&&0!==i.length&&void 0!==i[0]?(i[2]=(s[0]+s[2]+s[4])/3,i[3]=(s[1]+s[3]+s[5])/3):(i[0]=(s[0]+s[2]+s[4])/3,i[1]=(s[1]+s[3]+s[5])/3,i[2]=(s[0]+s[2]+s[4])/3+1,i[3]=(s[1]+s[3]+s[5])/3+1),e.redrawHint("select",!0),e.redraw();else if(n&&t.touches[1]&&!e.touchData.didSelect&&o.zoomingEnabled()&&o.panningEnabled()&&o.userZoomingEnabled()&&o.userPanningEnabled()){if(t.preventDefault(),e.data.bgActivePosistion=void 0,e.redrawHint("select",!0),ee=e.dragData.touchDragEles){e.redrawHint("drag",!0);for(var V=0;V<ee.length;V++){var F=ee[V]._private;F.grabbed=!1,F.rscratch.inDragLayer=!1}}var j=e.touchData.start,q=(w=t.touches[0].clientX-B,_=t.touches[0].clientY-N,z=t.touches[1].clientX-B,I=t.touches[1].clientY-N,X(w,_,z,I)),Y=q/D;if(A){var H=(w-k+(z-S))/2,K=(_-C+(I-P))/2,G=o.zoom(),U=G*Y,Z=o.pan(),$=M[0]*G+Z.x,Q=M[1]*G+Z.y,J={x:-U/G*($-Z.x-H)+$,y:-U/G*(Q-Z.y-K)+Q};if(j&&j.active()){var ee=e.dragData.touchDragEles;d(ee),e.redrawHint("drag",!0),e.redrawHint("eles",!0),j.unactivate().emit("freeon"),ee.emit("free"),e.dragData.didDrag&&(j.emit("dragfreeon"),ee.emit("dragfree"))}o.viewport({zoom:U,pan:J,cancelOnFailedZoom:!0}),o.emit("pinchzoom"),D=q,k=w,C=_,S=z,P=I,e.pinching=!0}if(t.touches[0]){h=e.projectIntoViewport(t.touches[0].clientX,t.touches[0].clientY);s[0]=h[0],s[1]=h[1]}if(t.touches[1]){h=e.projectIntoViewport(t.touches[1].clientX,t.touches[1].clientY);s[2]=h[0],s[3]=h[1]}if(t.touches[2]){h=e.projectIntoViewport(t.touches[2].clientX,t.touches[2].clientY);s[4]=h[0],s[5]=h[1]}}else if(t.touches[0]&&!e.touchData.didSelect){var te=e.touchData.start,ne=e.touchData.last;if(e.hoverData.draggingEles||e.swipePanning||(R=e.findNearestElement(s[0],s[1],!0,!0)),n&&null!=te&&t.preventDefault(),n&&null!=te&&e.nodeIsDraggable(te))if(p){ee=e.dragData.touchDragEles;var re=!e.dragData.didDrag;re&&u(ee,{inDragLayer:!0}),e.dragData.didDrag=!0;var ie={x:0,y:0};if(x(g[0])&&x(g[1]))if(ie.x+=g[0],ie.y+=g[1],re)e.redrawHint("eles",!0),(ae=e.touchData.dragDelta)&&x(ae[0])&&x(ae[1])&&(ie.x+=ae[0],ie.y+=ae[1]);e.hoverData.draggingEles=!0,ee.silentShift(ie).emit("position drag"),e.redrawHint("drag",!0),e.touchData.startPosition[0]==l[0]&&e.touchData.startPosition[1]==l[1]&&e.redrawHint("eles",!0),e.redraw()}else{var ae;0===(ae=e.touchData.dragDelta=e.touchData.dragDelta||[]).length?(ae.push(g[0]),ae.push(g[1])):(ae[0]+=g[0],ae[1]+=g[1])}if(r(te||R,["touchmove","tapdrag","vmousemove"],t,{x:s[0],y:s[1]}),te&&te.grabbed()||R==ne||(ne&&ne.emit({originalEvent:t,type:"tapdragout",position:{x:s[0],y:s[1]}}),R&&R.emit({originalEvent:t,type:"tapdragover",position:{x:s[0],y:s[1]}})),e.touchData.last=R,n)for(V=0;V<s.length;V++)s[V]&&e.touchData.startPosition[V]&&p&&(e.touchData.singleTouchMoved=!0);if(n&&(null==te||te.pannable())&&o.panningEnabled()&&o.userPanningEnabled()){a(te,e.touchData.starts)&&(t.preventDefault(),e.data.bgActivePosistion||(e.data.bgActivePosistion=bt(e.touchData.startPosition)),e.swipePanning?(o.panBy({x:g[0]*c,y:g[1]*c}),o.emit("dragpan")):p&&(e.swipePanning=!0,o.panBy({x:y*c,y:b*c}),o.emit("dragpan"),te&&(te.unactivate(),e.redrawHint("select",!0),e.touchData.start=null)));h=e.projectIntoViewport(t.touches[0].clientX,t.touches[0].clientY);s[0]=h[0],s[1]=h[1]}}for(v=0;v<s.length;v++)l[v]=s[v];n&&t.touches.length>0&&!e.hoverData.draggingEles&&!e.swipePanning&&null!=e.data.bgActivePosistion&&(e.data.bgActivePosistion=void 0,e.redrawHint("select",!0),e.redraw())}},!1),e.registerBinding(t,"touchcancel",V=function(t){var n=e.touchData.start;e.touchData.capture=!1,n&&n.unactivate()}),e.registerBinding(t,"touchend",F=function(t){var i=e.touchData.start;if(e.touchData.capture){0===t.touches.length&&(e.touchData.capture=!1),t.preventDefault();var a=e.selection;e.swipePanning=!1,e.hoverData.draggingEles=!1;var o,s=e.cy,l=s.zoom(),u=e.touchData.now,c=e.touchData.earlier;if(t.touches[0]){var h=e.projectIntoViewport(t.touches[0].clientX,t.touches[0].clientY);u[0]=h[0],u[1]=h[1]}if(t.touches[1]){h=e.projectIntoViewport(t.touches[1].clientX,t.touches[1].clientY);u[2]=h[0],u[3]=h[1]}if(t.touches[2]){h=e.projectIntoViewport(t.touches[2].clientX,t.touches[2].clientY);u[4]=h[0],u[5]=h[1]}if(i&&i.unactivate(),e.touchData.cxt){if(o={originalEvent:t,type:"cxttapend",position:{x:u[0],y:u[1]}},i?i.emit(o):s.emit(o),!e.touchData.cxtDragged){var p={originalEvent:t,type:"cxttap",position:{x:u[0],y:u[1]}};i?i.emit(p):s.emit(p)}return e.touchData.start&&(e.touchData.start._private.grabbed=!1),e.touchData.cxt=!1,e.touchData.start=null,void e.redraw()}if(!t.touches[2]&&s.boxSelectionEnabled()&&e.touchData.selecting){e.touchData.selecting=!1;var f=s.collection(e.getAllInBox(a[0],a[1],a[2],a[3]));a[0]=void 0,a[1]=void 0,a[2]=void 0,a[3]=void 0,a[4]=0,e.redrawHint("select",!0),s.emit({type:"boxend",originalEvent:t,position:{x:u[0],y:u[1]}});f.emit("box").stdFilter((function(e){return e.selectable()&&!e.selected()})).select().emit("boxselect"),f.nonempty()&&e.redrawHint("eles",!0),e.redraw()}if(null!=i&&i.unactivate(),t.touches[2])e.data.bgActivePosistion=void 0,e.redrawHint("select",!0);else if(t.touches[1]);else if(t.touches[0]);else if(!t.touches[0]){e.data.bgActivePosistion=void 0,e.redrawHint("select",!0);var g=e.dragData.touchDragEles;if(null!=i){var v=i._private.grabbed;d(g),e.redrawHint("drag",!0),e.redrawHint("eles",!0),v&&(i.emit("freeon"),g.emit("free"),e.dragData.didDrag&&(i.emit("dragfreeon"),g.emit("dragfree"))),r(i,["touchend","tapend","vmouseup","tapdragout"],t,{x:u[0],y:u[1]}),i.unactivate(),e.touchData.start=null}else{var y=e.findNearestElement(u[0],u[1],!0,!0);r(y,["touchend","tapend","vmouseup","tapdragout"],t,{x:u[0],y:u[1]})}var m=e.touchData.startPosition[0]-u[0],b=m*m,x=e.touchData.startPosition[1]-u[1],w=(b+x*x)*l*l;e.touchData.singleTouchMoved||(i||s.$(":selected").unselect(["tapunselect"]),r(i,["tap","vclick"],t,{x:u[0],y:u[1]}),j=!1,t.timeStamp-Y<=s.multiClickDebounceTime()?(q&&clearTimeout(q),j=!0,Y=null,r(i,["dbltap","vdblclick"],t,{x:u[0],y:u[1]})):(q=setTimeout((function(){j||r(i,["onetap","voneclick"],t,{x:u[0],y:u[1]})}),s.multiClickDebounceTime()),Y=t.timeStamp)),null!=i&&!e.dragData.didDrag&&i._private.selectable&&w<e.touchTapThreshold2&&!e.pinching&&("single"===s.selectionType()?(s.$(n).unmerge(i).unselect(["tapunselect"]),i.select(["tapselect"])):i.selected()?i.unselect(["tapunselect"]):i.select(["tapselect"]),e.redrawHint("eles",!0)),e.touchData.singleTouchMoved=!0}for(var E=0;E<u.length;E++)c[E]=u[E];e.dragData.didDrag=!1,0===t.touches.length&&(e.touchData.dragDelta=[],e.touchData.startPosition=[null,null,null,null,null,null],e.touchData.startGPosition=null,e.touchData.didSelect=!1),t.touches.length<2&&(1===t.touches.length&&(e.touchData.startGPosition=[t.touches[0].clientX,t.touches[0].clientY]),e.pinching=!1,e.redrawHint("eles",!0),e.redraw())}},!1),"undefined"==typeof TouchEvent){var H=[],K=function(e){return{clientX:e.clientX,clientY:e.clientY,force:1,identifier:e.pointerId,pageX:e.pageX,pageY:e.pageY,radiusX:e.width/2,radiusY:e.height/2,screenX:e.screenX,screenY:e.screenY,target:e.target}},G=function(e){H.push(function(e){return{event:e,touch:K(e)}}(e))},U=function(e){for(var t=0;t<H.length;t++){if(H[t].event.pointerId===e.pointerId)return void H.splice(t,1)}},Z=function(e){e.touches=H.map((function(e){return e.touch}))},$=function(e){return"mouse"===e.pointerType||4===e.pointerType};e.registerBinding(e.container,"pointerdown",(function(e){$(e)||(e.preventDefault(),G(e),Z(e),O(e))})),e.registerBinding(e.container,"pointerup",(function(e){$(e)||(U(e),Z(e),F(e))})),e.registerBinding(e.container,"pointercancel",(function(e){$(e)||(U(e),Z(e),V())})),e.registerBinding(e.container,"pointermove",(function(e){$(e)||(e.preventDefault(),function(e){var t=H.filter((function(t){return t.event.pointerId===e.pointerId}))[0];t.event=e,t.touch=K(e)}(e),Z(e),R(e))}))}};var gu={generatePolygon:function(e,t){return this.nodeShapes[e]={renderer:this,name:e,points:t,draw:function(e,t,n,r,i,a){this.renderer.nodeShapeImpl("polygon",e,t,n,r,i,this.points)},intersectLine:function(e,t,n,r,i,a,o,s){return $t(i,a,this.points,e,t,n/2,r/2,o)},checkPoint:function(e,t,n,r,i,a,o,s){return Xt(e,t,this.points,a,o,r,i,[0,-1],n)}}}};gu.generateEllipse=function(){return this.nodeShapes.ellipse={renderer:this,name:"ellipse",draw:function(e,t,n,r,i,a){this.renderer.nodeShapeImpl(this.name,e,t,n,r,i)},intersectLine:function(e,t,n,r,i,a,o,s){return function(e,t,n,r,i,a){var o=n-e,s=r-t;o/=i,s/=a;var l=Math.sqrt(o*o+s*s),u=l-1;if(u<0)return[];var c=u/l;return[(n-e)*c+e,(r-t)*c+t]}(i,a,e,t,n/2+o,r/2+o)},checkPoint:function(e,t,n,r,i,a,o,s){return Kt(e,t,r,i,a,o,n)}}},gu.generateRoundPolygon=function(e,t){return this.nodeShapes[e]={renderer:this,name:e,points:t,getOrCreateCorners:function(e,n,r,i,a,o,s){if(void 0!==o[s]&&o[s+"-cx"]===e&&o[s+"-cy"]===n)return o[s];o[s]=new Array(t.length/2),o[s+"-cx"]=e,o[s+"-cy"]=n;var l=r/2,u=i/2;a="auto"===a?rn(r,i):a;for(var c=new Array(t.length/2),d=0;d<t.length/2;d++)c[d]={x:e+l*t[2*d],y:n+u*t[2*d+1]};var h,p,f,g,v=c.length;for(p=c[v-1],h=0;h<v;h++)f=c[h%v],g=c[(h+1)%v],o[s][h]=Jl(p,f,g,a),p=f,f=g;return o[s]},draw:function(e,t,n,r,i,a,o){this.renderer.nodeShapeImpl("round-polygon",e,t,n,r,i,this.points,this.getOrCreateCorners(t,n,r,i,a,o,"drawCorners"))},intersectLine:function(e,t,n,r,i,a,o,s,l){return function(e,t,n,r,i,a,o,s,l){var u,c=[],d=new Array(2*n.length);l.forEach((function(n,a){0===a?(d[d.length-2]=n.startX,d[d.length-1]=n.startY):(d[4*a-2]=n.startX,d[4*a-1]=n.startY),d[4*a]=n.stopX,d[4*a+1]=n.stopY,0!==(u=Gt(e,t,r,i,n.cx,n.cy,n.radius)).length&&c.push(u[0],u[1])}));for(var h=0;h<d.length/4;h++)0!==(u=Zt(e,t,r,i,d[4*h],d[4*h+1],d[4*h+2],d[4*h+3],!1)).length&&c.push(u[0],u[1]);if(c.length>2){for(var p=[c[0],c[1]],f=Math.pow(p[0]-e,2)+Math.pow(p[1]-t,2),g=1;g<c.length/2;g++){var v=Math.pow(c[2*g]-e,2)+Math.pow(c[2*g+1]-t,2);v<=f&&(p[0]=c[2*g],p[1]=c[2*g+1],f=v)}return p}return c}(i,a,this.points,e,t,0,0,0,this.getOrCreateCorners(e,t,n,r,s,l,"corners"))},checkPoint:function(e,t,n,r,i,a,o,s,l){return function(e,t,n,r,i,a,o,s){for(var l=new Array(2*n.length),u=0;u<s.length;u++){var c=s[u];if(l[4*u+0]=c.startX,l[4*u+1]=c.startY,l[4*u+2]=c.stopX,l[4*u+3]=c.stopY,Math.pow(c.cx-e,2)+Math.pow(c.cy-t,2)<=Math.pow(c.radius,2))return!0}return Yt(e,t,l)}(e,t,this.points,0,0,0,0,this.getOrCreateCorners(a,o,r,i,s,l,"corners"))}}},gu.generateRoundRectangle=function(){return this.nodeShapes["round-rectangle"]=this.nodeShapes.roundrectangle={renderer:this,name:"round-rectangle",points:Jt(4,0),draw:function(e,t,n,r,i,a){this.renderer.nodeShapeImpl(this.name,e,t,n,r,i,this.points,a)},intersectLine:function(e,t,n,r,i,a,o,s){return Rt(i,a,e,t,n,r,o,s)},checkPoint:function(e,t,n,r,i,a,o,s){var l=r/2,u=i/2;s="auto"===s?nn(r,i):s;var c=2*(s=Math.min(l,u,s));return!!Xt(e,t,this.points,a,o,r,i-c,[0,-1],n)||(!!Xt(e,t,this.points,a,o,r-c,i,[0,-1],n)||(!!Kt(e,t,c,c,a-l+s,o-u+s,n)||(!!Kt(e,t,c,c,a+l-s,o-u+s,n)||(!!Kt(e,t,c,c,a+l-s,o+u-s,n)||!!Kt(e,t,c,c,a-l+s,o+u-s,n)))))}}},gu.generateCutRectangle=function(){return this.nodeShapes["cut-rectangle"]=this.nodeShapes.cutrectangle={renderer:this,name:"cut-rectangle",cornerLength:8,points:Jt(4,0),draw:function(e,t,n,r,i,a){this.renderer.nodeShapeImpl(this.name,e,t,n,r,i,null,a)},generateCutTrianglePts:function(e,t,n,r,i){var a="auto"===i?this.cornerLength:i,o=t/2,s=e/2,l=n-s,u=n+s,c=r-o,d=r+o;return{topLeft:[l,c+a,l+a,c,l+a,c+a],topRight:[u-a,c,u,c+a,u-a,c+a],bottomRight:[u,d-a,u-a,d,u-a,d-a],bottomLeft:[l+a,d,l,d-a,l+a,d-a]}},intersectLine:function(e,t,n,r,i,a,o,s){var l=this.generateCutTrianglePts(n+2*o,r+2*o,e,t,s),u=[].concat.apply([],[l.topLeft.splice(0,4),l.topRight.splice(0,4),l.bottomRight.splice(0,4),l.bottomLeft.splice(0,4)]);return $t(i,a,u,e,t)},checkPoint:function(e,t,n,r,i,a,o,s){var l="auto"===s?this.cornerLength:s;if(Xt(e,t,this.points,a,o,r,i-2*l,[0,-1],n))return!0;if(Xt(e,t,this.points,a,o,r-2*l,i,[0,-1],n))return!0;var u=this.generateCutTrianglePts(r,i,a,o);return Yt(e,t,u.topLeft)||Yt(e,t,u.topRight)||Yt(e,t,u.bottomRight)||Yt(e,t,u.bottomLeft)}}},gu.generateBarrel=function(){return this.nodeShapes.barrel={renderer:this,name:"barrel",points:Jt(4,0),draw:function(e,t,n,r,i,a){this.renderer.nodeShapeImpl(this.name,e,t,n,r,i)},intersectLine:function(e,t,n,r,i,a,o,s){var l=this.generateBarrelBezierPts(n+2*o,r+2*o,e,t),u=function(e){var t=Dt({x:e[0],y:e[1]},{x:e[2],y:e[3]},{x:e[4],y:e[5]},.15),n=Dt({x:e[0],y:e[1]},{x:e[2],y:e[3]},{x:e[4],y:e[5]},.5),r=Dt({x:e[0],y:e[1]},{x:e[2],y:e[3]},{x:e[4],y:e[5]},.85);return[e[0],e[1],t.x,t.y,n.x,n.y,r.x,r.y,e[4],e[5]]},c=[].concat(u(l.topLeft),u(l.topRight),u(l.bottomRight),u(l.bottomLeft));return $t(i,a,c,e,t)},generateBarrelBezierPts:function(e,t,n,r){var i=t/2,a=e/2,o=n-a,s=n+a,l=r-i,u=r+i,c=an(e,t),d=c.heightOffset,h=c.widthOffset,p=c.ctrlPtOffsetPct*e,f={topLeft:[o,l+d,o+p,l,o+h,l],topRight:[s-h,l,s-p,l,s,l+d],bottomRight:[s,u-d,s-p,u,s-h,u],bottomLeft:[o+h,u,o+p,u,o,u-d]};return f.topLeft.isTop=!0,f.topRight.isTop=!0,f.bottomLeft.isBottom=!0,f.bottomRight.isBottom=!0,f},checkPoint:function(e,t,n,r,i,a,o,s){var l=an(r,i),u=l.heightOffset,c=l.widthOffset;if(Xt(e,t,this.points,a,o,r,i-2*u,[0,-1],n))return!0;if(Xt(e,t,this.points,a,o,r-2*c,i,[0,-1],n))return!0;for(var d=this.generateBarrelBezierPts(r,i,a,o),h=function(e,t,n){var r,i,a=n[4],o=n[2],s=n[0],l=n[5],u=n[1],c=Math.min(a,s),d=Math.max(a,s),h=Math.min(l,u),p=Math.max(l,u);if(c<=e&&e<=d&&h<=t&&t<=p){var f=[(r=a)-2*(i=o)+s,2*(i-r),r],g=function(e,t,n,r){var i=t*t-4*e*(n-=r);if(i<0)return[];var a=Math.sqrt(i),o=2*e;return[(-t+a)/o,(-t-a)/o]}(f[0],f[1],f[2],e).filter((function(e){return 0<=e&&e<=1}));if(g.length>0)return g[0]}return null},p=Object.keys(d),f=0;f<p.length;f++){var g=d[p[f]],v=h(e,t,g);if(null!=v){var y=g[5],m=g[3],b=g[1],x=Pt(y,m,b,v);if(g.isTop&&x<=t)return!0;if(g.isBottom&&t<=x)return!0}}return!1}}},gu.generateBottomRoundrectangle=function(){return this.nodeShapes["bottom-round-rectangle"]=this.nodeShapes.bottomroundrectangle={renderer:this,name:"bottom-round-rectangle",points:Jt(4,0),draw:function(e,t,n,r,i,a){this.renderer.nodeShapeImpl(this.name,e,t,n,r,i,this.points,a)},intersectLine:function(e,t,n,r,i,a,o,s){var l=t-(r/2+o),u=Zt(i,a,e,t,e-(n/2+o),l,e+(n/2+o),l,!1);return u.length>0?u:Rt(i,a,e,t,n,r,o,s)},checkPoint:function(e,t,n,r,i,a,o,s){var l=2*(s="auto"===s?nn(r,i):s);if(Xt(e,t,this.points,a,o,r,i-l,[0,-1],n))return!0;if(Xt(e,t,this.points,a,o,r-l,i,[0,-1],n))return!0;var u=r/2+2*n,c=i/2+2*n;return!!Yt(e,t,[a-u,o-c,a-u,o,a+u,o,a+u,o-c])||(!!Kt(e,t,l,l,a+r/2-s,o+i/2-s,n)||!!Kt(e,t,l,l,a-r/2+s,o+i/2-s,n))}}},gu.registerNodeShapes=function(){var e=this.nodeShapes={},t=this;this.generateEllipse(),this.generatePolygon("triangle",Jt(3,0)),this.generateRoundPolygon("round-triangle",Jt(3,0)),this.generatePolygon("rectangle",Jt(4,0)),e.square=e.rectangle,this.generateRoundRectangle(),this.generateCutRectangle(),this.generateBarrel(),this.generateBottomRoundrectangle();var n=[0,1,1,0,0,-1,-1,0];this.generatePolygon("diamond",n),this.generateRoundPolygon("round-diamond",n),this.generatePolygon("pentagon",Jt(5,0)),this.generateRoundPolygon("round-pentagon",Jt(5,0)),this.generatePolygon("hexagon",Jt(6,0)),this.generateRoundPolygon("round-hexagon",Jt(6,0)),this.generatePolygon("heptagon",Jt(7,0)),this.generateRoundPolygon("round-heptagon",Jt(7,0)),this.generatePolygon("octagon",Jt(8,0)),this.generateRoundPolygon("round-octagon",Jt(8,0));var r=new Array(20),i=tn(5,0),a=tn(5,Math.PI/5),o=.5*(3-Math.sqrt(5));o*=1.57;for(var s=0;s<a.length/2;s++)a[2*s]*=o,a[2*s+1]*=o;for(s=0;s<5;s++)r[4*s]=i[2*s],r[4*s+1]=i[2*s+1],r[4*s+2]=a[2*s],r[4*s+3]=a[2*s+1];r=en(r),this.generatePolygon("star",r),this.generatePolygon("vee",[-1,-1,0,-.333,1,-1,0,1]),this.generatePolygon("rhomboid",[-1,-1,.333,-1,1,1,-.333,1]),this.generatePolygon("right-rhomboid",[-.333,-1,1,-1,.333,1,-1,1]),this.nodeShapes.concavehexagon=this.generatePolygon("concave-hexagon",[-1,-.95,-.75,0,-1,.95,1,.95,.75,0,1,-.95]);var l=[-1,-1,.25,-1,1,0,.25,1,-1,1];this.generatePolygon("tag",l),this.generateRoundPolygon("round-tag",l),e.makePolygon=function(e){var n,r="polygon-"+e.join("$");return(n=this[r])?n:t.generatePolygon(r,e)}};var vu={timeToRender:function(){return this.redrawTotalTime/this.redrawCount},redraw:function(e){e=e||We();var t=this;void 0===t.averageRedrawTime&&(t.averageRedrawTime=0),void 0===t.lastRedrawTime&&(t.lastRedrawTime=0),void 0===t.lastDrawTime&&(t.lastDrawTime=0),t.requestedFrame=!0,t.renderOptions=e},beforeRender:function(e,t){if(!this.destroyed){null==t&&Ve("Priority is not optional for beforeRender");var n=this.beforeRenderCallbacks;n.push({fn:e,priority:t}),n.sort((function(e,t){return t.priority-e.priority}))}}},yu=function(e,t,n){for(var r=e.beforeRenderCallbacks,i=0;i<r.length;i++)r[i].fn(t,n)};vu.startRenderLoop=function(){var e=this,t=e.cy;if(!e.renderLoopStarted){e.renderLoopStarted=!0;xe((function n(r){if(!e.destroyed){if(t.batching());else if(e.requestedFrame&&!e.skipFrame){yu(e,!0,r);var i=we();e.render(e.renderOptions);var a=e.lastDrawTime=we();void 0===e.averageRedrawTime&&(e.averageRedrawTime=a-i),void 0===e.redrawCount&&(e.redrawCount=0),e.redrawCount++,void 0===e.redrawTotalTime&&(e.redrawTotalTime=0);var o=a-i;e.redrawTotalTime+=o,e.lastRedrawTime=o,e.averageRedrawTime=e.averageRedrawTime/2+o/2,e.requestedFrame=!1}else yu(e,!1,r);e.skipFrame=!1,xe(n)}}))}};var mu=function(e){this.init(e)},bu=mu.prototype;bu.clientFunctions=["redrawHint","render","renderTo","matchCanvasSize","nodeShapeImpl","arrowShapeImpl"],bu.init=function(e){var t=this;t.options=e,t.cy=e.cy;var n=t.container=e.cy.container(),r=t.cy.window();if(r){var i=r.document,a=i.head,o="__________cytoscape_container",s=null!=i.getElementById("__________cytoscape_stylesheet");if(n.className.indexOf(o)<0&&(n.className=(n.className||"")+" "+o),!s){var l=i.createElement("style");l.id="__________cytoscape_stylesheet",l.textContent="."+o+" { position: relative; }",a.insertBefore(l,a.children[0])}"static"===r.getComputedStyle(n).getPropertyValue("position")&&je("A Cytoscape container has style position:static and so can not use UI extensions properly")}t.selection=[void 0,void 0,void 0,void 0,0],t.bezierProjPcts=[.05,.225,.4,.5,.6,.775,.95],t.hoverData={down:null,last:null,downTime:null,triggerMode:null,dragging:!1,initialPan:[null,null],capture:!1},t.dragData={possibleDragElements:[]},t.touchData={start:null,capture:!1,startPosition:[null,null,null,null,null,null],singleTouchStartTime:null,singleTouchMoved:!0,now:[null,null,null,null,null,null],earlier:[null,null,null,null,null,null]},t.redraws=0,t.showFps=e.showFps,t.debug=e.debug,t.hideEdgesOnViewport=e.hideEdgesOnViewport,t.textureOnViewport=e.textureOnViewport,t.wheelSensitivity=e.wheelSensitivity,t.motionBlurEnabled=e.motionBlur,t.forcedPixelRatio=x(e.pixelRatio)?e.pixelRatio:null,t.motionBlur=e.motionBlur,t.motionBlurOpacity=e.motionBlurOpacity,t.motionBlurTransparency=1-t.motionBlurOpacity,t.motionBlurPxRatio=1,t.mbPxRBlurry=1,t.minMbLowQualFrames=4,t.fullQualityMb=!1,t.clearedForMotionBlur=[],t.desktopTapThreshold=e.desktopTapThreshold,t.desktopTapThreshold2=e.desktopTapThreshold*e.desktopTapThreshold,t.touchTapThreshold=e.touchTapThreshold,t.touchTapThreshold2=e.touchTapThreshold*e.touchTapThreshold,t.tapholdDuration=500,t.bindings=[],t.beforeRenderCallbacks=[],t.beforeRenderPriorities={animations:400,eleCalcs:300,eleTxrDeq:200,lyrTxrDeq:150,lyrTxrSkip:100},t.registerNodeShapes(),t.registerArrowShapes(),t.registerCalculationListeners()},bu.notify=function(e,t){var n=this,r=n.cy;this.destroyed||("init"!==e?"destroy"!==e?(("add"===e||"remove"===e||"move"===e&&r.hasCompoundNodes()||"load"===e||"zorder"===e||"mount"===e)&&n.invalidateCachedZSortedEles(),"viewport"===e&&n.redrawHint("select",!0),"load"!==e&&"resize"!==e&&"mount"!==e||(n.invalidateContainerClientCoordsCache(),n.matchCanvasSize(n.container)),n.redrawHint("eles",!0),n.redrawHint("drag",!0),this.startRenderLoop(),this.redraw()):n.destroy():n.load())},bu.destroy=function(){var e=this;e.destroyed=!0,e.cy.stopAnimationLoop();for(var t=0;t<e.bindings.length;t++){var n=e.bindings[t],r=n.target;(r.off||r.removeEventListener).apply(r,n.args)}if(e.bindings=[],e.beforeRenderCallbacks=[],e.onUpdateEleCalcsFns=[],e.removeObserver&&e.removeObserver.disconnect(),e.styleObserver&&e.styleObserver.disconnect(),e.resizeObserver&&e.resizeObserver.disconnect(),e.labelCalcDiv)try{document.body.removeChild(e.labelCalcDiv)}catch(e){}},bu.isHeadless=function(){return!1},[Tl,hu,pu,fu,gu,vu].forEach((function(e){L(bu,e)}));var xu=function(e){return function(){var t=this,n=this.renderer;if(!t.dequeueingSetup){t.dequeueingSetup=!0;var r=ve((function(){n.redrawHint("eles",!0),n.redrawHint("drag",!0),n.redraw()}),e.deqRedrawThreshold),i=e.priority||Re;n.beforeRender((function(i,a){var o=we(),s=n.averageRedrawTime,l=n.lastRedrawTime,u=[],c=n.cy.extent(),d=n.getPixelRatio();for(i||n.flushRenderedStyleQueue();;){var h=we(),p=h-o,f=h-a;if(l<1e3/60){var g=1e3/60-(i?s:0);if(f>=e.deqFastCost*g)break}else if(i){if(p>=e.deqCost*l||p>=e.deqAvgCost*s)break}else if(f>=e.deqNoDrawCost*(1e3/60))break;var v=e.deq(t,d,c);if(!(v.length>0))break;for(var y=0;y<v.length;y++)u.push(v[y])}u.length>0&&(e.onDeqd(t,u),!i&&e.shouldRedraw(t,u,d,c)&&r())}),i(t))}}},wu=function(){function e(n){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Le;t(this,e),this.idsByKey=new $e,this.keyForId=new $e,this.cachesByLvl=new $e,this.lvls=[],this.getKey=n,this.doesEleInvalidateKey=r}return r(e,[{key:"getIdsFor",value:function(e){null==e&&Ve("Can not get id list for null key");var t=this.idsByKey,n=this.idsByKey.get(e);return n||(n=new Je,t.set(e,n)),n}},{key:"addIdForKey",value:function(e,t){null!=e&&this.getIdsFor(e).add(t)}},{key:"deleteIdForKey",value:function(e,t){null!=e&&this.getIdsFor(e).delete(t)}},{key:"getNumberOfIdsForKey",value:function(e){return null==e?0:this.getIdsFor(e).size}},{key:"updateKeyMappingFor",value:function(e){var t=e.id(),n=this.keyForId.get(t),r=this.getKey(e);this.deleteIdForKey(n,t),this.addIdForKey(r,t),this.keyForId.set(t,r)}},{key:"deleteKeyMappingFor",value:function(e){var t=e.id(),n=this.keyForId.get(t);this.deleteIdForKey(n,t),this.keyForId.delete(t)}},{key:"keyHasChangedFor",value:function(e){var t=e.id();return this.keyForId.get(t)!==this.getKey(e)}},{key:"isInvalid",value:function(e){return this.keyHasChangedFor(e)||this.doesEleInvalidateKey(e)}},{key:"getCachesAt",value:function(e){var t=this.cachesByLvl,n=this.lvls,r=t.get(e);return r||(r=new $e,t.set(e,r),n.push(e)),r}},{key:"getCache",value:function(e,t){return this.getCachesAt(t).get(e)}},{key:"get",value:function(e,t){var n=this.getKey(e),r=this.getCache(n,t);return null!=r&&this.updateKeyMappingFor(e),r}},{key:"getForCachedKey",value:function(e,t){var n=this.keyForId.get(e.id());return this.getCache(n,t)}},{key:"hasCache",value:function(e,t){return this.getCachesAt(t).has(e)}},{key:"has",value:function(e,t){var n=this.getKey(e);return this.hasCache(n,t)}},{key:"setCache",value:function(e,t,n){n.key=e,this.getCachesAt(t).set(e,n)}},{key:"set",value:function(e,t,n){var r=this.getKey(e);this.setCache(r,t,n),this.updateKeyMappingFor(e)}},{key:"deleteCache",value:function(e,t){this.getCachesAt(t).delete(e)}},{key:"delete",value:function(e,t){var n=this.getKey(e);this.deleteCache(n,t)}},{key:"invalidateKey",value:function(e){var t=this;this.lvls.forEach((function(n){return t.deleteCache(e,n)}))}},{key:"invalidate",value:function(e){var t=e.id(),n=this.keyForId.get(t);this.deleteKeyMappingFor(e);var r=this.doesEleInvalidateKey(e);return r&&this.invalidateKey(n),r||0===this.getNumberOfIdsForKey(n)}}]),e}(),Eu={dequeue:"dequeue",downscale:"downscale",highQuality:"highQuality"},ku=He({getKey:null,doesEleInvalidateKey:Le,drawElement:null,getBoundingBox:null,getRotationPoint:null,getRotationOffset:null,isVisible:Ae,allowEdgeTxrCaching:!0,allowParentTxrCaching:!0}),Cu=function(e,t){this.renderer=e,this.onDequeues=[];var n=ku(t);L(this,n),this.lookup=new wu(n.getKey,n.doesEleInvalidateKey),this.setupDequeueing()},Su=Cu.prototype;Su.reasons=Eu,Su.getTextureQueue=function(e){return this.eleImgCaches=this.eleImgCaches||{},this.eleImgCaches[e]=this.eleImgCaches[e]||[]},Su.getRetiredTextureQueue=function(e){var t=this.eleImgCaches.retired=this.eleImgCaches.retired||{};return t[e]=t[e]||[]},Su.getElementQueue=function(){return this.eleCacheQueue=this.eleCacheQueue||new rt((function(e,t){return t.reqs-e.reqs}))},Su.getElementKeyToQueue=function(){return this.eleKeyToCacheQueue=this.eleKeyToCacheQueue||{}},Su.getElement=function(e,t,n,r,i){var a=this,o=this.renderer,s=o.cy.zoom(),l=this.lookup;if(!t||0===t.w||0===t.h||isNaN(t.w)||isNaN(t.h)||!e.visible()||e.removed())return null;if(!a.allowEdgeTxrCaching&&e.isEdge()||!a.allowParentTxrCaching&&e.isParent())return null;if(null==r&&(r=Math.ceil(wt(s*n))),r<-4)r=-4;else if(s>=7.99||r>3)return null;var u=Math.pow(2,r),c=t.h*u,d=t.w*u,h=o.eleTextBiggerThanMin(e,u);if(!this.isVisible(e,h))return null;var p,f=l.get(e,r);if(f&&f.invalidated&&(f.invalidated=!1,f.texture.invalidatedWidth-=f.width),f)return f;if(p=c<=25?25:c<=50?50:50*Math.ceil(c/50),c>1024||d>1024)return null;var g=a.getTextureQueue(p),v=g[g.length-2],y=function(){return a.recycleTexture(p,d)||a.addTexture(p,d)};v||(v=g[g.length-1]),v||(v=y()),v.width-v.usedWidth<d&&(v=y());for(var m,b=function(e){return e&&e.scaledLabelShown===h},x=i&&i===Eu.dequeue,w=i&&i===Eu.highQuality,E=i&&i===Eu.downscale,k=r+1;k<=3;k++){var C=l.get(e,k);if(C){m=C;break}}var S=m&&m.level===r+1?m:null,P=function(){v.context.drawImage(S.texture.canvas,S.x,0,S.width,S.height,v.usedWidth,0,d,c)};if(v.context.setTransform(1,0,0,1,0,0),v.context.clearRect(v.usedWidth,0,d,p),b(S))P();else if(b(m)){if(!w)return a.queueElement(e,m.level-1),m;for(var D=m.level;D>r;D--)S=a.getElement(e,t,n,D,Eu.downscale);P()}else{var T;if(!x&&!w&&!E)for(var _=r-1;_>=-4;_--){var M=l.get(e,_);if(M){T=M;break}}if(b(T))return a.queueElement(e,r),T;v.context.translate(v.usedWidth,0),v.context.scale(u,u),this.drawElement(v.context,e,t,h,!1),v.context.scale(1/u,1/u),v.context.translate(-v.usedWidth,0)}return f={x:v.usedWidth,texture:v,level:r,scale:u,width:d,height:c,scaledLabelShown:h},v.usedWidth+=Math.ceil(d+8),v.eleCaches.push(f),l.set(e,r,f),a.checkTextureFullness(v),f},Su.invalidateElements=function(e){for(var t=0;t<e.length;t++)this.invalidateElement(e[t])},Su.invalidateElement=function(e){var t=this.lookup,n=[];if(t.isInvalid(e)){for(var r=-4;r<=3;r++){var i=t.getForCachedKey(e,r);i&&n.push(i)}if(t.invalidate(e))for(var a=0;a<n.length;a++){var o=n[a],s=o.texture;s.invalidatedWidth+=o.width,o.invalidated=!0,this.checkTextureUtility(s)}this.removeFromQueue(e)}},Su.checkTextureUtility=function(e){e.invalidatedWidth>=.2*e.width&&this.retireTexture(e)},Su.checkTextureFullness=function(e){var t=this.getTextureQueue(e.height);e.usedWidth/e.width>.8&&e.fullnessChecks>=10?Ke(t,e):e.fullnessChecks++},Su.retireTexture=function(e){var t=e.height,n=this.getTextureQueue(t),r=this.lookup;Ke(n,e),e.retired=!0;for(var i=e.eleCaches,a=0;a<i.length;a++){var o=i[a];r.deleteCache(o.key,o.level)}Ge(i),this.getRetiredTextureQueue(t).push(e)},Su.addTexture=function(e,t){var n={};return this.getTextureQueue(e).push(n),n.eleCaches=[],n.height=e,n.width=Math.max(1024,t),n.usedWidth=0,n.invalidatedWidth=0,n.fullnessChecks=0,n.canvas=this.renderer.makeOffscreenCanvas(n.width,n.height),n.context=n.canvas.getContext("2d"),n},Su.recycleTexture=function(e,t){for(var n=this.getTextureQueue(e),r=this.getRetiredTextureQueue(e),i=0;i<r.length;i++){var a=r[i];if(a.width>=t)return a.retired=!1,a.usedWidth=0,a.invalidatedWidth=0,a.fullnessChecks=0,Ge(a.eleCaches),a.context.setTransform(1,0,0,1,0,0),a.context.clearRect(0,0,a.width,a.height),Ke(r,a),n.push(a),a}},Su.queueElement=function(e,t){var n=this.getElementQueue(),r=this.getElementKeyToQueue(),i=this.getKey(e),a=r[i];if(a)a.level=Math.max(a.level,t),a.eles.merge(e),a.reqs++,n.updateItem(a);else{var o={eles:e.spawn().merge(e),level:t,reqs:1,key:i};n.push(o),r[i]=o}},Su.dequeue=function(e){for(var t=this.getElementQueue(),n=this.getElementKeyToQueue(),r=[],i=this.lookup,a=0;a<1&&t.size()>0;a++){var o=t.pop(),s=o.key,l=o.eles[0],u=i.hasCache(l,o.level);if(n[s]=null,!u){r.push(o);var c=this.getBoundingBox(l);this.getElement(l,c,e,o.level,Eu.dequeue)}}return r},Su.removeFromQueue=function(e){var t=this.getElementQueue(),n=this.getElementKeyToQueue(),r=this.getKey(e),i=n[r];null!=i&&(1===i.eles.length?(i.reqs=Ie,t.updateItem(i),t.pop(),n[r]=null):i.eles.unmerge(e))},Su.onDequeue=function(e){this.onDequeues.push(e)},Su.offDequeue=function(e){Ke(this.onDequeues,e)},Su.setupDequeueing=xu({deqRedrawThreshold:100,deqCost:.15,deqAvgCost:.1,deqNoDrawCost:.9,deqFastCost:.9,deq:function(e,t,n){return e.dequeue(t,n)},onDeqd:function(e,t){for(var n=0;n<e.onDequeues.length;n++){(0,e.onDequeues[n])(t)}},shouldRedraw:function(e,t,n,r){for(var i=0;i<t.length;i++)for(var a=t[i].eles,o=0;o<a.length;o++){var s=a[o].boundingBox();if(At(s,r))return!0}return!1},priority:function(e){return e.renderer.beforeRenderPriorities.eleTxrDeq}});var Pu=function(e){var t=this,n=t.renderer=e,r=n.cy;t.layersByLevel={},t.firstGet=!0,t.lastInvalidationTime=we()-500,t.skipping=!1,t.eleTxrDeqs=r.collection(),t.scheduleElementRefinement=ve((function(){t.refineElementTextures(t.eleTxrDeqs),t.eleTxrDeqs.unmerge(t.eleTxrDeqs)}),50),n.beforeRender((function(e,n){n-t.lastInvalidationTime<=250?t.skipping=!0:t.skipping=!1}),n.beforeRenderPriorities.lyrTxrSkip);t.layersQueue=new rt((function(e,t){return t.reqs-e.reqs})),t.setupDequeueing()},Du=Pu.prototype,Tu=0,_u=Math.pow(2,53)-1;Du.makeLayer=function(e,t){var n=Math.pow(2,t),r=Math.ceil(e.w*n),i=Math.ceil(e.h*n),a=this.renderer.makeOffscreenCanvas(r,i),o={id:Tu=++Tu%_u,bb:e,level:t,width:r,height:i,canvas:a,context:a.getContext("2d"),eles:[],elesQueue:[],reqs:0},s=o.context,l=-o.bb.x1,u=-o.bb.y1;return s.scale(n,n),s.translate(l,u),o},Du.getLayers=function(e,t,n){var r=this,i=r.renderer.cy.zoom(),a=r.firstGet;if(r.firstGet=!1,null==n)if((n=Math.ceil(wt(i*t)))<-4)n=-4;else if(i>=3.99||n>2)return null;r.validateLayersElesOrdering(n,e);var o,s,l=r.layersByLevel,u=Math.pow(2,n),c=l[n]=l[n]||[];if(r.levelIsComplete(n,e))return c;!function(){var t=function(t){if(r.validateLayersElesOrdering(t,e),r.levelIsComplete(t,e))return s=l[t],!0},i=function(e){if(!s)for(var r=n+e;-4<=r&&r<=2&&!t(r);r+=e);};i(1),i(-1);for(var a=c.length-1;a>=0;a--){var o=c[a];o.invalid&&Ke(c,o)}}();var d=function(t){var i=(t=t||{}).after;if(function(){if(!o){o=_t();for(var t=0;t<e.length;t++)Mt(o,e[t].boundingBox())}}(),o.w*u*(o.h*u)>16e6)return null;var a=r.makeLayer(o,n);if(null!=i){var s=c.indexOf(i)+1;c.splice(s,0,a)}else(void 0===t.insert||t.insert)&&c.unshift(a);return a};if(r.skipping&&!a)return null;for(var h=null,p=e.length/1,f=!a,g=0;g<e.length;g++){var v=e[g],y=v._private.rscratch,m=y.imgLayerCaches=y.imgLayerCaches||{},b=m[n];if(b)h=b;else{if((!h||h.eles.length>=p||!Ot(h.bb,v.boundingBox()))&&!(h=d({insert:!0,after:h})))return null;s||f?r.queueLayer(h,v):r.drawEleInLayer(h,v,n,t),h.eles.push(v),m[n]=h}}return s||(f?null:c)},Du.getEleLevelForLayerLevel=function(e,t){return e},Du.drawEleInLayer=function(e,t,n,r){var i=this.renderer,a=e.context,o=t.boundingBox();0!==o.w&&0!==o.h&&t.visible()&&(n=this.getEleLevelForLayerLevel(n,r),i.setImgSmoothing(a,!1),i.drawCachedElement(a,t,null,null,n,!0),i.setImgSmoothing(a,!0))},Du.levelIsComplete=function(e,t){var n=this.layersByLevel[e];if(!n||0===n.length)return!1;for(var r=0,i=0;i<n.length;i++){var a=n[i];if(a.reqs>0)return!1;if(a.invalid)return!1;r+=a.eles.length}return r===t.length},Du.validateLayersElesOrdering=function(e,t){var n=this.layersByLevel[e];if(n)for(var r=0;r<n.length;r++){for(var i=n[r],a=-1,o=0;o<t.length;o++)if(i.eles[0]===t[o]){a=o;break}if(a<0)this.invalidateLayer(i);else{var s=a;for(o=0;o<i.eles.length;o++)if(i.eles[o]!==t[s+o]){this.invalidateLayer(i);break}}}},Du.updateElementsInLayers=function(e,t){for(var n=k(e[0]),r=0;r<e.length;r++)for(var i=n?null:e[r],a=n?e[r]:e[r].ele,o=a._private.rscratch,s=o.imgLayerCaches=o.imgLayerCaches||{},l=-4;l<=2;l++){var u=s[l];u&&(i&&this.getEleLevelForLayerLevel(u.level)!==i.level||t(u,a,i))}},Du.haveLayers=function(){for(var e=!1,t=-4;t<=2;t++){var n=this.layersByLevel[t];if(n&&n.length>0){e=!0;break}}return e},Du.invalidateElements=function(e){var t=this;0!==e.length&&(t.lastInvalidationTime=we(),0!==e.length&&t.haveLayers()&&t.updateElementsInLayers(e,(function(e,n,r){t.invalidateLayer(e)})))},Du.invalidateLayer=function(e){if(this.lastInvalidationTime=we(),!e.invalid){var t=e.level,n=e.eles,r=this.layersByLevel[t];Ke(r,e),e.elesQueue=[],e.invalid=!0,e.replacement&&(e.replacement.invalid=!0);for(var i=0;i<n.length;i++){var a=n[i]._private.rscratch.imgLayerCaches;a&&(a[t]=null)}}},Du.refineElementTextures=function(e){var t=this;t.updateElementsInLayers(e,(function(e,n,r){var i=e.replacement;if(i||((i=e.replacement=t.makeLayer(e.bb,e.level)).replaces=e,i.eles=e.eles),!i.reqs)for(var a=0;a<i.eles.length;a++)t.queueLayer(i,i.eles[a])}))},Du.enqueueElementRefinement=function(e){this.eleTxrDeqs.merge(e),this.scheduleElementRefinement()},Du.queueLayer=function(e,t){var n=this.layersQueue,r=e.elesQueue,i=r.hasId=r.hasId||{};if(!e.replacement){if(t){if(i[t.id()])return;r.push(t),i[t.id()]=!0}e.reqs?(e.reqs++,n.updateItem(e)):(e.reqs=1,n.push(e))}},Du.dequeue=function(e){for(var t=this.layersQueue,n=[],r=0;r<1&&0!==t.size();){var i=t.peek();if(i.replacement)t.pop();else if(i.replaces&&i!==i.replaces.replacement)t.pop();else if(i.invalid)t.pop();else{var a=i.elesQueue.shift();a&&(this.drawEleInLayer(i,a,i.level,e),r++),0===n.length&&n.push(!0),0===i.elesQueue.length&&(t.pop(),i.reqs=0,i.replaces&&this.applyLayerReplacement(i),this.requestRedraw())}}return n},Du.applyLayerReplacement=function(e){var t=this.layersByLevel[e.level],n=e.replaces,r=t.indexOf(n);if(!(r<0||n.invalid)){t[r]=e;for(var i=0;i<e.eles.length;i++){var a=e.eles[i]._private,o=a.imgLayerCaches=a.imgLayerCaches||{};o&&(o[e.level]=e)}this.requestRedraw()}},Du.requestRedraw=ve((function(){var e=this.renderer;e.redrawHint("eles",!0),e.redrawHint("drag",!0),e.redraw()}),100),Du.setupDequeueing=xu({deqRedrawThreshold:50,deqCost:.15,deqAvgCost:.1,deqNoDrawCost:.9,deqFastCost:.9,deq:function(e,t){return e.dequeue(t)},onDeqd:Re,shouldRedraw:Ae,priority:function(e){return e.renderer.beforeRenderPriorities.lyrTxrDeq}});var Mu,Bu={};function Nu(e,t){for(var n=0;n<t.length;n++){var r=t[n];e.lineTo(r.x,r.y)}}function zu(e,t,n){for(var r,i=0;i<t.length;i++){var a=t[i];0===i&&(r=a),e.lineTo(a.x,a.y)}e.quadraticCurveTo(n.x,n.y,r.x,r.y)}function Iu(e,t,n){e.beginPath&&e.beginPath();for(var r=t,i=0;i<r.length;i++){var a=r[i];e.lineTo(a.x,a.y)}var o=n,s=n[0];e.moveTo(s.x,s.y);for(i=1;i<o.length;i++){a=o[i];e.lineTo(a.x,a.y)}e.closePath&&e.closePath()}function Au(e,t,n,r,i){e.beginPath&&e.beginPath(),e.arc(n,r,i,0,2*Math.PI,!1);var a=t,o=a[0];e.moveTo(o.x,o.y);for(var s=0;s<a.length;s++){var l=a[s];e.lineTo(l.x,l.y)}e.closePath&&e.closePath()}function Lu(e,t,n,r){e.arc(t,n,r,0,2*Math.PI,!1)}Bu.arrowShapeImpl=function(e){return(Mu||(Mu={polygon:Nu,"triangle-backcurve":zu,"triangle-tee":Iu,"circle-triangle":Au,"triangle-cross":Iu,circle:Lu}))[e]};var Ou={drawElement:function(e,t,n,r,i,a){t.isNode()?this.drawNode(e,t,n,r,i,a):this.drawEdge(e,t,n,r,i,a)},drawElementOverlay:function(e,t){t.isNode()?this.drawNodeOverlay(e,t):this.drawEdgeOverlay(e,t)},drawElementUnderlay:function(e,t){t.isNode()?this.drawNodeUnderlay(e,t):this.drawEdgeUnderlay(e,t)},drawCachedElementPortion:function(e,t,n,r,i,a,o,s){var l=this,u=n.getBoundingBox(t);if(0!==u.w&&0!==u.h){var c=n.getElement(t,u,r,i,a);if(null!=c){var d=s(l,t);if(0===d)return;var h,p,f,g,v,y,m=o(l,t),b=u.x1,x=u.y1,w=u.w,E=u.h;if(0!==m){var k=n.getRotationPoint(t);f=k.x,g=k.y,e.translate(f,g),e.rotate(m),(v=l.getImgSmoothing(e))||l.setImgSmoothing(e,!0);var C=n.getRotationOffset(t);h=C.x,p=C.y}else h=b,p=x;1!==d&&(y=e.globalAlpha,e.globalAlpha=y*d),e.drawImage(c.texture.canvas,c.x,0,c.width,c.height,h,p,w,E),1!==d&&(e.globalAlpha=y),0!==m&&(e.rotate(-m),e.translate(-f,-g),v||l.setImgSmoothing(e,!1))}else n.drawElement(e,t)}}},Ru=function(){return 0},Vu=function(e,t){return e.getTextAngle(t,null)},Fu=function(e,t){return e.getTextAngle(t,"source")},ju=function(e,t){return e.getTextAngle(t,"target")},qu=function(e,t){return t.effectiveOpacity()},Yu=function(e,t){return t.pstyle("text-opacity").pfValue*t.effectiveOpacity()};Ou.drawCachedElement=function(e,t,n,r,i,a){var o=this,s=o.data,l=s.eleTxrCache,u=s.lblTxrCache,c=s.slbTxrCache,d=s.tlbTxrCache,h=t.boundingBox(),p=!0===a?l.reasons.highQuality:null;if(0!==h.w&&0!==h.h&&t.visible()&&(!r||At(h,r))){var f=t.isEdge(),g=t.element()._private.rscratch.badLine;o.drawElementUnderlay(e,t),o.drawCachedElementPortion(e,t,l,n,i,p,Ru,qu),f&&g||o.drawCachedElementPortion(e,t,u,n,i,p,Vu,Yu),f&&!g&&(o.drawCachedElementPortion(e,t,c,n,i,p,Fu,Yu),o.drawCachedElementPortion(e,t,d,n,i,p,ju,Yu)),o.drawElementOverlay(e,t)}},Ou.drawElements=function(e,t){for(var n=0;n<t.length;n++){var r=t[n];this.drawElement(e,r)}},Ou.drawCachedElements=function(e,t,n,r){for(var i=0;i<t.length;i++){var a=t[i];this.drawCachedElement(e,a,n,r)}},Ou.drawCachedNodes=function(e,t,n,r){for(var i=0;i<t.length;i++){var a=t[i];a.isNode()&&this.drawCachedElement(e,a,n,r)}},Ou.drawLayeredElements=function(e,t,n,r){var i=this.data.lyrTxrCache.getLayers(t,n);if(i)for(var a=0;a<i.length;a++){var o=i[a],s=o.bb;0!==s.w&&0!==s.h&&e.drawImage(o.canvas,s.x1,s.y1,s.w,s.h)}else this.drawCachedElements(e,t,n,r)};var Xu={drawEdge:function(e,t,n){var r=!(arguments.length>3&&void 0!==arguments[3])||arguments[3],i=!(arguments.length>4&&void 0!==arguments[4])||arguments[4],a=!(arguments.length>5&&void 0!==arguments[5])||arguments[5],o=this,s=t._private.rscratch;if((!a||t.visible())&&!s.badLine&&null!=s.allpts&&!isNaN(s.allpts[0])){var l;n&&(l=n,e.translate(-l.x1,-l.y1));var u=a?t.pstyle("opacity").value:1,c=a?t.pstyle("line-opacity").value:1,d=t.pstyle("curve-style").value,h=t.pstyle("line-style").value,p=t.pstyle("width").pfValue,f=t.pstyle("line-cap").value,g=t.pstyle("line-outline-width").value,v=t.pstyle("line-outline-color").value,y=u*c,m=u*c,b=function(){var n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:y;"straight-triangle"===d?(o.eleStrokeStyle(e,t,n),o.drawEdgeTrianglePath(t,e,s.allpts)):(e.lineWidth=p,e.lineCap=f,o.eleStrokeStyle(e,t,n),o.drawEdgePath(t,e,s.allpts,h),e.lineCap="butt")},x=function(){var n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:y;e.lineWidth=p+g,e.lineCap=f,g>0?(o.colorStrokeStyle(e,v[0],v[1],v[2],n),"straight-triangle"===d?o.drawEdgeTrianglePath(t,e,s.allpts):(o.drawEdgePath(t,e,s.allpts,h),e.lineCap="butt")):e.lineCap="butt"},w=function(){i&&o.drawEdgeOverlay(e,t)},E=function(){i&&o.drawEdgeUnderlay(e,t)},k=function(){var n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:m;o.drawArrowheads(e,t,n)},C=function(){o.drawElementText(e,t,null,r)};e.lineJoin="round";var S="yes"===t.pstyle("ghost").value;if(S){var P=t.pstyle("ghost-offset-x").pfValue,D=t.pstyle("ghost-offset-y").pfValue,T=t.pstyle("ghost-opacity").value,_=y*T;e.translate(P,D),b(_),k(_),e.translate(-P,-D)}else x();E(),b(),k(),w(),C(),n&&e.translate(l.x1,l.y1)}}},Wu=function(e){if(!["overlay","underlay"].includes(e))throw new Error("Invalid state");return function(t,n){if(n.visible()){var r=n.pstyle("".concat(e,"-opacity")).value;if(0!==r){var i=this,a=i.usePaths(),o=n._private.rscratch,s=2*n.pstyle("".concat(e,"-padding")).pfValue,l=n.pstyle("".concat(e,"-color")).value;t.lineWidth=s,"self"!==o.edgeType||a?t.lineCap="round":t.lineCap="butt",i.colorStrokeStyle(t,l[0],l[1],l[2],r),i.drawEdgePath(n,t,o.allpts,"solid")}}}};Xu.drawEdgeOverlay=Wu("overlay"),Xu.drawEdgeUnderlay=Wu("underlay"),Xu.drawEdgePath=function(e,t,n,r){var i,a=e._private.rscratch,o=t,s=!1,u=this.usePaths(),c=e.pstyle("line-dash-pattern").pfValue,d=e.pstyle("line-dash-offset").pfValue;if(u){var h=n.join("$");a.pathCacheKey&&a.pathCacheKey===h?(i=t=a.pathCache,s=!0):(i=t=new Path2D,a.pathCacheKey=h,a.pathCache=i)}if(o.setLineDash)switch(r){case"dotted":o.setLineDash([1,1]);break;case"dashed":o.setLineDash(c),o.lineDashOffset=d;break;case"solid":o.setLineDash([])}if(!s&&!a.badLine)switch(t.beginPath&&t.beginPath(),t.moveTo(n[0],n[1]),a.edgeType){case"bezier":case"self":case"compound":case"multibezier":for(var p=2;p+3<n.length;p+=4)t.quadraticCurveTo(n[p],n[p+1],n[p+2],n[p+3]);break;case"straight":case"haystack":for(var f=2;f+1<n.length;f+=2)t.lineTo(n[f],n[f+1]);break;case"segments":if(a.isRound){var g,v=l(a.roundCorners);try{for(v.s();!(g=v.n()).done;){Ql(t,g.value)}}catch(e){v.e(e)}finally{v.f()}t.lineTo(n[n.length-2],n[n.length-1])}else for(var y=2;y+1<n.length;y+=2)t.lineTo(n[y],n[y+1])}t=o,u?t.stroke(i):t.stroke(),t.setLineDash&&t.setLineDash([])},Xu.drawEdgeTrianglePath=function(e,t,n){t.fillStyle=t.strokeStyle;for(var r=e.pstyle("width").pfValue,i=0;i+1<n.length;i+=2){var a=[n[i+2]-n[i],n[i+3]-n[i+1]],o=Math.sqrt(a[0]*a[0]+a[1]*a[1]),s=[a[1]/o,-a[0]/o],l=[s[0]*r/2,s[1]*r/2];t.beginPath(),t.moveTo(n[i]-l[0],n[i+1]-l[1]),t.lineTo(n[i]+l[0],n[i+1]+l[1]),t.lineTo(n[i+2],n[i+3]),t.closePath(),t.fill()}},Xu.drawArrowheads=function(e,t,n){var r=t._private.rscratch,i="haystack"===r.edgeType;i||this.drawArrowhead(e,t,"source",r.arrowStartX,r.arrowStartY,r.srcArrowAngle,n),this.drawArrowhead(e,t,"mid-target",r.midX,r.midY,r.midtgtArrowAngle,n),this.drawArrowhead(e,t,"mid-source",r.midX,r.midY,r.midsrcArrowAngle,n),i||this.drawArrowhead(e,t,"target",r.arrowEndX,r.arrowEndY,r.tgtArrowAngle,n)},Xu.drawArrowhead=function(e,t,n,r,i,a,o){if(!(isNaN(r)||null==r||isNaN(i)||null==i||isNaN(a)||null==a)){var s=t.pstyle(n+"-arrow-shape").value;if("none"!==s){var l="hollow"===t.pstyle(n+"-arrow-fill").value?"both":"filled",u=t.pstyle(n+"-arrow-fill").value,c=t.pstyle("width").pfValue,d=t.pstyle(n+"-arrow-width"),h="match-line"===d.value?c:d.pfValue;"%"===d.units&&(h*=c);var p=t.pstyle("opacity").value;void 0===o&&(o=p);var f=e.globalCompositeOperation;1===o&&"hollow"!==u||(e.globalCompositeOperation="destination-out",this.colorFillStyle(e,255,255,255,1),this.colorStrokeStyle(e,255,255,255,1),this.drawArrowShape(t,e,l,c,s,h,r,i,a),e.globalCompositeOperation=f);var g=t.pstyle(n+"-arrow-color").value;this.colorFillStyle(e,g[0],g[1],g[2],o),this.colorStrokeStyle(e,g[0],g[1],g[2],o),this.drawArrowShape(t,e,u,c,s,h,r,i,a)}}},Xu.drawArrowShape=function(e,t,n,r,i,a,o,s,l){var u,c=this,d=this.usePaths()&&"triangle-cross"!==i,h=!1,p=t,f={x:o,y:s},g=e.pstyle("arrow-scale").value,v=this.getArrowWidth(r,g),y=c.arrowShapes[i];if(d){var m=c.arrowPathCache=c.arrowPathCache||[],b=Te(i),x=m[b];null!=x?(u=t=x,h=!0):(u=t=new Path2D,m[b]=u)}h||(t.beginPath&&t.beginPath(),d?y.draw(t,1,0,{x:0,y:0},1):y.draw(t,v,l,f,r),t.closePath&&t.closePath()),t=p,d&&(t.translate(o,s),t.rotate(l),t.scale(v,v)),"filled"!==n&&"both"!==n||(d?t.fill(u):t.fill()),"hollow"!==n&&"both"!==n||(t.lineWidth=a/(d?v:1),t.lineJoin="miter",d?t.stroke(u):t.stroke()),d&&(t.scale(1/v,1/v),t.rotate(-l),t.translate(-o,-s))};var Hu={safeDrawImage:function(e,t,n,r,i,a,o,s,l,u){if(!(i<=0||a<=0||l<=0||u<=0))try{e.drawImage(t,n,r,i,a,o,s,l,u)}catch(e){je(e)}},drawInscribedImage:function(e,t,n,r,i){var a=this,o=n.position(),s=o.x,l=o.y,u=n.cy().style(),c=u.getIndexedStyle.bind(u),d=c(n,"background-fit","value",r),h=c(n,"background-repeat","value",r),p=n.width(),f=n.height(),g=2*n.padding(),v=p+("inner"===c(n,"background-width-relative-to","value",r)?0:g),y=f+("inner"===c(n,"background-height-relative-to","value",r)?0:g),m=n._private.rscratch,b="node"===c(n,"background-clip","value",r),x=c(n,"background-image-opacity","value",r)*i,w=c(n,"background-image-smoothing","value",r),E=n.pstyle("corner-radius").value;"auto"!==E&&(E=n.pstyle("corner-radius").pfValue);var k=t.width||t.cachedW,C=t.height||t.cachedH;null!=k&&null!=C||(document.body.appendChild(t),k=t.cachedW=t.width||t.offsetWidth,C=t.cachedH=t.height||t.offsetHeight,document.body.removeChild(t));var S=k,P=C;if("auto"!==c(n,"background-width","value",r)&&(S="%"===c(n,"background-width","units",r)?c(n,"background-width","pfValue",r)*v:c(n,"background-width","pfValue",r)),"auto"!==c(n,"background-height","value",r)&&(P="%"===c(n,"background-height","units",r)?c(n,"background-height","pfValue",r)*y:c(n,"background-height","pfValue",r)),0!==S&&0!==P){if("contain"===d)S*=D=Math.min(v/S,y/P),P*=D;else if("cover"===d){var D;S*=D=Math.max(v/S,y/P),P*=D}var T=s-v/2,_=c(n,"background-position-x","units",r),M=c(n,"background-position-x","pfValue",r);T+="%"===_?(v-S)*M:M;var B=c(n,"background-offset-x","units",r),N=c(n,"background-offset-x","pfValue",r);T+="%"===B?(v-S)*N:N;var z=l-y/2,I=c(n,"background-position-y","units",r),A=c(n,"background-position-y","pfValue",r);z+="%"===I?(y-P)*A:A;var L=c(n,"background-offset-y","units",r),O=c(n,"background-offset-y","pfValue",r);z+="%"===L?(y-P)*O:O,m.pathCache&&(T-=s,z-=l,s=0,l=0);var R=e.globalAlpha;e.globalAlpha=x;var V=a.getImgSmoothing(e),F=!1;if("no"===w&&V?(a.setImgSmoothing(e,!1),F=!0):"yes"!==w||V||(a.setImgSmoothing(e,!0),F=!0),"no-repeat"===h)b&&(e.save(),m.pathCache?e.clip(m.pathCache):(a.nodeShapes[a.getNodeShape(n)].draw(e,s,l,v,y,E,m),e.clip())),a.safeDrawImage(e,t,0,0,k,C,T,z,S,P),b&&e.restore();else{var j=e.createPattern(t,h);e.fillStyle=j,a.nodeShapes[a.getNodeShape(n)].draw(e,s,l,v,y,E,m),e.translate(T,z),e.fill(),e.translate(-T,-z)}e.globalAlpha=R,F&&a.setImgSmoothing(e,V)}}},Ku={};function Gu(e,t,n,r,i){var a=arguments.length>5&&void 0!==arguments[5]?arguments[5]:5,o=arguments.length>6?arguments[6]:void 0;e.beginPath(),e.moveTo(t+a,n),e.lineTo(t+r-a,n),e.quadraticCurveTo(t+r,n,t+r,n+a),e.lineTo(t+r,n+i-a),e.quadraticCurveTo(t+r,n+i,t+r-a,n+i),e.lineTo(t+a,n+i),e.quadraticCurveTo(t,n+i,t,n+i-a),e.lineTo(t,n+a),e.quadraticCurveTo(t,n,t+a,n),e.closePath(),o?e.stroke():e.fill()}Ku.eleTextBiggerThanMin=function(e,t){if(!t){var n=e.cy().zoom(),r=this.getPixelRatio(),i=Math.ceil(wt(n*r));t=Math.pow(2,i)}return!(e.pstyle("font-size").pfValue*t<e.pstyle("min-zoomed-font-size").pfValue)},Ku.drawElementText=function(e,t,n,r,i){var a=!(arguments.length>5&&void 0!==arguments[5])||arguments[5],o=this;if(null==r){if(a&&!o.eleTextBiggerThanMin(t))return}else if(!1===r)return;if(t.isNode()){var s=t.pstyle("label");if(!s||!s.value)return;var l=o.getLabelJustification(t);e.textAlign=l,e.textBaseline="bottom"}else{var u=t.element()._private.rscratch.badLine,c=t.pstyle("label"),d=t.pstyle("source-label"),h=t.pstyle("target-label");if(u||(!c||!c.value)&&(!d||!d.value)&&(!h||!h.value))return;e.textAlign="center",e.textBaseline="bottom"}var p,f=!n;n&&(p=n,e.translate(-p.x1,-p.y1)),null==i?(o.drawText(e,t,null,f,a),t.isEdge()&&(o.drawText(e,t,"source",f,a),o.drawText(e,t,"target",f,a))):o.drawText(e,t,i,f,a),n&&e.translate(p.x1,p.y1)},Ku.getFontCache=function(e){var t;this.fontCaches=this.fontCaches||[];for(var n=0;n<this.fontCaches.length;n++)if((t=this.fontCaches[n]).context===e)return t;return t={context:e},this.fontCaches.push(t),t},Ku.setupTextStyle=function(e,t){var n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],r=t.pstyle("font-style").strValue,i=t.pstyle("font-size").pfValue+"px",a=t.pstyle("font-family").strValue,o=t.pstyle("font-weight").strValue,s=n?t.effectiveOpacity()*t.pstyle("text-opacity").value:1,l=t.pstyle("text-outline-opacity").value*s,u=t.pstyle("color").value,c=t.pstyle("text-outline-color").value;e.font=r+" "+o+" "+i+" "+a,e.lineJoin="round",this.colorFillStyle(e,u[0],u[1],u[2],s),this.colorStrokeStyle(e,c[0],c[1],c[2],l)},Ku.getTextAngle=function(e,t){var n=e._private.rscratch,r=t?t+"-":"",i=e.pstyle(r+"text-rotation"),a=Ue(n,"labelAngle",t);return"autorotate"===i.strValue?e.isEdge()?a:0:"none"===i.strValue?0:i.pfValue},Ku.drawText=function(e,t,n){var r=!(arguments.length>3&&void 0!==arguments[3])||arguments[3],i=!(arguments.length>4&&void 0!==arguments[4])||arguments[4],a=t._private,o=a.rscratch,s=i?t.effectiveOpacity():1;if(!i||0!==s&&0!==t.pstyle("text-opacity").value){"main"===n&&(n=null);var l,u,c=Ue(o,"labelX",n),d=Ue(o,"labelY",n),h=this.getLabelText(t,n);if(null!=h&&""!==h&&!isNaN(c)&&!isNaN(d)){this.setupTextStyle(e,t,i);var p,f=n?n+"-":"",g=Ue(o,"labelWidth",n),v=Ue(o,"labelHeight",n),y=t.pstyle(f+"text-margin-x").pfValue,m=t.pstyle(f+"text-margin-y").pfValue,b=t.isEdge(),x=t.pstyle("text-halign").value,w=t.pstyle("text-valign").value;switch(b&&(x="center",w="center"),c+=y,d+=m,0!==(p=r?this.getTextAngle(t,n):0)&&(l=c,u=d,e.translate(l,u),e.rotate(p),c=0,d=0),w){case"top":break;case"center":d+=v/2;break;case"bottom":d+=v}var E=t.pstyle("text-background-opacity").value,k=t.pstyle("text-border-opacity").value,C=t.pstyle("text-border-width").pfValue,S=t.pstyle("text-background-padding").pfValue,P=t.pstyle("text-background-shape").strValue,D=0===P.indexOf("round"),T=2;if(E>0||C>0&&k>0){var _=c-S;switch(x){case"left":_-=g;break;case"center":_-=g/2}var M=d-v-S,B=g+2*S,N=v+2*S;if(E>0){var z=e.fillStyle,I=t.pstyle("text-background-color").value;e.fillStyle="rgba("+I[0]+","+I[1]+","+I[2]+","+E*s+")",D?Gu(e,_,M,B,N,T):e.fillRect(_,M,B,N),e.fillStyle=z}if(C>0&&k>0){var A=e.strokeStyle,L=e.lineWidth,O=t.pstyle("text-border-color").value,R=t.pstyle("text-border-style").value;if(e.strokeStyle="rgba("+O[0]+","+O[1]+","+O[2]+","+k*s+")",e.lineWidth=C,e.setLineDash)switch(R){case"dotted":e.setLineDash([1,1]);break;case"dashed":e.setLineDash([4,2]);break;case"double":e.lineWidth=C/4,e.setLineDash([]);break;case"solid":e.setLineDash([])}if(D?Gu(e,_,M,B,N,T,"stroke"):e.strokeRect(_,M,B,N),"double"===R){var V=C/2;D?Gu(e,_+V,M+V,B-2*V,N-2*V,T,"stroke"):e.strokeRect(_+V,M+V,B-2*V,N-2*V)}e.setLineDash&&e.setLineDash([]),e.lineWidth=L,e.strokeStyle=A}}var F=2*t.pstyle("text-outline-width").pfValue;if(F>0&&(e.lineWidth=F),"wrap"===t.pstyle("text-wrap").value){var j=Ue(o,"labelWrapCachedLines",n),q=Ue(o,"labelLineHeight",n),Y=g/2,X=this.getLabelJustification(t);switch("auto"===X||("left"===x?"left"===X?c+=-g:"center"===X&&(c+=-Y):"center"===x?"left"===X?c+=-Y:"right"===X&&(c+=Y):"right"===x&&("center"===X?c+=Y:"right"===X&&(c+=g))),w){case"top":d-=(j.length-1)*q;break;case"center":case"bottom":d-=(j.length-1)*q}for(var W=0;W<j.length;W++)F>0&&e.strokeText(j[W],c,d),e.fillText(j[W],c,d),d+=q}else F>0&&e.strokeText(h,c,d),e.fillText(h,c,d);0!==p&&(e.rotate(-p),e.translate(-l,-u))}}};var Uu={drawNode:function(e,t,n){var r,i,a=!(arguments.length>3&&void 0!==arguments[3])||arguments[3],o=!(arguments.length>4&&void 0!==arguments[4])||arguments[4],s=!(arguments.length>5&&void 0!==arguments[5])||arguments[5],l=this,u=t._private,c=u.rscratch,d=t.position();if(x(d.x)&&x(d.y)&&(!s||t.visible())){var h,p,f=s?t.effectiveOpacity():1,g=l.usePaths(),v=!1,y=t.padding();r=t.width()+2*y,i=t.height()+2*y,n&&(p=n,e.translate(-p.x1,-p.y1));for(var m=t.pstyle("background-image"),b=m.value,w=new Array(b.length),E=new Array(b.length),k=0,C=0;C<b.length;C++){var S=b[C],P=w[C]=null!=S&&"none"!==S;if(P){var D=t.cy().style().getIndexedStyle(t,"background-image-crossorigin","value",C);k++,E[C]=l.getCachedImage(S,D,(function(){u.backgroundTimestamp=Date.now(),t.emitAndNotify("background")}))}}var T=t.pstyle("background-blacken").value,_=t.pstyle("border-width").pfValue,M=t.pstyle("background-opacity").value*f,B=t.pstyle("border-color").value,N=t.pstyle("border-style").value,z=t.pstyle("border-join").value,I=t.pstyle("border-cap").value,A=t.pstyle("border-position").value,L=t.pstyle("border-dash-pattern").pfValue,O=t.pstyle("border-dash-offset").pfValue,R=t.pstyle("border-opacity").value*f,V=t.pstyle("outline-width").pfValue,F=t.pstyle("outline-color").value,j=t.pstyle("outline-style").value,q=t.pstyle("outline-opacity").value*f,Y=t.pstyle("outline-offset").value,X=t.pstyle("corner-radius").value;"auto"!==X&&(X=t.pstyle("corner-radius").pfValue);var W=function(){var n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:M;l.eleFillStyle(e,t,n)},H=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:R;l.colorStrokeStyle(e,B[0],B[1],B[2],t)},K=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:q;l.colorStrokeStyle(e,F[0],F[1],F[2],t)},G=function(e,t,n,r){var i,a=l.nodePathCache=l.nodePathCache||[],o=_e("polygon"===n?n+","+r.join(","):n,""+t,""+e,""+X),s=a[o],u=!1;return null!=s?(i=s,u=!0,c.pathCache=i):(i=new Path2D,a[o]=c.pathCache=i),{path:i,cacheHit:u}},U=t.pstyle("shape").strValue,Z=t.pstyle("shape-polygon-points").pfValue;if(g){e.translate(d.x,d.y);var $=G(r,i,U,Z);h=$.path,v=$.cacheHit}var Q=function(){if(!v){var n=d;g&&(n={x:0,y:0}),l.nodeShapes[l.getNodeShape(t)].draw(h||e,n.x,n.y,r,i,X,c)}g?e.fill(h):e.fill()},J=function(){for(var n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:f,r=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],i=u.backgrounding,a=0,o=0;o<E.length;o++){var s=t.cy().style().getIndexedStyle(t,"background-image-containment","value",o);r&&"over"===s||!r&&"inside"===s?a++:w[o]&&E[o].complete&&!E[o].error&&(a++,l.drawInscribedImage(e,E[o],t,o,n))}u.backgrounding=!(a===k),i!==u.backgrounding&&t.updateStyle(!1)},ee=function(){var n=arguments.length>0&&void 0!==arguments[0]&&arguments[0],a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:f;l.hasPie(t)&&(l.drawPie(e,t,a),n&&(g||l.nodeShapes[l.getNodeShape(t)].draw(e,d.x,d.y,r,i,X,c)))},te=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:f,n=(T>0?T:-T)*t,r=T>0?0:255;0!==T&&(l.colorFillStyle(e,r,r,r,n),g?e.fill(h):e.fill())},ne=function(){if(_>0){if(e.lineWidth=_,e.lineCap=I,e.lineJoin=z,e.setLineDash)switch(N){case"dotted":e.setLineDash([1,1]);break;case"dashed":e.setLineDash(L),e.lineDashOffset=O;break;case"solid":case"double":e.setLineDash([])}if("center"!==A){if(e.save(),e.lineWidth*=2,"inside"===A)g?e.clip(h):e.clip();else{var t=new Path2D;t.rect(-r/2-_,-i/2-_,r+2*_,i+2*_),t.addPath(h),e.clip(t,"evenodd")}g?e.stroke(h):e.stroke(),e.restore()}else g?e.stroke(h):e.stroke();if("double"===N){e.lineWidth=_/3;var n=e.globalCompositeOperation;e.globalCompositeOperation="destination-out",g?e.stroke(h):e.stroke(),e.globalCompositeOperation=n}e.setLineDash&&e.setLineDash([])}},re=function(){if(V>0){if(e.lineWidth=V,e.lineCap="butt",e.setLineDash)switch(j){case"dotted":e.setLineDash([1,1]);break;case"dashed":e.setLineDash([4,2]);break;case"solid":case"double":e.setLineDash([])}var n=d;g&&(n={x:0,y:0});var a=l.getNodeShape(t),o=_;"inside"===A&&(o=0),"outside"===A&&(o*=2);var s,u=(r+o+(V+Y))/r,c=(i+o+(V+Y))/i,h=r*u,p=i*c,f=l.nodeShapes[a].points;if(g)s=G(h,p,a,f).path;if("ellipse"===a)l.drawEllipsePath(s||e,n.x,n.y,h,p);else if(["round-diamond","round-heptagon","round-hexagon","round-octagon","round-pentagon","round-polygon","round-triangle","round-tag"].includes(a)){var v=0,y=0,m=0;"round-diamond"===a?v=1.4*(o+Y+V):"round-heptagon"===a?(v=1.075*(o+Y+V),m=-(o/2+Y+V)/35):"round-hexagon"===a?v=1.12*(o+Y+V):"round-pentagon"===a?(v=1.13*(o+Y+V),m=-(o/2+Y+V)/15):"round-tag"===a?(v=1.12*(o+Y+V),y=.07*(o/2+V+Y)):"round-triangle"===a&&(v=(o+Y+V)*(Math.PI/2),m=-(o+Y/2+V)/Math.PI),0!==v&&(h=r*(u=(r+v)/r),["round-hexagon","round-tag"].includes(a)||(p=i*(c=(i+v)/i)));for(var b=h/2,x=p/2,w=(X="auto"===X?rn(h,p):X)+(o+V+Y)/2,E=new Array(f.length/2),k=new Array(f.length/2),C=0;C<f.length/2;C++)E[C]={x:n.x+y+b*f[2*C],y:n.y+m+x*f[2*C+1]};var S,P,D,T,M=E.length;for(P=E[M-1],S=0;S<M;S++)D=E[S%M],T=E[(S+1)%M],k[S]=Jl(P,D,T,w),P=D,D=T;l.drawRoundPolygonPath(s||e,n.x+y,n.y+m,r*u,i*c,f,k)}else if(["roundrectangle","round-rectangle"].includes(a))X="auto"===X?nn(h,p):X,l.drawRoundRectanglePath(s||e,n.x,n.y,h,p,X+(o+V+Y)/2);else if(["cutrectangle","cut-rectangle"].includes(a))X="auto"===X?8:X,l.drawCutRectanglePath(s||e,n.x,n.y,h,p,null,X+(o+V+Y)/4);else if(["bottomroundrectangle","bottom-round-rectangle"].includes(a))X="auto"===X?nn(h,p):X,l.drawBottomRoundRectanglePath(s||e,n.x,n.y,h,p,X+(o+V+Y)/2);else if("barrel"===a)l.drawBarrelPath(s||e,n.x,n.y,h,p);else if(a.startsWith("polygon")||["rhomboid","right-rhomboid","round-tag","tag","vee"].includes(a)){f=Wt(Ht(f,(o+V+Y)/r)),l.drawPolygonPath(s||e,n.x,n.y,r,i,f)}else{f=Wt(Ht(f,-((o+V+Y)/r))),l.drawPolygonPath(s||e,n.x,n.y,r,i,f)}if(g?e.stroke(s):e.stroke(),"double"===j){e.lineWidth=o/3;var B=e.globalCompositeOperation;e.globalCompositeOperation="destination-out",g?e.stroke(s):e.stroke(),e.globalCompositeOperation=B}e.setLineDash&&e.setLineDash([])}},ie=function(){o&&l.drawNodeOverlay(e,t,d,r,i)},ae=function(){o&&l.drawNodeUnderlay(e,t,d,r,i)},oe=function(){l.drawElementText(e,t,null,a)},se="yes"===t.pstyle("ghost").value;if(se){var le=t.pstyle("ghost-offset-x").pfValue,ue=t.pstyle("ghost-offset-y").pfValue,ce=t.pstyle("ghost-opacity").value,de=ce*f;e.translate(le,ue),K(),re(),W(ce*M),Q(),J(de,!0),H(ce*R),ne(),ee(0!==T||0!==_),J(de,!1),te(de),e.translate(-le,-ue)}g&&e.translate(-d.x,-d.y),ae(),g&&e.translate(d.x,d.y),K(),re(),W(),Q(),J(f,!0),H(),ne(),ee(0!==T||0!==_),J(f,!1),te(),g&&e.translate(-d.x,-d.y),oe(),ie(),n&&e.translate(p.x1,p.y1)}}},Zu=function(e){if(!["overlay","underlay"].includes(e))throw new Error("Invalid state");return function(t,n,r,i,a){if(n.visible()){var o=n.pstyle("".concat(e,"-padding")).pfValue,s=n.pstyle("".concat(e,"-opacity")).value,l=n.pstyle("".concat(e,"-color")).value,u=n.pstyle("".concat(e,"-shape")).value,c=n.pstyle("".concat(e,"-corner-radius")).value;if(s>0){if(r=r||n.position(),null==i||null==a){var d=n.padding();i=n.width()+2*d,a=n.height()+2*d}this.colorFillStyle(t,l[0],l[1],l[2],s),this.nodeShapes[u].draw(t,r.x,r.y,i+2*o,a+2*o,c),t.fill()}}}};Uu.drawNodeOverlay=Zu("overlay"),Uu.drawNodeUnderlay=Zu("underlay"),Uu.hasPie=function(e){return(e=e[0])._private.hasPie},Uu.drawPie=function(e,t,n,r){t=t[0],r=r||t.position();var i=t.cy().style(),a=t.pstyle("pie-size"),o=r.x,s=r.y,l=t.width(),u=t.height(),c=Math.min(l,u)/2,d=0;this.usePaths()&&(o=0,s=0),"%"===a.units?c*=a.pfValue:void 0!==a.pfValue&&(c=a.pfValue/2);for(var h=1;h<=i.pieBackgroundN;h++){var p=t.pstyle("pie-"+h+"-background-size").value,f=t.pstyle("pie-"+h+"-background-color").value,g=t.pstyle("pie-"+h+"-background-opacity").value*n,v=p/100;v+d>1&&(v=1-d);var y=1.5*Math.PI+2*Math.PI*d,m=y+2*Math.PI*v;0===p||d>=1||d+v>1||(e.beginPath(),e.moveTo(o,s),e.arc(o,s,c,y,m),e.closePath(),this.colorFillStyle(e,f[0],f[1],f[2],g),e.fill(),d+=v)}};var $u={};$u.getPixelRatio=function(){var e=this.data.contexts[0];if(null!=this.forcedPixelRatio)return this.forcedPixelRatio;var t=this.cy.window(),n=e.backingStorePixelRatio||e.webkitBackingStorePixelRatio||e.mozBackingStorePixelRatio||e.msBackingStorePixelRatio||e.oBackingStorePixelRatio||e.backingStorePixelRatio||1;return(t.devicePixelRatio||1)/n},$u.paintCache=function(e){for(var t,n=this.paintCaches=this.paintCaches||[],r=!0,i=0;i<n.length;i++)if((t=n[i]).context===e){r=!1;break}return r&&(t={context:e},n.push(t)),t},$u.createGradientStyleFor=function(e,t,n,r,i){var a,o=this.usePaths(),s=n.pstyle(t+"-gradient-stop-colors").value,l=n.pstyle(t+"-gradient-stop-positions").pfValue;if("radial-gradient"===r)if(n.isEdge()){var u=n.sourceEndpoint(),c=n.targetEndpoint(),d=n.midpoint(),h=kt(u,d),p=kt(c,d);a=e.createRadialGradient(d.x,d.y,0,d.x,d.y,Math.max(h,p))}else{var f=o?{x:0,y:0}:n.position(),g=n.paddedWidth(),v=n.paddedHeight();a=e.createRadialGradient(f.x,f.y,0,f.x,f.y,Math.max(g,v))}else if(n.isEdge()){var y=n.sourceEndpoint(),m=n.targetEndpoint();a=e.createLinearGradient(y.x,y.y,m.x,m.y)}else{var b=o?{x:0,y:0}:n.position(),x=n.paddedWidth()/2,w=n.paddedHeight()/2;switch(n.pstyle("background-gradient-direction").value){case"to-bottom":a=e.createLinearGradient(b.x,b.y-w,b.x,b.y+w);break;case"to-top":a=e.createLinearGradient(b.x,b.y+w,b.x,b.y-w);break;case"to-left":a=e.createLinearGradient(b.x+x,b.y,b.x-x,b.y);break;case"to-right":a=e.createLinearGradient(b.x-x,b.y,b.x+x,b.y);break;case"to-bottom-right":case"to-right-bottom":a=e.createLinearGradient(b.x-x,b.y-w,b.x+x,b.y+w);break;case"to-top-right":case"to-right-top":a=e.createLinearGradient(b.x-x,b.y+w,b.x+x,b.y-w);break;case"to-bottom-left":case"to-left-bottom":a=e.createLinearGradient(b.x+x,b.y-w,b.x-x,b.y+w);break;case"to-top-left":case"to-left-top":a=e.createLinearGradient(b.x+x,b.y+w,b.x-x,b.y-w)}}if(!a)return null;for(var E=l.length===s.length,k=s.length,C=0;C<k;C++)a.addColorStop(E?l[C]:C/(k-1),"rgba("+s[C][0]+","+s[C][1]+","+s[C][2]+","+i+")");return a},$u.gradientFillStyle=function(e,t,n,r){var i=this.createGradientStyleFor(e,"background",t,n,r);if(!i)return null;e.fillStyle=i},$u.colorFillStyle=function(e,t,n,r,i){e.fillStyle="rgba("+t+","+n+","+r+","+i+")"},$u.eleFillStyle=function(e,t,n){var r=t.pstyle("background-fill").value;if("linear-gradient"===r||"radial-gradient"===r)this.gradientFillStyle(e,t,r,n);else{var i=t.pstyle("background-color").value;this.colorFillStyle(e,i[0],i[1],i[2],n)}},$u.gradientStrokeStyle=function(e,t,n,r){var i=this.createGradientStyleFor(e,"line",t,n,r);if(!i)return null;e.strokeStyle=i},$u.colorStrokeStyle=function(e,t,n,r,i){e.strokeStyle="rgba("+t+","+n+","+r+","+i+")"},$u.eleStrokeStyle=function(e,t,n){var r=t.pstyle("line-fill").value;if("linear-gradient"===r||"radial-gradient"===r)this.gradientStrokeStyle(e,t,r,n);else{var i=t.pstyle("line-color").value;this.colorStrokeStyle(e,i[0],i[1],i[2],n)}},$u.matchCanvasSize=function(e){var t=this,n=t.data,r=t.findContainerClientCoords(),i=r[2],a=r[3],o=t.getPixelRatio(),s=t.motionBlurPxRatio;e!==t.data.bufferCanvases[t.MOTIONBLUR_BUFFER_NODE]&&e!==t.data.bufferCanvases[t.MOTIONBLUR_BUFFER_DRAG]||(o=s);var l,u=i*o,c=a*o;if(u!==t.canvasWidth||c!==t.canvasHeight){t.fontCaches=null;var d=n.canvasContainer;d.style.width=i+"px",d.style.height=a+"px";for(var h=0;h<t.CANVAS_LAYERS;h++)(l=n.canvases[h]).width=u,l.height=c,l.style.width=i+"px",l.style.height=a+"px";for(h=0;h<t.BUFFER_COUNT;h++)(l=n.bufferCanvases[h]).width=u,l.height=c,l.style.width=i+"px",l.style.height=a+"px";t.textureMult=1,o<=1&&(l=n.bufferCanvases[t.TEXTURE_BUFFER],t.textureMult=2,l.width=u*t.textureMult,l.height=c*t.textureMult),t.canvasWidth=u,t.canvasHeight=c}},$u.renderTo=function(e,t,n,r){this.render({forcedContext:e,forcedZoom:t,forcedPan:n,drawAllLayers:!0,forcedPxRatio:r})},$u.render=function(e){var t=(e=e||We()).forcedContext,n=e.drawAllLayers,r=e.drawOnlyNodeLayer,i=e.forcedZoom,a=e.forcedPan,o=this,s=void 0===e.forcedPxRatio?this.getPixelRatio():e.forcedPxRatio,l=o.cy,u=o.data,c=u.canvasNeedsRedraw,d=o.textureOnViewport&&!t&&(o.pinching||o.hoverData.dragging||o.swipePanning||o.data.wheelZooming),h=void 0!==e.motionBlur?e.motionBlur:o.motionBlur,p=o.motionBlurPxRatio,f=l.hasCompoundNodes(),g=o.hoverData.draggingEles,v=!(!o.hoverData.selecting&&!o.touchData.selecting),y=h=h&&!t&&o.motionBlurEnabled&&!v;t||(o.prevPxRatio!==s&&(o.invalidateContainerClientCoordsCache(),o.matchCanvasSize(o.container),o.redrawHint("eles",!0),o.redrawHint("drag",!0)),o.prevPxRatio=s),!t&&o.motionBlurTimeout&&clearTimeout(o.motionBlurTimeout),h&&(null==o.mbFrames&&(o.mbFrames=0),o.mbFrames++,o.mbFrames<3&&(y=!1),o.mbFrames>o.minMbLowQualFrames&&(o.motionBlurPxRatio=o.mbPxRBlurry)),o.clearingMotionBlur&&(o.motionBlurPxRatio=1),o.textureDrawLastFrame&&!d&&(c[o.NODE]=!0,c[o.SELECT_BOX]=!0);var m=l.style(),b=l.zoom(),x=void 0!==i?i:b,w=l.pan(),E={x:w.x,y:w.y},k={zoom:b,pan:{x:w.x,y:w.y}},C=o.prevViewport;void 0===C||k.zoom!==C.zoom||k.pan.x!==C.pan.x||k.pan.y!==C.pan.y||g&&!f||(o.motionBlurPxRatio=1),a&&(E=a),x*=s,E.x*=s,E.y*=s;var S=o.getCachedZSortedEles();function P(e,t,n,r,i){var a=e.globalCompositeOperation;e.globalCompositeOperation="destination-out",o.colorFillStyle(e,255,255,255,o.motionBlurTransparency),e.fillRect(t,n,r,i),e.globalCompositeOperation=a}function D(e,r){var s,l,c,d;o.clearingMotionBlur||e!==u.bufferContexts[o.MOTIONBLUR_BUFFER_NODE]&&e!==u.bufferContexts[o.MOTIONBLUR_BUFFER_DRAG]?(s=E,l=x,c=o.canvasWidth,d=o.canvasHeight):(s={x:w.x*p,y:w.y*p},l=b*p,c=o.canvasWidth*p,d=o.canvasHeight*p),e.setTransform(1,0,0,1,0,0),"motionBlur"===r?P(e,0,0,c,d):t||void 0!==r&&!r||e.clearRect(0,0,c,d),n||(e.translate(s.x,s.y),e.scale(l,l)),a&&e.translate(a.x,a.y),i&&e.scale(i,i)}if(d||(o.textureDrawLastFrame=!1),d){if(o.textureDrawLastFrame=!0,!o.textureCache){o.textureCache={},o.textureCache.bb=l.mutableElements().boundingBox(),o.textureCache.texture=o.data.bufferCanvases[o.TEXTURE_BUFFER];var T=o.data.bufferContexts[o.TEXTURE_BUFFER];T.setTransform(1,0,0,1,0,0),T.clearRect(0,0,o.canvasWidth*o.textureMult,o.canvasHeight*o.textureMult),o.render({forcedContext:T,drawOnlyNodeLayer:!0,forcedPxRatio:s*o.textureMult}),(k=o.textureCache.viewport={zoom:l.zoom(),pan:l.pan(),width:o.canvasWidth,height:o.canvasHeight}).mpan={x:(0-k.pan.x)/k.zoom,y:(0-k.pan.y)/k.zoom}}c[o.DRAG]=!1,c[o.NODE]=!1;var _=u.contexts[o.NODE],M=o.textureCache.texture;k=o.textureCache.viewport;_.setTransform(1,0,0,1,0,0),h?P(_,0,0,k.width,k.height):_.clearRect(0,0,k.width,k.height);var B=m.core("outside-texture-bg-color").value,N=m.core("outside-texture-bg-opacity").value;o.colorFillStyle(_,B[0],B[1],B[2],N),_.fillRect(0,0,k.width,k.height);b=l.zoom();D(_,!1),_.clearRect(k.mpan.x,k.mpan.y,k.width/k.zoom/s,k.height/k.zoom/s),_.drawImage(M,k.mpan.x,k.mpan.y,k.width/k.zoom/s,k.height/k.zoom/s)}else o.textureOnViewport&&!t&&(o.textureCache=null);var z=l.extent(),I=o.pinching||o.hoverData.dragging||o.swipePanning||o.data.wheelZooming||o.hoverData.draggingEles||o.cy.animated(),A=o.hideEdgesOnViewport&&I,L=[];if(L[o.NODE]=!c[o.NODE]&&h&&!o.clearedForMotionBlur[o.NODE]||o.clearingMotionBlur,L[o.NODE]&&(o.clearedForMotionBlur[o.NODE]=!0),L[o.DRAG]=!c[o.DRAG]&&h&&!o.clearedForMotionBlur[o.DRAG]||o.clearingMotionBlur,L[o.DRAG]&&(o.clearedForMotionBlur[o.DRAG]=!0),c[o.NODE]||n||r||L[o.NODE]){var O=h&&!L[o.NODE]&&1!==p;D(_=t||(O?o.data.bufferContexts[o.MOTIONBLUR_BUFFER_NODE]:u.contexts[o.NODE]),h&&!O?"motionBlur":void 0),A?o.drawCachedNodes(_,S.nondrag,s,z):o.drawLayeredElements(_,S.nondrag,s,z),o.debug&&o.drawDebugPoints(_,S.nondrag),n||h||(c[o.NODE]=!1)}if(!r&&(c[o.DRAG]||n||L[o.DRAG])){O=h&&!L[o.DRAG]&&1!==p;D(_=t||(O?o.data.bufferContexts[o.MOTIONBLUR_BUFFER_DRAG]:u.contexts[o.DRAG]),h&&!O?"motionBlur":void 0),A?o.drawCachedNodes(_,S.drag,s,z):o.drawCachedElements(_,S.drag,s,z),o.debug&&o.drawDebugPoints(_,S.drag),n||h||(c[o.DRAG]=!1)}if(o.showFps||!r&&c[o.SELECT_BOX]&&!n){if(D(_=t||u.contexts[o.SELECT_BOX]),1==o.selection[4]&&(o.hoverData.selecting||o.touchData.selecting)){b=o.cy.zoom();var R=m.core("selection-box-border-width").value/b;_.lineWidth=R,_.fillStyle="rgba("+m.core("selection-box-color").value[0]+","+m.core("selection-box-color").value[1]+","+m.core("selection-box-color").value[2]+","+m.core("selection-box-opacity").value+")",_.fillRect(o.selection[0],o.selection[1],o.selection[2]-o.selection[0],o.selection[3]-o.selection[1]),R>0&&(_.strokeStyle="rgba("+m.core("selection-box-border-color").value[0]+","+m.core("selection-box-border-color").value[1]+","+m.core("selection-box-border-color").value[2]+","+m.core("selection-box-opacity").value+")",_.strokeRect(o.selection[0],o.selection[1],o.selection[2]-o.selection[0],o.selection[3]-o.selection[1]))}if(u.bgActivePosistion&&!o.hoverData.selecting){b=o.cy.zoom();var V=u.bgActivePosistion;_.fillStyle="rgba("+m.core("active-bg-color").value[0]+","+m.core("active-bg-color").value[1]+","+m.core("active-bg-color").value[2]+","+m.core("active-bg-opacity").value+")",_.beginPath(),_.arc(V.x,V.y,m.core("active-bg-size").pfValue/b,0,2*Math.PI),_.fill()}var F=o.lastRedrawTime;if(o.showFps&&F){F=Math.round(F);var j=Math.round(1e3/F);_.setTransform(1,0,0,1,0,0),_.fillStyle="rgba(255, 0, 0, 0.75)",_.strokeStyle="rgba(255, 0, 0, 0.75)",_.lineWidth=1,_.fillText("1 frame = "+F+" ms = "+j+" fps",0,20);_.strokeRect(0,30,250,20),_.fillRect(0,30,250*Math.min(j/60,1),20)}n||(c[o.SELECT_BOX]=!1)}if(h&&1!==p){var q=u.contexts[o.NODE],Y=o.data.bufferCanvases[o.MOTIONBLUR_BUFFER_NODE],X=u.contexts[o.DRAG],W=o.data.bufferCanvases[o.MOTIONBLUR_BUFFER_DRAG],H=function(e,t,n){e.setTransform(1,0,0,1,0,0),n||!y?e.clearRect(0,0,o.canvasWidth,o.canvasHeight):P(e,0,0,o.canvasWidth,o.canvasHeight);var r=p;e.drawImage(t,0,0,o.canvasWidth*r,o.canvasHeight*r,0,0,o.canvasWidth,o.canvasHeight)};(c[o.NODE]||L[o.NODE])&&(H(q,Y,L[o.NODE]),c[o.NODE]=!1),(c[o.DRAG]||L[o.DRAG])&&(H(X,W,L[o.DRAG]),c[o.DRAG]=!1)}o.prevViewport=k,o.clearingMotionBlur&&(o.clearingMotionBlur=!1,o.motionBlurCleared=!0,o.motionBlur=!0),h&&(o.motionBlurTimeout=setTimeout((function(){o.motionBlurTimeout=null,o.clearedForMotionBlur[o.NODE]=!1,o.clearedForMotionBlur[o.DRAG]=!1,o.motionBlur=!1,o.clearingMotionBlur=!d,o.mbFrames=0,c[o.NODE]=!0,c[o.DRAG]=!0,o.redraw()}),100)),t||l.emit("render")};for(var Qu={drawPolygonPath:function(e,t,n,r,i,a){var o=r/2,s=i/2;e.beginPath&&e.beginPath(),e.moveTo(t+o*a[0],n+s*a[1]);for(var l=1;l<a.length/2;l++)e.lineTo(t+o*a[2*l],n+s*a[2*l+1]);e.closePath()},drawRoundPolygonPath:function(e,t,n,r,i,a,o){o.forEach((function(t){return Ql(e,t)})),e.closePath()},drawRoundRectanglePath:function(e,t,n,r,i,a){var o=r/2,s=i/2,l="auto"===a?nn(r,i):Math.min(a,s,o);e.beginPath&&e.beginPath(),e.moveTo(t,n-s),e.arcTo(t+o,n-s,t+o,n,l),e.arcTo(t+o,n+s,t,n+s,l),e.arcTo(t-o,n+s,t-o,n,l),e.arcTo(t-o,n-s,t,n-s,l),e.lineTo(t,n-s),e.closePath()},drawBottomRoundRectanglePath:function(e,t,n,r,i,a){var o=r/2,s=i/2,l="auto"===a?nn(r,i):a;e.beginPath&&e.beginPath(),e.moveTo(t,n-s),e.lineTo(t+o,n-s),e.lineTo(t+o,n),e.arcTo(t+o,n+s,t,n+s,l),e.arcTo(t-o,n+s,t-o,n,l),e.lineTo(t-o,n-s),e.lineTo(t,n-s),e.closePath()},drawCutRectanglePath:function(e,t,n,r,i,a,o){var s=r/2,l=i/2,u="auto"===o?8:o;e.beginPath&&e.beginPath(),e.moveTo(t-s+u,n-l),e.lineTo(t+s-u,n-l),e.lineTo(t+s,n-l+u),e.lineTo(t+s,n+l-u),e.lineTo(t+s-u,n+l),e.lineTo(t-s+u,n+l),e.lineTo(t-s,n+l-u),e.lineTo(t-s,n-l+u),e.closePath()},drawBarrelPath:function(e,t,n,r,i){var a=r/2,o=i/2,s=t-a,l=t+a,u=n-o,c=n+o,d=an(r,i),h=d.widthOffset,p=d.heightOffset,f=d.ctrlPtOffsetPct*h;e.beginPath&&e.beginPath(),e.moveTo(s,u+p),e.lineTo(s,c-p),e.quadraticCurveTo(s+f,c,s+h,c),e.lineTo(l-h,c),e.quadraticCurveTo(l-f,c,l,c-p),e.lineTo(l,u+p),e.quadraticCurveTo(l-f,u,l-h,u),e.lineTo(s+h,u),e.quadraticCurveTo(s+f,u,s,u+p),e.closePath()}},Ju=Math.sin(0),ec=Math.cos(0),tc={},nc={},rc=Math.PI/40,ic=0*Math.PI;ic<2*Math.PI;ic+=rc)tc[ic]=Math.sin(ic),nc[ic]=Math.cos(ic);Qu.drawEllipsePath=function(e,t,n,r,i){if(e.beginPath&&e.beginPath(),e.ellipse)e.ellipse(t,n,r/2,i/2,0,0,2*Math.PI);else for(var a,o,s=r/2,l=i/2,u=0*Math.PI;u<2*Math.PI;u+=rc)a=t-s*tc[u]*Ju+s*nc[u]*ec,o=n+l*nc[u]*Ju+l*tc[u]*ec,0===u?e.moveTo(a,o):e.lineTo(a,o);e.closePath()};var ac={};function oc(e){var t=e.indexOf(",");return e.substr(t+1)}function sc(e,t,n){var r=function(){return t.toDataURL(n,e.quality)};switch(e.output){case"blob-promise":return new vr((function(r,i){try{t.toBlob((function(e){null!=e?r(e):i(new Error("`canvas.toBlob()` sent a null value in its callback"))}),n,e.quality)}catch(e){i(e)}}));case"blob":return function(e,t){for(var n=atob(e),r=new ArrayBuffer(n.length),i=new Uint8Array(r),a=0;a<n.length;a++)i[a]=n.charCodeAt(a);return new Blob([r],{type:t})}(oc(r()),n);case"base64":return oc(r());case"base64uri":default:return r()}}ac.createBuffer=function(e,t){var n=document.createElement("canvas");return n.width=e,n.height=t,[n,n.getContext("2d")]},ac.bufferCanvasImage=function(e){var t=this.cy,n=t.mutableElements().boundingBox(),r=this.findContainerClientCoords(),i=e.full?Math.ceil(n.w):r[2],a=e.full?Math.ceil(n.h):r[3],o=x(e.maxWidth)||x(e.maxHeight),s=this.getPixelRatio(),l=1;if(void 0!==e.scale)i*=e.scale,a*=e.scale,l=e.scale;else if(o){var u=1/0,c=1/0;x(e.maxWidth)&&(u=l*e.maxWidth/i),x(e.maxHeight)&&(c=l*e.maxHeight/a),i*=l=Math.min(u,c),a*=l}o||(i*=s,a*=s,l*=s);var d=document.createElement("canvas");d.width=i,d.height=a,d.style.width=i+"px",d.style.height=a+"px";var h=d.getContext("2d");if(i>0&&a>0){h.clearRect(0,0,i,a),h.globalCompositeOperation="source-over";var p=this.getCachedZSortedEles();if(e.full)h.translate(-n.x1*l,-n.y1*l),h.scale(l,l),this.drawElements(h,p),h.scale(1/l,1/l),h.translate(n.x1*l,n.y1*l);else{var f=t.pan(),g={x:f.x*l,y:f.y*l};l*=t.zoom(),h.translate(g.x,g.y),h.scale(l,l),this.drawElements(h,p),h.scale(1/l,1/l),h.translate(-g.x,-g.y)}e.bg&&(h.globalCompositeOperation="destination-over",h.fillStyle=e.bg,h.rect(0,0,i,a),h.fill())}return d},ac.png=function(e){return sc(e,this.bufferCanvasImage(e),"image/png")},ac.jpg=function(e){return sc(e,this.bufferCanvasImage(e),"image/jpeg")};var lc={nodeShapeImpl:function(e,t,n,r,i,a,o,s){switch(e){case"ellipse":return this.drawEllipsePath(t,n,r,i,a);case"polygon":return this.drawPolygonPath(t,n,r,i,a,o);case"round-polygon":return this.drawRoundPolygonPath(t,n,r,i,a,o,s);case"roundrectangle":case"round-rectangle":return this.drawRoundRectanglePath(t,n,r,i,a,s);case"cutrectangle":case"cut-rectangle":return this.drawCutRectanglePath(t,n,r,i,a,o,s);case"bottomroundrectangle":case"bottom-round-rectangle":return this.drawBottomRoundRectanglePath(t,n,r,i,a,s);case"barrel":return this.drawBarrelPath(t,n,r,i,a)}}},uc=dc,cc=dc.prototype;function dc(e){var t=this,n=t.cy.window().document;t.data={canvases:new Array(cc.CANVAS_LAYERS),contexts:new Array(cc.CANVAS_LAYERS),canvasNeedsRedraw:new Array(cc.CANVAS_LAYERS),bufferCanvases:new Array(cc.BUFFER_COUNT),bufferContexts:new Array(cc.CANVAS_LAYERS)};t.data.canvasContainer=n.createElement("div");var r=t.data.canvasContainer.style;t.data.canvasContainer.style["-webkit-tap-highlight-color"]="rgba(0,0,0,0)",r.position="relative",r.zIndex="0",r.overflow="hidden";var i=e.cy.container();i.appendChild(t.data.canvasContainer),i.style["-webkit-tap-highlight-color"]="rgba(0,0,0,0)";var a={"-webkit-user-select":"none","-moz-user-select":"-moz-none","user-select":"none","-webkit-tap-highlight-color":"rgba(0,0,0,0)","outline-style":"none"};c&&c.userAgent.match(/msie|trident|edge/i)&&(a["-ms-touch-action"]="none",a["touch-action"]="none");for(var o=0;o<cc.CANVAS_LAYERS;o++){var s=t.data.canvases[o]=n.createElement("canvas");t.data.contexts[o]=s.getContext("2d"),Object.keys(a).forEach((function(e){s.style[e]=a[e]})),s.style.position="absolute",s.setAttribute("data-id","layer"+o),s.style.zIndex=String(cc.CANVAS_LAYERS-o),t.data.canvasContainer.appendChild(s),t.data.canvasNeedsRedraw[o]=!1}t.data.topCanvas=t.data.canvases[0],t.data.canvases[cc.NODE].setAttribute("data-id","layer"+cc.NODE+"-node"),t.data.canvases[cc.SELECT_BOX].setAttribute("data-id","layer"+cc.SELECT_BOX+"-selectbox"),t.data.canvases[cc.DRAG].setAttribute("data-id","layer"+cc.DRAG+"-drag");for(o=0;o<cc.BUFFER_COUNT;o++)t.data.bufferCanvases[o]=n.createElement("canvas"),t.data.bufferContexts[o]=t.data.bufferCanvases[o].getContext("2d"),t.data.bufferCanvases[o].style.position="absolute",t.data.bufferCanvases[o].setAttribute("data-id","buffer"+o),t.data.bufferCanvases[o].style.zIndex=String(-o-1),t.data.bufferCanvases[o].style.visibility="hidden";t.pathsEnabled=!0;var l=_t(),u=function(e){return{x:-e.w/2,y:-e.h/2}},d=function(e){return e.boundingBox(),e[0]._private.bodyBounds},h=function(e){return e.boundingBox(),e[0]._private.labelBounds.main||l},p=function(e){return e.boundingBox(),e[0]._private.labelBounds.source||l},f=function(e){return e.boundingBox(),e[0]._private.labelBounds.target||l},g=function(e,t){return t},v=function(e,t,n){var r=e?e+"-":"";return{x:t.x+n.pstyle(r+"text-margin-x").pfValue,y:t.y+n.pstyle(r+"text-margin-y").pfValue}},y=function(e,t,n){var r=e[0]._private.rscratch;return{x:r[t],y:r[n]}},m=t.data.eleTxrCache=new Cu(t,{getKey:function(e){return e[0]._private.nodeKey},doesEleInvalidateKey:function(e){var t=e[0]._private;return!(t.oldBackgroundTimestamp===t.backgroundTimestamp)},drawElement:function(e,n,r,i,a){return t.drawElement(e,n,r,!1,!1,a)},getBoundingBox:d,getRotationPoint:function(e){return{x:((t=d(e)).x1+t.x2)/2,y:(t.y1+t.y2)/2};var t},getRotationOffset:function(e){return u(d(e))},allowEdgeTxrCaching:!1,allowParentTxrCaching:!1}),b=t.data.lblTxrCache=new Cu(t,{getKey:function(e){return e[0]._private.labelStyleKey},drawElement:function(e,n,r,i,a){return t.drawElementText(e,n,r,i,"main",a)},getBoundingBox:h,getRotationPoint:function(e){return v("",y(e,"labelX","labelY"),e)},getRotationOffset:function(e){var t=h(e),n=u(h(e));if(e.isNode()){switch(e.pstyle("text-halign").value){case"left":n.x=-t.w;break;case"right":n.x=0}switch(e.pstyle("text-valign").value){case"top":n.y=-t.h;break;case"bottom":n.y=0}}return n},isVisible:g}),x=t.data.slbTxrCache=new Cu(t,{getKey:function(e){return e[0]._private.sourceLabelStyleKey},drawElement:function(e,n,r,i,a){return t.drawElementText(e,n,r,i,"source",a)},getBoundingBox:p,getRotationPoint:function(e){return v("source",y(e,"sourceLabelX","sourceLabelY"),e)},getRotationOffset:function(e){return u(p(e))},isVisible:g}),w=t.data.tlbTxrCache=new Cu(t,{getKey:function(e){return e[0]._private.targetLabelStyleKey},drawElement:function(e,n,r,i,a){return t.drawElementText(e,n,r,i,"target",a)},getBoundingBox:f,getRotationPoint:function(e){return v("target",y(e,"targetLabelX","targetLabelY"),e)},getRotationOffset:function(e){return u(f(e))},isVisible:g}),E=t.data.lyrTxrCache=new Pu(t);t.onUpdateEleCalcs((function(e,t){m.invalidateElements(t),b.invalidateElements(t),x.invalidateElements(t),w.invalidateElements(t),E.invalidateElements(t);for(var n=0;n<t.length;n++){var r=t[n]._private;r.oldBackgroundTimestamp=r.backgroundTimestamp}}));var k=function(e){for(var t=0;t<e.length;t++)E.enqueueElementRefinement(e[t].ele)};m.onDequeue(k),b.onDequeue(k),x.onDequeue(k),w.onDequeue(k)}cc.CANVAS_LAYERS=3,cc.SELECT_BOX=0,cc.DRAG=1,cc.NODE=2,cc.BUFFER_COUNT=3,cc.TEXTURE_BUFFER=0,cc.MOTIONBLUR_BUFFER_NODE=1,cc.MOTIONBLUR_BUFFER_DRAG=2,cc.redrawHint=function(e,t){var n=this;switch(e){case"eles":n.data.canvasNeedsRedraw[cc.NODE]=t;break;case"drag":n.data.canvasNeedsRedraw[cc.DRAG]=t;break;case"select":n.data.canvasNeedsRedraw[cc.SELECT_BOX]=t}};var hc="undefined"!=typeof Path2D;cc.path2dEnabled=function(e){if(void 0===e)return this.pathsEnabled;this.pathsEnabled=!!e},cc.usePaths=function(){return hc&&this.pathsEnabled},cc.setImgSmoothing=function(e,t){null!=e.imageSmoothingEnabled?e.imageSmoothingEnabled=t:(e.webkitImageSmoothingEnabled=t,e.mozImageSmoothingEnabled=t,e.msImageSmoothingEnabled=t)},cc.getImgSmoothing=function(e){return null!=e.imageSmoothingEnabled?e.imageSmoothingEnabled:e.webkitImageSmoothingEnabled||e.mozImageSmoothingEnabled||e.msImageSmoothingEnabled},cc.makeOffscreenCanvas=function(t,n){var r;"undefined"!==("undefined"==typeof OffscreenCanvas?"undefined":e(OffscreenCanvas))?r=new OffscreenCanvas(t,n):((r=this.cy.window().document.createElement("canvas")).width=t,r.height=n);return r},[Bu,Ou,Xu,Hu,Ku,Uu,$u,Qu,ac,lc].forEach((function(e){L(cc,e)}));var pc=[{type:"layout",extensions:Cl},{type:"renderer",extensions:[{name:"null",impl:Sl},{name:"base",impl:mu},{name:"canvas",impl:uc}]}],fc={},gc={};function vc(e,t,n){var r=n,i=function(n){je("Can not register `"+t+"` for `"+e+"` since `"+n+"` already exists in the prototype and can not be overridden")};if("core"===e){if(Os.prototype[t])return i(t);Os.prototype[t]=n}else if("collection"===e){if(ts.prototype[t])return i(t);ts.prototype[t]=n}else if("layout"===e){for(var a=function(e){this.options=e,n.call(this,e),b(this._private)||(this._private={}),this._private.cy=e.cy,this._private.listeners=[],this.createEmitter()},o=a.prototype=Object.create(n.prototype),s=[],l=0;l<s.length;l++){var u=s[l];o[u]=o[u]||function(){return this}}o.start&&!o.run?o.run=function(){return this.start(),this}:!o.start&&o.run&&(o.start=function(){return this.run(),this});var c=n.prototype.stop;o.stop=function(){var e=this.options;if(e&&e.animate){var t=this.animations;if(t)for(var n=0;n<t.length;n++)t[n].stop()}return c?c.call(this):this.emit("layoutstop"),this},o.destroy||(o.destroy=function(){return this}),o.cy=function(){return this._private.cy};var d=function(e){return e._private.cy},h={addEventFields:function(e,t){t.layout=e,t.cy=d(e),t.target=e},bubble:function(){return!0},parent:function(e){return d(e)}};L(o,{createEmitter:function(){return this._private.emitter=new xo(h,this),this},emitter:function(){return this._private.emitter},on:function(e,t){return this.emitter().on(e,t),this},one:function(e,t){return this.emitter().one(e,t),this},once:function(e,t){return this.emitter().one(e,t),this},removeListener:function(e,t){return this.emitter().removeListener(e,t),this},removeAllListeners:function(){return this.emitter().removeAllListeners(),this},emit:function(e,t){return this.emitter().emit(e,t),this}}),Fi.eventAliasesOn(o),r=a}else if("renderer"===e&&"null"!==t&&"base"!==t){var p=yc("renderer","base"),f=p.prototype,g=n,v=n.prototype,y=function(){p.apply(this,arguments),g.apply(this,arguments)},m=y.prototype;for(var x in f){var w=f[x];if(null!=v[x])return i(x);m[x]=w}for(var E in v)m[E]=v[E];f.clientFunctions.forEach((function(e){m[e]=m[e]||function(){Ve("Renderer does not implement `renderer."+e+"()` on its prototype")}})),r=y}else if("__proto__"===e||"constructor"===e||"prototype"===e)return Ve(e+" is an illegal type to be registered, possibly lead to prototype pollutions");return V({map:fc,keys:[e,t],value:r})}function yc(e,t){return F({map:fc,keys:[e,t]})}function mc(e,t,n,r,i){return V({map:gc,keys:[e,t,n,r],value:i})}function bc(e,t,n,r){return F({map:gc,keys:[e,t,n,r]})}var xc=function(){return 2===arguments.length?yc.apply(null,arguments):3===arguments.length?vc.apply(null,arguments):4===arguments.length?bc.apply(null,arguments):5===arguments.length?mc.apply(null,arguments):void Ve("Invalid extension access syntax")};Os.prototype.extension=xc,pc.forEach((function(e){e.extensions.forEach((function(t){vc(e.type,t.name,t.impl)}))}));var wc=function e(){if(!(this instanceof e))return new e;this.length=0},Ec=wc.prototype;Ec.instanceString=function(){return"stylesheet"},Ec.selector=function(e){return this[this.length++]={selector:e,properties:[]},this},Ec.css=function(e,t){var n=this.length-1;if(v(e))this[n].properties.push({name:e,value:t});else if(b(e))for(var r=e,i=Object.keys(r),a=0;a<i.length;a++){var o=i[a],s=r[o];if(null!=s){var l=Ns.properties[o]||Ns.properties[B(o)];if(null!=l){var u=l.name,c=s;this[n].properties.push({name:u,value:c})}}}return this},Ec.style=Ec.css,Ec.generateStyle=function(e){var t=new Ns(e);return this.appendToStyle(t)},Ec.appendToStyle=function(e){for(var t=0;t<this.length;t++){var n=this[t],r=n.selector,i=n.properties;e.selector(r);for(var a=0;a<i.length;a++){var o=i[a];e.css(o.name,o.value)}}return e};var kc=function(e){return void 0===e&&(e={}),b(e)?new Os(e):v(e)?xc.apply(xc,arguments):void 0};return kc.use=function(e){var t=Array.prototype.slice.call(arguments,1);return t.unshift(kc),e.apply(null,t),this},kc.warnings=function(e){return Fe(e)},kc.version="3.30.2",kc.stylesheet=kc.Stylesheet=wc,kc}));
diff --git a/web/vendor/layout-base.js b/web/vendor/layout-base.js
new file mode 100644
index 0000000..ebbf2c6
--- /dev/null
+++ b/web/vendor/layout-base.js
@@ -0,0 +1,5230 @@
+(function webpackUniversalModuleDefinition(root, factory) {
+ if(typeof exports === 'object' && typeof module === 'object')
+ module.exports = factory();
+ else if(typeof define === 'function' && define.amd)
+ define([], factory);
+ else if(typeof exports === 'object')
+ exports["layoutBase"] = factory();
+ else
+ root["layoutBase"] = factory();
+})(this, function() {
+return /******/ (function(modules) { // webpackBootstrap
+/******/ // The module cache
+/******/ var installedModules = {};
+/******/
+/******/ // The require function
+/******/ function __webpack_require__(moduleId) {
+/******/
+/******/ // Check if module is in cache
+/******/ if(installedModules[moduleId]) {
+/******/ return installedModules[moduleId].exports;
+/******/ }
+/******/ // Create a new module (and put it into the cache)
+/******/ var module = installedModules[moduleId] = {
+/******/ i: moduleId,
+/******/ l: false,
+/******/ exports: {}
+/******/ };
+/******/
+/******/ // Execute the module function
+/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
+/******/
+/******/ // Flag the module as loaded
+/******/ module.l = true;
+/******/
+/******/ // Return the exports of the module
+/******/ return module.exports;
+/******/ }
+/******/
+/******/
+/******/ // expose the modules object (__webpack_modules__)
+/******/ __webpack_require__.m = modules;
+/******/
+/******/ // expose the module cache
+/******/ __webpack_require__.c = installedModules;
+/******/
+/******/ // identity function for calling harmony imports with the correct context
+/******/ __webpack_require__.i = function(value) { return value; };
+/******/
+/******/ // define getter function for harmony exports
+/******/ __webpack_require__.d = function(exports, name, getter) {
+/******/ if(!__webpack_require__.o(exports, name)) {
+/******/ Object.defineProperty(exports, name, {
+/******/ configurable: false,
+/******/ enumerable: true,
+/******/ get: getter
+/******/ });
+/******/ }
+/******/ };
+/******/
+/******/ // getDefaultExport function for compatibility with non-harmony modules
+/******/ __webpack_require__.n = function(module) {
+/******/ var getter = module && module.__esModule ?
+/******/ function getDefault() { return module['default']; } :
+/******/ function getModuleExports() { return module; };
+/******/ __webpack_require__.d(getter, 'a', getter);
+/******/ return getter;
+/******/ };
+/******/
+/******/ // Object.prototype.hasOwnProperty.call
+/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
+/******/
+/******/ // __webpack_public_path__
+/******/ __webpack_require__.p = "";
+/******/
+/******/ // Load entry module and return exports
+/******/ return __webpack_require__(__webpack_require__.s = 28);
+/******/ })
+/************************************************************************/
+/******/ ([
+/* 0 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+function LayoutConstants() {}
+
+/**
+ * Layout Quality: 0:draft, 1:default, 2:proof
+ */
+LayoutConstants.QUALITY = 1;
+
+/**
+ * Default parameters
+ */
+LayoutConstants.DEFAULT_CREATE_BENDS_AS_NEEDED = false;
+LayoutConstants.DEFAULT_INCREMENTAL = false;
+LayoutConstants.DEFAULT_ANIMATION_ON_LAYOUT = true;
+LayoutConstants.DEFAULT_ANIMATION_DURING_LAYOUT = false;
+LayoutConstants.DEFAULT_ANIMATION_PERIOD = 50;
+LayoutConstants.DEFAULT_UNIFORM_LEAF_NODE_SIZES = false;
+
+// -----------------------------------------------------------------------------
+// Section: General other constants
+// -----------------------------------------------------------------------------
+/*
+ * Margins of a graph to be applied on bouding rectangle of its contents. We
+ * assume margins on all four sides to be uniform.
+ */
+LayoutConstants.DEFAULT_GRAPH_MARGIN = 15;
+
+/*
+ * Whether to consider labels in node dimensions or not
+ */
+LayoutConstants.NODE_DIMENSIONS_INCLUDE_LABELS = false;
+
+/*
+ * Default dimension of a non-compound node.
+ */
+LayoutConstants.SIMPLE_NODE_SIZE = 40;
+
+/*
+ * Default dimension of a non-compound node.
+ */
+LayoutConstants.SIMPLE_NODE_HALF_SIZE = LayoutConstants.SIMPLE_NODE_SIZE / 2;
+
+/*
+ * Empty compound node size. When a compound node is empty, its both
+ * dimensions should be of this value.
+ */
+LayoutConstants.EMPTY_COMPOUND_NODE_SIZE = 40;
+
+/*
+ * Minimum length that an edge should take during layout
+ */
+LayoutConstants.MIN_EDGE_LENGTH = 1;
+
+/*
+ * World boundaries that layout operates on
+ */
+LayoutConstants.WORLD_BOUNDARY = 1000000;
+
+/*
+ * World boundaries that random positioning can be performed with
+ */
+LayoutConstants.INITIAL_WORLD_BOUNDARY = LayoutConstants.WORLD_BOUNDARY / 1000;
+
+/*
+ * Coordinates of the world center
+ */
+LayoutConstants.WORLD_CENTER_X = 1200;
+LayoutConstants.WORLD_CENTER_Y = 900;
+
+module.exports = LayoutConstants;
+
+/***/ }),
+/* 1 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+var LGraphObject = __webpack_require__(2);
+var IGeometry = __webpack_require__(8);
+var IMath = __webpack_require__(9);
+
+function LEdge(source, target, vEdge) {
+ LGraphObject.call(this, vEdge);
+
+ this.isOverlapingSourceAndTarget = false;
+ this.vGraphObject = vEdge;
+ this.bendpoints = [];
+ this.source = source;
+ this.target = target;
+}
+
+LEdge.prototype = Object.create(LGraphObject.prototype);
+
+for (var prop in LGraphObject) {
+ LEdge[prop] = LGraphObject[prop];
+}
+
+LEdge.prototype.getSource = function () {
+ return this.source;
+};
+
+LEdge.prototype.getTarget = function () {
+ return this.target;
+};
+
+LEdge.prototype.isInterGraph = function () {
+ return this.isInterGraph;
+};
+
+LEdge.prototype.getLength = function () {
+ return this.length;
+};
+
+LEdge.prototype.isOverlapingSourceAndTarget = function () {
+ return this.isOverlapingSourceAndTarget;
+};
+
+LEdge.prototype.getBendpoints = function () {
+ return this.bendpoints;
+};
+
+LEdge.prototype.getLca = function () {
+ return this.lca;
+};
+
+LEdge.prototype.getSourceInLca = function () {
+ return this.sourceInLca;
+};
+
+LEdge.prototype.getTargetInLca = function () {
+ return this.targetInLca;
+};
+
+LEdge.prototype.getOtherEnd = function (node) {
+ if (this.source === node) {
+ return this.target;
+ } else if (this.target === node) {
+ return this.source;
+ } else {
+ throw "Node is not incident with this edge";
+ }
+};
+
+LEdge.prototype.getOtherEndInGraph = function (node, graph) {
+ var otherEnd = this.getOtherEnd(node);
+ var root = graph.getGraphManager().getRoot();
+
+ while (true) {
+ if (otherEnd.getOwner() == graph) {
+ return otherEnd;
+ }
+
+ if (otherEnd.getOwner() == root) {
+ break;
+ }
+
+ otherEnd = otherEnd.getOwner().getParent();
+ }
+
+ return null;
+};
+
+LEdge.prototype.updateLength = function () {
+ var clipPointCoordinates = new Array(4);
+
+ this.isOverlapingSourceAndTarget = IGeometry.getIntersection(this.target.getRect(), this.source.getRect(), clipPointCoordinates);
+
+ if (!this.isOverlapingSourceAndTarget) {
+ this.lengthX = clipPointCoordinates[0] - clipPointCoordinates[2];
+ this.lengthY = clipPointCoordinates[1] - clipPointCoordinates[3];
+
+ if (Math.abs(this.lengthX) < 1.0) {
+ this.lengthX = IMath.sign(this.lengthX);
+ }
+
+ if (Math.abs(this.lengthY) < 1.0) {
+ this.lengthY = IMath.sign(this.lengthY);
+ }
+
+ this.length = Math.sqrt(this.lengthX * this.lengthX + this.lengthY * this.lengthY);
+ }
+};
+
+LEdge.prototype.updateLengthSimple = function () {
+ this.lengthX = this.target.getCenterX() - this.source.getCenterX();
+ this.lengthY = this.target.getCenterY() - this.source.getCenterY();
+
+ if (Math.abs(this.lengthX) < 1.0) {
+ this.lengthX = IMath.sign(this.lengthX);
+ }
+
+ if (Math.abs(this.lengthY) < 1.0) {
+ this.lengthY = IMath.sign(this.lengthY);
+ }
+
+ this.length = Math.sqrt(this.lengthX * this.lengthX + this.lengthY * this.lengthY);
+};
+
+module.exports = LEdge;
+
+/***/ }),
+/* 2 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+function LGraphObject(vGraphObject) {
+ this.vGraphObject = vGraphObject;
+}
+
+module.exports = LGraphObject;
+
+/***/ }),
+/* 3 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+var LGraphObject = __webpack_require__(2);
+var Integer = __webpack_require__(10);
+var RectangleD = __webpack_require__(13);
+var LayoutConstants = __webpack_require__(0);
+var RandomSeed = __webpack_require__(16);
+var PointD = __webpack_require__(5);
+
+function LNode(gm, loc, size, vNode) {
+ //Alternative constructor 1 : LNode(LGraphManager gm, Point loc, Dimension size, Object vNode)
+ if (size == null && vNode == null) {
+ vNode = loc;
+ }
+
+ LGraphObject.call(this, vNode);
+
+ //Alternative constructor 2 : LNode(Layout layout, Object vNode)
+ if (gm.graphManager != null) gm = gm.graphManager;
+
+ this.estimatedSize = Integer.MIN_VALUE;
+ this.inclusionTreeDepth = Integer.MAX_VALUE;
+ this.vGraphObject = vNode;
+ this.edges = [];
+ this.graphManager = gm;
+
+ if (size != null && loc != null) this.rect = new RectangleD(loc.x, loc.y, size.width, size.height);else this.rect = new RectangleD();
+}
+
+LNode.prototype = Object.create(LGraphObject.prototype);
+for (var prop in LGraphObject) {
+ LNode[prop] = LGraphObject[prop];
+}
+
+LNode.prototype.getEdges = function () {
+ return this.edges;
+};
+
+LNode.prototype.getChild = function () {
+ return this.child;
+};
+
+LNode.prototype.getOwner = function () {
+ // if (this.owner != null) {
+ // if (!(this.owner == null || this.owner.getNodes().indexOf(this) > -1)) {
+ // throw "assert failed";
+ // }
+ // }
+
+ return this.owner;
+};
+
+LNode.prototype.getWidth = function () {
+ return this.rect.width;
+};
+
+LNode.prototype.setWidth = function (width) {
+ this.rect.width = width;
+};
+
+LNode.prototype.getHeight = function () {
+ return this.rect.height;
+};
+
+LNode.prototype.setHeight = function (height) {
+ this.rect.height = height;
+};
+
+LNode.prototype.getCenterX = function () {
+ return this.rect.x + this.rect.width / 2;
+};
+
+LNode.prototype.getCenterY = function () {
+ return this.rect.y + this.rect.height / 2;
+};
+
+LNode.prototype.getCenter = function () {
+ return new PointD(this.rect.x + this.rect.width / 2, this.rect.y + this.rect.height / 2);
+};
+
+LNode.prototype.getLocation = function () {
+ return new PointD(this.rect.x, this.rect.y);
+};
+
+LNode.prototype.getRect = function () {
+ return this.rect;
+};
+
+LNode.prototype.getDiagonal = function () {
+ return Math.sqrt(this.rect.width * this.rect.width + this.rect.height * this.rect.height);
+};
+
+/**
+ * This method returns half the diagonal length of this node.
+ */
+LNode.prototype.getHalfTheDiagonal = function () {
+ return Math.sqrt(this.rect.height * this.rect.height + this.rect.width * this.rect.width) / 2;
+};
+
+LNode.prototype.setRect = function (upperLeft, dimension) {
+ this.rect.x = upperLeft.x;
+ this.rect.y = upperLeft.y;
+ this.rect.width = dimension.width;
+ this.rect.height = dimension.height;
+};
+
+LNode.prototype.setCenter = function (cx, cy) {
+ this.rect.x = cx - this.rect.width / 2;
+ this.rect.y = cy - this.rect.height / 2;
+};
+
+LNode.prototype.setLocation = function (x, y) {
+ this.rect.x = x;
+ this.rect.y = y;
+};
+
+LNode.prototype.moveBy = function (dx, dy) {
+ this.rect.x += dx;
+ this.rect.y += dy;
+};
+
+LNode.prototype.getEdgeListToNode = function (to) {
+ var edgeList = [];
+ var edge;
+ var self = this;
+
+ self.edges.forEach(function (edge) {
+
+ if (edge.target == to) {
+ if (edge.source != self) throw "Incorrect edge source!";
+
+ edgeList.push(edge);
+ }
+ });
+
+ return edgeList;
+};
+
+LNode.prototype.getEdgesBetween = function (other) {
+ var edgeList = [];
+ var edge;
+
+ var self = this;
+ self.edges.forEach(function (edge) {
+
+ if (!(edge.source == self || edge.target == self)) throw "Incorrect edge source and/or target";
+
+ if (edge.target == other || edge.source == other) {
+ edgeList.push(edge);
+ }
+ });
+
+ return edgeList;
+};
+
+LNode.prototype.getNeighborsList = function () {
+ var neighbors = new Set();
+
+ var self = this;
+ self.edges.forEach(function (edge) {
+
+ if (edge.source == self) {
+ neighbors.add(edge.target);
+ } else {
+ if (edge.target != self) {
+ throw "Incorrect incidency!";
+ }
+
+ neighbors.add(edge.source);
+ }
+ });
+
+ return neighbors;
+};
+
+LNode.prototype.withChildren = function () {
+ var withNeighborsList = new Set();
+ var childNode;
+ var children;
+
+ withNeighborsList.add(this);
+
+ if (this.child != null) {
+ var nodes = this.child.getNodes();
+ for (var i = 0; i < nodes.length; i++) {
+ childNode = nodes[i];
+ children = childNode.withChildren();
+ children.forEach(function (node) {
+ withNeighborsList.add(node);
+ });
+ }
+ }
+
+ return withNeighborsList;
+};
+
+LNode.prototype.getNoOfChildren = function () {
+ var noOfChildren = 0;
+ var childNode;
+
+ if (this.child == null) {
+ noOfChildren = 1;
+ } else {
+ var nodes = this.child.getNodes();
+ for (var i = 0; i < nodes.length; i++) {
+ childNode = nodes[i];
+
+ noOfChildren += childNode.getNoOfChildren();
+ }
+ }
+
+ if (noOfChildren == 0) {
+ noOfChildren = 1;
+ }
+ return noOfChildren;
+};
+
+LNode.prototype.getEstimatedSize = function () {
+ if (this.estimatedSize == Integer.MIN_VALUE) {
+ throw "assert failed";
+ }
+ return this.estimatedSize;
+};
+
+LNode.prototype.calcEstimatedSize = function () {
+ if (this.child == null) {
+ return this.estimatedSize = (this.rect.width + this.rect.height) / 2;
+ } else {
+ this.estimatedSize = this.child.calcEstimatedSize();
+ this.rect.width = this.estimatedSize;
+ this.rect.height = this.estimatedSize;
+
+ return this.estimatedSize;
+ }
+};
+
+LNode.prototype.scatter = function () {
+ var randomCenterX;
+ var randomCenterY;
+
+ var minX = -LayoutConstants.INITIAL_WORLD_BOUNDARY;
+ var maxX = LayoutConstants.INITIAL_WORLD_BOUNDARY;
+ randomCenterX = LayoutConstants.WORLD_CENTER_X + RandomSeed.nextDouble() * (maxX - minX) + minX;
+
+ var minY = -LayoutConstants.INITIAL_WORLD_BOUNDARY;
+ var maxY = LayoutConstants.INITIAL_WORLD_BOUNDARY;
+ randomCenterY = LayoutConstants.WORLD_CENTER_Y + RandomSeed.nextDouble() * (maxY - minY) + minY;
+
+ this.rect.x = randomCenterX;
+ this.rect.y = randomCenterY;
+};
+
+LNode.prototype.updateBounds = function () {
+ if (this.getChild() == null) {
+ throw "assert failed";
+ }
+ if (this.getChild().getNodes().length != 0) {
+ // wrap the children nodes by re-arranging the boundaries
+ var childGraph = this.getChild();
+ childGraph.updateBounds(true);
+
+ this.rect.x = childGraph.getLeft();
+ this.rect.y = childGraph.getTop();
+
+ this.setWidth(childGraph.getRight() - childGraph.getLeft());
+ this.setHeight(childGraph.getBottom() - childGraph.getTop());
+
+ // Update compound bounds considering its label properties
+ if (LayoutConstants.NODE_DIMENSIONS_INCLUDE_LABELS) {
+
+ var width = childGraph.getRight() - childGraph.getLeft();
+ var height = childGraph.getBottom() - childGraph.getTop();
+
+ if (this.labelWidth) {
+ if (this.labelPosHorizontal == "left") {
+ this.rect.x -= this.labelWidth;
+ this.setWidth(width + this.labelWidth);
+ } else if (this.labelPosHorizontal == "center" && this.labelWidth > width) {
+ this.rect.x -= (this.labelWidth - width) / 2;
+ this.setWidth(this.labelWidth);
+ } else if (this.labelPosHorizontal == "right") {
+ this.setWidth(width + this.labelWidth);
+ }
+ }
+
+ if (this.labelHeight) {
+ if (this.labelPosVertical == "top") {
+ this.rect.y -= this.labelHeight;
+ this.setHeight(height + this.labelHeight);
+ } else if (this.labelPosVertical == "center" && this.labelHeight > height) {
+ this.rect.y -= (this.labelHeight - height) / 2;
+ this.setHeight(this.labelHeight);
+ } else if (this.labelPosVertical == "bottom") {
+ this.setHeight(height + this.labelHeight);
+ }
+ }
+ }
+ }
+};
+
+LNode.prototype.getInclusionTreeDepth = function () {
+ if (this.inclusionTreeDepth == Integer.MAX_VALUE) {
+ throw "assert failed";
+ }
+ return this.inclusionTreeDepth;
+};
+
+LNode.prototype.transform = function (trans) {
+ var left = this.rect.x;
+
+ if (left > LayoutConstants.WORLD_BOUNDARY) {
+ left = LayoutConstants.WORLD_BOUNDARY;
+ } else if (left < -LayoutConstants.WORLD_BOUNDARY) {
+ left = -LayoutConstants.WORLD_BOUNDARY;
+ }
+
+ var top = this.rect.y;
+
+ if (top > LayoutConstants.WORLD_BOUNDARY) {
+ top = LayoutConstants.WORLD_BOUNDARY;
+ } else if (top < -LayoutConstants.WORLD_BOUNDARY) {
+ top = -LayoutConstants.WORLD_BOUNDARY;
+ }
+
+ var leftTop = new PointD(left, top);
+ var vLeftTop = trans.inverseTransformPoint(leftTop);
+
+ this.setLocation(vLeftTop.x, vLeftTop.y);
+};
+
+LNode.prototype.getLeft = function () {
+ return this.rect.x;
+};
+
+LNode.prototype.getRight = function () {
+ return this.rect.x + this.rect.width;
+};
+
+LNode.prototype.getTop = function () {
+ return this.rect.y;
+};
+
+LNode.prototype.getBottom = function () {
+ return this.rect.y + this.rect.height;
+};
+
+LNode.prototype.getParent = function () {
+ if (this.owner == null) {
+ return null;
+ }
+
+ return this.owner.getParent();
+};
+
+module.exports = LNode;
+
+/***/ }),
+/* 4 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+var LayoutConstants = __webpack_require__(0);
+
+function FDLayoutConstants() {}
+
+//FDLayoutConstants inherits static props in LayoutConstants
+for (var prop in LayoutConstants) {
+ FDLayoutConstants[prop] = LayoutConstants[prop];
+}
+
+FDLayoutConstants.MAX_ITERATIONS = 2500;
+
+FDLayoutConstants.DEFAULT_EDGE_LENGTH = 50;
+FDLayoutConstants.DEFAULT_SPRING_STRENGTH = 0.45;
+FDLayoutConstants.DEFAULT_REPULSION_STRENGTH = 4500.0;
+FDLayoutConstants.DEFAULT_GRAVITY_STRENGTH = 0.4;
+FDLayoutConstants.DEFAULT_COMPOUND_GRAVITY_STRENGTH = 1.0;
+FDLayoutConstants.DEFAULT_GRAVITY_RANGE_FACTOR = 3.8;
+FDLayoutConstants.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR = 1.5;
+FDLayoutConstants.DEFAULT_USE_SMART_IDEAL_EDGE_LENGTH_CALCULATION = true;
+FDLayoutConstants.DEFAULT_USE_SMART_REPULSION_RANGE_CALCULATION = true;
+FDLayoutConstants.DEFAULT_COOLING_FACTOR_INCREMENTAL = 0.3;
+FDLayoutConstants.COOLING_ADAPTATION_FACTOR = 0.33;
+FDLayoutConstants.ADAPTATION_LOWER_NODE_LIMIT = 1000;
+FDLayoutConstants.ADAPTATION_UPPER_NODE_LIMIT = 5000;
+FDLayoutConstants.MAX_NODE_DISPLACEMENT_INCREMENTAL = 100.0;
+FDLayoutConstants.MAX_NODE_DISPLACEMENT = FDLayoutConstants.MAX_NODE_DISPLACEMENT_INCREMENTAL * 3;
+FDLayoutConstants.MIN_REPULSION_DIST = FDLayoutConstants.DEFAULT_EDGE_LENGTH / 10.0;
+FDLayoutConstants.CONVERGENCE_CHECK_PERIOD = 100;
+FDLayoutConstants.PER_LEVEL_IDEAL_EDGE_LENGTH_FACTOR = 0.1;
+FDLayoutConstants.MIN_EDGE_LENGTH = 1;
+FDLayoutConstants.GRID_CALCULATION_CHECK_PERIOD = 10;
+
+module.exports = FDLayoutConstants;
+
+/***/ }),
+/* 5 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+function PointD(x, y) {
+ if (x == null && y == null) {
+ this.x = 0;
+ this.y = 0;
+ } else {
+ this.x = x;
+ this.y = y;
+ }
+}
+
+PointD.prototype.getX = function () {
+ return this.x;
+};
+
+PointD.prototype.getY = function () {
+ return this.y;
+};
+
+PointD.prototype.setX = function (x) {
+ this.x = x;
+};
+
+PointD.prototype.setY = function (y) {
+ this.y = y;
+};
+
+PointD.prototype.getDifference = function (pt) {
+ return new DimensionD(this.x - pt.x, this.y - pt.y);
+};
+
+PointD.prototype.getCopy = function () {
+ return new PointD(this.x, this.y);
+};
+
+PointD.prototype.translate = function (dim) {
+ this.x += dim.width;
+ this.y += dim.height;
+ return this;
+};
+
+module.exports = PointD;
+
+/***/ }),
+/* 6 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+var LGraphObject = __webpack_require__(2);
+var Integer = __webpack_require__(10);
+var LayoutConstants = __webpack_require__(0);
+var LGraphManager = __webpack_require__(7);
+var LNode = __webpack_require__(3);
+var LEdge = __webpack_require__(1);
+var RectangleD = __webpack_require__(13);
+var Point = __webpack_require__(12);
+var LinkedList = __webpack_require__(11);
+
+function LGraph(parent, obj2, vGraph) {
+ LGraphObject.call(this, vGraph);
+ this.estimatedSize = Integer.MIN_VALUE;
+ this.margin = LayoutConstants.DEFAULT_GRAPH_MARGIN;
+ this.edges = [];
+ this.nodes = [];
+ this.isConnected = false;
+ this.parent = parent;
+
+ if (obj2 != null && obj2 instanceof LGraphManager) {
+ this.graphManager = obj2;
+ } else if (obj2 != null && obj2 instanceof Layout) {
+ this.graphManager = obj2.graphManager;
+ }
+}
+
+LGraph.prototype = Object.create(LGraphObject.prototype);
+for (var prop in LGraphObject) {
+ LGraph[prop] = LGraphObject[prop];
+}
+
+LGraph.prototype.getNodes = function () {
+ return this.nodes;
+};
+
+LGraph.prototype.getEdges = function () {
+ return this.edges;
+};
+
+LGraph.prototype.getGraphManager = function () {
+ return this.graphManager;
+};
+
+LGraph.prototype.getParent = function () {
+ return this.parent;
+};
+
+LGraph.prototype.getLeft = function () {
+ return this.left;
+};
+
+LGraph.prototype.getRight = function () {
+ return this.right;
+};
+
+LGraph.prototype.getTop = function () {
+ return this.top;
+};
+
+LGraph.prototype.getBottom = function () {
+ return this.bottom;
+};
+
+LGraph.prototype.isConnected = function () {
+ return this.isConnected;
+};
+
+LGraph.prototype.add = function (obj1, sourceNode, targetNode) {
+ if (sourceNode == null && targetNode == null) {
+ var newNode = obj1;
+ if (this.graphManager == null) {
+ throw "Graph has no graph mgr!";
+ }
+ if (this.getNodes().indexOf(newNode) > -1) {
+ throw "Node already in graph!";
+ }
+ newNode.owner = this;
+ this.getNodes().push(newNode);
+
+ return newNode;
+ } else {
+ var newEdge = obj1;
+ if (!(this.getNodes().indexOf(sourceNode) > -1 && this.getNodes().indexOf(targetNode) > -1)) {
+ throw "Source or target not in graph!";
+ }
+
+ if (!(sourceNode.owner == targetNode.owner && sourceNode.owner == this)) {
+ throw "Both owners must be this graph!";
+ }
+
+ if (sourceNode.owner != targetNode.owner) {
+ return null;
+ }
+
+ // set source and target
+ newEdge.source = sourceNode;
+ newEdge.target = targetNode;
+
+ // set as intra-graph edge
+ newEdge.isInterGraph = false;
+
+ // add to graph edge list
+ this.getEdges().push(newEdge);
+
+ // add to incidency lists
+ sourceNode.edges.push(newEdge);
+
+ if (targetNode != sourceNode) {
+ targetNode.edges.push(newEdge);
+ }
+
+ return newEdge;
+ }
+};
+
+LGraph.prototype.remove = function (obj) {
+ var node = obj;
+ if (obj instanceof LNode) {
+ if (node == null) {
+ throw "Node is null!";
+ }
+ if (!(node.owner != null && node.owner == this)) {
+ throw "Owner graph is invalid!";
+ }
+ if (this.graphManager == null) {
+ throw "Owner graph manager is invalid!";
+ }
+ // remove incident edges first (make a copy to do it safely)
+ var edgesToBeRemoved = node.edges.slice();
+ var edge;
+ var s = edgesToBeRemoved.length;
+ for (var i = 0; i < s; i++) {
+ edge = edgesToBeRemoved[i];
+
+ if (edge.isInterGraph) {
+ this.graphManager.remove(edge);
+ } else {
+ edge.source.owner.remove(edge);
+ }
+ }
+
+ // now the node itself
+ var index = this.nodes.indexOf(node);
+ if (index == -1) {
+ throw "Node not in owner node list!";
+ }
+
+ this.nodes.splice(index, 1);
+ } else if (obj instanceof LEdge) {
+ var edge = obj;
+ if (edge == null) {
+ throw "Edge is null!";
+ }
+ if (!(edge.source != null && edge.target != null)) {
+ throw "Source and/or target is null!";
+ }
+ if (!(edge.source.owner != null && edge.target.owner != null && edge.source.owner == this && edge.target.owner == this)) {
+ throw "Source and/or target owner is invalid!";
+ }
+
+ var sourceIndex = edge.source.edges.indexOf(edge);
+ var targetIndex = edge.target.edges.indexOf(edge);
+ if (!(sourceIndex > -1 && targetIndex > -1)) {
+ throw "Source and/or target doesn't know this edge!";
+ }
+
+ edge.source.edges.splice(sourceIndex, 1);
+
+ if (edge.target != edge.source) {
+ edge.target.edges.splice(targetIndex, 1);
+ }
+
+ var index = edge.source.owner.getEdges().indexOf(edge);
+ if (index == -1) {
+ throw "Not in owner's edge list!";
+ }
+
+ edge.source.owner.getEdges().splice(index, 1);
+ }
+};
+
+LGraph.prototype.updateLeftTop = function () {
+ var top = Integer.MAX_VALUE;
+ var left = Integer.MAX_VALUE;
+ var nodeTop;
+ var nodeLeft;
+ var margin;
+
+ var nodes = this.getNodes();
+ var s = nodes.length;
+
+ for (var i = 0; i < s; i++) {
+ var lNode = nodes[i];
+ nodeTop = lNode.getTop();
+ nodeLeft = lNode.getLeft();
+
+ if (top > nodeTop) {
+ top = nodeTop;
+ }
+
+ if (left > nodeLeft) {
+ left = nodeLeft;
+ }
+ }
+
+ // Do we have any nodes in this graph?
+ if (top == Integer.MAX_VALUE) {
+ return null;
+ }
+
+ if (nodes[0].getParent().paddingLeft != undefined) {
+ margin = nodes[0].getParent().paddingLeft;
+ } else {
+ margin = this.margin;
+ }
+
+ this.left = left - margin;
+ this.top = top - margin;
+
+ // Apply the margins and return the result
+ return new Point(this.left, this.top);
+};
+
+LGraph.prototype.updateBounds = function (recursive) {
+ // calculate bounds
+ var left = Integer.MAX_VALUE;
+ var right = -Integer.MAX_VALUE;
+ var top = Integer.MAX_VALUE;
+ var bottom = -Integer.MAX_VALUE;
+ var nodeLeft;
+ var nodeRight;
+ var nodeTop;
+ var nodeBottom;
+ var margin;
+
+ var nodes = this.nodes;
+ var s = nodes.length;
+ for (var i = 0; i < s; i++) {
+ var lNode = nodes[i];
+
+ if (recursive && lNode.child != null) {
+ lNode.updateBounds();
+ }
+ nodeLeft = lNode.getLeft();
+ nodeRight = lNode.getRight();
+ nodeTop = lNode.getTop();
+ nodeBottom = lNode.getBottom();
+
+ if (left > nodeLeft) {
+ left = nodeLeft;
+ }
+
+ if (right < nodeRight) {
+ right = nodeRight;
+ }
+
+ if (top > nodeTop) {
+ top = nodeTop;
+ }
+
+ if (bottom < nodeBottom) {
+ bottom = nodeBottom;
+ }
+ }
+
+ var boundingRect = new RectangleD(left, top, right - left, bottom - top);
+ if (left == Integer.MAX_VALUE) {
+ this.left = this.parent.getLeft();
+ this.right = this.parent.getRight();
+ this.top = this.parent.getTop();
+ this.bottom = this.parent.getBottom();
+ }
+
+ if (nodes[0].getParent().paddingLeft != undefined) {
+ margin = nodes[0].getParent().paddingLeft;
+ } else {
+ margin = this.margin;
+ }
+
+ this.left = boundingRect.x - margin;
+ this.right = boundingRect.x + boundingRect.width + margin;
+ this.top = boundingRect.y - margin;
+ this.bottom = boundingRect.y + boundingRect.height + margin;
+};
+
+LGraph.calculateBounds = function (nodes) {
+ var left = Integer.MAX_VALUE;
+ var right = -Integer.MAX_VALUE;
+ var top = Integer.MAX_VALUE;
+ var bottom = -Integer.MAX_VALUE;
+ var nodeLeft;
+ var nodeRight;
+ var nodeTop;
+ var nodeBottom;
+
+ var s = nodes.length;
+
+ for (var i = 0; i < s; i++) {
+ var lNode = nodes[i];
+ nodeLeft = lNode.getLeft();
+ nodeRight = lNode.getRight();
+ nodeTop = lNode.getTop();
+ nodeBottom = lNode.getBottom();
+
+ if (left > nodeLeft) {
+ left = nodeLeft;
+ }
+
+ if (right < nodeRight) {
+ right = nodeRight;
+ }
+
+ if (top > nodeTop) {
+ top = nodeTop;
+ }
+
+ if (bottom < nodeBottom) {
+ bottom = nodeBottom;
+ }
+ }
+
+ var boundingRect = new RectangleD(left, top, right - left, bottom - top);
+
+ return boundingRect;
+};
+
+LGraph.prototype.getInclusionTreeDepth = function () {
+ if (this == this.graphManager.getRoot()) {
+ return 1;
+ } else {
+ return this.parent.getInclusionTreeDepth();
+ }
+};
+
+LGraph.prototype.getEstimatedSize = function () {
+ if (this.estimatedSize == Integer.MIN_VALUE) {
+ throw "assert failed";
+ }
+ return this.estimatedSize;
+};
+
+LGraph.prototype.calcEstimatedSize = function () {
+ var size = 0;
+ var nodes = this.nodes;
+ var s = nodes.length;
+
+ for (var i = 0; i < s; i++) {
+ var lNode = nodes[i];
+ size += lNode.calcEstimatedSize();
+ }
+
+ if (size == 0) {
+ this.estimatedSize = LayoutConstants.EMPTY_COMPOUND_NODE_SIZE;
+ } else {
+ this.estimatedSize = size / Math.sqrt(this.nodes.length);
+ }
+
+ return this.estimatedSize;
+};
+
+LGraph.prototype.updateConnected = function () {
+ var self = this;
+ if (this.nodes.length == 0) {
+ this.isConnected = true;
+ return;
+ }
+
+ var queue = new LinkedList();
+ var visited = new Set();
+ var currentNode = this.nodes[0];
+ var neighborEdges;
+ var currentNeighbor;
+ var childrenOfNode = currentNode.withChildren();
+ childrenOfNode.forEach(function (node) {
+ queue.push(node);
+ visited.add(node);
+ });
+
+ while (queue.length !== 0) {
+ currentNode = queue.shift();
+
+ // Traverse all neighbors of this node
+ neighborEdges = currentNode.getEdges();
+ var size = neighborEdges.length;
+ for (var i = 0; i < size; i++) {
+ var neighborEdge = neighborEdges[i];
+ currentNeighbor = neighborEdge.getOtherEndInGraph(currentNode, this);
+
+ // Add unvisited neighbors to the list to visit
+ if (currentNeighbor != null && !visited.has(currentNeighbor)) {
+ var childrenOfNeighbor = currentNeighbor.withChildren();
+
+ childrenOfNeighbor.forEach(function (node) {
+ queue.push(node);
+ visited.add(node);
+ });
+ }
+ }
+ }
+
+ this.isConnected = false;
+
+ if (visited.size >= this.nodes.length) {
+ var noOfVisitedInThisGraph = 0;
+
+ visited.forEach(function (visitedNode) {
+ if (visitedNode.owner == self) {
+ noOfVisitedInThisGraph++;
+ }
+ });
+
+ if (noOfVisitedInThisGraph == this.nodes.length) {
+ this.isConnected = true;
+ }
+ }
+};
+
+module.exports = LGraph;
+
+/***/ }),
+/* 7 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+var LGraph;
+var LEdge = __webpack_require__(1);
+
+function LGraphManager(layout) {
+ LGraph = __webpack_require__(6); // It may be better to initilize this out of this function but it gives an error (Right-hand side of 'instanceof' is not callable) now.
+ this.layout = layout;
+
+ this.graphs = [];
+ this.edges = [];
+}
+
+LGraphManager.prototype.addRoot = function () {
+ var ngraph = this.layout.newGraph();
+ var nnode = this.layout.newNode(null);
+ var root = this.add(ngraph, nnode);
+ this.setRootGraph(root);
+ return this.rootGraph;
+};
+
+LGraphManager.prototype.add = function (newGraph, parentNode, newEdge, sourceNode, targetNode) {
+ //there are just 2 parameters are passed then it adds an LGraph else it adds an LEdge
+ if (newEdge == null && sourceNode == null && targetNode == null) {
+ if (newGraph == null) {
+ throw "Graph is null!";
+ }
+ if (parentNode == null) {
+ throw "Parent node is null!";
+ }
+ if (this.graphs.indexOf(newGraph) > -1) {
+ throw "Graph already in this graph mgr!";
+ }
+
+ this.graphs.push(newGraph);
+
+ if (newGraph.parent != null) {
+ throw "Already has a parent!";
+ }
+ if (parentNode.child != null) {
+ throw "Already has a child!";
+ }
+
+ newGraph.parent = parentNode;
+ parentNode.child = newGraph;
+
+ return newGraph;
+ } else {
+ //change the order of the parameters
+ targetNode = newEdge;
+ sourceNode = parentNode;
+ newEdge = newGraph;
+ var sourceGraph = sourceNode.getOwner();
+ var targetGraph = targetNode.getOwner();
+
+ if (!(sourceGraph != null && sourceGraph.getGraphManager() == this)) {
+ throw "Source not in this graph mgr!";
+ }
+ if (!(targetGraph != null && targetGraph.getGraphManager() == this)) {
+ throw "Target not in this graph mgr!";
+ }
+
+ if (sourceGraph == targetGraph) {
+ newEdge.isInterGraph = false;
+ return sourceGraph.add(newEdge, sourceNode, targetNode);
+ } else {
+ newEdge.isInterGraph = true;
+
+ // set source and target
+ newEdge.source = sourceNode;
+ newEdge.target = targetNode;
+
+ // add edge to inter-graph edge list
+ if (this.edges.indexOf(newEdge) > -1) {
+ throw "Edge already in inter-graph edge list!";
+ }
+
+ this.edges.push(newEdge);
+
+ // add edge to source and target incidency lists
+ if (!(newEdge.source != null && newEdge.target != null)) {
+ throw "Edge source and/or target is null!";
+ }
+
+ if (!(newEdge.source.edges.indexOf(newEdge) == -1 && newEdge.target.edges.indexOf(newEdge) == -1)) {
+ throw "Edge already in source and/or target incidency list!";
+ }
+
+ newEdge.source.edges.push(newEdge);
+ newEdge.target.edges.push(newEdge);
+
+ return newEdge;
+ }
+ }
+};
+
+LGraphManager.prototype.remove = function (lObj) {
+ if (lObj instanceof LGraph) {
+ var graph = lObj;
+ if (graph.getGraphManager() != this) {
+ throw "Graph not in this graph mgr";
+ }
+ if (!(graph == this.rootGraph || graph.parent != null && graph.parent.graphManager == this)) {
+ throw "Invalid parent node!";
+ }
+
+ // first the edges (make a copy to do it safely)
+ var edgesToBeRemoved = [];
+
+ edgesToBeRemoved = edgesToBeRemoved.concat(graph.getEdges());
+
+ var edge;
+ var s = edgesToBeRemoved.length;
+ for (var i = 0; i < s; i++) {
+ edge = edgesToBeRemoved[i];
+ graph.remove(edge);
+ }
+
+ // then the nodes (make a copy to do it safely)
+ var nodesToBeRemoved = [];
+
+ nodesToBeRemoved = nodesToBeRemoved.concat(graph.getNodes());
+
+ var node;
+ s = nodesToBeRemoved.length;
+ for (var i = 0; i < s; i++) {
+ node = nodesToBeRemoved[i];
+ graph.remove(node);
+ }
+
+ // check if graph is the root
+ if (graph == this.rootGraph) {
+ this.setRootGraph(null);
+ }
+
+ // now remove the graph itself
+ var index = this.graphs.indexOf(graph);
+ this.graphs.splice(index, 1);
+
+ // also reset the parent of the graph
+ graph.parent = null;
+ } else if (lObj instanceof LEdge) {
+ edge = lObj;
+ if (edge == null) {
+ throw "Edge is null!";
+ }
+ if (!edge.isInterGraph) {
+ throw "Not an inter-graph edge!";
+ }
+ if (!(edge.source != null && edge.target != null)) {
+ throw "Source and/or target is null!";
+ }
+
+ // remove edge from source and target nodes' incidency lists
+
+ if (!(edge.source.edges.indexOf(edge) != -1 && edge.target.edges.indexOf(edge) != -1)) {
+ throw "Source and/or target doesn't know this edge!";
+ }
+
+ var index = edge.source.edges.indexOf(edge);
+ edge.source.edges.splice(index, 1);
+ index = edge.target.edges.indexOf(edge);
+ edge.target.edges.splice(index, 1);
+
+ // remove edge from owner graph manager's inter-graph edge list
+
+ if (!(edge.source.owner != null && edge.source.owner.getGraphManager() != null)) {
+ throw "Edge owner graph or owner graph manager is null!";
+ }
+ if (edge.source.owner.getGraphManager().edges.indexOf(edge) == -1) {
+ throw "Not in owner graph manager's edge list!";
+ }
+
+ var index = edge.source.owner.getGraphManager().edges.indexOf(edge);
+ edge.source.owner.getGraphManager().edges.splice(index, 1);
+ }
+};
+
+LGraphManager.prototype.updateBounds = function () {
+ this.rootGraph.updateBounds(true);
+};
+
+LGraphManager.prototype.getGraphs = function () {
+ return this.graphs;
+};
+
+LGraphManager.prototype.getAllNodes = function () {
+ if (this.allNodes == null) {
+ var nodeList = [];
+ var graphs = this.getGraphs();
+ var s = graphs.length;
+ for (var i = 0; i < s; i++) {
+ nodeList = nodeList.concat(graphs[i].getNodes());
+ }
+ this.allNodes = nodeList;
+ }
+ return this.allNodes;
+};
+
+LGraphManager.prototype.resetAllNodes = function () {
+ this.allNodes = null;
+};
+
+LGraphManager.prototype.resetAllEdges = function () {
+ this.allEdges = null;
+};
+
+LGraphManager.prototype.resetAllNodesToApplyGravitation = function () {
+ this.allNodesToApplyGravitation = null;
+};
+
+LGraphManager.prototype.getAllEdges = function () {
+ if (this.allEdges == null) {
+ var edgeList = [];
+ var graphs = this.getGraphs();
+ var s = graphs.length;
+ for (var i = 0; i < graphs.length; i++) {
+ edgeList = edgeList.concat(graphs[i].getEdges());
+ }
+
+ edgeList = edgeList.concat(this.edges);
+
+ this.allEdges = edgeList;
+ }
+ return this.allEdges;
+};
+
+LGraphManager.prototype.getAllNodesToApplyGravitation = function () {
+ return this.allNodesToApplyGravitation;
+};
+
+LGraphManager.prototype.setAllNodesToApplyGravitation = function (nodeList) {
+ if (this.allNodesToApplyGravitation != null) {
+ throw "assert failed";
+ }
+
+ this.allNodesToApplyGravitation = nodeList;
+};
+
+LGraphManager.prototype.getRoot = function () {
+ return this.rootGraph;
+};
+
+LGraphManager.prototype.setRootGraph = function (graph) {
+ if (graph.getGraphManager() != this) {
+ throw "Root not in this graph mgr!";
+ }
+
+ this.rootGraph = graph;
+ // root graph must have a root node associated with it for convenience
+ if (graph.parent == null) {
+ graph.parent = this.layout.newNode("Root node");
+ }
+};
+
+LGraphManager.prototype.getLayout = function () {
+ return this.layout;
+};
+
+LGraphManager.prototype.isOneAncestorOfOther = function (firstNode, secondNode) {
+ if (!(firstNode != null && secondNode != null)) {
+ throw "assert failed";
+ }
+
+ if (firstNode == secondNode) {
+ return true;
+ }
+ // Is second node an ancestor of the first one?
+ var ownerGraph = firstNode.getOwner();
+ var parentNode;
+
+ do {
+ parentNode = ownerGraph.getParent();
+
+ if (parentNode == null) {
+ break;
+ }
+
+ if (parentNode == secondNode) {
+ return true;
+ }
+
+ ownerGraph = parentNode.getOwner();
+ if (ownerGraph == null) {
+ break;
+ }
+ } while (true);
+ // Is first node an ancestor of the second one?
+ ownerGraph = secondNode.getOwner();
+
+ do {
+ parentNode = ownerGraph.getParent();
+
+ if (parentNode == null) {
+ break;
+ }
+
+ if (parentNode == firstNode) {
+ return true;
+ }
+
+ ownerGraph = parentNode.getOwner();
+ if (ownerGraph == null) {
+ break;
+ }
+ } while (true);
+
+ return false;
+};
+
+LGraphManager.prototype.calcLowestCommonAncestors = function () {
+ var edge;
+ var sourceNode;
+ var targetNode;
+ var sourceAncestorGraph;
+ var targetAncestorGraph;
+
+ var edges = this.getAllEdges();
+ var s = edges.length;
+ for (var i = 0; i < s; i++) {
+ edge = edges[i];
+
+ sourceNode = edge.source;
+ targetNode = edge.target;
+ edge.lca = null;
+ edge.sourceInLca = sourceNode;
+ edge.targetInLca = targetNode;
+
+ if (sourceNode == targetNode) {
+ edge.lca = sourceNode.getOwner();
+ continue;
+ }
+
+ sourceAncestorGraph = sourceNode.getOwner();
+
+ while (edge.lca == null) {
+ edge.targetInLca = targetNode;
+ targetAncestorGraph = targetNode.getOwner();
+
+ while (edge.lca == null) {
+ if (targetAncestorGraph == sourceAncestorGraph) {
+ edge.lca = targetAncestorGraph;
+ break;
+ }
+
+ if (targetAncestorGraph == this.rootGraph) {
+ break;
+ }
+
+ if (edge.lca != null) {
+ throw "assert failed";
+ }
+ edge.targetInLca = targetAncestorGraph.getParent();
+ targetAncestorGraph = edge.targetInLca.getOwner();
+ }
+
+ if (sourceAncestorGraph == this.rootGraph) {
+ break;
+ }
+
+ if (edge.lca == null) {
+ edge.sourceInLca = sourceAncestorGraph.getParent();
+ sourceAncestorGraph = edge.sourceInLca.getOwner();
+ }
+ }
+
+ if (edge.lca == null) {
+ throw "assert failed";
+ }
+ }
+};
+
+LGraphManager.prototype.calcLowestCommonAncestor = function (firstNode, secondNode) {
+ if (firstNode == secondNode) {
+ return firstNode.getOwner();
+ }
+ var firstOwnerGraph = firstNode.getOwner();
+
+ do {
+ if (firstOwnerGraph == null) {
+ break;
+ }
+ var secondOwnerGraph = secondNode.getOwner();
+
+ do {
+ if (secondOwnerGraph == null) {
+ break;
+ }
+
+ if (secondOwnerGraph == firstOwnerGraph) {
+ return secondOwnerGraph;
+ }
+ secondOwnerGraph = secondOwnerGraph.getParent().getOwner();
+ } while (true);
+
+ firstOwnerGraph = firstOwnerGraph.getParent().getOwner();
+ } while (true);
+
+ return firstOwnerGraph;
+};
+
+LGraphManager.prototype.calcInclusionTreeDepths = function (graph, depth) {
+ if (graph == null && depth == null) {
+ graph = this.rootGraph;
+ depth = 1;
+ }
+ var node;
+
+ var nodes = graph.getNodes();
+ var s = nodes.length;
+ for (var i = 0; i < s; i++) {
+ node = nodes[i];
+ node.inclusionTreeDepth = depth;
+
+ if (node.child != null) {
+ this.calcInclusionTreeDepths(node.child, depth + 1);
+ }
+ }
+};
+
+LGraphManager.prototype.includesInvalidEdge = function () {
+ var edge;
+ var edgesToRemove = [];
+
+ var s = this.edges.length;
+ for (var i = 0; i < s; i++) {
+ edge = this.edges[i];
+
+ if (this.isOneAncestorOfOther(edge.source, edge.target)) {
+ edgesToRemove.push(edge);
+ }
+ }
+
+ // Remove invalid edges from graph manager
+ for (var i = 0; i < edgesToRemove.length; i++) {
+ this.remove(edgesToRemove[i]);
+ }
+
+ // Invalid edges are cleared, so return false
+ return false;
+};
+
+module.exports = LGraphManager;
+
+/***/ }),
+/* 8 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+/**
+ * This class maintains a list of static geometry related utility methods.
+ *
+ *
+ * Copyright: i-Vis Research Group, Bilkent University, 2007 - present
+ */
+
+var Point = __webpack_require__(12);
+
+function IGeometry() {}
+
+/**
+ * This method calculates *half* the amount in x and y directions of the two
+ * input rectangles needed to separate them keeping their respective
+ * positioning, and returns the result in the input array. An input
+ * separation buffer added to the amount in both directions. We assume that
+ * the two rectangles do intersect.
+ */
+IGeometry.calcSeparationAmount = function (rectA, rectB, overlapAmount, separationBuffer) {
+ if (!rectA.intersects(rectB)) {
+ throw "assert failed";
+ }
+
+ var directions = new Array(2);
+
+ this.decideDirectionsForOverlappingNodes(rectA, rectB, directions);
+
+ overlapAmount[0] = Math.min(rectA.getRight(), rectB.getRight()) - Math.max(rectA.x, rectB.x);
+ overlapAmount[1] = Math.min(rectA.getBottom(), rectB.getBottom()) - Math.max(rectA.y, rectB.y);
+
+ // update the overlapping amounts for the following cases:
+ if (rectA.getX() <= rectB.getX() && rectA.getRight() >= rectB.getRight()) {
+ /* Case x.1:
+ *
+ * rectA
+ * | |
+ * | _________ |
+ * | | | |
+ * |________|_______|______|
+ * | |
+ * | |
+ * rectB
+ */
+ overlapAmount[0] += Math.min(rectB.getX() - rectA.getX(), rectA.getRight() - rectB.getRight());
+ } else if (rectB.getX() <= rectA.getX() && rectB.getRight() >= rectA.getRight()) {
+ /* Case x.2:
+ *
+ * rectB
+ * | |
+ * | _________ |
+ * | | | |
+ * |________|_______|______|
+ * | |
+ * | |
+ * rectA
+ */
+ overlapAmount[0] += Math.min(rectA.getX() - rectB.getX(), rectB.getRight() - rectA.getRight());
+ }
+ if (rectA.getY() <= rectB.getY() && rectA.getBottom() >= rectB.getBottom()) {
+ /* Case y.1:
+ * ________ rectA
+ * |
+ * |
+ * ______|____ rectB
+ * | |
+ * | |
+ * ______|____|
+ * |
+ * |
+ * |________
+ *
+ */
+ overlapAmount[1] += Math.min(rectB.getY() - rectA.getY(), rectA.getBottom() - rectB.getBottom());
+ } else if (rectB.getY() <= rectA.getY() && rectB.getBottom() >= rectA.getBottom()) {
+ /* Case y.2:
+ * ________ rectB
+ * |
+ * |
+ * ______|____ rectA
+ * | |
+ * | |
+ * ______|____|
+ * |
+ * |
+ * |________
+ *
+ */
+ overlapAmount[1] += Math.min(rectA.getY() - rectB.getY(), rectB.getBottom() - rectA.getBottom());
+ }
+
+ // find slope of the line passes two centers
+ var slope = Math.abs((rectB.getCenterY() - rectA.getCenterY()) / (rectB.getCenterX() - rectA.getCenterX()));
+ // if centers are overlapped
+ if (rectB.getCenterY() === rectA.getCenterY() && rectB.getCenterX() === rectA.getCenterX()) {
+ // assume the slope is 1 (45 degree)
+ slope = 1.0;
+ }
+
+ var moveByY = slope * overlapAmount[0];
+ var moveByX = overlapAmount[1] / slope;
+ if (overlapAmount[0] < moveByX) {
+ moveByX = overlapAmount[0];
+ } else {
+ moveByY = overlapAmount[1];
+ }
+ // return half the amount so that if each rectangle is moved by these
+ // amounts in opposite directions, overlap will be resolved
+ overlapAmount[0] = -1 * directions[0] * (moveByX / 2 + separationBuffer);
+ overlapAmount[1] = -1 * directions[1] * (moveByY / 2 + separationBuffer);
+};
+
+/**
+ * This method decides the separation direction of overlapping nodes
+ *
+ * if directions[0] = -1, then rectA goes left
+ * if directions[0] = 1, then rectA goes right
+ * if directions[1] = -1, then rectA goes up
+ * if directions[1] = 1, then rectA goes down
+ */
+IGeometry.decideDirectionsForOverlappingNodes = function (rectA, rectB, directions) {
+ if (rectA.getCenterX() < rectB.getCenterX()) {
+ directions[0] = -1;
+ } else {
+ directions[0] = 1;
+ }
+
+ if (rectA.getCenterY() < rectB.getCenterY()) {
+ directions[1] = -1;
+ } else {
+ directions[1] = 1;
+ }
+};
+
+/**
+ * This method calculates the intersection (clipping) points of the two
+ * input rectangles with line segment defined by the centers of these two
+ * rectangles. The clipping points are saved in the input double array and
+ * whether or not the two rectangles overlap is returned.
+ */
+IGeometry.getIntersection2 = function (rectA, rectB, result) {
+ //result[0-1] will contain clipPoint of rectA, result[2-3] will contain clipPoint of rectB
+ var p1x = rectA.getCenterX();
+ var p1y = rectA.getCenterY();
+ var p2x = rectB.getCenterX();
+ var p2y = rectB.getCenterY();
+
+ //if two rectangles intersect, then clipping points are centers
+ if (rectA.intersects(rectB)) {
+ result[0] = p1x;
+ result[1] = p1y;
+ result[2] = p2x;
+ result[3] = p2y;
+ return true;
+ }
+ //variables for rectA
+ var topLeftAx = rectA.getX();
+ var topLeftAy = rectA.getY();
+ var topRightAx = rectA.getRight();
+ var bottomLeftAx = rectA.getX();
+ var bottomLeftAy = rectA.getBottom();
+ var bottomRightAx = rectA.getRight();
+ var halfWidthA = rectA.getWidthHalf();
+ var halfHeightA = rectA.getHeightHalf();
+ //variables for rectB
+ var topLeftBx = rectB.getX();
+ var topLeftBy = rectB.getY();
+ var topRightBx = rectB.getRight();
+ var bottomLeftBx = rectB.getX();
+ var bottomLeftBy = rectB.getBottom();
+ var bottomRightBx = rectB.getRight();
+ var halfWidthB = rectB.getWidthHalf();
+ var halfHeightB = rectB.getHeightHalf();
+
+ //flag whether clipping points are found
+ var clipPointAFound = false;
+ var clipPointBFound = false;
+
+ // line is vertical
+ if (p1x === p2x) {
+ if (p1y > p2y) {
+ result[0] = p1x;
+ result[1] = topLeftAy;
+ result[2] = p2x;
+ result[3] = bottomLeftBy;
+ return false;
+ } else if (p1y < p2y) {
+ result[0] = p1x;
+ result[1] = bottomLeftAy;
+ result[2] = p2x;
+ result[3] = topLeftBy;
+ return false;
+ } else {
+ //not line, return null;
+ }
+ }
+ // line is horizontal
+ else if (p1y === p2y) {
+ if (p1x > p2x) {
+ result[0] = topLeftAx;
+ result[1] = p1y;
+ result[2] = topRightBx;
+ result[3] = p2y;
+ return false;
+ } else if (p1x < p2x) {
+ result[0] = topRightAx;
+ result[1] = p1y;
+ result[2] = topLeftBx;
+ result[3] = p2y;
+ return false;
+ } else {
+ //not valid line, return null;
+ }
+ } else {
+ //slopes of rectA's and rectB's diagonals
+ var slopeA = rectA.height / rectA.width;
+ var slopeB = rectB.height / rectB.width;
+
+ //slope of line between center of rectA and center of rectB
+ var slopePrime = (p2y - p1y) / (p2x - p1x);
+ var cardinalDirectionA = void 0;
+ var cardinalDirectionB = void 0;
+ var tempPointAx = void 0;
+ var tempPointAy = void 0;
+ var tempPointBx = void 0;
+ var tempPointBy = void 0;
+
+ //determine whether clipping point is the corner of nodeA
+ if (-slopeA === slopePrime) {
+ if (p1x > p2x) {
+ result[0] = bottomLeftAx;
+ result[1] = bottomLeftAy;
+ clipPointAFound = true;
+ } else {
+ result[0] = topRightAx;
+ result[1] = topLeftAy;
+ clipPointAFound = true;
+ }
+ } else if (slopeA === slopePrime) {
+ if (p1x > p2x) {
+ result[0] = topLeftAx;
+ result[1] = topLeftAy;
+ clipPointAFound = true;
+ } else {
+ result[0] = bottomRightAx;
+ result[1] = bottomLeftAy;
+ clipPointAFound = true;
+ }
+ }
+
+ //determine whether clipping point is the corner of nodeB
+ if (-slopeB === slopePrime) {
+ if (p2x > p1x) {
+ result[2] = bottomLeftBx;
+ result[3] = bottomLeftBy;
+ clipPointBFound = true;
+ } else {
+ result[2] = topRightBx;
+ result[3] = topLeftBy;
+ clipPointBFound = true;
+ }
+ } else if (slopeB === slopePrime) {
+ if (p2x > p1x) {
+ result[2] = topLeftBx;
+ result[3] = topLeftBy;
+ clipPointBFound = true;
+ } else {
+ result[2] = bottomRightBx;
+ result[3] = bottomLeftBy;
+ clipPointBFound = true;
+ }
+ }
+
+ //if both clipping points are corners
+ if (clipPointAFound && clipPointBFound) {
+ return false;
+ }
+
+ //determine Cardinal Direction of rectangles
+ if (p1x > p2x) {
+ if (p1y > p2y) {
+ cardinalDirectionA = this.getCardinalDirection(slopeA, slopePrime, 4);
+ cardinalDirectionB = this.getCardinalDirection(slopeB, slopePrime, 2);
+ } else {
+ cardinalDirectionA = this.getCardinalDirection(-slopeA, slopePrime, 3);
+ cardinalDirectionB = this.getCardinalDirection(-slopeB, slopePrime, 1);
+ }
+ } else {
+ if (p1y > p2y) {
+ cardinalDirectionA = this.getCardinalDirection(-slopeA, slopePrime, 1);
+ cardinalDirectionB = this.getCardinalDirection(-slopeB, slopePrime, 3);
+ } else {
+ cardinalDirectionA = this.getCardinalDirection(slopeA, slopePrime, 2);
+ cardinalDirectionB = this.getCardinalDirection(slopeB, slopePrime, 4);
+ }
+ }
+ //calculate clipping Point if it is not found before
+ if (!clipPointAFound) {
+ switch (cardinalDirectionA) {
+ case 1:
+ tempPointAy = topLeftAy;
+ tempPointAx = p1x + -halfHeightA / slopePrime;
+ result[0] = tempPointAx;
+ result[1] = tempPointAy;
+ break;
+ case 2:
+ tempPointAx = bottomRightAx;
+ tempPointAy = p1y + halfWidthA * slopePrime;
+ result[0] = tempPointAx;
+ result[1] = tempPointAy;
+ break;
+ case 3:
+ tempPointAy = bottomLeftAy;
+ tempPointAx = p1x + halfHeightA / slopePrime;
+ result[0] = tempPointAx;
+ result[1] = tempPointAy;
+ break;
+ case 4:
+ tempPointAx = bottomLeftAx;
+ tempPointAy = p1y + -halfWidthA * slopePrime;
+ result[0] = tempPointAx;
+ result[1] = tempPointAy;
+ break;
+ }
+ }
+ if (!clipPointBFound) {
+ switch (cardinalDirectionB) {
+ case 1:
+ tempPointBy = topLeftBy;
+ tempPointBx = p2x + -halfHeightB / slopePrime;
+ result[2] = tempPointBx;
+ result[3] = tempPointBy;
+ break;
+ case 2:
+ tempPointBx = bottomRightBx;
+ tempPointBy = p2y + halfWidthB * slopePrime;
+ result[2] = tempPointBx;
+ result[3] = tempPointBy;
+ break;
+ case 3:
+ tempPointBy = bottomLeftBy;
+ tempPointBx = p2x + halfHeightB / slopePrime;
+ result[2] = tempPointBx;
+ result[3] = tempPointBy;
+ break;
+ case 4:
+ tempPointBx = bottomLeftBx;
+ tempPointBy = p2y + -halfWidthB * slopePrime;
+ result[2] = tempPointBx;
+ result[3] = tempPointBy;
+ break;
+ }
+ }
+ }
+ return false;
+};
+
+/**
+ * This method returns in which cardinal direction does input point stays
+ * 1: North
+ * 2: East
+ * 3: South
+ * 4: West
+ */
+IGeometry.getCardinalDirection = function (slope, slopePrime, line) {
+ if (slope > slopePrime) {
+ return line;
+ } else {
+ return 1 + line % 4;
+ }
+};
+
+/**
+ * This method calculates the intersection of the two lines defined by
+ * point pairs (s1,s2) and (f1,f2).
+ */
+IGeometry.getIntersection = function (s1, s2, f1, f2) {
+ if (f2 == null) {
+ return this.getIntersection2(s1, s2, f1);
+ }
+
+ var x1 = s1.x;
+ var y1 = s1.y;
+ var x2 = s2.x;
+ var y2 = s2.y;
+ var x3 = f1.x;
+ var y3 = f1.y;
+ var x4 = f2.x;
+ var y4 = f2.y;
+ var x = void 0,
+ y = void 0; // intersection point
+ var a1 = void 0,
+ a2 = void 0,
+ b1 = void 0,
+ b2 = void 0,
+ c1 = void 0,
+ c2 = void 0; // coefficients of line eqns.
+ var denom = void 0;
+
+ a1 = y2 - y1;
+ b1 = x1 - x2;
+ c1 = x2 * y1 - x1 * y2; // { a1*x + b1*y + c1 = 0 is line 1 }
+
+ a2 = y4 - y3;
+ b2 = x3 - x4;
+ c2 = x4 * y3 - x3 * y4; // { a2*x + b2*y + c2 = 0 is line 2 }
+
+ denom = a1 * b2 - a2 * b1;
+
+ if (denom === 0) {
+ return null;
+ }
+
+ x = (b1 * c2 - b2 * c1) / denom;
+ y = (a2 * c1 - a1 * c2) / denom;
+
+ return new Point(x, y);
+};
+
+/**
+ * This method finds and returns the angle of the vector from the + x-axis
+ * in clockwise direction (compatible w/ Java coordinate system!).
+ */
+IGeometry.angleOfVector = function (Cx, Cy, Nx, Ny) {
+ var C_angle = void 0;
+
+ if (Cx !== Nx) {
+ C_angle = Math.atan((Ny - Cy) / (Nx - Cx));
+
+ if (Nx < Cx) {
+ C_angle += Math.PI;
+ } else if (Ny < Cy) {
+ C_angle += this.TWO_PI;
+ }
+ } else if (Ny < Cy) {
+ C_angle = this.ONE_AND_HALF_PI; // 270 degrees
+ } else {
+ C_angle = this.HALF_PI; // 90 degrees
+ }
+
+ return C_angle;
+};
+
+/**
+ * This method checks whether the given two line segments (one with point
+ * p1 and p2, the other with point p3 and p4) intersect at a point other
+ * than these points.
+ */
+IGeometry.doIntersect = function (p1, p2, p3, p4) {
+ var a = p1.x;
+ var b = p1.y;
+ var c = p2.x;
+ var d = p2.y;
+ var p = p3.x;
+ var q = p3.y;
+ var r = p4.x;
+ var s = p4.y;
+ var det = (c - a) * (s - q) - (r - p) * (d - b);
+
+ if (det === 0) {
+ return false;
+ } else {
+ var lambda = ((s - q) * (r - a) + (p - r) * (s - b)) / det;
+ var gamma = ((b - d) * (r - a) + (c - a) * (s - b)) / det;
+ return 0 < lambda && lambda < 1 && 0 < gamma && gamma < 1;
+ }
+};
+
+/**
+ * This method checks and calculates the intersection of
+ * a line segment and a circle.
+ */
+IGeometry.findCircleLineIntersections = function (Ex, Ey, Lx, Ly, Cx, Cy, r) {
+
+ // E is the starting point of the ray,
+ // L is the end point of the ray,
+ // C is the center of sphere you're testing against
+ // r is the radius of that sphere
+
+ // Compute:
+ // d = L - E ( Direction vector of ray, from start to end )
+ // f = E - C ( Vector from center sphere to ray start )
+
+ // Then the intersection is found by..
+ // P = E + t * d
+ // This is a parametric equation:
+ // Px = Ex + tdx
+ // Py = Ey + tdy
+
+ // get a, b, c values
+ var a = (Lx - Ex) * (Lx - Ex) + (Ly - Ey) * (Ly - Ey);
+ var b = 2 * ((Ex - Cx) * (Lx - Ex) + (Ey - Cy) * (Ly - Ey));
+ var c = (Ex - Cx) * (Ex - Cx) + (Ey - Cy) * (Ey - Cy) - r * r;
+
+ // get discriminant
+ var disc = b * b - 4 * a * c;
+ if (disc >= 0) {
+ // insert into quadratic formula
+ var t1 = (-b + Math.sqrt(b * b - 4 * a * c)) / (2 * a);
+ var t2 = (-b - Math.sqrt(b * b - 4 * a * c)) / (2 * a);
+ var intersections = null;
+ if (t1 >= 0 && t1 <= 1) {
+ // t1 is the intersection, and it's closer than t2
+ // (since t1 uses -b - discriminant)
+ // Impale, Poke
+ return [t1];
+ }
+
+ // here t1 didn't intersect so we are either started
+ // inside the sphere or completely past it
+ if (t2 >= 0 && t2 <= 1) {
+ // ExitWound
+ return [t2];
+ }
+
+ return intersections;
+ } else return null;
+};
+
+// -----------------------------------------------------------------------------
+// Section: Class Constants
+// -----------------------------------------------------------------------------
+/**
+ * Some useful pre-calculated constants
+ */
+IGeometry.HALF_PI = 0.5 * Math.PI;
+IGeometry.ONE_AND_HALF_PI = 1.5 * Math.PI;
+IGeometry.TWO_PI = 2.0 * Math.PI;
+IGeometry.THREE_PI = 3.0 * Math.PI;
+
+module.exports = IGeometry;
+
+/***/ }),
+/* 9 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+function IMath() {}
+
+/**
+ * This method returns the sign of the input value.
+ */
+IMath.sign = function (value) {
+ if (value > 0) {
+ return 1;
+ } else if (value < 0) {
+ return -1;
+ } else {
+ return 0;
+ }
+};
+
+IMath.floor = function (value) {
+ return value < 0 ? Math.ceil(value) : Math.floor(value);
+};
+
+IMath.ceil = function (value) {
+ return value < 0 ? Math.floor(value) : Math.ceil(value);
+};
+
+module.exports = IMath;
+
+/***/ }),
+/* 10 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+function Integer() {}
+
+Integer.MAX_VALUE = 2147483647;
+Integer.MIN_VALUE = -2147483648;
+
+module.exports = Integer;
+
+/***/ }),
+/* 11 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
+
+function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
+
+var nodeFrom = function nodeFrom(value) {
+ return { value: value, next: null, prev: null };
+};
+
+var add = function add(prev, node, next, list) {
+ if (prev !== null) {
+ prev.next = node;
+ } else {
+ list.head = node;
+ }
+
+ if (next !== null) {
+ next.prev = node;
+ } else {
+ list.tail = node;
+ }
+
+ node.prev = prev;
+ node.next = next;
+
+ list.length++;
+
+ return node;
+};
+
+var _remove = function _remove(node, list) {
+ var prev = node.prev,
+ next = node.next;
+
+
+ if (prev !== null) {
+ prev.next = next;
+ } else {
+ list.head = next;
+ }
+
+ if (next !== null) {
+ next.prev = prev;
+ } else {
+ list.tail = prev;
+ }
+
+ node.prev = node.next = null;
+
+ list.length--;
+
+ return node;
+};
+
+var LinkedList = function () {
+ function LinkedList(vals) {
+ var _this = this;
+
+ _classCallCheck(this, LinkedList);
+
+ this.length = 0;
+ this.head = null;
+ this.tail = null;
+
+ if (vals != null) {
+ vals.forEach(function (v) {
+ return _this.push(v);
+ });
+ }
+ }
+
+ _createClass(LinkedList, [{
+ key: "size",
+ value: function size() {
+ return this.length;
+ }
+ }, {
+ key: "insertBefore",
+ value: function insertBefore(val, otherNode) {
+ return add(otherNode.prev, nodeFrom(val), otherNode, this);
+ }
+ }, {
+ key: "insertAfter",
+ value: function insertAfter(val, otherNode) {
+ return add(otherNode, nodeFrom(val), otherNode.next, this);
+ }
+ }, {
+ key: "insertNodeBefore",
+ value: function insertNodeBefore(newNode, otherNode) {
+ return add(otherNode.prev, newNode, otherNode, this);
+ }
+ }, {
+ key: "insertNodeAfter",
+ value: function insertNodeAfter(newNode, otherNode) {
+ return add(otherNode, newNode, otherNode.next, this);
+ }
+ }, {
+ key: "push",
+ value: function push(val) {
+ return add(this.tail, nodeFrom(val), null, this);
+ }
+ }, {
+ key: "unshift",
+ value: function unshift(val) {
+ return add(null, nodeFrom(val), this.head, this);
+ }
+ }, {
+ key: "remove",
+ value: function remove(node) {
+ return _remove(node, this);
+ }
+ }, {
+ key: "pop",
+ value: function pop() {
+ return _remove(this.tail, this).value;
+ }
+ }, {
+ key: "popNode",
+ value: function popNode() {
+ return _remove(this.tail, this);
+ }
+ }, {
+ key: "shift",
+ value: function shift() {
+ return _remove(this.head, this).value;
+ }
+ }, {
+ key: "shiftNode",
+ value: function shiftNode() {
+ return _remove(this.head, this);
+ }
+ }, {
+ key: "get_object_at",
+ value: function get_object_at(index) {
+ if (index <= this.length()) {
+ var i = 1;
+ var current = this.head;
+ while (i < index) {
+ current = current.next;
+ i++;
+ }
+ return current.value;
+ }
+ }
+ }, {
+ key: "set_object_at",
+ value: function set_object_at(index, value) {
+ if (index <= this.length()) {
+ var i = 1;
+ var current = this.head;
+ while (i < index) {
+ current = current.next;
+ i++;
+ }
+ current.value = value;
+ }
+ }
+ }]);
+
+ return LinkedList;
+}();
+
+module.exports = LinkedList;
+
+/***/ }),
+/* 12 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+/*
+ *This class is the javascript implementation of the Point.java class in jdk
+ */
+function Point(x, y, p) {
+ this.x = null;
+ this.y = null;
+ if (x == null && y == null && p == null) {
+ this.x = 0;
+ this.y = 0;
+ } else if (typeof x == 'number' && typeof y == 'number' && p == null) {
+ this.x = x;
+ this.y = y;
+ } else if (x.constructor.name == 'Point' && y == null && p == null) {
+ p = x;
+ this.x = p.x;
+ this.y = p.y;
+ }
+}
+
+Point.prototype.getX = function () {
+ return this.x;
+};
+
+Point.prototype.getY = function () {
+ return this.y;
+};
+
+Point.prototype.getLocation = function () {
+ return new Point(this.x, this.y);
+};
+
+Point.prototype.setLocation = function (x, y, p) {
+ if (x.constructor.name == 'Point' && y == null && p == null) {
+ p = x;
+ this.setLocation(p.x, p.y);
+ } else if (typeof x == 'number' && typeof y == 'number' && p == null) {
+ //if both parameters are integer just move (x,y) location
+ if (parseInt(x) == x && parseInt(y) == y) {
+ this.move(x, y);
+ } else {
+ this.x = Math.floor(x + 0.5);
+ this.y = Math.floor(y + 0.5);
+ }
+ }
+};
+
+Point.prototype.move = function (x, y) {
+ this.x = x;
+ this.y = y;
+};
+
+Point.prototype.translate = function (dx, dy) {
+ this.x += dx;
+ this.y += dy;
+};
+
+Point.prototype.equals = function (obj) {
+ if (obj.constructor.name == "Point") {
+ var pt = obj;
+ return this.x == pt.x && this.y == pt.y;
+ }
+ return this == obj;
+};
+
+Point.prototype.toString = function () {
+ return new Point().constructor.name + "[x=" + this.x + ",y=" + this.y + "]";
+};
+
+module.exports = Point;
+
+/***/ }),
+/* 13 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+function RectangleD(x, y, width, height) {
+ this.x = 0;
+ this.y = 0;
+ this.width = 0;
+ this.height = 0;
+
+ if (x != null && y != null && width != null && height != null) {
+ this.x = x;
+ this.y = y;
+ this.width = width;
+ this.height = height;
+ }
+}
+
+RectangleD.prototype.getX = function () {
+ return this.x;
+};
+
+RectangleD.prototype.setX = function (x) {
+ this.x = x;
+};
+
+RectangleD.prototype.getY = function () {
+ return this.y;
+};
+
+RectangleD.prototype.setY = function (y) {
+ this.y = y;
+};
+
+RectangleD.prototype.getWidth = function () {
+ return this.width;
+};
+
+RectangleD.prototype.setWidth = function (width) {
+ this.width = width;
+};
+
+RectangleD.prototype.getHeight = function () {
+ return this.height;
+};
+
+RectangleD.prototype.setHeight = function (height) {
+ this.height = height;
+};
+
+RectangleD.prototype.getRight = function () {
+ return this.x + this.width;
+};
+
+RectangleD.prototype.getBottom = function () {
+ return this.y + this.height;
+};
+
+RectangleD.prototype.intersects = function (a) {
+ if (this.getRight() < a.x) {
+ return false;
+ }
+
+ if (this.getBottom() < a.y) {
+ return false;
+ }
+
+ if (a.getRight() < this.x) {
+ return false;
+ }
+
+ if (a.getBottom() < this.y) {
+ return false;
+ }
+
+ return true;
+};
+
+RectangleD.prototype.getCenterX = function () {
+ return this.x + this.width / 2;
+};
+
+RectangleD.prototype.getMinX = function () {
+ return this.getX();
+};
+
+RectangleD.prototype.getMaxX = function () {
+ return this.getX() + this.width;
+};
+
+RectangleD.prototype.getCenterY = function () {
+ return this.y + this.height / 2;
+};
+
+RectangleD.prototype.getMinY = function () {
+ return this.getY();
+};
+
+RectangleD.prototype.getMaxY = function () {
+ return this.getY() + this.height;
+};
+
+RectangleD.prototype.getWidthHalf = function () {
+ return this.width / 2;
+};
+
+RectangleD.prototype.getHeightHalf = function () {
+ return this.height / 2;
+};
+
+module.exports = RectangleD;
+
+/***/ }),
+/* 14 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
+
+function UniqueIDGeneretor() {}
+
+UniqueIDGeneretor.lastID = 0;
+
+UniqueIDGeneretor.createID = function (obj) {
+ if (UniqueIDGeneretor.isPrimitive(obj)) {
+ return obj;
+ }
+ if (obj.uniqueID != null) {
+ return obj.uniqueID;
+ }
+ obj.uniqueID = UniqueIDGeneretor.getString();
+ UniqueIDGeneretor.lastID++;
+ return obj.uniqueID;
+};
+
+UniqueIDGeneretor.getString = function (id) {
+ if (id == null) id = UniqueIDGeneretor.lastID;
+ return "Object#" + id + "";
+};
+
+UniqueIDGeneretor.isPrimitive = function (arg) {
+ var type = typeof arg === "undefined" ? "undefined" : _typeof(arg);
+ return arg == null || type != "object" && type != "function";
+};
+
+module.exports = UniqueIDGeneretor;
+
+/***/ }),
+/* 15 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
+
+var LayoutConstants = __webpack_require__(0);
+var LGraphManager = __webpack_require__(7);
+var LNode = __webpack_require__(3);
+var LEdge = __webpack_require__(1);
+var LGraph = __webpack_require__(6);
+var PointD = __webpack_require__(5);
+var Transform = __webpack_require__(17);
+var Emitter = __webpack_require__(29);
+
+function Layout(isRemoteUse) {
+ Emitter.call(this);
+
+ //Layout Quality: 0:draft, 1:default, 2:proof
+ this.layoutQuality = LayoutConstants.QUALITY;
+ //Whether layout should create bendpoints as needed or not
+ this.createBendsAsNeeded = LayoutConstants.DEFAULT_CREATE_BENDS_AS_NEEDED;
+ //Whether layout should be incremental or not
+ this.incremental = LayoutConstants.DEFAULT_INCREMENTAL;
+ //Whether we animate from before to after layout node positions
+ this.animationOnLayout = LayoutConstants.DEFAULT_ANIMATION_ON_LAYOUT;
+ //Whether we animate the layout process or not
+ this.animationDuringLayout = LayoutConstants.DEFAULT_ANIMATION_DURING_LAYOUT;
+ //Number iterations that should be done between two successive animations
+ this.animationPeriod = LayoutConstants.DEFAULT_ANIMATION_PERIOD;
+ /**
+ * Whether or not leaf nodes (non-compound nodes) are of uniform sizes. When
+ * they are, both spring and repulsion forces between two leaf nodes can be
+ * calculated without the expensive clipping point calculations, resulting
+ * in major speed-up.
+ */
+ this.uniformLeafNodeSizes = LayoutConstants.DEFAULT_UNIFORM_LEAF_NODE_SIZES;
+ /**
+ * This is used for creation of bendpoints by using dummy nodes and edges.
+ * Maps an LEdge to its dummy bendpoint path.
+ */
+ this.edgeToDummyNodes = new Map();
+ this.graphManager = new LGraphManager(this);
+ this.isLayoutFinished = false;
+ this.isSubLayout = false;
+ this.isRemoteUse = false;
+
+ if (isRemoteUse != null) {
+ this.isRemoteUse = isRemoteUse;
+ }
+}
+
+Layout.RANDOM_SEED = 1;
+
+Layout.prototype = Object.create(Emitter.prototype);
+
+Layout.prototype.getGraphManager = function () {
+ return this.graphManager;
+};
+
+Layout.prototype.getAllNodes = function () {
+ return this.graphManager.getAllNodes();
+};
+
+Layout.prototype.getAllEdges = function () {
+ return this.graphManager.getAllEdges();
+};
+
+Layout.prototype.getAllNodesToApplyGravitation = function () {
+ return this.graphManager.getAllNodesToApplyGravitation();
+};
+
+Layout.prototype.newGraphManager = function () {
+ var gm = new LGraphManager(this);
+ this.graphManager = gm;
+ return gm;
+};
+
+Layout.prototype.newGraph = function (vGraph) {
+ return new LGraph(null, this.graphManager, vGraph);
+};
+
+Layout.prototype.newNode = function (vNode) {
+ return new LNode(this.graphManager, vNode);
+};
+
+Layout.prototype.newEdge = function (vEdge) {
+ return new LEdge(null, null, vEdge);
+};
+
+Layout.prototype.checkLayoutSuccess = function () {
+ return this.graphManager.getRoot() == null || this.graphManager.getRoot().getNodes().length == 0 || this.graphManager.includesInvalidEdge();
+};
+
+Layout.prototype.runLayout = function () {
+ this.isLayoutFinished = false;
+
+ if (this.tilingPreLayout) {
+ this.tilingPreLayout();
+ }
+
+ this.initParameters();
+ var isLayoutSuccessfull;
+
+ if (this.checkLayoutSuccess()) {
+ isLayoutSuccessfull = false;
+ } else {
+ isLayoutSuccessfull = this.layout();
+ }
+
+ if (LayoutConstants.ANIMATE === 'during') {
+ // If this is a 'during' layout animation. Layout is not finished yet.
+ // We need to perform these in index.js when layout is really finished.
+ return false;
+ }
+
+ if (isLayoutSuccessfull) {
+ if (!this.isSubLayout) {
+ this.doPostLayout();
+ }
+ }
+
+ if (this.tilingPostLayout) {
+ this.tilingPostLayout();
+ }
+
+ this.isLayoutFinished = true;
+
+ return isLayoutSuccessfull;
+};
+
+/**
+ * This method performs the operations required after layout.
+ */
+Layout.prototype.doPostLayout = function () {
+ //assert !isSubLayout : "Should not be called on sub-layout!";
+ // Propagate geometric changes to v-level objects
+ if (!this.incremental) {
+ this.transform();
+ }
+ this.update();
+};
+
+/**
+ * This method updates the geometry of the target graph according to
+ * calculated layout.
+ */
+Layout.prototype.update2 = function () {
+ // update bend points
+ if (this.createBendsAsNeeded) {
+ this.createBendpointsFromDummyNodes();
+
+ // reset all edges, since the topology has changed
+ this.graphManager.resetAllEdges();
+ }
+
+ // perform edge, node and root updates if layout is not called
+ // remotely
+ if (!this.isRemoteUse) {
+ // update all edges
+ var edge;
+ var allEdges = this.graphManager.getAllEdges();
+ for (var i = 0; i < allEdges.length; i++) {
+ edge = allEdges[i];
+ // this.update(edge);
+ }
+
+ // recursively update nodes
+ var node;
+ var nodes = this.graphManager.getRoot().getNodes();
+ for (var i = 0; i < nodes.length; i++) {
+ node = nodes[i];
+ // this.update(node);
+ }
+
+ // update root graph
+ this.update(this.graphManager.getRoot());
+ }
+};
+
+Layout.prototype.update = function (obj) {
+ if (obj == null) {
+ this.update2();
+ } else if (obj instanceof LNode) {
+ var node = obj;
+ if (node.getChild() != null) {
+ // since node is compound, recursively update child nodes
+ var nodes = node.getChild().getNodes();
+ for (var i = 0; i < nodes.length; i++) {
+ update(nodes[i]);
+ }
+ }
+
+ // if the l-level node is associated with a v-level graph object,
+ // then it is assumed that the v-level node implements the
+ // interface Updatable.
+ if (node.vGraphObject != null) {
+ // cast to Updatable without any type check
+ var vNode = node.vGraphObject;
+
+ // call the update method of the interface
+ vNode.update(node);
+ }
+ } else if (obj instanceof LEdge) {
+ var edge = obj;
+ // if the l-level edge is associated with a v-level graph object,
+ // then it is assumed that the v-level edge implements the
+ // interface Updatable.
+
+ if (edge.vGraphObject != null) {
+ // cast to Updatable without any type check
+ var vEdge = edge.vGraphObject;
+
+ // call the update method of the interface
+ vEdge.update(edge);
+ }
+ } else if (obj instanceof LGraph) {
+ var graph = obj;
+ // if the l-level graph is associated with a v-level graph object,
+ // then it is assumed that the v-level object implements the
+ // interface Updatable.
+
+ if (graph.vGraphObject != null) {
+ // cast to Updatable without any type check
+ var vGraph = graph.vGraphObject;
+
+ // call the update method of the interface
+ vGraph.update(graph);
+ }
+ }
+};
+
+/**
+ * This method is used to set all layout parameters to default values
+ * determined at compile time.
+ */
+Layout.prototype.initParameters = function () {
+ if (!this.isSubLayout) {
+ this.layoutQuality = LayoutConstants.QUALITY;
+ this.animationDuringLayout = LayoutConstants.DEFAULT_ANIMATION_DURING_LAYOUT;
+ this.animationPeriod = LayoutConstants.DEFAULT_ANIMATION_PERIOD;
+ this.animationOnLayout = LayoutConstants.DEFAULT_ANIMATION_ON_LAYOUT;
+ this.incremental = LayoutConstants.DEFAULT_INCREMENTAL;
+ this.createBendsAsNeeded = LayoutConstants.DEFAULT_CREATE_BENDS_AS_NEEDED;
+ this.uniformLeafNodeSizes = LayoutConstants.DEFAULT_UNIFORM_LEAF_NODE_SIZES;
+ }
+
+ if (this.animationDuringLayout) {
+ this.animationOnLayout = false;
+ }
+};
+
+Layout.prototype.transform = function (newLeftTop) {
+ if (newLeftTop == undefined) {
+ this.transform(new PointD(0, 0));
+ } else {
+ // create a transformation object (from Eclipse to layout). When an
+ // inverse transform is applied, we get upper-left coordinate of the
+ // drawing or the root graph at given input coordinate (some margins
+ // already included in calculation of left-top).
+
+ var trans = new Transform();
+ var leftTop = this.graphManager.getRoot().updateLeftTop();
+
+ if (leftTop != null) {
+ trans.setWorldOrgX(newLeftTop.x);
+ trans.setWorldOrgY(newLeftTop.y);
+
+ trans.setDeviceOrgX(leftTop.x);
+ trans.setDeviceOrgY(leftTop.y);
+
+ var nodes = this.getAllNodes();
+ var node;
+
+ for (var i = 0; i < nodes.length; i++) {
+ node = nodes[i];
+ node.transform(trans);
+ }
+ }
+ }
+};
+
+Layout.prototype.positionNodesRandomly = function (graph) {
+
+ if (graph == undefined) {
+ //assert !this.incremental;
+ this.positionNodesRandomly(this.getGraphManager().getRoot());
+ this.getGraphManager().getRoot().updateBounds(true);
+ } else {
+ var lNode;
+ var childGraph;
+
+ var nodes = graph.getNodes();
+ for (var i = 0; i < nodes.length; i++) {
+ lNode = nodes[i];
+ childGraph = lNode.getChild();
+
+ if (childGraph == null) {
+ lNode.scatter();
+ } else if (childGraph.getNodes().length == 0) {
+ lNode.scatter();
+ } else {
+ this.positionNodesRandomly(childGraph);
+ lNode.updateBounds();
+ }
+ }
+ }
+};
+
+/**
+ * This method returns a list of trees where each tree is represented as a
+ * list of l-nodes. The method returns a list of size 0 when:
+ * - The graph is not flat or
+ * - One of the component(s) of the graph is not a tree.
+ */
+Layout.prototype.getFlatForest = function () {
+ var flatForest = [];
+ var isForest = true;
+
+ // Quick reference for all nodes in the graph manager associated with
+ // this layout. The list should not be changed.
+ var allNodes = this.graphManager.getRoot().getNodes();
+
+ // First be sure that the graph is flat
+ var isFlat = true;
+
+ for (var i = 0; i < allNodes.length; i++) {
+ if (allNodes[i].getChild() != null) {
+ isFlat = false;
+ }
+ }
+
+ // Return empty forest if the graph is not flat.
+ if (!isFlat) {
+ return flatForest;
+ }
+
+ // Run BFS for each component of the graph.
+
+ var visited = new Set();
+ var toBeVisited = [];
+ var parents = new Map();
+ var unProcessedNodes = [];
+
+ unProcessedNodes = unProcessedNodes.concat(allNodes);
+
+ // Each iteration of this loop finds a component of the graph and
+ // decides whether it is a tree or not. If it is a tree, adds it to the
+ // forest and continued with the next component.
+
+ while (unProcessedNodes.length > 0 && isForest) {
+ toBeVisited.push(unProcessedNodes[0]);
+
+ // Start the BFS. Each iteration of this loop visits a node in a
+ // BFS manner.
+ while (toBeVisited.length > 0 && isForest) {
+ //pool operation
+ var currentNode = toBeVisited[0];
+ toBeVisited.splice(0, 1);
+ visited.add(currentNode);
+
+ // Traverse all neighbors of this node
+ var neighborEdges = currentNode.getEdges();
+
+ for (var i = 0; i < neighborEdges.length; i++) {
+ var currentNeighbor = neighborEdges[i].getOtherEnd(currentNode);
+
+ // If BFS is not growing from this neighbor.
+ if (parents.get(currentNode) != currentNeighbor) {
+ // We haven't previously visited this neighbor.
+ if (!visited.has(currentNeighbor)) {
+ toBeVisited.push(currentNeighbor);
+ parents.set(currentNeighbor, currentNode);
+ }
+ // Since we have previously visited this neighbor and
+ // this neighbor is not parent of currentNode, given
+ // graph contains a component that is not tree, hence
+ // it is not a forest.
+ else {
+ isForest = false;
+ break;
+ }
+ }
+ }
+ }
+
+ // The graph contains a component that is not a tree. Empty
+ // previously found trees. The method will end.
+ if (!isForest) {
+ flatForest = [];
+ }
+ // Save currently visited nodes as a tree in our forest. Reset
+ // visited and parents lists. Continue with the next component of
+ // the graph, if any.
+ else {
+ var temp = [].concat(_toConsumableArray(visited));
+ flatForest.push(temp);
+ //flatForest = flatForest.concat(temp);
+ //unProcessedNodes.removeAll(visited);
+ for (var i = 0; i < temp.length; i++) {
+ var value = temp[i];
+ var index = unProcessedNodes.indexOf(value);
+ if (index > -1) {
+ unProcessedNodes.splice(index, 1);
+ }
+ }
+ visited = new Set();
+ parents = new Map();
+ }
+ }
+
+ return flatForest;
+};
+
+/**
+ * This method creates dummy nodes (an l-level node with minimal dimensions)
+ * for the given edge (one per bendpoint). The existing l-level structure
+ * is updated accordingly.
+ */
+Layout.prototype.createDummyNodesForBendpoints = function (edge) {
+ var dummyNodes = [];
+ var prev = edge.source;
+
+ var graph = this.graphManager.calcLowestCommonAncestor(edge.source, edge.target);
+
+ for (var i = 0; i < edge.bendpoints.length; i++) {
+ // create new dummy node
+ var dummyNode = this.newNode(null);
+ dummyNode.setRect(new Point(0, 0), new Dimension(1, 1));
+
+ graph.add(dummyNode);
+
+ // create new dummy edge between prev and dummy node
+ var dummyEdge = this.newEdge(null);
+ this.graphManager.add(dummyEdge, prev, dummyNode);
+
+ dummyNodes.add(dummyNode);
+ prev = dummyNode;
+ }
+
+ var dummyEdge = this.newEdge(null);
+ this.graphManager.add(dummyEdge, prev, edge.target);
+
+ this.edgeToDummyNodes.set(edge, dummyNodes);
+
+ // remove real edge from graph manager if it is inter-graph
+ if (edge.isInterGraph()) {
+ this.graphManager.remove(edge);
+ }
+ // else, remove the edge from the current graph
+ else {
+ graph.remove(edge);
+ }
+
+ return dummyNodes;
+};
+
+/**
+ * This method creates bendpoints for edges from the dummy nodes
+ * at l-level.
+ */
+Layout.prototype.createBendpointsFromDummyNodes = function () {
+ var edges = [];
+ edges = edges.concat(this.graphManager.getAllEdges());
+ edges = [].concat(_toConsumableArray(this.edgeToDummyNodes.keys())).concat(edges);
+
+ for (var k = 0; k < edges.length; k++) {
+ var lEdge = edges[k];
+
+ if (lEdge.bendpoints.length > 0) {
+ var path = this.edgeToDummyNodes.get(lEdge);
+
+ for (var i = 0; i < path.length; i++) {
+ var dummyNode = path[i];
+ var p = new PointD(dummyNode.getCenterX(), dummyNode.getCenterY());
+
+ // update bendpoint's location according to dummy node
+ var ebp = lEdge.bendpoints.get(i);
+ ebp.x = p.x;
+ ebp.y = p.y;
+
+ // remove the dummy node, dummy edges incident with this
+ // dummy node is also removed (within the remove method)
+ dummyNode.getOwner().remove(dummyNode);
+ }
+
+ // add the real edge to graph
+ this.graphManager.add(lEdge, lEdge.source, lEdge.target);
+ }
+ }
+};
+
+Layout.transform = function (sliderValue, defaultValue, minDiv, maxMul) {
+ if (minDiv != undefined && maxMul != undefined) {
+ var value = defaultValue;
+
+ if (sliderValue <= 50) {
+ var minValue = defaultValue / minDiv;
+ value -= (defaultValue - minValue) / 50 * (50 - sliderValue);
+ } else {
+ var maxValue = defaultValue * maxMul;
+ value += (maxValue - defaultValue) / 50 * (sliderValue - 50);
+ }
+
+ return value;
+ } else {
+ var a, b;
+
+ if (sliderValue <= 50) {
+ a = 9.0 * defaultValue / 500.0;
+ b = defaultValue / 10.0;
+ } else {
+ a = 9.0 * defaultValue / 50.0;
+ b = -8 * defaultValue;
+ }
+
+ return a * sliderValue + b;
+ }
+};
+
+/**
+ * This method finds and returns the center of the given nodes, assuming
+ * that the given nodes form a tree in themselves.
+ */
+Layout.findCenterOfTree = function (nodes) {
+ var list = [];
+ list = list.concat(nodes);
+
+ var removedNodes = [];
+ var remainingDegrees = new Map();
+ var foundCenter = false;
+ var centerNode = null;
+
+ if (list.length == 1 || list.length == 2) {
+ foundCenter = true;
+ centerNode = list[0];
+ }
+
+ for (var i = 0; i < list.length; i++) {
+ var node = list[i];
+ var degree = node.getNeighborsList().size;
+ remainingDegrees.set(node, node.getNeighborsList().size);
+
+ if (degree == 1) {
+ removedNodes.push(node);
+ }
+ }
+
+ var tempList = [];
+ tempList = tempList.concat(removedNodes);
+
+ while (!foundCenter) {
+ var tempList2 = [];
+ tempList2 = tempList2.concat(tempList);
+ tempList = [];
+
+ for (var i = 0; i < list.length; i++) {
+ var node = list[i];
+
+ var index = list.indexOf(node);
+ if (index >= 0) {
+ list.splice(index, 1);
+ }
+
+ var neighbours = node.getNeighborsList();
+
+ neighbours.forEach(function (neighbour) {
+ if (removedNodes.indexOf(neighbour) < 0) {
+ var otherDegree = remainingDegrees.get(neighbour);
+ var newDegree = otherDegree - 1;
+
+ if (newDegree == 1) {
+ tempList.push(neighbour);
+ }
+
+ remainingDegrees.set(neighbour, newDegree);
+ }
+ });
+ }
+
+ removedNodes = removedNodes.concat(tempList);
+
+ if (list.length == 1 || list.length == 2) {
+ foundCenter = true;
+ centerNode = list[0];
+ }
+ }
+
+ return centerNode;
+};
+
+/**
+ * During the coarsening process, this layout may be referenced by two graph managers
+ * this setter function grants access to change the currently being used graph manager
+ */
+Layout.prototype.setGraphManager = function (gm) {
+ this.graphManager = gm;
+};
+
+module.exports = Layout;
+
+/***/ }),
+/* 16 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+function RandomSeed() {}
+// adapted from: https://stackoverflow.com/a/19303725
+RandomSeed.seed = 1;
+RandomSeed.x = 0;
+
+RandomSeed.nextDouble = function () {
+ RandomSeed.x = Math.sin(RandomSeed.seed++) * 10000;
+ return RandomSeed.x - Math.floor(RandomSeed.x);
+};
+
+module.exports = RandomSeed;
+
+/***/ }),
+/* 17 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+var PointD = __webpack_require__(5);
+
+function Transform(x, y) {
+ this.lworldOrgX = 0.0;
+ this.lworldOrgY = 0.0;
+ this.ldeviceOrgX = 0.0;
+ this.ldeviceOrgY = 0.0;
+ this.lworldExtX = 1.0;
+ this.lworldExtY = 1.0;
+ this.ldeviceExtX = 1.0;
+ this.ldeviceExtY = 1.0;
+}
+
+Transform.prototype.getWorldOrgX = function () {
+ return this.lworldOrgX;
+};
+
+Transform.prototype.setWorldOrgX = function (wox) {
+ this.lworldOrgX = wox;
+};
+
+Transform.prototype.getWorldOrgY = function () {
+ return this.lworldOrgY;
+};
+
+Transform.prototype.setWorldOrgY = function (woy) {
+ this.lworldOrgY = woy;
+};
+
+Transform.prototype.getWorldExtX = function () {
+ return this.lworldExtX;
+};
+
+Transform.prototype.setWorldExtX = function (wex) {
+ this.lworldExtX = wex;
+};
+
+Transform.prototype.getWorldExtY = function () {
+ return this.lworldExtY;
+};
+
+Transform.prototype.setWorldExtY = function (wey) {
+ this.lworldExtY = wey;
+};
+
+/* Device related */
+
+Transform.prototype.getDeviceOrgX = function () {
+ return this.ldeviceOrgX;
+};
+
+Transform.prototype.setDeviceOrgX = function (dox) {
+ this.ldeviceOrgX = dox;
+};
+
+Transform.prototype.getDeviceOrgY = function () {
+ return this.ldeviceOrgY;
+};
+
+Transform.prototype.setDeviceOrgY = function (doy) {
+ this.ldeviceOrgY = doy;
+};
+
+Transform.prototype.getDeviceExtX = function () {
+ return this.ldeviceExtX;
+};
+
+Transform.prototype.setDeviceExtX = function (dex) {
+ this.ldeviceExtX = dex;
+};
+
+Transform.prototype.getDeviceExtY = function () {
+ return this.ldeviceExtY;
+};
+
+Transform.prototype.setDeviceExtY = function (dey) {
+ this.ldeviceExtY = dey;
+};
+
+Transform.prototype.transformX = function (x) {
+ var xDevice = 0.0;
+ var worldExtX = this.lworldExtX;
+ if (worldExtX != 0.0) {
+ xDevice = this.ldeviceOrgX + (x - this.lworldOrgX) * this.ldeviceExtX / worldExtX;
+ }
+
+ return xDevice;
+};
+
+Transform.prototype.transformY = function (y) {
+ var yDevice = 0.0;
+ var worldExtY = this.lworldExtY;
+ if (worldExtY != 0.0) {
+ yDevice = this.ldeviceOrgY + (y - this.lworldOrgY) * this.ldeviceExtY / worldExtY;
+ }
+
+ return yDevice;
+};
+
+Transform.prototype.inverseTransformX = function (x) {
+ var xWorld = 0.0;
+ var deviceExtX = this.ldeviceExtX;
+ if (deviceExtX != 0.0) {
+ xWorld = this.lworldOrgX + (x - this.ldeviceOrgX) * this.lworldExtX / deviceExtX;
+ }
+
+ return xWorld;
+};
+
+Transform.prototype.inverseTransformY = function (y) {
+ var yWorld = 0.0;
+ var deviceExtY = this.ldeviceExtY;
+ if (deviceExtY != 0.0) {
+ yWorld = this.lworldOrgY + (y - this.ldeviceOrgY) * this.lworldExtY / deviceExtY;
+ }
+ return yWorld;
+};
+
+Transform.prototype.inverseTransformPoint = function (inPoint) {
+ var outPoint = new PointD(this.inverseTransformX(inPoint.x), this.inverseTransformY(inPoint.y));
+ return outPoint;
+};
+
+module.exports = Transform;
+
+/***/ }),
+/* 18 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
+
+var Layout = __webpack_require__(15);
+var FDLayoutConstants = __webpack_require__(4);
+var LayoutConstants = __webpack_require__(0);
+var IGeometry = __webpack_require__(8);
+var IMath = __webpack_require__(9);
+
+function FDLayout() {
+ Layout.call(this);
+
+ this.useSmartIdealEdgeLengthCalculation = FDLayoutConstants.DEFAULT_USE_SMART_IDEAL_EDGE_LENGTH_CALCULATION;
+ this.gravityConstant = FDLayoutConstants.DEFAULT_GRAVITY_STRENGTH;
+ this.compoundGravityConstant = FDLayoutConstants.DEFAULT_COMPOUND_GRAVITY_STRENGTH;
+ this.gravityRangeFactor = FDLayoutConstants.DEFAULT_GRAVITY_RANGE_FACTOR;
+ this.compoundGravityRangeFactor = FDLayoutConstants.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR;
+ this.displacementThresholdPerNode = 3.0 * FDLayoutConstants.DEFAULT_EDGE_LENGTH / 100;
+ this.coolingFactor = FDLayoutConstants.DEFAULT_COOLING_FACTOR_INCREMENTAL;
+ this.initialCoolingFactor = FDLayoutConstants.DEFAULT_COOLING_FACTOR_INCREMENTAL;
+ this.totalDisplacement = 0.0;
+ this.oldTotalDisplacement = 0.0;
+ this.maxIterations = FDLayoutConstants.MAX_ITERATIONS;
+}
+
+FDLayout.prototype = Object.create(Layout.prototype);
+
+for (var prop in Layout) {
+ FDLayout[prop] = Layout[prop];
+}
+
+FDLayout.prototype.initParameters = function () {
+ Layout.prototype.initParameters.call(this, arguments);
+
+ this.totalIterations = 0;
+ this.notAnimatedIterations = 0;
+
+ this.useFRGridVariant = FDLayoutConstants.DEFAULT_USE_SMART_REPULSION_RANGE_CALCULATION;
+
+ this.grid = [];
+};
+
+FDLayout.prototype.calcIdealEdgeLengths = function () {
+ var edge;
+ var originalIdealLength;
+ var lcaDepth;
+ var source;
+ var target;
+ var sizeOfSourceInLca;
+ var sizeOfTargetInLca;
+
+ var allEdges = this.getGraphManager().getAllEdges();
+ for (var i = 0; i < allEdges.length; i++) {
+ edge = allEdges[i];
+
+ originalIdealLength = edge.idealLength;
+
+ if (edge.isInterGraph) {
+ source = edge.getSource();
+ target = edge.getTarget();
+
+ sizeOfSourceInLca = edge.getSourceInLca().getEstimatedSize();
+ sizeOfTargetInLca = edge.getTargetInLca().getEstimatedSize();
+
+ if (this.useSmartIdealEdgeLengthCalculation) {
+ edge.idealLength += sizeOfSourceInLca + sizeOfTargetInLca - 2 * LayoutConstants.SIMPLE_NODE_SIZE;
+ }
+
+ lcaDepth = edge.getLca().getInclusionTreeDepth();
+
+ edge.idealLength += originalIdealLength * FDLayoutConstants.PER_LEVEL_IDEAL_EDGE_LENGTH_FACTOR * (source.getInclusionTreeDepth() + target.getInclusionTreeDepth() - 2 * lcaDepth);
+ }
+ }
+};
+
+FDLayout.prototype.initSpringEmbedder = function () {
+
+ var s = this.getAllNodes().length;
+ if (this.incremental) {
+ if (s > FDLayoutConstants.ADAPTATION_LOWER_NODE_LIMIT) {
+ this.coolingFactor = Math.max(this.coolingFactor * FDLayoutConstants.COOLING_ADAPTATION_FACTOR, this.coolingFactor - (s - FDLayoutConstants.ADAPTATION_LOWER_NODE_LIMIT) / (FDLayoutConstants.ADAPTATION_UPPER_NODE_LIMIT - FDLayoutConstants.ADAPTATION_LOWER_NODE_LIMIT) * this.coolingFactor * (1 - FDLayoutConstants.COOLING_ADAPTATION_FACTOR));
+ }
+ this.maxNodeDisplacement = FDLayoutConstants.MAX_NODE_DISPLACEMENT_INCREMENTAL;
+ } else {
+ if (s > FDLayoutConstants.ADAPTATION_LOWER_NODE_LIMIT) {
+ this.coolingFactor = Math.max(FDLayoutConstants.COOLING_ADAPTATION_FACTOR, 1.0 - (s - FDLayoutConstants.ADAPTATION_LOWER_NODE_LIMIT) / (FDLayoutConstants.ADAPTATION_UPPER_NODE_LIMIT - FDLayoutConstants.ADAPTATION_LOWER_NODE_LIMIT) * (1 - FDLayoutConstants.COOLING_ADAPTATION_FACTOR));
+ } else {
+ this.coolingFactor = 1.0;
+ }
+ this.initialCoolingFactor = this.coolingFactor;
+ this.maxNodeDisplacement = FDLayoutConstants.MAX_NODE_DISPLACEMENT;
+ }
+
+ this.maxIterations = Math.max(this.getAllNodes().length * 5, this.maxIterations);
+
+ // Reassign this attribute by using new constant value
+ this.displacementThresholdPerNode = 3.0 * FDLayoutConstants.DEFAULT_EDGE_LENGTH / 100;
+ this.totalDisplacementThreshold = this.displacementThresholdPerNode * this.getAllNodes().length;
+
+ this.repulsionRange = this.calcRepulsionRange();
+};
+
+FDLayout.prototype.calcSpringForces = function () {
+ var lEdges = this.getAllEdges();
+ var edge;
+
+ for (var i = 0; i < lEdges.length; i++) {
+ edge = lEdges[i];
+
+ this.calcSpringForce(edge, edge.idealLength);
+ }
+};
+
+FDLayout.prototype.calcRepulsionForces = function () {
+ var gridUpdateAllowed = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
+ var forceToNodeSurroundingUpdate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
+
+ var i, j;
+ var nodeA, nodeB;
+ var lNodes = this.getAllNodes();
+ var processedNodeSet;
+
+ if (this.useFRGridVariant) {
+ if (this.totalIterations % FDLayoutConstants.GRID_CALCULATION_CHECK_PERIOD == 1 && gridUpdateAllowed) {
+ this.updateGrid();
+ }
+
+ processedNodeSet = new Set();
+
+ // calculate repulsion forces between each nodes and its surrounding
+ for (i = 0; i < lNodes.length; i++) {
+ nodeA = lNodes[i];
+ this.calculateRepulsionForceOfANode(nodeA, processedNodeSet, gridUpdateAllowed, forceToNodeSurroundingUpdate);
+ processedNodeSet.add(nodeA);
+ }
+ } else {
+ for (i = 0; i < lNodes.length; i++) {
+ nodeA = lNodes[i];
+
+ for (j = i + 1; j < lNodes.length; j++) {
+ nodeB = lNodes[j];
+
+ // If both nodes are not members of the same graph, skip.
+ if (nodeA.getOwner() != nodeB.getOwner()) {
+ continue;
+ }
+
+ this.calcRepulsionForce(nodeA, nodeB);
+ }
+ }
+ }
+};
+
+FDLayout.prototype.calcGravitationalForces = function () {
+ var node;
+ var lNodes = this.getAllNodesToApplyGravitation();
+
+ for (var i = 0; i < lNodes.length; i++) {
+ node = lNodes[i];
+ this.calcGravitationalForce(node);
+ }
+};
+
+FDLayout.prototype.moveNodes = function () {
+ var lNodes = this.getAllNodes();
+ var node;
+
+ for (var i = 0; i < lNodes.length; i++) {
+ node = lNodes[i];
+ node.move();
+ }
+};
+
+FDLayout.prototype.calcSpringForce = function (edge, idealLength) {
+ var sourceNode = edge.getSource();
+ var targetNode = edge.getTarget();
+
+ var length;
+ var springForce;
+ var springForceX;
+ var springForceY;
+
+ // Update edge length
+ if (this.uniformLeafNodeSizes && sourceNode.getChild() == null && targetNode.getChild() == null) {
+ edge.updateLengthSimple();
+ } else {
+ edge.updateLength();
+
+ if (edge.isOverlapingSourceAndTarget) {
+ return;
+ }
+ }
+
+ length = edge.getLength();
+
+ if (length == 0) return;
+
+ // Calculate spring forces
+ springForce = edge.edgeElasticity * (length - idealLength);
+
+ // Project force onto x and y axes
+ springForceX = springForce * (edge.lengthX / length);
+ springForceY = springForce * (edge.lengthY / length);
+
+ // Apply forces on the end nodes
+ sourceNode.springForceX += springForceX;
+ sourceNode.springForceY += springForceY;
+ targetNode.springForceX -= springForceX;
+ targetNode.springForceY -= springForceY;
+};
+
+FDLayout.prototype.calcRepulsionForce = function (nodeA, nodeB) {
+ var rectA = nodeA.getRect();
+ var rectB = nodeB.getRect();
+ var overlapAmount = new Array(2);
+ var clipPoints = new Array(4);
+ var distanceX;
+ var distanceY;
+ var distanceSquared;
+ var distance;
+ var repulsionForce;
+ var repulsionForceX;
+ var repulsionForceY;
+
+ if (rectA.intersects(rectB)) // two nodes overlap
+ {
+ // calculate separation amount in x and y directions
+ IGeometry.calcSeparationAmount(rectA, rectB, overlapAmount, FDLayoutConstants.DEFAULT_EDGE_LENGTH / 2.0);
+
+ repulsionForceX = 2 * overlapAmount[0];
+ repulsionForceY = 2 * overlapAmount[1];
+
+ var childrenConstant = nodeA.noOfChildren * nodeB.noOfChildren / (nodeA.noOfChildren + nodeB.noOfChildren);
+
+ // Apply forces on the two nodes
+ nodeA.repulsionForceX -= childrenConstant * repulsionForceX;
+ nodeA.repulsionForceY -= childrenConstant * repulsionForceY;
+ nodeB.repulsionForceX += childrenConstant * repulsionForceX;
+ nodeB.repulsionForceY += childrenConstant * repulsionForceY;
+ } else // no overlap
+ {
+ // calculate distance
+
+ if (this.uniformLeafNodeSizes && nodeA.getChild() == null && nodeB.getChild() == null) // simply base repulsion on distance of node centers
+ {
+ distanceX = rectB.getCenterX() - rectA.getCenterX();
+ distanceY = rectB.getCenterY() - rectA.getCenterY();
+ } else // use clipping points
+ {
+ IGeometry.getIntersection(rectA, rectB, clipPoints);
+
+ distanceX = clipPoints[2] - clipPoints[0];
+ distanceY = clipPoints[3] - clipPoints[1];
+ }
+
+ // No repulsion range. FR grid variant should take care of this.
+ if (Math.abs(distanceX) < FDLayoutConstants.MIN_REPULSION_DIST) {
+ distanceX = IMath.sign(distanceX) * FDLayoutConstants.MIN_REPULSION_DIST;
+ }
+
+ if (Math.abs(distanceY) < FDLayoutConstants.MIN_REPULSION_DIST) {
+ distanceY = IMath.sign(distanceY) * FDLayoutConstants.MIN_REPULSION_DIST;
+ }
+
+ distanceSquared = distanceX * distanceX + distanceY * distanceY;
+ distance = Math.sqrt(distanceSquared);
+
+ // Here we use half of the nodes' repulsion values for backward compatibility
+ repulsionForce = (nodeA.nodeRepulsion / 2 + nodeB.nodeRepulsion / 2) * nodeA.noOfChildren * nodeB.noOfChildren / distanceSquared;
+
+ // Project force onto x and y axes
+ repulsionForceX = repulsionForce * distanceX / distance;
+ repulsionForceY = repulsionForce * distanceY / distance;
+
+ // Apply forces on the two nodes
+ nodeA.repulsionForceX -= repulsionForceX;
+ nodeA.repulsionForceY -= repulsionForceY;
+ nodeB.repulsionForceX += repulsionForceX;
+ nodeB.repulsionForceY += repulsionForceY;
+ }
+};
+
+FDLayout.prototype.calcGravitationalForce = function (node) {
+ var ownerGraph;
+ var ownerCenterX;
+ var ownerCenterY;
+ var distanceX;
+ var distanceY;
+ var absDistanceX;
+ var absDistanceY;
+ var estimatedSize;
+ ownerGraph = node.getOwner();
+
+ ownerCenterX = (ownerGraph.getRight() + ownerGraph.getLeft()) / 2;
+ ownerCenterY = (ownerGraph.getTop() + ownerGraph.getBottom()) / 2;
+ distanceX = node.getCenterX() - ownerCenterX;
+ distanceY = node.getCenterY() - ownerCenterY;
+ absDistanceX = Math.abs(distanceX) + node.getWidth() / 2;
+ absDistanceY = Math.abs(distanceY) + node.getHeight() / 2;
+
+ if (node.getOwner() == this.graphManager.getRoot()) // in the root graph
+ {
+ estimatedSize = ownerGraph.getEstimatedSize() * this.gravityRangeFactor;
+
+ if (absDistanceX > estimatedSize || absDistanceY > estimatedSize) {
+ node.gravitationForceX = -this.gravityConstant * distanceX;
+ node.gravitationForceY = -this.gravityConstant * distanceY;
+ }
+ } else // inside a compound
+ {
+ estimatedSize = ownerGraph.getEstimatedSize() * this.compoundGravityRangeFactor;
+
+ if (absDistanceX > estimatedSize || absDistanceY > estimatedSize) {
+ node.gravitationForceX = -this.gravityConstant * distanceX * this.compoundGravityConstant;
+ node.gravitationForceY = -this.gravityConstant * distanceY * this.compoundGravityConstant;
+ }
+ }
+};
+
+FDLayout.prototype.isConverged = function () {
+ var converged;
+ var oscilating = false;
+
+ if (this.totalIterations > this.maxIterations / 3) {
+ oscilating = Math.abs(this.totalDisplacement - this.oldTotalDisplacement) < 2;
+ }
+
+ converged = this.totalDisplacement < this.totalDisplacementThreshold;
+
+ this.oldTotalDisplacement = this.totalDisplacement;
+
+ return converged || oscilating;
+};
+
+FDLayout.prototype.animate = function () {
+ if (this.animationDuringLayout && !this.isSubLayout) {
+ if (this.notAnimatedIterations == this.animationPeriod) {
+ this.update();
+ this.notAnimatedIterations = 0;
+ } else {
+ this.notAnimatedIterations++;
+ }
+ }
+};
+
+//This method calculates the number of children (weight) for all nodes
+FDLayout.prototype.calcNoOfChildrenForAllNodes = function () {
+ var node;
+ var allNodes = this.graphManager.getAllNodes();
+
+ for (var i = 0; i < allNodes.length; i++) {
+ node = allNodes[i];
+ node.noOfChildren = node.getNoOfChildren();
+ }
+};
+
+// -----------------------------------------------------------------------------
+// Section: FR-Grid Variant Repulsion Force Calculation
+// -----------------------------------------------------------------------------
+
+FDLayout.prototype.calcGrid = function (graph) {
+
+ var sizeX = 0;
+ var sizeY = 0;
+
+ sizeX = parseInt(Math.ceil((graph.getRight() - graph.getLeft()) / this.repulsionRange));
+ sizeY = parseInt(Math.ceil((graph.getBottom() - graph.getTop()) / this.repulsionRange));
+
+ var grid = new Array(sizeX);
+
+ for (var i = 0; i < sizeX; i++) {
+ grid[i] = new Array(sizeY);
+ }
+
+ for (var i = 0; i < sizeX; i++) {
+ for (var j = 0; j < sizeY; j++) {
+ grid[i][j] = new Array();
+ }
+ }
+
+ return grid;
+};
+
+FDLayout.prototype.addNodeToGrid = function (v, left, top) {
+
+ var startX = 0;
+ var finishX = 0;
+ var startY = 0;
+ var finishY = 0;
+
+ startX = parseInt(Math.floor((v.getRect().x - left) / this.repulsionRange));
+ finishX = parseInt(Math.floor((v.getRect().width + v.getRect().x - left) / this.repulsionRange));
+ startY = parseInt(Math.floor((v.getRect().y - top) / this.repulsionRange));
+ finishY = parseInt(Math.floor((v.getRect().height + v.getRect().y - top) / this.repulsionRange));
+
+ for (var i = startX; i <= finishX; i++) {
+ for (var j = startY; j <= finishY; j++) {
+ this.grid[i][j].push(v);
+ v.setGridCoordinates(startX, finishX, startY, finishY);
+ }
+ }
+};
+
+FDLayout.prototype.updateGrid = function () {
+ var i;
+ var nodeA;
+ var lNodes = this.getAllNodes();
+
+ this.grid = this.calcGrid(this.graphManager.getRoot());
+
+ // put all nodes to proper grid cells
+ for (i = 0; i < lNodes.length; i++) {
+ nodeA = lNodes[i];
+ this.addNodeToGrid(nodeA, this.graphManager.getRoot().getLeft(), this.graphManager.getRoot().getTop());
+ }
+};
+
+FDLayout.prototype.calculateRepulsionForceOfANode = function (nodeA, processedNodeSet, gridUpdateAllowed, forceToNodeSurroundingUpdate) {
+
+ if (this.totalIterations % FDLayoutConstants.GRID_CALCULATION_CHECK_PERIOD == 1 && gridUpdateAllowed || forceToNodeSurroundingUpdate) {
+ var surrounding = new Set();
+ nodeA.surrounding = new Array();
+ var nodeB;
+ var grid = this.grid;
+
+ for (var i = nodeA.startX - 1; i < nodeA.finishX + 2; i++) {
+ for (var j = nodeA.startY - 1; j < nodeA.finishY + 2; j++) {
+ if (!(i < 0 || j < 0 || i >= grid.length || j >= grid[0].length)) {
+ for (var k = 0; k < grid[i][j].length; k++) {
+ nodeB = grid[i][j][k];
+
+ // If both nodes are not members of the same graph,
+ // or both nodes are the same, skip.
+ if (nodeA.getOwner() != nodeB.getOwner() || nodeA == nodeB) {
+ continue;
+ }
+
+ // check if the repulsion force between
+ // nodeA and nodeB has already been calculated
+ if (!processedNodeSet.has(nodeB) && !surrounding.has(nodeB)) {
+ var distanceX = Math.abs(nodeA.getCenterX() - nodeB.getCenterX()) - (nodeA.getWidth() / 2 + nodeB.getWidth() / 2);
+ var distanceY = Math.abs(nodeA.getCenterY() - nodeB.getCenterY()) - (nodeA.getHeight() / 2 + nodeB.getHeight() / 2);
+
+ // if the distance between nodeA and nodeB
+ // is less then calculation range
+ if (distanceX <= this.repulsionRange && distanceY <= this.repulsionRange) {
+ //then add nodeB to surrounding of nodeA
+ surrounding.add(nodeB);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ nodeA.surrounding = [].concat(_toConsumableArray(surrounding));
+ }
+ for (i = 0; i < nodeA.surrounding.length; i++) {
+ this.calcRepulsionForce(nodeA, nodeA.surrounding[i]);
+ }
+};
+
+FDLayout.prototype.calcRepulsionRange = function () {
+ return 0.0;
+};
+
+module.exports = FDLayout;
+
+/***/ }),
+/* 19 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+var LEdge = __webpack_require__(1);
+var FDLayoutConstants = __webpack_require__(4);
+
+function FDLayoutEdge(source, target, vEdge) {
+ LEdge.call(this, source, target, vEdge);
+
+ // Ideal length and elasticity value for this edge
+ this.idealLength = FDLayoutConstants.DEFAULT_EDGE_LENGTH;
+ this.edgeElasticity = FDLayoutConstants.DEFAULT_SPRING_STRENGTH;
+}
+
+FDLayoutEdge.prototype = Object.create(LEdge.prototype);
+
+for (var prop in LEdge) {
+ FDLayoutEdge[prop] = LEdge[prop];
+}
+
+module.exports = FDLayoutEdge;
+
+/***/ }),
+/* 20 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+var LNode = __webpack_require__(3);
+var FDLayoutConstants = __webpack_require__(4);
+
+function FDLayoutNode(gm, loc, size, vNode) {
+ // alternative constructor is handled inside LNode
+ LNode.call(this, gm, loc, size, vNode);
+
+ // Repulsion value of this node
+ this.nodeRepulsion = FDLayoutConstants.DEFAULT_REPULSION_STRENGTH;
+
+ //Spring, repulsion and gravitational forces acting on this node
+ this.springForceX = 0;
+ this.springForceY = 0;
+ this.repulsionForceX = 0;
+ this.repulsionForceY = 0;
+ this.gravitationForceX = 0;
+ this.gravitationForceY = 0;
+ //Amount by which this node is to be moved in this iteration
+ this.displacementX = 0;
+ this.displacementY = 0;
+
+ //Start and finish grid coordinates that this node is fallen into
+ this.startX = 0;
+ this.finishX = 0;
+ this.startY = 0;
+ this.finishY = 0;
+
+ //Geometric neighbors of this node
+ this.surrounding = [];
+}
+
+FDLayoutNode.prototype = Object.create(LNode.prototype);
+
+for (var prop in LNode) {
+ FDLayoutNode[prop] = LNode[prop];
+}
+
+FDLayoutNode.prototype.setGridCoordinates = function (_startX, _finishX, _startY, _finishY) {
+ this.startX = _startX;
+ this.finishX = _finishX;
+ this.startY = _startY;
+ this.finishY = _finishY;
+};
+
+module.exports = FDLayoutNode;
+
+/***/ }),
+/* 21 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+function DimensionD(width, height) {
+ this.width = 0;
+ this.height = 0;
+ if (width !== null && height !== null) {
+ this.height = height;
+ this.width = width;
+ }
+}
+
+DimensionD.prototype.getWidth = function () {
+ return this.width;
+};
+
+DimensionD.prototype.setWidth = function (width) {
+ this.width = width;
+};
+
+DimensionD.prototype.getHeight = function () {
+ return this.height;
+};
+
+DimensionD.prototype.setHeight = function (height) {
+ this.height = height;
+};
+
+module.exports = DimensionD;
+
+/***/ }),
+/* 22 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+var UniqueIDGeneretor = __webpack_require__(14);
+
+function HashMap() {
+ this.map = {};
+ this.keys = [];
+}
+
+HashMap.prototype.put = function (key, value) {
+ var theId = UniqueIDGeneretor.createID(key);
+ if (!this.contains(theId)) {
+ this.map[theId] = value;
+ this.keys.push(key);
+ }
+};
+
+HashMap.prototype.contains = function (key) {
+ var theId = UniqueIDGeneretor.createID(key);
+ return this.map[key] != null;
+};
+
+HashMap.prototype.get = function (key) {
+ var theId = UniqueIDGeneretor.createID(key);
+ return this.map[theId];
+};
+
+HashMap.prototype.keySet = function () {
+ return this.keys;
+};
+
+module.exports = HashMap;
+
+/***/ }),
+/* 23 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+var UniqueIDGeneretor = __webpack_require__(14);
+
+function HashSet() {
+ this.set = {};
+}
+;
+
+HashSet.prototype.add = function (obj) {
+ var theId = UniqueIDGeneretor.createID(obj);
+ if (!this.contains(theId)) this.set[theId] = obj;
+};
+
+HashSet.prototype.remove = function (obj) {
+ delete this.set[UniqueIDGeneretor.createID(obj)];
+};
+
+HashSet.prototype.clear = function () {
+ this.set = {};
+};
+
+HashSet.prototype.contains = function (obj) {
+ return this.set[UniqueIDGeneretor.createID(obj)] == obj;
+};
+
+HashSet.prototype.isEmpty = function () {
+ return this.size() === 0;
+};
+
+HashSet.prototype.size = function () {
+ return Object.keys(this.set).length;
+};
+
+//concats this.set to the given list
+HashSet.prototype.addAllTo = function (list) {
+ var keys = Object.keys(this.set);
+ var length = keys.length;
+ for (var i = 0; i < length; i++) {
+ list.push(this.set[keys[i]]);
+ }
+};
+
+HashSet.prototype.size = function () {
+ return Object.keys(this.set).length;
+};
+
+HashSet.prototype.addAll = function (list) {
+ var s = list.length;
+ for (var i = 0; i < s; i++) {
+ var v = list[i];
+ this.add(v);
+ }
+};
+
+module.exports = HashSet;
+
+/***/ }),
+/* 24 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+// Some matrix (1d and 2d array) operations
+function Matrix() {}
+
+/**
+ * matrix multiplication
+ * array1, array2 and result are 2d arrays
+ */
+Matrix.multMat = function (array1, array2) {
+ var result = [];
+
+ for (var i = 0; i < array1.length; i++) {
+ result[i] = [];
+ for (var j = 0; j < array2[0].length; j++) {
+ result[i][j] = 0;
+ for (var k = 0; k < array1[0].length; k++) {
+ result[i][j] += array1[i][k] * array2[k][j];
+ }
+ }
+ }
+ return result;
+};
+
+/**
+ * matrix transpose
+ * array and result are 2d arrays
+ */
+Matrix.transpose = function (array) {
+ var result = [];
+
+ for (var i = 0; i < array[0].length; i++) {
+ result[i] = [];
+ for (var j = 0; j < array.length; j++) {
+ result[i][j] = array[j][i];
+ }
+ }
+
+ return result;
+};
+
+/**
+ * multiply array with constant
+ * array and result are 1d arrays
+ */
+Matrix.multCons = function (array, constant) {
+ var result = [];
+
+ for (var i = 0; i < array.length; i++) {
+ result[i] = array[i] * constant;
+ }
+
+ return result;
+};
+
+/**
+ * substract two arrays
+ * array1, array2 and result are 1d arrays
+ */
+Matrix.minusOp = function (array1, array2) {
+ var result = [];
+
+ for (var i = 0; i < array1.length; i++) {
+ result[i] = array1[i] - array2[i];
+ }
+
+ return result;
+};
+
+/**
+ * dot product of two arrays with same size
+ * array1 and array2 are 1d arrays
+ */
+Matrix.dotProduct = function (array1, array2) {
+ var product = 0;
+
+ for (var i = 0; i < array1.length; i++) {
+ product += array1[i] * array2[i];
+ }
+
+ return product;
+};
+
+/**
+ * magnitude of an array
+ * array is 1d array
+ */
+Matrix.mag = function (array) {
+ return Math.sqrt(this.dotProduct(array, array));
+};
+
+/**
+ * normalization of an array
+ * array and result are 1d array
+ */
+Matrix.normalize = function (array) {
+ var result = [];
+ var magnitude = this.mag(array);
+
+ for (var i = 0; i < array.length; i++) {
+ result[i] = array[i] / magnitude;
+ }
+
+ return result;
+};
+
+/**
+ * multiply an array with centering matrix
+ * array and result are 1d array
+ */
+Matrix.multGamma = function (array) {
+ var result = [];
+ var sum = 0;
+
+ for (var i = 0; i < array.length; i++) {
+ sum += array[i];
+ }
+
+ sum *= -1 / array.length;
+
+ for (var _i = 0; _i < array.length; _i++) {
+ result[_i] = sum + array[_i];
+ }
+ return result;
+};
+
+/**
+ * a special matrix multiplication
+ * result = 0.5 * C * INV * C^T * array
+ * array and result are 1d, C and INV are 2d arrays
+ */
+Matrix.multL = function (array, C, INV) {
+ var result = [];
+ var temp1 = [];
+ var temp2 = [];
+
+ // multiply by C^T
+ for (var i = 0; i < C[0].length; i++) {
+ var sum = 0;
+ for (var j = 0; j < C.length; j++) {
+ sum += -0.5 * C[j][i] * array[j];
+ }
+ temp1[i] = sum;
+ }
+ // multiply the result by INV
+ for (var _i2 = 0; _i2 < INV.length; _i2++) {
+ var _sum = 0;
+ for (var _j = 0; _j < INV.length; _j++) {
+ _sum += INV[_i2][_j] * temp1[_j];
+ }
+ temp2[_i2] = _sum;
+ }
+ // multiply the result by C
+ for (var _i3 = 0; _i3 < C.length; _i3++) {
+ var _sum2 = 0;
+ for (var _j2 = 0; _j2 < C[0].length; _j2++) {
+ _sum2 += C[_i3][_j2] * temp2[_j2];
+ }
+ result[_i3] = _sum2;
+ }
+
+ return result;
+};
+
+module.exports = Matrix;
+
+/***/ }),
+/* 25 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
+
+function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
+
+/**
+ * A classic Quicksort algorithm with Hoare's partition
+ * - Works also on LinkedList objects
+ *
+ * Copyright: i-Vis Research Group, Bilkent University, 2007 - present
+ */
+
+var LinkedList = __webpack_require__(11);
+
+var Quicksort = function () {
+ function Quicksort(A, compareFunction) {
+ _classCallCheck(this, Quicksort);
+
+ if (compareFunction !== null || compareFunction !== undefined) this.compareFunction = this._defaultCompareFunction;
+
+ var length = void 0;
+ if (A instanceof LinkedList) length = A.size();else length = A.length;
+
+ this._quicksort(A, 0, length - 1);
+ }
+
+ _createClass(Quicksort, [{
+ key: '_quicksort',
+ value: function _quicksort(A, p, r) {
+ if (p < r) {
+ var q = this._partition(A, p, r);
+ this._quicksort(A, p, q);
+ this._quicksort(A, q + 1, r);
+ }
+ }
+ }, {
+ key: '_partition',
+ value: function _partition(A, p, r) {
+ var x = this._get(A, p);
+ var i = p;
+ var j = r;
+ while (true) {
+ while (this.compareFunction(x, this._get(A, j))) {
+ j--;
+ }while (this.compareFunction(this._get(A, i), x)) {
+ i++;
+ }if (i < j) {
+ this._swap(A, i, j);
+ i++;
+ j--;
+ } else return j;
+ }
+ }
+ }, {
+ key: '_get',
+ value: function _get(object, index) {
+ if (object instanceof LinkedList) return object.get_object_at(index);else return object[index];
+ }
+ }, {
+ key: '_set',
+ value: function _set(object, index, value) {
+ if (object instanceof LinkedList) object.set_object_at(index, value);else object[index] = value;
+ }
+ }, {
+ key: '_swap',
+ value: function _swap(A, i, j) {
+ var temp = this._get(A, i);
+ this._set(A, i, this._get(A, j));
+ this._set(A, j, temp);
+ }
+ }, {
+ key: '_defaultCompareFunction',
+ value: function _defaultCompareFunction(a, b) {
+ return b > a;
+ }
+ }]);
+
+ return Quicksort;
+}();
+
+module.exports = Quicksort;
+
+/***/ }),
+/* 26 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+// Singular Value Decomposition implementation
+function SVD() {};
+
+/* Below singular value decomposition (svd) code including hypot function is adopted from https://github.com/dragonfly-ai/JamaJS
+ Some changes are applied to make the code compatible with the fcose code and to make it independent from Jama.
+ Input matrix is changed to a 2D array instead of Jama matrix. Matrix dimensions are taken according to 2D array instead of using Jama functions.
+ An object that includes singular value components is created for return.
+ The types of input parameters of the hypot function are removed.
+ let is used instead of var for the variable initialization.
+*/
+/*
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "{}"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright {yyyy} {name of copyright owner}
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+SVD.svd = function (A) {
+ this.U = null;
+ this.V = null;
+ this.s = null;
+ this.m = 0;
+ this.n = 0;
+ this.m = A.length;
+ this.n = A[0].length;
+ var nu = Math.min(this.m, this.n);
+ this.s = function (s) {
+ var a = [];
+ while (s-- > 0) {
+ a.push(0);
+ }return a;
+ }(Math.min(this.m + 1, this.n));
+ this.U = function (dims) {
+ var allocate = function allocate(dims) {
+ if (dims.length == 0) {
+ return 0;
+ } else {
+ var array = [];
+ for (var i = 0; i < dims[0]; i++) {
+ array.push(allocate(dims.slice(1)));
+ }
+ return array;
+ }
+ };
+ return allocate(dims);
+ }([this.m, nu]);
+ this.V = function (dims) {
+ var allocate = function allocate(dims) {
+ if (dims.length == 0) {
+ return 0;
+ } else {
+ var array = [];
+ for (var i = 0; i < dims[0]; i++) {
+ array.push(allocate(dims.slice(1)));
+ }
+ return array;
+ }
+ };
+ return allocate(dims);
+ }([this.n, this.n]);
+ var e = function (s) {
+ var a = [];
+ while (s-- > 0) {
+ a.push(0);
+ }return a;
+ }(this.n);
+ var work = function (s) {
+ var a = [];
+ while (s-- > 0) {
+ a.push(0);
+ }return a;
+ }(this.m);
+ var wantu = true;
+ var wantv = true;
+ var nct = Math.min(this.m - 1, this.n);
+ var nrt = Math.max(0, Math.min(this.n - 2, this.m));
+ for (var k = 0; k < Math.max(nct, nrt); k++) {
+ if (k < nct) {
+ this.s[k] = 0;
+ for (var i = k; i < this.m; i++) {
+ this.s[k] = SVD.hypot(this.s[k], A[i][k]);
+ }
+ ;
+ if (this.s[k] !== 0.0) {
+ if (A[k][k] < 0.0) {
+ this.s[k] = -this.s[k];
+ }
+ for (var _i = k; _i < this.m; _i++) {
+ A[_i][k] /= this.s[k];
+ }
+ ;
+ A[k][k] += 1.0;
+ }
+ this.s[k] = -this.s[k];
+ }
+ for (var j = k + 1; j < this.n; j++) {
+ if (function (lhs, rhs) {
+ return lhs && rhs;
+ }(k < nct, this.s[k] !== 0.0)) {
+ var t = 0;
+ for (var _i2 = k; _i2 < this.m; _i2++) {
+ t += A[_i2][k] * A[_i2][j];
+ }
+ ;
+ t = -t / A[k][k];
+ for (var _i3 = k; _i3 < this.m; _i3++) {
+ A[_i3][j] += t * A[_i3][k];
+ }
+ ;
+ }
+ e[j] = A[k][j];
+ }
+ ;
+ if (function (lhs, rhs) {
+ return lhs && rhs;
+ }(wantu, k < nct)) {
+ for (var _i4 = k; _i4 < this.m; _i4++) {
+ this.U[_i4][k] = A[_i4][k];
+ }
+ ;
+ }
+ if (k < nrt) {
+ e[k] = 0;
+ for (var _i5 = k + 1; _i5 < this.n; _i5++) {
+ e[k] = SVD.hypot(e[k], e[_i5]);
+ }
+ ;
+ if (e[k] !== 0.0) {
+ if (e[k + 1] < 0.0) {
+ e[k] = -e[k];
+ }
+ for (var _i6 = k + 1; _i6 < this.n; _i6++) {
+ e[_i6] /= e[k];
+ }
+ ;
+ e[k + 1] += 1.0;
+ }
+ e[k] = -e[k];
+ if (function (lhs, rhs) {
+ return lhs && rhs;
+ }(k + 1 < this.m, e[k] !== 0.0)) {
+ for (var _i7 = k + 1; _i7 < this.m; _i7++) {
+ work[_i7] = 0.0;
+ }
+ ;
+ for (var _j = k + 1; _j < this.n; _j++) {
+ for (var _i8 = k + 1; _i8 < this.m; _i8++) {
+ work[_i8] += e[_j] * A[_i8][_j];
+ }
+ ;
+ }
+ ;
+ for (var _j2 = k + 1; _j2 < this.n; _j2++) {
+ var _t = -e[_j2] / e[k + 1];
+ for (var _i9 = k + 1; _i9 < this.m; _i9++) {
+ A[_i9][_j2] += _t * work[_i9];
+ }
+ ;
+ }
+ ;
+ }
+ if (wantv) {
+ for (var _i10 = k + 1; _i10 < this.n; _i10++) {
+ this.V[_i10][k] = e[_i10];
+ };
+ }
+ }
+ };
+ var p = Math.min(this.n, this.m + 1);
+ if (nct < this.n) {
+ this.s[nct] = A[nct][nct];
+ }
+ if (this.m < p) {
+ this.s[p - 1] = 0.0;
+ }
+ if (nrt + 1 < p) {
+ e[nrt] = A[nrt][p - 1];
+ }
+ e[p - 1] = 0.0;
+ if (wantu) {
+ for (var _j3 = nct; _j3 < nu; _j3++) {
+ for (var _i11 = 0; _i11 < this.m; _i11++) {
+ this.U[_i11][_j3] = 0.0;
+ }
+ ;
+ this.U[_j3][_j3] = 1.0;
+ };
+ for (var _k = nct - 1; _k >= 0; _k--) {
+ if (this.s[_k] !== 0.0) {
+ for (var _j4 = _k + 1; _j4 < nu; _j4++) {
+ var _t2 = 0;
+ for (var _i12 = _k; _i12 < this.m; _i12++) {
+ _t2 += this.U[_i12][_k] * this.U[_i12][_j4];
+ };
+ _t2 = -_t2 / this.U[_k][_k];
+ for (var _i13 = _k; _i13 < this.m; _i13++) {
+ this.U[_i13][_j4] += _t2 * this.U[_i13][_k];
+ };
+ };
+ for (var _i14 = _k; _i14 < this.m; _i14++) {
+ this.U[_i14][_k] = -this.U[_i14][_k];
+ };
+ this.U[_k][_k] = 1.0 + this.U[_k][_k];
+ for (var _i15 = 0; _i15 < _k - 1; _i15++) {
+ this.U[_i15][_k] = 0.0;
+ };
+ } else {
+ for (var _i16 = 0; _i16 < this.m; _i16++) {
+ this.U[_i16][_k] = 0.0;
+ };
+ this.U[_k][_k] = 1.0;
+ }
+ };
+ }
+ if (wantv) {
+ for (var _k2 = this.n - 1; _k2 >= 0; _k2--) {
+ if (function (lhs, rhs) {
+ return lhs && rhs;
+ }(_k2 < nrt, e[_k2] !== 0.0)) {
+ for (var _j5 = _k2 + 1; _j5 < nu; _j5++) {
+ var _t3 = 0;
+ for (var _i17 = _k2 + 1; _i17 < this.n; _i17++) {
+ _t3 += this.V[_i17][_k2] * this.V[_i17][_j5];
+ };
+ _t3 = -_t3 / this.V[_k2 + 1][_k2];
+ for (var _i18 = _k2 + 1; _i18 < this.n; _i18++) {
+ this.V[_i18][_j5] += _t3 * this.V[_i18][_k2];
+ };
+ };
+ }
+ for (var _i19 = 0; _i19 < this.n; _i19++) {
+ this.V[_i19][_k2] = 0.0;
+ };
+ this.V[_k2][_k2] = 1.0;
+ };
+ }
+ var pp = p - 1;
+ var iter = 0;
+ var eps = Math.pow(2.0, -52.0);
+ var tiny = Math.pow(2.0, -966.0);
+ while (p > 0) {
+ var _k3 = void 0;
+ var kase = void 0;
+ for (_k3 = p - 2; _k3 >= -1; _k3--) {
+ if (_k3 === -1) {
+ break;
+ }
+ if (Math.abs(e[_k3]) <= tiny + eps * (Math.abs(this.s[_k3]) + Math.abs(this.s[_k3 + 1]))) {
+ e[_k3] = 0.0;
+ break;
+ }
+ };
+ if (_k3 === p - 2) {
+ kase = 4;
+ } else {
+ var ks = void 0;
+ for (ks = p - 1; ks >= _k3; ks--) {
+ if (ks === _k3) {
+ break;
+ }
+ var _t4 = (ks !== p ? Math.abs(e[ks]) : 0.0) + (ks !== _k3 + 1 ? Math.abs(e[ks - 1]) : 0.0);
+ if (Math.abs(this.s[ks]) <= tiny + eps * _t4) {
+ this.s[ks] = 0.0;
+ break;
+ }
+ };
+ if (ks === _k3) {
+ kase = 3;
+ } else if (ks === p - 1) {
+ kase = 1;
+ } else {
+ kase = 2;
+ _k3 = ks;
+ }
+ }
+ _k3++;
+ switch (kase) {
+ case 1:
+ {
+ var f = e[p - 2];
+ e[p - 2] = 0.0;
+ for (var _j6 = p - 2; _j6 >= _k3; _j6--) {
+ var _t5 = SVD.hypot(this.s[_j6], f);
+ var cs = this.s[_j6] / _t5;
+ var sn = f / _t5;
+ this.s[_j6] = _t5;
+ if (_j6 !== _k3) {
+ f = -sn * e[_j6 - 1];
+ e[_j6 - 1] = cs * e[_j6 - 1];
+ }
+ if (wantv) {
+ for (var _i20 = 0; _i20 < this.n; _i20++) {
+ _t5 = cs * this.V[_i20][_j6] + sn * this.V[_i20][p - 1];
+ this.V[_i20][p - 1] = -sn * this.V[_i20][_j6] + cs * this.V[_i20][p - 1];
+ this.V[_i20][_j6] = _t5;
+ };
+ }
+ };
+ };
+ break;
+ case 2:
+ {
+ var _f = e[_k3 - 1];
+ e[_k3 - 1] = 0.0;
+ for (var _j7 = _k3; _j7 < p; _j7++) {
+ var _t6 = SVD.hypot(this.s[_j7], _f);
+ var _cs = this.s[_j7] / _t6;
+ var _sn = _f / _t6;
+ this.s[_j7] = _t6;
+ _f = -_sn * e[_j7];
+ e[_j7] = _cs * e[_j7];
+ if (wantu) {
+ for (var _i21 = 0; _i21 < this.m; _i21++) {
+ _t6 = _cs * this.U[_i21][_j7] + _sn * this.U[_i21][_k3 - 1];
+ this.U[_i21][_k3 - 1] = -_sn * this.U[_i21][_j7] + _cs * this.U[_i21][_k3 - 1];
+ this.U[_i21][_j7] = _t6;
+ };
+ }
+ };
+ };
+ break;
+ case 3:
+ {
+ var scale = Math.max(Math.max(Math.max(Math.max(Math.abs(this.s[p - 1]), Math.abs(this.s[p - 2])), Math.abs(e[p - 2])), Math.abs(this.s[_k3])), Math.abs(e[_k3]));
+ var sp = this.s[p - 1] / scale;
+ var spm1 = this.s[p - 2] / scale;
+ var epm1 = e[p - 2] / scale;
+ var sk = this.s[_k3] / scale;
+ var ek = e[_k3] / scale;
+ var b = ((spm1 + sp) * (spm1 - sp) + epm1 * epm1) / 2.0;
+ var c = sp * epm1 * (sp * epm1);
+ var shift = 0.0;
+ if (function (lhs, rhs) {
+ return lhs || rhs;
+ }(b !== 0.0, c !== 0.0)) {
+ shift = Math.sqrt(b * b + c);
+ if (b < 0.0) {
+ shift = -shift;
+ }
+ shift = c / (b + shift);
+ }
+ var _f2 = (sk + sp) * (sk - sp) + shift;
+ var g = sk * ek;
+ for (var _j8 = _k3; _j8 < p - 1; _j8++) {
+ var _t7 = SVD.hypot(_f2, g);
+ var _cs2 = _f2 / _t7;
+ var _sn2 = g / _t7;
+ if (_j8 !== _k3) {
+ e[_j8 - 1] = _t7;
+ }
+ _f2 = _cs2 * this.s[_j8] + _sn2 * e[_j8];
+ e[_j8] = _cs2 * e[_j8] - _sn2 * this.s[_j8];
+ g = _sn2 * this.s[_j8 + 1];
+ this.s[_j8 + 1] = _cs2 * this.s[_j8 + 1];
+ if (wantv) {
+ for (var _i22 = 0; _i22 < this.n; _i22++) {
+ _t7 = _cs2 * this.V[_i22][_j8] + _sn2 * this.V[_i22][_j8 + 1];
+ this.V[_i22][_j8 + 1] = -_sn2 * this.V[_i22][_j8] + _cs2 * this.V[_i22][_j8 + 1];
+ this.V[_i22][_j8] = _t7;
+ };
+ }
+ _t7 = SVD.hypot(_f2, g);
+ _cs2 = _f2 / _t7;
+ _sn2 = g / _t7;
+ this.s[_j8] = _t7;
+ _f2 = _cs2 * e[_j8] + _sn2 * this.s[_j8 + 1];
+ this.s[_j8 + 1] = -_sn2 * e[_j8] + _cs2 * this.s[_j8 + 1];
+ g = _sn2 * e[_j8 + 1];
+ e[_j8 + 1] = _cs2 * e[_j8 + 1];
+ if (wantu && _j8 < this.m - 1) {
+ for (var _i23 = 0; _i23 < this.m; _i23++) {
+ _t7 = _cs2 * this.U[_i23][_j8] + _sn2 * this.U[_i23][_j8 + 1];
+ this.U[_i23][_j8 + 1] = -_sn2 * this.U[_i23][_j8] + _cs2 * this.U[_i23][_j8 + 1];
+ this.U[_i23][_j8] = _t7;
+ };
+ }
+ };
+ e[p - 2] = _f2;
+ iter = iter + 1;
+ };
+ break;
+ case 4:
+ {
+ if (this.s[_k3] <= 0.0) {
+ this.s[_k3] = this.s[_k3] < 0.0 ? -this.s[_k3] : 0.0;
+ if (wantv) {
+ for (var _i24 = 0; _i24 <= pp; _i24++) {
+ this.V[_i24][_k3] = -this.V[_i24][_k3];
+ };
+ }
+ }
+ while (_k3 < pp) {
+ if (this.s[_k3] >= this.s[_k3 + 1]) {
+ break;
+ }
+ var _t8 = this.s[_k3];
+ this.s[_k3] = this.s[_k3 + 1];
+ this.s[_k3 + 1] = _t8;
+ if (wantv && _k3 < this.n - 1) {
+ for (var _i25 = 0; _i25 < this.n; _i25++) {
+ _t8 = this.V[_i25][_k3 + 1];
+ this.V[_i25][_k3 + 1] = this.V[_i25][_k3];
+ this.V[_i25][_k3] = _t8;
+ };
+ }
+ if (wantu && _k3 < this.m - 1) {
+ for (var _i26 = 0; _i26 < this.m; _i26++) {
+ _t8 = this.U[_i26][_k3 + 1];
+ this.U[_i26][_k3 + 1] = this.U[_i26][_k3];
+ this.U[_i26][_k3] = _t8;
+ };
+ }
+ _k3++;
+ };
+ iter = 0;
+ p--;
+ };
+ break;
+ }
+ };
+ var result = { U: this.U, V: this.V, S: this.s };
+ return result;
+};
+
+// sqrt(a^2 + b^2) without under/overflow.
+SVD.hypot = function (a, b) {
+ var r = void 0;
+ if (Math.abs(a) > Math.abs(b)) {
+ r = b / a;
+ r = Math.abs(a) * Math.sqrt(1 + r * r);
+ } else if (b != 0) {
+ r = a / b;
+ r = Math.abs(b) * Math.sqrt(1 + r * r);
+ } else {
+ r = 0.0;
+ }
+ return r;
+};
+
+module.exports = SVD;
+
+/***/ }),
+/* 27 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
+
+function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
+
+/**
+ * Needleman-Wunsch algorithm is an procedure to compute the optimal global alignment of two string
+ * sequences by S.B.Needleman and C.D.Wunsch (1970).
+ *
+ * Aside from the inputs, you can assign the scores for,
+ * - Match: The two characters at the current index are same.
+ * - Mismatch: The two characters at the current index are different.
+ * - Insertion/Deletion(gaps): The best alignment involves one letter aligning to a gap in the other string.
+ */
+
+var NeedlemanWunsch = function () {
+ function NeedlemanWunsch(sequence1, sequence2) {
+ var match_score = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
+ var mismatch_penalty = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : -1;
+ var gap_penalty = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : -1;
+
+ _classCallCheck(this, NeedlemanWunsch);
+
+ this.sequence1 = sequence1;
+ this.sequence2 = sequence2;
+ this.match_score = match_score;
+ this.mismatch_penalty = mismatch_penalty;
+ this.gap_penalty = gap_penalty;
+
+ // Just the remove redundancy
+ this.iMax = sequence1.length + 1;
+ this.jMax = sequence2.length + 1;
+
+ // Grid matrix of scores
+ this.grid = new Array(this.iMax);
+ for (var i = 0; i < this.iMax; i++) {
+ this.grid[i] = new Array(this.jMax);
+
+ for (var j = 0; j < this.jMax; j++) {
+ this.grid[i][j] = 0;
+ }
+ }
+
+ // Traceback matrix (2D array, each cell is an array of boolean values for [`Diag`, `Up`, `Left`] positions)
+ this.tracebackGrid = new Array(this.iMax);
+ for (var _i = 0; _i < this.iMax; _i++) {
+ this.tracebackGrid[_i] = new Array(this.jMax);
+
+ for (var _j = 0; _j < this.jMax; _j++) {
+ this.tracebackGrid[_i][_j] = [null, null, null];
+ }
+ }
+
+ // The aligned sequences (return multiple possibilities)
+ this.alignments = [];
+
+ // Final alignment score
+ this.score = -1;
+
+ // Calculate scores and tracebacks
+ this.computeGrids();
+ }
+
+ _createClass(NeedlemanWunsch, [{
+ key: "getScore",
+ value: function getScore() {
+ return this.score;
+ }
+ }, {
+ key: "getAlignments",
+ value: function getAlignments() {
+ return this.alignments;
+ }
+
+ // Main dynamic programming procedure
+
+ }, {
+ key: "computeGrids",
+ value: function computeGrids() {
+ // Fill in the first row
+ for (var j = 1; j < this.jMax; j++) {
+ this.grid[0][j] = this.grid[0][j - 1] + this.gap_penalty;
+ this.tracebackGrid[0][j] = [false, false, true];
+ }
+
+ // Fill in the first column
+ for (var i = 1; i < this.iMax; i++) {
+ this.grid[i][0] = this.grid[i - 1][0] + this.gap_penalty;
+ this.tracebackGrid[i][0] = [false, true, false];
+ }
+
+ // Fill the rest of the grid
+ for (var _i2 = 1; _i2 < this.iMax; _i2++) {
+ for (var _j2 = 1; _j2 < this.jMax; _j2++) {
+ // Find the max score(s) among [`Diag`, `Up`, `Left`]
+ var diag = void 0;
+ if (this.sequence1[_i2 - 1] === this.sequence2[_j2 - 1]) diag = this.grid[_i2 - 1][_j2 - 1] + this.match_score;else diag = this.grid[_i2 - 1][_j2 - 1] + this.mismatch_penalty;
+
+ var up = this.grid[_i2 - 1][_j2] + this.gap_penalty;
+ var left = this.grid[_i2][_j2 - 1] + this.gap_penalty;
+
+ // If there exists multiple max values, capture them for multiple paths
+ var maxOf = [diag, up, left];
+ var indices = this.arrayAllMaxIndexes(maxOf);
+
+ // Update Grids
+ this.grid[_i2][_j2] = maxOf[indices[0]];
+ this.tracebackGrid[_i2][_j2] = [indices.includes(0), indices.includes(1), indices.includes(2)];
+ }
+ }
+
+ // Update alignment score
+ this.score = this.grid[this.iMax - 1][this.jMax - 1];
+ }
+
+ // Gets all possible valid sequence combinations
+
+ }, {
+ key: "alignmentTraceback",
+ value: function alignmentTraceback() {
+ var inProcessAlignments = [];
+
+ inProcessAlignments.push({ pos: [this.sequence1.length, this.sequence2.length],
+ seq1: "",
+ seq2: ""
+ });
+
+ while (inProcessAlignments[0]) {
+ var current = inProcessAlignments[0];
+ var directions = this.tracebackGrid[current.pos[0]][current.pos[1]];
+
+ if (directions[0]) {
+ inProcessAlignments.push({ pos: [current.pos[0] - 1, current.pos[1] - 1],
+ seq1: this.sequence1[current.pos[0] - 1] + current.seq1,
+ seq2: this.sequence2[current.pos[1] - 1] + current.seq2
+ });
+ }
+ if (directions[1]) {
+ inProcessAlignments.push({ pos: [current.pos[0] - 1, current.pos[1]],
+ seq1: this.sequence1[current.pos[0] - 1] + current.seq1,
+ seq2: '-' + current.seq2
+ });
+ }
+ if (directions[2]) {
+ inProcessAlignments.push({ pos: [current.pos[0], current.pos[1] - 1],
+ seq1: '-' + current.seq1,
+ seq2: this.sequence2[current.pos[1] - 1] + current.seq2
+ });
+ }
+
+ if (current.pos[0] === 0 && current.pos[1] === 0) this.alignments.push({ sequence1: current.seq1,
+ sequence2: current.seq2
+ });
+
+ inProcessAlignments.shift();
+ }
+
+ return this.alignments;
+ }
+
+ // Helper Functions
+
+ }, {
+ key: "getAllIndexes",
+ value: function getAllIndexes(arr, val) {
+ var indexes = [],
+ i = -1;
+ while ((i = arr.indexOf(val, i + 1)) !== -1) {
+ indexes.push(i);
+ }
+ return indexes;
+ }
+ }, {
+ key: "arrayAllMaxIndexes",
+ value: function arrayAllMaxIndexes(array) {
+ return this.getAllIndexes(array, Math.max.apply(null, array));
+ }
+ }]);
+
+ return NeedlemanWunsch;
+}();
+
+module.exports = NeedlemanWunsch;
+
+/***/ }),
+/* 28 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+var layoutBase = function layoutBase() {
+ return;
+};
+
+layoutBase.FDLayout = __webpack_require__(18);
+layoutBase.FDLayoutConstants = __webpack_require__(4);
+layoutBase.FDLayoutEdge = __webpack_require__(19);
+layoutBase.FDLayoutNode = __webpack_require__(20);
+layoutBase.DimensionD = __webpack_require__(21);
+layoutBase.HashMap = __webpack_require__(22);
+layoutBase.HashSet = __webpack_require__(23);
+layoutBase.IGeometry = __webpack_require__(8);
+layoutBase.IMath = __webpack_require__(9);
+layoutBase.Integer = __webpack_require__(10);
+layoutBase.Point = __webpack_require__(12);
+layoutBase.PointD = __webpack_require__(5);
+layoutBase.RandomSeed = __webpack_require__(16);
+layoutBase.RectangleD = __webpack_require__(13);
+layoutBase.Transform = __webpack_require__(17);
+layoutBase.UniqueIDGeneretor = __webpack_require__(14);
+layoutBase.Quicksort = __webpack_require__(25);
+layoutBase.LinkedList = __webpack_require__(11);
+layoutBase.LGraphObject = __webpack_require__(2);
+layoutBase.LGraph = __webpack_require__(6);
+layoutBase.LEdge = __webpack_require__(1);
+layoutBase.LGraphManager = __webpack_require__(7);
+layoutBase.LNode = __webpack_require__(3);
+layoutBase.Layout = __webpack_require__(15);
+layoutBase.LayoutConstants = __webpack_require__(0);
+layoutBase.NeedlemanWunsch = __webpack_require__(27);
+layoutBase.Matrix = __webpack_require__(24);
+layoutBase.SVD = __webpack_require__(26);
+
+module.exports = layoutBase;
+
+/***/ }),
+/* 29 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+
+function Emitter() {
+ this.listeners = [];
+}
+
+var p = Emitter.prototype;
+
+p.addListener = function (event, callback) {
+ this.listeners.push({
+ event: event,
+ callback: callback
+ });
+};
+
+p.removeListener = function (event, callback) {
+ for (var i = this.listeners.length; i >= 0; i--) {
+ var l = this.listeners[i];
+
+ if (l.event === event && l.callback === callback) {
+ this.listeners.splice(i, 1);
+ }
+ }
+};
+
+p.emit = function (event, data) {
+ for (var i = 0; i < this.listeners.length; i++) {
+ var l = this.listeners[i];
+
+ if (event === l.event) {
+ l.callback(data);
+ }
+ }
+};
+
+module.exports = Emitter;
+
+/***/ })
+/******/ ]);
+});
\ No newline at end of file
diff --git a/web/vendor/leaflet.css b/web/vendor/leaflet.css
new file mode 100644
index 0000000..9ade8dc
--- /dev/null
+++ b/web/vendor/leaflet.css
@@ -0,0 +1,661 @@
+/* required styles */
+
+.leaflet-pane,
+.leaflet-tile,
+.leaflet-marker-icon,
+.leaflet-marker-shadow,
+.leaflet-tile-container,
+.leaflet-pane > svg,
+.leaflet-pane > canvas,
+.leaflet-zoom-box,
+.leaflet-image-layer,
+.leaflet-layer {
+ position: absolute;
+ left: 0;
+ top: 0;
+ }
+.leaflet-container {
+ overflow: hidden;
+ }
+.leaflet-tile,
+.leaflet-marker-icon,
+.leaflet-marker-shadow {
+ -webkit-user-select: none;
+ -moz-user-select: none;
+ user-select: none;
+ -webkit-user-drag: none;
+ }
+/* Prevents IE11 from highlighting tiles in blue */
+.leaflet-tile::selection {
+ background: transparent;
+}
+/* Safari renders non-retina tile on retina better with this, but Chrome is worse */
+.leaflet-safari .leaflet-tile {
+ image-rendering: -webkit-optimize-contrast;
+ }
+/* hack that prevents hw layers "stretching" when loading new tiles */
+.leaflet-safari .leaflet-tile-container {
+ width: 1600px;
+ height: 1600px;
+ -webkit-transform-origin: 0 0;
+ }
+.leaflet-marker-icon,
+.leaflet-marker-shadow {
+ display: block;
+ }
+/* .leaflet-container svg: reset svg max-width decleration shipped in Joomla! (joomla.org) 3.x */
+/* .leaflet-container img: map is broken in FF if you have max-width: 100% on tiles */
+.leaflet-container .leaflet-overlay-pane svg {
+ max-width: none !important;
+ max-height: none !important;
+ }
+.leaflet-container .leaflet-marker-pane img,
+.leaflet-container .leaflet-shadow-pane img,
+.leaflet-container .leaflet-tile-pane img,
+.leaflet-container img.leaflet-image-layer,
+.leaflet-container .leaflet-tile {
+ max-width: none !important;
+ max-height: none !important;
+ width: auto;
+ padding: 0;
+ }
+
+.leaflet-container img.leaflet-tile {
+ /* See: https://bugs.chromium.org/p/chromium/issues/detail?id=600120 */
+ mix-blend-mode: plus-lighter;
+}
+
+.leaflet-container.leaflet-touch-zoom {
+ -ms-touch-action: pan-x pan-y;
+ touch-action: pan-x pan-y;
+ }
+.leaflet-container.leaflet-touch-drag {
+ -ms-touch-action: pinch-zoom;
+ /* Fallback for FF which doesn't support pinch-zoom */
+ touch-action: none;
+ touch-action: pinch-zoom;
+}
+.leaflet-container.leaflet-touch-drag.leaflet-touch-zoom {
+ -ms-touch-action: none;
+ touch-action: none;
+}
+.leaflet-container {
+ -webkit-tap-highlight-color: transparent;
+}
+.leaflet-container a {
+ -webkit-tap-highlight-color: rgba(51, 181, 229, 0.4);
+}
+.leaflet-tile {
+ filter: inherit;
+ visibility: hidden;
+ }
+.leaflet-tile-loaded {
+ visibility: inherit;
+ }
+.leaflet-zoom-box {
+ width: 0;
+ height: 0;
+ -moz-box-sizing: border-box;
+ box-sizing: border-box;
+ z-index: 800;
+ }
+/* workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=888319 */
+.leaflet-overlay-pane svg {
+ -moz-user-select: none;
+ }
+
+.leaflet-pane { z-index: 400; }
+
+.leaflet-tile-pane { z-index: 200; }
+.leaflet-overlay-pane { z-index: 400; }
+.leaflet-shadow-pane { z-index: 500; }
+.leaflet-marker-pane { z-index: 600; }
+.leaflet-tooltip-pane { z-index: 650; }
+.leaflet-popup-pane { z-index: 700; }
+
+.leaflet-map-pane canvas { z-index: 100; }
+.leaflet-map-pane svg { z-index: 200; }
+
+.leaflet-vml-shape {
+ width: 1px;
+ height: 1px;
+ }
+.lvml {
+ behavior: url(#default#VML);
+ display: inline-block;
+ position: absolute;
+ }
+
+
+/* control positioning */
+
+.leaflet-control {
+ position: relative;
+ z-index: 800;
+ pointer-events: visiblePainted; /* IE 9-10 doesn't have auto */
+ pointer-events: auto;
+ }
+.leaflet-top,
+.leaflet-bottom {
+ position: absolute;
+ z-index: 1000;
+ pointer-events: none;
+ }
+.leaflet-top {
+ top: 0;
+ }
+.leaflet-right {
+ right: 0;
+ }
+.leaflet-bottom {
+ bottom: 0;
+ }
+.leaflet-left {
+ left: 0;
+ }
+.leaflet-control {
+ float: left;
+ clear: both;
+ }
+.leaflet-right .leaflet-control {
+ float: right;
+ }
+.leaflet-top .leaflet-control {
+ margin-top: 10px;
+ }
+.leaflet-bottom .leaflet-control {
+ margin-bottom: 10px;
+ }
+.leaflet-left .leaflet-control {
+ margin-left: 10px;
+ }
+.leaflet-right .leaflet-control {
+ margin-right: 10px;
+ }
+
+
+/* zoom and fade animations */
+
+.leaflet-fade-anim .leaflet-popup {
+ opacity: 0;
+ -webkit-transition: opacity 0.2s linear;
+ -moz-transition: opacity 0.2s linear;
+ transition: opacity 0.2s linear;
+ }
+.leaflet-fade-anim .leaflet-map-pane .leaflet-popup {
+ opacity: 1;
+ }
+.leaflet-zoom-animated {
+ -webkit-transform-origin: 0 0;
+ -ms-transform-origin: 0 0;
+ transform-origin: 0 0;
+ }
+svg.leaflet-zoom-animated {
+ will-change: transform;
+}
+
+.leaflet-zoom-anim .leaflet-zoom-animated {
+ -webkit-transition: -webkit-transform 0.25s cubic-bezier(0,0,0.25,1);
+ -moz-transition: -moz-transform 0.25s cubic-bezier(0,0,0.25,1);
+ transition: transform 0.25s cubic-bezier(0,0,0.25,1);
+ }
+.leaflet-zoom-anim .leaflet-tile,
+.leaflet-pan-anim .leaflet-tile {
+ -webkit-transition: none;
+ -moz-transition: none;
+ transition: none;
+ }
+
+.leaflet-zoom-anim .leaflet-zoom-hide {
+ visibility: hidden;
+ }
+
+
+/* cursors */
+
+.leaflet-interactive {
+ cursor: pointer;
+ }
+.leaflet-grab {
+ cursor: -webkit-grab;
+ cursor: -moz-grab;
+ cursor: grab;
+ }
+.leaflet-crosshair,
+.leaflet-crosshair .leaflet-interactive {
+ cursor: crosshair;
+ }
+.leaflet-popup-pane,
+.leaflet-control {
+ cursor: auto;
+ }
+.leaflet-dragging .leaflet-grab,
+.leaflet-dragging .leaflet-grab .leaflet-interactive,
+.leaflet-dragging .leaflet-marker-draggable {
+ cursor: move;
+ cursor: -webkit-grabbing;
+ cursor: -moz-grabbing;
+ cursor: grabbing;
+ }
+
+/* marker & overlays interactivity */
+.leaflet-marker-icon,
+.leaflet-marker-shadow,
+.leaflet-image-layer,
+.leaflet-pane > svg path,
+.leaflet-tile-container {
+ pointer-events: none;
+ }
+
+.leaflet-marker-icon.leaflet-interactive,
+.leaflet-image-layer.leaflet-interactive,
+.leaflet-pane > svg path.leaflet-interactive,
+svg.leaflet-image-layer.leaflet-interactive path {
+ pointer-events: visiblePainted; /* IE 9-10 doesn't have auto */
+ pointer-events: auto;
+ }
+
+/* visual tweaks */
+
+.leaflet-container {
+ background: #ddd;
+ outline-offset: 1px;
+ }
+.leaflet-container a {
+ color: #0078A8;
+ }
+.leaflet-zoom-box {
+ border: 2px dotted #38f;
+ background: rgba(255,255,255,0.5);
+ }
+
+
+/* general typography */
+.leaflet-container {
+ font-family: "Helvetica Neue", Arial, Helvetica, sans-serif;
+ font-size: 12px;
+ font-size: 0.75rem;
+ line-height: 1.5;
+ }
+
+
+/* general toolbar styles */
+
+.leaflet-bar {
+ box-shadow: 0 1px 5px rgba(0,0,0,0.65);
+ border-radius: 4px;
+ }
+.leaflet-bar a {
+ background-color: #fff;
+ border-bottom: 1px solid #ccc;
+ width: 26px;
+ height: 26px;
+ line-height: 26px;
+ display: block;
+ text-align: center;
+ text-decoration: none;
+ color: black;
+ }
+.leaflet-bar a,
+.leaflet-control-layers-toggle {
+ background-position: 50% 50%;
+ background-repeat: no-repeat;
+ display: block;
+ }
+.leaflet-bar a:hover,
+.leaflet-bar a:focus {
+ background-color: #f4f4f4;
+ }
+.leaflet-bar a:first-child {
+ border-top-left-radius: 4px;
+ border-top-right-radius: 4px;
+ }
+.leaflet-bar a:last-child {
+ border-bottom-left-radius: 4px;
+ border-bottom-right-radius: 4px;
+ border-bottom: none;
+ }
+.leaflet-bar a.leaflet-disabled {
+ cursor: default;
+ background-color: #f4f4f4;
+ color: #bbb;
+ }
+
+.leaflet-touch .leaflet-bar a {
+ width: 30px;
+ height: 30px;
+ line-height: 30px;
+ }
+.leaflet-touch .leaflet-bar a:first-child {
+ border-top-left-radius: 2px;
+ border-top-right-radius: 2px;
+ }
+.leaflet-touch .leaflet-bar a:last-child {
+ border-bottom-left-radius: 2px;
+ border-bottom-right-radius: 2px;
+ }
+
+/* zoom control */
+
+.leaflet-control-zoom-in,
+.leaflet-control-zoom-out {
+ font: bold 18px 'Lucida Console', Monaco, monospace;
+ text-indent: 1px;
+ }
+
+.leaflet-touch .leaflet-control-zoom-in, .leaflet-touch .leaflet-control-zoom-out {
+ font-size: 22px;
+ }
+
+
+/* layers control */
+
+.leaflet-control-layers {
+ box-shadow: 0 1px 5px rgba(0,0,0,0.4);
+ background: #fff;
+ border-radius: 5px;
+ }
+.leaflet-control-layers-toggle {
+ background-image: url(images/layers.png);
+ width: 36px;
+ height: 36px;
+ }
+.leaflet-retina .leaflet-control-layers-toggle {
+ background-image: url(images/layers-2x.png);
+ background-size: 26px 26px;
+ }
+.leaflet-touch .leaflet-control-layers-toggle {
+ width: 44px;
+ height: 44px;
+ }
+.leaflet-control-layers .leaflet-control-layers-list,
+.leaflet-control-layers-expanded .leaflet-control-layers-toggle {
+ display: none;
+ }
+.leaflet-control-layers-expanded .leaflet-control-layers-list {
+ display: block;
+ position: relative;
+ }
+.leaflet-control-layers-expanded {
+ padding: 6px 10px 6px 6px;
+ color: #333;
+ background: #fff;
+ }
+.leaflet-control-layers-scrollbar {
+ overflow-y: scroll;
+ overflow-x: hidden;
+ padding-right: 5px;
+ }
+.leaflet-control-layers-selector {
+ margin-top: 2px;
+ position: relative;
+ top: 1px;
+ }
+.leaflet-control-layers label {
+ display: block;
+ font-size: 13px;
+ font-size: 1.08333em;
+ }
+.leaflet-control-layers-separator {
+ height: 0;
+ border-top: 1px solid #ddd;
+ margin: 5px -10px 5px -6px;
+ }
+
+/* Default icon URLs */
+.leaflet-default-icon-path { /* used only in path-guessing heuristic, see L.Icon.Default */
+ background-image: url(images/marker-icon.png);
+ }
+
+
+/* attribution and scale controls */
+
+.leaflet-container .leaflet-control-attribution {
+ background: #fff;
+ background: rgba(255, 255, 255, 0.8);
+ margin: 0;
+ }
+.leaflet-control-attribution,
+.leaflet-control-scale-line {
+ padding: 0 5px;
+ color: #333;
+ line-height: 1.4;
+ }
+.leaflet-control-attribution a {
+ text-decoration: none;
+ }
+.leaflet-control-attribution a:hover,
+.leaflet-control-attribution a:focus {
+ text-decoration: underline;
+ }
+.leaflet-attribution-flag {
+ display: inline !important;
+ vertical-align: baseline !important;
+ width: 1em;
+ height: 0.6669em;
+ }
+.leaflet-left .leaflet-control-scale {
+ margin-left: 5px;
+ }
+.leaflet-bottom .leaflet-control-scale {
+ margin-bottom: 5px;
+ }
+.leaflet-control-scale-line {
+ border: 2px solid #777;
+ border-top: none;
+ line-height: 1.1;
+ padding: 2px 5px 1px;
+ white-space: nowrap;
+ -moz-box-sizing: border-box;
+ box-sizing: border-box;
+ background: rgba(255, 255, 255, 0.8);
+ text-shadow: 1px 1px #fff;
+ }
+.leaflet-control-scale-line:not(:first-child) {
+ border-top: 2px solid #777;
+ border-bottom: none;
+ margin-top: -2px;
+ }
+.leaflet-control-scale-line:not(:first-child):not(:last-child) {
+ border-bottom: 2px solid #777;
+ }
+
+.leaflet-touch .leaflet-control-attribution,
+.leaflet-touch .leaflet-control-layers,
+.leaflet-touch .leaflet-bar {
+ box-shadow: none;
+ }
+.leaflet-touch .leaflet-control-layers,
+.leaflet-touch .leaflet-bar {
+ border: 2px solid rgba(0,0,0,0.2);
+ background-clip: padding-box;
+ }
+
+
+/* popup */
+
+.leaflet-popup {
+ position: absolute;
+ text-align: center;
+ margin-bottom: 20px;
+ }
+.leaflet-popup-content-wrapper {
+ padding: 1px;
+ text-align: left;
+ border-radius: 12px;
+ }
+.leaflet-popup-content {
+ margin: 13px 24px 13px 20px;
+ line-height: 1.3;
+ font-size: 13px;
+ font-size: 1.08333em;
+ min-height: 1px;
+ }
+.leaflet-popup-content p {
+ margin: 17px 0;
+ margin: 1.3em 0;
+ }
+.leaflet-popup-tip-container {
+ width: 40px;
+ height: 20px;
+ position: absolute;
+ left: 50%;
+ margin-top: -1px;
+ margin-left: -20px;
+ overflow: hidden;
+ pointer-events: none;
+ }
+.leaflet-popup-tip {
+ width: 17px;
+ height: 17px;
+ padding: 1px;
+
+ margin: -10px auto 0;
+ pointer-events: auto;
+
+ -webkit-transform: rotate(45deg);
+ -moz-transform: rotate(45deg);
+ -ms-transform: rotate(45deg);
+ transform: rotate(45deg);
+ }
+.leaflet-popup-content-wrapper,
+.leaflet-popup-tip {
+ background: white;
+ color: #333;
+ box-shadow: 0 3px 14px rgba(0,0,0,0.4);
+ }
+.leaflet-container a.leaflet-popup-close-button {
+ position: absolute;
+ top: 0;
+ right: 0;
+ border: none;
+ text-align: center;
+ width: 24px;
+ height: 24px;
+ font: 16px/24px Tahoma, Verdana, sans-serif;
+ color: #757575;
+ text-decoration: none;
+ background: transparent;
+ }
+.leaflet-container a.leaflet-popup-close-button:hover,
+.leaflet-container a.leaflet-popup-close-button:focus {
+ color: #585858;
+ }
+.leaflet-popup-scrolled {
+ overflow: auto;
+ }
+
+.leaflet-oldie .leaflet-popup-content-wrapper {
+ -ms-zoom: 1;
+ }
+.leaflet-oldie .leaflet-popup-tip {
+ width: 24px;
+ margin: 0 auto;
+
+ -ms-filter: "progid:DXImageTransform.Microsoft.Matrix(M11=0.70710678, M12=0.70710678, M21=-0.70710678, M22=0.70710678)";
+ filter: progid:DXImageTransform.Microsoft.Matrix(M11=0.70710678, M12=0.70710678, M21=-0.70710678, M22=0.70710678);
+ }
+
+.leaflet-oldie .leaflet-control-zoom,
+.leaflet-oldie .leaflet-control-layers,
+.leaflet-oldie .leaflet-popup-content-wrapper,
+.leaflet-oldie .leaflet-popup-tip {
+ border: 1px solid #999;
+ }
+
+
+/* div icon */
+
+.leaflet-div-icon {
+ background: #fff;
+ border: 1px solid #666;
+ }
+
+
+/* Tooltip */
+/* Base styles for the element that has a tooltip */
+.leaflet-tooltip {
+ position: absolute;
+ padding: 6px;
+ background-color: #fff;
+ border: 1px solid #fff;
+ border-radius: 3px;
+ color: #222;
+ white-space: nowrap;
+ -webkit-user-select: none;
+ -moz-user-select: none;
+ -ms-user-select: none;
+ user-select: none;
+ pointer-events: none;
+ box-shadow: 0 1px 3px rgba(0,0,0,0.4);
+ }
+.leaflet-tooltip.leaflet-interactive {
+ cursor: pointer;
+ pointer-events: auto;
+ }
+.leaflet-tooltip-top:before,
+.leaflet-tooltip-bottom:before,
+.leaflet-tooltip-left:before,
+.leaflet-tooltip-right:before {
+ position: absolute;
+ pointer-events: none;
+ border: 6px solid transparent;
+ background: transparent;
+ content: "";
+ }
+
+/* Directions */
+
+.leaflet-tooltip-bottom {
+ margin-top: 6px;
+}
+.leaflet-tooltip-top {
+ margin-top: -6px;
+}
+.leaflet-tooltip-bottom:before,
+.leaflet-tooltip-top:before {
+ left: 50%;
+ margin-left: -6px;
+ }
+.leaflet-tooltip-top:before {
+ bottom: 0;
+ margin-bottom: -12px;
+ border-top-color: #fff;
+ }
+.leaflet-tooltip-bottom:before {
+ top: 0;
+ margin-top: -12px;
+ margin-left: -6px;
+ border-bottom-color: #fff;
+ }
+.leaflet-tooltip-left {
+ margin-left: -6px;
+}
+.leaflet-tooltip-right {
+ margin-left: 6px;
+}
+.leaflet-tooltip-left:before,
+.leaflet-tooltip-right:before {
+ top: 50%;
+ margin-top: -6px;
+ }
+.leaflet-tooltip-left:before {
+ right: 0;
+ margin-right: -12px;
+ border-left-color: #fff;
+ }
+.leaflet-tooltip-right:before {
+ left: 0;
+ margin-left: -12px;
+ border-right-color: #fff;
+ }
+
+/* Printing */
+
+@media print {
+ /* Prevent printers from removing background-images of controls. */
+ .leaflet-control {
+ -webkit-print-color-adjust: exact;
+ print-color-adjust: exact;
+ }
+ }
diff --git a/web/vendor/leaflet.js b/web/vendor/leaflet.js
new file mode 100644
index 0000000..a3bf693
--- /dev/null
+++ b/web/vendor/leaflet.js
@@ -0,0 +1,6 @@
+/* @preserve
+ * Leaflet 1.9.4, a JS library for interactive maps. https://leafletjs.com
+ * (c) 2010-2023 Vladimir Agafonkin, (c) 2010-2011 CloudMade
+ */
+!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).leaflet={})}(this,function(t){"use strict";function l(t){for(var e,i,n=1,o=arguments.length;n<o;n++)for(e in i=arguments[n])t[e]=i[e];return t}var R=Object.create||function(t){return N.prototype=t,new N};function N(){}function a(t,e){var i,n=Array.prototype.slice;return t.bind?t.bind.apply(t,n.call(arguments,1)):(i=n.call(arguments,2),function(){return t.apply(e,i.length?i.concat(n.call(arguments)):arguments)})}var D=0;function h(t){return"_leaflet_id"in t||(t._leaflet_id=++D),t._leaflet_id}function j(t,e,i){var n,o,s=function(){n=!1,o&&(r.apply(i,o),o=!1)},r=function(){n?o=arguments:(t.apply(i,arguments),setTimeout(s,e),n=!0)};return r}function H(t,e,i){var n=e[1],e=e[0],o=n-e;return t===n&&i?t:((t-e)%o+o)%o+e}function u(){return!1}function i(t,e){return!1===e?t:(e=Math.pow(10,void 0===e?6:e),Math.round(t*e)/e)}function W(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}function F(t){return W(t).split(/\s+/)}function c(t,e){for(var i in Object.prototype.hasOwnProperty.call(t,"options")||(t.options=t.options?R(t.options):{}),e)t.options[i]=e[i];return t.options}function U(t,e,i){var n,o=[];for(n in t)o.push(encodeURIComponent(i?n.toUpperCase():n)+"="+encodeURIComponent(t[n]));return(e&&-1!==e.indexOf("?")?"&":"?")+o.join("&")}var V=/\{ *([\w_ -]+) *\}/g;function q(t,i){return t.replace(V,function(t,e){e=i[e];if(void 0===e)throw new Error("No value provided for variable "+t);return e="function"==typeof e?e(i):e})}var d=Array.isArray||function(t){return"[object Array]"===Object.prototype.toString.call(t)};function G(t,e){for(var i=0;i<t.length;i++)if(t[i]===e)return i;return-1}var K="data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=";function Y(t){return window["webkit"+t]||window["moz"+t]||window["ms"+t]}var X=0;function J(t){var e=+new Date,i=Math.max(0,16-(e-X));return X=e+i,window.setTimeout(t,i)}var $=window.requestAnimationFrame||Y("RequestAnimationFrame")||J,Q=window.cancelAnimationFrame||Y("CancelAnimationFrame")||Y("CancelRequestAnimationFrame")||function(t){window.clearTimeout(t)};function x(t,e,i){if(!i||$!==J)return $.call(window,a(t,e));t.call(e)}function r(t){t&&Q.call(window,t)}var tt={__proto__:null,extend:l,create:R,bind:a,get lastId(){return D},stamp:h,throttle:j,wrapNum:H,falseFn:u,formatNum:i,trim:W,splitWords:F,setOptions:c,getParamString:U,template:q,isArray:d,indexOf:G,emptyImageUrl:K,requestFn:$,cancelFn:Q,requestAnimFrame:x,cancelAnimFrame:r};function et(){}et.extend=function(t){function e(){c(this),this.initialize&&this.initialize.apply(this,arguments),this.callInitHooks()}var i,n=e.__super__=this.prototype,o=R(n);for(i in(o.constructor=e).prototype=o,this)Object.prototype.hasOwnProperty.call(this,i)&&"prototype"!==i&&"__super__"!==i&&(e[i]=this[i]);if(t.statics&&l(e,t.statics),t.includes){var s=t.includes;if("undefined"!=typeof L&&L&&L.Mixin){s=d(s)?s:[s];for(var r=0;r<s.length;r++)s[r]===L.Mixin.Events&&console.warn("Deprecated include of L.Mixin.Events: this property will be removed in future releases, please inherit from L.Evented instead.",(new Error).stack)}l.apply(null,[o].concat(t.includes))}return l(o,t),delete o.statics,delete o.includes,o.options&&(o.options=n.options?R(n.options):{},l(o.options,t.options)),o._initHooks=[],o.callInitHooks=function(){if(!this._initHooksCalled){n.callInitHooks&&n.callInitHooks.call(this),this._initHooksCalled=!0;for(var t=0,e=o._initHooks.length;t<e;t++)o._initHooks[t].call(this)}},e},et.include=function(t){var e=this.prototype.options;return l(this.prototype,t),t.options&&(this.prototype.options=e,this.mergeOptions(t.options)),this},et.mergeOptions=function(t){return l(this.prototype.options,t),this},et.addInitHook=function(t){var e=Array.prototype.slice.call(arguments,1),i="function"==typeof t?t:function(){this[t].apply(this,e)};return this.prototype._initHooks=this.prototype._initHooks||[],this.prototype._initHooks.push(i),this};var e={on:function(t,e,i){if("object"==typeof t)for(var n in t)this._on(n,t[n],e);else for(var o=0,s=(t=F(t)).length;o<s;o++)this._on(t[o],e,i);return this},off:function(t,e,i){if(arguments.length)if("object"==typeof t)for(var n in t)this._off(n,t[n],e);else{t=F(t);for(var o=1===arguments.length,s=0,r=t.length;s<r;s++)o?this._off(t[s]):this._off(t[s],e,i)}else delete this._events;return this},_on:function(t,e,i,n){"function"!=typeof e?console.warn("wrong listener type: "+typeof e):!1===this._listens(t,e,i)&&(e={fn:e,ctx:i=i===this?void 0:i},n&&(e.once=!0),this._events=this._events||{},this._events[t]=this._events[t]||[],this._events[t].push(e))},_off:function(t,e,i){var n,o,s;if(this._events&&(n=this._events[t]))if(1===arguments.length){if(this._firingCount)for(o=0,s=n.length;o<s;o++)n[o].fn=u;delete this._events[t]}else"function"!=typeof e?console.warn("wrong listener type: "+typeof e):!1!==(e=this._listens(t,e,i))&&(i=n[e],this._firingCount&&(i.fn=u,this._events[t]=n=n.slice()),n.splice(e,1))},fire:function(t,e,i){if(this.listens(t,i)){var n=l({},e,{type:t,target:this,sourceTarget:e&&e.sourceTarget||this});if(this._events){var o=this._events[t];if(o){this._firingCount=this._firingCount+1||1;for(var s=0,r=o.length;s<r;s++){var a=o[s],h=a.fn;a.once&&this.off(t,h,a.ctx),h.call(a.ctx||this,n)}this._firingCount--}}i&&this._propagateEvent(n)}return this},listens:function(t,e,i,n){"string"!=typeof t&&console.warn('"string" type argument expected');var o=e,s=("function"!=typeof e&&(n=!!e,i=o=void 0),this._events&&this._events[t]);if(s&&s.length&&!1!==this._listens(t,o,i))return!0;if(n)for(var r in this._eventParents)if(this._eventParents[r].listens(t,e,i,n))return!0;return!1},_listens:function(t,e,i){if(this._events){var n=this._events[t]||[];if(!e)return!!n.length;i===this&&(i=void 0);for(var o=0,s=n.length;o<s;o++)if(n[o].fn===e&&n[o].ctx===i)return o}return!1},once:function(t,e,i){if("object"==typeof t)for(var n in t)this._on(n,t[n],e,!0);else for(var o=0,s=(t=F(t)).length;o<s;o++)this._on(t[o],e,i,!0);return this},addEventParent:function(t){return this._eventParents=this._eventParents||{},this._eventParents[h(t)]=t,this},removeEventParent:function(t){return this._eventParents&&delete this._eventParents[h(t)],this},_propagateEvent:function(t){for(var e in this._eventParents)this._eventParents[e].fire(t.type,l({layer:t.target,propagatedFrom:t.target},t),!0)}},it=(e.addEventListener=e.on,e.removeEventListener=e.clearAllEventListeners=e.off,e.addOneTimeEventListener=e.once,e.fireEvent=e.fire,e.hasEventListeners=e.listens,et.extend(e));function p(t,e,i){this.x=i?Math.round(t):t,this.y=i?Math.round(e):e}var nt=Math.trunc||function(t){return 0<t?Math.floor(t):Math.ceil(t)};function m(t,e,i){return t instanceof p?t:d(t)?new p(t[0],t[1]):null==t?t:"object"==typeof t&&"x"in t&&"y"in t?new p(t.x,t.y):new p(t,e,i)}function f(t,e){if(t)for(var i=e?[t,e]:t,n=0,o=i.length;n<o;n++)this.extend(i[n])}function _(t,e){return!t||t instanceof f?t:new f(t,e)}function s(t,e){if(t)for(var i=e?[t,e]:t,n=0,o=i.length;n<o;n++)this.extend(i[n])}function g(t,e){return t instanceof s?t:new s(t,e)}function v(t,e,i){if(isNaN(t)||isNaN(e))throw new Error("Invalid LatLng object: ("+t+", "+e+")");this.lat=+t,this.lng=+e,void 0!==i&&(this.alt=+i)}function w(t,e,i){return t instanceof v?t:d(t)&&"object"!=typeof t[0]?3===t.length?new v(t[0],t[1],t[2]):2===t.length?new v(t[0],t[1]):null:null==t?t:"object"==typeof t&&"lat"in t?new v(t.lat,"lng"in t?t.lng:t.lon,t.alt):void 0===e?null:new v(t,e,i)}p.prototype={clone:function(){return new p(this.x,this.y)},add:function(t){return this.clone()._add(m(t))},_add:function(t){return this.x+=t.x,this.y+=t.y,this},subtract:function(t){return this.clone()._subtract(m(t))},_subtract:function(t){return this.x-=t.x,this.y-=t.y,this},divideBy:function(t){return this.clone()._divideBy(t)},_divideBy:function(t){return this.x/=t,this.y/=t,this},multiplyBy:function(t){return this.clone()._multiplyBy(t)},_multiplyBy:function(t){return this.x*=t,this.y*=t,this},scaleBy:function(t){return new p(this.x*t.x,this.y*t.y)},unscaleBy:function(t){return new p(this.x/t.x,this.y/t.y)},round:function(){return this.clone()._round()},_round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this},floor:function(){return this.clone()._floor()},_floor:function(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this},ceil:function(){return this.clone()._ceil()},_ceil:function(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this},trunc:function(){return this.clone()._trunc()},_trunc:function(){return this.x=nt(this.x),this.y=nt(this.y),this},distanceTo:function(t){var e=(t=m(t)).x-this.x,t=t.y-this.y;return Math.sqrt(e*e+t*t)},equals:function(t){return(t=m(t)).x===this.x&&t.y===this.y},contains:function(t){return t=m(t),Math.abs(t.x)<=Math.abs(this.x)&&Math.abs(t.y)<=Math.abs(this.y)},toString:function(){return"Point("+i(this.x)+", "+i(this.y)+")"}},f.prototype={extend:function(t){var e,i;if(t){if(t instanceof p||"number"==typeof t[0]||"x"in t)e=i=m(t);else if(e=(t=_(t)).min,i=t.max,!e||!i)return this;this.min||this.max?(this.min.x=Math.min(e.x,this.min.x),this.max.x=Math.max(i.x,this.max.x),this.min.y=Math.min(e.y,this.min.y),this.max.y=Math.max(i.y,this.max.y)):(this.min=e.clone(),this.max=i.clone())}return this},getCenter:function(t){return m((this.min.x+this.max.x)/2,(this.min.y+this.max.y)/2,t)},getBottomLeft:function(){return m(this.min.x,this.max.y)},getTopRight:function(){return m(this.max.x,this.min.y)},getTopLeft:function(){return this.min},getBottomRight:function(){return this.max},getSize:function(){return this.max.subtract(this.min)},contains:function(t){var e,i;return(t=("number"==typeof t[0]||t instanceof p?m:_)(t))instanceof f?(e=t.min,i=t.max):e=i=t,e.x>=this.min.x&&i.x<=this.max.x&&e.y>=this.min.y&&i.y<=this.max.y},intersects:function(t){t=_(t);var e=this.min,i=this.max,n=t.min,t=t.max,o=t.x>=e.x&&n.x<=i.x,t=t.y>=e.y&&n.y<=i.y;return o&&t},overlaps:function(t){t=_(t);var e=this.min,i=this.max,n=t.min,t=t.max,o=t.x>e.x&&n.x<i.x,t=t.y>e.y&&n.y<i.y;return o&&t},isValid:function(){return!(!this.min||!this.max)},pad:function(t){var e=this.min,i=this.max,n=Math.abs(e.x-i.x)*t,t=Math.abs(e.y-i.y)*t;return _(m(e.x-n,e.y-t),m(i.x+n,i.y+t))},equals:function(t){return!!t&&(t=_(t),this.min.equals(t.getTopLeft())&&this.max.equals(t.getBottomRight()))}},s.prototype={extend:function(t){var e,i,n=this._southWest,o=this._northEast;if(t instanceof v)i=e=t;else{if(!(t instanceof s))return t?this.extend(w(t)||g(t)):this;if(e=t._southWest,i=t._northEast,!e||!i)return this}return n||o?(n.lat=Math.min(e.lat,n.lat),n.lng=Math.min(e.lng,n.lng),o.lat=Math.max(i.lat,o.lat),o.lng=Math.max(i.lng,o.lng)):(this._southWest=new v(e.lat,e.lng),this._northEast=new v(i.lat,i.lng)),this},pad:function(t){var e=this._southWest,i=this._northEast,n=Math.abs(e.lat-i.lat)*t,t=Math.abs(e.lng-i.lng)*t;return new s(new v(e.lat-n,e.lng-t),new v(i.lat+n,i.lng+t))},getCenter:function(){return new v((this._southWest.lat+this._northEast.lat)/2,(this._southWest.lng+this._northEast.lng)/2)},getSouthWest:function(){return this._southWest},getNorthEast:function(){return this._northEast},getNorthWest:function(){return new v(this.getNorth(),this.getWest())},getSouthEast:function(){return new v(this.getSouth(),this.getEast())},getWest:function(){return this._southWest.lng},getSouth:function(){return this._southWest.lat},getEast:function(){return this._northEast.lng},getNorth:function(){return this._northEast.lat},contains:function(t){t=("number"==typeof t[0]||t instanceof v||"lat"in t?w:g)(t);var e,i,n=this._southWest,o=this._northEast;return t instanceof s?(e=t.getSouthWest(),i=t.getNorthEast()):e=i=t,e.lat>=n.lat&&i.lat<=o.lat&&e.lng>=n.lng&&i.lng<=o.lng},intersects:function(t){t=g(t);var e=this._southWest,i=this._northEast,n=t.getSouthWest(),t=t.getNorthEast(),o=t.lat>=e.lat&&n.lat<=i.lat,t=t.lng>=e.lng&&n.lng<=i.lng;return o&&t},overlaps:function(t){t=g(t);var e=this._southWest,i=this._northEast,n=t.getSouthWest(),t=t.getNorthEast(),o=t.lat>e.lat&&n.lat<i.lat,t=t.lng>e.lng&&n.lng<i.lng;return o&&t},toBBoxString:function(){return[this.getWest(),this.getSouth(),this.getEast(),this.getNorth()].join(",")},equals:function(t,e){return!!t&&(t=g(t),this._southWest.equals(t.getSouthWest(),e)&&this._northEast.equals(t.getNorthEast(),e))},isValid:function(){return!(!this._southWest||!this._northEast)}};var ot={latLngToPoint:function(t,e){t=this.projection.project(t),e=this.scale(e);return this.transformation._transform(t,e)},pointToLatLng:function(t,e){e=this.scale(e),t=this.transformation.untransform(t,e);return this.projection.unproject(t)},project:function(t){return this.projection.project(t)},unproject:function(t){return this.projection.unproject(t)},scale:function(t){return 256*Math.pow(2,t)},zoom:function(t){return Math.log(t/256)/Math.LN2},getProjectedBounds:function(t){var e;return this.infinite?null:(e=this.projection.bounds,t=this.scale(t),new f(this.transformation.transform(e.min,t),this.transformation.transform(e.max,t)))},infinite:!(v.prototype={equals:function(t,e){return!!t&&(t=w(t),Math.max(Math.abs(this.lat-t.lat),Math.abs(this.lng-t.lng))<=(void 0===e?1e-9:e))},toString:function(t){return"LatLng("+i(this.lat,t)+", "+i(this.lng,t)+")"},distanceTo:function(t){return st.distance(this,w(t))},wrap:function(){return st.wrapLatLng(this)},toBounds:function(t){var t=180*t/40075017,e=t/Math.cos(Math.PI/180*this.lat);return g([this.lat-t,this.lng-e],[this.lat+t,this.lng+e])},clone:function(){return new v(this.lat,this.lng,this.alt)}}),wrapLatLng:function(t){var e=this.wrapLng?H(t.lng,this.wrapLng,!0):t.lng;return new v(this.wrapLat?H(t.lat,this.wrapLat,!0):t.lat,e,t.alt)},wrapLatLngBounds:function(t){var e=t.getCenter(),i=this.wrapLatLng(e),n=e.lat-i.lat,e=e.lng-i.lng;return 0==n&&0==e?t:(i=t.getSouthWest(),t=t.getNorthEast(),new s(new v(i.lat-n,i.lng-e),new v(t.lat-n,t.lng-e)))}},st=l({},ot,{wrapLng:[-180,180],R:6371e3,distance:function(t,e){var i=Math.PI/180,n=t.lat*i,o=e.lat*i,s=Math.sin((e.lat-t.lat)*i/2),e=Math.sin((e.lng-t.lng)*i/2),t=s*s+Math.cos(n)*Math.cos(o)*e*e,i=2*Math.atan2(Math.sqrt(t),Math.sqrt(1-t));return this.R*i}}),rt=6378137,rt={R:rt,MAX_LATITUDE:85.0511287798,project:function(t){var e=Math.PI/180,i=this.MAX_LATITUDE,i=Math.max(Math.min(i,t.lat),-i),i=Math.sin(i*e);return new p(this.R*t.lng*e,this.R*Math.log((1+i)/(1-i))/2)},unproject:function(t){var e=180/Math.PI;return new v((2*Math.atan(Math.exp(t.y/this.R))-Math.PI/2)*e,t.x*e/this.R)},bounds:new f([-(rt=rt*Math.PI),-rt],[rt,rt])};function at(t,e,i,n){d(t)?(this._a=t[0],this._b=t[1],this._c=t[2],this._d=t[3]):(this._a=t,this._b=e,this._c=i,this._d=n)}function ht(t,e,i,n){return new at(t,e,i,n)}at.prototype={transform:function(t,e){return this._transform(t.clone(),e)},_transform:function(t,e){return t.x=(e=e||1)*(this._a*t.x+this._b),t.y=e*(this._c*t.y+this._d),t},untransform:function(t,e){return new p((t.x/(e=e||1)-this._b)/this._a,(t.y/e-this._d)/this._c)}};var lt=l({},st,{code:"EPSG:3857",projection:rt,transformation:ht(lt=.5/(Math.PI*rt.R),.5,-lt,.5)}),ut=l({},lt,{code:"EPSG:900913"});function ct(t){return document.createElementNS("http://www.w3.org/2000/svg",t)}function dt(t,e){for(var i,n,o,s,r="",a=0,h=t.length;a<h;a++){for(i=0,n=(o=t[a]).length;i<n;i++)r+=(i?"L":"M")+(s=o[i]).x+" "+s.y;r+=e?b.svg?"z":"x":""}return r||"M0 0"}var _t=document.documentElement.style,pt="ActiveXObject"in window,mt=pt&&!document.addEventListener,n="msLaunchUri"in navigator&&!("documentMode"in document),ft=y("webkit"),gt=y("android"),vt=y("android 2")||y("android 3"),yt=parseInt(/WebKit\/([0-9]+)|$/.exec(navigator.userAgent)[1],10),yt=gt&&y("Google")&&yt<537&&!("AudioNode"in window),xt=!!window.opera,wt=!n&&y("chrome"),bt=y("gecko")&&!ft&&!xt&&!pt,Pt=!wt&&y("safari"),Lt=y("phantom"),o="OTransition"in _t,Tt=0===navigator.platform.indexOf("Win"),Mt=pt&&"transition"in _t,zt="WebKitCSSMatrix"in window&&"m11"in new window.WebKitCSSMatrix&&!vt,_t="MozPerspective"in _t,Ct=!window.L_DISABLE_3D&&(Mt||zt||_t)&&!o&&!Lt,Zt="undefined"!=typeof orientation||y("mobile"),St=Zt&&ft,Et=Zt&&zt,kt=!window.PointerEvent&&window.MSPointerEvent,Ot=!(!window.PointerEvent&&!kt),At="ontouchstart"in window||!!window.TouchEvent,Bt=!window.L_NO_TOUCH&&(At||Ot),It=Zt&&xt,Rt=Zt&&bt,Nt=1<(window.devicePixelRatio||window.screen.deviceXDPI/window.screen.logicalXDPI),Dt=function(){var t=!1;try{var e=Object.defineProperty({},"passive",{get:function(){t=!0}});window.addEventListener("testPassiveEventSupport",u,e),window.removeEventListener("testPassiveEventSupport",u,e)}catch(t){}return t}(),jt=!!document.createElement("canvas").getContext,Ht=!(!document.createElementNS||!ct("svg").createSVGRect),Wt=!!Ht&&((Wt=document.createElement("div")).innerHTML="<svg/>","http://www.w3.org/2000/svg"===(Wt.firstChild&&Wt.firstChild.namespaceURI));function y(t){return 0<=navigator.userAgent.toLowerCase().indexOf(t)}var b={ie:pt,ielt9:mt,edge:n,webkit:ft,android:gt,android23:vt,androidStock:yt,opera:xt,chrome:wt,gecko:bt,safari:Pt,phantom:Lt,opera12:o,win:Tt,ie3d:Mt,webkit3d:zt,gecko3d:_t,any3d:Ct,mobile:Zt,mobileWebkit:St,mobileWebkit3d:Et,msPointer:kt,pointer:Ot,touch:Bt,touchNative:At,mobileOpera:It,mobileGecko:Rt,retina:Nt,passiveEvents:Dt,canvas:jt,svg:Ht,vml:!Ht&&function(){try{var t=document.createElement("div"),e=(t.innerHTML='<v:shape adj="1"/>',t.firstChild);return e.style.behavior="url(#default#VML)",e&&"object"==typeof e.adj}catch(t){return!1}}(),inlineSvg:Wt,mac:0===navigator.platform.indexOf("Mac"),linux:0===navigator.platform.indexOf("Linux")},Ft=b.msPointer?"MSPointerDown":"pointerdown",Ut=b.msPointer?"MSPointerMove":"pointermove",Vt=b.msPointer?"MSPointerUp":"pointerup",qt=b.msPointer?"MSPointerCancel":"pointercancel",Gt={touchstart:Ft,touchmove:Ut,touchend:Vt,touchcancel:qt},Kt={touchstart:function(t,e){e.MSPOINTER_TYPE_TOUCH&&e.pointerType===e.MSPOINTER_TYPE_TOUCH&&O(e);ee(t,e)},touchmove:ee,touchend:ee,touchcancel:ee},Yt={},Xt=!1;function Jt(t,e,i){return"touchstart"!==e||Xt||(document.addEventListener(Ft,$t,!0),document.addEventListener(Ut,Qt,!0),document.addEventListener(Vt,te,!0),document.addEventListener(qt,te,!0),Xt=!0),Kt[e]?(i=Kt[e].bind(this,i),t.addEventListener(Gt[e],i,!1),i):(console.warn("wrong event specified:",e),u)}function $t(t){Yt[t.pointerId]=t}function Qt(t){Yt[t.pointerId]&&(Yt[t.pointerId]=t)}function te(t){delete Yt[t.pointerId]}function ee(t,e){if(e.pointerType!==(e.MSPOINTER_TYPE_MOUSE||"mouse")){for(var i in e.touches=[],Yt)e.touches.push(Yt[i]);e.changedTouches=[e],t(e)}}var ie=200;function ne(t,i){t.addEventListener("dblclick",i);var n,o=0;function e(t){var e;1!==t.detail?n=t.detail:"mouse"===t.pointerType||t.sourceCapabilities&&!t.sourceCapabilities.firesTouchEvents||((e=Ne(t)).some(function(t){return t instanceof HTMLLabelElement&&t.attributes.for})&&!e.some(function(t){return t instanceof HTMLInputElement||t instanceof HTMLSelectElement})||((e=Date.now())-o<=ie?2===++n&&i(function(t){var e,i,n={};for(i in t)e=t[i],n[i]=e&&e.bind?e.bind(t):e;return(t=n).type="dblclick",n.detail=2,n.isTrusted=!1,n._simulated=!0,n}(t)):n=1,o=e))}return t.addEventListener("click",e),{dblclick:i,simDblclick:e}}var oe,se,re,ae,he,le,ue=we(["transform","webkitTransform","OTransform","MozTransform","msTransform"]),ce=we(["webkitTransition","transition","OTransition","MozTransition","msTransition"]),de="webkitTransition"===ce||"OTransition"===ce?ce+"End":"transitionend";function _e(t){return"string"==typeof t?document.getElementById(t):t}function pe(t,e){var i=t.style[e]||t.currentStyle&&t.currentStyle[e];return"auto"===(i=i&&"auto"!==i||!document.defaultView?i:(t=document.defaultView.getComputedStyle(t,null))?t[e]:null)?null:i}function P(t,e,i){t=document.createElement(t);return t.className=e||"",i&&i.appendChild(t),t}function T(t){var e=t.parentNode;e&&e.removeChild(t)}function me(t){for(;t.firstChild;)t.removeChild(t.firstChild)}function fe(t){var e=t.parentNode;e&&e.lastChild!==t&&e.appendChild(t)}function ge(t){var e=t.parentNode;e&&e.firstChild!==t&&e.insertBefore(t,e.firstChild)}function ve(t,e){return void 0!==t.classList?t.classList.contains(e):0<(t=xe(t)).length&&new RegExp("(^|\\s)"+e+"(\\s|$)").test(t)}function M(t,e){var i;if(void 0!==t.classList)for(var n=F(e),o=0,s=n.length;o<s;o++)t.classList.add(n[o]);else ve(t,e)||ye(t,((i=xe(t))?i+" ":"")+e)}function z(t,e){void 0!==t.classList?t.classList.remove(e):ye(t,W((" "+xe(t)+" ").replace(" "+e+" "," ")))}function ye(t,e){void 0===t.className.baseVal?t.className=e:t.className.baseVal=e}function xe(t){return void 0===(t=t.correspondingElement?t.correspondingElement:t).className.baseVal?t.className:t.className.baseVal}function C(t,e){if("opacity"in t.style)t.style.opacity=e;else if("filter"in t.style){var i=!1,n="DXImageTransform.Microsoft.Alpha";try{i=t.filters.item(n)}catch(t){if(1===e)return}e=Math.round(100*e),i?(i.Enabled=100!==e,i.Opacity=e):t.style.filter+=" progid:"+n+"(opacity="+e+")"}}function we(t){for(var e=document.documentElement.style,i=0;i<t.length;i++)if(t[i]in e)return t[i];return!1}function be(t,e,i){e=e||new p(0,0);t.style[ue]=(b.ie3d?"translate("+e.x+"px,"+e.y+"px)":"translate3d("+e.x+"px,"+e.y+"px,0)")+(i?" scale("+i+")":"")}function Z(t,e){t._leaflet_pos=e,b.any3d?be(t,e):(t.style.left=e.x+"px",t.style.top=e.y+"px")}function Pe(t){return t._leaflet_pos||new p(0,0)}function Le(){S(window,"dragstart",O)}function Te(){k(window,"dragstart",O)}function Me(t){for(;-1===t.tabIndex;)t=t.parentNode;t.style&&(ze(),le=(he=t).style.outlineStyle,t.style.outlineStyle="none",S(window,"keydown",ze))}function ze(){he&&(he.style.outlineStyle=le,le=he=void 0,k(window,"keydown",ze))}function Ce(t){for(;!((t=t.parentNode).offsetWidth&&t.offsetHeight||t===document.body););return t}function Ze(t){var e=t.getBoundingClientRect();return{x:e.width/t.offsetWidth||1,y:e.height/t.offsetHeight||1,boundingClientRect:e}}ae="onselectstart"in document?(re=function(){S(window,"selectstart",O)},function(){k(window,"selectstart",O)}):(se=we(["userSelect","WebkitUserSelect","OUserSelect","MozUserSelect","msUserSelect"]),re=function(){var t;se&&(t=document.documentElement.style,oe=t[se],t[se]="none")},function(){se&&(document.documentElement.style[se]=oe,oe=void 0)});pt={__proto__:null,TRANSFORM:ue,TRANSITION:ce,TRANSITION_END:de,get:_e,getStyle:pe,create:P,remove:T,empty:me,toFront:fe,toBack:ge,hasClass:ve,addClass:M,removeClass:z,setClass:ye,getClass:xe,setOpacity:C,testProp:we,setTransform:be,setPosition:Z,getPosition:Pe,get disableTextSelection(){return re},get enableTextSelection(){return ae},disableImageDrag:Le,enableImageDrag:Te,preventOutline:Me,restoreOutline:ze,getSizedParentNode:Ce,getScale:Ze};function S(t,e,i,n){if(e&&"object"==typeof e)for(var o in e)ke(t,o,e[o],i);else for(var s=0,r=(e=F(e)).length;s<r;s++)ke(t,e[s],i,n);return this}var E="_leaflet_events";function k(t,e,i,n){if(1===arguments.length)Se(t),delete t[E];else if(e&&"object"==typeof e)for(var o in e)Oe(t,o,e[o],i);else if(e=F(e),2===arguments.length)Se(t,function(t){return-1!==G(e,t)});else for(var s=0,r=e.length;s<r;s++)Oe(t,e[s],i,n);return this}function Se(t,e){for(var i in t[E]){var n=i.split(/\d/)[0];e&&!e(n)||Oe(t,n,null,null,i)}}var Ee={mouseenter:"mouseover",mouseleave:"mouseout",wheel:!("onwheel"in window)&&"mousewheel"};function ke(e,t,i,n){var o,s,r=t+h(i)+(n?"_"+h(n):"");e[E]&&e[E][r]||(s=o=function(t){return i.call(n||e,t||window.event)},!b.touchNative&&b.pointer&&0===t.indexOf("touch")?o=Jt(e,t,o):b.touch&&"dblclick"===t?o=ne(e,o):"addEventListener"in e?"touchstart"===t||"touchmove"===t||"wheel"===t||"mousewheel"===t?e.addEventListener(Ee[t]||t,o,!!b.passiveEvents&&{passive:!1}):"mouseenter"===t||"mouseleave"===t?e.addEventListener(Ee[t],o=function(t){t=t||window.event,We(e,t)&&s(t)},!1):e.addEventListener(t,s,!1):e.attachEvent("on"+t,o),e[E]=e[E]||{},e[E][r]=o)}function Oe(t,e,i,n,o){o=o||e+h(i)+(n?"_"+h(n):"");var s,r,i=t[E]&&t[E][o];i&&(!b.touchNative&&b.pointer&&0===e.indexOf("touch")?(n=t,r=i,Gt[s=e]?n.removeEventListener(Gt[s],r,!1):console.warn("wrong event specified:",s)):b.touch&&"dblclick"===e?(n=i,(r=t).removeEventListener("dblclick",n.dblclick),r.removeEventListener("click",n.simDblclick)):"removeEventListener"in t?t.removeEventListener(Ee[e]||e,i,!1):t.detachEvent("on"+e,i),t[E][o]=null)}function Ae(t){return t.stopPropagation?t.stopPropagation():t.originalEvent?t.originalEvent._stopped=!0:t.cancelBubble=!0,this}function Be(t){return ke(t,"wheel",Ae),this}function Ie(t){return S(t,"mousedown touchstart dblclick contextmenu",Ae),t._leaflet_disable_click=!0,this}function O(t){return t.preventDefault?t.preventDefault():t.returnValue=!1,this}function Re(t){return O(t),Ae(t),this}function Ne(t){if(t.composedPath)return t.composedPath();for(var e=[],i=t.target;i;)e.push(i),i=i.parentNode;return e}function De(t,e){var i,n;return e?(n=(i=Ze(e)).boundingClientRect,new p((t.clientX-n.left)/i.x-e.clientLeft,(t.clientY-n.top)/i.y-e.clientTop)):new p(t.clientX,t.clientY)}var je=b.linux&&b.chrome?window.devicePixelRatio:b.mac?3*window.devicePixelRatio:0<window.devicePixelRatio?2*window.devicePixelRatio:1;function He(t){return b.edge?t.wheelDeltaY/2:t.deltaY&&0===t.deltaMode?-t.deltaY/je:t.deltaY&&1===t.deltaMode?20*-t.deltaY:t.deltaY&&2===t.deltaMode?60*-t.deltaY:t.deltaX||t.deltaZ?0:t.wheelDelta?(t.wheelDeltaY||t.wheelDelta)/2:t.detail&&Math.abs(t.detail)<32765?20*-t.detail:t.detail?t.detail/-32765*60:0}function We(t,e){var i=e.relatedTarget;if(!i)return!0;try{for(;i&&i!==t;)i=i.parentNode}catch(t){return!1}return i!==t}var mt={__proto__:null,on:S,off:k,stopPropagation:Ae,disableScrollPropagation:Be,disableClickPropagation:Ie,preventDefault:O,stop:Re,getPropagationPath:Ne,getMousePosition:De,getWheelDelta:He,isExternalTarget:We,addListener:S,removeListener:k},Fe=it.extend({run:function(t,e,i,n){this.stop(),this._el=t,this._inProgress=!0,this._duration=i||.25,this._easeOutPower=1/Math.max(n||.5,.2),this._startPos=Pe(t),this._offset=e.subtract(this._startPos),this._startTime=+new Date,this.fire("start"),this._animate()},stop:function(){this._inProgress&&(this._step(!0),this._complete())},_animate:function(){this._animId=x(this._animate,this),this._step()},_step:function(t){var e=+new Date-this._startTime,i=1e3*this._duration;e<i?this._runFrame(this._easeOut(e/i),t):(this._runFrame(1),this._complete())},_runFrame:function(t,e){t=this._startPos.add(this._offset.multiplyBy(t));e&&t._round(),Z(this._el,t),this.fire("step")},_complete:function(){r(this._animId),this._inProgress=!1,this.fire("end")},_easeOut:function(t){return 1-Math.pow(1-t,this._easeOutPower)}}),A=it.extend({options:{crs:lt,center:void 0,zoom:void 0,minZoom:void 0,maxZoom:void 0,layers:[],maxBounds:void 0,renderer:void 0,zoomAnimation:!0,zoomAnimationThreshold:4,fadeAnimation:!0,markerZoomAnimation:!0,transform3DLimit:8388608,zoomSnap:1,zoomDelta:1,trackResize:!0},initialize:function(t,e){e=c(this,e),this._handlers=[],this._layers={},this._zoomBoundLayers={},this._sizeChanged=!0,this._initContainer(t),this._initLayout(),this._onResize=a(this._onResize,this),this._initEvents(),e.maxBounds&&this.setMaxBounds(e.maxBounds),void 0!==e.zoom&&(this._zoom=this._limitZoom(e.zoom)),e.center&&void 0!==e.zoom&&this.setView(w(e.center),e.zoom,{reset:!0}),this.callInitHooks(),this._zoomAnimated=ce&&b.any3d&&!b.mobileOpera&&this.options.zoomAnimation,this._zoomAnimated&&(this._createAnimProxy(),S(this._proxy,de,this._catchTransitionEnd,this)),this._addLayers(this.options.layers)},setView:function(t,e,i){if((e=void 0===e?this._zoom:this._limitZoom(e),t=this._limitCenter(w(t),e,this.options.maxBounds),i=i||{},this._stop(),this._loaded&&!i.reset&&!0!==i)&&(void 0!==i.animate&&(i.zoom=l({animate:i.animate},i.zoom),i.pan=l({animate:i.animate,duration:i.duration},i.pan)),this._zoom!==e?this._tryAnimatedZoom&&this._tryAnimatedZoom(t,e,i.zoom):this._tryAnimatedPan(t,i.pan)))return clearTimeout(this._sizeTimer),this;return this._resetView(t,e,i.pan&&i.pan.noMoveStart),this},setZoom:function(t,e){return this._loaded?this.setView(this.getCenter(),t,{zoom:e}):(this._zoom=t,this)},zoomIn:function(t,e){return t=t||(b.any3d?this.options.zoomDelta:1),this.setZoom(this._zoom+t,e)},zoomOut:function(t,e){return t=t||(b.any3d?this.options.zoomDelta:1),this.setZoom(this._zoom-t,e)},setZoomAround:function(t,e,i){var n=this.getZoomScale(e),o=this.getSize().divideBy(2),t=(t instanceof p?t:this.latLngToContainerPoint(t)).subtract(o).multiplyBy(1-1/n),n=this.containerPointToLatLng(o.add(t));return this.setView(n,e,{zoom:i})},_getBoundsCenterZoom:function(t,e){e=e||{},t=t.getBounds?t.getBounds():g(t);var i=m(e.paddingTopLeft||e.padding||[0,0]),n=m(e.paddingBottomRight||e.padding||[0,0]),o=this.getBoundsZoom(t,!1,i.add(n));return(o="number"==typeof e.maxZoom?Math.min(e.maxZoom,o):o)===1/0?{center:t.getCenter(),zoom:o}:(e=n.subtract(i).divideBy(2),n=this.project(t.getSouthWest(),o),i=this.project(t.getNorthEast(),o),{center:this.unproject(n.add(i).divideBy(2).add(e),o),zoom:o})},fitBounds:function(t,e){if((t=g(t)).isValid())return t=this._getBoundsCenterZoom(t,e),this.setView(t.center,t.zoom,e);throw new Error("Bounds are not valid.")},fitWorld:function(t){return this.fitBounds([[-90,-180],[90,180]],t)},panTo:function(t,e){return this.setView(t,this._zoom,{pan:e})},panBy:function(t,e){var i;return e=e||{},(t=m(t).round()).x||t.y?(!0===e.animate||this.getSize().contains(t)?(this._panAnim||(this._panAnim=new Fe,this._panAnim.on({step:this._onPanTransitionStep,end:this._onPanTransitionEnd},this)),e.noMoveStart||this.fire("movestart"),!1!==e.animate?(M(this._mapPane,"leaflet-pan-anim"),i=this._getMapPanePos().subtract(t).round(),this._panAnim.run(this._mapPane,i,e.duration||.25,e.easeLinearity)):(this._rawPanBy(t),this.fire("move").fire("moveend"))):this._resetView(this.unproject(this.project(this.getCenter()).add(t)),this.getZoom()),this):this.fire("moveend")},flyTo:function(n,o,t){if(!1===(t=t||{}).animate||!b.any3d)return this.setView(n,o,t);this._stop();var s=this.project(this.getCenter()),r=this.project(n),e=this.getSize(),a=this._zoom,h=(n=w(n),o=void 0===o?a:o,Math.max(e.x,e.y)),i=h*this.getZoomScale(a,o),l=r.distanceTo(s)||1,u=1.42,c=u*u;function d(t){t=(i*i-h*h+(t?-1:1)*c*c*l*l)/(2*(t?i:h)*c*l),t=Math.sqrt(t*t+1)-t;return t<1e-9?-18:Math.log(t)}function _(t){return(Math.exp(t)-Math.exp(-t))/2}function p(t){return(Math.exp(t)+Math.exp(-t))/2}var m=d(0);function f(t){return h*(p(m)*(_(t=m+u*t)/p(t))-_(m))/c}var g=Date.now(),v=(d(1)-m)/u,y=t.duration?1e3*t.duration:1e3*v*.8;return this._moveStart(!0,t.noMoveStart),function t(){var e=(Date.now()-g)/y,i=(1-Math.pow(1-e,1.5))*v;e<=1?(this._flyToFrame=x(t,this),this._move(this.unproject(s.add(r.subtract(s).multiplyBy(f(i)/l)),a),this.getScaleZoom(h/(e=i,h*(p(m)/p(m+u*e))),a),{flyTo:!0})):this._move(n,o)._moveEnd(!0)}.call(this),this},flyToBounds:function(t,e){t=this._getBoundsCenterZoom(t,e);return this.flyTo(t.center,t.zoom,e)},setMaxBounds:function(t){return t=g(t),this.listens("moveend",this._panInsideMaxBounds)&&this.off("moveend",this._panInsideMaxBounds),t.isValid()?(this.options.maxBounds=t,this._loaded&&this._panInsideMaxBounds(),this.on("moveend",this._panInsideMaxBounds)):(this.options.maxBounds=null,this)},setMinZoom:function(t){var e=this.options.minZoom;return this.options.minZoom=t,this._loaded&&e!==t&&(this.fire("zoomlevelschange"),this.getZoom()<this.options.minZoom)?this.setZoom(t):this},setMaxZoom:function(t){var e=this.options.maxZoom;return this.options.maxZoom=t,this._loaded&&e!==t&&(this.fire("zoomlevelschange"),this.getZoom()>this.options.maxZoom)?this.setZoom(t):this},panInsideBounds:function(t,e){this._enforcingBounds=!0;var i=this.getCenter(),t=this._limitCenter(i,this._zoom,g(t));return i.equals(t)||this.panTo(t,e),this._enforcingBounds=!1,this},panInside:function(t,e){var i=m((e=e||{}).paddingTopLeft||e.padding||[0,0]),n=m(e.paddingBottomRight||e.padding||[0,0]),o=this.project(this.getCenter()),t=this.project(t),s=this.getPixelBounds(),i=_([s.min.add(i),s.max.subtract(n)]),s=i.getSize();return i.contains(t)||(this._enforcingBounds=!0,n=t.subtract(i.getCenter()),i=i.extend(t).getSize().subtract(s),o.x+=n.x<0?-i.x:i.x,o.y+=n.y<0?-i.y:i.y,this.panTo(this.unproject(o),e),this._enforcingBounds=!1),this},invalidateSize:function(t){if(!this._loaded)return this;t=l({animate:!1,pan:!0},!0===t?{animate:!0}:t);var e=this.getSize(),i=(this._sizeChanged=!0,this._lastCenter=null,this.getSize()),n=e.divideBy(2).round(),o=i.divideBy(2).round(),n=n.subtract(o);return n.x||n.y?(t.animate&&t.pan?this.panBy(n):(t.pan&&this._rawPanBy(n),this.fire("move"),t.debounceMoveend?(clearTimeout(this._sizeTimer),this._sizeTimer=setTimeout(a(this.fire,this,"moveend"),200)):this.fire("moveend")),this.fire("resize",{oldSize:e,newSize:i})):this},stop:function(){return this.setZoom(this._limitZoom(this._zoom)),this.options.zoomSnap||this.fire("viewreset"),this._stop()},locate:function(t){var e,i;return t=this._locateOptions=l({timeout:1e4,watch:!1},t),"geolocation"in navigator?(e=a(this._handleGeolocationResponse,this),i=a(this._handleGeolocationError,this),t.watch?this._locationWatchId=navigator.geolocation.watchPosition(e,i,t):navigator.geolocation.getCurrentPosition(e,i,t)):this._handleGeolocationError({code:0,message:"Geolocation not supported."}),this},stopLocate:function(){return navigator.geolocation&&navigator.geolocation.clearWatch&&navigator.geolocation.clearWatch(this._locationWatchId),this._locateOptions&&(this._locateOptions.setView=!1),this},_handleGeolocationError:function(t){var e;this._container._leaflet_id&&(e=t.code,t=t.message||(1===e?"permission denied":2===e?"position unavailable":"timeout"),this._locateOptions.setView&&!this._loaded&&this.fitWorld(),this.fire("locationerror",{code:e,message:"Geolocation error: "+t+"."}))},_handleGeolocationResponse:function(t){if(this._container._leaflet_id){var e,i,n=new v(t.coords.latitude,t.coords.longitude),o=n.toBounds(2*t.coords.accuracy),s=this._locateOptions,r=(s.setView&&(e=this.getBoundsZoom(o),this.setView(n,s.maxZoom?Math.min(e,s.maxZoom):e)),{latlng:n,bounds:o,timestamp:t.timestamp});for(i in t.coords)"number"==typeof t.coords[i]&&(r[i]=t.coords[i]);this.fire("locationfound",r)}},addHandler:function(t,e){return e&&(e=this[t]=new e(this),this._handlers.push(e),this.options[t]&&e.enable()),this},remove:function(){if(this._initEvents(!0),this.options.maxBounds&&this.off("moveend",this._panInsideMaxBounds),this._containerId!==this._container._leaflet_id)throw new Error("Map container is being reused by another instance");try{delete this._container._leaflet_id,delete this._containerId}catch(t){this._container._leaflet_id=void 0,this._containerId=void 0}for(var t in void 0!==this._locationWatchId&&this.stopLocate(),this._stop(),T(this._mapPane),this._clearControlPos&&this._clearControlPos(),this._resizeRequest&&(r(this._resizeRequest),this._resizeRequest=null),this._clearHandlers(),this._loaded&&this.fire("unload"),this._layers)this._layers[t].remove();for(t in this._panes)T(this._panes[t]);return this._layers=[],this._panes=[],delete this._mapPane,delete this._renderer,this},createPane:function(t,e){e=P("div","leaflet-pane"+(t?" leaflet-"+t.replace("Pane","")+"-pane":""),e||this._mapPane);return t&&(this._panes[t]=e),e},getCenter:function(){return this._checkIfLoaded(),this._lastCenter&&!this._moved()?this._lastCenter.clone():this.layerPointToLatLng(this._getCenterLayerPoint())},getZoom:function(){return this._zoom},getBounds:function(){var t=this.getPixelBounds();return new s(this.unproject(t.getBottomLeft()),this.unproject(t.getTopRight()))},getMinZoom:function(){return void 0===this.options.minZoom?this._layersMinZoom||0:this.options.minZoom},getMaxZoom:function(){return void 0===this.options.maxZoom?void 0===this._layersMaxZoom?1/0:this._layersMaxZoom:this.options.maxZoom},getBoundsZoom:function(t,e,i){t=g(t),i=m(i||[0,0]);var n=this.getZoom()||0,o=this.getMinZoom(),s=this.getMaxZoom(),r=t.getNorthWest(),t=t.getSouthEast(),i=this.getSize().subtract(i),t=_(this.project(t,n),this.project(r,n)).getSize(),r=b.any3d?this.options.zoomSnap:1,a=i.x/t.x,i=i.y/t.y,t=e?Math.max(a,i):Math.min(a,i),n=this.getScaleZoom(t,n);return r&&(n=Math.round(n/(r/100))*(r/100),n=e?Math.ceil(n/r)*r:Math.floor(n/r)*r),Math.max(o,Math.min(s,n))},getSize:function(){return this._size&&!this._sizeChanged||(this._size=new p(this._container.clientWidth||0,this._container.clientHeight||0),this._sizeChanged=!1),this._size.clone()},getPixelBounds:function(t,e){t=this._getTopLeftPoint(t,e);return new f(t,t.add(this.getSize()))},getPixelOrigin:function(){return this._checkIfLoaded(),this._pixelOrigin},getPixelWorldBounds:function(t){return this.options.crs.getProjectedBounds(void 0===t?this.getZoom():t)},getPane:function(t){return"string"==typeof t?this._panes[t]:t},getPanes:function(){return this._panes},getContainer:function(){return this._container},getZoomScale:function(t,e){var i=this.options.crs;return e=void 0===e?this._zoom:e,i.scale(t)/i.scale(e)},getScaleZoom:function(t,e){var i=this.options.crs,t=(e=void 0===e?this._zoom:e,i.zoom(t*i.scale(e)));return isNaN(t)?1/0:t},project:function(t,e){return e=void 0===e?this._zoom:e,this.options.crs.latLngToPoint(w(t),e)},unproject:function(t,e){return e=void 0===e?this._zoom:e,this.options.crs.pointToLatLng(m(t),e)},layerPointToLatLng:function(t){t=m(t).add(this.getPixelOrigin());return this.unproject(t)},latLngToLayerPoint:function(t){return this.project(w(t))._round()._subtract(this.getPixelOrigin())},wrapLatLng:function(t){return this.options.crs.wrapLatLng(w(t))},wrapLatLngBounds:function(t){return this.options.crs.wrapLatLngBounds(g(t))},distance:function(t,e){return this.options.crs.distance(w(t),w(e))},containerPointToLayerPoint:function(t){return m(t).subtract(this._getMapPanePos())},layerPointToContainerPoint:function(t){return m(t).add(this._getMapPanePos())},containerPointToLatLng:function(t){t=this.containerPointToLayerPoint(m(t));return this.layerPointToLatLng(t)},latLngToContainerPoint:function(t){return this.layerPointToContainerPoint(this.latLngToLayerPoint(w(t)))},mouseEventToContainerPoint:function(t){return De(t,this._container)},mouseEventToLayerPoint:function(t){return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(t))},mouseEventToLatLng:function(t){return this.layerPointToLatLng(this.mouseEventToLayerPoint(t))},_initContainer:function(t){t=this._container=_e(t);if(!t)throw new Error("Map container not found.");if(t._leaflet_id)throw new Error("Map container is already initialized.");S(t,"scroll",this._onScroll,this),this._containerId=h(t)},_initLayout:function(){var t=this._container,e=(this._fadeAnimated=this.options.fadeAnimation&&b.any3d,M(t,"leaflet-container"+(b.touch?" leaflet-touch":"")+(b.retina?" leaflet-retina":"")+(b.ielt9?" leaflet-oldie":"")+(b.safari?" leaflet-safari":"")+(this._fadeAnimated?" leaflet-fade-anim":"")),pe(t,"position"));"absolute"!==e&&"relative"!==e&&"fixed"!==e&&"sticky"!==e&&(t.style.position="relative"),this._initPanes(),this._initControlPos&&this._initControlPos()},_initPanes:function(){var t=this._panes={};this._paneRenderers={},this._mapPane=this.createPane("mapPane",this._container),Z(this._mapPane,new p(0,0)),this.createPane("tilePane"),this.createPane("overlayPane"),this.createPane("shadowPane"),this.createPane("markerPane"),this.createPane("tooltipPane"),this.createPane("popupPane"),this.options.markerZoomAnimation||(M(t.markerPane,"leaflet-zoom-hide"),M(t.shadowPane,"leaflet-zoom-hide"))},_resetView:function(t,e,i){Z(this._mapPane,new p(0,0));var n=!this._loaded,o=(this._loaded=!0,e=this._limitZoom(e),this.fire("viewprereset"),this._zoom!==e);this._moveStart(o,i)._move(t,e)._moveEnd(o),this.fire("viewreset"),n&&this.fire("load")},_moveStart:function(t,e){return t&&this.fire("zoomstart"),e||this.fire("movestart"),this},_move:function(t,e,i,n){void 0===e&&(e=this._zoom);var o=this._zoom!==e;return this._zoom=e,this._lastCenter=t,this._pixelOrigin=this._getNewPixelOrigin(t),n?i&&i.pinch&&this.fire("zoom",i):((o||i&&i.pinch)&&this.fire("zoom",i),this.fire("move",i)),this},_moveEnd:function(t){return t&&this.fire("zoomend"),this.fire("moveend")},_stop:function(){return r(this._flyToFrame),this._panAnim&&this._panAnim.stop(),this},_rawPanBy:function(t){Z(this._mapPane,this._getMapPanePos().subtract(t))},_getZoomSpan:function(){return this.getMaxZoom()-this.getMinZoom()},_panInsideMaxBounds:function(){this._enforcingBounds||this.panInsideBounds(this.options.maxBounds)},_checkIfLoaded:function(){if(!this._loaded)throw new Error("Set map center and zoom first.")},_initEvents:function(t){this._targets={};var e=t?k:S;e((this._targets[h(this._container)]=this)._container,"click dblclick mousedown mouseup mouseover mouseout mousemove contextmenu keypress keydown keyup",this._handleDOMEvent,this),this.options.trackResize&&e(window,"resize",this._onResize,this),b.any3d&&this.options.transform3DLimit&&(t?this.off:this.on).call(this,"moveend",this._onMoveEnd)},_onResize:function(){r(this._resizeRequest),this._resizeRequest=x(function(){this.invalidateSize({debounceMoveend:!0})},this)},_onScroll:function(){this._container.scrollTop=0,this._container.scrollLeft=0},_onMoveEnd:function(){var t=this._getMapPanePos();Math.max(Math.abs(t.x),Math.abs(t.y))>=this.options.transform3DLimit&&this._resetView(this.getCenter(),this.getZoom())},_findEventTargets:function(t,e){for(var i,n=[],o="mouseout"===e||"mouseover"===e,s=t.target||t.srcElement,r=!1;s;){if((i=this._targets[h(s)])&&("click"===e||"preclick"===e)&&this._draggableMoved(i)){r=!0;break}if(i&&i.listens(e,!0)){if(o&&!We(s,t))break;if(n.push(i),o)break}if(s===this._container)break;s=s.parentNode}return n=n.length||r||o||!this.listens(e,!0)?n:[this]},_isClickDisabled:function(t){for(;t&&t!==this._container;){if(t._leaflet_disable_click)return!0;t=t.parentNode}},_handleDOMEvent:function(t){var e,i=t.target||t.srcElement;!this._loaded||i._leaflet_disable_events||"click"===t.type&&this._isClickDisabled(i)||("mousedown"===(e=t.type)&&Me(i),this._fireDOMEvent(t,e))},_mouseEvents:["click","dblclick","mouseover","mouseout","contextmenu"],_fireDOMEvent:function(t,e,i){"click"===t.type&&((a=l({},t)).type="preclick",this._fireDOMEvent(a,a.type,i));var n=this._findEventTargets(t,e);if(i){for(var o=[],s=0;s<i.length;s++)i[s].listens(e,!0)&&o.push(i[s]);n=o.concat(n)}if(n.length){"contextmenu"===e&&O(t);var r,a=n[0],h={originalEvent:t};for("keypress"!==t.type&&"keydown"!==t.type&&"keyup"!==t.type&&(r=a.getLatLng&&(!a._radius||a._radius<=10),h.containerPoint=r?this.latLngToContainerPoint(a.getLatLng()):this.mouseEventToContainerPoint(t),h.layerPoint=this.containerPointToLayerPoint(h.containerPoint),h.latlng=r?a.getLatLng():this.layerPointToLatLng(h.layerPoint)),s=0;s<n.length;s++)if(n[s].fire(e,h,!0),h.originalEvent._stopped||!1===n[s].options.bubblingMouseEvents&&-1!==G(this._mouseEvents,e))return}},_draggableMoved:function(t){return(t=t.dragging&&t.dragging.enabled()?t:this).dragging&&t.dragging.moved()||this.boxZoom&&this.boxZoom.moved()},_clearHandlers:function(){for(var t=0,e=this._handlers.length;t<e;t++)this._handlers[t].disable()},whenReady:function(t,e){return this._loaded?t.call(e||this,{target:this}):this.on("load",t,e),this},_getMapPanePos:function(){return Pe(this._mapPane)||new p(0,0)},_moved:function(){var t=this._getMapPanePos();return t&&!t.equals([0,0])},_getTopLeftPoint:function(t,e){return(t&&void 0!==e?this._getNewPixelOrigin(t,e):this.getPixelOrigin()).subtract(this._getMapPanePos())},_getNewPixelOrigin:function(t,e){var i=this.getSize()._divideBy(2);return this.project(t,e)._subtract(i)._add(this._getMapPanePos())._round()},_latLngToNewLayerPoint:function(t,e,i){i=this._getNewPixelOrigin(i,e);return this.project(t,e)._subtract(i)},_latLngBoundsToNewLayerBounds:function(t,e,i){i=this._getNewPixelOrigin(i,e);return _([this.project(t.getSouthWest(),e)._subtract(i),this.project(t.getNorthWest(),e)._subtract(i),this.project(t.getSouthEast(),e)._subtract(i),this.project(t.getNorthEast(),e)._subtract(i)])},_getCenterLayerPoint:function(){return this.containerPointToLayerPoint(this.getSize()._divideBy(2))},_getCenterOffset:function(t){return this.latLngToLayerPoint(t).subtract(this._getCenterLayerPoint())},_limitCenter:function(t,e,i){var n,o;return!i||(n=this.project(t,e),o=this.getSize().divideBy(2),o=new f(n.subtract(o),n.add(o)),o=this._getBoundsOffset(o,i,e),Math.abs(o.x)<=1&&Math.abs(o.y)<=1)?t:this.unproject(n.add(o),e)},_limitOffset:function(t,e){var i;return e?(i=new f((i=this.getPixelBounds()).min.add(t),i.max.add(t)),t.add(this._getBoundsOffset(i,e))):t},_getBoundsOffset:function(t,e,i){e=_(this.project(e.getNorthEast(),i),this.project(e.getSouthWest(),i)),i=e.min.subtract(t.min),e=e.max.subtract(t.max);return new p(this._rebound(i.x,-e.x),this._rebound(i.y,-e.y))},_rebound:function(t,e){return 0<t+e?Math.round(t-e)/2:Math.max(0,Math.ceil(t))-Math.max(0,Math.floor(e))},_limitZoom:function(t){var e=this.getMinZoom(),i=this.getMaxZoom(),n=b.any3d?this.options.zoomSnap:1;return n&&(t=Math.round(t/n)*n),Math.max(e,Math.min(i,t))},_onPanTransitionStep:function(){this.fire("move")},_onPanTransitionEnd:function(){z(this._mapPane,"leaflet-pan-anim"),this.fire("moveend")},_tryAnimatedPan:function(t,e){t=this._getCenterOffset(t)._trunc();return!(!0!==(e&&e.animate)&&!this.getSize().contains(t))&&(this.panBy(t,e),!0)},_createAnimProxy:function(){var t=this._proxy=P("div","leaflet-proxy leaflet-zoom-animated");this._panes.mapPane.appendChild(t),this.on("zoomanim",function(t){var e=ue,i=this._proxy.style[e];be(this._proxy,this.project(t.center,t.zoom),this.getZoomScale(t.zoom,1)),i===this._proxy.style[e]&&this._animatingZoom&&this._onZoomTransitionEnd()},this),this.on("load moveend",this._animMoveEnd,this),this._on("unload",this._destroyAnimProxy,this)},_destroyAnimProxy:function(){T(this._proxy),this.off("load moveend",this._animMoveEnd,this),delete this._proxy},_animMoveEnd:function(){var t=this.getCenter(),e=this.getZoom();be(this._proxy,this.project(t,e),this.getZoomScale(e,1))},_catchTransitionEnd:function(t){this._animatingZoom&&0<=t.propertyName.indexOf("transform")&&this._onZoomTransitionEnd()},_nothingToAnimate:function(){return!this._container.getElementsByClassName("leaflet-zoom-animated").length},_tryAnimatedZoom:function(t,e,i){if(!this._animatingZoom){if(i=i||{},!this._zoomAnimated||!1===i.animate||this._nothingToAnimate()||Math.abs(e-this._zoom)>this.options.zoomAnimationThreshold)return!1;var n=this.getZoomScale(e),n=this._getCenterOffset(t)._divideBy(1-1/n);if(!0!==i.animate&&!this.getSize().contains(n))return!1;x(function(){this._moveStart(!0,i.noMoveStart||!1)._animateZoom(t,e,!0)},this)}return!0},_animateZoom:function(t,e,i,n){this._mapPane&&(i&&(this._animatingZoom=!0,this._animateToCenter=t,this._animateToZoom=e,M(this._mapPane,"leaflet-zoom-anim")),this.fire("zoomanim",{center:t,zoom:e,noUpdate:n}),this._tempFireZoomEvent||(this._tempFireZoomEvent=this._zoom!==this._animateToZoom),this._move(this._animateToCenter,this._animateToZoom,void 0,!0),setTimeout(a(this._onZoomTransitionEnd,this),250))},_onZoomTransitionEnd:function(){this._animatingZoom&&(this._mapPane&&z(this._mapPane,"leaflet-zoom-anim"),this._animatingZoom=!1,this._move(this._animateToCenter,this._animateToZoom,void 0,!0),this._tempFireZoomEvent&&this.fire("zoom"),delete this._tempFireZoomEvent,this.fire("move"),this._moveEnd(!0))}});function Ue(t){return new B(t)}var B=et.extend({options:{position:"topright"},initialize:function(t){c(this,t)},getPosition:function(){return this.options.position},setPosition:function(t){var e=this._map;return e&&e.removeControl(this),this.options.position=t,e&&e.addControl(this),this},getContainer:function(){return this._container},addTo:function(t){this.remove(),this._map=t;var e=this._container=this.onAdd(t),i=this.getPosition(),t=t._controlCorners[i];return M(e,"leaflet-control"),-1!==i.indexOf("bottom")?t.insertBefore(e,t.firstChild):t.appendChild(e),this._map.on("unload",this.remove,this),this},remove:function(){return this._map&&(T(this._container),this.onRemove&&this.onRemove(this._map),this._map.off("unload",this.remove,this),this._map=null),this},_refocusOnMap:function(t){this._map&&t&&0<t.screenX&&0<t.screenY&&this._map.getContainer().focus()}}),Ve=(A.include({addControl:function(t){return t.addTo(this),this},removeControl:function(t){return t.remove(),this},_initControlPos:function(){var i=this._controlCorners={},n="leaflet-",o=this._controlContainer=P("div",n+"control-container",this._container);function t(t,e){i[t+e]=P("div",n+t+" "+n+e,o)}t("top","left"),t("top","right"),t("bottom","left"),t("bottom","right")},_clearControlPos:function(){for(var t in this._controlCorners)T(this._controlCorners[t]);T(this._controlContainer),delete this._controlCorners,delete this._controlContainer}}),B.extend({options:{collapsed:!0,position:"topright",autoZIndex:!0,hideSingleBase:!1,sortLayers:!1,sortFunction:function(t,e,i,n){return i<n?-1:n<i?1:0}},initialize:function(t,e,i){for(var n in c(this,i),this._layerControlInputs=[],this._layers=[],this._lastZIndex=0,this._handlingClick=!1,this._preventClick=!1,t)this._addLayer(t[n],n);for(n in e)this._addLayer(e[n],n,!0)},onAdd:function(t){this._initLayout(),this._update(),(this._map=t).on("zoomend",this._checkDisabledLayers,this);for(var e=0;e<this._layers.length;e++)this._layers[e].layer.on("add remove",this._onLayerChange,this);return this._container},addTo:function(t){return B.prototype.addTo.call(this,t),this._expandIfNotCollapsed()},onRemove:function(){this._map.off("zoomend",this._checkDisabledLayers,this);for(var t=0;t<this._layers.length;t++)this._layers[t].layer.off("add remove",this._onLayerChange,this)},addBaseLayer:function(t,e){return this._addLayer(t,e),this._map?this._update():this},addOverlay:function(t,e){return this._addLayer(t,e,!0),this._map?this._update():this},removeLayer:function(t){t.off("add remove",this._onLayerChange,this);t=this._getLayer(h(t));return t&&this._layers.splice(this._layers.indexOf(t),1),this._map?this._update():this},expand:function(){M(this._container,"leaflet-control-layers-expanded"),this._section.style.height=null;var t=this._map.getSize().y-(this._container.offsetTop+50);return t<this._section.clientHeight?(M(this._section,"leaflet-control-layers-scrollbar"),this._section.style.height=t+"px"):z(this._section,"leaflet-control-layers-scrollbar"),this._checkDisabledLayers(),this},collapse:function(){return z(this._container,"leaflet-control-layers-expanded"),this},_initLayout:function(){var t="leaflet-control-layers",e=this._container=P("div",t),i=this.options.collapsed,n=(e.setAttribute("aria-haspopup",!0),Ie(e),Be(e),this._section=P("section",t+"-list")),o=(i&&(this._map.on("click",this.collapse,this),S(e,{mouseenter:this._expandSafely,mouseleave:this.collapse},this)),this._layersLink=P("a",t+"-toggle",e));o.href="#",o.title="Layers",o.setAttribute("role","button"),S(o,{keydown:function(t){13===t.keyCode&&this._expandSafely()},click:function(t){O(t),this._expandSafely()}},this),i||this.expand(),this._baseLayersList=P("div",t+"-base",n),this._separator=P("div",t+"-separator",n),this._overlaysList=P("div",t+"-overlays",n),e.appendChild(n)},_getLayer:function(t){for(var e=0;e<this._layers.length;e++)if(this._layers[e]&&h(this._layers[e].layer)===t)return this._layers[e]},_addLayer:function(t,e,i){this._map&&t.on("add remove",this._onLayerChange,this),this._layers.push({layer:t,name:e,overlay:i}),this.options.sortLayers&&this._layers.sort(a(function(t,e){return this.options.sortFunction(t.layer,e.layer,t.name,e.name)},this)),this.options.autoZIndex&&t.setZIndex&&(this._lastZIndex++,t.setZIndex(this._lastZIndex)),this._expandIfNotCollapsed()},_update:function(){if(this._container){me(this._baseLayersList),me(this._overlaysList),this._layerControlInputs=[];for(var t,e,i,n=0,o=0;o<this._layers.length;o++)i=this._layers[o],this._addItem(i),e=e||i.overlay,t=t||!i.overlay,n+=i.overlay?0:1;this.options.hideSingleBase&&(this._baseLayersList.style.display=(t=t&&1<n)?"":"none"),this._separator.style.display=e&&t?"":"none"}return this},_onLayerChange:function(t){this._handlingClick||this._update();var e=this._getLayer(h(t.target)),t=e.overlay?"add"===t.type?"overlayadd":"overlayremove":"add"===t.type?"baselayerchange":null;t&&this._map.fire(t,e)},_createRadioElement:function(t,e){t='<input type="radio" class="leaflet-control-layers-selector" name="'+t+'"'+(e?' checked="checked"':"")+"/>",e=document.createElement("div");return e.innerHTML=t,e.firstChild},_addItem:function(t){var e,i=document.createElement("label"),n=this._map.hasLayer(t.layer),n=(t.overlay?((e=document.createElement("input")).type="checkbox",e.className="leaflet-control-layers-selector",e.defaultChecked=n):e=this._createRadioElement("leaflet-base-layers_"+h(this),n),this._layerControlInputs.push(e),e.layerId=h(t.layer),S(e,"click",this._onInputClick,this),document.createElement("span")),o=(n.innerHTML=" "+t.name,document.createElement("span"));return i.appendChild(o),o.appendChild(e),o.appendChild(n),(t.overlay?this._overlaysList:this._baseLayersList).appendChild(i),this._checkDisabledLayers(),i},_onInputClick:function(){if(!this._preventClick){var t,e,i=this._layerControlInputs,n=[],o=[];this._handlingClick=!0;for(var s=i.length-1;0<=s;s--)t=i[s],e=this._getLayer(t.layerId).layer,t.checked?n.push(e):t.checked||o.push(e);for(s=0;s<o.length;s++)this._map.hasLayer(o[s])&&this._map.removeLayer(o[s]);for(s=0;s<n.length;s++)this._map.hasLayer(n[s])||this._map.addLayer(n[s]);this._handlingClick=!1,this._refocusOnMap()}},_checkDisabledLayers:function(){for(var t,e,i=this._layerControlInputs,n=this._map.getZoom(),o=i.length-1;0<=o;o--)t=i[o],e=this._getLayer(t.layerId).layer,t.disabled=void 0!==e.options.minZoom&&n<e.options.minZoom||void 0!==e.options.maxZoom&&n>e.options.maxZoom},_expandIfNotCollapsed:function(){return this._map&&!this.options.collapsed&&this.expand(),this},_expandSafely:function(){var t=this._section,e=(this._preventClick=!0,S(t,"click",O),this.expand(),this);setTimeout(function(){k(t,"click",O),e._preventClick=!1})}})),qe=B.extend({options:{position:"topleft",zoomInText:'<span aria-hidden="true">+</span>',zoomInTitle:"Zoom in",zoomOutText:'<span aria-hidden="true">&#x2212;</span>',zoomOutTitle:"Zoom out"},onAdd:function(t){var e="leaflet-control-zoom",i=P("div",e+" leaflet-bar"),n=this.options;return this._zoomInButton=this._createButton(n.zoomInText,n.zoomInTitle,e+"-in",i,this._zoomIn),this._zoomOutButton=this._createButton(n.zoomOutText,n.zoomOutTitle,e+"-out",i,this._zoomOut),this._updateDisabled(),t.on("zoomend zoomlevelschange",this._updateDisabled,this),i},onRemove:function(t){t.off("zoomend zoomlevelschange",this._updateDisabled,this)},disable:function(){return this._disabled=!0,this._updateDisabled(),this},enable:function(){return this._disabled=!1,this._updateDisabled(),this},_zoomIn:function(t){!this._disabled&&this._map._zoom<this._map.getMaxZoom()&&this._map.zoomIn(this._map.options.zoomDelta*(t.shiftKey?3:1))},_zoomOut:function(t){!this._disabled&&this._map._zoom>this._map.getMinZoom()&&this._map.zoomOut(this._map.options.zoomDelta*(t.shiftKey?3:1))},_createButton:function(t,e,i,n,o){i=P("a",i,n);return i.innerHTML=t,i.href="#",i.title=e,i.setAttribute("role","button"),i.setAttribute("aria-label",e),Ie(i),S(i,"click",Re),S(i,"click",o,this),S(i,"click",this._refocusOnMap,this),i},_updateDisabled:function(){var t=this._map,e="leaflet-disabled";z(this._zoomInButton,e),z(this._zoomOutButton,e),this._zoomInButton.setAttribute("aria-disabled","false"),this._zoomOutButton.setAttribute("aria-disabled","false"),!this._disabled&&t._zoom!==t.getMinZoom()||(M(this._zoomOutButton,e),this._zoomOutButton.setAttribute("aria-disabled","true")),!this._disabled&&t._zoom!==t.getMaxZoom()||(M(this._zoomInButton,e),this._zoomInButton.setAttribute("aria-disabled","true"))}}),Ge=(A.mergeOptions({zoomControl:!0}),A.addInitHook(function(){this.options.zoomControl&&(this.zoomControl=new qe,this.addControl(this.zoomControl))}),B.extend({options:{position:"bottomleft",maxWidth:100,metric:!0,imperial:!0},onAdd:function(t){var e="leaflet-control-scale",i=P("div",e),n=this.options;return this._addScales(n,e+"-line",i),t.on(n.updateWhenIdle?"moveend":"move",this._update,this),t.whenReady(this._update,this),i},onRemove:function(t){t.off(this.options.updateWhenIdle?"moveend":"move",this._update,this)},_addScales:function(t,e,i){t.metric&&(this._mScale=P("div",e,i)),t.imperial&&(this._iScale=P("div",e,i))},_update:function(){var t=this._map,e=t.getSize().y/2,t=t.distance(t.containerPointToLatLng([0,e]),t.containerPointToLatLng([this.options.maxWidth,e]));this._updateScales(t)},_updateScales:function(t){this.options.metric&&t&&this._updateMetric(t),this.options.imperial&&t&&this._updateImperial(t)},_updateMetric:function(t){var e=this._getRoundNum(t);this._updateScale(this._mScale,e<1e3?e+" m":e/1e3+" km",e/t)},_updateImperial:function(t){var e,i,t=3.2808399*t;5280<t?(i=this._getRoundNum(e=t/5280),this._updateScale(this._iScale,i+" mi",i/e)):(i=this._getRoundNum(t),this._updateScale(this._iScale,i+" ft",i/t))},_updateScale:function(t,e,i){t.style.width=Math.round(this.options.maxWidth*i)+"px",t.innerHTML=e},_getRoundNum:function(t){var e=Math.pow(10,(Math.floor(t)+"").length-1),t=t/e;return e*(t=10<=t?10:5<=t?5:3<=t?3:2<=t?2:1)}})),Ke=B.extend({options:{position:"bottomright",prefix:'<a href="https://leafletjs.com" title="A JavaScript library for interactive maps">'+(b.inlineSvg?'<svg aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="12" height="8" viewBox="0 0 12 8" class="leaflet-attribution-flag"><path fill="#4C7BE1" d="M0 0h12v4H0z"/><path fill="#FFD500" d="M0 4h12v3H0z"/><path fill="#E0BC00" d="M0 7h12v1H0z"/></svg> ':"")+"Leaflet</a>"},initialize:function(t){c(this,t),this._attributions={}},onAdd:function(t){for(var e in(t.attributionControl=this)._container=P("div","leaflet-control-attribution"),Ie(this._container),t._layers)t._layers[e].getAttribution&&this.addAttribution(t._layers[e].getAttribution());return this._update(),t.on("layeradd",this._addAttribution,this),this._container},onRemove:function(t){t.off("layeradd",this._addAttribution,this)},_addAttribution:function(t){t.layer.getAttribution&&(this.addAttribution(t.layer.getAttribution()),t.layer.once("remove",function(){this.removeAttribution(t.layer.getAttribution())},this))},setPrefix:function(t){return this.options.prefix=t,this._update(),this},addAttribution:function(t){return t&&(this._attributions[t]||(this._attributions[t]=0),this._attributions[t]++,this._update()),this},removeAttribution:function(t){return t&&this._attributions[t]&&(this._attributions[t]--,this._update()),this},_update:function(){if(this._map){var t,e=[];for(t in this._attributions)this._attributions[t]&&e.push(t);var i=[];this.options.prefix&&i.push(this.options.prefix),e.length&&i.push(e.join(", ")),this._container.innerHTML=i.join(' <span aria-hidden="true">|</span> ')}}}),n=(A.mergeOptions({attributionControl:!0}),A.addInitHook(function(){this.options.attributionControl&&(new Ke).addTo(this)}),B.Layers=Ve,B.Zoom=qe,B.Scale=Ge,B.Attribution=Ke,Ue.layers=function(t,e,i){return new Ve(t,e,i)},Ue.zoom=function(t){return new qe(t)},Ue.scale=function(t){return new Ge(t)},Ue.attribution=function(t){return new Ke(t)},et.extend({initialize:function(t){this._map=t},enable:function(){return this._enabled||(this._enabled=!0,this.addHooks()),this},disable:function(){return this._enabled&&(this._enabled=!1,this.removeHooks()),this},enabled:function(){return!!this._enabled}})),ft=(n.addTo=function(t,e){return t.addHandler(e,this),this},{Events:e}),Ye=b.touch?"touchstart mousedown":"mousedown",Xe=it.extend({options:{clickTolerance:3},initialize:function(t,e,i,n){c(this,n),this._element=t,this._dragStartTarget=e||t,this._preventOutline=i},enable:function(){this._enabled||(S(this._dragStartTarget,Ye,this._onDown,this),this._enabled=!0)},disable:function(){this._enabled&&(Xe._dragging===this&&this.finishDrag(!0),k(this._dragStartTarget,Ye,this._onDown,this),this._enabled=!1,this._moved=!1)},_onDown:function(t){var e,i;this._enabled&&(this._moved=!1,ve(this._element,"leaflet-zoom-anim")||(t.touches&&1!==t.touches.length?Xe._dragging===this&&this.finishDrag():Xe._dragging||t.shiftKey||1!==t.which&&1!==t.button&&!t.touches||((Xe._dragging=this)._preventOutline&&Me(this._element),Le(),re(),this._moving||(this.fire("down"),i=t.touches?t.touches[0]:t,e=Ce(this._element),this._startPoint=new p(i.clientX,i.clientY),this._startPos=Pe(this._element),this._parentScale=Ze(e),i="mousedown"===t.type,S(document,i?"mousemove":"touchmove",this._onMove,this),S(document,i?"mouseup":"touchend touchcancel",this._onUp,this)))))},_onMove:function(t){var e;this._enabled&&(t.touches&&1<t.touches.length?this._moved=!0:!(e=new p((e=t.touches&&1===t.touches.length?t.touches[0]:t).clientX,e.clientY)._subtract(this._startPoint)).x&&!e.y||Math.abs(e.x)+Math.abs(e.y)<this.options.clickTolerance||(e.x/=this._parentScale.x,e.y/=this._parentScale.y,O(t),this._moved||(this.fire("dragstart"),this._moved=!0,M(document.body,"leaflet-dragging"),this._lastTarget=t.target||t.srcElement,window.SVGElementInstance&&this._lastTarget instanceof window.SVGElementInstance&&(this._lastTarget=this._lastTarget.correspondingUseElement),M(this._lastTarget,"leaflet-drag-target")),this._newPos=this._startPos.add(e),this._moving=!0,this._lastEvent=t,this._updatePosition()))},_updatePosition:function(){var t={originalEvent:this._lastEvent};this.fire("predrag",t),Z(this._element,this._newPos),this.fire("drag",t)},_onUp:function(){this._enabled&&this.finishDrag()},finishDrag:function(t){z(document.body,"leaflet-dragging"),this._lastTarget&&(z(this._lastTarget,"leaflet-drag-target"),this._lastTarget=null),k(document,"mousemove touchmove",this._onMove,this),k(document,"mouseup touchend touchcancel",this._onUp,this),Te(),ae();var e=this._moved&&this._moving;this._moving=!1,Xe._dragging=!1,e&&this.fire("dragend",{noInertia:t,distance:this._newPos.distanceTo(this._startPos)})}});function Je(t,e,i){for(var n,o,s,r,a,h,l,u=[1,4,2,8],c=0,d=t.length;c<d;c++)t[c]._code=si(t[c],e);for(s=0;s<4;s++){for(h=u[s],n=[],c=0,o=(d=t.length)-1;c<d;o=c++)r=t[c],a=t[o],r._code&h?a._code&h||((l=oi(a,r,h,e,i))._code=si(l,e),n.push(l)):(a._code&h&&((l=oi(a,r,h,e,i))._code=si(l,e),n.push(l)),n.push(r));t=n}return t}function $e(t,e){var i,n,o,s,r,a,h;if(!t||0===t.length)throw new Error("latlngs not passed");I(t)||(console.warn("latlngs are not flat! Only the first ring will be used"),t=t[0]);for(var l=w([0,0]),u=g(t),c=(u.getNorthWest().distanceTo(u.getSouthWest())*u.getNorthEast().distanceTo(u.getNorthWest())<1700&&(l=Qe(t)),t.length),d=[],_=0;_<c;_++){var p=w(t[_]);d.push(e.project(w([p.lat-l.lat,p.lng-l.lng])))}for(_=r=a=h=0,i=c-1;_<c;i=_++)n=d[_],o=d[i],s=n.y*o.x-o.y*n.x,a+=(n.x+o.x)*s,h+=(n.y+o.y)*s,r+=3*s;u=0===r?d[0]:[a/r,h/r],u=e.unproject(m(u));return w([u.lat+l.lat,u.lng+l.lng])}function Qe(t){for(var e=0,i=0,n=0,o=0;o<t.length;o++){var s=w(t[o]);e+=s.lat,i+=s.lng,n++}return w([e/n,i/n])}var ti,gt={__proto__:null,clipPolygon:Je,polygonCenter:$e,centroid:Qe};function ei(t,e){if(e&&t.length){var i=t=function(t,e){for(var i=[t[0]],n=1,o=0,s=t.length;n<s;n++)(function(t,e){var i=e.x-t.x,e=e.y-t.y;return i*i+e*e})(t[n],t[o])>e&&(i.push(t[n]),o=n);o<s-1&&i.push(t[s-1]);return i}(t,e=e*e),n=i.length,o=new(typeof Uint8Array!=void 0+""?Uint8Array:Array)(n);o[0]=o[n-1]=1,function t(e,i,n,o,s){var r,a,h,l=0;for(a=o+1;a<=s-1;a++)h=ri(e[a],e[o],e[s],!0),l<h&&(r=a,l=h);n<l&&(i[r]=1,t(e,i,n,o,r),t(e,i,n,r,s))}(i,o,e,0,n-1);var s,r=[];for(s=0;s<n;s++)o[s]&&r.push(i[s]);return r}return t.slice()}function ii(t,e,i){return Math.sqrt(ri(t,e,i,!0))}function ni(t,e,i,n,o){var s,r,a,h=n?ti:si(t,i),l=si(e,i);for(ti=l;;){if(!(h|l))return[t,e];if(h&l)return!1;a=si(r=oi(t,e,s=h||l,i,o),i),s===h?(t=r,h=a):(e=r,l=a)}}function oi(t,e,i,n,o){var s,r,a=e.x-t.x,e=e.y-t.y,h=n.min,n=n.max;return 8&i?(s=t.x+a*(n.y-t.y)/e,r=n.y):4&i?(s=t.x+a*(h.y-t.y)/e,r=h.y):2&i?(s=n.x,r=t.y+e*(n.x-t.x)/a):1&i&&(s=h.x,r=t.y+e*(h.x-t.x)/a),new p(s,r,o)}function si(t,e){var i=0;return t.x<e.min.x?i|=1:t.x>e.max.x&&(i|=2),t.y<e.min.y?i|=4:t.y>e.max.y&&(i|=8),i}function ri(t,e,i,n){var o=e.x,e=e.y,s=i.x-o,r=i.y-e,a=s*s+r*r;return 0<a&&(1<(a=((t.x-o)*s+(t.y-e)*r)/a)?(o=i.x,e=i.y):0<a&&(o+=s*a,e+=r*a)),s=t.x-o,r=t.y-e,n?s*s+r*r:new p(o,e)}function I(t){return!d(t[0])||"object"!=typeof t[0][0]&&void 0!==t[0][0]}function ai(t){return console.warn("Deprecated use of _flat, please use L.LineUtil.isFlat instead."),I(t)}function hi(t,e){var i,n,o,s,r,a;if(!t||0===t.length)throw new Error("latlngs not passed");I(t)||(console.warn("latlngs are not flat! Only the first ring will be used"),t=t[0]);for(var h=w([0,0]),l=g(t),u=(l.getNorthWest().distanceTo(l.getSouthWest())*l.getNorthEast().distanceTo(l.getNorthWest())<1700&&(h=Qe(t)),t.length),c=[],d=0;d<u;d++){var _=w(t[d]);c.push(e.project(w([_.lat-h.lat,_.lng-h.lng])))}for(i=d=0;d<u-1;d++)i+=c[d].distanceTo(c[d+1])/2;if(0===i)a=c[0];else for(n=d=0;d<u-1;d++)if(o=c[d],s=c[d+1],i<(n+=r=o.distanceTo(s))){a=[s.x-(r=(n-i)/r)*(s.x-o.x),s.y-r*(s.y-o.y)];break}l=e.unproject(m(a));return w([l.lat+h.lat,l.lng+h.lng])}var vt={__proto__:null,simplify:ei,pointToSegmentDistance:ii,closestPointOnSegment:function(t,e,i){return ri(t,e,i)},clipSegment:ni,_getEdgeIntersection:oi,_getBitCode:si,_sqClosestPointOnSegment:ri,isFlat:I,_flat:ai,polylineCenter:hi},yt={project:function(t){return new p(t.lng,t.lat)},unproject:function(t){return new v(t.y,t.x)},bounds:new f([-180,-90],[180,90])},xt={R:6378137,R_MINOR:6356752.314245179,bounds:new f([-20037508.34279,-15496570.73972],[20037508.34279,18764656.23138]),project:function(t){var e=Math.PI/180,i=this.R,n=t.lat*e,o=this.R_MINOR/i,o=Math.sqrt(1-o*o),s=o*Math.sin(n),s=Math.tan(Math.PI/4-n/2)/Math.pow((1-s)/(1+s),o/2),n=-i*Math.log(Math.max(s,1e-10));return new p(t.lng*e*i,n)},unproject:function(t){for(var e,i=180/Math.PI,n=this.R,o=this.R_MINOR/n,s=Math.sqrt(1-o*o),r=Math.exp(-t.y/n),a=Math.PI/2-2*Math.atan(r),h=0,l=.1;h<15&&1e-7<Math.abs(l);h++)e=s*Math.sin(a),e=Math.pow((1-e)/(1+e),s/2),a+=l=Math.PI/2-2*Math.atan(r*e)-a;return new v(a*i,t.x*i/n)}},wt={__proto__:null,LonLat:yt,Mercator:xt,SphericalMercator:rt},Pt=l({},st,{code:"EPSG:3395",projection:xt,transformation:ht(bt=.5/(Math.PI*xt.R),.5,-bt,.5)}),li=l({},st,{code:"EPSG:4326",projection:yt,transformation:ht(1/180,1,-1/180,.5)}),Lt=l({},ot,{projection:yt,transformation:ht(1,0,-1,0),scale:function(t){return Math.pow(2,t)},zoom:function(t){return Math.log(t)/Math.LN2},distance:function(t,e){var i=e.lng-t.lng,e=e.lat-t.lat;return Math.sqrt(i*i+e*e)},infinite:!0}),o=(ot.Earth=st,ot.EPSG3395=Pt,ot.EPSG3857=lt,ot.EPSG900913=ut,ot.EPSG4326=li,ot.Simple=Lt,it.extend({options:{pane:"overlayPane",attribution:null,bubblingMouseEvents:!0},addTo:function(t){return t.addLayer(this),this},remove:function(){return this.removeFrom(this._map||this._mapToAdd)},removeFrom:function(t){return t&&t.removeLayer(this),this},getPane:function(t){return this._map.getPane(t?this.options[t]||t:this.options.pane)},addInteractiveTarget:function(t){return this._map._targets[h(t)]=this},removeInteractiveTarget:function(t){return delete this._map._targets[h(t)],this},getAttribution:function(){return this.options.attribution},_layerAdd:function(t){var e,i=t.target;i.hasLayer(this)&&(this._map=i,this._zoomAnimated=i._zoomAnimated,this.getEvents&&(e=this.getEvents(),i.on(e,this),this.once("remove",function(){i.off(e,this)},this)),this.onAdd(i),this.fire("add"),i.fire("layeradd",{layer:this}))}})),ui=(A.include({addLayer:function(t){var e;if(t._layerAdd)return e=h(t),this._layers[e]||((this._layers[e]=t)._mapToAdd=this,t.beforeAdd&&t.beforeAdd(this),this.whenReady(t._layerAdd,t)),this;throw new Error("The provided object is not a Layer.")},removeLayer:function(t){var e=h(t);return this._layers[e]&&(this._loaded&&t.onRemove(this),delete this._layers[e],this._loaded&&(this.fire("layerremove",{layer:t}),t.fire("remove")),t._map=t._mapToAdd=null),this},hasLayer:function(t){return h(t)in this._layers},eachLayer:function(t,e){for(var i in this._layers)t.call(e,this._layers[i]);return this},_addLayers:function(t){for(var e=0,i=(t=t?d(t)?t:[t]:[]).length;e<i;e++)this.addLayer(t[e])},_addZoomLimit:function(t){isNaN(t.options.maxZoom)&&isNaN(t.options.minZoom)||(this._zoomBoundLayers[h(t)]=t,this._updateZoomLevels())},_removeZoomLimit:function(t){t=h(t);this._zoomBoundLayers[t]&&(delete this._zoomBoundLayers[t],this._updateZoomLevels())},_updateZoomLevels:function(){var t,e=1/0,i=-1/0,n=this._getZoomSpan();for(t in this._zoomBoundLayers)var o=this._zoomBoundLayers[t].options,e=void 0===o.minZoom?e:Math.min(e,o.minZoom),i=void 0===o.maxZoom?i:Math.max(i,o.maxZoom);this._layersMaxZoom=i===-1/0?void 0:i,this._layersMinZoom=e===1/0?void 0:e,n!==this._getZoomSpan()&&this.fire("zoomlevelschange"),void 0===this.options.maxZoom&&this._layersMaxZoom&&this.getZoom()>this._layersMaxZoom&&this.setZoom(this._layersMaxZoom),void 0===this.options.minZoom&&this._layersMinZoom&&this.getZoom()<this._layersMinZoom&&this.setZoom(this._layersMinZoom)}}),o.extend({initialize:function(t,e){var i,n;if(c(this,e),this._layers={},t)for(i=0,n=t.length;i<n;i++)this.addLayer(t[i])},addLayer:function(t){var e=this.getLayerId(t);return this._layers[e]=t,this._map&&this._map.addLayer(t),this},removeLayer:function(t){t=t in this._layers?t:this.getLayerId(t);return this._map&&this._layers[t]&&this._map.removeLayer(this._layers[t]),delete this._layers[t],this},hasLayer:function(t){return("number"==typeof t?t:this.getLayerId(t))in this._layers},clearLayers:function(){return this.eachLayer(this.removeLayer,this)},invoke:function(t){var e,i,n=Array.prototype.slice.call(arguments,1);for(e in this._layers)(i=this._layers[e])[t]&&i[t].apply(i,n);return this},onAdd:function(t){this.eachLayer(t.addLayer,t)},onRemove:function(t){this.eachLayer(t.removeLayer,t)},eachLayer:function(t,e){for(var i in this._layers)t.call(e,this._layers[i]);return this},getLayer:function(t){return this._layers[t]},getLayers:function(){var t=[];return this.eachLayer(t.push,t),t},setZIndex:function(t){return this.invoke("setZIndex",t)},getLayerId:h})),ci=ui.extend({addLayer:function(t){return this.hasLayer(t)?this:(t.addEventParent(this),ui.prototype.addLayer.call(this,t),this.fire("layeradd",{layer:t}))},removeLayer:function(t){return this.hasLayer(t)?((t=t in this._layers?this._layers[t]:t).removeEventParent(this),ui.prototype.removeLayer.call(this,t),this.fire("layerremove",{layer:t})):this},setStyle:function(t){return this.invoke("setStyle",t)},bringToFront:function(){return this.invoke("bringToFront")},bringToBack:function(){return this.invoke("bringToBack")},getBounds:function(){var t,e=new s;for(t in this._layers){var i=this._layers[t];e.extend(i.getBounds?i.getBounds():i.getLatLng())}return e}}),di=et.extend({options:{popupAnchor:[0,0],tooltipAnchor:[0,0],crossOrigin:!1},initialize:function(t){c(this,t)},createIcon:function(t){return this._createIcon("icon",t)},createShadow:function(t){return this._createIcon("shadow",t)},_createIcon:function(t,e){var i=this._getIconUrl(t);if(i)return i=this._createImg(i,e&&"IMG"===e.tagName?e:null),this._setIconStyles(i,t),!this.options.crossOrigin&&""!==this.options.crossOrigin||(i.crossOrigin=!0===this.options.crossOrigin?"":this.options.crossOrigin),i;if("icon"===t)throw new Error("iconUrl not set in Icon options (see the docs).");return null},_setIconStyles:function(t,e){var i=this.options,n=i[e+"Size"],n=m(n="number"==typeof n?[n,n]:n),o=m("shadow"===e&&i.shadowAnchor||i.iconAnchor||n&&n.divideBy(2,!0));t.className="leaflet-marker-"+e+" "+(i.className||""),o&&(t.style.marginLeft=-o.x+"px",t.style.marginTop=-o.y+"px"),n&&(t.style.width=n.x+"px",t.style.height=n.y+"px")},_createImg:function(t,e){return(e=e||document.createElement("img")).src=t,e},_getIconUrl:function(t){return b.retina&&this.options[t+"RetinaUrl"]||this.options[t+"Url"]}});var _i=di.extend({options:{iconUrl:"marker-icon.png",iconRetinaUrl:"marker-icon-2x.png",shadowUrl:"marker-shadow.png",iconSize:[25,41],iconAnchor:[12,41],popupAnchor:[1,-34],tooltipAnchor:[16,-28],shadowSize:[41,41]},_getIconUrl:function(t){return"string"!=typeof _i.imagePath&&(_i.imagePath=this._detectIconPath()),(this.options.imagePath||_i.imagePath)+di.prototype._getIconUrl.call(this,t)},_stripUrl:function(t){function e(t,e,i){return(e=e.exec(t))&&e[i]}return(t=e(t,/^url\((['"])?(.+)\1\)$/,2))&&e(t,/^(.*)marker-icon\.png$/,1)},_detectIconPath:function(){var t=P("div","leaflet-default-icon-path",document.body),e=pe(t,"background-image")||pe(t,"backgroundImage");return document.body.removeChild(t),(e=this._stripUrl(e))?e:(t=document.querySelector('link[href$="leaflet.css"]'))?t.href.substring(0,t.href.length-"leaflet.css".length-1):""}}),pi=n.extend({initialize:function(t){this._marker=t},addHooks:function(){var t=this._marker._icon;this._draggable||(this._draggable=new Xe(t,t,!0)),this._draggable.on({dragstart:this._onDragStart,predrag:this._onPreDrag,drag:this._onDrag,dragend:this._onDragEnd},this).enable(),M(t,"leaflet-marker-draggable")},removeHooks:function(){this._draggable.off({dragstart:this._onDragStart,predrag:this._onPreDrag,drag:this._onDrag,dragend:this._onDragEnd},this).disable(),this._marker._icon&&z(this._marker._icon,"leaflet-marker-draggable")},moved:function(){return this._draggable&&this._draggable._moved},_adjustPan:function(t){var e=this._marker,i=e._map,n=this._marker.options.autoPanSpeed,o=this._marker.options.autoPanPadding,s=Pe(e._icon),r=i.getPixelBounds(),a=i.getPixelOrigin(),a=_(r.min._subtract(a).add(o),r.max._subtract(a).subtract(o));a.contains(s)||(o=m((Math.max(a.max.x,s.x)-a.max.x)/(r.max.x-a.max.x)-(Math.min(a.min.x,s.x)-a.min.x)/(r.min.x-a.min.x),(Math.max(a.max.y,s.y)-a.max.y)/(r.max.y-a.max.y)-(Math.min(a.min.y,s.y)-a.min.y)/(r.min.y-a.min.y)).multiplyBy(n),i.panBy(o,{animate:!1}),this._draggable._newPos._add(o),this._draggable._startPos._add(o),Z(e._icon,this._draggable._newPos),this._onDrag(t),this._panRequest=x(this._adjustPan.bind(this,t)))},_onDragStart:function(){this._oldLatLng=this._marker.getLatLng(),this._marker.closePopup&&this._marker.closePopup(),this._marker.fire("movestart").fire("dragstart")},_onPreDrag:function(t){this._marker.options.autoPan&&(r(this._panRequest),this._panRequest=x(this._adjustPan.bind(this,t)))},_onDrag:function(t){var e=this._marker,i=e._shadow,n=Pe(e._icon),o=e._map.layerPointToLatLng(n);i&&Z(i,n),e._latlng=o,t.latlng=o,t.oldLatLng=this._oldLatLng,e.fire("move",t).fire("drag",t)},_onDragEnd:function(t){r(this._panRequest),delete this._oldLatLng,this._marker.fire("moveend").fire("dragend",t)}}),mi=o.extend({options:{icon:new _i,interactive:!0,keyboard:!0,title:"",alt:"Marker",zIndexOffset:0,opacity:1,riseOnHover:!1,riseOffset:250,pane:"markerPane",shadowPane:"shadowPane",bubblingMouseEvents:!1,autoPanOnFocus:!0,draggable:!1,autoPan:!1,autoPanPadding:[50,50],autoPanSpeed:10},initialize:function(t,e){c(this,e),this._latlng=w(t)},onAdd:function(t){this._zoomAnimated=this._zoomAnimated&&t.options.markerZoomAnimation,this._zoomAnimated&&t.on("zoomanim",this._animateZoom,this),this._initIcon(),this.update()},onRemove:function(t){this.dragging&&this.dragging.enabled()&&(this.options.draggable=!0,this.dragging.removeHooks()),delete this.dragging,this._zoomAnimated&&t.off("zoomanim",this._animateZoom,this),this._removeIcon(),this._removeShadow()},getEvents:function(){return{zoom:this.update,viewreset:this.update}},getLatLng:function(){return this._latlng},setLatLng:function(t){var e=this._latlng;return this._latlng=w(t),this.update(),this.fire("move",{oldLatLng:e,latlng:this._latlng})},setZIndexOffset:function(t){return this.options.zIndexOffset=t,this.update()},getIcon:function(){return this.options.icon},setIcon:function(t){return this.options.icon=t,this._map&&(this._initIcon(),this.update()),this._popup&&this.bindPopup(this._popup,this._popup.options),this},getElement:function(){return this._icon},update:function(){var t;return this._icon&&this._map&&(t=this._map.latLngToLayerPoint(this._latlng).round(),this._setPos(t)),this},_initIcon:function(){var t=this.options,e="leaflet-zoom-"+(this._zoomAnimated?"animated":"hide"),i=t.icon.createIcon(this._icon),n=!1,i=(i!==this._icon&&(this._icon&&this._removeIcon(),n=!0,t.title&&(i.title=t.title),"IMG"===i.tagName&&(i.alt=t.alt||"")),M(i,e),t.keyboard&&(i.tabIndex="0",i.setAttribute("role","button")),this._icon=i,t.riseOnHover&&this.on({mouseover:this._bringToFront,mouseout:this._resetZIndex}),this.options.autoPanOnFocus&&S(i,"focus",this._panOnFocus,this),t.icon.createShadow(this._shadow)),o=!1;i!==this._shadow&&(this._removeShadow(),o=!0),i&&(M(i,e),i.alt=""),this._shadow=i,t.opacity<1&&this._updateOpacity(),n&&this.getPane().appendChild(this._icon),this._initInteraction(),i&&o&&this.getPane(t.shadowPane).appendChild(this._shadow)},_removeIcon:function(){this.options.riseOnHover&&this.off({mouseover:this._bringToFront,mouseout:this._resetZIndex}),this.options.autoPanOnFocus&&k(this._icon,"focus",this._panOnFocus,this),T(this._icon),this.removeInteractiveTarget(this._icon),this._icon=null},_removeShadow:function(){this._shadow&&T(this._shadow),this._shadow=null},_setPos:function(t){this._icon&&Z(this._icon,t),this._shadow&&Z(this._shadow,t),this._zIndex=t.y+this.options.zIndexOffset,this._resetZIndex()},_updateZIndex:function(t){this._icon&&(this._icon.style.zIndex=this._zIndex+t)},_animateZoom:function(t){t=this._map._latLngToNewLayerPoint(this._latlng,t.zoom,t.center).round();this._setPos(t)},_initInteraction:function(){var t;this.options.interactive&&(M(this._icon,"leaflet-interactive"),this.addInteractiveTarget(this._icon),pi&&(t=this.options.draggable,this.dragging&&(t=this.dragging.enabled(),this.dragging.disable()),this.dragging=new pi(this),t&&this.dragging.enable()))},setOpacity:function(t){return this.options.opacity=t,this._map&&this._updateOpacity(),this},_updateOpacity:function(){var t=this.options.opacity;this._icon&&C(this._icon,t),this._shadow&&C(this._shadow,t)},_bringToFront:function(){this._updateZIndex(this.options.riseOffset)},_resetZIndex:function(){this._updateZIndex(0)},_panOnFocus:function(){var t,e,i=this._map;i&&(t=(e=this.options.icon.options).iconSize?m(e.iconSize):m(0,0),e=e.iconAnchor?m(e.iconAnchor):m(0,0),i.panInside(this._latlng,{paddingTopLeft:e,paddingBottomRight:t.subtract(e)}))},_getPopupAnchor:function(){return this.options.icon.options.popupAnchor},_getTooltipAnchor:function(){return this.options.icon.options.tooltipAnchor}});var fi=o.extend({options:{stroke:!0,color:"#3388ff",weight:3,opacity:1,lineCap:"round",lineJoin:"round",dashArray:null,dashOffset:null,fill:!1,fillColor:null,fillOpacity:.2,fillRule:"evenodd",interactive:!0,bubblingMouseEvents:!0},beforeAdd:function(t){this._renderer=t.getRenderer(this)},onAdd:function(){this._renderer._initPath(this),this._reset(),this._renderer._addPath(this)},onRemove:function(){this._renderer._removePath(this)},redraw:function(){return this._map&&this._renderer._updatePath(this),this},setStyle:function(t){return c(this,t),this._renderer&&(this._renderer._updateStyle(this),this.options.stroke&&t&&Object.prototype.hasOwnProperty.call(t,"weight")&&this._updateBounds()),this},bringToFront:function(){return this._renderer&&this._renderer._bringToFront(this),this},bringToBack:function(){return this._renderer&&this._renderer._bringToBack(this),this},getElement:function(){return this._path},_reset:function(){this._project(),this._update()},_clickTolerance:function(){return(this.options.stroke?this.options.weight/2:0)+(this._renderer.options.tolerance||0)}}),gi=fi.extend({options:{fill:!0,radius:10},initialize:function(t,e){c(this,e),this._latlng=w(t),this._radius=this.options.radius},setLatLng:function(t){var e=this._latlng;return this._latlng=w(t),this.redraw(),this.fire("move",{oldLatLng:e,latlng:this._latlng})},getLatLng:function(){return this._latlng},setRadius:function(t){return this.options.radius=this._radius=t,this.redraw()},getRadius:function(){return this._radius},setStyle:function(t){var e=t&&t.radius||this._radius;return fi.prototype.setStyle.call(this,t),this.setRadius(e),this},_project:function(){this._point=this._map.latLngToLayerPoint(this._latlng),this._updateBounds()},_updateBounds:function(){var t=this._radius,e=this._radiusY||t,i=this._clickTolerance(),t=[t+i,e+i];this._pxBounds=new f(this._point.subtract(t),this._point.add(t))},_update:function(){this._map&&this._updatePath()},_updatePath:function(){this._renderer._updateCircle(this)},_empty:function(){return this._radius&&!this._renderer._bounds.intersects(this._pxBounds)},_containsPoint:function(t){return t.distanceTo(this._point)<=this._radius+this._clickTolerance()}});var vi=gi.extend({initialize:function(t,e,i){if(c(this,e="number"==typeof e?l({},i,{radius:e}):e),this._latlng=w(t),isNaN(this.options.radius))throw new Error("Circle radius cannot be NaN");this._mRadius=this.options.radius},setRadius:function(t){return this._mRadius=t,this.redraw()},getRadius:function(){return this._mRadius},getBounds:function(){var t=[this._radius,this._radiusY||this._radius];return new s(this._map.layerPointToLatLng(this._point.subtract(t)),this._map.layerPointToLatLng(this._point.add(t)))},setStyle:fi.prototype.setStyle,_project:function(){var t,e,i,n,o,s=this._latlng.lng,r=this._latlng.lat,a=this._map,h=a.options.crs;h.distance===st.distance?(n=Math.PI/180,o=this._mRadius/st.R/n,t=a.project([r+o,s]),e=a.project([r-o,s]),e=t.add(e).divideBy(2),i=a.unproject(e).lat,n=Math.acos((Math.cos(o*n)-Math.sin(r*n)*Math.sin(i*n))/(Math.cos(r*n)*Math.cos(i*n)))/n,!isNaN(n)&&0!==n||(n=o/Math.cos(Math.PI/180*r)),this._point=e.subtract(a.getPixelOrigin()),this._radius=isNaN(n)?0:e.x-a.project([i,s-n]).x,this._radiusY=e.y-t.y):(o=h.unproject(h.project(this._latlng).subtract([this._mRadius,0])),this._point=a.latLngToLayerPoint(this._latlng),this._radius=this._point.x-a.latLngToLayerPoint(o).x),this._updateBounds()}});var yi=fi.extend({options:{smoothFactor:1,noClip:!1},initialize:function(t,e){c(this,e),this._setLatLngs(t)},getLatLngs:function(){return this._latlngs},setLatLngs:function(t){return this._setLatLngs(t),this.redraw()},isEmpty:function(){return!this._latlngs.length},closestLayerPoint:function(t){for(var e=1/0,i=null,n=ri,o=0,s=this._parts.length;o<s;o++)for(var r=this._parts[o],a=1,h=r.length;a<h;a++){var l,u,c=n(t,l=r[a-1],u=r[a],!0);c<e&&(e=c,i=n(t,l,u))}return i&&(i.distance=Math.sqrt(e)),i},getCenter:function(){if(this._map)return hi(this._defaultShape(),this._map.options.crs);throw new Error("Must add layer to map before using getCenter()")},getBounds:function(){return this._bounds},addLatLng:function(t,e){return e=e||this._defaultShape(),t=w(t),e.push(t),this._bounds.extend(t),this.redraw()},_setLatLngs:function(t){this._bounds=new s,this._latlngs=this._convertLatLngs(t)},_defaultShape:function(){return I(this._latlngs)?this._latlngs:this._latlngs[0]},_convertLatLngs:function(t){for(var e=[],i=I(t),n=0,o=t.length;n<o;n++)i?(e[n]=w(t[n]),this._bounds.extend(e[n])):e[n]=this._convertLatLngs(t[n]);return e},_project:function(){var t=new f;this._rings=[],this._projectLatlngs(this._latlngs,this._rings,t),this._bounds.isValid()&&t.isValid()&&(this._rawPxBounds=t,this._updateBounds())},_updateBounds:function(){var t=this._clickTolerance(),t=new p(t,t);this._rawPxBounds&&(this._pxBounds=new f([this._rawPxBounds.min.subtract(t),this._rawPxBounds.max.add(t)]))},_projectLatlngs:function(t,e,i){var n,o,s=t[0]instanceof v,r=t.length;if(s){for(o=[],n=0;n<r;n++)o[n]=this._map.latLngToLayerPoint(t[n]),i.extend(o[n]);e.push(o)}else for(n=0;n<r;n++)this._projectLatlngs(t[n],e,i)},_clipPoints:function(){var t=this._renderer._bounds;if(this._parts=[],this._pxBounds&&this._pxBounds.intersects(t))if(this.options.noClip)this._parts=this._rings;else for(var e,i,n,o,s=this._parts,r=0,a=0,h=this._rings.length;r<h;r++)for(e=0,i=(o=this._rings[r]).length;e<i-1;e++)(n=ni(o[e],o[e+1],t,e,!0))&&(s[a]=s[a]||[],s[a].push(n[0]),n[1]===o[e+1]&&e!==i-2||(s[a].push(n[1]),a++))},_simplifyPoints:function(){for(var t=this._parts,e=this.options.smoothFactor,i=0,n=t.length;i<n;i++)t[i]=ei(t[i],e)},_update:function(){this._map&&(this._clipPoints(),this._simplifyPoints(),this._updatePath())},_updatePath:function(){this._renderer._updatePoly(this)},_containsPoint:function(t,e){var i,n,o,s,r,a,h=this._clickTolerance();if(this._pxBounds&&this._pxBounds.contains(t))for(i=0,s=this._parts.length;i<s;i++)for(n=0,o=(r=(a=this._parts[i]).length)-1;n<r;o=n++)if((e||0!==n)&&ii(t,a[o],a[n])<=h)return!0;return!1}});yi._flat=ai;var xi=yi.extend({options:{fill:!0},isEmpty:function(){return!this._latlngs.length||!this._latlngs[0].length},getCenter:function(){if(this._map)return $e(this._defaultShape(),this._map.options.crs);throw new Error("Must add layer to map before using getCenter()")},_convertLatLngs:function(t){var t=yi.prototype._convertLatLngs.call(this,t),e=t.length;return 2<=e&&t[0]instanceof v&&t[0].equals(t[e-1])&&t.pop(),t},_setLatLngs:function(t){yi.prototype._setLatLngs.call(this,t),I(this._latlngs)&&(this._latlngs=[this._latlngs])},_defaultShape:function(){return(I(this._latlngs[0])?this._latlngs:this._latlngs[0])[0]},_clipPoints:function(){var t=this._renderer._bounds,e=this.options.weight,e=new p(e,e),t=new f(t.min.subtract(e),t.max.add(e));if(this._parts=[],this._pxBounds&&this._pxBounds.intersects(t))if(this.options.noClip)this._parts=this._rings;else for(var i,n=0,o=this._rings.length;n<o;n++)(i=Je(this._rings[n],t,!0)).length&&this._parts.push(i)},_updatePath:function(){this._renderer._updatePoly(this,!0)},_containsPoint:function(t){var e,i,n,o,s,r,a,h,l=!1;if(!this._pxBounds||!this._pxBounds.contains(t))return!1;for(o=0,a=this._parts.length;o<a;o++)for(s=0,r=(h=(e=this._parts[o]).length)-1;s<h;r=s++)i=e[s],n=e[r],i.y>t.y!=n.y>t.y&&t.x<(n.x-i.x)*(t.y-i.y)/(n.y-i.y)+i.x&&(l=!l);return l||yi.prototype._containsPoint.call(this,t,!0)}});var wi=ci.extend({initialize:function(t,e){c(this,e),this._layers={},t&&this.addData(t)},addData:function(t){var e,i,n,o=d(t)?t:t.features;if(o){for(e=0,i=o.length;e<i;e++)((n=o[e]).geometries||n.geometry||n.features||n.coordinates)&&this.addData(n);return this}var s,r=this.options;return(!r.filter||r.filter(t))&&(s=bi(t,r))?(s.feature=Zi(t),s.defaultOptions=s.options,this.resetStyle(s),r.onEachFeature&&r.onEachFeature(t,s),this.addLayer(s)):this},resetStyle:function(t){return void 0===t?this.eachLayer(this.resetStyle,this):(t.options=l({},t.defaultOptions),this._setLayerStyle(t,this.options.style),this)},setStyle:function(e){return this.eachLayer(function(t){this._setLayerStyle(t,e)},this)},_setLayerStyle:function(t,e){t.setStyle&&("function"==typeof e&&(e=e(t.feature)),t.setStyle(e))}});function bi(t,e){var i,n,o,s,r="Feature"===t.type?t.geometry:t,a=r?r.coordinates:null,h=[],l=e&&e.pointToLayer,u=e&&e.coordsToLatLng||Li;if(!a&&!r)return null;switch(r.type){case"Point":return Pi(l,t,i=u(a),e);case"MultiPoint":for(o=0,s=a.length;o<s;o++)i=u(a[o]),h.push(Pi(l,t,i,e));return new ci(h);case"LineString":case"MultiLineString":return n=Ti(a,"LineString"===r.type?0:1,u),new yi(n,e);case"Polygon":case"MultiPolygon":return n=Ti(a,"Polygon"===r.type?1:2,u),new xi(n,e);case"GeometryCollection":for(o=0,s=r.geometries.length;o<s;o++){var c=bi({geometry:r.geometries[o],type:"Feature",properties:t.properties},e);c&&h.push(c)}return new ci(h);case"FeatureCollection":for(o=0,s=r.features.length;o<s;o++){var d=bi(r.features[o],e);d&&h.push(d)}return new ci(h);default:throw new Error("Invalid GeoJSON object.")}}function Pi(t,e,i,n){return t?t(e,i):new mi(i,n&&n.markersInheritOptions&&n)}function Li(t){return new v(t[1],t[0],t[2])}function Ti(t,e,i){for(var n,o=[],s=0,r=t.length;s<r;s++)n=e?Ti(t[s],e-1,i):(i||Li)(t[s]),o.push(n);return o}function Mi(t,e){return void 0!==(t=w(t)).alt?[i(t.lng,e),i(t.lat,e),i(t.alt,e)]:[i(t.lng,e),i(t.lat,e)]}function zi(t,e,i,n){for(var o=[],s=0,r=t.length;s<r;s++)o.push(e?zi(t[s],I(t[s])?0:e-1,i,n):Mi(t[s],n));return!e&&i&&0<o.length&&o.push(o[0].slice()),o}function Ci(t,e){return t.feature?l({},t.feature,{geometry:e}):Zi(e)}function Zi(t){return"Feature"===t.type||"FeatureCollection"===t.type?t:{type:"Feature",properties:{},geometry:t}}Tt={toGeoJSON:function(t){return Ci(this,{type:"Point",coordinates:Mi(this.getLatLng(),t)})}};function Si(t,e){return new wi(t,e)}mi.include(Tt),vi.include(Tt),gi.include(Tt),yi.include({toGeoJSON:function(t){var e=!I(this._latlngs);return Ci(this,{type:(e?"Multi":"")+"LineString",coordinates:zi(this._latlngs,e?1:0,!1,t)})}}),xi.include({toGeoJSON:function(t){var e=!I(this._latlngs),i=e&&!I(this._latlngs[0]),t=zi(this._latlngs,i?2:e?1:0,!0,t);return Ci(this,{type:(i?"Multi":"")+"Polygon",coordinates:t=e?t:[t]})}}),ui.include({toMultiPoint:function(e){var i=[];return this.eachLayer(function(t){i.push(t.toGeoJSON(e).geometry.coordinates)}),Ci(this,{type:"MultiPoint",coordinates:i})},toGeoJSON:function(e){var i,n,t=this.feature&&this.feature.geometry&&this.feature.geometry.type;return"MultiPoint"===t?this.toMultiPoint(e):(i="GeometryCollection"===t,n=[],this.eachLayer(function(t){t.toGeoJSON&&(t=t.toGeoJSON(e),i?n.push(t.geometry):"FeatureCollection"===(t=Zi(t)).type?n.push.apply(n,t.features):n.push(t))}),i?Ci(this,{geometries:n,type:"GeometryCollection"}):{type:"FeatureCollection",features:n})}});var Mt=Si,Ei=o.extend({options:{opacity:1,alt:"",interactive:!1,crossOrigin:!1,errorOverlayUrl:"",zIndex:1,className:""},initialize:function(t,e,i){this._url=t,this._bounds=g(e),c(this,i)},onAdd:function(){this._image||(this._initImage(),this.options.opacity<1&&this._updateOpacity()),this.options.interactive&&(M(this._image,"leaflet-interactive"),this.addInteractiveTarget(this._image)),this.getPane().appendChild(this._image),this._reset()},onRemove:function(){T(this._image),this.options.interactive&&this.removeInteractiveTarget(this._image)},setOpacity:function(t){return this.options.opacity=t,this._image&&this._updateOpacity(),this},setStyle:function(t){return t.opacity&&this.setOpacity(t.opacity),this},bringToFront:function(){return this._map&&fe(this._image),this},bringToBack:function(){return this._map&&ge(this._image),this},setUrl:function(t){return this._url=t,this._image&&(this._image.src=t),this},setBounds:function(t){return this._bounds=g(t),this._map&&this._reset(),this},getEvents:function(){var t={zoom:this._reset,viewreset:this._reset};return this._zoomAnimated&&(t.zoomanim=this._animateZoom),t},setZIndex:function(t){return this.options.zIndex=t,this._updateZIndex(),this},getBounds:function(){return this._bounds},getElement:function(){return this._image},_initImage:function(){var t="IMG"===this._url.tagName,e=this._image=t?this._url:P("img");M(e,"leaflet-image-layer"),this._zoomAnimated&&M(e,"leaflet-zoom-animated"),this.options.className&&M(e,this.options.className),e.onselectstart=u,e.onmousemove=u,e.onload=a(this.fire,this,"load"),e.onerror=a(this._overlayOnError,this,"error"),!this.options.crossOrigin&&""!==this.options.crossOrigin||(e.crossOrigin=!0===this.options.crossOrigin?"":this.options.crossOrigin),this.options.zIndex&&this._updateZIndex(),t?this._url=e.src:(e.src=this._url,e.alt=this.options.alt)},_animateZoom:function(t){var e=this._map.getZoomScale(t.zoom),t=this._map._latLngBoundsToNewLayerBounds(this._bounds,t.zoom,t.center).min;be(this._image,t,e)},_reset:function(){var t=this._image,e=new f(this._map.latLngToLayerPoint(this._bounds.getNorthWest()),this._map.latLngToLayerPoint(this._bounds.getSouthEast())),i=e.getSize();Z(t,e.min),t.style.width=i.x+"px",t.style.height=i.y+"px"},_updateOpacity:function(){C(this._image,this.options.opacity)},_updateZIndex:function(){this._image&&void 0!==this.options.zIndex&&null!==this.options.zIndex&&(this._image.style.zIndex=this.options.zIndex)},_overlayOnError:function(){this.fire("error");var t=this.options.errorOverlayUrl;t&&this._url!==t&&(this._url=t,this._image.src=t)},getCenter:function(){return this._bounds.getCenter()}}),ki=Ei.extend({options:{autoplay:!0,loop:!0,keepAspectRatio:!0,muted:!1,playsInline:!0},_initImage:function(){var t="VIDEO"===this._url.tagName,e=this._image=t?this._url:P("video");if(M(e,"leaflet-image-layer"),this._zoomAnimated&&M(e,"leaflet-zoom-animated"),this.options.className&&M(e,this.options.className),e.onselectstart=u,e.onmousemove=u,e.onloadeddata=a(this.fire,this,"load"),t){for(var i=e.getElementsByTagName("source"),n=[],o=0;o<i.length;o++)n.push(i[o].src);this._url=0<i.length?n:[e.src]}else{d(this._url)||(this._url=[this._url]),!this.options.keepAspectRatio&&Object.prototype.hasOwnProperty.call(e.style,"objectFit")&&(e.style.objectFit="fill"),e.autoplay=!!this.options.autoplay,e.loop=!!this.options.loop,e.muted=!!this.options.muted,e.playsInline=!!this.options.playsInline;for(var s=0;s<this._url.length;s++){var r=P("source");r.src=this._url[s],e.appendChild(r)}}}});var Oi=Ei.extend({_initImage:function(){var t=this._image=this._url;M(t,"leaflet-image-layer"),this._zoomAnimated&&M(t,"leaflet-zoom-animated"),this.options.className&&M(t,this.options.className),t.onselectstart=u,t.onmousemove=u}});var Ai=o.extend({options:{interactive:!1,offset:[0,0],className:"",pane:void 0,content:""},initialize:function(t,e){t&&(t instanceof v||d(t))?(this._latlng=w(t),c(this,e)):(c(this,t),this._source=e),this.options.content&&(this._content=this.options.content)},openOn:function(t){return(t=arguments.length?t:this._source._map).hasLayer(this)||t.addLayer(this),this},close:function(){return this._map&&this._map.removeLayer(this),this},toggle:function(t){return this._map?this.close():(arguments.length?this._source=t:t=this._source,this._prepareOpen(),this.openOn(t._map)),this},onAdd:function(t){this._zoomAnimated=t._zoomAnimated,this._container||this._initLayout(),t._fadeAnimated&&C(this._container,0),clearTimeout(this._removeTimeout),this.getPane().appendChild(this._container),this.update(),t._fadeAnimated&&C(this._container,1),this.bringToFront(),this.options.interactive&&(M(this._container,"leaflet-interactive"),this.addInteractiveTarget(this._container))},onRemove:function(t){t._fadeAnimated?(C(this._container,0),this._removeTimeout=setTimeout(a(T,void 0,this._container),200)):T(this._container),this.options.interactive&&(z(this._container,"leaflet-interactive"),this.removeInteractiveTarget(this._container))},getLatLng:function(){return this._latlng},setLatLng:function(t){return this._latlng=w(t),this._map&&(this._updatePosition(),this._adjustPan()),this},getContent:function(){return this._content},setContent:function(t){return this._content=t,this.update(),this},getElement:function(){return this._container},update:function(){this._map&&(this._container.style.visibility="hidden",this._updateContent(),this._updateLayout(),this._updatePosition(),this._container.style.visibility="",this._adjustPan())},getEvents:function(){var t={zoom:this._updatePosition,viewreset:this._updatePosition};return this._zoomAnimated&&(t.zoomanim=this._animateZoom),t},isOpen:function(){return!!this._map&&this._map.hasLayer(this)},bringToFront:function(){return this._map&&fe(this._container),this},bringToBack:function(){return this._map&&ge(this._container),this},_prepareOpen:function(t){if(!(i=this._source)._map)return!1;if(i instanceof ci){var e,i=null,n=this._source._layers;for(e in n)if(n[e]._map){i=n[e];break}if(!i)return!1;this._source=i}if(!t)if(i.getCenter)t=i.getCenter();else if(i.getLatLng)t=i.getLatLng();else{if(!i.getBounds)throw new Error("Unable to get source layer LatLng.");t=i.getBounds().getCenter()}return this.setLatLng(t),this._map&&this.update(),!0},_updateContent:function(){if(this._content){var t=this._contentNode,e="function"==typeof this._content?this._content(this._source||this):this._content;if("string"==typeof e)t.innerHTML=e;else{for(;t.hasChildNodes();)t.removeChild(t.firstChild);t.appendChild(e)}this.fire("contentupdate")}},_updatePosition:function(){var t,e,i;this._map&&(e=this._map.latLngToLayerPoint(this._latlng),t=m(this.options.offset),i=this._getAnchor(),this._zoomAnimated?Z(this._container,e.add(i)):t=t.add(e).add(i),e=this._containerBottom=-t.y,i=this._containerLeft=-Math.round(this._containerWidth/2)+t.x,this._container.style.bottom=e+"px",this._container.style.left=i+"px")},_getAnchor:function(){return[0,0]}}),Bi=(A.include({_initOverlay:function(t,e,i,n){var o=e;return o instanceof t||(o=new t(n).setContent(e)),i&&o.setLatLng(i),o}}),o.include({_initOverlay:function(t,e,i,n){var o=i;return o instanceof t?(c(o,n),o._source=this):(o=e&&!n?e:new t(n,this)).setContent(i),o}}),Ai.extend({options:{pane:"popupPane",offset:[0,7],maxWidth:300,minWidth:50,maxHeight:null,autoPan:!0,autoPanPaddingTopLeft:null,autoPanPaddingBottomRight:null,autoPanPadding:[5,5],keepInView:!1,closeButton:!0,autoClose:!0,closeOnEscapeKey:!0,className:""},openOn:function(t){return!(t=arguments.length?t:this._source._map).hasLayer(this)&&t._popup&&t._popup.options.autoClose&&t.removeLayer(t._popup),t._popup=this,Ai.prototype.openOn.call(this,t)},onAdd:function(t){Ai.prototype.onAdd.call(this,t),t.fire("popupopen",{popup:this}),this._source&&(this._source.fire("popupopen",{popup:this},!0),this._source instanceof fi||this._source.on("preclick",Ae))},onRemove:function(t){Ai.prototype.onRemove.call(this,t),t.fire("popupclose",{popup:this}),this._source&&(this._source.fire("popupclose",{popup:this},!0),this._source instanceof fi||this._source.off("preclick",Ae))},getEvents:function(){var t=Ai.prototype.getEvents.call(this);return(void 0!==this.options.closeOnClick?this.options.closeOnClick:this._map.options.closePopupOnClick)&&(t.preclick=this.close),this.options.keepInView&&(t.moveend=this._adjustPan),t},_initLayout:function(){var t="leaflet-popup",e=this._container=P("div",t+" "+(this.options.className||"")+" leaflet-zoom-animated"),i=this._wrapper=P("div",t+"-content-wrapper",e);this._contentNode=P("div",t+"-content",i),Ie(e),Be(this._contentNode),S(e,"contextmenu",Ae),this._tipContainer=P("div",t+"-tip-container",e),this._tip=P("div",t+"-tip",this._tipContainer),this.options.closeButton&&((i=this._closeButton=P("a",t+"-close-button",e)).setAttribute("role","button"),i.setAttribute("aria-label","Close popup"),i.href="#close",i.innerHTML='<span aria-hidden="true">&#215;</span>',S(i,"click",function(t){O(t),this.close()},this))},_updateLayout:function(){var t=this._contentNode,e=t.style,i=(e.width="",e.whiteSpace="nowrap",t.offsetWidth),i=Math.min(i,this.options.maxWidth),i=(i=Math.max(i,this.options.minWidth),e.width=i+1+"px",e.whiteSpace="",e.height="",t.offsetHeight),n=this.options.maxHeight,o="leaflet-popup-scrolled";(n&&n<i?(e.height=n+"px",M):z)(t,o),this._containerWidth=this._container.offsetWidth},_animateZoom:function(t){var t=this._map._latLngToNewLayerPoint(this._latlng,t.zoom,t.center),e=this._getAnchor();Z(this._container,t.add(e))},_adjustPan:function(){var t,e,i,n,o,s,r,a;this.options.autoPan&&(this._map._panAnim&&this._map._panAnim.stop(),this._autopanning?this._autopanning=!1:(t=this._map,e=parseInt(pe(this._container,"marginBottom"),10)||0,e=this._container.offsetHeight+e,a=this._containerWidth,(i=new p(this._containerLeft,-e-this._containerBottom))._add(Pe(this._container)),i=t.layerPointToContainerPoint(i),o=m(this.options.autoPanPadding),n=m(this.options.autoPanPaddingTopLeft||o),o=m(this.options.autoPanPaddingBottomRight||o),s=t.getSize(),r=0,i.x+a+o.x>s.x&&(r=i.x+a-s.x+o.x),i.x-r-n.x<(a=0)&&(r=i.x-n.x),i.y+e+o.y>s.y&&(a=i.y+e-s.y+o.y),i.y-a-n.y<0&&(a=i.y-n.y),(r||a)&&(this.options.keepInView&&(this._autopanning=!0),t.fire("autopanstart").panBy([r,a]))))},_getAnchor:function(){return m(this._source&&this._source._getPopupAnchor?this._source._getPopupAnchor():[0,0])}})),Ii=(A.mergeOptions({closePopupOnClick:!0}),A.include({openPopup:function(t,e,i){return this._initOverlay(Bi,t,e,i).openOn(this),this},closePopup:function(t){return(t=arguments.length?t:this._popup)&&t.close(),this}}),o.include({bindPopup:function(t,e){return this._popup=this._initOverlay(Bi,this._popup,t,e),this._popupHandlersAdded||(this.on({click:this._openPopup,keypress:this._onKeyPress,remove:this.closePopup,move:this._movePopup}),this._popupHandlersAdded=!0),this},unbindPopup:function(){return this._popup&&(this.off({click:this._openPopup,keypress:this._onKeyPress,remove:this.closePopup,move:this._movePopup}),this._popupHandlersAdded=!1,this._popup=null),this},openPopup:function(t){return this._popup&&(this instanceof ci||(this._popup._source=this),this._popup._prepareOpen(t||this._latlng)&&this._popup.openOn(this._map)),this},closePopup:function(){return this._popup&&this._popup.close(),this},togglePopup:function(){return this._popup&&this._popup.toggle(this),this},isPopupOpen:function(){return!!this._popup&&this._popup.isOpen()},setPopupContent:function(t){return this._popup&&this._popup.setContent(t),this},getPopup:function(){return this._popup},_openPopup:function(t){var e;this._popup&&this._map&&(Re(t),e=t.layer||t.target,this._popup._source!==e||e instanceof fi?(this._popup._source=e,this.openPopup(t.latlng)):this._map.hasLayer(this._popup)?this.closePopup():this.openPopup(t.latlng))},_movePopup:function(t){this._popup.setLatLng(t.latlng)},_onKeyPress:function(t){13===t.originalEvent.keyCode&&this._openPopup(t)}}),Ai.extend({options:{pane:"tooltipPane",offset:[0,0],direction:"auto",permanent:!1,sticky:!1,opacity:.9},onAdd:function(t){Ai.prototype.onAdd.call(this,t),this.setOpacity(this.options.opacity),t.fire("tooltipopen",{tooltip:this}),this._source&&(this.addEventParent(this._source),this._source.fire("tooltipopen",{tooltip:this},!0))},onRemove:function(t){Ai.prototype.onRemove.call(this,t),t.fire("tooltipclose",{tooltip:this}),this._source&&(this.removeEventParent(this._source),this._source.fire("tooltipclose",{tooltip:this},!0))},getEvents:function(){var t=Ai.prototype.getEvents.call(this);return this.options.permanent||(t.preclick=this.close),t},_initLayout:function(){var t="leaflet-tooltip "+(this.options.className||"")+" leaflet-zoom-"+(this._zoomAnimated?"animated":"hide");this._contentNode=this._container=P("div",t),this._container.setAttribute("role","tooltip"),this._container.setAttribute("id","leaflet-tooltip-"+h(this))},_updateLayout:function(){},_adjustPan:function(){},_setPosition:function(t){var e,i=this._map,n=this._container,o=i.latLngToContainerPoint(i.getCenter()),i=i.layerPointToContainerPoint(t),s=this.options.direction,r=n.offsetWidth,a=n.offsetHeight,h=m(this.options.offset),l=this._getAnchor(),i="top"===s?(e=r/2,a):"bottom"===s?(e=r/2,0):(e="center"===s?r/2:"right"===s?0:"left"===s?r:i.x<o.x?(s="right",0):(s="left",r+2*(h.x+l.x)),a/2);t=t.subtract(m(e,i,!0)).add(h).add(l),z(n,"leaflet-tooltip-right"),z(n,"leaflet-tooltip-left"),z(n,"leaflet-tooltip-top"),z(n,"leaflet-tooltip-bottom"),M(n,"leaflet-tooltip-"+s),Z(n,t)},_updatePosition:function(){var t=this._map.latLngToLayerPoint(this._latlng);this._setPosition(t)},setOpacity:function(t){this.options.opacity=t,this._container&&C(this._container,t)},_animateZoom:function(t){t=this._map._latLngToNewLayerPoint(this._latlng,t.zoom,t.center);this._setPosition(t)},_getAnchor:function(){return m(this._source&&this._source._getTooltipAnchor&&!this.options.sticky?this._source._getTooltipAnchor():[0,0])}})),Ri=(A.include({openTooltip:function(t,e,i){return this._initOverlay(Ii,t,e,i).openOn(this),this},closeTooltip:function(t){return t.close(),this}}),o.include({bindTooltip:function(t,e){return this._tooltip&&this.isTooltipOpen()&&this.unbindTooltip(),this._tooltip=this._initOverlay(Ii,this._tooltip,t,e),this._initTooltipInteractions(),this._tooltip.options.permanent&&this._map&&this._map.hasLayer(this)&&this.openTooltip(),this},unbindTooltip:function(){return this._tooltip&&(this._initTooltipInteractions(!0),this.closeTooltip(),this._tooltip=null),this},_initTooltipInteractions:function(t){var e,i;!t&&this._tooltipHandlersAdded||(e=t?"off":"on",i={remove:this.closeTooltip,move:this._moveTooltip},this._tooltip.options.permanent?i.add=this._openTooltip:(i.mouseover=this._openTooltip,i.mouseout=this.closeTooltip,i.click=this._openTooltip,this._map?this._addFocusListeners():i.add=this._addFocusListeners),this._tooltip.options.sticky&&(i.mousemove=this._moveTooltip),this[e](i),this._tooltipHandlersAdded=!t)},openTooltip:function(t){return this._tooltip&&(this instanceof ci||(this._tooltip._source=this),this._tooltip._prepareOpen(t)&&(this._tooltip.openOn(this._map),this.getElement?this._setAriaDescribedByOnLayer(this):this.eachLayer&&this.eachLayer(this._setAriaDescribedByOnLayer,this))),this},closeTooltip:function(){if(this._tooltip)return this._tooltip.close()},toggleTooltip:function(){return this._tooltip&&this._tooltip.toggle(this),this},isTooltipOpen:function(){return this._tooltip.isOpen()},setTooltipContent:function(t){return this._tooltip&&this._tooltip.setContent(t),this},getTooltip:function(){return this._tooltip},_addFocusListeners:function(){this.getElement?this._addFocusListenersOnLayer(this):this.eachLayer&&this.eachLayer(this._addFocusListenersOnLayer,this)},_addFocusListenersOnLayer:function(t){var e="function"==typeof t.getElement&&t.getElement();e&&(S(e,"focus",function(){this._tooltip._source=t,this.openTooltip()},this),S(e,"blur",this.closeTooltip,this))},_setAriaDescribedByOnLayer:function(t){t="function"==typeof t.getElement&&t.getElement();t&&t.setAttribute("aria-describedby",this._tooltip._container.id)},_openTooltip:function(t){var e;this._tooltip&&this._map&&(this._map.dragging&&this._map.dragging.moving()&&!this._openOnceFlag?(this._openOnceFlag=!0,(e=this)._map.once("moveend",function(){e._openOnceFlag=!1,e._openTooltip(t)})):(this._tooltip._source=t.layer||t.target,this.openTooltip(this._tooltip.options.sticky?t.latlng:void 0)))},_moveTooltip:function(t){var e=t.latlng;this._tooltip.options.sticky&&t.originalEvent&&(t=this._map.mouseEventToContainerPoint(t.originalEvent),t=this._map.containerPointToLayerPoint(t),e=this._map.layerPointToLatLng(t)),this._tooltip.setLatLng(e)}}),di.extend({options:{iconSize:[12,12],html:!1,bgPos:null,className:"leaflet-div-icon"},createIcon:function(t){var t=t&&"DIV"===t.tagName?t:document.createElement("div"),e=this.options;return e.html instanceof Element?(me(t),t.appendChild(e.html)):t.innerHTML=!1!==e.html?e.html:"",e.bgPos&&(e=m(e.bgPos),t.style.backgroundPosition=-e.x+"px "+-e.y+"px"),this._setIconStyles(t,"icon"),t},createShadow:function(){return null}}));di.Default=_i;var Ni=o.extend({options:{tileSize:256,opacity:1,updateWhenIdle:b.mobile,updateWhenZooming:!0,updateInterval:200,zIndex:1,bounds:null,minZoom:0,maxZoom:void 0,maxNativeZoom:void 0,minNativeZoom:void 0,noWrap:!1,pane:"tilePane",className:"",keepBuffer:2},initialize:function(t){c(this,t)},onAdd:function(){this._initContainer(),this._levels={},this._tiles={},this._resetView()},beforeAdd:function(t){t._addZoomLimit(this)},onRemove:function(t){this._removeAllTiles(),T(this._container),t._removeZoomLimit(this),this._container=null,this._tileZoom=void 0},bringToFront:function(){return this._map&&(fe(this._container),this._setAutoZIndex(Math.max)),this},bringToBack:function(){return this._map&&(ge(this._container),this._setAutoZIndex(Math.min)),this},getContainer:function(){return this._container},setOpacity:function(t){return this.options.opacity=t,this._updateOpacity(),this},setZIndex:function(t){return this.options.zIndex=t,this._updateZIndex(),this},isLoading:function(){return this._loading},redraw:function(){var t;return this._map&&(this._removeAllTiles(),(t=this._clampZoom(this._map.getZoom()))!==this._tileZoom&&(this._tileZoom=t,this._updateLevels()),this._update()),this},getEvents:function(){var t={viewprereset:this._invalidateAll,viewreset:this._resetView,zoom:this._resetView,moveend:this._onMoveEnd};return this.options.updateWhenIdle||(this._onMove||(this._onMove=j(this._onMoveEnd,this.options.updateInterval,this)),t.move=this._onMove),this._zoomAnimated&&(t.zoomanim=this._animateZoom),t},createTile:function(){return document.createElement("div")},getTileSize:function(){var t=this.options.tileSize;return t instanceof p?t:new p(t,t)},_updateZIndex:function(){this._container&&void 0!==this.options.zIndex&&null!==this.options.zIndex&&(this._container.style.zIndex=this.options.zIndex)},_setAutoZIndex:function(t){for(var e,i=this.getPane().children,n=-t(-1/0,1/0),o=0,s=i.length;o<s;o++)e=i[o].style.zIndex,i[o]!==this._container&&e&&(n=t(n,+e));isFinite(n)&&(this.options.zIndex=n+t(-1,1),this._updateZIndex())},_updateOpacity:function(){if(this._map&&!b.ielt9){C(this._container,this.options.opacity);var t,e=+new Date,i=!1,n=!1;for(t in this._tiles){var o,s=this._tiles[t];s.current&&s.loaded&&(o=Math.min(1,(e-s.loaded)/200),C(s.el,o),o<1?i=!0:(s.active?n=!0:this._onOpaqueTile(s),s.active=!0))}n&&!this._noPrune&&this._pruneTiles(),i&&(r(this._fadeFrame),this._fadeFrame=x(this._updateOpacity,this))}},_onOpaqueTile:u,_initContainer:function(){this._container||(this._container=P("div","leaflet-layer "+(this.options.className||"")),this._updateZIndex(),this.options.opacity<1&&this._updateOpacity(),this.getPane().appendChild(this._container))},_updateLevels:function(){var t=this._tileZoom,e=this.options.maxZoom;if(void 0!==t){for(var i in this._levels)i=Number(i),this._levels[i].el.children.length||i===t?(this._levels[i].el.style.zIndex=e-Math.abs(t-i),this._onUpdateLevel(i)):(T(this._levels[i].el),this._removeTilesAtZoom(i),this._onRemoveLevel(i),delete this._levels[i]);var n=this._levels[t],o=this._map;return n||((n=this._levels[t]={}).el=P("div","leaflet-tile-container leaflet-zoom-animated",this._container),n.el.style.zIndex=e,n.origin=o.project(o.unproject(o.getPixelOrigin()),t).round(),n.zoom=t,this._setZoomTransform(n,o.getCenter(),o.getZoom()),u(n.el.offsetWidth),this._onCreateLevel(n)),this._level=n}},_onUpdateLevel:u,_onRemoveLevel:u,_onCreateLevel:u,_pruneTiles:function(){if(this._map){var t,e,i,n=this._map.getZoom();if(n>this.options.maxZoom||n<this.options.minZoom)this._removeAllTiles();else{for(t in this._tiles)(i=this._tiles[t]).retain=i.current;for(t in this._tiles)(i=this._tiles[t]).current&&!i.active&&(e=i.coords,this._retainParent(e.x,e.y,e.z,e.z-5)||this._retainChildren(e.x,e.y,e.z,e.z+2));for(t in this._tiles)this._tiles[t].retain||this._removeTile(t)}}},_removeTilesAtZoom:function(t){for(var e in this._tiles)this._tiles[e].coords.z===t&&this._removeTile(e)},_removeAllTiles:function(){for(var t in this._tiles)this._removeTile(t)},_invalidateAll:function(){for(var t in this._levels)T(this._levels[t].el),this._onRemoveLevel(Number(t)),delete this._levels[t];this._removeAllTiles(),this._tileZoom=void 0},_retainParent:function(t,e,i,n){var t=Math.floor(t/2),e=Math.floor(e/2),i=i-1,o=new p(+t,+e),o=(o.z=i,this._tileCoordsToKey(o)),o=this._tiles[o];return o&&o.active?o.retain=!0:(o&&o.loaded&&(o.retain=!0),n<i&&this._retainParent(t,e,i,n))},_retainChildren:function(t,e,i,n){for(var o=2*t;o<2*t+2;o++)for(var s=2*e;s<2*e+2;s++){var r=new p(o,s),r=(r.z=i+1,this._tileCoordsToKey(r)),r=this._tiles[r];r&&r.active?r.retain=!0:(r&&r.loaded&&(r.retain=!0),i+1<n&&this._retainChildren(o,s,i+1,n))}},_resetView:function(t){t=t&&(t.pinch||t.flyTo);this._setView(this._map.getCenter(),this._map.getZoom(),t,t)},_animateZoom:function(t){this._setView(t.center,t.zoom,!0,t.noUpdate)},_clampZoom:function(t){var e=this.options;return void 0!==e.minNativeZoom&&t<e.minNativeZoom?e.minNativeZoom:void 0!==e.maxNativeZoom&&e.maxNativeZoom<t?e.maxNativeZoom:t},_setView:function(t,e,i,n){var o=Math.round(e),o=void 0!==this.options.maxZoom&&o>this.options.maxZoom||void 0!==this.options.minZoom&&o<this.options.minZoom?void 0:this._clampZoom(o),s=this.options.updateWhenZooming&&o!==this._tileZoom;n&&!s||(this._tileZoom=o,this._abortLoading&&this._abortLoading(),this._updateLevels(),this._resetGrid(),void 0!==o&&this._update(t),i||this._pruneTiles(),this._noPrune=!!i),this._setZoomTransforms(t,e)},_setZoomTransforms:function(t,e){for(var i in this._levels)this._setZoomTransform(this._levels[i],t,e)},_setZoomTransform:function(t,e,i){var n=this._map.getZoomScale(i,t.zoom),e=t.origin.multiplyBy(n).subtract(this._map._getNewPixelOrigin(e,i)).round();b.any3d?be(t.el,e,n):Z(t.el,e)},_resetGrid:function(){var t=this._map,e=t.options.crs,i=this._tileSize=this.getTileSize(),n=this._tileZoom,o=this._map.getPixelWorldBounds(this._tileZoom);o&&(this._globalTileRange=this._pxBoundsToTileRange(o)),this._wrapX=e.wrapLng&&!this.options.noWrap&&[Math.floor(t.project([0,e.wrapLng[0]],n).x/i.x),Math.ceil(t.project([0,e.wrapLng[1]],n).x/i.y)],this._wrapY=e.wrapLat&&!this.options.noWrap&&[Math.floor(t.project([e.wrapLat[0],0],n).y/i.x),Math.ceil(t.project([e.wrapLat[1],0],n).y/i.y)]},_onMoveEnd:function(){this._map&&!this._map._animatingZoom&&this._update()},_getTiledPixelBounds:function(t){var e=this._map,i=e._animatingZoom?Math.max(e._animateToZoom,e.getZoom()):e.getZoom(),i=e.getZoomScale(i,this._tileZoom),t=e.project(t,this._tileZoom).floor(),e=e.getSize().divideBy(2*i);return new f(t.subtract(e),t.add(e))},_update:function(t){var e=this._map;if(e){var i=this._clampZoom(e.getZoom());if(void 0===t&&(t=e.getCenter()),void 0!==this._tileZoom){var n,e=this._getTiledPixelBounds(t),o=this._pxBoundsToTileRange(e),s=o.getCenter(),r=[],e=this.options.keepBuffer,a=new f(o.getBottomLeft().subtract([e,-e]),o.getTopRight().add([e,-e]));if(!(isFinite(o.min.x)&&isFinite(o.min.y)&&isFinite(o.max.x)&&isFinite(o.max.y)))throw new Error("Attempted to load an infinite number of tiles");for(n in this._tiles){var h=this._tiles[n].coords;h.z===this._tileZoom&&a.contains(new p(h.x,h.y))||(this._tiles[n].current=!1)}if(1<Math.abs(i-this._tileZoom))this._setView(t,i);else{for(var l=o.min.y;l<=o.max.y;l++)for(var u=o.min.x;u<=o.max.x;u++){var c,d=new p(u,l);d.z=this._tileZoom,this._isValidTile(d)&&((c=this._tiles[this._tileCoordsToKey(d)])?c.current=!0:r.push(d))}if(r.sort(function(t,e){return t.distanceTo(s)-e.distanceTo(s)}),0!==r.length){this._loading||(this._loading=!0,this.fire("loading"));for(var _=document.createDocumentFragment(),u=0;u<r.length;u++)this._addTile(r[u],_);this._level.el.appendChild(_)}}}}},_isValidTile:function(t){var e=this._map.options.crs;if(!e.infinite){var i=this._globalTileRange;if(!e.wrapLng&&(t.x<i.min.x||t.x>i.max.x)||!e.wrapLat&&(t.y<i.min.y||t.y>i.max.y))return!1}return!this.options.bounds||(e=this._tileCoordsToBounds(t),g(this.options.bounds).overlaps(e))},_keyToBounds:function(t){return this._tileCoordsToBounds(this._keyToTileCoords(t))},_tileCoordsToNwSe:function(t){var e=this._map,i=this.getTileSize(),n=t.scaleBy(i),i=n.add(i);return[e.unproject(n,t.z),e.unproject(i,t.z)]},_tileCoordsToBounds:function(t){t=this._tileCoordsToNwSe(t),t=new s(t[0],t[1]);return t=this.options.noWrap?t:this._map.wrapLatLngBounds(t)},_tileCoordsToKey:function(t){return t.x+":"+t.y+":"+t.z},_keyToTileCoords:function(t){var t=t.split(":"),e=new p(+t[0],+t[1]);return e.z=+t[2],e},_removeTile:function(t){var e=this._tiles[t];e&&(T(e.el),delete this._tiles[t],this.fire("tileunload",{tile:e.el,coords:this._keyToTileCoords(t)}))},_initTile:function(t){M(t,"leaflet-tile");var e=this.getTileSize();t.style.width=e.x+"px",t.style.height=e.y+"px",t.onselectstart=u,t.onmousemove=u,b.ielt9&&this.options.opacity<1&&C(t,this.options.opacity)},_addTile:function(t,e){var i=this._getTilePos(t),n=this._tileCoordsToKey(t),o=this.createTile(this._wrapCoords(t),a(this._tileReady,this,t));this._initTile(o),this.createTile.length<2&&x(a(this._tileReady,this,t,null,o)),Z(o,i),this._tiles[n]={el:o,coords:t,current:!0},e.appendChild(o),this.fire("tileloadstart",{tile:o,coords:t})},_tileReady:function(t,e,i){e&&this.fire("tileerror",{error:e,tile:i,coords:t});var n=this._tileCoordsToKey(t);(i=this._tiles[n])&&(i.loaded=+new Date,this._map._fadeAnimated?(C(i.el,0),r(this._fadeFrame),this._fadeFrame=x(this._updateOpacity,this)):(i.active=!0,this._pruneTiles()),e||(M(i.el,"leaflet-tile-loaded"),this.fire("tileload",{tile:i.el,coords:t})),this._noTilesToLoad()&&(this._loading=!1,this.fire("load"),b.ielt9||!this._map._fadeAnimated?x(this._pruneTiles,this):setTimeout(a(this._pruneTiles,this),250)))},_getTilePos:function(t){return t.scaleBy(this.getTileSize()).subtract(this._level.origin)},_wrapCoords:function(t){var e=new p(this._wrapX?H(t.x,this._wrapX):t.x,this._wrapY?H(t.y,this._wrapY):t.y);return e.z=t.z,e},_pxBoundsToTileRange:function(t){var e=this.getTileSize();return new f(t.min.unscaleBy(e).floor(),t.max.unscaleBy(e).ceil().subtract([1,1]))},_noTilesToLoad:function(){for(var t in this._tiles)if(!this._tiles[t].loaded)return!1;return!0}});var Di=Ni.extend({options:{minZoom:0,maxZoom:18,subdomains:"abc",errorTileUrl:"",zoomOffset:0,tms:!1,zoomReverse:!1,detectRetina:!1,crossOrigin:!1,referrerPolicy:!1},initialize:function(t,e){this._url=t,(e=c(this,e)).detectRetina&&b.retina&&0<e.maxZoom?(e.tileSize=Math.floor(e.tileSize/2),e.zoomReverse?(e.zoomOffset--,e.minZoom=Math.min(e.maxZoom,e.minZoom+1)):(e.zoomOffset++,e.maxZoom=Math.max(e.minZoom,e.maxZoom-1)),e.minZoom=Math.max(0,e.minZoom)):e.zoomReverse?e.minZoom=Math.min(e.maxZoom,e.minZoom):e.maxZoom=Math.max(e.minZoom,e.maxZoom),"string"==typeof e.subdomains&&(e.subdomains=e.subdomains.split("")),this.on("tileunload",this._onTileRemove)},setUrl:function(t,e){return this._url===t&&void 0===e&&(e=!0),this._url=t,e||this.redraw(),this},createTile:function(t,e){var i=document.createElement("img");return S(i,"load",a(this._tileOnLoad,this,e,i)),S(i,"error",a(this._tileOnError,this,e,i)),!this.options.crossOrigin&&""!==this.options.crossOrigin||(i.crossOrigin=!0===this.options.crossOrigin?"":this.options.crossOrigin),"string"==typeof this.options.referrerPolicy&&(i.referrerPolicy=this.options.referrerPolicy),i.alt="",i.src=this.getTileUrl(t),i},getTileUrl:function(t){var e={r:b.retina?"@2x":"",s:this._getSubdomain(t),x:t.x,y:t.y,z:this._getZoomForUrl()};return this._map&&!this._map.options.crs.infinite&&(t=this._globalTileRange.max.y-t.y,this.options.tms&&(e.y=t),e["-y"]=t),q(this._url,l(e,this.options))},_tileOnLoad:function(t,e){b.ielt9?setTimeout(a(t,this,null,e),0):t(null,e)},_tileOnError:function(t,e,i){var n=this.options.errorTileUrl;n&&e.getAttribute("src")!==n&&(e.src=n),t(i,e)},_onTileRemove:function(t){t.tile.onload=null},_getZoomForUrl:function(){var t=this._tileZoom,e=this.options.maxZoom;return(t=this.options.zoomReverse?e-t:t)+this.options.zoomOffset},_getSubdomain:function(t){t=Math.abs(t.x+t.y)%this.options.subdomains.length;return this.options.subdomains[t]},_abortLoading:function(){var t,e,i;for(t in this._tiles)this._tiles[t].coords.z!==this._tileZoom&&((i=this._tiles[t].el).onload=u,i.onerror=u,i.complete||(i.src=K,e=this._tiles[t].coords,T(i),delete this._tiles[t],this.fire("tileabort",{tile:i,coords:e})))},_removeTile:function(t){var e=this._tiles[t];if(e)return e.el.setAttribute("src",K),Ni.prototype._removeTile.call(this,t)},_tileReady:function(t,e,i){if(this._map&&(!i||i.getAttribute("src")!==K))return Ni.prototype._tileReady.call(this,t,e,i)}});function ji(t,e){return new Di(t,e)}var Hi=Di.extend({defaultWmsParams:{service:"WMS",request:"GetMap",layers:"",styles:"",format:"image/jpeg",transparent:!1,version:"1.1.1"},options:{crs:null,uppercase:!1},initialize:function(t,e){this._url=t;var i,n=l({},this.defaultWmsParams);for(i in e)i in this.options||(n[i]=e[i]);var t=(e=c(this,e)).detectRetina&&b.retina?2:1,o=this.getTileSize();n.width=o.x*t,n.height=o.y*t,this.wmsParams=n},onAdd:function(t){this._crs=this.options.crs||t.options.crs,this._wmsVersion=parseFloat(this.wmsParams.version);var e=1.3<=this._wmsVersion?"crs":"srs";this.wmsParams[e]=this._crs.code,Di.prototype.onAdd.call(this,t)},getTileUrl:function(t){var e=this._tileCoordsToNwSe(t),i=this._crs,i=_(i.project(e[0]),i.project(e[1])),e=i.min,i=i.max,e=(1.3<=this._wmsVersion&&this._crs===li?[e.y,e.x,i.y,i.x]:[e.x,e.y,i.x,i.y]).join(","),i=Di.prototype.getTileUrl.call(this,t);return i+U(this.wmsParams,i,this.options.uppercase)+(this.options.uppercase?"&BBOX=":"&bbox=")+e},setParams:function(t,e){return l(this.wmsParams,t),e||this.redraw(),this}});Di.WMS=Hi,ji.wms=function(t,e){return new Hi(t,e)};var Wi=o.extend({options:{padding:.1},initialize:function(t){c(this,t),h(this),this._layers=this._layers||{}},onAdd:function(){this._container||(this._initContainer(),M(this._container,"leaflet-zoom-animated")),this.getPane().appendChild(this._container),this._update(),this.on("update",this._updatePaths,this)},onRemove:function(){this.off("update",this._updatePaths,this),this._destroyContainer()},getEvents:function(){var t={viewreset:this._reset,zoom:this._onZoom,moveend:this._update,zoomend:this._onZoomEnd};return this._zoomAnimated&&(t.zoomanim=this._onAnimZoom),t},_onAnimZoom:function(t){this._updateTransform(t.center,t.zoom)},_onZoom:function(){this._updateTransform(this._map.getCenter(),this._map.getZoom())},_updateTransform:function(t,e){var i=this._map.getZoomScale(e,this._zoom),n=this._map.getSize().multiplyBy(.5+this.options.padding),o=this._map.project(this._center,e),n=n.multiplyBy(-i).add(o).subtract(this._map._getNewPixelOrigin(t,e));b.any3d?be(this._container,n,i):Z(this._container,n)},_reset:function(){for(var t in this._update(),this._updateTransform(this._center,this._zoom),this._layers)this._layers[t]._reset()},_onZoomEnd:function(){for(var t in this._layers)this._layers[t]._project()},_updatePaths:function(){for(var t in this._layers)this._layers[t]._update()},_update:function(){var t=this.options.padding,e=this._map.getSize(),i=this._map.containerPointToLayerPoint(e.multiplyBy(-t)).round();this._bounds=new f(i,i.add(e.multiplyBy(1+2*t)).round()),this._center=this._map.getCenter(),this._zoom=this._map.getZoom()}}),Fi=Wi.extend({options:{tolerance:0},getEvents:function(){var t=Wi.prototype.getEvents.call(this);return t.viewprereset=this._onViewPreReset,t},_onViewPreReset:function(){this._postponeUpdatePaths=!0},onAdd:function(){Wi.prototype.onAdd.call(this),this._draw()},_initContainer:function(){var t=this._container=document.createElement("canvas");S(t,"mousemove",this._onMouseMove,this),S(t,"click dblclick mousedown mouseup contextmenu",this._onClick,this),S(t,"mouseout",this._handleMouseOut,this),t._leaflet_disable_events=!0,this._ctx=t.getContext("2d")},_destroyContainer:function(){r(this._redrawRequest),delete this._ctx,T(this._container),k(this._container),delete this._container},_updatePaths:function(){if(!this._postponeUpdatePaths){for(var t in this._redrawBounds=null,this._layers)this._layers[t]._update();this._redraw()}},_update:function(){var t,e,i,n;this._map._animatingZoom&&this._bounds||(Wi.prototype._update.call(this),t=this._bounds,e=this._container,i=t.getSize(),n=b.retina?2:1,Z(e,t.min),e.width=n*i.x,e.height=n*i.y,e.style.width=i.x+"px",e.style.height=i.y+"px",b.retina&&this._ctx.scale(2,2),this._ctx.translate(-t.min.x,-t.min.y),this.fire("update"))},_reset:function(){Wi.prototype._reset.call(this),this._postponeUpdatePaths&&(this._postponeUpdatePaths=!1,this._updatePaths())},_initPath:function(t){this._updateDashArray(t);t=(this._layers[h(t)]=t)._order={layer:t,prev:this._drawLast,next:null};this._drawLast&&(this._drawLast.next=t),this._drawLast=t,this._drawFirst=this._drawFirst||this._drawLast},_addPath:function(t){this._requestRedraw(t)},_removePath:function(t){var e=t._order,i=e.next,e=e.prev;i?i.prev=e:this._drawLast=e,e?e.next=i:this._drawFirst=i,delete t._order,delete this._layers[h(t)],this._requestRedraw(t)},_updatePath:function(t){this._extendRedrawBounds(t),t._project(),t._update(),this._requestRedraw(t)},_updateStyle:function(t){this._updateDashArray(t),this._requestRedraw(t)},_updateDashArray:function(t){if("string"==typeof t.options.dashArray){for(var e,i=t.options.dashArray.split(/[, ]+/),n=[],o=0;o<i.length;o++){if(e=Number(i[o]),isNaN(e))return;n.push(e)}t.options._dashArray=n}else t.options._dashArray=t.options.dashArray},_requestRedraw:function(t){this._map&&(this._extendRedrawBounds(t),this._redrawRequest=this._redrawRequest||x(this._redraw,this))},_extendRedrawBounds:function(t){var e;t._pxBounds&&(e=(t.options.weight||0)+1,this._redrawBounds=this._redrawBounds||new f,this._redrawBounds.extend(t._pxBounds.min.subtract([e,e])),this._redrawBounds.extend(t._pxBounds.max.add([e,e])))},_redraw:function(){this._redrawRequest=null,this._redrawBounds&&(this._redrawBounds.min._floor(),this._redrawBounds.max._ceil()),this._clear(),this._draw(),this._redrawBounds=null},_clear:function(){var t,e=this._redrawBounds;e?(t=e.getSize(),this._ctx.clearRect(e.min.x,e.min.y,t.x,t.y)):(this._ctx.save(),this._ctx.setTransform(1,0,0,1,0,0),this._ctx.clearRect(0,0,this._container.width,this._container.height),this._ctx.restore())},_draw:function(){var t,e,i=this._redrawBounds;this._ctx.save(),i&&(e=i.getSize(),this._ctx.beginPath(),this._ctx.rect(i.min.x,i.min.y,e.x,e.y),this._ctx.clip()),this._drawing=!0;for(var n=this._drawFirst;n;n=n.next)t=n.layer,(!i||t._pxBounds&&t._pxBounds.intersects(i))&&t._updatePath();this._drawing=!1,this._ctx.restore()},_updatePoly:function(t,e){if(this._drawing){var i,n,o,s,r=t._parts,a=r.length,h=this._ctx;if(a){for(h.beginPath(),i=0;i<a;i++){for(n=0,o=r[i].length;n<o;n++)s=r[i][n],h[n?"lineTo":"moveTo"](s.x,s.y);e&&h.closePath()}this._fillStroke(h,t)}}},_updateCircle:function(t){var e,i,n,o;this._drawing&&!t._empty()&&(e=t._point,i=this._ctx,n=Math.max(Math.round(t._radius),1),1!=(o=(Math.max(Math.round(t._radiusY),1)||n)/n)&&(i.save(),i.scale(1,o)),i.beginPath(),i.arc(e.x,e.y/o,n,0,2*Math.PI,!1),1!=o&&i.restore(),this._fillStroke(i,t))},_fillStroke:function(t,e){var i=e.options;i.fill&&(t.globalAlpha=i.fillOpacity,t.fillStyle=i.fillColor||i.color,t.fill(i.fillRule||"evenodd")),i.stroke&&0!==i.weight&&(t.setLineDash&&t.setLineDash(e.options&&e.options._dashArray||[]),t.globalAlpha=i.opacity,t.lineWidth=i.weight,t.strokeStyle=i.color,t.lineCap=i.lineCap,t.lineJoin=i.lineJoin,t.stroke())},_onClick:function(t){for(var e,i,n=this._map.mouseEventToLayerPoint(t),o=this._drawFirst;o;o=o.next)(e=o.layer).options.interactive&&e._containsPoint(n)&&(("click"===t.type||"preclick"===t.type)&&this._map._draggableMoved(e)||(i=e));this._fireEvent(!!i&&[i],t)},_onMouseMove:function(t){var e;!this._map||this._map.dragging.moving()||this._map._animatingZoom||(e=this._map.mouseEventToLayerPoint(t),this._handleMouseHover(t,e))},_handleMouseOut:function(t){var e=this._hoveredLayer;e&&(z(this._container,"leaflet-interactive"),this._fireEvent([e],t,"mouseout"),this._hoveredLayer=null,this._mouseHoverThrottled=!1)},_handleMouseHover:function(t,e){if(!this._mouseHoverThrottled){for(var i,n,o=this._drawFirst;o;o=o.next)(i=o.layer).options.interactive&&i._containsPoint(e)&&(n=i);n!==this._hoveredLayer&&(this._handleMouseOut(t),n&&(M(this._container,"leaflet-interactive"),this._fireEvent([n],t,"mouseover"),this._hoveredLayer=n)),this._fireEvent(!!this._hoveredLayer&&[this._hoveredLayer],t),this._mouseHoverThrottled=!0,setTimeout(a(function(){this._mouseHoverThrottled=!1},this),32)}},_fireEvent:function(t,e,i){this._map._fireDOMEvent(e,i||e.type,t)},_bringToFront:function(t){var e,i,n=t._order;n&&(e=n.next,i=n.prev,e&&((e.prev=i)?i.next=e:e&&(this._drawFirst=e),n.prev=this._drawLast,(this._drawLast.next=n).next=null,this._drawLast=n,this._requestRedraw(t)))},_bringToBack:function(t){var e,i,n=t._order;n&&(e=n.next,(i=n.prev)&&((i.next=e)?e.prev=i:i&&(this._drawLast=i),n.prev=null,n.next=this._drawFirst,this._drawFirst.prev=n,this._drawFirst=n,this._requestRedraw(t)))}});function Ui(t){return b.canvas?new Fi(t):null}var Vi=function(){try{return document.namespaces.add("lvml","urn:schemas-microsoft-com:vml"),function(t){return document.createElement("<lvml:"+t+' class="lvml">')}}catch(t){}return function(t){return document.createElement("<"+t+' xmlns="urn:schemas-microsoft.com:vml" class="lvml">')}}(),zt={_initContainer:function(){this._container=P("div","leaflet-vml-container")},_update:function(){this._map._animatingZoom||(Wi.prototype._update.call(this),this.fire("update"))},_initPath:function(t){var e=t._container=Vi("shape");M(e,"leaflet-vml-shape "+(this.options.className||"")),e.coordsize="1 1",t._path=Vi("path"),e.appendChild(t._path),this._updateStyle(t),this._layers[h(t)]=t},_addPath:function(t){var e=t._container;this._container.appendChild(e),t.options.interactive&&t.addInteractiveTarget(e)},_removePath:function(t){var e=t._container;T(e),t.removeInteractiveTarget(e),delete this._layers[h(t)]},_updateStyle:function(t){var e=t._stroke,i=t._fill,n=t.options,o=t._container;o.stroked=!!n.stroke,o.filled=!!n.fill,n.stroke?(e=e||(t._stroke=Vi("stroke")),o.appendChild(e),e.weight=n.weight+"px",e.color=n.color,e.opacity=n.opacity,n.dashArray?e.dashStyle=d(n.dashArray)?n.dashArray.join(" "):n.dashArray.replace(/( *, *)/g," "):e.dashStyle="",e.endcap=n.lineCap.replace("butt","flat"),e.joinstyle=n.lineJoin):e&&(o.removeChild(e),t._stroke=null),n.fill?(i=i||(t._fill=Vi("fill")),o.appendChild(i),i.color=n.fillColor||n.color,i.opacity=n.fillOpacity):i&&(o.removeChild(i),t._fill=null)},_updateCircle:function(t){var e=t._point.round(),i=Math.round(t._radius),n=Math.round(t._radiusY||i);this._setPath(t,t._empty()?"M0 0":"AL "+e.x+","+e.y+" "+i+","+n+" 0,23592600")},_setPath:function(t,e){t._path.v=e},_bringToFront:function(t){fe(t._container)},_bringToBack:function(t){ge(t._container)}},qi=b.vml?Vi:ct,Gi=Wi.extend({_initContainer:function(){this._container=qi("svg"),this._container.setAttribute("pointer-events","none"),this._rootGroup=qi("g"),this._container.appendChild(this._rootGroup)},_destroyContainer:function(){T(this._container),k(this._container),delete this._container,delete this._rootGroup,delete this._svgSize},_update:function(){var t,e,i;this._map._animatingZoom&&this._bounds||(Wi.prototype._update.call(this),e=(t=this._bounds).getSize(),i=this._container,this._svgSize&&this._svgSize.equals(e)||(this._svgSize=e,i.setAttribute("width",e.x),i.setAttribute("height",e.y)),Z(i,t.min),i.setAttribute("viewBox",[t.min.x,t.min.y,e.x,e.y].join(" ")),this.fire("update"))},_initPath:function(t){var e=t._path=qi("path");t.options.className&&M(e,t.options.className),t.options.interactive&&M(e,"leaflet-interactive"),this._updateStyle(t),this._layers[h(t)]=t},_addPath:function(t){this._rootGroup||this._initContainer(),this._rootGroup.appendChild(t._path),t.addInteractiveTarget(t._path)},_removePath:function(t){T(t._path),t.removeInteractiveTarget(t._path),delete this._layers[h(t)]},_updatePath:function(t){t._project(),t._update()},_updateStyle:function(t){var e=t._path,t=t.options;e&&(t.stroke?(e.setAttribute("stroke",t.color),e.setAttribute("stroke-opacity",t.opacity),e.setAttribute("stroke-width",t.weight),e.setAttribute("stroke-linecap",t.lineCap),e.setAttribute("stroke-linejoin",t.lineJoin),t.dashArray?e.setAttribute("stroke-dasharray",t.dashArray):e.removeAttribute("stroke-dasharray"),t.dashOffset?e.setAttribute("stroke-dashoffset",t.dashOffset):e.removeAttribute("stroke-dashoffset")):e.setAttribute("stroke","none"),t.fill?(e.setAttribute("fill",t.fillColor||t.color),e.setAttribute("fill-opacity",t.fillOpacity),e.setAttribute("fill-rule",t.fillRule||"evenodd")):e.setAttribute("fill","none"))},_updatePoly:function(t,e){this._setPath(t,dt(t._parts,e))},_updateCircle:function(t){var e=t._point,i=Math.max(Math.round(t._radius),1),n="a"+i+","+(Math.max(Math.round(t._radiusY),1)||i)+" 0 1,0 ",e=t._empty()?"M0 0":"M"+(e.x-i)+","+e.y+n+2*i+",0 "+n+2*-i+",0 ";this._setPath(t,e)},_setPath:function(t,e){t._path.setAttribute("d",e)},_bringToFront:function(t){fe(t._path)},_bringToBack:function(t){ge(t._path)}});function Ki(t){return b.svg||b.vml?new Gi(t):null}b.vml&&Gi.include(zt),A.include({getRenderer:function(t){t=(t=t.options.renderer||this._getPaneRenderer(t.options.pane)||this.options.renderer||this._renderer)||(this._renderer=this._createRenderer());return this.hasLayer(t)||this.addLayer(t),t},_getPaneRenderer:function(t){var e;return"overlayPane"!==t&&void 0!==t&&(void 0===(e=this._paneRenderers[t])&&(e=this._createRenderer({pane:t}),this._paneRenderers[t]=e),e)},_createRenderer:function(t){return this.options.preferCanvas&&Ui(t)||Ki(t)}});var Yi=xi.extend({initialize:function(t,e){xi.prototype.initialize.call(this,this._boundsToLatLngs(t),e)},setBounds:function(t){return this.setLatLngs(this._boundsToLatLngs(t))},_boundsToLatLngs:function(t){return[(t=g(t)).getSouthWest(),t.getNorthWest(),t.getNorthEast(),t.getSouthEast()]}});Gi.create=qi,Gi.pointsToPath=dt,wi.geometryToLayer=bi,wi.coordsToLatLng=Li,wi.coordsToLatLngs=Ti,wi.latLngToCoords=Mi,wi.latLngsToCoords=zi,wi.getFeature=Ci,wi.asFeature=Zi,A.mergeOptions({boxZoom:!0});var _t=n.extend({initialize:function(t){this._map=t,this._container=t._container,this._pane=t._panes.overlayPane,this._resetStateTimeout=0,t.on("unload",this._destroy,this)},addHooks:function(){S(this._container,"mousedown",this._onMouseDown,this)},removeHooks:function(){k(this._container,"mousedown",this._onMouseDown,this)},moved:function(){return this._moved},_destroy:function(){T(this._pane),delete this._pane},_resetState:function(){this._resetStateTimeout=0,this._moved=!1},_clearDeferredResetState:function(){0!==this._resetStateTimeout&&(clearTimeout(this._resetStateTimeout),this._resetStateTimeout=0)},_onMouseDown:function(t){if(!t.shiftKey||1!==t.which&&1!==t.button)return!1;this._clearDeferredResetState(),this._resetState(),re(),Le(),this._startPoint=this._map.mouseEventToContainerPoint(t),S(document,{contextmenu:Re,mousemove:this._onMouseMove,mouseup:this._onMouseUp,keydown:this._onKeyDown},this)},_onMouseMove:function(t){this._moved||(this._moved=!0,this._box=P("div","leaflet-zoom-box",this._container),M(this._container,"leaflet-crosshair"),this._map.fire("boxzoomstart")),this._point=this._map.mouseEventToContainerPoint(t);var t=new f(this._point,this._startPoint),e=t.getSize();Z(this._box,t.min),this._box.style.width=e.x+"px",this._box.style.height=e.y+"px"},_finish:function(){this._moved&&(T(this._box),z(this._container,"leaflet-crosshair")),ae(),Te(),k(document,{contextmenu:Re,mousemove:this._onMouseMove,mouseup:this._onMouseUp,keydown:this._onKeyDown},this)},_onMouseUp:function(t){1!==t.which&&1!==t.button||(this._finish(),this._moved&&(this._clearDeferredResetState(),this._resetStateTimeout=setTimeout(a(this._resetState,this),0),t=new s(this._map.containerPointToLatLng(this._startPoint),this._map.containerPointToLatLng(this._point)),this._map.fitBounds(t).fire("boxzoomend",{boxZoomBounds:t})))},_onKeyDown:function(t){27===t.keyCode&&(this._finish(),this._clearDeferredResetState(),this._resetState())}}),Ct=(A.addInitHook("addHandler","boxZoom",_t),A.mergeOptions({doubleClickZoom:!0}),n.extend({addHooks:function(){this._map.on("dblclick",this._onDoubleClick,this)},removeHooks:function(){this._map.off("dblclick",this._onDoubleClick,this)},_onDoubleClick:function(t){var e=this._map,i=e.getZoom(),n=e.options.zoomDelta,i=t.originalEvent.shiftKey?i-n:i+n;"center"===e.options.doubleClickZoom?e.setZoom(i):e.setZoomAround(t.containerPoint,i)}})),Zt=(A.addInitHook("addHandler","doubleClickZoom",Ct),A.mergeOptions({dragging:!0,inertia:!0,inertiaDeceleration:3400,inertiaMaxSpeed:1/0,easeLinearity:.2,worldCopyJump:!1,maxBoundsViscosity:0}),n.extend({addHooks:function(){var t;this._draggable||(t=this._map,this._draggable=new Xe(t._mapPane,t._container),this._draggable.on({dragstart:this._onDragStart,drag:this._onDrag,dragend:this._onDragEnd},this),this._draggable.on("predrag",this._onPreDragLimit,this),t.options.worldCopyJump&&(this._draggable.on("predrag",this._onPreDragWrap,this),t.on("zoomend",this._onZoomEnd,this),t.whenReady(this._onZoomEnd,this))),M(this._map._container,"leaflet-grab leaflet-touch-drag"),this._draggable.enable(),this._positions=[],this._times=[]},removeHooks:function(){z(this._map._container,"leaflet-grab"),z(this._map._container,"leaflet-touch-drag"),this._draggable.disable()},moved:function(){return this._draggable&&this._draggable._moved},moving:function(){return this._draggable&&this._draggable._moving},_onDragStart:function(){var t,e=this._map;e._stop(),this._map.options.maxBounds&&this._map.options.maxBoundsViscosity?(t=g(this._map.options.maxBounds),this._offsetLimit=_(this._map.latLngToContainerPoint(t.getNorthWest()).multiplyBy(-1),this._map.latLngToContainerPoint(t.getSouthEast()).multiplyBy(-1).add(this._map.getSize())),this._viscosity=Math.min(1,Math.max(0,this._map.options.maxBoundsViscosity))):this._offsetLimit=null,e.fire("movestart").fire("dragstart"),e.options.inertia&&(this._positions=[],this._times=[])},_onDrag:function(t){var e,i;this._map.options.inertia&&(e=this._lastTime=+new Date,i=this._lastPos=this._draggable._absPos||this._draggable._newPos,this._positions.push(i),this._times.push(e),this._prunePositions(e)),this._map.fire("move",t).fire("drag",t)},_prunePositions:function(t){for(;1<this._positions.length&&50<t-this._times[0];)this._positions.shift(),this._times.shift()},_onZoomEnd:function(){var t=this._map.getSize().divideBy(2),e=this._map.latLngToLayerPoint([0,0]);this._initialWorldOffset=e.subtract(t).x,this._worldWidth=this._map.getPixelWorldBounds().getSize().x},_viscousLimit:function(t,e){return t-(t-e)*this._viscosity},_onPreDragLimit:function(){var t,e;this._viscosity&&this._offsetLimit&&(t=this._draggable._newPos.subtract(this._draggable._startPos),e=this._offsetLimit,t.x<e.min.x&&(t.x=this._viscousLimit(t.x,e.min.x)),t.y<e.min.y&&(t.y=this._viscousLimit(t.y,e.min.y)),t.x>e.max.x&&(t.x=this._viscousLimit(t.x,e.max.x)),t.y>e.max.y&&(t.y=this._viscousLimit(t.y,e.max.y)),this._draggable._newPos=this._draggable._startPos.add(t))},_onPreDragWrap:function(){var t=this._worldWidth,e=Math.round(t/2),i=this._initialWorldOffset,n=this._draggable._newPos.x,o=(n-e+i)%t+e-i,n=(n+e+i)%t-e-i,t=Math.abs(o+i)<Math.abs(n+i)?o:n;this._draggable._absPos=this._draggable._newPos.clone(),this._draggable._newPos.x=t},_onDragEnd:function(t){var e,i,n,o,s=this._map,r=s.options,a=!r.inertia||t.noInertia||this._times.length<2;s.fire("dragend",t),!a&&(this._prunePositions(+new Date),t=this._lastPos.subtract(this._positions[0]),a=(this._lastTime-this._times[0])/1e3,e=r.easeLinearity,a=(t=t.multiplyBy(e/a)).distanceTo([0,0]),i=Math.min(r.inertiaMaxSpeed,a),t=t.multiplyBy(i/a),n=i/(r.inertiaDeceleration*e),(o=t.multiplyBy(-n/2).round()).x||o.y)?(o=s._limitOffset(o,s.options.maxBounds),x(function(){s.panBy(o,{duration:n,easeLinearity:e,noMoveStart:!0,animate:!0})})):s.fire("moveend")}})),St=(A.addInitHook("addHandler","dragging",Zt),A.mergeOptions({keyboard:!0,keyboardPanDelta:80}),n.extend({keyCodes:{left:[37],right:[39],down:[40],up:[38],zoomIn:[187,107,61,171],zoomOut:[189,109,54,173]},initialize:function(t){this._map=t,this._setPanDelta(t.options.keyboardPanDelta),this._setZoomDelta(t.options.zoomDelta)},addHooks:function(){var t=this._map._container;t.tabIndex<=0&&(t.tabIndex="0"),S(t,{focus:this._onFocus,blur:this._onBlur,mousedown:this._onMouseDown},this),this._map.on({focus:this._addHooks,blur:this._removeHooks},this)},removeHooks:function(){this._removeHooks(),k(this._map._container,{focus:this._onFocus,blur:this._onBlur,mousedown:this._onMouseDown},this),this._map.off({focus:this._addHooks,blur:this._removeHooks},this)},_onMouseDown:function(){var t,e,i;this._focused||(i=document.body,t=document.documentElement,e=i.scrollTop||t.scrollTop,i=i.scrollLeft||t.scrollLeft,this._map._container.focus(),window.scrollTo(i,e))},_onFocus:function(){this._focused=!0,this._map.fire("focus")},_onBlur:function(){this._focused=!1,this._map.fire("blur")},_setPanDelta:function(t){for(var e=this._panKeys={},i=this.keyCodes,n=0,o=i.left.length;n<o;n++)e[i.left[n]]=[-1*t,0];for(n=0,o=i.right.length;n<o;n++)e[i.right[n]]=[t,0];for(n=0,o=i.down.length;n<o;n++)e[i.down[n]]=[0,t];for(n=0,o=i.up.length;n<o;n++)e[i.up[n]]=[0,-1*t]},_setZoomDelta:function(t){for(var e=this._zoomKeys={},i=this.keyCodes,n=0,o=i.zoomIn.length;n<o;n++)e[i.zoomIn[n]]=t;for(n=0,o=i.zoomOut.length;n<o;n++)e[i.zoomOut[n]]=-t},_addHooks:function(){S(document,"keydown",this._onKeyDown,this)},_removeHooks:function(){k(document,"keydown",this._onKeyDown,this)},_onKeyDown:function(t){if(!(t.altKey||t.ctrlKey||t.metaKey)){var e,i,n=t.keyCode,o=this._map;if(n in this._panKeys)o._panAnim&&o._panAnim._inProgress||(i=this._panKeys[n],t.shiftKey&&(i=m(i).multiplyBy(3)),o.options.maxBounds&&(i=o._limitOffset(m(i),o.options.maxBounds)),o.options.worldCopyJump?(e=o.wrapLatLng(o.unproject(o.project(o.getCenter()).add(i))),o.panTo(e)):o.panBy(i));else if(n in this._zoomKeys)o.setZoom(o.getZoom()+(t.shiftKey?3:1)*this._zoomKeys[n]);else{if(27!==n||!o._popup||!o._popup.options.closeOnEscapeKey)return;o.closePopup()}Re(t)}}})),Et=(A.addInitHook("addHandler","keyboard",St),A.mergeOptions({scrollWheelZoom:!0,wheelDebounceTime:40,wheelPxPerZoomLevel:60}),n.extend({addHooks:function(){S(this._map._container,"wheel",this._onWheelScroll,this),this._delta=0},removeHooks:function(){k(this._map._container,"wheel",this._onWheelScroll,this)},_onWheelScroll:function(t){var e=He(t),i=this._map.options.wheelDebounceTime,e=(this._delta+=e,this._lastMousePos=this._map.mouseEventToContainerPoint(t),this._startTime||(this._startTime=+new Date),Math.max(i-(+new Date-this._startTime),0));clearTimeout(this._timer),this._timer=setTimeout(a(this._performZoom,this),e),Re(t)},_performZoom:function(){var t=this._map,e=t.getZoom(),i=this._map.options.zoomSnap||0,n=(t._stop(),this._delta/(4*this._map.options.wheelPxPerZoomLevel)),n=4*Math.log(2/(1+Math.exp(-Math.abs(n))))/Math.LN2,i=i?Math.ceil(n/i)*i:n,n=t._limitZoom(e+(0<this._delta?i:-i))-e;this._delta=0,this._startTime=null,n&&("center"===t.options.scrollWheelZoom?t.setZoom(e+n):t.setZoomAround(this._lastMousePos,e+n))}})),kt=(A.addInitHook("addHandler","scrollWheelZoom",Et),A.mergeOptions({tapHold:b.touchNative&&b.safari&&b.mobile,tapTolerance:15}),n.extend({addHooks:function(){S(this._map._container,"touchstart",this._onDown,this)},removeHooks:function(){k(this._map._container,"touchstart",this._onDown,this)},_onDown:function(t){var e;clearTimeout(this._holdTimeout),1===t.touches.length&&(e=t.touches[0],this._startPos=this._newPos=new p(e.clientX,e.clientY),this._holdTimeout=setTimeout(a(function(){this._cancel(),this._isTapValid()&&(S(document,"touchend",O),S(document,"touchend touchcancel",this._cancelClickPrevent),this._simulateEvent("contextmenu",e))},this),600),S(document,"touchend touchcancel contextmenu",this._cancel,this),S(document,"touchmove",this._onMove,this))},_cancelClickPrevent:function t(){k(document,"touchend",O),k(document,"touchend touchcancel",t)},_cancel:function(){clearTimeout(this._holdTimeout),k(document,"touchend touchcancel contextmenu",this._cancel,this),k(document,"touchmove",this._onMove,this)},_onMove:function(t){t=t.touches[0];this._newPos=new p(t.clientX,t.clientY)},_isTapValid:function(){return this._newPos.distanceTo(this._startPos)<=this._map.options.tapTolerance},_simulateEvent:function(t,e){t=new MouseEvent(t,{bubbles:!0,cancelable:!0,view:window,screenX:e.screenX,screenY:e.screenY,clientX:e.clientX,clientY:e.clientY});t._simulated=!0,e.target.dispatchEvent(t)}})),Ot=(A.addInitHook("addHandler","tapHold",kt),A.mergeOptions({touchZoom:b.touch,bounceAtZoomLimits:!0}),n.extend({addHooks:function(){M(this._map._container,"leaflet-touch-zoom"),S(this._map._container,"touchstart",this._onTouchStart,this)},removeHooks:function(){z(this._map._container,"leaflet-touch-zoom"),k(this._map._container,"touchstart",this._onTouchStart,this)},_onTouchStart:function(t){var e,i,n=this._map;!t.touches||2!==t.touches.length||n._animatingZoom||this._zooming||(e=n.mouseEventToContainerPoint(t.touches[0]),i=n.mouseEventToContainerPoint(t.touches[1]),this._centerPoint=n.getSize()._divideBy(2),this._startLatLng=n.containerPointToLatLng(this._centerPoint),"center"!==n.options.touchZoom&&(this._pinchStartLatLng=n.containerPointToLatLng(e.add(i)._divideBy(2))),this._startDist=e.distanceTo(i),this._startZoom=n.getZoom(),this._moved=!1,this._zooming=!0,n._stop(),S(document,"touchmove",this._onTouchMove,this),S(document,"touchend touchcancel",this._onTouchEnd,this),O(t))},_onTouchMove:function(t){if(t.touches&&2===t.touches.length&&this._zooming){var e=this._map,i=e.mouseEventToContainerPoint(t.touches[0]),n=e.mouseEventToContainerPoint(t.touches[1]),o=i.distanceTo(n)/this._startDist;if(this._zoom=e.getScaleZoom(o,this._startZoom),!e.options.bounceAtZoomLimits&&(this._zoom<e.getMinZoom()&&o<1||this._zoom>e.getMaxZoom()&&1<o)&&(this._zoom=e._limitZoom(this._zoom)),"center"===e.options.touchZoom){if(this._center=this._startLatLng,1==o)return}else{i=i._add(n)._divideBy(2)._subtract(this._centerPoint);if(1==o&&0===i.x&&0===i.y)return;this._center=e.unproject(e.project(this._pinchStartLatLng,this._zoom).subtract(i),this._zoom)}this._moved||(e._moveStart(!0,!1),this._moved=!0),r(this._animRequest);n=a(e._move,e,this._center,this._zoom,{pinch:!0,round:!1},void 0);this._animRequest=x(n,this,!0),O(t)}},_onTouchEnd:function(){this._moved&&this._zooming?(this._zooming=!1,r(this._animRequest),k(document,"touchmove",this._onTouchMove,this),k(document,"touchend touchcancel",this._onTouchEnd,this),this._map.options.zoomAnimation?this._map._animateZoom(this._center,this._map._limitZoom(this._zoom),!0,this._map.options.zoomSnap):this._map._resetView(this._center,this._map._limitZoom(this._zoom))):this._zooming=!1}})),Xi=(A.addInitHook("addHandler","touchZoom",Ot),A.BoxZoom=_t,A.DoubleClickZoom=Ct,A.Drag=Zt,A.Keyboard=St,A.ScrollWheelZoom=Et,A.TapHold=kt,A.TouchZoom=Ot,t.Bounds=f,t.Browser=b,t.CRS=ot,t.Canvas=Fi,t.Circle=vi,t.CircleMarker=gi,t.Class=et,t.Control=B,t.DivIcon=Ri,t.DivOverlay=Ai,t.DomEvent=mt,t.DomUtil=pt,t.Draggable=Xe,t.Evented=it,t.FeatureGroup=ci,t.GeoJSON=wi,t.GridLayer=Ni,t.Handler=n,t.Icon=di,t.ImageOverlay=Ei,t.LatLng=v,t.LatLngBounds=s,t.Layer=o,t.LayerGroup=ui,t.LineUtil=vt,t.Map=A,t.Marker=mi,t.Mixin=ft,t.Path=fi,t.Point=p,t.PolyUtil=gt,t.Polygon=xi,t.Polyline=yi,t.Popup=Bi,t.PosAnimation=Fe,t.Projection=wt,t.Rectangle=Yi,t.Renderer=Wi,t.SVG=Gi,t.SVGOverlay=Oi,t.TileLayer=Di,t.Tooltip=Ii,t.Transformation=at,t.Util=tt,t.VideoOverlay=ki,t.bind=a,t.bounds=_,t.canvas=Ui,t.circle=function(t,e,i){return new vi(t,e,i)},t.circleMarker=function(t,e){return new gi(t,e)},t.control=Ue,t.divIcon=function(t){return new Ri(t)},t.extend=l,t.featureGroup=function(t,e){return new ci(t,e)},t.geoJSON=Si,t.geoJson=Mt,t.gridLayer=function(t){return new Ni(t)},t.icon=function(t){return new di(t)},t.imageOverlay=function(t,e,i){return new Ei(t,e,i)},t.latLng=w,t.latLngBounds=g,t.layerGroup=function(t,e){return new ui(t,e)},t.map=function(t,e){return new A(t,e)},t.marker=function(t,e){return new mi(t,e)},t.point=m,t.polygon=function(t,e){return new xi(t,e)},t.polyline=function(t,e){return new yi(t,e)},t.popup=function(t,e){return new Bi(t,e)},t.rectangle=function(t,e){return new Yi(t,e)},t.setOptions=c,t.stamp=h,t.svg=Ki,t.svgOverlay=function(t,e,i){return new Oi(t,e,i)},t.tileLayer=ji,t.tooltip=function(t,e){return new Ii(t,e)},t.transformation=ht,t.version="1.9.4",t.videoOverlay=function(t,e,i){return new ki(t,e,i)},window.L);t.noConflict=function(){return window.L=Xi,this},window.L=t});
+//# sourceMappingURL=leaflet.js.map
\ No newline at end of file