diff --git a/.gitattributes b/.gitattributes index a6344aac8c09253b3b630fb776ae94478aa0275b..c5bc9f41cca2e9ee0082116057bccb4c34637fff 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,35 +1,2 @@ -*.7z filter=lfs diff=lfs merge=lfs -text -*.arrow filter=lfs diff=lfs merge=lfs -text -*.bin filter=lfs diff=lfs merge=lfs -text -*.bz2 filter=lfs diff=lfs merge=lfs -text -*.ckpt filter=lfs diff=lfs merge=lfs -text -*.ftz filter=lfs diff=lfs merge=lfs -text -*.gz filter=lfs diff=lfs merge=lfs -text -*.h5 filter=lfs diff=lfs merge=lfs -text -*.joblib filter=lfs diff=lfs merge=lfs -text -*.lfs.* filter=lfs diff=lfs merge=lfs -text -*.mlmodel filter=lfs diff=lfs merge=lfs -text -*.model filter=lfs diff=lfs merge=lfs -text -*.msgpack filter=lfs diff=lfs merge=lfs -text -*.npy filter=lfs diff=lfs merge=lfs -text -*.npz filter=lfs diff=lfs merge=lfs -text -*.onnx filter=lfs diff=lfs merge=lfs -text -*.ot filter=lfs diff=lfs merge=lfs -text -*.parquet filter=lfs diff=lfs merge=lfs -text -*.pb filter=lfs diff=lfs merge=lfs -text -*.pickle filter=lfs diff=lfs merge=lfs -text -*.pkl filter=lfs diff=lfs merge=lfs -text -*.pt filter=lfs diff=lfs merge=lfs -text -*.pth filter=lfs diff=lfs merge=lfs -text -*.rar filter=lfs diff=lfs merge=lfs -text -*.safetensors filter=lfs diff=lfs merge=lfs -text -saved_model/**/* filter=lfs diff=lfs merge=lfs -text -*.tar.* filter=lfs diff=lfs merge=lfs -text -*.tar filter=lfs diff=lfs merge=lfs -text -*.tflite filter=lfs diff=lfs merge=lfs -text -*.tgz filter=lfs diff=lfs merge=lfs -text *.wasm filter=lfs diff=lfs merge=lfs -text -*.xz filter=lfs diff=lfs merge=lfs -text -*.zip filter=lfs diff=lfs merge=lfs -text -*.zst filter=lfs diff=lfs merge=lfs -text -*tfevents* filter=lfs diff=lfs merge=lfs -text +*.gz filter=lfs diff=lfs merge=lfs -text diff --git a/README.md b/README.md index 834b3badcf6fa73f7c3e903f1edfd7828233c13e..62d740a249434e2b5913a8330b4a43828cfe39c1 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,36 @@ --- title: LocalWebAgent -emoji: 🐨 -colorFrom: yellow -colorTo: green +emoji: 🐧 +colorFrom: green +colorTo: purple sdk: static +app_file: index.html pinned: false license: apache-2.0 -short_description: Run an AI agent completely local! +short_description: LFM3-1.7B agent driving a real Linux VM, fully offline +models: + - LiquidAI/LFM3-1.7B-ONNX +custom_headers: + cross-origin-embedder-policy: require-corp + cross-origin-opener-policy: same-origin + cross-origin-resource-policy: cross-origin --- -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference +# LocalWebAgent + +An AI agent with its own Linux computer, entirely inside one web page. + +- **Model:** [LFM3-1.7B](https://huggingface.co/LiquidAI/LFM3-1.7B) (q4f16 ONNX) running on your GPU through WebGPU with [transformers.js](https://github.com/huggingface/transformers.js). +- **Computer:** a real Debian (i386) machine running in the browser on [CheerpX](https://cheerpx.io), the engine behind [WebVM](https://webvm.io). +- **Agent harness:** the model calls `run_command`, `write_file` and `read_file` tools. Commands run in the same terminal you see, so you can watch and take over at any time. +- **File viewer:** browse the machine's files and open code (syntax highlighted), text, Markdown, images, audio and video. HTML pages open as sandboxed live previews together with the stylesheets, scripts, images and data files they reference, and links between pages work. +- **Offline:** the first visit downloads everything (about 1.6 GB) into your browser's storage. After that it works with no internet connection. + +**Requirements:** desktop Chrome or Edge with WebGPU and `shader-f16` support, about 2.5 GB of free disk space, and 8 GB or more RAM. Open the app at its own URL (`https://-localwebagent.static.hf.space`), because the embedded view on huggingface.co can't enable the cross-origin isolation CheerpX needs. + +## Licenses + +- This app: Apache-2.0. +- LFM3-1.7B: [LFM Open License v1.0](https://huggingface.co/LiquidAI/LFM3-1.7B-ONNX/blob/main/LICENSE). The weights are loaded directly from Liquid AI's repository, not re-hosted here. +- CheerpX: proprietary, free for personal and open-source projects. It is **not** included in this Space. Each visitor's browser loads it from Leaning Technologies' CDN and caches it locally. +- The Debian disk image (`disk/`) contains Debian packages under their respective free licenses. diff --git a/css/app.css b/css/app.css new file mode 100644 index 0000000000000000000000000000000000000000..fd31a75456c796933b84cefce9597edf81ef290b --- /dev/null +++ b/css/app.css @@ -0,0 +1,478 @@ +@font-face { + font-family: "Inter"; font-style: normal; font-weight: 100 900; font-display: swap; + src: url(../vendor/fonts/inter-latin.woff2) format("woff2"); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; +} +@font-face { + font-family: "Inter"; font-style: normal; font-weight: 100 900; font-display: swap; + src: url(../vendor/fonts/inter-latin-ext.woff2) format("woff2"); + unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF; +} +@font-face { + font-family: "JetBrains Mono"; font-style: normal; font-weight: 100 800; font-display: swap; + src: url(../vendor/fonts/jetbrains-mono-latin.woff2) format("woff2"); +} + +/* ---------- tokens ---------- */ +:root { + --bg: #fafafa; + --surface: #ffffff; + --surface-2: #f4f4f5; + --surface-3: #ececee; + --border: #e4e4e7; + --border-strong: #d4d4d8; + --text: #09090b; + --text-2: #52525b; + --text-3: #8a8a93; + --primary: #09090b; + --primary-ink: #fafafa; + --focus: #3b82f6; + --ok: #16a34a; + --warn: #ca8a04; + --bad: #dc2626; + --code-bg: #f4f4f5; + --code-text: #27272a; + --term-bg: #0c0c0e; + --term-border: #1f1f23; + --shadow-lg: 0 16px 48px -12px rgba(0, 0, 0, .18), 0 0 0 1px rgba(0, 0, 0, .05); + --sans: "Inter", ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif; + --mono: "JetBrains Mono", ui-monospace, "Cascadia Code", Menlo, Consolas, monospace; + --radius: 12px; + --radius-sm: 9px; + --radius-lg: 18px; + color-scheme: light; +} +@media (prefers-color-scheme: dark) { + :root:not([data-theme="light"]) { + --bg: #0c0c0e; + --surface: #111113; + --surface-2: #18181b; + --surface-3: #202024; + --border: #232327; + --border-strong: #2e2e33; + --text: #ececef; + --text-2: #a1a1aa; + --text-3: #6b6b74; + --primary: #ececef; + --primary-ink: #0c0c0e; + --focus: #60a5fa; + --ok: #3fb950; + --warn: #d29922; + --bad: #f85149; + --code-bg: #0c0c0e; + --code-text: #d4d4d8; + --shadow-lg: 0 24px 64px -16px rgba(0, 0, 0, .7), 0 0 0 1px rgba(255, 255, 255, .06); + color-scheme: dark; + } +} +:root[data-theme="dark"] { + --bg: #0c0c0e; --surface: #111113; --surface-2: #18181b; --surface-3: #202024; --border: #232327; --border-strong: #2e2e33; + --text: #ececef; --text-2: #a1a1aa; --text-3: #6b6b74; --primary: #ececef; --primary-ink: #0c0c0e; --focus: #60a5fa; + --ok: #3fb950; --warn: #d29922; --bad: #f85149; --code-bg: #0c0c0e; --code-text: #d4d4d8; color-scheme: dark; +} + +/* ---------- base ---------- */ +* { box-sizing: border-box; } +html, body { height: 100%; margin: 0; } +body { + background: var(--bg); color: var(--text); + font: 13.5px/1.55 var(--sans); font-feature-settings: "cv11", "ss03"; + -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; + display: grid; grid-template-rows: auto 1fr; overflow: hidden; +} +button, input, textarea { font: inherit; color: inherit; } +button { cursor: pointer; } +a { color: inherit; text-decoration: underline; text-decoration-color: var(--border-strong); text-underline-offset: 2px; } +a:hover { text-decoration-color: var(--text-2); } +[hidden] { display: none !important; } +.mono { font-family: var(--mono); font-size: .92em; } +.spacer { flex: 1; } +svg { width: 16px; height: 16px; fill: none; stroke: currentColor; stroke-width: 1.75; stroke-linecap: round; stroke-linejoin: round; flex: none; } +:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; } +::selection { background: color-mix(in srgb, var(--focus) 30%, transparent); } +kbd { font: 500 11px var(--mono); padding: 1px 6px; border: 1px solid var(--border-strong); border-bottom-width: 2px; border-radius: 6px; color: var(--text-2); background: var(--surface); } + +/* ---------- title bar ---------- */ +.titlebar { + height: 44px; display: flex; align-items: center; gap: 20px; padding: 0 10px 0 16px; + border-bottom: 1px solid var(--border); background: var(--surface); +} +.brand { display: flex; align-items: center; gap: 9px; min-width: 0; white-space: nowrap; } +.brand-name { font-weight: 600; letter-spacing: -.01em; } +.brand-sep { color: var(--border-strong); } +.brand-model { color: var(--text-2); } +.brand-device { color: var(--text-3); font-size: 11px; border: 1px solid var(--border); border-radius: 999px; padding: 0 8px; line-height: 18px; } +.status { display: flex; align-items: center; gap: 16px; margin-left: auto; font-size: 12px; color: var(--text-2); white-space: nowrap; } +.status-item { display: inline-flex; align-items: center; gap: 7px; } +.status-item i { width: 6px; height: 6px; border-radius: 50%; background: var(--text-3); opacity: .6; } +.status-item[data-state="ok"] i { background: var(--ok); opacity: 1; } +.status-item[data-state="busy"] i { background: var(--warn); opacity: 1; animation: blink 1.2s ease-in-out infinite; } +.status-item[data-state="warn"] i { background: var(--warn); opacity: 1; } +.status-item[data-state="bad"] i { background: var(--bad); opacity: 1; } +.status-item[data-state="bad"] { color: var(--bad); } +.status-text { font-variant-numeric: tabular-nums; } +@keyframes blink { 50% { opacity: .3; } } +.titlebar-actions { display: flex; gap: 2px; padding-left: 12px; border-left: 1px solid var(--border); } +.icon-btn { + width: 32px; height: 32px; display: grid; place-items: center; border: 0; border-radius: 10px; + background: none; color: var(--text-2); +} +.icon-btn:hover { background: var(--surface-2); color: var(--text); } + +/* ---------- workspace ---------- */ +.tabs { display: none; } +.workspace { --left: 46%; display: grid; grid-template-columns: minmax(380px, var(--left)) 1px minmax(360px, 1fr); min-height: 0; } +.pane { min-width: 0; min-height: 0; display: flex; flex-direction: column; } +.splitter { background: var(--border); position: relative; cursor: col-resize; } +.splitter::after { content: ""; position: absolute; inset: 0 -4px; z-index: 2; } +.splitter:hover, .splitter.dragging { background: var(--focus); } +body.resizing { cursor: col-resize; user-select: none; } +body.resizing iframe, body.resizing #terminal { pointer-events: none; } + +/* ---------- chat ---------- */ +.chat { background: var(--bg); } +.scroller { flex: 1; overflow-y: auto; scrollbar-gutter: stable; } +.thread { max-width: 760px; margin: 0 auto; padding: 28px 28px 12px; display: flex; flex-direction: column; gap: 22px; min-height: 100%; } + +.empty { margin: auto 0; padding-bottom: 8vh; } +.empty h1 { font-size: 20px; font-weight: 600; letter-spacing: -.02em; margin: 0 0 6px; } +.empty p { color: var(--text-2); margin: 0 0 28px; max-width: 520px; } +.examples-label, .section-label { font-size: 11.5px; font-weight: 500; color: var(--text-3); margin-bottom: 8px; } +.examples { display: flex; flex-direction: column; border: 1px solid var(--border); border-radius: var(--radius-lg); overflow: hidden; background: var(--surface); } +.example { + display: flex; align-items: center; gap: 10px; text-align: left; padding: 11px 14px; border: 0; background: none; + color: var(--text); border-top: 1px solid var(--border); +} +.example:first-child { border-top: 0; } +.example svg { color: var(--text-3); width: 14px; height: 14px; transition: transform .15s; } +.example:hover { background: var(--surface-2); } +.example:hover svg { transform: translateX(2px); color: var(--text-2); } + +.msg.user { + align-self: stretch; background: var(--surface-2); border: 1px solid var(--border); border-radius: var(--radius-lg); + padding: 11px 15px; white-space: pre-wrap; overflow-wrap: anywhere; +} +.msg.agent { display: flex; flex-direction: column; gap: 8px; } +.step { display: flex; flex-direction: column; gap: 8px; } + +/* reasoning */ +.reasoning summary { + list-style: none; display: inline-flex; align-items: center; gap: 6px; cursor: pointer; user-select: none; + color: var(--text-3); font-size: 12.5px; padding: 2px 0; +} +.reasoning summary::-webkit-details-marker { display: none; } +.reasoning summary svg { width: 12px; height: 12px; transition: transform .15s; } +.reasoning[open] summary svg { transform: rotate(90deg); } +.reasoning summary:hover { color: var(--text-2); } +.reasoning .r-body { + margin: 6px 0 2px 5px; padding: 2px 0 2px 13px; border-left: 1px solid var(--border-strong); + color: var(--text-2); font-size: 12.5px; white-space: pre-wrap; overflow-wrap: anywhere; max-height: 320px; overflow-y: auto; +} +.reasoning .r-time { font-variant-numeric: tabular-nums; } + +/* answer */ +.md { overflow-wrap: anywhere; } +.md:empty { display: none; } +.md p { margin: 0 0 10px; } .md p:last-child { margin-bottom: 0; } +.md ul, .md ol { margin: 4px 0 10px; padding-left: 20px; } .md li { margin: 2px 0; } +.md h3, .md h4, .md h5, .md h6 { margin: 14px 0 6px; font-size: 13.5px; font-weight: 600; } +.md strong { font-weight: 600; } +.md code { font: 12.5px var(--mono); background: var(--surface-2); border: 1px solid var(--border); padding: 1px 5px; border-radius: 6px; } +.md pre.md-code { background: var(--code-bg); border: 1px solid var(--border); color: var(--code-text); padding: 12px 14px; border-radius: var(--radius); overflow-x: auto; margin: 8px 0; } +.md pre.md-code code { background: none; border: 0; padding: 0; font-size: 12.5px; line-height: 1.6; } +.md-link { text-decoration: underline dotted; text-underline-offset: 2px; } + +/* tool calls */ +.tool { border: 1px solid var(--border); border-radius: var(--radius); background: var(--surface); overflow: hidden; } +.tool-head { + display: flex; align-items: center; gap: 9px; width: 100%; padding: 8px 12px; border: 0; background: none; text-align: left; + font-size: 12.5px; min-height: 38px; +} +.tool-head:hover { background: var(--surface-2); } +.tool-head > svg { color: var(--text-3); } +.tool-head .chev { width: 12px; height: 12px; color: var(--text-3); transition: transform .15s; } +.tool.open .tool-head .chev { transform: rotate(90deg); } +.tool-label { font-family: var(--mono); font-size: 12px; color: var(--text); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; } +.tool-label .verb { font-family: var(--sans); color: var(--text-2); font-size: 12.5px; margin-right: 6px; } +.tool-meta { margin-left: auto; display: inline-flex; align-items: center; gap: 8px; color: var(--text-3); font-size: 11.5px; font-variant-numeric: tabular-nums; white-space: nowrap; padding-left: 10px; } +.tool-meta .dot { width: 6px; height: 6px; border-radius: 50%; background: var(--text-3); } +.tool[data-state="running"] .dot { background: var(--warn); animation: blink 1s infinite; } +.tool[data-state="ok"] .dot { background: var(--ok); } +.tool[data-state="fail"] .dot, .tool[data-state="error"] .dot, .tool[data-state="timeout"] .dot { background: var(--bad); } +.tool[data-state="fail"] .t-status, .tool[data-state="error"] .t-status, .tool[data-state="timeout"] .t-status { color: var(--bad); } +.tool-body { border-top: 1px solid var(--border); } +.tool:not(.open) .tool-body { display: none; } +.tool-body pre { + margin: 0; padding: 10px 12px; font: 12px/1.6 var(--mono); white-space: pre-wrap; overflow-wrap: anywhere; + max-height: 300px; overflow-y: auto; background: var(--code-bg); color: var(--code-text); +} +.tool-body .sub { padding: 5px 12px; font-size: 11px; color: var(--text-3); background: var(--surface); border-top: 1px solid var(--border); } +.tool-body .sub:first-child { border-top: 0; } +.confirm { display: flex; align-items: center; gap: 8px; padding: 8px 10px; border-top: 1px solid var(--border); font-size: 12.5px; color: var(--text-2); } +.confirm span { margin-right: auto; } + +.run-status { display: flex; align-items: center; gap: 8px; color: var(--text-3); font-size: 12.5px; } +.spinner { width: 12px; height: 12px; border-radius: 50%; border: 1.5px solid var(--border-strong); border-top-color: var(--text-2); animation: spin .7s linear infinite; } +@keyframes spin { to { transform: rotate(360deg); } } +.run-foot { color: var(--text-3); font-size: 11.5px; font-variant-numeric: tabular-nums; padding-top: 2px; } +.notice { color: var(--text-3); font-size: 12.5px; } +.notice.center { align-self: center; text-align: center; } +.notice.error { color: var(--bad); } +.notice.warn { color: var(--warn); } + +/* ---------- composer ---------- */ +.composer-wrap { max-width: 760px; width: 100%; margin: 0 auto; padding: 8px 28px 10px; } +.composer { + border: 1px solid var(--border-strong); border-radius: 20px; background: var(--surface); + transition: border-color .15s, box-shadow .15s; +} +.composer:focus-within { border-color: var(--text-3); box-shadow: 0 0 0 3px color-mix(in srgb, var(--text-3) 15%, transparent); } +.composer textarea { + display: block; width: 100%; resize: none; border: 0; outline: 0; background: none; padding: 14px 16px 4px; + min-height: 46px; max-height: 220px; line-height: 1.5; +} +.composer textarea::placeholder { color: var(--text-3); } +.composer-bar { display: flex; align-items: center; gap: 4px; padding: 6px 8px 8px 8px; } +.toggle { + display: inline-flex; align-items: center; gap: 6px; height: 28px; padding: 0 11px; border-radius: 999px; + border: 1px solid transparent; background: none; color: var(--text-3); font-size: 12px; +} +.toggle svg { width: 13px; height: 13px; } +.toggle:hover { color: var(--text-2); background: var(--surface-2); } +.toggle[aria-pressed="true"] { color: var(--text); background: var(--surface-2); border-color: var(--border); } +.hint { color: var(--text-3); font-size: 11.5px; margin-right: 6px; } +.send { + width: 32px; height: 32px; display: grid; place-items: center; border-radius: 999px; border: 0; + background: var(--primary); color: var(--primary-ink); +} +.send svg { width: 15px; height: 15px; stroke-width: 2.2; } +.send:disabled { opacity: .3; cursor: not-allowed; } +.send.stop { background: var(--surface-3); color: var(--text); } +.meta { display: flex; justify-content: space-between; padding: 6px 2px 0; font-size: 11px; color: var(--text-3); font-variant-numeric: tabular-nums; min-height: 22px; } + +/* ---------- buttons ---------- */ +.btn { + height: 32px; padding: 0 14px; border-radius: 10px; border: 1px solid var(--border-strong); background: var(--surface); + color: var(--text); font-size: 12.5px; font-weight: 500; white-space: nowrap; display: inline-flex; align-items: center; justify-content: center; gap: 6px; +} +.btn:hover:not(:disabled) { background: var(--surface-2); } +.btn:disabled { opacity: .45; cursor: not-allowed; } +.btn.primary { background: var(--primary); border-color: var(--primary); color: var(--primary-ink); } +.btn.primary:hover:not(:disabled) { background: color-mix(in srgb, var(--primary) 88%, var(--bg)); } +.btn.danger { color: var(--bad); } +.btn.block { width: 100%; height: 42px; font-size: 13.5px; border-radius: var(--radius); } +.btn.small { height: 28px; padding: 0 12px; font-size: 12px; border-radius: 8px; } + +/* ---------- side pane (terminal + files) ---------- */ +.side { background: var(--surface); } +.side-head { + height: 48px; display: flex; align-items: center; gap: 10px; padding: 0 10px 0 10px; + border-bottom: 1px solid var(--border); background: var(--surface); +} +.seg { display: inline-flex; padding: 3px; gap: 2px; border-radius: 999px; background: var(--surface-2); border: 1px solid var(--border); } +.seg button { + display: inline-flex; align-items: center; gap: 7px; height: 28px; padding: 0 13px; border: 0; border-radius: 999px; + background: none; color: var(--text-2); font-size: 12.5px; font-weight: 500; +} +.seg button svg { width: 14px; height: 14px; } +.seg button:hover { color: var(--text); } +.seg button[aria-selected="true"], .seg button[aria-pressed="true"] { background: var(--surface); color: var(--text); box-shadow: 0 1px 2px rgba(0,0,0,.12), 0 0 0 1px var(--border); } +.seg.small button { height: 24px; padding: 0 10px; font-size: 12px; } +.side-meta { color: var(--text-3); font-size: 11px; } +.led { width: 6px; height: 6px; border-radius: 50%; background: var(--border-strong); transition: background .2s, box-shadow .2s; } +.led[data-on="1"] { background: var(--ok); box-shadow: 0 0 0 3px color-mix(in srgb, var(--ok) 20%, transparent); } +.badge { width: 7px; height: 7px; border-radius: 50%; background: var(--focus); } +.mini-btn { + height: 30px; min-width: 30px; display: inline-flex; align-items: center; justify-content: center; gap: 6px; padding: 0 7px; + border-radius: 9px; border: 0; background: none; color: var(--text-2); font-size: 12px; +} +.mini-btn svg { width: 15px; height: 15px; } +.mini-btn.labeled { padding: 0 11px 0 9px; } +.mini-btn:hover { background: var(--surface-2); color: var(--text); } +.mini-btn[aria-pressed="true"] { color: var(--text); background: var(--surface-2); } +.term-actions { display: inline-flex; gap: 2px; } +.side[data-view="files"] .term-actions, .side[data-view="files"] .side-meta { display: none; } +.side-body { flex: 1; min-height: 0; display: flex; } +.view { flex: 1; min-width: 0; min-height: 0; display: flex; flex-direction: column; } +.view-term { background: var(--term-bg); } +#terminal { flex: 1; min-height: 0; padding: 10px 0 4px 14px; } +#terminal .xterm { height: 100%; } +#terminal .xterm-viewport { scrollbar-width: thin; scrollbar-color: #2e2e33 transparent; } +body.side-max .workspace { grid-template-columns: 0 0 1fr; } +body.side-max .chat { visibility: hidden; } + +/* ---------- file viewer ---------- */ +.files { flex-direction: row; container-type: inline-size; background: var(--bg); } +.explorer { width: 240px; flex: none; display: flex; flex-direction: column; border-right: 1px solid var(--border); background: var(--surface); min-height: 0; } +.ex-head { display: flex; align-items: center; gap: 2px; padding: 8px 8px 4px; } +.crumbs { display: flex; flex-wrap: wrap; align-items: center; gap: 1px; padding: 2px 10px 8px; font: 11.5px var(--mono); color: var(--text-3); } +.crumb { border: 0; background: none; padding: 1px 4px; border-radius: 6px; color: var(--text-2); font: inherit; } +.crumb:hover { background: var(--surface-2); color: var(--text); } +.crumb-sep { color: var(--border-strong); } +.ex-list { flex: 1; overflow-y: auto; padding: 0 6px 8px; display: flex; flex-direction: column; gap: 1px; scrollbar-width: thin; } +.ex-list.loading { opacity: .5; } +.ex-item { + display: flex; align-items: center; gap: 9px; width: 100%; padding: 6px 9px; border: 0; border-radius: 9px; background: none; + text-align: left; font-size: 12.5px; color: var(--text); min-height: 32px; +} +.ex-item svg { width: 15px; height: 15px; color: var(--text-3); } +.ex-item:hover { background: var(--surface-2); } +.ex-item.active { background: color-mix(in srgb, var(--focus) 14%, transparent); } +.ex-item.active svg { color: var(--focus); } +.ex-item.dim { color: var(--text-3); } +.ex-name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.ex-size { color: var(--text-3); font-size: 11px; font-variant-numeric: tabular-nums; } +.ex-empty, .ex-error { padding: 12px; color: var(--text-3); font-size: 12px; } +.ex-error { color: var(--bad); } +.viewer { flex: 1; min-width: 0; display: flex; flex-direction: column; min-height: 0; } +.vw-head { display: flex; align-items: center; gap: 10px; min-height: 48px; padding: 0 10px 0 16px; border-bottom: 1px solid var(--border); background: var(--surface); } +.vw-path { display: flex; min-width: 0; font: 12px var(--mono); white-space: nowrap; } +.vw-dir { color: var(--text-3); overflow: hidden; text-overflow: ellipsis; min-width: 0; } +.vw-file { color: var(--text); flex: none; font-weight: 500; } +.vw-meta { color: var(--text-3); font-size: 11.5px; white-space: nowrap; font-variant-numeric: tabular-nums; } +.vw-actions { display: inline-flex; align-items: center; gap: 4px; } +.vw-body { flex: 1; min-height: 0; overflow: auto; display: flex; flex-direction: column; } +.vw-empty { margin: auto; text-align: center; color: var(--text-3); padding: 24px; display: flex; flex-direction: column; align-items: center; gap: 6px; } +.vw-empty svg { width: 28px; height: 28px; stroke-width: 1.4; margin-bottom: 4px; } +.vw-empty-title { color: var(--text-2); font-weight: 500; } +.vw-empty-sub { font-size: 12px; max-width: 280px; } +.vw-loading { margin: auto; } +.vw-code { display: flex; align-items: flex-start; min-width: max-content; min-height: 100%; background: var(--code-bg); } +.vw-code pre { margin: 0; padding: 14px 0; font: 12.5px/1.65 var(--mono); } +.vw-code .gutter { padding: 14px 14px 14px 16px; text-align: right; color: var(--text-3); opacity: .7; user-select: none; position: sticky; left: 0; background: var(--code-bg); border-right: 1px solid var(--border); } +.vw-code .code { padding-left: 16px; padding-right: 24px; color: var(--code-text); tab-size: 4; } +.vw-note { padding: 8px 16px; font-size: 12px; color: var(--text-3); border-top: 1px solid var(--border); background: var(--surface); } +.vw-note.top { border-top: 0; border-bottom: 1px solid var(--border); } +.vw-doc { padding: 24px 28px; max-width: 760px; } +.vw-image { flex: 1; display: grid; place-items: center; padding: 24px; overflow: auto; + background-color: var(--surface); background-image: linear-gradient(45deg, var(--surface-2) 25%, transparent 25%, transparent 75%, var(--surface-2) 75%), linear-gradient(45deg, var(--surface-2) 25%, transparent 25%, transparent 75%, var(--surface-2) 75%); + background-size: 20px 20px; background-position: 0 0, 10px 10px; } +.vw-image img { border-radius: 6px; box-shadow: 0 2px 12px rgba(0,0,0,.2); cursor: zoom-in; image-rendering: auto; } +.vw-image img.fit { max-width: 100%; max-height: 100%; cursor: zoom-out; } +.vw-media { flex: 1; display: grid; place-items: center; padding: 24px; } +.vw-media video { max-width: 100%; max-height: 100%; border-radius: var(--radius); } +.vw-binary .hex { margin: 0; padding: 14px 16px; font: 12px/1.6 var(--mono); color: var(--text-2); } +.vw-frame-wrap { flex: 1; display: flex; padding: 12px; background: var(--surface-2); } +.vw-frame { flex: 1; border: 1px solid var(--border); border-radius: var(--radius); background: #fff; box-shadow: 0 1px 3px rgba(0,0,0,.08); } +@container (max-width: 560px) { + .files { flex-direction: column; } + .explorer { width: auto; max-height: 38%; border-right: 0; border-bottom: 1px solid var(--border); } +} + +/* syntax highlighting (highlight.js classes) */ +.hljs-comment, .hljs-quote { color: var(--text-3); font-style: italic; } +.hljs-keyword, .hljs-selector-tag, .hljs-literal, .hljs-type, .hljs-built_in { color: #c084fc; } +.hljs-string, .hljs-regexp, .hljs-addition, .hljs-attribute, .hljs-template-tag { color: #4ade80; } +.hljs-number, .hljs-symbol, .hljs-bullet, .hljs-variable.constant_ { color: #fbbf24; } +.hljs-title, .hljs-title.function_, .hljs-section, .hljs-name { color: #60a5fa; } +.hljs-attr, .hljs-variable, .hljs-template-variable, .hljs-params, .hljs-property { color: #f9a8d4; } +.hljs-meta, .hljs-meta .hljs-keyword, .hljs-doctag { color: #22d3ee; } +.hljs-deletion { color: var(--bad); } +.hljs-tag { color: var(--text-2); } +.hljs-emphasis { font-style: italic; } .hljs-strong { font-weight: 600; } +:root[data-theme="light"] .hljs-keyword, :root[data-theme="light"] .hljs-built_in, :root[data-theme="light"] .hljs-type, :root[data-theme="light"] .hljs-literal { color: #7c3aed; } +@media (prefers-color-scheme: light) { + .hljs-keyword, .hljs-selector-tag, .hljs-literal, .hljs-type, .hljs-built_in { color: #7c3aed; } + .hljs-string, .hljs-regexp, .hljs-addition, .hljs-attribute { color: #15803d; } + .hljs-number, .hljs-symbol, .hljs-bullet { color: #b45309; } + .hljs-title, .hljs-title.function_, .hljs-section, .hljs-name { color: #1d4ed8; } + .hljs-attr, .hljs-variable, .hljs-params, .hljs-property { color: #be185d; } + .hljs-meta, .hljs-doctag { color: #0e7490; } +} + +/* "Open" link on tool rows */ +.tool-open { border: 0; background: none; color: var(--text-2); font-size: 11.5px; padding: 2px 9px; border-radius: 999px; display: inline-flex; align-items: center; gap: 5px; } +.tool-open svg { width: 12px; height: 12px; } +.tool-open:hover { background: var(--surface-3); color: var(--text); } + +/* ---------- setup ---------- */ +.setup { position: fixed; inset: 0; z-index: 20; background: var(--bg); overflow-y: auto; display: flex; padding: 48px 16px; } +.setup-inner { width: min(540px, 100%); margin: auto; } +.setup-brand { display: flex; align-items: center; gap: 10px; font-weight: 600; margin-bottom: 36px; } +.setup h2 { font-size: 22px; font-weight: 600; letter-spacing: -.02em; margin: 0 0 8px; } +.lede { color: var(--text-2); margin: 0 0 28px; } +.checks { list-style: none; margin: 0 0 24px; padding: 0; border: 1px solid var(--border); border-radius: var(--radius); background: var(--surface); } +.checks li { display: flex; align-items: center; gap: 10px; padding: 8px 12px; border-top: 1px solid var(--border); font-size: 12.5px; color: var(--text-2); } +.checks li:first-child { border-top: 0; } +.checks li svg { width: 14px; height: 14px; stroke-width: 2.2; } +.checks li.ok svg { color: var(--ok); } +.checks li.bad { color: var(--text); } +.checks li.bad svg { color: var(--bad); } +.checks li.warn svg { color: var(--warn); } +.components { border: 1px solid var(--border); border-radius: var(--radius); background: var(--surface); margin-bottom: 20px; } +.component { display: grid; grid-template-columns: 1fr auto; gap: 2px 16px; padding: 12px 14px 0; border-top: 1px solid var(--border); } +.component:first-child { border-top: 0; } +.c-main { display: flex; flex-direction: column; min-width: 0; } +.c-name { font-weight: 500; } +.c-desc { color: var(--text-3); font-size: 12px; } +.c-side { display: flex; flex-direction: column; align-items: flex-end; text-align: right; } +.c-size { color: var(--text-2); } +.row-state { font-size: 12px; color: var(--text-3); font-variant-numeric: tabular-nums; } +.component[data-state="done"] .row-state { color: var(--ok); } +.component[data-state="busy"] .row-state { color: var(--text-2); } +.component progress { + grid-column: 1 / -1; width: calc(100% + 28px); margin: 10px -14px 0; height: 2px; border: 0; appearance: none; background: transparent; display: block; +} +.component progress::-webkit-progress-bar { background: transparent; } +.component progress::-webkit-progress-value { background: var(--text); transition: width .25s; } +.component progress::-moz-progress-bar { background: var(--text); } +.component[data-state="done"] progress::-webkit-progress-value { background: var(--ok); } +.component[data-state="done"] progress::-moz-progress-bar { background: var(--ok); } +.note { min-height: 20px; font-size: 12.5px; color: var(--text-2); margin: 12px 0 0; } +.note.error { color: var(--bad); } +.fine { font-size: 11.5px; color: var(--text-3); margin: 28px 0 0; line-height: 1.6; } + +/* ---------- settings dialog ---------- */ +dialog { + width: min(460px, calc(100% - 32px)); padding: 0; border: 0; border-radius: 20px; + background: var(--surface); color: var(--text); box-shadow: var(--shadow-lg); +} +dialog::backdrop { background: rgba(0, 0, 0, .5); } +dialog[open] { animation: pop .14s ease-out; } +@keyframes pop { from { opacity: 0; transform: translateY(4px) scale(.99); } } +.dlg-head { display: flex; align-items: center; justify-content: space-between; padding: 16px 14px 6px 22px; } +.dlg-head h2 { margin: 0; font-size: 14.5px; font-weight: 600; } +.dlg-section { padding: 10px 22px 16px; } +.dlg-section + .dlg-section { border-top: 1px solid var(--border); padding-top: 14px; } +.row-setting { display: flex; align-items: center; justify-content: space-between; gap: 20px; padding: 8px 0; cursor: default; } +.rs-title { display: block; font-weight: 500; } +.rs-desc { display: block; color: var(--text-3); font-size: 12px; } +.num { + width: 76px; height: 32px; padding: 0 10px; border-radius: 10px; border: 1px solid var(--border-strong); + background: var(--surface-2); text-align: right; font-variant-numeric: tabular-nums; +} +.switch { + appearance: none; flex: none; width: 32px; height: 18px; border-radius: 99px; background: var(--surface-3); + border: 1px solid var(--border-strong); position: relative; cursor: pointer; transition: background .15s; margin: 0; +} +.switch::after { + content: ""; position: absolute; top: 2px; left: 2px; width: 12px; height: 12px; border-radius: 50%; + background: var(--text-2); transition: transform .15s, background .15s; +} +.switch:checked { background: var(--primary); border-color: var(--primary); } +.switch:checked::after { transform: translateX(14px); background: var(--primary-ink); } + +/* ---------- narrow screens ---------- */ +@media (max-width: 900px) { + body { grid-template-rows: auto auto 1fr; } + .brand-sep, .brand-model, .brand-device { display: none; } + .status { gap: 12px; } + .status-text { display: none; } + .tabs { display: flex; border-bottom: 1px solid var(--border); background: var(--surface); padding: 0 8px; } + .tabs button { padding: 9px 12px; border: 0; background: none; color: var(--text-3); font-weight: 500; border-bottom: 1.5px solid transparent; margin-bottom: -1px; } + .tabs button[aria-selected="true"] { color: var(--text); border-bottom-color: var(--text); } + .workspace { grid-template-columns: 1fr; } + .splitter { display: none; } + body[data-tab="chat"] .side, body[data-tab="term"] .chat, body[data-tab="files"] .chat { display: none; } + .side .seg, #side-max { display: none; } + .thread { padding: 20px 16px 8px; } + .composer-wrap { padding: 8px 16px 10px; } + .hint { display: none; } +} +@media (max-width: 480px) { + .toggle { padding: 0 7px; } + .toggle-text { display: none; } +} + +/* Code should show exactly what is typed: no programming ligatures (=> stays =>). */ +code, pre, kbd, .mono, .tool-label, .crumbs, .vw-path, .hex, #terminal * { font-variant-ligatures: none !important; font-feature-settings: "liga" 0, "calt" 0 !important; } diff --git a/disk/chunk-00000.gz b/disk/chunk-00000.gz new file mode 100644 index 0000000000000000000000000000000000000000..60ac43cc7b7be31cb3f8a59cde26bcace1cebb2d --- /dev/null +++ b/disk/chunk-00000.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:04c1a94ffac3dfac71f629aee86a65541ef386710e3cdfa8e819bcd6da2886cb +size 1027382 diff --git a/disk/chunk-00001.gz b/disk/chunk-00001.gz new file mode 100644 index 0000000000000000000000000000000000000000..047210f6b2fd00c90924376b8fc9db9de72c5185 --- /dev/null +++ b/disk/chunk-00001.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:470eeec7d4f5ba8e20003a4f594a2b3cef5b82dce196e625a82659a4bcc2e6be +size 1719838 diff --git a/disk/chunk-00002.gz b/disk/chunk-00002.gz new file mode 100644 index 0000000000000000000000000000000000000000..208e0567efdc9e0f1eb29391ecfac398e9788e48 --- /dev/null +++ b/disk/chunk-00002.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:09967bf3208891c9408b78fabb24c81668a93129db0bbfd31f6b7cefc95547db +size 1357969 diff --git a/disk/chunk-00003.gz b/disk/chunk-00003.gz new file mode 100644 index 0000000000000000000000000000000000000000..eec0df7f54d29c1154ac25bc9b3d9427629397ae --- /dev/null +++ b/disk/chunk-00003.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:29eba81334be26bff4b5822ace4660da9c981bd5e143cb22254cb08ad32ff285 +size 1802211 diff --git a/disk/chunk-00004.gz b/disk/chunk-00004.gz new file mode 100644 index 0000000000000000000000000000000000000000..015a64175b86c5663884345268aabdf5224ac93a --- /dev/null +++ b/disk/chunk-00004.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dc4286213fd4c570e4bd7e26a25f564867cf3420d1760e3edf6821bf5ca9bca9 +size 1706138 diff --git a/disk/chunk-00005.gz b/disk/chunk-00005.gz new file mode 100644 index 0000000000000000000000000000000000000000..6947097b1032df4def7f3451627bafc7fd517f15 --- /dev/null +++ b/disk/chunk-00005.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9cc1fdfc85d805da528dd729109a27d50321f258e515ec0d040ee85be6ea7216 +size 1427457 diff --git a/disk/chunk-00006.gz b/disk/chunk-00006.gz new file mode 100644 index 0000000000000000000000000000000000000000..99064cc95bc90db6cfbe0433e604f88ff4ae1ec3 --- /dev/null +++ b/disk/chunk-00006.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:27ca013dcc0df237722e7462ffbe0988fa598d9b012c578cc85a18ca9702b795 +size 1677164 diff --git a/disk/chunk-00007.gz b/disk/chunk-00007.gz new file mode 100644 index 0000000000000000000000000000000000000000..e00a97520a72237921792d4652137a75dbc8b5d7 --- /dev/null +++ b/disk/chunk-00007.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e15db36bd63b1e2396bd9993176b0f3a4c33407a12d51e1f0c3838a57d65cc9d +size 1625468 diff --git a/disk/chunk-00008.gz b/disk/chunk-00008.gz new file mode 100644 index 0000000000000000000000000000000000000000..f9f18c81ca6c66a4848ed39210a1712a57fd6246 --- /dev/null +++ b/disk/chunk-00008.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d97dbb6057bd86dc1d1dff32d24a23012ef869d0c6cf52bccd708f35b3853fe4 +size 1904995 diff --git a/disk/chunk-00009.gz b/disk/chunk-00009.gz new file mode 100644 index 0000000000000000000000000000000000000000..1690cf600da3ac4be91b8e348bce35678c1b2b7d --- /dev/null +++ b/disk/chunk-00009.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:38cb8516d766c25855d883d9af49c3e94447f72be179ee62f5a58181d2b06a6a +size 1911454 diff --git a/disk/chunk-00010.gz b/disk/chunk-00010.gz new file mode 100644 index 0000000000000000000000000000000000000000..6efb4cc1df0e3d8c90c845a51421801499e81271 --- /dev/null +++ b/disk/chunk-00010.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:93b30caf0a0152bf380fc12203f0d6553428337948914951ebb5767d8c40bd7e +size 1621999 diff --git a/disk/chunk-00011.gz b/disk/chunk-00011.gz new file mode 100644 index 0000000000000000000000000000000000000000..3a3ad376a2743523a3558ee72c53b8815edca9b4 --- /dev/null +++ b/disk/chunk-00011.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f599d45a19d028bd0db1cec18460a6b5c5002a413e63ee20d1e49eeb8e02ab41 +size 1893104 diff --git a/disk/chunk-00012.gz b/disk/chunk-00012.gz new file mode 100644 index 0000000000000000000000000000000000000000..abada2d0ca99d2905b4ebecd17057ce4c8731977 --- /dev/null +++ b/disk/chunk-00012.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:39723989aded0b9398db559c157adb51f2fc52a79ab1fe46356718ac70afcd3e +size 1203806 diff --git a/disk/chunk-00013.gz b/disk/chunk-00013.gz new file mode 100644 index 0000000000000000000000000000000000000000..77c19a19726948056ff78637f736e4da3f72b459 --- /dev/null +++ b/disk/chunk-00013.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fc4d3a1c6e1b8bb401de267455d4b3b6ac5390fd444439bf7dda9b12fdc68632 +size 1559848 diff --git a/disk/chunk-00014.gz b/disk/chunk-00014.gz new file mode 100644 index 0000000000000000000000000000000000000000..eeba813eb54524aeedd3a989143f594a4505018a --- /dev/null +++ b/disk/chunk-00014.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5cfcf5e11a610f9acc469dfe9e50ef6f893761593a01f0c7839817ec03ba63ad +size 1817662 diff --git a/disk/chunk-00015.gz b/disk/chunk-00015.gz new file mode 100644 index 0000000000000000000000000000000000000000..6a918a4900cb00cb145027b12193861e9bc7a78b --- /dev/null +++ b/disk/chunk-00015.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f934df12d78b9f81c452b7a38d992e6148d704cc6bcd8f974ef1d20a914fce3b +size 1445448 diff --git a/disk/chunk-00016.gz b/disk/chunk-00016.gz new file mode 100644 index 0000000000000000000000000000000000000000..20cb575dbda0c005b32057367927ffc4b434eb02 --- /dev/null +++ b/disk/chunk-00016.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:78048e8a712977e2f67cce56e72ab2251573e3fb4418b6a72c9e538624660180 +size 1812087 diff --git a/disk/chunk-00017.gz b/disk/chunk-00017.gz new file mode 100644 index 0000000000000000000000000000000000000000..c5a7ec7839ef26326b64b4ce82af3bd842077c05 --- /dev/null +++ b/disk/chunk-00017.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b80e05c1c80c13e813be7737088cee58fcdb4f9a0630372b0fd01bd7a4fbf8e4 +size 1854604 diff --git a/disk/chunk-00018.gz b/disk/chunk-00018.gz new file mode 100644 index 0000000000000000000000000000000000000000..432f5778d0baa1128e220d0732fc9e61f56aea49 --- /dev/null +++ b/disk/chunk-00018.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:beef50aeb8de5fe87b37ed428a6ce7ecf396420a77e53b5be93c89b71dd3af79 +size 1833966 diff --git a/disk/chunk-00019.gz b/disk/chunk-00019.gz new file mode 100644 index 0000000000000000000000000000000000000000..fa0635888ffa95c46cb0821933fddf13f55aa490 --- /dev/null +++ b/disk/chunk-00019.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f2c87e41f6f6c2559d2157ad8d61fd9cf8ec622fdbea3b8f65b4dfb669201cb8 +size 1088257 diff --git a/disk/chunk-00020.gz b/disk/chunk-00020.gz new file mode 100644 index 0000000000000000000000000000000000000000..4be51e708dd36e8992f20e211b60513aad52fb15 --- /dev/null +++ b/disk/chunk-00020.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:50261100194fb7c7ef714abfcf317d2895d31bfaa7f0ea54e9602088ac850f86 +size 508791 diff --git a/disk/chunk-00021.gz b/disk/chunk-00021.gz new file mode 100644 index 0000000000000000000000000000000000000000..57a04bd3c45b3d11ab4abf71291d3676b85356fb --- /dev/null +++ b/disk/chunk-00021.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cae2a4f52bebff345525cb0769ab931fc7733c48ba7d65d789f40e9443c1854e +size 504198 diff --git a/disk/chunk-00022.gz b/disk/chunk-00022.gz new file mode 100644 index 0000000000000000000000000000000000000000..a48ca760b84b21a88a35774a34469bb36e3a6d89 --- /dev/null +++ b/disk/chunk-00022.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8f25bce9e66cc00f7eecf4797f3c0157b34a66a52a31d2a0c0c33de68fa892c5 +size 661922 diff --git a/disk/chunk-00023.gz b/disk/chunk-00023.gz new file mode 100644 index 0000000000000000000000000000000000000000..80a38e3cf6e4aedbba5c2a703fd21caff5b19e0f --- /dev/null +++ b/disk/chunk-00023.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ea46da59f56997db8dbba9a2648df89bac90892a073d22eed921e4a2485d6c58 +size 750325 diff --git a/disk/chunk-00024.gz b/disk/chunk-00024.gz new file mode 100644 index 0000000000000000000000000000000000000000..985a9912ea71f69803b6e1df963a463a703518a1 --- /dev/null +++ b/disk/chunk-00024.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:449da875bc8cafbbec4646f919b0dd7c4decd59f1e729ad544f49eabc295bb7e +size 773845 diff --git a/disk/chunk-00025.gz b/disk/chunk-00025.gz new file mode 100644 index 0000000000000000000000000000000000000000..b522d606373008b69d4fc35ec72f313775bf6955 --- /dev/null +++ b/disk/chunk-00025.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:114a0a685ee163841c92891af802360d2a54de20d3678db47634cb3871a28224 +size 220784 diff --git a/disk/chunk-00026.gz b/disk/chunk-00026.gz new file mode 100644 index 0000000000000000000000000000000000000000..6d74c9bfc07d7afb471b27a41dc75b299da1aa72 --- /dev/null +++ b/disk/chunk-00026.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:824fbc46232ab90e4003d8b74113f6a01f42e6bf73d048f4866e339b63416c7c +size 2083342 diff --git a/disk/chunk-00027.gz b/disk/chunk-00027.gz new file mode 100644 index 0000000000000000000000000000000000000000..e68f8f17226cdedcfba70a6f1d86beb330720acd --- /dev/null +++ b/disk/chunk-00027.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c4aca0025564261b62700b8f5ee23d8b5d1ec2320c22c79d2f5c808a0f9ead84 +size 1861489 diff --git a/disk/chunk-00028.gz b/disk/chunk-00028.gz new file mode 100644 index 0000000000000000000000000000000000000000..47d74a485fcf944dbc65eff2f4dd2b08b1797243 --- /dev/null +++ b/disk/chunk-00028.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f74822b733696f6bcfa378ab1bcb7e1ba281955e3ce7cdf61a33519a9664bb13 +size 2286309 diff --git a/disk/chunk-00029.gz b/disk/chunk-00029.gz new file mode 100644 index 0000000000000000000000000000000000000000..7f076db50bd55a726998207dbd9e597c837adcc8 --- /dev/null +++ b/disk/chunk-00029.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2f8f2f83c1af0d97a041b94c81f10aa69ffbcf2a52723b46b014daf56aa8de72 +size 2261679 diff --git a/disk/chunk-00030.gz b/disk/chunk-00030.gz new file mode 100644 index 0000000000000000000000000000000000000000..0095c9420118166470de9060b03bfdb6cd98882a --- /dev/null +++ b/disk/chunk-00030.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:263c04c273a188b8b6a2184a7b929eaef7a093ca8ed4c5a06015a2a57c78d0ac +size 987448 diff --git a/disk/chunk-00031.gz b/disk/chunk-00031.gz new file mode 100644 index 0000000000000000000000000000000000000000..adac52905067469df059d77d1eaa2a9cbb216471 --- /dev/null +++ b/disk/chunk-00031.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:039f52db89d3ea9f23b21d089fb213a5455f7c0ac096fd794ba9e04b96292595 +size 1264011 diff --git a/disk/chunk-00032.gz b/disk/chunk-00032.gz new file mode 100644 index 0000000000000000000000000000000000000000..60ffee15c3d73da1e398aa70dbb3b63cc3d56fb1 --- /dev/null +++ b/disk/chunk-00032.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cb436a7a667914174911b6cf427df49aff0aec0cf1c6bfec6d42146fb9cb3e2e +size 784303 diff --git a/disk/chunk-00033.gz b/disk/chunk-00033.gz new file mode 100644 index 0000000000000000000000000000000000000000..1e5933be06c6be2875678e9178bf2210f5a56af4 --- /dev/null +++ b/disk/chunk-00033.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e6d2f66ebd86a84558edb95c0e20c989bf0f41b51def9ba662dc0f1f4ff7f2a5 +size 2201903 diff --git a/disk/chunk-00034.gz b/disk/chunk-00034.gz new file mode 100644 index 0000000000000000000000000000000000000000..c180f447dc6d45a3e33bca4cfc9fc6a6af29b115 --- /dev/null +++ b/disk/chunk-00034.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8d4ac871c818e6b49ccef383d60971646f1e2669dc054b998434e868d3768a61 +size 1809177 diff --git a/disk/chunk-00035.gz b/disk/chunk-00035.gz new file mode 100644 index 0000000000000000000000000000000000000000..ec2bd8975fa35b96aa49d86c3086f2e7f18aff07 --- /dev/null +++ b/disk/chunk-00035.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:aeed66cdfac320c798f2b6780c42ed95f474e6ad6cf643c8e6d6ce15b87bde44 +size 2338491 diff --git a/disk/chunk-00036.gz b/disk/chunk-00036.gz new file mode 100644 index 0000000000000000000000000000000000000000..64f0a2085ffeb959631ebb83f0212e26dee0fd84 --- /dev/null +++ b/disk/chunk-00036.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a6af4d214d314522e863be29aee4f48a07f0534650c900338e71d6d9d794d786 +size 2350830 diff --git a/disk/chunk-00037.gz b/disk/chunk-00037.gz new file mode 100644 index 0000000000000000000000000000000000000000..fc3eb697a5680da58a2e02411c039edc74e6843d --- /dev/null +++ b/disk/chunk-00037.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2bbaf8282465e3163e334a0bcd212f8bc4e325912a80220c34b2a2ee6f4021f2 +size 1099582 diff --git a/disk/chunk-00038.gz b/disk/chunk-00038.gz new file mode 100644 index 0000000000000000000000000000000000000000..041c561cdc01985fb69123e932e40007aab42fb1 --- /dev/null +++ b/disk/chunk-00038.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:be1b86e5ae5c57721ffb61e48b4a501fde106853df9af0ecb81032913a08cfa4 +size 1269573 diff --git a/disk/chunk-00039.gz b/disk/chunk-00039.gz new file mode 100644 index 0000000000000000000000000000000000000000..863a242112d94584a26590c7ba4d76594711ea2f --- /dev/null +++ b/disk/chunk-00039.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7b00ed46297605c5e5844ddad1c39f3a27b3085b1389d2efcfb5ef1355825ce1 +size 987682 diff --git a/disk/chunk-00040.gz b/disk/chunk-00040.gz new file mode 100644 index 0000000000000000000000000000000000000000..a68a7df8d0862e710bcd97a9360a2d4dc05d17ce --- /dev/null +++ b/disk/chunk-00040.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a24f19e74ee148e8092f2bc9457bd8827e1ed94aa1e3f36aa6c101a82017cd32 +size 957286 diff --git a/disk/chunk-00041.gz b/disk/chunk-00041.gz new file mode 100644 index 0000000000000000000000000000000000000000..e914bc2830d74de19966ba10d0a6f5331fff9364 --- /dev/null +++ b/disk/chunk-00041.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0a495e3a78a300a52bafcdf8dd3bfcb88c226a5141cee22029f1254c1ae9b2aa +size 2574133 diff --git a/disk/chunk-00042.gz b/disk/chunk-00042.gz new file mode 100644 index 0000000000000000000000000000000000000000..802603b05ab6752faf16b990881e156973e44130 --- /dev/null +++ b/disk/chunk-00042.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:76e5e36d3a78cda615b239dc3e0b26be941f29fb4512c42f4ebc3022a5fc0291 +size 937963 diff --git a/disk/chunk-00043.gz b/disk/chunk-00043.gz new file mode 100644 index 0000000000000000000000000000000000000000..38d0b240c203abfe5281d650cb27f4024331b449 --- /dev/null +++ b/disk/chunk-00043.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e5443fd65aec225762f0d13c11c59ac4d4efabf578223c3171a5954aa0e187e2 +size 1533398 diff --git a/disk/chunk-00044.gz b/disk/chunk-00044.gz new file mode 100644 index 0000000000000000000000000000000000000000..756a96dac91cb3cebd2cc9331637bc2f82dd61a2 --- /dev/null +++ b/disk/chunk-00044.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f229ac4bc0592c881edd29df43761ccb6555231e350e0c57ac72db04615c7491 +size 2304854 diff --git a/disk/chunk-00045.gz b/disk/chunk-00045.gz new file mode 100644 index 0000000000000000000000000000000000000000..639b75a1e3c74a39a49f174c6dacde27141c314c --- /dev/null +++ b/disk/chunk-00045.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:64a1230fa55911161a595d037cd41e54f19ac364f26fec09c981e0fff75c50d5 +size 1764538 diff --git a/disk/chunk-00046.gz b/disk/chunk-00046.gz new file mode 100644 index 0000000000000000000000000000000000000000..6ae50cef39f0e553dc2adc686287b822fb896221 --- /dev/null +++ b/disk/chunk-00046.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a9721bb80dbd5f13508807227180983bebb869b2c9fb05ddf058eb6d63e87462 +size 2360859 diff --git a/disk/chunk-00047.gz b/disk/chunk-00047.gz new file mode 100644 index 0000000000000000000000000000000000000000..1bb7ea893a9c51a926eea915933320a77e9249d4 --- /dev/null +++ b/disk/chunk-00047.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3559204073efc53723ad0653e860d7224b1f6cc33de9c4bb696628af32123870 +size 1629743 diff --git a/disk/chunk-00048.gz b/disk/chunk-00048.gz new file mode 100644 index 0000000000000000000000000000000000000000..b4d3ce914c86166270082701c1722dc5f641b75e --- /dev/null +++ b/disk/chunk-00048.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:802c3b53e1577b0cee7090bd88008a3ae09176d49e9ab4b034703782a33661c7 +size 1207628 diff --git a/disk/chunk-00049.gz b/disk/chunk-00049.gz new file mode 100644 index 0000000000000000000000000000000000000000..2cb5e1c12727490b61d2b5e13616f48289c38509 --- /dev/null +++ b/disk/chunk-00049.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a77429fa7ce7c954e5c059a027b2a4aa58ec870a16f0ca72ccf2adb03c90e35b +size 1246156 diff --git a/disk/chunk-00050.gz b/disk/chunk-00050.gz new file mode 100644 index 0000000000000000000000000000000000000000..66beff81aa5eee92b20c57e90056e3e09ad85825 --- /dev/null +++ b/disk/chunk-00050.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:61ed6ea8c64a0c69903a0aeadf070d1ca3819983ef0ba7cfba4cd4584d2782ac +size 1995714 diff --git a/disk/chunk-00051.gz b/disk/chunk-00051.gz new file mode 100644 index 0000000000000000000000000000000000000000..b53667eed9c5e352a689d8037bbe6569b36d1a71 --- /dev/null +++ b/disk/chunk-00051.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8624ce39bdb00644557c63268330880ac1a28f7dd5fdbfce7f47f8052a7aace1 +size 1930270 diff --git a/disk/chunk-00052.gz b/disk/chunk-00052.gz new file mode 100644 index 0000000000000000000000000000000000000000..43acf60e7b5a6993960ecadf7662becdc8bad284 --- /dev/null +++ b/disk/chunk-00052.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cf165244a96f504809c39608c53472218399c08c9add18e8e6a7ab14ac2e57ad +size 2016564 diff --git a/disk/chunk-00053.gz b/disk/chunk-00053.gz new file mode 100644 index 0000000000000000000000000000000000000000..3e0616f260680b73946733e3a323dffc2467d871 --- /dev/null +++ b/disk/chunk-00053.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c8cf9855386ceceee45c703d39d304935da86f12b596436d0b949b6e5cef10ce +size 2019434 diff --git a/disk/chunk-00054.gz b/disk/chunk-00054.gz new file mode 100644 index 0000000000000000000000000000000000000000..7bf8221bec91543ac72e58e0b54a8955763b6232 --- /dev/null +++ b/disk/chunk-00054.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f68d2a20d438332c7af862bdd937c8184c774eba1e23e886d3456c976bf98518 +size 1962824 diff --git a/disk/chunk-00055.gz b/disk/chunk-00055.gz new file mode 100644 index 0000000000000000000000000000000000000000..dc60751ef3536cf0c2252938996341f1c670333d --- /dev/null +++ b/disk/chunk-00055.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:53672f8a85577e3f32d47d102f3663b057f2c9606292f592d573e1a7022f7cc8 +size 1925883 diff --git a/disk/chunk-00056.gz b/disk/chunk-00056.gz new file mode 100644 index 0000000000000000000000000000000000000000..ac278442f5d0c7970629aa0dca4f76f851ed76ef --- /dev/null +++ b/disk/chunk-00056.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ad441c4e607a8e2bc366889f04e902e5a5569aa61775e6086179510f70b5a5e2 +size 1580553 diff --git a/disk/chunk-00057.gz b/disk/chunk-00057.gz new file mode 100644 index 0000000000000000000000000000000000000000..1731acea298201f19e28f359df07f0d68051364f --- /dev/null +++ b/disk/chunk-00057.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:14ea5737f98c80b255f6d6317179cee91a0c4157547f4812dbc52aca5863b698 +size 1280553 diff --git a/disk/chunk-00058.gz b/disk/chunk-00058.gz new file mode 100644 index 0000000000000000000000000000000000000000..9bf4aa844dc569ba60e2f74d26f8d512e26ea2ed --- /dev/null +++ b/disk/chunk-00058.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bbd7b3056404781fd87c8fdb9da8d931ac34458b3c38100f3327cd0ab4d169bf +size 1035818 diff --git a/disk/chunk-00059.gz b/disk/chunk-00059.gz new file mode 100644 index 0000000000000000000000000000000000000000..0d288b4358dec632ad3a6f80e4aa0ae734f846fa --- /dev/null +++ b/disk/chunk-00059.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:30e8a64862860950d5a46bc88977629c76fa4e0dfce1dbce53561a72ed5f4368 +size 1713354 diff --git a/disk/chunk-00060.gz b/disk/chunk-00060.gz new file mode 100644 index 0000000000000000000000000000000000000000..e9651abfee50d02d90791af79695c198e0f76125 --- /dev/null +++ b/disk/chunk-00060.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f4cf59d66d9327d3ac6aeb46ac88198e90d76b38028719a1c522414acf42b69f +size 1382679 diff --git a/disk/chunk-00061.gz b/disk/chunk-00061.gz new file mode 100644 index 0000000000000000000000000000000000000000..d3885603475f39f336ff278b63a1a003e79fffab --- /dev/null +++ b/disk/chunk-00061.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:18a82577c24fd2c104146120a9869a82381d13d942b51d7d796883bdefa6d3e4 +size 1666765 diff --git a/disk/chunk-00062.gz b/disk/chunk-00062.gz new file mode 100644 index 0000000000000000000000000000000000000000..4c6f4baa3e897c6c30dc09b1c0e0214af752b2ea --- /dev/null +++ b/disk/chunk-00062.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4bc7073373ed45b731f92fb5c1beae862e0b64d76d5ecda941072d326fcef458 +size 1724835 diff --git a/disk/chunk-00063.gz b/disk/chunk-00063.gz new file mode 100644 index 0000000000000000000000000000000000000000..4a15ff0750a6f16f906d4f5c771fd187eaa49810 --- /dev/null +++ b/disk/chunk-00063.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:849baef0dd759fbc6fd0705c55155a672d91f8e4be57eca9d179f272f9f48fb8 +size 1959086 diff --git a/disk/chunk-00064.gz b/disk/chunk-00064.gz new file mode 100644 index 0000000000000000000000000000000000000000..16c908d24af7d02ae9cdf51f9793d795f15948b7 --- /dev/null +++ b/disk/chunk-00064.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3f8bca9a61ad660367a8f351b70d5a0fbc93e03a0b33d98ab5102b7910fce5c6 +size 1750981 diff --git a/disk/chunk-00065.gz b/disk/chunk-00065.gz new file mode 100644 index 0000000000000000000000000000000000000000..35e39566f27ed91a3ffdcd25cade0592825571d3 --- /dev/null +++ b/disk/chunk-00065.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:622931152c1e44a205c7548735351e95ee2981a369045cb572f911ad714a5e43 +size 1324765 diff --git a/disk/chunk-00066.gz b/disk/chunk-00066.gz new file mode 100644 index 0000000000000000000000000000000000000000..f630639ab5edcbacb25c5ff0355080a4870708d1 --- /dev/null +++ b/disk/chunk-00066.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9ee66c81102e1cdd9b8c5f0195ca523a80a5196f7c297635c290de959ede274d +size 1547480 diff --git a/disk/chunk-00067.gz b/disk/chunk-00067.gz new file mode 100644 index 0000000000000000000000000000000000000000..16aacfcf2e6ecfa19c2cd3edd58a94b62ab95e15 --- /dev/null +++ b/disk/chunk-00067.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0a21bf3390a644e94df6d0fd7151642e0a0a1cb03b10ec4efe68b866284669cd +size 2135242 diff --git a/disk/chunk-00068.gz b/disk/chunk-00068.gz new file mode 100644 index 0000000000000000000000000000000000000000..34d2b0f14d56e1322ffbdebb4988e8841620041a --- /dev/null +++ b/disk/chunk-00068.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e728ef3cfcbf322675416644af3cb342dcccb60dba772e1c1f44e3e31fcf5dae +size 1402298 diff --git a/disk/chunk-00069.gz b/disk/chunk-00069.gz new file mode 100644 index 0000000000000000000000000000000000000000..3b2b9952f6ea5e39fd3d1683feb65d17d0ae8109 --- /dev/null +++ b/disk/chunk-00069.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e338b9aed8e7fd2451a97db877189b9cbdf70448145f30ef1a11bbb906ed730a +size 1403995 diff --git a/disk/chunk-00070.gz b/disk/chunk-00070.gz new file mode 100644 index 0000000000000000000000000000000000000000..d117b9310ddfe9057a3d5f68470a7856c6700cb8 --- /dev/null +++ b/disk/chunk-00070.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:972b994978f9f02225c5cc094118843f5e1b02e79a12f501cdfd096ed6ef28e4 +size 1255272 diff --git a/disk/chunk-00071.gz b/disk/chunk-00071.gz new file mode 100644 index 0000000000000000000000000000000000000000..8c39d2dd58c22ad2020f1e121a15dd5b53e72b02 --- /dev/null +++ b/disk/chunk-00071.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c02579b885c829a95de6ccb27967ccdd0aa0705138a862ebf8e90b99a3d662b5 +size 1843893 diff --git a/disk/chunk-00072.gz b/disk/chunk-00072.gz new file mode 100644 index 0000000000000000000000000000000000000000..00c6a72f5b45b16a97da81c4b5bfee99af1937a6 --- /dev/null +++ b/disk/chunk-00072.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:82e38000852fb168ac8119b45cd85a4df45dc7768e2f01692523a52da6ba6852 +size 1664091 diff --git a/disk/chunk-00073.gz b/disk/chunk-00073.gz new file mode 100644 index 0000000000000000000000000000000000000000..af9242d6700e5741fadc1bd1ad7f4437c5e1e409 --- /dev/null +++ b/disk/chunk-00073.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5bbd27ce8ec48e7d94e106e2d1a0be7b26f17bc47aa619a6434b0e8abb879ad1 +size 1549368 diff --git a/disk/chunk-00074.gz b/disk/chunk-00074.gz new file mode 100644 index 0000000000000000000000000000000000000000..34bd21ec09d125144bb955d88901d4759e50c7e6 --- /dev/null +++ b/disk/chunk-00074.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:79abd3ba9c7cd2fced2eb55c548a3793555c011a7398d9a6d3f5a1545a05739a +size 988179 diff --git a/disk/chunk-00075.gz b/disk/chunk-00075.gz new file mode 100644 index 0000000000000000000000000000000000000000..5c81c706b35f2f9799eab83e09c9873fd99a589f --- /dev/null +++ b/disk/chunk-00075.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:26ec55c7eefe87eea701f381c81c02d68aa1a33d5891fcea52d56c9cb6bcba2e +size 1672083 diff --git a/disk/chunk-00076.gz b/disk/chunk-00076.gz new file mode 100644 index 0000000000000000000000000000000000000000..7c6b034a65150e233e2ed644d7be368c260e42e6 --- /dev/null +++ b/disk/chunk-00076.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:10485f17d267134ce73fad88ff2641d43e64bc6ea646f53cd7b2c19be68ba45f +size 1891938 diff --git a/disk/chunk-00077.gz b/disk/chunk-00077.gz new file mode 100644 index 0000000000000000000000000000000000000000..fb4b045e7fb84ee4d562d9e49da5ff2fd09a6c3c --- /dev/null +++ b/disk/chunk-00077.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9fa8868b508f8df68aa730c5b0611ad268c94ce119c6b82a024fb4ce1761ec90 +size 1771146 diff --git a/disk/chunk-00078.gz b/disk/chunk-00078.gz new file mode 100644 index 0000000000000000000000000000000000000000..ab4dfbeb083a05432a57b08e71887870bfc9a9a7 --- /dev/null +++ b/disk/chunk-00078.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1e0e02990339ac4311d8de1edbf5ca661f6f106cd49ba81b4aac35351f6da2a9 +size 1103660 diff --git a/disk/chunk-00079.gz b/disk/chunk-00079.gz new file mode 100644 index 0000000000000000000000000000000000000000..bee09185fce28350c82d9d8c3e0dc561d9bdae67 --- /dev/null +++ b/disk/chunk-00079.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:49852ef37b617bba119736ce644fc56e2ae875efa8c0d02947f80222e80c1085 +size 949663 diff --git a/disk/chunk-00080.gz b/disk/chunk-00080.gz new file mode 100644 index 0000000000000000000000000000000000000000..49909a2454d191a39d240992f4d8aa7a79fec67b --- /dev/null +++ b/disk/chunk-00080.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:eec4272f9f62d7a6c0c4b65d1295c4361e7f1a20ea3fc7bb5af67d559af1d869 +size 1501023 diff --git a/disk/chunk-00081.gz b/disk/chunk-00081.gz new file mode 100644 index 0000000000000000000000000000000000000000..3ed2cef5db282e34d389967faf7fa550968a8964 --- /dev/null +++ b/disk/chunk-00081.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3a3cd5e84c7cf0f4bcee5b3d97714b49cdf5f555f57d4626d96de11aae8e432f +size 1344308 diff --git a/disk/chunk-00082.gz b/disk/chunk-00082.gz new file mode 100644 index 0000000000000000000000000000000000000000..f244d64b47d3aaca9aaa403d71ef64b2768defce --- /dev/null +++ b/disk/chunk-00082.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:38ab22517d88b78736ff82dff0cb4cd5032422242b6258c60bfea28c0731ceb0 +size 1725027 diff --git a/disk/chunk-00083.gz b/disk/chunk-00083.gz new file mode 100644 index 0000000000000000000000000000000000000000..3c81eee59a0783eb4e860c9beec21e18e499c037 --- /dev/null +++ b/disk/chunk-00083.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:65a0869fb85c69b3e830b71cb1b22839520c70e4859625c2c7923ad5c6ad3357 +size 1564780 diff --git a/disk/chunk-00084.gz b/disk/chunk-00084.gz new file mode 100644 index 0000000000000000000000000000000000000000..5f889cf6cef71f6e6f3ee8aff514cbc1300ebaa6 --- /dev/null +++ b/disk/chunk-00084.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:881703a6433b90728da698af48979d7681fb9dab9a5e2ebd826191966ac81e67 +size 743040 diff --git a/disk/chunk-00085.gz b/disk/chunk-00085.gz new file mode 100644 index 0000000000000000000000000000000000000000..495021dfecc77c9c9cdb9f0feea0837784d83c06 --- /dev/null +++ b/disk/chunk-00085.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:39a00febddbefcec5ab354c0a9bab38c6d3f21ade9660807573667983d9a8c5e +size 770369 diff --git a/disk/chunk-00086.gz b/disk/chunk-00086.gz new file mode 100644 index 0000000000000000000000000000000000000000..46b62b071e15da4b8e2c7b1ef1184b0894144eab --- /dev/null +++ b/disk/chunk-00086.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:73b15ef7d8701d95056f36ccc9ead381901698197c99db696a684c5e0278817a +size 1153194 diff --git a/disk/chunk-00087.gz b/disk/chunk-00087.gz new file mode 100644 index 0000000000000000000000000000000000000000..c4cd30d2e80d8f8a4574dca76c60c37484e2098b --- /dev/null +++ b/disk/chunk-00087.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bc4140c68a30c062c09b56283ab5448fdfb17e9d6183943c4711768a222089a3 +size 1582113 diff --git a/disk/chunk-00088.gz b/disk/chunk-00088.gz new file mode 100644 index 0000000000000000000000000000000000000000..dec63f95c8d2c1877cbcc8cd9633aadc87a285c4 --- /dev/null +++ b/disk/chunk-00088.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5b693cb9c9d1394f6a8f72da29516e67db87cd2dca7e87ba22fe9a73ecacf467 +size 1128687 diff --git a/disk/chunk-00089.gz b/disk/chunk-00089.gz new file mode 100644 index 0000000000000000000000000000000000000000..e86a9d2f8b0f1b2cd6522e60ca4bec12520f9c77 --- /dev/null +++ b/disk/chunk-00089.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5d5eba377b456a336d16b7b91fc8463c324a0fd3be50b837ac0822c38a3d5fa2 +size 586819 diff --git a/disk/chunk-00090.gz b/disk/chunk-00090.gz new file mode 100644 index 0000000000000000000000000000000000000000..ddeab7af7f62822f6aec1b3544a1914f785f70e7 --- /dev/null +++ b/disk/chunk-00090.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9bb05c4e7b667637e6a4c25f7827b4c229cb4007d4777b34def5694cb6568261 +size 1185531 diff --git a/disk/chunk-00091.gz b/disk/chunk-00091.gz new file mode 100644 index 0000000000000000000000000000000000000000..54a67f6d6d82de71da44aac9bf6288bd4c6f7da7 --- /dev/null +++ b/disk/chunk-00091.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:97c1cf52393e9f83a26778fcf6b285ab77287381e3d9f012fcd8b513f789a184 +size 1085565 diff --git a/disk/chunk-00092.gz b/disk/chunk-00092.gz new file mode 100644 index 0000000000000000000000000000000000000000..7e684ec1ef2e00116702dd2487624d9316ec968e --- /dev/null +++ b/disk/chunk-00092.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c2d3d52f03bc676aec2a1be2265551831b03a71814cb76c92ec5750515622a3d +size 1197726 diff --git a/disk/chunk-00093.gz b/disk/chunk-00093.gz new file mode 100644 index 0000000000000000000000000000000000000000..cf0c73166c8f27d2a9d7a5c9ed1a9b2a656df1ea --- /dev/null +++ b/disk/chunk-00093.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2dde1a31ede4884fc037e04d3839d2b31145b59898ef9718a82788cf8a45c8d5 +size 1354124 diff --git a/disk/chunk-00094.gz b/disk/chunk-00094.gz new file mode 100644 index 0000000000000000000000000000000000000000..303d4736700a018aeef30e9b35fc4161df0d4a8a --- /dev/null +++ b/disk/chunk-00094.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7088b3fdafb9b80970cc9581fb132d9768c9c3d7d69e758d5ca6b499ecd52dc9 +size 1220864 diff --git a/disk/chunk-00095.gz b/disk/chunk-00095.gz new file mode 100644 index 0000000000000000000000000000000000000000..bd334dcc4189a644d6f89b9e986b095c0fdaff17 --- /dev/null +++ b/disk/chunk-00095.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b6674369d81c474fd9eec808a56e57ea7b0f462098298d732cb0e1f632c3be34 +size 1398103 diff --git a/disk/chunk-00096.gz b/disk/chunk-00096.gz new file mode 100644 index 0000000000000000000000000000000000000000..3be7be4425d2b2bb3a4161f62f2a147a8682e618 --- /dev/null +++ b/disk/chunk-00096.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cde87f7a78f90ba1b9e9d4331f0955250f42859d6e8874f49dcb769a99349b2e +size 530050 diff --git a/disk/chunk-00097.gz b/disk/chunk-00097.gz new file mode 100644 index 0000000000000000000000000000000000000000..ab259ac45f340ee485f25c80ceb5fbb7f36da65a --- /dev/null +++ b/disk/chunk-00097.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d06e8a6f2a703f1fd386b924a39b0f3bfc1b5b6b8fa0fa5b36cd8fe8ba8c8255 +size 897467 diff --git a/disk/chunk-00098.gz b/disk/chunk-00098.gz new file mode 100644 index 0000000000000000000000000000000000000000..96a6f564525ec63e417191dabff148c929f184c7 --- /dev/null +++ b/disk/chunk-00098.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2c682922232e2da4a1eaca9f3203ceb9ee36823f45468bc92f4abe0c52d9e6dd +size 1077312 diff --git a/disk/chunk-00099.gz b/disk/chunk-00099.gz new file mode 100644 index 0000000000000000000000000000000000000000..473d0626ba4b6b6bca5158f23d82c16576bc2c10 --- /dev/null +++ b/disk/chunk-00099.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7d548f8961eb5aeffdbf363493db019a198dd52d401906daca9df165d8691078 +size 1102903 diff --git a/disk/chunk-00100.gz b/disk/chunk-00100.gz new file mode 100644 index 0000000000000000000000000000000000000000..28495fe1085efa8d67f5286a2e072335442f8464 --- /dev/null +++ b/disk/chunk-00100.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a2efc4763f1be713996715b3f4d818cd10cd9b09dd7faaf853b9e61980b1b083 +size 1036187 diff --git a/disk/chunk-00101.gz b/disk/chunk-00101.gz new file mode 100644 index 0000000000000000000000000000000000000000..211a62c380195c932b8b3c09fe3cce20ccd6dfc9 --- /dev/null +++ b/disk/chunk-00101.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:019fc5d449c7e04e8bc10d48aecbc5dd016a364625b5740d99378045ad77f58e +size 1194144 diff --git a/disk/chunk-00102.gz b/disk/chunk-00102.gz new file mode 100644 index 0000000000000000000000000000000000000000..f18f1b8a34c65beb190dee760c68599ac58eca50 --- /dev/null +++ b/disk/chunk-00102.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:740d61fc60160e0c0b26185a6723def0bf626e22dca9ed2435efac09990ade06 +size 591333 diff --git a/disk/chunk-00103.gz b/disk/chunk-00103.gz new file mode 100644 index 0000000000000000000000000000000000000000..3c397d6ff56c2f76dbd78a638b1fb85b6a3debe5 --- /dev/null +++ b/disk/chunk-00103.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:986aecae8463030da856d77040f9b7ba23909712673b99180fabe689d6c9d84d +size 1785973 diff --git a/disk/chunk-00104.gz b/disk/chunk-00104.gz new file mode 100644 index 0000000000000000000000000000000000000000..6ff1d240610da3ce232ebeee11c8b8661de77451 --- /dev/null +++ b/disk/chunk-00104.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:965d18d7afdb5ca3871dfa0e0ffb81c5437baf5eaf77e30ee0fef5d4e0a04f87 +size 2508827 diff --git a/disk/chunk-00105.gz b/disk/chunk-00105.gz new file mode 100644 index 0000000000000000000000000000000000000000..4ab545acdf9596044cf0ad82c66c7ecf46e5625a --- /dev/null +++ b/disk/chunk-00105.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:698be8930e6345936b2644e2ecb7a87f9ba055388c2d3551d691596bbf1e76bc +size 2512289 diff --git a/disk/chunk-00106.gz b/disk/chunk-00106.gz new file mode 100644 index 0000000000000000000000000000000000000000..7abb9b92944daa774a5d1fcf54c23d35b1973b80 --- /dev/null +++ b/disk/chunk-00106.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b90df8cb87c849da5b971f4bdbd1b99649cfa73d58e939ef44d08a18851e4bdb +size 1368287 diff --git a/disk/chunk-00107.gz b/disk/chunk-00107.gz new file mode 100644 index 0000000000000000000000000000000000000000..7fe9e8dd791b74f652a71cb4ea7ae46ad88f4a59 --- /dev/null +++ b/disk/chunk-00107.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:35ad007df5d3ea2267c5667fb6de8db12bc49d119ac7316d198a4ec9fe25269b +size 828280 diff --git a/disk/chunk-00108.gz b/disk/chunk-00108.gz new file mode 100644 index 0000000000000000000000000000000000000000..54c05e79a631711434e4ccbaf750b1a279538702 --- /dev/null +++ b/disk/chunk-00108.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bb1fd4aec4928b9506a63919058c61d00b01ca344a8156e09d87f96d44043726 +size 855987 diff --git a/disk/chunk-00109.gz b/disk/chunk-00109.gz new file mode 100644 index 0000000000000000000000000000000000000000..b8a27c08466bf7d37c5068b4a8318f04ce054920 --- /dev/null +++ b/disk/chunk-00109.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4b7126adbdf2ae58cac44132fa66af077c52c4f51662566c64e325daf1f70105 +size 881492 diff --git a/disk/chunk-00110.gz b/disk/chunk-00110.gz new file mode 100644 index 0000000000000000000000000000000000000000..ab56a67fc1e2419de91d261adefeccb41d488b5e --- /dev/null +++ b/disk/chunk-00110.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:aae40c828334e50c0f7f6c222bcd1d526c5c96d9ac4bdf3a2774fad05484e326 +size 909130 diff --git a/disk/chunk-00111.gz b/disk/chunk-00111.gz new file mode 100644 index 0000000000000000000000000000000000000000..b236b1a7c005c5108aa3966a0a152f77b946de7c --- /dev/null +++ b/disk/chunk-00111.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d55480f42e67353640857ba7f3e45df458c4e134ddddd77975590258401fd3df +size 646415 diff --git a/disk/chunk-00112.gz b/disk/chunk-00112.gz new file mode 100644 index 0000000000000000000000000000000000000000..dd0ecbd6e6226b7c8c561c65ddfc432bb512cbe7 --- /dev/null +++ b/disk/chunk-00112.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2d88a0dfe4931c233c246c9e703d96277bdf6bf198b90958a6f6e03d1034dda9 +size 1785498 diff --git a/disk/chunk-00113.gz b/disk/chunk-00113.gz new file mode 100644 index 0000000000000000000000000000000000000000..6d055fe5ea91b47d72796d24b82b4e336d7fc782 --- /dev/null +++ b/disk/chunk-00113.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2b09f31987852df3ea143bed9f82af3c9226e6ce14206b2ba368dcd860dbe083 +size 466655 diff --git a/disk/chunk-00114.gz b/disk/chunk-00114.gz new file mode 100644 index 0000000000000000000000000000000000000000..99181a0d740f036dc74dd7f9727069fa43fb423f --- /dev/null +++ b/disk/chunk-00114.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1e586c757185b6b0fa6474609bf2591b05a2e88c115037f32ca80b93fc56fb8e +size 593575 diff --git a/disk/chunk-00115.gz b/disk/chunk-00115.gz new file mode 100644 index 0000000000000000000000000000000000000000..2033a84b6ab835f6710d02d1efedf1c0f7e19cc4 --- /dev/null +++ b/disk/chunk-00115.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ca68b2021ba8754b9c88e4490b05cde7c21a3abc5f28e7bae04ce4fbbc704705 +size 496213 diff --git a/disk/chunk-00116.gz b/disk/chunk-00116.gz new file mode 100644 index 0000000000000000000000000000000000000000..f6b6040685672ad16c8149472ecd8d66237777c3 --- /dev/null +++ b/disk/chunk-00116.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fa0ad2b948aab6a2216a21c805ee4167e9de22594100ee217b5fda7949c6c874 +size 254901 diff --git a/disk/chunk-00128.gz b/disk/chunk-00128.gz new file mode 100644 index 0000000000000000000000000000000000000000..8a33741176dcffaeed3e05ac7ffae52b74fa148b --- /dev/null +++ b/disk/chunk-00128.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:575c084261269efd9f7269291cbe98201a6b395949503e1a83cdd803e7ba68ba +size 4112 diff --git a/disk/chunk-00160.gz b/disk/chunk-00160.gz new file mode 100644 index 0000000000000000000000000000000000000000..33ff6b3c8923c30956365fe05a387f5b35176c58 --- /dev/null +++ b/disk/chunk-00160.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a309ed8d7a0cb667a28ee26947d70c64ca9e15bca2f27774cb08c5124340b4fb +size 4405 diff --git a/disk/chunk-00192.gz b/disk/chunk-00192.gz new file mode 100644 index 0000000000000000000000000000000000000000..8a33741176dcffaeed3e05ac7ffae52b74fa148b --- /dev/null +++ b/disk/chunk-00192.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:575c084261269efd9f7269291cbe98201a6b395949503e1a83cdd803e7ba68ba +size 4112 diff --git a/disk/chunk-00224.gz b/disk/chunk-00224.gz new file mode 100644 index 0000000000000000000000000000000000000000..5ffb783d9efe6089801d8eb1df2fb98c2721c7f9 --- /dev/null +++ b/disk/chunk-00224.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:401085cd0dfc66ecf55b81381001eb520e7e1cfea1d608667ec73620a533f119 +size 4415 diff --git a/disk/manifest.json b/disk/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..f76ed3acfb7004261e3787e7fb8577e584ec8077 --- /dev/null +++ b/disk/manifest.json @@ -0,0 +1 @@ +{"format":1,"size":952107008,"chunkSize":4194304,"chunks":[1027382,1719838,1357969,1802211,1706138,1427457,1677164,1625468,1904995,1911454,1621999,1893104,1203806,1559848,1817662,1445448,1812087,1854604,1833966,1088257,508791,504198,661922,750325,773845,220784,2083342,1861489,2286309,2261679,987448,1264011,784303,2201903,1809177,2338491,2350830,1099582,1269573,987682,957286,2574133,937963,1533398,2304854,1764538,2360859,1629743,1207628,1246156,1995714,1930270,2016564,2019434,1962824,1925883,1580553,1280553,1035818,1713354,1382679,1666765,1724835,1959086,1750981,1324765,1547480,2135242,1402298,1403995,1255272,1843893,1664091,1549368,988179,1672083,1891938,1771146,1103660,949663,1501023,1344308,1725027,1564780,743040,770369,1153194,1582113,1128687,586819,1185531,1085565,1197726,1354124,1220864,1398103,530050,897467,1077312,1102903,1036187,1194144,591333,1785973,2508827,2512289,1368287,828280,855987,881492,909130,646415,1785498,466655,593575,496213,254901,0,0,0,0,0,0,0,0,0,0,0,4112,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,4405,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,4112,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,4415,0,0],"downloadBytes":166142720,"id":"82fa8bcb4fb9d52e"} \ No newline at end of file diff --git a/icon.svg b/icon.svg new file mode 100644 index 0000000000000000000000000000000000000000..4f2e990e3f258ce1b204341189c6541345a6429d --- /dev/null +++ b/icon.svg @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + diff --git a/index.html b/index.html index b0c4b3666032a737f3903db53e6a8a9272483e28..ad8e1e7935cf299586bc7269a1f3e70ad6e722c0 100644 --- a/index.html +++ b/index.html @@ -1,19 +1,209 @@ - - - - - My static Space - - - -
-

Welcome to your static Space!

-

You can modify this app directly by editing index.html in the Files and versions tab.

-

- Also don't forget to check the - Spaces documentation. -

-
- + + + + + LocalWebAgent + + + + + + + + + + +
+
+ + LocalWebAgent + / + LFM3-1.7B + WebGPU +
+
+ Model + Linux + Offline +
+
+ + +
+
+ + + +
+
+
+
+
+

Start a task

+

The agent plans and runs commands on a Debian machine inside this tab. The model and the computer both run on your device, offline.

+
Examples
+
+ + + + +
+
+
+
+ +
+
+ +
+ + + + Enter to send + + +
+
+
+
+
+ + + +
+
+
+ + +
+ debian-10 · i386 + + + + + + +
+
+
+ +
+
+
+ + + + +
+
+

Settings

+ +
+
+ + + + + +
+
+ +
+ Reset Linux filesErase everything created inside the machine. + +
+
+ Remove offline dataDelete the model, disk and files from this browser. + +
+
+
+
+ + + diff --git a/js/agent.js b/js/agent.js new file mode 100644 index 0000000000000000000000000000000000000000..a63657f63a57c5473a6d29a8e099988cc4bfe9c6 --- /dev/null +++ b/js/agent.js @@ -0,0 +1,165 @@ +// The agent harness: an LFM3 tool-calling loop over the Linux VM. +import { parseAssistant, shQuote } from "./toolcalls.js"; +import { TOOLS, systemPrompt } from "./prompts.js"; + +export { TOOLS, systemPrompt }; + +// Sampling for agent steps; tuned with tools/loop-test.mjs (see README). +export const SAMPLING = { temperature: 0.1, topK: 50, repetitionPenalty: 1.1 }; + +const MAX_TOOL_OUTPUT = 4000; + +export function truncateOutput(s, max = MAX_TOOL_OUTPUT) { + if (s.length <= max) return s; + const head = Math.floor(max * 0.35); + const tail = max - head; + return `${s.slice(0, head)}\n... [${s.length - max} characters omitted] ...\n${s.slice(-tail)}`; +} + +export class Agent { + /** + * @param {{llm: import('./llm.js').LLM, vm: import('./vm.js').VM, settings: object, ui: object}} deps + * ui hooks: startTurn(), onToken(view), onToolStart(call) -> handle, onToolEnd(handle, result), + * confirmTool(call) -> Promise, onStats(stats), onPrefill(done,total) + */ + constructor({ llm, vm, settings, ui }) { + this.llm = llm; + this.vm = vm; + this.settings = settings; + this.ui = ui; + this.history = []; + this.running = false; + this.stopRequested = false; + this.lastPromptTokens = 0; + } + + clear() { + this.history = []; + this.llm.resetCache(); + } + + stop() { + this.stopRequested = true; + this.llm.stop(); + if (this.vm.agentBusy) this.vm.interrupt(); + } + + async run(userText) { + if (this.running) throw new Error("Agent is already running"); + this.running = true; + this.stopRequested = false; + this.history.push({ role: "user", content: userText }); + try { + for (let step = 1; step <= this.settings.maxSteps; step++) { + if (this.stopRequested) break; + this.#compact(); + const thinking = this.settings.thinking; + const view = this.ui.startTurn(step); + let raw = ""; + const res = await this.llm.generate( + [{ role: "system", content: systemPrompt() }, ...this.history], + TOOLS, + { thinking, maxNewTokens: this.settings.maxNewTokens, thinkingBudget: this.settings.thinkingBudget, ...SAMPLING }, + (ev) => { + if (ev.type === "token" || ev.type === "replace") { + raw = ev.type === "replace" ? ev.text : raw + ev.text; + view.update(parseAssistant(raw, { thinkingOpen: thinking })); + } else if (ev.type === "prefill") view.prefill(ev.done, ev.total); + }, + ); + this.lastPromptTokens = res.promptTokens + res.genTokens; + this.ui.onStats(res); + const text = res.text; + const parsed = parseAssistant(text, { thinkingOpen: thinking }); + view.update(parsed, true); + if (res.thinkingCut) view.note(res.thinkingCut === "loop" ? "The model's reasoning started repeating, so it was cut short." : "The model's reasoning hit its length limit, so it was cut short."); + + if (res.stopped) { + this.history.push({ role: "assistant", content: "" + (parsed.content || "(stopped by the user)") }); + view.note("Stopped."); + break; + } + // Store exactly what was generated (plus the "" the prompt ended with), + // so the next prompt re-tokenizes to the same prefix and the KV cache is reused. + this.history.push({ role: "assistant", content: (thinking ? "" : "") + text }); + + const calls = parsed.calls.filter((c) => c.complete || !res.hitLimit); + if (!calls.length) { + if (res.hitLimit) view.note("The model hit its output limit for one step."); + break; // final answer + } + for (const call of calls) { + if (this.stopRequested) break; + const result = await this.#runTool(call); + this.history.push({ role: "tool", content: result }); + } + if (step === this.settings.maxSteps) view.note(`Reached the step limit (${this.settings.maxSteps}). Send a message to continue.`); + } + } finally { + this.running = false; + } + } + + async #runTool(call) { + const handle = this.ui.onToolStart(call); + const a = call.arguments; + let result; + try { + if (this.settings.confirmCommands && !(await this.ui.confirmTool(call, handle))) { + result = { text: "The user declined to run this.", exitCode: null, declined: true }; + } else if (call.name === "run_command") { + if (!a.command?.trim()) throw new Error("missing 'command'"); + const timeoutSec = Math.min(600, Math.max(5, parseInt(a.timeout, 10) || this.settings.commandTimeoutSec)); + const r = await this.vm.exec(a.command, { timeoutSec }); + result = { text: formatExec(r, timeoutSec), exitCode: r.exitCode, output: r.output, timedOut: r.timedOut }; + } else if (call.name === "write_file") { + if (!a.path) throw new Error("missing 'path'"); + let content = a.content ?? ""; + if (content && !content.endsWith("\n")) content += "\n"; // the call format strips it + const r = await this.vm.writeFile(a.path, content); + result = { text: formatExec(r), exitCode: r.exitCode, output: r.output }; + } else if (call.name === "read_file") { + if (!a.path) throw new Error("missing 'path'"); + const s = Math.max(1, parseInt(a.start_line, 10) || 1); + const e = Math.max(s, parseInt(a.end_line, 10) || s + 199); + const r = await this.vm.exec(`nl -ba -w4 -s' ' -- ${shQuote(a.path)} | sed -n '${s},${e}p'`); + result = { text: formatExec(r), exitCode: r.exitCode, output: r.output }; + } else { + result = { text: `Unknown tool "${call.name}". Available tools: run_command, write_file, read_file.`, exitCode: null }; + } + } catch (err) { + result = { text: `Tool error: ${err.message}`, exitCode: null, error: true }; + } + this.ui.onToolEnd(handle, result); + return result.text; + } + + // Keep the prompt within budget: shorten old tool outputs first, then drop old turns. + #compact() { + const budget = this.settings.contextBudgetTokens; + const est = () => this.history.reduce((n, m) => n + Math.ceil(m.content.length / 3.2), 900); + if (est() <= budget) return; + const toolIdx = this.history.map((m, i) => (m.role === "tool" ? i : -1)).filter((i) => i >= 0); + for (const i of toolIdx.slice(0, -2)) { + const c = this.history[i].content; + if (c.length > 400) this.history[i] = { role: "tool", content: c.slice(0, 300) + "\n... [older output truncated to save context]" }; + if (est() <= budget) return; + } + // Drop whole old exchanges (keep the latest user message and everything after it). + const lastUser = this.history.findLastIndex((m) => m.role === "user"); + while (est() > budget && lastUser > 0) { + const nextUser = this.history.findIndex((m, i) => i > 0 && m.role === "user"); + if (nextUser <= 0 || nextUser >= this.history.length) break; + this.history.splice(0, nextUser); + if (this.history.findLastIndex((m) => m.role === "user") === 0) break; + } + } +} + +function formatExec(r, timeoutSec) { + if (r.busy) return r.output; + const out = r.output?.length ? truncateOutput(r.output) : "(no output)"; + let head = r.exitCode === null ? "exit code: unknown" : `exit code: ${r.exitCode}`; + if (r.timedOut) head += ` (interrupted after ${timeoutSec}s timeout)`; + return `${head}\n${out}`; +} diff --git a/js/config-defaults.js b/js/config-defaults.js new file mode 100644 index 0000000000000000000000000000000000000000..361127f744b3bb4dce5422dc14b70060b8d0868e --- /dev/null +++ b/js/config-defaults.js @@ -0,0 +1,10 @@ +// Agent defaults. Kept free of browser APIs so Node tests can import it. +export const DEFAULTS = { + thinking: true, + confirmCommands: false, + maxSteps: 16, + commandTimeoutSec: 90, + maxNewTokens: 2048, + thinkingBudget: 1536, + contextBudgetTokens: 14000, +}; diff --git a/js/config.js b/js/config.js new file mode 100644 index 0000000000000000000000000000000000000000..c1ed419d18b18a14634230491bcad38dcea36dd6 --- /dev/null +++ b/js/config.js @@ -0,0 +1,36 @@ +// Central configuration. Everything that pins a version or a location lives here. +export const APP_VERSION = "0.3.0"; + +// --- Language model (loaded from the Hugging Face Hub, cached by transformers.js) --- +export const MODEL_ID = "LiquidAI/LFM3-1.7B-ONNX"; +export const MODEL_DTYPE = "q4f16"; +export const MODEL_DEVICE = "webgpu"; +// Files transformers.js fetches for this model; used to check the offline cache. +export const MODEL_FILES = [ + "config.json", "generation_config.json", "tokenizer.json", "tokenizer_config.json", + `onnx/model_${MODEL_DTYPE}.onnx`, `onnx/model_${MODEL_DTYPE}.onnx_data`, +]; +export const MODEL_DOWNLOAD_BYTES = 1_383_000_000; // approx, for the setup screen +export const hubUrl = (file) => `https://huggingface.co/${MODEL_ID}/resolve/main/${file}`; + +// --- CheerpX (WebVM engine). Proprietary: loaded from Leaning Technologies' CDN, +// never redistributed by this Space. The visitor's browser caches it for offline use. +export const CX_VERSION = "1.4.0"; +export const CX_BASE = `https://cxrtnc.leaningtech.com/${CX_VERSION}/`; +export const CX_FILES = [ + "cx.esm.js", "cx_esm.js", "cheerpOS.js", "cxbridge.js", "workerclock.js", "fail.wasm", + "cxcore.js", "cxcore.wasm", "cxcore-no-return-call.js", "cxcore-no-return-call.wasm", +]; + +// --- Linux disk image (chunked, see image/chunk.py). Defaults to ./disk/ in this Space. +export const DISK_BASE = new URL("./disk/", location.href).href; +// Virtual same-origin URL the service worker serves byte ranges for. +export const DISK_VIRTUAL_URL = new URL("./__vm__/disk.ext2", location.href).href; + +// --- Cache names (must match sw.js) --- +export const CACHE_CX = "lwa-cheerpx-" + CX_VERSION; +export const CACHE_DISK = "lwa-disk"; +export const CACHE_MODEL = "transformers-cache"; // transformers.js default + +// --- Agent defaults (in their own module so Node tests can import them) --- +export { DEFAULTS } from "./config-defaults.js"; diff --git a/js/files.js b/js/files.js new file mode 100644 index 0000000000000000000000000000000000000000..7d0feb6bd72af1564fa3f7a4aed436778b7f68eb --- /dev/null +++ b/js/files.js @@ -0,0 +1,428 @@ +// File viewer for the Linux machine: a directory explorer plus viewers for code, +// text, Markdown, images, audio/video and HTML. Files are read through hidden VM +// processes (vm.listDir / vm.readFile), so nothing shows up in the terminal. +// +// HTML files open as sandboxed previews: the page is bundled with the stylesheets, +// scripts and images it references (inlined as data: URLs) and rendered in an iframe +// with an opaque origin, so it can't touch the app. A small injected shim forwards +// clicks on relative links (opens that file in the viewer) and relative fetch() calls +// (answered with the file's contents) to the app. +import hljs from "../vendor/highlight.min.js"; +import { renderMarkdown } from "./markdown.js"; + +const HOME = "/home/user"; +const MAX_TEXT = 2e6; // larger text files are shown truncated +const MAX_HIGHLIGHT = 4e5; // above this, no syntax highlighting +const MAX_INLINE_ASSET = 15e6; + +const IMAGE = { png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif", webp: "image/webp", bmp: "image/bmp", ico: "image/x-icon", avif: "image/avif", svg: "image/svg+xml" }; +const VIDEO = { mp4: "video/mp4", webm: "video/webm", ogv: "video/ogg", mov: "video/quicktime" }; +const AUDIO = { mp3: "audio/mpeg", wav: "audio/wav", ogg: "audio/ogg", oga: "audio/ogg", m4a: "audio/mp4", flac: "audio/flac" }; +const MIME = { + ...IMAGE, ...VIDEO, ...AUDIO, html: "text/html", htm: "text/html", css: "text/css", js: "text/javascript", mjs: "text/javascript", + json: "application/json", txt: "text/plain", md: "text/markdown", csv: "text/csv", xml: "application/xml", wasm: "application/wasm", + woff: "font/woff", woff2: "font/woff2", ttf: "font/ttf", otf: "font/otf", pdf: "application/pdf", +}; +const LANG = { + py: "python", js: "javascript", mjs: "javascript", cjs: "javascript", jsx: "javascript", ts: "typescript", tsx: "typescript", + json: "json", c: "c", h: "c", cpp: "cpp", cc: "cpp", cxx: "cpp", hpp: "cpp", hh: "cpp", sh: "bash", bash: "bash", zsh: "bash", + css: "css", scss: "scss", less: "less", html: "xml", htm: "xml", xml: "xml", svg: "xml", md: "markdown", markdown: "markdown", + rs: "rust", go: "go", java: "java", kt: "kotlin", rb: "ruby", lua: "lua", sql: "sql", yml: "yaml", yaml: "yaml", toml: "ini", + ini: "ini", cfg: "ini", conf: "ini", php: "php", pl: "perl", r: "r", swift: "swift", diff: "diff", patch: "diff", + makefile: "makefile", mk: "makefile", dockerfile: "dockerfile", cs: "csharp", vim: "vim", tex: "latex", +}; +const TEXTISH = new Set(["txt", "log", "csv", "tsv", "env", "gitignore", "lock", "rst", "service", "list", "sources"]); + +const extOf = (name) => { + const base = name.split("/").pop().toLowerCase(); + if (base === "makefile" || base === "dockerfile") return base; + const i = base.lastIndexOf("."); + return i > 0 ? base.slice(i + 1) : ""; +}; +const kindOf = (name) => { + const e = extOf(name); + if (e === "svg") return "svg"; + if (IMAGE[e]) return "image"; + if (VIDEO[e]) return "video"; + if (AUDIO[e]) return "audio"; + if (e === "html" || e === "htm") return "html"; + if (e === "md" || e === "markdown") return "markdown"; + if (LANG[e] || TEXTISH.has(e)) return "code"; + return "unknown"; +}; +export const dirname = (p) => (p.replace(/\/+$/, "").replace(/\/[^/]*$/, "") || "/"); +export function resolvePath(base, ref) { + const parts = (ref.startsWith("/") ? ref : base + "/" + ref).split("/"); + const out = []; + for (const s of parts) { + if (!s || s === ".") continue; + if (s === "..") out.pop(); else out.push(s); + } + return "/" + out.join("/"); +} +const isRelativeRef = (u) => !!u && !/^([a-z][a-z0-9+.-]*:|\/\/|#)/i.test(u.trim()); +const stripQuery = (u) => u.split(/[?#]/)[0]; +const fmtSize = (n) => (n < 1024 ? `${n} B` : n < 1048576 ? `${(n / 1024).toFixed(1)} KB` : `${(n / 1048576).toFixed(1)} MB`); +const esc = (s) => s.replace(/&/g, "&").replace(//g, ">"); + +function h(tag, attrs = {}, ...kids) { + const el = document.createElement(tag); + for (const [k, v] of Object.entries(attrs)) { + if (k === "class") el.className = v; + else if (k.startsWith("on")) el.addEventListener(k.slice(2), v); + else if (v !== false && v != null) el.setAttribute(k, v === true ? "" : v); + } + for (const kid of kids.flat()) if (kid != null) el.append(kid); + return el; +} +function icon(name) { + const s = document.createElementNS("http://www.w3.org/2000/svg", "svg"); + const u = document.createElementNS("http://www.w3.org/2000/svg", "use"); + u.setAttribute("href", "#i-" + name); + s.append(u); + return s; +} +const iconFor = (entry) => entry.type === "d" ? "folder" : ({ image: "image", svg: "image", html: "globe", code: "file-code", markdown: "file", video: "film", audio: "music" })[kindOf(entry.name)] ?? "file"; + +export class FileBrowser { + /** @param {{vm: import('./vm.js').VM, root: HTMLElement, onOpen?: (path:string)=>void}} opts */ + constructor({ vm, root, onOpen }) { + this.vm = vm; + this.root = root; + this.onOpen = onOpen; + this.dir = HOME; + this.entries = []; + this.current = null; // { path, kind, size, mode: 'preview'|'source' } + this.showHidden = false; + this.objectUrls = []; + this.#build(); + window.addEventListener("message", (e) => this.#onFrameMessage(e)); + } + + #build() { + this.crumbs = h("div", { class: "crumbs" }); + this.list = h("div", { class: "ex-list", role: "listbox", "aria-label": "Files" }); + this.hiddenBtn = h("button", { class: "mini-btn", title: "Show hidden files", "aria-pressed": "false", onclick: () => this.#toggleHidden() }, icon("eye")); + const explorer = h("aside", { class: "explorer" }, + h("div", { class: "ex-head" }, + h("button", { class: "mini-btn", title: "Up one folder", onclick: () => this.navigate(dirname(this.dir)) }, icon("arrow-up")), + h("button", { class: "mini-btn", title: "Home", onclick: () => this.navigate(HOME) }, icon("home")), + h("span", { class: "spacer" }), + this.hiddenBtn, + h("button", { class: "mini-btn", title: "Refresh", onclick: () => this.refresh() }, icon("refresh"))), + this.crumbs, this.list); + + this.vwPath = h("span", { class: "vw-path" }); + this.vwMeta = h("span", { class: "vw-meta" }); + this.modeSeg = h("div", { class: "seg small", hidden: true }, + h("button", { "data-mode": "preview", onclick: () => this.#setMode("preview") }, "Preview"), + h("button", { "data-mode": "source", onclick: () => this.#setMode("source") }, "Source")); + this.vwActions = h("div", { class: "vw-actions", hidden: true }, + this.modeSeg, + h("button", { class: "mini-btn", title: "Reload file", onclick: () => this.current && this.open(this.current.path, { mode: this.current.mode }) }, icon("refresh")), + h("button", { class: "mini-btn", title: "Download", onclick: () => this.#download() }, icon("download"))); + this.vwBody = h("div", { class: "vw-body" }); + this.viewer = h("div", { class: "viewer" }, + h("div", { class: "vw-head" }, this.vwPath, this.vwMeta, h("span", { class: "spacer" }), this.vwActions), + this.vwBody); + this.root.append(explorer, this.viewer); + this.#placeholder("Select a file to view it.", "Code, text, images, audio, video and HTML pages open here."); + } + + #placeholder(title, sub) { + this.vwPath.textContent = ""; + this.vwMeta.textContent = ""; + this.vwActions.hidden = true; + this.vwBody.replaceChildren(h("div", { class: "vw-empty" }, icon("folder-open"), h("div", { class: "vw-empty-title" }, title), sub ? h("div", { class: "vw-empty-sub" }, sub) : null)); + } + + #toggleHidden() { + this.showHidden = !this.showHidden; + this.hiddenBtn.setAttribute("aria-pressed", String(this.showHidden)); + this.#renderList(); + } + + async navigate(dir) { + this.list.classList.add("loading"); + try { + const res = await this.vm.listDir(dir); + this.dir = res.path || dir; + this.entries = res.entries.sort((a, b) => (a.type === "d") !== (b.type === "d") ? (a.type === "d" ? -1 : 1) : a.name.localeCompare(b.name, undefined, { numeric: true })); + this.#renderList(); + } catch (err) { + this.list.replaceChildren(h("div", { class: "ex-error" }, err.message)); + } finally { + this.list.classList.remove("loading"); + } + } + + refresh() { return this.navigate(this.dir); } + + #renderList() { + const parts = this.dir.split("/").filter(Boolean); + this.crumbs.replaceChildren( + h("button", { class: "crumb", onclick: () => this.navigate("/") }, "/"), + ...parts.flatMap((p, i) => [ + i ? h("span", { class: "crumb-sep" }, "/") : null, + h("button", { class: "crumb", onclick: () => this.navigate("/" + parts.slice(0, i + 1).join("/")) }, p), + ]).filter(Boolean), + ); + const shown = this.entries.filter((e) => this.showHidden || !e.name.startsWith(".")); + if (!shown.length) { this.list.replaceChildren(h("div", { class: "ex-empty" }, "Empty folder")); return; } + this.list.replaceChildren(...shown.map((e) => { + const full = resolvePath(this.dir, e.name); + const row = h("button", { class: "ex-item" + (this.current?.path === full ? " active" : "") + (e.name.startsWith(".") ? " dim" : ""), role: "option", title: full }, + icon(iconFor(e)), h("span", { class: "ex-name" }, e.name), e.type === "f" ? h("span", { class: "ex-size" }, fmtSize(e.size)) : null); + row.addEventListener("click", () => (e.type === "d" ? this.navigate(full) : this.open(full))); + return row; + })); + } + + /** Opens a file (absolute path). Also moves the explorer to its folder. */ + async open(path, { mode } = {}) { + const kind = kindOf(path); + const defaultMode = kind === "html" || kind === "markdown" || kind === "svg" ? "preview" : "source"; + this.current = { path, kind, mode: mode ?? defaultMode }; + if (dirname(path) !== this.dir) this.navigate(dirname(path)); else this.#renderList(); + this.onOpen?.(path); + const cut = path.lastIndexOf("/") + 1; + this.vwPath.replaceChildren(h("span", { class: "vw-dir" }, path.slice(0, cut)), h("span", { class: "vw-file" }, path.slice(cut))); + this.vwPath.title = path; + this.vwMeta.textContent = ""; + this.vwActions.hidden = false; + this.modeSeg.hidden = !(kind === "html" || kind === "markdown" || kind === "svg"); + for (const b of this.modeSeg.children) b.setAttribute("aria-pressed", String(b.dataset.mode === this.current.mode)); + this.vwBody.replaceChildren(h("div", { class: "vw-loading" }, h("span", { class: "spinner" }))); + this.#revokeUrls(); + let blob; + try { + blob = await this.vm.readFile(path); + } catch (err) { + if (err.code === "EISDIR") return this.navigate(path); + this.vwBody.replaceChildren(h("div", { class: "vw-empty" }, icon("alert"), h("div", { class: "vw-empty-title" }, "Can't open this file"), h("div", { class: "vw-empty-sub" }, err.message))); + return; + } + if (this.current?.path !== path) return; // another file was opened meanwhile + this.current.blob = blob; + this.current.size = blob.size; + this.vwMeta.textContent = fmtSize(blob.size); + await this.#render(); + } + + #setMode(mode) { + if (!this.current) return; + this.current.mode = mode; + for (const b of this.modeSeg.children) b.setAttribute("aria-pressed", String(b.dataset.mode === mode)); + this.#render(); + } + + async #render() { + const { path, kind, blob, mode } = this.current; + const ext = extOf(path); + const body = this.vwBody; + if ((kind === "image" || (kind === "svg" && mode === "preview"))) { + const url = this.#url(new Blob([blob], { type: IMAGE[ext] })); + const img = h("img", { src: url, alt: path.split("/").pop(), class: "fit" }); + img.addEventListener("load", () => { this.vwMeta.textContent = `${img.naturalWidth} × ${img.naturalHeight} · ${fmtSize(blob.size)}`; }); + img.addEventListener("click", () => img.classList.toggle("fit")); + body.replaceChildren(h("div", { class: "vw-image" }, img)); + return; + } + if (kind === "video" || kind === "audio") { + const url = this.#url(new Blob([blob], { type: (VIDEO[ext] || AUDIO[ext]) })); + body.replaceChildren(h("div", { class: "vw-media" }, h(kind, { src: url, controls: true }))); + return; + } + if (kind === "html" && mode === "preview") return this.#renderHtml(); + if (kind === "markdown" && mode === "preview") { + body.replaceChildren(h("div", { class: "vw-doc md" })); + body.firstChild.innerHTML = renderMarkdown(await blob.slice(0, MAX_TEXT).text()); + return; + } + // text / code / unknown + const head = new Uint8Array(await blob.slice(0, 8000).arrayBuffer()); + if (kind === "unknown" && head.includes(0)) return this.#renderBinary(head); + const truncated = blob.size > MAX_TEXT; + const text = await blob.slice(0, MAX_TEXT).text(); + this.#renderCode(text, LANG[ext] ?? (kind === "unknown" && text.length < 50000 ? null : "plaintext"), truncated); + } + + #renderCode(text, lang, truncated) { + let html; + if (text.length > MAX_HIGHLIGHT || lang === "plaintext") html = esc(text); + else { + try { + html = lang && hljs.getLanguage(lang) ? hljs.highlight(text, { language: lang, ignoreIllegals: true }).value : hljs.highlightAuto(text).value; + } catch { html = esc(text); } + } + const lines = text.endsWith("\n") ? text.split("\n").length - 1 : text.split("\n").length; + const gutter = h("pre", { class: "gutter", "aria-hidden": "true" }); + gutter.textContent = Array.from({ length: Math.max(1, lines) }, (_, i) => i + 1).join("\n"); + const code = h("pre", { class: "code hljs" }); + code.innerHTML = html; + this.vwBody.replaceChildren(h("div", { class: "vw-code" }, gutter, code), + truncated ? h("div", { class: "vw-note" }, `Showing the first ${fmtSize(MAX_TEXT)}.`) : null); + this.vwMeta.textContent = `${lines.toLocaleString()} line${lines === 1 ? "" : "s"} · ${fmtSize(this.current.size)}`; + } + + #renderBinary(head) { + const rows = []; + for (let i = 0; i < Math.min(head.length, 512); i += 16) { + const bytes = [...head.slice(i, i + 16)]; + rows.push(i.toString(16).padStart(8, "0") + " " + bytes.map((b) => b.toString(16).padStart(2, "0")).join(" ").padEnd(48) + " " + + bytes.map((b) => (b >= 32 && b < 127 ? String.fromCharCode(b) : ".")).join("")); + } + this.vwBody.replaceChildren( + h("div", { class: "vw-binary" }, + h("div", { class: "vw-note top" }, `Binary file · ${fmtSize(this.current.size)}. Showing the first ${Math.min(head.length, 512)} bytes.`), + h("pre", { class: "hex" }, rows.join("\n")))); + } + + // ---------- HTML preview ---------- + async #renderHtml() { + const { path, blob } = this.current; + const frame = h("iframe", { + class: "vw-frame", title: "Preview of " + path, + sandbox: "allow-scripts allow-forms allow-modals allow-popups allow-downloads", + referrerpolicy: "no-referrer", + }); + this.vwBody.replaceChildren(h("div", { class: "vw-loading" }, h("span", { class: "spinner" }))); + const srcdoc = await this.#bundleHtml(path, await blob.text()); + if (this.current?.path !== path) return; + frame.srcdoc = srcdoc; + this.frame = frame; + this.frameDir = dirname(path); + this.vwBody.replaceChildren(h("div", { class: "vw-frame-wrap" }, frame)); + } + + async #readAsset(vmPath) { + try { + const b = await this.vm.readFile(vmPath, MAX_INLINE_ASSET); + return b; + } catch { return null; } + } + + async #dataUrl(vmPath) { + const b = await this.#readAsset(vmPath); + if (!b) return null; + const typed = new Blob([b], { type: MIME[extOf(vmPath)] ?? "application/octet-stream" }); + return new Promise((res) => { const r = new FileReader(); r.onload = () => res(r.result); r.onerror = () => res(null); r.readAsDataURL(typed); }); + } + + async #inlineCss(css, baseDir, depth = 0) { + // url(...) references + const refs = new Set(); + css.replace(/url\(\s*(['"]?)([^'")]+)\1\s*\)/g, (_, q, u) => { if (isRelativeRef(u) && !u.startsWith("data:")) refs.add(u); return _; }); + const map = new Map(); + await Promise.all([...refs].map(async (u) => map.set(u, await this.#dataUrl(resolvePath(baseDir, stripQuery(u)))))); + css = css.replace(/url\(\s*(['"]?)([^'")]+)\1\s*\)/g, (m, q, u) => (map.get(u) ? `url("${map.get(u)}")` : m)); + // @import "file.css" + if (depth < 3) { + const imports = [...css.matchAll(/@import\s+(?:url\()?\s*['"]([^'"]+)['"]\s*\)?\s*;/g)]; + for (const m of imports) { + if (!isRelativeRef(m[1])) continue; + const p = resolvePath(baseDir, stripQuery(m[1])); + const b = await this.#readAsset(p); + css = css.replace(m[0], b ? await this.#inlineCss(await b.text(), dirname(p), depth + 1) : ""); + } + } + return css; + } + + async #bundleHtml(path, html) { + const dir = dirname(path); + const doc = new DOMParser().parseFromString(html, "text/html"); + const jobs = []; + for (const link of doc.querySelectorAll('link[rel~="stylesheet"][href]')) { + const href = link.getAttribute("href"); + if (!isRelativeRef(href)) continue; + jobs.push((async () => { + const p = resolvePath(dir, stripQuery(href)); + const b = await this.#readAsset(p); + const style = doc.createElement("style"); + style.textContent = b ? await this.#inlineCss(await b.text(), dirname(p)) : `/* missing: ${href} */`; + link.replaceWith(style); + })()); + } + for (const style of doc.querySelectorAll("style")) jobs.push((async () => { style.textContent = await this.#inlineCss(style.textContent, dir); })()); + for (const s of doc.querySelectorAll("script[src]")) { + const src = s.getAttribute("src"); + if (!isRelativeRef(src)) continue; + jobs.push((async () => { + const b = await this.#readAsset(resolvePath(dir, stripQuery(src))); + s.removeAttribute("src"); + s.textContent = b ? (await b.text()).replace(/<\/script/gi, "<\\/script") : `console.error("LocalWebAgent preview: missing ${src.replace(/"/g, "")}")`; + })()); + } + for (const el of doc.querySelectorAll("img[src], source[src], video[src], audio[src], input[type=image][src], track[src], embed[src], link[rel~=icon][href], video[poster]")) { + for (const attr of ["src", "href", "poster"]) { + const v = el.getAttribute(attr); + if (!v || !isRelativeRef(v) || (attr === "href" && el.tagName !== "LINK")) continue; + jobs.push((async () => { const d = await this.#dataUrl(resolvePath(dir, stripQuery(v))); if (d) el.setAttribute(attr, d); })()); + } + } + for (const el of doc.querySelectorAll("img[srcset], source[srcset]")) el.removeAttribute("srcset"); + for (const el of doc.querySelectorAll("[style]")) jobs.push((async () => el.setAttribute("style", await this.#inlineCss(el.getAttribute("style"), dir)))()); + await Promise.all(jobs); + + const shim = doc.createElement("script"); + shim.textContent = PREVIEW_SHIM; + (doc.head ?? doc.documentElement).prepend(shim); + return "\n" + doc.documentElement.outerHTML; + } + + async #onFrameMessage(e) { + if (!this.frame || e.source !== this.frame.contentWindow) return; + const d = e.data; + if (d?.__lwa === "open" && typeof d.href === "string") { + if (isRelativeRef(d.href)) this.open(resolvePath(this.frameDir, stripQuery(d.href))); + else if (/^https?:/i.test(d.href)) window.open(d.href, "_blank", "noopener"); + } else if (d?.__lwa === "fetch" && typeof d.url === "string") { + const p = resolvePath(this.frameDir, stripQuery(d.url)); + const b = await this.#readAsset(p); + const reply = b + ? { __lwa: "file", id: d.id, body: await b.arrayBuffer(), type: MIME[extOf(p)] ?? "application/octet-stream" } + : { __lwa: "file", id: d.id, status: 404 }; + e.source.postMessage(reply, "*", reply.body ? [reply.body] : []); + } + } + + // ---------- misc ---------- + #url(blob) { const u = URL.createObjectURL(blob); this.objectUrls.push(u); return u; } + #revokeUrls() { for (const u of this.objectUrls) URL.revokeObjectURL(u); this.objectUrls = []; this.frame = null; } + + #download() { + if (!this.current?.blob) return; + const a = h("a", { href: URL.createObjectURL(this.current.blob), download: this.current.path.split("/").pop() }); + document.body.append(a); a.click(); a.remove(); + setTimeout(() => URL.revokeObjectURL(a.href), 10000); + } + + /** Called after the agent wrote a file: refresh the listing and the open file if it changed. */ + noteChanged(path) { + if (dirname(path) === this.dir) this.refresh(); + if (this.current?.path === path) this.open(path, { mode: this.current.mode }); + } +} + +// Runs inside the sandboxed preview (opaque origin). Relative links and fetch() calls +// are forwarded to the app, which answers from the Linux machine's files. +const PREVIEW_SHIM = `(() => { + const rel = (u) => typeof u === "string" && u.trim() && !/^([a-z][a-z0-9+.-]*:|\\/\\/|#)/i.test(u.trim()); + let seq = 0; const pending = new Map(); + addEventListener("message", (e) => { + const d = e.data; if (e.source !== parent || !d || d.__lwa !== "file") return; + const p = pending.get(d.id); if (!p) return; pending.delete(d.id); + p(d.body ? new Response(d.body, { status: 200, headers: { "Content-Type": d.type } }) : new Response("Not found", { status: 404 })); + }); + const nativeFetch = window.fetch.bind(window); + window.fetch = (input, init) => { + if (rel(input)) return new Promise((resolve) => { const id = ++seq; pending.set(id, resolve); parent.postMessage({ __lwa: "fetch", id, url: input }, "*"); }); + return nativeFetch(input, init); + }; + document.addEventListener("click", (e) => { + const a = e.target.closest && e.target.closest("a[href]"); if (!a) return; + const href = a.getAttribute("href"); if (!href || href.startsWith("#") || /^javascript:/i.test(href)) return; + e.preventDefault(); parent.postMessage({ __lwa: "open", href }, "*"); + }, true); +})();`; diff --git a/js/llm-engine.js b/js/llm-engine.js new file mode 100644 index 0000000000000000000000000000000000000000..6b88479872dbd9d880a70fa0a0c1c1cfe15955c3 --- /dev/null +++ b/js/llm-engine.js @@ -0,0 +1,211 @@ +// LFM3 generation engine, independent of where it runs. The browser worker passes +// in the transformers.js web build; tools/agent-e2e.mjs passes the Node build so the +// exact same logic can be tested off-GPU. +// +// Generation = chunked prefill (LiquidAI: "on WebGPU ... prefill in chunks of at most +// 256 tokens") followed by transformers.js generate(). The KV/conv cache is kept +// between calls: if the next prompt starts with exactly the tokens already in the +// cache (the usual case inside one agent run), only the new tokens are prefilled. + +const PREFILL_CHUNK = 256; +const LOOP_WINDOW = 40; // a verbatim repeat of this many tokens while thinking = a loop +const LOOP_MIN_TOKENS = 160; +const THINK_CLOSE = { + loop: "\n\nI am going in circles. I'll stop deliberating and take the next concrete step.\n\n", + budget: "\n\nI have thought about this enough. Time to act.\n\n", +}; + +export function createEngine(tf) { + const { AutoTokenizer, AutoModelForCausalLM, DynamicCache, Tensor, TextStreamer, InterruptableStoppingCriteria, StoppingCriteria } = tf; + let tokenizer = null; + let model = null; + let cached = null; // { tokens: number[], cache: DynamicCache } + const stopper = new InterruptableStoppingCriteria(); + let stopRequested = false; + + let thinkEndId = -1; + + // Stops generation while the model is still inside if it starts repeating + // itself verbatim or exceeds the thinking budget. Inactive once appears. + class ThinkingGuard extends StoppingCriteria { + constructor(promptLen, budget) { + super(); + this.promptLen = promptLen; + this.budget = budget; + this.scanned = promptLen; + this.closed = false; + this.reason = null; + this.cutAt = -1; + } + _call(input_ids) { + if (this.closed) return [false]; + if (this.reason) return [true]; + const ids = input_ids[0]; + for (let i = this.scanned; i < ids.length; i++) { + if (Number(ids[i]) === thinkEndId) { this.closed = true; return [false]; } + } + this.scanned = ids.length; + const len = ids.length - this.promptLen; + if (len >= this.budget) { this.reason = "budget"; this.cutAt = len; return [true]; } + if (len >= LOOP_MIN_TOKENS && len % 8 === 0) { + const g = ids.slice(this.promptLen).map(Number); + const tailStart = g.length - LOOP_WINDOW; + outer: for (let s = 0; s + LOOP_WINDOW <= tailStart; s++) { + for (let k = 0; k < LOOP_WINDOW; k++) if (g[s + k] !== g[tailStart + k]) continue outer; + this.reason = "loop"; + this.cutAt = tailStart; // keep one copy of the repeated passage + return [true]; + } + } + return [false]; + } + } + + const int64 = (arr, dims) => new Tensor("int64", BigInt64Array.from(arr, BigInt), dims); + const ones = (n) => new Tensor("int64", new BigInt64Array(n).fill(1n), [1, n]); + + async function load(modelId, { dtype, device, progress_callback, onStatus } = {}) { + tokenizer = await AutoTokenizer.from_pretrained(modelId, { progress_callback }); + onStatus?.("Downloading / loading model weights"); + model = await AutoModelForCausalLM.from_pretrained(modelId, { dtype, device, progress_callback }); + const te = tokenizer.encode("", { add_special_tokens: false }); + thinkEndId = te.length === 1 ? te[0] : -1; + // The LFM3 ONNX graph takes `logits_to_keep` (rank-1 int64). transformers.js only + // fills `num_logits_to_keep`, so inject it on every forward pass. + const forward = model.forward.bind(model); + model.forward = (inputs) => forward({ ...inputs, logits_to_keep: inputs.logits_to_keep ?? int64([1], [1]) }); + onStatus?.("Warming up"); + await generate([{ role: "user", content: "Hi" }], [], { thinking: false, maxNewTokens: 1 }); + await reset(); + } + + async function reset() { + if (cached) { const c = cached; cached = null; await c.cache.dispose(); } + } + + function stop() { stopRequested = true; stopper.interrupt(); } + + function promptTokens(messages, tools, thinking) { + const out = tokenizer.apply_chat_template(messages, { + tools: tools?.length ? tools : undefined, + add_generation_prompt: true, + tokenize: true, + return_tensor: false, + return_dict: false, + enable_thinking: thinking, + }); + return Array.isArray(out[0]) ? out[0] : out; + } + + /** + * emit({type:'token', text}) / emit({type:'prefill', done, total}) / + * emit({type:'replace', text}) when the thinking guard rewrites the output so far. + * options.thinkingBudget: max thinking tokens (0 disables the guard). + */ + async function generate(messages, tools, options = {}, emit = null) { + try { + const guard = options.thinking && options.thinkingBudget !== 0 && thinkEndId >= 0; + let r = await run(messages, tools, options, emit, "", guard); + if (r.thinkingCut && !r.stopped) { + // Close the thinking ourselves and let the model continue from there. + const prefix = r.text + THINK_CLOSE[r.thinkingCut]; + emit?.({ type: "replace", text: prefix }); + const r2 = await run(messages, tools, options, emit, prefix, false); + r = { + ...r2, + text: prefix + r2.text, + genTokens: r.genTokens + r2.genTokens, + genMs: r.genMs + r2.genMs, + prefillMs: r.prefillMs + r2.prefillMs, + thinkingCut: r.thinkingCut, + }; + } + return r; + } catch (err) { + await reset().catch(() => {}); // the cache may be half-updated + throw err; + } + } + + async function run(messages, tools, options, emit, assistantPrefix, useGuard) { + stopRequested = false; + stopper.reset(); + const ids = promptTokens(messages, tools, options.thinking); + if (assistantPrefix) ids.push(...tokenizer.encode(assistantPrefix, { add_special_tokens: false })); + const n = ids.length; + + let start = 0; + if (cached && cached.tokens.length < n && cached.tokens.every((t, i) => t === ids[i])) { + start = cached.tokens.length; + } else { + await reset(); + cached = { tokens: [], cache: new DynamicCache() }; + } + const cache = cached.cache; + + // Chunked prefill of everything except the last prompt token. + const tPrefill = performance.now(); + let pos = start; + while (pos < n - 1) { + if (stopRequested) break; + const end = Math.min(pos + PREFILL_CHUNK, n - 1); + const out = await model.forward({ + input_ids: int64(ids.slice(pos, end), [1, end - pos]), + attention_mask: ones(end), + past_key_values: cache, + }); + const entries = {}; + for (const k in out) { + if (k.startsWith("present")) entries[k.replace("present_conv", "past_conv").replace("present", "past_key_values")] = out[k]; + } + cache.update(entries); + out.logits?.dispose?.(); + pos = end; + cached.tokens = ids.slice(0, pos); + emit?.({ type: "prefill", done: pos - start, total: n - 1 - start }); + } + const prefillMs = performance.now() - tPrefill; + const base = { promptTokens: n, reused: start, newPrefill: pos - start, prefillMs }; + if (stopRequested) return { ...base, text: "", stopped: true, genTokens: 0, genMs: 0, hitLimit: false }; + + const streamer = emit ? new TextStreamer(tokenizer, { + skip_prompt: true, + skip_special_tokens: true, + callback_function: (text) => emit({ type: "token", text }), + }) : null; + const maxNew = options.maxNewTokens ?? 2048; + const guard = useGuard ? new ThinkingGuard(n, options.thinkingBudget ?? 1536) : null; + const tGen = performance.now(); + const res = await model.generate({ + input_ids: int64(ids, [1, n]), + attention_mask: ones(n), + past_key_values: cache, + max_new_tokens: maxNew, + do_sample: (options.temperature ?? 0) > 0, + temperature: options.temperature ?? 0.1, + top_k: options.topK ?? 50, + top_p: options.topP ?? 1.0, + repetition_penalty: options.repetitionPenalty ?? 1.1, + stopping_criteria: guard ? [stopper, guard] : stopper, + streamer, + return_dict_in_generate: true, + }); + const genMs = performance.now() - tGen; + const seq = res.sequences.tolist()[0].map(Number); + cached.tokens = seq.slice(0, seq.length - 1); // the cache holds all but the last sampled token + let gen = seq.slice(n); + const thinkingCut = guard?.reason ?? null; + if (thinkingCut) gen = gen.slice(0, guard.cutAt); + return { + ...base, + thinkingCut, + text: tokenizer.decode(gen, { skip_special_tokens: true }), + stopped: stopRequested, + genTokens: gen.length, + genMs, + hitLimit: gen.length >= maxNew, + }; + } + + return { load, generate, stop, reset }; +} diff --git a/js/llm-worker.js b/js/llm-worker.js new file mode 100644 index 0000000000000000000000000000000000000000..1df7fad1220004abc65ea293f6a0653b2361bdec --- /dev/null +++ b/js/llm-worker.js @@ -0,0 +1,50 @@ +// Web Worker that owns LFM3-1.7B, running on WebGPU via transformers.js + onnxruntime-web. +// The generation logic lives in llm-engine.js (shared with the Node test harness). +import * as tf from "../vendor/transformers.min.js"; +import { createEngine } from "./llm-engine.js"; + +tf.env.allowLocalModels = false; +tf.env.backends.onnx.wasm.wasmPaths = { + mjs: new URL("../vendor/ort/ort-wasm-simd-threaded.asyncify.mjs", import.meta.url).href, + wasm: new URL("../vendor/ort/ort-wasm-simd-threaded.asyncify.wasm", import.meta.url).href, +}; + +const engine = createEngine(tf); +const post = (msg) => self.postMessage(msg); + +self.onmessage = async ({ data }) => { + try { + if (data.type === "load") await load(data); + else if (data.type === "generate") { + const t0 = performance.now(); + const result = await engine.generate(data.messages, data.tools, data.options, (ev) => post({ ...ev, id: data.id })); + post({ type: "done", id: data.id, ...result, totalMs: performance.now() - t0 }); + } else if (data.type === "stop") engine.stop(); + else if (data.type === "reset") await engine.reset(); + } catch (err) { + post({ type: "error", id: data.id, message: String(err?.message ?? err), stack: err?.stack }); + } +}; + +async function load({ modelId, dtype, device }) { + if (device === "webgpu") { + const adapter = await navigator.gpu?.requestAdapter({ powerPreference: "high-performance" }); + if (!adapter) throw new Error("WebGPU is not available in this browser. Use a recent desktop Chrome or Edge."); + if (dtype.includes("f16") && !adapter.features.has("shader-f16")) { + throw new Error("This GPU/browser lacks WebGPU 'shader-f16' support, which the q4f16 model needs."); + } + const info = adapter.info ?? {}; + post({ type: "gpu", vendor: info.vendor, architecture: info.architecture, description: info.description }); + } + await engine.load(modelId, { + dtype, + device, + progress_callback: (p) => { + if (p.status === "progress" || p.status === "done" || p.status === "initiate") { + post({ type: "progress", file: p.file, loaded: p.loaded ?? 0, total: p.total ?? 0, status: p.status }); + } + }, + onStatus: (text) => post({ type: "status", text }), + }); + post({ type: "ready" }); +} diff --git a/js/llm.js b/js/llm.js new file mode 100644 index 0000000000000000000000000000000000000000..50ca17b06c6a1450172c4da5f68bc3240eefaeed --- /dev/null +++ b/js/llm.js @@ -0,0 +1,71 @@ +// Main-thread client for the model worker. +import { MODEL_ID, MODEL_DTYPE, MODEL_DEVICE } from "./config.js"; + +export class LLM { + constructor() { + this.worker = new Worker(new URL("./llm-worker.js", import.meta.url), { type: "module" }); + this.pending = new Map(); + this.nextId = 1; + this.ready = false; + this.onProgress = null; // ({file, loaded, total, status}) + this.onStatus = null; // (text) + this.onGpu = null; // (info) + this.worker.onmessage = ({ data }) => this.#onMessage(data); + this.worker.onerror = (e) => this.#fail(new Error(e.message || "Model worker crashed")); + } + + load() { + this.loading ??= new Promise((resolve, reject) => { + this.pending.set("load", { resolve, reject }); + this.worker.postMessage({ type: "load", modelId: MODEL_ID, dtype: MODEL_DTYPE, device: MODEL_DEVICE }); + }); + return this.loading; + } + + /** Streams tokens to onEvent({type:'token'|'prefill', ...}); resolves with stats + full text. */ + generate(messages, tools, options, onEvent) { + const id = this.nextId++; + return new Promise((resolve, reject) => { + this.pending.set(id, { resolve, reject, onEvent }); + this.worker.postMessage({ type: "generate", id, messages, tools, options }); + }); + } + + stop() { this.worker.postMessage({ type: "stop" }); } + resetCache() { this.worker.postMessage({ type: "reset" }); } + + #fail(err) { + for (const p of this.pending.values()) p.reject(err); + this.pending.clear(); + } + + #onMessage(m) { + switch (m.type) { + case "progress": this.onProgress?.(m); break; + case "status": this.onStatus?.(m.text); break; + case "gpu": this.onGpu?.(m); break; + case "ready": + this.ready = true; + this.pending.get("load")?.resolve(); + this.pending.delete("load"); + break; + case "token": + case "prefill": + this.pending.get(m.id)?.onEvent?.(m); + break; + case "done": + this.pending.get(m.id)?.resolve(m); + this.pending.delete(m.id); + break; + case "error": { + const err = new Error(m.message); + const key = m.id ?? "load"; + const p = this.pending.get(key) ?? this.pending.get("load"); + if (p) { p.reject(err); this.pending.delete(key); } + else console.error("model worker:", m.message, m.stack); + if (!this.ready) this.loading = null; // allow retry + break; + } + } + } +} diff --git a/js/main.js b/js/main.js new file mode 100644 index 0000000000000000000000000000000000000000..3316c28e8fba1bc596442b64aae99f5bcd1cd9f4 --- /dev/null +++ b/js/main.js @@ -0,0 +1,549 @@ +import { DEFAULTS, MODEL_DOWNLOAD_BYTES, MODEL_ID, MODEL_DEVICE, APP_VERSION } from "./config.js"; +import * as setup from "./setup.js"; +import { LLM } from "./llm.js"; +import { VM } from "./vm.js"; +import { Agent } from "./agent.js"; +import { renderMarkdown } from "./markdown.js"; +import { FileBrowser } from "./files.js"; + +// ---------- helpers ---------- +const $ = (s, el = document) => el.querySelector(s); +const h = (tag, attrs = {}, ...kids) => { + const el = document.createElement(tag); + for (const [k, v] of Object.entries(attrs)) { + if (k === "class") el.className = v; + else if (k.startsWith("on")) el.addEventListener(k.slice(2), v); + else if (v !== false && v != null) el.setAttribute(k, v === true ? "" : v); + } + for (const kid of kids.flat()) if (kid != null) el.append(kid); + return el; +}; +const SVG_NS = "http://www.w3.org/2000/svg"; +const icon = (name, cls) => { + const s = document.createElementNS(SVG_NS, "svg"); + if (cls) s.setAttribute("class", cls); + const u = document.createElementNS(SVG_NS, "use"); + u.setAttribute("href", "#i-" + name); + s.append(u); + return s; +}; +const fmtBytes = (n) => (n >= 1e9 ? (n / 1e9).toFixed(2) + " GB" : n >= 1e6 ? Math.round(n / 1e6) + " MB" : Math.round(n / 1e3) + " KB"); +const fmtSecs = (ms) => (ms < 1000 ? `${Math.max(0.1, ms / 1000).toFixed(1)}s` : ms < 60000 ? `${(ms / 1000).toFixed(1)}s` : `${Math.floor(ms / 60000)}m ${Math.round((ms % 60000) / 1000)}s`); +const plural = (n, w) => `${n} ${w}${n === 1 ? "" : "s"}`; + +// ---------- settings ---------- +const settings = { ...DEFAULTS }; +try { Object.assign(settings, JSON.parse(localStorage.getItem("lwa-settings") || "{}")); } catch {} +const saveSettings = () => { try { localStorage.setItem("lwa-settings", JSON.stringify(settings)); } catch {} }; + +// ---------- status ---------- +function status(name, state, text) { + const el = $(`[data-status="${name}"]`); + el.dataset.state = state; + $(".status-text", el).textContent = text; + el.title = text; +} + +const llm = new LLM(); +const vm = new VM(); +let agent = null; +let diskManifest = null; +let vmReady = false; +let files = null; + +// ---------- boot ---------- +async function init() { + $("#version").textContent = "v" + APP_VERSION; + $("#model-name").textContent = MODEL_ID.split("/")[1].replace("-ONNX", ""); + $("#gpu-name").textContent = MODEL_DEVICE === "webgpu" ? "WebGPU" : MODEL_DEVICE; + $("#model-size").textContent = fmtBytes(MODEL_DOWNLOAD_BYTES); + syncToggles(); + + const checks = await environmentChecks(); + renderChecks(checks); + if (!checks.isolated.ok || !checks.sw.ok) return showSetup(false); + + try { await setup.ensureServiceWorker(); } + catch (err) { checks.sw = { ok: false, text: err.message }; renderChecks(checks); return showSetup(false); } + + const [cx, disk, model] = await Promise.all([setup.cheerpxStatus(), setup.installedDisk(), setup.modelStatus()]); + diskManifest = disk; + const installed = { cx: cx.ready, disk: !!disk, model: model.ready }; + for (const k of Object.keys(installed)) if (installed[k]) setRow(k, 1, "Installed"); + const all = installed.cx && installed.disk && installed.model; + status("offline", all ? "ok" : "warn", all ? "Available offline" : "Not installed"); + + if (all && checks.gpu.ok) start(); + else showSetup(checks.gpu.ok); +} + +async function environmentChecks() { + const c = {}; + c.isolated = crossOriginIsolated + ? { ok: true, text: "Cross-origin isolation" } + : { ok: false, text: window.top !== window ? "The embedded view can't run the VM. Open the app in its own tab." : "Cross-origin isolation is off (COOP/COEP headers missing)" }; + c.sw = "serviceWorker" in navigator ? { ok: true, text: "Offline storage" } : { ok: false, text: "Offline storage unavailable (private window?)" }; + if (MODEL_DEVICE !== "webgpu") c.gpu = { ok: true, warn: true, text: `Model runs on ${MODEL_DEVICE} (slow; for testing)` }; + else if (!navigator.gpu) c.gpu = { ok: false, text: "WebGPU unavailable. Use desktop Chrome or Edge." }; + else { + try { + const a = await navigator.gpu.requestAdapter({ powerPreference: "high-performance" }); + if (!a) c.gpu = { ok: false, text: "No WebGPU adapter found" }; + else if (!a.features.has("shader-f16")) c.gpu = { ok: false, text: "This GPU lacks WebGPU shader-f16 support" }; + else c.gpu = { ok: true, text: "WebGPU with f16 shaders" + (a.info?.vendor ? ` · ${a.info.vendor}` : "") }; + } catch (e) { c.gpu = { ok: false, text: "WebGPU error: " + e.message }; } + } + const est = await setup.storageEstimate(); + const free = est ? est.quota - est.usage : null; + c.storage = free == null ? { ok: true, text: "Storage space unknown" } + : free > 2.2e9 ? { ok: true, text: `${fmtBytes(free)} of browser storage available` } + : { ok: true, warn: true, text: `Only ${fmtBytes(free)} of browser storage available; 2.2 GB needed` }; + return c; +} + +function renderChecks(c) { + $("#checks").replaceChildren(...Object.values(c).map((x) => { + const cls = !x.ok ? "bad" : x.warn ? "warn" : "ok"; + return h("li", { class: cls }, icon(cls === "ok" ? "check" : "x"), h("span", {}, x.text)); + })); + if (!c.isolated.ok && window.top !== window) { + $("#checks").append(h("li", {}, h("a", { href: location.href, target: "_blank", rel: "noopener", class: "btn small" }, "Open in a new tab"))); + } +} + +function setRow(k, frac, text) { + const row = $(`[data-row="${k}"]`); + row.dataset.state = frac >= 1 ? "done" : frac > 0 ? "busy" : "todo"; + $("progress", row).value = frac; + $(".row-state", row).textContent = text; +} + +function showSetup(canInstall) { + $("#setup").hidden = false; + const btn = $("#install"); + btn.disabled = !canInstall || !navigator.onLine; + if (!navigator.onLine) $("#setup-note").textContent = "You're offline. Connect once to install; after that it works without internet."; + btn.onclick = install; +} + +async function install() { + const btn = $("#install"); + const note = $("#setup-note"); + btn.disabled = true; + btn.textContent = "Installing"; + note.className = "note"; + note.textContent = "Keep this tab open. Interrupted downloads resume where they left off."; + await setup.requestPersistence(); + try { + const cxTask = setup.cheerpxStatus() + .then((s) => s.ready || setup.downloadCheerpX((f) => setRow("cx", f, Math.round(f * 100) + "%"))) + .then(() => setRow("cx", 1, "Installed")); + const diskTask = (async () => { + const remote = await setup.fetchRemoteManifest(); + if (diskManifest?.id === remote.id) return setRow("disk", 1, "Installed"); + $("#disk-size").textContent = fmtBytes(remote.downloadBytes); + diskManifest = await setup.downloadDisk((d, t) => setRow("disk", d / t, `${Math.round((d / t) * 100)}%`)); + setRow("disk", 1, "Installed"); + })(); + const modelTask = loadModel((f, text) => setRow("model", f, text)).then(() => setRow("model", 1, "Installed")); + await Promise.all([cxTask, diskTask, modelTask]); + status("offline", "ok", "Available offline"); + start(); + } catch (err) { + console.error(err); + note.className = "note error"; + note.textContent = "Installation failed: " + err.message; + btn.disabled = false; + btn.textContent = "Retry"; + } +} + +// Aggregates transformers.js per-file progress into one number. +function loadModel(onProgress) { + const files = new Map(); + llm.onProgress = (p) => { + if (!p.file) return; + const prev = files.get(p.file); + files.set(p.file, { loaded: p.status === "done" ? (prev?.total ?? p.loaded) : p.loaded, total: p.total || prev?.total || 0 }); + let loaded = 0, total = 0; + for (const f of files.values()) { loaded += f.loaded; total += f.total; } + total = Math.max(total, MODEL_DOWNLOAD_BYTES); + const frac = Math.min(0.99, loaded / total); + onProgress?.(frac, `${fmtBytes(loaded)} of ${fmtBytes(total)}`); + status("model", "busy", `Loading ${Math.round(frac * 100)}%`); + }; + llm.onStatus = (t) => { + const warm = t.includes("Warming"); + status("model", "busy", warm ? "Compiling GPU kernels" : "Loading"); + onProgress?.(0.99, warm ? "Compiling GPU kernels" : "Loading"); + }; + llm.onGpu = (g) => { if (g.vendor) $("#gpu-name").title = [g.vendor, g.architecture, g.description].filter(Boolean).join(" · "); }; + status("model", "busy", "Loading"); + return llm.load().then( + () => status("model", "ok", "Model ready"), + (err) => { status("model", "bad", "Model failed"); throw err; }, + ); +} + +// Only one tab may run the VM: two VMs writing the same saved disk corrupt it. +function acquireVmLock() { + if (!navigator.locks) return Promise.resolve(true); + return new Promise((resolve) => { + navigator.locks.request("lwa-vm", { ifAvailable: true }, (lock) => { + resolve(!!lock); + return lock ? new Promise(() => {}) : null; // held for the page's lifetime + }); + }); +} + +async function start() { + $("#setup").hidden = true; + if (!(await acquireVmLock())) { + status("vm", "bad", "Open in another tab"); + addNotice("LocalWebAgent is already running in another tab. Close it and reload this one; two copies at once would damage the machine's files.", "warn"); + return; + } + vm.mountTerminal($("#terminal")); + vm.onActivity = (busy) => { $("#cpu-led").dataset.on = busy ? "1" : "0"; }; + agent = new Agent({ llm, vm, settings, ui: chatUI }); + setComposerEnabled(); + + const vmTask = (async () => { + status("vm", "busy", "Booting"); + try { + diskManifest ??= await setup.installedDisk(); + await vm.boot({ diskId: diskManifest.id, onStatus: (t) => t !== "Ready" && status("vm", "busy", t) }); + vmReady = true; + status("vm", "ok", "Linux running"); + files = new FileBrowser({ vm, root: $("#files") }); + if (sideView === "files") files.navigate("/home/user"); + } catch (err) { + console.error(err); + status("vm", "bad", "Linux failed"); + vm.term?.writeln("\r\n\x1b[31mFailed to start Linux: " + err.message + "\x1b[0m"); + } + setComposerEnabled(); + })(); + const modelTask = llm.ready ? Promise.resolve() : loadModel().catch((err) => { + console.error(err); + addNotice("The model failed to load: " + err.message, "error"); + }); + await Promise.all([vmTask, modelTask]); + setComposerEnabled(); +} + +// ---------- conversation rendering ---------- +const thread = () => $("#messages"); +const scroller = () => $("#scroller"); +function scrollChat(force) { + const el = scroller(); + if (force || el.scrollHeight - el.scrollTop - el.clientHeight < 140) el.scrollTop = el.scrollHeight; +} +function addNotice(text, kind = "") { + $("#empty")?.remove(); + thread().append(h("div", { class: `notice center ${kind}` }, text)); + scrollChat(true); +} + +let currentRun = null; // { el, t0, steps, genTokens, genMs } + +const chatUI = { + startTurn(step) { + const stepEl = h("div", { class: "step" }); + const rTime = h("span", { class: "r-time" }); + const rLabel = h("span", { class: "r-label" }, "Reasoning"); + const reasoning = h("details", { class: "reasoning", hidden: true }, + h("summary", {}, icon("chevron"), rLabel, rTime), h("div", { class: "r-body" })); + const body = h("div", { class: "md" }); + const statusText = h("span", {}, step === 1 ? "Reading the task" : "Reading the result"); + const live = h("div", { class: "run-status" }, h("span", { class: "spinner" }), statusText); + stepEl.append(reasoning, body, live); + currentRun.el.append(stepEl); + scrollChat(true); + + let thinkStart = 0, thinkMs = 0, timer = null; + const tick = () => { rTime.textContent = ` · ${fmtSecs(performance.now() - thinkStart)}`; }; + return { + prefill(done, total) { statusText.textContent = `Reading ${total.toLocaleString()} tokens · ${Math.round((done / total) * 100)}%`; }, + update(p, final) { + if (p.thinking) { + if (!thinkStart) { thinkStart = performance.now(); timer = setInterval(tick, 200); } + reasoning.hidden = false; + $(".r-body", reasoning).textContent = p.thinking; + if (p.thinkingDone && !thinkMs) { + thinkMs = performance.now() - thinkStart; + clearInterval(timer); + rLabel.textContent = "Reasoned"; + rTime.textContent = ` for ${fmtSecs(thinkMs)}`; + } + } + body.innerHTML = p.content ? renderMarkdown(p.content) : ""; + const preparing = p.calls.find((c) => !c.complete); + statusText.textContent = p.thinking && !p.thinkingDone ? "Reasoning" + : preparing ? `Preparing ${TOOL_VERB[preparing.name]?.toLowerCase() ?? preparing.name}` + : p.calls.length ? "Running" : "Writing"; + if (final) { + clearInterval(timer); + if (thinkStart && !thinkMs) { rLabel.textContent = "Reasoned"; rTime.textContent = ` for ${fmtSecs(performance.now() - thinkStart)}`; } + live.remove(); + } + scrollChat(); + }, + note(text) { stepEl.append(h("div", { class: "notice" }, text)); scrollChat(); }, + }; + }, + + onToolStart(call) { + const a = call.arguments; + const verb = TOOL_VERB[call.name] ?? call.name; + const target = call.name === "run_command" ? firstLine(a.command ?? "") : a.path ?? ""; + const t0 = performance.now(); + const statusEl = h("span", { class: "t-status" }, "running"); + const timeEl = h("span", {}); + const head = h("button", { class: "tool-head", type: "button" }, + icon("chevron", "chev"), icon(TOOL_ICON[call.name] ?? "terminal"), + h("span", { class: "tool-label" }, call.name === "run_command" ? null : h("span", { class: "verb" }, verb), target), + h("span", { class: "tool-meta" }, timeEl, statusEl, h("span", { class: "dot" }))); + const bodyEl = h("div", { class: "tool-body" }); + if (call.name === "run_command" && (a.command ?? "").includes("\n")) bodyEl.append(h("pre", {}, a.command)); + if (call.name === "write_file") { + const content = a.content ?? ""; + bodyEl.append(h("div", { class: "sub" }, `${plural(content.replace(/\n$/, "").split("\n").length, "line")}`), h("pre", {}, content)); + } + const card = h("div", { class: "tool", "data-state": "running" }, head, bodyEl); + head.addEventListener("click", () => card.classList.toggle("open")); + card._t0 = t0; card._status = statusEl; card._time = timeEl; card._body = bodyEl; card._name = call.name; + currentRun.el.lastElementChild.append(card); + scrollChat(); + return card; + }, + + onToolEnd(card, r) { + const state = r.declined ? "declined" : r.error ? "error" : r.timedOut ? "timeout" : r.exitCode === 0 ? "ok" : r.exitCode === null ? "unknown" : "fail"; + card.dataset.state = state; + card._status.textContent = r.declined ? "skipped" : r.error ? "error" : r.timedOut ? "timed out" : r.exitCode === null ? "done" : `exit ${r.exitCode}`; + card._time.textContent = fmtSecs(performance.now() - card._t0); + const out = (r.error ? r.text : r.output ?? "").trim(); + if (card._name !== "write_file" && !r.declined) { + const lines = out ? out.split("\n").length : 0; + card._body.append(h("div", { class: "sub" }, out ? plural(lines, "line") + " of output" : "No output")); + if (out) card._body.append(h("pre", {}, out.length > 20000 ? out.slice(0, 20000) + "\n…" : out)); + if (out && lines <= 10 && card._name === "run_command") card.classList.add("open"); + } + if (state === "fail" || state === "error" || state === "timeout") card.classList.add("open"); + const written = card._name === "write_file" && state === "ok" ? / to (\/.*)$/m.exec(r.output ?? "")?.[1] : null; + if (written) { + const openBtn = h("button", { class: "tool-open", type: "button", title: "Open in the file viewer" }, icon("open"), "Open"); + openBtn.addEventListener("click", (e) => { e.stopPropagation(); openFile(written); }); + $(".tool-meta", card).prepend(openBtn); + files?.noteChanged(written); + if (sideView !== "files") $("#files-badge").hidden = false; + } else if (card._name === "run_command" && sideView === "files") files?.refresh(); + scrollChat(); + }, + + confirmTool(call, card) { + card.classList.add("open"); + return new Promise((resolve) => { + const bar = h("div", { class: "confirm" }, + h("span", {}, call.name === "write_file" ? "Write this file?" : "Run this command?"), + h("button", { class: "btn small", type: "button", onclick: () => { bar.remove(); resolve(false); } }, "Skip"), + h("button", { class: "btn small primary", type: "button", onclick: () => { bar.remove(); resolve(true); } }, "Run")); + card.append(bar); + scrollChat(true); + }); + }, + + onStats(s) { + currentRun.steps++; + currentRun.genTokens += s.genTokens; + currentRun.genMs += s.genMs; + const tps = s.genTokens / Math.max(0.001, s.genMs / 1000); + status("model", "ok", `${tps.toFixed(0)} tok/s`); + const used = s.promptTokens + s.genTokens; + $("#ctx").textContent = `${used.toLocaleString()} / ${settings.contextBudgetTokens.toLocaleString()} tokens`; + }, +}; + +const TOOL_VERB = { run_command: "Run", write_file: "Write", read_file: "Read" }; +const TOOL_ICON = { run_command: "terminal", write_file: "file-pen", read_file: "file" }; +const firstLine = (s) => { const l = s.trim().split("\n"); return l[0] + (l.length > 1 ? " …" : ""); }; + +function setComposerEnabled() { + const ready = llm.ready && vmReady; + const running = !!agent?.running; + $("#prompt").disabled = !ready; + $("#send").hidden = running; + $("#stop").hidden = !running; + $("#send").disabled = !ready; + $("#prompt").placeholder = ready ? "Describe a task for the agent" : !llm.ready ? "Loading the model…" : "Starting Linux…"; +} + +async function send(text) { + text = text.trim(); + if (!text || !agent || agent.running) return; + $("#empty")?.remove(); + thread().append(h("div", { class: "msg user" }, text)); + currentRun = { el: h("div", { class: "msg agent" }), t0: performance.now(), steps: 0, genTokens: 0, genMs: 0 }; + thread().append(currentRun.el); + scrollChat(true); + $("#prompt").value = ""; + autoGrow(); + const run = currentRun; + const p = agent.run(text); + setComposerEnabled(); + try { + await p; + } catch (err) { + console.error(err); + run.el.querySelectorAll(".run-status").forEach((el) => el.remove()); + run.el.append(h("div", { class: "notice error" }, "Error: " + err.message)); + } finally { + const tps = run.genTokens / Math.max(0.001, run.genMs / 1000); + run.el.append(h("div", { class: "run-foot" }, + [plural(run.steps, "step"), fmtSecs(performance.now() - run.t0), run.genTokens ? `${tps.toFixed(0)} tok/s` : null].filter(Boolean).join(" · "))); + setComposerEnabled(); + scrollChat(); + $("#prompt").focus(); + } +} + +function autoGrow() { + const t = $("#prompt"); + t.style.height = "auto"; + t.style.height = Math.min(220, t.scrollHeight) + "px"; +} + +function newConversation() { + if (agent?.running) return; + agent?.clear(); + $("#ctx").textContent = ""; + thread().replaceChildren(); + $("#prompt").focus(); +} + +// ---------- composer toggles ---------- +function syncToggles() { + $("#tog-thinking").setAttribute("aria-pressed", String(!!settings.thinking)); + $("#tog-confirm").setAttribute("aria-pressed", String(!!settings.confirmCommands)); +} +$("#tog-thinking").addEventListener("click", () => { settings.thinking = !settings.thinking; saveSettings(); syncToggles(); }); +$("#tog-confirm").addEventListener("click", () => { settings.confirmCommands = !settings.confirmCommands; saveSettings(); syncToggles(); }); + +// ---------- side pane: terminal / files ---------- +let sideView = "term"; +function setSideView(view) { + sideView = view; + const side = $(".side"); + side.dataset.view = view; + $(".view-term").hidden = view !== "term"; + $(".view-files").hidden = view !== "files"; + for (const b of document.querySelectorAll("[data-view]")) b.setAttribute("aria-selected", String(b.dataset.view === view)); + if (view === "files") { + $("#files-badge").hidden = true; + if (files && !files.entries.length) files.navigate(files.dir); + } else setTimeout(() => { try { vm.fit?.fit(); } catch {} }, 30); +} +function openFile(path) { + if (!files) return; + if (window.matchMedia("(max-width: 900px)").matches) selectTab("files"); + setSideView("files"); + files.open(path); +} +for (const b of document.querySelectorAll("[data-view]")) b.addEventListener("click", () => setSideView(b.dataset.view)); +$("#side-max").addEventListener("click", () => { + const on = document.body.classList.toggle("side-max"); + $("#side-max").setAttribute("aria-pressed", String(on)); + $("#side-max").title = on ? "Restore" : "Maximize"; + $("#side-max use").setAttribute("href", on ? "#i-minimize" : "#i-maximize"); + setTimeout(() => { try { vm.fit?.fit(); } catch {} }, 30); +}); +document.addEventListener("keydown", (e) => { if (e.key === "Escape" && document.body.classList.contains("side-max") && !$("#settings").open) $("#side-max").click(); }); + +// ---------- resizable split ---------- +(() => { + const ws = $("#workspace"); + const sp = $("#splitter"); + try { const w = localStorage.getItem("lwa-split"); if (w) ws.style.setProperty("--left", w); } catch {} + const setFrac = (frac) => { + const v = `${(Math.min(0.75, Math.max(0.25, frac)) * 100).toFixed(1)}%`; + ws.style.setProperty("--left", v); + try { localStorage.setItem("lwa-split", v); } catch {} + }; + sp.addEventListener("pointerdown", (e) => { + sp.setPointerCapture(e.pointerId); + sp.classList.add("dragging"); + document.body.classList.add("resizing"); + const rect = ws.getBoundingClientRect(); + const move = (ev) => setFrac((ev.clientX - rect.left) / rect.width); + const up = () => { + sp.classList.remove("dragging"); + document.body.classList.remove("resizing"); + sp.removeEventListener("pointermove", move); + try { vm.fit?.fit(); } catch {} + }; + sp.addEventListener("pointermove", move); + sp.addEventListener("pointerup", up, { once: true }); + }); + sp.addEventListener("keydown", (e) => { + if (e.key !== "ArrowLeft" && e.key !== "ArrowRight") return; + const cur = parseFloat(getComputedStyle(ws).getPropertyValue("--left")) / 100 || 0.46; + setFrac(cur + (e.key === "ArrowLeft" ? -0.02 : 0.02)); + }); +})(); + +// ---------- wiring ---------- +$("#composer").addEventListener("submit", (e) => { e.preventDefault(); send($("#prompt").value); }); +$("#prompt").addEventListener("keydown", (e) => { + if (e.key === "Enter" && !e.shiftKey && !e.isComposing) { e.preventDefault(); send($("#prompt").value); } +}); +$("#prompt").addEventListener("input", autoGrow); +$("#stop").addEventListener("click", () => agent?.stop()); +for (const b of document.querySelectorAll("[data-suggest]")) b.addEventListener("click", () => send(b.textContent)); +$("#ctrl-c").addEventListener("click", () => { vm.interrupt(); vm.term?.focus(); }); +$("#term-clear").addEventListener("click", () => { vm.term?.clear(); vm.term?.focus(); }); +$("#new-chat").addEventListener("click", newConversation); + +function selectTab(name) { + document.body.dataset.tab = name; + for (const t of document.querySelectorAll("[data-tab]")) t.setAttribute("aria-selected", String(t.dataset.tab === name)); + if (name === "term" || name === "files") setSideView(name); + if (name === "term") setTimeout(() => { try { vm.term?.focus(); } catch {} }, 50); +} +for (const tab of document.querySelectorAll("[data-tab]")) tab.addEventListener("click", () => selectTab(tab.dataset.tab)); + +const dlg = $("#settings"); +$("#open-settings").addEventListener("click", () => { + $("#set-thinking").checked = settings.thinking; + $("#set-confirm").checked = settings.confirmCommands; + $("#set-steps").value = settings.maxSteps; + $("#set-timeout").value = settings.commandTimeoutSec; + dlg.showModal(); +}); +dlg.addEventListener("close", () => { + settings.thinking = $("#set-thinking").checked; + settings.confirmCommands = $("#set-confirm").checked; + settings.maxSteps = Math.min(50, Math.max(1, Number($("#set-steps").value) || DEFAULTS.maxSteps)); + settings.commandTimeoutSec = Math.min(600, Math.max(5, Number($("#set-timeout").value) || DEFAULTS.commandTimeoutSec)); + saveSettings(); + syncToggles(); +}); +dlg.addEventListener("click", (e) => { if (e.target === dlg) dlg.close(); }); // click on backdrop +$("#reset-vm").addEventListener("click", async () => { + if (!confirm("Erase all files and changes made inside the Linux machine? The page will reload.")) return; + if (vm.overlayName) await setup.resetVmStorage(vm.overlayName); + location.reload(); +}); +$("#uninstall").addEventListener("click", async () => { + if (!confirm("Remove the model, the Linux disk and all saved files from this browser? Reinstalling needs an internet connection.")) return; + await setup.uninstallAll(); + location.reload(); +}); + +window.addEventListener("online", () => { if (!$("#setup").hidden) showSetup(true); }); +document.body.dataset.tab = "chat"; +$(".side").dataset.view = "term"; +init().catch((err) => { + console.error(err); + addNotice("Startup error: " + err.message, "error"); +}); diff --git a/js/markdown.js b/js/markdown.js new file mode 100644 index 0000000000000000000000000000000000000000..45ea63609b2fb892e61e0336419504b1fde4184a --- /dev/null +++ b/js/markdown.js @@ -0,0 +1,52 @@ +// Tiny, safe Markdown subset for agent replies: fenced code, inline code, bold, +// italics, headings, lists, links (text only, never navigates), paragraphs. +const esc = (s) => s.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); + +function inline(s) { + const codes = []; + s = s.replace(/`([^`\n]+)`/g, (_, c) => { codes.push(c); return `\u0000${codes.length - 1}\u0000`; }); + s = esc(s) + .replace(/\*\*([^*\n]+)\*\*/g, "$1") + .replace(/(^|[^*\w])\*([^*\n]+)\*(?!\w)/g, "$1$2") + .replace(/\[([^\]\n]+)\]\(([^)\s]+)\)/g, '$1'); + return s.replace(/\u0000(\d+)\u0000/g, (_, i) => `${esc(codes[Number(i)])}`); +} + +export function renderMarkdown(src) { + const out = []; + const lines = src.replace(/\r/g, "").split("\n"); + let i = 0; + let para = []; + const flush = () => { if (para.length) { out.push(`

${inline(para.join("\n")).replace(/\n/g, "
")}

`); para = []; } }; + while (i < lines.length) { + const line = lines[i]; + const fence = /^\s*```(\S*)/.exec(line); + if (fence) { + flush(); + const body = []; + i++; + while (i < lines.length && !/^\s*```/.test(lines[i])) body.push(lines[i++]); + i++; + out.push(`
${esc(body.join("\n"))}
`); + continue; + } + const h = /^(#{1,4})\s+(.*)$/.exec(line); + if (h) { flush(); out.push(`${inline(h[2])}`); i++; continue; } + if (/^\s*([-*+]|\d+[.)])\s+/.test(line)) { + flush(); + const ordered = /^\s*\d+[.)]/.test(line); + const items = []; + while (i < lines.length && /^\s*([-*+]|\d+[.)])\s+/.test(lines[i])) { + items.push(`
  • ${inline(lines[i].replace(/^\s*([-*+]|\d+[.)])\s+/, ""))}
  • `); + i++; + } + out.push(ordered ? `
      ${items.join("")}
    ` : ``); + continue; + } + if (!line.trim()) { flush(); i++; continue; } + para.push(line); + i++; + } + flush(); + return out.join(""); +} diff --git a/js/prompts.js b/js/prompts.js new file mode 100644 index 0000000000000000000000000000000000000000..27447d746e59e8a42d109964ce6926240edad1ef --- /dev/null +++ b/js/prompts.js @@ -0,0 +1,67 @@ +// System prompt and tool definitions for the agent (no browser dependencies, so tests can import it). + +export const TOOLS = [ + { + type: "function", + function: { + name: "run_command", + description: "Run a bash command on the Linux machine and get its output and exit code. The shell keeps its working directory and environment between calls. Commands get no stdin, so never start interactive programs.", + parameters: { + type: "object", + properties: { + command: { type: "string", description: "The bash command(s) to run." }, + timeout: { type: "integer", description: "Seconds before the command is interrupted (default 90, max 600)." }, + }, + required: ["command"], + }, + }, + }, + { + type: "function", + function: { + name: "write_file", + description: "Create or overwrite a text file with the given content. Parent directories are created. Use this instead of echo/heredocs or editors.", + parameters: { + type: "object", + properties: { + path: { type: "string", description: "File path, absolute or relative to the current directory." }, + content: { type: "string", description: "The complete file content." }, + }, + required: ["path", "content"], + }, + }, + }, + { + type: "function", + function: { + name: "read_file", + description: "Read a text file, with line numbers.", + parameters: { + type: "object", + properties: { + path: { type: "string", description: "File path." }, + start_line: { type: "integer", description: "First line to show (default 1)." }, + end_line: { type: "integer", description: "Last line to show (default start_line + 199)." }, + }, + required: ["path"], + }, + }, + }, +]; + +export function systemPrompt() { + return `You are LocalWebAgent, an AI agent that runs entirely inside the user's web browser. You operate a real Linux computer through tools. + +The computer: +- Debian 10, 32-bit x86, running in the browser. It has NO internet access: never try to download or install anything (no pip install, apt, curl, wget, git clone of remote repos). +- You are user "user" with home /home/user. Files persist between sessions. +- Installed: bash, coreutils, python3 (3.7, standard library only), gcc, g++, make, node (v10), git, sqlite3, jq, lua5.3, bc, zip/unzip, tar. +- The CPU is emulated and its floating-point math can be slightly off (for example 25**0.5 gives 4.999...). Prefer integer arithmetic: use i * i <= n instead of n**0.5 or math.sqrt. + +How to work: +1. Think briefly, then call one tool and read its result before deciding the next step. +2. Use write_file to create or change files. Never open editors (vim, nano) or other interactive programs. +3. Check your work: run the program or test the result before saying it is done. +4. When the task is complete, stop calling tools and reply with a short summary of what you did and the result. +5. If the user is just chatting or asks something that needs no computer, answer directly without tools.`; +} diff --git a/js/setup.js b/js/setup.js new file mode 100644 index 0000000000000000000000000000000000000000..852fe720d56aca19468e4d8245ed95e01dfc4b58 --- /dev/null +++ b/js/setup.js @@ -0,0 +1,153 @@ +// One-time online setup + offline status. Everything ends up in this origin's +// Cache Storage: the app shell and CheerpX (via sw.js), the disk image chunks +// (stored decompressed by downloadDisk), and the model (by transformers.js). +import { + CX_BASE, CX_FILES, CACHE_CX, CACHE_DISK, CACHE_MODEL, DISK_BASE, MODEL_FILES, hubUrl, +} from "./config.js"; + +const scopeUrl = (p) => new URL(p, document.baseURI).href; +const MANIFEST_KEY = () => scopeUrl("__vm__/manifest.json"); +const chunkKey = (i) => scopeUrl("__vm__/chunk/" + i); + +/** Registers sw.js and makes sure this page is controlled by it (reloads once on first visit). */ +export async function ensureServiceWorker() { + if (!("serviceWorker" in navigator)) { + throw new Error("Service workers are unavailable here (private window or unsupported browser), so offline mode can't work."); + } + const reg = await navigator.serviceWorker.register("./sw.js", { scope: "./" }); + if (!navigator.serviceWorker.controller) { + await navigator.serviceWorker.ready; + if (!sessionStorage.getItem("lwa-sw-reload")) { + sessionStorage.setItem("lwa-sw-reload", "1"); + location.reload(); + await new Promise(() => {}); // wait for the reload + } + } + sessionStorage.removeItem("lwa-sw-reload"); + return reg; +} + +export async function requestPersistence() { + try { return await navigator.storage?.persist?.(); } catch { return false; } +} + +export async function storageEstimate() { + try { return await navigator.storage.estimate(); } catch { return null; } +} + +// ---------- status ---------- +export async function cheerpxStatus() { + const cache = await caches.open(CACHE_CX); + const have = await Promise.all(CX_FILES.map((f) => cache.match(CX_BASE + f))); + return { ready: have.every(Boolean), have: have.filter(Boolean).length, total: CX_FILES.length }; +} + +export async function installedDisk() { + const cache = await caches.open(CACHE_DISK); + const res = await cache.match(MANIFEST_KEY()); + return res ? res.json() : null; +} + +export async function modelStatus() { + const cache = await caches.open(CACHE_MODEL); + const have = await Promise.all(MODEL_FILES.map((f) => cache.match(hubUrl(f)))); + return { ready: have.every(Boolean) }; +} + +export async function fetchRemoteManifest() { + const res = await fetch(DISK_BASE + "manifest.json", { cache: "no-store" }); + if (!res.ok) throw new Error(`disk manifest: HTTP ${res.status}`); + return res.json(); +} + +// ---------- downloads ---------- +export async function downloadCheerpX(onProgress) { + let done = 0; + for (const f of CX_FILES) { + // Goes through sw.js, which stores it in the CheerpX cache. + const res = await fetch(CX_BASE + f, { mode: "cors" }); + if (!res.ok && res.status !== 204) throw new Error(`CheerpX ${f}: HTTP ${res.status}`); + await res.arrayBuffer(); + onProgress?.(++done / CX_FILES.length); + } +} + +/** + * Downloads the chunked disk image. Resumable: chunks already stored are skipped. + * The manifest is written last, so its presence means the image is complete. + */ +export async function downloadDisk(onProgress, { concurrency = 4 } = {}) { + const manifest = await fetchRemoteManifest(); + const cache = await caches.open(CACHE_DISK); + const old = await installedDisk(); + if (old && old.id !== manifest.id) { + await caches.delete(CACHE_DISK); // different image: start clean + } + const disk = await caches.open(CACHE_DISK); + const todo = []; + let doneBytes = 0; + for (let i = 0; i < manifest.chunks.length; i++) { + if (!manifest.chunks[i]) continue; + if (await disk.match(chunkKey(i))) doneBytes += manifest.chunks[i]; + else todo.push(i); + } + const total = manifest.downloadBytes; + onProgress?.(doneBytes, total); + + let next = 0; + async function worker() { + while (next < todo.length) { + const i = todo[next++]; + const name = `chunk-${String(i).padStart(5, "0")}.gz`; + let attempt = 0; + for (;;) { + try { + const res = await fetch(DISK_BASE + name, { cache: "no-store" }); + if (!res.ok) throw new Error(`${name}: HTTP ${res.status}`); + const raw = await gunzipIfNeeded(new Uint8Array(await res.arrayBuffer())); + await disk.put(chunkKey(i), new Response(raw, { headers: { "Content-Type": "application/octet-stream" } })); + doneBytes += manifest.chunks[i]; + onProgress?.(doneBytes, total); + break; + } catch (err) { + if (++attempt >= 4) throw err; + await new Promise((r) => setTimeout(r, 1000 * attempt)); + } + } + } + } + await Promise.all(Array.from({ length: concurrency }, worker)); + await cache.put(MANIFEST_KEY(), new Response(JSON.stringify(manifest), { headers: { "Content-Type": "application/json" } })); + navigator.serviceWorker.controller?.postMessage({ type: "disk-updated" }); + return manifest; +} + +async function gunzipIfNeeded(bytes) { + // Some servers transparently decode .gz; only decompress real gzip data. + if (bytes[0] !== 0x1f || bytes[1] !== 0x8b) return bytes; + const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream("gzip")); + return new Uint8Array(await new Response(stream).arrayBuffer()); +} + +function deleteDb(name) { + return new Promise((resolve) => { + const req = indexedDB.deleteDatabase(name); + req.onsuccess = req.onerror = req.onblocked = () => resolve(); + }); +} + +/** Wipes the VM's saved changes. CheerpX names the IndexedDB database "cjFS_//". */ +export async function resetVmStorage(overlayName) { + const dbs = (await indexedDB.databases?.()) ?? []; + const names = dbs.map((d) => d.name).filter((n) => n?.includes(overlayName)); + for (const n of names.length ? names : ["cjFS_/" + overlayName + "/"]) await deleteDb(n); +} + +/** Removes everything this app stored (model, disk, CheerpX, VM files). */ +export async function uninstallAll() { + for (const k of await caches.keys()) { + if (k.startsWith("lwa-") || k === CACHE_MODEL || k.startsWith("transformers")) await caches.delete(k); + } + const dbs = (await indexedDB.databases?.()) ?? []; + for (const db of dbs) if (db.name?.includes("lwa-")) await deleteDb(db.name); +} diff --git a/js/toolcalls.js b/js/toolcalls.js new file mode 100644 index 0000000000000000000000000000000000000000..abab0514f8ed6405d4c6e167e8839d3fbaf21f41 --- /dev/null +++ b/js/toolcalls.js @@ -0,0 +1,50 @@ +// Parses LFM3 assistant output: +// [thinking][visible text]\n\n\nV\n\n\n +// `text` is what the model generated after the prompt, which (with thinking on) +// already ended in "", so the opening tag is usually absent. + +const CALL_RE = /\s*\n]+)>([\s\S]*?)(?:<\/function>\s*(?:<\/tool_call>|$)|$)/g; +const PARAM_RE = /\n]+)>\n?([\s\S]*?)(?:\n?<\/parameter>|$)/g; + +export function parseAssistant(text, { thinkingOpen = true } = {}) { + let thinking = ""; + let rest = text; + let thinkingDone = true; + const end = text.indexOf(""); + if (end >= 0) { + thinking = text.slice(0, end).replace(/^\s*/, ""); + rest = text.slice(end + "".length); + } else if (thinkingOpen) { + thinking = text.replace(/^\s*/, ""); + rest = ""; + thinkingDone = false; + } + + const calls = []; + const firstCall = rest.indexOf(""); + const content = (firstCall >= 0 ? rest.slice(0, firstCall) : rest).trim(); + if (firstCall >= 0) { + const tail = rest.slice(firstCall); + for (const m of tail.matchAll(CALL_RE)) { + const args = {}; + for (const p of m[2].matchAll(PARAM_RE)) args[p[1].trim()] = p[2]; + calls.push({ name: m[1].trim(), arguments: args, complete: /<\/function>/.test(m[0]) }); + } + // Fallback: JSON-style calls, {"name": ..., "arguments": {...}} + if (!calls.length) { + for (const m of tail.matchAll(/\s*(\{[\s\S]*?\})\s*<\/tool_call>/g)) { + try { + const j = JSON.parse(m[1]); + const args = typeof j.arguments === "string" ? JSON.parse(j.arguments) : (j.arguments ?? j.parameters ?? {}); + if (j.name) calls.push({ name: String(j.name), arguments: Object.fromEntries(Object.entries(args).map(([k, v]) => [k, typeof v === "string" ? v : JSON.stringify(v)])), complete: true }); + } catch {} + } + } + } + return { thinking: thinking.trim(), thinkingDone, content, calls }; +} + +/** Quotes a string for bash. */ +export function shQuote(s) { + return "'" + String(s).replace(/'/g, "'\\''") + "'"; +} diff --git a/js/vm.js b/js/vm.js new file mode 100644 index 0000000000000000000000000000000000000000..05d43c2c686e4ba638044524d3bac615786b34b1 --- /dev/null +++ b/js/vm.js @@ -0,0 +1,318 @@ +// The Linux VM: CheerpX (WebVM's engine) + an xterm.js terminal. +// +// The agent and the user share ONE interactive bash. To run a command, the agent +// writes it to a script on the /data device and types ` __lwa ` into the +// terminal. The rc file below defines __lwa, which sources the script (so `cd` and +// exported variables persist, like a human typing) and brackets its output with +// invisible OSC escape sequences that carry the id and exit status. Those markers +// are how output is captured reliably; terminals ignore unknown OSC sequences. +import { CX_BASE, DISK_VIRTUAL_URL } from "./config.js"; +import { shQuote } from "./toolcalls.js"; +import { Terminal } from "../vendor/xterm/xterm.mjs"; +import { FitAddon } from "../vendor/xterm/addon-fit.mjs"; + +const RC = String.raw` +[ -f /etc/bash.bashrc ] && . /etc/bash.bashrc +[ -f ~/.bashrc ] && . ~/.bashrc +HISTCONTROL=ignoreboth +PS1='\[\e[32m\]\u@localwebagent\[\e[0m\]:\[\e[34m\]\w\[\e[0m\]\$ ' +__lwa_prompt() { printf '\033]777;lwa;prompt\007'; } +PROMPT_COMMAND="__lwa_prompt" +# Runs agent command . First replaces the echoed " __lwa " line with the +# prompt followed by the real command (or a short label), so the terminal reads +# as if the agent had typed it. +__lwa() { + local f="/data/lwa_cmd_$1.sh" p="${"$"}{PS1@P}" + p="${"$"}{p//$'\001'/}"; p="${"$"}{p//$'\002'/}" + printf '\033[1A\r\033[2K%s' "$p" + if [ -f "/data/lwa_label_$1" ]; then + printf '\033[90m# %s\033[0m\n' "$(cat "/data/lwa_label_$1")" + else + sed -n '1p' "$f" + sed -n '2,12s/^/> /p' "$f" + [ "$(wc -l < "$f")" -gt 12 ] && printf '\033[90m> …\033[0m\n' + fi + printf '\033]777;lwa;start;%s\007' "$1" + . "/data/lwa_cmd_$1.sh" < /dev/null + printf '\033]777;lwa;end;%s;%s\007' "$1" "$?" +} +if [ -z "$__LWA_MOTD" ]; then export __LWA_MOTD=1; cat /etc/motd 2>/dev/null; fi +`; + +const MARK_RE = /\x1b\]777;lwa;([^\x07]*)\x07/g; + +export class VM { + constructor() { + this.term = null; + this.cx = null; + this.data = null; + this.send = null; + this.idle = false; // bash is sitting at its prompt + this.agentBusy = false; // agent owns the terminal + this.onActivity = null; // (busy:boolean) CPU activity + this.onIdleChange = null; + this.#decoder = new TextDecoder(); + } + #decoder; + #carry = ""; + #capture = null; // { id, started, out, resolve } + #seq = 0; + #idleWaiters = []; + + mountTerminal(el) { + this.term = new Terminal({ + cursorBlink: true, convertEol: true, fontSize: 12.5, lineHeight: 1.25, scrollback: 5000, + fontFamily: '"JetBrains Mono", "Cascadia Code", Menlo, Consolas, monospace', + theme: { + background: "#0c0c0e", foreground: "#d4d4d8", cursor: "#ececef", cursorAccent: "#0c0c0e", + selectionBackground: "#3f3f4699", black: "#18181b", brightBlack: "#52525b", + red: "#f87171", green: "#4ade80", yellow: "#facc15", blue: "#60a5fa", magenta: "#c084fc", cyan: "#22d3ee", + white: "#d4d4d8", brightRed: "#fca5a5", brightGreen: "#86efac", brightYellow: "#fde047", brightBlue: "#93c5fd", + brightMagenta: "#d8b4fe", brightCyan: "#67e8f9", brightWhite: "#fafafa", + }, + }); + this.fit = new FitAddon(); + this.term.loadAddon(this.fit); + this.term.open(el); + this.fit.fit(); + // A hidden pane (mobile tab) measures as ~0 columns; give the console a sane size. + if (this.term.cols < 40 || this.term.rows < 10) this.term.resize(100, 30); + new ResizeObserver(() => { try { this.fit.fit(); } catch {} }).observe(el); + this.term.onData((str) => { + if (!this.send) return; + if (this.agentBusy) { + // While the agent runs a command, only let Ctrl-C through (to interrupt it). + if (str === "\x03") this.#type("\x03"); + return; + } + if (str.includes("\r")) this.#setIdle(false); + this.#type(str); + }); + this.term.writeln("\x1b[90mStarting Debian (CheerpX)…\x1b[0m"); + } + + async boot({ diskId, onStatus }) { + onStatus?.("Loading CheerpX runtime"); + const CX = await import(CX_BASE + "cx.esm.js"); + onStatus?.("Attaching disk"); + const disk = await CX.HttpBytesDevice.create(DISK_VIRTUAL_URL); + // Writes go to IndexedDB, keyed by the image id so a new image never mixes with old blocks. + this.overlayName = "lwa-overlay-" + diskId; + const idb = await CX.IDBDevice.create(this.overlayName); + const overlay = await CX.OverlayDevice.create(disk, idb); + this.data = await CX.DataDevice.create(); + // VM -> page channel for the file viewer: hidden processes copy files here and the + // page reads them back from IndexedDB. Never shown in the terminal. + this.exportDev = await CX.IDBDevice.create("lwa-export"); + onStatus?.("Booting Linux"); + this.cx = await CX.Linux.create({ + mounts: [ + { type: "ext2", dev: overlay, path: "/" }, + { type: "dir", dev: this.data, path: "/data" }, + { type: "dir", dev: this.exportDev, path: "/export" }, + { type: "devs", path: "/dev" }, + { type: "devpts", path: "/dev/pts" }, + { type: "proc", path: "/proc" }, + { type: "sys", path: "/sys" }, + ], + }); + this.cx.registerCallback("cpuActivity", (s) => this.onActivity?.(s === "ready" ? false : true)); + this.send = this.cx.setCustomConsole((buf, vt) => this.#onOutput(buf, vt), this.term.cols, this.term.rows); + await this.data.writeFile("/lwarc.sh", RC); + this.#shellLoop(); + await this.waitIdle(60000); + onStatus?.("Ready"); + } + + async #shellLoop() { + // Like WebVM: restart the shell whenever it exits. + for (;;) { + this.#setIdle(false); + await this.cx.run("/bin/bash", ["--rcfile", "/data/lwarc.sh", "-i"], { + env: ["HOME=/home/user", "TERM=xterm-256color", "USER=user", "SHELL=/bin/bash", "EDITOR=vim", + "LANG=C.UTF-8", "LC_ALL=C.UTF-8", "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"], + cwd: "/home/user", uid: 1000, gid: 1000, + }); + // If the agent's command exited the shell, finish its capture. + if (this.#capture) this.#finishCapture(null); + } + } + + #type(str) { + for (let i = 0; i < str.length; i++) this.send(str.charCodeAt(i)); + } + + #setIdle(v) { + if (this.idle === v) return; + this.idle = v; + this.onIdleChange?.(v); + if (v) { const w = this.#idleWaiters; this.#idleWaiters = []; w.forEach((f) => f(true)); } + } + + waitIdle(ms) { + if (this.idle) return Promise.resolve(true); + return new Promise((resolve) => { + this.#idleWaiters.push(resolve); + setTimeout(() => resolve(false), ms); + }); + } + + #onOutput(buf, vt) { + if (vt !== 1) return; + const bytes = new Uint8Array(buf); + this.term.write(bytes); + let text = this.#carry + this.#decoder.decode(bytes, { stream: true }); + // Keep a possibly-incomplete marker for the next chunk. + const lastEsc = text.lastIndexOf("\x1b]777;"); + if (lastEsc >= 0 && text.indexOf("\x07", lastEsc) < 0) { + this.#carry = text.slice(lastEsc); + text = text.slice(0, lastEsc); + } else this.#carry = ""; + + let last = 0; + for (const m of text.matchAll(MARK_RE)) { + this.#appendCapture(text.slice(last, m.index)); + last = m.index + m[0].length; + const [kind, id, status] = m[1].split(";"); + if (kind === "prompt") { + if (this.#capture) this.#finishCapture(null); // shell came back without an end marker + this.#setIdle(true); + } else if (kind === "start" && this.#capture?.id === id) { + this.#capture.started = true; + } else if (kind === "end" && this.#capture?.id === id) { + this.#finishCapture(Number(status)); + } + } + this.#appendCapture(text.slice(last)); + } + + #appendCapture(s) { + const c = this.#capture; + if (!c || !c.started || !s) return; + c.out += s; + if (c.out.length > 400_000) c.out = c.out.slice(0, 100_000) + c.out.slice(-200_000); // bound memory + } + + #finishCapture(exitCode) { + const c = this.#capture; + if (!c) return; + this.#capture = null; + clearTimeout(c.timer); + c.resolve({ exitCode, output: cleanTerminalText(c.out), timedOut: c.timedOut }); + } + + /** Runs a bash snippet in the shared terminal. Resolves {exitCode, output, timedOut}. */ + async exec(command, { timeoutSec = 90, label = null } = {}) { + if (!this.send) throw new Error("VM not running"); + if (!(await this.waitIdle(5000))) { + return { exitCode: null, output: "The terminal is busy: a program is running in the foreground. Ask the user to finish or press Ctrl-C.", timedOut: false, busy: true }; + } + const id = String(++this.#seq); + await this.data.writeFile(`/lwa_cmd_${id}.sh`, command.endsWith("\n") ? command : command + "\n"); + if (label) await this.data.writeFile(`/lwa_label_${id}`, label); + this.agentBusy = true; + try { + const result = await new Promise((resolve) => { + this.#capture = { id, started: false, out: "", resolve, timedOut: false }; + this.#capture.timer = setTimeout(() => { + if (!this.#capture) return; + this.#capture.timedOut = true; + this.#type("\x03"); // Ctrl-C + setTimeout(() => this.#finishCapture(null), 3000); + }, timeoutSec * 1000); + this.#setIdle(false); + this.#type("\x15 __lwa " + id + "\r"); // Ctrl-U clears any half-typed input first + }); + await this.waitIdle(3000); + return result; + } finally { + this.agentBusy = false; + } + } + + /** Writes a file inside the VM (path relative to the shell's current directory). */ + async writeFile(path, content) { + const id = "f" + ++this.#seq; + await this.data.writeFile(`/lwa_${id}`, content); + const p = shQuote(path); + // `cat >` rather than `cp`: /data files are read-only and cp would copy that mode. + const lines = content.replace(/\n$/, "").split("\n").length; + return this.exec(`mkdir -p -- "$(dirname -- ${p})" && cat /data/lwa_${id} > ${p} && echo "wrote $(wc -c < ${p}) bytes to $(readlink -f -- ${p})"`, + { label: `write ${path} (${lines} line${lines === 1 ? "" : "s"})` }); + } + + interrupt() { if (this.send) this.#type("\x03"); } + + // ---------- hidden file access (for the file viewer) ---------- + // Files written to the IndexedDB-backed /export only become visible (even to the VM + // itself) after an explicit sync, hence the "&& sync" after every write. + #hiddenQueue = Promise.resolve(); + #xseq = 0; + + /** Runs a bash snippet in a separate, invisible process. Its output must be redirected. */ + hidden(script) { + const run = () => this.cx.run("/bin/bash", ["-c", script + " /dev/null 2>&1"], { + env: ["HOME=/home/user", "USER=user", "LANG=C.UTF-8", "PATH=/usr/local/bin:/usr/bin:/bin"], + cwd: "/home/user", uid: 1000, gid: 1000, + }); + const p = this.#hiddenQueue.then(run, run); + this.#hiddenQueue = p.catch(() => {}); + return p; + } + + async #exported(name) { + const blob = await this.exportDev.readFileAsBlob("/" + name); + this.hidden(`rm -f /export/${name}`); + return blob; + } + + /** Lists a directory: { path, entries: [{name, type: 'd'|'f'|'l', size, mtime}] } */ + async listDir(path) { + const n = "l" + ++this.#xseq; + const r = await this.hidden(`cd -- ${shQuote(path)} || exit 2; { pwd -P; find . -maxdepth 1 -mindepth 1 -printf '%y\t%s\t%T@\t%f\n'; } > /export/${n} && sync /export/${n}`); + if (r.status !== 0) throw new Error(r.status === 2 ? `Can't open ${path}` : `ls failed (${r.status})`); + const [abs, ...lines] = (await (await this.#exported(n)).text()).split("\n"); + const entries = lines.filter(Boolean).map((l) => { + const [type, size, mtime, ...name] = l.split("\t"); + return { name: name.join("\t"), type: type === "d" ? "d" : type === "l" ? "l" : "f", size: Number(size), mtime: Number(mtime) * 1000 }; + }); + return { path: abs, entries }; + } + + /** Reads a file as a Blob (throws if it is a directory, unreadable or larger than maxBytes). */ + async readFile(path, maxBytes = 25e6) { + const n = "r" + ++this.#xseq; + const r = await this.hidden(`f=${shQuote(path)}; [ -d "$f" ] && exit 3; [ -r "$f" ] || exit 2; [ "$(stat -L -c %s -- "$f")" -le ${Math.floor(maxBytes)} ] || exit 4; cat -- "$f" > /export/${n} && sync /export/${n}`); + if (r.status === 3) throw Object.assign(new Error("is a directory"), { code: "EISDIR" }); + if (r.status === 2) throw Object.assign(new Error(`Can't read ${path}`), { code: "ENOENT" }); + if (r.status === 4) throw Object.assign(new Error(`File is larger than ${Math.round(maxBytes / 1e6)} MB`), { code: "EFBIG" }); + if (r.status !== 0) throw new Error(`read failed (${r.status})`); + return this.#exported(n); + } + + /** Resolves a path relative to the interactive shell's home to an absolute path. */ + async realpath(path) { + const n = "p" + ++this.#xseq; + const r = await this.hidden(`readlink -f -- ${shQuote(path)} > /export/${n} && sync /export/${n}`); + if (r.status !== 0) throw new Error(`Can't resolve ${path}`); + return (await (await this.#exported(n)).text()).trim(); + } +} + + +/** Turns raw terminal bytes into plain text: drops escape sequences, applies \r overwrites. */ +export function cleanTerminalText(s) { + s = s + .replace(/\x1b\][^\x07\x1b]*(\x07|\x1b\\)/g, "") // OSC + .replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, "") // CSI + .replace(/\x1b[@-Z\\-_]/g, "") // other ESC + .replace(/\r+\n/g, "\n"); + return s + .split("\n") + .map((line) => { + const i = line.lastIndexOf("\r"); + return (i >= 0 ? line.slice(i + 1) : line).replace(/[\x00-\x08\x0b-\x1f\x7f]/g, ""); + }) + .join("\n") + .replace(/\n+$/, ""); +} diff --git a/sw.js b/sw.js new file mode 100644 index 0000000000000000000000000000000000000000..b3523449f832d385363ab59782edf44549011d81 --- /dev/null +++ b/sw.js @@ -0,0 +1,188 @@ +// LocalWebAgent service worker. +// 1. Keeps the app shell available offline (network-first, cache fallback). +// 2. Caches the CheerpX runtime the first time the browser loads it from +// Leaning Technologies' CDN, so the VM also boots offline. +// 3. Serves the Linux disk image to CheerpX as a byte-range-capable virtual file +// (__vm__/disk.ext2), backed by the chunks the setup screen stored in Cache Storage. +// 4. Adds the cross-origin isolation headers (COOP/COEP) that SharedArrayBuffer, +// CheerpX and multi-threaded WASM need, even when a host forgets to send them. +const SHELL_VERSION = "lwa-shell-0.3.0"; +const CX_ORIGIN = "https://cxrtnc.leaningtech.com"; +const CX_CACHE_PREFIX = "lwa-cheerpx-"; +const DISK_CACHE = "lwa-disk"; +const SCOPE = self.registration.scope; +const DISK_URL = SCOPE + "__vm__/disk.ext2"; +const MANIFEST_KEY = SCOPE + "__vm__/manifest.json"; +const chunkKey = (i) => SCOPE + "__vm__/chunk/" + i; + +const SHELL_FILES = [ + "./", "index.html", "css/app.css", "icon.svg", + "js/config.js", "js/config-defaults.js", "js/main.js", "js/setup.js", "js/vm.js", "js/agent.js", "js/llm.js", + "js/llm-worker.js", "js/llm-engine.js", "js/prompts.js", "js/toolcalls.js", "js/markdown.js", "js/files.js", + "vendor/transformers.min.js", "vendor/highlight.min.js", + "vendor/ort/ort-wasm-simd-threaded.asyncify.mjs", "vendor/ort/ort-wasm-simd-threaded.asyncify.wasm", + "vendor/xterm/xterm.mjs", "vendor/xterm/xterm.css", "vendor/xterm/addon-fit.mjs", + "vendor/fonts/inter-latin.woff2", "vendor/fonts/inter-latin-ext.woff2", "vendor/fonts/jetbrains-mono-latin.woff2", +]; + +self.addEventListener("install", (event) => { + event.waitUntil((async () => { + const cache = await caches.open(SHELL_VERSION); + // Best effort: a missing file must not block installation. + await Promise.all(SHELL_FILES.map((f) => cache.add(new Request(new URL(f, SCOPE), { cache: "reload" })).catch(() => {}))); + await self.skipWaiting(); + })()); +}); + +self.addEventListener("activate", (event) => { + event.waitUntil((async () => { + for (const k of await caches.keys()) { + if (k.startsWith("lwa-shell-") && k !== SHELL_VERSION) await caches.delete(k); + } + await self.clients.claim(); + })()); +}); + +self.addEventListener("message", (event) => { + if (event.data?.type === "disk-updated") { manifestPromise = null; lru.clear(); } +}); + +self.addEventListener("fetch", (event) => { + const req = event.request; + const url = new URL(req.url); + if (req.url.split("?")[0] === DISK_URL) return event.respondWith(serveDisk(req)); + if (url.origin === CX_ORIGIN) return event.respondWith(cheerpx(req)); + if (url.origin === self.location.origin && req.method === "GET") { + // Disk chunks are stored decompressed by the setup code; don't double-cache the .gz files. + if (url.pathname.includes("/disk/")) return; + return event.respondWith(shell(req)); + } + if (url.hostname === "huggingface.co" || url.hostname.endsWith(".hf.co")) return event.respondWith(hub(req)); +}); + +// ---------- app shell ---------- +async function shell(req) { + const cache = await caches.open(SHELL_VERSION); + try { + const res = await fetch(req); + if (res.ok && res.status === 200 && !req.headers.has("range")) cache.put(req, res.clone()).catch(() => {}); + return isolate(res); + } catch (err) { + const hit = (await cache.match(req, { ignoreSearch: true })) ?? + (req.mode === "navigate" ? await cache.match(new URL("index.html", SCOPE)) : undefined); + if (hit) return isolate(hit); + return new Response("Offline and not cached: " + req.url, { status: 504 }); + } +} + +function isolate(res) { + if (res.status === 0 || res.type === "opaque") return res; + const h = new Headers(res.headers); + h.set("Cross-Origin-Opener-Policy", "same-origin"); + h.set("Cross-Origin-Embedder-Policy", "require-corp"); + h.set("Cross-Origin-Resource-Policy", "cross-origin"); + return new Response(res.body, { status: res.status, statusText: res.statusText, headers: h }); +} + +// ---------- CheerpX runtime (cache-first) ---------- +async function cheerpx(req) { + const version = new URL(req.url).pathname.split("/")[1]; + const cache = await caches.open(CX_CACHE_PREFIX + version); + const hit = await cache.match(req.url); + if (hit) return hit; + const res = await fetch(req.url, { mode: "cors", credentials: "omit" }); + if (res.ok) await cache.put(req.url, res.clone()); + return res; +} + +// ---------- Hugging Face Hub (model files are cached by transformers.js itself) ---------- +async function hub(req) { + try { + return await fetch(req); + } catch { + // Offline: answer probes for optional files with a clean 404 instead of a network error. + return new Response("offline", { status: 404, statusText: "Offline" }); + } +} + +// ---------- Disk image ---------- +let manifestPromise = null; +function manifest() { + manifestPromise ??= caches.open(DISK_CACHE) + .then((c) => c.match(MANIFEST_KEY)) + .then((r) => (r ? r.json() : null)) + .catch(() => null); + return manifestPromise; +} + +// Small LRU of decompressed 4 MiB chunks. +const lru = new Map(); +const LRU_MAX = 12; +async function getChunk(m, i) { + if (!m.chunks[i]) return null; // all-zero chunk + let buf = lru.get(i); + if (buf) { lru.delete(i); lru.set(i, buf); return buf; } + const cache = await caches.open(DISK_CACHE); + const res = await cache.match(chunkKey(i)); + if (!res) throw new Error("disk chunk " + i + " missing; run setup again"); + buf = new Uint8Array(await res.arrayBuffer()); + lru.set(i, buf); + if (lru.size > LRU_MAX) lru.delete(lru.keys().next().value); + return buf; +} + +async function serveDisk(req) { + const m = await manifest(); + const base = { + "Accept-Ranges": "bytes", + "Content-Type": "application/octet-stream", + "Cross-Origin-Resource-Policy": "same-origin", + "Cache-Control": "no-store", + }; + if (!m) return new Response("Disk image not installed", { status: 503, headers: base }); + // CheerpX's HttpBytesDevice requires a validator; the image id changes with the content. + base["ETag"] = `"${m.id}"`; + base["Last-Modified"] = "Thu, 01 Jan 2026 00:00:00 GMT"; + const size = m.size; + if (req.method === "HEAD") return new Response(null, { status: 200, headers: { ...base, "Content-Length": String(size) } }); + + const range = /bytes=(\d*)-(\d*)/.exec(req.headers.get("range") ?? ""); + let start = 0, end = size - 1; + if (range) { + if (range[1] === "") { start = Math.max(0, size - Number(range[2])); } + else { start = Number(range[1]); if (range[2] !== "") end = Math.min(Number(range[2]), size - 1); } + } + if (start > end || start >= size) { + return new Response(null, { status: 416, headers: { ...base, "Content-Range": `bytes */${size}` } }); + } + + if (!range) { + // Full read: stream every chunk in order. + let i = 0; + const n = m.chunks.length; + const body = new ReadableStream({ + async pull(ctrl) { + if (i >= n) return ctrl.close(); + const len = Math.min(m.chunkSize, size - i * m.chunkSize); + const c = await getChunk(m, i++); + ctrl.enqueue(c ? c.subarray(0, len) : new Uint8Array(len)); + }, + }); + return new Response(body, { status: 200, headers: { ...base, "Content-Length": String(size) } }); + } + + const out = new Uint8Array(end - start + 1); + let pos = start; + while (pos <= end) { + const i = Math.floor(pos / m.chunkSize); + const off = pos - i * m.chunkSize; + const take = Math.min(m.chunkSize - off, end - pos + 1); + const c = await getChunk(m, i); + if (c) out.set(c.subarray(off, off + take), pos - start); + pos += take; + } + return new Response(out, { + status: 206, + headers: { ...base, "Content-Range": `bytes ${start}-${end}/${size}`, "Content-Length": String(out.length) }, + }); +} diff --git a/vendor/LICENSE.highlightjs.txt b/vendor/LICENSE.highlightjs.txt new file mode 100644 index 0000000000000000000000000000000000000000..2250cc7eca9bfe58df2f7e0b5db32e00baadfad3 --- /dev/null +++ b/vendor/LICENSE.highlightjs.txt @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2006, Ivan Sagalaev. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/LICENSE.transformers.txt b/vendor/LICENSE.transformers.txt new file mode 100644 index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7 --- /dev/null +++ b/vendor/LICENSE.transformers.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/fonts/LICENSE.inter.txt b/vendor/fonts/LICENSE.inter.txt new file mode 100644 index 0000000000000000000000000000000000000000..40589daa9de8bc96606292ea0be712ff0f0626eb --- /dev/null +++ b/vendor/fonts/LICENSE.inter.txt @@ -0,0 +1,93 @@ +Copyright 2016 The Inter Project Authors (https://github.com/rsms/inter) Inter-Italic[opsz,wght].ttf: Copyright 2016 The Inter Project Authors (https://github.com/rsms/inter) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/vendor/fonts/LICENSE.jetbrains-mono.txt b/vendor/fonts/LICENSE.jetbrains-mono.txt new file mode 100644 index 0000000000000000000000000000000000000000..8f7ed671137e7a27c646ead86f45d5cb4875f459 --- /dev/null +++ b/vendor/fonts/LICENSE.jetbrains-mono.txt @@ -0,0 +1,93 @@ +Copyright 2020 The JetBrains Mono Project Authors (https://github.com/JetBrains/JetBrainsMono) JetBrainsMono-Italic[wght].ttf: Copyright 2020 The JetBrains Mono Project Authors (https://github.com/JetBrains/JetBrainsMono) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/vendor/fonts/inter-latin-ext.woff2 b/vendor/fonts/inter-latin-ext.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..479d010d2902fa3a5b48e84a973db1978b2e9949 Binary files /dev/null and b/vendor/fonts/inter-latin-ext.woff2 differ diff --git a/vendor/fonts/inter-latin.woff2 b/vendor/fonts/inter-latin.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..d15208de03cd1ad7c5199f0a0ce915fe841e4722 Binary files /dev/null and b/vendor/fonts/inter-latin.woff2 differ diff --git a/vendor/fonts/jetbrains-mono-latin.woff2 b/vendor/fonts/jetbrains-mono-latin.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..cd5102a44c763f1cfe9f2b199fd5d7257491c0dd Binary files /dev/null and b/vendor/fonts/jetbrains-mono-latin.woff2 differ diff --git a/vendor/highlight.min.js b/vendor/highlight.min.js new file mode 100644 index 0000000000000000000000000000000000000000..42969eca900eba51b68233c8036013906af4fe86 --- /dev/null +++ b/vendor/highlight.min.js @@ -0,0 +1,1260 @@ +/*! + Highlight.js v11.12.0 (git: f7f7d3803b) + (c) 2006-2026 Josh Goebel and other contributors + License: BSD-3-Clause + */ +function e(n){return n instanceof Map?n.clear=n.delete=n.set=()=>{ +throw Error("map is read-only")}:n instanceof Set&&(n.add=n.clear=n.delete=()=>{ +throw Error("set is read-only") +}),Object.freeze(n),Object.getOwnPropertyNames(n).forEach(t=>{ +const a=n[t],i=typeof a;"object"!==i&&"function"!==i||Object.isFrozen(a)||e(a) +}),n}class n{constructor(e){ +void 0===e.data&&(e.data={}),this.data=e.data,this.isMatchIgnored=!1} +ignoreMatch(){this.isMatchIgnored=!0}}function t(e){ +return e.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'") +}function a(e,...n){const t=Object.create(null);for(const n in e)t[n]=e[n] +;return n.forEach(e=>{for(const n in e)t[n]=e[n]}),t}const i=e=>!!e.scope +;class r{constructor(e,n){ +this.buffer="",this.classPrefix=n.classPrefix,e.walk(this)}addText(e){ +this.buffer+=t(e)}openNode(e){if(!i(e))return;const n=((e,{prefix:n})=>{ +if(e.startsWith("language:"))return e.replace("language:","language-") +;if(e.includes(".")){const t=e.split(".") +;return[`${n}${t.shift()}`,...t.map((e,n)=>`${e}${"_".repeat(n+1)}`)].join(" ")} +return`${n}${e}`})(e.scope,{prefix:this.classPrefix});this.span(n)}closeNode(e){ +i(e)&&(this.buffer+="")}value(){return this.buffer}span(e){ +this.buffer+=``}}const s=(e={})=>{const n={children:[]} +;return Object.assign(n,e),n};class o{constructor(){ +this.rootNode=s(),this.stack=[this.rootNode]}get top(){ +return this.stack[this.stack.length-1]}get root(){return this.rootNode}add(e){ +this.top.children.push(e)}openNode(e){const n=s({scope:e}) +;this.add(n),this.stack.push(n)}closeNode(){ +if(this.stack.length>1)return this.stack.pop()}closeAllNodes(){ +for(;this.closeNode(););}toJSON(){return JSON.stringify(this.rootNode,null,4)} +walk(e){return this.constructor._walk(e,this.rootNode)}static _walk(e,n){ +return"string"==typeof n?e.addText(n):n.children&&(e.openNode(n), +n.children.forEach(n=>this._walk(e,n)),e.closeNode(n)),e}static _collapse(e){ +"string"!=typeof e&&e.children&&(e.children.every(e=>"string"==typeof e)?e.children=[e.children.join("")]:e.children.forEach(e=>{ +o._collapse(e)}))}}class c extends o{constructor(e){super(),this.options=e} +addText(e){""!==e&&this.add(e)}startScope(e){this.openNode(e)}endScope(){ +this.closeNode()}__addSublanguage(e,n){const t=e.root +;n&&(t.scope="language:"+n),this.add(t)}toHTML(){ +return new r(this,this.options).value()}finalize(){ +return this.closeAllNodes(),!0}}function l(e){ +return e?"string"==typeof e?e:e.source:null}function d(e){return b("(?=",e,")")} +function g(e){return b("(?:",e,")*")}function u(e){return b("(?:",e,")?")} +function b(...e){return e.map(e=>l(e)).join("")}function m(...e){const n=(e=>{ +const n=e[e.length-1] +;return"object"==typeof n&&n.constructor===Object?(e.splice(e.length-1,1),n):{} +})(e);return"("+(n.capture?"":"?:")+e.map(e=>l(e)).join("|")+")"}function p(e){ +return RegExp(e.toString()+"|").exec("").length-1} +const _=RegExp(m(/\[(?:[^\\\]]|\\.)*\]/,/\(\?<(?![=!])[^>]+>/,/\(\?'[^']+'/,/\(\??/,/\\([1-9][0-9]*)/,/\\./)) +;function h(e,{joinWith:n}){let t=0;return e.map(e=>{t+=1;const n=t +;let a=l(e),i="";for(;a.length>0;){const e=_.exec(a);if(!e){i+=a;break} +i+=a.substring(0,e.index), +a=a.substring(e.index+e[0].length),"\\"===e[0][0]&&e[1]?i+="\\"+(Number(e[1])+n):(i+=e[0], +("("===e[0]||/^\(\?[<']/.test(e[0]))&&t++)}return i}).map(e=>`(${e})`).join(n)} +const f="[a-zA-Z]\\w*",E="[a-zA-Z_]\\w*",y="\\b\\d+(\\.\\d+)?",w="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",v="\\b(0b[01]+)",N={ +begin:"\\\\[\\s\\S]",relevance:0},k={scope:"string",begin:"'",end:"'", +illegal:"\\n",contains:[N]},x={scope:"string",begin:'"',end:'"',illegal:"\\n", +contains:[N]},O=(e,n,t={})=>{const i=a({scope:"comment",begin:e,end:n, +contains:[]},t);i.contains.push({scope:"doctag", +begin:"[ ]*(?=(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):)", +end:/(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):/,excludeBegin:!0,relevance:0}) +;const r=m("I","a","is","so","us","to","at","if","in","it","on",/[A-Za-z]+['](d|ve|re|ll|t|s|n)/,/[A-Za-z]+[-][a-z]+/,/[A-Za-z][a-z]{2,}/) +;return i.contains.push({begin:b(/[ ]+/,"(",r,/[.]?[:]?([.][ ]|[ ])/,"){3}")}),i +},M=O("//","$"),A=O("/\\*","\\*/"),S=O("#","$");var C=Object.freeze({ +__proto__:null,APOS_STRING_MODE:k,BACKSLASH_ESCAPE:N,BINARY_NUMBER_MODE:{ +scope:"number",begin:v,relevance:0},BINARY_NUMBER_RE:v,COMMENT:O, +C_BLOCK_COMMENT_MODE:A,C_LINE_COMMENT_MODE:M,C_NUMBER_MODE:{scope:"number", +begin:w,relevance:0},C_NUMBER_RE:w,END_SAME_AS_BEGIN:e=>Object.assign(e,{ +"on:begin":(e,n)=>{n.data._beginMatch=e[1]},"on:end":(e,n)=>{ +n.data._beginMatch!==e[1]&&n.ignoreMatch()}}),HASH_COMMENT_MODE:S,IDENT_RE:f, +MATCH_NOTHING_RE:/\b\B/,METHOD_GUARD:{begin:"\\.\\s*"+E,relevance:0}, +NUMBER_MODE:{scope:"number",begin:y,relevance:0},NUMBER_RE:y, +PHRASAL_WORDS_MODE:{ +begin:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/ +},QUOTE_STRING_MODE:x,REGEXP_MODE:{scope:"regexp",begin:/\/(?=[^/\n]*\/)/, +end:/\/[gimuy]*/,contains:[N,{begin:/\[/,end:/\]/,relevance:0,contains:[N]}]}, +RE_STARTERS_RE:"!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~", +SHEBANG:(e={})=>{const n=/^#![ ]*\// +;return e.binary&&(e.begin=b(n,/.*\b/,e.binary,/\b.*/)),a({scope:"meta",begin:n, +end:/$/,relevance:0,"on:begin":(e,n)=>{0!==e.index&&n.ignoreMatch()}},e)}, +TITLE_MODE:{scope:"title",begin:f,relevance:0},UNDERSCORE_IDENT_RE:E, +UNDERSCORE_TITLE_MODE:{scope:"title",begin:E,relevance:0}});function T(e,n){ +"."===e.input[e.index-1]&&n.ignoreMatch()}function R(e,n){ +void 0!==e.className&&(e.scope=e.className,delete e.className)}function D(e,n){ +n&&e.beginKeywords&&(e.begin="\\b("+e.beginKeywords.split(" ").join("|")+")(?!\\.)(?=\\b|\\s)", +e.__beforeBegin=T,e.keywords=e.keywords||e.beginKeywords,delete e.beginKeywords, +void 0===e.relevance&&(e.relevance=0))}function I(e,n){ +Array.isArray(e.illegal)&&(e.illegal=m(...e.illegal))}function L(e,n){ +if(e.match){ +if(e.begin||e.end)throw Error("begin & end are not supported with match") +;e.begin=e.match,delete e.match}}function B(e,n){ +void 0===e.relevance&&(e.relevance=1)}const F=(e,n)=>{if(!e.beforeMatch)return +;if(e.starts)throw Error("beforeMatch cannot be used with starts") +;const t=Object.assign({},e);Object.keys(e).forEach(n=>{delete e[n] +}),e.keywords=t.keywords,e.begin=b(t.beforeMatch,d(t.begin)),e.starts={ +relevance:0,contains:[Object.assign(t,{endsParent:!0})] +},e.relevance=0,delete t.beforeMatch +},$=["of","and","for","in","not","or","if","then","parent","list","value"] +;function z(e,n,t="keyword"){const a=Object.create(null) +;return"string"==typeof e?i(t,e.split(" ")):Array.isArray(e)?i(t,e):Object.keys(e).forEach(t=>{ +Object.assign(a,z(e[t],n,t))}),a;function i(e,t){ +n&&(t=t.map(e=>e.toLowerCase())),t.forEach(n=>{const t=n.split("|") +;a[t[0]]=[e,U(t[0],t[1])]})}}function U(e,n){ +return n?Number(n):(e=>$.includes(e.toLowerCase()))(e)?0:1}const j={},P=e=>{ +console.error(e)},K=(e,...n)=>{console.log("WARN: "+e,...n)},H=(e,n)=>{ +j[`${e}/${n}`]||(console.log(`Deprecated as of ${e}. ${n}`),j[`${e}/${n}`]=!0) +},q=Error();function G(e,n,{key:t}){let a=0;const i=e[t],r={},s={} +;for(let e=1;e<=n.length;e++)s[e+a]=i[e],r[e+a]=!0,a+=p(n[e-1]) +;e[t]=s,e[t]._emit=r,e[t]._multi=!0}function Z(e){(e=>{ +e.scope&&"object"==typeof e.scope&&null!==e.scope&&(e.beginScope=e.scope, +delete e.scope)})(e),"string"==typeof e.beginScope&&(e.beginScope={ +_wrap:e.beginScope}),"string"==typeof e.endScope&&(e.endScope={_wrap:e.endScope +}),(e=>{if(Array.isArray(e.begin)){ +if(e.skip||e.excludeBegin||e.returnBegin)throw P("skip, excludeBegin, returnBegin not compatible with beginScope: {}"), +q +;if("object"!=typeof e.beginScope||null===e.beginScope)throw P("beginScope must be object"), +q;G(e,e.begin,{key:"beginScope"}),e.begin=h(e.begin,{joinWith:""})}})(e),(e=>{ +if(Array.isArray(e.end)){ +if(e.skip||e.excludeEnd||e.returnEnd)throw P("skip, excludeEnd, returnEnd not compatible with endScope: {}"), +q +;if("object"!=typeof e.endScope||null===e.endScope)throw P("endScope must be object"), +q;G(e,e.end,{key:"endScope"}),e.end=h(e.end,{joinWith:""})}})(e)}function W(e){ +function n(n,t){ +return RegExp(l(n),"m"+(e.case_insensitive?"i":"")+(e.unicodeRegex?"u":"")+(t?"g":"")) +}class t{constructor(){ +this.matchIndexes={},this.regexes=[],this.matchAt=1,this.position=0} +addRule(e,n){ +n.position=this.position++,this.matchIndexes[this.matchAt]=n,this.regexes.push([n,e]), +this.matchAt+=p(e)+1}compile(){0===this.regexes.length&&(this.exec=()=>null) +;const e=this.regexes.map(e=>e[1]);this.matcherRe=n(h(e,{joinWith:"|" +}),!0),this.lastIndex=0}exec(e){this.matcherRe.lastIndex=this.lastIndex +;const n=this.matcherRe.exec(e);if(!n)return null +;const t=n.findIndex((e,n)=>n>0&&void 0!==e),a=this.matchIndexes[t] +;return n.splice(0,t),Object.assign(n,a)}}class i{constructor(){ +this.rules=[],this.multiRegexes=[], +this.count=0,this.lastIndex=0,this.regexIndex=0}getMatcher(e){ +if(this.multiRegexes[e])return this.multiRegexes[e];const n=new t +;return this.rules.slice(e).forEach(([e,t])=>n.addRule(e,t)), +n.compile(),this.multiRegexes[e]=n,n}resumingScanAtSamePosition(){ +return 0!==this.regexIndex}considerAll(){this.regexIndex=0}addRule(e,n){ +this.rules.push([e,n]),"begin"===n.type&&this.count++}exec(e){ +const n=this.getMatcher(this.regexIndex);n.lastIndex=this.lastIndex +;let t=n.exec(e) +;if(this.resumingScanAtSamePosition())if(t&&t.index===this.lastIndex);else{ +const n=this.getMatcher(0);n.lastIndex=this.lastIndex+1,t=n.exec(e)} +return t&&(this.regexIndex+=t.position+1, +this.regexIndex===this.count&&this.considerAll()),t}} +if(e.compilerExtensions||(e.compilerExtensions=[]), +e.contains&&e.contains.includes("self"))throw Error("ERR: contains `self` is not supported at the top-level of a language. See documentation.") +;return e.classNameAliases=a(e.classNameAliases||{}),function t(r,s){const o=r +;if(r.isCompiled)return o +;[R,L,Z,F].forEach(e=>e(r,s)),e.compilerExtensions.forEach(e=>e(r,s)), +r.__beforeBegin=null,[D,I,B].forEach(e=>e(r,s)),r.isCompiled=!0;let c=null +;return"object"==typeof r.keywords&&r.keywords.$pattern&&(r.keywords=Object.assign({},r.keywords), +c=r.keywords.$pattern, +delete r.keywords.$pattern),c=c||/\w+/,r.keywords&&(r.keywords=z(r.keywords,e.case_insensitive)), +o.keywordPatternRe=n(c,!0), +s&&(r.begin||(r.begin=/\B|\b/),o.beginRe=n(o.begin),r.end||r.endsWithParent||(r.end=/\B|\b/), +r.end&&(o.endRe=n(o.end)), +o.terminatorEnd=l(o.end)||"",r.endsWithParent&&s.terminatorEnd&&(o.terminatorEnd+=(r.end?"|":"")+s.terminatorEnd)), +r.illegal&&(o.illegalRe=n(r.illegal)), +r.contains||(r.contains=[]),r.contains=[].concat(...r.contains.map(e=>(e=>(e.variants&&!e.cachedVariants&&(e.cachedVariants=e.variants.map(n=>a(e,{ +variants:null},n))),e.cachedVariants?e.cachedVariants:Q(e)?a(e,{ +starts:e.starts?a(e.starts):null +}):Object.isFrozen(e)?a(e):e))("self"===e?r:e))),r.contains.forEach(e=>{t(e,o) +}),r.starts&&t(r.starts,s),o.matcher=(e=>{const n=new i +;return e.contains.forEach(e=>n.addRule(e.begin,{rule:e,type:"begin" +})),e.terminatorEnd&&n.addRule(e.terminatorEnd,{type:"end" +}),e.illegal&&n.addRule(e.illegal,{type:"illegal"}),n})(o),o}(e)}function Q(e){ +return!!e&&(e.endsWithParent||Q(e.starts))}class X extends Error{ +constructor(e,n){super(e),this.name="HTMLInjectionError",this.html=n}} +const V=t,J=a,Y=Symbol("nomatch"),ee=t=>{ +const a=Object.create(null),i=Object.create(null),r=[];let s=!0 +;const o="Could not find the language '{}', did you forget to load/include a language module?",l={ +disableAutodetect:!0,name:"Plain text",contains:[]};let p={ +ignoreUnescapedHTML:!1,throwUnescapedHTML:!1,noHighlightRe:/^(no-?highlight)$/i, +languageDetectRe:/\blang(?:uage)?-([\w-]+)\b/i,classPrefix:"hljs-", +cssSelector:"pre code",languages:null,__emitter:c};function _(e){ +return p.noHighlightRe.test(e)}function h(e,n,t){let a="",i="" +;"object"==typeof n?(a=e, +t=n.ignoreIllegals,i=n.language):(H("10.7.0","highlight(lang, code, ...args) has been deprecated."), +H("10.7.0","Please use highlight(code, options) instead.\nhttps://github.com/highlightjs/highlight.js/issues/2277"), +i=e,a=n),void 0===t&&(t=!0);const r={code:a,language:i};O("before:highlight",r) +;const s=r.result?r.result:f(r.language,r.code,t) +;return s.code=r.code,O("after:highlight",s),s}function f(e,t,i,r){ +const c=Object.create(null);function l(e,n){return e.keywords[n]}function d(){ +if(!M.keywords)return void S.addText(C);let e=0;M.keywordPatternRe.lastIndex=0 +;let n=M.keywordPatternRe.exec(C),t="";for(;n;){t+=C.substring(e,n.index) +;const a=k.case_insensitive?n[0].toLowerCase():n[0],i=l(M,a);if(i){const[e,r]=i +;if(S.addText(t), +t="",c[a]=(c[a]||0)+1,c[a]<=7&&(T+=r),e.startsWith("_"))t+=n[0];else{ +const t=k.classNameAliases[e]||e;u(n[0],t)}}else t+=n[0] +;e=M.keywordPatternRe.lastIndex,n=M.keywordPatternRe.exec(C)} +t+=C.substring(e),S.addText(t)}function g(){null!=M.subLanguage?(()=>{ +if(""===C)return;let e=null;if("string"==typeof M.subLanguage){ +if(!a[M.subLanguage])return void S.addText(C) +;e=f(M.subLanguage,C,!0,A[M.subLanguage]),A[M.subLanguage]=e._top +}else e=E(C,M.subLanguage.length?M.subLanguage:null) +;M.relevance>0&&(T+=e.relevance),S.__addSublanguage(e._emitter,e.language) +})():d(),C=""}function u(e,n){ +""!==e&&(S.startScope(n),S.addText(e),S.endScope())}function b(e,n){let t=1 +;const a=n.length-1;for(;t<=a;){if(!e._emit[t]){t++;continue} +const a=k.classNameAliases[e[t]]||e[t],i=n[t];a?u(i,a):(C=i,d(),C=""),t++}} +function m(e,n){ +return e.scope&&"string"==typeof e.scope&&S.openNode(k.classNameAliases[e.scope]||e.scope), +e.beginScope&&(e.beginScope._wrap?(u(C,k.classNameAliases[e.beginScope._wrap]||e.beginScope._wrap), +C=""):e.beginScope._multi&&(b(e.beginScope,n),C="")),M=Object.create(e,{parent:{ +value:M}}),M}function _(e,t,a){let i=((e,n)=>{const t=e&&e.exec(n) +;return t&&0===t.index})(e.endRe,a);if(i){if(e["on:end"]){const a=new n(e) +;e["on:end"](t,a),a.isMatchIgnored&&(i=!1)}if(i){ +for(;e.endsParent&&e.parent;)e=e.parent;return e}} +if(e.endsWithParent)return _(e.parent,t,a)}function h(e){ +return 0===M.matcher.regexIndex?(C+=e[0],1):(I=!0,0)}function y(e){ +const n=e[0],a=t.substring(e.index),i=_(M,e,a);if(!i)return Y;const r=M +;M.endScope&&M.endScope._wrap?(g(), +u(n,M.endScope._wrap)):M.endScope&&M.endScope._multi?(g(), +b(M.endScope,e)):r.skip?C+=n:(r.returnEnd||r.excludeEnd||(C+=n), +g(),r.excludeEnd&&(C=n));do{ +M.scope&&S.closeNode(),M.skip||M.subLanguage||(T+=M.relevance),M=M.parent +}while(M!==i.parent);return i.starts&&m(i.starts,e),r.returnEnd?0:n.length} +let w={};function v(a,r){const o=r&&r[0];if(C+=a,null==o)return g(),0 +;if("begin"===w.type&&"end"===r.type&&w.index===r.index&&""===o){ +if(C+=t.slice(r.index,r.index+1),!s){const n=Error(`0 width match regex (${e})`) +;throw n.languageName=e,n.badRule=w.rule,n}return 1} +if(w=r,"begin"===r.type)return(e=>{ +const t=e[0],a=e.rule,i=new n(a),r=[a.__beforeBegin,a["on:begin"]] +;for(const n of r)if(n&&(n(e,i),i.isMatchIgnored))return h(t) +;return a.skip?C+=t:(a.excludeBegin&&(C+=t), +g(),a.returnBegin||a.excludeBegin||(C=t)),m(a,e),a.returnBegin?0:t.length})(r) +;if("illegal"===r.type&&!i){ +const e=Error('Illegal lexeme "'+o+'" for mode "'+(M.scope||"")+'"') +;throw e.mode=M,e}if("end"===r.type){const e=y(r);if(e!==Y)return e} +if("illegal"===r.type&&""===o)return r.index===t.length||(C+="\n"),1 +;if(D>1e5&&D>3*r.index)throw Error("potential infinite loop, way more iterations than matches") +;return C+=o,o.length}const k=N(e) +;if(!k)throw P(o.replace("{}",e)),Error('Unknown language: "'+e+'"') +;const x=W(k);let O="",M=r||x;const A={},S=new p.__emitter(p);(()=>{const e=[] +;for(let n=M;n!==k;n=n.parent)n.scope&&e.unshift(n.scope) +;e.forEach(e=>S.openNode(e))})();let C="",T=0,R=0,D=0,I=!1;try{ +if(k.__emitTokens)k.__emitTokens(t,S);else{for(M.matcher.considerAll();;){ +D++,I?I=!1:M.matcher.considerAll(),M.matcher.lastIndex=R +;const e=M.matcher.exec(t);if(!e)break;const n=v(t.substring(R,e.index),e) +;R=e.index+n}v(t.substring(R))}return S.finalize(),O=S.toHTML(),{language:e, +value:O,relevance:T,illegal:!1,_emitter:S,_top:M}}catch(n){ +if(n.message&&n.message.includes("Illegal"))return{language:e,value:V(t), +illegal:!0,relevance:0,_illegalBy:{message:n.message,index:R, +context:t.slice(R-100,R+100),mode:n.mode,resultSoFar:O},_emitter:S};if(s)return{ +language:e,value:V(t),illegal:!1,relevance:0,errorRaised:n,_emitter:S,_top:M} +;throw n}}function E(e,n){n=n||p.languages||Object.keys(a);const t=(e=>{ +const n={value:V(e),illegal:!1,relevance:0,_top:l,_emitter:new p.__emitter(p)} +;return n._emitter.addText(e),n})(e),i=n.filter(N).filter(x).map(n=>f(n,e,!1)) +;i.unshift(t);const r=i.sort((e,n)=>{ +if(e.relevance!==n.relevance)return n.relevance-e.relevance +;if(e.language&&n.language){if(N(e.language).supersetOf===n.language)return 1 +;if(N(n.language).supersetOf===e.language)return-1}return 0}),[s,o]=r,c=s +;return c.secondBest=o,c}function y(e){let n=null;const t=(e=>{ +let n=e.className+" ";n+=e.parentNode?e.parentNode.className:"" +;const t=p.languageDetectRe.exec(n);if(t){const n=N(t[1]) +;return n||(K(o.replace("{}",t[1])), +K("Falling back to no-highlight mode for this block.",e)),n?t[1]:"no-highlight"} +return n.split(/\s+/).find(e=>_(e)||N(e))})(e);if(_(t))return +;if(O("before:highlightElement",{el:e,language:t +}),e.dataset.highlighted)return void console.log("Element previously highlighted. To highlight again, first unset `dataset.highlighted`.",e) +;if(e.children.length>0&&(p.ignoreUnescapedHTML||(console.warn("One of your code blocks includes unescaped HTML. This is a potentially serious security risk."), +console.warn("https://github.com/highlightjs/highlight.js/wiki/security"), +console.warn("The element with unescaped HTML:"), +console.warn(e)),p.throwUnescapedHTML))throw new X("One of your code blocks includes unescaped HTML.",e.innerHTML) +;n=e;const a=n.textContent,r=t?h(a,{language:t,ignoreIllegals:!0}):E(a) +;e.innerHTML=r.value,e.dataset.highlighted="yes",((e,n,t)=>{const a=n&&i[n]||t +;e.classList.add("hljs"),e.classList.add("language-"+a) +})(e,t,r.language),e.result={language:r.language,re:r.relevance, +relevance:r.relevance},r.secondBest&&(e.secondBest={ +language:r.secondBest.language,relevance:r.secondBest.relevance +}),O("after:highlightElement",{el:e,result:r,text:a})}let w=!1;function v(){ +if("loading"===document.readyState)return w||window.addEventListener("DOMContentLoaded",()=>{ +v()},!1),void(w=!0);document.querySelectorAll(p.cssSelector).forEach(y)} +function N(e){return e=(e||"").toLowerCase(),a[e]||a[i[e]]} +function k(e,{languageName:n}){"string"==typeof e&&(e=[e]),e.forEach(e=>{ +i[e.toLowerCase()]=n})}function x(e){const n=N(e);return n&&!n.disableAutodetect +}function O(e,n){const t=e;r.forEach(e=>{e[t]&&e[t](n)})}Object.assign(t,{ +highlight:h,highlightAuto:E,highlightAll:v,highlightElement:y, +highlightBlock:e=>(H("10.7.0","highlightBlock will be removed entirely in v12.0"), +H("10.7.0","Please use highlightElement now."),y(e)),configure:e=>{p=J(p,e)}, +initHighlighting:()=>{ +v(),H("10.6.0","initHighlighting() deprecated. Use highlightAll() now.")}, +initHighlightingOnLoad:()=>{ +v(),H("10.6.0","initHighlightingOnLoad() deprecated. Use highlightAll() now.") +},registerLanguage:(e,n)=>{let i=null;try{i=n(t)}catch(n){ +if(P("Language definition for '{}' could not be registered.".replace("{}",e)), +!s)throw n;P(n),i=l} +i.name||(i.name=e),a[e]=i,i.rawDefinition=n.bind(null,t),i.aliases&&k(i.aliases,{ +languageName:e})},unregisterLanguage:e=>{delete a[e] +;for(const n of Object.keys(i))i[n]===e&&delete i[n]}, +listLanguages:()=>Object.keys(a),getLanguage:N,registerAliases:k, +autoDetection:x,inherit:J,addPlugin:e=>{(e=>{ +e["before:highlightBlock"]&&!e["before:highlightElement"]&&(e["before:highlightElement"]=n=>{ +e["before:highlightBlock"](Object.assign({block:n.el},n)) +}),e["after:highlightBlock"]&&!e["after:highlightElement"]&&(e["after:highlightElement"]=n=>{ +e["after:highlightBlock"](Object.assign({block:n.el},n))})})(e),r.push(e)}, +removePlugin:e=>{const n=r.indexOf(e);-1!==n&&r.splice(n,1)}}),t.debugMode=()=>{ +s=!1},t.safeMode=()=>{s=!0},t.versionString="11.12.0",t.regex={concat:b, +lookahead:d,either:m,optional:u,anyNumberOfTimes:g} +;for(const n in C)"object"==typeof C[n]&&e(C[n]);return Object.assign(t,C),t +},ne=ee({});ne.newInstance=()=>ee({});const te="[A-Za-z$_][0-9A-Za-z$_]*",ae={ +scope:"number", +match:"([-+]?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)|NaN|[-+]?Infinity", +relevance:0 +},ie=["as","in","of","if","for","while","finally","var","new","function","do","return","void","else","break","catch","instanceof","with","throw","case","default","try","switch","continue","typeof","delete","let","yield","const","class","debugger","async","await","static","import","from","export","extends","using"],re=["true","false","null","undefined","NaN","Infinity"],se=["Object","Function","Boolean","Symbol","Math","Date","Number","BigInt","String","RegExp","Array","Float32Array","Float64Array","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Int32Array","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array","Set","Map","WeakSet","WeakMap","ArrayBuffer","SharedArrayBuffer","Atomics","DataView","JSON","Promise","Generator","GeneratorFunction","AsyncFunction","Reflect","Proxy","Intl","WebAssembly"],oe=["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"],ce=["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],le=["arguments","this","super","console","window","document","localStorage","sessionStorage","module","self","global"],de=[].concat(ce,se,oe) +;function ge(e){const n=e.regex,t=te,a={begin:/<[A-Za-z0-9\\._:-]+/, +end:/\/[A-Za-z0-9\\._:-]+>|\/>/,isTrulyOpeningTag:(e,n)=>{ +const t=e[0].length+e.index,a=e.input[t] +;if("<"===a||","===a)return void n.ignoreMatch();let i +;">"===a&&(((e,{after:n})=>{const t="e+"\\s*\\("), +n.concat("(?!",N.join("|"),")")),t,n.lookahead(/\s*\(/)), +className:"title.function",relevance:0};var N;const k={ +begin:n.concat(/\./,n.lookahead(n.concat(t,/(?![0-9A-Za-z$_(])/))),end:t, +excludeBegin:!0,keywords:"prototype",className:"property",relevance:0},x={ +match:[/get|set/,/\s+/,t,/(?=\()/],className:{1:"keyword",3:"title.function"}, +contains:[{begin:/\(\)/},f] +},O="(\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|"+e.UNDERSCORE_IDENT_RE+")\\s*=>",M={ +match:[/const|var|let/,/\s+/,t,/\s*/,/=\s*/,/(async\s*)?/,n.lookahead(O)], +keywords:"async",className:{1:"keyword",3:"title.function"},contains:[f]} +;return{name:"JavaScript",aliases:["js","jsx","mjs","cjs"],keywords:i,exports:{ +PARAMS_CONTAINS:h,CLASS_REFERENCE:y},illegal:/#(?![$_A-Za-z])/, +contains:[e.SHEBANG({label:"shebang",binary:"node",relevance:5}),{ +label:"use_strict",className:"meta",relevance:10, +begin:/^\s*['"]use (strict|asm)['"]/ +},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,d,g,u,b,m,{match:/\$\d+/},c,y,{ +scope:"attr",match:t+n.lookahead(":"),relevance:0},M,{ +begin:"("+e.RE_STARTERS_RE+"|\\b(case|return|throw)\\b)\\s*", +keywords:"return throw case",relevance:0,contains:[m,e.REGEXP_MODE,{ +className:"function",begin:O,returnBegin:!0,end:"\\s*=>",contains:[{ +className:"params",variants:[{begin:e.UNDERSCORE_IDENT_RE,relevance:0},{ +className:null,begin:/\(\s*\)/,skip:!0},{begin:/(\s*)\(/,end:/\)/, +excludeBegin:!0,excludeEnd:!0,keywords:i,contains:h}]}]},{begin:/,/,relevance:0 +},{match:/\s+/,relevance:0},{variants:[{begin:"<>",end:""},{ +match:/<[A-Za-z0-9\\._:-]+\s*\/>/},{begin:a.begin, +"on:begin":a.isTrulyOpeningTag,end:a.end}],subLanguage:"xml",contains:[{ +begin:a.begin,end:a.end,skip:!0,contains:["self"]}]}]},w,{ +beginKeywords:"while if switch catch for"},{ +begin:"\\b(?!function)"+e.UNDERSCORE_IDENT_RE+"\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{", +returnBegin:!0,label:"func.def",contains:[f,e.inherit(e.TITLE_MODE,{begin:t, +className:"title.function"})]},{match:/\.\.\./,relevance:0},k,{match:"\\$"+t, +relevance:0},{match:[/\bconstructor(?=\s*\()/],className:{1:"title.function"}, +contains:[f]},v,{relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/, +className:"variable.constant"},E,x,{match:/\$[(.]/}]}} +const ue=e=>b(/\b/,e,/\w$/.test(e)?/\b/:/\B/),be=["Protocol","Type"].map(ue),me=["init","self"].map(ue),pe=["Any","Self"],_e=["actor","any","associatedtype","async","await",/as\?/,/as!/,"as","borrowing","break","case","catch","class","consume","consuming","continue","convenience","copy","default","defer","deinit","didSet","distributed","do","dynamic","each","else","enum","extension","fallthrough",/fileprivate\(set\)/,"fileprivate","final","for","func","get","guard","if","import","indirect","infix",/init\?/,/init!/,"inout",/internal\(set\)/,"internal","in","is","isolated","nonisolated","lazy","let","macro","mutating","nonmutating",/open\(set\)/,"open","operator","optional","override","package","postfix","precedencegroup","prefix",/private\(set\)/,"private","protocol",/public\(set\)/,"public","repeat","required","rethrows","return","set","some","static","struct","subscript","super","switch","throws","throw",/try\?/,/try!/,"try","typealias",/unowned\(safe\)/,/unowned\(unsafe\)/,"unowned","var","weak","where","while","willSet"],he=["false","nil","true"],fe=["assignment","associativity","higherThan","left","lowerThan","none","right"],Ee=["#colorLiteral","#column","#dsohandle","#else","#elseif","#endif","#error","#file","#fileID","#fileLiteral","#filePath","#function","#if","#imageLiteral","#keyPath","#line","#selector","#sourceLocation","#warning"],ye=["abs","all","any","assert","assertionFailure","debugPrint","dump","fatalError","getVaList","isKnownUniquelyReferenced","max","min","numericCast","pointwiseMax","pointwiseMin","precondition","preconditionFailure","print","readLine","repeatElement","sequence","stride","swap","swift_unboxFromSwiftValueWithType","transcode","type","unsafeBitCast","unsafeDowncast","withExtendedLifetime","withUnsafeMutablePointer","withUnsafePointer","withVaList","withoutActuallyEscaping","zip"],we=m(/[/=\-+!*%<>&|^~?]/,/[\u00A1-\u00A7]/,/[\u00A9\u00AB]/,/[\u00AC\u00AE]/,/[\u00B0\u00B1]/,/[\u00B6\u00BB\u00BF\u00D7\u00F7]/,/[\u2016-\u2017]/,/[\u2020-\u2027]/,/[\u2030-\u203E]/,/[\u2041-\u2053]/,/[\u2055-\u205E]/,/[\u2190-\u23FF]/,/[\u2500-\u2775]/,/[\u2794-\u2BFF]/,/[\u2E00-\u2E7F]/,/[\u3001-\u3003]/,/[\u3008-\u3020]/,/[\u3030]/),ve=m(we,/[\u0300-\u036F]/,/[\u1DC0-\u1DFF]/,/[\u20D0-\u20FF]/,/[\uFE00-\uFE0F]/,/[\uFE20-\uFE2F]/),Ne=b(we,ve,"*"),ke=m(/[a-zA-Z_]/,/[\u00A8\u00AA\u00AD\u00AF\u00B2-\u00B5\u00B7-\u00BA]/,/[\u00BC-\u00BE\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF]/,/[\u0100-\u02FF\u0370-\u167F\u1681-\u180D\u180F-\u1DBF]/,/[\u1E00-\u1FFF]/,/[\u200B-\u200D\u202A-\u202E\u203F-\u2040\u2054\u2060-\u206F]/,/[\u2070-\u20CF\u2100-\u218F\u2460-\u24FF\u2776-\u2793]/,/[\u2C00-\u2DFF\u2E80-\u2FFF]/,/[\u3004-\u3007\u3021-\u302F\u3031-\u303F\u3040-\uD7FF]/,/[\uF900-\uFD3D\uFD40-\uFDCF\uFDF0-\uFE1F\uFE30-\uFE44]/,/[\uFE47-\uFEFE\uFF00-\uFFFD]/),xe=m(ke,/\d/,/[\u0300-\u036F\u1DC0-\u1DFF\u20D0-\u20FF\uFE20-\uFE2F]/),Oe=b(ke,xe,"*"),Me=b(/[A-Z]/,xe,"*"),Ae=["attached","autoclosure",b(/convention\(/,m("swift","block","c"),/\)/),"discardableResult","dynamicCallable","dynamicMemberLookup","escaping","freestanding","frozen","GKInspectable","IBAction","IBDesignable","IBInspectable","IBOutlet","IBSegueAction","inlinable","main","nonobjc","NSApplicationMain","NSCopying","NSManaged",b(/objc\(/,Oe,/\)/),"objc","objcMembers","propertyWrapper","requires_stored_property_inits","resultBuilder","Sendable","testable","UIApplicationMain","unchecked","unknown","usableFromInline","warn_unqualified_access"],Se=["iOS","iOSApplicationExtension","macOS","macOSApplicationExtension","macCatalyst","macCatalystApplicationExtension","watchOS","watchOSApplicationExtension","tvOS","tvOSApplicationExtension","swift"],Ce=e=>({ +IMPORTANT:{scope:"meta",begin:"!important"}, +BLOCK_COMMENT:e.C_BLOCK_COMMENT_MODE,HEXCOLOR:{scope:"number", +begin:/#(([0-9a-fA-F]{3,4})|(([0-9a-fA-F]{2}){3,4}))\b/},UNICODE_RANGE:{ +scope:"number", +begin:/\b[Uu]\+[0-9A-Fa-f][0-9A-Fa-f?]{0,5}(-[0-9A-Fa-f][0-9A-Fa-f]{0,5})?/}, +FUNCTION_DISPATCH:{className:"built_in",begin:/[\w-]+(?=\()/}, +ATTRIBUTE_SELECTOR_MODE:{scope:"selector-attr",begin:/\[/,end:/\]/,illegal:"$", +contains:[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},CSS_NUMBER_MODE:{ +scope:"number", +begin:e.NUMBER_RE+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?", +relevance:0},CSS_VARIABLE:{className:"attr",begin:/--[A-Za-z_][A-Za-z0-9_-]*/} +}),Te=["a","abbr","address","article","aside","audio","b","blockquote","body","button","canvas","caption","cite","code","dd","del","details","dfn","div","dl","dt","em","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","html","i","iframe","img","input","ins","kbd","label","legend","li","main","mark","menu","nav","object","ol","optgroup","option","p","picture","q","quote","samp","section","select","source","span","strong","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","tr","ul","var","video","defs","g","marker","mask","pattern","svg","switch","symbol","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feFlood","feGaussianBlur","feImage","feMerge","feMorphology","feOffset","feSpecularLighting","feTile","feTurbulence","linearGradient","radialGradient","stop","circle","ellipse","image","line","path","polygon","polyline","rect","text","use","textPath","tspan","foreignObject","clipPath"],Re=["any-hover","any-pointer","aspect-ratio","color","color-gamut","color-index","device-aspect-ratio","device-height","device-width","display-mode","forced-colors","grid","height","hover","inverted-colors","monochrome","orientation","overflow-block","overflow-inline","pointer","prefers-color-scheme","prefers-contrast","prefers-reduced-motion","prefers-reduced-transparency","resolution","scan","scripting","update","width","min-width","max-width","min-height","max-height"].sort().reverse(),De=["active","any-link","blank","checked","current","default","defined","dir","disabled","drop","empty","enabled","first","first-child","first-of-type","fullscreen","future","focus","focus-visible","focus-within","has","host","host-context","hover","indeterminate","in-range","invalid","is","lang","last-child","last-of-type","left","link","local-link","not","nth-child","nth-col","nth-last-child","nth-last-col","nth-last-of-type","nth-of-type","only-child","only-of-type","optional","out-of-range","past","placeholder-shown","read-only","read-write","required","right","root","scope","target","target-within","user-invalid","valid","visited","where"].sort().reverse(),Ie=["after","backdrop","before","cue","cue-region","first-letter","first-line","grammar-error","marker","part","placeholder","selection","slotted","spelling-error"].sort().reverse(),Le=["accent-color","align-content","align-items","align-self","alignment-baseline","all","anchor-name","animation","animation-composition","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-range","animation-range-end","animation-range-start","animation-timeline","animation-timing-function","appearance","aspect-ratio","backdrop-filter","backface-visibility","background","background-attachment","background-blend-mode","background-clip","background-color","background-image","background-origin","background-position","background-position-x","background-position-y","background-repeat","background-size","baseline-shift","block-size","border","border-block","border-block-color","border-block-end","border-block-end-color","border-block-end-style","border-block-end-width","border-block-start","border-block-start-color","border-block-start-style","border-block-start-width","border-block-style","border-block-width","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-end-end-radius","border-end-start-radius","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-inline","border-inline-color","border-inline-end","border-inline-end-color","border-inline-end-style","border-inline-end-width","border-inline-start","border-inline-start-color","border-inline-start-style","border-inline-start-width","border-inline-style","border-inline-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-start-end-radius","border-start-start-radius","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-align","box-decoration-break","box-direction","box-flex","box-flex-group","box-lines","box-ordinal-group","box-orient","box-pack","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","caret-color","clear","clip","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","color-scheme","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","contain","contain-intrinsic-block-size","contain-intrinsic-height","contain-intrinsic-inline-size","contain-intrinsic-size","contain-intrinsic-width","container","container-name","container-type","content","content-visibility","corner-bottom-left-shape","corner-bottom-right-shape","corner-shape","corner-top-left-shape","corner-top-right-shape","counter-increment","counter-reset","counter-set","cue","cue-after","cue-before","cursor","cx","cy","direction","display","dominant-baseline","empty-cells","enable-background","field-sizing","fill","fill-opacity","fill-rule","filter","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","flood-color","flood-opacity","flow","font","font-display","font-family","font-feature-settings","font-kerning","font-language-override","font-optical-sizing","font-palette","font-size","font-size-adjust","font-smooth","font-smoothing","font-stretch","font-style","font-synthesis","font-synthesis-position","font-synthesis-small-caps","font-synthesis-style","font-synthesis-weight","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-emoji","font-variant-ligatures","font-variant-numeric","font-variant-position","font-variation-settings","font-weight","forced-color-adjust","gap","glyph-orientation-horizontal","glyph-orientation-vertical","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-column","grid-column-end","grid-column-start","grid-gap","grid-row","grid-row-end","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphenate-character","hyphenate-limit-chars","hyphens","icon","image-orientation","image-rendering","image-resolution","ime-mode","initial-letter","initial-letter-align","inline-size","inset","inset-area","inset-block","inset-block-end","inset-block-start","inset-inline","inset-inline-end","inset-inline-start","isolation","justify-content","justify-items","justify-self","kerning","left","letter-spacing","lighting-color","line-break","line-height","line-height-step","list-style","list-style-image","list-style-position","list-style-type","margin","margin-block","margin-block-end","margin-block-start","margin-bottom","margin-inline","margin-inline-end","margin-inline-start","margin-left","margin-right","margin-top","margin-trim","marker","marker-end","marker-mid","marker-start","marks","mask","mask-border","mask-border-mode","mask-border-outset","mask-border-repeat","mask-border-slice","mask-border-source","mask-border-width","mask-clip","mask-composite","mask-image","mask-mode","mask-origin","mask-position","mask-repeat","mask-size","mask-type","masonry-auto-flow","math-depth","math-shift","math-style","max-block-size","max-height","max-inline-size","max-width","min-block-size","min-height","min-inline-size","min-width","mix-blend-mode","nav-down","nav-index","nav-left","nav-right","nav-up","none","normal","object-fit","object-position","offset","offset-anchor","offset-distance","offset-path","offset-position","offset-rotate","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-anchor","overflow-block","overflow-clip-margin","overflow-inline","overflow-wrap","overflow-x","overflow-y","overlay","overscroll-behavior","overscroll-behavior-block","overscroll-behavior-inline","overscroll-behavior-x","overscroll-behavior-y","padding","padding-block","padding-block-end","padding-block-start","padding-bottom","padding-inline","padding-inline-end","padding-inline-start","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","paint-order","pause","pause-after","pause-before","perspective","perspective-origin","place-content","place-items","place-self","pointer-events","position","position-anchor","position-visibility","print-color-adjust","quotes","r","resize","rest","rest-after","rest-before","right","rotate","row-gap","ruby-align","ruby-position","scale","scroll-behavior","scroll-margin","scroll-margin-block","scroll-margin-block-end","scroll-margin-block-start","scroll-margin-bottom","scroll-margin-inline","scroll-margin-inline-end","scroll-margin-inline-start","scroll-margin-left","scroll-margin-right","scroll-margin-top","scroll-padding","scroll-padding-block","scroll-padding-block-end","scroll-padding-block-start","scroll-padding-bottom","scroll-padding-inline","scroll-padding-inline-end","scroll-padding-inline-start","scroll-padding-left","scroll-padding-right","scroll-padding-top","scroll-snap-align","scroll-snap-stop","scroll-snap-type","scroll-timeline","scroll-timeline-axis","scroll-timeline-name","scrollbar-color","scrollbar-gutter","scrollbar-width","shape-image-threshold","shape-margin","shape-outside","shape-rendering","speak","speak-as","src","stop-color","stop-opacity","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","tab-size","table-layout","text-align","text-align-all","text-align-last","text-anchor","text-combine-upright","text-decoration","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-skip-ink","text-decoration-style","text-decoration-thickness","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-indent","text-justify","text-orientation","text-overflow","text-rendering","text-shadow","text-size-adjust","text-transform","text-underline-offset","text-underline-position","text-wrap","text-wrap-mode","text-wrap-style","timeline-scope","top","touch-action","transform","transform-box","transform-origin","transform-style","transition","transition-behavior","transition-delay","transition-duration","transition-property","transition-timing-function","translate","unicode-bidi","unicode-range","user-modify","user-select","vector-effect","vertical-align","view-timeline","view-timeline-axis","view-timeline-inset","view-timeline-name","view-transition-name","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","white-space","white-space-collapse","widows","width","will-change","word-break","word-spacing","word-wrap","writing-mode","x","y","z-index","zoom"].sort().reverse(),Be=De.concat(Ie).sort().reverse() +;var Fe="[0-9](_*[0-9])*",$e=`\\.(${Fe})`,ze="[0-9a-fA-F](_*[0-9a-fA-F])*",Ue={ +className:"number",variants:[{ +begin:`(\\b(${Fe})((${$e})|\\.)?|(${$e}))[eE][+-]?(${Fe})[fFdD]?\\b`},{ +begin:`\\b(${Fe})((${$e})[fFdD]?\\b|\\.([fFdD]\\b)?)`},{ +begin:`(${$e})[fFdD]?\\b`},{begin:`\\b(${Fe})[fFdD]\\b`},{ +begin:`\\b0[xX]((${ze})\\.?|(${ze})?\\.(${ze}))[pP][+-]?(${Fe})[fFdD]?\\b`},{ +begin:"\\b(0|[1-9](_*[0-9])*)[lL]?\\b"},{begin:`\\b0[xX](${ze})[lL]?\\b`},{ +begin:"\\b0(_*[0-7])*[lL]?\\b"},{begin:"\\b0[bB][01](_*[01])*[lL]?\\b"}], +relevance:0};function je(e,n,t){return-1===t?"":e.replace(n,a=>je(e,n,t-1))} +var Pe=Object.freeze({__proto__:null,grmr_bash:e=>{const n=e.regex,t={},a={ +begin:/\$\{/,end:/\}/,contains:["self",{begin:/:-/,contains:[t]}]} +;Object.assign(t,{className:"variable",variants:[{ +begin:n.concat(/\$[\w\d#@][\w\d_]*/,"(?![\\w\\d])(?![$])")},a]});const i={ +className:"subst",begin:/\$\(/,end:/\)/,contains:[e.BACKSLASH_ESCAPE] +},r=e.inherit(e.COMMENT(),{match:[/(^|\s)/,/#.*$/],scope:{2:"comment"}}),s={ +begin:/<<-?\s*(?=\w+)/,starts:{contains:[e.END_SAME_AS_BEGIN({begin:/(\w+)/, +end:/(\w+)/,className:"string"})]}},o={className:"string",begin:/"/,end:/"/, +contains:[e.BACKSLASH_ESCAPE,t,i]};i.contains.push(o);const c={begin:/\$?\(\(/, +end:/\)\)/,contains:[{begin:/\d+#[0-9a-f]+/,className:"number"},e.NUMBER_MODE,t] +},l=e.SHEBANG({binary:"(fish|bash|zsh|sh|csh|ksh|tcsh|dash|scsh)",relevance:10 +}),d={className:"function",begin:/\w[\w\d_]*\s*\(\s*\)\s*\{/,returnBegin:!0, +contains:[e.inherit(e.TITLE_MODE,{begin:/\w[\w\d_]*/})],relevance:0};return{ +name:"Bash",aliases:["sh","zsh"],keywords:{$pattern:/\b[a-z][a-z0-9._-]+\b/, +keyword:["if","then","else","elif","fi","time","for","while","until","in","do","done","case","esac","coproc","function","select"], +literal:["true","false"], +built_in:["break","cd","continue","eval","exec","exit","export","getopts","hash","pwd","readonly","return","shift","test","times","trap","umask","unset","alias","bind","builtin","caller","command","declare","echo","enable","help","let","local","logout","mapfile","printf","read","readarray","source","sudo","type","typeset","ulimit","unalias","set","shopt","autoload","bg","bindkey","bye","cap","chdir","clone","comparguments","compcall","compctl","compdescribe","compfiles","compgroups","compquote","comptags","comptry","compvalues","dirs","disable","disown","echotc","echoti","emulate","fc","fg","float","functions","getcap","getln","history","integer","jobs","kill","limit","log","noglob","popd","print","pushd","pushln","rehash","sched","setcap","setopt","stat","suspend","ttyctl","unfunction","unhash","unlimit","unsetopt","vared","wait","whence","where","which","zcompile","zformat","zftp","zle","zmodload","zparseopts","zprof","zpty","zregexparse","zsocket","zstyle","ztcp","chcon","chgrp","chown","chmod","cp","dd","df","dir","dircolors","ln","ls","mkdir","mkfifo","mknod","mktemp","mv","realpath","rm","rmdir","shred","sync","touch","truncate","vdir","b2sum","base32","base64","cat","cksum","comm","csplit","cut","expand","fmt","fold","head","join","md5sum","nl","numfmt","od","paste","ptx","pr","sha1sum","sha224sum","sha256sum","sha384sum","sha512sum","shuf","sort","split","sum","tac","tail","tr","tsort","unexpand","uniq","wc","arch","basename","chroot","date","dirname","du","echo","env","expr","factor","groups","hostid","id","link","logname","nice","nohup","nproc","pathchk","pinky","printenv","printf","pwd","readlink","runcon","seq","sleep","stat","stdbuf","stty","tee","test","timeout","tty","uname","unlink","uptime","users","who","whoami","yes"] +},contains:[l,e.SHEBANG(),d,c,r,s,{match:/(\/[a-z._-]+)+/},o,{match:/\\"/},{ +className:"string",begin:/'/,end:/'/},{match:/\\'/},t]}},grmr_c:e=>{ +const n=e.regex,t=e.COMMENT("//","$",{contains:[{begin:/\\\n/}] +}),a="decltype\\(auto\\)",i="[a-zA-Z_]\\w*::",r="("+a+"|"+n.optional(i)+"[a-zA-Z_]\\w*"+n.optional("<[^<>]+>")+")",s={ +className:"type",variants:[{begin:"\\b[a-z\\d_]*_t\\b"},{ +match:n.concat(/\batomic_/,n.either("bool","char","schar","uchar","short","ushort","int","uint","long","ulong","llong","ullong","char16_t","char32_t","wchar_t","int_least8_t","uint_least8_t","int_least16_t","uint_least16_t","int_least32_t","uint_least32_t","int_least64_t","uint_least64_t","int_fast8_t","uint_fast8_t","int_fast16_t","uint_fast16_t","int_fast32_t","uint_fast32_t","int_fast64_t","uint_fast64_t","intptr_t","uintptr_t","size_t","ptrdiff_t","intmax_t","uintmax_t"),/\b/) +}]},o={className:"string",variants:[{begin:'(u8?|U|L)?"',end:'"',illegal:"\\n", +contains:[e.BACKSLASH_ESCAPE]},{ +begin:"(u8?|U|L)?'(\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)|.)", +end:"'",illegal:"."},e.END_SAME_AS_BEGIN({ +begin:/(?:u8?|U|L)?R"([^()\\\s"]{0,16})\(/,end:/\)([^()\\\s"]{0,16})"/})]},c={ +className:"number",variants:[{match:/\b(0b[01']+)/},{ +match:/(-?)\b([\d']+(\.[\d']*)?|\.[\d']+)((ll|LL|l|L)(u|U)?|(u|U)(ll|LL|l|L)?|f|F|b|B)/ +},{ +match:/(-?)\b(0[xX][a-fA-F0-9]+(?:'[a-fA-F0-9]+)*(?:\.[a-fA-F0-9]*(?:'[a-fA-F0-9]*)*)?(?:[pP][-+]?[0-9]+)?(l|L)?(u|U)?)/ +},{match:/(-?)\b\d+(?:'\d+)*(?:\.\d*(?:'\d*)*)?(?:[eE][-+]?\d+)?/}],relevance:0 +},l={scope:"meta",begin:/#\s*include\b/,end:/$/,keywords:{keyword:"include"}, +contains:[{begin:/\\\n/},o,{scope:"string",begin:/<.*?>/ +},t,e.C_BLOCK_COMMENT_MODE]},d={className:"meta",begin:/#\s*[a-z]+\b/,end:/$/, +keywords:{ +keyword:"if else elif endif define undef warning error line pragma _Pragma ifdef ifndef elifdef elifndef include" +},contains:[{begin:/\\\n/,relevance:0},e.inherit(o,{className:"string" +}),t,e.C_BLOCK_COMMENT_MODE]},g=[l,d],u={className:"title", +begin:n.optional(i)+e.IDENT_RE,relevance:0 +},b=n.optional(i)+e.IDENT_RE+"\\s*\\(",m={ +keyword:["asm","auto","break","case","continue","default","do","else","enum","extern","for","fortran","goto","if","inline","register","restrict","return","sizeof","typeof","typeof_unqual","struct","switch","typedef","union","volatile","while","_Alignas","_Alignof","_Atomic","_Generic","_Noreturn","_Static_assert","_Thread_local","alignas","alignof","noreturn","static_assert","thread_local","_Pragma"], +type:["float","double","signed","unsigned","int","short","long","char","void","_Bool","_BitInt","_Complex","_Imaginary","_Decimal32","_Decimal64","_Decimal96","_Decimal128","_Decimal64x","_Decimal128x","_Float16","_Float32","_Float64","_Float128","_Float32x","_Float64x","_Float128x","const","static","constexpr","complex","bool","imaginary"], +literal:"true false NULL", +built_in:"std string wstring cin cout cerr clog stdin stdout stderr stringstream istringstream ostringstream auto_ptr deque list queue stack vector map set pair bitset multiset multimap unordered_set unordered_map unordered_multiset unordered_multimap priority_queue make_pair array shared_ptr abort terminate abs acos asin atan2 atan calloc ceil cosh cos exit exp fabs floor fmod fprintf fputs free frexp fscanf future isalnum isalpha iscntrl isdigit isgraph islower isprint ispunct isspace isupper isxdigit tolower toupper labs ldexp log10 log malloc realloc memchr memcmp memcpy memset modf pow printf putchar puts scanf sinh sin snprintf sprintf sqrt sscanf strcat strchr strcmp strcpy strcspn strlen strncat strncmp strncpy strpbrk strrchr strspn strstr tanh tan vfprintf vprintf vsprintf endl initializer_list unique_ptr" +},p=[...g,s,t,e.C_BLOCK_COMMENT_MODE,c,o],_={variants:[{begin:/=/,end:/;/},{ +begin:/\(/,end:/\)/},{beginKeywords:"new throw return else",end:/;/}], +keywords:m,contains:p.concat([{begin:/\(/,end:/\)/,keywords:m, +contains:p.concat(["self"]),relevance:0}]),relevance:0},h={ +begin:"("+r+"[\\*&\\s]+){1,12}"+b,returnBegin:!0,end:/[{;=]/,excludeEnd:!0, +keywords:m,illegal:/[^\w\s\*&:<>.]/,contains:[{begin:a,keywords:m,relevance:0},{ +begin:b,returnBegin:!0,contains:[e.inherit(u,{className:"title.function"})], +relevance:0},{relevance:0,match:/,/},{className:"params",begin:/\(/,end:/\)/, +keywords:m,relevance:0,contains:[t,e.C_BLOCK_COMMENT_MODE,o,c,s,{begin:/\(/, +end:/\)/,keywords:m,relevance:0,contains:["self",t,e.C_BLOCK_COMMENT_MODE,o,c,s] +}]},s,t,e.C_BLOCK_COMMENT_MODE,...g]};return{name:"C",aliases:["h"],keywords:m, +disableAutodetect:!0,illegal:"=]/,contains:[{ +beginKeywords:"final class struct"},e.TITLE_MODE]}]),exports:{preprocessor:d, +strings:o,keywords:m}}},grmr_cpp:e=>{const n=e.regex,t=e.COMMENT("//","$",{ +contains:[{begin:/\\\n/}] +}),a="decltype\\(auto\\)",i="[a-zA-Z_]\\w*::",r="(?!struct)("+a+"|"+n.optional(i)+"[a-zA-Z_]\\w*"+n.optional("<[^<>]+>")+")",s={ +className:"type",begin:"\\b[a-z\\d_]*_t\\b"},o={className:"string",variants:[{ +begin:'(u8?|U|L)?"',end:'"',illegal:"\\n",contains:[e.BACKSLASH_ESCAPE]},{ +begin:"(u8?|U|L)?'(\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)|.)", +end:"'",illegal:"."},e.END_SAME_AS_BEGIN({ +begin:/(?:u8?|U|L)?R"([^()\\\s"]{0,16})\(/,end:/\)([^()\\\s"]{0,16})"/})]},c={ +className:"number",variants:[{ +begin:"[+-]?(?:(?:\\b[0-9](?:'?[0-9])*\\.(?:[0-9](?:'?[0-9])*)?|\\.[0-9](?:'?[0-9])*)(?:[Ee][+-]?[0-9](?:'?[0-9])*)?|\\b[0-9](?:'?[0-9])*[Ee][+-]?[0-9](?:'?[0-9])*|\\b0[Xx](?:[0-9A-Fa-f](?:'?[0-9A-Fa-f])*(?:\\.(?:[0-9A-Fa-f](?:'?[0-9A-Fa-f])*)?)?|\\.[0-9A-Fa-f](?:'?[0-9A-Fa-f])*)[Pp][+-]?[0-9](?:'?[0-9])*)(?:[Ff](?:16|32|64|128)?|(BF|bf)16|[Ll]|)" +},{ +begin:"[+-]?\\b(?:0[Bb][01](?:'?[01])*|0[Xx][0-9A-Fa-f](?:'?[0-9A-Fa-f])*|0(?:'?[0-7])*|[1-9](?:'?[0-9])*)(?:[Uu](?:LL?|ll?)|[Uu][Zz]?|(?:LL?|ll?)[Uu]?|[Zz][Uu]|)" +}],relevance:0},l=[{scope:"meta",begin:/#\s*include\b/,end:/$/,keywords:{ +keyword:"include"},contains:[{begin:/\\\n/},o,{scope:"string",begin:/<.*?>/ +},t,e.C_BLOCK_COMMENT_MODE]},{className:"meta",begin:/#\s*[a-z]+\b/,end:/$/, +keywords:{ +keyword:"if else elif endif define undef warning error line pragma _Pragma ifdef ifndef include" +},contains:[{begin:/\\\n/,relevance:0},e.inherit(o,{className:"string" +}),t,e.C_BLOCK_COMMENT_MODE]}],d={className:"title", +begin:n.optional(i)+e.IDENT_RE,relevance:0 +},g=n.optional(i)+e.IDENT_RE+"\\s*\\(",u=["alignas","alignof","and","and_eq","asm","atomic_cancel","atomic_commit","atomic_noexcept","auto","bitand","bitor","break","case","catch","class","co_await","co_return","co_yield","compl","concept","const_cast|10","consteval","constexpr","constinit","continue","decltype","default","delete","do","dynamic_cast|10","else","enum","explicit","export","extern","false","final","for","friend","goto","if","import","inline","module","mutable","namespace","new","noexcept","not","not_eq","nullptr","operator","or","or_eq","override","private","protected","public","reflexpr","register","reinterpret_cast|10","requires","return","sizeof","static_assert","static_cast|10","struct","switch","synchronized","template","this","thread_local","throw","transaction_safe","transaction_safe_dynamic","true","try","typedef","typeid","typename","union","using","virtual","volatile","while","xor","xor_eq"],b={ +type:["bool","char","char16_t","char32_t","char8_t","double","float","int","long","short","void","wchar_t","unsigned","signed","const","static"], +keyword:u,literal:["NULL","false","nullopt","nullptr","true"], +built_in:["_Pragma"], +_type_hints:["any","auto_ptr","barrier","binary_semaphore","bitset","complex","condition_variable","condition_variable_any","counting_semaphore","deque","false_type","flat_map","flat_set","future","imaginary","initializer_list","istringstream","jthread","latch","lock_guard","multimap","multiset","mutex","optional","ostringstream","packaged_task","pair","promise","priority_queue","queue","recursive_mutex","recursive_timed_mutex","scoped_lock","set","shared_future","shared_lock","shared_mutex","shared_timed_mutex","shared_ptr","stack","string_view","stringstream","timed_mutex","thread","true_type","tuple","unique_lock","unique_ptr","unordered_map","unordered_multimap","unordered_multiset","unordered_set","variant","vector","weak_ptr","wstring","wstring_view"] +},m={className:"function.dispatch",relevance:0,keywords:{ +_hint:["abort","abs","acos","apply","as_const","asin","atan","atan2","calloc","ceil","cerr","cin","clog","cos","cosh","cout","declval","endl","exchange","exit","exp","fabs","floor","fmod","forward","fprintf","fputs","free","frexp","fscanf","future","invoke","isalnum","isalpha","iscntrl","isdigit","isgraph","islower","isprint","ispunct","isspace","isupper","isxdigit","labs","launder","ldexp","log","log10","make_pair","make_shared","make_shared_for_overwrite","make_tuple","make_unique","malloc","memchr","memcmp","memcpy","memset","modf","move","pow","printf","putchar","puts","realloc","scanf","sin","sinh","snprintf","sprintf","sqrt","sscanf","std","stderr","stdin","stdout","strcat","strchr","strcmp","strcpy","strcspn","strlen","strncat","strncmp","strncpy","strpbrk","strrchr","strspn","strstr","swap","tan","tanh","terminate","to_underlying","tolower","toupper","vfprintf","visit","vprintf","vsprintf"] +}, +begin:n.concat(/\b/,`(?!${u.join("|")})`,e.IDENT_RE,n.lookahead(/(<[^<>]+>|)\s*\(/)) +},p=[m,...l,s,t,e.C_BLOCK_COMMENT_MODE,c,o],_={variants:[{begin:/=/,end:/;/},{ +begin:/\(/,end:/\)/},{beginKeywords:"new throw return else",end:/;/}], +keywords:b,contains:p.concat([{begin:/\(/,end:/\)/,keywords:b, +contains:p.concat(["self"]),relevance:0}]),relevance:0},h={className:"function", +begin:"("+r+"[\\*&\\s]+){1,12}"+g,returnBegin:!0,end:/[{;=]/,excludeEnd:!0, +keywords:b,illegal:/[^\w\s\*&:<>.]/,contains:[{begin:a,keywords:b,relevance:0},{ +begin:g,returnBegin:!0,contains:[d],relevance:0},{begin:/::/,relevance:0},{ +begin:/:/,endsWithParent:!0,contains:[o,c]},{relevance:0,match:/,/},{ +className:"params",begin:/\(/,end:/\)/,keywords:b,relevance:0, +contains:[t,e.C_BLOCK_COMMENT_MODE,o,c,s,{begin:/\(/,end:/\)/,keywords:b, +relevance:0,contains:["self",t,e.C_BLOCK_COMMENT_MODE,o,c,s]}] +},s,t,e.C_BLOCK_COMMENT_MODE,...l]};return{name:"C++", +aliases:["cc","c++","h++","hpp","hh","hxx","cxx"],keywords:b,illegal:"",keywords:b,contains:["self",s]},{begin:e.IDENT_RE+"::",keywords:b},{ +match:[/\b(?:enum(?:\s+(?:class|struct))?|class|struct|union)/,/\s+/,/\w+/], +className:{1:"keyword",3:"title.class"}}])}},grmr_csharp:e=>{const n={ +keyword:["abstract","as","base","break","case","catch","class","const","continue","do","else","event","explicit","extern","finally","fixed","for","foreach","goto","if","implicit","in","interface","internal","is","lock","namespace","new","operator","out","override","params","private","protected","public","readonly","record","ref","return","scoped","sealed","sizeof","stackalloc","static","struct","switch","this","throw","try","typeof","unchecked","unsafe","using","virtual","void","volatile","while"].concat(["add","alias","and","ascending","args","async","await","by","descending","dynamic","equals","file","from","get","global","group","init","into","join","let","nameof","not","notnull","on","or","orderby","partial","record","remove","required","scoped","select","set","unmanaged","value|0","var","when","where","with","yield"]), +built_in:["bool","byte","char","decimal","delegate","double","dynamic","enum","float","int","long","nint","nuint","object","sbyte","short","string","ulong","uint","ushort"], +literal:["default","false","null","true"]},t=e.inherit(e.TITLE_MODE,{ +begin:"[a-zA-Z](\\.?\\w)*"}),a="\\d(_*\\d)*",i="([uU][lL]?|[lL][uU]?)?",r={ +className:"number",variants:[{begin:"\\b0[bB]_*[01](_*[01])*"+i},{ +begin:"(-?)\\b0[xX]_*[a-fA-F0-9](_*[a-fA-F0-9])*"+i},{ +begin:"(-?)(\\b"+a+"(\\.("+a+")?)?|\\."+a+")([eE][-+]?"+a+")?([fFdDmM]|[uU][lL]?|[lL][uU]?)?" +}],relevance:0},s={className:"string",begin:'@"',end:'"',contains:[{begin:'""'}] +},o=e.inherit(s,{illegal:/\n/}),c={className:"subst",begin:/\{/,end:/\}/, +keywords:n},l=e.inherit(c,{illegal:/\n/}),d={className:"string",begin:/\$"/, +end:'"',illegal:/\n/,contains:[{begin:/\{\{/},{begin:/\}\}/ +},e.BACKSLASH_ESCAPE,l]},g={className:"string",begin:/\$@"/,end:'"',contains:[{ +begin:/\{\{/},{begin:/\}\}/},{begin:'""'},c]},u=e.inherit(g,{illegal:/\n/, +contains:[{begin:/\{\{/},{begin:/\}\}/},{begin:'""'},l]}) +;c.contains=[g,d,s,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,r,e.C_BLOCK_COMMENT_MODE], +l.contains=[u,d,o,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,r,e.inherit(e.C_BLOCK_COMMENT_MODE,{ +illegal:/\n/})];const b={variants:[{className:"string", +begin:/"""("*)(?!")(.|\n)*?"""\1/,relevance:1 +},g,d,s,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},m={begin:"<",end:">", +contains:[{beginKeywords:"in out"},t] +},p=e.IDENT_RE+"(<"+e.IDENT_RE+"(\\s*,\\s*"+e.IDENT_RE+")*>)?(\\[\\])?",_={ +begin:"@"+e.IDENT_RE,relevance:0};return{name:"C#",aliases:["cs","c#"], +keywords:n,illegal:/::/,contains:[e.COMMENT("///","$",{returnBegin:!0, +contains:[{className:"doctag",variants:[{begin:"///",relevance:0},{ +begin:"\x3c!--|--\x3e"},{begin:""}]}] +}),e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,{className:"meta",begin:"#", +end:"$",keywords:{ +keyword:"if else elif endif define undef warning error line region endregion pragma checksum" +}},b,r,{beginKeywords:"class interface",relevance:0,end:/[{;=]/, +illegal:/[^\s:,]/,contains:[{beginKeywords:"where class" +},t,m,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{beginKeywords:"namespace", +relevance:0,end:/[{;=]/,illegal:/[^\s:]/, +contains:[t,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{ +beginKeywords:"record",relevance:0,end:/[{;=]/,illegal:/[^\s:]/, +contains:[t,m,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{className:"meta", +begin:"^\\s*\\[(?=[\\w])",excludeBegin:!0,end:"\\]",excludeEnd:!0,contains:[{ +className:"string",begin:/"/,end:/"/}]},{ +beginKeywords:"new return throw await else",relevance:0},{className:"function", +begin:"("+p+"\\s+)+"+e.IDENT_RE+"\\s*(<[^=]+>\\s*)?\\(",returnBegin:!0, +end:/\s*[{;=]/,excludeEnd:!0,keywords:n,contains:[{ +beginKeywords:"public private protected static internal protected abstract async extern override unsafe virtual new sealed partial", +relevance:0},{begin:e.IDENT_RE+"\\s*(<[^=]+>\\s*)?\\(",returnBegin:!0, +contains:[e.TITLE_MODE,m],relevance:0},{match:/\(\)/},{className:"params", +begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:n,relevance:0, +contains:[b,r,e.C_BLOCK_COMMENT_MODE] +},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},_]}},grmr_css:e=>{ +const n=e.regex,t=Ce(e),a=[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE];return{ +name:"CSS",case_insensitive:!0,illegal:/[=|'\$]/,keywords:{ +keyframePosition:"from to"},classNameAliases:{keyframePosition:"selector-tag"}, +contains:[t.BLOCK_COMMENT,{begin:/-(webkit|moz|ms|o)-(?=[a-z])/ +},t.CSS_NUMBER_MODE,{className:"selector-id",begin:/#[A-Za-z0-9_-]+/,relevance:0 +},{className:"selector-class",begin:"\\.[a-zA-Z-][a-zA-Z0-9_-]*",relevance:0 +},t.ATTRIBUTE_SELECTOR_MODE,{className:"selector-pseudo",variants:[{ +begin:":("+De.join("|")+")"},{begin:":(:)?("+Ie.join("|")+")"}] +},t.CSS_VARIABLE,{className:"attribute",begin:"\\b("+Le.join("|")+")\\b"},{ +begin:/:/,end:/[;}{]/, +contains:[t.BLOCK_COMMENT,t.HEXCOLOR,t.IMPORTANT,t.CSS_NUMBER_MODE,t.UNICODE_RANGE,...a,{ +begin:/(url|data-uri)\(/,end:/\)/,relevance:0,keywords:{built_in:"url data-uri" +},contains:[...a,{className:"string",begin:/[^)]/,endsWithParent:!0, +excludeEnd:!0}]},t.FUNCTION_DISPATCH]},{begin:n.lookahead(/@/),end:"[{;]", +relevance:0,illegal:/:/,contains:[{className:"keyword",begin:/@-?\w[\w]*(-\w+)*/ +},{begin:/\s/,endsWithParent:!0,excludeEnd:!0,relevance:0,keywords:{ +$pattern:/[a-z-]+/,keyword:"and or not only",attribute:Re.join(" ")},contains:[{ +begin:/[a-z-]+(?=:)/,className:"attribute"},...a,t.CSS_NUMBER_MODE]}]},{ +className:"selector-tag",begin:"\\b("+Te.join("|")+")\\b"}]}},grmr_diff:e=>{ +const n=e.regex;return{name:"Diff",aliases:["patch"],contains:[{ +className:"meta",relevance:10, +match:n.either(/^@@ +-\d+,\d+ +\+\d+,\d+ +@@/,/^@@ +-\d+ +\+\d+,\d+ +@@/,/^@@ +-\d+,\d+ +\+\d+ +@@/,/^@@ +-\d+ +\+\d+ +@@/,/^\*\*\* +\d+,\d+ +\*\*\*\*$/,/^--- +\d+,\d+ +----$/) +},{className:"comment",variants:[{ +begin:n.either(/Index: /,/^index/,/={3,}/,/^-{3}/,/^\*{3} /,/^\+{3}/,/^diff --git/), +end:/$/},{match:/^\*{15}$/}]},{className:"addition",begin:/^\+/,end:/$/},{ +className:"deletion",begin:/^-/,end:/$/},{className:"addition",begin:/^!/, +end:/$/}]}},grmr_go:e=>{const n={ +keyword:["break","case","chan","const","continue","default","defer","else","fallthrough","for","func","go","goto","if","import","interface","map","package","range","return","select","struct","switch","type","var"], +type:["bool","byte","complex64","complex128","error","float32","float64","int8","int16","int32","int64","string","uint8","uint16","uint32","uint64","int","uint","uintptr","rune"], +literal:["true","false","iota","nil"], +built_in:["append","cap","close","complex","copy","imag","len","make","new","panic","print","println","real","recover","delete"] +};return{name:"Go",aliases:["golang"],keywords:n,illegal:"{const n=e.regex +;return{name:"GraphQL",aliases:["gql"],case_insensitive:!0,disableAutodetect:!1, +keywords:{ +keyword:["query","mutation","subscription","type","input","schema","directive","interface","union","scalar","fragment","enum","on"], +literal:["true","false","null"]}, +contains:[e.HASH_COMMENT_MODE,e.QUOTE_STRING_MODE,e.NUMBER_MODE,{ +scope:"punctuation",match:/[.]{3}/,relevance:0},{scope:"punctuation", +begin:/[\!\(\)\:\=\[\]\{\|\}]{1}/,relevance:0},{scope:"variable",begin:/\$/, +end:/\W/,excludeEnd:!0,relevance:0},{scope:"meta",match:/@\w+/,excludeEnd:!0},{ +scope:"symbol",begin:n.concat(/[_A-Za-z][_0-9A-Za-z]*/,n.lookahead(/\s*:/)), +relevance:0}],illegal:[/[;<']/,/BEGIN/]}},grmr_ini:e=>{const n=e.regex,t={ +className:"number",relevance:0,variants:[{begin:/([+-]+)?[\d]+_[\d_]+/},{ +begin:e.NUMBER_RE}]},a=e.COMMENT();a.variants=[{begin:/;/,end:/$/},{begin:/#/, +end:/$/}];const i={className:"variable",variants:[{begin:/\$[\w\d"][\w\d_]*/},{ +begin:/\$\{(.*?)\}/}]},r={className:"literal", +begin:/\bon|off|true|false|yes|no\b/},s={className:"string", +contains:[e.BACKSLASH_ESCAPE],variants:[{begin:"'''",end:"'''",relevance:10},{ +begin:'"""',end:'"""',relevance:10},{begin:'"',end:'"'},{begin:"'",end:"'"}] +},o={begin:/\[/,end:/\]/,contains:[a,r,i,s,t,"self"],relevance:0 +},c=n.either(/[A-Za-z0-9_-]+/,/"(\\"|[^"])*"/,/'[^']*'/);return{ +name:"TOML, also INI",aliases:["toml"],case_insensitive:!0,illegal:/\S/, +contains:[a,{className:"section",begin:/\[+/,end:/\]+/},{ +begin:n.concat(c,"(\\s*\\.\\s*",c,")*",n.lookahead(/\s*=\s*[^#\s]/)), +className:"attr",starts:{end:/$/,contains:[a,o,r,i,s,t]}}]}},grmr_java:e=>{ +const n=e.regex,t="[\xc0-\u02b8a-zA-Z_$][\xc0-\u02b8a-zA-Z_$0-9]*",a="(?:(?:\\s*\\[\\s*])+)?",i=t+"<@@@>"+a,r="(?:\\?(?:\\s+(?:extends|super)\\s+"+i+")?|"+i+")",s=je("(?:\\s*<\\s*"+r+"(?:\\s*,\\s*"+r+")*\\s*>)?",/<@@@>/g,2),o={ +keyword:["synchronized","abstract","private","var","static","if","const ","for","while","strictfp","finally","protected","import","native","final","void","enum","else","break","transient","catch","instanceof","volatile","case","assert","package","default","public","try","switch","continue","throws","protected","public","private","module","requires","exports","do","sealed","yield","permits","goto","when"], +literal:["false","true","null"], +type:["char","boolean","long","float","int","byte","short","double"], +built_in:["super","this"]},c={className:"meta",begin:"@"+t,contains:[{ +begin:/\(/,end:/\)/,contains:["self"]}]},l={className:"params",begin:/\(/, +end:/\)/,keywords:o,relevance:0,contains:[e.C_BLOCK_COMMENT_MODE],endsParent:!0} +;return{name:"Java",aliases:["jsp"],keywords:o,illegal:/<\/|#/, +contains:[e.COMMENT("/\\*\\*","\\*/",{relevance:0,contains:[{begin:/\w+@/, +relevance:0},{className:"doctag",begin:"@[A-Za-z]+"}]}),{ +begin:/import java\.[a-z]+\./,keywords:"import",relevance:2 +},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,{begin:/"""/,end:/"""/, +className:"string",contains:[e.BACKSLASH_ESCAPE] +},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,{ +match:[/\b(?:class|interface|enum|extends|implements|new)/,/\s+/,t],className:{ +1:"keyword",3:"title.class"}},{match:/non-sealed/,scope:"keyword"},{ +beginKeywords:"new throw return else yield assert",relevance:0},{ +begin:[t,n.concat(s,a,/\s+/),t,a,/\s*/,/=(?!=)/],className:{1:"type", +3:"variable",6:"operator"}},{begin:[/record/,/\s+/,t],className:{1:"keyword", +3:"title.class"},contains:[l,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{ +begin:[t,n.concat(s,a,/\s+/),t,/\s*(?=\()/],className:{1:"type", +3:"title.function"},keywords:o,contains:[{className:"params",begin:/\(/, +end:/\)/,keywords:o,relevance:0, +contains:[c,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,Ue,e.C_BLOCK_COMMENT_MODE] +},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},Ue,c]}},grmr_javascript:ge, +grmr_json:e=>{const n=["true","false","null"],t={scope:"literal", +beginKeywords:n.join(" ")};return{name:"JSON",aliases:["jsonc","json5"], +keywords:{literal:n},contains:[{className:"attr", +begin:/(("(\\.|[^\\"\r\n])*")|('(\\.|[^\\'\r\n])*'))(?=\s*:)/,relevance:1.01},{ +match:/[{}[\],:]/,className:"punctuation",relevance:0 +},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,t,ae,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE], +illegal:"\\S"}},grmr_kotlin:e=>{const n={ +keyword:"abstract as val var vararg get set class object open private protected public noinline crossinline dynamic final enum if else do while for when throw try catch finally import package is in fun override companion reified inline lateinit init interface annotation data sealed internal infix operator out by constructor super tailrec where const inner suspend typealias external expect actual", +built_in:"Byte Short Char Int Long Boolean Float Double Void Unit Nothing", +literal:"true false null"},t={className:"symbol",begin:e.UNDERSCORE_IDENT_RE+"@" +},a={className:"subst",begin:/\$\{/,end:/\}/,contains:[e.C_NUMBER_MODE]},i={ +className:"variable",begin:"\\$"+e.UNDERSCORE_IDENT_RE},r={className:"string", +variants:[{begin:'"""',end:'"""(?=[^"])',contains:[i,a]},{begin:"'",end:"'", +illegal:/\n/,contains:[e.BACKSLASH_ESCAPE]},{begin:'"',end:'"',illegal:/\n/, +contains:[e.BACKSLASH_ESCAPE,i,a]}]};a.contains.push(r);const s={ +className:"meta", +begin:"@(?:file|property|field|get|set|receiver|param|setparam|delegate)\\s*:(?:\\s*"+e.UNDERSCORE_IDENT_RE+")?" +},o={className:"meta",begin:"@"+e.UNDERSCORE_IDENT_RE,contains:[{begin:/\(/, +end:/\)/,contains:[e.inherit(r,{className:"string"}),"self"]}] +},c=Ue,l=e.COMMENT("/\\*","\\*/",{contains:[e.C_BLOCK_COMMENT_MODE]}),d={ +variants:[{className:"type",begin:e.UNDERSCORE_IDENT_RE},{begin:/\(/,end:/\)/, +contains:[]}]},g=d;return g.variants[1].contains=[d],d.variants[1].contains=[g], +{name:"Kotlin",aliases:["kt","kts","ktm","ktx"],keywords:n, +contains:[e.COMMENT("/\\*\\*","\\*/",{relevance:0,contains:[{className:"doctag", +begin:"@[A-Za-z]+"}]}),e.C_LINE_COMMENT_MODE,l,{className:"keyword", +begin:/\b(break|continue|return|this)\b/,starts:{contains:[{className:"symbol", +begin:/@\w+/}]}},t,s,o,{className:"function",beginKeywords:"fun",end:"[(]|$", +returnBegin:!0,excludeEnd:!0,keywords:n,relevance:5,contains:[{ +begin:e.UNDERSCORE_IDENT_RE+"\\s*\\(",returnBegin:!0,relevance:0, +contains:[e.UNDERSCORE_TITLE_MODE]},{className:"type",begin://, +keywords:"reified",relevance:0},{className:"params",begin:/\(/,end:/\)/, +endsParent:!0,keywords:n,relevance:0,contains:[{begin:/:/,end:/[=,\/]/, +endsWithParent:!0,contains:[d,e.C_LINE_COMMENT_MODE,l],relevance:0 +},e.C_LINE_COMMENT_MODE,l,s,o,r,e.C_NUMBER_MODE]},l]},{ +begin:[/class|interface|trait/,/\s+/,e.UNDERSCORE_IDENT_RE],beginScope:{ +3:"title.class"},keywords:"class interface trait",end:/[:\{(]|$/,excludeEnd:!0, +illegal:"extends implements",contains:[{ +beginKeywords:"public protected internal private constructor" +},e.UNDERSCORE_TITLE_MODE,{className:"type",begin://,excludeBegin:!0, +excludeEnd:!0,relevance:0},{className:"type",begin:/[,:]\s*/,end:/[<\(,){\s]|$/, +excludeBegin:!0,returnEnd:!0},s,o]},r,{className:"meta",begin:"^#!/usr/bin/env", +end:"$",illegal:"\n"},c]}},grmr_less:e=>{ +const n=Ce(e),t=Be,a="[\\w-]+",i="("+a+"|@\\{"+a+"\\})",r=[],s=[],o=e=>({ +className:"string",begin:"~?"+e+".*?"+e}),c=(e,n,t)=>({className:e,begin:n, +relevance:t}),l={$pattern:/[a-z-]+/,keyword:"and or not only", +attribute:Re.join(" ")},d={begin:"\\(",end:"\\)",contains:s,keywords:l, +relevance:0} +;s.push(e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,o("'"),o('"'),n.CSS_NUMBER_MODE,{ +begin:"(url|data-uri)\\(",starts:{className:"string",end:"[\\)\\n]", +excludeEnd:!0} +},n.UNICODE_RANGE,n.HEXCOLOR,d,c("variable","@@?"+a,10),c("variable","@\\{"+a+"\\}"),c("built_in","~?`[^`]*?`"),{ +className:"attribute",begin:a+"\\s*:",end:":",returnBegin:!0,excludeEnd:!0 +},n.IMPORTANT,{beginKeywords:"and not"},n.FUNCTION_DISPATCH);const g=s.concat({ +begin:/\{/,end:/\}/,contains:r}),u={beginKeywords:"when",endsWithParent:!0, +contains:[{beginKeywords:"and not"}].concat(s)},b={begin:i+"\\s*:", +returnBegin:!0,end:/[;}]/,relevance:0,contains:[{begin:/-(webkit|moz|ms|o)-/ +},n.CSS_VARIABLE,{className:"attribute",begin:"\\b("+Le.join("|")+")\\b", +end:/(?=:)/,starts:{endsWithParent:!0,illegal:"[<=$]",relevance:0,contains:s}}] +},m={className:"keyword", +begin:"@(import|media|charset|font-face|(-[a-z]+-)?keyframes|supports|document|namespace|page|viewport|host)\\b", +starts:{end:"[;{}]",keywords:l,returnEnd:!0,contains:s,relevance:0}},p={ +className:"variable",variants:[{begin:"@"+a+"\\s*:",relevance:15},{begin:"@"+a +}],starts:{end:"[;}]",returnEnd:!0,contains:g}},_={variants:[{ +begin:"[\\.#:&\\[>]",end:"[;{}]"},{begin:i,end:/\{/}],returnBegin:!0, +returnEnd:!0,illegal:"[<='$\"]",relevance:0, +contains:[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,u,c("keyword","all\\b"),c("variable","@\\{"+a+"\\}"),{ +begin:"\\b("+Te.join("|")+")\\b",className:"selector-tag" +},n.CSS_NUMBER_MODE,c("selector-tag",i,0),c("selector-id","#"+i),c("selector-class","\\."+i,0),c("selector-tag","&",0),n.ATTRIBUTE_SELECTOR_MODE,{ +className:"selector-pseudo",begin:":("+De.join("|")+")"},{ +className:"selector-pseudo",begin:":(:)?("+Ie.join("|")+")"},{begin:/\(/, +end:/\)/,relevance:0,contains:g},{begin:"!important"},n.FUNCTION_DISPATCH]},h={ +begin:a+":(:)?"+`(${t.join("|")})`,returnBegin:!0,contains:[_]} +;return r.push(e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,m,p,h,b,_,u,n.FUNCTION_DISPATCH), +{name:"Less",case_insensitive:!0,illegal:"[=>'/<($\"]",contains:r}}, +grmr_lua:e=>{const n="\\[=*\\[",t="\\]=*\\]",a={begin:n,end:t,contains:["self"] +},i=[e.COMMENT("--(?!"+n+")","$"),e.COMMENT("--"+n,t,{contains:[a],relevance:10 +})];return{name:"Lua",aliases:["pluto"],keywords:{ +$pattern:e.UNDERSCORE_IDENT_RE,literal:"true false nil", +keyword:"and break do else elseif end for goto if in local global not or repeat return then until while", +built_in:"_G _ENV _VERSION __index __newindex __mode __call __metatable __tostring __len __gc __add __sub __mul __div __mod __pow __concat __unm __eq __lt __le assert collectgarbage dofile error getfenv getmetatable ipairs load loadfile loadstring module next pairs pcall print rawequal rawget rawset require select setfenv setmetatable tonumber tostring type unpack xpcall arg self coroutine resume yield status wrap create running debug getupvalue debug sethook getmetatable gethook setmetatable setlocal traceback setfenv getinfo setupvalue getlocal getregistry getfenv io lines write close flush open output type read stderr stdin input stdout popen tmpfile math log max acos huge ldexp pi cos tanh pow deg tan cosh sinh random randomseed frexp ceil floor rad abs sqrt modf asin min mod fmod log10 atan2 exp sin atan os exit setlocale date getenv difftime remove time clock tmpname rename execute package preload loadlib loaded loaders cpath config path seeall string sub upper len gfind rep find match char dump gmatch reverse byte format gsub lower table setn insert getn foreachi maxn foreach concat sort remove" +},contains:i.concat([{className:"function",beginKeywords:"function",end:"\\)", +contains:[e.inherit(e.TITLE_MODE,{ +begin:"([_a-zA-Z]\\w*\\.)*([_a-zA-Z]\\w*:)?[_a-zA-Z]\\w*"}),{className:"params", +begin:"\\(",endsWithParent:!0,contains:i}].concat(i) +},e.C_NUMBER_MODE,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,{className:"string", +begin:n,end:t,contains:[a],relevance:5}])}},grmr_makefile:e=>{const n={ +className:"variable",variants:[{begin:"\\$\\("+e.UNDERSCORE_IDENT_RE+"\\)", +contains:[e.BACKSLASH_ESCAPE]},{begin:/\$[@%{ +const n={begin:/<\/?[A-Za-z_]/,end:">",subLanguage:"xml",relevance:0},t={ +variants:[{begin:/\[.+?\]\[.*?\]/,relevance:0},{ +begin:/\[.+?\]\(((data|javascript|mailto):|(?:http|ftp)s?:\/\/).*?\)/, +relevance:2},{ +begin:e.regex.concat(/\[.+?\]\(/,/[A-Za-z][A-Za-z0-9+.-]*/,/:\/\/.*?\)/), +relevance:2},{begin:/\[.+?\]\([./?&#].*?\)/,relevance:1},{ +begin:/\[.*?\]\(.*?\)/,relevance:0}],returnBegin:!0,contains:[{match:/\[(?=\])/ +},{className:"string",relevance:0,begin:"\\[",end:"\\]",excludeBegin:!0, +returnEnd:!0},{className:"link",relevance:0,begin:"\\]\\(",end:"\\)", +excludeBegin:!0,excludeEnd:!0},{className:"symbol",relevance:0,begin:"\\]\\[", +end:"\\]",excludeBegin:!0,excludeEnd:!0}]},a={className:"strong",contains:[], +variants:[{begin:/_{2}(?!\s)/,end:/_{2}/},{begin:/\*{2}(?!\s)/,end:/\*{2}/}] +},i={className:"emphasis",contains:[],variants:[{begin:/\*(?![*\s])/,end:/\*/},{ +begin:/_(?![_\s])/,end:/_/,relevance:0}]},r=e.inherit(a,{contains:[] +}),s=e.inherit(i,{contains:[]});a.contains.push(s),i.contains.push(r) +;let o=[n,t];return[a,i,r,s].forEach(e=>{e.contains=e.contains.concat(o) +}),o=o.concat(a,i),{name:"Markdown",aliases:["md","mkdown","mkd"],contains:[{ +className:"section",variants:[{begin:"^#{1,6}",end:"$",contains:o},{ +begin:"(?=^.+?\\n[=-]{2,}$)",contains:[{begin:"^[=-]*$"},{begin:"^",end:"\\n", +contains:o}]}]},n,{className:"bullet",begin:"^[ \t]*([*+-]|(\\d+\\.))(?=\\s+)", +end:"\\s+",excludeEnd:!0},{match:/^ {0,3}([-*_])[ \t]*(?:\1[ \t]*){2,}$/},a,i,{ +className:"quote",begin:"^>\\s+",contains:o,end:"$"},{className:"code", +variants:[{begin:"(`{3,})[^`](.|\\n)*?\\1`*[ ]*"},{ +begin:"(~{3,})[^~](.|\\n)*?\\1~*[ ]*"},{begin:"```",end:"```+[ ]*$"},{ +begin:"~~~",end:"~~~+[ ]*$"},{begin:"`.+?`"},{begin:"(?=^( {4}|\\t))", +contains:[{begin:"^( {4}|\\t)",end:"(\\n)$"}],relevance:0}]},t,{ +begin:/^\[[^\n]+\]:/,returnBegin:!0,contains:[{className:"symbol",begin:/\[/, +end:/\]/,excludeBegin:!0,excludeEnd:!0},{className:"link",begin:/:\s*/,end:/$/, +excludeBegin:!0}]},{scope:"literal", +match:/&([a-zA-Z0-9]+|#[0-9]{1,7}|#[Xx][0-9a-fA-F]{1,6});/}]}}, +grmr_objectivec:e=>{const n=/[a-zA-Z@][a-zA-Z0-9_]*/,t={$pattern:n, +keyword:["@interface","@class","@protocol","@implementation"]};return{ +name:"Objective-C",aliases:["mm","objc","obj-c","obj-c++","objective-c++"], +keywords:{"variable.language":["this","super"],$pattern:n, +keyword:["while","export","sizeof","typedef","const","struct","for","union","volatile","static","mutable","if","do","return","goto","enum","else","break","extern","asm","case","default","register","explicit","typename","switch","continue","inline","readonly","assign","readwrite","self","@synchronized","id","typeof","nonatomic","IBOutlet","IBAction","strong","weak","copy","in","out","inout","bycopy","byref","oneway","__strong","__weak","__block","__autoreleasing","@private","@protected","@public","@try","@property","@end","@throw","@catch","@finally","@autoreleasepool","@synthesize","@dynamic","@selector","@optional","@required","@encode","@package","@import","@defs","@compatibility_alias","__bridge","__bridge_transfer","__bridge_retained","__bridge_retain","__covariant","__contravariant","__kindof","_Nonnull","_Nullable","_Null_unspecified","__FUNCTION__","__PRETTY_FUNCTION__","__attribute__","getter","setter","retain","unsafe_unretained","nonnull","nullable","null_unspecified","null_resettable","class","instancetype","NS_DESIGNATED_INITIALIZER","NS_UNAVAILABLE","NS_REQUIRES_SUPER","NS_RETURNS_INNER_POINTER","NS_INLINE","NS_AVAILABLE","NS_DEPRECATED","NS_ENUM","NS_OPTIONS","NS_SWIFT_UNAVAILABLE","NS_ASSUME_NONNULL_BEGIN","NS_ASSUME_NONNULL_END","NS_REFINED_FOR_SWIFT","NS_SWIFT_NAME","NS_SWIFT_NOTHROW","NS_DURING","NS_HANDLER","NS_ENDHANDLER","NS_VALUERETURN","NS_VOIDRETURN"], +literal:["false","true","FALSE","TRUE","nil","YES","NO","NULL"], +built_in:["dispatch_once_t","dispatch_queue_t","dispatch_sync","dispatch_async","dispatch_once"], +type:["int","float","char","unsigned","signed","short","long","double","wchar_t","unichar","void","bool","BOOL","id|0","_Bool"] +},illegal:"/,end:/$/,illegal:"\\n" +},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{className:"class", +begin:"("+t.keyword.join("|")+")\\b",end:/(\{|$)/,excludeEnd:!0,keywords:t, +contains:[e.UNDERSCORE_TITLE_MODE]},{begin:"\\."+e.UNDERSCORE_IDENT_RE, +relevance:0}]}},grmr_perl:e=>{const n=e.regex,t=/[dualxmsipngr]{0,12}/,a={ +$pattern:/[\w.]+/, +keyword:"abs accept alarm and atan2 bind binmode bless break caller chdir chmod chomp chop chown chr chroot class close closedir connect continue cos crypt dbmclose dbmopen defined delete die do dump each else elsif endgrent endhostent endnetent endprotoent endpwent endservent eof eval exec exists exit exp fcntl field fileno flock for foreach fork format formline getc getgrent getgrgid getgrnam gethostbyaddr gethostbyname gethostent getlogin getnetbyaddr getnetbyname getnetent getpeername getpgrp getpriority getprotobyname getprotobynumber getprotoent getpwent getpwnam getpwuid getservbyname getservbyport getservent getsockname getsockopt given glob gmtime goto grep gt hex if index int ioctl join keys kill last lc lcfirst length link listen local localtime log lstat lt ma map method mkdir msgctl msgget msgrcv msgsnd my ne next no not oct open opendir or ord our pack package pipe pop pos print printf prototype push q|0 qq quotemeta qw qx rand read readdir readline readlink readpipe recv redo ref rename require reset return reverse rewinddir rindex rmdir say scalar seek seekdir select semctl semget semop send setgrent sethostent setnetent setpgrp setpriority setprotoent setpwent setservent setsockopt shift shmctl shmget shmread shmwrite shutdown sin sleep socket socketpair sort splice split sprintf sqrt srand stat state study sub substr symlink syscall sysopen sysread sysseek system syswrite tell telldir tie tied time times tr truncate uc ucfirst umask undef unless unlink unpack unshift untie until use utime values vec wait waitpid wantarray warn when while write x|0 xor y|0" +},i={className:"subst",begin:"[$@]\\{",end:"\\}",keywords:a},r={begin:/->\{/, +end:/\}/},s={scope:"attr",match:/\s+:\s*\w+(\s*\(.*?\))?/},o={scope:"variable", +variants:[{begin:/\$\d/},{ +begin:n.concat(/[$%@](?!")(\^\w\b|#\w+(::\w+)*|\{\w+\}|\w+(::\w*)*)/,"(?![A-Za-z])(?![@$%])") +},{begin:/[$%@](?!")[^\s\w{=]|\$=/,relevance:0}],contains:[s]},c={ +className:"number",variants:[{match:/0?\.[0-9][0-9_]+\b/},{ +match:/\bv?(0|[1-9][0-9_]*(\.[0-9_]+)?|[1-9][0-9_]*)\b/},{ +match:/\b0[0-7][0-7_]*\b/},{match:/\b0x[0-9a-fA-F][0-9a-fA-F_]*\b/},{ +match:/\b0b[0-1][0-1_]*\b/}],relevance:0 +},l=[e.BACKSLASH_ESCAPE,i,o],d=[/!/,/\//,/\|/,/\?/,/'/,/"/,/#/],g=(e,a,i="\\1")=>{ +const r="\\1"===i?i:n.concat(i,a) +;return n.concat(n.concat("(?:",e,")"),a,/(?:\\.|[^\\\/])*?/,r,/(?:\\.|[^\\\/])*?/,i,t) +},u=(e,a,i)=>n.concat(n.concat("(?:",e,")"),a,/(?:\\.|[^\\\/])*?/,i,t),b=[o,e.HASH_COMMENT_MODE,e.COMMENT(/^=\w/,/=cut/,{ +endsWithParent:!0}),r,{className:"string",contains:l,variants:[{ +begin:"q[qwxr]?\\s*\\(",end:"\\)",relevance:5},{begin:"q[qwxr]?\\s*\\[", +end:"\\]",relevance:5},{begin:"q[qwxr]?\\s*\\{",end:"\\}",relevance:5},{ +begin:"q[qwxr]?\\s*\\|",end:"\\|",relevance:5},{begin:"q[qwxr]?\\s*<",end:">", +relevance:5},{begin:"qw\\s+q",end:"q",relevance:5},{begin:"'",end:"'", +contains:[e.BACKSLASH_ESCAPE]},{begin:'"',end:'"'},{begin:"`",end:"`", +contains:[e.BACKSLASH_ESCAPE]},{begin:/\{\w+\}/,relevance:0},{ +begin:"-?\\w+\\s*=>",relevance:0}]},c,{ +begin:"(\\/\\/|"+e.RE_STARTERS_RE+"|\\b(split|return|print|reverse|grep)\\b)\\s*", +keywords:"split return print reverse grep",relevance:0, +contains:[e.HASH_COMMENT_MODE,{className:"regexp",variants:[{ +begin:g("s|tr|y",n.either(...d,{capture:!0}))},{begin:g("s|tr|y","\\(","\\)")},{ +begin:g("s|tr|y","\\[","\\]")},{begin:g("s|tr|y","\\{","\\}")}],relevance:2},{ +className:"regexp",variants:[{begin:/(m|qr)\/\//,relevance:0},{ +begin:u("(?:m|qr)?",/\//,/\//)},{begin:u("m|qr",n.either(...d,{capture:!0 +}),/\1/)},{begin:u("m|qr",/\(/,/\)/)},{begin:u("m|qr",/\[/,/\]/)},{ +begin:u("m|qr",/\{/,/\}/)}]}]},{className:"function",beginKeywords:"sub method", +end:"(\\s*\\(.*?\\))?[;{]",excludeEnd:!0,relevance:5,contains:[e.TITLE_MODE,s] +},{className:"class",beginKeywords:"class",end:"[;{]",excludeEnd:!0,relevance:5, +contains:[e.TITLE_MODE,s,c]},{begin:"-\\w\\b",relevance:0},{begin:"^__DATA__$", +end:"^__END__$",subLanguage:"mojolicious",contains:[{begin:"^@@.*",end:"$", +className:"comment"}]}];return i.contains=b,r.contains=b,{name:"Perl", +aliases:["pl","pm"],keywords:a,contains:b}},grmr_php:e=>{ +const n=e.regex,t=/(?![A-Za-z0-9])(?![$])/,a=n.concat(/[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/,t),i=n.concat(/(\\?[A-Z][a-z0-9_\x7f-\xff]+|\\?[A-Z]+(?=[A-Z][a-z0-9_\x7f-\xff])){1,}/,t),r=n.concat(/[A-Z]+/,t),s={ +scope:"variable",match:"\\$+"+a},o={scope:"subst",variants:[{begin:/\$\w+/},{ +begin:/\{\$/,end:/\}/}]},c=e.inherit(e.APOS_STRING_MODE,{illegal:null +}),l="[ \t\n]",d={scope:"string",variants:[e.inherit(e.QUOTE_STRING_MODE,{ +illegal:null,contains:e.QUOTE_STRING_MODE.contains.concat(o)}),c,{ +begin:/<<<[ \t]*(?:(\w+)|"(\w+)")\n/,end:/[ \t]*(\w+)\b/, +contains:e.QUOTE_STRING_MODE.contains.concat(o),"on:begin":(e,n)=>{ +n.data._beginMatch=e[1]||e[2]},"on:end":(e,n)=>{ +n.data._beginMatch!==e[1]&&n.ignoreMatch()}},e.END_SAME_AS_BEGIN({ +begin:/<<<[ \t]*'(\w+)'\n/,end:/[ \t]*(\w+)\b/})]},g={scope:"number",variants:[{ +begin:"\\b0[bB][01]+(?:_[01]+)*\\b"},{begin:"\\b0[oO][0-7]+(?:_[0-7]+)*\\b"},{ +begin:"\\b0[xX][\\da-fA-F]+(?:_[\\da-fA-F]+)*\\b"},{ +begin:"(?:\\b\\d+(?:_\\d+)*(\\.(?:\\d+(?:_\\d+)*))?|\\B\\.\\d+)(?:[eE][+-]?\\d+)?" +}],relevance:0 +},u=["false","null","true"],b=["__CLASS__","__DIR__","__FILE__","__FUNCTION__","__COMPILER_HALT_OFFSET__","__LINE__","__METHOD__","__NAMESPACE__","__TRAIT__","die","echo","exit","include","include_once","print","require","require_once","array","abstract","and","as","binary","bool","boolean","break","callable","case","catch","class","clone","const","continue","declare","default","do","double","else","elseif","empty","enddeclare","endfor","endforeach","endif","endswitch","endwhile","enum","eval","extends","final","finally","float","for","foreach","from","global","goto","if","implements","instanceof","insteadof","int","integer","interface","isset","iterable","list","match|0","mixed","new","never","object","or","private","protected","public","readonly","real","return","string","switch","throw","trait","try","unset","use","var","void","while","xor","yield"],m=["Error|0","AppendIterator","ArgumentCountError","ArithmeticError","ArrayIterator","ArrayObject","AssertionError","BadFunctionCallException","BadMethodCallException","CachingIterator","CallbackFilterIterator","CompileError","Countable","DirectoryIterator","DivisionByZeroError","DomainException","EmptyIterator","ErrorException","Exception","FilesystemIterator","FilterIterator","GlobIterator","InfiniteIterator","InvalidArgumentException","IteratorIterator","LengthException","LimitIterator","LogicException","MultipleIterator","NoRewindIterator","OutOfBoundsException","OutOfRangeException","OuterIterator","OverflowException","ParentIterator","ParseError","RangeException","RecursiveArrayIterator","RecursiveCachingIterator","RecursiveCallbackFilterIterator","RecursiveDirectoryIterator","RecursiveFilterIterator","RecursiveIterator","RecursiveIteratorIterator","RecursiveRegexIterator","RecursiveTreeIterator","RegexIterator","RuntimeException","SeekableIterator","SplDoublyLinkedList","SplFileInfo","SplFileObject","SplFixedArray","SplHeap","SplMaxHeap","SplMinHeap","SplObjectStorage","SplObserver","SplPriorityQueue","SplQueue","SplStack","SplSubject","SplTempFileObject","TypeError","UnderflowException","UnexpectedValueException","UnhandledMatchError","ArrayAccess","BackedEnum","Closure","Fiber","Generator","Iterator","IteratorAggregate","Serializable","Stringable","Throwable","Traversable","UnitEnum","WeakReference","WeakMap","Directory","__PHP_Incomplete_Class","parent","php_user_filter","self","static","stdClass"],p={ +keyword:b,literal:(e=>{const n=[];return e.forEach(e=>{ +n.push(e),e.toLowerCase()===e?n.push(e.toUpperCase()):n.push(e.toLowerCase())}), +n})(u),built_in:m},_=e=>e.map(e=>e.replace(/\|\d+$/,"")),h={variants:[{ +match:[/new/,n.concat(l,"+"),n.concat("(?!",_(m).join("\\b|"),"\\b)"),i],scope:{ +1:"keyword",4:"title.class"}}]},f=n.concat(a,"\\b(?!\\()"),E={variants:[{ +match:[n.concat(/::/,n.lookahead(/(?!class\b)/)),f],scope:{2:"variable.constant" +}},{match:[/::/,/class/],scope:{2:"variable.language"}},{ +match:[i,n.concat(/::/,n.lookahead(/(?!class\b)/)),f],scope:{1:"title.class", +3:"variable.constant"}},{match:[i,n.concat("::",n.lookahead(/(?!class\b)/))], +scope:{1:"title.class"}},{match:[i,/::/,/class/],scope:{1:"title.class", +3:"variable.language"}}]},y={scope:"attr", +match:n.concat(a,n.lookahead(":"),n.lookahead(/(?!::)/))},w={relevance:0, +begin:/\(/,end:/\)/,keywords:p, +contains:[y,s,E,e.C_BLOCK_COMMENT_MODE,e.C_LINE_COMMENT_MODE,e.HASH_COMMENT_MODE,d,g,h] +},v={relevance:0, +match:[/\b/,n.concat("(?!fn\\b|function\\b|",_(b).join("\\b|"),"|",_(m).join("\\b|"),"\\b)"),a,n.concat(l,"*"),n.lookahead(/(?=\()/)], +scope:{3:"title.function.invoke"},contains:[w]};w.contains.push(v) +;const N=[y,E,e.C_BLOCK_COMMENT_MODE,e.C_LINE_COMMENT_MODE,e.HASH_COMMENT_MODE,d,g,h],k={ +begin:n.concat(/#\[\s*\\?/,n.either(i,r)),beginScope:"meta",end:/]/, +endScope:"meta",keywords:{literal:u,keyword:["new","array"]},contains:[{ +begin:/\[/,end:/]/,keywords:{literal:u,keyword:["new","array"]}, +contains:["self",...N]},...N,{scope:"meta",variants:[{match:i},{match:r}]}]} +;return{case_insensitive:!1,keywords:p, +contains:[k,e.HASH_COMMENT_MODE,e.COMMENT("//","$"),e.COMMENT("/\\*","\\*/",{ +contains:[{scope:"doctag",match:"@[A-Za-z]+"}]}),{match:/__halt_compiler\(\);/, +keywords:"__halt_compiler",starts:{scope:"comment",end:e.MATCH_NOTHING_RE, +contains:[{match:/\?>/,scope:"meta",endsParent:!0}]}},{scope:"meta",variants:[{ +begin:/<\?php/,relevance:10},{begin:/<\?=/},{begin:/<\?/,relevance:.1},{ +begin:/\?>/}]},{scope:"variable.language",match:/\$this\b/},s,v,E,{ +match:[/const/,/\s/,a],scope:{1:"keyword",3:"variable.constant"}},h,{ +scope:"function",relevance:0,beginKeywords:"fn function",end:/[;{]/, +excludeEnd:!0,illegal:"[$%\\[]",contains:[{beginKeywords:"use" +},e.UNDERSCORE_TITLE_MODE,{begin:"=>",endsParent:!0},{scope:"params", +begin:"\\(",end:"\\)",excludeBegin:!0,excludeEnd:!0,keywords:p, +contains:["self",k,s,E,e.C_BLOCK_COMMENT_MODE,e.C_LINE_COMMENT_MODE,e.HASH_COMMENT_MODE,d,g] +}]},{scope:"class",variants:[{beginKeywords:"enum",illegal:/[($"]/},{ +beginKeywords:"class interface trait",illegal:/[:($"]/}],relevance:0,end:/\{/, +excludeEnd:!0,contains:[{beginKeywords:"extends implements" +},e.UNDERSCORE_TITLE_MODE]},{beginKeywords:"namespace",relevance:0,end:";", +illegal:/[.']/,contains:[e.inherit(e.UNDERSCORE_TITLE_MODE,{scope:"title.class" +})]},{beginKeywords:"use",relevance:0,end:";",contains:[{ +match:/\b(as|const|function)\b/,scope:"keyword"},e.UNDERSCORE_TITLE_MODE]},d,g]} +},grmr_php_template:e=>({name:"PHP template",subLanguage:"xml",contains:[{ +begin:/<\?(php|=)?/,end:/\?>/,subLanguage:"php",contains:[{begin:"/\\*", +end:"\\*/",skip:!0},{begin:'b"',end:'"',skip:!0},{begin:"b'",end:"'",skip:!0 +},e.inherit(e.APOS_STRING_MODE,{illegal:null,className:null,contains:null, +skip:!0}),e.inherit(e.QUOTE_STRING_MODE,{illegal:null,className:null, +contains:null,skip:!0})]}]}),grmr_plaintext:e=>({name:"Plain text", +aliases:["text","txt"],disableAutodetect:!0}),grmr_python:e=>{ +const n=e.regex,t=/[\p{XID_Start}_]\p{XID_Continue}*/u,a=["and","as","assert","async","await","break","case","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","lazy","match","nonlocal|10","not","or","pass","raise","return","try","while","with","yield"],i={ +$pattern:/[A-Za-z]\w+|__\w+__/,keyword:a, +built_in:["__import__","abs","aiter","all","anext","any","ascii","bin","bool","breakpoint","bytearray","bytes","callable","chr","classmethod","compile","complex","delattr","dict","dir","divmod","enumerate","eval","exec","filter","float","format","frozendict","frozenset","getattr","globals","hasattr","hash","help","hex","id","input","int","isinstance","issubclass","iter","len","list","locals","map","max","memoryview","min","next","object","oct","open","ord","pow","print","property","range","repr","reversed","round","sentinel","set","setattr","slice","sorted","staticmethod","str","sum","super","tuple","type","vars","zip"], +literal:["__debug__","Ellipsis","False","None","NotImplemented","True"], +type:["Any","Callable","Coroutine","Dict","List","Literal","Generic","Optional","Sequence","Set","Tuple","Type","Union"] +},r={className:"meta",begin:/^(>>>|\.\.\.) /},s={className:"subst",begin:/\{/, +end:/\}/,keywords:i,illegal:/#/},o={begin:/\{\{/,relevance:0},c={ +className:"string",contains:[e.BACKSLASH_ESCAPE],variants:[{ +begin:/([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?'''/,end:/'''/, +contains:[e.BACKSLASH_ESCAPE,r],relevance:10},{ +begin:/([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?"""/,end:/"""/, +contains:[e.BACKSLASH_ESCAPE,r],relevance:10},{ +begin:/([fFtT][rR]|[rR][fFtT]|[fFtT])'''/,end:/'''/, +contains:[e.BACKSLASH_ESCAPE,r,o,s]},{begin:/([fFtT][rR]|[rR][fFtT]|[fFtT])"""/, +end:/"""/,contains:[e.BACKSLASH_ESCAPE,r,o,s]},{begin:/([uU]|[rR])'/,end:/'/, +relevance:10},{begin:/([uU]|[rR])"/,end:/"/,relevance:10},{ +begin:/([bB]|[bB][rR]|[rR][bB])'/,end:/'/},{begin:/([bB]|[bB][rR]|[rR][bB])"/, +end:/"/},{begin:/([fFtT][rR]|[rR][fFtT]|[fFtT])'/,end:/'/, +contains:[e.BACKSLASH_ESCAPE,o,s]},{begin:/([fFtT][rR]|[rR][fFtT]|[fFtT])"/, +end:/"/,contains:[e.BACKSLASH_ESCAPE,o,s] +},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE] +},l="[0-9](_?[0-9])*",d=`(\\b(${l}))?\\.(${l})|\\b(${l})\\.`,g="\\b|"+a.join("|"),u={ +className:"number",relevance:0,variants:[{ +begin:`(\\b(${l})|(${d}))[eE][+-]?(${l})[jJ]?(?=${g})`},{begin:`(${d})[jJ]?`},{ +begin:`\\b([1-9](_?[0-9])*|0+(_?0)*)[lLjJ]?(?=${g})`},{ +begin:`\\b0[bB](_?[01])+[lL]?(?=${g})`},{begin:`\\b0[oO](_?[0-7])+[lL]?(?=${g})` +},{begin:`\\b0[xX](_?[0-9a-fA-F])+[lL]?(?=${g})`},{begin:`\\b(${l})[jJ](?=${g})` +}]},b={className:"comment",begin:n.lookahead(/# type:/),end:/$/,keywords:i, +contains:[{begin:/# type:/},{begin:/#/,end:/\b\B/,endsWithParent:!0}]},m={ +className:"params",variants:[{className:"",begin:/\(\s*\)/,skip:!0},{begin:/\(/, +end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:i, +contains:["self",r,u,c,e.HASH_COMMENT_MODE]}]};return s.contains=[c,u,r],{ +name:"Python",aliases:["py","gyp","ipython"],unicodeRegex:!0,keywords:i, +illegal:/(<\/|\?)|=>/,contains:[r,u,{scope:"variable.language",match:/\bself\b/ +},{beginKeywords:"if",relevance:0},{match:/\bor\b/,scope:"keyword" +},c,b,e.HASH_COMMENT_MODE,{match:[/\bdef/,/\s+/,t],scope:{1:"keyword", +3:"title.function"},contains:[m]},{variants:[{ +match:[/\bclass/,/\s+/,t,/\s*/,/\(\s*/,t,/\s*\)/]},{match:[/\bclass/,/\s+/,t]}], +scope:{1:"keyword",3:"title.class",6:"title.class.inherited"}},{ +className:"meta",begin:/^[\t ]*@/,end:/(?=#)|$/,contains:[u,m,c]}]}}, +grmr_python_repl:e=>({aliases:["pycon"],contains:[{className:"meta.prompt", +starts:{end:/ |$/,starts:{end:"$",subLanguage:"python"}},variants:[{ +begin:/^>>>(?=[ ]|$)/},{begin:/^\.\.\.(?=[ ]|$)/}]}]}),grmr_r:e=>{ +const n=e.regex,t=/(?:(?:[a-zA-Z]|\.[._a-zA-Z])[._a-zA-Z0-9]*)|\.(?!\d)/,a=n.either(/0[xX][0-9a-fA-F]+\.[0-9a-fA-F]*[pP][+-]?\d+i?/,/0[xX][0-9a-fA-F]+(?:[pP][+-]?\d+)?[Li]?/,/(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?[Li]?/),i=/[=!<>:]=|\|\||&&|:::?|<-|<<-|->>|->|\|>|[-+*\/?!$&|:<=>@^~]|\*\*/,r=n.either(/[()]/,/[{}]/,/\[\[/,/[[\]]/,/\\/,/,/) +;return{name:"R",keywords:{$pattern:t, +keyword:"function if in break next repeat else for while", +literal:"NULL NA TRUE FALSE Inf NaN NA_integer_|10 NA_real_|10 NA_character_|10 NA_complex_|10", +built_in:"LETTERS letters month.abb month.name pi T F abs acos acosh all any anyNA Arg as.call as.character as.complex as.double as.environment as.integer as.logical as.null.default as.numeric as.raw asin asinh atan atanh attr attributes baseenv browser c call ceiling class Conj cos cosh cospi cummax cummin cumprod cumsum digamma dim dimnames emptyenv exp expression floor forceAndCall gamma gc.time globalenv Im interactive invisible is.array is.atomic is.call is.character is.complex is.double is.environment is.expression is.finite is.function is.infinite is.integer is.language is.list is.logical is.matrix is.na is.name is.nan is.null is.numeric is.object is.pairlist is.raw is.recursive is.single is.symbol lazyLoadDBfetch length lgamma list log max min missing Mod names nargs nzchar oldClass on.exit pos.to.env proc.time prod quote range Re rep retracemem return round seq_along seq_len seq.int sign signif sin sinh sinpi sqrt standardGeneric substitute sum switch tan tanh tanpi tracemem trigamma trunc unclass untracemem UseMethod xtfrm" +},contains:[e.COMMENT(/#'/,/$/,{contains:[{scope:"doctag",match:/@examples/, +starts:{end:n.lookahead(n.either(/\n^#'\s*(?=@[a-zA-Z]+)/,/\n^(?!#')/)), +endsParent:!0}},{scope:"doctag",begin:"@param",end:/$/,contains:[{ +scope:"variable",variants:[{match:t},{match:/`(?:\\.|[^`\\])+`/}],endsParent:!0 +}]},{scope:"doctag",match:/@[a-zA-Z]+/},{scope:"keyword",match:/\\[a-zA-Z]+/}] +}),e.HASH_COMMENT_MODE,{scope:"string",contains:[e.BACKSLASH_ESCAPE], +variants:[e.END_SAME_AS_BEGIN({begin:/[rR]"(-*)\(/,end:/\)(-*)"/ +}),e.END_SAME_AS_BEGIN({begin:/[rR]"(-*)\{/,end:/\}(-*)"/ +}),e.END_SAME_AS_BEGIN({begin:/[rR]"(-*)\[/,end:/\](-*)"/ +}),e.END_SAME_AS_BEGIN({begin:/[rR]'(-*)\(/,end:/\)(-*)'/ +}),e.END_SAME_AS_BEGIN({begin:/[rR]'(-*)\{/,end:/\}(-*)'/ +}),e.END_SAME_AS_BEGIN({begin:/[rR]'(-*)\[/,end:/\](-*)'/}),{begin:'"',end:'"', +relevance:0},{begin:"'",end:"'",relevance:0}]},{relevance:0,variants:[{scope:{ +1:"operator",2:"number"},match:[i,a]},{scope:{1:"operator",2:"number"}, +match:[/%[^%]*%/,a]},{scope:{1:"punctuation",2:"number"},match:[r,a]},{scope:{ +2:"number"},match:[/[^a-zA-Z0-9._]|^/,a]}]},{scope:{3:"operator"}, +match:[t,/\s+/,/<-/,/\s+/]},{scope:"operator",relevance:0,variants:[{match:i},{ +match:/%[^%]*%/}]},{scope:"punctuation",relevance:0,match:r},{begin:"`",end:"`", +contains:[{begin:/\\./}]}]}},grmr_ruby:e=>{ +const n=e.regex,t="([a-zA-Z_]\\w*[!?=]?|[-+~]@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?)",a=n.either(/\b([A-Z]+[a-z0-9]+)+/,/\b([A-Z]+[a-z0-9]+)+[A-Z]+/),i=n.concat(a,/(::\w+)*/),r={ +"variable.constant":["__FILE__","__LINE__","__ENCODING__"], +"variable.language":["self","super"], +keyword:["alias","and","begin","BEGIN","break","case","class","defined","do","else","elsif","end","END","ensure","for","if","in","module","next","not","or","redo","require","rescue","retry","return","then","undef","unless","until","when","while","yield","include","extend","prepend","public","private","protected","raise","throw"], +built_in:["proc","lambda","attr_accessor","attr_reader","attr_writer","define_method","private_constant","module_function"], +literal:["true","false","nil"]},s={className:"doctag",begin:"@[A-Za-z]+"},o={ +begin:"#<",end:">"},c=[e.COMMENT("#","$",{contains:[s] +}),e.COMMENT("^=begin","^=end",{contains:[s],relevance:10 +}),e.COMMENT("^__END__",e.MATCH_NOTHING_RE)],l={className:"subst",begin:/#\{/, +end:/\}/,keywords:r},d={className:"string",contains:[e.BACKSLASH_ESCAPE,l], +variants:[{begin:/'/,end:/'/},{begin:/"/,end:/"/},{begin:/`/,end:/`/},{ +begin:/%[qQwWx]?\(/,end:/\)/},{begin:/%[qQwWx]?\[/,end:/\]/},{ +begin:/%[qQwWx]?\{/,end:/\}/},{begin:/%[qQwWx]?/},{begin:/%[qQwWx]?\//, +end:/\//},{begin:/%[qQwWx]?%/,end:/%/},{begin:/%[qQwWx]?-/,end:/-/},{ +begin:/%[qQwWx]?\|/,end:/\|/},{begin:/\B\?(\\\d{1,3})/},{ +begin:/\B\?(\\x[A-Fa-f0-9]{1,2})/},{begin:/\B\?(\\u\{?[A-Fa-f0-9]{1,6}\}?)/},{ +begin:/\B\?(\\M-\\C-|\\M-\\c|\\c\\M-|\\M-|\\C-\\M-)[\x20-\x7e]/},{ +begin:/\B\?\\(c|C-)[\x20-\x7e]/},{begin:/\B\?\\?\S/},{ +begin:n.concat(/<<[-~]?'?/,n.lookahead(/(\w+)(?=\W)[^\n]*\n(?:[^\n]*\n)*?\s*\1\b/)), +contains:[e.END_SAME_AS_BEGIN({begin:/(\w+)/,end:/(\w+)/, +contains:[e.BACKSLASH_ESCAPE,l]})]}]},g="[0-9](_?[0-9])*",u={className:"number", +relevance:0,variants:[{ +begin:`\\b([1-9](_?[0-9])*|0)(\\.(${g}))?([eE][+-]?(${g})|r)?i?\\b`},{ +begin:"\\b0[dD][0-9](_?[0-9])*r?i?\\b"},{begin:"\\b0[bB][0-1](_?[0-1])*r?i?\\b" +},{begin:"\\b0[oO][0-7](_?[0-7])*r?i?\\b"},{ +begin:"\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*r?i?\\b"},{ +begin:"\\b0(_?[0-7])+r?i?\\b"}]},b={variants:[{match:/\(\)/},{ +className:"params",begin:/\(/,end:/(?=\))/,excludeBegin:!0,endsParent:!0, +keywords:r}]},m=[d,{variants:[{match:[/class\s+/,i,/\s+<\s+/,i]},{ +match:[/\b(class|module)\s+/,i]}],scope:{2:"title.class", +4:"title.class.inherited"},keywords:r},{match:[/(include|extend)\s+/,i],scope:{ +2:"title.class"},keywords:r},{relevance:0,match:[i,/\.new[. (]/],scope:{ +1:"title.class"}},{relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/, +className:"variable.constant"},{relevance:0,match:a,scope:"title.class"},{ +match:[/def/,/\s+/,t],scope:{1:"keyword",3:"title.function"},contains:[b]},{ +begin:"::"},{className:"symbol",begin:e.UNDERSCORE_IDENT_RE+"(!|\\?)?:", +relevance:0},{className:"symbol",begin:":(?!\\s)",contains:[d,{begin:t}], +relevance:0},u,{className:"variable", +begin:"(\\$\\W)|((\\$|@@?)(\\w+))(?=[^@$?])(?![A-Za-z])(?![@$?'])"},{ +className:"params",begin:/\|(?!=)/,end:/\|/,excludeBegin:!0,excludeEnd:!0, +relevance:0,keywords:r},{begin:"("+e.RE_STARTERS_RE+"|unless)\\s*", +keywords:"unless",contains:[{className:"regexp",contains:[e.BACKSLASH_ESCAPE,l], +illegal:/\n/,variants:[{begin:"/",end:"/[a-z]*"},{begin:/%r\{/,end:/\}[a-z]*/},{ +begin:"%r\\(",end:"\\)[a-z]*"},{begin:"%r!",end:"![a-z]*"},{begin:"%r\\[", +end:"\\][a-z]*"}]}].concat(o,c),relevance:0}].concat(o,c) +;l.contains=m,b.contains=m;const p=[{begin:/^\s*=>/,starts:{end:"$",contains:m} +},{className:"meta.prompt", +begin:"^([>?]>|[\\w#]+\\(\\w+\\):\\d+:\\d+[>*]|(\\w+-)?\\d+\\.\\d+\\.\\d+(p\\d+)?[^\\d][^>]+>)(?=[ ])", +starts:{end:"$",keywords:r,contains:m}}];return c.unshift(o),{name:"Ruby", +aliases:["rb","gemspec","podspec","thor","irb"],keywords:r,illegal:/\/\*/, +contains:[e.SHEBANG({binary:"ruby"})].concat(p).concat(c).concat(m)}}, +grmr_rust:e=>{ +const n=e.regex,t=/(r#)?/,a=n.concat(t,e.UNDERSCORE_IDENT_RE),i=n.concat(t,e.IDENT_RE),r={ +scope:"title.function.invoke",relevance:0, +begin:n.concat(/\b/,/(?!(?:let|for|while|if|else|match)\b)/,i,n.lookahead(/\s*\(/)) +},s="([ui](8|16|32|64|128|size)|f(16|32|64|128))?",o=["drop ","Copy","Send","Sized","Sync","Drop","Fn","FnMut","FnOnce","ToOwned","Clone","Debug","PartialEq","PartialOrd","Eq","Ord","AsRef","AsMut","Into","From","Default","Iterator","Extend","IntoIterator","DoubleEndedIterator","ExactSizeIterator","SliceConcatExt","ToString","assert!","assert_eq!","bitflags!","bytes!","cfg!","col!","concat!","concat_idents!","debug_assert!","debug_assert_eq!","env!","eprintln!","panic!","file!","format!","format_args!","include_bytes!","include_str!","line!","local_data_key!","module_path!","option_env!","print!","println!","select!","stringify!","try!","unimplemented!","unreachable!","vec!","write!","writeln!","macro_rules!","assert_ne!","debug_assert_ne!"],c=["i8","i16","i32","i64","i128","isize","u8","u16","u32","u64","u128","usize","f16","f32","f64","f128","str","char","bool","Box","Option","Result","String","Vec"] +;return{name:"Rust",aliases:["rs"],keywords:{$pattern:e.IDENT_RE+"!?",type:c, +keyword:["abstract","as","async","await","become","box","break","const","continue","crate","do","dyn","else","enum","extern","false","final","fn","for","if","impl","in","let","loop","macro","match","mod","move","mut","override","priv","pub","raw","ref","return","self","Self","static","struct","super","trait","true","try","type","typeof","union","unsafe","unsized","use","virtual","where","while","yield"], +literal:["true","false","Some","None","Ok","Err"],built_in:o},illegal:""},r]}},grmr_scss:e=>{ +const n=Ce(e),t=Ie,a=De,i="@[a-z-]+",r={className:"variable", +begin:"(\\$[a-zA-Z-][a-zA-Z0-9_-]*)\\b",relevance:0};return{name:"SCSS", +case_insensitive:!0,illegal:"[=/|']", +contains:[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,n.CSS_NUMBER_MODE,{ +className:"selector-id",begin:"#[A-Za-z0-9_-]+",relevance:0},{ +className:"selector-class",begin:"\\.[A-Za-z0-9_-]+",relevance:0 +},n.ATTRIBUTE_SELECTOR_MODE,{className:"selector-tag", +begin:"\\b("+Te.join("|")+")\\b",relevance:0},{className:"selector-pseudo", +begin:":("+a.join("|")+")"},{className:"selector-pseudo", +begin:":(:)?("+t.join("|")+")"},r,{begin:/\(/,end:/\)/, +contains:[n.CSS_NUMBER_MODE]},n.CSS_VARIABLE,{className:"attribute", +begin:"\\b("+Le.join("|")+")\\b"},{ +begin:"\\b(whitespace|wait|w-resize|visible|vertical-text|vertical-ideographic|uppercase|upper-roman|upper-alpha|underline|transparent|top|thin|thick|text|text-top|text-bottom|tb-rl|table-header-group|table-footer-group|sw-resize|super|strict|static|square|solid|small-caps|separate|se-resize|scroll|s-resize|rtl|row-resize|ridge|right|repeat|repeat-y|repeat-x|relative|progress|pointer|overline|outside|outset|oblique|nowrap|not-allowed|normal|none|nw-resize|no-repeat|no-drop|newspaper|ne-resize|n-resize|move|middle|medium|ltr|lr-tb|lowercase|lower-roman|lower-alpha|loose|list-item|line|line-through|line-edge|lighter|left|keep-all|justify|italic|inter-word|inter-ideograph|inside|inset|inline|inline-block|inherit|inactive|ideograph-space|ideograph-parenthesis|ideograph-numeric|ideograph-alpha|horizontal|hidden|help|hand|groove|fixed|ellipsis|e-resize|double|dotted|distribute|distribute-space|distribute-letter|distribute-all-lines|disc|disabled|default|decimal|dashed|crosshair|collapse|col-resize|circle|char|center|capitalize|break-word|break-all|bottom|both|bolder|bold|block|bidi-override|below|baseline|auto|always|all-scroll|absolute|table|table-cell)\\b" +},{begin:/:/,end:/[;}{]/,relevance:0, +contains:[n.BLOCK_COMMENT,r,n.HEXCOLOR,n.CSS_NUMBER_MODE,n.UNICODE_RANGE,e.QUOTE_STRING_MODE,e.APOS_STRING_MODE,n.IMPORTANT,n.FUNCTION_DISPATCH] +},{begin:"@(page|font-face)",keywords:{$pattern:i,keyword:"@page @font-face"}},{ +begin:"@",end:"[{;]",returnBegin:!0,keywords:{$pattern:/[a-z-]+/, +keyword:"and or not only",attribute:Re.join(" ")},contains:[{begin:i, +className:"keyword"},{begin:/[a-z-]+(?=:)/,className:"attribute" +},r,e.QUOTE_STRING_MODE,e.APOS_STRING_MODE,n.HEXCOLOR,n.CSS_NUMBER_MODE] +},n.FUNCTION_DISPATCH]}},grmr_shell:e=>({name:"Shell Session", +aliases:["console","shellsession"],contains:[{className:"meta.prompt", +begin:/^\s{0,3}[./~\w\d[\]()@-]*[>%$#][ ]?/,starts:{end:/[^\\](?=\s*$)/, +subLanguage:"bash"}}]}),grmr_sql:e=>{ +const n=e.regex,t=e.COMMENT("--","$"),a=["abs","acos","array_agg","asin","atan","avg","cast","ceil","ceiling","coalesce","corr","cos","cosh","count","covar_pop","covar_samp","cume_dist","dense_rank","deref","element","exp","extract","first_value","floor","json_array","json_arrayagg","json_exists","json_object","json_objectagg","json_query","json_table","json_table_primitive","json_value","lag","last_value","lead","listagg","ln","log","log10","lower","max","min","mod","nth_value","ntile","nullif","percent_rank","percentile_cont","percentile_disc","position","position_regex","power","rank","regr_avgx","regr_avgy","regr_count","regr_intercept","regr_r2","regr_slope","regr_sxx","regr_sxy","regr_syy","row_number","sin","sinh","sqrt","stddev_pop","stddev_samp","substring","substring_regex","sum","tan","tanh","translate","translate_regex","treat","trim","trim_array","unnest","upper","value_of","var_pop","var_samp","width_bucket"],i=a,r=["abs","acos","all","allocate","alter","and","any","are","array","array_agg","array_max_cardinality","as","asensitive","asin","asymmetric","at","atan","atomic","authorization","avg","begin","begin_frame","begin_partition","between","bigint","binary","blob","boolean","both","by","call","called","cardinality","cascaded","case","cast","ceil","ceiling","char","char_length","character","character_length","check","classifier","clob","close","coalesce","collate","collect","column","commit","condition","connect","constraint","contains","convert","copy","corr","corresponding","cos","cosh","count","covar_pop","covar_samp","create","cross","cube","cume_dist","current","current_catalog","current_date","current_default_transform_group","current_path","current_role","current_row","current_schema","current_time","current_timestamp","current_path","current_role","current_transform_group_for_type","current_user","cursor","cycle","date","day","deallocate","dec","decimal","decfloat","declare","default","define","delete","dense_rank","deref","describe","deterministic","disconnect","distinct","double","drop","dynamic","each","element","else","empty","end","end_frame","end_partition","end-exec","equals","escape","every","except","exec","execute","exists","exp","external","extract","false","fetch","filter","first_value","float","floor","for","foreign","frame_row","free","from","full","function","fusion","get","global","grant","group","grouping","groups","having","hold","hour","identity","in","indicator","initial","inner","inout","insensitive","insert","int","integer","intersect","intersection","interval","into","is","join","json_array","json_arrayagg","json_exists","json_object","json_objectagg","json_query","json_table","json_table_primitive","json_value","lag","language","large","last_value","lateral","lead","leading","left","like","like_regex","listagg","ln","local","localtime","localtimestamp","log","log10","lower","match","match_number","match_recognize","matches","max","member","merge","method","min","minute","mod","modifies","module","month","multiset","national","natural","nchar","nclob","new","no","none","normalize","not","nth_value","ntile","null","nullif","numeric","octet_length","occurrences_regex","of","offset","old","omit","on","one","only","open","or","order","out","outer","over","overlaps","overlay","parameter","partition","pattern","per","percent","percent_rank","percentile_cont","percentile_disc","period","portion","position","position_regex","power","precedes","precision","prepare","primary","procedure","ptf","range","rank","reads","real","recursive","ref","references","referencing","regr_avgx","regr_avgy","regr_count","regr_intercept","regr_r2","regr_slope","regr_sxx","regr_sxy","regr_syy","release","result","return","returns","revoke","right","rollback","rollup","row","row_number","rows","running","savepoint","scope","scroll","search","second","seek","select","sensitive","session_user","set","show","similar","sin","sinh","skip","smallint","some","specific","specifictype","sql","sqlexception","sqlstate","sqlwarning","sqrt","start","static","stddev_pop","stddev_samp","submultiset","subset","substring","substring_regex","succeeds","sum","symmetric","system","system_time","system_user","table","tablesample","tan","tanh","then","time","timestamp","timezone_hour","timezone_minute","to","trailing","translate","translate_regex","translation","treat","trigger","trim","trim_array","true","truncate","uescape","union","unique","unknown","unnest","update","upper","user","using","value","values","value_of","var_pop","var_samp","varbinary","varchar","varying","versioning","when","whenever","where","width_bucket","window","with","within","without","year","add","asc","collation","desc","final","first","last","view"].filter(e=>!a.includes(e)),s={ +match:n.concat(/\b/,n.either(...i),/\s*\(/),relevance:0,keywords:{built_in:i}} +;function o(e){ +return n.concat(/\b/,n.either(...e.map(e=>e.replace(/\s+/,"\\s+"))),/\b/)} +const c={scope:"keyword", +match:o(["create table","insert into","primary key","foreign key","not null","alter table","add constraint","grouping sets","on overflow","character set","respect nulls","ignore nulls","nulls first","nulls last","depth first","breadth first"]), +relevance:0};return{name:"SQL",case_insensitive:!0,illegal:/[{}]|<\//,keywords:{ +$pattern:/\b[\w\.]+/,keyword:((e,{exceptions:n,when:t}={})=>{const a=t +;return n=n||[],e.map(e=>e.match(/\|\d+$/)||n.includes(e)?e:a(e)?e+"|0":e)})(r,{ +when:e=>e.length<3}),literal:["true","false","unknown"], +type:["bigint","binary","blob","boolean","char","character","clob","date","dec","decfloat","decimal","float","int","integer","interval","nchar","nclob","national","numeric","real","row","smallint","time","timestamp","varchar","varying","varbinary"], +built_in:["current_catalog","current_date","current_default_transform_group","current_path","current_role","current_schema","current_transform_group_for_type","current_user","session_user","system_time","system_user","current_time","localtime","current_timestamp","localtimestamp"] +},contains:[{scope:"type", +match:o(["double precision","large object","with timezone","without timezone"]) +},c,s,{scope:"variable",match:/@[a-z0-9][a-z0-9_]*/},{scope:"string",variants:[{ +begin:/'/,end:/'/,contains:[{match:/''/}]}]},{begin:/"/,end:/"/,contains:[{ +match:/""/}]},e.C_NUMBER_MODE,e.C_BLOCK_COMMENT_MODE,t,{scope:"operator", +match:/[-+*/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?/,relevance:0}]}}, +grmr_swift:e=>{const n={match:/\s+/,relevance:0},t=e.COMMENT("/\\*","\\*/",{ +contains:["self"]}),a=[e.C_LINE_COMMENT_MODE,t],i={match:[/\./,m(...be,...me)], +className:{2:"keyword"}},r={match:b(/\./,m(..._e)),relevance:0 +},s=_e.filter(e=>"string"==typeof e).concat(["_|0"]),o={variants:[{ +className:"keyword", +match:m(..._e.filter(e=>"string"!=typeof e).concat(pe).map(ue),...me)}]},c={ +$pattern:m(/\b\w+/,/#\w+/),keyword:s.concat(Ee),literal:he},l=[i,r,o],g=[{ +match:b(/\./,m(...ye)),relevance:0},{className:"built_in", +match:b(/\b/,m(...ye),/(?=\()/)}],u={match:/->/,relevance:0},p=[u,{ +className:"operator",relevance:0,variants:[{match:Ne},{match:`\\.(\\.|${ve})+`}] +}],_="([0-9]_*)+",h="([0-9a-fA-F]_*)+",f={className:"number",relevance:0, +variants:[{match:`\\b(${_})(\\.(${_}))?([eE][+-]?(${_}))?\\b`},{ +match:`\\b0x(${h})(\\.(${h}))?([pP][+-]?(${_}))?\\b`},{match:/\b0o([0-7]_*)+\b/ +},{match:/\b0b([01]_*)+\b/}]},E=(e="")=>({className:"subst",variants:[{ +match:b(/\\/,e,/[0\\tnr"']/)},{match:b(/\\/,e,/u\{[0-9a-fA-F]{1,8}\}/)}] +}),y=(e="")=>({className:"subst",match:b(/\\/,e,/[\t ]*(?:[\r\n]|\r\n)/) +}),w=(e="")=>({className:"subst",label:"interpol",begin:b(/\\/,e,/\(/),end:/\)/ +}),v=(e="")=>({begin:b(e,/"""/),end:b(/"""/,e),contains:[E(e),y(e),w(e)] +}),N=(e="")=>({begin:b(e,/"/),end:b(/"/,e),contains:[E(e),w(e)]}),k={ +className:"string", +variants:[v(),v("#"),v("##"),v("###"),N(),N("#"),N("##"),N("###")] +},x=[e.BACKSLASH_ESCAPE,{begin:/\[/,end:/\]/,relevance:0, +contains:[e.BACKSLASH_ESCAPE]}],O={begin:/\/[^\s](?=[^/\n]*\/)/,end:/\//, +contains:x},M=e=>{const n=b(e,/\//),t=b(/\//,e);return{begin:n,end:t, +contains:[...x,{scope:"comment",begin:`#(?!.*${t})`,end:/$/}]}},A={ +scope:"regexp",variants:[M("###"),M("##"),M("#"),O]},S={match:b(/`/,Oe,/`/) +},C=[S,{className:"variable",match:/\$\d+/},{className:"variable", +match:`\\$${xe}+`}],T=[{match:/(@|#(un)?)available/,scope:"keyword",starts:{ +contains:[{begin:/\(/,end:/\)/,keywords:Se,contains:[...p,f,k]}]}},{ +scope:"keyword",match:b(/@/,m(...Ae),d(m(/\(/,/\s+/)))},{scope:"meta", +match:b(/@/,Oe)}],R={match:d(/\b[A-Z]/),relevance:0,contains:[{className:"type", +match:b(/(AV|CA|CF|CG|CI|CL|CM|CN|CT|MK|MP|MTK|MTL|NS|SCN|SK|UI|WK|XC)/,xe,"+") +},{className:"type",match:Me,relevance:0},{match:/[?!]+/,relevance:0},{ +match:/\.\.\./,relevance:0},{match:b(/\s+&\s+/,d(Me)),relevance:0}]},D={ +begin://,keywords:c,contains:[...a,...l,...T,u,R]};R.contains.push(D) +;const I={begin:/\(/,end:/\)/,relevance:0,keywords:c,contains:["self",{ +match:b(Oe,/\s*:/),keywords:"_|0",relevance:0 +},...a,A,...l,...g,...p,f,k,...C,...T,R]},L={begin://, +keywords:"repeat each",contains:[...a,R]},B={begin:/\(/,end:/\)/,keywords:c, +contains:[{begin:m(d(b(Oe,/\s*:/)),d(b(Oe,/\s+/,Oe,/\s*:/))),end:/:/, +relevance:0,contains:[{className:"keyword",match:/\b_\b/},{className:"params", +match:Oe}]},...a,...l,...p,f,k,...T,R,I],endsParent:!0,illegal:/["']/},F={ +match:[/(func|macro)/,/\s+/,m(S.match,Oe,Ne)],className:{1:"keyword", +3:"title.function"},contains:[L,B,n],illegal:[/\[/,/%/]},$={ +match:[/\b(?:subscript|init[?!]?)/,/\s*(?=[<(])/],className:{1:"keyword"}, +contains:[L,B,n],illegal:/\[|%/},z={match:[/operator/,/\s+/,Ne],className:{ +1:"keyword",3:"title"}},U={begin:[/precedencegroup/,/\s+/,Me],className:{ +1:"keyword",3:"title"},contains:[R],keywords:[...fe,...he],end:/}/},j={ +begin:[/(struct|protocol|class|extension|enum|actor)/,/\s+/,Oe,/\s*/], +beginScope:{1:"keyword",3:"title.class"},keywords:c,contains:[L,...l,{begin:/:/, +end:/\{/,keywords:c,contains:[{scope:"title.class.inherited",match:Me},...l], +relevance:0}]};for(const e of k.variants){ +const n=e.contains.find(e=>"interpol"===e.label);n.keywords=c +;const t=[...l,...g,...p,f,k,...C];n.contains=[...t,{begin:/\(/,end:/\)/, +contains:["self",...t]}]}return{name:"Swift",keywords:c,contains:[...a,F,$,{ +match:[/class\b/,/\s+/,/func\b/,/\s+/,/\b[A-Za-z_][A-Za-z0-9_]*\b/],scope:{ +1:"keyword",3:"keyword",5:"title.function"}},{match:[/class\b/,/\s+/,/var\b/], +scope:{1:"keyword",3:"keyword"}},j,z,U,{beginKeywords:"import",end:/$/, +contains:[...a],relevance:0},A,...l,...g,...p,f,k,...C,...T,R,I]}}, +grmr_typescript:e=>{ +const n=e.regex,t=ge(e),a=te,i=["any","void","number","boolean","string","object","never","symbol","bigint","unknown"],r={ +begin:[/namespace/,/\s+/,e.IDENT_RE],beginScope:{1:"keyword",3:"title.class"} +},s={beginKeywords:"interface",end:/\{/,excludeEnd:!0,keywords:{ +keyword:"interface extends",built_in:i},contains:[t.exports.CLASS_REFERENCE] +},o={$pattern:te, +keyword:ie.concat(["type","interface","public","private","protected","implements","declare","abstract","readonly","enum","override","satisfies"]), +literal:re,built_in:de.concat(i),"variable.language":le},c={className:"meta", +begin:"@"+a},l=(e,n,t)=>{const a=e.contains.findIndex(e=>e.label===n) +;if(-1===a)throw Error("can not find mode to replace");e.contains.splice(a,1,t)} +;Object.assign(t.keywords,o),t.exports.PARAMS_CONTAINS.push(c) +;const d=t.contains.find(e=>"attr"===e.scope),g=Object.assign({},d,{ +match:n.concat(a,n.lookahead(/\s*\?:/))}) +;return t.exports.PARAMS_CONTAINS.push([t.exports.CLASS_REFERENCE,d,g]), +t.contains=t.contains.concat([c,r,s,g]), +l(t,"shebang",e.SHEBANG()),l(t,"use_strict",{className:"meta",relevance:10, +begin:/^\s*['"]use strict['"]/ +}),t.contains.find(e=>"func.def"===e.label).relevance=0,Object.assign(t,{ +name:"TypeScript",aliases:["ts","tsx","mts","cts"]}),t},grmr_vbnet:e=>{ +const n=e.regex,t=/\d{1,2}\/\d{1,2}\/\d{4}/,a=/\d{4}-\d{1,2}-\d{1,2}/,i=/(\d|1[012])(:\d+){0,2} *(AM|PM)/,r=/\d{1,2}(:\d{1,2}){1,2}/,s={ +className:"literal",variants:[{begin:n.concat(/# */,n.either(a,t),/ *#/)},{ +begin:n.concat(/# */,r,/ *#/)},{begin:n.concat(/# */,i,/ *#/)},{ +begin:n.concat(/# */,n.either(a,t),/ +/,n.either(i,r),/ *#/)}] +},o=e.COMMENT(/'''/,/$/,{contains:[{className:"doctag",begin:/<\/?/,end:/>/}] +}),c=e.COMMENT(null,/$/,{variants:[{begin:/'/},{begin:/([\t ]|^)REM(?=\s)/}]}) +;return{name:"Visual Basic .NET",aliases:["vb"],case_insensitive:!0, +classNameAliases:{label:"symbol"},keywords:{ +keyword:"addhandler alias aggregate ansi as async assembly auto binary by byref byval call case catch class compare const continue custom declare default delegate dim distinct do each equals else elseif end enum erase error event exit explicit finally for friend from function get global goto group handles if implements imports in inherits interface into iterator join key let lib loop me mid module mustinherit mustoverride mybase myclass namespace narrowing new next notinheritable notoverridable of off on operator option optional order overloads overridable overrides paramarray partial preserve private property protected public raiseevent readonly redim removehandler resume return select set shadows shared skip static step stop structure strict sub synclock take text then throw to try unicode until using when where while widening with withevents writeonly yield", +built_in:"addressof and andalso await directcast gettype getxmlnamespace is isfalse isnot istrue like mod nameof new not or orelse trycast typeof xor cbool cbyte cchar cdate cdbl cdec cint clng cobj csbyte cshort csng cstr cuint culng cushort", +type:"boolean byte char date decimal double integer long object sbyte short single string uinteger ulong ushort", +literal:"true false nothing"}, +illegal:"//|\\{|\\}|endif|gosub|variant|wend|^\\$ ",contains:[{ +className:"string",begin:/"(""|[^/n])"C\b/},{className:"string",begin:/"/, +end:/"/,illegal:/\n/,contains:[{begin:/""/}]},s,{className:"number",relevance:0, +variants:[{begin:/\b\d[\d_]*((\.[\d_]+(E[+-]?[\d_]+)?)|(E[+-]?[\d_]+))[RFD@!#]?/ +},{begin:/\b\d[\d_]*((U?[SIL])|[%&])?/},{begin:/&H[\dA-F_]+((U?[SIL])|[%&])?/},{ +begin:/&O[0-7_]+((U?[SIL])|[%&])?/},{begin:/&B[01_]+((U?[SIL])|[%&])?/}]},{ +className:"label",begin:/^\w+:/},o,c,{className:"meta", +begin:/[\t ]*#(const|disable|else|elseif|enable|end|externalsource|if|region)\b/, +end:/$/,keywords:{ +keyword:"const disable else elseif enable end externalsource if region then"}, +contains:[c]}]}},grmr_wasm:e=>{e.regex;const n=e.COMMENT(/\(;/,/;\)/) +;return n.contains.push("self"),{name:"WebAssembly",keywords:{$pattern:/[\w.]+/, +keyword:["anyfunc","block","br","br_if","br_table","call","call_indirect","data","drop","elem","else","end","export","func","global.get","global.set","local.get","local.set","local.tee","get_global","get_local","global","if","import","local","loop","memory","memory.grow","memory.size","module","mut","nop","offset","param","result","return","select","set_global","set_local","start","table","tee_local","then","type","unreachable"] +},contains:[e.COMMENT(/;;/,/$/),n,{match:[/(?:offset|align)/,/\s*/,/=/], +className:{1:"keyword",3:"operator"}},{className:"variable",begin:/\$[\w_]+/},{ +match:/(\((?!;)|\))+/,className:"punctuation",relevance:0},{ +begin:[/(?:func|call|call_indirect)/,/\s+/,/\$[^\s)]+/],className:{1:"keyword", +3:"title.function"}},e.QUOTE_STRING_MODE,{match:/(i32|i64|f32|f64)(?!\.)/, +className:"type"},{className:"keyword", +match:/\b(f32|f64|i32|i64)(?:\.(?:abs|add|and|ceil|clz|const|convert_[su]\/i(?:32|64)|copysign|ctz|demote\/f64|div(?:_[su])?|eqz?|extend_[su]\/i32|floor|ge(?:_[su])?|gt(?:_[su])?|le(?:_[su])?|load(?:(?:8|16|32)_[su])?|lt(?:_[su])?|max|min|mul|nearest|neg?|or|popcnt|promote\/f32|reinterpret\/[fi](?:32|64)|rem_[su]|rot[lr]|shl|shr_[su]|store(?:8|16|32)?|sqrt|sub|trunc(?:_[su]\/f(?:32|64))?|wrap\/i64|xor))\b/ +},{className:"number",relevance:0, +match:/[+-]?\b(?:\d(?:_?\d)*(?:\.\d(?:_?\d)*)?(?:[eE][+-]?\d(?:_?\d)*)?|0x[\da-fA-F](?:_?[\da-fA-F])*(?:\.[\da-fA-F](?:_?[\da-fA-D])*)?(?:[pP][+-]?\d(?:_?\d)*)?)\b|\binf\b|\bnan(?::0x[\da-fA-F](?:_?[\da-fA-D])*)?\b/ +}]}},grmr_xml:e=>{ +const n=e.regex,t=n.concat(/[\p{L}_]/u,n.optional(/[\p{L}0-9_.-]*:/u),/[\p{L}0-9_.-]*/u),a={ +className:"symbol",begin:/&[a-z]+;|&#[0-9]+;|&#x[a-f0-9]+;/},i={begin:/\s/, +contains:[{className:"keyword",begin:/#?[a-z_][a-z1-9_-]+/,illegal:/\n/}] +},r=e.inherit(i,{begin:/\(/,end:/\)/}),s=e.inherit(e.APOS_STRING_MODE,{ +className:"string"}),o=e.inherit(e.QUOTE_STRING_MODE,{className:"string"}),c={ +endsWithParent:!0,illegal:/`]+/}]}]}]};return{ +name:"HTML, XML", +aliases:["html","xhtml","rss","atom","xjb","xsd","xsl","plist","wsf","svg"], +case_insensitive:!0,unicodeRegex:!0,contains:[{className:"meta",begin://,relevance:10,contains:[i,o,s,r,{begin:/\[/,end:/\]/,contains:[{ +className:"meta",begin://,contains:[i,r,o,s]}]}] +},e.COMMENT(//,{relevance:10}),{begin://, +relevance:10},a,{className:"meta",end:/\?>/,variants:[{begin:/<\?xml/, +relevance:10,contains:[o]},{begin:/<\?[a-z][a-z0-9]+/}]},{className:"tag", +begin:/)/,end:/>/,keywords:{name:"style"},contains:[c],starts:{ +end:/<\/style>/,returnEnd:!0,subLanguage:"css"}},{className:"tag", +begin:/)/,end:/>/,keywords:{name:"script"},contains:[c],starts:{ +end:/<\/script>/,returnEnd:!0,subLanguage:"javascript"}},{className:"tag", +begin:/<>|<\/>/},{className:"tag", +begin:n.concat(//,/>/,/\s/)))), +end:/\/?>/,contains:[{className:"name",begin:t,relevance:0,starts:c}]},{ +className:"tag",begin:n.concat(/<\//,n.lookahead(n.concat(t,/>/))),contains:[{ +className:"name",begin:t,relevance:0},{begin:/>/,relevance:0,endsParent:!0}]}]} +},grmr_yaml:e=>{ +const n="true false yes no null",t="[\\w#;/?:@&=+$,.~*'()[\\]]+",a={ +className:"string",relevance:0,variants:[{begin:/"/,end:/"/},{begin:/\S+/}], +contains:[e.BACKSLASH_ESCAPE,{className:"template-variable",variants:[{ +begin:/\{\{/,end:/\}\}/},{begin:/%\{/,end:/\}/}]}]},i=e.inherit(a,{variants:[{ +begin:/'/,end:/'/,contains:[{begin:/''/,relevance:0}]},{begin:/"/,end:/"/},{ +begin:/[^\s,{}[\]]+/}]}),r={end:",",endsWithParent:!0,excludeEnd:!0,keywords:n, +relevance:0},s={begin:/\{/,end:/\}/,contains:[r],illegal:"\\n",relevance:0},o={ +begin:"\\[",end:"\\]",contains:[r],illegal:"\\n",relevance:0},c=[{ +className:"attr",variants:[{begin:/[\w*@][\w*@ :()\./-]*:(?=[ \t]|$)/},{ +begin:/"[\w*@][\w*@ :()\./-]*":(?=[ \t]|$)/},{ +begin:/'[\w*@][\w*@ :()\./-]*':(?=[ \t]|$)/}]},{className:"meta", +begin:"^---\\s*$",relevance:10},{className:"string", +begin:"[\\|>]([1-9]?[+-])?[ ]*\\n( +)[^ ][^\\n]*\\n(\\2[^\\n]+\\n?)*"},{ +begin:"<%[%=-]?",end:"[%-]?%>",subLanguage:"ruby",excludeBegin:!0,excludeEnd:!0, +relevance:0},{className:"type",begin:"!\\w+!"+t},{className:"type", +begin:"!<"+t+">"},{className:"type",begin:"!"+t},{className:"type",begin:"!!"+t +},{className:"meta",begin:"&"+e.UNDERSCORE_IDENT_RE+"$"},{className:"meta", +begin:"\\*"+e.UNDERSCORE_IDENT_RE+"$"},{className:"bullet",begin:"-(?=[ ]|$)", +relevance:0},e.HASH_COMMENT_MODE,{beginKeywords:n,keywords:{literal:n}},{ +className:"number", +begin:"\\b[0-9]{4}(-[0-9][0-9]){0,2}([Tt \\t][0-9][0-9]?(:[0-9][0-9]){2})?(\\.[0-9]*)?([ \\t])*(Z|[-+][0-9][0-9]?(:[0-9][0-9])?)?\\b" +},{className:"number",begin:e.C_NUMBER_RE+"\\b",relevance:0},s,o,{ +className:"string",relevance:0,begin:/'/,end:/'/,contains:[{match:/''/, +scope:"char.escape",relevance:0}]},a],l=[...c] +;return l.pop(),l.push(i),r.contains=l,{name:"YAML",case_insensitive:!0, +aliases:["yml"],contains:c}}});const Ke=ne;for(const e of Object.keys(Pe)){ +const n=e.replace("grmr_","").replace("_","-");Ke.registerLanguage(n,Pe[e])} +export{Ke as default}; \ No newline at end of file diff --git a/vendor/ort/LICENSE.txt b/vendor/ort/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..31645a141d599cda9ce54024827464d0d0a4fbdf --- /dev/null +++ b/vendor/ort/LICENSE.txt @@ -0,0 +1,9 @@ +onnxruntime-web (https://github.com/microsoft/onnxruntime) +MIT License +Copyright (c) Microsoft Corporation + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/ort/ort-wasm-simd-threaded.asyncify.mjs b/vendor/ort/ort-wasm-simd-threaded.asyncify.mjs new file mode 100644 index 0000000000000000000000000000000000000000..db24b9639c1427b829e269f98381ffe850d3dce6 --- /dev/null +++ b/vendor/ort/ort-wasm-simd-threaded.asyncify.mjs @@ -0,0 +1,124 @@ +async function ortWasmThreaded(moduleArg={}){var moduleRtn;var g=moduleArg,aa=!!globalThis.window,ba=!!globalThis.WorkerGlobalScope,m=globalThis.process?.versions?.node&&"renderer"!=globalThis.process?.type,n=ba&&self.name?.startsWith("em-pthread");if(m){const {createRequire:a}=await import("module");var require=a(import.meta.url),ca=require("worker_threads");global.Worker=ca.Worker;n=(ba=!ca.Qe)&&"em-pthread"==ca.workerData}g.mountExternalData=(a,b)=>{a.startsWith("./")&&(a=a.substring(2));(g.ed||(g.ed=new Map)).set(a,b)}; +g.unmountExternalData=()=>{delete g.ed;delete g.Te;delete g.Se;delete g.Ue};var SharedArrayBuffer=globalThis.SharedArrayBuffer??(new WebAssembly.Memory({initial:0,maximum:0,shared:!0})).buffer.constructor; +let ea=()=>{const a=b=>(...c)=>{const d=r;c=b(...c);return r!=d?da():c};(b=>{for(const c of b)g[c]=a(g[c])})(["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"]);"undefined"!==typeof jsepRunAsync&&(g._OrtRun=jsepRunAsync(g._OrtRun),g._OrtRunWithBinding=jsepRunAsync(g._OrtRunWithBinding));ea=void 0};g.asyncInit=()=>{ea?.()};var fa="./this.program",ha=(a,b)=>{throw b;},ia=import.meta.url,ka="",la,ma; +if(m){var fs=require("fs");ia.startsWith("file:")&&(ka=require("path").dirname(require("url").fileURLToPath(ia))+"/");ma=a=>{a=na(a)?new URL(a):a;return fs.readFileSync(a)};la=async a=>{a=na(a)?new URL(a):a;return fs.readFileSync(a,void 0)};1{process.exitCode=a;throw b;}}else if(aa||ba){try{ka=(new URL(".",ia)).href}catch{}m||(ba&&(ma=a=>{var b=new XMLHttpRequest;b.open("GET",a,!1);b.responseType="arraybuffer"; +b.send(null);return new Uint8Array(b.response)}),la=async a=>{if(na(a))return new Promise((c,d)=>{var e=new XMLHttpRequest;e.open("GET",a,!0);e.responseType="arraybuffer";e.onload=()=>{200==e.status||0==e.status&&e.response?c(e.response):d(e.status)};e.onerror=d;e.send(null)});var b=await fetch(a,{credentials:"same-origin"});if(b.ok)return b.arrayBuffer();throw Error(b.status+" : "+b.url);})}var oa=console.log.bind(console),pa=console.error.bind(console); +if(m){var qa=require("util"),ra=a=>"object"==typeof a?qa.inspect(a):a;oa=(...a)=>fs.writeSync(1,a.map(ra).join(" ")+"\n");pa=(...a)=>fs.writeSync(2,a.map(ra).join(" ")+"\n")}var sa=oa,t=pa,ta,ua,va=!1,wa,na=a=>a.startsWith("file://");function u(){v.buffer!=w.buffer&&xa()}var ya,za; +if(m&&n){var Ba=ca.parentPort;Ba.on("message",a=>global.onmessage?.({data:a}));Object.assign(globalThis,{self:global,postMessage:a=>Ba.postMessage(a)});process.on("uncaughtException",a=>{postMessage({$c:"uncaughtException",error:a});process.exit(1)})}var Ca; +if(n){var Da=!1;self.onunhandledrejection=b=>{throw b.reason||b;};function a(b){try{var c=b.data,d=c.$c;if("load"===d){let e=[];self.onmessage=f=>e.push(f);Ca=()=>{postMessage({$c:"loaded"});for(let f of e)a(f);self.onmessage=a};for(const f of c.ue)if(!g[f]||g[f].proxy)g[f]=(...k)=>{postMessage({$c:"callHandler",te:f,args:k})},"print"==f&&(sa=g[f]),"printErr"==f&&(t=g[f]);v=c.Me;xa();ua=c.Ne;Ea();Fa()}else if("run"===d){Ga(c.Xc);Ha(c.Xc,0,0,1,0,0);Ia();Ja(c.Xc);Da||(Ka(),Da=!0);try{La(c.ze,c.kd)}catch(e){if("unwind"!= +e)throw e;}}else"setimmediate"!==c.target&&("checkMailbox"===d?Da&&Ma():d&&(t(`worker: received unknown command ${d}`),t(c)))}catch(e){throw Na(),e;}}self.onmessage=a}var w,x,Oa,Pa,B,C,Qa,D,E,Ra,Sa=!1;function xa(){var a=v.buffer;g.HEAP8=w=new Int8Array(a);Oa=new Int16Array(a);g.HEAPU8=x=new Uint8Array(a);Pa=new Uint16Array(a);g.HEAP32=B=new Int32Array(a);g.HEAPU32=C=new Uint32Array(a);Qa=new Float32Array(a);D=new Float64Array(a);E=new BigInt64Array(a);Ra=new BigUint64Array(a)} +function Ta(){Sa=!0;n?Ca():F.hc()}function G(a){a="Aborted("+a+")";t(a);va=!0;a=new WebAssembly.RuntimeError(a+". Build with -sASSERTIONS for more info.");za?.(a);throw a;}var Ua;async function Va(a){if(!ta)try{var b=await la(a);return new Uint8Array(b)}catch{}if(a==Ua&&ta)a=new Uint8Array(ta);else if(ma)a=ma(a);else throw"both async and sync fetching of the wasm failed";return a} +async function Wa(a,b){try{var c=await Va(a);return await WebAssembly.instantiate(c,b)}catch(d){t(`failed to asynchronously prepare wasm: ${d}`),G(d)}}async function Xa(a){var b=Ua;if(!ta&&!na(b)&&!m)try{var c=fetch(b,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(c,a)}catch(d){t(`wasm streaming compile failed: ${d}`),t("falling back to ArrayBuffer instantiation")}return Wa(b,a)} +function Ya(){Za={qa:$a,f:ab,K:bb,k:cb,p:db,l:eb,fa:fb,b:gb,da:hb,gc:ib,q:jb,ea:kb,Ua:lb,cc:mb,ec:nb,Va:ob,Sa:pb,La:qb,Ra:rb,oa:sb,dc:tb,ac:ub,Ta:vb,bc:wb,_a:xb,Ba:yb,Xb:zb,Vb:Ab,Aa:Bb,O:Cb,J:Eb,Wb:Fb,ka:Gb,Yb:Hb,Oa:Ib,_b:Jb,Ea:Kb,Tb:Lb,Ca:Mb,Na:Ja,Xa:Nb,U:Ob,n:Pb,c:Qb,qb:Rb,w:Sb,N:Tb,A:Ub,j:Vb,o:Wb,rb:Xb,H:Yb,T:Zb,g:$b,u:ac,m:bc,i:cc,Ia:dc,Ja:ec,Ka:fc,Ga:gc,Ha:hc,Ub:ic,ab:jc,Za:kc,Z:lc,pb:mc,Da:nc,Ya:oc,X:pc,Wa:qc,$b:rc,G:sc,db:tc,_:uc,pa:vc,Zb:wc,cb:xc,bb:yc,lb:zc,z:Ac,sa:Bc,ra:Cc,nb:Dc,Y:Ec,v:Fc, +kb:Gc,jb:Hc,ib:Ic,mb:Jc,gb:Kc,fb:Lc,eb:Mc,Pa:Nc,Qa:Oc,fc:Pc,W:Qc,Fa:Rc,ma:Sc,Ma:Tc,la:Uc,Fb:Vc,va:Wc,Gb:Xc,wa:Yc,E:Zc,e:$c,r:ad,x:bd,C:cd,Ib:dd,ca:ed,D:fd,xa:gd,aa:hd,ha:jd,Jb:kd,Kb:ld,za:md,Lb:nd,ya:od,Mb:pd,ua:qd,ba:rd,d:sd,B:td,s:ud,Eb:vd,t:wd,y:xd,F:yd,I:zd,L:Ad,Nb:Bd,R:Cd,ia:Dd,$:Ed,Pb:Fd,Rb:Gd,Ob:Hd,h:Id,a:v,$a:Jd,Hb:Kd,V:Ld,M:Md,na:Nd,Db:Od,ja:Pd,S:Qd,Ab:Rd,Bb:Sd,vb:Td,wb:Ud,P:Vd,xb:Wd,yb:Xd,ta:Yd,Sb:Zd,ob:$d,Q:ae,hb:be,Cb:ce,sb:de,tb:ee,ub:fe,ga:ge,zb:he,Qb:ie};return{a:Za}} +async function Ea(){function a(d,e){var f=F=d.exports;d={};for(let [k,h]of Object.entries(f))"function"==typeof h?(f=je(h),d[k]=f):d[k]=h;F=d;F=ke();le.push(F.sd);d=F;me=d.ic;Ka=d.jc;g._OrtInit=d.kc;g._OrtGetLastError=d.lc;g._OrtCreateSessionOptions=d.mc;g._OrtAppendExecutionProvider=d.nc;g._OrtAddFreeDimensionOverride=d.oc;g._OrtAddSessionConfigEntry=d.pc;g._OrtReleaseSessionOptions=d.qc;g._OrtCreateSession=d.rc;g._OrtReleaseSession=d.sc;g._OrtGetInputOutputCount=d.tc;g._OrtGetInputOutputMetadata= +d.uc;g._OrtFree=d.vc;g._OrtCreateTensor=d.wc;g._OrtGetTensorData=d.xc;g._OrtReleaseTensor=d.yc;g._OrtCreateRunOptions=d.zc;g._OrtAddRunConfigEntry=d.Ac;g._OrtReleaseRunOptions=d.Bc;g._OrtCreateBinding=d.Cc;g._OrtBindInput=d.Dc;g._OrtBindOutput=d.Ec;g._OrtClearBoundOutputs=d.Fc;g._OrtReleaseBinding=d.Gc;g._OrtRunWithBinding=d.Hc;g._OrtRun=d.Ic;g._OrtEndProfiling=d.Jc;ne=g._OrtCreateWebGpuInstance=d.Kc;g._wgpuCreateInstance=d.Lc;oe=g._OrtGetWebGpuDevice=d.Mc;pe=d.Nc;H=g._free=d.Oc;qe=g._malloc=d.Pc; +re=g._wgpuBufferRelease=d.Qc;se=d.Rc;te=d.Sc;ue=d.Tc;ve=d.Uc;we=d.Vc;xe=d.Yc;ye=d.Zc;ze=d.hd;Ae=d.id;Be=d.jd;Ce=d.ld;De=d.md;Ee=d.nd;Fe=d.od;Ge=d.pd;He=d.qd;Ie=d.rd;Ha=d.ud;Na=d.vd;Je=d.wd;Ke=d.xd;Le=d.yd;Me=d.zd;Ne=d.Ad;Oe=d.Bd;I=d.Cd;Pe=d.Dd;Qe=d.Ed;J=d.Fd;Re=d.Gd;K=d.Hd;Se=d.Id;Te=d.Jd;Ue=d.Kd;Ve=d.Ld;dynCall_vii=d.Md;We=d.Nd;dynCall_v=d.Od;Xe=d.Pd;Ye=d.Qd;Ze=d.Rd;dynCall_iii=d.Sd;$e=d.Td;af=d.Ud;bf=d.Vd;dynCall_vi=d.Wd;cf=d.Xd;df=d.Yd;ef=d.Zd;ff=d._d;gf=d.$d;hf=d.ae;jf=d.be;kf=d.ce;lf=d.de;mf= +d.fe;nf=d.ge;of=d.he;pf=d.ie;qf=d.je;rf=d.ke;sf=d.le;tf=d.me;uf=d.Ae;vf=d.Be;wf=d.Ce;xf=d.De;yf=d.Ee;zf=d.Fe;Af=d.Ge;Bf=d.He;Cf=d.Ie;Df=d.Je;Ef=d.Ke;Ff=d.nf;Gf=d.of;Hf=d.pf;If=d.qf;ua=e;return F}var b=Ya();if(g.instantiateWasm)return new Promise(d=>{g.instantiateWasm(b,(e,f)=>{d(a(e,f))})});if(n){var c=new WebAssembly.Instance(ua,Ya());return a(c,ua)}Ua??=g.locateFile?g.locateFile?g.locateFile("ort-wasm-simd-threaded.asyncify.wasm",ka):ka+"ort-wasm-simd-threaded.asyncify.wasm":(new URL("ort-wasm-simd-threaded.asyncify.wasm", +import.meta.url)).href;return function(d){return a(d.instance,d.module)}(await Xa(b))}class Jf{name="ExitStatus";constructor(a){this.message=`Program terminated with exit(${a})`;this.status=a}} +var Kf=a=>{a.terminate();a.onmessage=()=>{}},Lf=[],Mf=0,Nf=null,Tf=a=>{0==Of.length&&(Pf(),Qf(Of[0]));var b=Of.pop();if(!b)return 6;Rf.push(b);Sf[a.Xc]=b;b.Xc=a.Xc;var c={$c:"run",ze:a.ye,kd:a.kd,Xc:a.Xc};m&&b.unref();b.postMessage(c,a.oe);return 0},L=0,M=(a,b,...c)=>{var d=16*c.length,e=K(),f=Re(d),k=f>>>3,h;for(h of c)"bigint"==typeof h?((u(),E)[k++>>>0]=1n,(u(),E)[k++>>>0]=h):((u(),E)[k++>>>0]=0n,(u(),D)[k++>>>0]=h);a=Je(a,0,d,f,b);J(e);return a}; +function Jd(a){if(n)return M(0,1,a);wa=a;if(!(0{wa=a;if(n)throw Uf(a),"unwind";Jd(a)},Of=[],Rf=[],le=[],Sf={};function Vf(){for(var a=g.numThreads-1;a--;)Pf();Lf.push(async()=>{var b=Wf();Mf++;await b;Mf--;0==Mf&&Nf&&(b=Nf,Nf=null,b())})}var Xf=a=>{var b=a.Xc;delete Sf[b];Of.push(a);Rf.splice(Rf.indexOf(a),1);a.Xc=0;Ke(b)};function Ia(){le.forEach(a=>a())} +var Qf=a=>new Promise(b=>{a.onmessage=f=>{var k=f.data;f=k.$c;if(k.gd&&k.gd!=pe()){var h=Sf[k.gd];h?h.postMessage(k,k.oe):t(`Internal error! Worker sent a message "${f}" to target pthread ${k.gd}, but that thread no longer exists!`)}else if("checkMailbox"===f)Ma();else if("spawnThread"===f)Tf(k);else if("cleanupThread"===f)N(()=>{Xf(Sf[k.Le])});else if("loaded"===f)a.loaded=!0,m&&!a.Xc&&a.unref(),b(a);else if("setimmediate"===k.target)a.postMessage(k);else if("uncaughtException"===f)a.onerror(k.error); +else if("callHandler"===f)g[k.te](...k.args);else f&&t(`worker sent an unknown command ${f}`)};a.onerror=f=>{t(`${"worker sent an error!"} ${f.filename}:${f.lineno}: ${f.message}`);throw f;};m&&(a.on("message",f=>a.onmessage({data:f})),a.on("error",f=>a.onerror(f)));var c=[],d=[],e;for(e of d)g.propertyIsEnumerable(e)&&c.push(e);a.postMessage({$c:"load",ue:c,Me:v,Ne:ua})});async function Wf(){if(!n)return Promise.all(Of.map(Qf))} +function Pf(){var a=new Worker(new URL(import.meta.url),{type:"module",workerData:"em-pthread",name:"em-pthread"});Of.push(a)}function Ga(a){var b=(u(),C)[a+52>>>2>>>0];a=(u(),C)[a+56>>>2>>>0];Qe(b,b-a);J(b)}var La=(a,b)=>{L=0;a=We(a,b);0-9007199254740992>a||9007199254740992>>=0;var b=new $f(a);0==(u(),w)[b.ad+12>>>0]&&(ag(b,!0),Zf--);bg(b,!1);Yf.push(b);return Ve(a)} +var cg=0,bb=()=>{I(0,0);var a=Yf.pop();Se(a.td);cg=0};function ag(a,b){b=b?1:0;(u(),w)[a.ad+12>>>0]=b}function bg(a,b){b=b?1:0;(u(),w)[a.ad+13>>>0]=b}class $f{constructor(a){this.td=a;this.ad=a-24}}var dg=a=>{var b=cg;if(!b)return Pe(0),0;var c=new $f(b);(u(),C)[c.ad+16>>>2>>>0]=b;var d=(u(),C)[c.ad+4>>>2>>>0];if(!d)return Pe(0),b;for(var e of a){if(0===e||e===d)break;if(Ue(e,d,c.ad+16))return Pe(e),b}Pe(d);return b};function cb(){return dg([])}function db(a){return dg([a>>>0])} +function eb(a,b,c,d){return dg([a>>>0,b>>>0,c>>>0,d>>>0])}var fb=()=>{var a=Yf.pop();a||G("no exception to throw");var b=a.td;0==(u(),w)[a.ad+13>>>0]&&(Yf.push(a),bg(a,!0),ag(a,!1),Zf++);Te(b);cg=b;throw cg;};function gb(a,b,c){a>>>=0;var d=new $f(a);b>>>=0;c>>>=0;(u(),C)[d.ad+16>>>2>>>0]=0;(u(),C)[d.ad+4>>>2>>>0]=b;(u(),C)[d.ad+8>>>2>>>0]=c;Te(a);cg=a;Zf++;throw cg;}var hb=()=>Zf;function eg(a,b,c,d){return n?M(2,1,a,b,c,d):ib(a,b,c,d)} +function ib(a,b,c,d){a>>>=0;b>>>=0;c>>>=0;d>>>=0;if(!globalThis.SharedArrayBuffer)return 6;var e=[];if(n&&0===e.length)return eg(a,b,c,d);a={ye:c,Xc:a,kd:d,oe:e};return n?(a.$c="spawnThread",postMessage(a,e),0):Tf(a)}function jb(a){cg||=a>>>0;throw cg;} +var fg=globalThis.TextDecoder&&new TextDecoder,gg=(a,b,c,d)=>{c=b+c;if(d)return c;for(;a[b]&&!(b>=c);)++b;return b},hg=(a,b=0,c,d)=>{b>>>=0;c=gg(a,b,c,d);if(16e?d+=String.fromCharCode(e):(e-=65536,d+=String.fromCharCode(55296| +e>>10,56320|e&1023))}}else d+=String.fromCharCode(e)}return d},ig=(a,b,c)=>(a>>>=0)?hg((u(),x),a,b,c):"";function kb(a,b,c){return n?M(3,1,a,b,c):0}function lb(a,b){if(n)return M(4,1,a,b)}function mb(a,b){if(n)return M(5,1,a,b)}function nb(a,b,c){if(n)return M(6,1,a,b,c)}function ob(a,b,c){return n?M(7,1,a,b,c):0}function pb(a,b){if(n)return M(8,1,a,b)}function qb(a,b,c){if(n)return M(9,1,a,b,c)}function rb(a,b,c,d){if(n)return M(10,1,a,b,c,d)}function sb(a,b,c,d){if(n)return M(11,1,a,b,c,d)} +function tb(a,b,c,d){if(n)return M(12,1,a,b,c,d)}function ub(a){if(n)return M(13,1,a)}function vb(a,b){if(n)return M(14,1,a,b)}function wb(a,b,c){if(n)return M(15,1,a,b,c)}var xb=()=>G(""),P=a=>{a>>>=0;for(var b="";;){var c=(u(),x)[a++>>>0];if(!c)return b;b+=String.fromCharCode(c)}},jg={},kg={},lg={},mg=class extends Error{constructor(a){super(a);this.name="BindingError"}}; +function ng(a,b,c={}){var d=b.name;if(!a)throw new mg(`type "${d}" must have a positive integer typeid pointer`);if(kg.hasOwnProperty(a)){if(c.ve)return;throw new mg(`Cannot register type '${d}' twice`);}kg[a]=b;delete lg[a];jg.hasOwnProperty(a)&&(b=jg[a],delete jg[a],b.forEach(e=>e()))}function Q(a,b,c={}){return ng(a,b,c)} +var og=(a,b,c)=>{switch(b){case 1:return c?d=>(u(),w)[d>>>0]:d=>(u(),x)[d>>>0];case 2:return c?d=>(u(),Oa)[d>>>1>>>0]:d=>(u(),Pa)[d>>>1>>>0];case 4:return c?d=>(u(),B)[d>>>2>>>0]:d=>(u(),C)[d>>>2>>>0];case 8:return c?d=>(u(),E)[d>>>3>>>0]:d=>(u(),Ra)[d>>>3>>>0];default:throw new TypeError(`invalid integer width (${b}): ${a}`);}}; +function yb(a,b,c,d,e){a>>>=0;c>>>=0;b=P(b>>>0);d=0n===d;let f=k=>k;if(d){const k=8*c;f=h=>BigInt.asUintN(k,h);e=f(e)}Q(a,{name:b,Wc:f,cd:(k,h)=>{"number"==typeof h&&(h=BigInt(h));return h},bd:og(b,c,!d),dd:null})}function zb(a,b,c,d){a>>>=0;b=P(b>>>0);Q(a,{name:b,Wc:function(e){return!!e},cd:function(e,f){return f?c:d},bd:function(e){return this.Wc((u(),x)[e>>>0])},dd:null})}var pg=[],qg=[0,1,,1,null,1,!0,1,!1,1];function Qb(a){a>>>=0;9{if(!a)throw new mg(`Cannot use deleted val. handle = ${a}`);return qg[a]},S=a=>{switch(a){case void 0:return 2;case null:return 4;case !0:return 6;case !1:return 8;default:const b=pg.pop()||qg.length;qg[b]=a;qg[b+1]=1;return b}};function rg(a){return this.Wc((u(),C)[a>>>2>>>0])}var sg={name:"emscripten::val",Wc:a=>{var b=R(a);Qb(a);return b},cd:(a,b)=>S(b),bd:rg,dd:null};function Ab(a){return Q(a>>>0,sg)} +var tg=(a,b)=>{switch(b){case 4:return function(c){return this.Wc((u(),Qa)[c>>>2>>>0])};case 8:return function(c){return this.Wc((u(),D)[c>>>3>>>0])};default:throw new TypeError(`invalid float width (${b}): ${a}`);}};function Bb(a,b,c){a>>>=0;c>>>=0;b=P(b>>>0);Q(a,{name:b,Wc:d=>d,cd:(d,e)=>e,bd:tg(b,c),dd:null})}function Cb(a,b,c,d,e){a>>>=0;c>>>=0;b=P(b>>>0);let f=h=>h;if(0===d){var k=32-8*c;f=h=>h<>>k;e=f(e)}Q(a,{name:b,Wc:f,cd:(h,l)=>l,bd:og(b,c,0!==d),dd:null})} +function Eb(a,b,c){function d(f){var k=(u(),C)[f>>>2>>>0];f=(u(),C)[f+4>>>2>>>0];return new e((u(),w).buffer,f,k)}a>>>=0;var e=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][b];c=P(c>>>0);Q(a,{name:c,Wc:d,bd:d},{ve:!0})} +var T=(a,b,c)=>{var d=(u(),x);b>>>=0;if(0=k){if(b>=c)break;d[b++>>>0]=k}else if(2047>=k){if(b+1>=c)break;d[b++>>>0]=192|k>>6;d[b++>>>0]=128|k&63}else if(65535>=k){if(b+2>=c)break;d[b++>>>0]=224|k>>12;d[b++>>>0]=128|k>>6&63;d[b++>>>0]=128|k&63}else{if(b+3>=c)break;d[b++>>>0]=240|k>>18;d[b++>>>0]=128|k>>12&63;d[b++>>>0]=128|k>>6&63;d[b++>>>0]=128|k&63;f++}}d[b>>>0]=0;a=b-e}else a=0;return a},U=a=>{for(var b=0,c=0;c=d?b++:2047>=d?b+=2:55296<=d&&57343>=d?(b+=4,++c):b+=3}return b}; +function Fb(a,b){a>>>=0;b=P(b>>>0);Q(a,{name:b,Wc(c){var d=(u(),C)[c>>>2>>>0];d=ig(c+4,d,!0);H(c);return d},cd(c,d){d instanceof ArrayBuffer&&(d=new Uint8Array(d));var e="string"==typeof d;if(!(e||ArrayBuffer.isView(d)&&1==d.BYTES_PER_ELEMENT))throw new mg("Cannot pass non-string to std::string");var f=e?U(d):d.length;var k=qe(4+f+1),h=k+4;(u(),C)[k>>>2>>>0]=f;e?T(d,h,f+1):(u(),x).set(d,h>>>0);null!==c&&c.push(H,k);return k},bd:rg,dd(c){H(c)}})} +var ug=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,vg=(a,b,c)=>{a>>>=1;b=gg((u(),Pa),a,b/2,c);if(16>>0];c+=String.fromCharCode(d)}return c},wg=(a,b,c)=>{c??=2147483647;if(2>c)return 0;c-=2;var d=b;c=c<2*a.length?c/2:a.length;for(var e=0;e>>1>>>0]=f;b+=2}(u(),Oa)[b>>>1>>>0]=0;return b-d},xg=a=>2*a.length,yg=(a,b,c)=>{var d="";a>>>=2;for(var e=0;!(e>=b/4);e++){var f= +(u(),C)[a+e>>>0];if(!f&&!c)break;d+=String.fromCodePoint(f)}return d},zg=(a,b,c)=>{b>>>=0;c??=2147483647;if(4>c)return 0;var d=b;c=d+c-4;for(var e=0;e>>2>>>0]=f;b+=4;if(b+4>c)break}(u(),B)[b>>>2>>>0]=0;return b-d},Ag=a=>{for(var b=0,c=0;c>>=0;b>>>=0;c>>>=0;c=P(c);if(2===b){var d=vg;var e=wg;var f=xg}else d=yg,e=zg,f=Ag;Q(a,{name:c,Wc:k=>{var h=(u(),C)[k>>>2>>>0];h=d(k+4,h*b,!0);H(k);return h},cd:(k,h)=>{if("string"!=typeof h)throw new mg(`Cannot pass non-string to C++ string type ${c}`);var l=f(h),p=qe(4+l+b);(u(),C)[p>>>2>>>0]=l/b;e(h,p+4,l+b);null!==k&&k.push(H,p);return p},bd:rg,dd(k){H(k)}})}function Hb(a,b){a>>>=0;b=P(b>>>0);Q(a,{we:!0,name:b,Wc:()=>{},cd:()=>{}})} +function Ib(a){Ha(a>>>0,!ba,1,!aa,131072,!1);Ia()}var N=a=>{if(!va)try{if(a(),!(0Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function Ja(a){a>>>=0;Bg||(Atomics.waitAsync((u(),B),a>>>2,a).value.then(Ma),a+=128,Atomics.store((u(),B),a>>>2,1))}var Ma=()=>N(()=>{var a=pe();a&&(Ja(a),Ne())}); +function Jb(a,b){a>>>=0;a==b>>>0?setTimeout(Ma):n?postMessage({gd:a,$c:"checkMailbox"}):(a=Sf[a])&&a.postMessage({$c:"checkMailbox"})}var Cg=[];function Kb(a,b,c,d,e){b>>>=0;e>>>=0;Cg.length=0;c=e>>>3;for(d=e+d>>>3;c>>0]?f=(u(),E)[c++>>>0]:f=(u(),D)[c++>>>0];Cg.push(f)}return(b?Dg[b]:Eg[a])(...Cg)}var Lb=()=>{L=0};function Mb(a){a>>>=0;n?postMessage({$c:"cleanupThread",Le:a}):Xf(Sf[a])}function Nb(a){m&&Sf[a>>>0].ref()}var Fg=a=>{try{a()}catch(b){G(b)}}; +function je(a){var b=(...c)=>{Gg.push(a);try{return a(...c)}finally{va||(Gg.pop(),r&&1===Hg&&0===Gg.length&&(Hg=0,L+=1,Fg(Gf),"undefined"!=typeof Fibers&&Fibers.We()))}};Ig.set(a,b);return b}var Hg=0,r=null,Jg=0,Gg=[],Kg=new Map,Lg=new Map,Ig=new Map,Mg=0,Ng=null,Og=[];function da(){return new Promise((a,b)=>{Ng={resolve:a,reject:b}})} +function Pg(){var a=qe(65548),b=a+12;(u(),C)[a>>>2>>>0]=b;(u(),C)[a+4>>>2>>>0]=b+65536;b=Gg[0];if(!Kg.has(b)){var c=Mg++;Kg.set(b,c);Lg.set(c,b)}b=Kg.get(b);(u(),B)[a+8>>>2>>>0]=b;return a}function Qg(){var a=(u(),B)[r+8>>>2>>>0];a=Lg.get(a);a=Ig.get(a);--L;return a()} +function Rg(a){if(!va){if(0===Hg){var b=!1,c=!1;a((d=0)=>{if(!va&&(Jg=d,b=!0,c)){Hg=2;Fg(()=>Hf(r));"undefined"!=typeof MainLoop&&MainLoop.se&&MainLoop.resume();d=!1;try{var e=Qg()}catch(h){e=h,d=!0}var f=!1;if(!r){var k=Ng;k&&(Ng=null,(d?k.reject:k.resolve)(e),f=!0)}if(d&&!f)throw e;}});c=!0;b||(Hg=1,r=Pg(),"undefined"!=typeof MainLoop&&MainLoop.se&&MainLoop.pause(),Fg(()=>Ff(r)))}else 2===Hg?(Hg=0,Fg(If),H(r),r=null,Og.forEach(N)):G(`invalid state: ${Hg}`);return Jg}}var Sg=a=>Rg(b=>{a().then(b)}); +function Ob(a){a>>>=0;return Sg(async()=>{var b=await R(a);return S(b)})}var Tg=[],Ug=a=>{var b=Tg.length;Tg.push(a);return b},Vg=(a,b)=>{for(var c=Array(a),d=0;d>>2>>>0],k=kg[f];if(void 0===k)throw a=`parameter ${d}`,f=me(f),b=P(f),H(f),new mg(`${a} has unknown type ${b}`);c[e]=k}return c},Wg=(a,b,c)=>{var d=[];a=a(d,c);d.length&&((u(),C)[b>>>2>>>0]=S(d));return a},Xg={},Yg=a=>{var b=Xg[a];return void 0===b?P(a):b}; +function Pb(a,b,c){var [d,...e]=Vg(a,b>>>0);b=d.cd.bind(d);var f=e.map(l=>l.bd.bind(l));a--;var k={toValue:R};a=f.map((l,p)=>{var q=`argFromPtr${p}`;k[q]=l;return`${q}(args${p?"+"+8*p:""})`});switch(c){case 0:var h="toValue(handle)";break;case 2:h="new (toValue(handle))";break;case 3:h="";break;case 1:k.getStringOrSymbol=Yg,h="toValue(handle)[getStringOrSymbol(methodName)]"}h+=`(${a})`;d.we||(k.toReturnWire=b,k.emval_returnValue=Wg,h=`return emval_returnValue(toReturnWire, destructorsRef, ${h})`); +h=`return function (handle, methodName, destructorsRef, args) {\n ${h}\n }`;c=(new Function(Object.keys(k),h))(...Object.values(k));h=`methodCaller<(${e.map(l=>l.name)}) => ${d.name}>`;return Ug(Object.defineProperty(c,"name",{value:h}))}function Rb(a,b){b>>>=0;a=R(a>>>0);b=R(b);return a==b}function Sb(a){a>>>=0;if(!a)return S(globalThis);a=Yg(a);return S(globalThis[a])}function Tb(a){a=Yg(a>>>0);return S(g[a])}function Ub(a,b){b>>>=0;a=R(a>>>0);b=R(b);return S(a[b])} +function Vb(a){a>>>=0;9>>0](b>>>0,c>>>0,d>>>0,e>>>0)}function Xb(a,b,c,d,e){return Wb(a>>>0,b>>>0,c>>>0,d>>>0,e>>>0)}function Yb(){return S([])}function Zb(a){a=R(a>>>0);for(var b=Array(a.length),c=0;c>>0))}function ac(){return S({})}function bc(a){a>>>=0;for(var b=R(a);b.length;){var c=b.pop();b.pop()(c)}Qb(a)}function cc(a,b,c){b>>>=0;c>>>=0;a=R(a>>>0);b=R(b);c=R(c);a[b]=c} +function dc(a,b){a=O(a);b>>>=0;a=new Date(1E3*a);(u(),B)[b>>>2>>>0]=a.getUTCSeconds();(u(),B)[b+4>>>2>>>0]=a.getUTCMinutes();(u(),B)[b+8>>>2>>>0]=a.getUTCHours();(u(),B)[b+12>>>2>>>0]=a.getUTCDate();(u(),B)[b+16>>>2>>>0]=a.getUTCMonth();(u(),B)[b+20>>>2>>>0]=a.getUTCFullYear()-1900;(u(),B)[b+24>>>2>>>0]=a.getUTCDay();a=(a.getTime()-Date.UTC(a.getUTCFullYear(),0,1,0,0,0,0))/864E5|0;(u(),B)[b+28>>>2>>>0]=a} +var Zg=a=>0===a%4&&(0!==a%100||0===a%400),$g=[0,31,60,91,121,152,182,213,244,274,305,335],ah=[0,31,59,90,120,151,181,212,243,273,304,334]; +function ec(a,b){a=O(a);b>>>=0;a=new Date(1E3*a);(u(),B)[b>>>2>>>0]=a.getSeconds();(u(),B)[b+4>>>2>>>0]=a.getMinutes();(u(),B)[b+8>>>2>>>0]=a.getHours();(u(),B)[b+12>>>2>>>0]=a.getDate();(u(),B)[b+16>>>2>>>0]=a.getMonth();(u(),B)[b+20>>>2>>>0]=a.getFullYear()-1900;(u(),B)[b+24>>>2>>>0]=a.getDay();var c=(Zg(a.getFullYear())?$g:ah)[a.getMonth()]+a.getDate()-1|0;(u(),B)[b+28>>>2>>>0]=c;(u(),B)[b+36>>>2>>>0]=-(60*a.getTimezoneOffset());c=(new Date(a.getFullYear(),6,1)).getTimezoneOffset();var d=(new Date(a.getFullYear(), +0,1)).getTimezoneOffset();a=(c!=d&&a.getTimezoneOffset()==Math.min(d,c))|0;(u(),B)[b+32>>>2>>>0]=a} +function fc(a){a>>>=0;var b=new Date((u(),B)[a+20>>>2>>>0]+1900,(u(),B)[a+16>>>2>>>0],(u(),B)[a+12>>>2>>>0],(u(),B)[a+8>>>2>>>0],(u(),B)[a+4>>>2>>>0],(u(),B)[a>>>2>>>0],0),c=(u(),B)[a+32>>>2>>>0],d=b.getTimezoneOffset(),e=(new Date(b.getFullYear(),6,1)).getTimezoneOffset(),f=(new Date(b.getFullYear(),0,1)).getTimezoneOffset(),k=Math.min(f,e);0>c?(u(),B)[a+32>>>2>>>0]=Number(e!=f&&k==d):0>>2>>>0]=b.getDay();c=(Zg(b.getFullYear())? +$g:ah)[b.getMonth()]+b.getDate()-1|0;(u(),B)[a+28>>>2>>>0]=c;(u(),B)[a>>>2>>>0]=b.getSeconds();(u(),B)[a+4>>>2>>>0]=b.getMinutes();(u(),B)[a+8>>>2>>>0]=b.getHours();(u(),B)[a+12>>>2>>>0]=b.getDate();(u(),B)[a+16>>>2>>>0]=b.getMonth();(u(),B)[a+20>>>2>>>0]=b.getYear();a=b.getTime();return BigInt(isNaN(a)?-1:a/1E3)}function gc(a,b,c,d,e,f,k){return n?M(16,1,a,b,c,d,e,f,k):-52}function hc(a,b,c,d,e,f){if(n)return M(17,1,a,b,c,d,e,f)}var bh={},sc=()=>performance.timeOrigin+performance.now(); +function ic(a,b){if(n)return M(18,1,a,b);bh[a]&&(clearTimeout(bh[a].id),delete bh[a]);if(!b)return 0;var c=setTimeout(()=>{delete bh[a];N(()=>Me(a,performance.timeOrigin+performance.now()))},b);bh[a]={id:c,Ve:b};return 0} +function jc(a,b,c,d){a>>>=0;b>>>=0;c>>>=0;d>>>=0;var e=(new Date).getFullYear(),f=(new Date(e,0,1)).getTimezoneOffset();e=(new Date(e,6,1)).getTimezoneOffset();var k=Math.max(f,e);(u(),C)[a>>>2>>>0]=60*k;(u(),B)[b>>>2>>>0]=Number(f!=e);b=h=>{var l=Math.abs(h);return`UTC${0<=h?"-":"+"}${String(Math.floor(l/60)).padStart(2,"0")}${String(l%60).padStart(2,"0")}`};a=b(f);b=b(e);eDate.now(),ch=1; +function kc(a,b,c){c>>>=0;if(!(0<=a&&3>=a))return 28;if(0===a)a=Date.now();else if(ch)a=performance.timeOrigin+performance.now();else return 52;a=Math.round(1E6*a);(u(),E)[c>>>3>>>0]=BigInt(a);return 0}var dh=[],eh=(a,b)=>{dh.length=0;for(var c;c=(u(),x)[a++>>>0];){var d=105!=c;d&=112!=c;b+=d&&b%8?4:0;dh.push(112==c?(u(),C)[b>>>2>>>0]:106==c?(u(),E)[b>>>3>>>0]:105==c?(u(),B)[b>>>2>>>0]:(u(),D)[b>>>3>>>0]);b+=d?8:4}return dh};function lc(a,b,c){a>>>=0;b=eh(b>>>0,c>>>0);return Dg[a](...b)} +function mc(a,b,c){a>>>=0;b=eh(b>>>0,c>>>0);return Dg[a](...b)}var nc=()=>{};function pc(a,b){return t(ig(a>>>0,b>>>0))}var qc=()=>{L+=1;throw"unwind";};function rc(){return 4294901760}var tc=()=>1,uc=()=>m?require("os").cpus().length:navigator.hardwareConcurrency,fh={},gh=a=>{var b=U(a)+1,c=qe(b);c&&T(a,c,b);return c},hh=a=>{var b;return(b=/\bwasm-function\[\d+\]:(0x[0-9a-f]+)/.exec(a))?+b[1]:(b=/:(\d+):\d+(?:\)|$)/.exec(a))?2147483648|+b[1]:0},ih=a=>{for(var b of a)(a=hh(b))&&(fh[a]=b)}; +function xc(){var a=Error().stack.toString().split("\n");"Error"==a[0]&&a.shift();ih(a);fh.ee=hh(a[3]);fh.xe=a;return fh.ee}function vc(a){a=fh[a>>>0];if(!a)return 0;var b;if(b=/^\s+at .*\.wasm\.(.*) \(.*\)$/.exec(a))a=b[1];else if(b=/^\s+at (.*) \(.*\)$/.exec(a))a=b[1];else if(b=/^(.+?)@/.exec(a))a=b[1];else return 0;H(vc.ne??0);vc.ne=gh(a);return vc.ne} +function wc(a){a>>>=0;var b=(u(),x).length;if(a<=b||4294901760=c;c*=2){var d=b*(1+.2/c);d=Math.min(d,a+100663296);a:{d=(Math.min(4294901760,65536*Math.ceil(Math.max(a,d)/65536))-v.buffer.byteLength+65535)/65536|0;try{v.grow(d);xa();var e=1;break a}catch(f){}e=void 0}if(e)return!0}return!1} +function yc(a,b,c){a>>>=0;b>>>=0;if(fh.ee==a)var d=fh.xe;else d=Error().stack.toString().split("\n"),"Error"==d[0]&&d.shift(),ih(d);for(var e=3;d[e]&&hh(d[e])!=a;)++e;for(a=0;a>>2>>>0]=hh(d[a+e]);return a} +var V=a=>{var b=U(a)+1,c=Re(b);T(a,c,b);return c},jh=a=>(u(),C)[a>>>2>>>0]+4294967296*(u(),B)[a+4>>>2>>>0],W=[],kh=(a,b)=>{W[a>>>0]=b},X=[],lh=[],mh=(a,b)=>{lh[a]=new Promise(c=>b.finally(()=>c(a)))},Y=a=>{if(a)return W[a>>>0]},nh=(a,b=0)=>{"unmapped"===a.mapState||G();b=ze(b);W[b>>>0]=a;return b},oh=(a,b=0)=>{var c=Be(b);b=Ae(b,c);W[c>>>0]=a.queue;W[b>>>0]=a;return b},ph=(a,b)=>{for(a=(u(),C)[a>>>2>>>0];a;a=(u(),C)[a>>>2>>>0]){var c=(u(),B)[a+4>>>2>>>0];b[c](a)}},qh=(a,b,c)=>{(u(),C)[a>>>2>>>0]= +b;(u(),C)[a+4>>>2>>>0]=c},rh=a=>{var b=(u(),C)[a>>>2>>>0];a=(u(),C)[a+4>>>2>>>0];return ig(b,a)},Z=a=>{var b=(u(),C)[a>>>2>>>0];a=(u(),C)[a+4>>>2>>>0];if(b)return ig(b,a);if(0===a)return""},sh=a=>{var b=Z(a+4);var c=(c=(u(),C)[a+12>>>2>>>0])?Y(c):"auto";if(a+=16){var d=Y((u(),C)[a+4>>>2>>>0]);var e=(u(),C)[a+16>>>2>>>0];var f=(u(),C)[a+20>>>2>>>0];if(e){for(var k={},h=0;h>>3>>>0]}e=k}else e=void 0;a={module:d,constants:e,entryPoint:Z(a+8)}}else a=void 0; +return{label:b,layout:c,compute:a}},th=(a,b)=>{function c(f,k,h,l=0){f=a[f]??l;(u(),C)[k+h>>>2>>>0]=f}function d(f,k,h,l=0){k+=h;f=a[f]??l;(u(),C)[k>>>2>>>0]=f;l=(u(),C)[k>>>2>>>0];(u(),C)[k+4>>>2>>>0]=(f-l)/4294967296}var e=(u(),C)[b>>>2>>>0];c("maxTextureDimension1D",b,4);c("maxTextureDimension2D",b,8);c("maxTextureDimension3D",b,12);c("maxTextureArrayLayers",b,16);c("maxBindGroups",b,20);c("maxBindGroupsPlusVertexBuffers",b,24);c("maxBindingsPerBindGroup",b,28);c("maxDynamicUniformBuffersPerPipelineLayout", +b,32);c("maxDynamicStorageBuffersPerPipelineLayout",b,36);c("maxSampledTexturesPerShaderStage",b,40);c("maxSamplersPerShaderStage",b,44);c("maxStorageBuffersPerShaderStage",b,48);c("maxStorageTexturesPerShaderStage",b,52);c("maxUniformBuffersPerShaderStage",b,56);c("minUniformBufferOffsetAlignment",b,80);c("minStorageBufferOffsetAlignment",b,84);d("maxUniformBufferBindingSize",b,64);d("maxStorageBufferBindingSize",b,72);c("maxVertexBuffers",b,88);d("maxBufferSize",b,96);c("maxVertexAttributes",b, +104);c("maxVertexBufferArrayStride",b,108);c("maxInterStageShaderVariables",b,112);c("maxColorAttachments",b,116);c("maxColorAttachmentBytesPerSample",b,120);c("maxComputeWorkgroupStorageSize",b,124);c("maxComputeInvocationsPerWorkgroup",b,128);c("maxComputeWorkgroupSizeX",b,132);c("maxComputeWorkgroupSizeY",b,136);c("maxComputeWorkgroupSizeZ",b,140);c("maxComputeWorkgroupsPerDimension",b,144);c("maxImmediateSize",b,148);0!==e&&(u(),c("maxStorageBuffersInVertexStage",e,8,a.maxStorageBuffersPerShaderStage), +c("maxStorageBuffersInFragmentStage",e,16,a.maxStorageBuffersPerShaderStage),c("maxStorageTexturesInVertexStage",e,12,a.maxStorageTexturesPerShaderStage),c("maxStorageTexturesInFragmentStage",e,20,a.maxStorageTexturesPerShaderStage))},vh=(a,b)=>{(u(),C)[b+52>>>2>>>0]=a.subgroupMinSize;(u(),C)[b+56>>>2>>>0]=a.subgroupMaxSize;var c=gh(a.vendor+a.architecture+a.device+a.description),d=U(a.vendor);qh(b+4,c,d);c+=d;d=U(a.architecture);qh(b+12,c,d);c+=d;d=U(a.device);qh(b+20,c,d);c+=d;d=U(a.description); +qh(b+28,c,d);c+=d;(u(),B)[b+36>>>2>>>0]=2;c=a.isFallbackAdapter?3:4;(u(),B)[b+40>>>2>>>0]=c;(u(),C)[b+44>>>2>>>0]=0;(u(),C)[b+48>>>2>>>0]=0;ph(b,{327739:e=>{let f=0,k=0;if(a.subgroupMatrixConfigs){f=a.subgroupMatrixConfigs.length;k=qe(20*f);for(const [h,l]of a.subgroupMatrixConfigs.entries()){const p=k+20*h,q=uh.indexOf(l.componentType),y=uh.indexOf(l.resultComponentType);(u(),B)[p>>>2>>>0]=q;(u(),B)[p+4>>>2>>>0]=y;(u(),C)[p+8>>>2>>>0]=l.M;(u(),C)[p+12>>>2>>>0]=l.N;(u(),C)[p+16>>>2>>>0]=l.K}}(u(), +C)[e+12>>>2>>>0]=k;(u(),C)[e+8>>>2>>>0]=f}})},wh=[,,"uniform","storage","read-only-storage"],xh=[,"validation","out-of-memory","internal"],yh=[,"compatibility","core"],zh={1:"core-features-and-limits",2:"depth-clip-control",3:"depth32float-stencil8",4:"texture-compression-bc",5:"texture-compression-bc-sliced-3d",6:"texture-compression-etc2",7:"texture-compression-astc",8:"texture-compression-astc-sliced-3d",9:"timestamp-query",10:"indirect-first-instance",11:"shader-f16",12:"rg11b10ufloat-renderable", +13:"bgra8unorm-storage",14:"float32-filterable",15:"float32-blendable",16:"clip-distances",17:"dual-source-blending",18:"subgroups",19:"texture-formats-tier1",20:"texture-formats-tier2",21:"primitive-index",22:"texture-component-swizzle",23:"subgroup-size-control",327692:"chromium-experimental-unorm16-texture-formats",327729:"chromium-experimental-multi-draw-indirect",327732:"chromium-experimental-subgroup-matrix"},Ah=[,"low-power","high-performance"],Bh=[,"occlusion","timestamp"],Ch=[,,"filtering", +"non-filtering","comparison"],Dh=[,,"write-only","read-only","read-write"],uh=[,"f32","f16","u32","i32","u8","i8"],Eh=[,"r8unorm","r8snorm","r8uint","r8sint","r16unorm","r16snorm","r16uint","r16sint","r16float","rg8unorm","rg8snorm","rg8uint","rg8sint","r32float","r32uint","r32sint","rg16unorm","rg16snorm","rg16uint","rg16sint","rg16float","rgba8unorm","rgba8unorm-srgb","rgba8snorm","rgba8uint","rgba8sint","bgra8unorm","bgra8unorm-srgb","rgb10a2uint","rgb10a2unorm","rg11b10ufloat","rgb9e5ufloat", +"rg32float","rg32uint","rg32sint","rgba16unorm","rgba16snorm","rgba16uint","rgba16sint","rgba16float","rgba32float","rgba32uint","rgba32sint","stencil8","depth16unorm","depth24plus","depth24plus-stencil8","depth32float","depth32float-stencil8","bc1-rgba-unorm","bc1-rgba-unorm-srgb","bc2-rgba-unorm","bc2-rgba-unorm-srgb","bc3-rgba-unorm","bc3-rgba-unorm-srgb","bc4-r-unorm","bc4-r-snorm","bc5-rg-unorm","bc5-rg-snorm","bc6h-rgb-ufloat","bc6h-rgb-float","bc7-rgba-unorm","bc7-rgba-unorm-srgb","etc2-rgb8unorm", +"etc2-rgb8unorm-srgb","etc2-rgb8a1unorm","etc2-rgb8a1unorm-srgb","etc2-rgba8unorm","etc2-rgba8unorm-srgb","eac-r11unorm","eac-r11snorm","eac-rg11unorm","eac-rg11snorm","astc-4x4-unorm","astc-4x4-unorm-srgb","astc-5x4-unorm","astc-5x4-unorm-srgb","astc-5x5-unorm","astc-5x5-unorm-srgb","astc-6x5-unorm","astc-6x5-unorm-srgb","astc-6x6-unorm","astc-6x6-unorm-srgb","astc-8x5-unorm","astc-8x5-unorm-srgb","astc-8x6-unorm","astc-8x6-unorm-srgb","astc-8x8-unorm","astc-8x8-unorm-srgb","astc-10x5-unorm","astc-10x5-unorm-srgb", +"astc-10x6-unorm","astc-10x6-unorm-srgb","astc-10x8-unorm","astc-10x8-unorm-srgb","astc-10x10-unorm","astc-10x10-unorm-srgb","astc-12x10-unorm","astc-12x10-unorm-srgb","astc-12x12-unorm","astc-12x12-unorm-srgb"],Fh=[,,"float","unfilterable-float","depth","sint","uint"],Gh=[,"1d","2d","2d-array","cube","cube-array","3d"],Hh={undefined:1,unknown:1,destroyed:2}; +function zc(a,b,c,d,e,f){b=O(b);c=O(c);d>>>=0;e>>>=0;f>>>=0;var k=Y(a>>>0);a={};if(f){var h=(u(),C)[f+12>>>2>>>0];if(h){var l=(u(),C)[f+16>>>2>>>0];a.requiredFeatures=Array.from((u(),C).subarray(l>>>2>>>0,l+4*h>>>2>>>0),q=>zh[q])}if(h=(u(),C)[f+20>>>2>>>0]){l=(u(),C)[h>>>2>>>0];var p={};function q(z,A,ja,Aa=!1){A+=ja;A=(u(),C)[A>>>2>>>0];4294967295==A||Aa&&0==A||(p[z]=A)}function y(z,A,ja){A+=ja;ja=(u(),C)[A>>>2>>>0];var Aa=(u(),C)[A+4>>>2>>>0];if(4294967295!=ja||4294967295!=Aa)p[z]=jh(A)}q("maxTextureDimension1D", +h,4);q("maxTextureDimension2D",h,8);q("maxTextureDimension3D",h,12);q("maxTextureArrayLayers",h,16);q("maxBindGroups",h,20);q("maxBindGroupsPlusVertexBuffers",h,24);q("maxBindingsPerBindGroup",h,28);q("maxDynamicUniformBuffersPerPipelineLayout",h,32);q("maxDynamicStorageBuffersPerPipelineLayout",h,36);q("maxSampledTexturesPerShaderStage",h,40);q("maxSamplersPerShaderStage",h,44);q("maxStorageBuffersPerShaderStage",h,48);q("maxStorageTexturesPerShaderStage",h,52);q("maxUniformBuffersPerShaderStage", +h,56);q("minUniformBufferOffsetAlignment",h,80);q("minStorageBufferOffsetAlignment",h,84);y("maxUniformBufferBindingSize",h,64);y("maxStorageBufferBindingSize",h,72);q("maxVertexBuffers",h,88);y("maxBufferSize",h,96);q("maxVertexAttributes",h,104);q("maxVertexBufferArrayStride",h,108);q("maxInterStageShaderVariables",h,112);q("maxColorAttachments",h,116);q("maxColorAttachmentBytesPerSample",h,120);q("maxComputeWorkgroupStorageSize",h,124);q("maxComputeInvocationsPerWorkgroup",h,128);q("maxComputeWorkgroupSizeX", +h,132);q("maxComputeWorkgroupSizeY",h,136);q("maxComputeWorkgroupSizeZ",h,140);q("maxComputeWorkgroupsPerDimension",h,144);q("maxImmediateSize",h,148,!0);0!==l&&(u(),"maxStorageBuffersInVertexStage"in GPUSupportedLimits.prototype&&(q("maxStorageBuffersInVertexStage",l,8),q("maxStorageTexturesInVertexStage",l,12),q("maxStorageBuffersInFragmentStage",l,16),q("maxStorageTexturesInFragmentStage",l,20)));a.requiredLimits=p}if(h=(u(),C)[f+24>>>2>>>0])h={label:Z(h+4)},a.defaultQueue=h;a.label=Z(f+4)}L+= +1;mh(b,k.requestDevice(a).then(q=>{--L;N(()=>{W[e>>>0]=q.queue;W[d>>>0]=q;L+=1;mh(c,q.lost.then(y=>{N(()=>{q.onuncapturederror=()=>{};var z=K(),A=V(y.message);De(c,Hh[y.reason],A);J(z)});--L}));q.onuncapturederror=y=>{var z=5;y.error instanceof GPUValidationError?z=2:y.error instanceof GPUOutOfMemoryError?z=3:y.error instanceof GPUInternalError&&(z=4);var A=K();y=V(y.error.message);Ie(d,z,y);J(A)};"adapterInfo"in q||(q.adapterInfo=k.info);He(b,1,d,0)})},q=>{--L;N(()=>{var y=K(),z=V(q.message);He(b, +3,d,z);c&&De(c,4,z);J(y)})}))}function Ac(a){a>>>=0;var b=Y(a),c=X[a];if(c){for(var d=0;d>>=0;c>>>=0;var d=Y(a);4294967295==c&&(c=void 0);try{var e=d.getMappedRange(b>>>0,c)}catch(k){return 0}var f=Oe(16,e.byteLength);(u(),x).set(new Uint8Array(e),f>>>0);X[a].push(()=>H(f));return f} +function Cc(a,b,c){a>>>=0;c>>>=0;var d=Y(a);4294967295==c&&(c=void 0);try{var e=d.getMappedRange(b>>>0,c)}catch(k){return 0}var f=Oe(16,e.byteLength);(u(),x).fill(0,f,e.byteLength);X[a].push(()=>{(new Uint8Array(e)).set((u(),x).subarray(f>>>0,f+e.byteLength>>>0));H(f)});return f} +function Dc(a,b,c,d,e){a>>>=0;b=O(b);c=O(c);e>>>=0;var f=Y(a);X[a]=[];4294967295==e&&(e=void 0);L+=1;mh(b,f.mapAsync(c,d>>>0,e).then(()=>{--L;N(()=>{Ee(b,1,0)})},k=>{--L;N(()=>{K();var h=V(k.message);Ee(b,"AbortError"===k.name?4:"OperationError"===k.name?3:0,h);delete X[a]})}))}function Ec(a){a>>>=0;var b=Y(a),c=X[a];if(c){for(var d=0;d>>0]} +function Gc(a,b,c){a>>>=0;b>>>=0;c>>>=0;var d=!!(u(),C)[b+32>>>2>>>0];b={label:Z(b+4),usage:(u(),C)[b+16>>>2>>>0],size:jh(b+24),mappedAtCreation:d};a=Y(a);try{var e=a.createBuffer(b)}catch(f){return!1}W[c>>>0]=e;d&&(X[c]=[]);return!0}function Hc(a,b,c,d){a>>>=0;b=O(b);d>>>=0;c=sh(c>>>0);a=Y(a);L+=1;mh(b,a.createComputePipelineAsync(c).then(e=>{--L;N(()=>{W[d>>>0]=e;Ce(b,1,d,0)})},e=>{--L;N(()=>{var f=K(),k=V(e.message);Ce(b,"validation"===e.reason?3:"internal"===e.reason?4:0,d,k);J(f)})}))} +function Ic(a,b,c){a>>>=0;b>>>=0;c>>>=0;var d=(u(),C)[b>>>2>>>0],e=(u(),B)[d+4>>>2>>>0];b={label:Z(b+4),code:""};switch(e){case 2:b.code=rh(d+8)}a=Y(a).createShaderModule(b);W[c>>>0]=a}var Jc=a=>{a=Y(a);a.onuncapturederror=null;a.destroy()}; +function Kc(a,b){b=O(b);a=Y(a>>>0);L+=1;mh(b,a.popErrorScope().then(c=>{--L;N(()=>{var d=5;c?c instanceof GPUValidationError?d=2:c instanceof GPUOutOfMemoryError?d=3:c instanceof GPUInternalError&&(d=4):d=1;var e=K(),f=c?V(c.message):0;Fe(b,1,d,f);J(e)})},c=>{--L;N(()=>{var d=K(),e=V(c.message);Fe(b,1,5,e);J(d)})}))} +function Lc(a,b,c,d){b=O(b);c>>>=0;d>>>=0;if(c){var e={featureLevel:yh[(u(),B)[c+4>>>2>>>0]],powerPreference:Ah[(u(),B)[c+8>>>2>>>0]],forceFallbackAdapter:!!(u(),C)[c+12>>>2>>>0]};a=(u(),C)[c>>>2>>>0];0!==a&&(u(),e.Ye=!!(u(),C)[a+8>>>2>>>0])}"gpu"in navigator?(L+=1,mh(b,navigator.gpu.requestAdapter(e).then(f=>{--L;N(()=>{if(f)W[d>>>0]=f,Ge(b,1,d,0);else{var k=K(),h=V("WebGPU not available on this browser (requestAdapter returned null)");Ge(b,3,d,h);J(k)}})},f=>{--L;N(()=>{var k=K(),h=V(f.message); +Ge(b,4,d,h);J(k)})}))):(e=K(),a=V("WebGPU not available on this browser (navigator.gpu is not available)"),Ge(b,3,d,a),J(e))}function Mc(a,b,c){a>>>=0;b>>>=0;c>>>=0;return Sg(async()=>{var d=[];if(c){var e=(u(),B)[c>>>2>>>0];d.length=b+1;d[b]=new Promise(h=>setTimeout(h,e,0))}else d.length=b;for(var f=0;f{if(!Jh){var a={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:fa||"./this.program"},b;for(b in Ih)void 0===Ih[b]?delete a[b]:a[b]=Ih[b];var c=[];for(b in a)c.push(`${b}=${a[b]}`);Jh=c}return Jh},Jh;function Nc(a,b){if(n)return M(19,1,a,b);a>>>=0;b>>>=0;var c=0,d=0,e;for(e of Kh()){var f=b+c;(u(),C)[a+d>>>2>>>0]=f;c+=T(e,f,Infinity)+1;d+=4}return 0} +function Oc(a,b){if(n)return M(20,1,a,b);a>>>=0;b>>>=0;var c=Kh();(u(),C)[a>>>2>>>0]=c.length;a=0;for(var d of c)a+=U(d)+1;(u(),C)[b>>>2>>>0]=a;return 0}function Qc(a){return n?M(21,1,a):52}function Rc(a,b,c,d,e){return n?M(22,1,a,b,c,d,e):52}function Sc(a,b,c,d){return n?M(23,1,a,b,c,d):52}function Tc(a,b,c,d){return n?M(24,1,a,b,c,d):70}var Lh=[null,[],[]]; +function Uc(a,b,c,d){if(n)return M(25,1,a,b,c,d);b>>>=0;c>>>=0;d>>>=0;for(var e=0,f=0;f>>2>>>0],h=(u(),C)[b+4>>>2>>>0];b+=8;for(var l=0;l>>0],y=Lh[p];0===q||10===q?((1===p?sa:t)(hg(y)),y.length=0):y.push(q)}e+=h}(u(),C)[d>>>2>>>0]=e;return 0}function Id(a){return a>>>0}function Kd(a,b){th(Y(a>>>0).limits,b>>>0);return 1}function Ld(a,b){return Y(a>>>0).features.has(zh[b])}function Md(a){return BigInt(Y(a>>>0).size)} +function Nd(a){return BigInt(Y(a>>>0).usage)}function Od(a,b){a>>>=0;b>>>=0;if(b){var c=Z(b+4);b=(u(),C)[b+12>>>2>>>0];b=0!==b?{querySet:Y((u(),C)[b+4>>>2>>>0]),beginningOfPassWriteIndex:(u(),C)[b+8>>>2>>>0],endOfPassWriteIndex:(u(),C)[b+12>>>2>>>0]}:void 0;c={label:c,timestampWrites:b}}b=Y(a);a=we(0);c=b.beginComputePass(c);W[a>>>0]=c;return a}function Pd(a,b,c,d){c=O(c);d=O(d);a=Y(a>>>0);-1==d&&(d=void 0);a.clearBuffer(Y(b>>>0),c,d)} +function Qd(a,b,c,d,e,f){c=O(c);e=O(e);f=O(f);Y(a>>>0).copyBufferToBuffer(Y(b>>>0),c,Y(d>>>0),e,f)}function Rd(a){var b=Y(a>>>0);a=ue(0);b=b.finish();W[a>>>0]=b;return a}function Sd(a,b,c,d,e,f){f=O(f);Y(a>>>0).resolveQuerySet(Y(b>>>0),c,d,Y(e>>>0),f)}function Td(a,b,c,d){Y(a>>>0).dispatchWorkgroups(b,c,d)}function Ud(a,b,c){c=O(c);Y(a>>>0).dispatchWorkgroupsIndirect(Y(b>>>0),c)}function Vd(a){Y(a>>>0).end()} +function Wd(a,b,c,d,e){d>>>=0;e>>>=0;a=Y(a>>>0);c=Y(c>>>0);0==d?a.setBindGroup(b,c):a.setBindGroup(b,c,(u(),C),e>>>2,d)}function Xd(a,b){Y(a>>>0).setPipeline(Y(b>>>0))}function Yd(a,b,c){Y(a>>>0).Xe(Y(b>>>0),c)} +function Zd(a,b){function c(e){var f=(u(),C)[e+8>>>2>>>0],k=(u(),C)[e+32>>>2>>>0],h=(u(),C)[e+36>>>2>>>0],l=0;ph(e,{14:p=>{l=(u(),C)[p+8>>>2>>>0]}});f?(k=jh(e+24),-1==k&&(k=void 0),f={buffer:Y(f),offset:jh(e+16),size:k}):f=Y(k||h||l);return{binding:(u(),C)[e+4>>>2>>>0],resource:f}}a>>>=0;b>>>=0;b={label:Z(b+4),layout:Y((u(),C)[b+12>>>2>>>0]),entries:function(e,f){for(var k=[],h=0;h>>2>>>0],(u(),C)[b+20>>>2>>>0])};a=Y(a);var d=se(0);kh(d,a.createBindGroup(b)); +return d} +function $d(a,b){function c(l){var p=(u(),C)[l+4>>>2>>>0];if(p)return{type:wh[p],hasDynamicOffset:!!(u(),C)[l+8>>>2>>>0],minBindingSize:jh(l+16)}}function d(l){if(l=(u(),C)[l+4>>>2>>>0])return{type:Ch[l]}}function e(l){var p=(u(),C)[l+4>>>2>>>0];if(p)return{sampleType:Fh[p],viewDimension:Gh[(u(),B)[l+8>>>2>>>0]],multisampled:!!(u(),C)[l+12>>>2>>>0]}}function f(l){var p=(u(),C)[l+4>>>2>>>0];if(p)return{access:Dh[p],format:Eh[(u(),B)[l+8>>>2>>>0]],viewDimension:Gh[(u(),B)[l+12>>>2>>>0]]}}function k(l){var p={binding:(u(), +C)[l+4>>>2>>>0],visibility:(u(),C)[l+8>>>2>>>0],buffer:c(l+24),sampler:d(l+48),texture:e(l+56),storageTexture:f(l+72)};ph(l,{13:()=>{p.externalTexture={}}});return p}a>>>=0;b>>>=0;b={label:Z(b+4),entries:function(l,p){for(var q=[],y=0;y>>2>>>0],(u(),C)[b+16>>>2>>>0])};a=Y(a);var h=te(0);kh(h,a.createBindGroupLayout(b));return h}function ae(a,b){a>>>=0;b>>>=0;var c;b&&(c={label:Z(b+4)});b=Y(a);a=ve(0);c=b.createCommandEncoder(c);W[a>>>0]=c;return a} +function be(a,b){a>>>=0;b>>>=0;for(var c=(u(),C)[b+12>>>2>>>0],d=(u(),C)[b+16>>>2>>>0],e=[],f=0;f>>2>>>0]));b={label:Z(b+4),bindGroupLayouts:e,immediateSize:(u(),C)[b+20>>>2>>>0]};c=Y(a);a=xe(0);b=c.createPipelineLayout(b);W[a>>>0]=b;return a}function ce(a,b){a>>>=0;b>>>=0;b={type:Bh[(u(),B)[b+12>>>2>>>0]],count:(u(),C)[b+16>>>2>>>0]};var c=Y(a);a=ye(0);b=c.createQuerySet(b);W[a>>>0]=b;return a}function de(a,b){vh(Y(a>>>0).adapterInfo,b>>>0);return 1} +var Mh={"core-features-and-limits":1,"depth-clip-control":2,"depth32float-stencil8":3,"texture-compression-bc":4,"texture-compression-bc-sliced-3d":5,"texture-compression-etc2":6,"texture-compression-astc":7,"texture-compression-astc-sliced-3d":8,"timestamp-query":9,"indirect-first-instance":10,"shader-f16":11,"rg11b10ufloat-renderable":12,"bgra8unorm-storage":13,"float32-filterable":14,"float32-blendable":15,"clip-distances":16,"dual-source-blending":17,subgroups:18,"texture-formats-tier1":19,"texture-formats-tier2":20, +"primitive-index":21,"texture-component-swizzle":22,"subgroup-size-control":23,"chromium-experimental-unorm16-texture-formats":327692,"chromium-experimental-multi-draw-indirect":327729,"chromium-experimental-subgroup-matrix":327732};function ee(a,b){b>>>=0;var c=Y(a>>>0);a=qe(4*c.features.size);var d=0,e=0;for(const f of c.features)c=Mh[f],0<=c&&((u(),B)[a+d>>>2>>>0]=c,d+=4,e++);(u(),C)[b+4>>>2>>>0]=a;(u(),C)[b>>>2>>>0]=e}function fe(a,b){th(Y(a>>>0).limits,b>>>0);return 1} +function ge(a,b){Y(a>>>0).pushErrorScope(xh[b])}function he(a,b,c){b>>>=0;c>>>=0;a=Y(a>>>0);b=Array.from((u(),B).subarray(c>>>2>>>0,c+4*b>>>2>>>0),d=>Y(d));a.submit(b)}function ie(a,b,c,d,e){c=O(c);d>>>=0;e>>>=0;a=Y(a>>>0);b=Y(b>>>0);d=(u(),x).subarray(d>>>0,d+e>>>0);a.writeBuffer(b,c,d,0,e)}n||Vf();n||(v=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),xa());g.wasmBinary&&(ta=g.wasmBinary);g.stackSave=()=>K();g.stackRestore=a=>J(a);g.stackAlloc=a=>Re(a); +g.setValue=function(a,b,c="i8"){c.endsWith("*")&&(c="*");switch(c){case "i1":(u(),w)[a>>>0]=b;break;case "i8":(u(),w)[a>>>0]=b;break;case "i16":(u(),Oa)[a>>>1>>>0]=b;break;case "i32":(u(),B)[a>>>2>>>0]=b;break;case "i64":(u(),E)[a>>>3>>>0]=BigInt(b);break;case "float":(u(),Qa)[a>>>2>>>0]=b;break;case "double":(u(),D)[a>>>3>>>0]=b;break;case "*":(u(),C)[a>>>2>>>0]=b;break;default:G(`invalid type for setValue: ${c}`)}}; +g.getValue=function(a,b="i8"){b.endsWith("*")&&(b="*");switch(b){case "i1":return(u(),w)[a>>>0];case "i8":return(u(),w)[a>>>0];case "i16":return(u(),Oa)[a>>>1>>>0];case "i32":return(u(),B)[a>>>2>>>0];case "i64":return(u(),E)[a>>>3>>>0];case "float":return(u(),Qa)[a>>>2>>>0];case "double":return(u(),D)[a>>>3>>>0];case "*":return(u(),C)[a>>>2>>>0];default:G(`invalid type for getValue: ${b}`)}};g.UTF8ToString=ig;g.stringToUTF8=T;g.lengthBytesUTF8=U; +var Eg=[Jd,Uf,eg,kb,lb,mb,nb,ob,pb,qb,rb,sb,tb,ub,vb,wb,gc,hc,ic,Nc,Oc,Qc,Rc,Sc,Tc,Uc],Dg={1280444:(a,b,c,d,e)=>{if("undefined"==typeof g||!g.ed)return 1;a=ig(Number(a>>>0));a.startsWith("./")&&(a=a.substring(2));a=g.ed.get(a);if(!a)return 2;b=Number(b>>>0);c=Number(c>>>0);d=Number(d>>>0);if(b+c>a.byteLength)return 3;try{const f=a.subarray(b,b+c);switch(e){case 0:(u(),x).set(f,d>>>0);break;case 1:g.pe?g.pe(d,f):g.Re(d,f);break;default:return 4}return 0}catch{return 4}},1281268:(a,b,c)=>{g.re(a,(u(), +x).subarray(b>>>0,b+c>>>0))},1281332:()=>g.Pe(),1281374:a=>{g.qe(a)},1281411:()=>"undefined"!==typeof wasmOffsetConverter};function $a(){return"undefined"!==typeof wasmOffsetConverter}var me,Ka,ne,oe,pe,H,qe,re,se,te,ue,ve,we,xe,ye,ze,Ae,Be,Ce,De,Ee,Fe,Ge,He,Ie,Ha,Na,Je,Ke,Le,Me,Ne,Oe,I,Pe,Qe,J,Re,K,Se,Te,Ue,Ve,dynCall_vii,We,dynCall_v,Xe,Ye,Ze,dynCall_iii,$e,af,bf,dynCall_vi,cf,df,ef,ff,gf,hf,jf,kf,lf,mf,nf,of,pf,qf,rf,sf,tf,uf,vf,wf,xf,yf,zf,Af,Bf,Cf,Df,Ef,Ff,Gf,Hf,If,Za; +function bd(a,b,c,d){var e=K();try{return bf(a,b,c,d)}catch(f){J(e);if(f!==f+0)throw f;I(1,0)}}function ad(a,b,c){var d=K();try{return dynCall_iii(a,b,c)}catch(e){J(d);if(e!==e+0)throw e;I(1,0)}}function sd(a){var b=K();try{dynCall_v(a)}catch(c){J(b);if(c!==c+0)throw c;I(1,0)}}function $c(a,b){var c=K();try{return We(a,b)}catch(d){J(c);if(d!==d+0)throw d;I(1,0)}}function ud(a,b,c){var d=K();try{dynCall_vii(a,b,c)}catch(e){J(d);if(e!==e+0)throw e;I(1,0)}} +function td(a,b){var c=K();try{dynCall_vi(a,b)}catch(d){J(c);if(d!==d+0)throw d;I(1,0)}}function fd(a,b,c,d,e,f,k){var h=K();try{return Ze(a,b,c,d,e,f,k)}catch(l){J(h);if(l!==l+0)throw l;I(1,0)}}function yd(a,b,c,d,e,f){var k=K();try{Xe(a,b,c,d,e,f)}catch(h){J(k);if(h!==h+0)throw h;I(1,0)}}function wd(a,b,c,d){var e=K();try{af(a,b,c,d)}catch(f){J(e);if(f!==f+0)throw f;I(1,0)}}function zd(a,b,c,d,e,f,k){var h=K();try{df(a,b,c,d,e,f,k)}catch(l){J(h);if(l!==l+0)throw l;I(1,0)}} +function Gd(a,b,c,d,e,f,k){var h=K();try{ef(a,b,c,d,e,f,k)}catch(l){J(h);if(l!==l+0)throw l;I(1,0)}}function Fd(a,b,c,d,e,f,k,h){var l=K();try{pf(a,b,c,d,e,f,k,h)}catch(p){J(l);if(p!==p+0)throw p;I(1,0)}}function Dd(a,b,c,d,e,f,k,h,l,p,q,y){var z=K();try{ff(a,b,c,d,e,f,k,h,l,p,q,y)}catch(A){J(z);if(A!==A+0)throw A;I(1,0)}}function cd(a,b,c,d,e){var f=K();try{return cf(a,b,c,d,e)}catch(k){J(f);if(k!==k+0)throw k;I(1,0)}} +function Hd(a,b,c,d,e,f){var k=K();try{qf(a,b,c,d,e,f)}catch(h){J(k);if(h!==h+0)throw h;I(1,0)}}function xd(a,b,c,d,e){var f=K();try{Ye(a,b,c,d,e)}catch(k){J(f);if(k!==k+0)throw k;I(1,0)}}function Ad(a,b,c,d,e,f,k,h){var l=K();try{$e(a,b,c,d,e,f,k,h)}catch(p){J(l);if(p!==p+0)throw p;I(1,0)}}function Zc(a){var b=K();try{return rf(a)}catch(c){J(b);if(c!==c+0)throw c;I(1,0)}}function Bd(a,b,c,d,e,f,k,h,l){var p=K();try{hf(a,b,c,d,e,f,k,h,l)}catch(q){J(p);if(q!==q+0)throw q;I(1,0)}} +function md(a,b,c){var d=K();try{return sf(a,b,c)}catch(e){J(d);if(e!==e+0)throw e;I(1,0)}}function pd(a,b){var c=K();try{return Ef(a,b)}catch(d){J(c);if(d!==d+0)throw d;I(1,0);return 0n}}function nd(a,b,c,d){var e=K();try{return tf(a,b,c,d)}catch(f){J(e);if(f!==f+0)throw f;I(1,0)}}function od(a){var b=K();try{return gf(a)}catch(c){J(b);if(c!==c+0)throw c;I(1,0);return 0n}}function ld(a,b,c,d){var e=K();try{return uf(a,b,c,d)}catch(f){J(e);if(f!==f+0)throw f;I(1,0)}} +function kd(a,b,c,d,e){var f=K();try{return vf(a,b,c,d,e)}catch(k){J(f);if(k!==k+0)throw k;I(1,0)}}function jd(a,b,c,d,e,f){var k=K();try{return wf(a,b,c,d,e,f)}catch(h){J(k);if(h!==h+0)throw h;I(1,0)}}function ed(a,b,c,d,e,f){var k=K();try{return nf(a,b,c,d,e,f)}catch(h){J(k);if(h!==h+0)throw h;I(1,0)}}function dd(a,b,c,d,e,f){var k=K();try{return xf(a,b,c,d,e,f)}catch(h){J(k);if(h!==h+0)throw h;I(1,0)}} +function gd(a,b,c,d,e,f,k,h){var l=K();try{return of(a,b,c,d,e,f,k,h)}catch(p){J(l);if(p!==p+0)throw p;I(1,0)}}function rd(a,b,c,d,e){var f=K();try{return yf(a,b,c,d,e)}catch(k){J(f);if(k!==k+0)throw k;I(1,0);return 0n}}function Yc(a,b,c,d){var e=K();try{return zf(a,b,c,d)}catch(f){J(e);if(f!==f+0)throw f;I(1,0)}}function Wc(a,b,c,d){var e=K();try{return Af(a,b,c,d)}catch(f){J(e);if(f!==f+0)throw f;I(1,0)}} +function hd(a,b,c,d,e,f,k,h,l,p,q,y){var z=K();try{return Bf(a,b,c,d,e,f,k,h,l,p,q,y)}catch(A){J(z);if(A!==A+0)throw A;I(1,0)}}function Cd(a,b,c,d,e,f,k,h,l,p,q){var y=K();try{Cf(a,b,c,d,e,f,k,h,l,p,q)}catch(z){J(y);if(z!==z+0)throw z;I(1,0)}}function Ed(a,b,c,d,e,f,k,h,l,p,q,y,z,A,ja,Aa){var Nh=K();try{Df(a,b,c,d,e,f,k,h,l,p,q,y,z,A,ja,Aa)}catch(Db){J(Nh);if(Db!==Db+0)throw Db;I(1,0)}}function qd(a,b,c){var d=K();try{return kf(a,b,c)}catch(e){J(d);if(e!==e+0)throw e;I(1,0);return 0n}} +function Xc(a,b,c){var d=K();try{return jf(a,b,c)}catch(e){J(d);if(e!==e+0)throw e;I(1,0)}}function Vc(a,b,c){var d=K();try{return lf(a,b,c)}catch(e){J(d);if(e!==e+0)throw e;I(1,0)}}function vd(a,b,c,d){var e=K();try{mf(a,b,c,d)}catch(f){J(e);if(f!==f+0)throw f;I(1,0)}}function ke(){var a=F;a=Object.assign({},a);var b=d=>e=>d(e)>>>0,c=d=>()=>d()>>>0;a.ic=b(a.ic);a.Nc=c(a.Nc);a.Pc=b(a.Pc);a.Bd=(d=>(e,f)=>d(e,f)>>>0)(a.Bd);a.Gd=b(a.Gd);a.Hd=c(a.Hd);a.Ld=b(a.Ld);return a} +function Fa(){if(0{const b=new WeakMap;let c=1,d=void 0,e=void 0;g.webgpuRegisterDevice=h=>{if(void 0!==e)throw Error("another WebGPU EP inference session is being created.");if(h){var l=b.get(h);if(!l){l=ne();const p=oh(h,l);l=[c++,l,p];b.set(h,l)}d=h;e=l[0];return l}d=void 0;e=0};const f=new Map;g.webgpuOnCreateSession=h=>{if(void 0!==e){var l=e;e=void 0;if(h){const p=oe(l);f.set(h,p);0===l&&a(d??Y(p))}d=void 0}};g.webgpuOnReleaseSession=h=>{f.delete(h)};const k=Symbol("gpuBufferMetadata");g.webgpuRegisterBuffer= +(h,l,p)=>{if(p)return h[k]=[p,NaN],p;if(p=h[k])return p[1]++,p[0];l=f.get(l);if(void 0===l)throw Error("Invalid session handle passed to webgpuRegisterBuffer");l=nh(h,l);h[k]=[l,1];return l};g.webgpuUnregisterBuffer=h=>{const l=h[k];if(!l)throw Error("Buffer is not registered");l[1]--;0===l[1]&&(re(l[0]),delete h[k])};g.webgpuGetBuffer=h=>Y(h);g.webgpuCreateDownloader=(h,l,p)=>{p=f.get(p);if(void 0===p)throw Error("Invalid session handle passed to webgpuRegisterBuffer");const q=Y(p),y=16*Math.ceil(Number(l)/ +16);return async()=>{const z=q.createBuffer({size:y,usage:9});try{const A=q.createCommandEncoder();A.copyBufferToBuffer(h,0,z,0,y);q.queue.submit([A.finish()]);await z.mapAsync(GPUMapMode.READ);return z.getMappedRange().slice(0,l)}finally{z.destroy()}}};g.pe=(h,l)=>{var p=l.buffer;const q=l.byteOffset,y=l.byteLength;l=16*Math.ceil(Number(y)/16);h=Y(h);if(!d){var z=oe(e);d=Y(z)}z=d.createBuffer({mappedAtCreation:!0,size:l,usage:6});const A=z.getMappedRange();(new Uint8Array(A)).set(new Uint8Array(p, +q,y));z.unmap();p=d.createCommandEncoder();p.copyBufferToBuffer(z,0,h,0,l);d.queue.submit([p.finish()]);z.destroy()}}; +g.webnnInit=a=>{const b=a[0];[g.Pe,g.qe,g.webnnEnsureTensor,g.re,g.webnnDownloadTensor,g.Oe,g.webnnEnableTraceEvent]=a.slice(1);g.webnnReleaseTensorId=g.qe;g.webnnUploadTensor=g.re;g.webnnRegisterMLContext=g.Oe;g.webnnOnRunStart=c=>b.onRunStart(c);g.webnnOnRunEnd=b.onRunEnd.bind(b);g.webnnOnReleaseSession=c=>{b.onReleaseSession(c)};g.webnnCreateMLTensorDownloader=(c,d)=>b.createMLTensorDownloader(c,d);g.webnnRegisterMLTensor=(c,d,e,f)=>b.registerMLTensor(c,d,e,f);g.webnnCreateMLContext=c=>b.createMLContext(c); +g.webnnRegisterGraphInput=b.registerGraphInput.bind(b);g.webnnIsGraphInput=b.isGraphInput.bind(b);g.webnnRegisterGraphOutput=b.registerGraphOutput.bind(b);g.webnnIsGraphOutput=b.isGraphOutput.bind(b);g.webnnCreateTemporaryTensor=b.createTemporaryTensor.bind(b);g.webnnIsGraphInputOutputTypeSupported=b.isGraphInputOutputTypeSupported.bind(b)};Sa?moduleRtn=g:moduleRtn=new Promise((a,b)=>{ya=a;za=b}); +;return moduleRtn}export default ortWasmThreaded;var isPthread=globalThis.self?.name?.startsWith("em-pthread");var isNode=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer";if(isNode)isPthread=(await import("worker_threads")).workerData==="em-pthread";isPthread&&ortWasmThreaded(); diff --git a/vendor/ort/ort-wasm-simd-threaded.asyncify.wasm b/vendor/ort/ort-wasm-simd-threaded.asyncify.wasm new file mode 100644 index 0000000000000000000000000000000000000000..811402f06e2fa7661d75d67dbf61c4683b3aad96 --- /dev/null +++ b/vendor/ort/ort-wasm-simd-threaded.asyncify.wasm @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:49871f5a4409519797e127440868a6d1923339d9185907f301a5b2a1d90af082 +size 26861777 diff --git a/vendor/transformers.min.js b/vendor/transformers.min.js new file mode 100644 index 0000000000000000000000000000000000000000..3713a217e10ab4cb21e1819c0697b034c0a9c6f6 --- /dev/null +++ b/vendor/transformers.min.js @@ -0,0 +1,42 @@ +var OP=Object.defineProperty;var Ts=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var yn=(t,e)=>{for(var r in e)OP(t,r,{get:e[r],enumerable:!0})};var xt={};var Gt={};var kA={};var IP="4.3.2",ld=typeof self<"u",bn=!OA(xt),TA=!OA(Gt),Oc=ld&&"caches"in self,CP=typeof globalThis.Deno<"u",C3=typeof globalThis.Bun<"u",Cc=CP&&Oc&&!bn,SA=typeof process<"u",MA=SA&&process?.release?.name==="node"&&!Cc,cd=typeof window<"u"&&typeof window.document<"u",ud=ld&&["DedicatedWorkerGlobalScope","ServiceWorkerGlobalScope","SharedWorkerGlobalScope"].includes(self.constructor?.name),PP=cd||ud||Cc,NP=MA||typeof navigator<"u"&&"gpu"in navigator,LP=typeof navigator<"u"&&"ml"in navigator,zP=typeof crypto<"u"&&typeof crypto.getRandomValues=="function",$P=typeof chrome<"u"&&typeof chrome.runtime<"u"&&typeof chrome.runtime.id=="string",RP=typeof ServiceWorkerGlobalScope<"u"&&ld&&self instanceof ServiceWorkerGlobalScope,BP=()=>{if(typeof navigator>"u")return!1;let t=navigator.userAgent;if(!((navigator.vendor||"").indexOf("Apple")>-1&&!t.match(/CriOS|FxiOS|EdgiOS|OPiOS|mercury|brave/i)&&!t.includes("Chrome")&&!t.includes("Android")))return!1;let r=t.match(/Version\/(\d+)/);return r?parseInt(r[1],10)<26:!1},DP=BP(),le=Object.freeze({IS_BROWSER_ENV:cd,IS_WEBWORKER_ENV:ud,IS_WEB_ENV:PP,IS_SERVICE_WORKER_ENV:RP,IS_DENO_WEB_RUNTIME:Cc,IS_WEB_CACHE_AVAILABLE:Oc,IS_WEBGPU_AVAILABLE:NP,IS_WEBNN_AVAILABLE:LP,IS_SAFARI_BELOW_26:DP,IS_PROCESS_AVAILABLE:SA,IS_NODE_ENV:MA,IS_FS_AVAILABLE:bn,IS_PATH_AVAILABLE:TA,IS_CRYPTO_AVAILABLE:zP,IS_CHROME_AVAILABLE:$P}),pd=bn&&TA,Ic="./";if(pd){let t=import.meta.url;t?Ic=Gt.dirname(Gt.dirname(kA.fileURLToPath(t))):typeof __dirname<"u"&&(Ic=Gt.dirname(__dirname))}var UP=pd?Gt.join(Ic,"/.cache/"):null,EA="/models/",FP=pd?Gt.join(Ic,EA):EA,GP=typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):void 0,It=Object.freeze({DEBUG:10,INFO:20,WARNING:30,ERROR:40,NONE:50}),AA=It.WARNING,he={version:IP,backends:{onnx:{}},get logLevel(){return AA},set logLevel(t){AA=t,he.backends.onnx?.setLogLevel?.(t)},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(cd||ud||Cc),localModelPath:FP,useFS:bn,useBrowserCache:Oc,useFSCache:bn,cacheDir:UP,useCustomCache:!1,customCache:null,useWasmCache:Oc||bn,cacheKey:"transformers-cache",experimental_useCrossOriginStorage:!1,fetch:GP};function OA(t){return Object.keys(t).length===0}var We=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}_call(...t){throw Error("Must implement _call method in subclass")}};function fr(t,e){t&&t(e)}var Ar=class extends We{constructor(e,r){super(),this.callback=e,this.files_loading=r,this.loads=new Map}_call(e){if(e.status==="progress"){this.files_loading[e.file]={loaded:e.loaded,total:e.total};let r=Object.values(this.files_loading).reduce((o,a)=>o+a.loaded,0),s=Object.values(this.files_loading).reduce((o,a)=>o+a.total,0),n=s>0?r/s*100:0;this.callback({status:"progress_total",name:e.name,progress:n,loaded:r,total:s,files:structuredClone(this.files_loading)})}this.callback(e)}};function IA(t){return Number.isInteger(t)||typeof t=="bigint"}function fd(t){return t==null||t===-1}function dd(t){let e=[],r=t;for(;Array.isArray(r);)e.push(r.length),r=r[0];return e}function yt(...t){return Array.prototype.concat.apply([],t)}function CA(...t){return t.reduce((e,r)=>e.flatMap(s=>r.map(n=>[s,n])))}function vn(t,e){return Math.abs((t+e)%(2*e)-e)}function He(t,e){return Object.assign({},...e.map(r=>{if(t[r]!==void 0)return{[r]:t[r]}}))}function PA(t,e){let r=0;for(let s of t)s===e&&++r;return r}var te={error(...t){he.logLevel<=It.ERROR&&console.error(...t)},warn(...t){he.logLevel<=It.WARNING&&console.warn(...t)},info(...t){he.logLevel<=It.INFO&&console.log(...t)},debug(...t){he.logLevel<=It.DEBUG&&console.log(...t)},log(...t){this.info(...t)}};var jP=class{constructor(t){this.trie=this._build_trie(t)}_build_trie(t){let e=Object.create(null);for(let r of t){let s=e;for(let n=0;ns&&e.push(t.slice(s,n)),e.push(a),n+=a.length,s=n):++n}return s{try{return new RegExp(t,e)}catch(r){if(!(r instanceof SyntaxError))throw r;let s=new Map,n=t.replace(/(\\[pP])\{([^}=]+)\}/g,(o,a,i,l)=>{let c=0;for(let f=l-1;f>=0&&t[f]==="\\";--f)++c;if(c%2===1)return o;let u=s.get(i);if(u===void 0){try{new RegExp(`\\p{${i}}`,"u"),u=i}catch{u=`Script=${i}`}s.set(i,u)}return`${a}{${u}}`});if(n===t)throw r;try{return new RegExp(n,e)}catch{throw r}}},_d=t=>t.replace(/ \./g,".").replace(/ \?/g,"?").replace(/ \!/g,"!").replace(/ ,/g,",").replace(/ \' /g,"'").replace(/ n't/g,"n't").replace(/ 'm/g,"'m").replace(/ 's/g,"'s").replace(/ 've/g,"'ve").replace(/ 're/g,"'re"),zc=(t,e=!0)=>{if(t.Regex!==void 0){let r=lN(oN(t.Regex));return jA(r,"gu")}else if(t.String!==void 0){let r=cN(t.String);return new RegExp(e?r:`(${r})`,"gu")}else return console.warn("Unknown pattern type:",t),null},kn="\\p{Alphabetic}\\p{M}\\p{Nd}\\p{Pc}",qA=`${kn}\\u00B2\\u00B3\\u00B9\\u00BC-\\u00BE`,dr=`[${qA}]`,WA=`[^${qA}]`,VP=`(?:(?|[:=!>])/,XA=/^\\([pPxu])\{([^}]*)\}/,tN=/^\{(\d+(?:,\d*)?|,\d+)\}/,rN=/^\[:(\^?)(\p{Alphabetic}+):\]/u,sN=/^\[:\^:\]/,nN=/^\[(?:\.[^\]]*\.\]|=[^\]]*=\])/,KA=/^(?:\\x[0-9A-Fa-f]{2}|\\u[0-9A-Fa-f]{4}|\\c[A-Za-z])/,YA=t=>t>="A"&&t<="Z"||t>="a"&&t<="z",Pc=(t,e)=>String.fromCodePoint(t.codePointAt(e)),LA=t=>{if(!/^[0-9A-Fa-f]{1,8}$/.test(t))return null;let e=Number.parseInt(t,16);if(e>127)return null;let r=String.fromCharCode(e);return YA(r)?`[${r.toLowerCase()}${r.toUpperCase()}]`:null},oN=t=>t.replace(/\[\^\(\\s\|\[([^\]]+)\]\)\]/g,"[^()|\\s$1]"),QA="[\\s\\S]",zA=256,$A=()=>({fragment:"",alternatives:[],tail:null,contains_complex_set:!1}),hd=t=>{throw new SyntaxError(`Unsupported range with a set-valued character-class operand at index ${t}`)},Nc=(t,e,r,s=!0)=>{t.tail==="range"&&hd(r),t.alternatives.push(e),t.tail="set",t.contains_complex_set=t.contains_complex_set||s},Rr=(t,e,r=!1,s=-1)=>{if(r&&t.tail==="range"&&hd(s),t.tail==="range"){t.fragment+=e,t.tail="complete_range";return}t.fragment+=e,t.tail=r?"set":"scalar",t.contains_complex_set=t.contains_complex_set||r},aN=(t,e,r)=>{let s=XA.exec(t.slice(e));if(s){let[m,_,w]=s;if(_==="P"&&w==="Word")Nc(r,`[^${kn}]`,e);else{let x=_==="x"?`\\u{${w}}`:_==="p"&&w==="Word"?kn:m;Rr(r,x,_==="p"||_==="P",e)}return e+m.length}let n=KA.exec(t.slice(e));if(n)return Rr(r,n[0]),e+n[0].length;if(e+1>=t.length)throw new SyntaxError(`Unterminated escape in character class at index ${e}`);let o=Pc(t,e+1),a=e+1+o.length,i=VA.get(o);if(i!==void 0)return Rr(r,i),a;let l=JP.get(o);if(l!==void 0)return Nc(r,l,e),a;let c=QP.get(o),u,f=!1;return c!==void 0?(u=c,f=o!=="a"&&o!=="e"):/[A-Za-z0-9]/.test(o)?u=`\\${o}`:HA.includes(o)||o==="-"?u=`\\${o}`:u=o,Rr(r,u,f,e),a},JA=t=>t.length===1?t[0]:`(?:(?=(?:${t.join("|")}))${QA})`,RA=t=>{let e=t.fragment.length===0?t.alternatives:[`[${t.fragment}]`,...t.alternatives];return JA(e)},iN=t=>{let e=jA(`^(?:${t})$`,"u"),r="";for(let s=0;s<26;++s){let n=String.fromCharCode(65+s),o=String.fromCharCode(97+s),a=e.test(n),i=e.test(o);a!==i&&(r+=a?o:n)}return r},ZA=(t,e,r,s=!0,n=1)=>{if(n>zA)throw new SyntaxError(`Maximum character-class nesting depth of ${zA} exceeded at index ${e}`);let o=e+1,a=t[o]==="^";a&&++o;let i=o,l=[$A()],c=l[0],u=!1;for(;o1?new SyntaxError(`Malformed character-class intersection with an empty operand at index ${o}`):new SyntaxError(`Empty character class at index ${e}`);let m=l.some(k=>k.contains_complex_set);if(a&&l.length>1&&u)throw new SyntaxError(`Unsupported outer-negated character-class intersection with a nested negated class containing a Unicode property, POSIX class, or shorthand at index ${e}`);let _=RA(l[0]),w=_;if(l.length>1){let k="";for(let M=1;M0&&(x?(b+=k,w=`[${b}]`):w=JA([w,`[${k}]`]))}return{atom:a?x?`[^${b}]`:`(?:(?!${w})${QA})`:w,end:o+1,negated:a,contains_complex_set:m,contains_nested_negated_complex_set:u}}if(t.startsWith("&&",o)){if(c.tail===null)throw new SyntaxError(`Malformed character-class intersection with an empty operand at index ${o}`);c=$A(),l.push(c),o+=2;continue}if(f==="["){let m=t.slice(o);if(sN.test(m))throw new SyntaxError(`Malformed empty negated POSIX character class at index ${o}`);let _=rN.exec(m);if(_){let[,x,b]=_,A=ZP.get(b);if(A===void 0)throw new SyntaxError(`Unsupported POSIX character class "${b}" at index ${o}`);if(r&&x&&(b==="lower"||b==="upper"))throw new SyntaxError(`Unsupported negated POSIX ${b} class inside an inline case-insensitive group`);x?Nc(c,`[^${A}]`,o):Rr(c,A,!0,o),o+=_[0].length;continue}if(nN.test(m))throw new SyntaxError(`Unsupported POSIX collating or equivalence bracket expression at index ${o}`);let w=ZA(t,o,r,!1,n+1);Nc(c,w.atom,o,w.contains_complex_set),u||=w.contains_nested_negated_complex_set||w.negated&&w.contains_complex_set,o=w.end;continue}if(f==="-"){let m=t[o+1]==="]"||t.startsWith("&&",o+1);c.tail==="set"&&!m&&hd(o),c.tail===null||c.tail==="range"||c.tail==="complete_range"||m?Rr(c,"\\-"):(c.fragment+="-",c.tail="range"),++o;continue}Rr(c,f==="^"&&c.fragment.length===0?"\\^":f),o+=f.length}throw new SyntaxError(`${l.length>1?"Unterminated character-class intersection":"Unterminated character class"} at index ${e}`)},lN=t=>{let e="",r=-1,s=!1,n=!1,o=[],a=i=>{r=e.length,e+=i,s=!1};for(let i=0;i=t.length){e+=l;break}let f=Pc(t,i+1);if(i+=1+f.length,f==="G")continue;let m=VA.get(f);if(m!==void 0){a(m);continue}let _=YP.get(f),w;_!==void 0?w=_:/[A-Za-z0-9]/.test(f)?w=`\\${f}`:HA.includes(f)?w=`\\${f}`:w=f,a(w);continue}switch(l){case"[":{let c=ZA(t,i,n);a(c.atom),i=c.end;continue}case"]":a("\\]"),++i;continue;case".":a("[^\\n]"),++i;continue;case"^":a(XP),++i;continue;case"$":a(KP),++i;continue;case"(":{let c=t.startsWith("(?i:",i),u=c?"(?i:":eN.exec(t.slice(i))?.[0]??"(",f=c||u==="(?>"?"(?:":u;o.push([e.length,n]),c&&(n=!0),e+=f,s=!1,i+=u.length;continue}case")":e+=l,[r,n]=o.pop()??[-1,!1],s=!1,++i;continue;case"|":e+=l,r=-1,s=!1,++i;continue;case"{":{let c=tN.exec(t.slice(i));if(!c||r<0){a("\\{"),++i;continue}let u=c[1].startsWith(",")?`0${c[1]}`:c[1];i+=c[0].length;let f=t[i];f==="+"||f==="*"?(e=`${e.slice(0,r)}(?:${e.slice(r)}{${u}})${f}`,++i):e+=`{${u}}`,s=!0;continue}case"}":a("\\}"),++i;continue;case"+":if(s){++i;continue}e+=l,s=!0,++i;continue;case"*":case"?":e+=l,s=!0,++i;continue;default:a(n&&YA(l)?`[${l.toLowerCase()}${l.toUpperCase()}]`:l),i+=l.length;continue}}return e},cN=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),uN=(t,e,r)=>{let s=[],n=0;for(;nt>=19968&&t<=40959||t>=13312&&t<=19903||t>=131072&&t<=173791||t>=173824&&t<=177983||t>=177984&&t<=178207||t>=178208&&t<=183983||t>=63744&&t<=64255||t>=194560&&t<=195103,fN=t=>Number.isInteger(t)||typeof t=="bigint",dN=t=>{let e=0;for(let r of t)++e;return e},mN=t=>e2(t.toLowerCase()),Qt=(...t)=>Array.prototype.concat.apply([],t),gd=t=>new Map(Object.entries(t)),_N=(t,e)=>{let r=[],s=0;for(let n of t.matchAll(e)){let o=n[0];s0&&r.push(o),s=n.index+o.length}return st.replace(/\p{M}/gu,""),BA=(t,e,r=[])=>{if(!t||Array.isArray(t)||typeof t!="object")return`${e} must be a valid object`;for(let s of r)if(!(s in t))return`${e} must contain a "${s}" property`;return null},hN=t=>t.match(/\S+/g)||[],gN=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}},Io=gN,wN=class extends Io{constructor(t){super(),this.config=t}_call(t){return this.normalize(t)}},Tr=wN,xN=class extends Tr{tokenize_chinese_chars(t){let e=[];for(let r=0;rr.normalize("NFKC")).join("\uFF5E"):t=t.normalize("NFKC"),t}},vN=bN,kN=class extends Tr{constructor(t){super(t),this.normalizers=(t.normalizers??[]).map(e=>t2(e))}normalize(t){return this.normalizers.reduce((e,r)=>r?r.normalize(e):e,t)}},EN=kN,AN=class extends Tr{constructor(t){super(t),this.pattern=zc(this.config.pattern??{})}normalize(t){return this.pattern===null?t:t.replaceAll(this.pattern,this.config.content??"")}},TN=AN,SN=class extends Tr{constructor(){super(...arguments),this.form="NFC"}normalize(t){return t=t.normalize(this.form),t}},$c=SN,MN=class extends $c{constructor(){super(...arguments),this.form="NFC"}},ON=MN,IN=class extends $c{constructor(){super(...arguments),this.form="NFD"}},CN=IN,PN=class extends $c{constructor(){super(...arguments),this.form="NFKC"}},NN=PN,LN=class extends $c{constructor(){super(...arguments),this.form="NFKD"}},zN=LN,$N=class extends Tr{normalize(t){return this.config.strip_left&&this.config.strip_right?t=t.trim():(this.config.strip_left&&(t=t.trimStart()),this.config.strip_right&&(t=t.trimEnd())),t}},RN=$N,BN=class extends Tr{normalize(t){return e2(t)}},DN=BN,UN=class extends Tr{normalize(t){return t.toLowerCase()}},FN=UN,GN=class extends Tr{normalize(t){return t=this.config.prepend+t,t}},jN=GN;function qN(t){if(t===null)return null;switch(t.type){case"BertNormalizer":return new yN(t);case"Precompiled":return new vN(t);case"Sequence":return new EN(t);case"Replace":return new TN(t);case"NFC":return new ON(t);case"NFD":return new CN(t);case"NFKC":return new NN(t);case"NFKD":return new zN(t);case"Strip":return new RN(t);case"StripAccents":return new DN(t);case"Lowercase":return new FN(t);case"Prepend":return new jN(t);default:throw new Error(`Unknown Normalizer type: ${t.type}`)}}var t2=qN,WN=class extends Io{pre_tokenize(t,e){return(Array.isArray(t)?t.map(r=>this.pre_tokenize_text(r,e)):this.pre_tokenize_text(t,e)).flat()}_call(t,e){return this.pre_tokenize(t,e)}},Jt=WN,r2=(()=>{let t=[...Array.from({length:94},(n,o)=>o+33),...Array.from({length:12},(n,o)=>o+161),...Array.from({length:82},(n,o)=>o+174)],e=t.slice(),r=0;for(let n=0;n<256;++n)t.includes(n)||(t.push(n),e.push(256+r),r+=1);let s=e.map(n=>String.fromCharCode(n));return Object.fromEntries(t.map((n,o)=>[n,s[o]]))})(),VN=t=>Object.fromEntries(Object.entries(t).map(([e,r])=>[r,e])),HN=VN(r2),Lc="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",XN=class extends Jt{constructor(t){super(),this.config=t,this.add_prefix_space=this.config.add_prefix_space??!1,this.trim_offsets=this.config.trim_offsets??!1,this.use_regex=this.config.use_regex??!0,this.pattern=/'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+/gu,this.byte_encoder=r2,this.text_encoder=new TextEncoder}pre_tokenize_text(t,e){return this.add_prefix_space&&!t.startsWith(" ")&&(t=" "+t),(this.use_regex?t.match(this.pattern)||[]:[t]).map(s=>Array.from(this.text_encoder.encode(s),n=>this.byte_encoder[n]).join(""))}},KN=XN,YN=class extends Jt{pre_tokenize_text(t,e){return t.match(/\w+|[^\w\s]+/g)||[]}},QN=YN,JN=class extends Jt{constructor(t){super(),this.replacement=t.replacement??"\u2581",this.str_rep=t.str_rep||this.replacement,this.prepend_scheme=t.prepend_scheme??"always"}pre_tokenize_text(t,e){let{section_index:r=void 0}=e??{},s=t.replaceAll(" ",this.str_rep);return!s.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&r===0)&&(s=this.str_rep+s),[s]}},ZN=JN,eL=class extends Jt{constructor(t){super(),this.config=t,this.pattern=zc(this.config.pattern??{},this.config.invert??!0)}pre_tokenize_text(t){return this.pattern===null?[]:this.config.invert?(t.match(this.pattern)||[]).filter(e=>e):this.config.behavior?.toLowerCase()==="removed"?t.split(this.pattern).filter(e=>e):_N(t,this.pattern)}},tL=eL,rL=class extends Jt{constructor(t){super(),this.config=t,this.pattern=new RegExp(`[^${Lc}]+|[${Lc}]+`,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},sL=rL,nL=class extends Jt{constructor(t){super(),this.config=t;let e=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(e,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},oL=nL,aL=class extends Jt{constructor(){super(),this.pattern=new RegExp(`[^\\s${Lc}]+|[${Lc}]`,"gu")}pre_tokenize_text(t,e){return t.trim().match(this.pattern)||[]}},iL=aL,lL=class extends Jt{constructor(t){super(),this.config=t,this.pattern=zc(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(t){return this.pattern===null?[t]:[t.replaceAll(this.pattern,this.config.content??"")]}},cL=lL,uL=class extends Jt{constructor(t){super(),this.tokenizers=(t.pretokenizers??[]).map(e=>s2(e))}pre_tokenize_text(t,e){return this.tokenizers.reduce((r,s)=>s?s.pre_tokenize(r,e):r,[t])}},pL=uL,fL=class extends Jt{pre_tokenize_text(t){return hN(t)}},dL=fL,mL=class extends Jt{constructor(t){super(),this.config=t,this._length=t.length}pre_tokenize_text(t){let e=[];for(let r=0;rthis.max_input_chars_per_word){e.push(this.unk_token);continue}let n=!1,o=0,a=[];for(;o0&&(c=this.config.continuing_subword_prefix+c),this.tokens_to_ids.has(c)){l=c;break}--i}if(l===null){n=!0;break}a.push(l),o=i}n?e.push(this.unk_token):e.push(...a)}return e}},DA=wL,UA=class n2{constructor(e,r){this.is_leaf=e,this.children=r}static default(){return new n2(!1,new Map)}},xL=class{constructor(){this.root=UA.default()}extend(t){for(let e of t)this.push(e)}push(t){let e=this.root;for(let r of t){let s=e.children.get(r);s===void 0&&(s=UA.default(),e.children.set(r,s)),e=s}e.is_leaf=!0}*common_prefix_search(t,e=0){let r=this.root;if(r===void 0)return;let s="";for(let n=e;n[]),this.end_nodes=Array.from({length:this.len+1},()=>[]);let s=new md(this.bos_token_id??0,0,0,0,0),n=new md(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(s.clone()),this.nodes.push(n.clone()),this.begin_nodes[this.len].push(n),this.end_nodes[0].push(s)}insert(t,e,r,s){let n=this.nodes.length,o=new md(s,n,t,e,r);this.begin_nodes[t].push(o),this.end_nodes[t+e].push(o),this.nodes.push(o)}viterbi(){let t=this.len,e=0;for(;e<=t;){if(this.begin_nodes[e].length==0)return[];for(let a of this.begin_nodes[e]){a.prev=null;let i=0,l=null;for(let c of this.end_nodes[e]){let u=c.backtrace_score+a.score;(l===null||u>i)&&(l=c.clone(),i=u)}if(l!==null)a.prev=l,a.backtrace_score=i;else return[]}++e}let r=[],n=this.begin_nodes[t][0].prev;if(n===null)return[];let o=n.clone();for(;o.prev!==null;)r.push(o.clone()),o=o.clone().prev.clone();return r.reverse(),r}piece(t){return this.chars.slice(t.pos,t.pos+t.length).join("")}tokens(){return this.viterbi().map(e=>this.piece(e))}token_ids(){return this.viterbi().map(e=>e.token_id)}},vL=bL;function kL(t){if(t.length===0)throw new Error("Array must not be empty");let e=t[0],r=0;for(let s=1;s[s,n])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=e,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.min_score=kL(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new yL,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(t){let e=t.chars,r=1,s=0;for(;sr>s,e=1/0){this._heap=[],this._comparator=t,this._max_size=e}get size(){return this._heap.length}is_empty(){return this.size===0}peek(){return this._heap[0]}push(...t){return this.extend(t)}extend(t){for(let e of t)if(this.size0&&this._swap(0,e),this._heap.pop(),this._sift_down(),t}replace(t){let e=this.peek();return this._heap[0]=t,this._sift_down(),e}_parent(t){return(t+1>>>1)-1}_left(t){return(t<<1)+1}_right(t){return t+1<<1}_greater(t,e){return this._comparator(this._heap[t],this._heap[e])}_swap(t,e){let r=this._heap[t];this._heap[t]=this._heap[e],this._heap[e]=r}_sift_up(){this._sift_up_from(this.size-1)}_sift_up_from(t){for(;t>0&&this._greater(t,this._parent(t));)this._swap(t,this._parent(t)),t=this._parent(t)}_sift_down(){let t=0;for(;this._left(t)this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}},ML=SL,OL=class extends Rc{constructor(t){super(t),this.tokens_to_ids=gd(t.vocab),this.unk_token_id=this.tokens_to_ids.get(t.unk_token),this.unk_token=t.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(let[r,s]of this.tokens_to_ids)this.vocab[s]=r;let e=Array.isArray(t.merges[0]);this.merges=e?t.merges:t.merges.map(r=>r.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((r,s)=>[JSON.stringify(r),s])),this.end_of_word_suffix=t.end_of_word_suffix,this.continuing_subword_suffix=t.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.max_length_to_cache=256,this.cache_capacity=1e4,this.cache=new ML(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe(t){if(t.length===0)return[];let e=this.cache.get(t);if(e!==void 0)return e;let r=Array.from(t);this.end_of_word_suffix&&(r[r.length-1]+=this.end_of_word_suffix);let s=[];if(r.length>1){let n=new TL((i,l)=>i.score`<0x${a.toString(16).toUpperCase().padStart(2,"0")}>`);o.every(a=>this.tokens_to_ids.has(a))?e.push(...o):this.unk_token!=null&&e.push(this.unk_token)}else this.unk_token!=null&&e.push(this.unk_token)}return e}},GA=OL,IL=class extends Rc{constructor(t,e){super(t);let r=t.vocab;this.tokens_to_ids=gd(e.target_lang?r[e.target_lang]:r),this.bos_token=e.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=e.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=e.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=e.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(let[s,n]of this.tokens_to_ids)this.vocab[n]=s}encode(t){return t}},CL=IL;function PL(t,e){switch(t.type){case"WordPiece":return new DA(t);case"Unigram":return new FA(t,e.eos_token);case"BPE":return new GA(t);default:if(t.vocab)return Array.isArray(t.vocab)?new FA(t,e.eos_token):Object.hasOwn(t,"continuing_subword_prefix")&&Object.hasOwn(t,"unk_token")?Object.hasOwn(t,"merges")?new GA(t):new DA(t):new CL(t,{target_lang:e.target_lang,bos_token:e.bos_token,eos_token:e.eos_token,pad_token:e.pad_token,unk_token:e.unk_token});throw new Error(`Unknown TokenizerModel type: ${t?.type}`)}}var NL=PL,LL=class extends Io{constructor(t){super(),this.config=t}_call(t,...e){return this.post_process(t,...e)}},Co=LL,zL=class extends Co{post_process(t,e=null,r=!0){let s=e===null?this.config.single:this.config.pair,n=[],o=[];for(let a of s)"SpecialToken"in a?r&&(n.push(a.SpecialToken.id),o.push(a.SpecialToken.type_id)):"Sequence"in a&&(a.Sequence.id==="A"?(n=Qt(n,t),o=Qt(o,new Array(t.length).fill(a.Sequence.type_id))):a.Sequence.id==="B"&&(n=Qt(n,e),o=Qt(o,new Array(e.length).fill(a.Sequence.type_id))));return{tokens:n,token_type_ids:o}}},$L=zL,RL=class extends Co{post_process(t,e=null){return{tokens:t,tokens_pair:e}}},BL=RL,DL=class extends Co{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e=null,r=!0){r&&(t=Qt([this.cls[0]],t,[this.sep[0]]));let s=new Array(t.length).fill(0);if(e){let n=[],o=r?[this.sep[0]]:[];t=Qt(t,n,e,o),s=Qt(s,new Array(e.length+n.length+o.length).fill(1))}return{tokens:t,token_type_ids:s}}},UL=DL,FL=class extends Co{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e,r=!0){r&&(t=Qt([this.cls[0]],t,[this.sep[0]]));let s=new Array(t.length).fill(0);if(e){let n=r?[this.sep[0]]:[],o=r?[this.sep[0]]:[];t=Qt(t,n,e,o),s=Qt(s,new Array(e.length+n.length+o.length).fill(1))}return{tokens:t,token_type_ids:s}}},GL=FL,jL=class extends Co{constructor(t){super(t),this.processors=(t.processors??[]).map(e=>a2(e))}post_process(t,e=null,r=!0){let s={tokens:t,tokens_pair:e};for(let n of this.processors)s=n.post_process(s.tokens,s.tokens_pair,r);return s}},qL=jL;function WL(t){if(t===null)return null;switch(t.type){case"TemplateProcessing":return new $L(t);case"ByteLevel":return new BL(t);case"BertProcessing":return new UL(t);case"RobertaProcessing":return new GL(t);case"Sequence":return new qL(t);default:throw new Error(`Unknown PostProcessor type: ${t.type}`)}}var a2=WL,VL=class extends Io{constructor(t){super(),this.config=t,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets="trim_offsets"in t?t.trim_offsets:!1}_call(t){return this.decode(t)}decode(t){return this.decode_chain(t).join("")}},jt=VL,HL=class extends jt{constructor(t){super(t),this.byte_decoder=HN,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(t){let e=t.join(""),r=new Uint8Array([...e].map(s=>this.byte_decoder[s]));return this.text_decoder.decode(r)}decode_chain(t){let e=[],r=[];for(let s of t)this.added_tokens.find(n=>n.content===s)!==void 0?(r.length>0&&(e.push(this.convert_tokens_to_string(r)),r=[]),e.push(s)):r.push(s);return r.length>0&&e.push(this.convert_tokens_to_string(r)),e}},XL=HL,KL=class extends jt{constructor(t){super(t),this.cleanup=t.cleanup}decode_chain(t){return t.map((e,r)=>{if(r!==0){let s=this.config.prefix;s&&e.startsWith(s)?e=e.replace(s,""):e=" "+e}return this.cleanup&&(e=_d(e)),e})}},YL=KL,QL=class extends jt{constructor(t){super(t),this.replacement=t.replacement??"\u2581"}decode_chain(t){let e=[];for(let r=0;re.replaceAll(this.suffix,r===t.length-1?"":" "))}},ez=ZL,tz=class extends jt{constructor(t){super(t),this.pad_token=t.pad_token??"",this.word_delimiter_token=t.word_delimiter_token??"",this.cleanup=t.cleanup}convert_tokens_to_string(t){if(t.length===0)return"";let e=[t[0]];for(let n=1;nn!==this.pad_token).join("");return this.cleanup&&(s=_d(s).replaceAll(this.word_delimiter_token," ").trim()),s}decode_chain(t){return[this.convert_tokens_to_string(t)]}},rz=tz,sz=class extends jt{constructor(t){super(t),this.decoders=(t.decoders??[]).map(e=>i2(e))}decode_chain(t){return this.decoders.reduce((e,r)=>r.decode_chain(e),t)}},nz=sz,oz=class extends jt{constructor(t){super(t),this.pattern=zc(this.config.pattern)}decode_chain(t){let e=this.config.content??"",r=this.pattern;return r===null?t:t.map(s=>s.replaceAll(r,e))}},az=oz,iz=class extends jt{decode_chain(t){return[t.join("")]}},lz=iz,cz=class extends jt{constructor(t){super(t),this.content=t.content??"",this.start=t.start??0,this.stop=t.stop??0}decode_chain(t){return t.map(e=>{let r=0;for(let n=0;n")){let o=parseInt(s.slice(3,5),16);isNaN(o)||(n=o)}if(n!==null)r.push(n);else{if(r.length>0){let o=this.text_decoder.decode(Uint8Array.from(r));e.push(o),r=[]}e.push(s)}}if(r.length>0){let s=this.text_decoder.decode(Uint8Array.from(r));e.push(s),r=[]}return e}},fz=pz;function dz(t){if(t===null)return null;switch(t.type){case"ByteLevel":return new XL(t);case"WordPiece":return new YL(t);case"Metaspace":return new JL(t);case"BPEDecoder":return new ez(t);case"CTC":return new rz(t);case"Sequence":return new nz(t);case"Replace":return new az(t);case"Fuse":return new lz(t);case"Strip":return new uz(t);case"ByteFallback":return new fz(t);default:throw new Error(`Unknown Decoder type: ${t.type}`)}}var i2=dz,mz=class{constructor(t,e){let r=BA(t,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(r)throw new Error(r);let s=BA(e,"Config");if(s)throw new Error(s);this.tokenizer=t,this.config=e,this.normalizer=t2(this.tokenizer.normalizer),this.pre_tokenizer=s2(this.tokenizer.pre_tokenizer),this.model=NL(this.tokenizer.model,this.config),this.post_processor=a2(this.tokenizer.post_processor),this.decoder=i2(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];let n=[],o=[];this.added_tokens_map=new Map;for(let a of this.tokenizer.added_tokens){let i=new WP(a);if(this.added_tokens.push(i),this.model.tokens_to_ids.set(i.content,i.id),this.model.vocab[i.id]=i.content,i.special&&(this.special_tokens.push(i.content),this.all_special_ids.push(i.id)),this.added_tokens_map.set(i.content,i),i.normalized&&this.normalizer!==null){let l=this.normalizer(i.content);o.push(l),this.added_tokens_map.set(l,i)}else n.push(i.content)}(this.config.additional_special_tokens??[]).forEach(a=>{this.special_tokens.includes(a)||this.special_tokens.push(a)}),this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.splitter_unnormalized=new NA(n),this.splitter_normalized=new NA(o),this.remove_space=this.config.remove_space,this.clean_up_tokenization_spaces=this.config.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=this.config.do_lowercase_and_remove_accent??!1}encode(t,{text_pair:e=null,add_special_tokens:r=!0,return_token_type_ids:s=null}={}){let{tokens:n,token_type_ids:o}=this.tokenize_helper(t,{text_pair:e,add_special_tokens:r}),a=n.map(l=>this.added_tokens_map.get(l)?.id??this.model.tokens_to_ids.get(l)??this.model.unk_token_id),i={ids:a,tokens:n,attention_mask:new Array(a.length).fill(1)};return s&&o&&(i.token_type_ids=o),i}decode(t,e={}){if(!Array.isArray(t)||t.length===0||!fN(t[0]))throw Error("token_ids must be a non-empty array of integers.");let r=t.map(n=>this.model.vocab[Number(n)]??this.model.unk_token);e.skip_special_tokens&&(r=r.filter(n=>!this.special_tokens.includes(n)));let s=this.decoder?this.decoder(r):r.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(s=s.replaceAll(this.decoder.end_of_word_suffix," "),e.skip_special_tokens&&(s=s.trim())),(e.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)&&(s=_d(s)),s}tokenize(t,{text_pair:e=null,add_special_tokens:r=!1}={}){return this.tokenize_helper(t,{text_pair:e,add_special_tokens:r}).tokens}encode_text(t){if(t===null)return null;let e=this.splitter_unnormalized.split(t);return e.forEach((r,s)=>{let n=this.added_tokens_map.get(r);n&&(n.lstrip&&s>0&&(e[s-1]=e[s-1].trimEnd()),n.rstrip&&s{if(r.length===0)return[];if(this.added_tokens_map.has(r))return[r];if(this.remove_space===!0&&(r=r.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(r=mN(r)),this.normalizer!==null&&(r=this.normalizer(r)),r.length===0)return[];let n=this.splitter_normalized.split(r);return n.forEach((o,a)=>{let i=this.added_tokens_map.get(o);i&&(i.lstrip&&a>0&&(n[a-1]=n[a-1].trimEnd()),i.rstrip&&a{if(o.length===0)return[];if(this.added_tokens_map.has(o))return[o];let a=this.pre_tokenizer!==null?this.pre_tokenizer(o,{section_index:s}):[o];return this.model(a)})})}tokenize_helper(t,{text_pair:e=null,add_special_tokens:r=!0}){let s=this.encode_text(t),n=this.encode_text(e||null);return this.post_processor?this.post_processor(s,n,r):{tokens:Qt(s??[],n??[])}}token_to_id(t){return this.model.tokens_to_ids.get(t)}id_to_token(t){return this.model.vocab[t]}get_added_tokens_decoder(){let t=new Map;for(let e of this.added_tokens)t.set(e.id,e);return t}get_vocab(t=!0){let e=new Map;for(let r=0;re in t?_z(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,gz=(t,e,r)=>(hz(t,typeof e!="symbol"?e+"":e,r),r),D=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ExponentiationBinaryOperator:"ExponentiationBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Comment:"Comment"}),qt=class{constructor(t,e){this.value=t,this.type=e}};function c2(t){return/\w/.test(t)}function Ss(t){return/[0-9]/.test(t)}function u2(t){return/\s/.test(t)}var wz=[["{%",D.OpenStatement],["%}",D.CloseStatement],["{{",D.OpenExpression],["}}",D.CloseExpression],["(",D.OpenParen],[")",D.CloseParen],["{",D.OpenCurlyBracket],["}",D.CloseCurlyBracket],["[",D.OpenSquareBracket],["]",D.CloseSquareBracket],[",",D.Comma],[".",D.Dot],[":",D.Colon],["|",D.Pipe],["<=",D.ComparisonBinaryOperator],[">=",D.ComparisonBinaryOperator],["==",D.ComparisonBinaryOperator],["!=",D.ComparisonBinaryOperator],["<",D.ComparisonBinaryOperator],[">",D.ComparisonBinaryOperator],["+",D.AdditiveBinaryOperator],["-",D.AdditiveBinaryOperator],["~",D.AdditiveBinaryOperator],["**",D.ExponentiationBinaryOperator],["*",D.MultiplicativeBinaryOperator],["//",D.MultiplicativeBinaryOperator],["/",D.MultiplicativeBinaryOperator],["%",D.MultiplicativeBinaryOperator],["=",D.Equals]],xz=new Map([["n",` +`],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function yz(t,e={}){return t.endsWith(` +`)&&(t=t.slice(0,-1)),e.lstrip_blocks&&(t=t.replace(/^[ \t]*({[#%-])/gm,"$1")),e.trim_blocks&&(t=t.replace(/([#%-]})\n/g,"$1")),t.replace(/(\s*){%(-?)\s*(?:end)?generation\s*(-?)%}(\s*)/gs,(r,s,n,o,a)=>(n?"":s)+(o?"":a))}function bz(t,e={}){let r=[],s=yz(t,e),n=0,o=0,a=c=>{let u="";for(;c(s[n]);){if(s[n]==="\\"){if(++n,n>=s.length)throw new SyntaxError("Unexpected end of input");let f=s[n++],m=xz.get(f);if(m===void 0)throw new SyntaxError(`Unexpected escaped character: ${f}`);u+=m;continue}if(u+=s[n++],n>=s.length)throw new SyntaxError("Unexpected end of input")}return u},i=()=>{let c=r.at(-1);c&&c.type===D.Text&&(c.value=c.value.trimEnd(),c.value===""&&r.pop())},l=()=>{for(;n0){r.push(new qt(f,D.Text));continue}}if(s[n]==="{"&&s[n+1]==="#"){n+=2;let f=s[n]==="-";f&&++n;let m="";for(;s[n]!=="#"||s[n+1]!=="}";){if(n+2>=s.length)throw new SyntaxError("Missing end of comment tag");m+=s[n++]}let _=m.endsWith("-");_&&(m=m.slice(0,-1)),f&&i(),r.push(new qt(m,D.Comment)),n+=2,_&&l();continue}if(s.slice(n,n+3)==="{%-"){i(),r.push(new qt("{%",D.OpenStatement)),n+=3;continue}if(s.slice(n,n+3)==="{{-"){i(),r.push(new qt("{{",D.OpenExpression)),o=0,n+=3;continue}if(a(u2),s.slice(n,n+3)==="-%}"){r.push(new qt("%}",D.CloseStatement)),n+=3,l();continue}if(s.slice(n,n+3)==="-}}"){r.push(new qt("}}",D.CloseExpression)),n+=3,l();continue}let u=s[n];if(u==="-"||u==="+"){let f=r.at(-1)?.type;if(f===D.Text||f===void 0)throw new SyntaxError(`Unexpected character: ${u}`);switch(f){case D.Identifier:case D.NumericLiteral:case D.StringLiteral:case D.CloseParen:case D.CloseSquareBracket:break;default:{++n;let m=a(Ss);if(m.length>0&&s[n]==="."&&Ss(s[n+1])){++n;let _=a(Ss);m=`${m}.${_}`}r.push(new qt(`${u}${m}`,m.length>0?D.NumericLiteral:D.UnaryOperator));continue}}}for(let[f,m]of wz){if(f==="}}"&&o>0)continue;if(s.slice(n,n+f.length)===f){r.push(new qt(f,m)),m===D.OpenExpression?o=0:m===D.OpenCurlyBracket?++o:m===D.CloseCurlyBracket&&--o,n+=f.length;continue e}}if(u==="'"||u==='"'){++n;let f=a(m=>m!==u);r.push(new qt(f,D.StringLiteral)),++n;continue}if(Ss(u)){let f=a(Ss);if(r.at(-1)?.type!==D.Dot&&s[n]==="."&&Ss(s[n+1])){++n;let m=a(Ss);f=`${f}.${m}`}r.push(new qt(f,D.NumericLiteral));continue}if(c2(u)){let f=a(c2);r.push(new qt(f,D.Identifier));continue}throw new SyntaxError(`Unexpected character: ${u}`)}return r}var Wt=class{type="Statement"},vz=class extends Wt{constructor(t){super(),this.body=t}type="Program"},kz=class extends Wt{constructor(t,e,r){super(),this.test=t,this.body=e,this.alternate=r}type="If"},Ez=class extends Wt{constructor(t,e,r,s){super(),this.loopvar=t,this.iterable=e,this.body=r,this.defaultBlock=s}type="For"},Az=class extends Wt{type="Break"},Tz=class extends Wt{type="Continue"},Sz=class extends Wt{constructor(t,e,r){super(),this.assignee=t,this.value=e,this.body=r}type="Set"},Mz=class extends Wt{constructor(t,e,r){super(),this.name=t,this.args=e,this.body=r}type="Macro"},Oz=class extends Wt{constructor(t){super(),this.value=t}type="Comment"},Ct=class extends Wt{type="Expression"},Iz=class extends Ct{constructor(t,e,r){super(),this.object=t,this.property=e,this.computed=r}type="MemberExpression"},p2=class extends Ct{constructor(t,e){super(),this.callee=t,this.args=e}type="CallExpression"},Br=class extends Ct{constructor(t){super(),this.value=t}type="Identifier"},An=class extends Ct{constructor(t){super(),this.value=t}type="Literal"},Cz=class extends An{type="IntegerLiteral"},Pz=class extends An{type="FloatLiteral"},f2=class extends An{type="StringLiteral"},Nz=class extends An{type="ArrayLiteral"},d2=class extends An{type="TupleLiteral"},Lz=class extends An{type="ObjectLiteral"},En=class extends Ct{constructor(t,e,r){super(),this.operator=t,this.left=e,this.right=r}type="BinaryExpression"},zz=class extends Ct{constructor(t,e){super(),this.operand=t,this.filter=e}type="FilterExpression"},$z=class extends Wt{constructor(t,e){super(),this.filter=t,this.body=e}type="FilterStatement"},Rz=class extends Ct{constructor(t,e){super(),this.lhs=t,this.test=e}type="SelectExpression"},Bz=class extends Ct{constructor(t,e,r){super(),this.operand=t,this.negate=e,this.test=r}type="TestExpression"},m2=class extends Ct{constructor(t,e){super(),this.operator=t,this.argument=e}type="UnaryExpression"},Dz=class extends Ct{constructor(t=void 0,e=void 0,r=void 0){super(),this.start=t,this.stop=e,this.step=r}type="SliceExpression"},wd=class extends Ct{constructor(t,e){super(),this.key=t,this.value=e}type="KeywordArgumentExpression"},Uz=class extends Ct{constructor(t){super(),this.argument=t}type="SpreadExpression"},Fz=class extends Ct{constructor(t){super(),this.argument=t}type="KeywordSpreadExpression"},Gz=class extends Wt{constructor(t,e,r){super(),this.call=t,this.callerArgs=e,this.body=r}type="CallStatement"},jz=class extends Ct{constructor(t,e,r){super(),this.condition=t,this.trueExpr=e,this.falseExpr=r}type="Ternary"};function qz(t){let e=new vz([]),r=0;function s(L,z){let G=t[r++];if(!G||G.type!==L)throw new Error(`Parser Error: ${z}. ${G.type} !== ${L}.`);return G}function n(L){if(!l(L))throw new SyntaxError(`Expected ${L}`);++r}function o(){switch(t[r].type){case D.Comment:return new Oz(t[r++].value);case D.Text:return c();case D.OpenStatement:return u();case D.OpenExpression:return f();default:throw new SyntaxError(`Unexpected token type: ${t[r].type}`)}}function a(...L){return r+L.length<=t.length&&L.every((z,G)=>z===t[r+G].type)}function i(...L){return t[r]?.type===D.OpenStatement&&t[r+1]?.type===D.Identifier&&L.includes(t[r+1]?.value)}function l(...L){return r+L.length<=t.length&&L.every((z,G)=>t[r+G].type==="Identifier"&&z===t[r+G].value)}function c(){return new f2(s(D.Text,"Expected text token").value)}function u(){if(s(D.OpenStatement,"Expected opening statement token"),t[r].type!==D.Identifier)throw new SyntaxError(`Unknown statement, got ${t[r].type}`);let L=t[r].value,z;switch(L){case"set":++r,z=m();break;case"if":++r,z=_(),s(D.OpenStatement,"Expected {% token"),n("endif"),s(D.CloseStatement,"Expected %} token");break;case"macro":++r,z=w(),s(D.OpenStatement,"Expected {% token"),n("endmacro"),s(D.CloseStatement,"Expected %} token");break;case"for":++r,z=b(),s(D.OpenStatement,"Expected {% token"),n("endfor"),s(D.CloseStatement,"Expected %} token");break;case"call":{++r;let G=null;a(D.OpenParen)&&(G=F("parameters"));let ge=me();if(ge.type!=="Identifier")throw new SyntaxError("Expected identifier following call statement");let ie=F("call");s(D.CloseStatement,"Expected closing statement token");let ot=[];for(;!i("endcall");)ot.push(o());s(D.OpenStatement,"Expected '{%'"),n("endcall"),s(D.CloseStatement,"Expected closing statement token");let Fe=new p2(ge,ie);z=new Gz(Fe,G,ot);break}case"break":++r,s(D.CloseStatement,"Expected closing statement token"),z=new Az;break;case"continue":++r,s(D.CloseStatement,"Expected closing statement token"),z=new Tz;break;case"filter":{++r;let G=me();G instanceof Br&&a(D.OpenParen)&&(G=j(G)),s(D.CloseStatement,"Expected closing statement token");let ge=[];for(;!i("endfilter");)ge.push(o());s(D.OpenStatement,"Expected '{%'"),n("endfilter"),s(D.CloseStatement,"Expected '%}'"),z=new $z(G,ge);break}default:throw new SyntaxError(`Unknown statement type: ${L}`)}return z}function f(){s(D.OpenExpression,"Expected opening expression token");let L=A();return s(D.CloseExpression,"Expected closing expression token"),L}function m(){let L=x(),z=null,G=[];if(a(D.Equals))++r,z=x();else{for(s(D.CloseStatement,"Expected %} token");!i("endset");)G.push(o());s(D.OpenStatement,"Expected {% token"),n("endset")}return s(D.CloseStatement,"Expected closing statement token"),new Sz(L,z,G)}function _(){let L=A();s(D.CloseStatement,"Expected closing statement token");let z=[],G=[];for(;!i("elif","else","endif");)z.push(o());if(i("elif")){++r,++r;let ge=_();G.push(ge)}else if(i("else"))for(++r,++r,s(D.CloseStatement,"Expected closing statement token");!i("endif");)G.push(o());return new kz(L,z,G)}function w(){let L=me();if(L.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");let z=F("parameters");s(D.CloseStatement,"Expected closing statement token");let G=[];for(;!i("endmacro");)G.push(o());return new Mz(L,z,G)}function x(L=!1){let z=L?me:A,G=[z()],ge=a(D.Comma);for(;ge&&(++r,G.push(z()),!!a(D.Comma)););return ge?new d2(G):G[0]}function b(){let L=x(!0);if(!(L instanceof Br||L instanceof d2))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${L.type} instead`);if(!l("in"))throw new SyntaxError("Expected `in` keyword following loop variable");++r;let z=A();s(D.CloseStatement,"Expected closing statement token");let G=[];for(;!i("endfor","else");)G.push(o());let ge=[];if(i("else"))for(++r,++r,s(D.CloseStatement,"Expected closing statement token");!i("endfor");)ge.push(o());return new Ez(L,z,G,ge)}function A(){return k()}function k(){let L=M();if(l("if")){++r;let z=M();if(l("else")){++r;let G=k();return new jz(z,L,G)}else return new Rz(L,z)}return L}function M(){let L=S();for(;l("or");){let z=t[r];++r;let G=S();L=new En(z,L,G)}return L}function S(){let L=O();for(;l("and");){let z=t[r];++r;let G=O();L=new En(z,L,G)}return L}function O(){let L;for(;l("not");){let z=t[r];++r;let G=O();L=new m2(z,G)}return L??C()}function C(){let L=v();for(;;){let z;if(l("not","in"))z=new qt("not in",D.Identifier),r+=2;else if(l("in"))z=t[r++];else if(a(D.ComparisonBinaryOperator))z=t[r++];else break;let G=v();L=new En(z,L,G)}return L}function v(){let L=B();for(;a(D.AdditiveBinaryOperator);){let z=t[r];++r;let G=B();L=new En(z,L,G)}return L}function U(){let L=Q(me());return a(D.OpenParen)?j(L):L}function j(L){let z=new p2(L,F("call"));return z=Q(z),a(D.OpenParen)&&(z=j(z)),z}function F(L){s(D.OpenParen,"Expected opening parenthesis for arguments list");let z=K(L);return s(D.CloseParen,"Expected closing parenthesis for arguments list"),z}function K(L){let z=[],G=new Set,ge=!1,ie=!1;for(;!a(D.CloseParen);){let ot=a(D.ExponentiationBinaryOperator),Fe=a(D.MultiplicativeBinaryOperator)&&t[r].value==="*";if(L==="parameters"&&(ot||Fe))throw new SyntaxError("Argument unpacking is not allowed in parameter declarations");if(ot){if(++r,z.push(new Fz(A())),a(D.Comma)&&++r,!a(D.CloseParen))throw new SyntaxError("Expected closing parenthesis: `**` must be applied to the final argument");break}let Re;if(Fe){if(ie)throw new SyntaxError("Only one `*` argument unpacking is allowed");ie=!0,++r;let et=A();Re=new Uz(et)}else{if(Re=A(),a(D.Equals)){if(++r,!(Re instanceof Br))throw new SyntaxError(L==="parameters"?"Expected identifier for parameter declaration":"Expected identifier for keyword argument");let et=A();Re=new wd(Re,et)}if(L==="parameters"){if(!(Re instanceof Br||Re instanceof wd))throw new SyntaxError("Expected identifier for parameter declaration");let et=Re instanceof Br?Re.value:Re.key.value;if(G.has(et))throw new SyntaxError(`Duplicate parameter name: ${et}`);G.add(et)}if(Re instanceof wd)ge=!0;else{if(ge)throw new SyntaxError(L==="call"?"Positional arguments must come before keyword arguments":"Non-default argument follows default argument");if(ie)throw new SyntaxError("Positional arguments must not follow `*` argument unpacking")}}z.push(Re),a(D.Comma)&&++r}return z}function Y(){let L=[],z=!1;for(;!a(D.CloseSquareBracket);)a(D.Colon)?(L.push(void 0),++r,z=!0):(L.push(A()),a(D.Colon)&&(++r,z=!0));if(L.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(z){if(L.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new Dz(...L)}return L[0]}function Q(L){for(;a(D.Dot)||a(D.OpenSquareBracket);){let z=t[r];++r;let G,ge=z.type===D.OpenSquareBracket;if(ge)G=Y(),s(D.CloseSquareBracket,"Expected closing square bracket");else if(G=me(),G.type!=="Identifier"&&G.type!=="IntegerLiteral")throw new SyntaxError("Expected identifier or integer following dot operator");L=new Iz(L,G,ge)}return L}function B(){let L=I();for(;a(D.MultiplicativeBinaryOperator);){let z=t[r++],G=I();L=new En(z,L,G)}return L}function I(){let L=oe();for(;a(D.ExponentiationBinaryOperator);){let z=t[r++],G=oe();L=new En(z,L,G)}return L}function oe(){let L=J();for(;l("is");){++r;let z=l("not");z&&++r;let G=me();if(!(G instanceof Br))throw new SyntaxError("Expected identifier for the test");L=new Bz(L,z,G)}return L}function J(){let L=Z();for(;a(D.Pipe);){++r;let z=me();if(!(z instanceof Br))throw new SyntaxError("Expected identifier for the filter");a(D.OpenParen)&&(z=j(z)),L=new zz(L,z)}return L}function Z(){let L=t[r];if(L&&(L.type===D.UnaryOperator||L.type===D.AdditiveBinaryOperator)&&(L.value==="-"||L.value==="+")){let z=t[r++],G=Z();return new m2(z,G)}return U()}function me(){let L=t[r++];switch(L.type){case D.NumericLiteral:{let z=L.value;return z.includes(".")?new Pz(Number(z)):new Cz(Number(z))}case D.StringLiteral:{let z=L.value;for(;a(D.StringLiteral);)z+=t[r++].value;return new f2(z)}case D.Identifier:return new Br(L.value);case D.OpenParen:{let z=x();return s(D.CloseParen,"Expected closing parenthesis, got ${tokens[current].type} instead."),z}case D.OpenSquareBracket:{let z=[];for(;!a(D.CloseSquareBracket);)z.push(A()),a(D.Comma)&&++r;return++r,new Nz(z)}case D.OpenCurlyBracket:{let z=new Map;for(;!a(D.CloseCurlyBracket);){let G=A();s(D.Colon,"Expected colon between key and value in object literal");let ge=A();z.set(G,ge),a(D.Comma)&&++r}return++r,new Lz(z)}default:throw new SyntaxError(`Unexpected token: ${L.type}`)}}for(;r0)for(let n=t;ne;n+=r)s.push(n);return s}function _2(t,e,r,s=1){let n=Math.sign(s);n>=0?(e=(e??=0)<0?Math.max(t.length+e,0):Math.min(e,t.length),r=(r??=t.length)<0?Math.max(t.length+r,0):Math.min(r,t.length)):(e=(e??=t.length-1)<0?Math.max(t.length+e,-1):Math.min(e,t.length-1),r=(r??=-1)<-1?Math.max(t.length+r,-1):Math.min(r,t.length-1));let o=[];for(let a=e;n*ae.toUpperCase())}function Hz(t){return Xz(new Date,t)}function Xz(t,e){let r=new Intl.DateTimeFormat(void 0,{month:"long"}),s=new Intl.DateTimeFormat(void 0,{month:"short"}),n=o=>o<10?"0"+o:o.toString();return e.replace(/%[YmdbBHM%]/g,o=>{switch(o){case"%Y":return t.getFullYear().toString();case"%m":return n(t.getMonth()+1);case"%d":return n(t.getDate());case"%b":return s.format(t);case"%B":return r.format(t);case"%H":return n(t.getHours());case"%M":return n(t.getMinutes());case"%%":return"%";default:return o}})}function Kz(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Yz(t,e,r,s){if(s===0)return t;let n=s==null||s<0?1/0:s,o=e.length===0?new RegExp("(?=)","gu"):new RegExp(Kz(e),"gu");return t.replaceAll(o,a=>n>0?(--n,r):a)}var h2=class extends Error{},g2=class extends Error{},Qz=new Map,tr=class{type="RuntimeValue";value;get builtins(){return Qz}constructor(t=void 0){this.value=t}__bool__(){return new fe(!!this.value)}toString(){return String(this.value)}},de=class extends tr{type="IntegerValue"},De=class extends tr{type="FloatValue";toString(){return Object.is(this.value,-0)?"-0.0":this.value%1===0?this.value.toFixed(1):this.value.toString()}},re=class extends tr{type="StringValue";_builtins;get builtins(){return this._builtins??=new Map([["upper",new Ke(()=>new re(this.value.toUpperCase()))],["lower",new Ke(()=>new re(this.value.toLowerCase()))],["strip",new Ke(()=>new re(this.value.trim()))],["title",new Ke(()=>new re(Vz(this.value)))],["capitalize",new Ke(()=>new re(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],["length",new de(this.value.length)],["rstrip",new Ke(()=>new re(this.value.trimEnd()))],["lstrip",new Ke(()=>new re(this.value.trimStart()))],["startswith",new Ke(t=>{if(t.length===0)throw new Error("startswith() requires at least one argument");let e=t[0];if(e instanceof re)return new fe(this.value.startsWith(e.value));if(e instanceof ke){for(let r of e.value){if(!(r instanceof re))throw new Error("startswith() tuple elements must be strings");if(this.value.startsWith(r.value))return new fe(!0)}return new fe(!1)}throw new Error("startswith() argument must be a string or tuple of strings")})],["endswith",new Ke(t=>{if(t.length===0)throw new Error("endswith() requires at least one argument");let e=t[0];if(e instanceof re)return new fe(this.value.endsWith(e.value));if(e instanceof ke){for(let r of e.value){if(!(r instanceof re))throw new Error("endswith() tuple elements must be strings");if(this.value.endsWith(r.value))return new fe(!0)}return new fe(!1)}throw new Error("endswith() argument must be a string or tuple of strings")})],["split",new Ke(t=>{let e=t[0]??new Ye;if(!(e instanceof re||e instanceof Ye))throw new Error("sep argument must be a string or null");let r=t[1]??new de(-1);if(!(r instanceof de))throw new Error("maxsplit argument must be a number");let s=[];if(e instanceof Ye){let n=this.value.trimStart();for(let{0:o,index:a}of n.matchAll(/\S+/g)){if(r.value!==-1&&s.length>=r.value&&a!==void 0){s.push(o+n.slice(a+o.length));break}s.push(o)}}else{if(e.value==="")throw new Error("empty separator");s=this.value.split(e.value),r.value!==-1&&s.length>r.value&&s.push(s.splice(r.value).join(e.value))}return new ke(s.map(n=>new re(n)))})],["replace",new Ke(t=>{if(t.length<2)throw new Error("replace() requires at least two arguments");let e=t[0],r=t[1];if(!(e instanceof re&&r instanceof re))throw new Error("replace() arguments must be strings");let s;if(t.length>2?t[2].type==="KeywordArgumentsValue"?s=t[2].value.get("count")??new Ye:s=t[2]:s=new Ye,!(s instanceof de||s instanceof Ye))throw new Error("replace() count argument must be a number or null");return new re(Yz(this.value,e.value,r.value,s.value))})]])}},fe=class extends tr{type="BooleanValue"},Jz=/[\x7f-\uffff]/g;function w2(t){return t.replace(Jz,e=>"\\u"+e.charCodeAt(0).toString(16).padStart(4,"0"))}function Ur(t,e={},r=0,s=!0){let{indent:n=null,ensureAscii:o=!1,separators:a=null,sortKeys:i=!1}=e,l,c;switch(a?[l,c]=a:n?(l=",",c=": "):(l=", ",c=": "),t.type){case"NullValue":return"null";case"UndefinedValue":return s?"null":"undefined";case"IntegerValue":case"FloatValue":case"BooleanValue":return JSON.stringify(t.value);case"StringValue":{let u=JSON.stringify(t.value);return o&&(u=w2(u)),u}case"ArrayValue":case"NamespaceValue":case"ObjectValue":{let u=n?" ".repeat(n):"",f=` +`+u.repeat(r),m=f+u;if(t.type==="ArrayValue"){let _=t.value.map(w=>Ur(w,e,r+1,s));return n?`[${m}${_.join(`${l}${m}`)}${f}]`:`[${_.join(l)}]`}else{let _=Array.from(t.value.entries());i&&(_=_.sort(([x],[b])=>x.localeCompare(b)));let w=_.map(([x,b])=>{let A=JSON.stringify(x);o&&(A=w2(A));let k=`${A}${c}${Ur(b,e,r+1,s)}`;return n?`${m}${k}`:k});return n?`{${w.join(l)}${f}}`:`{${w.join(l)}}`}}default:throw new Error(`Cannot convert to JSON: ${t.type}`)}}var At=class extends tr{type="ObjectValue";_builtins;__bool__(){return new fe(this.value.size>0)}get builtins(){return this._builtins??=new Map([["get",new Ke(([t,e])=>{if(!(t instanceof re))throw new Error(`Object key must be a string: got ${t.type}`);return this.value.get(t.value)??e??new Ye})],["items",new Ke(()=>this.items())],["keys",new Ke(()=>this.keys())],["values",new Ke(()=>this.values())],["dictsort",new Ke(t=>{let e=new Map,r=t.filter(i=>i instanceof Ms?(e=i.value,!1):!0),s=r.at(0)??e.get("case_sensitive")??new fe(!1);if(!(s instanceof fe))throw new Error("case_sensitive must be a boolean");let n=r.at(1)??e.get("by")??new re("key");if(!(n instanceof re))throw new Error("by must be a string");if(!["key","value"].includes(n.value))throw new Error("by must be either 'key' or 'value'");let o=r.at(2)??e.get("reverse")??new fe(!1);if(!(o instanceof fe))throw new Error("reverse must be a boolean");let a=Array.from(this.value.entries()).map(([i,l])=>new ke([new re(i),l])).sort((i,l)=>{let c=n.value==="key"?0:1,u=i.value[c],f=l.value[c],m=xd(u,f,s.value);return o.value?-m:m});return new ke(a)})]])}items(){return new ke(Array.from(this.value.entries()).map(([t,e])=>new ke([new re(t),e])))}keys(){return new ke(Array.from(this.value.keys()).map(t=>new re(t)))}values(){return new ke(Array.from(this.value.values()))}toString(){return Ur(this,{},0,!1)}},Ms=class extends At{type="KeywordArgumentsValue"},bd=class extends tr{type="NamespaceValue";toString(){return Ur(this,{},0,!1)}},ke=class extends tr{type="ArrayValue";_builtins;get builtins(){return this._builtins??=new Map([["length",new de(this.value.length)]])}__bool__(){return new fe(this.value.length>0)}toString(){return Ur(this,{},0,!1)}},x2=class extends ke{type="TupleValue"},Ke=class extends tr{type="FunctionValue"},Ye=class extends tr{type="NullValue"},Xe=class extends tr{type="UndefinedValue"};function Zz(t){let e;if(t instanceof ke?e=t.value:t instanceof re&&(e=Array.from(t.value,n=>new re(n))),!e||e.length!==2)throw new Error("namespace expected an object or an iterable of [key, value] pairs");let[r,s]=e;if(!(r instanceof re))throw new Error("namespace keys must be strings");return[r,s]}var k2=class{constructor(t){this.parent=t}variables=new Map([["namespace",new Ke(t=>{let e=t.slice(),r;if(e.at(-1)instanceof Ms&&(r=e.pop()),e.length>1)throw new Error(`namespace expected at most 1 argument, got ${e.length}`);let s=new Map;if(e.length===1){let n=e[0];if(n instanceof At)for(let[o,a]of n.value)s.set(o,a);else if(n instanceof ke)for(let o of n.value){let[a,i]=Zz(o);s.set(a.value,i)}else throw new Error(`'${n.type}' object is not iterable`)}if(r)for(let[n,o]of r.value)s.set(n,o);return new bd(s)})]]);tests=k2.TESTS;set(t,e){return this.declareVariable(t,Dc(e))}declareVariable(t,e){if(this.variables.has(t))throw new SyntaxError(`Variable already declared: ${t}`);return this.variables.set(t,e),e}setVariable(t,e){return this.variables.set(t,e),e}resolve(t){if(this.variables.has(t))return this;if(this.parent)return this.parent.resolve(t);throw new Error(`Unknown variable: ${t}`)}lookupVariable(t){try{return this.resolve(t).variables.get(t)??new Xe}catch{return new Xe}}},Dr=k2;gz(Dr,"TESTS",new Map([["boolean",t=>t.type==="BooleanValue"],["callable",t=>t instanceof Ke],["odd",t=>{if(!(t instanceof de))throw new Error(`cannot odd on ${t.type}`);return t.value%2!==0}],["even",t=>{if(!(t instanceof de))throw new Error(`cannot even on ${t.type}`);return t.value%2===0}],["false",t=>t.type==="BooleanValue"&&!t.value],["true",t=>t.type==="BooleanValue"&&t.value],["none",t=>t.type==="NullValue"],["string",t=>t.type==="StringValue"],["number",t=>t instanceof de||t instanceof De],["integer",t=>t instanceof de],["iterable",t=>t.type==="ArrayValue"||t.type==="StringValue"],["mapping",t=>t instanceof At],["sequence",t=>t instanceof ke||t instanceof At||t instanceof re],["lower",t=>{let e=t.value;return t.type==="StringValue"&&e===e.toLowerCase()}],["upper",t=>{let e=t.value;return t.type==="StringValue"&&e===e.toUpperCase()}],["none",t=>t.type==="NullValue"],["defined",t=>t.type!=="UndefinedValue"],["undefined",t=>t.type==="UndefinedValue"],["equalto",(t,e)=>t.value===e.value],["eq",(t,e)=>t.value===e.value]]));function e$(t){t.set("false",!1),t.set("true",!0),t.set("none",null),t.set("raise_exception",e=>{throw new Error(e)}),t.set("range",Wz),t.set("strftime_now",Hz),t.set("True",!0),t.set("False",!1),t.set("None",null)}function Bc(t){return t instanceof At||t instanceof bd}function Uc(t){return t instanceof de||t instanceof De||t instanceof fe}function Fc(t){return t instanceof fe?Number(t.value):t.value}function y2(t,e){let r=e.split("."),s=t;for(let n of r)if(Bc(s))s=s.value.get(n)??new Xe;else if(s instanceof ke){let o=parseInt(n,10);if(!isNaN(o)&&o>=0&&on?1:0}if(t.type!==e.type)throw new Error(`Cannot compare different types: ${t.type} and ${e.type}`);if(t.type==="StringValue"){let s=t.value,n=e.value;return r||(s=s.toLowerCase(),n=n.toLowerCase()),sn?1:0}else throw new Error(`Cannot compare type: ${t.type}`)}function yd(t){if(t.type==="Identifier")return{name:t.value};let e=t;return{name:e.key.value,defaultValue:e.value}}function b2(t){return t==="kwargs"||t==="varargs"}function v2(t,e){let r=new Set,s=new Set,n=u=>{b2(u)&&r.add(u)},o=u=>{if(u.type==="Identifier")n(u.value);else if(u.type==="TupleLiteral")for(let f of u.value)o(f)},a=u=>{n(yd(u).name)},i=u=>{for(let f of u){let m=yd(f);m.defaultValue&&c(m.defaultValue)}},l=u=>{u.type==="CallExpression"&&c(u.args)},c=u=>{if(Array.isArray(u)){for(let f of u)c(f);return}if(u instanceof Map){for(let[f,m]of u)c(f),c(m);return}if(u instanceof Wt)switch(u.type){case"For":{let f=u;if(o(f.loopvar),f.iterable.type==="SelectExpression"){let m=f.iterable;c(m.lhs),c(f.body),c(f.defaultBlock),c(m.test);return}c(f.iterable),c(f.body),c(f.defaultBlock);return}case"Set":{let f=u;o(f.assignee),c(f.value),c(f.body);return}case"Macro":{let f=u;for(let m of f.args)a(m);i(f.args),c(f.body);return}case"CallStatement":{let f=u;c(f.call);for(let m of f.callerArgs??[])a(m);i(f.callerArgs??[]),c(f.body);return}case"FilterStatement":{let f=u;c(f.body),l(f.filter);return}case"Identifier":{let f=u.value;b2(f)&&!r.has(f)&&s.add(f);return}case"MemberExpression":{let f=u;c(f.object),f.computed&&c(f.property);return}case"FilterExpression":{let f=u;c(f.operand),l(f.filter);return}case"TestExpression":c(u.operand);return;case"SelectExpression":{let f=u;c(f.test),c(f.lhs);return}case"KeywordArgumentExpression":c(u.value);return;default:for(let f of Object.values(u))c(f)}};for(let u of t)a(u);return c(e),s}var t$=class{global;constructor(t){this.global=t??new Dr}run(t){return this.evaluate(t,this.global)}evaluateBinaryExpression(t,e){let r=this.evaluate(t.left,e);switch(t.operator.value){case"and":return r.__bool__().value?this.evaluate(t.right,e):r;case"or":return r.__bool__().value?r:this.evaluate(t.right,e)}let s=this.evaluate(t.right,e);switch(t.operator.value){case"==":return new fe(r.value==s.value);case"!=":return new fe(r.value!=s.value)}if(r instanceof Xe||s instanceof Xe){if(s instanceof Xe&&["in","not in"].includes(t.operator.value))return new fe(t.operator.value==="not in");throw new Error(`Cannot perform operation ${t.operator.value} on undefined values`)}else{if(r instanceof Ye||s instanceof Ye)throw new Error("Cannot perform operation on null values");if(t.operator.value==="~")return new re(r.value.toString()+s.value.toString());if(t.operator.value==="**"&&Uc(r)&&Uc(s)){let n=Fc(r),o=Fc(s);if(n===0&&o<0)throw new Error("0.0 cannot be raised to a negative power");let a=n**o;if(!Number.isFinite(a))throw new Error("Exponentiation result is not a finite real number");return r instanceof De||s instanceof De||o<0?new De(a):new de(a)}else if((r instanceof de||r instanceof De)&&(s instanceof de||s instanceof De)){let n=r.value,o=s.value;switch(t.operator.value){case"+":case"-":case"*":{let a=t.operator.value==="+"?n+o:t.operator.value==="-"?n-o:n*o;return r instanceof De||s instanceof De?new De(a):new de(a)}case"/":return new De(n/o);case"//":{let a=Math.floor(n/o);return r instanceof De||s instanceof De?new De(a):new de(a)}case"%":{let a=n%o;return r instanceof De||s instanceof De?new De(a):new de(a)}case"<":return new fe(n":return new fe(n>o);case">=":return new fe(n>=o);case"<=":return new fe(n<=o)}}else if(r instanceof ke&&s instanceof ke){if(t.operator.value==="+")return new ke(r.value.concat(s.value))}else if(s instanceof ke){let n=s.value.find(o=>o.value===r.value)!==void 0;switch(t.operator.value){case"in":return new fe(n);case"not in":return new fe(!n)}}}if((r instanceof re||s instanceof re)&&t.operator.value==="+")return new re(r.value.toString()+s.value.toString());if(r instanceof re&&s instanceof re)switch(t.operator.value){case"in":return new fe(s.value.includes(r.value));case"not in":return new fe(!s.value.includes(r.value))}if(r instanceof re&&s instanceof At)switch(t.operator.value){case"in":return new fe(s.value.has(r.value));case"not in":return new fe(!s.value.has(r.value))}throw new SyntaxError(`Unknown operator "${t.operator.value}" between ${r.type} and ${s.type}`)}evaluateArguments(t,e){let r=[],s=new Map,n=(o,a)=>{if(s.has(o))throw new Error(`Got multiple values for keyword argument '${o}'`);s.set(o,a)};for(let o of t)if(o.type==="SpreadExpression"){let a=o,i=this.evaluate(a.argument,e);if(!(i instanceof ke))throw new Error(`Cannot unpack non-iterable type: ${i.type}`);for(let l of i.value)r.push(l)}else o.type!=="KeywordArgumentExpression"&&o.type!=="KeywordSpreadExpression"&&r.push(this.evaluate(o,e));for(let o of t)if(o.type==="KeywordArgumentExpression"){let a=o;n(a.key.value,this.evaluate(a.value,e))}else if(o.type==="KeywordSpreadExpression"){let a=o,i=this.evaluate(a.argument,e);if(!(i instanceof At))throw new Error(`Argument after ** must be a mapping, not ${i.type}`);for(let[l,c]of i.value)n(l,c)}return[r,s]}applyFilter(t,e,r){if(e.type==="Identifier"){let s=e;if(s.value==="safe")return t;if(s.value==="tojson")return new re(Ur(t,{}));if(t instanceof ke)switch(s.value){case"list":return t;case"first":return t.value[0];case"last":return t.value[t.value.length-1];case"length":return new de(t.value.length);case"reverse":return new ke(t.value.slice().reverse());case"sort":return new ke(t.value.slice().sort((n,o)=>xd(n,o,!1)));case"join":return new re(t.value.map(n=>n.value).join(""));case"string":return new re(Ur(t,{},0,!1));case"unique":{let n=new Set,o=[];for(let a of t.value)n.has(a.value)||(n.add(a.value),o.push(a));return new ke(o)}default:throw new Error(`Unknown ArrayValue filter: ${s.value}`)}else if(t instanceof re)switch(s.value){case"length":case"upper":case"lower":case"title":case"capitalize":{let n=t.builtins.get(s.value);if(n instanceof Ke)return n.value([],r);if(n instanceof de)return n;throw new Error(`Unknown StringValue filter: ${s.value}`)}case"trim":return new re(t.value.trim());case"indent":return new re(t.value.split(` +`).map((n,o)=>o===0||n.length===0?n:" "+n).join(` +`));case"join":case"string":return t;case"int":{let n=parseInt(t.value,10);return new de(isNaN(n)?0:n)}case"float":{let n=parseFloat(t.value);return new De(isNaN(n)?0:n)}default:throw new Error(`Unknown StringValue filter: ${s.value}`)}else if(t instanceof de||t instanceof De)switch(s.value){case"abs":return t instanceof de?new de(Math.abs(t.value)):new De(Math.abs(t.value));case"int":return new de(Math.floor(t.value));case"float":return new De(t.value);case"string":return new re(t.toString());default:throw new Error(`Unknown NumericValue filter: ${s.value}`)}else if(t instanceof At)switch(s.value){case"items":return new ke(Array.from(t.value.entries()).map(([n,o])=>new ke([new re(n),o])));case"length":return new de(t.value.size);default:{let n=t.builtins.get(s.value);if(n)return n instanceof Ke?n.value([],r):n;throw new Error(`Unknown ObjectValue filter: ${s.value}`)}}else if(t instanceof fe)switch(s.value){case"bool":return new fe(t.value);case"int":return new de(t.value?1:0);case"float":return new De(t.value?1:0);case"string":return new re(t.value?"true":"false");default:throw new Error(`Unknown BooleanValue filter: ${s.value}`)}throw new Error(`Cannot apply filter "${s.value}" to type: ${t.type}`)}else if(e.type==="CallExpression"){let s=e;if(s.callee.type!=="Identifier")throw new Error(`Unknown filter: ${s.callee.type}`);let n=s.callee.value;if(n==="tojson"){let[,o]=this.evaluateArguments(s.args,r),a=o.get("indent")??new Ye;if(!(a instanceof de||a instanceof Ye))throw new Error("If set, indent must be a number");let i=o.get("ensure_ascii")??new fe(!1);if(!(i instanceof fe))throw new Error("If set, ensure_ascii must be a boolean");let l=o.get("sort_keys")??new fe(!1);if(!(l instanceof fe))throw new Error("If set, sort_keys must be a boolean");let c=o.get("separators")??new Ye,u=null;if(c instanceof ke||c instanceof x2){if(c.value.length!==2)throw new Error("separators must be a tuple of two strings");let[f,m]=c.value;if(!(f instanceof re)||!(m instanceof re))throw new Error("separators must be a tuple of two strings");u=[f.value,m.value]}else if(!(c instanceof Ye))throw new Error("If set, separators must be a tuple of two strings");return new re(Ur(t,{indent:a.value,ensureAscii:i.value,sortKeys:l.value,separators:u}))}else if(n==="join"){let o;if(t instanceof re)o=Array.from(t.value);else if(t instanceof ke)o=t.value.map(c=>c.value);else throw new Error(`Cannot apply filter "${n}" to type: ${t.type}`);let[a,i]=this.evaluateArguments(s.args,r),l=a.at(0)??i.get("separator")??new re("");if(!(l instanceof re))throw new Error("separator must be a string");return new re(o.join(l.value))}else if(n==="int"||n==="float"){let[o,a]=this.evaluateArguments(s.args,r),i=o.at(0)??a.get("default")??(n==="int"?new de(0):new De(0));if(t instanceof re){let l=n==="int"?parseInt(t.value,10):parseFloat(t.value);return isNaN(l)?i:n==="int"?new de(l):new De(l)}else{if(t instanceof de||t instanceof De)return t;if(t instanceof fe)return n==="int"?new de(t.value?1:0):new De(t.value?1:0);throw new Error(`Cannot apply filter "${n}" to type: ${t.type}`)}}else if(n==="default"){let[o,a]=this.evaluateArguments(s.args,r),i=o[0]??new re(""),l=o[1]??a.get("boolean")??new fe(!1);if(!(l instanceof fe))throw new Error("`default` filter flag must be a boolean");return t instanceof Xe||l.value&&!t.__bool__().value?i:t}if(t instanceof ke){switch(n){case"sort":{let[o,a]=this.evaluateArguments(s.args,r),i=o.at(0)??a.get("reverse")??new fe(!1);if(!(i instanceof fe))throw new Error("reverse must be a boolean");let l=o.at(1)??a.get("case_sensitive")??new fe(!1);if(!(l instanceof fe))throw new Error("case_sensitive must be a boolean");let c=o.at(2)??a.get("attribute")??new Ye;if(!(c instanceof re||c instanceof de||c instanceof Ye))throw new Error("attribute must be a string, integer, or null");let u=f=>{if(c instanceof Ye)return f;let m=c instanceof de?String(c.value):c.value;return y2(f,m)};return new ke(t.value.slice().sort((f,m)=>{let _=u(f),w=u(m),x=xd(_,w,l.value);return i.value?-x:x}))}case"selectattr":case"rejectattr":{let o=n==="selectattr";if(t.value.some(f=>!Bc(f)))throw new Error(`\`${n}\` can only be applied to array of objects`);if(s.args.some(f=>f.type!=="StringLiteral"))throw new Error(`arguments of \`${n}\` must be strings`);let[a,i,l]=s.args.map(f=>this.evaluate(f,r)),c;if(i){let f=r.tests.get(i.value);if(!f)throw new Error(`Unknown test: ${i.value}`);c=f}else c=(...f)=>f[0].__bool__().value;let u=t.value.filter(f=>{let m=f.value.get(a.value),_=m?c(m,l):!1;return o?_:!_});return new ke(u)}case"map":{let[,o]=this.evaluateArguments(s.args,r);if(o.has("attribute")){let a=o.get("attribute");if(!(a instanceof re))throw new Error("attribute must be a string");let i=o.get("default"),l=t.value.map(c=>{if(!Bc(c))throw new Error("items in map must be an object");let u=y2(c,a.value);return u instanceof Xe?i??new Xe:u});return new ke(l)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${n}`)}else if(t instanceof re){switch(n){case"indent":{let[o,a]=this.evaluateArguments(s.args,r),i=o.at(0)??a.get("width")??new de(4);if(!(i instanceof de))throw new Error("width must be a number");let l=o.at(1)??a.get("first")??new fe(!1),c=o.at(2)??a.get("blank")??new fe(!1),u=t.value.split(` +`),f=" ".repeat(i.value),m=u.map((_,w)=>!l.value&&w===0||!c.value&&_.length===0?_:f+_);return new re(m.join(` +`))}case"replace":{let o=t.builtins.get("replace");if(!(o instanceof Ke))throw new Error("replace filter not available");let[a,i]=this.evaluateArguments(s.args,r);return o.value([...a,new Ms(i)],r)}}throw new Error(`Unknown StringValue filter: ${n}`)}else if(t instanceof At){let o=t.builtins.get(n);if(o&&o instanceof Ke){let[a,i]=this.evaluateArguments(s.args,r);return i.size>0&&a.push(new Ms(i)),o.value(a,r)}throw new Error(`Unknown ObjectValue filter: ${n}`)}else throw new Error(`Cannot apply filter "${n}" to type: ${t.type}`)}throw new Error(`Unknown filter: ${e.type}`)}evaluateFilterExpression(t,e){let r=this.evaluate(t.operand,e);return this.applyFilter(r,t.filter,e)}evaluateTestExpression(t,e){let r=this.evaluate(t.operand,e),s=e.tests.get(t.test.value);if(!s)throw new Error(`Unknown test: ${t.test.value}`);let n=s(r);return new fe(t.negate?!n:n)}evaluateSelectExpression(t,e){return this.evaluate(t.test,e).__bool__().value?this.evaluate(t.lhs,e):new Xe}evaluateUnaryExpression(t,e){let r=this.evaluate(t.argument,e);switch(t.operator.value){case"not":return new fe(!r.value);case"+":case"-":{let s=t.operator.value==="-"?-1:1;if(r instanceof de||r instanceof De||r instanceof fe){let n=r instanceof fe?r.value?1:0:r.value,o=s*n;return r instanceof De?new De(o):new de(o)}throw new SyntaxError(`Unknown operator "${t.operator.value}" for ${r.type}`)}default:throw new SyntaxError(`Unknown operator: ${t.operator.value}`)}}evaluateTernaryExpression(t,e){return this.evaluate(t.condition,e).__bool__().value?this.evaluate(t.trueExpr,e):this.evaluate(t.falseExpr,e)}evalProgram(t,e){return this.evaluateBlock(t.body,e)}evaluateBlock(t,e){let r="";for(let s of t){let n=this.evaluate(s,e);n.type!=="NullValue"&&n.type!=="UndefinedValue"&&(r+=n.toString())}return new re(r)}evaluateIdentifier(t,e){return e.lookupVariable(t.value)}evaluateCallExpression(t,e){let[r,s]=this.evaluateArguments(t.args,e);s.size>0&&r.push(new Ms(s));let n=this.evaluate(t.callee,e);if(n.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${n.type}`);return n.value(r,e)}evaluateSliceExpression(t,e,r){if(!(t instanceof ke||t instanceof re))throw new Error("Slice object must be an array or string");let s=this.evaluate(e.start,r),n=this.evaluate(e.stop,r),o=this.evaluate(e.step,r);if(!(s instanceof de||s instanceof Xe))throw new Error("Slice start must be numeric or undefined");if(!(n instanceof de||n instanceof Xe))throw new Error("Slice stop must be numeric or undefined");if(!(o instanceof de||o instanceof Xe))throw new Error("Slice step must be numeric or undefined");return t instanceof ke?new ke(_2(t.value,s.value,n.value,o.value)):new re(_2(Array.from(t.value),s.value,n.value,o.value).join(""))}evaluateMemberExpression(t,e){let r=this.evaluate(t.object,e),s;if(t.computed){if(t.property.type==="SliceExpression")return this.evaluateSliceExpression(r,t.property,e);s=this.evaluate(t.property,e)}else t.property.type==="IntegerLiteral"?s=new de(t.property.value):s=new re(t.property.value);let n;if(Bc(r)){if(!(s instanceof re))throw new Error(`Cannot access property with non-string: got ${s.type}`);n=r.value.get(s.value)??(r instanceof At?r.builtins.get(s.value):void 0)}else if(r instanceof ke||r instanceof re)if(s instanceof de)n=r.value.at(s.value),r instanceof re&&(n=new re(r.value.at(s.value)));else if(s instanceof re)n=r.builtins.get(s.value);else throw new Error(`Cannot access property with non-string/non-number: got ${s.type}`);else{if(!(s instanceof re))throw new Error(`Cannot access property with non-string: got ${s.type}`);n=r.builtins.get(s.value)}return n instanceof tr?n:new Xe}evaluateSet(t,e){let r=t.value?this.evaluate(t.value,e):this.evaluateBlock(t.body,e);if(t.assignee.type==="Identifier"){let s=t.assignee.value;e.setVariable(s,r)}else if(t.assignee.type==="TupleLiteral"){let s=t.assignee;if(!(r instanceof ke))throw new Error(`Cannot unpack non-iterable type in set: ${r.type}`);let n=r.value;if(n.length!==s.value.length)throw new Error(`Too ${s.value.length>n.length?"few":"many"} items to unpack in set`);for(let o=0;o_.setVariable(t.loopvar.value,f);else if(t.loopvar.type==="TupleLiteral"){let _=t.loopvar;if(f.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${f.type}`);let w=f;if(_.value.length!==w.value.length)throw new Error(`Too ${_.value.length>w.value.length?"few":"many"} items to unpack`);m=x=>{for(let b=0;b<_.value.length;++b){if(_.value[b].type!=="Identifier")throw new Error(`Cannot unpack non-identifier type: ${_.value[b].type}`);x.setVariable(_.value[b].value,w.value[b])}}}else throw new Error(`Invalid loop variable(s): ${t.loopvar.type}`);s&&(m(u),!this.evaluate(s,u).__bool__().value)||(o.push(f),a.push(m))}let i="",l=!0;for(let c=0;c0?o[c-1]:new Xe],["nextitem",c0)throw new Error(`macro ${t} takes no keyword argument '${a.keys().next().value}'`);if(r.has("varargs"))n.setVariable("varargs",new ke(o.slice(e.length)));else if(o.length>e.length)throw new Error(`macro ${t} takes not more than ${e.length} argument(s)`);for(let[l,c]of i)n.setVariable(l,this.evaluate(c,n))}evaluateMacro(t,e){let r=v2(t.args,t.body);return e.setVariable(t.name.value,new Ke((s,n)=>{let o=new Dr(n);return this.bindMacroArguments(`'${t.name.value}'`,t.args,r,s,o),this.evaluateBlock(t.body,o)})),new Ye}evaluateCallStatement(t,e){let r=t.callerArgs??[],s=v2(r,t.body),n=new Ke(c=>{let u=new Dr(e);return this.bindMacroArguments("None",r,s,c,u),this.evaluateBlock(t.body,u)}),[o,a]=this.evaluateArguments(t.call.args,e);o.push(new Ms(a));let i=this.evaluate(t.call.callee,e);if(i.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${i.type}`);let l=new Dr(e);return l.setVariable("caller",n),i.value(o,l)}evaluateFilterStatement(t,e){let r=this.evaluateBlock(t.body,e);return this.applyFilter(r,t.filter,e)}evaluate(t,e){if(!t)return new Xe;switch(t.type){case"Program":return this.evalProgram(t,e);case"Set":return this.evaluateSet(t,e);case"If":return this.evaluateIf(t,e);case"For":return this.evaluateFor(t,e);case"Macro":return this.evaluateMacro(t,e);case"CallStatement":return this.evaluateCallStatement(t,e);case"Break":throw new h2;case"Continue":throw new g2;case"IntegerLiteral":return new de(t.value);case"FloatLiteral":return new De(t.value);case"StringLiteral":return new re(t.value);case"ArrayLiteral":return new ke(t.value.map(r=>this.evaluate(r,e)));case"TupleLiteral":return new x2(t.value.map(r=>this.evaluate(r,e)));case"ObjectLiteral":{let r=new Map;for(let[s,n]of t.value){let o=this.evaluate(s,e);if(!(o instanceof re))throw new Error(`Object keys must be strings: got ${o.type}`);r.set(o.value,this.evaluate(n,e))}return new At(r)}case"Identifier":return this.evaluateIdentifier(t,e);case"CallExpression":return this.evaluateCallExpression(t,e);case"MemberExpression":return this.evaluateMemberExpression(t,e);case"UnaryExpression":return this.evaluateUnaryExpression(t,e);case"BinaryExpression":return this.evaluateBinaryExpression(t,e);case"FilterExpression":return this.evaluateFilterExpression(t,e);case"FilterStatement":return this.evaluateFilterStatement(t,e);case"TestExpression":return this.evaluateTestExpression(t,e);case"SelectExpression":return this.evaluateSelectExpression(t,e);case"Ternary":return this.evaluateTernaryExpression(t,e);case"Comment":return new Ye;default:throw new SyntaxError(`Unknown node type: ${t.type}`)}}};function Dc(t){switch(typeof t){case"number":return Number.isInteger(t)?new de(t):new De(t);case"string":return new re(t);case"boolean":return new fe(t);case"undefined":return new Xe;case"object":return t===null?new Ye:Array.isArray(t)?new ke(t.map(Dc)):new At(new Map(Object.entries(t).map(([e,r])=>[e,Dc(r)])));case"function":return new Ke((e,r)=>{let s=t(...e.map(n=>n.value))??null;return Dc(s)});default:throw new Error(`Cannot convert to runtime value: ${t}`)}}var pt=` +`,r$="{%- ",s$=" -%}",tt=Object.freeze({CONDITIONAL:0,LOGICAL_OR:1,LOGICAL_AND:2,LOGICAL_NOT:3,COMPARISON:4,ADDITIVE:5,MULTIPLICATIVE:6,EXPONENTIATION:7,TEST:8,FILTER:9,UNARY_SIGN:10,ATOM:11});function E2(t){switch(t.operator.type){case"ExponentiationBinaryOperator":return tt.EXPONENTIATION;case"MultiplicativeBinaryOperator":return tt.MULTIPLICATIVE;case"AdditiveBinaryOperator":return tt.ADDITIVE;case"ComparisonBinaryOperator":return tt.COMPARISON;case"Identifier":return t.operator.value==="and"?tt.LOGICAL_AND:t.operator.value==="in"||t.operator.value==="not in"?tt.COMPARISON:tt.LOGICAL_OR}return tt.LOGICAL_OR}function A2(t){switch(t.type){case"SelectExpression":case"Ternary":return tt.CONDITIONAL;case"BinaryExpression":return E2(t);case"UnaryExpression":return t.operator.value==="not"?tt.LOGICAL_NOT:tt.UNARY_SIGN;case"TestExpression":return tt.TEST;case"FilterExpression":return tt.FILTER;default:return tt.ATOM}}function Zt(t,e){let r=Qe(t);return A2(t)o$(s,e,r)).join(pt)}function Gc(t){return t.map(e=>Qe(e)).join(", ")}function o$(t,e,r){let s=r.repeat(e);switch(t.type){case"Program":return er(t.body,e,r);case"If":return a$(t,e,r);case"For":return i$(t,e,r);case"Set":return l$(t,e,r);case"Macro":return c$(t,e,r);case"Break":return s+bt("break");case"Continue":return s+bt("continue");case"CallStatement":return u$(t,e,r);case"FilterStatement":return p$(t,e,r);case"Comment":return s+"{# "+t.value+" #}";default:return s+"{{- "+Qe(t)+" -}}"}}function a$(t,e,r){let s=r.repeat(e),n=[],o=t;for(;o&&(n.push({test:o.test,body:o.body}),o.alternate.length===1&&o.alternate[0].type==="If");)o=o.alternate[0];let a=s+bt("if",Qe(n[0].test))+pt+er(n[0].body,e+1,r);for(let i=1;i0&&(a+=pt+s+bt("else")+pt+er(o.alternate,e+1,r)),a+=pt+s+bt("endif"),a}function i$(t,e,r){let s=r.repeat(e),n="";if(t.iterable.type==="SelectExpression"){let a=t.iterable;n=`${Qe(a.lhs)} if ${Qe(a.test)}`}else n=Qe(t.iterable);let o=s+bt("for",Qe(t.loopvar),"in",n)+pt+er(t.body,e+1,r);return t.defaultBlock.length>0&&(o+=pt+s+bt("else")+pt+er(t.defaultBlock,e+1,r)),o+=pt+s+bt("endfor"),o}function l$(t,e,r){let s=r.repeat(e),n=Qe(t.assignee),o=t.value?Qe(t.value):"",a=s+bt("set",`${n}${t.value?" = "+o:""}`);return t.body.length===0?a:a+pt+er(t.body,e+1,r)+pt+s+bt("endset")}function c$(t,e,r){let s=r.repeat(e),n=Gc(t.args);return s+bt("macro",`${t.name.value}(${n})`)+pt+er(t.body,e+1,r)+pt+s+bt("endmacro")}function u$(t,e,r){let s=r.repeat(e),n=t.callerArgs&&t.callerArgs.length>0?`(${Gc(t.callerArgs)})`:"",o=Qe(t.call),a=s+bt(`call${n}`,o)+pt;return a+=er(t.body,e+1,r)+pt,a+=s+bt("endcall"),a}function p$(t,e,r){let s=r.repeat(e),n=t.filter.type==="Identifier"?t.filter.value:Qe(t.filter),o=s+bt("filter",n)+pt;return o+=er(t.body,e+1,r)+pt,o+=s+bt("endfilter"),o}function Qe(t){switch(t.type){case"SpreadExpression":return`*${Qe(t.argument)}`;case"KeywordSpreadExpression":return`**${Qe(t.argument)}`;case"Identifier":return t.value;case"IntegerLiteral":return`${t.value}`;case"FloatLiteral":{let e=t.value;return Object.is(e,-0)?"-0.0":e%1===0?e.toFixed(1):e.toString()}case"StringLiteral":return JSON.stringify(t.value);case"BinaryExpression":{let e=t,r=E2(e),s=Zt(e.left,r),n=Zt(e.right,r+1);return`${s} ${e.operator.value} ${n}`}case"UnaryExpression":{let e=t,r=e.argument.type==="UnaryExpression"?A2(e):tt.ATOM;return e.operator.value+(e.operator.value==="not"?" ":"")+Zt(e.argument,r)}case"CallExpression":{let e=t,r=Gc(e.args);return`${Qe(e.callee)}(${r})`}case"MemberExpression":{let e=t,r=Zt(e.object,tt.ATOM),s=Qe(e.property);return!e.computed&&e.property.type!=="Identifier"&&e.property.type!=="IntegerLiteral"&&(s=`(${s})`),e.computed?`${r}[${s}]`:`${r}.${s}`}case"FilterExpression":{let e=t,r=Zt(e.operand,tt.FILTER);return e.filter.type==="CallExpression"?`${r} | ${Qe(e.filter)}`:`${r} | ${e.filter.value}`}case"SelectExpression":{let e=t;return`${Zt(e.lhs,tt.LOGICAL_OR)} if ${Zt(e.test,tt.LOGICAL_OR)}`}case"TestExpression":{let e=t;return`${Zt(e.operand,tt.TEST)} is${e.negate?" not":""} ${e.test.value}`}case"ArrayLiteral":case"TupleLiteral":{let e=Gc(t.value),r=t.type==="ArrayLiteral"?"[]":"()";return`${r[0]}${e}${r[1]}`}case"ObjectLiteral":return`{${Array.from(t.value.entries()).map(([r,s])=>`${Qe(r)}: ${Qe(s)}`).join(", ")}}`;case"SliceExpression":{let e=t,r=e.start?Qe(e.start):"",s=e.stop?Qe(e.stop):"",n=e.step?`:${Qe(e.step)}`:"";return`${r}:${s}${n}`}case"KeywordArgumentExpression":{let e=t;return`${e.key.value}=${Qe(e.value)}`}case"Ternary":{let e=t;return`${Zt(e.trueExpr,tt.LOGICAL_OR)} if ${Zt(e.condition,tt.LOGICAL_OR)} else ${Zt(e.falseExpr,tt.CONDITIONAL)}`}default:throw new Error(`Unknown expression type: ${t.type}`)}}var T2=class{parsed;constructor(t){let e=bz(t,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=qz(e)}render(t){let e=new Dr;if(e$(e),t)for(let[n,o]of Object.entries(t))e.set(n,o);return new t$(e).run(this.parsed).value}format(t){return n$(this.parsed,t?.indent||" ")}};var f$={txt:"text/plain",html:"text/html",css:"text/css",js:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif"},Fr=class t{constructor(e){if(this.filePath=e,this.headers=new Headers,this.exists=xt.existsSync(e),this.exists){this.status=200,this.statusText="OK";let r=xt.statSync(e);this.headers.set("content-length",r.size.toString()),this.updateContentType();let s=xt.createReadStream(e);this.body=new ReadableStream({start(n){s.on("data",o=>n.enqueue(o)),s.on("end",()=>n.close()),s.on("error",o=>n.error(o))},cancel(){s.destroy()}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){let e=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",f$[e]??"application/octet-stream")}clone(){let e=new t(this.filePath);return e.exists=this.exists,e.status=this.status,e.statusText=this.statusText,e.headers=new Headers(this.headers),e}async arrayBuffer(){return(await xt.promises.readFile(this.filePath)).buffer}async blob(){let e=await xt.promises.readFile(this.filePath);return new Blob([e],{type:this.headers.get("content-type")})}async text(){return await xt.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}};var Gr=class{constructor(e){this._mt=new Uint32Array(624),this._idx=625,this._gauss_next=null,this._random_fn=this.random.bind(this),this.seed(e)}seed(e){if(e==null)if(le.IS_CRYPTO_AVAILABLE){let i=new Uint32Array(1);crypto.getRandomValues(i),e=i[0]}else e=Date.now()>>>0;Number.isSafeInteger(e)&&(e=Math.abs(e));let r=this._mt,s=(i,l)=>Math.imul(i,l)>>>0,n=[];for(let i=e||0;i>0;i=Math.floor(i/4294967296))n.push(i&4294967295);n.length||n.push(0),r[0]=19650218;for(let i=1;i<624;++i)r[i]=s(1812433253,r[i-1]^r[i-1]>>>30)+i>>>0;let o=1,a=0;for(let i=Math.max(624,n.length);i>0;--i,++o,++a)o>=624&&(r[0]=r[623],o=1),a>=n.length&&(a=0),r[o]=(r[o]^s(r[o-1]^r[o-1]>>>30,1664525))+n[a]+a>>>0;for(let i=623;i>0;--i,++o)o>=624&&(r[0]=r[623],o=1),r[o]=(r[o]^s(r[o-1]^r[o-1]>>>30,1566083941))-o>>>0;r[0]=2147483648,this._idx=624,this._gauss_next=null}_int32(){let e=this._mt;if(this._idx>=624){for(let s=0;s<624;++s){let n=e[s]&2147483648|e[(s+1)%624]&2147483647;e[s]=(e[(s+397)%624]^n>>>1^(n&1?2567483615:0))>>>0}this._idx=0}let r=e[this._idx++];return r^=r>>>11,r^=r<<7&2636928640,r^=r<<15&4022730752,r^=r>>>18,r>>>0}random(){return((this._int32()>>>5)*67108864+(this._int32()>>>6))/9007199254740992}gauss(e=0,r=1){let s=this._gauss_next;if(this._gauss_next=null,s===null){let n=this.random()*2*Math.PI,o=Math.sqrt(-2*Math.log(1-this.random()));s=Math.cos(n)*o,this._gauss_next=Math.sin(n)*o}return e+s*r}shuffle(e){for(let r=e.length-1;r>0;--r){let s=32-Math.clz32(r+1),n=this._int32()>>>32-s;for(;n>r;)n=this._int32()>>>32-s;let o=e[r];e[r]=e[n],e[n]=o}}choices(e,r){return e[S2(this._random_fn,r)]}};function S2(t,e){let r=0;for(let n=0;nS2(Os.random,t);var d$=new Gr,Tn=class{constructor(e){this.path=e}async match(e){let r=Gt.join(this.path,e),s=new Fr(r);if(s.exists)return s}async put(e,r,s=void 0){let n=Gt.join(this.path,e),o=le.IS_PROCESS_AVAILABLE?process.pid:Date.now(),a=d$._int32().toString(36),i=n+`.tmp.${o}.${a}`;try{let l=r.headers.get("Content-Length"),c=parseInt(l??"0"),u=0;await xt.promises.mkdir(Gt.dirname(n),{recursive:!0});let f=xt.createWriteStream(i),m=r.body.getReader();for(;;){let{done:_,value:w}=await m.read();if(_)break;await new Promise((b,A)=>{f.write(w,k=>{if(k){A(k);return}b()})}),u+=w.length;let x=c?u/c*100:0;s?.({progress:x,loaded:u,total:c})}await new Promise((_,w)=>{f.close(x=>x?w(x):_())}),await xt.promises.rename(i,n)}catch(l){try{await xt.promises.unlink(i)}catch{}throw l}}async delete(e){let r=Gt.join(this.path,e);try{return await xt.promises.unlink(r),!0}catch{return!1}}};var O2={400:"Bad request error occurred while trying to load file",401:"Unauthorized access to file",403:"Forbidden access to file",404:"Could not locate file",408:"Request timeout error occurred while trying to load file",500:"Internal server error error occurred while trying to load file",502:"Bad gateway error occurred while trying to load file",503:"Service unavailable error occurred while trying to load file",504:"Gateway timeout error occurred while trying to load file"},jc=100,I2=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function Po(...t){return t=t.map((e,r)=>(r&&(e=e.replace(new RegExp("^/"),"")),r!==t.length-1&&(e=e.replace(new RegExp("/$"),"")),e)),t.join("/")}function Sr(t,e=null,r=null){let s;try{s=new URL(t)}catch{return!1}return!(e&&!e.includes(s.protocol)||r&&!r.includes(s.hostname))}function C2(t){return!(!I2.test(t)||t.includes("..")||t.includes("--")||t.endsWith(".git")||t.endsWith(".ipynb"))}function Sn(t,e={},...r){return JSON.stringify([t,e.revision??"main",e.cache_dir??null,e.local_files_only??!1,...r])}var Is=class extends Error{constructor(e,{status:r=null}={}){super(e),this.name="ModelFileNotFoundError",this.status=r}},m$=new Set([401,403,404]);function qc(t,e,r){if(!r)return null;let n=`${O2[t]??`Error (${t}) occurred while trying to load file`}: "${e}".`;throw m$.has(t)?new Is(n,{status:t}):Error(n)}async function P2(t,e,r){let s=t.headers.get("Content-Length"),n=s?parseInt(s,10):r??0;s===null&&!r&&te.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let o=new Uint8Array(n),a=0,i=t.body.getReader();async function l(){let{done:c,value:u}=await i.read();if(c)return;let f=a+u.length;if(f>n){n=f;let _=new Uint8Array(n);_.set(o),o=_}o.set(u,a),a=f;let m=a/n*100;return e({progress:m,loaded:a,total:n}),l()}return await l(),o}function vd(t){return Sr(t,["blob:"])}function No(t,{allowUnresolved:e=!1}={}){let r;if(typeof location<"u"&&location.href)r=location.href;else if(typeof import.meta<"u"&&import.meta.url)r=import.meta.url;else return t;try{return new URL(t,r).href}catch(s){if(!e)throw s;return t}}var L2="SHA-256",_$="experimental_transformers-hash-cache",N2=t=>({algorithm:L2,value:t}),Lo=class{#t=null;_getHashCache=()=>(this.#t??=caches.open(_$),this.#t);static isAvailable=()=>typeof navigator<"u"&&"crossOriginStorage"in navigator;match=async e=>{let r=await this._getFileHash(e);if(r)try{let n=await(await navigator.crossOriginStorage.requestFileHandle(N2(r))).getFile();return new Response(n,{headers:{"Content-Length":String(n.size)}})}catch{return}};put=async(e,r)=>{let s=await this._getFileHash(e);if(s){let n=await r.blob();await this._storeBlobInCOS(n,s)}else this._processAndStore(e,r.body)};_storeBlobInCOS=async(e,r)=>{let n=await(await navigator.crossOriginStorage.requestFileHandle(N2(r),{create:!0,origins:"*"})).createWritable();await n.write(e),await n.close()};_processAndStore=async(e,r)=>{try{let s=[];for await(let a of r)s.push(a);let n=new Blob(s),o=await this._getBlobHash(n);await this._storeBlobInCOS(n,o);try{await(await this._getHashCache()).put(e,new Response(o))}catch{}}catch{}};delete=async e=>{try{return await(await this._getHashCache()).delete(e)}catch{return!1}};_getFileHash=async e=>{try{let r=await this._getHashCache(),s=await r.match(e);if(s)return s.text();let n=await this._getLfsFileHash(e);return n?(await r.put(e,new Response(n)),n):null}catch{return null}};_getLfsFileHash=async e=>{if(!e.includes("/resolve/"))return null;let r=e.replace("/resolve/","/raw/");try{let n=(await fetch(r).then(o=>o.text())).match(/^oid sha256:([0-9a-f]+)$/m);return n?n[1]:null}catch{return null}};_getBlobHash=async e=>{let r=await e.arrayBuffer(),s=await crypto.subtle.digest(L2,r);return Array.from(new Uint8Array(s)).map(o=>o.toString(16).padStart(2,"0")).join("")}};async function rr(t=null){let e=null;if(he.useCustomCache){if(!he.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!he.customCache.match||!he.customCache.put)throw new Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");e=he.customCache}if(!e&&he.experimental_useCrossOriginStorage&&Lo.isAvailable()&&(e=new Lo),!e&&he.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{e=await caches.open(he.cacheKey)}catch(r){te.warn("An error occurred while opening the browser cache:",r)}}if(!e&&he.useFSCache){if(!le.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");e=new Tn(t??he.cacheDir)}return e}async function z2(t,...e){for(let r of e)try{let s=await t.match(r);if(s)return s}catch{continue}}var Wc=class{#t;#e;constructor(e){this.#t=e,this.#e=new Map}get(e){if(!this.#e.has(e))return;let r=this.#e.get(e);return this.#e.delete(e),this.#e.set(e,r),r}put(e,r){this.#e.has(e)&&this.#e.delete(e),this.#e.set(e,r),this.#e.size>this.#t&&this.#e.delete(this.#e.keys().next().value)}delete(e){return this.#e.delete(e)}clear(){this.#e.clear()}};var h$=100,kd=new Wc(h$);function Vc(t,e){let r=kd.get(t);if(r!==void 0)return r;let s=e().then(n=>n,n=>(kd.delete(t),Promise.reject(n)));return kd.put(t,s),s}async function g$(t){if(!Sr(t,["http:","https:"]))return null;let e=Ed(t);return e.set("Range","bytes=0-0"),he.fetch(t,{method:"GET",headers:e,cache:"no-store"})}function Pt(t,e,r={}){let s=Sn(t,r,e);return Vc(s,()=>w$(t,e,r))}async function w$(t,e,r){let s=await rr(r?.cache_dir),{localPath:n,remoteURL:o,proposedCacheKey:a,validModelId:i}=qr(t,e,r,s),l=await Wr(s,n,a);if(l!==void 0&&typeof l!="string"){let c=l.headers.get("content-length"),u=l.headers.get("content-type");return{exists:!0,size:c?parseInt(c,10):void 0,contentType:u||void 0,fromCache:!0}}if(he.allowLocalModels&&!Sr(n,["http:","https:"]))try{let u=await jr(n);if(typeof u!="string"&&u.status!==404){let f=u.headers.get("content-length"),m=u.headers.get("content-type");return{exists:!0,size:f?parseInt(f,10):void 0,contentType:m||void 0,fromCache:!1}}}catch{}if(he.allowRemoteModels&&!r.local_files_only&&i){let c=await g$(o);if(c&&c.status>=200&&c.status<300){let u,f=c.headers.get("content-type");if(c.status===206){let m=c.headers.get("content-range");if(m){let _=m.match(/bytes \d+-\d+\/(\d+)/);_&&(u=parseInt(_[1],10))}}else if(c.status===200)try{await c.body?.cancel()}catch{}if(u===void 0){let m=c.headers.get("content-length");u=m?parseInt(m,10):void 0}return{exists:!0,size:u,contentType:f||void 0,fromCache:!1}}c&&c.status!==404&&c.status!==416&&qc(c.status,o,!0)}return{exists:!1,fromCache:!1}}async function jr(t){return he.useFS&&!Sr(t,["http:","https:","blob:"])?new Fr(t instanceof URL?t.protocol==="file:"?t.pathname:t.toString():t):he.fetch(t,{headers:Ed(t)})}function Ed(t){let e=typeof process<"u"&&process?.release?.name==="node",r=new Headers;if(e){let s=!!process.env?.TESTING_REMOTELY,n=he.version;if(r.set("User-Agent",`transformers.js/${n}; is_ci/${s};`),Sr(t,["http:","https:"],["huggingface.co","hf.co"])){let a=process.env?.HF_TOKEN??process.env?.HF_ACCESS_TOKEN;a&&r.set("Authorization",`Bearer ${a}`)}}return r}function qr(t,e,r={},s=null){let n=r.revision??"main",o=Po(t,e),a=C2(t),i=a?Po(he.localModelPath,o):o,l=Po(he.remoteHost,he.remotePathTemplate.replaceAll("{model}",t).replaceAll("{revision}",encodeURIComponent(n)),e),c=s instanceof Tn?n==="main"?o:Po(t,n,e):l;return{requestURL:o,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:a}}async function Wr(t,e,r){if(t)return await z2(t,e,r)}async function x$(t,e,r,s,n,o,a={}){if(await r.match(s)===void 0&&!(typeof Cache<"u"&&r instanceof Cache&&!Sr(No(s,{allowUnresolved:!0}),["http:","https:"])))if(o){if(typeof n!="string"){let i=new Headers(n.headers);i.set("content-length",o.byteLength.toString()),await r.put(s,new Response(o,{headers:i})).catch(l=>{te.warn(`Unable to add response to browser cache: ${l}.`)})}}else{let i=a.progress_callback?l=>fr(a.progress_callback,{status:"progress",name:t,file:e,...l}):void 0;await r.put(s,n,i)}}async function y$(t,e,r=!0,s={},n=!1,o=null){let{requestURL:a,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:u}=qr(t,e,s,o),f,m=!1,_;_=await Wr(o,i,c);let w=_!==void 0;if(w)f=c;else{if(he.allowLocalModels)if(Sr(a,["http:","https:"])){if(s.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${a}.`);if(!he.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${a}.`)}else try{_=await jr(i),f=i}catch(k){te.warn(`Unable to load from local path "${i}": "${k}"`)}if(_===void 0||typeof _!="string"&&_.status===404){if(s.local_files_only||!he.allowRemoteModels){if(r)throw new Is(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${i}".`);return null}if(!u)throw new Is(`Local file missing at "${i}" and download aborted due to invalid model ID "${t}".`);if(_=await jr(l),_.status!==200)return qc(_.status,l,r);f=c}m=o&&typeof Response<"u"&&_ instanceof Response&&_.status===200}fr(s.progress_callback,{status:"download",name:t,file:e});let x;if(!(le.IS_NODE_ENV&&n)){let A;if(typeof _!="string")if(!s.progress_callback)A=new Uint8Array(await _.arrayBuffer());else if(w&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent))A=new Uint8Array(await _.arrayBuffer()),fr(s.progress_callback,{status:"progress",name:t,file:e,progress:100,loaded:A.length,total:A.length});else{let k,M=_.headers.get("content-length");if(M)k=parseInt(M,10);else try{let S=await Pt(t,e,s);S.size&&(k=S.size)}catch{}A=await P2(_,S=>{fr(s.progress_callback,{status:"progress",name:t,file:e,...S})},k)}x=A}if(m&&f&&typeof _!="string"&&await x$(t,e,o,f,_,x,s),le.IS_NODE_ENV&&n&&s.progress_callback&&typeof _!="string"){let A=parseInt(_.headers.get("content-length"),10)||0;fr(s.progress_callback,{status:"progress",name:t,file:e,progress:100,loaded:A,total:A})}if(fr(s.progress_callback,{status:"done",name:t,file:e}),x){if(!le.IS_NODE_ENV&&n)throw new Error("Cannot return path in a browser environment.");return x}if(_ instanceof Fr)return _.filePath;let b=await o?.match(f);if(b instanceof Fr)return b.filePath;if(b instanceof Response)return new Uint8Array(await b.arrayBuffer());if(typeof b=="string")return b;throw new Error("Unable to get model file path or buffer.")}var Ad=new Map;async function zo(t,e,r=!0,s={},n=!1){if(!he.allowLocalModels){if(s.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");if(!he.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}let o=Sn(t,s,e,r,n),{progress_callback:a}=s,i=a instanceof Ar?a.loads:Ad,l=i.get(o);return l||(fr(a,{status:"initiate",name:t,file:e}),l=rr(s.cache_dir).then(c=>y$(t,e,r,s,n,c)),i===Ad&&(l=l.finally(()=>Ad.delete(o))),i.set(o,l)),await l}async function $o(t,e,r=!0,s={}){let n=await zo(t,e,r,s,!1);return n===null?null:new TextDecoder("utf-8").decode(n)}async function lt(t,e,r=!0,s={}){let n=await $o(t,e,r,s);return n===null?{}:JSON.parse(n)}function R2(t,[e,r,s],[n,o],a="bilinear",i=!1){let l=o/s,c=n/r,u=new t.constructor(n*o*e),f=r*s,m=n*o;for(let _=0;_=0;--i)n[i]=l,s[i]=e[r[i]],l*=s[i];let o=r.map((i,l)=>n[r.indexOf(l)]),a=new t.constructor(t.length);for(let i=0;i=0;--c)l+=u%e[c]*o[c],u=Math.floor(u/e[c]);a[l]=t[i]}return[a,s]}function Ue(t){let e=Le(t)[0],r=t.map(o=>Math.exp(o-e)),s=r.reduce((o,a)=>o+a,0);return r.map(o=>o/s)}function Sd(t){let e=Le(t)[0],r=0;for(let o=0;oo-e-s)}function D2(t,e){let r=0;for(let s=0;se+r*r,0))}function Ro(t){if(t.length===0)throw Error("Array must not be empty");let e=t[0],r=0;for(let s=1;se&&(e=t[s],r=s);return[e,r]}function U2(t){return t>0&&(t&t-1)===0}var Hc=class{constructor(e){if(this.size=e|0,this.size<=1||!U2(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=e<<1,this.table=new Float64Array(this.size*2);for(let s=0;ss;s<<=1)++r;this._width=r%2===0?r-1:r,this._bitrev=new Int32Array(1<>>n&3)<>>1);for(let n=0;n>>1]=e[n];return s}toComplexArray(e,r){let s=r||this.createComplexArray();for(let n=0;n>>1],s[n+1]=0;return s}transform(e,r){if(e===r)throw new Error("Input and output buffers must be different");this._transform4(e,r,1)}realTransform(e,r){if(e===r)throw new Error("Input and output buffers must be different");this._realTransform4(e,r,1)}inverseTransform(e,r){if(e===r)throw new Error("Input and output buffers must be different");this._transform4(e,r,-1);for(let s=0;s>=2;a>=2;a>>=2){i=n/a<<1;let m=i>>>2;for(l=0;l>>1,a>>>1)}else for(l=0,c=0;l>>1,a>>>1,s)}let f=this.table;for(a>>=2;a>=2;a>>=2){i=n/a<<1;let _=i>>>1,w=_>>>1,x=w>>>1;for(l=0;l>>1;for(let _=2;_>1;++u){let f=(u+1-e)**2/2,m=Math.sqrt(l**2+c**2)**f,_=f*Math.atan2(c,l),w=2*u;o[w]=m*Math.cos(_),o[w+1]=m*Math.sin(_),a[w]=o[w],a[w+1]=-o[w+1]}this._slicedChirpBuffer=o.subarray(r,s),this._f=new Hc(n>>1),this._f.transform(this._chirpBuffer,a)}_transform(e,r,s){let n=this._buffer1,o=this._buffer2,a=this._outBuffer1,i=this._outBuffer2,l=this._chirpBuffer,c=this._slicedChirpBuffer,u=this._a;if(s)for(let f=0;f>1,w=r[_];n[f]=w*c[f],n[m]=w*c[m]}else for(let f=0;f=t.length&&(l=2*(t.length-1)-l),s[a++]=t[l]}s.sort(),r[o]=s[n]}return r}function Cs(t,e){let r=Math.pow(10,e);return Math.round(t*r)/r}function G2(t){let e=Math.round(t);return Math.abs(t)%1===.5?e%2===0?e:e-1:e}function j2(t){let e=t.length,r=t[0].length,s=[e+1,r+1],n=Array.from({length:s[0]},()=>Array(s[1]).fill(1/0));n[0][0]=0;let o=Array.from({length:s[0]},()=>Array(s[1]).fill(-1));for(let u=1;u0||i>0;)switch(l.push(a-1),c.push(i-1),o[a][i]){case 0:--a,--i;break;case 1:--a;break;case 2:--i;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${a}, ${i}]. Please file a bug report.`)}return l.reverse(),c.reverse(),[l,c]}var q2=(function(){let t=null;return function(e){if(!t){t=new Float32Array(65536);let o=new ArrayBuffer(4),a=new Uint32Array(o),i=new Float32Array(o);for(let l=0;l>10,m=l&1023;if(f===31)c=u|2139095040|m<<13;else if(f===0)if(m===0)c=u;else{let _=113;for(;(m&1024)===0;)m<<=1,--_;m&=-1025,c=u|_<<23|m<<13}else c=u|f+112<<23|m<<13;a[0]=c,t[l]=i[0]}}let r=e.length,s=t,n=new Float32Array(r);for(let o=0;otm,TRACE:()=>ru,TRACE_EVENT_BEGIN:()=>Kr,TRACE_EVENT_END:()=>Yr,TRACE_FUNC_BEGIN:()=>Rs,TRACE_FUNC_END:()=>Bs,Tensor:()=>sr,default:()=>Y$,env:()=>Je,registerBackend:()=>$s});var Zd=Object.defineProperty,v$=Object.getOwnPropertyDescriptor,k$=Object.getOwnPropertyNames,E$=Object.prototype.hasOwnProperty,A$=(t=>typeof Ts<"u"?Ts:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof Ts<"u"?Ts:e)[r]}):t)(function(t){if(typeof Ts<"u")return Ts.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')}),Ae=(t,e,r)=>()=>{if(r)throw r[0];try{return t&&(e=t(t=0)),e}catch(s){throw r=[s],s}},Wo=(t,e)=>{for(var r in e)Zd(t,r,{get:e[r],enumerable:!0})},T$=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of k$(e))!E$.call(t,n)&&n!==r&&Zd(t,n,{get:()=>e[n],enumerable:!(s=v$(e,n))||s.enumerable});return t},tu=t=>T$(Zd({},"__esModule",{value:!0}),t),Bo,Vr,$s,V2,yT,bT=Ae(()=>{"use strict";Bo=new Map,Vr=[],$s=(t,e,r)=>{if(e&&typeof e.init=="function"&&typeof e.createInferenceSessionHandler=="function"){let s=Bo.get(t);if(s===void 0)Bo.set(t,{backend:e,priority:r});else{if(s.priority>r)return;if(s.priority===r&&s.backend!==e)throw new Error(`cannot register backend "${t}" using priority ${r}`)}if(r>=0){let n=Vr.indexOf(t);n!==-1&&Vr.splice(n,1);for(let o=0;o{let e=Bo.get(t);if(!e)return"backend not found.";if(e.initialized)return e.backend;if(e.aborted)return e.error;{let r=!!e.initPromise;try{return r||(e.initPromise=e.backend.init(t)),await e.initPromise,e.initialized=!0,e.backend}catch(s){return r||(e.error=`${s}`,e.aborted=!0),e.error}finally{delete e.initPromise}}},yT=async t=>{let e=t.executionProviders||[],r=e.map(l=>typeof l=="string"?l:l.name),s=r.length===0?Vr:r,n,o=[],a=new Set;for(let l of s){let c=await V2(l);typeof c=="string"?o.push({name:l,err:c}):(n||(n=c),n===c&&a.add(l))}if(!n)throw new Error(`no available backend found. ERR: ${o.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(let{name:l,err:c}of o)r.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${c}`);let i=e.filter(l=>a.has(typeof l=="string"?l:l.name));return[n,new Proxy(t,{get:(l,c)=>c==="executionProviders"?i:Reflect.get(l,c)})]}}),S$=Ae(()=>{"use strict";bT()}),vT,M$=Ae(()=>{"use strict";vT="1.31.0-dev.20260911-2a43ec07e"}),Md,mt,kT=Ae(()=>{"use strict";M$(),Md="warning",mt={wasm:{},webgl:{},webgpu:{},versions:{common:vT},set logLevel(t){if(t!==void 0){if(typeof t!="string"||["verbose","info","warning","error","fatal"].indexOf(t)===-1)throw new Error(`Unsupported logging level: ${t}`);Md=t}},get logLevel(){return Md}},Object.defineProperty(mt,"logLevel",{enumerable:!0})}),Je,O$=Ae(()=>{"use strict";kT(),Je=mt}),ET,AT,I$=Ae(()=>{"use strict";ET=(t,e)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=t.dims[3],r.height=t.dims[2];let s=r.getContext("2d");if(s!=null){let n,o;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],o=t.dims[3]):(n=t.dims[3],o=t.dims[2]);let a=e?.format!==void 0?e.format:"RGB",i=e?.norm,l,c;i===void 0||i.mean===void 0?l=[255,255,255,255]:typeof i.mean=="number"?l=[i.mean,i.mean,i.mean,i.mean]:(l=[i.mean[0],i.mean[1],i.mean[2],0],i.mean[3]!==void 0&&(l[3]=i.mean[3])),i===void 0||i.bias===void 0?c=[0,0,0,0]:typeof i.bias=="number"?c=[i.bias,i.bias,i.bias,i.bias]:(c=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(c[3]=i.bias[3]));let u=o*n,f=0,m=u,_=u*2,w=-1;a==="RGBA"?(f=0,m=u,_=u*2,w=u*3):a==="RGB"?(f=0,m=u,_=u*2):a==="RBG"&&(f=0,_=u,m=u*2);for(let x=0;x{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(r!=null){let n,o,a;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],o=t.dims[1],a=t.dims[3]):(n=t.dims[3],o=t.dims[2],a=t.dims[1]);let i=e!==void 0&&e.format!==void 0?e.format:"RGB",l=e?.norm,c,u;l===void 0||l.mean===void 0?c=[255,255,255,255]:typeof l.mean=="number"?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(c[3]=l.mean[3])),l===void 0||l.bias===void 0?u=[0,0,0,0]:typeof l.bias=="number"?u=[l.bias,l.bias,l.bias,l.bias]:(u=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(u[3]=l.bias[3]));let f=o*n;if(e!==void 0&&(e.format!==void 0&&a===4&&e.format!=="RGBA"||a===3&&e.format!=="RGB"&&e.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let m=4,_=0,w=1,x=2,b=3,A=0,k=f,M=f*2,S=-1;i==="RGBA"?(A=0,k=f,M=f*2,S=f*3):i==="RGB"?(A=0,k=f,M=f*2):i==="RBG"&&(A=0,M=f,k=f*2),s=r.createImageData(n,o);for(let O=0;O{"use strict";em(),Kc=(t,e)=>{if(t===void 0)throw new Error("Image buffer must be defined");if(e.height===void 0||e.width===void 0)throw new Error("Image height and width must be defined");if(e.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:s}=e,n=e.norm??{mean:255,bias:0},o,a;typeof n.mean=="number"?o=[n.mean,n.mean,n.mean,n.mean]:o=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?a=[n.bias,n.bias,n.bias,n.bias]:a=[n.bias[0],n.bias[1],n.bias[2],n.bias[3]??0];let i=e.format!==void 0?e.format:"RGBA",l=e.tensorFormat!==void 0&&e.tensorFormat!==void 0?e.tensorFormat:"RGB",c=r*s,u=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),f=4,m=0,_=1,w=2,x=3,b=0,A=c,k=c*2,M=-1;i==="RGB"&&(f=3,m=0,_=1,w=2,x=-1),l==="RGBA"?M=c*3:l==="RBG"?(b=0,k=c,A=c*2):l==="BGR"&&(k=0,A=c,b=c*2);for(let S=0;S{let r=typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement,s=typeof ImageData<"u"&&t instanceof ImageData,n=typeof ImageBitmap<"u"&&t instanceof ImageBitmap,o=typeof t=="string",a,i=e??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=u=>typeof HTMLCanvasElement<"u"&&u instanceof HTMLCanvasElement||u instanceof OffscreenCanvas?u.getContext("2d"):null;if(r){let u=l();u.width=t.width,u.height=t.height;let f=c(u);if(f!=null){let m=t.height,_=t.width;if(e!==void 0&&e.resizedHeight!==void 0&&e.resizedWidth!==void 0&&(m=e.resizedHeight,_=e.resizedWidth),e!==void 0){if(i=e,e.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");i.tensorFormat="RGBA",i.height=m,i.width=_}else i.tensorFormat="RGBA",i.height=m,i.width=_;f.drawImage(t,0,0),a=f.getImageData(0,0,_,m).data}else throw new Error("Can not access image data")}else if(s){let u,f;if(e!==void 0&&e.resizedWidth!==void 0&&e.resizedHeight!==void 0?(u=e.resizedHeight,f=e.resizedWidth):(u=t.height,f=t.width),e!==void 0&&(i=e),i.format="RGBA",i.height=u,i.width=f,e!==void 0){let m=l();m.width=f,m.height=u;let _=c(m);if(_!=null)_.putImageData(t,0,0),a=_.getImageData(0,0,f,u).data;else throw new Error("Can not access image data")}else a=t.data}else if(n){if(e===void 0)throw new Error("Please provide image config with format for Imagebitmap");let u=l();u.width=t.width,u.height=t.height;let f=c(u);if(f!=null){let m=t.height,_=t.width;return f.drawImage(t,0,0,_,m),a=f.getImageData(0,0,_,m).data,i.height=m,i.width=_,Kc(a,i)}else throw new Error("Can not access image data")}else{if(o)return new Promise((u,f)=>{let m=l(),_=c(m);if(!t||!_)return f();let w=new Image;w.crossOrigin="Anonymous",w.src=t,w.onload=()=>{m.width=w.width,m.height=w.height,_.drawImage(w,0,0,m.width,m.height);let x=_.getImageData(0,0,m.width,m.height);i.height=m.height,i.width=m.width,u(Kc(x.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==void 0)return Kc(a,i);throw new Error("Input data provided is not supported - aborted tensor creation")},ST=(t,e)=>{let{width:r,height:s,download:n,dispose:o}=e,a=[1,s,r,4];return new $t({location:"texture",type:"float32",texture:t,dims:a,download:n,dispose:o})},MT=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new $t({location:"gpu-buffer",type:r??"float32",gpuBuffer:t,dims:s,download:n,dispose:o})},OT=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new $t({location:"ml-tensor",type:r??"float32",mlTensor:t,dims:s,download:n,dispose:o})},IT=(t,e,r)=>new $t({location:"cpu-pinned",type:t,data:e,dims:r??[e.length]})}),Ls,jo,Od,CT,P$=Ae(()=>{"use strict";Ls=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),jo=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Od=!1,CT=()=>{if(!Od){Od=!0;let t=typeof BigInt64Array<"u"&&BigInt64Array.from,e=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,s=typeof r<"u"&&r.from;t&&(Ls.set("int64",BigInt64Array),jo.set(BigInt64Array,"int64")),e&&(Ls.set("uint64",BigUint64Array),jo.set(BigUint64Array,"uint64")),s?(Ls.set("float16",r),jo.set(r,"float16")):Ls.set("float16",Uint16Array)}}}),PT,NT,N$=Ae(()=>{"use strict";em(),PT=t=>{let e=1;for(let r=0;r{switch(t.location){case"cpu":return new $t(t.type,t.data,e);case"cpu-pinned":return new $t({location:"cpu-pinned",data:t.data,type:t.type,dims:e});case"texture":return new $t({location:"texture",texture:t.texture,type:t.type,dims:e});case"gpu-buffer":return new $t({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:e});case"ml-tensor":return new $t({location:"ml-tensor",mlTensor:t.mlTensor,type:t.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}}}),$t,em=Ae(()=>{"use strict";I$(),C$(),P$(),N$(),$t=class{constructor(t,e,r){CT();let s,n;if(typeof t=="object"&&"location"in t)switch(this.dataLocation=t.location,s=t.type,n=t.dims,t.location){case"cpu-pinned":{let a=Ls.get(s);if(!a)throw new TypeError(`unsupported type "${s}" to create tensor from pinned buffer`);if(!(t.data instanceof a))throw new TypeError(`buffer should be of type ${a.name}`);this.cpuData=t.data;break}case"texture":{if(s!=="float32")throw new TypeError(`unsupported type "${s}" to create tensor from texture`);this.gpuTextureData=t.texture,this.downloader=t.download,this.disposer=t.dispose;break}case"gpu-buffer":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from gpu buffer`);this.gpuBufferData=t.gpuBuffer,this.downloader=t.download,this.disposer=t.dispose;break}case"ml-tensor":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint64"&&s!=="int8"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from MLTensor`);this.mlTensorData=t.mlTensor,this.downloader=t.download,this.disposer=t.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,i;if(typeof t=="string")if(s=t,i=r,t==="string"){if(!Array.isArray(e))throw new TypeError("A string tensor's data must be a string array.");a=e}else{let l=Ls.get(t);if(l===void 0)throw new TypeError(`Unsupported tensor type: ${t}.`);if(Array.isArray(e)){if(t==="float16"&&l===Uint16Array||t==="uint4"||t==="int4")throw new TypeError(`Creating a ${t} tensor from number array is not supported. Please use ${l.name} as data.`);t==="uint64"||t==="int64"?a=l.from(e,BigInt):a=l.from(e)}else if(e instanceof l)a=e;else if(e instanceof Uint8ClampedArray)if(t==="uint8")a=Uint8Array.from(e);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(t==="float16"&&e instanceof Uint16Array&&l!==Uint16Array)a=new globalThis.Float16Array(e.buffer,e.byteOffset,e.length);else throw new TypeError(`A ${s} tensor's data must be type of ${l}`)}else if(i=e,Array.isArray(t)){if(t.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let l=typeof t[0];if(l==="string")s="string",a=t;else if(l==="boolean")s="bool",a=Uint8Array.from(t);else throw new TypeError(`Invalid element type of data array: ${l}.`)}else if(t instanceof Uint8ClampedArray)s="uint8",a=Uint8Array.from(t);else{let l=jo.get(t.constructor);if(l===void 0)throw new TypeError(`Unsupported type for tensor data: ${t.constructor}.`);s=l,a=t}if(i===void 0)i=[a.length];else if(!Array.isArray(i))throw new TypeError("A tensor's dims must be a number array");n=i,this.cpuData=a,this.dataLocation="cpu"}let o=PT(n);if(this.cpuData&&o!==this.cpuData.length&&!((s==="uint4"||s==="int4")&&Math.ceil(o/2)===this.cpuData.length))throw new Error(`Tensor's size(${o}) does not match data length(${this.cpuData.length}).`);this.type=s,this.dims=n,this.size=o}static async fromImage(t,e){return TT(t,e)}static fromTexture(t,e){return ST(t,e)}static fromGpuBuffer(t,e){return MT(t,e)}static fromMLTensor(t,e){return OT(t,e)}static fromPinnedBuffer(t,e,r){return IT(t,e,r)}toDataURL(t){return ET(this,t)}toImageData(t){return AT(this,t)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(t){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let e=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=e,t&&this.disposer&&(this.disposer(),this.disposer=void 0),e}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(t){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return NT(this,t)}}}),sr,LT=Ae(()=>{"use strict";em(),sr=$t}),ru,Id,Rs,Bs,Kr,Yr,zT=Ae(()=>{"use strict";kT(),ru=(t,e)=>{(typeof mt.trace>"u"?!mt.wasm.trace:!mt.trace)||console.timeStamp(`${t}::ORT::${e}`)},Id=(t,e)=>{let r=new Error().stack?.split(/\r\n|\r|\n/g)||[],s=!1;for(let n=0;n{(typeof mt.trace>"u"?!mt.wasm.trace:!mt.trace)||Id("BEGIN",t)},Bs=t=>{(typeof mt.trace>"u"?!mt.wasm.trace:!mt.trace)||Id("END",t)},Kr=t=>{(typeof mt.trace>"u"?!mt.wasm.trace:!mt.trace)||console.time(`ORT::${t}`)},Yr=t=>{(typeof mt.trace>"u"?!mt.wasm.trace:!mt.trace)||console.timeEnd(`ORT::${t}`)}}),$T,L$=Ae(()=>{"use strict";bT(),LT(),zT(),$T=class RT{constructor(e){this.handler=e}async run(e,r,s){Rs(),Kr("InferenceSession.run");let n={},o={};if(typeof e!="object"||e===null||e instanceof sr||Array.isArray(e))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let a=!0;if(typeof r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof sr)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(r.length===0)throw new TypeError("'fetches' cannot be an empty array.");a=!1;for(let c of r){if(typeof c!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);n[c]=null}if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let c=!1,u=Object.getOwnPropertyNames(r);for(let f of this.outputNames)if(u.indexOf(f)!==-1){let m=r[f];(m===null||m instanceof sr)&&(c=!0,a=!1,n[f]=m)}if(c){if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else o=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let c of this.inputNames)if(typeof e[c]>"u")throw new Error(`input '${c}' is missing in 'feeds'.`);if(a)for(let c of this.outputNames)n[c]=null;let i=await this.handler.run(e,n,o),l={};for(let c in i)if(Object.hasOwnProperty.call(i,c)){let u=i[c];u instanceof sr?l[c]=u:l[c]=new sr(u.type,u.data,u.dims)}return Yr("InferenceSession.run"),Bs(),l}async release(){return this.handler.dispose()}static async create(e,r,s,n){Rs(),Kr("InferenceSession.create");let o,a={};if(typeof e=="string"){if(o=e,typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof Uint8Array){if(o=e,typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer){let u=e,f=0,m=e.byteLength;if(typeof r=="object"&&r!==null)a=r;else if(typeof r=="number"){if(f=r,!Number.isSafeInteger(f))throw new RangeError("'byteOffset' must be an integer.");if(f<0||f>=u.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${u.byteLength}).`);if(m=e.byteLength-f,typeof s=="number"){if(m=s,!Number.isSafeInteger(m))throw new RangeError("'byteLength' must be an integer.");if(m<=0||f+m>u.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${u.byteLength-f}].`);if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(typeof s<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof r<"u")throw new TypeError("'options' must be an object.");o=new Uint8Array(u,f,m)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[i,l]=await yT(a),c=await i.createInferenceSessionHandler(o,l);return Yr("InferenceSession.create"),Bs(),new RT(c)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),tm,z$=Ae(()=>{"use strict";L$(),tm=$T}),$$=Ae(()=>{"use strict"}),R$=Ae(()=>{"use strict"}),B$=Ae(()=>{"use strict"}),D$=Ae(()=>{"use strict"}),BT={};Wo(BT,{InferenceSession:()=>tm,TRACE:()=>ru,TRACE_EVENT_BEGIN:()=>Kr,TRACE_EVENT_END:()=>Yr,TRACE_FUNC_BEGIN:()=>Rs,TRACE_FUNC_END:()=>Bs,Tensor:()=>sr,env:()=>Je,registerBackend:()=>$s});var Ds=Ae(()=>{"use strict";S$(),O$(),z$(),LT(),$$(),R$(),zT(),B$(),D$()}),rm=Ae(()=>{"use strict"}),DT={};Wo(DT,{default:()=>UT});var Cd,Pd,UT,U$=Ae(()=>{"use strict";tS(),Us(),sm(),Cd="ort-wasm-proxy-worker",Pd=globalThis.self?.name===Cd,Pd&&(self.onmessage=t=>{let{type:e,in:r}=t.data;try{switch(e){case"init-wasm":nm(r.wasm).then(()=>{cm(r).then(()=>{postMessage({type:e})},s=>{postMessage({type:e,err:s})})},s=>{postMessage({type:e,err:s})});break;case"init-ep":{let{epName:s,env:n}=r;um(n,s).then(()=>{postMessage({type:e})},o=>{postMessage({type:e,err:o})});break}case"copy-from":{let{buffer:s}=r,n=ou(s);postMessage({type:e,out:n});break}case"create":{let{model:s,options:n}=r;pm(s,n).then(o=>{postMessage({type:e,out:o})},o=>{postMessage({type:e,err:o})});break}case"release":fm(r),postMessage({type:e});break;case"run":{let{sessionId:s,inputIndices:n,inputs:o,outputIndices:a,options:i}=r;dm(s,n,o,a,new Array(a.length).fill(null),i).then(l=>{l.some(c=>c[3]!=="cpu")?postMessage({type:e,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:e,out:l},_m([...o,...l]))},l=>{postMessage({type:e,err:l})});break}case"end-profiling":mm(r),postMessage({type:e});break;default:}}catch(s){postMessage({type:e,err:s})}}),UT=Pd?null:t=>new Worker(t??Lt,{type:"module",name:Cd})}),FT={};Wo(FT,{default:()=>GT});async function H2(t={}){var e=t,r=!!globalThis.window,s=!!globalThis.WorkerGlobalScope,n=s&&self.name?.startsWith("em-pthread");e.mountExternalData=(p,d)=>{p.startsWith("./")&&(p=p.substring(2)),(e.ed||(e.ed=new Map)).set(p,d)},e.unmountExternalData=()=>{delete e.ed,delete e.Te,delete e.Se,delete e.Ue},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let o=()=>{let p=d=>(...h)=>{let g=ur;return h=d(...h),ur!=g?new Promise((E,T)=>{qf={resolve:E,reject:T}}):h};(()=>{for(let d of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])e[d]=p(e[d])})(),typeof jsepRunAsync<"u"&&(e._OrtRun=jsepRunAsync(e._OrtRun),e._OrtRunWithBinding=jsepRunAsync(e._OrtRunWithBinding)),o=void 0};e.asyncInit=()=>{o?.()};var a,i,l=(p,d)=>{throw d},c=import.meta.url,u="";if(r||s){try{u=new URL(".",c).href}catch{}s&&(i=p=>{var d=new XMLHttpRequest;return d.open("GET",p,!1),d.responseType="arraybuffer",d.send(null),new Uint8Array(d.response)}),a=async p=>{if(C(p))return new Promise((h,g)=>{var E=new XMLHttpRequest;E.open("GET",p,!0),E.responseType="arraybuffer",E.onload=()=>{E.status==200||E.status==0&&E.response?h(E.response):g(E.status)},E.onerror=g,E.send(null)});var d=await fetch(p,{credentials:"same-origin"});if(d.ok)return d.arrayBuffer();throw Error(d.status+" : "+d.url)}}var f,m,_,w,x,b,A=console.log.bind(console),k=console.error.bind(console),M=A,S=k,O=!1,C=p=>p.startsWith("file://");function v(){zr.buffer!=F.buffer&&G()}if(n){let p=function(d){try{var h=d.data,g=h.$c;if(g==="load"){let E=[];self.onmessage=T=>E.push(T),b=()=>{postMessage({$c:"loaded"});for(let T of E)p(T);self.onmessage=p};for(let T of h.ue)e[T]&&!e[T].proxy||(e[T]=(...N)=>{postMessage({$c:"callHandler",te:T,args:N})},T=="print"&&(M=e[T]),T=="printErr"&&(S=e[T]));zr=h.Me,G(),m=h.Ne,Fe(),Mc()}else if(g==="run"){(function(E){var T=(v(),I)[E+52>>>2>>>0];E=(v(),I)[E+56>>>2>>>0],CE(T,T-E),ce(T)})(h.Xc),rd(h.Xc,0,0,1,0,0),pk(),Ff(h.Xc),j||(fE(),j=!0);try{xO(h.ze,h.kd)}catch(E){if(E!="unwind")throw E}}else h.target!=="setimmediate"&&(g==="checkMailbox"?j&&wc():g&&(S(`worker: received unknown command ${g}`),S(h)))}catch(E){throw TE(),E}};var U=p,j=!1;self.onunhandledrejection=d=>{throw d.reason||d},self.onmessage=p}var F,K,Y,Q,B,I,oe,J,Z,me,L,z=!1;function G(){var p=zr.buffer;e.HEAP8=F=new Int8Array(p),Y=new Int16Array(p),e.HEAPU8=K=new Uint8Array(p),Q=new Uint16Array(p),e.HEAP32=B=new Int32Array(p),e.HEAPU32=I=new Uint32Array(p),oe=new Float32Array(p),J=new Float64Array(p),Z=new BigInt64Array(p),me=new BigUint64Array(p)}function ge(){z=!0,n?b():Er.hc()}function ie(p){throw S(p="Aborted("+p+")"),O=!0,p=new WebAssembly.RuntimeError(p+". Build with -sASSERTIONS for more info."),x?.(p),p}function ot(){return{a:{qa:jC,f:yO,K:bO,k:vO,p:kO,l:EO,fa:AO,b:TO,da:SO,gc:gk,q:MO,ea:bk,Ua:vk,cc:kk,ec:Ek,Va:Ak,Sa:Tk,La:Sk,Ra:Mk,oa:Ok,dc:Ik,ac:Ck,Ta:Pk,bc:Nk,_a:OO,Ba:CO,Xb:PO,Vb:LO,Aa:$O,O:RO,J:BO,Wb:DO,ka:VO,Yb:HO,Oa:XO,_b:YO,Ea:QO,Tb:JO,Ca:ZO,Na:Ff,Xa:eI,U:nI,n:cI,c:Df,qb:uI,w:pI,N:fI,A:dI,j:mI,o:Fk,rb:_I,H:hI,T:gI,g:wI,u:xI,m:yI,i:bI,Ia:vI,Ja:kI,Ka:EI,Ga:Wk,Ha:Vk,Ub:Hk,ab:TI,Za:OI,Z:II,pb:CI,Da:PI,Ya:SI,X:NI,Wa:LI,$b:zI,G:AI,db:$I,_:RI,pa:kc,Zb:DI,cb:BI,bb:UI,lb:ZI,z:eC,sa:tC,ra:rC,nb:sC,Y:nC,v:oC,kb:aC,jb:iC,ib:lC,mb:cC,gb:uC,fb:pC,eb:fC,Pa:nE,Qa:oE,fc:mn,W:aE,Fa:iE,ma:lE,Ma:cE,la:uE,Fb:SP,va:bP,Gb:TP,wa:yP,E:iP,e:HC,r:WC,x:qC,C:sP,Ib:gP,ca:hP,D:YC,xa:wP,aa:vP,ha:_P,Jb:mP,Kb:dP,za:cP,Lb:pP,ya:fP,Mb:uP,ua:AP,ba:xP,d:VC,B:KC,s:XC,Eb:MP,t:JC,y:oP,F:QC,I:ZC,L:aP,Nb:lP,R:kP,ia:rP,$:EP,Pb:tP,Rb:eP,Ob:nP,h:mC,a:zr,$a:dn,Hb:_C,V:hC,M:gC,na:wC,Db:xC,ja:yC,S:bC,Ab:vC,Bb:kC,vb:EC,wb:AC,P:TC,xb:SC,yb:MC,ta:OC,Sb:IC,ob:CC,Q:PC,hb:NC,Cb:LC,sb:zC,tb:RC,ub:BC,ga:DC,zb:UC,Qb:FC}}}async function Fe(){function p(g,E){var T=Er=g.exports;g={};for(let[N,P]of Object.entries(T))typeof P=="function"?(T=tI(P),g[N]=T):g[N]=P;return Er=g,Er=(function(){var N=Er,P=H=>xe=>H(xe)>>>0,R=H=>()=>H()>>>0;return(N=Object.assign({},N)).ic=P(N.ic),N.Nc=R(N.Nc),N.Pc=P(N.Pc),N.Bd=(H=>(xe,ve)=>H(xe,ve)>>>0)(N.Bd),N.Gd=P(N.Gd),N.Hd=R(N.Hd),N.Ld=P(N.Ld),N})(),ck.push(Er.sd),pE=(g=Er).ic,fE=g.jc,e._OrtInit=g.kc,e._OrtGetLastError=g.lc,e._OrtCreateSessionOptions=g.mc,e._OrtAppendExecutionProvider=g.nc,e._OrtAddFreeDimensionOverride=g.oc,e._OrtAddSessionConfigEntry=g.pc,e._OrtReleaseSessionOptions=g.qc,e._OrtCreateSession=g.rc,e._OrtReleaseSession=g.sc,e._OrtGetInputOutputCount=g.tc,e._OrtGetInputOutputMetadata=g.uc,e._OrtFree=g.vc,e._OrtCreateTensor=g.wc,e._OrtGetTensorData=g.xc,e._OrtReleaseTensor=g.yc,e._OrtCreateRunOptions=g.zc,e._OrtAddRunConfigEntry=g.Ac,e._OrtReleaseRunOptions=g.Bc,e._OrtCreateBinding=g.Cc,e._OrtBindInput=g.Dc,e._OrtBindOutput=g.Ec,e._OrtClearBoundOutputs=g.Fc,e._OrtReleaseBinding=g.Gc,e._OrtRunWithBinding=g.Hc,e._OrtRun=g.Ic,e._OrtEndProfiling=g.Jc,dE=e._OrtCreateWebGpuInstance=g.Kc,e._wgpuCreateInstance=g.Lc,Yf=e._OrtGetWebGpuDevice=g.Mc,Tc=g.Nc,Ft=e._free=g.Oc,ks=e._malloc=g.Pc,mE=e._wgpuBufferRelease=g.Qc,_E=g.Rc,hE=g.Sc,gE=g.Tc,wE=g.Uc,xE=g.Vc,yE=g.Yc,bE=g.Zc,vE=g.hd,kE=g.id,EE=g.jd,Qf=g.ld,Jf=g.md,Zf=g.nd,ed=g.od,So=g.pd,td=g.qd,AE=g.rd,rd=g.ud,TE=g.vd,SE=g.wd,ME=g.xd,sd=g.yd,OE=g.zd,IE=g.Ad,nd=g.Bd,be=g.Cd,Mo=g.Dd,CE=g.Ed,ce=g.Fd,Sc=g.Gd,ue=g.Hd,PE=g.Id,od=g.Jd,NE=g.Kd,LE=g.Ld,zE=g.Md,ad=g.Nd,$E=g.Od,RE=g.Pd,BE=g.Qd,DE=g.Rd,UE=g.Sd,FE=g.Td,GE=g.Ud,jE=g.Vd,qE=g.Wd,WE=g.Xd,VE=g.Yd,HE=g.Zd,XE=g._d,KE=g.$d,YE=g.ae,QE=g.be,JE=g.ce,ZE=g.de,eA=g.fe,tA=g.ge,rA=g.he,sA=g.ie,nA=g.je,oA=g.ke,aA=g.le,iA=g.me,lA=g.Ae,cA=g.Be,uA=g.Ce,pA=g.De,fA=g.Ee,dA=g.Fe,mA=g.Ge,_A=g.He,hA=g.Ie,gA=g.Je,wA=g.Ke,xA=g.nf,yA=g.of,bA=g.pf,vA=g.qf,m=E,Er}var d,h=ot();return e.instantiateWasm?new Promise(g=>{e.instantiateWasm(h,(E,T)=>{g(p(E,T))})}):n?p(new WebAssembly.Instance(m,ot()),m):(L??=e.locateFile?e.locateFile?e.locateFile("ort-wasm-simd-threaded.asyncify.wasm",u):u+"ort-wasm-simd-threaded.asyncify.wasm":new URL("ort-wasm-simd-threaded.asyncify.wasm",import.meta.url).href,d=await(async function(g){var E=L;if(!f&&!C(E))try{var T=fetch(E,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(T,g)}catch(N){S(`wasm streaming compile failed: ${N}`),S("falling back to ArrayBuffer instantiation")}return(async function(N,P){try{var R=await(async function(H){if(!f)try{var xe=await a(H);return new Uint8Array(xe)}catch{}if(H==L&&f)H=new Uint8Array(f);else{if(!i)throw"both async and sync fetching of the wasm failed";H=i(H)}return H})(N);return await WebAssembly.instantiate(R,P)}catch(H){S(`failed to asynchronously prepare wasm: ${H}`),ie(H)}})(E,g)})(h),p(d.instance,d.module))}class Re{name="ExitStatus";constructor(d){this.message=`Program terminated with exit(${d})`,this.status=d}}var et=p=>{p.terminate(),p.onmessage=()=>{}},qe=[],Ce=0,at=null,lr=p=>{Lr.length==0&&(dk(),fk(Lr[0]));var d=Lr.pop();if(!d)return 6;Ao.push(d),ys[p.Xc]=d,d.Xc=p.Xc;var h={$c:"run",ze:p.ye,kd:p.kd,Xc:p.Xc};return d.postMessage(h,p.oe),0},Pe=0,Ge=(p,d,...h)=>{var g,E=16*h.length,T=ue(),N=Sc(E),P=N>>>3;for(g of h)typeof g=="bigint"?((v(),Z)[P++>>>0]=1n,(v(),Z)[P++>>>0]=g):((v(),Z)[P++>>>0]=0n,(v(),J)[P++>>>0]=g);return p=SE(p,0,E,N,d),ce(T),p};function dn(p){if(n)return Ge(0,1,p);if(_=p,!(0{if(_=p,n)throw Eo(p),"unwind";dn(p)},Lr=[],Ao=[],ck=[],ys={},uk=p=>{var d=p.Xc;delete ys[d],Lr.push(p),Ao.splice(Ao.indexOf(p),1),p.Xc=0,ME(d)};function pk(){ck.forEach(p=>p())}var fk=p=>new Promise(d=>{p.onmessage=E=>{var T=E.data;if(E=T.$c,T.gd&&T.gd!=Tc()){var N=ys[T.gd];N?N.postMessage(T,T.oe):S(`Internal error! Worker sent a message "${E}" to target pthread ${T.gd}, but that thread no longer exists!`)}else E==="checkMailbox"?wc():E==="spawnThread"?lr(T):E==="cleanupThread"?St(()=>{uk(ys[T.Le])}):E==="loaded"?(p.loaded=!0,d(p)):T.target==="setimmediate"?p.postMessage(T):E==="uncaughtException"?p.onerror(T.error):E==="callHandler"?e[T.te](...T.args):E&&S(`worker sent an unknown command ${E}`)},p.onerror=E=>{throw S(`worker sent an error! ${E.filename}:${E.lineno}: ${E.message}`),E};var h,g=[];for(h of[])e.propertyIsEnumerable(h)&&g.push(h);p.postMessage({$c:"load",ue:g,Me:zr,Ne:m})});function dk(){var p=new Worker((()=>{let d=URL;return import.meta.url>"file:"&&import.meta.url<"file;"?new d("ort.webgpu.bundle.min.mjs",import.meta.url):new URL(import.meta.url)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});Lr.push(p)}var zr,xO=(p,d)=>{Pe=0,p=ad(p,d),0-9007199254740992>p||9007199254740992>>=0);return(v(),F)[d.ad+12>>>0]==0&&(mk(d,!0),gc--),_k(d,!1),hc.push(d),LE(p)}var _n=0,bO=()=>{be(0,0);var p=hc.pop();PE(p.td),_n=0};function mk(p,d){d=d?1:0,(v(),F)[p.ad+12>>>0]=d}function _k(p,d){d=d?1:0,(v(),F)[p.ad+13>>>0]=d}class zf{constructor(d){this.td=d,this.ad=d-24}}var $f=p=>{var d=_n;if(!d)return Mo(0),0;var h=new zf(d);(v(),I)[h.ad+16>>>2>>>0]=d;var g=(v(),I)[h.ad+4>>>2>>>0];if(!g)return Mo(0),d;for(var E of p){if(E===0||E===g)break;if(NE(E,g,h.ad+16))return Mo(E),d}return Mo(g),d};function vO(){return $f([])}function kO(p){return $f([p>>>0])}function EO(p,d,h,g){return $f([p>>>0,d>>>0,h>>>0,g>>>0])}var AO=()=>{var p=hc.pop();p||ie("no exception to throw");var d=p.td;throw(v(),F)[p.ad+13>>>0]==0&&(hc.push(p),_k(p,!0),mk(p,!1),gc++),od(d),_n=d};function TO(p,d,h){var g=new zf(p>>>=0);throw d>>>=0,h>>>=0,(v(),I)[g.ad+16>>>2>>>0]=0,(v(),I)[g.ad+4>>>2>>>0]=d,(v(),I)[g.ad+8>>>2>>>0]=h,od(p),gc++,_n=p}var SO=()=>gc;function hk(p,d,h,g){return n?Ge(2,1,p,d,h,g):gk(p,d,h,g)}function gk(p,d,h,g){if(p>>>=0,d>>>=0,h>>>=0,g>>>=0,!globalThis.SharedArrayBuffer)return 6;var E=[];return n&&E.length===0?hk(p,d,h,g):(p={ye:h,Xc:p,kd:g,oe:E},n?(p.$c="spawnThread",postMessage(p,E),0):lr(p))}function MO(p){throw _n||=p>>>0,_n}var wk=globalThis.TextDecoder&&new TextDecoder,xk=(p,d,h,g)=>{if(h=d+h,g)return h;for(;p[d]&&!(d>=h);)++d;return d},yk=(p,d=0,h,g)=>{if(16<(h=xk(p,d>>>=0,h,g))-d&&p.buffer&&wk)return wk.decode(p.buffer instanceof ArrayBuffer?p.subarray(d,h):p.slice(d,h));for(g="";d(E=(240&E)==224?(15&E)<<12|T<<6|N:(7&E)<<18|T<<12|N<<6|63&p[d++])?g+=String.fromCharCode(E):(E-=65536,g+=String.fromCharCode(55296|E>>10,56320|1023&E))}}else g+=String.fromCharCode(E)}return g},hn=(p,d,h)=>(p>>>=0)?yk((v(),K),p,d,h):"";function bk(p,d,h){return n?Ge(3,1,p,d,h):0}function vk(p,d){if(n)return Ge(4,1,p,d)}function kk(p,d){if(n)return Ge(5,1,p,d)}function Ek(p,d,h){if(n)return Ge(6,1,p,d,h)}function Ak(p,d,h){return n?Ge(7,1,p,d,h):0}function Tk(p,d){if(n)return Ge(8,1,p,d)}function Sk(p,d,h){if(n)return Ge(9,1,p,d,h)}function Mk(p,d,h,g){if(n)return Ge(10,1,p,d,h,g)}function Ok(p,d,h,g){if(n)return Ge(11,1,p,d,h,g)}function Ik(p,d,h,g){if(n)return Ge(12,1,p,d,h,g)}function Ck(p){if(n)return Ge(13,1,p)}function Pk(p,d){if(n)return Ge(14,1,p,d)}function Nk(p,d,h){if(n)return Ge(15,1,p,d,h)}var OO=()=>ie(""),cr=p=>{p>>>=0;for(var d="";;){var h=(v(),K)[p++>>>0];if(!h)return d;d+=String.fromCharCode(h)}},Rf={},Bf={},IO={},gn=class extends Error{constructor(p){super(p),this.name="BindingError"}};function yr(p,d,h={}){return(function(g,E,T={}){var N=E.name;if(!g)throw new gn(`type "${N}" must have a positive integer typeid pointer`);if(Bf.hasOwnProperty(g)){if(T.ve)return;throw new gn(`Cannot register type '${N}' twice`)}Bf[g]=E,delete IO[g],Rf.hasOwnProperty(g)&&(E=Rf[g],delete Rf[g],E.forEach(P=>P()))})(p,d,h)}var Lk=(p,d,h)=>{switch(d){case 1:return h?g=>(v(),F)[g>>>0]:g=>(v(),K)[g>>>0];case 2:return h?g=>(v(),Y)[g>>>1>>>0]:g=>(v(),Q)[g>>>1>>>0];case 4:return h?g=>(v(),B)[g>>>2>>>0]:g=>(v(),I)[g>>>2>>>0];case 8:return h?g=>(v(),Z)[g>>>3>>>0]:g=>(v(),me)[g>>>3>>>0];default:throw new TypeError(`invalid integer width (${d}): ${p}`)}};function CO(p,d,h,g,E){p>>>=0,h>>>=0,d=cr(d>>>0);let T=N=>N;if(g=g===0n){let N=8*h;T=P=>BigInt.asUintN(N,P),E=T(E)}yr(p,{name:d,Wc:T,cd:(N,P)=>(typeof P=="number"&&(P=BigInt(P)),P),bd:Lk(d,h,!g),dd:null})}function PO(p,d,h,g){yr(p>>>=0,{name:d=cr(d>>>0),Wc:function(E){return!!E},cd:function(E,T){return T?h:g},bd:function(E){return this.Wc((v(),K)[E>>>0])},dd:null})}var zk=[],bs=[0,1,,1,null,1,!0,1,!1,1];function Df(p){9<(p>>>=0)&&--bs[p+1]===0&&(bs[p]=void 0,zk.push(p))}var Ut=p=>{if(!p)throw new gn(`Cannot use deleted val. handle = ${p}`);return bs[p]},Kt=p=>{switch(p){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let d=zk.pop()||bs.length;return bs[d]=p,bs[d+1]=1,d}};function Uf(p){return this.Wc((v(),I)[p>>>2>>>0])}var NO={name:"emscripten::val",Wc:p=>{var d=Ut(p);return Df(p),d},cd:(p,d)=>Kt(d),bd:Uf,dd:null};function LO(p){return yr(p>>>0,NO)}var zO=(p,d)=>{switch(d){case 4:return function(h){return this.Wc((v(),oe)[h>>>2>>>0])};case 8:return function(h){return this.Wc((v(),J)[h>>>3>>>0])};default:throw new TypeError(`invalid float width (${d}): ${p}`)}};function $O(p,d,h){h>>>=0,yr(p>>>=0,{name:d=cr(d>>>0),Wc:g=>g,cd:(g,E)=>E,bd:zO(d,h),dd:null})}function RO(p,d,h,g,E){p>>>=0,h>>>=0,d=cr(d>>>0);let T=P=>P;if(g===0){var N=32-8*h;T=P=>P<>>N,E=T(E)}yr(p,{name:d,Wc:T,cd:(P,R)=>R,bd:Lk(d,h,g!==0),dd:null})}function BO(p,d,h){function g(T){var N=(v(),I)[T>>>2>>>0];return T=(v(),I)[T+4>>>2>>>0],new E((v(),F).buffer,T,N)}var E=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][d];yr(p>>>=0,{name:h=cr(h>>>0),Wc:g,bd:g},{ve:!0})}var br=(p,d,h)=>{var g=(v(),K);if(d>>>=0,0=N){if(d>=h)break;g[d++>>>0]=N}else if(2047>=N){if(d+1>=h)break;g[d++>>>0]=192|N>>6,g[d++>>>0]=128|63&N}else if(65535>=N){if(d+2>=h)break;g[d++>>>0]=224|N>>12,g[d++>>>0]=128|N>>6&63,g[d++>>>0]=128|63&N}else{if(d+3>=h)break;g[d++>>>0]=240|N>>18,g[d++>>>0]=128|N>>12&63,g[d++>>>0]=128|N>>6&63,g[d++>>>0]=128|63&N,T++}}g[d>>>0]=0,p=d-E}else p=0;return p},vr=p=>{for(var d=0,h=0;h=g?d++:2047>=g?d+=2:55296<=g&&57343>=g?(d+=4,++h):d+=3}return d};function DO(p,d){yr(p>>>=0,{name:d=cr(d>>>0),Wc(h){var g=(v(),I)[h>>>2>>>0];return g=hn(h+4,g,!0),Ft(h),g},cd(h,g){g instanceof ArrayBuffer&&(g=new Uint8Array(g));var E=typeof g=="string";if(!(E||ArrayBuffer.isView(g)&&g.BYTES_PER_ELEMENT==1))throw new gn("Cannot pass non-string to std::string");var T=E?vr(g):g.length,N=ks(4+T+1),P=N+4;return(v(),I)[N>>>2>>>0]=T,E?br(g,P,T+1):(v(),K).set(g,P>>>0),h!==null&&h.push(Ft,N),N},bd:Uf,dd(h){Ft(h)}})}var $k=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,UO=(p,d,h)=>{if(p>>>=1,16<(d=xk((v(),Q),p,d/2,h))-p&&$k)return $k.decode((v(),Q).slice(p,d));for(h="";p>>0];h+=String.fromCharCode(g)}return h},FO=(p,d,h)=>{if(h??=2147483647,2>h)return 0;var g=d;h=(h-=2)<2*p.length?h/2:p.length;for(var E=0;E>>1>>>0]=T,d+=2}return(v(),Y)[d>>>1>>>0]=0,d-g},GO=p=>2*p.length,jO=(p,d,h)=>{var g="";p>>>=2;for(var E=0;!(E>=d/4);E++){var T=(v(),I)[p+E>>>0];if(!T&&!h)break;g+=String.fromCodePoint(T)}return g},qO=(p,d,h)=>{if(d>>>=0,h??=2147483647,4>h)return 0;var g=d;h=g+h-4;for(var E=0;E>>2>>>0]=T,(d+=4)+4>h)break}return(v(),B)[d>>>2>>>0]=0,d-g},WO=p=>{for(var d=0,h=0;h>>=0,d>>>=0,h=cr(h>>>=0),d===2)var g=UO,E=FO,T=GO;else g=jO,E=qO,T=WO;yr(p,{name:h,Wc:N=>{var P=(v(),I)[N>>>2>>>0];return P=g(N+4,P*d,!0),Ft(N),P},cd:(N,P)=>{if(typeof P!="string")throw new gn(`Cannot pass non-string to C++ string type ${h}`);var R=T(P),H=ks(4+R+d);return(v(),I)[H>>>2>>>0]=R/d,E(P,H+4,R+d),N!==null&&N.push(Ft,H),H},bd:Uf,dd(N){Ft(N)}})}function HO(p,d){yr(p>>>=0,{we:!0,name:d=cr(d>>>0),Wc:()=>{},cd:()=>{}})}function XO(p){rd(p>>>0,!s,1,!r,131072,!1),pk()}var St=p=>{if(!O)try{if(p(),!(0Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function Ff(p){p>>>=0,KO||(Atomics.waitAsync((v(),B),p>>>2,p).value.then(wc),p+=128,Atomics.store((v(),B),p>>>2,1))}var wc=()=>St(()=>{var p=Tc();p&&(Ff(p),IE())});function YO(p,d){(p>>>=0)==d>>>0?setTimeout(wc):n?postMessage({gd:p,$c:"checkMailbox"}):(p=ys[p])&&p.postMessage({$c:"checkMailbox"})}var Gf=[];function QO(p,d,h,g,E){for(d>>>=0,E>>>=0,Gf.length=0,h=E>>>3,g=E+g>>>3;h>>0]?(v(),Z)[h++>>>0]:(v(),J)[h++>>>0],Gf.push(T)}return(d?id[d]:GC[p])(...Gf)}var JO=()=>{Pe=0};function ZO(p){p>>>=0,n?postMessage({$c:"cleanupThread",Le:p}):uk(ys[p])}function eI(p){}var xc=p=>{try{p()}catch(d){ie(d)}};function tI(p){var d=(...h)=>{yc.push(p);try{return p(...h)}finally{O||(yc.pop(),ur&&$r===1&&yc.length===0&&($r=0,Pe+=1,xc(yA),typeof Fibers<"u"&&Fibers.We()))}};return Dk.set(p,d),d}var $r=0,ur=null,Rk=0,yc=[],jf=new Map,Bk=new Map,Dk=new Map,rI=0,qf=null,sI=[],Uk=p=>(function(d){if(!O){if($r===0){var h=!1,g=!1;d((E=0)=>{if(!O&&(Rk=E,h=!0,g)){$r=2,xc(()=>bA(ur)),typeof MainLoop<"u"&&MainLoop.se&&MainLoop.resume(),E=!1;try{var T=(function(){var R=(v(),B)[ur+8>>>2>>>0];return R=Bk.get(R),R=Dk.get(R),--Pe,R()})()}catch(R){T=R,E=!0}var N=!1;if(!ur){var P=qf;P&&(qf=null,(E?P.reject:P.resolve)(T),N=!0)}if(E&&!N)throw T}}),g=!0,h||($r=1,ur=(function(){var E=ks(65548),T=E+12;if((v(),I)[E>>>2>>>0]=T,(v(),I)[E+4>>>2>>>0]=T+65536,T=yc[0],!jf.has(T)){var N=rI++;jf.set(T,N),Bk.set(N,T)}return T=jf.get(T),(v(),B)[E+8>>>2>>>0]=T,E})(),typeof MainLoop<"u"&&MainLoop.se&&MainLoop.pause(),xc(()=>xA(ur)))}else $r===2?($r=0,xc(vA),Ft(ur),ur=null,sI.forEach(St)):ie(`invalid state: ${$r}`);return Rk}})(d=>{p().then(d)});function nI(p){return p>>>=0,Uk(async()=>{var d=await Ut(p);return Kt(d)})}var Wf=[],oI=p=>{var d=Wf.length;return Wf.push(p),d},aI=(p,d)=>{for(var h=Array(p),g=0;g>>2>>>0],N=Bf[T];if(N===void 0)throw p=`parameter ${g}`,T=pE(T),d=cr(T),Ft(T),new gn(`${p} has unknown type ${d}`);h[E]=N}return h},iI=(p,d,h)=>{var g=[];return p=p(g,h),g.length&&((v(),I)[d>>>2>>>0]=Kt(g)),p},lI={},bc=p=>{var d=lI[p];return d===void 0?cr(p):d};function cI(p,d,h){var[g,...E]=aI(p,d>>>0);d=g.cd.bind(g);var T=E.map(R=>R.bd.bind(R));p--;var N={toValue:Ut};switch(p=T.map((R,H)=>{var xe=`argFromPtr${H}`;return N[xe]=R,`${xe}(args${H?"+"+8*H:""})`}),h){case 0:var P="toValue(handle)";break;case 2:P="new (toValue(handle))";break;case 3:P="";break;case 1:N.getStringOrSymbol=bc,P="toValue(handle)[getStringOrSymbol(methodName)]"}return P+=`(${p})`,g.we||(N.toReturnWire=d,N.emval_returnValue=iI,P=`return emval_returnValue(toReturnWire, destructorsRef, ${P})`),P=`return function (handle, methodName, destructorsRef, args) { + ${P} + }`,h=new Function(Object.keys(N),P)(...Object.values(N)),P=`methodCaller<(${E.map(R=>R.name)}) => ${g.name}>`,oI(Object.defineProperty(h,"name",{value:P}))}function uI(p,d){return d>>>=0,(p=Ut(p>>>0))==Ut(d)}function pI(p){return(p>>>=0)?(p=bc(p),Kt(globalThis[p])):Kt(globalThis)}function fI(p){return p=bc(p>>>0),Kt(e[p])}function dI(p,d){return d>>>=0,p=Ut(p>>>0),d=Ut(d),Kt(p[d])}function mI(p){9<(p>>>=0)&&(bs[p+1]+=1)}function Fk(p,d,h,g,E){return Wf[p>>>0](d>>>0,h>>>0,g>>>0,E>>>0)}function _I(p,d,h,g,E){return Fk(p>>>0,d>>>0,h>>>0,g>>>0,E>>>0)}function hI(){return Kt([])}function gI(p){p=Ut(p>>>0);for(var d=Array(p.length),h=0;h>>0))}function xI(){return Kt({})}function yI(p){for(var d=Ut(p>>>=0);d.length;){var h=d.pop();d.pop()(h)}Df(p)}function bI(p,d,h){d>>>=0,h>>>=0,p=Ut(p>>>0),d=Ut(d),h=Ut(h),p[d]=h}function vI(p,d){p=gt(p),d>>>=0,p=new Date(1e3*p),(v(),B)[d>>>2>>>0]=p.getUTCSeconds(),(v(),B)[d+4>>>2>>>0]=p.getUTCMinutes(),(v(),B)[d+8>>>2>>>0]=p.getUTCHours(),(v(),B)[d+12>>>2>>>0]=p.getUTCDate(),(v(),B)[d+16>>>2>>>0]=p.getUTCMonth(),(v(),B)[d+20>>>2>>>0]=p.getUTCFullYear()-1900,(v(),B)[d+24>>>2>>>0]=p.getUTCDay(),p=(p.getTime()-Date.UTC(p.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,(v(),B)[d+28>>>2>>>0]=p}var Gk=p=>p%4==0&&(p%100!=0||p%400==0),jk=[0,31,60,91,121,152,182,213,244,274,305,335],qk=[0,31,59,90,120,151,181,212,243,273,304,334];function kI(p,d){p=gt(p),d>>>=0,p=new Date(1e3*p),(v(),B)[d>>>2>>>0]=p.getSeconds(),(v(),B)[d+4>>>2>>>0]=p.getMinutes(),(v(),B)[d+8>>>2>>>0]=p.getHours(),(v(),B)[d+12>>>2>>>0]=p.getDate(),(v(),B)[d+16>>>2>>>0]=p.getMonth(),(v(),B)[d+20>>>2>>>0]=p.getFullYear()-1900,(v(),B)[d+24>>>2>>>0]=p.getDay();var h=(Gk(p.getFullYear())?jk:qk)[p.getMonth()]+p.getDate()-1|0;(v(),B)[d+28>>>2>>>0]=h,(v(),B)[d+36>>>2>>>0]=-60*p.getTimezoneOffset(),h=new Date(p.getFullYear(),6,1).getTimezoneOffset();var g=new Date(p.getFullYear(),0,1).getTimezoneOffset();p=0|(h!=g&&p.getTimezoneOffset()==Math.min(g,h)),(v(),B)[d+32>>>2>>>0]=p}function EI(p){p>>>=0;var d=new Date((v(),B)[p+20>>>2>>>0]+1900,(v(),B)[p+16>>>2>>>0],(v(),B)[p+12>>>2>>>0],(v(),B)[p+8>>>2>>>0],(v(),B)[p+4>>>2>>>0],(v(),B)[p>>>2>>>0],0),h=(v(),B)[p+32>>>2>>>0],g=d.getTimezoneOffset(),E=new Date(d.getFullYear(),6,1).getTimezoneOffset(),T=new Date(d.getFullYear(),0,1).getTimezoneOffset(),N=Math.min(T,E);return 0>h?(v(),B)[p+32>>>2>>>0]=+(E!=T&&N==g):0>>2>>>0]=d.getDay(),h=(Gk(d.getFullYear())?jk:qk)[d.getMonth()]+d.getDate()-1|0,(v(),B)[p+28>>>2>>>0]=h,(v(),B)[p>>>2>>>0]=d.getSeconds(),(v(),B)[p+4>>>2>>>0]=d.getMinutes(),(v(),B)[p+8>>>2>>>0]=d.getHours(),(v(),B)[p+12>>>2>>>0]=d.getDate(),(v(),B)[p+16>>>2>>>0]=d.getMonth(),(v(),B)[p+20>>>2>>>0]=d.getYear(),p=d.getTime(),BigInt(isNaN(p)?-1:p/1e3)}function Wk(p,d,h,g,E,T,N){return n?Ge(16,1,p,d,h,g,E,T,N):-52}function Vk(p,d,h,g,E,T){if(n)return Ge(17,1,p,d,h,g,E,T)}var To={},AI=()=>performance.timeOrigin+performance.now();function Hk(p,d){if(n)return Ge(18,1,p,d);if(To[p]&&(clearTimeout(To[p].id),delete To[p]),!d)return 0;var h=setTimeout(()=>{delete To[p],St(()=>OE(p,performance.timeOrigin+performance.now()))},d);return To[p]={id:h,Ve:d},0}function TI(p,d,h,g){p>>>=0,d>>>=0,h>>>=0,g>>>=0;var E=new Date().getFullYear(),T=new Date(E,0,1).getTimezoneOffset();E=new Date(E,6,1).getTimezoneOffset();var N=Math.max(T,E);(v(),I)[p>>>2>>>0]=60*N,(v(),B)[d>>>2>>>0]=+(T!=E),p=(d=P=>{var R=Math.abs(P);return`UTC${0<=P?"-":"+"}${String(Math.floor(R/60)).padStart(2,"0")}${String(R%60).padStart(2,"0")}`})(T),d=d(E),EDate.now(),MI=1;function OI(p,d,h){if(h>>>=0,!(0<=p&&3>=p))return 28;if(p===0)p=Date.now();else{if(!MI)return 52;p=performance.timeOrigin+performance.now()}return p=Math.round(1e6*p),(v(),Z)[h>>>3>>>0]=BigInt(p),0}var Vf=[],Xk=(p,d)=>{Vf.length=0;for(var h;h=(v(),K)[p++>>>0];){var g=h!=105;d+=(g&=h!=112)&&d%8?4:0,Vf.push(h==112?(v(),I)[d>>>2>>>0]:h==106?(v(),Z)[d>>>3>>>0]:h==105?(v(),B)[d>>>2>>>0]:(v(),J)[d>>>3>>>0]),d+=g?8:4}return Vf};function II(p,d,h){return p>>>=0,d=Xk(d>>>0,h>>>0),id[p](...d)}function CI(p,d,h){return p>>>=0,d=Xk(d>>>0,h>>>0),id[p](...d)}var PI=()=>{};function NI(p,d){return S(hn(p>>>0,d>>>0))}var LI=()=>{throw Pe+=1,"unwind"};function zI(){return 4294901760}var $I=()=>1,RI=()=>navigator.hardwareConcurrency,vs={},Kk=p=>{var d=vr(p)+1,h=ks(d);return h&&br(p,h,d),h},vc=p=>{var d;return(d=/\bwasm-function\[\d+\]:(0x[0-9a-f]+)/.exec(p))?+d[1]:(d=/:(\d+):\d+(?:\)|$)/.exec(p))?2147483648|+d[1]:0},Yk=p=>{for(var d of p)(p=vc(d))&&(vs[p]=d)};function BI(){var p=Error().stack.toString().split(` +`);return p[0]=="Error"&&p.shift(),Yk(p),vs.ee=vc(p[3]),vs.xe=p,vs.ee}function kc(p){if(!(p=vs[p>>>0]))return 0;var d;if(d=/^\s+at .*\.wasm\.(.*) \(.*\)$/.exec(p))p=d[1];else if(d=/^\s+at (.*) \(.*\)$/.exec(p))p=d[1];else{if(!(d=/^(.+?)@/.exec(p)))return 0;p=d[1]}return Ft(kc.ne??0),kc.ne=Kk(p),kc.ne}function DI(p){p>>>=0;var d=(v(),K).length;if(p<=d||4294901760=h;h*=2){var g=d*(1+.2/h);g=Math.min(g,p+100663296);e:{g=(Math.min(4294901760,65536*Math.ceil(Math.max(p,g)/65536))-zr.buffer.byteLength+65535)/65536|0;try{zr.grow(g),G();var E=1;break e}catch{}E=void 0}if(E)return!0}return!1}function UI(p,d,h){if(p>>>=0,d>>>=0,vs.ee==p)var g=vs.xe;else(g=Error().stack.toString().split(` +`))[0]=="Error"&&g.shift(),Yk(g);for(var E=3;g[E]&&vc(g[E])!=p;)++E;for(p=0;p>>2>>>0]=vc(g[p+E]);return p}var pr=p=>{var d=vr(p)+1,h=Sc(d);return br(p,h,d),h},wn=p=>(v(),I)[p>>>2>>>0]+4294967296*(v(),B)[p+4>>>2>>>0],wt=[],Qk=(p,d)=>{wt[p>>>0]=d},kr=[],Ec=[],xn=(p,d)=>{Ec[p]=new Promise(h=>d.finally(()=>h(p)))},ae=p=>{if(p)return wt[p>>>0]},Hf=(p,d)=>{for(p=(v(),I)[p>>>2>>>0];p;p=(v(),I)[p>>>2>>>0])d[(v(),B)[p+4>>>2>>>0]](p)},Ac=(p,d,h)=>{(v(),I)[p>>>2>>>0]=d,(v(),I)[p+4>>>2>>>0]=h},Jk=p=>{var d=(v(),I)[p>>>2>>>0];return p=(v(),I)[p+4>>>2>>>0],hn(d,p)},Yt=p=>{var d=(v(),I)[p>>>2>>>0];return p=(v(),I)[p+4>>>2>>>0],d?hn(d,p):p===0?"":void 0},FI=p=>{var d=Yt(p+4),h=(h=(v(),I)[p+12>>>2>>>0])?ae(h):"auto";if(p+=16){var g=ae((v(),I)[p+4>>>2>>>0]),E=(v(),I)[p+16>>>2>>>0],T=(v(),I)[p+20>>>2>>>0];if(E){for(var N={},P=0;P>>3>>>0]}E=N}else E=void 0;p={module:g,constants:E,entryPoint:Yt(p+8)}}else p=void 0;return{label:d,layout:h,compute:p}},Zk=(p,d)=>{function h(T,N,P,R=0){T=p[T]??R,(v(),I)[N+P>>>2>>>0]=T}function g(T,N,P,R=0){N+=P,T=p[T]??R,(v(),I)[N>>>2>>>0]=T,R=(v(),I)[N>>>2>>>0],(v(),I)[N+4>>>2>>>0]=(T-R)/4294967296}var E=(v(),I)[d>>>2>>>0];h("maxTextureDimension1D",d,4),h("maxTextureDimension2D",d,8),h("maxTextureDimension3D",d,12),h("maxTextureArrayLayers",d,16),h("maxBindGroups",d,20),h("maxBindGroupsPlusVertexBuffers",d,24),h("maxBindingsPerBindGroup",d,28),h("maxDynamicUniformBuffersPerPipelineLayout",d,32),h("maxDynamicStorageBuffersPerPipelineLayout",d,36),h("maxSampledTexturesPerShaderStage",d,40),h("maxSamplersPerShaderStage",d,44),h("maxStorageBuffersPerShaderStage",d,48),h("maxStorageTexturesPerShaderStage",d,52),h("maxUniformBuffersPerShaderStage",d,56),h("minUniformBufferOffsetAlignment",d,80),h("minStorageBufferOffsetAlignment",d,84),g("maxUniformBufferBindingSize",d,64),g("maxStorageBufferBindingSize",d,72),h("maxVertexBuffers",d,88),g("maxBufferSize",d,96),h("maxVertexAttributes",d,104),h("maxVertexBufferArrayStride",d,108),h("maxInterStageShaderVariables",d,112),h("maxColorAttachments",d,116),h("maxColorAttachmentBytesPerSample",d,120),h("maxComputeWorkgroupStorageSize",d,124),h("maxComputeInvocationsPerWorkgroup",d,128),h("maxComputeWorkgroupSizeX",d,132),h("maxComputeWorkgroupSizeY",d,136),h("maxComputeWorkgroupSizeZ",d,140),h("maxComputeWorkgroupsPerDimension",d,144),h("maxImmediateSize",d,148),E!==0&&(v(),h("maxStorageBuffersInVertexStage",E,8,p.maxStorageBuffersPerShaderStage),h("maxStorageBuffersInFragmentStage",E,16,p.maxStorageBuffersPerShaderStage),h("maxStorageTexturesInVertexStage",E,12,p.maxStorageTexturesPerShaderStage),h("maxStorageTexturesInFragmentStage",E,20,p.maxStorageTexturesPerShaderStage))},GI=(p,d)=>{(v(),I)[d+52>>>2>>>0]=p.subgroupMinSize,(v(),I)[d+56>>>2>>>0]=p.subgroupMaxSize;var h=Kk(p.vendor+p.architecture+p.device+p.description),g=vr(p.vendor);Ac(d+4,h,g),h+=g,g=vr(p.architecture),Ac(d+12,h,g),h+=g,g=vr(p.device),Ac(d+20,h,g),h+=g,g=vr(p.description),Ac(d+28,h,g),h+=g,(v(),B)[d+36>>>2>>>0]=2,h=p.isFallbackAdapter?3:4,(v(),B)[d+40>>>2>>>0]=h,(v(),I)[d+44>>>2>>>0]=0,(v(),I)[d+48>>>2>>>0]=0,Hf(d,{327739:E=>{let T=0,N=0;if(p.subgroupMatrixConfigs){T=p.subgroupMatrixConfigs.length,N=ks(20*T);for(let[P,R]of p.subgroupMatrixConfigs.entries()){let H=N+20*P,xe=tE.indexOf(R.componentType),ve=tE.indexOf(R.resultComponentType);(v(),B)[H>>>2>>>0]=xe,(v(),B)[H+4>>>2>>>0]=ve,(v(),I)[H+8>>>2>>>0]=R.M,(v(),I)[H+12>>>2>>>0]=R.N,(v(),I)[H+16>>>2>>>0]=R.K}}(v(),I)[E+12>>>2>>>0]=N,(v(),I)[E+8>>>2>>>0]=T}})},jI=[,,"uniform","storage","read-only-storage"],qI=[,"validation","out-of-memory","internal"],WI=[,"compatibility","core"],eE={1:"core-features-and-limits",2:"depth-clip-control",3:"depth32float-stencil8",4:"texture-compression-bc",5:"texture-compression-bc-sliced-3d",6:"texture-compression-etc2",7:"texture-compression-astc",8:"texture-compression-astc-sliced-3d",9:"timestamp-query",10:"indirect-first-instance",11:"shader-f16",12:"rg11b10ufloat-renderable",13:"bgra8unorm-storage",14:"float32-filterable",15:"float32-blendable",16:"clip-distances",17:"dual-source-blending",18:"subgroups",19:"texture-formats-tier1",20:"texture-formats-tier2",21:"primitive-index",22:"texture-component-swizzle",23:"subgroup-size-control",327692:"chromium-experimental-unorm16-texture-formats",327729:"chromium-experimental-multi-draw-indirect",327732:"chromium-experimental-subgroup-matrix"},VI=[,"low-power","high-performance"],HI=[,"occlusion","timestamp"],XI=[,,"filtering","non-filtering","comparison"],KI=[,,"write-only","read-only","read-write"],tE=[,"f32","f16","u32","i32","u8","i8"],YI=[,"r8unorm","r8snorm","r8uint","r8sint","r16unorm","r16snorm","r16uint","r16sint","r16float","rg8unorm","rg8snorm","rg8uint","rg8sint","r32float","r32uint","r32sint","rg16unorm","rg16snorm","rg16uint","rg16sint","rg16float","rgba8unorm","rgba8unorm-srgb","rgba8snorm","rgba8uint","rgba8sint","bgra8unorm","bgra8unorm-srgb","rgb10a2uint","rgb10a2unorm","rg11b10ufloat","rgb9e5ufloat","rg32float","rg32uint","rg32sint","rgba16unorm","rgba16snorm","rgba16uint","rgba16sint","rgba16float","rgba32float","rgba32uint","rgba32sint","stencil8","depth16unorm","depth24plus","depth24plus-stencil8","depth32float","depth32float-stencil8","bc1-rgba-unorm","bc1-rgba-unorm-srgb","bc2-rgba-unorm","bc2-rgba-unorm-srgb","bc3-rgba-unorm","bc3-rgba-unorm-srgb","bc4-r-unorm","bc4-r-snorm","bc5-rg-unorm","bc5-rg-snorm","bc6h-rgb-ufloat","bc6h-rgb-float","bc7-rgba-unorm","bc7-rgba-unorm-srgb","etc2-rgb8unorm","etc2-rgb8unorm-srgb","etc2-rgb8a1unorm","etc2-rgb8a1unorm-srgb","etc2-rgba8unorm","etc2-rgba8unorm-srgb","eac-r11unorm","eac-r11snorm","eac-rg11unorm","eac-rg11snorm","astc-4x4-unorm","astc-4x4-unorm-srgb","astc-5x4-unorm","astc-5x4-unorm-srgb","astc-5x5-unorm","astc-5x5-unorm-srgb","astc-6x5-unorm","astc-6x5-unorm-srgb","astc-6x6-unorm","astc-6x6-unorm-srgb","astc-8x5-unorm","astc-8x5-unorm-srgb","astc-8x6-unorm","astc-8x6-unorm-srgb","astc-8x8-unorm","astc-8x8-unorm-srgb","astc-10x5-unorm","astc-10x5-unorm-srgb","astc-10x6-unorm","astc-10x6-unorm-srgb","astc-10x8-unorm","astc-10x8-unorm-srgb","astc-10x10-unorm","astc-10x10-unorm-srgb","astc-12x10-unorm","astc-12x10-unorm-srgb","astc-12x12-unorm","astc-12x12-unorm-srgb"],QI=[,,"float","unfilterable-float","depth","sint","uint"],rE=[,"1d","2d","2d-array","cube","cube-array","3d"],JI={undefined:1,unknown:1,destroyed:2};function ZI(p,d,h,g,E,T){d=gt(d),h=gt(h),g>>>=0,E>>>=0,T>>>=0;var N=ae(p>>>0);if(p={},T){var P=(v(),I)[T+12>>>2>>>0];if(P){var R=(v(),I)[T+16>>>2>>>0];p.requiredFeatures=Array.from((v(),I).subarray(R>>>2>>>0,R+4*P>>>2>>>0),ee=>eE[ee])}if(P=(v(),I)[T+20>>>2>>>0]){let ee=function(Mt,Et,Es,As=!1){Et+=Es,(Et=(v(),I)[Et>>>2>>>0])==4294967295||As&&Et==0||(ve[Mt]=Et)},Be=function(Mt,Et,Es){Et+=Es,Es=(v(),I)[Et>>>2>>>0];var As=(v(),I)[Et+4>>>2>>>0];Es==4294967295&&As==4294967295||(ve[Mt]=wn(Et))};var H=ee,xe=Be;R=(v(),I)[P>>>2>>>0];var ve={};ee("maxTextureDimension1D",P,4),ee("maxTextureDimension2D",P,8),ee("maxTextureDimension3D",P,12),ee("maxTextureArrayLayers",P,16),ee("maxBindGroups",P,20),ee("maxBindGroupsPlusVertexBuffers",P,24),ee("maxBindingsPerBindGroup",P,28),ee("maxDynamicUniformBuffersPerPipelineLayout",P,32),ee("maxDynamicStorageBuffersPerPipelineLayout",P,36),ee("maxSampledTexturesPerShaderStage",P,40),ee("maxSamplersPerShaderStage",P,44),ee("maxStorageBuffersPerShaderStage",P,48),ee("maxStorageTexturesPerShaderStage",P,52),ee("maxUniformBuffersPerShaderStage",P,56),ee("minUniformBufferOffsetAlignment",P,80),ee("minStorageBufferOffsetAlignment",P,84),Be("maxUniformBufferBindingSize",P,64),Be("maxStorageBufferBindingSize",P,72),ee("maxVertexBuffers",P,88),Be("maxBufferSize",P,96),ee("maxVertexAttributes",P,104),ee("maxVertexBufferArrayStride",P,108),ee("maxInterStageShaderVariables",P,112),ee("maxColorAttachments",P,116),ee("maxColorAttachmentBytesPerSample",P,120),ee("maxComputeWorkgroupStorageSize",P,124),ee("maxComputeInvocationsPerWorkgroup",P,128),ee("maxComputeWorkgroupSizeX",P,132),ee("maxComputeWorkgroupSizeY",P,136),ee("maxComputeWorkgroupSizeZ",P,140),ee("maxComputeWorkgroupsPerDimension",P,144),ee("maxImmediateSize",P,148,!0),R!==0&&(v(),"maxStorageBuffersInVertexStage"in GPUSupportedLimits.prototype&&(ee("maxStorageBuffersInVertexStage",R,8),ee("maxStorageTexturesInVertexStage",R,12),ee("maxStorageBuffersInFragmentStage",R,16),ee("maxStorageTexturesInFragmentStage",R,20))),p.requiredLimits=ve}(P=(v(),I)[T+24>>>2>>>0])&&(P={label:Yt(P+4)},p.defaultQueue=P),p.label=Yt(T+4)}Pe+=1,xn(d,N.requestDevice(p).then(ee=>{--Pe,St(()=>{wt[E>>>0]=ee.queue,wt[g>>>0]=ee,Pe+=1,xn(h,ee.lost.then(Be=>{St(()=>{ee.onuncapturederror=()=>{};var Mt=ue(),Et=pr(Be.message);Jf(h,JI[Be.reason],Et),ce(Mt)}),--Pe})),ee.onuncapturederror=Be=>{var Mt=5;Be.error instanceof GPUValidationError?Mt=2:Be.error instanceof GPUOutOfMemoryError?Mt=3:Be.error instanceof GPUInternalError&&(Mt=4);var Et=ue();Be=pr(Be.error.message),AE(g,Mt,Be),ce(Et)},"adapterInfo"in ee||(ee.adapterInfo=N.info),td(d,1,g,0)})},ee=>{--Pe,St(()=>{var Be=ue(),Mt=pr(ee.message);td(d,3,g,Mt),h&&Jf(h,4,Mt),ce(Be)})}))}function eC(p){var d=ae(p>>>=0),h=kr[p];if(h){for(var g=0;g>>=0;var g=ae(p>>>=0);h==4294967295&&(h=void 0);try{var E=g.getMappedRange(d>>>0,h)}catch{return 0}var T=nd(16,E.byteLength);return(v(),K).set(new Uint8Array(E),T>>>0),kr[p].push(()=>Ft(T)),T}function rC(p,d,h){h>>>=0;var g=ae(p>>>=0);h==4294967295&&(h=void 0);try{var E=g.getMappedRange(d>>>0,h)}catch{return 0}var T=nd(16,E.byteLength);return(v(),K).fill(0,T,E.byteLength),kr[p].push(()=>{new Uint8Array(E).set((v(),K).subarray(T>>>0,T+E.byteLength>>>0)),Ft(T)}),T}function sC(p,d,h,g,E){p>>>=0,d=gt(d),h=gt(h),E>>>=0;var T=ae(p);kr[p]=[],E==4294967295&&(E=void 0),Pe+=1,xn(d,T.mapAsync(h,g>>>0,E).then(()=>{--Pe,St(()=>{Zf(d,1,0)})},N=>{--Pe,St(()=>{ue();var P=pr(N.message);Zf(d,N.name==="AbortError"?4:N.name==="OperationError"?3:0,P),delete kr[p]})}))}function nC(p){var d=ae(p>>>=0),h=kr[p];if(h){for(var g=0;g>>0]}function aC(p,d,h){p>>>=0,d>>>=0,h>>>=0;var g=!!(v(),I)[d+32>>>2>>>0];d={label:Yt(d+4),usage:(v(),I)[d+16>>>2>>>0],size:wn(d+24),mappedAtCreation:g},p=ae(p);try{var E=p.createBuffer(d)}catch{return!1}return wt[h>>>0]=E,g&&(kr[h]=[]),!0}function iC(p,d,h,g){p>>>=0,d=gt(d),g>>>=0,h=FI(h>>>0),p=ae(p),Pe+=1,xn(d,p.createComputePipelineAsync(h).then(E=>{--Pe,St(()=>{wt[g>>>0]=E,Qf(d,1,g,0)})},E=>{--Pe,St(()=>{var T=ue(),N=pr(E.message);Qf(d,E.reason==="validation"?3:E.reason==="internal"?4:0,g,N),ce(T)})}))}function lC(p,d,h){p>>>=0,d>>>=0,h>>>=0;var g=(v(),I)[d>>>2>>>0],E=(v(),B)[g+4>>>2>>>0];d={label:Yt(d+4),code:""},E===2&&(d.code=Jk(g+8)),p=ae(p).createShaderModule(d),wt[h>>>0]=p}var cC=p=>{(p=ae(p)).onuncapturederror=null,p.destroy()};function uC(p,d){d=gt(d),p=ae(p>>>0),Pe+=1,xn(d,p.popErrorScope().then(h=>{--Pe,St(()=>{var g=5;h?h instanceof GPUValidationError?g=2:h instanceof GPUOutOfMemoryError?g=3:h instanceof GPUInternalError&&(g=4):g=1;var E=ue(),T=h?pr(h.message):0;ed(d,1,g,T),ce(E)})},h=>{--Pe,St(()=>{var g=ue(),E=pr(h.message);ed(d,1,5,E),ce(g)})}))}function pC(p,d,h,g){if(d=gt(d),g>>>=0,h>>>=0){var E={featureLevel:WI[(v(),B)[h+4>>>2>>>0]],powerPreference:VI[(v(),B)[h+8>>>2>>>0]],forceFallbackAdapter:!!(v(),I)[h+12>>>2>>>0]};(p=(v(),I)[h>>>2>>>0])!==0&&(v(),E.Ye=!!(v(),I)[p+8>>>2>>>0])}"gpu"in navigator?(Pe+=1,xn(d,navigator.gpu.requestAdapter(E).then(T=>{--Pe,St(()=>{if(T)wt[g>>>0]=T,So(d,1,g,0);else{var N=ue(),P=pr("WebGPU not available on this browser (requestAdapter returned null)");So(d,3,g,P),ce(N)}})},T=>{--Pe,St(()=>{var N=ue(),P=pr(T.message);So(d,4,g,P),ce(N)})}))):(E=ue(),p=pr("WebGPU not available on this browser (navigator.gpu is not available)"),So(d,3,g,p),ce(E))}function fC(p,d,h){return p>>>=0,d>>>=0,h>>>=0,Uk(async()=>{var g=[];if(h){var E=(v(),B)[h>>>2>>>0];g.length=d+1,g[d]=new Promise(P=>setTimeout(P,E,0))}else g.length=d;for(var T=0;T{if(!Xf){var p,d={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:"./this.program"};for(p in Kf)Kf[p]===void 0?delete d[p]:d[p]=Kf[p];var h=[];for(p in d)h.push(`${p}=${d[p]}`);Xf=h}return Xf};function nE(p,d){if(n)return Ge(19,1,p,d);p>>>=0,d>>>=0;var h,g=0,E=0;for(h of sE()){var T=d+g;(v(),I)[p+E>>>2>>>0]=T,g+=br(h,T,1/0)+1,E+=4}return 0}function oE(p,d){if(n)return Ge(20,1,p,d);p>>>=0,d>>>=0;var h=sE();for(var g of((v(),I)[p>>>2>>>0]=h.length,p=0,h))p+=vr(g)+1;return(v(),I)[d>>>2>>>0]=p,0}function aE(p){return n?Ge(21,1,p):52}function iE(p,d,h,g,E){return n?Ge(22,1,p,d,h,g,E):52}function lE(p,d,h,g){return n?Ge(23,1,p,d,h,g):52}function cE(p,d,h,g){return n?Ge(24,1,p,d,h,g):70}var dC=[null,[],[]];function uE(p,d,h,g){if(n)return Ge(25,1,p,d,h,g);d>>>=0,h>>>=0,g>>>=0;for(var E=0,T=0;T>>2>>>0],P=(v(),I)[d+4>>>2>>>0];d+=8;for(var R=0;R>>0],ve=dC[H];xe===0||xe===10?((H===1?M:S)(yk(ve)),ve.length=0):ve.push(xe)}E+=P}return(v(),I)[g>>>2>>>0]=E,0}function mC(p){return p>>>0}function _C(p,d){return Zk(ae(p>>>0).limits,d>>>0),1}function hC(p,d){return ae(p>>>0).features.has(eE[d])}function gC(p){return BigInt(ae(p>>>0).size)}function wC(p){return BigInt(ae(p>>>0).usage)}function xC(p,d){if(p>>>=0,d>>>=0){var h=Yt(d+4);h={label:h,timestampWrites:d=(d=(v(),I)[d+12>>>2>>>0])!==0?{querySet:ae((v(),I)[d+4>>>2>>>0]),beginningOfPassWriteIndex:(v(),I)[d+8>>>2>>>0],endOfPassWriteIndex:(v(),I)[d+12>>>2>>>0]}:void 0}}return d=ae(p),p=xE(0),h=d.beginComputePass(h),wt[p>>>0]=h,p}function yC(p,d,h,g){h=gt(h),(g=gt(g))==-1&&(g=void 0),(p=ae(p>>>0)).clearBuffer(ae(d>>>0),h,g)}function bC(p,d,h,g,E,T){h=gt(h),E=gt(E),T=gt(T),ae(p>>>0).copyBufferToBuffer(ae(d>>>0),h,ae(g>>>0),E,T)}function vC(p){var d=ae(p>>>0);return p=gE(0),d=d.finish(),wt[p>>>0]=d,p}function kC(p,d,h,g,E,T){T=gt(T),ae(p>>>0).resolveQuerySet(ae(d>>>0),h,g,ae(E>>>0),T)}function EC(p,d,h,g){ae(p>>>0).dispatchWorkgroups(d,h,g)}function AC(p,d,h){h=gt(h),ae(p>>>0).dispatchWorkgroupsIndirect(ae(d>>>0),h)}function TC(p){ae(p>>>0).end()}function SC(p,d,h,g,E){g>>>=0,E>>>=0,p=ae(p>>>0),h=ae(h>>>0),g==0?p.setBindGroup(d,h):p.setBindGroup(d,h,(v(),I),E>>>2,g)}function MC(p,d){ae(p>>>0).setPipeline(ae(d>>>0))}function OC(p,d,h){ae(p>>>0).Xe(ae(d>>>0),h)}function IC(p,d){function h(E){var T=(v(),I)[E+8>>>2>>>0],N=(v(),I)[E+32>>>2>>>0],P=(v(),I)[E+36>>>2>>>0],R=0;return Hf(E,{14:H=>{R=(v(),I)[H+8>>>2>>>0]}}),T?((N=wn(E+24))==-1&&(N=void 0),T={buffer:ae(T),offset:wn(E+16),size:N}):T=ae(N||P||R),{binding:(v(),I)[E+4>>>2>>>0],resource:T}}p>>>=0,d={label:Yt((d>>>=0)+4),layout:ae((v(),I)[d+12>>>2>>>0]),entries:(function(E,T){for(var N=[],P=0;P>>2>>>0],(v(),I)[d+20>>>2>>>0])},p=ae(p);var g=_E(0);return Qk(g,p.createBindGroup(d)),g}function CC(p,d){function h(R){var H=(v(),I)[R+4>>>2>>>0];if(H)return{type:jI[H],hasDynamicOffset:!!(v(),I)[R+8>>>2>>>0],minBindingSize:wn(R+16)}}function g(R){if(R=(v(),I)[R+4>>>2>>>0])return{type:XI[R]}}function E(R){var H=(v(),I)[R+4>>>2>>>0];if(H)return{sampleType:QI[H],viewDimension:rE[(v(),B)[R+8>>>2>>>0]],multisampled:!!(v(),I)[R+12>>>2>>>0]}}function T(R){var H=(v(),I)[R+4>>>2>>>0];if(H)return{access:KI[H],format:YI[(v(),B)[R+8>>>2>>>0]],viewDimension:rE[(v(),B)[R+12>>>2>>>0]]}}function N(R){var H={binding:(v(),I)[R+4>>>2>>>0],visibility:(v(),I)[R+8>>>2>>>0],buffer:h(R+24),sampler:g(R+48),texture:E(R+56),storageTexture:T(R+72)};return Hf(R,{13:()=>{H.externalTexture={}}}),H}p>>>=0,d={label:Yt((d>>>=0)+4),entries:(function(R,H){for(var xe=[],ve=0;ve>>2>>>0],(v(),I)[d+16>>>2>>>0])},p=ae(p);var P=hE(0);return Qk(P,p.createBindGroupLayout(d)),P}function PC(p,d){var h;return p>>>=0,(d>>>=0)&&(h={label:Yt(d+4)}),d=ae(p),p=wE(0),h=d.createCommandEncoder(h),wt[p>>>0]=h,p}function NC(p,d){p>>>=0,d>>>=0;for(var h=(v(),I)[d+12>>>2>>>0],g=(v(),I)[d+16>>>2>>>0],E=[],T=0;T>>2>>>0]));return d={label:Yt(d+4),bindGroupLayouts:E,immediateSize:(v(),I)[d+20>>>2>>>0]},h=ae(p),p=yE(0),d=h.createPipelineLayout(d),wt[p>>>0]=d,p}function LC(p,d){p>>>=0,d>>>=0,d={type:HI[(v(),B)[d+12>>>2>>>0]],count:(v(),I)[d+16>>>2>>>0]};var h=ae(p);return p=bE(0),d=h.createQuerySet(d),wt[p>>>0]=d,p}function zC(p,d){return GI(ae(p>>>0).adapterInfo,d>>>0),1}var $C={"core-features-and-limits":1,"depth-clip-control":2,"depth32float-stencil8":3,"texture-compression-bc":4,"texture-compression-bc-sliced-3d":5,"texture-compression-etc2":6,"texture-compression-astc":7,"texture-compression-astc-sliced-3d":8,"timestamp-query":9,"indirect-first-instance":10,"shader-f16":11,"rg11b10ufloat-renderable":12,"bgra8unorm-storage":13,"float32-filterable":14,"float32-blendable":15,"clip-distances":16,"dual-source-blending":17,subgroups:18,"texture-formats-tier1":19,"texture-formats-tier2":20,"primitive-index":21,"texture-component-swizzle":22,"subgroup-size-control":23,"chromium-experimental-unorm16-texture-formats":327692,"chromium-experimental-multi-draw-indirect":327729,"chromium-experimental-subgroup-matrix":327732};function RC(p,d){d>>>=0;var h=ae(p>>>0);p=ks(4*h.features.size);var g=0,E=0;for(let T of h.features)0<=(h=$C[T])&&((v(),B)[p+g>>>2>>>0]=h,g+=4,E++);(v(),I)[d+4>>>2>>>0]=p,(v(),I)[d>>>2>>>0]=E}function BC(p,d){return Zk(ae(p>>>0).limits,d>>>0),1}function DC(p,d){ae(p>>>0).pushErrorScope(qI[d])}function UC(p,d,h){d>>>=0,h>>>=0,p=ae(p>>>0),d=Array.from((v(),B).subarray(h>>>2>>>0,h+4*d>>>2>>>0),g=>ae(g)),p.submit(d)}function FC(p,d,h,g,E){h=gt(h),g>>>=0,E>>>=0,p=ae(p>>>0),d=ae(d>>>0),g=(v(),K).subarray(g>>>0,g+E>>>0),p.writeBuffer(d,h,g,0,E)}n||(function(){for(var p=e.numThreads-1;p--;)dk();qe.push(async()=>{var d=(async function(){if(!n)return Promise.all(Lr.map(fk))})();Ce++,await d,--Ce==0&&at&&(d=at,at=null,d())})})(),n||(zr=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),G()),e.wasmBinary&&(f=e.wasmBinary),e.stackSave=()=>ue(),e.stackRestore=p=>ce(p),e.stackAlloc=p=>Sc(p),e.setValue=function(p,d,h="i8"){switch(h.endsWith("*")&&(h="*"),h){case"i1":case"i8":(v(),F)[p>>>0]=d;break;case"i16":(v(),Y)[p>>>1>>>0]=d;break;case"i32":(v(),B)[p>>>2>>>0]=d;break;case"i64":(v(),Z)[p>>>3>>>0]=BigInt(d);break;case"float":(v(),oe)[p>>>2>>>0]=d;break;case"double":(v(),J)[p>>>3>>>0]=d;break;case"*":(v(),I)[p>>>2>>>0]=d;break;default:ie(`invalid type for setValue: ${h}`)}},e.getValue=function(p,d="i8"){switch(d.endsWith("*")&&(d="*"),d){case"i1":case"i8":return(v(),F)[p>>>0];case"i16":return(v(),Y)[p>>>1>>>0];case"i32":return(v(),B)[p>>>2>>>0];case"i64":return(v(),Z)[p>>>3>>>0];case"float":return(v(),oe)[p>>>2>>>0];case"double":return(v(),J)[p>>>3>>>0];case"*":return(v(),I)[p>>>2>>>0];default:ie(`invalid type for getValue: ${d}`)}},e.UTF8ToString=hn,e.stringToUTF8=br,e.lengthBytesUTF8=vr;var pE,fE,dE,Yf,Tc,Ft,ks,mE,_E,hE,gE,wE,xE,yE,bE,vE,kE,EE,Qf,Jf,Zf,ed,So,td,AE,rd,TE,SE,ME,sd,OE,IE,nd,be,Mo,CE,ce,Sc,ue,PE,od,NE,LE,zE,ad,$E,RE,BE,DE,UE,FE,GE,jE,qE,WE,VE,HE,XE,KE,YE,QE,JE,ZE,eA,tA,rA,sA,nA,oA,aA,iA,lA,cA,uA,pA,fA,dA,mA,_A,hA,gA,wA,xA,yA,bA,vA,Er,GC=[dn,Eo,hk,bk,vk,kk,Ek,Ak,Tk,Sk,Mk,Ok,Ik,Ck,Pk,Nk,Wk,Vk,Hk,nE,oE,aE,iE,lE,cE,uE],id={1280444:(p,d,h,g,E)=>{if(e===void 0||!e.ed)return 1;if((p=hn(Number(p>>>0))).startsWith("./")&&(p=p.substring(2)),!(p=e.ed.get(p)))return 2;if(d=Number(d>>>0),h=Number(h>>>0),g=Number(g>>>0),d+h>p.byteLength)return 3;try{let T=p.subarray(d,d+h);switch(E){case 0:(v(),K).set(T,g>>>0);break;case 1:e.pe?e.pe(g,T):e.Re(g,T);break;default:return 4}return 0}catch{return 4}},1281268:(p,d,h)=>{e.re(p,(v(),K).subarray(d>>>0,d+h>>>0))},1281332:()=>e.Pe(),1281374:p=>{e.qe(p)},1281411:()=>typeof wasmOffsetConverter<"u"};function jC(){return typeof wasmOffsetConverter<"u"}function qC(p,d,h,g){var E=ue();try{return jE(p,d,h,g)}catch(T){if(ce(E),T!==T+0)throw T;be(1,0)}}function WC(p,d,h){var g=ue();try{return UE(p,d,h)}catch(E){if(ce(g),E!==E+0)throw E;be(1,0)}}function VC(p){var d=ue();try{$E(p)}catch(h){if(ce(d),h!==h+0)throw h;be(1,0)}}function HC(p,d){var h=ue();try{return ad(p,d)}catch(g){if(ce(h),g!==g+0)throw g;be(1,0)}}function XC(p,d,h){var g=ue();try{zE(p,d,h)}catch(E){if(ce(g),E!==E+0)throw E;be(1,0)}}function KC(p,d){var h=ue();try{qE(p,d)}catch(g){if(ce(h),g!==g+0)throw g;be(1,0)}}function YC(p,d,h,g,E,T,N){var P=ue();try{return DE(p,d,h,g,E,T,N)}catch(R){if(ce(P),R!==R+0)throw R;be(1,0)}}function QC(p,d,h,g,E,T){var N=ue();try{RE(p,d,h,g,E,T)}catch(P){if(ce(N),P!==P+0)throw P;be(1,0)}}function JC(p,d,h,g){var E=ue();try{GE(p,d,h,g)}catch(T){if(ce(E),T!==T+0)throw T;be(1,0)}}function ZC(p,d,h,g,E,T,N){var P=ue();try{VE(p,d,h,g,E,T,N)}catch(R){if(ce(P),R!==R+0)throw R;be(1,0)}}function eP(p,d,h,g,E,T,N){var P=ue();try{HE(p,d,h,g,E,T,N)}catch(R){if(ce(P),R!==R+0)throw R;be(1,0)}}function tP(p,d,h,g,E,T,N,P){var R=ue();try{sA(p,d,h,g,E,T,N,P)}catch(H){if(ce(R),H!==H+0)throw H;be(1,0)}}function rP(p,d,h,g,E,T,N,P,R,H,xe,ve){var ee=ue();try{XE(p,d,h,g,E,T,N,P,R,H,xe,ve)}catch(Be){if(ce(ee),Be!==Be+0)throw Be;be(1,0)}}function sP(p,d,h,g,E){var T=ue();try{return WE(p,d,h,g,E)}catch(N){if(ce(T),N!==N+0)throw N;be(1,0)}}function nP(p,d,h,g,E,T){var N=ue();try{nA(p,d,h,g,E,T)}catch(P){if(ce(N),P!==P+0)throw P;be(1,0)}}function oP(p,d,h,g,E){var T=ue();try{BE(p,d,h,g,E)}catch(N){if(ce(T),N!==N+0)throw N;be(1,0)}}function aP(p,d,h,g,E,T,N,P){var R=ue();try{FE(p,d,h,g,E,T,N,P)}catch(H){if(ce(R),H!==H+0)throw H;be(1,0)}}function iP(p){var d=ue();try{return oA(p)}catch(h){if(ce(d),h!==h+0)throw h;be(1,0)}}function lP(p,d,h,g,E,T,N,P,R){var H=ue();try{YE(p,d,h,g,E,T,N,P,R)}catch(xe){if(ce(H),xe!==xe+0)throw xe;be(1,0)}}function cP(p,d,h){var g=ue();try{return aA(p,d,h)}catch(E){if(ce(g),E!==E+0)throw E;be(1,0)}}function uP(p,d){var h=ue();try{return wA(p,d)}catch(g){if(ce(h),g!==g+0)throw g;return be(1,0),0n}}function pP(p,d,h,g){var E=ue();try{return iA(p,d,h,g)}catch(T){if(ce(E),T!==T+0)throw T;be(1,0)}}function fP(p){var d=ue();try{return KE(p)}catch(h){if(ce(d),h!==h+0)throw h;return be(1,0),0n}}function dP(p,d,h,g){var E=ue();try{return lA(p,d,h,g)}catch(T){if(ce(E),T!==T+0)throw T;be(1,0)}}function mP(p,d,h,g,E){var T=ue();try{return cA(p,d,h,g,E)}catch(N){if(ce(T),N!==N+0)throw N;be(1,0)}}function _P(p,d,h,g,E,T){var N=ue();try{return uA(p,d,h,g,E,T)}catch(P){if(ce(N),P!==P+0)throw P;be(1,0)}}function hP(p,d,h,g,E,T){var N=ue();try{return tA(p,d,h,g,E,T)}catch(P){if(ce(N),P!==P+0)throw P;be(1,0)}}function gP(p,d,h,g,E,T){var N=ue();try{return pA(p,d,h,g,E,T)}catch(P){if(ce(N),P!==P+0)throw P;be(1,0)}}function wP(p,d,h,g,E,T,N,P){var R=ue();try{return rA(p,d,h,g,E,T,N,P)}catch(H){if(ce(R),H!==H+0)throw H;be(1,0)}}function xP(p,d,h,g,E){var T=ue();try{return fA(p,d,h,g,E)}catch(N){if(ce(T),N!==N+0)throw N;return be(1,0),0n}}function yP(p,d,h,g){var E=ue();try{return dA(p,d,h,g)}catch(T){if(ce(E),T!==T+0)throw T;be(1,0)}}function bP(p,d,h,g){var E=ue();try{return mA(p,d,h,g)}catch(T){if(ce(E),T!==T+0)throw T;be(1,0)}}function vP(p,d,h,g,E,T,N,P,R,H,xe,ve){var ee=ue();try{return _A(p,d,h,g,E,T,N,P,R,H,xe,ve)}catch(Be){if(ce(ee),Be!==Be+0)throw Be;be(1,0)}}function kP(p,d,h,g,E,T,N,P,R,H,xe){var ve=ue();try{hA(p,d,h,g,E,T,N,P,R,H,xe)}catch(ee){if(ce(ve),ee!==ee+0)throw ee;be(1,0)}}function EP(p,d,h,g,E,T,N,P,R,H,xe,ve,ee,Be,Mt,Et){var Es=ue();try{gA(p,d,h,g,E,T,N,P,R,H,xe,ve,ee,Be,Mt,Et)}catch(As){if(ce(Es),As!==As+0)throw As;be(1,0)}}function AP(p,d,h){var g=ue();try{return JE(p,d,h)}catch(E){if(ce(g),E!==E+0)throw E;return be(1,0),0n}}function TP(p,d,h){var g=ue();try{return QE(p,d,h)}catch(E){if(ce(g),E!==E+0)throw E;be(1,0)}}function SP(p,d,h){var g=ue();try{return ZE(p,d,h)}catch(E){if(ce(g),E!==E+0)throw E;be(1,0)}}function MP(p,d,h,g){var E=ue();try{eA(p,d,h,g)}catch(T){if(ce(E),T!==T+0)throw T;be(1,0)}}function Mc(){if(0{let d=new WeakMap,h,g,E=1;e.webgpuRegisterDevice=P=>{if(g!==void 0)throw Error("another WebGPU EP inference session is being created.");if(P){var R=d.get(P);if(!R){let H=((xe,ve=0)=>{var ee=EE(ve);return ve=kE(ve,ee),wt[ee>>>0]=xe.queue,wt[ve>>>0]=xe,ve})(P,R=dE());R=[E++,R,H],d.set(P,R)}return h=P,g=R[0],R}h=void 0,g=0};let T=new Map;e.webgpuOnCreateSession=P=>{if(g!==void 0){var R=g;if(g=void 0,P){let H=Yf(R);T.set(P,H),R===0&&p(h??ae(H))}h=void 0}},e.webgpuOnReleaseSession=P=>{T.delete(P)};let N=Symbol("gpuBufferMetadata");e.webgpuRegisterBuffer=(P,R,H)=>{if(H)return P[N]=[H,NaN],H;if(H=P[N])return H[1]++,H[0];if((R=T.get(R))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");return R=((xe,ve=0)=>(xe.mapState==="unmapped"||ie(),ve=vE(ve),wt[ve>>>0]=xe,ve))(P,R),P[N]=[R,1],R},e.webgpuUnregisterBuffer=P=>{let R=P[N];if(!R)throw Error("Buffer is not registered");R[1]--,R[1]===0&&(mE(R[0]),delete P[N])},e.webgpuGetBuffer=P=>ae(P),e.webgpuCreateDownloader=(P,R,H)=>{if((H=T.get(H))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");let xe=ae(H),ve=16*Math.ceil(Number(R)/16);return async()=>{let ee=xe.createBuffer({size:ve,usage:9});try{let Be=xe.createCommandEncoder();return Be.copyBufferToBuffer(P,0,ee,0,ve),xe.queue.submit([Be.finish()]),await ee.mapAsync(GPUMapMode.READ),ee.getMappedRange().slice(0,R)}finally{ee.destroy()}}},e.pe=(P,R)=>{var H=R.buffer;let xe=R.byteOffset,ve=R.byteLength;if(R=16*Math.ceil(Number(ve)/16),P=ae(P),!h){var ee=Yf(g);h=ae(ee)}let Be=(ee=h.createBuffer({mappedAtCreation:!0,size:R,usage:6})).getMappedRange();new Uint8Array(Be).set(new Uint8Array(H,xe,ve)),ee.unmap(),(H=h.createCommandEncoder()).copyBufferToBuffer(ee,0,P,0,R),h.queue.submit([H.finish()]),ee.destroy()}},e.webnnInit=p=>{let d=p[0];[e.Pe,e.qe,e.webnnEnsureTensor,e.re,e.webnnDownloadTensor,e.Oe,e.webnnEnableTraceEvent]=p.slice(1),e.webnnReleaseTensorId=e.qe,e.webnnUploadTensor=e.re,e.webnnRegisterMLContext=e.Oe,e.webnnOnRunStart=h=>d.onRunStart(h),e.webnnOnRunEnd=d.onRunEnd.bind(d),e.webnnOnReleaseSession=h=>{d.onReleaseSession(h)},e.webnnCreateMLTensorDownloader=(h,g)=>d.createMLTensorDownloader(h,g),e.webnnRegisterMLTensor=(h,g,E,T)=>d.registerMLTensor(h,g,E,T),e.webnnCreateMLContext=h=>d.createMLContext(h),e.webnnRegisterGraphInput=d.registerGraphInput.bind(d),e.webnnIsGraphInput=d.isGraphInput.bind(d),e.webnnRegisterGraphOutput=d.registerGraphOutput.bind(d),e.webnnIsGraphOutput=d.isGraphOutput.bind(d),e.webnnCreateTemporaryTensor=d.createTemporaryTensor.bind(d),e.webnnIsGraphInputOutputTypeSupported=d.isGraphInputOutputTypeSupported.bind(d)},z?e:new Promise((p,d)=>{w=p,x=d})}var GT,X2,F$=Ae(()=>{"use strict";GT=H2,X2=globalThis.self?.name?.startsWith("em-pthread"),X2&&H2()}),Nd,Kd,K2,Lt,jT,Yc,Y2,Q2,Ld,J2,zd,qT,$d,WT,sm=Ae(()=>{"use strict";rm(),Nd=typeof location>"u"?void 0:location.origin,Kd=import.meta.url>"file:"&&import.meta.url<"file;",K2=()=>{if(Kd){let t=URL;return new URL(new t("ort.webgpu.bundle.min.mjs",import.meta.url).href,Nd).href}return import.meta.url},Lt=K2(),jT=()=>{if(Lt&&!Lt.startsWith("blob:"))return Lt.substring(0,Lt.lastIndexOf("/")+1)},Yc=(t,e)=>{try{let r=e??Lt;return(r?new URL(t,r):new URL(t)).origin===Nd}catch{return!1}},Y2=(t,e)=>{let r=e??Lt;try{return(r?new URL(t,r):new URL(t)).href}catch{return}},Q2=(t,e)=>`${e??"./"}${t}`,Ld=async t=>{let e=await(await fetch(t,{credentials:"same-origin"})).blob();return URL.createObjectURL(e)},J2=async t=>(await import(t)).default,zd=(U$(),tu(DT)).default,qT=async()=>{if(!Lt)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Yc(Lt))return[void 0,zd()];let t=await Ld(Lt);return[t,zd(t)]},$d=(F$(),tu(FT)).default,WT=async(t,e,r,s)=>{let n=$d&&!(t||e);if(n)if(Lt)n=Yc(Lt)||s&&!r;else if(s&&!r)n=!0;else throw new Error("cannot determine the script source URL.");if(n)return[void 0,$d];{let o="ort-wasm-simd-threaded.asyncify.mjs",a=t??Y2(o,e),i=r&&a&&!Yc(a,e),l=i?await Ld(a):a??Q2(o,e);return[i?l:void 0,await J2(l)]}}}),Rd,Qc,Do,Bd,Z2,eT,tT,nm,je,Us=Ae(()=>{"use strict";sm(),Qc=!1,Do=!1,Bd=!1,Z2=()=>{if(typeof SharedArrayBuffer>"u")return!1;try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},eT=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},tT=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},nm=async t=>{if(Qc)return Promise.resolve();if(Do)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Bd)throw new Error("previous call to 'initializeWebAssembly()' failed.");Do=!0;let e=t.initTimeout,r=t.numThreads;if(t.simd!==!1){if(t.simd==="relaxed"){if(!tT())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!eT())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let s=Z2();r>1&&!s&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+r+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),t.numThreads=r=1);let n=t.wasmPaths,o=typeof n=="string"?n:void 0,a=n?.mjs,i=a?.href??a,l=n?.wasm,c=l?.href??l,u=t.wasmBinary,[f,m]=await WT(i,o,r>1,!!u||!!c),_=!1,w=[];if(e>0&&w.push(new Promise(x=>{setTimeout(()=>{_=!0,x()},e)})),w.push(new Promise((x,b)=>{let A={numThreads:r};if(u)A.wasmBinary=u,A.locateFile=k=>k;else if(c||o)A.locateFile=k=>c??o+k;else if(i&&i.indexOf("blob:")!==0)A.locateFile=k=>new URL(k,i).href;else if(f){let k=jT();k&&(A.locateFile=M=>k+M)}m(A).then(k=>{Do=!1,Qc=!0,Rd=k,x(),f&&URL.revokeObjectURL(f)},k=>{Do=!1,Bd=!0,b(k)})})),await Promise.race(w),_)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},je=()=>{if(Qc&&Rd)return Rd;throw new Error("WebAssembly is not initialized yet.")}}),zt,su,ze,om=Ae(()=>{"use strict";Us(),zt=(t,e)=>{let r=je(),s=r.lengthBytesUTF8(t)+1,n=r._malloc(s);return r.stringToUTF8(t,n,s),e.push(n),n},su=(t,e,r,s)=>{if(typeof t=="object"&&t!==null){if(r.has(t))throw new Error("Circular reference in options");r.add(t)}Object.entries(t).forEach(([n,o])=>{let a=e?e+n:n;if(typeof o=="object")su(o,a+".",r,s);else if(typeof o=="string"||typeof o=="number")s(a,o.toString());else if(typeof o=="boolean")s(a,o?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof o}`)})},ze=t=>{let e=je(),r=e.stackSave();try{let s=e.PTR_SIZE,n=e.stackAlloc(2*s);e._OrtGetLastError(n,n+s);let o=Number(e.getValue(n,s===4?"i32":"i64")),a=e.getValue(n+s,"*"),i=a?e.UTF8ToString(a):"";throw new Error(`${t} ERROR_CODE: ${o}, ERROR_MESSAGE: ${i}`)}finally{e.stackRestore(r)}}}),VT,G$=Ae(()=>{"use strict";Us(),om(),VT=t=>{let e=je(),r=0,s=[],n=t||{};try{if(t?.logSeverityLevel===void 0)n.logSeverityLevel=2;else if(typeof t.logSeverityLevel!="number"||!Number.isInteger(t.logSeverityLevel)||t.logSeverityLevel<0||t.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${t.logSeverityLevel}`);if(t?.logVerbosityLevel===void 0)n.logVerbosityLevel=0;else if(typeof t.logVerbosityLevel!="number"||!Number.isInteger(t.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${t.logVerbosityLevel}`);t?.terminate===void 0&&(n.terminate=!1);let o=0;return t?.tag!==void 0&&(o=zt(t.tag,s)),r=e._OrtCreateRunOptions(n.logSeverityLevel,n.logVerbosityLevel,!!n.terminate,o),r===0&&ze("Can't create run options."),t?.extra!==void 0&&su(t.extra,"",new WeakSet,(a,i)=>{let l=zt(a,s),c=zt(i,s);e._OrtAddRunConfigEntry(r,l,c)!==0&&ze(`Can't set a run config entry: ${a} - ${i}.`)}),[r,s]}catch(o){throw r!==0&&e._OrtReleaseRunOptions(r),s.forEach(a=>e._free(a)),o}}}),rT,sT,nT,Mn,_r,oT,HT,j$=Ae(()=>{"use strict";Us(),om(),rT=t=>{switch(t){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${t}`)}},sT=t=>{switch(t){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${t}`)}},nT=t=>{t.extra||(t.extra={}),t.extra.session||(t.extra.session={});let e=t.extra.session;e.use_ort_model_bytes_directly||(e.use_ort_model_bytes_directly="1"),t.executionProviders&&t.executionProviders.some(r=>(typeof r=="string"?r:r.name)==="webgpu")&&(t.enableMemPattern=!1)},Mn=(t,e,r,s)=>{let n=zt(e,s),o=zt(r,s);je()._OrtAddSessionConfigEntry(t,n,o)!==0&&ze(`Can't set a session config entry: ${e} - ${r}.`)},_r=(t,e,r,s)=>{let n=zt(e,s),o=zt(r,s);t.push([n,o])},oT=async(t,e,r)=>{let s=e.executionProviders;for(let n of s){let o=typeof n=="string"?n:n.name,a=[];switch(o){case"webnn":if(o="WEBNN",Mn(t,"session.disable_quant_qdq","1",r),Mn(t,"session.disable_qdq_constant_folding","1",r),typeof n!="string"){let f=n?.deviceType;f&&Mn(t,"deviceType",f,r)}break;case"webgpu":{o="WebGPU";let f;if(typeof n!="string"){let _=n;if(_.device)if(typeof GPUDevice<"u"&&_.device instanceof GPUDevice)f=_.device;else throw new Error("Invalid GPU device set in WebGPU EP options.");let{enableGraphCapture:w}=e;if(typeof w=="boolean"&&w&&_r(a,"enableGraphCapture","1",r),typeof _.preferredLayout=="string"&&_r(a,"preferredLayout",_.preferredLayout,r),_.forceCpuNodeNames){let x=Array.isArray(_.forceCpuNodeNames)?_.forceCpuNodeNames:[_.forceCpuNodeNames];_r(a,"forceCpuNodeNames",x.join(` +`),r)}_.validationMode&&_r(a,"validationMode",_.validationMode,r),typeof _.enableMatmulFp32Accumulation=="boolean"&&_r(a,"enableMatmulFp32Accumulation",_.enableMatmulFp32Accumulation?"1":"0",r);for(let x of["storageBufferCacheMode","uniformBufferCacheMode","queryResolveBufferCacheMode","defaultBufferCacheMode"]){let b=_[x];if(b){if(b!=="disabled"&&b!=="lazyRelease"&&b!=="simple"&&b!=="bucket")throw new Error(`${x} must be one of 'disabled', 'lazyRelease', 'simple' or 'bucket': ${b}`);_r(a,x,b,r)}}}let m=je().webgpuRegisterDevice(f);if(m){let[_,w,x]=m;_r(a,"deviceId",_.toString(),r),_r(a,"webgpuInstance",w.toString(),r),_r(a,"webgpuDevice",x.toString(),r)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${o}`)}let i=zt(o,r),l=a.length,c=0,u=0;if(l>0){c=je()._malloc(l*je().PTR_SIZE),r.push(c),u=je()._malloc(l*je().PTR_SIZE),r.push(u);for(let f=0;f{let e=je(),r=0,s=[],n=t||{};nT(n);try{let o=rT(n.graphOptimizationLevel??"all"),a=sT(n.executionMode??"sequential"),i=typeof n.logId=="string"?zt(n.logId,s):0,l=n.logSeverityLevel??2;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log severity level is not valid: ${l}`);let c=n.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw new Error(`log verbosity level is not valid: ${c}`);let u=typeof n.optimizedModelFilePath=="string"?zt(n.optimizedModelFilePath,s):0;if(r=e._OrtCreateSessionOptions(o,!!n.enableCpuMemArena,!!n.enableMemPattern,a,!!n.enableProfiling,0,i,l,c,u),r===0&&ze("Can't create session options."),n.executionProviders&&await oT(r,n,s),n.enableGraphCapture!==void 0){if(typeof n.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${n.enableGraphCapture}`);Mn(r,"enableGraphCapture",n.enableGraphCapture.toString(),s)}if(n.freeDimensionOverrides)for(let[f,m]of Object.entries(n.freeDimensionOverrides)){if(typeof f!="string")throw new Error(`free dimension override name must be a string: ${f}`);if(typeof m!="number"||!Number.isInteger(m)||m<0)throw new Error(`free dimension override value must be a non-negative integer: ${m}`);let _=zt(f,s);e._OrtAddFreeDimensionOverride(r,_,m)!==0&&ze(`Can't set a free dimension override: ${f} - ${m}.`)}return n.extra!==void 0&&su(n.extra,"",new WeakSet,(f,m)=>{Mn(r,f,m,s)}),[r,s]}catch(o){throw r!==0&&e._OrtReleaseSessionOptions(r)!==0&&ze("Can't release session options."),s.forEach(a=>e._free(a)),o}}}),zs,eu,In,qo,nu,am,im,Yd,Cn=Ae(()=>{"use strict";zs=t=>{switch(t){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${t}`)}},eu=t=>{switch(t){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${t}`)}},In=(t,e)=>{let r=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][t],s=typeof e=="number"?e:e.reduce((n,o)=>n*o,1);return r>0?Math.ceil(s*r):void 0},qo=t=>{switch(t){case"float16":return typeof Float16Array<"u"?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${t}`)}},nu=t=>{switch(t){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${t}`)}},am=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint8"||t==="bool"||t==="uint4"||t==="int4",im=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint64"||t==="int8"||t==="uint8"||t==="bool"||t==="uint4"||t==="int4",Yd=t=>{switch(t){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${t}`)}}}),lm,XT=Ae(()=>{"use strict";rm(),lm=async t=>{if(typeof t=="string"){let e=await fetch(t);if(!e.ok)throw new Error(`failed to load external data file: ${t}`);let r=e.headers.get("Content-Length"),s=r?parseInt(r,10):0;if(s<1073741824)return new Uint8Array(await e.arrayBuffer());{if(!e.body)throw new Error(`failed to load external data file: ${t}, no response body.`);let n=e.body.getReader(),o;try{o=new ArrayBuffer(s)}catch(i){if(i instanceof RangeError){let l=Math.ceil(s/65536);o=new WebAssembly.Memory({initial:l,maximum:l}).buffer}else throw i}let a=0;for(;;){let{done:i,value:l}=await n.read();if(i)break;let c=l.byteLength;new Uint8Array(o,a,c).set(l),a+=c}return new Uint8Array(o,0,s)}}else return t instanceof Blob?new Uint8Array(await t.arrayBuffer()):t instanceof Uint8Array?t:new Uint8Array(t)}}),KT,q$=Ae(()=>{"use strict";Cn(),KT=(t,e)=>new(qo(e))(t)}),aT,iT,lT,cT,YT,uT,Ot,QT=Ae(()=>{"use strict";Cn(),aT=["V","I","W","E","F"],iT=(t,e)=>{console.log(`[${aT[t]},${new Date().toISOString()}]${e}`)},YT=(t,e)=>{lT=t,cT=e},uT=(t,e)=>{let r=nu(t),s=nu(lT);r>=s&&iT(r,typeof e=="function"?e():e)},Ot=(...t)=>{cT&&uT(...t)}}),Dd,pT,Ud,fT,Fd,dT,Gd,jd,qd,mT,JT,W$=Ae(()=>{"use strict";Cn(),QT(),Dd=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),pT=(t,e)=>{if(e==="int32")return t;let r=Dd.get(e);if(!r)throw new Error(`WebNN backend does not support data type: ${e}`);let s=r/8;if(t.byteLength%s!==0)throw new Error(`Invalid Uint8Array length - must be a multiple of ${s}.`);let n=t.byteLength/s,o=new(qo(e))(t.buffer,t.byteOffset,n);switch(e){case"int64":case"uint64":{let a=new Int32Array(n);for(let i=0;i2147483647n||l<-2147483648n)throw new Error("Can not convert int64 data to int32 - value out of range.");a[i]=Number(l)}return new Uint8Array(a.buffer)}case"int8":case"uint8":case"uint32":{if(e==="uint32"&&o.some(i=>i>2147483647))throw new Error("Can not convert uint32 data to int32 - value out of range.");let a=Int32Array.from(o,Number);return new Uint8Array(a.buffer)}default:throw new Error(`Unsupported data conversion from ${e} to 'int32'`)}},Ud=(t,e)=>{if(e==="int32")return t;if(t.byteLength%4!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 4 (int32).");let r=t.byteLength/4,s=new Int32Array(t.buffer,t.byteOffset,r);switch(e){case"int64":{let n=BigInt64Array.from(s,BigInt);return new Uint8Array(n.buffer)}case"uint64":{if(s.some(o=>o<0))throw new Error("Can not convert int32 data to uin64 - negative value found.");let n=BigUint64Array.from(s,BigInt);return new Uint8Array(n.buffer)}case"int8":{if(s.some(o=>o<-128||o>127))throw new Error("Can not convert int32 data to int8 - value out of range.");let n=Int8Array.from(s,Number);return new Uint8Array(n.buffer)}case"uint8":{if(s.some(n=>n<0||n>255))throw new Error("Can not convert int32 data to uint8 - value out of range.");return Uint8Array.from(s,Number)}case"uint32":{if(s.some(o=>o<0))throw new Error("Can not convert int32 data to uint32 - negative value found.");let n=Uint32Array.from(s,Number);return new Uint8Array(n.buffer)}default:throw new Error(`Unsupported data conversion from 'int32' to ${e}`)}},fT=1,Fd=()=>fT++,dT=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),Gd=(t,e)=>{let r=Dd.get(t);if(!r)throw new Error(`WebNN backend does not support data type: ${t}`);return e.length>0?Math.ceil(e.reduce((s,n)=>s*n)*r/8):0},jd=class{constructor(t){this.isDataConverted=!1;let{sessionId:e,context:r,tensor:s,dataType:n,shape:o,fallbackDataType:a}=t;this.sessionId=e,this.mlContext=r,this.mlTensor=s,this.dataType=n,this.tensorShape=o,this.fallbackDataType=a}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return Gd(this.dataType,this.tensorShape)}destroy(){Ot("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(t){this.mlContext.writeTensor(this.mlTensor,t)}async read(t){if(this.fallbackDataType){let e=await this.mlContext.readTensor(this.mlTensor),r=Ud(new Uint8Array(e),this.dataType);if(t){(t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)).set(r);return}else return new Uint8Array(r).buffer}else return t?this.mlContext.readTensor(this.mlTensor,t):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(t,e,r){return this.mlContext===t&&this.dataType===e&&this.tensorShape.length===r.length&&this.tensorShape.every((s,n)=>s===r[n])}setIsDataConverted(t){this.isDataConverted=t}},qd=class{constructor(t,e){this.tensorManager=t,this.wrapper=e}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(t,e,r,s){let n=this.tensorManager.getMLContext(t),o=this.tensorManager.getMLOpSupportLimits(t),a;if(!o?.input.dataTypes.includes(e)){if(a=dT.get(e),!a||!o?.input.dataTypes.includes(a))throw new Error(`WebNN backend does not support data type: ${e}`);Ot("verbose",()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${e} to ${a}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(n,e,r))return this.wrapper.tensor;if(s){if(this.wrapper.byteLength!==Gd(e,r))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let i=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(t,e,r,i,!0,!0,a),s&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(t){let e=t;if(this.wrapper){if(this.wrapper.fallbackType)if(this.wrapper.fallbackType==="int32")e=pT(t,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw new Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`);if(t.byteLength===this.wrapper.byteLength){this.wrapper.write(e);return}else Ot("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor()}this.activeUpload?this.activeUpload.set(e):this.activeUpload=new Uint8Array(e)}async download(t){if(this.activeUpload){let e=this.wrapper?.isDataConverted?Ud(this.activeUpload,this.wrapper?.type):this.activeUpload;if(t){t instanceof ArrayBuffer?new Uint8Array(t).set(e):new Uint8Array(t.buffer,t.byteOffset,t.byteLength).set(e);return}else return e.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return t?this.wrapper.read(t):this.wrapper.read()}},mT=class{constructor(t){this.backend=t,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(t){let e=this.backend.getMLContext(t);if(!e)throw new Error("MLContext not found for session.");return e}getMLOpSupportLimits(t){return this.backend.getMLOpSupportLimits(t)}reserveTensorId(){let t=Fd();return this.tensorTrackersById.set(t,new qd(this)),t}releaseTensorId(t){let e=this.tensorTrackersById.get(t);e&&(this.tensorTrackersById.delete(t),e.tensorWrapper&&this.releaseTensor(e.tensorWrapper))}async ensureTensor(t,e,r,s,n){Ot("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${e}, dataType: ${r}, shape: ${s}, copyOld: ${n}}`);let o=this.tensorTrackersById.get(e);if(!o)throw new Error("Tensor not found.");return o.ensureTensor(t,r,s,n)}upload(t,e){let r=this.tensorTrackersById.get(t);if(!r)throw new Error("Tensor not found.");r.upload(e)}async download(t,e){Ot("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${t}, dstBuffer: ${e?.byteLength}}`);let r=this.tensorTrackersById.get(t);if(!r)throw new Error("Tensor not found.");return r.download(e)}releaseTensorsForSession(t){for(let e of this.freeTensors)e.sessionId===t&&e.destroy();this.freeTensors=this.freeTensors.filter(e=>e.sessionId!==t)}registerTensor(t,e,r,s){let n=this.getMLContext(t),o=Fd(),a=new jd({sessionId:t,context:n,tensor:e,dataType:r,shape:s});return this.tensorTrackersById.set(o,new qd(this,a)),this.externalTensors.add(a),o}async getCachedTensor(t,e,r,s,n,o,a){let i=this.getMLContext(t);for(let[c,u]of this.freeTensors.entries())if(u.canReuseTensor(i,e,r)){Ot("verbose",()=>`[WebNN] Reusing tensor {dataType: ${e}, ${a?`fallbackDataType: ${a},`:""} shape: ${r}`);let f=this.freeTensors.splice(c,1)[0];return f.sessionId=t,f}Ot("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${e}, ${a?`fallbackDataType: ${a},`:""} shape: ${r}}`);let l=await i.createTensor({dataType:a??e,shape:r,dimensions:r,usage:s,writable:n,readable:o});return new jd({sessionId:t,context:i,tensor:l,dataType:e,shape:r,fallbackDataType:a})}releaseTensor(t){this.externalTensors.has(t)&&this.externalTensors.delete(t),this.freeTensors.push(t)}},JT=(...t)=>new mT(...t)}),ZT={};Wo(ZT,{WebNNBackend:()=>eS});var Uo,_T,eS,V$=Ae(()=>{"use strict";Cn(),Us(),q$(),W$(),QT(),Uo=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),_T=(t,e)=>{if(t===e)return!0;if(t===void 0||e===void 0)return!1;let r=Object.keys(t).sort(),s=Object.keys(e).sort();return r.length===s.length&&r.every((n,o)=>n===s[o]&&t[n]===e[n])},eS=class{constructor(t){this.tensorManager=JT(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.sessionGraphOutputs=new Map,this.temporaryGraphInputs=[],this.temporaryGraphOutputs=[],this.temporarySessionTensorIds=new Map,this.mlOpSupportLimitsBySessionId=new Map,YT(t.logLevel,!!t.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(t){Ot("verbose",()=>`[WebNN] onRunStart {sessionId: ${t}}`),this.activeSessionId=t}onRunEnd(t){Ot("verbose",()=>`[WebNN] onRunEnd {sessionId: ${t}}`);let e=this.temporarySessionTensorIds.get(t);if(e){for(let r of e)Ot("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${r}}`),this.tensorManager.releaseTensorId(r);this.temporarySessionTensorIds.delete(t),this.activeSessionId=void 0}}async createMLContext(t){if(t instanceof GPUDevice){let r=this.mlContextCache.findIndex(s=>s.gpuDevice===t);if(r!==-1)return this.mlContextCache[r].mlContext;{let s=await navigator.ml.createContext(t);return this.mlContextCache.push({gpuDevice:t,mlContext:s}),s}}else if(t===void 0){let r=this.mlContextCache.findIndex(s=>s.options===void 0&&s.gpuDevice===void 0);if(r!==-1)return this.mlContextCache[r].mlContext;{let s=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:s}),s}}let e=this.mlContextCache.findIndex(r=>_T(r.options,t));if(e!==-1)return this.mlContextCache[e].mlContext;{let r=await navigator.ml.createContext(t);return this.mlContextCache.push({options:t,mlContext:r}),r}}registerMLContext(t,e){this.mlContextBySessionId.set(t,e);let r=this.sessionIdsByMLContext.get(e);r||(r=new Set,this.sessionIdsByMLContext.set(e,r)),r.add(t),this.mlOpSupportLimitsBySessionId.has(t)||this.mlOpSupportLimitsBySessionId.set(t,e.opSupportLimits()),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(t,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(t,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[])}onReleaseSession(t){this.sessionGraphInputs.delete(t),this.sessionGraphOutputs.delete(t);let e=this.mlContextBySessionId.get(t);if(!e)return;this.tensorManager.releaseTensorsForSession(t),this.mlContextBySessionId.delete(t),this.mlOpSupportLimitsBySessionId.delete(t);let r=this.sessionIdsByMLContext.get(e);if(r.delete(t),r.size===0){this.sessionIdsByMLContext.delete(e);let s=this.mlContextCache.findIndex(n=>n.mlContext===e);s!==-1&&this.mlContextCache.splice(s,1)}}getMLContext(t){return this.mlContextBySessionId.get(t)}getMLOpSupportLimits(t){return this.mlOpSupportLimitsBySessionId.get(t)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(t){Ot("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${t}}`),this.tensorManager.releaseTensorId(t)}async ensureTensor(t,e,r,s,n){let o=Uo.get(r);if(!o)throw new Error(`Unsupported ONNX data type: ${r}`);return this.tensorManager.ensureTensor(t??this.currentSessionId,e,o,s,n)}async createTemporaryTensor(t,e,r){Ot("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${e}, shape: ${r}}`);let s=Uo.get(e);if(!s)throw new Error(`Unsupported ONNX data type: ${e}`);let n=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(t,n,s,r,!1);let o=this.temporarySessionTensorIds.get(t);return o?o.push(n):this.temporarySessionTensorIds.set(t,[n]),n}uploadTensor(t,e){if(!je().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");Ot("verbose",()=>`[WebNN] uploadTensor {tensorId: ${t}, data: ${e.byteLength}}`),this.tensorManager.upload(t,e)}async downloadTensor(t,e){return this.tensorManager.download(t,e)}createMLTensorDownloader(t,e){return async()=>{let r=await this.tensorManager.download(t);return KT(r,e)}}registerMLTensor(t,e,r,s){let n=Uo.get(r);if(!n)throw new Error(`Unsupported ONNX data type: ${r}`);let o=this.tensorManager.registerTensor(t,e,n,s);return Ot("verbose",()=>`[WebNN] registerMLTensor {tensor: ${e}, dataType: ${n}, dimensions: ${s}} -> {tensorId: ${o}}`),o}registerGraphInput(t){this.temporaryGraphInputs.push(t)}registerGraphOutput(t){this.temporaryGraphOutputs.push(t)}isGraphInput(t,e){let r=this.sessionGraphInputs.get(t);return r?r.includes(e):!1}isGraphOutput(t,e){let r=this.sessionGraphOutputs.get(t);return r?r.includes(e):!1}isGraphInputOutputTypeSupported(t,e,r=!0){let s=Uo.get(zs(e)),n=this.mlOpSupportLimitsBySessionId.get(t);return typeof s>"u"?!1:r?!!n?.input.dataTypes.includes(s):!!n?.output.dataTypes.includes(s)}flush(){}}}),hT,cm,um,Hr,gT,Wd,ou,pm,fm,Vd,dm,mm,_m,tS=Ae(()=>{"use strict";Ds(),G$(),j$(),Cn(),Us(),om(),XT(),hT=(t,e)=>{je()._OrtInit(t,e)!==0&&ze("Can't initialize onnxruntime.")},cm=async t=>{hT(t.wasm.numThreads,nu(t.logLevel))},um=async(t,e)=>{je().asyncInit?.();let r=t.webgpu.adapter;if(e==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(r){if(typeof r.limits!="object"||typeof r.features!="object"||typeof r.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let s=t.webgpu.powerPreference;if(s!==void 0&&s!=="low-power"&&s!=="high-performance")throw new Error(`Invalid powerPreference setting: "${s}"`);let n=t.webgpu.forceFallbackAdapter;if(n!==void 0&&typeof n!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${n}"`);if(r=await navigator.gpu.requestAdapter({powerPreference:s,forceFallbackAdapter:n}),!r)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(e==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment");if(e==="webgpu"&&je().webgpuInit(s=>{t.webgpu.device=s}),e==="webnn"){let s=new(V$(),tu(ZT)).WebNNBackend(t);je().webnnInit([s,()=>s.reserveTensorId(),n=>s.releaseTensorId(n),async(n,o,a,i,l)=>s.ensureTensor(n,o,a,i,l),(n,o)=>{s.uploadTensor(n,o)},async(n,o)=>s.downloadTensor(n,o),(n,o)=>s.registerMLContext(n,o),!!t.trace])}},Hr=new Map,gT=t=>{let e=je(),r=e.stackSave();try{let s=e.PTR_SIZE,n=e.stackAlloc(2*s);e._OrtGetInputOutputCount(t,n,n+s)!==0&&ze("Can't get session input/output count.");let o=s===4?"i32":"i64";return[Number(e.getValue(n,o)),Number(e.getValue(n+s,o))]}finally{e.stackRestore(r)}},Wd=(t,e)=>{let r=je(),s=r.stackSave(),n=0;try{let o=r.PTR_SIZE,a=r.stackAlloc(2*o);r._OrtGetInputOutputMetadata(t,e,a,a+o)!==0&&ze("Can't get session input/output metadata.");let i=Number(r.getValue(a,"*"));n=Number(r.getValue(a+o,"*"));let l=r.HEAP32[n/4];if(l===0)return[i,0];let c=r.HEAPU32[n/4+1],u=[];for(let f=0;f{let e=je(),r=e._malloc(t.byteLength);if(r===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${t.byteLength}.`);return e.HEAPU8.set(t,r),[r,t.byteLength]},pm=async(t,e)=>{let r,s,n=je();Array.isArray(t)?[r,s]=t:t.buffer===n.HEAPU8.buffer?[r,s]=[t.byteOffset,t.byteLength]:[r,s]=ou(t);let o=0,a=0,i=0,l=[],c=[],u=[];try{if([a,l]=await HT(e),e?.externalData&&n.mountExternalData){let S=[];for(let O of e.externalData){let C=typeof O=="string"?O:O.path,v=typeof O=="string"?O:O.data;S.push(lm(v).then(U=>{n.mountExternalData(C,U)}))}await Promise.all(S)}for(let S of e?.executionProviders??[])if((typeof S=="string"?S:S.name)==="webnn"){if(n.shouldTransferToMLTensor=!1,typeof S!="string"){let O=S,C=O?.context,v=O?.gpuDevice,U=O?.deviceType,j=O?.powerPreference;C?n.currentContext=C:v?n.currentContext=await n.webnnCreateMLContext(v):n.currentContext=await n.webnnCreateMLContext({deviceType:U,powerPreference:j})}else n.currentContext=await n.webnnCreateMLContext();break}o=await n._OrtCreateSession(r,s,a),n.webgpuOnCreateSession?.(o),o===0&&ze("Can't create a session."),n.jsepOnCreateSession?.(),n.currentContext&&(n.webnnRegisterMLContext(o,n.currentContext),n.currentContext=void 0,n.shouldTransferToMLTensor=!0);let[f,m]=gT(o),_=!!e?.enableGraphCapture,w=[],x=[],b=[],A=[],k=[];for(let S=0;SS==="gpu-buffer"||S==="ml-tensor"||S==="ml-tensor-cpu-output")&&(i=n._OrtCreateBinding(o),i===0&&ze("Can't create IO binding."),M={handle:i,outputPreferredLocations:k,outputPreferredLocationsEncoded:k.map(S=>S==="ml-tensor-cpu-output"?"ml-tensor":S).map(S=>Yd(S))}),Hr.set(o,[o,c,u,M,_,!1]),[o,w,x,b,A]}catch(f){throw c.forEach(m=>n._OrtFree(m)),u.forEach(m=>n._OrtFree(m)),i!==0&&n._OrtReleaseBinding(i)!==0&&ze("Can't release IO binding."),o!==0&&n._OrtReleaseSession(o)!==0&&ze("Can't release session."),f}finally{n._free(r),a!==0&&n._OrtReleaseSessionOptions(a)!==0&&ze("Can't release session options."),l.forEach(f=>n._free(f)),n.unmountExternalData?.()}},fm=t=>{let e=je(),r=Hr.get(t);if(!r)throw new Error(`cannot release session. invalid session id: ${t}`);let[s,n,o,a,i]=r;a&&(i&&e._OrtClearBoundOutputs(a.handle)!==0&&ze("Can't clear bound outputs."),e._OrtReleaseBinding(a.handle)!==0&&ze("Can't release IO binding.")),e.jsepOnReleaseSession?.(t),e.webnnOnReleaseSession?.(t),e.webgpuOnReleaseSession?.(t),n.forEach(l=>e._OrtFree(l)),o.forEach(l=>e._OrtFree(l)),e._OrtReleaseSession(s)!==0&&ze("Can't release session."),Hr.delete(t)},Vd=async(t,e,r,s,n,o,a=!1)=>{if(!t){e.push(0);return}let i=je(),l=i.PTR_SIZE,c=t[0],u=t[1],f=t[3],m=f,_,w;if(c==="string"&&(f==="gpu-buffer"||f==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(a&&f!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${o} when enableGraphCapture is true.`);if(f==="gpu-buffer"){let A=t[2].gpuBuffer;w=In(zs(c),u);{let k=i.webgpuRegisterBuffer;if(!k)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');_=k(A,s)}}else if(f==="ml-tensor"){let A=t[2].mlTensor;w=In(zs(c),u);let k=i.webnnRegisterMLTensor;if(!k)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');_=k(s,A,zs(c),u)}else{let A=t[2];if(Array.isArray(A)){w=l*A.length,_=i._malloc(w),r.push(_);for(let k=0;ki.setValue(b+M*l,k,l===4?"i32":"i64"));let A=i._OrtCreateTensor(zs(c),_,w,b,u.length,Yd(m));A===0&&ze(`Can't create tensor for input/output. session=${s}, index=${o}.`),e.push(A)}finally{i.stackRestore(x)}},dm=async(t,e,r,s,n,o)=>{let a=je(),i=a.PTR_SIZE,l=Hr.get(t);if(!l)throw new Error(`cannot run inference. invalid session id: ${t}`);let c=l[0],u=l[1],f=l[2],m=l[3],_=l[4],w=l[5],x=e.length,b=s.length,A=0,k=[],M=[],S=[],O=[],C=[],v=a.stackSave(),U=a.stackAlloc(x*i),j=a.stackAlloc(x*i),F=a.stackAlloc(b*i),K=a.stackAlloc(b*i);try{[A,k]=VT(o),Kr("wasm prepareInputOutputTensor");for(let I=0;Iqe*Ce,1);L=eu(ge);let et=m?.outputPreferredLocations[s[I]];if(L==="string"){if(et==="gpu-buffer"||et==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let qe=[];for(let Ce=0;Ce0){let qe=a.webgpuGetBuffer;if(!qe)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Ce=qe(z),at=In(ge,Re);if(at===void 0||!am(L))throw new Error(`Unsupported data type: ${L}`);me=!0;{a.webgpuRegisterBuffer(Ce,t,z);let lr=a.webgpuCreateDownloader(Ce,at,t);Q.push([L,Fe,{gpuBuffer:Ce,download:async()=>{let Pe=await lr();return new(qo(L))(Pe)},dispose:()=>{a._OrtReleaseTensor(oe)!==0&&ze("Can't release tensor.")}},"gpu-buffer"])}}else if(et==="ml-tensor"&&Re>0){let qe=a.webnnEnsureTensor,Ce=a.webnnIsGraphInputOutputTypeSupported;if(!qe||!Ce)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(In(ge,Re)===void 0||!im(L))throw new Error(`Unsupported data type: ${L}`);if(!Ce(t,L,!1))throw new Error(`preferredLocation "ml-tensor" for ${L} output is not supported by current WebNN Context.`);let at=await qe(t,z,ge,Fe,!1);me=!0,Q.push([L,Fe,{mlTensor:at,download:a.webnnCreateMLTensorDownloader(z,L),dispose:()=>{a.webnnReleaseTensorId(z),a._OrtReleaseTensor(oe)}},"ml-tensor"])}else if(et==="ml-tensor-cpu-output"&&Re>0){let qe=a.webnnCreateMLTensorDownloader(z,L)(),Ce=Q.length;me=!0,B.push((async()=>{let at=[Ce,await qe];return a.webnnReleaseTensorId(z),a._OrtReleaseTensor(oe),at})()),Q.push([L,Fe,[],"cpu"])}else{let qe=qo(L),Ce=new qe(Re);new Uint8Array(Ce.buffer,Ce.byteOffset,Ce.byteLength).set(a.HEAPU8.subarray(z,z+Ce.byteLength)),Q.push([L,Fe,Ce,"cpu"])}}finally{a.stackRestore(J),L==="string"&&z&&a._free(z),me||a._OrtReleaseTensor(oe)}}m&&!_&&(a._OrtClearBoundOutputs(m.handle)!==0&&ze("Can't clear bound outputs."),Hr.set(t,[c,u,f,m,_,!1]));for(let[I,oe]of await Promise.all(B))Q[I][2]=oe;return Yr("wasm ProcessOutputTensor"),Q}finally{a.webnnOnRunEnd?.(c),a.stackRestore(v),r.forEach(Y=>{Y&&Y[3]==="gpu-buffer"&&a.webgpuUnregisterBuffer(Y[2].gpuBuffer)}),n.forEach(Y=>{Y&&Y[3]==="gpu-buffer"&&a.webgpuUnregisterBuffer(Y[2].gpuBuffer)}),M.forEach(Y=>a._OrtReleaseTensor(Y)),S.forEach(Y=>a._OrtReleaseTensor(Y)),O.forEach(Y=>a._free(Y)),A!==0&&a._OrtReleaseRunOptions(A),k.forEach(Y=>a._free(Y))}},mm=t=>{let e=je(),r=Hr.get(t);if(!r)throw new Error("invalid session id");let s=r[0],n=e._OrtEndProfiling(s);n===0&&ze("Can't get an profile file name."),e._OrtFree(n)},_m=t=>{let e=[];for(let r of t){let s=r[2];!Array.isArray(s)&&"buffer"in s&&e.push(s.buffer)}return e}}),Xr,Vt,On,Fo,Go,Jc,Hd,Zc,Ps,Ns,wT,rS,sS,nS,oS,aS,iS,lS,cS=Ae(()=>{"use strict";Ds(),tS(),Us(),sm(),Xr=()=>!!Je.wasm.proxy&&typeof document<"u",On=!1,Fo=!1,Go=!1,Zc=new Map,Ps=(t,e)=>{let r=Zc.get(t);r?r.push(e):Zc.set(t,[e])},Ns=()=>{if(On||!Fo||Go||!Vt)throw new Error("worker not ready")},wT=t=>{switch(t.data.type){case"init-wasm":On=!1,t.data.err?(Go=!0,Hd[1](t.data.err)):(Fo=!0,Hd[0]()),Jc&&(URL.revokeObjectURL(Jc),Jc=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let e=Zc.get(t.data.type);t.data.err?e.shift()[1](t.data.err):e.shift()[0](t.data.out);break}default:}},rS=async()=>{if(!Fo){if(On)throw new Error("multiple calls to 'initWasm()' detected.");if(Go)throw new Error("previous call to 'initWasm()' failed.");if(On=!0,Xr())return new Promise((t,e)=>{Vt?.terminate(),qT().then(([r,s])=>{try{Vt=s,Vt.onerror=o=>e(o),Vt.onmessage=wT,Hd=[t,e];let n={type:"init-wasm",in:Je};!n.in.wasm.wasmPaths&&(r||Kd)&&(n.in.wasm.wasmPaths={wasm:new URL("ort-wasm-simd-threaded.asyncify.wasm",import.meta.url).href}),Vt.postMessage(n),Jc=r}catch(n){e(n)}},e)});try{await nm(Je.wasm),await cm(Je),Fo=!0}catch(t){throw Go=!0,t}finally{On=!1}}},sS=async t=>{if(Xr())return Ns(),new Promise((e,r)=>{Ps("init-ep",[e,r]);let s={type:"init-ep",in:{epName:t,env:Je}};Vt.postMessage(s)});await um(Je,t)},nS=async t=>Xr()?(Ns(),new Promise((e,r)=>{Ps("copy-from",[e,r]);let s={type:"copy-from",in:{buffer:t}};Vt.postMessage(s,[t.buffer])})):ou(t),oS=async(t,e)=>{if(Xr()){if(e?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Ns(),new Promise((r,s)=>{Ps("create",[r,s]);let n={type:"create",in:{model:t,options:{...e}}},o=[];t instanceof Uint8Array&&o.push(t.buffer),Vt.postMessage(n,o)})}else return pm(t,e)},aS=async t=>{if(Xr())return Ns(),new Promise((e,r)=>{Ps("release",[e,r]);let s={type:"release",in:t};Vt.postMessage(s)});fm(t)},iS=async(t,e,r,s,n,o)=>{if(Xr()){if(r.some(a=>a[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(n.some(a=>a))throw new Error("pre-allocated output tensor is not supported for proxy.");return Ns(),new Promise((a,i)=>{Ps("run",[a,i]);let l=r,c={type:"run",in:{sessionId:t,inputIndices:e,inputs:l,outputIndices:s,options:o}};Vt.postMessage(c,_m(l))})}else return dm(t,e,r,s,n,o)},lS=async t=>{if(Xr())return Ns(),new Promise((e,r)=>{Ps("end-profiling",[e,r]);let s={type:"end-profiling",in:t};Vt.postMessage(s)});mm(t)}}),Xd,xT,uS,H$=Ae(()=>{"use strict";Ds(),cS(),Cn(),rm(),XT(),Xd=(t,e)=>{switch(t.location){case"cpu":return[t.type,t.dims,t.data,"cpu"];case"gpu-buffer":return[t.type,t.dims,{gpuBuffer:t.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[t.type,t.dims,{mlTensor:t.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${t.location} for ${e()}`)}},xT=t=>{switch(t[3]){case"cpu":return new sr(t[0],t[2],t[1]);case"gpu-buffer":{let e=t[0];if(!am(e))throw new Error(`not supported data type: ${e} for deserializing GPU tensor`);let{gpuBuffer:r,download:s,dispose:n}=t[2];return sr.fromGpuBuffer(r,{dataType:e,dims:t[1],download:s,dispose:n})}case"ml-tensor":{let e=t[0];if(!im(e))throw new Error(`not supported data type: ${e} for deserializing MLTensor tensor`);let{mlTensor:r,download:s,dispose:n}=t[2];return sr.fromMLTensor(r,{dataType:e,dims:t[1],download:s,dispose:n})}default:throw new Error(`invalid data location: ${t[3]}`)}},uS=class{async fetchModelAndCopyToWasmMemory(t){return nS(await lm(t))}async loadModel(t,e){Rs();let r;typeof t=="string"?r=await this.fetchModelAndCopyToWasmMemory(t):r=t,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await oS(r,e),Bs()}async dispose(){return aS(this.sessionId)}async run(t,e,r){Rs();let s=[],n=[];Object.entries(t).forEach(f=>{let m=f[0],_=f[1],w=this.inputNames.indexOf(m);if(w===-1)throw new Error(`invalid input '${m}'`);s.push(_),n.push(w)});let o=[],a=[];Object.entries(e).forEach(f=>{let m=f[0],_=f[1],w=this.outputNames.indexOf(m);if(w===-1)throw new Error(`invalid output '${m}'`);o.push(_),a.push(w)});let i=s.map((f,m)=>Xd(f,()=>`input "${this.inputNames[n[m]]}"`)),l=o.map((f,m)=>f?Xd(f,()=>`output "${this.outputNames[a[m]]}"`):null),c=await iS(this.sessionId,n,i,a,l,r),u={};for(let f=0;fJd,initializeFlags:()=>Qd,wasmBackend:()=>fS});var Qd,Jd,fS,X$=Ae(()=>{"use strict";Ds(),cS(),H$(),Qd=()=>{(typeof Je.wasm.initTimeout!="number"||Je.wasm.initTimeout<0)&&(Je.wasm.initTimeout=0);let t=Je.wasm.simd;if(typeof t!="boolean"&&t!==void 0&&t!=="fixed"&&t!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${t}". Reset it to \`false\` and ignore SIMD feature checking.`),Je.wasm.simd=!1),typeof Je.wasm.proxy!="boolean"&&(Je.wasm.proxy=!1),typeof Je.wasm.trace!="boolean"&&(Je.wasm.trace=!1),typeof Je.wasm.numThreads!="number"||!Number.isInteger(Je.wasm.numThreads)||Je.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)Je.wasm.numThreads=1;else{let e=typeof navigator>"u"?A$("node:os").cpus().length:navigator.hardwareConcurrency;Je.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},Jd=class{async init(t){Qd(),await rS(),await sS(t)}async createInferenceSessionHandler(t,e){let r=new uS;return await r.loadModel(t,e),r}},fS=new Jd});Ds();Ds();Ds();var K$="1.31.0-dev.20260914-8d85527a0",Y$=BT;{let t=(X$(),tu(pS)).wasmBackend;$s("webgpu",t,5),$s("webnn",t,5),$s("cpu",t,10),$s("wasm",t,10)}Object.defineProperty(Je.versions,"web",{value:K$,enumerable:!0});async function dS(t){let e=t.split("/").pop(),r;try{if(r=await rr(),r){let n=await r.match(t);if(n)return n}}catch(n){te.warn(`Failed to load ${e} from cache:`,n)}let s=await he.fetch(t);if(!s.ok)throw new Error(`Failed to fetch ${e}: ${s.status} ${s.statusText}`);if(r)try{await r.put(t,s.clone())}catch(n){te.warn(`Failed to cache ${e}:`,n)}return s}async function mS(t){let e=await dS(t);if(!e||typeof e=="string")return null;try{return await e.arrayBuffer()}catch(r){return te.warn("Failed to read WASM binary:",r),null}}async function _S(t){if(le.IS_SERVICE_WORKER_ENV||le.IS_CHROME_AVAILABLE)return t;let e=await dS(t);if(!e||typeof e=="string")return null;try{let r=await e.text();r=r.replaceAll("globalThis.process?.versions?.node","false");let s=new Blob([r],{type:"text/javascript"});return URL.createObjectURL(s)}catch(r){return te.warn("Failed to read WASM factory:",r),null}}var hS="1.30.0";var gS="warning",gm={wasm:{},webgl:{},webgpu:{},versions:{common:hS},set logLevel(t){if(t!==void 0){if(typeof t!="string"||["verbose","info","warning","error","fatal"].indexOf(t)===-1)throw new Error(`Unsupported logging level: ${t}`);gS=t}},get logLevel(){return gS}};Object.defineProperty(gm,"logLevel",{enumerable:!0});var wS=(t,e)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=t.dims[3],r.height=t.dims[2];let s=r.getContext("2d");if(s!=null){let n,o;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],o=t.dims[3]):(n=t.dims[3],o=t.dims[2]);let a=e?.format!==void 0?e.format:"RGB",i=e?.norm,l,c;i===void 0||i.mean===void 0?l=[255,255,255,255]:typeof i.mean=="number"?l=[i.mean,i.mean,i.mean,i.mean]:(l=[i.mean[0],i.mean[1],i.mean[2],0],i.mean[3]!==void 0&&(l[3]=i.mean[3])),i===void 0||i.bias===void 0?c=[0,0,0,0]:typeof i.bias=="number"?c=[i.bias,i.bias,i.bias,i.bias]:(c=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(c[3]=i.bias[3]));let u=o*n,f=0,m=u,_=u*2,w=-1;a==="RGBA"?(f=0,m=u,_=u*2,w=u*3):a==="RGB"?(f=0,m=u,_=u*2):a==="RBG"&&(f=0,_=u,m=u*2);for(let x=0;x{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(r!=null){let n,o,a;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],o=t.dims[1],a=t.dims[3]):(n=t.dims[3],o=t.dims[2],a=t.dims[1]);let i=e!==void 0&&e.format!==void 0?e.format:"RGB",l=e?.norm,c,u;l===void 0||l.mean===void 0?c=[255,255,255,255]:typeof l.mean=="number"?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(c[3]=l.mean[3])),l===void 0||l.bias===void 0?u=[0,0,0,0]:typeof l.bias=="number"?u=[l.bias,l.bias,l.bias,l.bias]:(u=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(u[3]=l.bias[3]));let f=o*n;if(e!==void 0&&(e.format!==void 0&&a===4&&e.format!=="RGBA"||a===3&&e.format!=="RGB"&&e.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let m=4,_=0,w=1,x=2,b=3,A=0,k=f,M=f*2,S=-1;i==="RGBA"?(A=0,k=f,M=f*2,S=f*3):i==="RGB"?(A=0,k=f,M=f*2):i==="RBG"&&(A=0,M=f,k=f*2),s=r.createImageData(n,o);for(let O=0;O{if(t===void 0)throw new Error("Image buffer must be defined");if(e.height===void 0||e.width===void 0)throw new Error("Image height and width must be defined");if(e.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:s}=e,n=e.norm??{mean:255,bias:0},o,a;typeof n.mean=="number"?o=[n.mean,n.mean,n.mean,n.mean]:o=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?a=[n.bias,n.bias,n.bias,n.bias]:a=[n.bias[0],n.bias[1],n.bias[2],n.bias[3]??0];let i=e.format!==void 0?e.format:"RGBA",l=e.tensorFormat!==void 0&&e.tensorFormat!==void 0?e.tensorFormat:"RGB",c=r*s,u=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),f=4,m=0,_=1,w=2,x=3,b=0,A=c,k=c*2,M=-1;i==="RGB"&&(f=3,m=0,_=1,w=2,x=-1),l==="RGBA"?M=c*3:l==="RBG"?(b=0,k=c,A=c*2):l==="BGR"&&(k=0,A=c,b=c*2);for(let O=0;O{let r=typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement,s=typeof ImageData<"u"&&t instanceof ImageData,n=typeof ImageBitmap<"u"&&t instanceof ImageBitmap,o=typeof t=="string",a,i=e??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=u=>typeof HTMLCanvasElement<"u"&&u instanceof HTMLCanvasElement||u instanceof OffscreenCanvas?u.getContext("2d"):null;if(r){let u=l();u.width=t.width,u.height=t.height;let f=c(u);if(f!=null){let m=t.height,_=t.width;if(e!==void 0&&e.resizedHeight!==void 0&&e.resizedWidth!==void 0&&(m=e.resizedHeight,_=e.resizedWidth),e!==void 0){if(i=e,e.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");i.tensorFormat="RGBA",i.height=m,i.width=_}else i.tensorFormat="RGBA",i.height=m,i.width=_;f.drawImage(t,0,0),a=f.getImageData(0,0,_,m).data}else throw new Error("Can not access image data")}else if(s){let u,f;if(e!==void 0&&e.resizedWidth!==void 0&&e.resizedHeight!==void 0?(u=e.resizedHeight,f=e.resizedWidth):(u=t.height,f=t.width),e!==void 0&&(i=e),i.format="RGBA",i.height=u,i.width=f,e!==void 0){let m=l();m.width=f,m.height=u;let _=c(m);if(_!=null)_.putImageData(t,0,0),a=_.getImageData(0,0,f,u).data;else throw new Error("Can not access image data")}else a=t.data}else if(n){if(e===void 0)throw new Error("Please provide image config with format for Imagebitmap");let u=l();u.width=t.width,u.height=t.height;let f=c(u);if(f!=null){let m=t.height,_=t.width;return f.drawImage(t,0,0,_,m),a=f.getImageData(0,0,_,m).data,i.height=m,i.width=_,wm(a,i)}else throw new Error("Can not access image data")}else{if(o)return new Promise((u,f)=>{let m=l(),_=c(m);if(!t||!_)return f();let w=new Image;w.crossOrigin="Anonymous",w.src=t,w.onload=()=>{m.width=w.width,m.height=w.height,_.drawImage(w,0,0,m.width,m.height);let x=_.getImageData(0,0,m.width,m.height);i.height=m.height,i.width=m.width,u(wm(x.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==void 0)return wm(a,i);throw new Error("Input data provided is not supported - aborted tensor creation")},bS=(t,e)=>{let{width:r,height:s,download:n,dispose:o}=e,a=[1,s,r,4];return new vt({location:"texture",type:"float32",texture:t,dims:a,download:n,dispose:o})},vS=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new vt({location:"gpu-buffer",type:r??"float32",gpuBuffer:t,dims:s,download:n,dispose:o})},kS=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new vt({location:"ml-tensor",type:r??"float32",mlTensor:t,dims:s,download:n,dispose:o})},ES=(t,e,r)=>new vt({location:"cpu-pinned",type:t,data:e,dims:r??[e.length]});var Fs=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Vo=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),AS=!1,TS=()=>{if(!AS){AS=!0;let t=typeof BigInt64Array<"u"&&BigInt64Array.from,e=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,s=typeof r<"u"&&r.from;t&&(Fs.set("int64",BigInt64Array),Vo.set(BigInt64Array,"int64")),e&&(Fs.set("uint64",BigUint64Array),Vo.set(BigUint64Array,"uint64")),s?(Fs.set("float16",r),Vo.set(r,"float16")):Fs.set("float16",Uint16Array)}};var SS=t=>{let e=1;for(let r=0;r{switch(t.location){case"cpu":return new vt(t.type,t.data,e);case"cpu-pinned":return new vt({location:"cpu-pinned",data:t.data,type:t.type,dims:e});case"texture":return new vt({location:"texture",texture:t.texture,type:t.type,dims:e});case"gpu-buffer":return new vt({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:e});case"ml-tensor":return new vt({location:"ml-tensor",mlTensor:t.mlTensor,type:t.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}};var vt=class{constructor(e,r,s){TS();let n,o;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,n=e.type,o=e.dims,e.location){case"cpu-pinned":{let i=Fs.get(n);if(!i)throw new TypeError(`unsupported type "${n}" to create tensor from pinned buffer`);if(!(e.data instanceof i))throw new TypeError(`buffer should be of type ${i.name}`);this.cpuData=e.data;break}case"texture":{if(n!=="float32")throw new TypeError(`unsupported type "${n}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}case"ml-tensor":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint64"&&n!=="int8"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let i,l;if(typeof e=="string")if(n=e,l=s,e==="string"){if(!Array.isArray(r))throw new TypeError("A string tensor's data must be a string array.");i=r}else{let c=Fs.get(e);if(c===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(r)){if(e==="float16"&&c===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${c.name} as data.`);e==="uint64"||e==="int64"?i=c.from(r,BigInt):i=c.from(r)}else if(r instanceof c)i=r;else if(r instanceof Uint8ClampedArray)if(e==="uint8")i=Uint8Array.from(r);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(e==="float16"&&r instanceof Uint16Array&&c!==Uint16Array)i=new globalThis.Float16Array(r.buffer,r.byteOffset,r.length);else throw new TypeError(`A ${n} tensor's data must be type of ${c}`)}else if(l=r,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let c=typeof e[0];if(c==="string")n="string",i=e;else if(c==="boolean")n="bool",i=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${c}.`)}else if(e instanceof Uint8ClampedArray)n="uint8",i=Uint8Array.from(e);else{let c=Vo.get(e.constructor);if(c===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);n=c,i=e}if(l===void 0)l=[i.length];else if(!Array.isArray(l))throw new TypeError("A tensor's dims must be a number array");o=l,this.cpuData=i,this.dataLocation="cpu"}let a=SS(o);if(this.cpuData&&a!==this.cpuData.length&&!((n==="uint4"||n==="int4")&&Math.ceil(a/2)===this.cpuData.length))throw new Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=n,this.dims=o,this.size=a}static async fromImage(e,r){return yS(e,r)}static fromTexture(e,r){return bS(e,r)}static fromGpuBuffer(e,r){return vS(e,r)}static fromMLTensor(e,r){return kS(e,r)}static fromPinnedBuffer(e,r,s){return ES(e,r,s)}toDataURL(e){return wS(this,e)}toImageData(e){return xS(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let r=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=r,e&&this.disposer&&(this.disposer(),this.disposer=void 0),r}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return MS(this,e)}};var au=vt;var Q$=Object.freeze({auto:null,gpu:null,cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",coreml:"coreml",webnn:{name:"webnn",deviceType:"cpu"},"webnn-npu":{name:"webnn",deviceType:"npu"},"webnn-gpu":{name:"webnn",deviceType:"gpu"},"webnn-cpu":{name:"webnn",deviceType:"cpu"}});function PS(t){return t<=It.DEBUG?0:t<=It.INFO?2:t<=It.WARNING||t<=It.ERROR?3:4}var J$={0:"verbose",1:"info",2:"warning",3:"error",4:"fatal"},Rt=[],xm,Nn,OS=Symbol.for("onnxruntime");if(OS in globalThis)Nn=globalThis[OS];else if(le.IS_NODE_ENV){switch(Nn=W2,process.platform){case"win32":Rt.push("dml");break;case"linux":process.arch==="x64"&&Rt.push("cuda");break;case"darwin":Rt.push("coreml");break}Rt.push("webgpu"),Rt.push("cpu"),xm=["cpu"]}else Nn=hm,le.IS_WEBNN_AVAILABLE&&Rt.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),le.IS_WEBGPU_AVAILABLE&&Rt.push("webgpu"),Rt.push("wasm"),xm=["wasm"];function Z$(){return[...Rt]}var eR=Nn.InferenceSession;function NS(t=null){if(!t)return xm;switch(t){case"auto":return Rt;case"gpu":return Rt.filter(e=>["webgpu","cuda","dml","webnn-gpu"].includes(e))}if(Rt.includes(t))return[Q$[t]??t];throw new Error(`Unsupported device: "${t}". Should be one of: ${Rt.join(", ")}.`)}var IS=Promise.resolve(),Pn=null;async function tR(){if(Pn)return Pn;if(!(he.useWasmCache&&typeof ft?.wasm?.wasmPaths=="object"&&ft?.wasm?.wasmPaths?.wasm&&ft?.wasm?.wasmPaths?.mjs)){if(le.IS_DENO_WEB_RUNTIME)throw new Error("env.useWasmCache=false is not supported in Deno's web runtime. Remove the useWasmCache override.");return Pn=Promise.resolve(),Pn}return Pn=(async()=>{let e=ft.wasm.wasmPaths,r=!1;await Promise.all([e.wasm&&!vd(e.wasm)?(async()=>{try{let s=await mS(No(e.wasm));s&&(ft.wasm.wasmBinary=s,r=!0)}catch(s){te.warn("Failed to pre-load WASM binary:",s)}})():Promise.resolve(),e.mjs&&!vd(e.mjs)?(async()=>{try{let s=await _S(No(e.mjs));s&&(ft.wasm.wasmPaths.mjs=s)}catch(s){te.warn("Failed to pre-load WASM factory:",s)}})():Promise.resolve()]),r||(ft.wasm.wasmPaths.mjs=e.mjs)})(),Pn}async function iu(t,e,r){await tR();let s=PS(he.logLevel??It.WARNING),n=()=>eR.create(t,{logSeverityLevel:s,...e}),o=await(le.IS_WEB_ENV?IS=IS.then(n):n());return o.config=r,o}var CS=Promise.resolve();async function lu(t,e){let r=()=>t.run(e);return le.IS_WEB_ENV?CS=CS.then(r):r()}function cu(t){return t instanceof Nn.Tensor}var ft=Nn?.env;function Ho(){return ft?.wasm?.proxy}if(ft){let t=function(e){let r=PS(e);ft.logLevel=J$[r]};if(ft.wasm){if(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&ft.versions?.web&&!ft.wasm.wasmPaths){let e=`https://cdn.jsdelivr.net/npm/onnxruntime-web@${ft.versions.web}/dist/`,r=".asyncify";le.IS_SAFARI_BELOW_26&&!le.IS_WEBGPU_AVAILABLE&&(r=""),ft.wasm.wasmPaths={mjs:`${e}ort-wasm-simd-threaded${r}.mjs`,wasm:`${e}ort-wasm-simd-threaded${r}.wasm`}}ft.wasm.proxy=!1}ft.webgpu&&(ft.webgpu.powerPreference="high-performance"),t(he.logLevel??It.WARNING),he.backends.onnx={...ft,setLogLevel:t,getSupportedDevices:Z$}}var Qr=async(t,e,r)=>{let s=await iu(new Uint8Array(t),e);return(async n=>{let o=Ho(),a=Object.fromEntries(Object.entries(n).map(([l,c])=>[l,(o?c.clone():c).ort_tensor])),i=await lu(s,a);return Array.isArray(r)?r.map(l=>new $(i[l])):new $(i[r])})},hr=class{static session_options={};static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=Qr([8,10,18,0,58,129,1,10,41,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,18,10,4,109,111,100,101,34,7,110,101,97,114,101,115,116,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,21],this.session_options,"y")),this._nearest_interpolate_4d}static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=Qr([8,9,18,0,58,128,1,10,40,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,17,10,4,109,111,100,101,34,6,108,105,110,101,97,114,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bilinear_interpolate_4d}static get bicubic_interpolate_4d(){return this._bicubic_interpolate_4d||(this._bicubic_interpolate_4d=Qr([8,9,18,0,58,127,10,39,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,16,10,4,109,111,100,101,34,5,99,117,98,105,99,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bicubic_interpolate_4d}static get matmul(){return this._matmul||(this._matmul=Qr([8,9,18,0,58,55,10,17,10,1,97,10,1,98,18,1,99,34,6,77,97,116,77,117,108,18,1,114,90,9,10,1,97,18,4,10,2,8,1,90,9,10,1,98,18,4,10,2,8,1,98,9,10,1,99,18,4,10,2,8,1,66,2,16,20],this.session_options,"c")),this._matmul}static get stft(){return this._stft||(this._stft=Qr([8,7,18,0,58,148,1,10,38,10,1,115,10,1,106,10,1,119,10,1,108,18,1,111,34,4,83,84,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,115,90,26,10,1,115,18,21,10,19,8,1,18,15,10,3,18,1,98,10,3,18,1,115,10,3,18,1,99,90,11,10,1,106,18,6,10,4,8,7,18,0,90,16,10,1,119,18,11,10,9,8,1,18,5,10,3,18,1,119,90,11,10,1,108,18,6,10,4,8,7,18,0,98,31,10,1,111,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,102,10,3,18,1,100,10,3,18,1,99,66,2,16,17],this.session_options,"o")),this._stft}static get rfft(){return this._rfft||(this._rfft=Qr([8,9,58,93,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,19,10,1,120,18,14,10,12,8,1,18,8,10,0,10,0,10,2,8,1,90,11,10,1,97,18,6,10,4,8,7,18,0,98,19,10,1,121,18,14,10,12,8,1,18,8,10,0,10,0,10,2,8,2,66,2,16,20],this.session_options,"y")),this._rfft}static get top_k(){return this._top_k||(this._top_k=Qr([8,10,18,0,58,73,10,18,10,1,120,10,1,107,18,1,118,18,1,105,34,4,84,111,112,75,18,1,116,90,9,10,1,120,18,4,10,2,8,1,90,15,10,1,107,18,10,10,8,8,7,18,4,10,2,8,1,98,9,10,1,118,18,4,10,2,8,1,98,9,10,1,105,18,4,10,2,8,7,66,2,16,21],this.session_options,["v","i"])),this._top_k}static get slice(){return this._slice||(this._slice=Qr([8,7,18,0,58,96,10,25,10,1,120,10,1,115,10,1,101,10,1,97,10,1,116,18,1,121,34,5,83,108,105,99,101,18,1,114,90,9,10,1,120,18,4,10,2,8,1,90,9,10,1,115,18,4,10,2,8,7,90,9,10,1,101,18,4,10,2,8,7,90,9,10,1,97,18,4,10,2,8,7,90,9,10,1,116,18,4,10,2,8,7,98,9,10,1,121,18,4,10,2,8,1,66,2,16,13],this.session_options,"y")),this._slice}};var LS=Object.freeze({auto:"auto",gpu:"gpu",cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",coreml:"coreml",webnn:"webnn","webnn-npu":"webnn-npu","webnn-gpu":"webnn-gpu","webnn-cpu":"webnn-cpu"}),ym=le.IS_NODE_ENV?"cpu":"wasm";function uu(t,e,{warn:r}={}){return t?typeof t=="string"?t:t.hasOwnProperty(e)?t[e]:(r&&r(`device not specified for "${e}". Using the default device (${ym}).`),ym):ym}var RS=(function(){let t;return async function(){if(t===void 0)if(!le.IS_WEBGPU_AVAILABLE)t=!1;else try{t=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{t=!1}return t}})(),it=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16",q2:"q2",q2f16:"q2f16",q1:"q1",q1f16:"q1f16"}),zS=it.fp32,$S=Object.freeze({[LS.wasm]:it.q8}),Jr=Object.freeze({[it.fp32]:"",[it.fp16]:"_fp16",[it.int8]:"_int8",[it.uint8]:"_uint8",[it.q8]:"_quantized",[it.q4]:"_q4",[it.q2]:"_q2",[it.q1]:"_q1",[it.q4f16]:"_q4f16",[it.q2f16]:"_q2f16",[it.q1f16]:"_q1f16",[it.bnb4]:"_bnb4"});function pu(t,e,r,{configDtype:s=null,warn:n}={}){let o,a=!1;t&&typeof t!="string"?t.hasOwnProperty(e)?o=t[e]:(o=null,a=!0):o=t;let i;if(o===it.auto){if(s){let l=typeof s=="string"?s:s?.[e];if(l&&l!==it.auto&&it.hasOwnProperty(l))return l}i=$S[r]??zS}else o&&it.hasOwnProperty(o)?i=o:i=$S[r]??zS;return a&&n&&n(`dtype not specified for "${e}". Using the default dtype (${i}) for this device (${r}).`),i}var Zr=Object.freeze({float32:Float32Array,float16:typeof Float16Array<"u"?Float16Array:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array,uint4:Uint8Array,int4:Int8Array});var $=class t{get dims(){return this.ort_tensor.dims}set dims(e){this.ort_tensor.dims=e}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}ort_tensor;constructor(...e){return cu(e[0])?this.ort_tensor=e[0]:this.ort_tensor=new au(e[0],e[1],e[2]),new Proxy(this,{get:(r,s)=>{if(typeof s=="string"){let n=Number(s);if(Number.isInteger(n))return r._getitem(n)}return r[s]},set:(r,s,n)=>r[s]=n})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){let[e,...r]=this.dims;if(r.length>0){let s=r.reduce((n,o)=>n*o);for(let n=0;n0){let n=s.reduce((o,a)=>o*a);return this._subarray(e,n,s)}else return new t(this.type,[this.data[e]],s)}_subarray(e,r,s){let n=e*r,o=(e+1)*r,a="subarray"in this.data?this.data.subarray(n,o):this.data.slice(n,o);return new t(this.type,a,s)}item(){let e=this.data;if(e.length!==1)throw new Error(`a Tensor with ${e.length} elements cannot be converted to Scalar`);return e[0]}tolist(){return rR(this.data,this.dims)}sigmoid(){return this.clone().sigmoid_()}sigmoid_(){let e=this.data;for(let r=0;r0||a>0&&n<0;r[o]=i?a+n:a}return this}clone(){return new t(this.type,this.data.slice(),this.dims.slice())}slice(...e){let r=[],s=[];for(let u=0;u_)throw new Error(`Invalid slice: ${f}`);let w=[Math.max(m,0),Math.min(_,this.dims[u])];s.push(w),r.push(w[1]-w[0])}else throw new Error(`Invalid slice: ${f}`)}let n=s.map(([u,f])=>f-u),o=n.reduce((u,f)=>u*f),a=this.data,i=new a.constructor(o),l=this.stride(),c=!0;for(let u=1;u=0;--m){let w=n[m];f+=(_%w+s[m][0])*l[m],_=Math.floor(_/w)}i[u]=a[f]}return new t(this.type,i,r)}permute(...e){return sR(this,e)}transpose(...e){return this.permute(...e)}sum(e=null,r=!1){return this.norm(1,e,r)}norm(e="fro",r=null,s=!1){if(e==="fro")e=2;else if(typeof e=="string")throw Error(`Unsupported norm: ${e}`);let n=this.data,o=n instanceof BigInt64Array||n instanceof BigUint64Array;if(o&&e!==1)throw Error(`Expected a floating point tensor as input. Got ${this.type}`);let a,i;if(o?(a=(f,m)=>f+m,i=0n):(a=(f,m)=>f+m**e,i=0),r===null){let f=n.reduce(a,i);return e!==1&&(f=f**(1/e)),new t(this.type,[f],[])}let[l,c,u]=Xo(a,this,r,s);if(e!==1)for(let f=0;f=0;--l){let f=this.dims[l];if(l!==r){let m=c%f;i+=m*u,u*=this.dims[l]}c=Math.floor(c/f)}n[a]/=o[i]}return this}normalize(e=2,r=1){return this.clone().normalize_(e,r)}stride(){return bm(this.dims)}squeeze(e=null){return new t(this.type,this.data,BS(this.dims,e))}squeeze_(e=null){return this.dims=BS(this.dims,e),this}unsqueeze(e){return new t(this.type,this.data,DS(this.dims,e))}unsqueeze_(e){return this.dims=DS(this.dims,e),this}flatten_(e=0,r=-1){r=(r+this.dims.length)%this.dims.length;let s=this.dims.slice(0,e),n=this.dims.slice(e,r+1),o=this.dims.slice(r+1);return this.dims=[...s,n.reduce((a,i)=>a*i,1),...o],this}flatten(e=0,r=-1){return this.clone().flatten_(e,r)}view(...e){let r=-1;for(let n=0;ni!==r?o*a:o,1);e[r]=s.length/n}return new t(this.type,s,e)}neg_(){let e=this.data;for(let r=0;re?1:0;return new t("bool",r,this.dims)}lt(e){let r=new Uint8Array(this.data.length),s=this.data;for(let n=0;nMath.min(a,i),this,e,r,1/0);return new t(s,n,o)}max(e=null,r=!1){if(e===null){let a=Le(this.data)[0];return new t(this.type,[a],[])}let[s,n,o]=Xo((a,i)=>Math.max(a,i),this,e,r,-1/0);return new t(s,n,o)}argmin(e=null,r=!1){if(e!==null)throw new Error("`dim !== null` not yet implemented.");let s=Ro(this.data)[1];return new t("int64",[BigInt(s)],[])}argmax(e=null,r=!1){if(e!==null)throw new Error("`dim !== null` not yet implemented.");let s=Le(this.data)[1];return new t("int64",[BigInt(s)],[])}repeat(...e){if(e.lengthu===1)){if(e.length===this.dims.length)return this.clone();let u=e.length-this.dims.length,f=Array(u).fill(1).concat(this.dims);return new t(this.type,this.data.slice(),f)}let r=e.length-this.dims.length,s=Array(r).fill(1).concat(this.dims),n=s.map((u,f)=>u*e[f]),o=n.reduce((u,f)=>u*f,1),a=this.data,i=new a.constructor(o),l=bm(s),c=bm(n);for(let u=0;uBigInt(Math.floor(o)):r=BigInt;else if(this.type==="float16"&&e=="float32"&&this.data instanceof Uint16Array)return new t(e,q2(this.data),this.dims);return new t(e,Zr[e].from(this.data,r),this.dims)}};function rR(t,e){let r=t.length,s=e.length===0?1:e.reduce((o,a)=>o*a);if(r!==s)throw Error(`cannot reshape array of size ${r} into shape (${e})`);let n=t;for(let o=e.length-1;o>=0;o--)n=n.reduce((a,i)=>{let l=a[a.length-1];return l.lengthnew $("int64",t,[t.length]);async function du(t,e,r,s,n){return await(await hr.slice)({x:t,s:fu(e),e:fu(r),a:fu(s),t:fu(n??new Array(s.length).fill(1))})}function FS(t,e){let r=t.data,s=e.data,n=[t.dims[0],t.dims[2]],o=new r.constructor(n[0]*n[1]),[a,i,l]=t.dims,c=0;for(let u=0;ur!==1):typeof e=="number"?t[e]===1&&t.splice(e,1):Array.isArray(e)&&(t=t.filter((r,s)=>r!==1||!e.includes(s))),t}function DS(t,e){return e=nr(e,t.length+1),t=t.slice(),t.splice(e,0,1),t}function nr(t,e,r=null,s=!0){if(t<-e||t>=e){if(s)throw new Error(`IndexError: index ${t} is out of bounds for dimension${r===null?"":" "+r} with size ${e}`);return t<-e?0:e}return t<0&&(t=(t%e+e)%e),t}function Ee(t,e=0){e=nr(e,t[0].dims.length);let r=t[0].dims.slice();r[e]=t.reduce((a,i)=>a+i.dims[e],0);let s=r.reduce((a,i)=>a*i,1),n=new t[0].data.constructor(s),o=t[0].type;if(e===0){let a=0;for(let i of t){let l=i.data;n.set(l,a),a+=l.length}}else{let a=0;for(let i=0;i=0;--m){let x=c[m],b=_%x;m===e&&(b+=a),f+=b*w,w*=r[m],_=Math.floor(_/x)}n[f]=l[u]}a+=c[e]}}return new $(o,n,r)}function kt(t,e=0){return Ee(t.map(r=>r.unsqueeze(e)),e)}function Xo(t,e,r,s=!1,n=null){let o=e.data,a=e.dims;r=nr(r,a.length);let i=a.slice();i[r]=1;let l=new o.constructor(o.length/a[r]);n!==null&&l.fill(n);for(let c=0;c=0;--f){let w=a[f];if(f!==r){let x=m%w;u+=x*_,_*=i[f]}m=Math.floor(m/w)}l[u]=t(l[u],o[c],c,u)}return s||i.splice(r,1),[e.type,l,i]}function km(t,e=null,r=1,s=!1){let n=t.data,o=t.dims;if(e===null){let _=n.reduce((A,k)=>A+k,0)/n.length,w=Math.sqrt(n.reduce((A,k)=>A+(k-_)**2,0)/(n.length-r)),x=new $(t.type,[_],[]);return[new $(t.type,[w],[]),x]}e=nr(e,o.length);let a=mu(t,e,s),i=a.data,[l,c,u]=Xo((m,_,w,x)=>m+(_-i[x])**2,t,e,s);for(let m=0;mc+u,0);return new $(t.type,[l/n.length],[])}e=nr(e,s.length);let[o,a,i]=Xo((l,c)=>l+c,t,e,r);if(s[e]!==1)for(let l=0;l=0;--r)e[r]=s,s*=t[r];return e}function Em(t,e,r,s){let n=t.reduce((o,a)=>o*a,1);return new $(r,new s(n).fill(e),t)}function Ze(t,e){let r,s;if(typeof e=="number")r="float32",s=Float32Array;else if(typeof e=="bigint")r="int64",s=BigInt64Array;else if(typeof e=="boolean")r="bool",s=Uint8Array;else throw new Error(`Unsupported data type: ${typeof e}`);return Em(t,e,r,s)}function Ko(t,e){return Ze(t.dims,e)}function st(t){return Em(t,1n,"int64",BigInt64Array)}function Ln(t){return st(t.dims)}function Am(t){return Em(t,0n,"int64",BigInt64Array)}function Yo(t){return Am(t.dims)}function e6(t){let e=t.reduce((r,s)=>r*s,1);return new $("float32",Float32Array.from({length:e},()=>Os.random()),t)}function GS(t){let e=t.reduce((r,s)=>r*s,1);return new $("float32",Float32Array.from({length:e},()=>Os.gauss()),t)}function jS(t,e){if(t.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(t.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(e))throw new Error("The precision must be either 'binary' or 'ubinary'");let r=e==="binary",s=r?"int8":"uint8",n=r?Int8Array:Uint8Array,o=t.data,a=new n(o.length/8);for(let i=0;i0?1:0,c=Math.floor(i/8),u=i%8;a[c]|=l<<7-u,r&&u===0&&(a[c]-=128)}return new $(s,a,[t.dims[0],t.dims[1]/8])}async function zn(t){if(!t)throw new Error("modelId is required for get_tokenizer_files");return(await Pt(t,"tokenizer_config.json",{})).exists?["tokenizer.json","tokenizer_config.json"]:[]}async function Tm(t,e){let r=await zn(t);return await Promise.all(r.map(s=>lt(t,s,!0,e)))}function Qo(t){let e=t.dims;switch(e.length){case 1:return t.tolist();case 2:if(e[0]!==1)throw new Error("Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.");return t.tolist()[0];default:throw new Error(`Expected tensor to have 1-2 dimensions, got ${e.length}.`)}}var nR=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function oR(t,e,r,s){for(let n of Object.keys(t)){let o=e-t[n].length,a=r(n),i=new Array(o).fill(a);t[n]=s==="right"?yt(t[n],i):yt(i,t[n])}}function aR(t,e){for(let r of Object.keys(t))t[r].length=e}function Gs(t,...e){for(let r of e){if(!Object.hasOwn(t,r))continue;let s=t[r];if(s)if(typeof s=="object"){if(s.__type==="AddedToken")return s.content;throw Error(`Unknown token: ${s}`)}else return s}return null}function iR(t){let e=[];for(let r of t.get_added_tokens_decoder().values())r.special&&e.push(r);return e}var V=class extends We{return_token_type_ids=!1;padding_side="right";constructor(e,r){if(super(),this._tokenizerJSON=e,this._tokenizerConfig=r,this._tokenizer=new l2(e,r),this.config=r,this.padding_side=r.padding_side??this.padding_side,this.mask_token=Gs(r,"mask_token"),this.mask_token_id=this._tokenizer.token_to_id(this.mask_token),this.pad_token=Gs(r,"pad_token","eos_token"),this.pad_token_id=this._tokenizer.token_to_id(this.pad_token),this.sep_token=Gs(r,"sep_token"),this.sep_token_id=this._tokenizer.token_to_id(this.sep_token),this.unk_token=Gs(r,"unk_token"),this.unk_token_id=this._tokenizer.token_to_id(this.unk_token),this.bos_token=Gs(r,"bos_token"),this.bos_token_id=this._tokenizer.token_to_id(this.bos_token),this.eos_token=Gs(r,"eos_token"),this.eos_token_id=this._tokenizer.token_to_id(this.eos_token),this.chat_template=r.chat_template??null,Array.isArray(this.chat_template)){let n=Object.create(null);for(let{name:o,template:a}of this.chat_template){if(typeof o!="string"||typeof a!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');n[o]=a}this.chat_template=n}this._compiled_template_cache=new Map;let s=iR(this._tokenizer);this.all_special_ids=s.map(n=>n.id),this.all_special_tokens=s.map(n=>n.content)}static async from_pretrained(e,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main"}={}){let i=await Tm(e,{progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a});return new this(...i)}get_vocab(){return this._tokenizer.get_vocab()}get model_max_length(){return this._tokenizerConfig.model_max_length??1/0}get add_eos_token(){return this._tokenizerConfig.add_eos_token}get add_bos_token(){return this._tokenizerConfig.add_bos_token}convert_tokens_to_ids(e){return typeof e=="string"?this._tokenizer.token_to_id(e):e.map(r=>this._tokenizer.token_to_id(r))}_call(e,r={}){let{text_pair:s=null,add_special_tokens:n=!0,padding:o=!1,return_token_type_ids:a=null}=r,{truncation:i=null,max_length:l=null}=r,c=r.return_tensor??!0,u=Array.isArray(e),f;if(u){if(e.length===0)throw Error("text array must be non-empty");if(s!==null){if(Array.isArray(s)){if(e.length!==s.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");f=e.map((_,w)=>this._encode_plus(_,{text_pair:s[w],add_special_tokens:n,return_token_type_ids:a}))}else f=e.map(_=>this._encode_plus(_,{add_special_tokens:n,return_token_type_ids:a}))}else{if(e==null)throw Error("text may not be null or undefined");if(Array.isArray(s))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");f=[this._encode_plus(e,{text_pair:s,add_special_tokens:n,return_token_type_ids:a})]}if(l===null?l=this.model_max_length:i===null&&(o===!0?(te.warn("`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`."),l=this.model_max_length):o===!1&&(te.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation: true` to explicitly truncate examples to max length."),i=!0)),o===!0&&(l=Math.min(Le(f.map(_=>_.input_ids.length))[0],l??1/0)),l=Math.min(l,this.model_max_length??1/0),o||i)for(let _=0;_l?i&&aR(f[_],l):o&&oR(f[_],l,w=>w==="input_ids"?this.pad_token_id:0,this.padding_side));let m={};if(c){if(!(o&&i)&&f.some(w=>{for(let x of Object.keys(w))if(w[x].length!==f[0][x]?.length)return!0;return!1}))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");let _=[f.length,f[0].input_ids.length];for(let w of Object.keys(f[0]))m[w]=new $("int64",BigInt64Array.from(f.flatMap(x=>x[w]).map(BigInt)),_)}else{for(let _ of Object.keys(f[0]))m[_]=f.map(w=>w[_]);if(!u)for(let _ of Object.keys(m))m[_]=m[_][0]}return m}_encode_text(e){return e===null?null:this._tokenizer.encode(e).tokens}_encode_plus(e,{text_pair:r=null,add_special_tokens:s=!0,return_token_type_ids:n=null}={}){let{ids:o,attention_mask:a,token_type_ids:i}=this._tokenizer.encode(e,{text_pair:r,add_special_tokens:s,return_token_type_ids:n??this.return_token_type_ids});return{input_ids:o,attention_mask:a,...i?{token_type_ids:i}:{}}}tokenize(e,{pair:r=null,add_special_tokens:s=!1}={}){return this._tokenizer.tokenize(e,{text_pair:r,add_special_tokens:s})}encode(e,{text_pair:r=null,add_special_tokens:s=!0,return_token_type_ids:n=null}={}){return this._tokenizer.encode(e,{text_pair:r,add_special_tokens:s,return_token_type_ids:n}).ids}batch_decode(e,r={}){return e instanceof $&&(e=e.tolist()),e.map(s=>this.decode(s,r))}decode(e,r={}){if(e instanceof $&&(e=Qo(e)),!Array.isArray(e)||e.length===0||!IA(e[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(e,r)}decode_single(e,{skip_special_tokens:r=!1,clean_up_tokenization_spaces:s=null}){return this._tokenizer.decode(e,{skip_special_tokens:r,clean_up_tokenization_spaces:s})}get_chat_template({chat_template:e=null,tools:r=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){let s=this.chat_template;if(e!==null&&Object.hasOwn(s,e))e=s[e];else if(e===null)if(r!==null&&"tool_use"in s)e=s.tool_use;else if("default"in s)e=s.default;else throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(s).sort()}.`)}else if(e===null)if(this.chat_template)e=this.chat_template;else throw Error("Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating");return e}apply_chat_template(e,r={}){let{tools:s=null,documents:n=null,chat_template:o=null,add_generation_prompt:a=!1,tokenize:i=!0,padding:l=!1,truncation:c=!1,max_length:u=null,return_tensor:f=!0,return_dict:m=!0,tokenizer_kwargs:_={},...w}=r;if(o=this.get_chat_template({chat_template:o,tools:s}),typeof o!="string")throw Error(`chat_template must be a string, but got ${typeof o}`);let x=this._compiled_template_cache.get(o);x===void 0&&(x=new T2(o),this._compiled_template_cache.set(o,x));let b=Object.create(null);for(let k of nR){let M=Gs(this.config,k);M&&(b[k]=M)}let A=x.render({messages:e,add_generation_prompt:a,tools:s,documents:n,...b,...w});if(i){let k=this._call(A,{add_special_tokens:!1,padding:l,truncation:c,max_length:u,return_tensor:f,..._});return m?k:k.input_ids}return A}};function $n(t,e,r,s){if(!("language_codes"in t)||!Array.isArray(t.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in t)||!(t.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in t)||typeof t.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");let n=s.src_lang,o=s.tgt_lang;if(!t.language_codes.includes(o))throw new Error(`Target language code "${o}" is not valid. Must be one of: {${t.language_codes.join(", ")}}`);if(n!==void 0){if(!t.language_codes.includes(n))throw new Error(`Source language code "${n}" is not valid. Must be one of: {${t.language_codes.join(", ")}}`);let a=t._tokenizer.post_processor?.config;if(a&&"single"in a){for(let i of a.single)if("SpecialToken"in i&&t.languageRegex.test(i.SpecialToken.id)){i.SpecialToken.id=t.lang_to_token(n);break}}}return s.forced_bos_token_id=t._tokenizer.token_to_id(t.lang_to_token(o)),t._call(e,r)}var w_={};yn(w_,{AlbertTokenizer:()=>Sm,AutoTokenizer:()=>ne,BartTokenizer:()=>Mm,BertTokenizer:()=>Om,BlenderbotSmallTokenizer:()=>Im,BlenderbotTokenizer:()=>Cm,BloomTokenizer:()=>Pm,CLIPTokenizer:()=>Lm,CamembertTokenizer:()=>Nm,CodeGenTokenizer:()=>$m,CodeLlamaTokenizer:()=>zm,CohereAsrTokenizer:()=>Bm,CohereTokenizer:()=>Rm,ConvBertTokenizer:()=>Dm,DebertaTokenizer:()=>Fm,DebertaV2Tokenizer:()=>Um,DistilBertTokenizer:()=>Gm,ElectraTokenizer:()=>jm,EsmTokenizer:()=>qm,FalconTokenizer:()=>Wm,GPT2Tokenizer:()=>Xm,GPTNeoXTokenizer:()=>Hm,GemmaTokenizer:()=>Vm,HerbertTokenizer:()=>Km,LlamaTokenizer:()=>Ym,M2M100Tokenizer:()=>Qm,MBart50Tokenizer:()=>Zm,MBartTokenizer:()=>Jo,MPNetTokenizer:()=>r_,MarianTokenizer:()=>Jm,MgpstrTokenizer:()=>e_,MobileBertTokenizer:()=>t_,NllbTokenizer:()=>s_,NougatTokenizer:()=>n_,PreTrainedTokenizer:()=>V,Qwen2Tokenizer:()=>o_,RoFormerTokenizer:()=>i_,RobertaTokenizer:()=>a_,SiglipTokenizer:()=>l_,SpeechT5Tokenizer:()=>c_,SqueezeBertTokenizer:()=>u_,T5Tokenizer:()=>p_,TokenizersBackend:()=>V,VitsTokenizer:()=>d_,Wav2Vec2CTCTokenizer:()=>m_,WhisperTokenizer:()=>__,XLMRobertaTokenizer:()=>h_,XLMTokenizer:()=>g_});var Sm=class extends V{return_token_type_ids=!0};var Mm=class extends V{};var Om=class extends V{return_token_type_ids=!0};var Im=class extends V{};var Cm=class extends V{};var Pm=class extends V{};var Nm=class extends V{};var Lm=class extends V{};var zm=class extends V{};var $m=class extends V{};var Rm=class extends V{};var Bm=class extends V{};var Dm=class extends V{return_token_type_ids=!0};var Um=class extends V{return_token_type_ids=!0};var Fm=class extends V{return_token_type_ids=!0};var Gm=class extends V{};var jm=class extends V{return_token_type_ids=!0};var qm=class extends V{};var Wm=class extends V{};var Vm=class extends V{};var Hm=class extends V{};var Xm=class extends V{};var Km=class extends V{return_token_type_ids=!0};var Ym=class extends V{padding_side="left"};var Qm=class extends V{constructor(e,r){super(e,r),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)).map(s=>s.slice(2,-2)),this.lang_to_token=s=>`__${s}__`}_build_translation_inputs(e,r,s){return $n(this,e,r,s)}};var Jm=class extends V{constructor(e,r){super(e,r),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=Array.from(this.get_vocab().keys()).filter(s=>this.languageRegex.test(s)),te.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(e){if(e===null)return null;let[r,...s]=e.trim().split(this.languageRegex);if(s.length===0)return super._encode_text(r);if(s.length===2){let[n,o]=s;return this.supported_language_codes.includes(n)||te.warn(`Unsupported language code "${n}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),yt([n],super._encode_text(o))}}};var Jo=class extends V{constructor(e,r){super(e,r),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)).map(s=>s),this.lang_to_token=s=>s}_build_translation_inputs(e,r,s){return $n(this,e,r,s)}};var Zm=class extends Jo{};var e_=class extends V{};var t_=class extends V{return_token_type_ids=!0};var r_=class extends V{};var s_=class extends V{constructor(e,r){super(e,r),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)),this.lang_to_token=s=>s}_build_translation_inputs(e,r,s){return $n(this,e,r,s)}};var n_=class extends V{};var o_=class extends V{};var a_=class extends V{};var i_=class extends V{return_token_type_ids=!0};var l_=class extends V{};var c_=class extends V{};var u_=class extends V{return_token_type_ids=!0};var p_=class extends V{};var f_=class extends jt{decode_chain(e){let r="";for(let s=1;s[e,t]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function WS(t){t=t.toLowerCase();let e=lR.get(t);if(e===void 0){let r=t.match(/^<\|([a-z]{2})\|>$/);if(r&&(t=r[1]),Zo.has(t))e=t;else{let n=t.length===2?Zo.keys():Zo.values();throw new Error(`Language "${t}" is not supported. Must be one of: ${JSON.stringify(Array.from(n))}`)}}return e}var cR="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",VS=new RegExp(`^[${cR}]+$`,"gu"),uR=.1,__=class extends V{get timestamp_begin(){return this._tokenizer.token_to_id("<|notimestamps|>")+1}_decode_asr(e,{return_timestamps:r=!1,return_language:s=!1,time_precision:n=null,force_full_sequences:o=!0}={}){if(n===null)throw Error("Must specify time_precision");let a=null,i=r==="word";function l(){return{language:a,timestamp:[null,null],text:""}}let c=[],u=l(),f=0,m=this.timestamp_begin,w=m+1500,x=[],b=[],A=!1,k=null,M=new Set(this.all_special_ids);for(let C of e){let v=C.tokens,U=i?C.token_timestamps:null,j=null,F=m;if("stride"in C){let[Q,B,I]=C.stride;if(f-=B,k=Q-I,B&&(F=B/n+m),I)for(let oe=v.length-1;oe>=0;--oe){let J=Number(v[oe]);if(J>=m){if(j!==null&&(J-m)*n=m&&B<=w){let I=(B-m)*n+f,oe=Cs(I,2);if(j!==null&&B>=j)A=!0;else if(A||x.length>0&&B0&&u.timestamp[1]!==null))for(let L of u.words)L.timestamp[1]>u.timestamp[1]&&u.timestamp[1]>=L.timestamp[0]&&(L.timestamp[1]=u.timestamp[1]);c.push(u),x=[],K=[],b=[],Y=[],u=l()}}else if(K.push(B),i){let I=Cs(U[Q]+f,2),oe;if(Q+10?(x.push(K),i&&b.push(Y)):x.every(Q=>Q.length===0)&&(u=l(),x=[],K=[],b=[],Y=[])}if(x.length>0){if(o&&r)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");let[C,v]=this.findLongestCommonSequence(x,b),U=this.decode(C);u.text=U,i&&(u.words=this.collateWordTimestamps(C,v,a)),c.push(u)}let S=Object.create(null),O=c.map(C=>C.text).join("");if(r||s){for(let C=0;C0,i=a?[]:null,l=a?r[0]:null;for(let c=1;cB===F[I]&&l[O+I][0]-uR<=r[c][U+I][0]).length:K=v.filter((B,I)=>B===F[I]).length;let Y=S/1e4,Q=K/S+Y;K>1&&Q>f&&(f=Q,m=[O,C,U,j])}let[w,x,b,A]=m,k=Math.floor((x+w)/2),M=Math.floor((A+b)/2);if(a&&f===0&&n>0){let S=l[n-1][0],O=r[c].findIndex(C=>C[0]>=S);M=O===-1?u.length:O}o.push(...s.slice(0,k)),s=u.slice(M),n=s.length,a&&(i.push(...l.slice(0,k)),l=r[c].slice(M))}return o.push(...s),a?(i.push(...l),[o,i]):[o,[]]}collateWordTimestamps(e,r,s){let[n,o,a]=this.combineTokensIntoWords(e,s),i=[];for(let l=0;l=n){let i=((a-n)*s).toFixed(2);o.push(`<|${i}|>`),o.push([])}else o[o.length-1].push(a);return o=o.map(a=>typeof a=="string"?a:super.decode(a,r)),o.join("")}splitTokensOnUnicode(e){let r=this.decode(e,{decode_with_timestamps:!0}),s="\uFFFD",n=[],o=[],a=[],i=[],l=[],c=0;for(let u=0;u=this._tokenizer.token_to_id("<|endoftext|>"),_=c.startsWith(" "),w=c.trim(),x=VS.test(w);if(m||_||x||o.length===0)o.push(c),a.push(u),i.push(f);else{let b=o.length-1;o[b]+=c,a[b].push(...u),i[b].push(...f)}}return[o,a,i]}mergePunctuations(e,r,s,n,o){let a=structuredClone(e),i=structuredClone(r),l=structuredClone(s),c=a.length-2,u=a.length-1;for(;c>=0;)a[c].startsWith(" ")&&n.includes(a[c].trim())?(a[u]=a[c]+a[u],i[u]=yt(i[c],i[u]),l[u]=yt(l[c],l[u]),a[c]="",i[c]=[],l[c]=[]):u=c,--c;for(c=0,u=1;uf),i.filter(f=>f.length>0),l.filter(f=>f.length>0)]}};var h_=class extends V{};var g_=class extends V{return_token_type_ids=!0;constructor(e,r){super(e,r),te.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}};var ne=class{static async from_pretrained(e,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main"}={}){let[i,l]=await Tm(e,{progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a}),c=l.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer",u=w_[c];return u||(te.warn(`Unknown tokenizer class "${c}", attempting to construct from base class.`),u=V),new u(i,l)}};var es="https://github.com/huggingface/transformers.js/issues/new/choose",_u="preprocessor_config.json",Mr="preprocessor_config.json",hu="processor_config.json",gu="chat_template.jinja";var se=class extends We{static classes=["image_processor_class","tokenizer_class","feature_extractor_class"];static uses_processor_config=!1;static uses_chat_template_file=!1;constructor(e,r,s){super(),this.config=e,this.components=r,this.chat_template=s}get image_processor(){return this.components.image_processor}get tokenizer(){return this.components.tokenizer}get feature_extractor(){return this.components.feature_extractor}apply_chat_template(e,r={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(e,{tokenize:!1,chat_template:this.chat_template??void 0,...r})}batch_decode(...e){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(...e)}decode(...e){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.decode(...e)}async _call(e,...r){for(let s of[this.image_processor,this.feature_extractor,this.tokenizer])if(s)return s(e,...r);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(e,r={}){let[s,n,o]=await Promise.all([this.uses_processor_config?lt(e,hu,!0,r):{},Promise.all(this.classes.filter(a=>a in this).map(async a=>{let i=await this[a].from_pretrained(e,r);return[a.replace(/_class$/,""),i]})).then(Object.fromEntries),this.uses_chat_template_file?$o(e,gu,!0,r):null]);return new this(s,n,o)}};var ju={};yn(ju,{ChatterboxProcessor:()=>L_,CohereAsrProcessor:()=>z_,EmbeddingGemma2Processor:()=>R_,EmbeddingGemma2VideoProcessor:()=>ca,Florence2Processor:()=>Ih,Gemma3Processor:()=>Ch,Gemma3nProcessor:()=>Ph,Gemma4Processor:()=>la,Glm46VProcessor:()=>Nh,GraniteSpeechProcessor:()=>Lh,GroundingDinoProcessor:()=>zh,Idefics3Processor:()=>Du,JinaCLIPProcessor:()=>Rh,Lfm2VlProcessor:()=>Bh,Lfm3VlProcessor:()=>Dh,LlavaProcessor:()=>Uh,MgpstrProcessor:()=>Fh,MoonshineProcessor:()=>Gh,OwlViTProcessor:()=>jh,PaliGemmaProcessor:()=>qh,Phi3VProcessor:()=>Wh,PixtralProcessor:()=>Vh,Processor:()=>se,PyAnnoteProcessor:()=>Hh,Qwen2VLProcessor:()=>Vs,Qwen2_5_VLProcessor:()=>pa,Qwen3VLProcessor:()=>Xh,Sam2Processor:()=>Uu,Sam2VideoProcessor:()=>Kh,SamProcessor:()=>fa,SmolVLMProcessor:()=>Du,SpeechT5Processor:()=>Yh,UltravoxProcessor:()=>Qh,VLChatProcessor:()=>$h,VoxtralProcessor:()=>Jh,VoxtralRealtimeProcessor:()=>eg,Wav2Vec2Processor:()=>tg,Wav2Vec2ProcessorWithLM:()=>rg,WhisperProcessor:()=>sg});var Oe=class extends We{constructor(e){super(),this.config=e}static async from_pretrained(e,r={}){let s=await lt(e,_u,!0,r);return new this(s)}};function Ie(t,e){if(!(t instanceof Float32Array||t instanceof Float64Array))throw new Error(`${e} expects input to be a Float32Array or a Float64Array, but got ${t?.constructor?.name??typeof t} instead. If using the feature extractor directly, remember to use \`load_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}var ia={};yn(ia,{ASTFeatureExtractor:()=>b_,ChatterboxFeatureExtractor:()=>v_,ClapFeatureExtractor:()=>k_,CohereAsrFeatureExtractor:()=>E_,DacFeatureExtractor:()=>sa,EncodecFeatureExtractor:()=>ta,FeatureExtractor:()=>Oe,Gemma3nAudioFeatureExtractor:()=>na,Gemma4AudioFeatureExtractor:()=>oa,GraniteSpeechFeatureExtractor:()=>A_,MoonshineFeatureExtractor:()=>T_,ParakeetFeatureExtractor:()=>ra,PyAnnoteFeatureExtractor:()=>aa,SeamlessM4TFeatureExtractor:()=>S_,SnacFeatureExtractor:()=>M_,SpeechT5FeatureExtractor:()=>O_,VoxtralRealtimeFeatureExtractor:()=>P_,Wav2Vec2FeatureExtractor:()=>I_,WeSpeakerFeatureExtractor:()=>C_,WhisperFeatureExtractor:()=>N_});var pR=()=>{};var HS={fromWeb:pR};var fR=()=>{};var XS=fR;async function wu(t,e){if(le.IS_BROWSER_ENV){if(le.IS_WEBWORKER_ENV)throw new Error("Unable to save a file from a Web Worker.");let r=URL.createObjectURL(e),s=document.createElement("a");s.href=r,s.download=t,s.click(),s.remove(),URL.revokeObjectURL(r)}else if(le.IS_FS_AVAILABLE){let r=e.stream(),s=HS.fromWeb(r),n=xt.createWriteStream(t);await XS(s,n)}else throw new Error("Unable to save because filesystem is disabled in this environment.")}async function QS(t,e){if(typeof AudioContext>"u")throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");let r=await(await jr(t)).arrayBuffer(),s=new AudioContext({sampleRate:e});typeof e>"u"&&te.warn(`No sampling rate provided, using default of ${s.sampleRate}Hz.`);let n=await s.decodeAudioData(r),o;if(n.numberOfChannels===2){let a=Math.sqrt(2),i=n.getChannelData(0),l=n.getChannelData(1);o=new Float32Array(i.length);for(let c=0;c2595*Math.log10(1+t/700),kaldi:t=>1127*Math.log(1+t/700),slaney:(t,e=1e3,r=15,s=27/Math.log(6.4))=>t>=e?r+Math.log(t/e)*s:3*t/200};function x_(t,e="htk"){let r=mR[e];if(!r)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof t=="number"?r(t):t.map(s=>r(s))}var _R={htk:t=>700*(10**(t/2595)-1),kaldi:t=>700*(Math.exp(t/1127)-1),slaney:(t,e=1e3,r=15,s=Math.log(6.4)/27)=>t>=r?e*Math.exp(s*(t-r)):200*t/3};function hR(t,e="htk"){let r=_R[e];if(!r)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof t=="number"?r(t):t.map(s=>r(s))}function gR(t,e){let r=Float64Array.from({length:e.length-1},(a,i)=>e[i+1]-e[i]),s=Array.from({length:t.length},()=>new Array(e.length));for(let a=0;anew Array(t.length));for(let a=0;at+s*o)}function dt(t,e,r,s,n,o=null,a="htk",i=!1){if(o!==null&&o!=="slaney")throw new Error('norm must be one of null or "slaney"');if(t<2)throw new Error(`Require num_frequency_bins: ${t} >= 2`);if(r>s)throw new Error(`Require min_frequency: ${r} <= max_frequency: ${s}`);let l=x_(r,a),c=x_(s,a),u=YS(l,c,e+2),f=hR(u,a),m;if(i){let w=n/((t-1)*2);m=x_(Float64Array.from({length:t},(x,b)=>b*w),a),f=u}else m=YS(0,Math.floor(n/2),t);let _=gR(m,f);if(o!==null&&o==="slaney")for(let w=0;wn)throw Error(`frame_length (${r}) may not be larger than fft_length (${n})`);if(j!==r)throw new Error(`Length of the window (${j}) must equal frame_length (${r})`);if(s<=0)throw new Error("hop_length must be greater than zero");if(o===null&&f!==null)throw new Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(!u)throw new Error("`preemphasis_htk_flavor=false` is not currently supported.");if(a){let z=Math.floor(r/2);switch(i){case"reflect":{t=wR(t,z,z);break}case"constant":{let G=new t.constructor(t.length+2*z);G.set(t,z),t=G;break}case"semicausal":{let G=new t.constructor(t.length+z);G.set(t,z),t=G;break}default:throw new Error(`pad_mode="${i}" not implemented yet.`)}}let F=Math.floor(1+Math.floor((t.length-r)/s));M!==null&&FF?O&&(Q=S):Q=Y=S);let B=new Xc(n),I=new Float64Array(n),oe=new Float64Array(B.outputBufferSize),J=new Float32Array(K*Q);for(let z=0;z=1;--ie)I[ie]-=c*I[ie-1];I[0]*=1-c}for(let ie=0;ieMath.pow(c,.85));break;default:throw new Error(`Unknown window type ${e}.`)}if(r&&(a=a.subarray(0,t)),s===null||t===s)return a;if(t>s)throw new Error(`Length of the window (${t}) may not be larger than frame_length (${s})`);let i=new Float64Array(s),l=n?Math.floor((s-t)/2):0;return i.set(a,l),i}function bR(t,e){let r=t.reduce((o,a)=>o+a.length,0),s=new ArrayBuffer(44),n=new DataView(s);return xu(n,0,"RIFF"),n.setUint32(4,36+r*4,!0),xu(n,8,"WAVE"),xu(n,12,"fmt "),n.setUint32(16,16,!0),n.setUint16(20,3,!0),n.setUint16(22,1,!0),n.setUint32(24,e,!0),n.setUint32(28,e*4,!0),n.setUint16(32,4,!0),n.setUint16(34,32,!0),xu(n,36,"data"),n.setUint32(40,r*4,!0),new Blob([s,...t.map(o=>o.buffer instanceof ArrayBuffer?new Uint8Array(o.buffer,o.byteOffset,o.byteLength):o.slice())],{type:"audio/wav"})}function xu(t,e,r){for(let s=0;sn+o.length,0),r=new Float32Array(e),s=0;for(let n of this.audio)r.set(n,s),s+=n.length;return r}else return this.audio}toBlob(){let e=this.audio;return e instanceof Float32Array&&(e=[e]),bR(e,this.sampling_rate)}async save(e){return wu(e,this.toBlob())}};var b_=class extends Oe{constructor(e){super(e);let r=this.config.sampling_rate,s=dt(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=_t(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(e,r){return ct(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:r,transpose:!0})}async _call(e){Ie(e,"ASTFeatureExtractor");let r=await this._extract_fbank_features(e,this.config.max_length);if(this.config.do_normalize){let s=this.std*2,n=r.data;for(let o=0;o0)if(s==="rand_trunc"){a=!0;let l=Math.floor(Os.random()*(i+1));e=e.subarray(l,l+r),o=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${s}" not implemented`);else{if(i<0){let l=new Float64Array(r);if(l.set(e),n==="repeat")for(let c=e.length;c=1;--n)e[n]-=r*e[n-1];return await ct(e,this.window,this.window.length,this.config.hop_length,{fft_length:this.config.n_fft,power:2,mel_filters:this.config.mel_filters,log_mel:"log",mel_floor:-1/0,pad_mode:"constant",center:!0,transpose:!0,mel_offset:2**-24})}async _call(e){Ie(e,"ParakeetFeatureExtractor");let r=await this._extract_fbank_features(e),s=Math.floor((e.length+Math.floor(this.config.n_fft/2)*2-this.config.n_fft)/this.config.hop_length),n=r.data;n.fill(0,s*r.dims[1]);let[o,a]=r.dims,i=new Float64Array(a),l=new Float64Array(a);for(let f=0;f1?s-1:1;for(let f=0;f=u){l.push(e.slice(c,u));break}let f=Math.max(c,c+a-i),m=Math.min(c+a,u),_;m<=f?_=c+a:_=this._find_split_point_energy(e,f,m,n),_=Math.max(c+1,Math.min(_,u)),l.push(e.slice(c,_)),c=_}return l}_find_split_point_energy(e,r,s,n){let o=s-r;if(o<=n)return Math.floor((r+s)/2);let a=1/0,i=r,l=o-n;for(let c=0;c<=l;c+=n){let u=0;for(let f=0;fr&&(e=e.slice(0,r)),n&&e.length%o!==0){let l=o-e.length%o,c=new Float64Array(e.length+l);c.set(e),this.config.padding_value!==0&&c.fill(this.config.padding_value,e.length),e=c}let a=await this._extract_fbank_features(e,this.config.max_length),i=Ze([1,a.dims[0]],!0);return{input_features:a.unsqueeze_(0),input_features_mask:i}}};var oa=class extends na{async _extract_fbank_features(e,r){let{frame_length:s,hop_length:n,fft_length:o}=this.config,a=Math.floor(s/2),i=Math.floor((e.length+a-(s+1))/n)+1;return ct(e,this.window,s,n,{fft_length:o,center:!0,pad_mode:"semicausal",onesided:!0,preemphasis:this.config.preemphasis,preemphasis_htk_flavor:this.config.preemphasis_htk_flavor,mel_filters:this.mel_filters,log_mel:"log",mel_floor:this.config.mel_floor,mel_floor_mode:"add",remove_dc_offset:!1,transpose:!0,max_num_frames:i})}async _call(e,r={}){Ie(e,"Gemma4AudioFeatureExtractor");let s=e.length,n=await super._call(e,r),{input_features:o}=n,[,a,i]=o.dims,{frame_length:l,hop_length:c}=this.config,u=Math.floor(l/2),f=l+1,m=new Uint8Array(s+u+(r.pad_to_multiple_of??128));m.fill(1,u,u+s);let _=new Uint8Array(a);for(let x=0;x({id:l,start:c*s,end:u*s,confidence:f/(u-c)})))}return n}};var S_=class extends Oe{constructor(e){super(e);let r=this.config.sampling_rate,s=dt(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=_t(400,"povey",{periodic:!1})}async _extract_fbank_features(e,r){return e=e.map(s=>s*32768),ct(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:r,transpose:!0})}async _call(e,{padding:r=!0,pad_to_multiple_of:s=2,do_normalize_per_mel_bins:n=!0,return_attention_mask:o=!0}={}){Ie(e,"SeamlessM4TFeatureExtractor");let a=await this._extract_fbank_features(e,this.config.max_length);if(n){let[w,x]=a.dims,b=a.data;for(let A=0;A0){let k=new Float32Array(x*(w+A));k.set(b),k.fill(this.config.padding_value,b.length);let M=w+A;a=new $(a.type,k,[M,x]),o&&(i=new $("int64",new BigInt64Array(M),[1,M]),i.data.fill(1n,0,w))}}let[l,c]=a.dims,u=this.config.stride;if(l%u!==0)throw new Error(`The number of frames (${l}) must be a multiple of the stride (${u}).`);let m=a.view(1,Math.floor(l/u),c*u),_={input_features:m};if(o){let w=m.dims[1],x=new BigInt64Array(w);if(i){let b=i.data;for(let A=1,k=0;Ao+a,0)/e.length,n=e.reduce((o,a)=>o+(a-s)**2,0)/e.length;return e.map(o=>(o-s)/Math.sqrt(n+1e-7))}async _call(e){Ie(e,"Wav2Vec2FeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let r=e;this.config.do_normalize&&(r=this._zero_mean_unit_var_norm(r));let s=[1,r.length];return{input_values:new $("float32",r,s),attention_mask:new $("int64",new BigInt64Array(r.length).fill(1n),s)}}};var C_=class extends Oe{constructor(e){super(e);let r=this.config.sampling_rate,s=dt(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=_t(400,"hamming",{periodic:!1}),this.min_num_frames=this.config.min_num_frames}async _extract_fbank_features(e){return e=e.map(r=>r*32768),ct(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(e){Ie(e,"WeSpeakerFeatureExtractor");let r=(await this._extract_fbank_features(e)).unsqueeze_(0);if(this.config.fbank_centering_span===null){let s=r.mean(1).data,n=r.data,[o,a,i]=r.dims;for(let l=0;ln?(e.length>this.config.n_samples&&te.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),s=e.slice(0,n)):(s=new Float32Array(n),s.set(e)),{input_features:(await this._extract_fbank_features(s)).unsqueeze_(0)}}};var Ve=class{static async from_pretrained(e,r={}){let s=await lt(e,_u,!0,r),n=s.feature_extractor_type,o=ia[n];if(!o)throw new Error(`Unknown feature_extractor_type: '${n}'. Please report this at ${es}.`);return new o(s)}};var L_=class extends se{static tokenizer_class=ne;static feature_extractor_class=Ve;async _call(e,r=null){let s=this.tokenizer(e),n=r?await this.feature_extractor(r):{};return{...s,...n}}};var kR=new Set(["ja","zh"]),z_=class extends se{static tokenizer_class=ne;static feature_extractor_class=Ve;static uses_processor_config=!0;get_decoder_prompt_ids(e="en"){let r=["\u2581","<|startofcontext|>","<|startoftranscript|>","<|emo:undefined|>",`<|${e}|>`,`<|${e}|>`,"<|pnc|>","<|noitn|>","<|notimestamp|>","<|nodiarize|>"];return this.tokenizer.convert_tokens_to_ids(r)}static join_chunks(e,r="en"){let s=e.filter(a=>a&&a.trim());if(s.length===0)return"";let n=kR.has(r)?"":" ";return[s[0].trimEnd(),...s.slice(1).map(a=>a.trim())].join(n)}async _call(e){return await this.feature_extractor(e)}};var yu={};var js,eM,ts;if(le.IS_WEB_ENV)js=(t,e)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this environment.");return new self.OffscreenCanvas(t,e)},ts=self.createImageBitmap,eM=self.ImageData;else if(yu)ts=async t=>{let r=(await t.metadata()).channels,{data:s,info:n}=await t.rotate().raw().toBuffer({resolveWithObject:!0}),o=new rt(new Uint8ClampedArray(s),n.width,n.height,n.channels);return r!==void 0&&r!==n.channels&&o.convert(r),o};else throw new Error("Unable to load image processing library.");var ER={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},AR=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]),rt=class t{constructor(e,r,s,n){this.data=e,this.width=r,this.height=s,this.channels=n}get size(){return[this.width,this.height]}static async read(e){if(e instanceof t)return e;if(typeof e=="string"||e instanceof URL)return await this.fromURL(e);if(e instanceof Blob)return await this.fromBlob(e);if(typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas)return this.fromCanvas(e);throw new Error(`Unsupported input type: ${typeof e}`)}static fromCanvas(e){if(!le.IS_WEB_ENV)throw new Error("fromCanvas() is only supported in browser environments.");let s=e.getContext("2d").getImageData(0,0,e.width,e.height).data;return new t(s,e.width,e.height,4)}static async fromURL(e){let r=await jr(e);if(r.status!==200)throw new Error(`Unable to read image from "${e}" (${r.status} ${r.statusText})`);let s=await r.blob();return this.fromBlob(s)}static async fromBlob(e){if(le.IS_WEB_ENV){let r=await ts(e),s=js(r.width,r.height).getContext("2d");return s.drawImage(r,0,0),new this(s.getImageData(0,0,r.width,r.height).data,r.width,r.height,4)}else{let r=yu(await e.arrayBuffer());return await ts(r)}}static fromTensor(e,r="CHW"){if(e.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${e.dims.length} dimensions.`);if(r==="CHW")e=e.permute(1,2,0);else if(r!=="HWC")throw new Error(`Unsupported channel format: ${r}`);if(!(e.data instanceof Uint8ClampedArray||e.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${e.type}`);switch(e.dims[2]){case 1:case 2:case 3:case 4:return new t(e.data,e.dims[1],e.dims[0],e.dims[2]);default:throw new Error(`Unsupported number of channels: ${e.dims[2]}`)}}grayscale(){if(this.channels===1)return this;let e=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let r=0,s=0;r=0?l=s:u=-s,n>=0?c=n:f=-n,i.drawImage(a,l,c,e,r,u,f,e,r),new t(i.getImageData(0,0,e,r).data,e,r,4).convert(o)}else{let o=this.toSharp();if(s>=0&&n>=0)o=o.extract({left:Math.floor(s),top:Math.floor(n),width:e,height:r});else if(s<=0&&n<=0){let a=Math.floor(-n),i=Math.floor(-s);o=o.extend({top:a,left:i,right:e-this.width-i,bottom:r-this.height-a})}else{let a=[0,0],i=0;n<0?(a[0]=Math.floor(-n),a[1]=r-this.height-a[0]):i=Math.floor(n);let l=[0,0],c=0;s<0?(l[0]=Math.floor(-s),l[1]=e-this.width-l[0]):c=Math.floor(s),o=o.extend({top:a[0],bottom:a[1],left:l[0],right:l[1]}).extract({left:c,top:i,width:e,height:r})}return await ts(o)}}async toBlob(e="image/png",r=1){if(!le.IS_WEB_ENV)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:e,quality:r})}toTensor(e="CHW"){let r=new $("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(e!=="HWC")if(e==="CHW")r=r.permute(2,0,1);else throw new Error(`Unsupported channel format: ${e}`);return r}toCanvas(){if(!le.IS_WEB_ENV)throw new Error("toCanvas() is only supported in browser environments.");let e=this.clone().rgba(),r=js(e.width,e.height),s=new eM(e.data,e.width,e.height);return r.getContext("2d").putImageData(s,0,0),r}split(){let{data:e,width:r,height:s,channels:n}=this,o=e.constructor,a=e.length/n,i=Array.from({length:n},()=>new o(a));for(let l=0;lnew t(l,r,s,1))}_update(e,r,s,n=null){return this.data=e,this.width=r,this.height=s,n!==null&&(this.channels=n),this}clone(){return new t(this.data.slice(),this.width,this.height,this.channels)}convert(e){if(this.channels===e)return this;switch(e){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(e){if(le.IS_WEB_ENV){if(le.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");let r=e.split(".").pop().toLowerCase(),s=AR.get(r)??"image/png",n=await this.toBlob(s);return wu(e,n)}else if(le.IS_FS_AVAILABLE)await this.toSharp().toFile(e);else throw new Error("Unable to save the image because filesystem is disabled in this environment.")}toSharp(){if(le.IS_WEB_ENV)throw new Error("toSharp() is only supported in server-side environments.");return yu(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}},TR=rt.read.bind(rt);function SR(t,e,r,s,n){let o=s*r**2,a=Math.sqrt(o/(t*e)),i=n*r,l=Math.floor(a*t/i)*i,c=Math.floor(a*e/i)*i;if(l===0&&c===0)throw new Error(`Attempting to resize to a 0 x 0 image. Resized height should be divisible by \`pooling_kernel_size * patch_size\`=${i}.`);let u=Math.floor(s/n**2)*i;return l===0?(l=i,c=Math.min(Math.floor(e/t)*i,u)):c===0&&(c=i,l=Math.min(Math.floor(t/e)*i,u)),[l,c]}function MR(t,e,r,s,n,o,a){let i=Math.floor(e/n),l=Math.floor(r/n),c=i*l,u=n*n*s,f=new Float32Array(o*u),m=0;for(let x=0;xc.replaceAll(this.image_token,()=>` + +${this.boi_token}${this.image_token.repeat(i[l++])}${this.eoi_token} + +`))}let a;if(s){let i=Array.isArray(s)?s:[s];a=await this.feature_extractor(i[0],n);let l=this.feature_extractor.config.sampling_rate??16e3,c=0;e=e.map(u=>u.replaceAll(this.audio_token,()=>` + +${this.boa_token}${this.audio_token.repeat(this._compute_audio_num_tokens(i[c++].length,l))}${this.eoa_token} + +`))}return{...this.tokenizer(e,n),...o,...a}}};var ca=class extends We{constructor(e){super(),this.config=e,this.frame_processor=new qs(e),this.max_frames=e.max_frames??32,this.overflow_strategy=e.overflow_strategy??"uniform"}sample_frames(e){let r=e.length,{max_frames:s}=this;if(r<=s)return e;if(this.overflow_strategy==="truncate")return e.slice(0,s);let n=s>1?(r-1)/(s-1):0;return Array.from({length:s},(o,a)=>e[a>0&&a===s-1?r-1:Math.floor(a*n)])}async _call(e){Array.isArray(e)||(e=[e]);let r=e.map(i=>this.sample_frames(i.frames.map(l=>l.image))),{pixel_values:s,image_position_ids:n,num_soft_tokens_per_image:o}=await this.frame_processor(r.flat()),a=0;return{pixel_values_videos:s,video_position_ids:n,num_frames_per_video:r.map(i=>i.length),num_soft_tokens_per_video:r.map(i=>o[(a+=i.length)-1])}}};function $_(t,e){return Array.isArray(t)?t.every(r=>Array.isArray(r))?t:e?[t]:t.map(r=>[r]):[[t]]}function OR(t,e,r){let s=0;if(t=t.map(n=>n.replaceAll(e,()=>r[s++]??"")),s!==r.length)throw new Error(`Found ${s} ${e} tokens in the text, but ${r.length} inputs were passed.`);return t}var R_=class extends la{constructor(e,r,s){super(e,r,s),this.video_token=this.tokenizer.config.video_token,this.video_processor=e.video_processor&&new ca(e.video_processor)}async _call(e,r=null,s=null,n=null,o={}){let a=[[this.image_token,r&&$_(r,!0)],[this.video_token,n&&$_(n,!1)],[this.audio_token,s&&$_(s,!1)]];if(e==null){let O=a.filter(([,v])=>v),C=O[0]?.[1].length;if(O.some(([,v])=>v.length!==C))throw new Error("Received a different number of samples per modality.");e=Array.from({length:C},(v,U)=>O.flatMap(([j,F])=>Array(F[U].length).fill(j)).join(" "))}else typeof e=="string"&&(e=[e]);let[i,l,c]=a.map(([,O])=>O?.flat()),u=i&&await this.image_processor(i),f=l&&await this.video_processor(l),m=c&&await this._process_audio(c),{image_token:_,video_token:w,audio_token:x,boi_token:b,eoi_token:A,boa_token:k,eoa_token:M}=this,S={[_]:u?.num_soft_tokens_per_image.map(O=>b+_.repeat(O)+A),[w]:f?.num_soft_tokens_per_video.map((O,C)=>(b+w.repeat(O)+A).repeat(f.num_frames_per_video[C])),[x]:m?.num_soft_tokens_per_audio.map(O=>k+x.repeat(O)+M)};for(let[O,C]of Object.entries(S))e=OR(e,O,C??[]);return{...this.tokenizer(e,{padding:!0,...o}),...u,...f,...m}}async _process_audio(e){let r=[];for(let i of e)r.push(await this.feature_extractor(i));let s=Math.max(...r.map(i=>i.input_features.dims[1])),n=r[0].input_features.dims[2],o=new Float32Array(e.length*s*n),a=new Uint8Array(e.length*s);return r.forEach((i,l)=>{o.set(i.input_features.data,l*s*n),a.set(i.input_features_mask.data,l*s)}),{input_features:new $("float32",o,[e.length,s,n]),input_features_mask:new $("bool",a,[e.length,s]),num_soft_tokens_per_audio:r.map(({input_features_mask:{data:i}})=>{let l=0;for(let c=0;cs&&(o=Math.floor(n)*e),oe&&A.push(M)}else{let M=Le(b.data)[1];if(M===l-1||(k=Ue(b.data),k[M]O*f[(C+1)%2])),m.boxes.push(S),m.classes.push(M),m.scores.push(k[M])}}c.push(m)}return c}function bu(t,e=null){let r=t.logits,s=r.dims[0];if(e!==null&&e.length!==s)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let n=[];for(let o=0;of[A]&&(f[A]=b[A],m[A]=x)}let _=new Array(i.dims[0]);for(let x=0;xx!==void 0);n.push({segmentation:u,labels:w})}return n}function IR(t,e,r,s){let n=[],o=[],a=[];for(let i=0;ir&&(n.push(c),o.push(m),a.push(u))}return[n,o,a]}function CR(t,e,r,s=.5,n=.8){let o=[],a=0,i=0,l=e[r].data;for(let u=0;u=s&&++i;let c=a>0&&i>0;return c&&(c=a/i>n),[c,o]}function PR(t,e,r,s,n,o=null,a=null){let[i,l]=a??t[0].dims,c=new $("int32",new Int32Array(i*l),[i,l]),u=[];if(a!==null)for(let x=0;xm[k]&&(f[k]=x,m[k]=A[k])}let _=0,w=c.data;for(let x=0;x200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(t,e)/Math.min(t,e)}`);let a=Math.round(t/r)*r,i=Math.round(e/r)*r;if(o*a*i>n){let l=Math.sqrt(o*t*e/n);a=Math.max(r,Math.floor(t/l/r)*r),i=Math.max(r,Math.floor(e/l/r)*r)}else if(o*a*io?c=Math.floor(o*l/n):o>n&&(l=Math.floor(n*c/o)),await e.resize(c,l,{resample:s}))}async crop_margin(e,r=200){let s=e.clone().grayscale(),n=Ro(s.data)[0],a=Le(s.data)[0]-n;if(a===0)return e;let i=r/255,l=s.width,c=s.height,u=0,f=0,m=s.data;for(let _=0;_this.preprocess(o)));return{pixel_values:kt(s.map(o=>o.pixel_values),0),original_sizes:s.map(o=>o.original_size),reshaped_input_sizes:s.map(o=>o.reshaped_input_size)}}static async from_pretrained(e,r={}){let s=await lt(e,Mr,!0,r);return new this(s)}};var Gn={};yn(Gn,{BeitFeatureExtractor:()=>D_,BitImageProcessor:()=>U_,CHMv2ImageProcessor:()=>G_,CLIPFeatureExtractor:()=>j_,CLIPImageProcessor:()=>Eu,ChineseCLIPFeatureExtractor:()=>F_,ConvNextFeatureExtractor:()=>q_,ConvNextImageProcessor:()=>Au,DINOv3ViTImageProcessor:()=>H_,DPTFeatureExtractor:()=>K_,DPTImageProcessor:()=>Mu,DeiTFeatureExtractor:()=>W_,DeiTImageProcessor:()=>Tu,DetrFeatureExtractor:()=>V_,DetrImageProcessor:()=>Su,DonutFeatureExtractor:()=>X_,DonutImageProcessor:()=>Bn,EfficientNetImageProcessor:()=>Y_,GLPNFeatureExtractor:()=>Z_,Gemma3ImageProcessor:()=>Q_,Gemma4ImageProcessor:()=>qs,Glm46VImageProcessor:()=>J_,GroundingDinoImageProcessor:()=>eh,Idefics3ImageProcessor:()=>Ou,ImageFeatureExtractor:()=>X,ImageProcessor:()=>X,JinaCLIPImageProcessor:()=>rh,Lfm2VlImageProcessor:()=>sh,Lfm3VlImageProcessor:()=>nh,LlavaOnevisionImageProcessor:()=>oh,Mask2FormerImageProcessor:()=>ih,MaskFormerFeatureExtractor:()=>ah,MaskFormerImageProcessor:()=>Dn,MobileNetV1FeatureExtractor:()=>lh,MobileNetV1ImageProcessor:()=>Iu,MobileNetV2FeatureExtractor:()=>ch,MobileNetV2ImageProcessor:()=>Cu,MobileNetV3FeatureExtractor:()=>uh,MobileNetV3ImageProcessor:()=>Pu,MobileNetV4FeatureExtractor:()=>ph,MobileNetV4ImageProcessor:()=>Nu,MobileViTFeatureExtractor:()=>fh,MobileViTImageProcessor:()=>Lu,NougatImageProcessor:()=>dh,OwlViTFeatureExtractor:()=>mh,OwlViTImageProcessor:()=>Un,Owlv2ImageProcessor:()=>_h,Phi3VImageProcessor:()=>wh,PixtralImageProcessor:()=>xh,PvtImageProcessor:()=>yh,Qwen2VLImageProcessor:()=>Ws,RTDetrImageProcessor:()=>bh,Sam2ImageProcessor:()=>ua,Sam3ImageProcessor:()=>ua,SamImageProcessor:()=>ua,SapiensFeatureExtractor:()=>vh,SapiensImageProcessor:()=>zu,SegformerFeatureExtractor:()=>kh,SegformerImageProcessor:()=>$u,SiglipImageProcessor:()=>Eh,SmolVLMImageProcessor:()=>Ou,Swin2SRImageProcessor:()=>Ah,VLMImageProcessor:()=>th,ViTFeatureExtractor:()=>Th,ViTImageProcessor:()=>Ru,VitMatteImageProcessor:()=>Sh,VitPoseImageProcessor:()=>Mh,YolosFeatureExtractor:()=>Oh,YolosImageProcessor:()=>Bu});var D_=class extends X{};var U_=class extends X{};var F_=class extends X{};var G_=class extends X{};var Eu=class extends X{},j_=class extends Eu{};var Au=class extends X{constructor(e){super(e),this.crop_pct=this.config.crop_pct??224/256}async resize(e){let r=this.size?.shortest_edge;if(r===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(r<384){let s=Math.floor(r/this.crop_pct),[n,o]=this.get_resize_output_image_size(e,{shortest_edge:s});e=await e.resize(n,o,{resample:this.resample}),e=await e.center_crop(r,r)}else e=await e.resize(r,r,{resample:this.resample});return e}},q_=class extends Au{};var Tu=class extends X{},W_=class extends Tu{};var Su=class extends X{async _call(e){let r=await super._call(e),s=[r.pixel_values.dims[0],64,64],n=Ze(s,1n);return{...r,pixel_mask:n}}post_process_object_detection(...e){return rs(...e)}post_process_panoptic_segmentation(...e){return vu(...e)}post_process_instance_segmentation(...e){return ku(...e)}},V_=class extends Su{};var H_=class extends X{};var Bn=class extends X{pad_image(e,r,s,n={}){let[o,a,i]=r,l=this.image_mean;Array.isArray(this.image_mean)||(l=new Array(i).fill(l));let c=this.image_std;Array.isArray(c)||(c=new Array(i).fill(l));let u=l.map((f,m)=>-f/c[m]);return super.pad_image(e,r,s,{center:!0,constant_values:u,...n})}},X_=class extends Bn{};var Mu=class extends X{},K_=class extends Mu{};var Y_=class extends X{constructor(e){super(e),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(r=>r*r))}};var Q_=class extends X{};var Ws=class extends X{constructor(e){super(e),this.min_pixels=e.min_pixels??e.size?.shortest_edge,this.max_pixels=e.max_pixels??e.size?.longest_edge,this.patch_size=e.patch_size,this.merge_size=e.merge_size}get_resize_output_image_size(e,r){let s=this.patch_size*this.merge_size;return Rn(e.height,e.width,s,this.min_pixels,this.max_pixels)}async _call(e,...r){let{pixel_values:s,original_sizes:n,reshaped_input_sizes:o}=await super._call(e,...r),a=s,{temporal_patch_size:i,merge_size:l,patch_size:c}=this.config;a.dims[0]===1&&(a=Ee(Array.from({length:i},()=>a),0));let u=a.dims[0]/i,f=a.dims[1],m=Math.floor(a.dims[2]/c),_=Math.floor(a.dims[3]/c),w=a.view(u,i,f,Math.floor(m/l),l,c,Math.floor(_/l),l,c).permute(0,3,6,4,7,2,1,5,8).view(u*m*_,f*i*c*c),x=new $("int64",[u,m,_],[1,3]);return{pixel_values:w,image_grid_thw:x,original_sizes:n,reshaped_input_sizes:o}}};var J_=class extends Ws{get_resize_output_image_size(e,r){let s=this.patch_size*this.merge_size,n=this.config.temporal_patch_size??2;return Rn(e.height,e.width,s,this.min_pixels,this.max_pixels,n)}};var Z_=class extends X{};var eh=class extends X{async _call(e){let r=await super._call(e),s=r.pixel_values.dims,n=st([s[0],s[2],s[3]]);return{...r,pixel_mask:n}}};var Ou=class extends X{constructor(e){super(e),this.do_image_splitting=e.do_image_splitting??!0,this.max_image_size=e.max_image_size}get_resize_for_vision_encoder(e,r){let[s,n]=e.dims.slice(-2),o=n/s;return n>=s?(n=Math.ceil(n/r)*r,s=Math.floor(n/o),s=Math.ceil(s/r)*r):(s=Math.ceil(s/r)*r,n=Math.floor(s*o),n=Math.ceil(n/r)*r),{height:s,width:n}}async _call(e,{do_image_splitting:r=null,return_row_col_info:s=!1}={}){let n;if(!Array.isArray(e))n=[[e]];else{if(e.length===0||!e[0])throw new Error("No images provided.");Array.isArray(e[0])?n=e:n=[e]}let o=[],a=[],i=[],l=[],c=[];for(let A of n){let k=await Promise.all(A.map(O=>this.preprocess(O)));l.push(...k.map(O=>O.original_size)),c.push(...k.map(O=>O.reshaped_input_size)),k.forEach(O=>O.pixel_values.unsqueeze_(0));let{longest_edge:M}=this.max_image_size,S;if(r??this.do_image_splitting){let O=new Array(k.length),C=new Array(k.length);S=await Promise.all(k.map(async(v,U)=>{let j=this.get_resize_for_vision_encoder(v.pixel_values,M),F=await Tt(v.pixel_values,{size:[j.height,j.width]}),{frames:K,num_splits_h:Y,num_splits_w:Q}=await this.split_image(F,this.max_image_size);return O[U]=Y,C[U]=Q,Ee(K,0)})),a.push(O),i.push(C)}else{let O=[M,M];S=await Promise.all(k.map(C=>Tt(C.pixel_values,{size:O}))),a.push(new Array(k.length).fill(0)),i.push(new Array(k.length).fill(0))}o.push(Ee(S,0))}let u=o.length,[f,m,_,w]=o[0].dims,x,b;if(u===1)x=o[0].unsqueeze_(0),b=Ze([u,f,_,w],!0);else{let A=Math.max(...o.map(S=>S.dims.at(0)));b=Ze([u,A,_,w],!0);let k=b.data,M=A*_*w;for(let S=0;Ss||i>n){l=Math.ceil(a/s),c=Math.ceil(i/n);let u=Math.ceil(a/l),f=Math.ceil(i/c);for(let w=0;wr*this.rescale_factor)}pad_image(e,r,s,n){return super.pad_image(e,r,s,{constant_values:this.constant_values,center:!0,...n})}};var rh=class extends X{constructor(e){let{resize_mode:r,fill_color:s,interpolation:n,size:o,...a}=e,i=r==="squash"?{width:o,height:o}:r==="shortest"?{shortest_edge:o}:{longest_edge:o},l=n==="bicubic"?3:2;super({...a,size:i,resample:l,do_center_crop:!0,crop_size:o,do_normalize:!0})}};function sM(t,e){return Math.round(t/e)*e}function NR(t,e,r,s,n){let o=1/0,a=[1,1],i=r*s;for(let l of e){let c=Math.abs(t-l[0]/l[1]);c.5*n*n*l[0]*l[1]&&(a=l)}return a}function LR(t,e){let r=[],s=new Set;for(let n=t;n<=e;++n)for(let o=1;o<=n;++o)for(let a=1;a<=n;++a){let i=o*a;if(i>=t&&i<=e){let l=o<<16|a;s.has(l)||(s.add(l),r.push([o,a]))}}return r.sort((n,o)=>n[0]*n[1]-o[0]*o[1])}function zR(t,e){let[r,s,n,o]=t.dims,a=Math.floor(n/e),i=Math.floor(o/e),l=e*e*s,c=t.data,u=new Float32Array(r*a*i*l),f=n*o;for(let m=0;mthis.max_image_tokens*(this.encoder_patch_size*this.downsample_factor)**2*this.max_pixels_tolerance}_get_grid_layout(e,r){let s=LR(this.min_tiles,this.max_tiles),[n,o]=NR(r/e,s,r,e,this.tile_size);return{grid_width:n,grid_height:o,target_width:this.tile_size*n,target_height:this.tile_size*o}}async _call(e,{return_row_col_info:r=null}={}){let s;Array.isArray(e)?Array.isArray(e[0])?s=e:s=[e]:s=[[e]];let n=[],o=[],a=[],i=[],l=[],c=[];for(let f of s){let m=await Promise.all(f.map(_=>this.preprocess(_,{do_pad:!1})));for(let{pixel_values:_}of m){let[,w,x]=_.dims,b=_.unsqueeze_(0),A=this.encoder_patch_size*this.downsample_factor,k=A**2,[M,S]=Rn(Math.max(A,w),Math.max(A,x),A,this.min_image_tokens*k,this.max_image_tokens*k).map(F=>Math.max(A,F)),O,C=1,v=1,U=this._is_image_too_large(w,x),j=this.do_image_splitting&&!(this.min_tiles===1&&this.max_tiles===1);if(U&&j){let{grid_width:F,grid_height:K,target_width:Y,target_height:Q}=this._get_grid_layout(w,x);C=K,v=F;let B=await Tt(b,{size:[Q,Y]});O=[];for(let I=0;Isuper._call(n,...r)));return{pixel_values:Ee(s.map(n=>n.pixel_values),0),image_grid_thw:Ee(s.map(n=>n.image_grid_thw),0),original_sizes:s.flatMap(n=>n.original_sizes),reshaped_input_sizes:s.flatMap(n=>n.reshaped_input_sizes)}}};var oh=class extends X{};var Dn=class extends X{post_process_panoptic_segmentation(...e){return vu(...e)}post_process_instance_segmentation(...e){return ku(...e)}},ah=class extends Dn{};var ih=class extends Dn{};var Iu=class extends X{},lh=class extends Iu{};var Cu=class extends X{},ch=class extends Cu{};var Pu=class extends X{},uh=class extends Pu{};var Nu=class extends X{},ph=class extends Nu{};var Lu=class extends X{},fh=class extends Lu{};var dh=class extends Bn{};var Un=class extends X{post_process_object_detection(...e){return rs(...e)}},mh=class extends Un{};var _h=class extends Un{};var Bt=336,RR=[2,3],{ceil:hh,floor:Fn,sqrt:gh}=Math,wh=class extends X{constructor(e){super({...e,do_normalize:!0,do_pad:!0,pad_size:"custom",do_convert_rgb:!0,do_resize:!0}),this._num_crops=e.num_crops}calc_num_image_tokens_from_image_size(e,r){let{num_img_tokens:s}=this.config;return Fn((Fn(r/Bt)*Fn(e/Bt)+1)*s+1+(Fn(r/Bt)+1)*gh(s))}get_resize_output_image_size(e,r){let s=this._num_crops,[n,o]=e.size,a=n/o,i=1;for(;i*Math.ceil(i/a)<=s;)i+=1;i-=1;let l=Math.floor(i*336),c=Math.floor(l/a);return[l,c]}pad_image(e,r,s,n={}){let[o,a]=r,i=Bt*hh(o/Bt),l=Bt*hh(a/Bt),c=[1,1,1].map((u,f)=>(u-this.image_mean[f])/this.image_std[f]);return super.pad_image(e,r,{width:l,height:i},{center:!0,constant_values:c,...n})}async _call(e,{num_crops:r=null}={}){if(this._num_crops=r??=this.config.num_crops,r<4||gh(r)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(e)||(e=[e]);let s=e.length,n=await Promise.all(e.map(m=>this.preprocess(m))),o=n.map(m=>m.original_size),a=n.map(m=>m.reshaped_input_size),i=[];for(let{pixel_values:m}of n){m.unsqueeze_(0);let[_,w]=m.dims.slice(-2),x=await Tt(m,{size:[Bt,Bt],mode:"bicubic"});if(r>0){let b=[],A=gh(r),k=Fn(w/A),M=Fn(_/A);for(let O=0;Om.map(_=>Bt*hh(_/Bt))),u=new $("int64",c.flat(),[s,2]),f=c.map(([m,_])=>this.calc_num_image_tokens_from_image_size(_,m));return{pixel_values:l,original_sizes:o,reshaped_input_sizes:a,image_sizes:u,num_img_tokens:f}}};var xh=class extends X{get_resize_output_image_size(e,r){let{longest_edge:s}=r;if(s===void 0)throw new Error("size must contain 'longest_edge'");let[n,o]=e.size,a=Math.max(n,o)/s,i=n,l=o;a>1&&(i=Math.floor(n/a),l=Math.floor(o/a));let{patch_size:c,spatial_merge_size:u}=this.config;if(!u)throw new Error("config must contain 'spatial_merge_size'");let f=c*u,m=Math.floor((i-1)/f)+1,_=Math.floor((l-1)/f)+1;return[m*f,_*f]}};var yh=class extends X{};var bh=class extends X{post_process_object_detection(...e){return rs(...e)}};var ua=class extends X{reshape_input_points(e,r,s,n=!1){e=structuredClone(e);let o=dd(e);if(o.length===3)n||(o=[1,...o]),e=[e];else if(o.length!==4)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let a=0;an!==r.dims[o]))throw Error(`The first ${s.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new $("int64",e.flat(1/0).map(BigInt),s)}async _call(e,{input_points:r=null,input_labels:s=null,input_boxes:n=null}={}){let o=await super._call(e);if(r&&(o.input_points=this.reshape_input_points(r,o.original_sizes,o.reshaped_input_sizes)),s){if(!o.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");o.input_labels=this.add_input_labels(s,o.input_points)}return n&&(o.input_boxes=this.reshape_input_points(n,o.original_sizes,o.reshaped_input_sizes,!0)),o}async post_process_masks(e,r,s,{mask_threshold:n=0,binarize:o=!0,pad_size:a=null}={}){let i=[];a=a??this.pad_size??this.size;let l=[a.height,a.width];for(let c=0;cn&&(w[x]=1);m=new $("bool",w,m.dims)}i.push(m)}return i}generate_crop_boxes(e,r,{crop_n_layers:s=0,overlap_ratio:n=512/1500,points_per_crop:o=32,crop_n_points_downscale_factor:a=1}={}){}};var zu=class extends X{post_process_semantic_segmentation(...e){return bu(...e)}},vh=class extends zu{};var $u=class extends X{post_process_semantic_segmentation(...e){return bu(...e)}},kh=class extends $u{};var Eh=class extends X{};var Ah=class extends X{pad_image(e,r,s,n={}){let[o,a,i]=r;return super.pad_image(e,r,{width:a+(s-a%s)%s,height:o+(s-o%s)%s},{mode:"symmetric",center:!1,constant_values:-1,...n})}};var Ru=class extends X{},Th=class extends Ru{};var Sh=class extends X{async _call(e,r){Array.isArray(e)||(e=[e]),Array.isArray(r)||(r=[r]);let s=await Promise.all(e.map(a=>this.preprocess(a))),n=await Promise.all(r.map(a=>this.preprocess(a,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:kt(s.map((a,i)=>Ee([a.pixel_values,n[i].pixel_values],0)),0),original_sizes:s.map(a=>a.original_size),reshaped_input_sizes:s.map(a=>a.reshaped_input_size)}}};var Mh=class extends X{post_process_pose_estimation(e,r,{threshold:s=null}={}){let n=e.tolist(),[o,a,i,l]=e.dims,c=[];for(let u=0;u/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(e){typeof e=="string"&&(e=[e]);let r=[];for(let s of e)if(this.task_prompts_without_inputs.has(s))r.push(this.task_prompts_without_inputs.get(s));else{for(let[n,o]of this.task_prompts_with_input)if(s.includes(n)){r.push(o.replaceAll("{input}",s).replaceAll(n,""));break}r.length!==e.length&&r.push(s)}return r}post_process_generation(e,r,s){let n=this.tasks_answer_post_processing_type.get(r)??"pure_text";e=e.replaceAll("","").replaceAll("","");let o;switch(n){case"pure_text":o=e;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":let a=n==="ocr"?"quad_boxes":"bboxes",i=e.matchAll(this.regexes[a]),l=[],c=[];for(let[u,f,...m]of i)l.push(f?f.trim():l.at(-1)??""),c.push(m.map((_,w)=>(Number(_)+.5)/this.size_per_bin*s[w%2]));o={labels:l,[a]:c};break;default:throw new Error(`Task "${r}" (of type "${n}") not yet implemented.`)}return{[r]:o}}async _call(e,r=null,s={}){if(!e&&!r)throw new Error("Either text or images must be provided");let n=await this.image_processor(e,s),o=r?this.tokenizer(this.construct_prompts(r),s):{};return{...n,...o}}};var Ch=class extends se{static tokenizer_class=ne;static image_processor_class=Te;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,r,s){super(e,r,s),this.image_seq_length=this.config.image_seq_length;let{boi_token:n,image_token:o,eoi_token:a}=this.tokenizer.config;this.boi_token=n,this.image_token=o,this.eoi_token=a;let i=o.repeat(this.image_seq_length);this.full_image_sequence=` + +${n}${i}${a} + +`}async _call(e,r=null,s={}){typeof e=="string"&&(e=[e]);let n;return r&&(n=await this.image_processor(r,s),e=e.map(a=>a.replaceAll(this.boi_token,this.full_image_sequence))),{...this.tokenizer(e,s),...n}}};var Ph=class extends se{static image_processor_class=Te;static feature_extractor_class=Ve;static tokenizer_class=ne;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,r,s){super(e,r,s),this.audio_seq_length=this.config.audio_seq_length,this.image_seq_length=this.config.image_seq_length;let{audio_token_id:n,boa_token:o,audio_token:a,eoa_token:i,image_token_id:l,boi_token:c,image_token:u,eoi_token:f}=this.tokenizer.config;this.audio_token_id=n,this.boa_token=o,this.audio_token=a;let m=a.repeat(this.audio_seq_length);this.full_audio_sequence=` + +${o}${m}${i} + +`,this.image_token_id=l,this.boi_token=c,this.image_token=u;let _=u.repeat(this.image_seq_length);this.full_image_sequence=` + +${c}${_}${f} + +`}async _call(e,r=null,s=null,n={}){typeof e=="string"&&(e=[e]);let o;s&&(o=await this.feature_extractor(s,n),e=e.map(l=>l.replaceAll(this.audio_token,this.full_audio_sequence)));let a;return r&&(a=await this.image_processor(r,n),e=e.map(l=>l.replaceAll(this.image_token,this.full_image_sequence))),{...this.tokenizer(e,n),...a,...o}}};var Vs=class extends se{static image_processor_class=Te;static tokenizer_class=ne;static image_token="<|image_pad|>";async _call(e,r=null,...s){Array.isArray(e)||(e=[e]);let n,o;if(r&&(n=await this.image_processor(r),o=n.image_grid_thw),o){let i=this.image_processor.config.merge_size**2,l=0,c=this.constructor.image_token,u=o.tolist();e=e.map(f=>{for(;f.includes(c);){let m=Number(u[l++].reduce((_,w)=>_*w,1n));f=f.replace(c,"<|placeholder|>".repeat(Math.floor(m/i)))}return f.replaceAll("<|placeholder|>",c)})}return{...this.tokenizer(e),...n}}};var Nh=class extends Vs{static image_token="<|image|>"};var Lh=class extends se{static tokenizer_class=ne;static feature_extractor_class=Ve;static uses_processor_config=!0;_get_num_audio_features(e){let{hop_length:r}=this.feature_extractor.config.melspec_kwargs,{projector_window_size:s,projector_downsample_rate:n}=this.feature_extractor.config,o=Math.floor(s/n),a=Math.floor(e/r)+1,i=Math.floor(a/2);return Math.ceil(i/s)*o}async _call(e,r=null,s={}){if(Array.isArray(e))throw new Error("Batched inputs are not supported yet.");let n={};if(r){let{input_features:a}=await this.feature_extractor(r);n.input_features=a;let i=this._get_num_audio_features(r.length),l=new Uint8Array(i).fill(1);n.input_features_mask=new $("bool",l,[1,i]);let c=this.config.audio_token??"<|audio|>";if(!e.includes(c))throw new Error(`The input text does not contain the audio token ${c}.`);e=e.replaceAll(c,c.repeat(i))}return{...this.tokenizer(e,{add_special_tokens:!1,...s}),...n}}};function BR(t,e){let s=t.dims.at(-1)-1,n=t.tolist();n.fill(!1,0,1),n.fill(!1,s);let o=e.tolist();return n.map((a,i)=>a?i:null).filter(a=>a!==null).map(a=>o[a])}var zh=class extends se{static tokenizer_class=ne;static image_processor_class=Te;async _call(e,r,s={}){let n=e?await this.image_processor(e,s):{};return{...r?this.tokenizer(r,s):{},...n}}post_process_grounded_object_detection(e,r,{box_threshold:s=.25,text_threshold:n=.25,target_sizes:o=null}={}){let{logits:a,pred_boxes:i}=e,l=a.dims[0];if(o!==null&&o.length!==l)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let c=a.dims.at(1),u=a.sigmoid(),f=u.max(-1).tolist(),m=i.tolist().map(w=>w.map(x=>B_(x))),_=[];for(let w=0;wS.map((O,C)=>O*x[(C+1)%2])));let b=f[w],A=[],k=[],M=[];for(let S=0;S`+n.repeat(t);a+=` +`}return a+=` +${s}${o}`+n.repeat(t)+`${s}`,a}function UR(t,e,r,s){return`${e}${s}`+r.repeat(t)+`${e}`}function FR(t,e,r,s,n,o){return t===0&&e===0?UR(r,s,n,o):DR(r,t,e,s,n,o)}var Du=class extends se{static image_processor_class=Te;static tokenizer_class=ne;static uses_processor_config=!0;fake_image_token="";image_token="";global_img_token="";async _call(e,r=null,s={}){s.return_row_col_info??=!0;let n;r&&(n=await this.image_processor(r,s)),Array.isArray(e)||(e=[e]);let o=n.rows??[new Array(e.length).fill(0)],a=n.cols??[new Array(e.length).fill(0)],i=this.config.image_seq_len,l=[],c=[];for(let f=0;fFR(k,w[M],i,this.fake_image_token,this.image_token,this.global_img_token)),b=m.split(this.image_token);if(b.length===0)throw new Error("The image token should be present in the text.");let A=b[0];for(let k=0;kb.images).flatMap(b=>b.images).map(b=>rt.read(b)));let n=this.tokenizer,o=n.apply_chat_template(e,{tokenize:!1,add_generation_prompt:!0,chat_template:s}),a=b=>n.encode(b,{add_special_tokens:!1}),i=o.split(this.image_tag),l=i.length-1;if(r.length!==l)throw new Error(`Number of images provided (${r.length}) does not match number of "${this.image_tag}" image tags (${l})`);let[c,u,f]=n.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]),m=a(i[0]),_=new Array(m.length).fill(!1);for(let b=1;b0){let b=await this.image_processor(r);return b.pixel_values.unsqueeze_(0),{...x,...b}}return x}};var Rh=class extends se{static tokenizer_class=ne;static image_processor_class=Te;async _call(e=null,r=null,s={}){if(!e&&!r)throw new Error("Either text or images must be provided");let n=e?this.tokenizer(e,s):{},o=r?await this.image_processor(r,s):{};return{...n,...o}}};var Bh=class extends se{static tokenizer_class=ne;static image_processor_class=Te;async _call(e,r=null,s={}){let{image_rows:n,image_cols:o,image_sizes:a,...i}=await this.image_processor(e,{...s,return_row_col_info:!0});if(r){let l=this.config.image_token??"",{tile_size:c=512,downsample_factor:u=2,encoder_patch_size:f=16,use_thumbnail:m=!0}=this.image_processor.config,_=M=>Math.ceil(Math.floor(M/f)/u),w=_(c)**2,x=this.config.image_start_token??"<|image_start|>",b=this.config.image_end_token??"<|image_end|>",A=this.config.image_thumbnail??"<|img_thumbnail|>";Array.isArray(r)||(r=[r]);let k=0;r=r.map(M=>{let S=M.split(l);return S[0]+S.slice(1).map(O=>{let C=k++,[v,U]=a[C],j=n[C],F=o[C],K=_(v)*_(U),Y=x;if(j>1||F>1){let Q=l.repeat(w);for(let B=0;B`+Q;m&&(Y+=A+l.repeat(K))}else Y+=l.repeat(K);return Y+b+O}).join("")})}return{...i,...r?this.tokenizer(r,s):{}}}};var Dh=class extends se{static tokenizer_class=ne;static image_processor_class=Te;async _call(e,r=null,s={}){let n=e?await this.image_processor(e,s):{};if(r!==null){Array.isArray(r)||(r=[r]);let o=this.tokenizer.config.image_token??"<|image|>",a=n.image_grid_thw?.tolist()??[],i=r.reduce((u,f)=>u+f.split(o).length-1,0);if(i!==a.length)throw new Error(`Found ${i} ${o} tokens in the text but received ${a.length} images.`);let l=this.image_processor.config.merge_size,c=0;r=r.map(u=>u.replaceAll(o,()=>{let f=Number(a[c++].reduce((m,_)=>m*_,1n));return o.repeat(f/l**2)}))}return{...n,...r!==null?this.tokenizer(r,s):{}}}};var Uh=class extends se{static tokenizer_class=ne;static image_processor_class=Te;static uses_processor_config=!0;async _call(e,r=null,s={}){let n=await this.image_processor(e,s);if(r){let[a,i]=n.pixel_values.dims.slice(-2),{image_token:l,patch_size:c,num_additional_image_tokens:u}=this.config,f=Math.floor(a/c)*Math.floor(i/c)+u;r=structuredClone(r),Array.isArray(r)||(r=[r]);for(let m=0;m0?x.reduce((A,k)=>A*k,1):0;c.push(w),l.push(b)}return[o(c),l]}char_decode(e){return this.char_tokenizer.batch_decode(e).map(r=>r.replaceAll(" ",""))}bpe_decode(e){return this.bpe_tokenizer.batch_decode(e)}wp_decode(e){return this.wp_tokenizer.batch_decode(e).map(r=>r.replaceAll(" ",""))}batch_decode([e,r,s]){let[n,o]=this._decode_helper(e,"char"),[a,i]=this._decode_helper(r,"bpe"),[l,c]=this._decode_helper(s,"wp"),u=[],f=[];for(let m=0;mc.includes(jn))?a=r.map(c=>{let u=c.replaceAll(jn,jn.repeat(o)),f=u.lastIndexOf(jn),m=f===-1?0:f+jn.length;return u.slice(0,m)+n+u.slice(m)+` +`}):(te.warn("You are passing both `text` and `images` to `PaliGemmaProcessor`. The processor expects special image tokens in the text, as many tokens as there are images per each text. It is recommended to add `` tokens in the very beginning of your text. For this call, we will infer how many images each text has and add special tokens."),a=r.map(c=>GR(c,n,o,jn,e.length)));let i=this.tokenizer(a,s);return{...await this.image_processor(e,s),...i}}};var oM="<|image|>",jR=/<\|image_\d+\|>/g,Wh=class extends se{static image_processor_class=Te;static tokenizer_class=ne;async _call(e,r=null,{padding:s=!0,truncation:n=!0,num_crops:o=null}={}){Array.isArray(e)||(e=[e]);let a,i;if(r){i=await this.image_processor(r,{num_crops:o});let{num_img_tokens:l}=i,c=e.map((f,m)=>f.split(jR).join(oM.repeat(l[m])));a=this.tokenizer(c,{padding:s,truncation:n});let u=this.tokenizer._tokenizer.token_to_id(oM);a.input_ids.map_(f=>f==u?-f:f)}else a=this.tokenizer(e);return{...a,...i}}};var Vh=class extends se{static tokenizer_class=ne;static image_processor_class=Te;static uses_processor_config=!0;async _call(e,r=null,s={}){let n=await this.image_processor(e,s);if(r){let[a,i]=n.pixel_values.dims.slice(-2),{image_token:l,image_break_token:c,image_end_token:u,patch_size:f,spatial_merge_size:m}=this.config,_=f*m,w=Math.floor(a/_),x=Math.floor(i/_);r=structuredClone(r),Array.isArray(r)||(r=[r]);for(let b=0;bVR(w,l)),u=c.map(w=>w.length),f=c.flat(),m=(await Promise.all(f.map(w=>this.feature_extractor(w,s)))).map(w=>w.input_features);n.audio_values=m.length>1?Ee(m,0):m[0];let _=a[0];for(let w=0;w0){if(c>jc)throw new Error(`The number of external data chunks (${c}) exceeds the maximum allowed value (${jc}).`);let u=og(a,c);for(let f of u){let m=`${s.subfolder??""}/${f}`;l.push(zo(t,m,!0,s,i).then(_=>_ instanceof Uint8Array?{path:f,data:_}:f))}}else o.externalData!==void 0&&(l=o.externalData.map(async u=>{if(typeof u.data=="string"){let f=await zo(t,u.data,!0,s);return{...u,data:f}}return u}));return Promise.all(l)}async function QR(t,e,r,s=!1,n=void 0){let o=r.config?.["transformers.js_config"]??{},a=uu(r.device??o.device,e,{warn:k=>te.info(k)}),i=NS(a),l=o.device_config??{};l.hasOwnProperty(a)&&(o={...o,...l[a]});let c=pu(r.dtype??o.dtype,e,a,{configDtype:o.dtype,warn:k=>te.info(k)});if(Jr.hasOwnProperty(c)){if(a==="webgpu"&&!le.IS_NODE_ENV&&c===it.fp16&&!await RS())throw new Error(`The device (${a}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${c}. Should be one of: ${Object.keys(it).join(", ")}`);let u=Jr[c],f={...r.session_options};f.executionProviders??=i;let m=o.free_dimension_overrides;m?f.freeDimensionOverrides??=m:a.startsWith("webnn")&&!f.freeDimensionOverrides&&te.warn(`WebNN does not currently support dynamic shapes and requires 'free_dimension_overrides' to be set in config.json, preferably as a field within config["transformers.js_config"]["device_config"]["${a}"]. When 'free_dimension_overrides' is not set, you may experience significant performance degradation.`);let _=iM(t,e,r,u),w=r.use_external_data_format??o.use_external_data_format,x=await lM(t,e,u,r,w,f);if(x.length>0&&(!le.IS_NODE_ENV||x.some(k=>typeof k!="string"))&&(f.externalData=x),s&&a==="webgpu"){let k=Hs(r.config,{prefix:"present",session_name:n});if(k.size>0&&!Ho()){let M={};for(let S of k)M[S]="gpu-buffer";f.preferredOutputLocation=M}}return{buffer_or_path:await _,session_options:f,session_config:{dtype:c,device:a}}}async function cM(t,e,r,s=void 0){return Object.fromEntries(await Promise.all(Object.keys(e).map(async n=>{let o=s?.[n]??!1,{buffer_or_path:a,session_options:i,session_config:l}=await QR(t,e[n],r,o,n),c=await iu(a,i,l);return[n,c]})))}function uM(t){for(let e in t)cu(t[e])?t[e]=new $(t[e]):typeof t[e]=="object"&&uM(t[e]);return t}async function pe(t,e){let r=JR(t,e);try{let s=Object.fromEntries(Object.entries(r).map(([o,a])=>{let i=a.ort_tensor;return le.IS_NODE_ENV&&typeof Float16Array<"u"&&i.cpuData instanceof Float16Array&&(i.cpuData=new Uint16Array(i.cpuData.buffer)),[o,i]})),n=await lu(t,s);return uM(n)}catch(s){let n=Object.fromEntries(Object.entries(r).map(([o,a])=>{let i={type:a.type,dims:a.dims,location:a.location};return i.location!=="gpu-buffer"&&(i.data=a.data),[o,i]}));throw te.error(`An error occurred during model execution: "${s}".`),te.error("Inputs given to model:",n),s}}function JR(t,e){let r=Object.create(null),s=[];for(let a of t.inputNames){let i=e[a];if(!(i instanceof $)){s.push(a);continue}r[a]=Ho()?i.clone():i}if(s.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${s.join(", ")}.`);let n=Object.keys(e).length,o=t.inputNames.length;if(n>o){let a=Object.keys(e).filter(i=>!t.inputNames.includes(i));te.warn(`WARNING: Too many inputs were provided (${n} > ${o}). The following inputs will be ignored: "${a.join(", ")}".`)}return r}var Se=class{},Wu=class extends Se{constructor({last_hidden_state:e,hidden_states:r=null,attentions:s=null}){super(),this.last_hidden_state=e,this.hidden_states=r,this.attentions=s}},q=class extends Se{constructor({logits:e,...r}){super(),this.logits=e;let s=Object.values(r);s.length>0&&(this.attentions=s)}},we=class extends Se{constructor({logits:e}){super(),this.logits=e}},ye=class extends Se{constructor({logits:e}){super(),this.logits=e}},Me=class extends Se{constructor({start_logits:e,end_logits:r}){super(),this.start_logits=e,this.end_logits=r}},ht=class extends Se{constructor({logits:e}){super(),this.logits=e}},Vu=class extends Se{constructor({logits:e,past_key_values:r}){super(),this.logits=e,this.past_key_values=r}},Hu=class extends Se{constructor({logits:e,past_key_values:r,encoder_outputs:s,decoder_attentions:n=null,cross_attentions:o=null}){super(),this.logits=e,this.past_key_values=r,this.encoder_outputs=s,this.decoder_attentions=n,this.cross_attentions=o}},Vn=class extends Se{constructor({alphas:e}){super(),this.alphas=e}};var Dt=class extends We{_call(e,r){throw Error("`_call` should be implemented in a subclass")}},da=class extends We{_call(e,r){throw Error("`_call` should be implemented in a subclass")}},Xs=class extends We{constructor(){super(),this.processors=[]}push(e){this.processors.push(e)}extend(e){this.processors.push(...e)}_call(e,r){let s=r;for(let n of this.processors)s=n(e,s);return s}[Symbol.iterator](){return this.processors.values()}},Xu=class extends Dt{constructor(e){super(),this.bos_token_id=e}_call(e,r){for(let s=0;s=1&&o[o.length-1]>=this.timestamp_begin,i=o.length<2||o[o.length-2]>=this.timestamp_begin;if(a&&(i?n.subarray(this.timestamp_begin).fill(-1/0):n.subarray(0,this.eos_token_id).fill(-1/0)),e[s].length===this.begin_index&&this.max_initial_timestamp_index!==null){let f=this.timestamp_begin+this.max_initial_timestamp_index;n.subarray(f+1).fill(-1/0)}let l=Sd(n),c=Math.log(l.subarray(this.timestamp_begin).map(Math.exp).reduce((f,m)=>f+m)),u=Le(l.subarray(0,this.timestamp_begin))[0];c>u&&n.subarray(0,this.timestamp_begin).fill(-1/0)}return r}},Ju=class extends Dt{constructor(e){super(),this.no_repeat_ngram_size=e}getNgrams(e){let r=e.length,s=[];for(let o=0;o1 to use the classifier-free guidance processor, got guidance scale ${e}.`);this.guidance_scale=e}_call(e,r){if(r.dims[0]!==2*e.length)throw new Error(`Logits should have twice the batch size of the input ids, the first half of batches corresponding to the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got batch size ${r.dims[0]} for the logits and ${e.length} for the input ids.`);let s=e.length,n=r.slice([0,s],null),o=r.slice([s,r.dims[0]],null);for(let a=0;a1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${e}`);if(!Number.isInteger(s)||s<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${s}`);this.top_p=e,this.filter_value=r,this.min_tokens_to_keep=s}},fM=class extends da{constructor(e,{filter_value:r=-1/0,min_tokens_to_keep:s=1}={}){if(super(),!Number.isInteger(e)||e<0)throw new Error(`\`top_k\` must be a positive integer, but is ${e}`);this.top_k=Math.max(e,s),this.filter_value=r}};var Ks=class{max_length=20;max_new_tokens=null;min_length=0;min_new_tokens=null;early_stopping=!1;max_time=null;do_sample=!1;num_beams=1;num_beam_groups=1;penalty_alpha=null;use_cache=!0;temperature=1;top_k=50;top_p=1;typical_p=1;epsilon_cutoff=0;eta_cutoff=0;diversity_penalty=0;repetition_penalty=1;encoder_repetition_penalty=1;length_penalty=1;no_repeat_ngram_size=0;bad_words_ids=null;force_words_ids=null;renormalize_logits=!1;constraints=null;forced_bos_token_id=null;forced_eos_token_id=null;remove_invalid_values=!1;exponential_decay_length_penalty=null;suppress_tokens=null;streamer=null;begin_suppress_tokens=null;forced_decoder_ids=null;guidance_scale=null;num_return_sequences=1;output_attentions=!1;output_hidden_states=!1;output_scores=!1;return_dict_in_generate=!1;pad_token_id=null;bos_token_id=null;eos_token_id=null;encoder_no_repeat_ngram_size=0;decoder_start_token_id=null;generation_kwargs={};constructor(e){Object.assign(this,He(e,Object.getOwnPropertyNames(this)))}};var ss=class extends We{_call(e,r){throw Error("StoppingCriteria needs to be subclassed")}},Xn=class t extends We{constructor(){super(),this.criteria=[]}push(e){this.criteria.push(e)}extend(e){e instanceof t?e=e.criteria:e instanceof ss&&(e=[e]),this.criteria.push(...e)}_call(e,r){let s=new Array(e.length).fill(!1);for(let n of this.criteria){let o=n(e,r);for(let a=0;ar.length>=this.max_length)}},ap=class extends ss{constructor(e){super(),Array.isArray(e)||(e=[e]),this.eos_token_id=e}_call(e,r){return e.map(s=>{let n=s.at(-1);return this.eos_token_id.some(o=>n==o)})}},dM=class extends ss{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(e,r){return new Array(e.length).fill(this.interrupted)}};var Ys=class extends We{constructor(e){super(),this.generation_config=e}async _call(e){return this.sample(e)}async sample(e){throw Error("sample should be implemented in subclasses.")}getLogits(e,r){let s=e.dims.at(-1),n=e.data;if(r===-1)n=n.slice(-s);else{let o=r*s;n=n.slice(o,o+s)}return n}randomSelect(e){return M2(e)}static getSampler(e){if(e.do_sample)return new ig(e);if(e.num_beams>1)return new lg(e);if(e.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${e.num_return_sequences}.`);return new ag(e)}},ag=class extends Ys{async sample(e){let r=Le(e.data)[1];return[[BigInt(r),0]]}},ig=class extends Ys{async sample(e){let r=e.dims.at(-1);this.generation_config.top_k>0&&(r=Math.min(this.generation_config.top_k,r));let[s,n]=await or(e,r),o=Ue(s.data);return Array.from({length:this.generation_config.num_beams},()=>{let a=this.randomSelect(o);return[n.data[a],Math.log(o[a])]})}},lg=class extends Ys{async sample(e){let r=e.dims.at(-1);this.generation_config.top_k>0&&(r=Math.min(this.generation_config.top_k,r));let[s,n]=await or(e,r),o=Ue(s.data);return Array.from({length:this.generation_config.num_beams},(a,i)=>[n.data[i],Math.log(o[i])])}};var cg=class{constructor(e){if(e)for(let r in e){if(r in this)throw new TypeError(`Key "${r}" conflicts with an existing property on DynamicCache`);let s=e[r];if(!(s instanceof $))throw new TypeError(`Expected a Tensor for key "${r}", got ${typeof s}`);this[r]=s}}get_seq_length(){let e=this;if(Object.keys(e).length===0)return 0;for(let r in e)if(r.startsWith("past_key_values."))return e[r].dims.at(-2);throw new Error("Unable to determine sequence length from the cache.")}update(e){for(let r in e){let s=this[r],n=e[r];s&&s!==n&&s.location==="gpu-buffer"&&s.dispose(),this[r]=n}}async dispose(){let e=[];for(let r of Object.values(this))r.location==="gpu-buffer"&&e.push(r.dispose());await Promise.all(e)}},Kn=cg;var W={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,DecoderOnlyWithoutHead:5,MaskGeneration:6,ImageTextToText:7,Musicgen:8,MultiModality:9,Phi3V:10,AudioTextToText:11,AutoEncoder:12,ImageAudioTextToText:13,Supertonic:14,Chatterbox:15,VoxtralRealtime:16,MultimodalEncoder:17},gr={[W.DecoderOnly]:{sessions:(t,e)=>({model:e.model_file_name??"model"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[W.DecoderOnlyWithoutHead]:{sessions:(t,e)=>({model:e.model_file_name??"model"})},[W.Seq2Seq]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[W.Vision2Seq]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[W.Musicgen]:{sessions:()=>({model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[W.EncoderDecoder]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0}},[W.MaskGeneration]:{sessions:()=>({model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"})},[W.ImageTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(t,e,r)=>{let s={...gr[W.ImageTextToText].text_only_sessions};return r||(s.vision_encoder="vision_encoder"),t.is_encoder_decoder&&(s.model="encoder_model"),s},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[W.AudioTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(t,e,r)=>{let s={...gr[W.AudioTextToText].text_only_sessions};return r||(s.audio_encoder="audio_encoder"),s},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[W.ImageAudioTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(t,e,r)=>{let s={...gr[W.ImageAudioTextToText].text_only_sessions};return r||(s.audio_encoder="audio_encoder",s.vision_encoder="vision_encoder"),s},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[W.Phi3V]:{sessions:()=>({prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[W.MultiModality]:{sessions:()=>({prepare_inputs_embeds:"prepare_inputs_embeds",model:"language_model",lm_head:"lm_head",gen_head:"gen_head",gen_img_embeds:"gen_img_embeds",image_decode:"image_decode"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[W.AutoEncoder]:{sessions:()=>({encoder_model:"encoder_model",decoder_model:"decoder_model"})},[W.Supertonic]:{sessions:()=>({text_encoder:"text_encoder",latent_denoiser:"latent_denoiser",voice_decoder:"voice_decoder"})},[W.Chatterbox]:{sessions:()=>({embed_tokens:"embed_tokens",speech_encoder:"speech_encoder",model:"language_model",conditional_decoder:"conditional_decoder"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[W.VoxtralRealtime]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(t,e,r)=>{let s={...gr[W.VoxtralRealtime].text_only_sessions};return r||(s.audio_encoder="audio_encoder"),s},cache_sessions:{decoder_model_merged:!0,audio_encoder:!0},optional_configs:{generation_config:"generation_config.json"}},[W.MultimodalEncoder]:{sessions:(t,e)=>({model:e.model_file_name??"model",...t.vision_config&&{vision_encoder:"vision_encoder"},...t.audio_config&&{audio_encoder:"audio_encoder"}})},default:{sessions:(t,e)=>({model:e.model_file_name??"model"})}};function mM(t){return gr[t]?.text_only_sessions??null}function ip(t,e,r={}){let s=gr[t]??gr.default;return{sessions:s.sessions(e,r,r.textOnly??!1),cache_sessions:s.cache_sessions,optional_configs:s.optional_configs}}function Yn(t,{warn:e=!0}={}){let r=t.architectures||[];for(let s of r){let n=ar.get(s);if(n!==void 0)return n}if(t.model_type){let s=ar.get(t.model_type);if(s!==void 0)return s;for(let n of Object.values(Qs))if(n.has(t.model_type)){let o=ar.get(n.get(t.model_type));if(o!==void 0)return o}}if(e){let s=r.length>0?r.join(", "):"(none)";te.warn(`[resolve_model_type] Architecture(s) not found in MODEL_TYPE_MAPPING: [${s}] for model type '${t.model_type}'. Falling back to EncoderOnly (single model.onnx file). If you encounter issues, please report at: ${es}`)}return W.EncoderOnly}function ma(t,{config:e=null,cache_dir:r=null,local_files_only:s=!1,revision:n="main"}={}){if(e!==null)return Ht.from_pretrained(t,{config:e,cache_dir:r,local_files_only:s,revision:n});let o=Sn(t,{cache_dir:r,local_files_only:s,revision:n});return Vc(o,()=>Ht.from_pretrained(t,{config:e,cache_dir:r,local_files_only:s,revision:n}))}async function Qn(t,{config:e=null,dtype:r=null,device:s=null,model_file_name:n=null}={}){e=await ma(t,{config:e});let o=["config.json"],a=e["transformers.js_config"]??{},i=a.use_external_data_format,l="onnx",c=s??a.device,u=r??a.dtype,f=Yn(e),m=(x,b=null)=>{b=b??x;let A=uu(c,x),k=pu(u,x,A),M=Jr[k]??"",S=`${b}${M}.onnx`,O=l?`${l}/${S}`:S;o.push(O);let C=ng(i,S,x);for(let v of og(S,C)){let U=l?`${l}/${v}`:v;o.push(U)}},{sessions:_,optional_configs:w}=ip(f,e,{model_file_name:n});for(let[x,b]of Object.entries(_))m(x,b);if(w)for(let x of Object.values(w))o.push(x);return o}var Qs=null;function gM(t){Qs=t}function ug(t){if(t instanceof $)return t;if(t.length===0)throw Error("items must be non-empty");if(Array.isArray(t[0])){if(t.some(e=>e.length!==t[0].length))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.");return new $("int64",BigInt64Array.from(t.flat().map(e=>BigInt(e))),[t.length,t[0].length])}else return new $("int64",BigInt64Array.from(t.map(e=>BigInt(e))),[1,t.length])}function pg(t){return new $("bool",[t],[1])}var _M={[W.DecoderOnly]:{can_generate:!0,forward:Nt,prepare_inputs:ns},[W.DecoderOnlyWithoutHead]:{can_generate:!1,forward:Nt,prepare_inputs:ns},[W.Seq2Seq]:{can_generate:!0,forward:lp,prepare_inputs:_a},[W.Vision2Seq]:{can_generate:!0,forward:lp,prepare_inputs:_a},[W.Musicgen]:{can_generate:!0,forward:lp},[W.EncoderDecoder]:{can_generate:!1,forward:lp},[W.ImageTextToText]:{can_generate:!0,forward:r3,prepare_inputs:cp},[W.AudioTextToText]:{can_generate:!0,forward:t3,prepare_inputs:cp},[W.ImageAudioTextToText]:{can_generate:!0,prepare_inputs:cp},[W.Phi3V]:{can_generate:!0,prepare_inputs:cp},[W.MultiModality]:{can_generate:!0},[W.AutoEncoder]:{can_generate:!1,forward:ZR},[W.Chatterbox]:{can_generate:!0,forward:Xt},[W.VoxtralRealtime]:{can_generate:!0,prepare_inputs:ns},default:{can_generate:!1,forward:Xt}};function hM(t,e){let r=ar.get(t),s=!1,n=e?.architectures?.[0];if(n&&n!==t&&t?.endsWith("ForCausalLM")&&n.endsWith("ForConditionalGeneration")){let i=ar.get(n);i!==void 0&&(r=i,s=!0)}let o=_M[r]??_M.default,a=gr[r]??gr.default;return{typeConfig:{...o,...a},textOnly:s,modelType:r}}var ar=new Map,pp=new Map,Js=new Map,y=class extends We{main_input_name="input_ids";forward_params=["input_ids","attention_mask"];_return_dict_in_generate_keys=null;constructor(e,r,s){super(),this.config=e,this.sessions=r,this.configs=s;let n=Js.get(this.constructor),{typeConfig:o}=hM(n,e);this.can_generate=o.can_generate,this._forward=o.forward,this._prepare_inputs_for_generation=o.prepare_inputs,this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){let e=[];for(let r of Object.values(this.sessions))e.push(r.release?.());return await Promise.all(e)}static async from_pretrained(e,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main",model_file_name:i=null,subfolder:l="onnx",device:c=null,dtype:u=null,use_external_data_format:f=null,session_options:m={}}={}){let _={progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a,model_file_name:i,subfolder:l,device:c,dtype:u,use_external_data_format:f,session_options:m},w=Js.get(this);s=_.config=await Ht.from_pretrained(e,_);let{typeConfig:x,textOnly:b,modelType:A}=hM(w,s);if(A===void 0){let O=w??s?.model_type;O!=="custom"&&te.warn(`Model type for '${O}' not found, assuming encoder-only architecture. Please report this at ${es}.`)}if(r&&!(r instanceof Ar)){let O={};try{let C=await Qn(e,{config:s,dtype:u,device:c,model_file_name:i});(await Promise.all(C.map(U=>Pt(e,U,_)))).forEach((U,j)=>{if(U.exists){let F=C[j]==="config.json";O[C[j]]={loaded:F?U.size??0:0,total:U.size??0}}})}catch(C){te.warn(`Unable to fetch model file metadata for total progress tracking: ${C}`)}Object.keys(O).length>0&&(_.progress_callback=new Ar(r,O))}let k=x.sessions(s,_,b),M=[cM(e,k,_,x.cache_sessions)];x.optional_configs&&M.push(n3(e,x.optional_configs,_));let S=await Promise.all(M);return new this(s,...S)}async _call(e){return await this.forward(e)}async forward(e){return await this._forward(this,e)}get generation_config(){return this.configs?.generation_config??null}_get_logits_processor(e,r,s=null){let n=new Xs;if(e.repetition_penalty!==null&&e.repetition_penalty!==1&&n.push(new Zu(e.repetition_penalty)),e.no_repeat_ngram_size!==null&&e.no_repeat_ngram_size>0&&n.push(new Ju(e.no_repeat_ngram_size)),e.bad_words_ids!==null&&n.push(new rp(e.bad_words_ids,e.eos_token_id)),e.min_length!==null&&e.eos_token_id!==null&&e.min_length>0&&n.push(new ep(e.min_length,e.eos_token_id)),e.min_new_tokens!==null&&e.eos_token_id!==null&&e.min_new_tokens>0&&n.push(new tp(r,e.min_new_tokens,e.eos_token_id)),e.forced_bos_token_id!==null&&n.push(new Xu(e.forced_bos_token_id)),e.forced_eos_token_id!==null&&n.push(new Ku(e.max_length,e.forced_eos_token_id)),e.suppress_tokens!==null&&n.push(new Yu(e.suppress_tokens)),e.begin_suppress_tokens!==null){let o=r>1||e.forced_bos_token_id===null?r:r+1;n.push(new Hn(e.begin_suppress_tokens,o))}return e.guidance_scale!==null&&e.guidance_scale>1&&n.push(new sp(e.guidance_scale)),e.temperature===0&&e.do_sample&&(te.warn("`do_sample` changed to false because `temperature: 0` implies greedy sampling (always selecting the most likely token), which is incompatible with `do_sample: true`."),e.do_sample=!1),e.do_sample&&e.temperature!==null&&e.temperature!==1&&n.push(new np(e.temperature)),s!==null&&n.extend(s),n}_prepare_generation_config(e,r,s=Ks){let n={...this.config};for(let a of["decoder","generator","text_config"])a in n&&Object.assign(n,n[a]);let o=new s(n);return Object.assign(o,this.generation_config??{}),e&&Object.assign(o,e),r&&Object.assign(o,He(r,Object.getOwnPropertyNames(o))),o}_get_stopping_criteria(e,r=null){let s=new Xn;return e.max_length!==null&&s.push(new op(e.max_length,this.config.max_position_embeddings??null)),e.eos_token_id!==null&&s.push(new ap(e.eos_token_id)),r&&s.extend(r),s}_validate_model_class(){if(!this.can_generate){let e=[Qs.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,Qs.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES,Qs.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,Qs.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES].filter(Boolean),r=Js.get(this.constructor),s=new Set,n=this.config.model_type;for(let a of e){let i=a?.get(n);i&&s.add(i)}let o=`The current model class (${r}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw s.size>0&&(o+=` Please use the following class instead: ${[...s].join(", ")}`),Error(o)}}prepare_inputs_for_generation(...e){if(!this._prepare_inputs_for_generation)throw new Error("prepare_inputs_for_generation is not implemented for this model.");return this._prepare_inputs_for_generation(this,...e)}_update_model_kwargs_for_generation({generated_input_ids:e,outputs:r,model_inputs:s,is_encoder_decoder:n}){return s.past_key_values=up(r,s.past_key_values),s.input_ids=new $("int64",e.flat(),[e.length,1]),n?"decoder_attention_mask"in s&&(s.decoder_attention_mask=Ee([s.decoder_attention_mask,st([s.decoder_attention_mask.dims[0],1])],1)):s.attention_mask=Ee([s.attention_mask,st([s.attention_mask.dims[0],1])],1),s.position_ids=null,s}_prepare_model_inputs({inputs:e,bos_token_id:r,model_kwargs:s}){let n=He(s,this.forward_params),o=this.main_input_name;if(o in n){if(e)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else n[o]=e;return{inputs_tensor:n[o],model_inputs:n,model_input_name:o}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:e,model_inputs:r,model_input_name:s,generation_config:n}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!r.inputs_embeds&&"_prepare_inputs_embeds"in this){let{input_ids:a,pixel_values:i,attention_mask:l,...c}=r,u=await this._prepare_inputs_embeds(r);r={...c,...He(u,["inputs_embeds","attention_mask"])}}let{last_hidden_state:o}=await Xt(this,r);if(n.guidance_scale!==null&&n.guidance_scale>1)o=Ee([o,Ko(o,0)],0),"attention_mask"in r&&(r.attention_mask=Ee([r.attention_mask,Yo(r.attention_mask)],0));else if(r.decoder_input_ids){let a=ug(r.decoder_input_ids).dims[0];if(a!==o.dims[0]){if(o.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${o.dims[0]}) than the decoder inputs (${a}).`);o=Ee(Array.from({length:a},()=>o),0)}}return r.encoder_outputs=o,r}_prepare_decoder_input_ids_for_generation({batch_size:e,model_input_name:r,model_kwargs:s,decoder_start_token_id:n,bos_token_id:o,generation_config:a}){let{decoder_input_ids:i,...l}=s;if(!(i instanceof $)){if(i)Array.isArray(i[0])||(i=Array.from({length:e},()=>i));else if(n??=o,this.config.model_type==="musicgen")i=Array.from({length:e*this.config.decoder.num_codebooks},()=>[n]);else if(Array.isArray(n)){if(n.length!==e)throw new Error(`\`decoder_start_token_id\` expected to have length ${e} but got ${n.length}`);i=n}else i=Array.from({length:e},()=>[n]);i=ug(i)}return l.decoder_attention_mask=Ln(i),{input_ids:i,model_inputs:l}}async generate({inputs:e=null,generation_config:r=null,logits_processor:s=null,stopping_criteria:n=null,streamer:o=null,...a}){this._validate_model_class(),r=this._prepare_generation_config(r,a);let{inputs_tensor:i,model_inputs:l,model_input_name:c}=this._prepare_model_inputs({inputs:e,model_kwargs:a}),u=this.config.is_encoder_decoder;u&&("encoder_outputs"in l||(l=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:i,model_inputs:l,model_input_name:c,generation_config:r})));let f;u?{input_ids:f,model_inputs:l}=this._prepare_decoder_input_ids_for_generation({batch_size:l[c].dims.at(0),model_input_name:c,model_kwargs:l,decoder_start_token_id:r.decoder_start_token_id,bos_token_id:r.bos_token_id,generation_config:r}):f=l[c];let m=f.dims.at(-1);r.max_new_tokens!==null&&(r.max_length=m+r.max_new_tokens);let _=this._get_logits_processor(r,m,s),w=this._get_stopping_criteria(r,n),x=l[c].dims.at(0),b=Ys.getSampler(r),A=new Array(x).fill(0),k=f.tolist();o&&o.put(k);let M,S={},O={};for(;;){if(l=this.prepare_inputs_for_generation(k,l,r),M=await this.forward(l),r.return_dict_in_generate)if(r.output_attentions){let B=e3(M);for(let I in B)I in S||(S[I]=[]),S[I].push(B[I])}else this._return_dict_in_generate_keys&&Object.assign(O,He(M,this._return_dict_in_generate_keys));let F=M.logits.slice(null,-1,null).to("float32"),K=_(k,F),Y=[];for(let B=0;BB))break;l=this._update_model_kwargs_for_generation({generated_input_ids:Y,outputs:M,model_inputs:l,is_encoder_decoder:u})}o&&o.end();let C=new $("int64",k.flat(),[k.length,k[0].length]),v=up(M,l.past_key_values),U=new Set(Object.values(v));for(let F of Object.values(M))F.location==="gpu-buffer"&&!U.has(F)&&F.dispose();return"past_key_values"in a||r.return_dict_in_generate||await v.dispose(),r.return_dict_in_generate?{sequences:C,past_key_values:v,...S,...O}:C}async _encode_input(e,r,s){if(!Object.hasOwn(this.sessions,e))throw new Error(`Model does not have a ${e} session.`);let n=this.sessions[e];return(await pe(n,He(r,n.inputNames)))[s]}async encode_image(e){return this._encode_input("vision_encoder",e,"image_features")}async encode_text(e){return this._encode_input("embed_tokens",e,"inputs_embeds")}async encode_audio(e){return this._encode_input("audio_encoder",e,"audio_features")}};async function lp(t,e){let{encoder_outputs:r,input_ids:s,decoder_input_ids:n,decoder_attention_mask:o,...a}=e;if(!r){let i=He(e,t.sessions.model.inputNames);r=(await Xt(t,i)).last_hidden_state}return a.input_ids=n,a.encoder_hidden_states=r,t.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(a.encoder_attention_mask=e.attention_mask),o&&!a.attention_mask&&(a.attention_mask=o),await Nt(t,a,!0)}async function Xt(t,e){let r=t.sessions.model,s=He(e,r.inputNames);if(r.inputNames.includes("inputs_embeds")&&!s.inputs_embeds){if(!e.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");s.inputs_embeds=await t.encode_text({input_ids:e.input_ids})}if(r.inputNames.includes("token_type_ids")&&!s.token_type_ids){if(!s.input_ids)throw new Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");s.token_type_ids=Yo(s.input_ids)}if(r.inputNames.includes("pixel_mask")&&!s.pixel_mask){if(!s.pixel_values)throw new Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");let n=s.pixel_values.dims;s.pixel_mask=st([n[0],n[2],n[3]])}return await pe(r,s)}async function ZR(t,e){let r=await t.encode(e);return await t.decode(r)}function up(t,e){let r=Object.create(null);for(let s in t)if(s.startsWith("present")){let n=s.replace("present_ssm","past_ssm").replace("present_conv","past_conv").replace("present_recurrent","past_recurrent").replace("present_compressor","past_compressor").replace("present_indexer","past_indexer").replace("present","past_key_values");s.includes("encoder")&&e?r[n]=e[n]:r[n]=t[s]}return e?(e.update(r),e):new Kn(r)}function e3(t){let e={};for(let r of["cross_attentions","encoder_attentions","decoder_attentions"])for(let s in t)s.startsWith(r)&&(r in e||(e[r]=[]),e[r].push(t[s]));return e}function fg(t,e){return t.map(r=>typeof r=="number"?r:e[r]??0)}function ha(t,e,r){if(r&&Object.keys(r).length>0)return Object.assign(e,r),r;let s=t.sessions.decoder_model_merged??t.sessions.model,n=(e[t.main_input_name]??e.attention_mask)?.dims?.[0]??1,o=Hs(t.config),a=t.config?.normalized_config?.num_heads,i={batch_size:n};typeof a=="number"&&(i["batch_size x num_heads"]=n*a);let l=Object.create(null);for(let c of s.inputMetadata){if(!o.has(c.name))continue;let u=fg(c.shape,i),f=u.reduce((w,x)=>w*x,1),m=Zr[c.type],_=new $(c.type,new m(f),u);e[c.name]=_,l[c.name]=_}return r?(r.update(l),r):new Kn(l)}function Zs(t,e,r){if(e.num_logits_to_keep)return;(t.sessions.decoder_model_merged??t.sessions.model)?.inputNames.includes("num_logits_to_keep")&&(e.num_logits_to_keep=new $("int64",[r],[]))}async function Nt(t,e,r=!1){let s=t.sessions[r?"decoder_model_merged":"model"],{past_key_values:n,...o}=e;if(s.inputNames.includes("use_cache_branch")&&(o.use_cache_branch=pg(n!=null&&Object.keys(n).length>0)),s.inputNames.includes("position_ids")&&o.attention_mask&&!o.position_ids){let i=["paligemma","gemma3_text","gemma3"].includes(t.config.model_type)?1:0;o.position_ids=s3(o,n,i)}Zs(t,o,0n),ha(t,o,n);let a=He(o,s.inputNames);return await pe(s,a)}async function wM(t,{encode_function:e,merge_function:r,modality_input_names:s,modality_output_name:n,input_ids:o=null,attention_mask:a=null,position_ids:i=null,inputs_embeds:l=null,past_key_values:c=null,generation_config:u=null,logits_processor:f=null,num_logits_to_keep:m=null,..._}){if(!l){l=await t.encode_text({input_ids:o,..._});let x=He(_,s);if(Object.keys(x).length>0){if(o.dims[1]!==1){let b=await e({...x,..._});({inputs_embeds:l,attention_mask:a}=r({[n]:b,inputs_embeds:l,input_ids:o,attention_mask:a}))}else if(c&&o.dims[1]===1){let b=o.dims[1],A=c.get_seq_length();a=Ee([st([o.dims[0],A]),a.slice(null,[a.dims[1]-b,a.dims[1]])],1)}}}if(!i&&["qwen2_vl","qwen2_vl_text","qwen2_5_vl","qwen2_5_vl_text","qwen3_vl","qwen3_vl_text","qwen3_vl_moe","qwen3_vl_moe_text","qwen3_5","qwen3_5_text","qwen3_5_moe","qwen3_5_moe_text","glm_ocr","glm_ocr_text"].includes(t.config.model_type)){let{image_grid_thw:x,video_grid_thw:b}=_;[i]=t.get_rope_index(o,x,b,a)}return await Nt(t,{inputs_embeds:l,past_key_values:c,attention_mask:a,position_ids:i,generation_config:u,logits_processor:f,num_logits_to_keep:m},!0)}async function t3(t,e){return await wM(t,{...e,modality_input_names:["audio_values","input_features"],modality_output_name:"audio_features",encode_function:t.encode_audio.bind(t),merge_function:t._merge_input_ids_with_audio_features.bind(t)})}async function r3(t,e){return await wM(t,{...e,modality_input_names:["pixel_values"],modality_output_name:"image_features",encode_function:t.encode_image.bind(t),merge_function:t._merge_input_ids_with_image_features.bind(t)})}function dg(t,e=0){let[r,s]=t.dims,n=t.data,o=new BigInt64Array(n.length);for(let a=0;ao.dims[1]||n[n.at(-1)])),Zs(t,r,1n),{...r,decoder_input_ids:ug(e)}}function cp(t,...e){return t.config.is_encoder_decoder?_a(t,...e):ns(t,...e)}function xM({modality_token_id:t,inputs_embeds:e,modality_features:r,input_ids:s,attention_mask:n}){let o=s.tolist().map(c=>c.reduce((u,f,m)=>(f==t&&u.push(m),u),[])),a=o.reduce((c,u)=>c+u.length,0),i=r.dims[0];if(a!==i)throw new Error(`Number of tokens and features do not match: tokens: ${a}, features ${i}`);let l=0;for(let c=0;c{let n=await lt(t,e[s],!1,r);return[s,n]})))}var Ul={};yn(Ul,{ASTForAudioClassification:()=>Ag,ASTModel:()=>Eg,ASTPreTrainedModel:()=>ya,AfmoeForCausalLM:()=>bg,AfmoeModel:()=>yg,AfmoePreTrainedModel:()=>wa,AlbertForMaskedLM:()=>gg,AlbertForQuestionAnswering:()=>hg,AlbertForSequenceClassification:()=>_g,AlbertModel:()=>mg,AlbertPreTrainedModel:()=>en,ApertusForCausalLM:()=>xg,ApertusModel:()=>wg,ApertusPreTrainedModel:()=>ga,ArceeForCausalLM:()=>kg,ArceeModel:()=>vg,ArceePreTrainedModel:()=>xa,BartForConditionalGeneration:()=>Sg,BartForSequenceClassification:()=>Mg,BartModel:()=>Tg,BartPretrainedModel:()=>Zn,BaseModelOutput:()=>Wu,BeitForImageClassification:()=>Ig,BeitModel:()=>Og,BeitPreTrainedModel:()=>ba,BertForMaskedLM:()=>Pg,BertForQuestionAnswering:()=>zg,BertForSequenceClassification:()=>Ng,BertForTokenClassification:()=>Lg,BertModel:()=>Cg,BertPreTrainedModel:()=>os,BlenderbotForConditionalGeneration:()=>Rg,BlenderbotModel:()=>$g,BlenderbotPreTrainedModel:()=>va,BlenderbotSmallForConditionalGeneration:()=>Dg,BlenderbotSmallModel:()=>Bg,BlenderbotSmallPreTrainedModel:()=>ka,BloomForCausalLM:()=>Fg,BloomModel:()=>Ug,BloomPreTrainedModel:()=>Ea,CHMv2ForDepthEstimation:()=>Xg,CHMv2PreTrainedModel:()=>_p,CLIPModel:()=>Yg,CLIPPreTrainedModel:()=>wr,CLIPSegForImageSegmentation:()=>tw,CLIPSegModel:()=>ew,CLIPSegPreTrainedModel:()=>Oa,CLIPTextModel:()=>Qg,CLIPTextModelWithProjection:()=>Ma,CLIPVisionModel:()=>Jg,CLIPVisionModelWithProjection:()=>Zg,CamembertForMaskedLM:()=>jg,CamembertForQuestionAnswering:()=>Vg,CamembertForSequenceClassification:()=>qg,CamembertForTokenClassification:()=>Wg,CamembertModel:()=>Gg,CamembertPreTrainedModel:()=>as,CausalLMOutput:()=>ht,CausalLMOutputWithPast:()=>Vu,ChatterboxModel:()=>Aa,ChatterboxPreTrainedModel:()=>dp,ChineseCLIPModel:()=>Hg,ChineseCLIPPreTrainedModel:()=>mp,ClapAudioModelWithProjection:()=>Sa,ClapModel:()=>Kg,ClapPreTrainedModel:()=>eo,ClapTextModelWithProjection:()=>Ta,CodeGenForCausalLM:()=>sw,CodeGenModel:()=>rw,CodeGenPreTrainedModel:()=>Ia,Cohere2ForCausalLM:()=>iw,Cohere2Model:()=>aw,Cohere2PreTrainedModel:()=>Pa,CohereAsrForConditionalGeneration:()=>cw,CohereAsrModel:()=>lw,CohereAsrPreTrainedModel:()=>Na,CohereForCausalLM:()=>ow,CohereModel:()=>nw,CoherePreTrainedModel:()=>Ca,ConvBertForMaskedLM:()=>pw,ConvBertForQuestionAnswering:()=>mw,ConvBertForSequenceClassification:()=>fw,ConvBertForTokenClassification:()=>dw,ConvBertModel:()=>uw,ConvBertPreTrainedModel:()=>is,ConvNextForImageClassification:()=>hw,ConvNextModel:()=>_w,ConvNextPreTrainedModel:()=>La,ConvNextV2ForImageClassification:()=>ww,ConvNextV2Model:()=>gw,ConvNextV2PreTrainedModel:()=>za,DFineForObjectDetection:()=>vw,DFineModel:()=>bw,DFinePreTrainedModel:()=>Ra,DINOv3ConvNextModel:()=>Yw,DINOv3ConvNextPreTrainedModel:()=>vp,DINOv3ViTModel:()=>Qw,DINOv3ViTPreTrainedModel:()=>kp,DPTForDepthEstimation:()=>ox,DPTModel:()=>nx,DPTPreTrainedModel:()=>Wa,DacDecoderModel:()=>Da,DacDecoderOutput:()=>gp,DacEncoderModel:()=>Ba,DacEncoderOutput:()=>hp,DacModel:()=>kw,DacPreTrainedModel:()=>to,DebertaForMaskedLM:()=>Aw,DebertaForQuestionAnswering:()=>Mw,DebertaForSequenceClassification:()=>Tw,DebertaForTokenClassification:()=>Sw,DebertaModel:()=>Ew,DebertaPreTrainedModel:()=>ls,DebertaV2ForMaskedLM:()=>Lw,DebertaV2ForQuestionAnswering:()=>Rw,DebertaV2ForSequenceClassification:()=>zw,DebertaV2ForTokenClassification:()=>$w,DebertaV2Model:()=>Nw,DebertaV2PreTrainedModel:()=>cs,DecisionTransformerModel:()=>Bw,DecisionTransformerPreTrainedModel:()=>wp,DeepseekV3ForCausalLM:()=>Iw,DeepseekV3Model:()=>Ow,DeepseekV3PreTrainedModel:()=>Ua,DeepseekV4ForCausalLM:()=>Pw,DeepseekV4Model:()=>Cw,DeepseekV4PreTrainedModel:()=>Fa,DeiTForImageClassification:()=>Uw,DeiTModel:()=>Dw,DeiTPreTrainedModel:()=>Ga,DepthAnythingForDepthEstimation:()=>Fw,DepthAnythingPreTrainedModel:()=>xp,DepthProForDepthEstimation:()=>Gw,DepthProPreTrainedModel:()=>yp,DetrForObjectDetection:()=>qw,DetrForSegmentation:()=>Ww,DetrModel:()=>jw,DetrObjectDetectionOutput:()=>so,DetrPreTrainedModel:()=>ro,DetrSegmentationOutput:()=>bp,Dinov2ForImageClassification:()=>Hw,Dinov2Model:()=>Vw,Dinov2PreTrainedModel:()=>ja,Dinov2WithRegistersForImageClassification:()=>Kw,Dinov2WithRegistersModel:()=>Xw,Dinov2WithRegistersPreTrainedModel:()=>qa,DistilBertForMaskedLM:()=>rx,DistilBertForQuestionAnswering:()=>tx,DistilBertForSequenceClassification:()=>Zw,DistilBertForTokenClassification:()=>ex,DistilBertModel:()=>Jw,DistilBertPreTrainedModel:()=>us,DonutSwinModel:()=>sx,DonutSwinPreTrainedModel:()=>Ep,EdgeTamModel:()=>T1,EfficientNetForImageClassification:()=>ix,EfficientNetModel:()=>ax,EfficientNetPreTrainedModel:()=>Va,ElectraForMaskedLM:()=>cx,ElectraForQuestionAnswering:()=>fx,ElectraForSequenceClassification:()=>ux,ElectraForTokenClassification:()=>px,ElectraModel:()=>lx,ElectraPreTrainedModel:()=>ps,EmbeddingGemma2Model:()=>Ha,EmbeddingGemma2PreTrainedModel:()=>Ap,Ernie4_5ForCausalLM:()=>mx,Ernie4_5Model:()=>dx,Ernie4_5PretrainedModel:()=>Xa,EsmForMaskedLM:()=>hx,EsmForSequenceClassification:()=>gx,EsmForTokenClassification:()=>wx,EsmModel:()=>_x,EsmPreTrainedModel:()=>tn,EuroBertForMaskedLM:()=>yx,EuroBertForSequenceClassification:()=>bx,EuroBertForTokenClassification:()=>vx,EuroBertModel:()=>xx,EuroBertPreTrainedModel:()=>rn,ExaoneForCausalLM:()=>Ex,ExaoneModel:()=>kx,ExaonePreTrainedModel:()=>Ka,FalconForCausalLM:()=>Tx,FalconH1ForCausalLM:()=>Mx,FalconH1Model:()=>Sx,FalconH1PreTrainedModel:()=>Qa,FalconModel:()=>Ax,FalconPreTrainedModel:()=>Ya,FastViTForImageClassification:()=>Ix,FastViTModel:()=>Ox,FastViTPreTrainedModel:()=>Ja,Florence2ForConditionalGeneration:()=>Cx,Florence2PreTrainedModel:()=>Tp,GLPNForDepthEstimation:()=>Xx,GLPNModel:()=>Hx,GLPNPreTrainedModel:()=>oi,GPT2LMHeadModel:()=>ny,GPT2Model:()=>sy,GPT2PreTrainedModel:()=>ui,GPTBigCodeForCausalLM:()=>Yx,GPTBigCodeModel:()=>Kx,GPTBigCodePreTrainedModel:()=>ai,GPTJForCausalLM:()=>ay,GPTJModel:()=>oy,GPTJPreTrainedModel:()=>pi,GPTNeoForCausalLM:()=>Jx,GPTNeoModel:()=>Qx,GPTNeoPreTrainedModel:()=>ii,GPTNeoXForCausalLM:()=>ey,GPTNeoXModel:()=>Zx,GPTNeoXPreTrainedModel:()=>li,Gemma2ForCausalLM:()=>zx,Gemma2Model:()=>Lx,Gemma2PreTrainedModel:()=>ei,Gemma3ForCausalLM:()=>Dx,Gemma3ForConditionalGeneration:()=>Op,Gemma3Model:()=>Bx,Gemma3PreTrainedModel:()=>Mp,Gemma3nForCausalLM:()=>Ux,Gemma3nForConditionalGeneration:()=>fs,Gemma3nPreTrainedModel:()=>Ip,Gemma4ForCausalLM:()=>Fx,Gemma4ForConditionalGeneration:()=>no,GemmaForCausalLM:()=>Nx,GemmaModel:()=>Px,GemmaPreTrainedModel:()=>Za,GlmForCausalLM:()=>jx,GlmModel:()=>Gx,GlmMoeDsaForCausalLM:()=>Wx,GlmMoeDsaModel:()=>qx,GlmMoeDsaPreTrainedModel:()=>ri,GlmOcrForConditionalGeneration:()=>Vx,GlmPreTrainedModel:()=>ti,GptOssForCausalLM:()=>ry,GptOssModel:()=>ty,GptOssPreTrainedModel:()=>ci,GraniteForCausalLM:()=>ly,GraniteModel:()=>iy,GraniteMoeHybridForCausalLM:()=>uy,GraniteMoeHybridModel:()=>cy,GraniteMoeHybridPreTrainedModel:()=>di,GranitePreTrainedModel:()=>fi,GraniteSpeechForConditionalGeneration:()=>py,GroundingDinoForObjectDetection:()=>fy,GroundingDinoPreTrainedModel:()=>Np,GroupViTModel:()=>dy,GroupViTPreTrainedModel:()=>Lp,HeliumForCausalLM:()=>_y,HeliumModel:()=>my,HeliumPreTrainedModel:()=>mi,HieraForImageClassification:()=>gy,HieraModel:()=>hy,HieraPreTrainedModel:()=>_i,HrmTextForCausalLM:()=>xy,HrmTextModel:()=>wy,HrmTextPreTrainedModel:()=>hi,HubertForCTC:()=>Ty,HubertForSequenceClassification:()=>Sy,HubertModel:()=>Ay,HubertPreTrainedModel:()=>Ey,HunYuanDenseV1ForCausalLM:()=>Oy,HunYuanDenseV1Model:()=>My,HunYuanDenseV1PreTrainedModel:()=>gi,IJepaForImageClassification:()=>Cy,IJepaModel:()=>Iy,IJepaPreTrainedModel:()=>xi,Idefics3ForConditionalGeneration:()=>wi,ImageMattingOutput:()=>Vn,JAISLMHeadModel:()=>Ny,JAISModel:()=>Py,JAISPreTrainedModel:()=>yi,JinaCLIPModel:()=>Ly,JinaCLIPPreTrainedModel:()=>ao,JinaCLIPTextModel:()=>bi,JinaCLIPVisionModel:()=>zy,Lfm2ForCausalLM:()=>Ry,Lfm2Model:()=>$y,Lfm2MoeForCausalLM:()=>Uy,Lfm2MoeModel:()=>Dy,Lfm2MoePreTrainedModel:()=>ki,Lfm2PreTrainedModel:()=>vi,Lfm2VlForConditionalGeneration:()=>Fy,Lfm3ForCausalLM:()=>jy,Lfm3Model:()=>Gy,Lfm3PreTrainedModel:()=>Ei,Lfm3VlForConditionalGeneration:()=>qy,LightOnOcrForConditionalGeneration:()=>By,LiteWhisperForConditionalGeneration:()=>Gv,Llama4ForCausalLM:()=>Hy,Llama4PreTrainedModel:()=>zp,LlamaForCausalLM:()=>Vy,LlamaModel:()=>Wy,LlamaPreTrainedModel:()=>Ai,LlavaForConditionalGeneration:()=>ut,LlavaOnevisionForConditionalGeneration:()=>ut,LlavaPreTrainedModel:()=>Sp,LlavaQwen2ForCausalLM:()=>Rx,LongT5ForConditionalGeneration:()=>Ky,LongT5Model:()=>Xy,LongT5PreTrainedModel:()=>Ti,M2M100ForConditionalGeneration:()=>Qy,M2M100Model:()=>Yy,M2M100PreTrainedModel:()=>Si,MBartForCausalLM:()=>o0,MBartForConditionalGeneration:()=>s0,MBartForSequenceClassification:()=>n0,MBartModel:()=>r0,MBartPreTrainedModel:()=>on,MPNetForMaskedLM:()=>Y0,MPNetForQuestionAnswering:()=>Z0,MPNetForSequenceClassification:()=>Q0,MPNetForTokenClassification:()=>J0,MPNetModel:()=>K0,MPNetPreTrainedModel:()=>ds,MT5ForConditionalGeneration:()=>sb,MT5Model:()=>rb,MT5PreTrainedModel:()=>Gi,MarianMTModel:()=>Zy,MarianModel:()=>Jy,MarianPreTrainedModel:()=>Mi,MaskFormerForInstanceSegmentation:()=>t0,MaskFormerModel:()=>e0,MaskFormerPreTrainedModel:()=>Oi,MaskedLMOutput:()=>ye,Metric3DForDepthEstimation:()=>a0,Metric3DPreTrainedModel:()=>$p,Metric3Dv2ForDepthEstimation:()=>i0,Metric3Dv2PreTrainedModel:()=>Rp,MgpstrForSceneTextRecognition:()=>l0,MgpstrModelOutput:()=>Bp,MgpstrPreTrainedModel:()=>Dp,MimiDecoderModel:()=>Ci,MimiDecoderOutput:()=>Fp,MimiEncoderModel:()=>Ii,MimiEncoderOutput:()=>Up,MimiModel:()=>c0,MimiPreTrainedModel:()=>io,Ministral3ForCausalLM:()=>d0,Ministral3Model:()=>f0,Ministral3PreTrainedModel:()=>Ni,MinistralForCausalLM:()=>p0,MinistralModel:()=>u0,MinistralPreTrainedModel:()=>Pi,Mistral3ForConditionalGeneration:()=>h0,Mistral4ForCausalLM:()=>w0,Mistral4Model:()=>g0,Mistral4PreTrainedModel:()=>zi,MistralForCausalLM:()=>_0,MistralModel:()=>m0,MistralPreTrainedModel:()=>Li,MobileBertForMaskedLM:()=>y0,MobileBertForQuestionAnswering:()=>v0,MobileBertForSequenceClassification:()=>b0,MobileBertModel:()=>x0,MobileBertPreTrainedModel:()=>an,MobileLLMForCausalLM:()=>E0,MobileLLMModel:()=>k0,MobileLLMPreTrainedModel:()=>$i,MobileNetV1ForImageClassification:()=>T0,MobileNetV1ForSemanticSegmentation:()=>S0,MobileNetV1Model:()=>A0,MobileNetV1PreTrainedModel:()=>lo,MobileNetV2ForImageClassification:()=>O0,MobileNetV2ForSemanticSegmentation:()=>I0,MobileNetV2Model:()=>M0,MobileNetV2PreTrainedModel:()=>co,MobileNetV3ForImageClassification:()=>P0,MobileNetV3ForSemanticSegmentation:()=>N0,MobileNetV3Model:()=>C0,MobileNetV3PreTrainedModel:()=>uo,MobileNetV4ForImageClassification:()=>z0,MobileNetV4ForSemanticSegmentation:()=>$0,MobileNetV4Model:()=>L0,MobileNetV4PreTrainedModel:()=>po,MobileViTForImageClassification:()=>B0,MobileViTModel:()=>R0,MobileViTPreTrainedModel:()=>Ri,MobileViTV2ForImageClassification:()=>U0,MobileViTV2Model:()=>D0,MobileViTV2PreTrainedModel:()=>Bi,ModelOutput:()=>Se,ModernBertDecoderForCausalLM:()=>V0,ModernBertDecoderModel:()=>W0,ModernBertDecoderPreTrainedModel:()=>Di,ModernBertForMaskedLM:()=>G0,ModernBertForSequenceClassification:()=>j0,ModernBertForTokenClassification:()=>q0,ModernBertModel:()=>F0,ModernBertPreTrainedModel:()=>ln,Moondream1ForConditionalGeneration:()=>$x,MoonshineForConditionalGeneration:()=>X0,MoonshineModel:()=>H0,MoonshinePreTrainedModel:()=>Ui,MptForCausalLM:()=>tb,MptModel:()=>eb,MptPreTrainedModel:()=>Fi,MultiModalityCausalLM:()=>nb,MultiModalityPreTrainedModel:()=>Gp,MusicgenForCausalLM:()=>ab,MusicgenForConditionalGeneration:()=>qi,MusicgenModel:()=>ob,MusicgenPreTrainedModel:()=>ji,NanoChatForCausalLM:()=>lb,NanoChatModel:()=>ib,NanoChatPreTrainedModel:()=>Wi,NemotronHForCausalLM:()=>ub,NemotronHModel:()=>cb,NemotronHPreTrainedModel:()=>Vi,NeoBertForMaskedLM:()=>fb,NeoBertForQuestionAnswering:()=>_b,NeoBertForSequenceClassification:()=>db,NeoBertForTokenClassification:()=>mb,NeoBertModel:()=>pb,NeoBertPreTrainedModel:()=>ms,NomicBertModel:()=>hb,NomicBertPreTrainedModel:()=>jp,OPTForCausalLM:()=>Ib,OPTModel:()=>Ob,OPTPreTrainedModel:()=>Zi,Olmo2ForCausalLM:()=>yb,Olmo2Model:()=>xb,Olmo2PreTrainedModel:()=>Xi,Olmo3ForCausalLM:()=>vb,Olmo3Model:()=>bb,Olmo3PreTrainedModel:()=>Ki,OlmoForCausalLM:()=>wb,OlmoHybridForCausalLM:()=>Eb,OlmoHybridModel:()=>kb,OlmoHybridPreTrainedModel:()=>Yi,OlmoModel:()=>gb,OlmoPreTrainedModel:()=>Hi,OpenAIPrivacyFilterForTokenClassification:()=>Tb,OpenAIPrivacyFilterModel:()=>Ab,OpenAIPrivacyFilterPreTrainedModel:()=>Qi,OpenELMForCausalLM:()=>Mb,OpenELMModel:()=>Sb,OpenELMPreTrainedModel:()=>Ji,OwlViTForObjectDetection:()=>Lb,OwlViTModel:()=>Nb,OwlViTPreTrainedModel:()=>tl,Owlv2ForObjectDetection:()=>Pb,Owlv2Model:()=>Cb,Owlv2PreTrainedModel:()=>el,PaliGemmaForConditionalGeneration:()=>zb,ParakeetForCTC:()=>$b,ParakeetPreTrainedModel:()=>qp,PatchTSMixerForPrediction:()=>Bb,PatchTSMixerModel:()=>Rb,PatchTSMixerPreTrainedModel:()=>rl,PatchTSTForPrediction:()=>Ub,PatchTSTModel:()=>Db,PatchTSTPreTrainedModel:()=>sl,Phi3ForCausalLM:()=>qb,Phi3Model:()=>jb,Phi3PreTrainedModel:()=>ol,Phi3VForCausalLM:()=>al,Phi3VPreTrainedModel:()=>Wp,PhiForCausalLM:()=>Gb,PhiModel:()=>Fb,PhiPreTrainedModel:()=>nl,PreTrainedModel:()=>y,PvtForImageClassification:()=>Vb,PvtModel:()=>Wb,PvtPreTrainedModel:()=>il,PyAnnoteForAudioFrameClassification:()=>Xb,PyAnnoteModel:()=>Hb,PyAnnotePreTrainedModel:()=>ll,QuestionAnsweringModelOutput:()=>Me,Qwen2ForCausalLM:()=>Yb,Qwen2Model:()=>Kb,Qwen2MoeForCausalLM:()=>Jb,Qwen2MoeModel:()=>Qb,Qwen2MoePreTrainedModel:()=>ul,Qwen2PreTrainedModel:()=>cl,Qwen2VLForCausalLM:()=>si,Qwen2VLForConditionalGeneration:()=>oo,Qwen2VLPreTrainedModel:()=>Cp,Qwen2_5_VLForCausalLM:()=>ni,Qwen2_5_VLForConditionalGeneration:()=>sn,Qwen3ForCausalLM:()=>e1,Qwen3Model:()=>Zb,Qwen3MoeForCausalLM:()=>r1,Qwen3MoeModel:()=>t1,Qwen3MoePreTrainedModel:()=>fl,Qwen3NextForCausalLM:()=>n1,Qwen3NextModel:()=>s1,Qwen3NextPreTrainedModel:()=>dl,Qwen3PreTrainedModel:()=>pl,Qwen3VLForCausalLM:()=>ml,Qwen3VLForConditionalGeneration:()=>cn,Qwen3VLMoeForCausalLM:()=>a1,Qwen3VLMoeForConditionalGeneration:()=>o1,Qwen3_5ForCausalLM:()=>_l,Qwen3_5ForConditionalGeneration:()=>fo,Qwen3_5MoeForCausalLM:()=>l1,Qwen3_5MoeForConditionalGeneration:()=>i1,RFDetrForObjectDetection:()=>f1,RFDetrModel:()=>p1,RFDetrObjectDetectionOutput:()=>Vp,RFDetrPreTrainedModel:()=>gl,RTDetrForObjectDetection:()=>yw,RTDetrModel:()=>xw,RTDetrObjectDetectionOutput:()=>xr,RTDetrPreTrainedModel:()=>$a,RTDetrV2ForObjectDetection:()=>E1,RTDetrV2Model:()=>k1,RTDetrV2ObjectDetectionOutput:()=>Hp,RTDetrV2PreTrainedModel:()=>wl,ResNetForImageClassification:()=>u1,ResNetModel:()=>c1,ResNetPreTrainedModel:()=>hl,RoFormerForMaskedLM:()=>x1,RoFormerForQuestionAnswering:()=>v1,RoFormerForSequenceClassification:()=>y1,RoFormerForTokenClassification:()=>b1,RoFormerModel:()=>w1,RoFormerPreTrainedModel:()=>hs,RobertaForMaskedLM:()=>m1,RobertaForQuestionAnswering:()=>g1,RobertaForSequenceClassification:()=>_1,RobertaForTokenClassification:()=>h1,RobertaModel:()=>d1,RobertaPreTrainedModel:()=>_s,Sam2ImageSegmentationOutput:()=>Yp,Sam2Model:()=>xl,Sam2PreTrainedModel:()=>Qp,Sam3TrackerModel:()=>S1,SamImageSegmentationOutput:()=>Xp,SamModel:()=>A1,SamPreTrainedModel:()=>Kp,SapiensForDepthEstimation:()=>O1,SapiensForNormalEstimation:()=>I1,SapiensForSemanticSegmentation:()=>M1,SapiensPreTrainedModel:()=>mo,SegformerForImageClassification:()=>P1,SegformerForSemanticSegmentation:()=>N1,SegformerModel:()=>C1,SegformerPreTrainedModel:()=>_o,Seq2SeqLMOutput:()=>Hu,SequenceClassifierOutput:()=>q,SiglipModel:()=>L1,SiglipPreTrainedModel:()=>yl,SiglipTextModel:()=>bl,SiglipVisionModel:()=>z1,SmolLM3ForCausalLM:()=>R1,SmolLM3Model:()=>$1,SmolLM3PreTrainedModel:()=>vl,SmolVLMForConditionalGeneration:()=>B1,SnacDecoderModel:()=>El,SnacEncoderModel:()=>kl,SnacModel:()=>D1,SnacPreTrainedModel:()=>ho,SolarOpenForCausalLM:()=>F1,SolarOpenModel:()=>U1,SolarOpenPreTrainedModel:()=>Al,SpeechT5ForSpeechToText:()=>j1,SpeechT5ForTextToSpeech:()=>q1,SpeechT5HifiGan:()=>W1,SpeechT5Model:()=>G1,SpeechT5PreTrainedModel:()=>go,SqueezeBertForMaskedLM:()=>H1,SqueezeBertForQuestionAnswering:()=>K1,SqueezeBertForSequenceClassification:()=>X1,SqueezeBertModel:()=>V1,SqueezeBertPreTrainedModel:()=>un,StableLmForCausalLM:()=>Q1,StableLmModel:()=>Y1,StableLmPreTrainedModel:()=>Tl,Starcoder2ForCausalLM:()=>Z1,Starcoder2Model:()=>J1,Starcoder2PreTrainedModel:()=>Sl,StyleTextToSpeech2Model:()=>ev,StyleTextToSpeech2PreTrainedModel:()=>Jp,SupertonicForConditionalGeneration:()=>Ml,SupertonicPreTrainedModel:()=>Zp,Swin2SRForImageSuperResolution:()=>ov,Swin2SRModel:()=>nv,Swin2SRPreTrainedModel:()=>Ol,SwinForImageClassification:()=>rv,SwinForSemanticSegmentation:()=>sv,SwinModel:()=>tv,SwinPreTrainedModel:()=>wo,T5ForConditionalGeneration:()=>iv,T5Model:()=>av,T5PreTrainedModel:()=>Il,TableTransformerForObjectDetection:()=>cv,TableTransformerModel:()=>lv,TableTransformerObjectDetectionOutput:()=>ef,TableTransformerPreTrainedModel:()=>Cl,TokenClassifierOutput:()=>we,TrOCRForCausalLM:()=>uv,TrOCRPreTrainedModel:()=>tf,UltravoxModel:()=>nn,UltravoxPreTrainedModel:()=>Pp,UniSpeechForCTC:()=>fv,UniSpeechForSequenceClassification:()=>dv,UniSpeechModel:()=>pv,UniSpeechPreTrainedModel:()=>xo,UniSpeechSatForAudioFrameClassification:()=>gv,UniSpeechSatForCTC:()=>_v,UniSpeechSatForSequenceClassification:()=>hv,UniSpeechSatModel:()=>mv,UniSpeechSatPreTrainedModel:()=>pn,VaultGemmaForCausalLM:()=>xv,VaultGemmaModel:()=>wv,VaultGemmaPreTrainedModel:()=>Pl,ViTForImageClassification:()=>vv,ViTMAEModel:()=>kv,ViTMAEPreTrainedModel:()=>rf,ViTMSNForImageClassification:()=>Av,ViTMSNModel:()=>Ev,ViTMSNPreTrainedModel:()=>Ll,ViTModel:()=>bv,ViTPreTrainedModel:()=>Nl,VisionEncoderDecoderModel:()=>yv,VitMatteForImageMatting:()=>Tv,VitMattePreTrainedModel:()=>sf,VitPoseForPoseEstimation:()=>Sv,VitPosePreTrainedModel:()=>nf,VitsModel:()=>Mv,VitsModelOutput:()=>of,VitsPreTrainedModel:()=>af,VoxtralForConditionalGeneration:()=>Ov,VoxtralRealtimeForConditionalGeneration:()=>zl,VoxtralRealtimePreTrainedModel:()=>lf,Wav2Vec2BertForCTC:()=>Nv,Wav2Vec2BertForSequenceClassification:()=>Lv,Wav2Vec2BertModel:()=>Pv,Wav2Vec2BertPreTrainedModel:()=>yo,Wav2Vec2ForAudioFrameClassification:()=>ky,Wav2Vec2ForCTC:()=>by,Wav2Vec2ForSequenceClassification:()=>vy,Wav2Vec2Model:()=>yy,Wav2Vec2PreTrainedModel:()=>ir,WavLMForAudioFrameClassification:()=>Dv,WavLMForCTC:()=>$v,WavLMForSequenceClassification:()=>Rv,WavLMForXVector:()=>Bv,WavLMModel:()=>zv,WavLMPreTrainedModel:()=>gs,WeSpeakerResNetModel:()=>Uv,WeSpeakerResNetPreTrainedModel:()=>uf,WhisperForConditionalGeneration:()=>ff,WhisperModel:()=>Fv,WhisperPreTrainedModel:()=>$l,XLMForQuestionAnswering:()=>Hv,XLMForSequenceClassification:()=>Wv,XLMForTokenClassification:()=>Vv,XLMModel:()=>jv,XLMPreTrainedModel:()=>ws,XLMRobertaForMaskedLM:()=>Kv,XLMRobertaForQuestionAnswering:()=>Jv,XLMRobertaForSequenceClassification:()=>Yv,XLMRobertaForTokenClassification:()=>Qv,XLMRobertaModel:()=>Xv,XLMRobertaPreTrainedModel:()=>xs,XLMWithLMHeadModel:()=>qv,XVectorOutput:()=>cf,YolosForObjectDetection:()=>ek,YolosModel:()=>Zv,YolosObjectDetectionOutput:()=>df,YolosPreTrainedModel:()=>Rl,YoutuForCausalLM:()=>rk,YoutuModel:()=>tk,YoutuPreTrainedModel:()=>Bl,ZayaForCausalLM:()=>nk,ZayaModel:()=>sk,ZayaPreTrainedModel:()=>Dl});var en=class extends y{},mg=class extends en{},_g=class extends en{async _call(e){return new q(await super._call(e))}},hg=class extends en{async _call(e){return new Me(await super._call(e))}},gg=class extends en{async _call(e){return new ye(await super._call(e))}};var ga=class extends y{},wg=class extends ga{},xg=class extends ga{};var wa=class extends y{},yg=class extends wa{},bg=class extends wa{};var xa=class extends y{},vg=class extends xa{},kg=class extends xa{};var ya=class extends y{},Eg=class extends ya{},Ag=class extends ya{};var Zn=class extends y{},Tg=class extends Zn{},Sg=class extends Zn{},Mg=class extends Zn{async _call(e){return new q(await super._call(e))}};var ba=class extends y{},Og=class extends ba{},Ig=class extends ba{async _call(e){return new q(await super._call(e))}};var os=class extends y{},Cg=class extends os{},Pg=class extends os{async _call(e){return new ye(await super._call(e))}},Ng=class extends os{async _call(e){return new q(await super._call(e))}},Lg=class extends os{async _call(e){return new we(await super._call(e))}},zg=class extends os{async _call(e){return new Me(await super._call(e))}};var va=class extends y{},$g=class extends va{},Rg=class extends va{};var ka=class extends y{},Bg=class extends ka{},Dg=class extends ka{};var Ea=class extends y{},Ug=class extends Ea{},Fg=class extends Ea{};var as=class extends y{},Gg=class extends as{},jg=class extends as{async _call(e){return new ye(await super._call(e))}},qg=class extends as{async _call(e){return new q(await super._call(e))}},Wg=class extends as{async _call(e){return new we(await super._call(e))}},Vg=class extends as{async _call(e){return new Me(await super._call(e))}};var o3=4299n,yM=6561n,dp=class extends y{forward_params=["input_ids","inputs_embeds","attention_mask","position_ids","audio_values","exaggeration","audio_features","audio_tokens","speaker_embeddings","speaker_features","past_key_values"];main_input_name="input_ids";_return_dict_in_generate_keys=["audio_tokens","speaker_embeddings","speaker_features"]},Aa=class extends dp{async encode_speech(e){return pe(this.sessions.speech_encoder,{audio_values:e})}async forward({input_ids:e=null,attention_mask:r=null,audio_values:s=null,exaggeration:n=null,position_ids:o=null,inputs_embeds:a=null,past_key_values:i=null,generation_config:l=null,logits_processor:c=null,num_logits_to_keep:u=null,audio_features:f=null,audio_tokens:m=null,speaker_embeddings:_=null,speaker_features:w=null,...x}){let b;if(!a){let k=this.sessions.embed_tokens.inputNames,M={input_ids:e};if(k.includes("exaggeration")){if(!(n instanceof $)){let S=e.dims[0];if(n==null)n=Ze([S],.5);else if(typeof n=="number")n=Ze([S],n);else if(Array.isArray(n))n=new $("float32",n,[S]);else throw new Error("Unsupported type for `exaggeration` input")}M.exaggeration=n}if(k.includes("position_ids")&&(M.position_ids=o),{inputs_embeds:a}=await pe(this.sessions.embed_tokens,M),f&&m&&_&&w&&(b={audio_features:f,audio_tokens:m,speaker_embeddings:_,speaker_features:w}),b||s)b??=await this.encode_speech(s),a=Ee([b.audio_features,a],1),r=st([a.dims[0],a.dims[1]]);else{let S=a.dims[1];if(!i||S!==1)throw new Error("Incorrect state encountered during generation.");let O=i.get_seq_length();r=st([a.dims[0],O+S])}}return{...await Nt(this,{inputs_embeds:a,past_key_values:i,attention_mask:r,generation_config:l,logits_processor:c,num_logits_to_keep:u},!1),...b}}prepare_inputs_for_generation(e,r,s){if(!r.position_ids&&this.sessions.embed_tokens.inputNames.includes("position_ids"))if(r.input_ids.dims[1]===1){let n=Array.from({length:e.length},(o,a)=>e[a].length-e[a].findLastIndex(i=>i==yM)-1);r.position_ids=new $("int64",n,[e.length,1])}else{let o=r.input_ids.tolist().map(a=>{let i=0;return a.map(l=>l>=yM?0:i++)});r.position_ids=new $("int64",o.flat(),r.input_ids.dims)}return r.input_ids.dims[1]===1&&(delete r.audio_values,delete r.audio_features,delete r.audio_tokens,delete r.speaker_embeddings,delete r.speaker_features),ns(this,e,r,s)}async generate(e){let r=e.past_key_values,{sequences:s,audio_tokens:n,speaker_embeddings:o,speaker_features:a,past_key_values:i}=await super.generate({...e,return_dict_in_generate:!0});try{let l=s.slice(null,[e.input_ids.dims[1],-1]),c=Ze([l.dims[0],3],o3),u=Ee([n,l,c],1),{waveform:f}=await pe(this.sessions.conditional_decoder,{speech_tokens:u,speaker_features:a,speaker_embeddings:o});return f}finally{i!==r&&await i?.dispose()}}};var mp=class extends y{},Hg=class extends mp{};var _p=class extends y{},Xg=class extends _p{};var eo=class extends y{},Kg=class extends eo{},Ta=class extends eo{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},Sa=class extends eo{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"audio_model"})}};var wr=class extends y{},Yg=class extends wr{},Qg=class extends wr{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},Ma=class extends wr{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},Jg=class extends wr{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"vision_model"})}},Zg=class extends wr{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"vision_model"})}};var Oa=class extends y{},ew=class extends Oa{},tw=class extends Oa{};var Ia=class extends y{},rw=class extends Ia{},sw=class extends Ia{};var Ca=class extends y{},nw=class extends Ca{},ow=class extends Ca{};var Pa=class extends y{},aw=class extends Pa{},iw=class extends Pa{};var Na=class extends y{requires_attention_mask=!1;main_input_name="input_features";forward_params=["input_features","decoder_input_ids","decoder_attention_mask","past_key_values"]},lw=class extends Na{},cw=class extends Na{};var is=class extends y{},uw=class extends is{},pw=class extends is{async _call(e){return new ye(await super._call(e))}},fw=class extends is{async _call(e){return new q(await super._call(e))}},dw=class extends is{async _call(e){return new we(await super._call(e))}},mw=class extends is{async _call(e){return new Me(await super._call(e))}};var La=class extends y{},_w=class extends La{},hw=class extends La{async _call(e){return new q(await super._call(e))}};var za=class extends y{},gw=class extends za{},ww=class extends za{async _call(e){return new q(await super._call(e))}};var $a=class extends y{},xw=class extends $a{},yw=class extends $a{async _call(e){return new xr(await super._call(e))}},xr=class extends Se{constructor({logits:e,pred_boxes:r}){super(),this.logits=e,this.pred_boxes=r}};var Ra=class extends y{},bw=class extends Ra{},vw=class extends Ra{async _call(e){return new xr(await super._call(e))}};var hp=class extends Se{constructor({audio_codes:e}){super(),this.audio_codes=e}},gp=class extends Se{constructor({audio_values:e}){super(),this.audio_values=e}},to=class extends y{main_input_name="input_values";forward_params=["input_values"]},kw=class extends to{async encode(e){return new hp(await pe(this.sessions.encoder_model,e))}async decode(e){return new gp(await pe(this.sessions.decoder_model,e))}},Ba=class extends to{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"encoder_model"})}},Da=class extends to{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"decoder_model"})}};var ls=class extends y{},Ew=class extends ls{},Aw=class extends ls{async _call(e){return new ye(await super._call(e))}},Tw=class extends ls{async _call(e){return new q(await super._call(e))}},Sw=class extends ls{async _call(e){return new we(await super._call(e))}},Mw=class extends ls{async _call(e){return new Me(await super._call(e))}};var Ua=class extends y{},Ow=class extends Ua{},Iw=class extends Ua{};var Fa=class extends y{},Cw=class extends Fa{},Pw=class extends Fa{};var cs=class extends y{},Nw=class extends cs{},Lw=class extends cs{async _call(e){return new ye(await super._call(e))}},zw=class extends cs{async _call(e){return new q(await super._call(e))}},$w=class extends cs{async _call(e){return new we(await super._call(e))}},Rw=class extends cs{async _call(e){return new Me(await super._call(e))}};var wp=class extends y{},Bw=class extends wp{};var Ga=class extends y{},Dw=class extends Ga{},Uw=class extends Ga{async _call(e){return new q(await super._call(e))}};var xp=class extends y{},Fw=class extends xp{};var yp=class extends y{},Gw=class extends yp{};var ro=class extends y{},jw=class extends ro{},qw=class extends ro{async _call(e){return new so(await super._call(e))}},Ww=class extends ro{async _call(e){return new bp(await super._call(e))}},so=class extends Se{constructor({logits:e,pred_boxes:r}){super(),this.logits=e,this.pred_boxes=r}},bp=class extends Se{constructor({logits:e,pred_boxes:r,pred_masks:s}){super(),this.logits=e,this.pred_boxes=r,this.pred_masks=s}};var ja=class extends y{},Vw=class extends ja{},Hw=class extends ja{async _call(e){return new q(await super._call(e))}};var qa=class extends y{},Xw=class extends qa{},Kw=class extends qa{async _call(e){return new q(await super._call(e))}};var vp=class extends y{},Yw=class extends vp{};var kp=class extends y{},Qw=class extends kp{};var us=class extends y{},Jw=class extends us{},Zw=class extends us{async _call(e){return new q(await super._call(e))}},ex=class extends us{async _call(e){return new we(await super._call(e))}},tx=class extends us{async _call(e){return new Me(await super._call(e))}},rx=class extends us{async _call(e){return new ye(await super._call(e))}};var Ep=class extends y{},sx=class extends Ep{};var Wa=class extends y{},nx=class extends Wa{},ox=class extends Wa{};var Va=class extends y{},ax=class extends Va{},ix=class extends Va{async _call(e){return new q(await super._call(e))}};var ps=class extends y{},lx=class extends ps{},cx=class extends ps{async _call(e){return new ye(await super._call(e))}},ux=class extends ps{async _call(e){return new q(await super._call(e))}},px=class extends ps{async _call(e){return new we(await super._call(e))}},fx=class extends ps{async _call(e){return new Me(await super._call(e))}};var Ap=class extends y{},Ha=class extends Ap{async forward({input_ids:e,attention_mask:r,pixel_values:s=null,image_position_ids:n=null,pixel_values_videos:o=null,video_position_ids:a=null,input_features:i=null,input_features_mask:l=null}){let c={image_features:s&&await this.encode_image({pixel_values:s,pixel_position_ids:n}),video_features:o&&await this.encode_image({pixel_values:o,pixel_position_ids:a}),audio_features:i&&await this.encode_audio({input_features:i,input_features_mask:l})},{image_token_id:u,video_token_id:f,audio_token_id:m,text_config:_}=this.config,w={image:u,video:f,audio:m};for(let[x,b]of Object.entries(w)){let A=`${x}_features`;c[A]??=new $("float32",new Float32Array(0),[0,_.hidden_size]);let k=0;for(let M of e.data)Number(M)===b&&++k;if(k!==c[A].dims[0])throw new Error(`The number of ${x} tokens (${k}) and ${x} features (${c[A].dims[0]}) do not match.`)}return await pe(this.sessions.model,{input_ids:e,attention_mask:r,...c})}};var Xa=class extends y{},dx=class extends Xa{},mx=class extends Xa{};var tn=class extends y{},_x=class extends tn{},hx=class extends tn{async _call(e){return new ye(await super._call(e))}},gx=class extends tn{async _call(e){return new q(await super._call(e))}},wx=class extends tn{async _call(e){return new we(await super._call(e))}};var rn=class extends y{},xx=class extends rn{},yx=class extends rn{async _call(e){return new ye(await super._call(e))}},bx=class extends rn{async _call(e){return new q(await super._call(e))}},vx=class extends rn{async _call(e){return new we(await super._call(e))}};var Ka=class extends y{},kx=class extends Ka{},Ex=class extends Ka{};var Ya=class extends y{},Ax=class extends Ya{},Tx=class extends Ya{};var Qa=class extends y{},Sx=class extends Qa{},Mx=class extends Qa{};var Ja=class extends y{},Ox=class extends Ja{},Ix=class extends Ja{async _call(e){return new q(await super._call(e))}};var Tp=class extends y{forward_params=["input_ids","inputs_embeds","attention_mask","pixel_values","encoder_outputs","decoder_input_ids","decoder_inputs_embeds","decoder_attention_mask","past_key_values"];main_input_name="inputs_embeds"},Cx=class extends Tp{_merge_input_ids_with_image_features({inputs_embeds:e,image_features:r,input_ids:s,attention_mask:n}){return{inputs_embeds:Ee([r,e],1),attention_mask:Ee([st(r.dims.slice(0,2)),n],1)}}async _prepare_inputs_embeds({input_ids:e,pixel_values:r,inputs_embeds:s,attention_mask:n}){if(!e&&!r)throw new Error("Either `input_ids` or `pixel_values` should be provided.");let o,a;return e&&(o=await this.encode_text({input_ids:e})),r&&(a=await this.encode_image({pixel_values:r})),o&&a?{inputs_embeds:s,attention_mask:n}=this._merge_input_ids_with_image_features({inputs_embeds:o,image_features:a,input_ids:e,attention_mask:n}):s=o||a,{inputs_embeds:s,attention_mask:n}}async forward({input_ids:e,pixel_values:r,attention_mask:s,decoder_input_ids:n,decoder_attention_mask:o,encoder_outputs:a,past_key_values:i,inputs_embeds:l,decoder_inputs_embeds:c,num_logits_to_keep:u=null}){if(l||({inputs_embeds:l,attention_mask:s}=await this._prepare_inputs_embeds({input_ids:e,pixel_values:r,inputs_embeds:l,attention_mask:s})),!a){let{last_hidden_state:m}=await Xt(this,{inputs_embeds:l,attention_mask:s});a=m}if(!c){if(!n)throw new Error("Either `decoder_input_ids` or `decoder_inputs_embeds` should be provided.");c=await this.encode_text({input_ids:n})}return await Nt(this,{inputs_embeds:c,attention_mask:o,encoder_attention_mask:s,encoder_hidden_states:a,past_key_values:i,num_logits_to_keep:u},!0)}};var Za=class extends y{},Px=class extends Za{},Nx=class extends Za{};var ei=class extends y{},Lx=class extends ei{},zx=class extends ei{};var Sp=class extends y{forward_params=["input_ids","attention_mask","pixel_values","position_ids","past_key_values"]},ut=class extends Sp{_merge_input_ids_with_image_features(e){let r=e.image_features.dims.at(-1),s=e.image_features.view(-1,r);return Jn({image_token_id:this.config.image_token_index??this.config.image_token_id,...e,image_features:s})}},$x=class extends ut{},Rx=class extends ut{};var Mp=class extends y{},Bx=class extends Mp{},Op=class extends ut{},Dx=class extends Op{};var Ip=class extends y{forward_params=["input_ids","attention_mask","inputs_embeds","per_layer_inputs","position_ids","pixel_values","input_features","input_features_mask","past_key_values"]},fs=class extends Ip{async forward({input_ids:e=null,attention_mask:r=null,pixel_values:s=null,input_features:n=null,input_features_mask:o=null,position_ids:a=null,inputs_embeds:i=null,per_layer_inputs:l=null,past_key_values:c=null,generation_config:u=null,logits_processor:f=null,num_logits_to_keep:m=null,..._}){if((!i||!l)&&({inputs_embeds:i,per_layer_inputs:l}=await pe(this.sessions.embed_tokens,{input_ids:e}),e.dims[1]!==1)){if(s){let{image_features:x}=await this._encode_vision({pixel_values:s,..._});({inputs_embeds:i,attention_mask:r}=this._merge_input_ids_with_image_features({image_features:x,inputs_embeds:i,input_ids:e,attention_mask:r}))}if(n){let{audio_features:x}=await pe(this.sessions.audio_encoder,{input_features:n,input_features_mask:o});({inputs_embeds:i,attention_mask:r}=this._merge_input_ids_with_audio_features({audio_features:x,inputs_embeds:i,input_ids:e,attention_mask:r}))}}return await Nt(this,{inputs_embeds:i,per_layer_inputs:l,past_key_values:c,attention_mask:r,position_ids:a,generation_config:u,logits_processor:f,num_logits_to_keep:m},!0)}_encode_vision(e){return pe(this.sessions.vision_encoder,{pixel_values:e.pixel_values})}_merge_input_ids_with_image_features(e){let r=e.image_features.dims.at(-1),s=e.image_features.view(-1,r);return Jn({image_token_id:this.config.image_token_id,...e,image_features:s})}_merge_input_ids_with_audio_features(e){let r=e.audio_features.dims.at(-1),s=e.audio_features.view(-1,r);return fp({audio_token_id:this.config.audio_token_id,...e,audio_features:s})}},Ux=class extends fs{};var no=class extends fs{forward_params=["input_ids","attention_mask","inputs_embeds","per_layer_inputs","position_ids","pixel_values","image_position_ids","input_features","input_features_mask","past_key_values"];_encode_vision(e){return pe(this.sessions.vision_encoder,{pixel_values:e.pixel_values,pixel_position_ids:e.image_position_ids})}},Fx=class extends no{};var ti=class extends y{},Gx=class extends ti{},jx=class extends ti{};var ri=class extends y{},qx=class extends ri{},Wx=class extends ri{};var Cp=class extends y{forward_params=["input_ids","attention_mask","position_ids","past_key_values","pixel_values","image_grid_thw"]},oo=class extends Cp{image_grid_thw_name="grid_thw";_get_text_only_rope_index(e,r){if(r){let{data:s,dims:n}=dg(r),o=BigInt64Array.from({length:3*s.length},(i,l)=>s[l%s.length]),a=Array.from({length:n[0]},(i,l)=>Le(s.subarray(n[1]*l,n[1]*(l+1)))[0]+1n+BigInt(n[1]));return[new $("int64",o,[3,...n]),new $("int64",a,[a.length,1])]}else{let[s,n]=e.dims,o=BigInt64Array.from({length:3*s*n},(a,i)=>BigInt(Math.floor(i%n/s)));return[new $("int64",o,[3,...e.dims]),Am([s,1])]}}_reorder_and_write_positions(e,r,s,n){let o=e.reduce((c,u)=>c+u.length,0),a=new Array(o),i=0;for(let c=0;c<3;++c)for(let u of e){let f=u.length/3;for(let m=c*f;m<(c+1)*f;++m)a[i++]=u[m]}let l=0;for(let c=0;c(M==l&&k.push(S),k),[]).map(k=>c[k+1]),m=f.filter(k=>k==a).length,_=f.filter(k=>k==i).length,w=[],x=0,b=m,A=_;for(let k=0;kG>x&&z==a),S=c.findIndex((z,G)=>G>x&&z==i),O=b>0&&M!==-1?M:c.length+1,C=A>0&&S!==-1?S:c.length+1,v,U,j,F;O0?Le(w.at(-1))[0]+1:0;w.push(Array.from({length:3*B},(z,G)=>I+G%B));let oe=B+I,J=K*Y*Q,Z=Array.from({length:J},(z,G)=>oe+Math.floor(G/(Y*Q))),me=Array.from({length:J},(z,G)=>oe+Math.floor(G/Q)%Y),L=Array.from({length:J},(z,G)=>oe+G%Q);w.push([Z,me,L].flat()),x=v+J}if(x0?Le(w.at(-1))[0]+1:0,M=c.length-x;w.push(Array.from({length:3*M},(S,O)=>k+O%M))}return w}get_rope_index(e,r,s,n){let{vision_config:o}=this.config,a=o.spatial_merge_size??2;if(r||s){let i=e.tolist();n||(n=Ln(e));let l=n.tolist(),c=Array.from({length:3},()=>Array.from({length:e.dims[0]},()=>Array.from({length:e.dims[1]},()=>0))),u=r?r.tolist():[],f=s?s.tolist():[],m={image_index:0,video_index:0},_=[];for(let w=0;wl[w][M]==1),b=this._get_multimodal_rope_positions({filtered_ids:x,image_grid_thw_list:u,video_grid_thw_list:f,spatial_merge_size:a,state:m}),A=this._reorder_and_write_positions(b,l[w],c,w);_.push(Le(A)[0]+1-i[w].length)}return[new $("int64",c.flat(1/0),[3,e.dims[0],e.dims[1]]),new $("int64",_,[_.length,1])]}else return this._get_text_only_rope_index(e,n)}async encode_image({pixel_values:e,image_grid_thw:r}){return(await pe(this.sessions.vision_encoder,{pixel_values:e,[this.image_grid_thw_name]:r})).image_features}_merge_input_ids_with_image_features(e){return Jn({image_token_id:this.config.image_token_id,...e})}prepare_inputs_for_generation(e,r,s){if(Zs(this,r,1n),!r.attention_mask||r.position_ids||!(this.sessions.decoder_model_merged??this.sessions.model).inputNames.includes("position_ids"))return r;if(!r.past_key_values)[r.position_ids,r.rope_deltas]=this.get_rope_index(r.input_ids,r.image_grid_thw,r.video_grid_thw,r.attention_mask);else{r.pixel_values=null;let o=r.past_key_values.get_seq_length();if(oa+l);r.position_ids=kt([i,i,i],0)}}return r}},si=class extends oo{};var sn=class extends oo{image_grid_thw_name="image_grid_thw"},ni=class extends si{image_grid_thw_name="image_grid_thw"};var Vx=class extends sn{get_vision_position_ids(e,r,s,n){let o=Math.floor(r[0]/s),a=Math.floor(r[1]/n),i=Math.floor(r[2]/n),l=a*i*o,c=Array.from({length:l},()=>e),u=Array.from({length:l},(m,_)=>e+Math.floor(_/(i*o))),f=Array.from({length:l},(m,_)=>e+_%i);return[...c,...u,...f]}_get_multimodal_rope_positions({filtered_ids:e,image_grid_thw_list:r,video_grid_thw_list:s,spatial_merge_size:n,state:o}){let{image_token_id:a}=this.config,i=[],l=0,c=e[0]==a?1:0;for(let m=1;m<=e.length;++m){let _=mu+A%x)),u+=x}else{let x=r[o.image_index++].map(Number),b=x[0];f.push(this.get_vision_position_ids(u,x,b,n)),u+=Math.max(x[1],x[2])/n}return f}};var oi=class extends y{},Hx=class extends oi{},Xx=class extends oi{};var ai=class extends y{},Kx=class extends ai{},Yx=class extends ai{};var ii=class extends y{},Qx=class extends ii{},Jx=class extends ii{};var li=class extends y{},Zx=class extends li{},ey=class extends li{};var ci=class extends y{},ty=class extends ci{},ry=class extends ci{};var ui=class extends y{},sy=class extends ui{},ny=class extends ui{};var pi=class extends y{},oy=class extends pi{},ay=class extends pi{};var fi=class extends y{},iy=class extends fi{},ly=class extends fi{};var di=class extends y{},cy=class extends di{},uy=class extends di{};var Pp=class extends y{forward_params=["input_ids","attention_mask","position_ids","audio_values","past_key_values"]},nn=class extends Pp{_merge_input_ids_with_audio_features(e){let r=e.audio_features.dims.at(-1),s=e.audio_features.view(-1,r);return fp({audio_token_id:this.config.ignore_index??this.config.audio_token_id??this.config.audio_token_index,...e,audio_features:s})}};var py=class extends nn{forward_params=["input_ids","attention_mask","input_features","past_key_values"]};var Np=class extends y{},fy=class extends Np{};var Lp=class extends y{},dy=class extends Lp{};var mi=class extends y{},my=class extends mi{},_y=class extends mi{};var _i=class extends y{},hy=class extends _i{},gy=class extends _i{async _call(e){return new q(await super._call(e))}};var hi=class extends y{},wy=class extends hi{},xy=class extends hi{forward_params=["input_ids","attention_mask","token_type_ids","past_key_values"];prepare_inputs_for_generation(e,r,s){let n=ns(this,e,r,s);return n.token_type_ids=(n.past_key_values?Yo:Ln)(n.input_ids),n}};var ir=class extends y{},yy=class extends ir{},by=class extends ir{async _call(e){return new ht(await super._call(e))}},vy=class extends ir{async _call(e){return new q(await super._call(e))}},ky=class extends ir{async _call(e){return new we(await super._call(e))}};var Ey=class extends y{},Ay=class extends ir{},Ty=class extends ir{async _call(e){return new ht(await super._call(e))}},Sy=class extends ir{async _call(e){return new q(await super._call(e))}};var gi=class extends y{},My=class extends gi{},Oy=class extends gi{};var wi=class extends ut{forward_params=["input_ids","attention_mask","pixel_values","pixel_attention_mask","position_ids","past_key_values"]};var xi=class extends y{},Iy=class extends xi{},Cy=class extends xi{async _call(e){return new q(await super._call(e))}};var yi=class extends y{},Py=class extends yi{},Ny=class extends yi{};var ao=class extends y{},Ly=class extends ao{async forward(e){let r=!e.input_ids,s=!e.pixel_values;if(r&&s)throw new Error("Either `input_ids` or `pixel_values` should be provided.");if(r&&(e.input_ids=st([e.pixel_values.dims[0],1])),s){let{image_size:c}=this.config.vision_config;e.pixel_values=Ze([0,3,c,c],0)}let{text_embeddings:n,image_embeddings:o,l2norm_text_embeddings:a,l2norm_image_embeddings:i}=await super.forward(e),l={};return r||(l.text_embeddings=n,l.l2norm_text_embeddings=a),s||(l.image_embeddings=o,l.l2norm_image_embeddings=i),l}},bi=class extends ao{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},zy=class extends ao{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"vision_model"})}};var vi=class extends y{},$y=class extends vi{},Ry=class extends vi{};var By=class extends ut{};var ki=class extends y{},Dy=class extends ki{},Uy=class extends ki{};var Fy=class extends ut{forward_params=["input_ids","attention_mask","pixel_values","pixel_attention_mask","spatial_shapes","position_ids","past_key_values"]};var Ei=class extends y{},Gy=class extends Ei{},jy=class extends Ei{};var qy=class extends ut{forward_params=["input_ids","attention_mask","pixel_values","image_grid_thw","position_ids","past_key_values"]};var Ai=class extends y{},Wy=class extends Ai{},Vy=class extends Ai{};var zp=class extends y{},Hy=class extends zp{};var Ti=class extends y{},Xy=class extends Ti{},Ky=class extends Ti{};var Si=class extends y{},Yy=class extends Si{},Qy=class extends Si{};var Mi=class extends y{},Jy=class extends Mi{},Zy=class extends Mi{};var Oi=class extends y{},e0=class extends Oi{},t0=class extends Oi{};var on=class extends y{},r0=class extends on{},s0=class extends on{},n0=class extends on{async _call(e){return new q(await super._call(e))}},o0=class extends on{};var $p=class extends y{},a0=class extends $p{};var Rp=class extends y{},i0=class extends Rp{};var Bp=class extends Se{constructor({char_logits:e,bpe_logits:r,wp_logits:s}){super(),this.char_logits=e,this.bpe_logits=r,this.wp_logits=s}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}},Dp=class extends y{},l0=class extends Dp{async _call(e){return new Bp(await super._call(e))}};var Up=class extends Se{constructor({audio_codes:e}){super(),this.audio_codes=e}},Fp=class extends Se{constructor({audio_values:e}){super(),this.audio_values=e}},io=class extends y{main_input_name="input_values";forward_params=["input_values"]},c0=class extends io{async encode(e){return new Up(await pe(this.sessions.encoder_model,e))}async decode(e){return new Fp(await pe(this.sessions.decoder_model,e))}},Ii=class extends io{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"encoder_model"})}},Ci=class extends io{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"decoder_model"})}};var Pi=class extends y{},u0=class extends Pi{},p0=class extends Pi{};var Ni=class extends y{},f0=class extends Ni{},d0=class extends Ni{};var Li=class extends y{},m0=class extends Li{},_0=class extends Li{};var h0=class extends ut{};var zi=class extends y{},g0=class extends zi{},w0=class extends zi{};var an=class extends y{},x0=class extends an{},y0=class extends an{async _call(e){return new ye(await super._call(e))}},b0=class extends an{async _call(e){return new q(await super._call(e))}},v0=class extends an{async _call(e){return new Me(await super._call(e))}};var $i=class extends y{},k0=class extends $i{},E0=class extends $i{};var lo=class extends y{},A0=class extends lo{},T0=class extends lo{async _call(e){return new q(await super._call(e))}},S0=class extends lo{};var co=class extends y{},M0=class extends co{},O0=class extends co{async _call(e){return new q(await super._call(e))}},I0=class extends co{};var uo=class extends y{},C0=class extends uo{},P0=class extends uo{async _call(e){return new q(await super._call(e))}},N0=class extends uo{};var po=class extends y{},L0=class extends po{},z0=class extends po{async _call(e){return new q(await super._call(e))}},$0=class extends po{};var Ri=class extends y{},R0=class extends Ri{},B0=class extends Ri{async _call(e){return new q(await super._call(e))}};var Bi=class extends y{},D0=class extends Bi{},U0=class extends Bi{async _call(e){return new q(await super._call(e))}};var ln=class extends y{},F0=class extends ln{},G0=class extends ln{async _call(e){return new ye(await super._call(e))}},j0=class extends ln{async _call(e){return new q(await super._call(e))}},q0=class extends ln{async _call(e){return new we(await super._call(e))}};var Di=class extends y{},W0=class extends Di{},V0=class extends Di{};var Ui=class extends y{requires_attention_mask=!1;main_input_name="input_values";forward_params=["input_values","decoder_input_ids","past_key_values"]},H0=class extends Ui{},X0=class extends Ui{};var ds=class extends y{},K0=class extends ds{},Y0=class extends ds{async _call(e){return new ye(await super._call(e))}},Q0=class extends ds{async _call(e){return new q(await super._call(e))}},J0=class extends ds{async _call(e){return new we(await super._call(e))}},Z0=class extends ds{async _call(e){return new Me(await super._call(e))}};var Fi=class extends y{},eb=class extends Fi{},tb=class extends Fi{};var Gi=class extends y{},rb=class extends Gi{},sb=class extends Gi{};var Gp=class extends y{},nb=class extends Gp{forward_params=["input_ids","pixel_values","images_seq_mask","images_emb_mask","attention_mask","position_ids","past_key_values"];constructor(...e){super(...e),this._generation_mode="text"}async forward(e){let r=this._generation_mode??"text",s;if(r==="text"||!e.past_key_values){let l=this.sessions.prepare_inputs_embeds,c=He(e,l.inputNames);s=await pe(l,c)}else{let l=this.sessions.gen_img_embeds,c=He({image_ids:e.input_ids},l.inputNames);s=await pe(l,c)}let n={...e,...s},o=await Nt(this,n),a=this.sessions[r==="text"?"lm_head":"gen_head"];if(!a)throw new Error(`Unable to find "${a}" generation head`);let i=await pe(a,He(o,a.inputNames));return{...s,...o,...i}}prepare_inputs_for_generation(e,r,s){let n=!!r.past_key_values;return Zs(this,r,1n),s.guidance_scale!==null&&s.guidance_scale>1&&(n?r.input_ids=Ee([r.input_ids,r.input_ids],0):(r.input_ids=Ee([r.input_ids,Ko(r.input_ids,BigInt(s.pad_token_id))],0),r.attention_mask=Ee([r.attention_mask,Ko(r.attention_mask,0n)],0))),(n||!r.pixel_values)&&(r.pixel_values=Ze([0,0,3,384,384],1)),n&&(r.images_seq_mask=new $("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),r.images_emb_mask=new $("bool",new Array(0).fill(!1),[1,1,0])),r}async generate(e){return this._generation_mode="text",super.generate(e)}async generate_images(e){this._generation_mode="image";let r=(e.inputs??e[this.main_input_name]).dims[1],n=(await super.generate(e)).slice(null,[r,null]),o=this.sessions.image_decode,{decoded_image:a}=await pe(o,{generated_tokens:n}),i=a.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),l=[];for(let c of i){let u=rt.fromTensor(c);l.push(u)}return l}};var ji=class extends y{},ob=class extends ji{},ab=class extends ji{},qi=class extends y{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"];_apply_and_filter_by_delay_pattern_mask(e){let[r,s]=e.dims,n=this.config.decoder.num_codebooks,o=s-n,a=0;for(let c=0;c0&&m<=o&&(e.data[a++]=e.data[c])}let i=Math.floor(r/n),l=a/(i*n);return new $(e.type,e.data.slice(0,a),[i,n,l])}prepare_inputs_for_generation(e,r,s){let n=BigInt(this.config.decoder.pad_token_id),o=structuredClone(e);for(let a=0;a=i&&(o[a][i]=n);return s.guidance_scale!==null&&s.guidance_scale>1&&(o=o.concat(o)),_a(this,o,r,s)}async generate(e){let r=await super.generate(e),s=this._apply_and_filter_by_delay_pattern_mask(r).unsqueeze_(0),{audio_values:n}=await pe(this.sessions.encodec_decode,{audio_codes:s});return n}};var Wi=class extends y{},ib=class extends Wi{},lb=class extends Wi{};var Vi=class extends y{},cb=class extends Vi{},ub=class extends Vi{};var ms=class extends y{},pb=class extends ms{},fb=class extends ms{async _call(e){return new ye(await super._call(e))}},db=class extends ms{async _call(e){return new q(await super._call(e))}},mb=class extends ms{async _call(e){return new we(await super._call(e))}},_b=class extends ms{async _call(e){return new Me(await super._call(e))}};var jp=class extends y{},hb=class extends jp{};var Hi=class extends y{},gb=class extends Hi{},wb=class extends Hi{};var Xi=class extends y{},xb=class extends Xi{},yb=class extends Xi{};var Ki=class extends y{},bb=class extends Ki{},vb=class extends Ki{};var Yi=class extends y{},kb=class extends Yi{},Eb=class extends Yi{};var Qi=class extends y{},Ab=class extends Qi{},Tb=class extends Qi{async _call(e){return new q(await super._call(e))}};var Ji=class extends y{},Sb=class extends Ji{},Mb=class extends Ji{};var Zi=class extends y{},Ob=class extends Zi{},Ib=class extends Zi{};var el=class extends y{},Cb=class extends el{},Pb=class extends el{};var tl=class extends y{},Nb=class extends tl{},Lb=class extends tl{};var zb=class extends ut{};var qp=class extends y{},$b=class extends qp{async _call(e){return new ht(await super._call(e))}};var rl=class extends y{},Rb=class extends rl{},Bb=class extends rl{};var sl=class extends y{},Db=class extends sl{},Ub=class extends sl{};var nl=class extends y{},Fb=class extends nl{},Gb=class extends nl{};var ol=class extends y{},jb=class extends ol{},qb=class extends ol{};var Wp=class extends y{forward_params=["input_ids","inputs_embeds","attention_mask","position_ids","pixel_values","image_sizes","past_key_values"]},al=class extends Wp{async forward({input_ids:e=null,attention_mask:r=null,pixel_values:s=null,image_sizes:n=null,position_ids:o=null,inputs_embeds:a=null,past_key_values:i=null,generation_config:l=null,logits_processor:c=null,num_logits_to_keep:u=null,...f}){if(!a){let _;if(s&&e.dims[1]!==1){if(!n)throw new Error("`image_sizes` must be provided when `pixel_values` is provided.");({image_features:_}=await pe(this.sessions.vision_encoder,{pixel_values:s,image_sizes:n}))}else{let w=this.config.normalized_config.hidden_size;_=new $("float32",[],[0,w])}({inputs_embeds:a}=await pe(this.sessions.prepare_inputs_embeds,{input_ids:e,image_features:_}))}return await Nt(this,{inputs_embeds:a,past_key_values:i,attention_mask:r,position_ids:o,generation_config:l,logits_processor:c,num_logits_to_keep:u},!1)}};var il=class extends y{},Wb=class extends il{},Vb=class extends il{async _call(e){return new q(await super._call(e))}};var ll=class extends y{},Hb=class extends ll{},Xb=class extends ll{async _call(e){return new we(await super._call(e))}};var cl=class extends y{},Kb=class extends cl{},Yb=class extends cl{};var ul=class extends y{},Qb=class extends ul{},Jb=class extends ul{};var pl=class extends y{},Zb=class extends pl{},e1=class extends pl{};var fl=class extends y{},t1=class extends fl{},r1=class extends fl{};var dl=class extends y{},s1=class extends dl{},n1=class extends dl{};var cn=class extends sn{},ml=class extends ni{};var o1=class extends cn{},a1=class extends ml{};var fo=class extends cn{},_l=class extends fo{};var i1=class extends fo{},l1=class extends _l{};var hl=class extends y{},c1=class extends hl{},u1=class extends hl{async _call(e){return new q(await super._call(e))}};var gl=class extends y{},p1=class extends gl{},f1=class extends gl{async _call(e){return new Vp(await super._call(e))}},Vp=class extends xr{};var _s=class extends y{},d1=class extends _s{},m1=class extends _s{async _call(e){return new ye(await super._call(e))}},_1=class extends _s{async _call(e){return new q(await super._call(e))}},h1=class extends _s{async _call(e){return new we(await super._call(e))}},g1=class extends _s{async _call(e){return new Me(await super._call(e))}};var hs=class extends y{},w1=class extends hs{},x1=class extends hs{async _call(e){return new ye(await super._call(e))}},y1=class extends hs{async _call(e){return new q(await super._call(e))}},b1=class extends hs{async _call(e){return new we(await super._call(e))}},v1=class extends hs{async _call(e){return new Me(await super._call(e))}};var wl=class extends y{},k1=class extends wl{},E1=class extends wl{async _call(e){return new Hp(await super._call(e))}},Hp=class extends xr{};var Xp=class extends Se{constructor({iou_scores:e,pred_masks:r}){super(),this.iou_scores=e,this.pred_masks=r}},Kp=class extends y{},A1=class extends Kp{async get_image_embeddings({pixel_values:e}){return await Xt(this,{pixel_values:e})}async forward(e){!e.image_embeddings||!e.image_positional_embeddings?e={...e,...await this.get_image_embeddings(e)}:e={...e},e.input_labels??=st(e.input_points.dims.slice(0,-1));let r={image_embeddings:e.image_embeddings,image_positional_embeddings:e.image_positional_embeddings};return e.input_points&&(r.input_points=e.input_points),e.input_labels&&(r.input_labels=e.input_labels),e.input_boxes&&(r.input_boxes=e.input_boxes),await pe(this.sessions.prompt_encoder_mask_decoder,r)}async _call(e){return new Xp(await super._call(e))}};var Yp=class extends Se{constructor({iou_scores:e,pred_masks:r,object_score_logits:s}){super(),this.iou_scores=e,this.pred_masks=r,this.object_score_logits=s}},Qp=class extends y{},xl=class extends Qp{async get_image_embeddings({pixel_values:e}){return await Xt(this,{pixel_values:e})}async forward(e){let{num_feature_levels:r}=this.config.vision_config;if(Array.from({length:r},(a,i)=>`image_embeddings.${i}`).some(a=>!e[a])?e={...e,...await this.get_image_embeddings(e)}:e={...e},e.input_points){if(e.input_boxes&&e.input_boxes.dims[1]!==1)throw new Error("When both `input_points` and `input_boxes` are provided, the number of boxes per image must be 1.");let a=e.input_points.dims;e.input_labels??=st(a.slice(0,-1)),e.input_boxes??=Ze([a[0],0,4],0)}else if(e.input_boxes){let a=e.input_boxes.dims;e.input_labels=Ze([a[0],a[1],0],-1n),e.input_points=Ze([a[0],1,0,2],0)}else throw new Error("At least one of `input_points` or `input_boxes` must be provided.");let n=this.sessions.prompt_encoder_mask_decoder,o=He(e,n.inputNames);return await pe(n,o)}async _call(e){return new Yp(await super._call(e))}},T1=class extends xl{},S1=class extends xl{};var mo=class extends y{},M1=class extends mo{},O1=class extends mo{},I1=class extends mo{};var _o=class extends y{},C1=class extends _o{},P1=class extends _o{},N1=class extends _o{};var yl=class extends y{},L1=class extends yl{},bl=class extends yl{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},z1=class extends wr{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"vision_model"})}};var vl=class extends y{},$1=class extends vl{},R1=class extends vl{};var B1=class extends wi{};var ho=class extends y{main_input_name="input_values";forward_params=["input_values"]},D1=class extends ho{async encode(e){return await pe(this.sessions.encoder_model,e)}async decode(e){return await pe(this.sessions.decoder_model,e)}},kl=class extends ho{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"encoder_model"})}},El=class extends ho{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"decoder_model"})}};var Al=class extends y{},U1=class extends Al{},F1=class extends Al{};var go=class extends y{},G1=class extends go{},j1=class extends go{},q1=class extends go{async generate_speech(e,r,{threshold:s=.5,minlenratio:n=0,maxlenratio:o=20,vocoder:a=null}={}){let i={input_ids:e},{encoder_outputs:l,encoder_attention_mask:c}=await Xt(this,i),u=l.dims[1]/this.config.reduction_factor,f=Math.floor(u*o),m=Math.floor(u*n),_=this.config.num_mel_bins,w=[],x=null,b=null,A=0;for(;;){++A;let S=pg(!!b),O;b?O=b.output_sequence_out:O=new $("float32",new Float32Array(_),[1,1,_]);let C={use_cache_branch:S,output_sequence:O,encoder_attention_mask:c,speaker_embeddings:r,encoder_hidden_states:l};ha(this,C,x),b=await pe(this.sessions.decoder_model_merged,C),x=up(b,x);let{prob:v,spectrum:U}=b;if(w.push(U),A>=m&&(Array.from(v.data).filter(j=>j>=s).length>0||A>=f))break}let k=Ee(w),{waveform:M}=await pe(a.sessions.model,{spectrogram:k});return{spectrogram:k,waveform:M}}},W1=class extends y{main_input_name="spectrogram"};var un=class extends y{},V1=class extends un{},H1=class extends un{async _call(e){return new ye(await super._call(e))}},X1=class extends un{async _call(e){return new q(await super._call(e))}},K1=class extends un{async _call(e){return new Me(await super._call(e))}};var Tl=class extends y{},Y1=class extends Tl{},Q1=class extends Tl{};var Sl=class extends y{},J1=class extends Sl{},Z1=class extends Sl{};var Jp=class extends y{},ev=class extends Jp{};var Zp=class extends y{},Ml=class extends Zp{async generate_speech({input_ids:e,attention_mask:r,style:s,num_inference_steps:n=5,speed:o=1.05}){let{sampling_rate:a,chunk_compress_factor:i,base_chunk_size:l,latent_dim:c}=this.config,{last_hidden_state:u,durations:f}=await pe(this.sessions.text_encoder,{input_ids:e,attention_mask:r,style:s}),m=f.div(o).mul_(a),_=l*i,w=m.data,x=Int32Array.from(w,F=>Math.ceil(F/_)),b=Math.max(...x),A=e.dims[0],k=new BigInt64Array(A*b);for(let F=0;FM*S,1),k=Zr[x.type];l[x.name]=new $(x.type,new k(A),b)}let m=Zr[f],_=new $(f,new m(i*bM),[1,i,bM]),w=e[Symbol.asyncIterator]?.()??e[Symbol.iterator]?.();if(!w)throw new Error("input_features must be iterable or async iterable");return{encoder_session:n,enc_kv_cache:l,enc_padding_cache:_,enc_past_seq_len:0,audio_embed_queue:[],audio_embed_total_tokens:0,audio_queue_offset:0,audio_consumed:0,stream_exhausted:!1,chunks_iter:w,text_hidden_size:r.hidden_size}}async function l3(t,e){let r=e.dims[2],s=Math.floor((a3+r-3)/2)+1,n=new $("int64",BigInt64Array.from({length:s},(u,f)=>BigInt(t.enc_past_seq_len+f)),[1,s]),o=t.enc_past_seq_len+s,a=st([1,o]),{audio_embeds:i,present_padding_cache:l,...c}=await pe(t.encoder_session,{input_features:e,attention_mask:a,position_ids:n,past_padding_cache:t.enc_padding_cache,...t.enc_kv_cache});t.enc_padding_cache.location==="gpu-buffer"&&t.enc_padding_cache.dispose(),t.enc_padding_cache=l;for(let u in c)if(u.startsWith("present.")){let f=u.replace("present","past_key_values"),m=t.enc_kv_cache[f];m?.location==="gpu-buffer"&&m.dispose(),t.enc_kv_cache[f]=c[u]}return t.enc_past_seq_len=o,i}async function c3(t,e){for(;t.audio_embed_total_tokens0&&t.audio_embed_queue.length>0;){let a=t.audio_embed_queue[0],i=a.tokens-t.audio_queue_offset,l=Math.min(o,i),c=t.audio_queue_offset*t.text_hidden_size;for(let u=0;u=a.tokens&&(t.audio_embed_queue.shift(),t.audio_queue_offset=0)}t.audio_consumed+=r-o}var Cv=class extends ss{constructor(e){super(),this._s=e}_call(e){let r=this._s.stream_exhausted&&this._s.audio_embed_queue.length===0;return e.map(()=>r)}},lf=class extends y{forward_params=["input_ids","attention_mask","position_ids","past_key_values"]},zl=class extends lf{async forward({input_ids:e,past_key_values:r,...s}){let n=e.dims[1],o=Iv.get(this);o&&await c3(o,o.audio_consumed+n);let{inputs_embeds:a}=await pe(this.sessions.embed_tokens,{input_ids:e});o&&u3(o,a,n);let i={inputs_embeds:a,...s};ha(this,i,r);let l=this.sessions.decoder_model_merged,c=He(i,l.inputNames);return await pe(l,c)}async generate({input_features:e,stopping_criteria:r,...s}){if(!e)throw new Error("input_features (generator/iterable) must be provided");let n=i3(this,e);Iv.set(this,n);let o=new Xn;o.push(new Cv(n)),r&&o.extend(r);try{return await super.generate({...s,stopping_criteria:o})}finally{n.enc_kv_cache.dispose(),Iv.delete(this)}}};var yo=class extends y{},Pv=class extends yo{},Nv=class extends yo{async _call(e){return new ht(await super._call(e))}},Lv=class extends yo{async _call(e){return new q(await super._call(e))}};var cf=class extends Se{constructor({logits:e,embeddings:r}){super(),this.logits=e,this.embeddings=r}},gs=class extends y{},zv=class extends gs{},$v=class extends gs{async _call(e){return new ht(await super._call(e))}},Rv=class extends gs{async _call(e){return new q(await super._call(e))}},Bv=class extends gs{async _call(e){return new cf(await super._call(e))}},Dv=class extends gs{async _call(e){return new we(await super._call(e))}};var uf=class extends y{},Uv=class extends uf{};var pf=class extends Ks{return_timestamps=null;return_token_timestamps=null;num_frames=null;alignment_heads=null;task=null;language=null;no_timestamps_token_id=null;prompt_ids=null;is_multilingual=null;lang_to_id=null;task_to_id=null;max_initial_timestamp_index=1};var $l=class extends y{requires_attention_mask=!1;main_input_name="input_features";forward_params=["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"]},Fv=class extends $l{},ff=class extends $l{_prepare_generation_config(e,r){return super._prepare_generation_config(e,r,pf)}_retrieve_init_tokens(e){let r=[e.decoder_start_token_id],s=e.language,n=e.task;if(e.is_multilingual){s||(te.warn("No language specified - defaulting to English (en)."),s="en");let a=`<|${WS(s)}|>`;r.push(e.lang_to_id[a]),r.push(e.task_to_id[n??"transcribe"])}else if(s||n)throw new Error("Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config.");return!e.return_timestamps&&e.no_timestamps_token_id&&r.at(-1)!==e.no_timestamps_token_id?r.push(e.no_timestamps_token_id):e.return_timestamps&&r.at(-1)===e.no_timestamps_token_id&&(te.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),r.pop()),r.filter(o=>o!=null)}async generate({inputs:e=null,generation_config:r=null,logits_processor:s=null,stopping_criteria:n=null,...o}){r=this._prepare_generation_config(r,o);let a=o.decoder_input_ids instanceof $?Qo(o.decoder_input_ids):o.decoder_input_ids??this._retrieve_init_tokens(r);if(r.return_timestamps&&(s??=new Xs,s.push(new Qu(r,a))),r.begin_suppress_tokens&&(s??=new Xs,s.push(new Hn(r.begin_suppress_tokens,a.length))),r.return_token_timestamps){if(!r.alignment_heads)throw new Error("Model generation config has no `alignment_heads`, token-level timestamps not available. See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config.");r.task==="translate"&&te.warn("Token-level timestamps may not be reliable for task 'translate'."),r.output_attentions=!0,r.return_dict_in_generate=!0}if(r.return_timestamps&&!o.max_new_tokens)return this._generate_with_seek({inputs:e,generation_config:r,logits_processor:s,init_tokens:a,kwargs:o});let i=await super.generate({inputs:e,generation_config:r,logits_processor:s,decoder_input_ids:a,...o});return r.return_token_timestamps&&(i.token_timestamps=this._extract_token_timestamps(i,r.alignment_heads,r.num_frames,.02,a.length)),i}async _generate_with_seek({inputs:e,generation_config:r,logits_processor:s,init_tokens:n,kwargs:o}){let a=r.no_timestamps_token_id+1,i=Array.isArray(r.eos_token_id)?r.eos_token_id[0]:r.eos_token_id,l=r.return_token_timestamps,c=e,u=c.dims[2],f=2,m=this.config.max_source_positions,_=f*m,w=0,x=[],b=[];for(;wZ+J)}if(U.length>0&&U.at(-1)===i&&U.pop(),U.length===0)break;let F=U.map(J=>J>=a),K=U.length>=2&&F[U.length-1]&&!F[U.length-2],Y=[];for(let J=0;J0)if(K)Q=k-w;else{let J=Y.at(-1);Q=(U[J-1]-a)*f,B=J}else Q=k-w;let I=Math.floor(w/f),oe=a+1500;for(let J=0;J=a&&(U[J]=Math.min(U[J]+I,oe));x.push(...U.slice(0,B)),j&&b.push(...j.slice(0,B)),w+=Q}x.push(i);let A=[...n,...x];if(l){let k=new $("int64",A.map(BigInt),[1,A.length]),M=[...new Array(n.length).fill(0),...b,0],S=new $("float32",new Float32Array(M),[1,M.length]);return{sequences:k,token_timestamps:S}}return new $("int64",A.map(BigInt),[1,A.length])}_extract_token_timestamps(e,r,s=null,n=.02,o=0){if(!e.cross_attentions)throw new Error("Model outputs must contain cross attentions to extract timestamps. This is most likely because the model was not exported with `output_attentions=True`.");s==null&&te.warn("`num_frames` has not been set, meaning the entire audio will be analyzed. This may lead to inaccurate token-level timestamps for short audios (< 30 seconds).");let a=this.config.median_filter_width;a===void 0&&(te.warn("Model config has no `median_filter_width`, using default value of 7."),a=7);let i=e.cross_attentions,l=Array.from({length:this.config.decoder_layers},(A,k)=>Ee(i.map(M=>M[k]),2)),c=kt(r.map(([A,k])=>{if(A>=l.length)throw new Error(`Layer index ${A} is out of bounds for cross attentions (length ${l.length}).`);return s?l[A].slice(null,k,null,[0,s]):l[A].slice(null,k)})).permute(1,0,2,3),[u,f]=km(c,-2,0,!0),m=c.clone();for(let A=0;A0?m.slice(null,null,[o,m.dims[2]],null):m,w=[mu(_,1)],x=e.sequences.dims,b=new $("float32",new Float32Array(x[0]*x[1]),x);for(let A=0;AM[F+1]-M[F]),C=yt([1],O).map(j=>!!j),v=[];for(let j=0;j0&&U.push(v.at(-1)),b[A].data.set(U)}return b}},Gv=class extends ff{};var ws=class extends y{},jv=class extends ws{},qv=class extends ws{async _call(e){return new ye(await super._call(e))}},Wv=class extends ws{async _call(e){return new q(await super._call(e))}},Vv=class extends ws{async _call(e){return new we(await super._call(e))}},Hv=class extends ws{async _call(e){return new Me(await super._call(e))}};var xs=class extends y{},Xv=class extends xs{},Kv=class extends xs{async _call(e){return new ye(await super._call(e))}},Yv=class extends xs{async _call(e){return new q(await super._call(e))}},Qv=class extends xs{async _call(e){return new we(await super._call(e))}},Jv=class extends xs{async _call(e){return new Me(await super._call(e))}};var Rl=class extends y{},Zv=class extends Rl{},ek=class extends Rl{async _call(e){return new df(await super._call(e))}},df=class extends Se{constructor({logits:e,pred_boxes:r}){super(),this.logits=e,this.pred_boxes=r}};var Bl=class extends y{},tk=class extends Bl{},rk=class extends Bl{};var Dl=class extends y{},sk=class extends Dl{},nk=class extends Dl{};var p3=new Map([["bert","BertModel"],["eurobert","EuroBertModel"],["neobert","NeoBertModel"],["modernbert","ModernBertModel"],["nomic_bert","NomicBertModel"],["roformer","RoFormerModel"],["electra","ElectraModel"],["esm","EsmModel"],["convbert","ConvBertModel"],["camembert","CamembertModel"],["deberta","DebertaModel"],["deberta-v2","DebertaV2Model"],["mpnet","MPNetModel"],["albert","AlbertModel"],["distilbert","DistilBertModel"],["roberta","RobertaModel"],["xlm","XLMModel"],["xlm-roberta","XLMRobertaModel"],["clap","ClapModel"],["clip","CLIPModel"],["clipseg","CLIPSegModel"],["chinese_clip","ChineseCLIPModel"],["siglip","SiglipModel"],["jina_clip","JinaCLIPModel"],["mobilebert","MobileBertModel"],["squeezebert","SqueezeBertModel"],["wav2vec2","Wav2Vec2Model"],["wav2vec2-bert","Wav2Vec2BertModel"],["unispeech","UniSpeechModel"],["unispeech-sat","UniSpeechSatModel"],["hubert","HubertModel"],["wavlm","WavLMModel"],["audio-spectrogram-transformer","ASTModel"],["vits","VitsModel"],["pyannote","PyAnnoteModel"],["wespeaker-resnet","WeSpeakerResNetModel"],["detr","DetrModel"],["rt_detr","RTDetrModel"],["rt_detr_v2","RTDetrV2Model"],["rf_detr","RFDetrModel"],["d_fine","DFineModel"],["table-transformer","TableTransformerModel"],["vit","ViTModel"],["ijepa","IJepaModel"],["pvt","PvtModel"],["vit_msn","ViTMSNModel"],["vit_mae","ViTMAEModel"],["groupvit","GroupViTModel"],["fastvit","FastViTModel"],["mobilevit","MobileViTModel"],["mobilevitv2","MobileViTV2Model"],["owlvit","OwlViTModel"],["owlv2","Owlv2Model"],["beit","BeitModel"],["deit","DeiTModel"],["hiera","HieraModel"],["convnext","ConvNextModel"],["convnextv2","ConvNextV2Model"],["dinov2","Dinov2Model"],["dinov2_with_registers","Dinov2WithRegistersModel"],["dinov3_vit","DINOv3ViTModel"],["dinov3_convnext","DINOv3ConvNextModel"],["resnet","ResNetModel"],["swin","SwinModel"],["swin2sr","Swin2SRModel"],["donut-swin","DonutSwinModel"],["yolos","YolosModel"],["dpt","DPTModel"],["glpn","GLPNModel"],["hifigan","SpeechT5HifiGan"],["efficientnet","EfficientNetModel"],["decision_transformer","DecisionTransformerModel"],["patchtst","PatchTSTModel"],["patchtsmixer","PatchTSMixerModel"],["mobilenet_v1","MobileNetV1Model"],["mobilenet_v2","MobileNetV2Model"],["mobilenet_v3","MobileNetV3Model"],["mobilenet_v4","MobileNetV4Model"],["maskformer","MaskFormerModel"],["mgp-str","MgpstrForSceneTextRecognition"],["style_text_to_speech_2","StyleTextToSpeech2Model"],["openai_privacy_filter","OpenAIPrivacyFilterModel"],["embedding_gemma2","EmbeddingGemma2Model"]]),f3=new Map([["t5","T5Model"],["longt5","LongT5Model"],["mt5","MT5Model"],["bart","BartModel"],["mbart","MBartModel"],["marian","MarianModel"],["whisper","WhisperModel"],["cohere_asr","CohereAsrModel"],["m2m_100","M2M100Model"],["blenderbot","BlenderbotModel"],["blenderbot-small","BlenderbotSmallModel"]]),d3=new Map([["mimi","MimiModel"],["dac","DacModel"],["snac","SnacModel"]]),m3=new Map([["bloom","BloomModel"],["jais","JAISModel"],["gpt2","GPT2Model"],["gpt_oss","GptOssModel"],["gptj","GPTJModel"],["gpt_bigcode","GPTBigCodeModel"],["gpt_neo","GPTNeoModel"],["gpt_neox","GPTNeoXModel"],["codegen","CodeGenModel"],["llama","LlamaModel"],["apertus","ApertusModel"],["nanochat","NanoChatModel"],["arcee","ArceeModel"],["afmoe","AfmoeModel"],["lfm2","Lfm2Model"],["lfm2_moe","Lfm2MoeModel"],["lfm3","Lfm3Model"],["smollm3","SmolLM3Model"],["exaone","ExaoneModel"],["olmo","OlmoModel"],["olmo2","Olmo2Model"],["olmo3","Olmo3Model"],["olmo_hybrid","OlmoHybridModel"],["mobilellm","MobileLLMModel"],["granite","GraniteModel"],["granitemoehybrid","GraniteMoeHybridModel"],["cohere","CohereModel"],["cohere2","Cohere2Model"],["gemma","GemmaModel"],["gemma2","Gemma2Model"],["vaultgemma","VaultGemmaModel"],["gemma3_text","Gemma3Model"],["helium","HeliumModel"],["glm","GlmModel"],["glm_moe_dsa","GlmMoeDsaModel"],["openelm","OpenELMModel"],["qwen2","Qwen2Model"],["qwen2_moe","Qwen2MoeModel"],["qwen3","Qwen3Model"],["qwen3_moe","Qwen3MoeModel"],["qwen3_next","Qwen3NextModel"],["phi","PhiModel"],["phi3","Phi3Model"],["mpt","MptModel"],["opt","OPTModel"],["mistral","MistralModel"],["mistral4","Mistral4Model"],["ministral","MinistralModel"],["ministral3","Ministral3Model"],["ernie4_5","Ernie4_5ForCausalLM"],["starcoder2","Starcoder2Model"],["deepseek_v3","DeepseekV3Model"],["deepseek_v4","DeepseekV4Model"],["falcon","FalconModel"],["falcon_h1","FalconH1Model"],["nemotron_h","NemotronHModel"],["solar_open","SolarOpenModel"],["stablelm","StableLmModel"],["modernbert-decoder","ModernBertDecoderModel"],["hunyuan_v1_dense","HunYuanDenseV1Model"],["youtu","YoutuModel"],["zaya","ZayaModel"],["hrm_text","HrmTextModel"]]),vM=new Map([["speecht5","SpeechT5ForSpeechToText"],["whisper","WhisperForConditionalGeneration"],["lite-whisper","LiteWhisperForConditionalGeneration"],["moonshine","MoonshineForConditionalGeneration"],["cohere_asr","CohereAsrForConditionalGeneration"]]),kM=new Map([["speecht5","SpeechT5ForTextToSpeech"]]),EM=new Map([["vits","VitsModel"],["musicgen","MusicgenForConditionalGeneration"],["supertonic","SupertonicForConditionalGeneration"]]),AM=new Map([["bert","BertForSequenceClassification"],["eurobert","EuroBertForSequenceClassification"],["neobert","NeoBertForSequenceClassification"],["modernbert","ModernBertForSequenceClassification"],["roformer","RoFormerForSequenceClassification"],["electra","ElectraForSequenceClassification"],["esm","EsmForSequenceClassification"],["convbert","ConvBertForSequenceClassification"],["camembert","CamembertForSequenceClassification"],["deberta","DebertaForSequenceClassification"],["deberta-v2","DebertaV2ForSequenceClassification"],["mpnet","MPNetForSequenceClassification"],["albert","AlbertForSequenceClassification"],["distilbert","DistilBertForSequenceClassification"],["roberta","RobertaForSequenceClassification"],["xlm","XLMForSequenceClassification"],["xlm-roberta","XLMRobertaForSequenceClassification"],["bart","BartForSequenceClassification"],["mbart","MBartForSequenceClassification"],["mobilebert","MobileBertForSequenceClassification"],["squeezebert","SqueezeBertForSequenceClassification"]]),TM=new Map([["bert","BertForTokenClassification"],["eurobert","EuroBertForTokenClassification"],["neobert","NeoBertForTokenClassification"],["modernbert","ModernBertForTokenClassification"],["roformer","RoFormerForTokenClassification"],["electra","ElectraForTokenClassification"],["esm","EsmForTokenClassification"],["convbert","ConvBertForTokenClassification"],["camembert","CamembertForTokenClassification"],["deberta","DebertaForTokenClassification"],["deberta-v2","DebertaV2ForTokenClassification"],["mpnet","MPNetForTokenClassification"],["distilbert","DistilBertForTokenClassification"],["roberta","RobertaForTokenClassification"],["xlm","XLMForTokenClassification"],["xlm-roberta","XLMRobertaForTokenClassification"],["openai_privacy_filter","OpenAIPrivacyFilterForTokenClassification"]]),SM=new Map([["t5","T5ForConditionalGeneration"],["longt5","LongT5ForConditionalGeneration"],["mt5","MT5ForConditionalGeneration"],["bart","BartForConditionalGeneration"],["mbart","MBartForConditionalGeneration"],["marian","MarianMTModel"],["m2m_100","M2M100ForConditionalGeneration"],["blenderbot","BlenderbotForConditionalGeneration"],["blenderbot-small","BlenderbotSmallForConditionalGeneration"]]),MM=new Map([["bloom","BloomForCausalLM"],["gpt2","GPT2LMHeadModel"],["gpt_oss","GptOssForCausalLM"],["jais","JAISLMHeadModel"],["gptj","GPTJForCausalLM"],["gpt_bigcode","GPTBigCodeForCausalLM"],["gpt_neo","GPTNeoForCausalLM"],["gpt_neox","GPTNeoXForCausalLM"],["codegen","CodeGenForCausalLM"],["llama","LlamaForCausalLM"],["nanochat","NanoChatForCausalLM"],["apertus","ApertusForCausalLM"],["llama4_text","Llama4ForCausalLM"],["arcee","ArceeForCausalLM"],["afmoe","AfmoeForCausalLM"],["lfm2","Lfm2ForCausalLM"],["lfm2_moe","Lfm2MoeForCausalLM"],["lfm3","Lfm3ForCausalLM"],["smollm3","SmolLM3ForCausalLM"],["exaone","ExaoneForCausalLM"],["olmo","OlmoForCausalLM"],["olmo2","Olmo2ForCausalLM"],["olmo3","Olmo3ForCausalLM"],["olmo_hybrid","OlmoHybridForCausalLM"],["mobilellm","MobileLLMForCausalLM"],["granite","GraniteForCausalLM"],["granitemoehybrid","GraniteMoeHybridForCausalLM"],["cohere","CohereForCausalLM"],["cohere2","Cohere2ForCausalLM"],["gemma","GemmaForCausalLM"],["gemma2","Gemma2ForCausalLM"],["vaultgemma","VaultGemmaForCausalLM"],["gemma3_text","Gemma3ForCausalLM"],["gemma3","Gemma3ForCausalLM"],["helium","HeliumForCausalLM"],["glm","GlmForCausalLM"],["glm_moe_dsa","GlmMoeDsaForCausalLM"],["openelm","OpenELMForCausalLM"],["qwen2","Qwen2ForCausalLM"],["qwen2_moe","Qwen2MoeForCausalLM"],["qwen3","Qwen3ForCausalLM"],["qwen3_moe","Qwen3MoeForCausalLM"],["qwen3_next","Qwen3NextForCausalLM"],["qwen2_vl","Qwen2VLForCausalLM"],["qwen2_5_vl","Qwen2_5_VLForCausalLM"],["qwen3_vl","Qwen3VLForCausalLM"],["qwen3_vl_moe","Qwen3VLMoeForCausalLM"],["qwen3_5","Qwen3_5ForCausalLM"],["qwen3_5_text","Qwen3_5ForCausalLM"],["qwen3_5_moe","Qwen3_5MoeForCausalLM"],["gemma3n","Gemma3nForCausalLM"],["gemma4","Gemma4ForCausalLM"],["phi","PhiForCausalLM"],["phi3","Phi3ForCausalLM"],["mpt","MptForCausalLM"],["opt","OPTForCausalLM"],["mbart","MBartForCausalLM"],["mistral","MistralForCausalLM"],["mistral4","Mistral4ForCausalLM"],["ministral","MinistralForCausalLM"],["ministral3","Ministral3ForCausalLM"],["ernie4_5","Ernie4_5ForCausalLM"],["starcoder2","Starcoder2ForCausalLM"],["deepseek_v3","DeepseekV3ForCausalLM"],["deepseek_v4","DeepseekV4ForCausalLM"],["falcon","FalconForCausalLM"],["falcon_h1","FalconH1ForCausalLM"],["nemotron_h","NemotronHForCausalLM"],["trocr","TrOCRForCausalLM"],["solar_open","SolarOpenForCausalLM"],["stablelm","StableLmForCausalLM"],["modernbert-decoder","ModernBertDecoderForCausalLM"],["hunyuan_v1_dense","HunYuanDenseV1ForCausalLM"],["youtu","YoutuForCausalLM"],["zaya","ZayaForCausalLM"],["hrm_text","HrmTextForCausalLM"],["phi3_v","Phi3VForCausalLM"]]),_3=new Map([["multi_modality","MultiModalityCausalLM"]]),OM=new Map([["bert","BertForMaskedLM"],["eurobert","EuroBertForMaskedLM"],["neobert","NeoBertForMaskedLM"],["modernbert","ModernBertForMaskedLM"],["roformer","RoFormerForMaskedLM"],["electra","ElectraForMaskedLM"],["esm","EsmForMaskedLM"],["convbert","ConvBertForMaskedLM"],["camembert","CamembertForMaskedLM"],["deberta","DebertaForMaskedLM"],["deberta-v2","DebertaV2ForMaskedLM"],["mpnet","MPNetForMaskedLM"],["albert","AlbertForMaskedLM"],["distilbert","DistilBertForMaskedLM"],["roberta","RobertaForMaskedLM"],["xlm","XLMWithLMHeadModel"],["xlm-roberta","XLMRobertaForMaskedLM"],["mobilebert","MobileBertForMaskedLM"],["squeezebert","SqueezeBertForMaskedLM"]]),IM=new Map([["bert","BertForQuestionAnswering"],["neobert","NeoBertForQuestionAnswering"],["roformer","RoFormerForQuestionAnswering"],["electra","ElectraForQuestionAnswering"],["convbert","ConvBertForQuestionAnswering"],["camembert","CamembertForQuestionAnswering"],["deberta","DebertaForQuestionAnswering"],["deberta-v2","DebertaV2ForQuestionAnswering"],["mpnet","MPNetForQuestionAnswering"],["albert","AlbertForQuestionAnswering"],["distilbert","DistilBertForQuestionAnswering"],["roberta","RobertaForQuestionAnswering"],["xlm","XLMForQuestionAnswering"],["xlm-roberta","XLMRobertaForQuestionAnswering"],["mobilebert","MobileBertForQuestionAnswering"],["squeezebert","SqueezeBertForQuestionAnswering"]]),CM=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"],["idefics3","Idefics3ForConditionalGeneration"],["smolvlm","SmolVLMForConditionalGeneration"]]),PM=new Map([["llava","LlavaForConditionalGeneration"],["llava_onevision","LlavaOnevisionForConditionalGeneration"],["moondream1","Moondream1ForConditionalGeneration"],["florence2","Florence2ForConditionalGeneration"],["qwen2_vl","Qwen2VLForConditionalGeneration"],["qwen2_5_vl","Qwen2_5_VLForConditionalGeneration"],["qwen3_vl","Qwen3VLForConditionalGeneration"],["qwen3_vl_moe","Qwen3VLMoeForConditionalGeneration"],["qwen3_5","Qwen3_5ForConditionalGeneration"],["qwen3_5_moe","Qwen3_5MoeForConditionalGeneration"],["lfm2_vl","Lfm2VlForConditionalGeneration"],["lfm3_vl","Lfm3VlForConditionalGeneration"],["idefics3","Idefics3ForConditionalGeneration"],["smolvlm","SmolVLMForConditionalGeneration"],["paligemma","PaliGemmaForConditionalGeneration"],["llava_qwen2","LlavaQwen2ForCausalLM"],["gemma3","Gemma3ForConditionalGeneration"],["gemma3n","Gemma3nForConditionalGeneration"],["gemma4","Gemma4ForConditionalGeneration"],["mistral3","Mistral3ForConditionalGeneration"],["lighton_ocr","LightOnOcrForConditionalGeneration"],["glm_ocr","GlmOcrForConditionalGeneration"]]),NM=new Map([["granite_speech","GraniteSpeechForConditionalGeneration"],["ultravox","UltravoxModel"],["voxtral","VoxtralForConditionalGeneration"],["voxtral_realtime","VoxtralRealtimeForConditionalGeneration"]]),h3=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"]]),LM=new Map([["vit","ViTForImageClassification"],["ijepa","IJepaForImageClassification"],["pvt","PvtForImageClassification"],["vit_msn","ViTMSNForImageClassification"],["fastvit","FastViTForImageClassification"],["mobilevit","MobileViTForImageClassification"],["mobilevitv2","MobileViTV2ForImageClassification"],["beit","BeitForImageClassification"],["deit","DeiTForImageClassification"],["hiera","HieraForImageClassification"],["convnext","ConvNextForImageClassification"],["convnextv2","ConvNextV2ForImageClassification"],["dinov2","Dinov2ForImageClassification"],["dinov2_with_registers","Dinov2WithRegistersForImageClassification"],["resnet","ResNetForImageClassification"],["swin","SwinForImageClassification"],["segformer","SegformerForImageClassification"],["efficientnet","EfficientNetForImageClassification"],["mobilenet_v1","MobileNetV1ForImageClassification"],["mobilenet_v2","MobileNetV2ForImageClassification"],["mobilenet_v3","MobileNetV3ForImageClassification"],["mobilenet_v4","MobileNetV4ForImageClassification"]]),zM=new Map([["detr","DetrForObjectDetection"],["rt_detr","RTDetrForObjectDetection"],["rt_detr_v2","RTDetrV2ForObjectDetection"],["rf_detr","RFDetrForObjectDetection"],["d_fine","DFineForObjectDetection"],["table-transformer","TableTransformerForObjectDetection"],["yolos","YolosForObjectDetection"]]),$M=new Map([["owlvit","OwlViTForObjectDetection"],["owlv2","Owlv2ForObjectDetection"],["grounding-dino","GroundingDinoForObjectDetection"]]),bo=new Map([["detr","DetrForSegmentation"],["clipseg","CLIPSegForImageSegmentation"]]),RM=new Map([["segformer","SegformerForSemanticSegmentation"],["sapiens","SapiensForSemanticSegmentation"],["swin","SwinForSemanticSegmentation"],["mobilenet_v1","MobileNetV1ForSemanticSegmentation"],["mobilenet_v2","MobileNetV2ForSemanticSegmentation"],["mobilenet_v3","MobileNetV3ForSemanticSegmentation"],["mobilenet_v4","MobileNetV4ForSemanticSegmentation"]]),BM=new Map([["detr","DetrForSegmentation"],["maskformer","MaskFormerForInstanceSegmentation"]]),DM=new Map([["sam","SamModel"],["sam2","Sam2Model"],["edgetam","EdgeTamModel"],["sam3_tracker","Sam3TrackerModel"]]),UM=new Map([["wav2vec2","Wav2Vec2ForCTC"],["wav2vec2-bert","Wav2Vec2BertForCTC"],["unispeech","UniSpeechForCTC"],["unispeech-sat","UniSpeechSatForCTC"],["wavlm","WavLMForCTC"],["hubert","HubertForCTC"],["parakeet_ctc","ParakeetForCTC"]]),FM=new Map([["wav2vec2","Wav2Vec2ForSequenceClassification"],["wav2vec2-bert","Wav2Vec2BertForSequenceClassification"],["unispeech","UniSpeechForSequenceClassification"],["unispeech-sat","UniSpeechSatForSequenceClassification"],["wavlm","WavLMForSequenceClassification"],["hubert","HubertForSequenceClassification"],["audio-spectrogram-transformer","ASTForAudioClassification"]]),GM=new Map([["wavlm","WavLMForXVector"]]),jM=new Map([["unispeech-sat","UniSpeechSatForAudioFrameClassification"],["wavlm","WavLMForAudioFrameClassification"],["wav2vec2","Wav2Vec2ForAudioFrameClassification"],["pyannote","PyAnnoteForAudioFrameClassification"]]),qM=new Map([["vitmatte","VitMatteForImageMatting"]]),g3=new Map([["patchtst","PatchTSTForPrediction"],["patchtsmixer","PatchTSMixerForPrediction"]]),WM=new Map([["swin2sr","Swin2SRForImageSuperResolution"]]),VM=new Map([["chmv2","CHMv2ForDepthEstimation"],["dpt","DPTForDepthEstimation"],["depth_anything","DepthAnythingForDepthEstimation"],["glpn","GLPNForDepthEstimation"],["sapiens","SapiensForDepthEstimation"],["depth_pro","DepthProForDepthEstimation"],["metric3d","Metric3DForDepthEstimation"],["metric3dv2","Metric3Dv2ForDepthEstimation"]]),HM=new Map([["sapiens","SapiensForNormalEstimation"]]),XM=new Map([["vitpose","VitPoseForPoseEstimation"]]),KM=new Map([["clip","CLIPVisionModelWithProjection"],["siglip","SiglipVisionModel"],["jina_clip","JinaCLIPVisionModel"]]),ok=[[p3,W.EncoderOnly],[f3,W.EncoderDecoder],[m3,W.DecoderOnlyWithoutHead],[d3,W.AutoEncoder],[AM,W.EncoderOnly],[TM,W.EncoderOnly],[SM,W.Seq2Seq],[vM,W.Seq2Seq],[MM,W.DecoderOnly],[_3,W.MultiModality],[OM,W.EncoderOnly],[IM,W.EncoderOnly],[CM,W.Vision2Seq],[PM,W.ImageTextToText],[NM,W.AudioTextToText],[LM,W.EncoderOnly],[bo,W.EncoderOnly],[BM,W.EncoderOnly],[RM,W.EncoderOnly],[qM,W.EncoderOnly],[g3,W.EncoderOnly],[WM,W.EncoderOnly],[VM,W.EncoderOnly],[HM,W.EncoderOnly],[XM,W.EncoderOnly],[zM,W.EncoderOnly],[$M,W.EncoderOnly],[DM,W.MaskGeneration],[UM,W.EncoderOnly],[FM,W.EncoderOnly],[kM,W.Seq2Seq],[EM,W.EncoderOnly],[GM,W.EncoderOnly],[jM,W.EncoderOnly],[KM,W.EncoderOnly]];for(let[t,e]of ok)for(let r of t.values()){ar.set(r,e);let s=Ul[r];Js.set(s,r),pp.set(r,s)}var w3=[["MusicgenForConditionalGeneration",qi,W.Musicgen],["Phi3VForCausalLM",al,W.Phi3V],["CLIPTextModelWithProjection",Ma,W.EncoderOnly],["SiglipTextModel",bl,W.EncoderOnly],["JinaCLIPTextModel",bi,W.EncoderOnly],["ClapTextModelWithProjection",Ta,W.EncoderOnly],["ClapAudioModelWithProjection",Sa,W.EncoderOnly],["DacEncoderModel",Ba,W.EncoderOnly],["DacDecoderModel",Da,W.EncoderOnly],["MimiEncoderModel",Ii,W.EncoderOnly],["MimiDecoderModel",Ci,W.EncoderOnly],["SnacEncoderModel",kl,W.EncoderOnly],["SnacDecoderModel",El,W.EncoderOnly],["Gemma3nForConditionalGeneration",fs,W.ImageAudioTextToText],["Gemma4ForConditionalGeneration",no,W.ImageAudioTextToText],["SupertonicForConditionalGeneration",Ml,W.Supertonic],["ChatterboxModel",Aa,W.Chatterbox],["EmbeddingGemma2Model",Ha,W.MultimodalEncoder],["VoxtralRealtimeForConditionalGeneration",zl,W.VoxtralRealtime]];for(let[t,e,r]of w3)ar.set(t,r),Js.set(e,t),pp.set(t,e);var YM=new Map([["modnet",bo],["birefnet",bo],["isnet",bo],["ben",bo]]);for(let[t,e]of YM.entries())e.set(t,"PreTrainedModel"),ar.set(t,W.EncoderOnly),pp.set(t,y);var QM=new Set(YM.keys());ar.set("PreTrainedModel",W.EncoderOnly);Js.set(y,"PreTrainedModel");var $e={MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES:AM,MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES:TM,MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES:kM,MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES:EM,MODEL_FOR_MASKED_LM_MAPPING_NAMES:OM,MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES:IM,MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES:LM,MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES:bo,MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES:RM,MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES:BM,MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES:zM,MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES:$M,MODEL_FOR_MASK_GENERATION_MAPPING_NAMES:DM,MODEL_FOR_CTC_MAPPING_NAMES:UM,MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES:FM,MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES:GM,MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES:jM,MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES:h3,MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES:qM,MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES:WM,MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES:VM,MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES:HM,MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES:XM,MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES:KM,MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES:PM,MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES:NM,MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES:SM,MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES:vM,MODEL_FOR_CAUSAL_LM_MAPPING_NAMES:MM,MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES:CM};gM($e);var Ne=class{static MODEL_CLASS_MAPPINGS=null;static BASE_IF_FAIL=!1;static supports(e){if(!this.MODEL_CLASS_MAPPINGS)return!1;for(let r of this.MODEL_CLASS_MAPPINGS)if(r.has(e))return!0;return this.BASE_IF_FAIL}static async from_pretrained(e,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main",model_file_name:i=null,subfolder:l="onnx",device:c=null,dtype:u=null,use_external_data_format:f=null,session_options:m={}}={}){let _={progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a,model_file_name:i,subfolder:l,device:c,dtype:u,use_external_data_format:f,session_options:m};if(_.config=await Ht.from_pretrained(e,_),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);let{model_type:w}=_.config;for(let x of this.MODEL_CLASS_MAPPINGS){let b=x.get(w);if(!b){for(let A of x.values())if(A[0]===w){b=A;break}if(!b)continue}return await Ul[b].from_pretrained(e,_)}if(this.BASE_IF_FAIL)return QM.has(w)||te.warn(`Unknown model class "${w}", attempting to construct from base class.`),await y.from_pretrained(e,_);throw Error(`Unsupported model type: ${w}`)}},Or=class extends Ne{static MODEL_CLASS_MAPPINGS=ok.map(e=>e[0]);static BASE_IF_FAIL=!0},Fl=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES]},mf=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES]},vo=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES]},_f=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES]},hf=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES]},gf=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES]},wf=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES]},xf=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_MASKED_LM_MAPPING_NAMES]},yf=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES]},bf=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES]},vf=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES]},Gl=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES]},jl=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES]},ql=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES]},kf=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES]},Ef=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES]},JM=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_MASK_GENERATION_MAPPING_NAMES]},Af=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_CTC_MAPPING_NAMES]},Tf=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES]},ZM=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES]},eO=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES]},Sf=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES]},tO=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES]},Mf=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES]},Of=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES]},rO=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES]},sO=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES]},If=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES]},nO=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES]},oO=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES]};async function nt(t){return Array.isArray(t)||(t=[t]),await Promise.all(t.map(e=>rt.read(e)))}async function Ir(t,e){return Array.isArray(t)||(t=[t]),await Promise.all(t.map(r=>typeof r=="string"||r instanceof URL?y_(r,e):r instanceof Float64Array?new Float32Array(r):r))}function Wl(t,e){e&&(t=t.map(a=>a|0));let[r,s,n,o]=t;return{xmin:r,ymin:s,xmax:n,ymax:o}}var _e=class extends We{constructor({task:e,model:r,tokenizer:s=null,processor:n=null}){super(),this.task=e,this.model=r,this.tokenizer=s,this.processor=n}async dispose(){await this.model.dispose()}};var Vl=class extends _e{async _call(e,{top_k:r=1}={}){let s=this.tokenizer(e,{padding:!0,truncation:!0}),n=await this.model(s),{problem_type:o,id2label:a}=this.model.config,i=o==="multi_label_classification"?c=>c.sigmoid():c=>new $("float32",Ue(c.data),c.dims),l=[];for(let c of n.logits){let u=i(c),f=await or(u,r),m=f[0].tolist(),w=f[1].tolist().map((x,b)=>({label:a?a[x]:`LABEL_${x}`,score:m[b]}));r===1?l.push(...w):l.push(w)}return Array.isArray(e)||r===1?l:l[0]}};var Hl=class extends _e{async _call(e,{ignore_labels:r=["O"],aggregation_strategy:s="none"}={}){if(s!=="none"&&s!=="simple")throw new Error(`Invalid aggregation_strategy: "${s}". Must be one of "none" or "simple".`);let n=Array.isArray(e),o=this.tokenizer(n?e:[e],{padding:!0,truncation:!0}),i=(await this.model(o)).logits,l=this.model.config.id2label,c=[];for(let u=0;u{let l=0,c=[];for(let u=a;uC==f),b=a[_].tolist(),A=i[_].tolist();for(let C=1;Cv==w[C])!==-1)&&(b[C]=-1/0,A[C]=-1/0);let k=Ue(b).map((C,v)=>[C,v]),M=Ue(A).map((C,v)=>[C,v]);k[0][0]=0,M[0][0]=0;let S=CA(k,M).filter(C=>C[0][1]<=C[1][1]).map(C=>[C[0][1],C[1][1],C[0][0]*C[1][0]]).sort((C,v)=>v[2]-C[2]),O=[];for(let C=0;Cb==s);if(f===-1)throw Error(`Mask token (${n}) not found in text.`);let m=a[c][f],_=await or(new $("float32",Ue(m.data),m.dims),r),w=_[0].tolist(),x=_[1].tolist();i.push(x.map((b,A)=>{let k=u.slice();return k[f]=b,{score:w[A],token:Number(b),token_str:this.tokenizer.decode([b]),sequence:this.tokenizer.decode(k,{skip_special_tokens:!0})}}))}return Array.isArray(e)?i:i[0]}};var Cr=class extends _e{_default_generation_config={max_new_tokens:256};_key="generated_text";async _call(e,r={}){Array.isArray(e)||(e=[e]),this.model.config.prefix&&(e=e.map(l=>this.model.config.prefix+l));let s=this.model.config.task_specific_params;s&&s[this.task]&&s[this.task].prefix&&(e=e.map(l=>s[this.task].prefix+l));let n=this.tokenizer,o={padding:!0,truncation:!0},a;this.task==="translation"&&"_build_translation_inputs"in n?a=n._build_translation_inputs(e,o,r):a=n(e,o);let i=await this.model.generate({...a,...this._default_generation_config,...r});return n.batch_decode(i,{skip_special_tokens:!0}).map(l=>({[this._key]:l}))}};var Yl=class extends Cr{_key="summary_text"};var Ql=class extends Cr{_key="translation_text"};function aO(t){return Array.isArray(t)&&t.every(e=>"role"in e&&"content"in e)}var Jl=class extends _e{_default_generation_config={max_new_tokens:256};async _call(e,r={}){let{add_special_tokens:s,return_full_text:n,tools:o,documents:a,chat_template:i,tokenizer_encode_kwargs:l,...c}=r,u=!1,f=!1,m=s??(this.tokenizer.add_bos_token||this.tokenizer.add_eos_token)??!1,_=l,w;if(typeof e=="string")w=e=[e];else if(Array.isArray(e)&&e.every(O=>typeof O=="string"))u=!0,w=e;else{if(aO(e))e=[e];else if(Array.isArray(e)&&e.every(aO))u=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");f=!0;let O={tokenize:!1,add_generation_prompt:!0,...He({tools:o,documents:a,chat_template:i},["tools","documents","chat_template"]),..._};w=e.map(C=>this.tokenizer.apply_chat_template(C,O)),m=!1,_=void 0}let x=f?!1:n??!0;this.tokenizer.padding_side="left";let b=this.tokenizer(w,{add_special_tokens:m,padding:!0,truncation:!0,..._}),A=await this.model.generate({...b,...this._default_generation_config,...c}),k=this.tokenizer.batch_decode(A,{skip_special_tokens:!0}),M;!x&&b.input_ids.dims.at(-1)>0&&(M=this.tokenizer.batch_decode(b.input_ids,{skip_special_tokens:!0}).map(O=>O.length));let S=Array.from({length:e.length},O=>[]);for(let O=0;O[r.toLowerCase(),s])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(te.warn("Could not find 'entailment' in label2id mapping. Using 2 as entailment_id."),this.entailment_id=2),this.contradiction_id=this.label2id.contradiction??this.label2id.not_entailment,this.contradiction_id===void 0&&(te.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(e,r,{hypothesis_template:s="This example is {}.",multi_label:n=!1}={}){let o=Array.isArray(e);o||(e=[e]),Array.isArray(r)||(r=[r]);let a=r.map(c=>s.replace("{}",c)),i=n||r.length===1,l=[];for(let c of e){let u=[];for(let _ of a){let w=this.tokenizer(c,{text_pair:_,padding:!0,truncation:!0}),x=await this.model(w);i?u.push([x.logits.data[this.contradiction_id],x.logits.data[this.entailment_id]]):u.push(x.logits.data[this.entailment_id])}let m=(i?u.map(_=>Ue(_)[1]):Ue(u)).map((_,w)=>[_,w]).sort((_,w)=>w[0]-_[0]);l.push({sequence:c,labels:m.map(_=>r[_[1]]),scores:m.map(_=>_[0])})}return o?l:l[0]}};var ec=class extends _e{async _call(e,{top_k:r=5}={}){let s=this.processor.feature_extractor.config.sampling_rate,n=await Ir(e,s),o=this.model.config.id2label,a=[];for(let i of n){let l=await this.processor(i),u=(await this.model(l)).logits[0],f=await or(new $("float32",Ue(u.data),u.dims),r),m=f[0].tolist(),w=f[1].tolist().map((x,b)=>({label:o?o[x]:`LABEL_${x}`,score:m[b]}));a.push(w)}return Array.isArray(e)?a:a[0]}};var tc=class extends _e{async _call(e,r,{hypothesis_template:s="This is a sound of {}."}={}){let n=!Array.isArray(e);n&&(e=[e]);let o=r.map(u=>s.replace("{}",u)),a=this.tokenizer(o,{padding:!0,truncation:!0}),i=this.processor.feature_extractor.config.sampling_rate,l=await Ir(e,i),c=[];for(let u of l){let f=await this.processor(u),m=await this.model({...a,...f}),_=Ue(m.logits_per_audio.data);c.push([..._].map((w,x)=>({score:w,label:r[x]})))}return n?c[0]:c}};var rc=class extends _e{_default_generation_config={};async _call(e,r={}){switch(r={...this._default_generation_config,...r},this.model.config.model_type){case"whisper":case"lite-whisper":return this._call_whisper(e,r);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":case"parakeet_ctc":return this._call_wav2vec2(e,r);case"moonshine":return this._call_moonshine(e,r);case"cohere_asr":return this._call_cohere_asr(e,r);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(e,r){r.language&&te.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),r.task&&te.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');let s=!Array.isArray(e),n=s?[e]:e,o=this.processor.feature_extractor.config.sampling_rate,a=await Ir(n,o),i=[];for(let l of a){let c=await this.processor(l),f=(await this.model(c)).logits[0],m=[];for(let w of f)m.push(Le(w.data)[1]);let _=this.tokenizer.decode(m,{skip_special_tokens:!0}).trim();i.push({text:_})}return s?i[0]:i}async _call_whisper(e,r){let s=r.return_timestamps??!1,n=r.chunk_length_s??0,o=r.force_full_sequences??!1,a=r.stride_length_s??null,i={...r};s==="word"&&(i.return_token_timestamps=!0,i.return_timestamps=!0);let l=!Array.isArray(e),c=l?[e]:e,u=this.processor.feature_extractor.config,f=u.chunk_length/this.model.config.max_source_positions,m=u.hop_length,_=u.sampling_rate,w=await Ir(c,_),x=[];for(let b of w){let A=[];if(n>0){if(a===null)a=n/6;else if(n<=a)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");let S=_*n,O=_*a,C=S-2*O,v=0;for(;;){let U=v+S,j=b.subarray(v,U),F=await this.processor(j),K=v===0,Y=U>=b.length;if(A.push({stride:[j.length,K?0:O,Y?0:O],input_features:F.input_features,is_last:Y}),Y)break;v+=C}}else A=[{stride:[b.length,0,0],input_features:(await this.processor(b)).input_features,is_last:!0}];for(let S of A){i.num_frames=Math.floor(S.stride[0]/m);let O=await this.model.generate({inputs:S.input_features,...i});if(s==="word"){let C=O.sequences.tolist()[0],v=O.token_timestamps.tolist()[0],U=this.tokenizer.timestamp_begin,j=Math.max(C.findIndex(F=>Number(F)>=U),0);S.tokens=C.slice(j),S.token_timestamps=v.slice(j).map(F=>Cs(F,2))}else S.tokens=O[0].tolist();S.stride=S.stride.map(C=>C/_)}let[k,M]=this.tokenizer._decode_asr(A,{time_precision:f,return_timestamps:s,force_full_sequences:o});x.push({text:k,...M})}return l?x[0]:x}async _call_moonshine(e,r){let s=!Array.isArray(e),n=s?[e]:e,o=this.processor.feature_extractor.config.sampling_rate,a=await Ir(n,o),i=[];for(let l of a){let c=await this.processor(l),u=Math.floor(l.length/o)*6,f=await this.model.generate({max_new_tokens:u,...r,...c}),m=this.tokenizer.batch_decode(f,{skip_special_tokens:!0})[0];i.push({text:m})}return s?i[0]:i}async _call_cohere_asr(e,r){let s=!Array.isArray(e),n=s?[e]:e,o=this.processor.feature_extractor,a=o.config.sampling_rate,i=await Ir(n,a),l=r.language??"en",c=this.processor.get_decoder_prompt_ids(l),u=[];for(let f of i){let m=o.split_audio(f),_=[];for(let x of m){let b=await this.processor(x),A=await this.model.generate({...b,decoder_input_ids:c,...r}),k=this.tokenizer.decode(A[0].tolist(),{skip_special_tokens:!0}).trim();_.push(k)}let w=this.processor.constructor.join_chunks(_,l);u.push({text:w})}return s?u[0]:u}};var sc=class extends _e{DEFAULT_VOCODER_ID="Xenova/speecht5_hifigan";constructor(e){super(e),this.vocoder=e.vocoder??null}async _prepare_speaker_embeddings(e,r){if((typeof e=="string"||e instanceof URL)&&(e=new Float32Array(await(await he.fetch(e)).arrayBuffer())),e instanceof Float32Array)e=new $("float32",e,[e.length]);else if(!(e instanceof $))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");if(r>1){if(e.dims[0]===1)e=e.repeat(r,1);else if(e.dims[0]!==r)throw new Error(`Expected speaker embeddings batch size to be 1 or ${r}, but got ${e.dims[0]}.`)}return e}_postprocess_waveform(e,r,s,n=null){let o=r.data,[a,i]=r.dims,l=n?n.data:null,c=[];for(let u=0;u({generated_text:u.trim()}));a.push(c)}return s?a:a[0]}};var oc=class extends _e{async _call(e,{top_k:r=5}={}){let s=await nt(e),{pixel_values:n}=await this.processor(s),o=await this.model({pixel_values:n}),{id2label:a}=this.model.config,i=[];for(let l of o.logits){let c=await or(new $("float32",Ue(l.data),l.dims),r),u=c[0].tolist(),m=c[1].tolist().map((_,w)=>({label:a?a[_]:`LABEL_${_}`,score:u[w]}));i.push(m)}return Array.isArray(e)?i:i[0]}};var iO={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"},fn=class extends _e{async _call(e,{threshold:r=.5,mask_threshold:s=.5,overlap_mask_area_threshold:n=.8,label_ids_to_fuse:o=null,target_sizes:a=null,subtask:i=null}={}){if(Array.isArray(e)&&e.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");let c=await nt(e),u=c.map(k=>[k.height,k.width]),f=await this.processor(c),{inputNames:m,outputNames:_}=this.model.sessions.model;if(!m.includes("pixel_values")){if(m.length!==1)throw Error(`Expected a single input name, but got ${m.length} inputs: ${m}.`);let k=m[0];if(k in f)throw Error(`Input name ${k} already exists in the inputs.`);f[k]=f.pixel_values}let w=await this.model(f),x=null;if(i!==null)x=iO[i];else if(this.processor.image_processor){for(let[k,M]of Object.entries(iO))if(M in this.processor.image_processor){x=this.processor.image_processor[M].bind(this.processor.image_processor),i=k;break}}let b=this.model.config.id2label,A=[];if(i)if(i==="panoptic"||i==="instance"){let k=x(w,r,s,n,o,a??u)[0],M=k.segmentation;for(let S of k.segments_info){let O=new Uint8ClampedArray(M.data.length);for(let v=0;vU<-1e-5||U>1+1e-5)&&C.sigmoid_();let v=await rt.fromTensor(C.mul_(255).to("uint8")).resize(O[1],O[0]);A.push({label:null,score:null,mask:v})}}return A}};var ac=class extends fn{async _call(e,r={}){let s=await nt(e),n=await super._call(e,r),o=s.map((a,i)=>{let l=a.clone();return l.putAlpha(n[i].mask),l});return Array.isArray(e)?o:o[0]}};var ic=class extends _e{async _call(e,r,{hypothesis_template:s="This is a photo of {}"}={}){let n=Array.isArray(e),o=await nt(e),a=r.map(m=>s.replace("{}",m)),i=this.tokenizer(a,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:l}=await this.processor(o),c=await this.model({...i,pixel_values:l}),u=this.model.config.model_type==="siglip"?m=>m.sigmoid().data:m=>Ue(m.data),f=[];for(let m of c.logits_per_image){let w=[...u(m)].map((x,b)=>({score:x,label:r[b]}));w.sort((x,b)=>b.score-x.score),f.push(w)}return n?f:f[0]}};var lc=class extends _e{async _call(e,{threshold:r=.9,percentage:s=!1}={}){let n=Array.isArray(e);if(n&&e.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");let o=await nt(e),a=s?null:o.map(_=>[_.height,_.width]),{pixel_values:i,pixel_mask:l}=await this.processor(o),c=await this.model({pixel_values:i,pixel_mask:l}),u=this.processor.image_processor.post_process_object_detection(c,r,a),{id2label:f}=this.model.config,m=u.map(_=>_.boxes.map((w,x)=>({score:_.scores[x],label:f[_.classes[x]],box:Wl(w,!s)})));return n?m:m[0]}};var cc=class extends _e{async _call(e,r,{threshold:s=.1,top_k:n=null,percentage:o=!1}={}){let a=Array.isArray(e),i=await nt(e),l=this.tokenizer(r,{padding:!0,truncation:!0}),c=await this.processor(i),u=[];for(let f=0;f({score:A.scores[M],label:A.labels[M],box:Wl(k,!o)}))}else{let A=this.processor.image_processor.post_process_object_detection(x,s,_,!0)[0];b=A.boxes.map((k,M)=>({score:A.scores[M],label:r[A.classes[M]],box:Wl(k,!o)}))}b.sort((A,k)=>k.score-A.score),n!==null&&(b=b.slice(0,n)),u.push(b)}return a?u:u[0]}};var uc=class extends _e{_default_generation_config={max_new_tokens:256};async _call(e,r,s={}){if(Array.isArray(e)){if(e.length!==1)throw Error("Document Question Answering pipeline currently only supports a batch size of 1.");e=e[0]}let n=(await nt(e))[0],{pixel_values:o}=await this.processor(n),a=`${r}`,i=this.tokenizer(a,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,l=await this.model.generate({inputs:o,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:i,...this._default_generation_config,...s}),u=this.tokenizer.batch_decode(l)[0].match(/(.*?)<\/s_answer>/),f=null;return u&&u.length>=2&&(f=u[1].trim()),[{answer:f}]}};var pc=class extends _e{async _call(e){let r=await nt(e),s=await this.processor(r),n=await this.model(s),o=[];for(let a of n.reconstruction){let i=a.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");o.push(rt.fromTensor(i))}return Array.isArray(e)?o:o[0]}};var fc=class extends _e{async _call(e){let r=await nt(e),s=await this.processor(r),{predicted_depth:n}=await this.model(s),o=[];for(let a=0;a`onnx/${m}`);return i.filter(m=>!m.startsWith("onnx/")||f.some(_=>m.startsWith(_)))}}return i}async function rde(t,e=null,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main",device:i=null,dtype:l=null,subfolder:c="onnx",use_external_data_format:u=null,model_file_name:f=null,session_options:m={}}={}){t=Cf[t]??t;let _=ko[t.split("_",1)[0]];if(!_)throw Error(`Unsupported pipeline: ${t}. Must be one of [${Object.keys(ko)}]`);e||(e=_.default.model,te.info(`No model specified. Using default model: "${e}".`),!l&&_.default.dtype&&(l=_.default.dtype));let w=await Nr(t,e,{device:i,dtype:l}),x={};if(r)try{(await Promise.all(w.map(async K=>Pt(e,K)))).forEach((K,Y)=>{K.exists&&(x[w[Y]]={loaded:0,total:K.size??0})})}catch(F){te.warn(`Unable to fetch model file metadata for total progress tracking: ${F}`)}let b={progress_callback:r?new Ar(r,x):void 0,config:s,cache_dir:n,local_files_only:o,revision:a,device:i,dtype:l,subfolder:c,use_external_data_format:u,model_file_name:f,session_options:m},A=w.includes("tokenizer.json"),k=w.includes("preprocessor_config.json"),M=_.model,S;if(Array.isArray(M)){let F=s??await Ht.from_pretrained(e,b),{model_type:K}=F,Y=M.find(Q=>Q.supports(K));if(!Y)throw Error(`Unsupported model type "${K}" for task "${t}". None of the candidate model classes support this type.`);S=Y.from_pretrained(e,{...b,config:F})}else S=M.from_pretrained(e,b);let[O,C,v]=await Promise.all([A?ne.from_pretrained(e,b):null,k?qu.from_pretrained(e,b):null,S]),U={task:t,model:v};O&&(U.tokenizer=O),C&&(U.processor=C),fr(r,{status:"ready",task:t,model:e});let j=_.pipeline;return new j(U)}var b3=t=>t>=19968&&t<=40959||t>=13312&&t<=19903||t>=131072&&t<=173791||t>=173824&&t<=177983||t>=177984&&t<=178207||t>=178208&&t<=183983||t>=63744&&t<=64255||t>=194560&&t<=195103,ak=class{put(e){throw Error("Not implemented")}end(){throw Error("Not implemented")}},lO=le.IS_PROCESS_AVAILABLE?t=>process.stdout.write(t):t=>console.log(t),ik=class extends ak{constructor(e,{skip_prompt:r=!1,callback_function:s=null,token_callback_function:n=null,skip_special_tokens:o=!0,decode_kwargs:a={},...i}={}){super(),this.tokenizer=e,this.skip_prompt=r,this.callback_function=s??lO,this.token_callback_function=n,this.decode_kwargs={skip_special_tokens:o,...a,...i},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0,this.special_ids=new Set(this.tokenizer.all_special_ids.map(BigInt))}put(e){if(e.length>1)throw Error("TextStreamer only supports batch size of 1");let r=this.next_tokens_are_prompt;if(r&&(this.next_tokens_are_prompt=!1,this.skip_prompt))return;let s=e[0];if(this.token_callback_function?.(s),s.length===1&&this.special_ids.has(s[0])){if(this.decode_kwargs.skip_special_tokens)return;if(this.token_cache.length>0){let l=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len);this.on_finalized_text(l,!1),this.token_cache=[],this.print_len=0}let a=this.tokenizer.decode(s,this.decode_kwargs);this.on_finalized_text(a,!1);return}this.token_cache=yt(this.token_cache,s);let n=this.tokenizer.decode(this.token_cache,this.decode_kwargs),o;r||n.endsWith(` +`)?(o=n.slice(this.print_len),this.token_cache=[],this.print_len=0):n.length>0&&b3(n.charCodeAt(n.length-1))?(o=n.slice(this.print_len),this.print_len+=o.length):(o=n.slice(this.print_len,n.lastIndexOf(" ")+1),this.print_len+=o.length),this.on_finalized_text(o,!1)}end(){let e;this.token_cache.length>0?(e=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):e="",this.next_tokens_are_prompt=!0,this.on_finalized_text(e,!0)}on_finalized_text(e,r){e.length>0&&this.callback_function?.(e),r&&this.callback_function===lO&&le.IS_PROCESS_AVAILABLE&&this.callback_function?.(` +`)}},cO=class extends ik{constructor(e,{skip_prompt:r=!1,callback_function:s=null,token_callback_function:n=null,on_chunk_start:o=null,on_chunk_end:a=null,on_finalize:i=null,time_precision:l=.02,skip_special_tokens:c=!0,decode_kwargs:u={}}={}){super(e,{skip_prompt:r,skip_special_tokens:c,callback_function:s,token_callback_function:n,decode_kwargs:u}),this.timestamp_begin=e.timestamp_begin,this.on_chunk_start=o,this.on_chunk_end=a,this.on_finalize=i,this.time_precision=l,this.waiting_for_timestamp=!1}put(e){if(e.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");let r=e[0];if(r.length===1){let s=Number(r[0])-this.timestamp_begin;if(s>=0){let n=s*this.time_precision;this.waiting_for_timestamp?this.on_chunk_end?.(n):this.on_chunk_start?.(n),this.waiting_for_timestamp=!this.waiting_for_timestamp,this.token_callback_function?.(r);return}}return super.put(e)}end(){super.end(),this.on_finalize?.()}};var _c=class{constructor(e,r){this.image=e,this.timestamp=r}},Nf=class{constructor(e,r){e.length>0&&e[0]instanceof rt&&(e=e.map((s,n)=>new _c(s,(n+1)/(e.length+1)*r))),this.frames=e,this.duration=r}get width(){return this.frames[0].image.width}get height(){return this.frames[0].image.height}get fps(){return this.frames.length/this.duration}};async function v3(t,{num_frames:e=null,fps:r=null}={}){if(!le.IS_BROWSER_ENV)throw new Error("`load_video` is currently only supported in browser environments.");if(e==null&&r==null)throw new Error("Either num_frames or fps must be provided.");let s=[],n=document.createElement("video");if(n.crossOrigin="anonymous",n.muted=!0,typeof t=="string")n.src=t;else if(t instanceof Blob)n.src=URL.createObjectURL(t);else if(t instanceof HTMLVideoElement)n.src=t.src;else throw new Error("Invalid URL or video element provided.");if(await new Promise(f=>n.onloadedmetadata=f),n.seekable.start(0)===n.seekable.end(0)){let m=await(await he.fetch(n.src)).blob();n.src=URL.createObjectURL(m),await new Promise(_=>n.onloadedmetadata=_)}let o=n.duration,a,i;e!=null?(a=e,i=e===1?0:o/(e-1)):(i=1/r,a=Math.floor(o/i));let l=[];for(let f=0;f{n.onseeked=x}),u.drawImage(n,0,0,c.width,c.height);let m=u.getImageData(0,0,c.width,c.height),_=new rt(m.data,c.width,c.height,4),w=new _c(_,f);s.push(w)}return n.remove(),new Nf(s,o)}async function Lf(t,e,r={}){let s=await rr(r?.cache_dir);if(!s)return{allCached:!1,files:e.map(a=>({file:a,cached:!1}))};let n=await Promise.all(e.map(async o=>{let{localPath:a,proposedCacheKey:i}=qr(t,o,r,s),l=await Wr(s,a,i);return{file:o,cached:!!l}}));return{allCached:n.every(o=>o.cached),files:n}}async function uO(t,e,r={}){let s=await rr(r?.cache_dir);if(!s)return!1;let{localPath:n,proposedCacheKey:o}=qr(t,e,r,s);return!!await Wr(s,n,o)}async function pO(t,e={}){if(!t)throw new Error("modelId is required");if(!await uO(t,"config.json",e))return!1;let r=await Pr(t,e);return(await Lf(t,r,e)).allCached}async function fO(t,e={}){if(!t)throw new Error("modelId is required");let r=await Pr(t,e);return await Lf(t,r,e)}async function dO(t,e,r={}){if(!t)throw new Error("task is required");if(!e)throw new Error("modelId is required");if(!await uO(e,"config.json",r))return!1;let s=await Nr(t,e,r);return(await Lf(e,s,r)).allCached}async function mO(t,e,r={}){if(!t)throw new Error("task is required");if(!e)throw new Error("modelId is required");let s=await Nr(t,e,r);return await Lf(e,s,r)}async function _O(t,e,r={}){let s=await rr(r?.cache_dir);if(!s)return{filesDeleted:0,filesCached:0,files:e.map(o=>({file:o,deleted:!1,wasCached:!1}))};if(!s.delete)throw new Error("Cache does not support delete operation");let n=await Promise.all(e.map(async o=>{let{localPath:a,proposedCacheKey:i}=qr(t,o,r,s),c=!!await Wr(s,a,i),u=!1;if(c){let f=await s.delete(i),m=!f&&i!==a?await s.delete(a):!1;u=f||m}return{file:o,deleted:u,wasCached:c}}));return{filesDeleted:n.filter(o=>o.deleted).length,filesCached:n.filter(o=>o.wasCached).length,files:n}}async function hO(t,e={}){if(!t)throw new Error("modelId is required");let r=await Pr(t,e);return await _O(t,r,e)}async function gO(t,e,r={}){if(!t)throw new Error("task is required");if(!e)throw new Error("modelId is required");let s=await Nr(t,e,r);return await _O(e,s,r)}var k3=Object.keys(Jr);async function wO(t,{config:e=null,model_file_name:r=null,revision:s="main",cache_dir:n=null,local_files_only:o=!1}={}){e=await ma(t,{config:e,cache_dir:n,local_files_only:o,revision:s});let a="onnx",i=Yn(e),{sessions:l}=ip(i,e,{model_file_name:r}),c=Object.values(l),u={revision:s,cache_dir:n,local_files_only:o};return(await Promise.all(k3.map(async m=>{let _=Jr[m]??"",w=await Promise.all(c.map(async x=>{let b=`${a}/${x}${_}.onnx`;return(await Pt(t,b,u)).exists}));return{dtype:m,available:w.every(Boolean)}}))).filter(m=>m.available).map(m=>m.dtype)}var lk=class{static async get_files(e,r={}){return Pr(e,r)}static async get_pipeline_files(e,r,s={}){return Nr(e,r,s)}static async get_model_files(e,r={}){return Qn(e,r)}static async get_tokenizer_files(e){return zn(e)}static async get_processor_files(e){return Pf(e)}static async get_available_dtypes(e,r={}){return wO(e,r)}static async is_cached(e,r={}){return pO(e,r)}static async is_cached_files(e,r={}){return fO(e,r)}static async is_pipeline_cached(e,r,s={}){return dO(e,r,s)}static async is_pipeline_cached_files(e,r,s={}){return mO(e,r,s)}static async get_file_metadata(e,r,s={}){return Pt(e,r,s)}static async clear_cache(e,r={}){return hO(e,r)}static async clear_pipeline_cache(e,r,s={}){return gO(e,r,s)}};export{b_ as ASTFeatureExtractor,Ag as ASTForAudioClassification,Eg as ASTModel,ya as ASTPreTrainedModel,bg as AfmoeForCausalLM,yg as AfmoeModel,wa as AfmoePreTrainedModel,gg as AlbertForMaskedLM,hg as AlbertForQuestionAnswering,_g as AlbertForSequenceClassification,mg as AlbertModel,en as AlbertPreTrainedModel,Sm as AlbertTokenizer,xg as ApertusForCausalLM,wg as ApertusModel,ga as ApertusPreTrainedModel,kg as ArceeForCausalLM,vg as ArceeModel,xa as ArceePreTrainedModel,ec as AudioClassificationPipeline,Ht as AutoConfig,Ve as AutoFeatureExtractor,Te as AutoImageProcessor,Or as AutoModel,Tf as AutoModelForAudioClassification,eO as AutoModelForAudioFrameClassification,oO as AutoModelForAudioTextToText,Af as AutoModelForCTC,wf as AutoModelForCausalLM,Of as AutoModelForDepthEstimation,Sf as AutoModelForDocumentQuestionAnswering,vf as AutoModelForImageClassification,If as AutoModelForImageFeatureExtraction,tO as AutoModelForImageMatting,Gl as AutoModelForImageSegmentation,nO as AutoModelForImageTextToText,Mf as AutoModelForImageToImage,JM as AutoModelForMaskGeneration,xf as AutoModelForMaskedLM,rO as AutoModelForNormalEstimation,kf as AutoModelForObjectDetection,sO as AutoModelForPoseEstimation,yf as AutoModelForQuestionAnswering,jl as AutoModelForSemanticSegmentation,vo as AutoModelForSeq2SeqLM,Fl as AutoModelForSequenceClassification,_f as AutoModelForSpeechSeq2Seq,hf as AutoModelForTextToSpectrogram,gf as AutoModelForTextToWaveform,mf as AutoModelForTokenClassification,ql as AutoModelForUniversalSegmentation,bf as AutoModelForVision2Seq,ZM as AutoModelForXVector,Ef as AutoModelForZeroShotObjectDetection,qu as AutoProcessor,ne as AutoTokenizer,rc as AutomaticSpeechRecognitionPipeline,ac as BackgroundRemovalPipeline,Sg as BartForConditionalGeneration,Mg as BartForSequenceClassification,Tg as BartModel,Zn as BartPretrainedModel,Mm as BartTokenizer,Wu as BaseModelOutput,ak as BaseStreamer,D_ as BeitFeatureExtractor,Ig as BeitForImageClassification,Og as BeitModel,ba as BeitPreTrainedModel,Pg as BertForMaskedLM,zg as BertForQuestionAnswering,Ng as BertForSequenceClassification,Lg as BertForTokenClassification,Cg as BertModel,os as BertPreTrainedModel,Om as BertTokenizer,U_ as BitImageProcessor,Rg as BlenderbotForConditionalGeneration,$g as BlenderbotModel,va as BlenderbotPreTrainedModel,Dg as BlenderbotSmallForConditionalGeneration,Bg as BlenderbotSmallModel,ka as BlenderbotSmallPreTrainedModel,Im as BlenderbotSmallTokenizer,Cm as BlenderbotTokenizer,Fg as BloomForCausalLM,Ug as BloomModel,Ea as BloomPreTrainedModel,Pm as BloomTokenizer,Xg as CHMv2ForDepthEstimation,G_ as CHMv2ImageProcessor,_p as CHMv2PreTrainedModel,j_ as CLIPFeatureExtractor,Eu as CLIPImageProcessor,Yg as CLIPModel,wr as CLIPPreTrainedModel,tw as CLIPSegForImageSegmentation,ew as CLIPSegModel,Oa as CLIPSegPreTrainedModel,Qg as CLIPTextModel,Ma as CLIPTextModelWithProjection,Lm as CLIPTokenizer,Jg as CLIPVisionModel,Zg as CLIPVisionModelWithProjection,jg as CamembertForMaskedLM,Vg as CamembertForQuestionAnswering,qg as CamembertForSequenceClassification,Wg as CamembertForTokenClassification,Gg as CamembertModel,as as CamembertPreTrainedModel,Nm as CamembertTokenizer,ht as CausalLMOutput,Vu as CausalLMOutputWithPast,v_ as ChatterboxFeatureExtractor,Aa as ChatterboxModel,dp as ChatterboxPreTrainedModel,L_ as ChatterboxProcessor,F_ as ChineseCLIPFeatureExtractor,Hg as ChineseCLIPModel,mp as ChineseCLIPPreTrainedModel,Sa as ClapAudioModelWithProjection,k_ as ClapFeatureExtractor,Kg as ClapModel,eo as ClapPreTrainedModel,Ta as ClapTextModelWithProjection,sp as ClassifierFreeGuidanceLogitsProcessor,sw as CodeGenForCausalLM,rw as CodeGenModel,Ia as CodeGenPreTrainedModel,$m as CodeGenTokenizer,zm as CodeLlamaTokenizer,iw as Cohere2ForCausalLM,aw as Cohere2Model,Pa as Cohere2PreTrainedModel,E_ as CohereAsrFeatureExtractor,cw as CohereAsrForConditionalGeneration,lw as CohereAsrModel,Na as CohereAsrPreTrainedModel,z_ as CohereAsrProcessor,Bm as CohereAsrTokenizer,ow as CohereForCausalLM,nw as CohereModel,Ca as CoherePreTrainedModel,Rm as CohereTokenizer,pw as ConvBertForMaskedLM,mw as ConvBertForQuestionAnswering,fw as ConvBertForSequenceClassification,dw as ConvBertForTokenClassification,uw as ConvBertModel,is as ConvBertPreTrainedModel,Dm as ConvBertTokenizer,q_ as ConvNextFeatureExtractor,hw as ConvNextForImageClassification,Au as ConvNextImageProcessor,_w as ConvNextModel,La as ConvNextPreTrainedModel,ww as ConvNextV2ForImageClassification,gw as ConvNextV2Model,za as ConvNextV2PreTrainedModel,vw as DFineForObjectDetection,bw as DFineModel,Ra as DFinePreTrainedModel,Yw as DINOv3ConvNextModel,vp as DINOv3ConvNextPreTrainedModel,H_ as DINOv3ViTImageProcessor,Qw as DINOv3ViTModel,kp as DINOv3ViTPreTrainedModel,K_ as DPTFeatureExtractor,ox as DPTForDepthEstimation,Mu as DPTImageProcessor,nx as DPTModel,Wa as DPTPreTrainedModel,Da as DacDecoderModel,gp as DacDecoderOutput,Ba as DacEncoderModel,hp as DacEncoderOutput,sa as DacFeatureExtractor,kw as DacModel,to as DacPreTrainedModel,Aw as DebertaForMaskedLM,Mw as DebertaForQuestionAnswering,Tw as DebertaForSequenceClassification,Sw as DebertaForTokenClassification,Ew as DebertaModel,ls as DebertaPreTrainedModel,Fm as DebertaTokenizer,Lw as DebertaV2ForMaskedLM,Rw as DebertaV2ForQuestionAnswering,zw as DebertaV2ForSequenceClassification,$w as DebertaV2ForTokenClassification,Nw as DebertaV2Model,cs as DebertaV2PreTrainedModel,Um as DebertaV2Tokenizer,Bw as DecisionTransformerModel,wp as DecisionTransformerPreTrainedModel,Iw as DeepseekV3ForCausalLM,Ow as DeepseekV3Model,Ua as DeepseekV3PreTrainedModel,Pw as DeepseekV4ForCausalLM,Cw as DeepseekV4Model,Fa as DeepseekV4PreTrainedModel,W_ as DeiTFeatureExtractor,Uw as DeiTForImageClassification,Tu as DeiTImageProcessor,Dw as DeiTModel,Ga as DeiTPreTrainedModel,Fw as DepthAnythingForDepthEstimation,xp as DepthAnythingPreTrainedModel,fc as DepthEstimationPipeline,Gw as DepthProForDepthEstimation,yp as DepthProPreTrainedModel,V_ as DetrFeatureExtractor,qw as DetrForObjectDetection,Ww as DetrForSegmentation,Su as DetrImageProcessor,jw as DetrModel,so as DetrObjectDetectionOutput,ro as DetrPreTrainedModel,bp as DetrSegmentationOutput,Hw as Dinov2ForImageClassification,Vw as Dinov2Model,ja as Dinov2PreTrainedModel,Kw as Dinov2WithRegistersForImageClassification,Xw as Dinov2WithRegistersModel,qa as Dinov2WithRegistersPreTrainedModel,rx as DistilBertForMaskedLM,tx as DistilBertForQuestionAnswering,Zw as DistilBertForSequenceClassification,ex as DistilBertForTokenClassification,Jw as DistilBertModel,us as DistilBertPreTrainedModel,Gm as DistilBertTokenizer,uc as DocumentQuestionAnsweringPipeline,X_ as DonutFeatureExtractor,Bn as DonutImageProcessor,sx as DonutSwinModel,Ep as DonutSwinPreTrainedModel,Kn as DynamicCache,T1 as EdgeTamModel,ix as EfficientNetForImageClassification,Y_ as EfficientNetImageProcessor,ax as EfficientNetModel,Va as EfficientNetPreTrainedModel,cx as ElectraForMaskedLM,fx as ElectraForQuestionAnswering,ux as ElectraForSequenceClassification,px as ElectraForTokenClassification,lx as ElectraModel,ps as ElectraPreTrainedModel,jm as ElectraTokenizer,Ha as EmbeddingGemma2Model,Ap as EmbeddingGemma2PreTrainedModel,R_ as EmbeddingGemma2Processor,ca as EmbeddingGemma2VideoProcessor,ta as EncodecFeatureExtractor,ap as EosTokenCriteria,mx as Ernie4_5ForCausalLM,dx as Ernie4_5Model,Xa as Ernie4_5PretrainedModel,hx as EsmForMaskedLM,gx as EsmForSequenceClassification,wx as EsmForTokenClassification,_x as EsmModel,tn as EsmPreTrainedModel,qm as EsmTokenizer,yx as EuroBertForMaskedLM,bx as EuroBertForSequenceClassification,vx as EuroBertForTokenClassification,xx as EuroBertModel,rn as EuroBertPreTrainedModel,Ex as ExaoneForCausalLM,kx as ExaoneModel,Ka as ExaonePreTrainedModel,Tx as FalconForCausalLM,Mx as FalconH1ForCausalLM,Sx as FalconH1Model,Qa as FalconH1PreTrainedModel,Ax as FalconModel,Ya as FalconPreTrainedModel,Wm as FalconTokenizer,Ix as FastViTForImageClassification,Ox as FastViTModel,Ja as FastViTPreTrainedModel,dc as FeatureExtractionPipeline,Oe as FeatureExtractor,Kl as FillMaskPipeline,Cx as Florence2ForConditionalGeneration,Tp as Florence2PreTrainedModel,Ih as Florence2Processor,Xu as ForcedBOSTokenLogitsProcessor,Ku as ForcedEOSTokenLogitsProcessor,Z_ as GLPNFeatureExtractor,Xx as GLPNForDepthEstimation,Hx as GLPNModel,oi as GLPNPreTrainedModel,ny as GPT2LMHeadModel,sy as GPT2Model,ui as GPT2PreTrainedModel,Xm as GPT2Tokenizer,Yx as GPTBigCodeForCausalLM,Kx as GPTBigCodeModel,ai as GPTBigCodePreTrainedModel,ay as GPTJForCausalLM,oy as GPTJModel,pi as GPTJPreTrainedModel,Jx as GPTNeoForCausalLM,Qx as GPTNeoModel,ii as GPTNeoPreTrainedModel,ey as GPTNeoXForCausalLM,Zx as GPTNeoXModel,li as GPTNeoXPreTrainedModel,Hm as GPTNeoXTokenizer,zx as Gemma2ForCausalLM,Lx as Gemma2Model,ei as Gemma2PreTrainedModel,Dx as Gemma3ForCausalLM,Op as Gemma3ForConditionalGeneration,Q_ as Gemma3ImageProcessor,Bx as Gemma3Model,Mp as Gemma3PreTrainedModel,Ch as Gemma3Processor,na as Gemma3nAudioFeatureExtractor,Ux as Gemma3nForCausalLM,fs as Gemma3nForConditionalGeneration,Ip as Gemma3nPreTrainedModel,Ph as Gemma3nProcessor,oa as Gemma4AudioFeatureExtractor,Fx as Gemma4ForCausalLM,no as Gemma4ForConditionalGeneration,qs as Gemma4ImageProcessor,la as Gemma4Processor,Nx as GemmaForCausalLM,Px as GemmaModel,Za as GemmaPreTrainedModel,Vm as GemmaTokenizer,Ks as GenerationConfig,J_ as Glm46VImageProcessor,Nh as Glm46VProcessor,jx as GlmForCausalLM,Gx as GlmModel,Wx as GlmMoeDsaForCausalLM,qx as GlmMoeDsaModel,ri as GlmMoeDsaPreTrainedModel,Vx as GlmOcrForConditionalGeneration,ti as GlmPreTrainedModel,ry as GptOssForCausalLM,ty as GptOssModel,ci as GptOssPreTrainedModel,ly as GraniteForCausalLM,iy as GraniteModel,uy as GraniteMoeHybridForCausalLM,cy as GraniteMoeHybridModel,di as GraniteMoeHybridPreTrainedModel,fi as GranitePreTrainedModel,A_ as GraniteSpeechFeatureExtractor,py as GraniteSpeechForConditionalGeneration,Lh as GraniteSpeechProcessor,fy as GroundingDinoForObjectDetection,eh as GroundingDinoImageProcessor,Np as GroundingDinoPreTrainedModel,zh as GroundingDinoProcessor,dy as GroupViTModel,Lp as GroupViTPreTrainedModel,_y as HeliumForCausalLM,my as HeliumModel,mi as HeliumPreTrainedModel,Km as HerbertTokenizer,gy as HieraForImageClassification,hy as HieraModel,_i as HieraPreTrainedModel,xy as HrmTextForCausalLM,wy as HrmTextModel,hi as HrmTextPreTrainedModel,Ty as HubertForCTC,Sy as HubertForSequenceClassification,Ay as HubertModel,Ey as HubertPreTrainedModel,Oy as HunYuanDenseV1ForCausalLM,My as HunYuanDenseV1Model,gi as HunYuanDenseV1PreTrainedModel,Cy as IJepaForImageClassification,Iy as IJepaModel,xi as IJepaPreTrainedModel,wi as Idefics3ForConditionalGeneration,Ou as Idefics3ImageProcessor,Du as Idefics3Processor,oc as ImageClassificationPipeline,mc as ImageFeatureExtractionPipeline,X as ImageFeatureExtractor,Vn as ImageMattingOutput,X as ImageProcessor,fn as ImageSegmentationPipeline,pc as ImageToImagePipeline,nc as ImageToTextPipeline,dM as InterruptableStoppingCriteria,Ny as JAISLMHeadModel,Py as JAISModel,yi as JAISPreTrainedModel,rh as JinaCLIPImageProcessor,Ly as JinaCLIPModel,ao as JinaCLIPPreTrainedModel,Rh as JinaCLIPProcessor,bi as JinaCLIPTextModel,zy as JinaCLIPVisionModel,Ry as Lfm2ForCausalLM,$y as Lfm2Model,Uy as Lfm2MoeForCausalLM,Dy as Lfm2MoeModel,ki as Lfm2MoePreTrainedModel,vi as Lfm2PreTrainedModel,Fy as Lfm2VlForConditionalGeneration,sh as Lfm2VlImageProcessor,Bh as Lfm2VlProcessor,jy as Lfm3ForCausalLM,Gy as Lfm3Model,Ei as Lfm3PreTrainedModel,qy as Lfm3VlForConditionalGeneration,nh as Lfm3VlImageProcessor,Dh as Lfm3VlProcessor,By as LightOnOcrForConditionalGeneration,Gv as LiteWhisperForConditionalGeneration,Hy as Llama4ForCausalLM,zp as Llama4PreTrainedModel,Vy as LlamaForCausalLM,Wy as LlamaModel,Ai as LlamaPreTrainedModel,Ym as LlamaTokenizer,ut as LlavaForConditionalGeneration,ut as LlavaOnevisionForConditionalGeneration,oh as LlavaOnevisionImageProcessor,Sp as LlavaPreTrainedModel,Uh as LlavaProcessor,Rx as LlavaQwen2ForCausalLM,It as LogLevel,Dt as LogitsProcessor,Xs as LogitsProcessorList,da as LogitsWarper,Ky as LongT5ForConditionalGeneration,Xy as LongT5Model,Ti as LongT5PreTrainedModel,Qy as M2M100ForConditionalGeneration,Yy as M2M100Model,Si as M2M100PreTrainedModel,Qm as M2M100Tokenizer,Zm as MBart50Tokenizer,o0 as MBartForCausalLM,s0 as MBartForConditionalGeneration,n0 as MBartForSequenceClassification,r0 as MBartModel,on as MBartPreTrainedModel,Jo as MBartTokenizer,Y0 as MPNetForMaskedLM,Z0 as MPNetForQuestionAnswering,Q0 as MPNetForSequenceClassification,J0 as MPNetForTokenClassification,K0 as MPNetModel,ds as MPNetPreTrainedModel,r_ as MPNetTokenizer,sb as MT5ForConditionalGeneration,rb as MT5Model,Gi as MT5PreTrainedModel,Zy as MarianMTModel,Jy as MarianModel,Mi as MarianPreTrainedModel,Jm as MarianTokenizer,ih as Mask2FormerImageProcessor,ah as MaskFormerFeatureExtractor,t0 as MaskFormerForInstanceSegmentation,Dn as MaskFormerImageProcessor,e0 as MaskFormerModel,Oi as MaskFormerPreTrainedModel,ye as MaskedLMOutput,op as MaxLengthCriteria,a0 as Metric3DForDepthEstimation,$p as Metric3DPreTrainedModel,i0 as Metric3Dv2ForDepthEstimation,Rp as Metric3Dv2PreTrainedModel,l0 as MgpstrForSceneTextRecognition,Bp as MgpstrModelOutput,Dp as MgpstrPreTrainedModel,Fh as MgpstrProcessor,e_ as MgpstrTokenizer,Ci as MimiDecoderModel,Fp as MimiDecoderOutput,Ii as MimiEncoderModel,Up as MimiEncoderOutput,c0 as MimiModel,io as MimiPreTrainedModel,ep as MinLengthLogitsProcessor,tp as MinNewTokensLengthLogitsProcessor,d0 as Ministral3ForCausalLM,f0 as Ministral3Model,Ni as Ministral3PreTrainedModel,p0 as MinistralForCausalLM,u0 as MinistralModel,Pi as MinistralPreTrainedModel,h0 as Mistral3ForConditionalGeneration,w0 as Mistral4ForCausalLM,g0 as Mistral4Model,zi as Mistral4PreTrainedModel,_0 as MistralForCausalLM,m0 as MistralModel,Li as MistralPreTrainedModel,y0 as MobileBertForMaskedLM,v0 as MobileBertForQuestionAnswering,b0 as MobileBertForSequenceClassification,x0 as MobileBertModel,an as MobileBertPreTrainedModel,t_ as MobileBertTokenizer,E0 as MobileLLMForCausalLM,k0 as MobileLLMModel,$i as MobileLLMPreTrainedModel,lh as MobileNetV1FeatureExtractor,T0 as MobileNetV1ForImageClassification,S0 as MobileNetV1ForSemanticSegmentation,Iu as MobileNetV1ImageProcessor,A0 as MobileNetV1Model,lo as MobileNetV1PreTrainedModel,ch as MobileNetV2FeatureExtractor,O0 as MobileNetV2ForImageClassification,I0 as MobileNetV2ForSemanticSegmentation,Cu as MobileNetV2ImageProcessor,M0 as MobileNetV2Model,co as MobileNetV2PreTrainedModel,uh as MobileNetV3FeatureExtractor,P0 as MobileNetV3ForImageClassification,N0 as MobileNetV3ForSemanticSegmentation,Pu as MobileNetV3ImageProcessor,C0 as MobileNetV3Model,uo as MobileNetV3PreTrainedModel,ph as MobileNetV4FeatureExtractor,z0 as MobileNetV4ForImageClassification,$0 as MobileNetV4ForSemanticSegmentation,Nu as MobileNetV4ImageProcessor,L0 as MobileNetV4Model,po as MobileNetV4PreTrainedModel,fh as MobileViTFeatureExtractor,B0 as MobileViTForImageClassification,Lu as MobileViTImageProcessor,R0 as MobileViTModel,Ri as MobileViTPreTrainedModel,U0 as MobileViTV2ForImageClassification,D0 as MobileViTV2Model,Bi as MobileViTV2PreTrainedModel,Is as ModelFileNotFoundError,Se as ModelOutput,lk as ModelRegistry,V0 as ModernBertDecoderForCausalLM,W0 as ModernBertDecoderModel,Di as ModernBertDecoderPreTrainedModel,G0 as ModernBertForMaskedLM,j0 as ModernBertForSequenceClassification,q0 as ModernBertForTokenClassification,F0 as ModernBertModel,ln as ModernBertPreTrainedModel,$x as Moondream1ForConditionalGeneration,T_ as MoonshineFeatureExtractor,X0 as MoonshineForConditionalGeneration,H0 as MoonshineModel,Ui as MoonshinePreTrainedModel,Gh as MoonshineProcessor,tb as MptForCausalLM,eb as MptModel,Fi as MptPreTrainedModel,nb as MultiModalityCausalLM,Gp as MultiModalityPreTrainedModel,ab as MusicgenForCausalLM,qi as MusicgenForConditionalGeneration,ob as MusicgenModel,ji as MusicgenPreTrainedModel,lb as NanoChatForCausalLM,ib as NanoChatModel,Wi as NanoChatPreTrainedModel,ub as NemotronHForCausalLM,cb as NemotronHModel,Vi as NemotronHPreTrainedModel,fb as NeoBertForMaskedLM,_b as NeoBertForQuestionAnswering,db as NeoBertForSequenceClassification,mb as NeoBertForTokenClassification,pb as NeoBertModel,ms as NeoBertPreTrainedModel,s_ as NllbTokenizer,rp as NoBadWordsLogitsProcessor,Ju as NoRepeatNGramLogitsProcessor,hb as NomicBertModel,jp as NomicBertPreTrainedModel,dh as NougatImageProcessor,n_ as NougatTokenizer,Ib as OPTForCausalLM,Ob as OPTModel,Zi as OPTPreTrainedModel,lc as ObjectDetectionPipeline,yb as Olmo2ForCausalLM,xb as Olmo2Model,Xi as Olmo2PreTrainedModel,vb as Olmo3ForCausalLM,bb as Olmo3Model,Ki as Olmo3PreTrainedModel,wb as OlmoForCausalLM,Eb as OlmoHybridForCausalLM,kb as OlmoHybridModel,Yi as OlmoHybridPreTrainedModel,gb as OlmoModel,Hi as OlmoPreTrainedModel,Tb as OpenAIPrivacyFilterForTokenClassification,Ab as OpenAIPrivacyFilterModel,Qi as OpenAIPrivacyFilterPreTrainedModel,Mb as OpenELMForCausalLM,Sb as OpenELMModel,Ji as OpenELMPreTrainedModel,mh as OwlViTFeatureExtractor,Lb as OwlViTForObjectDetection,Un as OwlViTImageProcessor,Nb as OwlViTModel,tl as OwlViTPreTrainedModel,jh as OwlViTProcessor,Pb as Owlv2ForObjectDetection,_h as Owlv2ImageProcessor,Cb as Owlv2Model,el as Owlv2PreTrainedModel,zb as PaliGemmaForConditionalGeneration,qh as PaliGemmaProcessor,ra as ParakeetFeatureExtractor,$b as ParakeetForCTC,qp as ParakeetPreTrainedModel,Bb as PatchTSMixerForPrediction,Rb as PatchTSMixerModel,rl as PatchTSMixerPreTrainedModel,Ub as PatchTSTForPrediction,Db as PatchTSTModel,sl as PatchTSTPreTrainedModel,qb as Phi3ForCausalLM,jb as Phi3Model,ol as Phi3PreTrainedModel,al as Phi3VForCausalLM,wh as Phi3VImageProcessor,Wp as Phi3VPreTrainedModel,Wh as Phi3VProcessor,Gb as PhiForCausalLM,Fb as PhiModel,nl as PhiPreTrainedModel,xh as PixtralImageProcessor,Vh as PixtralProcessor,y as PreTrainedModel,V as PreTrainedTokenizer,Wn as PretrainedConfig,se as Processor,Vb as PvtForImageClassification,yh as PvtImageProcessor,Wb as PvtModel,il as PvtPreTrainedModel,aa as PyAnnoteFeatureExtractor,Xb as PyAnnoteForAudioFrameClassification,Hb as PyAnnoteModel,ll as PyAnnotePreTrainedModel,Hh as PyAnnoteProcessor,Me as QuestionAnsweringModelOutput,Xl as QuestionAnsweringPipeline,Yb as Qwen2ForCausalLM,Kb as Qwen2Model,Jb as Qwen2MoeForCausalLM,Qb as Qwen2MoeModel,ul as Qwen2MoePreTrainedModel,cl as Qwen2PreTrainedModel,o_ as Qwen2Tokenizer,si as Qwen2VLForCausalLM,oo as Qwen2VLForConditionalGeneration,Ws as Qwen2VLImageProcessor,Cp as Qwen2VLPreTrainedModel,Vs as Qwen2VLProcessor,ni as Qwen2_5_VLForCausalLM,sn as Qwen2_5_VLForConditionalGeneration,pa as Qwen2_5_VLProcessor,e1 as Qwen3ForCausalLM,Zb as Qwen3Model,r1 as Qwen3MoeForCausalLM,t1 as Qwen3MoeModel,fl as Qwen3MoePreTrainedModel,n1 as Qwen3NextForCausalLM,s1 as Qwen3NextModel,dl as Qwen3NextPreTrainedModel,pl as Qwen3PreTrainedModel,ml as Qwen3VLForCausalLM,cn as Qwen3VLForConditionalGeneration,a1 as Qwen3VLMoeForCausalLM,o1 as Qwen3VLMoeForConditionalGeneration,Xh as Qwen3VLProcessor,_l as Qwen3_5ForCausalLM,fo as Qwen3_5ForConditionalGeneration,l1 as Qwen3_5MoeForCausalLM,i1 as Qwen3_5MoeForConditionalGeneration,f1 as RFDetrForObjectDetection,p1 as RFDetrModel,Vp as RFDetrObjectDetectionOutput,gl as RFDetrPreTrainedModel,yw as RTDetrForObjectDetection,bh as RTDetrImageProcessor,xw as RTDetrModel,xr as RTDetrObjectDetectionOutput,$a as RTDetrPreTrainedModel,E1 as RTDetrV2ForObjectDetection,k1 as RTDetrV2Model,Hp as RTDetrV2ObjectDetectionOutput,wl as RTDetrV2PreTrainedModel,ea as RawAudio,rt as RawImage,Nf as RawVideo,_c as RawVideoFrame,Zu as RepetitionPenaltyLogitsProcessor,u1 as ResNetForImageClassification,c1 as ResNetModel,hl as ResNetPreTrainedModel,x1 as RoFormerForMaskedLM,v1 as RoFormerForQuestionAnswering,y1 as RoFormerForSequenceClassification,b1 as RoFormerForTokenClassification,w1 as RoFormerModel,hs as RoFormerPreTrainedModel,i_ as RoFormerTokenizer,m1 as RobertaForMaskedLM,g1 as RobertaForQuestionAnswering,_1 as RobertaForSequenceClassification,h1 as RobertaForTokenClassification,d1 as RobertaModel,_s as RobertaPreTrainedModel,a_ as RobertaTokenizer,ua as Sam2ImageProcessor,Yp as Sam2ImageSegmentationOutput,xl as Sam2Model,Qp as Sam2PreTrainedModel,Uu as Sam2Processor,Kh as Sam2VideoProcessor,ua as Sam3ImageProcessor,S1 as Sam3TrackerModel,ua as SamImageProcessor,Xp as SamImageSegmentationOutput,A1 as SamModel,Kp as SamPreTrainedModel,fa as SamProcessor,vh as SapiensFeatureExtractor,O1 as SapiensForDepthEstimation,I1 as SapiensForNormalEstimation,M1 as SapiensForSemanticSegmentation,zu as SapiensImageProcessor,mo as SapiensPreTrainedModel,S_ as SeamlessM4TFeatureExtractor,kh as SegformerFeatureExtractor,P1 as SegformerForImageClassification,N1 as SegformerForSemanticSegmentation,$u as SegformerImageProcessor,C1 as SegformerModel,_o as SegformerPreTrainedModel,Hu as Seq2SeqLMOutput,q as SequenceClassifierOutput,Eh as SiglipImageProcessor,L1 as SiglipModel,yl as SiglipPreTrainedModel,bl as SiglipTextModel,l_ as SiglipTokenizer,z1 as SiglipVisionModel,R1 as SmolLM3ForCausalLM,$1 as SmolLM3Model,vl as SmolLM3PreTrainedModel,B1 as SmolVLMForConditionalGeneration,Ou as SmolVLMImageProcessor,Du as SmolVLMProcessor,El as SnacDecoderModel,kl as SnacEncoderModel,M_ as SnacFeatureExtractor,D1 as SnacModel,ho as SnacPreTrainedModel,F1 as SolarOpenForCausalLM,U1 as SolarOpenModel,Al as SolarOpenPreTrainedModel,O_ as SpeechT5FeatureExtractor,j1 as SpeechT5ForSpeechToText,q1 as SpeechT5ForTextToSpeech,W1 as SpeechT5HifiGan,G1 as SpeechT5Model,go as SpeechT5PreTrainedModel,Yh as SpeechT5Processor,c_ as SpeechT5Tokenizer,H1 as SqueezeBertForMaskedLM,K1 as SqueezeBertForQuestionAnswering,X1 as SqueezeBertForSequenceClassification,V1 as SqueezeBertModel,un as SqueezeBertPreTrainedModel,u_ as SqueezeBertTokenizer,Q1 as StableLmForCausalLM,Y1 as StableLmModel,Tl as StableLmPreTrainedModel,Z1 as Starcoder2ForCausalLM,J1 as Starcoder2Model,Sl as Starcoder2PreTrainedModel,ss as StoppingCriteria,Xn as StoppingCriteriaList,ev as StyleTextToSpeech2Model,Jp as StyleTextToSpeech2PreTrainedModel,Yl as SummarizationPipeline,Ml as SupertonicForConditionalGeneration,Zp as SupertonicPreTrainedModel,Hn as SuppressTokensAtBeginLogitsProcessor,Yu as SuppressTokensLogitsProcessor,ov as Swin2SRForImageSuperResolution,Ah as Swin2SRImageProcessor,nv as Swin2SRModel,Ol as Swin2SRPreTrainedModel,rv as SwinForImageClassification,sv as SwinForSemanticSegmentation,tv as SwinModel,wo as SwinPreTrainedModel,iv as T5ForConditionalGeneration,av as T5Model,Il as T5PreTrainedModel,p_ as T5Tokenizer,cv as TableTransformerForObjectDetection,lv as TableTransformerModel,ef as TableTransformerObjectDetectionOutput,Cl as TableTransformerPreTrainedModel,np as TemperatureLogitsWarper,$ as Tensor,Cr as Text2TextGenerationPipeline,Vl as TextClassificationPipeline,Jl as TextGenerationPipeline,ik as TextStreamer,sc as TextToAudioPipeline,Hl as TokenClassificationPipeline,we as TokenClassifierOutput,V as TokenizersBackend,fM as TopKLogitsWarper,pM as TopPLogitsWarper,uv as TrOCRForCausalLM,tf as TrOCRPreTrainedModel,Ql as TranslationPipeline,nn as UltravoxModel,Pp as UltravoxPreTrainedModel,Qh as UltravoxProcessor,fv as UniSpeechForCTC,dv as UniSpeechForSequenceClassification,pv as UniSpeechModel,xo as UniSpeechPreTrainedModel,gv as UniSpeechSatForAudioFrameClassification,_v as UniSpeechSatForCTC,hv as UniSpeechSatForSequenceClassification,mv as UniSpeechSatModel,pn as UniSpeechSatPreTrainedModel,$h as VLChatProcessor,th as VLMImageProcessor,xv as VaultGemmaForCausalLM,wv as VaultGemmaModel,Pl as VaultGemmaPreTrainedModel,Th as ViTFeatureExtractor,vv as ViTForImageClassification,Ru as ViTImageProcessor,kv as ViTMAEModel,rf as ViTMAEPreTrainedModel,Av as ViTMSNForImageClassification,Ev as ViTMSNModel,Ll as ViTMSNPreTrainedModel,bv as ViTModel,Nl as ViTPreTrainedModel,yv as VisionEncoderDecoderModel,Tv as VitMatteForImageMatting,Sh as VitMatteImageProcessor,sf as VitMattePreTrainedModel,Sv as VitPoseForPoseEstimation,Mh as VitPoseImageProcessor,nf as VitPosePreTrainedModel,Mv as VitsModel,of as VitsModelOutput,af as VitsPreTrainedModel,d_ as VitsTokenizer,Ov as VoxtralForConditionalGeneration,Jh as VoxtralProcessor,P_ as VoxtralRealtimeFeatureExtractor,zl as VoxtralRealtimeForConditionalGeneration,lf as VoxtralRealtimePreTrainedModel,eg as VoxtralRealtimeProcessor,Nv as Wav2Vec2BertForCTC,Lv as Wav2Vec2BertForSequenceClassification,Pv as Wav2Vec2BertModel,yo as Wav2Vec2BertPreTrainedModel,m_ as Wav2Vec2CTCTokenizer,I_ as Wav2Vec2FeatureExtractor,ky as Wav2Vec2ForAudioFrameClassification,by as Wav2Vec2ForCTC,vy as Wav2Vec2ForSequenceClassification,yy as Wav2Vec2Model,ir as Wav2Vec2PreTrainedModel,tg as Wav2Vec2Processor,rg as Wav2Vec2ProcessorWithLM,Dv as WavLMForAudioFrameClassification,$v as WavLMForCTC,Rv as WavLMForSequenceClassification,Bv as WavLMForXVector,zv as WavLMModel,gs as WavLMPreTrainedModel,C_ as WeSpeakerFeatureExtractor,Uv as WeSpeakerResNetModel,uf as WeSpeakerResNetPreTrainedModel,N_ as WhisperFeatureExtractor,ff as WhisperForConditionalGeneration,Fv as WhisperModel,$l as WhisperPreTrainedModel,sg as WhisperProcessor,cO as WhisperTextStreamer,Qu as WhisperTimeStampLogitsProcessor,__ as WhisperTokenizer,Hv as XLMForQuestionAnswering,Wv as XLMForSequenceClassification,Vv as XLMForTokenClassification,jv as XLMModel,ws as XLMPreTrainedModel,Kv as XLMRobertaForMaskedLM,Jv as XLMRobertaForQuestionAnswering,Yv as XLMRobertaForSequenceClassification,Qv as XLMRobertaForTokenClassification,Xv as XLMRobertaModel,xs as XLMRobertaPreTrainedModel,h_ as XLMRobertaTokenizer,g_ as XLMTokenizer,qv as XLMWithLMHeadModel,cf as XVectorOutput,Oh as YolosFeatureExtractor,ek as YolosForObjectDetection,Bu as YolosImageProcessor,Zv as YolosModel,df as YolosObjectDetectionOutput,Rl as YolosPreTrainedModel,rk as YoutuForCausalLM,tk as YoutuModel,Bl as YoutuPreTrainedModel,nk as ZayaForCausalLM,sk as ZayaModel,Dl as ZayaPreTrainedModel,tc as ZeroShotAudioClassificationPipeline,Zl as ZeroShotClassificationPipeline,ic as ZeroShotImageClassificationPipeline,cc as ZeroShotObjectDetectionPipeline,Ee as cat,b$ as cos_sim,D2 as dot,he as env,Ze as full,Ko as full_like,vm as interpolate,Tt as interpolate_4d,ZU as layer_norm,QS as load_audio,TR as load_image,v3 as load_video,Sd as log_softmax,US as matmul,mu as mean,FS as mean_pooling,st as ones,Ln as ones_like,sR as permute,rde as pipeline,jS as quantize_embeddings,e6 as rand,GS as randn,Os as random,y_ as read_audio,JU as rfft,du as slice,Ue as softmax,kt as stack,km as std_mean,or as topk,Am as zeros,Yo as zeros_like}; diff --git a/vendor/xterm/LICENSE.txt b/vendor/xterm/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..4472336c9f3dee53c82f951cff3d9ddbadc65614 --- /dev/null +++ b/vendor/xterm/LICENSE.txt @@ -0,0 +1,21 @@ +Copyright (c) 2017-2019, The xterm.js authors (https://github.com/xtermjs/xterm.js) +Copyright (c) 2014-2016, SourceLair Private Company (https://www.sourcelair.com) +Copyright (c) 2012-2013, Christopher Jeffrey (https://github.com/chjj/) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/vendor/xterm/addon-fit.mjs b/vendor/xterm/addon-fit.mjs new file mode 100644 index 0000000000000000000000000000000000000000..24d4f61877d369edb7f2773570575a1c10edf832 --- /dev/null +++ b/vendor/xterm/addon-fit.mjs @@ -0,0 +1,18 @@ +/** + * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved. + * @license MIT + * + * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License) + * @license MIT + * + * Originally forked from (with the author's permission): + * Fabrice Bellard's javascript vt100 for jslinux: + * http://bellard.org/jslinux/ + * Copyright (c) 2011 Fabrice Bellard + */ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +var h=2,_=1,o=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let t=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let t=this._terminal._core._renderService.dimensions;if(t.css.cell.width===0||t.css.cell.height===0)return;let s=this._terminal.options.scrollback===0?0:this._terminal.options.overviewRuler?.width||14,r=window.getComputedStyle(this._terminal.element.parentElement),l=parseInt(r.getPropertyValue("height")),a=Math.max(0,parseInt(r.getPropertyValue("width"))),i=window.getComputedStyle(this._terminal.element),n={top:parseInt(i.getPropertyValue("padding-top")),bottom:parseInt(i.getPropertyValue("padding-bottom")),right:parseInt(i.getPropertyValue("padding-right")),left:parseInt(i.getPropertyValue("padding-left"))},m=n.top+n.bottom,d=n.right+n.left,c=l-m,p=a-d-s;return{cols:Math.max(h,Math.floor(p/t.css.cell.width)),rows:Math.max(_,Math.floor(c/t.css.cell.height))}}};export{o as FitAddon}; +//# sourceMappingURL=addon-fit.mjs.map diff --git a/vendor/xterm/xterm.css b/vendor/xterm/xterm.css new file mode 100644 index 0000000000000000000000000000000000000000..819654e4537eeb7b64364249e52274b7197b9c8a --- /dev/null +++ b/vendor/xterm/xterm.css @@ -0,0 +1,285 @@ +/** + * Copyright (c) 2014 The xterm.js authors. All rights reserved. + * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License) + * https://github.com/chjj/term.js + * @license MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * Originally forked from (with the author's permission): + * Fabrice Bellard's javascript vt100 for jslinux: + * http://bellard.org/jslinux/ + * Copyright (c) 2011 Fabrice Bellard + * The original design remains. The terminal itself + * has been extended to include xterm CSI codes, among + * other features. + */ + +/** + * Default styles for xterm.js + */ + +.xterm { + cursor: text; + position: relative; + user-select: none; + -ms-user-select: none; + -webkit-user-select: none; +} + +.xterm.focus, +.xterm:focus { + outline: none; +} + +.xterm .xterm-helpers { + position: absolute; + top: 0; + /** + * The z-index of the helpers must be higher than the canvases in order for + * IMEs to appear on top. + */ + z-index: 5; +} + +.xterm .xterm-helper-textarea { + padding: 0; + border: 0; + margin: 0; + /* Move textarea out of the screen to the far left, so that the cursor is not visible */ + position: absolute; + opacity: 0; + left: -9999em; + top: 0; + width: 0; + height: 0; + z-index: -5; + /** Prevent wrapping so the IME appears against the textarea at the correct position */ + white-space: nowrap; + overflow: hidden; + resize: none; +} + +.xterm .composition-view { + /* TODO: Composition position got messed up somewhere */ + background: #000; + color: #FFF; + display: none; + position: absolute; + white-space: nowrap; + z-index: 1; +} + +.xterm .composition-view.active { + display: block; +} + +.xterm .xterm-viewport { + /* On OS X this is required in order for the scroll bar to appear fully opaque */ + background-color: #000; + overflow-y: scroll; + cursor: default; + position: absolute; + right: 0; + left: 0; + top: 0; + bottom: 0; +} + +.xterm .xterm-screen { + position: relative; +} + +.xterm .xterm-screen canvas { + position: absolute; + left: 0; + top: 0; +} + +.xterm-char-measure-element { + display: inline-block; + visibility: hidden; + position: absolute; + top: 0; + left: -9999em; + line-height: normal; +} + +.xterm.enable-mouse-events { + /* When mouse events are enabled (eg. tmux), revert to the standard pointer cursor */ + cursor: default; +} + +.xterm.xterm-cursor-pointer, +.xterm .xterm-cursor-pointer { + cursor: pointer; +} + +.xterm.column-select.focus { + /* Column selection mode */ + cursor: crosshair; +} + +.xterm .xterm-accessibility:not(.debug), +.xterm .xterm-message { + position: absolute; + left: 0; + top: 0; + bottom: 0; + right: 0; + z-index: 10; + color: transparent; + pointer-events: none; +} + +.xterm .xterm-accessibility-tree:not(.debug) *::selection { + color: transparent; +} + +.xterm .xterm-accessibility-tree { + font-family: monospace; + user-select: text; + white-space: pre; +} + +.xterm .xterm-accessibility-tree > div { + transform-origin: left; + width: fit-content; +} + +.xterm .live-region { + position: absolute; + left: -9999px; + width: 1px; + height: 1px; + overflow: hidden; +} + +.xterm-dim { + /* Dim should not apply to background, so the opacity of the foreground color is applied + * explicitly in the generated class and reset to 1 here */ + opacity: 1 !important; +} + +.xterm-underline-1 { text-decoration: underline; } +.xterm-underline-2 { text-decoration: double underline; } +.xterm-underline-3 { text-decoration: wavy underline; } +.xterm-underline-4 { text-decoration: dotted underline; } +.xterm-underline-5 { text-decoration: dashed underline; } + +.xterm-overline { + text-decoration: overline; +} + +.xterm-overline.xterm-underline-1 { text-decoration: overline underline; } +.xterm-overline.xterm-underline-2 { text-decoration: overline double underline; } +.xterm-overline.xterm-underline-3 { text-decoration: overline wavy underline; } +.xterm-overline.xterm-underline-4 { text-decoration: overline dotted underline; } +.xterm-overline.xterm-underline-5 { text-decoration: overline dashed underline; } + +.xterm-strikethrough { + text-decoration: line-through; +} + +.xterm-screen .xterm-decoration-container .xterm-decoration { + z-index: 6; + position: absolute; +} + +.xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer { + z-index: 7; +} + +.xterm-decoration-overview-ruler { + z-index: 8; + position: absolute; + top: 0; + right: 0; + pointer-events: none; +} + +.xterm-decoration-top { + z-index: 2; + position: relative; +} + + + +/* Derived from vs/base/browser/ui/scrollbar/media/scrollbar.css */ + +/* xterm.js customization: Override xterm's cursor style */ +.xterm .xterm-scrollable-element > .scrollbar { + cursor: default; +} + +/* Arrows */ +.xterm .xterm-scrollable-element > .scrollbar > .scra { + cursor: pointer; + font-size: 11px !important; +} + +.xterm .xterm-scrollable-element > .visible { + opacity: 1; + + /* Background rule added for IE9 - to allow clicks on dom node */ + background:rgba(0,0,0,0); + + transition: opacity 100ms linear; + /* In front of peek view */ + z-index: 11; +} +.xterm .xterm-scrollable-element > .invisible { + opacity: 0; + pointer-events: none; +} +.xterm .xterm-scrollable-element > .invisible.fade { + transition: opacity 800ms linear; +} + +/* Scrollable Content Inset Shadow */ +.xterm .xterm-scrollable-element > .shadow { + position: absolute; + display: none; +} +.xterm .xterm-scrollable-element > .shadow.top { + display: block; + top: 0; + left: 3px; + height: 3px; + width: 100%; + box-shadow: var(--vscode-scrollbar-shadow, #000) 0 6px 6px -6px inset; +} +.xterm .xterm-scrollable-element > .shadow.left { + display: block; + top: 3px; + left: 0; + height: 100%; + width: 3px; + box-shadow: var(--vscode-scrollbar-shadow, #000) 6px 0 6px -6px inset; +} +.xterm .xterm-scrollable-element > .shadow.top-left-corner { + display: block; + top: 0; + left: 0; + height: 3px; + width: 3px; +} +.xterm .xterm-scrollable-element > .shadow.top.left { + box-shadow: var(--vscode-scrollbar-shadow, #000) 6px 0 6px -6px inset; +} diff --git a/vendor/xterm/xterm.mjs b/vendor/xterm/xterm.mjs new file mode 100644 index 0000000000000000000000000000000000000000..d54025622304faca5d168cdfc6d038525577ae03 --- /dev/null +++ b/vendor/xterm/xterm.mjs @@ -0,0 +1,53 @@ +/** + * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved. + * @license MIT + * + * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License) + * @license MIT + * + * Originally forked from (with the author's permission): + * Fabrice Bellard's javascript vt100 for jslinux: + * http://bellard.org/jslinux/ + * Copyright (c) 2011 Fabrice Bellard + */ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +var zs=Object.defineProperty;var Rl=Object.getOwnPropertyDescriptor;var Ll=(s,t)=>{for(var e in t)zs(s,e,{get:t[e],enumerable:!0})};var M=(s,t,e,i)=>{for(var r=i>1?void 0:i?Rl(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(r=(i?o(t,e,r):o(r))||r);return i&&r&&zs(t,e,r),r},S=(s,t)=>(e,i)=>t(e,i,s);var Gs="Terminal input",mi={get:()=>Gs,set:s=>Gs=s},$s="Too much output to announce, navigate to rows manually to read",_i={get:()=>$s,set:s=>$s=s};function Al(s){return s.replace(/\r?\n/g,"\r")}function kl(s,t){return t?"\x1B[200~"+s+"\x1B[201~":s}function Vs(s,t){s.clipboardData&&s.clipboardData.setData("text/plain",t.selectionText),s.preventDefault()}function qs(s,t,e,i){if(s.stopPropagation(),s.clipboardData){let r=s.clipboardData.getData("text/plain");Cn(r,t,e,i)}}function Cn(s,t,e,i){s=Al(s),s=kl(s,e.decPrivateModes.bracketedPasteMode&&i.rawOptions.ignoreBracketedPasteMode!==!0),e.triggerDataEvent(s,!0),t.value=""}function Mn(s,t,e){let i=e.getBoundingClientRect(),r=s.clientX-i.left-10,n=s.clientY-i.top-10;t.style.width="20px",t.style.height="20px",t.style.left=`${r}px`,t.style.top=`${n}px`,t.style.zIndex="1000",t.focus()}function Pn(s,t,e,i,r){Mn(s,t,e),r&&i.rightClickSelect(s),t.value=i.selectionText,t.select()}function Ce(s){return s>65535?(s-=65536,String.fromCharCode((s>>10)+55296)+String.fromCharCode(s%1024+56320)):String.fromCharCode(s)}function It(s,t=0,e=s.length){let i="";for(let r=t;r65535?(n-=65536,i+=String.fromCharCode((n>>10)+55296)+String.fromCharCode(n%1024+56320)):i+=String.fromCharCode(n)}return i}var er=class{constructor(){this._interim=0}clear(){this._interim=0}decode(t,e){let i=t.length;if(!i)return 0;let r=0,n=0;if(this._interim){let o=t.charCodeAt(n++);56320<=o&&o<=57343?e[r++]=(this._interim-55296)*1024+o-56320+65536:(e[r++]=this._interim,e[r++]=o),this._interim=0}for(let o=n;o=i)return this._interim=l,r;let a=t.charCodeAt(o);56320<=a&&a<=57343?e[r++]=(l-55296)*1024+a-56320+65536:(e[r++]=l,e[r++]=a);continue}l!==65279&&(e[r++]=l)}return r}},tr=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(t,e){let i=t.length;if(!i)return 0;let r=0,n,o,l,a,u=0,h=0;if(this.interim[0]){let _=!1,p=this.interim[0];p&=(p&224)===192?31:(p&240)===224?15:7;let m=0,f;for(;(f=this.interim[++m]&63)&&m<4;)p<<=6,p|=f;let A=(this.interim[0]&224)===192?2:(this.interim[0]&240)===224?3:4,R=A-m;for(;h=i)return 0;if(f=t[h++],(f&192)!==128){h--,_=!0;break}else this.interim[m++]=f,p<<=6,p|=f&63}_||(A===2?p<128?h--:e[r++]=p:A===3?p<2048||p>=55296&&p<=57343||p===65279||(e[r++]=p):p<65536||p>1114111||(e[r++]=p)),this.interim.fill(0)}let c=i-4,d=h;for(;d=i)return this.interim[0]=n,r;if(o=t[d++],(o&192)!==128){d--;continue}if(u=(n&31)<<6|o&63,u<128){d--;continue}e[r++]=u}else if((n&240)===224){if(d>=i)return this.interim[0]=n,r;if(o=t[d++],(o&192)!==128){d--;continue}if(d>=i)return this.interim[0]=n,this.interim[1]=o,r;if(l=t[d++],(l&192)!==128){d--;continue}if(u=(n&15)<<12|(o&63)<<6|l&63,u<2048||u>=55296&&u<=57343||u===65279)continue;e[r++]=u}else if((n&248)===240){if(d>=i)return this.interim[0]=n,r;if(o=t[d++],(o&192)!==128){d--;continue}if(d>=i)return this.interim[0]=n,this.interim[1]=o,r;if(l=t[d++],(l&192)!==128){d--;continue}if(d>=i)return this.interim[0]=n,this.interim[1]=o,this.interim[2]=l,r;if(a=t[d++],(a&192)!==128){d--;continue}if(u=(n&7)<<18|(o&63)<<12|(l&63)<<6|a&63,u<65536||u>1114111)continue;e[r++]=u}}return r}};var ir="";var we=" ";var De=class s{constructor(){this.fg=0;this.bg=0;this.extended=new rt}static toColorRGB(t){return[t>>>16&255,t>>>8&255,t&255]}static fromColorRGB(t){return(t[0]&255)<<16|(t[1]&255)<<8|t[2]&255}clone(){let t=new s;return t.fg=this.fg,t.bg=this.bg,t.extended=this.extended.clone(),t}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)===50331648}isBgRGB(){return(this.bg&50331648)===50331648}isFgPalette(){return(this.fg&50331648)===16777216||(this.fg&50331648)===33554432}isBgPalette(){return(this.bg&50331648)===16777216||(this.bg&50331648)===33554432}isFgDefault(){return(this.fg&50331648)===0}isBgDefault(){return(this.bg&50331648)===0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:case 33554432:return this.fg&255;case 50331648:return this.fg&16777215;default:return-1}}getBgColor(){switch(this.bg&50331648){case 16777216:case 33554432:return this.bg&255;case 50331648:return this.bg&16777215;default:return-1}}hasExtendedAttrs(){return this.bg&268435456}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(this.bg&268435456&&~this.extended.underlineColor)switch(this.extended.underlineColor&50331648){case 16777216:case 33554432:return this.extended.underlineColor&255;case 50331648:return this.extended.underlineColor&16777215;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return this.bg&268435456&&~this.extended.underlineColor?this.extended.underlineColor&50331648:this.getFgColorMode()}isUnderlineColorRGB(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===50331648:this.isFgRGB()}isUnderlineColorPalette(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===16777216||(this.extended.underlineColor&50331648)===33554432:this.isFgPalette()}isUnderlineColorDefault(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===0:this.isFgDefault()}getUnderlineStyle(){return this.fg&268435456?this.bg&268435456?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},rt=class s{constructor(t=0,e=0){this._ext=0;this._urlId=0;this._ext=t,this._urlId=e}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(t){this._ext=t}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(t){this._ext&=-469762049,this._ext|=t<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(t){this._ext&=-67108864,this._ext|=t&67108863}get urlId(){return this._urlId}set urlId(t){this._urlId=t}get underlineVariantOffset(){let t=(this._ext&3758096384)>>29;return t<0?t^4294967288:t}set underlineVariantOffset(t){this._ext&=536870911,this._ext|=t<<29&3758096384}clone(){return new s(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}};var q=class s extends De{constructor(){super(...arguments);this.content=0;this.fg=0;this.bg=0;this.extended=new rt;this.combinedData=""}static fromCharData(e){let i=new s;return i.setFromCharData(e),i}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?Ce(this.content&2097151):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(e){this.fg=e[0],this.bg=0;let i=!1;if(e[1].length>2)i=!0;else if(e[1].length===2){let r=e[1].charCodeAt(0);if(55296<=r&&r<=56319){let n=e[1].charCodeAt(1);56320<=n&&n<=57343?this.content=(r-55296)*1024+n-56320+65536|e[2]<<22:i=!0}else i=!0}else this.content=e[1].charCodeAt(0)|e[2]<<22;i&&(this.combinedData=e[1],this.content=2097152|e[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}};var js="di$target",Hn="di$dependencies",Fn=new Map;function Xs(s){return s[Hn]||[]}function ie(s){if(Fn.has(s))return Fn.get(s);let t=function(e,i,r){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");Pl(t,e,r)};return t._id=s,Fn.set(s,t),t}function Pl(s,t,e){t[js]===t?t[Hn].push({id:s,index:e}):(t[Hn]=[{id:s,index:e}],t[js]=t)}var F=ie("BufferService"),rr=ie("CoreMouseService"),ge=ie("CoreService"),Zs=ie("CharsetService"),xt=ie("InstantiationService");var nr=ie("LogService"),H=ie("OptionsService"),sr=ie("OscLinkService"),Js=ie("UnicodeService"),Be=ie("DecorationService");var wt=class{constructor(t,e,i){this._bufferService=t;this._optionsService=e;this._oscLinkService=i}provideLinks(t,e){let i=this._bufferService.buffer.lines.get(t-1);if(!i){e(void 0);return}let r=[],n=this._optionsService.rawOptions.linkHandler,o=new q,l=i.getTrimmedLength(),a=-1,u=-1,h=!1;for(let c=0;cn?n.activate(m,f,_):Ol(m,f),hover:(m,f)=>n?.hover?.(m,f,_),leave:(m,f)=>n?.leave?.(m,f,_)})}h=!1,o.hasExtendedAttrs()&&o.extended.urlId?(u=c,a=o.extended.urlId):(u=-1,a=-1)}}e(r)}};wt=M([S(0,F),S(1,H),S(2,sr)],wt);function Ol(s,t){if(confirm(`Do you want to navigate to ${t}? + +WARNING: This link could potentially be dangerous`)){let i=window.open();if(i){try{i.opener=null}catch{}i.location.href=t}else console.warn("Opening link blocked as opener could not be cleared")}}var nt=ie("CharSizeService"),ae=ie("CoreBrowserService"),Dt=ie("MouseService"),ce=ie("RenderService"),Qs=ie("SelectionService"),or=ie("CharacterJoinerService"),Re=ie("ThemeService"),lr=ie("LinkProviderService");var Wn=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(t){setTimeout(()=>{throw t.stack?ar.isErrorNoTelemetry(t)?new ar(t.message+` + +`+t.stack):new Error(t.message+` + +`+t.stack):t},0)}}addListener(t){return this.listeners.push(t),()=>{this._removeListener(t)}}emit(t){this.listeners.forEach(e=>{e(t)})}_removeListener(t){this.listeners.splice(this.listeners.indexOf(t),1)}setUnexpectedErrorHandler(t){this.unexpectedErrorHandler=t}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(t){this.unexpectedErrorHandler(t),this.emit(t)}onUnexpectedExternalError(t){this.unexpectedErrorHandler(t)}},Bl=new Wn;function Lt(s){Nl(s)||Bl.onUnexpectedError(s)}var Un="Canceled";function Nl(s){return s instanceof bi?!0:s instanceof Error&&s.name===Un&&s.message===Un}var bi=class extends Error{constructor(){super(Un),this.name=this.message}};function eo(s){return s?new Error(`Illegal argument: ${s}`):new Error("Illegal argument")}var ar=class s extends Error{constructor(t){super(t),this.name="CodeExpectedError"}static fromError(t){if(t instanceof s)return t;let e=new s;return e.message=t.message,e.stack=t.stack,e}static isErrorNoTelemetry(t){return t.name==="CodeExpectedError"}},Rt=class s extends Error{constructor(t){super(t||"An unexpected bug occurred."),Object.setPrototypeOf(this,s.prototype)}};function Fl(s,t,e=0,i=s.length){let r=e,n=i;for(;r{function s(a){return a<0}l.isLessThan=s;function t(a){return a<=0}l.isLessThanOrEqual=t;function e(a){return a>0}l.isGreaterThan=e;function i(a){return a===0}l.isNeitherLessOrGreaterThan=i,l.greaterThan=1,l.lessThan=-1,l.neitherLessOrGreaterThan=0})(ro||={});function no(s,t){return(e,i)=>t(s(e),s(i))}var so=(s,t)=>s-t;var At=class At{constructor(t){this.iterate=t}forEach(t){this.iterate(e=>(t(e),!0))}toArray(){let t=[];return this.iterate(e=>(t.push(e),!0)),t}filter(t){return new At(e=>this.iterate(i=>t(i)?e(i):!0))}map(t){return new At(e=>this.iterate(i=>e(t(i))))}some(t){let e=!1;return this.iterate(i=>(e=t(i),!e)),e}findFirst(t){let e;return this.iterate(i=>t(i)?(e=i,!1):!0),e}findLast(t){let e;return this.iterate(i=>(t(i)&&(e=i),!0)),e}findLastMaxBy(t){let e,i=!0;return this.iterate(r=>((i||ro.isGreaterThan(t(r,e)))&&(i=!1,e=r),!0)),e}};At.empty=new At(t=>{});var io=At;function co(s,t){let e=Object.create(null);for(let i of s){let r=t(i),n=e[r];n||(n=e[r]=[]),n.push(i)}return e}var lo,ao,oo=class{constructor(t,e){this.toKey=e;this._map=new Map;this[lo]="SetWithKey";for(let i of t)this.add(i)}get size(){return this._map.size}add(t){let e=this.toKey(t);return this._map.set(e,t),this}delete(t){return this._map.delete(this.toKey(t))}has(t){return this._map.has(this.toKey(t))}*entries(){for(let t of this._map.values())yield[t,t]}keys(){return this.values()}*values(){for(let t of this._map.values())yield t}clear(){this._map.clear()}forEach(t,e){this._map.forEach(i=>t.call(e,i,i,this))}[(ao=Symbol.iterator,lo=Symbol.toStringTag,ao)](){return this.values()}};var ur=class{constructor(){this.map=new Map}add(t,e){let i=this.map.get(t);i||(i=new Set,this.map.set(t,i)),i.add(e)}delete(t,e){let i=this.map.get(t);i&&(i.delete(e),i.size===0&&this.map.delete(t))}forEach(t,e){let i=this.map.get(t);i&&i.forEach(e)}get(t){let e=this.map.get(t);return e||new Set}};function Kn(s,t){let e=this,i=!1,r;return function(){if(i)return r;if(i=!0,t)try{r=s.apply(e,arguments)}finally{t()}else r=s.apply(e,arguments);return r}}var zn;(O=>{function s(I){return I&&typeof I=="object"&&typeof I[Symbol.iterator]=="function"}O.is=s;let t=Object.freeze([]);function e(){return t}O.empty=e;function*i(I){yield I}O.single=i;function r(I){return s(I)?I:i(I)}O.wrap=r;function n(I){return I||t}O.from=n;function*o(I){for(let k=I.length-1;k>=0;k--)yield I[k]}O.reverse=o;function l(I){return!I||I[Symbol.iterator]().next().done===!0}O.isEmpty=l;function a(I){return I[Symbol.iterator]().next().value}O.first=a;function u(I,k){let P=0;for(let oe of I)if(k(oe,P++))return!0;return!1}O.some=u;function h(I,k){for(let P of I)if(k(P))return P}O.find=h;function*c(I,k){for(let P of I)k(P)&&(yield P)}O.filter=c;function*d(I,k){let P=0;for(let oe of I)yield k(oe,P++)}O.map=d;function*_(I,k){let P=0;for(let oe of I)yield*k(oe,P++)}O.flatMap=_;function*p(...I){for(let k of I)yield*k}O.concat=p;function m(I,k,P){let oe=P;for(let Me of I)oe=k(oe,Me);return oe}O.reduce=m;function*f(I,k,P=I.length){for(k<0&&(k+=I.length),P<0?P+=I.length:P>I.length&&(P=I.length);ki.source!==null&&!this.getRootParent(i,t).isSingleton).flatMap(([i])=>i)}computeLeakingDisposables(t=10,e){let i;if(e)i=e;else{let a=new Map,u=[...this.livingDisposables.values()].filter(c=>c.source!==null&&!this.getRootParent(c,a).isSingleton);if(u.length===0)return;let h=new Set(u.map(c=>c.value));if(i=u.filter(c=>!(c.parent&&h.has(c.parent))),i.length===0)throw new Error("There are cyclic diposable chains!")}if(!i)return;function r(a){function u(c,d){for(;c.length>0&&d.some(_=>typeof _=="string"?_===c[0]:c[0].match(_));)c.shift()}let h=a.source.split(` +`).map(c=>c.trim().replace("at ","")).filter(c=>c!=="");return u(h,["Error",/^trackDisposable \(.*\)$/,/^DisposableTracker.trackDisposable \(.*\)$/]),h.reverse()}let n=new ur;for(let a of i){let u=r(a);for(let h=0;h<=u.length;h++)n.add(u.slice(0,h).join(` +`),a)}i.sort(no(a=>a.idx,so));let o="",l=0;for(let a of i.slice(0,t)){l++;let u=r(a),h=[];for(let c=0;cr(f)[c]),f=>f);delete m[u[c]];for(let[f,A]of Object.entries(m))h.unshift(` - stacktraces of ${A.length} other leaks continue with ${f}`);h.unshift(d)}o+=` + + +==================== Leaking disposable ${l}/${i.length}: ${a.value.constructor.name} ==================== +${h.join(` +`)} +============================================================ + +`}return i.length>t&&(o+=` + + +... and ${i.length-t} more leaking disposables + +`),{leaks:i,details:o}}};hr.idx=0;var uo=hr;function Ul(s){dt=s}if(Wl){let s="__is_disposable_tracked__";Ul(new class{trackDisposable(t){let e=new Error("Potentially leaked disposable").stack;setTimeout(()=>{t[s]||console.log(e)},3e3)}setParent(t,e){if(t&&t!==D.None)try{t[s]=!0}catch{}}markAsDisposed(t){if(t&&t!==D.None)try{t[s]=!0}catch{}}markAsSingleton(t){}})}function fr(s){return dt?.trackDisposable(s),s}function pr(s){dt?.markAsDisposed(s)}function vi(s,t){dt?.setParent(s,t)}function Kl(s,t){if(dt)for(let e of s)dt.setParent(e,t)}function Gn(s){return dt?.markAsSingleton(s),s}function Ne(s){if(zn.is(s)){let t=[];for(let e of s)if(e)try{e.dispose()}catch(i){t.push(i)}if(t.length===1)throw t[0];if(t.length>1)throw new AggregateError(t,"Encountered errors while disposing of store");return Array.isArray(s)?[]:s}else if(s)return s.dispose(),s}function ho(...s){let t=C(()=>Ne(s));return Kl(s,t),t}function C(s){let t=fr({dispose:Kn(()=>{pr(t),s()})});return t}var dr=class dr{constructor(){this._toDispose=new Set;this._isDisposed=!1;fr(this)}dispose(){this._isDisposed||(pr(this),this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{Ne(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t)return t;if(t===this)throw new Error("Cannot register a disposable on itself!");return vi(t,this),this._isDisposed?dr.DISABLE_DISPOSED_WARNING||console.warn(new Error("Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!").stack):this._toDispose.add(t),t}delete(t){if(t){if(t===this)throw new Error("Cannot dispose a disposable on itself!");this._toDispose.delete(t),t.dispose()}}deleteAndLeak(t){t&&this._toDispose.has(t)&&(this._toDispose.delete(t),vi(t,null))}};dr.DISABLE_DISPOSED_WARNING=!1;var Ee=dr,D=class{constructor(){this._store=new Ee;fr(this),vi(this._store,this)}dispose(){pr(this),this._store.dispose()}_register(t){if(t===this)throw new Error("Cannot register a disposable on itself!");return this._store.add(t)}};D.None=Object.freeze({dispose(){}});var ye=class{constructor(){this._isDisposed=!1;fr(this)}get value(){return this._isDisposed?void 0:this._value}set value(t){this._isDisposed||t===this._value||(this._value?.dispose(),t&&vi(t,this),this._value=t)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,pr(this),this._value?.dispose(),this._value=void 0}clearAndLeak(){let t=this._value;return this._value=void 0,t&&vi(t,null),t}};var fe=typeof window=="object"?window:globalThis;var kt=class kt{constructor(t){this.element=t,this.next=kt.Undefined,this.prev=kt.Undefined}};kt.Undefined=new kt(void 0);var G=kt,Ct=class{constructor(){this._first=G.Undefined;this._last=G.Undefined;this._size=0}get size(){return this._size}isEmpty(){return this._first===G.Undefined}clear(){let t=this._first;for(;t!==G.Undefined;){let e=t.next;t.prev=G.Undefined,t.next=G.Undefined,t=e}this._first=G.Undefined,this._last=G.Undefined,this._size=0}unshift(t){return this._insert(t,!1)}push(t){return this._insert(t,!0)}_insert(t,e){let i=new G(t);if(this._first===G.Undefined)this._first=i,this._last=i;else if(e){let n=this._last;this._last=i,i.prev=n,n.next=i}else{let n=this._first;this._first=i,i.next=n,n.prev=i}this._size+=1;let r=!1;return()=>{r||(r=!0,this._remove(i))}}shift(){if(this._first!==G.Undefined){let t=this._first.element;return this._remove(this._first),t}}pop(){if(this._last!==G.Undefined){let t=this._last.element;return this._remove(this._last),t}}_remove(t){if(t.prev!==G.Undefined&&t.next!==G.Undefined){let e=t.prev;e.next=t.next,t.next.prev=e}else t.prev===G.Undefined&&t.next===G.Undefined?(this._first=G.Undefined,this._last=G.Undefined):t.next===G.Undefined?(this._last=this._last.prev,this._last.next=G.Undefined):t.prev===G.Undefined&&(this._first=this._first.next,this._first.prev=G.Undefined);this._size-=1}*[Symbol.iterator](){let t=this._first;for(;t!==G.Undefined;)yield t.element,t=t.next}};var zl=globalThis.performance&&typeof globalThis.performance.now=="function",mr=class s{static create(t){return new s(t)}constructor(t){this._now=zl&&t===!1?Date.now:globalThis.performance.now.bind(globalThis.performance),this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=this._now(),this._stopTime=-1}elapsed(){return this._stopTime!==-1?this._stopTime-this._startTime:this._now()-this._startTime}};var Gl=!1,fo=!1,$l=!1,$;(Qe=>{Qe.None=()=>D.None;function t(y){if($l){let{onDidAddListener:T}=y,g=gi.create(),w=0;y.onDidAddListener=()=>{++w===2&&(console.warn("snapshotted emitter LIKELY used public and SHOULD HAVE BEEN created with DisposableStore. snapshotted here"),g.print()),T?.()}}}function e(y,T){return d(y,()=>{},0,void 0,!0,void 0,T)}Qe.defer=e;function i(y){return(T,g=null,w)=>{let E=!1,x;return x=y(N=>{if(!E)return x?x.dispose():E=!0,T.call(g,N)},null,w),E&&x.dispose(),x}}Qe.once=i;function r(y,T,g){return h((w,E=null,x)=>y(N=>w.call(E,T(N)),null,x),g)}Qe.map=r;function n(y,T,g){return h((w,E=null,x)=>y(N=>{T(N),w.call(E,N)},null,x),g)}Qe.forEach=n;function o(y,T,g){return h((w,E=null,x)=>y(N=>T(N)&&w.call(E,N),null,x),g)}Qe.filter=o;function l(y){return y}Qe.signal=l;function a(...y){return(T,g=null,w)=>{let E=ho(...y.map(x=>x(N=>T.call(g,N))));return c(E,w)}}Qe.any=a;function u(y,T,g,w){let E=g;return r(y,x=>(E=T(E,x),E),w)}Qe.reduce=u;function h(y,T){let g,w={onWillAddFirstListener(){g=y(E.fire,E)},onDidRemoveLastListener(){g?.dispose()}};T||t(w);let E=new v(w);return T?.add(E),E.event}function c(y,T){return T instanceof Array?T.push(y):T&&T.add(y),y}function d(y,T,g=100,w=!1,E=!1,x,N){let Z,te,Oe,ze=0,le,et={leakWarningThreshold:x,onWillAddFirstListener(){Z=y(ht=>{ze++,te=T(te,ht),w&&!Oe&&(me.fire(te),te=void 0),le=()=>{let fi=te;te=void 0,Oe=void 0,(!w||ze>1)&&me.fire(fi),ze=0},typeof g=="number"?(clearTimeout(Oe),Oe=setTimeout(le,g)):Oe===void 0&&(Oe=0,queueMicrotask(le))})},onWillRemoveListener(){E&&ze>0&&le?.()},onDidRemoveLastListener(){le=void 0,Z.dispose()}};N||t(et);let me=new v(et);return N?.add(me),me.event}Qe.debounce=d;function _(y,T=0,g){return Qe.debounce(y,(w,E)=>w?(w.push(E),w):[E],T,void 0,!0,void 0,g)}Qe.accumulate=_;function p(y,T=(w,E)=>w===E,g){let w=!0,E;return o(y,x=>{let N=w||!T(x,E);return w=!1,E=x,N},g)}Qe.latch=p;function m(y,T,g){return[Qe.filter(y,T,g),Qe.filter(y,w=>!T(w),g)]}Qe.split=m;function f(y,T=!1,g=[],w){let E=g.slice(),x=y(te=>{E?E.push(te):Z.fire(te)});w&&w.add(x);let N=()=>{E?.forEach(te=>Z.fire(te)),E=null},Z=new v({onWillAddFirstListener(){x||(x=y(te=>Z.fire(te)),w&&w.add(x))},onDidAddFirstListener(){E&&(T?setTimeout(N):N())},onDidRemoveLastListener(){x&&x.dispose(),x=null}});return w&&w.add(Z),Z.event}Qe.buffer=f;function A(y,T){return(w,E,x)=>{let N=T(new O);return y(function(Z){let te=N.evaluate(Z);te!==R&&w.call(E,te)},void 0,x)}}Qe.chain=A;let R=Symbol("HaltChainable");class O{constructor(){this.steps=[]}map(T){return this.steps.push(T),this}forEach(T){return this.steps.push(g=>(T(g),g)),this}filter(T){return this.steps.push(g=>T(g)?g:R),this}reduce(T,g){let w=g;return this.steps.push(E=>(w=T(w,E),w)),this}latch(T=(g,w)=>g===w){let g=!0,w;return this.steps.push(E=>{let x=g||!T(E,w);return g=!1,w=E,x?E:R}),this}evaluate(T){for(let g of this.steps)if(T=g(T),T===R)break;return T}}function I(y,T,g=w=>w){let w=(...Z)=>N.fire(g(...Z)),E=()=>y.on(T,w),x=()=>y.removeListener(T,w),N=new v({onWillAddFirstListener:E,onDidRemoveLastListener:x});return N.event}Qe.fromNodeEventEmitter=I;function k(y,T,g=w=>w){let w=(...Z)=>N.fire(g(...Z)),E=()=>y.addEventListener(T,w),x=()=>y.removeEventListener(T,w),N=new v({onWillAddFirstListener:E,onDidRemoveLastListener:x});return N.event}Qe.fromDOMEventEmitter=k;function P(y){return new Promise(T=>i(y)(T))}Qe.toPromise=P;function oe(y){let T=new v;return y.then(g=>{T.fire(g)},()=>{T.fire(void 0)}).finally(()=>{T.dispose()}),T.event}Qe.fromPromise=oe;function Me(y,T){return y(g=>T.fire(g))}Qe.forward=Me;function Pe(y,T,g){return T(g),y(w=>T(w))}Qe.runAndSubscribe=Pe;class Ke{constructor(T,g){this._observable=T;this._counter=0;this._hasChanged=!1;let w={onWillAddFirstListener:()=>{T.addObserver(this)},onDidRemoveLastListener:()=>{T.removeObserver(this)}};g||t(w),this.emitter=new v(w),g&&g.add(this.emitter)}beginUpdate(T){this._counter++}handlePossibleChange(T){}handleChange(T,g){this._hasChanged=!0}endUpdate(T){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function di(y,T){return new Ke(y,T).emitter.event}Qe.fromObservable=di;function V(y){return(T,g,w)=>{let E=0,x=!1,N={beginUpdate(){E++},endUpdate(){E--,E===0&&(y.reportChanges(),x&&(x=!1,T.call(g)))},handlePossibleChange(){},handleChange(){x=!0}};y.addObserver(N),y.reportChanges();let Z={dispose(){y.removeObserver(N)}};return w instanceof Ee?w.add(Z):Array.isArray(w)&&w.push(Z),Z}}Qe.fromObservableLight=V})($||={});var Mt=class Mt{constructor(t){this.listenerCount=0;this.invocationCount=0;this.elapsedOverall=0;this.durations=[];this.name=`${t}_${Mt._idPool++}`,Mt.all.add(this)}start(t){this._stopWatch=new mr,this.listenerCount=t}stop(){if(this._stopWatch){let t=this._stopWatch.elapsed();this.durations.push(t),this.elapsedOverall+=t,this.invocationCount+=1,this._stopWatch=void 0}}};Mt.all=new Set,Mt._idPool=0;var $n=Mt,po=-1;var br=class br{constructor(t,e,i=(br._idPool++).toString(16).padStart(3,"0")){this._errorHandler=t;this.threshold=e;this.name=i;this._warnCountdown=0}dispose(){this._stacks?.clear()}check(t,e){let i=this.threshold;if(i<=0||e{let n=this._stacks.get(t.value)||0;this._stacks.set(t.value,n-1)}}getMostFrequentStack(){if(!this._stacks)return;let t,e=0;for(let[i,r]of this._stacks)(!t||e{if(s instanceof Pt)t(s);else for(let e=0;e{s.length!==0&&(console.warn("[LEAKING LISTENERS] GC'ed these listeners that were NOT yet disposed:"),console.warn(s.join(` +`)),s.length=0)},3e3),_r=new FinalizationRegistry(t=>{typeof t=="string"&&s.push(t)})}var v=class{constructor(t){this._size=0;this._options=t,this._leakageMon=po>0||this._options?.leakWarningThreshold?new Vn(t?.onListenerError??Lt,this._options?.leakWarningThreshold??po):void 0,this._perfMon=this._options?._profName?new $n(this._options._profName):void 0,this._deliveryQueue=this._options?.deliveryQueue}dispose(){if(!this._disposed){if(this._disposed=!0,this._deliveryQueue?.current===this&&this._deliveryQueue.reset(),this._listeners){if(fo){let t=this._listeners;queueMicrotask(()=>{Yl(t,e=>e.stack?.print())})}this._listeners=void 0,this._size=0}this._options?.onDidRemoveLastListener?.(),this._leakageMon?.dispose()}}get event(){return this._event??=(t,e,i)=>{if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let a=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(a);let u=this._leakageMon.getMostFrequentStack()??["UNKNOWN stack",-1],h=new Yn(`${a}. HINT: Stack shows most frequent listener (${u[1]}-times)`,u[0]);return(this._options?.onListenerError||Lt)(h),D.None}if(this._disposed)return D.None;e&&(t=t.bind(e));let r=new Pt(t),n,o;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(r.stack=gi.create(),n=this._leakageMon.check(r.stack,this._size+1)),fo&&(r.stack=o??gi.create()),this._listeners?this._listeners instanceof Pt?(this._deliveryQueue??=new jn,this._listeners=[this._listeners,r]):this._listeners.push(r):(this._options?.onWillAddFirstListener?.(this),this._listeners=r,this._options?.onDidAddFirstListener?.(this)),this._size++;let l=C(()=>{_r?.unregister(l),n?.(),this._removeListener(r)});if(i instanceof Ee?i.add(l):Array.isArray(i)&&i.push(l),_r){let a=new Error().stack.split(` +`).slice(2,3).join(` +`).trim(),u=/(file:|vscode-file:\/\/vscode-app)?(\/[^:]*:\d+:\d+)/.exec(a);_r.register(l,u?.[2]??a,l)}return l},this._event}_removeListener(t){if(this._options?.onWillRemoveListener?.(this),!this._listeners)return;if(this._size===1){this._listeners=void 0,this._options?.onDidRemoveLastListener?.(this),this._size=0;return}let e=this._listeners,i=e.indexOf(t);if(i===-1)throw console.log("disposed?",this._disposed),console.log("size?",this._size),console.log("arr?",JSON.stringify(this._listeners)),new Error("Attempted to dispose unknown listener");this._size--,e[i]=void 0;let r=this._deliveryQueue.current===this;if(this._size*ql<=e.length){let n=0;for(let o=0;o0}};var jn=class{constructor(){this.i=-1;this.end=0}enqueue(t,e,i){this.i=0,this.end=i,this.current=t,this.value=e}reset(){this.i=this.end,this.current=void 0,this.value=void 0}};var gr=class gr{constructor(){this.mapWindowIdToZoomLevel=new Map;this._onDidChangeZoomLevel=new v;this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event;this.mapWindowIdToZoomFactor=new Map;this._onDidChangeFullscreen=new v;this.onDidChangeFullscreen=this._onDidChangeFullscreen.event;this.mapWindowIdToFullScreen=new Map}getZoomLevel(t){return this.mapWindowIdToZoomLevel.get(this.getWindowId(t))??0}setZoomLevel(t,e){if(this.getZoomLevel(e)===t)return;let i=this.getWindowId(e);this.mapWindowIdToZoomLevel.set(i,t),this._onDidChangeZoomLevel.fire(i)}getZoomFactor(t){return this.mapWindowIdToZoomFactor.get(this.getWindowId(t))??1}setZoomFactor(t,e){this.mapWindowIdToZoomFactor.set(this.getWindowId(e),t)}setFullscreen(t,e){if(this.isFullscreen(e)===t)return;let i=this.getWindowId(e);this.mapWindowIdToFullScreen.set(i,t),this._onDidChangeFullscreen.fire(i)}isFullscreen(t){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(t))}getWindowId(t){return t.vscodeWindowId}};gr.INSTANCE=new gr;var Si=gr;function Xl(s,t,e){typeof t=="string"&&(t=s.matchMedia(t)),t.addEventListener("change",e)}var Eu=Si.INSTANCE.onDidChangeZoomLevel;function mo(s){return Si.INSTANCE.getZoomFactor(s)}var Tu=Si.INSTANCE.onDidChangeFullscreen,Ot=typeof navigator=="object"?navigator.userAgent:"",Ei=Ot.indexOf("Firefox")>=0,Bt=Ot.indexOf("AppleWebKit")>=0,Ti=Ot.indexOf("Chrome")>=0,Sr=!Ti&&Ot.indexOf("Safari")>=0;var Iu=Ot.indexOf("Electron/")>=0,yu=Ot.indexOf("Android")>=0,vr=!1;if(typeof fe.matchMedia=="function"){let s=fe.matchMedia("(display-mode: standalone) or (display-mode: window-controls-overlay)"),t=fe.matchMedia("(display-mode: fullscreen)");vr=s.matches,Xl(fe,s,({matches:e})=>{vr&&t.matches||(vr=e)})}function _o(){return vr}var Nt="en",yr=!1,xr=!1,Ii=!1,Zl=!1,vo=!1,go=!1,Jl=!1,Ql=!1,ea=!1,ta=!1,Tr,Ir=Nt,bo=Nt,ia,$e,Ve=globalThis,xe;typeof Ve.vscode<"u"&&typeof Ve.vscode.process<"u"?xe=Ve.vscode.process:typeof process<"u"&&typeof process?.versions?.node=="string"&&(xe=process);var So=typeof xe?.versions?.electron=="string",ra=So&&xe?.type==="renderer";if(typeof xe=="object"){yr=xe.platform==="win32",xr=xe.platform==="darwin",Ii=xe.platform==="linux",Zl=Ii&&!!xe.env.SNAP&&!!xe.env.SNAP_REVISION,Jl=So,ea=!!xe.env.CI||!!xe.env.BUILD_ARTIFACTSTAGINGDIRECTORY,Tr=Nt,Ir=Nt;let s=xe.env.VSCODE_NLS_CONFIG;if(s)try{let t=JSON.parse(s);Tr=t.userLocale,bo=t.osLocale,Ir=t.resolvedLanguage||Nt,ia=t.languagePack?.translationsConfigFile}catch{}vo=!0}else typeof navigator=="object"&&!ra?($e=navigator.userAgent,yr=$e.indexOf("Windows")>=0,xr=$e.indexOf("Macintosh")>=0,Ql=($e.indexOf("Macintosh")>=0||$e.indexOf("iPad")>=0||$e.indexOf("iPhone")>=0)&&!!navigator.maxTouchPoints&&navigator.maxTouchPoints>0,Ii=$e.indexOf("Linux")>=0,ta=$e?.indexOf("Mobi")>=0,go=!0,Ir=globalThis._VSCODE_NLS_LANGUAGE||Nt,Tr=navigator.language.toLowerCase(),bo=Tr):console.error("Unable to resolve platform.");var Xn=0;xr?Xn=1:yr?Xn=3:Ii&&(Xn=2);var wr=yr,Te=xr,Zn=Ii;var Dr=vo;var na=go&&typeof Ve.importScripts=="function",xu=na?Ve.origin:void 0;var Fe=$e,st=Ir,sa;(i=>{function s(){return st}i.value=s;function t(){return st.length===2?st==="en":st.length>=3?st[0]==="e"&&st[1]==="n"&&st[2]==="-":!1}i.isDefaultVariant=t;function e(){return st==="en"}i.isDefault=e})(sa||={});var oa=typeof Ve.postMessage=="function"&&!Ve.importScripts,Eo=(()=>{if(oa){let s=[];Ve.addEventListener("message",e=>{if(e.data&&e.data.vscodeScheduleAsyncWork)for(let i=0,r=s.length;i{let i=++t;s.push({id:i,callback:e}),Ve.postMessage({vscodeScheduleAsyncWork:i},"*")}}return s=>setTimeout(s)})();var la=!!(Fe&&Fe.indexOf("Chrome")>=0),wu=!!(Fe&&Fe.indexOf("Firefox")>=0),Du=!!(!la&&Fe&&Fe.indexOf("Safari")>=0),Ru=!!(Fe&&Fe.indexOf("Edg/")>=0),Lu=!!(Fe&&Fe.indexOf("Android")>=0);var ot=typeof navigator=="object"?navigator:{},aa={clipboard:{writeText:Dr||document.queryCommandSupported&&document.queryCommandSupported("copy")||!!(ot&&ot.clipboard&&ot.clipboard.writeText),readText:Dr||!!(ot&&ot.clipboard&&ot.clipboard.readText)},keyboard:Dr||_o()?0:ot.keyboard||Sr?1:2,touch:"ontouchstart"in fe||ot.maxTouchPoints>0,pointerEvents:fe.PointerEvent&&("ontouchstart"in fe||navigator.maxTouchPoints>0)};var yi=class{constructor(){this._keyCodeToStr=[],this._strToKeyCode=Object.create(null)}define(t,e){this._keyCodeToStr[t]=e,this._strToKeyCode[e.toLowerCase()]=t}keyCodeToStr(t){return this._keyCodeToStr[t]}strToKeyCode(t){return this._strToKeyCode[t.toLowerCase()]||0}},Jn=new yi,To=new yi,Io=new yi,yo=new Array(230);var Qn;(o=>{function s(l){return Jn.keyCodeToStr(l)}o.toString=s;function t(l){return Jn.strToKeyCode(l)}o.fromString=t;function e(l){return To.keyCodeToStr(l)}o.toUserSettingsUS=e;function i(l){return Io.keyCodeToStr(l)}o.toUserSettingsGeneral=i;function r(l){return To.strToKeyCode(l)||Io.strToKeyCode(l)}o.fromUserSettings=r;function n(l){if(l>=98&&l<=113)return null;switch(l){case 16:return"Up";case 18:return"Down";case 15:return"Left";case 17:return"Right"}return Jn.keyCodeToStr(l)}o.toElectronAccelerator=n})(Qn||={});var Rr=class s{constructor(t,e,i,r,n){this.ctrlKey=t;this.shiftKey=e;this.altKey=i;this.metaKey=r;this.keyCode=n}equals(t){return t instanceof s&&this.ctrlKey===t.ctrlKey&&this.shiftKey===t.shiftKey&&this.altKey===t.altKey&&this.metaKey===t.metaKey&&this.keyCode===t.keyCode}getHashCode(){let t=this.ctrlKey?"1":"0",e=this.shiftKey?"1":"0",i=this.altKey?"1":"0",r=this.metaKey?"1":"0";return`K${t}${e}${i}${r}${this.keyCode}`}isModifierKey(){return this.keyCode===0||this.keyCode===5||this.keyCode===57||this.keyCode===6||this.keyCode===4}toKeybinding(){return new es([this])}isDuplicateModifierCase(){return this.ctrlKey&&this.keyCode===5||this.shiftKey&&this.keyCode===4||this.altKey&&this.keyCode===6||this.metaKey&&this.keyCode===57}};var es=class{constructor(t){if(t.length===0)throw eo("chords");this.chords=t}getHashCode(){let t="";for(let e=0,i=this.chords.length;e{function s(r){return r===i.None||r===i.Cancelled||r instanceof ts?!0:!r||typeof r!="object"?!1:typeof r.isCancellationRequested=="boolean"&&typeof r.onCancellationRequested=="function"}i.isCancellationToken=s,i.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:$.None}),i.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:Do})})(ma||={});var ts=class{constructor(){this._isCancelled=!1;this._emitter=null}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?Do:(this._emitter||(this._emitter=new v),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}};var _a=Symbol("MicrotaskDelay");var Ye=class{constructor(t,e){this._isDisposed=!1;this._token=-1,typeof t=="function"&&typeof e=="number"&&this.setIfNotSet(t,e)}dispose(){this.cancel(),this._isDisposed=!0}cancel(){this._token!==-1&&(clearTimeout(this._token),this._token=-1)}cancelAndSet(t,e){if(this._isDisposed)throw new Rt("Calling 'cancelAndSet' on a disposed TimeoutTimer");this.cancel(),this._token=setTimeout(()=>{this._token=-1,t()},e)}setIfNotSet(t,e){if(this._isDisposed)throw new Rt("Calling 'setIfNotSet' on a disposed TimeoutTimer");this._token===-1&&(this._token=setTimeout(()=>{this._token=-1,t()},e))}},kr=class{constructor(){this.disposable=void 0;this.isDisposed=!1}cancel(){this.disposable?.dispose(),this.disposable=void 0}cancelAndSet(t,e,i=globalThis){if(this.isDisposed)throw new Rt("Calling 'cancelAndSet' on a disposed IntervalTimer");this.cancel();let r=i.setInterval(()=>{t()},e);this.disposable=C(()=>{i.clearInterval(r),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}};var ba,Ar;(function(){typeof globalThis.requestIdleCallback!="function"||typeof globalThis.cancelIdleCallback!="function"?Ar=(s,t)=>{Eo(()=>{if(e)return;let i=Date.now()+15;t(Object.freeze({didTimeout:!0,timeRemaining(){return Math.max(0,i-Date.now())}}))});let e=!1;return{dispose(){e||(e=!0)}}}:Ar=(s,t,e)=>{let i=s.requestIdleCallback(t,typeof e=="number"?{timeout:e}:void 0),r=!1;return{dispose(){r||(r=!0,s.cancelIdleCallback(i))}}},ba=s=>Ar(globalThis,s)})();var va;(e=>{async function s(i){let r,n=await Promise.all(i.map(o=>o.then(l=>l,l=>{r||(r=l)})));if(typeof r<"u")throw r;return n}e.settled=s;function t(i){return new Promise(async(r,n)=>{try{await i(r,n)}catch(o){n(o)}})}e.withAsyncBody=t})(va||={});var _e=class _e{static fromArray(t){return new _e(e=>{e.emitMany(t)})}static fromPromise(t){return new _e(async e=>{e.emitMany(await t)})}static fromPromises(t){return new _e(async e=>{await Promise.all(t.map(async i=>e.emitOne(await i)))})}static merge(t){return new _e(async e=>{await Promise.all(t.map(async i=>{for await(let r of i)e.emitOne(r)}))})}constructor(t,e){this._state=0,this._results=[],this._error=null,this._onReturn=e,this._onStateChanged=new v,queueMicrotask(async()=>{let i={emitOne:r=>this.emitOne(r),emitMany:r=>this.emitMany(r),reject:r=>this.reject(r)};try{await Promise.resolve(t(i)),this.resolve()}catch(r){this.reject(r)}finally{i.emitOne=void 0,i.emitMany=void 0,i.reject=void 0}})}[Symbol.asyncIterator](){let t=0;return{next:async()=>{do{if(this._state===2)throw this._error;if(t(this._onReturn?.(),{done:!0,value:void 0})}}static map(t,e){return new _e(async i=>{for await(let r of t)i.emitOne(e(r))})}map(t){return _e.map(this,t)}static filter(t,e){return new _e(async i=>{for await(let r of t)e(r)&&i.emitOne(r)})}filter(t){return _e.filter(this,t)}static coalesce(t){return _e.filter(t,e=>!!e)}coalesce(){return _e.coalesce(this)}static async toPromise(t){let e=[];for await(let i of t)e.push(i);return e}toPromise(){return _e.toPromise(this)}emitOne(t){this._state===0&&(this._results.push(t),this._onStateChanged.fire())}emitMany(t){this._state===0&&(this._results=this._results.concat(t),this._onStateChanged.fire())}resolve(){this._state===0&&(this._state=1,this._onStateChanged.fire())}reject(t){this._state===0&&(this._state=2,this._error=t,this._onStateChanged.fire())}};_e.EMPTY=_e.fromArray([]);var Ro=_e;function Lo(s){return 55296<=s&&s<=56319}function is(s){return 56320<=s&&s<=57343}function Ao(s,t){return(s-55296<<10)+(t-56320)+65536}function Mo(s){return ns(s,0)}function ns(s,t){switch(typeof s){case"object":return s===null?je(349,t):Array.isArray(s)?Ea(s,t):Ta(s,t);case"string":return Po(s,t);case"boolean":return Sa(s,t);case"number":return je(s,t);case"undefined":return je(937,t);default:return je(617,t)}}function je(s,t){return(t<<5)-t+s|0}function Sa(s,t){return je(s?433:863,t)}function Po(s,t){t=je(149417,t);for(let e=0,i=s.length;ens(i,e),t)}function Ta(s,t){return t=je(181387,t),Object.keys(s).sort().reduce((e,i)=>(e=Po(i,e),ns(s[i],e)),t)}function rs(s,t,e=32){let i=e-t,r=~((1<>>i)>>>0}function ko(s,t=0,e=s.byteLength,i=0){for(let r=0;re.toString(16).padStart(2,"0")).join(""):Ia((s>>>0).toString(16),t/4)}var Cr=class Cr{constructor(){this._h0=1732584193;this._h1=4023233417;this._h2=2562383102;this._h3=271733878;this._h4=3285377520;this._buff=new Uint8Array(67),this._buffDV=new DataView(this._buff.buffer),this._buffLen=0,this._totalLen=0,this._leftoverHighSurrogate=0,this._finished=!1}update(t){let e=t.length;if(e===0)return;let i=this._buff,r=this._buffLen,n=this._leftoverHighSurrogate,o,l;for(n!==0?(o=n,l=-1,n=0):(o=t.charCodeAt(0),l=0);;){let a=o;if(Lo(o))if(l+1>>6,t[e++]=128|(i&63)>>>0):i<65536?(t[e++]=224|(i&61440)>>>12,t[e++]=128|(i&4032)>>>6,t[e++]=128|(i&63)>>>0):(t[e++]=240|(i&1835008)>>>18,t[e++]=128|(i&258048)>>>12,t[e++]=128|(i&4032)>>>6,t[e++]=128|(i&63)>>>0),e>=64&&(this._step(),e-=64,this._totalLen+=64,t[0]=t[64],t[1]=t[65],t[2]=t[66]),e}digest(){return this._finished||(this._finished=!0,this._leftoverHighSurrogate&&(this._leftoverHighSurrogate=0,this._buffLen=this._push(this._buff,this._buffLen,65533)),this._totalLen+=this._buffLen,this._wrapUp()),wi(this._h0)+wi(this._h1)+wi(this._h2)+wi(this._h3)+wi(this._h4)}_wrapUp(){this._buff[this._buffLen++]=128,ko(this._buff,this._buffLen),this._buffLen>56&&(this._step(),ko(this._buff));let t=8*this._totalLen;this._buffDV.setUint32(56,Math.floor(t/4294967296),!1),this._buffDV.setUint32(60,t%4294967296,!1),this._step()}_step(){let t=Cr._bigBlock32,e=this._buffDV;for(let c=0;c<64;c+=4)t.setUint32(c,e.getUint32(c,!1),!1);for(let c=64;c<320;c+=4)t.setUint32(c,rs(t.getUint32(c-12,!1)^t.getUint32(c-32,!1)^t.getUint32(c-56,!1)^t.getUint32(c-64,!1),1),!1);let i=this._h0,r=this._h1,n=this._h2,o=this._h3,l=this._h4,a,u,h;for(let c=0;c<80;c++)c<20?(a=r&n|~r&o,u=1518500249):c<40?(a=r^n^o,u=1859775393):c<60?(a=r&n|r&o|n&o,u=2400959708):(a=r^n^o,u=3395469782),h=rs(i,5)+a+l+u+t.getUint32(c*4,!1)&4294967295,l=o,o=n,n=rs(r,30),r=i,i=h;this._h0=this._h0+i&4294967295,this._h1=this._h1+r&4294967295,this._h2=this._h2+n&4294967295,this._h3=this._h3+o&4294967295,this._h4=this._h4+l&4294967295}};Cr._bigBlock32=new DataView(new ArrayBuffer(320));var Co=Cr;var{registerWindow:Bh,getWindow:be,getDocument:Nh,getWindows:Fh,getWindowsCount:Hh,getWindowId:Oo,getWindowById:Wh,hasWindow:Uh,onDidRegisterWindow:No,onWillUnregisterWindow:Kh,onDidUnregisterWindow:zh}=function(){let s=new Map;fe;let t={window:fe,disposables:new Ee};s.set(fe.vscodeWindowId,t);let e=new v,i=new v,r=new v;function n(o,l){return(typeof o=="number"?s.get(o):void 0)??(l?t:void 0)}return{onDidRegisterWindow:e.event,onWillUnregisterWindow:r.event,onDidUnregisterWindow:i.event,registerWindow(o){if(s.has(o.vscodeWindowId))return D.None;let l=new Ee,a={window:o,disposables:l.add(new Ee)};return s.set(o.vscodeWindowId,a),l.add(C(()=>{s.delete(o.vscodeWindowId),i.fire(o)})),l.add(L(o,Y.BEFORE_UNLOAD,()=>{r.fire(o)})),e.fire(a),l},getWindows(){return s.values()},getWindowsCount(){return s.size},getWindowId(o){return o.vscodeWindowId},hasWindow(o){return s.has(o)},getWindowById:n,getWindow(o){let l=o;if(l?.ownerDocument?.defaultView)return l.ownerDocument.defaultView.window;let a=o;return a?.view?a.view.window:fe},getDocument(o){return be(o).document}}}();var ss=class{constructor(t,e,i,r){this._node=t,this._type=e,this._handler=i,this._options=r||!1,this._node.addEventListener(this._type,this._handler,this._options)}dispose(){this._handler&&(this._node.removeEventListener(this._type,this._handler,this._options),this._node=null,this._handler=null)}};function L(s,t,e,i){return new ss(s,t,e,i)}function ya(s,t){return function(e){return t(new qe(s,e))}}function xa(s){return function(t){return s(new ft(t))}}var os=function(t,e,i,r){let n=i;return e==="click"||e==="mousedown"||e==="contextmenu"?n=ya(be(t),i):(e==="keydown"||e==="keypress"||e==="keyup")&&(n=xa(i)),L(t,e,n,r)};var wa,mt;var Mr=class extends kr{constructor(t){super(),this.defaultTarget=t&&be(t)}cancelAndSet(t,e,i){return super.cancelAndSet(t,e,i??this.defaultTarget)}},Di=class{constructor(t,e=0){this._runner=t,this.priority=e,this._canceled=!1}dispose(){this._canceled=!0}execute(){if(!this._canceled)try{this._runner()}catch(t){Lt(t)}}static sort(t,e){return e.priority-t.priority}};(function(){let s=new Map,t=new Map,e=new Map,i=new Map,r=n=>{e.set(n,!1);let o=s.get(n)??[];for(t.set(n,o),s.set(n,[]),i.set(n,!0);o.length>0;)o.sort(Di.sort),o.shift().execute();i.set(n,!1)};mt=(n,o,l=0)=>{let a=Oo(n),u=new Di(o,l),h=s.get(a);return h||(h=[],s.set(a,h)),h.push(u),e.get(a)||(e.set(a,!0),n.requestAnimationFrame(()=>r(a))),u},wa=(n,o,l)=>{let a=Oo(n);if(i.get(a)){let u=new Di(o,l),h=t.get(a);return h||(h=[],t.set(a,h)),h.push(u),u}else return mt(n,o,l)}})();var pt=class pt{constructor(t,e){this.width=t;this.height=e}with(t=this.width,e=this.height){return t!==this.width||e!==this.height?new pt(t,e):this}static is(t){return typeof t=="object"&&typeof t.height=="number"&&typeof t.width=="number"}static lift(t){return t instanceof pt?t:new pt(t.width,t.height)}static equals(t,e){return t===e?!0:!t||!e?!1:t.width===e.width&&t.height===e.height}};pt.None=new pt(0,0);var Bo=pt;function Fo(s){let t=s.getBoundingClientRect(),e=be(s);return{left:t.left+e.scrollX,top:t.top+e.scrollY,width:t.width,height:t.height}}var Gh=new class{constructor(){this.mutationObservers=new Map}observe(s,t,e){let i=this.mutationObservers.get(s);i||(i=new Map,this.mutationObservers.set(s,i));let r=Mo(e),n=i.get(r);if(n)n.users+=1;else{let o=new v,l=new MutationObserver(u=>o.fire(u));l.observe(s,e);let a=n={users:1,observer:l,onDidMutate:o.event};t.add(C(()=>{a.users-=1,a.users===0&&(o.dispose(),l.disconnect(),i?.delete(r),i?.size===0&&this.mutationObservers.delete(s))})),i.set(r,n)}return n.onDidMutate}};var Y={CLICK:"click",AUXCLICK:"auxclick",DBLCLICK:"dblclick",MOUSE_UP:"mouseup",MOUSE_DOWN:"mousedown",MOUSE_OVER:"mouseover",MOUSE_MOVE:"mousemove",MOUSE_OUT:"mouseout",MOUSE_ENTER:"mouseenter",MOUSE_LEAVE:"mouseleave",MOUSE_WHEEL:"wheel",POINTER_UP:"pointerup",POINTER_DOWN:"pointerdown",POINTER_MOVE:"pointermove",POINTER_LEAVE:"pointerleave",CONTEXT_MENU:"contextmenu",WHEEL:"wheel",KEY_DOWN:"keydown",KEY_PRESS:"keypress",KEY_UP:"keyup",LOAD:"load",BEFORE_UNLOAD:"beforeunload",UNLOAD:"unload",PAGE_SHOW:"pageshow",PAGE_HIDE:"pagehide",PASTE:"paste",ABORT:"abort",ERROR:"error",RESIZE:"resize",SCROLL:"scroll",FULLSCREEN_CHANGE:"fullscreenchange",WK_FULLSCREEN_CHANGE:"webkitfullscreenchange",SELECT:"select",CHANGE:"change",SUBMIT:"submit",RESET:"reset",FOCUS:"focus",FOCUS_IN:"focusin",FOCUS_OUT:"focusout",BLUR:"blur",INPUT:"input",STORAGE:"storage",DRAG_START:"dragstart",DRAG:"drag",DRAG_ENTER:"dragenter",DRAG_LEAVE:"dragleave",DRAG_OVER:"dragover",DROP:"drop",DRAG_END:"dragend",ANIMATION_START:Bt?"webkitAnimationStart":"animationstart",ANIMATION_END:Bt?"webkitAnimationEnd":"animationend",ANIMATION_ITERATION:Bt?"webkitAnimationIteration":"animationiteration"};var Da=/([\w\-]+)?(#([\w\-]+))?((\.([\w\-]+))*)/;function Ho(s,t,e,...i){let r=Da.exec(t);if(!r)throw new Error("Bad use of emmet");let n=r[1]||"div",o;return s!=="http://www.w3.org/1999/xhtml"?o=document.createElementNS(s,n):o=document.createElement(n),r[3]&&(o.id=r[3]),r[4]&&(o.className=r[4].replace(/\./g," ").trim()),e&&Object.entries(e).forEach(([l,a])=>{typeof a>"u"||(/^on\w+$/.test(l)?o[l]=a:l==="selected"?a&&o.setAttribute(l,"true"):o.setAttribute(l,a))}),o.append(...i),o}function Ra(s,t,...e){return Ho("http://www.w3.org/1999/xhtml",s,t,...e)}Ra.SVG=function(s,t,...e){return Ho("http://www.w3.org/2000/svg",s,t,...e)};var ls=class{constructor(t){this.domNode=t;this._maxWidth="";this._width="";this._height="";this._top="";this._left="";this._bottom="";this._right="";this._paddingTop="";this._paddingLeft="";this._paddingBottom="";this._paddingRight="";this._fontFamily="";this._fontWeight="";this._fontSize="";this._fontStyle="";this._fontFeatureSettings="";this._fontVariationSettings="";this._textDecoration="";this._lineHeight="";this._letterSpacing="";this._className="";this._display="";this._position="";this._visibility="";this._color="";this._backgroundColor="";this._layerHint=!1;this._contain="none";this._boxShadow=""}setMaxWidth(t){let e=Ie(t);this._maxWidth!==e&&(this._maxWidth=e,this.domNode.style.maxWidth=this._maxWidth)}setWidth(t){let e=Ie(t);this._width!==e&&(this._width=e,this.domNode.style.width=this._width)}setHeight(t){let e=Ie(t);this._height!==e&&(this._height=e,this.domNode.style.height=this._height)}setTop(t){let e=Ie(t);this._top!==e&&(this._top=e,this.domNode.style.top=this._top)}setLeft(t){let e=Ie(t);this._left!==e&&(this._left=e,this.domNode.style.left=this._left)}setBottom(t){let e=Ie(t);this._bottom!==e&&(this._bottom=e,this.domNode.style.bottom=this._bottom)}setRight(t){let e=Ie(t);this._right!==e&&(this._right=e,this.domNode.style.right=this._right)}setPaddingTop(t){let e=Ie(t);this._paddingTop!==e&&(this._paddingTop=e,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(t){let e=Ie(t);this._paddingLeft!==e&&(this._paddingLeft=e,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(t){let e=Ie(t);this._paddingBottom!==e&&(this._paddingBottom=e,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(t){let e=Ie(t);this._paddingRight!==e&&(this._paddingRight=e,this.domNode.style.paddingRight=this._paddingRight)}setFontFamily(t){this._fontFamily!==t&&(this._fontFamily=t,this.domNode.style.fontFamily=this._fontFamily)}setFontWeight(t){this._fontWeight!==t&&(this._fontWeight=t,this.domNode.style.fontWeight=this._fontWeight)}setFontSize(t){let e=Ie(t);this._fontSize!==e&&(this._fontSize=e,this.domNode.style.fontSize=this._fontSize)}setFontStyle(t){this._fontStyle!==t&&(this._fontStyle=t,this.domNode.style.fontStyle=this._fontStyle)}setFontFeatureSettings(t){this._fontFeatureSettings!==t&&(this._fontFeatureSettings=t,this.domNode.style.fontFeatureSettings=this._fontFeatureSettings)}setFontVariationSettings(t){this._fontVariationSettings!==t&&(this._fontVariationSettings=t,this.domNode.style.fontVariationSettings=this._fontVariationSettings)}setTextDecoration(t){this._textDecoration!==t&&(this._textDecoration=t,this.domNode.style.textDecoration=this._textDecoration)}setLineHeight(t){let e=Ie(t);this._lineHeight!==e&&(this._lineHeight=e,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(t){let e=Ie(t);this._letterSpacing!==e&&(this._letterSpacing=e,this.domNode.style.letterSpacing=this._letterSpacing)}setClassName(t){this._className!==t&&(this._className=t,this.domNode.className=this._className)}toggleClassName(t,e){this.domNode.classList.toggle(t,e),this._className=this.domNode.className}setDisplay(t){this._display!==t&&(this._display=t,this.domNode.style.display=this._display)}setPosition(t){this._position!==t&&(this._position=t,this.domNode.style.position=this._position)}setVisibility(t){this._visibility!==t&&(this._visibility=t,this.domNode.style.visibility=this._visibility)}setColor(t){this._color!==t&&(this._color=t,this.domNode.style.color=this._color)}setBackgroundColor(t){this._backgroundColor!==t&&(this._backgroundColor=t,this.domNode.style.backgroundColor=this._backgroundColor)}setLayerHinting(t){this._layerHint!==t&&(this._layerHint=t,this.domNode.style.transform=this._layerHint?"translate3d(0px, 0px, 0px)":"")}setBoxShadow(t){this._boxShadow!==t&&(this._boxShadow=t,this.domNode.style.boxShadow=t)}setContain(t){this._contain!==t&&(this._contain=t,this.domNode.style.contain=this._contain)}setAttribute(t,e){this.domNode.setAttribute(t,e)}removeAttribute(t){this.domNode.removeAttribute(t)}appendChild(t){this.domNode.appendChild(t.domNode)}removeChild(t){this.domNode.removeChild(t.domNode)}};function Ie(s){return typeof s=="number"?`${s}px`:s}function _t(s){return new ls(s)}var Wt=class{constructor(){this._hooks=new Ee;this._pointerMoveCallback=null;this._onStopCallback=null}dispose(){this.stopMonitoring(!1),this._hooks.dispose()}stopMonitoring(t,e){if(!this.isMonitoring())return;this._hooks.clear(),this._pointerMoveCallback=null;let i=this._onStopCallback;this._onStopCallback=null,t&&i&&i(e)}isMonitoring(){return!!this._pointerMoveCallback}startMonitoring(t,e,i,r,n){this.isMonitoring()&&this.stopMonitoring(!1),this._pointerMoveCallback=r,this._onStopCallback=n;let o=t;try{t.setPointerCapture(e),this._hooks.add(C(()=>{try{t.releasePointerCapture(e)}catch{}}))}catch{o=be(t)}this._hooks.add(L(o,Y.POINTER_MOVE,l=>{if(l.buttons!==i){this.stopMonitoring(!0);return}l.preventDefault(),this._pointerMoveCallback(l)})),this._hooks.add(L(o,Y.POINTER_UP,l=>this.stopMonitoring(!0)))}};function Wo(s,t,e){let i=null,r=null;if(typeof e.value=="function"?(i="value",r=e.value,r.length!==0&&console.warn("Memoize should only be used in functions with zero parameters")):typeof e.get=="function"&&(i="get",r=e.get),!r)throw new Error("not supported");let n=`$memoize$${t}`;e[i]=function(...o){return this.hasOwnProperty(n)||Object.defineProperty(this,n,{configurable:!1,enumerable:!1,writable:!1,value:r.apply(this,o)}),this[n]}}var He;(n=>(n.Tap="-xterm-gesturetap",n.Change="-xterm-gesturechange",n.Start="-xterm-gesturestart",n.End="-xterm-gesturesend",n.Contextmenu="-xterm-gesturecontextmenu"))(He||={});var Q=class Q extends D{constructor(){super();this.dispatched=!1;this.targets=new Ct;this.ignoreTargets=new Ct;this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register($.runAndSubscribe(No,({window:e,disposables:i})=>{i.add(L(e.document,"touchstart",r=>this.onTouchStart(r),{passive:!1})),i.add(L(e.document,"touchend",r=>this.onTouchEnd(e,r))),i.add(L(e.document,"touchmove",r=>this.onTouchMove(r),{passive:!1}))},{window:fe,disposables:this._store}))}static addTarget(e){if(!Q.isTouchDevice())return D.None;Q.INSTANCE||(Q.INSTANCE=Gn(new Q));let i=Q.INSTANCE.targets.push(e);return C(i)}static ignoreTarget(e){if(!Q.isTouchDevice())return D.None;Q.INSTANCE||(Q.INSTANCE=Gn(new Q));let i=Q.INSTANCE.ignoreTargets.push(e);return C(i)}static isTouchDevice(){return"ontouchstart"in fe||navigator.maxTouchPoints>0}dispose(){this.handle&&(this.handle.dispose(),this.handle=null),super.dispose()}onTouchStart(e){let i=Date.now();this.handle&&(this.handle.dispose(),this.handle=null);for(let r=0,n=e.targetTouches.length;r=Q.HOLD_DELAY&&Math.abs(u.initialPageX-Se(u.rollingPageX))<30&&Math.abs(u.initialPageY-Se(u.rollingPageY))<30){let c=this.newGestureEvent(He.Contextmenu,u.initialTarget);c.pageX=Se(u.rollingPageX),c.pageY=Se(u.rollingPageY),this.dispatchEvent(c)}else if(n===1){let c=Se(u.rollingPageX),d=Se(u.rollingPageY),_=Se(u.rollingTimestamps)-u.rollingTimestamps[0],p=c-u.rollingPageX[0],m=d-u.rollingPageY[0],f=[...this.targets].filter(A=>u.initialTarget instanceof Node&&A.contains(u.initialTarget));this.inertia(e,f,r,Math.abs(p)/_,p>0?1:-1,c,Math.abs(m)/_,m>0?1:-1,d)}this.dispatchEvent(this.newGestureEvent(He.End,u.initialTarget)),delete this.activeTouches[a.identifier]}this.dispatched&&(i.preventDefault(),i.stopPropagation(),this.dispatched=!1)}newGestureEvent(e,i){let r=document.createEvent("CustomEvent");return r.initEvent(e,!1,!0),r.initialTarget=i,r.tapCount=0,r}dispatchEvent(e){if(e.type===He.Tap){let i=new Date().getTime(),r=0;i-this._lastSetTapCountTime>Q.CLEAR_TAP_COUNT_TIME?r=1:r=2,this._lastSetTapCountTime=i,e.tapCount=r}else(e.type===He.Change||e.type===He.Contextmenu)&&(this._lastSetTapCountTime=0);if(e.initialTarget instanceof Node){for(let r of this.ignoreTargets)if(r.contains(e.initialTarget))return;let i=[];for(let r of this.targets)if(r.contains(e.initialTarget)){let n=0,o=e.initialTarget;for(;o&&o!==r;)n++,o=o.parentElement;i.push([n,r])}i.sort((r,n)=>r[0]-n[0]);for(let[r,n]of i)n.dispatchEvent(e),this.dispatched=!0}}inertia(e,i,r,n,o,l,a,u,h){this.handle=mt(e,()=>{let c=Date.now(),d=c-r,_=0,p=0,m=!0;n+=Q.SCROLL_FRICTION*d,a+=Q.SCROLL_FRICTION*d,n>0&&(m=!1,_=o*n*d),a>0&&(m=!1,p=u*a*d);let f=this.newGestureEvent(He.Change);f.translationX=_,f.translationY=p,i.forEach(A=>A.dispatchEvent(f)),m||this.inertia(e,i,c,n,o,l+_,a,u,h+p)})}onTouchMove(e){let i=Date.now();for(let r=0,n=e.changedTouches.length;r3&&(l.rollingPageX.shift(),l.rollingPageY.shift(),l.rollingTimestamps.shift()),l.rollingPageX.push(o.pageX),l.rollingPageY.push(o.pageY),l.rollingTimestamps.push(i)}this.dispatched&&(e.preventDefault(),e.stopPropagation(),this.dispatched=!1)}};Q.SCROLL_FRICTION=-.005,Q.HOLD_DELAY=700,Q.CLEAR_TAP_COUNT_TIME=400,M([Wo],Q,"isTouchDevice",1);var Pr=Q;var lt=class extends D{onclick(t,e){this._register(L(t,Y.CLICK,i=>e(new qe(be(t),i))))}onmousedown(t,e){this._register(L(t,Y.MOUSE_DOWN,i=>e(new qe(be(t),i))))}onmouseover(t,e){this._register(L(t,Y.MOUSE_OVER,i=>e(new qe(be(t),i))))}onmouseleave(t,e){this._register(L(t,Y.MOUSE_LEAVE,i=>e(new qe(be(t),i))))}onkeydown(t,e){this._register(L(t,Y.KEY_DOWN,i=>e(new ft(i))))}onkeyup(t,e){this._register(L(t,Y.KEY_UP,i=>e(new ft(i))))}oninput(t,e){this._register(L(t,Y.INPUT,e))}onblur(t,e){this._register(L(t,Y.BLUR,e))}onfocus(t,e){this._register(L(t,Y.FOCUS,e))}onchange(t,e){this._register(L(t,Y.CHANGE,e))}ignoreGesture(t){return Pr.ignoreTarget(t)}};var Uo=11,Or=class extends lt{constructor(t){super(),this._onActivate=t.onActivate,this.bgDomNode=document.createElement("div"),this.bgDomNode.className="arrow-background",this.bgDomNode.style.position="absolute",this.bgDomNode.style.width=t.bgWidth+"px",this.bgDomNode.style.height=t.bgHeight+"px",typeof t.top<"u"&&(this.bgDomNode.style.top="0px"),typeof t.left<"u"&&(this.bgDomNode.style.left="0px"),typeof t.bottom<"u"&&(this.bgDomNode.style.bottom="0px"),typeof t.right<"u"&&(this.bgDomNode.style.right="0px"),this.domNode=document.createElement("div"),this.domNode.className=t.className,this.domNode.style.position="absolute",this.domNode.style.width=Uo+"px",this.domNode.style.height=Uo+"px",typeof t.top<"u"&&(this.domNode.style.top=t.top+"px"),typeof t.left<"u"&&(this.domNode.style.left=t.left+"px"),typeof t.bottom<"u"&&(this.domNode.style.bottom=t.bottom+"px"),typeof t.right<"u"&&(this.domNode.style.right=t.right+"px"),this._pointerMoveMonitor=this._register(new Wt),this._register(os(this.bgDomNode,Y.POINTER_DOWN,e=>this._arrowPointerDown(e))),this._register(os(this.domNode,Y.POINTER_DOWN,e=>this._arrowPointerDown(e))),this._pointerdownRepeatTimer=this._register(new Mr),this._pointerdownScheduleRepeatTimer=this._register(new Ye)}_arrowPointerDown(t){if(!t.target||!(t.target instanceof Element))return;let e=()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,be(t))};this._onActivate(),this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancelAndSet(e,200),this._pointerMoveMonitor.startMonitoring(t.target,t.pointerId,t.buttons,i=>{},()=>{this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancel()}),t.preventDefault()}};var cs=class s{constructor(t,e,i,r,n,o,l){this._forceIntegerValues=t;this._scrollStateBrand=void 0;this._forceIntegerValues&&(e=e|0,i=i|0,r=r|0,n=n|0,o=o|0,l=l|0),this.rawScrollLeft=r,this.rawScrollTop=l,e<0&&(e=0),r+e>i&&(r=i-e),r<0&&(r=0),n<0&&(n=0),l+n>o&&(l=o-n),l<0&&(l=0),this.width=e,this.scrollWidth=i,this.scrollLeft=r,this.height=n,this.scrollHeight=o,this.scrollTop=l}equals(t){return this.rawScrollLeft===t.rawScrollLeft&&this.rawScrollTop===t.rawScrollTop&&this.width===t.width&&this.scrollWidth===t.scrollWidth&&this.scrollLeft===t.scrollLeft&&this.height===t.height&&this.scrollHeight===t.scrollHeight&&this.scrollTop===t.scrollTop}withScrollDimensions(t,e){return new s(this._forceIntegerValues,typeof t.width<"u"?t.width:this.width,typeof t.scrollWidth<"u"?t.scrollWidth:this.scrollWidth,e?this.rawScrollLeft:this.scrollLeft,typeof t.height<"u"?t.height:this.height,typeof t.scrollHeight<"u"?t.scrollHeight:this.scrollHeight,e?this.rawScrollTop:this.scrollTop)}withScrollPosition(t){return new s(this._forceIntegerValues,this.width,this.scrollWidth,typeof t.scrollLeft<"u"?t.scrollLeft:this.rawScrollLeft,this.height,this.scrollHeight,typeof t.scrollTop<"u"?t.scrollTop:this.rawScrollTop)}createScrollEvent(t,e){let i=this.width!==t.width,r=this.scrollWidth!==t.scrollWidth,n=this.scrollLeft!==t.scrollLeft,o=this.height!==t.height,l=this.scrollHeight!==t.scrollHeight,a=this.scrollTop!==t.scrollTop;return{inSmoothScrolling:e,oldWidth:t.width,oldScrollWidth:t.scrollWidth,oldScrollLeft:t.scrollLeft,width:this.width,scrollWidth:this.scrollWidth,scrollLeft:this.scrollLeft,oldHeight:t.height,oldScrollHeight:t.scrollHeight,oldScrollTop:t.scrollTop,height:this.height,scrollHeight:this.scrollHeight,scrollTop:this.scrollTop,widthChanged:i,scrollWidthChanged:r,scrollLeftChanged:n,heightChanged:o,scrollHeightChanged:l,scrollTopChanged:a}}},Ri=class extends D{constructor(e){super();this._scrollableBrand=void 0;this._onScroll=this._register(new v);this.onScroll=this._onScroll.event;this._smoothScrollDuration=e.smoothScrollDuration,this._scheduleAtNextAnimationFrame=e.scheduleAtNextAnimationFrame,this._state=new cs(e.forceIntegerValues,0,0,0,0,0,0),this._smoothScrolling=null}dispose(){this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),super.dispose()}setSmoothScrollDuration(e){this._smoothScrollDuration=e}validateScrollPosition(e){return this._state.withScrollPosition(e)}getScrollDimensions(){return this._state}setScrollDimensions(e,i){let r=this._state.withScrollDimensions(e,i);this._setState(r,!!this._smoothScrolling),this._smoothScrolling?.acceptScrollDimensions(this._state)}getFutureScrollPosition(){return this._smoothScrolling?this._smoothScrolling.to:this._state}getCurrentScrollPosition(){return this._state}setScrollPositionNow(e){let i=this._state.withScrollPosition(e);this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),this._setState(i,!1)}setScrollPositionSmooth(e,i){if(this._smoothScrollDuration===0)return this.setScrollPositionNow(e);if(this._smoothScrolling){e={scrollLeft:typeof e.scrollLeft>"u"?this._smoothScrolling.to.scrollLeft:e.scrollLeft,scrollTop:typeof e.scrollTop>"u"?this._smoothScrolling.to.scrollTop:e.scrollTop};let r=this._state.withScrollPosition(e);if(this._smoothScrolling.to.scrollLeft===r.scrollLeft&&this._smoothScrolling.to.scrollTop===r.scrollTop)return;let n;i?n=new Nr(this._smoothScrolling.from,r,this._smoothScrolling.startTime,this._smoothScrolling.duration):n=this._smoothScrolling.combine(this._state,r,this._smoothScrollDuration),this._smoothScrolling.dispose(),this._smoothScrolling=n}else{let r=this._state.withScrollPosition(e);this._smoothScrolling=Nr.start(this._state,r,this._smoothScrollDuration)}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}hasPendingScrollAnimation(){return!!this._smoothScrolling}_performSmoothScrolling(){if(!this._smoothScrolling)return;let e=this._smoothScrolling.tick(),i=this._state.withScrollPosition(e);if(this._setState(i,!0),!!this._smoothScrolling){if(e.isDone){this._smoothScrolling.dispose(),this._smoothScrolling=null;return}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}}_setState(e,i){let r=this._state;r.equals(e)||(this._state=e,this._onScroll.fire(this._state.createScrollEvent(r,i)))}},Br=class{constructor(t,e,i){this.scrollLeft=t,this.scrollTop=e,this.isDone=i}};function as(s,t){let e=t-s;return function(i){return s+e*ka(i)}}function La(s,t,e){return function(i){return i2.5*i){let n,o;return t{this._domNode?.setClassName(this._visibleClassName)},0))}_hide(t){this._revealTimer.cancel(),this._isVisible&&(this._isVisible=!1,this._domNode?.setClassName(this._invisibleClassName+(t?" fade":"")))}};var Ca=140,Ut=class extends lt{constructor(t){super(),this._lazyRender=t.lazyRender,this._host=t.host,this._scrollable=t.scrollable,this._scrollByPage=t.scrollByPage,this._scrollbarState=t.scrollbarState,this._visibilityController=this._register(new Fr(t.visibility,"visible scrollbar "+t.extraScrollbarClassName,"invisible scrollbar "+t.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new Wt),this._shouldRender=!0,this.domNode=_t(document.createElement("div")),this.domNode.setAttribute("role","presentation"),this.domNode.setAttribute("aria-hidden","true"),this._visibilityController.setDomNode(this.domNode),this.domNode.setPosition("absolute"),this._register(L(this.domNode.domNode,Y.POINTER_DOWN,e=>this._domNodePointerDown(e)))}_createArrow(t){let e=this._register(new Or(t));this.domNode.domNode.appendChild(e.bgDomNode),this.domNode.domNode.appendChild(e.domNode)}_createSlider(t,e,i,r){this.slider=_t(document.createElement("div")),this.slider.setClassName("slider"),this.slider.setPosition("absolute"),this.slider.setTop(t),this.slider.setLeft(e),typeof i=="number"&&this.slider.setWidth(i),typeof r=="number"&&this.slider.setHeight(r),this.slider.setLayerHinting(!0),this.slider.setContain("strict"),this.domNode.domNode.appendChild(this.slider.domNode),this._register(L(this.slider.domNode,Y.POINTER_DOWN,n=>{n.button===0&&(n.preventDefault(),this._sliderPointerDown(n))})),this.onclick(this.slider.domNode,n=>{n.leftButton&&n.stopPropagation()})}_onElementSize(t){return this._scrollbarState.setVisibleSize(t)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollSize(t){return this._scrollbarState.setScrollSize(t)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollPosition(t){return this._scrollbarState.setScrollPosition(t)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}beginReveal(){this._visibilityController.setShouldBeVisible(!0)}beginHide(){this._visibilityController.setShouldBeVisible(!1)}render(){this._shouldRender&&(this._shouldRender=!1,this._renderDomNode(this._scrollbarState.getRectangleLargeSize(),this._scrollbarState.getRectangleSmallSize()),this._updateSlider(this._scrollbarState.getSliderSize(),this._scrollbarState.getArrowSize()+this._scrollbarState.getSliderPosition()))}_domNodePointerDown(t){t.target===this.domNode.domNode&&this._onPointerDown(t)}delegatePointerDown(t){let e=this.domNode.domNode.getClientRects()[0].top,i=e+this._scrollbarState.getSliderPosition(),r=e+this._scrollbarState.getSliderPosition()+this._scrollbarState.getSliderSize(),n=this._sliderPointerPosition(t);i<=n&&n<=r?t.button===0&&(t.preventDefault(),this._sliderPointerDown(t)):this._onPointerDown(t)}_onPointerDown(t){let e,i;if(t.target===this.domNode.domNode&&typeof t.offsetX=="number"&&typeof t.offsetY=="number")e=t.offsetX,i=t.offsetY;else{let n=Fo(this.domNode.domNode);e=t.pageX-n.left,i=t.pageY-n.top}let r=this._pointerDownRelativePosition(e,i);this._setDesiredScrollPositionNow(this._scrollByPage?this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(r):this._scrollbarState.getDesiredScrollPositionFromOffset(r)),t.button===0&&(t.preventDefault(),this._sliderPointerDown(t))}_sliderPointerDown(t){if(!t.target||!(t.target instanceof Element))return;let e=this._sliderPointerPosition(t),i=this._sliderOrthogonalPointerPosition(t),r=this._scrollbarState.clone();this.slider.toggleClassName("active",!0),this._pointerMoveMonitor.startMonitoring(t.target,t.pointerId,t.buttons,n=>{let o=this._sliderOrthogonalPointerPosition(n),l=Math.abs(o-i);if(wr&&l>Ca){this._setDesiredScrollPositionNow(r.getScrollPosition());return}let u=this._sliderPointerPosition(n)-e;this._setDesiredScrollPositionNow(r.getDesiredScrollPositionFromDelta(u))},()=>{this.slider.toggleClassName("active",!1),this._host.onDragEnd()}),this._host.onDragStart()}_setDesiredScrollPositionNow(t){let e={};this.writeScrollPosition(e,t),this._scrollable.setScrollPositionNow(e)}updateScrollbarSize(t){this._updateScrollbarSize(t),this._scrollbarState.setScrollbarSize(t),this._shouldRender=!0,this._lazyRender||this.render()}isNeeded(){return this._scrollbarState.isNeeded()}};var Kt=class s{constructor(t,e,i,r,n,o){this._scrollbarSize=Math.round(e),this._oppositeScrollbarSize=Math.round(i),this._arrowSize=Math.round(t),this._visibleSize=r,this._scrollSize=n,this._scrollPosition=o,this._computedAvailableSize=0,this._computedIsNeeded=!1,this._computedSliderSize=0,this._computedSliderRatio=0,this._computedSliderPosition=0,this._refreshComputedValues()}clone(){return new s(this._arrowSize,this._scrollbarSize,this._oppositeScrollbarSize,this._visibleSize,this._scrollSize,this._scrollPosition)}setVisibleSize(t){let e=Math.round(t);return this._visibleSize!==e?(this._visibleSize=e,this._refreshComputedValues(),!0):!1}setScrollSize(t){let e=Math.round(t);return this._scrollSize!==e?(this._scrollSize=e,this._refreshComputedValues(),!0):!1}setScrollPosition(t){let e=Math.round(t);return this._scrollPosition!==e?(this._scrollPosition=e,this._refreshComputedValues(),!0):!1}setScrollbarSize(t){this._scrollbarSize=Math.round(t)}setOppositeScrollbarSize(t){this._oppositeScrollbarSize=Math.round(t)}static _computeValues(t,e,i,r,n){let o=Math.max(0,i-t),l=Math.max(0,o-2*e),a=r>0&&r>i;if(!a)return{computedAvailableSize:Math.round(o),computedIsNeeded:a,computedSliderSize:Math.round(l),computedSliderRatio:0,computedSliderPosition:0};let u=Math.round(Math.max(20,Math.floor(i*l/r))),h=(l-u)/(r-i),c=n*h;return{computedAvailableSize:Math.round(o),computedIsNeeded:a,computedSliderSize:Math.round(u),computedSliderRatio:h,computedSliderPosition:Math.round(c)}}_refreshComputedValues(){let t=s._computeValues(this._oppositeScrollbarSize,this._arrowSize,this._visibleSize,this._scrollSize,this._scrollPosition);this._computedAvailableSize=t.computedAvailableSize,this._computedIsNeeded=t.computedIsNeeded,this._computedSliderSize=t.computedSliderSize,this._computedSliderRatio=t.computedSliderRatio,this._computedSliderPosition=t.computedSliderPosition}getArrowSize(){return this._arrowSize}getScrollPosition(){return this._scrollPosition}getRectangleLargeSize(){return this._computedAvailableSize}getRectangleSmallSize(){return this._scrollbarSize}isNeeded(){return this._computedIsNeeded}getSliderSize(){return this._computedSliderSize}getSliderPosition(){return this._computedSliderPosition}getDesiredScrollPositionFromOffset(t){if(!this._computedIsNeeded)return 0;let e=t-this._arrowSize-this._computedSliderSize/2;return Math.round(e/this._computedSliderRatio)}getDesiredScrollPositionFromOffsetPaged(t){if(!this._computedIsNeeded)return 0;let e=t-this._arrowSize,i=this._scrollPosition;return e0&&Math.abs(t.deltaY)>0)return 1;let i=.5;if((!this._isAlmostInt(t.deltaX)||!this._isAlmostInt(t.deltaY))&&(i+=.25),e){let r=Math.abs(t.deltaX),n=Math.abs(t.deltaY),o=Math.abs(e.deltaX),l=Math.abs(e.deltaY),a=Math.max(Math.min(r,o),1),u=Math.max(Math.min(n,l),1),h=Math.max(r,o),c=Math.max(n,l);h%a===0&&c%u===0&&(i-=.5)}return Math.min(Math.max(i,0),1)}_isAlmostInt(t){return Math.abs(Math.round(t)-t)<.01}};zr.INSTANCE=new zr;var hs=zr,ds=class extends lt{constructor(e,i,r){super();this._onScroll=this._register(new v);this.onScroll=this._onScroll.event;this._onWillScroll=this._register(new v);this.onWillScroll=this._onWillScroll.event;this._options=Pa(i),this._scrollable=r,this._register(this._scrollable.onScroll(o=>{this._onWillScroll.fire(o),this._onDidScroll(o),this._onScroll.fire(o)}));let n={onMouseWheel:o=>this._onMouseWheel(o),onDragStart:()=>this._onDragStart(),onDragEnd:()=>this._onDragEnd()};this._verticalScrollbar=this._register(new Ur(this._scrollable,this._options,n)),this._horizontalScrollbar=this._register(new Wr(this._scrollable,this._options,n)),this._domNode=document.createElement("div"),this._domNode.className="xterm-scrollable-element "+this._options.className,this._domNode.setAttribute("role","presentation"),this._domNode.style.position="relative",this._domNode.appendChild(e),this._domNode.appendChild(this._horizontalScrollbar.domNode.domNode),this._domNode.appendChild(this._verticalScrollbar.domNode.domNode),this._options.useShadows?(this._leftShadowDomNode=_t(document.createElement("div")),this._leftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=_t(document.createElement("div")),this._topShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=_t(document.createElement("div")),this._topLeftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topLeftShadowDomNode.domNode)):(this._leftShadowDomNode=null,this._topShadowDomNode=null,this._topLeftShadowDomNode=null),this._listenOnDomNode=this._options.listenOnDomNode||this._domNode,this._mouseWheelToDispose=[],this._setListeningToMouseWheel(this._options.handleMouseWheel),this.onmouseover(this._listenOnDomNode,o=>this._onMouseOver(o)),this.onmouseleave(this._listenOnDomNode,o=>this._onMouseLeave(o)),this._hideTimeout=this._register(new Ye),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=Ne(this._mouseWheelToDispose),super.dispose()}getDomNode(){return this._domNode}getOverviewRulerLayoutInfo(){return{parent:this._domNode,insertBefore:this._verticalScrollbar.domNode.domNode}}delegateVerticalScrollbarPointerDown(e){this._verticalScrollbar.delegatePointerDown(e)}getScrollDimensions(){return this._scrollable.getScrollDimensions()}setScrollDimensions(e){this._scrollable.setScrollDimensions(e,!1)}updateClassName(e){this._options.className=e,Te&&(this._options.className+=" mac"),this._domNode.className="xterm-scrollable-element "+this._options.className}updateOptions(e){typeof e.handleMouseWheel<"u"&&(this._options.handleMouseWheel=e.handleMouseWheel,this._setListeningToMouseWheel(this._options.handleMouseWheel)),typeof e.mouseWheelScrollSensitivity<"u"&&(this._options.mouseWheelScrollSensitivity=e.mouseWheelScrollSensitivity),typeof e.fastScrollSensitivity<"u"&&(this._options.fastScrollSensitivity=e.fastScrollSensitivity),typeof e.scrollPredominantAxis<"u"&&(this._options.scrollPredominantAxis=e.scrollPredominantAxis),typeof e.horizontal<"u"&&(this._options.horizontal=e.horizontal),typeof e.vertical<"u"&&(this._options.vertical=e.vertical),typeof e.horizontalScrollbarSize<"u"&&(this._options.horizontalScrollbarSize=e.horizontalScrollbarSize),typeof e.verticalScrollbarSize<"u"&&(this._options.verticalScrollbarSize=e.verticalScrollbarSize),typeof e.scrollByPage<"u"&&(this._options.scrollByPage=e.scrollByPage),this._horizontalScrollbar.updateOptions(this._options),this._verticalScrollbar.updateOptions(this._options),this._options.lazyRender||this._render()}setRevealOnScroll(e){this._revealOnScroll=e}delegateScrollFromMouseWheelEvent(e){this._onMouseWheel(new xi(e))}_setListeningToMouseWheel(e){if(this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=Ne(this._mouseWheelToDispose),e)){let r=n=>{this._onMouseWheel(new xi(n))};this._mouseWheelToDispose.push(L(this._listenOnDomNode,Y.MOUSE_WHEEL,r,{passive:!1}))}}_onMouseWheel(e){if(e.browserEvent?.defaultPrevented)return;let i=hs.INSTANCE;zo&&i.acceptStandardWheelEvent(e);let r=!1;if(e.deltaY||e.deltaX){let o=e.deltaY*this._options.mouseWheelScrollSensitivity,l=e.deltaX*this._options.mouseWheelScrollSensitivity;this._options.scrollPredominantAxis&&(this._options.scrollYToX&&l+o===0?l=o=0:Math.abs(o)>=Math.abs(l)?l=0:o=0),this._options.flipAxes&&([o,l]=[l,o]);let a=!Te&&e.browserEvent&&e.browserEvent.shiftKey;(this._options.scrollYToX||a)&&!l&&(l=o,o=0),e.browserEvent&&e.browserEvent.altKey&&(l=l*this._options.fastScrollSensitivity,o=o*this._options.fastScrollSensitivity);let u=this._scrollable.getFutureScrollPosition(),h={};if(o){let c=Ko*o,d=u.scrollTop-(c<0?Math.floor(c):Math.ceil(c));this._verticalScrollbar.writeScrollPosition(h,d)}if(l){let c=Ko*l,d=u.scrollLeft-(c<0?Math.floor(c):Math.ceil(c));this._horizontalScrollbar.writeScrollPosition(h,d)}h=this._scrollable.validateScrollPosition(h),(u.scrollLeft!==h.scrollLeft||u.scrollTop!==h.scrollTop)&&(zo&&this._options.mouseWheelSmoothScroll&&i.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(h):this._scrollable.setScrollPositionNow(h),r=!0)}let n=r;!n&&this._options.alwaysConsumeMouseWheel&&(n=!0),!n&&this._options.consumeMouseWheelIfScrollbarIsNeeded&&(this._verticalScrollbar.isNeeded()||this._horizontalScrollbar.isNeeded())&&(n=!0),n&&(e.preventDefault(),e.stopPropagation())}_onDidScroll(e){this._shouldRender=this._horizontalScrollbar.onDidScroll(e)||this._shouldRender,this._shouldRender=this._verticalScrollbar.onDidScroll(e)||this._shouldRender,this._options.useShadows&&(this._shouldRender=!0),this._revealOnScroll&&this._reveal(),this._options.lazyRender||this._render()}renderNow(){if(!this._options.lazyRender)throw new Error("Please use `lazyRender` together with `renderNow`!");this._render()}_render(){if(this._shouldRender&&(this._shouldRender=!1,this._horizontalScrollbar.render(),this._verticalScrollbar.render(),this._options.useShadows)){let e=this._scrollable.getCurrentScrollPosition(),i=e.scrollTop>0,r=e.scrollLeft>0,n=r?" left":"",o=i?" top":"",l=r||i?" top-left-corner":"";this._leftShadowDomNode.setClassName(`shadow${n}`),this._topShadowDomNode.setClassName(`shadow${o}`),this._topLeftShadowDomNode.setClassName(`shadow${l}${o}${n}`)}}_onDragStart(){this._isDragging=!0,this._reveal()}_onDragEnd(){this._isDragging=!1,this._hide()}_onMouseLeave(e){this._mouseIsOver=!1,this._hide()}_onMouseOver(e){this._mouseIsOver=!0,this._reveal()}_reveal(){this._verticalScrollbar.beginReveal(),this._horizontalScrollbar.beginReveal(),this._scheduleHide()}_hide(){!this._mouseIsOver&&!this._isDragging&&(this._verticalScrollbar.beginHide(),this._horizontalScrollbar.beginHide())}_scheduleHide(){!this._mouseIsOver&&!this._isDragging&&this._hideTimeout.cancelAndSet(()=>this._hide(),Ma)}};var Kr=class extends ds{constructor(t,e,i){super(t,e,i)}setScrollPosition(t){t.reuseAnimation?this._scrollable.setScrollPositionSmooth(t,t.reuseAnimation):this._scrollable.setScrollPositionNow(t)}getScrollPosition(){return this._scrollable.getCurrentScrollPosition()}};function Pa(s){let t={lazyRender:typeof s.lazyRender<"u"?s.lazyRender:!1,className:typeof s.className<"u"?s.className:"",useShadows:typeof s.useShadows<"u"?s.useShadows:!0,handleMouseWheel:typeof s.handleMouseWheel<"u"?s.handleMouseWheel:!0,flipAxes:typeof s.flipAxes<"u"?s.flipAxes:!1,consumeMouseWheelIfScrollbarIsNeeded:typeof s.consumeMouseWheelIfScrollbarIsNeeded<"u"?s.consumeMouseWheelIfScrollbarIsNeeded:!1,alwaysConsumeMouseWheel:typeof s.alwaysConsumeMouseWheel<"u"?s.alwaysConsumeMouseWheel:!1,scrollYToX:typeof s.scrollYToX<"u"?s.scrollYToX:!1,mouseWheelScrollSensitivity:typeof s.mouseWheelScrollSensitivity<"u"?s.mouseWheelScrollSensitivity:1,fastScrollSensitivity:typeof s.fastScrollSensitivity<"u"?s.fastScrollSensitivity:5,scrollPredominantAxis:typeof s.scrollPredominantAxis<"u"?s.scrollPredominantAxis:!0,mouseWheelSmoothScroll:typeof s.mouseWheelSmoothScroll<"u"?s.mouseWheelSmoothScroll:!0,arrowSize:typeof s.arrowSize<"u"?s.arrowSize:11,listenOnDomNode:typeof s.listenOnDomNode<"u"?s.listenOnDomNode:null,horizontal:typeof s.horizontal<"u"?s.horizontal:1,horizontalScrollbarSize:typeof s.horizontalScrollbarSize<"u"?s.horizontalScrollbarSize:10,horizontalSliderSize:typeof s.horizontalSliderSize<"u"?s.horizontalSliderSize:0,horizontalHasArrows:typeof s.horizontalHasArrows<"u"?s.horizontalHasArrows:!1,vertical:typeof s.vertical<"u"?s.vertical:1,verticalScrollbarSize:typeof s.verticalScrollbarSize<"u"?s.verticalScrollbarSize:10,verticalHasArrows:typeof s.verticalHasArrows<"u"?s.verticalHasArrows:!1,verticalSliderSize:typeof s.verticalSliderSize<"u"?s.verticalSliderSize:0,scrollByPage:typeof s.scrollByPage<"u"?s.scrollByPage:!1};return t.horizontalSliderSize=typeof s.horizontalSliderSize<"u"?s.horizontalSliderSize:t.horizontalScrollbarSize,t.verticalSliderSize=typeof s.verticalSliderSize<"u"?s.verticalSliderSize:t.verticalScrollbarSize,Te&&(t.className+=" mac"),t}var zt=class extends D{constructor(e,i,r,n,o,l,a,u){super();this._bufferService=r;this._optionsService=a;this._renderService=u;this._onRequestScrollLines=this._register(new v);this.onRequestScrollLines=this._onRequestScrollLines.event;this._isSyncing=!1;this._isHandlingScroll=!1;this._suppressOnScrollHandler=!1;let h=this._register(new Ri({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:c=>mt(n.window,c)}));this._register(this._optionsService.onSpecificOptionChange("smoothScrollDuration",()=>{h.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new Kr(i,{vertical:1,horizontal:2,useShadows:!1,mouseWheelSmoothScroll:!0,...this._getChangeOptions()},h)),this._register(this._optionsService.onMultipleOptionChange(["scrollSensitivity","fastScrollSensitivity","overviewRuler"],()=>this._scrollableElement.updateOptions(this._getChangeOptions()))),this._register(o.onProtocolChange(c=>{this._scrollableElement.updateOptions({handleMouseWheel:!(c&16)})})),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register($.runAndSubscribe(l.onChangeColors,()=>{this._scrollableElement.getDomNode().style.backgroundColor=l.colors.background.css})),e.appendChild(this._scrollableElement.getDomNode()),this._register(C(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=n.mainDocument.createElement("style"),i.appendChild(this._styleElement),this._register(C(()=>this._styleElement.remove())),this._register($.runAndSubscribe(l.onChangeColors,()=>{this._styleElement.textContent=[".xterm .xterm-scrollable-element > .scrollbar > .slider {",` background: ${l.colors.scrollbarSliderBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider:hover {",` background: ${l.colors.scrollbarSliderHoverBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider.active {",` background: ${l.colors.scrollbarSliderActiveBackground.css};`,"}"].join(` +`)})),this._register(this._bufferService.onResize(()=>this.queueSync())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._latestYDisp=void 0,this.queueSync()})),this._register(this._bufferService.onScroll(()=>this._sync())),this._register(this._scrollableElement.onScroll(c=>this._handleScroll(c)))}scrollLines(e){let i=this._scrollableElement.getScrollPosition();this._scrollableElement.setScrollPosition({reuseAnimation:!0,scrollTop:i.scrollTop+e*this._renderService.dimensions.css.cell.height})}scrollToLine(e,i){i&&(this._latestYDisp=e),this._scrollableElement.setScrollPosition({reuseAnimation:!i,scrollTop:e*this._renderService.dimensions.css.cell.height})}_getChangeOptions(){return{mouseWheelScrollSensitivity:this._optionsService.rawOptions.scrollSensitivity,fastScrollSensitivity:this._optionsService.rawOptions.fastScrollSensitivity,verticalScrollbarSize:this._optionsService.rawOptions.overviewRuler?.width||14}}queueSync(e){e!==void 0&&(this._latestYDisp=e),this._queuedAnimationFrame===void 0&&(this._queuedAnimationFrame=this._renderService.addRefreshCallback(()=>{this._queuedAnimationFrame=void 0,this._sync(this._latestYDisp)}))}_sync(e=this._bufferService.buffer.ydisp){!this._renderService||this._isSyncing||(this._isSyncing=!0,this._suppressOnScrollHandler=!0,this._scrollableElement.setScrollDimensions({height:this._renderService.dimensions.css.canvas.height,scrollHeight:this._renderService.dimensions.css.cell.height*this._bufferService.buffer.lines.length}),this._suppressOnScrollHandler=!1,e!==this._latestYDisp&&this._scrollableElement.setScrollPosition({scrollTop:e*this._renderService.dimensions.css.cell.height}),this._isSyncing=!1)}_handleScroll(e){if(!this._renderService||this._isHandlingScroll||this._suppressOnScrollHandler)return;this._isHandlingScroll=!0;let i=Math.round(e.scrollTop/this._renderService.dimensions.css.cell.height),r=i-this._bufferService.buffer.ydisp;r!==0&&(this._latestYDisp=i,this._onRequestScrollLines.fire(r)),this._isHandlingScroll=!1}};zt=M([S(2,F),S(3,ae),S(4,rr),S(5,Re),S(6,H),S(7,ce)],zt);var Gt=class extends D{constructor(e,i,r,n,o){super();this._screenElement=e;this._bufferService=i;this._coreBrowserService=r;this._decorationService=n;this._renderService=o;this._decorationElements=new Map;this._altBufferIsActive=!1;this._dimensionsChanged=!1;this._container=document.createElement("div"),this._container.classList.add("xterm-decoration-container"),this._screenElement.appendChild(this._container),this._register(this._renderService.onRenderedViewportChange(()=>this._doRefreshDecorations())),this._register(this._renderService.onDimensionsChange(()=>{this._dimensionsChanged=!0,this._queueRefresh()})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt})),this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh())),this._register(this._decorationService.onDecorationRemoved(l=>this._removeDecoration(l))),this._register(C(()=>{this._container.remove(),this._decorationElements.clear()}))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback(()=>{this._doRefreshDecorations(),this._animationFrame=void 0}))}_doRefreshDecorations(){for(let e of this._decorationService.decorations)this._renderDecoration(e);this._dimensionsChanged=!1}_renderDecoration(e){this._refreshStyle(e),this._dimensionsChanged&&this._refreshXPosition(e)}_createElement(e){let i=this._coreBrowserService.mainDocument.createElement("div");i.classList.add("xterm-decoration"),i.classList.toggle("xterm-decoration-top-layer",e?.options?.layer==="top"),i.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,i.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,i.style.top=`${(e.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height}px`,i.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;let r=e.options.x??0;return r&&r>this._bufferService.cols&&(i.style.display="none"),this._refreshXPosition(e,i),i}_refreshStyle(e){let i=e.marker.line-this._bufferService.buffers.active.ydisp;if(i<0||i>=this._bufferService.rows)e.element&&(e.element.style.display="none",e.onRenderEmitter.fire(e.element));else{let r=this._decorationElements.get(e);r||(r=this._createElement(e),e.element=r,this._decorationElements.set(e,r),this._container.appendChild(r),e.onDispose(()=>{this._decorationElements.delete(e),r.remove()})),r.style.display=this._altBufferIsActive?"none":"block",this._altBufferIsActive||(r.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,r.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,r.style.top=`${i*this._renderService.dimensions.css.cell.height}px`,r.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`),e.onRenderEmitter.fire(r)}}_refreshXPosition(e,i=e.element){if(!i)return;let r=e.options.x??0;(e.options.anchor||"left")==="right"?i.style.right=r?`${r*this._renderService.dimensions.css.cell.width}px`:"":i.style.left=r?`${r*this._renderService.dimensions.css.cell.width}px`:""}_removeDecoration(e){this._decorationElements.get(e)?.remove(),this._decorationElements.delete(e),e.dispose()}};Gt=M([S(1,F),S(2,ae),S(3,Be),S(4,ce)],Gt);var Gr=class{constructor(){this._zones=[];this._zonePool=[];this._zonePoolIndex=0;this._linePadding={full:0,left:0,center:0,right:0}}get zones(){return this._zonePool.length=Math.min(this._zonePool.length,this._zones.length),this._zones}clear(){this._zones.length=0,this._zonePoolIndex=0}addDecoration(t){if(t.options.overviewRulerOptions){for(let e of this._zones)if(e.color===t.options.overviewRulerOptions.color&&e.position===t.options.overviewRulerOptions.position){if(this._lineIntersectsZone(e,t.marker.line))return;if(this._lineAdjacentToZone(e,t.marker.line,t.options.overviewRulerOptions.position)){this._addLineToZone(e,t.marker.line);return}}if(this._zonePoolIndex=t.startBufferLine&&e<=t.endBufferLine}_lineAdjacentToZone(t,e,i){return e>=t.startBufferLine-this._linePadding[i||"full"]&&e<=t.endBufferLine+this._linePadding[i||"full"]}_addLineToZone(t,e){t.startBufferLine=Math.min(t.startBufferLine,e),t.endBufferLine=Math.max(t.endBufferLine,e)}};var We={full:0,left:0,center:0,right:0},at={full:0,left:0,center:0,right:0},Li={full:0,left:0,center:0,right:0},bt=class extends D{constructor(e,i,r,n,o,l,a,u){super();this._viewportElement=e;this._screenElement=i;this._bufferService=r;this._decorationService=n;this._renderService=o;this._optionsService=l;this._themeService=a;this._coreBrowserService=u;this._colorZoneStore=new Gr;this._shouldUpdateDimensions=!0;this._shouldUpdateAnchor=!0;this._lastKnownBufferLength=0;this._canvas=this._coreBrowserService.mainDocument.createElement("canvas"),this._canvas.classList.add("xterm-decoration-overview-ruler"),this._refreshCanvasDimensions(),this._viewportElement.parentElement?.insertBefore(this._canvas,this._viewportElement),this._register(C(()=>this._canvas?.remove()));let h=this._canvas.getContext("2d");if(h)this._ctx=h;else throw new Error("Ctx cannot be null");this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh(void 0,!0))),this._register(this._decorationService.onDecorationRemoved(()=>this._queueRefresh(void 0,!0))),this._register(this._renderService.onRenderedViewportChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?"none":"block"})),this._register(this._bufferService.onScroll(()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())})),this._register(this._renderService.onRender(()=>{(!this._containerHeight||this._containerHeight!==this._screenElement.clientHeight)&&(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh(!0))),this._register(this._optionsService.onSpecificOptionChange("overviewRuler",()=>this._queueRefresh(!0))),this._register(this._themeService.onChangeColors(()=>this._queueRefresh())),this._queueRefresh(!0)}get _width(){return this._optionsService.options.overviewRuler?.width||0}_refreshDrawConstants(){let e=Math.floor((this._canvas.width-1)/3),i=Math.ceil((this._canvas.width-1)/3);at.full=this._canvas.width,at.left=e,at.center=i,at.right=e,this._refreshDrawHeightConstants(),Li.full=1,Li.left=1,Li.center=1+at.left,Li.right=1+at.left+at.center}_refreshDrawHeightConstants(){We.full=Math.round(2*this._coreBrowserService.dpr);let e=this._canvas.height/this._bufferService.buffer.lines.length,i=Math.round(Math.max(Math.min(e,12),6)*this._coreBrowserService.dpr);We.left=i,We.center=i,We.right=i}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*We.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*We.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*We.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*We.right)}),this._lastKnownBufferLength=this._bufferService.buffers.normal.lines.length}_refreshCanvasDimensions(){this._canvas.style.width=`${this._width}px`,this._canvas.width=Math.round(this._width*this._coreBrowserService.dpr),this._canvas.style.height=`${this._screenElement.clientHeight}px`,this._canvas.height=Math.round(this._screenElement.clientHeight*this._coreBrowserService.dpr),this._refreshDrawConstants(),this._refreshColorZonePadding()}_refreshDecorations(){this._shouldUpdateDimensions&&this._refreshCanvasDimensions(),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._colorZoneStore.clear();for(let i of this._decorationService.decorations)this._colorZoneStore.addDecoration(i);this._ctx.lineWidth=1,this._renderRulerOutline();let e=this._colorZoneStore.zones;for(let i of e)i.position!=="full"&&this._renderColorZone(i);for(let i of e)i.position==="full"&&this._renderColorZone(i);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderRulerOutline(){this._ctx.fillStyle=this._themeService.colors.overviewRulerBorder.css,this._ctx.fillRect(0,0,1,this._canvas.height),this._optionsService.rawOptions.overviewRuler.showTopBorder&&this._ctx.fillRect(1,0,this._canvas.width-1,1),this._optionsService.rawOptions.overviewRuler.showBottomBorder&&this._ctx.fillRect(1,this._canvas.height-1,this._canvas.width-1,this._canvas.height)}_renderColorZone(e){this._ctx.fillStyle=e.color,this._ctx.fillRect(Li[e.position||"full"],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-We[e.position||"full"]/2),at[e.position||"full"],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+We[e.position||"full"]))}_queueRefresh(e,i){this._shouldUpdateDimensions=e||this._shouldUpdateDimensions,this._shouldUpdateAnchor=i||this._shouldUpdateAnchor,this._animationFrame===void 0&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._refreshDecorations(),this._animationFrame=void 0}))}};bt=M([S(2,F),S(3,Be),S(4,ce),S(5,H),S(6,Re),S(7,ae)],bt);var b;(E=>(E.NUL="\0",E.SOH="",E.STX="",E.ETX="",E.EOT="",E.ENQ="",E.ACK="",E.BEL="\x07",E.BS="\b",E.HT=" ",E.LF=` +`,E.VT="\v",E.FF="\f",E.CR="\r",E.SO="",E.SI="",E.DLE="",E.DC1="",E.DC2="",E.DC3="",E.DC4="",E.NAK="",E.SYN="",E.ETB="",E.CAN="",E.EM="",E.SUB="",E.ESC="\x1B",E.FS="",E.GS="",E.RS="",E.US="",E.SP=" ",E.DEL="\x7F"))(b||={});var Ai;(g=>(g.PAD="\x80",g.HOP="\x81",g.BPH="\x82",g.NBH="\x83",g.IND="\x84",g.NEL="\x85",g.SSA="\x86",g.ESA="\x87",g.HTS="\x88",g.HTJ="\x89",g.VTS="\x8A",g.PLD="\x8B",g.PLU="\x8C",g.RI="\x8D",g.SS2="\x8E",g.SS3="\x8F",g.DCS="\x90",g.PU1="\x91",g.PU2="\x92",g.STS="\x93",g.CCH="\x94",g.MW="\x95",g.SPA="\x96",g.EPA="\x97",g.SOS="\x98",g.SGCI="\x99",g.SCI="\x9A",g.CSI="\x9B",g.ST="\x9C",g.OSC="\x9D",g.PM="\x9E",g.APC="\x9F"))(Ai||={});var fs;(t=>t.ST=`${b.ESC}\\`)(fs||={});var $t=class{constructor(t,e,i,r,n,o){this._textarea=t;this._compositionView=e;this._bufferService=i;this._optionsService=r;this._coreService=n;this._renderService=o;this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=""}get isComposing(){return this._isComposing}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent="",this._dataAlreadySent="",this._compositionView.classList.add("active")}compositionupdate(t){this._compositionView.textContent=t.data,this.updateCompositionElements(),setTimeout(()=>{this._compositionPosition.end=this._textarea.value.length},0)}compositionend(){this._finalizeComposition(!0)}keydown(t){if(this._isComposing||this._isSendingComposition){if(t.keyCode===20||t.keyCode===229||t.keyCode===16||t.keyCode===17||t.keyCode===18)return!1;this._finalizeComposition(!1)}return t.keyCode===229?(this._handleAnyTextareaChanges(),!1):!0}_finalizeComposition(t){if(this._compositionView.classList.remove("active"),this._isComposing=!1,t){let e={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){this._isSendingComposition=!1;let i;e.start+=this._dataAlreadySent.length,this._isComposing?i=this._textarea.value.substring(e.start,this._compositionPosition.start):i=this._textarea.value.substring(e.start),i.length>0&&this._coreService.triggerDataEvent(i,!0)}},0)}else{this._isSendingComposition=!1;let e=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(e,!0)}}_handleAnyTextareaChanges(){let t=this._textarea.value;setTimeout(()=>{if(!this._isComposing){let e=this._textarea.value,i=e.replace(t,"");this._dataAlreadySent=i,e.length>t.length?this._coreService.triggerDataEvent(i,!0):e.lengththis.updateCompositionElements(!0),0)}}};$t=M([S(2,F),S(3,H),S(4,ge),S(5,ce)],$t);var ue=0,he=0,de=0,J=0,ps={css:"#00000000",rgba:0},j;(i=>{function s(r,n,o,l){return l!==void 0?`#${vt(r)}${vt(n)}${vt(o)}${vt(l)}`:`#${vt(r)}${vt(n)}${vt(o)}`}i.toCss=s;function t(r,n,o,l=255){return(r<<24|n<<16|o<<8|l)>>>0}i.toRgba=t;function e(r,n,o,l){return{css:i.toCss(r,n,o,l),rgba:i.toRgba(r,n,o,l)}}i.toColor=e})(j||={});var U;(l=>{function s(a,u){if(J=(u.rgba&255)/255,J===1)return{css:u.css,rgba:u.rgba};let h=u.rgba>>24&255,c=u.rgba>>16&255,d=u.rgba>>8&255,_=a.rgba>>24&255,p=a.rgba>>16&255,m=a.rgba>>8&255;ue=_+Math.round((h-_)*J),he=p+Math.round((c-p)*J),de=m+Math.round((d-m)*J);let f=j.toCss(ue,he,de),A=j.toRgba(ue,he,de);return{css:f,rgba:A}}l.blend=s;function t(a){return(a.rgba&255)===255}l.isOpaque=t;function e(a,u,h){let c=$r.ensureContrastRatio(a.rgba,u.rgba,h);if(c)return j.toColor(c>>24&255,c>>16&255,c>>8&255)}l.ensureContrastRatio=e;function i(a){let u=(a.rgba|255)>>>0;return[ue,he,de]=$r.toChannels(u),{css:j.toCss(ue,he,de),rgba:u}}l.opaque=i;function r(a,u){return J=Math.round(u*255),[ue,he,de]=$r.toChannels(a.rgba),{css:j.toCss(ue,he,de,J),rgba:j.toRgba(ue,he,de,J)}}l.opacity=r;function n(a,u){return J=a.rgba&255,r(a,J*u/255)}l.multiplyOpacity=n;function o(a){return[a.rgba>>24&255,a.rgba>>16&255,a.rgba>>8&255]}l.toColorRGB=o})(U||={});var z;(i=>{let s,t;try{let r=document.createElement("canvas");r.width=1,r.height=1;let n=r.getContext("2d",{willReadFrequently:!0});n&&(s=n,s.globalCompositeOperation="copy",t=s.createLinearGradient(0,0,1,1))}catch{}function e(r){if(r.match(/#[\da-f]{3,8}/i))switch(r.length){case 4:return ue=parseInt(r.slice(1,2).repeat(2),16),he=parseInt(r.slice(2,3).repeat(2),16),de=parseInt(r.slice(3,4).repeat(2),16),j.toColor(ue,he,de);case 5:return ue=parseInt(r.slice(1,2).repeat(2),16),he=parseInt(r.slice(2,3).repeat(2),16),de=parseInt(r.slice(3,4).repeat(2),16),J=parseInt(r.slice(4,5).repeat(2),16),j.toColor(ue,he,de,J);case 7:return{css:r,rgba:(parseInt(r.slice(1),16)<<8|255)>>>0};case 9:return{css:r,rgba:parseInt(r.slice(1),16)>>>0}}let n=r.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(n)return ue=parseInt(n[1]),he=parseInt(n[2]),de=parseInt(n[3]),J=Math.round((n[5]===void 0?1:parseFloat(n[5]))*255),j.toColor(ue,he,de,J);if(!s||!t)throw new Error("css.toColor: Unsupported css format");if(s.fillStyle=t,s.fillStyle=r,typeof s.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(s.fillRect(0,0,1,1),[ue,he,de,J]=s.getImageData(0,0,1,1).data,J!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:j.toRgba(ue,he,de,J),css:r}}i.toColor=e})(z||={});var ve;(e=>{function s(i){return t(i>>16&255,i>>8&255,i&255)}e.relativeLuminance=s;function t(i,r,n){let o=i/255,l=r/255,a=n/255,u=o<=.03928?o/12.92:Math.pow((o+.055)/1.055,2.4),h=l<=.03928?l/12.92:Math.pow((l+.055)/1.055,2.4),c=a<=.03928?a/12.92:Math.pow((a+.055)/1.055,2.4);return u*.2126+h*.7152+c*.0722}e.relativeLuminance2=t})(ve||={});var $r;(n=>{function s(o,l){if(J=(l&255)/255,J===1)return l;let a=l>>24&255,u=l>>16&255,h=l>>8&255,c=o>>24&255,d=o>>16&255,_=o>>8&255;return ue=c+Math.round((a-c)*J),he=d+Math.round((u-d)*J),de=_+Math.round((h-_)*J),j.toRgba(ue,he,de)}n.blend=s;function t(o,l,a){let u=ve.relativeLuminance(o>>8),h=ve.relativeLuminance(l>>8);if(Xe(u,h)>8));if(m>8));return m>A?p:f}return p}let d=i(o,l,a),_=Xe(u,ve.relativeLuminance(d>>8));if(_>8));return _>m?d:p}return d}}n.ensureContrastRatio=t;function e(o,l,a){let u=o>>24&255,h=o>>16&255,c=o>>8&255,d=l>>24&255,_=l>>16&255,p=l>>8&255,m=Xe(ve.relativeLuminance2(d,_,p),ve.relativeLuminance2(u,h,c));for(;m0||_>0||p>0);)d-=Math.max(0,Math.ceil(d*.1)),_-=Math.max(0,Math.ceil(_*.1)),p-=Math.max(0,Math.ceil(p*.1)),m=Xe(ve.relativeLuminance2(d,_,p),ve.relativeLuminance2(u,h,c));return(d<<24|_<<16|p<<8|255)>>>0}n.reduceLuminance=e;function i(o,l,a){let u=o>>24&255,h=o>>16&255,c=o>>8&255,d=l>>24&255,_=l>>16&255,p=l>>8&255,m=Xe(ve.relativeLuminance2(d,_,p),ve.relativeLuminance2(u,h,c));for(;m>>0}n.increaseLuminance=i;function r(o){return[o>>24&255,o>>16&255,o>>8&255,o&255]}n.toChannels=r})($r||={});function vt(s){let t=s.toString(16);return t.length<2?"0"+t:t}function Xe(s,t){return s1){let c=this._getJoinedRanges(r,l,o,e,n);for(let d=0;d1){let h=this._getJoinedRanges(r,l,o,e,n);for(let c=0;c=di,E=y,x=this._workCell;if(_.length>0&&y===_[0][0]&&w){let W=_.shift(),An=this._isCellInSelection(W[0],e);for(O=W[0]+1;O=W[1],w?(g=!0,x=new Vr(this._workCell,t.translateToString(!0,W[0],W[1]),W[1]-W[0]),E=W[1]-1,T=x.getWidth()):di=W[1]}let N=this._isCellInSelection(y,e),Z=i&&y===o,te=Qe&&y>=h&&y<=c,Oe=!1;this._decorationService.forEachDecorationAtCell(y,e,void 0,W=>{Oe=!0});let ze=x.getChars()||we;if(ze===" "&&(x.isUnderline()||x.isOverline())&&(ze="\xA0"),Ke=T*a-u.get(ze,x.isBold(),x.isItalic()),!f)f=this._document.createElement("span");else if(A&&(N&&Pe||!N&&!Pe&&x.bg===I)&&(N&&Pe&&p.selectionForeground||x.fg===k)&&x.extended.ext===P&&te===oe&&Ke===Me&&!Z&&!g&&!Oe&&w){x.isInvisible()?R+=we:R+=ze,A++;continue}else A&&(f.textContent=R),f=this._document.createElement("span"),A=0,R="";if(I=x.bg,k=x.fg,P=x.extended.ext,oe=te,Me=Ke,Pe=N,g&&o>=y&&o<=E&&(o=y),!this._coreService.isCursorHidden&&Z&&this._coreService.isCursorInitialized){if(V.push("xterm-cursor"),this._coreBrowserService.isFocused)l&&V.push("xterm-cursor-blink"),V.push(r==="bar"?"xterm-cursor-bar":r==="underline"?"xterm-cursor-underline":"xterm-cursor-block");else if(n)switch(n){case"outline":V.push("xterm-cursor-outline");break;case"block":V.push("xterm-cursor-block");break;case"bar":V.push("xterm-cursor-bar");break;case"underline":V.push("xterm-cursor-underline");break;default:break}}if(x.isBold()&&V.push("xterm-bold"),x.isItalic()&&V.push("xterm-italic"),x.isDim()&&V.push("xterm-dim"),x.isInvisible()?R=we:R=x.getChars()||we,x.isUnderline()&&(V.push(`xterm-underline-${x.extended.underlineStyle}`),R===" "&&(R="\xA0"),!x.isUnderlineColorDefault()))if(x.isUnderlineColorRGB())f.style.textDecorationColor=`rgb(${De.toColorRGB(x.getUnderlineColor()).join(",")})`;else{let W=x.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&x.isBold()&&W<8&&(W+=8),f.style.textDecorationColor=p.ansi[W].css}x.isOverline()&&(V.push("xterm-overline"),R===" "&&(R="\xA0")),x.isStrikethrough()&&V.push("xterm-strikethrough"),te&&(f.style.textDecoration="underline");let le=x.getFgColor(),et=x.getFgColorMode(),me=x.getBgColor(),ht=x.getBgColorMode(),fi=!!x.isInverse();if(fi){let W=le;le=me,me=W;let An=et;et=ht,ht=An}let tt,Qi,pi=!1;this._decorationService.forEachDecorationAtCell(y,e,void 0,W=>{W.options.layer!=="top"&&pi||(W.backgroundColorRGB&&(ht=50331648,me=W.backgroundColorRGB.rgba>>8&16777215,tt=W.backgroundColorRGB),W.foregroundColorRGB&&(et=50331648,le=W.foregroundColorRGB.rgba>>8&16777215,Qi=W.foregroundColorRGB),pi=W.options.layer==="top")}),!pi&&N&&(tt=this._coreBrowserService.isFocused?p.selectionBackgroundOpaque:p.selectionInactiveBackgroundOpaque,me=tt.rgba>>8&16777215,ht=50331648,pi=!0,p.selectionForeground&&(et=50331648,le=p.selectionForeground.rgba>>8&16777215,Qi=p.selectionForeground)),pi&&V.push("xterm-decoration-top");let it;switch(ht){case 16777216:case 33554432:it=p.ansi[me],V.push(`xterm-bg-${me}`);break;case 50331648:it=j.toColor(me>>16,me>>8&255,me&255),this._addStyle(f,`background-color:#${qo((me>>>0).toString(16),"0",6)}`);break;case 0:default:fi?(it=p.foreground,V.push(`xterm-bg-${257}`)):it=p.background}switch(tt||x.isDim()&&(tt=U.multiplyOpacity(it,.5)),et){case 16777216:case 33554432:x.isBold()&&le<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(le+=8),this._applyMinimumContrast(f,it,p.ansi[le],x,tt,void 0)||V.push(`xterm-fg-${le}`);break;case 50331648:let W=j.toColor(le>>16&255,le>>8&255,le&255);this._applyMinimumContrast(f,it,W,x,tt,Qi)||this._addStyle(f,`color:#${qo(le.toString(16),"0",6)}`);break;case 0:default:this._applyMinimumContrast(f,it,p.foreground,x,tt,Qi)||fi&&V.push(`xterm-fg-${257}`)}V.length&&(f.className=V.join(" "),V.length=0),!Z&&!g&&!Oe&&w?A++:f.textContent=R,Ke!==this.defaultSpacing&&(f.style.letterSpacing=`${Ke}px`),d.push(f),y=E}return f&&A&&(f.textContent=R),d}_applyMinimumContrast(t,e,i,r,n,o){if(this._optionsService.rawOptions.minimumContrastRatio===1||$o(r.getCode()))return!1;let l=this._getContrastCache(r),a;if(!n&&!o&&(a=l.getColor(e.rgba,i.rgba)),a===void 0){let u=this._optionsService.rawOptions.minimumContrastRatio/(r.isDim()?2:1);a=U.ensureContrastRatio(n||e,o||i,u),l.setColor((n||e).rgba,(o||i).rgba,a??null)}return a?(this._addStyle(t,`color:${a.css}`),!0):!1}_getContrastCache(t){return t.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(t,e){t.setAttribute("style",`${t.getAttribute("style")||""}${e};`)}_isCellInSelection(t,e){let i=this._selectionStart,r=this._selectionEnd;return!i||!r?!1:this._columnSelectMode?i[0]<=r[0]?t>=i[0]&&e>=i[1]&&t=i[1]&&t>=r[0]&&e<=r[1]:e>i[1]&&e=i[0]&&t=i[0]}};Vt=M([S(1,or),S(2,H),S(3,ae),S(4,ge),S(5,Be),S(6,Re)],Vt);function qo(s,t,e){for(;s.length0&&(this._flat[r]=l),l}let n=t;e&&(n+="B"),i&&(n+="I");let o=this._holey.get(n);if(o===void 0){let l=0;e&&(l|=1),i&&(l|=2),o=this._measure(t,l),o>0&&this._holey.set(n,o)}return o}_measure(t,e){let i=this._measureElements[e];return i.textContent=t.repeat(32),i.offsetWidth/32}};var ms=class{constructor(){this.clear()}clear(){this.hasSelection=!1,this.columnSelectMode=!1,this.viewportStartRow=0,this.viewportEndRow=0,this.viewportCappedStartRow=0,this.viewportCappedEndRow=0,this.startCol=0,this.endCol=0,this.selectionStart=void 0,this.selectionEnd=void 0}update(t,e,i,r=!1){if(this.selectionStart=e,this.selectionEnd=i,!e||!i||e[0]===i[0]&&e[1]===i[1]){this.clear();return}let n=t.buffers.active.ydisp,o=e[1]-n,l=i[1]-n,a=Math.max(o,0),u=Math.min(l,t.rows-1);if(a>=t.rows||u<0){this.clear();return}this.hasSelection=!0,this.columnSelectMode=r,this.viewportStartRow=o,this.viewportEndRow=l,this.viewportCappedStartRow=a,this.viewportCappedEndRow=u,this.startCol=e[0],this.endCol=i[0]}isCellSelected(t,e,i){return this.hasSelection?(i-=t.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?e>=this.startCol&&i>=this.viewportCappedStartRow&&e=this.viewportCappedStartRow&&e>=this.endCol&&i<=this.viewportCappedEndRow:i>this.viewportStartRow&&i=this.startCol&&e=this.startCol):!1}};function Yo(){return new ms}var _s="xterm-dom-renderer-owner-",Le="xterm-rows",jr="xterm-fg-",jo="xterm-bg-",ki="xterm-focus",Xr="xterm-selection",Na=1,Yt=class extends D{constructor(e,i,r,n,o,l,a,u,h,c,d,_,p,m){super();this._terminal=e;this._document=i;this._element=r;this._screenElement=n;this._viewportElement=o;this._helperContainer=l;this._linkifier2=a;this._charSizeService=h;this._optionsService=c;this._bufferService=d;this._coreService=_;this._coreBrowserService=p;this._themeService=m;this._terminalClass=Na++;this._rowElements=[];this._selectionRenderModel=Yo();this.onRequestRedraw=this._register(new v).event;this._rowContainer=this._document.createElement("div"),this._rowContainer.classList.add(Le),this._rowContainer.style.lineHeight="normal",this._rowContainer.setAttribute("aria-hidden","true"),this._refreshRowElements(this._bufferService.cols,this._bufferService.rows),this._selectionContainer=this._document.createElement("div"),this._selectionContainer.classList.add(Xr),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions=Vo(),this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(f=>this._injectCss(f))),this._injectCss(this._themeService.colors),this._rowFactory=u.createInstance(Vt,document),this._element.classList.add(_s+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(f=>this._handleLinkHover(f))),this._register(this._linkifier2.onHideLinkUnderline(f=>this._handleLinkLeave(f))),this._register(C(()=>{this._element.classList.remove(_s+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new Yr(this._document,this._helperContainer),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}_updateDimensions(){let e=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*e,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*e),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.left=0,this.dimensions.device.char.top=0,this.dimensions.device.canvas.width=this.dimensions.device.cell.width*this._bufferService.cols,this.dimensions.device.canvas.height=this.dimensions.device.cell.height*this._bufferService.rows,this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/e),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/e),this.dimensions.css.cell.width=this.dimensions.css.canvas.width/this._bufferService.cols,this.dimensions.css.cell.height=this.dimensions.css.canvas.height/this._bufferService.rows;for(let r of this._rowElements)r.style.width=`${this.dimensions.css.canvas.width}px`,r.style.height=`${this.dimensions.css.cell.height}px`,r.style.lineHeight=`${this.dimensions.css.cell.height}px`,r.style.overflow="hidden";this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._dimensionsStyleElement));let i=`${this._terminalSelector} .${Le} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=i,this._selectionContainer.style.height=this._viewportElement.style.height,this._screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._screenElement.style.height=`${this.dimensions.css.canvas.height}px`}_injectCss(e){this._themeStyleElement||(this._themeStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._themeStyleElement));let i=`${this._terminalSelector} .${Le} { pointer-events: none; color: ${e.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;i+=`${this._terminalSelector} .${Le} .xterm-dim { color: ${U.multiplyOpacity(e.foreground,.5).css};}`,i+=`${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`;let r=`blink_underline_${this._terminalClass}`,n=`blink_bar_${this._terminalClass}`,o=`blink_block_${this._terminalClass}`;i+=`@keyframes ${r} { 50% { border-bottom-style: hidden; }}`,i+=`@keyframes ${n} { 50% { box-shadow: none; }}`,i+=`@keyframes ${o} { 0% { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css}; } 50% { background-color: inherit; color: ${e.cursor.css}; }}`,i+=`${this._terminalSelector} .${Le}.${ki} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${r} 1s step-end infinite;}${this._terminalSelector} .${Le}.${ki} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${n} 1s step-end infinite;}${this._terminalSelector} .${Le}.${ki} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${o} 1s step-end infinite;}${this._terminalSelector} .${Le} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${Le} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${Le} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${Le} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${Le} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,i+=`${this._terminalSelector} .${Xr} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${Xr} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${Xr} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[l,a]of e.ansi.entries())i+=`${this._terminalSelector} .${jr}${l} { color: ${a.css}; }${this._terminalSelector} .${jr}${l}.xterm-dim { color: ${U.multiplyOpacity(a,.5).css}; }${this._terminalSelector} .${jo}${l} { background-color: ${a.css}; }`;i+=`${this._terminalSelector} .${jr}${257} { color: ${U.opaque(e.background).css}; }${this._terminalSelector} .${jr}${257}.xterm-dim { color: ${U.multiplyOpacity(U.opaque(e.background),.5).css}; }${this._terminalSelector} .${jo}${257} { background-color: ${e.foreground.css}; }`,this._themeStyleElement.textContent=i}_setDefaultSpacing(){let e=this.dimensions.css.cell.width-this._widthCache.get("W",!1,!1);this._rowContainer.style.letterSpacing=`${e}px`,this._rowFactory.defaultSpacing=e}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(e,i){for(let r=this._rowElements.length;r<=i;r++){let n=this._document.createElement("div");this._rowContainer.appendChild(n),this._rowElements.push(n)}for(;this._rowElements.length>i;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(e,i){this._refreshRowElements(e,i),this._updateDimensions(),this.handleSelectionChanged(this._selectionRenderModel.selectionStart,this._selectionRenderModel.selectionEnd,this._selectionRenderModel.columnSelectMode)}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(ki),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(ki),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(e,i,r){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(e,i,r),this.renderRows(0,this._bufferService.rows-1),!e||!i||(this._selectionRenderModel.update(this._terminal,e,i,r),!this._selectionRenderModel.hasSelection))return;let n=this._selectionRenderModel.viewportStartRow,o=this._selectionRenderModel.viewportEndRow,l=this._selectionRenderModel.viewportCappedStartRow,a=this._selectionRenderModel.viewportCappedEndRow,u=this._document.createDocumentFragment();if(r){let h=e[0]>i[0];u.appendChild(this._createSelectionElement(l,h?i[0]:e[0],h?e[0]:i[0],a-l+1))}else{let h=n===l?e[0]:0,c=l===o?i[0]:this._bufferService.cols;u.appendChild(this._createSelectionElement(l,h,c));let d=a-l-1;if(u.appendChild(this._createSelectionElement(l+1,0,this._bufferService.cols,d)),l!==a){let _=o===a?i[0]:this._bufferService.cols;u.appendChild(this._createSelectionElement(a,0,_))}}this._selectionContainer.appendChild(u)}_createSelectionElement(e,i,r,n=1){let o=this._document.createElement("div"),l=i*this.dimensions.css.cell.width,a=this.dimensions.css.cell.width*(r-i);return l+a>this.dimensions.css.canvas.width&&(a=this.dimensions.css.canvas.width-l),o.style.height=`${n*this.dimensions.css.cell.height}px`,o.style.top=`${e*this.dimensions.css.cell.height}px`,o.style.left=`${l}px`,o.style.width=`${a}px`,o}handleCursorMove(){}_handleOptionsChanged(){this._updateDimensions(),this._injectCss(this._themeService.colors),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}clear(){for(let e of this._rowElements)e.replaceChildren()}renderRows(e,i){let r=this._bufferService.buffer,n=r.ybase+r.y,o=Math.min(r.x,this._bufferService.cols-1),l=this._coreService.decPrivateModes.cursorBlink??this._optionsService.rawOptions.cursorBlink,a=this._coreService.decPrivateModes.cursorStyle??this._optionsService.rawOptions.cursorStyle,u=this._optionsService.rawOptions.cursorInactiveStyle;for(let h=e;h<=i;h++){let c=h+r.ydisp,d=this._rowElements[h],_=r.lines.get(c);if(!d||!_)break;d.replaceChildren(...this._rowFactory.createRow(_,c,c===n,a,u,o,l,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${_s}${this._terminalClass}`}_handleLinkHover(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!0)}_handleLinkLeave(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!1)}_setCellUnderline(e,i,r,n,o,l){r<0&&(e=0),n<0&&(i=0);let a=this._bufferService.rows-1;r=Math.max(Math.min(r,a),0),n=Math.max(Math.min(n,a),0),o=Math.min(o,this._bufferService.cols);let u=this._bufferService.buffer,h=u.ybase+u.y,c=Math.min(u.x,o-1),d=this._optionsService.rawOptions.cursorBlink,_=this._optionsService.rawOptions.cursorStyle,p=this._optionsService.rawOptions.cursorInactiveStyle;for(let m=r;m<=n;++m){let f=m+u.ydisp,A=this._rowElements[m],R=u.lines.get(f);if(!A||!R)break;A.replaceChildren(...this._rowFactory.createRow(R,f,f===h,_,p,c,d,this.dimensions.css.cell.width,this._widthCache,l?m===r?e:0:-1,l?(m===n?i:o)-1:-1))}}};Yt=M([S(7,xt),S(8,nt),S(9,H),S(10,F),S(11,ge),S(12,ae),S(13,Re)],Yt);var jt=class extends D{constructor(e,i,r){super();this._optionsService=r;this.width=0;this.height=0;this._onCharSizeChange=this._register(new v);this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this._register(new vs(this._optionsService))}catch{this._measureStrategy=this._register(new bs(e,i,this._optionsService))}this._register(this._optionsService.onMultipleOptionChange(["fontFamily","fontSize"],()=>this.measure()))}get hasValidSize(){return this.width>0&&this.height>0}measure(){let e=this._measureStrategy.measure();(e.width!==this.width||e.height!==this.height)&&(this.width=e.width,this.height=e.height,this._onCharSizeChange.fire())}};jt=M([S(2,H)],jt);var Zr=class extends D{constructor(){super(...arguments);this._result={width:0,height:0}}_validateAndSet(e,i){e!==void 0&&e>0&&i!==void 0&&i>0&&(this._result.width=e,this._result.height=i)}},bs=class extends Zr{constructor(e,i,r){super();this._document=e;this._parentElement=i;this._optionsService=r;this._measureElement=this._document.createElement("span"),this._measureElement.classList.add("xterm-char-measure-element"),this._measureElement.textContent="W".repeat(32),this._measureElement.setAttribute("aria-hidden","true"),this._measureElement.style.whiteSpace="pre",this._measureElement.style.fontKerning="none",this._parentElement.appendChild(this._measureElement)}measure(){return this._measureElement.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._measureElement.style.fontSize=`${this._optionsService.rawOptions.fontSize}px`,this._validateAndSet(Number(this._measureElement.offsetWidth)/32,Number(this._measureElement.offsetHeight)),this._result}},vs=class extends Zr{constructor(e){super();this._optionsService=e;this._canvas=new OffscreenCanvas(100,100),this._ctx=this._canvas.getContext("2d");let i=this._ctx.measureText("W");if(!("width"in i&&"fontBoundingBoxAscent"in i&&"fontBoundingBoxDescent"in i))throw new Error("Required font metrics not supported")}measure(){this._ctx.font=`${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;let e=this._ctx.measureText("W");return this._validateAndSet(e.width,e.fontBoundingBoxAscent+e.fontBoundingBoxDescent),this._result}};var Jr=class extends D{constructor(e,i,r){super();this._textarea=e;this._window=i;this.mainDocument=r;this._isFocused=!1;this._cachedIsFocused=void 0;this._screenDprMonitor=this._register(new gs(this._window));this._onDprChange=this._register(new v);this.onDprChange=this._onDprChange.event;this._onWindowChange=this._register(new v);this.onWindowChange=this._onWindowChange.event;this._register(this.onWindowChange(n=>this._screenDprMonitor.setWindow(n))),this._register($.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register(L(this._textarea,"focus",()=>this._isFocused=!0)),this._register(L(this._textarea,"blur",()=>this._isFocused=!1))}get window(){return this._window}set window(e){this._window!==e&&(this._window=e,this._onWindowChange.fire(this._window))}get dpr(){return this.window.devicePixelRatio}get isFocused(){return this._cachedIsFocused===void 0&&(this._cachedIsFocused=this._isFocused&&this._textarea.ownerDocument.hasFocus(),queueMicrotask(()=>this._cachedIsFocused=void 0)),this._cachedIsFocused}},gs=class extends D{constructor(e){super();this._parentWindow=e;this._windowResizeListener=this._register(new ye);this._onDprChange=this._register(new v);this.onDprChange=this._onDprChange.event;this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this._register(C(()=>this.clearListener()))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=L(this._parentWindow,"resize",()=>this._setDprAndFireIfDiffers())}_setDprAndFireIfDiffers(){this._parentWindow.devicePixelRatio!==this._currentDevicePixelRatio&&this._onDprChange.fire(this._parentWindow.devicePixelRatio),this._updateDpr()}_updateDpr(){this._outerListener&&(this._resolutionMediaMatchList?.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){!this._resolutionMediaMatchList||!this._outerListener||(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._outerListener=void 0)}};var Qr=class extends D{constructor(){super();this.linkProviders=[];this._register(C(()=>this.linkProviders.length=0))}registerLinkProvider(e){return this.linkProviders.push(e),{dispose:()=>{let i=this.linkProviders.indexOf(e);i!==-1&&this.linkProviders.splice(i,1)}}}};function Ci(s,t,e){let i=e.getBoundingClientRect(),r=s.getComputedStyle(e),n=parseInt(r.getPropertyValue("padding-left")),o=parseInt(r.getPropertyValue("padding-top"));return[t.clientX-i.left-n,t.clientY-i.top-o]}function Xo(s,t,e,i,r,n,o,l,a){if(!n)return;let u=Ci(s,t,e);if(u)return u[0]=Math.ceil((u[0]+(a?o/2:0))/o),u[1]=Math.ceil(u[1]/l),u[0]=Math.min(Math.max(u[0],1),i+(a?1:0)),u[1]=Math.min(Math.max(u[1],1),r),u}var Xt=class{constructor(t,e){this._renderService=t;this._charSizeService=e}getCoords(t,e,i,r,n){return Xo(window,t,e,i,r,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,n)}getMouseReportCoords(t,e){let i=Ci(window,t,e);if(this._charSizeService.hasValidSize)return i[0]=Math.min(Math.max(i[0],0),this._renderService.dimensions.css.canvas.width-1),i[1]=Math.min(Math.max(i[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(i[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(i[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(i[0]),y:Math.floor(i[1])}}};Xt=M([S(0,ce),S(1,nt)],Xt);var en=class{constructor(t,e){this._renderCallback=t;this._coreBrowserService=e;this._refreshCallbacks=[]}dispose(){this._animationFrame&&(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0)}addRefreshCallback(t){return this._refreshCallbacks.push(t),this._animationFrame||(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh())),this._animationFrame}refresh(t,e,i){this._rowCount=i,t=t!==void 0?t:0,e=e!==void 0?e:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,t):t,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,e):e,!this._animationFrame&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()))}_innerRefresh(){if(this._animationFrame=void 0,this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0){this._runRefreshCallbacks();return}let t=Math.max(this._rowStart,0),e=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(t,e),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(let t of this._refreshCallbacks)t(0);this._refreshCallbacks=[]}};var tn={};Ll(tn,{getSafariVersion:()=>Ha,isChromeOS:()=>Ts,isFirefox:()=>Ss,isIpad:()=>Wa,isIphone:()=>Ua,isLegacyEdge:()=>Fa,isLinux:()=>Bi,isMac:()=>Zt,isNode:()=>Mi,isSafari:()=>Zo,isWindows:()=>Es});var Mi=typeof process<"u"&&"title"in process,Pi=Mi?"node":navigator.userAgent,Oi=Mi?"node":navigator.platform,Ss=Pi.includes("Firefox"),Fa=Pi.includes("Edge"),Zo=/^((?!chrome|android).)*safari/i.test(Pi);function Ha(){if(!Zo)return 0;let s=Pi.match(/Version\/(\d+)/);return s===null||s.length<2?0:parseInt(s[1])}var Zt=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(Oi),Wa=Oi==="iPad",Ua=Oi==="iPhone",Es=["Windows","Win16","Win32","WinCE"].includes(Oi),Bi=Oi.indexOf("Linux")>=0,Ts=/\bCrOS\b/.test(Pi);var rn=class{constructor(){this._tasks=[];this._i=0}enqueue(t){this._tasks.push(t),this._start()}flush(){for(;this._in){r-e<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(r-e))}ms`),this._start();return}r=n}this.clear()}},Is=class extends rn{_requestCallback(t){return setTimeout(()=>t(this._createDeadline(16)))}_cancelCallback(t){clearTimeout(t)}_createDeadline(t){let e=performance.now()+t;return{timeRemaining:()=>Math.max(0,e-performance.now())}}},ys=class extends rn{_requestCallback(t){return requestIdleCallback(t)}_cancelCallback(t){cancelIdleCallback(t)}},Jt=!Mi&&"requestIdleCallback"in window?ys:Is,nn=class{constructor(){this._queue=new Jt}set(t){this._queue.clear(),this._queue.enqueue(t)}flush(){this._queue.flush()}};var Qt=class extends D{constructor(e,i,r,n,o,l,a,u,h){super();this._rowCount=e;this._optionsService=r;this._charSizeService=n;this._coreService=o;this._coreBrowserService=u;this._renderer=this._register(new ye);this._pausedResizeTask=new nn;this._observerDisposable=this._register(new ye);this._isPaused=!1;this._needsFullRefresh=!1;this._isNextRenderRedrawOnly=!0;this._needsSelectionRefresh=!1;this._canvasWidth=0;this._canvasHeight=0;this._selectionState={start:void 0,end:void 0,columnSelectMode:!1};this._onDimensionsChange=this._register(new v);this.onDimensionsChange=this._onDimensionsChange.event;this._onRenderedViewportChange=this._register(new v);this.onRenderedViewportChange=this._onRenderedViewportChange.event;this._onRender=this._register(new v);this.onRender=this._onRender.event;this._onRefreshRequest=this._register(new v);this.onRefreshRequest=this._onRefreshRequest.event;this._renderDebouncer=new en((c,d)=>this._renderRows(c,d),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new xs(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register(C(()=>this._syncOutputHandler.dispose())),this._register(this._coreBrowserService.onDprChange(()=>this.handleDevicePixelRatioChange())),this._register(a.onResize(()=>this._fullRefresh())),this._register(a.buffers.onBufferActivate(()=>this._renderer.value?.clear())),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._charSizeService.onCharSizeChange(()=>this.handleCharSizeChanged())),this._register(l.onDecorationRegistered(()=>this._fullRefresh())),this._register(l.onDecorationRemoved(()=>this._fullRefresh())),this._register(this._optionsService.onMultipleOptionChange(["customGlyphs","drawBoldTextInBrightColors","letterSpacing","lineHeight","fontFamily","fontSize","fontWeight","fontWeightBold","minimumContrastRatio","rescaleOverlappingGlyphs"],()=>{this.clear(),this.handleResize(a.cols,a.rows),this._fullRefresh()})),this._register(this._optionsService.onMultipleOptionChange(["cursorBlink","cursorStyle"],()=>this.refreshRows(a.buffer.y,a.buffer.y,!0))),this._register(h.onChangeColors(()=>this._fullRefresh())),this._registerIntersectionObserver(this._coreBrowserService.window,i),this._register(this._coreBrowserService.onWindowChange(c=>this._registerIntersectionObserver(c,i)))}get dimensions(){return this._renderer.value.dimensions}_registerIntersectionObserver(e,i){if("IntersectionObserver"in e){let r=new e.IntersectionObserver(n=>this._handleIntersectionChange(n[n.length-1]),{threshold:0});r.observe(i),this._observerDisposable.value=C(()=>r.disconnect())}}_handleIntersectionChange(e){this._isPaused=e.isIntersecting===void 0?e.intersectionRatio===0:!e.isIntersecting,!this._isPaused&&!this._charSizeService.hasValidSize&&this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(e,i,r=!1){if(this._isPaused){this._needsFullRefresh=!0;return}if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,i);return}let n=this._syncOutputHandler.flush();n&&(e=Math.min(e,n.start),i=Math.max(i,n.end)),r||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(e,i,this._rowCount)}_renderRows(e,i){if(this._renderer.value){if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,i);return}e=Math.min(e,this._rowCount-1),i=Math.min(i,this._rowCount-1),this._renderer.value.renderRows(e,i),this._needsSelectionRefresh&&(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),this._needsSelectionRefresh=!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:e,end:i}),this._onRender.fire({start:e,end:i}),this._isNextRenderRedrawOnly=!0}}resize(e,i){this._rowCount=i,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(e){this._renderer.value=e,this._renderer.value&&(this._renderer.value.onRequestRedraw(i=>this.refreshRows(i.start,i.end,!0)),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(e){return this._renderDebouncer.addRefreshCallback(e)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){this._renderer.value&&(this._renderer.value.clearTextureAtlas?.(),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(e,i){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set(()=>this._renderer.value?.handleResize(e,i)):this._renderer.value.handleResize(e,i),this._fullRefresh())}handleCharSizeChanged(){this._renderer.value?.handleCharSizeChanged()}handleBlur(){this._renderer.value?.handleBlur()}handleFocus(){this._renderer.value?.handleFocus()}handleSelectionChanged(e,i,r){this._selectionState.start=e,this._selectionState.end=i,this._selectionState.columnSelectMode=r,this._renderer.value?.handleSelectionChanged(e,i,r)}handleCursorMove(){this._renderer.value?.handleCursorMove()}clear(){this._renderer.value?.clear()}};Qt=M([S(2,H),S(3,nt),S(4,ge),S(5,Be),S(6,F),S(7,ae),S(8,Re)],Qt);var xs=class{constructor(t,e,i){this._coreBrowserService=t;this._coreService=e;this._onTimeout=i;this._start=0;this._end=0;this._isBuffering=!1}bufferRows(t,e){this._isBuffering?(this._start=Math.min(this._start,t),this._end=Math.max(this._end,e)):(this._start=t,this._end=e,this._isBuffering=!0),this._timeout===void 0&&(this._timeout=this._coreBrowserService.window.setTimeout(()=>{this._timeout=void 0,this._coreService.decPrivateModes.synchronizedOutput=!1,this._onTimeout()},1e3))}flush(){if(this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0),!this._isBuffering)return;let t={start:this._start,end:this._end};return this._isBuffering=!1,t}dispose(){this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0)}};function Jo(s,t,e,i){let r=e.buffer.x,n=e.buffer.y;if(!e.buffer.hasScrollback)return Ga(r,n,s,t,e,i)+sn(n,t,e,i)+$a(r,n,s,t,e,i);let o;if(n===t)return o=r>s?"D":"C",Fi(Math.abs(r-s),Ni(o,i));o=n>t?"D":"C";let l=Math.abs(n-t),a=za(n>t?s:r,e)+(l-1)*e.cols+1+Ka(n>t?r:s,e);return Fi(a,Ni(o,i))}function Ka(s,t){return s-1}function za(s,t){return t.cols-s}function Ga(s,t,e,i,r,n){return sn(t,i,r,n).length===0?"":Fi(el(s,t,s,t-gt(t,r),!1,r).length,Ni("D",n))}function sn(s,t,e,i){let r=s-gt(s,e),n=t-gt(t,e),o=Math.abs(r-n)-Va(s,t,e);return Fi(o,Ni(Qo(s,t),i))}function $a(s,t,e,i,r,n){let o;sn(t,i,r,n).length>0?o=i-gt(i,r):o=t;let l=i,a=qa(s,t,e,i,r,n);return Fi(el(s,o,e,l,a==="C",r).length,Ni(a,n))}function Va(s,t,e){let i=0,r=s-gt(s,e),n=t-gt(t,e);for(let o=0;o=0&&s0?o=i-gt(i,r):o=t,s=e&&ot?"A":"B"}function el(s,t,e,i,r,n){let o=s,l=t,a="";for(;(o!==e||l!==i)&&l>=0&&ln.cols-1?(a+=n.buffer.translateBufferLineToString(l,!1,s,o),o=0,s=0,l++):!r&&o<0&&(a+=n.buffer.translateBufferLineToString(l,!1,0,s+1),o=n.cols-1,s=o,l--);return a+n.buffer.translateBufferLineToString(l,!1,s,o)}function Ni(s,t){let e=t?"O":"[";return b.ESC+e+s}function Fi(s,t){s=Math.floor(s);let e="";for(let i=0;ithis._bufferService.cols?t%this._bufferService.cols===0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(t/this._bufferService.cols)-1]:[t%this._bufferService.cols,this.selectionStart[1]+Math.floor(t/this._bufferService.cols)]:[t,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){let t=this.selectionStart[0]+this.selectionStartLength;return t>this._bufferService.cols?[t%this._bufferService.cols,this.selectionStart[1]+Math.floor(t/this._bufferService.cols)]:[Math.max(t,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){let t=this.selectionStart,e=this.selectionEnd;return!t||!e?!1:t[1]>e[1]||t[1]===e[1]&&t[0]>e[0]}handleTrim(t){return this.selectionStart&&(this.selectionStart[1]-=t),this.selectionEnd&&(this.selectionEnd[1]-=t),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}};function ws(s,t){if(s.start.y>s.end.y)throw new Error(`Buffer range end (${s.end.x}, ${s.end.y}) cannot be before start (${s.start.x}, ${s.start.y})`);return t*(s.end.y-s.start.y)+(s.end.x-s.start.x+1)}var Ds=50,Ya=15,ja=50,Xa=500,Za="\xA0",Ja=new RegExp(Za,"g");var ei=class extends D{constructor(e,i,r,n,o,l,a,u,h){super();this._element=e;this._screenElement=i;this._linkifier=r;this._bufferService=n;this._coreService=o;this._mouseService=l;this._optionsService=a;this._renderService=u;this._coreBrowserService=h;this._dragScrollAmount=0;this._enabled=!0;this._workCell=new q;this._mouseDownTimeStamp=0;this._oldHasSelection=!1;this._oldSelectionStart=void 0;this._oldSelectionEnd=void 0;this._onLinuxMouseSelection=this._register(new v);this.onLinuxMouseSelection=this._onLinuxMouseSelection.event;this._onRedrawRequest=this._register(new v);this.onRequestRedraw=this._onRedrawRequest.event;this._onSelectionChange=this._register(new v);this.onSelectionChange=this._onSelectionChange.event;this._onRequestScrollLines=this._register(new v);this.onRequestScrollLines=this._onRequestScrollLines.event;this._mouseMoveListener=c=>this._handleMouseMove(c),this._mouseUpListener=c=>this._handleMouseUp(c),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(c=>this._handleTrim(c)),this._register(this._bufferService.buffers.onBufferActivate(c=>this._handleBufferActivate(c))),this.enable(),this._model=new on(this._bufferService),this._activeSelectionMode=0,this._register(C(()=>{this._removeMouseDownListeners()})),this._register(this._bufferService.onResize(c=>{c.rowsChanged&&this.clearSelection()}))}reset(){this.clearSelection()}disable(){this.clearSelection(),this._enabled=!1}enable(){this._enabled=!0}get selectionStart(){return this._model.finalSelectionStart}get selectionEnd(){return this._model.finalSelectionEnd}get hasSelection(){let e=this._model.finalSelectionStart,i=this._model.finalSelectionEnd;return!e||!i?!1:e[0]!==i[0]||e[1]!==i[1]}get selectionText(){let e=this._model.finalSelectionStart,i=this._model.finalSelectionEnd;if(!e||!i)return"";let r=this._bufferService.buffer,n=[];if(this._activeSelectionMode===3){if(e[0]===i[0])return"";let l=e[0]l.replace(Ja," ")).join(Es?`\r +`:` +`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh())),Bi&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(e){let i=this._getMouseBufferCoords(e),r=this._model.finalSelectionStart,n=this._model.finalSelectionEnd;return!r||!n||!i?!1:this._areCoordsInSelection(i,r,n)}isCellInSelection(e,i){let r=this._model.finalSelectionStart,n=this._model.finalSelectionEnd;return!r||!n?!1:this._areCoordsInSelection([e,i],r,n)}_areCoordsInSelection(e,i,r){return e[1]>i[1]&&e[1]=i[0]&&e[0]=i[0]}_selectWordAtCursor(e,i){let r=this._linkifier.currentLink?.link?.range;if(r)return this._model.selectionStart=[r.start.x-1,r.start.y-1],this._model.selectionStartLength=ws(r,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let n=this._getMouseBufferCoords(e);return n?(this._selectWordAt(n,i),this._model.selectionEnd=void 0,!0):!1}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,i){this._model.clearSelection(),e=Math.max(e,0),i=Math.min(i,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,i],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){let i=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(i)return i[0]--,i[1]--,i[1]+=this._bufferService.buffer.ydisp,i}_getMouseEventScrollAmount(e){let i=Ci(this._coreBrowserService.window,e,this._screenElement)[1],r=this._renderService.dimensions.css.canvas.height;return i>=0&&i<=r?0:(i>r&&(i-=r),i=Math.min(Math.max(i,-Ds),Ds),i/=Ds,i/Math.abs(i)+Math.round(i*(Ya-1)))}shouldForceSelection(e){return Zt?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,!(e.button===2&&this.hasSelection)&&e.button===0){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):e.detail===1?this._handleSingleClick(e):e.detail===2?this._handleDoubleClick(e):e.detail===3&&this._handleTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener("mouseup",this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),ja)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener("mouseup",this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;let i=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);i&&i.length!==this._model.selectionStart[0]&&i.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let i=this._getMouseBufferCoords(e);i&&(this._activeSelectionMode=2,this._selectLineAt(i[1]))}shouldColumnSelect(e){return e.altKey&&!(Zt&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;let i=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd){this.refresh(!0);return}this._activeSelectionMode===2?this._model.selectionEnd[1]0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));let r=this._bufferService.buffer;if(this._model.selectionEnd[1]0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(e.ydisp+this._bufferService.rows,e.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=e.ydisp),this.refresh()}}_handleMouseUp(e){let i=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&ithis._handleTrim(i))}_convertViewportColToCharacterIndex(e,i){let r=i;for(let n=0;i>=n;n++){let o=e.loadCell(n,this._workCell).getChars().length;this._workCell.getWidth()===0?r--:o>1&&i!==n&&(r+=o-1)}return r}setSelection(e,i,r){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,i],this._model.selectionStartLength=r,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,i,r=!0,n=!0){if(e[0]>=this._bufferService.cols)return;let o=this._bufferService.buffer,l=o.lines.get(e[1]);if(!l)return;let a=o.translateBufferLineToString(e[1],!1),u=this._convertViewportColToCharacterIndex(l,e[0]),h=u,c=e[0]-u,d=0,_=0,p=0,m=0;if(a.charAt(u)===" "){for(;u>0&&a.charAt(u-1)===" ";)u--;for(;h1&&(m+=I-1,h+=I-1);R>0&&u>0&&!this._isCharWordSeparator(l.loadCell(R-1,this._workCell));){l.loadCell(R-1,this._workCell);let k=this._workCell.getChars().length;this._workCell.getWidth()===0?(d++,R--):k>1&&(p+=k-1,u-=k-1),u--,R--}for(;O1&&(m+=k-1,h+=k-1),h++,O++}}h++;let f=u+c-d+p,A=Math.min(this._bufferService.cols,h-u+d+_-p-m);if(!(!i&&a.slice(u,h).trim()==="")){if(r&&f===0&&l.getCodePoint(0)!==32){let R=o.lines.get(e[1]-1);if(R&&l.isWrapped&&R.getCodePoint(this._bufferService.cols-1)!==32){let O=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(O){let I=this._bufferService.cols-O.start;f-=I,A+=I}}}if(n&&f+A===this._bufferService.cols&&l.getCodePoint(this._bufferService.cols-1)!==32){let R=o.lines.get(e[1]+1);if(R?.isWrapped&&R.getCodePoint(0)!==32){let O=this._getWordAt([0,e[1]+1],!1,!1,!0);O&&(A+=O.length)}}return{start:f,length:A}}}_selectWordAt(e,i){let r=this._getWordAt(e,i);if(r){for(;r.start<0;)r.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[r.start,e[1]],this._model.selectionStartLength=r.length}}_selectToWordAt(e){let i=this._getWordAt(e,!0);if(i){let r=e[1];for(;i.start<0;)i.start+=this._bufferService.cols,r--;if(!this._model.areSelectionValuesReversed())for(;i.start+i.length>this._bufferService.cols;)i.length-=this._bufferService.cols,r++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?i.start:i.start+i.length,r]}}_isCharWordSeparator(e){return e.getWidth()===0?!1:this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){let i=this._bufferService.buffer.getWrappedRangeForLine(e),r={start:{x:0,y:i.first},end:{x:this._bufferService.cols-1,y:i.last}};this._model.selectionStart=[0,i.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=ws(r,this._bufferService.cols)}};ei=M([S(3,F),S(4,ge),S(5,Dt),S(6,H),S(7,ce),S(8,ae)],ei);var Hi=class{constructor(){this._data={}}set(t,e,i){this._data[t]||(this._data[t]={}),this._data[t][e]=i}get(t,e){return this._data[t]?this._data[t][e]:void 0}clear(){this._data={}}};var Wi=class{constructor(){this._color=new Hi;this._css=new Hi}setCss(t,e,i){this._css.set(t,e,i)}getCss(t,e){return this._css.get(t,e)}setColor(t,e,i){this._color.set(t,e,i)}getColor(t,e){return this._color.get(t,e)}clear(){this._color.clear(),this._css.clear()}};var re=Object.freeze((()=>{let s=[z.toColor("#2e3436"),z.toColor("#cc0000"),z.toColor("#4e9a06"),z.toColor("#c4a000"),z.toColor("#3465a4"),z.toColor("#75507b"),z.toColor("#06989a"),z.toColor("#d3d7cf"),z.toColor("#555753"),z.toColor("#ef2929"),z.toColor("#8ae234"),z.toColor("#fce94f"),z.toColor("#729fcf"),z.toColor("#ad7fa8"),z.toColor("#34e2e2"),z.toColor("#eeeeec")],t=[0,95,135,175,215,255];for(let e=0;e<216;e++){let i=t[e/36%6|0],r=t[e/6%6|0],n=t[e%6];s.push({css:j.toCss(i,r,n),rgba:j.toRgba(i,r,n)})}for(let e=0;e<24;e++){let i=8+e*10;s.push({css:j.toCss(i,i,i),rgba:j.toRgba(i,i,i)})}return s})());var St=z.toColor("#ffffff"),Ki=z.toColor("#000000"),tl=z.toColor("#ffffff"),il=Ki,Ui={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117},Qa=St,ti=class extends D{constructor(e){super();this._optionsService=e;this._contrastCache=new Wi;this._halfContrastCache=new Wi;this._onChangeColors=this._register(new v);this.onChangeColors=this._onChangeColors.event;this._colors={foreground:St,background:Ki,cursor:tl,cursorAccent:il,selectionForeground:void 0,selectionBackgroundTransparent:Ui,selectionBackgroundOpaque:U.blend(Ki,Ui),selectionInactiveBackgroundTransparent:Ui,selectionInactiveBackgroundOpaque:U.blend(Ki,Ui),scrollbarSliderBackground:U.opacity(St,.2),scrollbarSliderHoverBackground:U.opacity(St,.4),scrollbarSliderActiveBackground:U.opacity(St,.5),overviewRulerBorder:St,ansi:re.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this._register(this._optionsService.onSpecificOptionChange("minimumContrastRatio",()=>this._contrastCache.clear())),this._register(this._optionsService.onSpecificOptionChange("theme",()=>this._setTheme(this._optionsService.rawOptions.theme)))}get colors(){return this._colors}_setTheme(e={}){let i=this._colors;if(i.foreground=K(e.foreground,St),i.background=K(e.background,Ki),i.cursor=U.blend(i.background,K(e.cursor,tl)),i.cursorAccent=U.blend(i.background,K(e.cursorAccent,il)),i.selectionBackgroundTransparent=K(e.selectionBackground,Ui),i.selectionBackgroundOpaque=U.blend(i.background,i.selectionBackgroundTransparent),i.selectionInactiveBackgroundTransparent=K(e.selectionInactiveBackground,i.selectionBackgroundTransparent),i.selectionInactiveBackgroundOpaque=U.blend(i.background,i.selectionInactiveBackgroundTransparent),i.selectionForeground=e.selectionForeground?K(e.selectionForeground,ps):void 0,i.selectionForeground===ps&&(i.selectionForeground=void 0),U.isOpaque(i.selectionBackgroundTransparent)&&(i.selectionBackgroundTransparent=U.opacity(i.selectionBackgroundTransparent,.3)),U.isOpaque(i.selectionInactiveBackgroundTransparent)&&(i.selectionInactiveBackgroundTransparent=U.opacity(i.selectionInactiveBackgroundTransparent,.3)),i.scrollbarSliderBackground=K(e.scrollbarSliderBackground,U.opacity(i.foreground,.2)),i.scrollbarSliderHoverBackground=K(e.scrollbarSliderHoverBackground,U.opacity(i.foreground,.4)),i.scrollbarSliderActiveBackground=K(e.scrollbarSliderActiveBackground,U.opacity(i.foreground,.5)),i.overviewRulerBorder=K(e.overviewRulerBorder,Qa),i.ansi=re.slice(),i.ansi[0]=K(e.black,re[0]),i.ansi[1]=K(e.red,re[1]),i.ansi[2]=K(e.green,re[2]),i.ansi[3]=K(e.yellow,re[3]),i.ansi[4]=K(e.blue,re[4]),i.ansi[5]=K(e.magenta,re[5]),i.ansi[6]=K(e.cyan,re[6]),i.ansi[7]=K(e.white,re[7]),i.ansi[8]=K(e.brightBlack,re[8]),i.ansi[9]=K(e.brightRed,re[9]),i.ansi[10]=K(e.brightGreen,re[10]),i.ansi[11]=K(e.brightYellow,re[11]),i.ansi[12]=K(e.brightBlue,re[12]),i.ansi[13]=K(e.brightMagenta,re[13]),i.ansi[14]=K(e.brightCyan,re[14]),i.ansi[15]=K(e.brightWhite,re[15]),e.extendedAnsi){let r=Math.min(i.ansi.length-16,e.extendedAnsi.length);for(let n=0;no.index-l.index),r=[];for(let o of i){let l=this._services.get(o.id);if(!l)throw new Error(`[createInstance] ${t.name} depends on UNKNOWN service ${o.id._id}.`);r.push(l)}let n=i.length>0?i[0].index:e.length;if(e.length!==n)throw new Error(`[createInstance] First service dependency of ${t.name} at position ${n+1} conflicts with ${e.length} static arguments`);return new t(...e,...r)}};var ec={trace:0,debug:1,info:2,warn:3,error:4,off:5},tc="xterm.js: ",ii=class extends D{constructor(e){super();this._optionsService=e;this._logLevel=5;this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange("logLevel",()=>this._updateLogLevel())),ic=this}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=ec[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let i=0;ithis._length)for(let i=this._length;i=e;n--)this._array[this._getCyclicIndex(n+r.length)]=this._array[this._getCyclicIndex(n)];for(let n=0;nthis._maxLength){let n=this._length+r.length-this._maxLength;this._startIndex+=n,this._length=this._maxLength,this.onTrimEmitter.fire(n)}else this._length+=r.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,i,r){if(!(i<=0)){if(e<0||e>=this._length)throw new Error("start argument out of range");if(e+r<0)throw new Error("Cannot shift elements in list beyond index 0");if(r>0){for(let o=i-1;o>=0;o--)this.set(e+o+r,this.get(e+o));let n=e+i+r-this._length;if(n>0)for(this._length+=n;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let n=0;n>22,e&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):i]}set(t,e){this._data[t*B+1]=e[0],e[1].length>1?(this._combined[t]=e[1],this._data[t*B+0]=t|2097152|e[2]<<22):this._data[t*B+0]=e[1].charCodeAt(0)|e[2]<<22}getWidth(t){return this._data[t*B+0]>>22}hasWidth(t){return this._data[t*B+0]&12582912}getFg(t){return this._data[t*B+1]}getBg(t){return this._data[t*B+2]}hasContent(t){return this._data[t*B+0]&4194303}getCodePoint(t){let e=this._data[t*B+0];return e&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):e&2097151}isCombined(t){return this._data[t*B+0]&2097152}getString(t){let e=this._data[t*B+0];return e&2097152?this._combined[t]:e&2097151?Ce(e&2097151):""}isProtected(t){return this._data[t*B+2]&536870912}loadCell(t,e){return an=t*B,e.content=this._data[an+0],e.fg=this._data[an+1],e.bg=this._data[an+2],e.content&2097152&&(e.combinedData=this._combined[t]),e.bg&268435456&&(e.extended=this._extendedAttrs[t]),e}setCell(t,e){e.content&2097152&&(this._combined[t]=e.combinedData),e.bg&268435456&&(this._extendedAttrs[t]=e.extended),this._data[t*B+0]=e.content,this._data[t*B+1]=e.fg,this._data[t*B+2]=e.bg}setCellFromCodepoint(t,e,i,r){r.bg&268435456&&(this._extendedAttrs[t]=r.extended),this._data[t*B+0]=e|i<<22,this._data[t*B+1]=r.fg,this._data[t*B+2]=r.bg}addCodepointToCell(t,e,i){let r=this._data[t*B+0];r&2097152?this._combined[t]+=Ce(e):r&2097151?(this._combined[t]=Ce(r&2097151)+Ce(e),r&=-2097152,r|=2097152):r=e|1<<22,i&&(r&=-12582913,r|=i<<22),this._data[t*B+0]=r}insertCells(t,e,i){if(t%=this.length,t&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t-1,0,1,i),e=0;--n)this.setCell(t+e+n,this.loadCell(t+n,r));for(let n=0;nthis.length){if(this._data.buffer.byteLength>=i*4)this._data=new Uint32Array(this._data.buffer,0,i);else{let r=new Uint32Array(i);r.set(this._data),this._data=r}for(let r=this.length;r=t&&delete this._combined[l]}let n=Object.keys(this._extendedAttrs);for(let o=0;o=t&&delete this._extendedAttrs[l]}}return this.length=t,i*4*Ls=0;--t)if(this._data[t*B+0]&4194303)return t+(this._data[t*B+0]>>22);return 0}getNoBgTrimmedLength(){for(let t=this.length-1;t>=0;--t)if(this._data[t*B+0]&4194303||this._data[t*B+2]&50331648)return t+(this._data[t*B+0]>>22);return 0}copyCellsFrom(t,e,i,r,n){let o=t._data;if(n)for(let a=r-1;a>=0;a--){for(let u=0;u=e&&(this._combined[u-e+i]=t._combined[u])}}translateToString(t,e,i,r){e=e??0,i=i??this.length,t&&(i=Math.min(i,this.getTrimmedLength())),r&&(r.length=0);let n="";for(;e>22||1}return r&&r.push(e),n}};function sl(s,t,e,i,r,n){let o=[];for(let l=0;l=l&&i0&&(f>c||h[f].getTrimmedLength()===0);f--)m++;m>0&&(o.push(l+h.length-m),o.push(m)),l+=h.length-1}return o}function ol(s,t){let e=[],i=0,r=t[i],n=0;for(let o=0;ori(s,u,t)).reduce((a,u)=>a+u),n=0,o=0,l=0;for(;la&&(n-=a,o++);let u=s[o].getWidth(n-1)===2;u&&n--;let h=u?e-1:e;i.push(h),l+=h}return i}function ri(s,t,e){if(t===s.length-1)return s[t].getTrimmedLength();let i=!s[t].hasContent(e-1)&&s[t].getWidth(e-1)===1,r=s[t+1].getWidth(0)===2;return i&&r?e-1:e}var un=class un{constructor(t){this.line=t;this.isDisposed=!1;this._disposables=[];this._id=un._nextId++;this._onDispose=this.register(new v);this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),Ne(this._disposables),this._disposables.length=0)}register(t){return this._disposables.push(t),t}};un._nextId=1;var cn=un;var ne={},Je=ne.B;ne[0]={"`":"\u25C6",a:"\u2592",b:"\u2409",c:"\u240C",d:"\u240D",e:"\u240A",f:"\xB0",g:"\xB1",h:"\u2424",i:"\u240B",j:"\u2518",k:"\u2510",l:"\u250C",m:"\u2514",n:"\u253C",o:"\u23BA",p:"\u23BB",q:"\u2500",r:"\u23BC",s:"\u23BD",t:"\u251C",u:"\u2524",v:"\u2534",w:"\u252C",x:"\u2502",y:"\u2264",z:"\u2265","{":"\u03C0","|":"\u2260","}":"\xA3","~":"\xB7"};ne.A={"#":"\xA3"};ne.B=void 0;ne[4]={"#":"\xA3","@":"\xBE","[":"ij","\\":"\xBD","]":"|","{":"\xA8","|":"f","}":"\xBC","~":"\xB4"};ne.C=ne[5]={"[":"\xC4","\\":"\xD6","]":"\xC5","^":"\xDC","`":"\xE9","{":"\xE4","|":"\xF6","}":"\xE5","~":"\xFC"};ne.R={"#":"\xA3","@":"\xE0","[":"\xB0","\\":"\xE7","]":"\xA7","{":"\xE9","|":"\xF9","}":"\xE8","~":"\xA8"};ne.Q={"@":"\xE0","[":"\xE2","\\":"\xE7","]":"\xEA","^":"\xEE","`":"\xF4","{":"\xE9","|":"\xF9","}":"\xE8","~":"\xFB"};ne.K={"@":"\xA7","[":"\xC4","\\":"\xD6","]":"\xDC","{":"\xE4","|":"\xF6","}":"\xFC","~":"\xDF"};ne.Y={"#":"\xA3","@":"\xA7","[":"\xB0","\\":"\xE7","]":"\xE9","`":"\xF9","{":"\xE0","|":"\xF2","}":"\xE8","~":"\xEC"};ne.E=ne[6]={"@":"\xC4","[":"\xC6","\\":"\xD8","]":"\xC5","^":"\xDC","`":"\xE4","{":"\xE6","|":"\xF8","}":"\xE5","~":"\xFC"};ne.Z={"#":"\xA3","@":"\xA7","[":"\xA1","\\":"\xD1","]":"\xBF","{":"\xB0","|":"\xF1","}":"\xE7"};ne.H=ne[7]={"@":"\xC9","[":"\xC4","\\":"\xD6","]":"\xC5","^":"\xDC","`":"\xE9","{":"\xE4","|":"\xF6","}":"\xE5","~":"\xFC"};ne["="]={"#":"\xF9","@":"\xE0","[":"\xE9","\\":"\xE7","]":"\xEA","^":"\xEE",_:"\xE8","`":"\xF4","{":"\xE4","|":"\xF6","}":"\xFC","~":"\xFB"};var cl=4294967295,$i=class{constructor(t,e,i){this._hasScrollback=t;this._optionsService=e;this._bufferService=i;this.ydisp=0;this.ybase=0;this.y=0;this.x=0;this.tabs={};this.savedY=0;this.savedX=0;this.savedCurAttrData=X.clone();this.savedCharset=Je;this.markers=[];this._nullCell=q.fromCharData([0,ir,1,0]);this._whitespaceCell=q.fromCharData([0,we,1,32]);this._isClearing=!1;this._memoryCleanupQueue=new Jt;this._memoryCleanupPosition=0;this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new zi(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(t){return t?(this._nullCell.fg=t.fg,this._nullCell.bg=t.bg,this._nullCell.extended=t.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new rt),this._nullCell}getWhitespaceCell(t){return t?(this._whitespaceCell.fg=t.fg,this._whitespaceCell.bg=t.bg,this._whitespaceCell.extended=t.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new rt),this._whitespaceCell}getBlankLine(t,e){return new Ze(this._bufferService.cols,this.getNullCell(t),e)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let e=this.ybase+this.y-this.ydisp;return e>=0&&ecl?cl:e}fillViewportRows(t){if(this.lines.length===0){t===void 0&&(t=X);let e=this._rows;for(;e--;)this.lines.push(this.getBlankLine(t))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new zi(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(t,e){let i=this.getNullCell(X),r=0,n=this._getCorrectBufferLength(e);if(n>this.lines.maxLength&&(this.lines.maxLength=n),this.lines.length>0){if(this._cols0&&this.lines.length<=this.ybase+this.y+o+1?(this.ybase--,o++,this.ydisp>0&&this.ydisp--):this.lines.push(new Ze(t,i)));else for(let l=this._rows;l>e;l--)this.lines.length>e+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(n0&&(this.lines.trimStart(l),this.ybase=Math.max(this.ybase-l,0),this.ydisp=Math.max(this.ydisp-l,0),this.savedY=Math.max(this.savedY-l,0)),this.lines.maxLength=n}this.x=Math.min(this.x,t-1),this.y=Math.min(this.y,e-1),o&&(this.y+=o),this.savedX=Math.min(this.savedX,t-1),this.scrollTop=0}if(this.scrollBottom=e-1,this._isReflowEnabled&&(this._reflow(t,e),this._cols>t))for(let o=0;o.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let t=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,t=!1);let e=0;for(;this._memoryCleanupPosition100)return!0;return t}get _isReflowEnabled(){let t=this._optionsService.rawOptions.windowsPty;return t&&t.buildNumber?this._hasScrollback&&t.backend==="conpty"&&t.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(t,e){this._cols!==t&&(t>this._cols?this._reflowLarger(t,e):this._reflowSmaller(t,e))}_reflowLarger(t,e){let i=this._optionsService.rawOptions.reflowCursorLine,r=sl(this.lines,this._cols,t,this.ybase+this.y,this.getNullCell(X),i);if(r.length>0){let n=ol(this.lines,r);ll(this.lines,n.layout),this._reflowLargerAdjustViewport(t,e,n.countRemoved)}}_reflowLargerAdjustViewport(t,e,i){let r=this.getNullCell(X),n=i;for(;n-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length=0;l--){let a=this.lines.get(l);if(!a||!a.isWrapped&&a.getTrimmedLength()<=t)continue;let u=[a];for(;a.isWrapped&&l>0;)a=this.lines.get(--l),u.unshift(a);if(!i){let I=this.ybase+this.y;if(I>=l&&I0&&(n.push({start:l+u.length+o,newLines:p}),o+=p.length),u.push(...p);let m=c.length-1,f=c[m];f===0&&(m--,f=c[m]);let A=u.length-d-1,R=h;for(;A>=0;){let I=Math.min(R,f);if(u[m]===void 0)break;if(u[m].copyCellsFrom(u[A],R-I,f-I,I,!0),f-=I,f===0&&(m--,f=c[m]),R-=I,R===0){A--;let k=Math.max(A,0);R=ri(u,k,this._cols)}}for(let I=0;I0;)this.ybase===0?this.y0){let l=[],a=[];for(let f=0;f=0;f--)if(d&&d.start>h+_){for(let A=d.newLines.length-1;A>=0;A--)this.lines.set(f--,d.newLines[A]);f++,l.push({index:h+1,amount:d.newLines.length}),_+=d.newLines.length,d=n[++c]}else this.lines.set(f,a[h--]);let p=0;for(let f=l.length-1;f>=0;f--)l[f].index+=p,this.lines.onInsertEmitter.fire(l[f]),p+=l[f].amount;let m=Math.max(0,u+o-this.lines.maxLength);m>0&&this.lines.onTrimEmitter.fire(m)}}translateBufferLineToString(t,e,i=0,r){let n=this.lines.get(t);return n?n.translateToString(e,i,r):""}getWrappedRangeForLine(t){let e=t,i=t;for(;e>0&&this.lines.get(e).isWrapped;)e--;for(;i+10;);return t>=this._cols?this._cols-1:t<0?0:t}nextStop(t){for(t==null&&(t=this.x);!this.tabs[++t]&&t=this._cols?this._cols-1:t<0?0:t}clearMarkers(t){this._isClearing=!0;for(let e=0;e{e.line-=i,e.line<0&&e.dispose()})),e.register(this.lines.onInsert(i=>{e.line>=i.index&&(e.line+=i.amount)})),e.register(this.lines.onDelete(i=>{e.line>=i.index&&e.linei.index&&(e.line-=i.amount)})),e.register(e.onDispose(()=>this._removeMarker(e))),e}_removeMarker(t){this._isClearing||this.markers.splice(this.markers.indexOf(t),1)}};var hn=class extends D{constructor(e,i){super();this._optionsService=e;this._bufferService=i;this._onBufferActivate=this._register(new v);this.onBufferActivate=this._onBufferActivate.event;this.reset(),this._register(this._optionsService.onSpecificOptionChange("scrollback",()=>this.resize(this._bufferService.cols,this._bufferService.rows))),this._register(this._optionsService.onSpecificOptionChange("tabStopWidth",()=>this.setupTabStops()))}reset(){this._normal=new $i(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new $i(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(e,i){this._normal.resize(e,i),this._alt.resize(e,i),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}};var ks=2,Cs=1,ni=class extends D{constructor(e){super();this.isUserScrolling=!1;this._onResize=this._register(new v);this.onResize=this._onResize.event;this._onScroll=this._register(new v);this.onScroll=this._onScroll.event;this.cols=Math.max(e.rawOptions.cols||0,ks),this.rows=Math.max(e.rawOptions.rows||0,Cs),this.buffers=this._register(new hn(e,this)),this._register(this.buffers.onBufferActivate(i=>{this._onScroll.fire(i.activeBuffer.ydisp)}))}get buffer(){return this.buffers.active}resize(e,i){let r=this.cols!==e,n=this.rows!==i;this.cols=e,this.rows=i,this.buffers.resize(e,i),this._onResize.fire({cols:e,rows:i,colsChanged:r,rowsChanged:n})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,i=!1){let r=this.buffer,n;n=this._cachedBlankLine,(!n||n.length!==this.cols||n.getFg(0)!==e.fg||n.getBg(0)!==e.bg)&&(n=r.getBlankLine(e,i),this._cachedBlankLine=n),n.isWrapped=i;let o=r.ybase+r.scrollTop,l=r.ybase+r.scrollBottom;if(r.scrollTop===0){let a=r.lines.isFull;l===r.lines.length-1?a?r.lines.recycle().copyFrom(n):r.lines.push(n.clone()):r.lines.splice(l+1,0,n.clone()),a?this.isUserScrolling&&(r.ydisp=Math.max(r.ydisp-1,0)):(r.ybase++,this.isUserScrolling||r.ydisp++)}else{let a=l-o+1;r.lines.shiftElements(o+1,a-1,-1),r.lines.set(l,n.clone())}this.isUserScrolling||(r.ydisp=r.ybase),this._onScroll.fire(r.ydisp)}scrollLines(e,i){let r=this.buffer;if(e<0){if(r.ydisp===0)return;this.isUserScrolling=!0}else e+r.ydisp>=r.ybase&&(this.isUserScrolling=!1);let n=r.ydisp;r.ydisp=Math.max(Math.min(r.ydisp+e,r.ybase),0),n!==r.ydisp&&(i||this._onScroll.fire(r.ydisp))}};ni=M([S(0,H)],ni);var si={cols:80,rows:24,cursorBlink:!1,cursorStyle:"block",cursorWidth:1,cursorInactiveStyle:"outline",customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:"alt",fastScrollSensitivity:5,fontFamily:"monospace",fontSize:15,fontWeight:"normal",fontWeightBold:"bold",ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:"info",logger:null,scrollback:1e3,scrollOnEraseInDisplay:!1,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},reflowCursorLine:!1,rescaleOverlappingGlyphs:!1,rightClickSelectsWord:Zt,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRuler:{}},nc=["normal","bold","100","200","300","400","500","600","700","800","900"],dn=class extends D{constructor(e){super();this._onOptionChange=this._register(new v);this.onOptionChange=this._onOptionChange.event;let i={...si};for(let r in e)if(r in i)try{let n=e[r];i[r]=this._sanitizeAndValidateOption(r,n)}catch(n){console.error(n)}this.rawOptions=i,this.options={...i},this._setupOptions(),this._register(C(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(e,i){return this.onOptionChange(r=>{r===e&&i(this.rawOptions[e])})}onMultipleOptionChange(e,i){return this.onOptionChange(r=>{e.indexOf(r)!==-1&&i()})}_setupOptions(){let e=r=>{if(!(r in si))throw new Error(`No option with key "${r}"`);return this.rawOptions[r]},i=(r,n)=>{if(!(r in si))throw new Error(`No option with key "${r}"`);n=this._sanitizeAndValidateOption(r,n),this.rawOptions[r]!==n&&(this.rawOptions[r]=n,this._onOptionChange.fire(r))};for(let r in this.rawOptions){let n={get:e.bind(this,r),set:i.bind(this,r)};Object.defineProperty(this.options,r,n)}}_sanitizeAndValidateOption(e,i){switch(e){case"cursorStyle":if(i||(i=si[e]),!sc(i))throw new Error(`"${i}" is not a valid value for ${e}`);break;case"wordSeparator":i||(i=si[e]);break;case"fontWeight":case"fontWeightBold":if(typeof i=="number"&&1<=i&&i<=1e3)break;i=nc.includes(i)?i:si[e];break;case"cursorWidth":i=Math.floor(i);case"lineHeight":case"tabStopWidth":if(i<1)throw new Error(`${e} cannot be less than 1, value: ${i}`);break;case"minimumContrastRatio":i=Math.max(1,Math.min(21,Math.round(i*10)/10));break;case"scrollback":if(i=Math.min(i,4294967295),i<0)throw new Error(`${e} cannot be less than 0, value: ${i}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(i<=0)throw new Error(`${e} cannot be less than or equal to 0, value: ${i}`);break;case"rows":case"cols":if(!i&&i!==0)throw new Error(`${e} must be numeric, value: ${i}`);break;case"windowsPty":i=i??{};break}return i}};function sc(s){return s==="block"||s==="underline"||s==="bar"}function oi(s,t=5){if(typeof s!="object")return s;let e=Array.isArray(s)?[]:{};for(let i in s)e[i]=t<=1?s[i]:s[i]&&oi(s[i],t-1);return e}var ul=Object.freeze({insertMode:!1}),hl=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),li=class extends D{constructor(e,i,r){super();this._bufferService=e;this._logService=i;this._optionsService=r;this.isCursorInitialized=!1;this.isCursorHidden=!1;this._onData=this._register(new v);this.onData=this._onData.event;this._onUserInput=this._register(new v);this.onUserInput=this._onUserInput.event;this._onBinary=this._register(new v);this.onBinary=this._onBinary.event;this._onRequestScrollToBottom=this._register(new v);this.onRequestScrollToBottom=this._onRequestScrollToBottom.event;this.modes=oi(ul),this.decPrivateModes=oi(hl)}reset(){this.modes=oi(ul),this.decPrivateModes=oi(hl)}triggerDataEvent(e,i=!1){if(this._optionsService.rawOptions.disableStdin)return;let r=this._bufferService.buffer;i&&this._optionsService.rawOptions.scrollOnUserInput&&r.ybase!==r.ydisp&&this._onRequestScrollToBottom.fire(),i&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`),this._logService.trace("sending data (codes)",()=>e.split("").map(n=>n.charCodeAt(0))),this._onData.fire(e)}triggerBinaryEvent(e){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${e}"`),this._logService.trace("sending binary (codes)",()=>e.split("").map(i=>i.charCodeAt(0))),this._onBinary.fire(e))}};li=M([S(0,F),S(1,nr),S(2,H)],li);var dl={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:s=>s.button===4||s.action!==1?!1:(s.ctrl=!1,s.alt=!1,s.shift=!1,!0)},VT200:{events:19,restrict:s=>s.action!==32},DRAG:{events:23,restrict:s=>!(s.action===32&&s.button===3)},ANY:{events:31,restrict:s=>!0}};function Ms(s,t){let e=(s.ctrl?16:0)|(s.shift?4:0)|(s.alt?8:0);return s.button===4?(e|=64,e|=s.action):(e|=s.button&3,s.button&4&&(e|=64),s.button&8&&(e|=128),s.action===32?e|=32:s.action===0&&!t&&(e|=3)),e}var Ps=String.fromCharCode,fl={DEFAULT:s=>{let t=[Ms(s,!1)+32,s.col+32,s.row+32];return t[0]>255||t[1]>255||t[2]>255?"":`\x1B[M${Ps(t[0])}${Ps(t[1])}${Ps(t[2])}`},SGR:s=>{let t=s.action===0&&s.button!==4?"m":"M";return`\x1B[<${Ms(s,!0)};${s.col};${s.row}${t}`},SGR_PIXELS:s=>{let t=s.action===0&&s.button!==4?"m":"M";return`\x1B[<${Ms(s,!0)};${s.x};${s.y}${t}`}},ai=class extends D{constructor(e,i,r){super();this._bufferService=e;this._coreService=i;this._optionsService=r;this._protocols={};this._encodings={};this._activeProtocol="";this._activeEncoding="";this._lastEvent=null;this._wheelPartialScroll=0;this._onProtocolChange=this._register(new v);this.onProtocolChange=this._onProtocolChange.event;for(let n of Object.keys(dl))this.addProtocol(n,dl[n]);for(let n of Object.keys(fl))this.addEncoding(n,fl[n]);this.reset()}addProtocol(e,i){this._protocols[e]=i}addEncoding(e,i){this._encodings[e]=i}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(e){if(!this._protocols[e])throw new Error(`unknown protocol "${e}"`);this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e){if(!this._encodings[e])throw new Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(e,i,r){if(e.deltaY===0||e.shiftKey||i===void 0||r===void 0)return 0;let n=i/r,o=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(o/=n+0,Math.abs(e.deltaY)<50&&(o*=.3),this._wheelPartialScroll+=o,o=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(o*=this._bufferService.rows),o}_applyScrollModifier(e,i){return i.altKey||i.ctrlKey||i.shiftKey?e*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:e*this._optionsService.rawOptions.scrollSensitivity}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows||e.button===4&&e.action===32||e.button===3&&e.action!==32||e.button!==4&&(e.action===2||e.action===3)||(e.col++,e.row++,e.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,e,this._activeEncoding==="SGR_PIXELS"))||!this._protocols[this._activeProtocol].restrict(e))return!1;let i=this._encodings[this._activeEncoding](e);return i&&(this._activeEncoding==="DEFAULT"?this._coreService.triggerBinaryEvent(i):this._coreService.triggerDataEvent(i,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(e&1),up:!!(e&2),drag:!!(e&4),move:!!(e&8),wheel:!!(e&16)}}_equalEvents(e,i,r){if(r){if(e.x!==i.x||e.y!==i.y)return!1}else if(e.col!==i.col||e.row!==i.row)return!1;return!(e.button!==i.button||e.action!==i.action||e.ctrl!==i.ctrl||e.alt!==i.alt||e.shift!==i.shift)}};ai=M([S(0,F),S(1,ge),S(2,H)],ai);var Os=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],ac=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]],se;function cc(s,t){let e=0,i=t.length-1,r;if(st[i][1])return!1;for(;i>=e;)if(r=e+i>>1,s>t[r][1])e=r+1;else if(s=131072&&t<=196605||t>=196608&&t<=262141?2:1}charProperties(t,e){let i=this.wcwidth(t),r=i===0&&e!==0;if(r){let n=Ae.extractWidth(e);n===0?r=!1:n>i&&(i=n)}return Ae.createPropertyValue(0,i,r)}};var Ae=class s{constructor(){this._providers=Object.create(null);this._active="";this._onChange=new v;this.onChange=this._onChange.event;let t=new fn;this.register(t),this._active=t.version,this._activeProvider=t}static extractShouldJoin(t){return(t&1)!==0}static extractWidth(t){return t>>1&3}static extractCharKind(t){return t>>3}static createPropertyValue(t,e,i=!1){return(t&16777215)<<3|(e&3)<<1|(i?1:0)}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(t){if(!this._providers[t])throw new Error(`unknown Unicode version "${t}"`);this._active=t,this._activeProvider=this._providers[t],this._onChange.fire(t)}register(t){this._providers[t.version]=t}wcwidth(t){return this._activeProvider.wcwidth(t)}getStringCellWidth(t){let e=0,i=0,r=t.length;for(let n=0;n=r)return e+this.wcwidth(o);let u=t.charCodeAt(n);56320<=u&&u<=57343?o=(o-55296)*1024+u-56320+65536:e+=this.wcwidth(u)}let l=this.charProperties(o,i),a=s.extractWidth(l);s.extractShouldJoin(l)&&(a-=s.extractWidth(i)),e+=a,i=l}return e}charProperties(t,e){return this._activeProvider.charProperties(t,e)}};var pn=class{constructor(){this.glevel=0;this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(t){this.glevel=t,this.charset=this._charsets[t]}setgCharset(t,e){this._charsets[t]=e,this.glevel===t&&(this.charset=e)}};function Bs(s){let e=s.buffer.lines.get(s.buffer.ybase+s.buffer.y-1)?.get(s.cols-1),i=s.buffer.lines.get(s.buffer.ybase+s.buffer.y);i&&e&&(i.isWrapped=e[3]!==0&&e[3]!==32)}var Vi=2147483647,uc=256,ci=class s{constructor(t=32,e=32){this.maxLength=t;this.maxSubParamsLength=e;if(e>uc)throw new Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(t),this.length=0,this._subParams=new Int32Array(e),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(t),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}static fromArray(t){let e=new s;if(!t.length)return e;for(let i=Array.isArray(t[0])?1:0;i>8,r=this._subParamsIdx[e]&255;r-i>0&&t.push(Array.prototype.slice.call(this._subParams,i,r))}return t}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(t){if(this._digitIsSub=!1,this.length>=this.maxLength){this._rejectDigits=!0;return}if(t<-1)throw new Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=t>Vi?Vi:t}addSubParam(t){if(this._digitIsSub=!0,!!this.length){if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength){this._rejectSubDigits=!0;return}if(t<-1)throw new Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=t>Vi?Vi:t,this._subParamsIdx[this.length-1]++}}hasSubParams(t){return(this._subParamsIdx[t]&255)-(this._subParamsIdx[t]>>8)>0}getSubParams(t){let e=this._subParamsIdx[t]>>8,i=this._subParamsIdx[t]&255;return i-e>0?this._subParams.subarray(e,i):null}getSubParamsAll(){let t={};for(let e=0;e>8,r=this._subParamsIdx[e]&255;r-i>0&&(t[e]=this._subParams.slice(i,r))}return t}addDigit(t){let e;if(this._rejectDigits||!(e=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let i=this._digitIsSub?this._subParams:this.params,r=i[e-1];i[e-1]=~r?Math.min(r*10+t,Vi):t}};var qi=[],mn=class{constructor(){this._state=0;this._active=qi;this._id=-1;this._handlers=Object.create(null);this._handlerFb=()=>{};this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(t,e){this._handlers[t]===void 0&&(this._handlers[t]=[]);let i=this._handlers[t];return i.push(e),{dispose:()=>{let r=i.indexOf(e);r!==-1&&i.splice(r,1)}}}clearHandler(t){this._handlers[t]&&delete this._handlers[t]}setHandlerFallback(t){this._handlerFb=t}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=qi}reset(){if(this._state===2)for(let t=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;t>=0;--t)this._active[t].end(!1);this._stack.paused=!1,this._active=qi,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||qi,!this._active.length)this._handlerFb(this._id,"START");else for(let t=this._active.length-1;t>=0;t--)this._active[t].start()}_put(t,e,i){if(!this._active.length)this._handlerFb(this._id,"PUT",It(t,e,i));else for(let r=this._active.length-1;r>=0;r--)this._active[r].put(t,e,i)}start(){this.reset(),this._state=1}put(t,e,i){if(this._state!==3){if(this._state===1)for(;e0&&this._put(t,e,i)}}end(t,e=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),!this._active.length)this._handlerFb(this._id,"END",t);else{let i=!1,r=this._active.length-1,n=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,i=e,n=this._stack.fallThrough,this._stack.paused=!1),!n&&i===!1){for(;r>=0&&(i=this._active[r].end(t),i!==!0);r--)if(i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,i;r--}for(;r>=0;r--)if(i=this._active[r].end(!1),i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,i}this._active=qi,this._id=-1,this._state=0}}},pe=class{constructor(t){this._handler=t;this._data="";this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(t,e,i){this._hitLimit||(this._data+=It(t,e,i),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}end(t){let e=!1;if(this._hitLimit)e=!1;else if(t&&(e=this._handler(this._data),e instanceof Promise))return e.then(i=>(this._data="",this._hitLimit=!1,i));return this._data="",this._hitLimit=!1,e}};var Yi=[],_n=class{constructor(){this._handlers=Object.create(null);this._active=Yi;this._ident=0;this._handlerFb=()=>{};this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=Yi}registerHandler(t,e){this._handlers[t]===void 0&&(this._handlers[t]=[]);let i=this._handlers[t];return i.push(e),{dispose:()=>{let r=i.indexOf(e);r!==-1&&i.splice(r,1)}}}clearHandler(t){this._handlers[t]&&delete this._handlers[t]}setHandlerFallback(t){this._handlerFb=t}reset(){if(this._active.length)for(let t=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;t>=0;--t)this._active[t].unhook(!1);this._stack.paused=!1,this._active=Yi,this._ident=0}hook(t,e){if(this.reset(),this._ident=t,this._active=this._handlers[t]||Yi,!this._active.length)this._handlerFb(this._ident,"HOOK",e);else for(let i=this._active.length-1;i>=0;i--)this._active[i].hook(e)}put(t,e,i){if(!this._active.length)this._handlerFb(this._ident,"PUT",It(t,e,i));else for(let r=this._active.length-1;r>=0;r--)this._active[r].put(t,e,i)}unhook(t,e=!0){if(!this._active.length)this._handlerFb(this._ident,"UNHOOK",t);else{let i=!1,r=this._active.length-1,n=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,i=e,n=this._stack.fallThrough,this._stack.paused=!1),!n&&i===!1){for(;r>=0&&(i=this._active[r].unhook(t),i!==!0);r--)if(i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,i;r--}for(;r>=0;r--)if(i=this._active[r].unhook(!1),i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,i}this._active=Yi,this._ident=0}},ji=new ci;ji.addParam(0);var Xi=class{constructor(t){this._handler=t;this._data="";this._params=ji;this._hitLimit=!1}hook(t){this._params=t.length>1||t.params[0]?t.clone():ji,this._data="",this._hitLimit=!1}put(t,e,i){this._hitLimit||(this._data+=It(t,e,i),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}unhook(t){let e=!1;if(this._hitLimit)e=!1;else if(t&&(e=this._handler(this._data,this._params),e instanceof Promise))return e.then(i=>(this._params=ji,this._data="",this._hitLimit=!1,i));return this._params=ji,this._data="",this._hitLimit=!1,e}};var Fs=class{constructor(t){this.table=new Uint8Array(t)}setDefault(t,e){this.table.fill(t<<4|e)}add(t,e,i,r){this.table[e<<8|t]=i<<4|r}addMany(t,e,i,r){for(let n=0;nu),i=(a,u)=>e.slice(a,u),r=i(32,127),n=i(0,24);n.push(25),n.push.apply(n,i(28,32));let o=i(0,14),l;s.setDefault(1,0),s.addMany(r,0,2,0);for(l in o)s.addMany([24,26,153,154],l,3,0),s.addMany(i(128,144),l,3,0),s.addMany(i(144,152),l,3,0),s.add(156,l,0,0),s.add(27,l,11,1),s.add(157,l,4,8),s.addMany([152,158,159],l,0,7),s.add(155,l,11,3),s.add(144,l,11,9);return s.addMany(n,0,3,0),s.addMany(n,1,3,1),s.add(127,1,0,1),s.addMany(n,8,0,8),s.addMany(n,3,3,3),s.add(127,3,0,3),s.addMany(n,4,3,4),s.add(127,4,0,4),s.addMany(n,6,3,6),s.addMany(n,5,3,5),s.add(127,5,0,5),s.addMany(n,2,3,2),s.add(127,2,0,2),s.add(93,1,4,8),s.addMany(r,8,5,8),s.add(127,8,5,8),s.addMany([156,27,24,26,7],8,6,0),s.addMany(i(28,32),8,0,8),s.addMany([88,94,95],1,0,7),s.addMany(r,7,0,7),s.addMany(n,7,0,7),s.add(156,7,0,0),s.add(127,7,0,7),s.add(91,1,11,3),s.addMany(i(64,127),3,7,0),s.addMany(i(48,60),3,8,4),s.addMany([60,61,62,63],3,9,4),s.addMany(i(48,60),4,8,4),s.addMany(i(64,127),4,7,0),s.addMany([60,61,62,63],4,0,6),s.addMany(i(32,64),6,0,6),s.add(127,6,0,6),s.addMany(i(64,127),6,0,0),s.addMany(i(32,48),3,9,5),s.addMany(i(32,48),5,9,5),s.addMany(i(48,64),5,0,6),s.addMany(i(64,127),5,7,0),s.addMany(i(32,48),4,9,5),s.addMany(i(32,48),1,9,2),s.addMany(i(32,48),2,9,2),s.addMany(i(48,127),2,10,0),s.addMany(i(48,80),1,10,0),s.addMany(i(81,88),1,10,0),s.addMany([89,90,92],1,10,0),s.addMany(i(96,127),1,10,0),s.add(80,1,11,9),s.addMany(n,9,0,9),s.add(127,9,0,9),s.addMany(i(28,32),9,0,9),s.addMany(i(32,48),9,9,12),s.addMany(i(48,60),9,8,10),s.addMany([60,61,62,63],9,9,10),s.addMany(n,11,0,11),s.addMany(i(32,128),11,0,11),s.addMany(i(28,32),11,0,11),s.addMany(n,10,0,10),s.add(127,10,0,10),s.addMany(i(28,32),10,0,10),s.addMany(i(48,60),10,8,10),s.addMany([60,61,62,63],10,0,11),s.addMany(i(32,48),10,9,12),s.addMany(n,12,0,12),s.add(127,12,0,12),s.addMany(i(28,32),12,0,12),s.addMany(i(32,48),12,9,12),s.addMany(i(48,64),12,0,11),s.addMany(i(64,127),12,12,13),s.addMany(i(64,127),10,12,13),s.addMany(i(64,127),9,12,13),s.addMany(n,13,13,13),s.addMany(r,13,13,13),s.add(127,13,0,13),s.addMany([27,156,24,26],13,14,0),s.add(ke,0,2,0),s.add(ke,8,5,8),s.add(ke,6,0,6),s.add(ke,11,0,11),s.add(ke,13,13,13),s}(),bn=class extends D{constructor(e=hc){super();this._transitions=e;this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0};this.initialState=0,this.currentState=this.initialState,this._params=new ci,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(i,r,n)=>{},this._executeHandlerFb=i=>{},this._csiHandlerFb=(i,r)=>{},this._escHandlerFb=i=>{},this._errorHandlerFb=i=>i,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register(C(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new mn),this._dcsParser=this._register(new _n),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},()=>!0)}_identifier(e,i=[64,126]){let r=0;if(e.prefix){if(e.prefix.length>1)throw new Error("only one byte as prefix supported");if(r=e.prefix.charCodeAt(0),r&&60>r||r>63)throw new Error("prefix must be in range 0x3c .. 0x3f")}if(e.intermediates){if(e.intermediates.length>2)throw new Error("only two bytes as intermediates are supported");for(let o=0;ol||l>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");r<<=8,r|=l}}if(e.final.length!==1)throw new Error("final must be a single byte");let n=e.final.charCodeAt(0);if(i[0]>n||n>i[1])throw new Error(`final must be in range ${i[0]} .. ${i[1]}`);return r<<=8,r|=n,r}identToString(e){let i=[];for(;e;)i.push(String.fromCharCode(e&255)),e>>=8;return i.reverse().join("")}setPrintHandler(e){this._printHandler=e}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(e,i){let r=this._identifier(e,[48,126]);this._escHandlers[r]===void 0&&(this._escHandlers[r]=[]);let n=this._escHandlers[r];return n.push(i),{dispose:()=>{let o=n.indexOf(i);o!==-1&&n.splice(o,1)}}}clearEscHandler(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]}setEscHandlerFallback(e){this._escHandlerFb=e}setExecuteHandler(e,i){this._executeHandlers[e.charCodeAt(0)]=i}clearExecuteHandler(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]}setExecuteHandlerFallback(e){this._executeHandlerFb=e}registerCsiHandler(e,i){let r=this._identifier(e);this._csiHandlers[r]===void 0&&(this._csiHandlers[r]=[]);let n=this._csiHandlers[r];return n.push(i),{dispose:()=>{let o=n.indexOf(i);o!==-1&&n.splice(o,1)}}}clearCsiHandler(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]}setCsiHandlerFallback(e){this._csiHandlerFb=e}registerDcsHandler(e,i){return this._dcsParser.registerHandler(this._identifier(e),i)}clearDcsHandler(e){this._dcsParser.clearHandler(this._identifier(e))}setDcsHandlerFallback(e){this._dcsParser.setHandlerFallback(e)}registerOscHandler(e,i){return this._oscParser.registerHandler(e,i)}clearOscHandler(e){this._oscParser.clearHandler(e)}setOscHandlerFallback(e){this._oscParser.setHandlerFallback(e)}setErrorHandler(e){this._errorHandler=e}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(e,i,r,n,o){this._parseStack.state=e,this._parseStack.handlers=i,this._parseStack.handlerPos=r,this._parseStack.transition=n,this._parseStack.chunkPos=o}parse(e,i,r){let n=0,o=0,l=0,a;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,l=this._parseStack.chunkPos+1;else{if(r===void 0||this._parseStack.state===1)throw this._parseStack.state=1,new Error("improper continuation due to previous async handler, giving up parsing");let u=this._parseStack.handlers,h=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(r===!1&&h>-1){for(;h>=0&&(a=u[h](this._params),a!==!0);h--)if(a instanceof Promise)return this._parseStack.handlerPos=h,a}this._parseStack.handlers=[];break;case 4:if(r===!1&&h>-1){for(;h>=0&&(a=u[h](),a!==!0);h--)if(a instanceof Promise)return this._parseStack.handlerPos=h,a}this._parseStack.handlers=[];break;case 6:if(n=e[this._parseStack.chunkPos],a=this._dcsParser.unhook(n!==24&&n!==26,r),a)return a;n===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(n=e[this._parseStack.chunkPos],a=this._oscParser.end(n!==24&&n!==26,r),a)return a;n===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break}this._parseStack.state=0,l=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=this._parseStack.transition&15}for(let u=l;u>4){case 2:for(let m=u+1;;++m){if(m>=i||(n=e[m])<32||n>126&&n=i||(n=e[m])<32||n>126&&n=i||(n=e[m])<32||n>126&&n=i||(n=e[m])<32||n>126&&n=0&&(a=c[d](this._params),a!==!0);d--)if(a instanceof Promise)return this._preserveStack(3,c,d,o,u),a;d<0&&this._csiHandlerFb(this._collect<<8|n,this._params),this.precedingJoinState=0;break;case 8:do switch(n){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(n-48)}while(++u47&&n<60);u--;break;case 9:this._collect<<=8,this._collect|=n;break;case 10:let _=this._escHandlers[this._collect<<8|n],p=_?_.length-1:-1;for(;p>=0&&(a=_[p](),a!==!0);p--)if(a instanceof Promise)return this._preserveStack(4,_,p,o,u),a;p<0&&this._escHandlerFb(this._collect<<8|n),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|n,this._params);break;case 13:for(let m=u+1;;++m)if(m>=i||(n=e[m])===24||n===26||n===27||n>127&&n=i||(n=e[m])<32||n>127&&n>4:n>>8}return i}}function Hs(s,t){let e=s.toString(16),i=e.length<2?"0"+e:e;switch(t){case 4:return e[0];case 8:return i;case 12:return(i+i).slice(0,3);default:return i+i}}function ml(s,t=16){let[e,i,r]=s;return`rgb:${Hs(e,t)}/${Hs(i,t)}/${Hs(r,t)}`}var mc={"(":0,")":1,"*":2,"+":3,"-":1,".":2},ut=131072,_l=10;function bl(s,t){if(s>24)return t.setWinLines||!1;switch(s){case 1:return!!t.restoreWin;case 2:return!!t.minimizeWin;case 3:return!!t.setWinPosition;case 4:return!!t.setWinSizePixels;case 5:return!!t.raiseWin;case 6:return!!t.lowerWin;case 7:return!!t.refreshWin;case 8:return!!t.setWinSizeChars;case 9:return!!t.maximizeWin;case 10:return!!t.fullscreenWin;case 11:return!!t.getWinState;case 13:return!!t.getWinPosition;case 14:return!!t.getWinSizePixels;case 15:return!!t.getScreenSizePixels;case 16:return!!t.getCellSizePixels;case 18:return!!t.getWinSizeChars;case 19:return!!t.getScreenSizeChars;case 20:return!!t.getIconTitle;case 21:return!!t.getWinTitle;case 22:return!!t.pushTitle;case 23:return!!t.popTitle;case 24:return!!t.setWinLines}return!1}var vl=5e3,gl=0,vn=class extends D{constructor(e,i,r,n,o,l,a,u,h=new bn){super();this._bufferService=e;this._charsetService=i;this._coreService=r;this._logService=n;this._optionsService=o;this._oscLinkService=l;this._coreMouseService=a;this._unicodeService=u;this._parser=h;this._parseBuffer=new Uint32Array(4096);this._stringDecoder=new er;this._utf8Decoder=new tr;this._windowTitle="";this._iconName="";this._windowTitleStack=[];this._iconNameStack=[];this._curAttrData=X.clone();this._eraseAttrDataInternal=X.clone();this._onRequestBell=this._register(new v);this.onRequestBell=this._onRequestBell.event;this._onRequestRefreshRows=this._register(new v);this.onRequestRefreshRows=this._onRequestRefreshRows.event;this._onRequestReset=this._register(new v);this.onRequestReset=this._onRequestReset.event;this._onRequestSendFocus=this._register(new v);this.onRequestSendFocus=this._onRequestSendFocus.event;this._onRequestSyncScrollBar=this._register(new v);this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event;this._onRequestWindowsOptionsReport=this._register(new v);this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event;this._onA11yChar=this._register(new v);this.onA11yChar=this._onA11yChar.event;this._onA11yTab=this._register(new v);this.onA11yTab=this._onA11yTab.event;this._onCursorMove=this._register(new v);this.onCursorMove=this._onCursorMove.event;this._onLineFeed=this._register(new v);this.onLineFeed=this._onLineFeed.event;this._onScroll=this._register(new v);this.onScroll=this._onScroll.event;this._onTitleChange=this._register(new v);this.onTitleChange=this._onTitleChange.event;this._onColor=this._register(new v);this.onColor=this._onColor.event;this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0};this._specialColors=[256,257,258];this._register(this._parser),this._dirtyRowTracker=new Zi(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(c=>this._activeBuffer=c.activeBuffer)),this._parser.setCsiHandlerFallback((c,d)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(c),params:d.toArray()})}),this._parser.setEscHandlerFallback(c=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(c)})}),this._parser.setExecuteHandlerFallback(c=>{this._logService.debug("Unknown EXECUTE code: ",{code:c})}),this._parser.setOscHandlerFallback((c,d,_)=>{this._logService.debug("Unknown OSC code: ",{identifier:c,action:d,data:_})}),this._parser.setDcsHandlerFallback((c,d,_)=>{d==="HOOK"&&(_=_.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(c),action:d,payload:_})}),this._parser.setPrintHandler((c,d,_)=>this.print(c,d,_)),this._parser.registerCsiHandler({final:"@"},c=>this.insertChars(c)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},c=>this.scrollLeft(c)),this._parser.registerCsiHandler({final:"A"},c=>this.cursorUp(c)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},c=>this.scrollRight(c)),this._parser.registerCsiHandler({final:"B"},c=>this.cursorDown(c)),this._parser.registerCsiHandler({final:"C"},c=>this.cursorForward(c)),this._parser.registerCsiHandler({final:"D"},c=>this.cursorBackward(c)),this._parser.registerCsiHandler({final:"E"},c=>this.cursorNextLine(c)),this._parser.registerCsiHandler({final:"F"},c=>this.cursorPrecedingLine(c)),this._parser.registerCsiHandler({final:"G"},c=>this.cursorCharAbsolute(c)),this._parser.registerCsiHandler({final:"H"},c=>this.cursorPosition(c)),this._parser.registerCsiHandler({final:"I"},c=>this.cursorForwardTab(c)),this._parser.registerCsiHandler({final:"J"},c=>this.eraseInDisplay(c,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},c=>this.eraseInDisplay(c,!0)),this._parser.registerCsiHandler({final:"K"},c=>this.eraseInLine(c,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},c=>this.eraseInLine(c,!0)),this._parser.registerCsiHandler({final:"L"},c=>this.insertLines(c)),this._parser.registerCsiHandler({final:"M"},c=>this.deleteLines(c)),this._parser.registerCsiHandler({final:"P"},c=>this.deleteChars(c)),this._parser.registerCsiHandler({final:"S"},c=>this.scrollUp(c)),this._parser.registerCsiHandler({final:"T"},c=>this.scrollDown(c)),this._parser.registerCsiHandler({final:"X"},c=>this.eraseChars(c)),this._parser.registerCsiHandler({final:"Z"},c=>this.cursorBackwardTab(c)),this._parser.registerCsiHandler({final:"`"},c=>this.charPosAbsolute(c)),this._parser.registerCsiHandler({final:"a"},c=>this.hPositionRelative(c)),this._parser.registerCsiHandler({final:"b"},c=>this.repeatPrecedingCharacter(c)),this._parser.registerCsiHandler({final:"c"},c=>this.sendDeviceAttributesPrimary(c)),this._parser.registerCsiHandler({prefix:">",final:"c"},c=>this.sendDeviceAttributesSecondary(c)),this._parser.registerCsiHandler({final:"d"},c=>this.linePosAbsolute(c)),this._parser.registerCsiHandler({final:"e"},c=>this.vPositionRelative(c)),this._parser.registerCsiHandler({final:"f"},c=>this.hVPosition(c)),this._parser.registerCsiHandler({final:"g"},c=>this.tabClear(c)),this._parser.registerCsiHandler({final:"h"},c=>this.setMode(c)),this._parser.registerCsiHandler({prefix:"?",final:"h"},c=>this.setModePrivate(c)),this._parser.registerCsiHandler({final:"l"},c=>this.resetMode(c)),this._parser.registerCsiHandler({prefix:"?",final:"l"},c=>this.resetModePrivate(c)),this._parser.registerCsiHandler({final:"m"},c=>this.charAttributes(c)),this._parser.registerCsiHandler({final:"n"},c=>this.deviceStatus(c)),this._parser.registerCsiHandler({prefix:"?",final:"n"},c=>this.deviceStatusPrivate(c)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},c=>this.softReset(c)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},c=>this.setCursorStyle(c)),this._parser.registerCsiHandler({final:"r"},c=>this.setScrollRegion(c)),this._parser.registerCsiHandler({final:"s"},c=>this.saveCursor(c)),this._parser.registerCsiHandler({final:"t"},c=>this.windowOptions(c)),this._parser.registerCsiHandler({final:"u"},c=>this.restoreCursor(c)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},c=>this.insertColumns(c)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},c=>this.deleteColumns(c)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},c=>this.selectProtected(c)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},c=>this.requestMode(c,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},c=>this.requestMode(c,!1)),this._parser.setExecuteHandler(b.BEL,()=>this.bell()),this._parser.setExecuteHandler(b.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(b.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(b.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(b.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(b.BS,()=>this.backspace()),this._parser.setExecuteHandler(b.HT,()=>this.tab()),this._parser.setExecuteHandler(b.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(b.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(Ai.IND,()=>this.index()),this._parser.setExecuteHandler(Ai.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(Ai.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new pe(c=>(this.setTitle(c),this.setIconName(c),!0))),this._parser.registerOscHandler(1,new pe(c=>this.setIconName(c))),this._parser.registerOscHandler(2,new pe(c=>this.setTitle(c))),this._parser.registerOscHandler(4,new pe(c=>this.setOrReportIndexedColor(c))),this._parser.registerOscHandler(8,new pe(c=>this.setHyperlink(c))),this._parser.registerOscHandler(10,new pe(c=>this.setOrReportFgColor(c))),this._parser.registerOscHandler(11,new pe(c=>this.setOrReportBgColor(c))),this._parser.registerOscHandler(12,new pe(c=>this.setOrReportCursorColor(c))),this._parser.registerOscHandler(104,new pe(c=>this.restoreIndexedColor(c))),this._parser.registerOscHandler(110,new pe(c=>this.restoreFgColor(c))),this._parser.registerOscHandler(111,new pe(c=>this.restoreBgColor(c))),this._parser.registerOscHandler(112,new pe(c=>this.restoreCursorColor(c))),this._parser.registerEscHandler({final:"7"},()=>this.saveCursor()),this._parser.registerEscHandler({final:"8"},()=>this.restoreCursor()),this._parser.registerEscHandler({final:"D"},()=>this.index()),this._parser.registerEscHandler({final:"E"},()=>this.nextLine()),this._parser.registerEscHandler({final:"H"},()=>this.tabSet()),this._parser.registerEscHandler({final:"M"},()=>this.reverseIndex()),this._parser.registerEscHandler({final:"="},()=>this.keypadApplicationMode()),this._parser.registerEscHandler({final:">"},()=>this.keypadNumericMode()),this._parser.registerEscHandler({final:"c"},()=>this.fullReset()),this._parser.registerEscHandler({final:"n"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"o"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"|"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"}"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"~"},()=>this.setgLevel(1)),this._parser.registerEscHandler({intermediates:"%",final:"@"},()=>this.selectDefaultCharset()),this._parser.registerEscHandler({intermediates:"%",final:"G"},()=>this.selectDefaultCharset());for(let c in ne)this._parser.registerEscHandler({intermediates:"(",final:c},()=>this.selectCharset("("+c)),this._parser.registerEscHandler({intermediates:")",final:c},()=>this.selectCharset(")"+c)),this._parser.registerEscHandler({intermediates:"*",final:c},()=>this.selectCharset("*"+c)),this._parser.registerEscHandler({intermediates:"+",final:c},()=>this.selectCharset("+"+c)),this._parser.registerEscHandler({intermediates:"-",final:c},()=>this.selectCharset("-"+c)),this._parser.registerEscHandler({intermediates:".",final:c},()=>this.selectCharset("."+c)),this._parser.registerEscHandler({intermediates:"/",final:c},()=>this.selectCharset("/"+c));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(c=>(this._logService.error("Parsing error: ",c),c)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new Xi((c,d)=>this.requestStatusString(c,d)))}getAttrData(){return this._curAttrData}_preserveStack(e,i,r,n){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=i,this._parseStack.decodedLength=r,this._parseStack.position=n}_logSlowResolvingAsync(e){this._logService.logLevel<=3&&Promise.race([e,new Promise((i,r)=>setTimeout(()=>r("#SLOW_TIMEOUT"),vl))]).catch(i=>{if(i!=="#SLOW_TIMEOUT")throw i;console.warn(`async parser handler taking longer than ${vl} ms`)})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,i){let r,n=this._activeBuffer.x,o=this._activeBuffer.y,l=0,a=this._parseStack.paused;if(a){if(r=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,i))return this._logSlowResolvingAsync(r),r;n=this._parseStack.cursorStartX,o=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>ut&&(l=this._parseStack.position+ut)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e=="string"?` "${e}"`:` "${Array.prototype.map.call(e,c=>String.fromCharCode(c)).join("")}"`}`),this._logService.logLevel===0&&this._logService.trace("parsing data (codes)",typeof e=="string"?e.split("").map(c=>c.charCodeAt(0)):e),this._parseBuffer.lengthut)for(let c=l;c0&&_.getWidth(this._activeBuffer.x-1)===2&&_.setCellFromCodepoint(this._activeBuffer.x-1,0,1,d);let p=this._parser.precedingJoinState;for(let m=i;mu){if(h){let O=_,I=this._activeBuffer.x-R;for(this._activeBuffer.x=R,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),_=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),R>0&&_ instanceof Ze&&_.copyCellsFrom(O,I,0,R,!1);I=0;)_.setCellFromCodepoint(this._activeBuffer.x++,0,0,d);continue}if(c&&(_.insertCells(this._activeBuffer.x,o-R,this._activeBuffer.getNullCell(d)),_.getWidth(u-1)===2&&_.setCellFromCodepoint(u-1,0,1,d)),_.setCellFromCodepoint(this._activeBuffer.x++,n,o,d),o>0)for(;--o;)_.setCellFromCodepoint(this._activeBuffer.x++,0,0,d)}this._parser.precedingJoinState=p,this._activeBuffer.x0&&_.getWidth(this._activeBuffer.x)===0&&!_.hasContent(this._activeBuffer.x)&&_.setCellFromCodepoint(this._activeBuffer.x,0,1,d),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,i){return e.final==="t"&&!e.prefix&&!e.intermediates?this._parser.registerCsiHandler(e,r=>bl(r.params[0],this._optionsService.rawOptions.windowOptions)?i(r):!0):this._parser.registerCsiHandler(e,i)}registerDcsHandler(e,i){return this._parser.registerDcsHandler(e,new Xi(i))}registerEscHandler(e,i){return this._parser.registerEscHandler(e,i)}registerOscHandler(e,i){return this._parser.registerOscHandler(e,new pe(i))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)?.isWrapped){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);e.hasWidth(this._activeBuffer.x)&&!e.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e,i){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+i):(this._activeBuffer.x=e,this._activeBuffer.y=i),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,i){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+i)}cursorUp(e){let i=this._activeBuffer.y-this._activeBuffer.scrollTop;return i>=0?this._moveCursor(0,-Math.min(i,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){let i=this._activeBuffer.scrollBottom-this._activeBuffer.y;return i>=0?this._moveCursor(0,Math.min(i,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){let i=e.params[0];return i===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:i===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let i=e.params[0]||1;for(;i--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let i=e.params[0]||1;for(;i--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){let i=e.params[0];return i===1&&(this._curAttrData.bg|=536870912),(i===2||i===0)&&(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,i,r,n=!1,o=!1){let l=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);l.replaceCells(i,r,this._activeBuffer.getNullCell(this._eraseAttrData()),o),n&&(l.isWrapped=!1)}_resetBufferLine(e,i=!1){let r=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);r&&(r.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),i),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),r.isWrapped=!1)}eraseInDisplay(e,i=!1){this._restrictCursor(this._bufferService.cols);let r;switch(e.params[0]){case 0:for(r=this._activeBuffer.y,this._dirtyRowTracker.markDirty(r),this._eraseInBufferLine(r++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,i);r=this._bufferService.cols&&(this._activeBuffer.lines.get(r+1).isWrapped=!1);r--;)this._resetBufferLine(r,i);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(r=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,r-1);r--&&!this._activeBuffer.lines.get(this._activeBuffer.ybase+r)?.getTrimmedLength(););for(;r>=0;r--)this._bufferService.scroll(this._eraseAttrData())}else{for(r=this._bufferService.rows,this._dirtyRowTracker.markDirty(r-1);r--;)this._resetBufferLine(r,i);this._dirtyRowTracker.markDirty(0)}break;case 3:let n=this._activeBuffer.lines.length-this._bufferService.rows;n>0&&(this._activeBuffer.lines.trimStart(n),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-n,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-n,0),this._onScroll.fire(0));break}return!0}eraseInLine(e,i=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,i);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,i);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,i);break}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let i=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.y65535?2:1}let c=h;for(let d=1;d0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(b.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(b.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(b.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(b.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(e.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(b.ESC+"[>83;40003;0c")),!0}_is(e){return(this._optionsService.rawOptions.termName+"").indexOf(e)===0}setMode(e){for(let i=0;i(P[P.NOT_RECOGNIZED=0]="NOT_RECOGNIZED",P[P.SET=1]="SET",P[P.RESET=2]="RESET",P[P.PERMANENTLY_SET=3]="PERMANENTLY_SET",P[P.PERMANENTLY_RESET=4]="PERMANENTLY_RESET"))(r||={});let n=this._coreService.decPrivateModes,{activeProtocol:o,activeEncoding:l}=this._coreMouseService,a=this._coreService,{buffers:u,cols:h}=this._bufferService,{active:c,alt:d}=u,_=this._optionsService.rawOptions,p=(A,R)=>(a.triggerDataEvent(`${b.ESC}[${i?"":"?"}${A};${R}$y`),!0),m=A=>A?1:2,f=e.params[0];return i?f===2?p(f,4):f===4?p(f,m(a.modes.insertMode)):f===12?p(f,3):f===20?p(f,m(_.convertEol)):p(f,0):f===1?p(f,m(n.applicationCursorKeys)):f===3?p(f,_.windowOptions.setWinLines?h===80?2:h===132?1:0:0):f===6?p(f,m(n.origin)):f===7?p(f,m(n.wraparound)):f===8?p(f,3):f===9?p(f,m(o==="X10")):f===12?p(f,m(_.cursorBlink)):f===25?p(f,m(!a.isCursorHidden)):f===45?p(f,m(n.reverseWraparound)):f===66?p(f,m(n.applicationKeypad)):f===67?p(f,4):f===1e3?p(f,m(o==="VT200")):f===1002?p(f,m(o==="DRAG")):f===1003?p(f,m(o==="ANY")):f===1004?p(f,m(n.sendFocus)):f===1005?p(f,4):f===1006?p(f,m(l==="SGR")):f===1015?p(f,4):f===1016?p(f,m(l==="SGR_PIXELS")):f===1048?p(f,1):f===47||f===1047||f===1049?p(f,m(c===d)):f===2004?p(f,m(n.bracketedPasteMode)):f===2026?p(f,m(n.synchronizedOutput)):p(f,0)}_updateAttrColor(e,i,r,n,o){return i===2?(e|=50331648,e&=-16777216,e|=De.fromColorRGB([r,n,o])):i===5&&(e&=-50331904,e|=33554432|r&255),e}_extractColor(e,i,r){let n=[0,0,-1,0,0,0],o=0,l=0;do{if(n[l+o]=e.params[i+l],e.hasSubParams(i+l)){let a=e.getSubParams(i+l),u=0;do n[1]===5&&(o=1),n[l+u+1+o]=a[u];while(++u=2||n[1]===2&&l+o>=5)break;n[1]&&(o=1)}while(++l+i5)&&(e=1),i.extended.underlineStyle=e,i.fg|=268435456,e===0&&(i.fg&=-268435457),i.updateExtended()}_processSGR0(e){e.fg=X.fg,e.bg=X.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-67108864,e.updateExtended()}charAttributes(e){if(e.length===1&&e.params[0]===0)return this._processSGR0(this._curAttrData),!0;let i=e.length,r,n=this._curAttrData;for(let o=0;o=30&&r<=37?(n.fg&=-50331904,n.fg|=16777216|r-30):r>=40&&r<=47?(n.bg&=-50331904,n.bg|=16777216|r-40):r>=90&&r<=97?(n.fg&=-50331904,n.fg|=16777216|r-90|8):r>=100&&r<=107?(n.bg&=-50331904,n.bg|=16777216|r-100|8):r===0?this._processSGR0(n):r===1?n.fg|=134217728:r===3?n.bg|=67108864:r===4?(n.fg|=268435456,this._processUnderline(e.hasSubParams(o)?e.getSubParams(o)[0]:1,n)):r===5?n.fg|=536870912:r===7?n.fg|=67108864:r===8?n.fg|=1073741824:r===9?n.fg|=2147483648:r===2?n.bg|=134217728:r===21?this._processUnderline(2,n):r===22?(n.fg&=-134217729,n.bg&=-134217729):r===23?n.bg&=-67108865:r===24?(n.fg&=-268435457,this._processUnderline(0,n)):r===25?n.fg&=-536870913:r===27?n.fg&=-67108865:r===28?n.fg&=-1073741825:r===29?n.fg&=2147483647:r===39?(n.fg&=-67108864,n.fg|=X.fg&16777215):r===49?(n.bg&=-67108864,n.bg|=X.bg&16777215):r===38||r===48||r===58?o+=this._extractColor(e,o,n):r===53?n.bg|=1073741824:r===55?n.bg&=-1073741825:r===59?(n.extended=n.extended.clone(),n.extended.underlineColor=-1,n.updateExtended()):r===100?(n.fg&=-67108864,n.fg|=X.fg&16777215,n.bg&=-67108864,n.bg|=X.bg&16777215):this._logService.debug("Unknown SGR attribute: %d.",r);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${b.ESC}[0n`);break;case 6:let i=this._activeBuffer.y+1,r=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${b.ESC}[${i};${r}R`);break}return!0}deviceStatusPrivate(e){switch(e.params[0]){case 6:let i=this._activeBuffer.y+1,r=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${b.ESC}[?${i};${r}R`);break;case 15:break;case 25:break;case 26:break;case 53:break}return!0}softReset(e){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=X.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){let i=e.length===0?1:e.params[0];if(i===0)this._coreService.decPrivateModes.cursorStyle=void 0,this._coreService.decPrivateModes.cursorBlink=void 0;else{switch(i){case 1:case 2:this._coreService.decPrivateModes.cursorStyle="block";break;case 3:case 4:this._coreService.decPrivateModes.cursorStyle="underline";break;case 5:case 6:this._coreService.decPrivateModes.cursorStyle="bar";break}let r=i%2===1;this._coreService.decPrivateModes.cursorBlink=r}return!0}setScrollRegion(e){let i=e.params[0]||1,r;return(e.length<2||(r=e.params[1])>this._bufferService.rows||r===0)&&(r=this._bufferService.rows),r>i&&(this._activeBuffer.scrollTop=i-1,this._activeBuffer.scrollBottom=r-1,this._setCursor(0,0)),!0}windowOptions(e){if(!bl(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;let i=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:i!==2&&this._onRequestWindowsOptionsReport.fire(0);break;case 16:this._onRequestWindowsOptionsReport.fire(1);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${b.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(i===0||i===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>_l&&this._windowTitleStack.shift()),(i===0||i===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>_l&&this._iconNameStack.shift());break;case 23:(i===0||i===2)&&this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),(i===0||i===1)&&this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop());break}return!0}saveCursor(e){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){let i=[],r=e.split(";");for(;r.length>1;){let n=r.shift(),o=r.shift();if(/^\d+$/.exec(n)){let l=parseInt(n);if(Sl(l))if(o==="?")i.push({type:0,index:l});else{let a=Ws(o);a&&i.push({type:1,index:l,color:a})}}}return i.length&&this._onColor.fire(i),!0}setHyperlink(e){let i=e.indexOf(";");if(i===-1)return!0;let r=e.slice(0,i).trim(),n=e.slice(i+1);return n?this._createHyperlink(r,n):r.trim()?!1:this._finishHyperlink()}_createHyperlink(e,i){this._getCurrentLinkId()&&this._finishHyperlink();let r=e.split(":"),n,o=r.findIndex(l=>l.startsWith("id="));return o!==-1&&(n=r[o].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:n,uri:i}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,i){let r=e.split(";");for(let n=0;n=this._specialColors.length);++n,++i)if(r[n]==="?")this._onColor.fire([{type:0,index:this._specialColors[i]}]);else{let o=Ws(r[n]);o&&this._onColor.fire([{type:1,index:this._specialColors[i],color:o}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;let i=[],r=e.split(";");for(let n=0;n=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=X.clone(),this._eraseAttrDataInternal=X.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=this._curAttrData.bg&67108863,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){let e=new q;e.content=1<<22|69,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let i=0;i(this._coreService.triggerDataEvent(`${b.ESC}${a}${b.ESC}\\`),!0),n=this._bufferService.buffer,o=this._optionsService.rawOptions,l={block:2,underline:4,bar:6};return r(e==='"q'?`P1$r${this._curAttrData.isProtected()?1:0}"q`:e==='"p'?'P1$r61;1"p':e==="r"?`P1$r${n.scrollTop+1};${n.scrollBottom+1}r`:e==="m"?"P1$r0m":e===" q"?`P1$r${l[o.cursorStyle]-(o.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(e,i){this._dirtyRowTracker.markRangeDirty(e,i)}},Zi=class{constructor(t){this._bufferService=t;this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(t){tthis.end&&(this.end=t)}markRangeDirty(t,e){t>e&&(gl=t,t=e,e=gl),tthis.end&&(this.end=e)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};Zi=M([S(0,F)],Zi);function Sl(s){return 0<=s&&s<256}var _c=5e7,El=12,bc=50,gn=class extends D{constructor(e){super();this._action=e;this._writeBuffer=[];this._callbacks=[];this._pendingData=0;this._bufferOffset=0;this._isSyncWriting=!1;this._syncCalls=0;this._didUserInput=!1;this._onWriteParsed=this._register(new v);this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(e,i){if(i!==void 0&&this._syncCalls>i){this._syncCalls=0;return}if(this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;this._isSyncWriting=!0;let r;for(;r=this._writeBuffer.shift();){this._action(r);let n=this._callbacks.shift();n&&n()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,i){if(this._pendingData>_c)throw new Error("write data discarded, use flow control to avoid losing data");if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput){this._didUserInput=!1,this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(i),this._innerWrite();return}setTimeout(()=>this._innerWrite())}this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(i)}_innerWrite(e=0,i=!0){let r=e||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let n=this._writeBuffer[this._bufferOffset],o=this._action(n,i);if(o){let a=u=>performance.now()-r>=El?setTimeout(()=>this._innerWrite(0,u)):this._innerWrite(r,u);o.catch(u=>(queueMicrotask(()=>{throw u}),Promise.resolve(!1))).then(a);return}let l=this._callbacks[this._bufferOffset];if(l&&l(),this._bufferOffset++,this._pendingData-=n.length,performance.now()-r>=El)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>bc&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout(()=>this._innerWrite())):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}};var ui=class{constructor(t){this._bufferService=t;this._nextId=1;this._entriesWithId=new Map;this._dataByLinkId=new Map}registerLink(t){let e=this._bufferService.buffer;if(t.id===void 0){let a=e.addMarker(e.ybase+e.y),u={data:t,id:this._nextId++,lines:[a]};return a.onDispose(()=>this._removeMarkerFromLink(u,a)),this._dataByLinkId.set(u.id,u),u.id}let i=t,r=this._getEntryIdKey(i),n=this._entriesWithId.get(r);if(n)return this.addLineToLink(n.id,e.ybase+e.y),n.id;let o=e.addMarker(e.ybase+e.y),l={id:this._nextId++,key:this._getEntryIdKey(i),data:i,lines:[o]};return o.onDispose(()=>this._removeMarkerFromLink(l,o)),this._entriesWithId.set(l.key,l),this._dataByLinkId.set(l.id,l),l.id}addLineToLink(t,e){let i=this._dataByLinkId.get(t);if(i&&i.lines.every(r=>r.line!==e)){let r=this._bufferService.buffer.addMarker(e);i.lines.push(r),r.onDispose(()=>this._removeMarkerFromLink(i,r))}}getLinkData(t){return this._dataByLinkId.get(t)?.data}_getEntryIdKey(t){return`${t.id};;${t.uri}`}_removeMarkerFromLink(t,e){let i=t.lines.indexOf(e);i!==-1&&(t.lines.splice(i,1),t.lines.length===0&&(t.data.id!==void 0&&this._entriesWithId.delete(t.key),this._dataByLinkId.delete(t.id)))}};ui=M([S(0,F)],ui);var Tl=!1,Sn=class extends D{constructor(e){super();this._windowsWrappingHeuristics=this._register(new ye);this._onBinary=this._register(new v);this.onBinary=this._onBinary.event;this._onData=this._register(new v);this.onData=this._onData.event;this._onLineFeed=this._register(new v);this.onLineFeed=this._onLineFeed.event;this._onResize=this._register(new v);this.onResize=this._onResize.event;this._onWriteParsed=this._register(new v);this.onWriteParsed=this._onWriteParsed.event;this._onScroll=this._register(new v);this._instantiationService=new ln,this.optionsService=this._register(new dn(e)),this._instantiationService.setService(H,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(ni)),this._instantiationService.setService(F,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(ii)),this._instantiationService.setService(nr,this._logService),this.coreService=this._register(this._instantiationService.createInstance(li)),this._instantiationService.setService(ge,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(ai)),this._instantiationService.setService(rr,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(Ae)),this._instantiationService.setService(Js,this.unicodeService),this._charsetService=this._instantiationService.createInstance(pn),this._instantiationService.setService(Zs,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(ui),this._instantiationService.setService(sr,this._oscLinkService),this._inputHandler=this._register(new vn(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register($.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register($.forward(this._bufferService.onResize,this._onResize)),this._register($.forward(this.coreService.onData,this._onData)),this._register($.forward(this.coreService.onBinary,this._onBinary)),this._register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom(!0))),this._register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this._register(this.optionsService.onMultipleOptionChange(["windowsMode","windowsPty"],()=>this._handleWindowsPtyOptionChange())),this._register(this._bufferService.onScroll(()=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this._register(new gn((i,r)=>this._inputHandler.parse(i,r))),this._register($.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new v),this._onScroll.event(e=>{this._onScrollApi?.fire(e.position)})),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(e){for(let i in e)this.optionsService.options[i]=e[i]}write(e,i){this._writeBuffer.write(e,i)}writeSync(e,i){this._logService.logLevel<=3&&!Tl&&(this._logService.warn("writeSync is unreliable and will be removed soon."),Tl=!0),this._writeBuffer.writeSync(e,i)}input(e,i=!0){this.coreService.triggerDataEvent(e,i)}resize(e,i){isNaN(e)||isNaN(i)||(e=Math.max(e,ks),i=Math.max(i,Cs),this._bufferService.resize(e,i))}scroll(e,i=!1){this._bufferService.scroll(e,i)}scrollLines(e,i){this._bufferService.scrollLines(e,i)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let i=e-this._bufferService.buffer.ydisp;i!==0&&this.scrollLines(i)}registerEscHandler(e,i){return this._inputHandler.registerEscHandler(e,i)}registerDcsHandler(e,i){return this._inputHandler.registerDcsHandler(e,i)}registerCsiHandler(e,i){return this._inputHandler.registerCsiHandler(e,i)}registerOscHandler(e,i){return this._inputHandler.registerOscHandler(e,i)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1,i=this.optionsService.rawOptions.windowsPty;i&&i.buildNumber!==void 0&&i.buildNumber!==void 0?e=i.backend==="conpty"&&i.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(e=!0),e?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let e=[];e.push(this.onLineFeed(Bs.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:"H"},()=>(Bs(this._bufferService),!1))),this._windowsWrappingHeuristics.value=C(()=>{for(let i of e)i.dispose()})}}};var gc={48:["0",")"],49:["1","!"],50:["2","@"],51:["3","#"],52:["4","$"],53:["5","%"],54:["6","^"],55:["7","&"],56:["8","*"],57:["9","("],186:[";",":"],187:["=","+"],188:[",","<"],189:["-","_"],190:[".",">"],191:["/","?"],192:["`","~"],219:["[","{"],220:["\\","|"],221:["]","}"],222:["'",'"']};function Il(s,t,e,i){let r={type:0,cancel:!1,key:void 0},n=(s.shiftKey?1:0)|(s.altKey?2:0)|(s.ctrlKey?4:0)|(s.metaKey?8:0);switch(s.keyCode){case 0:s.key==="UIKeyInputUpArrow"?t?r.key=b.ESC+"OA":r.key=b.ESC+"[A":s.key==="UIKeyInputLeftArrow"?t?r.key=b.ESC+"OD":r.key=b.ESC+"[D":s.key==="UIKeyInputRightArrow"?t?r.key=b.ESC+"OC":r.key=b.ESC+"[C":s.key==="UIKeyInputDownArrow"&&(t?r.key=b.ESC+"OB":r.key=b.ESC+"[B");break;case 8:r.key=s.ctrlKey?"\b":b.DEL,s.altKey&&(r.key=b.ESC+r.key);break;case 9:if(s.shiftKey){r.key=b.ESC+"[Z";break}r.key=b.HT,r.cancel=!0;break;case 13:r.key=s.altKey?b.ESC+b.CR:b.CR,r.cancel=!0;break;case 27:r.key=b.ESC,s.altKey&&(r.key=b.ESC+b.ESC),r.cancel=!0;break;case 37:if(s.metaKey)break;n?r.key=b.ESC+"[1;"+(n+1)+"D":t?r.key=b.ESC+"OD":r.key=b.ESC+"[D";break;case 39:if(s.metaKey)break;n?r.key=b.ESC+"[1;"+(n+1)+"C":t?r.key=b.ESC+"OC":r.key=b.ESC+"[C";break;case 38:if(s.metaKey)break;n?r.key=b.ESC+"[1;"+(n+1)+"A":t?r.key=b.ESC+"OA":r.key=b.ESC+"[A";break;case 40:if(s.metaKey)break;n?r.key=b.ESC+"[1;"+(n+1)+"B":t?r.key=b.ESC+"OB":r.key=b.ESC+"[B";break;case 45:!s.shiftKey&&!s.ctrlKey&&(r.key=b.ESC+"[2~");break;case 46:n?r.key=b.ESC+"[3;"+(n+1)+"~":r.key=b.ESC+"[3~";break;case 36:n?r.key=b.ESC+"[1;"+(n+1)+"H":t?r.key=b.ESC+"OH":r.key=b.ESC+"[H";break;case 35:n?r.key=b.ESC+"[1;"+(n+1)+"F":t?r.key=b.ESC+"OF":r.key=b.ESC+"[F";break;case 33:s.shiftKey?r.type=2:s.ctrlKey?r.key=b.ESC+"[5;"+(n+1)+"~":r.key=b.ESC+"[5~";break;case 34:s.shiftKey?r.type=3:s.ctrlKey?r.key=b.ESC+"[6;"+(n+1)+"~":r.key=b.ESC+"[6~";break;case 112:n?r.key=b.ESC+"[1;"+(n+1)+"P":r.key=b.ESC+"OP";break;case 113:n?r.key=b.ESC+"[1;"+(n+1)+"Q":r.key=b.ESC+"OQ";break;case 114:n?r.key=b.ESC+"[1;"+(n+1)+"R":r.key=b.ESC+"OR";break;case 115:n?r.key=b.ESC+"[1;"+(n+1)+"S":r.key=b.ESC+"OS";break;case 116:n?r.key=b.ESC+"[15;"+(n+1)+"~":r.key=b.ESC+"[15~";break;case 117:n?r.key=b.ESC+"[17;"+(n+1)+"~":r.key=b.ESC+"[17~";break;case 118:n?r.key=b.ESC+"[18;"+(n+1)+"~":r.key=b.ESC+"[18~";break;case 119:n?r.key=b.ESC+"[19;"+(n+1)+"~":r.key=b.ESC+"[19~";break;case 120:n?r.key=b.ESC+"[20;"+(n+1)+"~":r.key=b.ESC+"[20~";break;case 121:n?r.key=b.ESC+"[21;"+(n+1)+"~":r.key=b.ESC+"[21~";break;case 122:n?r.key=b.ESC+"[23;"+(n+1)+"~":r.key=b.ESC+"[23~";break;case 123:n?r.key=b.ESC+"[24;"+(n+1)+"~":r.key=b.ESC+"[24~";break;default:if(s.ctrlKey&&!s.shiftKey&&!s.altKey&&!s.metaKey)s.keyCode>=65&&s.keyCode<=90?r.key=String.fromCharCode(s.keyCode-64):s.keyCode===32?r.key=b.NUL:s.keyCode>=51&&s.keyCode<=55?r.key=String.fromCharCode(s.keyCode-51+27):s.keyCode===56?r.key=b.DEL:s.keyCode===219?r.key=b.ESC:s.keyCode===220?r.key=b.FS:s.keyCode===221&&(r.key=b.GS);else if((!e||i)&&s.altKey&&!s.metaKey){let l=gc[s.keyCode]?.[s.shiftKey?1:0];if(l)r.key=b.ESC+l;else if(s.keyCode>=65&&s.keyCode<=90){let a=s.ctrlKey?s.keyCode-64:s.keyCode+32,u=String.fromCharCode(a);s.shiftKey&&(u=u.toUpperCase()),r.key=b.ESC+u}else if(s.keyCode===32)r.key=b.ESC+(s.ctrlKey?b.NUL:" ");else if(s.key==="Dead"&&s.code.startsWith("Key")){let a=s.code.slice(3,4);s.shiftKey||(a=a.toLowerCase()),r.key=b.ESC+a,r.cancel=!0}}else e&&!s.altKey&&!s.ctrlKey&&!s.shiftKey&&s.metaKey?s.keyCode===65&&(r.type=1):s.key&&!s.ctrlKey&&!s.altKey&&!s.metaKey&&s.keyCode>=48&&s.key.length===1?r.key=s.key:s.key&&s.ctrlKey&&(s.key==="_"&&(r.key=b.US),s.key==="@"&&(r.key=b.NUL));break}return r}var ee=0,En=class{constructor(t){this._getKey=t;this._array=[];this._insertedValues=[];this._flushInsertedTask=new Jt;this._isFlushingInserted=!1;this._deletedIndices=[];this._flushDeletedTask=new Jt;this._isFlushingDeleted=!1}clear(){this._array.length=0,this._insertedValues.length=0,this._flushInsertedTask.clear(),this._isFlushingInserted=!1,this._deletedIndices.length=0,this._flushDeletedTask.clear(),this._isFlushingDeleted=!1}insert(t){this._flushCleanupDeleted(),this._insertedValues.length===0&&this._flushInsertedTask.enqueue(()=>this._flushInserted()),this._insertedValues.push(t)}_flushInserted(){let t=this._insertedValues.sort((n,o)=>this._getKey(n)-this._getKey(o)),e=0,i=0,r=new Array(this._array.length+this._insertedValues.length);for(let n=0;n=this._array.length||this._getKey(t[e])<=this._getKey(this._array[i])?(r[n]=t[e],e++):r[n]=this._array[i++];this._array=r,this._insertedValues.length=0}_flushCleanupInserted(){!this._isFlushingInserted&&this._insertedValues.length>0&&this._flushInsertedTask.flush()}delete(t){if(this._flushCleanupInserted(),this._array.length===0)return!1;let e=this._getKey(t);if(e===void 0||(ee=this._search(e),ee===-1)||this._getKey(this._array[ee])!==e)return!1;do if(this._array[ee]===t)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(ee),!0;while(++een-o),e=0,i=new Array(this._array.length-t.length),r=0;for(let n=0;n0&&this._flushDeletedTask.flush()}*getKeyIterator(t){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(ee=this._search(t),!(ee<0||ee>=this._array.length)&&this._getKey(this._array[ee])===t))do yield this._array[ee];while(++ee=this._array.length)&&this._getKey(this._array[ee])===t))do e(this._array[ee]);while(++ee=e;){let r=e+i>>1,n=this._getKey(this._array[r]);if(n>t)i=r-1;else if(n0&&this._getKey(this._array[r-1])===t;)r--;return r}}return e}};var Us=0,yl=0,Tn=class extends D{constructor(){super();this._decorations=new En(e=>e?.marker.line);this._onDecorationRegistered=this._register(new v);this.onDecorationRegistered=this._onDecorationRegistered.event;this._onDecorationRemoved=this._register(new v);this.onDecorationRemoved=this._onDecorationRemoved.event;this._register(C(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let i=new Ks(e);if(i){let r=i.marker.onDispose(()=>i.dispose()),n=i.onDispose(()=>{n.dispose(),i&&(this._decorations.delete(i)&&this._onDecorationRemoved.fire(i),r.dispose())});this._decorations.insert(i),this._onDecorationRegistered.fire(i)}return i}reset(){for(let e of this._decorations.values())e.dispose();this._decorations.clear()}*getDecorationsAtCell(e,i,r){let n=0,o=0;for(let l of this._decorations.getKeyIterator(i))n=l.options.x??0,o=n+(l.options.width??1),e>=n&&e{Us=o.options.x??0,yl=Us+(o.options.width??1),e>=Us&&e=this._debounceThresholdMS)this._lastRefreshMs=r,this._innerRefresh();else if(!this._additionalRefreshRequested){let n=r-this._lastRefreshMs,o=this._debounceThresholdMS-n;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},o)}}_innerRefresh(){if(this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return;let t=Math.max(this._rowStart,0),e=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(t,e)}};var xl=20;var wl=!1,Tt=class extends D{constructor(e,i,r,n){super();this._terminal=e;this._coreBrowserService=r;this._renderService=n;this._rowColumns=new WeakMap;this._liveRegionLineCount=0;this._charsToConsume=[];this._charsToAnnounce="";let o=this._coreBrowserService.mainDocument;this._accessibilityContainer=o.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=o.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let l=0;lthis._handleBoundaryFocus(l,0),this._bottomBoundaryFocusListener=l=>this._handleBoundaryFocus(l,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=o.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this._register(new In(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");wl?(this._accessibilityContainer.classList.add("debug"),this._rowContainer.classList.add("debug"),this._debugRootContainer=o.createElement("div"),this._debugRootContainer.classList.add("xterm"),this._debugRootContainer.appendChild(o.createTextNode("------start a11y------")),this._debugRootContainer.appendChild(this._accessibilityContainer),this._debugRootContainer.appendChild(o.createTextNode("------end a11y------")),this._terminal.element.insertAdjacentElement("afterend",this._debugRootContainer)):this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this._register(this._terminal.onResize(l=>this._handleResize(l.rows))),this._register(this._terminal.onRender(l=>this._refreshRows(l.start,l.end))),this._register(this._terminal.onScroll(()=>this._refreshRows())),this._register(this._terminal.onA11yChar(l=>this._handleChar(l))),this._register(this._terminal.onLineFeed(()=>this._handleChar(` +`))),this._register(this._terminal.onA11yTab(l=>this._handleTab(l))),this._register(this._terminal.onKey(l=>this._handleKey(l.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(L(o,"selectionchange",()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(C(()=>{wl?this._debugRootContainer.remove():this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let i=0;i0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===` +`&&(this._liveRegionLineCount++,this._liveRegionLineCount===xl+1&&(this._liveRegion.textContent+=_i.get())))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),/\p{Control}/u.test(e)||this._charsToConsume.push(e)}_refreshRows(e,i){this._liveRegionDebouncer.refresh(e,i,this._terminal.rows)}_renderRows(e,i){let r=this._terminal.buffer,n=r.lines.length.toString();for(let o=e;o<=i;o++){let l=r.lines.get(r.ydisp+o),a=[],u=l?.translateToString(!0,void 0,void 0,a)||"",h=(r.ydisp+o+1).toString(),c=this._rowElements[o];c&&(u.length===0?(c.textContent="\xA0",this._rowColumns.set(c,[0,1])):(c.textContent=u,this._rowColumns.set(c,a)),c.setAttribute("aria-posinset",h),c.setAttribute("aria-setsize",n),this._alignRowWidth(c))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(e,i){let r=e.target,n=this._rowElements[i===0?1:this._rowElements.length-2],o=r.getAttribute("aria-posinset"),l=i===0?"1":`${this._terminal.buffer.lines.length}`;if(o===l||e.relatedTarget!==n)return;let a,u;if(i===0?(a=r,u=this._rowElements.pop(),this._rowContainer.removeChild(u)):(a=this._rowElements.shift(),u=r,this._rowContainer.removeChild(a)),a.removeEventListener("focus",this._topBoundaryFocusListener),u.removeEventListener("focus",this._bottomBoundaryFocusListener),i===0){let h=this._createAccessibilityTreeNode();this._rowElements.unshift(h),this._rowContainer.insertAdjacentElement("afterbegin",h)}else{let h=this._createAccessibilityTreeNode();this._rowElements.push(h),this._rowContainer.appendChild(h)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(i===0?-1:1),this._rowElements[i===0?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleSelectionChange(){if(this._rowElements.length===0)return;let e=this._coreBrowserService.mainDocument.getSelection();if(!e)return;if(e.isCollapsed){this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection();return}if(!e.anchorNode||!e.focusNode){console.error("anchorNode and/or focusNode are null");return}let i={node:e.anchorNode,offset:e.anchorOffset},r={node:e.focusNode,offset:e.focusOffset};if((i.node.compareDocumentPosition(r.node)&Node.DOCUMENT_POSITION_PRECEDING||i.node===r.node&&i.offset>r.offset)&&([i,r]=[r,i]),i.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(i={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(i.node))return;let n=this._rowElements.slice(-1)[0];if(r.node.compareDocumentPosition(n)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(r={node:n,offset:n.textContent?.length??0}),!this._rowContainer.contains(r.node))return;let o=({node:u,offset:h})=>{let c=u instanceof Text?u.parentNode:u,d=parseInt(c?.getAttribute("aria-posinset"),10)-1;if(isNaN(d))return console.warn("row is invalid. Race condition?"),null;let _=this._rowColumns.get(c);if(!_)return console.warn("columns is null. Race condition?"),null;let p=h<_.length?_[h]:_.slice(-1)[0]+1;return p>=this._terminal.cols&&(++d,p=0),{row:d,column:p}},l=o(i),a=o(r);if(!(!l||!a)){if(l.row>a.row||l.row===a.row&&l.column>=a.column)throw new Error("invalid range");this._terminal.select(l.column,l.row,(a.row-l.row)*this._terminal.cols-l.column+a.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let i=this._rowContainer.children.length;ie;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){let e=this._coreBrowserService.mainDocument.createElement("div");return e.setAttribute("role","listitem"),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e{Ne(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,this._activeProviderReplies?.clear()})),this._register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this._register(L(this._element,"mouseleave",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(L(this._element,"mousemove",this._handleMouseMove.bind(this))),this._register(L(this._element,"mousedown",this._handleMouseDown.bind(this))),this._register(L(this._element,"mouseup",this._handleMouseUp.bind(this)))}get currentLink(){return this._currentLink}_handleMouseMove(e){this._lastMouseEvent=e;let i=this._positionFromMouseEvent(e,this._element,this._mouseService);if(!i)return;this._isMouseOut=!1;let r=e.composedPath();for(let n=0;n{n?.forEach(o=>{o.link.dispose&&o.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=e.y);let r=!1;for(let[n,o]of this._linkProviderService.linkProviders.entries())i?this._activeProviderReplies?.get(n)&&(r=this._checkLinkProviderResult(n,e,r)):o.provideLinks(e.y,l=>{if(this._isMouseOut)return;let a=l?.map(u=>({link:u}));this._activeProviderReplies?.set(n,a),r=this._checkLinkProviderResult(n,e,r),this._activeProviderReplies?.size===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)})}_removeIntersectingLinks(e,i){let r=new Set;for(let n=0;ne?this._bufferService.cols:a.link.range.end.x;for(let c=u;c<=h;c++){if(r.has(c)){o.splice(l--,1);break}r.add(c)}}}}_checkLinkProviderResult(e,i,r){if(!this._activeProviderReplies)return r;let n=this._activeProviderReplies.get(e),o=!1;for(let l=0;lthis._linkAtPosition(a.link,i));l&&(r=!0,this._handleNewLink(l))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!r)for(let l=0;lthis._linkAtPosition(u.link,i));if(a){r=!0,this._handleNewLink(a);break}}return r}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;let i=this._positionFromMouseEvent(e,this._element,this._mouseService);i&&this._mouseDownLink&&Ec(this._mouseDownLink.link,this._currentLink.link)&&this._linkAtPosition(this._currentLink.link,i)&&this._currentLink.link.activate(e,this._currentLink.link.text)}_clearCurrentLink(e,i){!this._currentLink||!this._lastMouseEvent||(!e||!i||this._currentLink.link.range.start.y>=e&&this._currentLink.link.range.end.y<=i)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,Ne(this._linkCacheDisposables),this._linkCacheDisposables.length=0)}_handleNewLink(e){if(!this._lastMouseEvent)return;let i=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);i&&this._linkAtPosition(e.link,i)&&(this._currentLink=e,this._currentLink.state={decorations:{underline:e.link.decorations===void 0?!0:e.link.decorations.underline,pointerCursor:e.link.decorations===void 0?!0:e.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,e.link,this._lastMouseEvent),e.link.decorations={},Object.defineProperties(e.link.decorations,{pointerCursor:{get:()=>this._currentLink?.state?.decorations.pointerCursor,set:r=>{this._currentLink?.state&&this._currentLink.state.decorations.pointerCursor!==r&&(this._currentLink.state.decorations.pointerCursor=r,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",r))}},underline:{get:()=>this._currentLink?.state?.decorations.underline,set:r=>{this._currentLink?.state&&this._currentLink?.state?.decorations.underline!==r&&(this._currentLink.state.decorations.underline=r,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,r))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(r=>{if(!this._currentLink)return;let n=r.start===0?0:r.start+1+this._bufferService.buffer.ydisp,o=this._bufferService.buffer.ydisp+1+r.end;if(this._currentLink.link.range.start.y>=n&&this._currentLink.link.range.end.y<=o&&(this._clearCurrentLink(n,o),this._lastMouseEvent)){let l=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);l&&this._askForLink(l,!1)}})))}_linkHover(e,i,r){this._currentLink?.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(i,!0),this._currentLink.state.decorations.pointerCursor&&e.classList.add("xterm-cursor-pointer")),i.hover&&i.hover(r,i.text)}_fireUnderlineEvent(e,i){let r=e.range,n=this._bufferService.buffer.ydisp,o=this._createLinkUnderlineEvent(r.start.x-1,r.start.y-n-1,r.end.x,r.end.y-n-1,void 0);(i?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(o)}_linkLeave(e,i,r){this._currentLink?.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(i,!1),this._currentLink.state.decorations.pointerCursor&&e.classList.remove("xterm-cursor-pointer")),i.leave&&i.leave(r,i.text)}_linkAtPosition(e,i){let r=e.range.start.y*this._bufferService.cols+e.range.start.x,n=e.range.end.y*this._bufferService.cols+e.range.end.x,o=i.y*this._bufferService.cols+i.x;return r<=o&&o<=n}_positionFromMouseEvent(e,i,r){let n=r.getCoords(e,i,this._bufferService.cols,this._bufferService.rows);if(n)return{x:n[0],y:n[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,i,r,n,o){return{x1:e,y1:i,x2:r,y2:n,cols:this._bufferService.cols,fg:o}}};hi=M([S(1,Dt),S(2,ce),S(3,F),S(4,lr)],hi);function Ec(s,t){return s.text===t.text&&s.range.start.x===t.range.start.x&&s.range.start.y===t.range.start.y&&s.range.end.x===t.range.end.x&&s.range.end.y===t.range.end.y}var yn=class extends Sn{constructor(e={}){super(e);this._linkifier=this._register(new ye);this.browser=tn;this._keyDownHandled=!1;this._keyDownSeen=!1;this._keyPressHandled=!1;this._unprocessedDeadKey=!1;this._accessibilityManager=this._register(new ye);this._onCursorMove=this._register(new v);this.onCursorMove=this._onCursorMove.event;this._onKey=this._register(new v);this.onKey=this._onKey.event;this._onRender=this._register(new v);this.onRender=this._onRender.event;this._onSelectionChange=this._register(new v);this.onSelectionChange=this._onSelectionChange.event;this._onTitleChange=this._register(new v);this.onTitleChange=this._onTitleChange.event;this._onBell=this._register(new v);this.onBell=this._onBell.event;this._onFocus=this._register(new v);this._onBlur=this._register(new v);this._onA11yCharEmitter=this._register(new v);this._onA11yTabEmitter=this._register(new v);this._onWillOpen=this._register(new v);this._setup(),this._decorationService=this._instantiationService.createInstance(Tn),this._instantiationService.setService(Be,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(Qr),this._instantiationService.setService(lr,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(wt)),this._register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this._register(this._inputHandler.onRequestRefreshRows(i=>this.refresh(i?.start??0,i?.end??this.rows-1))),this._register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this._register(this._inputHandler.onRequestReset(()=>this.reset())),this._register(this._inputHandler.onRequestWindowsOptionsReport(i=>this._reportWindowsOptions(i))),this._register(this._inputHandler.onColor(i=>this._handleColorEvent(i))),this._register($.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register($.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register($.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register($.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(i=>this._afterResize(i.cols,i.rows))),this._register(C(()=>{this._customKeyEventHandler=void 0,this.element?.parentNode?.removeChild(this.element)}))}get linkifier(){return this._linkifier.value}get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}_handleColorEvent(e){if(this._themeService)for(let i of e){let r,n="";switch(i.index){case 256:r="foreground",n="10";break;case 257:r="background",n="11";break;case 258:r="cursor",n="12";break;default:r="ansi",n="4;"+i.index}switch(i.type){case 0:let o=U.toColorRGB(r==="ansi"?this._themeService.colors.ansi[i.index]:this._themeService.colors[r]);this.coreService.triggerDataEvent(`${b.ESC}]${n};${ml(o)}${fs.ST}`);break;case 1:if(r==="ansi")this._themeService.modifyColors(l=>l.ansi[i.index]=j.toColor(...i.color));else{let l=r;this._themeService.modifyColors(a=>a[l]=j.toColor(...i.color))}break;case 2:this._themeService.restoreColor(i.index);break}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(e){e?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(Tt,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(b.ESC+"[I"),this.element.classList.add("focus"),this._showCursor(),this._onFocus.fire()}blur(){return this.textarea?.blur()}_handleTextAreaBlur(){this.textarea.value="",this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(b.ESC+"[O"),this.element.classList.remove("focus"),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;let e=this.buffer.ybase+this.buffer.y,i=this.buffer.lines.get(e);if(!i)return;let r=Math.min(this.buffer.x,this.cols-1),n=this._renderService.dimensions.css.cell.height,o=i.getWidth(r),l=this._renderService.dimensions.css.cell.width*o,a=this.buffer.y*this._renderService.dimensions.css.cell.height,u=r*this._renderService.dimensions.css.cell.width;this.textarea.style.left=u+"px",this.textarea.style.top=a+"px",this.textarea.style.width=l+"px",this.textarea.style.height=n+"px",this.textarea.style.lineHeight=n+"px",this.textarea.style.zIndex="-5"}_initGlobal(){this._bindKeys(),this._register(L(this.element,"copy",i=>{this.hasSelection()&&Vs(i,this._selectionService)}));let e=i=>qs(i,this.textarea,this.coreService,this.optionsService);this._register(L(this.textarea,"paste",e)),this._register(L(this.element,"paste",e)),Ss?this._register(L(this.element,"mousedown",i=>{i.button===2&&Pn(i,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(L(this.element,"contextmenu",i=>{Pn(i,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),Bi&&this._register(L(this.element,"auxclick",i=>{i.button===1&&Mn(i,this.textarea,this.screenElement)}))}_bindKeys(){this._register(L(this.textarea,"keyup",e=>this._keyUp(e),!0)),this._register(L(this.textarea,"keydown",e=>this._keyDown(e),!0)),this._register(L(this.textarea,"keypress",e=>this._keyPress(e),!0)),this._register(L(this.textarea,"compositionstart",()=>this._compositionHelper.compositionstart())),this._register(L(this.textarea,"compositionupdate",e=>this._compositionHelper.compositionupdate(e))),this._register(L(this.textarea,"compositionend",()=>this._compositionHelper.compositionend())),this._register(L(this.textarea,"input",e=>this._inputEvent(e),!0)),this._register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(e){if(!e)throw new Error("Terminal requires a parent element.");if(e.isConnected||this._logService.debug("Terminal.open was called on an element that was not attached to the DOM"),this.element?.ownerDocument.defaultView&&this._coreBrowserService){this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView);return}this._document=e.ownerDocument,this.options.documentOverride&&this.options.documentOverride instanceof Document&&(this._document=this.optionsService.rawOptions.documentOverride),this.element=this._document.createElement("div"),this.element.dir="ltr",this.element.classList.add("terminal"),this.element.classList.add("xterm"),e.appendChild(this.element);let i=this._document.createDocumentFragment();this._viewportElement=this._document.createElement("div"),this._viewportElement.classList.add("xterm-viewport"),i.appendChild(this._viewportElement),this.screenElement=this._document.createElement("div"),this.screenElement.classList.add("xterm-screen"),this._register(L(this.screenElement,"mousemove",o=>this.updateCursorStyle(o))),this._helperContainer=this._document.createElement("div"),this._helperContainer.classList.add("xterm-helpers"),this.screenElement.appendChild(this._helperContainer),i.appendChild(this.screenElement);let r=this.textarea=this._document.createElement("textarea");this.textarea.classList.add("xterm-helper-textarea"),this.textarea.setAttribute("aria-label",mi.get()),Ts||this.textarea.setAttribute("aria-multiline","false"),this.textarea.setAttribute("autocorrect","off"),this.textarea.setAttribute("autocapitalize","off"),this.textarea.setAttribute("spellcheck","false"),this.textarea.tabIndex=0,this._register(this.optionsService.onSpecificOptionChange("disableStdin",()=>r.readOnly=this.optionsService.rawOptions.disableStdin)),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(Jr,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<"u"?window.document:null)),this._instantiationService.setService(ae,this._coreBrowserService),this._register(L(this.textarea,"focus",o=>this._handleTextAreaFocus(o))),this._register(L(this.textarea,"blur",()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(jt,this._document,this._helperContainer),this._instantiationService.setService(nt,this._charSizeService),this._themeService=this._instantiationService.createInstance(ti),this._instantiationService.setService(Re,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(ct),this._instantiationService.setService(or,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(Qt,this.rows,this.screenElement)),this._instantiationService.setService(ce,this._renderService),this._register(this._renderService.onRenderedViewportChange(o=>this._onRender.fire(o))),this.onResize(o=>this._renderService.resize(o.cols,o.rows)),this._compositionView=this._document.createElement("div"),this._compositionView.classList.add("composition-view"),this._compositionHelper=this._instantiationService.createInstance($t,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(Xt),this._instantiationService.setService(Dt,this._mouseService);let n=this._linkifier.value=this._register(this._instantiationService.createInstance(hi,this.screenElement));this.element.appendChild(i);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this._register(this.onCursorMove(()=>{this._renderService.handleCursorMove(),this._syncTextArea()})),this._register(this.onResize(()=>this._renderService.handleResize(this.cols,this.rows))),this._register(this.onBlur(()=>this._renderService.handleBlur())),this._register(this.onFocus(()=>this._renderService.handleFocus())),this._viewport=this._register(this._instantiationService.createInstance(zt,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines(o=>{super.scrollLines(o,!1),this.refresh(0,this.rows-1)})),this._selectionService=this._register(this._instantiationService.createInstance(ei,this.element,this.screenElement,n)),this._instantiationService.setService(Qs,this._selectionService),this._register(this._selectionService.onRequestScrollLines(o=>this.scrollLines(o.amount,o.suppressScrollEvent))),this._register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this._register(this._selectionService.onRequestRedraw(o=>this._renderService.handleSelectionChanged(o.start,o.end,o.columnSelectMode))),this._register(this._selectionService.onLinuxMouseSelection(o=>{this.textarea.value=o,this.textarea.focus(),this.textarea.select()})),this._register($.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{this._selectionService.refresh(),this._viewport?.queueSync()})),this._register(this._instantiationService.createInstance(Gt,this.screenElement)),this._register(L(this.element,"mousedown",o=>this._selectionService.handleMouseDown(o))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add("enable-mouse-events")):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(Tt,this)),this._register(this.optionsService.onSpecificOptionChange("screenReaderMode",o=>this._handleScreenReaderModeOptionChange(o))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(bt,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRuler",o=>{!this._overviewRulerRenderer&&o&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(bt,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(Yt,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,i=this.element;function r(l){let a=e._mouseService.getMouseReportCoords(l,e.screenElement);if(!a)return!1;let u,h;switch(l.overrideType||l.type){case"mousemove":h=32,l.buttons===void 0?(u=3,l.button!==void 0&&(u=l.button<3?l.button:3)):u=l.buttons&1?0:l.buttons&4?1:l.buttons&2?2:3;break;case"mouseup":h=0,u=l.button<3?l.button:3;break;case"mousedown":h=1,u=l.button<3?l.button:3;break;case"wheel":if(e._customWheelEventHandler&&e._customWheelEventHandler(l)===!1)return!1;let c=l.deltaY;if(c===0||e.coreMouseService.consumeWheelEvent(l,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return!1;h=c<0?0:1,u=4;break;default:return!1}return h===void 0||u===void 0||u>4?!1:e.coreMouseService.triggerMouseEvent({col:a.col,row:a.row,x:a.x,y:a.y,button:u,action:h,ctrl:l.ctrlKey,alt:l.altKey,shift:l.shiftKey})}let n={mouseup:null,wheel:null,mousedrag:null,mousemove:null},o={mouseup:l=>(r(l),l.buttons||(this._document.removeEventListener("mouseup",n.mouseup),n.mousedrag&&this._document.removeEventListener("mousemove",n.mousedrag)),this.cancel(l)),wheel:l=>(r(l),this.cancel(l,!0)),mousedrag:l=>{l.buttons&&r(l)},mousemove:l=>{l.buttons||r(l)}};this._register(this.coreMouseService.onProtocolChange(l=>{l?(this.optionsService.rawOptions.logLevel==="debug"&&this._logService.debug("Binding to mouse events:",this.coreMouseService.explainEvents(l)),this.element.classList.add("enable-mouse-events"),this._selectionService.disable()):(this._logService.debug("Unbinding from mouse events."),this.element.classList.remove("enable-mouse-events"),this._selectionService.enable()),l&8?n.mousemove||(i.addEventListener("mousemove",o.mousemove),n.mousemove=o.mousemove):(i.removeEventListener("mousemove",n.mousemove),n.mousemove=null),l&16?n.wheel||(i.addEventListener("wheel",o.wheel,{passive:!1}),n.wheel=o.wheel):(i.removeEventListener("wheel",n.wheel),n.wheel=null),l&2?n.mouseup||(n.mouseup=o.mouseup):(this._document.removeEventListener("mouseup",n.mouseup),n.mouseup=null),l&4?n.mousedrag||(n.mousedrag=o.mousedrag):(this._document.removeEventListener("mousemove",n.mousedrag),n.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(L(i,"mousedown",l=>{if(l.preventDefault(),this.focus(),!(!this.coreMouseService.areMouseEventsActive||this._selectionService.shouldForceSelection(l)))return r(l),n.mouseup&&this._document.addEventListener("mouseup",n.mouseup),n.mousedrag&&this._document.addEventListener("mousemove",n.mousedrag),this.cancel(l)})),this._register(L(i,"wheel",l=>{if(!n.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(l)===!1)return!1;if(!this.buffer.hasScrollback){if(l.deltaY===0)return!1;if(e.coreMouseService.consumeWheelEvent(l,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return this.cancel(l,!0);let h=b.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?"O":"[")+(l.deltaY<0?"A":"B");return this.coreService.triggerDataEvent(h,!0),this.cancel(l,!0)}}},{passive:!1}))}refresh(e,i){this._renderService?.refreshRows(e,i)}updateCursorStyle(e){this._selectionService?.shouldColumnSelect(e)?this.element.classList.add("column-select"):this.element.classList.remove("column-select")}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(e,i){this._viewport?this._viewport.scrollLines(e):super.scrollLines(e,i),this.refresh(0,this.rows-1)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){e&&this._viewport?this._viewport.scrollToLine(this.buffer.ybase,!0):this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let i=e-this._bufferService.buffer.ydisp;i!==0&&this.scrollLines(i)}paste(e){Cn(e,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(e){this._customKeyEventHandler=e}attachCustomWheelEventHandler(e){this._customWheelEventHandler=e}registerLinkProvider(e){return this._linkProviderService.registerLinkProvider(e)}registerCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");let i=this._characterJoinerService.register(e);return this.refresh(0,this.rows-1),i}deregisterCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");this._characterJoinerService.deregister(e)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(e){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+e)}registerDecoration(e){return this._decorationService.registerDecoration(e)}hasSelection(){return this._selectionService?this._selectionService.hasSelection:!1}select(e,i,r){this._selectionService.setSelection(e,i,r)}getSelection(){return this._selectionService?this._selectionService.selectionText:""}getSelectionPosition(){if(!(!this._selectionService||!this._selectionService.hasSelection))return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){this._selectionService?.clearSelection()}selectAll(){this._selectionService?.selectAll()}selectLines(e,i){this._selectionService?.selectLines(e,i)}_keyDown(e){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;let i=this.browser.isMac&&this.options.macOptionIsMeta&&e.altKey;if(!i&&!this._compositionHelper.keydown(e))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(!0),!1;!i&&(e.key==="Dead"||e.key==="AltGraph")&&(this._unprocessedDeadKey=!0);let r=Il(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),r.type===3||r.type===2){let n=this.rows-1;return this.scrollLines(r.type===2?-n:n),this.cancel(e,!0)}if(r.type===1&&this.selectAll(),this._isThirdLevelShift(this.browser,e)||(r.cancel&&this.cancel(e,!0),!r.key)||e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.key.length===1&&e.key.charCodeAt(0)>=65&&e.key.charCodeAt(0)<=90)return!0;if(this._unprocessedDeadKey)return this._unprocessedDeadKey=!1,!0;if((r.key===b.ETX||r.key===b.CR)&&(this.textarea.value=""),this._onKey.fire({key:r.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(r.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey)return this.cancel(e,!0);this._keyDownHandled=!0}_isThirdLevelShift(e,i){let r=e.isMac&&!this.options.macOptionIsMeta&&i.altKey&&!i.ctrlKey&&!i.metaKey||e.isWindows&&i.altKey&&i.ctrlKey&&!i.metaKey||e.isWindows&&i.getModifierState("AltGraph");return i.type==="keypress"?r:r&&(!i.keyCode||i.keyCode>47)}_keyUp(e){this._keyDownSeen=!1,!(this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)&&(Tc(e)||this.focus(),this.updateCursorStyle(e),this._keyPressHandled=!1)}_keyPress(e){let i;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;if(this.cancel(e),e.charCode)i=e.charCode;else if(e.which===null||e.which===void 0)i=e.keyCode;else if(e.which!==0&&e.charCode!==0)i=e.which;else return!1;return!i||(e.altKey||e.ctrlKey||e.metaKey)&&!this._isThirdLevelShift(this.browser,e)?!1:(i=String.fromCharCode(i),this._onKey.fire({key:i,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(i,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,!0)}_inputEvent(e){if(e.data&&e.inputType==="insertText"&&(!e.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;let i=e.data;return this.coreService.triggerDataEvent(i,!0),this.cancel(e),!0}return!1}resize(e,i){if(e===this.cols&&i===this.rows){this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure();return}super.resize(e,i)}_afterResize(e,i){this._charSizeService?.measure()}clear(){if(!(this.buffer.ybase===0&&this.buffer.y===0)){this.buffer.clearAllMarkers(),this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let e=1;e=0;t--)this._addons[t].instance.dispose()}loadAddon(t,e){let i={instance:e,dispose:e.dispose,isDisposed:!1};this._addons.push(i),e.dispose=()=>this._wrappedAddonDispose(i),e.activate(t)}_wrappedAddonDispose(t){if(t.isDisposed)return;let e=-1;for(let i=0;i=this._line.length))return e?(this._line.loadCell(t,e),e):this._line.loadCell(t,new q)}translateToString(t,e,i){return this._line.translateToString(t,e,i)}};var Ji=class{constructor(t,e){this._buffer=t;this.type=e}init(t){return this._buffer=t,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(t){let e=this._buffer.lines.get(t);if(e)return new wn(e)}getNullCell(){return new q}};var Dn=class extends D{constructor(e){super();this._core=e;this._onBufferChange=this._register(new v);this.onBufferChange=this._onBufferChange.event;this._normal=new Ji(this._core.buffers.normal,"normal"),this._alternate=new Ji(this._core.buffers.alt,"alternate"),this._core.buffers.onBufferActivate(()=>this._onBufferChange.fire(this.active))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw new Error("Active buffer is neither normal nor alternate")}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}};var Rn=class{constructor(t){this._core=t}registerCsiHandler(t,e){return this._core.registerCsiHandler(t,i=>e(i.toArray()))}addCsiHandler(t,e){return this.registerCsiHandler(t,e)}registerDcsHandler(t,e){return this._core.registerDcsHandler(t,(i,r)=>e(i,r.toArray()))}addDcsHandler(t,e){return this.registerDcsHandler(t,e)}registerEscHandler(t,e){return this._core.registerEscHandler(t,e)}addEscHandler(t,e){return this.registerEscHandler(t,e)}registerOscHandler(t,e){return this._core.registerOscHandler(t,e)}addOscHandler(t,e){return this.registerOscHandler(t,e)}};var Ln=class{constructor(t){this._core=t}register(t){this._core.unicodeService.register(t)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(t){this._core.unicodeService.activeVersion=t}};var Ic=["cols","rows"],Ue=0,Dl=class extends D{constructor(t){super(),this._core=this._register(new yn(t)),this._addonManager=this._register(new xn),this._publicOptions={...this._core.options};let e=r=>this._core.options[r],i=(r,n)=>{this._checkReadonlyOptions(r),this._core.options[r]=n};for(let r in this._core.options){let n={get:e.bind(this,r),set:i.bind(this,r)};Object.defineProperty(this._publicOptions,r,n)}}_checkReadonlyOptions(t){if(Ic.includes(t))throw new Error(`Option "${t}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw new Error("You must set the allowProposedApi option to true to use proposed API")}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onKey(){return this._core.onKey}get onLineFeed(){return this._core.onLineFeed}get onRender(){return this._core.onRender}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onSelectionChange(){return this._core.onSelectionChange}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get element(){return this._core.element}get parser(){return this._parser||(this._parser=new Rn(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new Ln(this._core)}get textarea(){return this._core.textarea}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._buffer||(this._buffer=this._register(new Dn(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let t=this._core.coreService.decPrivateModes,e="none";switch(this._core.coreMouseService.activeProtocol){case"X10":e="x10";break;case"VT200":e="vt200";break;case"DRAG":e="drag";break;case"ANY":e="any";break}return{applicationCursorKeysMode:t.applicationCursorKeys,applicationKeypadMode:t.applicationKeypad,bracketedPasteMode:t.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:e,originMode:t.origin,reverseWraparoundMode:t.reverseWraparound,sendFocusMode:t.sendFocus,synchronizedOutputMode:t.synchronizedOutput,wraparoundMode:t.wraparound}}get options(){return this._publicOptions}set options(t){for(let e in t)this._publicOptions[e]=t[e]}blur(){this._core.blur()}focus(){this._core.focus()}input(t,e=!0){this._core.input(t,e)}resize(t,e){this._verifyIntegers(t,e),this._core.resize(t,e)}open(t){this._core.open(t)}attachCustomKeyEventHandler(t){this._core.attachCustomKeyEventHandler(t)}attachCustomWheelEventHandler(t){this._core.attachCustomWheelEventHandler(t)}registerLinkProvider(t){return this._core.registerLinkProvider(t)}registerCharacterJoiner(t){return this._checkProposedApi(),this._core.registerCharacterJoiner(t)}deregisterCharacterJoiner(t){this._checkProposedApi(),this._core.deregisterCharacterJoiner(t)}registerMarker(t=0){return this._verifyIntegers(t),this._core.registerMarker(t)}registerDecoration(t){return this._checkProposedApi(),this._verifyPositiveIntegers(t.x??0,t.width??0,t.height??0),this._core.registerDecoration(t)}hasSelection(){return this._core.hasSelection()}select(t,e,i){this._verifyIntegers(t,e,i),this._core.select(t,e,i)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(t,e){this._verifyIntegers(t,e),this._core.selectLines(t,e)}dispose(){super.dispose()}scrollLines(t){this._verifyIntegers(t),this._core.scrollLines(t)}scrollPages(t){this._verifyIntegers(t),this._core.scrollPages(t)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(t){this._verifyIntegers(t),this._core.scrollToLine(t)}clear(){this._core.clear()}write(t,e){this._core.write(t,e)}writeln(t,e){this._core.write(t),this._core.write(`\r +`,e)}paste(t){this._core.paste(t)}refresh(t,e){this._verifyIntegers(t,e),this._core.refresh(t,e)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(t){this._addonManager.loadAddon(this,t)}static get strings(){return{get promptLabel(){return mi.get()},set promptLabel(t){mi.set(t)},get tooMuchOutput(){return _i.get()},set tooMuchOutput(t){_i.set(t)}}}_verifyIntegers(...t){for(Ue of t)if(Ue===1/0||isNaN(Ue)||Ue%1!==0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...t){for(Ue of t)if(Ue&&(Ue===1/0||isNaN(Ue)||Ue%1!==0||Ue<0))throw new Error("This API only accepts positive integers")}};export{Dl as Terminal}; +//# sourceMappingURL=xterm.mjs.map