diff --git a/web/main.py b/web/main.py index c29321201064727b7da14d1ba61c613460070f6f..92ecf4e3a8832643eb8b7430b88e2686f2b0f353 100644 --- a/web/main.py +++ b/web/main.py @@ -1,10 +1,11 @@ -"""HeliOS-NYC web UI — FastAPI + SSE streaming of the Burr FSM trace. +"""Riprap web UI — FastAPI + SSE streaming of the Burr FSM trace. Run: uvicorn web.main:app --reload --port 8000 """ from __future__ import annotations import json +import os import warnings from pathlib import Path @@ -20,14 +21,21 @@ from app.fsm import iter_steps # noqa: E402 ROOT = Path(__file__).resolve().parent STATIC = ROOT / "static" +SVELTEKIT_BUILD = ROOT / "sveltekit" / "build" app = FastAPI(title="Riprap") app.mount("/static", StaticFiles(directory=STATIC), name="static") +# SvelteKit static build (adapter-static). Serves the new design-system UI +# from /, /q/sample, /q/. The legacy custom-element pages remain at +# /legacy, /single, /compare, /register/* for as long as they're useful. +if SVELTEKIT_BUILD.exists(): + app.mount("/_app", StaticFiles(directory=SVELTEKIT_BUILD / "_app"), name="sveltekit_assets") + import json as _json # noqa: E402 import geopandas as _gpd # noqa: E402 -from fastapi.responses import JSONResponse, Response # noqa: E402 +from fastapi.responses import JSONResponse # noqa: E402 _LAYER_CACHE: dict = {} @@ -74,13 +82,221 @@ def _warm_caches(): dep_stormwater.load(scen) print("[startup] flood layers ready", flush=True) print("[startup] warming RAG (Granite Embedding 278M + 5 PDFs)...", flush=True) - from app import rag - rag.warm() - print("[startup] RAG ready", flush=True) + # RAG warm loads sentence-transformers, which on some HF Space rebuilds + # has hit transformers-lazy-import edge cases (CodeCarbonCallback). The + # Space *must* start even if RAG fails — the FSM still works without + # RAG citations (specialists deliver their own grounded data, and the + # rag step in fsm.py already handles `rag=[]` gracefully). Surface the + # failure loudly in logs but don't kill the app. + try: + from app import rag + rag.warm() + print("[startup] RAG ready", flush=True) + except Exception as e: # noqa: BLE001 + print(f"[startup] RAG warm FAILED — continuing without RAG: " + f"{type(e).__name__}: {e}", flush=True) + import traceback + traceback.print_exc() + # Pre-import the heavy EO/ML stacks on the main thread so the + # parallel-fanout workers don't race each other on first + # import (sklearn's "partially initialized module" surfaces as a + # spurious ImportError when terratorch / tsfm_public both pull + # sklearn concurrently from worker threads). + # Warm the Ollama LLM models so the first user query doesn't pay a + # cold-load penalty (~70 s for the 3B planner, ~12 s for the 8B + # reconciler at Q4_K_M). Sets keep_alive to 24 h so they stay + # resident across queries. Both calls use num_ctx that matches the + # production call sites (Mellea's 4096), so Ollama's KV cache is + # pre-allocated at the right size and the first reconcile doesn't + # pay an extra grow-and-reinit cost. + if os.environ.get("RIPRAP_SKIP_LLM_WARM", "").lower() not in ("1", "true", "yes"): + print("[startup] warming Ollama models (granite4.1:3b + 8b)...", + flush=True) + try: + import httpx as _httpx + base = os.environ.get( + "OLLAMA_BASE_URL", + os.environ.get("OLLAMA_HOST", "http://localhost:11434"), + ) + if not base.startswith("http"): + base = "http://" + base + keep_alive = os.environ.get("OLLAMA_KEEP_ALIVE", "24h") + num_ctx = int(os.environ.get("RIPRAP_MELLEA_NUM_CTX", "4096")) + for tag in (os.environ.get("RIPRAP_OLLAMA_3B_TAG", "granite4.1:3b"), + os.environ.get("RIPRAP_OLLAMA_8B_TAG", "granite4.1:8b")): + try: + r = _httpx.post( + base.rstrip("/") + "/api/generate", + json={ + "model": tag, + "prompt": "hi", + "stream": False, + "keep_alive": keep_alive, + "options": {"num_ctx": num_ctx, "num_predict": 1}, + }, + timeout=180, + ) + if r.status_code == 200: + load_s = r.json().get("load_duration", 0) / 1e9 + print(f"[startup] {tag} loaded " + f"(load_duration={load_s:.1f}s, " + f"keep_alive={keep_alive}, num_ctx={num_ctx})", + flush=True) + else: + print(f"[startup] {tag} warm failed " + f"({r.status_code})", flush=True) + except Exception as warm_err: + print(f"[startup] {tag} warm failed: {warm_err}", + flush=True) + except Exception as e: + print(f"[startup] LLM warm skipped: {e}", flush=True) + print("[startup] pre-importing terratorch + tsfm_public...", flush=True) + try: + import sklearn # noqa: F401 prime sklearn first + import terratorch # noqa: F401 + import tsfm_public # noqa: F401 + except Exception as e: + print(f"[startup] heavy-EO pre-import skipped: {e}", flush=True) + # Warm the TerraMind specialist so first per-query call is just + # the diffusion (~3 s), not model load (~30 s). No-ops if deps + # are missing on this deployment. + try: + from app.context import terramind_synthesis + terramind_synthesis.warm() + print("[startup] TerraMind ready", flush=True) + except Exception as e: + print(f"[startup] TerraMind warm skipped: {e}", flush=True) + + +@app.get("/api/debug/eo") +def api_debug_eo(): + """Diagnostic for the EO toolchain (Phase 1 + Phase 4) on HF Spaces. + + Surfaces sys.path, PYTHONPATH, and per-module import status so we + can tell whether terratorch is actually findable from inside the + uvicorn process. Used to debug why the runtime --target install + appears to succeed in the entrypoint but isn't visible to the + FSM specialists at request time. + """ + import os + import sys + import traceback + from pathlib import Path + + out = { + "python_executable": sys.executable, + "python_version": sys.version, + "PYTHONPATH": os.environ.get("PYTHONPATH"), + "PYTHONNOUSERSITE": os.environ.get("PYTHONNOUSERSITE"), + "HOME": os.environ.get("HOME"), + "sys.path": sys.path, + } + eo_dir = Path(os.environ.get("HOME", "/home/user")) / ".eo-pkgs" + out["eo_dir"] = str(eo_dir) + out["eo_dir_exists"] = eo_dir.exists() + if eo_dir.exists(): + out["eo_dir_contents"] = sorted(p.name for p in eo_dir.iterdir())[:50] + out["modules"] = {} + for name in ("terratorch", "einops", "diffusers", "timm", + "rasterio", "planetary_computer", "pystac_client"): + try: + mod = __import__(name) + out["modules"][name] = {"ok": True, + "file": getattr(mod, "__file__", "?")} + except Exception as e: + out["modules"][name] = {"ok": False, + "err": f"{type(e).__name__}: {e}", + "tb": traceback.format_exc().splitlines()[-3:]} + return JSONResponse(out) + + +@app.get("/api/backend") +async def api_backend(): + """Live LLM-backend descriptor for the UI's hardware badge. + + Returns the configured primary (vLLM/AMD or Ollama/local), plus a + quick reachability ping so the badge can show whether the primary is + actually answering or whether the Router is on the fallback path. + """ + import httpx + + from app import llm + info = llm.backend_info() + reachable = None + try: + if info["primary"] in ("vllm", "mlx") and info["vllm_base_url"]: + url = info["vllm_base_url"].rstrip("/") + "/models" + async with httpx.AsyncClient(timeout=2.5) as client: + r = await client.get(url, headers={"Authorization": "Bearer ping"}) + # vLLM and mlx_lm.server both return 200 on /v1/models when + # reachable; vLLM may return 401 with --api-key set. Either + # proves the server is up. Anything else = unreachable. + reachable = r.status_code in (200, 401) + else: + url = info["ollama_base_url"].rstrip("/") + "/api/tags" + async with httpx.AsyncClient(timeout=2.5) as client: + r = await client.get(url) + reachable = r.status_code == 200 + except Exception: + reachable = False + info["reachable"] = reachable + info["effective_engine"] = ( + info["engine"] if reachable + else (info.get("fallback_engine") or "offline") + ) + return JSONResponse(info) @app.get("/") def index(): + """SvelteKit cold-start page (the new design-system UI). Falls back to + the legacy custom-element agent.html if the SvelteKit build hasn't been + compiled yet — that lets `uvicorn` boot in a fresh checkout without a + Node toolchain present.""" + sk = SVELTEKIT_BUILD / "index.html" + if sk.exists(): + return FileResponse(sk) + return FileResponse(STATIC / "agent.html") + + +@app.get("/q/sample") +def q_sample_page(): + """The prerendered Red Hook demo briefing (no SSE).""" + sk = SVELTEKIT_BUILD / "q" / "sample.html" + if sk.exists(): + return FileResponse(sk) + return JSONResponse({"error": "sveltekit build not present"}, status_code=503) + + +@app.get("/q/{query_id}") +def q_query_page(query_id: str): # noqa: ARG001 — captured for the SPA router + """Live briefing route. Served by the SvelteKit SPA fallback (200.html); + the client opens an EventSource to /api/agent/stream.""" + sk = SVELTEKIT_BUILD / "200.html" + if sk.exists(): + return FileResponse(sk) + return JSONResponse({"error": "sveltekit build not present"}, status_code=503) + + +@app.get("/print/{query_id}") +def print_page(query_id: str): # noqa: ARG001 — captured by the SPA router + """Curated print artifact for a completed briefing. The client + hydrates from localStorage (key riprap:print:) and + auto-fires window.print() — no backend round-trip.""" + sk = SVELTEKIT_BUILD / "200.html" + if sk.exists(): + return FileResponse(sk) + return JSONResponse({"error": "sveltekit build not present"}, status_code=503) + + +@app.get("/legacy") +def legacy_index(): + """Original custom-element agent page, preserved for fallback / debugging.""" + return FileResponse(STATIC / "agent.html") + + +@app.get("/single") +def single_address_page(): return FileResponse(STATIC / "index.html") @@ -89,6 +305,18 @@ def compare_page(): return FileResponse(STATIC / "compare.html") +@app.get("/agent") +def agent_page(): + return FileResponse(STATIC / "agent.html") + + +@app.get("/report") +def report_page(): + """Print-ready auditable report. Reads the prior agent run from + the browser's sessionStorage; fully client-side render.""" + return FileResponse(STATIC / "report.html") + + @app.get("/register/{asset_class}") def register_page(asset_class: str): if asset_class not in ("schools", "nycha", "mta_entrances"): @@ -121,6 +349,7 @@ async def compare_stream(a: str, b: str, request: Request): route updates to the correct panel.""" import asyncio import queue + from app.fsm import iter_steps def gen_for_side(side: str, q_text: str, out_q): @@ -132,7 +361,7 @@ async def compare_stream(a: str, b: str, request: Request): out_q.put({"side": side, "kind": "error", "err": str(e)}) out_q.put({"side": side, "kind": "_done"}) - out_q: "queue.Queue[dict]" = queue.Queue() + out_q: queue.Queue[dict] = queue.Queue() def kick(): # run both sides in parallel threads — each Burr Application owns @@ -187,6 +416,153 @@ async def stream(q: str, request: Request): "X-Accel-Buffering": "no"}) +@app.get("/api/agent") +def api_agent(q: str): + """Agentic endpoint: take a natural-language query, plan it via + Granite 4.1, dispatch to the appropriate intent module, return the + full result as JSON. The Plan is included so callers can see the + agent's routing decision. + + All non-trivial reconciliation (single_address / neighborhood / + development_check) routes through Mellea-validated rejection + sampling against four grounding requirements. live_now stays on + streaming reconcile because outputs are short and the live signals + have low hallucination surface.""" + from app.intents import development_check as i_dev + from app.intents import live_now as i_live + from app.intents import neighborhood as i_nbhd + from app.intents import single_address as i_addr + from app.planner import plan as run_planner + p = run_planner(q) + if p.intent == "development_check": + out = i_dev.run(p, q, strict=True) + elif p.intent == "neighborhood": + out = i_nbhd.run(p, q, strict=True) + elif p.intent == "live_now": + out = i_live.run(p, q) + else: + out = i_addr.run(p, q, strict=True) + return JSONResponse(out) + + +@app.get("/api/agent/stream") +async def api_agent_stream(q: str): + """SSE: emit `plan` once the planner finishes, then a `step` event per + finalized specialist, then `final` with the full result. The intent + runs in a thread; we marshal events through a queue.""" + import asyncio + import queue + out_q: queue.Queue[dict] = queue.Queue() + + def runner(): + try: + from app.intents import development_check as i_dev + from app.intents import live_now as i_live + from app.intents import neighborhood as i_nbhd + from app.intents import single_address as i_addr + from app.planner import plan as run_planner + + def _on_plan_token(delta: str): + out_q.put({"kind": "plan_token", "delta": delta}) + p = run_planner(q, on_token=_on_plan_token) + out_q.put({"kind": "plan", + "intent": p.intent, + "targets": p.targets, + "specialists": p.specialists, + "rationale": p.rationale}) + if p.intent == "development_check": + final = i_dev.run(p, q, progress_q=out_q, strict=True) + elif p.intent == "neighborhood": + final = i_nbhd.run(p, q, progress_q=out_q, strict=True) + elif p.intent == "live_now": + final = i_live.run(p, q, progress_q=out_q) + else: + final = i_addr.run(p, q, progress_q=out_q, strict=True) + out_q.put({"kind": "final", **final}) + except Exception as e: + out_q.put({"kind": "error", "err": str(e)}) + finally: + out_q.put({"kind": "_done"}) + + async def event_stream(): + loop = asyncio.get_event_loop() + loop.run_in_executor(None, runner) + yield f"event: hello\ndata: {json.dumps({'query': q})}\n\n" + while True: + try: + ev = await asyncio.to_thread(out_q.get, True, 1.0) + except Exception: + continue + kind = ev.get("kind") + if kind == "_done": + break + yield f"event: {kind}\ndata: {json.dumps(ev, default=str)}\n\n" + yield "event: done\ndata: {}\n\n" + + return StreamingResponse(event_stream(), media_type="text/event-stream", + headers={"Cache-Control": "no-cache", + "X-Accel-Buffering": "no"}) + + +@app.get("/api/agent/plan") +def api_agent_plan(q: str): + """Just the plan, no execution. Useful for showing the agent's routing + decision before running specialists.""" + from app.planner import plan as run_planner + p = run_planner(q) + return JSONResponse({ + "intent": p.intent, + "targets": p.targets, + "specialists": p.specialists, + "rationale": p.rationale, + }) + + +@app.get("/api/layers/nta") +def layer_nta(code: str): + """Return the NTA polygon for a given NTA code as GeoJSON (EPSG:4326).""" + from app.areas import nta as nta_mod + g = nta_mod.load() + sub = g[g["nta2020"] == code][["nta2020", "ntaname", "boroname", "geometry"]] + if sub.empty: + return JSONResponse({"type": "FeatureCollection", "features": []}, status_code=404) + return JSONResponse(_json.loads(sub.to_json()), + headers={"Cache-Control": "public, max-age=3600"}) + + +@app.get("/api/layers/sandy_clipped") +def layer_sandy_clipped(code: str): + """Sandy inundation polygons clipped to an NTA bbox + simplified. + Used by the agent map for neighborhood / development_check intents.""" + from app.areas import nta as nta_mod + from app.flood_layers import sandy_inundation + poly = nta_mod.polygon_for(code) + if poly is None: + return JSONResponse({"type": "FeatureCollection", "features": []}) + bounds = poly.bounds + cx, cy = (bounds[0] + bounds[2]) / 2, (bounds[1] + bounds[3]) / 2 + # bbox half-extent in metres ~ half the polygon span × 111 km/deg + half_m = max((bounds[2] - bounds[0]), (bounds[3] - bounds[1])) / 2 * 111_000 + return JSONResponse(_clip_simplify(sandy_inundation.load(), cy, cx, half_m * 1.2), + headers={"Cache-Control": "public, max-age=600"}) + + +@app.get("/api/layers/dep_clipped") +def layer_dep_clipped(code: str, scenario: str = "dep_extreme_2080"): + """DEP scenario polygons clipped to an NTA bbox + simplified.""" + from app.areas import nta as nta_mod + from app.flood_layers import dep_stormwater + poly = nta_mod.polygon_for(code) + if poly is None: + return JSONResponse({"type": "FeatureCollection", "features": []}) + bounds = poly.bounds + cx, cy = (bounds[0] + bounds[2]) / 2, (bounds[1] + bounds[3]) / 2 + half_m = max((bounds[2] - bounds[0]), (bounds[3] - bounds[1])) / 2 * 111_000 + return JSONResponse(_clip_simplify(dep_stormwater.load(scenario), cy, cx, half_m * 1.2, + props_keep={"Flooding_Category"}), + headers={"Cache-Control": "public, max-age=600"}) + + @app.get("/api/layers/sandy") def layer_sandy(lat: float, lon: float, r: float = 1500): key = ("sandy", round(lat, 4), round(lon, 4), int(r)) diff --git a/web/static/agent.html b/web/static/agent.html new file mode 100644 index 0000000000000000000000000000000000000000..94e8743af86704d512067e3a99bb800b7d1d57f1 --- /dev/null +++ b/web/static/agent.html @@ -0,0 +1,523 @@ + + + + + +Riprap — agent + + + + + +
+
+
+ Riprap + · + citation-grounded flood-exposure briefings for NYC +
+
+ + checking… + +
+
+
+ +
+
+ + +
+
+ +
+ Try: + + + + + + + +
+ +
+ +
+ + +
+
+
+ + +
+ +
+ + +
+ + + + + + + diff --git a/web/static/agent.js b/web/static/agent.js new file mode 100644 index 0000000000000000000000000000000000000000..17671ba83540694d4655f9c3d0261318bd98dba3 --- /dev/null +++ b/web/static/agent.js @@ -0,0 +1,1391 @@ +// Riprap agent client — three-panel UI with live SSE streaming, intent- +// dispatched map, and structured report rendering. + +const $ = (s) => document.querySelector(s); + +const STEP_LABELS = { + // single_address chain (linear FSM) + geocode: ["Geocode (DCP Geosearch)", "address → lat/lon, BBL"], + sandy_inundation: ["Sandy Inundation (NYC OD)", "empirical 2012 extent"], + dep_stormwater: ["DEP Stormwater Maps", "pluvial scenarios + 2080 SLR"], + floodnet: ["FloodNet sensor network", "live ultrasonic depth sensors"], + nyc311: ["NYC 311 archive", "flood complaints in 200m"], + noaa_tides: ["NOAA Tides & Currents (live)", "Battery / Kings Pt / Sandy Hook"], + nws_alerts: ["NWS Public Alerts (live)", "active flood-relevant alerts"], + nws_obs: ["NWS METAR observation (live)", "nearest ASOS recent precipitation"], + ttm_forecast: ["Granite TTM r2 — surge nowcast", "9.6h forecast at the closest of Battery / Kings Pt / Sandy Hook"], + ttm_311_forecast: ["Granite TTM r2 — 311 forecast", "4-week per-address flood-complaint forecast (52w history)"], + floodnet_forecast: ["Granite TTM r2 — FloodNet forecast", "flood-event recurrence forecast at nearest FloodNet sensor"], + mta_entrance_exposure: ["MTA subway entrances", "subway-entrance exposure (point-in-polygon Sandy + DEP)"], + nycha_development_exposure: ["NYCHA developments", "NYCHA campus footprint × Sandy + DEP overlap %"], + doe_school_exposure: ["NYC DOE schools", "school-point exposure (Sandy + DEP)"], + doh_hospital_exposure: ["NYS DOH hospitals", "Article-28 hospital exposure (Sandy + DEP)"], + microtopo_lidar: ["LiDAR terrain (DEM + TWI + HAND)", "USGS 3DEP DEM + whitebox-workflows"], + ida_hwm_2021: ["Ida 2021 high-water marks", "USGS empirical post-event extent"], + prithvi_eo_v2: ["Prithvi-EO 2.0 (NASA/IBM)", "Sen1Floods11 satellite segmentation"], + prithvi_eo_live: ["Prithvi-EO 2.0 — live segmentation","fresh Sentinel-2 water mask at this address"], + terramind_synthesis: ["TerraMind 1.0 base — synthetic LULC", "DEM → ESRI Land Cover, any-to-any generative synthesis (IBM/ESA)"], + rag_granite_embedding: ["Granite Embedding 278M (RAG)", "policy corpus retrieval (+ Granite Reranker R2 if enabled)"], + gliner_extract: ["GLiNER typed extraction", "agencies, dollar amounts, projects, locations"], + reconcile_granite41: ["Granite 4.1 reconcile (local)", "document-grounded synthesis"], + // neighborhood + dev_check + nta_resolve: ["NTA polygon resolve", "name → NYC NTA 2020 polygon"], + sandy_nta: ["Sandy 2012, polygon-aggregated", "% of NTA inside 2012 inundation"], + dep_extreme_2080_nta: ["DEP Extreme-2080, polygon", "% of NTA in modeled flooding"], + dep_moderate_2050_nta: ["DEP Moderate-2050, polygon", "% of NTA in modeled flooding"], + dep_moderate_current_nta:["DEP Moderate-current, polygon", "% of NTA in modeled flooding"], + nyc311_nta: ["NYC 311, polygon-aggregated", "complaints inside polygon"], + microtopo_nta: ["LiDAR terrain, polygon", "median HAND/TWI + flood bands"], + rag_nta: ["Granite Embedding RAG (NTA)", "policy retrieval for the place"], + reconcile_neighborhood: ["Granite 4.1 reconcile (NTA)", "polygon-flavored briefing"], + // dev_check + dob_permits_nta: ["NYC DOB permits in polygon", "active NB / A1 / DM jobs ↔ flood layers"], + rag_dev: ["Granite Embedding RAG (dev)", "policy on new construction in flood zones"], + reconcile_development: ["Granite 4.1 reconcile (dev)", "flagged-projects briefing"], + // live_now + reconcile_live_now: ["Granite 4.1 reconcile (live)", "current-conditions briefing"], +}; + +const SOURCE_LABELS = { + geocode: "NYC DCP Geosearch", + nta_resolve: "NYC DCP Neighborhood Tabulation Areas 2020", + sandy: "NYC OD 5xsi-dfpx — Sandy 2012 inundation", + sandy_nta: "Sandy 2012 inundation, polygon-aggregated", + dep_extreme_2080: "NYC DEP Stormwater — Extreme-2080", + dep_moderate_2050: "NYC DEP Stormwater — Moderate-2050", + dep_moderate_current: "NYC DEP Stormwater — Moderate-current", + dep_extreme_2080_nta: "NYC DEP Extreme-2080, polygon-aggregated", + dep_moderate_2050_nta: "NYC DEP Moderate-2050, polygon-aggregated", + dep_moderate_current_nta: "NYC DEP Moderate-current, polygon-aggregated", + floodnet: "FloodNet NYC", + nyc311: "NYC 311 (erm2-nwe9)", + nyc311_nta: "NYC 311, polygon-aggregated", + microtopo: "USGS 3DEP DEM", + microtopo_nta: "USGS 3DEP DEM, polygon-aggregated", + ida_hwm: "USGS Hurricane Ida 2021 HWMs", + prithvi_water: "Prithvi-EO 2.0 — Hurricane Ida 2021 polygons", + prithvi_live: "Prithvi-EO 2.0 — live Sentinel-2 water segmentation", + terramind_synthetic: "TerraMind 1.0 base — synthetic LULC (DEM→ESRI Land Cover)", + gliner_comptroller: "GLiNER over Comptroller report", + gliner_dep_2013: "GLiNER over DEP wastewater plan", + gliner_nycha: "GLiNER over NYCHA Lessons Learned", + gliner_mta: "GLiNER over MTA Climate Resilience Roadmap", + gliner_coned: "GLiNER over Con Edison Climate Resilience", + noaa_tides: "NOAA CO-OPS Tides & Currents", + nws_alerts: "NWS Public Alerts", + nws_obs: "NWS Station Observations", + ttm_forecast: "Granite TimeSeries TTM r2 — surge residual nowcast", + ttm_311_forecast: "Granite TimeSeries TTM r2 — per-address 311 weekly forecast", + floodnet_forecast: "Granite TimeSeries TTM r2 — FloodNet sensor recurrence forecast", + dob_permits: "NYC DOB Permit Issuance (Socrata ipu4-2q9a)", + live_target: "Riprap planner — live target", + rag_comptroller: 'NYC Comptroller — "Is NYC Ready for Rain?" (2024)', + rag_npcc4: "NPCC4 (2024)", + rag_mta: "MTA Climate Resilience Roadmap", + rag_nycha: "NYCHA Flood Resilience: Lessons Learned", + rag_coned: "Con Edison Climate Resilience Plan", + // Register-specialist family labels — chip lookups for dynamic + // doc_ids (mta_entrance_, nycha_dev_, doe_school_, + // nyc_hospital_) fall through to these via family-prefix match. + mta_entrance: "MTA subway-entrance exposure (Open Data)", + nycha_dev: "NYCHA development exposure (NYC OD phvi-damg)", + doe_school: "NYC DOE school exposure", + nyc_hospital: "NYS DOH hospital exposure (vn5v-hh5r)", +}; + +// Canonical URL per doc_id — clicking a source row opens the underlying +// dataset / API / report in a new tab so users can verify provenance. +const SOURCE_URLS = { + geocode: "https://geosearch.planninglabs.nyc/", + nta_resolve: "https://www.nyc.gov/site/planning/data-maps/open-data/dwn-nynta.page", + sandy: "https://data.cityofnewyork.us/Environment/Sandy-Inundation-Zone/uyj8-7rv5", + sandy_nta: "https://data.cityofnewyork.us/Environment/Sandy-Inundation-Zone/uyj8-7rv5", + dep_extreme_2080: "https://data.cityofnewyork.us/Environment/NYC-Stormwater-Flood-Map-Extreme-Flood-with-Curren/w8eg-8ha6", + dep_moderate_2050: "https://data.cityofnewyork.us/Environment/NYC-Stormwater-Flood-Map-Moderate-Flood-with-Curre/9i7c-xyvv", + dep_moderate_current: "https://data.cityofnewyork.us/Environment/NYC-Stormwater-Flood-Map-Moderate-Flood/5rzh-cyqd", + dep_extreme_2080_nta: "https://data.cityofnewyork.us/Environment/NYC-Stormwater-Flood-Map-Extreme-Flood-with-Curren/w8eg-8ha6", + dep_moderate_2050_nta: "https://data.cityofnewyork.us/Environment/NYC-Stormwater-Flood-Map-Moderate-Flood-with-Curre/9i7c-xyvv", + dep_moderate_current_nta: "https://data.cityofnewyork.us/Environment/NYC-Stormwater-Flood-Map-Moderate-Flood/5rzh-cyqd", + floodnet: "https://www.floodnet.nyc/", + nyc311: "https://data.cityofnewyork.us/Social-Services/311-Service-Requests-from-2010-to-Present/erm2-nwe9", + nyc311_nta: "https://data.cityofnewyork.us/Social-Services/311-Service-Requests-from-2010-to-Present/erm2-nwe9", + microtopo: "https://www.usgs.gov/3d-elevation-program", + microtopo_nta: "https://www.usgs.gov/3d-elevation-program", + ida_hwm: "https://stn.wim.usgs.gov/STNDataPortal/", + prithvi_water: "https://huggingface.co/ibm-nasa-geospatial/Prithvi-EO-2.0-300M-TL-Sen1Floods11", + prithvi_live: "https://huggingface.co/ibm-nasa-geospatial/Prithvi-EO-2.0-300M-TL-Sen1Floods11", + terramind_synthetic: "https://huggingface.co/ibm-esa-geospatial/TerraMind-1.0-base", + gliner_comptroller: "https://huggingface.co/urchade/gliner_medium-v2.1", + gliner_dep_2013: "https://huggingface.co/urchade/gliner_medium-v2.1", + gliner_nycha: "https://huggingface.co/urchade/gliner_medium-v2.1", + gliner_mta: "https://huggingface.co/urchade/gliner_medium-v2.1", + gliner_coned: "https://huggingface.co/urchade/gliner_medium-v2.1", + noaa_tides: "https://tidesandcurrents.noaa.gov/", + nws_alerts: "https://www.weather.gov/documentation/services-web-api", + nws_obs: "https://www.weather.gov/documentation/services-web-api", + ttm_forecast: "https://huggingface.co/ibm-granite/granite-timeseries-ttm-r2", + ttm_311_forecast: "https://huggingface.co/ibm-granite/granite-timeseries-ttm-r2", + floodnet_forecast: "https://huggingface.co/ibm-granite/granite-timeseries-ttm-r2", + dob_permits: "https://data.cityofnewyork.us/Housing-Development/DOB-Permit-Issuance/ipu4-2q9a", + rag_comptroller: "https://comptroller.nyc.gov/reports/is-new-york-city-ready-for-rain/", + rag_npcc4: "https://nyaspubs.onlinelibrary.wiley.com/toc/17496632/2024/1539/1", + rag_mta: "https://new.mta.info/sustainability/climate-resilience", + rag_nycha: "https://www.nyc.gov/site/nycha/about/sustainability.page", + rag_coned: "https://www.coned.com/en/our-energy-future/climate-change-resilience", + mta_entrance: "https://data.ny.gov/Transportation/MTA-Subway-Entrances-and-Exits-2024/i9wp-a4ja", + nycha_dev: "https://data.cityofnewyork.us/Housing-Development/Map-of-NYCHA-Developments/i9rv-hdr5", + doe_school: "https://data.cityofnewyork.us/Education/School-Locations/jfju-ynrr", + nyc_hospital: "https://health.data.ny.gov/Health/Health-Facility-Certification-Information/2g9y-7kqm", +}; + +// Per-source vintage / "as of" — what date the underlying data represents. +// For live sources, the answer is "live; observation timestamps in payload". +// For archival sources, this is the dataset publication or extent date. +const SOURCE_VINTAGES = { + geocode: "live (NYC DCP Geosearch v2)", + nta_resolve: "NYC NTA 2020 boundaries (DCP, Sept 2022 release)", + sandy: "Sandy 2012 inundation extent (NYC OEM survey, dataset published 2013)", + sandy_nta: "Sandy 2012 inundation extent (polygon-aggregated)", + dep_extreme_2080: "NYC DEP Stormwater Flood Map — Extreme + 2080 SLR (2021 release)", + dep_moderate_2050: "NYC DEP Stormwater Flood Map — Moderate + 2050 SLR (2021 release)", + dep_moderate_current: "NYC DEP Stormwater Flood Map — Moderate, current SLR (2021 release)", + dep_extreme_2080_nta: "NYC DEP Extreme-2080 (2021 release; polygon-aggregated)", + dep_moderate_2050_nta: "NYC DEP Moderate-2050 (2021 release; polygon-aggregated)", + dep_moderate_current_nta: "NYC DEP Moderate-current (2021 release; polygon-aggregated)", + floodnet: "live FloodNet sensor stream (per-event timestamps in payload)", + nyc311: "live NYC 311 archive, trailing 5-year window (latest record in payload)", + nyc311_nta: "live NYC 311 archive, trailing 3-year window (polygon-aggregated)", + microtopo: "USGS 3DEP DEM (NYC LiDAR collect, ~2018) + derived HAND/TWI", + microtopo_nta: "USGS 3DEP DEM (NYC ~2018) — polygon-aggregated stats", + ida_hwm: "USGS Short-Term Network Event 312 — Hurricane Ida 2021 high-water marks (Sept 1-2 2021 survey)", + prithvi_water: "Prithvi-EO 2.0 satellite segmentation, scenes 2021-08-25 (pre) & 2021-09-02 (post Ida)", + prithvi_live: "live Sentinel-2 L2A scene from Microsoft Planetary Computer (acquisition timestamp in payload)", + terramind_synthetic: "synthetic prior — TerraMind 1.0 base generated a plausible categorical land-cover map from the LiDAR terrain at this point (deterministic seed, 10 diffusion steps; class fractions cite-able; not a measurement)", + gliner_comptroller: "GLiNER typed extraction over the Comptroller PDF (per-paragraph)", + gliner_dep_2013: "GLiNER typed extraction over the DEP wastewater plan", + gliner_nycha: "GLiNER typed extraction over the NYCHA Lessons Learned PDF", + gliner_mta: "GLiNER typed extraction over the MTA Resilience Roadmap", + gliner_coned: "GLiNER typed extraction over the Con Edison Climate Resilience plan", + noaa_tides: "live NOAA CO-OPS, 6-min cadence (observation time in payload)", + nws_alerts: "live NWS Public Alerts API (effective/expires in payload)", + nws_obs: "live NWS hourly METAR observation (observation time in payload)", + ttm_forecast: "live TTM forecast based on trailing 51 h at the closest NOAA gauge to this address (Battery / Kings Pt / Sandy Hook)", + ttm_311_forecast: "live TTM forecast based on trailing 52 weeks of NYC 311 flood complaints within 200 m of this address", + floodnet_forecast: "live TTM forecast based on the 512-day daily flood-event series at the nearest FloodNet sensor", + dob_permits: "live NYC DOB Permit Issuance, trailing 18-month window (per-permit issuance dates in payload)", + rag_comptroller: "NYC Comptroller report 'Is NYC Ready for Rain?' (2024)", + rag_npcc4: "NPCC4 — NYC Climate Assessment 4th edition, Annals NYAS vol. 1539 (2024)", + rag_mta: "MTA Climate Resilience Roadmap, October 2025 update", + rag_nycha: "NYCHA Flood Resilience: Lessons Learned (post-Sandy)", + rag_coned: "Con Edison Climate Change Resilience Plan, NY PSC Case 22-E-0222 (2023)", + scope_note: "Riprap planner — geographic scope guard (this query)", + live_target: "Riprap planner — live target (this query)", + mta_entrance: "MTA Open Data subway-entrance geometry (refreshed monthly) joined to Sandy 2012 + DEP scenarios + USGS 3DEP DEM", + nycha_dev: "NYC Open Data NYCHA Developments (phvi-damg) joined to Sandy 2012 + DEP scenarios + USGS 3DEP DEM", + doe_school: "NYC DOE Locations Points (1992 schools) joined to Sandy 2012 + DEP scenarios + USGS 3DEP DEM", + nyc_hospital: "NYS DOH Health Facility Certification (vn5v-hh5r, NYC counties + fac_desc_short=HOSP) joined to Sandy 2012 + DEP scenarios + USGS 3DEP DEM", +}; + +const INTENT_PILL_CLASS = { + development_check: "dev", + live_now: "live", + neighborhood: "nbhd", + single_address: "addr", +}; + +// --------------------------------------------------------------------------- +// MAP +// --------------------------------------------------------------------------- + +let map = null; +let mapInit = false; + +function ensureMap() { + if (mapInit) return; + mapInit = true; + map = new maplibregl.Map({ + container: "map", + style: { + version: 8, + // CARTO Voyager — more editorial typography + softer palette than + // Positron, no API key required. Retina (@2x) tiles for crisp type. + sources: { + basemap: { + type: "raster", + tiles: [ + "https://a.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}@2x.png", + "https://b.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}@2x.png", + "https://c.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}@2x.png", + "https://d.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}@2x.png", + ], + tileSize: 256, + attribution: "© OpenStreetMap contributors © CARTO", + }, + }, + layers: [ + { id: "bg", type: "background", paint: { "background-color": "#f3f5f8" } }, + { id: "basemap", type: "raster", source: "basemap" }, + ], + }, + center: [-74.0, 40.72], + zoom: 10, + attributionControl: { compact: true }, + // Required for map.getCanvas().toDataURL() to work on the report-export + // path. Otherwise the WebGL drawing buffer is cleared after each frame + // and snapshots come back blank. + preserveDrawingBuffer: true, + }); + map.addControl(new maplibregl.NavigationControl({ visualizePitch: false }), "top-right"); + map.on("load", initMapSources); +} + +function initMapSources() { + // Sandy + DEP overlays (used for nbhd / dev_check) + map.addSource("sandy", { type: "geojson", data: empty() }); + map.addLayer({ id: "sandy-fill", type: "fill", source: "sandy", + paint: { "fill-color": "#fc5d52", "fill-opacity": 0.25 } }); + map.addLayer({ id: "sandy-line", type: "line", source: "sandy", + paint: { "line-color": "#fc5d52", "line-width": 0.5, "line-opacity": 0.7 } }); + + map.addSource("dep", { type: "geojson", data: empty() }); + map.addLayer({ id: "dep-fill", type: "fill", source: "dep", + paint: { + "fill-color": ["match", ["get", "Flooding_Category"], + 1, "#568adf", 2, "#1642DF", 3, "#031553", "#568adf"], + "fill-opacity": 0.32 } }); + + // Prithvi-EO 2.0 live water-segmentation polygons. Cyan to differ + // visually from Sandy (red) and DEP (blue) — this is *observed today* + // water from the latest cloud-free Sentinel-2 scene, not a modeled + // scenario. We outline + fill so even sliver geometries (river edges, + // canal banks) show up at street zoom. + map.addSource("prithvi_live", { type: "geojson", data: empty() }); + map.addLayer({ id: "prithvi-live-fill", type: "fill", source: "prithvi_live", + paint: { "fill-color": "#48c6eb", "fill-opacity": 0.45 } }); + map.addLayer({ id: "prithvi-live-line", type: "line", source: "prithvi_live", + paint: { "line-color": "#1aa3c8", "line-width": 1.2, "line-opacity": 0.85 } }); + + // TerraMind synthesised LULC polygons — *synthetic-prior* tier + // (4th epistemic class). Per-feature fill_color carried from the + // server side so the legend stays in one place. Dashed outline so + // it visually reads as "synthesized, not observed". + map.addSource("terramind_lulc", { type: "geojson", data: empty() }); + map.addLayer({ id: "terramind-lulc-fill", type: "fill", + source: "terramind_lulc", + paint: { + "fill-color": ["coalesce", ["get", "fill_color"], "#9ca3af"], + "fill-opacity": 0.30, + }, + }); + map.addLayer({ id: "terramind-lulc-line", type: "line", + source: "terramind_lulc", + paint: { + "line-color": ["coalesce", ["get", "fill_color"], "#9ca3af"], + "line-width": 1.0, + "line-dasharray": [2, 2], + "line-opacity": 0.65, + }, + }); + map.on("click", "terramind-lulc-fill", (e) => { + const f = e.features[0]; const p = f.properties; + new maplibregl.Popup().setLngLat(e.lngLat) + .setHTML(`TerraMind synthetic land-cover
` + + `Class: ${escapeHtml(p.label || "")} (tentative)
` + + `Synthesised from LiDAR DEM, not observed.`) + .addTo(map); + }); + + // NTA polygon outline + map.addSource("nta", { type: "geojson", data: empty() }); + map.addLayer({ id: "nta-line", type: "line", source: "nta", + paint: { "line-color": "#0b3b6b", "line-width": 2.4, "line-opacity": 0.9 } }); + map.addLayer({ id: "nta-fill", type: "fill", source: "nta", + paint: { "fill-color": "#0b3b6b", "fill-opacity": 0.04 } }); + + // DOB permit pins + map.addSource("permits", { type: "geojson", data: empty() }); + map.addLayer({ id: "permits-circles", type: "circle", source: "permits", + paint: { + "circle-radius": ["case", ["get", "any_flood"], 6, 4], + "circle-color": [ + "case", + ["get", "in_sandy"], "#fc5d52", + [">=", ["get", "dep_max_class"], 2], "#1642DF", + [">", ["get", "dep_max_class"], 0], "#568adf", + "#1a8754", + ], + "circle-stroke-color": "#ffffff", + "circle-stroke-width": 1.4, + "circle-opacity": 0.95, + } }); + map.on("click", "permits-circles", (e) => { + const f = e.features[0]; const p = f.properties; + new maplibregl.Popup() + .setLngLat(f.geometry.coordinates) + .setHTML( + `${escapeHtml(p.address || "(unknown)")}
` + + `${p.job_type} · ${p.in_sandy === 'true' ? 'Sandy zone' : 'outside Sandy'}
` + + `DEP class: ${p.dep_max_class}`) + .addTo(map); + }); + + // Address pin (single_address intent) + map.addSource("addr", { type: "geojson", data: empty() }); + map.addLayer({ id: "addr-pin", type: "circle", source: "addr", + paint: { "circle-radius": 10, "circle-color": "#0b3b6b", + "circle-stroke-color": "#fff", "circle-stroke-width": 3 } }); + + // Search-radius circles (200 m / 600 m / 800 m). Visualizes the + // spatial scope each specialist is reading from. Drawn as a thin + // line so the underlying point data is readable through them. + map.addSource("scope", { type: "geojson", data: empty() }); + map.addLayer({ id: "scope-line", type: "line", source: "scope", + paint: { "line-color": "#0b3b6b", "line-width": 1.0, + "line-opacity": 0.55, "line-dasharray": [3, 3] } }); + + // NYC 311 flood complaint pins — coloured by descriptor. + map.addSource("nyc311_pts", { type: "geojson", data: empty() }); + map.addLayer({ id: "nyc311-circles", type: "circle", source: "nyc311_pts", + paint: { + "circle-radius": 4.5, + "circle-color": ["match", ["get", "descriptor"], + "Sewer Backup (Use Comments) (SA)", "#fc5d52", + "Catch Basin Clogged/Flooding (Use Comments) (SC)", "#f59e0b", + "Street Flooding (SJ)", "#1642DF", + "Manhole Overflow (Use Comments) (SA1)", "#8b5cf6", + "#6b7280", + ], + "circle-stroke-color": "#ffffff", + "circle-stroke-width": 1.0, + "circle-opacity": 0.85, + }, + }); + map.on("click", "nyc311-circles", (e) => { + const f = e.features[0]; const p = f.properties; + new maplibregl.Popup().setLngLat(f.geometry.coordinates) + .setHTML(`311 complaint
${escapeHtml(p.descriptor || "")}
` + + `${escapeHtml(p.date || "")}
${escapeHtml(p.address || "")}`) + .addTo(map); + }); + + // FloodNet sensors — triangles via SDF circle stand-in (cyan, + // larger if the sensor has triggered events). + map.addSource("floodnet_pts", { type: "geojson", data: empty() }); + map.addLayer({ id: "floodnet-circles", type: "circle", source: "floodnet_pts", + paint: { + "circle-radius": 7, + "circle-color": "#48c6eb", + "circle-stroke-color": "#1aa3c8", + "circle-stroke-width": 2.0, + "circle-opacity": 0.95, + }, + }); + map.on("click", "floodnet-circles", (e) => { + const f = e.features[0]; const p = f.properties; + new maplibregl.Popup().setLngLat(f.geometry.coordinates) + .setHTML(`FloodNet sensor
${escapeHtml(p.name || p.deployment_id || "")}`) + .addTo(map); + }); + + // USGS Hurricane Ida 2021 high-water marks — hot orange, sized by height. + map.addSource("ida_hwm_pts", { type: "geojson", data: empty() }); + map.addLayer({ id: "ida-hwm-circles", type: "circle", source: "ida_hwm_pts", + paint: { + "circle-radius": ["interpolate", ["linear"], + ["coalesce", ["get", "height_above_gnd_ft"], 0], + 0, 4, 3, 7, 6, 11], + "circle-color": "#ea580c", + "circle-stroke-color": "#7c2d12", + "circle-stroke-width": 1.4, + "circle-opacity": 0.92, + }, + }); + map.on("click", "ida-hwm-circles", (e) => { + const f = e.features[0]; const p = f.properties; + new maplibregl.Popup().setLngLat(f.geometry.coordinates) + .setHTML(`USGS Ida 2021 high-water mark
` + + `${escapeHtml(p.site || "(unnamed)")}
` + + `Elevation: ${p.elev_ft ?? "?"} ft
` + + `Height above ground: ${p.height_above_gnd_ft ?? "?"} ft`) + .addTo(map); + }); + + // NOAA tide gauge marker — shows which of the 3 gauges is active. + map.addSource("noaa_gauge", { type: "geojson", data: empty() }); + map.addLayer({ id: "noaa-gauge-marker", type: "circle", source: "noaa_gauge", + paint: { + "circle-radius": 9, + "circle-color": "#0ea5e9", + "circle-stroke-color": "#fff", + "circle-stroke-width": 2.5, + }, + }); + map.on("click", "noaa-gauge-marker", (e) => { + const f = e.features[0]; const p = f.properties; + new maplibregl.Popup().setLngLat(f.geometry.coordinates) + .setHTML(`NOAA tide gauge
${escapeHtml(p.name || "")}
` + + `Observed water level: ${p.observed_ft ?? "?"} ft MLLW
` + + `Residual (≈ surge): ${p.residual_ft ?? "?"} ft`) + .addTo(map); + }); +} + +// ~3 m/° latitude × cos(lat) for longitude. Build a circle polygon +// approximating a fixed-radius (meters) buffer around (lat, lon). +function metersBuffer(lat, lon, meters, steps = 64) { + const dLat = meters / 111_000.0; + const dLon = meters / (111_000.0 * Math.cos(lat * Math.PI / 180)); + const ring = []; + for (let i = 0; i <= steps; i++) { + const a = (i / steps) * 2 * Math.PI; + ring.push([lon + dLon * Math.cos(a), lat + dLat * Math.sin(a)]); + } + return { type: "Polygon", coordinates: [ring] }; +} + +function empty() { return { type: "FeatureCollection", features: [] }; } + +function clearMap() { + if (!map || !map.getSource) return; + for (const id of ["sandy", "dep", "nta", "permits", "addr", "prithvi_live", + "terramind_lulc", + "scope", "nyc311_pts", "floodnet_pts", "ida_hwm_pts", + "noaa_gauge"]) { + const s = map.getSource(id); + if (s) s.setData(empty()); + } +} + +async function fillMapForFinal(d) { + if (!map || !map.loaded()) { + map.once("load", () => fillMapForFinal(d)); + return; + } + clearMap(); + const intent = d.intent; + if (intent === "single_address") return fillMapAddress(d); + if (intent === "neighborhood") return fillMapNeighborhood(d); + if (intent === "development_check") return fillMapDevelopment(d); + if (intent === "live_now") return fillMapLive(d); +} + +async function fillMapAddress(d) { + const geo = d.geocode; + if (!geo || !geo.lat) return; + map.flyTo({ center: [geo.lon, geo.lat], zoom: 15.5, duration: 700 }); + map.getSource("addr").setData({ type: "FeatureCollection", + features: [{ type: "Feature", + geometry: { type: "Point", coordinates: [geo.lon, geo.lat] }, properties: {} }] }); + // Fetch Sandy + DEP layers clipped to address + try { + const r = await fetch(`/api/layers/sandy?lat=${geo.lat}&lon=${geo.lon}&r=1500`); + map.getSource("sandy").setData(await r.json()); + } catch {} + try { + const r = await fetch(`/api/layers/dep_extreme_2080?lat=${geo.lat}&lon=${geo.lon}&r=1500`); + map.getSource("dep").setData(await r.json()); + } catch {} + // Prithvi-EO live water mask comes inlined in the SSE final event, + // not via a separate /api/layers fetch — it's per-query, not corpus. + const live = d.prithvi_live; + if (live && live.ok && live.polygons_geojson && map.getSource("prithvi_live")) { + map.getSource("prithvi_live").setData(live.polygons_geojson); + } + + // TerraMind synthesised LULC polygons — same per-query pattern. + const tm = d.terramind; + if (tm && tm.ok && tm.polygons_geojson && map.getSource("terramind_lulc")) { + map.getSource("terramind_lulc").setData(tm.polygons_geojson); + } + + // ---- search-radius scope rings (200 m / 600 m / 800 m) ---- + // Three rings matching the buffers each specialist actually reads: + // 200 m for 311, 600 m for FloodNet sensors, 800 m for Ida HWMs. + if (map.getSource("scope")) { + map.getSource("scope").setData({ + type: "FeatureCollection", + features: [200, 600, 800].map(r => ({ + type: "Feature", + geometry: metersBuffer(geo.lat, geo.lon, r), + properties: { radius_m: r }, + })), + }); + } + + // ---- NYC 311 flood complaint pins ---- + const c311 = d.nyc311 || {}; + const c311Pts = c311.points || []; + if (map.getSource("nyc311_pts")) { + map.getSource("nyc311_pts").setData({ + type: "FeatureCollection", + features: c311Pts.filter(p => p.lat && p.lon).map(p => ({ + type: "Feature", + geometry: { type: "Point", coordinates: [p.lon, p.lat] }, + properties: { + descriptor: p.descriptor || "", + date: p.date || "", + address: p.address || "", + }, + })), + }); + } + + // ---- FloodNet sensors ---- + const fn = d.floodnet || {}; + const fnSensors = fn.sensors || []; + if (map.getSource("floodnet_pts")) { + map.getSource("floodnet_pts").setData({ + type: "FeatureCollection", + features: fnSensors.filter(s => s.lat && s.lon).map(s => ({ + type: "Feature", + geometry: { type: "Point", coordinates: [s.lon, s.lat] }, + properties: { + name: s.name || s.deployment_id || "", + deployment_id: s.deployment_id || "", + }, + })), + }); + } + + // ---- USGS Ida 2021 HWMs ---- + const hwm = d.ida_hwm || {}; + const hwmPts = hwm.points || []; + if (map.getSource("ida_hwm_pts")) { + map.getSource("ida_hwm_pts").setData({ + type: "FeatureCollection", + features: hwmPts.filter(p => p.lat && p.lon).map(p => ({ + type: "Feature", + geometry: { type: "Point", coordinates: [p.lon, p.lat] }, + properties: { + site: p.site || "", + elev_ft: p.elev_ft, + height_above_gnd_ft: p.height_above_gnd_ft, + }, + })), + }); + } + + // ---- NOAA tide gauge marker ---- + const tides = d.noaa_tides || {}; + if (tides.station_id && tides.station_lat && tides.station_lon && + map.getSource("noaa_gauge")) { + map.getSource("noaa_gauge").setData({ + type: "FeatureCollection", + features: [{ + type: "Feature", + geometry: { type: "Point", + coordinates: [tides.station_lon, tides.station_lat] }, + properties: { + name: tides.station_name || tides.station_id, + observed_ft: tides.observed_ft_mllw, + residual_ft: tides.residual_ft, + }, + }], + }); + } +} + +async function fillMapNeighborhood(d) { + const t = d.target; + if (!t || !t.bbox || !t.nta_code) return; + const [minx, miny, maxx, maxy] = t.bbox; + map.fitBounds([[minx, miny], [maxx, maxy]], { padding: 32, duration: 700 }); + const [r1, r2, r3] = await Promise.all([ + fetch(`/api/layers/nta?code=${t.nta_code}`).then(r => r.json()), + fetch(`/api/layers/sandy_clipped?code=${t.nta_code}`).then(r => r.json()).catch(() => empty()), + fetch(`/api/layers/dep_clipped?code=${t.nta_code}&scenario=dep_extreme_2080`).then(r => r.json()).catch(() => empty()), + ]); + map.getSource("nta").setData(r1); + map.getSource("sandy").setData(r2); + map.getSource("dep").setData(r3); + // Prithvi-EO live water mask (NTA centroid) — same per-query GeoJSON + // as the single_address path; clipped visually to the NTA polygon by + // the basemap zoom. + const live = d.prithvi_live; + if (live && live.ok && live.polygons_geojson && map.getSource("prithvi_live")) { + map.getSource("prithvi_live").setData(live.polygons_geojson); + } + // TerraMind synthesised LULC at NTA centroid. + const tm = d.terramind; + if (tm && tm.ok && tm.polygons_geojson && map.getSource("terramind_lulc")) { + map.getSource("terramind_lulc").setData(tm.polygons_geojson); + } +} + +async function fillMapDevelopment(d) { + await fillMapNeighborhood(d); // same NTA + Sandy + DEP overlays + const pins = ((d.dob_summary || {}).all_pins) || []; + const fc = { + type: "FeatureCollection", + features: pins.filter(p => p.lat && p.lon).map(p => ({ + type: "Feature", + geometry: { type: "Point", coordinates: [p.lon, p.lat] }, + properties: { + address: p.address, job_type: p.job_type, + in_sandy: !!p.in_sandy, any_flood: !!p.any_flood, + dep_max_class: p.dep_max_class || 0, + }, + })), + }; + map.getSource("permits").setData(fc); +} + +function fillMapLive(d) { + // NYC overview with the 3 NOAA gauges + map.flyTo({ center: [-74.0, 40.7], zoom: 10, duration: 700 }); +} + +// Fire as each FSM step completes, so the map updates progressively +// instead of waiting for the `final` event. Each branch is idempotent — +// it's safe if `final` later overwrites with the same data. +async function incrementallyFillMap(step) { + if (!map || !map.loaded()) { + map.once("load", () => incrementallyFillMap(step)); + return; + } + const r = step.result || {}; + // Address mode — geocode just resolved + if (step.step === "geocode" && r.lat != null && r.lon != null) { + map.flyTo({ center: [r.lon, r.lat], zoom: 15.5, duration: 700 }); + map.getSource("addr").setData({ type: "FeatureCollection", + features: [{ type: "Feature", + geometry: { type: "Point", coordinates: [r.lon, r.lat] }, properties: {} }] }); + Promise.all([ + fetch(`/api/layers/sandy?lat=${r.lat}&lon=${r.lon}&r=1500`).then(x => x.json()).catch(() => empty()), + fetch(`/api/layers/dep_extreme_2080?lat=${r.lat}&lon=${r.lon}&r=1500`).then(x => x.json()).catch(() => empty()), + ]).then(([s, d]) => { + map.getSource("sandy").setData(s); + map.getSource("dep").setData(d); + }); + return; + } + // Neighborhood / dev_check — NTA polygon resolved + if (step.step === "nta_resolve" && r.nta_code && r.bbox) { + const [minx, miny, maxx, maxy] = r.bbox; + map.fitBounds([[minx, miny], [maxx, maxy]], { padding: 32, duration: 700 }); + Promise.all([ + fetch(`/api/layers/nta?code=${r.nta_code}`).then(x => x.json()).catch(() => empty()), + fetch(`/api/layers/sandy_clipped?code=${r.nta_code}`).then(x => x.json()).catch(() => empty()), + fetch(`/api/layers/dep_clipped?code=${r.nta_code}&scenario=dep_extreme_2080`).then(x => x.json()).catch(() => empty()), + ]).then(([n, s, d]) => { + map.getSource("nta").setData(n); + map.getSource("sandy").setData(s); + map.getSource("dep").setData(d); + }); + return; + } + // Dev_check — DOB permits arrived; pin them now + if (step.step === "dob_permits_nta" && Array.isArray(r.all_pins)) { + const fc = { type: "FeatureCollection", + features: r.all_pins.filter(p => p.lat && p.lon).map(p => ({ + type: "Feature", + geometry: { type: "Point", coordinates: [p.lon, p.lat] }, + properties: { + address: p.address, job_type: p.job_type, + in_sandy: !!p.in_sandy, any_flood: !!p.any_flood, + dep_max_class: p.dep_max_class || 0, + }, + })) }; + map.getSource("permits").setData(fc); + return; + } +} + +// --------------------------------------------------------------------------- +// REPORT (paragraph) RENDERING +// --------------------------------------------------------------------------- + +function escapeHtml(s) { + return String(s ?? "").replace(/&/g, "&").replace(//g, ">"); +} + +let CITE_INDEX = {}; +// Resolve a doc_id to its source-label family. Register specialists emit +// per-asset doc_ids like `mta_entrance_54` / `nycha_dev_004` — for those +// we strip the trailing `_` and look up the family key. +const _FAMILY_PREFIXES = ["mta_entrance", "nycha_dev", "doe_school", "nyc_hospital"]; +function _docIdFamily(norm) { + for (const fam of _FAMILY_PREFIXES) { + if (norm.startsWith(fam + "_")) return fam; + } + return null; +} +function _resolveSourceLabel(norm) { + if (SOURCE_LABELS[norm]) return SOURCE_LABELS[norm]; + const fam = _docIdFamily(norm); + return fam ? SOURCE_LABELS[fam] : norm; +} +function rewriteCitations(html) { + return html.replace(/\[([a-z0-9_]+)\]/gi, (_, id) => { + const norm = id.toLowerCase(); + if (CITE_INDEX[norm] == null) CITE_INDEX[norm] = Object.keys(CITE_INDEX).length + 1; + const n = CITE_INDEX[norm]; + return `${n}`; + }); +} + +// Sources footer is a Lit web component () — driven +// by the citeIndex signal in /static/components/signals.js. We feed +// it the labels/urls/vintages once at boot and update the signal as +// the briefing markdown is rendered. +async function renderSources() { + const el = document.getElementById("sourcesFooter"); + if (!el) return; + // Module is loaded async; wait for define() then push fresh data. + await customElements.whenDefined("r-sources-footer"); + el.labels = SOURCE_LABELS; + el.urls = SOURCE_URLS; + el.vintages = SOURCE_VINTAGES; + // Push the citation index into the shared signal — the component + // re-renders reactively. + const { citeIndex } = await import("/static/components/signals.js"); + citeIndex.set({ ...CITE_INDEX }); +} + +function renderMarkdown(text) { + // Block recognizer: + // `**Header.**` (own line) →

+ // lines starting `- ` or `* ` → bullet items collected into
    + // anything else →

    + // Inline `**foo**` → + const lines = text.split("\n"); + const out = []; + let para = []; let bullets = []; + const flushPara = () => { + if (!para.length) return; + const safe = escapeHtml(para.join(" ").trim()).replace(/\*\*([^*]+)\*\*/g, "$1"); + if (safe) out.push(`

    ${safe}

    `); + para = []; + }; + const flushBullets = () => { + if (!bullets.length) return; + const items = bullets.map(b => { + const safe = escapeHtml(b.trim()).replace(/\*\*([^*]+)\*\*/g, "$1"); + return `
  • ${safe}
  • `; + }).join(""); + out.push(`
      ${items}
    `); + bullets = []; + }; + // Granite sometimes runs all bullets onto one line separated by " - "; + // pre-split those so each becomes its own bullet. + const expanded = []; + for (const line of lines) { + if (line.trim().startsWith("- ") && line.includes(" - ", 2)) { + // split into bullets + const parts = line.split(/(?:^|(?<=\.\s))\s*-\s+/g).filter(p => p.trim()); + for (const p of parts) expanded.push("- " + p.trim()); + } else { + expanded.push(line); + } + } + for (const line of expanded) { + const m = line.match(/^\s*\*\*([A-Z][A-Za-z\s/]+)\.\*\*\s*$/); + if (m) { + flushPara(); flushBullets(); + out.push(`

    ${escapeHtml(m[1])}

    `); + continue; + } + if (/^\s*[-*]\s+/.test(line)) { + flushPara(); + bullets.push(line.replace(/^\s*[-*]\s+/, "")); + } else { + flushBullets(); + para.push(line); + } + } + flushPara(); flushBullets(); + return out.join(""); +} + +// Briefing is now the Lit web component. It owns markdown +// rendering, citation chip binding, and pushing CITE_INDEX into the +// shared signal — agent.js just feeds it `.text` + `.sourceLabels`. +async function setBriefingText(text) { + const el = document.getElementById("paragraph"); + if (!el) return; + await customElements.whenDefined("r-briefing"); + el.sourceLabels = SOURCE_LABELS; + el.text = text || ""; +} +function renderParagraph(text) { setBriefingText(text); } + +// --------------------------------------------------------------------------- +// FACTS PANEL — intent-specific quick-look stats below the map +// --------------------------------------------------------------------------- + +function renderFacts(d) { + const intent = d.intent; + const panel = $("#factsPanel"); + const body = $("#factsBody"); + panel.style.display = ""; + if (intent === "neighborhood") renderNbhdFacts(d, body); + else if (intent === "development_check") renderDevFacts(d, body); + else if (intent === "live_now") renderLiveFacts(d, body); + else if (intent === "single_address") renderAddressFacts(d, body); +} + +function renderNbhdFacts(d, body) { + $("#factsTitle").textContent = `Findings — ${d.target?.nta_name || ""}`; + const s = d.sandy_nta || {}; const dep = d.dep_nta || {}; + const m = d.microtopo_nta || {}; const c = d.nyc311_nta || {}; + const sandyPct = s.fraction != null ? (s.fraction * 100).toFixed(1) + "%" : "—"; + const dep80 = (dep.dep_extreme_2080 || {}).fraction_any; + const dep50 = (dep.dep_moderate_2050 || {}).fraction_any; + body.innerHTML = ` +
    ${sandyPct}
    +
    of the neighborhood is inside the 2012 Sandy Inundation Zone
    +
    +
    DEP Extreme 2080
    ${dep80!=null ? (dep80*100).toFixed(1)+"%" : "—"}
    +
    DEP Moderate 2050
    ${dep50!=null ? (dep50*100).toFixed(1)+"%" : "—"}
    +
    311 (3 yr)
    ${c.n ?? "—"} flood complaints
    +
    HAND median
    ${m.hand_median_m != null ? m.hand_median_m+" m" : "—"}
    +
    HAND < 1 m fraction
    ${m.frac_hand_lt1 != null ? (m.frac_hand_lt1*100).toFixed(0)+"%" : "—"}
    +
    TWI median
    ${m.twi_median ?? "—"}
    +
    `; +} + +function renderDevFacts(d, body) { + $("#factsTitle").textContent = `Active construction — ${d.target?.nta_name || ""}`; + const ds = d.dob_summary || {}; + body.innerHTML = ` +
    ${ds.n_in_sandy ?? 0} / ${ds.n_total ?? 0}
    +
    active projects inside the Sandy zone
    +
    +
    Total active
    ${ds.n_total ?? 0}
    +
    In any DEP scenario
    ${ds.n_in_dep_any ?? 0}
    +
    In severe DEP (≥1 ft)
    ${ds.n_in_dep_severe ?? 0}
    +
    By job type
    ${Object.entries(ds.by_job_type || {}).map(([k,v]) => `${v} ${k}`).join(", ")}
    +
    `; +} + +function renderLiveFacts(d, body) { + $("#factsTitle").textContent = `Live conditions — ${d.place || "NYC"}`; + const t = d.noaa_tides || {}; const a = d.nws_alerts || {}; const o = d.nws_obs || {}; + const ttm = d.ttm_forecast || {}; + const r = t.residual_ft; + body.innerHTML = ` +
    ${a.n_active ?? 0} alerts
    +
    active flood-relevant NWS alerts at this point
    +
    +
    Tide gauge
    ${t.station_name || "—"}
    +
    Observed
    ${t.observed_ft_mllw != null ? t.observed_ft_mllw+" ft MLLW" : "—"}
    +
    Residual
    ${r != null ? (r >= 0 ? "+" : "")+r+" ft" : "—"}
    +
    Nearest ASOS
    ${o.station_id || "—"}
    +
    Precip 1h
    ${o.precip_last_hour_mm != null ? o.precip_last_hour_mm+" mm" : "—"}
    +
    TTM peak (next 9.6h)
    ${ttm.forecast_peak_ft != null ? ttm.forecast_peak_ft+" ft" : "—"}
    +
    `; +} + +function renderAddressFacts(d, body) { + $("#factsTitle").textContent = "Findings"; + const geo = d.geocode || {}; + const dep = d.dep || {}; const e80 = (dep.dep_extreme_2080 || {}); + const m = d.microtopo || {}; + body.innerHTML = ` +
    ${geo.address || "—"}
    +
    +
    Sandy zone
    ${d.sandy ? "INSIDE" : "outside"}
    +
    DEP Extreme 2080
    ${e80.depth_label || "—"}
    +
    HAND
    ${m.hand_m != null ? m.hand_m+" m" : "—"}
    +
    TWI
    ${m.twi ?? "—"}
    +
    Elev pct (200m)
    ${m.rel_elev_pct_200m ?? "—"}
    +
    311 (5y, 200m)
    ${(d.nyc311 || {}).n ?? "—"}
    +
    `; +} + +// --------------------------------------------------------------------------- +// TRACE PANEL +// --------------------------------------------------------------------------- + +// Trace list is a Lit web component (); pushTraceStep delegates +// once the component is registered. STEP_LABELS is set on the element +// at boot. +async function pushTraceStep(step) { + const el = document.getElementById("steps"); + if (!el) return; + await customElements.whenDefined("r-trace"); + if (!el.stepLabels || !Object.keys(el.stepLabels).length) { + el.stepLabels = STEP_LABELS; + } + el.pushStep(step); +} + +async function clearTrace() { + const el = document.getElementById("steps"); + if (el) { + await customElements.whenDefined("r-trace"); + el.clear(); + } + $("#traceMeta").textContent = ""; +} + +// -------------------------------------------------------------------------- +// Loading-state and chrome helpers +// -------------------------------------------------------------------------- + +function setMapLoading(text) { + const el = $("#mapLoading"); + if (!el) return; + if (text) { + el.style.display = ""; + $("#mapLoadingText").textContent = text; + } else { + el.style.display = "none"; + } +} + +function setLegend(intent) { + const el = $("#mapLegend"); + if (!el) return; + // Reusable legend rows shared across intents. + const empirical = ` +
    Sandy 2012 extent
    +
    DEP Extreme-2080
    `; + const points = ` +
    311 — sewer backup
    +
    311 — catch basin
    +
    311 — street flooding
    +
    FloodNet sensor
    +
    Ida 2021 high-water mark
    +
    NOAA tide gauge
    `; + // Synthetic-prior tier — distinct visual idiom (dashed) so users + // immediately read it as "generated, not observed". + const synthetic = ` +
    Synthetic priors (not observed)
    +
    Prithvi-EO 2.0 — live water mask
    +
    TerraMind — synthetic LULC (DEM→ESRI Land Cover, dashed = generated)
    `; + + if (intent === "development_check") { + el.innerHTML = ` +
    Active permits
    +
    Inside Sandy zone
    +
    DEP deep band (≥1 ft)
    +
    DEP nuisance band
    +
    No flood layer
    +
    ${empirical}
    ${synthetic}`; + el.style.display = ""; + } else if (intent === "neighborhood") { + el.innerHTML = `${empirical} +
    NTA boundary
    ${synthetic}`; + el.style.display = ""; + } else if (intent === "single_address") { + el.innerHTML = ` +
    Address
    ${empirical}${points}${synthetic}`; + el.style.display = ""; + } else { + el.style.display = "none"; + } +} + +// Mirrors app/score.py.composite() — see ARCHITECTURE.md / METHODOLOGY.md. +// Used only for the single_address intent badge; neighborhood and +// development_check have their own headline stats in the facts panel. +const REG_W = { fema_1pct: 1.0, fema_02pct: 0.5, + dep_moderate_2050: 0.75, dep_extreme_2080: 0.50, dep_tidal_2050: 0.75 }; +const HYD_W = { hand_band: 1.0, twi_quartile: 0.5, + elev_pct_200m_inv: 0.5, elev_pct_750m_inv: 0.5, basin_relief_band: 0.25 }; +const EMP_W = { sandy: 1.0, ida_hwm_within_100m: 1.0, ida_hwm_within_800m: 0.5, + prithvi_polygon: 0.75, complaints_band: 0.75, floodnet_trigger: 0.75 }; +const handBand = h => h == null ? 0 : (h < 1 ? 1 : h < 3 ? 0.66 : h < 10 ? 0.33 : 0); +const pctInvBand = p => p == null ? 0 : (p < 10 ? 1 : p < 25 ? 0.66 : p < 50 ? 0.33 : 0); +const twiBand = t => t == null ? 0 : (t >= 12 ? 1 : t >= 10 ? 0.66 : t >= 8 ? 0.33 : 0); +const reliefBand = r => r == null ? 0 : (r >= 8 ? 1 : r >= 4 ? 0.66 : r >= 2 ? 0.33 : 0); +const complBand = n => !n ? 0 : (n >= 10 ? 1 : n >= 3 ? 0.66 : 0.33); +const sumW = w => Object.values(w).reduce((a, b) => a + b, 0); + +function computeComposite(ev) { + const dep = ev.dep || {}, mt = ev.microtopo || {}, ida = ev.ida_hwm || {}, pw = ev.prithvi_water || {}; + const s = { + fema_1pct: false, fema_02pct: false, + dep_moderate_2050: (dep.dep_moderate_2050?.depth_class || 0) > 0, + dep_extreme_2080: (dep.dep_extreme_2080?.depth_class || 0) > 0, + dep_tidal_2050: false, + hand_m: mt.hand_m, twi: mt.twi, + rel_elev_pct_200m: mt.rel_elev_pct_200m, + rel_elev_pct_750m: mt.rel_elev_pct_750m, + basin_relief_m: mt.basin_relief_m, + sandy: !!ev.sandy, + ida_hwm_within_100m: (ida.nearest_dist_m != null && ida.nearest_dist_m < 100), + ida_hwm_within_800m: (ida.n_within_radius || 0) > 0, + prithvi_polygon: !!pw.inside_water_polygon, + complaints_count: ev.nyc311?.n || 0, + floodnet_trigger: (ev.floodnet?.n_flood_events_3y || 0) > 0, + }; + let regRaw = 0; for (const [k, w] of Object.entries(REG_W)) regRaw += s[k] ? w : 0; + const reg = regRaw / sumW(REG_W); + const hb = { hand_band: handBand(s.hand_m), twi_quartile: twiBand(s.twi), + elev_pct_200m_inv: pctInvBand(s.rel_elev_pct_200m), + elev_pct_750m_inv: pctInvBand(s.rel_elev_pct_750m), + basin_relief_band: reliefBand(s.basin_relief_m) }; + let hydRaw = 0; for (const [k, w] of Object.entries(HYD_W)) hydRaw += w * hb[k]; + const hyd = hydRaw / sumW(HYD_W); + const ev2 = { sandy: s.sandy ? 1 : 0, + ida_hwm_within_100m: s.ida_hwm_within_100m ? 1 : 0, + ida_hwm_within_800m: s.ida_hwm_within_800m ? 1 : 0, + prithvi_polygon: s.prithvi_polygon ? 1 : 0, + complaints_band: complBand(s.complaints_count), + floodnet_trigger: s.floodnet_trigger ? 1 : 0 }; + let empRaw = 0; for (const [k, w] of Object.entries(EMP_W)) empRaw += w * ev2[k]; + const emp = empRaw / sumW(EMP_W); + const composite = reg + hyd + emp; + let tier = 0; + if (composite >= 1.50) tier = 1; + else if (composite >= 1.00) tier = 2; + else if (composite >= 0.50) tier = 3; + else if (composite >= 0.01) tier = 4; + const floorApplied = !!(s.sandy || s.ida_hwm_within_100m); + if (floorApplied && (tier === 0 || tier > 2)) tier = 2; + return { tier, composite, floorApplied, + sub: { regulatory: reg, hydrological: hyd, empirical: emp } }; +} + +function tierMeta(tier) { + if (tier === 1) return { tier, label: "High exposure", + help: "Multiple sub-indices saturated. Not a damage probability." }; + if (tier === 2) return { tier, label: "Elevated exposure", + help: "At least one sub-index near saturation. Not a damage probability." }; + if (tier === 3) return { tier, label: "Moderate exposure", + help: "Partial signals across categories. Not a damage probability." }; + if (tier === 4) return { tier, label: "Limited exposure", + help: "A single contextual signal." }; + return { tier: 0, label: "No flagged exposure", + help: "No positive flood signal across the assessed sources." }; +} + +function renderBriefHead(d) { + const intent = d.intent; + const place = (d.target && d.target.nta_name) + || (d.geocode && d.geocode.address) + || d.place || "—"; + const meta = []; + const eyebrowMap = { + single_address: "Flood-exposure briefing — address", + neighborhood: "Flood-exposure briefing — neighborhood", + development_check: "Active development × flood exposure", + live_now: "Current conditions — NYC", + }; + $("#briefEyebrow").textContent = eyebrowMap[intent] || "Briefing"; + $("#briefTitle").innerHTML = escapeHtml(place); + + // For single_address intent, append the tier badge inline with the title + // — same idiom as the legacy /single page. + if (intent === "single_address") { + const c = computeComposite(d); + const m = tierMeta(c.tier); + const titleEl = $("#briefTitle"); + const floor = c.floorApplied ? ' empirical floor' : ""; + titleEl.innerHTML += ` + Tier ${m.tier} · ${escapeHtml(m.label)}${floor} + `; + } + + // Mellea compliance badge — present iff strict mode ran and produced + // metadata. Color reflects pass ratio: green for full, amber partial, + // red none. + if (d.mellea) { + const m = d.mellea; + const passed = (m.requirements_passed || []).length; + const total = m.requirements_total || 0; + const cls = passed === total ? "full" + : passed > 0 ? "partial" + : "none"; + const tip = `Mellea (IBM Research) ran ${m.n_attempts} attempt${m.n_attempts === 1 ? "" : "s"}` + + ` (${m.rerolls} reroll${m.rerolls === 1 ? "" : "s"}). ` + + `Requirements passed: ${(m.requirements_passed || []).join(", ") || "none"}. ` + + (m.requirements_failed?.length + ? `Failed: ${m.requirements_failed.join(", ")}.` : ""); + $("#briefTitle").innerHTML += + ` ` + + `Mellea ${passed}/${total}` + + (m.rerolls > 0 ? ` · ${m.rerolls} reroll${m.rerolls === 1 ? "" : "s"}` : "") + + ``; + } + if (intent === "single_address" && d.geocode) { + if (d.geocode.borough) meta.push(`borough ${escapeHtml(d.geocode.borough)}`); + if (d.geocode.bbl) meta.push(`bbl ${escapeHtml(d.geocode.bbl)}`); + } else if (d.target && d.target.borough) { + meta.push(`borough ${escapeHtml(d.target.borough)}`); + if (d.target.nta_code) meta.push(`nta ${escapeHtml(d.target.nta_code)}`); + } + if (d.total_s != null) meta.push(`runtime ${d.total_s}s`); + meta.push(`assessed ${new Date().toISOString().slice(0,16).replace("T"," ")}`); + $("#briefMeta").innerHTML = meta.join('·'); +} + +// --------------------------------------------------------------------------- +// PLANNER ROW +// --------------------------------------------------------------------------- + +function renderPlan(p) { + const pillCls = INTENT_PILL_CLASS[p.intent] || ""; + $("#plannerRow").innerHTML = ` +
    +
    Planner
    +
    ${escapeHtml(p.intent)}
    +
    Targets
    +
    ${(p.targets || []).map(t => escapeHtml(t.type) + ":" + escapeHtml(t.text)).join(", ") || "(none)"}
    +
    Specialists
    +
    ${(p.specialists || []).join(", ")}
    +
    "${escapeHtml(p.rationale || "")}"
    +
    `; +} + +// --------------------------------------------------------------------------- +// SSE driver +// --------------------------------------------------------------------------- + +let currentEs = null; +// Buffers for the report-export feature — capture the full plan, trace, +// and final result during streaming so the report page can render the +// complete evidence package without re-running the agent. +let LAST_RESULT = null; +let LAST_TRACE = []; +let LAST_PLAN = null; +let LAST_PLAN_OBJ = null; +let TRACE_BUF = []; + +function ask(q) { + ensureMap(); + clearTrace(); clearMap(); + $("#plannerRow").innerHTML = ""; + setBriefingText(""); + $("#paragraph").classList.remove("streaming"); + const banner = $("#melleaBanner"); + if (banner) { banner.style.display = "none"; banner.innerHTML = ""; } + $("#reportPanel").style.display = "none"; + $("#factsPanel").style.display = "none"; + $("#reportSkel").style.display = ""; + $("#traceSkel").style.display = ""; + $("#mapLegend").style.display = "none"; + setMapLoading("Granite is planning the query…"); + $("#goBtn").disabled = true; + $("#traceMeta").textContent = "…"; + + if (currentEs) currentEs.close(); + const es = new EventSource("/api/agent/stream?q=" + encodeURIComponent(q)); + currentEs = es; + const t0 = Date.now(); + let streamBuf = ""; + let streamTimer = null; + let planStreamBuf = ""; + let planStreamTimer = null; + const ensurePlannerStream = () => { + let el = $("#plannerRow .planner-streaming"); + if (!el) { + $("#plannerRow").innerHTML = `
    `; + el = $("#plannerRow .planner-streaming"); + } + return el; + }; + const repaintPlanner = () => { + const el = $("#plannerRow .planner-streaming"); + if (el) el.textContent = planStreamBuf; + }; + const schedulePlannerRepaint = () => { + if (planStreamTimer) return; + planStreamTimer = setTimeout(() => { planStreamTimer = null; repaintPlanner(); }, 60); + }; + // Re-render the partial markdown on every token, but at most every 80 ms + // so the browser isn't murdered by a token-stream that arrives in bursts. + // Build the Sources footer alongside so it grows as new doc_ids appear. + // Briefing component owns citation indexing + chip binding via shared + // signals; we just feed it the latest text. Sources footer reacts to + // the citeIndex signal that updates each render. + const repaint = () => { + setBriefingText(streamBuf); + renderSources(); + }; + const scheduleRepaint = () => { + if (streamTimer) return; + streamTimer = setTimeout(() => { streamTimer = null; repaint(); }, 80); + }; + + es.addEventListener("plan_token", (e) => { + ensurePlannerStream(); + const d = JSON.parse(e.data); + planStreamBuf += d.delta || ""; + schedulePlannerRepaint(); + }); + es.addEventListener("plan", (e) => { + if (planStreamTimer) { clearTimeout(planStreamTimer); planStreamTimer = null; } + const planObj = JSON.parse(e.data); + LAST_PLAN_OBJ = planObj; + renderPlan(planObj); + setLegend(planObj.intent); + setMapLoading(planObj.intent === "live_now" ? null : "Resolving location…"); + $("#traceSkel").style.display = "none"; + TRACE_BUF = []; + $("#reportBtn").classList.remove("ready"); + }); + es.addEventListener("step", (e) => { + const step = JSON.parse(e.data); + TRACE_BUF.push(step); + incrementallyFillMap(step); + if (step.step === "geocode" || step.step === "nta_resolve") setMapLoading(null); + }); + es.addEventListener("step", (e) => { pushTraceStep(JSON.parse(e.data)); }); + let currentAttempt = 0; + es.addEventListener("token", (e) => { + const d = JSON.parse(e.data); + if (!streamBuf || (d.attempt != null && d.attempt !== currentAttempt)) { + // First token of a (possibly new) attempt → reveal panel, reset + // buffer if Mellea moved to a reroll. + if (d.attempt != null && d.attempt !== currentAttempt) { + currentAttempt = d.attempt; + streamBuf = ""; + } + $("#reportSkel").style.display = "none"; + $("#reportPanel").style.display = ""; + $("#paragraph").classList.add("streaming"); + } + streamBuf += d.delta || ""; + scheduleRepaint(); + }); + // Mellea per-attempt outcome — render a small banner above the briefing + // when a reroll is about to start so the user knows the model is + // self-correcting (and what failed). + es.addEventListener("mellea_attempt", (e) => { + const d = JSON.parse(e.data); + const banner = $("#melleaBanner"); + if (!banner) return; + if (d.failed && d.failed.length) { + banner.className = "mellea-banner reroll"; + banner.innerHTML = `↻ Mellea reroll — attempt ${(d.attempt|0)+1} failed: ${d.failed.join(", ")}. Re-drafting…`; + banner.style.display = ""; + } else { + banner.className = "mellea-banner pass"; + banner.innerHTML = `✓ Mellea — all 4 grounding requirements satisfied`; + banner.style.display = ""; + } + }); + es.addEventListener("final", (e) => { + const d = JSON.parse(e.data); + const dt = ((Date.now() - t0) / 1000).toFixed(1); + $("#traceMeta").textContent = `${dt}s`; + setMapLoading(null); + $("#reportSkel").style.display = "none"; + $("#paragraph").classList.remove("streaming"); + if (d.paragraph) { + $("#reportPanel").style.display = ""; + streamBuf = d.paragraph; + if (streamTimer) { clearTimeout(streamTimer); streamTimer = null; } + repaint(); + renderBriefHead(d); + } + renderFacts(d); + fillMapForFinal(d); + // Stash everything needed for the auditable-report page. + LAST_RESULT = { query: q, finishedAt: new Date().toISOString(), + wallSeconds: Number(dt), result: d }; + LAST_TRACE = TRACE_BUF.slice(); + LAST_PLAN = LAST_PLAN_OBJ; + $("#reportBtn").classList.add("ready"); + }); + es.addEventListener("error", () => {}); + es.addEventListener("done", () => { es.close(); $("#goBtn").disabled = false; }); +} + +// --------------------------------------------------------------------------- +// wire +// --------------------------------------------------------------------------- + +// Bind form/sample handlers FIRST so a throw in ensureMap() (e.g. a +// WebGL init failure) can't strand the user with a dead "Ask" button. +$("#agentForm").addEventListener("submit", (e) => { + e.preventDefault(); + const q = $("#q").value.trim(); + if (q) ask(q); +}); +document.querySelectorAll(".sample-btn").forEach(b => { + b.addEventListener("click", () => { $("#q").value = b.dataset.q; ask(b.dataset.q); }); +}); +try { ensureMap(); } catch (e) { console.error("ensureMap failed:", e); } + +// Backend hardware pill: fetches /api/backend, renders " · " +// and a state color (green=primary up, amber=fallback active, red=down). +// Refreshes every 60s so a flipped droplet shows up without a page reload. +async function refreshBackendPill() { + const pill = document.getElementById("backendPill"); + const text = document.getElementById("backendPillText"); + if (!pill || !text) return; + try { + const r = await fetch("/api/backend", { cache: "no-store" }); + if (!r.ok) throw new Error("status " + r.status); + const info = await r.json(); + const onFallback = info.reachable === false && !!info.fallback_engine; + const engine = onFallback ? info.fallback_engine : info.engine; + const hw = onFallback ? "fallback" : info.hardware; + text.textContent = `${hw} · Granite 4.1 / ${engine}`; + pill.dataset.state = + info.reachable ? "ok" : + onFallback ? "fallback" : "down"; + const detail = info.vllm_base_url + ? `Primary: ${info.engine} @ ${info.vllm_base_url}` + : `Engine: ${info.engine}`; + pill.title = info.reachable + ? `${detail} — reachable. No vendor LLM is contacted.` + : onFallback + ? `${detail} unreachable; running on ${info.fallback_engine} fallback.` + : `${detail} — UNREACHABLE.`; + } catch (e) { + text.textContent = "backend unknown"; + pill.dataset.state = "down"; + pill.title = "Could not query /api/backend: " + e.message; + } +} +refreshBackendPill(); +setInterval(refreshBackendPill, 60000); + +// Subscribe to the shared highlight signal so vanilla-rendered citation +// chips in the briefing prose mirror the highlight state driven by the +// Lit (and vice versa). +(async () => { + const { highlightedDocId } = await import("/static/components/signals.js"); + const apply = () => { + const id = highlightedDocId.get(); + document.querySelectorAll("#paragraph .cite").forEach(c => { + c.classList.toggle("hl", c.dataset.srcId === id); + }); + }; + // Lit-labs/signals exposes a subscribe / effect — try both shapes. + if (typeof highlightedDocId.subscribe === "function") { + highlightedDocId.subscribe(apply); + } else { + // Polyfill: poll on mutation. Cheap; signal updates are rare. + const orig = highlightedDocId.set.bind(highlightedDocId); + highlightedDocId.set = (v) => { orig(v); apply(); }; + } +})(); + +// "Generate auditable report" — snapshots the live map, packs the full +// evidence (query / plan / per-specialist trace / final result / per-source +// vintages / labels / urls), parks it in sessionStorage, opens /report. +$("#reportBtn").addEventListener("click", () => { + if (!LAST_RESULT) return; + let mapPng = null; + try { + if (map && map.loaded()) { + // preserveDrawingBuffer:false would force a one-frame render here + map.triggerRepaint(); + mapPng = map.getCanvas().toDataURL("image/png"); + } + } catch (e) { + console.warn("map snapshot failed", e); + } + const pkg = { + ...LAST_RESULT, + plan: LAST_PLAN, + trace: LAST_TRACE, + mapPng, + sourceLabels: SOURCE_LABELS, + sourceUrls: SOURCE_URLS, + sourceVintages: SOURCE_VINTAGES, + stepLabels: STEP_LABELS, + }; + try { + sessionStorage.setItem("riprap_report", JSON.stringify(pkg)); + window.open("/report", "_blank"); + } catch (e) { + alert("Could not stash report payload (storage may be full): " + e.message); + } +}); diff --git a/web/static/app.js b/web/static/app.js index 0ed26559a0d6c91f2b1daf9ce06c73bc5e711d55..e7b2de1b41be6e1dbb51046ad300ead641fdeac0 100644 --- a/web/static/app.js +++ b/web/static/app.js @@ -1,4 +1,4 @@ -// HeliOS-NYC web client. Subscribes to SSE, lights up FSM steps. +// Riprap web client — subscribes to SSE, lights up FSM steps, renders the report. const STEP_LABELS = { geocode: ["Geocode (DCP Geosearch)", "address → lat/lon, BBL"], @@ -6,6 +6,10 @@ const STEP_LABELS = { dep_stormwater: ["DEP Stormwater Maps", "pluvial scenarios + 2080 SLR"], floodnet: ["FloodNet sensor network", "live ultrasonic depth sensors"], nyc311: ["NYC 311 archive", "flood complaints in buffer"], + noaa_tides: ["NOAA Tides & Currents (live)", "Battery / Kings Pt / Sandy Hook water level"], + nws_alerts: ["NWS Public Alerts (live)", "active flood-relevant alerts at point"], + nws_obs: ["NWS METAR observation (live)", "nearest ASOS recent precipitation"], + ttm_forecast: ["Granite TTM r2 (TimeSeries)", "9.6h surge-residual nowcast at the Battery"], microtopo_lidar: ["LiDAR terrain (DEM + TWI + HAND)", "USGS 3DEP DEM + whitebox-workflows hydrology"], ida_hwm_2021: ["Ida 2021 high-water marks", "USGS empirical post-event extent"], prithvi_eo_v2: ["Prithvi-EO 2.0 (300M, NASA/IBM)", "Sen1Floods11 satellite water segmentation"], @@ -15,6 +19,7 @@ const STEP_LABELS = { const STEPS_ORDER = [ "geocode", "sandy_inundation", "dep_stormwater", "floodnet", "nyc311", + "noaa_tides", "nws_alerts", "nws_obs", "ttm_forecast", "microtopo_lidar", "ida_hwm_2021", "prithvi_eo_v2", "rag_granite_embedding", "reconcile_granite41", ]; @@ -255,8 +260,45 @@ function rewriteCitations(text) { }); } +function escapeHtml(s) { + return s.replace(/&/g, "&").replace(//g, ">"); +} + +function renderMarkdown(text) { + // Tiny safe markdown subset: + // **Header.** (on its own line) ->

    Header

    + // **inline bold** (mid-sentence) -> ... + // We escape HTML first to defang any injection in model output. + const lines = text.split("\n"); + const out = []; + let bodyBuf = []; + const flushBody = () => { + if (!bodyBuf.length) return; + const body = bodyBuf.join(" ").trim(); + bodyBuf = []; + if (!body) return; + const safe = escapeHtml(body) + .replace(/\*\*([^*]+)\*\*/g, "$1"); + out.push(`

    ${safe}

    `); + }; + const headerRe = /^\s*\*\*([A-Z][A-Za-z\s/]+)\.\*\*\s*$/; + for (const line of lines) { + const m = line.match(headerRe); + if (m) { + flushBody(); + out.push(`

    ${escapeHtml(m[1])}

    `); + } else { + bodyBuf.push(line); + } + } + flushBody(); + return out.join(""); +} + function renderParagraph(text) { - $("#paragraph").innerHTML = rewriteCitations(text); + // Build markdown structure FIRST, then rewrite citations inside. Citations + // are bracketed tokens like [sandy] which don't conflict with our markdown. + $("#paragraph").innerHTML = rewriteCitations(renderMarkdown(text)); } const SOURCE_LABELS = { @@ -275,6 +317,10 @@ const SOURCE_LABELS = { rag_coned: "Con Edison Climate Change Resilience Plan (Case 22-E-0222)", rag_mta: "MTA Climate Resilience Roadmap (Oct 2025)", rag_comptroller: "NYC Comptroller — \"Is NYC Ready for Rain?\" (2024)", + noaa_tides: "NOAA CO-OPS Tides & Currents — live water level (6-min)", + nws_alerts: "NWS Public Alerts API — active flood-relevant alerts", + nws_obs: "NWS Station Observations — nearest ASOS hourly METAR", + ttm_forecast: "Granite TimeSeries TTM r2 — surge-residual nowcast (Ekambaram et al. 2024, NeurIPS)", }; // ---------------------------------------------------------------------- @@ -282,29 +328,129 @@ const SOURCE_LABELS = { // evidence cards, policy quotes, methodology footer. // ---------------------------------------------------------------------- -function tierMeta(score) { - // Mirror app/score.py rubric: ≥6 = T1, 4-5 = T2, 2-3 = T3, 1 = T4, 0 = T0. - if (score >= 6) return {tier: 1, label: "High exposure", help: "Multiple positive flood signals — historical inundation and modeled scenarios both indicate substantial risk."}; - if (score >= 4) return {tier: 2, label: "Elevated exposure", help: "Significant overlap with at least one empirical or modeled scenario."}; - if (score >= 2) return {tier: 3, label: "Moderate exposure", help: "One or two positive signals; localised or scenario-specific risk."}; - if (score >= 1) return {tier: 4, label: "Limited exposure", help: "A single contextual signal; no positive scenario hits."}; - return {tier: 0, label: "No flagged exposure", help: "No positive flood signal across the assessed sources."}; +// Tier meta — uses the new composite breakpoints, mirrors app/score.py. +// Tooltip copy explicitly states scope: exposure, not damage probability. +function tierMeta(tier) { + if (tier === 1) return {tier: 1, label: "High exposure", + help: "Multiple sub-indices saturated; empirical and/or modeled scenarios both indicate substantial exposure. Not a damage probability."}; + if (tier === 2) return {tier: 2, label: "Elevated exposure", + help: "At least one sub-index near saturation; significant overlap with empirical or modeled scenarios. Not a damage probability."}; + if (tier === 3) return {tier: 3, label: "Moderate exposure", + help: "Partial signals across categories; scenario- or neighborhood-specific exposure. Not a damage probability."}; + if (tier === 4) return {tier: 4, label: "Limited exposure", + help: "A single contextual signal; no positive scenario hits."}; + return {tier: 0, label: "No flagged exposure", + help: "No positive flood signal across the assessed sources."}; } -function computeScore(ev) { - // Mirror server-side rubric so we render consistently. - let s = 0; - if (ev.sandy) s += 3; +// ---- Score computation: mirrors app/score.py.composite() exactly --------- +// Three thematic sub-indices, equal weights within each, max-empirical +// floor. Live signals (NWS alerts, surge, precip) are NOT in this score +// per IPCC AR6 WG II's distinction between exposure (static) and event +// occurrence (live). +const REG_W = { + fema_1pct: 1.0, fema_02pct: 0.5, + dep_moderate_2050: 0.75, dep_extreme_2080: 0.50, dep_tidal_2050: 0.75, +}; +const HYD_W = { + hand_band: 1.0, twi_quartile: 0.5, + elev_pct_200m_inv: 0.5, elev_pct_750m_inv: 0.5, basin_relief_band: 0.25, +}; +const EMP_W = { + sandy: 1.0, + ida_hwm_within_100m: 1.0, ida_hwm_within_800m: 0.5, + prithvi_polygon: 0.75, complaints_band: 0.75, floodnet_trigger: 0.75, +}; + +const handBand = (h) => h == null ? 0 : (h < 1 ? 1 : h < 3 ? 0.66 : h < 10 ? 0.33 : 0); +const pctInvBand = (p) => p == null ? 0 : (p < 10 ? 1 : p < 25 ? 0.66 : p < 50 ? 0.33 : 0); +const twiBand = (t) => t == null ? 0 : (t >= 12 ? 1 : t >= 10 ? 0.66 : t >= 8 ? 0.33 : 0); +const reliefBand = (r) => r == null ? 0 : (r >= 8 ? 1 : r >= 4 ? 0.66 : r >= 2 ? 0.33 : 0); +const complBand = (n) => !n ? 0 : (n >= 10 ? 1 : n >= 3 ? 0.66 : 0.33); +const sumW = (w) => Object.values(w).reduce((a, b) => a + b, 0); + +function computeComposite(ev) { const dep = ev.dep || {}; - if ((dep.dep_extreme_2080?.depth_class || 0) > 0) s += 2; - if ((dep.dep_moderate_2050?.depth_class || 0) > 0) s += 2; - if ((dep.dep_moderate_current?.depth_class || 0) > 0) s += 1; - if ((ev.nyc311?.n || 0) >= 3) s += 1; - if ((ev.floodnet?.n_flood_events_3y || 0) > 0) s += 1; - if ((ev.rag || []).length) s += 1; - return s; + const mt = ev.microtopo || {}; + const ida = ev.ida_hwm || {}; + const pw = ev.prithvi_water || {}; + + // Build the signal dict in the shape app/score.py expects. + const s = { + // Regulatory + fema_1pct: false, // not yet wired in this build + fema_02pct: false, + dep_moderate_2050: (dep.dep_moderate_2050?.depth_class || 0) > 0, + dep_extreme_2080: (dep.dep_extreme_2080?.depth_class || 0) > 0, + dep_tidal_2050: false, // tidal scenario not in current FSM + // Hydrological + hand_m: mt.hand_m, + twi: mt.twi, + rel_elev_pct_200m: mt.rel_elev_pct_200m, + rel_elev_pct_750m: mt.rel_elev_pct_750m, + basin_relief_m: mt.basin_relief_m, + // Empirical + sandy: !!ev.sandy, + ida_hwm_within_100m: (ida.nearest_dist_m != null && ida.nearest_dist_m < 100) || + (ida.n_within_radius || 0) > 0 && (ida.nearest_dist_m || 9999) < 100, + ida_hwm_within_800m: (ida.n_within_radius || 0) > 0, + prithvi_polygon: !!pw.inside_water_polygon, + complaints_count: ev.nyc311?.n || 0, + floodnet_trigger: (ev.floodnet?.n_flood_events_3y || 0) > 0, + }; + + // Regulatory sub-index (binary signals) + let regRaw = 0; + for (const [k, w] of Object.entries(REG_W)) regRaw += s[k] ? w : 0; + const reg = regRaw / sumW(REG_W); + + // Hydrological sub-index (banded continuous) + const hydBands = { + hand_band: handBand(s.hand_m), + twi_quartile: twiBand(s.twi), + elev_pct_200m_inv: pctInvBand(s.rel_elev_pct_200m), + elev_pct_750m_inv: pctInvBand(s.rel_elev_pct_750m), + basin_relief_band: reliefBand(s.basin_relief_m), + }; + let hydRaw = 0; + for (const [k, w] of Object.entries(HYD_W)) hydRaw += w * hydBands[k]; + const hyd = hydRaw / sumW(HYD_W); + + // Empirical sub-index + const empVals = { + sandy: s.sandy ? 1 : 0, + ida_hwm_within_100m: s.ida_hwm_within_100m ? 1 : 0, + ida_hwm_within_800m: s.ida_hwm_within_800m ? 1 : 0, + prithvi_polygon: s.prithvi_polygon ? 1 : 0, + complaints_band: complBand(s.complaints_count), + floodnet_trigger: s.floodnet_trigger ? 1 : 0, + }; + let empRaw = 0; + for (const [k, w] of Object.entries(EMP_W)) empRaw += w * empVals[k]; + const emp = empRaw / sumW(EMP_W); + + const composite = reg + hyd + emp; + + // Tier breakpoints (mirror score.py) + let tier = 0; + if (composite >= 1.50) tier = 1; + else if (composite >= 1.00) tier = 2; + else if (composite >= 0.50) tier = 3; + else if (composite >= 0.01) tier = 4; + + // Max-empirical floor: Sandy or HWM-within-100m → tier ≤ 2 + const floorApplied = !!(s.sandy || s.ida_hwm_within_100m); + if (floorApplied && (tier === 0 || tier > 2)) tier = 2; + + return { + subindices: {regulatory: reg, hydrological: hyd, empirical: emp}, + composite, tier, floorApplied, + }; } +// Backward-compat shim: places that called computeScore() now read .tier. +function computeScore(ev) { return computeComposite(ev).tier; } + function renderHeader(ev) { const geo = ev.geocode || {}; $("#reportAddr").textContent = geo.address || "(unresolved)"; @@ -314,12 +460,13 @@ function renderHeader(ev) { } function renderTier(ev) { - const score = computeScore(ev); - const m = tierMeta(score); + const c = computeComposite(ev); + const m = tierMeta(c.tier); const badge = $("#tierBadge"); badge.className = "tier-badge t-" + m.tier; $("#tierNum").textContent = m.tier; - $("#tierLabel").textContent = `Tier ${m.tier} — ${m.label}`; + const floor = c.floorApplied ? " · empirical floor" : ""; + $("#tierLabel").textContent = `Tier ${m.tier} — ${m.label}${floor}`; $("#tierHelp").textContent = m.help; } @@ -557,6 +704,106 @@ function renderEvidence(ev) { })); } + // Live signals — refresh every query, may produce nothing on a calm day. + const tides = ev.noaa_tides; + if (tides && tides.observed_ft_mllw != null) { + const rows = [ + ["Gauge", `${tides.station_name} (${tides.station_id})`], + ["Distance to gauge", `${tides.distance_km} km`], + ["Observed", `${tides.observed_ft_mllw} ft above MLLW`], + ]; + if (tides.predicted_ft_mllw != null) + rows.push(["Predicted (astro tide)", `${tides.predicted_ft_mllw} ft`]); + if (tides.residual_ft != null) + rows.push(["Residual (obs − pred)", `${tides.residual_ft >= 0 ? "+" : ""}${tides.residual_ft} ft`]); + if (tides.obs_time) + rows.push(["Observation time", tides.obs_time]); + const flag = (tides.residual_ft != null && tides.residual_ft >= 1.0) ? "hit" : "note"; + cards.push(evCard({ + key: "noaa_tides", + title: "NOAA Tides & Currents — live coastal water level", + flag, rows, + sourceText: "NOAA CO-OPS API (api.tidesandcurrents.noaa.gov)", + sourceUrl: `https://tidesandcurrents.noaa.gov/stationhome.html?id=${tides.station_id}`, + vintage: "live, 6-min cadence; residual ≈ surge", + collapsed: false, + })); + } + + const al = ev.nws_alerts; + if (al && al.n_active > 0) { + const rows = [["Active flood-relevant alerts", String(al.n_active)]]; + (al.alerts || []).slice(0, 3).forEach((a, i) => { + rows.push([ + `Alert ${i + 1}`, + `${a.event} (${a.severity || "?"} / ${a.urgency || "?"}) — expires ${ + (a.expires || "").slice(0, 16) + }`, + ]); + }); + cards.push(evCard({ + key: "nws_alerts", + title: "NWS — active flood alerts at this point", + flag: "hit", rows, + sourceText: "NWS Public Alerts API (api.weather.gov)", + sourceUrl: "https://www.weather.gov/documentation/services-web-api", + vintage: "live, push-cadence (refresh on event)", + collapsed: false, + })); + } + + const obs = ev.nws_obs; + if (obs && obs.station_id && !obs.error && ( + obs.precip_last_hour_mm != null || + obs.precip_last_6h_mm != null)) { + const rows = [ + ["Nearest ASOS station", `${obs.station_name} (${obs.station_id})`], + ["Distance", `${obs.distance_km} km`], + ]; + if (obs.precip_last_hour_mm != null) + rows.push(["Precip last 1 h", `${obs.precip_last_hour_mm} mm`]); + if (obs.precip_last_3h_mm != null) + rows.push(["Precip last 3 h", `${obs.precip_last_3h_mm} mm`]); + if (obs.precip_last_6h_mm != null) + rows.push(["Precip last 6 h", `${obs.precip_last_6h_mm} mm`]); + if (obs.obs_time) + rows.push(["Observation time", obs.obs_time]); + const heavy = (obs.precip_last_hour_mm || 0) >= 10 || + (obs.precip_last_6h_mm || 0) >= 25; + cards.push(evCard({ + key: "nws_obs", + title: "NWS hourly METAR — recent precipitation", + flag: heavy ? "hit" : "note", rows, + sourceText: "NWS station observations API", + sourceUrl: `https://www.weather.gov/wrh/timeseries?site=${obs.station_id}`, + vintage: "live, ~hourly", + collapsed: false, + })); + } + + const ttm = ev.ttm_forecast; + if (ttm && ttm.available) { + const peak = ttm.forecast_peak_ft; + const rows = [ + ["Gauge", `${ttm.station_name} (NOAA ${ttm.station_id})`], + ["Recent residual", `${ttm.history_recent_ft} ft`], + ["Recent peak |residual|", `${ttm.history_peak_abs_ft} ft (last ~51 h)`], + ["Forecast peak residual", `${peak >= 0 ? "+" : ""}${peak} ft`], + ["Forecast peak time", `~${ttm.forecast_peak_minutes_ahead} min ahead (${(ttm.forecast_peak_time_utc || "").slice(11, 16)} UTC)`], + ["Threshold", `±${ttm.threshold_ft} ft (gate for emission)`], + ]; + const flag = ttm.interesting ? (Math.abs(peak) >= 0.5 ? "hit" : "note") : "miss"; + cards.push(evCard({ + key: "ttm_forecast", + title: "Granite TimeSeries TTM r2 — surge nowcast", + flag, rows, + sourceText: "IBM Granite TimeSeries TTM r2 (Ekambaram et al. 2024, NeurIPS)", + sourceUrl: "https://huggingface.co/ibm-granite/granite-timeseries-ttm-r2", + vintage: "zero-shot multivariate forecaster, ~1.5M params; runs on CPU", + collapsed: !ttm.interesting, + })); + } + $("#evidenceCards").innerHTML = cards.join(""); } diff --git a/web/static/components/briefing.js b/web/static/components/briefing.js new file mode 100644 index 0000000000000000000000000000000000000000..2e87bf5cdd10a680946808985349be683d19a8a5 --- /dev/null +++ b/web/static/components/briefing.js @@ -0,0 +1,133 @@ +// — the streaming-token, citation-chipped briefing panel. +// +// Replaces the agent.js renderMarkdown + rewriteCitations + paint +// scheduler. Token streaming becomes "append to a signal, re-render." +// +// Properties: +// text — full markdown text (set by parent on token / final events) +// streaming — bool; shows the blinking caret +// citeIndex — { doc_id: number } shared with +// sourceLabels — passed through for chip tooltips +// +// Signals consumed: +// highlightedDocId — toggles `.hl` on chips reactively (set by +// on hover) +// Signals updated: +// citeIndex — populated as citations are encountered in the text +// highlightedDocId — set on chip hover/click + +import { html, LitElement } from "https://esm.sh/lit@3"; +import { unsafeHTML } from "https://esm.sh/lit@3/directives/unsafe-html.js"; +import { SignalWatcher } from "https://esm.sh/@lit-labs/signals@0.1.x"; +import { citeIndex, highlightedDocId } from "./signals.js"; + +// Same minimal markdown subset as agent.js renderMarkdown — kept +// duplicated for now; will collapse when agent.js stops calling +// renderMarkdown. After full port this is the only impl. +function renderMarkdownPure(text) { + const lines = text.split("\n"); + const out = []; + let para = []; let bullets = []; + const escapeHtml = (s) => + String(s ?? "").replace(/&/g, "&").replace(//g, ">"); + const flushPara = () => { + if (!para.length) return; + const safe = escapeHtml(para.join(" ").trim()) + .replace(/\*\*([^*]+)\*\*/g, "$1"); + if (safe) out.push(`

    ${safe}

    `); + para = []; + }; + const flushBullets = () => { + if (!bullets.length) return; + const items = bullets.map(b => { + const safe = escapeHtml(b.trim()).replace(/\*\*([^*]+)\*\*/g, "$1"); + return `
  • ${safe}
  • `; + }).join(""); + out.push(`
      ${items}
    `); + bullets = []; + }; + // Granite sometimes runs all bullets onto one line. + const expanded = []; + for (const line of lines) { + if (line.trim().startsWith("- ") && line.includes(" - ", 2)) { + const parts = line.split(/(?:^|(?<=\.\s))\s*-\s+/g).filter(p => p.trim()); + for (const p of parts) expanded.push("- " + p.trim()); + } else { expanded.push(line); } + } + for (const line of expanded) { + const m = line.match(/^\s*\*\*([A-Z][A-Za-z\s/]+)\.\*\*\s*$/); + if (m) { flushPara(); flushBullets(); out.push(`

    ${escapeHtml(m[1])}

    `); } + else if (/^\s*[-*]\s+/.test(line)) { flushPara(); bullets.push(line.replace(/^\s*[-*]\s+/, "")); } + else { flushBullets(); para.push(line); } + } + flushPara(); flushBullets(); + return out.join(""); +} + +function rewriteCitations(html, sourceLabels, indexMap) { + return html.replace(/\[([a-z0-9_]+)\]/gi, (_, id) => { + const norm = id.toLowerCase(); + if (indexMap[norm] == null) indexMap[norm] = Object.keys(indexMap).length + 1; + const n = indexMap[norm]; + const lab = sourceLabels[norm] || norm; + return `${n}`; + }); +} + +export class Briefing extends SignalWatcher(LitElement) { + static properties = { + text: { type: String }, + streaming: { type: Boolean, reflect: true }, + sourceLabels: { type: Object }, + }; + + // No shadow DOM — we use the parent's `.report-pane #paragraph` styles + // directly so the markdown renders match the legacy/print idiom. + createRenderRoot() { return this; } + + constructor() { + super(); + this.text = ""; + this.streaming = false; + this.sourceLabels = {}; + } + + updated(changed) { + if (changed.has("text") && this.text) { + // Bind chip hover/click to the highlight signal post-render. + this._bindChips(); + } + } + + _bindChips() { + this.querySelectorAll(".cite").forEach(c => { + const id = c.dataset.srcId; + if (!id || c.dataset.signalBound) return; + c.dataset.signalBound = "1"; + c.addEventListener("mouseenter", () => highlightedDocId.set(id)); + c.addEventListener("click", (e) => { + e.stopPropagation(); + const cur = highlightedDocId.get(); + highlightedDocId.set(cur === id ? null : id); + }); + }); + // Apply highlight class reactively from current signal value. + const hl = highlightedDocId.get(); + this.querySelectorAll(".cite").forEach(c => { + c.classList.toggle("hl", c.dataset.srcId === hl); + }); + } + + render() { + if (!this.text) return html`
    Waiting for content…
    `; + const indexMap = {}; + const md = renderMarkdownPure(this.text); + const withCites = rewriteCitations(md, this.sourceLabels, indexMap); + // Push the citation index up to the shared signal so SourcesFooter + // re-renders. Done in render() because indexMap is computed here. + queueMicrotask(() => citeIndex.set({ ...indexMap })); + return html`${unsafeHTML(withCites)}`; + } +} + +customElements.define("r-briefing", Briefing); diff --git a/web/static/components/signals.js b/web/static/components/signals.js new file mode 100644 index 0000000000000000000000000000000000000000..f9059d50f9235ab43fcf7b9a45697977bccdedce --- /dev/null +++ b/web/static/components/signals.js @@ -0,0 +1,21 @@ +// Shared reactive state for Riprap web components. +// +// Lit components import these signals; updating one signal re-renders +// every subscribed component. Replaces the hand-wired DOM-querying +// cross-linking we used to do in vanilla JS. + +import { signal } from "https://esm.sh/@lit-labs/signals@0.1.x"; + +// Currently-highlighted citation doc_id. When a Briefing chip is hovered +// or clicked, this gets set; SourcesFooter observes it and highlights +// the matching row, and vice versa. +export const highlightedDocId = signal(null); + +// The full agent run output (from /api/agent/stream `final` event). +// Components that need the result post-render read from this. +export const lastResult = signal(null); + +// The cite-index map { doc_id: number } populated by Briefing as it +// renders the streamed markdown. SourcesFooter reads it to know which +// numbered rows to render. +export const citeIndex = signal({}); diff --git a/web/static/components/sources-footer.js b/web/static/components/sources-footer.js new file mode 100644 index 0000000000000000000000000000000000000000..345ad06c0c5a56e107d224a6c97ecfc30c986ea8 --- /dev/null +++ b/web/static/components/sources-footer.js @@ -0,0 +1,144 @@ +// — numbered, hyperlinked, vintage-aware Sources +// section that appears below the Briefing in the agent UI and inside +// the printable /report. +// +// Shared signals power the cross-linking with : hovering +// a [N] chip in the prose highlights the matching
  • here, and +// clicking either side persists the highlight + scrolls into view. +// +// Mounts via . Reads: +// - citeIndex — { doc_id: number } from Briefing +// - highlightedDocId — current highlight target (in/out) +// Plus three label/url/vintage maps passed in as properties. + +import { html, css, LitElement } from "https://esm.sh/lit@3"; +import { SignalWatcher } from "https://esm.sh/@lit-labs/signals@0.1.x"; +import { citeIndex, highlightedDocId } from "./signals.js"; + +export class SourcesFooter extends SignalWatcher(LitElement) { + static properties = { + labels: { type: Object }, + urls: { type: Object }, + vintages: { type: Object }, + }; + + static styles = css` + :host { + display: block; + border-top: 1px solid var(--line, #e5e7eb); + background: var(--bg-soft, #f5f7fb); + padding: 12px 16px 14px; + } + :host([hidden]) { display: none; } + .src-h { + font-size: 10px; font-weight: 700; + text-transform: uppercase; letter-spacing: 0.10em; + color: var(--text-muted, #6b7280); + margin: 0 0 8px; + } + ol { + margin: 0; padding: 0; list-style: none; + display: grid; gap: 6px; + font-size: 11.5px; line-height: 1.45; + } + li { + display: grid; grid-template-columns: 22px 1fr; + gap: 8px; align-items: baseline; + padding: 4px 6px; border-radius: 3px; + cursor: pointer; + transition: background 0.15s; + } + li:hover, li.hl { + background: rgba(22, 66, 223, 0.10); + } + .src-num { + font-family: var(--mono, monospace); font-size: 10.5px; + font-weight: 700; color: var(--nyc-blue, #1642DF); + text-align: right; + } + .src-link { + color: var(--text, #111); text-decoration: none; + border-bottom: 1px dotted var(--text-muted, #6b7280); + transition: color 0.12s, border-color 0.12s; + } + .src-link:hover { + color: var(--nyc-blue, #1642DF); + border-bottom-color: var(--nyc-blue, #1642DF); + } + .src-ext { + font-size: 9.5px; color: var(--text-faint, #9ca3af); + margin-left: 2px; vertical-align: super; + } + .src-vintage { + display: block; color: var(--text-muted, #6b7280); + font-size: 9.5px; margin-top: 2px; + } + .src-id { + display: inline-block; + font-family: var(--mono, monospace); font-size: 9.5px; + color: var(--text-faint, #9ca3af); margin-left: 6px; + } + `; + + constructor() { + super(); + this.labels = {}; + this.urls = {}; + this.vintages = {}; + } + + _entries() { + return Object.entries(citeIndex.get() || {}).sort((a, b) => a[1] - b[1]); + } + + _onHover(id) { + highlightedDocId.set(id); + } + + _onLeave() { + // Only clear if not pinned by click — keep highlight on click. + // For now, hover-only highlight clears on leave. + } + + _onClick(id) { + const cur = highlightedDocId.get(); + highlightedDocId.set(cur === id ? null : id); + } + + render() { + const entries = this._entries(); + if (!entries.length) { + this.setAttribute("hidden", ""); + return html``; + } + this.removeAttribute("hidden"); + const hl = highlightedDocId.get(); + return html` +
    Sources
    +
      + ${entries.map(([id, n]) => { + const url = this.urls[id]; + const label = this.labels[id] || id; + const vintage = this.vintages[id]; + const cls = id === hl ? "hl" : ""; + return html` +
    1. this._onHover(id)} + @click=${() => this._onClick(id)}> + [${n}] +
      + ${url + ? html` e.stopPropagation()}>${label} ` + : html`${label}`} + ${id} + ${vintage ? html`${vintage}` : ""} +
      +
    2. + `; + })} +
    + `; + } +} + +customElements.define("r-sources-footer", SourcesFooter); diff --git a/web/static/components/trace.js b/web/static/components/trace.js new file mode 100644 index 0000000000000000000000000000000000000000..6143a33a1f1f93b98cb9b16d36dec9be7709f7b0 --- /dev/null +++ b/web/static/components/trace.js @@ -0,0 +1,87 @@ +// — specialist trail. Reactive list of pipeline steps. +// +// API: +// .pushStep(step) — append a {step, ok, elapsed_s, result, err} record +// .clear() — reset +// .meta = "1.4s" — text shown in the header +// .stepLabels = {...} — { stepName: [label, hint] } map (set once at boot) +// +// Light DOM (no shadow) so the existing `#steps li.ok / .err / .running` +// CSS in agent.html keeps applying without rewrites. + +import { html, css, LitElement } from "https://esm.sh/lit@3"; + +const escapeHtml = (s) => + String(s ?? "").replace(/&/g, "&").replace(//g, ">"); + +export class Trace extends LitElement { + static properties = { + steps: { type: Array, state: true }, + meta: { type: String, reflect: true }, + stepLabels: { type: Object }, + }; + + createRenderRoot() { return this; } + + constructor() { + super(); + this.steps = []; + this.meta = ""; + this.stepLabels = {}; + } + + pushStep(step) { + this.steps = [...this.steps, step]; + } + + clear() { + this.steps = []; + this.meta = ""; + } + + _renderStep(step) { + const [label, hint] = this.stepLabels[step.step] || [step.step, ""]; + const ok = step.ok === true; + const fail = step.ok === false; + const cls = ok ? "ok" : fail ? "err" : "running"; + const mark = ok ? "✓" : fail ? "✗" : "○"; + const time = step.elapsed_s != null + ? `${step.elapsed_s}s` : ""; + const result = step.result + ? `
    ${escapeHtml(JSON.stringify(step.result))}
    ` : ""; + const err = step.err + ? `
    ${escapeHtml(step.err)}
    ` : ""; + // Inner HTML is hand-built so the existing list CSS targets the same + // structure as the legacy renderer; we keep .innerHTML rather than + // Lit's html`` for byte-for-byte parity here. + const li = document.createElement("li"); + li.className = cls; + li.innerHTML = ` + ${mark} +
    +
    ${escapeHtml(label)}
    +
    ${escapeHtml(hint)}
    +
    + ${time} + ${result} + ${err} + `; + return li; + } + + render() { + // Render the
      as innerHTML on update so we don't fight Lit's + // template diffing for raw HTML lists. + queueMicrotask(() => { + const ol = this.querySelector("ol#steps-list"); + if (!ol) return; + ol.innerHTML = ""; + for (const s of this.steps) ol.appendChild(this._renderStep(s)); + }); + // Inline reset so the legacy `#steps { list-style: none; ... }` rules + // (which now target the host element, not the
        ) keep applying. + return html`
          `; + } +} + +customElements.define("r-trace", Trace); diff --git a/web/static/dist/riprap.js b/web/static/dist/riprap.js new file mode 100644 index 0000000000000000000000000000000000000000..a69d9b1a9a5724094a3c8d5fbe2d80a98fe1dee5 --- /dev/null +++ b/web/static/dist/riprap.js @@ -0,0 +1,3777 @@ +const es = "5"; +typeof window < "u" && ((window.__svelte ??= {}).v ??= /* @__PURE__ */ new Set()).add(es); +const ts = 1, rs = 2, ns = 16, ss = 1, is = 4, ls = 8, os = 16, as = 4, fs = 1, us = 2, Fr = "[", rr = "[!", $r = "[?", nr = "]", Ge = {}, P = Symbol(), zr = "http://www.w3.org/1999/xhtml", cs = "http://www.w3.org/2000/svg", hs = "http://www.w3.org/1998/Math/MathML", ds = !1; +var jr = Array.isArray, vs = Array.prototype.indexOf, rt = Array.prototype.includes, Ct = Array.from, At = Object.keys, gt = Object.defineProperty, qe = Object.getOwnPropertyDescriptor, ps = Object.getOwnPropertyDescriptors, _s = Object.prototype, gs = Array.prototype, Hr = Object.getPrototypeOf, kr = Object.isExtensible; +function bs(e) { + return typeof e == "function"; +} +const re = () => { +}; +function ms(e) { + for (var t = 0; t < e.length; t++) + e[t](); +} +function qr() { + var e, t, r = new Promise((n, s) => { + e = n, t = s; + }); + return { promise: r, resolve: e, reject: t }; +} +function ws(e, t) { + if (Array.isArray(e)) + return e; + if (!(Symbol.iterator in e)) + return Array.from(e); + const r = []; + for (const n of e) + if (r.push(n), r.length === t) break; + return r; +} +const H = 2, nt = 4, Rt = 8, Br = 1 << 24, he = 16, de = 32, Ne = 64, Ht = 128, se = 512, D = 1024, z = 2048, _e = 4096, V = 8192, Z = 16384, Ce = 32768, qt = 1 << 25, Ke = 65536, Bt = 1 << 17, ys = 1 << 18, Xe = 1 << 19, $s = 1 << 20, Ee = 1 << 25, Je = 65536, Nt = 1 << 21, bt = 1 << 22, De = 1 << 23, vt = Symbol("$state"), Ur = Symbol("legacy props"), ye = new class extends Error { + name = "StaleReactionError"; + message = "The reaction that called `getAbortSignal()` was re-run or destroyed"; +}(), ks = ( + // We gotta write it like this because after downleveling the pure comment may end up in the wrong location + !!globalThis.document?.contentType && /* @__PURE__ */ globalThis.document.contentType.includes("xml") +), Lt = 3, at = 8; +function Es(e) { + throw new Error("https://svelte.dev/e/lifecycle_outside_component"); +} +function xs() { + throw new Error("https://svelte.dev/e/async_derived_orphan"); +} +function Ts(e, t, r) { + throw new Error("https://svelte.dev/e/each_key_duplicate"); +} +function Ss(e) { + throw new Error("https://svelte.dev/e/effect_in_teardown"); +} +function As() { + throw new Error("https://svelte.dev/e/effect_in_unowned_derived"); +} +function Ns(e) { + throw new Error("https://svelte.dev/e/effect_orphan"); +} +function Os() { + throw new Error("https://svelte.dev/e/effect_update_depth_exceeded"); +} +function Ms() { + throw new Error("https://svelte.dev/e/hydration_failed"); +} +function Cs(e) { + throw new Error("https://svelte.dev/e/props_invalid_value"); +} +function Rs() { + throw new Error("https://svelte.dev/e/state_descriptors_fixed"); +} +function Ls() { + throw new Error("https://svelte.dev/e/state_prototype_fixed"); +} +function Is() { + throw new Error("https://svelte.dev/e/state_unsafe_mutation"); +} +function Ds() { + throw new Error("https://svelte.dev/e/svelte_boundary_reset_onerror"); +} +function Ps() { + console.warn("https://svelte.dev/e/derived_inert"); +} +function wt(e) { + console.warn("https://svelte.dev/e/hydration_mismatch"); +} +function Fs() { + console.warn("https://svelte.dev/e/svelte_boundary_reset_noop"); +} +let N = !1; +function xe(e) { + N = e; +} +let x; +function j(e) { + if (e === null) + throw wt(), Ge; + return x = e; +} +function st() { + return j(/* @__PURE__ */ ve(x)); +} +function F(e) { + if (N) { + if (/* @__PURE__ */ ve(x) !== null) + throw wt(), Ge; + x = e; + } +} +function Vr(e = 1) { + if (N) { + for (var t = e, r = x; t--; ) + r = /** @type {TemplateNode} */ + /* @__PURE__ */ ve(r); + x = r; + } +} +function Ot(e = !0) { + for (var t = 0, r = x; ; ) { + if (r.nodeType === at) { + var n = ( + /** @type {Comment} */ + r.data + ); + if (n === nr) { + if (t === 0) return r; + t -= 1; + } else (n === Fr || n === rr || // "[1", "[2", etc. for if blocks + n[0] === "[" && !isNaN(Number(n.slice(1)))) && (t += 1); + } + var s = ( + /** @type {TemplateNode} */ + /* @__PURE__ */ ve(r) + ); + e && r.remove(), r = s; + } +} +function Yr(e) { + if (!e || e.nodeType !== at) + throw wt(), Ge; + return ( + /** @type {Comment} */ + e.data + ); +} +function Wr(e) { + return e === this.v; +} +function Gr(e, t) { + return e != e ? t == t : e !== t || e !== null && typeof e == "object" || typeof e == "function"; +} +function Kr(e) { + return !Gr(e, this.v); +} +let zs = !1, G = null; +function it(e) { + G = e; +} +function It(e, t = !1, r) { + G = { + p: G, + i: !1, + c: null, + e: null, + s: e, + x: null, + r: ( + /** @type {Effect} */ + y + ), + l: null + }; +} +function Dt(e) { + var t = ( + /** @type {ComponentContext} */ + G + ), r = t.e; + if (r !== null) { + t.e = null; + for (var n of r) + wn(n); + } + return e !== void 0 && (t.x = e), t.i = !0, G = t.p, e ?? /** @type {T} */ + {}; +} +function Jr() { + return !0; +} +let ze = []; +function Zr() { + var e = ze; + ze = [], ms(e); +} +function Pe(e) { + if (ze.length === 0 && !pt) { + var t = ze; + queueMicrotask(() => { + t === ze && Zr(); + }); + } + ze.push(e); +} +function js() { + for (; ze.length > 0; ) + Zr(); +} +function Xr(e) { + var t = y; + if (t === null) + return A.f |= De, e; + if (!(t.f & Ce) && !(t.f & nt)) + throw e; + Ie(e, t); +} +function Ie(e, t) { + for (; t !== null; ) { + if (t.f & Ht) { + if (!(t.f & Ce)) + throw e; + try { + t.b.error(e); + return; + } catch (r) { + e = r; + } + } + t = t.parent; + } + throw e; +} +const Hs = -7169; +function R(e, t) { + e.f = e.f & Hs | t; +} +function sr(e) { + e.f & se || e.deps === null ? R(e, D) : R(e, _e); +} +function Qr(e) { + if (e !== null) + for (const t of e) + !(t.f & H) || !(t.f & Je) || (t.f ^= Je, Qr( + /** @type {Derived} */ + t.deps + )); +} +function en(e, t, r) { + e.f & z ? t.add(e) : e.f & _e && r.add(e), Qr(e.deps), R(e, D); +} +function tn(e, t, r) { + if (e == null) + return t(void 0), re; + const n = ft( + () => e.subscribe( + t, + // @ts-expect-error + r + ) + ); + return n.unsubscribe ? () => n.unsubscribe() : n; +} +const Qe = []; +function rn(e, t = re) { + let r = null; + const n = /* @__PURE__ */ new Set(); + function s(l) { + if (Gr(e, l) && (e = l, r)) { + const f = !Qe.length; + for (const a of n) + a[1](), Qe.push(a, e); + if (f) { + for (let a = 0; a < Qe.length; a += 2) + Qe[a][0](Qe[a + 1]); + Qe.length = 0; + } + } + } + function i(l) { + s(l( + /** @type {T} */ + e + )); + } + function o(l, f = re) { + const a = [l, f]; + return n.add(a), n.size === 1 && (r = t(s, i) || re), l( + /** @type {T} */ + e + ), () => { + n.delete(a), n.size === 0 && r && (r(), r = null); + }; + } + return { set: s, update: i, subscribe: o }; +} +function qs(e) { + let t; + return tn(e, (r) => t = r)(), t; +} +let kt = !1, Ut = Symbol(); +function Vt(e, t, r) { + const n = r[t] ??= { + store: null, + source: /* @__PURE__ */ ar(void 0), + unsubscribe: re + }; + if (n.store !== e && !(Ut in r)) + if (n.unsubscribe(), n.store = e ?? null, e == null) + n.source.v = void 0, n.unsubscribe = re; + else { + var s = !0; + n.unsubscribe = tn(e, (i) => { + s ? n.source.v = i : te(n.source, i); + }), s = !1; + } + return e && Ut in r ? qs(e) : b(n.source); +} +function nn() { + const e = {}; + function t() { + cr(() => { + for (var r in e) + e[r].unsubscribe(); + gt(e, Ut, { + enumerable: !1, + value: !0 + }); + }); + } + return [e, t]; +} +function Bs(e) { + var t = kt; + try { + return kt = !1, [e(), kt]; + } finally { + kt = t; + } +} +const Fe = /* @__PURE__ */ new Set(); +let S = null, ue = null, Yt = null, pt = !1, jt = !1, et = null, xt = null; +var Er = 0; +let Us = 1; +class Oe { + id = Us++; + /** + * The current values of any signals that are updated in this batch. + * Tuple format: [value, is_derived] (note: is_derived is false for deriveds, too, if they were overridden via assignment) + * They keys of this map are identical to `this.#previous` + * @type {Map} + */ + current = /* @__PURE__ */ new Map(); + /** + * The values of any signals (sources and deriveds) that are updated in this batch _before_ those updates took place. + * They keys of this map are identical to `this.#current` + * @type {Map} + */ + previous = /* @__PURE__ */ new Map(); + /** + * When the batch is committed (and the DOM is updated), we need to remove old branches + * and append new ones by calling the functions added inside (if/each/key/etc) blocks + * @type {Set<(batch: Batch) => void>} + */ + #e = /* @__PURE__ */ new Set(); + /** + * If a fork is discarded, we need to destroy any effects that are no longer needed + * @type {Set<(batch: Batch) => void>} + */ + #n = /* @__PURE__ */ new Set(); + /** + * Callbacks that should run only when a fork is committed. + * @type {Set<(batch: Batch) => void>} + */ + #t = /* @__PURE__ */ new Set(); + /** + * Async effects that are currently in flight + * @type {Map} + */ + #i = /* @__PURE__ */ new Map(); + /** + * Async effects that are currently in flight, _not_ inside a pending boundary + * @type {Map} + */ + #s = /* @__PURE__ */ new Map(); + /** + * A deferred that resolves when the batch is committed, used with `settled()` + * TODO replace with Promise.withResolvers once supported widely enough + * @type {{ promise: Promise, resolve: (value?: any) => void, reject: (reason: unknown) => void } | null} + */ + #l = null; + /** + * The root effects that need to be flushed + * @type {Effect[]} + */ + #r = []; + /** + * Effects created while this batch was active. + * @type {Effect[]} + */ + #o = []; + /** + * Deferred effects (which run after async work has completed) that are DIRTY + * @type {Set} + */ + #f = /* @__PURE__ */ new Set(); + /** + * Deferred effects that are MAYBE_DIRTY + * @type {Set} + */ + #u = /* @__PURE__ */ new Set(); + /** + * A map of branches that still exist, but will be destroyed when this batch + * is committed — we skip over these during `process`. + * The value contains child effects that were dirty/maybe_dirty before being reset, + * so they can be rescheduled if the branch survives. + * @type {Map} + */ + #a = /* @__PURE__ */ new Map(); + /** + * Inverse of #skipped_branches which we need to tell prior batches to unskip them when committing + * @type {Set} + */ + #h = /* @__PURE__ */ new Set(); + is_fork = !1; + #v = !1; + /** @type {Set} */ + #d = /* @__PURE__ */ new Set(); + #c() { + return this.is_fork || this.#s.size > 0; + } + #b() { + for (const n of this.#d) + for (const s of n.#s.keys()) { + for (var t = !1, r = s; r.parent !== null; ) { + if (this.#a.has(r)) { + t = !0; + break; + } + r = r.parent; + } + if (!t) + return !0; + } + return !1; + } + /** + * Add an effect to the #skipped_branches map and reset its children + * @param {Effect} effect + */ + skip_effect(t) { + this.#a.has(t) || this.#a.set(t, { d: [], m: [] }), this.#h.delete(t); + } + /** + * Remove an effect from the #skipped_branches map and reschedule + * any tracked dirty/maybe_dirty child effects + * @param {Effect} effect + * @param {(e: Effect) => void} callback + */ + unskip_effect(t, r = (n) => this.schedule(n)) { + var n = this.#a.get(t); + if (n) { + this.#a.delete(t); + for (var s of n.d) + R(s, z), r(s); + for (s of n.m) + R(s, _e), r(s); + } + this.#h.add(t); + } + #p() { + if (Er++ > 1e3 && (Fe.delete(this), Vs()), !this.#c()) { + for (const l of this.#f) + this.#u.delete(l), R(l, z), this.schedule(l); + for (const l of this.#u) + R(l, _e), this.schedule(l); + } + const t = this.#r; + this.#r = [], this.apply(); + var r = et = [], n = [], s = xt = []; + for (const l of t) + try { + this.#g(l, r, n); + } catch (f) { + throw on(l), f; + } + if (S = null, s.length > 0) { + var i = Oe.ensure(); + for (const l of s) + i.schedule(l); + } + if (et = null, xt = null, this.#c() || this.#b()) { + this.#_(n), this.#_(r); + for (const [l, f] of this.#a) + ln(l, f); + } else { + this.#i.size === 0 && Fe.delete(this), this.#f.clear(), this.#u.clear(); + for (const l of this.#e) l(this); + this.#e.clear(), xr(n), xr(r), this.#l?.resolve(); + } + var o = ( + /** @type {Batch | null} */ + /** @type {unknown} */ + S + ); + if (this.#r.length > 0) { + const l = o ??= this; + l.#r.push(...this.#r.filter((f) => !l.#r.includes(f))); + } + o !== null && (Fe.add(o), o.#p()); + } + /** + * Traverse the effect tree, executing effects or stashing + * them for later execution as appropriate + * @param {Effect} root + * @param {Effect[]} effects + * @param {Effect[]} render_effects + */ + #g(t, r, n) { + t.f ^= D; + for (var s = t.first; s !== null; ) { + var i = s.f, o = (i & (de | Ne)) !== 0, l = o && (i & D) !== 0, f = l || (i & V) !== 0 || this.#a.has(s); + if (!f && s.fn !== null) { + o ? s.f ^= D : i & nt ? r.push(s) : $t(s) && (i & he && this.#u.add(s), ot(s)); + var a = s.first; + if (a !== null) { + s = a; + continue; + } + } + for (; s !== null; ) { + var u = s.next; + if (u !== null) { + s = u; + break; + } + s = s.parent; + } + } + } + /** + * @param {Effect[]} effects + */ + #_(t) { + for (var r = 0; r < t.length; r += 1) + en(t[r], this.#f, this.#u); + } + /** + * Associate a change to a given source with the current + * batch, noting its previous and current values + * @param {Value} source + * @param {any} value + * @param {boolean} [is_derived] + */ + capture(t, r, n = !1) { + t.v !== P && !this.previous.has(t) && this.previous.set(t, t.v), t.f & De || (this.current.set(t, [r, n]), ue?.set(t, r)), this.is_fork || (t.v = r); + } + activate() { + S = this; + } + deactivate() { + S = null, ue = null; + } + flush() { + try { + jt = !0, S = this, this.#p(); + } finally { + Er = 0, Yt = null, et = null, xt = null, jt = !1, S = null, ue = null, Be.clear(); + } + } + discard() { + for (const t of this.#n) t(this); + this.#n.clear(), this.#t.clear(), Fe.delete(this); + } + /** + * @param {Effect} effect + */ + register_created_effect(t) { + this.#o.push(t); + } + #m() { + for (const u of Fe) { + var t = u.id < this.id, r = []; + for (const [c, [d, v]] of this.current) { + if (u.current.has(c)) { + var n = ( + /** @type {[any, boolean]} */ + u.current.get(c)[0] + ); + if (t && d !== n) + u.current.set(c, [d, v]); + else + continue; + } + r.push(c); + } + var s = [...u.current.keys()].filter((c) => !this.current.has(c)); + if (s.length === 0) + t && u.discard(); + else if (r.length > 0) { + if (t) + for (const c of this.#h) + u.unskip_effect(c, (d) => { + d.f & (he | bt) ? u.schedule(d) : u.#_([d]); + }); + u.activate(); + var i = /* @__PURE__ */ new Set(), o = /* @__PURE__ */ new Map(); + for (var l of r) + sn(l, s, i, o); + o = /* @__PURE__ */ new Map(); + var f = [...u.current.keys()].filter( + (c) => this.current.has(c) ? ( + /** @type {[any, boolean]} */ + this.current.get(c)[0] !== c + ) : !0 + ); + for (const c of this.#o) + !(c.f & (Z | V | Bt)) && ir(c, f, o) && (c.f & (bt | he) ? (R(c, z), u.schedule(c)) : u.#f.add(c)); + if (u.#r.length > 0) { + u.apply(); + for (var a of u.#r) + u.#g(a, [], []); + u.#r = []; + } + u.deactivate(); + } + } + for (const u of Fe) + u.#d.has(this) && (u.#d.delete(this), u.#d.size === 0 && !u.#c() && (u.activate(), u.#p())); + } + /** + * @param {boolean} blocking + * @param {Effect} effect + */ + increment(t, r) { + let n = this.#i.get(r) ?? 0; + if (this.#i.set(r, n + 1), t) { + let s = this.#s.get(r) ?? 0; + this.#s.set(r, s + 1); + } + } + /** + * @param {boolean} blocking + * @param {Effect} effect + * @param {boolean} skip - whether to skip updates (because this is triggered by a stale reaction) + */ + decrement(t, r, n) { + let s = this.#i.get(r) ?? 0; + if (s === 1 ? this.#i.delete(r) : this.#i.set(r, s - 1), t) { + let i = this.#s.get(r) ?? 0; + i === 1 ? this.#s.delete(r) : this.#s.set(r, i - 1); + } + this.#v || n || (this.#v = !0, Pe(() => { + this.#v = !1, this.flush(); + })); + } + /** + * @param {Set} dirty_effects + * @param {Set} maybe_dirty_effects + */ + transfer_effects(t, r) { + for (const n of t) + this.#f.add(n); + for (const n of r) + this.#u.add(n); + t.clear(), r.clear(); + } + /** @param {(batch: Batch) => void} fn */ + oncommit(t) { + this.#e.add(t); + } + /** @param {(batch: Batch) => void} fn */ + ondiscard(t) { + this.#n.add(t); + } + /** @param {(batch: Batch) => void} fn */ + on_fork_commit(t) { + this.#t.add(t); + } + run_fork_commit_callbacks() { + for (const t of this.#t) t(this); + this.#t.clear(); + } + settled() { + return (this.#l ??= qr()).promise; + } + static ensure() { + if (S === null) { + const t = S = new Oe(); + jt || (Fe.add(S), pt || Pe(() => { + S === t && t.flush(); + })); + } + return S; + } + apply() { + { + ue = null; + return; + } + } + /** + * + * @param {Effect} effect + */ + schedule(t) { + if (Yt = t, t.b?.is_pending && t.f & (nt | Rt | Br) && !(t.f & Ce)) { + t.b.defer_effect(t); + return; + } + for (var r = t; r.parent !== null; ) { + r = r.parent; + var n = r.f; + if (et !== null && r === y && (A === null || !(A.f & H))) + return; + if (n & (Ne | de)) { + if (!(n & D)) + return; + r.f ^= D; + } + } + this.#r.push(r); + } +} +function Se(e) { + var t = pt; + pt = !0; + try { + for (var r; ; ) { + if (js(), S === null) + return ( + /** @type {T} */ + r + ); + S.flush(); + } + } finally { + pt = t; + } +} +function Vs() { + try { + Os(); + } catch (e) { + Ie(e, Yt); + } +} +let we = null; +function xr(e) { + var t = e.length; + if (t !== 0) { + for (var r = 0; r < t; ) { + var n = e[r++]; + if (!(n.f & (Z | V)) && $t(n) && (we = /* @__PURE__ */ new Set(), ot(n), n.deps === null && n.first === null && n.nodes === null && n.teardown === null && n.ac === null && kn(n), we?.size > 0)) { + Be.clear(); + for (const s of we) { + if (s.f & (Z | V)) continue; + const i = [s]; + let o = s.parent; + for (; o !== null; ) + we.has(o) && (we.delete(o), i.push(o)), o = o.parent; + for (let l = i.length - 1; l >= 0; l--) { + const f = i[l]; + f.f & (Z | V) || ot(f); + } + } + we.clear(); + } + } + we = null; + } +} +function sn(e, t, r, n) { + if (!r.has(e) && (r.add(e), e.reactions !== null)) + for (const s of e.reactions) { + const i = s.f; + i & H ? sn( + /** @type {Derived} */ + s, + t, + r, + n + ) : i & (bt | he) && !(i & z) && ir(s, t, n) && (R(s, z), lr( + /** @type {Effect} */ + s + )); + } +} +function ir(e, t, r) { + const n = r.get(e); + if (n !== void 0) return n; + if (e.deps !== null) + for (const s of e.deps) { + if (rt.call(t, s)) + return !0; + if (s.f & H && ir( + /** @type {Derived} */ + s, + t, + r + )) + return r.set( + /** @type {Derived} */ + s, + !0 + ), !0; + } + return r.set(e, !1), !1; +} +function lr(e) { + S.schedule(e); +} +function ln(e, t) { + if (!(e.f & de && e.f & D)) { + e.f & z ? t.d.push(e) : e.f & _e && t.m.push(e), R(e, D); + for (var r = e.first; r !== null; ) + ln(r, t), r = r.next; + } +} +function on(e) { + R(e, D); + for (var t = e.first; t !== null; ) + on(t), t = t.next; +} +function Ys(e) { + let t = 0, r = Ze(0), n; + return () => { + ur() && (b(r), dr(() => (t === 0 && (n = ft(() => e(() => _t(r)))), t += 1, () => { + Pe(() => { + t -= 1, t === 0 && (n?.(), n = void 0, _t(r)); + }); + }))); + }; +} +var Ws = Ke | Xe; +function Gs(e, t, r, n) { + new Ks(e, t, r, n); +} +class Ks { + /** @type {Boundary | null} */ + parent; + is_pending = !1; + /** + * API-level transformError transform function. Transforms errors before they reach the `failed` snippet. + * Inherited from parent boundary, or defaults to identity. + * @type {(error: unknown) => unknown} + */ + transform_error; + /** @type {TemplateNode} */ + #e; + /** @type {TemplateNode | null} */ + #n = N ? x : null; + /** @type {BoundaryProps} */ + #t; + /** @type {((anchor: Node) => void)} */ + #i; + /** @type {Effect} */ + #s; + /** @type {Effect | null} */ + #l = null; + /** @type {Effect | null} */ + #r = null; + /** @type {Effect | null} */ + #o = null; + /** @type {DocumentFragment | null} */ + #f = null; + #u = 0; + #a = 0; + #h = !1; + /** @type {Set} */ + #v = /* @__PURE__ */ new Set(); + /** @type {Set} */ + #d = /* @__PURE__ */ new Set(); + /** + * A source containing the number of pending async deriveds/expressions. + * Only created if `$effect.pending()` is used inside the boundary, + * otherwise updating the source results in needless `Batch.ensure()` + * calls followed by no-op flushes + * @type {Source | null} + */ + #c = null; + #b = Ys(() => (this.#c = Ze(this.#u), () => { + this.#c = null; + })); + /** + * @param {TemplateNode} node + * @param {BoundaryProps} props + * @param {((anchor: Node) => void)} children + * @param {((error: unknown) => unknown) | undefined} [transform_error] + */ + constructor(t, r, n, s) { + this.#e = t, this.#t = r, this.#i = (i) => { + var o = ( + /** @type {Effect} */ + y + ); + o.b = this, o.f |= Ht, n(i); + }, this.parent = /** @type {Effect} */ + y.b, this.transform_error = s ?? this.parent?.transform_error ?? ((i) => i), this.#s = vr(() => { + if (N) { + const i = ( + /** @type {Comment} */ + this.#n + ); + st(); + const o = i.data === rr; + if (i.data.startsWith($r)) { + const f = JSON.parse(i.data.slice($r.length)); + this.#g(f); + } else o ? this.#_() : this.#p(); + } else + this.#m(); + }, Ws), N && (this.#e = x); + } + #p() { + try { + this.#l = ee(() => this.#i(this.#e)); + } catch (t) { + this.error(t); + } + } + /** + * @param {unknown} error The deserialized error from the server's hydration comment + */ + #g(t) { + const r = this.#t.failed; + r && (this.#o = ee(() => { + r( + this.#e, + () => t, + () => () => { + } + ); + })); + } + #_() { + const t = this.#t.pending; + t && (this.is_pending = !0, this.#r = ee(() => t(this.#e)), Pe(() => { + var r = this.#f = document.createDocumentFragment(), n = ie(); + r.append(n), this.#l = this.#y(() => ee(() => this.#i(n))), this.#a === 0 && (this.#e.before(r), this.#f = null, Ue( + /** @type {Effect} */ + this.#r, + () => { + this.#r = null; + } + ), this.#w( + /** @type {Batch} */ + S + )); + })); + } + #m() { + try { + if (this.is_pending = this.has_pending_snippet(), this.#a = 0, this.#u = 0, this.#l = ee(() => { + this.#i(this.#e); + }), this.#a > 0) { + var t = this.#f = document.createDocumentFragment(); + gr(this.#l, t); + const r = ( + /** @type {(anchor: Node) => void} */ + this.#t.pending + ); + this.#r = ee(() => r(this.#e)); + } else + this.#w( + /** @type {Batch} */ + S + ); + } catch (r) { + this.error(r); + } + } + /** + * @param {Batch} batch + */ + #w(t) { + this.is_pending = !1, t.transfer_effects(this.#v, this.#d); + } + /** + * Defer an effect inside a pending boundary until the boundary resolves + * @param {Effect} effect + */ + defer_effect(t) { + en(t, this.#v, this.#d); + } + /** + * Returns `false` if the effect exists inside a boundary whose pending snippet is shown + * @returns {boolean} + */ + is_rendered() { + return !this.is_pending && (!this.parent || this.parent.is_rendered()); + } + has_pending_snippet() { + return !!this.#t.pending; + } + /** + * @template T + * @param {() => T} fn + */ + #y(t) { + var r = y, n = A, s = G; + ge(this.#s), oe(this.#s), it(this.#s.ctx); + try { + return Oe.ensure(), t(); + } catch (i) { + return Xr(i), null; + } finally { + ge(r), oe(n), it(s); + } + } + /** + * Updates the pending count associated with the currently visible pending snippet, + * if any, such that we can replace the snippet with content once work is done + * @param {1 | -1} d + * @param {Batch} batch + */ + #$(t, r) { + if (!this.has_pending_snippet()) { + this.parent && this.parent.#$(t, r); + return; + } + this.#a += t, this.#a === 0 && (this.#w(r), this.#r && Ue(this.#r, () => { + this.#r = null; + }), this.#f && (this.#e.before(this.#f), this.#f = null)); + } + /** + * Update the source that powers `$effect.pending()` inside this boundary, + * and controls when the current `pending` snippet (if any) is removed. + * Do not call from inside the class + * @param {1 | -1} d + * @param {Batch} batch + */ + update_pending_count(t, r) { + this.#$(t, r), this.#u += t, !(!this.#c || this.#h) && (this.#h = !0, Pe(() => { + this.#h = !1, this.#c && lt(this.#c, this.#u); + })); + } + get_effect_pending() { + return this.#b(), b( + /** @type {Source} */ + this.#c + ); + } + /** @param {unknown} error */ + error(t) { + if (!this.#t.onerror && !this.#t.failed) + throw t; + S?.is_fork ? (this.#l && S.skip_effect(this.#l), this.#r && S.skip_effect(this.#r), this.#o && S.skip_effect(this.#o), S.on_fork_commit(() => { + this.#k(t); + })) : this.#k(t); + } + /** + * @param {unknown} error + */ + #k(t) { + this.#l && (Y(this.#l), this.#l = null), this.#r && (Y(this.#r), this.#r = null), this.#o && (Y(this.#o), this.#o = null), N && (j( + /** @type {TemplateNode} */ + this.#n + ), Vr(), j(Ot())); + var r = this.#t.onerror; + let n = this.#t.failed; + var s = !1, i = !1; + const o = () => { + if (s) { + Fs(); + return; + } + s = !0, i && Ds(), this.#o !== null && Ue(this.#o, () => { + this.#o = null; + }), this.#y(() => { + this.#m(); + }); + }, l = (f) => { + try { + i = !0, r?.(f, o), i = !1; + } catch (a) { + Ie(a, this.#s && this.#s.parent); + } + n && (this.#o = this.#y(() => { + try { + return ee(() => { + var a = ( + /** @type {Effect} */ + y + ); + a.b = this, a.f |= Ht, n( + this.#e, + () => f, + () => o + ); + }); + } catch (a) { + return Ie( + a, + /** @type {Effect} */ + this.#s.parent + ), null; + } + })); + }; + Pe(() => { + var f; + try { + f = this.transform_error(t); + } catch (a) { + Ie(a, this.#s && this.#s.parent); + return; + } + f !== null && typeof f == "object" && typeof /** @type {any} */ + f.then == "function" ? f.then( + l, + /** @param {unknown} e */ + (a) => Ie(a, this.#s && this.#s.parent) + ) : l(f); + }); + } +} +function Js(e, t, r, n) { + const s = Pt; + var i = e.filter((d) => !d.settled); + if (r.length === 0 && i.length === 0) { + n(t.map(s)); + return; + } + var o = ( + /** @type {Effect} */ + y + ), l = Zs(), f = i.length === 1 ? i[0].promise : i.length > 1 ? Promise.all(i.map((d) => d.promise)) : null; + function a(d) { + l(); + try { + n(d); + } catch (v) { + o.f & Z || Ie(v, o); + } + Mt(); + } + if (r.length === 0) { + f.then(() => a(t.map(s))); + return; + } + var u = an(); + function c() { + Promise.all(r.map((d) => /* @__PURE__ */ Xs(d))).then((d) => a([...t.map(s), ...d])).catch((d) => Ie(d, o)).finally(() => u()); + } + f ? f.then(() => { + l(), c(), Mt(); + }) : c(); +} +function Zs() { + var e = ( + /** @type {Effect} */ + y + ), t = A, r = G, n = ( + /** @type {Batch} */ + S + ); + return function(i = !0) { + ge(e), oe(t), it(r), i && !(e.f & Z) && (n?.activate(), n?.apply()); + }; +} +function Mt(e = !0) { + ge(null), oe(null), it(null), e && S?.deactivate(); +} +function an() { + var e = ( + /** @type {Effect} */ + y + ), t = ( + /** @type {Boundary} */ + e.b + ), r = ( + /** @type {Batch} */ + S + ), n = t.is_rendered(); + return t.update_pending_count(1, r), r.increment(n, e), (s = !1) => { + t.update_pending_count(-1, r), r.decrement(n, e, s); + }; +} +// @__NO_SIDE_EFFECTS__ +function Pt(e) { + var t = H | z; + return y !== null && (y.f |= Xe), { + ctx: G, + deps: null, + effects: null, + equals: Wr, + f: t, + fn: e, + reactions: null, + rv: 0, + v: ( + /** @type {V} */ + P + ), + wv: 0, + parent: y, + ac: null + }; +} +// @__NO_SIDE_EFFECTS__ +function Xs(e, t, r) { + let n = ( + /** @type {Effect | null} */ + y + ); + n === null && xs(); + var s = ( + /** @type {Promise} */ + /** @type {unknown} */ + void 0 + ), i = Ze( + /** @type {V} */ + P + ), o = !A, l = /* @__PURE__ */ new Map(); + return li(() => { + var f = ( + /** @type {Effect} */ + y + ), a = qr(); + s = a.promise; + try { + Promise.resolve(e()).then(a.resolve, a.reject).finally(Mt); + } catch (v) { + a.reject(v), Mt(); + } + var u = ( + /** @type {Batch} */ + S + ); + if (o) { + if (f.f & Ce) + var c = an(); + if ( + /** @type {Boundary} */ + n.b.is_rendered() + ) + l.get(u)?.reject(ye), l.delete(u); + else { + for (const v of l.values()) + v.reject(ye); + l.clear(); + } + l.set(u, a); + } + const d = (v, h = void 0) => { + if (c) { + var p = h === ye; + c(p); + } + if (!(h === ye || f.f & Z)) { + if (u.activate(), h) + i.f |= De, lt(i, h); + else { + i.f & De && (i.f ^= De), lt(i, v); + for (const [_, $] of l) { + if (l.delete(_), _ === u) break; + $.reject(ye); + } + } + u.deactivate(); + } + }; + a.promise.then(d, (v) => d(null, v || "unknown")); + }), cr(() => { + for (const f of l.values()) + f.reject(ye); + }), new Promise((f) => { + function a(u) { + function c() { + u === s ? f(i) : a(s); + } + u.then(c, c); + } + a(s); + }); +} +// @__NO_SIDE_EFFECTS__ +function Le(e) { + const t = /* @__PURE__ */ Pt(e); + return Tn(t), t; +} +// @__NO_SIDE_EFFECTS__ +function fn(e) { + const t = /* @__PURE__ */ Pt(e); + return t.equals = Kr, t; +} +function Qs(e) { + var t = e.effects; + if (t !== null) { + e.effects = null; + for (var r = 0; r < t.length; r += 1) + Y( + /** @type {Effect} */ + t[r] + ); + } +} +function or(e) { + var t, r = y, n = e.parent; + if (!Me && n !== null && n.f & (Z | V)) + return Ps(), e.v; + ge(n); + try { + e.f &= ~Je, Qs(e), t = On(e); + } finally { + ge(r); + } + return t; +} +function un(e) { + var t = or(e); + if (!e.equals(t) && (e.wv = An(), (!S?.is_fork || e.deps === null) && (S !== null ? S.capture(e, t, !0) : e.v = t, e.deps === null))) { + R(e, D); + return; + } + Me || (ue !== null ? (ur() || S?.is_fork) && ue.set(e, t) : sr(e)); +} +function ei(e) { + if (e.effects !== null) + for (const t of e.effects) + (t.teardown || t.ac) && (t.teardown?.(), t.ac?.abort(ye), t.teardown = re, t.ac = null, mt(t, 0), pr(t)); +} +function cn(e) { + if (e.effects !== null) + for (const t of e.effects) + t.teardown && ot(t); +} +let Wt = /* @__PURE__ */ new Set(); +const Be = /* @__PURE__ */ new Map(); +let hn = !1; +function Ze(e, t) { + var r = { + f: 0, + // TODO ideally we could skip this altogether, but it causes type errors + v: e, + reactions: null, + equals: Wr, + rv: 0, + wv: 0 + }; + return r; +} +// @__NO_SIDE_EFFECTS__ +function me(e, t) { + const r = Ze(e); + return Tn(r), r; +} +// @__NO_SIDE_EFFECTS__ +function ar(e, t = !1, r = !0) { + const n = Ze(e); + return t || (n.equals = Kr), n; +} +function te(e, t, r = !1) { + A !== null && // since we are untracking the function inside `$inspect.with` we need to add this check + // to ensure we error if state is set inside an inspect effect + (!ce || A.f & Bt) && Jr() && A.f & (H | he | bt | Bt) && (le === null || !rt.call(le, e)) && Is(); + let n = r ? je(t) : t; + return lt(e, n, xt); +} +function lt(e, t, r = null) { + if (!e.equals(t)) { + Be.set(e, Me ? t : e.v); + var n = Oe.ensure(); + if (n.capture(e, t), e.f & H) { + const s = ( + /** @type {Derived} */ + e + ); + e.f & z && or(s), ue === null && sr(s); + } + e.wv = An(), dn(e, z, r), y !== null && y.f & D && !(y.f & (de | Ne)) && (Q === null ? ai([e]) : Q.push(e)), !n.is_fork && Wt.size > 0 && !hn && ti(); + } + return t; +} +function ti() { + hn = !1; + for (const e of Wt) + e.f & D && R(e, _e), $t(e) && ot(e); + Wt.clear(); +} +function _t(e) { + te(e, e.v + 1); +} +function dn(e, t, r) { + var n = e.reactions; + if (n !== null) + for (var s = n.length, i = 0; i < s; i++) { + var o = n[i], l = o.f, f = (l & z) === 0; + if (f && R(o, t), l & H) { + var a = ( + /** @type {Derived} */ + o + ); + ue?.delete(a), l & Je || (l & se && (y === null || !(y.f & Nt)) && (o.f |= Je), dn(a, _e, r)); + } else if (f) { + var u = ( + /** @type {Effect} */ + o + ); + l & he && we !== null && we.add(u), r !== null ? r.push(u) : lr(u); + } + } +} +function je(e) { + if (typeof e != "object" || e === null || vt in e) + return e; + const t = Hr(e); + if (t !== _s && t !== gs) + return e; + var r = /* @__PURE__ */ new Map(), n = jr(e), s = /* @__PURE__ */ me(0), i = Ve, o = (l) => { + if (Ve === i) + return l(); + var f = A, a = Ve; + oe(null), Ar(i); + var u = l(); + return oe(f), Ar(a), u; + }; + return n && r.set("length", /* @__PURE__ */ me( + /** @type {any[]} */ + e.length + )), new Proxy( + /** @type {any} */ + e, + { + defineProperty(l, f, a) { + (!("value" in a) || a.configurable === !1 || a.enumerable === !1 || a.writable === !1) && Rs(); + var u = r.get(f); + return u === void 0 ? o(() => { + var c = /* @__PURE__ */ me(a.value); + return r.set(f, c), c; + }) : te(u, a.value, !0), !0; + }, + deleteProperty(l, f) { + var a = r.get(f); + if (a === void 0) { + if (f in l) { + const u = o(() => /* @__PURE__ */ me(P)); + r.set(f, u), _t(s); + } + } else + te(a, P), _t(s); + return !0; + }, + get(l, f, a) { + if (f === vt) + return e; + var u = r.get(f), c = f in l; + if (u === void 0 && (!c || qe(l, f)?.writable) && (u = o(() => { + var v = je(c ? l[f] : P), h = /* @__PURE__ */ me(v); + return h; + }), r.set(f, u)), u !== void 0) { + var d = b(u); + return d === P ? void 0 : d; + } + return Reflect.get(l, f, a); + }, + getOwnPropertyDescriptor(l, f) { + var a = Reflect.getOwnPropertyDescriptor(l, f); + if (a && "value" in a) { + var u = r.get(f); + u && (a.value = b(u)); + } else if (a === void 0) { + var c = r.get(f), d = c?.v; + if (c !== void 0 && d !== P) + return { + enumerable: !0, + configurable: !0, + value: d, + writable: !0 + }; + } + return a; + }, + has(l, f) { + if (f === vt) + return !0; + var a = r.get(f), u = a !== void 0 && a.v !== P || Reflect.has(l, f); + if (a !== void 0 || y !== null && (!u || qe(l, f)?.writable)) { + a === void 0 && (a = o(() => { + var d = u ? je(l[f]) : P, v = /* @__PURE__ */ me(d); + return v; + }), r.set(f, a)); + var c = b(a); + if (c === P) + return !1; + } + return u; + }, + set(l, f, a, u) { + var c = r.get(f), d = f in l; + if (n && f === "length") + for (var v = a; v < /** @type {Source} */ + c.v; v += 1) { + var h = r.get(v + ""); + h !== void 0 ? te(h, P) : v in l && (h = o(() => /* @__PURE__ */ me(P)), r.set(v + "", h)); + } + if (c === void 0) + (!d || qe(l, f)?.writable) && (c = o(() => /* @__PURE__ */ me(void 0)), te(c, je(a)), r.set(f, c)); + else { + d = c.v !== P; + var p = o(() => je(a)); + te(c, p); + } + var _ = Reflect.getOwnPropertyDescriptor(l, f); + if (_?.set && _.set.call(u, a), !d) { + if (n && typeof f == "string") { + var $ = ( + /** @type {Source} */ + r.get("length") + ), g = Number(f); + Number.isInteger(g) && g >= $.v && te($, g + 1); + } + _t(s); + } + return !0; + }, + ownKeys(l) { + b(s); + var f = Reflect.ownKeys(l).filter((c) => { + var d = r.get(c); + return d === void 0 || d.v !== P; + }); + for (var [a, u] of r) + u.v !== P && !(a in l) && f.push(a); + return f; + }, + setPrototypeOf() { + Ls(); + } + } + ); +} +var Tr, vn, pn, _n; +function Gt() { + if (Tr === void 0) { + Tr = window, vn = /Firefox/.test(navigator.userAgent); + var e = Element.prototype, t = Node.prototype, r = Text.prototype; + pn = qe(t, "firstChild").get, _n = qe(t, "nextSibling").get, kr(e) && (e.__click = void 0, e.__className = void 0, e.__attributes = null, e.__style = void 0, e.__e = void 0), kr(r) && (r.__t = void 0); + } +} +function ie(e = "") { + return document.createTextNode(e); +} +// @__NO_SIDE_EFFECTS__ +function ne(e) { + return ( + /** @type {TemplateNode | null} */ + pn.call(e) + ); +} +// @__NO_SIDE_EFFECTS__ +function ve(e) { + return ( + /** @type {TemplateNode | null} */ + _n.call(e) + ); +} +function B(e, t) { + if (!N) + return /* @__PURE__ */ ne(e); + var r = /* @__PURE__ */ ne(x); + if (r === null) + r = x.appendChild(ie()); + else if (t && r.nodeType !== Lt) { + var n = ie(); + return r?.before(n), j(n), n; + } + return t && fr( + /** @type {Text} */ + r + ), j(r), r; +} +function Kt(e, t = !1) { + if (!N) { + var r = /* @__PURE__ */ ne(e); + return r instanceof Comment && r.data === "" ? /* @__PURE__ */ ve(r) : r; + } + if (t) { + if (x?.nodeType !== Lt) { + var n = ie(); + return x?.before(n), j(n), n; + } + fr( + /** @type {Text} */ + x + ); + } + return x; +} +function $e(e, t = 1, r = !1) { + let n = N ? x : e; + for (var s; t--; ) + s = n, n = /** @type {TemplateNode} */ + /* @__PURE__ */ ve(n); + if (!N) + return n; + if (r) { + if (n?.nodeType !== Lt) { + var i = ie(); + return n === null ? s?.after(i) : n.before(i), j(i), i; + } + fr( + /** @type {Text} */ + n + ); + } + return j(n), n; +} +function gn(e) { + e.textContent = ""; +} +function bn() { + return !1; +} +function Ft(e, t, r) { + return ( + /** @type {T extends keyof HTMLElementTagNameMap ? HTMLElementTagNameMap[T] : Element} */ + document.createElementNS(t ?? zr, e, void 0) + ); +} +function fr(e) { + if ( + /** @type {string} */ + e.nodeValue.length < 65536 + ) + return; + let t = e.nextSibling; + for (; t !== null && t.nodeType === Lt; ) + t.remove(), e.nodeValue += /** @type {string} */ + t.nodeValue, t = e.nextSibling; +} +function yt(e) { + var t = A, r = y; + oe(null), ge(null); + try { + return e(); + } finally { + oe(t), ge(r); + } +} +function ri(e) { + y === null && (A === null && Ns(), As()), Me && Ss(); +} +function ni(e, t) { + var r = t.last; + r === null ? t.last = t.first = e : (r.next = e, e.prev = r, t.last = e); +} +function be(e, t) { + var r = y; + r !== null && r.f & V && (e |= V); + var n = { + ctx: G, + deps: null, + nodes: null, + f: e | z | se, + first: null, + fn: t, + last: null, + next: null, + parent: r, + b: r && r.b, + prev: null, + teardown: null, + wv: 0, + ac: null + }; + S?.register_created_effect(n); + var s = n; + if (e & nt) + et !== null ? et.push(n) : Oe.ensure().schedule(n); + else if (t !== null) { + try { + ot(n); + } catch (o) { + throw Y(n), o; + } + s.deps === null && s.teardown === null && s.nodes === null && s.first === s.last && // either `null`, or a singular child + !(s.f & Xe) && (s = s.first, e & he && e & Ke && s !== null && (s.f |= Ke)); + } + if (s !== null && (s.parent = r, r !== null && ni(s, r), A !== null && A.f & H && !(e & Ne))) { + var i = ( + /** @type {Derived} */ + A + ); + (i.effects ??= []).push(s); + } + return n; +} +function ur() { + return A !== null && !ce; +} +function cr(e) { + const t = be(Rt, null); + return R(t, D), t.teardown = e, t; +} +function mn(e) { + ri(); + var t = ( + /** @type {Effect} */ + y.f + ), r = !A && (t & de) !== 0 && (t & Ce) === 0; + if (r) { + var n = ( + /** @type {ComponentContext} */ + G + ); + (n.e ??= []).push(e); + } else + return wn(e); +} +function wn(e) { + return be(nt | $s, e); +} +function si(e) { + Oe.ensure(); + const t = be(Ne | Xe, e); + return () => { + Y(t); + }; +} +function ii(e) { + Oe.ensure(); + const t = be(Ne | Xe, e); + return (r = {}) => new Promise((n) => { + r.outro ? Ue(t, () => { + Y(t), n(void 0); + }) : (Y(t), n(void 0)); + }); +} +function hr(e) { + return be(nt, e); +} +function li(e) { + return be(bt | Xe, e); +} +function dr(e, t = 0) { + return be(Rt | t, e); +} +function Te(e, t = [], r = [], n = []) { + Js(n, t, r, (s) => { + be(Rt, () => e(...s.map(b))); + }); +} +function vr(e, t = 0) { + var r = be(he | t, e); + return r; +} +function ee(e) { + return be(de | Xe, e); +} +function yn(e) { + var t = e.teardown; + if (t !== null) { + const r = Me, n = A; + Sr(!0), oe(null); + try { + t.call(null); + } finally { + Sr(r), oe(n); + } + } +} +function pr(e, t = !1) { + var r = e.first; + for (e.first = e.last = null; r !== null; ) { + const s = r.ac; + s !== null && yt(() => { + s.abort(ye); + }); + var n = r.next; + r.f & Ne ? r.parent = null : Y(r, t), r = n; + } +} +function oi(e) { + for (var t = e.first; t !== null; ) { + var r = t.next; + t.f & de || Y(t), t = r; + } +} +function Y(e, t = !0) { + var r = !1; + (t || e.f & ys) && e.nodes !== null && e.nodes.end !== null && ($n( + e.nodes.start, + /** @type {TemplateNode} */ + e.nodes.end + ), r = !0), R(e, qt), pr(e, t && !r), mt(e, 0); + var n = e.nodes && e.nodes.t; + if (n !== null) + for (const i of n) + i.stop(); + yn(e), e.f ^= qt, e.f |= Z; + var s = e.parent; + s !== null && s.first !== null && kn(e), e.next = e.prev = e.teardown = e.ctx = e.deps = e.fn = e.nodes = e.ac = e.b = null; +} +function $n(e, t) { + for (; e !== null; ) { + var r = e === t ? null : /* @__PURE__ */ ve(e); + e.remove(), e = r; + } +} +function kn(e) { + var t = e.parent, r = e.prev, n = e.next; + r !== null && (r.next = n), n !== null && (n.prev = r), t !== null && (t.first === e && (t.first = n), t.last === e && (t.last = r)); +} +function Ue(e, t, r = !0) { + var n = []; + En(e, n, !0); + var s = () => { + r && Y(e), t && t(); + }, i = n.length; + if (i > 0) { + var o = () => --i || s(); + for (var l of n) + l.out(o); + } else + s(); +} +function En(e, t, r) { + if (!(e.f & V)) { + e.f ^= V; + var n = e.nodes && e.nodes.t; + if (n !== null) + for (const l of n) + (l.is_global || r) && t.push(l); + for (var s = e.first; s !== null; ) { + var i = s.next; + if (!(s.f & Ne)) { + var o = (s.f & Ke) !== 0 || // If this is a branch effect without a block effect parent, + // it means the parent block effect was pruned. In that case, + // transparency information was transferred to the branch effect. + (s.f & de) !== 0 && (e.f & he) !== 0; + En(s, t, o ? r : !1); + } + s = i; + } + } +} +function _r(e) { + xn(e, !0); +} +function xn(e, t) { + if (e.f & V) { + e.f ^= V, e.f & D || (R(e, z), Oe.ensure().schedule(e)); + for (var r = e.first; r !== null; ) { + var n = r.next, s = (r.f & Ke) !== 0 || (r.f & de) !== 0; + xn(r, s ? t : !1), r = n; + } + var i = e.nodes && e.nodes.t; + if (i !== null) + for (const o of i) + (o.is_global || t) && o.in(); + } +} +function gr(e, t) { + if (e.nodes) + for (var r = e.nodes.start, n = e.nodes.end; r !== null; ) { + var s = r === n ? null : /* @__PURE__ */ ve(r); + t.append(r), r = s; + } +} +let Tt = !1, Me = !1; +function Sr(e) { + Me = e; +} +let A = null, ce = !1; +function oe(e) { + A = e; +} +let y = null; +function ge(e) { + y = e; +} +let le = null; +function Tn(e) { + A !== null && (le === null ? le = [e] : le.push(e)); +} +let W = null, J = 0, Q = null; +function ai(e) { + Q = e; +} +let Sn = 1, He = 0, Ve = He; +function Ar(e) { + Ve = e; +} +function An() { + return ++Sn; +} +function $t(e) { + var t = e.f; + if (t & z) + return !0; + if (t & H && (e.f &= ~Je), t & _e) { + for (var r = ( + /** @type {Value[]} */ + e.deps + ), n = r.length, s = 0; s < n; s++) { + var i = r[s]; + if ($t( + /** @type {Derived} */ + i + ) && un( + /** @type {Derived} */ + i + ), i.wv > e.wv) + return !0; + } + t & se && // During time traveling we don't want to reset the status so that + // traversal of the graph in the other batches still happens + ue === null && R(e, D); + } + return !1; +} +function Nn(e, t, r = !0) { + var n = e.reactions; + if (n !== null && !(le !== null && rt.call(le, e))) + for (var s = 0; s < n.length; s++) { + var i = n[s]; + i.f & H ? Nn( + /** @type {Derived} */ + i, + t, + !1 + ) : t === i && (r ? R(i, z) : i.f & D && R(i, _e), lr( + /** @type {Effect} */ + i + )); + } +} +function On(e) { + var t = W, r = J, n = Q, s = A, i = le, o = G, l = ce, f = Ve, a = e.f; + W = /** @type {null | Value[]} */ + null, J = 0, Q = null, A = a & (de | Ne) ? null : e, le = null, it(e.ctx), ce = !1, Ve = ++He, e.ac !== null && (yt(() => { + e.ac.abort(ye); + }), e.ac = null); + try { + e.f |= Nt; + var u = ( + /** @type {Function} */ + e.fn + ), c = u(); + e.f |= Ce; + var d = e.deps, v = S?.is_fork; + if (W !== null) { + var h; + if (v || mt(e, J), d !== null && J > 0) + for (d.length = J + W.length, h = 0; h < W.length; h++) + d[J + h] = W[h]; + else + e.deps = d = W; + if (ur() && e.f & se) + for (h = J; h < d.length; h++) + (d[h].reactions ??= []).push(e); + } else !v && d !== null && J < d.length && (mt(e, J), d.length = J); + if (Jr() && Q !== null && !ce && d !== null && !(e.f & (H | _e | z))) + for (h = 0; h < /** @type {Source[]} */ + Q.length; h++) + Nn( + Q[h], + /** @type {Effect} */ + e + ); + if (s !== null && s !== e) { + if (He++, s.deps !== null) + for (let p = 0; p < r; p += 1) + s.deps[p].rv = He; + if (t !== null) + for (const p of t) + p.rv = He; + Q !== null && (n === null ? n = Q : n.push(.../** @type {Source[]} */ + Q)); + } + return e.f & De && (e.f ^= De), c; + } catch (p) { + return Xr(p); + } finally { + e.f ^= Nt, W = t, J = r, Q = n, A = s, le = i, it(o), ce = l, Ve = f; + } +} +function fi(e, t) { + let r = t.reactions; + if (r !== null) { + var n = vs.call(r, e); + if (n !== -1) { + var s = r.length - 1; + s === 0 ? r = t.reactions = null : (r[n] = r[s], r.pop()); + } + } + if (r === null && t.f & H && // Destroying a child effect while updating a parent effect can cause a dependency to appear + // to be unused, when in fact it is used by the currently-updating parent. Checking `new_deps` + // allows us to skip the expensive work of disconnecting and immediately reconnecting it + (W === null || !rt.call(W, t))) { + var i = ( + /** @type {Derived} */ + t + ); + i.f & se && (i.f ^= se, i.f &= ~Je), i.v !== P && sr(i), ei(i), mt(i, 0); + } +} +function mt(e, t) { + var r = e.deps; + if (r !== null) + for (var n = t; n < r.length; n++) + fi(e, r[n]); +} +function ot(e) { + var t = e.f; + if (!(t & Z)) { + R(e, D); + var r = y, n = Tt; + y = e, Tt = !0; + try { + t & (he | Br) ? oi(e) : pr(e), yn(e); + var s = On(e); + e.teardown = typeof s == "function" ? s : null, e.wv = Sn; + var i; + ds && zs && e.f & z && e.deps; + } finally { + Tt = n, y = r; + } + } +} +async function ui() { + await Promise.resolve(), Se(); +} +function b(e) { + var t = e.f, r = (t & H) !== 0; + if (A !== null && !ce) { + var n = y !== null && (y.f & Z) !== 0; + if (!n && (le === null || !rt.call(le, e))) { + var s = A.deps; + if (A.f & Nt) + e.rv < He && (e.rv = He, W === null && s !== null && s[J] === e ? J++ : W === null ? W = [e] : W.push(e)); + else { + (A.deps ??= []).push(e); + var i = e.reactions; + i === null ? e.reactions = [A] : rt.call(i, A) || i.push(A); + } + } + } + if (Me && Be.has(e)) + return Be.get(e); + if (r) { + var o = ( + /** @type {Derived} */ + e + ); + if (Me) { + var l = o.v; + return (!(o.f & D) && o.reactions !== null || Cn(o)) && (l = or(o)), Be.set(o, l), l; + } + var f = (o.f & se) === 0 && !ce && A !== null && (Tt || (A.f & se) !== 0), a = (o.f & Ce) === 0; + $t(o) && (f && (o.f |= se), un(o)), f && !a && (cn(o), Mn(o)); + } + if (ue?.has(e)) + return ue.get(e); + if (e.f & De) + throw e.v; + return e.v; +} +function Mn(e) { + if (e.f |= se, e.deps !== null) + for (const t of e.deps) + (t.reactions ??= []).push(e), t.f & H && !(t.f & se) && (cn( + /** @type {Derived} */ + t + ), Mn( + /** @type {Derived} */ + t + )); +} +function Cn(e) { + if (e.v === P) return !0; + if (e.deps === null) return !1; + for (const t of e.deps) + if (Be.has(t) || t.f & H && Cn( + /** @type {Derived} */ + t + )) + return !0; + return !1; +} +function ft(e) { + var t = ce; + try { + return ce = !0, e(); + } finally { + ce = t; + } +} +const ht = Symbol("events"), Rn = /* @__PURE__ */ new Set(), Jt = /* @__PURE__ */ new Set(); +function ci(e, t, r, n = {}) { + function s(i) { + if (n.capture || Zt.call(t, i), !i.cancelBubble) + return yt(() => r?.call(this, i)); + } + return e.startsWith("pointer") || e.startsWith("touch") || e === "wheel" ? Pe(() => { + t.addEventListener(e, s, n); + }) : t.addEventListener(e, s, n), s; +} +function hi(e, t, r, n, s) { + var i = { capture: n, passive: s }, o = ci(e, t, r, i); + (t === document.body || // @ts-ignore + t === window || // @ts-ignore + t === document || // Firefox has quirky behavior, it can happen that we still get "canplay" events when the element is already removed + t instanceof HTMLMediaElement) && cr(() => { + t.removeEventListener(e, o, i); + }); +} +function Nr(e, t, r) { + (t[ht] ??= {})[e] = r; +} +function di(e) { + for (var t = 0; t < e.length; t++) + Rn.add(e[t]); + for (var r of Jt) + r(e); +} +let Or = null; +function Zt(e) { + var t = this, r = ( + /** @type {Node} */ + t.ownerDocument + ), n = e.type, s = e.composedPath?.() || [], i = ( + /** @type {null | Element} */ + s[0] || e.target + ); + Or = e; + var o = 0, l = Or === e && e[ht]; + if (l) { + var f = s.indexOf(l); + if (f !== -1 && (t === document || t === /** @type {any} */ + window)) { + e[ht] = t; + return; + } + var a = s.indexOf(t); + if (a === -1) + return; + f <= a && (o = f); + } + if (i = /** @type {Element} */ + s[o] || e.target, i !== t) { + gt(e, "currentTarget", { + configurable: !0, + get() { + return i || r; + } + }); + var u = A, c = y; + oe(null), ge(null); + try { + for (var d, v = []; i !== null; ) { + var h = i.assignedSlot || i.parentNode || /** @type {any} */ + i.host || null; + try { + var p = i[ht]?.[n]; + p != null && (!/** @type {any} */ + i.disabled || // DOM could've been updated already by the time this is reached, so we check this as well + // -> the target could not have been disabled because it emits the event in the first place + e.target === i) && p.call(i, e); + } catch (_) { + d ? v.push(_) : d = _; + } + if (e.cancelBubble || h === t || h === null) + break; + i = h; + } + if (d) { + for (let _ of v) + queueMicrotask(() => { + throw _; + }); + throw d; + } + } finally { + e[ht] = t, delete e.currentTarget, oe(u), ge(c); + } + } +} +const vi = ( + // We gotta write it like this because after downleveling the pure comment may end up in the wrong location + globalThis?.window?.trustedTypes && /* @__PURE__ */ globalThis.window.trustedTypes.createPolicy("svelte-trusted-html", { + /** @param {string} html */ + createHTML: (e) => e + }) +); +function pi(e) { + return ( + /** @type {string} */ + vi?.createHTML(e) ?? e + ); +} +function _i(e) { + var t = Ft("template"); + return t.innerHTML = pi(e.replaceAll("", "")), t.content; +} +function Ae(e, t) { + var r = ( + /** @type {Effect} */ + y + ); + r.nodes === null && (r.nodes = { start: e, end: t, a: null, t: null }); +} +// @__NO_SIDE_EFFECTS__ +function ae(e, t) { + var r = (t & fs) !== 0, n = (t & us) !== 0, s, i = !e.startsWith(""); + return () => { + if (N) + return Ae(x, null), x; + s === void 0 && (s = _i(i ? e : "" + e), r || (s = /** @type {TemplateNode} */ + /* @__PURE__ */ ne(s))); + var o = ( + /** @type {TemplateNode} */ + n || vn ? document.importNode(s, !0) : s.cloneNode(!0) + ); + if (r) { + var l = ( + /** @type {TemplateNode} */ + /* @__PURE__ */ ne(o) + ), f = ( + /** @type {TemplateNode} */ + o.lastChild + ); + Ae(l, f); + } else + Ae(o, o); + return o; + }; +} +function Ln() { + if (N) + return Ae(x, null), x; + var e = document.createDocumentFragment(), t = document.createComment(""), r = ie(); + return e.append(t, r), Ae(t, r), e; +} +function U(e, t) { + if (N) { + var r = ( + /** @type {Effect & { nodes: EffectNodes }} */ + y + ); + (!(r.f & Ce) || r.nodes.end === null) && (r.nodes.end = x), st(); + return; + } + e !== null && e.before( + /** @type {Node} */ + t + ); +} +const gi = ["touchstart", "touchmove"]; +function bi(e) { + return gi.includes(e); +} +let Xt = !0; +function fe(e, t) { + var r = t == null ? "" : typeof t == "object" ? `${t}` : t; + r !== (e.__t ??= e.nodeValue) && (e.__t = r, e.nodeValue = `${r}`); +} +function In(e, t) { + return Dn(e, t); +} +function mi(e, t) { + Gt(), t.intro = t.intro ?? !1; + const r = t.target, n = N, s = x; + try { + for (var i = /* @__PURE__ */ ne(r); i && (i.nodeType !== at || /** @type {Comment} */ + i.data !== Fr); ) + i = /* @__PURE__ */ ve(i); + if (!i) + throw Ge; + xe(!0), j( + /** @type {Comment} */ + i + ); + const o = Dn(e, { ...t, anchor: i }); + return xe(!1), /** @type {Exports} */ + o; + } catch (o) { + if (o instanceof Error && o.message.split(` +`).some((l) => l.startsWith("https://svelte.dev/e/"))) + throw o; + return o !== Ge && console.warn("Failed to hydrate: ", o), t.recover === !1 && Ms(), Gt(), gn(r), xe(!1), In(e, t); + } finally { + xe(n), j(s); + } +} +const Et = /* @__PURE__ */ new Map(); +function Dn(e, { target: t, anchor: r, props: n = {}, events: s, context: i, intro: o = !0, transformError: l }) { + Gt(); + var f = void 0, a = ii(() => { + var u = r ?? t.appendChild(ie()); + Gs( + /** @type {TemplateNode} */ + u, + { + pending: () => { + } + }, + (v) => { + It({}); + var h = ( + /** @type {ComponentContext} */ + G + ); + if (i && (h.c = i), s && (n.$$events = s), N && Ae( + /** @type {TemplateNode} */ + v, + null + ), Xt = o, f = e(v, n) || {}, Xt = !0, N && (y.nodes.end = x, x === null || x.nodeType !== at || /** @type {Comment} */ + x.data !== nr)) + throw wt(), Ge; + Dt(); + }, + l + ); + var c = /* @__PURE__ */ new Set(), d = (v) => { + for (var h = 0; h < v.length; h++) { + var p = v[h]; + if (!c.has(p)) { + c.add(p); + var _ = bi(p); + for (const C of [t, document]) { + var $ = Et.get(C); + $ === void 0 && ($ = /* @__PURE__ */ new Map(), Et.set(C, $)); + var g = $.get(p); + g === void 0 ? (C.addEventListener(p, Zt, { passive: _ }), $.set(p, 1)) : $.set(p, g + 1); + } + } + } + }; + return d(Ct(Rn)), Jt.add(d), () => { + for (var v of c) + for (const _ of [t, document]) { + var h = ( + /** @type {Map} */ + Et.get(_) + ), p = ( + /** @type {number} */ + h.get(v) + ); + --p == 0 ? (_.removeEventListener(v, Zt), h.delete(v), h.size === 0 && Et.delete(_)) : h.set(v, p); + } + Jt.delete(d), u !== r && u.parentNode?.removeChild(u); + }; + }); + return Qt.set(f, a), f; +} +let Qt = /* @__PURE__ */ new WeakMap(); +function wi(e, t) { + const r = Qt.get(e); + return r ? (Qt.delete(e), r(t)) : Promise.resolve(); +} +class yi { + /** @type {TemplateNode} */ + anchor; + /** @type {Map} */ + #e = /* @__PURE__ */ new Map(); + /** + * Map of keys to effects that are currently rendered in the DOM. + * These effects are visible and actively part of the document tree. + * Example: + * ``` + * {#if condition} + * foo + * {:else} + * bar + * {/if} + * ``` + * Can result in the entries `true->Effect` and `false->Effect` + * @type {Map} + */ + #n = /* @__PURE__ */ new Map(); + /** + * Similar to #onscreen with respect to the keys, but contains branches that are not yet + * in the DOM, because their insertion is deferred. + * @type {Map} + */ + #t = /* @__PURE__ */ new Map(); + /** + * Keys of effects that are currently outroing + * @type {Set} + */ + #i = /* @__PURE__ */ new Set(); + /** + * Whether to pause (i.e. outro) on change, or destroy immediately. + * This is necessary for `` + */ + #s = !0; + /** + * @param {TemplateNode} anchor + * @param {boolean} transition + */ + constructor(t, r = !0) { + this.anchor = t, this.#s = r; + } + /** + * @param {Batch} batch + */ + #l = (t) => { + if (this.#e.has(t)) { + var r = ( + /** @type {Key} */ + this.#e.get(t) + ), n = this.#n.get(r); + if (n) + _r(n), this.#i.delete(r); + else { + var s = this.#t.get(r); + s && (this.#n.set(r, s.effect), this.#t.delete(r), s.fragment.lastChild.remove(), this.anchor.before(s.fragment), n = s.effect); + } + for (const [i, o] of this.#e) { + if (this.#e.delete(i), i === t) + break; + const l = this.#t.get(o); + l && (Y(l.effect), this.#t.delete(o)); + } + for (const [i, o] of this.#n) { + if (i === r || this.#i.has(i)) continue; + const l = () => { + if (Array.from(this.#e.values()).includes(i)) { + var a = document.createDocumentFragment(); + gr(o, a), a.append(ie()), this.#t.set(i, { effect: o, fragment: a }); + } else + Y(o); + this.#i.delete(i), this.#n.delete(i); + }; + this.#s || !n ? (this.#i.add(i), Ue(o, l, !1)) : l(); + } + } + }; + /** + * @param {Batch} batch + */ + #r = (t) => { + this.#e.delete(t); + const r = Array.from(this.#e.values()); + for (const [n, s] of this.#t) + r.includes(n) || (Y(s.effect), this.#t.delete(n)); + }; + /** + * + * @param {any} key + * @param {null | ((target: TemplateNode) => void)} fn + */ + ensure(t, r) { + var n = ( + /** @type {Batch} */ + S + ), s = bn(); + if (r && !this.#n.has(t) && !this.#t.has(t)) + if (s) { + var i = document.createDocumentFragment(), o = ie(); + i.append(o), this.#t.set(t, { + effect: ee(() => r(o)), + fragment: i + }); + } else + this.#n.set( + t, + ee(() => r(this.anchor)) + ); + if (this.#e.set(n, t), s) { + for (const [l, f] of this.#n) + l === t ? n.unskip_effect(f) : n.skip_effect(f); + for (const [l, f] of this.#t) + l === t ? n.unskip_effect(f.effect) : n.skip_effect(f.effect); + n.oncommit(this.#l), n.ondiscard(this.#r); + } else + N && (this.anchor = x), this.#l(n); + } +} +function $i(e) { + G === null && Es(), mn(() => { + const t = ft(e); + if (typeof t == "function") return ( + /** @type {() => void} */ + t + ); + }); +} +function Ye(e, t, r = !1) { + var n; + N && (n = x, st()); + var s = new yi(e), i = r ? Ke : 0; + function o(l, f) { + if (N) { + var a = Yr( + /** @type {TemplateNode} */ + n + ); + if (l !== parseInt(a.substring(1))) { + var u = Ot(); + j(u), s.anchor = u, xe(!1), s.ensure(l, f), xe(!0); + return; + } + } + s.ensure(l, f); + } + vr(() => { + var l = !1; + t((f, a = 0) => { + l = !0, o(a, f); + }), l || o(-1, null); + }, i); +} +function ki(e, t) { + return t; +} +function Ei(e, t, r) { + for (var n = [], s = t.length, i, o = t.length, l = 0; l < s; l++) { + let c = t[l]; + Ue( + c, + () => { + if (i) { + if (i.pending.delete(c), i.done.add(c), i.pending.size === 0) { + var d = ( + /** @type {Set} */ + e.outrogroups + ); + er(e, Ct(i.done)), d.delete(i), d.size === 0 && (e.outrogroups = null); + } + } else + o -= 1; + }, + !1 + ); + } + if (o === 0) { + var f = n.length === 0 && r !== null; + if (f) { + var a = ( + /** @type {Element} */ + r + ), u = ( + /** @type {Element} */ + a.parentNode + ); + gn(u), u.append(a), e.items.clear(); + } + er(e, t, !f); + } else + i = { + pending: new Set(t), + done: /* @__PURE__ */ new Set() + }, (e.outrogroups ??= /* @__PURE__ */ new Set()).add(i); +} +function er(e, t, r = !0) { + var n; + if (e.pending.size > 0) { + n = /* @__PURE__ */ new Set(); + for (const o of e.pending.values()) + for (const l of o) + n.add( + /** @type {EachItem} */ + e.items.get(l).e + ); + } + for (var s = 0; s < t.length; s++) { + var i = t[s]; + if (n?.has(i)) { + i.f |= Ee; + const o = document.createDocumentFragment(); + gr(i, o); + } else + Y(t[s], r); + } +} +var Mr; +function Pn(e, t, r, n, s, i = null) { + var o = e, l = /* @__PURE__ */ new Map(); + { + var f = ( + /** @type {Element} */ + e + ); + o = N ? j(/* @__PURE__ */ ne(f)) : f.appendChild(ie()); + } + N && st(); + var a = null, u = /* @__PURE__ */ fn(() => { + var g = r(); + return jr(g) ? g : g == null ? [] : Ct(g); + }), c, d = /* @__PURE__ */ new Map(), v = !0; + function h(g) { + $.effect.f & Z || ($.pending.delete(g), $.fallback = a, xi($, c, o, t, n), a !== null && (c.length === 0 ? a.f & Ee ? (a.f ^= Ee, dt(a, null, o)) : _r(a) : Ue(a, () => { + a = null; + }))); + } + function p(g) { + $.pending.delete(g); + } + var _ = vr(() => { + c = /** @type {V[]} */ + b(u); + var g = c.length; + let C = !1; + if (N) { + var w = Yr(o) === rr; + w !== (g === 0) && (o = Ot(), j(o), xe(!1), C = !0); + } + for (var m = /* @__PURE__ */ new Set(), T = ( + /** @type {Batch} */ + S + ), M = bn(), E = 0; E < g; E += 1) { + N && x.nodeType === at && /** @type {Comment} */ + x.data === nr && (o = /** @type {Comment} */ + x, C = !0, xe(!1)); + var L = c[E], q = n(L, E), O = v ? null : l.get(q); + O ? (O.v && lt(O.v, L), O.i && lt(O.i, E), M && T.unskip_effect(O.e)) : (O = Ti( + l, + v ? o : Mr ??= ie(), + L, + q, + E, + s, + t, + r + ), v || (O.e.f |= Ee), l.set(q, O)), m.add(q); + } + if (g === 0 && i && !a && (v ? a = ee(() => i(o)) : (a = ee(() => i(Mr ??= ie())), a.f |= Ee)), g > m.size && Ts(), N && g > 0 && j(Ot()), !v) + if (d.set(T, m), M) { + for (const [k, I] of l) + m.has(k) || T.skip_effect(I.e); + T.oncommit(h), T.ondiscard(p); + } else + h(T); + C && xe(!0), b(u); + }), $ = { effect: _, items: l, pending: d, outrogroups: null, fallback: a }; + v = !1, N && (o = x); +} +function ct(e) { + for (; e !== null && !(e.f & de); ) + e = e.next; + return e; +} +function xi(e, t, r, n, s) { + var i = t.length, o = e.items, l = ct(e.effect.first), f, a = null, u = [], c = [], d, v, h, p; + for (p = 0; p < i; p += 1) { + if (d = t[p], v = s(d, p), h = /** @type {EachItem} */ + o.get(v).e, e.outrogroups !== null) + for (const E of e.outrogroups) + E.pending.delete(h), E.done.delete(h); + if (h.f & V && _r(h), h.f & Ee) + if (h.f ^= Ee, h === l) + dt(h, null, r); + else { + var _ = a ? a.next : l; + h === e.effect.last && (e.effect.last = h.prev), h.prev && (h.prev.next = h.next), h.next && (h.next.prev = h.prev), Re(e, a, h), Re(e, h, _), dt(h, _, r), a = h, u = [], c = [], l = ct(a.next); + continue; + } + if (h !== l) { + if (f !== void 0 && f.has(h)) { + if (u.length < c.length) { + var $ = c[0], g; + a = $.prev; + var C = u[0], w = u[u.length - 1]; + for (g = 0; g < u.length; g += 1) + dt(u[g], $, r); + for (g = 0; g < c.length; g += 1) + f.delete(c[g]); + Re(e, C.prev, w.next), Re(e, a, C), Re(e, w, $), l = $, a = w, p -= 1, u = [], c = []; + } else + f.delete(h), dt(h, l, r), Re(e, h.prev, h.next), Re(e, h, a === null ? e.effect.first : a.next), Re(e, a, h), a = h; + continue; + } + for (u = [], c = []; l !== null && l !== h; ) + (f ??= /* @__PURE__ */ new Set()).add(l), c.push(l), l = ct(l.next); + if (l === null) + continue; + } + h.f & Ee || u.push(h), a = h, l = ct(h.next); + } + if (e.outrogroups !== null) { + for (const E of e.outrogroups) + E.pending.size === 0 && (er(e, Ct(E.done)), e.outrogroups?.delete(E)); + e.outrogroups.size === 0 && (e.outrogroups = null); + } + if (l !== null || f !== void 0) { + var m = []; + if (f !== void 0) + for (h of f) + h.f & V || m.push(h); + for (; l !== null; ) + !(l.f & V) && l !== e.fallback && m.push(l), l = ct(l.next); + var T = m.length; + if (T > 0) { + var M = i === 0 ? r : null; + Ei(e, m, M); + } + } +} +function Ti(e, t, r, n, s, i, o, l) { + var f = o & ts ? o & ns ? Ze(r) : /* @__PURE__ */ ar(r, !1, !1) : null, a = o & rs ? Ze(s) : null; + return { + v: f, + i: a, + e: ee(() => (i(t, f ?? r, a ?? s, l), () => { + e.delete(n); + })) + }; +} +function dt(e, t, r) { + if (e.nodes) + for (var n = e.nodes.start, s = e.nodes.end, i = t && !(t.f & Ee) ? ( + /** @type {EffectNodes} */ + t.nodes.start + ) : r; n !== null; ) { + var o = ( + /** @type {TemplateNode} */ + /* @__PURE__ */ ve(n) + ); + if (i.before(n), n === s) + return; + n = o; + } +} +function Re(e, t, r) { + t === null ? e.effect.first = r : t.next = r, r === null ? e.effect.last = t : r.prev = t; +} +function Si(e, t, r = !1, n = !1, s = !1, i = !1) { + var o = e, l = ""; + if (r) { + var f = ( + /** @type {Element} */ + e + ); + N && (o = j(/* @__PURE__ */ ne(f))); + } + Te(() => { + var a = ( + /** @type {Effect} */ + y + ); + if (l === (l = t() ?? "")) { + N && st(); + return; + } + if (r && !N) { + a.nodes = null, f.innerHTML = /** @type {string} */ + l, l !== "" && Ae( + /** @type {TemplateNode} */ + /* @__PURE__ */ ne(f), + /** @type {TemplateNode} */ + f.lastChild + ); + return; + } + if (a.nodes !== null && ($n( + a.nodes.start, + /** @type {TemplateNode} */ + a.nodes.end + ), a.nodes = null), l !== "") { + if (N) { + x.data; + for (var u = st(), c = u; u !== null && (u.nodeType !== at || /** @type {Comment} */ + u.data !== ""); ) + c = u, u = /* @__PURE__ */ ve(u); + if (u === null) + throw wt(), Ge; + Ae(x, c), o = j(u); + return; + } + var d = n ? cs : s ? hs : void 0, v = ( + /** @type {HTMLTemplateElement | SVGElement | MathMLElement} */ + Ft(n ? "svg" : s ? "math" : "template", d) + ); + v.innerHTML = /** @type {any} */ + l; + var h = n || s ? v : ( + /** @type {HTMLTemplateElement} */ + v.content + ); + if (Ae( + /** @type {TemplateNode} */ + /* @__PURE__ */ ne(h), + /** @type {TemplateNode} */ + h.lastChild + ), n || s) + for (; /* @__PURE__ */ ne(h); ) + o.before( + /** @type {TemplateNode} */ + /* @__PURE__ */ ne(h) + ); + else + o.before(h); + } + }); +} +const Ai = () => performance.now(), ke = { + // don't access requestAnimationFrame eagerly outside method + // this allows basic testing of user code without JSDOM + // bunder will eval and remove ternary when the user's app is built + tick: ( + /** @param {any} _ */ + (e) => requestAnimationFrame(e) + ), + now: () => Ai(), + tasks: /* @__PURE__ */ new Set() +}; +function Fn() { + const e = ke.now(); + ke.tasks.forEach((t) => { + t.c(e) || (ke.tasks.delete(t), t.f()); + }), ke.tasks.size !== 0 && ke.tick(Fn); +} +function Ni(e) { + let t; + return ke.tasks.size === 0 && ke.tick(Fn), { + promise: new Promise((r) => { + ke.tasks.add(t = { c: e, f: r }); + }), + abort() { + ke.tasks.delete(t); + } + }; +} +function Cr(e, t) { + yt(() => { + e.dispatchEvent(new CustomEvent(t)); + }); +} +function Oi(e) { + if (e === "float") return "cssFloat"; + if (e === "offset") return "cssOffset"; + if (e.startsWith("--")) return e; + const t = e.split("-"); + return t.length === 1 ? t[0] : t[0] + t.slice(1).map( + /** @param {any} word */ + (r) => r[0].toUpperCase() + r.slice(1) + ).join(""); +} +function Rr(e) { + const t = {}, r = e.split(";"); + for (const n of r) { + const [s, i] = n.split(":"); + if (!s || i === void 0) break; + const o = Oi(s.trim()); + t[o] = i.trim(); + } + return t; +} +const Mi = (e) => e; +function tr(e, t, r, n) { + var s = (e & as) !== 0, i = "in", o, l = t.inert, f = t.style.overflow, a, u; + function c() { + return yt(() => o ??= r()(t, n?.() ?? /** @type {P} */ + {}, { + direction: i + })); + } + var d = { + is_global: s, + in() { + t.inert = l, a?.abort(), a = zn( + t, + c(), + u, + 1, + () => { + Cr(t, "introstart"); + }, + () => { + Cr(t, "introend"), a?.abort(), a = o = void 0, t.style.overflow = f; + } + ); + }, + out(_) { + { + _?.(), o = void 0; + return; + } + }, + stop: () => { + a?.abort(); + } + }, v = ( + /** @type {Effect & { nodes: EffectNodes }} */ + y + ); + if ((v.nodes.t ??= []).push(d), Xt) { + var h = s; + if (!h) { + for (var p = ( + /** @type {Effect | null} */ + v.parent + ); p && p.f & Ke; ) + for (; (p = p.parent) && !(p.f & he); ) + ; + h = !p || (p.f & Ce) !== 0; + } + h && hr(() => { + ft(() => d.in()); + }); + } +} +function zn(e, t, r, n, s, i) { + if (bs(t)) { + var o, l = !1; + return Pe(() => { + if (!l) { + var _ = t({ direction: "in" }); + o = zn(e, _, r, n, s, i); + } + }), { + abort: () => { + l = !0, o?.abort(); + }, + deactivate: () => o.deactivate(), + reset: () => o.reset(), + t: () => o.t() + }; + } + if (!t?.duration && !t?.delay) + return s(), i(), { + abort: re, + deactivate: re, + reset: re, + t: () => n + }; + const { delay: f = 0, css: a, tick: u, easing: c = Mi } = t; + var d = []; + if (u && u(0, 1), a) { + var v = Rr(a(0, 1)); + d.push(v, v); + } + var h = () => 1 - n, p = e.animate(d, { duration: f, fill: "forwards" }); + return p.onfinish = () => { + p.cancel(), s(); + var _ = 1 - n, $ = n - _, g = ( + /** @type {number} */ + t.duration * Math.abs($) + ), C = []; + if (g > 0) { + var w = !1; + if (a) + for (var m = Math.ceil(g / 16.666666666666668), T = 0; T <= m; T += 1) { + var M = _ + $ * c(T / m), E = Rr(a(M, 1 - M)); + C.push(E), w ||= E.overflow === "hidden"; + } + w && (e.style.overflow = "hidden"), h = () => { + var L = ( + /** @type {number} */ + /** @type {globalThis.Animation} */ + p.currentTime + ); + return _ + $ * c(L / g); + }, u && Ni(() => { + if (p.playState !== "running") return !1; + var L = h(); + return u(L, 1 - L), !0; + }); + } + p = e.animate(C, { duration: g, fill: "forwards" }), p.onfinish = () => { + h = () => n, u?.(n, 1 - n), i(); + }; + }, { + abort: () => { + p && (p.cancel(), p.effect = null, p.onfinish = re); + }, + deactivate: () => { + i = re; + }, + reset: () => { + }, + t: () => h() + }; +} +function br(e, t) { + hr(() => { + var r = e.getRootNode(), n = ( + /** @type {ShadowRoot} */ + r.host ? ( + /** @type {ShadowRoot} */ + r + ) : ( + /** @type {Document} */ + r.head ?? /** @type {Document} */ + r.ownerDocument.head + ) + ); + if (!n.querySelector("#" + t.hash)) { + const s = Ft("style"); + s.id = t.hash, s.textContent = t.code, n.appendChild(s); + } + }); +} +function jn(e) { + var t, r, n = ""; + if (typeof e == "string" || typeof e == "number") n += e; + else if (typeof e == "object") if (Array.isArray(e)) { + var s = e.length; + for (t = 0; t < s; t++) e[t] && (r = jn(e[t])) && (n && (n += " "), n += r); + } else for (r in e) e[r] && (n && (n += " "), n += r); + return n; +} +function Ci() { + for (var e, t, r = 0, n = "", s = arguments.length; r < s; r++) (e = arguments[r]) && (t = jn(e)) && (n && (n += " "), n += t); + return n; +} +function Ri(e) { + return typeof e == "object" ? Ci(e) : e ?? ""; +} +const Lr = [...` +\r\f \v\uFEFF`]; +function Li(e, t, r) { + var n = e == null ? "" : "" + e; + if (t && (n = n ? n + " " + t : t), r) { + for (var s of Object.keys(r)) + if (r[s]) + n = n ? n + " " + s : s; + else if (n.length) + for (var i = s.length, o = 0; (o = n.indexOf(s, o)) >= 0; ) { + var l = o + i; + (o === 0 || Lr.includes(n[o - 1])) && (l === n.length || Lr.includes(n[l])) ? n = (o === 0 ? "" : n.substring(0, o)) + n.substring(l + 1) : o = l; + } + } + return n === "" ? null : n; +} +function Hn(e, t, r, n, s, i) { + var o = e.__className; + if (N || o !== r || o === void 0) { + var l = Li(r, n, i); + (!N || l !== e.getAttribute("class")) && (l == null ? e.removeAttribute("class") : e.className = l), e.__className = r; + } else if (i && s !== i) + for (var f in i) { + var a = !!i[f]; + (s == null || a !== !!s[f]) && e.classList.toggle(f, a); + } + return i; +} +const Ii = Symbol("is custom element"), Di = Symbol("is html"), Pi = ks ? "link" : "LINK"; +function Fi(e, t, r, n) { + var s = zi(e); + N && (s[t] = e.getAttribute(t), e.nodeName === Pi) || s[t] !== (s[t] = r) && (r == null ? e.removeAttribute(t) : typeof r != "string" && ji(e).includes(t) ? e[t] = r : e.setAttribute(t, r)); +} +function zi(e) { + return ( + /** @type {Record} **/ + // @ts-expect-error + e.__attributes ??= { + [Ii]: e.nodeName.includes("-"), + [Di]: e.namespaceURI === zr + } + ); +} +var Ir = /* @__PURE__ */ new Map(); +function ji(e) { + var t = e.getAttribute("is") || e.nodeName, r = Ir.get(t); + if (r) return r; + Ir.set(t, r = []); + for (var n, s = e, i = Element.prototype; i !== s; ) { + n = ps(s); + for (var o in n) + n[o].set && r.push(o); + s = Hr(s); + } + return r; +} +function Dr(e, t) { + return e === t || e?.[vt] === t; +} +function qn(e = {}, t, r, n) { + var s = ( + /** @type {ComponentContext} */ + G.r + ), i = ( + /** @type {Effect} */ + y + ); + return hr(() => { + var o, l; + return dr(() => { + o = l, l = [], ft(() => { + e !== r(...l) && (t(e, ...l), o && Dr(r(...o), e) && t(null, ...o)); + }); + }), () => { + let f = i; + for (; f !== s && f.parent !== null && f.parent.f & qt; ) + f = f.parent; + const a = () => { + l && Dr(r(...l), e) && t(null, ...l); + }, u = f.teardown; + f.teardown = () => { + a(), u?.(); + }; + }; + }), e; +} +function We(e, t, r, n) { + var s = (r & ls) !== 0, i = (r & os) !== 0, o = ( + /** @type {V} */ + n + ), l = !0, f = () => (l && (l = !1, o = i ? ft( + /** @type {() => V} */ + n + ) : ( + /** @type {V} */ + n + )), o); + let a; + if (s) { + var u = vt in e || Ur in e; + a = qe(e, t)?.set ?? (u && t in e ? (g) => e[t] = g : void 0); + } + var c, d = !1; + s ? [c, d] = Bs(() => ( + /** @type {V} */ + e[t] + )) : c = /** @type {V} */ + e[t], c === void 0 && n !== void 0 && (c = f(), a && (Cs(), a(c))); + var v; + if (v = () => { + var g = ( + /** @type {V} */ + e[t] + ); + return g === void 0 ? f() : (l = !0, g); + }, !(r & is)) + return v; + if (a) { + var h = e.$$legacy; + return ( + /** @type {() => V} */ + function(g, C) { + return arguments.length > 0 ? ((!C || h || d) && a(C ? v() : g), g) : v(); + } + ); + } + var p = !1, _ = (r & ss ? Pt : fn)(() => (p = !1, v())); + s && b(_); + var $ = ( + /** @type {Effect} */ + y + ); + return ( + /** @type {() => V} */ + function(g, C) { + if (arguments.length > 0) { + const w = C ? b(_) : s ? je(g) : g; + return te(_, w), p = !0, o !== void 0 && (o = w), g; + } + return Me && p || $.f & Z ? _.v : b(_); + } + ); +} +function Hi(e) { + return new qi(e); +} +class qi { + /** @type {any} */ + #e; + /** @type {Record} */ + #n; + /** + * @param {ComponentConstructorOptions & { + * component: any; + * }} options + */ + constructor(t) { + var r = /* @__PURE__ */ new Map(), n = (i, o) => { + var l = /* @__PURE__ */ ar(o, !1, !1); + return r.set(i, l), l; + }; + const s = new Proxy( + { ...t.props || {}, $$events: {} }, + { + get(i, o) { + return b(r.get(o) ?? n(o, Reflect.get(i, o))); + }, + has(i, o) { + return o === Ur ? !0 : (b(r.get(o) ?? n(o, Reflect.get(i, o))), Reflect.has(i, o)); + }, + set(i, o, l) { + return te(r.get(o) ?? n(o, l), l), Reflect.set(i, o, l); + } + } + ); + this.#n = (t.hydrate ? mi : In)(t.component, { + target: t.target, + anchor: t.anchor, + props: s, + context: t.context, + intro: t.intro ?? !1, + recover: t.recover, + transformError: t.transformError + }), (!t?.props?.$$host || t.sync === !1) && Se(), this.#e = s.$$events; + for (const i of Object.keys(this.#n)) + i === "$set" || i === "$destroy" || i === "$on" || gt(this, i, { + get() { + return this.#n[i]; + }, + /** @param {any} value */ + set(o) { + this.#n[i] = o; + }, + enumerable: !0 + }); + this.#n.$set = /** @param {Record} next */ + (i) => { + Object.assign(s, i); + }, this.#n.$destroy = () => { + wi(this.#n); + }; + } + /** @param {Record} props */ + $set(t) { + this.#n.$set(t); + } + /** + * @param {string} event + * @param {(...args: any[]) => any} callback + * @returns {any} + */ + $on(t, r) { + this.#e[t] = this.#e[t] || []; + const n = (...s) => r.call(this, ...s); + return this.#e[t].push(n), () => { + this.#e[t] = this.#e[t].filter( + /** @param {any} fn */ + (s) => s !== n + ); + }; + } + $destroy() { + this.#n.$destroy(); + } +} +let Bn; +typeof HTMLElement == "function" && (Bn = class extends HTMLElement { + /** The Svelte component constructor */ + $$ctor; + /** Slots */ + $$s; + /** @type {any} The Svelte component instance */ + $$c; + /** Whether or not the custom element is connected */ + $$cn = !1; + /** @type {Record} Component props data */ + $$d = {}; + /** `true` if currently in the process of reflecting component props back to attributes */ + $$r = !1; + /** @type {Record} Props definition (name, reflected, type etc) */ + $$p_d = {}; + /** @type {Record} Event listeners */ + $$l = {}; + /** @type {Map} Event listener unsubscribe functions */ + $$l_u = /* @__PURE__ */ new Map(); + /** @type {any} The managed render effect for reflecting attributes */ + $$me; + /** @type {ShadowRoot | null} The ShadowRoot of the custom element */ + $$shadowRoot = null; + /** + * @param {*} $$componentCtor + * @param {*} $$slots + * @param {ShadowRootInit | undefined} shadow_root_init + */ + constructor(e, t, r) { + super(), this.$$ctor = e, this.$$s = t, r && (this.$$shadowRoot = this.attachShadow(r)); + } + /** + * @param {string} type + * @param {EventListenerOrEventListenerObject} listener + * @param {boolean | AddEventListenerOptions} [options] + */ + addEventListener(e, t, r) { + if (this.$$l[e] = this.$$l[e] || [], this.$$l[e].push(t), this.$$c) { + const n = this.$$c.$on(e, t); + this.$$l_u.set(t, n); + } + super.addEventListener(e, t, r); + } + /** + * @param {string} type + * @param {EventListenerOrEventListenerObject} listener + * @param {boolean | AddEventListenerOptions} [options] + */ + removeEventListener(e, t, r) { + if (super.removeEventListener(e, t, r), this.$$c) { + const n = this.$$l_u.get(t); + n && (n(), this.$$l_u.delete(t)); + } + } + async connectedCallback() { + if (this.$$cn = !0, !this.$$c) { + let e = function(n) { + return (s) => { + const i = Ft("slot"); + n !== "default" && (i.name = n), U(s, i); + }; + }; + if (await Promise.resolve(), !this.$$cn || this.$$c) + return; + const t = {}, r = Bi(this); + for (const n of this.$$s) + n in r && (n === "default" && !this.$$d.children ? (this.$$d.children = e(n), t.default = !0) : t[n] = e(n)); + for (const n of this.attributes) { + const s = this.$$g_p(n.name); + s in this.$$d || (this.$$d[s] = St(s, n.value, this.$$p_d, "toProp")); + } + for (const n in this.$$p_d) + !(n in this.$$d) && this[n] !== void 0 && (this.$$d[n] = this[n], delete this[n]); + this.$$c = Hi({ + component: this.$$ctor, + target: this.$$shadowRoot || this, + props: { + ...this.$$d, + $$slots: t, + $$host: this + } + }), this.$$me = si(() => { + dr(() => { + this.$$r = !0; + for (const n of At(this.$$c)) { + if (!this.$$p_d[n]?.reflect) continue; + this.$$d[n] = this.$$c[n]; + const s = St( + n, + this.$$d[n], + this.$$p_d, + "toAttribute" + ); + s == null ? this.removeAttribute(this.$$p_d[n].attribute || n) : this.setAttribute(this.$$p_d[n].attribute || n, s); + } + this.$$r = !1; + }); + }); + for (const n in this.$$l) + for (const s of this.$$l[n]) { + const i = this.$$c.$on(n, s); + this.$$l_u.set(s, i); + } + this.$$l = {}; + } + } + // We don't need this when working within Svelte code, but for compatibility of people using this outside of Svelte + // and setting attributes through setAttribute etc, this is helpful + /** + * @param {string} attr + * @param {string} _oldValue + * @param {string} newValue + */ + attributeChangedCallback(e, t, r) { + this.$$r || (e = this.$$g_p(e), this.$$d[e] = St(e, r, this.$$p_d, "toProp"), this.$$c?.$set({ [e]: this.$$d[e] })); + } + disconnectedCallback() { + this.$$cn = !1, Promise.resolve().then(() => { + !this.$$cn && this.$$c && (this.$$c.$destroy(), this.$$me(), this.$$c = void 0); + }); + } + /** + * @param {string} attribute_name + */ + $$g_p(e) { + return At(this.$$p_d).find( + (t) => this.$$p_d[t].attribute === e || !this.$$p_d[t].attribute && t.toLowerCase() === e + ) || e; + } +}); +function St(e, t, r, n) { + const s = r[e]?.type; + if (t = s === "Boolean" && typeof t != "boolean" ? t != null : t, !n || !r[e]) + return t; + if (n === "toAttribute") + switch (s) { + case "Object": + case "Array": + return t == null ? null : JSON.stringify(t); + case "Boolean": + return t ? "" : null; + case "Number": + return t ?? null; + default: + return t; + } + else + switch (s) { + case "Object": + case "Array": + return t && JSON.parse(t); + case "Boolean": + return t; + case "Number": + return t != null ? +t : t; + default: + return t; + } +} +function Bi(e) { + const t = {}; + return e.childNodes.forEach((r) => { + t[ + /** @type {Element} node */ + r.slot || "default" + ] = !0; + }), t; +} +function mr(e, t, r, n, s, i) { + let o = class extends Bn { + constructor() { + super(e, r, s), this.$$p_d = t; + } + static get observedAttributes() { + return At(t).map( + (l) => (t[l].attribute || l).toLowerCase() + ); + } + }; + return At(t).forEach((l) => { + gt(o.prototype, l, { + get() { + return this.$$c && l in this.$$c ? this.$$c[l] : this.$$d[l]; + }, + set(f) { + f = St(l, f, t), this.$$d[l] = f; + var a = this.$$c; + if (a) { + var u = qe(a, l)?.get; + u ? a[l] = f : a.$set({ [l]: f }); + } + } + }); + }), n.forEach((l) => { + gt(o.prototype, l, { + get() { + return this.$$c?.[l]; + } + }); + }), e.element = /** @type {any} */ + o, o; +} +const tt = rn(null), Un = rn({}), Ui = (e) => e; +function Vn(e) { + const t = e - 1; + return t * t * t + 1; +} +function Pr(e) { + const t = typeof e == "string" && e.match(/^\s*(-?[\d.]+)([^\s]*)\s*$/); + return t ? [parseFloat(t[1]), t[2] || "px"] : [ + /** @type {number} */ + e, + "px" + ]; +} +function Vi(e, { delay: t = 0, duration: r = 400, easing: n = Ui } = {}) { + const s = +getComputedStyle(e).opacity; + return { + delay: t, + duration: r, + easing: n, + css: (i) => `opacity: ${i * s}` + }; +} +function Yi(e, { delay: t = 0, duration: r = 400, easing: n = Vn, x: s = 0, y: i = 0, opacity: o = 0 } = {}) { + const l = getComputedStyle(e), f = +l.opacity, a = l.transform === "none" ? "" : l.transform, u = f * (1 - o), [c, d] = Pr(s), [v, h] = Pr(i); + return { + delay: t, + duration: r, + easing: n, + css: (p, _) => ` + transform: ${a} translate(${(1 - p) * c}${d}, ${(1 - p) * v}${h}); + opacity: ${f - u * _}` + }; +} +function Wi(e, { delay: t = 0, duration: r = 400, easing: n = Vn, start: s = 0, opacity: i = 0 } = {}) { + const o = getComputedStyle(e), l = +o.opacity, f = o.transform === "none" ? "" : o.transform, a = 1 - s, u = l * (1 - i); + return { + delay: t, + duration: r, + easing: n, + css: (c, d) => ` + transform: ${f} scale(${1 - a * d}); + opacity: ${l - u * d} + ` + }; +} +function Yn(e) { + const t = e - 1; + return t * t * t + 1; +} +var Gi = /* @__PURE__ */ ae(' '), Ki = /* @__PURE__ */ ae(' '), Ji = /* @__PURE__ */ ae(' '), Zi = /* @__PURE__ */ ae('
        1. '), Xi = /* @__PURE__ */ ae('
          Sources
            ', 1); +const Qi = { + hash: "svelte-3iukgs", + code: `:host {display:block;border-top:1px solid var(--line, #e5e7eb);background:var(--bg-soft, #f5f7fb);padding:12px 16px 14px;}:host(:not(:has(ol))) {display:none;}.src-h.svelte-3iukgs {font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:0.10em;color:var(--text-muted, #6b7280);margin:0 0 8px;}ol.svelte-3iukgs {margin:0;padding:0;list-style:none;display:grid;gap:6px;font-size:11.5px;line-height:1.45;}li.svelte-3iukgs {display:grid;grid-template-columns:22px 1fr;gap:8px;align-items:baseline;padding:4px 6px;border-radius:3px;cursor:pointer;transition:background 0.15s;}li.svelte-3iukgs:hover, li.hl.svelte-3iukgs {background:rgba(22, 66, 223, 0.10);}li.hl.svelte-3iukgs { + /* Brief pulse each time a chip selects this row. */ + animation: svelte-3iukgs-pulse 360ms cubic-bezier(.2,.7,.3,1);} + @keyframes svelte-3iukgs-pulse { + 0% { box-shadow: 0 0 0 0 rgba(22, 66, 223, 0.35); } + 60% { box-shadow: 0 0 0 6px rgba(22, 66, 223, 0.00); } + 100% { box-shadow: 0 0 0 0 rgba(22, 66, 223, 0.00); } + }.src-num.svelte-3iukgs {font-family:var(--mono, monospace);font-size:10.5px;font-weight:700;color:var(--nyc-blue, #1642DF);text-align:right;}.src-link.svelte-3iukgs {color:var(--text, #111);text-decoration:none;border-bottom:1px dotted var(--text-muted, #6b7280);}.src-link.svelte-3iukgs:hover {color:var(--nyc-blue, #1642DF);border-bottom-color:var(--nyc-blue, #1642DF);}.src-ext.svelte-3iukgs {font-size:9.5px;color:var(--text-faint, #9ca3af);margin-left:2px;vertical-align:super;}.src-vintage.svelte-3iukgs {display:block;color:var(--text-muted, #6b7280);font-size:9.5px;margin-top:2px;}.src-id.svelte-3iukgs {display:inline-block;font-family:var(--mono, monospace);font-size:9.5px;color:var(--text-faint, #9ca3af);margin-left:6px;}` +}; +function el(e, t) { + It(t, !0), br(e, Qi); + const r = () => Vt(Un, "$citeIndex", s), n = () => Vt(tt, "$highlightedDocId", s), [s, i] = nn(); + let o = We(t, "labels", 23, () => ({})), l = We(t, "urls", 23, () => ({})), f = We(t, "vintages", 23, () => ({})), a = /* @__PURE__ */ Le(() => Object.entries(r() || {}).sort((_, $) => _[1] - $[1])), u = /* @__PURE__ */ Le(n); + var c = { + get labels() { + return o(); + }, + set labels(_ = {}) { + o(_), Se(); + }, + get urls() { + return l(); + }, + set urls(_ = {}) { + l(_), Se(); + }, + get vintages() { + return f(); + }, + set vintages(_ = {}) { + f(_), Se(); + } + }, d = Ln(), v = Kt(d); + { + var h = (_) => { + var $ = Xi(), g = Kt($), C = $e(g, 2); + Pn(C, 21, () => b(a), ([w, m]) => w, (w, m) => { + var T = /* @__PURE__ */ Le(() => ws(b(m), 2)); + let M = () => b(T)[0], E = () => b(T)[1]; + const L = /* @__PURE__ */ Le(() => l()[M()]), q = /* @__PURE__ */ Le(() => o()[M()] || M()), O = /* @__PURE__ */ Le(() => f()[M()]); + var k = Zi(); + let I; + var X = B(k), Wn = B(X); + F(X); + var wr = $e(X, 2), yr = B(wr); + { + var Gn = (pe) => { + var K = Gi(), ut = B(K); + Vr(), F(K), Te(() => { + Fi(K, "href", b(L)), fe(ut, `${b(q) ?? ""} `); + }), Nr("click", K, (Qn) => Qn.stopPropagation()), U(pe, K); + }, Kn = (pe) => { + var K = Ki(), ut = B(K, !0); + F(K), Te(() => fe(ut, b(q))), U(pe, K); + }; + Ye(yr, (pe) => { + b(L) ? pe(Gn) : pe(Kn, -1); + }); + } + var zt = $e(yr, 2), Jn = B(zt, !0); + F(zt); + var Zn = $e(zt, 2); + { + var Xn = (pe) => { + var K = Ji(), ut = B(K, !0); + F(K), Te(() => fe(ut, b(O))), U(pe, K); + }; + Ye(Zn, (pe) => { + b(O) && pe(Xn); + }); + } + F(wr), F(k), Te(() => { + I = Hn(k, 1, "svelte-3iukgs", null, I, { hl: M() === b(u) }), fe(Wn, `[${E() ?? ""}]`), fe(Jn, M()); + }), hi("mouseenter", k, () => tt.set(M())), Nr("click", k, () => tt.set(b(u) === M() ? null : M())), tr(1, k, () => Wi, () => ({ start: 0.96, duration: 220, easing: Yn })), U(w, k); + }), F(C), tr(1, g, () => Vi, () => ({ duration: 200 })), U(_, $); + }; + Ye(v, (_) => { + b(a).length && _(h); + }); + } + U(e, d); + var p = Dt(c); + return i(), p; +} +di(["click"]); +customElements.define("r-sources-footer", mr( + el, + { + labels: { type: "Object" }, + urls: { type: "Object" }, + vintages: { type: "Object" } + }, + [], + [], + { mode: "open" } +)); +var tl = /* @__PURE__ */ ae('
            Waiting for content…
            '), rl = /* @__PURE__ */ ae('
            '); +const nl = { + hash: "svelte-5ir0b", + code: `:host {display:block;} + /* The host-level styles for typography, .cite, etc. live in the parent + stylesheet and target #paragraph descendants — they pierce shadow DOM + for inline-styled markup we don't ship here. The .rsum-* classes are + wired in the global stylesheet. We intentionally don't restate them. */:host(.streaming)::after, + :host([streaming])::after {content:"▋";display:inline-block;color:var(--nyc-blue, #1642DF);margin-left:2px; + animation: svelte-5ir0b-caret 0.9s steps(1) infinite;} + @keyframes svelte-5ir0b-caret { 50% { opacity: 0; } }` +}; +function sl(e, t) { + It(t, !0), br(e, nl); + const r = () => Vt(tt, "$highlightedDocId", n), [n, s] = nn(); + let i = We(t, "text", 7, ""), o = We(t, "streaming", 7, !1), l = We(t, "sourceLabels", 23, () => ({})); + const f = (w) => String(w ?? "").replace(/&/g, "&").replace(//g, ">"); + function a(w) { + const m = w.split(` +`), T = []; + let M = [], E = []; + const L = () => { + if (!M.length) return; + const k = f(M.join(" ").trim()).replace(/\*\*([^*]+)\*\*/g, "$1"); + k && T.push(`

            ${k}

            `), M = []; + }, q = () => { + if (!E.length) return; + const k = E.map((I) => `
          1. ${f(I.trim()).replace(/\*\*([^*]+)\*\*/g, "$1")}
          2. `).join(""); + T.push(`
              ${k}
            `), E = []; + }, O = []; + for (const k of m) + if (k.trim().startsWith("- ") && k.includes(" - ", 2)) { + const I = k.split(/(?:^|(?<=\.\s))\s*-\s+/g).filter((X) => X.trim()); + for (const X of I) O.push("- " + X.trim()); + } else + O.push(k); + for (const k of O) { + const I = k.match(/^\s*\*\*([A-Z][A-Za-z\s/]+)\.\*\*\s*$/); + I ? (L(), q(), T.push(`

            ${f(I[1])}

            `)) : /^\s*[-*]\s+/.test(k) ? (L(), E.push(k.replace(/^\s*[-*]\s+/, ""))) : (q(), M.push(k)); + } + return L(), q(), T.join(""); + } + function u(w, m) { + return w.replace(/\[([a-z0-9_]+)\]/gi, (T, M) => { + const E = M.toLowerCase(); + m[E] == null && (m[E] = Object.keys(m).length + 1); + const L = m[E], q = l()[E] || E; + return `${L}`; + }); + } + let c = /* @__PURE__ */ Le(() => { + if (!i()) return ""; + const w = {}, m = a(i()), T = u(m, w); + return queueMicrotask(() => Un.set({ ...w })), T; + }), d, v = /* @__PURE__ */ Le(r); + mn(() => { + b(c), b(v), d && ui().then(() => { + d.querySelectorAll(".cite").forEach((m) => { + const T = m.dataset.srcId; + T && (m.classList.toggle("hl", T === b(v)), !m.dataset.bound && (m.dataset.bound = "1", m.addEventListener("mouseenter", () => tt.set(T)), m.addEventListener("click", (M) => { + M.stopPropagation(), tt.update((E) => E === T ? null : T); + }))); + }); + }); + }); + var h = { + get text() { + return i(); + }, + set text(w = "") { + i(w), Se(); + }, + get streaming() { + return o(); + }, + set streaming(w = !1) { + o(w), Se(); + }, + get sourceLabels() { + return l(); + }, + set sourceLabels(w = {}) { + l(w), Se(); + } + }, p = Ln(), _ = Kt(p); + { + var $ = (w) => { + var m = tl(); + U(w, m); + }, g = (w) => { + var m = rl(); + Si(m, () => b(c), !0), F(m), qn(m, (T) => d = T, () => d), U(w, m); + }; + Ye(_, (w) => { + i() ? w(g, -1) : w($); + }); + } + U(e, p); + var C = Dt(h); + return s(), C; +} +customElements.define("r-briefing", mr( + sl, + { + text: { type: "String" }, + streaming: { reflect: !0, type: "Boolean" }, + sourceLabels: { type: "Object" } + }, + [], + [], + { mode: "open" } +)); +var il = /* @__PURE__ */ ae(' '), ll = /* @__PURE__ */ ae('
            '), ol = /* @__PURE__ */ ae('
            '), al = /* @__PURE__ */ ae('
          3. '), fl = /* @__PURE__ */ ae('
              '); +const ul = { + hash: "svelte-c4g9ik", + code: ":host {display:block;}ol.svelte-c4g9ik {list-style:none;margin:0;padding:4px 0;font-size:12.5px;}li.svelte-c4g9ik {display:grid;grid-template-columns:18px 1fr auto;gap:10px;padding:7px 14px;border-bottom:1px solid var(--line, #e5e7eb);align-items:baseline;}li.svelte-c4g9ik:last-child {border-bottom:0;}.icon.svelte-c4g9ik {font-weight:700;font-size:14px;line-height:1;}.running.svelte-c4g9ik .icon:where(.svelte-c4g9ik) {color:var(--nyc-blue, #1642DF);}.ok.svelte-c4g9ik .icon:where(.svelte-c4g9ik) {color:var(--good, #1a8754);}.err.svelte-c4g9ik .icon:where(.svelte-c4g9ik) {color:var(--nyc-scarlet, #b80000);}.label.svelte-c4g9ik {color:var(--text, #111);font-weight:500;}.meta.svelte-c4g9ik {color:var(--text-muted, #6b7280);font-size:11px;}.time.svelte-c4g9ik {font-family:var(--mono, monospace);color:var(--text-faint, #9ca3af);font-size:11.5px;}.running.svelte-c4g9ik {background:rgba(22, 66, 223, 0.04);}.result.svelte-c4g9ik {grid-column:2 / -1;color:var(--text-muted, #6b7280);font-size:11px;font-family:var(--mono, monospace);margin-top:3px;word-break:break-word;line-height:1.4;}" +}; +function cl(e, t) { + It(t, !0), br(e, ul); + let r = We(t, "stepLabels", 23, () => ({})), n = /* @__PURE__ */ me(je([])); + $i(() => { + const c = s?.getRootNode()?.host; + c && (c.pushStep = (d) => { + te(n, [...b(n), d], !0); + }, c.clear = () => { + te(n, [], !0); + }); + }); + let s; + function i(c) { + return c.ok === !0 ? "ok" : c.ok === !1 ? "err" : "running"; + } + function o(c) { + return c.ok === !0 ? "✓" : c.ok === !1 ? "✗" : "○"; + } + function l(c) { + return r()[c.step] && r()[c.step][0] || c.step; + } + function f(c) { + return r()[c.step] && r()[c.step][1] || ""; + } + var a = { + get stepLabels() { + return r(); + }, + set stepLabels(c = {}) { + r(c), Se(); + } + }, u = fl(); + return Pn(u, 21, () => b(n), ki, (c, d) => { + var v = al(), h = B(v), p = B(h, !0); + F(h); + var _ = $e(h, 2), $ = B(_), g = B($, !0); + F($); + var C = $e($, 2), w = B(C, !0); + F(C), F(_); + var m = $e(_, 2); + { + var T = (O) => { + var k = il(), I = B(k); + F(k), Te(() => fe(I, `${b(d).elapsed_s ?? ""}s`)), U(O, k); + }; + Ye(m, (O) => { + b(d).elapsed_s != null && O(T); + }); + } + var M = $e(m, 2); + { + var E = (O) => { + var k = ll(), I = B(k, !0); + F(k), Te((X) => fe(I, X), [() => JSON.stringify(b(d).result)]), U(O, k); + }; + Ye(M, (O) => { + b(d).result && O(E); + }); + } + var L = $e(M, 2); + { + var q = (O) => { + var k = ol(), I = B(k, !0); + F(k), Te(() => fe(I, b(d).err)), U(O, k); + }; + Ye(L, (O) => { + b(d).err && O(q); + }); + } + F(v), Te( + (O, k, I, X) => { + Hn(v, 1, O, "svelte-c4g9ik"), fe(p, k), fe(g, I), fe(w, X); + }, + [ + () => Ri(i(b(d))), + () => o(b(d)), + () => l(b(d)), + () => f(b(d)) + ] + ), tr(1, v, () => Yi, () => ({ y: -8, duration: 220, easing: Yn })), U(c, v); + }), F(u), qn(u, (c) => s = c, () => s), U(e, u), Dt(a); +} +customElements.define("r-trace", mr(cl, { stepLabels: { type: "Object" } }, [], [], { mode: "open" })); +export { + Un as citeIndex, + tt as highlightedDocId +}; +//# sourceMappingURL=riprap.js.map diff --git a/web/static/dist/riprap.js.map b/web/static/dist/riprap.js.map new file mode 100644 index 0000000000000000000000000000000000000000..2bbbb343a095476ba5f1614e9495d3ad40e8d749 --- /dev/null +++ b/web/static/dist/riprap.js.map @@ -0,0 +1 @@ +{"version":3,"file":"riprap.js","sources":["../../svelte/node_modules/svelte/src/version.js","../../svelte/node_modules/svelte/src/internal/disclose-version.js","../../svelte/node_modules/svelte/src/constants.js","../../svelte/node_modules/esm-env/false.js","../../svelte/node_modules/svelte/src/internal/shared/utils.js","../../svelte/node_modules/svelte/src/internal/client/constants.js","../../svelte/node_modules/svelte/src/internal/shared/errors.js","../../svelte/node_modules/svelte/src/internal/client/errors.js","../../svelte/node_modules/svelte/src/internal/client/warnings.js","../../svelte/node_modules/svelte/src/internal/client/dom/hydration.js","../../svelte/node_modules/svelte/src/internal/client/reactivity/equality.js","../../svelte/node_modules/svelte/src/internal/flags/index.js","../../svelte/node_modules/svelte/src/internal/client/context.js","../../svelte/node_modules/svelte/src/internal/client/dom/task.js","../../svelte/node_modules/svelte/src/internal/client/error-handling.js","../../svelte/node_modules/svelte/src/internal/client/reactivity/status.js","../../svelte/node_modules/svelte/src/internal/client/reactivity/utils.js","../../svelte/node_modules/svelte/src/store/utils.js","../../svelte/node_modules/svelte/src/store/shared/index.js","../../svelte/node_modules/svelte/src/internal/client/reactivity/store.js","../../svelte/node_modules/svelte/src/internal/client/reactivity/batch.js","../../svelte/node_modules/svelte/src/reactivity/create-subscriber.js","../../svelte/node_modules/svelte/src/internal/client/dom/blocks/boundary.js","../../svelte/node_modules/svelte/src/internal/client/reactivity/async.js","../../svelte/node_modules/svelte/src/internal/client/reactivity/deriveds.js","../../svelte/node_modules/svelte/src/internal/client/reactivity/sources.js","../../svelte/node_modules/svelte/src/internal/client/proxy.js","../../svelte/node_modules/svelte/src/internal/client/dom/operations.js","../../svelte/node_modules/svelte/src/internal/client/dom/elements/bindings/shared.js","../../svelte/node_modules/svelte/src/internal/client/reactivity/effects.js","../../svelte/node_modules/svelte/src/internal/client/runtime.js","../../svelte/node_modules/svelte/src/internal/client/dom/elements/events.js","../../svelte/node_modules/svelte/src/internal/client/dom/reconciler.js","../../svelte/node_modules/svelte/src/internal/client/dom/template.js","../../svelte/node_modules/svelte/src/utils.js","../../svelte/node_modules/svelte/src/internal/client/render.js","../../svelte/node_modules/svelte/src/internal/client/dom/blocks/branches.js","../../svelte/node_modules/svelte/src/index-client.js","../../svelte/node_modules/svelte/src/internal/client/dom/blocks/if.js","../../svelte/node_modules/svelte/src/internal/client/dom/blocks/each.js","../../svelte/node_modules/svelte/src/internal/client/dom/blocks/html.js","../../svelte/node_modules/svelte/src/internal/client/timing.js","../../svelte/node_modules/svelte/src/internal/client/loop.js","../../svelte/node_modules/svelte/src/internal/client/dom/elements/transitions.js","../../svelte/node_modules/svelte/src/internal/client/dom/css.js","../../svelte/node_modules/clsx/dist/clsx.mjs","../../svelte/node_modules/svelte/src/internal/shared/attributes.js","../../svelte/node_modules/svelte/src/internal/client/dom/elements/class.js","../../svelte/node_modules/svelte/src/internal/client/dom/elements/attributes.js","../../svelte/node_modules/svelte/src/internal/client/dom/elements/bindings/this.js","../../svelte/node_modules/svelte/src/internal/client/reactivity/props.js","../../svelte/node_modules/svelte/src/legacy/legacy-client.js","../../svelte/node_modules/svelte/src/internal/client/dom/elements/custom-element.js","../../svelte/src/lib/stores.js","../../svelte/node_modules/svelte/src/transition/index.js","../../svelte/node_modules/svelte/src/easing/index.js","../../svelte/src/lib/SourcesFooter.svelte","../../svelte/src/lib/Briefing.svelte","../../svelte/src/lib/Trace.svelte"],"sourcesContent":["// generated during release, do not modify\n\n/**\n * The current version, as set in package.json.\n * @type {string}\n */\nexport const VERSION = '5.55.5';\nexport const PUBLIC_VERSION = '5';\n","import { PUBLIC_VERSION } from '../version.js';\n\nif (typeof window !== 'undefined') {\n\t// @ts-expect-error\n\t((window.__svelte ??= {}).v ??= new Set()).add(PUBLIC_VERSION);\n}\n","export const EACH_ITEM_REACTIVE = 1;\nexport const EACH_INDEX_REACTIVE = 1 << 1;\n/** See EachBlock interface metadata.is_controlled for an explanation what this is */\nexport const EACH_IS_CONTROLLED = 1 << 2;\nexport const EACH_IS_ANIMATED = 1 << 3;\nexport const EACH_ITEM_IMMUTABLE = 1 << 4;\n\nexport const PROPS_IS_IMMUTABLE = 1;\nexport const PROPS_IS_RUNES = 1 << 1;\nexport const PROPS_IS_UPDATED = 1 << 2;\nexport const PROPS_IS_BINDABLE = 1 << 3;\nexport const PROPS_IS_LAZY_INITIAL = 1 << 4;\n\nexport const TRANSITION_IN = 1;\nexport const TRANSITION_OUT = 1 << 1;\nexport const TRANSITION_GLOBAL = 1 << 2;\n\nexport const TEMPLATE_FRAGMENT = 1;\nexport const TEMPLATE_USE_IMPORT_NODE = 1 << 1;\nexport const TEMPLATE_USE_SVG = 1 << 2;\nexport const TEMPLATE_USE_MATHML = 1 << 3;\n\nexport const HYDRATION_START = '[';\n/** used to indicate that an `{:else}...` block was rendered */\nexport const HYDRATION_START_ELSE = '[!';\n/** used to indicate that a boundary's `failed` snippet was rendered on the server */\nexport const HYDRATION_START_FAILED = '[?';\nexport const HYDRATION_END = ']';\nexport const HYDRATION_ERROR = {};\n\nexport const ELEMENT_IS_NAMESPACED = 1;\nexport const ELEMENT_PRESERVE_ATTRIBUTE_CASE = 1 << 1;\nexport const ELEMENT_IS_INPUT = 1 << 2;\n\nexport const UNINITIALIZED = Symbol();\n\n// Dev-time component properties\nexport const FILENAME = Symbol('filename');\nexport const HMR = Symbol('hmr');\n\nexport const NAMESPACE_HTML = 'http://www.w3.org/1999/xhtml';\nexport const NAMESPACE_SVG = 'http://www.w3.org/2000/svg';\nexport const NAMESPACE_MATHML = 'http://www.w3.org/1998/Math/MathML';\n\n// we use a list of ignorable runtime warnings because not every runtime warning\n// can be ignored and we want to keep the validation for svelte-ignore in place\nexport const IGNORABLE_RUNTIME_WARNINGS = /** @type {const} */ ([\n\t'await_waterfall',\n\t'await_reactivity_loss',\n\t'state_snapshot_uncloneable',\n\t'binding_property_non_reactive',\n\t'hydration_attribute_changed',\n\t'hydration_html_changed',\n\t'ownership_invalid_binding',\n\t'ownership_invalid_mutation'\n]);\n\n/**\n * Whitespace inside one of these elements will not result in\n * a whitespace node being created in any circumstances. (This\n * list is almost certainly very incomplete)\n * TODO this is currently unused\n */\nexport const ELEMENTS_WITHOUT_TEXT = ['audio', 'datalist', 'dl', 'optgroup', 'select', 'video'];\n\nexport const ATTACHMENT_KEY = '@attach';\n","export default false;\n","// Store the references to globals in case someone tries to monkey patch these, causing the below\n// to de-opt (this occurs often when using popular extensions).\nexport var is_array = Array.isArray;\nexport var index_of = Array.prototype.indexOf;\nexport var includes = Array.prototype.includes;\nexport var array_from = Array.from;\nexport var object_keys = Object.keys;\nexport var define_property = Object.defineProperty;\nexport var get_descriptor = Object.getOwnPropertyDescriptor;\nexport var get_descriptors = Object.getOwnPropertyDescriptors;\nexport var object_prototype = Object.prototype;\nexport var array_prototype = Array.prototype;\nexport var get_prototype_of = Object.getPrototypeOf;\nexport var is_extensible = Object.isExtensible;\nexport var has_own_property = Object.prototype.hasOwnProperty;\n\n/**\n * @param {any} thing\n * @returns {thing is Function}\n */\nexport function is_function(thing) {\n\treturn typeof thing === 'function';\n}\n\nexport const noop = () => {};\n\n// Adapted from https://github.com/then/is-promise/blob/master/index.js\n// Distributed under MIT License https://github.com/then/is-promise/blob/master/LICENSE\n\n/**\n * @template [T=any]\n * @param {any} value\n * @returns {value is PromiseLike}\n */\nexport function is_promise(value) {\n\treturn typeof value?.then === 'function';\n}\n\n/** @param {Function} fn */\nexport function run(fn) {\n\treturn fn();\n}\n\n/** @param {Array<() => void>} arr */\nexport function run_all(arr) {\n\tfor (var i = 0; i < arr.length; i++) {\n\t\tarr[i]();\n\t}\n}\n\n/**\n * TODO replace with Promise.withResolvers once supported widely enough\n * @template [T=void]\n */\nexport function deferred() {\n\t/** @type {(value: T) => void} */\n\tvar resolve;\n\n\t/** @type {(reason: any) => void} */\n\tvar reject;\n\n\t/** @type {Promise} */\n\tvar promise = new Promise((res, rej) => {\n\t\tresolve = res;\n\t\treject = rej;\n\t});\n\n\t// @ts-expect-error\n\treturn { promise, resolve, reject };\n}\n\n/**\n * @template V\n * @param {V} value\n * @param {V | (() => V)} fallback\n * @param {boolean} [lazy]\n * @returns {V}\n */\nexport function fallback(value, fallback, lazy = false) {\n\treturn value === undefined\n\t\t? lazy\n\t\t\t? /** @type {() => V} */ (fallback)()\n\t\t\t: /** @type {V} */ (fallback)\n\t\t: value;\n}\n\n/**\n * When encountering a situation like `let [a, b, c] = $derived(blah())`,\n * we need to stash an intermediate value that `a`, `b`, and `c` derive\n * from, in case it's an iterable\n * @template T\n * @param {ArrayLike | Iterable} value\n * @param {number} [n]\n * @returns {Array}\n */\nexport function to_array(value, n) {\n\t// return arrays unchanged\n\tif (Array.isArray(value)) {\n\t\treturn value;\n\t}\n\n\t// if value is not iterable, or `n` is unspecified (indicates a rest\n\t// element, which means we're not concerned about unbounded iterables)\n\t// convert to an array with `Array.from`\n\tif (n === undefined || !(Symbol.iterator in value)) {\n\t\treturn Array.from(value);\n\t}\n\n\t// otherwise, populate an array with `n` values\n\n\t/** @type {T[]} */\n\tconst array = [];\n\n\tfor (const element of value) {\n\t\tarray.push(element);\n\t\tif (array.length === n) break;\n\t}\n\n\treturn array;\n}\n\n/**\n * @param {Record} obj\n * @param {Array} keys\n * @returns {Record}\n */\nexport function exclude_from_object(obj, keys) {\n\t/** @type {Record} */\n\tvar result = {};\n\n\tfor (var key in obj) {\n\t\tif (!keys.includes(key)) {\n\t\t\tresult[key] = obj[key];\n\t\t}\n\t}\n\n\tfor (var symbol of Object.getOwnPropertySymbols(obj)) {\n\t\tif (Object.propertyIsEnumerable.call(obj, symbol) && !keys.includes(symbol)) {\n\t\t\tresult[symbol] = obj[symbol];\n\t\t}\n\t}\n\n\treturn result;\n}\n","// General flags\nexport const DERIVED = 1 << 1;\nexport const EFFECT = 1 << 2;\nexport const RENDER_EFFECT = 1 << 3;\n/**\n * An effect that does not destroy its child effects when it reruns.\n * Runs as part of render effects, i.e. not eagerly as part of tree traversal or effect flushing.\n */\nexport const MANAGED_EFFECT = 1 << 24;\n/**\n * An effect that does not destroy its child effects when it reruns (like MANAGED_EFFECT).\n * Runs eagerly as part of tree traversal or effect flushing.\n */\nexport const BLOCK_EFFECT = 1 << 4;\nexport const BRANCH_EFFECT = 1 << 5;\nexport const ROOT_EFFECT = 1 << 6;\nexport const BOUNDARY_EFFECT = 1 << 7;\n/**\n * Indicates that a reaction is connected to an effect root — either it is an effect,\n * or it is a derived that is depended on by at least one effect. If a derived has\n * no dependents, we can disconnect it from the graph, allowing it to either be\n * GC'd or reconnected later if an effect comes to depend on it again\n */\nexport const CONNECTED = 1 << 9;\nexport const CLEAN = 1 << 10;\nexport const DIRTY = 1 << 11;\nexport const MAYBE_DIRTY = 1 << 12;\nexport const INERT = 1 << 13;\nexport const DESTROYED = 1 << 14;\n/** Set once a reaction has run for the first time */\nexport const REACTION_RAN = 1 << 15;\n/** Effect is in the process of getting destroyed. Can be observed in child teardown functions */\nexport const DESTROYING = 1 << 25;\n\n// Flags exclusive to effects\n/**\n * 'Transparent' effects do not create a transition boundary.\n * This is on a block effect 99% of the time but may also be on a branch effect if its parent block effect was pruned\n */\nexport const EFFECT_TRANSPARENT = 1 << 16;\nexport const EAGER_EFFECT = 1 << 17;\nexport const HEAD_EFFECT = 1 << 18;\nexport const EFFECT_PRESERVED = 1 << 19;\nexport const USER_EFFECT = 1 << 20;\nexport const EFFECT_OFFSCREEN = 1 << 25;\n\n// Flags exclusive to deriveds\n/**\n * Tells that we marked this derived and its reactions as visited during the \"mark as (maybe) dirty\"-phase.\n * Will be lifted during execution of the derived and during checking its dirty state (both are necessary\n * because a derived might be checked but not executed). This is a pure performance optimization flag and\n * should not be used for any other purpose!\n */\nexport const WAS_MARKED = 1 << 16;\n\n// Flags used for async\nexport const REACTION_IS_UPDATING = 1 << 21;\nexport const ASYNC = 1 << 22;\n\nexport const ERROR_VALUE = 1 << 23;\n\nexport const STATE_SYMBOL = Symbol('$state');\nexport const LEGACY_PROPS = Symbol('legacy props');\nexport const LOADING_ATTR_SYMBOL = Symbol('');\nexport const PROXY_PATH_SYMBOL = Symbol('proxy path');\n/** An anchor might change, via this symbol on the original anchor we can tell HMR about the updated anchor */\nexport const HMR_ANCHOR = Symbol('hmr anchor');\n\n/** allow users to ignore aborted signal errors if `reason.name === 'StaleReactionError` */\nexport const STALE_REACTION = new (class StaleReactionError extends Error {\n\tname = 'StaleReactionError';\n\tmessage = 'The reaction that called `getAbortSignal()` was re-run or destroyed';\n})();\n\nexport const IS_XHTML =\n\t// We gotta write it like this because after downleveling the pure comment may end up in the wrong location\n\t!!globalThis.document?.contentType &&\n\t/* @__PURE__ */ globalThis.document.contentType.includes('xml');\nexport const ELEMENT_NODE = 1;\nexport const TEXT_NODE = 3;\nexport const COMMENT_NODE = 8;\nexport const DOCUMENT_FRAGMENT_NODE = 11;\n","/* This file is generated by scripts/process-messages/index.js. Do not edit! */\n\nimport { DEV } from 'esm-env';\n\n/**\n * Cannot use `%name%(...)` unless the `experimental.async` compiler option is `true`\n * @param {string} name\n * @returns {never}\n */\nexport function experimental_async_required(name) {\n\tif (DEV) {\n\t\tconst error = new Error(`experimental_async_required\\nCannot use \\`${name}(...)\\` unless the \\`experimental.async\\` compiler option is \\`true\\`\\nhttps://svelte.dev/e/experimental_async_required`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/experimental_async_required`);\n\t}\n}\n\n/**\n * Cannot use `{@render children(...)}` if the parent component uses `let:` directives. Consider using a named snippet instead\n * @returns {never}\n */\nexport function invalid_default_snippet() {\n\tif (DEV) {\n\t\tconst error = new Error(`invalid_default_snippet\\nCannot use \\`{@render children(...)}\\` if the parent component uses \\`let:\\` directives. Consider using a named snippet instead\\nhttps://svelte.dev/e/invalid_default_snippet`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/invalid_default_snippet`);\n\t}\n}\n\n/**\n * A snippet function was passed invalid arguments. Snippets should only be instantiated via `{@render ...}`\n * @returns {never}\n */\nexport function invalid_snippet_arguments() {\n\tif (DEV) {\n\t\tconst error = new Error(`invalid_snippet_arguments\\nA snippet function was passed invalid arguments. Snippets should only be instantiated via \\`{@render ...}\\`\\nhttps://svelte.dev/e/invalid_snippet_arguments`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/invalid_snippet_arguments`);\n\t}\n}\n\n/**\n * An invariant violation occurred, meaning Svelte's internal assumptions were flawed. This is a bug in Svelte, not your app — please open an issue at https://github.com/sveltejs/svelte, citing the following message: \"%message%\"\n * @param {string} message\n * @returns {never}\n */\nexport function invariant_violation(message) {\n\tif (DEV) {\n\t\tconst error = new Error(`invariant_violation\\nAn invariant violation occurred, meaning Svelte's internal assumptions were flawed. This is a bug in Svelte, not your app — please open an issue at https://github.com/sveltejs/svelte, citing the following message: \"${message}\"\\nhttps://svelte.dev/e/invariant_violation`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/invariant_violation`);\n\t}\n}\n\n/**\n * `%name%(...)` can only be used during component initialisation\n * @param {string} name\n * @returns {never}\n */\nexport function lifecycle_outside_component(name) {\n\tif (DEV) {\n\t\tconst error = new Error(`lifecycle_outside_component\\n\\`${name}(...)\\` can only be used during component initialisation\\nhttps://svelte.dev/e/lifecycle_outside_component`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/lifecycle_outside_component`);\n\t}\n}\n\n/**\n * Context was not set in a parent component\n * @returns {never}\n */\nexport function missing_context() {\n\tif (DEV) {\n\t\tconst error = new Error(`missing_context\\nContext was not set in a parent component\\nhttps://svelte.dev/e/missing_context`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/missing_context`);\n\t}\n}\n\n/**\n * Attempted to render a snippet without a `{@render}` block. This would cause the snippet code to be stringified instead of its content being rendered to the DOM. To fix this, change `{snippet}` to `{@render snippet()}`.\n * @returns {never}\n */\nexport function snippet_without_render_tag() {\n\tif (DEV) {\n\t\tconst error = new Error(`snippet_without_render_tag\\nAttempted to render a snippet without a \\`{@render}\\` block. This would cause the snippet code to be stringified instead of its content being rendered to the DOM. To fix this, change \\`{snippet}\\` to \\`{@render snippet()}\\`.\\nhttps://svelte.dev/e/snippet_without_render_tag`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/snippet_without_render_tag`);\n\t}\n}\n\n/**\n * `%name%` is not a store with a `subscribe` method\n * @param {string} name\n * @returns {never}\n */\nexport function store_invalid_shape(name) {\n\tif (DEV) {\n\t\tconst error = new Error(`store_invalid_shape\\n\\`${name}\\` is not a store with a \\`subscribe\\` method\\nhttps://svelte.dev/e/store_invalid_shape`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/store_invalid_shape`);\n\t}\n}\n\n/**\n * The `this` prop on `` must be a string, if defined\n * @returns {never}\n */\nexport function svelte_element_invalid_this_value() {\n\tif (DEV) {\n\t\tconst error = new Error(`svelte_element_invalid_this_value\\nThe \\`this\\` prop on \\`\\` must be a string, if defined\\nhttps://svelte.dev/e/svelte_element_invalid_this_value`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/svelte_element_invalid_this_value`);\n\t}\n}","/* This file is generated by scripts/process-messages/index.js. Do not edit! */\n\nimport { DEV } from 'esm-env';\n\nexport * from '../shared/errors.js';\n\n/**\n * Cannot create a `$derived(...)` with an `await` expression outside of an effect tree\n * @returns {never}\n */\nexport function async_derived_orphan() {\n\tif (DEV) {\n\t\tconst error = new Error(`async_derived_orphan\\nCannot create a \\`$derived(...)\\` with an \\`await\\` expression outside of an effect tree\\nhttps://svelte.dev/e/async_derived_orphan`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/async_derived_orphan`);\n\t}\n}\n\n/**\n * Using `bind:value` together with a checkbox input is not allowed. Use `bind:checked` instead\n * @returns {never}\n */\nexport function bind_invalid_checkbox_value() {\n\tif (DEV) {\n\t\tconst error = new Error(`bind_invalid_checkbox_value\\nUsing \\`bind:value\\` together with a checkbox input is not allowed. Use \\`bind:checked\\` instead\\nhttps://svelte.dev/e/bind_invalid_checkbox_value`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/bind_invalid_checkbox_value`);\n\t}\n}\n\n/**\n * Component %component% has an export named `%key%` that a consumer component is trying to access using `bind:%key%`, which is disallowed. Instead, use `bind:this` (e.g. `<%name% bind:this={component} />`) and then access the property on the bound component instance (e.g. `component.%key%`)\n * @param {string} component\n * @param {string} key\n * @param {string} name\n * @returns {never}\n */\nexport function bind_invalid_export(component, key, name) {\n\tif (DEV) {\n\t\tconst error = new Error(`bind_invalid_export\\nComponent ${component} has an export named \\`${key}\\` that a consumer component is trying to access using \\`bind:${key}\\`, which is disallowed. Instead, use \\`bind:this\\` (e.g. \\`<${name} bind:this={component} />\\`) and then access the property on the bound component instance (e.g. \\`component.${key}\\`)\\nhttps://svelte.dev/e/bind_invalid_export`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/bind_invalid_export`);\n\t}\n}\n\n/**\n * A component is attempting to bind to a non-bindable property `%key%` belonging to %component% (i.e. `<%name% bind:%key%={...}>`). To mark a property as bindable: `let { %key% = $bindable() } = $props()`\n * @param {string} key\n * @param {string} component\n * @param {string} name\n * @returns {never}\n */\nexport function bind_not_bindable(key, component, name) {\n\tif (DEV) {\n\t\tconst error = new Error(`bind_not_bindable\\nA component is attempting to bind to a non-bindable property \\`${key}\\` belonging to ${component} (i.e. \\`<${name} bind:${key}={...}>\\`). To mark a property as bindable: \\`let { ${key} = $bindable() } = $props()\\`\\nhttps://svelte.dev/e/bind_not_bindable`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/bind_not_bindable`);\n\t}\n}\n\n/**\n * Calling `%method%` on a component instance (of %component%) is no longer valid in Svelte 5\n * @param {string} method\n * @param {string} component\n * @returns {never}\n */\nexport function component_api_changed(method, component) {\n\tif (DEV) {\n\t\tconst error = new Error(`component_api_changed\\nCalling \\`${method}\\` on a component instance (of ${component}) is no longer valid in Svelte 5\\nhttps://svelte.dev/e/component_api_changed`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/component_api_changed`);\n\t}\n}\n\n/**\n * Attempted to instantiate %component% with `new %name%`, which is no longer valid in Svelte 5. If this component is not under your control, set the `compatibility.componentApi` compiler option to `4` to keep it working.\n * @param {string} component\n * @param {string} name\n * @returns {never}\n */\nexport function component_api_invalid_new(component, name) {\n\tif (DEV) {\n\t\tconst error = new Error(`component_api_invalid_new\\nAttempted to instantiate ${component} with \\`new ${name}\\`, which is no longer valid in Svelte 5. If this component is not under your control, set the \\`compatibility.componentApi\\` compiler option to \\`4\\` to keep it working.\\nhttps://svelte.dev/e/component_api_invalid_new`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/component_api_invalid_new`);\n\t}\n}\n\n/**\n * A derived value cannot reference itself recursively\n * @returns {never}\n */\nexport function derived_references_self() {\n\tif (DEV) {\n\t\tconst error = new Error(`derived_references_self\\nA derived value cannot reference itself recursively\\nhttps://svelte.dev/e/derived_references_self`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/derived_references_self`);\n\t}\n}\n\n/**\n * Keyed each block has duplicate key `%value%` at indexes %a% and %b%\n * @param {string} a\n * @param {string} b\n * @param {string | undefined | null} [value]\n * @returns {never}\n */\nexport function each_key_duplicate(a, b, value) {\n\tif (DEV) {\n\t\tconst error = new Error(`each_key_duplicate\\n${value\n\t\t\t? `Keyed each block has duplicate key \\`${value}\\` at indexes ${a} and ${b}`\n\t\t\t: `Keyed each block has duplicate key at indexes ${a} and ${b}`}\\nhttps://svelte.dev/e/each_key_duplicate`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/each_key_duplicate`);\n\t}\n}\n\n/**\n * Keyed each block has key that is not idempotent — the key for item at index %index% was `%a%` but is now `%b%`. Keys must be the same each time for a given item\n * @param {string} index\n * @param {string} a\n * @param {string} b\n * @returns {never}\n */\nexport function each_key_volatile(index, a, b) {\n\tif (DEV) {\n\t\tconst error = new Error(`each_key_volatile\\nKeyed each block has key that is not idempotent — the key for item at index ${index} was \\`${a}\\` but is now \\`${b}\\`. Keys must be the same each time for a given item\\nhttps://svelte.dev/e/each_key_volatile`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/each_key_volatile`);\n\t}\n}\n\n/**\n * `%rune%` cannot be used inside an effect cleanup function\n * @param {string} rune\n * @returns {never}\n */\nexport function effect_in_teardown(rune) {\n\tif (DEV) {\n\t\tconst error = new Error(`effect_in_teardown\\n\\`${rune}\\` cannot be used inside an effect cleanup function\\nhttps://svelte.dev/e/effect_in_teardown`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/effect_in_teardown`);\n\t}\n}\n\n/**\n * Effect cannot be created inside a `$derived` value that was not itself created inside an effect\n * @returns {never}\n */\nexport function effect_in_unowned_derived() {\n\tif (DEV) {\n\t\tconst error = new Error(`effect_in_unowned_derived\\nEffect cannot be created inside a \\`$derived\\` value that was not itself created inside an effect\\nhttps://svelte.dev/e/effect_in_unowned_derived`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/effect_in_unowned_derived`);\n\t}\n}\n\n/**\n * `%rune%` can only be used inside an effect (e.g. during component initialisation)\n * @param {string} rune\n * @returns {never}\n */\nexport function effect_orphan(rune) {\n\tif (DEV) {\n\t\tconst error = new Error(`effect_orphan\\n\\`${rune}\\` can only be used inside an effect (e.g. during component initialisation)\\nhttps://svelte.dev/e/effect_orphan`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/effect_orphan`);\n\t}\n}\n\n/**\n * `$effect.pending()` can only be called inside an effect or derived\n * @returns {never}\n */\nexport function effect_pending_outside_reaction() {\n\tif (DEV) {\n\t\tconst error = new Error(`effect_pending_outside_reaction\\n\\`$effect.pending()\\` can only be called inside an effect or derived\\nhttps://svelte.dev/e/effect_pending_outside_reaction`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/effect_pending_outside_reaction`);\n\t}\n}\n\n/**\n * Maximum update depth exceeded. This typically indicates that an effect reads and writes the same piece of state\n * @returns {never}\n */\nexport function effect_update_depth_exceeded() {\n\tif (DEV) {\n\t\tconst error = new Error(`effect_update_depth_exceeded\\nMaximum update depth exceeded. This typically indicates that an effect reads and writes the same piece of state\\nhttps://svelte.dev/e/effect_update_depth_exceeded`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/effect_update_depth_exceeded`);\n\t}\n}\n\n/**\n * Cannot use `flushSync` inside an effect\n * @returns {never}\n */\nexport function flush_sync_in_effect() {\n\tif (DEV) {\n\t\tconst error = new Error(`flush_sync_in_effect\\nCannot use \\`flushSync\\` inside an effect\\nhttps://svelte.dev/e/flush_sync_in_effect`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/flush_sync_in_effect`);\n\t}\n}\n\n/**\n * Cannot commit a fork that was already discarded\n * @returns {never}\n */\nexport function fork_discarded() {\n\tif (DEV) {\n\t\tconst error = new Error(`fork_discarded\\nCannot commit a fork that was already discarded\\nhttps://svelte.dev/e/fork_discarded`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/fork_discarded`);\n\t}\n}\n\n/**\n * Cannot create a fork inside an effect or when state changes are pending\n * @returns {never}\n */\nexport function fork_timing() {\n\tif (DEV) {\n\t\tconst error = new Error(`fork_timing\\nCannot create a fork inside an effect or when state changes are pending\\nhttps://svelte.dev/e/fork_timing`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/fork_timing`);\n\t}\n}\n\n/**\n * `getAbortSignal()` can only be called inside an effect or derived\n * @returns {never}\n */\nexport function get_abort_signal_outside_reaction() {\n\tif (DEV) {\n\t\tconst error = new Error(`get_abort_signal_outside_reaction\\n\\`getAbortSignal()\\` can only be called inside an effect or derived\\nhttps://svelte.dev/e/get_abort_signal_outside_reaction`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/get_abort_signal_outside_reaction`);\n\t}\n}\n\n/**\n * Expected to find a hydratable with key `%key%` during hydration, but did not.\n * @param {string} key\n * @returns {never}\n */\nexport function hydratable_missing_but_required(key) {\n\tif (DEV) {\n\t\tconst error = new Error(`hydratable_missing_but_required\\nExpected to find a hydratable with key \\`${key}\\` during hydration, but did not.\\nhttps://svelte.dev/e/hydratable_missing_but_required`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/hydratable_missing_but_required`);\n\t}\n}\n\n/**\n * Failed to hydrate the application\n * @returns {never}\n */\nexport function hydration_failed() {\n\tif (DEV) {\n\t\tconst error = new Error(`hydration_failed\\nFailed to hydrate the application\\nhttps://svelte.dev/e/hydration_failed`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/hydration_failed`);\n\t}\n}\n\n/**\n * Could not `{@render}` snippet due to the expression being `null` or `undefined`. Consider using optional chaining `{@render snippet?.()}`\n * @returns {never}\n */\nexport function invalid_snippet() {\n\tif (DEV) {\n\t\tconst error = new Error(`invalid_snippet\\nCould not \\`{@render}\\` snippet due to the expression being \\`null\\` or \\`undefined\\`. Consider using optional chaining \\`{@render snippet?.()}\\`\\nhttps://svelte.dev/e/invalid_snippet`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/invalid_snippet`);\n\t}\n}\n\n/**\n * `%name%(...)` cannot be used in runes mode\n * @param {string} name\n * @returns {never}\n */\nexport function lifecycle_legacy_only(name) {\n\tif (DEV) {\n\t\tconst error = new Error(`lifecycle_legacy_only\\n\\`${name}(...)\\` cannot be used in runes mode\\nhttps://svelte.dev/e/lifecycle_legacy_only`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/lifecycle_legacy_only`);\n\t}\n}\n\n/**\n * Cannot do `bind:%key%={undefined}` when `%key%` has a fallback value\n * @param {string} key\n * @returns {never}\n */\nexport function props_invalid_value(key) {\n\tif (DEV) {\n\t\tconst error = new Error(`props_invalid_value\\nCannot do \\`bind:${key}={undefined}\\` when \\`${key}\\` has a fallback value\\nhttps://svelte.dev/e/props_invalid_value`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/props_invalid_value`);\n\t}\n}\n\n/**\n * Rest element properties of `$props()` such as `%property%` are readonly\n * @param {string} property\n * @returns {never}\n */\nexport function props_rest_readonly(property) {\n\tif (DEV) {\n\t\tconst error = new Error(`props_rest_readonly\\nRest element properties of \\`$props()\\` such as \\`${property}\\` are readonly\\nhttps://svelte.dev/e/props_rest_readonly`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/props_rest_readonly`);\n\t}\n}\n\n/**\n * The `%rune%` rune is only available inside `.svelte` and `.svelte.js/ts` files\n * @param {string} rune\n * @returns {never}\n */\nexport function rune_outside_svelte(rune) {\n\tif (DEV) {\n\t\tconst error = new Error(`rune_outside_svelte\\nThe \\`${rune}\\` rune is only available inside \\`.svelte\\` and \\`.svelte.js/ts\\` files\\nhttps://svelte.dev/e/rune_outside_svelte`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/rune_outside_svelte`);\n\t}\n}\n\n/**\n * `setContext` must be called when a component first initializes, not in a subsequent effect or after an `await` expression\n * @returns {never}\n */\nexport function set_context_after_init() {\n\tif (DEV) {\n\t\tconst error = new Error(`set_context_after_init\\n\\`setContext\\` must be called when a component first initializes, not in a subsequent effect or after an \\`await\\` expression\\nhttps://svelte.dev/e/set_context_after_init`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/set_context_after_init`);\n\t}\n}\n\n/**\n * Property descriptors defined on `$state` objects must contain `value` and always be `enumerable`, `configurable` and `writable`.\n * @returns {never}\n */\nexport function state_descriptors_fixed() {\n\tif (DEV) {\n\t\tconst error = new Error(`state_descriptors_fixed\\nProperty descriptors defined on \\`$state\\` objects must contain \\`value\\` and always be \\`enumerable\\`, \\`configurable\\` and \\`writable\\`.\\nhttps://svelte.dev/e/state_descriptors_fixed`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/state_descriptors_fixed`);\n\t}\n}\n\n/**\n * Cannot set prototype of `$state` object\n * @returns {never}\n */\nexport function state_prototype_fixed() {\n\tif (DEV) {\n\t\tconst error = new Error(`state_prototype_fixed\\nCannot set prototype of \\`$state\\` object\\nhttps://svelte.dev/e/state_prototype_fixed`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/state_prototype_fixed`);\n\t}\n}\n\n/**\n * Updating state inside `$derived(...)`, `$inspect(...)` or a template expression is forbidden. If the value should not be reactive, declare it without `$state`\n * @returns {never}\n */\nexport function state_unsafe_mutation() {\n\tif (DEV) {\n\t\tconst error = new Error(`state_unsafe_mutation\\nUpdating state inside \\`$derived(...)\\`, \\`$inspect(...)\\` or a template expression is forbidden. If the value should not be reactive, declare it without \\`$state\\`\\nhttps://svelte.dev/e/state_unsafe_mutation`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/state_unsafe_mutation`);\n\t}\n}\n\n/**\n * A `` `reset` function cannot be called while an error is still being handled\n * @returns {never}\n */\nexport function svelte_boundary_reset_onerror() {\n\tif (DEV) {\n\t\tconst error = new Error(`svelte_boundary_reset_onerror\\nA \\`\\` \\`reset\\` function cannot be called while an error is still being handled\\nhttps://svelte.dev/e/svelte_boundary_reset_onerror`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/svelte_boundary_reset_onerror`);\n\t}\n}","/* This file is generated by scripts/process-messages/index.js. Do not edit! */\n\nimport { DEV } from 'esm-env';\n\nvar bold = 'font-weight: bold';\nvar normal = 'font-weight: normal';\n\n/**\n * Assignment to `%property%` property (%location%) will evaluate to the right-hand side, not the value of `%property%` following the assignment. This may result in unexpected behaviour.\n * @param {string} property\n * @param {string} location\n */\nexport function assignment_value_stale(property, location) {\n\tif (DEV) {\n\t\tconsole.warn(`%c[svelte] assignment_value_stale\\n%cAssignment to \\`${property}\\` property (${location}) will evaluate to the right-hand side, not the value of \\`${property}\\` following the assignment. This may result in unexpected behaviour.\\nhttps://svelte.dev/e/assignment_value_stale`, bold, normal);\n\t} else {\n\t\tconsole.warn(`https://svelte.dev/e/assignment_value_stale`);\n\t}\n}\n\n/**\n * Detected reactivity loss when reading `%name%`. This happens when state is read in an async function after an earlier `await`\n * @param {string} name\n */\nexport function await_reactivity_loss(name) {\n\tif (DEV) {\n\t\tconsole.warn(`%c[svelte] await_reactivity_loss\\n%cDetected reactivity loss when reading \\`${name}\\`. This happens when state is read in an async function after an earlier \\`await\\`\\nhttps://svelte.dev/e/await_reactivity_loss`, bold, normal);\n\t} else {\n\t\tconsole.warn(`https://svelte.dev/e/await_reactivity_loss`);\n\t}\n}\n\n/**\n * An async derived, `%name%` (%location%) was not read immediately after it resolved. This often indicates an unnecessary waterfall, which can slow down your app\n * @param {string} name\n * @param {string} location\n */\nexport function await_waterfall(name, location) {\n\tif (DEV) {\n\t\tconsole.warn(`%c[svelte] await_waterfall\\n%cAn async derived, \\`${name}\\` (${location}) was not read immediately after it resolved. This often indicates an unnecessary waterfall, which can slow down your app\\nhttps://svelte.dev/e/await_waterfall`, bold, normal);\n\t} else {\n\t\tconsole.warn(`https://svelte.dev/e/await_waterfall`);\n\t}\n}\n\n/**\n * `%binding%` (%location%) is binding to a non-reactive property\n * @param {string} binding\n * @param {string | undefined | null} [location]\n */\nexport function binding_property_non_reactive(binding, location) {\n\tif (DEV) {\n\t\tconsole.warn(\n\t\t\t`%c[svelte] binding_property_non_reactive\\n%c${location\n\t\t\t\t? `\\`${binding}\\` (${location}) is binding to a non-reactive property`\n\t\t\t\t: `\\`${binding}\\` is binding to a non-reactive property`}\\nhttps://svelte.dev/e/binding_property_non_reactive`,\n\t\t\tbold,\n\t\t\tnormal\n\t\t);\n\t} else {\n\t\tconsole.warn(`https://svelte.dev/e/binding_property_non_reactive`);\n\t}\n}\n\n/**\n * Your `console.%method%` contained `$state` proxies. Consider using `$inspect(...)` or `$state.snapshot(...)` instead\n * @param {string} method\n */\nexport function console_log_state(method) {\n\tif (DEV) {\n\t\tconsole.warn(`%c[svelte] console_log_state\\n%cYour \\`console.${method}\\` contained \\`$state\\` proxies. Consider using \\`$inspect(...)\\` or \\`$state.snapshot(...)\\` instead\\nhttps://svelte.dev/e/console_log_state`, bold, normal);\n\t} else {\n\t\tconsole.warn(`https://svelte.dev/e/console_log_state`);\n\t}\n}\n\n/**\n * Reading a derived belonging to a now-destroyed effect may result in stale values\n */\nexport function derived_inert() {\n\tif (DEV) {\n\t\tconsole.warn(`%c[svelte] derived_inert\\n%cReading a derived belonging to a now-destroyed effect may result in stale values\\nhttps://svelte.dev/e/derived_inert`, bold, normal);\n\t} else {\n\t\tconsole.warn(`https://svelte.dev/e/derived_inert`);\n\t}\n}\n\n/**\n * %handler% should be a function. Did you mean to %suggestion%?\n * @param {string} handler\n * @param {string} suggestion\n */\nexport function event_handler_invalid(handler, suggestion) {\n\tif (DEV) {\n\t\tconsole.warn(`%c[svelte] event_handler_invalid\\n%c${handler} should be a function. Did you mean to ${suggestion}?\\nhttps://svelte.dev/e/event_handler_invalid`, bold, normal);\n\t} else {\n\t\tconsole.warn(`https://svelte.dev/e/event_handler_invalid`);\n\t}\n}\n\n/**\n * Expected to find a hydratable with key `%key%` during hydration, but did not.\n * @param {string} key\n */\nexport function hydratable_missing_but_expected(key) {\n\tif (DEV) {\n\t\tconsole.warn(`%c[svelte] hydratable_missing_but_expected\\n%cExpected to find a hydratable with key \\`${key}\\` during hydration, but did not.\\nhttps://svelte.dev/e/hydratable_missing_but_expected`, bold, normal);\n\t} else {\n\t\tconsole.warn(`https://svelte.dev/e/hydratable_missing_but_expected`);\n\t}\n}\n\n/**\n * The `%attribute%` attribute on `%html%` changed its value between server and client renders. The client value, `%value%`, will be ignored in favour of the server value\n * @param {string} attribute\n * @param {string} html\n * @param {string} value\n */\nexport function hydration_attribute_changed(attribute, html, value) {\n\tif (DEV) {\n\t\tconsole.warn(`%c[svelte] hydration_attribute_changed\\n%cThe \\`${attribute}\\` attribute on \\`${html}\\` changed its value between server and client renders. The client value, \\`${value}\\`, will be ignored in favour of the server value\\nhttps://svelte.dev/e/hydration_attribute_changed`, bold, normal);\n\t} else {\n\t\tconsole.warn(`https://svelte.dev/e/hydration_attribute_changed`);\n\t}\n}\n\n/**\n * The value of an `{@html ...}` block %location% changed between server and client renders. The client value will be ignored in favour of the server value\n * @param {string | undefined | null} [location]\n */\nexport function hydration_html_changed(location) {\n\tif (DEV) {\n\t\tconsole.warn(\n\t\t\t`%c[svelte] hydration_html_changed\\n%c${location\n\t\t\t\t? `The value of an \\`{@html ...}\\` block ${location} changed between server and client renders. The client value will be ignored in favour of the server value`\n\t\t\t\t: 'The value of an `{@html ...}` block changed between server and client renders. The client value will be ignored in favour of the server value'}\\nhttps://svelte.dev/e/hydration_html_changed`,\n\t\t\tbold,\n\t\t\tnormal\n\t\t);\n\t} else {\n\t\tconsole.warn(`https://svelte.dev/e/hydration_html_changed`);\n\t}\n}\n\n/**\n * Hydration failed because the initial UI does not match what was rendered on the server. The error occurred near %location%\n * @param {string | undefined | null} [location]\n */\nexport function hydration_mismatch(location) {\n\tif (DEV) {\n\t\tconsole.warn(\n\t\t\t`%c[svelte] hydration_mismatch\\n%c${location\n\t\t\t\t? `Hydration failed because the initial UI does not match what was rendered on the server. The error occurred near ${location}`\n\t\t\t\t: 'Hydration failed because the initial UI does not match what was rendered on the server'}\\nhttps://svelte.dev/e/hydration_mismatch`,\n\t\t\tbold,\n\t\t\tnormal\n\t\t);\n\t} else {\n\t\tconsole.warn(`https://svelte.dev/e/hydration_mismatch`);\n\t}\n}\n\n/**\n * The `render` function passed to `createRawSnippet` should return HTML for a single element\n */\nexport function invalid_raw_snippet_render() {\n\tif (DEV) {\n\t\tconsole.warn(`%c[svelte] invalid_raw_snippet_render\\n%cThe \\`render\\` function passed to \\`createRawSnippet\\` should return HTML for a single element\\nhttps://svelte.dev/e/invalid_raw_snippet_render`, bold, normal);\n\t} else {\n\t\tconsole.warn(`https://svelte.dev/e/invalid_raw_snippet_render`);\n\t}\n}\n\n/**\n * Detected a migrated `$:` reactive block in `%filename%` that both accesses and updates the same reactive value. This may cause recursive updates when converted to an `$effect`.\n * @param {string} filename\n */\nexport function legacy_recursive_reactive_block(filename) {\n\tif (DEV) {\n\t\tconsole.warn(`%c[svelte] legacy_recursive_reactive_block\\n%cDetected a migrated \\`$:\\` reactive block in \\`${filename}\\` that both accesses and updates the same reactive value. This may cause recursive updates when converted to an \\`$effect\\`.\\nhttps://svelte.dev/e/legacy_recursive_reactive_block`, bold, normal);\n\t} else {\n\t\tconsole.warn(`https://svelte.dev/e/legacy_recursive_reactive_block`);\n\t}\n}\n\n/**\n * Tried to unmount a component that was not mounted\n */\nexport function lifecycle_double_unmount() {\n\tif (DEV) {\n\t\tconsole.warn(`%c[svelte] lifecycle_double_unmount\\n%cTried to unmount a component that was not mounted\\nhttps://svelte.dev/e/lifecycle_double_unmount`, bold, normal);\n\t} else {\n\t\tconsole.warn(`https://svelte.dev/e/lifecycle_double_unmount`);\n\t}\n}\n\n/**\n * %parent% passed property `%prop%` to %child% with `bind:`, but its parent component %owner% did not declare `%prop%` as a binding. Consider creating a binding between %owner% and %parent% (e.g. `bind:%prop%={...}` instead of `%prop%={...}`)\n * @param {string} parent\n * @param {string} prop\n * @param {string} child\n * @param {string} owner\n */\nexport function ownership_invalid_binding(parent, prop, child, owner) {\n\tif (DEV) {\n\t\tconsole.warn(`%c[svelte] ownership_invalid_binding\\n%c${parent} passed property \\`${prop}\\` to ${child} with \\`bind:\\`, but its parent component ${owner} did not declare \\`${prop}\\` as a binding. Consider creating a binding between ${owner} and ${parent} (e.g. \\`bind:${prop}={...}\\` instead of \\`${prop}={...}\\`)\\nhttps://svelte.dev/e/ownership_invalid_binding`, bold, normal);\n\t} else {\n\t\tconsole.warn(`https://svelte.dev/e/ownership_invalid_binding`);\n\t}\n}\n\n/**\n * Mutating unbound props (`%name%`, at %location%) is strongly discouraged. Consider using `bind:%prop%={...}` in %parent% (or using a callback) instead\n * @param {string} name\n * @param {string} location\n * @param {string} prop\n * @param {string} parent\n */\nexport function ownership_invalid_mutation(name, location, prop, parent) {\n\tif (DEV) {\n\t\tconsole.warn(`%c[svelte] ownership_invalid_mutation\\n%cMutating unbound props (\\`${name}\\`, at ${location}) is strongly discouraged. Consider using \\`bind:${prop}={...}\\` in ${parent} (or using a callback) instead\\nhttps://svelte.dev/e/ownership_invalid_mutation`, bold, normal);\n\t} else {\n\t\tconsole.warn(`https://svelte.dev/e/ownership_invalid_mutation`);\n\t}\n}\n\n/**\n * The `value` property of a `\\` element should be an array, but it received a non-array value. The selection will be kept as is.\\nhttps://svelte.dev/e/select_multiple_invalid_value`, bold, normal);\n\t} else {\n\t\tconsole.warn(`https://svelte.dev/e/select_multiple_invalid_value`);\n\t}\n}\n\n/**\n * Reactive `$state(...)` proxies and the values they proxy have different identities. Because of this, comparisons with `%operator%` will produce unexpected results\n * @param {string} operator\n */\nexport function state_proxy_equality_mismatch(operator) {\n\tif (DEV) {\n\t\tconsole.warn(`%c[svelte] state_proxy_equality_mismatch\\n%cReactive \\`$state(...)\\` proxies and the values they proxy have different identities. Because of this, comparisons with \\`${operator}\\` will produce unexpected results\\nhttps://svelte.dev/e/state_proxy_equality_mismatch`, bold, normal);\n\t} else {\n\t\tconsole.warn(`https://svelte.dev/e/state_proxy_equality_mismatch`);\n\t}\n}\n\n/**\n * Tried to unmount a state proxy, rather than a component\n */\nexport function state_proxy_unmount() {\n\tif (DEV) {\n\t\tconsole.warn(`%c[svelte] state_proxy_unmount\\n%cTried to unmount a state proxy, rather than a component\\nhttps://svelte.dev/e/state_proxy_unmount`, bold, normal);\n\t} else {\n\t\tconsole.warn(`https://svelte.dev/e/state_proxy_unmount`);\n\t}\n}\n\n/**\n * A `` `reset` function only resets the boundary the first time it is called\n */\nexport function svelte_boundary_reset_noop() {\n\tif (DEV) {\n\t\tconsole.warn(`%c[svelte] svelte_boundary_reset_noop\\n%cA \\`\\` \\`reset\\` function only resets the boundary the first time it is called\\nhttps://svelte.dev/e/svelte_boundary_reset_noop`, bold, normal);\n\t} else {\n\t\tconsole.warn(`https://svelte.dev/e/svelte_boundary_reset_noop`);\n\t}\n}\n\n/**\n * The `slide` transition does not work correctly for elements with `display: %value%`\n * @param {string} value\n */\nexport function transition_slide_display(value) {\n\tif (DEV) {\n\t\tconsole.warn(`%c[svelte] transition_slide_display\\n%cThe \\`slide\\` transition does not work correctly for elements with \\`display: ${value}\\`\\nhttps://svelte.dev/e/transition_slide_display`, bold, normal);\n\t} else {\n\t\tconsole.warn(`https://svelte.dev/e/transition_slide_display`);\n\t}\n}","/** @import { TemplateNode } from '#client' */\n\nimport { COMMENT_NODE } from '#client/constants';\nimport {\n\tHYDRATION_END,\n\tHYDRATION_ERROR,\n\tHYDRATION_START,\n\tHYDRATION_START_ELSE\n} from '../../../constants.js';\nimport * as w from '../warnings.js';\nimport { get_next_sibling } from './operations.js';\n\n/**\n * Use this variable to guard everything related to hydration code so it can be treeshaken out\n * if the user doesn't use the `hydrate` method and these code paths are therefore not needed.\n */\nexport let hydrating = false;\n\n/** @param {boolean} value */\nexport function set_hydrating(value) {\n\thydrating = value;\n}\n\n/**\n * The node that is currently being hydrated. This starts out as the first node inside the opening\n * comment, and updates each time a component calls `$.child(...)` or `$.sibling(...)`.\n * When entering a block (e.g. `{#if ...}`), `hydrate_node` is the block opening comment; by the\n * time we leave the block it is the closing comment, which serves as the block's anchor.\n * @type {TemplateNode}\n */\nexport let hydrate_node;\n\n/** @param {TemplateNode | null} node */\nexport function set_hydrate_node(node) {\n\tif (node === null) {\n\t\tw.hydration_mismatch();\n\t\tthrow HYDRATION_ERROR;\n\t}\n\n\treturn (hydrate_node = node);\n}\n\nexport function hydrate_next() {\n\treturn set_hydrate_node(get_next_sibling(hydrate_node));\n}\n\n/** @param {TemplateNode} node */\nexport function reset(node) {\n\tif (!hydrating) return;\n\n\t// If the node has remaining siblings, something has gone wrong\n\tif (get_next_sibling(hydrate_node) !== null) {\n\t\tw.hydration_mismatch();\n\t\tthrow HYDRATION_ERROR;\n\t}\n\n\thydrate_node = node;\n}\n\n/**\n * @param {HTMLTemplateElement} template\n */\nexport function hydrate_template(template) {\n\tif (hydrating) {\n\t\t// @ts-expect-error TemplateNode doesn't include DocumentFragment, but it's actually fine\n\t\thydrate_node = template.content;\n\t}\n}\n\nexport function next(count = 1) {\n\tif (hydrating) {\n\t\tvar i = count;\n\t\tvar node = hydrate_node;\n\n\t\twhile (i--) {\n\t\t\tnode = /** @type {TemplateNode} */ (get_next_sibling(node));\n\t\t}\n\n\t\thydrate_node = node;\n\t}\n}\n\n/**\n * Skips or removes (depending on {@link remove}) all nodes starting at `hydrate_node` up until the next hydration end comment\n * @param {boolean} remove\n */\nexport function skip_nodes(remove = true) {\n\tvar depth = 0;\n\tvar node = hydrate_node;\n\n\twhile (true) {\n\t\tif (node.nodeType === COMMENT_NODE) {\n\t\t\tvar data = /** @type {Comment} */ (node).data;\n\n\t\t\tif (data === HYDRATION_END) {\n\t\t\t\tif (depth === 0) return node;\n\t\t\t\tdepth -= 1;\n\t\t\t} else if (\n\t\t\t\tdata === HYDRATION_START ||\n\t\t\t\tdata === HYDRATION_START_ELSE ||\n\t\t\t\t// \"[1\", \"[2\", etc. for if blocks\n\t\t\t\t(data[0] === '[' && !isNaN(Number(data.slice(1))))\n\t\t\t) {\n\t\t\t\tdepth += 1;\n\t\t\t}\n\t\t}\n\n\t\tvar next = /** @type {TemplateNode} */ (get_next_sibling(node));\n\t\tif (remove) node.remove();\n\t\tnode = next;\n\t}\n}\n\n/**\n *\n * @param {TemplateNode} node\n */\nexport function read_hydration_instruction(node) {\n\tif (!node || node.nodeType !== COMMENT_NODE) {\n\t\tw.hydration_mismatch();\n\t\tthrow HYDRATION_ERROR;\n\t}\n\n\treturn /** @type {Comment} */ (node).data;\n}\n","/** @import { Equals } from '#client' */\n\n/** @type {Equals} */\nexport function equals(value) {\n\treturn value === this.v;\n}\n\n/**\n * @param {unknown} a\n * @param {unknown} b\n * @returns {boolean}\n */\nexport function safe_not_equal(a, b) {\n\treturn a != a\n\t\t? b == b\n\t\t: a !== b || (a !== null && typeof a === 'object') || typeof a === 'function';\n}\n\n/**\n * @param {unknown} a\n * @param {unknown} b\n * @returns {boolean}\n */\nexport function not_equal(a, b) {\n\treturn a !== b;\n}\n\n/** @type {Equals} */\nexport function safe_equals(value) {\n\treturn !safe_not_equal(value, this.v);\n}\n","/** True if experimental.async=true */\nexport let async_mode_flag = false;\n/** True if we're not certain that we only have Svelte 5 code in the compilation */\nexport let legacy_mode_flag = false;\n/** True if $inspect.trace is used */\nexport let tracing_mode_flag = false;\n\nexport function enable_async_mode_flag() {\n\tasync_mode_flag = true;\n}\n\n/** ONLY USE THIS DURING TESTING */\nexport function disable_async_mode_flag() {\n\tasync_mode_flag = false;\n}\n\nexport function enable_legacy_mode_flag() {\n\tlegacy_mode_flag = true;\n}\n\nexport function enable_tracing_mode_flag() {\n\ttracing_mode_flag = true;\n}\n","/** @import { ComponentContext, DevStackEntry, Effect } from '#client' */\nimport { DEV } from 'esm-env';\nimport * as e from './errors.js';\nimport { active_effect, active_reaction } from './runtime.js';\nimport { create_user_effect } from './reactivity/effects.js';\nimport { async_mode_flag, legacy_mode_flag } from '../flags/index.js';\nimport { FILENAME } from '../../constants.js';\nimport { BRANCH_EFFECT } from './constants.js';\n\n/** @type {ComponentContext | null} */\nexport let component_context = null;\n\n/** @param {ComponentContext | null} context */\nexport function set_component_context(context) {\n\tcomponent_context = context;\n}\n\n/** @type {DevStackEntry | null} */\nexport let dev_stack = null;\n\n/** @param {DevStackEntry | null} stack */\nexport function set_dev_stack(stack) {\n\tdev_stack = stack;\n}\n\n/**\n * Execute a callback with a new dev stack entry\n * @param {() => any} callback - Function to execute\n * @param {DevStackEntry['type']} type - Type of block/component\n * @param {any} component - Component function\n * @param {number} line - Line number\n * @param {number} column - Column number\n * @param {Record} [additional] - Any additional properties to add to the dev stack entry\n * @returns {any}\n */\nexport function add_svelte_meta(callback, type, component, line, column, additional) {\n\tconst parent = dev_stack;\n\n\tdev_stack = {\n\t\ttype,\n\t\tfile: component[FILENAME],\n\t\tline,\n\t\tcolumn,\n\t\tparent,\n\t\t...additional\n\t};\n\n\ttry {\n\t\treturn callback();\n\t} finally {\n\t\tdev_stack = parent;\n\t}\n}\n\n/**\n * The current component function. Different from current component context:\n * ```html\n * \n * \n * \n * \n * ```\n * @type {ComponentContext['function']}\n */\nexport let dev_current_component_function = null;\n\n/** @param {ComponentContext['function']} fn */\nexport function set_dev_current_component_function(fn) {\n\tdev_current_component_function = fn;\n}\n\n/**\n * Returns a `[get, set]` pair of functions for working with context in a type-safe way.\n *\n * `get` will throw an error if no parent component called `set`.\n *\n * @template T\n * @returns {[() => T, (context: T) => T]}\n * @since 5.40.0\n */\nexport function createContext() {\n\tconst key = {};\n\n\treturn [\n\t\t() => {\n\t\t\tif (!hasContext(key)) {\n\t\t\t\te.missing_context();\n\t\t\t}\n\n\t\t\treturn getContext(key);\n\t\t},\n\t\t(context) => setContext(key, context)\n\t];\n}\n\n/**\n * Retrieves the context that belongs to the closest parent component with the specified `key`.\n * Must be called during component initialisation.\n *\n * [`createContext`](https://svelte.dev/docs/svelte/svelte#createContext) is a type-safe alternative.\n *\n * @template T\n * @param {any} key\n * @returns {T}\n */\nexport function getContext(key) {\n\tconst context_map = get_or_init_context_map('getContext');\n\tconst result = /** @type {T} */ (context_map.get(key));\n\treturn result;\n}\n\n/**\n * Associates an arbitrary `context` object with the current component and the specified `key`\n * and returns that object. The context is then available to children of the component\n * (including slotted content) with `getContext`.\n *\n * Like lifecycle functions, this must be called during component initialisation.\n *\n * [`createContext`](https://svelte.dev/docs/svelte/svelte#createContext) is a type-safe alternative.\n *\n * @template T\n * @param {any} key\n * @param {T} context\n * @returns {T}\n */\nexport function setContext(key, context) {\n\tconst context_map = get_or_init_context_map('setContext');\n\n\tif (async_mode_flag) {\n\t\tvar flags = /** @type {Effect} */ (active_effect).f;\n\t\tvar valid =\n\t\t\t!active_reaction &&\n\t\t\t(flags & BRANCH_EFFECT) !== 0 &&\n\t\t\t// pop() runs synchronously, so this indicates we're setting context after an await\n\t\t\t!(/** @type {ComponentContext} */ (component_context).i);\n\n\t\tif (!valid) {\n\t\t\te.set_context_after_init();\n\t\t}\n\t}\n\n\tcontext_map.set(key, context);\n\treturn context;\n}\n\n/**\n * Checks whether a given `key` has been set in the context of a parent component.\n * Must be called during component initialisation.\n *\n * @param {any} key\n * @returns {boolean}\n */\nexport function hasContext(key) {\n\tconst context_map = get_or_init_context_map('hasContext');\n\treturn context_map.has(key);\n}\n\n/**\n * Retrieves the whole context map that belongs to the closest parent component.\n * Must be called during component initialisation. Useful, for example, if you\n * programmatically create a component and want to pass the existing context to it.\n *\n * @template {Map} [T=Map]\n * @returns {T}\n */\nexport function getAllContexts() {\n\tconst context_map = get_or_init_context_map('getAllContexts');\n\treturn /** @type {T} */ (context_map);\n}\n\n/**\n * @param {Record} props\n * @param {any} runes\n * @param {Function} [fn]\n * @returns {void}\n */\nexport function push(props, runes = false, fn) {\n\tcomponent_context = {\n\t\tp: component_context,\n\t\ti: false,\n\t\tc: null,\n\t\te: null,\n\t\ts: props,\n\t\tx: null,\n\t\tr: /** @type {Effect} */ (active_effect),\n\t\tl: legacy_mode_flag && !runes ? { s: null, u: null, $: [] } : null\n\t};\n\n\tif (DEV) {\n\t\t// component function\n\t\tcomponent_context.function = fn;\n\t\tdev_current_component_function = fn;\n\t}\n}\n\n/**\n * @template {Record} T\n * @param {T} [component]\n * @returns {T}\n */\nexport function pop(component) {\n\tvar context = /** @type {ComponentContext} */ (component_context);\n\tvar effects = context.e;\n\n\tif (effects !== null) {\n\t\tcontext.e = null;\n\n\t\tfor (var fn of effects) {\n\t\t\tcreate_user_effect(fn);\n\t\t}\n\t}\n\n\tif (component !== undefined) {\n\t\tcontext.x = component;\n\t}\n\n\tcontext.i = true;\n\n\tcomponent_context = context.p;\n\n\tif (DEV) {\n\t\tdev_current_component_function = component_context?.function ?? null;\n\t}\n\n\treturn component ?? /** @type {T} */ ({});\n}\n\n/** @returns {boolean} */\nexport function is_runes() {\n\treturn !legacy_mode_flag || (component_context !== null && component_context.l === null);\n}\n\n/**\n * @param {string} name\n * @returns {Map}\n */\nfunction get_or_init_context_map(name) {\n\tif (component_context === null) {\n\t\te.lifecycle_outside_component(name);\n\t}\n\n\treturn (component_context.c ??= new Map(get_parent_context(component_context) || undefined));\n}\n\n/**\n * @param {ComponentContext} component_context\n * @returns {Map | null}\n */\nfunction get_parent_context(component_context) {\n\tlet parent = component_context.p;\n\twhile (parent !== null) {\n\t\tconst context_map = parent.c;\n\t\tif (context_map !== null) {\n\t\t\treturn context_map;\n\t\t}\n\t\tparent = parent.p;\n\t}\n\treturn null;\n}\n","import { run_all } from '../../shared/utils.js';\nimport { is_flushing_sync } from '../reactivity/batch.js';\n\n/** @type {Array<() => void>} */\nlet micro_tasks = [];\n\nfunction run_micro_tasks() {\n\tvar tasks = micro_tasks;\n\tmicro_tasks = [];\n\trun_all(tasks);\n}\n\n/**\n * @param {() => void} fn\n */\nexport function queue_micro_task(fn) {\n\tif (micro_tasks.length === 0 && !is_flushing_sync) {\n\t\tvar tasks = micro_tasks;\n\t\tqueueMicrotask(() => {\n\t\t\t// If this is false, a flushSync happened in the meantime. Do _not_ run new scheduled microtasks in that case\n\t\t\t// as the ordering of microtasks would be broken at that point - consider this case:\n\t\t\t// - queue_micro_task schedules microtask A to flush task X\n\t\t\t// - synchronously after, flushSync runs, processing task X\n\t\t\t// - synchronously after, some other microtask B is scheduled, but not through queue_micro_task but for example a Promise.resolve() in user code\n\t\t\t// - synchronously after, queue_micro_task schedules microtask C to flush task Y\n\t\t\t// - one tick later, microtask A now resolves, flushing task Y before microtask B, which is incorrect\n\t\t\t// This if check prevents that race condition (that realistically will only happen in tests)\n\t\t\tif (tasks === micro_tasks) run_micro_tasks();\n\t\t});\n\t}\n\n\tmicro_tasks.push(fn);\n}\n\n/**\n * Synchronously run any queued tasks.\n */\nexport function flush_tasks() {\n\twhile (micro_tasks.length > 0) {\n\t\trun_micro_tasks();\n\t}\n}\n","/** @import { Derived, Effect } from '#client' */\n/** @import { Boundary } from './dom/blocks/boundary.js' */\nimport { DEV } from 'esm-env';\nimport { FILENAME } from '../../constants.js';\nimport { is_firefox } from './dom/operations.js';\nimport { ERROR_VALUE, BOUNDARY_EFFECT, REACTION_RAN, EFFECT } from './constants.js';\nimport { define_property, get_descriptor } from '../shared/utils.js';\nimport { active_effect, active_reaction } from './runtime.js';\n\nconst adjustments = new WeakMap();\n\n/**\n * @param {unknown} error\n */\nexport function handle_error(error) {\n\tvar effect = active_effect;\n\n\t// for unowned deriveds, don't throw until we read the value\n\tif (effect === null) {\n\t\t/** @type {Derived} */ (active_reaction).f |= ERROR_VALUE;\n\t\treturn error;\n\t}\n\n\tif (DEV && error instanceof Error && !adjustments.has(error)) {\n\t\tadjustments.set(error, get_adjustments(error, effect));\n\t}\n\n\t// if the error occurred while creating this subtree, we let it\n\t// bubble up until it hits a boundary that can handle it, unless\n\t// it's an $effect in which case it doesn't run immediately\n\tif ((effect.f & REACTION_RAN) === 0 && (effect.f & EFFECT) === 0) {\n\t\tif (DEV && !effect.parent && error instanceof Error) {\n\t\t\tapply_adjustments(error);\n\t\t}\n\n\t\tthrow error;\n\t}\n\n\t// otherwise we bubble up the effect tree ourselves\n\tinvoke_error_boundary(error, effect);\n}\n\n/**\n * @param {unknown} error\n * @param {Effect | null} effect\n */\nexport function invoke_error_boundary(error, effect) {\n\twhile (effect !== null) {\n\t\tif ((effect.f & BOUNDARY_EFFECT) !== 0) {\n\t\t\tif ((effect.f & REACTION_RAN) === 0) {\n\t\t\t\t// we are still creating the boundary effect\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\t/** @type {Boundary} */ (effect.b).error(error);\n\t\t\t\treturn;\n\t\t\t} catch (e) {\n\t\t\t\terror = e;\n\t\t\t}\n\t\t}\n\n\t\teffect = effect.parent;\n\t}\n\n\tif (DEV && error instanceof Error) {\n\t\tapply_adjustments(error);\n\t}\n\n\tthrow error;\n}\n\n/**\n * Add useful information to the error message/stack in development\n * @param {Error} error\n * @param {Effect} effect\n */\nfunction get_adjustments(error, effect) {\n\tconst message_descriptor = get_descriptor(error, 'message');\n\n\t// if the message was already changed and it's not configurable we can't change it\n\t// or it will throw a different error swallowing the original error\n\tif (message_descriptor && !message_descriptor.configurable) return;\n\n\tvar indent = is_firefox ? ' ' : '\\t';\n\tvar component_stack = `\\n${indent}in ${effect.fn?.name || ''}`;\n\tvar context = effect.ctx;\n\n\twhile (context !== null) {\n\t\tcomponent_stack += `\\n${indent}in ${context.function?.[FILENAME].split('/').pop()}`;\n\t\tcontext = context.p;\n\t}\n\n\treturn {\n\t\tmessage: error.message + `\\n${component_stack}\\n`,\n\t\tstack: error.stack\n\t\t\t?.split('\\n')\n\t\t\t.filter((line) => !line.includes('svelte/src/internal'))\n\t\t\t.join('\\n')\n\t};\n}\n\n/**\n * @param {Error} error\n */\nfunction apply_adjustments(error) {\n\tconst adjusted = adjustments.get(error);\n\n\tif (adjusted) {\n\t\tdefine_property(error, 'message', {\n\t\t\tvalue: adjusted.message\n\t\t});\n\n\t\tdefine_property(error, 'stack', {\n\t\t\tvalue: adjusted.stack\n\t\t});\n\t}\n}\n","/** @import { Derived, Signal } from '#client' */\nimport { CLEAN, CONNECTED, DIRTY, MAYBE_DIRTY } from '#client/constants';\n\nconst STATUS_MASK = ~(DIRTY | MAYBE_DIRTY | CLEAN);\n\n/**\n * @param {Signal} signal\n * @param {number} status\n */\nexport function set_signal_status(signal, status) {\n\tsignal.f = (signal.f & STATUS_MASK) | status;\n}\n\n/**\n * Set a derived's status to CLEAN or MAYBE_DIRTY based on its connection state.\n * @param {Derived} derived\n */\nexport function update_derived_status(derived) {\n\t// Only mark as MAYBE_DIRTY if disconnected and has dependencies.\n\tif ((derived.f & CONNECTED) !== 0 || derived.deps === null) {\n\t\tset_signal_status(derived, CLEAN);\n\t} else {\n\t\tset_signal_status(derived, MAYBE_DIRTY);\n\t}\n}\n","/** @import { Derived, Effect, Value } from '#client' */\nimport { CLEAN, DERIVED, DIRTY, MAYBE_DIRTY, WAS_MARKED } from '#client/constants';\nimport { set_signal_status } from './status.js';\n\n/**\n * @param {Value[] | null} deps\n */\nfunction clear_marked(deps) {\n\tif (deps === null) return;\n\n\tfor (const dep of deps) {\n\t\tif ((dep.f & DERIVED) === 0 || (dep.f & WAS_MARKED) === 0) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tdep.f ^= WAS_MARKED;\n\n\t\tclear_marked(/** @type {Derived} */ (dep).deps);\n\t}\n}\n\n/**\n * @param {Effect} effect\n * @param {Set} dirty_effects\n * @param {Set} maybe_dirty_effects\n */\nexport function defer_effect(effect, dirty_effects, maybe_dirty_effects) {\n\tif ((effect.f & DIRTY) !== 0) {\n\t\tdirty_effects.add(effect);\n\t} else if ((effect.f & MAYBE_DIRTY) !== 0) {\n\t\tmaybe_dirty_effects.add(effect);\n\t}\n\n\t// Since we're not executing these effects now, we need to clear any WAS_MARKED flags\n\t// so that other batches can correctly reach these effects during their own traversal\n\tclear_marked(effect.deps);\n\n\t// mark as clean so they get scheduled if they depend on pending async state\n\tset_signal_status(effect, CLEAN);\n}\n","/** @import { Readable } from './public' */\nimport { untrack } from '../internal/client/runtime.js';\nimport { noop } from '../internal/shared/utils.js';\n\n/**\n * @template T\n * @param {Readable | null | undefined} store\n * @param {(value: T) => void} run\n * @param {(value: T) => void} [invalidate]\n * @returns {() => void}\n */\nexport function subscribe_to_store(store, run, invalidate) {\n\tif (store == null) {\n\t\t// @ts-expect-error\n\t\trun(undefined);\n\n\t\t// @ts-expect-error\n\t\tif (invalidate) invalidate(undefined);\n\n\t\treturn noop;\n\t}\n\n\t// Svelte store takes a private second argument\n\t// StartStopNotifier could mutate state, and we want to silence the corresponding validation error\n\tconst unsub = untrack(() =>\n\t\tstore.subscribe(\n\t\t\trun,\n\t\t\t// @ts-expect-error\n\t\t\tinvalidate\n\t\t)\n\t);\n\n\t// Also support RxJS\n\t// @ts-expect-error TODO fix this in the types?\n\treturn unsub.unsubscribe ? () => unsub.unsubscribe() : unsub;\n}\n","/** @import { Readable, StartStopNotifier, Subscriber, Unsubscriber, Updater, Writable } from '../public.js' */\n/** @import { Stores, StoresValues, SubscribeInvalidateTuple } from '../private.js' */\nimport { noop, run_all } from '../../internal/shared/utils.js';\nimport { safe_not_equal } from '../../internal/client/reactivity/equality.js';\nimport { subscribe_to_store } from '../utils.js';\n\n/**\n * @type {Array | any>}\n */\nconst subscriber_queue = [];\n\n/**\n * Creates a `Readable` store that allows reading by subscription.\n *\n * @template T\n * @param {T} [value] initial value\n * @param {StartStopNotifier} [start]\n * @returns {Readable}\n */\nexport function readable(value, start) {\n\treturn {\n\t\tsubscribe: writable(value, start).subscribe\n\t};\n}\n\n/**\n * Create a `Writable` store that allows both updating and reading by subscription.\n *\n * @template T\n * @param {T} [value] initial value\n * @param {StartStopNotifier} [start]\n * @returns {Writable}\n */\nexport function writable(value, start = noop) {\n\t/** @type {Unsubscriber | null} */\n\tlet stop = null;\n\n\t/** @type {Set>} */\n\tconst subscribers = new Set();\n\n\t/**\n\t * @param {T} new_value\n\t * @returns {void}\n\t */\n\tfunction set(new_value) {\n\t\tif (safe_not_equal(value, new_value)) {\n\t\t\tvalue = new_value;\n\t\t\tif (stop) {\n\t\t\t\t// store is ready\n\t\t\t\tconst run_queue = !subscriber_queue.length;\n\t\t\t\tfor (const subscriber of subscribers) {\n\t\t\t\t\tsubscriber[1]();\n\t\t\t\t\tsubscriber_queue.push(subscriber, value);\n\t\t\t\t}\n\t\t\t\tif (run_queue) {\n\t\t\t\t\tfor (let i = 0; i < subscriber_queue.length; i += 2) {\n\t\t\t\t\t\tsubscriber_queue[i][0](subscriber_queue[i + 1]);\n\t\t\t\t\t}\n\t\t\t\t\tsubscriber_queue.length = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * @param {Updater} fn\n\t * @returns {void}\n\t */\n\tfunction update(fn) {\n\t\tset(fn(/** @type {T} */ (value)));\n\t}\n\n\t/**\n\t * @param {Subscriber} run\n\t * @param {() => void} [invalidate]\n\t * @returns {Unsubscriber}\n\t */\n\tfunction subscribe(run, invalidate = noop) {\n\t\t/** @type {SubscribeInvalidateTuple} */\n\t\tconst subscriber = [run, invalidate];\n\t\tsubscribers.add(subscriber);\n\t\tif (subscribers.size === 1) {\n\t\t\tstop = start(set, update) || noop;\n\t\t}\n\t\trun(/** @type {T} */ (value));\n\t\treturn () => {\n\t\t\tsubscribers.delete(subscriber);\n\t\t\tif (subscribers.size === 0 && stop) {\n\t\t\t\tstop();\n\t\t\t\tstop = null;\n\t\t\t}\n\t\t};\n\t}\n\treturn { set, update, subscribe };\n}\n\n/**\n * Derived value store by synchronizing one or more readable stores and\n * applying an aggregation function over its input values.\n *\n * @template {Stores} S\n * @template T\n * @overload\n * @param {S} stores\n * @param {(values: StoresValues, set: (value: T) => void, update: (fn: Updater) => void) => Unsubscriber | void} fn\n * @param {T} [initial_value]\n * @returns {Readable}\n */\n/**\n * Derived value store by synchronizing one or more readable stores and\n * applying an aggregation function over its input values.\n *\n * @template {Stores} S\n * @template T\n * @overload\n * @param {S} stores\n * @param {(values: StoresValues) => T} fn\n * @param {T} [initial_value]\n * @returns {Readable}\n */\n/**\n * @template {Stores} S\n * @template T\n * @param {S} stores\n * @param {Function} fn\n * @param {T} [initial_value]\n * @returns {Readable}\n */\nexport function derived(stores, fn, initial_value) {\n\tconst single = !Array.isArray(stores);\n\t/** @type {Array>} */\n\tconst stores_array = single ? [stores] : stores;\n\tif (!stores_array.every(Boolean)) {\n\t\tthrow new Error('derived() expects stores as input, got a falsy value');\n\t}\n\tconst auto = fn.length < 2;\n\treturn readable(initial_value, (set, update) => {\n\t\tlet started = false;\n\t\t/** @type {T[]} */\n\t\tconst values = [];\n\t\tlet pending = 0;\n\t\tlet cleanup = noop;\n\t\tconst sync = () => {\n\t\t\tif (pending) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcleanup();\n\t\t\tconst result = fn(single ? values[0] : values, set, update);\n\t\t\tif (auto) {\n\t\t\t\tset(result);\n\t\t\t} else {\n\t\t\t\tcleanup = typeof result === 'function' ? result : noop;\n\t\t\t}\n\t\t};\n\t\tconst unsubscribers = stores_array.map((store, i) =>\n\t\t\tsubscribe_to_store(\n\t\t\t\tstore,\n\t\t\t\t(value) => {\n\t\t\t\t\tvalues[i] = value;\n\t\t\t\t\tpending &= ~(1 << i);\n\t\t\t\t\tif (started) {\n\t\t\t\t\t\tsync();\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tpending |= 1 << i;\n\t\t\t\t}\n\t\t\t)\n\t\t);\n\t\tstarted = true;\n\t\tsync();\n\t\treturn function stop() {\n\t\t\trun_all(unsubscribers);\n\t\t\tcleanup();\n\t\t\t// We need to set this to false because callbacks can still happen despite having unsubscribed:\n\t\t\t// Callbacks might already be placed in the queue which doesn't know it should no longer\n\t\t\t// invoke this derived store.\n\t\t\tstarted = false;\n\t\t};\n\t});\n}\n\n/**\n * Takes a store and returns a new one derived from the old one that is readable.\n *\n * @template T\n * @param {Readable} store - store to make readonly\n * @returns {Readable}\n */\nexport function readonly(store) {\n\treturn {\n\t\t// @ts-expect-error TODO i suspect the bind is unnecessary\n\t\tsubscribe: store.subscribe.bind(store)\n\t};\n}\n\n/**\n * Get the current value from a store by subscribing and immediately unsubscribing.\n *\n * @template T\n * @param {Readable} store\n * @returns {T}\n */\nexport function get(store) {\n\tlet value;\n\tsubscribe_to_store(store, (_) => (value = _))();\n\t// @ts-expect-error\n\treturn value;\n}\n","/** @import { StoreReferencesContainer } from '#client' */\n/** @import { Store } from '#shared' */\nimport { subscribe_to_store } from '../../../store/utils.js';\nimport { get as get_store } from '../../../store/shared/index.js';\nimport { define_property, noop } from '../../shared/utils.js';\nimport { get } from '../runtime.js';\nimport { teardown } from './effects.js';\nimport { mutable_source, set } from './sources.js';\nimport { DEV } from 'esm-env';\n\n/**\n * We set this to `true` when updating a store so that we correctly\n * schedule effects if the update takes place inside a `$:` effect\n */\nexport let legacy_is_updating_store = false;\n\n/**\n * Whether or not the prop currently being read is a store binding, as in\n * ``. If it is, we treat the prop as mutable even in\n * runes mode, and skip `binding_property_non_reactive` validation\n */\nlet is_store_binding = false;\n\nlet IS_UNMOUNTED = Symbol();\n\n/**\n * Gets the current value of a store. If the store isn't subscribed to yet, it will create a proxy\n * signal that will be updated when the store is. The store references container is needed to\n * track reassignments to stores and to track the correct component context.\n * @template V\n * @param {Store | null | undefined} store\n * @param {string} store_name\n * @param {StoreReferencesContainer} stores\n * @returns {V}\n */\nexport function store_get(store, store_name, stores) {\n\tconst entry = (stores[store_name] ??= {\n\t\tstore: null,\n\t\tsource: mutable_source(undefined),\n\t\tunsubscribe: noop\n\t});\n\n\tif (DEV) {\n\t\tentry.source.label = store_name;\n\t}\n\n\t// if the component that setup this is already unmounted we don't want to register a subscription\n\tif (entry.store !== store && !(IS_UNMOUNTED in stores)) {\n\t\tentry.unsubscribe();\n\t\tentry.store = store ?? null;\n\n\t\tif (store == null) {\n\t\t\tentry.source.v = undefined; // see synchronous callback comment below\n\t\t\tentry.unsubscribe = noop;\n\t\t} else {\n\t\t\tvar is_synchronous_callback = true;\n\n\t\t\tentry.unsubscribe = subscribe_to_store(store, (v) => {\n\t\t\t\tif (is_synchronous_callback) {\n\t\t\t\t\t// If the first updates to the store value (possibly multiple of them) are synchronously\n\t\t\t\t\t// inside a derived, we will hit the `state_unsafe_mutation` error if we `set` the value\n\t\t\t\t\tentry.source.v = v;\n\t\t\t\t} else {\n\t\t\t\t\tset(entry.source, v);\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tis_synchronous_callback = false;\n\t\t}\n\t}\n\n\t// if the component that setup this stores is already unmounted the source will be out of sync\n\t// so we just use the `get` for the stores, less performant but it avoids to create a memory leak\n\t// and it will keep the value consistent\n\tif (store && IS_UNMOUNTED in stores) {\n\t\treturn get_store(store);\n\t}\n\n\treturn get(entry.source);\n}\n\n/**\n * Unsubscribe from a store if it's not the same as the one in the store references container.\n * We need this in addition to `store_get` because someone could unsubscribe from a store but\n * then never subscribe to the new one (if any), causing the subscription to stay open wrongfully.\n * @param {Store | null | undefined} store\n * @param {string} store_name\n * @param {StoreReferencesContainer} stores\n */\nexport function store_unsub(store, store_name, stores) {\n\t/** @type {StoreReferencesContainer[''] | undefined} */\n\tlet entry = stores[store_name];\n\n\tif (entry && entry.store !== store) {\n\t\t// Don't reset store yet, so that store_get above can resubscribe to new store if necessary\n\t\tentry.unsubscribe();\n\t\tentry.unsubscribe = noop;\n\t}\n\n\treturn store;\n}\n\n/**\n * Sets the new value of a store and returns that value.\n * @template V\n * @param {Store} store\n * @param {V} value\n * @returns {V}\n */\nexport function store_set(store, value) {\n\tupdate_with_flag(store, value);\n\treturn value;\n}\n\n/**\n * @param {StoreReferencesContainer} stores\n * @param {string} store_name\n */\nexport function invalidate_store(stores, store_name) {\n\tvar entry = stores[store_name];\n\tif (entry.store !== null) {\n\t\tstore_set(entry.store, entry.source.v);\n\t}\n}\n\n/**\n * Unsubscribes from all auto-subscribed stores on destroy\n * @returns {[StoreReferencesContainer, ()=>void]}\n */\nexport function setup_stores() {\n\t/** @type {StoreReferencesContainer} */\n\tconst stores = {};\n\n\tfunction cleanup() {\n\t\tteardown(() => {\n\t\t\tfor (var store_name in stores) {\n\t\t\t\tconst ref = stores[store_name];\n\t\t\t\tref.unsubscribe();\n\t\t\t}\n\t\t\tdefine_property(stores, IS_UNMOUNTED, {\n\t\t\t\tenumerable: false,\n\t\t\t\tvalue: true\n\t\t\t});\n\t\t});\n\t}\n\n\treturn [stores, cleanup];\n}\n\n/**\n * @param {Store} store\n * @param {V} value\n * @template V\n */\nfunction update_with_flag(store, value) {\n\tlegacy_is_updating_store = true;\n\n\ttry {\n\t\tstore.set(value);\n\t} finally {\n\t\tlegacy_is_updating_store = false;\n\t}\n}\n\n/**\n * Updates a store with a new value.\n * @param {Store} store the store to update\n * @param {any} expression the expression that mutates the store\n * @param {V} new_value the new store value\n * @template V\n */\nexport function store_mutate(store, expression, new_value) {\n\tupdate_with_flag(store, new_value);\n\treturn expression;\n}\n\n/**\n * @param {Store} store\n * @param {number} store_value\n * @param {1 | -1} [d]\n * @returns {number}\n */\nexport function update_store(store, store_value, d = 1) {\n\tupdate_with_flag(store, store_value + d);\n\treturn store_value;\n}\n\n/**\n * @param {Store} store\n * @param {number} store_value\n * @param {1 | -1} [d]\n * @returns {number}\n */\nexport function update_pre_store(store, store_value, d = 1) {\n\tconst value = store_value + d;\n\tupdate_with_flag(store, value);\n\treturn value;\n}\n\n/**\n * Called inside prop getters to communicate that the prop is a store binding\n */\nexport function mark_store_binding() {\n\tis_store_binding = true;\n}\n\n/**\n * Returns a tuple that indicates whether `fn()` reads a prop that is a store binding.\n * Used to prevent `binding_property_non_reactive` validation false positives and\n * ensure that these props are treated as mutable even in runes mode\n * @template T\n * @param {() => T} fn\n * @returns {[T, boolean]}\n */\nexport function capture_store_binding(fn) {\n\tvar previous_is_store_binding = is_store_binding;\n\n\ttry {\n\t\tis_store_binding = false;\n\t\treturn [fn(), is_store_binding];\n\t} finally {\n\t\tis_store_binding = previous_is_store_binding;\n\t}\n}\n","/** @import { Fork } from 'svelte' */\n/** @import { Derived, Effect, Reaction, Source, Value } from '#client' */\nimport {\n\tBLOCK_EFFECT,\n\tBRANCH_EFFECT,\n\tCLEAN,\n\tDESTROYED,\n\tDIRTY,\n\tEFFECT,\n\tASYNC,\n\tINERT,\n\tRENDER_EFFECT,\n\tROOT_EFFECT,\n\tMAYBE_DIRTY,\n\tDERIVED,\n\tEAGER_EFFECT,\n\tERROR_VALUE,\n\tMANAGED_EFFECT,\n\tREACTION_RAN\n} from '#client/constants';\nimport { async_mode_flag } from '../../flags/index.js';\nimport { deferred, define_property, includes } from '../../shared/utils.js';\nimport {\n\tactive_effect,\n\tactive_reaction,\n\tget,\n\tincrement_write_version,\n\tis_dirty,\n\tupdate_effect\n} from '../runtime.js';\nimport * as e from '../errors.js';\nimport { flush_tasks, queue_micro_task } from '../dom/task.js';\nimport { DEV } from 'esm-env';\nimport { invoke_error_boundary } from '../error-handling.js';\nimport { flush_eager_effects, old_values, set_eager_effects, source, update } from './sources.js';\nimport { eager_effect, unlink_effect } from './effects.js';\nimport { defer_effect } from './utils.js';\nimport { UNINITIALIZED } from '../../../constants.js';\nimport { set_signal_status } from './status.js';\nimport { legacy_is_updating_store } from './store.js';\nimport { invariant } from '../../shared/dev.js';\nimport { log_effect_tree } from '../dev/debug.js';\n\n/** @type {Set} */\nconst batches = new Set();\n\n/** @type {Batch | null} */\nexport let current_batch = null;\n\n/**\n * This is needed to avoid overwriting inputs\n * @type {Batch | null}\n */\nexport let previous_batch = null;\n\n/**\n * When time travelling (i.e. working in one batch, while other batches\n * still have ongoing work), we ignore the real values of affected\n * signals in favour of their values within the batch\n * @type {Map | null}\n */\nexport let batch_values = null;\n\n/** @type {Effect | null} */\nlet last_scheduled_effect = null;\n\nexport let is_flushing_sync = false;\nlet is_processing = false;\n\n/**\n * During traversal, this is an array. Newly created effects are (if not immediately\n * executed) pushed to this array, rather than going through the scheduling\n * rigamarole that would cause another turn of the flush loop.\n * @type {Effect[] | null}\n */\nexport let collected_effects = null;\n\n/**\n * An array of effects that are marked during traversal as a result of a `set`\n * (not `internal_set`) call. These will be added to the next batch and\n * trigger another `batch.process()`\n * @type {Effect[] | null}\n * @deprecated when we get rid of legacy mode and stores, we can get rid of this\n */\nexport let legacy_updates = null;\n\nvar flush_count = 0;\nvar source_stacks = DEV ? new Set() : null;\n\nlet uid = 1;\n\nexport class Batch {\n\tid = uid++;\n\n\t/**\n\t * The current values of any signals that are updated in this batch.\n\t * Tuple format: [value, is_derived] (note: is_derived is false for deriveds, too, if they were overridden via assignment)\n\t * They keys of this map are identical to `this.#previous`\n\t * @type {Map}\n\t */\n\tcurrent = new Map();\n\n\t/**\n\t * The values of any signals (sources and deriveds) that are updated in this batch _before_ those updates took place.\n\t * They keys of this map are identical to `this.#current`\n\t * @type {Map}\n\t */\n\tprevious = new Map();\n\n\t/**\n\t * When the batch is committed (and the DOM is updated), we need to remove old branches\n\t * and append new ones by calling the functions added inside (if/each/key/etc) blocks\n\t * @type {Set<(batch: Batch) => void>}\n\t */\n\t#commit_callbacks = new Set();\n\n\t/**\n\t * If a fork is discarded, we need to destroy any effects that are no longer needed\n\t * @type {Set<(batch: Batch) => void>}\n\t */\n\t#discard_callbacks = new Set();\n\n\t/**\n\t * Callbacks that should run only when a fork is committed.\n\t * @type {Set<(batch: Batch) => void>}\n\t */\n\t#fork_commit_callbacks = new Set();\n\n\t/**\n\t * Async effects that are currently in flight\n\t * @type {Map}\n\t */\n\t#pending = new Map();\n\n\t/**\n\t * Async effects that are currently in flight, _not_ inside a pending boundary\n\t * @type {Map}\n\t */\n\t#blocking_pending = new Map();\n\n\t/**\n\t * A deferred that resolves when the batch is committed, used with `settled()`\n\t * TODO replace with Promise.withResolvers once supported widely enough\n\t * @type {{ promise: Promise, resolve: (value?: any) => void, reject: (reason: unknown) => void } | null}\n\t */\n\t#deferred = null;\n\n\t/**\n\t * The root effects that need to be flushed\n\t * @type {Effect[]}\n\t */\n\t#roots = [];\n\n\t/**\n\t * Effects created while this batch was active.\n\t * @type {Effect[]}\n\t */\n\t#new_effects = [];\n\n\t/**\n\t * Deferred effects (which run after async work has completed) that are DIRTY\n\t * @type {Set}\n\t */\n\t#dirty_effects = new Set();\n\n\t/**\n\t * Deferred effects that are MAYBE_DIRTY\n\t * @type {Set}\n\t */\n\t#maybe_dirty_effects = new Set();\n\n\t/**\n\t * A map of branches that still exist, but will be destroyed when this batch\n\t * is committed — we skip over these during `process`.\n\t * The value contains child effects that were dirty/maybe_dirty before being reset,\n\t * so they can be rescheduled if the branch survives.\n\t * @type {Map}\n\t */\n\t#skipped_branches = new Map();\n\n\t/**\n\t * Inverse of #skipped_branches which we need to tell prior batches to unskip them when committing\n\t * @type {Set}\n\t */\n\t#unskipped_branches = new Set();\n\n\tis_fork = false;\n\n\t#decrement_queued = false;\n\n\t/** @type {Set} */\n\t#blockers = new Set();\n\n\t#is_deferred() {\n\t\treturn this.is_fork || this.#blocking_pending.size > 0;\n\t}\n\n\t#is_blocked() {\n\t\tfor (const batch of this.#blockers) {\n\t\t\tfor (const effect of batch.#blocking_pending.keys()) {\n\t\t\t\tvar skipped = false;\n\t\t\t\tvar e = effect;\n\n\t\t\t\twhile (e.parent !== null) {\n\t\t\t\t\tif (this.#skipped_branches.has(e)) {\n\t\t\t\t\t\tskipped = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\te = e.parent;\n\t\t\t\t}\n\n\t\t\t\tif (!skipped) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t * Add an effect to the #skipped_branches map and reset its children\n\t * @param {Effect} effect\n\t */\n\tskip_effect(effect) {\n\t\tif (!this.#skipped_branches.has(effect)) {\n\t\t\tthis.#skipped_branches.set(effect, { d: [], m: [] });\n\t\t}\n\t\tthis.#unskipped_branches.delete(effect);\n\t}\n\n\t/**\n\t * Remove an effect from the #skipped_branches map and reschedule\n\t * any tracked dirty/maybe_dirty child effects\n\t * @param {Effect} effect\n\t * @param {(e: Effect) => void} callback\n\t */\n\tunskip_effect(effect, callback = (e) => this.schedule(e)) {\n\t\tvar tracked = this.#skipped_branches.get(effect);\n\t\tif (tracked) {\n\t\t\tthis.#skipped_branches.delete(effect);\n\n\t\t\tfor (var e of tracked.d) {\n\t\t\t\tset_signal_status(e, DIRTY);\n\t\t\t\tcallback(e);\n\t\t\t}\n\n\t\t\tfor (e of tracked.m) {\n\t\t\t\tset_signal_status(e, MAYBE_DIRTY);\n\t\t\t\tcallback(e);\n\t\t\t}\n\t\t}\n\t\tthis.#unskipped_branches.add(effect);\n\t}\n\n\t#process() {\n\t\tif (flush_count++ > 1000) {\n\t\t\tbatches.delete(this);\n\t\t\tinfinite_loop_guard();\n\t\t}\n\n\t\t// we only reschedule previously-deferred effects if we expect\n\t\t// to be able to run them after processing the batch\n\t\tif (!this.#is_deferred()) {\n\t\t\tfor (const e of this.#dirty_effects) {\n\t\t\t\tthis.#maybe_dirty_effects.delete(e);\n\t\t\t\tset_signal_status(e, DIRTY);\n\t\t\t\tthis.schedule(e);\n\t\t\t}\n\n\t\t\tfor (const e of this.#maybe_dirty_effects) {\n\t\t\t\tset_signal_status(e, MAYBE_DIRTY);\n\t\t\t\tthis.schedule(e);\n\t\t\t}\n\t\t}\n\n\t\tconst roots = this.#roots;\n\t\tthis.#roots = [];\n\n\t\tthis.apply();\n\n\t\t/** @type {Effect[]} */\n\t\tvar effects = (collected_effects = []);\n\n\t\t/** @type {Effect[]} */\n\t\tvar render_effects = [];\n\n\t\t/**\n\t\t * @type {Effect[]}\n\t\t * @deprecated when we get rid of legacy mode and stores, we can get rid of this\n\t\t */\n\t\tvar updates = (legacy_updates = []);\n\n\t\tfor (const root of roots) {\n\t\t\ttry {\n\t\t\t\tthis.#traverse(root, effects, render_effects);\n\t\t\t} catch (e) {\n\t\t\t\treset_all(root);\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t}\n\n\t\t// any writes should take effect in a subsequent batch\n\t\tcurrent_batch = null;\n\n\t\tif (updates.length > 0) {\n\t\t\tvar batch = Batch.ensure();\n\t\t\tfor (const e of updates) {\n\t\t\t\tbatch.schedule(e);\n\t\t\t}\n\t\t}\n\n\t\tcollected_effects = null;\n\t\tlegacy_updates = null;\n\n\t\tif (this.#is_deferred() || this.#is_blocked()) {\n\t\t\tthis.#defer_effects(render_effects);\n\t\t\tthis.#defer_effects(effects);\n\n\t\t\tfor (const [e, t] of this.#skipped_branches) {\n\t\t\t\treset_branch(e, t);\n\t\t\t}\n\t\t} else {\n\t\t\tif (this.#pending.size === 0) {\n\t\t\t\tbatches.delete(this);\n\t\t\t}\n\n\t\t\t// clear effects. Those that are still needed will be rescheduled through unskipping the skipped branches.\n\t\t\tthis.#dirty_effects.clear();\n\t\t\tthis.#maybe_dirty_effects.clear();\n\n\t\t\t// append/remove branches\n\t\t\tfor (const fn of this.#commit_callbacks) fn(this);\n\t\t\tthis.#commit_callbacks.clear();\n\n\t\t\tprevious_batch = this;\n\t\t\tflush_queued_effects(render_effects);\n\t\t\tflush_queued_effects(effects);\n\t\t\tprevious_batch = null;\n\n\t\t\tthis.#deferred?.resolve();\n\t\t}\n\n\t\tvar next_batch = /** @type {Batch | null} */ (/** @type {unknown} */ (current_batch));\n\n\t\t// Edge case: During traversal new branches might create effects that run immediately and set state,\n\t\t// causing an effect and therefore a root to be scheduled again. We need to traverse the current batch\n\t\t// once more in that case - most of the time this will just clean up dirty branches.\n\t\tif (this.#roots.length > 0) {\n\t\t\tconst batch = (next_batch ??= this);\n\t\t\tbatch.#roots.push(...this.#roots.filter((r) => !batch.#roots.includes(r)));\n\t\t}\n\n\t\tif (next_batch !== null) {\n\t\t\tbatches.add(next_batch);\n\n\t\t\tif (DEV) {\n\t\t\t\tfor (const source of this.current.keys()) {\n\t\t\t\t\t/** @type {Set} */ (source_stacks).add(source);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tnext_batch.#process();\n\t\t}\n\n\t\t// In sync mode flushSync can cause #commit to wrongfully think that there needs to be a rebase, so we only do it in async mode\n\t\t// TODO fix the underlying cause, otherwise this will likely regress when non-async mode is removed\n\t\tif (async_mode_flag && !batches.has(this)) {\n\t\t\tthis.#commit();\n\t\t}\n\t}\n\n\t/**\n\t * Traverse the effect tree, executing effects or stashing\n\t * them for later execution as appropriate\n\t * @param {Effect} root\n\t * @param {Effect[]} effects\n\t * @param {Effect[]} render_effects\n\t */\n\t#traverse(root, effects, render_effects) {\n\t\troot.f ^= CLEAN;\n\n\t\tvar effect = root.first;\n\n\t\twhile (effect !== null) {\n\t\t\tvar flags = effect.f;\n\t\t\tvar is_branch = (flags & (BRANCH_EFFECT | ROOT_EFFECT)) !== 0;\n\t\t\tvar is_skippable_branch = is_branch && (flags & CLEAN) !== 0;\n\n\t\t\tvar skip = is_skippable_branch || (flags & INERT) !== 0 || this.#skipped_branches.has(effect);\n\n\t\t\tif (!skip && effect.fn !== null) {\n\t\t\t\tif (is_branch) {\n\t\t\t\t\teffect.f ^= CLEAN;\n\t\t\t\t} else if ((flags & EFFECT) !== 0) {\n\t\t\t\t\teffects.push(effect);\n\t\t\t\t} else if (async_mode_flag && (flags & (RENDER_EFFECT | MANAGED_EFFECT)) !== 0) {\n\t\t\t\t\trender_effects.push(effect);\n\t\t\t\t} else if (is_dirty(effect)) {\n\t\t\t\t\tif ((flags & BLOCK_EFFECT) !== 0) this.#maybe_dirty_effects.add(effect);\n\t\t\t\t\tupdate_effect(effect);\n\t\t\t\t}\n\n\t\t\t\tvar child = effect.first;\n\n\t\t\t\tif (child !== null) {\n\t\t\t\t\teffect = child;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\twhile (effect !== null) {\n\t\t\t\tvar next = effect.next;\n\n\t\t\t\tif (next !== null) {\n\t\t\t\t\teffect = next;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\teffect = effect.parent;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * @param {Effect[]} effects\n\t */\n\t#defer_effects(effects) {\n\t\tfor (var i = 0; i < effects.length; i += 1) {\n\t\t\tdefer_effect(effects[i], this.#dirty_effects, this.#maybe_dirty_effects);\n\t\t}\n\t}\n\n\t/**\n\t * Associate a change to a given source with the current\n\t * batch, noting its previous and current values\n\t * @param {Value} source\n\t * @param {any} value\n\t * @param {boolean} [is_derived]\n\t */\n\tcapture(source, value, is_derived = false) {\n\t\tif (source.v !== UNINITIALIZED && !this.previous.has(source)) {\n\t\t\tthis.previous.set(source, source.v);\n\t\t}\n\n\t\t// Don't save errors in `batch_values`, or they won't be thrown in `runtime.js#get`\n\t\tif ((source.f & ERROR_VALUE) === 0) {\n\t\t\tthis.current.set(source, [value, is_derived]);\n\t\t\tbatch_values?.set(source, value);\n\t\t}\n\n\t\tif (!this.is_fork) {\n\t\t\tsource.v = value;\n\t\t}\n\t}\n\n\tactivate() {\n\t\tcurrent_batch = this;\n\t}\n\n\tdeactivate() {\n\t\tcurrent_batch = null;\n\t\tbatch_values = null;\n\t}\n\n\tflush() {\n\t\tvar source_stacks = DEV ? new Set() : null;\n\n\t\ttry {\n\t\t\tis_processing = true;\n\t\t\tcurrent_batch = this;\n\n\t\t\tthis.#process();\n\t\t} finally {\n\t\t\tflush_count = 0;\n\t\t\tlast_scheduled_effect = null;\n\t\t\tcollected_effects = null;\n\t\t\tlegacy_updates = null;\n\t\t\tis_processing = false;\n\n\t\t\tcurrent_batch = null;\n\t\t\tbatch_values = null;\n\n\t\t\told_values.clear();\n\n\t\t\tif (DEV) {\n\t\t\t\tfor (const source of /** @type {Set} */ (source_stacks)) {\n\t\t\t\t\tsource.updated = null;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tdiscard() {\n\t\tfor (const fn of this.#discard_callbacks) fn(this);\n\t\tthis.#discard_callbacks.clear();\n\t\tthis.#fork_commit_callbacks.clear();\n\n\t\tbatches.delete(this);\n\t}\n\n\t/**\n\t * @param {Effect} effect\n\t */\n\tregister_created_effect(effect) {\n\t\tthis.#new_effects.push(effect);\n\t}\n\n\t#commit() {\n\t\t// If there are other pending batches, they now need to be 'rebased' —\n\t\t// in other words, we re-run block/async effects with the newly\n\t\t// committed state, unless the batch in question has a more\n\t\t// recent value for a given source\n\t\tfor (const batch of batches) {\n\t\t\tvar is_earlier = batch.id < this.id;\n\n\t\t\t/** @type {Source[]} */\n\t\t\tvar sources = [];\n\n\t\t\tfor (const [source, [value, is_derived]] of this.current) {\n\t\t\t\tif (batch.current.has(source)) {\n\t\t\t\t\tvar batch_value = /** @type {[any, boolean]} */ (batch.current.get(source))[0]; // faster than destructuring\n\n\t\t\t\t\tif (is_earlier && value !== batch_value) {\n\t\t\t\t\t\t// bring the value up to date\n\t\t\t\t\t\tbatch.current.set(source, [value, is_derived]);\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// same value or later batch has more recent value,\n\t\t\t\t\t\t// no need to re-run these effects\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tsources.push(source);\n\t\t\t}\n\n\t\t\t// Re-run async/block effects that depend on distinct values changed in both batches\n\t\t\tvar others = [...batch.current.keys()].filter((s) => !this.current.has(s));\n\n\t\t\tif (others.length === 0) {\n\t\t\t\tif (is_earlier) {\n\t\t\t\t\t// this batch is now obsolete and can be discarded\n\t\t\t\t\tbatch.discard();\n\t\t\t\t}\n\t\t\t} else if (sources.length > 0) {\n\t\t\t\tif (DEV) {\n\t\t\t\t\tinvariant(batch.#roots.length === 0, 'Batch has scheduled roots');\n\t\t\t\t}\n\n\t\t\t\t// A batch was unskipped in a later batch -> tell prior batches to unskip it, too\n\t\t\t\tif (is_earlier) {\n\t\t\t\t\tfor (const unskipped of this.#unskipped_branches) {\n\t\t\t\t\t\tbatch.unskip_effect(unskipped, (e) => {\n\t\t\t\t\t\t\tif ((e.f & (BLOCK_EFFECT | ASYNC)) !== 0) {\n\t\t\t\t\t\t\t\tbatch.schedule(e);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tbatch.#defer_effects([e]);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tbatch.activate();\n\n\t\t\t\t/** @type {Set} */\n\t\t\t\tvar marked = new Set();\n\n\t\t\t\t/** @type {Map} */\n\t\t\t\tvar checked = new Map();\n\n\t\t\t\tfor (var source of sources) {\n\t\t\t\t\tmark_effects(source, others, marked, checked);\n\t\t\t\t}\n\n\t\t\t\tchecked = new Map();\n\t\t\t\tvar current_unequal = [...batch.current.keys()].filter((c) =>\n\t\t\t\t\tthis.current.has(c) ? /** @type {[any, boolean]} */ (this.current.get(c))[0] !== c : true\n\t\t\t\t);\n\n\t\t\t\tfor (const effect of this.#new_effects) {\n\t\t\t\t\tif (\n\t\t\t\t\t\t(effect.f & (DESTROYED | INERT | EAGER_EFFECT)) === 0 &&\n\t\t\t\t\t\tdepends_on(effect, current_unequal, checked)\n\t\t\t\t\t) {\n\t\t\t\t\t\tif ((effect.f & (ASYNC | BLOCK_EFFECT)) !== 0) {\n\t\t\t\t\t\t\tset_signal_status(effect, DIRTY);\n\t\t\t\t\t\t\tbatch.schedule(effect);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tbatch.#dirty_effects.add(effect);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Only apply and traverse when we know we triggered async work with marking the effects\n\t\t\t\tif (batch.#roots.length > 0) {\n\t\t\t\t\tbatch.apply();\n\n\t\t\t\t\tfor (var root of batch.#roots) {\n\t\t\t\t\t\tbatch.#traverse(root, [], []);\n\t\t\t\t\t}\n\n\t\t\t\t\tbatch.#roots = [];\n\t\t\t\t}\n\n\t\t\t\tbatch.deactivate();\n\t\t\t}\n\t\t}\n\n\t\tfor (const batch of batches) {\n\t\t\tif (batch.#blockers.has(this)) {\n\t\t\t\tbatch.#blockers.delete(this);\n\n\t\t\t\tif (batch.#blockers.size === 0 && !batch.#is_deferred()) {\n\t\t\t\t\tbatch.activate();\n\t\t\t\t\tbatch.#process();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * @param {boolean} blocking\n\t * @param {Effect} effect\n\t */\n\tincrement(blocking, effect) {\n\t\tlet pending_count = this.#pending.get(effect) ?? 0;\n\t\tthis.#pending.set(effect, pending_count + 1);\n\n\t\tif (blocking) {\n\t\t\tlet blocking_pending_count = this.#blocking_pending.get(effect) ?? 0;\n\t\t\tthis.#blocking_pending.set(effect, blocking_pending_count + 1);\n\t\t}\n\t}\n\n\t/**\n\t * @param {boolean} blocking\n\t * @param {Effect} effect\n\t * @param {boolean} skip - whether to skip updates (because this is triggered by a stale reaction)\n\t */\n\tdecrement(blocking, effect, skip) {\n\t\tlet pending_count = this.#pending.get(effect) ?? 0;\n\n\t\tif (pending_count === 1) {\n\t\t\tthis.#pending.delete(effect);\n\t\t} else {\n\t\t\tthis.#pending.set(effect, pending_count - 1);\n\t\t}\n\n\t\tif (blocking) {\n\t\t\tlet blocking_pending_count = this.#blocking_pending.get(effect) ?? 0;\n\n\t\t\tif (blocking_pending_count === 1) {\n\t\t\t\tthis.#blocking_pending.delete(effect);\n\t\t\t} else {\n\t\t\t\tthis.#blocking_pending.set(effect, blocking_pending_count - 1);\n\t\t\t}\n\t\t}\n\n\t\tif (this.#decrement_queued || skip) return;\n\t\tthis.#decrement_queued = true;\n\n\t\tqueue_micro_task(() => {\n\t\t\tthis.#decrement_queued = false;\n\t\t\tthis.flush();\n\t\t});\n\t}\n\n\t/**\n\t * @param {Set} dirty_effects\n\t * @param {Set} maybe_dirty_effects\n\t */\n\ttransfer_effects(dirty_effects, maybe_dirty_effects) {\n\t\tfor (const e of dirty_effects) {\n\t\t\tthis.#dirty_effects.add(e);\n\t\t}\n\n\t\tfor (const e of maybe_dirty_effects) {\n\t\t\tthis.#maybe_dirty_effects.add(e);\n\t\t}\n\n\t\tdirty_effects.clear();\n\t\tmaybe_dirty_effects.clear();\n\t}\n\n\t/** @param {(batch: Batch) => void} fn */\n\toncommit(fn) {\n\t\tthis.#commit_callbacks.add(fn);\n\t}\n\n\t/** @param {(batch: Batch) => void} fn */\n\tondiscard(fn) {\n\t\tthis.#discard_callbacks.add(fn);\n\t}\n\n\t/** @param {(batch: Batch) => void} fn */\n\ton_fork_commit(fn) {\n\t\tthis.#fork_commit_callbacks.add(fn);\n\t}\n\n\trun_fork_commit_callbacks() {\n\t\tfor (const fn of this.#fork_commit_callbacks) fn(this);\n\t\tthis.#fork_commit_callbacks.clear();\n\t}\n\n\tsettled() {\n\t\treturn (this.#deferred ??= deferred()).promise;\n\t}\n\n\tstatic ensure() {\n\t\tif (current_batch === null) {\n\t\t\tconst batch = (current_batch = new Batch());\n\n\t\t\tif (!is_processing) {\n\t\t\t\tbatches.add(current_batch);\n\n\t\t\t\tif (!is_flushing_sync) {\n\t\t\t\t\tqueue_micro_task(() => {\n\t\t\t\t\t\tif (current_batch !== batch) {\n\t\t\t\t\t\t\t// a flushSync happened in the meantime\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tbatch.flush();\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn current_batch;\n\t}\n\n\tapply() {\n\t\tif (!async_mode_flag || (!this.is_fork && batches.size === 1)) {\n\t\t\tbatch_values = null;\n\t\t\treturn;\n\t\t}\n\n\t\t// if there are multiple batches, we are 'time travelling' —\n\t\t// we need to override values with the ones in this batch...\n\t\tbatch_values = new Map();\n\t\tfor (const [source, [value]] of this.current) {\n\t\t\tbatch_values.set(source, value);\n\t\t}\n\n\t\t// ...and undo changes belonging to other batches unless they block this one\n\t\tfor (const batch of batches) {\n\t\t\tif (batch === this || batch.is_fork) continue;\n\n\t\t\t// A batch is blocked on an earlier batch if it overlaps with the earlier batch's changes but is not a superset\n\t\t\tvar intersects = false;\n\t\t\tvar differs = false;\n\n\t\t\tif (batch.id < this.id) {\n\t\t\t\tfor (const [source, [, is_derived]] of batch.current) {\n\t\t\t\t\t// Derived values don't partake in the blocking mechanism, because a derived could\n\t\t\t\t\t// be triggered in one batch already but not the other one yet, causing a false-positive\n\t\t\t\t\tif (is_derived) continue;\n\n\t\t\t\t\tintersects ||= this.current.has(source);\n\t\t\t\t\tdiffers ||= !this.current.has(source);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (intersects && differs) {\n\t\t\t\tthis.#blockers.add(batch);\n\t\t\t} else {\n\t\t\t\tfor (const [source, previous] of batch.previous) {\n\t\t\t\t\tif (!batch_values.has(source)) {\n\t\t\t\t\t\tbatch_values.set(source, previous);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t *\n\t * @param {Effect} effect\n\t */\n\tschedule(effect) {\n\t\tlast_scheduled_effect = effect;\n\n\t\t// defer render effects inside a pending boundary\n\t\t// TODO the `REACTION_RAN` check is only necessary because of legacy `$:` effects AFAICT — we can remove later\n\t\tif (\n\t\t\teffect.b?.is_pending &&\n\t\t\t(effect.f & (EFFECT | RENDER_EFFECT | MANAGED_EFFECT)) !== 0 &&\n\t\t\t(effect.f & REACTION_RAN) === 0\n\t\t) {\n\t\t\teffect.b.defer_effect(effect);\n\t\t\treturn;\n\t\t}\n\n\t\tvar e = effect;\n\n\t\twhile (e.parent !== null) {\n\t\t\te = e.parent;\n\t\t\tvar flags = e.f;\n\n\t\t\t// if the effect is being scheduled because a parent (each/await/etc) block\n\t\t\t// updated an internal source, or because a branch is being unskipped,\n\t\t\t// bail out or we'll cause a second flush\n\t\t\tif (collected_effects !== null && e === active_effect) {\n\t\t\t\tif (async_mode_flag) return;\n\n\t\t\t\t// in sync mode, render effects run during traversal. in an extreme edge case\n\t\t\t\t// — namely that we're setting a value inside a derived read during traversal —\n\t\t\t\t// they can be made dirty after they have already been visited, in which\n\t\t\t\t// case we shouldn't bail out. we also shouldn't bail out if we're\n\t\t\t\t// updating a store inside a `$:`, since this might invalidate\n\t\t\t\t// effects that were already visited\n\t\t\t\tif (\n\t\t\t\t\t(active_reaction === null || (active_reaction.f & DERIVED) === 0) &&\n\t\t\t\t\t!legacy_is_updating_store\n\t\t\t\t) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ((flags & (ROOT_EFFECT | BRANCH_EFFECT)) !== 0) {\n\t\t\t\tif ((flags & CLEAN) === 0) {\n\t\t\t\t\t// branch is already dirty, bail\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\te.f ^= CLEAN;\n\t\t\t}\n\t\t}\n\n\t\tthis.#roots.push(e);\n\t}\n}\n\n// TODO Svelte@6 think about removing the callback argument.\n/**\n * Synchronously flush any pending updates.\n * Returns void if no callback is provided, otherwise returns the result of calling the callback.\n * @template [T=void]\n * @param {(() => T) | undefined} [fn]\n * @returns {T}\n */\nexport function flushSync(fn) {\n\tvar was_flushing_sync = is_flushing_sync;\n\tis_flushing_sync = true;\n\n\ttry {\n\t\tvar result;\n\n\t\tif (fn) {\n\t\t\tif (current_batch !== null && !current_batch.is_fork) {\n\t\t\t\tcurrent_batch.flush();\n\t\t\t}\n\n\t\t\tresult = fn();\n\t\t}\n\n\t\twhile (true) {\n\t\t\tflush_tasks();\n\n\t\t\tif (current_batch === null) {\n\t\t\t\treturn /** @type {T} */ (result);\n\t\t\t}\n\n\t\t\tcurrent_batch.flush();\n\t\t}\n\t} finally {\n\t\tis_flushing_sync = was_flushing_sync;\n\t}\n}\n\nfunction infinite_loop_guard() {\n\tif (DEV) {\n\t\tvar updates = new Map();\n\n\t\tfor (const source of /** @type {Batch} */ (current_batch).current.keys()) {\n\t\t\tfor (const [stack, update] of source.updated ?? []) {\n\t\t\t\tvar entry = updates.get(stack);\n\n\t\t\t\tif (!entry) {\n\t\t\t\t\tentry = { error: update.error, count: 0 };\n\t\t\t\t\tupdates.set(stack, entry);\n\t\t\t\t}\n\n\t\t\t\tentry.count += update.count;\n\t\t\t}\n\t\t}\n\n\t\tfor (const update of updates.values()) {\n\t\t\tif (update.error) {\n\t\t\t\t// eslint-disable-next-line no-console\n\t\t\t\tconsole.error(update.error);\n\t\t\t}\n\t\t}\n\t}\n\n\ttry {\n\t\te.effect_update_depth_exceeded();\n\t} catch (error) {\n\t\tif (DEV) {\n\t\t\t// stack contains no useful information, replace it\n\t\t\tdefine_property(error, 'stack', { value: '' });\n\t\t}\n\n\t\t// Best effort: invoke the boundary nearest the most recent\n\t\t// effect and hope that it's relevant to the infinite loop\n\t\tinvoke_error_boundary(error, last_scheduled_effect);\n\t}\n}\n\n/** @type {Set | null} */\nexport let eager_block_effects = null;\n\n/**\n * @param {Array} effects\n * @returns {void}\n */\nfunction flush_queued_effects(effects) {\n\tvar length = effects.length;\n\tif (length === 0) return;\n\n\tvar i = 0;\n\n\twhile (i < length) {\n\t\tvar effect = effects[i++];\n\n\t\tif ((effect.f & (DESTROYED | INERT)) === 0 && is_dirty(effect)) {\n\t\t\teager_block_effects = new Set();\n\n\t\t\tupdate_effect(effect);\n\n\t\t\t// Effects with no dependencies or teardown do not get added to the effect tree.\n\t\t\t// Deferred effects (e.g. `$effect(...)`) _are_ added to the tree because we\n\t\t\t// don't know if we need to keep them until they are executed. Doing the check\n\t\t\t// here (rather than in `update_effect`) allows us to skip the work for\n\t\t\t// immediate effects.\n\t\t\tif (\n\t\t\t\teffect.deps === null &&\n\t\t\t\teffect.first === null &&\n\t\t\t\teffect.nodes === null &&\n\t\t\t\teffect.teardown === null &&\n\t\t\t\teffect.ac === null\n\t\t\t) {\n\t\t\t\t// remove this effect from the graph\n\t\t\t\tunlink_effect(effect);\n\t\t\t}\n\n\t\t\t// If update_effect() has a flushSync() in it, we may have flushed another flush_queued_effects(),\n\t\t\t// which already handled this logic and did set eager_block_effects to null.\n\t\t\tif (eager_block_effects?.size > 0) {\n\t\t\t\told_values.clear();\n\n\t\t\t\tfor (const e of eager_block_effects) {\n\t\t\t\t\t// Skip eager effects that have already been unmounted\n\t\t\t\t\tif ((e.f & (DESTROYED | INERT)) !== 0) continue;\n\n\t\t\t\t\t// Run effects in order from ancestor to descendant, else we could run into nullpointers\n\t\t\t\t\t/** @type {Effect[]} */\n\t\t\t\t\tconst ordered_effects = [e];\n\t\t\t\t\tlet ancestor = e.parent;\n\t\t\t\t\twhile (ancestor !== null) {\n\t\t\t\t\t\tif (eager_block_effects.has(ancestor)) {\n\t\t\t\t\t\t\teager_block_effects.delete(ancestor);\n\t\t\t\t\t\t\tordered_effects.push(ancestor);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tancestor = ancestor.parent;\n\t\t\t\t\t}\n\n\t\t\t\t\tfor (let j = ordered_effects.length - 1; j >= 0; j--) {\n\t\t\t\t\t\tconst e = ordered_effects[j];\n\t\t\t\t\t\t// Skip eager effects that have already been unmounted\n\t\t\t\t\t\tif ((e.f & (DESTROYED | INERT)) !== 0) continue;\n\t\t\t\t\t\tupdate_effect(e);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\teager_block_effects.clear();\n\t\t\t}\n\t\t}\n\t}\n\n\teager_block_effects = null;\n}\n\n/**\n * This is similar to `mark_reactions`, but it only marks async/block effects\n * depending on `value` and at least one of the other `sources`, so that\n * these effects can re-run after another batch has been committed\n * @param {Value} value\n * @param {Source[]} sources\n * @param {Set} marked\n * @param {Map} checked\n */\nfunction mark_effects(value, sources, marked, checked) {\n\tif (marked.has(value)) return;\n\tmarked.add(value);\n\n\tif (value.reactions !== null) {\n\t\tfor (const reaction of value.reactions) {\n\t\t\tconst flags = reaction.f;\n\n\t\t\tif ((flags & DERIVED) !== 0) {\n\t\t\t\tmark_effects(/** @type {Derived} */ (reaction), sources, marked, checked);\n\t\t\t} else if (\n\t\t\t\t(flags & (ASYNC | BLOCK_EFFECT)) !== 0 &&\n\t\t\t\t(flags & DIRTY) === 0 &&\n\t\t\t\tdepends_on(reaction, sources, checked)\n\t\t\t) {\n\t\t\t\tset_signal_status(reaction, DIRTY);\n\t\t\t\tschedule_effect(/** @type {Effect} */ (reaction));\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * When committing a fork, we need to trigger eager effects so that\n * any `$state.eager(...)` expressions update immediately. This\n * function allows us to discover them\n * @param {Value} value\n * @param {Set} effects\n */\nfunction mark_eager_effects(value, effects) {\n\tif (value.reactions === null) return;\n\n\tfor (const reaction of value.reactions) {\n\t\tconst flags = reaction.f;\n\n\t\tif ((flags & DERIVED) !== 0) {\n\t\t\tmark_eager_effects(/** @type {Derived} */ (reaction), effects);\n\t\t} else if ((flags & EAGER_EFFECT) !== 0) {\n\t\t\tset_signal_status(reaction, DIRTY);\n\t\t\teffects.add(/** @type {Effect} */ (reaction));\n\t\t}\n\t}\n}\n\n/**\n * @param {Reaction} reaction\n * @param {Source[]} sources\n * @param {Map} checked\n */\nfunction depends_on(reaction, sources, checked) {\n\tconst depends = checked.get(reaction);\n\tif (depends !== undefined) return depends;\n\n\tif (reaction.deps !== null) {\n\t\tfor (const dep of reaction.deps) {\n\t\t\tif (includes.call(sources, dep)) {\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tif ((dep.f & DERIVED) !== 0 && depends_on(/** @type {Derived} */ (dep), sources, checked)) {\n\t\t\t\tchecked.set(/** @type {Derived} */ (dep), true);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\n\tchecked.set(reaction, false);\n\n\treturn false;\n}\n\n/**\n * @param {Effect} effect\n * @returns {void}\n */\nexport function schedule_effect(effect) {\n\t/** @type {Batch} */ (current_batch).schedule(effect);\n}\n\n/** @type {Source[]} */\nlet eager_versions = [];\n\nfunction eager_flush() {\n\tflushSync(() => {\n\t\tconst eager = eager_versions;\n\t\teager_versions = [];\n\t\tfor (const version of eager) {\n\t\t\tupdate(version);\n\t\t}\n\t});\n}\n\n/**\n * Implementation of `$state.eager(fn())`\n * @template T\n * @param {() => T} fn\n * @returns {T}\n */\nexport function eager(fn) {\n\tvar version = source(0);\n\tvar initial = true;\n\tvar value = /** @type {T} */ (undefined);\n\n\tget(version);\n\n\teager_effect(() => {\n\t\tif (initial) {\n\t\t\t// the first time this runs, we create an eager effect\n\t\t\t// that will run eagerly whenever the expression changes\n\t\t\tvar previous_batch_values = batch_values;\n\n\t\t\ttry {\n\t\t\t\tbatch_values = null;\n\t\t\t\tvalue = fn();\n\t\t\t} finally {\n\t\t\t\tbatch_values = previous_batch_values;\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\t// the second time this effect runs, it's to schedule a\n\t\t// `version` update. since this will recreate the effect,\n\t\t// we don't need to evaluate the expression here\n\t\tif (eager_versions.length === 0) {\n\t\t\tqueue_micro_task(eager_flush);\n\t\t}\n\n\t\teager_versions.push(version);\n\t});\n\n\tinitial = false;\n\n\treturn value;\n}\n\n/**\n * Mark all the effects inside a skipped branch CLEAN, so that\n * they can be correctly rescheduled later. Tracks dirty and maybe_dirty\n * effects so they can be rescheduled if the branch survives.\n * @param {Effect} effect\n * @param {{ d: Effect[], m: Effect[] }} tracked\n */\nfunction reset_branch(effect, tracked) {\n\t// clean branch = nothing dirty inside, no need to traverse further\n\tif ((effect.f & BRANCH_EFFECT) !== 0 && (effect.f & CLEAN) !== 0) {\n\t\treturn;\n\t}\n\n\tif ((effect.f & DIRTY) !== 0) {\n\t\ttracked.d.push(effect);\n\t} else if ((effect.f & MAYBE_DIRTY) !== 0) {\n\t\ttracked.m.push(effect);\n\t}\n\n\tset_signal_status(effect, CLEAN);\n\n\tvar e = effect.first;\n\twhile (e !== null) {\n\t\treset_branch(e, tracked);\n\t\te = e.next;\n\t}\n}\n\n/**\n * Mark an entire effect tree clean following an error\n * @param {Effect} effect\n */\nfunction reset_all(effect) {\n\tset_signal_status(effect, CLEAN);\n\n\tvar e = effect.first;\n\twhile (e !== null) {\n\t\treset_all(e);\n\t\te = e.next;\n\t}\n}\n\n/**\n * Creates a 'fork', in which state changes are evaluated but not applied to the DOM.\n * This is useful for speculatively loading data (for example) when you suspect that\n * the user is about to take some action.\n *\n * Frameworks like SvelteKit can use this to preload data when the user touches or\n * hovers over a link, making any subsequent navigation feel instantaneous.\n *\n * The `fn` parameter is a synchronous function that modifies some state. The\n * state changes will be reverted after the fork is initialised, then reapplied\n * if and when the fork is eventually committed.\n *\n * When it becomes clear that a fork will _not_ be committed (e.g. because the\n * user navigated elsewhere), it must be discarded to avoid leaking memory.\n *\n * @param {() => void} fn\n * @returns {Fork}\n * @since 5.42\n */\nexport function fork(fn) {\n\tif (!async_mode_flag) {\n\t\te.experimental_async_required('fork');\n\t}\n\n\tif (current_batch !== null) {\n\t\te.fork_timing();\n\t}\n\n\tvar batch = Batch.ensure();\n\tbatch.is_fork = true;\n\tbatch_values = new Map();\n\n\tvar committed = false;\n\tvar settled = batch.settled();\n\n\tflushSync(fn);\n\n\treturn {\n\t\tcommit: async () => {\n\t\t\tif (committed) {\n\t\t\t\tawait settled;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (!batches.has(batch)) {\n\t\t\t\te.fork_discarded();\n\t\t\t}\n\n\t\t\tcommitted = true;\n\n\t\t\tbatch.is_fork = false;\n\n\t\t\t// apply changes and update write versions so deriveds see the change\n\t\t\tfor (var [source, [value]] of batch.current) {\n\t\t\t\tsource.v = value;\n\t\t\t\tsource.wv = increment_write_version();\n\t\t\t}\n\n\t\t\tbatch.activate();\n\t\t\tbatch.run_fork_commit_callbacks();\n\t\t\tbatch.deactivate();\n\n\t\t\t// trigger any `$state.eager(...)` expressions with the new state.\n\t\t\t// eager effects don't get scheduled like other effects, so we\n\t\t\t// can't just encounter them during traversal, we need to\n\t\t\t// proactively flush them\n\t\t\t// TODO maybe there's a better implementation?\n\t\t\tflushSync(() => {\n\t\t\t\t/** @type {Set} */\n\t\t\t\tvar eager_effects = new Set();\n\n\t\t\t\tfor (var source of batch.current.keys()) {\n\t\t\t\t\tmark_eager_effects(source, eager_effects);\n\t\t\t\t}\n\n\t\t\t\tset_eager_effects(eager_effects);\n\t\t\t\tflush_eager_effects();\n\t\t\t});\n\n\t\t\tbatch.flush();\n\t\t\tawait settled;\n\t\t},\n\t\tdiscard: () => {\n\t\t\t// cause any MAYBE_DIRTY deriveds to update\n\t\t\t// if they depend on things thath changed\n\t\t\t// inside the discarded fork\n\t\t\tfor (var source of batch.current.keys()) {\n\t\t\t\tsource.wv = increment_write_version();\n\t\t\t}\n\n\t\t\tif (!committed && batches.has(batch)) {\n\t\t\t\tbatch.discard();\n\t\t\t}\n\t\t}\n\t};\n}\n\n/**\n * Forcibly remove all current batches, to prevent cross-talk between tests\n */\nexport function clear() {\n\tbatches.clear();\n}\n","import { get, tick, untrack } from '../internal/client/runtime.js';\nimport { effect_tracking, render_effect } from '../internal/client/reactivity/effects.js';\nimport { source, increment } from '../internal/client/reactivity/sources.js';\nimport { tag } from '../internal/client/dev/tracing.js';\nimport { DEV } from 'esm-env';\nimport { queue_micro_task } from '../internal/client/dom/task.js';\n\n/**\n * Returns a `subscribe` function that integrates external event-based systems with Svelte's reactivity.\n * It's particularly useful for integrating with web APIs like `MediaQuery`, `IntersectionObserver`, or `WebSocket`.\n *\n * If `subscribe` is called inside an effect (including indirectly, for example inside a getter),\n * the `start` callback will be called with an `update` function. Whenever `update` is called, the effect re-runs.\n *\n * If `start` returns a cleanup function, it will be called when the effect is destroyed.\n *\n * If `subscribe` is called in multiple effects, `start` will only be called once as long as the effects\n * are active, and the returned teardown function will only be called when all effects are destroyed.\n *\n * It's best understood with an example. Here's an implementation of [`MediaQuery`](https://svelte.dev/docs/svelte/svelte-reactivity#MediaQuery):\n *\n * ```js\n * import { createSubscriber } from 'svelte/reactivity';\n * import { on } from 'svelte/events';\n *\n * export class MediaQuery {\n * \t#query;\n * \t#subscribe;\n *\n * \tconstructor(query) {\n * \t\tthis.#query = window.matchMedia(`(${query})`);\n *\n * \t\tthis.#subscribe = createSubscriber((update) => {\n * \t\t\t// when the `change` event occurs, re-run any effects that read `this.current`\n * \t\t\tconst off = on(this.#query, 'change', update);\n *\n * \t\t\t// stop listening when all the effects are destroyed\n * \t\t\treturn () => off();\n * \t\t});\n * \t}\n *\n * \tget current() {\n * \t\t// This makes the getter reactive, if read in an effect\n * \t\tthis.#subscribe();\n *\n * \t\t// Return the current state of the query, whether or not we're in an effect\n * \t\treturn this.#query.matches;\n * \t}\n * }\n * ```\n * @param {(update: () => void) => (() => void) | void} start\n * @since 5.7.0\n */\nexport function createSubscriber(start) {\n\tlet subscribers = 0;\n\tlet version = source(0);\n\t/** @type {(() => void) | void} */\n\tlet stop;\n\n\tif (DEV) {\n\t\ttag(version, 'createSubscriber version');\n\t}\n\n\treturn () => {\n\t\tif (effect_tracking()) {\n\t\t\tget(version);\n\n\t\t\trender_effect(() => {\n\t\t\t\tif (subscribers === 0) {\n\t\t\t\t\tstop = untrack(() => start(() => increment(version)));\n\t\t\t\t}\n\n\t\t\t\tsubscribers += 1;\n\n\t\t\t\treturn () => {\n\t\t\t\t\tqueue_micro_task(() => {\n\t\t\t\t\t\t// Only count down after a microtask, else we would reach 0 before our own render effect reruns,\n\t\t\t\t\t\t// but reach 1 again when the tick callback of the prior teardown runs. That would mean we\n\t\t\t\t\t\t// re-subcribe unnecessarily and create a memory leak because the old subscription is never cleaned up.\n\t\t\t\t\t\tsubscribers -= 1;\n\n\t\t\t\t\t\tif (subscribers === 0) {\n\t\t\t\t\t\t\tstop?.();\n\t\t\t\t\t\t\tstop = undefined;\n\t\t\t\t\t\t\t// Increment the version to ensure any dependent deriveds are marked dirty when the subscription is picked up again later.\n\t\t\t\t\t\t\t// If we didn't do this then the comparison of write versions would determine that the derived has a later version than\n\t\t\t\t\t\t\t// the subscriber, and it would not be re-run.\n\t\t\t\t\t\t\tincrement(version);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t};\n\t\t\t});\n\t\t}\n\t};\n}\n","/** @import { Effect, Source, TemplateNode, } from '#client' */\nimport {\n\tBOUNDARY_EFFECT,\n\tDIRTY,\n\tEFFECT_PRESERVED,\n\tEFFECT_TRANSPARENT,\n\tMAYBE_DIRTY\n} from '#client/constants';\nimport { HYDRATION_START_ELSE, HYDRATION_START_FAILED } from '../../../../constants.js';\nimport { component_context, set_component_context } from '../../context.js';\nimport { handle_error, invoke_error_boundary } from '../../error-handling.js';\nimport {\n\tblock,\n\tbranch,\n\tdestroy_effect,\n\tmove_effect,\n\tpause_effect\n} from '../../reactivity/effects.js';\nimport {\n\tactive_effect,\n\tactive_reaction,\n\tget,\n\tset_active_effect,\n\tset_active_reaction\n} from '../../runtime.js';\nimport {\n\thydrate_next,\n\thydrate_node,\n\thydrating,\n\tnext,\n\tskip_nodes,\n\tset_hydrate_node\n} from '../hydration.js';\nimport { queue_micro_task } from '../task.js';\nimport * as e from '../../errors.js';\nimport * as w from '../../warnings.js';\nimport { DEV } from 'esm-env';\nimport { Batch, current_batch, previous_batch, schedule_effect } from '../../reactivity/batch.js';\nimport { internal_set, source } from '../../reactivity/sources.js';\nimport { tag } from '../../dev/tracing.js';\nimport { createSubscriber } from '../../../../reactivity/create-subscriber.js';\nimport { create_text } from '../operations.js';\nimport { defer_effect } from '../../reactivity/utils.js';\nimport { set_signal_status } from '../../reactivity/status.js';\n\n/**\n * @typedef {{\n * \t onerror?: (error: unknown, reset: () => void) => void;\n * failed?: (anchor: Node, error: () => unknown, reset: () => () => void) => void;\n * pending?: (anchor: Node) => void;\n * }} BoundaryProps\n */\n\nvar flags = EFFECT_TRANSPARENT | EFFECT_PRESERVED;\n\n/**\n * @param {TemplateNode} node\n * @param {BoundaryProps} props\n * @param {((anchor: Node) => void)} children\n * @param {((error: unknown) => unknown) | undefined} [transform_error]\n * @returns {void}\n */\nexport function boundary(node, props, children, transform_error) {\n\tnew Boundary(node, props, children, transform_error);\n}\n\nexport class Boundary {\n\t/** @type {Boundary | null} */\n\tparent;\n\n\tis_pending = false;\n\n\t/**\n\t * API-level transformError transform function. Transforms errors before they reach the `failed` snippet.\n\t * Inherited from parent boundary, or defaults to identity.\n\t * @type {(error: unknown) => unknown}\n\t */\n\ttransform_error;\n\n\t/** @type {TemplateNode} */\n\t#anchor;\n\n\t/** @type {TemplateNode | null} */\n\t#hydrate_open = hydrating ? hydrate_node : null;\n\n\t/** @type {BoundaryProps} */\n\t#props;\n\n\t/** @type {((anchor: Node) => void)} */\n\t#children;\n\n\t/** @type {Effect} */\n\t#effect;\n\n\t/** @type {Effect | null} */\n\t#main_effect = null;\n\n\t/** @type {Effect | null} */\n\t#pending_effect = null;\n\n\t/** @type {Effect | null} */\n\t#failed_effect = null;\n\n\t/** @type {DocumentFragment | null} */\n\t#offscreen_fragment = null;\n\n\t#local_pending_count = 0;\n\t#pending_count = 0;\n\t#pending_count_update_queued = false;\n\n\t/** @type {Set} */\n\t#dirty_effects = new Set();\n\n\t/** @type {Set} */\n\t#maybe_dirty_effects = new Set();\n\n\t/**\n\t * A source containing the number of pending async deriveds/expressions.\n\t * Only created if `$effect.pending()` is used inside the boundary,\n\t * otherwise updating the source results in needless `Batch.ensure()`\n\t * calls followed by no-op flushes\n\t * @type {Source | null}\n\t */\n\t#effect_pending = null;\n\n\t#effect_pending_subscriber = createSubscriber(() => {\n\t\tthis.#effect_pending = source(this.#local_pending_count);\n\n\t\tif (DEV) {\n\t\t\ttag(this.#effect_pending, '$effect.pending()');\n\t\t}\n\n\t\treturn () => {\n\t\t\tthis.#effect_pending = null;\n\t\t};\n\t});\n\n\t/**\n\t * @param {TemplateNode} node\n\t * @param {BoundaryProps} props\n\t * @param {((anchor: Node) => void)} children\n\t * @param {((error: unknown) => unknown) | undefined} [transform_error]\n\t */\n\tconstructor(node, props, children, transform_error) {\n\t\tthis.#anchor = node;\n\t\tthis.#props = props;\n\n\t\tthis.#children = (anchor) => {\n\t\t\tvar effect = /** @type {Effect} */ (active_effect);\n\n\t\t\teffect.b = this;\n\t\t\teffect.f |= BOUNDARY_EFFECT;\n\n\t\t\tchildren(anchor);\n\t\t};\n\n\t\tthis.parent = /** @type {Effect} */ (active_effect).b;\n\n\t\t// Inherit transform_error from parent boundary, or use the provided one, or default to identity\n\t\tthis.transform_error = transform_error ?? this.parent?.transform_error ?? ((e) => e);\n\n\t\tthis.#effect = block(() => {\n\t\t\tif (hydrating) {\n\t\t\t\tconst comment = /** @type {Comment} */ (this.#hydrate_open);\n\t\t\t\thydrate_next();\n\n\t\t\t\tconst server_rendered_pending = comment.data === HYDRATION_START_ELSE;\n\t\t\t\tconst server_rendered_failed = comment.data.startsWith(HYDRATION_START_FAILED);\n\n\t\t\t\tif (server_rendered_failed) {\n\t\t\t\t\t// Server rendered the failed snippet - hydrate it.\n\t\t\t\t\t// The serialized error is embedded in the comment: \n\t\t\t\t\tconst serialized_error = JSON.parse(comment.data.slice(HYDRATION_START_FAILED.length));\n\t\t\t\t\tthis.#hydrate_failed_content(serialized_error);\n\t\t\t\t} else if (server_rendered_pending) {\n\t\t\t\t\tthis.#hydrate_pending_content();\n\t\t\t\t} else {\n\t\t\t\t\tthis.#hydrate_resolved_content();\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tthis.#render();\n\t\t\t}\n\t\t}, flags);\n\n\t\tif (hydrating) {\n\t\t\tthis.#anchor = hydrate_node;\n\t\t}\n\t}\n\n\t#hydrate_resolved_content() {\n\t\ttry {\n\t\t\tthis.#main_effect = branch(() => this.#children(this.#anchor));\n\t\t} catch (error) {\n\t\t\tthis.error(error);\n\t\t}\n\t}\n\n\t/**\n\t * @param {unknown} error The deserialized error from the server's hydration comment\n\t */\n\t#hydrate_failed_content(error) {\n\t\tconst failed = this.#props.failed;\n\t\tif (!failed) return;\n\n\t\tthis.#failed_effect = branch(() => {\n\t\t\tfailed(\n\t\t\t\tthis.#anchor,\n\t\t\t\t() => error,\n\t\t\t\t() => () => {}\n\t\t\t);\n\t\t});\n\t}\n\n\t#hydrate_pending_content() {\n\t\tconst pending = this.#props.pending;\n\t\tif (!pending) return;\n\n\t\tthis.is_pending = true;\n\t\tthis.#pending_effect = branch(() => pending(this.#anchor));\n\n\t\tqueue_micro_task(() => {\n\t\t\tvar fragment = (this.#offscreen_fragment = document.createDocumentFragment());\n\t\t\tvar anchor = create_text();\n\n\t\t\tfragment.append(anchor);\n\n\t\t\tthis.#main_effect = this.#run(() => {\n\t\t\t\treturn branch(() => this.#children(anchor));\n\t\t\t});\n\n\t\t\tif (this.#pending_count === 0) {\n\t\t\t\tthis.#anchor.before(fragment);\n\t\t\t\tthis.#offscreen_fragment = null;\n\n\t\t\t\tpause_effect(/** @type {Effect} */ (this.#pending_effect), () => {\n\t\t\t\t\tthis.#pending_effect = null;\n\t\t\t\t});\n\n\t\t\t\tthis.#resolve(/** @type {Batch} */ (current_batch));\n\t\t\t}\n\t\t});\n\t}\n\n\t#render() {\n\t\ttry {\n\t\t\tthis.is_pending = this.has_pending_snippet();\n\t\t\tthis.#pending_count = 0;\n\t\t\tthis.#local_pending_count = 0;\n\n\t\t\tthis.#main_effect = branch(() => {\n\t\t\t\tthis.#children(this.#anchor);\n\t\t\t});\n\n\t\t\tif (this.#pending_count > 0) {\n\t\t\t\tvar fragment = (this.#offscreen_fragment = document.createDocumentFragment());\n\t\t\t\tmove_effect(this.#main_effect, fragment);\n\n\t\t\t\tconst pending = /** @type {(anchor: Node) => void} */ (this.#props.pending);\n\t\t\t\tthis.#pending_effect = branch(() => pending(this.#anchor));\n\t\t\t} else {\n\t\t\t\tthis.#resolve(/** @type {Batch} */ (current_batch));\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthis.error(error);\n\t\t}\n\t}\n\n\t/**\n\t * @param {Batch} batch\n\t */\n\t#resolve(batch) {\n\t\tthis.is_pending = false;\n\n\t\t// any effects that were previously deferred should be transferred\n\t\t// to the batch, which will flush in the next microtask\n\t\tbatch.transfer_effects(this.#dirty_effects, this.#maybe_dirty_effects);\n\t}\n\n\t/**\n\t * Defer an effect inside a pending boundary until the boundary resolves\n\t * @param {Effect} effect\n\t */\n\tdefer_effect(effect) {\n\t\tdefer_effect(effect, this.#dirty_effects, this.#maybe_dirty_effects);\n\t}\n\n\t/**\n\t * Returns `false` if the effect exists inside a boundary whose pending snippet is shown\n\t * @returns {boolean}\n\t */\n\tis_rendered() {\n\t\treturn !this.is_pending && (!this.parent || this.parent.is_rendered());\n\t}\n\n\thas_pending_snippet() {\n\t\treturn !!this.#props.pending;\n\t}\n\n\t/**\n\t * @template T\n\t * @param {() => T} fn\n\t */\n\t#run(fn) {\n\t\tvar previous_effect = active_effect;\n\t\tvar previous_reaction = active_reaction;\n\t\tvar previous_ctx = component_context;\n\n\t\tset_active_effect(this.#effect);\n\t\tset_active_reaction(this.#effect);\n\t\tset_component_context(this.#effect.ctx);\n\n\t\ttry {\n\t\t\tBatch.ensure();\n\t\t\treturn fn();\n\t\t} catch (e) {\n\t\t\thandle_error(e);\n\t\t\treturn null;\n\t\t} finally {\n\t\t\tset_active_effect(previous_effect);\n\t\t\tset_active_reaction(previous_reaction);\n\t\t\tset_component_context(previous_ctx);\n\t\t}\n\t}\n\n\t/**\n\t * Updates the pending count associated with the currently visible pending snippet,\n\t * if any, such that we can replace the snippet with content once work is done\n\t * @param {1 | -1} d\n\t * @param {Batch} batch\n\t */\n\t#update_pending_count(d, batch) {\n\t\tif (!this.has_pending_snippet()) {\n\t\t\tif (this.parent) {\n\t\t\t\tthis.parent.#update_pending_count(d, batch);\n\t\t\t}\n\n\t\t\t// if there's no parent, we're in a scope with no pending snippet\n\t\t\treturn;\n\t\t}\n\n\t\tthis.#pending_count += d;\n\n\t\tif (this.#pending_count === 0) {\n\t\t\tthis.#resolve(batch);\n\n\t\t\tif (this.#pending_effect) {\n\t\t\t\tpause_effect(this.#pending_effect, () => {\n\t\t\t\t\tthis.#pending_effect = null;\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tif (this.#offscreen_fragment) {\n\t\t\t\tthis.#anchor.before(this.#offscreen_fragment);\n\t\t\t\tthis.#offscreen_fragment = null;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Update the source that powers `$effect.pending()` inside this boundary,\n\t * and controls when the current `pending` snippet (if any) is removed.\n\t * Do not call from inside the class\n\t * @param {1 | -1} d\n\t * @param {Batch} batch\n\t */\n\tupdate_pending_count(d, batch) {\n\t\tthis.#update_pending_count(d, batch);\n\n\t\tthis.#local_pending_count += d;\n\n\t\tif (!this.#effect_pending || this.#pending_count_update_queued) return;\n\t\tthis.#pending_count_update_queued = true;\n\n\t\tqueue_micro_task(() => {\n\t\t\tthis.#pending_count_update_queued = false;\n\t\t\tif (this.#effect_pending) {\n\t\t\t\tinternal_set(this.#effect_pending, this.#local_pending_count);\n\t\t\t}\n\t\t});\n\t}\n\n\tget_effect_pending() {\n\t\tthis.#effect_pending_subscriber();\n\t\treturn get(/** @type {Source} */ (this.#effect_pending));\n\t}\n\n\t/** @param {unknown} error */\n\terror(error) {\n\t\t// If we have nothing to capture the error, or if we hit an error while\n\t\t// rendering the fallback, re-throw for another boundary to handle\n\t\tif (!this.#props.onerror && !this.#props.failed) {\n\t\t\tthrow error;\n\t\t}\n\n\t\tif (current_batch?.is_fork) {\n\t\t\tif (this.#main_effect) current_batch.skip_effect(this.#main_effect);\n\t\t\tif (this.#pending_effect) current_batch.skip_effect(this.#pending_effect);\n\t\t\tif (this.#failed_effect) current_batch.skip_effect(this.#failed_effect);\n\n\t\t\tcurrent_batch.on_fork_commit(() => {\n\t\t\t\tthis.#handle_error(error);\n\t\t\t});\n\t\t} else {\n\t\t\tthis.#handle_error(error);\n\t\t}\n\t}\n\n\t/**\n\t * @param {unknown} error\n\t */\n\t#handle_error(error) {\n\t\tif (this.#main_effect) {\n\t\t\tdestroy_effect(this.#main_effect);\n\t\t\tthis.#main_effect = null;\n\t\t}\n\n\t\tif (this.#pending_effect) {\n\t\t\tdestroy_effect(this.#pending_effect);\n\t\t\tthis.#pending_effect = null;\n\t\t}\n\n\t\tif (this.#failed_effect) {\n\t\t\tdestroy_effect(this.#failed_effect);\n\t\t\tthis.#failed_effect = null;\n\t\t}\n\n\t\tif (hydrating) {\n\t\t\tset_hydrate_node(/** @type {TemplateNode} */ (this.#hydrate_open));\n\t\t\tnext();\n\t\t\tset_hydrate_node(skip_nodes());\n\t\t}\n\n\t\tvar onerror = this.#props.onerror;\n\t\tlet failed = this.#props.failed;\n\t\tvar did_reset = false;\n\t\tvar calling_on_error = false;\n\n\t\tconst reset = () => {\n\t\t\tif (did_reset) {\n\t\t\t\tw.svelte_boundary_reset_noop();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tdid_reset = true;\n\n\t\t\tif (calling_on_error) {\n\t\t\t\te.svelte_boundary_reset_onerror();\n\t\t\t}\n\n\t\t\tif (this.#failed_effect !== null) {\n\t\t\t\tpause_effect(this.#failed_effect, () => {\n\t\t\t\t\tthis.#failed_effect = null;\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tthis.#run(() => {\n\t\t\t\tthis.#render();\n\t\t\t});\n\t\t};\n\n\t\t/** @param {unknown} transformed_error */\n\t\tconst handle_error_result = (transformed_error) => {\n\t\t\ttry {\n\t\t\t\tcalling_on_error = true;\n\t\t\t\tonerror?.(transformed_error, reset);\n\t\t\t\tcalling_on_error = false;\n\t\t\t} catch (error) {\n\t\t\t\tinvoke_error_boundary(error, this.#effect && this.#effect.parent);\n\t\t\t}\n\n\t\t\tif (failed) {\n\t\t\t\tthis.#failed_effect = this.#run(() => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\treturn branch(() => {\n\t\t\t\t\t\t\t// errors in `failed` snippets cause the boundary to error again\n\t\t\t\t\t\t\t// TODO Svelte 6: revisit this decision, most likely better to go to parent boundary instead\n\t\t\t\t\t\t\tvar effect = /** @type {Effect} */ (active_effect);\n\n\t\t\t\t\t\t\teffect.b = this;\n\t\t\t\t\t\t\teffect.f |= BOUNDARY_EFFECT;\n\n\t\t\t\t\t\t\tfailed(\n\t\t\t\t\t\t\t\tthis.#anchor,\n\t\t\t\t\t\t\t\t() => transformed_error,\n\t\t\t\t\t\t\t\t() => reset\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t});\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tinvoke_error_boundary(error, /** @type {Effect} */ (this.#effect.parent));\n\t\t\t\t\t\treturn null;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t};\n\n\t\tqueue_micro_task(() => {\n\t\t\t// Run the error through the API-level transformError transform (e.g. SvelteKit's handleError)\n\t\t\t/** @type {unknown} */\n\t\t\tvar result;\n\t\t\ttry {\n\t\t\t\tresult = this.transform_error(error);\n\t\t\t} catch (e) {\n\t\t\t\tinvoke_error_boundary(e, this.#effect && this.#effect.parent);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (\n\t\t\t\tresult !== null &&\n\t\t\t\ttypeof result === 'object' &&\n\t\t\t\ttypeof (/** @type {any} */ (result).then) === 'function'\n\t\t\t) {\n\t\t\t\t// transformError returned a Promise — wait for it\n\t\t\t\t/** @type {any} */ (result).then(\n\t\t\t\t\thandle_error_result,\n\t\t\t\t\t/** @param {unknown} e */\n\t\t\t\t\t(e) => invoke_error_boundary(e, this.#effect && this.#effect.parent)\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\t// Synchronous result — handle immediately\n\t\t\t\thandle_error_result(result);\n\t\t\t}\n\t\t});\n\t}\n}\n\nexport function pending() {\n\tif (active_effect === null) {\n\t\te.effect_pending_outside_reaction();\n\t}\n\n\tvar boundary = active_effect.b;\n\n\tif (boundary === null) {\n\t\treturn 0; // TODO eventually we will need this to be global\n\t}\n\n\treturn boundary.get_effect_pending();\n}\n","/** @import { Blocker, Effect, Value } from '#client' */\nimport { DESTROYED, STALE_REACTION } from '#client/constants';\nimport { DEV } from 'esm-env';\nimport {\n\tcomponent_context,\n\tdev_stack,\n\tis_runes,\n\tset_component_context,\n\tset_dev_stack\n} from '../context.js';\nimport { Boundary } from '../dom/blocks/boundary.js';\nimport { invoke_error_boundary } from '../error-handling.js';\nimport {\n\tactive_effect,\n\tactive_reaction,\n\tset_active_effect,\n\tset_active_reaction\n} from '../runtime.js';\nimport { Batch, current_batch } from './batch.js';\nimport {\n\tasync_derived,\n\treactivity_loss_tracker,\n\tderived,\n\tderived_safe_equal,\n\tset_reactivity_loss_tracker\n} from './deriveds.js';\nimport { aborted } from './effects.js';\n\n/**\n * @param {Blocker[]} blockers\n * @param {Array<() => any>} sync\n * @param {Array<() => Promise>} async\n * @param {(values: Value[]) => any} fn\n */\nexport function flatten(blockers, sync, async, fn) {\n\tconst d = is_runes() ? derived : derived_safe_equal;\n\n\t// Filter out already-settled blockers - no need to wait for them\n\tvar pending = blockers.filter((b) => !b.settled);\n\n\tif (async.length === 0 && pending.length === 0) {\n\t\tfn(sync.map(d));\n\t\treturn;\n\t}\n\n\tvar parent = /** @type {Effect} */ (active_effect);\n\n\tvar restore = capture();\n\tvar blocker_promise =\n\t\tpending.length === 1\n\t\t\t? pending[0].promise\n\t\t\t: pending.length > 1\n\t\t\t\t? Promise.all(pending.map((b) => b.promise))\n\t\t\t\t: null;\n\n\t/** @param {Value[]} values */\n\tfunction finish(values) {\n\t\trestore();\n\n\t\ttry {\n\t\t\tfn(values);\n\t\t} catch (error) {\n\t\t\tif ((parent.f & DESTROYED) === 0) {\n\t\t\t\tinvoke_error_boundary(error, parent);\n\t\t\t}\n\t\t}\n\n\t\tunset_context();\n\t}\n\n\t// Fast path: blockers but no async expressions\n\tif (async.length === 0) {\n\t\t/** @type {Promise} */ (blocker_promise).then(() => finish(sync.map(d)));\n\t\treturn;\n\t}\n\n\tvar decrement_pending = increment_pending();\n\n\t// Full path: has async expressions\n\tfunction run() {\n\t\tPromise.all(async.map((expression) => async_derived(expression)))\n\t\t\t.then((result) => finish([...sync.map(d), ...result]))\n\t\t\t.catch((error) => invoke_error_boundary(error, parent))\n\t\t\t.finally(() => decrement_pending());\n\t}\n\n\tif (blocker_promise) {\n\t\tblocker_promise.then(() => {\n\t\t\trestore();\n\t\t\trun();\n\t\t\tunset_context();\n\t\t});\n\t} else {\n\t\trun();\n\t}\n}\n\n/**\n * @param {Blocker[]} blockers\n * @param {(values: Value[]) => any} fn\n */\nexport function run_after_blockers(blockers, fn) {\n\tflatten(blockers, [], [], fn);\n}\n\n/**\n * Captures the current effect context so that we can restore it after\n * some asynchronous work has happened (so that e.g. `await a + b`\n * causes `b` to be registered as a dependency).\n */\nexport function capture() {\n\tvar previous_effect = /** @type {Effect} */ (active_effect);\n\tvar previous_reaction = active_reaction;\n\tvar previous_component_context = component_context;\n\tvar previous_batch = /** @type {Batch} */ (current_batch);\n\n\tif (DEV) {\n\t\tvar previous_dev_stack = dev_stack;\n\t}\n\n\treturn function restore(activate_batch = true) {\n\t\tset_active_effect(previous_effect);\n\t\tset_active_reaction(previous_reaction);\n\t\tset_component_context(previous_component_context);\n\n\t\tif (activate_batch && (previous_effect.f & DESTROYED) === 0) {\n\t\t\t// TODO we only need optional chaining here because `{#await ...}` blocks\n\t\t\t// are anomalous. Once we retire them we can get rid of it\n\t\t\tprevious_batch?.activate();\n\t\t\tprevious_batch?.apply();\n\t\t}\n\n\t\tif (DEV) {\n\t\t\tset_reactivity_loss_tracker(null);\n\t\t\tset_dev_stack(previous_dev_stack);\n\t\t}\n\t};\n}\n\n/**\n * Wraps an `await` expression in such a way that the effect context that was\n * active before the expression evaluated can be reapplied afterwards —\n * `await a + b` becomes `(await $.save(a))() + b`\n * @template T\n * @param {Promise} promise\n * @returns {Promise<() => T>}\n */\nexport async function save(promise) {\n\tvar restore = capture();\n\tvar value = await promise;\n\n\treturn () => {\n\t\trestore();\n\t\treturn value;\n\t};\n}\n\n/**\n * Reset `current_async_effect` after the `promise` resolves, so\n * that we can emit `await_reactivity_loss` warnings\n * @template T\n * @param {Promise} promise\n * @returns {Promise<() => T>}\n */\nexport async function track_reactivity_loss(promise) {\n\tvar previous_async_effect = reactivity_loss_tracker;\n\t// Ensure that unrelated reads after an async operation is kicked off don't cause false positives\n\tqueueMicrotask(() => {\n\t\tif (reactivity_loss_tracker === previous_async_effect) {\n\t\t\tset_reactivity_loss_tracker(null);\n\t\t}\n\t});\n\n\tvar value = await promise;\n\n\treturn () => {\n\t\tset_reactivity_loss_tracker(previous_async_effect);\n\t\t// While this can result in false negatives it also guards against the more important\n\t\t// false positives that would occur if this is the last in a chain of async operations,\n\t\t// and the reactivity_loss_tracker would then stay around until the next async operation happens.\n\t\tqueueMicrotask(() => {\n\t\t\tif (reactivity_loss_tracker === previous_async_effect) {\n\t\t\t\tset_reactivity_loss_tracker(null);\n\t\t\t}\n\t\t});\n\n\t\treturn value;\n\t};\n}\n\n/**\n * Used in `for await` loops in DEV, so\n * that we can emit `await_reactivity_loss` warnings\n * after each `async_iterator` result resolves and\n * after the `async_iterator` return resolves (if it runs)\n * @template T\n * @template TReturn\n * @param {Iterable | AsyncIterable} iterable\n * @returns {AsyncGenerator}\n */\nexport async function* for_await_track_reactivity_loss(iterable) {\n\t// This is based on the algorithms described in ECMA-262:\n\t// ForIn/OfBodyEvaluation\n\t// https://tc39.es/ecma262/multipage/ecmascript-language-statements-and-declarations.html#sec-runtime-semantics-forin-div-ofbodyevaluation-lhs-stmt-iterator-lhskind-labelset\n\t// AsyncIteratorClose\n\t// https://tc39.es/ecma262/multipage/abstract-operations.html#sec-asynciteratorclose\n\n\t/** @type {AsyncIterator} */\n\t// @ts-ignore\n\tconst iterator = iterable[Symbol.asyncIterator]?.() ?? iterable[Symbol.iterator]?.();\n\n\tif (iterator === undefined) {\n\t\tthrow new TypeError('value is not async iterable');\n\t}\n\n\t/** Whether the completion of the iterator was \"normal\", meaning it wasn't ended via `break` or a similar method */\n\tlet normal_completion = false;\n\ttry {\n\t\twhile (true) {\n\t\t\tconst { done, value } = (await track_reactivity_loss(iterator.next()))();\n\t\t\tif (done) {\n\t\t\t\tnormal_completion = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tvar prev = reactivity_loss_tracker;\n\t\t\tyield value;\n\t\t\tset_reactivity_loss_tracker(prev);\n\t\t}\n\t} finally {\n\t\t// If the iterator had an abrupt completion and `return` is defined on the iterator, call it and return the value\n\t\tif (!normal_completion && iterator.return !== undefined) {\n\t\t\t// eslint-disable-next-line no-unsafe-finally\n\t\t\treturn /** @type {TReturn} */ ((await track_reactivity_loss(iterator.return()))().value);\n\t\t}\n\t}\n}\n\nexport function unset_context(deactivate_batch = true) {\n\tset_active_effect(null);\n\tset_active_reaction(null);\n\tset_component_context(null);\n\tif (deactivate_batch) current_batch?.deactivate();\n\n\tif (DEV) {\n\t\tset_reactivity_loss_tracker(null);\n\t\tset_dev_stack(null);\n\t}\n}\n\n/**\n * @param {Array<() => void | Promise>} thunks\n */\nexport function run(thunks) {\n\tconst restore = capture();\n\n\tconst decrement_pending = increment_pending();\n\n\tvar active = /** @type {Effect} */ (active_effect);\n\n\t/** @type {null | { error: any }} */\n\tvar errored = null;\n\n\t/** @param {any} error */\n\tconst handle_error = (error) => {\n\t\terrored = { error }; // wrap in object in case a promise rejects with a falsy value\n\n\t\tif (!aborted(active)) {\n\t\t\tinvoke_error_boundary(error, active);\n\t\t}\n\t};\n\n\tvar promise = Promise.resolve(thunks[0]()).catch(handle_error);\n\n\t/** @type {Blocker} */\n\tvar blocker = { promise, settled: false };\n\tvar blockers = [blocker];\n\n\tpromise.finally(() => {\n\t\tblocker.settled = true;\n\t\tunset_context();\n\t});\n\n\tfor (const fn of thunks.slice(1)) {\n\t\tpromise = promise\n\t\t\t.then(() => {\n\t\t\t\trestore();\n\n\t\t\t\tif (errored) {\n\t\t\t\t\tthrow errored.error;\n\t\t\t\t}\n\n\t\t\t\tif (aborted(active)) {\n\t\t\t\t\tthrow STALE_REACTION;\n\t\t\t\t}\n\n\t\t\t\treturn fn();\n\t\t\t})\n\t\t\t.catch(handle_error);\n\n\t\tconst blocker = { promise, settled: false };\n\t\tblockers.push(blocker);\n\n\t\tpromise.finally(() => {\n\t\t\tblocker.settled = true;\n\t\t\tunset_context();\n\t\t});\n\t}\n\n\tpromise\n\t\t// wait one more tick, so that template effects are\n\t\t// guaranteed to run before `$effect(...)`\n\t\t.then(() => Promise.resolve())\n\t\t.finally(() => decrement_pending());\n\n\treturn blockers;\n}\n\n/**\n * @param {Blocker[]} blockers\n */\nexport function wait(blockers) {\n\treturn Promise.all(blockers.map((b) => b.promise));\n}\n\n/**\n * @returns {(skip?: boolean) => void}\n */\nexport function increment_pending() {\n\tvar effect = /** @type {Effect} */ (active_effect);\n\tvar boundary = /** @type {Boundary} */ (effect.b);\n\tvar batch = /** @type {Batch} */ (current_batch);\n\tvar blocking = boundary.is_rendered();\n\n\tboundary.update_pending_count(1, batch);\n\tbatch.increment(blocking, effect);\n\n\treturn (skip = false) => {\n\t\tboundary.update_pending_count(-1, batch);\n\t\tbatch.decrement(blocking, effect, skip);\n\t};\n}\n","/** @import { Derived, Effect, Reaction, Source, Value } from '#client' */\n/** @import { Batch } from './batch.js'; */\n/** @import { Boundary } from '../dom/blocks/boundary.js'; */\nimport { DEV } from 'esm-env';\nimport {\n\tERROR_VALUE,\n\tDERIVED,\n\tDIRTY,\n\tEFFECT_PRESERVED,\n\tSTALE_REACTION,\n\tASYNC,\n\tWAS_MARKED,\n\tDESTROYED,\n\tCLEAN,\n\tREACTION_RAN,\n\tINERT\n} from '#client/constants';\nimport {\n\tactive_reaction,\n\tactive_effect,\n\tupdate_reaction,\n\tincrement_write_version,\n\tset_active_effect,\n\tpush_reaction_value,\n\tis_destroying_effect,\n\tupdate_effect,\n\tremove_reactions,\n\tskipped_deps,\n\tnew_deps\n} from '../runtime.js';\nimport { equals, safe_equals } from './equality.js';\nimport * as e from '../errors.js';\nimport * as w from '../warnings.js';\nimport {\n\tasync_effect,\n\tdestroy_effect,\n\tdestroy_effect_children,\n\teffect_tracking,\n\tteardown\n} from './effects.js';\nimport { eager_effects, internal_set, set_eager_effects, source } from './sources.js';\nimport { get_error } from '../../shared/dev.js';\nimport { async_mode_flag, tracing_mode_flag } from '../../flags/index.js';\nimport { component_context } from '../context.js';\nimport { UNINITIALIZED } from '../../../constants.js';\nimport { batch_values, current_batch } from './batch.js';\nimport { increment_pending, unset_context } from './async.js';\nimport { deferred, includes, noop } from '../../shared/utils.js';\nimport { set_signal_status, update_derived_status } from './status.js';\n\n/**\n * This allows us to track 'reactivity loss' that occurs when signals\n * are read after a non-context-restoring `await`. Dev-only\n * @type {{ effect: Effect, effect_deps: Set, warned: boolean } | null}\n */\nexport let reactivity_loss_tracker = null;\n\n/** @param {{ effect: Effect, effect_deps: Set, warned: boolean } | null} v */\nexport function set_reactivity_loss_tracker(v) {\n\treactivity_loss_tracker = v;\n}\n\nexport const recent_async_deriveds = new Set();\n\n/**\n * @template V\n * @param {() => V} fn\n * @returns {Derived}\n */\n/*#__NO_SIDE_EFFECTS__*/\nexport function derived(fn) {\n\tvar flags = DERIVED | DIRTY;\n\n\tif (active_effect !== null) {\n\t\t// Since deriveds are evaluated lazily, any effects created inside them are\n\t\t// created too late to ensure that the parent effect is added to the tree\n\t\tactive_effect.f |= EFFECT_PRESERVED;\n\t}\n\n\t/** @type {Derived} */\n\tconst signal = {\n\t\tctx: component_context,\n\t\tdeps: null,\n\t\teffects: null,\n\t\tequals,\n\t\tf: flags,\n\t\tfn,\n\t\treactions: null,\n\t\trv: 0,\n\t\tv: /** @type {V} */ (UNINITIALIZED),\n\t\twv: 0,\n\t\tparent: active_effect,\n\t\tac: null\n\t};\n\n\tif (DEV && tracing_mode_flag) {\n\t\tsignal.created = get_error('created at');\n\t}\n\n\treturn signal;\n}\n\n/**\n * @template V\n * @param {() => V | Promise} fn\n * @param {string} [label]\n * @param {string} [location] If provided, print a warning if the value is not read immediately after update\n * @returns {Promise>}\n */\n/*#__NO_SIDE_EFFECTS__*/\nexport function async_derived(fn, label, location) {\n\tlet parent = /** @type {Effect | null} */ (active_effect);\n\n\tif (parent === null) {\n\t\te.async_derived_orphan();\n\t}\n\n\tvar promise = /** @type {Promise} */ (/** @type {unknown} */ (undefined));\n\tvar signal = source(/** @type {V} */ (UNINITIALIZED));\n\n\tif (DEV) signal.label = label;\n\n\t// only suspend in async deriveds created on initialisation\n\tvar should_suspend = !active_reaction;\n\n\t/** @type {Map>>} */\n\tvar deferreds = new Map();\n\n\tasync_effect(() => {\n\t\tvar effect = /** @type {Effect} */ (active_effect);\n\n\t\tif (DEV) {\n\t\t\treactivity_loss_tracker = { effect, effect_deps: new Set(), warned: false };\n\t\t}\n\n\t\t/** @type {ReturnType>} */\n\t\tvar d = deferred();\n\t\tpromise = d.promise;\n\n\t\ttry {\n\t\t\t// If this code is changed at some point, make sure to still access the then property\n\t\t\t// of fn() to read any signals it might access, so that we track them as dependencies.\n\t\t\t// We call `unset_context` to undo any `save` calls that happen inside `fn()`\n\t\t\tPromise.resolve(fn()).then(d.resolve, d.reject).finally(unset_context);\n\t\t} catch (error) {\n\t\t\td.reject(error);\n\t\t\tunset_context();\n\t\t}\n\n\t\tif (DEV) {\n\t\t\tif (reactivity_loss_tracker) {\n\t\t\t\t// Reused deps from previous run (indices 0 to skipped_deps-1)\n\t\t\t\t// We deliberately only track direct dependencies of the async expression to encourage\n\t\t\t\t// dependencies being directly visible at the point of the expression\n\t\t\t\tif (effect.deps !== null) {\n\t\t\t\t\tfor (let i = 0; i < skipped_deps; i += 1) {\n\t\t\t\t\t\treactivity_loss_tracker.effect_deps.add(effect.deps[i]);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// New deps discovered this run\n\t\t\t\tif (new_deps !== null) {\n\t\t\t\t\tfor (let i = 0; i < new_deps.length; i += 1) {\n\t\t\t\t\t\treactivity_loss_tracker.effect_deps.add(new_deps[i]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treactivity_loss_tracker = null;\n\t\t}\n\n\t\tvar batch = /** @type {Batch} */ (current_batch);\n\n\t\tif (should_suspend) {\n\t\t\t// we only increment the batch's pending state for updates, not creation, otherwise\n\t\t\t// we will decrement to zero before the work that depends on this promise (e.g. a\n\t\t\t// template effect) has initialized, causing the batch to resolve prematurely\n\t\t\tif ((effect.f & REACTION_RAN) !== 0) {\n\t\t\t\tvar decrement_pending = increment_pending();\n\t\t\t}\n\n\t\t\tif (/** @type {Boundary} */ (parent.b).is_rendered()) {\n\t\t\t\tdeferreds.get(batch)?.reject(STALE_REACTION);\n\t\t\t\tdeferreds.delete(batch); // delete to ensure correct order in Map iteration below\n\t\t\t} else {\n\t\t\t\t// While the boundary is still showing pending, a new run supersedes all older in-flight runs\n\t\t\t\t// for this async expression. Cancel eagerly so resolution cannot commit stale values.\n\t\t\t\tfor (const d of deferreds.values()) {\n\t\t\t\t\td.reject(STALE_REACTION);\n\t\t\t\t}\n\t\t\t\tdeferreds.clear();\n\t\t\t}\n\n\t\t\tdeferreds.set(batch, d);\n\t\t}\n\n\t\t/**\n\t\t * @param {any} value\n\t\t * @param {unknown} error\n\t\t */\n\t\tconst handler = (value, error = undefined) => {\n\t\t\tif (DEV) {\n\t\t\t\treactivity_loss_tracker = null;\n\t\t\t}\n\n\t\t\tif (decrement_pending) {\n\t\t\t\t// don't trigger an update if we're only here because\n\t\t\t\t// the promise was superseded before it could resolve\n\t\t\t\tvar skip = error === STALE_REACTION;\n\t\t\t\tdecrement_pending(skip);\n\t\t\t}\n\n\t\t\tif (error === STALE_REACTION || (effect.f & DESTROYED) !== 0) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tbatch.activate();\n\n\t\t\tif (error) {\n\t\t\t\tsignal.f |= ERROR_VALUE;\n\n\t\t\t\t// @ts-expect-error the error is the wrong type, but we don't care\n\t\t\t\tinternal_set(signal, error);\n\t\t\t} else {\n\t\t\t\tif ((signal.f & ERROR_VALUE) !== 0) {\n\t\t\t\t\tsignal.f ^= ERROR_VALUE;\n\t\t\t\t}\n\n\t\t\t\tinternal_set(signal, value);\n\n\t\t\t\t// All prior async derived runs are now stale\n\t\t\t\tfor (const [b, d] of deferreds) {\n\t\t\t\t\tdeferreds.delete(b);\n\t\t\t\t\tif (b === batch) break;\n\t\t\t\t\td.reject(STALE_REACTION);\n\t\t\t\t}\n\n\t\t\t\tif (DEV && location !== undefined) {\n\t\t\t\t\trecent_async_deriveds.add(signal);\n\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tif (recent_async_deriveds.has(signal)) {\n\t\t\t\t\t\t\tw.await_waterfall(/** @type {string} */ (signal.label), location);\n\t\t\t\t\t\t\trecent_async_deriveds.delete(signal);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tbatch.deactivate();\n\t\t};\n\n\t\td.promise.then(handler, (e) => handler(null, e || 'unknown'));\n\t});\n\n\tteardown(() => {\n\t\tfor (const d of deferreds.values()) {\n\t\t\td.reject(STALE_REACTION);\n\t\t}\n\t});\n\n\tif (DEV) {\n\t\t// add a flag that lets this be printed as a derived\n\t\t// when using `$inspect.trace()`\n\t\tsignal.f |= ASYNC;\n\t}\n\n\treturn new Promise((fulfil) => {\n\t\t/** @param {Promise} p */\n\t\tfunction next(p) {\n\t\t\tfunction go() {\n\t\t\t\tif (p === promise) {\n\t\t\t\t\tfulfil(signal);\n\t\t\t\t} else {\n\t\t\t\t\t// if the effect re-runs before the initial promise\n\t\t\t\t\t// resolves, delay resolution until we have a value\n\t\t\t\t\tnext(promise);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tp.then(go, go);\n\t\t}\n\n\t\tnext(promise);\n\t});\n}\n\n/**\n * @template V\n * @param {() => V} fn\n * @returns {Derived}\n */\n/*#__NO_SIDE_EFFECTS__*/\nexport function user_derived(fn) {\n\tconst d = derived(fn);\n\n\tif (!async_mode_flag) push_reaction_value(d);\n\n\treturn d;\n}\n\n/**\n * @template V\n * @param {() => V} fn\n * @returns {Derived}\n */\n/*#__NO_SIDE_EFFECTS__*/\nexport function derived_safe_equal(fn) {\n\tconst signal = derived(fn);\n\tsignal.equals = safe_equals;\n\treturn signal;\n}\n\n/**\n * @param {Derived} derived\n * @returns {void}\n */\nexport function destroy_derived_effects(derived) {\n\tvar effects = derived.effects;\n\n\tif (effects !== null) {\n\t\tderived.effects = null;\n\n\t\tfor (var i = 0; i < effects.length; i += 1) {\n\t\t\tdestroy_effect(/** @type {Effect} */ (effects[i]));\n\t\t}\n\t}\n}\n\n/**\n * The currently updating deriveds, used to detect infinite recursion\n * in dev mode and provide a nicer error than 'too much recursion'\n * @type {Derived[]}\n */\nlet stack = [];\n\n/**\n * @template T\n * @param {Derived} derived\n * @returns {T}\n */\nexport function execute_derived(derived) {\n\tvar value;\n\tvar prev_active_effect = active_effect;\n\tvar parent = derived.parent;\n\n\tif (!is_destroying_effect && parent !== null && (parent.f & (DESTROYED | INERT)) !== 0) {\n\t\tw.derived_inert();\n\n\t\treturn derived.v;\n\t}\n\n\tset_active_effect(parent);\n\n\tif (DEV) {\n\t\tlet prev_eager_effects = eager_effects;\n\t\tset_eager_effects(new Set());\n\t\ttry {\n\t\t\tif (includes.call(stack, derived)) {\n\t\t\t\te.derived_references_self();\n\t\t\t}\n\n\t\t\tstack.push(derived);\n\n\t\t\tderived.f &= ~WAS_MARKED;\n\t\t\tdestroy_derived_effects(derived);\n\t\t\tvalue = update_reaction(derived);\n\t\t} finally {\n\t\t\tset_active_effect(prev_active_effect);\n\t\t\tset_eager_effects(prev_eager_effects);\n\t\t\tstack.pop();\n\t\t}\n\t} else {\n\t\ttry {\n\t\t\tderived.f &= ~WAS_MARKED;\n\t\t\tdestroy_derived_effects(derived);\n\t\t\tvalue = update_reaction(derived);\n\t\t} finally {\n\t\t\tset_active_effect(prev_active_effect);\n\t\t}\n\t}\n\n\treturn value;\n}\n\n/**\n * @param {Derived} derived\n * @returns {void}\n */\nexport function update_derived(derived) {\n\tvar value = execute_derived(derived);\n\n\tif (!derived.equals(value)) {\n\t\tderived.wv = increment_write_version();\n\n\t\t// in a fork, we don't update the underlying value, just `batch_values`.\n\t\t// the underlying value will be updated when the fork is committed.\n\t\t// otherwise, the next time we get here after a 'real world' state\n\t\t// change, `derived.equals` may incorrectly return `true`\n\t\tif (!current_batch?.is_fork || derived.deps === null) {\n\t\t\tif (current_batch !== null) {\n\t\t\t\tcurrent_batch.capture(derived, value, true);\n\t\t\t} else {\n\t\t\t\tderived.v = value;\n\t\t\t}\n\n\t\t\t// deriveds without dependencies should never be recomputed\n\t\t\tif (derived.deps === null) {\n\t\t\t\tset_signal_status(derived, CLEAN);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\n\t// don't mark derived clean if we're reading it inside a\n\t// cleanup function, or it will cache a stale value\n\tif (is_destroying_effect) {\n\t\treturn;\n\t}\n\n\t// During time traveling we don't want to reset the status so that\n\t// traversal of the graph in the other batches still happens\n\tif (batch_values !== null) {\n\t\t// only cache the value if we're in a tracking context, otherwise we won't\n\t\t// clear the cache in `mark_reactions` when dependencies are updated\n\t\tif (effect_tracking() || current_batch?.is_fork) {\n\t\t\tbatch_values.set(derived, value);\n\t\t}\n\t} else {\n\t\tupdate_derived_status(derived);\n\t}\n}\n\n/**\n * @param {Derived} derived\n */\nexport function freeze_derived_effects(derived) {\n\tif (derived.effects === null) return;\n\n\tfor (const e of derived.effects) {\n\t\t// if the effect has a teardown function or abort signal, call it\n\t\tif (e.teardown || e.ac) {\n\t\t\te.teardown?.();\n\t\t\te.ac?.abort(STALE_REACTION);\n\n\t\t\t// make it a noop so it doesn't get called again if the derived\n\t\t\t// is unfrozen. we don't set it to `null`, because the existence\n\t\t\t// of a teardown function is what determines whether the\n\t\t\t// effect runs again during unfreezing\n\t\t\te.teardown = noop;\n\t\t\te.ac = null;\n\n\t\t\tremove_reactions(e, 0);\n\t\t\tdestroy_effect_children(e);\n\t\t}\n\t}\n}\n\n/**\n * @param {Derived} derived\n */\nexport function unfreeze_derived_effects(derived) {\n\tif (derived.effects === null) return;\n\n\tfor (const e of derived.effects) {\n\t\t// if the effect was previously frozen — indicated by the presence\n\t\t// of a teardown function — unfreeze it\n\t\tif (e.teardown) {\n\t\t\tupdate_effect(e);\n\t\t}\n\t}\n}\n","/** @import { Derived, Effect, Source, Value } from '#client' */\nimport { DEV } from 'esm-env';\nimport {\n\tactive_reaction,\n\tactive_effect,\n\tuntracked_writes,\n\tget,\n\tset_untracked_writes,\n\tuntrack,\n\tincrement_write_version,\n\tupdate_effect,\n\tcurrent_sources,\n\tis_dirty,\n\tuntracking,\n\tis_destroying_effect,\n\tpush_reaction_value\n} from '../runtime.js';\nimport { equals, safe_equals } from './equality.js';\nimport {\n\tCLEAN,\n\tDERIVED,\n\tDIRTY,\n\tBRANCH_EFFECT,\n\tEAGER_EFFECT,\n\tMAYBE_DIRTY,\n\tBLOCK_EFFECT,\n\tROOT_EFFECT,\n\tASYNC,\n\tWAS_MARKED,\n\tCONNECTED,\n\tREACTION_IS_UPDATING\n} from '#client/constants';\nimport * as e from '../errors.js';\nimport { legacy_mode_flag, tracing_mode_flag } from '../../flags/index.js';\nimport { includes } from '../../shared/utils.js';\nimport { tag_proxy } from '../dev/tracing.js';\nimport { get_error } from '../../shared/dev.js';\nimport { component_context, is_runes } from '../context.js';\nimport {\n\tBatch,\n\tbatch_values,\n\teager_block_effects,\n\tschedule_effect,\n\tlegacy_updates\n} from './batch.js';\nimport { proxy } from '../proxy.js';\nimport { execute_derived } from './deriveds.js';\nimport { set_signal_status, update_derived_status } from './status.js';\n\n/** @type {Set} */\nexport let eager_effects = new Set();\n\n/** @type {Map} */\nexport const old_values = new Map();\n\n/**\n * @param {Set} v\n */\nexport function set_eager_effects(v) {\n\teager_effects = v;\n}\n\nlet eager_effects_deferred = false;\n\nexport function set_eager_effects_deferred() {\n\teager_effects_deferred = true;\n}\n\n/**\n * @template V\n * @param {V} v\n * @param {Error | null} [stack]\n * @returns {Source}\n */\n// TODO rename this to `state` throughout the codebase\nexport function source(v, stack) {\n\t/** @type {Value} */\n\tvar signal = {\n\t\tf: 0, // TODO ideally we could skip this altogether, but it causes type errors\n\t\tv,\n\t\treactions: null,\n\t\tequals,\n\t\trv: 0,\n\t\twv: 0\n\t};\n\n\tif (DEV && tracing_mode_flag) {\n\t\tsignal.created = stack ?? get_error('created at');\n\t\tsignal.updated = null;\n\t\tsignal.set_during_effect = false;\n\t\tsignal.trace = null;\n\t}\n\n\treturn signal;\n}\n\n/**\n * @template V\n * @param {V} v\n * @param {Error | null} [stack]\n */\n/*#__NO_SIDE_EFFECTS__*/\nexport function state(v, stack) {\n\tconst s = source(v, stack);\n\n\tpush_reaction_value(s);\n\n\treturn s;\n}\n\n/**\n * @template V\n * @param {V} initial_value\n * @param {boolean} [immutable]\n * @returns {Source}\n */\n/*#__NO_SIDE_EFFECTS__*/\nexport function mutable_source(initial_value, immutable = false, trackable = true) {\n\tconst s = source(initial_value);\n\tif (!immutable) {\n\t\ts.equals = safe_equals;\n\t}\n\n\t// bind the signal to the component context, in case we need to\n\t// track updates to trigger beforeUpdate/afterUpdate callbacks\n\tif (legacy_mode_flag && trackable && component_context !== null && component_context.l !== null) {\n\t\t(component_context.l.s ??= []).push(s);\n\t}\n\n\treturn s;\n}\n\n/**\n * @template V\n * @param {Value} source\n * @param {V} value\n */\nexport function mutate(source, value) {\n\tset(\n\t\tsource,\n\t\tuntrack(() => get(source))\n\t);\n\treturn value;\n}\n\n/**\n * @template V\n * @param {Source} source\n * @param {V} value\n * @param {boolean} [should_proxy]\n * @returns {V}\n */\nexport function set(source, value, should_proxy = false) {\n\tif (\n\t\tactive_reaction !== null &&\n\t\t// since we are untracking the function inside `$inspect.with` we need to add this check\n\t\t// to ensure we error if state is set inside an inspect effect\n\t\t(!untracking || (active_reaction.f & EAGER_EFFECT) !== 0) &&\n\t\tis_runes() &&\n\t\t(active_reaction.f & (DERIVED | BLOCK_EFFECT | ASYNC | EAGER_EFFECT)) !== 0 &&\n\t\t(current_sources === null || !includes.call(current_sources, source))\n\t) {\n\t\te.state_unsafe_mutation();\n\t}\n\n\tlet new_value = should_proxy ? proxy(value) : value;\n\n\tif (DEV) {\n\t\ttag_proxy(new_value, /** @type {string} */ (source.label));\n\t}\n\n\treturn internal_set(source, new_value, legacy_updates);\n}\n\n/**\n * @template V\n * @param {Source} source\n * @param {V} value\n * @param {Effect[] | null} [updated_during_traversal]\n * @returns {V}\n */\nexport function internal_set(source, value, updated_during_traversal = null) {\n\tif (!source.equals(value)) {\n\t\told_values.set(source, is_destroying_effect ? value : source.v);\n\n\t\tvar batch = Batch.ensure();\n\t\tbatch.capture(source, value);\n\n\t\tif (DEV) {\n\t\t\tif (tracing_mode_flag || active_effect !== null) {\n\t\t\t\tsource.updated ??= new Map();\n\n\t\t\t\t// For performance reasons, when not using $inspect.trace, we only start collecting stack traces\n\t\t\t\t// after the same source has been updated more than 5 times in the same flush cycle.\n\t\t\t\tconst count = (source.updated.get('')?.count ?? 0) + 1;\n\t\t\t\tsource.updated.set('', { error: /** @type {any} */ (null), count });\n\n\t\t\t\tif (tracing_mode_flag || count > 5) {\n\t\t\t\t\tconst error = get_error('updated at');\n\n\t\t\t\t\tif (error !== null) {\n\t\t\t\t\t\tlet entry = source.updated.get(error.stack);\n\n\t\t\t\t\t\tif (!entry) {\n\t\t\t\t\t\t\tentry = { error, count: 0 };\n\t\t\t\t\t\t\tsource.updated.set(error.stack, entry);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tentry.count++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (active_effect !== null) {\n\t\t\t\tsource.set_during_effect = true;\n\t\t\t}\n\t\t}\n\n\t\tif ((source.f & DERIVED) !== 0) {\n\t\t\tconst derived = /** @type {Derived} */ (source);\n\n\t\t\t// if we are assigning to a dirty derived we set it to clean/maybe dirty but we also eagerly execute it to track the dependencies\n\t\t\tif ((source.f & DIRTY) !== 0) {\n\t\t\t\texecute_derived(derived);\n\t\t\t}\n\n\t\t\t// During time traveling we don't want to reset the status so that\n\t\t\t// traversal of the graph in the other batches still happens\n\t\t\tif (batch_values === null) {\n\t\t\t\tupdate_derived_status(derived);\n\t\t\t}\n\t\t}\n\n\t\tsource.wv = increment_write_version();\n\n\t\t// For debugging, in case you want to know which reactions are being scheduled:\n\t\t// log_reactions(source);\n\t\tmark_reactions(source, DIRTY, updated_during_traversal);\n\n\t\t// It's possible that the current reaction might not have up-to-date dependencies\n\t\t// whilst it's actively running. So in the case of ensuring it registers the reaction\n\t\t// properly for itself, we need to ensure the current effect actually gets\n\t\t// scheduled. i.e: `$effect(() => x++)`\n\t\tif (\n\t\t\tis_runes() &&\n\t\t\tactive_effect !== null &&\n\t\t\t(active_effect.f & CLEAN) !== 0 &&\n\t\t\t(active_effect.f & (BRANCH_EFFECT | ROOT_EFFECT)) === 0\n\t\t) {\n\t\t\tif (untracked_writes === null) {\n\t\t\t\tset_untracked_writes([source]);\n\t\t\t} else {\n\t\t\t\tuntracked_writes.push(source);\n\t\t\t}\n\t\t}\n\n\t\tif (!batch.is_fork && eager_effects.size > 0 && !eager_effects_deferred) {\n\t\t\tflush_eager_effects();\n\t\t}\n\t}\n\n\treturn value;\n}\n\nexport function flush_eager_effects() {\n\teager_effects_deferred = false;\n\n\tfor (const effect of eager_effects) {\n\t\t// Mark clean inspect-effects as maybe dirty and then check their dirtiness\n\t\t// instead of just updating the effects - this way we avoid overfiring.\n\t\tif ((effect.f & CLEAN) !== 0) {\n\t\t\tset_signal_status(effect, MAYBE_DIRTY);\n\t\t}\n\n\t\tif (is_dirty(effect)) {\n\t\t\tupdate_effect(effect);\n\t\t}\n\t}\n\n\teager_effects.clear();\n}\n\n/**\n * @template {number | bigint} T\n * @param {Source} source\n * @param {1 | -1} [d]\n * @returns {T}\n */\nexport function update(source, d = 1) {\n\tvar value = get(source);\n\tvar result = d === 1 ? value++ : value--;\n\n\tset(source, value);\n\n\t// @ts-expect-error\n\treturn result;\n}\n\n/**\n * @template {number | bigint} T\n * @param {Source} source\n * @param {1 | -1} [d]\n * @returns {T}\n */\nexport function update_pre(source, d = 1) {\n\tvar value = get(source);\n\n\t// @ts-expect-error\n\t// eslint-disable-next-line no-useless-assignment -- `++`/`--` used for return value, not side effect on `value`\n\treturn set(source, d === 1 ? ++value : --value);\n}\n\n/**\n * Silently (without using `get`) increment a source\n * @param {Source} source\n */\nexport function increment(source) {\n\tset(source, source.v + 1);\n}\n\n/**\n * @param {Value} signal\n * @param {number} status should be DIRTY or MAYBE_DIRTY\n * @param {Effect[] | null} updated_during_traversal\n * @returns {void}\n */\nfunction mark_reactions(signal, status, updated_during_traversal) {\n\tvar reactions = signal.reactions;\n\tif (reactions === null) return;\n\n\tvar runes = is_runes();\n\tvar length = reactions.length;\n\n\tfor (var i = 0; i < length; i++) {\n\t\tvar reaction = reactions[i];\n\t\tvar flags = reaction.f;\n\n\t\t// In legacy mode, skip the current effect to prevent infinite loops\n\t\tif (!runes && reaction === active_effect) continue;\n\n\t\t// Inspect effects need to run immediately, so that the stack trace makes sense\n\t\tif (DEV && (flags & EAGER_EFFECT) !== 0) {\n\t\t\teager_effects.add(reaction);\n\t\t\tcontinue;\n\t\t}\n\n\t\tvar not_dirty = (flags & DIRTY) === 0;\n\n\t\t// don't set a DIRTY reaction to MAYBE_DIRTY\n\t\tif (not_dirty) {\n\t\t\tset_signal_status(reaction, status);\n\t\t}\n\n\t\tif ((flags & DERIVED) !== 0) {\n\t\t\tvar derived = /** @type {Derived} */ (reaction);\n\n\t\t\tbatch_values?.delete(derived);\n\n\t\t\tif ((flags & WAS_MARKED) === 0) {\n\t\t\t\t// Only connected deriveds being executed outside the update cycle can be reliably unmarked right away\n\t\t\t\tif (\n\t\t\t\t\tflags & CONNECTED &&\n\t\t\t\t\t(active_effect === null || (active_effect.f & REACTION_IS_UPDATING) === 0)\n\t\t\t\t) {\n\t\t\t\t\treaction.f |= WAS_MARKED;\n\t\t\t\t}\n\n\t\t\t\tmark_reactions(derived, MAYBE_DIRTY, updated_during_traversal);\n\t\t\t}\n\t\t} else if (not_dirty) {\n\t\t\tvar effect = /** @type {Effect} */ (reaction);\n\n\t\t\tif ((flags & BLOCK_EFFECT) !== 0 && eager_block_effects !== null) {\n\t\t\t\teager_block_effects.add(effect);\n\t\t\t}\n\n\t\t\tif (updated_during_traversal !== null) {\n\t\t\t\tupdated_during_traversal.push(effect);\n\t\t\t} else {\n\t\t\t\tschedule_effect(effect);\n\t\t\t}\n\t\t}\n\t}\n}\n","/** @import { Source } from '#client' */\nimport { DEV } from 'esm-env';\nimport {\n\tget,\n\tactive_effect,\n\tupdate_version,\n\tactive_reaction,\n\tset_update_version,\n\tset_active_reaction\n} from './runtime.js';\nimport {\n\tarray_prototype,\n\tget_descriptor,\n\tget_prototype_of,\n\tis_array,\n\tobject_prototype\n} from '../shared/utils.js';\nimport {\n\tstate as source,\n\tset,\n\tincrement,\n\tflush_eager_effects,\n\tset_eager_effects_deferred\n} from './reactivity/sources.js';\nimport { PROXY_PATH_SYMBOL, STATE_SYMBOL } from '#client/constants';\nimport { UNINITIALIZED } from '../../constants.js';\nimport * as e from './errors.js';\nimport { tag } from './dev/tracing.js';\nimport { get_error } from '../shared/dev.js';\nimport { tracing_mode_flag } from '../flags/index.js';\n\n// TODO move all regexes into shared module?\nconst regex_is_valid_identifier = /^[a-zA-Z_$][a-zA-Z_$0-9]*$/;\n\n/**\n * @template T\n * @param {T} value\n * @returns {T}\n */\nexport function proxy(value) {\n\t// if non-proxyable, or is already a proxy, return `value`\n\tif (typeof value !== 'object' || value === null || STATE_SYMBOL in value) {\n\t\treturn value;\n\t}\n\n\tconst prototype = get_prototype_of(value);\n\n\tif (prototype !== object_prototype && prototype !== array_prototype) {\n\t\treturn value;\n\t}\n\n\t/** @type {Map>} */\n\tvar sources = new Map();\n\tvar is_proxied_array = is_array(value);\n\tvar version = source(0);\n\n\tvar stack = DEV && tracing_mode_flag ? get_error('created at') : null;\n\tvar parent_version = update_version;\n\n\t/**\n\t * Executes the proxy in the context of the reaction it was originally created in, if any\n\t * @template T\n\t * @param {() => T} fn\n\t */\n\tvar with_parent = (fn) => {\n\t\tif (update_version === parent_version) {\n\t\t\treturn fn();\n\t\t}\n\n\t\t// child source is being created after the initial proxy —\n\t\t// prevent it from being associated with the current reaction\n\t\tvar reaction = active_reaction;\n\t\tvar version = update_version;\n\n\t\tset_active_reaction(null);\n\t\tset_update_version(parent_version);\n\n\t\tvar result = fn();\n\n\t\tset_active_reaction(reaction);\n\t\tset_update_version(version);\n\n\t\treturn result;\n\t};\n\n\tif (is_proxied_array) {\n\t\t// We need to create the length source eagerly to ensure that\n\t\t// mutations to the array are properly synced with our proxy\n\t\tsources.set('length', source(/** @type {any[]} */ (value).length, stack));\n\t\tif (DEV) {\n\t\t\tvalue = /** @type {any} */ (inspectable_array(/** @type {any[]} */ (value)));\n\t\t}\n\t}\n\n\t/** Used in dev for $inspect.trace() */\n\tvar path = '';\n\tlet updating = false;\n\t/** @param {string} new_path */\n\tfunction update_path(new_path) {\n\t\tif (updating) return;\n\t\tupdating = true;\n\t\tpath = new_path;\n\n\t\ttag(version, `${path} version`);\n\n\t\t// rename all child sources and child proxies\n\t\tfor (const [prop, source] of sources) {\n\t\t\ttag(source, get_label(path, prop));\n\t\t}\n\t\tupdating = false;\n\t}\n\n\treturn new Proxy(/** @type {any} */ (value), {\n\t\tdefineProperty(_, prop, descriptor) {\n\t\t\tif (\n\t\t\t\t!('value' in descriptor) ||\n\t\t\t\tdescriptor.configurable === false ||\n\t\t\t\tdescriptor.enumerable === false ||\n\t\t\t\tdescriptor.writable === false\n\t\t\t) {\n\t\t\t\t// we disallow non-basic descriptors, because unless they are applied to the\n\t\t\t\t// target object — which we avoid, so that state can be forked — we will run\n\t\t\t\t// afoul of the various invariants\n\t\t\t\t// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/getOwnPropertyDescriptor#invariants\n\t\t\t\te.state_descriptors_fixed();\n\t\t\t}\n\t\t\tvar s = sources.get(prop);\n\t\t\tif (s === undefined) {\n\t\t\t\twith_parent(() => {\n\t\t\t\t\tvar s = source(descriptor.value, stack);\n\t\t\t\t\tsources.set(prop, s);\n\t\t\t\t\tif (DEV && typeof prop === 'string') {\n\t\t\t\t\t\ttag(s, get_label(path, prop));\n\t\t\t\t\t}\n\t\t\t\t\treturn s;\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tset(s, descriptor.value, true);\n\t\t\t}\n\n\t\t\treturn true;\n\t\t},\n\n\t\tdeleteProperty(target, prop) {\n\t\t\tvar s = sources.get(prop);\n\n\t\t\tif (s === undefined) {\n\t\t\t\tif (prop in target) {\n\t\t\t\t\tconst s = with_parent(() => source(UNINITIALIZED, stack));\n\t\t\t\t\tsources.set(prop, s);\n\t\t\t\t\tincrement(version);\n\n\t\t\t\t\tif (DEV) {\n\t\t\t\t\t\ttag(s, get_label(path, prop));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tset(s, UNINITIALIZED);\n\t\t\t\tincrement(version);\n\t\t\t}\n\n\t\t\treturn true;\n\t\t},\n\n\t\tget(target, prop, receiver) {\n\t\t\tif (prop === STATE_SYMBOL) {\n\t\t\t\treturn value;\n\t\t\t}\n\n\t\t\tif (DEV && prop === PROXY_PATH_SYMBOL) {\n\t\t\t\treturn update_path;\n\t\t\t}\n\n\t\t\tvar s = sources.get(prop);\n\t\t\tvar exists = prop in target;\n\n\t\t\t// create a source, but only if it's an own property and not a prototype property\n\t\t\tif (s === undefined && (!exists || get_descriptor(target, prop)?.writable)) {\n\t\t\t\ts = with_parent(() => {\n\t\t\t\t\tvar p = proxy(exists ? target[prop] : UNINITIALIZED);\n\t\t\t\t\tvar s = source(p, stack);\n\n\t\t\t\t\tif (DEV) {\n\t\t\t\t\t\ttag(s, get_label(path, prop));\n\t\t\t\t\t}\n\n\t\t\t\t\treturn s;\n\t\t\t\t});\n\n\t\t\t\tsources.set(prop, s);\n\t\t\t}\n\n\t\t\tif (s !== undefined) {\n\t\t\t\tvar v = get(s);\n\t\t\t\treturn v === UNINITIALIZED ? undefined : v;\n\t\t\t}\n\n\t\t\treturn Reflect.get(target, prop, receiver);\n\t\t},\n\n\t\tgetOwnPropertyDescriptor(target, prop) {\n\t\t\tvar descriptor = Reflect.getOwnPropertyDescriptor(target, prop);\n\n\t\t\tif (descriptor && 'value' in descriptor) {\n\t\t\t\tvar s = sources.get(prop);\n\t\t\t\tif (s) descriptor.value = get(s);\n\t\t\t} else if (descriptor === undefined) {\n\t\t\t\tvar source = sources.get(prop);\n\t\t\t\tvar value = source?.v;\n\n\t\t\t\tif (source !== undefined && value !== UNINITIALIZED) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tenumerable: true,\n\t\t\t\t\t\tconfigurable: true,\n\t\t\t\t\t\tvalue,\n\t\t\t\t\t\twritable: true\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn descriptor;\n\t\t},\n\n\t\thas(target, prop) {\n\t\t\tif (prop === STATE_SYMBOL) {\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tvar s = sources.get(prop);\n\t\t\tvar has = (s !== undefined && s.v !== UNINITIALIZED) || Reflect.has(target, prop);\n\n\t\t\tif (\n\t\t\t\ts !== undefined ||\n\t\t\t\t(active_effect !== null && (!has || get_descriptor(target, prop)?.writable))\n\t\t\t) {\n\t\t\t\tif (s === undefined) {\n\t\t\t\t\ts = with_parent(() => {\n\t\t\t\t\t\tvar p = has ? proxy(target[prop]) : UNINITIALIZED;\n\t\t\t\t\t\tvar s = source(p, stack);\n\n\t\t\t\t\t\tif (DEV) {\n\t\t\t\t\t\t\ttag(s, get_label(path, prop));\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn s;\n\t\t\t\t\t});\n\n\t\t\t\t\tsources.set(prop, s);\n\t\t\t\t}\n\n\t\t\t\tvar value = get(s);\n\t\t\t\tif (value === UNINITIALIZED) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn has;\n\t\t},\n\n\t\tset(target, prop, value, receiver) {\n\t\t\tvar s = sources.get(prop);\n\t\t\tvar has = prop in target;\n\n\t\t\t// variable.length = value -> clear all signals with index >= value\n\t\t\tif (is_proxied_array && prop === 'length') {\n\t\t\t\tfor (var i = value; i < /** @type {Source} */ (s).v; i += 1) {\n\t\t\t\t\tvar other_s = sources.get(i + '');\n\t\t\t\t\tif (other_s !== undefined) {\n\t\t\t\t\t\tset(other_s, UNINITIALIZED);\n\t\t\t\t\t} else if (i in target) {\n\t\t\t\t\t\t// If the item exists in the original, we need to create an uninitialized source,\n\t\t\t\t\t\t// else a later read of the property would result in a source being created with\n\t\t\t\t\t\t// the value of the original item at that index.\n\t\t\t\t\t\tother_s = with_parent(() => source(UNINITIALIZED, stack));\n\t\t\t\t\t\tsources.set(i + '', other_s);\n\n\t\t\t\t\t\tif (DEV) {\n\t\t\t\t\t\t\ttag(other_s, get_label(path, i));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// If we haven't yet created a source for this property, we need to ensure\n\t\t\t// we do so otherwise if we read it later, then the write won't be tracked and\n\t\t\t// the heuristics of effects will be different vs if we had read the proxied\n\t\t\t// object property before writing to that property.\n\t\t\tif (s === undefined) {\n\t\t\t\tif (!has || get_descriptor(target, prop)?.writable) {\n\t\t\t\t\ts = with_parent(() => source(undefined, stack));\n\n\t\t\t\t\tif (DEV) {\n\t\t\t\t\t\ttag(s, get_label(path, prop));\n\t\t\t\t\t}\n\t\t\t\t\tset(s, proxy(value));\n\n\t\t\t\t\tsources.set(prop, s);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\thas = s.v !== UNINITIALIZED;\n\n\t\t\t\tvar p = with_parent(() => proxy(value));\n\t\t\t\tset(s, p);\n\t\t\t}\n\n\t\t\tvar descriptor = Reflect.getOwnPropertyDescriptor(target, prop);\n\n\t\t\t// Set the new value before updating any signals so that any listeners get the new value\n\t\t\tif (descriptor?.set) {\n\t\t\t\tdescriptor.set.call(receiver, value);\n\t\t\t}\n\n\t\t\tif (!has) {\n\t\t\t\t// If we have mutated an array directly, we might need to\n\t\t\t\t// signal that length has also changed. Do it before updating metadata\n\t\t\t\t// to ensure that iterating over the array as a result of a metadata update\n\t\t\t\t// will not cause the length to be out of sync.\n\t\t\t\tif (is_proxied_array && typeof prop === 'string') {\n\t\t\t\t\tvar ls = /** @type {Source} */ (sources.get('length'));\n\t\t\t\t\tvar n = Number(prop);\n\n\t\t\t\t\tif (Number.isInteger(n) && n >= ls.v) {\n\t\t\t\t\t\tset(ls, n + 1);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tincrement(version);\n\t\t\t}\n\n\t\t\treturn true;\n\t\t},\n\n\t\townKeys(target) {\n\t\t\tget(version);\n\n\t\t\tvar own_keys = Reflect.ownKeys(target).filter((key) => {\n\t\t\t\tvar source = sources.get(key);\n\t\t\t\treturn source === undefined || source.v !== UNINITIALIZED;\n\t\t\t});\n\n\t\t\tfor (var [key, source] of sources) {\n\t\t\t\tif (source.v !== UNINITIALIZED && !(key in target)) {\n\t\t\t\t\town_keys.push(key);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn own_keys;\n\t\t},\n\n\t\tsetPrototypeOf() {\n\t\t\te.state_prototype_fixed();\n\t\t}\n\t});\n}\n\n/**\n * @param {string} path\n * @param {string | symbol} prop\n */\nfunction get_label(path, prop) {\n\tif (typeof prop === 'symbol') return `${path}[Symbol(${prop.description ?? ''})]`;\n\tif (regex_is_valid_identifier.test(prop)) return `${path}.${prop}`;\n\treturn /^\\d+$/.test(prop) ? `${path}[${prop}]` : `${path}['${prop}']`;\n}\n\n/**\n * @param {any} value\n */\nexport function get_proxied_value(value) {\n\ttry {\n\t\tif (value !== null && typeof value === 'object' && STATE_SYMBOL in value) {\n\t\t\treturn value[STATE_SYMBOL];\n\t\t}\n\t} catch {\n\t\t// the above if check can throw an error if the value in question\n\t\t// is the contentWindow of an iframe on another domain, in which\n\t\t// case we want to just return the value (because it's definitely\n\t\t// not a proxied value) so we don't break any JavaScript interacting\n\t\t// with that iframe (such as various payment companies client side\n\t\t// JavaScript libraries interacting with their iframes on the same\n\t\t// domain)\n\t}\n\n\treturn value;\n}\n\n/**\n * @param {any} a\n * @param {any} b\n */\nexport function is(a, b) {\n\treturn Object.is(get_proxied_value(a), get_proxied_value(b));\n}\n\nconst ARRAY_MUTATING_METHODS = new Set([\n\t'copyWithin',\n\t'fill',\n\t'pop',\n\t'push',\n\t'reverse',\n\t'shift',\n\t'sort',\n\t'splice',\n\t'unshift'\n]);\n\n/**\n * Wrap array mutating methods so $inspect is triggered only once and\n * to prevent logging an array in intermediate state (e.g. with an empty slot)\n * @param {any[]} array\n */\nfunction inspectable_array(array) {\n\treturn new Proxy(array, {\n\t\tget(target, prop, receiver) {\n\t\t\tvar value = Reflect.get(target, prop, receiver);\n\t\t\tif (!ARRAY_MUTATING_METHODS.has(/** @type {string} */ (prop))) {\n\t\t\t\treturn value;\n\t\t\t}\n\n\t\t\t/**\n\t\t\t * @this {any[]}\n\t\t\t * @param {any[]} args\n\t\t\t */\n\t\t\treturn function (...args) {\n\t\t\t\tset_eager_effects_deferred();\n\t\t\t\tvar result = value.apply(this, args);\n\t\t\t\tflush_eager_effects();\n\t\t\t\treturn result;\n\t\t\t};\n\t\t}\n\t});\n}\n","/** @import { Effect, TemplateNode } from '#client' */\nimport { hydrate_node, hydrating, set_hydrate_node } from './hydration.js';\nimport { DEV } from 'esm-env';\nimport { init_array_prototype_warnings } from '../dev/equality.js';\nimport { get_descriptor, is_extensible } from '../../shared/utils.js';\nimport { active_effect } from '../runtime.js';\nimport { async_mode_flag } from '../../flags/index.js';\nimport { TEXT_NODE, REACTION_RAN } from '#client/constants';\nimport { eager_block_effects } from '../reactivity/batch.js';\nimport { NAMESPACE_HTML } from '../../../constants.js';\n\n// export these for reference in the compiled code, making global name deduplication unnecessary\n/** @type {Window} */\nexport var $window;\n\n/** @type {Document} */\nexport var $document;\n\n/** @type {boolean} */\nexport var is_firefox;\n\n/** @type {() => Node | null} */\nvar first_child_getter;\n/** @type {() => Node | null} */\nvar next_sibling_getter;\n\n/**\n * Initialize these lazily to avoid issues when using the runtime in a server context\n * where these globals are not available while avoiding a separate server entry point\n */\nexport function init_operations() {\n\tif ($window !== undefined) {\n\t\treturn;\n\t}\n\n\t$window = window;\n\t$document = document;\n\tis_firefox = /Firefox/.test(navigator.userAgent);\n\n\tvar element_prototype = Element.prototype;\n\tvar node_prototype = Node.prototype;\n\tvar text_prototype = Text.prototype;\n\n\t// @ts-ignore\n\tfirst_child_getter = get_descriptor(node_prototype, 'firstChild').get;\n\t// @ts-ignore\n\tnext_sibling_getter = get_descriptor(node_prototype, 'nextSibling').get;\n\n\tif (is_extensible(element_prototype)) {\n\t\t// the following assignments improve perf of lookups on DOM nodes\n\t\t// @ts-expect-error\n\t\telement_prototype.__click = undefined;\n\t\t// @ts-expect-error\n\t\telement_prototype.__className = undefined;\n\t\t// @ts-expect-error\n\t\telement_prototype.__attributes = null;\n\t\t// @ts-expect-error\n\t\telement_prototype.__style = undefined;\n\t\t// @ts-expect-error\n\t\telement_prototype.__e = undefined;\n\t}\n\n\tif (is_extensible(text_prototype)) {\n\t\t// @ts-expect-error\n\t\ttext_prototype.__t = undefined;\n\t}\n\n\tif (DEV) {\n\t\t// @ts-expect-error\n\t\telement_prototype.__svelte_meta = null;\n\n\t\tinit_array_prototype_warnings();\n\t}\n}\n\n/**\n * @param {string} value\n * @returns {Text}\n */\nexport function create_text(value = '') {\n\treturn document.createTextNode(value);\n}\n\n/**\n * @template {Node} N\n * @param {N} node\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function get_first_child(node) {\n\treturn /** @type {TemplateNode | null} */ (first_child_getter.call(node));\n}\n\n/**\n * @template {Node} N\n * @param {N} node\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function get_next_sibling(node) {\n\treturn /** @type {TemplateNode | null} */ (next_sibling_getter.call(node));\n}\n\n/**\n * Don't mark this as side-effect-free, hydration needs to walk all nodes\n * @template {Node} N\n * @param {N} node\n * @param {boolean} is_text\n * @returns {TemplateNode | null}\n */\nexport function child(node, is_text) {\n\tif (!hydrating) {\n\t\treturn get_first_child(node);\n\t}\n\n\tvar child = get_first_child(hydrate_node);\n\n\t// Child can be null if we have an element with a single child, like `

              {text}

              `, where `text` is empty\n\tif (child === null) {\n\t\tchild = hydrate_node.appendChild(create_text());\n\t} else if (is_text && child.nodeType !== TEXT_NODE) {\n\t\tvar text = create_text();\n\t\tchild?.before(text);\n\t\tset_hydrate_node(text);\n\t\treturn text;\n\t}\n\n\tif (is_text) {\n\t\tmerge_text_nodes(/** @type {Text} */ (child));\n\t}\n\n\tset_hydrate_node(child);\n\treturn child;\n}\n\n/**\n * Don't mark this as side-effect-free, hydration needs to walk all nodes\n * @param {TemplateNode} node\n * @param {boolean} [is_text]\n * @returns {TemplateNode | null}\n */\nexport function first_child(node, is_text = false) {\n\tif (!hydrating) {\n\t\tvar first = get_first_child(node);\n\n\t\t// TODO prevent user comments with the empty string when preserveComments is true\n\t\tif (first instanceof Comment && first.data === '') return get_next_sibling(first);\n\n\t\treturn first;\n\t}\n\n\tif (is_text) {\n\t\t// if an {expression} is empty during SSR, there might be no\n\t\t// text node to hydrate — we must therefore create one\n\t\tif (hydrate_node?.nodeType !== TEXT_NODE) {\n\t\t\tvar text = create_text();\n\n\t\t\thydrate_node?.before(text);\n\t\t\tset_hydrate_node(text);\n\t\t\treturn text;\n\t\t}\n\n\t\tmerge_text_nodes(/** @type {Text} */ (hydrate_node));\n\t}\n\n\treturn hydrate_node;\n}\n\n/**\n * Don't mark this as side-effect-free, hydration needs to walk all nodes\n * @param {TemplateNode} node\n * @param {number} count\n * @param {boolean} is_text\n * @returns {TemplateNode | null}\n */\nexport function sibling(node, count = 1, is_text = false) {\n\tlet next_sibling = hydrating ? hydrate_node : node;\n\tvar last_sibling;\n\n\twhile (count--) {\n\t\tlast_sibling = next_sibling;\n\t\tnext_sibling = /** @type {TemplateNode} */ (get_next_sibling(next_sibling));\n\t}\n\n\tif (!hydrating) {\n\t\treturn next_sibling;\n\t}\n\n\tif (is_text) {\n\t\t// if a sibling {expression} is empty during SSR, there might be no\n\t\t// text node to hydrate — we must therefore create one\n\t\tif (next_sibling?.nodeType !== TEXT_NODE) {\n\t\t\tvar text = create_text();\n\t\t\t// If the next sibling is `null` and we're handling text then it's because\n\t\t\t// the SSR content was empty for the text, so we need to generate a new text\n\t\t\t// node and insert it after the last sibling\n\t\t\tif (next_sibling === null) {\n\t\t\t\tlast_sibling?.after(text);\n\t\t\t} else {\n\t\t\t\tnext_sibling.before(text);\n\t\t\t}\n\t\t\tset_hydrate_node(text);\n\t\t\treturn text;\n\t\t}\n\n\t\tmerge_text_nodes(/** @type {Text} */ (next_sibling));\n\t}\n\n\tset_hydrate_node(next_sibling);\n\treturn next_sibling;\n}\n\n/**\n * @template {Node} N\n * @param {N} node\n * @returns {void}\n */\nexport function clear_text_content(node) {\n\tnode.textContent = '';\n}\n\n/**\n * Returns `true` if we're updating the current block, for example `condition` in\n * an `{#if condition}` block just changed. In this case, the branch should be\n * appended (or removed) at the same time as other updates within the\n * current ``\n */\nexport function should_defer_append() {\n\tif (!async_mode_flag) return false;\n\tif (eager_block_effects !== null) return false;\n\n\tvar flags = /** @type {Effect} */ (active_effect).f;\n\treturn (flags & REACTION_RAN) !== 0;\n}\n\n/**\n * @template {keyof HTMLElementTagNameMap | string} T\n * @param {T} tag\n * @param {string} [namespace]\n * @param {string} [is]\n * @returns {T extends keyof HTMLElementTagNameMap ? HTMLElementTagNameMap[T] : Element}\n */\nexport function create_element(tag, namespace, is) {\n\tlet options = is ? { is } : undefined;\n\treturn /** @type {T extends keyof HTMLElementTagNameMap ? HTMLElementTagNameMap[T] : Element} */ (\n\t\tdocument.createElementNS(namespace ?? NAMESPACE_HTML, tag, options)\n\t);\n}\n\nexport function create_fragment() {\n\treturn document.createDocumentFragment();\n}\n\n/**\n * @param {string} data\n * @returns\n */\nexport function create_comment(data = '') {\n\treturn document.createComment(data);\n}\n\n/**\n * @param {Element} element\n * @param {string} key\n * @param {string} value\n * @returns\n */\nexport function set_attribute(element, key, value = '') {\n\tif (key.startsWith('xlink:')) {\n\t\telement.setAttributeNS('http://www.w3.org/1999/xlink', key, value);\n\t\treturn;\n\t}\n\treturn element.setAttribute(key, value);\n}\n\n/**\n * Browsers split text nodes larger than 65536 bytes when parsing.\n * For hydration to succeed, we need to stitch them back together\n * @param {Text} text\n */\nexport function merge_text_nodes(text) {\n\tif (/** @type {string} */ (text.nodeValue).length < 65536) {\n\t\treturn;\n\t}\n\n\tlet next = text.nextSibling;\n\n\twhile (next !== null && next.nodeType === TEXT_NODE) {\n\t\tnext.remove();\n\n\t\t/** @type {string} */ (text.nodeValue) += /** @type {string} */ (next.nodeValue);\n\n\t\tnext = text.nextSibling;\n\t}\n}\n","import { teardown } from '../../../reactivity/effects.js';\nimport {\n\tactive_effect,\n\tactive_reaction,\n\tset_active_effect,\n\tset_active_reaction\n} from '../../../runtime.js';\nimport { add_form_reset_listener } from '../misc.js';\n\n/**\n * Fires the handler once immediately (unless corresponding arg is set to `false`),\n * then listens to the given events until the render effect context is destroyed\n * @param {EventTarget} target\n * @param {Array} events\n * @param {(event?: Event) => void} handler\n * @param {any} call_handler_immediately\n */\nexport function listen(target, events, handler, call_handler_immediately = true) {\n\tif (call_handler_immediately) {\n\t\thandler();\n\t}\n\n\tfor (var name of events) {\n\t\ttarget.addEventListener(name, handler);\n\t}\n\n\tteardown(() => {\n\t\tfor (var name of events) {\n\t\t\ttarget.removeEventListener(name, handler);\n\t\t}\n\t});\n}\n\n/**\n * @template T\n * @param {() => T} fn\n */\nexport function without_reactive_context(fn) {\n\tvar previous_reaction = active_reaction;\n\tvar previous_effect = active_effect;\n\tset_active_reaction(null);\n\tset_active_effect(null);\n\ttry {\n\t\treturn fn();\n\t} finally {\n\t\tset_active_reaction(previous_reaction);\n\t\tset_active_effect(previous_effect);\n\t}\n}\n\n/**\n * Listen to the given event, and then instantiate a global form reset listener if not already done,\n * to notify all bindings when the form is reset\n * @param {HTMLElement} element\n * @param {string} event\n * @param {(is_reset?: true) => void} handler\n * @param {(is_reset?: true) => void} [on_reset]\n */\nexport function listen_to_event_and_reset_event(element, event, handler, on_reset = handler) {\n\telement.addEventListener(event, () => without_reactive_context(handler));\n\t// @ts-expect-error\n\tconst prev = element.__on_r;\n\tif (prev) {\n\t\t// special case for checkbox that can have multiple binds (group & checked)\n\t\t// @ts-expect-error\n\t\telement.__on_r = () => {\n\t\t\tprev();\n\t\t\ton_reset(true);\n\t\t};\n\t} else {\n\t\t// @ts-expect-error\n\t\telement.__on_r = () => on_reset(true);\n\t}\n\n\tadd_form_reset_listener();\n}\n","/** @import { Blocker, ComponentContext, ComponentContextLegacy, Derived, Effect, TemplateNode, TransitionManager } from '#client' */\nimport {\n\tis_dirty,\n\tactive_effect,\n\tactive_reaction,\n\tupdate_effect,\n\tget,\n\tis_destroying_effect,\n\tremove_reactions,\n\tset_active_reaction,\n\tset_is_destroying_effect,\n\tuntrack,\n\tuntracking,\n\tset_active_effect\n} from '../runtime.js';\nimport {\n\tDIRTY,\n\tBRANCH_EFFECT,\n\tRENDER_EFFECT,\n\tEFFECT,\n\tDESTROYED,\n\tINERT,\n\tREACTION_RAN,\n\tBLOCK_EFFECT,\n\tROOT_EFFECT,\n\tEFFECT_TRANSPARENT,\n\tDERIVED,\n\tCLEAN,\n\tEAGER_EFFECT,\n\tHEAD_EFFECT,\n\tMAYBE_DIRTY,\n\tEFFECT_PRESERVED,\n\tSTALE_REACTION,\n\tUSER_EFFECT,\n\tASYNC,\n\tCONNECTED,\n\tMANAGED_EFFECT,\n\tDESTROYING\n} from '#client/constants';\nimport * as e from '../errors.js';\nimport { DEV } from 'esm-env';\nimport { define_property } from '../../shared/utils.js';\nimport { get_next_sibling } from '../dom/operations.js';\nimport { component_context, dev_current_component_function, dev_stack } from '../context.js';\nimport { Batch, collected_effects, current_batch } from './batch.js';\nimport { flatten, increment_pending } from './async.js';\nimport { without_reactive_context } from '../dom/elements/bindings/shared.js';\nimport { set_signal_status } from './status.js';\n\n/**\n * @param {'$effect' | '$effect.pre' | '$inspect'} rune\n */\nexport function validate_effect(rune) {\n\tif (active_effect === null) {\n\t\tif (active_reaction === null) {\n\t\t\te.effect_orphan(rune);\n\t\t}\n\n\t\te.effect_in_unowned_derived();\n\t}\n\n\tif (is_destroying_effect) {\n\t\te.effect_in_teardown(rune);\n\t}\n}\n\n/**\n * @param {Effect} effect\n * @param {Effect} parent_effect\n */\nfunction push_effect(effect, parent_effect) {\n\tvar parent_last = parent_effect.last;\n\tif (parent_last === null) {\n\t\tparent_effect.last = parent_effect.first = effect;\n\t} else {\n\t\tparent_last.next = effect;\n\t\teffect.prev = parent_last;\n\t\tparent_effect.last = effect;\n\t}\n}\n\n/**\n * @param {number} type\n * @param {null | (() => void | (() => void))} fn\n * @returns {Effect}\n */\nfunction create_effect(type, fn) {\n\tvar parent = active_effect;\n\n\tif (DEV) {\n\t\t// Ensure the parent is never an inspect effect\n\t\twhile (parent !== null && (parent.f & EAGER_EFFECT) !== 0) {\n\t\t\tparent = parent.parent;\n\t\t}\n\t}\n\n\tif (parent !== null && (parent.f & INERT) !== 0) {\n\t\ttype |= INERT;\n\t}\n\n\t/** @type {Effect} */\n\tvar effect = {\n\t\tctx: component_context,\n\t\tdeps: null,\n\t\tnodes: null,\n\t\tf: type | DIRTY | CONNECTED,\n\t\tfirst: null,\n\t\tfn,\n\t\tlast: null,\n\t\tnext: null,\n\t\tparent,\n\t\tb: parent && parent.b,\n\t\tprev: null,\n\t\tteardown: null,\n\t\twv: 0,\n\t\tac: null\n\t};\n\n\tif (DEV) {\n\t\teffect.component_function = dev_current_component_function;\n\t}\n\n\tcurrent_batch?.register_created_effect(effect);\n\n\t/** @type {Effect | null} */\n\tvar e = effect;\n\n\tif ((type & EFFECT) !== 0) {\n\t\tif (collected_effects !== null) {\n\t\t\t// created during traversal — collect and run afterwards\n\t\t\tcollected_effects.push(effect);\n\t\t} else {\n\t\t\t// schedule for later\n\t\t\tBatch.ensure().schedule(effect);\n\t\t}\n\t} else if (fn !== null) {\n\t\ttry {\n\t\t\tupdate_effect(effect);\n\t\t} catch (e) {\n\t\t\tdestroy_effect(effect);\n\t\t\tthrow e;\n\t\t}\n\n\t\t// if an effect doesn't need to be kept in the tree (because it\n\t\t// won't re-run, has no DOM, and has no teardown etc)\n\t\t// then we skip it and go to its child (if any)\n\t\tif (\n\t\t\te.deps === null &&\n\t\t\te.teardown === null &&\n\t\t\te.nodes === null &&\n\t\t\te.first === e.last && // either `null`, or a singular child\n\t\t\t(e.f & EFFECT_PRESERVED) === 0\n\t\t) {\n\t\t\te = e.first;\n\t\t\tif ((type & BLOCK_EFFECT) !== 0 && (type & EFFECT_TRANSPARENT) !== 0 && e !== null) {\n\t\t\t\te.f |= EFFECT_TRANSPARENT;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (e !== null) {\n\t\te.parent = parent;\n\n\t\tif (parent !== null) {\n\t\t\tpush_effect(e, parent);\n\t\t}\n\n\t\t// if we're in a derived, add the effect there too\n\t\tif (\n\t\t\tactive_reaction !== null &&\n\t\t\t(active_reaction.f & DERIVED) !== 0 &&\n\t\t\t(type & ROOT_EFFECT) === 0\n\t\t) {\n\t\t\tvar derived = /** @type {Derived} */ (active_reaction);\n\t\t\t(derived.effects ??= []).push(e);\n\t\t}\n\t}\n\n\treturn effect;\n}\n\n/**\n * Internal representation of `$effect.tracking()`\n * @returns {boolean}\n */\nexport function effect_tracking() {\n\treturn active_reaction !== null && !untracking;\n}\n\n/**\n * @param {() => void} fn\n */\nexport function teardown(fn) {\n\tconst effect = create_effect(RENDER_EFFECT, null);\n\tset_signal_status(effect, CLEAN);\n\teffect.teardown = fn;\n\treturn effect;\n}\n\n/**\n * Internal representation of `$effect(...)`\n * @param {() => void | (() => void)} fn\n */\nexport function user_effect(fn) {\n\tvalidate_effect('$effect');\n\n\tif (DEV) {\n\t\tdefine_property(fn, 'name', {\n\t\t\tvalue: '$effect'\n\t\t});\n\t}\n\n\t// Non-nested `$effect(...)` in a component should be deferred\n\t// until the component is mounted\n\tvar flags = /** @type {Effect} */ (active_effect).f;\n\tvar defer = !active_reaction && (flags & BRANCH_EFFECT) !== 0 && (flags & REACTION_RAN) === 0;\n\n\tif (defer) {\n\t\t// Top-level `$effect(...)` in an unmounted component — defer until mount\n\t\tvar context = /** @type {ComponentContext} */ (component_context);\n\t\t(context.e ??= []).push(fn);\n\t} else {\n\t\t// Everything else — create immediately\n\t\treturn create_user_effect(fn);\n\t}\n}\n\n/**\n * @param {() => void | (() => void)} fn\n */\nexport function create_user_effect(fn) {\n\treturn create_effect(EFFECT | USER_EFFECT, fn);\n}\n\n/**\n * Internal representation of `$effect.pre(...)`\n * @param {() => void | (() => void)} fn\n * @returns {Effect}\n */\nexport function user_pre_effect(fn) {\n\tvalidate_effect('$effect.pre');\n\tif (DEV) {\n\t\tdefine_property(fn, 'name', {\n\t\t\tvalue: '$effect.pre'\n\t\t});\n\t}\n\treturn create_effect(RENDER_EFFECT | USER_EFFECT, fn);\n}\n\n/** @param {() => void | (() => void)} fn */\nexport function eager_effect(fn) {\n\treturn create_effect(EAGER_EFFECT, fn);\n}\n\n/**\n * Internal representation of `$effect.root(...)`\n * @param {() => void | (() => void)} fn\n * @returns {() => void}\n */\nexport function effect_root(fn) {\n\tBatch.ensure();\n\tconst effect = create_effect(ROOT_EFFECT | EFFECT_PRESERVED, fn);\n\n\treturn () => {\n\t\tdestroy_effect(effect);\n\t};\n}\n\n/**\n * An effect root whose children can transition out\n * @param {() => void} fn\n * @returns {(options?: { outro?: boolean }) => Promise}\n */\nexport function component_root(fn) {\n\tBatch.ensure();\n\tconst effect = create_effect(ROOT_EFFECT | EFFECT_PRESERVED, fn);\n\n\treturn (options = {}) => {\n\t\treturn new Promise((fulfil) => {\n\t\t\tif (options.outro) {\n\t\t\t\tpause_effect(effect, () => {\n\t\t\t\t\tdestroy_effect(effect);\n\t\t\t\t\tfulfil(undefined);\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tdestroy_effect(effect);\n\t\t\t\tfulfil(undefined);\n\t\t\t}\n\t\t});\n\t};\n}\n\n/**\n * @param {() => void | (() => void)} fn\n * @returns {Effect}\n */\nexport function effect(fn) {\n\treturn create_effect(EFFECT, fn);\n}\n\n/**\n * Internal representation of `$: ..`\n * @param {() => any} deps\n * @param {() => void | (() => void)} fn\n */\nexport function legacy_pre_effect(deps, fn) {\n\tvar context = /** @type {ComponentContextLegacy} */ (component_context);\n\n\t/** @type {{ effect: null | Effect, ran: boolean, deps: () => any }} */\n\tvar token = { effect: null, ran: false, deps };\n\n\tcontext.l.$.push(token);\n\n\ttoken.effect = render_effect(() => {\n\t\tdeps();\n\n\t\t// If this legacy pre effect has already run before the end of the reset, then\n\t\t// bail out to emulate the same behavior.\n\t\tif (token.ran) return;\n\n\t\ttoken.ran = true;\n\n\t\tvar effect = /** @type {Effect} */ (active_effect);\n\n\t\t// here, we lie: by setting `active_effect` to be the parent branch, any writes\n\t\t// that happen inside `fn` will _not_ cause an unnecessary reschedule, because\n\t\t// the affected effects will be children of `active_effect`. this is safe\n\t\t// because these effects are known to run in the correct order\n\t\ttry {\n\t\t\tset_active_effect(effect.parent);\n\t\t\tuntrack(fn);\n\t\t} finally {\n\t\t\tset_active_effect(effect);\n\t\t}\n\t});\n}\n\nexport function legacy_pre_effect_reset() {\n\tvar context = /** @type {ComponentContextLegacy} */ (component_context);\n\n\trender_effect(() => {\n\t\t// Run dirty `$:` statements\n\t\tfor (var token of context.l.$) {\n\t\t\ttoken.deps();\n\n\t\t\tvar effect = token.effect;\n\n\t\t\t// If the effect is CLEAN, then make it MAYBE_DIRTY. This ensures we traverse through\n\t\t\t// the effects dependencies and correctly ensure each dependency is up-to-date.\n\t\t\tif ((effect.f & CLEAN) !== 0 && effect.deps !== null) {\n\t\t\t\tset_signal_status(effect, MAYBE_DIRTY);\n\t\t\t}\n\n\t\t\tif (is_dirty(effect)) {\n\t\t\t\tupdate_effect(effect);\n\t\t\t}\n\n\t\t\ttoken.ran = false;\n\t\t}\n\t});\n}\n\n/**\n * @param {() => void | (() => void)} fn\n * @returns {Effect}\n */\nexport function async_effect(fn) {\n\treturn create_effect(ASYNC | EFFECT_PRESERVED, fn);\n}\n\n/**\n * @param {() => void | (() => void)} fn\n * @returns {Effect}\n */\nexport function render_effect(fn, flags = 0) {\n\treturn create_effect(RENDER_EFFECT | flags, fn);\n}\n\n/**\n * @param {(...expressions: any) => void | (() => void)} fn\n * @param {Array<() => any>} sync\n * @param {Array<() => Promise>} async\n * @param {Blocker[]} blockers\n */\nexport function template_effect(fn, sync = [], async = [], blockers = []) {\n\tflatten(blockers, sync, async, (values) => {\n\t\tcreate_effect(RENDER_EFFECT, () => fn(...values.map(get)));\n\t});\n}\n\n/**\n * Like `template_effect`, but with an effect which is deferred until the batch commits\n * @param {(...expressions: any) => void | (() => void)} fn\n * @param {Array<() => any>} sync\n * @param {Array<() => Promise>} async\n * @param {Blocker[]} blockers\n */\nexport function deferred_template_effect(fn, sync = [], async = [], blockers = []) {\n\tif (async.length > 0 || blockers.length > 0) {\n\t\tvar decrement_pending = increment_pending();\n\t}\n\n\tflatten(blockers, sync, async, (values) => {\n\t\tcreate_effect(EFFECT, () => fn(...values.map(get)));\n\n\t\tif (decrement_pending) {\n\t\t\tdecrement_pending();\n\t\t}\n\t});\n}\n\n/**\n * @param {(() => void)} fn\n * @param {number} flags\n */\nexport function block(fn, flags = 0) {\n\tvar effect = create_effect(BLOCK_EFFECT | flags, fn);\n\tif (DEV) {\n\t\teffect.dev_stack = dev_stack;\n\t}\n\treturn effect;\n}\n\n/**\n * @param {(() => void)} fn\n * @param {number} flags\n */\nexport function managed(fn, flags = 0) {\n\tvar effect = create_effect(MANAGED_EFFECT | flags, fn);\n\tif (DEV) {\n\t\teffect.dev_stack = dev_stack;\n\t}\n\treturn effect;\n}\n\n/**\n * @param {(() => void)} fn\n */\nexport function branch(fn) {\n\treturn create_effect(BRANCH_EFFECT | EFFECT_PRESERVED, fn);\n}\n\n/**\n * @param {Effect} effect\n */\nexport function execute_effect_teardown(effect) {\n\tvar teardown = effect.teardown;\n\tif (teardown !== null) {\n\t\tconst previously_destroying_effect = is_destroying_effect;\n\t\tconst previous_reaction = active_reaction;\n\t\tset_is_destroying_effect(true);\n\t\tset_active_reaction(null);\n\t\ttry {\n\t\t\tteardown.call(null);\n\t\t} finally {\n\t\t\tset_is_destroying_effect(previously_destroying_effect);\n\t\t\tset_active_reaction(previous_reaction);\n\t\t}\n\t}\n}\n\n/**\n * @param {Effect} signal\n * @param {boolean} remove_dom\n * @returns {void}\n */\nexport function destroy_effect_children(signal, remove_dom = false) {\n\tvar effect = signal.first;\n\tsignal.first = signal.last = null;\n\n\twhile (effect !== null) {\n\t\tconst controller = effect.ac;\n\n\t\tif (controller !== null) {\n\t\t\twithout_reactive_context(() => {\n\t\t\t\tcontroller.abort(STALE_REACTION);\n\t\t\t});\n\t\t}\n\n\t\tvar next = effect.next;\n\n\t\tif ((effect.f & ROOT_EFFECT) !== 0) {\n\t\t\t// this is now an independent root\n\t\t\teffect.parent = null;\n\t\t} else {\n\t\t\tdestroy_effect(effect, remove_dom);\n\t\t}\n\n\t\teffect = next;\n\t}\n}\n\n/**\n * @param {Effect} signal\n * @returns {void}\n */\nexport function destroy_block_effect_children(signal) {\n\tvar effect = signal.first;\n\n\twhile (effect !== null) {\n\t\tvar next = effect.next;\n\t\tif ((effect.f & BRANCH_EFFECT) === 0) {\n\t\t\tdestroy_effect(effect);\n\t\t}\n\t\teffect = next;\n\t}\n}\n\n/**\n * @param {Effect} effect\n * @param {boolean} [remove_dom]\n * @returns {void}\n */\nexport function destroy_effect(effect, remove_dom = true) {\n\tvar removed = false;\n\n\tif (\n\t\t(remove_dom || (effect.f & HEAD_EFFECT) !== 0) &&\n\t\teffect.nodes !== null &&\n\t\teffect.nodes.end !== null\n\t) {\n\t\tremove_effect_dom(effect.nodes.start, /** @type {TemplateNode} */ (effect.nodes.end));\n\t\tremoved = true;\n\t}\n\n\tset_signal_status(effect, DESTROYING);\n\tdestroy_effect_children(effect, remove_dom && !removed);\n\tremove_reactions(effect, 0);\n\n\tvar transitions = effect.nodes && effect.nodes.t;\n\n\tif (transitions !== null) {\n\t\tfor (const transition of transitions) {\n\t\t\ttransition.stop();\n\t\t}\n\t}\n\n\texecute_effect_teardown(effect);\n\n\teffect.f ^= DESTROYING;\n\teffect.f |= DESTROYED;\n\n\tvar parent = effect.parent;\n\n\t// If the parent doesn't have any children, then skip this work altogether\n\tif (parent !== null && parent.first !== null) {\n\t\tunlink_effect(effect);\n\t}\n\n\tif (DEV) {\n\t\teffect.component_function = null;\n\t}\n\n\t// `first` and `child` are nulled out in destroy_effect_children\n\t// we don't null out `parent` so that error propagation can work correctly\n\teffect.next =\n\t\teffect.prev =\n\t\teffect.teardown =\n\t\teffect.ctx =\n\t\teffect.deps =\n\t\teffect.fn =\n\t\teffect.nodes =\n\t\teffect.ac =\n\t\teffect.b =\n\t\t\tnull;\n}\n\n/**\n *\n * @param {TemplateNode | null} node\n * @param {TemplateNode} end\n */\nexport function remove_effect_dom(node, end) {\n\twhile (node !== null) {\n\t\t/** @type {TemplateNode | null} */\n\t\tvar next = node === end ? null : get_next_sibling(node);\n\n\t\tnode.remove();\n\t\tnode = next;\n\t}\n}\n\n/**\n * Detach an effect from the effect tree, freeing up memory and\n * reducing the amount of work that happens on subsequent traversals\n * @param {Effect} effect\n */\nexport function unlink_effect(effect) {\n\tvar parent = effect.parent;\n\tvar prev = effect.prev;\n\tvar next = effect.next;\n\n\tif (prev !== null) prev.next = next;\n\tif (next !== null) next.prev = prev;\n\n\tif (parent !== null) {\n\t\tif (parent.first === effect) parent.first = next;\n\t\tif (parent.last === effect) parent.last = prev;\n\t}\n}\n\n/**\n * When a block effect is removed, we don't immediately destroy it or yank it\n * out of the DOM, because it might have transitions. Instead, we 'pause' it.\n * It stays around (in memory, and in the DOM) until outro transitions have\n * completed, and if the state change is reversed then we _resume_ it.\n * A paused effect does not update, and the DOM subtree becomes inert.\n * @param {Effect} effect\n * @param {() => void} [callback]\n * @param {boolean} [destroy]\n */\nexport function pause_effect(effect, callback, destroy = true) {\n\t/** @type {TransitionManager[]} */\n\tvar transitions = [];\n\n\tpause_children(effect, transitions, true);\n\n\tvar fn = () => {\n\t\tif (destroy) destroy_effect(effect);\n\t\tif (callback) callback();\n\t};\n\n\tvar remaining = transitions.length;\n\tif (remaining > 0) {\n\t\tvar check = () => --remaining || fn();\n\t\tfor (var transition of transitions) {\n\t\t\ttransition.out(check);\n\t\t}\n\t} else {\n\t\tfn();\n\t}\n}\n\n/**\n * @param {Effect} effect\n * @param {TransitionManager[]} transitions\n * @param {boolean} local\n */\nfunction pause_children(effect, transitions, local) {\n\tif ((effect.f & INERT) !== 0) return;\n\teffect.f ^= INERT;\n\n\tvar t = effect.nodes && effect.nodes.t;\n\n\tif (t !== null) {\n\t\tfor (const transition of t) {\n\t\t\tif (transition.is_global || local) {\n\t\t\t\ttransitions.push(transition);\n\t\t\t}\n\t\t}\n\t}\n\n\tvar child = effect.first;\n\n\twhile (child !== null) {\n\t\tvar sibling = child.next;\n\n\t\t// If this child is a root effect, then it will become an independent root when its parent\n\t\t// is destroyed, it should therefore not become inert nor partake in transitions.\n\t\tif ((child.f & ROOT_EFFECT) === 0) {\n\t\t\tvar transparent =\n\t\t\t\t(child.f & EFFECT_TRANSPARENT) !== 0 ||\n\t\t\t\t// If this is a branch effect without a block effect parent,\n\t\t\t\t// it means the parent block effect was pruned. In that case,\n\t\t\t\t// transparency information was transferred to the branch effect.\n\t\t\t\t((child.f & BRANCH_EFFECT) !== 0 && (effect.f & BLOCK_EFFECT) !== 0);\n\t\t\t// TODO we don't need to call pause_children recursively with a linked list in place\n\t\t\t// it's slightly more involved though as we have to account for `transparent` changing\n\t\t\t// through the tree.\n\t\t\tpause_children(child, transitions, transparent ? local : false);\n\t\t}\n\n\t\tchild = sibling;\n\t}\n}\n\n/**\n * The opposite of `pause_effect`. We call this if (for example)\n * `x` becomes falsy then truthy: `{#if x}...{/if}`\n * @param {Effect} effect\n */\nexport function resume_effect(effect) {\n\tresume_children(effect, true);\n}\n\n/**\n * @param {Effect} effect\n * @param {boolean} local\n */\nfunction resume_children(effect, local) {\n\tif ((effect.f & INERT) === 0) return;\n\teffect.f ^= INERT;\n\n\t// If a dependency of this effect changed while it was paused,\n\t// schedule the effect to update. we don't use `is_dirty`\n\t// here because we don't want to eagerly recompute a derived like\n\t// `{#if foo}{foo.bar()}{/if}` if `foo` is now `undefined\n\tif ((effect.f & CLEAN) === 0) {\n\t\tset_signal_status(effect, DIRTY);\n\t\tBatch.ensure().schedule(effect); // Assumption: This happens during the commit phase of the batch, causing another flush, but it's safe\n\t}\n\n\tvar child = effect.first;\n\n\twhile (child !== null) {\n\t\tvar sibling = child.next;\n\t\tvar transparent = (child.f & EFFECT_TRANSPARENT) !== 0 || (child.f & BRANCH_EFFECT) !== 0;\n\t\t// TODO we don't need to call resume_children recursively with a linked list in place\n\t\t// it's slightly more involved though as we have to account for `transparent` changing\n\t\t// through the tree.\n\t\tresume_children(child, transparent ? local : false);\n\t\tchild = sibling;\n\t}\n\n\tvar t = effect.nodes && effect.nodes.t;\n\n\tif (t !== null) {\n\t\tfor (const transition of t) {\n\t\t\tif (transition.is_global || local) {\n\t\t\t\ttransition.in();\n\t\t\t}\n\t\t}\n\t}\n}\n\nexport function aborted(effect = /** @type {Effect} */ (active_effect)) {\n\treturn (effect.f & DESTROYED) !== 0;\n}\n\n/**\n * @param {Effect} effect\n * @param {DocumentFragment} fragment\n */\nexport function move_effect(effect, fragment) {\n\tif (!effect.nodes) return;\n\n\t/** @type {TemplateNode | null} */\n\tvar node = effect.nodes.start;\n\tvar end = effect.nodes.end;\n\n\twhile (node !== null) {\n\t\t/** @type {TemplateNode | null} */\n\t\tvar next = node === end ? null : get_next_sibling(node);\n\n\t\tfragment.append(node);\n\t\tnode = next;\n\t}\n}\n","/** @import { Derived, Effect, Reaction, Source, Value } from '#client' */\nimport { DEV } from 'esm-env';\nimport { get_descriptors, get_prototype_of, includes, index_of } from '../shared/utils.js';\nimport {\n\tdestroy_block_effect_children,\n\tdestroy_effect_children,\n\teffect_tracking,\n\texecute_effect_teardown\n} from './reactivity/effects.js';\nimport {\n\tDIRTY,\n\tMAYBE_DIRTY,\n\tCLEAN,\n\tDERIVED,\n\tDESTROYED,\n\tBRANCH_EFFECT,\n\tSTATE_SYMBOL,\n\tBLOCK_EFFECT,\n\tROOT_EFFECT,\n\tCONNECTED,\n\tREACTION_IS_UPDATING,\n\tSTALE_REACTION,\n\tERROR_VALUE,\n\tWAS_MARKED,\n\tMANAGED_EFFECT,\n\tREACTION_RAN\n} from './constants.js';\nimport { old_values } from './reactivity/sources.js';\nimport {\n\treactivity_loss_tracker,\n\texecute_derived,\n\tfreeze_derived_effects,\n\trecent_async_deriveds,\n\tunfreeze_derived_effects,\n\tupdate_derived\n} from './reactivity/deriveds.js';\nimport { async_mode_flag, tracing_mode_flag } from '../flags/index.js';\nimport { tracing_expressions } from './dev/tracing.js';\nimport { get_error } from '../shared/dev.js';\nimport {\n\tcomponent_context,\n\tdev_current_component_function,\n\tdev_stack,\n\tis_runes,\n\tset_component_context,\n\tset_dev_current_component_function,\n\tset_dev_stack\n} from './context.js';\nimport {\n\tBatch,\n\tbatch_values,\n\tcurrent_batch,\n\tflushSync,\n\tschedule_effect\n} from './reactivity/batch.js';\nimport { handle_error } from './error-handling.js';\nimport { UNINITIALIZED } from '../../constants.js';\nimport { captured_signals } from './legacy.js';\nimport { without_reactive_context } from './dom/elements/bindings/shared.js';\nimport { set_signal_status, update_derived_status } from './reactivity/status.js';\nimport * as w from './warnings.js';\n\nlet is_updating_effect = false;\n\nexport let is_destroying_effect = false;\n\n/** @param {boolean} value */\nexport function set_is_destroying_effect(value) {\n\tis_destroying_effect = value;\n}\n\n/** @type {null | Reaction} */\nexport let active_reaction = null;\n\nexport let untracking = false;\n\n/** @param {null | Reaction} reaction */\nexport function set_active_reaction(reaction) {\n\tactive_reaction = reaction;\n}\n\n/** @type {null | Effect} */\nexport let active_effect = null;\n\n/** @param {null | Effect} effect */\nexport function set_active_effect(effect) {\n\tactive_effect = effect;\n}\n\n/**\n * When sources are created within a reaction, reading and writing\n * them within that reaction should not cause a re-run\n * @type {null | Source[]}\n */\nexport let current_sources = null;\n\n/** @param {Value} value */\nexport function push_reaction_value(value) {\n\tif (active_reaction !== null && (!async_mode_flag || (active_reaction.f & DERIVED) !== 0)) {\n\t\tif (current_sources === null) {\n\t\t\tcurrent_sources = [value];\n\t\t} else {\n\t\t\tcurrent_sources.push(value);\n\t\t}\n\t}\n}\n\n/**\n * The dependencies of the reaction that is currently being executed. In many cases,\n * the dependencies are unchanged between runs, and so this will be `null` unless\n * and until a new dependency is accessed — we track this via `skipped_deps`\n * @type {null | Value[]}\n */\nexport let new_deps = null;\n\nexport let skipped_deps = 0;\n\n/**\n * Tracks writes that the effect it's executed in doesn't listen to yet,\n * so that the dependency can be added to the effect later on if it then reads it\n * @type {null | Source[]}\n */\nexport let untracked_writes = null;\n\n/** @param {null | Source[]} value */\nexport function set_untracked_writes(value) {\n\tuntracked_writes = value;\n}\n\n/**\n * @type {number} Used by sources and deriveds for handling updates.\n * Version starts from 1 so that unowned deriveds differentiate between a created effect and a run one for tracing\n **/\nexport let write_version = 1;\n\n/** @type {number} Used to version each read of a source of derived to avoid duplicating depedencies inside a reaction */\nlet read_version = 0;\n\nexport let update_version = read_version;\n\n/** @param {number} value */\nexport function set_update_version(value) {\n\tupdate_version = value;\n}\n\nexport function increment_write_version() {\n\treturn ++write_version;\n}\n\n/**\n * Determines whether a derived or effect is dirty.\n * If it is MAYBE_DIRTY, will set the status to CLEAN\n * @param {Reaction} reaction\n * @returns {boolean}\n */\nexport function is_dirty(reaction) {\n\tvar flags = reaction.f;\n\n\tif ((flags & DIRTY) !== 0) {\n\t\treturn true;\n\t}\n\n\tif (flags & DERIVED) {\n\t\treaction.f &= ~WAS_MARKED;\n\t}\n\n\tif ((flags & MAYBE_DIRTY) !== 0) {\n\t\tvar dependencies = /** @type {Value[]} */ (reaction.deps);\n\t\tvar length = dependencies.length;\n\n\t\tfor (var i = 0; i < length; i++) {\n\t\t\tvar dependency = dependencies[i];\n\n\t\t\tif (is_dirty(/** @type {Derived} */ (dependency))) {\n\t\t\t\tupdate_derived(/** @type {Derived} */ (dependency));\n\t\t\t}\n\n\t\t\tif (dependency.wv > reaction.wv) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\tif (\n\t\t\t(flags & CONNECTED) !== 0 &&\n\t\t\t// During time traveling we don't want to reset the status so that\n\t\t\t// traversal of the graph in the other batches still happens\n\t\t\tbatch_values === null\n\t\t) {\n\t\t\tset_signal_status(reaction, CLEAN);\n\t\t}\n\t}\n\n\treturn false;\n}\n\n/**\n * @param {Value} signal\n * @param {Effect} effect\n * @param {boolean} [root]\n */\nfunction schedule_possible_effect_self_invalidation(signal, effect, root = true) {\n\tvar reactions = signal.reactions;\n\tif (reactions === null) return;\n\n\tif (!async_mode_flag && current_sources !== null && includes.call(current_sources, signal)) {\n\t\treturn;\n\t}\n\n\tfor (var i = 0; i < reactions.length; i++) {\n\t\tvar reaction = reactions[i];\n\n\t\tif ((reaction.f & DERIVED) !== 0) {\n\t\t\tschedule_possible_effect_self_invalidation(/** @type {Derived} */ (reaction), effect, false);\n\t\t} else if (effect === reaction) {\n\t\t\tif (root) {\n\t\t\t\tset_signal_status(reaction, DIRTY);\n\t\t\t} else if ((reaction.f & CLEAN) !== 0) {\n\t\t\t\tset_signal_status(reaction, MAYBE_DIRTY);\n\t\t\t}\n\t\t\tschedule_effect(/** @type {Effect} */ (reaction));\n\t\t}\n\t}\n}\n\n/** @param {Reaction} reaction */\nexport function update_reaction(reaction) {\n\tvar previous_deps = new_deps;\n\tvar previous_skipped_deps = skipped_deps;\n\tvar previous_untracked_writes = untracked_writes;\n\tvar previous_reaction = active_reaction;\n\tvar previous_sources = current_sources;\n\tvar previous_component_context = component_context;\n\tvar previous_untracking = untracking;\n\tvar previous_update_version = update_version;\n\n\tvar flags = reaction.f;\n\n\tnew_deps = /** @type {null | Value[]} */ (null);\n\tskipped_deps = 0;\n\tuntracked_writes = null;\n\tactive_reaction = (flags & (BRANCH_EFFECT | ROOT_EFFECT)) === 0 ? reaction : null;\n\n\tcurrent_sources = null;\n\tset_component_context(reaction.ctx);\n\tuntracking = false;\n\tupdate_version = ++read_version;\n\n\tif (reaction.ac !== null) {\n\t\twithout_reactive_context(() => {\n\t\t\t/** @type {AbortController} */ (reaction.ac).abort(STALE_REACTION);\n\t\t});\n\n\t\treaction.ac = null;\n\t}\n\n\ttry {\n\t\treaction.f |= REACTION_IS_UPDATING;\n\t\tvar fn = /** @type {Function} */ (reaction.fn);\n\t\tvar result = fn();\n\t\treaction.f |= REACTION_RAN;\n\t\tvar deps = reaction.deps;\n\n\t\t// Don't remove reactions during fork;\n\t\t// they must remain for when fork is discarded\n\t\tvar is_fork = current_batch?.is_fork;\n\n\t\tif (new_deps !== null) {\n\t\t\tvar i;\n\n\t\t\tif (!is_fork) {\n\t\t\t\tremove_reactions(reaction, skipped_deps);\n\t\t\t}\n\n\t\t\tif (deps !== null && skipped_deps > 0) {\n\t\t\t\tdeps.length = skipped_deps + new_deps.length;\n\t\t\t\tfor (i = 0; i < new_deps.length; i++) {\n\t\t\t\t\tdeps[skipped_deps + i] = new_deps[i];\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treaction.deps = deps = new_deps;\n\t\t\t}\n\n\t\t\tif (effect_tracking() && (reaction.f & CONNECTED) !== 0) {\n\t\t\t\tfor (i = skipped_deps; i < deps.length; i++) {\n\t\t\t\t\t(deps[i].reactions ??= []).push(reaction);\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (!is_fork && deps !== null && skipped_deps < deps.length) {\n\t\t\tremove_reactions(reaction, skipped_deps);\n\t\t\tdeps.length = skipped_deps;\n\t\t}\n\n\t\t// If we're inside an effect and we have untracked writes, then we need to\n\t\t// ensure that if any of those untracked writes result in re-invalidation\n\t\t// of the current effect, then that happens accordingly\n\t\tif (\n\t\t\tis_runes() &&\n\t\t\tuntracked_writes !== null &&\n\t\t\t!untracking &&\n\t\t\tdeps !== null &&\n\t\t\t(reaction.f & (DERIVED | MAYBE_DIRTY | DIRTY)) === 0\n\t\t) {\n\t\t\tfor (i = 0; i < /** @type {Source[]} */ (untracked_writes).length; i++) {\n\t\t\t\tschedule_possible_effect_self_invalidation(\n\t\t\t\t\tuntracked_writes[i],\n\t\t\t\t\t/** @type {Effect} */ (reaction)\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// If we are returning to an previous reaction then\n\t\t// we need to increment the read version to ensure that\n\t\t// any dependencies in this reaction aren't marked with\n\t\t// the same version\n\t\tif (previous_reaction !== null && previous_reaction !== reaction) {\n\t\t\tread_version++;\n\n\t\t\t// update the `rv` of the previous reaction's deps — both existing and new —\n\t\t\t// so that they are not added again\n\t\t\tif (previous_reaction.deps !== null) {\n\t\t\t\tfor (let i = 0; i < previous_skipped_deps; i += 1) {\n\t\t\t\t\tprevious_reaction.deps[i].rv = read_version;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (previous_deps !== null) {\n\t\t\t\tfor (const dep of previous_deps) {\n\t\t\t\t\tdep.rv = read_version;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (untracked_writes !== null) {\n\t\t\t\tif (previous_untracked_writes === null) {\n\t\t\t\t\tprevious_untracked_writes = untracked_writes;\n\t\t\t\t} else {\n\t\t\t\t\tprevious_untracked_writes.push(.../** @type {Source[]} */ (untracked_writes));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif ((reaction.f & ERROR_VALUE) !== 0) {\n\t\t\treaction.f ^= ERROR_VALUE;\n\t\t}\n\n\t\treturn result;\n\t} catch (error) {\n\t\treturn handle_error(error);\n\t} finally {\n\t\treaction.f ^= REACTION_IS_UPDATING;\n\t\tnew_deps = previous_deps;\n\t\tskipped_deps = previous_skipped_deps;\n\t\tuntracked_writes = previous_untracked_writes;\n\t\tactive_reaction = previous_reaction;\n\t\tcurrent_sources = previous_sources;\n\t\tset_component_context(previous_component_context);\n\t\tuntracking = previous_untracking;\n\t\tupdate_version = previous_update_version;\n\t}\n}\n\n/**\n * @template V\n * @param {Reaction} signal\n * @param {Value} dependency\n * @returns {void}\n */\nfunction remove_reaction(signal, dependency) {\n\tlet reactions = dependency.reactions;\n\tif (reactions !== null) {\n\t\tvar index = index_of.call(reactions, signal);\n\t\tif (index !== -1) {\n\t\t\tvar new_length = reactions.length - 1;\n\t\t\tif (new_length === 0) {\n\t\t\t\treactions = dependency.reactions = null;\n\t\t\t} else {\n\t\t\t\t// Swap with last element and then remove.\n\t\t\t\treactions[index] = reactions[new_length];\n\t\t\t\treactions.pop();\n\t\t\t}\n\t\t}\n\t}\n\n\t// If the derived has no reactions, then we can disconnect it from the graph,\n\t// allowing it to either reconnect in the future, or be GC'd by the VM.\n\tif (\n\t\treactions === null &&\n\t\t(dependency.f & DERIVED) !== 0 &&\n\t\t// Destroying a child effect while updating a parent effect can cause a dependency to appear\n\t\t// to be unused, when in fact it is used by the currently-updating parent. Checking `new_deps`\n\t\t// allows us to skip the expensive work of disconnecting and immediately reconnecting it\n\t\t(new_deps === null || !includes.call(new_deps, dependency))\n\t) {\n\t\tvar derived = /** @type {Derived} */ (dependency);\n\n\t\t// If we are working with a derived that is owned by an effect, then mark it as being\n\t\t// disconnected and remove the mark flag, as it cannot be reliably removed otherwise\n\t\tif ((derived.f & CONNECTED) !== 0) {\n\t\t\tderived.f ^= CONNECTED;\n\t\t\tderived.f &= ~WAS_MARKED;\n\t\t}\n\n\t\t// In a fork it's possible that a derived is executed and gets reactions, then commits, but is\n\t\t// never re-executed. This is possible when the derived is only executed once in the context\n\t\t// of a new branch which happens before fork.commit() runs. In this case, the derived still has\n\t\t// UNINITIALIZED as its value, and then when it's loosing its reactions we need to ensure it stays\n\t\t// DIRTY so it is reexecuted once someone wants its value again.\n\t\tif (derived.v !== UNINITIALIZED) {\n\t\t\tupdate_derived_status(derived);\n\t\t}\n\n\t\t// freeze any effects inside this derived\n\t\tfreeze_derived_effects(derived);\n\n\t\t// Disconnect any reactions owned by this reaction\n\t\tremove_reactions(derived, 0);\n\t}\n}\n\n/**\n * @param {Reaction} signal\n * @param {number} start_index\n * @returns {void}\n */\nexport function remove_reactions(signal, start_index) {\n\tvar dependencies = signal.deps;\n\tif (dependencies === null) return;\n\n\tfor (var i = start_index; i < dependencies.length; i++) {\n\t\tremove_reaction(signal, dependencies[i]);\n\t}\n}\n\n/**\n * @param {Effect} effect\n * @returns {void}\n */\nexport function update_effect(effect) {\n\tvar flags = effect.f;\n\n\tif ((flags & DESTROYED) !== 0) {\n\t\treturn;\n\t}\n\n\tset_signal_status(effect, CLEAN);\n\n\tvar previous_effect = active_effect;\n\tvar was_updating_effect = is_updating_effect;\n\n\tactive_effect = effect;\n\tis_updating_effect = true;\n\n\tif (DEV) {\n\t\tvar previous_component_fn = dev_current_component_function;\n\t\tset_dev_current_component_function(effect.component_function);\n\t\tvar previous_stack = /** @type {any} */ (dev_stack);\n\t\t// only block effects have a dev stack, keep the current one otherwise\n\t\tset_dev_stack(effect.dev_stack ?? dev_stack);\n\t}\n\n\ttry {\n\t\tif ((flags & (BLOCK_EFFECT | MANAGED_EFFECT)) !== 0) {\n\t\t\tdestroy_block_effect_children(effect);\n\t\t} else {\n\t\t\tdestroy_effect_children(effect);\n\t\t}\n\n\t\texecute_effect_teardown(effect);\n\t\tvar teardown = update_reaction(effect);\n\t\teffect.teardown = typeof teardown === 'function' ? teardown : null;\n\t\teffect.wv = write_version;\n\n\t\t// In DEV, increment versions of any sources that were written to during the effect,\n\t\t// so that they are correctly marked as dirty when the effect re-runs\n\t\tif (DEV && tracing_mode_flag && (effect.f & DIRTY) !== 0 && effect.deps !== null) {\n\t\t\tfor (var dep of effect.deps) {\n\t\t\t\tif (dep.set_during_effect) {\n\t\t\t\t\tdep.wv = increment_write_version();\n\t\t\t\t\tdep.set_during_effect = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} finally {\n\t\tis_updating_effect = was_updating_effect;\n\t\tactive_effect = previous_effect;\n\n\t\tif (DEV) {\n\t\t\tset_dev_current_component_function(previous_component_fn);\n\t\t\tset_dev_stack(previous_stack);\n\t\t}\n\t}\n}\n\n/**\n * Returns a promise that resolves once any pending state changes have been applied.\n * @returns {Promise}\n */\nexport async function tick() {\n\tif (async_mode_flag) {\n\t\treturn new Promise((f) => {\n\t\t\t// Race them against each other - in almost all cases requestAnimationFrame will fire first,\n\t\t\t// but e.g. in case the window is not focused or a view transition happens, requestAnimationFrame\n\t\t\t// will be delayed and setTimeout helps us resolve fast enough in that case\n\t\t\trequestAnimationFrame(() => f());\n\t\t\tsetTimeout(() => f());\n\t\t});\n\t}\n\n\tawait Promise.resolve();\n\n\t// By calling flushSync we guarantee that any pending state changes are applied after one tick.\n\t// TODO look into whether we can make flushing subsequent updates synchronously in the future.\n\tflushSync();\n}\n\n/**\n * Returns a promise that resolves once any state changes, and asynchronous work resulting from them,\n * have resolved and the DOM has been updated\n * @returns {Promise}\n * @since 5.36\n */\nexport function settled() {\n\treturn Batch.ensure().settled();\n}\n\n/**\n * @template V\n * @param {Value} signal\n * @returns {V}\n */\nexport function get(signal) {\n\tvar flags = signal.f;\n\tvar is_derived = (flags & DERIVED) !== 0;\n\n\tcaptured_signals?.add(signal);\n\n\t// Register the dependency on the current reaction signal.\n\tif (active_reaction !== null && !untracking) {\n\t\t// if we're in a derived that is being read inside an _async_ derived,\n\t\t// it's possible that the effect was already destroyed. In this case,\n\t\t// we don't add the dependency, because that would create a memory leak\n\t\tvar destroyed = active_effect !== null && (active_effect.f & DESTROYED) !== 0;\n\n\t\tif (!destroyed && (current_sources === null || !includes.call(current_sources, signal))) {\n\t\t\tvar deps = active_reaction.deps;\n\n\t\t\tif ((active_reaction.f & REACTION_IS_UPDATING) !== 0) {\n\t\t\t\t// we're in the effect init/update cycle\n\t\t\t\tif (signal.rv < read_version) {\n\t\t\t\t\tsignal.rv = read_version;\n\n\t\t\t\t\t// If the signal is accessing the same dependencies in the same\n\t\t\t\t\t// order as it did last time, increment `skipped_deps`\n\t\t\t\t\t// rather than updating `new_deps`, which creates GC cost\n\t\t\t\t\tif (new_deps === null && deps !== null && deps[skipped_deps] === signal) {\n\t\t\t\t\t\tskipped_deps++;\n\t\t\t\t\t} else if (new_deps === null) {\n\t\t\t\t\t\tnew_deps = [signal];\n\t\t\t\t\t} else {\n\t\t\t\t\t\tnew_deps.push(signal);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// we're adding a dependency outside the init/update cycle\n\t\t\t\t// (i.e. after an `await`)\n\t\t\t\t(active_reaction.deps ??= []).push(signal);\n\n\t\t\t\tvar reactions = signal.reactions;\n\n\t\t\t\tif (reactions === null) {\n\t\t\t\t\tsignal.reactions = [active_reaction];\n\t\t\t\t} else if (!includes.call(reactions, active_reaction)) {\n\t\t\t\t\treactions.push(active_reaction);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif (DEV) {\n\t\tif (\n\t\t\t!untracking &&\n\t\t\treactivity_loss_tracker &&\n\t\t\t!reactivity_loss_tracker.warned &&\n\t\t\t(reactivity_loss_tracker.effect.f & REACTION_IS_UPDATING) === 0 &&\n\t\t\t!reactivity_loss_tracker.effect_deps.has(signal)\n\t\t) {\n\t\t\treactivity_loss_tracker.warned = true;\n\n\t\t\tw.await_reactivity_loss(/** @type {string} */ (signal.label));\n\n\t\t\tvar trace = get_error('traced at');\n\t\t\t// eslint-disable-next-line no-console\n\t\t\tif (trace) console.warn(trace);\n\t\t}\n\n\t\trecent_async_deriveds.delete(signal);\n\n\t\tif (\n\t\t\ttracing_mode_flag &&\n\t\t\t!untracking &&\n\t\t\ttracing_expressions !== null &&\n\t\t\tactive_reaction !== null &&\n\t\t\ttracing_expressions.reaction === active_reaction\n\t\t) {\n\t\t\t// Used when mapping state between special blocks like `each`\n\t\t\tif (signal.trace) {\n\t\t\t\tsignal.trace();\n\t\t\t} else {\n\t\t\t\ttrace = get_error('traced at');\n\n\t\t\t\tif (trace) {\n\t\t\t\t\tvar entry = tracing_expressions.entries.get(signal);\n\n\t\t\t\t\tif (entry === undefined) {\n\t\t\t\t\t\tentry = { traces: [] };\n\t\t\t\t\t\ttracing_expressions.entries.set(signal, entry);\n\t\t\t\t\t}\n\n\t\t\t\t\tvar last = entry.traces[entry.traces.length - 1];\n\n\t\t\t\t\t// traces can be duplicated, e.g. by `snapshot` invoking both\n\t\t\t\t\t// both `getOwnPropertyDescriptor` and `get` traps at once\n\t\t\t\t\tif (trace.stack !== last?.stack) {\n\t\t\t\t\t\tentry.traces.push(trace);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif (is_destroying_effect && old_values.has(signal)) {\n\t\treturn old_values.get(signal);\n\t}\n\n\tif (is_derived) {\n\t\tvar derived = /** @type {Derived} */ (signal);\n\n\t\tif (is_destroying_effect) {\n\t\t\tvar value = derived.v;\n\n\t\t\t// if the derived is dirty and has reactions, or depends on the values that just changed, re-execute\n\t\t\t// (a derived can be maybe_dirty due to the effect destroy removing its last reaction)\n\t\t\tif (\n\t\t\t\t((derived.f & CLEAN) === 0 && derived.reactions !== null) ||\n\t\t\t\tdepends_on_old_values(derived)\n\t\t\t) {\n\t\t\t\tvalue = execute_derived(derived);\n\t\t\t}\n\n\t\t\told_values.set(derived, value);\n\n\t\t\treturn value;\n\t\t}\n\n\t\t// connect disconnected deriveds if we are reading them inside an effect,\n\t\t// or inside another derived that is already connected\n\t\tvar should_connect =\n\t\t\t(derived.f & CONNECTED) === 0 &&\n\t\t\t!untracking &&\n\t\t\tactive_reaction !== null &&\n\t\t\t(is_updating_effect || (active_reaction.f & CONNECTED) !== 0);\n\n\t\tvar is_new = (derived.f & REACTION_RAN) === 0;\n\n\t\tif (is_dirty(derived)) {\n\t\t\tif (should_connect) {\n\t\t\t\t// set the flag before `update_derived`, so that the derived\n\t\t\t\t// is added as a reaction to its dependencies\n\t\t\t\tderived.f |= CONNECTED;\n\t\t\t}\n\n\t\t\tupdate_derived(derived);\n\t\t}\n\n\t\tif (should_connect && !is_new) {\n\t\t\tunfreeze_derived_effects(derived);\n\t\t\treconnect(derived);\n\t\t}\n\t}\n\n\tif (batch_values?.has(signal)) {\n\t\treturn batch_values.get(signal);\n\t}\n\n\tif ((signal.f & ERROR_VALUE) !== 0) {\n\t\tthrow signal.v;\n\t}\n\n\treturn signal.v;\n}\n\n/**\n * (Re)connect a disconnected derived, so that it is notified\n * of changes in `mark_reactions`\n * @param {Derived} derived\n */\nfunction reconnect(derived) {\n\tderived.f |= CONNECTED;\n\n\tif (derived.deps === null) return;\n\n\tfor (const dep of derived.deps) {\n\t\t(dep.reactions ??= []).push(derived);\n\n\t\tif ((dep.f & DERIVED) !== 0 && (dep.f & CONNECTED) === 0) {\n\t\t\tunfreeze_derived_effects(/** @type {Derived} */ (dep));\n\t\t\treconnect(/** @type {Derived} */ (dep));\n\t\t}\n\t}\n}\n\n/** @param {Derived} derived */\nfunction depends_on_old_values(derived) {\n\tif (derived.v === UNINITIALIZED) return true; // we don't know, so assume the worst\n\tif (derived.deps === null) return false;\n\n\tfor (const dep of derived.deps) {\n\t\tif (old_values.has(dep)) {\n\t\t\treturn true;\n\t\t}\n\n\t\tif ((dep.f & DERIVED) !== 0 && depends_on_old_values(/** @type {Derived} */ (dep))) {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn false;\n}\n\n/**\n * Like `get`, but checks for `undefined`. Used for `var` declarations because they can be accessed before being declared\n * @template V\n * @param {Value | undefined} signal\n * @returns {V | undefined}\n */\nexport function safe_get(signal) {\n\treturn signal && get(signal);\n}\n\n/**\n * When used inside a [`$derived`](https://svelte.dev/docs/svelte/$derived) or [`$effect`](https://svelte.dev/docs/svelte/$effect),\n * any state read inside `fn` will not be treated as a dependency.\n *\n * ```ts\n * $effect(() => {\n * // this will run when `data` changes, but not when `time` changes\n * save(data, {\n * timestamp: untrack(() => time)\n * });\n * });\n * ```\n * @template T\n * @param {() => T} fn\n * @returns {T}\n */\nexport function untrack(fn) {\n\tvar previous_untracking = untracking;\n\ttry {\n\t\tuntracking = true;\n\t\treturn fn();\n\t} finally {\n\t\tuntracking = previous_untracking;\n\t}\n}\n\n/**\n * Possibly traverse an object and read all its properties so that they're all reactive in case this is `$state`.\n * Does only check first level of an object for performance reasons (heuristic should be good for 99% of all cases).\n * @param {any} value\n * @returns {void}\n */\nexport function deep_read_state(value) {\n\tif (typeof value !== 'object' || !value || value instanceof EventTarget) {\n\t\treturn;\n\t}\n\n\tif (STATE_SYMBOL in value) {\n\t\tdeep_read(value);\n\t} else if (!Array.isArray(value)) {\n\t\tfor (let key in value) {\n\t\t\tconst prop = value[key];\n\t\t\tif (typeof prop === 'object' && prop && STATE_SYMBOL in prop) {\n\t\t\t\tdeep_read(prop);\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Deeply traverse an object and read all its properties\n * so that they're all reactive in case this is `$state`\n * @param {any} value\n * @param {Set} visited\n * @returns {void}\n */\nexport function deep_read(value, visited = new Set()) {\n\tif (\n\t\ttypeof value === 'object' &&\n\t\tvalue !== null &&\n\t\t// We don't want to traverse DOM elements\n\t\t!(value instanceof EventTarget) &&\n\t\t!visited.has(value)\n\t) {\n\t\tvisited.add(value);\n\t\t// When working with a possible SvelteDate, this\n\t\t// will ensure we capture changes to it.\n\t\tif (value instanceof Date) {\n\t\t\tvalue.getTime();\n\t\t}\n\t\tfor (let key in value) {\n\t\t\ttry {\n\t\t\t\tdeep_read(value[key], visited);\n\t\t\t} catch (e) {\n\t\t\t\t// continue\n\t\t\t}\n\t\t}\n\t\tconst proto = get_prototype_of(value);\n\t\tif (\n\t\t\tproto !== Object.prototype &&\n\t\t\tproto !== Array.prototype &&\n\t\t\tproto !== Map.prototype &&\n\t\t\tproto !== Set.prototype &&\n\t\t\tproto !== Date.prototype\n\t\t) {\n\t\t\tconst descriptors = get_descriptors(proto);\n\t\t\tfor (let key in descriptors) {\n\t\t\t\tconst get = descriptors[key].get;\n\t\t\t\tif (get) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tget.call(value);\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\t// continue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n","import { teardown } from '../../reactivity/effects.js';\nimport { define_property } from '../../../shared/utils.js';\nimport { hydrating } from '../hydration.js';\nimport { queue_micro_task } from '../task.js';\nimport { FILENAME } from '../../../../constants.js';\nimport * as w from '../../warnings.js';\nimport {\n\tactive_effect,\n\tactive_reaction,\n\tset_active_effect,\n\tset_active_reaction\n} from '../../runtime.js';\nimport { without_reactive_context } from './bindings/shared.js';\n\n/**\n * Used on elements, as a map of event type -> event handler,\n * and on events themselves to track which element handled an event\n */\nexport const event_symbol = Symbol('events');\n\n/** @type {Set} */\nexport const all_registered_events = new Set();\n\n/** @type {Set<(events: Array) => void>} */\nexport const root_event_handles = new Set();\n\n/**\n * SSR adds onload and onerror attributes to catch those events before the hydration.\n * This function detects those cases, removes the attributes and replays the events.\n * @param {HTMLElement} dom\n */\nexport function replay_events(dom) {\n\tif (!hydrating) return;\n\n\tdom.removeAttribute('onload');\n\tdom.removeAttribute('onerror');\n\t// @ts-expect-error\n\tconst event = dom.__e;\n\tif (event !== undefined) {\n\t\t// @ts-expect-error\n\t\tdom.__e = undefined;\n\t\tqueueMicrotask(() => {\n\t\t\tif (dom.isConnected) {\n\t\t\t\tdom.dispatchEvent(event);\n\t\t\t}\n\t\t});\n\t}\n}\n\n/**\n * @param {string} event_name\n * @param {EventTarget} dom\n * @param {EventListener} [handler]\n * @param {AddEventListenerOptions} [options]\n */\nexport function create_event(event_name, dom, handler, options = {}) {\n\t/**\n\t * @this {EventTarget}\n\t */\n\tfunction target_handler(/** @type {Event} */ event) {\n\t\tif (!options.capture) {\n\t\t\t// Only call in the bubble phase, else delegated events would be called before the capturing events\n\t\t\thandle_event_propagation.call(dom, event);\n\t\t}\n\t\tif (!event.cancelBubble) {\n\t\t\treturn without_reactive_context(() => {\n\t\t\t\treturn handler?.call(this, event);\n\t\t\t});\n\t\t}\n\t}\n\n\t// Chrome has a bug where pointer events don't work when attached to a DOM element that has been cloned\n\t// with cloneNode() and the DOM element is disconnected from the document. To ensure the event works, we\n\t// defer the attachment till after it's been appended to the document. TODO: remove this once Chrome fixes\n\t// this bug. The same applies to wheel events and touch events.\n\tif (\n\t\tevent_name.startsWith('pointer') ||\n\t\tevent_name.startsWith('touch') ||\n\t\tevent_name === 'wheel'\n\t) {\n\t\tqueue_micro_task(() => {\n\t\t\tdom.addEventListener(event_name, target_handler, options);\n\t\t});\n\t} else {\n\t\tdom.addEventListener(event_name, target_handler, options);\n\t}\n\n\treturn target_handler;\n}\n\n/**\n * Attaches an event handler to an element and returns a function that removes the handler. Using this\n * rather than `addEventListener` will preserve the correct order relative to handlers added declaratively\n * (with attributes like `onclick`), which use event delegation for performance reasons\n *\n * @param {EventTarget} element\n * @param {string} type\n * @param {EventListener} handler\n * @param {AddEventListenerOptions} [options]\n */\nexport function on(element, type, handler, options = {}) {\n\tvar target_handler = create_event(type, element, handler, options);\n\n\treturn () => {\n\t\telement.removeEventListener(type, target_handler, options);\n\t};\n}\n\n/**\n * @param {string} event_name\n * @param {Element} dom\n * @param {EventListener} [handler]\n * @param {boolean} [capture]\n * @param {boolean} [passive]\n * @returns {void}\n */\nexport function event(event_name, dom, handler, capture, passive) {\n\tvar options = { capture, passive };\n\tvar target_handler = create_event(event_name, dom, handler, options);\n\n\tif (\n\t\tdom === document.body ||\n\t\t// @ts-ignore\n\t\tdom === window ||\n\t\t// @ts-ignore\n\t\tdom === document ||\n\t\t// Firefox has quirky behavior, it can happen that we still get \"canplay\" events when the element is already removed\n\t\tdom instanceof HTMLMediaElement\n\t) {\n\t\tteardown(() => {\n\t\t\tdom.removeEventListener(event_name, target_handler, options);\n\t\t});\n\t}\n}\n\n/**\n * @param {string} event_name\n * @param {Element} element\n * @param {EventListener} [handler]\n * @returns {void}\n */\nexport function delegated(event_name, element, handler) {\n\t// @ts-expect-error\n\t(element[event_symbol] ??= {})[event_name] = handler;\n}\n\n/**\n * @param {Array} events\n * @returns {void}\n */\nexport function delegate(events) {\n\tfor (var i = 0; i < events.length; i++) {\n\t\tall_registered_events.add(events[i]);\n\t}\n\n\tfor (var fn of root_event_handles) {\n\t\tfn(events);\n\t}\n}\n\n// used to store the reference to the currently propagated event\n// to prevent garbage collection between microtasks in Firefox\n// If the event object is GCed too early, the expando __root property\n// set on the event object is lost, causing the event delegation\n// to process the event twice\nlet last_propagated_event = null;\n\n/**\n * @this {EventTarget}\n * @param {Event} event\n * @returns {void}\n */\nexport function handle_event_propagation(event) {\n\tvar handler_element = this;\n\tvar owner_document = /** @type {Node} */ (handler_element).ownerDocument;\n\tvar event_name = event.type;\n\tvar path = event.composedPath?.() || [];\n\tvar current_target = /** @type {null | Element} */ (path[0] || event.target);\n\n\tlast_propagated_event = event;\n\n\t// composedPath contains list of nodes the event has propagated through.\n\t// We check `event_symbol` to skip all nodes below it in case this is a\n\t// parent of the `event_symbol` node, which indicates that there's nested\n\t// mounted apps. In this case we don't want to trigger events multiple times.\n\tvar path_idx = 0;\n\n\t// the `last_propagated_event === event` check is redundant, but\n\t// without it the variable will be DCE'd and things will\n\t// fail mysteriously in Firefox\n\t// @ts-expect-error is added below\n\tvar handled_at = last_propagated_event === event && event[event_symbol];\n\n\tif (handled_at) {\n\t\tvar at_idx = path.indexOf(handled_at);\n\t\tif (\n\t\t\tat_idx !== -1 &&\n\t\t\t(handler_element === document || handler_element === /** @type {any} */ (window))\n\t\t) {\n\t\t\t// This is the fallback document listener or a window listener, but the event was already handled\n\t\t\t// -> ignore, but set handle_at to document/window so that we're resetting the event\n\t\t\t// chain in case someone manually dispatches the same event object again.\n\t\t\t// @ts-expect-error\n\t\t\tevent[event_symbol] = handler_element;\n\t\t\treturn;\n\t\t}\n\n\t\t// We're deliberately not skipping if the index is higher, because\n\t\t// someone could create an event programmatically and emit it multiple times,\n\t\t// in which case we want to handle the whole propagation chain properly each time.\n\t\t// (this will only be a false negative if the event is dispatched multiple times and\n\t\t// the fallback document listener isn't reached in between, but that's super rare)\n\t\tvar handler_idx = path.indexOf(handler_element);\n\t\tif (handler_idx === -1) {\n\t\t\t// handle_idx can theoretically be -1 (happened in some JSDOM testing scenarios with an event listener on the window object)\n\t\t\t// so guard against that, too, and assume that everything was handled at this point.\n\t\t\treturn;\n\t\t}\n\n\t\tif (at_idx <= handler_idx) {\n\t\t\tpath_idx = at_idx;\n\t\t}\n\t}\n\n\tcurrent_target = /** @type {Element} */ (path[path_idx] || event.target);\n\t// there can only be one delegated event per element, and we either already handled the current target,\n\t// or this is the very first target in the chain which has a non-delegated listener, in which case it's safe\n\t// to handle a possible delegated event on it later (through the root delegation listener for example).\n\tif (current_target === handler_element) return;\n\n\t// Proxy currentTarget to correct target\n\tdefine_property(event, 'currentTarget', {\n\t\tconfigurable: true,\n\t\tget() {\n\t\t\treturn current_target || owner_document;\n\t\t}\n\t});\n\n\t// This started because of Chromium issue https://chromestatus.com/feature/5128696823545856,\n\t// where removal or moving of of the DOM can cause sync `blur` events to fire, which can cause logic\n\t// to run inside the current `active_reaction`, which isn't what we want at all. However, on reflection,\n\t// it's probably best that all event handled by Svelte have this behaviour, as we don't really want\n\t// an event handler to run in the context of another reaction or effect.\n\tvar previous_reaction = active_reaction;\n\tvar previous_effect = active_effect;\n\tset_active_reaction(null);\n\tset_active_effect(null);\n\n\ttry {\n\t\t/**\n\t\t * @type {unknown}\n\t\t */\n\t\tvar throw_error;\n\t\t/**\n\t\t * @type {unknown[]}\n\t\t */\n\t\tvar other_errors = [];\n\n\t\twhile (current_target !== null) {\n\t\t\t/** @type {null | Element} */\n\t\t\tvar parent_element =\n\t\t\t\tcurrent_target.assignedSlot ||\n\t\t\t\tcurrent_target.parentNode ||\n\t\t\t\t/** @type {any} */ (current_target).host ||\n\t\t\t\tnull;\n\n\t\t\ttry {\n\t\t\t\t// @ts-expect-error\n\t\t\t\tvar delegated = current_target[event_symbol]?.[event_name];\n\n\t\t\t\tif (\n\t\t\t\t\tdelegated != null &&\n\t\t\t\t\t(!(/** @type {any} */ (current_target).disabled) ||\n\t\t\t\t\t\t// DOM could've been updated already by the time this is reached, so we check this as well\n\t\t\t\t\t\t// -> the target could not have been disabled because it emits the event in the first place\n\t\t\t\t\t\tevent.target === current_target)\n\t\t\t\t) {\n\t\t\t\t\tdelegated.call(current_target, event);\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tif (throw_error) {\n\t\t\t\t\tother_errors.push(error);\n\t\t\t\t} else {\n\t\t\t\t\tthrow_error = error;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (event.cancelBubble || parent_element === handler_element || parent_element === null) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcurrent_target = parent_element;\n\t\t}\n\n\t\tif (throw_error) {\n\t\t\tfor (let error of other_errors) {\n\t\t\t\t// Throw the rest of the errors, one-by-one on a microtask\n\t\t\t\tqueueMicrotask(() => {\n\t\t\t\t\tthrow error;\n\t\t\t\t});\n\t\t\t}\n\t\t\tthrow throw_error;\n\t\t}\n\t} finally {\n\t\t// @ts-expect-error is used above\n\t\tevent[event_symbol] = handler_element;\n\t\t// @ts-ignore remove proxy on currentTarget\n\t\tdelete event.currentTarget;\n\t\tset_active_reaction(previous_reaction);\n\t\tset_active_effect(previous_effect);\n\t}\n}\n\n/**\n * In dev, warn if an event handler is not a function, as it means the\n * user probably called the handler or forgot to add a `() =>`\n * @param {() => (event: Event, ...args: any) => void} thunk\n * @param {EventTarget} element\n * @param {[Event, ...any]} args\n * @param {any} component\n * @param {[number, number]} [loc]\n * @param {boolean} [remove_parens]\n */\nexport function apply(\n\tthunk,\n\telement,\n\targs,\n\tcomponent,\n\tloc,\n\thas_side_effects = false,\n\tremove_parens = false\n) {\n\tlet handler;\n\tlet error;\n\n\ttry {\n\t\thandler = thunk();\n\t} catch (e) {\n\t\terror = e;\n\t}\n\n\tif (typeof handler !== 'function' && (has_side_effects || handler != null || error)) {\n\t\tconst filename = component?.[FILENAME];\n\t\tconst location = loc ? ` at ${filename}:${loc[0]}:${loc[1]}` : ` in ${filename}`;\n\t\tconst phase = args[0]?.eventPhase < Event.BUBBLING_PHASE ? 'capture' : '';\n\t\tconst event_name = args[0]?.type + phase;\n\t\tconst description = `\\`${event_name}\\` handler${location}`;\n\t\tconst suggestion = remove_parens ? 'remove the trailing `()`' : 'add a leading `() =>`';\n\n\t\tw.event_handler_invalid(description, suggestion);\n\n\t\tif (error) {\n\t\t\tthrow error;\n\t\t}\n\t}\n\thandler?.apply(element, args);\n}\n","import { create_element } from './operations.js';\n\nconst policy =\n\t// We gotta write it like this because after downleveling the pure comment may end up in the wrong location\n\tglobalThis?.window?.trustedTypes &&\n\t/* @__PURE__ */ globalThis.window.trustedTypes.createPolicy('svelte-trusted-html', {\n\t\t/** @param {string} html */\n\t\tcreateHTML: (html) => {\n\t\t\treturn html;\n\t\t}\n\t});\n\n/** @param {string} html */\nexport function create_trusted_html(html) {\n\treturn /** @type {string} */ (policy?.createHTML(html) ?? html);\n}\n\n/**\n * @param {string} html\n */\nexport function create_fragment_from_html(html) {\n\tvar elem = create_element('template');\n\telem.innerHTML = create_trusted_html(html.replaceAll('', '')); // XHTML compliance\n\treturn elem.content;\n}\n","/** @import { Effect, EffectNodes, TemplateNode } from '#client' */\n/** @import { TemplateStructure } from './types' */\nimport { hydrate_next, hydrate_node, hydrating, set_hydrate_node } from './hydration.js';\nimport {\n\tcreate_text,\n\tget_first_child,\n\tget_next_sibling,\n\tis_firefox,\n\tcreate_element,\n\tcreate_fragment,\n\tcreate_comment,\n\tset_attribute,\n\tmerge_text_nodes\n} from './operations.js';\nimport { create_fragment_from_html } from './reconciler.js';\nimport { active_effect } from '../runtime.js';\nimport {\n\tNAMESPACE_MATHML,\n\tNAMESPACE_SVG,\n\tTEMPLATE_FRAGMENT,\n\tTEMPLATE_USE_IMPORT_NODE,\n\tTEMPLATE_USE_MATHML,\n\tTEMPLATE_USE_SVG\n} from '../../../constants.js';\nimport {\n\tCOMMENT_NODE,\n\tDOCUMENT_FRAGMENT_NODE,\n\tIS_XHTML,\n\tREACTION_RAN,\n\tTEXT_NODE\n} from '#client/constants';\n\nconst TEMPLATE_TAG = IS_XHTML ? 'template' : 'TEMPLATE';\nconst SCRIPT_TAG = IS_XHTML ? 'script' : 'SCRIPT';\n\n/**\n * @param {TemplateNode} start\n * @param {TemplateNode | null} end\n */\nexport function assign_nodes(start, end) {\n\tvar effect = /** @type {Effect} */ (active_effect);\n\tif (effect.nodes === null) {\n\t\teffect.nodes = { start, end, a: null, t: null };\n\t}\n}\n\n/**\n * @param {string} content\n * @param {number} flags\n * @returns {() => Node | Node[]}\n */\n/*#__NO_SIDE_EFFECTS__*/\nexport function from_html(content, flags) {\n\tvar is_fragment = (flags & TEMPLATE_FRAGMENT) !== 0;\n\tvar use_import_node = (flags & TEMPLATE_USE_IMPORT_NODE) !== 0;\n\n\t/** @type {Node} */\n\tvar node;\n\n\t/**\n\t * Whether or not the first item is a text/element node. If not, we need to\n\t * create an additional comment node to act as `effect.nodes.start`\n\t */\n\tvar has_start = !content.startsWith('');\n\n\treturn () => {\n\t\tif (hydrating) {\n\t\t\tassign_nodes(hydrate_node, null);\n\t\t\treturn hydrate_node;\n\t\t}\n\n\t\tif (node === undefined) {\n\t\t\tnode = create_fragment_from_html(has_start ? content : '' + content);\n\t\t\tif (!is_fragment) node = /** @type {TemplateNode} */ (get_first_child(node));\n\t\t}\n\n\t\tvar clone = /** @type {TemplateNode} */ (\n\t\t\tuse_import_node || is_firefox ? document.importNode(node, true) : node.cloneNode(true)\n\t\t);\n\n\t\tif (is_fragment) {\n\t\t\tvar start = /** @type {TemplateNode} */ (get_first_child(clone));\n\t\t\tvar end = /** @type {TemplateNode} */ (clone.lastChild);\n\n\t\t\tassign_nodes(start, end);\n\t\t} else {\n\t\t\tassign_nodes(clone, clone);\n\t\t}\n\n\t\treturn clone;\n\t};\n}\n\n/**\n * @param {string} content\n * @param {number} flags\n * @param {'svg' | 'math'} ns\n * @returns {() => Node | Node[]}\n */\n/*#__NO_SIDE_EFFECTS__*/\nfunction from_namespace(content, flags, ns = 'svg') {\n\t/**\n\t * Whether or not the first item is a text/element node. If not, we need to\n\t * create an additional comment node to act as `effect.nodes.start`\n\t */\n\tvar has_start = !content.startsWith('');\n\n\tvar is_fragment = (flags & TEMPLATE_FRAGMENT) !== 0;\n\tvar wrapped = `<${ns}>${has_start ? content : '' + content}`;\n\n\t/** @type {Element | DocumentFragment} */\n\tvar node;\n\n\treturn () => {\n\t\tif (hydrating) {\n\t\t\tassign_nodes(hydrate_node, null);\n\t\t\treturn hydrate_node;\n\t\t}\n\n\t\tif (!node) {\n\t\t\tvar fragment = /** @type {DocumentFragment} */ (create_fragment_from_html(wrapped));\n\t\t\tvar root = /** @type {Element} */ (get_first_child(fragment));\n\n\t\t\tif (is_fragment) {\n\t\t\t\tnode = document.createDocumentFragment();\n\t\t\t\twhile (get_first_child(root)) {\n\t\t\t\t\tnode.appendChild(/** @type {TemplateNode} */ (get_first_child(root)));\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tnode = /** @type {Element} */ (get_first_child(root));\n\t\t\t}\n\t\t}\n\n\t\tvar clone = /** @type {TemplateNode} */ (node.cloneNode(true));\n\n\t\tif (is_fragment) {\n\t\t\tvar start = /** @type {TemplateNode} */ (get_first_child(clone));\n\t\t\tvar end = /** @type {TemplateNode} */ (clone.lastChild);\n\n\t\t\tassign_nodes(start, end);\n\t\t} else {\n\t\t\tassign_nodes(clone, clone);\n\t\t}\n\n\t\treturn clone;\n\t};\n}\n\n/**\n * @param {string} content\n * @param {number} flags\n */\n/*#__NO_SIDE_EFFECTS__*/\nexport function from_svg(content, flags) {\n\treturn from_namespace(content, flags, 'svg');\n}\n\n/**\n * @param {string} content\n * @param {number} flags\n */\n/*#__NO_SIDE_EFFECTS__*/\nexport function from_mathml(content, flags) {\n\treturn from_namespace(content, flags, 'math');\n}\n\n/**\n * @param {TemplateStructure[]} structure\n * @param {typeof NAMESPACE_SVG | typeof NAMESPACE_MATHML | undefined} [ns]\n */\nfunction fragment_from_tree(structure, ns) {\n\tvar fragment = create_fragment();\n\n\tfor (var item of structure) {\n\t\tif (typeof item === 'string') {\n\t\t\tfragment.append(create_text(item));\n\t\t\tcontinue;\n\t\t}\n\n\t\t// if `preserveComments === true`, comments are represented as `['// ']`\n\t\tif (item === undefined || item[0][0] === '/') {\n\t\t\tfragment.append(create_comment(item ? item[0].slice(3) : ''));\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst [name, attributes, ...children] = item;\n\n\t\tconst namespace = name === 'svg' ? NAMESPACE_SVG : name === 'math' ? NAMESPACE_MATHML : ns;\n\n\t\tvar element = create_element(name, namespace, attributes?.is);\n\n\t\tfor (var key in attributes) {\n\t\t\tset_attribute(element, key, attributes[key]);\n\t\t}\n\n\t\tif (children.length > 0) {\n\t\t\tvar target =\n\t\t\t\telement.nodeName === TEMPLATE_TAG\n\t\t\t\t\t? /** @type {HTMLTemplateElement} */ (element).content\n\t\t\t\t\t: element;\n\n\t\t\ttarget.append(\n\t\t\t\tfragment_from_tree(children, element.nodeName === 'foreignObject' ? undefined : namespace)\n\t\t\t);\n\t\t}\n\n\t\tfragment.append(element);\n\t}\n\n\treturn fragment;\n}\n\n/**\n * @param {TemplateStructure[]} structure\n * @param {number} flags\n * @returns {() => Node | Node[]}\n */\n/*#__NO_SIDE_EFFECTS__*/\nexport function from_tree(structure, flags) {\n\tvar is_fragment = (flags & TEMPLATE_FRAGMENT) !== 0;\n\tvar use_import_node = (flags & TEMPLATE_USE_IMPORT_NODE) !== 0;\n\n\t/** @type {Node} */\n\tvar node;\n\n\treturn () => {\n\t\tif (hydrating) {\n\t\t\tassign_nodes(hydrate_node, null);\n\t\t\treturn hydrate_node;\n\t\t}\n\n\t\tif (node === undefined) {\n\t\t\tconst ns =\n\t\t\t\t(flags & TEMPLATE_USE_SVG) !== 0\n\t\t\t\t\t? NAMESPACE_SVG\n\t\t\t\t\t: (flags & TEMPLATE_USE_MATHML) !== 0\n\t\t\t\t\t\t? NAMESPACE_MATHML\n\t\t\t\t\t\t: undefined;\n\n\t\t\tnode = fragment_from_tree(structure, ns);\n\t\t\tif (!is_fragment) node = /** @type {TemplateNode} */ (get_first_child(node));\n\t\t}\n\n\t\tvar clone = /** @type {TemplateNode} */ (\n\t\t\tuse_import_node || is_firefox ? document.importNode(node, true) : node.cloneNode(true)\n\t\t);\n\n\t\tif (is_fragment) {\n\t\t\tvar start = /** @type {TemplateNode} */ (get_first_child(clone));\n\t\t\tvar end = /** @type {TemplateNode} */ (clone.lastChild);\n\n\t\t\tassign_nodes(start, end);\n\t\t} else {\n\t\t\tassign_nodes(clone, clone);\n\t\t}\n\n\t\treturn clone;\n\t};\n}\n\n/**\n * @param {() => Element | DocumentFragment} fn\n */\nexport function with_script(fn) {\n\treturn () => run_scripts(fn());\n}\n\n/**\n * Creating a document fragment from HTML that contains script tags will not execute\n * the scripts. We need to replace the script tags with new ones so that they are executed.\n * @param {Element | DocumentFragment} node\n * @returns {Node | Node[]}\n */\nfunction run_scripts(node) {\n\t// scripts were SSR'd, in which case they will run\n\tif (hydrating) return node;\n\n\tconst is_fragment = node.nodeType === DOCUMENT_FRAGMENT_NODE;\n\tconst scripts =\n\t\t/** @type {HTMLElement} */ (node).nodeName === SCRIPT_TAG\n\t\t\t? [/** @type {HTMLScriptElement} */ (node)]\n\t\t\t: node.querySelectorAll('script');\n\n\tconst effect = /** @type {Effect & { nodes: EffectNodes }} */ (active_effect);\n\n\tfor (const script of scripts) {\n\t\tconst clone = create_element('script');\n\t\tfor (var attribute of script.attributes) {\n\t\t\tclone.setAttribute(attribute.name, attribute.value);\n\t\t}\n\n\t\tclone.textContent = script.textContent;\n\n\t\t// The script has changed - if it's at the edges, the effect now points at dead nodes\n\t\tif (is_fragment ? node.firstChild === script : node === script) {\n\t\t\teffect.nodes.start = clone;\n\t\t}\n\t\tif (is_fragment ? node.lastChild === script : node === script) {\n\t\t\teffect.nodes.end = clone;\n\t\t}\n\n\t\tscript.replaceWith(clone);\n\t}\n\treturn node;\n}\n\n/**\n * Don't mark this as side-effect-free, hydration needs to walk all nodes\n * @param {any} value\n */\nexport function text(value = '') {\n\tif (!hydrating) {\n\t\tvar t = create_text(value + '');\n\t\tassign_nodes(t, t);\n\t\treturn t;\n\t}\n\n\tvar node = hydrate_node;\n\n\tif (node.nodeType !== TEXT_NODE) {\n\t\t// if an {expression} is empty during SSR, we need to insert an empty text node\n\t\tnode.before((node = create_text()));\n\t\tset_hydrate_node(node);\n\t} else {\n\t\tmerge_text_nodes(/** @type {Text} */ (node));\n\t}\n\n\tassign_nodes(node, node);\n\treturn node;\n}\n\n/**\n * @returns {TemplateNode | DocumentFragment}\n */\nexport function comment() {\n\t// we're not delegating to `template` here for performance reasons\n\tif (hydrating) {\n\t\tassign_nodes(hydrate_node, null);\n\t\treturn hydrate_node;\n\t}\n\n\tvar frag = document.createDocumentFragment();\n\tvar start = document.createComment('');\n\tvar anchor = create_text();\n\tfrag.append(start, anchor);\n\n\tassign_nodes(start, anchor);\n\n\treturn frag;\n}\n\n/**\n * Assign the created (or in hydration mode, traversed) dom elements to the current block\n * and insert the elements into the dom (in client mode).\n * @param {Text | Comment | Element} anchor\n * @param {DocumentFragment | Element} dom\n */\nexport function append(anchor, dom) {\n\tif (hydrating) {\n\t\tvar effect = /** @type {Effect & { nodes: EffectNodes }} */ (active_effect);\n\n\t\t// When hydrating and outer component and an inner component is async, i.e. blocked on a promise,\n\t\t// then by the time the inner resolves we have already advanced to the end of the hydrated nodes\n\t\t// of the parent component. Check for defined for that reason to avoid rewinding the parent's end marker.\n\t\tif ((effect.f & REACTION_RAN) === 0 || effect.nodes.end === null) {\n\t\t\teffect.nodes.end = hydrate_node;\n\t\t}\n\n\t\thydrate_next();\n\t\treturn;\n\t}\n\n\tif (anchor === null) {\n\t\t// edge case — void `` with content\n\t\treturn;\n\t}\n\n\tanchor.before(/** @type {Node} */ (dom));\n}\n\n/**\n * Create (or hydrate) an unique UID for the component instance.\n */\nexport function props_id() {\n\tif (\n\t\thydrating &&\n\t\thydrate_node &&\n\t\thydrate_node.nodeType === COMMENT_NODE &&\n\t\thydrate_node.textContent?.startsWith(`$`)\n\t) {\n\t\tconst id = hydrate_node.textContent.substring(1);\n\t\thydrate_next();\n\t\treturn id;\n\t}\n\n\t// @ts-expect-error This way we ensure the id is unique even across Svelte runtimes\n\t(window.__svelte ??= {}).uid ??= 1;\n\n\t// @ts-expect-error\n\treturn `c${window.__svelte.uid++}`;\n}\n","const regex_return_characters = /\\r/g;\n\n/**\n * @param {string} str\n * @returns {string}\n */\nexport function hash(str) {\n\tstr = str.replace(regex_return_characters, '');\n\tlet hash = 5381;\n\tlet i = str.length;\n\n\twhile (i--) hash = ((hash << 5) - hash) ^ str.charCodeAt(i);\n\treturn (hash >>> 0).toString(36);\n}\n\nconst VOID_ELEMENT_NAMES = [\n\t'area',\n\t'base',\n\t'br',\n\t'col',\n\t'command',\n\t'embed',\n\t'hr',\n\t'img',\n\t'input',\n\t'keygen',\n\t'link',\n\t'meta',\n\t'param',\n\t'source',\n\t'track',\n\t'wbr'\n];\n\n/**\n * Returns `true` if `name` is of a void element\n * @param {string} name\n */\nexport function is_void(name) {\n\treturn VOID_ELEMENT_NAMES.includes(name) || name.toLowerCase() === '!doctype';\n}\n\nconst RESERVED_WORDS = [\n\t'arguments',\n\t'await',\n\t'break',\n\t'case',\n\t'catch',\n\t'class',\n\t'const',\n\t'continue',\n\t'debugger',\n\t'default',\n\t'delete',\n\t'do',\n\t'else',\n\t'enum',\n\t'eval',\n\t'export',\n\t'extends',\n\t'false',\n\t'finally',\n\t'for',\n\t'function',\n\t'if',\n\t'implements',\n\t'import',\n\t'in',\n\t'instanceof',\n\t'interface',\n\t'let',\n\t'new',\n\t'null',\n\t'package',\n\t'private',\n\t'protected',\n\t'public',\n\t'return',\n\t'static',\n\t'super',\n\t'switch',\n\t'this',\n\t'throw',\n\t'true',\n\t'try',\n\t'typeof',\n\t'var',\n\t'void',\n\t'while',\n\t'with',\n\t'yield'\n];\n\n/**\n * Returns `true` if `word` is a reserved JavaScript keyword\n * @param {string} word\n */\nexport function is_reserved(word) {\n\treturn RESERVED_WORDS.includes(word);\n}\n\n/**\n * @param {string} name\n */\nexport function is_capture_event(name) {\n\treturn name.endsWith('capture') && name !== 'gotpointercapture' && name !== 'lostpointercapture';\n}\n\n/** List of Element events that will be delegated */\nconst DELEGATED_EVENTS = [\n\t'beforeinput',\n\t'click',\n\t'change',\n\t'dblclick',\n\t'contextmenu',\n\t'focusin',\n\t'focusout',\n\t'input',\n\t'keydown',\n\t'keyup',\n\t'mousedown',\n\t'mousemove',\n\t'mouseout',\n\t'mouseover',\n\t'mouseup',\n\t'pointerdown',\n\t'pointermove',\n\t'pointerout',\n\t'pointerover',\n\t'pointerup',\n\t'touchend',\n\t'touchmove',\n\t'touchstart'\n];\n\n/**\n * Returns `true` if `event_name` is a delegated event\n * @param {string} event_name\n */\nexport function can_delegate_event(event_name) {\n\treturn DELEGATED_EVENTS.includes(event_name);\n}\n\n/**\n * Attributes that are boolean, i.e. they are present or not present.\n */\nconst DOM_BOOLEAN_ATTRIBUTES = [\n\t'allowfullscreen',\n\t'async',\n\t'autofocus',\n\t'autoplay',\n\t'checked',\n\t'controls',\n\t'default',\n\t'disabled',\n\t'formnovalidate',\n\t'indeterminate',\n\t'inert',\n\t'ismap',\n\t'loop',\n\t'multiple',\n\t'muted',\n\t'nomodule',\n\t'novalidate',\n\t'open',\n\t'playsinline',\n\t'readonly',\n\t'required',\n\t'reversed',\n\t'seamless',\n\t'selected',\n\t'webkitdirectory',\n\t'defer',\n\t'disablepictureinpicture',\n\t'disableremoteplayback'\n];\n\n/**\n * Returns `true` if `name` is a boolean attribute\n * @param {string} name\n */\nexport function is_boolean_attribute(name) {\n\treturn DOM_BOOLEAN_ATTRIBUTES.includes(name);\n}\n\n/**\n * @type {Record}\n * List of attribute names that should be aliased to their property names\n * because they behave differently between setting them as an attribute and\n * setting them as a property.\n */\nconst ATTRIBUTE_ALIASES = {\n\t// no `class: 'className'` because we handle that separately\n\tformnovalidate: 'formNoValidate',\n\tismap: 'isMap',\n\tnomodule: 'noModule',\n\tplaysinline: 'playsInline',\n\treadonly: 'readOnly',\n\tdefaultvalue: 'defaultValue',\n\tdefaultchecked: 'defaultChecked',\n\tsrcobject: 'srcObject',\n\tnovalidate: 'noValidate',\n\tallowfullscreen: 'allowFullscreen',\n\tdisablepictureinpicture: 'disablePictureInPicture',\n\tdisableremoteplayback: 'disableRemotePlayback'\n};\n\n/**\n * @param {string} name\n */\nexport function normalize_attribute(name) {\n\tname = name.toLowerCase();\n\treturn ATTRIBUTE_ALIASES[name] ?? name;\n}\n\nconst DOM_PROPERTIES = [\n\t...DOM_BOOLEAN_ATTRIBUTES,\n\t'formNoValidate',\n\t'isMap',\n\t'noModule',\n\t'playsInline',\n\t'readOnly',\n\t'value',\n\t'volume',\n\t'defaultValue',\n\t'defaultChecked',\n\t'srcObject',\n\t'noValidate',\n\t'allowFullscreen',\n\t'disablePictureInPicture',\n\t'disableRemotePlayback'\n];\n\n/**\n * @param {string} name\n */\nexport function is_dom_property(name) {\n\treturn DOM_PROPERTIES.includes(name);\n}\n\nconst NON_STATIC_PROPERTIES = ['autofocus', 'muted', 'defaultValue', 'defaultChecked'];\n\n/**\n * Returns `true` if the given attribute cannot be set through the template\n * string, i.e. needs some kind of JavaScript handling to work.\n * @param {string} name\n */\nexport function cannot_be_set_statically(name) {\n\treturn NON_STATIC_PROPERTIES.includes(name);\n}\n\n/**\n * Subset of delegated events which should be passive by default.\n * These two are already passive via browser defaults on window, document and body.\n * But since\n * - we're delegating them\n * - they happen often\n * - they apply to mobile which is generally less performant\n * we're marking them as passive by default for other elements, too.\n */\nconst PASSIVE_EVENTS = ['touchstart', 'touchmove'];\n\n/**\n * Returns `true` if `name` is a passive event\n * @param {string} name\n */\nexport function is_passive_event(name) {\n\treturn PASSIVE_EVENTS.includes(name);\n}\n\nconst CONTENT_EDITABLE_BINDINGS = ['textContent', 'innerHTML', 'innerText'];\n\n/** @param {string} name */\nexport function is_content_editable_binding(name) {\n\treturn CONTENT_EDITABLE_BINDINGS.includes(name);\n}\n\nconst LOAD_ERROR_ELEMENTS = [\n\t'body',\n\t'embed',\n\t'iframe',\n\t'img',\n\t'link',\n\t'object',\n\t'script',\n\t'style',\n\t'track'\n];\n\n/**\n * Returns `true` if the element emits `load` and `error` events\n * @param {string} name\n */\nexport function is_load_error_element(name) {\n\treturn LOAD_ERROR_ELEMENTS.includes(name);\n}\n\nconst SVG_ELEMENTS = [\n\t'altGlyph',\n\t'altGlyphDef',\n\t'altGlyphItem',\n\t'animate',\n\t'animateColor',\n\t'animateMotion',\n\t'animateTransform',\n\t'circle',\n\t'clipPath',\n\t'color-profile',\n\t'cursor',\n\t'defs',\n\t'desc',\n\t'discard',\n\t'ellipse',\n\t'feBlend',\n\t'feColorMatrix',\n\t'feComponentTransfer',\n\t'feComposite',\n\t'feConvolveMatrix',\n\t'feDiffuseLighting',\n\t'feDisplacementMap',\n\t'feDistantLight',\n\t'feDropShadow',\n\t'feFlood',\n\t'feFuncA',\n\t'feFuncB',\n\t'feFuncG',\n\t'feFuncR',\n\t'feGaussianBlur',\n\t'feImage',\n\t'feMerge',\n\t'feMergeNode',\n\t'feMorphology',\n\t'feOffset',\n\t'fePointLight',\n\t'feSpecularLighting',\n\t'feSpotLight',\n\t'feTile',\n\t'feTurbulence',\n\t'filter',\n\t'font',\n\t'font-face',\n\t'font-face-format',\n\t'font-face-name',\n\t'font-face-src',\n\t'font-face-uri',\n\t'foreignObject',\n\t'g',\n\t'glyph',\n\t'glyphRef',\n\t'hatch',\n\t'hatchpath',\n\t'hkern',\n\t'image',\n\t'line',\n\t'linearGradient',\n\t'marker',\n\t'mask',\n\t'mesh',\n\t'meshgradient',\n\t'meshpatch',\n\t'meshrow',\n\t'metadata',\n\t'missing-glyph',\n\t'mpath',\n\t'path',\n\t'pattern',\n\t'polygon',\n\t'polyline',\n\t'radialGradient',\n\t'rect',\n\t'set',\n\t'solidcolor',\n\t'stop',\n\t'svg',\n\t'switch',\n\t'symbol',\n\t'text',\n\t'textPath',\n\t'tref',\n\t'tspan',\n\t'unknown',\n\t'use',\n\t'view',\n\t'vkern'\n];\n\n/** @param {string} name */\nexport function is_svg(name) {\n\treturn SVG_ELEMENTS.includes(name);\n}\n\nconst MATHML_ELEMENTS = [\n\t'annotation',\n\t'annotation-xml',\n\t'maction',\n\t'math',\n\t'merror',\n\t'mfrac',\n\t'mi',\n\t'mmultiscripts',\n\t'mn',\n\t'mo',\n\t'mover',\n\t'mpadded',\n\t'mphantom',\n\t'mprescripts',\n\t'mroot',\n\t'mrow',\n\t'ms',\n\t'mspace',\n\t'msqrt',\n\t'mstyle',\n\t'msub',\n\t'msubsup',\n\t'msup',\n\t'mtable',\n\t'mtd',\n\t'mtext',\n\t'mtr',\n\t'munder',\n\t'munderover',\n\t'semantics'\n];\n\n/** @param {string} name */\nexport function is_mathml(name) {\n\treturn MATHML_ELEMENTS.includes(name);\n}\n\nconst STATE_CREATION_RUNES = /** @type {const} */ ([\n\t'$state',\n\t'$state.raw',\n\t'$derived',\n\t'$derived.by'\n]);\n\nconst RUNES = /** @type {const} */ ([\n\t...STATE_CREATION_RUNES,\n\t'$state.eager',\n\t'$state.snapshot',\n\t'$props',\n\t'$props.id',\n\t'$bindable',\n\t'$effect',\n\t'$effect.pre',\n\t'$effect.tracking',\n\t'$effect.root',\n\t'$effect.pending',\n\t'$inspect',\n\t'$inspect().with',\n\t'$inspect.trace',\n\t'$host'\n]);\n\n/** @typedef {typeof RUNES[number]} RuneName */\n\n/**\n * @param {string} name\n * @returns {name is RuneName}\n */\nexport function is_rune(name) {\n\treturn RUNES.includes(/** @type {RuneName} */ (name));\n}\n\n/** @typedef {typeof STATE_CREATION_RUNES[number]} StateCreationRuneName */\n\n/**\n * @param {string} name\n * @returns {name is StateCreationRuneName}\n */\nexport function is_state_creation_rune(name) {\n\treturn STATE_CREATION_RUNES.includes(/** @type {StateCreationRuneName} */ (name));\n}\n\n/** List of elements that require raw contents and should not have SSR comments put in them */\nconst RAW_TEXT_ELEMENTS = /** @type {const} */ (['textarea', 'script', 'style', 'title']);\n\n/** @param {string} name */\nexport function is_raw_text_element(name) {\n\treturn RAW_TEXT_ELEMENTS.includes(/** @type {typeof RAW_TEXT_ELEMENTS[number]} */ (name));\n}\n\n// Matches valid HTML/SVG/MathML element names and custom element names.\n// https://html.spec.whatwg.org/multipage/custom-elements.html#valid-custom-element-name\n//\n// Standard elements: ASCII alpha start, followed by ASCII alphanumerics.\n// Custom elements: ASCII alpha start, followed by any mix of PCENChar (which\n// includes ASCII alphanumerics, `-`, `.`, `_`, and specified Unicode ranges),\n// with at least one hyphen required somewhere after the first character.\n//\n// Rejects strings containing whitespace, quotes, angle brackets, slashes, equals,\n// or other characters that could break out of a tag-name token and enable markup injection.\nexport const REGEX_VALID_TAG_NAME =\n\t/^[a-zA-Z][a-zA-Z0-9]*(-[a-zA-Z0-9.\\-_\\u00B7\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u203F-\\u2040\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\u{10000}-\\u{EFFFF}]+)*$/u;\n\n/**\n * Prevent devtools trying to make `location` a clickable link by inserting a zero-width space\n * @template {string | undefined} T\n * @param {T} location\n * @returns {T};\n */\nexport function sanitize_location(location) {\n\treturn /** @type {T} */ (location?.replace(/\\//g, '/\\u200b'));\n}\n","/** @import { ComponentContext, Effect, EffectNodes, TemplateNode } from '#client' */\n/** @import { Component, ComponentType, SvelteComponent, MountOptions } from '../../index.js' */\nimport { DEV } from 'esm-env';\nimport {\n\tclear_text_content,\n\tcreate_text,\n\tget_first_child,\n\tget_next_sibling,\n\tinit_operations\n} from './dom/operations.js';\nimport { HYDRATION_END, HYDRATION_ERROR, HYDRATION_START } from '../../constants.js';\nimport { active_effect } from './runtime.js';\nimport { push, pop, component_context } from './context.js';\nimport { component_root } from './reactivity/effects.js';\nimport { hydrate_node, hydrating, set_hydrate_node, set_hydrating } from './dom/hydration.js';\nimport { array_from } from '../shared/utils.js';\nimport {\n\tall_registered_events,\n\thandle_event_propagation,\n\troot_event_handles\n} from './dom/elements/events.js';\nimport * as w from './warnings.js';\nimport * as e from './errors.js';\nimport { assign_nodes } from './dom/template.js';\nimport { is_passive_event } from '../../utils.js';\nimport { COMMENT_NODE, STATE_SYMBOL } from './constants.js';\nimport { boundary } from './dom/blocks/boundary.js';\n\n/**\n * This is normally true — block effects should run their intro transitions —\n * but is false during hydration (unless `options.intro` is `true`) and\n * when creating the children of a `` that just changed tag\n */\nexport let should_intro = true;\n\n/** @param {boolean} value */\nexport function set_should_intro(value) {\n\tshould_intro = value;\n}\n\n/**\n * @param {Element} text\n * @param {string} value\n * @returns {void}\n */\nexport function set_text(text, value) {\n\t// For objects, we apply string coercion (which might make things like $state array references in the template reactive) before diffing\n\tvar str = value == null ? '' : typeof value === 'object' ? `${value}` : value;\n\t// @ts-expect-error\n\tif (str !== (text.__t ??= text.nodeValue)) {\n\t\t// @ts-expect-error\n\t\ttext.__t = str;\n\t\ttext.nodeValue = `${str}`;\n\t}\n}\n\n/**\n * Mounts a component to the given target and returns the exports and potentially the props (if compiled with `accessors: true`) of the component.\n * Transitions will play during the initial render unless the `intro` option is set to `false`.\n *\n * @template {Record} Props\n * @template {Record} Exports\n * @param {ComponentType> | Component} component\n * @param {MountOptions} options\n * @returns {Exports}\n */\nexport function mount(component, options) {\n\treturn _mount(component, options);\n}\n\n/**\n * Hydrates a component on the given target and returns the exports and potentially the props (if compiled with `accessors: true`) of the component\n *\n * @template {Record} Props\n * @template {Record} Exports\n * @param {ComponentType> | Component} component\n * @param {{} extends Props ? {\n * \t\ttarget: Document | Element | ShadowRoot;\n * \t\tprops?: Props;\n * \t\tevents?: Record any>;\n * \tcontext?: Map;\n * \t\tintro?: boolean;\n * \t\trecover?: boolean;\n *\t\ttransformError?: (error: unknown) => unknown;\n * \t} : {\n * \t\ttarget: Document | Element | ShadowRoot;\n * \t\tprops: Props;\n * \t\tevents?: Record any>;\n * \tcontext?: Map;\n * \t\tintro?: boolean;\n * \t\trecover?: boolean;\n *\t\ttransformError?: (error: unknown) => unknown;\n * \t}} options\n * @returns {Exports}\n */\nexport function hydrate(component, options) {\n\tinit_operations();\n\toptions.intro = options.intro ?? false;\n\tconst target = options.target;\n\tconst was_hydrating = hydrating;\n\tconst previous_hydrate_node = hydrate_node;\n\n\ttry {\n\t\tvar anchor = get_first_child(target);\n\n\t\twhile (\n\t\t\tanchor &&\n\t\t\t(anchor.nodeType !== COMMENT_NODE || /** @type {Comment} */ (anchor).data !== HYDRATION_START)\n\t\t) {\n\t\t\tanchor = get_next_sibling(anchor);\n\t\t}\n\n\t\tif (!anchor) {\n\t\t\tthrow HYDRATION_ERROR;\n\t\t}\n\n\t\tset_hydrating(true);\n\t\tset_hydrate_node(/** @type {Comment} */ (anchor));\n\n\t\tconst instance = _mount(component, { ...options, anchor });\n\n\t\tset_hydrating(false);\n\n\t\treturn /** @type {Exports} */ (instance);\n\t} catch (error) {\n\t\t// re-throw Svelte errors - they are certainly not related to hydration\n\t\tif (\n\t\t\terror instanceof Error &&\n\t\t\terror.message.split('\\n').some((line) => line.startsWith('https://svelte.dev/e/'))\n\t\t) {\n\t\t\tthrow error;\n\t\t}\n\t\tif (error !== HYDRATION_ERROR) {\n\t\t\t// eslint-disable-next-line no-console\n\t\t\tconsole.warn('Failed to hydrate: ', error);\n\t\t}\n\n\t\tif (options.recover === false) {\n\t\t\te.hydration_failed();\n\t\t}\n\n\t\t// If an error occurred above, the operations might not yet have been initialised.\n\t\tinit_operations();\n\t\tclear_text_content(target);\n\n\t\tset_hydrating(false);\n\t\treturn mount(component, options);\n\t} finally {\n\t\tset_hydrating(was_hydrating);\n\t\tset_hydrate_node(previous_hydrate_node);\n\t}\n}\n\n/** @type {Map>} */\nconst listeners = new Map();\n\n/**\n * @template {Record} Exports\n * @param {ComponentType> | Component} Component\n * @param {MountOptions} options\n * @returns {Exports}\n */\nfunction _mount(\n\tComponent,\n\t{ target, anchor, props = {}, events, context, intro = true, transformError }\n) {\n\tinit_operations();\n\n\t/** @type {Exports} */\n\t// @ts-expect-error will be defined because the render effect runs synchronously\n\tvar component = undefined;\n\n\tvar unmount = component_root(() => {\n\t\tvar anchor_node = anchor ?? target.appendChild(create_text());\n\n\t\tboundary(\n\t\t\t/** @type {TemplateNode} */ (anchor_node),\n\t\t\t{\n\t\t\t\tpending: () => {}\n\t\t\t},\n\t\t\t(anchor_node) => {\n\t\t\t\tpush({});\n\t\t\t\tvar ctx = /** @type {ComponentContext} */ (component_context);\n\t\t\t\tif (context) ctx.c = context;\n\n\t\t\t\tif (events) {\n\t\t\t\t\t// We can't spread the object or else we'd lose the state proxy stuff, if it is one\n\t\t\t\t\t/** @type {any} */ (props).$$events = events;\n\t\t\t\t}\n\n\t\t\t\tif (hydrating) {\n\t\t\t\t\tassign_nodes(/** @type {TemplateNode} */ (anchor_node), null);\n\t\t\t\t}\n\n\t\t\t\tshould_intro = intro;\n\t\t\t\t// @ts-expect-error the public typings are not what the actual function looks like\n\t\t\t\tcomponent = Component(anchor_node, props) || {};\n\t\t\t\tshould_intro = true;\n\n\t\t\t\tif (hydrating) {\n\t\t\t\t\t/** @type {Effect & { nodes: EffectNodes }} */ (active_effect).nodes.end = hydrate_node;\n\n\t\t\t\t\tif (\n\t\t\t\t\t\thydrate_node === null ||\n\t\t\t\t\t\thydrate_node.nodeType !== COMMENT_NODE ||\n\t\t\t\t\t\t/** @type {Comment} */ (hydrate_node).data !== HYDRATION_END\n\t\t\t\t\t) {\n\t\t\t\t\t\tw.hydration_mismatch();\n\t\t\t\t\t\tthrow HYDRATION_ERROR;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tpop();\n\t\t\t},\n\t\t\ttransformError\n\t\t);\n\n\t\t// Setup event delegation _after_ component is mounted - if an error would happen during mount, it would otherwise not be cleaned up\n\t\t/** @type {Set} */\n\t\tvar registered_events = new Set();\n\n\t\t/** @param {Array} events */\n\t\tvar event_handle = (events) => {\n\t\t\tfor (var i = 0; i < events.length; i++) {\n\t\t\t\tvar event_name = events[i];\n\n\t\t\t\tif (registered_events.has(event_name)) continue;\n\t\t\t\tregistered_events.add(event_name);\n\n\t\t\t\tvar passive = is_passive_event(event_name);\n\n\t\t\t\t// Add the event listener to both the container and the document.\n\t\t\t\t// The container listener ensures we catch events from within in case\n\t\t\t\t// the outer content stops propagation of the event.\n\t\t\t\t//\n\t\t\t\t// The document listener ensures we catch events that originate from elements that were\n\t\t\t\t// manually moved outside of the container (e.g. via manual portals).\n\t\t\t\tfor (const node of [target, document]) {\n\t\t\t\t\tvar counts = listeners.get(node);\n\n\t\t\t\t\tif (counts === undefined) {\n\t\t\t\t\t\tcounts = new Map();\n\t\t\t\t\t\tlisteners.set(node, counts);\n\t\t\t\t\t}\n\n\t\t\t\t\tvar count = counts.get(event_name);\n\n\t\t\t\t\tif (count === undefined) {\n\t\t\t\t\t\tnode.addEventListener(event_name, handle_event_propagation, { passive });\n\t\t\t\t\t\tcounts.set(event_name, 1);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcounts.set(event_name, count + 1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\tevent_handle(array_from(all_registered_events));\n\t\troot_event_handles.add(event_handle);\n\n\t\treturn () => {\n\t\t\tfor (var event_name of registered_events) {\n\t\t\t\tfor (const node of [target, document]) {\n\t\t\t\t\tvar counts = /** @type {Map} */ (listeners.get(node));\n\t\t\t\t\tvar count = /** @type {number} */ (counts.get(event_name));\n\n\t\t\t\t\tif (--count == 0) {\n\t\t\t\t\t\tnode.removeEventListener(event_name, handle_event_propagation);\n\t\t\t\t\t\tcounts.delete(event_name);\n\n\t\t\t\t\t\tif (counts.size === 0) {\n\t\t\t\t\t\t\tlisteners.delete(node);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcounts.set(event_name, count);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\troot_event_handles.delete(event_handle);\n\n\t\t\tif (anchor_node !== anchor) {\n\t\t\t\tanchor_node.parentNode?.removeChild(anchor_node);\n\t\t\t}\n\t\t};\n\t});\n\n\tmounted_components.set(component, unmount);\n\treturn component;\n}\n\n/**\n * References of the components that were mounted or hydrated.\n * Uses a `WeakMap` to avoid memory leaks.\n */\nlet mounted_components = new WeakMap();\n\n/**\n * Unmounts a component that was previously mounted using `mount` or `hydrate`.\n *\n * Since 5.13.0, if `options.outro` is `true`, [transitions](https://svelte.dev/docs/svelte/transition) will play before the component is removed from the DOM.\n *\n * Returns a `Promise` that resolves after transitions have completed if `options.outro` is true, or immediately otherwise (prior to 5.13.0, returns `void`).\n *\n * ```js\n * import { mount, unmount } from 'svelte';\n * import App from './App.svelte';\n *\n * const app = mount(App, { target: document.body });\n *\n * // later...\n * unmount(app, { outro: true });\n * ```\n * @param {Record} component\n * @param {{ outro?: boolean }} [options]\n * @returns {Promise}\n */\nexport function unmount(component, options) {\n\tconst fn = mounted_components.get(component);\n\n\tif (fn) {\n\t\tmounted_components.delete(component);\n\t\treturn fn(options);\n\t}\n\n\tif (DEV) {\n\t\tif (STATE_SYMBOL in component) {\n\t\t\tw.state_proxy_unmount();\n\t\t} else {\n\t\t\tw.lifecycle_double_unmount();\n\t\t}\n\t}\n\n\treturn Promise.resolve();\n}\n","/** @import { Effect, TemplateNode } from '#client' */\nimport { Batch, current_batch } from '../../reactivity/batch.js';\nimport {\n\tbranch,\n\tdestroy_effect,\n\tmove_effect,\n\tpause_effect,\n\tresume_effect\n} from '../../reactivity/effects.js';\nimport { HMR_ANCHOR } from '../../constants.js';\nimport { hydrate_node, hydrating } from '../hydration.js';\nimport { create_text, should_defer_append } from '../operations.js';\nimport { DEV } from 'esm-env';\n\n/**\n * @typedef {{ effect: Effect, fragment: DocumentFragment }} Branch\n */\n\n/**\n * @template Key\n */\nexport class BranchManager {\n\t/** @type {TemplateNode} */\n\tanchor;\n\n\t/** @type {Map} */\n\t#batches = new Map();\n\n\t/**\n\t * Map of keys to effects that are currently rendered in the DOM.\n\t * These effects are visible and actively part of the document tree.\n\t * Example:\n\t * ```\n\t * {#if condition}\n\t * \tfoo\n\t * {:else}\n\t * \tbar\n\t * {/if}\n\t * ```\n\t * Can result in the entries `true->Effect` and `false->Effect`\n\t * @type {Map}\n\t */\n\t#onscreen = new Map();\n\n\t/**\n\t * Similar to #onscreen with respect to the keys, but contains branches that are not yet\n\t * in the DOM, because their insertion is deferred.\n\t * @type {Map}\n\t */\n\t#offscreen = new Map();\n\n\t/**\n\t * Keys of effects that are currently outroing\n\t * @type {Set}\n\t */\n\t#outroing = new Set();\n\n\t/**\n\t * Whether to pause (i.e. outro) on change, or destroy immediately.\n\t * This is necessary for ``\n\t */\n\t#transition = true;\n\n\t/**\n\t * @param {TemplateNode} anchor\n\t * @param {boolean} transition\n\t */\n\tconstructor(anchor, transition = true) {\n\t\tthis.anchor = anchor;\n\t\tthis.#transition = transition;\n\t}\n\n\t/**\n\t * @param {Batch} batch\n\t */\n\t#commit = (batch) => {\n\t\t// if this batch was made obsolete, bail\n\t\tif (!this.#batches.has(batch)) return;\n\n\t\tvar key = /** @type {Key} */ (this.#batches.get(batch));\n\n\t\tvar onscreen = this.#onscreen.get(key);\n\n\t\tif (onscreen) {\n\t\t\t// effect is already in the DOM — abort any current outro\n\t\t\tresume_effect(onscreen);\n\t\t\tthis.#outroing.delete(key);\n\t\t} else {\n\t\t\t// effect is currently offscreen. put it in the DOM\n\t\t\tvar offscreen = this.#offscreen.get(key);\n\n\t\t\tif (offscreen) {\n\t\t\t\tthis.#onscreen.set(key, offscreen.effect);\n\t\t\t\tthis.#offscreen.delete(key);\n\n\t\t\t\tif (DEV) {\n\t\t\t\t\t// Tell hmr.js about the anchor it should use for updates,\n\t\t\t\t\t// since the initial one will be removed\n\t\t\t\t\t/** @type {any} */ (offscreen.fragment.lastChild)[HMR_ANCHOR] = this.anchor;\n\t\t\t\t}\n\n\t\t\t\t// remove the anchor...\n\t\t\t\t/** @type {TemplateNode} */ (offscreen.fragment.lastChild).remove();\n\n\t\t\t\t// ...and append the fragment\n\t\t\t\tthis.anchor.before(offscreen.fragment);\n\t\t\t\tonscreen = offscreen.effect;\n\t\t\t}\n\t\t}\n\n\t\tfor (const [b, k] of this.#batches) {\n\t\t\tthis.#batches.delete(b);\n\n\t\t\tif (b === batch) {\n\t\t\t\t// keep values for newer batches\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tconst offscreen = this.#offscreen.get(k);\n\n\t\t\tif (offscreen) {\n\t\t\t\t// for older batches, destroy offscreen effects\n\t\t\t\t// as they will never be committed\n\t\t\t\tdestroy_effect(offscreen.effect);\n\t\t\t\tthis.#offscreen.delete(k);\n\t\t\t}\n\t\t}\n\n\t\t// outro/destroy all onscreen effects...\n\t\tfor (const [k, effect] of this.#onscreen) {\n\t\t\t// ...except the one that was just committed\n\t\t\t// or those that are already outroing (else the transition is aborted and the effect destroyed right away)\n\t\t\tif (k === key || this.#outroing.has(k)) continue;\n\n\t\t\tconst on_destroy = () => {\n\t\t\t\tconst keys = Array.from(this.#batches.values());\n\n\t\t\t\tif (keys.includes(k)) {\n\t\t\t\t\t// keep the effect offscreen, as another batch will need it\n\t\t\t\t\tvar fragment = document.createDocumentFragment();\n\t\t\t\t\tmove_effect(effect, fragment);\n\n\t\t\t\t\tfragment.append(create_text()); // TODO can we avoid this?\n\n\t\t\t\t\tthis.#offscreen.set(k, { effect, fragment });\n\t\t\t\t} else {\n\t\t\t\t\tdestroy_effect(effect);\n\t\t\t\t}\n\n\t\t\t\tthis.#outroing.delete(k);\n\t\t\t\tthis.#onscreen.delete(k);\n\t\t\t};\n\n\t\t\tif (this.#transition || !onscreen) {\n\t\t\t\tthis.#outroing.add(k);\n\t\t\t\tpause_effect(effect, on_destroy, false);\n\t\t\t} else {\n\t\t\t\ton_destroy();\n\t\t\t}\n\t\t}\n\t};\n\n\t/**\n\t * @param {Batch} batch\n\t */\n\t#discard = (batch) => {\n\t\tthis.#batches.delete(batch);\n\n\t\tconst keys = Array.from(this.#batches.values());\n\n\t\tfor (const [k, branch] of this.#offscreen) {\n\t\t\tif (!keys.includes(k)) {\n\t\t\t\tdestroy_effect(branch.effect);\n\t\t\t\tthis.#offscreen.delete(k);\n\t\t\t}\n\t\t}\n\t};\n\n\t/**\n\t *\n\t * @param {any} key\n\t * @param {null | ((target: TemplateNode) => void)} fn\n\t */\n\tensure(key, fn) {\n\t\tvar batch = /** @type {Batch} */ (current_batch);\n\t\tvar defer = should_defer_append();\n\n\t\tif (fn && !this.#onscreen.has(key) && !this.#offscreen.has(key)) {\n\t\t\tif (defer) {\n\t\t\t\tvar fragment = document.createDocumentFragment();\n\t\t\t\tvar target = create_text();\n\n\t\t\t\tfragment.append(target);\n\n\t\t\t\tthis.#offscreen.set(key, {\n\t\t\t\t\teffect: branch(() => fn(target)),\n\t\t\t\t\tfragment\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tthis.#onscreen.set(\n\t\t\t\t\tkey,\n\t\t\t\t\tbranch(() => fn(this.anchor))\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tthis.#batches.set(batch, key);\n\n\t\tif (defer) {\n\t\t\tfor (const [k, effect] of this.#onscreen) {\n\t\t\t\tif (k === key) {\n\t\t\t\t\tbatch.unskip_effect(effect);\n\t\t\t\t} else {\n\t\t\t\t\tbatch.skip_effect(effect);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (const [k, branch] of this.#offscreen) {\n\t\t\t\tif (k === key) {\n\t\t\t\t\tbatch.unskip_effect(branch.effect);\n\t\t\t\t} else {\n\t\t\t\t\tbatch.skip_effect(branch.effect);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tbatch.oncommit(this.#commit);\n\t\t\tbatch.ondiscard(this.#discard);\n\t\t} else {\n\t\t\tif (hydrating) {\n\t\t\t\tthis.anchor = hydrate_node;\n\t\t\t}\n\n\t\t\tthis.#commit(batch);\n\t\t}\n\t}\n}\n","/** @import { ComponentContext, ComponentContextLegacy } from '#client' */\n/** @import { EventDispatcher } from './index.js' */\n/** @import { NotFunction } from './internal/types.js' */\nimport { active_reaction, untrack } from './internal/client/runtime.js';\nimport { is_array } from './internal/shared/utils.js';\nimport { user_effect } from './internal/client/index.js';\nimport * as e from './internal/client/errors.js';\nimport { legacy_mode_flag } from './internal/flags/index.js';\nimport { component_context } from './internal/client/context.js';\nimport { DEV } from 'esm-env';\n\nif (DEV) {\n\t/**\n\t * @param {string} rune\n\t */\n\tfunction throw_rune_error(rune) {\n\t\tif (!(rune in globalThis)) {\n\t\t\t// TODO if people start adjusting the \"this can contain runes\" config through v-p-s more, adjust this message\n\t\t\t/** @type {any} */\n\t\t\tlet value; // let's hope noone modifies this global, but belts and braces\n\t\t\tObject.defineProperty(globalThis, rune, {\n\t\t\t\tconfigurable: true,\n\t\t\t\t// eslint-disable-next-line getter-return\n\t\t\t\tget: () => {\n\t\t\t\t\tif (value !== undefined) {\n\t\t\t\t\t\treturn value;\n\t\t\t\t\t}\n\n\t\t\t\t\te.rune_outside_svelte(rune);\n\t\t\t\t},\n\t\t\t\tset: (v) => {\n\t\t\t\t\tvalue = v;\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}\n\n\tthrow_rune_error('$state');\n\tthrow_rune_error('$effect');\n\tthrow_rune_error('$derived');\n\tthrow_rune_error('$inspect');\n\tthrow_rune_error('$props');\n\tthrow_rune_error('$bindable');\n}\n\n/**\n * Returns an [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) that aborts when the current [derived](https://svelte.dev/docs/svelte/$derived) or [effect](https://svelte.dev/docs/svelte/$effect) re-runs or is destroyed.\n *\n * Must be called while a derived or effect is running.\n *\n * ```svelte\n * \n * ```\n */\nexport function getAbortSignal() {\n\tif (active_reaction === null) {\n\t\te.get_abort_signal_outside_reaction();\n\t}\n\n\treturn (active_reaction.ac ??= new AbortController()).signal;\n}\n\n/**\n * `onMount`, like [`$effect`](https://svelte.dev/docs/svelte/$effect), schedules a function to run as soon as the component has been mounted to the DOM.\n * Unlike `$effect`, the provided function only runs once.\n *\n * It must be called during the component's initialisation (but doesn't need to live _inside_ the component;\n * it can be called from an external module). If a function is returned _synchronously_ from `onMount`,\n * it will be called when the component is unmounted.\n *\n * `onMount` functions do not run during [server-side rendering](https://svelte.dev/docs/svelte/svelte-server#render).\n *\n * @template T\n * @param {() => NotFunction | Promise> | (() => any)} fn\n * @returns {void}\n */\nexport function onMount(fn) {\n\tif (component_context === null) {\n\t\te.lifecycle_outside_component('onMount');\n\t}\n\n\tif (legacy_mode_flag && component_context.l !== null) {\n\t\tinit_update_callbacks(component_context).m.push(fn);\n\t} else {\n\t\tuser_effect(() => {\n\t\t\tconst cleanup = untrack(fn);\n\t\t\tif (typeof cleanup === 'function') return /** @type {() => void} */ (cleanup);\n\t\t});\n\t}\n}\n\n/**\n * Schedules a callback to run immediately before the component is unmounted.\n *\n * Out of `onMount`, `beforeUpdate`, `afterUpdate` and `onDestroy`, this is the\n * only one that runs inside a server-side component.\n *\n * @param {() => any} fn\n * @returns {void}\n */\nexport function onDestroy(fn) {\n\tif (component_context === null) {\n\t\te.lifecycle_outside_component('onDestroy');\n\t}\n\n\tonMount(() => () => untrack(fn));\n}\n\n/**\n * @template [T=any]\n * @param {string} type\n * @param {T} [detail]\n * @param {any}params_0\n * @returns {CustomEvent}\n */\nfunction create_custom_event(type, detail, { bubbles = false, cancelable = false } = {}) {\n\treturn new CustomEvent(type, { detail, bubbles, cancelable });\n}\n\n/**\n * Creates an event dispatcher that can be used to dispatch [component events](https://svelte.dev/docs/svelte/legacy-on#Component-events).\n * Event dispatchers are functions that can take two arguments: `name` and `detail`.\n *\n * Component events created with `createEventDispatcher` create a\n * [CustomEvent](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent).\n * These events do not [bubble](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#Event_bubbling_and_capture).\n * The `detail` argument corresponds to the [CustomEvent.detail](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/detail)\n * property and can contain any type of data.\n *\n * The event dispatcher can be typed to narrow the allowed event names and the type of the `detail` argument:\n * ```ts\n * const dispatch = createEventDispatcher<{\n * loaded: null; // does not take a detail argument\n * change: string; // takes a detail argument of type string, which is required\n * optional: number | null; // takes an optional detail argument of type number\n * }>();\n * ```\n *\n * @deprecated Use callback props and/or the `$host()` rune instead — see [migration guide](https://svelte.dev/docs/svelte/v5-migration-guide#Event-changes-Component-events)\n * @template {Record} [EventMap = any]\n * @returns {EventDispatcher}\n */\nexport function createEventDispatcher() {\n\tconst active_component_context = component_context;\n\tif (active_component_context === null) {\n\t\te.lifecycle_outside_component('createEventDispatcher');\n\t}\n\n\t/**\n\t * @param [detail]\n\t * @param [options]\n\t */\n\treturn (type, detail, options) => {\n\t\tconst events = /** @type {Record} */ (\n\t\t\tactive_component_context.s.$$events\n\t\t)?.[/** @type {string} */ (type)];\n\n\t\tif (events) {\n\t\t\tconst callbacks = is_array(events) ? events.slice() : [events];\n\t\t\t// TODO are there situations where events could be dispatched\n\t\t\t// in a server (non-DOM) environment?\n\t\t\tconst event = create_custom_event(/** @type {string} */ (type), detail, options);\n\t\t\tfor (const fn of callbacks) {\n\t\t\t\tfn.call(active_component_context.x, event);\n\t\t\t}\n\t\t\treturn !event.defaultPrevented;\n\t\t}\n\n\t\treturn true;\n\t};\n}\n\n// TODO mark beforeUpdate and afterUpdate as deprecated in Svelte 6\n\n/**\n * Schedules a callback to run immediately before the component is updated after any state change.\n *\n * The first time the callback runs will be before the initial `onMount`.\n *\n * In runes mode use `$effect.pre` instead.\n *\n * @deprecated Use [`$effect.pre`](https://svelte.dev/docs/svelte/$effect#$effect.pre) instead\n * @param {() => void} fn\n * @returns {void}\n */\nexport function beforeUpdate(fn) {\n\tif (component_context === null) {\n\t\te.lifecycle_outside_component('beforeUpdate');\n\t}\n\n\tif (component_context.l === null) {\n\t\te.lifecycle_legacy_only('beforeUpdate');\n\t}\n\n\tinit_update_callbacks(component_context).b.push(fn);\n}\n\n/**\n * Schedules a callback to run immediately after the component has been updated.\n *\n * The first time the callback runs will be after the initial `onMount`.\n *\n * In runes mode use `$effect` instead.\n *\n * @deprecated Use [`$effect`](https://svelte.dev/docs/svelte/$effect) instead\n * @param {() => void} fn\n * @returns {void}\n */\nexport function afterUpdate(fn) {\n\tif (component_context === null) {\n\t\te.lifecycle_outside_component('afterUpdate');\n\t}\n\n\tif (component_context.l === null) {\n\t\te.lifecycle_legacy_only('afterUpdate');\n\t}\n\n\tinit_update_callbacks(component_context).a.push(fn);\n}\n\n/**\n * Legacy-mode: Init callbacks object for onMount/beforeUpdate/afterUpdate\n * @param {ComponentContext} context\n */\nfunction init_update_callbacks(context) {\n\tvar l = /** @type {ComponentContextLegacy} */ (context).l;\n\treturn (l.u ??= { a: [], b: [], m: [] });\n}\n\nexport { flushSync, fork } from './internal/client/reactivity/batch.js';\nexport {\n\tcreateContext,\n\tgetContext,\n\tgetAllContexts,\n\thasContext,\n\tsetContext\n} from './internal/client/context.js';\nexport { hydratable } from './internal/client/hydratable.js';\nexport { hydrate, mount, unmount } from './internal/client/render.js';\nexport { tick, untrack, settled } from './internal/client/runtime.js';\nexport { createRawSnippet } from './internal/client/dom/blocks/snippet.js';\n","/** @import { TemplateNode } from '#client' */\nimport { EFFECT_TRANSPARENT } from '#client/constants';\nimport {\n\thydrate_next,\n\thydrating,\n\tread_hydration_instruction,\n\tskip_nodes,\n\tset_hydrate_node,\n\tset_hydrating,\n\thydrate_node\n} from '../hydration.js';\nimport { block } from '../../reactivity/effects.js';\nimport { BranchManager } from './branches.js';\n\n/**\n * @param {TemplateNode} node\n * @param {(branch: (fn: (anchor: Node) => void, key?: number | false) => void) => void} fn\n * @param {boolean} [elseif] True if this is an `{:else if ...}` block rather than an `{#if ...}`, as that affects which transitions are considered 'local'\n * @returns {void}\n */\nexport function if_block(node, fn, elseif = false) {\n\t/** @type {TemplateNode | undefined} */\n\tvar marker;\n\tif (hydrating) {\n\t\tmarker = hydrate_node;\n\t\thydrate_next();\n\t}\n\n\tvar branches = new BranchManager(node);\n\tvar flags = elseif ? EFFECT_TRANSPARENT : 0;\n\n\t/**\n\t * @param {number | false} key\n\t * @param {null | ((anchor: Node) => void)} fn\n\t */\n\tfunction update_branch(key, fn) {\n\t\tif (hydrating) {\n\t\t\tvar data = read_hydration_instruction(/** @type {TemplateNode} */ (marker));\n\n\t\t\t// \"[n\" = branch n, \"[-1\" = else\n\t\t\tif (key !== parseInt(data.substring(1))) {\n\t\t\t\t// Hydration mismatch: remove everything inside the anchor and start fresh.\n\t\t\t\t// This could happen with `{#if browser}...{/if}`, for example\n\t\t\t\tvar anchor = skip_nodes();\n\n\t\t\t\tset_hydrate_node(anchor);\n\t\t\t\tbranches.anchor = anchor;\n\n\t\t\t\tset_hydrating(false);\n\t\t\t\tbranches.ensure(key, fn);\n\t\t\t\tset_hydrating(true);\n\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tbranches.ensure(key, fn);\n\t}\n\n\tblock(() => {\n\t\tvar has_branch = false;\n\n\t\tfn((fn, key = 0) => {\n\t\t\thas_branch = true;\n\t\t\tupdate_branch(key, fn);\n\t\t});\n\n\t\tif (!has_branch) {\n\t\t\tupdate_branch(-1, null);\n\t\t}\n\t}, flags);\n}\n","/** @import { EachItem, EachOutroGroup, EachState, Effect, EffectNodes, MaybeSource, Source, TemplateNode, TransitionManager, Value } from '#client' */\n/** @import { Batch } from '../../reactivity/batch.js'; */\nimport {\n\tEACH_INDEX_REACTIVE,\n\tEACH_IS_ANIMATED,\n\tEACH_IS_CONTROLLED,\n\tEACH_ITEM_IMMUTABLE,\n\tEACH_ITEM_REACTIVE,\n\tHYDRATION_END,\n\tHYDRATION_START_ELSE\n} from '../../../../constants.js';\nimport {\n\thydrate_next,\n\thydrate_node,\n\thydrating,\n\tread_hydration_instruction,\n\tskip_nodes,\n\tset_hydrate_node,\n\tset_hydrating\n} from '../hydration.js';\nimport {\n\tclear_text_content,\n\tcreate_text,\n\tget_first_child,\n\tget_next_sibling,\n\tshould_defer_append\n} from '../operations.js';\nimport {\n\tblock,\n\tbranch,\n\tdestroy_effect,\n\tmove_effect,\n\tpause_effect,\n\tresume_effect\n} from '../../reactivity/effects.js';\nimport { source, mutable_source, internal_set } from '../../reactivity/sources.js';\nimport { array_from, is_array } from '../../../shared/utils.js';\nimport { BRANCH_EFFECT, COMMENT_NODE, DESTROYED, EFFECT_OFFSCREEN, INERT } from '#client/constants';\nimport { queue_micro_task } from '../task.js';\nimport { get } from '../../runtime.js';\nimport { DEV } from 'esm-env';\nimport { derived_safe_equal } from '../../reactivity/deriveds.js';\nimport { current_batch } from '../../reactivity/batch.js';\nimport * as e from '../../errors.js';\nimport { tag } from '../../dev/tracing.js';\n\n// When making substantive changes to this file, validate them with the each block stress test:\n// https://svelte.dev/playground/1972b2cf46564476ad8c8c6405b23b7b\n// This test also exists in this repo, as `packages/svelte/tests/manual/each-stress-test`\n\n/**\n * @param {any} _\n * @param {number} i\n */\nexport function index(_, i) {\n\treturn i;\n}\n\n/**\n * Pause multiple effects simultaneously, and coordinate their\n * subsequent destruction. Used in each blocks\n * @param {EachState} state\n * @param {Effect[]} to_destroy\n * @param {null | Node} controlled_anchor\n */\nfunction pause_effects(state, to_destroy, controlled_anchor) {\n\t/** @type {TransitionManager[]} */\n\tvar transitions = [];\n\tvar length = to_destroy.length;\n\n\t/** @type {EachOutroGroup} */\n\tvar group;\n\tvar remaining = to_destroy.length;\n\n\tfor (var i = 0; i < length; i++) {\n\t\tlet effect = to_destroy[i];\n\n\t\tpause_effect(\n\t\t\teffect,\n\t\t\t() => {\n\t\t\t\tif (group) {\n\t\t\t\t\tgroup.pending.delete(effect);\n\t\t\t\t\tgroup.done.add(effect);\n\n\t\t\t\t\tif (group.pending.size === 0) {\n\t\t\t\t\t\tvar groups = /** @type {Set} */ (state.outrogroups);\n\n\t\t\t\t\t\tdestroy_effects(state, array_from(group.done));\n\t\t\t\t\t\tgroups.delete(group);\n\n\t\t\t\t\t\tif (groups.size === 0) {\n\t\t\t\t\t\t\tstate.outrogroups = null;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tremaining -= 1;\n\t\t\t\t}\n\t\t\t},\n\t\t\tfalse\n\t\t);\n\t}\n\n\tif (remaining === 0) {\n\t\t// If we're in a controlled each block (i.e. the block is the only child of an\n\t\t// element), and we are removing all items, _and_ there are no out transitions,\n\t\t// we can use the fast path — emptying the element and replacing the anchor\n\t\tvar fast_path = transitions.length === 0 && controlled_anchor !== null;\n\n\t\tif (fast_path) {\n\t\t\tvar anchor = /** @type {Element} */ (controlled_anchor);\n\t\t\tvar parent_node = /** @type {Element} */ (anchor.parentNode);\n\n\t\t\tclear_text_content(parent_node);\n\t\t\tparent_node.append(anchor);\n\n\t\t\tstate.items.clear();\n\t\t}\n\n\t\tdestroy_effects(state, to_destroy, !fast_path);\n\t} else {\n\t\tgroup = {\n\t\t\tpending: new Set(to_destroy),\n\t\t\tdone: new Set()\n\t\t};\n\n\t\t(state.outrogroups ??= new Set()).add(group);\n\t}\n}\n\n/**\n * @param {EachState} state\n * @param {Effect[]} to_destroy\n * @param {boolean} remove_dom\n */\nfunction destroy_effects(state, to_destroy, remove_dom = true) {\n\t/** @type {Set | undefined} */\n\tvar preserved_effects;\n\n\t// The loop-in-a-loop isn't ideal, but we should only hit this in relatively rare cases\n\tif (state.pending.size > 0) {\n\t\tpreserved_effects = new Set();\n\n\t\tfor (const keys of state.pending.values()) {\n\t\t\tfor (const key of keys) {\n\t\t\t\tpreserved_effects.add(/** @type {EachItem} */ (state.items.get(key)).e);\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (var i = 0; i < to_destroy.length; i++) {\n\t\tvar e = to_destroy[i];\n\n\t\tif (preserved_effects?.has(e)) {\n\t\t\te.f |= EFFECT_OFFSCREEN;\n\n\t\t\tconst fragment = document.createDocumentFragment();\n\t\t\tmove_effect(e, fragment);\n\t\t} else {\n\t\t\tdestroy_effect(to_destroy[i], remove_dom);\n\t\t}\n\t}\n}\n\n/** @type {TemplateNode} */\nvar offscreen_anchor;\n\n/**\n * @template V\n * @param {Element | Comment} node The next sibling node, or the parent node if this is a 'controlled' block\n * @param {number} flags\n * @param {() => V[]} get_collection\n * @param {(value: V, index: number) => any} get_key\n * @param {(anchor: Node, item: MaybeSource, index: MaybeSource) => void} render_fn\n * @param {null | ((anchor: Node) => void)} fallback_fn\n * @returns {void}\n */\nexport function each(node, flags, get_collection, get_key, render_fn, fallback_fn = null) {\n\tvar anchor = node;\n\n\t/** @type {Map} */\n\tvar items = new Map();\n\n\tvar is_controlled = (flags & EACH_IS_CONTROLLED) !== 0;\n\n\tif (is_controlled) {\n\t\tvar parent_node = /** @type {Element} */ (node);\n\n\t\tanchor = hydrating\n\t\t\t? set_hydrate_node(get_first_child(parent_node))\n\t\t\t: parent_node.appendChild(create_text());\n\t}\n\n\tif (hydrating) {\n\t\thydrate_next();\n\t}\n\n\t/** @type {Effect | null} */\n\tvar fallback = null;\n\n\t// TODO: ideally we could use derived for runes mode but because of the ability\n\t// to use a store which can be mutated, we can't do that here as mutating a store\n\t// will still result in the collection array being the same from the store\n\tvar each_array = derived_safe_equal(() => {\n\t\tvar collection = get_collection();\n\n\t\treturn is_array(collection) ? collection : collection == null ? [] : array_from(collection);\n\t});\n\n\tif (DEV) {\n\t\ttag(each_array, '{#each ...}');\n\t}\n\n\t/** @type {V[]} */\n\tvar array;\n\n\t/** @type {Map>} */\n\tvar pending = new Map();\n\n\tvar first_run = true;\n\n\t/**\n\t * @param {Batch} batch\n\t */\n\tfunction commit(batch) {\n\t\tif ((state.effect.f & DESTROYED) !== 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tstate.pending.delete(batch);\n\n\t\tstate.fallback = fallback;\n\t\treconcile(state, array, anchor, flags, get_key);\n\n\t\tif (fallback !== null) {\n\t\t\tif (array.length === 0) {\n\t\t\t\tif ((fallback.f & EFFECT_OFFSCREEN) === 0) {\n\t\t\t\t\tresume_effect(fallback);\n\t\t\t\t} else {\n\t\t\t\t\tfallback.f ^= EFFECT_OFFSCREEN;\n\t\t\t\t\tmove(fallback, null, anchor);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tpause_effect(fallback, () => {\n\t\t\t\t\t// TODO only null out if no pending batch needs it,\n\t\t\t\t\t// otherwise re-add `fallback.fragment` and move the\n\t\t\t\t\t// effect into it\n\t\t\t\t\tfallback = null;\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * @param {Batch} batch\n\t */\n\tfunction discard(batch) {\n\t\tstate.pending.delete(batch);\n\t}\n\n\tvar effect = block(() => {\n\t\tarray = /** @type {V[]} */ (get(each_array));\n\t\tvar length = array.length;\n\n\t\t/** `true` if there was a hydration mismatch. Needs to be a `let` or else it isn't treeshaken out */\n\t\tlet mismatch = false;\n\n\t\tif (hydrating) {\n\t\t\tvar is_else = read_hydration_instruction(anchor) === HYDRATION_START_ELSE;\n\n\t\t\tif (is_else !== (length === 0)) {\n\t\t\t\t// hydration mismatch — remove the server-rendered DOM and start over\n\t\t\t\tanchor = skip_nodes();\n\n\t\t\t\tset_hydrate_node(anchor);\n\t\t\t\tset_hydrating(false);\n\t\t\t\tmismatch = true;\n\t\t\t}\n\t\t}\n\n\t\tvar keys = new Set();\n\t\tvar batch = /** @type {Batch} */ (current_batch);\n\t\tvar defer = should_defer_append();\n\n\t\tfor (var index = 0; index < length; index += 1) {\n\t\t\tif (\n\t\t\t\thydrating &&\n\t\t\t\thydrate_node.nodeType === COMMENT_NODE &&\n\t\t\t\t/** @type {Comment} */ (hydrate_node).data === HYDRATION_END\n\t\t\t) {\n\t\t\t\t// The server rendered fewer items than expected,\n\t\t\t\t// so break out and continue appending non-hydrated items\n\t\t\t\tanchor = /** @type {Comment} */ (hydrate_node);\n\t\t\t\tmismatch = true;\n\t\t\t\tset_hydrating(false);\n\t\t\t}\n\n\t\t\tvar value = array[index];\n\t\t\tvar key = get_key(value, index);\n\n\t\t\tif (DEV) {\n\t\t\t\t// Check that the key function is idempotent (returns the same value when called twice)\n\t\t\t\tvar key_again = get_key(value, index);\n\t\t\t\tif (key !== key_again) {\n\t\t\t\t\te.each_key_volatile(String(index), String(key), String(key_again));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvar item = first_run ? null : items.get(key);\n\n\t\t\tif (item) {\n\t\t\t\t// update before reconciliation, to trigger any async updates\n\t\t\t\tif (item.v) internal_set(item.v, value);\n\t\t\t\tif (item.i) internal_set(item.i, index);\n\n\t\t\t\tif (defer) {\n\t\t\t\t\tbatch.unskip_effect(item.e);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\titem = create_item(\n\t\t\t\t\titems,\n\t\t\t\t\tfirst_run ? anchor : (offscreen_anchor ??= create_text()),\n\t\t\t\t\tvalue,\n\t\t\t\t\tkey,\n\t\t\t\t\tindex,\n\t\t\t\t\trender_fn,\n\t\t\t\t\tflags,\n\t\t\t\t\tget_collection\n\t\t\t\t);\n\n\t\t\t\tif (!first_run) {\n\t\t\t\t\titem.e.f |= EFFECT_OFFSCREEN;\n\t\t\t\t}\n\n\t\t\t\titems.set(key, item);\n\t\t\t}\n\n\t\t\tkeys.add(key);\n\t\t}\n\n\t\tif (length === 0 && fallback_fn && !fallback) {\n\t\t\tif (first_run) {\n\t\t\t\tfallback = branch(() => fallback_fn(anchor));\n\t\t\t} else {\n\t\t\t\tfallback = branch(() => fallback_fn((offscreen_anchor ??= create_text())));\n\t\t\t\tfallback.f |= EFFECT_OFFSCREEN;\n\t\t\t}\n\t\t}\n\n\t\tif (length > keys.size) {\n\t\t\tif (DEV) {\n\t\t\t\tvalidate_each_keys(array, get_key);\n\t\t\t} else {\n\t\t\t\t// in prod, the additional information isn't printed, so don't bother computing it\n\t\t\t\te.each_key_duplicate('', '', '');\n\t\t\t}\n\t\t}\n\n\t\t// remove excess nodes\n\t\tif (hydrating && length > 0) {\n\t\t\tset_hydrate_node(skip_nodes());\n\t\t}\n\n\t\tif (!first_run) {\n\t\t\tpending.set(batch, keys);\n\n\t\t\tif (defer) {\n\t\t\t\tfor (const [key, item] of items) {\n\t\t\t\t\tif (!keys.has(key)) {\n\t\t\t\t\t\tbatch.skip_effect(item.e);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tbatch.oncommit(commit);\n\t\t\t\tbatch.ondiscard(discard);\n\t\t\t} else {\n\t\t\t\tcommit(batch);\n\t\t\t}\n\t\t}\n\n\t\tif (mismatch) {\n\t\t\t// continue in hydration mode\n\t\t\tset_hydrating(true);\n\t\t}\n\n\t\t// When we mount the each block for the first time, the collection won't be\n\t\t// connected to this effect as the effect hasn't finished running yet and its deps\n\t\t// won't be assigned. However, it's possible that when reconciling the each block\n\t\t// that a mutation occurred and it's made the collection MAYBE_DIRTY, so reading the\n\t\t// collection again can provide consistency to the reactive graph again as the deriveds\n\t\t// will now be `CLEAN`.\n\t\tget(each_array);\n\t});\n\n\t/** @type {EachState} */\n\tvar state = { effect, flags, items, pending, outrogroups: null, fallback };\n\n\tfirst_run = false;\n\n\tif (hydrating) {\n\t\tanchor = hydrate_node;\n\t}\n}\n\n/**\n * Skip past any non-branch effects (which could be created with `createSubscriber`, for example) to find the next branch effect\n * @param {Effect | null} effect\n * @returns {Effect | null}\n */\nfunction skip_to_branch(effect) {\n\twhile (effect !== null && (effect.f & BRANCH_EFFECT) === 0) {\n\t\teffect = effect.next;\n\t}\n\treturn effect;\n}\n\n/**\n * Add, remove, or reorder items output by an each block as its input changes\n * @template V\n * @param {EachState} state\n * @param {Array} array\n * @param {Element | Comment | Text} anchor\n * @param {number} flags\n * @param {(value: V, index: number) => any} get_key\n * @returns {void}\n */\nfunction reconcile(state, array, anchor, flags, get_key) {\n\tvar is_animated = (flags & EACH_IS_ANIMATED) !== 0;\n\n\tvar length = array.length;\n\tvar items = state.items;\n\tvar current = skip_to_branch(state.effect.first);\n\n\t/** @type {undefined | Set} */\n\tvar seen;\n\n\t/** @type {Effect | null} */\n\tvar prev = null;\n\n\t/** @type {undefined | Set} */\n\tvar to_animate;\n\n\t/** @type {Effect[]} */\n\tvar matched = [];\n\n\t/** @type {Effect[]} */\n\tvar stashed = [];\n\n\t/** @type {V} */\n\tvar value;\n\n\t/** @type {any} */\n\tvar key;\n\n\t/** @type {Effect | undefined} */\n\tvar effect;\n\n\t/** @type {number} */\n\tvar i;\n\n\tif (is_animated) {\n\t\tfor (i = 0; i < length; i += 1) {\n\t\t\tvalue = array[i];\n\t\t\tkey = get_key(value, i);\n\t\t\teffect = /** @type {EachItem} */ (items.get(key)).e;\n\n\t\t\t// offscreen == coming in now, no animation in that case,\n\t\t\t// else this would happen https://github.com/sveltejs/svelte/issues/17181\n\t\t\tif ((effect.f & EFFECT_OFFSCREEN) === 0) {\n\t\t\t\teffect.nodes?.a?.measure();\n\t\t\t\t(to_animate ??= new Set()).add(effect);\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (i = 0; i < length; i += 1) {\n\t\tvalue = array[i];\n\t\tkey = get_key(value, i);\n\n\t\teffect = /** @type {EachItem} */ (items.get(key)).e;\n\n\t\tif (state.outrogroups !== null) {\n\t\t\tfor (const group of state.outrogroups) {\n\t\t\t\tgroup.pending.delete(effect);\n\t\t\t\tgroup.done.delete(effect);\n\t\t\t}\n\t\t}\n\n\t\tif ((effect.f & INERT) !== 0) {\n\t\t\tresume_effect(effect);\n\t\t\tif (is_animated) {\n\t\t\t\teffect.nodes?.a?.unfix();\n\t\t\t\t(to_animate ??= new Set()).delete(effect);\n\t\t\t}\n\t\t}\n\n\t\tif ((effect.f & EFFECT_OFFSCREEN) !== 0) {\n\t\t\teffect.f ^= EFFECT_OFFSCREEN;\n\n\t\t\tif (effect === current) {\n\t\t\t\tmove(effect, null, anchor);\n\t\t\t} else {\n\t\t\t\tvar next = prev ? prev.next : current;\n\n\t\t\t\tif (effect === state.effect.last) {\n\t\t\t\t\tstate.effect.last = effect.prev;\n\t\t\t\t}\n\n\t\t\t\tif (effect.prev) effect.prev.next = effect.next;\n\t\t\t\tif (effect.next) effect.next.prev = effect.prev;\n\t\t\t\tlink(state, prev, effect);\n\t\t\t\tlink(state, effect, next);\n\n\t\t\t\tmove(effect, next, anchor);\n\t\t\t\tprev = effect;\n\n\t\t\t\tmatched = [];\n\t\t\t\tstashed = [];\n\n\t\t\t\tcurrent = skip_to_branch(prev.next);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tif (effect !== current) {\n\t\t\tif (seen !== undefined && seen.has(effect)) {\n\t\t\t\tif (matched.length < stashed.length) {\n\t\t\t\t\t// more efficient to move later items to the front\n\t\t\t\t\tvar start = stashed[0];\n\t\t\t\t\tvar j;\n\n\t\t\t\t\tprev = start.prev;\n\n\t\t\t\t\tvar a = matched[0];\n\t\t\t\t\tvar b = matched[matched.length - 1];\n\n\t\t\t\t\tfor (j = 0; j < matched.length; j += 1) {\n\t\t\t\t\t\tmove(matched[j], start, anchor);\n\t\t\t\t\t}\n\n\t\t\t\t\tfor (j = 0; j < stashed.length; j += 1) {\n\t\t\t\t\t\tseen.delete(stashed[j]);\n\t\t\t\t\t}\n\n\t\t\t\t\tlink(state, a.prev, b.next);\n\t\t\t\t\tlink(state, prev, a);\n\t\t\t\t\tlink(state, b, start);\n\n\t\t\t\t\tcurrent = start;\n\t\t\t\t\tprev = b;\n\t\t\t\t\ti -= 1;\n\n\t\t\t\t\tmatched = [];\n\t\t\t\t\tstashed = [];\n\t\t\t\t} else {\n\t\t\t\t\t// more efficient to move earlier items to the back\n\t\t\t\t\tseen.delete(effect);\n\t\t\t\t\tmove(effect, current, anchor);\n\n\t\t\t\t\tlink(state, effect.prev, effect.next);\n\t\t\t\t\tlink(state, effect, prev === null ? state.effect.first : prev.next);\n\t\t\t\t\tlink(state, prev, effect);\n\n\t\t\t\t\tprev = effect;\n\t\t\t\t}\n\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tmatched = [];\n\t\t\tstashed = [];\n\n\t\t\twhile (current !== null && current !== effect) {\n\t\t\t\t(seen ??= new Set()).add(current);\n\t\t\t\tstashed.push(current);\n\t\t\t\tcurrent = skip_to_branch(current.next);\n\t\t\t}\n\n\t\t\tif (current === null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tif ((effect.f & EFFECT_OFFSCREEN) === 0) {\n\t\t\tmatched.push(effect);\n\t\t}\n\n\t\tprev = effect;\n\t\tcurrent = skip_to_branch(effect.next);\n\t}\n\n\tif (state.outrogroups !== null) {\n\t\tfor (const group of state.outrogroups) {\n\t\t\tif (group.pending.size === 0) {\n\t\t\t\tdestroy_effects(state, array_from(group.done));\n\t\t\t\tstate.outrogroups?.delete(group);\n\t\t\t}\n\t\t}\n\n\t\tif (state.outrogroups.size === 0) {\n\t\t\tstate.outrogroups = null;\n\t\t}\n\t}\n\n\tif (current !== null || seen !== undefined) {\n\t\t/** @type {Effect[]} */\n\t\tvar to_destroy = [];\n\n\t\tif (seen !== undefined) {\n\t\t\tfor (effect of seen) {\n\t\t\t\tif ((effect.f & INERT) === 0) {\n\t\t\t\t\tto_destroy.push(effect);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\twhile (current !== null) {\n\t\t\t// If the each block isn't inert, then inert effects are currently outroing and will be removed once the transition is finished\n\t\t\tif ((current.f & INERT) === 0 && current !== state.fallback) {\n\t\t\t\tto_destroy.push(current);\n\t\t\t}\n\n\t\t\tcurrent = skip_to_branch(current.next);\n\t\t}\n\n\t\tvar destroy_length = to_destroy.length;\n\n\t\tif (destroy_length > 0) {\n\t\t\tvar controlled_anchor = (flags & EACH_IS_CONTROLLED) !== 0 && length === 0 ? anchor : null;\n\n\t\t\tif (is_animated) {\n\t\t\t\tfor (i = 0; i < destroy_length; i += 1) {\n\t\t\t\t\tto_destroy[i].nodes?.a?.measure();\n\t\t\t\t}\n\n\t\t\t\tfor (i = 0; i < destroy_length; i += 1) {\n\t\t\t\t\tto_destroy[i].nodes?.a?.fix();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tpause_effects(state, to_destroy, controlled_anchor);\n\t\t}\n\t}\n\n\tif (is_animated) {\n\t\tqueue_micro_task(() => {\n\t\t\tif (to_animate === undefined) return;\n\t\t\tfor (effect of to_animate) {\n\t\t\t\teffect.nodes?.a?.apply();\n\t\t\t}\n\t\t});\n\t}\n}\n\n/**\n * @template V\n * @param {Map} items\n * @param {Node} anchor\n * @param {V} value\n * @param {unknown} key\n * @param {number} index\n * @param {(anchor: Node, item: V | Source, index: number | Value, collection: () => V[]) => void} render_fn\n * @param {number} flags\n * @param {() => V[]} get_collection\n * @returns {EachItem}\n */\nfunction create_item(items, anchor, value, key, index, render_fn, flags, get_collection) {\n\tvar v =\n\t\t(flags & EACH_ITEM_REACTIVE) !== 0\n\t\t\t? (flags & EACH_ITEM_IMMUTABLE) === 0\n\t\t\t\t? mutable_source(value, false, false)\n\t\t\t\t: source(value)\n\t\t\t: null;\n\n\tvar i = (flags & EACH_INDEX_REACTIVE) !== 0 ? source(index) : null;\n\n\tif (DEV && v) {\n\t\t// For tracing purposes, we need to link the source signal we create with the\n\t\t// collection + index so that tracing works as intended\n\t\tv.trace = () => {\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unused-expressions\n\t\t\tget_collection()[i?.v ?? index];\n\t\t};\n\t}\n\n\treturn {\n\t\tv,\n\t\ti,\n\t\te: branch(() => {\n\t\t\trender_fn(anchor, v ?? value, i ?? index, get_collection);\n\n\t\t\treturn () => {\n\t\t\t\titems.delete(key);\n\t\t\t};\n\t\t})\n\t};\n}\n\n/**\n * @param {Effect} effect\n * @param {Effect | null} next\n * @param {Text | Element | Comment} anchor\n */\nfunction move(effect, next, anchor) {\n\tif (!effect.nodes) return;\n\n\tvar node = effect.nodes.start;\n\tvar end = effect.nodes.end;\n\n\tvar dest =\n\t\tnext && (next.f & EFFECT_OFFSCREEN) === 0\n\t\t\t? /** @type {EffectNodes} */ (next.nodes).start\n\t\t\t: anchor;\n\n\twhile (node !== null) {\n\t\tvar next_node = /** @type {TemplateNode} */ (get_next_sibling(node));\n\t\tdest.before(node);\n\n\t\tif (node === end) {\n\t\t\treturn;\n\t\t}\n\n\t\tnode = next_node;\n\t}\n}\n\n/**\n * @param {EachState} state\n * @param {Effect | null} prev\n * @param {Effect | null} next\n */\nfunction link(state, prev, next) {\n\tif (prev === null) {\n\t\tstate.effect.first = next;\n\t} else {\n\t\tprev.next = next;\n\t}\n\n\tif (next === null) {\n\t\tstate.effect.last = prev;\n\t} else {\n\t\tnext.prev = prev;\n\t}\n}\n\n/**\n * @param {Array} array\n * @param {(item: any, index: number) => string} key_fn\n * @returns {void}\n */\nfunction validate_each_keys(array, key_fn) {\n\tconst keys = new Map();\n\tconst length = array.length;\n\n\tfor (let i = 0; i < length; i++) {\n\t\tconst key = key_fn(array[i], i);\n\n\t\tif (keys.has(key)) {\n\t\t\tconst a = String(keys.get(key));\n\t\t\tconst b = String(i);\n\n\t\t\t/** @type {string | null} */\n\t\t\tlet k = String(key);\n\t\t\tif (k.startsWith('[object ')) k = null;\n\n\t\t\te.each_key_duplicate(a, b, k);\n\t\t}\n\n\t\tkeys.set(key, i);\n\t}\n}\n","/** @import { Effect, TemplateNode } from '#client' */\n/** @import {} from 'trusted-types' */\nimport {\n\tFILENAME,\n\tHYDRATION_ERROR,\n\tNAMESPACE_SVG,\n\tNAMESPACE_MATHML\n} from '../../../../constants.js';\nimport { remove_effect_dom, template_effect } from '../../reactivity/effects.js';\nimport { hydrate_next, hydrate_node, hydrating, set_hydrate_node } from '../hydration.js';\n\nimport { assign_nodes } from '../template.js';\nimport * as w from '../../warnings.js';\nimport { hash, sanitize_location } from '../../../../utils.js';\nimport { DEV } from 'esm-env';\nimport { dev_current_component_function } from '../../context.js';\nimport { create_element, get_first_child, get_next_sibling } from '../operations.js';\nimport { active_effect } from '../../runtime.js';\nimport { COMMENT_NODE } from '#client/constants';\n\n/**\n * @param {Element} element\n * @param {string | null} server_hash\n * @param {string | TrustedHTML} value\n */\nfunction check_hash(element, server_hash, value) {\n\tif (!server_hash || server_hash === hash(String(value ?? ''))) return;\n\n\tlet location;\n\n\t// @ts-expect-error\n\tconst loc = element.__svelte_meta?.loc;\n\tif (loc) {\n\t\tlocation = `near ${loc.file}:${loc.line}:${loc.column}`;\n\t} else if (dev_current_component_function?.[FILENAME]) {\n\t\tlocation = `in ${dev_current_component_function[FILENAME]}`;\n\t}\n\n\tw.hydration_html_changed(sanitize_location(location));\n}\n\n/**\n * @param {Element | Text | Comment} node\n * @param {() => string | TrustedHTML} get_value\n * @param {boolean} [is_controlled]\n * @param {boolean} [svg]\n * @param {boolean} [mathml]\n * @param {boolean} [skip_warning]\n * @returns {void}\n */\nexport function html(\n\tnode,\n\tget_value,\n\tis_controlled = false,\n\tsvg = false,\n\tmathml = false,\n\tskip_warning = false\n) {\n\tvar anchor = node;\n\n\t/** @type {string | TrustedHTML} */\n\tvar value = '';\n\n\tif (is_controlled) {\n\t\tvar parent_node = /** @type {Element} */ (node);\n\n\t\tif (hydrating) {\n\t\t\tanchor = set_hydrate_node(get_first_child(parent_node));\n\t\t}\n\t}\n\n\ttemplate_effect(() => {\n\t\tvar effect = /** @type {Effect} */ (active_effect);\n\n\t\tif (value === (value = get_value() ?? '')) {\n\t\t\tif (hydrating) hydrate_next();\n\t\t\treturn;\n\t\t}\n\n\t\tif (is_controlled && !hydrating) {\n\t\t\t// When @html is the only child, use innerHTML directly.\n\t\t\t// This also handles contenteditable, where the user may delete the anchor comment.\n\t\t\teffect.nodes = null;\n\t\t\tparent_node.innerHTML = /** @type {string} */ (value);\n\n\t\t\tif (value !== '') {\n\t\t\t\tassign_nodes(\n\t\t\t\t\t/** @type {TemplateNode} */ (get_first_child(parent_node)),\n\t\t\t\t\t/** @type {TemplateNode} */ (parent_node.lastChild)\n\t\t\t\t);\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\tif (effect.nodes !== null) {\n\t\t\tremove_effect_dom(effect.nodes.start, /** @type {TemplateNode} */ (effect.nodes.end));\n\t\t\teffect.nodes = null;\n\t\t}\n\n\t\tif (value === '') return;\n\n\t\tif (hydrating) {\n\t\t\t// We're deliberately not trying to repair mismatches between server and client,\n\t\t\t// as it's costly and error-prone (and it's an edge case to have a mismatch anyway)\n\t\t\tvar hash = /** @type {Comment} */ (hydrate_node).data;\n\n\t\t\t/** @type {TemplateNode | null} */\n\t\t\tvar next = hydrate_next();\n\t\t\tvar last = next;\n\n\t\t\twhile (\n\t\t\t\tnext !== null &&\n\t\t\t\t(next.nodeType !== COMMENT_NODE || /** @type {Comment} */ (next).data !== '')\n\t\t\t) {\n\t\t\t\tlast = next;\n\t\t\t\tnext = get_next_sibling(next);\n\t\t\t}\n\n\t\t\tif (next === null) {\n\t\t\t\tw.hydration_mismatch();\n\t\t\t\tthrow HYDRATION_ERROR;\n\t\t\t}\n\n\t\t\tif (DEV && !skip_warning) {\n\t\t\t\tcheck_hash(/** @type {Element} */ (next.parentNode), hash, value);\n\t\t\t}\n\n\t\t\tassign_nodes(hydrate_node, last);\n\t\t\tanchor = set_hydrate_node(next);\n\t\t\treturn;\n\t\t}\n\n\t\t// Don't use create_fragment_with_script_from_html here because that would mean script tags are executed.\n\t\t// @html is basically `.innerHTML = ...` and that doesn't execute scripts either due to security reasons.\n\t\t// Use a