@puddle-code/cli 0.3.14 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +4 -4
- package/README.md +31 -19
- package/dist/host-control.mjs +1980 -133
- package/dist/index.js +4341 -970
- package/dist/install.sh +401 -40
- package/dist/public/assets/App-CB0Bm55u.js +9 -0
- package/dist/public/assets/{CompilationCommandForm-8ipw9M-Z.js → CompilationCommandForm-vv5bglnl.js} +1 -1
- package/dist/public/assets/Dashboard-BQd42kix.js +1 -0
- package/dist/public/assets/{EditorTabClose-o1L4BgTN.js → EditorTabClose-D3LwFFHd.js} +1 -1
- package/dist/public/assets/{LazyTerminal-Crwcrh-K.js → LazyTerminal-CfuC3bjp.js} +2 -2
- package/dist/public/assets/{ModelRefcount-0o8MEOUT.js → ModelRefcount-DtJdNeW7.js} +1 -1
- package/dist/public/assets/NewProjectDialog-DYn30yon.js +1 -0
- package/dist/public/assets/{NotebookWidget-Ci7TAuWd.js → NotebookWidget-BntkgqbM.js} +1 -1
- package/dist/public/assets/PaneEditorBody-ChNwAz96.js +284 -0
- package/dist/public/assets/{PdfViewer-BoFsXAue.js → PdfViewer-DYmz05py.js} +1 -1
- package/dist/public/assets/ReleaseNotesDialog-D2kA6oIr.js +1 -0
- package/dist/public/assets/SettingsDialog-BWWWn7I0.js +8 -0
- package/dist/public/assets/{Terminal-B3Iw783s.js → Terminal-BQHSZc8Q.js} +5 -5
- package/dist/public/assets/Workspace-DVTqrQNf.js +20 -0
- package/dist/public/assets/api-BOuyloUi.js +1 -0
- package/dist/public/assets/auth-olLlgxc3.js +64 -0
- package/dist/public/assets/{buffer-store-B2nYD11t.js → buffer-store-BWLcD39y.js} +1 -1
- package/dist/public/assets/{context-CwZ4epwz.js → context-C3-WejyN.js} +1 -1
- package/dist/public/assets/{forward-link-C-8Xn8gf.js → forward-link-DMvLf0Xw.js} +1 -1
- package/dist/public/assets/{hotkeys-DOpJ1a7g.js → hotkeys-Cu0t6sbz.js} +1 -1
- package/dist/public/assets/index--5A6_BeN.css +2 -0
- package/dist/public/assets/{index-B9DFgBft.js → index-BUAoYe1o.js} +3 -3
- package/dist/public/assets/markdown-CMSzQtLp.js +8 -0
- package/dist/public/assets/markdown-it-CWoG9_Dn.js +13 -0
- package/dist/public/assets/{markdown-mermaid-CZnHoKN5.js → markdown-mermaid-BCXEEB98.js} +1 -1
- package/dist/public/assets/media-refresh-store-BplHZVs4.js +1 -0
- package/dist/public/assets/notification-delivery-CDWhS_kj.js +1 -0
- package/dist/public/assets/protocol-support-CsLR9u7d.js +1 -0
- package/dist/public/assets/queue-BlrQxHDl.js +3 -0
- package/dist/public/assets/{scroll-restoration-gKZDDamc.js → scroll-restoration-CwXbvZvT.js} +1 -1
- package/dist/public/assets/selection-actions-B2XIuCoH.js +1 -0
- package/dist/public/assets/{session-order-SN_zG4Us.js → session-order-unCbOqgk.js} +1 -1
- package/dist/public/assets/{switch-iVuj74VW.js → switch-DVo2TkMf.js} +1 -1
- package/dist/public/assets/{use-ui-state-CQp93ZE4.js → use-ui-state-i7N5-9dI.js} +1 -1
- package/dist/public/assets/{view-state-store-CVAUWqnG.js → view-state-store-Cy9sQJoZ.js} +1 -1
- package/dist/public/assets/ws-BX1iQbeP.js +1 -0
- package/dist/public/index.html +3 -3
- package/dist/pudl.js +1996 -183
- package/package.json +1 -1
- package/dist/public/assets/App-5QiKmUI_.js +0 -2
- package/dist/public/assets/Dashboard-B9v8mQKk.js +0 -1
- package/dist/public/assets/NewProjectDialog-qFDLTphH.js +0 -1
- package/dist/public/assets/PaneEditorBody-C8uTV9yU.js +0 -303
- package/dist/public/assets/SettingsDialog-tW18Y_Wr.js +0 -8
- package/dist/public/assets/Workspace-D2IYXJV2.js +0 -20
- package/dist/public/assets/api-CfmzEbQ_.js +0 -1
- package/dist/public/assets/auth-CIb9G2C5.js +0 -64
- package/dist/public/assets/errors-DTaodZDR.js +0 -1
- package/dist/public/assets/index-DwtrJj9v.css +0 -2
- package/dist/public/assets/media-refresh-store-DDvrEM5K.js +0 -1
- package/dist/public/assets/notification-delivery-DdTD40aA.js +0 -1
- package/dist/public/assets/protocol-support-BGk73LFk.js +0 -1
- package/dist/public/assets/selection-actions-BjVj7hXw.js +0 -1
- package/dist/public/assets/ws-CspBmo8M.js +0 -1
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/NotebookWidget-BntkgqbM.js","assets/rolldown-runtime-QTnfLwEv.js","assets/react-CZI7_Jkm.js","assets/auth-olLlgxc3.js","assets/context-C3-WejyN.js","assets/protocol-support-CsLR9u7d.js","assets/jsx-runtime-By8HlURe.js","assets/api-BOuyloUi.js","assets/preload-helper-Czpn1I53.js","assets/index-BUAoYe1o.js","assets/react-dom-cJyBB_A4.js","assets/client-settings-CwqpIric.js","assets/index--5A6_BeN.css","assets/PdfViewer-DYmz05py.js","assets/dist-BOS6OKSE.js","assets/createLucideIcon-DyMAgLa3.js","assets/view-state-store-Cy9sQJoZ.js","assets/scroll-restoration-CwXbvZvT.js","assets/PdfViewer-Re37jQgv.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{t}from"./react-CZI7_Jkm.js";import{R as n,St as r,Tt as i,_ as a,d as o,f as s,p as c,u as l}from"./protocol-support-CsLR9u7d.js";import{at as u,ct as d,it as f,k as p,lt as m,nt as h,o as g,ot as _,rt as v,st as y,tt as b}from"./auth-olLlgxc3.js";import{n as x,t as S}from"./context-C3-WejyN.js";import{i as C,r as w,t as ee}from"./client-settings-CwqpIric.js";import{t as T}from"./jsx-runtime-By8HlURe.js";import{t as E}from"./preload-helper-Czpn1I53.js";import{a as D,r as O}from"./index-BUAoYe1o.js";import{t as k}from"./purify.es-D8QhFVkO.js";import"./katex.min-ZqdHjttS.js";import{a as A,c as j,h as te,i as M,p as N,r as P}from"./editor.api2-4X9Vh9Zw.js";import{n as F,r as ne,t as re}from"./api-BOuyloUi.js";import{c as ie,g as ae,p as oe}from"./hotkeys-Cu0t6sbz.js";import{B as se,C as ce,E as le,J as ue,K as de,O as fe,P as pe,R as me,T as he,U as ge,W as _e,X as ve,Y as ye,Z as be,_ as xe,a as Se,at as Ce,d as we,i as Te,it as Ee,j as De,k as Oe,m as ke,n as Ae,nt as je,ot as Me,r as Ne,rt as Pe,st as Fe,u as Ie,v as Le,w as Re}from"./media-refresh-store-BplHZVs4.js";import{n as I}from"./dist-BOS6OKSE.js";import{t as ze}from"./x-DCpy1q13.js";import{n as Be,t as Ve}from"./chevron-right-BRjnLYaO.js";import{n as He,r as Ue}from"./dist-Cde1E3eV.js";import{t as We}from"./createLucideIcon-DyMAgLa3.js";import{a as Ge,i as Ke,n as qe,o as Je,r as Ye,t as Xe}from"./select-9OADuw7W.js";import{t as Ze}from"./chevron-down--sjpQEHH.js";import{a as Qe,n as $e,o as et,r as tt,t as nt}from"./FindWidget-CVH9U-_P.js";import{t as rt}from"./copy-CGsu8426.js";import{t as it}from"./rotate-ccw-CNjR2LSi.js";import{a as at,i as ot,n as st,o as ct,r as lt,t as ut}from"./preview-kind-DiWpvEc0.js";import{a as dt,o as ft,r as pt,s as mt,t as ht}from"./command-BUOkDmUW.js";import{n as gt,r as _t,t as vt}from"./popover-CtxJVkPi.js";import{i as yt,n as bt,r as xt}from"./markdown-it-CWoG9_Dn.js";import{t as St}from"./debounce-B9DrqirV.js";import{a as Ct,c as wt,d as Tt,f as Et,i as Dt,l as Ot,o as kt,p as At,r as jt,s as Mt,t as Nt,u as Pt}from"./buffer-store-BWLcD39y.js";import{r as Ft,t as It}from"./view-state-store-Cy9sQJoZ.js";import{a as Lt,c as Rt,i as zt,n as Bt,o as Vt,r as Ht,s as Ut,t as Wt}from"./markdown-CMSzQtLp.js";import{i as Gt,n as Kt,r as qt,t as Jt}from"./drafts-B_tChlzR.js";import{r as Yt}from"./buffer-logic-BAkSBQT7.js";import{a as Xt,i as Zt,n as Qt,o as $t,r as en}from"./editor-sync-W1bamxAP.js";import{r as tn,t as nn}from"./math-CSw6sgCC.js";import{n as rn}from"./math-delimiters-BCnTi7Ii.js";import{n as an}from"./markdown-mermaid-BCXEEB98.js";var on=We(`arrow-down-to-line`,[[`path`,{d:`M12 17V3`,key:`1cwfxf`}],[`path`,{d:`m6 11 6 6 6-6`,key:`12ii2o`}],[`path`,{d:`M19 21H5`,key:`150jfl`}]]),sn=We(`arrow-up-to-line`,[[`path`,{d:`M5 3h14`,key:`7usisc`}],[`path`,{d:`m18 13-6-6-6 6`,key:`1kf1n9`}],[`path`,{d:`M12 7v14`,key:`1akyts`}]]),cn=We(`combine`,[[`path`,{d:`M14 3a1 1 0 0 1 1 1v5a1 1 0 0 1-1 1`,key:`1l7d7l`}],[`path`,{d:`M19 3a1 1 0 0 1 1 1v5a1 1 0 0 1-1 1`,key:`9955pe`}],[`path`,{d:`m7 15 3 3`,key:`4hkfgk`}],[`path`,{d:`m7 21 3-3H5a2 2 0 0 1-2-2v-2`,key:`1xljwe`}],[`rect`,{x:`14`,y:`14`,width:`7`,height:`7`,rx:`1`,key:`1cdgtw`}],[`rect`,{x:`3`,y:`3`,width:`7`,height:`7`,rx:`1`,key:`zi3rio`}]]),ln=We(`cpu`,[[`path`,{d:`M12 20v2`,key:`1lh1kg`}],[`path`,{d:`M12 2v2`,key:`tus03m`}],[`path`,{d:`M17 20v2`,key:`1rnc9c`}],[`path`,{d:`M17 2v2`,key:`11trls`}],[`path`,{d:`M2 12h2`,key:`1t8f8n`}],[`path`,{d:`M2 17h2`,key:`7oei6x`}],[`path`,{d:`M2 7h2`,key:`asdhe0`}],[`path`,{d:`M20 12h2`,key:`1q8mjw`}],[`path`,{d:`M20 17h2`,key:`1fpfkl`}],[`path`,{d:`M20 7h2`,key:`1o8tra`}],[`path`,{d:`M7 20v2`,key:`4gnj0m`}],[`path`,{d:`M7 2v2`,key:`1i4yhu`}],[`rect`,{x:`4`,y:`4`,width:`16`,height:`16`,rx:`2`,key:`1vbyd7`}],[`rect`,{x:`8`,y:`8`,width:`8`,height:`8`,rx:`1`,key:`z9xiuo`}]]),un=We(`list-tree`,[[`path`,{d:`M8 5h13`,key:`1pao27`}],[`path`,{d:`M13 12h8`,key:`h98zly`}],[`path`,{d:`M13 19h8`,key:`c3s6r1`}],[`path`,{d:`M3 10a2 2 0 0 0 2 2h3`,key:`1npucw`}],[`path`,{d:`M3 5v12a2 2 0 0 0 2 2h3`,key:`x1gjn2`}]]),L=e(t(),1),R=T();String.prototype.codePointAt;function dn(e,t){return function(n){let r,i=0,a=``;for(;r=e.exec(n);)i!==r.index&&(a+=n.substring(i,r.index)),a+=t.get(r[0].charCodeAt(0)),i=r.index+1;return a+n.substring(i)}}var fn=dn(/["&\u00A0]/g,new Map([[34,`"`],[38,`&`],[160,` `]])),pn=dn(/[&<>\u00A0]/g,new Map([[38,`&`],[60,`<`],[62,`>`],[160,` `]])),mn=new Map,hn=new Map,gn=1;function _n(e){for(let t of hn.get(e)??[])t()}function vn(e,t){mn.set(e,t),_n(e)}function yn(e){let t={phase:`unresolved`,revision:gn++};return vn(e,t),t}function bn(e){let t=mn.get(e);return!t||t.phase!==`unresolved`&&t.phase!==`load-error`?null:(vn(e,{phase:`loading`,revision:t.revision}),t.revision)}function xn(e,t,n,r){let i=mn.get(e);return!i||i.phase!==`loading`||i.revision!==t?!1:(vn(e,{phase:`opening`,revision:t,content:n,mtimeMs:r}),!0)}function Sn(e,t){let n=mn.get(e);return!n||n.phase!==`opening`||n.revision!==t?!1:(vn(e,{...n,phase:`comparing`}),!0)}function Cn(e,t,n){let r=mn.get(e);return!r||r.phase!==`loading`||r.revision!==t?!1:(vn(e,{phase:`load-error`,revision:t,message:n}),!0)}function wn(e,t){return t&&e?.phase===`unresolved`}function Tn(e){return e?.phase===`comparing`?e.mtimeMs:void 0}function En(e){return e?.phase===`loading`||e?.phase===`load-error`||e?.phase===`opening`}function Dn(e){return e.phase===`opening`||e.phase===`comparing`}function On(e){mn.delete(e)&&_n(e)}function kn(e){return mn.get(e)??null}function An(e,t){let n=hn.get(e);return n||(n=new Set,hn.set(e,n)),n.add(t),()=>n.delete(t)}function jn(e){return{tabSize:e,insertSpaces:!0,detectIndentation:!1}}var Mn=new It,Nn=new It;function Pn(e){let t={...e.contributionsState};return delete t[`editor.contrib.wordHighlighter`],{...e,contributionsState:t}}function Fn(e,t){let n=(0,L.useRef)(null),r=(0,L.useRef)(null);return(0,L.useLayoutEffect)(()=>(n.current&&(r.current=t(n.current,e)),()=>{r.current?.(),r.current=null}),[e,t]),(0,L.useCallback)(i=>{r.current?.(),n.current=i,i.onDidDispose(()=>{n.current===i&&(n.current=null)}),r.current=t(i,e)},[e,t])}function In(e,t){let n=Mn.get(t);n&&e.restoreViewState(n);let r=()=>{if(!e.getModel())return;let n=e.saveViewState();n&&Mn.set(t,Pn(n))},i=[e.onDidScrollChange(r),e.onDidChangeCursorSelection(r)];return()=>{r(),i.forEach(e=>e.dispose())}}function Ln(e,t){let n=Nn.get(t),r=n!==void 0,i=()=>{if(r||!e.getModel())return;let n=e.saveViewState();n&&Nn.set(t,{...n,original:n.original&&Pn(n.original),modified:n.modified&&Pn(n.modified)})};n&&e.restoreViewState(n);let a=[e.onDidUpdateDiff(()=>{r&&(r=!1,n&&e.restoreViewState(n))}),...[e.getOriginalEditor(),e.getModifiedEditor()].flatMap(e=>[e.onDidScrollChange(i),e.onDidChangeCursorSelection(i)])];return()=>{i(),a.forEach(e=>e.dispose())}}function Rn(e){return Fn(Ft(`code`,e),In)}function zn(e){return Fn(Ft(`diff`,e),Ln)}function Bn({session:e,path:t,conflict:n,model:r,onTakeDisk:i,onKeepMine:a,onSave:o,onReady:s}){let c=C(),l=zn([`conflict`,r.uri.toString()]),u=(0,L.useId)(),d=(0,L.useMemo)(()=>getComputedStyle(document.documentElement).getPropertyValue(`--font-mono`).trim()||void 0,[]),f=(0,L.useRef)(o);f.current=o;let p=(0,L.useRef)(null),m=()=>{let e=p.current;if(!e)return;let t=e.getModel();e.setModel(null),t?.original.dispose(),p.current=null},h=(0,L.useRef)(m);return h.current=m,(0,L.useEffect)(()=>()=>h.current(),[]),(0,R.jsxs)(`div`,{className:`flex h-full flex-col bg-ground`,children:[(0,R.jsxs)(`div`,{className:`flex items-center gap-3 bg-elevated px-3 py-1.5 text-xs text-fg-secondary`,children:[(0,R.jsx)(`span`,{children:`This file changed on disk. Yours is on the right — merge what you want, then save.`}),(0,R.jsx)(`button`,{type:`button`,onClick:i,className:`ml-auto shrink-0 text-fg-muted transition-colors hover:text-fg`,children:`Take the disk version`}),(0,R.jsx)(`button`,{type:`button`,onClick:a,disabled:n.phase!==`comparing`,className:`shrink-0 text-fg-muted transition-colors hover:text-fg`,children:`Keep mine`})]}),(0,R.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,R.jsx)(At,{modifiedModelPath:r.uri.toString(),originalModelPath:`puddle-disk://${encodeURIComponent(e)}/${n.mtimeMs}/${encodeURIComponent(u)}/${t.split(`/`).map(encodeURIComponent).join(`/`)}`,original:n.content,language:r.getLanguageId(),theme:Tt,keepCurrentModifiedModel:!0,loading:(0,R.jsx)(`div`,{className:`p-3 text-xs text-fg-muted`,children:`…`}),onMount:e=>{l(e),p.current=e,e.onDidDispose(()=>{p.current=null}),e.getModifiedEditor().addCommand(M.CtrlCmd|P.KeyS,()=>f.current()),s?.(n.revision)},options:{readOnly:n.phase!==`comparing`,originalEditable:!1,renderSideBySide:!0,automaticLayout:!0,fontFamily:d,fontSize:c.editorFontSize,...jn(c.editorTabSize),wordWrap:c.editorWordWrap?`on`:`off`,minimap:{enabled:!1},fixedOverflowWidgets:!0,scrollBeyondLastLine:!1}})})]})}function Vn({session:e,path:t,buffer:n,focused:r}){let i=n.conflict;return!i||i.phase===`unresolved`?null:Dn(i)&&n.model?(0,R.jsx)(Bn,{session:e,path:t,conflict:i,model:n.model,onTakeDisk:n.takeDisk,onKeepMine:n.keepMine,onSave:n.save,onReady:r?n.comparisonReady:void 0}):i.phase===`load-error`?(0,R.jsxs)(`div`,{className:`flex h-full flex-col items-center justify-center gap-3 bg-ground px-4 text-center text-sm text-fg-muted`,children:[(0,R.jsx)(`span`,{children:`The disk version could not be loaded.`}),(0,R.jsx)(`span`,{className:`max-w-lg text-xs text-fg-secondary`,children:i.message}),(0,R.jsx)(`button`,{type:`button`,onClick:n.compare,className:`rounded-md bg-elevated px-3 py-1.5 text-xs text-fg-secondary transition-colors hover:bg-border hover:text-fg`,children:`Retry compare`})]}):(0,R.jsx)(`div`,{className:`flex h-full items-center justify-center bg-ground text-sm text-fg-muted`,children:`Loading the disk version…`})}function Hn(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):0}function Un(e,t,n){return Hn(e/Math.max(1,t-n))}function Wn(e,t,n){return Hn(e)*Math.max(0,t-n)}function Gn(e,t){return JSON.stringify([e,t.session,t.root??null,t.path])}var Kn=new class{positions=new Map;listeners=new Map;revision=0;publish(e,t,n,r=null){let i={ratio:Hn(n),sourceLine:r!==null&&Number.isFinite(r)?Math.max(1,r):null,revision:++this.revision},a=Gn(e,t);this.positions.set(a,i);for(let e of this.listeners.get(a)??[])e(i);return i}get(e,t){return this.positions.get(Gn(e,t))}subscribe(e,t,n){let r=Gn(e,t),i=this.listeners.get(r);i||(i=new Set,this.listeners.set(r,i)),i.add(n);let a=this.positions.get(r);return a&&n(a),()=>{i?.delete(n),i?.size===0&&this.listeners.delete(r)}}},qn=new It;function Jn(e){let t=null;return{schedule:()=>{t===null&&(t=requestAnimationFrame(()=>{t=null,e()}))},dispose:()=>{t!==null&&cancelAnimationFrame(t),t=null}}}function Yn(e,t,n,r){let i=Math.max(0,t-n);if(e.ratio<=0)return 0;if(e.ratio>=1)return i;if(e.sourceLine!==null&&r){let t=Ut(r,e.sourceLine);if(t!==null)return Math.min(i,Math.max(0,t))}return Wn(e.ratio,t,n)}function Xn(e,t){if(t.driver&&t.receiver)throw Error(`a preview scroll surface cannot be both driver and receiver`);let n=t.store??Kn,r=t.viewKey?qn.get(t.viewKey):void 0,i=t.sourceAnchors?.(),a=()=>void 0,o,s=n=>{r=n,t.viewKey&&qn.set(t.viewKey,n),e.scrollTop=Yn(n,e.scrollHeight,e.clientHeight,i)};r&&s(r);let c=()=>{if(e.clientHeight<=0)return;let a=Un(e.scrollTop,e.scrollHeight,e.clientHeight),o=i?Rt(i,e.scrollTop):null;r={ratio:a,sourceLine:o,revision:0},t.viewKey&&qn.set(t.viewKey,r),t.driver&&n.publish(t.channel,t.target,a,o)};t.receiver?a=n.subscribe(t.channel,t.target,s):(t.driver||t.viewKey)&&(o=Jn(c),e.addEventListener(`scroll`,o.schedule,{passive:!0}),o.schedule());let l=new ResizeObserver(()=>{i=t.sourceAnchors?.(),r?s(r):o?.schedule()});for(let e of t.resizeElements??[])l.observe(e);return()=>{o&&(c(),e.removeEventListener(`scroll`,o.schedule)),a(),l.disconnect(),o?.dispose()}}function Zn(e,t){let n=e.getModel()?.getLineCount()??0;if(n===0)return null;let r=1,i=n;for(;r<i;){let n=Math.ceil((r+i)/2);e.getTopForLineNumber(n)<=t?r=n:i=n-1}let a=e.getTopForLineNumber(r),o=r<n?e.getTopForLineNumber(r+1):e.getScrollHeight();return o<=a?r:r+Math.min(1,Math.max(0,(t-a)/(o-a)))}function Qn(e,t){let n=e.getModel()?.getLineCount()??0;if(n===0||!Number.isFinite(t))return null;let r=Math.min(n+1,Math.max(1,t)),i=Math.floor(r);if(i>n)return e.getScrollHeight();let a=i+1,o=e.getTopForLineNumber(i),s=a<=n?e.getTopForLineNumber(a):e.getScrollHeight();return o+(r-i)*(s-o)}function $n(e,t,n){if(t.driver&&t.receiver)throw Error(`a Monaco scroll surface cannot be both driver and receiver`);let r=t.store??Kn,i=[],a,o=()=>void 0,s,c=()=>e.getLayoutInfo().height,l=t=>{a=t;let r=t.ratio>0&&t.ratio<1&&t.sourceLine!==null?Qn(e,t.sourceLine):null;e.setScrollTop(r??Yn(t,e.getScrollHeight(),c()),n)};return t.receiver?(o=r.subscribe(t.channel,t.target,l),i.push(e.onDidChangeModel(()=>a&&l(a))),i.push(e.onDidLayoutChange(()=>a&&l(a))),i.push(e.onDidContentSizeChange(()=>a&&l(a)))):t.driver&&(s=Jn(()=>{let n=Un(e.getScrollTop(),e.getScrollHeight(),c());r.publish(t.channel,t.target,n,Zn(e,e.getScrollTop()))}),i.push(e.onDidScrollChange(s.schedule)),i.push(e.onDidChangeModel(s.schedule)),i.push(e.onDidChangeModelContent(s.schedule)),i.push(e.onDidLayoutChange(s.schedule)),i.push(e.onDidContentSizeChange(s.schedule)),s.schedule()),()=>{o();for(let e of i)e.dispose();s?.dispose()}}function er(e){return!e}function tr(e){let t=e.split(`+`),n=t.pop()??``,r=0;for(let e of t)e===`meta`?r|=M.CtrlCmd:e===`ctrl`?r|=M.WinCtrl:e===`alt`?r|=M.Alt:e===`shift`&&(r|=M.Shift);let i=P[/^Key[A-Z]$/.test(n)?`Key${n.slice(3)}`:/^Digit[0-9]$/.test(n)?`Digit${n.slice(5)}`:n];return typeof i==`number`?r|i:null}function nr(e,t){let n=tr(ie(`editor.save`));n!==null&&e.addCommand(n,()=>t.onSave());let r=tr(ie(`editor.wordWrap`));e.addAction({id:`puddle.toggleWordWrap`,label:`Toggle Word Wrap`,keybindings:r===null?[]:[r],run:()=>w({editorWordWrap:er(ee().editorWordWrap)})})}var rr=new WeakSet;function ir(e){return rr.has(e)?!1:(rr.add(e),!0)}function ar(e){return`file-conflict:${e}`}function or(e,t,n,r,i){let a=i?.passive===!0,o=i?.focused??!0,s=Nt(e,t,r),c=be(e,t,{root:r,live:i?.live}),l=ye(e,r),[u,d]=(0,L.useState)(null),[f,p]=(0,L.useState)(!1),m=(0,L.useRef)(!1),h=(0,L.useRef)(null),g=(0,L.useRef)(null),_=(0,L.useRef)(n);_.current=n;let v=(0,L.useRef)(!1),y=(0,L.useCallback)((e,t)=>{g.current?.cancel(),v.current=!0;try{Mt(s,e,t)}finally{v.current=!1}},[s]),b=(0,L.useSyncExternalStore)((0,L.useCallback)(e=>Pt(s,e),[s]),()=>Dt(s)),x=(0,L.useSyncExternalStore)((0,L.useCallback)(e=>$t(s,e),[s]),()=>Xt(s)),S=(0,L.useSyncExternalStore)((0,L.useCallback)(e=>An(s,e),[s]),()=>kn(s));(0,L.useEffect)(()=>{let n=c.data;if(!n||n.binary||n.content===null||m.current)return;m.current=!0;let i=Ot(s)!==void 0,a=jt(e,t,n.content,n.mtime_ms,r),o=a.getValue();d(a),!i&&Gt(e,t,r).then(i=>{if(!i)return;let s=Kt(i,o,n.mtime_ms);s===`discard`?Jt(e,t,r):s===`restore`?Yt(a,i.content)&&p(!0):I(`This file has an unsaved draft from an earlier version.`,{description:`The file changed on disk since the draft was saved.`,duration:12e3,action:{label:`Restore draft`,onClick:()=>{Yt(a,i.content)&&p(!0)}}})})},[c.data,s,e,t,r]),(0,L.useEffect)(()=>{if(!u||a)return;let n=qt(e,t,r);g.current=n;let i=u.onDidChangeContent(()=>{v.current||(n(u.getValue(),Ot(s)??0),Qt(e,t,r))});return()=>{n.flush(),i.dispose(),g.current=null}},[u,s,e,t,r,a]),(0,L.useEffect)(()=>{!u||!x.savedElsewhere||Dt(s)||c.refetch().then(e=>{Dt(s)||(e.data&&e.data.content!==null&&y(e.data.content,e.data.mtime_ms),Zt(s))})},[x.savedElsewhere,u,s]),(0,L.useEffect)(()=>{let e=c.data;!u||!e||e.content===null||!Dt(s)&&e.mtime_ms!==Ot(s)&&y(e.content,e.mtime_ms)},[c.data,u,s]);let C=(0,L.useCallback)((n,i)=>{Ct(s,n,i),g.current?.cancel(),Jt(e,t,r),en(e,t,i,r),p(!1),On(s)},[s,e,t,r]),w=(0,L.useCallback)(()=>{let e=bn(s);e!==null&&(I.dismiss(ar(s)),c.refetch({throwOnError:!0}).then(t=>{let n=t.data;if(!n)throw Error(`The disk version did not load.`);if(n.content===null)throw Error(`The file on disk is binary and cannot be compared as text.`);xn(s,e,n.content,n.mtime_ms)}).catch(t=>{Cn(s,e,t instanceof Error?t.message:`The disk version did not load.`)}))},[c,s]),ee=(0,L.useRef)(w);ee.current=w,(0,L.useEffect)(()=>{if(!wn(S,o))return;let e=ar(s);return I(`File changed on disk`,{id:e,description:`Nothing was written — your unsaved version is intact.`,duration:1/0,closeButton:!0,action:{label:`Compare`,onClick:()=>ee.current()}}),()=>{I.dismiss(e)}},[S,o,s]);let T=(0,L.useCallback)(()=>{c.refetch().then(n=>{n.data&&n.data.content!==null&&y(n.data.content,n.data.mtime_ms),Jt(e,t,r),p(!1),On(s)})},[s,e,t,y]),E=(0,L.useCallback)((e,n)=>{l.mutate({path:t,content:e},{onSuccess:e=>C(n,e.mtime_ms),onError:e=>I.error(e instanceof Error?e.message:`Overwrite failed`)})},[l,t,C]),D=(0,L.useCallback)(async()=>{if(!u||!Dt(s))return!0;let e=u.getValue(),n=u.getAlternativeVersionId();if(En(kn(s)))return!1;let r=Tn(kn(s))??Ot(s);try{let i=await l.mutateAsync({path:t,content:e,expected_mtime_ms:r});return C(n,i.mtime_ms),!0}catch(e){return e instanceof re&&e.status===409&&e.code===`stale_file`?yn(s):I.error(e instanceof Error?e.message:`Save failed`),!1}},[u,s,l,t,C]),O=(0,L.useRef)(D);O.current=D,(0,L.useEffect)(()=>fe(De(e,t,r),()=>O.current(),{session:e,path:t,...r===void 0?{}:{root:r}}),[e,t,r]);let k=(0,L.useCallback)(()=>{let n=h.current,i=_.current;!n||!i||!o||i.session!==e||i.path!==t||(i.root??void 0)!==(r??void 0)||ir(i)&&(n.revealLineInCenter(i.line),n.setPosition({lineNumber:i.line,column:i.column??1}),n.focus())},[e,t,r,o]),A=(0,L.useCallback)(e=>{h.current=e,nr(e,{onSave:()=>O.current()}),k()},[k]);(0,L.useEffect)(()=>{k()},[n,u,k]);let j=(0,L.useCallback)(()=>{T()},[T]),te=(0,L.useCallback)(()=>{!u||kn(s)?.phase!==`comparing`||E(u.getValue(),u.getAlternativeVersionId())},[u,s,E]),M=(0,L.useCallback)(e=>{Sn(s,e)},[s]),N,P=null;c.data?.binary?N=`binary`:c.error?c.error instanceof re&&c.error.status===413?N=`too-large`:(N=`error`,P=c.error instanceof Error?c.error.message:`Failed to load file`):N=u?`ready`:`loading`;let F=b&&x.savedElsewhere?`saved-elsewhere`:b&&x.dirtyElsewhere?`dirty-elsewhere`:null;return{status:N,errorMessage:P,model:u,dirty:b,restoredNotice:f,discardRestore:j,peerBadge:F,conflict:S,takeDisk:T,keepMine:te,compare:w,comparisonReady:M,save:D,onMount:A}}function sr(e,t,n,r){for(let i of e)if(fr([i],n).some(e=>(r===void 0||e.kind===r)&&t>=e.startLineNumber&&t<=e.endLineNumber))return i;return null}function cr(e,t){return ur(e.modifiedStartLineNumber,e.modifiedEndLineNumber)>0?Math.min(t,e.modifiedEndLineNumber):Math.max(0,Math.min(t,e.modifiedStartLineNumber-1))}function lr(e){let t=ur(e.originalStartLineNumber,e.originalEndLineNumber),n=ur(e.modifiedStartLineNumber,e.modifiedEndLineNumber);return Math.max(5,Math.min(14,t+n+4))}function ur(e,t){return t===0?0:Math.max(0,t-e+1)}function dr(e,t){if(e>t)return{startLineNumber:Math.max(1,t),endLineNumber:Math.max(1,t),kind:`deleted-after`};let n=Math.max(1,e);return{startLineNumber:n,endLineNumber:n,kind:`deleted-before`}}function fr(e,t){let n=[];for(let r of e){let e=ur(r.originalStartLineNumber,r.originalEndLineNumber),i=ur(r.modifiedStartLineNumber,r.modifiedEndLineNumber);if(e===0&&i>0){n.push({startLineNumber:r.modifiedStartLineNumber,endLineNumber:r.modifiedEndLineNumber,kind:`added`});continue}if(i===0&&e>0){n.push(dr(r.modifiedStartLineNumber,t));continue}let a=Math.min(e,i);a>0&&n.push({startLineNumber:r.modifiedStartLineNumber,endLineNumber:r.modifiedStartLineNumber+a-1,kind:`modified`}),i>a&&n.push({startLineNumber:r.modifiedStartLineNumber+a,endLineNumber:r.modifiedEndLineNumber,kind:`added`}),e>a&&n.push(dr(r.modifiedStartLineNumber+i,t))}return n}var pr=28,mr=[[`puddle-dirty-added`,`added`],[`puddle-dirty-modified`,`modified`],[`puddle-dirty-deleted-before`,`deleted-before`],[`puddle-dirty-deleted-after`,`deleted-after`]];function hr(e){if(e){for(let[t,n]of mr)if(e.classList.contains(t)||e.closest(`.${t}`))return n}}function gr({editor:e,original:t,modified:n,path:r}){let i=[],a=null,o=!1,s=t=>{try{e.changeViewZones(e=>e.removeZone(t))}catch{}},c=()=>{let e=a;e&&(a=null,e.frame!==null&&cancelAnimationFrame(e.frame),e.diffEditor&&(e.diffEditor.setModel(null),e.diffEditor.dispose()),s(e.zoneId))},l=e=>{let t=e.diffEditor;if(!t)return;let r=Math.max(1,Math.min(n.getLineCount(),e.change.modifiedStartLineNumber));t.getModifiedEditor().revealLineInCenter(r,N.ScrollType.Immediate)},u=(i,s)=>{if(a?.anchorLine===i){c();return}c();let u=e.getOption(N.EditorOption.lineHeight),d=document.createElement(`div`);d.className=`puddle-dirty-peek`;let f=document.createElement(`div`);f.className=`puddle-dirty-peek-header`;let p=document.createElement(`span`);p.className=`puddle-dirty-peek-title`,p.textContent=`${r.split(`/`).pop()??r} · Local changes against HEAD`;let m=document.createElement(`button`);m.type=`button`,m.className=`puddle-dirty-peek-close`,m.setAttribute(`aria-label`,`Close inline change`),m.title=`Close inline change`,m.textContent=`×`,m.addEventListener(`pointerdown`,e=>{e.preventDefault(),e.stopPropagation(),c()}),m.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),c()});let h=document.createElement(`div`);h.className=`puddle-dirty-peek-editor`,f.append(p,m),d.append(f,h);let g=document.createElement(`div`);g.className=`puddle-dirty-peek-margin`;let _={afterLineNumber:cr(s,n.getLineCount()),heightInPx:pr+lr(s)*u,domNode:d,marginDomNode:g,suppressMouseDown:!1},v=``;e.changeViewZones(e=>{v=e.addZone(_)});let y={anchorLine:i,change:s,zone:_,zoneId:v,frame:null,diffEditor:null};a=y,y.frame=requestAnimationFrame(()=>{if(y.frame=null,o||a!==y)return;let r=N.createDiffEditor(h,{readOnly:!0,domReadOnly:!0,originalEditable:!1,renderSideBySide:!1,renderMarginRevertIcon:!1,renderOverviewRuler:!1,enableSplitViewResizing:!1,isInEmbeddedEditor:!0,automaticLayout:!0,fontFamily:e.getOption(N.EditorOption.fontFamily),fontSize:e.getOption(N.EditorOption.fontSize),lineHeight:u,minimap:{enabled:!1},glyphMargin:!1,folding:!1,scrollBeyondLastLine:!1,fixedOverflowWidgets:!0,hideUnchangedRegions:{enabled:!0,minimumLineCount:0,contextLineCount:2,revealLineCount:3}});y.diffEditor=r,r.setModel({original:t,modified:n}),r.onDidUpdateDiff(()=>l(y)),l(y)}),e.revealLineInCenter(Math.max(1,Math.min(n.getLineCount(),s.modifiedStartLineNumber)))},d=e.onMouseDown(e=>{if(!e.event.leftButton||e.target.type!==N.MouseTargetType.GUTTER_LINE_DECORATIONS||e.target.position===null)return;let t=e.target.position.lineNumber,r=sr(i,t,n.getLineCount(),hr(e.target.element));r&&(e.event.preventDefault(),e.event.stopPropagation(),u(t,r))});return{update(t){if(i=t,!a)return;let r=a,o=sr(t,r.anchorLine,n.getLineCount());if(!o){c();return}r.change=o,r.zone.afterLineNumber=cr(o,n.getLineCount()),r.zone.heightInPx=pr+lr(o)*e.getOption(N.EditorOption.lineHeight);try{e.changeViewZones(e=>e.layoutZone(r.zoneId))}catch{c();return}l(r)},dispose(){o=!0,d.dispose(),c()}}}var _r={added:`puddle-dirty-added`,modified:`puddle-dirty-modified`,"deleted-before":`puddle-dirty-deleted-before`,"deleted-after":`puddle-dirty-deleted-after`};function vr(e,t,r,i){let o=n(),s=de(e,t,{root:r,enabled:o.data!==void 0&&a(o.data.protocol)&&i!==null}),[c,l]=(0,L.useState)(null),u=(0,L.useCallback)(e=>{l(e)},[]);return(0,L.useEffect)(()=>{let e=s.data;if(!c||!i||!e||e.repository===null||e.ignored||e.binary)return;let n=document.createElement(`div`);n.className=`puddle-hidden-diff-controller`,document.body.appendChild(n);let r=N.createModel(e.exists?e.content??``:``,i.getLanguageId()),a=N.createDiffEditor(n,{readOnly:!0,automaticLayout:!1,renderSideBySide:!1,minimap:{enabled:!1}}),o=c.createDecorationsCollection();a.setModel({original:r,modified:i});let l=gr({editor:c,original:r,modified:i,path:t}),u=()=>{let e=a.getLineChanges();e&&(l.update(e),o.set(fr(e,i.getLineCount()).map(e=>({range:new j(e.startLineNumber,1,e.endLineNumber,1),options:{isWholeLine:!0,linesDecorationsClassName:_r[e.kind]}}))))},d=a.onDidUpdateDiff(u);return u(),()=>{d.dispose(),l.dispose(),o.clear(),a.setModel(null),a.dispose(),r.dispose(),n.remove()}},[c,i,s.data]),u}function yr({message:e,session:t,path:n,root:r,download:i}){return(0,R.jsxs)(`div`,{className:`flex h-full flex-col items-center justify-center gap-3 bg-ground text-sm text-fg-muted`,children:[(0,R.jsx)(`span`,{children:e}),i&&(0,R.jsxs)(`button`,{type:`button`,onClick:()=>void me(t,n,r).catch(e=>I.error(e instanceof Error?e.message:`Download failed`)),className:`flex items-center gap-1.5 text-fg-secondary transition-colors hover:text-fg`,children:[(0,R.jsx)(Ce,{className:`size-4`}),`Download`]})]})}function br({session:e,path:t,reveal:n,root:r,focused:i=!0,scrollDriver:a=!1,scrollReceiver:o=!1,scrollChannel:s=`profile`}){let c=C(),l=Rn([e,r,t]),u=or(e,t,n,r,{focused:i}),d=pe(e,t,r),f=vr(e,t,r,u.model),p=(0,L.useMemo)(()=>getComputedStyle(document.documentElement).getPropertyValue(`--font-mono`).trim()||void 0,[]),[m,h]=(0,L.useState)(null),g=(0,L.useMemo)(()=>({session:e,path:t,root:r}),[e,t,r]),_=u.conflict!==null&&u.conflict.phase!==`unresolved`;if((0,L.useEffect)(()=>{if(!(!m||!u.model||_))return $n(m,{channel:s,target:g,driver:a,receiver:o},N.ScrollType.Immediate)},[m,u.model,_,s,g,a,o]),(0,L.useEffect)(()=>{let e=u.model;e&&N.setModelMarkers(e,`puddle-compilation`,d.map(t=>{let n=Math.min(t.line,e.getLineCount()),r=e.getLineMaxColumn(n),i=Math.min(t.column??1,r),a=t.end_line??n,o=Math.max(n,Math.min(a,e.getLineCount())),s=e.getLineMaxColumn(o),c=Math.min(t.end_column??(t.column?i+1:s),s);return{severity:t.severity===`error`?A.Error:t.severity===`warning`?A.Warning:A.Info,message:t.message,source:`Puddle compilation`,startLineNumber:n,startColumn:i,endLineNumber:o,endColumn:Math.max(i,c)}}))},[u.model,d]),u.conflict&&u.conflict.phase!==`unresolved`)return(0,R.jsx)(Vn,{session:e,path:t,buffer:u,focused:i});if(u.status===`binary`)return(0,R.jsx)(yr,{message:`Binary file — use Download`,session:e,path:t,root:r,download:!0});if(u.status===`too-large`)return(0,R.jsx)(yr,{message:`File too large to edit — use Download`,session:e,path:t,root:r,download:!0});if(u.status===`error`)return(0,R.jsx)(yr,{message:u.errorMessage??`Failed to load file`,session:e,path:t,root:r});let v=u.peerBadge===`saved-elsewhere`?`Saved in another window`:u.peerBadge===`dirty-elsewhere`?`Also being edited in another window`:null;return(0,R.jsxs)(`div`,{className:`flex h-full flex-col bg-ground`,children:[u.restoredNotice&&(0,R.jsxs)(`div`,{className:`flex items-center gap-3 bg-elevated px-3 py-1.5 text-xs text-fg-secondary`,children:[(0,R.jsx)(`span`,{children:`Restored unsaved changes`}),(0,R.jsx)(`button`,{type:`button`,onClick:u.discardRestore,className:`text-fg-muted transition-colors hover:text-fg`,children:`Discard`})]}),v&&(0,R.jsx)(`div`,{className:`bg-surface px-3 py-1 text-xs text-fg-muted`,children:v}),(0,R.jsx)(`div`,{className:`min-h-0 flex-1`,children:u.model&&(0,R.jsx)(Et,{path:u.model.uri.toString(),defaultValue:u.model.getValue(),theme:`puddle`,keepCurrentModel:!0,saveViewState:!1,onMount:e=>{l(e),u.onMount(e),f(e),h(e)},loading:(0,R.jsx)(`div`,{className:`p-3 text-xs text-fg-muted`,children:`…`}),options:{automaticLayout:!0,fontFamily:p,fontSize:c.editorFontSize,...jn(c.editorTabSize),wordWrap:c.editorWordWrap?`on`:`off`,minimap:{enabled:!1},glyphMargin:!1,lineDecorationsWidth:10,fixedOverflowWidgets:!0,scrollBeyondLastLine:!1}})})]})}function z({children:e}){return(0,R.jsx)(`div`,{className:`flex h-full items-center justify-center px-4 text-xs text-fg-muted`,children:e})}function xr(e,t){let n=(0,L.useRef)(t);n.current=t,(0,L.useEffect)(()=>(wt(e),()=>{n.current?.(),kt(e)}),[e])}function Sr(e,t,n,r){let i=r.split(`/`).map(encodeURIComponent).join(`/`);return`${e}://${encodeURIComponent(t)}/${encodeURIComponent(n)}/${i}`}function Cr({session:e,refName:t,path:n,content:r}){let i=C(),a=Rn([e,t,n]),o=(0,L.useMemo)(()=>getComputedStyle(document.documentElement).getPropertyValue(`--font-mono`).trim()||void 0,[]);return(0,R.jsx)(Et,{path:Sr(`puddle-view`,e,t,n),defaultValue:r,theme:Tt,saveViewState:!1,onMount:a,loading:(0,R.jsx)(z,{children:`…`}),options:{readOnly:!0,automaticLayout:!0,fontFamily:o,fontSize:i.editorFontSize,...jn(i.editorTabSize),minimap:{enabled:!1},fixedOverflowWidgets:!0,scrollBeyondLastLine:!1}})}function wr({session:e,against:t,path:n,root:r,indexBase:i=!1}){let a=_e(e,t,n,{root:r,enabled:!i}),o=ue(e,n,{root:r,enabled:i}),s=i?o:a;return s.isPending?(0,R.jsx)(z,{children:`…`}):s.error?(0,R.jsx)(z,{children:s.error instanceof Error?s.error.message:`Failed to load`}):s.data.binary?(0,R.jsx)(z,{children:`Binary file — deleted`}):(0,R.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,R.jsx)(`div`,{className:`bg-surface px-4 py-1 text-xs text-fg-muted`,children:`Deleted`}),(0,R.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,R.jsx)(Cr,{session:e,refName:`${t}:${r??``}`,path:n,content:s.data.content??``})})]})}function Tr({session:e,against:t,path:n,basePath:r,root:i,indexBase:a=!1,focused:o=!0}){let s=C(),c=zn([e,i,t,a,n]),l=or(e,n,null,i,{focused:o}),u=_e(e,t,r,{root:i,enabled:!a}),d=ue(e,r,{root:i,enabled:a}),f=a?d:u,p=(0,L.useRef)(null);xr(Nt(e,n,i),()=>{let e=p.current;if(!e)return;let t=e.getModel();e.setModel(null),t?.original.dispose(),p.current=null});let m=(0,L.useRef)(l.save);m.current=l.save;let h=(0,L.useMemo)(()=>getComputedStyle(document.documentElement).getPropertyValue(`--font-mono`).trim()||void 0,[]),g=f.error instanceof re&&f.error.status===404;return l.conflict&&l.conflict.phase!==`unresolved`?(0,R.jsx)(Vn,{session:e,path:n,buffer:l,focused:o}):l.status===`binary`||f.data?.binary?(0,R.jsx)(z,{children:`Binary file`}):l.status===`too-large`?(0,R.jsx)(z,{children:`File too large to show`}):l.status===`error`?(0,R.jsx)(z,{children:l.errorMessage??`Failed to load file`}):g||a&&d.data&&!d.data.exists?(0,R.jsx)(br,{session:e,path:n,reveal:null,root:i,focused:o}):f.isPending||!l.model?(0,R.jsx)(z,{children:`…`}):f.error?(0,R.jsx)(z,{children:f.error instanceof Error?f.error.message:`Failed to load base`}):(0,R.jsx)(At,{modifiedModelPath:l.model.uri.toString(),originalModelPath:Sr(`puddle-base`,e,`${t}:${i??``}`,r),original:f.data.content??``,language:l.model.getLanguageId(),theme:Tt,keepCurrentModifiedModel:!0,loading:(0,R.jsx)(z,{children:`…`}),onMount:e=>{c(e),p.current=e,e.onDidDispose(()=>{p.current=null}),e.getModifiedEditor().addCommand(M.CtrlCmd|P.KeyS,()=>m.current())},options:{readOnly:!1,originalEditable:!1,renderSideBySide:!0,automaticLayout:!0,fontFamily:h,fontSize:s.editorFontSize,...jn(s.editorTabSize),wordWrap:s.editorWordWrap?`on`:`off`,minimap:{enabled:!1},fixedOverflowWidgets:!0,scrollBeyondLastLine:!1}})}function Er({session:e,against:t,entry:n,root:r}){let i=C(),a=zn([e,r,t,`staged`,n.path]),o=n.old_path??n.path,s=_e(e,t,o,{root:r,enabled:n.status!==`added`}),c=ue(e,n.path,{root:r,enabled:n.status!==`deleted`}),l=(0,L.useMemo)(()=>getComputedStyle(document.documentElement).getPropertyValue(`--font-mono`).trim()||void 0,[]);if(n.status===`deleted`)return(0,R.jsx)(wr,{session:e,against:t,path:o,root:r});if(c.isPending||n.status!==`added`&&s.isPending)return(0,R.jsx)(z,{children:`…`});if(c.error||s.error){let e=c.error??s.error;return(0,R.jsx)(z,{children:e instanceof Error?e.message:`Failed to load staged content`})}return c.data.binary||s.data?.binary?(0,R.jsx)(z,{children:`Binary file`}):n.status===`added`?(0,R.jsx)(Cr,{session:e,refName:`index:${r??``}`,path:n.path,content:c.data.content??``}):s.data?(0,R.jsx)(At,{originalModelPath:Sr(`puddle-head`,e,`${t}:${r??``}`,o),modifiedModelPath:Sr(`puddle-index`,e,`${t}:${r??``}`,n.path),original:s.data.content??``,modified:c.data.content??``,onMount:a,theme:Tt,loading:(0,R.jsx)(z,{children:`…`}),options:{readOnly:!0,originalEditable:!1,renderSideBySide:!0,automaticLayout:!0,fontFamily:l,fontSize:i.editorFontSize,...jn(i.editorTabSize),wordWrap:i.editorWordWrap?`on`:`off`,minimap:{enabled:!1},fixedOverflowWidgets:!0,scrollBeyondLastLine:!1}}):(0,R.jsx)(z,{children:`Failed to load HEAD content`})}function Dr({session:e,path:t,root:n,focused:r}){return xr(Nt(e,t,n)),(0,R.jsx)(br,{session:e,path:t,reveal:null,root:n,focused:r})}function Or({session:e,against:t,entry:n,root:r,area:i,focused:a=!0}){if(i===`staged`)return(0,R.jsx)(Er,{session:e,against:t,entry:n,root:r});switch(n.status){case`added`:return(0,R.jsx)(Dr,{session:e,path:n.path,root:r,focused:a});case`deleted`:return(0,R.jsx)(wr,{session:e,against:t,path:n.path,root:r,indexBase:i===`unstaged`});case`modified`:case`renamed`:return(0,R.jsx)(Tr,{session:e,against:t,path:n.path,basePath:n.old_path??n.path,root:r,indexBase:i===`unstaged`,focused:a});default:return null}}function kr({session:e,sha:t,path:n,root:r}){let i=_e(e,t,n,{root:r});return i.isPending?(0,R.jsx)(z,{children:`…`}):i.error?(0,R.jsx)(z,{children:i.error instanceof Error?i.error.message:`Failed to load file`}):i.data.binary?(0,R.jsx)(z,{children:`Binary file`}):(0,R.jsx)(Cr,{session:e,refName:`${t}:${r??``}`,path:n,content:i.data.content??``})}function Ar({session:e,originalRef:t,originalPath:n,originalContent:r,modifiedRef:i,modifiedPath:a,modifiedContent:o,root:s}){let c=C(),l=zn([e,s,t,n,i,a]),u=(0,L.useRef)(null),d=(0,L.useMemo)(()=>getComputedStyle(document.documentElement).getPropertyValue(`--font-mono`).trim()||void 0,[]);return(0,L.useEffect)(()=>()=>{let e=u.current;if(!e)return;let t=e.getModel();e.setModel(null),t?.original.dispose(),t?.modified.dispose(),u.current=null},[]),(0,R.jsx)(At,{originalModelPath:Sr(`puddle-hist-orig`,e,`${t}:${s??``}`,n),modifiedModelPath:Sr(`puddle-hist-mod`,e,`${i}:${s??``}`,a),original:r,modified:o,theme:Tt,keepCurrentOriginalModel:!0,keepCurrentModifiedModel:!0,loading:(0,R.jsx)(z,{children:`…`}),onMount:e=>{l(e),u.current=e,e.onDidDispose(()=>{u.current=null})},options:{readOnly:!0,originalEditable:!1,renderSideBySide:!0,automaticLayout:!0,fontFamily:d,fontSize:c.editorFontSize,...jn(c.editorTabSize),minimap:{enabled:!1},fixedOverflowWidgets:!0,scrollBeyondLastLine:!1}})}function jr({session:e,sha:t,path:n,basePath:r,root:i}){let a=_e(e,`${t}^`,r,{root:i}),o=_e(e,t,n,{root:i});return a.error instanceof re&&a.error.status===404?(0,R.jsx)(kr,{session:e,sha:t,path:n,root:i}):a.isPending||o.isPending?(0,R.jsx)(z,{children:`…`}):a.error?(0,R.jsx)(z,{children:a.error instanceof Error?a.error.message:`Failed to load original`}):o.error?(0,R.jsx)(z,{children:o.error instanceof Error?o.error.message:`Failed to load file`}):a.data.binary||o.data.binary?(0,R.jsx)(z,{children:`Binary file`}):(0,R.jsx)(Ar,{session:e,originalRef:`${t}^`,originalPath:r,originalContent:a.data.content??``,modifiedRef:t,modifiedPath:n,modifiedContent:o.data.content??``,root:i})}function Mr({session:e,sha:t,entry:n,isRootCommit:r,root:i}){switch(le(n.status,r)){case`added`:return(0,R.jsx)(kr,{session:e,sha:t,path:n.path,root:i});case`deleted`:return(0,R.jsx)(wr,{session:e,against:`${t}^`,path:n.path,root:i});case`modified`:case`renamed`:return(0,R.jsx)(jr,{session:e,sha:t,path:n.path,basePath:n.old_path??n.path,root:i});default:return null}}function Nr({session:e,sha:t,path:n,root:r}){let i=ge(e,t,r);if(i.isPending)return(0,R.jsx)(`div`,{className:`px-4 py-3 text-xs text-fg-muted`,children:`Loading commit…`});if(i.error)return(0,R.jsx)(`div`,{className:`px-4 py-3 text-xs text-fg-muted`,children:i.error instanceof Error?i.error.message:`Failed to load commit`});let a=i.data.files.find(e=>e.path===n);return a?(0,R.jsx)(`div`,{className:`h-full`,children:(0,R.jsx)(Mr,{session:e,sha:t,entry:a,isRootCommit:i.data.parents.length===0,root:r})}):(0,R.jsxs)(`div`,{className:`flex h-full items-center justify-center px-4 text-center text-xs text-fg-muted`,children:[(0,R.jsx)(`span`,{className:`text-fg-secondary`,children:n}),` is not part of`,` `,(0,R.jsx)(`span`,{className:`font-mono`,children:t.slice(0,7)}),`.`]})}function Pr({session:e,path:t,root:n,area:r,focused:i=!0}){let a=ve(e,{root:n,against:r===void 0?`base`:`head`,area:r});if(a.isPending)return(0,R.jsx)(`div`,{className:`px-4 py-3 text-xs text-fg-muted`,children:`Loading diff…`});if(a.error)return(0,R.jsx)(`div`,{className:`px-4 py-3 text-xs text-fg-muted`,children:a.error instanceof Error?a.error.message:`Failed to load diff`});let o=a.data.entries.find(e=>e.path===t);return o?(0,R.jsx)(`div`,{className:`h-full`,children:(0,R.jsx)(Or,{session:e,against:a.data.against,entry:o,root:n,area:r,focused:i})}):(0,R.jsxs)(`div`,{className:`flex h-full items-center justify-center px-4 text-center text-xs text-fg-muted`,children:[`No changes to `,(0,R.jsx)(`span`,{className:`mx-1 text-fg-secondary`,children:t}),` against the base.`]})}var Fr=800;function Ir({name:e}){let t=C(),n=ae(),r=Rn([n,e]),a=he(n,e),o=i(),s=oe(`editor.save`),c=(0,L.useRef)(null),l=(0,L.useRef)(null),u=(0,L.useMemo)(()=>getComputedStyle(document.documentElement).getPropertyValue(`--font-mono`).trim()||void 0,[]);if((0,L.useEffect)(()=>{if(n===null)return;let t=St(t=>{ce(n,e,t).catch(e=>I.error(e instanceof Error?e.message:`Draft not saved`))},Fr);return l.current=t,()=>{t.flush(),l.current=null}},[n,e]),n===null)return null;if(a.error)return(0,R.jsx)(`div`,{className:`flex h-full items-center justify-center bg-ground text-sm text-fg-muted`,children:a.error instanceof Error?a.error.message:`Failed to load the draft`});if(a.data===void 0)return(0,R.jsx)(`div`,{className:`p-3 text-xs text-fg-muted`,children:`…`});let d=()=>{let t=c.current;t&&(l.current?.flush(),Le({name:e,content:t.getValue()}))};return(0,R.jsxs)(`div`,{className:`flex h-full flex-col bg-ground`,children:[(0,R.jsxs)(`div`,{className:`bg-surface px-3 py-1 text-xs text-fg-muted`,children:[`Draft — not in any worktree; `,s,` saves it into one`]}),(0,R.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,R.jsx)(Et,{path:`puddle-untitled://${n}/${e}`,defaultValue:a.data.content,theme:Tt,keepCurrentModel:!1,saveViewState:!1,loading:(0,R.jsx)(`div`,{className:`p-3 text-xs text-fg-muted`,children:`…`}),onMount:t=>{r(t),c.current=t,xe(e,t.getValue()),nr(t,{onSave:d})},onChange:t=>{let r=t??``;xe(e,r),Re(o,n,e,r),l.current?.(r)},options:{automaticLayout:!0,fontFamily:u,fontSize:t.editorFontSize,...jn(t.editorTabSize),minimap:{enabled:!1},fixedOverflowWidgets:!0,scrollBeyondLastLine:!1,wordWrap:t.editorWordWrap?`on`:`off`}})})]})}var Lr=d([y(),h(y())]),Rr=_(y(),m()),zr=f({output_type:y(),text:Lr.optional(),data:_(y(),m()).optional(),traceback:h(y()).optional(),ename:y().optional(),evalue:y().optional()}),Br=f({id:y().optional(),cell_type:b([`code`,`markdown`,`raw`]),metadata:Rr,source:Lr,outputs:h(zr).optional(),execution_count:u().int().nullable().optional()}),Vr=f({nbformat:v(4),nbformat_minor:u().int().nonnegative(),metadata:Rr,cells:h(Br).max(2e3)});function Hr(e){if(e.length>5*1024*1024)throw Error(`This notebook exceeds the 5 MiB editor limit.`);let t;try{t=JSON.parse(e)}catch{throw Error(`This notebook is not valid JSON. Switch to source to repair it.`)}let n=Vr.safeParse(t);if(!n.success)throw Error(`Expected a version 4 notebook with at most 2,000 valid cells. Switch to source to inspect it.`);return n.data}function B(e){return typeof e==`string`?e:Array.isArray(e)&&e.every(e=>typeof e==`string`)?e.join(``):``}function Ur(e,t,n){return{...e,cells:e.cells.map((e,r)=>r===t?{...e,source:n.match(/[^\n]*\n|[^\n]+$/g)??[],...e.cell_type===`code`&&e.outputs?.length&&!e.metadata.puddle_execution?{metadata:{...e.metadata,puddle_execution:{id:`saved`,revision:0,source:B(e.source),state:`saved`}}}:{}}:e)}}function Wr(e){let t=new Set;return{...e,cells:e.cells.map((n,r)=>{let i=n.id;if(!i||t.has(i))for(i=`puddle-${r}`;t.has(i)||e.cells.some(e=>e.id===i);)i+=`-`;return t.add(i),n.id===i?n:{...n,id:i}})}}function Gr(e,t){if(e.cell_type!==`code`)return e.cell_type===`raw`?`plaintext`:`markdown`;let n=e.metadata.vscode,r=t.metadata.language_info,i=t.metadata.kernelspec,a=n?.languageId??r?.name??i?.language??`python`;return typeof a==`string`?a:`python`}function Kr(e,t){let n=t===`markdown`||t===`raw`?t:`code`,r={...e,cell_type:n};return n===`code`?(r.metadata={...e.metadata,vscode:{...e.metadata.vscode??{},languageId:t}},r.outputs??=[],r.execution_count??=null):(delete r.outputs,delete r.execution_count),r}function qr(e){return{id:crypto.randomUUID(),cell_type:e,metadata:{},source:[],...e===`code`?{outputs:[],execution_count:null}:{}}}function Jr(e){return(e.output_type===`error`?e.traceback?.join(`
|
|
3
|
+
`)??`${e.ename??`Error`}: ${e.evalue??``}`:B(e.text??e.data?.[`text/plain`])).replace(/\u001b\[[0-?]*[ -/]*[@-~]/g,``)}function Yr(e,t){let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n++;let r=e.length,i=t.length;for(;r>n&&i>n&&e[r-1]===t[i-1];)r--,i--;return{start:n,end:r,text:t.slice(n,i)}}function Xr(e){return{...e,cells:e.cells.map(e=>e.cell_type===`code`?{...e,outputs:[],execution_count:null}:e)}}function Zr(e){return e.cells.map((e,t)=>{let n=B(e.source).split(`
|
|
4
|
+
`).find(e=>e.trim())?.trim()??``;return{index:t,level:e.cell_type===`markdown`?/^(#{1,6})\s/.exec(n)?.[1]?.length??0:0,label:(e.cell_type===`markdown`?n.replace(/^#{1,6}\s+/,``):n).slice(0,100)||`${e.cell_type===`code`?`Code`:e.cell_type===`markdown`?`Markdown`:`Raw`} cell`}})}function Qr(e,t){let n=Zr(e),r=n[t]?.level;if(!r)return[t];let i=n.find(e=>e.index>t&&e.level>0&&e.level<=r);return Array.from({length:(i?.index??e.cells.length)-t},(e,n)=>t+n)}function $r(e,t){let n=!1,r=new Map(t.cells.map(e=>[e.id,e])),i=e.cells.map(e=>{let i=r.get(e.id);if(e.cell_type!==`code`||!i||i.state===`queued`)return e;let a=e.metadata.puddle_execution;return a?.id===t.id&&typeof a.revision==`number`&&a.revision>=i.revision||i.state===`cancelled`&&i.elapsed_ms===void 0?e:(n=!0,{...e,outputs:i.outputs,execution_count:i.execution_count,metadata:{...e.metadata,puddle_execution:{id:t.id,revision:i.revision,source:i.source,state:i.state,elapsed_ms:i.elapsed_ms}}})});return n?{...e,cells:i}:e}function ei(e){let t=e.metadata.puddle_execution;if(!(!t||typeof t!=`object`||!(`source`in t)||typeof t.source!=`string`||!(`state`in t)||typeof t.state!=`string`))return{source:t.source,state:t.state===`running`||t.state===`queued`?`saved`:t.state,...`elapsed_ms`in t&&typeof t.elapsed_ms==`number`?{elapsed_ms:t.elapsed_ms}:{}}}function ti({notebook:e,active:t,selected:n,update:r,choose:i,setEditing:a,run:o,onUndo:s,onRedo:c}){let l=(n,a=e.cells.findIndex(e=>e.id===t)+1)=>{if(e.cells.length>=2e3)return;let o=qr(n),s=[...e.cells];s.splice(t===null?s.length:a,0,o),r({...e,cells:s}),i(o.id,!0)},u=(t,n)=>r({...e,cells:e.cells.map((e,r)=>r===t?n:e)}),d=(t,n)=>{e.cells[t]?.cell_type===`code`&&o([t]),a(null),n===`insert`||n===`next`&&t===e.cells.length-1?l(e.cells[t].cell_type,t+1):n===`next`&&i(e.cells[t+1].id)};return{add:l,replace:u,execute:d,operation:(t,n)=>{let a=[...e.cells],o=a[t];if(n===`insert`){l(`code`,t+1);return}if(n===`clear`){u(t,{...o,outputs:[],execution_count:null});return}if(n===`delete`&&(a.splice(t,1),a.length&&i(a[Math.min(t,a.length-1)].id)),n===`up`||n===`down`){let e=t+(n===`up`?-1:1);if(e<0||e>=a.length)return;[a[t],a[e]]=[a[e],o],i(o.id)}if(n===`duplicate`){if(a.length>=2e3)return;let e={...structuredClone(o),id:crypto.randomUUID()};a.splice(t+1,0,e),i(e.id,!0)}if(n===`merge`){let e=a[t+1];if(!e||e.cell_type!==o.cell_type)return;a[t]={...o,source:`${B(o.source)}\n${B(e.source)}`},a.splice(t+1,1),i(o.id,!0)}r({...e,cells:a})},keyDown:f=>{if(f.target.closest(`.monaco-editor,input,textarea,[role=dialog],[role=menu],[cmdk-root]`))return;let p=e.cells.findIndex(e=>e.id===t);if((f.metaKey||f.ctrlKey)&&f.key.toLowerCase()===`z`){f.preventDefault(),f.shiftKey?c?.():s?.();return}if(f.key===`Enter`&&(f.metaKey||f.ctrlKey)&&n.length>1){f.preventDefault(),o(e.cells.flatMap((e,t)=>n.includes(e.id)?[t]:[]));return}if(f.key===`Enter`&&p>=0)f.preventDefault(),f.metaKey||f.ctrlKey||f.shiftKey||f.altKey?d(p,f.shiftKey?`next`:f.altKey?`insert`:`stay`):a(t);else if(f.key===`ArrowDown`||f.key===`ArrowUp`){f.preventDefault();let t=Math.max(0,Math.min(e.cells.length-1,p+(f.key===`ArrowDown`?1:-1)));e.cells[t]&&i(e.cells[t].id,!1,f.shiftKey)}else!f.metaKey&&!f.ctrlKey&&!f.altKey&&((f.key===`a`||f.key===`b`)&&(f.preventDefault(),l(`code`,Math.max(0,p+ +(f.key===`b`)))),(f.key===`m`||f.key===`y`)&&p>=0&&(f.preventDefault(),u(p,Kr(e.cells[p],f.key===`m`?`markdown`:`python`))),(f.key===`Delete`||f.key===`Backspace`)&&(f.preventDefault(),r({...e,cells:e.cells.filter(e=>!n.includes(e.id))})))}}}function ni(e,t,n,r,i){if(!(e.target.closest(`.monaco-editor,input,textarea`)||!r.length)&&!(t!==`paste`&&window.getSelection()?.toString()))if(t===`paste`){let t=e.clipboardData.getData(`text/plain`);if(t.length>5*1024*1024)return;try{let a=JSON.parse(t);if(!a||typeof a!=`object`||!(`puddle_notebook_cells`in a))return;let o=Hr(JSON.stringify({nbformat:4,nbformat_minor:5,metadata:{},cells:a.puddle_notebook_cells})).cells;if(e.preventDefault(),n.cells.length+o.length>2e3){I.error(`A notebook can contain at most 2,000 cells`);return}let s=[...n.cells],c=Math.max(...s.flatMap((e,t)=>r.includes(e.id)?[t]:[]));s.splice(c+1,0,...o.map(e=>({...e,id:crypto.randomUUID()}))),i({...n,cells:s})}catch{}}else{let a=n.cells.filter(e=>r.includes(e.id));e.clipboardData.setData(`text/plain`,JSON.stringify({puddle_notebook_cells:a})),e.preventDefault(),t===`cut`&&i({...n,cells:n.cells.filter(e=>!r.includes(e.id))})}}function ri({controls:e}){return e.open?(0,R.jsx)(nt,{query:e.query,focusKey:e.focusKey,options:e.options,result:e.result,onQueryChange:e.setQuery,onOptionsChange:e.setOptions,onNext:e.next,onPrevious:e.previous,onClose:e.close}):null}function ii(e,t){return Math.min(t,Math.max(1,Math.floor(e)))}function ai({notebook:e,focused:t,onReveal:n,onChange:r}){let[i,a]=(0,L.useState)(!1),[o,s]=(0,L.useState)(``),c=(0,L.useRef)(null),l=(0,L.useRef)([]),u=(0,L.useRef)(-1),d=(0,L.useRef)(!1),f=Qe({shortcutEnabled:t,onFind:(t,r,a)=>{let o=c.current;if(a===`reset`){l.current=[],u.current=-1;for(let n of e.cells){let e=[{text:B(n.source),output:!1},...i?[{text:(n.outputs??[]).map(Jr).join(`
|
|
5
|
+
`),output:!0}]:[]];for(let i of e){let e=tt(i.text,t,r,Math.max(0,1e3-l.current.length));if(e.invalid)return{index:-1,count:0,invalid:!0};if(l.current.push(...e.matches.map(e=>({...e,id:n.id,output:i.output}))),l.current.length>=1e3)break}if(l.current.length>=1e3)break}if(d.current&&o){let e=l.current.findIndex(e=>e.id===o.id&&e.output===o.output&&e.start>=o.start);u.current=e>=0?e-1:-1}}let s=l.current.length;return u.current=s?(u.current+(a===`previous`?-1:1)+s)%s:-1,c.current=l.current[u.current]??null,d.current||n(c.current),{index:u.current,count:s,limited:s>=1e3}},onClear:()=>{c.current=null,n(null)}});(0,L.useEffect)(()=>{f.refresh()},[i,f.refresh]);let p=t=>{let n=$e(f.query,f.options);if(!n||!r)return;let i=e;e.cells.forEach((e,r)=>{let a=B(e.source),s=c.current;t?i=Ur(i,r,a.replace(n,o)):s&&!s.output&&s.id===e.id&&(i=Ur(i,r,a.slice(0,s.start)+a.slice(s.start,s.end).replace(n,o)+a.slice(s.end)))}),r(i),l.current=[],c.current=null};return(0,L.useEffect)(()=>{d.current=c.current!==null,f.open&&f.refresh(),d.current=!1},[e,f.open,f.refresh]),(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(ri,{controls:f}),f.open&&(0,R.jsxs)(`div`,{className:`absolute right-2 top-10 z-30 flex max-w-full flex-wrap items-center gap-2 rounded-b-md bg-surface px-2 py-1.5 text-xs text-fg-secondary`,children:[(0,R.jsxs)(`label`,{className:`flex cursor-pointer items-center gap-1`,children:[(0,R.jsx)(`input`,{type:`checkbox`,checked:i,onChange:e=>a(e.target.checked)}),`Include output`]}),r&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`input`,{"aria-label":`Replace in notebook`,value:o,onChange:e=>s(e.target.value),placeholder:`Replace`,className:`min-w-0 bg-ground px-2 py-1 outline-none`}),(0,R.jsx)(`button`,{type:`button`,className:`cursor-pointer hover:text-fg`,disabled:!f.query||!!c.current?.output,onClick:()=>p(!1),children:`Replace`}),(0,R.jsx)(`button`,{type:`button`,className:`cursor-pointer hover:text-fg`,disabled:!f.query,onClick:()=>p(!0),children:`Replace all`})]})]})]})}function oi(e){return r({queryKey:[`notebook-kernels`],queryFn:()=>F(`GET`,`/api/notebooks/kernels`),enabled:e,staleTime:3e4})}function si(e,t){return r({queryKey:[`notebook-kernel`,e],queryFn:()=>F(`POST`,`/api/notebooks/status`,{source:e}),enabled:t,refetchInterval:1500,retry:!1})}function ci(e){return F(`POST`,`/api/notebooks/kernel`,e)}function li(e,t){return r({queryKey:[`notebook-environments`,e],queryFn:()=>F(`POST`,`/api/notebooks/environments`,{source:e}),enabled:t,staleTime:3e4,retry:!1})}function ui(e,t,a,c){let l=n(),u=c&&!g()&&o(l.data?.protocol),d=(0,L.useRef)({notebook:t,onChange:a});d.current={notebook:t,onChange:a};let f=i(),[p,m]=(0,L.useState)(!1),h=(0,L.useRef)(!1),[_,v]=(0,L.useState)(null),y=(0,L.useRef)(!0);(0,L.useEffect)(()=>(y.current=!0,()=>{y.current=!1}),[]);let b=[`notebook-execution`,e],x=r({queryKey:b,queryFn:()=>F(`POST`,`/api/notebooks/execution`,{source:e}),enabled:u,retry:!1,refetchInterval:e=>e.state.data?.execution?.state===`running`?250:1500}),S=x.data?.execution;(0,L.useEffect)(()=>{if(!S||!d.current.notebook||!d.current.onChange)return;let e=$r(d.current.notebook,S);e!==d.current.notebook&&d.current.onChange(e)},[S]);let C=async t=>{let n=d.current.notebook;if(!u||!n||h.current||S?.state===`running`)return;let r=n.cells.flatMap((e,n)=>e.cell_type===`code`&&B(e.source).trim()&&(!t||t.includes(n))?[{id:e.id,source:B(e.source)}]:[]);if(r.length){h.current=!0,m(!0),v(null),d.current.onChange?.(n);try{let t=n.metadata.kernelspec,i=await F(`POST`,`/api/notebooks/execute`,{source:e,cells:r,...t?.name?{kernel:t.name}:{}});y.current&&f.setQueryData(b,i)}catch(e){y.current&&v(e instanceof Error?e.message:`Notebook execution failed`)}finally{h.current=!1,y.current&&(m(!1),f.invalidateQueries({queryKey:b}))}}},w=(0,L.useRef)(C);return w.current=C,(0,L.useEffect)(()=>u?we(e,()=>{w.current()}):void 0,[u,e.session,e.path,e.root]),{supported:u,intelligenceSupported:u&&s(l.data?.protocol),run:C,interrupt:async()=>{try{await ci({source:e,action:`interrupt`})}catch(e){y.current&&v(e instanceof Error?e.message:`Interrupt failed`)}finally{f.invalidateQueries({queryKey:b})}},execution:S,busy:p||S?.state===`running`,error:_??(x.error instanceof Error?x.error.message:S?.error)}}var di=(0,L.createContext)(null);function fi({source:e,environment:t,current:n,kernels:r,pending:i,onAction:a}){let[o,s]=(0,L.useState)(!1),[c,l]=(0,L.useState)(``),u=(0,L.useId)(),d=li(e,o),f=[...d.data?.environments??[]];t&&!f.some(e=>e.python===t.python)&&f.unshift(t);let p=e=>{s(!1),a(e)};return(0,R.jsxs)(vt,{open:o,onOpenChange:s,children:[(0,R.jsx)(_t,{asChild:!0,children:(0,R.jsxs)(`button`,{type:`button`,disabled:i,"aria-label":`Select Python environment`,title:t?.python??`Changing environments starts a fresh kernel`,className:`flex max-w-64 cursor-pointer items-center gap-1.5 rounded-sm px-2 py-1.5 text-xs text-fg-secondary hover:bg-surface hover:text-fg disabled:cursor-default disabled:opacity-40`,children:[(0,R.jsx)(ln,{className:`size-3.5 shrink-0`}),(0,R.jsx)(`span`,{className:`truncate`,children:t?.label??n?.display_name??`Select environment`})]})}),(0,R.jsxs)(gt,{align:`end`,className:`w-96 max-w-[calc(100vw-2rem)] p-3`,children:[(0,R.jsx)(`p`,{className:`mb-2 text-xs text-fg-muted`,children:`Python environments on this host`}),(0,R.jsxs)(`div`,{className:`max-h-64 overflow-y-auto`,"aria-label":`Python environments`,children:[d.isLoading&&(0,R.jsx)(`p`,{role:`status`,className:`py-2 text-xs text-fg-muted`,children:`Looking for environments…`}),d.isError&&(0,R.jsx)(`p`,{role:`alert`,className:`py-2 text-xs text-danger`,children:`Couldn’t discover environments. You can enter a path below.`}),d.data&&!f.length&&(0,R.jsx)(`p`,{className:`py-2 text-xs text-fg-muted`,children:`No Python environments found. Enter a path below.`}),f.map(n=>(0,R.jsxs)(`button`,{type:`button`,disabled:i,onClick:()=>p({source:e,action:`select-python`,python:n.python}),className:`flex w-full cursor-pointer items-center gap-2 rounded-sm px-2 py-2 text-left hover:bg-surface disabled:cursor-default disabled:opacity-40`,children:[(0,R.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,R.jsx)(`p`,{className:`text-xs text-fg`,children:n.label}),(0,R.jsx)(`p`,{className:`break-all text-xs text-fg-muted`,children:n.python}),(n.error||!n.ipykernel||!n.nbconvert)&&(0,R.jsx)(`p`,{className:`text-xs text-fg-secondary`,children:n.error?`Couldn’t inspect this Python`:n.ipykernel?`nbconvert not installed`:`ipykernel not installed`})]}),t?.python===n.python&&(0,R.jsx)(Je,{className:`size-3.5 shrink-0 text-accent`})]},n.python)),r.length>0&&(0,R.jsx)(`p`,{className:`mb-1 mt-3 text-xs text-fg-muted`,children:`Registered Jupyter kernels`}),r.map(r=>(0,R.jsxs)(`button`,{type:`button`,disabled:i,className:`flex w-full cursor-pointer items-center justify-between rounded-sm px-2 py-2 text-left text-xs text-fg-secondary hover:bg-surface hover:text-fg`,onClick:()=>p({source:e,action:`select`,kernel:r.name}),children:[r.display_name,!t&&n?.name===r.name&&(0,R.jsx)(Je,{className:`size-3.5`})]},r.name))]}),(0,R.jsxs)(`form`,{className:`mt-3 flex flex-col gap-2`,onSubmit:t=>{t.preventDefault(),c.trim()&&p({source:e,action:`select-python`,python:c.trim()})},children:[(0,R.jsx)(`label`,{htmlFor:u,className:`text-xs text-fg-secondary`,children:`Environment folder or Python executable`}),(0,R.jsx)(Be,{id:u,value:c,onChange:e=>l(e.target.value),placeholder:`.venv, ~/miniforge3/envs/analysis, /path/to/python`,disabled:i}),(0,R.jsx)(`p`,{className:`text-xs text-fg-muted`,children:`Relative paths start beside this notebook. Switching starts fresh.`}),(0,R.jsx)(`button`,{type:`submit`,disabled:i||!c.trim(),className:`cursor-pointer self-end rounded-sm px-2 py-1.5 text-xs text-fg-secondary hover:bg-surface hover:text-fg disabled:cursor-default disabled:opacity-40`,children:`Use path`})]})]})]})}var pi=`flex cursor-pointer items-center gap-1.5 whitespace-nowrap rounded-sm px-2 py-1.5 text-xs text-fg-secondary transition-colors hover:bg-surface hover:text-fg disabled:cursor-default disabled:opacity-40`;function mi({source:e,notebook:t,onSelect:r}){let a=(0,L.useRef)(r);a.current=r;let o=(0,L.useRef)(!0);(0,L.useEffect)(()=>(o.current=!0,()=>{o.current=!1}),[]);let s=n(),u=c(s.data?.protocol),d=l(s.data?.protocol),f=oi(u),p=si(e,u),m=i(),[h,g]=(0,L.useState)(null),_=h!==null,[v,y]=(0,L.useState)(null);if(!u)return null;let b=t.metadata.kernelspec,x=p.data?.kernel??(typeof b?.name==`string`?b.name:``),S=f.data?.kernels??[],C=S.find(e=>e.name===x),w=p.data?.environment,ee=w&&!w.error?[!w.ipykernel&&`ipykernel`,!w.nbconvert&&`nbconvert`].filter(Boolean).join(` and `):``,T=p.data&&p.data.state!==`stopped`&&p.data.state!==`dead`,E=p.data?.state===`busy`||p.data?.state===`starting`,D=async t=>{g(t.action),y(null);try{let n=await ci(t);if(m.setQueryData([`notebook-kernel`,e],n),(t.action===`select-python`||t.action===`install-python`)&&(m.invalidateQueries({queryKey:[`notebook-environments`]}),o.current&&a.current({name:`python3`,display_name:`Python 3`,language:`python`})),t.action===`select`){let e=S.find(e=>e.name===t.kernel);e&&o.current&&a.current(e)}}catch(e){y(e instanceof Error?e.message:`Kernel operation failed`)}finally{g(null)}};return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(`div`,{className:`ml-auto flex items-center gap-1`,children:[E&&(0,R.jsxs)(`button`,{type:`button`,className:pi,disabled:_,onClick:()=>void D({source:e,action:`interrupt`}),children:[(0,R.jsx)(je,{className:`size-3.5`}),`Interrupt`]}),(0,R.jsx)(`span`,{className:`text-xs text-fg-muted`,role:`status`,children:_?h===`install-python`?`Installing…`:`Updating…`:p.data?.state===`dead`?`Kernel exited`:E?`Busy`:T?`Idle`:``}),d?(0,R.jsx)(fi,{source:e,environment:w,current:C,kernels:S,pending:_,onAction:D}):(0,R.jsxs)(Xe,{value:C?.name??``,disabled:_||!f.data?.available||S.length===0,onValueChange:t=>void D({source:e,action:`select`,kernel:t}),children:[(0,R.jsxs)(Ke,{className:`h-7 max-w-52 gap-1.5 bg-transparent text-xs hover:bg-surface`,"aria-label":`Select kernel`,title:`Kernels stay alive until shut down. Changing kernels starts fresh.`,children:[(0,R.jsx)(ln,{className:`size-3.5 shrink-0`}),(0,R.jsx)(Ge,{placeholder:x?`${x} (not installed)`:`Select Kernel`})]}),(0,R.jsx)(qe,{children:S.map(e=>(0,R.jsx)(Ye,{value:e.name,detail:e.language,children:(0,R.jsx)(`span`,{children:e.display_name})},e.name))})]}),(0,R.jsxs)(Ne,{children:[(0,R.jsx)(Ie,{asChild:!0,children:(0,R.jsx)(`button`,{type:`button`,className:pi,disabled:_,"aria-label":`Kernel actions`,children:(0,R.jsx)(Ee,{className:`size-3.5`})})}),(0,R.jsxs)(Te,{align:`end`,children:[(0,R.jsxs)(Se,{disabled:!C&&!w,onSelect:()=>void D({source:e,action:`restart`}),children:[(0,R.jsx)(it,{}),`Restart kernel`]}),(0,R.jsxs)(Se,{disabled:!T,onSelect:()=>void D({source:e,action:`shutdown`}),children:[(0,R.jsx)(ze,{}),`Shut down kernel`]})]})]})]}),ee&&(0,R.jsxs)(`div`,{className:`flex w-full flex-wrap items-center gap-2 px-2 text-xs text-fg-muted`,children:[(0,R.jsxs)(`span`,{className:`break-all`,children:[ee,` missing from `,w?.python,`.`]}),(0,R.jsxs)(`button`,{type:`button`,className:pi,disabled:_,onClick:()=>{w&&D({source:e,action:`install-python`,python:w.python})},children:[`Install `,ee]})]}),(v||p.data?.error||!d&&(f.data?.error||f.isError)||p.isError)&&(0,R.jsx)(`p`,{role:`alert`,className:`w-full px-2 text-xs text-danger`,children:v??p.data?.error??f.data?.error??`Couldn’t load notebook kernels`}),!d&&f.data&&!f.data.available&&!f.data.error&&(0,R.jsx)(`p`,{className:`w-full px-2 text-xs text-fg-muted`,children:`Install Jupyter and a language kernel on this host to run notebooks.`})]})}var hi=`flex cursor-pointer items-center gap-1.5 whitespace-nowrap rounded-sm px-2 py-1.5 text-xs text-fg-secondary transition-colors hover:bg-surface hover:text-fg disabled:cursor-default disabled:opacity-40`;function gi({notebook:e,source:t,onChange:r,onAdd:i,onRevealCell:a,onRun:o,onRunCopy:s,onRunSection:l,running:u=!1}){let[d,f]=(0,L.useState)(!1),p=n(),m=si(t,!!o&&c(p.data?.protocol)),h=u||m.data?.state===`busy`||m.data?.state===`starting`,g=m.data?.environment,_=g&&(!g.ipykernel||!g.nbconvert),v=Zr(e),y=e.cells.some(e=>e.cell_type===`code`&&((e.outputs?.length??0)>0||e.execution_count!=null));return(0,R.jsxs)(`div`,{className:`flex shrink-0 flex-wrap items-center gap-1 bg-ground px-3 py-2`,role:`toolbar`,"aria-label":`Notebook`,children:[r&&(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)(`button`,{type:`button`,className:hi,disabled:e.cells.length>=2e3,onClick:()=>i(`code`),"aria-label":`Add code cell`,children:[(0,R.jsx)(Ue,{className:`size-3.5`}),`Code`]}),(0,R.jsxs)(`button`,{type:`button`,className:hi,disabled:e.cells.length>=2e3,onClick:()=>i(`markdown`),"aria-label":`Add Markdown cell`,children:[(0,R.jsx)(Ue,{className:`size-3.5`}),`Markdown`]})]}),o&&(0,R.jsxs)(`button`,{type:`button`,className:hi,disabled:h||_,onClick:o,children:[(0,R.jsx)(Pe,{className:`size-3.5`}),h?`Running…`:`Run All`]}),r&&(0,R.jsxs)(`button`,{type:`button`,className:hi,disabled:!y,onClick:()=>r(Xr(e)),children:[(0,R.jsx)(He,{className:`size-3.5`}),`Clear All Outputs`]}),(0,R.jsxs)(vt,{open:d,onOpenChange:f,children:[(0,R.jsx)(_t,{asChild:!0,children:(0,R.jsxs)(`button`,{type:`button`,className:hi,disabled:v.length===0,children:[(0,R.jsx)(un,{className:`size-3.5`}),`Outline`]})}),(0,R.jsx)(gt,{align:`start`,className:`max-h-72 w-72 overflow-y-auto p-1`,children:(0,R.jsx)(`nav`,{"aria-label":`Notebook outline`,className:`flex flex-col`,children:v.map(e=>(0,R.jsxs)(`div`,{className:`group/outline flex items-center`,style:{paddingLeft:`calc(var(--spacing) * ${Math.max(0,e.level-1)*3})`},children:[(0,R.jsxs)(`button`,{type:`button`,className:`${hi} min-w-0 flex-1 text-left`,onClick:()=>{a(e.index),f(!1)},children:[(0,R.jsx)(`span`,{className:`w-5 shrink-0 text-fg-muted`,children:e.index+1}),(0,R.jsx)(`span`,{className:`truncate`,children:e.label})]}),!!e.level&&l&&(0,R.jsx)(`button`,{type:`button`,disabled:h,title:`Run Section`,"aria-label":`Run section ${e.label}`,className:`${hi} opacity-0 group-hover/outline:opacity-100 focus:opacity-100 pointer-coarse:opacity-100`,onClick:()=>{l(e.index),f(!1)},children:(0,R.jsx)(Pe,{className:`size-3.5`})})]},e.index))})})]}),r&&(0,R.jsxs)(Ne,{children:[(0,R.jsx)(Ie,{asChild:!0,children:(0,R.jsx)(`button`,{type:`button`,className:hi,"aria-label":`More notebook actions`,children:(0,R.jsx)(Ee,{className:`size-3.5`})})}),(0,R.jsxs)(Te,{align:`start`,children:[s&&(0,R.jsx)(Se,{disabled:h,onSelect:s,children:`Run to Executed Copy`}),(0,R.jsxs)(Se,{disabled:e.cells.length>=2e3,onSelect:()=>i(`raw`),children:[(0,R.jsx)(Ue,{}),`Add raw cell`]})]})]}),r&&o&&(0,R.jsx)(mi,{source:t,notebook:e,onSelect:t=>r({...e,metadata:{...e.metadata,kernelspec:t}})},JSON.stringify(t))]})}function _i({code:e,onRun:t,busy:n,index:r,count:i,canMerge:a,onOperation:o}){let s=(e,t,n,r=!1)=>(0,R.jsx)(`button`,{type:`button`,className:`cursor-pointer rounded-sm p-1 text-fg-muted hover:bg-surface hover:text-fg disabled:cursor-default disabled:opacity-40`,title:e,"aria-label":e,onClick:n,disabled:r,children:t});return(0,R.jsxs)(`div`,{className:`ml-auto flex flex-wrap items-center opacity-0 focus-within:opacity-100 group-hover/cell:opacity-100 pointer-coarse:opacity-100`,children:[e&&t&&(0,R.jsxs)(R.Fragment,{children:[s(`Run Cell`,(0,R.jsx)(Pe,{className:`size-3.5`}),()=>t(`cell`),n),s(`Run Above`,(0,R.jsx)(sn,{className:`size-3.5`}),()=>t(`above`),n||r===0),s(`Run Cell and Below`,(0,R.jsx)(on,{className:`size-3.5`}),()=>t(`below`),n)]}),s(`Insert cell below`,(0,R.jsx)(Ue,{className:`size-3.5`}),()=>o(`insert`),i>=2e3),s(`Duplicate cell`,(0,R.jsx)(rt,{className:`size-3.5`}),()=>o(`duplicate`),i>=2e3),s(`Merge with next cell`,(0,R.jsx)(cn,{className:`size-3.5`}),()=>o(`merge`),!a),s(`Move cell up`,(0,R.jsx)(Me,{className:`size-3.5`}),()=>o(`up`),r===0),s(`Move cell down`,(0,R.jsx)(Fe,{className:`size-3.5`}),()=>o(`down`),r===i-1),s(`Delete cell`,(0,R.jsx)(He,{className:`size-3.5`}),()=>o(`delete`))]})}function vi(e,t){let n=async(n,r,i)=>{let a=e.getValue();if(a.length>65536||i.isCancellationRequested)return null;let o=e.getVersionId();try{let s=await F(`POST`,`/api/notebooks/intelligence`,{source:t,kind:n,code:a,cursor:[...a.slice(0,e.getOffsetAt(r))].length});return i.isCancellationRequested||e.isDisposed()||o!==e.getVersionId()?null:{response:s,code:a}}catch{return null}},r=()=>{let t=e.getLanguageId();return t===`markdown`||t===`plaintext`?[]:[te.registerCompletionItemProvider(t,{triggerCharacters:[`.`],async provideCompletionItems(t,r,i,a){if(t!==e)return{suggestions:[]};let o=await n(`complete`,r,a);if(!o)return{suggestions:[]};let{response:s,code:c}=o,l=e.getPositionAt([...c].slice(0,s.start).join(``).length),u=e.getPositionAt([...c].slice(0,s.end).join(``).length),d=new j(l.lineNumber,l.column,u.lineNumber,u.column);return{suggestions:s.matches.map(e=>({label:e,insertText:e,kind:te.CompletionItemKind.Text,range:d}))}}}),te.registerHoverProvider(t,{async provideHover(t,r,i){if(t!==e)return null;let a=await n(`inspect`,r,i);return a?.response.documentation?{contents:[{value:a.response.documentation.replace(/\u001b\[[0-?]*[ -/]*[@-~]/g,``).replace(/[\\`*_{}[\]()#+.!<>-]/g,`\\$&`),isTrusted:!1,supportHtml:!1}]}:null}})]},i=r(),a=e.onDidChangeLanguage(()=>{i.forEach(e=>e.dispose()),i=r()});return{dispose(){a.dispose(),i.forEach(e=>e.dispose())}}}function yi({value:e,language:t,label:n,focus:r,onChange:i,onExecute:a,onEscape:o,onSplit:s,onSave:c,match:l}){let u=C(),d=Math.round(u.editorFontSize*1.5),f=(0,L.useContext)(di),[p,m]=(0,L.useState)(null);(0,L.useEffect)(()=>{if(!p||!f?.intelligence)return;let e=vi(p,{session:f.session,path:f.path,...f.root?{root:f.root}:{}});return()=>e.dispose()},[p,f?.intelligence,f?.session,f?.path,f?.root]);let h=(0,L.useRef)(null),g=(0,L.useRef)(null),_=(0,L.useRef)(null),v=(0,L.useRef)(!1),y=(0,L.useRef)(null),b=(0,L.useRef)({onChange:i,onExecute:a,onEscape:o,onSplit:s,onSave:c});b.current={onChange:i,onExecute:a,onEscape:o,onSplit:s,onSave:c};let x=(0,L.useRef)(r);x.current=r;let S=(0,L.useRef)(l);S.current=l;let w=e=>{let t=e.getModel(),n=S.current;if(!t||!n)return;let r=t.getPositionAt(n.start),i=t.getPositionAt(n.end);e.setSelection(new j(r.lineNumber,r.column,i.lineNumber,i.column)),e.revealPositionInCenter(r)};(0,L.useEffect)(()=>{g.current&&w(g.current)},[l]);let[ee,T]=(0,L.useState)(!1),[E,D]=(0,L.useState)(!1),[O,k]=(0,L.useState)(Math.max(64,e.split(`
|
|
6
|
+
`).length*d+24));return(0,L.useEffect)(()=>{let e=new IntersectionObserver(([e])=>T(!!e?.isIntersecting),{rootMargin:`600px`});return h.current&&e.observe(h.current),()=>e.disconnect()},[]),(0,L.useEffect)(()=>()=>{_.current?.dispose()},[]),(0,L.useEffect)(()=>{let n=_.current;n&&n.getValue()!==e&&(v.current=!0,n.pushEditOperations([],[{range:n.getFullModelRange(),text:e}],()=>null),v.current=!1),n&&N.setModelLanguage(n,t)},[e,t]),(0,L.useEffect)(()=>{r&&g.current?.focus()},[r]),(0,R.jsxs)(`div`,{ref:h,style:{height:O},className:`relative min-w-0 rounded-md bg-surface`,onWheelCapture:e=>{!e.shiftKey&&Math.abs(e.deltaY)>=Math.abs(e.deltaX)&&!e.target.closest(`.overflowingContentWidgets,.overflowingOverlayWidgets,.contentWidgets,.overlayWidgets`)&&e.stopPropagation()},children:[!p&&(0,R.jsx)(`pre`,{"aria-hidden":`true`,className:`absolute inset-0 overflow-hidden px-2 py-3 font-mono text-fg`,style:{fontSize:u.editorFontSize,lineHeight:`${d}px`,whiteSpace:u.editorWordWrap?`pre-wrap`:`pre`},children:e}),(ee||r||E)&&(0,R.jsx)(Et,{loading:null,theme:`puddle`,defaultValue:e,defaultLanguage:t,keepCurrentModel:!0,saveViewState:!1,onMount:e=>{if(_.current){let t=e.getModel();e.setModel(_.current),t!==_.current&&t?.dispose()}else _.current=e.getModel();g.current=e,m(e.getModel()),nr(e,{onSave:()=>b.current.onSave()}),y.current&&e.restoreViewState(y.current),e.setScrollTop(0);let t=!1,n=()=>{if(t||!h.current||!h.current.clientWidth)return;t=!0,e.layout({width:h.current.clientWidth,height:h.current.clientHeight});let n=Math.max(64,e.getContentHeight());h.current.style.height=`${n}px`,e.layout({width:h.current.clientWidth,height:n}),k(n),t=!1},r=e.onDidContentSizeChange(n),i=new ResizeObserver(n);i.observe(h.current);let a=e.onDidFocusEditorWidget(()=>D(!0)),o=e.onDidBlurEditorWidget(()=>D(!1)),s=e.onDidChangeModelContent(()=>{v.current||b.current.onChange(e.getValue())}),c=e.onDidScrollChange(()=>{y.current=e.saveViewState()}),l=e.onDidChangeCursorSelection(()=>{y.current=e.saveViewState()});e.addCommand(M.CtrlCmd|P.Enter,()=>b.current.onExecute(`stay`)),e.addCommand(M.Shift|P.Enter,()=>b.current.onExecute(`next`)),e.addCommand(M.Alt|P.Enter,()=>b.current.onExecute(`insert`)),e.addCommand(P.Escape,()=>b.current.onEscape(),`!suggestWidgetVisible && !findWidgetVisible`),e.addCommand(M.CtrlCmd|M.Shift|P.Minus,()=>{let t=e.getPosition();t&&b.current.onSplit(e.getModel().getOffsetAt(t))}),e.onDidDispose(()=>{r.dispose(),i.disconnect(),a.dispose(),o.dispose(),c.dispose(),l.dispose(),s.dispose(),g.current=null,m(null)}),n(),w(e),x.current&&e.focus()},beforeMount:()=>{_.current&&N.setModelLanguage(_.current,t)},options:{ariaLabel:n,automaticLayout:!1,fontFamily:getComputedStyle(document.documentElement).getPropertyValue(`--font-mono`).trim(),fontSize:u.editorFontSize,lineHeight:d,...jn(u.editorTabSize),wordWrap:u.editorWordWrap?`on`:`off`,minimap:{enabled:!1},glyphMargin:!1,folding:!0,lineNumbers:`off`,lineDecorationsWidth:8,lineNumbersMinChars:3,scrollBeyondLastLine:!1,fixedOverflowWidgets:!0,padding:{top:12,bottom:12},renderLineHighlight:`none`,occurrencesHighlight:`off`,scrollbar:{alwaysConsumeMouseWheel:!1,vertical:`hidden`}},onChange:()=>{g.current&&(y.current=g.current.saveViewState())}})]})}function bi({language:e,onChange:t}){let[n,r]=(0,L.useState)(!1),i=[`markdown`,`raw`,...te.getLanguages().map(e=>e.id).filter(e=>e!==`markdown`).sort()];return(0,R.jsxs)(vt,{open:n,onOpenChange:r,children:[(0,R.jsx)(_t,{asChild:!0,children:(0,R.jsxs)(`button`,{type:`button`,"aria-label":`Cell language: ${e}`,className:`flex cursor-pointer items-center gap-1 font-mono text-xs text-fg-muted hover:text-fg`,children:[e,(0,R.jsx)(Ze,{className:`size-3`})]})}),(0,R.jsxs)(gt,{align:`start`,className:`w-56 p-0`,children:[(0,R.jsxs)(ht,{children:[(0,R.jsx)(dt,{placeholder:`Find a language…`}),(0,R.jsxs)(mt,{children:[(0,R.jsx)(pt,{children:`No matching languages`}),i.map(e=>(0,R.jsx)(ft,{onSelect:()=>{t(e),r(!1)},children:e},e))]})]}),(0,R.jsx)(`p`,{className:`px-3 py-2 text-xs text-fg-muted`,children:`Code languages set highlighting. Execution uses the notebook kernel.`})]})]})}async function xi(e,t,n){let r=`path=${encodeURIComponent(t)}${se(n)}`,i=g();return i?Ci(i,async()=>{if(g()!==i)throw Error(`Preview host changed`);let t=p.parse(await F(`GET`,`/api/worktrees/${e}/preview-asset?${r}`));return new Blob([Uint8Array.from(atob(t.data),e=>e.charCodeAt(0))],{type:t.mime})}):(await ne(`GET`,`/api/worktrees/${e}/media?${r}`)).blob()}var Si=new WeakMap;async function Ci(e,t){let n=Si.get(e);if(n||(n={active:0,waiting:[]},Si.set(e,n)),n.waiting.length>=128)throw Error(`Too many preview assets`);n.active>=2?await new Promise(e=>n.waiting.push(e)):n.active+=1;try{return await t()}finally{let e=n.waiting.shift();e?e():--n.active}}function wi(e,t,n,r,i){(0,L.useEffect)(()=>{let t=e.current;if(!t)return;let a=!1,o=[],s=async e=>{try{let t=await xi(n,e,i);if(a)return null;let r=URL.createObjectURL(t);return o.push(r),r}catch{return null}};for(let e of t.querySelectorAll(`img[src], source[src]`)){let t=lt(r,e.getAttribute(`src`)??``);t&&(e.removeAttribute(`src`),s(t).then(t=>{!a&&t&&e.setAttribute(`src`,t)}))}for(let e of t.querySelectorAll(`img[srcset], source[srcset]`)){let t=ut(e.getAttribute(`srcset`)??``),n=t.map(({ref:e})=>lt(r,e));n.some(e=>e!==null)&&(e.removeAttribute(`srcset`),Promise.all(t.map(async(e,t)=>{let r=n[t];if(!r)return e;let i=await s(r);return i?{...e,ref:i}:null})).then(t=>{if(a)return;let n=t.filter(e=>e!==null);n.length>0&&e.setAttribute(`srcset`,ot(n))}))}return()=>{a=!0;for(let e of o)URL.revokeObjectURL(e)}},[t,e,n,r,i])}function Ti(e,t){let n=URL.createObjectURL(e),r=document.createElement(`a`);try{r.href=n,r.download=t,document.body.appendChild(r),r.click()}finally{r.remove(),setTimeout(()=>URL.revokeObjectURL(n),6e4)}}var Ei=(0,L.lazy)(()=>E(()=>import(`./NotebookWidget-BntkgqbM.js`),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12])));function Di(e,t){return!t||typeof t!=`object`?e:e.replace(/attachment:([^\s"')>]+)/g,(e,n)=>{try{let r=t[decodeURIComponent(n)];if(!r||typeof r!=`object`)return e;for(let e of[`image/png`,`image/jpeg`,`image/gif`,`image/webp`]){let t=B(r[e]).replace(/\s/g,``);if(t&&/^[A-Za-z0-9+/]*={0,2}$/.test(t))return`data:${e};base64,${t}`}}catch{}return e})}function Oi({text:e,markdown:t=!1,attachments:n}){let r=(0,L.useContext)(di),i=(0,L.useRef)(null),a=(0,L.useId)().replace(/[^a-zA-Z0-9_-]/g,``),o=(0,L.useSyncExternalStore)(D,O,O),s=(0,L.useMemo)(()=>k.sanitize(t?Wt(Di(e,n),a):e,{FORBID_TAGS:[`style`,`iframe`,`form`,`input`,`button`],...t?{}:{FORBID_ATTR:[`style`]}}),[e,t,n,a]),c=(0,L.useMemo)(()=>({__html:s}),[s,o]);return wi(i,s,r?.session??``,r?.path??``,r?.root),(0,L.useEffect)(()=>{let e=new AbortController;return i.current&&t&&an(i.current,o,e.signal),()=>e.abort()},[s,o,t]),(0,R.jsx)(`div`,{ref:i,className:`md-preview overflow-x-auto text-sm`,dangerouslySetInnerHTML:c,onClick:e=>{let t=e.target.closest(`a`);if(!t)return;let n=t.getAttribute(`href`)??``;if(/^https?:/i.test(n)){e.preventDefault(),window.open(n,`_blank`,`noopener,noreferrer`);return}if(n.startsWith(`#`)){e.preventDefault();try{i.current?.querySelector(`#${CSS.escape(decodeURIComponent(n.slice(1)))}`)?.scrollIntoView({block:`nearest`})}catch{}return}let a=r?lt(r.path,n):null;a&&(e.preventDefault(),(e.metaKey||e.ctrlKey)&&r?.onOpenFile?.(a))}})}var ki=`cursor-pointer rounded-sm p-1 text-fg-muted hover:bg-surface hover:text-fg`;function Ai({output:e}){let t=null;for(let n of[`image/png`,`image/jpeg`,`image/gif`,`image/webp`]){let r=B(e.data?.[n]).replace(/\s/g,``);if(r&&/^[A-Za-z0-9+/]*={0,2}$/.test(r)){try{t={src:`data:${n};base64,${r}`,blob:new Blob([Uint8Array.from(atob(r),e=>e.charCodeAt(0))],{type:n}),extension:n.split(`/`)[1]}}catch{}if(t)break}}let n=B(e.data?.[`image/svg+xml`]),r=n?k.sanitize(n,{USE_PROFILES:{svg:!0,svgFilters:!0},FORBID_TAGS:[`style`,`foreignObject`,`image`,`use`],FORBID_ATTR:[`style`,`href`,`xlink:href`]}):``,i=B(e.data?.[`text/html`]),a=B(e.data?.[`text/markdown`]),o=e.data?.[`application/json`],s=e.data?.[`application/vnd.jupyter.widget-view+json`],c=s&&typeof s==`object`&&`model_id`in s&&typeof s.model_id==`string`?s.model_id:null,l=Jr(e)||(o===void 0?``:JSON.stringify(o,null,2))||`This output format cannot be displayed.`;return(0,R.jsxs)(`div`,{className:`group/output relative`,children:[(0,R.jsxs)(`div`,{className:`absolute right-1 top-0 z-10 flex gap-1 bg-ground opacity-0 group-hover/output:opacity-100 focus-within:opacity-100 pointer-coarse:opacity-100`,children:[(0,R.jsx)(`button`,{type:`button`,title:`Copy output`,"aria-label":`Copy output`,className:ki,onClick:()=>{navigator.clipboard.writeText(l).catch(()=>I.error(`Could not copy output`))},children:(0,R.jsx)(rt,{className:`size-3.5`})}),(t||r)&&(0,R.jsx)(`button`,{type:`button`,title:`Save image`,"aria-label":`Save image`,className:ki,onClick:()=>Ti(t?.blob??new Blob([r],{type:`image/svg+xml`}),`notebook-output.${t?.extension??`svg`}`),children:(0,R.jsx)(Ce,{className:`size-3.5`})})]}),c?(0,R.jsx)(L.Suspense,{fallback:(0,R.jsx)(`p`,{className:`text-xs text-fg-muted`,children:`Loading widget…`}),children:(0,R.jsx)(Ei,{modelId:c,fallback:Jr(e)})}):t?(0,R.jsx)(`img`,{src:t.src,alt:`Notebook output`,className:`max-w-full`}):r?(0,R.jsx)(`div`,{dangerouslySetInnerHTML:{__html:r}}):i?(0,R.jsx)(Oi,{text:i}):a?(0,R.jsx)(Oi,{text:a,markdown:!0}):(0,R.jsx)(`pre`,{className:`overflow-x-auto whitespace-pre-wrap font-mono text-sm ${e.output_type===`error`?`text-danger`:`text-fg-secondary`}`,children:l})]})}function ji({source:e,execution:t,onInterrupt:n}){let r=(0,L.useRef)(null),i=(0,L.useRef)(!1),[a,o]=(0,L.useState)(``),[s,c]=(0,L.useState)(!1),[l,u]=(0,L.useState)(null),d=t.input;return(0,L.useEffect)(()=>{r.current?.focus({preventScroll:!0}),r.current?.scrollIntoView({block:`nearest`})},[]),d?(0,R.jsxs)(`form`,{className:`mt-2 font-mono text-sm text-fg-secondary`,"aria-busy":s,onSubmit:n=>{n.preventDefault(),!i.current&&(i.current=!0,c(!0),u(null),F(`POST`,`/api/notebooks/input`,{source:e,run_id:t.id,input_id:d.id,value:a}).then(()=>{d.password&&o(``)}).catch(e=>{u(e instanceof Error?e.message:`Input failed`),i.current=!1,c(!1)}))},children:[(0,R.jsxs)(`label`,{className:`flex min-w-0 flex-wrap items-baseline`,children:[(0,R.jsx)(`span`,{className:`whitespace-pre-wrap break-words`,children:d.prompt}),(0,R.jsx)(`input`,{ref:r,"aria-label":d.prompt||`Kernel input`,type:d.password?`password`:`text`,value:a,readOnly:s,maxLength:65536,autoComplete:`off`,autoCapitalize:`off`,spellCheck:!1,onChange:e=>o(e.target.value),onKeyDown:e=>{n&&e.ctrlKey&&!e.metaKey&&!e.altKey&&!e.shiftKey&&e.key.toLowerCase()===`c`&&e.currentTarget.selectionStart===e.currentTarget.selectionEnd&&(e.preventDefault(),e.stopPropagation(),n())},className:`min-w-16 flex-1 cursor-text bg-transparent p-0 text-fg outline-none read-only:opacity-60`})]}),l&&(0,R.jsx)(`p`,{role:`alert`,className:`mt-1 text-xs text-danger`,children:l})]}):null}var Mi=`cursor-pointer rounded-sm p-1 text-fg-muted transition-colors hover:bg-surface hover:text-fg disabled:cursor-default disabled:opacity-40`;function Ni({cell:e,notebook:t,index:n,active:r,editing:i,selected:a,editable:o,onSelect:s,onEdit:c,onSource:l,onLanguage:u,onExecute:d,onRun:f,onInterrupt:p,onOperation:m,onSplit:h,onSave:g,execution:_,inputExecution:v,inputSource:y,match:b,onToggleSection:x,sectionCollapsed:S}){let C=(0,L.useRef)(null),[w,ee]=(0,L.useState)(!1),T=y?v?.input:void 0;(0,L.useEffect)(()=>{(b?.output||T)&&ee(!1)},[b,T]);let E=w&&!T,D=e.cell_type===`code`,O=B(e.source),k=_?.state===`running`||_?.state===`queued`,A=Gr(e,t),j=(e,t,n,r=!1)=>(0,R.jsx)(`button`,{type:`button`,className:Mi,title:e,"aria-label":e,onClick:n,disabled:r,children:t});return(0,R.jsxs)(`section`,{ref:C,"data-notebook-cell":n,"data-cell-id":e.id,tabIndex:r?0:-1,"aria-label":`Cell ${n+1}`,"aria-current":r||void 0,className:`group/cell relative min-w-0 outline-none ${a?`bg-surface`:``}`,onMouseDown:e=>{e.shiftKey&&!e.target.closest(`.monaco-editor,input,button`)&&e.preventDefault()},onFocus:()=>{r||s(!1)},onClick:e=>{if((e.metaKey||e.ctrlKey)&&D&&!e.target.closest(`.monaco-editor,a,button,input`)){e.preventDefault(),f?.(`cell`);return}e.target.closest(`button,input,[role=option]`)||s(e.shiftKey&&!e.target.closest(`.monaco-editor`))},children:[(0,R.jsx)(`div`,{className:`absolute -left-10 top-9 w-9 text-center font-mono text-xs text-fg-muted`,children:(0,R.jsxs)(`button`,{type:`button`,className:`${Mi} group/run relative w-full`,disabled:!o||D&&(!f||!k&&!O.trim()),title:D?k?`Interrupt execution`:`Run Cell (⌘/Ctrl+Enter)`:i?`Show rendered cell`:`Edit cell source`,"aria-label":D?k?`Interrupt execution`:`Run Cell`:i?`Show rendered cell`:`Edit cell source`,onClick:()=>{D?k?p?.():f?.(`cell`):c(!i)},children:[(0,R.jsx)(`span`,{className:D&&f?`group-hover/run:invisible group-focus-visible/run:invisible`:``,children:D?`[${k?`*`:e.execution_count??` `}]`:i?`[›]`:`[ ]`}),D&&f&&(k?(0,R.jsx)(je,{className:`absolute inset-0 m-auto hidden size-3.5 group-hover/run:block group-focus-visible/run:block`}):(0,R.jsx)(Pe,{className:`absolute inset-0 m-auto hidden size-3.5 group-hover/run:block group-focus-visible/run:block`}))]})}),(0,R.jsxs)(`div`,{className:`mb-2 flex min-h-7 items-center gap-2 text-xs text-fg-muted`,children:[x&&j(S?`Expand section`:`Fold section`,S?(0,R.jsx)(Ve,{className:`size-3`}):(0,R.jsx)(Ze,{className:`size-3`}),x),o?(0,R.jsx)(bi,{language:e.cell_type===`raw`?`raw`:A,onChange:u}):(0,R.jsx)(`span`,{className:`font-mono`,children:e.cell_type===`raw`?`raw`:A}),_&&(0,R.jsxs)(`span`,{role:`status`,children:[_.state,_.elapsed_ms===void 0?``:` · ${(_.elapsed_ms/1e3).toFixed(1)}s`]}),_&&_.source!==O&&(0,R.jsx)(`span`,{title:`The source changed after this execution`,children:`Source changed`}),o&&(0,R.jsx)(_i,{code:D,onRun:f,busy:k,index:n,count:t.cells.length,canMerge:e.cell_type===t.cells[n+1]?.cell_type,onOperation:m})]}),o&&(D||i)?(0,R.jsx)(yi,{value:O,match:b&&!b.output?b:void 0,language:A,label:`Cell ${n+1} source`,focus:r&&i&&!b,onChange:e=>{e!==O&&l(e)},onExecute:d,onEscape:()=>{c(!1),C.current?.focus()},onSave:g,onSplit:h}):e.cell_type===`markdown`?(0,R.jsx)(`div`,{onDoubleClick:()=>{o&&c(!0)},className:o?`cursor-text`:``,children:(0,R.jsx)(Oi,{text:O,markdown:!0,attachments:e.attachments})}):(0,R.jsx)(`pre`,{className:`overflow-x-auto whitespace-pre-wrap font-mono text-sm`,onDoubleClick:()=>{o&&c(!0)},children:O}),(!!e.outputs?.length||T)&&(0,R.jsxs)(`div`,{className:`mt-2`,role:`group`,"aria-label":`Cell ${n+1} output`,children:[(0,R.jsxs)(`div`,{className:`flex items-center gap-2 text-xs text-fg-muted`,children:[j(E?`Expand output`:`Collapse output`,E?(0,R.jsx)(Ve,{className:`size-3`}):(0,R.jsx)(Ze,{className:`size-3`}),()=>ee(!w),!!T),(0,R.jsx)(`span`,{children:`Output`}),o&&j(`Clear cell output`,(0,R.jsx)(He,{className:`size-3`}),()=>m(`clear`))]}),!E&&(0,R.jsxs)(`div`,{className:`max-h-96 overflow-auto`,children:[e.outputs?.map((e,t)=>(0,R.jsx)(`div`,{className:`mt-2`,children:(0,R.jsx)(Ai,{output:e})},t)),T&&v&&y&&(0,R.jsx)(ji,{source:y,execution:v,onInterrupt:p},`${v.id}:${T.id}`)]})]})]})}var Pi=new It;function Fi(e,t,n){let r=Pi.get(n),i=!!r,a=e.scrollTop,o=()=>e.clientHeight>0&&e.clientWidth>0,s=()=>{if(!o())return;let r=e.getBoundingClientRect().top,i=[...t.querySelectorAll(`[data-cell-id]`)].find(e=>e.getBoundingClientRect().bottom>r);Pi.set(n,{cell:i?.dataset.cellId,offset:i?i.getBoundingClientRect().top-r:0,top:e.scrollTop,left:e.scrollLeft})},c=()=>{if(!i||!r||!o())return;let n=r.cell?t.querySelector(`[data-cell-id="${CSS.escape(r.cell)}"]`):null;e.scrollTop=n?e.scrollTop+n.getBoundingClientRect().top-e.getBoundingClientRect().top-r.offset:r.top,e.scrollLeft=r.left,a=e.scrollTop},l=()=>{i=!1},u=()=>{e.scrollTop!==a&&(i=!1),i||s()};c();let d=new ResizeObserver(c);d.observe(e),d.observe(t),e.addEventListener(`scroll`,u,{passive:!0});let f=[`wheel`,`touchstart`,`pointerdown`,`keydown`];for(let t of f)e.addEventListener(t,l,{passive:!0});return()=>{i||s(),d.disconnect(),e.removeEventListener(`scroll`,u);for(let t of f)e.removeEventListener(t,l)}}function Ii({text:e,session:t,path:n,root:r,onChange:i,onRun:a,running:o,onUndo:s,onRedo:c,onOpenFile:l,focused:u=!0}){let d=(0,L.useMemo)(()=>{try{return{notebook:Wr(Hr(e)),error:null}}catch(e){return{notebook:null,error:e instanceof Error?e.message:`Invalid notebook`}}},[e]),[f,p]=(0,L.useState)([]),[m,h]=(0,L.useState)(null),g=(0,L.useRef)(!0),[_,v]=(0,L.useState)(null),[y,b]=(0,L.useState)(null),C=(0,L.useRef)(null),[w,ee]=(0,L.useState)([]),T=(0,L.useRef)(null),E=(0,L.useRef)(null),D=(0,L.useRef)(null),O=Ft(`notebook`,[t,r,n]),k=d.notebook!==null;(0,L.useLayoutEffect)(()=>{if(!(!T.current||!E.current||!k))return Fi(T.current,E.current,O)},[O,k]),(0,L.useLayoutEffect)(()=>{if(!D.current)return;let e=E.current?.querySelector(`[data-cell-id="${CSS.escape(D.current)}"]`);e&&(e.scrollIntoView({block:`nearest`}),g.current&&e.focus({preventScroll:!0}),g.current=!0,D.current=null)});let A=e=>i?.(`${JSON.stringify(e,null,1)}\n`),j=d.notebook,te=(0,L.useMemo)(()=>({session:t,path:n,...r===void 0?{}:{root:r}}),[t,n,r]),M=ui(te,j,i?A:void 0,!!a),N=x(te,j,i?A:void 0,!!a),P=M.execution?.input?M.execution.cells.find(e=>e.state===`running`)?.id:void 0;if((0,L.useLayoutEffect)(()=>{if(!j||!P||!f.length)return;let e=j.cells.findIndex(e=>e.id===P),t=f.filter(t=>{let n=j.cells.findIndex(e=>e.id===t);return n<0||!Qr(j,n).includes(e)});t.length!==f.length&&p(t)},[j,P,f]),!j)return(0,R.jsx)(`p`,{className:`p-6 text-sm text-danger`,role:`alert`,children:d.error});let F=(e,t=!1)=>{let n=C.current??_??e,r=j.cells.findIndex(e=>e.id===n),i=j.cells.findIndex(t=>t.id===e);ee(t?j.cells.slice(Math.min(r,i),Math.max(r,i)+1).map(e=>e.id):[e]),t||(C.current=e),v(e)},ne=(e,t=!1,n=!1)=>{F(e,n),b(t?e:null),D.current=e},re=Zr(j),ie=new Set(j.cells.flatMap((e,t)=>f.includes(e.id)?Qr(j,t).slice(1):[])),{add:ae,replace:oe,execute:se,operation:ce,keyDown:le}=ti({notebook:j,active:_,selected:w,update:A,choose:ne,setEditing:b,run:M.run,onUndo:s,onRedo:c});return(0,R.jsx)(S.Provider,{value:N,children:(0,R.jsx)(di.Provider,{value:{...te,onOpenFile:l,intelligence:M.intelligenceSupported},children:(0,R.jsxs)(`div`,{className:`relative flex h-full min-h-0 flex-col bg-ground`,onKeyDown:i?le:void 0,onCopy:e=>{i&&ni(e,`copy`,j,w,A)},onCut:e=>{i&&ni(e,`cut`,j,w,A)},onPaste:e=>{i&&ni(e,`paste`,j,w,A)},children:[(0,R.jsx)(ai,{notebook:j,focused:u,onChange:i?A:void 0,onReveal:e=>{h(e),e&&(p([]),v(e.id),e.output||b(e.id),D.current=e.id,g.current=!1)}}),(0,R.jsx)(gi,{notebook:j,source:{session:t,path:n,...r===void 0?{}:{root:r}},onChange:i?A:void 0,onAdd:ae,onRun:M.supported?()=>{M.run()}:a,onRunCopy:M.supported?a:void 0,running:o||M.busy,onRevealCell:e=>{p([]),ne(j.cells[e].id)},onRunSection:M.supported?e=>{M.run(Qr(j,e))}:void 0}),(0,R.jsx)(`div`,{ref:T,className:`min-h-0 flex-1 overflow-auto bg-ground text-fg`,children:(0,R.jsxs)(`div`,{ref:E,className:`mx-auto flex max-w-4xl flex-col gap-7 py-6 pr-6 pl-14`,children:[(0,R.jsxs)(`p`,{className:`text-xs text-fg-muted`,children:[j.cells.length,` cells`]}),N.saveWarning&&(0,R.jsx)(`p`,{role:`status`,className:`text-xs text-fg-muted`,children:N.saveWarning}),M.error&&(0,R.jsx)(`p`,{role:`alert`,className:`text-xs text-danger`,children:M.error}),j.cells.map((e,a)=>ie.has(a)?null:(0,R.jsx)(Ni,{cell:e,match:m&&m.id===e.id?m:void 0,sectionCollapsed:f.includes(e.id),onToggleSection:re[a]?.level?()=>p(t=>t.includes(e.id)?t.filter(t=>t!==e.id):[...t,e.id]):void 0,notebook:j,index:a,active:_===e.id,editing:y===e.id,selected:w.length>1&&w.includes(e.id),editable:!!i,onSelect:t=>F(e.id,t),onEdit:t=>{v(e.id),b(t?e.id:null)},onSource:e=>A(Ur(j,a,e)),onLanguage:t=>oe(a,Kr(e,t)),onInterrupt:()=>{M.interrupt()},execution:M.execution?.cells.find(t=>t.id===e.id)??ei(e),inputExecution:P===e.id?M.execution??void 0:void 0,inputSource:te,onRun:M.supported?e=>{M.run(j.cells.flatMap((t,n)=>(e===`cell`?n===a:e===`above`?n<a:n>=a)?[n]:[]))}:void 0,onExecute:e=>se(a,e),onOperation:e=>ce(a,e),onSave:()=>{Oe(De(t,n,r))},onSplit:t=>{if(j.cells.length>=2e3)return;let n=B(e.source),r={...qr(e.cell_type),source:n.slice(t)},i=[...j.cells];i.splice(a,1,{...e,source:n.slice(0,t)},r),A({...j,cells:i}),ne(r.id,!0)}},e.id)),i&&(0,R.jsx)(`div`,{className:`flex gap-3`,children:[`code`,`markdown`,`raw`].map(e=>(0,R.jsxs)(`button`,{disabled:j.cells.length>=2e3,className:`cursor-pointer rounded-sm p-1 text-fg-muted transition-colors hover:bg-surface hover:text-fg disabled:cursor-default disabled:opacity-40 flex items-center gap-1.5 text-xs`,onClick:()=>ae(e,j.cells.length),children:[(0,R.jsx)(Ue,{className:`size-3.5`}),e===`code`?`Code`:e===`markdown`?`Markdown`:`Raw`,` cell`]},e))})]})})]})})})}var Li=0;function Ri(e){let t=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode(e){let t=e.parentElement;return!e.textContent||t?.closest(`script, style, noscript, [hidden], [aria-hidden="true"]`)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}}),n=[],r=``,i;for(;i=t.nextNode();){let e=i.textContent??``,t=r.length;r+=e,n.push({node:i,start:t,end:r.length})}return{text:r,nodes:n}}function zi(e,t){let n=t.find(t=>t.end>e.start),r=t.findLast(t=>t.start<e.end);if(!n||!r)return null;let i=document.createRange();return i.setStart(n.node,e.start-n.start),i.setEnd(r.node,e.end-r.start),i}var Bi=class{root;matchName=`puddle-find-${++Li}-match`;activeName=`puddle-find-${Li}-active`;style;signature=``;ranges=[];index=-1;limited=!1;constructor(e){this.root=e,this.style=document.createElement(`style`),this.style.textContent=`
|
|
7
|
+
::highlight(${this.matchName}) { background: var(--selection); }
|
|
8
|
+
::highlight(${this.activeName}) { background: var(--accent); color: var(--action-ink); }
|
|
9
|
+
`,document.head.appendChild(this.style)}find(e,t,n){let r=JSON.stringify([e,t]);if(r!==this.signature||n===`reset`){this.signature=r;let n=Ri(this.root),i=tt(n.text,e,t);if(this.ranges=i.matches.map(e=>zi(e,n.nodes)).filter(e=>e!==null),this.limited=i.limited,this.index=this.ranges.length>0?0:-1,i.invalid)return this.clearHighlights(),{index:-1,count:0,invalid:!0}}else this.ranges.length>0&&(this.index=n===`previous`?(this.index-1+this.ranges.length)%this.ranges.length:(this.index+1)%this.ranges.length);return this.paint(),{index:this.index,count:this.ranges.length,limited:this.limited}}clear(){this.signature=``,this.ranges=[],this.index=-1,this.limited=!1,this.clearHighlights()}dispose(){this.clear(),this.style.remove()}clearHighlights(){CSS.highlights.delete(this.matchName),CSS.highlights.delete(this.activeName)}paint(){if(this.clearHighlights(),this.ranges.length===0)return;CSS.highlights.set(this.matchName,new Highlight(...this.ranges));let e=this.ranges[this.index];e&&(CSS.highlights.set(this.activeName,new Highlight(e)),e.startContainer.parentElement?.scrollIntoView({block:`center`,inline:`nearest`}))}};k.addHook(`afterSanitizeAttributes`,e=>{e.tagName===`A`&&/^https?:/i.test(e.getAttribute(`href`)??``)&&(e.setAttribute(`target`,`_blank`),e.setAttribute(`rel`,`noopener noreferrer`))});function Vi({session:e,path:t,text:n,root:r,scrollDriver:i=!1,scrollReceiver:a=!1,scrollChannel:o=`profile`,focused:s=!0,onRevealSource:c,onOpenFile:l,mobile:u=!1}){let d=Ft(`markdown`,[e,r,t]),f=(0,L.useId)().replace(/[^A-Za-z0-9_-]/g,``),p=(0,L.useSyncExternalStore)(e=>D(e),O,O),m=(0,L.useMemo)(()=>k.sanitize(Wt(n,f)),[n,f]),h=(0,L.useMemo)(()=>Lt(n),[n]),g=(0,L.useMemo)(()=>({__html:m}),[m,p]),_=(0,L.useRef)(null),v=(0,L.useRef)(null),y=(0,L.useRef)(null);(0,L.useEffect)(()=>{let e=v.current;if(!e)return;let t=new Bi(e);return y.current=t,()=>{t.dispose(),y.current=null}},[]);let b=Qe({shortcutEnabled:s,onFind:(e,t,n)=>y.current?.find(e,t,n)??et,onClear:()=>y.current?.clear(),onCloseFocus:()=>_.current?.focus({preventScroll:!0})});(0,L.useEffect)(()=>b.refresh(),[m,p,b.refresh]),(0,L.useEffect)(()=>{let e=v.current;if(!e)return;let t=new AbortController;return an(e,p,t.signal).then(()=>{t.signal.aborted||b.refresh()}),()=>t.abort()},[m,p,b.refresh]),(0,L.useLayoutEffect)(()=>{let n=_.current,s=v.current;if(!(!n||!s))return Xn(n,{viewKey:d,channel:o,target:{session:e,path:t,root:r},driver:i,receiver:a,resizeElements:[n,s],sourceAnchors:()=>Vt(n,s,h)})},[m,h,e,t,r,o,i,a,d]),wi(v,m,e,t,r);let x=e=>{let n=e.target.closest(`a`);if(n){let r=n.getAttribute(`href`)??``;if(/^https?:/i.test(r))return;if(e.preventDefault(),r.startsWith(`#`)){let e=Hi(r);(e?v.current?.querySelector(`#${CSS.escape(e)}`):null)?.scrollIntoView({block:`nearest`});return}if(!u&&!e.metaKey&&!e.ctrlKey)return;let i=lt(t,r);if(!i)return;l?.(i);return}if(!e.metaKey&&!e.ctrlKey||!c)return;let r=_.current,i=v.current;if(!r||!i)return;let a=e.clientY-r.getBoundingClientRect().top+r.scrollTop,o=Rt(Vt(r,i,h),a);o!==null&&(e.preventDefault(),c({line:ii(o,h)}))},S=C().editorFontSize;return(0,R.jsxs)(`div`,{className:`relative size-full bg-ground`,children:[(0,R.jsx)(`div`,{ref:_,tabIndex:-1,className:`h-full overflow-auto overscroll-contain outline-none`,children:(0,R.jsx)(`div`,{ref:v,onClick:x,style:{fontSize:S},className:`md-preview mx-auto max-w-3xl px-6 py-5 text-fg-secondary`,dangerouslySetInnerHTML:g})}),(0,R.jsx)(ri,{controls:b})]})}function Hi(e){try{return decodeURIComponent(e.slice(1))}catch{return null}}var Ui=`puddle-preview-scroll-report`,Wi=`puddle-preview-scroll-apply`,Gi=`puddle-preview-source-reveal`;function Ki(){return crypto.randomUUID()}function qi(e,t,n){if(e.source!==t||t===null||typeof e.data!=`object`||e.data===null)return null;let r=e.data;return r.channel===n?r:null}function Ji(e,t,n){let r=qi(e,t,n);return!r||r.kind!==`puddle-preview-scroll-report`||typeof r.ratio!=`number`||!Number.isFinite(r.ratio)||r.sourceLine!==null&&(typeof r.sourceLine!=`number`||!Number.isFinite(r.sourceLine))||typeof r.layout!=`boolean`||typeof r.scrolled!=`boolean`?null:{kind:Ui,channel:n,ratio:Hn(r.ratio),sourceLine:r.sourceLine===null?null:Math.max(1,r.sourceLine),layout:r.layout,scrolled:r.scrolled}}function Yi(e,t,n){let r=qi(e,t,n);return!r||r.kind!==`puddle-preview-source-reveal`||typeof r.line!=`number`||!Number.isFinite(r.line)?null:{kind:Gi,channel:n,line:Math.max(1,r.line)}}function Xi(e,t,n){e?.postMessage({kind:Wi,channel:t,ratio:Hn(n.ratio),sourceLine:n.sourceLine!==null&&Number.isFinite(n.sourceLine)?Math.max(1,n.sourceLine):null},`*`)}function Zi(e){return`(() => {
|
|
10
|
+
const channel = ${JSON.stringify(e)};
|
|
11
|
+
const reportKind = ${JSON.stringify(Ui)};
|
|
12
|
+
const applyKind = ${JSON.stringify(Wi)};
|
|
13
|
+
const revealKind = ${JSON.stringify(Gi)};
|
|
14
|
+
const lineAttribute = ${JSON.stringify(Ht)};
|
|
15
|
+
const endLineAttribute = ${JSON.stringify(Bt)};
|
|
16
|
+
const countAttribute = ${JSON.stringify(zt)};
|
|
17
|
+
let frame = 0;
|
|
18
|
+
let layoutChanged = false;
|
|
19
|
+
let scrolled = false;
|
|
20
|
+
let sourceAnchors = [];
|
|
21
|
+
const scrolling = () => document.scrollingElement || document.documentElement;
|
|
22
|
+
const clamp = (value, lower, upper) => Math.min(upper, Math.max(lower, value));
|
|
23
|
+
const numberAttribute = (element, attribute) => {
|
|
24
|
+
const value = Number(element.getAttribute(attribute));
|
|
25
|
+
return Number.isFinite(value) && value >= 1 ? value : null;
|
|
26
|
+
};
|
|
27
|
+
const measureAnchors = () => {
|
|
28
|
+
const root = scrolling();
|
|
29
|
+
const lineCount = numberAttribute(document.documentElement, countAttribute);
|
|
30
|
+
if (lineCount === null) {
|
|
31
|
+
sourceAnchors = [];
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
const values = [{ line: 1, offset: 0 }];
|
|
35
|
+
for (const element of document.querySelectorAll('[' + lineAttribute + ']')) {
|
|
36
|
+
const line = numberAttribute(element, lineAttribute);
|
|
37
|
+
if (line === null || line > lineCount + 1 || element.getClientRects().length === 0) continue;
|
|
38
|
+
const rect = element.getBoundingClientRect();
|
|
39
|
+
const top = rect.top + root.scrollTop;
|
|
40
|
+
values.push({ line, offset: top });
|
|
41
|
+
const endLine = numberAttribute(element, endLineAttribute);
|
|
42
|
+
if (endLine !== null && endLine <= lineCount + 1 && endLine > line && rect.height > 0) {
|
|
43
|
+
values.push({ line: endLine, offset: top + rect.height });
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
values.push({ line: lineCount + 1, offset: root.scrollHeight });
|
|
47
|
+
values.sort((a, b) => a.offset - b.offset || a.line - b.line);
|
|
48
|
+
const result = [];
|
|
49
|
+
for (const value of values) {
|
|
50
|
+
const previous = result[result.length - 1];
|
|
51
|
+
if (previous && (value.line <= previous.line || value.offset <= previous.offset)) continue;
|
|
52
|
+
result.push(value);
|
|
53
|
+
}
|
|
54
|
+
sourceAnchors = result;
|
|
55
|
+
};
|
|
56
|
+
const interpolate = (value, lowerInput, upperInput, lowerOutput, upperOutput) => {
|
|
57
|
+
if (upperInput <= lowerInput) return lowerOutput;
|
|
58
|
+
const progress = clamp((value - lowerInput) / (upperInput - lowerInput), 0, 1);
|
|
59
|
+
return lowerOutput + progress * (upperOutput - lowerOutput);
|
|
60
|
+
};
|
|
61
|
+
const mapped = (value, input, output) => {
|
|
62
|
+
const values = sourceAnchors;
|
|
63
|
+
if (!values.length) return null;
|
|
64
|
+
if (value <= values[0][input]) return values[0][output];
|
|
65
|
+
const last = values[values.length - 1];
|
|
66
|
+
if (value >= last[input]) return last[output];
|
|
67
|
+
let low = 0;
|
|
68
|
+
let high = values.length - 1;
|
|
69
|
+
while (low + 1 < high) {
|
|
70
|
+
const middle = Math.floor((low + high) / 2);
|
|
71
|
+
if (values[middle][input] <= value) low = middle;
|
|
72
|
+
else high = middle;
|
|
73
|
+
}
|
|
74
|
+
return interpolate(value, values[low][input], values[high][input],
|
|
75
|
+
values[low][output], values[high][output]);
|
|
76
|
+
};
|
|
77
|
+
const report = () => {
|
|
78
|
+
frame = 0;
|
|
79
|
+
if (layoutChanged) measureAnchors();
|
|
80
|
+
const root = scrolling();
|
|
81
|
+
const ratio = clamp(root.scrollTop / Math.max(1, root.scrollHeight - innerHeight), 0, 1);
|
|
82
|
+
const sourceLine = mapped(root.scrollTop, 'offset', 'line');
|
|
83
|
+
parent.postMessage({ kind: reportKind, channel, ratio, sourceLine, layout: layoutChanged, scrolled }, '*');
|
|
84
|
+
layoutChanged = false;
|
|
85
|
+
scrolled = false;
|
|
86
|
+
};
|
|
87
|
+
const schedule = (layout = false) => {
|
|
88
|
+
layoutChanged = layoutChanged || layout;
|
|
89
|
+
if (!frame) frame = requestAnimationFrame(report);
|
|
90
|
+
};
|
|
91
|
+
addEventListener('scroll', () => { scrolled = true; schedule(false); }, { passive: true });
|
|
92
|
+
addEventListener('load', () => schedule(true));
|
|
93
|
+
const resizeObserver = new ResizeObserver(() => schedule(true));
|
|
94
|
+
resizeObserver.observe(document.documentElement);
|
|
95
|
+
if (document.body) resizeObserver.observe(document.body);
|
|
96
|
+
const mutationObserver = new MutationObserver(() => schedule(true));
|
|
97
|
+
mutationObserver.observe(document.documentElement, { subtree: true, childList: true, attributes: true });
|
|
98
|
+
addEventListener('click', (event) => {
|
|
99
|
+
if ((!event.metaKey && !event.ctrlKey) || event.button !== 0) return;
|
|
100
|
+
const target = event.target instanceof Element ? event.target : null;
|
|
101
|
+
if (target && target.closest('a[href]')) return;
|
|
102
|
+
if (layoutChanged) measureAnchors();
|
|
103
|
+
const root = scrolling();
|
|
104
|
+
const line = mapped(event.clientY + root.scrollTop, 'offset', 'line');
|
|
105
|
+
if (line === null) return;
|
|
106
|
+
event.preventDefault();
|
|
107
|
+
event.stopPropagation();
|
|
108
|
+
parent.postMessage({ kind: revealKind, channel, line }, '*');
|
|
109
|
+
}, true);
|
|
110
|
+
addEventListener('message', (event) => {
|
|
111
|
+
const data = event.data;
|
|
112
|
+
if (event.source !== parent || !data || data.kind !== applyKind ||
|
|
113
|
+
data.channel !== channel || typeof data.ratio !== 'number' ||
|
|
114
|
+
!Number.isFinite(data.ratio) ||
|
|
115
|
+
(data.sourceLine !== null &&
|
|
116
|
+
(typeof data.sourceLine !== 'number' || !Number.isFinite(data.sourceLine)))) return;
|
|
117
|
+
if (layoutChanged) measureAnchors();
|
|
118
|
+
const root = scrolling();
|
|
119
|
+
const ratio = clamp(data.ratio, 0, 1);
|
|
120
|
+
const maximum = Math.max(0, root.scrollHeight - innerHeight);
|
|
121
|
+
const semantic = ratio > 0 && ratio < 1 && data.sourceLine !== null
|
|
122
|
+
? mapped(data.sourceLine, 'line', 'offset')
|
|
123
|
+
: null;
|
|
124
|
+
scrollTo(0, semantic === null ? ratio * maximum : clamp(semantic, 0, maximum));
|
|
125
|
+
});
|
|
126
|
+
schedule(true);
|
|
127
|
+
})();`}function Qi(e,t){let n=e.createElement(`script`);n.textContent=Zi(t),(e.body??e.documentElement).appendChild(n)}var $i=`puddle-preview-find-open`,ea=`puddle-preview-find-apply`,ta=`puddle-preview-find-result`,na=`puddle-preview-find-clear`;function ra(e,t,n){if(e.source!==t||t===null||typeof e.data!=`object`||e.data===null)return null;let r=e.data;return r.channel===n?r.kind===`puddle-preview-find-open`?{kind:$i,channel:n}:r.kind!==`puddle-preview-find-result`||typeof r.index!=`number`||!Number.isInteger(r.index)||r.index<-1||typeof r.count!=`number`||!Number.isInteger(r.count)||r.count<0||r.invalid!==void 0&&typeof r.invalid!=`boolean`||r.limited!==void 0&&typeof r.limited!=`boolean`?null:{kind:ta,channel:n,index:r.index,count:r.count,...r.invalid===void 0?{}:{invalid:r.invalid},...r.limited===void 0?{}:{limited:r.limited}}:null}function ia(e,t,n,r,i){e?.postMessage({kind:ea,channel:t,query:n,options:r,direction:i},`*`)}function aa(e,t){e?.postMessage({kind:na,channel:t},`*`)}function oa(e){return`(() => {
|
|
128
|
+
const channel = ${JSON.stringify(e)};
|
|
129
|
+
const openKind = ${JSON.stringify($i)};
|
|
130
|
+
const applyKind = ${JSON.stringify(ea)};
|
|
131
|
+
const resultKind = ${JSON.stringify(ta)};
|
|
132
|
+
const clearKind = ${JSON.stringify(na)};
|
|
133
|
+
const matchName = 'puddle-find-match';
|
|
134
|
+
const activeName = 'puddle-find-active';
|
|
135
|
+
const limit = 1000;
|
|
136
|
+
let signature = '';
|
|
137
|
+
let ranges = [];
|
|
138
|
+
let index = -1;
|
|
139
|
+
let limited = false;
|
|
140
|
+
|
|
141
|
+
const style = document.createElement('style');
|
|
142
|
+
style.textContent =
|
|
143
|
+
'::highlight(' + matchName + ') { background: Mark; color: MarkText; }' +
|
|
144
|
+
'::highlight(' + activeName + ') { background: Highlight; color: HighlightText; }';
|
|
145
|
+
(document.head || document.documentElement).appendChild(style);
|
|
146
|
+
|
|
147
|
+
const clearHighlights = () => {
|
|
148
|
+
CSS.highlights.delete(matchName);
|
|
149
|
+
CSS.highlights.delete(activeName);
|
|
150
|
+
};
|
|
151
|
+
const clear = () => {
|
|
152
|
+
signature = '';
|
|
153
|
+
ranges = [];
|
|
154
|
+
index = -1;
|
|
155
|
+
limited = false;
|
|
156
|
+
clearHighlights();
|
|
157
|
+
};
|
|
158
|
+
const report = (invalid = false) => {
|
|
159
|
+
parent.postMessage({
|
|
160
|
+
kind: resultKind,
|
|
161
|
+
channel,
|
|
162
|
+
index,
|
|
163
|
+
count: ranges.length,
|
|
164
|
+
invalid,
|
|
165
|
+
limited,
|
|
166
|
+
}, '*');
|
|
167
|
+
};
|
|
168
|
+
const textNodes = () => {
|
|
169
|
+
const walker = document.createTreeWalker(document.body || document.documentElement,
|
|
170
|
+
NodeFilter.SHOW_TEXT, {
|
|
171
|
+
acceptNode(node) {
|
|
172
|
+
const parent = node.parentElement;
|
|
173
|
+
if (!node.textContent || (parent && parent.closest(
|
|
174
|
+
'script, style, noscript, [hidden], [aria-hidden="true"]'
|
|
175
|
+
))) return NodeFilter.FILTER_REJECT;
|
|
176
|
+
return NodeFilter.FILTER_ACCEPT;
|
|
177
|
+
}
|
|
178
|
+
});
|
|
179
|
+
const nodes = [];
|
|
180
|
+
let text = '';
|
|
181
|
+
let node;
|
|
182
|
+
while (node = walker.nextNode()) {
|
|
183
|
+
const value = node.textContent || '';
|
|
184
|
+
const start = text.length;
|
|
185
|
+
text += value;
|
|
186
|
+
nodes.push({ node, start, end: text.length });
|
|
187
|
+
}
|
|
188
|
+
return { text, nodes };
|
|
189
|
+
};
|
|
190
|
+
const compile = (query, options) => {
|
|
191
|
+
const slash = String.fromCharCode(92);
|
|
192
|
+
const specials = new Set(['.', '*', '+', '?', '^', '$', '{', '}', '(', ')', '|', '[', ']', slash]);
|
|
193
|
+
let pattern = options.regex
|
|
194
|
+
? query
|
|
195
|
+
: Array.from(query, (character) => specials.has(character) ? slash + character : character).join('');
|
|
196
|
+
if (options.wholeWord) pattern = slash + 'b(?:' + pattern + ')' + slash + 'b';
|
|
197
|
+
return new RegExp(pattern, options.caseSensitive ? 'g' : 'gi');
|
|
198
|
+
};
|
|
199
|
+
const rangeFor = (match, nodes) => {
|
|
200
|
+
const first = nodes.find((entry) => entry.end > match.start);
|
|
201
|
+
const last = nodes.findLast((entry) => entry.start < match.end);
|
|
202
|
+
if (!first || !last) return null;
|
|
203
|
+
const range = document.createRange();
|
|
204
|
+
range.setStart(first.node, match.start - first.start);
|
|
205
|
+
range.setEnd(last.node, match.end - last.start);
|
|
206
|
+
return range;
|
|
207
|
+
};
|
|
208
|
+
const rebuild = (query, options) => {
|
|
209
|
+
ranges = [];
|
|
210
|
+
limited = false;
|
|
211
|
+
index = -1;
|
|
212
|
+
if (!query) return false;
|
|
213
|
+
let matcher;
|
|
214
|
+
try {
|
|
215
|
+
matcher = compile(query, options);
|
|
216
|
+
} catch {
|
|
217
|
+
return true;
|
|
218
|
+
}
|
|
219
|
+
const content = textNodes();
|
|
220
|
+
let match;
|
|
221
|
+
while (match = matcher.exec(content.text)) {
|
|
222
|
+
if (!match[0].length) {
|
|
223
|
+
matcher.lastIndex++;
|
|
224
|
+
continue;
|
|
225
|
+
}
|
|
226
|
+
if (ranges.length === limit) {
|
|
227
|
+
limited = true;
|
|
228
|
+
break;
|
|
229
|
+
}
|
|
230
|
+
const range = rangeFor(
|
|
231
|
+
{ start: match.index, end: match.index + match[0].length },
|
|
232
|
+
content.nodes,
|
|
233
|
+
);
|
|
234
|
+
if (range) ranges.push(range);
|
|
235
|
+
}
|
|
236
|
+
index = ranges.length ? 0 : -1;
|
|
237
|
+
return false;
|
|
238
|
+
};
|
|
239
|
+
const paint = () => {
|
|
240
|
+
clearHighlights();
|
|
241
|
+
if (!ranges.length) return;
|
|
242
|
+
CSS.highlights.set(matchName, new Highlight(...ranges));
|
|
243
|
+
const active = ranges[index];
|
|
244
|
+
if (!active) return;
|
|
245
|
+
CSS.highlights.set(activeName, new Highlight(active));
|
|
246
|
+
const element = active.startContainer.parentElement;
|
|
247
|
+
if (element) element.scrollIntoView({ block: 'center', inline: 'nearest' });
|
|
248
|
+
};
|
|
249
|
+
|
|
250
|
+
addEventListener('keydown', (event) => {
|
|
251
|
+
const mac = /Mac|iPhone|iPad/.test(navigator.platform);
|
|
252
|
+
const modifier = mac
|
|
253
|
+
? event.metaKey && !event.ctrlKey
|
|
254
|
+
: event.ctrlKey && !event.metaKey;
|
|
255
|
+
if (event.key.toLowerCase() !== 'f' || !modifier || event.altKey || event.shiftKey) return;
|
|
256
|
+
event.preventDefault();
|
|
257
|
+
event.stopPropagation();
|
|
258
|
+
parent.postMessage({ kind: openKind, channel }, '*');
|
|
259
|
+
}, true);
|
|
260
|
+
|
|
261
|
+
addEventListener('message', (event) => {
|
|
262
|
+
const data = event.data;
|
|
263
|
+
if (event.source !== parent || !data || data.channel !== channel) return;
|
|
264
|
+
if (data.kind === clearKind) {
|
|
265
|
+
clear();
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
if (data.kind !== applyKind || typeof data.query !== 'string' ||
|
|
269
|
+
!data.options || typeof data.options !== 'object') return;
|
|
270
|
+
const nextSignature = JSON.stringify([data.query, data.options]);
|
|
271
|
+
let invalid = false;
|
|
272
|
+
if (nextSignature !== signature || data.direction === 'reset') {
|
|
273
|
+
signature = nextSignature;
|
|
274
|
+
invalid = rebuild(data.query, data.options);
|
|
275
|
+
} else if (ranges.length) {
|
|
276
|
+
index = data.direction === 'previous'
|
|
277
|
+
? (index - 1 + ranges.length) % ranges.length
|
|
278
|
+
: (index + 1) % ranges.length;
|
|
279
|
+
}
|
|
280
|
+
if (invalid) clearHighlights();
|
|
281
|
+
else paint();
|
|
282
|
+
report(invalid);
|
|
283
|
+
});
|
|
284
|
+
})();`}function sa(e,t){let n=e.createElement(`script`);n.textContent=oa(t),(e.body??e.documentElement).appendChild(n)}var ca=`script, style, pre, code, kbd, samp, textarea, math, svg, .katex`,la=/\bmathjax\b|\bkatex\b/i;function ua(e){if(fa(e))return!1;let t=e.body??e.documentElement;return t?da(t):!1}function da(e){let t=e.ownerDocument,n=t.createTreeWalker(e,NodeFilter.SHOW_TEXT),r=[];for(;n.nextNode();){let e=n.currentNode;/[$\\]/.test(e.data)&&(e.parentElement?.closest(ca)||r.push(e))}let i={},a=!1;for(let e of r)pa(t,e,i)&&(a=!0);return a}function fa(e){if(e.querySelector(`.katex, math`))return!0;for(let t of e.querySelectorAll(`script`))if(la.test(t.getAttribute(`src`)??``)||la.test(t.textContent??``))return!0;return!1}function pa(e,t,n){let r=t.data;if(!rn(r))return!1;let i=e.createDocumentFragment(),a=e.createElement(`span`),o=0;for(let t=rn(r,0);t;t=rn(r,o)){for(t.start>o&&i.appendChild(e.createTextNode(r.slice(o,t.start))),a.innerHTML=tn(t.tex,t.display,n);a.firstChild;)i.appendChild(a.firstChild);o=t.start+t.length}return o<r.length&&i.appendChild(e.createTextNode(r.slice(o))),t.replaceWith(i),!0}var ma=new Set([65534,65535,131070,131071,196606,196607,262142,262143,327678,327679,393214,393215,458750,458751,524286,524287,589822,589823,655358,655359,720894,720895,786430,786431,851966,851967,917502,917503,983038,983039,1048574,1048575,1114110,1114111]),V;(function(e){e[e.EOF=-1]=`EOF`,e[e.NULL=0]=`NULL`,e[e.TABULATION=9]=`TABULATION`,e[e.CARRIAGE_RETURN=13]=`CARRIAGE_RETURN`,e[e.LINE_FEED=10]=`LINE_FEED`,e[e.FORM_FEED=12]=`FORM_FEED`,e[e.SPACE=32]=`SPACE`,e[e.EXCLAMATION_MARK=33]=`EXCLAMATION_MARK`,e[e.QUOTATION_MARK=34]=`QUOTATION_MARK`,e[e.AMPERSAND=38]=`AMPERSAND`,e[e.APOSTROPHE=39]=`APOSTROPHE`,e[e.HYPHEN_MINUS=45]=`HYPHEN_MINUS`,e[e.SOLIDUS=47]=`SOLIDUS`,e[e.DIGIT_0=48]=`DIGIT_0`,e[e.DIGIT_9=57]=`DIGIT_9`,e[e.SEMICOLON=59]=`SEMICOLON`,e[e.LESS_THAN_SIGN=60]=`LESS_THAN_SIGN`,e[e.EQUALS_SIGN=61]=`EQUALS_SIGN`,e[e.GREATER_THAN_SIGN=62]=`GREATER_THAN_SIGN`,e[e.QUESTION_MARK=63]=`QUESTION_MARK`,e[e.LATIN_CAPITAL_A=65]=`LATIN_CAPITAL_A`,e[e.LATIN_CAPITAL_Z=90]=`LATIN_CAPITAL_Z`,e[e.RIGHT_SQUARE_BRACKET=93]=`RIGHT_SQUARE_BRACKET`,e[e.GRAVE_ACCENT=96]=`GRAVE_ACCENT`,e[e.LATIN_SMALL_A=97]=`LATIN_SMALL_A`,e[e.LATIN_SMALL_Z=122]=`LATIN_SMALL_Z`})(V||={});var H={DASH_DASH:`--`,CDATA_START:`[CDATA[`,DOCTYPE:`doctype`,SCRIPT:`script`,PUBLIC:`public`,SYSTEM:`system`};function ha(e){return e>=55296&&e<=57343}function ga(e){return e>=56320&&e<=57343}function _a(e,t){return(e-55296)*1024+9216+t}function va(e){return e!==32&&e!==10&&e!==13&&e!==9&&e!==12&&e>=1&&e<=31||e>=127&&e<=159}function ya(e){return e>=64976&&e<=65007||ma.has(e)}var U;(function(e){e.controlCharacterInInputStream=`control-character-in-input-stream`,e.noncharacterInInputStream=`noncharacter-in-input-stream`,e.surrogateInInputStream=`surrogate-in-input-stream`,e.nonVoidHtmlElementStartTagWithTrailingSolidus=`non-void-html-element-start-tag-with-trailing-solidus`,e.endTagWithAttributes=`end-tag-with-attributes`,e.endTagWithTrailingSolidus=`end-tag-with-trailing-solidus`,e.unexpectedSolidusInTag=`unexpected-solidus-in-tag`,e.unexpectedNullCharacter=`unexpected-null-character`,e.unexpectedQuestionMarkInsteadOfTagName=`unexpected-question-mark-instead-of-tag-name`,e.invalidFirstCharacterOfTagName=`invalid-first-character-of-tag-name`,e.unexpectedEqualsSignBeforeAttributeName=`unexpected-equals-sign-before-attribute-name`,e.missingEndTagName=`missing-end-tag-name`,e.unexpectedCharacterInAttributeName=`unexpected-character-in-attribute-name`,e.unknownNamedCharacterReference=`unknown-named-character-reference`,e.missingSemicolonAfterCharacterReference=`missing-semicolon-after-character-reference`,e.unexpectedCharacterAfterDoctypeSystemIdentifier=`unexpected-character-after-doctype-system-identifier`,e.unexpectedCharacterInUnquotedAttributeValue=`unexpected-character-in-unquoted-attribute-value`,e.eofBeforeTagName=`eof-before-tag-name`,e.eofInTag=`eof-in-tag`,e.missingAttributeValue=`missing-attribute-value`,e.missingWhitespaceBetweenAttributes=`missing-whitespace-between-attributes`,e.missingWhitespaceAfterDoctypePublicKeyword=`missing-whitespace-after-doctype-public-keyword`,e.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers=`missing-whitespace-between-doctype-public-and-system-identifiers`,e.missingWhitespaceAfterDoctypeSystemKeyword=`missing-whitespace-after-doctype-system-keyword`,e.missingQuoteBeforeDoctypePublicIdentifier=`missing-quote-before-doctype-public-identifier`,e.missingQuoteBeforeDoctypeSystemIdentifier=`missing-quote-before-doctype-system-identifier`,e.missingDoctypePublicIdentifier=`missing-doctype-public-identifier`,e.missingDoctypeSystemIdentifier=`missing-doctype-system-identifier`,e.abruptDoctypePublicIdentifier=`abrupt-doctype-public-identifier`,e.abruptDoctypeSystemIdentifier=`abrupt-doctype-system-identifier`,e.cdataInHtmlContent=`cdata-in-html-content`,e.incorrectlyOpenedComment=`incorrectly-opened-comment`,e.eofInScriptHtmlCommentLikeText=`eof-in-script-html-comment-like-text`,e.eofInDoctype=`eof-in-doctype`,e.nestedComment=`nested-comment`,e.abruptClosingOfEmptyComment=`abrupt-closing-of-empty-comment`,e.eofInComment=`eof-in-comment`,e.incorrectlyClosedComment=`incorrectly-closed-comment`,e.eofInCdata=`eof-in-cdata`,e.absenceOfDigitsInNumericCharacterReference=`absence-of-digits-in-numeric-character-reference`,e.nullCharacterReference=`null-character-reference`,e.surrogateCharacterReference=`surrogate-character-reference`,e.characterReferenceOutsideUnicodeRange=`character-reference-outside-unicode-range`,e.controlCharacterReference=`control-character-reference`,e.noncharacterCharacterReference=`noncharacter-character-reference`,e.missingWhitespaceBeforeDoctypeName=`missing-whitespace-before-doctype-name`,e.missingDoctypeName=`missing-doctype-name`,e.invalidCharacterSequenceAfterDoctypeName=`invalid-character-sequence-after-doctype-name`,e.duplicateAttribute=`duplicate-attribute`,e.nonConformingDoctype=`non-conforming-doctype`,e.missingDoctype=`missing-doctype`,e.misplacedDoctype=`misplaced-doctype`,e.endTagWithoutMatchingOpenElement=`end-tag-without-matching-open-element`,e.closingOfElementWithOpenChildElements=`closing-of-element-with-open-child-elements`,e.disallowedContentInNoscriptInHead=`disallowed-content-in-noscript-in-head`,e.openElementsLeftAfterEof=`open-elements-left-after-eof`,e.abandonedHeadElementChild=`abandoned-head-element-child`,e.misplacedStartTagForHeadElement=`misplaced-start-tag-for-head-element`,e.nestedNoscriptInHead=`nested-noscript-in-head`,e.eofInElementThatCanContainOnlyText=`eof-in-element-that-can-contain-only-text`})(U||={});var ba=65536,xa=class{constructor(e){this.handler=e,this.html=``,this.pos=-1,this.lastGapPos=-2,this.gapStack=[],this.skipNextNewLine=!1,this.lastChunkWritten=!1,this.endOfChunkHit=!1,this.bufferWaterline=ba,this.isEol=!1,this.lineStartPos=0,this.droppedBufferSize=0,this.line=1,this.lastErrOffset=-1}get col(){return this.pos-this.lineStartPos+Number(this.lastGapPos!==this.pos)}get offset(){return this.droppedBufferSize+this.pos}getError(e,t){let{line:n,col:r,offset:i}=this,a=r+t,o=i+t;return{code:e,startLine:n,endLine:n,startCol:a,endCol:a,startOffset:o,endOffset:o}}_err(e){this.handler.onParseError&&this.lastErrOffset!==this.offset&&(this.lastErrOffset=this.offset,this.handler.onParseError(this.getError(e,0)))}_addGap(){this.gapStack.push(this.lastGapPos),this.lastGapPos=this.pos}_processSurrogate(e){if(this.pos!==this.html.length-1){let t=this.html.charCodeAt(this.pos+1);if(ga(t))return this.pos++,this._addGap(),_a(e,t)}else if(!this.lastChunkWritten)return this.endOfChunkHit=!0,V.EOF;return this._err(U.surrogateInInputStream),e}willDropParsedChunk(){return this.pos>this.bufferWaterline}dropParsedChunk(){this.willDropParsedChunk()&&(this.html=this.html.substring(this.pos),this.lineStartPos-=this.pos,this.droppedBufferSize+=this.pos,this.pos=0,this.lastGapPos=-2,this.gapStack.length=0)}write(e,t){this.html.length>0?this.html+=e:this.html=e,this.endOfChunkHit=!1,this.lastChunkWritten=t}insertHtmlAtCurrentPos(e){this.html=this.html.substring(0,this.pos+1)+e+this.html.substring(this.pos+1),this.endOfChunkHit=!1}startsWith(e,t){if(this.pos+e.length>this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,!1;if(t)return this.html.startsWith(e,this.pos);for(let t=0;t<e.length;t++)if((this.html.charCodeAt(this.pos+t)|32)!==e.charCodeAt(t))return!1;return!0}peek(e){let t=this.pos+e;if(t>=this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,V.EOF;let n=this.html.charCodeAt(t);return n===V.CARRIAGE_RETURN?V.LINE_FEED:n}advance(){if(this.pos++,this.isEol&&(this.isEol=!1,this.line++,this.lineStartPos=this.pos),this.pos>=this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,V.EOF;let e=this.html.charCodeAt(this.pos);return e===V.CARRIAGE_RETURN?(this.isEol=!0,this.skipNextNewLine=!0,V.LINE_FEED):e===V.LINE_FEED&&(this.isEol=!0,this.skipNextNewLine)?(this.line--,this.skipNextNewLine=!1,this._addGap(),this.advance()):(this.skipNextNewLine=!1,ha(e)&&(e=this._processSurrogate(e)),this.handler.onParseError===null||e>31&&e<127||e===V.LINE_FEED||e===V.CARRIAGE_RETURN||e>159&&e<64976||this._checkForProblematicCharacters(e),e)}_checkForProblematicCharacters(e){va(e)?this._err(U.controlCharacterInInputStream):ya(e)&&this._err(U.noncharacterInInputStream)}retreat(e){for(this.pos-=e;this.pos<this.lastGapPos;)this.lastGapPos=this.gapStack.pop(),this.pos--;this.isEol=!1}},W;(function(e){e[e.CHARACTER=0]=`CHARACTER`,e[e.NULL_CHARACTER=1]=`NULL_CHARACTER`,e[e.WHITESPACE_CHARACTER=2]=`WHITESPACE_CHARACTER`,e[e.START_TAG=3]=`START_TAG`,e[e.END_TAG=4]=`END_TAG`,e[e.COMMENT=5]=`COMMENT`,e[e.DOCTYPE=6]=`DOCTYPE`,e[e.EOF=7]=`EOF`,e[e.HIBERNATION=8]=`HIBERNATION`})(W||={});function Sa(e,t){for(let n=e.attrs.length-1;n>=0;n--)if(e.attrs[n].name===t)return e.attrs[n].value;return null}var G;(function(e){e.HTML=`http://www.w3.org/1999/xhtml`,e.MATHML=`http://www.w3.org/1998/Math/MathML`,e.SVG=`http://www.w3.org/2000/svg`,e.XLINK=`http://www.w3.org/1999/xlink`,e.XML=`http://www.w3.org/XML/1998/namespace`,e.XMLNS=`http://www.w3.org/2000/xmlns/`})(G||={});var Ca;(function(e){e.TYPE=`type`,e.ACTION=`action`,e.ENCODING=`encoding`,e.PROMPT=`prompt`,e.NAME=`name`,e.COLOR=`color`,e.FACE=`face`,e.SIZE=`size`})(Ca||={});var K;(function(e){e.NO_QUIRKS=`no-quirks`,e.QUIRKS=`quirks`,e.LIMITED_QUIRKS=`limited-quirks`})(K||={});var q;(function(e){e.A=`a`,e.ADDRESS=`address`,e.ANNOTATION_XML=`annotation-xml`,e.APPLET=`applet`,e.AREA=`area`,e.ARTICLE=`article`,e.ASIDE=`aside`,e.B=`b`,e.BASE=`base`,e.BASEFONT=`basefont`,e.BGSOUND=`bgsound`,e.BIG=`big`,e.BLOCKQUOTE=`blockquote`,e.BODY=`body`,e.BR=`br`,e.BUTTON=`button`,e.CAPTION=`caption`,e.CENTER=`center`,e.CODE=`code`,e.COL=`col`,e.COLGROUP=`colgroup`,e.DD=`dd`,e.DESC=`desc`,e.DETAILS=`details`,e.DIALOG=`dialog`,e.DIR=`dir`,e.DIV=`div`,e.DL=`dl`,e.DT=`dt`,e.EM=`em`,e.EMBED=`embed`,e.FIELDSET=`fieldset`,e.FIGCAPTION=`figcaption`,e.FIGURE=`figure`,e.FONT=`font`,e.FOOTER=`footer`,e.FOREIGN_OBJECT=`foreignObject`,e.FORM=`form`,e.FRAME=`frame`,e.FRAMESET=`frameset`,e.H1=`h1`,e.H2=`h2`,e.H3=`h3`,e.H4=`h4`,e.H5=`h5`,e.H6=`h6`,e.HEAD=`head`,e.HEADER=`header`,e.HGROUP=`hgroup`,e.HR=`hr`,e.HTML=`html`,e.I=`i`,e.IMG=`img`,e.IMAGE=`image`,e.INPUT=`input`,e.IFRAME=`iframe`,e.KEYGEN=`keygen`,e.LABEL=`label`,e.LI=`li`,e.LINK=`link`,e.LISTING=`listing`,e.MAIN=`main`,e.MALIGNMARK=`malignmark`,e.MARQUEE=`marquee`,e.MATH=`math`,e.MENU=`menu`,e.META=`meta`,e.MGLYPH=`mglyph`,e.MI=`mi`,e.MO=`mo`,e.MN=`mn`,e.MS=`ms`,e.MTEXT=`mtext`,e.NAV=`nav`,e.NOBR=`nobr`,e.NOFRAMES=`noframes`,e.NOEMBED=`noembed`,e.NOSCRIPT=`noscript`,e.OBJECT=`object`,e.OL=`ol`,e.OPTGROUP=`optgroup`,e.OPTION=`option`,e.P=`p`,e.PARAM=`param`,e.PLAINTEXT=`plaintext`,e.PRE=`pre`,e.RB=`rb`,e.RP=`rp`,e.RT=`rt`,e.RTC=`rtc`,e.RUBY=`ruby`,e.S=`s`,e.SCRIPT=`script`,e.SEARCH=`search`,e.SECTION=`section`,e.SELECT=`select`,e.SOURCE=`source`,e.SMALL=`small`,e.SPAN=`span`,e.STRIKE=`strike`,e.STRONG=`strong`,e.STYLE=`style`,e.SUB=`sub`,e.SUMMARY=`summary`,e.SUP=`sup`,e.TABLE=`table`,e.TBODY=`tbody`,e.TEMPLATE=`template`,e.TEXTAREA=`textarea`,e.TFOOT=`tfoot`,e.TD=`td`,e.TH=`th`,e.THEAD=`thead`,e.TITLE=`title`,e.TR=`tr`,e.TRACK=`track`,e.TT=`tt`,e.U=`u`,e.UL=`ul`,e.SVG=`svg`,e.VAR=`var`,e.WBR=`wbr`,e.XMP=`xmp`})(q||={});var J;(function(e){e[e.UNKNOWN=0]=`UNKNOWN`,e[e.A=1]=`A`,e[e.ADDRESS=2]=`ADDRESS`,e[e.ANNOTATION_XML=3]=`ANNOTATION_XML`,e[e.APPLET=4]=`APPLET`,e[e.AREA=5]=`AREA`,e[e.ARTICLE=6]=`ARTICLE`,e[e.ASIDE=7]=`ASIDE`,e[e.B=8]=`B`,e[e.BASE=9]=`BASE`,e[e.BASEFONT=10]=`BASEFONT`,e[e.BGSOUND=11]=`BGSOUND`,e[e.BIG=12]=`BIG`,e[e.BLOCKQUOTE=13]=`BLOCKQUOTE`,e[e.BODY=14]=`BODY`,e[e.BR=15]=`BR`,e[e.BUTTON=16]=`BUTTON`,e[e.CAPTION=17]=`CAPTION`,e[e.CENTER=18]=`CENTER`,e[e.CODE=19]=`CODE`,e[e.COL=20]=`COL`,e[e.COLGROUP=21]=`COLGROUP`,e[e.DD=22]=`DD`,e[e.DESC=23]=`DESC`,e[e.DETAILS=24]=`DETAILS`,e[e.DIALOG=25]=`DIALOG`,e[e.DIR=26]=`DIR`,e[e.DIV=27]=`DIV`,e[e.DL=28]=`DL`,e[e.DT=29]=`DT`,e[e.EM=30]=`EM`,e[e.EMBED=31]=`EMBED`,e[e.FIELDSET=32]=`FIELDSET`,e[e.FIGCAPTION=33]=`FIGCAPTION`,e[e.FIGURE=34]=`FIGURE`,e[e.FONT=35]=`FONT`,e[e.FOOTER=36]=`FOOTER`,e[e.FOREIGN_OBJECT=37]=`FOREIGN_OBJECT`,e[e.FORM=38]=`FORM`,e[e.FRAME=39]=`FRAME`,e[e.FRAMESET=40]=`FRAMESET`,e[e.H1=41]=`H1`,e[e.H2=42]=`H2`,e[e.H3=43]=`H3`,e[e.H4=44]=`H4`,e[e.H5=45]=`H5`,e[e.H6=46]=`H6`,e[e.HEAD=47]=`HEAD`,e[e.HEADER=48]=`HEADER`,e[e.HGROUP=49]=`HGROUP`,e[e.HR=50]=`HR`,e[e.HTML=51]=`HTML`,e[e.I=52]=`I`,e[e.IMG=53]=`IMG`,e[e.IMAGE=54]=`IMAGE`,e[e.INPUT=55]=`INPUT`,e[e.IFRAME=56]=`IFRAME`,e[e.KEYGEN=57]=`KEYGEN`,e[e.LABEL=58]=`LABEL`,e[e.LI=59]=`LI`,e[e.LINK=60]=`LINK`,e[e.LISTING=61]=`LISTING`,e[e.MAIN=62]=`MAIN`,e[e.MALIGNMARK=63]=`MALIGNMARK`,e[e.MARQUEE=64]=`MARQUEE`,e[e.MATH=65]=`MATH`,e[e.MENU=66]=`MENU`,e[e.META=67]=`META`,e[e.MGLYPH=68]=`MGLYPH`,e[e.MI=69]=`MI`,e[e.MO=70]=`MO`,e[e.MN=71]=`MN`,e[e.MS=72]=`MS`,e[e.MTEXT=73]=`MTEXT`,e[e.NAV=74]=`NAV`,e[e.NOBR=75]=`NOBR`,e[e.NOFRAMES=76]=`NOFRAMES`,e[e.NOEMBED=77]=`NOEMBED`,e[e.NOSCRIPT=78]=`NOSCRIPT`,e[e.OBJECT=79]=`OBJECT`,e[e.OL=80]=`OL`,e[e.OPTGROUP=81]=`OPTGROUP`,e[e.OPTION=82]=`OPTION`,e[e.P=83]=`P`,e[e.PARAM=84]=`PARAM`,e[e.PLAINTEXT=85]=`PLAINTEXT`,e[e.PRE=86]=`PRE`,e[e.RB=87]=`RB`,e[e.RP=88]=`RP`,e[e.RT=89]=`RT`,e[e.RTC=90]=`RTC`,e[e.RUBY=91]=`RUBY`,e[e.S=92]=`S`,e[e.SCRIPT=93]=`SCRIPT`,e[e.SEARCH=94]=`SEARCH`,e[e.SECTION=95]=`SECTION`,e[e.SELECT=96]=`SELECT`,e[e.SOURCE=97]=`SOURCE`,e[e.SMALL=98]=`SMALL`,e[e.SPAN=99]=`SPAN`,e[e.STRIKE=100]=`STRIKE`,e[e.STRONG=101]=`STRONG`,e[e.STYLE=102]=`STYLE`,e[e.SUB=103]=`SUB`,e[e.SUMMARY=104]=`SUMMARY`,e[e.SUP=105]=`SUP`,e[e.TABLE=106]=`TABLE`,e[e.TBODY=107]=`TBODY`,e[e.TEMPLATE=108]=`TEMPLATE`,e[e.TEXTAREA=109]=`TEXTAREA`,e[e.TFOOT=110]=`TFOOT`,e[e.TD=111]=`TD`,e[e.TH=112]=`TH`,e[e.THEAD=113]=`THEAD`,e[e.TITLE=114]=`TITLE`,e[e.TR=115]=`TR`,e[e.TRACK=116]=`TRACK`,e[e.TT=117]=`TT`,e[e.U=118]=`U`,e[e.UL=119]=`UL`,e[e.SVG=120]=`SVG`,e[e.VAR=121]=`VAR`,e[e.WBR=122]=`WBR`,e[e.XMP=123]=`XMP`})(J||={});var wa=new Map([[q.A,J.A],[q.ADDRESS,J.ADDRESS],[q.ANNOTATION_XML,J.ANNOTATION_XML],[q.APPLET,J.APPLET],[q.AREA,J.AREA],[q.ARTICLE,J.ARTICLE],[q.ASIDE,J.ASIDE],[q.B,J.B],[q.BASE,J.BASE],[q.BASEFONT,J.BASEFONT],[q.BGSOUND,J.BGSOUND],[q.BIG,J.BIG],[q.BLOCKQUOTE,J.BLOCKQUOTE],[q.BODY,J.BODY],[q.BR,J.BR],[q.BUTTON,J.BUTTON],[q.CAPTION,J.CAPTION],[q.CENTER,J.CENTER],[q.CODE,J.CODE],[q.COL,J.COL],[q.COLGROUP,J.COLGROUP],[q.DD,J.DD],[q.DESC,J.DESC],[q.DETAILS,J.DETAILS],[q.DIALOG,J.DIALOG],[q.DIR,J.DIR],[q.DIV,J.DIV],[q.DL,J.DL],[q.DT,J.DT],[q.EM,J.EM],[q.EMBED,J.EMBED],[q.FIELDSET,J.FIELDSET],[q.FIGCAPTION,J.FIGCAPTION],[q.FIGURE,J.FIGURE],[q.FONT,J.FONT],[q.FOOTER,J.FOOTER],[q.FOREIGN_OBJECT,J.FOREIGN_OBJECT],[q.FORM,J.FORM],[q.FRAME,J.FRAME],[q.FRAMESET,J.FRAMESET],[q.H1,J.H1],[q.H2,J.H2],[q.H3,J.H3],[q.H4,J.H4],[q.H5,J.H5],[q.H6,J.H6],[q.HEAD,J.HEAD],[q.HEADER,J.HEADER],[q.HGROUP,J.HGROUP],[q.HR,J.HR],[q.HTML,J.HTML],[q.I,J.I],[q.IMG,J.IMG],[q.IMAGE,J.IMAGE],[q.INPUT,J.INPUT],[q.IFRAME,J.IFRAME],[q.KEYGEN,J.KEYGEN],[q.LABEL,J.LABEL],[q.LI,J.LI],[q.LINK,J.LINK],[q.LISTING,J.LISTING],[q.MAIN,J.MAIN],[q.MALIGNMARK,J.MALIGNMARK],[q.MARQUEE,J.MARQUEE],[q.MATH,J.MATH],[q.MENU,J.MENU],[q.META,J.META],[q.MGLYPH,J.MGLYPH],[q.MI,J.MI],[q.MO,J.MO],[q.MN,J.MN],[q.MS,J.MS],[q.MTEXT,J.MTEXT],[q.NAV,J.NAV],[q.NOBR,J.NOBR],[q.NOFRAMES,J.NOFRAMES],[q.NOEMBED,J.NOEMBED],[q.NOSCRIPT,J.NOSCRIPT],[q.OBJECT,J.OBJECT],[q.OL,J.OL],[q.OPTGROUP,J.OPTGROUP],[q.OPTION,J.OPTION],[q.P,J.P],[q.PARAM,J.PARAM],[q.PLAINTEXT,J.PLAINTEXT],[q.PRE,J.PRE],[q.RB,J.RB],[q.RP,J.RP],[q.RT,J.RT],[q.RTC,J.RTC],[q.RUBY,J.RUBY],[q.S,J.S],[q.SCRIPT,J.SCRIPT],[q.SEARCH,J.SEARCH],[q.SECTION,J.SECTION],[q.SELECT,J.SELECT],[q.SOURCE,J.SOURCE],[q.SMALL,J.SMALL],[q.SPAN,J.SPAN],[q.STRIKE,J.STRIKE],[q.STRONG,J.STRONG],[q.STYLE,J.STYLE],[q.SUB,J.SUB],[q.SUMMARY,J.SUMMARY],[q.SUP,J.SUP],[q.TABLE,J.TABLE],[q.TBODY,J.TBODY],[q.TEMPLATE,J.TEMPLATE],[q.TEXTAREA,J.TEXTAREA],[q.TFOOT,J.TFOOT],[q.TD,J.TD],[q.TH,J.TH],[q.THEAD,J.THEAD],[q.TITLE,J.TITLE],[q.TR,J.TR],[q.TRACK,J.TRACK],[q.TT,J.TT],[q.U,J.U],[q.UL,J.UL],[q.SVG,J.SVG],[q.VAR,J.VAR],[q.WBR,J.WBR],[q.XMP,J.XMP]]);function Ta(e){return wa.get(e)??J.UNKNOWN}var Y=J,Ea={[G.HTML]:new Set([Y.ADDRESS,Y.APPLET,Y.AREA,Y.ARTICLE,Y.ASIDE,Y.BASE,Y.BASEFONT,Y.BGSOUND,Y.BLOCKQUOTE,Y.BODY,Y.BR,Y.BUTTON,Y.CAPTION,Y.CENTER,Y.COL,Y.COLGROUP,Y.DD,Y.DETAILS,Y.DIR,Y.DIV,Y.DL,Y.DT,Y.EMBED,Y.FIELDSET,Y.FIGCAPTION,Y.FIGURE,Y.FOOTER,Y.FORM,Y.FRAME,Y.FRAMESET,Y.H1,Y.H2,Y.H3,Y.H4,Y.H5,Y.H6,Y.HEAD,Y.HEADER,Y.HGROUP,Y.HR,Y.HTML,Y.IFRAME,Y.IMG,Y.INPUT,Y.LI,Y.LINK,Y.LISTING,Y.MAIN,Y.MARQUEE,Y.MENU,Y.META,Y.NAV,Y.NOEMBED,Y.NOFRAMES,Y.NOSCRIPT,Y.OBJECT,Y.OL,Y.P,Y.PARAM,Y.PLAINTEXT,Y.PRE,Y.SCRIPT,Y.SECTION,Y.SELECT,Y.SOURCE,Y.STYLE,Y.SUMMARY,Y.TABLE,Y.TBODY,Y.TD,Y.TEMPLATE,Y.TEXTAREA,Y.TFOOT,Y.TH,Y.THEAD,Y.TITLE,Y.TR,Y.TRACK,Y.UL,Y.WBR,Y.XMP]),[G.MATHML]:new Set([Y.MI,Y.MO,Y.MN,Y.MS,Y.MTEXT,Y.ANNOTATION_XML]),[G.SVG]:new Set([Y.TITLE,Y.FOREIGN_OBJECT,Y.DESC]),[G.XLINK]:new Set,[G.XML]:new Set,[G.XMLNS]:new Set},Da=new Set([Y.H1,Y.H2,Y.H3,Y.H4,Y.H5,Y.H6]),Oa=new Set([q.STYLE,q.SCRIPT,q.XMP,q.IFRAME,q.NOEMBED,q.NOFRAMES,q.PLAINTEXT]);function ka(e,t){return Oa.has(e)||t&&e===q.NOSCRIPT}var X;(function(e){e[e.DATA=0]=`DATA`,e[e.RCDATA=1]=`RCDATA`,e[e.RAWTEXT=2]=`RAWTEXT`,e[e.SCRIPT_DATA=3]=`SCRIPT_DATA`,e[e.PLAINTEXT=4]=`PLAINTEXT`,e[e.TAG_OPEN=5]=`TAG_OPEN`,e[e.END_TAG_OPEN=6]=`END_TAG_OPEN`,e[e.TAG_NAME=7]=`TAG_NAME`,e[e.RCDATA_LESS_THAN_SIGN=8]=`RCDATA_LESS_THAN_SIGN`,e[e.RCDATA_END_TAG_OPEN=9]=`RCDATA_END_TAG_OPEN`,e[e.RCDATA_END_TAG_NAME=10]=`RCDATA_END_TAG_NAME`,e[e.RAWTEXT_LESS_THAN_SIGN=11]=`RAWTEXT_LESS_THAN_SIGN`,e[e.RAWTEXT_END_TAG_OPEN=12]=`RAWTEXT_END_TAG_OPEN`,e[e.RAWTEXT_END_TAG_NAME=13]=`RAWTEXT_END_TAG_NAME`,e[e.SCRIPT_DATA_LESS_THAN_SIGN=14]=`SCRIPT_DATA_LESS_THAN_SIGN`,e[e.SCRIPT_DATA_END_TAG_OPEN=15]=`SCRIPT_DATA_END_TAG_OPEN`,e[e.SCRIPT_DATA_END_TAG_NAME=16]=`SCRIPT_DATA_END_TAG_NAME`,e[e.SCRIPT_DATA_ESCAPE_START=17]=`SCRIPT_DATA_ESCAPE_START`,e[e.SCRIPT_DATA_ESCAPE_START_DASH=18]=`SCRIPT_DATA_ESCAPE_START_DASH`,e[e.SCRIPT_DATA_ESCAPED=19]=`SCRIPT_DATA_ESCAPED`,e[e.SCRIPT_DATA_ESCAPED_DASH=20]=`SCRIPT_DATA_ESCAPED_DASH`,e[e.SCRIPT_DATA_ESCAPED_DASH_DASH=21]=`SCRIPT_DATA_ESCAPED_DASH_DASH`,e[e.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN=22]=`SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN`,e[e.SCRIPT_DATA_ESCAPED_END_TAG_OPEN=23]=`SCRIPT_DATA_ESCAPED_END_TAG_OPEN`,e[e.SCRIPT_DATA_ESCAPED_END_TAG_NAME=24]=`SCRIPT_DATA_ESCAPED_END_TAG_NAME`,e[e.SCRIPT_DATA_DOUBLE_ESCAPE_START=25]=`SCRIPT_DATA_DOUBLE_ESCAPE_START`,e[e.SCRIPT_DATA_DOUBLE_ESCAPED=26]=`SCRIPT_DATA_DOUBLE_ESCAPED`,e[e.SCRIPT_DATA_DOUBLE_ESCAPED_DASH=27]=`SCRIPT_DATA_DOUBLE_ESCAPED_DASH`,e[e.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH=28]=`SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH`,e[e.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN=29]=`SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN`,e[e.SCRIPT_DATA_DOUBLE_ESCAPE_END=30]=`SCRIPT_DATA_DOUBLE_ESCAPE_END`,e[e.BEFORE_ATTRIBUTE_NAME=31]=`BEFORE_ATTRIBUTE_NAME`,e[e.ATTRIBUTE_NAME=32]=`ATTRIBUTE_NAME`,e[e.AFTER_ATTRIBUTE_NAME=33]=`AFTER_ATTRIBUTE_NAME`,e[e.BEFORE_ATTRIBUTE_VALUE=34]=`BEFORE_ATTRIBUTE_VALUE`,e[e.ATTRIBUTE_VALUE_DOUBLE_QUOTED=35]=`ATTRIBUTE_VALUE_DOUBLE_QUOTED`,e[e.ATTRIBUTE_VALUE_SINGLE_QUOTED=36]=`ATTRIBUTE_VALUE_SINGLE_QUOTED`,e[e.ATTRIBUTE_VALUE_UNQUOTED=37]=`ATTRIBUTE_VALUE_UNQUOTED`,e[e.AFTER_ATTRIBUTE_VALUE_QUOTED=38]=`AFTER_ATTRIBUTE_VALUE_QUOTED`,e[e.SELF_CLOSING_START_TAG=39]=`SELF_CLOSING_START_TAG`,e[e.BOGUS_COMMENT=40]=`BOGUS_COMMENT`,e[e.MARKUP_DECLARATION_OPEN=41]=`MARKUP_DECLARATION_OPEN`,e[e.COMMENT_START=42]=`COMMENT_START`,e[e.COMMENT_START_DASH=43]=`COMMENT_START_DASH`,e[e.COMMENT=44]=`COMMENT`,e[e.COMMENT_LESS_THAN_SIGN=45]=`COMMENT_LESS_THAN_SIGN`,e[e.COMMENT_LESS_THAN_SIGN_BANG=46]=`COMMENT_LESS_THAN_SIGN_BANG`,e[e.COMMENT_LESS_THAN_SIGN_BANG_DASH=47]=`COMMENT_LESS_THAN_SIGN_BANG_DASH`,e[e.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH=48]=`COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH`,e[e.COMMENT_END_DASH=49]=`COMMENT_END_DASH`,e[e.COMMENT_END=50]=`COMMENT_END`,e[e.COMMENT_END_BANG=51]=`COMMENT_END_BANG`,e[e.DOCTYPE=52]=`DOCTYPE`,e[e.BEFORE_DOCTYPE_NAME=53]=`BEFORE_DOCTYPE_NAME`,e[e.DOCTYPE_NAME=54]=`DOCTYPE_NAME`,e[e.AFTER_DOCTYPE_NAME=55]=`AFTER_DOCTYPE_NAME`,e[e.AFTER_DOCTYPE_PUBLIC_KEYWORD=56]=`AFTER_DOCTYPE_PUBLIC_KEYWORD`,e[e.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER=57]=`BEFORE_DOCTYPE_PUBLIC_IDENTIFIER`,e[e.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED=58]=`DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED`,e[e.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED=59]=`DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED`,e[e.AFTER_DOCTYPE_PUBLIC_IDENTIFIER=60]=`AFTER_DOCTYPE_PUBLIC_IDENTIFIER`,e[e.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS=61]=`BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS`,e[e.AFTER_DOCTYPE_SYSTEM_KEYWORD=62]=`AFTER_DOCTYPE_SYSTEM_KEYWORD`,e[e.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER=63]=`BEFORE_DOCTYPE_SYSTEM_IDENTIFIER`,e[e.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED=64]=`DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED`,e[e.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED=65]=`DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED`,e[e.AFTER_DOCTYPE_SYSTEM_IDENTIFIER=66]=`AFTER_DOCTYPE_SYSTEM_IDENTIFIER`,e[e.BOGUS_DOCTYPE=67]=`BOGUS_DOCTYPE`,e[e.CDATA_SECTION=68]=`CDATA_SECTION`,e[e.CDATA_SECTION_BRACKET=69]=`CDATA_SECTION_BRACKET`,e[e.CDATA_SECTION_END=70]=`CDATA_SECTION_END`,e[e.CHARACTER_REFERENCE=71]=`CHARACTER_REFERENCE`,e[e.AMBIGUOUS_AMPERSAND=72]=`AMBIGUOUS_AMPERSAND`})(X||={});var Z={DATA:X.DATA,RCDATA:X.RCDATA,RAWTEXT:X.RAWTEXT,SCRIPT_DATA:X.SCRIPT_DATA,PLAINTEXT:X.PLAINTEXT,CDATA_SECTION:X.CDATA_SECTION};function Aa(e){return e>=V.DIGIT_0&&e<=V.DIGIT_9}function ja(e){return e>=V.LATIN_CAPITAL_A&&e<=V.LATIN_CAPITAL_Z}function Ma(e){return e>=V.LATIN_SMALL_A&&e<=V.LATIN_SMALL_Z}function Na(e){return Ma(e)||ja(e)}function Pa(e){return Na(e)||Aa(e)}function Fa(e){return e+32}function Ia(e){return e===V.SPACE||e===V.LINE_FEED||e===V.TABULATION||e===V.FORM_FEED}function La(e){return Ia(e)||e===V.SOLIDUS||e===V.GREATER_THAN_SIGN}function Ra(e){return e===V.NULL?U.nullCharacterReference:e>1114111?U.characterReferenceOutsideUnicodeRange:ha(e)?U.surrogateCharacterReference:ya(e)?U.noncharacterCharacterReference:va(e)||e===V.CARRIAGE_RETURN?U.controlCharacterReference:null}var za=class{constructor(e,t){this.options=e,this.handler=t,this.paused=!1,this.inLoop=!1,this.inForeignNode=!1,this.lastStartTagName=``,this.active=!1,this.state=X.DATA,this.returnState=X.DATA,this.entityStartPos=0,this.consumedAfterSnapshot=-1,this.currentCharacterToken=null,this.currentToken=null,this.currentAttr={name:``,value:``},this.preprocessor=new xa(t),this.currentLocation=this.getCurrentLocation(-1),this.entityDecoder=new xt(yt,(e,t)=>{this.preprocessor.pos=this.entityStartPos+t-1,this._flushCodePointConsumedAsCharacterReference(e)},t.onParseError?{missingSemicolonAfterCharacterReference:()=>{this._err(U.missingSemicolonAfterCharacterReference,1)},absenceOfDigitsInNumericCharacterReference:e=>{this._err(U.absenceOfDigitsInNumericCharacterReference,this.entityStartPos-this.preprocessor.pos+e)},validateNumericCharacterReference:e=>{let t=Ra(e);t&&this._err(t,1)}}:void 0)}_err(e,t=0){var n,r;(r=(n=this.handler).onParseError)==null||r.call(n,this.preprocessor.getError(e,t))}getCurrentLocation(e){return this.options.sourceCodeLocationInfo?{startLine:this.preprocessor.line,startCol:this.preprocessor.col-e,startOffset:this.preprocessor.offset-e,endLine:-1,endCol:-1,endOffset:-1}:null}_runParsingLoop(){if(!this.inLoop){for(this.inLoop=!0;this.active&&!this.paused;){this.consumedAfterSnapshot=0;let e=this._consume();this._ensureHibernation()||this._callState(e)}this.inLoop=!1}}pause(){this.paused=!0}resume(e){if(!this.paused)throw Error(`Parser was already resumed`);this.paused=!1,!this.inLoop&&(this._runParsingLoop(),this.paused||e?.())}write(e,t,n){this.active=!0,this.preprocessor.write(e,t),this._runParsingLoop(),this.paused||n?.()}insertHtmlAtCurrentPos(e){this.active=!0,this.preprocessor.insertHtmlAtCurrentPos(e),this._runParsingLoop()}_ensureHibernation(){return this.preprocessor.endOfChunkHit?(this.preprocessor.retreat(this.consumedAfterSnapshot),this.consumedAfterSnapshot=0,this.active=!1,!0):!1}_consume(){return this.consumedAfterSnapshot++,this.preprocessor.advance()}_advanceBy(e){this.consumedAfterSnapshot+=e;for(let t=0;t<e;t++)this.preprocessor.advance()}_consumeSequenceIfMatch(e,t){return this.preprocessor.startsWith(e,t)?(this._advanceBy(e.length-1),!0):!1}_createStartTagToken(){this.currentToken={type:W.START_TAG,tagName:``,tagID:J.UNKNOWN,selfClosing:!1,ackSelfClosing:!1,attrs:[],location:this.getCurrentLocation(1)}}_createEndTagToken(){this.currentToken={type:W.END_TAG,tagName:``,tagID:J.UNKNOWN,selfClosing:!1,ackSelfClosing:!1,attrs:[],location:this.getCurrentLocation(2)}}_createCommentToken(e){this.currentToken={type:W.COMMENT,data:``,location:this.getCurrentLocation(e)}}_createDoctypeToken(e){this.currentToken={type:W.DOCTYPE,name:e,forceQuirks:!1,publicId:null,systemId:null,location:this.currentLocation}}_createCharacterToken(e,t){this.currentCharacterToken={type:e,chars:t,location:this.currentLocation}}_createAttr(e){this.currentAttr={name:e,value:``},this.currentLocation=this.getCurrentLocation(0)}_leaveAttrName(){var e;let t=this.currentToken;if(Sa(t,this.currentAttr.name)===null){if(t.attrs.push(this.currentAttr),t.location&&this.currentLocation){let n=(e=t.location).attrs??(e.attrs=Object.create(null));n[this.currentAttr.name]=this.currentLocation,this._leaveAttrValue()}}else this._err(U.duplicateAttribute)}_leaveAttrValue(){this.currentLocation&&(this.currentLocation.endLine=this.preprocessor.line,this.currentLocation.endCol=this.preprocessor.col,this.currentLocation.endOffset=this.preprocessor.offset)}prepareToken(e){this._emitCurrentCharacterToken(e.location),this.currentToken=null,e.location&&(e.location.endLine=this.preprocessor.line,e.location.endCol=this.preprocessor.col+1,e.location.endOffset=this.preprocessor.offset+1),this.currentLocation=this.getCurrentLocation(-1)}emitCurrentTagToken(){let e=this.currentToken;this.prepareToken(e),e.tagID=Ta(e.tagName),e.type===W.START_TAG?(this.lastStartTagName=e.tagName,this.handler.onStartTag(e)):(e.attrs.length>0&&this._err(U.endTagWithAttributes),e.selfClosing&&this._err(U.endTagWithTrailingSolidus),this.handler.onEndTag(e)),this.preprocessor.dropParsedChunk()}emitCurrentComment(e){this.prepareToken(e),this.handler.onComment(e),this.preprocessor.dropParsedChunk()}emitCurrentDoctype(e){this.prepareToken(e),this.handler.onDoctype(e),this.preprocessor.dropParsedChunk()}_emitCurrentCharacterToken(e){if(this.currentCharacterToken){switch(e&&this.currentCharacterToken.location&&(this.currentCharacterToken.location.endLine=e.startLine,this.currentCharacterToken.location.endCol=e.startCol,this.currentCharacterToken.location.endOffset=e.startOffset),this.currentCharacterToken.type){case W.CHARACTER:this.handler.onCharacter(this.currentCharacterToken);break;case W.NULL_CHARACTER:this.handler.onNullCharacter(this.currentCharacterToken);break;case W.WHITESPACE_CHARACTER:this.handler.onWhitespaceCharacter(this.currentCharacterToken);break}this.currentCharacterToken=null}}_emitEOFToken(){let e=this.getCurrentLocation(0);e&&(e.endLine=e.startLine,e.endCol=e.startCol,e.endOffset=e.startOffset),this._emitCurrentCharacterToken(e),this.handler.onEof({type:W.EOF,location:e}),this.active=!1}_appendCharToCurrentCharacterToken(e,t){if(this.currentCharacterToken)if(this.currentCharacterToken.type===e){this.currentCharacterToken.chars+=t;return}else this.currentLocation=this.getCurrentLocation(0),this._emitCurrentCharacterToken(this.currentLocation),this.preprocessor.dropParsedChunk();this._createCharacterToken(e,t)}_emitCodePoint(e){let t=Ia(e)?W.WHITESPACE_CHARACTER:e===V.NULL?W.NULL_CHARACTER:W.CHARACTER;this._appendCharToCurrentCharacterToken(t,e<65536?String.fromCharCode(e):String.fromCodePoint(e))}_emitChars(e){this._appendCharToCurrentCharacterToken(W.CHARACTER,e)}_startCharacterReference(){this.returnState=this.state,this.state=X.CHARACTER_REFERENCE,this.entityStartPos=this.preprocessor.pos,this.entityDecoder.startEntity(this._isCharacterReferenceInAttribute()?bt.Attribute:bt.Legacy)}_isCharacterReferenceInAttribute(){return this.returnState===X.ATTRIBUTE_VALUE_DOUBLE_QUOTED||this.returnState===X.ATTRIBUTE_VALUE_SINGLE_QUOTED||this.returnState===X.ATTRIBUTE_VALUE_UNQUOTED}_flushCodePointConsumedAsCharacterReference(e){this._isCharacterReferenceInAttribute()?this.currentAttr.value+=String.fromCodePoint(e):this._emitCodePoint(e)}_callState(e){switch(this.state){case X.DATA:this._stateData(e);break;case X.RCDATA:this._stateRcdata(e);break;case X.RAWTEXT:this._stateRawtext(e);break;case X.SCRIPT_DATA:this._stateScriptData(e);break;case X.PLAINTEXT:this._statePlaintext(e);break;case X.TAG_OPEN:this._stateTagOpen(e);break;case X.END_TAG_OPEN:this._stateEndTagOpen(e);break;case X.TAG_NAME:this._stateTagName(e);break;case X.RCDATA_LESS_THAN_SIGN:this._stateRcdataLessThanSign(e);break;case X.RCDATA_END_TAG_OPEN:this._stateRcdataEndTagOpen(e);break;case X.RCDATA_END_TAG_NAME:this._stateRcdataEndTagName(e);break;case X.RAWTEXT_LESS_THAN_SIGN:this._stateRawtextLessThanSign(e);break;case X.RAWTEXT_END_TAG_OPEN:this._stateRawtextEndTagOpen(e);break;case X.RAWTEXT_END_TAG_NAME:this._stateRawtextEndTagName(e);break;case X.SCRIPT_DATA_LESS_THAN_SIGN:this._stateScriptDataLessThanSign(e);break;case X.SCRIPT_DATA_END_TAG_OPEN:this._stateScriptDataEndTagOpen(e);break;case X.SCRIPT_DATA_END_TAG_NAME:this._stateScriptDataEndTagName(e);break;case X.SCRIPT_DATA_ESCAPE_START:this._stateScriptDataEscapeStart(e);break;case X.SCRIPT_DATA_ESCAPE_START_DASH:this._stateScriptDataEscapeStartDash(e);break;case X.SCRIPT_DATA_ESCAPED:this._stateScriptDataEscaped(e);break;case X.SCRIPT_DATA_ESCAPED_DASH:this._stateScriptDataEscapedDash(e);break;case X.SCRIPT_DATA_ESCAPED_DASH_DASH:this._stateScriptDataEscapedDashDash(e);break;case X.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN:this._stateScriptDataEscapedLessThanSign(e);break;case X.SCRIPT_DATA_ESCAPED_END_TAG_OPEN:this._stateScriptDataEscapedEndTagOpen(e);break;case X.SCRIPT_DATA_ESCAPED_END_TAG_NAME:this._stateScriptDataEscapedEndTagName(e);break;case X.SCRIPT_DATA_DOUBLE_ESCAPE_START:this._stateScriptDataDoubleEscapeStart(e);break;case X.SCRIPT_DATA_DOUBLE_ESCAPED:this._stateScriptDataDoubleEscaped(e);break;case X.SCRIPT_DATA_DOUBLE_ESCAPED_DASH:this._stateScriptDataDoubleEscapedDash(e);break;case X.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH:this._stateScriptDataDoubleEscapedDashDash(e);break;case X.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN:this._stateScriptDataDoubleEscapedLessThanSign(e);break;case X.SCRIPT_DATA_DOUBLE_ESCAPE_END:this._stateScriptDataDoubleEscapeEnd(e);break;case X.BEFORE_ATTRIBUTE_NAME:this._stateBeforeAttributeName(e);break;case X.ATTRIBUTE_NAME:this._stateAttributeName(e);break;case X.AFTER_ATTRIBUTE_NAME:this._stateAfterAttributeName(e);break;case X.BEFORE_ATTRIBUTE_VALUE:this._stateBeforeAttributeValue(e);break;case X.ATTRIBUTE_VALUE_DOUBLE_QUOTED:this._stateAttributeValueDoubleQuoted(e);break;case X.ATTRIBUTE_VALUE_SINGLE_QUOTED:this._stateAttributeValueSingleQuoted(e);break;case X.ATTRIBUTE_VALUE_UNQUOTED:this._stateAttributeValueUnquoted(e);break;case X.AFTER_ATTRIBUTE_VALUE_QUOTED:this._stateAfterAttributeValueQuoted(e);break;case X.SELF_CLOSING_START_TAG:this._stateSelfClosingStartTag(e);break;case X.BOGUS_COMMENT:this._stateBogusComment(e);break;case X.MARKUP_DECLARATION_OPEN:this._stateMarkupDeclarationOpen(e);break;case X.COMMENT_START:this._stateCommentStart(e);break;case X.COMMENT_START_DASH:this._stateCommentStartDash(e);break;case X.COMMENT:this._stateComment(e);break;case X.COMMENT_LESS_THAN_SIGN:this._stateCommentLessThanSign(e);break;case X.COMMENT_LESS_THAN_SIGN_BANG:this._stateCommentLessThanSignBang(e);break;case X.COMMENT_LESS_THAN_SIGN_BANG_DASH:this._stateCommentLessThanSignBangDash(e);break;case X.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH:this._stateCommentLessThanSignBangDashDash(e);break;case X.COMMENT_END_DASH:this._stateCommentEndDash(e);break;case X.COMMENT_END:this._stateCommentEnd(e);break;case X.COMMENT_END_BANG:this._stateCommentEndBang(e);break;case X.DOCTYPE:this._stateDoctype(e);break;case X.BEFORE_DOCTYPE_NAME:this._stateBeforeDoctypeName(e);break;case X.DOCTYPE_NAME:this._stateDoctypeName(e);break;case X.AFTER_DOCTYPE_NAME:this._stateAfterDoctypeName(e);break;case X.AFTER_DOCTYPE_PUBLIC_KEYWORD:this._stateAfterDoctypePublicKeyword(e);break;case X.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER:this._stateBeforeDoctypePublicIdentifier(e);break;case X.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED:this._stateDoctypePublicIdentifierDoubleQuoted(e);break;case X.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED:this._stateDoctypePublicIdentifierSingleQuoted(e);break;case X.AFTER_DOCTYPE_PUBLIC_IDENTIFIER:this._stateAfterDoctypePublicIdentifier(e);break;case X.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS:this._stateBetweenDoctypePublicAndSystemIdentifiers(e);break;case X.AFTER_DOCTYPE_SYSTEM_KEYWORD:this._stateAfterDoctypeSystemKeyword(e);break;case X.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER:this._stateBeforeDoctypeSystemIdentifier(e);break;case X.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED:this._stateDoctypeSystemIdentifierDoubleQuoted(e);break;case X.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED:this._stateDoctypeSystemIdentifierSingleQuoted(e);break;case X.AFTER_DOCTYPE_SYSTEM_IDENTIFIER:this._stateAfterDoctypeSystemIdentifier(e);break;case X.BOGUS_DOCTYPE:this._stateBogusDoctype(e);break;case X.CDATA_SECTION:this._stateCdataSection(e);break;case X.CDATA_SECTION_BRACKET:this._stateCdataSectionBracket(e);break;case X.CDATA_SECTION_END:this._stateCdataSectionEnd(e);break;case X.CHARACTER_REFERENCE:this._stateCharacterReference();break;case X.AMBIGUOUS_AMPERSAND:this._stateAmbiguousAmpersand(e);break;default:throw Error(`Unknown state`)}}_stateData(e){switch(e){case V.LESS_THAN_SIGN:this.state=X.TAG_OPEN;break;case V.AMPERSAND:this._startCharacterReference();break;case V.NULL:this._err(U.unexpectedNullCharacter),this._emitCodePoint(e);break;case V.EOF:this._emitEOFToken();break;default:this._emitCodePoint(e)}}_stateRcdata(e){switch(e){case V.AMPERSAND:this._startCharacterReference();break;case V.LESS_THAN_SIGN:this.state=X.RCDATA_LESS_THAN_SIGN;break;case V.NULL:this._err(U.unexpectedNullCharacter),this._emitChars(`�`);break;case V.EOF:this._emitEOFToken();break;default:this._emitCodePoint(e)}}_stateRawtext(e){switch(e){case V.LESS_THAN_SIGN:this.state=X.RAWTEXT_LESS_THAN_SIGN;break;case V.NULL:this._err(U.unexpectedNullCharacter),this._emitChars(`�`);break;case V.EOF:this._emitEOFToken();break;default:this._emitCodePoint(e)}}_stateScriptData(e){switch(e){case V.LESS_THAN_SIGN:this.state=X.SCRIPT_DATA_LESS_THAN_SIGN;break;case V.NULL:this._err(U.unexpectedNullCharacter),this._emitChars(`�`);break;case V.EOF:this._emitEOFToken();break;default:this._emitCodePoint(e)}}_statePlaintext(e){switch(e){case V.NULL:this._err(U.unexpectedNullCharacter),this._emitChars(`�`);break;case V.EOF:this._emitEOFToken();break;default:this._emitCodePoint(e)}}_stateTagOpen(e){if(Na(e))this._createStartTagToken(),this.state=X.TAG_NAME,this._stateTagName(e);else switch(e){case V.EXCLAMATION_MARK:this.state=X.MARKUP_DECLARATION_OPEN;break;case V.SOLIDUS:this.state=X.END_TAG_OPEN;break;case V.QUESTION_MARK:this._err(U.unexpectedQuestionMarkInsteadOfTagName),this._createCommentToken(1),this.state=X.BOGUS_COMMENT,this._stateBogusComment(e);break;case V.EOF:this._err(U.eofBeforeTagName),this._emitChars(`<`),this._emitEOFToken();break;default:this._err(U.invalidFirstCharacterOfTagName),this._emitChars(`<`),this.state=X.DATA,this._stateData(e)}}_stateEndTagOpen(e){if(Na(e))this._createEndTagToken(),this.state=X.TAG_NAME,this._stateTagName(e);else switch(e){case V.GREATER_THAN_SIGN:this._err(U.missingEndTagName),this.state=X.DATA;break;case V.EOF:this._err(U.eofBeforeTagName),this._emitChars(`</`),this._emitEOFToken();break;default:this._err(U.invalidFirstCharacterOfTagName),this._createCommentToken(2),this.state=X.BOGUS_COMMENT,this._stateBogusComment(e)}}_stateTagName(e){let t=this.currentToken;switch(e){case V.SPACE:case V.LINE_FEED:case V.TABULATION:case V.FORM_FEED:this.state=X.BEFORE_ATTRIBUTE_NAME;break;case V.SOLIDUS:this.state=X.SELF_CLOSING_START_TAG;break;case V.GREATER_THAN_SIGN:this.state=X.DATA,this.emitCurrentTagToken();break;case V.NULL:this._err(U.unexpectedNullCharacter),t.tagName+=`�`;break;case V.EOF:this._err(U.eofInTag),this._emitEOFToken();break;default:t.tagName+=String.fromCodePoint(ja(e)?Fa(e):e)}}_stateRcdataLessThanSign(e){e===V.SOLIDUS?this.state=X.RCDATA_END_TAG_OPEN:(this._emitChars(`<`),this.state=X.RCDATA,this._stateRcdata(e))}_stateRcdataEndTagOpen(e){Na(e)?(this.state=X.RCDATA_END_TAG_NAME,this._stateRcdataEndTagName(e)):(this._emitChars(`</`),this.state=X.RCDATA,this._stateRcdata(e))}handleSpecialEndTag(e){if(!this.preprocessor.startsWith(this.lastStartTagName,!1))return!this._ensureHibernation();this._createEndTagToken();let t=this.currentToken;switch(t.tagName=this.lastStartTagName,this.preprocessor.peek(this.lastStartTagName.length)){case V.SPACE:case V.LINE_FEED:case V.TABULATION:case V.FORM_FEED:return this._advanceBy(this.lastStartTagName.length),this.state=X.BEFORE_ATTRIBUTE_NAME,!1;case V.SOLIDUS:return this._advanceBy(this.lastStartTagName.length),this.state=X.SELF_CLOSING_START_TAG,!1;case V.GREATER_THAN_SIGN:return this._advanceBy(this.lastStartTagName.length),this.emitCurrentTagToken(),this.state=X.DATA,!1;default:return!this._ensureHibernation()}}_stateRcdataEndTagName(e){this.handleSpecialEndTag(e)&&(this._emitChars(`</`),this.state=X.RCDATA,this._stateRcdata(e))}_stateRawtextLessThanSign(e){e===V.SOLIDUS?this.state=X.RAWTEXT_END_TAG_OPEN:(this._emitChars(`<`),this.state=X.RAWTEXT,this._stateRawtext(e))}_stateRawtextEndTagOpen(e){Na(e)?(this.state=X.RAWTEXT_END_TAG_NAME,this._stateRawtextEndTagName(e)):(this._emitChars(`</`),this.state=X.RAWTEXT,this._stateRawtext(e))}_stateRawtextEndTagName(e){this.handleSpecialEndTag(e)&&(this._emitChars(`</`),this.state=X.RAWTEXT,this._stateRawtext(e))}_stateScriptDataLessThanSign(e){switch(e){case V.SOLIDUS:this.state=X.SCRIPT_DATA_END_TAG_OPEN;break;case V.EXCLAMATION_MARK:this.state=X.SCRIPT_DATA_ESCAPE_START,this._emitChars(`<!`);break;default:this._emitChars(`<`),this.state=X.SCRIPT_DATA,this._stateScriptData(e)}}_stateScriptDataEndTagOpen(e){Na(e)?(this.state=X.SCRIPT_DATA_END_TAG_NAME,this._stateScriptDataEndTagName(e)):(this._emitChars(`</`),this.state=X.SCRIPT_DATA,this._stateScriptData(e))}_stateScriptDataEndTagName(e){this.handleSpecialEndTag(e)&&(this._emitChars(`</`),this.state=X.SCRIPT_DATA,this._stateScriptData(e))}_stateScriptDataEscapeStart(e){e===V.HYPHEN_MINUS?(this.state=X.SCRIPT_DATA_ESCAPE_START_DASH,this._emitChars(`-`)):(this.state=X.SCRIPT_DATA,this._stateScriptData(e))}_stateScriptDataEscapeStartDash(e){e===V.HYPHEN_MINUS?(this.state=X.SCRIPT_DATA_ESCAPED_DASH_DASH,this._emitChars(`-`)):(this.state=X.SCRIPT_DATA,this._stateScriptData(e))}_stateScriptDataEscaped(e){switch(e){case V.HYPHEN_MINUS:this.state=X.SCRIPT_DATA_ESCAPED_DASH,this._emitChars(`-`);break;case V.LESS_THAN_SIGN:this.state=X.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break;case V.NULL:this._err(U.unexpectedNullCharacter),this._emitChars(`�`);break;case V.EOF:this._err(U.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break;default:this._emitCodePoint(e)}}_stateScriptDataEscapedDash(e){switch(e){case V.HYPHEN_MINUS:this.state=X.SCRIPT_DATA_ESCAPED_DASH_DASH,this._emitChars(`-`);break;case V.LESS_THAN_SIGN:this.state=X.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break;case V.NULL:this._err(U.unexpectedNullCharacter),this.state=X.SCRIPT_DATA_ESCAPED,this._emitChars(`�`);break;case V.EOF:this._err(U.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break;default:this.state=X.SCRIPT_DATA_ESCAPED,this._emitCodePoint(e)}}_stateScriptDataEscapedDashDash(e){switch(e){case V.HYPHEN_MINUS:this._emitChars(`-`);break;case V.LESS_THAN_SIGN:this.state=X.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break;case V.GREATER_THAN_SIGN:this.state=X.SCRIPT_DATA,this._emitChars(`>`);break;case V.NULL:this._err(U.unexpectedNullCharacter),this.state=X.SCRIPT_DATA_ESCAPED,this._emitChars(`�`);break;case V.EOF:this._err(U.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break;default:this.state=X.SCRIPT_DATA_ESCAPED,this._emitCodePoint(e)}}_stateScriptDataEscapedLessThanSign(e){e===V.SOLIDUS?this.state=X.SCRIPT_DATA_ESCAPED_END_TAG_OPEN:Na(e)?(this._emitChars(`<`),this.state=X.SCRIPT_DATA_DOUBLE_ESCAPE_START,this._stateScriptDataDoubleEscapeStart(e)):(this._emitChars(`<`),this.state=X.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(e))}_stateScriptDataEscapedEndTagOpen(e){Na(e)?(this.state=X.SCRIPT_DATA_ESCAPED_END_TAG_NAME,this._stateScriptDataEscapedEndTagName(e)):(this._emitChars(`</`),this.state=X.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(e))}_stateScriptDataEscapedEndTagName(e){this.handleSpecialEndTag(e)&&(this._emitChars(`</`),this.state=X.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(e))}_stateScriptDataDoubleEscapeStart(e){if(this.preprocessor.startsWith(H.SCRIPT,!1)&&La(this.preprocessor.peek(H.SCRIPT.length))){this._emitCodePoint(e);for(let e=0;e<H.SCRIPT.length;e++)this._emitCodePoint(this._consume());this.state=X.SCRIPT_DATA_DOUBLE_ESCAPED}else this._ensureHibernation()||(this.state=X.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(e))}_stateScriptDataDoubleEscaped(e){switch(e){case V.HYPHEN_MINUS:this.state=X.SCRIPT_DATA_DOUBLE_ESCAPED_DASH,this._emitChars(`-`);break;case V.LESS_THAN_SIGN:this.state=X.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars(`<`);break;case V.NULL:this._err(U.unexpectedNullCharacter),this._emitChars(`�`);break;case V.EOF:this._err(U.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break;default:this._emitCodePoint(e)}}_stateScriptDataDoubleEscapedDash(e){switch(e){case V.HYPHEN_MINUS:this.state=X.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH,this._emitChars(`-`);break;case V.LESS_THAN_SIGN:this.state=X.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars(`<`);break;case V.NULL:this._err(U.unexpectedNullCharacter),this.state=X.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitChars(`�`);break;case V.EOF:this._err(U.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break;default:this.state=X.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitCodePoint(e)}}_stateScriptDataDoubleEscapedDashDash(e){switch(e){case V.HYPHEN_MINUS:this._emitChars(`-`);break;case V.LESS_THAN_SIGN:this.state=X.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars(`<`);break;case V.GREATER_THAN_SIGN:this.state=X.SCRIPT_DATA,this._emitChars(`>`);break;case V.NULL:this._err(U.unexpectedNullCharacter),this.state=X.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitChars(`�`);break;case V.EOF:this._err(U.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break;default:this.state=X.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitCodePoint(e)}}_stateScriptDataDoubleEscapedLessThanSign(e){e===V.SOLIDUS?(this.state=X.SCRIPT_DATA_DOUBLE_ESCAPE_END,this._emitChars(`/`)):(this.state=X.SCRIPT_DATA_DOUBLE_ESCAPED,this._stateScriptDataDoubleEscaped(e))}_stateScriptDataDoubleEscapeEnd(e){if(this.preprocessor.startsWith(H.SCRIPT,!1)&&La(this.preprocessor.peek(H.SCRIPT.length))){this._emitCodePoint(e);for(let e=0;e<H.SCRIPT.length;e++)this._emitCodePoint(this._consume());this.state=X.SCRIPT_DATA_ESCAPED}else this._ensureHibernation()||(this.state=X.SCRIPT_DATA_DOUBLE_ESCAPED,this._stateScriptDataDoubleEscaped(e))}_stateBeforeAttributeName(e){switch(e){case V.SPACE:case V.LINE_FEED:case V.TABULATION:case V.FORM_FEED:break;case V.SOLIDUS:case V.GREATER_THAN_SIGN:case V.EOF:this.state=X.AFTER_ATTRIBUTE_NAME,this._stateAfterAttributeName(e);break;case V.EQUALS_SIGN:this._err(U.unexpectedEqualsSignBeforeAttributeName),this._createAttr(`=`),this.state=X.ATTRIBUTE_NAME;break;default:this._createAttr(``),this.state=X.ATTRIBUTE_NAME,this._stateAttributeName(e)}}_stateAttributeName(e){switch(e){case V.SPACE:case V.LINE_FEED:case V.TABULATION:case V.FORM_FEED:case V.SOLIDUS:case V.GREATER_THAN_SIGN:case V.EOF:this._leaveAttrName(),this.state=X.AFTER_ATTRIBUTE_NAME,this._stateAfterAttributeName(e);break;case V.EQUALS_SIGN:this._leaveAttrName(),this.state=X.BEFORE_ATTRIBUTE_VALUE;break;case V.QUOTATION_MARK:case V.APOSTROPHE:case V.LESS_THAN_SIGN:this._err(U.unexpectedCharacterInAttributeName),this.currentAttr.name+=String.fromCodePoint(e);break;case V.NULL:this._err(U.unexpectedNullCharacter),this.currentAttr.name+=`�`;break;default:this.currentAttr.name+=String.fromCodePoint(ja(e)?Fa(e):e)}}_stateAfterAttributeName(e){switch(e){case V.SPACE:case V.LINE_FEED:case V.TABULATION:case V.FORM_FEED:break;case V.SOLIDUS:this.state=X.SELF_CLOSING_START_TAG;break;case V.EQUALS_SIGN:this.state=X.BEFORE_ATTRIBUTE_VALUE;break;case V.GREATER_THAN_SIGN:this.state=X.DATA,this.emitCurrentTagToken();break;case V.EOF:this._err(U.eofInTag),this._emitEOFToken();break;default:this._createAttr(``),this.state=X.ATTRIBUTE_NAME,this._stateAttributeName(e)}}_stateBeforeAttributeValue(e){switch(e){case V.SPACE:case V.LINE_FEED:case V.TABULATION:case V.FORM_FEED:break;case V.QUOTATION_MARK:this.state=X.ATTRIBUTE_VALUE_DOUBLE_QUOTED;break;case V.APOSTROPHE:this.state=X.ATTRIBUTE_VALUE_SINGLE_QUOTED;break;case V.GREATER_THAN_SIGN:this._err(U.missingAttributeValue),this.state=X.DATA,this.emitCurrentTagToken();break;default:this.state=X.ATTRIBUTE_VALUE_UNQUOTED,this._stateAttributeValueUnquoted(e)}}_stateAttributeValueDoubleQuoted(e){switch(e){case V.QUOTATION_MARK:this.state=X.AFTER_ATTRIBUTE_VALUE_QUOTED;break;case V.AMPERSAND:this._startCharacterReference();break;case V.NULL:this._err(U.unexpectedNullCharacter),this.currentAttr.value+=`�`;break;case V.EOF:this._err(U.eofInTag),this._emitEOFToken();break;default:this.currentAttr.value+=String.fromCodePoint(e)}}_stateAttributeValueSingleQuoted(e){switch(e){case V.APOSTROPHE:this.state=X.AFTER_ATTRIBUTE_VALUE_QUOTED;break;case V.AMPERSAND:this._startCharacterReference();break;case V.NULL:this._err(U.unexpectedNullCharacter),this.currentAttr.value+=`�`;break;case V.EOF:this._err(U.eofInTag),this._emitEOFToken();break;default:this.currentAttr.value+=String.fromCodePoint(e)}}_stateAttributeValueUnquoted(e){switch(e){case V.SPACE:case V.LINE_FEED:case V.TABULATION:case V.FORM_FEED:this._leaveAttrValue(),this.state=X.BEFORE_ATTRIBUTE_NAME;break;case V.AMPERSAND:this._startCharacterReference();break;case V.GREATER_THAN_SIGN:this._leaveAttrValue(),this.state=X.DATA,this.emitCurrentTagToken();break;case V.NULL:this._err(U.unexpectedNullCharacter),this.currentAttr.value+=`�`;break;case V.QUOTATION_MARK:case V.APOSTROPHE:case V.LESS_THAN_SIGN:case V.EQUALS_SIGN:case V.GRAVE_ACCENT:this._err(U.unexpectedCharacterInUnquotedAttributeValue),this.currentAttr.value+=String.fromCodePoint(e);break;case V.EOF:this._err(U.eofInTag),this._emitEOFToken();break;default:this.currentAttr.value+=String.fromCodePoint(e)}}_stateAfterAttributeValueQuoted(e){switch(e){case V.SPACE:case V.LINE_FEED:case V.TABULATION:case V.FORM_FEED:this._leaveAttrValue(),this.state=X.BEFORE_ATTRIBUTE_NAME;break;case V.SOLIDUS:this._leaveAttrValue(),this.state=X.SELF_CLOSING_START_TAG;break;case V.GREATER_THAN_SIGN:this._leaveAttrValue(),this.state=X.DATA,this.emitCurrentTagToken();break;case V.EOF:this._err(U.eofInTag),this._emitEOFToken();break;default:this._err(U.missingWhitespaceBetweenAttributes),this.state=X.BEFORE_ATTRIBUTE_NAME,this._stateBeforeAttributeName(e)}}_stateSelfClosingStartTag(e){switch(e){case V.GREATER_THAN_SIGN:{let e=this.currentToken;e.selfClosing=!0,this.state=X.DATA,this.emitCurrentTagToken();break}case V.EOF:this._err(U.eofInTag),this._emitEOFToken();break;default:this._err(U.unexpectedSolidusInTag),this.state=X.BEFORE_ATTRIBUTE_NAME,this._stateBeforeAttributeName(e)}}_stateBogusComment(e){let t=this.currentToken;switch(e){case V.GREATER_THAN_SIGN:this.state=X.DATA,this.emitCurrentComment(t);break;case V.EOF:this.emitCurrentComment(t),this._emitEOFToken();break;case V.NULL:this._err(U.unexpectedNullCharacter),t.data+=`�`;break;default:t.data+=String.fromCodePoint(e)}}_stateMarkupDeclarationOpen(e){this._consumeSequenceIfMatch(H.DASH_DASH,!0)?(this._createCommentToken(H.DASH_DASH.length+1),this.state=X.COMMENT_START):this._consumeSequenceIfMatch(H.DOCTYPE,!1)?(this.currentLocation=this.getCurrentLocation(H.DOCTYPE.length+1),this.state=X.DOCTYPE):this._consumeSequenceIfMatch(H.CDATA_START,!0)?this.inForeignNode?this.state=X.CDATA_SECTION:(this._err(U.cdataInHtmlContent),this._createCommentToken(H.CDATA_START.length+1),this.currentToken.data=`[CDATA[`,this.state=X.BOGUS_COMMENT):this._ensureHibernation()||(this._err(U.incorrectlyOpenedComment),this._createCommentToken(2),this.state=X.BOGUS_COMMENT,this._stateBogusComment(e))}_stateCommentStart(e){switch(e){case V.HYPHEN_MINUS:this.state=X.COMMENT_START_DASH;break;case V.GREATER_THAN_SIGN:{this._err(U.abruptClosingOfEmptyComment),this.state=X.DATA;let e=this.currentToken;this.emitCurrentComment(e);break}default:this.state=X.COMMENT,this._stateComment(e)}}_stateCommentStartDash(e){let t=this.currentToken;switch(e){case V.HYPHEN_MINUS:this.state=X.COMMENT_END;break;case V.GREATER_THAN_SIGN:this._err(U.abruptClosingOfEmptyComment),this.state=X.DATA,this.emitCurrentComment(t);break;case V.EOF:this._err(U.eofInComment),this.emitCurrentComment(t),this._emitEOFToken();break;default:t.data+=`-`,this.state=X.COMMENT,this._stateComment(e)}}_stateComment(e){let t=this.currentToken;switch(e){case V.HYPHEN_MINUS:this.state=X.COMMENT_END_DASH;break;case V.LESS_THAN_SIGN:t.data+=`<`,this.state=X.COMMENT_LESS_THAN_SIGN;break;case V.NULL:this._err(U.unexpectedNullCharacter),t.data+=`�`;break;case V.EOF:this._err(U.eofInComment),this.emitCurrentComment(t),this._emitEOFToken();break;default:t.data+=String.fromCodePoint(e)}}_stateCommentLessThanSign(e){let t=this.currentToken;switch(e){case V.EXCLAMATION_MARK:t.data+=`!`,this.state=X.COMMENT_LESS_THAN_SIGN_BANG;break;case V.LESS_THAN_SIGN:t.data+=`<`;break;default:this.state=X.COMMENT,this._stateComment(e)}}_stateCommentLessThanSignBang(e){e===V.HYPHEN_MINUS?this.state=X.COMMENT_LESS_THAN_SIGN_BANG_DASH:(this.state=X.COMMENT,this._stateComment(e))}_stateCommentLessThanSignBangDash(e){e===V.HYPHEN_MINUS?this.state=X.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH:(this.state=X.COMMENT_END_DASH,this._stateCommentEndDash(e))}_stateCommentLessThanSignBangDashDash(e){e!==V.GREATER_THAN_SIGN&&e!==V.EOF&&this._err(U.nestedComment),this.state=X.COMMENT_END,this._stateCommentEnd(e)}_stateCommentEndDash(e){let t=this.currentToken;switch(e){case V.HYPHEN_MINUS:this.state=X.COMMENT_END;break;case V.EOF:this._err(U.eofInComment),this.emitCurrentComment(t),this._emitEOFToken();break;default:t.data+=`-`,this.state=X.COMMENT,this._stateComment(e)}}_stateCommentEnd(e){let t=this.currentToken;switch(e){case V.GREATER_THAN_SIGN:this.state=X.DATA,this.emitCurrentComment(t);break;case V.EXCLAMATION_MARK:this.state=X.COMMENT_END_BANG;break;case V.HYPHEN_MINUS:t.data+=`-`;break;case V.EOF:this._err(U.eofInComment),this.emitCurrentComment(t),this._emitEOFToken();break;default:t.data+=`--`,this.state=X.COMMENT,this._stateComment(e)}}_stateCommentEndBang(e){let t=this.currentToken;switch(e){case V.HYPHEN_MINUS:t.data+=`--!`,this.state=X.COMMENT_END_DASH;break;case V.GREATER_THAN_SIGN:this._err(U.incorrectlyClosedComment),this.state=X.DATA,this.emitCurrentComment(t);break;case V.EOF:this._err(U.eofInComment),this.emitCurrentComment(t),this._emitEOFToken();break;default:t.data+=`--!`,this.state=X.COMMENT,this._stateComment(e)}}_stateDoctype(e){switch(e){case V.SPACE:case V.LINE_FEED:case V.TABULATION:case V.FORM_FEED:this.state=X.BEFORE_DOCTYPE_NAME;break;case V.GREATER_THAN_SIGN:this.state=X.BEFORE_DOCTYPE_NAME,this._stateBeforeDoctypeName(e);break;case V.EOF:{this._err(U.eofInDoctype),this._createDoctypeToken(null);let e=this.currentToken;e.forceQuirks=!0,this.emitCurrentDoctype(e),this._emitEOFToken();break}default:this._err(U.missingWhitespaceBeforeDoctypeName),this.state=X.BEFORE_DOCTYPE_NAME,this._stateBeforeDoctypeName(e)}}_stateBeforeDoctypeName(e){if(ja(e))this._createDoctypeToken(String.fromCharCode(Fa(e))),this.state=X.DOCTYPE_NAME;else switch(e){case V.SPACE:case V.LINE_FEED:case V.TABULATION:case V.FORM_FEED:break;case V.NULL:this._err(U.unexpectedNullCharacter),this._createDoctypeToken(`�`),this.state=X.DOCTYPE_NAME;break;case V.GREATER_THAN_SIGN:{this._err(U.missingDoctypeName),this._createDoctypeToken(null);let e=this.currentToken;e.forceQuirks=!0,this.emitCurrentDoctype(e),this.state=X.DATA;break}case V.EOF:{this._err(U.eofInDoctype),this._createDoctypeToken(null);let e=this.currentToken;e.forceQuirks=!0,this.emitCurrentDoctype(e),this._emitEOFToken();break}default:this._createDoctypeToken(String.fromCodePoint(e)),this.state=X.DOCTYPE_NAME}}_stateDoctypeName(e){let t=this.currentToken;switch(e){case V.SPACE:case V.LINE_FEED:case V.TABULATION:case V.FORM_FEED:this.state=X.AFTER_DOCTYPE_NAME;break;case V.GREATER_THAN_SIGN:this.state=X.DATA,this.emitCurrentDoctype(t);break;case V.NULL:this._err(U.unexpectedNullCharacter),t.name+=`�`;break;case V.EOF:this._err(U.eofInDoctype),t.forceQuirks=!0,this.emitCurrentDoctype(t),this._emitEOFToken();break;default:t.name+=String.fromCodePoint(ja(e)?Fa(e):e)}}_stateAfterDoctypeName(e){let t=this.currentToken;switch(e){case V.SPACE:case V.LINE_FEED:case V.TABULATION:case V.FORM_FEED:break;case V.GREATER_THAN_SIGN:this.state=X.DATA,this.emitCurrentDoctype(t);break;case V.EOF:this._err(U.eofInDoctype),t.forceQuirks=!0,this.emitCurrentDoctype(t),this._emitEOFToken();break;default:this._consumeSequenceIfMatch(H.PUBLIC,!1)?this.state=X.AFTER_DOCTYPE_PUBLIC_KEYWORD:this._consumeSequenceIfMatch(H.SYSTEM,!1)?this.state=X.AFTER_DOCTYPE_SYSTEM_KEYWORD:this._ensureHibernation()||(this._err(U.invalidCharacterSequenceAfterDoctypeName),t.forceQuirks=!0,this.state=X.BOGUS_DOCTYPE,this._stateBogusDoctype(e))}}_stateAfterDoctypePublicKeyword(e){let t=this.currentToken;switch(e){case V.SPACE:case V.LINE_FEED:case V.TABULATION:case V.FORM_FEED:this.state=X.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER;break;case V.QUOTATION_MARK:this._err(U.missingWhitespaceAfterDoctypePublicKeyword),t.publicId=``,this.state=X.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;break;case V.APOSTROPHE:this._err(U.missingWhitespaceAfterDoctypePublicKeyword),t.publicId=``,this.state=X.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;break;case V.GREATER_THAN_SIGN:this._err(U.missingDoctypePublicIdentifier),t.forceQuirks=!0,this.state=X.DATA,this.emitCurrentDoctype(t);break;case V.EOF:this._err(U.eofInDoctype),t.forceQuirks=!0,this.emitCurrentDoctype(t),this._emitEOFToken();break;default:this._err(U.missingQuoteBeforeDoctypePublicIdentifier),t.forceQuirks=!0,this.state=X.BOGUS_DOCTYPE,this._stateBogusDoctype(e)}}_stateBeforeDoctypePublicIdentifier(e){let t=this.currentToken;switch(e){case V.SPACE:case V.LINE_FEED:case V.TABULATION:case V.FORM_FEED:break;case V.QUOTATION_MARK:t.publicId=``,this.state=X.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;break;case V.APOSTROPHE:t.publicId=``,this.state=X.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;break;case V.GREATER_THAN_SIGN:this._err(U.missingDoctypePublicIdentifier),t.forceQuirks=!0,this.state=X.DATA,this.emitCurrentDoctype(t);break;case V.EOF:this._err(U.eofInDoctype),t.forceQuirks=!0,this.emitCurrentDoctype(t),this._emitEOFToken();break;default:this._err(U.missingQuoteBeforeDoctypePublicIdentifier),t.forceQuirks=!0,this.state=X.BOGUS_DOCTYPE,this._stateBogusDoctype(e)}}_stateDoctypePublicIdentifierDoubleQuoted(e){let t=this.currentToken;switch(e){case V.QUOTATION_MARK:this.state=X.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;break;case V.NULL:this._err(U.unexpectedNullCharacter),t.publicId+=`�`;break;case V.GREATER_THAN_SIGN:this._err(U.abruptDoctypePublicIdentifier),t.forceQuirks=!0,this.emitCurrentDoctype(t),this.state=X.DATA;break;case V.EOF:this._err(U.eofInDoctype),t.forceQuirks=!0,this.emitCurrentDoctype(t),this._emitEOFToken();break;default:t.publicId+=String.fromCodePoint(e)}}_stateDoctypePublicIdentifierSingleQuoted(e){let t=this.currentToken;switch(e){case V.APOSTROPHE:this.state=X.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;break;case V.NULL:this._err(U.unexpectedNullCharacter),t.publicId+=`�`;break;case V.GREATER_THAN_SIGN:this._err(U.abruptDoctypePublicIdentifier),t.forceQuirks=!0,this.emitCurrentDoctype(t),this.state=X.DATA;break;case V.EOF:this._err(U.eofInDoctype),t.forceQuirks=!0,this.emitCurrentDoctype(t),this._emitEOFToken();break;default:t.publicId+=String.fromCodePoint(e)}}_stateAfterDoctypePublicIdentifier(e){let t=this.currentToken;switch(e){case V.SPACE:case V.LINE_FEED:case V.TABULATION:case V.FORM_FEED:this.state=X.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS;break;case V.GREATER_THAN_SIGN:this.state=X.DATA,this.emitCurrentDoctype(t);break;case V.QUOTATION_MARK:this._err(U.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers),t.systemId=``,this.state=X.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break;case V.APOSTROPHE:this._err(U.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers),t.systemId=``,this.state=X.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break;case V.EOF:this._err(U.eofInDoctype),t.forceQuirks=!0,this.emitCurrentDoctype(t),this._emitEOFToken();break;default:this._err(U.missingQuoteBeforeDoctypeSystemIdentifier),t.forceQuirks=!0,this.state=X.BOGUS_DOCTYPE,this._stateBogusDoctype(e)}}_stateBetweenDoctypePublicAndSystemIdentifiers(e){let t=this.currentToken;switch(e){case V.SPACE:case V.LINE_FEED:case V.TABULATION:case V.FORM_FEED:break;case V.GREATER_THAN_SIGN:this.emitCurrentDoctype(t),this.state=X.DATA;break;case V.QUOTATION_MARK:t.systemId=``,this.state=X.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break;case V.APOSTROPHE:t.systemId=``,this.state=X.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break;case V.EOF:this._err(U.eofInDoctype),t.forceQuirks=!0,this.emitCurrentDoctype(t),this._emitEOFToken();break;default:this._err(U.missingQuoteBeforeDoctypeSystemIdentifier),t.forceQuirks=!0,this.state=X.BOGUS_DOCTYPE,this._stateBogusDoctype(e)}}_stateAfterDoctypeSystemKeyword(e){let t=this.currentToken;switch(e){case V.SPACE:case V.LINE_FEED:case V.TABULATION:case V.FORM_FEED:this.state=X.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER;break;case V.QUOTATION_MARK:this._err(U.missingWhitespaceAfterDoctypeSystemKeyword),t.systemId=``,this.state=X.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break;case V.APOSTROPHE:this._err(U.missingWhitespaceAfterDoctypeSystemKeyword),t.systemId=``,this.state=X.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break;case V.GREATER_THAN_SIGN:this._err(U.missingDoctypeSystemIdentifier),t.forceQuirks=!0,this.state=X.DATA,this.emitCurrentDoctype(t);break;case V.EOF:this._err(U.eofInDoctype),t.forceQuirks=!0,this.emitCurrentDoctype(t),this._emitEOFToken();break;default:this._err(U.missingQuoteBeforeDoctypeSystemIdentifier),t.forceQuirks=!0,this.state=X.BOGUS_DOCTYPE,this._stateBogusDoctype(e)}}_stateBeforeDoctypeSystemIdentifier(e){let t=this.currentToken;switch(e){case V.SPACE:case V.LINE_FEED:case V.TABULATION:case V.FORM_FEED:break;case V.QUOTATION_MARK:t.systemId=``,this.state=X.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break;case V.APOSTROPHE:t.systemId=``,this.state=X.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break;case V.GREATER_THAN_SIGN:this._err(U.missingDoctypeSystemIdentifier),t.forceQuirks=!0,this.state=X.DATA,this.emitCurrentDoctype(t);break;case V.EOF:this._err(U.eofInDoctype),t.forceQuirks=!0,this.emitCurrentDoctype(t),this._emitEOFToken();break;default:this._err(U.missingQuoteBeforeDoctypeSystemIdentifier),t.forceQuirks=!0,this.state=X.BOGUS_DOCTYPE,this._stateBogusDoctype(e)}}_stateDoctypeSystemIdentifierDoubleQuoted(e){let t=this.currentToken;switch(e){case V.QUOTATION_MARK:this.state=X.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;break;case V.NULL:this._err(U.unexpectedNullCharacter),t.systemId+=`�`;break;case V.GREATER_THAN_SIGN:this._err(U.abruptDoctypeSystemIdentifier),t.forceQuirks=!0,this.emitCurrentDoctype(t),this.state=X.DATA;break;case V.EOF:this._err(U.eofInDoctype),t.forceQuirks=!0,this.emitCurrentDoctype(t),this._emitEOFToken();break;default:t.systemId+=String.fromCodePoint(e)}}_stateDoctypeSystemIdentifierSingleQuoted(e){let t=this.currentToken;switch(e){case V.APOSTROPHE:this.state=X.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;break;case V.NULL:this._err(U.unexpectedNullCharacter),t.systemId+=`�`;break;case V.GREATER_THAN_SIGN:this._err(U.abruptDoctypeSystemIdentifier),t.forceQuirks=!0,this.emitCurrentDoctype(t),this.state=X.DATA;break;case V.EOF:this._err(U.eofInDoctype),t.forceQuirks=!0,this.emitCurrentDoctype(t),this._emitEOFToken();break;default:t.systemId+=String.fromCodePoint(e)}}_stateAfterDoctypeSystemIdentifier(e){let t=this.currentToken;switch(e){case V.SPACE:case V.LINE_FEED:case V.TABULATION:case V.FORM_FEED:break;case V.GREATER_THAN_SIGN:this.emitCurrentDoctype(t),this.state=X.DATA;break;case V.EOF:this._err(U.eofInDoctype),t.forceQuirks=!0,this.emitCurrentDoctype(t),this._emitEOFToken();break;default:this._err(U.unexpectedCharacterAfterDoctypeSystemIdentifier),this.state=X.BOGUS_DOCTYPE,this._stateBogusDoctype(e)}}_stateBogusDoctype(e){let t=this.currentToken;switch(e){case V.GREATER_THAN_SIGN:this.emitCurrentDoctype(t),this.state=X.DATA;break;case V.NULL:this._err(U.unexpectedNullCharacter);break;case V.EOF:this.emitCurrentDoctype(t),this._emitEOFToken();break;default:}}_stateCdataSection(e){switch(e){case V.RIGHT_SQUARE_BRACKET:this.state=X.CDATA_SECTION_BRACKET;break;case V.EOF:this._err(U.eofInCdata),this._emitEOFToken();break;default:this._emitCodePoint(e)}}_stateCdataSectionBracket(e){e===V.RIGHT_SQUARE_BRACKET?this.state=X.CDATA_SECTION_END:(this._emitChars(`]`),this.state=X.CDATA_SECTION,this._stateCdataSection(e))}_stateCdataSectionEnd(e){switch(e){case V.GREATER_THAN_SIGN:this.state=X.DATA;break;case V.RIGHT_SQUARE_BRACKET:this._emitChars(`]`);break;default:this._emitChars(`]]`),this.state=X.CDATA_SECTION,this._stateCdataSection(e)}}_stateCharacterReference(){let e=this.entityDecoder.write(this.preprocessor.html,this.preprocessor.pos);if(e<0)if(this.preprocessor.lastChunkWritten)e=this.entityDecoder.end();else{this.active=!1,this.preprocessor.pos=this.preprocessor.html.length-1,this.consumedAfterSnapshot=0,this.preprocessor.endOfChunkHit=!0;return}e===0?(this.preprocessor.pos=this.entityStartPos,this._flushCodePointConsumedAsCharacterReference(V.AMPERSAND),this.state=!this._isCharacterReferenceInAttribute()&&Pa(this.preprocessor.peek(1))?X.AMBIGUOUS_AMPERSAND:this.returnState):this.state=this.returnState}_stateAmbiguousAmpersand(e){Pa(e)?this._flushCodePointConsumedAsCharacterReference(e):(e===V.SEMICOLON&&this._err(U.unknownNamedCharacterReference),this.state=this.returnState,this._callState(e))}},Ba=new Set([J.DD,J.DT,J.LI,J.OPTGROUP,J.OPTION,J.P,J.RB,J.RP,J.RT,J.RTC]),Va=new Set([...Ba,J.CAPTION,J.COLGROUP,J.TBODY,J.TD,J.TFOOT,J.TH,J.THEAD,J.TR]),Ha=new Set([J.APPLET,J.CAPTION,J.HTML,J.MARQUEE,J.OBJECT,J.TABLE,J.TD,J.TEMPLATE,J.TH]),Ua=new Set([...Ha,J.OL,J.UL]),Wa=new Set([...Ha,J.BUTTON]),Ga=new Set([J.ANNOTATION_XML,J.MI,J.MN,J.MO,J.MS,J.MTEXT]),Ka=new Set([J.DESC,J.FOREIGN_OBJECT,J.TITLE]),qa=new Set([J.TR,J.TEMPLATE,J.HTML]),Ja=new Set([J.TBODY,J.TFOOT,J.THEAD,J.TEMPLATE,J.HTML]),Ya=new Set([J.TABLE,J.TEMPLATE,J.HTML]),Xa=new Set([J.TD,J.TH]),Za=class{get currentTmplContentOrNode(){return this._isInTemplate()?this.treeAdapter.getTemplateContent(this.current):this.current}constructor(e,t,n){this.treeAdapter=t,this.handler=n,this.items=[],this.tagIDs=[],this.stackTop=-1,this.tmplCount=0,this.currentTagId=J.UNKNOWN,this.current=e}_indexOf(e){return this.items.lastIndexOf(e,this.stackTop)}_isInTemplate(){return this.currentTagId===J.TEMPLATE&&this.treeAdapter.getNamespaceURI(this.current)===G.HTML}_updateCurrentElement(){this.current=this.items[this.stackTop],this.currentTagId=this.tagIDs[this.stackTop]}push(e,t){this.stackTop++,this.items[this.stackTop]=e,this.current=e,this.tagIDs[this.stackTop]=t,this.currentTagId=t,this._isInTemplate()&&this.tmplCount++,this.handler.onItemPush(e,t,!0)}pop(){let e=this.current;this.tmplCount>0&&this._isInTemplate()&&this.tmplCount--,this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(e,!0)}replace(e,t){let n=this._indexOf(e);this.items[n]=t,n===this.stackTop&&(this.current=t)}insertAfter(e,t,n){let r=this._indexOf(e)+1;this.items.splice(r,0,t),this.tagIDs.splice(r,0,n),this.stackTop++,r===this.stackTop&&this._updateCurrentElement(),this.current&&this.currentTagId!==void 0&&this.handler.onItemPush(this.current,this.currentTagId,r===this.stackTop)}popUntilTagNamePopped(e){let t=this.stackTop+1;do t=this.tagIDs.lastIndexOf(e,t-1);while(t>0&&this.treeAdapter.getNamespaceURI(this.items[t])!==G.HTML);this.shortenToLength(Math.max(t,0))}shortenToLength(e){for(;this.stackTop>=e;){let t=this.current;this.tmplCount>0&&this._isInTemplate()&&--this.tmplCount,this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(t,this.stackTop<e)}}popUntilElementPopped(e){let t=this._indexOf(e);this.shortenToLength(Math.max(t,0))}popUntilPopped(e,t){let n=this._indexOfTagNames(e,t);this.shortenToLength(Math.max(n,0))}popUntilNumberedHeaderPopped(){this.popUntilPopped(Da,G.HTML)}popUntilTableCellPopped(){this.popUntilPopped(Xa,G.HTML)}popAllUpToHtmlElement(){this.tmplCount=0,this.shortenToLength(1)}_indexOfTagNames(e,t){for(let n=this.stackTop;n>=0;n--)if(e.has(this.tagIDs[n])&&this.treeAdapter.getNamespaceURI(this.items[n])===t)return n;return-1}clearBackTo(e,t){let n=this._indexOfTagNames(e,t);this.shortenToLength(n+1)}clearBackToTableContext(){this.clearBackTo(Ya,G.HTML)}clearBackToTableBodyContext(){this.clearBackTo(Ja,G.HTML)}clearBackToTableRowContext(){this.clearBackTo(qa,G.HTML)}remove(e){let t=this._indexOf(e);t>=0&&(t===this.stackTop?this.pop():(this.items.splice(t,1),this.tagIDs.splice(t,1),this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(e,!1)))}tryPeekProperlyNestedBodyElement(){return this.stackTop>=1&&this.tagIDs[1]===J.BODY?this.items[1]:null}contains(e){return this._indexOf(e)>-1}getCommonAncestor(e){let t=this._indexOf(e)-1;return t>=0?this.items[t]:null}isRootHtmlElementCurrent(){return this.stackTop===0&&this.tagIDs[0]===J.HTML}hasInDynamicScope(e,t){for(let n=this.stackTop;n>=0;n--){let r=this.tagIDs[n];switch(this.treeAdapter.getNamespaceURI(this.items[n])){case G.HTML:if(r===e)return!0;if(t.has(r))return!1;break;case G.SVG:if(Ka.has(r))return!1;break;case G.MATHML:if(Ga.has(r))return!1;break}}return!0}hasInScope(e){return this.hasInDynamicScope(e,Ha)}hasInListItemScope(e){return this.hasInDynamicScope(e,Ua)}hasInButtonScope(e){return this.hasInDynamicScope(e,Wa)}hasNumberedHeaderInScope(){for(let e=this.stackTop;e>=0;e--){let t=this.tagIDs[e];switch(this.treeAdapter.getNamespaceURI(this.items[e])){case G.HTML:if(Da.has(t))return!0;if(Ha.has(t))return!1;break;case G.SVG:if(Ka.has(t))return!1;break;case G.MATHML:if(Ga.has(t))return!1;break}}return!0}hasInTableScope(e){for(let t=this.stackTop;t>=0;t--)if(this.treeAdapter.getNamespaceURI(this.items[t])===G.HTML)switch(this.tagIDs[t]){case e:return!0;case J.TABLE:case J.HTML:return!1}return!0}hasTableBodyContextInTableScope(){for(let e=this.stackTop;e>=0;e--)if(this.treeAdapter.getNamespaceURI(this.items[e])===G.HTML)switch(this.tagIDs[e]){case J.TBODY:case J.THEAD:case J.TFOOT:return!0;case J.TABLE:case J.HTML:return!1}return!0}hasInSelectScope(e){for(let t=this.stackTop;t>=0;t--)if(this.treeAdapter.getNamespaceURI(this.items[t])===G.HTML)switch(this.tagIDs[t]){case e:return!0;case J.OPTION:case J.OPTGROUP:break;default:return!1}return!0}generateImpliedEndTags(){for(;this.currentTagId!==void 0&&Ba.has(this.currentTagId);)this.pop()}generateImpliedEndTagsThoroughly(){for(;this.currentTagId!==void 0&&Va.has(this.currentTagId);)this.pop()}generateImpliedEndTagsWithExclusion(e){for(;this.currentTagId!==void 0&&this.currentTagId!==e&&Va.has(this.currentTagId);)this.pop()}},Qa=3,$a;(function(e){e[e.Marker=0]=`Marker`,e[e.Element=1]=`Element`})($a||={});var eo={type:$a.Marker},to=class{constructor(e){this.treeAdapter=e,this.entries=[],this.bookmark=null}_getNoahArkConditionCandidates(e,t){let n=[],r=t.length,i=this.treeAdapter.getTagName(e),a=this.treeAdapter.getNamespaceURI(e);for(let e=0;e<this.entries.length;e++){let t=this.entries[e];if(t.type===$a.Marker)break;let{element:o}=t;if(this.treeAdapter.getTagName(o)===i&&this.treeAdapter.getNamespaceURI(o)===a){let t=this.treeAdapter.getAttrList(o);t.length===r&&n.push({idx:e,attrs:t})}}return n}_ensureNoahArkCondition(e){if(this.entries.length<Qa)return;let t=this.treeAdapter.getAttrList(e),n=this._getNoahArkConditionCandidates(e,t);if(n.length<Qa)return;let r=new Map(t.map(e=>[e.name,e.value])),i=0;for(let e=0;e<n.length;e++){let t=n[e];t.attrs.every(e=>r.get(e.name)===e.value)&&(i+=1,i>=Qa&&this.entries.splice(t.idx,1))}}insertMarker(){this.entries.unshift(eo)}pushElement(e,t){this._ensureNoahArkCondition(e),this.entries.unshift({type:$a.Element,element:e,token:t})}insertElementAfterBookmark(e,t){let n=this.entries.indexOf(this.bookmark);this.entries.splice(n,0,{type:$a.Element,element:e,token:t})}removeEntry(e){let t=this.entries.indexOf(e);t!==-1&&this.entries.splice(t,1)}clearToLastMarker(){let e=this.entries.indexOf(eo);e===-1?this.entries.length=0:this.entries.splice(0,e+1)}getElementEntryInScopeWithTagName(e){let t=this.entries.find(t=>t.type===$a.Marker||this.treeAdapter.getTagName(t.element)===e);return t&&t.type===$a.Element?t:null}getElementEntry(e){return this.entries.find(t=>t.type===$a.Element&&t.element===e)}},no={createDocument(){return{nodeName:`#document`,mode:K.NO_QUIRKS,childNodes:[]}},createDocumentFragment(){return{nodeName:`#document-fragment`,childNodes:[]}},createElement(e,t,n){return{nodeName:e,tagName:e,attrs:n,namespaceURI:t,childNodes:[],parentNode:null}},createCommentNode(e){return{nodeName:`#comment`,data:e,parentNode:null}},createTextNode(e){return{nodeName:`#text`,value:e,parentNode:null}},appendChild(e,t){e.childNodes.push(t),t.parentNode=e},insertBefore(e,t,n){let r=e.childNodes.indexOf(n);e.childNodes.splice(r,0,t),t.parentNode=e},setTemplateContent(e,t){e.content=t},getTemplateContent(e){return e.content},setDocumentType(e,t,n,r){let i=e.childNodes.find(e=>e.nodeName===`#documentType`);if(i)i.name=t,i.publicId=n,i.systemId=r;else{let i={nodeName:`#documentType`,name:t,publicId:n,systemId:r,parentNode:null};no.appendChild(e,i)}},setDocumentMode(e,t){e.mode=t},getDocumentMode(e){return e.mode},detachNode(e){if(e.parentNode){let t=e.parentNode.childNodes.indexOf(e);e.parentNode.childNodes.splice(t,1),e.parentNode=null}},insertText(e,t){if(e.childNodes.length>0){let n=e.childNodes[e.childNodes.length-1];if(no.isTextNode(n)){n.value+=t;return}}no.appendChild(e,no.createTextNode(t))},insertTextBefore(e,t,n){let r=e.childNodes[e.childNodes.indexOf(n)-1];r&&no.isTextNode(r)?r.value+=t:no.insertBefore(e,no.createTextNode(t),n)},adoptAttributes(e,t){let n=new Set(e.attrs.map(e=>e.name));for(let r=0;r<t.length;r++)n.has(t[r].name)||e.attrs.push(t[r])},getFirstChild(e){return e.childNodes[0]},getChildNodes(e){return e.childNodes},getParentNode(e){return e.parentNode},getAttrList(e){return e.attrs},getTagName(e){return e.tagName},getNamespaceURI(e){return e.namespaceURI},getTextNodeContent(e){return e.value},getCommentNodeContent(e){return e.data},getDocumentTypeNodeName(e){return e.name},getDocumentTypeNodePublicId(e){return e.publicId},getDocumentTypeNodeSystemId(e){return e.systemId},isTextNode(e){return e.nodeName===`#text`},isCommentNode(e){return e.nodeName===`#comment`},isDocumentTypeNode(e){return e.nodeName===`#documentType`},isElementNode(e){return Object.prototype.hasOwnProperty.call(e,`tagName`)},setNodeSourceCodeLocation(e,t){e.sourceCodeLocation=t},getNodeSourceCodeLocation(e){return e.sourceCodeLocation},updateNodeSourceCodeLocation(e,t){e.sourceCodeLocation={...e.sourceCodeLocation,...t}}},ro=`html`,io=`about:legacy-compat`,ao=`http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd`,oo=`+//silmaril//dtd html pro v0r11 19970101//,-//as//dtd html 3.0 aswedit + extensions//,-//advasoft ltd//dtd html 3.0 aswedit + extensions//,-//ietf//dtd html 2.0 level 1//,-//ietf//dtd html 2.0 level 2//,-//ietf//dtd html 2.0 strict level 1//,-//ietf//dtd html 2.0 strict level 2//,-//ietf//dtd html 2.0 strict//,-//ietf//dtd html 2.0//,-//ietf//dtd html 2.1e//,-//ietf//dtd html 3.0//,-//ietf//dtd html 3.2 final//,-//ietf//dtd html 3.2//,-//ietf//dtd html 3//,-//ietf//dtd html level 0//,-//ietf//dtd html level 1//,-//ietf//dtd html level 2//,-//ietf//dtd html level 3//,-//ietf//dtd html strict level 0//,-//ietf//dtd html strict level 1//,-//ietf//dtd html strict level 2//,-//ietf//dtd html strict level 3//,-//ietf//dtd html strict//,-//ietf//dtd html//,-//metrius//dtd metrius presentational//,-//microsoft//dtd internet explorer 2.0 html strict//,-//microsoft//dtd internet explorer 2.0 html//,-//microsoft//dtd internet explorer 2.0 tables//,-//microsoft//dtd internet explorer 3.0 html strict//,-//microsoft//dtd internet explorer 3.0 html//,-//microsoft//dtd internet explorer 3.0 tables//,-//netscape comm. corp.//dtd html//,-//netscape comm. corp.//dtd strict html//,-//o'reilly and associates//dtd html 2.0//,-//o'reilly and associates//dtd html extended 1.0//,-//o'reilly and associates//dtd html extended relaxed 1.0//,-//sq//dtd html 2.0 hotmetal + extensions//,-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//,-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//,-//spyglass//dtd html 2.0 extended//,-//sun microsystems corp.//dtd hotjava html//,-//sun microsystems corp.//dtd hotjava strict html//,-//w3c//dtd html 3 1995-03-24//,-//w3c//dtd html 3.2 draft//,-//w3c//dtd html 3.2 final//,-//w3c//dtd html 3.2//,-//w3c//dtd html 3.2s draft//,-//w3c//dtd html 4.0 frameset//,-//w3c//dtd html 4.0 transitional//,-//w3c//dtd html experimental 19960712//,-//w3c//dtd html experimental 970421//,-//w3c//dtd w3 html//,-//w3o//dtd w3 html 3.0//,-//webtechs//dtd mozilla html 2.0//,-//webtechs//dtd mozilla html//`.split(`,`),so=[...oo,`-//w3c//dtd html 4.01 frameset//`,`-//w3c//dtd html 4.01 transitional//`],co=new Set([`-//w3o//dtd w3 html strict 3.0//en//`,`-/w3c/dtd html 4.0 transitional/en`,`html`]),lo=[`-//w3c//dtd xhtml 1.0 frameset//`,`-//w3c//dtd xhtml 1.0 transitional//`],uo=[...lo,`-//w3c//dtd html 4.01 frameset//`,`-//w3c//dtd html 4.01 transitional//`];function fo(e,t){return t.some(t=>e.startsWith(t))}function po(e){return e.name===ro&&e.publicId===null&&(e.systemId===null||e.systemId===io)}function mo(e){if(e.name!==ro)return K.QUIRKS;let{systemId:t}=e;if(t&&t.toLowerCase()===ao)return K.QUIRKS;let{publicId:n}=e;if(n!==null){if(n=n.toLowerCase(),co.has(n))return K.QUIRKS;let e=t===null?so:oo;if(fo(n,e))return K.QUIRKS;if(e=t===null?lo:uo,fo(n,e))return K.LIMITED_QUIRKS}return K.NO_QUIRKS}var ho={TEXT_HTML:`text/html`,APPLICATION_XML:`application/xhtml+xml`},go=`definitionurl`,_o=`definitionURL`,vo=new Map(`attributeName.attributeType.baseFrequency.baseProfile.calcMode.clipPathUnits.diffuseConstant.edgeMode.filterUnits.glyphRef.gradientTransform.gradientUnits.kernelMatrix.kernelUnitLength.keyPoints.keySplines.keyTimes.lengthAdjust.limitingConeAngle.markerHeight.markerUnits.markerWidth.maskContentUnits.maskUnits.numOctaves.pathLength.patternContentUnits.patternTransform.patternUnits.pointsAtX.pointsAtY.pointsAtZ.preserveAlpha.preserveAspectRatio.primitiveUnits.refX.refY.repeatCount.repeatDur.requiredExtensions.requiredFeatures.specularConstant.specularExponent.spreadMethod.startOffset.stdDeviation.stitchTiles.surfaceScale.systemLanguage.tableValues.targetX.targetY.textLength.viewBox.viewTarget.xChannelSelector.yChannelSelector.zoomAndPan`.split(`.`).map(e=>[e.toLowerCase(),e])),yo=new Map([[`xlink:actuate`,{prefix:`xlink`,name:`actuate`,namespace:G.XLINK}],[`xlink:arcrole`,{prefix:`xlink`,name:`arcrole`,namespace:G.XLINK}],[`xlink:href`,{prefix:`xlink`,name:`href`,namespace:G.XLINK}],[`xlink:role`,{prefix:`xlink`,name:`role`,namespace:G.XLINK}],[`xlink:show`,{prefix:`xlink`,name:`show`,namespace:G.XLINK}],[`xlink:title`,{prefix:`xlink`,name:`title`,namespace:G.XLINK}],[`xlink:type`,{prefix:`xlink`,name:`type`,namespace:G.XLINK}],[`xml:lang`,{prefix:`xml`,name:`lang`,namespace:G.XML}],[`xml:space`,{prefix:`xml`,name:`space`,namespace:G.XML}],[`xmlns`,{prefix:``,name:`xmlns`,namespace:G.XMLNS}],[`xmlns:xlink`,{prefix:`xmlns`,name:`xlink`,namespace:G.XMLNS}]]),bo=new Map(`altGlyph.altGlyphDef.altGlyphItem.animateColor.animateMotion.animateTransform.clipPath.feBlend.feColorMatrix.feComponentTransfer.feComposite.feConvolveMatrix.feDiffuseLighting.feDisplacementMap.feDistantLight.feFlood.feFuncA.feFuncB.feFuncG.feFuncR.feGaussianBlur.feImage.feMerge.feMergeNode.feMorphology.feOffset.fePointLight.feSpecularLighting.feSpotLight.feTile.feTurbulence.foreignObject.glyphRef.linearGradient.radialGradient.textPath`.split(`.`).map(e=>[e.toLowerCase(),e])),xo=new Set([J.B,J.BIG,J.BLOCKQUOTE,J.BODY,J.BR,J.CENTER,J.CODE,J.DD,J.DIV,J.DL,J.DT,J.EM,J.EMBED,J.H1,J.H2,J.H3,J.H4,J.H5,J.H6,J.HEAD,J.HR,J.I,J.IMG,J.LI,J.LISTING,J.MENU,J.META,J.NOBR,J.OL,J.P,J.PRE,J.RUBY,J.S,J.SMALL,J.SPAN,J.STRONG,J.STRIKE,J.SUB,J.SUP,J.TABLE,J.TT,J.U,J.UL,J.VAR]);function So(e){let t=e.tagID;return t===J.FONT&&e.attrs.some(({name:e})=>e===Ca.COLOR||e===Ca.SIZE||e===Ca.FACE)||xo.has(t)}function Co(e){for(let t=0;t<e.attrs.length;t++)if(e.attrs[t].name===go){e.attrs[t].name=_o;break}}function wo(e){for(let t=0;t<e.attrs.length;t++){let n=vo.get(e.attrs[t].name);n!=null&&(e.attrs[t].name=n)}}function To(e){for(let t=0;t<e.attrs.length;t++){let n=yo.get(e.attrs[t].name);n&&(e.attrs[t].prefix=n.prefix,e.attrs[t].name=n.name,e.attrs[t].namespace=n.namespace)}}function Eo(e){let t=bo.get(e.tagName);t!=null&&(e.tagName=t,e.tagID=Ta(e.tagName))}function Do(e,t){return t===G.MATHML&&(e===J.MI||e===J.MO||e===J.MN||e===J.MS||e===J.MTEXT)}function Oo(e,t,n){if(t===G.MATHML&&e===J.ANNOTATION_XML){for(let e=0;e<n.length;e++)if(n[e].name===Ca.ENCODING){let t=n[e].value.toLowerCase();return t===ho.TEXT_HTML||t===ho.APPLICATION_XML}}return t===G.SVG&&(e===J.FOREIGN_OBJECT||e===J.DESC||e===J.TITLE)}function ko(e,t,n,r){return(!r||r===G.HTML)&&Oo(e,t,n)||(!r||r===G.MATHML)&&Do(e,t)}var Ao=`hidden`,jo=8,Mo=3,Q;(function(e){e[e.INITIAL=0]=`INITIAL`,e[e.BEFORE_HTML=1]=`BEFORE_HTML`,e[e.BEFORE_HEAD=2]=`BEFORE_HEAD`,e[e.IN_HEAD=3]=`IN_HEAD`,e[e.IN_HEAD_NO_SCRIPT=4]=`IN_HEAD_NO_SCRIPT`,e[e.AFTER_HEAD=5]=`AFTER_HEAD`,e[e.IN_BODY=6]=`IN_BODY`,e[e.TEXT=7]=`TEXT`,e[e.IN_TABLE=8]=`IN_TABLE`,e[e.IN_TABLE_TEXT=9]=`IN_TABLE_TEXT`,e[e.IN_CAPTION=10]=`IN_CAPTION`,e[e.IN_COLUMN_GROUP=11]=`IN_COLUMN_GROUP`,e[e.IN_TABLE_BODY=12]=`IN_TABLE_BODY`,e[e.IN_ROW=13]=`IN_ROW`,e[e.IN_CELL=14]=`IN_CELL`,e[e.IN_SELECT=15]=`IN_SELECT`,e[e.IN_SELECT_IN_TABLE=16]=`IN_SELECT_IN_TABLE`,e[e.IN_TEMPLATE=17]=`IN_TEMPLATE`,e[e.AFTER_BODY=18]=`AFTER_BODY`,e[e.IN_FRAMESET=19]=`IN_FRAMESET`,e[e.AFTER_FRAMESET=20]=`AFTER_FRAMESET`,e[e.AFTER_AFTER_BODY=21]=`AFTER_AFTER_BODY`,e[e.AFTER_AFTER_FRAMESET=22]=`AFTER_AFTER_FRAMESET`})(Q||={});var No={startLine:-1,startCol:-1,startOffset:-1,endLine:-1,endCol:-1,endOffset:-1},Po=new Set([J.TABLE,J.TBODY,J.TFOOT,J.THEAD,J.TR]),Fo={scriptingEnabled:!0,sourceCodeLocationInfo:!1,treeAdapter:no,onParseError:null},Io=class{constructor(e,t,n=null,r=null){this.fragmentContext=n,this.scriptHandler=r,this.currentToken=null,this.stopped=!1,this.insertionMode=Q.INITIAL,this.originalInsertionMode=Q.INITIAL,this.headElement=null,this.formElement=null,this.currentNotInHTML=!1,this.tmplInsertionModeStack=[],this.pendingCharacterTokens=[],this.hasNonWhitespacePendingCharacterToken=!1,this.framesetOk=!0,this.skipNextNewLine=!1,this.fosterParentingEnabled=!1,this.options={...Fo,...e},this.treeAdapter=this.options.treeAdapter,this.onParseError=this.options.onParseError,this.onParseError&&(this.options.sourceCodeLocationInfo=!0),this.document=t??this.treeAdapter.createDocument(),this.tokenizer=new za(this.options,this),this.activeFormattingElements=new to(this.treeAdapter),this.fragmentContextID=n?Ta(this.treeAdapter.getTagName(n)):J.UNKNOWN,this._setContextModes(n??this.document,this.fragmentContextID),this.openElements=new Za(this.document,this.treeAdapter,this)}static parse(e,t){let n=new this(t);return n.tokenizer.write(e,!0),n.document}static getFragmentParser(e,t){let n={...Fo,...t};e??=n.treeAdapter.createElement(q.TEMPLATE,G.HTML,[]);let r=n.treeAdapter.createElement(`documentmock`,G.HTML,[]),i=new this(n,r,e);return i.fragmentContextID===J.TEMPLATE&&i.tmplInsertionModeStack.unshift(Q.IN_TEMPLATE),i._initTokenizerForFragmentParsing(),i._insertFakeRootElement(),i._resetInsertionMode(),i._findFormInFragmentContext(),i}getFragment(){let e=this.treeAdapter.getFirstChild(this.document),t=this.treeAdapter.createDocumentFragment();return this._adoptNodes(e,t),t}_err(e,t,n){if(!this.onParseError)return;let r=e.location??No,i={code:t,startLine:r.startLine,startCol:r.startCol,startOffset:r.startOffset,endLine:n?r.startLine:r.endLine,endCol:n?r.startCol:r.endCol,endOffset:n?r.startOffset:r.endOffset};this.onParseError(i)}onItemPush(e,t,n){var r,i;(i=(r=this.treeAdapter).onItemPush)==null||i.call(r,e),n&&this.openElements.stackTop>0&&this._setContextModes(e,t)}onItemPop(e,t){var n,r;if(this.options.sourceCodeLocationInfo&&this._setEndLocation(e,this.currentToken),(r=(n=this.treeAdapter).onItemPop)==null||r.call(n,e,this.openElements.current),t){let e,t;this.openElements.stackTop===0&&this.fragmentContext?(e=this.fragmentContext,t=this.fragmentContextID):{current:e,currentTagId:t}=this.openElements,this._setContextModes(e,t)}}_setContextModes(e,t){let n=e===this.document||e&&this.treeAdapter.getNamespaceURI(e)===G.HTML;this.currentNotInHTML=!n,this.tokenizer.inForeignNode=!n&&e!==void 0&&t!==void 0&&!this._isIntegrationPoint(t,e)}_switchToTextParsing(e,t){this._insertElement(e,G.HTML),this.tokenizer.state=t,this.originalInsertionMode=this.insertionMode,this.insertionMode=Q.TEXT}switchToPlaintextParsing(){this.insertionMode=Q.TEXT,this.originalInsertionMode=Q.IN_BODY,this.tokenizer.state=Z.PLAINTEXT}_getAdjustedCurrentElement(){return this.openElements.stackTop===0&&this.fragmentContext?this.fragmentContext:this.openElements.current}_findFormInFragmentContext(){let e=this.fragmentContext;for(;e;){if(this.treeAdapter.getTagName(e)===q.FORM){this.formElement=e;break}e=this.treeAdapter.getParentNode(e)}}_initTokenizerForFragmentParsing(){if(!(!this.fragmentContext||this.treeAdapter.getNamespaceURI(this.fragmentContext)!==G.HTML))switch(this.fragmentContextID){case J.TITLE:case J.TEXTAREA:this.tokenizer.state=Z.RCDATA;break;case J.STYLE:case J.XMP:case J.IFRAME:case J.NOEMBED:case J.NOFRAMES:case J.NOSCRIPT:this.tokenizer.state=Z.RAWTEXT;break;case J.SCRIPT:this.tokenizer.state=Z.SCRIPT_DATA;break;case J.PLAINTEXT:this.tokenizer.state=Z.PLAINTEXT;break;default:}}_setDocumentType(e){let t=e.name||``,n=e.publicId||``,r=e.systemId||``;if(this.treeAdapter.setDocumentType(this.document,t,n,r),e.location){let t=this.treeAdapter.getChildNodes(this.document).find(e=>this.treeAdapter.isDocumentTypeNode(e));t&&this.treeAdapter.setNodeSourceCodeLocation(t,e.location)}}_attachElementToTree(e,t){if(this.options.sourceCodeLocationInfo){let n=t&&{...t,startTag:t};this.treeAdapter.setNodeSourceCodeLocation(e,n)}if(this._shouldFosterParentOnInsertion())this._fosterParentElement(e);else{let t=this.openElements.currentTmplContentOrNode;this.treeAdapter.appendChild(t??this.document,e)}}_appendElement(e,t){let n=this.treeAdapter.createElement(e.tagName,t,e.attrs);this._attachElementToTree(n,e.location)}_insertElement(e,t){let n=this.treeAdapter.createElement(e.tagName,t,e.attrs);this._attachElementToTree(n,e.location),this.openElements.push(n,e.tagID)}_insertFakeElement(e,t){let n=this.treeAdapter.createElement(e,G.HTML,[]);this._attachElementToTree(n,null),this.openElements.push(n,t)}_insertTemplate(e){let t=this.treeAdapter.createElement(e.tagName,G.HTML,e.attrs),n=this.treeAdapter.createDocumentFragment();this.treeAdapter.setTemplateContent(t,n),this._attachElementToTree(t,e.location),this.openElements.push(t,e.tagID),this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(n,null)}_insertFakeRootElement(){let e=this.treeAdapter.createElement(q.HTML,G.HTML,[]);this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(e,null),this.treeAdapter.appendChild(this.openElements.current,e),this.openElements.push(e,J.HTML)}_appendCommentNode(e,t){let n=this.treeAdapter.createCommentNode(e.data);this.treeAdapter.appendChild(t,n),this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(n,e.location)}_insertCharacters(e){let t,n;if(this._shouldFosterParentOnInsertion()?({parent:t,beforeElement:n}=this._findFosterParentingLocation(),n?this.treeAdapter.insertTextBefore(t,e.chars,n):this.treeAdapter.insertText(t,e.chars)):(t=this.openElements.currentTmplContentOrNode,this.treeAdapter.insertText(t,e.chars)),!e.location)return;let r=this.treeAdapter.getChildNodes(t),i=r[(n?r.lastIndexOf(n):r.length)-1];if(this.treeAdapter.getNodeSourceCodeLocation(i)){let{endLine:t,endCol:n,endOffset:r}=e.location;this.treeAdapter.updateNodeSourceCodeLocation(i,{endLine:t,endCol:n,endOffset:r})}else this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(i,e.location)}_adoptNodes(e,t){for(let n=this.treeAdapter.getFirstChild(e);n;n=this.treeAdapter.getFirstChild(e))this.treeAdapter.detachNode(n),this.treeAdapter.appendChild(t,n)}_setEndLocation(e,t){if(this.treeAdapter.getNodeSourceCodeLocation(e)&&t.location){let n=t.location,r=this.treeAdapter.getTagName(e),i=t.type===W.END_TAG&&r===t.tagName?{endTag:{...n},endLine:n.endLine,endCol:n.endCol,endOffset:n.endOffset}:{endLine:n.startLine,endCol:n.startCol,endOffset:n.startOffset};this.treeAdapter.updateNodeSourceCodeLocation(e,i)}}shouldProcessStartTagTokenInForeignContent(e){if(!this.currentNotInHTML)return!1;let t,n;return this.openElements.stackTop===0&&this.fragmentContext?(t=this.fragmentContext,n=this.fragmentContextID):{current:t,currentTagId:n}=this.openElements,e.tagID===J.SVG&&this.treeAdapter.getTagName(t)===q.ANNOTATION_XML&&this.treeAdapter.getNamespaceURI(t)===G.MATHML?!1:this.tokenizer.inForeignNode||(e.tagID===J.MGLYPH||e.tagID===J.MALIGNMARK)&&n!==void 0&&!this._isIntegrationPoint(n,t,G.HTML)}_processToken(e){switch(e.type){case W.CHARACTER:this.onCharacter(e);break;case W.NULL_CHARACTER:this.onNullCharacter(e);break;case W.COMMENT:this.onComment(e);break;case W.DOCTYPE:this.onDoctype(e);break;case W.START_TAG:this._processStartTag(e);break;case W.END_TAG:this.onEndTag(e);break;case W.EOF:this.onEof(e);break;case W.WHITESPACE_CHARACTER:this.onWhitespaceCharacter(e);break}}_isIntegrationPoint(e,t,n){return ko(e,this.treeAdapter.getNamespaceURI(t),this.treeAdapter.getAttrList(t),n)}_reconstructActiveFormattingElements(){let e=this.activeFormattingElements.entries.length;if(e){let t=this.activeFormattingElements.entries.findIndex(e=>e.type===$a.Marker||this.openElements.contains(e.element)),n=t===-1?e-1:t-1;for(let e=n;e>=0;e--){let t=this.activeFormattingElements.entries[e];this._insertElement(t.token,this.treeAdapter.getNamespaceURI(t.element)),t.element=this.openElements.current}}}_closeTableCell(){this.openElements.generateImpliedEndTags(),this.openElements.popUntilTableCellPopped(),this.activeFormattingElements.clearToLastMarker(),this.insertionMode=Q.IN_ROW}_closePElement(){this.openElements.generateImpliedEndTagsWithExclusion(J.P),this.openElements.popUntilTagNamePopped(J.P)}_resetInsertionMode(){for(let e=this.openElements.stackTop;e>=0;e--)switch(e===0&&this.fragmentContext?this.fragmentContextID:this.openElements.tagIDs[e]){case J.TR:this.insertionMode=Q.IN_ROW;return;case J.TBODY:case J.THEAD:case J.TFOOT:this.insertionMode=Q.IN_TABLE_BODY;return;case J.CAPTION:this.insertionMode=Q.IN_CAPTION;return;case J.COLGROUP:this.insertionMode=Q.IN_COLUMN_GROUP;return;case J.TABLE:this.insertionMode=Q.IN_TABLE;return;case J.BODY:this.insertionMode=Q.IN_BODY;return;case J.FRAMESET:this.insertionMode=Q.IN_FRAMESET;return;case J.SELECT:this._resetInsertionModeForSelect(e);return;case J.TEMPLATE:this.insertionMode=this.tmplInsertionModeStack[0];return;case J.HTML:this.insertionMode=this.headElement?Q.AFTER_HEAD:Q.BEFORE_HEAD;return;case J.TD:case J.TH:if(e>0){this.insertionMode=Q.IN_CELL;return}break;case J.HEAD:if(e>0){this.insertionMode=Q.IN_HEAD;return}break}this.insertionMode=Q.IN_BODY}_resetInsertionModeForSelect(e){if(e>0)for(let t=e-1;t>0;t--){let e=this.openElements.tagIDs[t];if(e===J.TEMPLATE)break;if(e===J.TABLE){this.insertionMode=Q.IN_SELECT_IN_TABLE;return}}this.insertionMode=Q.IN_SELECT}_isElementCausesFosterParenting(e){return Po.has(e)}_shouldFosterParentOnInsertion(){return this.fosterParentingEnabled&&this.openElements.currentTagId!==void 0&&this._isElementCausesFosterParenting(this.openElements.currentTagId)}_findFosterParentingLocation(){for(let e=this.openElements.stackTop;e>=0;e--){let t=this.openElements.items[e];switch(this.openElements.tagIDs[e]){case J.TEMPLATE:if(this.treeAdapter.getNamespaceURI(t)===G.HTML)return{parent:this.treeAdapter.getTemplateContent(t),beforeElement:null};break;case J.TABLE:{let n=this.treeAdapter.getParentNode(t);return n?{parent:n,beforeElement:t}:{parent:this.openElements.items[e-1],beforeElement:null}}default:}}return{parent:this.openElements.items[0],beforeElement:null}}_fosterParentElement(e){let t=this._findFosterParentingLocation();t.beforeElement?this.treeAdapter.insertBefore(t.parent,e,t.beforeElement):this.treeAdapter.appendChild(t.parent,e)}_isSpecialElement(e,t){return Ea[this.treeAdapter.getNamespaceURI(e)].has(t)}onCharacter(e){if(this.skipNextNewLine=!1,this.tokenizer.inForeignNode){$c(this,e);return}switch(this.insertionMode){case Q.INITIAL:Yo(this,e);break;case Q.BEFORE_HTML:Qo(this,e);break;case Q.BEFORE_HEAD:ts(this,e);break;case Q.IN_HEAD:as(this,e);break;case Q.IN_HEAD_NO_SCRIPT:cs(this,e);break;case Q.AFTER_HEAD:ds(this,e);break;case Q.IN_BODY:case Q.IN_CAPTION:case Q.IN_CELL:case Q.IN_TEMPLATE:ms(this,e);break;case Q.TEXT:case Q.IN_SELECT:case Q.IN_SELECT_IN_TABLE:this._insertCharacters(e);break;case Q.IN_TABLE:case Q.IN_TABLE_BODY:case Q.IN_ROW:cc(this,e);break;case Q.IN_TABLE_TEXT:xc(this,e);break;case Q.IN_COLUMN_GROUP:Oc(this,e);break;case Q.AFTER_BODY:Wc(this,e);break;case Q.AFTER_AFTER_BODY:Xc(this,e);break;default:}}onNullCharacter(e){if(this.skipNextNewLine=!1,this.tokenizer.inForeignNode){Qc(this,e);return}switch(this.insertionMode){case Q.INITIAL:Yo(this,e);break;case Q.BEFORE_HTML:Qo(this,e);break;case Q.BEFORE_HEAD:ts(this,e);break;case Q.IN_HEAD:as(this,e);break;case Q.IN_HEAD_NO_SCRIPT:cs(this,e);break;case Q.AFTER_HEAD:ds(this,e);break;case Q.TEXT:this._insertCharacters(e);break;case Q.IN_TABLE:case Q.IN_TABLE_BODY:case Q.IN_ROW:cc(this,e);break;case Q.IN_COLUMN_GROUP:Oc(this,e);break;case Q.AFTER_BODY:Wc(this,e);break;case Q.AFTER_AFTER_BODY:Xc(this,e);break;default:}}onComment(e){if(this.skipNextNewLine=!1,this.currentNotInHTML){Wo(this,e);return}switch(this.insertionMode){case Q.INITIAL:case Q.BEFORE_HTML:case Q.BEFORE_HEAD:case Q.IN_HEAD:case Q.IN_HEAD_NO_SCRIPT:case Q.AFTER_HEAD:case Q.IN_BODY:case Q.IN_TABLE:case Q.IN_CAPTION:case Q.IN_COLUMN_GROUP:case Q.IN_TABLE_BODY:case Q.IN_ROW:case Q.IN_CELL:case Q.IN_SELECT:case Q.IN_SELECT_IN_TABLE:case Q.IN_TEMPLATE:case Q.IN_FRAMESET:case Q.AFTER_FRAMESET:Wo(this,e);break;case Q.IN_TABLE_TEXT:Sc(this,e);break;case Q.AFTER_BODY:Go(this,e);break;case Q.AFTER_AFTER_BODY:case Q.AFTER_AFTER_FRAMESET:Ko(this,e);break;default:}}onDoctype(e){switch(this.skipNextNewLine=!1,this.insertionMode){case Q.INITIAL:Jo(this,e);break;case Q.BEFORE_HEAD:case Q.IN_HEAD:case Q.IN_HEAD_NO_SCRIPT:case Q.AFTER_HEAD:this._err(e,U.misplacedDoctype);break;case Q.IN_TABLE_TEXT:Sc(this,e);break;default:}}onStartTag(e){this.skipNextNewLine=!1,this.currentToken=e,this._processStartTag(e),e.selfClosing&&!e.ackSelfClosing&&this._err(e,U.nonVoidHtmlElementStartTagWithTrailingSolidus)}_processStartTag(e){this.shouldProcessStartTagTokenInForeignContent(e)?tl(this,e):this._startTagOutsideForeignContent(e)}_startTagOutsideForeignContent(e){switch(this.insertionMode){case Q.INITIAL:Yo(this,e);break;case Q.BEFORE_HTML:Xo(this,e);break;case Q.BEFORE_HEAD:$o(this,e);break;case Q.IN_HEAD:ns(this,e);break;case Q.IN_HEAD_NO_SCRIPT:os(this,e);break;case Q.AFTER_HEAD:ls(this,e);break;case Q.IN_BODY:$(this,e);break;case Q.IN_TABLE:_c(this,e);break;case Q.IN_TABLE_TEXT:Sc(this,e);break;case Q.IN_CAPTION:wc(this,e);break;case Q.IN_COLUMN_GROUP:Ec(this,e);break;case Q.IN_TABLE_BODY:kc(this,e);break;case Q.IN_ROW:jc(this,e);break;case Q.IN_CELL:Nc(this,e);break;case Q.IN_SELECT:Fc(this,e);break;case Q.IN_SELECT_IN_TABLE:Lc(this,e);break;case Q.IN_TEMPLATE:zc(this,e);break;case Q.AFTER_BODY:Hc(this,e);break;case Q.IN_FRAMESET:Gc(this,e);break;case Q.AFTER_FRAMESET:qc(this,e);break;case Q.AFTER_AFTER_BODY:Yc(this,e);break;case Q.AFTER_AFTER_FRAMESET:Zc(this,e);break;default:}}onEndTag(e){this.skipNextNewLine=!1,this.currentToken=e,this.currentNotInHTML?nl(this,e):this._endTagOutsideForeignContent(e)}_endTagOutsideForeignContent(e){switch(this.insertionMode){case Q.INITIAL:Yo(this,e);break;case Q.BEFORE_HTML:Zo(this,e);break;case Q.BEFORE_HEAD:es(this,e);break;case Q.IN_HEAD:rs(this,e);break;case Q.IN_HEAD_NO_SCRIPT:ss(this,e);break;case Q.AFTER_HEAD:us(this,e);break;case Q.IN_BODY:ic(this,e);break;case Q.TEXT:oc(this,e);break;case Q.IN_TABLE:vc(this,e);break;case Q.IN_TABLE_TEXT:Sc(this,e);break;case Q.IN_CAPTION:Tc(this,e);break;case Q.IN_COLUMN_GROUP:Dc(this,e);break;case Q.IN_TABLE_BODY:Ac(this,e);break;case Q.IN_ROW:Mc(this,e);break;case Q.IN_CELL:Pc(this,e);break;case Q.IN_SELECT:Ic(this,e);break;case Q.IN_SELECT_IN_TABLE:Rc(this,e);break;case Q.IN_TEMPLATE:Bc(this,e);break;case Q.AFTER_BODY:Uc(this,e);break;case Q.IN_FRAMESET:Kc(this,e);break;case Q.AFTER_FRAMESET:Jc(this,e);break;case Q.AFTER_AFTER_BODY:Xc(this,e);break;default:}}onEof(e){switch(this.insertionMode){case Q.INITIAL:Yo(this,e);break;case Q.BEFORE_HTML:Qo(this,e);break;case Q.BEFORE_HEAD:ts(this,e);break;case Q.IN_HEAD:as(this,e);break;case Q.IN_HEAD_NO_SCRIPT:cs(this,e);break;case Q.AFTER_HEAD:ds(this,e);break;case Q.IN_BODY:case Q.IN_TABLE:case Q.IN_CAPTION:case Q.IN_COLUMN_GROUP:case Q.IN_TABLE_BODY:case Q.IN_ROW:case Q.IN_CELL:case Q.IN_SELECT:case Q.IN_SELECT_IN_TABLE:ac(this,e);break;case Q.TEXT:sc(this,e);break;case Q.IN_TABLE_TEXT:Sc(this,e);break;case Q.IN_TEMPLATE:Vc(this,e);break;case Q.AFTER_BODY:case Q.IN_FRAMESET:case Q.AFTER_FRAMESET:case Q.AFTER_AFTER_BODY:case Q.AFTER_AFTER_FRAMESET:qo(this,e);break;default:}}onWhitespaceCharacter(e){if(this.skipNextNewLine&&(this.skipNextNewLine=!1,e.chars.charCodeAt(0)===V.LINE_FEED)){if(e.chars.length===1)return;e.chars=e.chars.substr(1)}if(this.tokenizer.inForeignNode){this._insertCharacters(e);return}switch(this.insertionMode){case Q.IN_HEAD:case Q.IN_HEAD_NO_SCRIPT:case Q.AFTER_HEAD:case Q.TEXT:case Q.IN_COLUMN_GROUP:case Q.IN_SELECT:case Q.IN_SELECT_IN_TABLE:case Q.IN_FRAMESET:case Q.AFTER_FRAMESET:this._insertCharacters(e);break;case Q.IN_BODY:case Q.IN_CAPTION:case Q.IN_CELL:case Q.IN_TEMPLATE:case Q.AFTER_BODY:case Q.AFTER_AFTER_BODY:case Q.AFTER_AFTER_FRAMESET:ps(this,e);break;case Q.IN_TABLE:case Q.IN_TABLE_BODY:case Q.IN_ROW:cc(this,e);break;case Q.IN_TABLE_TEXT:bc(this,e);break;default:}}};function Lo(e,t){let n=e.activeFormattingElements.getElementEntryInScopeWithTagName(t.tagName);return n?e.openElements.contains(n.element)?e.openElements.hasInScope(t.tagID)||(n=null):(e.activeFormattingElements.removeEntry(n),n=null):rc(e,t),n}function Ro(e,t){let n=null,r=e.openElements.stackTop;for(;r>=0;r--){let i=e.openElements.items[r];if(i===t.element)break;e._isSpecialElement(i,e.openElements.tagIDs[r])&&(n=i)}return n||(e.openElements.shortenToLength(Math.max(r,0)),e.activeFormattingElements.removeEntry(t)),n}function zo(e,t,n){let r=t,i=e.openElements.getCommonAncestor(t);for(let a=0,o=i;o!==n;a++,o=i){i=e.openElements.getCommonAncestor(o);let n=e.activeFormattingElements.getElementEntry(o),s=n&&a>=Mo;!n||s?(s&&e.activeFormattingElements.removeEntry(n),e.openElements.remove(o)):(o=Bo(e,n),r===t&&(e.activeFormattingElements.bookmark=n),e.treeAdapter.detachNode(r),e.treeAdapter.appendChild(o,r),r=o)}return r}function Bo(e,t){let n=e.treeAdapter.getNamespaceURI(t.element),r=e.treeAdapter.createElement(t.token.tagName,n,t.token.attrs);return e.openElements.replace(t.element,r),t.element=r,r}function Vo(e,t,n){let r=Ta(e.treeAdapter.getTagName(t));if(e._isElementCausesFosterParenting(r))e._fosterParentElement(n);else{let i=e.treeAdapter.getNamespaceURI(t);r===J.TEMPLATE&&i===G.HTML&&(t=e.treeAdapter.getTemplateContent(t)),e.treeAdapter.appendChild(t,n)}}function Ho(e,t,n){let r=e.treeAdapter.getNamespaceURI(n.element),{token:i}=n,a=e.treeAdapter.createElement(i.tagName,r,i.attrs);e._adoptNodes(t,a),e.treeAdapter.appendChild(t,a),e.activeFormattingElements.insertElementAfterBookmark(a,i),e.activeFormattingElements.removeEntry(n),e.openElements.remove(n.element),e.openElements.insertAfter(t,a,i.tagID)}function Uo(e,t){for(let n=0;n<jo;n++){let n=Lo(e,t);if(!n)break;let r=Ro(e,n);if(!r)break;e.activeFormattingElements.bookmark=n;let i=zo(e,r,n.element),a=e.openElements.getCommonAncestor(n.element);e.treeAdapter.detachNode(i),a&&Vo(e,a,i),Ho(e,r,n)}}function Wo(e,t){e._appendCommentNode(t,e.openElements.currentTmplContentOrNode)}function Go(e,t){e._appendCommentNode(t,e.openElements.items[0])}function Ko(e,t){e._appendCommentNode(t,e.document)}function qo(e,t){if(e.stopped=!0,t.location){let n=e.fragmentContext?0:2;for(let r=e.openElements.stackTop;r>=n;r--)e._setEndLocation(e.openElements.items[r],t);if(!e.fragmentContext&&e.openElements.stackTop>=0){let n=e.openElements.items[0],r=e.treeAdapter.getNodeSourceCodeLocation(n);if(r&&!r.endTag&&(e._setEndLocation(n,t),e.openElements.stackTop>=1)){let n=e.openElements.items[1],r=e.treeAdapter.getNodeSourceCodeLocation(n);r&&!r.endTag&&e._setEndLocation(n,t)}}}}function Jo(e,t){e._setDocumentType(t);let n=t.forceQuirks?K.QUIRKS:mo(t);po(t)||e._err(t,U.nonConformingDoctype),e.treeAdapter.setDocumentMode(e.document,n),e.insertionMode=Q.BEFORE_HTML}function Yo(e,t){e._err(t,U.missingDoctype,!0),e.treeAdapter.setDocumentMode(e.document,K.QUIRKS),e.insertionMode=Q.BEFORE_HTML,e._processToken(t)}function Xo(e,t){t.tagID===J.HTML?(e._insertElement(t,G.HTML),e.insertionMode=Q.BEFORE_HEAD):Qo(e,t)}function Zo(e,t){let n=t.tagID;(n===J.HTML||n===J.HEAD||n===J.BODY||n===J.BR)&&Qo(e,t)}function Qo(e,t){e._insertFakeRootElement(),e.insertionMode=Q.BEFORE_HEAD,e._processToken(t)}function $o(e,t){switch(t.tagID){case J.HTML:$(e,t);break;case J.HEAD:e._insertElement(t,G.HTML),e.headElement=e.openElements.current,e.insertionMode=Q.IN_HEAD;break;default:ts(e,t)}}function es(e,t){let n=t.tagID;n===J.HEAD||n===J.BODY||n===J.HTML||n===J.BR?ts(e,t):e._err(t,U.endTagWithoutMatchingOpenElement)}function ts(e,t){e._insertFakeElement(q.HEAD,J.HEAD),e.headElement=e.openElements.current,e.insertionMode=Q.IN_HEAD,e._processToken(t)}function ns(e,t){switch(t.tagID){case J.HTML:$(e,t);break;case J.BASE:case J.BASEFONT:case J.BGSOUND:case J.LINK:case J.META:e._appendElement(t,G.HTML),t.ackSelfClosing=!0;break;case J.TITLE:e._switchToTextParsing(t,Z.RCDATA);break;case J.NOSCRIPT:e.options.scriptingEnabled?e._switchToTextParsing(t,Z.RAWTEXT):(e._insertElement(t,G.HTML),e.insertionMode=Q.IN_HEAD_NO_SCRIPT);break;case J.NOFRAMES:case J.STYLE:e._switchToTextParsing(t,Z.RAWTEXT);break;case J.SCRIPT:e._switchToTextParsing(t,Z.SCRIPT_DATA);break;case J.TEMPLATE:e._insertTemplate(t),e.activeFormattingElements.insertMarker(),e.framesetOk=!1,e.insertionMode=Q.IN_TEMPLATE,e.tmplInsertionModeStack.unshift(Q.IN_TEMPLATE);break;case J.HEAD:e._err(t,U.misplacedStartTagForHeadElement);break;default:as(e,t)}}function rs(e,t){switch(t.tagID){case J.HEAD:e.openElements.pop(),e.insertionMode=Q.AFTER_HEAD;break;case J.BODY:case J.BR:case J.HTML:as(e,t);break;case J.TEMPLATE:is(e,t);break;default:e._err(t,U.endTagWithoutMatchingOpenElement)}}function is(e,t){e.openElements.tmplCount>0?(e.openElements.generateImpliedEndTagsThoroughly(),e.openElements.currentTagId!==J.TEMPLATE&&e._err(t,U.closingOfElementWithOpenChildElements),e.openElements.popUntilTagNamePopped(J.TEMPLATE),e.activeFormattingElements.clearToLastMarker(),e.tmplInsertionModeStack.shift(),e._resetInsertionMode()):e._err(t,U.endTagWithoutMatchingOpenElement)}function as(e,t){e.openElements.pop(),e.insertionMode=Q.AFTER_HEAD,e._processToken(t)}function os(e,t){switch(t.tagID){case J.HTML:$(e,t);break;case J.BASEFONT:case J.BGSOUND:case J.HEAD:case J.LINK:case J.META:case J.NOFRAMES:case J.STYLE:ns(e,t);break;case J.NOSCRIPT:e._err(t,U.nestedNoscriptInHead);break;default:cs(e,t)}}function ss(e,t){switch(t.tagID){case J.NOSCRIPT:e.openElements.pop(),e.insertionMode=Q.IN_HEAD;break;case J.BR:cs(e,t);break;default:e._err(t,U.endTagWithoutMatchingOpenElement)}}function cs(e,t){let n=t.type===W.EOF?U.openElementsLeftAfterEof:U.disallowedContentInNoscriptInHead;e._err(t,n),e.openElements.pop(),e.insertionMode=Q.IN_HEAD,e._processToken(t)}function ls(e,t){switch(t.tagID){case J.HTML:$(e,t);break;case J.BODY:e._insertElement(t,G.HTML),e.framesetOk=!1,e.insertionMode=Q.IN_BODY;break;case J.FRAMESET:e._insertElement(t,G.HTML),e.insertionMode=Q.IN_FRAMESET;break;case J.BASE:case J.BASEFONT:case J.BGSOUND:case J.LINK:case J.META:case J.NOFRAMES:case J.SCRIPT:case J.STYLE:case J.TEMPLATE:case J.TITLE:e._err(t,U.abandonedHeadElementChild),e.openElements.push(e.headElement,J.HEAD),ns(e,t),e.openElements.remove(e.headElement);break;case J.HEAD:e._err(t,U.misplacedStartTagForHeadElement);break;default:ds(e,t)}}function us(e,t){switch(t.tagID){case J.BODY:case J.HTML:case J.BR:ds(e,t);break;case J.TEMPLATE:is(e,t);break;default:e._err(t,U.endTagWithoutMatchingOpenElement)}}function ds(e,t){e._insertFakeElement(q.BODY,J.BODY),e.insertionMode=Q.IN_BODY,fs(e,t)}function fs(e,t){switch(t.type){case W.CHARACTER:ms(e,t);break;case W.WHITESPACE_CHARACTER:ps(e,t);break;case W.COMMENT:Wo(e,t);break;case W.START_TAG:$(e,t);break;case W.END_TAG:ic(e,t);break;case W.EOF:ac(e,t);break;default:}}function ps(e,t){e._reconstructActiveFormattingElements(),e._insertCharacters(t)}function ms(e,t){e._reconstructActiveFormattingElements(),e._insertCharacters(t),e.framesetOk=!1}function hs(e,t){e.openElements.tmplCount===0&&e.treeAdapter.adoptAttributes(e.openElements.items[0],t.attrs)}function gs(e,t){let n=e.openElements.tryPeekProperlyNestedBodyElement();n&&e.openElements.tmplCount===0&&(e.framesetOk=!1,e.treeAdapter.adoptAttributes(n,t.attrs))}function _s(e,t){let n=e.openElements.tryPeekProperlyNestedBodyElement();e.framesetOk&&n&&(e.treeAdapter.detachNode(n),e.openElements.popAllUpToHtmlElement(),e._insertElement(t,G.HTML),e.insertionMode=Q.IN_FRAMESET)}function vs(e,t){e.openElements.hasInButtonScope(J.P)&&e._closePElement(),e._insertElement(t,G.HTML)}function ys(e,t){e.openElements.hasInButtonScope(J.P)&&e._closePElement(),e.openElements.currentTagId!==void 0&&Da.has(e.openElements.currentTagId)&&e.openElements.pop(),e._insertElement(t,G.HTML)}function bs(e,t){e.openElements.hasInButtonScope(J.P)&&e._closePElement(),e._insertElement(t,G.HTML),e.skipNextNewLine=!0,e.framesetOk=!1}function xs(e,t){let n=e.openElements.tmplCount>0;(!e.formElement||n)&&(e.openElements.hasInButtonScope(J.P)&&e._closePElement(),e._insertElement(t,G.HTML),n||(e.formElement=e.openElements.current))}function Ss(e,t){e.framesetOk=!1;let n=t.tagID;for(let t=e.openElements.stackTop;t>=0;t--){let r=e.openElements.tagIDs[t];if(n===J.LI&&r===J.LI||(n===J.DD||n===J.DT)&&(r===J.DD||r===J.DT)){e.openElements.generateImpliedEndTagsWithExclusion(r),e.openElements.popUntilTagNamePopped(r);break}if(r!==J.ADDRESS&&r!==J.DIV&&r!==J.P&&e._isSpecialElement(e.openElements.items[t],r))break}e.openElements.hasInButtonScope(J.P)&&e._closePElement(),e._insertElement(t,G.HTML)}function Cs(e,t){e.openElements.hasInButtonScope(J.P)&&e._closePElement(),e._insertElement(t,G.HTML),e.tokenizer.state=Z.PLAINTEXT}function ws(e,t){e.openElements.hasInScope(J.BUTTON)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(J.BUTTON)),e._reconstructActiveFormattingElements(),e._insertElement(t,G.HTML),e.framesetOk=!1}function Ts(e,t){let n=e.activeFormattingElements.getElementEntryInScopeWithTagName(q.A);n&&(Uo(e,t),e.openElements.remove(n.element),e.activeFormattingElements.removeEntry(n)),e._reconstructActiveFormattingElements(),e._insertElement(t,G.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t)}function Es(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,G.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t)}function Ds(e,t){e._reconstructActiveFormattingElements(),e.openElements.hasInScope(J.NOBR)&&(Uo(e,t),e._reconstructActiveFormattingElements()),e._insertElement(t,G.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t)}function Os(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,G.HTML),e.activeFormattingElements.insertMarker(),e.framesetOk=!1}function ks(e,t){e.treeAdapter.getDocumentMode(e.document)!==K.QUIRKS&&e.openElements.hasInButtonScope(J.P)&&e._closePElement(),e._insertElement(t,G.HTML),e.framesetOk=!1,e.insertionMode=Q.IN_TABLE}function As(e,t){e._reconstructActiveFormattingElements(),e._appendElement(t,G.HTML),e.framesetOk=!1,t.ackSelfClosing=!0}function js(e){let t=Sa(e,Ca.TYPE);return t!=null&&t.toLowerCase()===Ao}function Ms(e,t){e._reconstructActiveFormattingElements(),e._appendElement(t,G.HTML),js(t)||(e.framesetOk=!1),t.ackSelfClosing=!0}function Ns(e,t){e._appendElement(t,G.HTML),t.ackSelfClosing=!0}function Ps(e,t){e.openElements.hasInButtonScope(J.P)&&e._closePElement(),e._appendElement(t,G.HTML),e.framesetOk=!1,t.ackSelfClosing=!0}function Fs(e,t){t.tagName=q.IMG,t.tagID=J.IMG,As(e,t)}function Is(e,t){e._insertElement(t,G.HTML),e.skipNextNewLine=!0,e.tokenizer.state=Z.RCDATA,e.originalInsertionMode=e.insertionMode,e.framesetOk=!1,e.insertionMode=Q.TEXT}function Ls(e,t){e.openElements.hasInButtonScope(J.P)&&e._closePElement(),e._reconstructActiveFormattingElements(),e.framesetOk=!1,e._switchToTextParsing(t,Z.RAWTEXT)}function Rs(e,t){e.framesetOk=!1,e._switchToTextParsing(t,Z.RAWTEXT)}function zs(e,t){e._switchToTextParsing(t,Z.RAWTEXT)}function Bs(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,G.HTML),e.framesetOk=!1,e.insertionMode=e.insertionMode===Q.IN_TABLE||e.insertionMode===Q.IN_CAPTION||e.insertionMode===Q.IN_TABLE_BODY||e.insertionMode===Q.IN_ROW||e.insertionMode===Q.IN_CELL?Q.IN_SELECT_IN_TABLE:Q.IN_SELECT}function Vs(e,t){e.openElements.currentTagId===J.OPTION&&e.openElements.pop(),e._reconstructActiveFormattingElements(),e._insertElement(t,G.HTML)}function Hs(e,t){e.openElements.hasInScope(J.RUBY)&&e.openElements.generateImpliedEndTags(),e._insertElement(t,G.HTML)}function Us(e,t){e.openElements.hasInScope(J.RUBY)&&e.openElements.generateImpliedEndTagsWithExclusion(J.RTC),e._insertElement(t,G.HTML)}function Ws(e,t){e._reconstructActiveFormattingElements(),Co(t),To(t),t.selfClosing?e._appendElement(t,G.MATHML):e._insertElement(t,G.MATHML),t.ackSelfClosing=!0}function Gs(e,t){e._reconstructActiveFormattingElements(),wo(t),To(t),t.selfClosing?e._appendElement(t,G.SVG):e._insertElement(t,G.SVG),t.ackSelfClosing=!0}function Ks(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,G.HTML)}function $(e,t){switch(t.tagID){case J.I:case J.S:case J.B:case J.U:case J.EM:case J.TT:case J.BIG:case J.CODE:case J.FONT:case J.SMALL:case J.STRIKE:case J.STRONG:Es(e,t);break;case J.A:Ts(e,t);break;case J.H1:case J.H2:case J.H3:case J.H4:case J.H5:case J.H6:ys(e,t);break;case J.P:case J.DL:case J.OL:case J.UL:case J.DIV:case J.DIR:case J.NAV:case J.MAIN:case J.MENU:case J.ASIDE:case J.CENTER:case J.FIGURE:case J.FOOTER:case J.HEADER:case J.HGROUP:case J.DIALOG:case J.DETAILS:case J.ADDRESS:case J.ARTICLE:case J.SEARCH:case J.SECTION:case J.SUMMARY:case J.FIELDSET:case J.BLOCKQUOTE:case J.FIGCAPTION:vs(e,t);break;case J.LI:case J.DD:case J.DT:Ss(e,t);break;case J.BR:case J.IMG:case J.WBR:case J.AREA:case J.EMBED:case J.KEYGEN:As(e,t);break;case J.HR:Ps(e,t);break;case J.RB:case J.RTC:Hs(e,t);break;case J.RT:case J.RP:Us(e,t);break;case J.PRE:case J.LISTING:bs(e,t);break;case J.XMP:Ls(e,t);break;case J.SVG:Gs(e,t);break;case J.HTML:hs(e,t);break;case J.BASE:case J.LINK:case J.META:case J.STYLE:case J.TITLE:case J.SCRIPT:case J.BGSOUND:case J.BASEFONT:case J.TEMPLATE:ns(e,t);break;case J.BODY:gs(e,t);break;case J.FORM:xs(e,t);break;case J.NOBR:Ds(e,t);break;case J.MATH:Ws(e,t);break;case J.TABLE:ks(e,t);break;case J.INPUT:Ms(e,t);break;case J.PARAM:case J.TRACK:case J.SOURCE:Ns(e,t);break;case J.IMAGE:Fs(e,t);break;case J.BUTTON:ws(e,t);break;case J.APPLET:case J.OBJECT:case J.MARQUEE:Os(e,t);break;case J.IFRAME:Rs(e,t);break;case J.SELECT:Bs(e,t);break;case J.OPTION:case J.OPTGROUP:Vs(e,t);break;case J.NOEMBED:case J.NOFRAMES:zs(e,t);break;case J.FRAMESET:_s(e,t);break;case J.TEXTAREA:Is(e,t);break;case J.NOSCRIPT:e.options.scriptingEnabled?zs(e,t):Ks(e,t);break;case J.PLAINTEXT:Cs(e,t);break;case J.COL:case J.TH:case J.TD:case J.TR:case J.HEAD:case J.FRAME:case J.TBODY:case J.TFOOT:case J.THEAD:case J.CAPTION:case J.COLGROUP:break;default:Ks(e,t)}}function qs(e,t){if(e.openElements.hasInScope(J.BODY)&&(e.insertionMode=Q.AFTER_BODY,e.options.sourceCodeLocationInfo)){let n=e.openElements.tryPeekProperlyNestedBodyElement();n&&e._setEndLocation(n,t)}}function Js(e,t){e.openElements.hasInScope(J.BODY)&&(e.insertionMode=Q.AFTER_BODY,Uc(e,t))}function Ys(e,t){let n=t.tagID;e.openElements.hasInScope(n)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(n))}function Xs(e){let t=e.openElements.tmplCount>0,{formElement:n}=e;t||(e.formElement=null),(n||t)&&e.openElements.hasInScope(J.FORM)&&(e.openElements.generateImpliedEndTags(),t?e.openElements.popUntilTagNamePopped(J.FORM):n&&e.openElements.remove(n))}function Zs(e){e.openElements.hasInButtonScope(J.P)||e._insertFakeElement(q.P,J.P),e._closePElement()}function Qs(e){e.openElements.hasInListItemScope(J.LI)&&(e.openElements.generateImpliedEndTagsWithExclusion(J.LI),e.openElements.popUntilTagNamePopped(J.LI))}function $s(e,t){let n=t.tagID;e.openElements.hasInScope(n)&&(e.openElements.generateImpliedEndTagsWithExclusion(n),e.openElements.popUntilTagNamePopped(n))}function ec(e){e.openElements.hasNumberedHeaderInScope()&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilNumberedHeaderPopped())}function tc(e,t){let n=t.tagID;e.openElements.hasInScope(n)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(n),e.activeFormattingElements.clearToLastMarker())}function nc(e){e._reconstructActiveFormattingElements(),e._insertFakeElement(q.BR,J.BR),e.openElements.pop(),e.framesetOk=!1}function rc(e,t){let n=t.tagName,r=t.tagID;for(let t=e.openElements.stackTop;t>0;t--){let i=e.openElements.items[t],a=e.openElements.tagIDs[t];if(r===a&&(r!==J.UNKNOWN||e.treeAdapter.getTagName(i)===n)){e.openElements.generateImpliedEndTagsWithExclusion(r),e.openElements.stackTop>=t&&e.openElements.shortenToLength(t);break}if(e._isSpecialElement(i,a))break}}function ic(e,t){switch(t.tagID){case J.A:case J.B:case J.I:case J.S:case J.U:case J.EM:case J.TT:case J.BIG:case J.CODE:case J.FONT:case J.NOBR:case J.SMALL:case J.STRIKE:case J.STRONG:Uo(e,t);break;case J.P:Zs(e);break;case J.DL:case J.UL:case J.OL:case J.DIR:case J.DIV:case J.NAV:case J.PRE:case J.MAIN:case J.MENU:case J.ASIDE:case J.BUTTON:case J.CENTER:case J.FIGURE:case J.FOOTER:case J.HEADER:case J.HGROUP:case J.DIALOG:case J.ADDRESS:case J.ARTICLE:case J.DETAILS:case J.SEARCH:case J.SECTION:case J.SUMMARY:case J.LISTING:case J.FIELDSET:case J.BLOCKQUOTE:case J.FIGCAPTION:Ys(e,t);break;case J.LI:Qs(e);break;case J.DD:case J.DT:$s(e,t);break;case J.H1:case J.H2:case J.H3:case J.H4:case J.H5:case J.H6:ec(e);break;case J.BR:nc(e);break;case J.BODY:qs(e,t);break;case J.HTML:Js(e,t);break;case J.FORM:Xs(e);break;case J.APPLET:case J.OBJECT:case J.MARQUEE:tc(e,t);break;case J.TEMPLATE:is(e,t);break;default:rc(e,t)}}function ac(e,t){e.tmplInsertionModeStack.length>0?Vc(e,t):qo(e,t)}function oc(e,t){var n;t.tagID===J.SCRIPT&&((n=e.scriptHandler)==null||n.call(e,e.openElements.current)),e.openElements.pop(),e.insertionMode=e.originalInsertionMode}function sc(e,t){e._err(t,U.eofInElementThatCanContainOnlyText),e.openElements.pop(),e.insertionMode=e.originalInsertionMode,e.onEof(t)}function cc(e,t){if(e.openElements.currentTagId!==void 0&&Po.has(e.openElements.currentTagId))switch(e.pendingCharacterTokens.length=0,e.hasNonWhitespacePendingCharacterToken=!1,e.originalInsertionMode=e.insertionMode,e.insertionMode=Q.IN_TABLE_TEXT,t.type){case W.CHARACTER:xc(e,t);break;case W.WHITESPACE_CHARACTER:bc(e,t);break}else yc(e,t)}function lc(e,t){e.openElements.clearBackToTableContext(),e.activeFormattingElements.insertMarker(),e._insertElement(t,G.HTML),e.insertionMode=Q.IN_CAPTION}function uc(e,t){e.openElements.clearBackToTableContext(),e._insertElement(t,G.HTML),e.insertionMode=Q.IN_COLUMN_GROUP}function dc(e,t){e.openElements.clearBackToTableContext(),e._insertFakeElement(q.COLGROUP,J.COLGROUP),e.insertionMode=Q.IN_COLUMN_GROUP,Ec(e,t)}function fc(e,t){e.openElements.clearBackToTableContext(),e._insertElement(t,G.HTML),e.insertionMode=Q.IN_TABLE_BODY}function pc(e,t){e.openElements.clearBackToTableContext(),e._insertFakeElement(q.TBODY,J.TBODY),e.insertionMode=Q.IN_TABLE_BODY,kc(e,t)}function mc(e,t){e.openElements.hasInTableScope(J.TABLE)&&(e.openElements.popUntilTagNamePopped(J.TABLE),e._resetInsertionMode(),e._processStartTag(t))}function hc(e,t){js(t)?e._appendElement(t,G.HTML):yc(e,t),t.ackSelfClosing=!0}function gc(e,t){!e.formElement&&e.openElements.tmplCount===0&&(e._insertElement(t,G.HTML),e.formElement=e.openElements.current,e.openElements.pop())}function _c(e,t){switch(t.tagID){case J.TD:case J.TH:case J.TR:pc(e,t);break;case J.STYLE:case J.SCRIPT:case J.TEMPLATE:ns(e,t);break;case J.COL:dc(e,t);break;case J.FORM:gc(e,t);break;case J.TABLE:mc(e,t);break;case J.TBODY:case J.TFOOT:case J.THEAD:fc(e,t);break;case J.INPUT:hc(e,t);break;case J.CAPTION:lc(e,t);break;case J.COLGROUP:uc(e,t);break;default:yc(e,t)}}function vc(e,t){switch(t.tagID){case J.TABLE:e.openElements.hasInTableScope(J.TABLE)&&(e.openElements.popUntilTagNamePopped(J.TABLE),e._resetInsertionMode());break;case J.TEMPLATE:is(e,t);break;case J.BODY:case J.CAPTION:case J.COL:case J.COLGROUP:case J.HTML:case J.TBODY:case J.TD:case J.TFOOT:case J.TH:case J.THEAD:case J.TR:break;default:yc(e,t)}}function yc(e,t){let n=e.fosterParentingEnabled;e.fosterParentingEnabled=!0,fs(e,t),e.fosterParentingEnabled=n}function bc(e,t){e.pendingCharacterTokens.push(t)}function xc(e,t){e.pendingCharacterTokens.push(t),e.hasNonWhitespacePendingCharacterToken=!0}function Sc(e,t){let n=0;if(e.hasNonWhitespacePendingCharacterToken)for(;n<e.pendingCharacterTokens.length;n++)yc(e,e.pendingCharacterTokens[n]);else for(;n<e.pendingCharacterTokens.length;n++)e._insertCharacters(e.pendingCharacterTokens[n]);e.insertionMode=e.originalInsertionMode,e._processToken(t)}var Cc=new Set([J.CAPTION,J.COL,J.COLGROUP,J.TBODY,J.TD,J.TFOOT,J.TH,J.THEAD,J.TR]);function wc(e,t){let n=t.tagID;Cc.has(n)?e.openElements.hasInTableScope(J.CAPTION)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(J.CAPTION),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=Q.IN_TABLE,_c(e,t)):$(e,t)}function Tc(e,t){let n=t.tagID;switch(n){case J.CAPTION:case J.TABLE:e.openElements.hasInTableScope(J.CAPTION)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(J.CAPTION),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=Q.IN_TABLE,n===J.TABLE&&vc(e,t));break;case J.BODY:case J.COL:case J.COLGROUP:case J.HTML:case J.TBODY:case J.TD:case J.TFOOT:case J.TH:case J.THEAD:case J.TR:break;default:ic(e,t)}}function Ec(e,t){switch(t.tagID){case J.HTML:$(e,t);break;case J.COL:e._appendElement(t,G.HTML),t.ackSelfClosing=!0;break;case J.TEMPLATE:ns(e,t);break;default:Oc(e,t)}}function Dc(e,t){switch(t.tagID){case J.COLGROUP:e.openElements.currentTagId===J.COLGROUP&&(e.openElements.pop(),e.insertionMode=Q.IN_TABLE);break;case J.TEMPLATE:is(e,t);break;case J.COL:break;default:Oc(e,t)}}function Oc(e,t){e.openElements.currentTagId===J.COLGROUP&&(e.openElements.pop(),e.insertionMode=Q.IN_TABLE,e._processToken(t))}function kc(e,t){switch(t.tagID){case J.TR:e.openElements.clearBackToTableBodyContext(),e._insertElement(t,G.HTML),e.insertionMode=Q.IN_ROW;break;case J.TH:case J.TD:e.openElements.clearBackToTableBodyContext(),e._insertFakeElement(q.TR,J.TR),e.insertionMode=Q.IN_ROW,jc(e,t);break;case J.CAPTION:case J.COL:case J.COLGROUP:case J.TBODY:case J.TFOOT:case J.THEAD:e.openElements.hasTableBodyContextInTableScope()&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=Q.IN_TABLE,_c(e,t));break;default:_c(e,t)}}function Ac(e,t){let n=t.tagID;switch(t.tagID){case J.TBODY:case J.TFOOT:case J.THEAD:e.openElements.hasInTableScope(n)&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=Q.IN_TABLE);break;case J.TABLE:e.openElements.hasTableBodyContextInTableScope()&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=Q.IN_TABLE,vc(e,t));break;case J.BODY:case J.CAPTION:case J.COL:case J.COLGROUP:case J.HTML:case J.TD:case J.TH:case J.TR:break;default:vc(e,t)}}function jc(e,t){switch(t.tagID){case J.TH:case J.TD:e.openElements.clearBackToTableRowContext(),e._insertElement(t,G.HTML),e.insertionMode=Q.IN_CELL,e.activeFormattingElements.insertMarker();break;case J.CAPTION:case J.COL:case J.COLGROUP:case J.TBODY:case J.TFOOT:case J.THEAD:case J.TR:e.openElements.hasInTableScope(J.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=Q.IN_TABLE_BODY,kc(e,t));break;default:_c(e,t)}}function Mc(e,t){switch(t.tagID){case J.TR:e.openElements.hasInTableScope(J.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=Q.IN_TABLE_BODY);break;case J.TABLE:e.openElements.hasInTableScope(J.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=Q.IN_TABLE_BODY,Ac(e,t));break;case J.TBODY:case J.TFOOT:case J.THEAD:(e.openElements.hasInTableScope(t.tagID)||e.openElements.hasInTableScope(J.TR))&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=Q.IN_TABLE_BODY,Ac(e,t));break;case J.BODY:case J.CAPTION:case J.COL:case J.COLGROUP:case J.HTML:case J.TD:case J.TH:break;default:vc(e,t)}}function Nc(e,t){let n=t.tagID;Cc.has(n)?(e.openElements.hasInTableScope(J.TD)||e.openElements.hasInTableScope(J.TH))&&(e._closeTableCell(),jc(e,t)):$(e,t)}function Pc(e,t){let n=t.tagID;switch(n){case J.TD:case J.TH:e.openElements.hasInTableScope(n)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(n),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=Q.IN_ROW);break;case J.TABLE:case J.TBODY:case J.TFOOT:case J.THEAD:case J.TR:e.openElements.hasInTableScope(n)&&(e._closeTableCell(),Mc(e,t));break;case J.BODY:case J.CAPTION:case J.COL:case J.COLGROUP:case J.HTML:break;default:ic(e,t)}}function Fc(e,t){switch(t.tagID){case J.HTML:$(e,t);break;case J.OPTION:e.openElements.currentTagId===J.OPTION&&e.openElements.pop(),e._insertElement(t,G.HTML);break;case J.OPTGROUP:e.openElements.currentTagId===J.OPTION&&e.openElements.pop(),e.openElements.currentTagId===J.OPTGROUP&&e.openElements.pop(),e._insertElement(t,G.HTML);break;case J.HR:e.openElements.currentTagId===J.OPTION&&e.openElements.pop(),e.openElements.currentTagId===J.OPTGROUP&&e.openElements.pop(),e._appendElement(t,G.HTML),t.ackSelfClosing=!0;break;case J.INPUT:case J.KEYGEN:case J.TEXTAREA:case J.SELECT:e.openElements.hasInSelectScope(J.SELECT)&&(e.openElements.popUntilTagNamePopped(J.SELECT),e._resetInsertionMode(),t.tagID!==J.SELECT&&e._processStartTag(t));break;case J.SCRIPT:case J.TEMPLATE:ns(e,t);break;default:}}function Ic(e,t){switch(t.tagID){case J.OPTGROUP:e.openElements.stackTop>0&&e.openElements.currentTagId===J.OPTION&&e.openElements.tagIDs[e.openElements.stackTop-1]===J.OPTGROUP&&e.openElements.pop(),e.openElements.currentTagId===J.OPTGROUP&&e.openElements.pop();break;case J.OPTION:e.openElements.currentTagId===J.OPTION&&e.openElements.pop();break;case J.SELECT:e.openElements.hasInSelectScope(J.SELECT)&&(e.openElements.popUntilTagNamePopped(J.SELECT),e._resetInsertionMode());break;case J.TEMPLATE:is(e,t);break;default:}}function Lc(e,t){let n=t.tagID;n===J.CAPTION||n===J.TABLE||n===J.TBODY||n===J.TFOOT||n===J.THEAD||n===J.TR||n===J.TD||n===J.TH?(e.openElements.popUntilTagNamePopped(J.SELECT),e._resetInsertionMode(),e._processStartTag(t)):Fc(e,t)}function Rc(e,t){let n=t.tagID;n===J.CAPTION||n===J.TABLE||n===J.TBODY||n===J.TFOOT||n===J.THEAD||n===J.TR||n===J.TD||n===J.TH?e.openElements.hasInTableScope(n)&&(e.openElements.popUntilTagNamePopped(J.SELECT),e._resetInsertionMode(),e.onEndTag(t)):Ic(e,t)}function zc(e,t){switch(t.tagID){case J.BASE:case J.BASEFONT:case J.BGSOUND:case J.LINK:case J.META:case J.NOFRAMES:case J.SCRIPT:case J.STYLE:case J.TEMPLATE:case J.TITLE:ns(e,t);break;case J.CAPTION:case J.COLGROUP:case J.TBODY:case J.TFOOT:case J.THEAD:e.tmplInsertionModeStack[0]=Q.IN_TABLE,e.insertionMode=Q.IN_TABLE,_c(e,t);break;case J.COL:e.tmplInsertionModeStack[0]=Q.IN_COLUMN_GROUP,e.insertionMode=Q.IN_COLUMN_GROUP,Ec(e,t);break;case J.TR:e.tmplInsertionModeStack[0]=Q.IN_TABLE_BODY,e.insertionMode=Q.IN_TABLE_BODY,kc(e,t);break;case J.TD:case J.TH:e.tmplInsertionModeStack[0]=Q.IN_ROW,e.insertionMode=Q.IN_ROW,jc(e,t);break;default:e.tmplInsertionModeStack[0]=Q.IN_BODY,e.insertionMode=Q.IN_BODY,$(e,t)}}function Bc(e,t){t.tagID===J.TEMPLATE&&is(e,t)}function Vc(e,t){e.openElements.tmplCount>0?(e.openElements.popUntilTagNamePopped(J.TEMPLATE),e.activeFormattingElements.clearToLastMarker(),e.tmplInsertionModeStack.shift(),e._resetInsertionMode(),e.onEof(t)):qo(e,t)}function Hc(e,t){t.tagID===J.HTML?$(e,t):Wc(e,t)}function Uc(e,t){if(t.tagID===J.HTML){if(e.fragmentContext||(e.insertionMode=Q.AFTER_AFTER_BODY),e.options.sourceCodeLocationInfo&&e.openElements.tagIDs[0]===J.HTML){e._setEndLocation(e.openElements.items[0],t);let n=e.openElements.items[1];n&&!e.treeAdapter.getNodeSourceCodeLocation(n)?.endTag&&e._setEndLocation(n,t)}}else Wc(e,t)}function Wc(e,t){e.insertionMode=Q.IN_BODY,fs(e,t)}function Gc(e,t){switch(t.tagID){case J.HTML:$(e,t);break;case J.FRAMESET:e._insertElement(t,G.HTML);break;case J.FRAME:e._appendElement(t,G.HTML),t.ackSelfClosing=!0;break;case J.NOFRAMES:ns(e,t);break;default:}}function Kc(e,t){t.tagID===J.FRAMESET&&!e.openElements.isRootHtmlElementCurrent()&&(e.openElements.pop(),!e.fragmentContext&&e.openElements.currentTagId!==J.FRAMESET&&(e.insertionMode=Q.AFTER_FRAMESET))}function qc(e,t){switch(t.tagID){case J.HTML:$(e,t);break;case J.NOFRAMES:ns(e,t);break;default:}}function Jc(e,t){t.tagID===J.HTML&&(e.insertionMode=Q.AFTER_AFTER_FRAMESET)}function Yc(e,t){t.tagID===J.HTML?$(e,t):Xc(e,t)}function Xc(e,t){e.insertionMode=Q.IN_BODY,fs(e,t)}function Zc(e,t){switch(t.tagID){case J.HTML:$(e,t);break;case J.NOFRAMES:ns(e,t);break;default:}}function Qc(e,t){t.chars=`�`,e._insertCharacters(t)}function $c(e,t){e._insertCharacters(t),e.framesetOk=!1}function el(e){for(;e.treeAdapter.getNamespaceURI(e.openElements.current)!==G.HTML&&e.openElements.currentTagId!==void 0&&!e._isIntegrationPoint(e.openElements.currentTagId,e.openElements.current);)e.openElements.pop()}function tl(e,t){if(So(t))el(e),e._startTagOutsideForeignContent(t);else{let n=e._getAdjustedCurrentElement(),r=e.treeAdapter.getNamespaceURI(n);r===G.MATHML?Co(t):r===G.SVG&&(Eo(t),wo(t)),To(t),t.selfClosing?e._appendElement(t,r):e._insertElement(t,r),t.ackSelfClosing=!0}}function nl(e,t){if(t.tagID===J.P||t.tagID===J.BR){el(e),e._endTagOutsideForeignContent(t);return}for(let n=e.openElements.stackTop;n>0;n--){let r=e.openElements.items[n];if(e.treeAdapter.getNamespaceURI(r)===G.HTML){e._endTagOutsideForeignContent(t);break}let i=e.treeAdapter.getTagName(r);if(i.toLowerCase()===t.tagName){t.tagName=i,e.openElements.shortenToLength(n);break}}}var rl=new Set([q.AREA,q.BASE,q.BASEFONT,q.BGSOUND,q.BR,q.COL,q.EMBED,q.FRAME,q.HR,q.IMG,q.INPUT,q.KEYGEN,q.LINK,q.META,q.PARAM,q.SOURCE,q.TRACK,q.WBR]);function il(e,t){return t.treeAdapter.isElementNode(e)&&t.treeAdapter.getNamespaceURI(e)===G.HTML&&rl.has(t.treeAdapter.getTagName(e))}var al={treeAdapter:no,scriptingEnabled:!0};function ol(e,t){let n={...al,...t};return il(e,n)?``:sl(e,n)}function sl(e,t){let n=``,r=t.treeAdapter.isElementNode(e)&&t.treeAdapter.getTagName(e)===q.TEMPLATE&&t.treeAdapter.getNamespaceURI(e)===G.HTML?t.treeAdapter.getTemplateContent(e):e,i=t.treeAdapter.getChildNodes(r);if(i)for(let e of i)n+=cl(e,t);return n}function cl(e,t){return t.treeAdapter.isElementNode(e)?ll(e,t):t.treeAdapter.isTextNode(e)?dl(e,t):t.treeAdapter.isCommentNode(e)?fl(e,t):t.treeAdapter.isDocumentTypeNode(e)?pl(e,t):``}function ll(e,t){let n=t.treeAdapter.getTagName(e);return`<${n}${ul(e,t)}>${il(e,t)?``:`${sl(e,t)}</${n}>`}`}function ul(e,{treeAdapter:t}){let n=``;for(let r of t.getAttrList(e)){if(n+=` `,r.namespace)switch(r.namespace){case G.XML:n+=`xml:${r.name}`;break;case G.XMLNS:r.name!==`xmlns`&&(n+=`xmlns:`),n+=r.name;break;case G.XLINK:n+=`xlink:${r.name}`;break;default:n+=`${r.prefix}:${r.name}`}else n+=r.name;n+=`="${fn(r.value)}"`}return n}function dl(e,t){let{treeAdapter:n}=t,r=n.getTextNodeContent(e),i=n.getParentNode(e),a=i&&n.isElementNode(i)&&n.getTagName(i);return a&&n.getNamespaceURI(i)===G.HTML&&ka(a,t.scriptingEnabled)?r:pn(r)}function fl(e,{treeAdapter:t}){return`<!--${t.getCommentNodeContent(e)}-->`}function pl(e,{treeAdapter:t}){return`<!DOCTYPE ${t.getDocumentTypeNodeName(e)}>`}function ml(e,t){return Io.parse(e,t)}function hl(e){return`attrs`in e&&`tagName`in e}function gl(e){return hl(e)&&e.nodeName===`template`}function _l(e,t,n){e.attrs=e.attrs.filter(e=>e.name!==t),n!==void 0&&e.attrs.push({name:t,value:n})}function vl(e){if(hl(e)){_l(e,Ht),_l(e,Bt);let t=e.sourceCodeLocation;t&&(_l(e,Ht,String(t.startLine)),_l(e,Bt,String(t.endLine)))}if(`childNodes`in e)for(let t of e.childNodes)vl(t);gl(e)&&vl(e.content)}function yl(e){let t=ml(e,{sourceCodeLocationInfo:!0});vl(t);let n=t.childNodes.find(e=>hl(e)&&e.tagName===`html`);return n&&_l(n,zt,String(Lt(e))),ol(t)}var bl=[[`img`,`src`],[`script`,`src`],[`link[rel~="stylesheet" i]`,`href`],[`link[rel~="icon" i]`,`href`],[`source`,`src`],[`video`,`src`],[`video`,`poster`],[`audio`,`src`]],xl=[`img[srcset]`,`source[srcset]`],Sl=20*1024*1024;async function Cl(e,t,n,r,i,a,o,s){let c=new DOMParser().parseFromString(yl(n),`text/html`);if(i!==void 0){let e=c.createElement(`style`);e.textContent=`:where(html) { font-size: ${i}px; }`;let t=c.head??c.documentElement;t.insertBefore(e,t.firstChild)}ua(c)&&await wl(c);let l=[];for(let[n,i]of bl)for(let o of c.querySelectorAll(n)){let n=lt(t,o.getAttribute(i)??``);n&&(o.removeAttribute(i),l.push(Tl(e,n,r,a).then(e=>{e&&o.setAttribute(i,e)})))}for(let n of xl)for(let i of c.querySelectorAll(n)){let n=ut(i.getAttribute(`srcset`)??``),o=n.map(({ref:e})=>lt(t,e));o.some(e=>e!==null)&&(i.removeAttribute(`srcset`),l.push(Promise.all(n.map(async(t,n)=>{let i=o[n];if(!i)return t;let s=await Tl(e,i,r,a);return s?{...t,ref:s}:null})).then(e=>{let t=e.filter(e=>e!==null);t.length>0&&i.setAttribute(`srcset`,ot(t))})))}return await Promise.all(l),o&&Qi(c,o),s&&sa(c,s),`<!doctype html>${c.documentElement.outerHTML}`}async function wl(e){let{default:t}=await E(async()=>{let{default:e}=await import(`./_virtual_katex-inline-css-DN-_JSKR.js`);return{default:e}},[]),n=e.createElement(`style`);n.textContent=`${t}\n${nn}`,(e.head??e.documentElement).appendChild(n)}function Tl(e,t,n,r){let i=n.get(t);if(i)return i;let a=xi(e,t,r).then(async e=>e.size>Sl?null:`data:${El(t,e.type)};base64,${Dl(await e.arrayBuffer())}`).catch(()=>null);return n.set(t,a),a}function El(e,t){let n=(e.split(`/`).pop()??``).split(`.`).pop()?.toLowerCase()??``;return n===`css`?`text/css`:n===`js`||n===`mjs`?`text/javascript`:t!==``&&t!==`application/octet-stream`?t:`application/octet-stream`}function Dl(e){let t=new Uint8Array(e),n=``,r=32768;for(let e=0;e<t.length;e+=r)n+=String.fromCharCode(...t.subarray(e,e+r));return btoa(n)}function Ol({session:e,path:t,text:n,root:r,scrollDriver:i=!1,scrollReceiver:a=!1,scrollChannel:o=`profile`,focused:s=!0,onRevealSource:c,mobile:l=!1}){let u=Ft(`html`,[e,r,t]),[d,f]=(0,L.useState)(null),p=(0,L.useRef)(new Map),m=C().editorFontSize,h=(0,L.useRef)(null),[g]=(0,L.useState)(Ki),[_]=(0,L.useState)(Ki),v=Qe({shortcutEnabled:s,onFind:(e,t,n)=>ia(h.current?.contentWindow??null,_,e,t,n),onClear:()=>aa(h.current?.contentWindow??null,_),onCloseFocus:()=>h.current?.focus()}),y=(0,L.useMemo)(()=>({session:e,path:t,root:r}),[e,t,r]),b=(0,L.useMemo)(()=>Lt(n),[n]);return(0,L.useEffect)(()=>{let i=!1;return Cl(e,t,n,p.current,m,r,g,_).then(e=>{i||f(e)}),()=>{i=!0}},[e,t,n,m,r,g,_,l]),(0,L.useEffect)(()=>{let e=e=>{let t=ra(e,h.current?.contentWindow??null,_);t?.kind===`puddle-preview-find-open`?v.openFind():t?.kind===`puddle-preview-find-result`&&v.setResult(t)};return window.addEventListener(`message`,e),()=>window.removeEventListener(`message`,e)},[v.openFind,v.setResult,_]),(0,L.useEffect)(()=>{if(a)return Kn.subscribe(o,y,e=>{Xi(h.current?.contentWindow??null,g,e)})},[a,o,y,g]),(0,L.useEffect)(()=>{let e=e=>{let t=Ji(e,h.current?.contentWindow??null,g);if(t)if(t.layout&&(a||!t.scrolled)){let e=(a?Kn.get(o,y):void 0)??qn.get(u);if(e&&Xi(h.current?.contentWindow??null,g,e),i){let n=e??t;Kn.publish(o,y,n.ratio,n.sourceLine)}}else qn.set(u,{ratio:t.ratio,sourceLine:t.sourceLine,revision:0}),i&&Kn.publish(o,y,t.ratio,t.sourceLine);let n=c?Yi(e,h.current?.contentWindow??null,g):null;n&&c?.({line:ii(n.line,b)})};return window.addEventListener(`message`,e),()=>window.removeEventListener(`message`,e)},[i,a,o,y,g,c,b,u]),d===null?null:(0,R.jsxs)(`div`,{className:`relative size-full bg-paper`,children:[(0,R.jsx)(`iframe`,{ref:h,sandbox:`allow-scripts`,src:l?`/preview.html`:void 0,srcDoc:l?void 0:d,title:t,className:`size-full bg-paper`,onLoad:()=>{let e=h.current;l&&e&&!e.dataset.delivered&&(e.dataset.delivered=`true`,e.contentWindow?.postMessage({kind:`puddle-preview-document`,html:d},`*`));{let e=(a?Kn.get(o,y):void 0)??qn.get(u);e&&Xi(h.current?.contentWindow??null,g,e)}v.refresh()}},l?d:void 0),(0,R.jsx)(ri,{controls:v})]})}function kl({kind:e,...t}){return e===`notebook`?(0,R.jsx)(Ii,{...t}):e===`markdown`?(0,R.jsx)(Vi,{...t}):(0,R.jsx)(Ol,{...t})}function Al({session:e,path:t,kind:n,root:r,focused:i=!0,scrollDriver:a=!1,scrollReceiver:o=!1,scrollChannel:s=`profile`,onRevealSource:c,onRunCompilation:l,compilationRunning:u}){let{openFile:d}=ke(),f=or(e,t,null,r,{passive:n!==`notebook`,live:!0,focused:i}),p=f.model,m=(0,L.useSyncExternalStore)(n=>Pt(Nt(e,t,r),n),()=>p?.getValue()??null);return f.conflict&&f.conflict.phase!==`unresolved`?(0,R.jsx)(Vn,{session:e,path:t,buffer:f,focused:i}):m===null?(0,R.jsx)(`p`,{className:`p-6 text-sm text-fg-muted`,children:f.status===`loading`?`Loading…`:f.errorMessage??`This file cannot be previewed.`}):n===`notebook`?(0,R.jsx)(Ii,{session:e,path:t,root:r,text:m,focused:i,onOpenFile:t=>d(e,t,void 0,{...st(t)?{view:`preview`}:{},...r===void 0?{}:{root:r}}),onRun:l?()=>l(!0):void 0,running:u,onUndo:()=>{p?.undo()},onRedo:()=>{p?.redo()},onChange:e=>{let t=f.model;if(!t)return;let n=Yr(t.getValue(),e),r=t.getPositionAt(n.start),i=t.getPositionAt(n.end);t.pushStackElement(),t.pushEditOperations([],[{range:{startLineNumber:r.lineNumber,startColumn:r.column,endLineNumber:i.lineNumber,endColumn:i.column},text:n.text}],()=>null),t.pushStackElement()}}):(0,R.jsx)(kl,{session:e,path:t,kind:n,text:m,root:r,scrollDriver:a,scrollReceiver:o,scrollChannel:s,focused:i,onRevealSource:c,onOpenFile:t=>d(e,t,void 0,{...st(t)?{view:`preview`}:{},...r===void 0?{}:{root:r}})})}var jl={png:`image`,jpg:`image`,jpeg:`image`,gif:`image`,webp:`image`,bmp:`image`,ico:`image`,avif:`image`,svg:`image`,mp4:`video`,m4v:`video`,webm:`video`,mov:`video`,mkv:`video`,avi:`video`,mp3:`audio`,wav:`audio`,ogg:`audio`,m4a:`audio`,flac:`audio`,aac:`audio`,pdf:`pdf`};function Ml(e){let t=e.split(`/`).pop()??e,n=t.lastIndexOf(`.`);return n<=0?null:jl[t.slice(n+1).toLowerCase()]??null}var Nl=(0,L.lazy)(()=>E(()=>import(`./PdfViewer-DYmz05py.js`).then(e=>({default:e.PdfViewer})),__vite__mapDeps([13,1,2,3,6,8,7,14,10,15,16,17,18])));function Pl({session:e,path:t,kind:n,root:r,generatedBy:i,refreshKey:a,onRevealSource:o,readOnly:s=!1}){let{asset:c,error:l}=Ll(e,t,r,Ae(e,t,r),a);if(l)return(0,R.jsxs)(Fl,{children:[(0,R.jsx)(`p`,{className:`text-sm text-fg-secondary`,children:l}),!s&&(0,R.jsx)(Il,{session:e,path:t,root:r})]});if(!c)return(0,R.jsx)(Fl,{children:(0,R.jsx)(`span`,{className:`text-xs text-fg-muted`,children:`…`})});let{url:u,blob:d}=c;return n===`image`?(0,R.jsx)(Fl,{children:(0,R.jsx)(`img`,{src:u,alt:t,className:`max-h-full max-w-full object-contain`})}):n===`video`?(0,R.jsx)(Fl,{children:(0,R.jsx)(`video`,{src:u,controls:!0,className:`max-h-full max-w-full`})}):n===`audio`?(0,R.jsx)(Fl,{children:(0,R.jsx)(`audio`,{src:u,controls:!0,className:`w-full max-w-xl`})}):(0,R.jsx)(L.Suspense,{fallback:(0,R.jsx)(Fl,{children:(0,R.jsx)(`span`,{className:`text-xs text-fg-muted`,children:`Loading PDF…`})}),children:(0,R.jsx)(Nl,{blob:d,session:e,path:t,root:r,onRevealSource:!s&&zl(t,r,i)?o:void 0,onDownload:s?void 0:()=>void Rl(e,t,r)})})}function Fl({children:e}){return(0,R.jsx)(`div`,{className:`flex h-full w-full flex-col items-center justify-center gap-3 overflow-auto bg-ground p-4`,children:e})}function Il({session:e,path:t,root:n}){return(0,R.jsx)(`button`,{type:`button`,onClick:()=>void Rl(e,t,n),className:`rounded-md bg-elevated px-3 py-1.5 text-sm text-fg transition-colors hover:bg-border/70`,children:`Download`})}function Ll(e,t,n,r=0,i){let[a,o]=(0,L.useState)(null),[s,c]=(0,L.useState)(null);return(0,L.useEffect)(()=>{let r=null,i=!1;return o(null),c(null),xi(e,t,n).then(e=>{i||(r=URL.createObjectURL(e),o({url:r,blob:e}))}).catch(e=>{i||c(e instanceof Error?e.message:`Couldn’t load this file.`)}),()=>{i=!0,r&&URL.revokeObjectURL(r)}},[e,t,n,r,i]),{asset:a,error:s}}function Rl(e,t,n){return me(e,t,n).catch(e=>{I.error(e instanceof Error?e.message:`Download failed`)})}function zl(e,t,n){if(!t||!e.toLowerCase().endsWith(`.pdf`))return!1;if(n===`latex`)return!0;let r=t.replaceAll(`\\`,`/`).replaceAll(/\/{2,}/g,`/`);return`${r}/${e.replaceAll(`\\`,`/`)}`.includes(`/.puddle/latex/`)||/(?:^|\/)latex\/[a-f\d]{24}\/current\/?$/i.test(r)}function Bl({tab:e,reveal:t,focused:n,scrollDriver:r,scrollReceiver:i,scrollChannel:a,onRevealSource:o,onRevealCompiledSource:s,onRunCompilation:c,compilationRunning:l}){let u=ct(e),d=e.view===`preview`||e.view===`linked`||e.view===`locked`,f=e.view===`linked`||e.view===`locked`?`${e.view}:${e.session}:${e.root??``}:${e.path}`:at(e);if(u===`diff`)return(0,R.jsx)(Pr,{session:e.session,path:e.path,root:e.root,area:e.git_area,focused:n},at(e));if(u===`commit`&&e.sha)return(0,R.jsx)(Nr,{session:e.session,sha:e.sha,path:e.path,root:e.root},at(e));if(u===`external`&&e.root!==void 0){let u=Ml(e.path);if(u)return(0,R.jsx)(Pl,{session:e.session,path:e.path,kind:u,root:e.root,generatedBy:e.generated_by,onRevealSource:s},at(e));let p=d?st(e.path):null;return p?(0,R.jsx)(Al,{session:e.session,path:e.path,kind:p,onRunCompilation:e.generated_by?void 0:c,compilationRunning:l,root:e.root,focused:n,scrollDriver:r,scrollReceiver:i,scrollChannel:a,onRevealSource:o},f):(0,R.jsx)(br,{session:e.session,path:e.path,reveal:t,root:e.root,focused:n,scrollDriver:r,scrollReceiver:i,scrollChannel:a},at(e))}if(u===`untitled`)return(0,R.jsx)(Ir,{name:e.path},at(e));let p=Ml(e.path);if(p)return(0,R.jsx)(Pl,{session:e.session,path:e.path,kind:p,generatedBy:e.generated_by,onRevealSource:s},at(e));let m=d?st(e.path):null;return m?(0,R.jsx)(Al,{session:e.session,path:e.path,kind:m,onRunCompilation:e.generated_by?void 0:c,compilationRunning:l,focused:n,scrollDriver:r,scrollReceiver:i,scrollChannel:a,onRevealSource:o},f):(0,R.jsx)(br,{session:e.session,path:e.path,reveal:t,focused:n,scrollDriver:r,scrollReceiver:i,scrollChannel:a},at(e))}export{Bl as PaneEditorBody};
|