astrion-website/demo/static/dist/assets/main.js

437 lines
2.1 MiB
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/PersonalizationDrawer.js","assets/runtime-dom.esm-bundler.js","assets/FancyCheck.js","assets/_plugin-vue_export-helper.js","assets/FancyCheck.css","assets/useMarkdownRenderer.js","assets/PersonalizationDrawer.css","assets/ImagePicker.js","assets/ImagePicker.css","assets/ConversationReviewDialog.js","assets/ConversationReviewDialog.css","assets/SubAgentActivityDialog.js","assets/SubAgentActivityDialog.css","assets/BackgroundCommandDialog.js","assets/VersioningDialog.js","assets/VersioningDialog.css","assets/UserQuestionDialog.js","assets/UserQuestionDialog.css","assets/PlanApprovalDialog.js","assets/PlanApprovalDialog.css","assets/TutorialOverlay.js","assets/NewUserTutorialPrompt.js","assets/NewUserTutorialPrompt.css","assets/GoalProgressDialog.js","assets/GoalProgressDialog.css","assets/WorkflowDemoShell.js","assets/WorkflowDemoShell.css","assets/VirtualMonitorSurface.js","assets/PathAuthorizationDialog.js","assets/PathAuthorizationDialog.css"])))=>i.map(i=>d[i]);
var bF=Object.defineProperty;var MM=s=>{throw TypeError(s)};var _F=(s,e,t)=>e in s?bF(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var _e=(s,e,t)=>_F(s,typeof e!="symbol"?e+"":e,t),Dk=(s,e,t)=>e.has(s)||MM("Cannot "+t);var f=(s,e,t)=>(Dk(s,e,"read from private field"),t?t.call(s):e.get(s)),D=(s,e,t)=>e.has(s)?MM("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(s):e.set(s,t),x=(s,e,t,n)=>(Dk(s,e,"write to private field"),n?n.call(s,t):e.set(s,t),t),B=(s,e,t)=>(Dk(s,e,"access private method"),t);var xs=(s,e,t,n)=>({set _(i){x(s,e,i,t)},get _(){return f(s,e,n)}});import{l as ye,C as jv,D as iE,E as SF,G as m2,k as pe,H as rE,I as v2,J as y2,K as wF,L as kF,M as CF,x as mw,N as ft,O as TF,w as Xe,P as b2,a as xn,d as at,o as Cn,Q as xM,q as Qe,R as _2,S as AF,b as F,c as $,n as ke,g as E,y as Ke,t as ae,f as ge,s as Vt,F as Ie,r as tt,U as Vv,p as mi,V as S2,e as Wt,i as hn,W as EF,A as Ne,X as Sp,u as We,Y as MF,T as us,h as _v,z as Sv,j as sS,Z as xF,_ as IF,$ as RF,a0 as LF,a1 as PF,a2 as OF,a3 as br,m as w2,a4 as Xs,a5 as DF}from"./runtime-dom.esm-bundler.js";import{_ as Qt}from"./_plugin-vue_export-helper.js";import{P as vw,p as NF,a as BF,b as FF,r as k2,k as $F}from"./useMarkdownRenderer.js";import{F as HF}from"./FancyCheck.js";/*!
* pinia v3.0.4
* (c) 2025 Eduardo San Martin Morote
* @license MIT
*/let C2;const G0=s=>C2=s,T2=Symbol();function m1(s){return s&&typeof s=="object"&&Object.prototype.toString.call(s)==="[object Object]"&&typeof s.toJSON!="function"}var wv;(function(s){s.direct="direct",s.patchObject="patch object",s.patchFunction="patch function"})(wv||(wv={}));function UF(){const s=m2(!0),e=s.run(()=>pe({}));let t=[],n=[];const i=rE({install(r){G0(i),i._a=r,r.provide(T2,i),r.config.globalProperties.$pinia=i,n.forEach(o=>t.push(o)),n=[]},use(r){return this._a?t.push(r):n.push(r),this},_p:t,_a:null,_e:s,_s:new Map,state:e});return i}const A2=()=>{};function IM(s,e,t,n=A2){s.add(e);const i=()=>{s.delete(e)&&n()};return!t&&kF()&&CF(i),i}function Uf(s,...e){s.forEach(t=>{t(...e)})}const WF=s=>s(),RM=Symbol(),Nk=Symbol();function v1(s,e){s instanceof Map&&e instanceof Map?e.forEach((t,n)=>s.set(n,t)):s instanceof Set&&e instanceof Set&&e.forEach(s.add,s);for(const t in e){if(!e.hasOwnProperty(t))continue;const n=e[t],i=s[t];m1(i)&&m1(n)&&s.hasOwnProperty(t)&&!jv(n)&&!iE(n)?s[t]=v1(i,n):s[t]=n}return s}const zF=Symbol();function jF(s){return!m1(s)||!Object.prototype.hasOwnProperty.call(s,zF)}const{assign:zc}=Object;function VF(s){return!!(jv(s)&&s.effect)}function GF(s,e,t,n){const{state:i,actions:r,getters:o}=e,a=t.state.value[s];let c;function l(){a||(t.state.value[s]=i?i():{});const u=TF(t.state.value[s]);return zc(u,r,Object.keys(o||{}).reduce((h,d)=>(h[d]=rE(ye(()=>{G0(t);const p=t._s.get(s);return o[d].call(p,p)})),h),{}))}return c=E2(s,l,e,t,n,!0),c}function E2(s,e,t={},n,i,r){let o;const a=zc({actions:{}},t),c={deep:!0};let l,u,h=new Set,d=new Set,p;const m=n.state.value[s];!r&&!m&&(n.state.value[s]={});let v;function g(k){let A;l=u=!1,typeof k=="function"?(k(n.state.value[s]),A={type:wv.patchFunction,storeId:s,events:p}):(v1(n.state.value[s],k),A={type:wv.patchObject,payload:k,storeId:s,events:p});const M=v=Symbol();ft().then(()=>{v===M&&(l=!0)}),u=!0,Uf(h,A,n.state.value[s])}const y=r?function(){const{state:A}=t,M=A?A():{};this.$patch(R=>{zc(R,M)})}:A2;function b(){o.stop(),h.clear(),d.clear(),n._s.delete(s)}const _=(k,A="")=>{if(RM in k)return k[Nk]=A,k;const M=function(){G0(n);const R=Array.from(arguments),P=new Set,L=new Set;function z(V){P.add(V)}function Q(V){L.add(V)}Uf(d,{args:R,name:M[Nk],store:S,after:z,onError:Q});let W;try{W=k.apply(this&&this.$id===s?this:S,R)}catch(V){throw Uf(L,V),V}return W instanceof Promise?W.then(V=>(Uf(P,V),V)).catch(V=>(Uf(L,V),Promise.reject(V))):(Uf(P,W),W)};return M[RM]=!0,M[Nk]=A,M},w={_p:n,$id:s,$onAction:IM.bind(null,d),$patch:g,$reset:y,$subscribe(k,A={}){const M=IM(h,k,A.detached,()=>R()),R=o.run(()=>Xe(()=>n.state.value[s],P=>{(A.flush==="sync"?u:l)&&k({storeId:s,type:wv.direct,events:p},P)},zc({},c,A)));return M},$dispose:b},S=mw(w);n._s.set(s,S);const T=(n._a&&n._a.runWithContext||WF)(()=>n._e.run(()=>(o=m2()).run(()=>e({action:_}))));for(const k in T){const A=T[k];if(jv(A)&&!VF(A)||iE(A))r||(m&&jF(A)&&(jv(A)?A.value=m[k]:v1(A,m[k])),n.state.value[s][k]=A);else if(typeof A=="function"){const M=_(A,k);T[k]=M,a.actions[k]=A}}return zc(S,T),zc(v2(S),T),Object.defineProperty(S,"$state",{get:()=>n.state.value[s],set:k=>{g(A=>{zc(A,k)})}}),n._p.forEach(k=>{zc(S,o.run(()=>k({store:S,app:n._a,pinia:n,options:a})))}),m&&r&&t.hydrate&&t.hydrate(S.$state,m),l=!0,u=!0,S}/*! #__NO_SIDE_EFFECTS__ */function dn(s,e,t){let n;const i=typeof e=="function";n=i?t:e;function r(o,a){const c=wF();return o=o||(c?y2(T2,null):null),o&&G0(o),o=C2,o._s.has(s)||(i?E2(s,e,n,o):GF(s,n,o)),o._s.get(s)}return r.$id=s,r}function b_(s,e){return Array.isArray(e)?e.reduce((t,n)=>(t[n]=function(){return s(this.$pinia)[n]},t),{}):Object.keys(e).reduce((t,n)=>(t[n]=function(){const i=s(this.$pinia),r=e[n];return typeof r=="function"?r.call(this,i):i[r]},t),{})}function Ir(s,e){return Array.isArray(e)?e.reduce((t,n)=>(t[n]=function(...i){return s(this.$pinia)[n](...i)},t),{}):Object.keys(e).reduce((t,n)=>(t[n]=function(...i){return s(this.$pinia)[e[n]](...i)},t),{})}function Ko(s,e){return Array.isArray(e)?e.reduce((t,n)=>(t[n]={get(){return s(this.$pinia)[n]},set(i){return s(this.$pinia)[n]=i}},t),{}):Object.keys(e).reduce((t,n)=>(t[n]={get(){return s(this.$pinia)[e[n]]},set(i){return s(this.$pinia)[e[n]]=i}},t),{})}function Ii(s){const e=v2(s),t={};for(const n in e){const i=e[n];i.effect?t[n]=ye({get:()=>s[n],set(r){s[n]=r}}):(jv(i)||iE(i))&&(t[n]=SF(s,n))}return t}const qF="modulepreload",KF=function(s){return"/static/dist/"+s},LM={},wt=function(e,t,n){let i=Promise.resolve();if(t&&t.length>0){document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),a=(o==null?void 0:o.nonce)||(o==null?void 0:o.getAttribute("nonce"));i=Promise.allSettled(t.map(c=>{if(c=KF(c),c in LM)return;LM[c]=!0;const l=c.endsWith(".css"),u=l?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${u}`))return;const h=document.createElement("link");if(h.rel=l?"stylesheet":qF,l||(h.as="script"),h.crossOrigin="",h.href=c,a&&h.setAttribute("nonce",a),document.head.appendChild(h),l)return new Promise((d,p)=>{h.addEventListener("load",d),h.addEventListener("error",()=>p(new Error(`Unable to preload CSS for ${c}`)))})}))}function r(o){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=o,window.dispatchEvent(a),!a.defaultPrevented)throw o}return i.then(o=>{for(const a of o||[])a.status==="rejected"&&r(a.reason);return e().catch(r)})},QF=typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(max-width: 768px)").matches:!1,Vs=dn("ui",{state:()=>({sidebarCollapsed:!0,chatDisplayMode:"chat",rightWidth:420,rightCollapsed:!0,rightSplitRatio:.5,isResizing:!1,resizingPanel:null,minPanelWidth:350,maxPanelWidth:600,quotaToast:null,quotaToastTimer:null,toastQueue:[],nextToastId:1,confirmDialog:null,pendingConfirmResolver:null,easterEgg:{active:!1,effect:null,payload:null,instance:null,cleanupTimer:null,destroying:!1,destroyPromise:null},isMobileViewport:QF,mobileOverlayMenuOpen:!1,activeMobileOverlay:null,imagePreview:null}),actions:{openImagePreview(s){const e=String((s==null?void 0:s.url)||"");e&&(this.imagePreview={url:e,name:String((s==null?void 0:s.name)||"")})},closeImagePreview(){this.imagePreview=null},setSidebarCollapsed(s){this.sidebarCollapsed=s},toggleSidebar(){this.sidebarCollapsed=!this.sidebarCollapsed},setChatDisplayMode(s){this.chatDisplayMode=s},toggleChatDisplayMode(){this.chatDisplayMode=this.chatDisplayMode==="chat"?"monitor":"chat"},setRightWidth(s){this.rightWidth=s},setRightCollapsed(s){this.rightCollapsed=s},setRightSplitRatio(s){this.rightSplitRatio=Math.max(.15,Math.min(.85,s))},setResizing(s,e=null){this.isResizing=s,this.resizingPanel=s?e:null},setPanelBounds(s,e){this.minPanelWidth=s,this.maxPanelWidth=e},setIsMobileViewport(s){this.isMobileViewport=s,s||(this.mobileOverlayMenuOpen=!1,this.activeMobileOverlay=null)},setMobileOverlayMenuOpen(s){this.mobileOverlayMenuOpen=s},toggleMobileOverlayMenu(){this.mobileOverlayMenuOpen=!this.mobileOverlayMenuOpen},setActiveMobileOverlay(s){this.activeMobileOverlay=s},closeMobileOverlay(){this.activeMobileOverlay=null},showQuotaToastMessage(s,e="fast",t=5e3){this.quotaToast={message:s,type:e},this.quotaToastTimer&&clearTimeout(this.quotaToastTimer),this.quotaToastTimer=setTimeout(()=>{this.dismissQuotaToast()},t)},dismissQuotaToast(){this.quotaToastTimer&&(clearTimeout(this.quotaToastTimer),this.quotaToastTimer=null),this.quotaToast=null},pushToast(s={}){const e=s.title||"",t=s.message||"";if(!e&&!t)return 0;const n=this.nextToastId++,i={id:n,title:e,message:t,type:s.type||"info",closable:s.closable!==!1,timeoutId:null},r=Object.prototype.hasOwnProperty.call(s,"duration")?s.duration:4e3;return r!==null&&(i.timeoutId=setTimeout(()=>this.dismissToast(n),r)),this.toastQueue.push(i),n},updateToast(s,e={}){const t=this.toastQueue.find(n=>n.id===s);t&&(e.title!==void 0&&(t.title=e.title),e.message!==void 0&&(t.message=e.message),e.type!==void 0&&(t.type=e.type),e.closable!==void 0&&(t.closable=e.closable),Object.prototype.hasOwnProperty.call(e,"duration")&&(t.timeoutId&&(clearTimeout(t.timeoutId),t.timeoutId=null),e.duration!==null&&typeof e.duration=="number"&&(t.timeoutId=setTimeout(()=>this.dismissToast(s),e.duration))))},dismissToast(s){const e=this.toastQueue.findIndex(n=>n.id===s);if(e===-1)return;const[t]=this.toastQueue.splice(e,1);t&&t.timeoutId&&clearTimeout(t.timeoutId)},requestConfirm(s={}){return new Promise(e=>{if(this.pendingConfirmResolver){const t=this.pendingConfirmResolver;this.pendingConfirmResolver=null,t(!1)}this.confirmDialog={visible:!0,title:s.title||"确认操作",message:s.message||"请确认本次操作",confirmText:s.confirmText||"确认",cancelText:s.cancelText||"取消",warningText:s.warningText||"",closeOnBackdrop:s.closeOnBackdrop!==!1,confirmVariant:s.confirmVariant==="danger"?"danger":"primary",confirmOnLeft:s.confirmOnLeft===!0},this.pendingConfirmResolver=e})},resolveConfirm(s){this.confirmDialog&&(this.confirmDialog.visible=!1);const e=this.pendingConfirmResolver;this.pendingConfirmResolver=null,this.confirmDialog=null,e&&e(!!s)},setEasterEggState(s){this.easterEgg={...this.easterEgg,...s}},clearEasterEgg(){this.easterEgg={active:!1,effect:null,payload:null,instance:null,cleanupTimer:null,destroying:!1,destroyPromise:null}}}}),XF=Object.freeze(Object.defineProperty({__proto__:null,useUiStore:Vs},Symbol.toStringTag,{value:"Module"})),YF=new Set(["chat","compact","hidden"]),JF=new Set(["user","presend"]),ZF=new Set(["guidance","goal_review","compression","compression_handoff","sub_agent","background_command","workflow"]);function y1(s){return String(s||"").trim().toLowerCase()}function M2(s){return String((s==null?void 0:s.content)||(s==null?void 0:s.message)||"").trim()}function e$(s){const e=M2(s);return e.includes("【目标模式已开启】")||e.includes(`[系统通知|goal]
【目标模式已开启】`)}function x2(s){return M2(s).includes("审核智能体对于你的工作结束给出了以下内容")}function Oh(s){var i;const e=(s==null?void 0:s.metadata)||{},t=y1(e.visibility||((i=e.ui)==null?void 0:i.visibility)||(s==null?void 0:s.visibility));if(YF.has(t))return t;if(e.hidden===!0||e.system_injected_image||e.system_injected_video)return"hidden";const n=y1(e.message_source||e.source||(s==null?void 0:s.message_source)||(s==null?void 0:s.source));return n==="skill"||n==="goal_prompt"||e$(s)||n==="notify"&&(e.runtime_mode_notice||s!=null&&s.runtime_mode_notice)?"hidden":ZF.has(n)||x2(s)?"compact":"chat"}function kv(s){var n;const e=(s==null?void 0:s.metadata)||{};if(typeof e.starts_work=="boolean")return e.starts_work;if(typeof((n=e.ui)==null?void 0:n.starts_work)=="boolean")return e.ui.starts_work;if(typeof(s==null?void 0:s.starts_work)=="boolean")return s.starts_work;if(Oh(s)==="hidden")return!1;const t=y1(e.message_source||e.source||(s==null?void 0:s.message_source)||(s==null?void 0:s.source));return t==="guidance"||t==="goal_prompt"||t==="skill"?!1:t==="goal_review"||x2(s)?!0:t==="compression"||t==="compression_handoff"?!1:JF.has(t||"user")}const Bk=["正在构思…","稍候AI 正在准备","准备工具中","容我三思…","答案马上就来","灵感加载中","思路拼装中","琢磨最佳方案","脑内开会中","整理资料中","润色回复中","调配上下文","搜刮记忆中","快敲完了,别急","领域展开","工具链装配中…","句子正在成形…","让我再捋一捋…","知识库检索中…"],t$=/<show_html\b[\s\S]*?<\/show_html>/i;function s$(s){return s?t$.test(s):!1}function n$(){if(!Bk.length)return"";const s=Math.floor(Math.random()*Bk.length);return Bk[s]}function Fk(){return{role:"assistant",actions:[],streamingThinking:"",streamingText:"",currentStreamingType:null,activeThinkingId:null,awaitingFirstContent:!1,generatingLabel:n$()}}function __(s){return`${s}-${Date.now()}-${Math.random().toString(36).slice(2)}`}function $k(s){return new Set(Array.from(s))}function i$(s){return new Map(Array.from(s.entries()))}function Hk(s){s&&s.awaitingFirstContent&&(s.awaitingFirstContent=!1)}const Uk=(...s)=>{},oE=dn("chat",{state:()=>({messages:[],currentMessageIndex:-1,streamingMessage:!1,expandedBlocks:new Set,autoScrollEnabled:!0,userScrolling:!1,thinkingScrollLocks:new Map}),getters:{isScrollLocked:s=>s.autoScrollEnabled&&!s.userScrolling},actions:{setStreamingMessage(s){this.streamingMessage=!!s},setCurrentMessageIndex(s){this.currentMessageIndex=s},setMessages(s){this.messages=s},clearMessages(){this.messages=[],this.currentMessageIndex=-1},updateEditSummaryByMessageId(s,e){var n;const t=i=>{i.metadata={...i.metadata||{},edit_summary:e}};if(s)for(let i=this.messages.length-1;i>=0;i-=1){const r=this.messages[i];if((r==null?void 0:r.role)==="user"&&(r==null?void 0:r.message_id)===s){t(r);return}}for(let i=this.messages.length-1;i>=0;i-=1){const r=this.messages[i];if((r==null?void 0:r.role)==="user"&&((n=r==null?void 0:r.metadata)==null?void 0:n.starts_work)===!0){t(r);return}}},toggleBlock(s){const e=$k(this.expandedBlocks);e.has(s)?e.delete(s):e.add(s),this.expandedBlocks=e},expandBlock(s){const e=$k(this.expandedBlocks);e.add(s),this.expandedBlocks=e},collapseBlock(s){const e=$k(this.expandedBlocks);e.delete(s),this.expandedBlocks=e},clearExpandedBlocks(){this.expandedBlocks=new Set},setThinkingLock(s,e){const t=i$(this.thinkingScrollLocks);e?t.set(s,!0):t.delete(s),this.thinkingScrollLocks=t},clearThinkingLocks(){this.thinkingScrollLocks=new Map},setScrollState(s){typeof s.autoScrollEnabled<"u"&&(this.autoScrollEnabled=!!s.autoScrollEnabled),typeof s.userScrolling<"u"&&(this.userScrolling=!!s.userScrolling)},enableAutoScroll(){this.setScrollState({autoScrollEnabled:!0,userScrolling:!1})},disableAutoScroll(){this.setScrollState({autoScrollEnabled:!1,userScrolling:!1})},toggleScrollLockState(){return this.isScrollLocked?(this.disableAutoScroll(),!1):(this.enableAutoScroll(),!0)},ensureAssistantMessage(){if(this.currentMessageIndex>=0)return this.messages[this.currentMessageIndex];const s=Fk();return this.messages.push(s),this.currentMessageIndex=this.messages.length-1,s},addUserMessage(s,e=[],t=[],n=[],i="user",r={}){const o=new Date().toISOString(),a=String(i||"user").trim().toLowerCase(),c={media_refs:Array.isArray(n)?n:[],message_source:a,...r};c.visibility=Oh({content:s,metadata:c}),c.starts_work=kv({content:s,metadata:c}),c.starts_work===!0&&(c.work_timer={status:"working",started_at:o}),this.messages.push({role:"user",content:s,images:e,videos:t,media_refs:Array.isArray(n)?n:[],metadata:c,created_at:o}),this.currentMessageIndex=-1},startAssistantMessage(){const s=Fk();return this.messages.push(s),this.currentMessageIndex=this.messages.length-1,this.streamingMessage=!0,s.awaitingFirstContent=!0,s},startThinkingAction(){const s=this.ensureAssistantMessage();Hk(s);const e=this.getActiveThinkingAction(s);if(e&&e.streaming===!0)return{action:e,blockId:e.blockId||e.id};s.streamingThinking="",s.currentStreamingType="thinking";const t=__("thinking"),n=t,i={id:t,type:"thinking",content:"",streaming:!0,timestamp:Date.now(),blockId:n};return s.actions.push(i),s.activeThinkingId=t,{action:i,blockId:n}},appendThinkingChunk(s){if(this.currentMessageIndex<0)return null;const e=this.messages[this.currentMessageIndex];e.streamingThinking+=s;const t=this.getActiveThinkingAction(e);return t?(t.content+=s,t):null},completeThinking(s){if(this.currentMessageIndex<0)return null;const e=this.messages[this.currentMessageIndex],t=this.getActiveThinkingAction(e);return t?(t.streaming=!1,t.content=s,e.streamingThinking="",e.currentStreamingType=null,e.activeThinkingId=null,t.blockId||t.id):null},startTextAction(){const s=this.ensureAssistantMessage();if(!s)return null;Hk(s);const e=s.actions[s.actions.length-1];if(e&&e.type==="text"&&e.streaming===!0)return e;s.streamingText="",s.currentStreamingType="text",s.__splitByShowHtml=!1;const t={id:__("text"),type:"text",content:"",streaming:!0,timestamp:Date.now()};return s.actions.push(t),t},appendTextChunk(s){if(this.currentMessageIndex<0)return null;const e=this.messages[this.currentMessageIndex];if(!e)return null;typeof e.streamingText!="string"&&(e.streamingText=""),e.streamingText+=s;let t=e.actions[e.actions.length-1];return t&&t.type==="text"&&t.streaming||(t={id:__("text"),type:"text",content:"",streaming:!0,timestamp:Date.now(),continuation:!0},e.actions.push(t)),t.content+=s,t.streaming&&s$(t.content)&&(t.streaming=!1,t.frozenByShowHtml=!0,e.__splitByShowHtml=!0),t},completeText(s){if(this.currentMessageIndex<0)return;const e=this.messages[this.currentMessageIndex],t=!!e.__splitByShowHtml;let n=!1;for(let i=e.actions.length-1;i>=0;i--){const r=e.actions[i];if(r.type==="text"&&r.streaming){r.streaming=!1,n=!0,!t&&typeof s=="string"&&s.length&&(r.content=s);break}}if(!n&&!t&&typeof s=="string")for(let i=e.actions.length-1;i>=0;i--){const r=e.actions[i];if(r.type==="text"){r.content=s;break}}e.streamingText="",e.currentStreamingType=null,delete e.__splitByShowHtml},addSystemMessage(s,e=null){const t=(e==null?void 0:e.variant)==="sub_agent_done";if(t&&Array.isArray(this.messages)&&this.messages.length>0){const r=this.messages[this.messages.length-1],o=Array.isArray(r==null?void 0:r.actions)?r.actions:[];(r==null?void 0:r.role)==="assistant"&&o.length===0&&!!(r!=null&&r.awaitingFirstContent)&&(Uk("chat.addSystemMessage:cleanup-empty-assistant-placeholder",{currentMessageIndex:this.currentMessageIndex,messagesLengthBeforeCleanup:this.messages.length}),this.messages.pop(),this.currentMessageIndex=this.messages.length-1)}const n=t?Fk():this.ensureAssistantMessage();Hk(n),Uk("chat.addSystemMessage:before",{content:s,meta:e,useStandaloneMessage:t,messagesLengthBefore:this.messages.length,currentMessageIndex:this.currentMessageIndex,actionsBefore:Array.isArray(n==null?void 0:n.actions)?n.actions.length:-1});const i={id:__("system"),type:"system",content:s,variant:(e==null?void 0:e.variant)||null,timestamp:Date.now()};n.actions.push(i),t&&(this.messages.push(n),this.currentMessageIndex=this.messages.length-1),Uk("chat.addSystemMessage:after",{messagesLengthAfter:this.messages.length,currentMessageIndex:this.currentMessageIndex,actionsAfter:Array.isArray(n==null?void 0:n.actions)?n.actions.length:-1})},getActiveThinkingAction(s){if(!s||!Array.isArray(s.actions))return null;if(s.activeThinkingId){const e=s.actions.find(t=>t&&t.id===s.activeThinkingId&&t.type==="thinking");if(e)return e}for(let e=s.actions.length-1;e>=0;e--){const t=s.actions[e];if(t&&t.type==="thinking"&&t.streaming!==!1)return t}return null},resetChatState(){this.messages=[],this.currentMessageIndex=-1,this.streamingMessage=!1,this.clearExpandedBlocks(),this.clearThinkingLocks()}}}),q0=dn("input",{state:()=>({inputMessage:"",inputLineCount:1,inputIsMultiline:!1,inputIsFocused:!1,quickMenuOpen:!1,toolMenuOpen:!1,settingsOpen:!1,imagePickerOpen:!1,selectedImages:[],videoPickerOpen:!1,selectedVideos:[],selectedFiles:[],goalModeArmed:!1,goalRunning:!1,goalProgress:null,goalDialogOpen:!1}),actions:{setInputMessage(s){this.inputMessage=s},clearInputMessage(){this.inputMessage=""},setInputLineCount(s){this.inputLineCount=s},setInputMultiline(s){this.inputIsMultiline=s},setInputFocused(s){this.inputIsFocused=s},openQuickMenu(){this.quickMenuOpen=!0},setQuickMenuOpen(s){this.quickMenuOpen=s,s||(this.toolMenuOpen=!1,this.settingsOpen=!1)},toggleQuickMenu(){const s=!this.quickMenuOpen;return this.setQuickMenuOpen(s),s},closeMenus(){this.quickMenuOpen=!1,this.toolMenuOpen=!1,this.settingsOpen=!1},toggleToolMenu(){return this.toolMenuOpen=!this.toolMenuOpen,this.toolMenuOpen},setToolMenuOpen(s){this.toolMenuOpen=s},toggleSettingsMenu(){return this.settingsOpen=!this.settingsOpen,this.settingsOpen},setSettingsOpen(s){this.settingsOpen=s},setImagePickerOpen(s){this.imagePickerOpen=s},setVideoPickerOpen(s){this.videoPickerOpen=s},setSelectedImages(s){this.selectedImages=s.slice(0,9)},addSelectedImage(s){if(!s)return;const e=Array.from(new Set([...this.selectedImages,s]));this.selectedImages=e.slice(0,9)},removeSelectedImage(s){this.selectedImages=this.selectedImages.filter(e=>e!==s)},clearSelectedImages(){this.selectedImages=[]},setSelectedVideos(s){this.selectedVideos=s.slice(0,1)},addSelectedVideo(s){s&&(this.selectedVideos=[s])},removeSelectedVideo(s){this.selectedVideos=this.selectedVideos.filter(e=>e!==s)},clearSelectedVideos(){this.selectedVideos=[]},addSelectedFile(s){if(!s)return;const e=Array.from(new Set([...this.selectedFiles,s]));this.selectedFiles=e.slice(0,9)},removeSelectedFile(s){this.selectedFiles=this.selectedFiles.filter(e=>e!==s)},clearSelectedFiles(){this.selectedFiles=[]},toggleGoalArmed(){return this.goalRunning?this.goalModeArmed:(this.goalModeArmed=!this.goalModeArmed,this.goalModeArmed)},setGoalArmed(s){this.goalModeArmed=s},setGoalRunning(s){this.goalRunning=s,s&&(this.goalModeArmed=!1)},setGoalProgress(s){this.goalProgress=s},setGoalDialogOpen(s){this.goalDialogOpen=s}}}),I2=dn("tool",{state:()=>({preparingTools:new Map,activeTools:new Map,toolActionIndex:new Map,toolStacks:new Map,toolSettings:[],toolSettingsLoading:!1}),actions:{setToolSettings(s){this.toolSettings=s},setToolSettingsLoading(s){this.toolSettingsLoading=s},registerToolAction(s,e=null){if(!s||s.type!=="tool")return;const t=new Set;s.id&&t.add(s.id),s.tool&&s.tool.id&&t.add(s.tool.id),e&&t.add(e),s.tool&&s.tool.executionId&&t.add(s.tool.executionId),t.forEach(n=>{n!=null&&this.toolActionIndex.set(String(n),s)})},unregisterToolAction(s){if(!s||s.type!=="tool")return;const e=[];for(const[t,n]of this.toolActionIndex.entries())n===s&&e.push(t);e.forEach(t=>this.toolActionIndex.delete(t)),s.tool&&s.tool.name&&this.releaseToolAction(s.tool.name,s)},findToolAction(s,e,t){const n=[t,s,e];for(const i of n){if(i==null)continue;const r=String(i);if(this.toolActionIndex.has(r))return this.toolActionIndex.get(r)}return null},trackToolAction(s,e){if(!s||!e)return;this.toolStacks.has(s)||this.toolStacks.set(s,[]);const t=this.toolStacks.get(s);t.includes(e)||t.push(e)},releaseToolAction(s,e){if(!s||!this.toolStacks.has(s))return;const t=this.toolStacks.get(s),n=t.indexOf(e);n!==-1&&t.splice(n,1),t.length===0&&this.toolStacks.delete(s)},getLatestActiveToolAction(s){if(!s||!this.toolStacks.has(s))return null;const e=this.toolStacks.get(s);for(let t=e.length-1;t>=0;t--){const n=e[t];if(!(!n||n.type!=="tool"||!n.tool)&&["preparing","running","stale"].includes(n.tool.status))return n}return e[e.length-1]||null},resetToolTracking(){this.preparingTools.clear(),this.activeTools.clear(),this.toolActionIndex.clear(),this.toolStacks.clear()}}}),Wk=()=>({count:0,limit:0,reset_at:null,window_start:null}),PM=()=>({fast:Wk(),thinking:Wk(),search:Wk(),role:"user"}),S_=6e4,r$=3e5,vm=5e3,o$=3e4,R2=dn("resource",{state:()=>({tokenPanelCollapsed:!0,currentContextTokens:0,currentConversationTokens:{cumulative_input_tokens:0,cumulative_output_tokens:0,cumulative_total_tokens:0},projectStorage:{used_bytes:0,limit_bytes:null,limit_label:"",usage_percent:null},containerStatus:null,containerNetRate:{down_bps:null,up_bps:null},containerVisibilityBound:!1,lastContainerSample:null,containerStatsInFlight:!1,containerStatsFailCount:0,containerStatsIntervalMs:vm,containerStatsTimer:null,projectStorageTimer:null,projectStorageInFlight:!1,projectStorageFailCount:0,projectStorageIntervalMs:S_,usageQuota:PM(),usageQuotaTimer:null}),actions:{resetTokenStatistics(){this.currentContextTokens=0,this.currentConversationTokens={cumulative_input_tokens:0,cumulative_output_tokens:0,cumulative_total_tokens:0}},setCurrentContextTokens(s){this.currentContextTokens=s||0},toggleTokenPanel(){this.tokenPanelCollapsed=!this.tokenPanelCollapsed,this.tokenPanelCollapsed?this.stopContainerStatsPolling():this.startContainerStatsPolling()},async updateCurrentContextTokens(s){if(!s){this.currentContextTokens=0;return}try{const t=await(await fetch(`/api/conversations/${s}/tokens`)).json();t.success&&t.data?this.currentContextTokens=t.data.total_tokens||0:this.currentContextTokens=0}catch(e){console.warn("获取当前上下文Token异常:",e),this.currentContextTokens=0}},async fetchConversationTokenStatistics(s){if(!s){this.resetTokenStatistics();return}try{const t=await(await fetch(`/api/conversations/${s}/token-statistics`)).json();t.success&&t.data&&(this.currentConversationTokens.cumulative_input_tokens=t.data.total_input_tokens||0,this.currentConversationTokens.cumulative_output_tokens=t.data.total_output_tokens||0,this.currentConversationTokens.cumulative_total_tokens=t.data.total_tokens||0,typeof t.data.current_context_tokens=="number"&&(this.currentContextTokens=t.data.current_context_tokens))}catch(e){console.warn("获取Token统计异常:",e)}},applyStatusSnapshot(s){if(!(!s||typeof s!="object")){if(s.project){const e=s.project;if(this.projectStorage.used_bytes=e.total_size||0,this.projectStorage.limit_bytes=e.limit_bytes??null,this.projectStorage.limit_label=e.limit_label||(e.limit_bytes?`${(e.limit_bytes/(1024*1024)).toFixed(0)} MB`:"未限制"),e.limit_bytes){const t=typeof e.usage_percent=="number"?e.usage_percent:e.total_size/e.limit_bytes*100;this.projectStorage.usage_percent=t}else this.projectStorage.usage_percent=null}Object.prototype.hasOwnProperty.call(s,"container")&&this.updateContainerStatus(s.container)}},updateContainerStatus(s){if(!s||s.mode!=="docker"){this.containerStatus=s||null,this.containerNetRate={down_bps:null,up_bps:null},this.lastContainerSample=null;return}const e=s.stats;if(e&&typeof e.timestamp=="number"){const t={timestamp:e.timestamp,rx_bytes:e.net_io&&typeof e.net_io.rx_bytes=="number"?e.net_io.rx_bytes:null,tx_bytes:e.net_io&&typeof e.net_io.tx_bytes=="number"?e.net_io.tx_bytes:null},n=this.lastContainerSample;if(n&&t.rx_bytes!==null&&t.tx_bytes!==null&&n.rx_bytes!==null&&n.tx_bytes!==null){const i=Math.max(.001,t.timestamp-n.timestamp),r=Math.max(0,(t.rx_bytes-n.rx_bytes)/i),o=Math.max(0,(t.tx_bytes-n.tx_bytes)/i);this.containerNetRate={down_bps:r,up_bps:o}}else this.containerNetRate={down_bps:null,up_bps:null};this.lastContainerSample=t}else this.containerNetRate={down_bps:null,up_bps:null},this.lastContainerSample=null;this.containerStatus=s},async pollContainerStats(){if(typeof document<"u"&&document.hidden||this.containerStatsInFlight)return;this.containerStatsInFlight=!0;const s=typeof AbortController<"u"?new AbortController:null,e=s?window.setTimeout(()=>s.abort(),4e3):null;try{const t=await fetch("/api/container-status",{signal:s==null?void 0:s.signal});if(!t.ok)throw new Error(`http-${t.status}`);const n=await t.json();n.success&&this.updateContainerStatus(n.data||null),this.containerStatsFailCount=0,this.containerStatsIntervalMs>vm&&this._restartContainerStatsTimer(vm)}catch(t){if(console.warn("获取容器状态异常:",t),this.containerStatsFailCount+=1,this.containerStatsFailCount>=3){const n=Math.min(this.containerStatsIntervalMs*2,o$);this._restartContainerStatsTimer(n)}}finally{this.containerStatsInFlight=!1,e&&clearTimeout(e)}},startContainerStatsPolling(){this.containerStatsTimer||this.tokenPanelCollapsed||(this.containerStatsFailCount=0,this.containerStatsIntervalMs=vm,this.pollContainerStats(),this.containerStatsTimer=setInterval(()=>{this.pollContainerStats()},this.containerStatsIntervalMs))},stopContainerStatsPolling(){this.containerStatsTimer&&(clearInterval(this.containerStatsTimer),this.containerStatsTimer=null),this.containerStatsInFlight=!1},_restartContainerStatsTimer(s){this.containerStatsTimer&&(clearInterval(this.containerStatsTimer),this.containerStatsTimer=null),this.containerStatsIntervalMs=s,this.containerStatsTimer=setInterval(()=>{this.pollContainerStats()},this.containerStatsIntervalMs)},bindContainerVisibilityWatcher(){if(this.containerVisibilityBound||typeof document>"u")return;const s=()=>{document.hidden?this.stopContainerStatsPolling():(this.containerStatsFailCount=0,this.containerStatsIntervalMs=vm,this.startContainerStatsPolling())};document.addEventListener("visibilitychange",s),this.containerVisibilityBound=!0},async pollProjectStorage(){if(!this.projectStorageInFlight){this.projectStorageInFlight=!0;try{const s=await fetch("/api/project-storage");if(!s.ok)throw new Error(s.statusText||"请求失败");const e=await s.json();e&&e.success&&e.data&&(this.projectStorage.used_bytes=e.data.used_bytes||0,this.projectStorage.limit_bytes=e.data.limit_bytes??null,this.projectStorage.limit_label=e.data.limit_label||"",this.projectStorage.usage_percent=e.data.usage_percent??null,this.projectStorageFailCount=0,this.projectStorageIntervalMs>S_&&this._restartProjectStorageTimer(S_))}catch(s){if(this.projectStorageFailCount+=1,console.warn("获取存储信息失败:",s),this.projectStorageFailCount>=3){const e=Math.min(this.projectStorageIntervalMs*2,r$);e!==this.projectStorageIntervalMs&&(console.warn(`连续获取失败,存储轮询间隔调整为 ${Math.round(e/1e3)} 秒`),this._restartProjectStorageTimer(e))}}finally{this.projectStorageInFlight=!1}}},startProjectStoragePolling(){this.projectStorageTimer||(this.pollProjectStorage(),this.projectStorageTimer=setInterval(()=>{this.pollProjectStorage()},this.projectStorageIntervalMs))},stopProjectStoragePolling(){this.projectStorageTimer&&(clearInterval(this.projectStorageTimer),this.projectStorageTimer=null),this.projectStorageInFlight=!1,this.projectStorageFailCount=0,this.projectStorageIntervalMs=S_},_restartProjectStorageTimer(s){this.projectStorageTimer&&clearInterval(this.projectStorageTimer),this.projectStorageIntervalMs=Math.max(s,1e4),this.projectStorageTimer=setInterval(()=>{this.pollProjectStorage()},this.projectStorageIntervalMs)},normalizeUsageQuota(s){const e=PM(),t=s&&s.quotas||{},n=t.role||s&&s.role||"user";return{fast:{...e.fast,...t.fast||{}},thinking:{...e.thinking,...t.thinking||{}},search:{...e.search,...t.search||{}},role:n}},setUsageQuota(s){this.usageQuota=this.normalizeUsageQuota(s)},async fetchUsageQuota(){try{const s=await fetch("/api/usage");if(!s.ok)throw new Error(s.statusText||"请求失败");const e=await s.json();e&&e.success&&e.data&&this.setUsageQuota(e.data)}catch(s){console.warn("获取用量配额失败:",s)}},startUsageQuotaPolling(){this.usageQuotaTimer||(this.fetchUsageQuota(),this.usageQuotaTimer=setInterval(()=>{this.fetchUsageQuota()},6e4))},stopUsageQuotaPolling(){this.usageQuotaTimer&&(clearInterval(this.usageQuotaTimer),this.usageQuotaTimer=null)}}}),L2="agents_sidebar_conversation_type",a$=()=>{try{return window.localStorage.getItem(L2)==="multi_agent"?"multi_agent":"normal"}catch{return"normal"}},l$=s=>{try{window.localStorage.setItem(L2,s)}catch{}},P2=()=>({conversationsByType:{normal:[],multi_agent:[]},pagingByType:{normal:{offset:0,hasMore:!1,loaded:!1},multi_agent:{offset:0,hasMore:!1,loaded:!1}}}),vr=dn("conversation",{state:()=>({conversations:[],searchResults:[],searchGroups:[],conversationInsertAnimations:{},conversationListAnimationMode:"idle",pendingDeletingConversationIds:[],conversationsLoading:!1,hasMoreConversations:!1,loadingMoreConversations:!1,currentConversationId:null,currentConversationTitle:"",searchQuery:"",searchTimer:null,searchActive:!1,searchInProgress:!1,searchMoreAvailable:!1,searchOffset:0,searchTotal:0,conversationsOffset:0,conversationsLimit:20,runningWorkspaceTasks:[],acknowledgedCompletedTaskIds:[],workspaceGroups:[],multiAgentMode:!1,sidebarConversationType:a$(),conversationsCache:{normal:{list:[],offset:0,hasMore:!1,loaded:!1},multi_agent:{list:[],offset:0,hasMore:!1,loaded:!1}}}),actions:{setCurrentConversationId(s){this.currentConversationId=s},setSidebarConversationType(s){const e=s==="multi_agent"?"multi_agent":"normal";if(this.sidebarConversationType===e)return;const t=this.sidebarConversationType,n=this.conversationsCache[t];n.offset=this.conversationsOffset,n.hasMore=this.hasMoreConversations,this.sidebarConversationType=e,l$(e);const i=this.conversationsCache[e];this.conversations=i.list,this.conversationsOffset=i.offset,this.hasMoreConversations=i.hasMore,this.loadingMoreConversations=!1;for(const r of this.workspaceGroups){if(!r||!r.conversationsByType)continue;const o=r.pagingByType[t];o.offset=r.offset,o.hasMore=r.hasMore,r.conversations=r.conversationsByType[e],r.offset=r.pagingByType[e].offset,r.hasMore=r.pagingByType[e].hasMore,r.loadingMore=!1}},resetConversations(){this.resetConversationsCacheOnly(),this.searchResults=[],this.searchGroups=[],this.conversationInsertAnimations={},this.conversationListAnimationMode="idle",this.pendingDeletingConversationIds=[],this.searchActive=!1,this.searchInProgress=!1,this.searchMoreAvailable=!1,this.searchOffset=0,this.searchTotal=0,this.hasMoreConversations=!1,this.loadingMoreConversations=!1,this.conversationsOffset=0,this.runningWorkspaceTasks=[],this.acknowledgedCompletedTaskIds=[]},resetConversationsTypeCache(){this.resetConversationsCacheOnly()},resetConversationsCacheOnly(){this.conversationsCache={normal:{list:[],offset:0,hasMore:!1,loaded:!1},multi_agent:{list:[],offset:0,hasMore:!1,loaded:!1}},this.conversations=this.conversationsCache[this.sidebarConversationType].list},cancelSearchTimer(){this.searchTimer&&(clearTimeout(this.searchTimer),this.searchTimer=null)},setWorkspaceGroups(s){this.workspaceGroups=s},setWorkspaceGroupExpanded(s,e){const t=this.workspaceGroups.find(n=>n.workspaceId===s);t&&(t.expanded=e)},setWorkspaceGroupConversations(s,e){const t=this.workspaceGroups.find(n=>n.workspaceId===s);t&&t.conversations.splice(0,t.conversations.length,...e)},appendWorkspaceGroupConversations(s,e){const t=this.workspaceGroups.find(n=>n.workspaceId===s);t&&t.conversations.push(...e)},setWorkspaceGroupLoading(s,e){const t=this.workspaceGroups.find(n=>n.workspaceId===s);t&&(t.loading=e)},setWorkspaceGroupLoadingMore(s,e){const t=this.workspaceGroups.find(n=>n.workspaceId===s);t&&(t.loadingMore=e)},setWorkspaceGroupHasMore(s,e){const t=this.workspaceGroups.find(n=>n.workspaceId===s);t&&(t.hasMore=e)},setWorkspaceGroupOffset(s,e){const t=this.workspaceGroups.find(n=>n.workspaceId===s);t&&(t.offset=e)},setWorkspaceGroupVisibleOffset(s,e){const t=this.workspaceGroups.find(n=>n.workspaceId===s);t&&(t.visibleOffset=Math.max(0,e))},ensureWorkspaceGroup(s){if(!s)return;if(!this.workspaceGroups.some(t=>t.workspaceId===s)){const t=P2();this.workspaceGroups.push({workspaceId:s,conversations:t.conversationsByType[this.sidebarConversationType],...t,loading:!1,hasMore:!1,loadingMore:!1,offset:0,visibleOffset:0,visibleLimit:5,bufferLimit:20,fetchLimit:25,expanded:!0})}},async loadWorkspaceConversations(s,{reset:e=!1,refresh:t=!1}={}){var l,u;if(!s)return;let n=this.workspaceGroups.findIndex(h=>h.workspaceId===s);n===-1&&(this.ensureWorkspaceGroup(s),n=this.workspaceGroups.length-1);const i=this.workspaceGroups[n],r=this.sidebarConversationType,o=i.conversationsByType[r],a=i.pagingByType[r];if(e&&(o.length=0,a.offset=0,a.hasMore=!1,a.loaded=!1,i.visibleOffset=0,r===this.sidebarConversationType&&(i.offset=0,i.hasMore=!1)),i.loading||i.loadingMore)return;const c=t?0:a.offset;i.loading=!0;try{const h=r==="multi_agent"?"&multi_agent_mode=1":"&multi_agent_mode=0",p=await(await fetch(`/api/conversations?workspace_id=${encodeURIComponent(s)}&limit=${i.fetchLimit}&offset=${c}${h}`)).json();if(p.success){const m=(((l=p.data)==null?void 0:l.conversations)||[]).map(g=>({id:g.id,title:g.title,updated_at:g.updated_at,total_messages:g.total_messages,total_tools:g.total_tools}));if(t){const g=o.slice(m.length);o.splice(0,o.length,...m,...g)}else c===0?o.splice(0,o.length,...m):o.push(...m);a.hasMore=!!((u=p.data)!=null&&u.has_more),a.loaded=!0,t||(a.offset=c+m.length),r===this.sidebarConversationType&&(i.hasMore=a.hasMore,i.offset=a.offset);const v=r==="multi_agent"?"normal":"multi_agent";c===0&&!i.pagingByType[v].loaded&&this.loadWorkspaceConversationTypeCache(s,v).catch(()=>{})}else console.error("加载工作区对话失败:",p.error)}catch(h){console.error("加载工作区对话异常:",h)}finally{i.loading=!1}},async loadWorkspaceConversationTypeCache(s,e){var i,r;const t=this.workspaceGroups.find(o=>o.workspaceId===s);if(!t||t.pagingByType[e].loaded)return;const n=e==="multi_agent"?"&multi_agent_mode=1":"&multi_agent_mode=0";try{const a=await(await fetch(`/api/conversations?workspace_id=${encodeURIComponent(s)}&limit=${t.fetchLimit}&offset=0${n}`)).json();if(!(a!=null&&a.success)||t.pagingByType[e].loaded)return;const c=(((i=a.data)==null?void 0:i.conversations)||[]).map(l=>({id:l.id,title:l.title,updated_at:l.updated_at,total_messages:l.total_messages,total_tools:l.total_tools}));t.conversationsByType[e].push(...c),t.pagingByType[e].offset=c.length,t.pagingByType[e].hasMore=!!((r=a.data)!=null&&r.has_more),t.pagingByType[e].loaded=!0}catch(o){console.error("补载工作区对话缓存异常:",o)}},async loadMoreWorkspaceConversations(s){var i,r,o;const e=this.workspaceGroups.findIndex(a=>a.workspaceId===s);if(e===-1)return;const t=this.workspaceGroups[e];if(!(t.loadingMore||!(t.conversations.length>t.visibleLimit)&&!t.hasMore)){if(t.loadingMore=!0,t.hasMore){const a=this.sidebarConversationType;try{const c=t.conversations.length,l=a==="multi_agent"?"&multi_agent_mode=1":"&multi_agent_mode=0",h=await(await fetch(`/api/conversations?workspace_id=${encodeURIComponent(s)}&limit=${t.bufferLimit}&offset=${c}${l}`)).json();if(h.success){const d=(((i=h.data)==null?void 0:i.conversations)||[]).map(m=>({id:m.id,title:m.title,updated_at:m.updated_at,total_messages:m.total_messages,total_tools:m.total_tools}));t.conversations.push(...d),t.hasMore=!!((r=h.data)!=null&&r.has_more);const p=(o=t.pagingByType)==null?void 0:o[a];p&&(p.offset=t.conversations.length,p.hasMore=t.hasMore)}}catch(c){console.error("加载更多工作区对话异常:",c)}}t.visibleLimit+=t.bufferLimit,t.loadingMore=!1}}}}),Ei=Object.freeze(Object.defineProperty({__proto__:null,createEmptyGroupTypeCache:P2,useConversationStore:vr},Symbol.toStringTag,{value:"Module"}));function c$(...s){}function O2(s){if(!s)return[];const e=Object.keys(s).map(t=>{const n=s[t]||{};return n.type==="folder"?{type:"folder",name:t,path:n.path||t,children:O2(n.children)}:{type:"file",name:t,path:n.path||t,annotation:n.annotation||""}});return e.sort((t,n)=>t.type!==n.type?t.type==="folder"?-1:1:t.name.localeCompare(n.name,"zh-CN")),e}const Tc=dn("file",{state:()=>({fileTree:[],expandedFolders:{},todoList:null,todoListLive:!1,todoSyncSeq:0,fileTreeUnavailable:!1,fileTreeMessage:"",contextMenu:{visible:!1,x:0,y:0,node:null}}),actions:{async fetchFileTree(){try{const e=await(await fetch("/api/files")).json();c$("[FileTree] fetch result",e),this.setFileTreeFromResponse(e)}catch(s){console.error("获取文件树失败:",s)}},markFileTreeUnavailable(s){this.fileTreeUnavailable=!0,this.fileTreeMessage=s||"宿主机模式下文件树不可用",this.fileTree=[],this.expandedFolders={}},setFileTreeFromResponse(s){if(!s){console.warn("[FileTree] 空 payload");return}if(s.unavailable){this.markFileTreeUnavailable(s.message||s.error);return}const e=s.structure||s;if(e&&e.unavailable){this.markFileTreeUnavailable(e.message||e.error);return}if(!e||!e.tree){console.warn("[FileTree] 缺少 structure.tree",e);return}this.fileTreeUnavailable=!1,this.fileTreeMessage="";const t=O2(e.tree),n={...this.expandedFolders},i=new Set,r=o=>{o.forEach(a=>{a.type==="folder"&&(i.add(a.path),n[a.path]===void 0&&(n[a.path]=!1),r(a.children||[]))})};r(t),Object.keys(n).forEach(o=>{i.has(o)||delete n[o]}),this.expandedFolders=n,this.fileTree=t},toggleFolder(s){if(!s)return;const e=!!this.expandedFolders[s];this.expandedFolders={...this.expandedFolders,[s]:!e}},async fetchTodoList(){const s=vr().currentConversationId;if(!s){this.setTodoList(null);return}try{const e=`/api/todo-list?conversation_id=${encodeURIComponent(s)}`,n=await(await fetch(e)).json();n&&n.success&&(this.todoListLive=!1,this.todoList=n.data||null,this.todoSyncSeq+=1)}catch(e){console.error("获取待办列表失败:",e)}},setTodoList(s,e=!1){this.todoListLive=e,this.todoList=s,this.todoSyncSeq+=1},showContextMenu(s){if(!s||!s.node)return;const{node:e,event:t}=s;if(!e.path&&e.path!==""){this.hideContextMenu();return}if(e.type!=="file"&&e.type!=="folder"){this.hideContextMenu();return}t&&typeof t.preventDefault=="function"&&t.preventDefault(),t&&typeof t.stopPropagation=="function"&&t.stopPropagation();const n=200,i=50,r=window.innerWidth,o=window.innerHeight;let a=t&&t.clientX||0,c=t&&t.clientY||0;a+n>r&&(a=r-n-8),c+i>o&&(c=o-i-8),this.contextMenu={visible:!0,x:Math.max(8,a),y:Math.max(8,c),node:e}},hideContextMenu(){this.contextMenu.visible&&(this.contextMenu={visible:!1,x:0,y:0,node:null})}}}),u$={categories:{},forced_category_states:{},disabled_models:[],ui_blocks:{}},No=dn("policy",{state:()=>({loaded:!1,loading:!1,error:"",policy:null}),getters:{disabledModelSet(s){var e;return new Set(((e=s.policy)==null?void 0:e.disabled_models)||[])},forcedCategoryStates(s){var e;return((e=s.policy)==null?void 0:e.forced_category_states)||{}},uiBlocks(s){var e;return((e=s.policy)==null?void 0:e.ui_blocks)||{}}},actions:{async fetchPolicy(){if(!this.loading){this.loading=!0,this.error="";try{const s=await fetch("/api/effective-policy"),e=await s.json();if(!s.ok||!e.success)throw new Error(e.error||"加载策略失败");this.policy=e.data||u$,this.loaded=!0}catch(s){this.error=(s==null?void 0:s.message)||"加载策略失败"}finally{this.loading=!1}}},isModelDisabled(s){return this.disabledModelSet.has(s)},isCategoryLocked(s){return typeof this.forcedCategoryStates[s]=="boolean"},categoryLockedState(s){const e=this.forcedCategoryStates;return typeof e[s]=="boolean"?e[s]:null},isBlocked(s){return!!this.uiBlocks[s]}}});function h$(s){if(!s)return null;const e={"image/jpeg":"image.jpg","image/jpg":"image.jpg","image/png":"image.png","image/gif":"image.gif","image/webp":"image.webp","image/bmp":"image.bmp","image/svg+xml":"image.svg","video/mp4":"video.mp4","video/quicktime":"video.mov","video/x-matroska":"video.mkv","video/avi":"video.avi","video/webm":"video.webm","application/pdf":"document.pdf","text/plain":"document.txt","text/markdown":"document.md"},t=s.split(";")[0].trim().toLowerCase();return e[t]||null}const D2=dn("upload",{state:()=>({uploading:!1,mediaUploading:!1}),actions:{setUploading(s){this.uploading=s},setMediaUploading(s){this.mediaUploading=s},async handleSelectedFiles(s){if(!s)return;const e=Array.isArray(s)?s:Array.from(s),[t]=e;t&&await this.uploadFile(t)},async uploadFiles(s,e={}){var c;if(!s)return[];const t=Array.isArray(s)?s:Array.from(s);if(!t.length)return[];const{markUploading:n=!0,markMediaUploading:i=!1}=e;if((c=No().uiBlocks)!=null&&c.block_upload)return Vs().pushToast({title:"上传被禁用",message:"已被管理员禁用上传功能",type:"warning"}),[];const o=Tc(),a=[];n&&this.setUploading(!0),i&&this.setMediaUploading(!0);try{for(const l of t){const u=await this.uploadFile(l,{manageUploading:!1,refreshFileTree:!1,skipPolicyCheck:!0});u!=null&&u.path&&a.push(u)}a.length&&await o.fetchFileTree()}finally{i&&this.setMediaUploading(!1),n&&this.setUploading(!1)}return a},async uploadFile(s,e={}){var u;const{manageUploading:t=!0,refreshFileTree:n=!0,skipPolicyCheck:i=!1}=e;if(!s||t&&this.uploading)return null;const r=No();if(!i&&((u=r.uiBlocks)!=null&&u.block_upload))return Vs().pushToast({title:"上传被禁用",message:"已被管理员禁用上传功能",type:"warning"}),null;const o=Vs(),a=Tc();(s.type&&s.type.startsWith("video/")||/\.(mp4|mov|m4v|webm|avi|mkv|flv|mpg|mpeg)$/i.test(s.name||""))&&o.pushToast({title:"视频处理中",message:"读取视频需要较长时间,请耐心等待",type:"info",duration:5e3}),t&&this.setUploading(!0);const l=o.pushToast({title:"上传文件",message:`正在上传 ${s.name}...`,type:"info",duration:null});try{const h=s.name||h$(s.type)||`upload_${Date.now()}`,d=new FormData;d.append("file",s),d.append("filename",h);const p=await fetch("/api/upload",{method:"POST",body:d});l&&o.updateToast(l,{message:"文件已上传,正在执行安全扫描...",type:"info"});let m={};try{m=await p.json()}catch{throw new Error("服务器响应无法解析")}if(!p.ok||!m.success){const g=m.error||m.message||"上传失败";throw new Error(g)}n&&await a.fetchFileTree();const v=`上传成功:${m.path||s.name}`;return l?o.updateToast(l,{title:"上传完成",message:v,type:"success",duration:4500}):o.pushToast({title:"上传完成",message:v,type:"success"}),m!=null&&m.path?{path:m.path,filename:m.filename||s.name||m.path}:null}catch(h){const d=h&&h.message?String(h.message):"",p=s&&s.name?s.name:"文件";let m=d||"请稍后重试";/安全审核未通过/.test(d)||/Eicar/i.test(d)?m=`${p} 安全审核未通过`:/文件类型不在允许列表中/.test(d)?m=`${p} 文件类型不在允许列表中`:m?m=`${p} 上传失败:${m}`:m=`${p} 上传失败,请稍后重试`;const v=Vs();return l?v.updateToast(l,{title:"上传失败",message:m,type:"error",duration:5e3}):v.pushToast({title:"上传失败",message:m,type:"error"}),null}finally{t&&this.setUploading(!1)}}}}),d$=new Set(["completed","failed","timeout","terminated"]),oh=dn("subAgent",{state:()=>({subAgents:[],activityTimer:null,activeAgent:null,silentActivityTaskId:null,stoppingTaskIds:{},activityEntries:[],activityLoading:!1,activityError:null}),actions:{async fetchSubAgents(){var s;try{const e=vr(),t=e.currentConversationId;if(!t){this.subAgents=[];return}this.subAgents=this.subAgents.filter(r=>!r.conversation_id||r.conversation_id===t);let n;if(e.multiAgentMode?n=await fetch(`/api/multiagent/active_sub_agents?conversation_id=${encodeURIComponent(t)}`):n=await fetch(`/api/sub_agents?conversation_id=${encodeURIComponent(t)}`),!n.ok)throw new Error(await n.text());const i=await n.json();if(i.success){const r=e.multiAgentMode?Array.isArray(i.agents)?i.agents:[]:Array.isArray(i.data)?i.data:[];r.sort((a,c)=>(Number(a==null?void 0:a.created_at)||0)-(Number(c==null?void 0:c.created_at)||0)),this.subAgents=r;const o=(s=this.activeAgent)==null?void 0:s.task_id;if(o){const a=this.subAgents.find(c=>c.task_id===o);a&&(this.activeAgent={...a})}}}catch(e){console.error("获取子智能体列表失败:",e)}},openSubAgent(s,e){!s||!s.task_id||(e!=null&&e.silent?this.silentActivityTaskId=s.task_id:(this.activeAgent=s,this.silentActivityTaskId=null),this.activityEntries=[],this.activityError=null,this.fetchSubAgentActivity(s.task_id),this.startActivityPolling())},closeSubAgent(){this.stopActivityPolling(),this.activeAgent=null,this.silentActivityTaskId=null,this.activityEntries=[],this.activityError=null,this.activityLoading=!1},startActivityPolling(){this.activityTimer||(this.activityTimer=setInterval(()=>{var e;const s=((e=this.activeAgent)==null?void 0:e.task_id)||this.silentActivityTaskId;s&&this.fetchSubAgentActivity(s)},2e3))},stopActivityPolling(){this.activityTimer&&(clearInterval(this.activityTimer),this.activityTimer=null)},async fetchSubAgentActivity(s){if(s){this.activityLoading=!0;try{const e=vr().currentConversationId,t=e?`&conversation_id=${encodeURIComponent(e)}`:"",n=await fetch(`/api/sub_agents/${s}/activity?limit=100000${t}`);if(!n.ok)throw new Error(await n.text());const i=await n.json();if(i&&i.success&&i.data){const r=Array.isArray(i.data.entries)?i.data.entries:[];this.activityEntries=r,this.activeAgent&&this.activeAgent.task_id===s&&(this.activeAgent={...this.activeAgent,status:i.data.status||this.activeAgent.status});const o=this.subAgents.find(c=>c.task_id===s);o&&i.data.status&&(o.status=i.data.status);const a=(i.data.status||"").toString();d$.has(a)&&this.stopActivityPolling()}}catch(e){this.activityError=(e==null?void 0:e.message)||String(e),console.error("获取子智能体活动失败:",e)}finally{this.activityLoading=!1}}},async terminateSubAgent(s){var t;const e=(s||"").toString().trim();if(!e)return{success:!1,error:"task_id 不能为空"};this.stoppingTaskIds={...this.stoppingTaskIds,[e]:!0};try{const i=vr().currentConversationId,r=i?`?conversation_id=${encodeURIComponent(i)}`:"",o=await fetch(`/api/sub_agents/${encodeURIComponent(e)}/terminate${r}`,{method:"POST"}),a=await o.json().catch(()=>({}));if(!o.ok||!(a!=null&&a.success))throw new Error((a==null?void 0:a.error)||`HTTP ${o.status}`);return await this.fetchSubAgents(),((t=this.activeAgent)==null?void 0:t.task_id)===e&&(await this.fetchSubAgentActivity(e),this.activeAgent={...this.activeAgent,status:"terminated"}),{success:!0,data:(a==null?void 0:a.data)||null}}catch(n){return{success:!1,error:(n==null?void 0:n.message)||String(n)}}finally{const n={...this.stoppingTaskIds};delete n[e],this.stoppingTaskIds=n}},async stopAllAgents(s){var e;try{const n=vr().currentConversationId,i=n?`?conversation_id=${encodeURIComponent(n)}`:"",r=await fetch(`/api/sub_agents/stop_all${i}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:s})}),o=await r.json().catch(()=>({}));if(!r.ok||!(o!=null&&o.success))throw new Error((o==null?void 0:o.error)||`HTTP ${r.status}`);return await this.fetchSubAgents(),{success:!0,stoppedCount:((e=o==null?void 0:o.data)==null?void 0:e.stopped_count)||0}}catch(t){return{success:!1,error:(t==null?void 0:t.message)||String(t)}}},stripConversationPrefix(s){return s?s.startsWith("conv_")?s.slice(5):s:""},getBaseUrl(){const s=window.SUB_AGENT_BASE_URL||window.__SUB_AGENT_BASE_URL__;if(s&&typeof s=="string")return s.replace(/\/$/,"");const{protocol:e,hostname:t}=window.location;if(t&&t.includes("agent.")){const n=t.replace("agent.","subagent.");return`${e}//${n}`}return`${e}//${t}:8092`}}}),f$=Object.freeze(Object.defineProperty({__proto__:null,useSubAgentStore:oh},Symbol.toStringTag,{value:"Module"}));function zk(){const s=vr().currentConversationId;return s?`conversation_id=${encodeURIComponent(s)}`:""}const p$=new Set(["completed","failed","timeout","cancelled"]),cm=dn("backgroundCommand",{state:()=>({commands:[],detailPollTimer:null,activeCommand:null,silentDetailCommandId:null,stoppingCommandIds:{},activeDetail:null,detailLoading:!1,detailError:null}),actions:{async fetchCommands(){var s;try{const e=vr().currentConversationId;if(!e){this.commands=[];return}const t=zk();this.commands=this.commands.filter(r=>!r.conversation_id||r.conversation_id===e);const n=await fetch(`/api/background_commands?limit=200${t?`&${t}`:""}`);if(!n.ok)throw new Error(await n.text());const i=await n.json();if(i.success){const r=Array.isArray(i.data)?i.data:[];r.sort((a,c)=>(Number(a==null?void 0:a.created_at)||0)-(Number(c==null?void 0:c.created_at)||0)),this.commands=r;const o=(s=this.activeCommand)==null?void 0:s.command_id;if(o){const a=this.commands.find(c=>c.command_id===o);a&&(this.activeCommand={...a})}}}catch(e){console.error("获取后台指令列表失败:",e)}},openCommand(s,e){!s||!s.command_id||(e!=null&&e.silent?this.silentDetailCommandId=s.command_id:(this.activeCommand=s,this.silentDetailCommandId=null),this.activeDetail=null,this.detailError=null,this.fetchCommandDetail(s.command_id),this.startDetailPolling())},closeCommand(){this.stopDetailPolling(),this.activeCommand=null,this.silentDetailCommandId=null,this.activeDetail=null,this.detailError=null,this.detailLoading=!1},startDetailPolling(){this.detailPollTimer||(this.detailPollTimer=setInterval(()=>{var e;const s=((e=this.activeCommand)==null?void 0:e.command_id)||this.silentDetailCommandId;s&&this.fetchCommandDetail(s)},2e3))},stopDetailPolling(){this.detailPollTimer&&(clearInterval(this.detailPollTimer),this.detailPollTimer=null)},async fetchCommandDetail(s){if(s){this.detailLoading=!0;try{const e=zk(),t=await fetch(`/api/background_commands/${encodeURIComponent(s)}${e?`?${e}`:""}`);if(!t.ok)throw new Error(await t.text());const n=await t.json();if(n&&n.success&&n.data){this.activeDetail=n.data;const i=this.commands.find(o=>o.command_id===s);i&&Object.assign(i,n.data),this.activeCommand&&this.activeCommand.command_id===s&&(this.activeCommand={...this.activeCommand,...n.data});const r=(n.data.status||"").toString();p$.has(r)&&this.stopDetailPolling()}}catch(e){this.detailError=(e==null?void 0:e.message)||String(e),console.error("获取后台指令详情失败:",e)}finally{this.detailLoading=!1}}},async cancelCommand(s){var t;const e=(s||"").toString().trim();if(!e)return{success:!1,error:"command_id 不能为空"};this.stoppingCommandIds={...this.stoppingCommandIds,[e]:!0};try{const n=zk(),i=await fetch(`/api/background_commands/${encodeURIComponent(e)}/cancel${n?`?${n}`:""}`,{method:"POST"}),r=await i.json().catch(()=>({}));if(!i.ok||!(r!=null&&r.success))throw new Error((r==null?void 0:r.error)||`HTTP ${i.status}`);return await this.fetchCommands(),((t=this.activeCommand)==null?void 0:t.command_id)===e&&await this.fetchCommandDetail(e),{success:!0,data:(r==null?void 0:r.data)||null}}catch(n){return{success:!1,error:(n==null?void 0:n.message)||String(n)}}finally{const n={...this.stoppingCommandIds};delete n[e],this.stoppingCommandIds=n}},async stopAllCommands(s){var e;try{const t=await fetch("/api/background_commands/stop_all",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s?{conversation_id:s}:{})}),n=await t.json().catch(()=>({}));if(!t.ok||!(n!=null&&n.success))throw new Error((n==null?void 0:n.error)||`HTTP ${t.status}`);return await this.fetchCommands(),{success:!0,stoppedCount:((e=n==null?void 0:n.data)==null?void 0:e.stopped_count)||0}}catch(t){return{success:!1,error:(t==null?void 0:t.message)||String(t)}}}}}),N2=dn("focus",{state:()=>({focusedFiles:{}}),actions:{async fetchFocusedFiles(){try{const s=await fetch("/api/focused");if(!s.ok)throw new Error(s.statusText||"请求失败");const e=await s.json();this.focusedFiles=e||{}}catch(s){console.error("获取聚焦文件失败:",s)}},setFocusedFiles(s){this.focusedFiles=s||{}},clearFocusedFiles(){this.focusedFiles={}}}}),Qi=dn("model",{state:()=>({currentModelKey:"",models:[]}),getters:{currentModel(s){return s.models.find(e=>e.key===s.currentModelKey)||s.models[0]||null}},actions:{setModels(s){var t;if(!Array.isArray(s))return;this.models=s,this.currentModelKey&&this.models.some(n=>n.key===this.currentModelKey)||(this.currentModelKey=((t=this.models[0])==null?void 0:t.key)||"")},setModel(s){if(this.currentModelKey===s)return;if(this.models.some(t=>t.key===s)){this.currentModelKey=s;return}s&&(this.models=[...this.models,{key:s,label:s,description:"",fastOnly:!1,supportsThinking:!0}],this.currentModelKey=s)},async fetchModels(){const s=await fetch("/api/v1/models",{cache:"no-store"}),e=await s.json();if(!s.ok||!(e!=null&&e.success)||!Array.isArray(e.items))throw new Error((e==null?void 0:e.error)||"加载模型列表失败");const t=e.items.filter(n=>n&&n.model_key).map(n=>{const i=String(n.multimodal||"none"),r=i==="image"||i==="image,video",o=i==="video"||i==="image,video";return{key:String(n.model_key),label:String(n.name||n.model_key),description:String(n.description||""),visible:n.visible!==!1,multimodal:i,supportsImage:r,supportsVideo:o,contextWindow:typeof n.context_window=="number"?n.context_window:null,maxOutputTokens:typeof n.max_output_tokens=="number"?n.max_output_tokens:null,fastOnly:!!n.fast_only,supportsThinking:!!n.supports_thinking,thinkingOnly:!!n.thinking_only,supportsReasoningEffort:!!n.supports_reasoning_effort}});this.setModels(t)}}}),B2=()=>({auto_approval:{model:"",thinking:!1,timeout_seconds:60,max_rounds:3,max_command_timeout:20},goal_review:{model:"",thinking:!1,timeout_seconds:60,max_rounds:3,max_command_timeout:60},workflow_review:{model:"",thinking:!1,timeout_seconds:120,max_rounds:6,max_command_timeout:60}}),g$=s=>{const e=B2(),t=s&&typeof s=="object"?s:{},n=(o,a,c,l)=>{const u=typeof o=="number"?o:parseInt(o,10);return Number.isFinite(u)?Math.max(c,Math.min(Math.trunc(u),l)):a},i=["auto_approval","goal_review","workflow_review"],r={};for(const o of i){const a=e[o],c=t[o]&&typeof t[o]=="object"?t[o]:{};r[o]={model:typeof c.model=="string"?c.model:"",thinking:typeof c.thinking=="boolean"?c.thinking:a.thinking,timeout_seconds:n(c.timeout_seconds,a.timeout_seconds,5,3600),max_rounds:n(c.max_rounds,a.max_rounds,1,50),max_command_timeout:n(c.max_command_timeout,a.max_command_timeout,1,600)}}return r},b1=10,Wf={min:1,max:30},nS=20,w_=5,m$=8e4,v$=15e4,OM=["fast","thinking"],DM=["low","medium","high","xhigh","max"],aE="agents_personalization_experiments",_1="agents_ui_theme",F2="agents_stacked_hide_borders",$2="agents_minimal_expand_height_limited",lE="agents_quick_dock_auto_expand",H2=()=>{if(typeof window>"u"||!window.localStorage)return"classic";const s=window.localStorage.getItem(_1);return s==="light"||s==="dark"||s==="classic"?s:"classic"},y$=()=>typeof window>"u"||!window.localStorage?!1:window.localStorage.getItem(F2)==="true",b$=()=>{if(typeof window>"u"||!window.localStorage)return"stacked";try{const s=window.localStorage.getItem(aE);if(!s)return"stacked";const e=JSON.parse(s);if(typeof(e==null?void 0:e.blockDisplayMode)=="string"&&["traditional","stacked","minimal"].includes(e.blockDisplayMode))return e.blockDisplayMode}catch(s){console.warn("读取堆叠块显示模式缓存失败:",s)}return"stacked"},NM=s=>{if(!(typeof window>"u"||!window.localStorage))try{window.localStorage.setItem(F2,s?"true":"false")}catch(e){console.warn("写入堆叠块边线设置失败:",e)}},U2=()=>{if(typeof window>"u"||!window.localStorage)return!0;const s=window.localStorage.getItem(lE);return s===null?!0:s==="true"},W2=()=>typeof window>"u"||!window.localStorage?!1:window.localStorage.getItem(lE)!==null,_$=s=>{if(!(typeof window>"u"||!window.localStorage))try{window.localStorage.setItem(lE,s?"true":"false")}catch(e){console.warn("写入快捷窗口自动展开设置缓存失败:",e)}},S$=()=>{if(typeof window>"u"||!window.localStorage)return!0;const s=window.localStorage.getItem($2);return s===null?!0:s==="true"},BM=s=>{if(!(typeof window>"u"||!window.localStorage))try{window.localStorage.setItem($2,s?"true":"false")}catch(e){console.warn("写入极简展开高度限制设置失败:",e)}},w$=()=>({enabled:!1,communication_style:"default",conversation_continuity:"medium",auto_generate_title:!0,recent_conversations_prompt_enabled:!1,recent_conversations_prompt_limit:b1,project_memory_inject_limit:nS,tool_intent_enabled:!0,skill_hints_enabled:!1,skill_strict_terminal_enabled:!1,skill_strict_sub_agent_enabled:!1,skill_strict_run_command_foreground_enabled:!1,skill_strict_run_command_background_enabled:!1,silent_tool_disable:!1,hide_tool_approval_panel:!0,enhanced_tool_display:!0,compact_message_display:"full",block_display_mode:b$(),show_status_avatar:!0,show_git_status_bar:!0,auto_open_terminal_panel:!0,quick_dock_auto_expand:U2(),file_preview_auto_wrap:!1,edit_summary_live_display:!1,modify_history_enabled:!0,stacked_hide_borders:y$(),minimal_expand_height_limited:S$(),enhanced_tool_display_categories:[],enabled_skills:[],self_identify:"",user_name:"",use_custom_names:!1,profession:"",tone:"",considerations:"",disabled_tool_categories:[],default_run_mode:null,default_reasoning_effort:null,default_permission_mode:"unrestricted",default_work_mode:"plan",versioning_enabled_by_default:!0,versioning_backup_mode:"shallow",versioning_restore_mode:"overwrite",default_model:null,image_compression:"original",auto_shallow_compress_enabled:!1,auto_deep_compress_enabled:!0,shallow_compress_trigger_tokens:null,shallow_compress_keep_recent_tools:null,shallow_compress_keep_user_turn_tools:null,shallow_compress_max_replace_per_round:null,shallow_compress_trigger_tool_calls_interval:null,deep_compress_trigger_tokens:null,deep_compress_form:"file",agents_md_auto_inject:!1,new_chat_button_behavior:"route",group_sidebar_by_workspace:!1,sidebar_pinned_workspaces:[],sidebar_workspace_order:[],theme:H2(),goal_review_mode:"readonly",goal_end_conditions:["max_turns"],goal_max_turns:5,goal_max_tokens:null,review_agents:B2()}),ym=()=>({blockDisplayMode:"stacked",compactMessageDisplay:"full"}),k$=()=>{if(typeof window>"u"||!window.localStorage)return ym();try{const s=window.localStorage.getItem(aE);if(!s)return ym();const e=JSON.parse(s);let t=ym().blockDisplayMode;typeof(e==null?void 0:e.blockDisplayMode)=="string"&&["traditional","stacked","minimal"].includes(e.blockDisplayMode)?t=e.blockDisplayMode:typeof(e==null?void 0:e.stackedBlocksEnabled)=="boolean"&&(t=e.stackedBlocksEnabled?"stacked":"traditional");let n=ym().compactMessageDisplay;return typeof(e==null?void 0:e.compactMessageDisplay)=="string"&&["full","brief"].includes(e.compactMessageDisplay)&&(n=e.compactMessageDisplay),{blockDisplayMode:t,compactMessageDisplay:n}}catch(s){return console.warn("无法读取实验功能设置:",s),ym()}};let k_=null;const qs=dn("personalization",{state:()=>({visible:!1,loading:!1,saving:!1,loaded:!1,status:"",error:"",toggleUpdating:!1,overlayPressActive:!1,tonePresets:["健谈","幽默","直言不讳","鼓励性","诗意","企业商务","打破常规","同理心"],form:w$(),toolCategories:[],skillsCatalog:[],recentConversationsPromptLimitRange:{...Wf},projectMemoryInjectLimitMin:w_,experiments:k$()}),actions:{async openDrawer(){this.visible=!0,this.loading||await this.fetchPersonalization()},closeDrawer(){this.visible=!1,this.overlayPressActive=!1},handleOverlayPressStart(s){if(s.target!==s.currentTarget){this.overlayPressActive=!1;return}s.type==="mousedown"&&s.button!==0||(this.overlayPressActive=!0)},handleOverlayPressEnd(s){const e=this.overlayPressActive&&s.target===s.currentTarget;this.overlayPressActive=!1,e&&(s.cancelable&&s.preventDefault(),this.closeDrawer())},handleOverlayPressCancel(){this.overlayPressActive=!1},async fetchPersonalization(){this.loading=!0,this.error="";try{const s=await fetch("/api/personalization"),e=await s.json();if(!s.ok||!e.success)throw new Error(e.error||"加载失败");this.applyPersonalizationData(e.data||{}),this.applyPersonalizationMeta(e),this.loaded=!0}catch(s){this.error=(s==null?void 0:s.message)||"加载失败"}finally{this.loading=!1}},applyPersonalizationData(s){var o;const e=this.form&&typeof this.form.default_model=="string"?this.form.default_model:null,t=((o=this.form)==null?void 0:o.theme)||H2();this.form={enabled:!!s.enabled,communication_style:s.communication_style==="human_like"||s.communication_style==="auto"?s.communication_style:"default",conversation_continuity:s.conversation_continuity==="low"||s.conversation_continuity==="high"?s.conversation_continuity:"medium",auto_generate_title:s.auto_generate_title!==!1,recent_conversations_prompt_enabled:!!s.recent_conversations_prompt_enabled,recent_conversations_prompt_limit:this.normalizeRecentConversationsPromptLimit(s.recent_conversations_prompt_limit),project_memory_inject_limit:this.normalizeProjectMemoryInjectLimit(s.project_memory_inject_limit),tool_intent_enabled:!!s.tool_intent_enabled,skill_hints_enabled:!!s.skill_hints_enabled,skill_strict_terminal_enabled:!!s.skill_strict_terminal_enabled,skill_strict_sub_agent_enabled:!!s.skill_strict_sub_agent_enabled,skill_strict_run_command_foreground_enabled:!!s.skill_strict_run_command_foreground_enabled,skill_strict_run_command_background_enabled:!!s.skill_strict_run_command_background_enabled,silent_tool_disable:!!s.silent_tool_disable,hide_tool_approval_panel:s.hide_tool_approval_panel!==!1,enhanced_tool_display:s.enhanced_tool_display!==!1,compact_message_display:s.compact_message_display==="brief"?"brief":"full",block_display_mode:s.block_display_mode==="traditional"||s.block_display_mode==="stacked"||s.block_display_mode==="minimal"?s.block_display_mode:"stacked",show_status_avatar:s.show_status_avatar!==!1,show_git_status_bar:s.show_git_status_bar!==!1,auto_open_terminal_panel:s.auto_open_terminal_panel!==!1,quick_dock_auto_expand:s.quick_dock_auto_expand!==!1,file_preview_auto_wrap:!!s.file_preview_auto_wrap,edit_summary_live_display:!!s.edit_summary_live_display,modify_history_enabled:s.modify_history_enabled!==!1,stacked_hide_borders:!!s.stacked_hide_borders,minimal_expand_height_limited:s.minimal_expand_height_limited!==!1,enhanced_tool_display_categories:Array.isArray(s.enhanced_tool_display_categories)?s.enhanced_tool_display_categories.filter(a=>typeof a=="string"):[],enabled_skills:Array.isArray(s.enabled_skills)?s.enabled_skills.filter(a=>typeof a=="string"):[],self_identify:s.self_identify||"",user_name:s.user_name||"",use_custom_names:!!s.use_custom_names,profession:s.profession||"",tone:s.tone||"",considerations:typeof s.considerations=="string"?s.considerations:Array.isArray(s.considerations)?s.considerations.filter(a=>typeof a=="string").join(`
`):"",disabled_tool_categories:Array.isArray(s.disabled_tool_categories)?s.disabled_tool_categories.filter(a=>typeof a=="string"):[],default_run_mode:(()=>{const a=s.default_run_mode==="deep"?"thinking":s.default_run_mode;return typeof a=="string"&&OM.includes(a)?a:null})(),default_reasoning_effort:typeof s.default_reasoning_effort=="string"&&DM.includes(s.default_reasoning_effort)?s.default_reasoning_effort:null,default_permission_mode:s.default_permission_mode==="readonly"||s.default_permission_mode==="approval"||s.default_permission_mode==="auto_approval"||s.default_permission_mode==="unrestricted"?s.default_permission_mode:"unrestricted",default_work_mode:s.default_work_mode==="plan"||s.default_work_mode==="ask"||s.default_work_mode==="execute"?s.default_work_mode:"plan",versioning_enabled_by_default:s.versioning_enabled_by_default!==!1,versioning_backup_mode:s.versioning_backup_mode==="full"?"full":"shallow",versioning_restore_mode:"overwrite",default_model:typeof s.default_model=="string"?s.default_model:e,image_compression:typeof s.image_compression=="string"?s.image_compression:"original",auto_shallow_compress_enabled:!!s.auto_shallow_compress_enabled,auto_deep_compress_enabled:!!s.auto_deep_compress_enabled,shallow_compress_trigger_tokens:this.normalizeCompressionNumber(s.shallow_compress_trigger_tokens),shallow_compress_keep_recent_tools:this.normalizeCompressionNumber(s.shallow_compress_keep_recent_tools),shallow_compress_keep_user_turn_tools:this.normalizeCompressionNumber(s.shallow_compress_keep_user_turn_tools),shallow_compress_max_replace_per_round:this.normalizeCompressionNumber(s.shallow_compress_max_replace_per_round),shallow_compress_trigger_tool_calls_interval:this.normalizeCompressionNumber(s.shallow_compress_trigger_tool_calls_interval),deep_compress_trigger_tokens:this.normalizeCompressionNumber(s.deep_compress_trigger_tokens),deep_compress_form:s.deep_compress_form==="inject"?"inject":"file",agents_md_auto_inject:!!s.agents_md_auto_inject,new_chat_button_behavior:s.new_chat_button_behavior==="blank"?"blank":"route",group_sidebar_by_workspace:!!s.group_sidebar_by_workspace,sidebar_pinned_workspaces:Array.isArray(s.sidebar_pinned_workspaces)?s.sidebar_pinned_workspaces.filter(a=>typeof a=="string"):[],sidebar_workspace_order:Array.isArray(s.sidebar_workspace_order)?s.sidebar_workspace_order.filter(a=>typeof a=="string"):[],theme:["classic","light","dark"].includes(s.theme)?s.theme:t,goal_review_mode:s.goal_review_mode==="active"?"active":"readonly",goal_end_conditions:Array.isArray(s.goal_end_conditions)?s.goal_end_conditions.filter(a=>a==="max_turns"||a==="max_tokens"):["max_turns"],goal_max_turns:typeof s.goal_max_turns=="number"&&s.goal_max_turns>0?s.goal_max_turns:5,goal_max_tokens:typeof s.goal_max_tokens=="number"&&s.goal_max_tokens>0?s.goal_max_tokens:null,review_agents:g$(s.review_agents)};const n=typeof window<"u"&&window.localStorage?window.localStorage.getItem(_1):null;this.form.theme!==n&&this.applyTheme(this.form.theme),NM(this.form.stacked_hide_borders),BM(this.form.minimal_expand_height_limited),_$(this.form.quick_dock_auto_expand);const i=this.experiments.compactMessageDisplay;this.form.compact_message_display==="full"&&i==="brief"&&(this.form={...this.form,compact_message_display:"brief"},this.persistCompactMessageDisplay("brief"));const r=this.experiments.blockDisplayMode;this.form.block_display_mode==="stacked"&&r!=="stacked"&&(this.form={...this.form,block_display_mode:r}),this.experiments={...this.experiments,compactMessageDisplay:this.form.compact_message_display,blockDisplayMode:this.form.block_display_mode},this.persistExperiments(),this.clearFeedback()},applyTheme(s){if(typeof window>"u")return;window.localStorage.setItem(_1,s),document.documentElement.setAttribute("data-theme",s),document.body.setAttribute("data-theme",s)},normalizeCompressionNumber(s){if(s===null||typeof s>"u"||s==="")return null;const e=Number(s);if(!Number.isFinite(e))return null;const t=Math.round(e);return t<=0?null:t},normalizeRecentConversationsPromptLimit(s){const e=Number(s),t=this.recentConversationsPromptLimitRange.min??Wf.min,n=this.recentConversationsPromptLimitRange.max??Wf.max;return Number.isFinite(e)?Math.max(t,Math.min(n,Math.round(e))):b1},normalizeProjectMemoryInjectLimit(s){if(typeof s>"u")return nS;if(s===null||s==="")return null;const e=Number(s);if(!Number.isFinite(e))return nS;const t=Math.round(e);if(t<=0)return null;const n=this.projectMemoryInjectLimitMin??w_;return Math.max(n,t)},applyPersonalizationMeta(s){if(s&&s.recent_conversations_prompt_limit_range){const{min:e,max:t}=s.recent_conversations_prompt_limit_range;this.recentConversationsPromptLimitRange={min:typeof e=="number"?e:Wf.min,max:typeof t=="number"?t:Wf.max}}else this.recentConversationsPromptLimitRange={...Wf};if(s&&s.project_memory_inject_limit_range){const{min:e}=s.project_memory_inject_limit_range;this.projectMemoryInjectLimitMin=typeof e=="number"?e:w_}else this.projectMemoryInjectLimitMin=w_;s&&Array.isArray(s.tool_categories)?this.toolCategories=s.tool_categories.map((e={})=>({id:typeof e.id=="string"?e.id:String(e.id??""),label:e.label&&String(e.label)||(typeof e.id=="string"?e.id:String(e.id??""))})).filter(e=>!!e.id):this.toolCategories=[],s&&Array.isArray(s.skills_catalog)?this.skillsCatalog=s.skills_catalog.map((e={})=>({id:typeof e.id=="string"?e.id:String(e.id??""),label:e.label&&String(e.label)||(typeof e.id=="string"?e.id:String(e.id??"")),description:typeof e.description=="string"?e.description:void 0})).filter(e=>!!e.id):this.skillsCatalog=[]},clearFeedback(){this.status="",this.error=""},async toggleEnabled(){if(this.toggleUpdating)return;const s=!this.form.enabled,e=this.form.enabled;this.toggleUpdating=!0,this.status="",this.error="",this.form.enabled=s;try{const t=await fetch("/api/personalization",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:s})}),n=await t.json();if(!t.ok||!n.success)throw new Error(n.error||"更新失败");n.data&&this.applyPersonalizationData(n.data),this.applyPersonalizationMeta(n);const i=s?"已启用":"已停用";this.status=i,setTimeout(()=>{this.status===i&&(this.status="")},2e3)}catch(t){this.form.enabled=e,this.error=(t==null?void 0:t.message)||"更新失败"}finally{this.toggleUpdating=!1}},async save(){if(!this.saving){this.saving=!0,this.status="",this.error="";try{const s=this.normalizeCompressionNumber(this.form.shallow_compress_trigger_tokens)??m$;if((this.normalizeCompressionNumber(this.form.deep_compress_trigger_tokens)??v$)<=s)throw new Error("深压缩触发上下文必须大于浅压缩触发上下文");const t=await fetch("/api/personalization",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(this.form)}),n=await t.json();if(!t.ok||!n.success)throw new Error(n.error||"保存失败");this.applyPersonalizationData(n.data||{}),this.applyPersonalizationMeta(n),this.status="已保存",setTimeout(()=>{this.status==="已保存"&&(this.status="")},3e3)}catch(s){this.error=(s==null?void 0:s.message)||"保存失败"}finally{this.saving=!1}}},updateField(s){!s||!s.key||(this.form={...this.form,[s.key]:s.value},s.key==="stacked_hide_borders"&&NM(!!s.value),s.key==="minimal_expand_height_limited"&&BM(!!s.value),this.clearFeedback(),this.scheduleAutoSave())},scheduleAutoSave(){k_&&clearTimeout(k_),k_=setTimeout(()=>{k_=null,this.autoSave()},500)},async autoSave(){if(!this.saving){this.saving=!0;try{const s=await fetch("/api/personalization",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(this.form)}),e=await s.json();if(!s.ok||!e.success)throw new Error(e.error||"自动保存失败")}catch(s){this.error=(s==null?void 0:s.message)||"自动保存失败"}finally{this.saving=!1}}},setRecentConversationsPromptLimit(s){const e=s===null||typeof s>"u"?b1:this.normalizeRecentConversationsPromptLimit(s);this.form={...this.form,recent_conversations_prompt_limit:e},this.clearFeedback(),this.scheduleAutoSave()},setProjectMemoryInjectLimit(s){const e=s===null||typeof s>"u"?null:this.normalizeProjectMemoryInjectLimit(s);this.form={...this.form,project_memory_inject_limit:e},this.clearFeedback(),this.scheduleAutoSave()},restoreProjectMemoryInjectLimit(){this.form={...this.form,project_memory_inject_limit:nS},this.clearFeedback(),this.scheduleAutoSave()},toggleDefaultToolCategory(s){if(!s)return;const e=new Set(this.form.disabled_tool_categories||[]);e.has(s)?e.delete(s):e.add(s),this.form={...this.form,disabled_tool_categories:Array.from(e)},this.clearFeedback(),this.scheduleAutoSave()},toggleSkill(s){if(!s)return;const e=new Set(this.form.enabled_skills||[]);e.has(s)?e.delete(s):e.add(s),this.form={...this.form,enabled_skills:Array.from(e)},this.clearFeedback(),this.scheduleAutoSave()},setDefaultRunMode(s){let e=null;typeof s=="string"&&OM.includes(s)&&(e=s),this.form={...this.form,default_run_mode:e},this.clearFeedback(),this.scheduleAutoSave()},setDefaultReasoningEffort(s){let e=null;typeof s=="string"&&DM.includes(s)&&(e=s),this.form={...this.form,default_reasoning_effort:e},this.clearFeedback(),this.scheduleAutoSave()},setDefaultPermissionMode(s){const t=["readonly","approval","auto_approval","unrestricted"].includes(s)?s:"unrestricted";this.form={...this.form,default_permission_mode:t},this.clearFeedback(),this.scheduleAutoSave()},setDefaultWorkMode(s){const t=["plan","ask","execute"].includes(s)?s:"plan";this.form={...this.form,default_work_mode:t},this.clearFeedback(),this.scheduleAutoSave()},setVersioningRestoreMode(s){const e="overwrite";this.form={...this.form,versioning_restore_mode:e},this.clearFeedback(),this.scheduleAutoSave()},setVersioningBackupMode(s){const e=s==="full"?"full":"shallow";this.form={...this.form,versioning_backup_mode:e},this.clearFeedback(),this.scheduleAutoSave()},setDefaultModel(s){const e=Qi(),t=new Set((e.models||[]).map(i=>i.key)),n=typeof s=="string"&&t.has(s)?s:null;this.form={...this.form,default_model:n},this.clearFeedback(),this.scheduleAutoSave()},setImageCompression(s){["original","1080p","720p","540p"].includes(s)&&(this.form={...this.form,image_compression:s},this.clearFeedback(),this.scheduleAutoSave())},applyTonePreset(s){s&&(this.form={...this.form,tone:s},this.clearFeedback(),this.scheduleAutoSave())},updateConsiderations(s){this.form={...this.form,considerations:s},this.clearFeedback(),this.scheduleAutoSave()},async logout(){try{const s=await fetch("/logout",{method:"POST",credentials:"same-origin",cache:"no-store"});let e=null;try{e=await s.json()}catch{e=null}if(s.ok&&(!e||e.success!==!1)){window.location.replace(`/login?logged_out=1&ts=${Date.now()}`);return}window.location.replace(`/logout?ts=${Date.now()}`)}catch(s){console.error("退出登录失败:",s),this.error=(s==null?void 0:s.message)||"退出登录失败,请稍后重试",window.location.replace(`/logout?ts=${Date.now()}`)}},persistExperiments(){if(!(typeof window>"u"||!window.localStorage))try{window.localStorage.setItem(aE,JSON.stringify(this.experiments))}catch(s){console.warn("写入实验功能设置失败:",s)}},setBlockDisplayMode(s){this.experiments={...this.experiments,blockDisplayMode:s},this.persistExperiments(),this.form={...this.form,block_display_mode:s},this.scheduleAutoSave()},setCompactMessageDisplay(s){const e=s==="brief"?"brief":"full";this.form={...this.form,compact_message_display:e},this.experiments={...this.experiments,compactMessageDisplay:e},this.persistExperiments(),this.clearFeedback(),this.persistCompactMessageDisplay(e)},async persistCompactMessageDisplay(s){try{const e=await fetch("/api/personalization",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({compact_message_display:s})}),t=await e.json();(!e.ok||!t.success)&&console.warn("保存简略消息显示失败:",t==null?void 0:t.error)}catch(e){console.warn("保存简略消息显示失败:",e)}},setCommunicationStyle(s){this.form={...this.form,communication_style:s},this.clearFeedback(),this.scheduleAutoSave()},setConversationContinuity(s){this.form={...this.form,conversation_continuity:s},this.clearFeedback(),this.scheduleAutoSave()}}}),C$=Object.freeze(Object.defineProperty({__proto__:null,hasCachedQuickDockAutoExpand:W2,loadCachedQuickDockAutoExpand:U2,usePersonalizationStore:qs},Symbol.toStringTag,{value:"Module"})),T$={browserSearch:"正在搜索",webExtract:"正在提取",webSave:"正在保存",appendFile:"正在编辑",modifyFile:"正在编辑",createFile:"正在创建",deleteFile:"正在删除",readFile:"正在读取",reader:"正在读取",focus:"正在聚焦",unfocus:"正在处理",runCommand:"运行命令",terminalSession:"打开终端",terminalInput:"终端输入",terminalSnapshot:"获取终端输出",memoryUpdate:"正在同步记忆",todoCreate:"正在更新待办",todoUpdate:"正在更新待办",todoFinish:"正在完成任务",todoFinishConfirm:"正在确认任务",todoDelete:"正在移除任务",wait:"正在等待",sleep:"正在等待",createFolder:"正在创建文件夹",renameFile:"正在重命名",terminalReset:"正在重置终端",terminalSleep:"准备等待",terminalRun:"终端运行中",ocr:"正在提取",memory:"正在同步记忆",todo:"正在管理待办",genericTool:"调用工具"};function FM(s){return T$[s]||null}const z2=dn("connection",{state:()=>({isConnected:!1,socket:null,stopRequested:!1,projectPath:"",agentVersion:"",thinkingMode:!0,runMode:"thinking",reasoningEffort:null}),actions:{setSocket(s){this.socket=s},setConnected(s){this.isConnected=s},setStopRequested(s){this.stopRequested=s},requestStop(){this.stopRequested=!0},clearStopRequest(){this.stopRequested=!1},setProjectPath(s){this.projectPath=s},setAgentVersion(s){this.agentVersion=s},setThinkingMode(s){this.thinkingMode=!!s},toggleThinkingMode(){this.thinkingMode=!this.thinkingMode},setRunMode(s){this.runMode=s,this.thinkingMode=s!=="fast"},setReasoningEffort(s){this.reasoningEffort=s}}}),jk=(...s)=>{},zf=(...s)=>{},_h=(...s)=>{},Vk=["__pycache__","config","core","data","doc","docker","logs","modules","node_modules","project","prompts","scratch_test","scripts","static","sub_agent","test","users","utils"],A$=32,$M={web_search:"browserSearch",extract_webpage:"webExtract",save_webpage:"webSave",read_file:"reader",view_video:"reader",vlm_analyze:"ocr",ocr_image:"ocr",create_folder:"createFolder",create_file:"createFile",rename_file:"renameFile",delete_file:"deleteFile",write_file:"modifyFile",edit_file:"modifyFile",run_command:"runCommand",terminal_session:"terminalSession",terminal_input:"terminalInput",terminal_snapshot:"terminalSnapshot",sleep:"terminalSleep",update_memory:"memoryUpdate",recall_project_memory:"reader",search_project_memory:"reader",update_project_memory:"memoryUpdate",todo_create:"todoCreate",todo_update_task:"todoUpdate",todo_delete_task:"todoDelete",terminal_run:"runCommand"},E$=(s="evt")=>`${s}-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,j2=dn("monitor",{state:()=>({statusLabel:"待机",queue:[],playing:!1,awaitingTools:{},lastTreeSnapshot:[...Vk],lastSpeechAt:0,thinkingActive:!1,pendingResults:{},completedResults:{},driver:null,speechBuffer:"",bubbleActive:!1,pendingProgressScene:null,progressIndicator:{id:null,label:"",scene:null}}),getters:{isLocked:s=>s.playing||s.queue.length>0},actions:{registerDriver(s){this.driver=s,this.driver.resetScene({desktopRoots:this.lastTreeSnapshot,preserveBubble:this.bubbleActive,preservePointer:!1,preserveWindows:!1}),this.speechBuffer&&(this.driver.showSpeechBubble(this.speechBuffer,{variant:"info",duration:0}),this.bubbleActive=!0),this.driver.setManualInteractionEnabled(!this.isLocked),this.pendingProgressScene&&(zf("registerDriver:apply-pending",{scene:this.pendingProgressScene}),this.driver.previewSceneProgress(this.pendingProgressScene),this.pendingProgressScene=null),this.queue.length&&this.processQueue()},unregisterDriver(){this.driver&&(this.driver.setManualInteractionEnabled(!1),this.driver.hideBubble()),this.driver=null,this.playing=!1},syncDesktopFromTree(s){var t,n;if(!Array.isArray(s)||!s.length){this.lastTreeSnapshot=[...Vk],(t=this.driver)==null||t.setDesktopRoots(this.lastTreeSnapshot,{immediate:!0});return}const e=s.filter(i=>i&&i.type==="folder").map(i=>i.name).filter(Boolean);this.lastTreeSnapshot=e.length?e:[...Vk],(n=this.driver)==null||n.setDesktopRoots(this.lastTreeSnapshot)},resetVisualState(s){var a,c;const e=!!(s!=null&&s.preserveBubble),t=(s==null?void 0:s.preservePointer)!==!1,n=!!(s!=null&&s.preserveWindows),i=!!(s!=null&&s.preserveQueue),r=!!(s!=null&&s.preservePendingResults),o=!!(s!=null&&s.preserveAwaitingTools);this.statusLabel="待机",i||(this.queue=[],this.playing=!1),this.lastSpeechAt=0,o||(this.awaitingTools={}),r||(Object.values(this.pendingResults).forEach(l=>{l!=null&&l.timeout&&clearTimeout(l.timeout)}),this.pendingResults={},this.completedResults={}),e||(this.speechBuffer="",this.bubbleActive=!1),this.thinkingActive=!1,this.pendingProgressScene=null,this.progressIndicator={id:null,label:"",scene:null},(a=this.driver)==null||a.resetScene({desktopRoots:this.lastTreeSnapshot,preserveBubble:e,preservePointer:t,preserveWindows:n}),(c=this.driver)==null||c.setManualInteractionEnabled(!this.isLocked)},setProgressIndicator(s){this.progressIndicator={id:s.id,label:s.label,scene:s.scene},zf("progress-indicator:set",this.progressIndicator)},previewToolIntent(s){this.bubbleActive&&this.hideBubble(`tool-intent:${(s==null?void 0:s.name)||"unknown"}`),this.speechBuffer="";const e=$M[s.name]||"genericTool",t=FM(e);t&&(this.setStatus(t),this.progressIndicator={id:null,label:t,scene:e},zf("preview-tool-intent",{tool:s.name,script:e,label:t}),this.driver?this.driver.previewSceneProgress(e):this.pendingProgressScene=e)},clearProgressIndicator(s){s&&this.progressIndicator.id&&s!==this.progressIndicator.id||(zf("progress-indicator:clear",{id:this.progressIndicator.id,label:this.progressIndicator.label}),this.progressIndicator={id:null,label:"",scene:null})},setStatus(s){this.statusLabel=s},showBubble(s,e={}){var t;s&&(jk("showBubble",{text:s,variant:e==null?void 0:e.variant,duration:e==null?void 0:e.duration}),(t=this.driver)==null||t.showSpeechBubble(s,e),this.bubbleActive=!0)},hideBubble(s){var e;(e=this.driver)==null||e.hideBubble(),this.bubbleActive=!1,this.thinkingActive=!1},resetSpeechBuffer(){this.speechBuffer=""},showPendingReply(){var s;if(this.setStatus("待机"),this.driver&&typeof this.driver.showWaitingBubble=="function"){this.driver.showWaitingBubble("等待回复"),this.bubbleActive=!0;return}(s=this.driver)==null||s.showSpeechBubble("等待回复...",{variant:"info",duration:0}),this.bubbleActive=!0},enqueueModelSpeech(s){if(s){if(this.setStatus("正在规划"),this.speechBuffer=`${this.speechBuffer}${s}`,this.lastSpeechAt=Date.now(),jk("enqueueModelSpeech",{incoming:s,combined:this.speechBuffer}),this.playing||!this.driver){this.bubbleActive=!1;return}this.driver.showSpeechBubble(this.speechBuffer,{variant:"info",duration:0}),this.bubbleActive=!0}},enqueueModelThinking(){var t;const s=z2();s.runMode==="fast"||s.thinkingMode===!1||this.playing||!this.driver||this.thinkingActive||(this.setStatus("思考中"),(t=this.driver)==null||t.showThinkingBubble(),this.bubbleActive=!0,this.thinkingActive=!0)},endModelOutput(){this.setStatus("待机"),this.thinkingActive=!1},enqueueToolEvent(s){var c,l,u,h,d;const t=Date.now()-this.lastSpeechAt,n=480,i=$M[s.name]||"genericTool",r=FM(i);r&&this.setStatus(r);const o=s.executionId||s.id||E$("tool");if(this.ensurePendingResult(o),this.queue.push({id:o,script:i,payload:{...s,executionId:o}}),this.awaitingTools[o]=s.name,this.driver&&typeof this.driver.preparePendingCreation=="function"&&(s.name==="create_folder"||s.name==="create_file")){const p=((c=s==null?void 0:s.arguments)==null?void 0:c.path)||((l=s==null?void 0:s.arguments)==null?void 0:l.target_path)||((u=s==null?void 0:s.arguments)==null?void 0:u.targetPath)||((h=s==null?void 0:s.argumentSnapshot)==null?void 0:h.path)||((d=s==null?void 0:s.argumentSnapshot)==null?void 0:d.target_path);this.driver.preparePendingCreation(p)}_h("enqueue",{id:o,tool:s.name,script:i,queueSize:this.queue.length,awaiting:Object.keys(this.awaitingTools).length,status:this.statusLabel}),r?this.setProgressIndicator({id:o,label:r,scene:i}):this.clearProgressIndicator();const a=()=>{this.driver?(zf("enqueueToolEvent:preview-now",{tool:s.name,script:i,id:o}),this.driver.previewSceneProgress(i)):(zf("enqueueToolEvent:pending-preview",{tool:s.name,script:i,id:o}),this.pendingProgressScene=i),this.bubbleActive&&this.hideBubble(`tool-enqueue:${(s==null?void 0:s.name)||"unknown"}`)};if(this.bubbleActive&&t>=0&&t<n){const p=n-t;_h("enqueue:delay-preview-for-speech",{delay:p,recentSpeechGap:t,tool:s.name}),setTimeout(a,p)}else a();this.processQueue()},resolveToolResult(s){var t;const e=s.execution_id||s.executionId||s.id;if(e&&this.awaitingTools[e]&&delete this.awaitingTools[e],_h("tool-result",{id:e,status:s.status,message:s.message,hasResult:s.result!==void 0}),e&&this.clearProgressIndicator(e),s.status&&["failed","error"].includes(s.status)){const n=s.message||"工具执行失败";(t=this.driver)==null||t.showSpeechBubble(n,{variant:"error",icon:"✖",duration:2800}),this.setStatus("异常"),setTimeout(()=>this.hideBubble(),2600)}e&&this.fulfillPendingResult(e,s)},ensurePendingResult(s){if(!s)return;const e=Object.prototype.hasOwnProperty.call(this.completedResults,s);if(this.pendingResults[s]){if(e){const r=this.completedResults[s];delete this.completedResults[s],this.pendingResults[s].resolve(r)}return}let t=()=>{};const i={promise:new Promise(r=>{t=r}),resolve:r=>{i.settled||(i.settled=!0,i.timeout&&(clearTimeout(i.timeout),i.timeout=null)),t(r)},timeout:null,settled:!1};if(i.timeout=setTimeout(()=>{i.settled||(i.resolve(null),this.cleanupPendingResult(s,i))},12e3),this.pendingResults[s]=i,e){const r=this.completedResults[s];delete this.completedResults[s],i.resolve(r)}},waitForResult(s){if(!s)return Promise.resolve(null);const e=String(s);if(Object.prototype.hasOwnProperty.call(this.completedResults,e)){const n=this.completedResults[e];return delete this.completedResults[e],Promise.resolve(n)}this.ensurePendingResult(e);const t=this.pendingResults[e];return t?t.promise.finally(()=>{this.cleanupPendingResult(e,t)}):Promise.resolve(null)},fulfillPendingResult(s,e){if(!s)return;const t=this.pendingResults[s];if(t){t.resolve(e);return}this.completedResults[s]=e;const n=Object.keys(this.completedResults);if(n.length>A$){const i=n[0];delete this.completedResults[i]}},cleanupPendingResult(s,e){if(!s)return;const t=e||this.pendingResults[s];t&&(t.timeout&&(clearTimeout(t.timeout),t.timeout=null),this.pendingResults[s]===t&&delete this.pendingResults[s])},async processQueue(){if(!(this.playing||!this.queue.length)&&this.driver){for(this.playing=!0,this.driver.setManualInteractionEnabled(!1),_h("queue-start",{size:this.queue.length});this.queue.length&&this.driver;){const s=this.queue.shift();s&&(jk("processQueue start",{script:s.script,bubbleActive:this.bubbleActive,speechBufferLength:this.speechBuffer.length}),this.bubbleActive&&this.hideBubble(`queue-start:${s.script}`),this.speechBuffer="",await this.runScript(s))}this.playing=!1,this.driver&&this.driver.setManualInteractionEnabled(!0),this.speechBuffer&&this.driver&&(this.driver.showSpeechBubble(this.speechBuffer,{variant:"info",duration:0}),this.bubbleActive=!0),this.setStatus("待机")}},async runScript(s){var a,c,l,u,h;if(!this.driver){this.queue.unshift(s);return}const e=((a=s.payload)==null?void 0:a.executionId)||((c=s.payload)==null?void 0:c.execution_id)||s.id||((l=s.payload)==null?void 0:l.id)||null;_h("runScript:start",{script:s.script,waitKey:e,payloadTool:(u=s.payload)==null?void 0:u.name,payloadId:(h=s.payload)==null?void 0:h.id});let t,n=!1;const i=async()=>{if(!e)return n=!0,t===void 0&&(t=null),t;if(n)return t;try{t=await this.waitForResult(e)}catch(d){console.warn("monitor waitForResult error",d),t=null}finally{n=!0}return t},r=d=>{const p=typeof d=="string"&&d.trim().length?d.trim():"进行中";return p.startsWith("正在")?`回放${p.slice(2)}`:p},o={waitForResult:()=>i(),setStatus:d=>this.setStatus(r(d)),statusPhase:"playback"};this.setStatus("工具操作回放"),_h("runScript:playback",{script:s.script,waitKey:e,status:this.statusLabel});try{await this.driver.playScene(s.script,s.payload||{},o)}catch(d){console.warn("Monitor scene error",d)}finally{_h("runScript:end",{script:s.script,waitKey:e})}}}}),Gk={damping:.7,stiffness:.05,mass:1.25},M$=70,x$=1e3/60,I$=350;let iS=!1,HM=!1;function R$(){HM||typeof document>"u"||(document.addEventListener("mousedown",()=>{iS=!0}),document.addEventListener("mouseup",()=>{iS=!1}),document.addEventListener("click",()=>{iS=!1}),HM=!0)}const qk=new Map;function Kk(...s){const e={damping:Gk.damping,stiffness:Gk.stiffness,mass:Gk.mass};let t=!1;for(const i of s){if(i==="instant"){t=!0;continue}typeof i!="object"||!i||(t=!1,e.damping=i.damping??e.damping,e.stiffness=i.stiffness??e.stiffness,e.mass=i.mass??e.mass)}const n=JSON.stringify(e);return qk.has(n)||qk.set(n,Object.freeze({...e})),t?"instant":qk.get(n)}function L$(s={}){R$();let e={...s};const t=new Set,n={isAtBottom:e.initial!==!1,isNearBottom:!1,escapedFromLock:!1,velocity:0,accumulated:0,resizeDifference:0};function i(){const M=r();for(const R of t)R(M)}function r(){return{isAtBottom:n.isAtBottom||n.isNearBottom,isNearBottom:n.isNearBottom,escapedFromLock:n.escapedFromLock}}function o(){var M;return((M=n.scrollElement)==null?void 0:M.scrollTop)??0}function a(M){n.scrollElement&&(n.scrollElement.scrollTop=M,n.ignoreScrollToTop=n.scrollElement.scrollTop)}function c(){const M=n.scrollElement,R=n.contentElement;return!M||!R?0:M.scrollHeight-1-M.clientHeight}let l;function u(){const M=n.scrollElement,R=n.contentElement;if(!M||!R)return 0;const P=c();if(!e.targetScrollTop)return P;if((l==null?void 0:l.targetScrollTop)===P)return l.calculatedScrollTop;const L=Math.max(Math.min(e.targetScrollTop(P,{scrollElement:M,contentElement:R}),P),0);return l={targetScrollTop:P,calculatedScrollTop:L},typeof requestAnimationFrame<"u"&&requestAnimationFrame(()=>{l=void 0}),L}function h(){return u()-o()}function d(){return h()<=M$}function p(M){n.isAtBottom=M,i()}function m(M){n.escapedFromLock=M,i()}function v(M){n.isNearBottom=M,i()}function g(){var z;if(!iS||typeof window>"u")return!1;const M=(z=window.getSelection)==null?void 0:z.call(window);if(!M||!M.rangeCount)return!1;const R=M.getRangeAt(0),P=n.scrollElement;if(!P)return!1;const L=R.commonAncestorContainer;return!!(L&&(P.contains(L)||L.contains(P)))}const y=M=>{if(M.target!==n.scrollElement)return;const R=o(),P=n.ignoreScrollToTop;let L=n.lastScrollTop??R;n.lastScrollTop=R,n.ignoreScrollToTop=void 0,P&&P>R&&(L=P),v(d()),setTimeout(()=>{var W;if(n.resizeDifference||R===P)return;if(g()){m(!0),p(!1);return}const z=R>L,Q=R<L;if((W=n.animation)!=null&&W.ignoreEscapes){a(L);return}Q&&(m(!0),p(!1)),z&&m(!1),!n.escapedFromLock&&d()&&p(!0)},1)},b=M=>{var L;const R=n.scrollElement;if(!R)return;let P=M.target;for(;P&&!["scroll","auto"].includes(getComputedStyle(P).overflow);){if(!P.parentElement)return;P=P.parentElement}P===R&&M.deltaY<0&&R.scrollHeight>R.clientHeight&&!((L=n.animation)!=null&&L.ignoreEscapes)&&(m(!0),p(!1))};function _(M,R){w(),n.scrollElement=M,n.contentElement=R,getComputedStyle(M).overflow==="visible"&&(M.style.overflow="auto"),M.addEventListener("scroll",y,{passive:!0}),M.addEventListener("wheel",b,{passive:!0});let P;n.resizeObserver=new ResizeObserver(L=>{const z=L[0];if(!z)return;const{height:Q}=z.contentRect,W=Q-(P??Q);if(n.resizeDifference=W,o()>c()&&a(c()),v(d()),W>=0){const V=Kk(e,P?e.resize:e.initial);T({animation:V,wait:!0,preserveScrollPosition:!0,duration:V==="instant"?void 0:I$})}else d()&&(m(!1),p(!0));P=Q,typeof requestAnimationFrame<"u"&&requestAnimationFrame(()=>{setTimeout(()=>{n.resizeDifference===W&&(n.resizeDifference=0)},1)})}),n.resizeObserver.observe(R)}function w(){var M;n.scrollElement&&(n.scrollElement.removeEventListener("scroll",y),n.scrollElement.removeEventListener("wheel",b)),(M=n.resizeObserver)==null||M.disconnect(),n.resizeObserver=void 0,n.scrollElement=void 0,n.contentElement=void 0}function S(){w(),t.clear()}function C(M){e={...e,...M}}function T(M={}){var N;const R=typeof M=="string"?{animation:M}:M;R.preserveScrollPosition||p(!0);const P=Date.now()+(Number(R.wait)||0),L=Kk(e,R.animation),{ignoreEscapes:z=!1}=R;let Q,W=u();R.duration instanceof Promise?R.duration.finally(()=>{Q=Date.now()}):Q=P+(R.duration??0);const V=async()=>{const O=new Promise(H=>{if(typeof requestAnimationFrame>"u"){H(!1);return}requestAnimationFrame(()=>H(!0))}).then(()=>{var ie;if(!n.isAtBottom)return n.animation=void 0,!1;const H=o(),G=typeof performance<"u"?performance.now():Date.now(),ee=(G-(n.lastTick??G))/x$;if(n.animation||(n.animation={behavior:L,promise:O,ignoreEscapes:z}),n.animation.behavior===L&&(n.lastTick=G),g()||P>Date.now())return V();if(H<Math.min(W,u())){if(((ie=n.animation)==null?void 0:ie.behavior)===L){if(L==="instant")return a(u()),V();const ve=L;n.velocity=(ve.damping*n.velocity+ve.stiffness*h())/ve.mass,n.accumulated+=n.velocity*ee;const le=o();a(le+n.accumulated),o()!==le&&(n.accumulated=0)}return V()}return Q>Date.now()?(W=u(),V()):(n.animation=void 0,o()<u()?T({animation:Kk(e,e.resize),ignoreEscapes:z,duration:Math.max(0,Q-Date.now())||void 0}):n.isAtBottom)});return O.then(H=>(typeof requestAnimationFrame<"u"&&requestAnimationFrame(()=>{n.animation||(n.lastTick=void 0,n.velocity=0)}),H))};return R.wait!==!0&&(n.animation=void 0),((N=n.animation)==null?void 0:N.behavior)===L?n.animation.promise:V()}const k=()=>{m(!0),p(!1)};function A(M){return t.add(M),()=>t.delete(M)}return{attach:_,detach:w,destroy:S,setOptions:C,getState:r,onChange:A,scrollToBottom:T,stopScroll:k}}function P$(s={}){const e=pe(null),t=pe(null),n=pe(s.initial!==!1),i=pe(!1),r=pe(!1),o=L$(s);let a=null;return b2(c=>{!e.value||!t.value||(o.attach(e.value,t.value),a=o.onChange(l=>{n.value=l.isAtBottom,i.value=l.isNearBottom,r.value=l.escapedFromLock}),c(()=>{a==null||a(),a=null,o.detach()}))}),xn(()=>{o.destroy()}),{scrollRef:e,contentRef:t,isAtBottom:n,isNearBottom:i,escapedFromLock:r,scrollToBottom:c=>o.scrollToBottom(c),stopScroll:()=>o.stopScroll(),setOptions:c=>o.setOptions(c)}}const Gv=null,{min:Dh,max:Yo,abs:UM,floor:O$}=Math,V2=(s,e,t)=>Dh(t,Yo(e,s)),G2=s=>[...s].sort((e,t)=>e-t),D$=typeof queueMicrotask=="function"?queueMicrotask:s=>{Promise.resolve().then(s)},S1=()=>{let s;return[new Promise(e=>{s=e}),s]},q2=s=>{let e;return()=>(s&&(e=s(),s=void 0),e)},Cv=(s,e,t)=>{const n=t?"unshift":"push";for(let i=0;i<e;i++)s[n](-1);return s},K2=(s,e)=>{const t=s.t[e];return t===-1?s.o:t},N$=(s,e,t)=>{const n=s.t[e]===-1;return s.t[e]=t,s.i=Dh(e,s.i),n},rS=(s,e)=>{if(!s.l)return 0;if(s.i>=e)return s.u[e];s.i<0&&(s.u[0]=0,s.i=0);let t=s.i,n=s.u[t];for(;t<e;)n+=K2(s,t),s.u[++t]=n;return s.i=e,n},jf=(s,e,t=0,n=s.l-1)=>{let i=t;for(;t<=n;){const r=O$((t+n)/2);rS(s,r)<=e?(i=r,t=r+1):n=r-1}return V2(i,0,s.l-1)},WM=(s,e,t)=>{const n=e-s.l;return s.i=t?-1:Dh(e-1,s.i),s.l=e,n>0?(Cv(s.u,n),Cv(s.t,n,t),s.o*n):(s.u.splice(n),(t?s.t.splice(0,-n):s.t.splice(n)).reduce((i,r)=>i-(r===-1?s.o:r),0))},B$=s=>s.documentElement,F$=s=>s.ownerDocument,$$=s=>s.defaultView,Q2=q2(()=>!!/iP(hone|od|ad)/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>0),H$=q2(()=>"scrollBehavior"in B$(document).style),U$=(s,e=40,t=0,n,i=!1)=>{let r=!!t,o=1,a=0,c=0,l=0,u=0,h=0,d=0,p=0,m=0,v=Gv,g=[0,r?Yo(t-1,0):-1],y=0,b=!1;const _=((L,z,Q)=>({o:z,t:Q?Cv(Q.slice(0,Dh(L,Q.length)),Yo(0,L-Q.length)):Cv([],L),l:L,i:-1,u:Cv([],L+1)}))(s,n?n[1]:e,n&&n[0]),w=new Set,S=()=>l-c,C=()=>S()+h+u,T=(L,z)=>((Q,W,V,N)=>{if(N=Dh(N,Q.l-1),rS(Q,N)<=W){const O=jf(Q,V,N);return[jf(Q,W,N,O),O]}{const O=jf(Q,W,void 0,N);return[O,jf(Q,V,O)]}})(_,L,z,g[0]),k=()=>rS(_,_.l),A=(L,z)=>{const Q=rS(_,L)-h;return z?k()-Q-M(L):Q},M=L=>K2(_,L),R=(L,z=-1)=>_.t[L]===z,P=L=>{L&&(Q2()&&p!==0||v&&m===1?h+=L:u+=L)};return{p:()=>{w.clear()},m:()=>o,h:()=>(L=>[L.t.slice(),L.o])(_),v:(L=200)=>{if(!b||r)return g;let z,Q;if(d)[z,Q]=g;else{let W=Yo(0,C()),V=W+a;i||(L=Yo(0,L),p!==1&&(W-=L),p!==2&&(V+=L)),[z,Q]=g=T(Yo(0,W),Yo(0,V)),v&&(z=Dh(z,v[0]),Q=Yo(Q,v[1]))}return[Yo(z,0),Dh(Q,_.l-1)]},S:L=>jf(_,L-c),I:R,O:A,k:M,j:()=>_.l,N:()=>l,B:()=>p!==0,T:()=>a,q:()=>c,M:k,P:()=>(d=u,u=0,[d,m===2]),R:(L,z)=>{const Q=[L,z];return w.add(Q),()=>{w.delete(Q)}},A:(L,z)=>{let Q,W,V=0;switch(L){case 1:{if(z===l&&m===0)break;const N=d;d=0;const O=z-l,H=UM(O);N&&H<UM(N)+1||m!==0||(p=O<0?2:1),r&&(r=!1),l=z,V=4;const G=S();G>=-a&&G<=k()&&(V+=1,W=H>a);break}case 2:V=8,p!==0&&(Q=!0,V+=1),p=0,m=0,v=Gv;break;case 3:{const N=z.filter(([O,H])=>!R(O,H));if(!N.length)break;P(N.reduce((O,[H,G])=>{let ee;if(m===2)ee=!0;else if(v&&m===1)ee=H<v[0];else{const ie=S(),ve=A(H),le=M(H);ee=p!==1&&m===0?ve+le<=ie:ve<ie&&ve+le<ie+a}return ee&&(O+=G-M(H)),O},0));for(const[O,H]of N){const G=M(O),ee=N$(_,O,H);i&&(y+=ee?H:H-G)}i&&a&&y>a&&(P(((O,H)=>{let G=0;const ee=[];O.t.forEach((K,X)=>{K!==-1&&(ee.push(K),X<H&&G++)}),O.i=-1;const ie=G2(ee),ve=ie.length,le=ve/2|0,oe=ve%2==0?(ie[le-1]+ie[le])/2:ie[le],I=O.o;return((O.o=oe)-I)*Yo(H-G,0)})(_,jf(_,C()))),i=!1),V=3,W=!0;break}case 4:a!==z&&(a||(b=W=!0),a=z,V=3);break;case 5:z[1]?(P(WM(_,z[0],!0)),m=2,V=1):(WM(_,z[0]),V=1);break;case 6:c=z;break;case 7:m=1;break;case 8:v=T(z,z+a),V=1}V&&(o=1+(2147483647&o),Q&&h&&(u+=h,h=0),w.forEach(([N,O])=>{V&N&&O(W)}))}}},cE=setTimeout,Qk=(s,e)=>e?-s:s,W$=(s,e,t,n,i,r)=>{const o=Date.now;let a=0,c=!1,l=!1,u=!1,h=!1;const d=(()=>{let y;const b=()=>{y!=Gv&&clearTimeout(y)},_=()=>{b(),y=cE(()=>{y=Gv,(()=>{if(c||l)return c=!1,void d();u=!1,s.A(2)})()},150)};return _.C=b,_})(),p=()=>{a=o(),u&&(h=!0),s.A(1,n()),d()},m=y=>{if(c||!s.B()||y.ctrlKey)return;const b=o()-a;150>b&&50<b&&(t?y.deltaX:y.deltaY)&&(c=!0)},v=()=>{l=!0,u=h=!1},g=()=>{l=!1,Q2()&&(u=!0)};return e.addEventListener("scroll",p),e.addEventListener("wheel",m,{passive:!0}),e.addEventListener("touchstart",v,{passive:!0}),e.addEventListener("touchend",g,{passive:!0}),{H:()=>{e.removeEventListener("scroll",p),e.removeEventListener("wheel",m),e.removeEventListener("touchstart",v),e.removeEventListener("touchend",g),d.C()},V:()=>{const[y,b]=s.P();y&&(i(y,b,h),h=!1,b&&s.T()>s.M()&&s.A(1,n()))}}},z$=(s,e,t)=>{let n;return[async(i,r)=>{if(!await e())return;n&&n();const o=()=>{const[a,c]=S1();return n=()=>{c(!1)},s.T()&&cE(n,150),[a,s.R(2,()=>{c(!0)})]};if(r&&H$())s.A(8,i()),D$(async()=>{for(;;){let a=!0;for(let[u,h]=s.v();u<=h;u++)if(s.I(u)){a=!1;break}if(a)break;const[c,l]=o();try{if(!await c)return}finally{l()}}s.A(7),t(i(),r)});else for(;;){const[a,c]=o();try{if(s.A(7),t(i()),!await a)return}finally{c()}}},()=>{n&&n()}]},j$=s=>{let e;return{F(t){(e||(e=new($$(F$(t))).ResizeObserver(s))).observe(t)},J(t){e.unobserve(t)},H(){e&&e.disconnect()}}},V$=at({props:{L:{type:Object,required:!0},W:{type:Object,required:!0},X:{type:Object,required:!0},Y:{type:Function,required:!0},D:{type:Number,required:!0},U:{type:Boolean},G:{type:Boolean},K:{type:Boolean},Z:{type:String,required:!0},ee:Object},setup(s){const e=pe(),t=ye(()=>s.L.value&&s.W.O(s.D,s.K)),n=ye(()=>s.L.value&&s.W.I(s.D));return Xe(()=>e.value&&s.D,(i,r,o)=>{o(s.Y(e.value,s.D))},{flush:"post"}),()=>{const{X:i,U:r,G:o,Z:a}=s,c=n.value,{style:l,...u}=s.ee??{},h={contain:"layout style",position:c&&o?void 0:"absolute",[r?"height":"width"]:"100%",[r?"top":"left"]:"0px",[r?"left":"top"]:t.value+"px",visibility:!c||o?void 0:"hidden",...l};return r&&(h.display="inline-flex"),Qe(a,AF({ref:e,style:h},u),typeof(d=i)=="function"||Object.prototype.toString.call(d)==="[object Object]"&&!_2(d)?i:{default:()=>[i],_:2},16,["style"]);var d}}}),G$=(s,e)=>{if(s.length===1){const t=s[0].key;if(t!=null)return t}return"_"+e},q$=(s,e)=>s[0]===e[0]&&s[1]===e[1],K$=at({props:{data:{type:Array,required:!0},bufferSize:Number,itemSize:Number,shift:Boolean,horizontal:Boolean,startMargin:{type:Number,default:0},ssrCount:Number,scrollRef:Object,as:{type:String,default:"div"},item:{type:String,default:"div"},itemProps:Function,keepMounted:Array,cache:Object},emits:["scroll","scrollEnd"],setup(s,{emit:e,expose:t,slots:n}){let i=!!s.ssrCount;const r=s.horizontal,o=pe(),a=U$(s.data.length,s.itemSize,s.ssrCount,s.cache,!s.itemSize),c=((m,v)=>{let g;const y=v?"width":"height",b=new WeakMap,_=j$(w=>{const S=[];for(const{target:C,contentRect:T}of w)if(C.offsetParent)if(C===g)m.A(4,T[y]);else{const k=b.get(C);k!=Gv&&S.push([k,T[y]])}S.length&&m.A(3,S)});return{te(w){_.F(g=w)},re:(w,S)=>(b.set(w,S),_.F(w),()=>{b.delete(w),_.J(w)}),p:_.H}})(a,r),l=((m,v)=>{let g,y,b=S1(),_=!1;const w=v?"scrollLeft":"scrollTop",S=v?"overflowX":"overflowY",[C,T]=z$(m,()=>b[0],(k,A)=>{k=Qk(k,_),A?g.scrollTo({[v?"left":"top"]:k,behavior:"smooth"}):g[w]=k});return{oe(k,A){g=A,v&&(_=getComputedStyle(A).direction==="rtl"),y=W$(m,A,v,()=>Qk(A[w],_),(M,R,P)=>{if(P){const L=A.style,z=L[S];L[S]="hidden",cE(()=>{L[S]=z})}A[w]=Qk(m.N()+M,_),R&&T()}),b[1](!0)},p(){y&&y.H(),b[1](!1),b=S1()},ne:()=>_,se(k){C(()=>k)},ie(k){k+=m.N(),C(()=>k)},le(k,{align:A,smooth:M,offset:R=0}={}){if(k=V2(k,0,m.j()-1),A==="nearest"){const P=m.O(k),L=m.N();if(P<L)A="start";else{if(!(P+m.k(k)>L+m.T()))return;A="end"}}C(()=>R+m.q()+m.O(k)+(A==="end"?m.k(k)-m.T():A==="center"?(m.k(k)-m.T())/2:0),M)},ce:()=>{y&&y.V()}}})(a,r),u=pe(a.m());a.R(1,()=>{u.value=a.m()}),a.R(4,()=>{e("scroll",a.N())}),a.R(8,()=>{e("scrollEnd")});const h=ye(m=>{u.value;const v=a.v(s.bufferSize);return m&&q$(m,v)?m:v}),d=ye(()=>u.value&&a.B()),p=ye(()=>u.value&&a.M());return Cn(()=>{i=!1;const m=o.value,v=requestAnimationFrame(()=>{const g=y=>{c.te(y),l.oe(m,y)};s.scrollRef?g(s.scrollRef):g(m.parentElement)});xM(()=>{cancelAnimationFrame(v)})}),xM(()=>{a.p(),c.p(),l.p()}),Xe(()=>s.data.length,m=>{a.A(5,[m,s.shift])}),Xe(()=>s.startMargin,m=>{a.A(6,m)},{immediate:!0}),Xe([u],()=>{l.ce()},{flush:"post"}),t({get cache(){return a.h()},get scrollOffset(){return a.N()},get scrollSize(){return(m=>Yo(m.M(),m.T()))(a)},get viewportSize(){return a.T()},findItemIndex:a.S,getItemOffset:a.O,getItemSize:a.k,scrollToIndex:l.le,scrollTo:l.se,scrollBy:l.ie}),()=>{const m=s.as,v=s.item,g=p.value,y=l.ne(),b=[],_=S=>{var T;const C=n.default({item:s.data[S],index:S});return Qe(V$,{key:G$(C,S),L:u,W:a,Y:c.re,D:S,X:C,U:r,K:y,G:i,Z:v,ee:(T=s.itemProps)==null?void 0:T.call(s,{item:s.data[S],index:S})},null,8,["L","W","Y","D","X","U","K","G","Z","ee"])};if(s.keepMounted){const S=new Set(s.keepMounted);for(let[C,T]=h.value;C<=T;C++)S.add(C);G2([...S]).forEach(C=>{b.push(_(C))})}else for(let[S,C]=h.value;S<=C;S++)b.push(_(S));return Qe(m,{ref:o,style:{contain:"size style",overflowAnchor:"none",flex:"none",position:"relative",width:r?g+"px":"100%",height:r?"100%":g+"px",pointerEvents:d.value?"none":void 0}},typeof(w=b)=="function"||Object.prototype.toString.call(w)==="[object Object]"&&!_2(w)?b:{default:()=>[b],_:2},8,["style"]);var w}}});function Q$(s,e){const{stopScroll:t,duration:n=300,defaultDirection:i="auto"}=e,r=new Map,o=new Map;let a=null;function c(d,p,m){const v=d.top-p.top,g=p.height/2;return v>g?"up":"down"}function l(){const d=s.value;if(!d){a=null;return}const p=d.getBoundingClientRect(),m=performance.now();let v=!1;for(const[g,y]of r){const b=m-y.startTime;if(!(document.body.contains(d)&&d.contains(y.element))){r.delete(g);continue}const w=y.element.getBoundingClientRect(),S=w.top-p.top,C=w.bottom-p.top;let T=0;y.mode==="up"?T=C-y.initialBottom:T=-(S-y.initialTop);const k=Math.abs(T)>1,A=y.extendOnGrowth&&k&&b>y.duration*.6;if(A&&(y.startTime=m-y.duration*.3),b>=y.duration&&!A){y.phase==="collapse"&&o.delete(g),r.delete(g);continue}v=!0,Math.abs(T)>.5&&(d.scrollTop+=T)}v?a=requestAnimationFrame(l):a=null}function u(d,p,m){const v=s.value;if(!v)return;const g=v.getBoundingClientRect(),y=d.getBoundingClientRect(),b=y.top-g.top,_=y.bottom-g.top;if(_<-50||b>g.height+50)return;const w=(m==null?void 0:m.phase)??"expand",S=(m==null?void 0:m.direction)??i;let C;S!=="auto"?C=S:w==="collapse"&&o.has(p)||w==="expand"&&o.has(p)?C=o.get(p):(C=c(y,g),o.set(p,C));const T=(m==null?void 0:m.extendOnGrowth)??!1;t();const k=r.get(p);r.set(p,{element:d,startTime:performance.now(),duration:(m==null?void 0:m.duration)??n,mode:C,initialTop:b,initialBottom:_,extendOnGrowth:T||(k==null?void 0:k.extendOnGrowth)||!1,phase:w}),a===null&&(a=requestAnimationFrame(l))}function h(){a!==null&&(cancelAnimationFrame(a),a=null),r.clear(),o.clear()}return{anchorBlockElement:u,stopAll:h}}function Se(s){const e=document.createElement("div");return e.textContent=s,e.innerHTML}function uE(s){if(s===0)return"0 B";const e=1024,t=["B","KB","MB","GB"],n=Math.floor(Math.log(s)/Math.log(e));return Math.round(s/Math.pow(e,n)*100)/100+" "+t[n]}function X$(s){if(s<=0)return"0 秒";if(s<60)return`${s} 秒`;const e=Math.floor(s/60),t=s%60;if(e<60)return t>0?`${e} 分 ${t} 秒`:`${e} 分`;const n=Math.floor(e/60),i=e%60;return i===0&&t===0?`${n} 小时`:`${n} 小时 ${i} 分 ${t} 秒`}function as(s,e,t="✗ 失败"){const n=String((s==null?void 0:s.status)||"").toLowerCase();return n==="awaiting_user_answer"?"等待回答":n==="awaiting_approval"||n==="pending_approval"||n==="pending"?"待审批":n==="rejected"?"✗ 已拒绝":n==="cancelled"?"✗ 已取消":s!=null&&s.success?e:t}function hE(s,e,t,n){const i=s.tool,r=i==null?void 0:i.result,o=(i==null?void 0:i.arguments)||{},a=i==null?void 0:i.name;return r?typeof r=="string"?`<div class="tool-result-content scrollable"><pre>${Se(r)}</pre></div>`:a==="web_search"?J$(r,o,e,t,n):a==="extract_webpage"?Z$(r,o):a==="save_webpage"?e3(r,o):a==="create_file"||a==="create_folder"?t3(r,o):a==="write_file"?s3(r,o):a==="edit_file"?n3(r,o):a==="delete_file"?i3(r,o):a==="rename_file"?r3(r,o):a==="read_file"||a==="read_skill"?o3(r,o):a==="create_skill"?S3(r):a==="list_workflows"?w3(r,o):a==="save_workflow"?k3(r,o):a==="vlm_analyze"?a3(r,o):a==="ocr_image"?l3(r,o):a==="view_image"?c3(r,o):a==="terminal_session"?u3(r,o):a==="terminal_input"?h3(r,o):a==="terminal_snapshot"?d3(r,o):a==="sleep"?f3(r,o):a==="run_command"?p3(r,o):a==="update_memory"?g3(r,o):a==="recall_project_memory"?m3(r,o):a==="search_project_memory"?v3(r,o):a==="update_project_memory"?y3(r,o):a==="conversation_search"?b3(r,o):a==="conversation_review"?_3(r,o):a==="ask_user"?A3(r,o):a==="manage_personalization"?E3(r,o):a==="todo_create"?M3(r,o):a==="todo_update_task"?x3(r):a==="trigger_easter_egg"?I3(r,o):a==="create_sub_agent"?R3(r,o):a==="terminate_sub_agent"?L3(r,o):a==="send_message_to_sub_agent"?O3(r,o):a==="answer_sub_agent_question"?D3(r,o):a==="create_custom_agent"?N3(r,o):a==="list_agents"?B3(r):a==="list_active_sub_agents"?F3(r):a==="get_sub_agent_status"?P3(r):Y$(r,o,a):""}function Y$(s,e,t){const n=as(s,"✓ 完成","✗ 失败");let i='<div class="tool-result-meta">';i+=`<div><strong>工具:</strong>${Se(t)}</div>`,i+=`<div><strong>状态:</strong>${Se(n)}</div>`,["path","file_path","agent_id","target_agent_id","question","role_id","url"].forEach(a=>{const c=(e==null?void 0:e[a])??(s==null?void 0:s[a]);if(c!==void 0&&c!==""&&c!==null){const l={path:"路径",file_path:"路径",agent_id:"子智能体 ID",target_agent_id:"目标子智能体 ID",question:"问题",role_id:"角色 ID",url:"URL"},u=typeof c=="string"?c:JSON.stringify(c),h=String(u).slice(0,200),d=String(u).length>200?"…":"";i+=`<div><strong>${Se(l[a]||a)}</strong>${Se(h+d)}</div>`}}),!(s!=null&&s.success)&&(s!=null&&s.error)&&(i+=`<div><strong>错误:</strong>${Se(String(s.error))}</div>`),i+="</div>";const o=(s==null?void 0:s.message)??(s==null?void 0:s.summary)??(s==null?void 0:s.answer)??(s==null?void 0:s.output)??(s==null?void 0:s.content)??(s==null?void 0:s.data)??"";return o&&typeof o=="string"&&o.trim()?(i+='<div class="tool-result-content scrollable">',i+=`<pre>${Se(o.trim())}</pre>`,i+="</div>"):s!=null&&s.success&&(i+='<div class="tool-result-content scrollable">',i+='<div class="tool-result-empty">工具执行完成,无额外可展示内容。</div>',i+="</div>"),i}function J$(s,e,t,n,i){const r=s.query||e.query||"",o=s.filters||{},a=s.total_results||0,c=s.results||[];let l='<div class="tool-result-meta">';return l+=`<div><strong>搜索内容:</strong>${Se(r)}</div>`,l+=`<div><strong>主题:</strong>${Se(t(o))}</div>`,l+=`<div><strong>时间范围:</strong>${Se(n(o))}</div>`,l+=`<div><strong>限定网站:</strong>${Se(i(o))}</div>`,l+=`<div><strong>结果数量:</strong>${a}</div>`,l+="</div>",c.length>0?(l+='<div class="search-result-list">',c.forEach(u=>{l+='<div class="search-result-item">',l+=`<div class="search-result-title">${Se(u.title||"无标题")}</div>`,l+='<div class="search-result-url">',u.url?l+=`<a href="${Se(u.url)}" target="_blank">${Se(u.url)}</a>`:l+="<span>无可用链接</span>",l+="</div></div>"}),l+="</div>"):l+='<div class="tool-result-empty">未返回详细的搜索结果。</div>',l}function Z$(s,e){const t=e.url||s.url||"",n=as(s,"✓ 成功"),i=s.content||s.text||"";let r='<div class="tool-result-meta">';return r+=`<div><strong>URL</strong>${Se(t)}</div>`,r+=`<div><strong>状态:</strong>${n}</div>`,r+="</div>",i&&(r+='<div class="tool-result-content scrollable">',r+=`<pre>${Se(i)}</pre>`,r+="</div>"),r}function e3(s,e){const t=e.url||s.url||"",n=s.path||e.save_path||"",i=as(s,"✓ 已保存");let r='<div class="tool-result-meta">';return r+=`<div><strong>URL</strong>${Se(t)}</div>`,r+=`<div><strong>保存路径:</strong>${Se(n)}</div>`,r+=`<div><strong>状态:</strong>${i}</div>`,r+="</div>",r}function t3(s,e){const t=e.path||s.path||"",n=as(s,"✓ 已创建");let i='<div class="tool-result-meta">';return i+=`<div><strong>路径:</strong>${Se(t)}</div>`,i+=`<div><strong>状态:</strong>${n}</div>`,i+="</div>",i}function s3(s,e){const t=e.file_path||e.path||s.path||"",n=as(s,"✓ 已写入"),i=typeof e.append=="boolean"?e.append:null,r=String(s.mode||"").toLowerCase(),o=i===!0||r==="a"?"追加":i===!1||r==="w"?"覆盖":"无",a=i===!0||r==="a"?e.content||"":s.new_file??e.content??"";let c='<div class="tool-result-meta">';return c+=`<div><strong>路径:</strong>${Se(t)}</div>`,c+=`<div><strong>状态:</strong>${n}</div>`,c+=`<div><strong>模式:</strong>${o}</div>`,!s.success&&s.error&&(c+=`<div><strong>错误:</strong>${Se(String(s.error))}</div>`),c+="</div>",s.success&&a&&(c+='<div class="tool-result-diff scrollable">',a.split(`
`).forEach((u,h)=>{c+=`<div class="diff-line diff-add"><span class="diff-line-number">${h+1}</span><span class="diff-marker">+</span><span class="diff-content">${Se(u)}</span></div>`}),c+="</div>"),c}function n3(s,e){const t=e.file_path||e.path||s.path||"",n=as(s,"✓ 已编辑"),i=typeof s.found_matches=="number"?s.found_matches:typeof s.replacements=="number"?s.replacements:null,r=typeof s.replacements=="number"?s.replacements:null,o=Array.isArray(s.details)?s.details.filter(c=>c&&c.status==="success"):[];let a='<div class="tool-result-meta">';if(a+=`<div><strong>路径:</strong>${Se(t)}</div>`,a+=`<div><strong>状态:</strong>${n}</div>`,a+=`<div><strong>替换组数:</strong>${(s.replacement_groups??o.length)||"无"}</div>`,a+=`<div><strong>找到:</strong>${i??"无"}处</div>`,a+=`<div><strong>替换:</strong>${r??"无"}处</div>`,!s.success&&s.error&&(a+=`<div><strong>错误:</strong>${Se(String(s.error))}</div>`),a+="</div>",!s.success)return a;if(o.length>0){a+='<div class="tool-result-diff scrollable">';const c=(p,m,v,g="")=>{const y=typeof p=="number"&&Number.isFinite(p)?String(p):"";a+=`<div class="diff-line${g?` ${g}`:""}"><span class="diff-line-number">${Se(y)}</span><span class="diff-marker">${Se(m)}</span><span class="diff-content">${Se(v)}</span></div>`},l=[];o.forEach(p=>{const m=p.old_string||"",v=p.new_string||"",g=Array.isArray(p.contexts)?p.contexts:[],y=m?m.split(`
`):[],b=v?v.split(`
`):[],_=w=>{var k;const S=[],C=Number((w==null?void 0:w.old_start_line)??((k=p.matched_lines)==null?void 0:k[0])),T=Number.isFinite(C)?C:null;return m&&y.forEach((A,M)=>{S.push({lineNo:T===null?null:T+M,marker:"-",text:A,className:"diff-remove"})}),v&&b.forEach((A,M)=>{S.push({lineNo:T===null?null:T+M,marker:"+",text:A,className:"diff-add"})}),S};if(g.length>0)g.forEach(w=>{var W,V,N;const S=[],C=Array.isArray(w.before_lines)?w.before_lines:[],T=Array.isArray(w.after_lines)?w.after_lines:[],k=C.length>=2&&C.every(O=>String((O==null?void 0:O.text)??"")==="")?[]:C.length>=2&&String(((W=C[0])==null?void 0:W.text)??"")===""?C.slice(1):C,A=T.length>=2&&T.every(O=>String((O==null?void 0:O.text)??"")==="")?[]:T.length>=2&&String(((V=T[T.length-1])==null?void 0:V.text)??"")===""?T.slice(0,-1):T,M=Number((w==null?void 0:w.old_start_line)??((N=p.matched_lines)==null?void 0:N[0])),R=Number((w==null?void 0:w.old_end_line)??M),P=Number.isFinite(M)&&Number.isFinite(R)?Math.max(1,R-M+1):Math.max(1,m?m.split(`
`).length:1),z=(v===""?0:v.split(`
`).length)-P;k.forEach(O=>{S.push({lineNo:Number(O.line),marker:" ",text:String(O.text??""),className:""})}),S.push(..._(w)),A.forEach(O=>{const H=Number(O.line),G=Number.isFinite(H)?H+z:H;S.push({lineNo:G,marker:" ",text:String(O.text??""),className:""})});const Q=S.filter(O=>typeof O.lineNo=="number"&&Number.isFinite(O.lineNo));l.push({rows:S,minLine:Q.length?Math.min(...Q.map(O=>O.lineNo)):null,maxLine:Q.length?Math.max(...Q.map(O=>O.lineNo)):null})});else{const w=_(),S=w.filter(C=>typeof C.lineNo=="number"&&Number.isFinite(C.lineNo));l.push({rows:w,minLine:S.length?Math.min(...S.map(C=>C.lineNo)):null,maxLine:S.length?Math.max(...S.map(C=>C.lineNo)):null})}});const u=l.sort((p,m)=>(p.minLine??Number.MAX_SAFE_INTEGER)-(m.minLine??Number.MAX_SAFE_INTEGER)),h=[];u.forEach(p=>{const m=h[h.length-1];m&&p.minLine!==null&&m.maxLine!==null&&p.minLine<=m.maxLine+1?(m.rows.push(...p.rows),m.maxLine=Math.max(m.maxLine,p.maxLine??m.maxLine)):h.push({...p,rows:[...p.rows]})});const d={" ":0,"-":1,"+":2};h.forEach((p,m)=>{m>0&&c(null," ","⋮","diff-separator");const v=new Set;p.rows.filter(y=>y.marker!==" "||typeof y.lineNo!="number"?!0:v.has(y.lineNo)?!1:(v.add(y.lineNo),!0)).sort((y,b)=>{const _=y.marker==="-"||y.marker==="+",w=b.marker==="-"||b.marker==="+";return _&&w?(d[y.marker]??9)-(d[b.marker]??9)||(y.lineNo??Number.MAX_SAFE_INTEGER)-(b.lineNo??Number.MAX_SAFE_INTEGER):(y.lineNo??Number.MAX_SAFE_INTEGER)-(b.lineNo??Number.MAX_SAFE_INTEGER)||(d[y.marker]??9)-(d[b.marker]??9)}).forEach(y=>c(y.lineNo,y.marker,y.text,y.className))}),a+="</div>"}return a}function i3(s,e){const t=e.path||s.path||"",n=as(s,"✓ 已删除");let i='<div class="tool-result-meta">';return i+=`<div><strong>路径:</strong>${Se(t)}</div>`,i+=`<div><strong>状态:</strong>${n}</div>`,i+="</div>",i}function r3(s,e){const t=e.old_path||e.source||s.old_path||"",n=e.new_path||e.destination||s.new_path||"",i=as(s,"✓ 已重命名");let r='<div class="tool-result-meta">';return r+=`<div><strong>路径:</strong>${Se(t)}</div>`,r+=`<div><strong>状态:</strong>${i}</div>`,r+=`<div><strong>重命名:</strong>${Se(t)} → ${Se(n)}</div>`,r+="</div>",r}function o3(s,e){const t=e.path||s.path||"",n=as(s,"✓ 成功"),i=s.size||s.file_size||0,r=s.type||"read";let o='<div class="tool-result-meta">';if(o+=`<div><strong>路径:</strong>${Se(t)}</div>`,o+=`<div><strong>状态:</strong>${n}</div>`,i>0&&(o+=`<div><strong>大小:</strong>${uE(i)}</div>`),r!=="read"&&(o+=`<div><strong>模式:</strong>${Se(r)}</div>`),o+="</div>",r==="read"){const a=s.content||s.text||"";a&&(o+='<div class="tool-result-content scrollable">',o+=`<pre>${Se(a)}</pre>`,o+="</div>")}else if(r==="search"){const a=s.matches||[],c=s.query||e.query||"";c&&(o+='<div class="tool-result-meta">',o+=`<div><strong>搜索关键词:</strong>${Se(c)}</div>`,o+=`<div><strong>匹配数量:</strong>${a.length}</div>`,o+="</div>"),a.length>0?(o+='<div class="tool-result-content scrollable">',a.forEach((l,u)=>{u>0&&(o+='<div class="search-match-separator">⋯</div>'),o+='<div class="search-match-item">';const h=l.line_start===l.line_end?`${l.line_start}`:`${l.line_start}-${l.line_end}`;o+=`<div class="search-match-line">行 ${h}</div>`,o+=`<pre>${Se(l.snippet||l.content||"")}</pre>`,o+="</div>"}),o+="</div>"):o+='<div class="tool-result-empty">未找到匹配内容</div>'}else if(r==="extract"){const a=s.segments||[];a.length>0?(o+='<div class="tool-result-meta">',o+=`<div><strong>提取片段数:</strong>${a.length}</div>`,o+="</div>",o+='<div class="tool-result-content scrollable">',a.forEach((c,l)=>{l>0&&(o+='<div class="segment-separator">⋯</div>'),o+='<div class="segment-item">';const u=c.start_line||c.line_start||"?",h=c.end_line||c.line_end||"?";o+=`<div class="segment-range">行 ${u}-${h}</div>`,o+=`<pre>${Se(c.content||c.text||"")}</pre>`,o+="</div>"}),o+="</div>"):o+='<div class="tool-result-empty">未提取到内容</div>'}return o}function a3(s,e){const t=e.image_path||e.path||s.path||"",n=as(s,"✓ 成功"),i=s.analysis||s.result||"";let r='<div class="tool-result-meta">';return r+=`<div><strong>路径:</strong>${Se(t)}</div>`,r+=`<div><strong>状态:</strong>${n}</div>`,r+="</div>",i&&(r+='<div class="tool-result-content scrollable">',r+='<div class="content-label">分析结果:</div>',r+=`<pre>${Se(i)}</pre>`,r+="</div>"),r}function l3(s,e){const t=e.image_path||e.path||s.path||"",n=as(s,"✓ 成功"),i=s.size||s.file_size||0,r=s.text||s.ocr_text||"",o=s.image_url||s.url||"";let a='<div class="tool-result-meta">';return a+=`<div><strong>路径:</strong>${Se(t)}</div>`,a+=`<div><strong>状态:</strong>${n}</div>`,i>0&&(a+=`<div><strong>大小:</strong>${uE(i)}</div>`),a+="</div>",o&&(a+=`<div class="tool-result-image"><img src="${Se(o)}" alt="OCR图片" style="max-width: 100%; height: auto;" /></div>`),r&&(a+='<div class="tool-result-content scrollable">',a+='<div class="content-label">识别文本:</div>',a+=`<pre>${Se(r)}</pre>`,a+="</div>"),a}function c3(s,e){const t=e.image_path||e.path||s.path||"",n=as(s,"✓ 成功"),i=s.size||s.file_size||0;let r=s.image_url||s.url||"";!r&&t&&s.success!==!1&&(r=`/api/file/content?path=${encodeURIComponent(t)}`);let o='<div class="tool-result-meta">';if(o+=`<div><strong>路径:</strong>${Se(t)}</div>`,o+=`<div><strong>状态:</strong>${n}</div>`,i>0&&(o+=`<div><strong>大小:</strong>${uE(i)}</div>`),o+="</div>",r){const a=Se(r);o+=`<div class="tool-result-image"><a href="${a}" target="_blank" rel="noopener" title="在新窗口查看原图"><img src="${a}" alt="查看图片" loading="lazy" /></a></div>`}return o}function u3(s,e){const t=e.operation||e.action||"start",n=e.session_name||e.name||s.session_name||"",i=as(s,"✓ 成功");let r='<div class="tool-result-meta">';return r+=`<div><strong>操作:</strong>${Se(t)}</div>`,r+=`<div><strong>终端名:</strong>${Se(n)}</div>`,r+=`<div><strong>状态:</strong>${i}</div>`,r+="</div>",r}function h3(s,e){const t=e.command||e.input||"",n=e.output_wait||30,i=s.output||s.result||"";let r='<div class="tool-result-meta">';return r+=`<div><strong>指令:</strong>${Se(t)}</div>`,r+=`<div><strong>等待时间:</strong>${n}秒</div>`,r+="</div>",i&&(r+='<div class="tool-result-content scrollable">',r+='<div class="content-label">输出:</div>',r+=`<pre>${Se(i)}</pre>`,r+="</div>"),r}function d3(s,e){const t=e.session_name||e.name||s.session_name||"",n=as(s,"✓ 成功"),i=e.start_line||0,r=e.end_line||0,o=s.content||s.output||"";let a='<div class="tool-result-meta">';return a+=`<div><strong>状态:</strong>${n}</div>`,a+=`<div><strong>终端名:</strong>${Se(t)}</div>`,(i||r)&&(a+=`<div><strong>行范围:</strong>${i} - ${r}</div>`),a+="</div>",o&&(a+='<div class="tool-result-content scrollable">',a+='<div class="content-label">获取的内容:</div>',a+=`<pre>${Se(o)}</pre>`,a+="</div>"),a}function f3(s,e){const t=as(s,"✓ 完成"),n=(s==null?void 0:s.mode)||"seconds";let i='<div class="tool-result-meta">';if(i+=`<div><strong>状态:</strong>${t}</div>`,i+=`<div><strong>模式:</strong>${Se(n)}</div>`,n==="seconds"||n===""||n===null){const r=e.seconds||e.duration||0;i+=`<div><strong>等待时间:</strong>${r}秒</div>`,e.reason&&(i+=`<div><strong>原因:</strong>${Se(String(e.reason))}</div>`)}else if(n==="wait_sub_agent_output"){const r=(s==null?void 0:s.agent_id)??(e==null?void 0:e.wait_sub_agent_output_ids)??"";r!==""&&(i+=`<div><strong>等待子智能体:</strong>#${Se(String(r))}</div>`)}else if(n==="wait_sub_agent_ids"){const r=Array.isArray(s==null?void 0:s.agent_ids)?s.agent_ids:[];r.length>0&&(i+=`<div><strong>等待子智能体:</strong>${r.map(String).join(", ")}</div>`);const o=Array.isArray(s==null?void 0:s.waited_task_ids)?s.waited_task_ids:[];o.length>0&&(i+=`<div><strong>任务 ID</strong>${o.map(String).join(", ")}</div>`)}else if(n==="wait_runcommand_id"){const r=(s==null?void 0:s.command_id)??(e==null?void 0:e.wait_runcommand_id)??"";r!==""&&(i+=`<div><strong>后台命令 ID</strong>${Se(String(r))}</div>`)}if(!(s!=null&&s.success)&&(s!=null&&s.error)&&(i+=`<div><strong>错误:</strong>${Se(String(s.error))}</div>`),i+="</div>",n==="seconds"||n===""||n===null){const r=(s==null?void 0:s.message)||"";r&&(i+='<div class="tool-result-content scrollable">',i+='<div class="content-label">结果:</div>',i+=`<pre>${Se(String(r))}</pre>`,i+="</div>")}else if(n==="wait_sub_agent_output"){const r=(s==null?void 0:s.message)||"";r&&(i+='<div class="tool-result-content scrollable">',i+='<div class="content-label">子智能体输出:</div>',i+=`<pre>${Se(String(r))}</pre>`,i+="</div>")}else if(n==="wait_sub_agent_ids"){const r=Array.isArray(s==null?void 0:s.results)?s.results:[];r.length>0&&(i+='<div class="tool-result-content scrollable">',i+=`<div class="content-label">已等待 ${r.length} 个子智能体:</div>`,r.forEach(o=>{if(!o||typeof o!="object")return;const a=o.agent_id??"?",c=o.task_id??"?",l=o.status??"unknown",u=o.success===!0;i+='<div class="sub-agent-result-item">',i+=`<div><strong>子智能体 #${Se(String(a))}</strong>(任务 ${Se(String(c))})· ${Se(String(l))} · ${u?"✓ 成功":"✗ 失败"}</div>`;const h=o.message||o.error||"";if(h){const d=o.runtime_seconds??o.elapsed_seconds??null,p=d!==null?`运行 ${Math.round(Number(d))} 秒`:"",m=o.stats;if(p||m){if(i+='<div class="sub-agent-meta">',p&&(i+=`<span>${Se(p)}</span>`),m&&typeof m=="object"){const v=[];m.api_calls!=null&&v.push(`调用 ${m.api_calls} 次`),m.files_read!=null&&v.push(`阅读 ${m.files_read} 次`),m.edit_files!=null&&v.push(`编辑 ${m.edit_files} 次`),m.searches!=null&&v.push(`搜索 ${m.searches} 次`),m.web_pages!=null&&v.push(`网页 ${m.web_pages} 个`),m.commands!=null&&v.push(`命令 ${m.commands} 个`),v.length>0&&(i+=`<span>${Se(v.join(" | "))}</span>`)}i+="</div>"}i+=`<pre>${Se(String(h))}</pre>`}i+="</div>"}),i+="</div>")}else if(n==="wait_runcommand_id"){const r=s==null?void 0:s.result;if(r&&typeof r=="object"){const o=r.output||r.stdout||"",a=r.exit_code!==void 0?r.exit_code:r.returncode;i+='<div class="tool-result-content scrollable">',i+='<div class="content-label">后台命令输出:</div>',a!==void 0&&(i+=`<div><strong>退出码:</strong>${Se(String(a))}</div>`),o?i+=`<pre>${Se(String(o))}</pre>`:i+='<div class="tool-result-empty">[无输出]</div>',i+="</div>"}}return i}function p3(s,e){const t=e.command||"",n=e.timeout||30,i=s.output||s.stdout||"",r=s.exit_code!==void 0?s.exit_code:s.returncode;let o='<div class="tool-result-meta">';return o+=`<div><strong>指令:</strong>${Se(t)}</div>`,o+=`<div><strong>超时时间:</strong>${n}秒</div>`,r!==void 0&&(o+=`<div><strong>退出码:</strong>${r}</div>`),o+="</div>",i&&(o+='<div class="tool-result-content scrollable">',o+='<div class="content-label">输出:</div>',o+=`<pre>${Se(i)}</pre>`,o+="</div>"),o}function g3(s,e){const t=e.operation||s.operation||"",n=e.content||"",i=e.index||s.index,r=s.count||0;let o='<div class="tool-result-meta">';return t==="append"?(o+="<div>新增记忆</div>",o+=`<div>${r}. ${Se(n)}</div>`):t==="replace"?(o+="<div>更新记忆</div>",o+=`<div>${i}. ${Se(n)}</div>`):t==="delete"&&(o+="<div>删除记忆</div>",o+=`<div>${i}. ${Se(n||"已删除")}</div>`),o+="</div>",o}function m3(s,e){const t=e.name||s.memory_name||"",n=as(s,"✓ 已读取"),i=s.content||s.text||"";let r='<div class="tool-result-meta">';return r+=`<div><strong>状态:</strong>${n}</div>`,r+=`<div><strong>记忆:</strong>${Se(t)}</div>`,r+="</div>",s.success&&i?(r+='<div class="tool-result-content scrollable">',r+=`<pre>${Se(i)}</pre>`,r+="</div>"):!s.success&&s.error&&(r+=`<div class="tool-result-error">${Se(String(s.error))}</div>`),r}function v3(s,e){const t=Array.isArray(s==null?void 0:s.keywords)?s.keywords:Array.isArray(e==null?void 0:e.keywords)?e.keywords:[],n=Array.isArray(s==null?void 0:s.results)?s.results:[],i=as(s,"✓ 完成");let r='<div class="tool-result-meta">';return r+=`<div><strong>关键词:</strong>${Se(t.join(" / ")||"(未指定)")}</div>`,r+=`<div><strong>状态:</strong>${i}</div>`,r+=`<div><strong>命中记忆:</strong>${n.length} 条</div>`,!(s!=null&&s.success)&&(s!=null&&s.error)&&(r+=`<div><strong>错误:</strong>${Se(String(s.error))}</div>`),r+="</div>",n.length?(r+='<div class="search-result-list">',n.forEach(o=>{r+='<div class="search-result-item">',r+=`<div class="search-result-title">${Se(o.name||o.file||"")}</div>`,o.description&&(r+=`<div><strong>描述:</strong>${Se(o.description)}</div>`);const a=Array.isArray(o.snippets)?o.snippets:[];a.length>0&&(r+='<div class="search-match-item">',a.forEach(c=>{const l=`L${c.line??"?"}: ${c.text||""}`,u=Se(l);r+=`<div class="search-match-snippet" title="${u.replace(/"/g,"&quot;")}">${u}</div>`}),r+="</div>"),r+="</div>"}),r+="</div>",r):(s!=null&&s.success&&(r+='<div class="tool-result-empty">未找到匹配的项目记忆。</div>'),r)}function y3(s,e){const t=e.name||s.memory_name||"",n=e.description||"",i=e.content||"",r=as(s,"✓ 已更新");let o='<div class="tool-result-meta">';return o+=`<div><strong>状态:</strong>${r}</div>`,o+=`<div><strong>记忆:</strong>${Se(t)}</div>`,n&&(o+=`<div><strong>描述:</strong>${Se(n)}</div>`),!s.success&&s.error&&(o+=`<div><strong>错误:</strong>${Se(String(s.error))}</div>`),o+="</div>",s.success&&i&&(o+='<div class="tool-result-content scrollable">',o+='<div class="content-label">记忆内容:</div>',o+=`<pre>${Se(i)}</pre>`,o+="</div>"),o}function b3(s,e){const t=Array.isArray(s==null?void 0:s.results)?s.results:[],n=Array.isArray(s==null?void 0:s.keywords)?s.keywords:Array.isArray(e==null?void 0:e.keywords)?e.keywords:[],i=n.length?n.join(" / "):(s==null?void 0:s.query)||(e==null?void 0:e.query)||"(未指定)";let r='<div class="tool-result-meta">';return r+=`<div><strong>关键词:</strong>${Se(i)}</div>`,r+=`<div><strong>日期范围:</strong>${Se((s==null?void 0:s.start_date)||(e==null?void 0:e.start_date)||"不限")} ~ ${Se((s==null?void 0:s.end_date)||(e==null?void 0:e.end_date)||"不限")}</div>`,r+="<div><strong>范围:</strong>当前工作区历史对话(已排除当前对话)</div>",r+=`<div><strong>结果数量:</strong>${t.length}</div>`,r+="</div>",t.length?(r+='<div class="search-result-list">',t.forEach(o=>{r+='<div class="search-result-item">',r+=`<div class="search-result-title">${Se(o.title||"未命名对话")}</div>`,r+=`<div><strong>ID</strong>${Se(o.id||"")}</div>`,r+=`<div><strong>规模:</strong>${Se(String(o.total_messages||0))} 条消息,${Se(String(o.total_tools||0))} 个工具</div>`,o.first_user_message&&(r+=`<div><strong>首条用户消息:</strong>${Se(o.first_user_message)}</div>`),o.updated_at&&(r+=`<div><strong>更新时间:</strong>${Se(o.updated_at)}</div>`),r+="</div>"}),r+="</div>",r):(r+='<div class="tool-result-empty">未找到匹配对话。</div>',r)}function _3(s,e){const t=as(s,(s==null?void 0:s.mode)==="read"?"✓ 已返回":"✓ 已生成");let n='<div class="tool-result-meta">';return n+=`<div><strong>对话 ID</strong>${Se((s==null?void 0:s.conversation_id)||(e==null?void 0:e.conversation_id)||"")}</div>`,n+=`<div><strong>状态:</strong>${t}</div>`,n+=`<div><strong>模式:</strong>${Se((s==null?void 0:s.mode)||(e==null?void 0:e.mode)||"")}</div>`,s!=null&&s.title&&(n+=`<div><strong>标题:</strong>${Se(s.title)}</div>`),s!=null&&s.path&&(n+=`<div><strong>回顾文件:</strong>${Se(s.path)}</div>`),(s==null?void 0:s.char_count)!==void 0&&(n+=`<div><strong>字符数:</strong>${Se(String(s.char_count))}</div>`),n+="</div>",!(s!=null&&s.success)&&(s!=null&&s.error)&&(n+=`<div class="tool-result-error">${Se(s.error)}</div>`),s!=null&&s.too_long&&(s!=null&&s.path)&&(n+='<div class="tool-result-warning">内容太长,已保存到文件,请分段或查找阅读。</div>'),s!=null&&s.content&&(n+='<div class="tool-result-content scrollable">',n+='<div class="content-label">回顾内容:</div>',n+=`<pre>${Se(s.content)}</pre>`,n+="</div>"),n}function S3(s){const e=as(s,"✓ 已归档");let t='<div class="tool-result-meta">';return t+=`<div><strong>状态:</strong>${e}</div>`,s!=null&&s.skill_name&&(t+=`<div><strong>Skill</strong>${Se(s.skill_name)}</div>`),t+="</div>",!(s!=null&&s.success)&&(s!=null&&s.error)&&(t+=`<div class="tool-result-error">${Se(s.error)}</div>`),s!=null&&s.sync_warning&&(t+=`<div class="tool-result-warning">${Se(s.sync_warning)}</div>`),t}function w3(s,e){if(!(s!=null&&s.success)){const r=(s==null?void 0:s.error)??"查询失败";return`<div class="tool-result-error">⚠️ ${Se(String(r))}</div>`}const t=String((e==null?void 0:e.name)||(s==null?void 0:s.workflow_name)||"");if(t){let r='<div class="tool-result-meta">';r+=`<div><strong>工作流:</strong>${Se(t)}</div>`,r+="</div>";const o=String((s==null?void 0:s.message)||"");return o&&(r+='<div class="tool-result-content scrollable">',r+=`<pre>${Se(o)}</pre>`,r+="</div>"),r}const n=Array.isArray(s==null?void 0:s.workflows)?s.workflows:[];if(n.length===0)return'<div class="tool-result-empty">当前没有可用工作流。</div>';let i='<div class="tool-result-meta">';return i+=`<div><strong>工作流数量:</strong>${n.length}</div>`,i+="</div>",i+='<div class="search-result-list">',n.forEach(r=>{const o=Se(String((r==null?void 0:r.name)||"未命名")),a=Se(String((r==null?void 0:r.description)||"(无描述)")),c=(r==null?void 0:r.source)==="builtin"?"内置":"用户",l=Number((r==null?void 0:r.nodeCount)||0);i+='<div class="search-result-item">',i+=`<div class="search-result-title">${o}</div>`,i+=`<div>${a}</div>`,i+=`<div><strong>来源:</strong>${c} | <strong>节点:</strong>${l}</div>`,i+="</div>"}),i+="</div>",i}function k3(s,e){const t=as(s,"✓ 已归档");let n='<div class="tool-result-meta">';n+=`<div><strong>状态:</strong>${t}</div>`;const i=String((e==null?void 0:e.source_dir)||"");return i&&(n+=`<div><strong>源目录:</strong>${Se(i)}</div>`),s!=null&&s.workflow_name&&(n+=`<div><strong>工作流:</strong>${Se(String(s.workflow_name))}</div>`),s!=null&&s.success&&typeof(s==null?void 0:s.node_count)=="number"&&(n+=`<div><strong>节点数:</strong>${s.node_count}</div>`),s!=null&&s.success&&(s!=null&&s.overwritten)?n+="<div><strong>模式:</strong>覆盖已有版本</div>":s!=null&&s.success&&(s!=null&&s.shadows_builtin)&&(n+="<div><strong>模式:</strong>用户副本(遮蔽同名内置)</div>"),n+="</div>",!(s!=null&&s.success)&&(s!=null&&s.error)&&(n+=`<div class="tool-result-error">${Se(String(s.error))}</div>`),s!=null&&s.success&&(s!=null&&s.summary)&&(n+='<div class="tool-result-content">',n+=Se(String(s.summary)),n+="</div>"),n}function C3(s){return{self_identify:"AI 自称",user_name:"用户称呼",profession:"用户职业",tone:"交流语气",considerations:"注意事项",theme:"主题",communication_style:"交流风格",conversation_continuity:"对话连续性",enabled:"个性化开关"}[s]||s}function T3(s,e){return e==null||e===""?"未设置":s==="enabled"?e?"开启":"关闭":s==="considerations"?typeof e!="string"||e.trim()===""?"未设置":e.trim():s==="communication_style"?{default:"default标准 AI 风格)",human_like:"human_like拟人聊天风格",auto:"auto自动"}[String(e)]||String(e):s==="conversation_continuity"&&{low:"low",medium:"medium",high:"high"}[String(e)]||String(e)}function A3(s,e){const t=e.question||s.question||"",n=e.context||s.context||"",i=as(s,"✓ 已回答"),r=s.status==="answered"?String(s.answer_text||s.message||"").trim():"";let o='<div class="tool-result-meta">';o+=`<div><strong>状态:</strong>${Se(i)}</div>`,t&&(o+=`<div><strong>问题:</strong>${Se(String(t))}</div>`),n&&(o+=`<div><strong>说明:</strong>${Se(String(n))}</div>`),o+="</div>";const a=Array.isArray(e.options)?e.options:[];return a.length>0&&(o+='<div class="tool-result-content">',o+='<div class="tool-result-meta">',o+="<div><strong>提供的选项:</strong></div>",a.forEach((c,l)=>{const u=String((c==null?void 0:c.label)||(c==null?void 0:c.id)||`选项 ${l+1}`),h=String((c==null?void 0:c.description)||"").trim();o+=`<div>${l+1}. ${Se(u)}${h?` — ${Se(h)}`:""}</div>`}),o+="</div></div>"),r&&(o+='<div class="tool-result-content">',o+='<div class="tool-result-meta">',r.split(`
`).map(c=>c.trim()).filter(Boolean).forEach(c=>{const l=c.indexOf("");if(l>0){const u=c.slice(0,l+1),h=c.slice(l+1);o+=`<div><strong>${Se(u)}</strong>${Se(h)}</div>`}else o+=`<div><strong>用户回答:</strong>${Se(c)}</div>`}),o+="</div></div>"),o}function E3(s,e){const t=String(e.action||s.action||"read"),n=as(s,t==="update"?"✓ 已更新":"✓ 已读取"),i=String(s.updated_field||e.field||""),r=s.updated_value??e.value;let o='<div class="tool-result-meta">';return o+=`<div><strong>操作:</strong>${Se(t==="update"?"更新配置":"读取配置")}</div>`,o+=`<div><strong>状态:</strong>${n}</div>`,s!=null&&s.success?(t==="update"&&i&&(o+=`<div><strong>修改项:</strong>${Se(C3(i))}</div>`,o+=`<div><strong>修改后:</strong>${Se(T3(i,r))}</div>`),o+="</div>",o):(s!=null&&s.error&&(o+=`<div><strong>错误:</strong>${Se(String(s.error))}</div>`),Array.isArray(s==null?void 0:s.validation_errors)&&s.validation_errors.length>0&&(o+=`<div><strong>校验:</strong>${Se(s.validation_errors.join(""))}</div>`),o+="</div>",o)}function M3(s,e){const t=as(s,"✓ 已创建"),n=s.todo_list||{},i=n.title||e.title||"",r=n.tasks||e.tasks||[];let o='<div class="tool-result-meta">';return o+=`<div><strong>状态:</strong>${t}</div>`,o+=`<div><strong>标题:</strong>${Se(i)}</div>`,o+="</div>",r.length>0&&(o+='<div class="tool-result-content">',o+='<div class="todo-list">',r.forEach(a=>{const c=typeof a=="string"?a:a.text||a.title||a.content||"";o+=`<div class="todo-item"><input type="checkbox" disabled /> ${Se(c)}</div>`}),o+="</div>",o+="</div>"),o}function x3(s){const e=as(s,"✓ 已更新"),t=s.todo_list||{},n=t.title||"",i=t.tasks||[];let r='<div class="tool-result-meta">';return r+=`<div><strong>状态:</strong>${e}</div>`,r+=`<div><strong>标题:</strong>${Se(n)}</div>`,r+="</div>",i.length>0&&(r+='<div class="tool-result-content">',r+='<div class="todo-list">',i.forEach(o=>{const a=typeof o=="string"?o:o.text||o.title||o.content||"",c=typeof o=="object"&&(o.status==="done"||o.completed||o.done||o.checked);r+=`<div class="todo-item"><input type="checkbox" ${c?"checked":""} disabled /> ${Se(a)}</div>`}),r+="</div>",r+="</div>"),r}function I3(s,e){const t=as(s,"✓ 已触发"),n=s.type||e.type||"",i=s.content||s.message||"";let r='<div class="tool-result-meta">';return r+=`<div><strong>状态:</strong>${t}</div>`,r+=`<div><strong>类型:</strong>${Se(n)}</div>`,r+="</div>",i&&(r+='<div class="tool-result-content">',r+=`<div class="easter-egg-content">${Se(i)}</div>`,r+="</div>"),r}function R3(s,e){const t=as(s,"✓ 已创建","✗ 创建失败"),n=s.agent_id??e.agent_id??"",i=s.task_id??"",r=s.deliverables_dir??"",o=e.task??"",a=s.message??s.summary??"",c=s.stats||{},l=s.runtime_seconds??s.elapsed_seconds??c.runtime_seconds??0,u=c.api_calls??c.turn_count??0,h=(c.files_read||0)+(c.write_files||0)+(c.edit_files||0)+(c.searches||0)+(c.web_pages||0)+(c.commands||0),d=l>0||u>0||h>0;let p='<div class="tool-result-meta">';if(p+=`<div><strong>状态:</strong>${t}</div>`,n!==""&&(p+=`<div><strong>子智能体 ID</strong>${Se(String(n))}</div>`),i!==""&&(p+=`<div><strong>任务 ID</strong>${Se(String(i))}</div>`),r!==""&&(p+=`<div><strong>交付目录:</strong>${Se(String(r))}</div>`),o){const m=String(o).slice(0,200),v=String(o).length>200?"…":"";p+=`<div><strong>任务:</strong>${Se(m+v)}</div>`}return p+="</div>",(a||d)&&(p+='<div class="tool-result-content scrollable">',d&&(p+='<div class="content-label">执行统计</div>',l>0&&(p+=`<div><strong>工作时间:</strong>${X$(l)}</div>`),u>0&&(p+=`<div><strong>调用次数:</strong>${u} 次</div>`),h>0&&(p+=`<div><strong>工具次数:</strong>${h} 次</div>`)),a&&(d&&(p+='<div class="content-label">最终回复</div>'),p+=`<div>${Se(String(a))}</div>`),p+="</div>"),p}function L3(s,e){const t=as(s,"✓ 已关闭","✗ 关闭失败"),n=s.agent_id??e.agent_id??"",i=s.task_id??"",r=s.message??s.system_message??"";let o='<div class="tool-result-meta">';return o+=`<div><strong>状态:</strong>${t}</div>`,n!==""&&(o+=`<div><strong>子智能体 ID</strong>${Se(String(n))}</div>`),i!==""&&(o+=`<div><strong>任务 ID</strong>${Se(String(i))}</div>`),o+="</div>",r&&(o+='<div class="tool-result-content scrollable">',o+=`<div>${Se(String(r))}</div>`,o+="</div>"),o}function P3(s){if(!s.success){const n=s.error??"查询失败";return`<div class="tool-result-error">⚠️ ${Se(String(n))}</div>`}const e=Array.isArray(s.results)?s.results:[];if(e.length===0)return'<div class="tool-result-empty">未返回子智能体状态。</div>';let t='<div class="sub-agent-status-list">';return e.forEach(n=>{var l,u;const i=n.agent_id??"",r=n.found!==!1,o=String(n.status||""),a=n.task_id??"",c=n.summary??((l=n.final_result)==null?void 0:l.message)??((u=n.final_result)==null?void 0:u.summary)??"";t+='<div class="sub-agent-status-item">',t+=`<div class="sub-agent-status-header">子智能体 #${Se(String(i))}</div>`,r?(t+='<div class="tool-result-meta">',o==="completed"?t+="<div><strong>状态:</strong>已完成</div>":o==="terminated"?t+="<div><strong>状态:</strong>已终止</div>":o==="running"?t+="<div><strong>状态:</strong>运行中</div>":o==="pending"?t+="<div><strong>状态:</strong>等待中</div>":t+=`<div><strong>状态:</strong>${Se(o||"未知")}</div>`,a!==""&&(t+=`<div><strong>任务 ID</strong>${Se(String(a))}</div>`),t+="</div>",c&&(t+='<div class="tool-result-content scrollable">',t+=`<div>${Se(String(c))}</div>`,t+="</div>")):(t+='<div class="tool-result-meta">',t+="<div><strong>状态:</strong>不存在</div>",t+="</div>"),t+="</div>"}),t+="</div>",t}function O3(s,e){const t=as(s,"✓ 已发送","✗ 发送失败"),n=e.agent_id??s.agent_id??"";let i='<div class="tool-result-meta">';return i+=`<div><strong>状态:</strong>${t}</div>`,n!==""&&(i+=`<div><strong>子智能体 ID</strong>${Se(String(n))}</div>`),!(s!=null&&s.success)&&(s!=null&&s.error)&&(i+=`<div><strong>错误:</strong>${Se(String(s.error))}</div>`),i+="</div>",i}function D3(s,e){const t=as(s,"✓ 已回复","✗ 回复失败"),n=e.question_id??s.question_id??"",i=e.answer??"";let r='<div class="tool-result-meta">';if(r+=`<div><strong>状态:</strong>${t}</div>`,n&&(r+=`<div><strong>问题 ID</strong>${Se(String(n))}</div>`),!(s!=null&&s.success)&&(s!=null&&s.error)&&(r+=`<div><strong>错误:</strong>${Se(String(s.error))}</div>`),r+="</div>",i&&typeof i=="string"){r+='<div class="tool-result-content scrollable">',r+='<div class="content-label">回复内容</div>';const o=String(i).slice(0,500),a=String(i).length>500?"…":"";r+=`<pre>${Se(o+a)}</pre>`,r+="</div>"}return r}function N3(s,e){const t=!!(s!=null&&s.overwritten),n=s!=null&&s.success?t?"✓ 已覆盖更新":"✓ 已创建":"✗ 创建失败",i=e.role_id??s.role_id??"",r=e.name??s.name??i;let o='<div class="tool-result-meta">';return o+=`<div><strong>状态:</strong>${n}</div>`,i!==""&&(o+=`<div><strong>角色 ID</strong>${Se(String(i))}</div>`),r&&r!==i&&(o+=`<div><strong>角色名:</strong>${Se(String(r))}</div>`),!(s!=null&&s.success)&&(s!=null&&s.error)&&(o+=`<div><strong>错误:</strong>${Se(String(s.error))}</div>`),o+="</div>",o}function B3(s){if(!(s!=null&&s.success)){const n=(s==null?void 0:s.error)??"查询失败";return`<div class="tool-result-error">⚠️ ${Se(String(n))}</div>`}const e=Array.isArray(s.roles)?s.roles:[];if(e.length===0)return'<div class="tool-result-empty">当前没有可用角色。</div>';let t='<div class="tool-result-meta">';return t+=`<div><strong>角色数量:</strong>${e.length}</div>`,t+="</div>",t+='<div class="search-result-list">',e.forEach(n=>{const i=n.role_id||"未知",r=n.name||i,o=n.description||"",a=n.thinking_mode||"fast",c=n.is_custom?"是":"否";t+='<div class="search-result-item">',t+=`<div class="search-result-title">${Se(i)} — ${Se(r)}</div>`,o&&(t+=`<div>${Se(o)}</div>`),t+=`<div><strong>思考模式:</strong>${Se(a)} | <strong>自定义:</strong>${Se(c)}</div>`,t+="</div>"}),t+="</div>",t}function F3(s){if(!(s!=null&&s.success)){const n=(s==null?void 0:s.error)??"查询失败";return`<div class="tool-result-error">⚠️ ${Se(String(n))}</div>`}const e=Array.isArray(s.agents)?s.agents:[];if(e.length===0)return'<div class="tool-result-empty">当前会话没有活跃子智能体。</div>';let t='<div class="tool-result-meta">';return t+=`<div><strong>活跃数量:</strong>${e.length}</div>`,t+="</div>",t+='<div class="sub-agent-status-list">',e.forEach(n=>{const i=n.agent_id??"?",r=n.display_name||`Agent_${i}`,o=n.status||"unknown",a=n.summary||"",c=n.last_output||"";if(t+='<div class="sub-agent-status-item">',t+=`<div class="sub-agent-status-header">#${Se(String(i))} ${Se(r)} [${Se(o)}]</div>`,t+='<div class="tool-result-meta">',a&&(t+=`<div><strong>任务:</strong>${Se(String(a))}</div>`),c){const l=String(c).slice(0,120),u=String(c).length>120?"…":"";t+=`<div><strong>最近输出:</strong>${Se(l+u)}</div>`}t+="</div>",t+="</div>"}),t+="</div>",t}const $3=["data-block-id"],H3={class:"status-icon"},U3={class:"status-text"},W3={class:"tool-desc"},z3={class:"content-inner"},j3=["innerHTML"],V3={key:0,class:"progress-indicator"},zM=at({name:"ToolAction",__name:"ToolAction",props:{action:{},expanded:{type:Boolean},blockId:{},iconStyle:{type:Function},getToolAnimationClass:{type:Function},getToolIcon:{type:Function},getToolStatusText:{type:Function},getToolDescription:{type:Function},formatSearchTopic:{type:Function},formatSearchTime:{type:Function},formatSearchDomains:{type:Function},streamingMessage:{type:Boolean},registerCollapseContent:{type:Function},collapseKey:{}},emits:["toggle"],setup(s){const e=s;function t(){return hE(e.action,e.formatSearchTopic,e.formatSearchTime,e.formatSearchDomains)}return(n,i)=>(F(),$("div",{class:ke(["collapsible-block tool-block",{expanded:s.expanded,processing:s.action.tool.status==="preparing"||s.action.tool.status==="running",completed:s.action.tool.status==="completed"}]),"data-block-id":s.blockId||s.collapseKey||s.action.tool.id||s.action.id||"tool"},[E("div",{class:"collapsible-header",onClick:i[0]||(i[0]=r=>n.$emit("toggle"))},[i[1]||(i[1]=E("div",{class:"arrow"},null,-1)),E("div",H3,[E("span",{class:ke(["tool-icon icon icon-md",s.getToolAnimationClass(s.action.tool)]),style:Ke(s.iconStyle(s.getToolIcon(s.action.tool))),"aria-hidden":"true"},null,6)]),E("span",U3,ae(s.getToolStatusText(s.action.tool)),1),E("span",W3,ae(s.getToolDescription(s.action.tool)),1)]),E("div",{class:"collapsible-content",ref:r=>s.registerCollapseContent&&s.registerCollapseContent(s.collapseKey||s.action.tool.id||s.action.id||"tool",r)},[E("div",z3,[E("div",{innerHTML:t()},null,8,j3)])],512),s.action.tool.status==="preparing"||s.action.tool.status==="running"?(F(),$("div",V3)):ge("",!0)],10,$3))}}),G3="data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%2024%2024'%20fill='none'%20stroke='currentColor'%20stroke-width='2'%20stroke-linecap='round'%20stroke-linejoin='round'%3e%3cpath%20d='M15%2012H3m14%206H3M21%206H3'%20/%3e%3c/svg%3e",q3={class:"more-copy"},K3={class:"more-title"},Q3={class:"more-desc"},X3=["data-block-id"],Y3=["onClick"],J3={class:"status-icon"},Z3={class:"status-text"},e5=["onScroll"],t5=["data-block-id"],s5=["onClick"],n5={class:"status-icon"},i5={class:"status-text"},r5={class:"tool-desc"},o5={class:"content-inner"},a5=["innerHTML"],l5={key:0,class:"progress-indicator"},Xk=6,c5=600,u5=36,h5=at({name:"StackedBlocks",__name:"StackedBlocks",props:{actions:{},expandedBlocks:{},conversationRunning:{type:Boolean},isLatestMessage:{type:Boolean},iconStyle:{type:Function},toggleBlock:{type:Function},registerThinkingRef:{type:Function},handleThinkingScroll:{type:Function},getToolAnimationClass:{type:Function},getToolIcon:{type:Function},getToolStatusText:{type:Function},getToolDescription:{type:Function},formatSearchTopic:{type:Function},formatSearchTime:{type:Function},formatSearchDomains:{type:Function}},emits:["more-toggle"],setup(s,{emit:e}){const t=s,n=e;let i=0;const r=`stacked-${++i}`,o=qs(),a=ye(()=>o.form.stacked_hide_borders),c=X=>hE(X,t.formatSearchTopic,t.formatSearchTime,t.formatSearchDomains),l=pe(null),u=pe(null),h=pe(null),d=pe(!1),p=pe(0),m=pe(0),v=pe(0),g=pe(0),y=pe(!1),b=pe({}),_=new Map,w=ye(()=>(t.actions||[]).filter(X=>X&&(X.type==="thinking"||X.type==="tool"))),S=ye(()=>Math.max(0,w.value.length-Xk)),C=ye(()=>S.value>0||d.value),T=ye(()=>w.value.length===1),k=ye(()=>!!t.conversationRunning&&!!t.isLatestMessage),A=ye(()=>w.value.length),M=ye(()=>d.value?"已展开全部":"更多"),R=ye(()=>d.value?`共 ${A.value} 个步骤`:`${S.value} 个步骤折叠`),P=(X,J)=>(X==null?void 0:X.blockId)||(X==null?void 0:X.id)||`stacked-${J}`,L=(X,J)=>{var he;return(he=t.expandedBlocks)==null?void 0:he.has(P(X,J))},z=X=>{var J;return(J=t.expandedBlocks)==null?void 0:J.has(X)},Q=X=>{const J=Math.max(0,b.value[X]||0);return{maxHeight:z(X)?`${J}px`:"0px"}},W=X=>{var he;const J=(he=X==null?void 0:X.tool)==null?void 0:he.status;return J==="preparing"||J==="running"},V=X=>{var J;return((J=X==null?void 0:X.tool)==null?void 0:J.status)==="completed"},N=()=>{d.value=!d.value,le();const X=h.value;X instanceof HTMLElement&&n("more-toggle",{element:X,expanded:d.value,stackKey:r})},O=X=>{typeof t.toggleBlock=="function"&&(t.toggleBlock(X),le())},H=(X,J)=>{J instanceof HTMLElement?_.set(X,J):_.delete(X),typeof t.registerThinkingRef=="function"&&t.registerThinkingRef(X,J)},G=(X,J)=>{typeof t.handleThinkingScroll=="function"&&t.handleThinkingScroll(X,J)},ee=X=>X?X instanceof HTMLElement?X:X.$el&&X.$el instanceof HTMLElement?X.$el:null:null,ie=()=>{const X=ee(h.value);if(!X)return 56;const J=X.querySelector(".more-title");return Math.max(48,Math.ceil((J==null?void 0:J.getBoundingClientRect().height)||56))},ve=()=>{const X=ee(u.value);if(!ee(l.value)||!X)return;const he=Array.from(X.children),be=w.value,Re=[],rt={};he.forEach((ce,de)=>{const we=be[de],Le=P(we,de),He=ce.querySelector(".collapsible-header"),yt=ce.querySelector(".content-inner"),At=He?Math.ceil(He.offsetHeight):u5,Nt=yt?Math.min(Math.ceil(yt.offsetHeight),c5):0;rt[Le]=Nt;const It=z(Le),Jt=a.value||de===he.length-1?0:1;Re.push(At+(It?Nt:0)+Jt)}),b.value=rt;const st=ce=>ce.length?ce.reduce((de,we)=>de+we,0):0,et=st(Re),De=st(Re.slice(0,Math.max(0,Re.length-Xk))),xe=st(Re.slice(-Xk));m.value=C.value?ie():0;const se=m.value+(d.value||!C.value?et:xe);p.value=se+2,v.value=d.value||!C.value?0:-De,g.value=Math.max(0,se-m.value)},le=()=>{ft(()=>{requestAnimationFrame(()=>{ve(),y.value||requestAnimationFrame(()=>{y.value=!0})})})};let oe=null,I=null;const K=()=>{oe&&(oe.disconnect(),_.forEach(X=>oe.observe(X)))};return Cn(()=>{le(),typeof ResizeObserver<"u"&&(oe=new ResizeObserver(()=>{I&&cancelAnimationFrame(I),I=requestAnimationFrame(()=>ve())}),ft(()=>K()))}),xn(()=>{oe&&(oe.disconnect(),oe=null),I&&(cancelAnimationFrame(I),I=null)}),Xe(()=>{var Re,rt,st,et;const X=w.value,J=((Re=X[0])==null?void 0:Re.blockId)||((rt=X[0])==null?void 0:rt.id)||"",he=((st=X[X.length-1])==null?void 0:st.blockId)||((et=X[X.length-1])==null?void 0:et.id)||"",be=X.map(De=>{var xe,se,ce;return(De==null?void 0:De.type)==="tool"?`T:${((xe=De==null?void 0:De.tool)==null?void 0:xe.status)||"?"}${(se=De==null?void 0:De.tool)!=null&&se.result?"R":"-"}`:(De==null?void 0:De.type)==="thinking"?`H:${De!=null&&De.streaming?"S":"-"}${Math.floor((((ce=De==null?void 0:De.content)==null?void 0:ce.length)||0)/48)}`:"?"}).join(",");return`${X.length}|${J}|${he}|${C.value}|${be}`},()=>{ft(()=>{K(),le()})}),Xe(()=>t.expandedBlocks?t.expandedBlocks.size:0,()=>le()),Xe(a,()=>le()),(X,J)=>(F(),$("div",{class:ke(["stacked-shell",{"stacked-shell--single":T.value,"stacked-shell--not-ready":!y.value,"stacked-shell--no-borders":a.value}]),ref_key:"shell",ref:l,style:Ke({height:`${p.value}px`,paddingTop:C.value?`${m.value}px`:"0px"})},[E("div",{class:ke(["stacked-more-block",{visible:C.value}]),ref_key:"moreBlock",ref:h,style:Ke({height:`${C.value?m.value:0}px`}),onClick:N},[J[0]||(J[0]=E("img",{class:"more-icon",src:G3,alt:"展开"},null,-1)),E("div",q3,[E("span",K3,ae(M.value),1),E("span",Q3,ae(R.value),1)])],6),E("div",{class:"stacked-viewport",style:Ke({height:`${g.value}px`})},[Qe(Vv,{name:"stacked",tag:"div",class:"stacked-inner",ref_key:"inner",ref:u,style:Ke({transform:`translateY(${v.value}px)`}),appear:k.value,css:k.value},{default:Vt(()=>[(F(!0),$(Ie,null,tt(w.value,(he,be)=>(F(),$("div",{key:P(he,be),class:"stacked-item"},[he.type==="thinking"?(F(),$("div",{key:0,class:ke(["collapsible-block thinking-block stacked-block",{expanded:L(he,be),processing:he.streaming}]),"data-block-id":P(he,be)},[E("div",{class:"collapsible-header",onClick:Re=>O(P(he,be))},[J[1]||(J[1]=E("div",{class:"arrow"},null,-1)),E("div",J3,[E("span",{class:ke(["thinking-icon",{"thinking-animation":he.streaming}])},[E("span",{class:"icon icon-sm",style:Ke(s.iconStyle("brain")),"aria-hidden":"true"},null,4)],2)]),E("span",Z3,ae(he.streaming?"正在思考...":"思考过程"),1)],8,Y3),E("div",{class:"collapsible-content",style:Ke(Q(P(he,be)))},[E("div",{class:"content-inner thinking-content",ref_for:!0,ref:Re=>H(P(he,be),Re),onScroll:Re=>G(P(he,be),Re),style:{"max-height":"240px","overflow-y":"auto"}},ae(he.content),41,e5)],4)],10,X3)):he.type==="tool"?(F(),$("div",{key:1,class:ke(["collapsible-block tool-block stacked-block",{expanded:L(he,be),processing:W(he),completed:V(he)}]),"data-block-id":P(he,be)},[E("div",{class:"collapsible-header",onClick:Re=>O(P(he,be))},[J[2]||(J[2]=E("div",{class:"arrow"},null,-1)),E("div",n5,[E("span",{class:ke(["tool-icon icon icon-md",s.getToolAnimationClass(he.tool)]),style:Ke(s.iconStyle(s.getToolIcon(he.tool))),"aria-hidden":"true"},null,6)]),E("span",i5,ae(s.getToolStatusText(he.tool)),1),E("span",r5,ae(s.getToolDescription(he.tool)),1)],8,s5),E("div",{class:"collapsible-content",style:Ke(Q(P(he,be)))},[E("div",o5,[E("div",{innerHTML:c(he)},null,8,a5)])],4),W(he)?(F(),$("div",l5)):ge("",!0)],10,t5)):ge("",!0)]))),128))]),_:1},8,["style","appear","css"])],4)],6))}}),d5=Qt(h5,[["__scopeId","data-v-be07323d"]]),f5={class:"square-grid-loader"},p5=at({__name:"SquareGridLoader",setup(s){return(e,t)=>(F(),$("div",f5,[...t[0]||(t[0]=[mi('<div class="square" id="sq1" data-v-afc6b5c3></div><div class="square" id="sq2" data-v-afc6b5c3></div><div class="square" id="sq3" data-v-afc6b5c3></div><div class="square" id="sq4" data-v-afc6b5c3></div><div class="square" id="sq5" data-v-afc6b5c3></div><div class="square" id="sq6" data-v-afc6b5c3></div><div class="square" id="sq7" data-v-afc6b5c3></div><div class="square" id="sq8" data-v-afc6b5c3></div><div class="square" id="sq9" data-v-afc6b5c3></div>',9)])]))}}),g5=Qt(p5,[["__scopeId","data-v-afc6b5c3"]]),m5={class:"rotating-squares-loader"},v5=at({__name:"RotatingSquaresLoader",setup(s){return(e,t)=>(F(),$("div",m5,[...t[0]||(t[0]=[mi('<div class="square" data-v-db47acef></div><div class="square" data-v-db47acef></div><div class="square" data-v-db47acef></div><div class="square" data-v-db47acef></div><div class="square" data-v-db47acef></div><div class="square" data-v-db47acef></div><div class="square" data-v-db47acef></div>',7)])]))}}),y5=Qt(v5,[["__scopeId","data-v-db47acef"]]),b5={class:"dual-chase-loader"},_5=at({__name:"DualChaseLoader",setup(s){return(e,t)=>(F(),$("div",b5))}}),S5=Qt(_5,[["__scopeId","data-v-337256ff"]]),w5={class:"bouncing-squares-loader"},k5=at({__name:"BouncingSquaresLoader",setup(s){return(e,t)=>(F(),$("div",w5,[...t[0]||(t[0]=[E("div",{class:"square"},null,-1),E("div",{class:"square"},null,-1),E("div",{class:"square"},null,-1)])]))}}),C5=Qt(k5,[["__scopeId","data-v-502bc545"]]),T5={class:"five-squares-loader"},A5=at({__name:"FiveSquaresLoader",setup(s){return(e,t)=>(F(),$("div",T5,[...t[0]||(t[0]=[mi('<div id="sq1" data-v-4ffc5a36></div><div id="sq2" data-v-4ffc5a36></div><div id="sq3" data-v-4ffc5a36></div><div id="sq4" data-v-4ffc5a36></div><div id="sq5" data-v-4ffc5a36></div>',5)])]))}}),E5=Qt(A5,[["__scopeId","data-v-4ffc5a36"]]),M5={class:"nine-grid-loader"},x5=at({__name:"NineGridLoader",setup(s){return(e,t)=>(F(),$("div",M5,[...t[0]||(t[0]=[mi('<div class="box" data-v-62be6033></div><div class="box" data-v-62be6033></div><div class="box" data-v-62be6033></div><div class="box" data-v-62be6033></div><div class="box" data-v-62be6033></div><div class="box" data-v-62be6033></div><div class="box" data-v-62be6033></div><div class="box" data-v-62be6033></div><div class="box" data-v-62be6033></div>',9)])]))}}),I5=Qt(x5,[["__scopeId","data-v-62be6033"]]),R5={class:"ripple-loader"},L5=at({__name:"RippleLoader",setup(s){return(e,t)=>(F(),$("div",R5,[...t[0]||(t[0]=[mi('<div class="cell d-0" data-v-e8d9f3ef></div><div class="cell d-1" data-v-e8d9f3ef></div><div class="cell d-2" data-v-e8d9f3ef></div><div class="cell d-1" data-v-e8d9f3ef></div><div class="cell d-2" data-v-e8d9f3ef></div><div class="cell d-2" data-v-e8d9f3ef></div><div class="cell d-3" data-v-e8d9f3ef></div><div class="cell d-3" data-v-e8d9f3ef></div><div class="cell d-4" data-v-e8d9f3ef></div>',9)])]))}}),P5=Qt(L5,[["__scopeId","data-v-e8d9f3ef"]]),O5={class:"newton-loader"},D5=at({__name:"NewtonCradleSquaresLoader",setup(s){return(e,t)=>(F(),$("div",O5,[...t[0]||(t[0]=[E("div",{class:"dot"},null,-1),E("div",{class:"dot"},null,-1),E("div",{class:"dot"},null,-1),E("div",{class:"dot"},null,-1)])]))}}),N5=Qt(D5,[["__scopeId","data-v-4316d9b8"]]),B5={class:"dot-spinner-loader"},F5=at({__name:"DotSpinnerSquaresLoader",setup(s){return(e,t)=>(F(),$("div",B5,[...t[0]||(t[0]=[mi('<div class="dot" data-v-89be96b5></div><div class="dot" data-v-89be96b5></div><div class="dot" data-v-89be96b5></div><div class="dot" data-v-89be96b5></div><div class="dot" data-v-89be96b5></div><div class="dot" data-v-89be96b5></div><div class="dot" data-v-89be96b5></div><div class="dot" data-v-89be96b5></div>',8)])]))}}),$5=Qt(F5,[["__scopeId","data-v-89be96b5"]]),H5={class:"orbit-loader"},U5=at({__name:"OrbitBlurSquaresLoader",setup(s){return(e,t)=>(F(),$("div",H5,[...t[0]||(t[0]=[mi('<div class="orbe" style="--index:0;" data-v-19a87dd3></div><div class="orbe" style="--index:1;" data-v-19a87dd3></div><div class="orbe" style="--index:2;" data-v-19a87dd3></div><div class="orbe" style="--index:3;" data-v-19a87dd3></div><div class="orbe" style="--index:4;" data-v-19a87dd3></div>',5)])]))}}),W5=Qt(U5,[["__scopeId","data-v-19a87dd3"]]),z5={class:"shadow-rolling-loader"},j5=at({__name:"ShadowRollingSquaresLoader",setup(s){return(e,t)=>(F(),$("div",z5))}}),V5=Qt(j5,[["__scopeId","data-v-0934be8f"]]),G5={class:"jumping-seq-loader"},q5=at({__name:"JumpingSequenceSquaresLoader",setup(s){return(e,t)=>(F(),$("div",G5,[...t[0]||(t[0]=[mi('<div class="sq" data-v-bb2c052b></div><div class="sq" data-v-bb2c052b></div><div class="sq" data-v-bb2c052b></div><div class="sq" data-v-bb2c052b></div><div class="sq" data-v-bb2c052b></div>',5)])]))}}),K5=Qt(q5,[["__scopeId","data-v-bb2c052b"]]),Q5={class:"chaotic-orbit-loader"},X5=at({__name:"ChaoticOrbitSquaresLoader",setup(s){return(e,t)=>(F(),$("div",Q5))}}),Y5=Qt(X5,[["__scopeId","data-v-c29a198e"]]),J5={class:"leap-frog-loader"},Z5=at({__name:"LeapFrogSquaresLoader",setup(s){return(e,t)=>(F(),$("div",J5,[...t[0]||(t[0]=[E("div",{class:"dot"},null,-1),E("div",{class:"dot"},null,-1),E("div",{class:"dot"},null,-1)])]))}}),e4=Qt(Z5,[["__scopeId","data-v-2e407c57"]]),t4={class:"wave-matrix-loader"},s4=at({__name:"WaveMatrixSquaresLoader",setup(s){return(e,t)=>(F(),$("div",t4,[...t[0]||(t[0]=[E("div",{class:"sq"},null,-1),E("div",{class:"sq"},null,-1),E("div",{class:"sq"},null,-1),E("div",{class:"sq"},null,-1)])]))}}),n4=Qt(s4,[["__scopeId","data-v-c583d74c"]]),i4={class:"follow-track-loader"},r4=at({__name:"FollowTrackSquaresLoader",setup(s){return(e,t)=>(F(),$("div",i4,[...t[0]||(t[0]=[mi('<div class="sq" data-v-091a0000></div><div class="sq" data-v-091a0000></div><div class="sq" data-v-091a0000></div><div class="sq" data-v-091a0000></div><div class="sq" data-v-091a0000></div>',5)])]))}}),o4=Qt(r4,[["__scopeId","data-v-091a0000"]]),a4={class:"four-corner-loader"},l4=at({__name:"FourCornerCycleSquaresLoader",setup(s){return(e,t)=>(F(),$("div",a4,[...t[0]||(t[0]=[E("div",{class:"sq"},null,-1),E("div",{class:"sq"},null,-1),E("div",{class:"sq"},null,-1),E("div",{class:"sq"},null,-1)])]))}}),c4=Qt(l4,[["__scopeId","data-v-3a59d23d"]]),jM=[g5,y5,S5,C5,E5,I5,P5,N5,$5,W5,V5,K5,Y5,e4,n4,o4,c4],u4=4,Vf=[],h4=s=>{const e=Math.floor(Math.random()*s.length);return s[e]};function Yk(){const s=jM.length;if(s===0)throw new Error("loaderPool 不能为空");const e=Math.max(0,Math.min(u4,s-1));let t=Array.from({length:s},(r,o)=>o);if(e>0&&Vf.length>0){const r=new Set(Vf.slice(-e)),o=t.filter(a=>!r.has(a));o.length>0&&(t=o)}const n=h4(t);Vf.push(n);const i=Math.max(s*2,e+1);return Vf.length>i&&Vf.splice(0,Vf.length-i),jM[n]}const d4=["data-streaming"],f4={class:"code-block-header"},p4={class:"code-language"},g4=at({name:"CodeBlock",__name:"CodeBlock",props:{content:{},language:{},isStreaming:{type:Boolean}},setup(s){const e=s,t=pe(null),n=pe(!1),i=ye(()=>e.language||"text"),r=ye(()=>!e.language||e.language==="text"?"language-plain":`language-${e.language}`);function o(){ft(()=>{if(!(!t.value||typeof vw>"u"))try{vw.highlightElement(t.value)}catch(c){console.warn("代码高亮失败:",c)}})}Xe(()=>e.content,o,{immediate:!0}),Cn(o);async function a(c){if(c.stopPropagation(),!(n.value||!e.content))try{await navigator.clipboard.writeText(e.content),n.value=!0,window.setTimeout(()=>{n.value=!1},5e3)}catch(l){console.warn("复制失败:",l)}}return(c,l)=>(F(),$("div",{class:"code-block-wrapper","data-streaming":s.isStreaming?"1":void 0,"data-md-code-block":"1"},[E("div",f4,[E("span",p4,ae(i.value),1),E("button",{class:ke(["copy-code-btn",{copied:n.value}]),title:"复制代码","aria-label":"复制代码",onClick:a},null,2)]),E("pre",null,[E("code",{ref_key:"codeEl",ref:t,class:ke(r.value)},ae(s.content),3)])],8,d4))}});function m4(s){if(!s)return[];if(typeof document>"u")return[{key:"c0",html:s}];const e=document.createElement("template");e.innerHTML=s;const t=[];for(const n of Array.from(e.content.childNodes)){if(n.nodeType===Node.TEXT_NODE){const i=n.textContent||"";if(!i.trim())continue;t.push({key:`c${t.length}`,html:i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")});continue}n.nodeType===Node.ELEMENT_NODE&&t.push({key:`c${t.length}`,html:n.outerHTML})}return t}const v4={key:0,class:"markdown-text-segment"},y4=["innerHTML"],b4=40,_4=at({name:"MarkdownRenderer",__name:"MarkdownRenderer",props:{content:{},isStreaming:{type:Boolean}},setup(s){const e=s,t=pe(null),n=y2("mathRenderedCallback",()=>{}),i=ye(()=>NF(e.content||"",e.isStreaming));function r(l){return FF(l,e.isStreaming)}const o=new Map;function a(l){const u=o.get(l.key);if(u&&u.content===l.content)return u.chunks;const h=m4(r(l.content));if(o.set(l.key,{content:l.content,chunks:h}),o.size>b4){const d=o.keys().next().value;d!==void 0&&o.delete(d)}return h}function c(){ft(()=>{t.value&&(BF(t.value),n())})}return Cn(c),S2(c),Xe(()=>e.content,c,{immediate:!0}),(l,u)=>(F(),$("div",{ref_key:"containerRef",ref:t,class:"markdown-renderer"},[(F(!0),$(Ie,null,tt(i.value,h=>(F(),$(Ie,{key:h.key},[h.type==="text"?(F(),$("div",v4,[(F(!0),$(Ie,null,tt(a(h),d=>(F(),$("div",{key:d.key,class:"md-html-chunk",innerHTML:d.html},null,8,y4))),128))])):(F(),Wt(g4,{key:1,content:h.content,language:h.language,"is-streaming":!h.closed},null,8,["content","language","is-streaming"]))],64))),128))],512))}}),xm=Qt(_4,[["__scopeId","data-v-8e651a8a"]]),S4={class:"minimal-blocks-container"},w4={key:0,class:"summary-group"},k4=["data-group-id","onClick"],C4={class:"summary-content-wrapper"},T4={class:"summary-preview"},A4={key:0,class:"summary-tool-reel-window"},E4={class:"summary-status-icon"},M4={key:0,class:"summary-icon-inner"},x4={key:1,class:"check-icon",width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2"},I4={class:"step-timeline"},R4={class:"step-content"},L4={key:0,class:"step-body"},P4=["onScroll","innerHTML"],O4={key:1,class:"step-body"},D4={class:"step-header"},N4={key:0,class:"tool-intent"},B4={key:1,class:"tool-result"},F4=["innerHTML"],$4={key:2,class:"tool-result"},H4={key:2,class:"summary-group sub-agent-system-group"},U4={class:"summary-line-text sub-agent-system-summary-line"},W4={class:"summary-content-wrapper"},z4={class:"summary-preview"},j4=20,Jk=26,V4=1450,Zk=520,VM=170,GM=2,G4=at({__name:"MinimalBlocks",props:{actions:{},conversationRunning:{type:Boolean},isLatestMessage:{type:Boolean},iconStyle:{type:Function},getToolIcon:{type:Function},getToolStatusText:{type:Function},getToolDescription:{type:Function},formatSearchTopic:{type:Function},formatSearchTime:{type:Function},formatSearchDomains:{type:Function},registerThinkingRef:{type:Function},handleThinkingScroll:{type:Function}},emits:["group-toggle"],setup(s,{emit:e}){const t=qs(),n=ye(()=>t.form.minimal_expand_height_limited),i=s,r=e,o=pe(new Set),a=new Map,c=new Map,l=new Map,u=new Map,h=mw({}),d=new Map,p=new Map,m=se=>Array.from(se||""),v=se=>{const ce=typeof se=="string"?se:"",de=ce.indexOf(`
`);return de>0?ce.substring(0,de):ce},g=se=>{const ce=se.tool;if(!ce)return"";const de=t.form.tool_intent_enabled,we=ce.intent_rendered||ce.intent_full||"";return de&&we?v(we):ce.status==="preparing"?`准备调用 ${ce.name||"工具"}...`:ce.status==="running"?`正在调用 ${ce.name||"工具"}...`:ce.status==="completed"?ce.display_name||ce.name||"工具执行完成":se.streaming?"正在执行工具...":ce.display_name||ce.name||"执行工具"},y=se=>{var de;if(se.type!=="tool")return!1;if(se.streaming)return!0;const ce=String(((de=se.tool)==null?void 0:de.status)||"").toLowerCase();return["hinted","preparing","running","pending","pending_approval","awaiting_approval","awaiting_user_answer"].includes(ce)},b=se=>{let ce=-1;for(let we=se.length-1;we>=0;we--){if(se[we].type==="tool"){ce=we;break}if(se[we].type==="thinking")break}if(ce<0)return[];let de=ce;for(;de>0&&se[de-1].type==="tool";)de--;return se.slice(de,ce+1)},_=se=>{const ce=b(se);return ce.some(y)?ce:[]},w=se=>_(se).map(g).filter(ce=>ce.trim().length>0),S=(se,ce)=>{var Le;const de=(Le=h[ce])!=null&&Le.completing?h[ce].items:null;if(de!=null&&de.length)return de;const we=w(se);return we.length>0?[...we,we[0]]:[]},C=(se,ce)=>{var de;return!!((de=h[ce])!=null&&de.completing)||ve(se,ce)&&w(se).length>1},T=(se,ce)=>{var de;return ve(se,ce)||!!((de=h[ce])!=null&&de.completing)},k=se=>{var ce;return((ce=h[se])==null?void 0:ce.phase)||"idle"},A=se=>{var ce;return{transform:`translateY(${((ce=h[se])==null?void 0:ce.offsetPx)||0}px)`}},M=se=>{const ce=d.get(se);ce&&(window.clearInterval(ce),d.delete(se)),(p.get(se)||[]).forEach(we=>window.clearTimeout(we)),p.delete(se)},R=(se,ce)=>{const de=p.get(se)||[];de.push(ce),p.set(se,de)},P=(se,ce)=>{const de=h[se];if(!de||de.completing||ce<2)return;const we=(de.index+1)%ce,He=-(we===0?ce:we)*Jk;de.phase="rolling",de.offsetPx=He-GM;const yt=window.setTimeout(()=>{if(de.phase="settle",de.offsetPx=He,de.index=we,we===0){const At=window.setTimeout(()=>{de.phase="idle",de.offsetPx=0},VM);R(se,At)}},Zk);R(se,yt)},L=(se,ce)=>{const de=h[se];if(!de||de.completing)return;const we=de.items.length>1?de.items:b(ce).map(g).filter(At=>At.trim().length>0);if(we.length<2){M(se),delete h[se];return}M(se),de.items=we,de.signature=we.join(""),de.completing=!0;const Le=we.length-1,He=-de.index*Jk,yt=-Le*Jk;de.phase="idle",de.offsetPx=He,window.requestAnimationFrame(()=>{de.phase="rolling",de.offsetPx=yt-GM;const At=window.setTimeout(()=>{de.phase="settle",de.offsetPx=yt,de.index=Le},Zk);R(se,At);const Nt=window.setTimeout(()=>{M(se),delete h[se]},Zk+VM+260);R(se,Nt)})},z=()=>{const se=new Set;W.value.forEach(ce=>{if(ce.type!=="summary"||!ce.actions||!C(ce.actions,ce.id))return;const de=w(ce.actions),we=de.join("");if(se.add(ce.id),!h[ce.id]||h[ce.id].signature!==we?(M(ce.id),h[ce.id]={index:0,offsetPx:0,phase:"idle",signature:we,items:de}):h[ce.id].items=de,!d.has(ce.id)){const Le=window.setInterval(()=>P(ce.id,de.length),V4);d.set(ce.id,Le)}}),Object.keys(h).forEach(ce=>{if(!se.has(ce)){const de=W.value.find(we=>we.id===ce);if((de==null?void 0:de.type)==="summary"&&de.actions&&!h[ce].completing){se.add(ce),L(ce,de.actions);return}h[ce].completing||(M(ce),delete h[ce])}})},Q=se=>{const ce=W.value.find(Nt=>Nt.id===se);if(!ce||!ce.actions)return Yk();const we=ce.actions.find(Nt=>Nt.streaming)||ce.actions[ce.actions.length-1];if(!we)return Yk();const Le=ce.actions.indexOf(we);let He=-1;for(let Nt=Le-1;Nt>=0;Nt--)if(ce.actions[Nt].type!==we.type){He=Nt;break}const yt=He>=0?`${ce.actions[He].id}-${we.type}`:`start-${we.type}`,At=`${se}-${yt}`;return u.has(At)||u.set(At,Yk()),u.get(At)},W=ye(()=>{const se=[];let ce=[],de=0;if(i.actions.forEach((we,Le)=>{if(we.type==="thinking"||we.type==="tool")ce.push(we);else if(we.type==="text"||we.type==="system"){if(ce.length>0){const He=ce[0].id||ce[0].blockId||`summary-${de}`;se.push({type:"summary",id:`summary-${He}`,actions:ce}),de++,ce=[]}if(we.type==="text"){const He=typeof we.content=="string"?we.content:"";if(!He.trim())return;se.push({type:"text",id:`text-${Le}`,content:He,streaming:we.streaming})}else se.push({type:"system",id:`system-${Le}`,content:we.content})}}),ce.length>0){const we=ce[0].id||ce[0].blockId||`summary-${de}`;se.push({type:"summary",id:`summary-${we}`,actions:ce})}return se}),V={read_file:"read",read_skill:"read",vlm_analyze:"read",view_image:"read",view_video:"read",run_command:"command",terminal_session:"command",terminal_input:"command",terminal_snapshot:"command",create_file:"edit",write_file:"edit",edit_file:"edit",delete_file:"edit",rename_file:"edit",create_folder:"edit",web_search:"search",extract_webpage:"webpage",save_webpage:"webpage",list_mcp_servers:"mcp",activate_workflow:"workflow_activate",report_workflow_stage:"workflow_advance",choose_workflow_branch:"workflow_advance",get_workflow_status:"workflow",deactivate_workflow:"workflow",list_workflows:"workflow",save_workflow:"workflow",todo_create:"todo_create",todo_update_task:"todo_update",update_memory:"memory_update",update_project_memory:"memory_update",recall_project_memory:"memory_read",search_project_memory:"memory_read",conversation_search:"conversation",conversation_review:"conversation",create_sub_agent:"sub_agent",close_sub_agent:"sub_agent_manage",terminate_sub_agent:"sub_agent_manage",get_sub_agent_status:"sub_agent_manage",sleep:"wait",ask_user:"ask",submit_plan:"plan",create_skill:"skill",manage_personalization:"settings",trigger_easter_egg:"easter_egg"},N={read:se=>`读取了 ${se} 个文件`,command:se=>`运行了 ${se} 个指令`,edit:se=>`编辑了 ${se} 次文件`,search:se=>`搜索了 ${se} 次`,webpage:se=>`查看了 ${se} 次网页`,mcp:se=>`执行了 ${se} 次 MCP 工具`,workflow_activate:se=>`激活了 ${se} 个工作流`,workflow_advance:se=>`推进了 ${se} 次工作流进度`,workflow:se=>`执行了 ${se} 次工作流操作`,todo_create:se=>`创建了 ${se} 次待办`,todo_update:se=>`更新了 ${se} 次待办`,memory_update:se=>`更新了 ${se} 次记忆`,memory_read:se=>`查看了 ${se} 次记忆`,conversation:se=>`回顾了 ${se} 次对话`,sub_agent:se=>`创建了 ${se} 个子智能体`,sub_agent_manage:se=>`管理了 ${se} 次子智能体`,wait:se=>`等待了 ${se} 次`,ask:se=>`询问了 ${se} 次`,plan:se=>`提交了 ${se} 次计划`,skill:se=>`归档了 ${se} 次技能`,settings:se=>`更新了 ${se} 次个性化设置`,easter_egg:se=>`触发了 ${se} 次彩蛋`,other:se=>`执行了 ${se} 次其他操作`},O=["read","command","edit","search","webpage","mcp","workflow_activate","workflow_advance","workflow","todo_create","todo_update","memory_update","memory_read","conversation","sub_agent","sub_agent_manage","wait","ask","plan","skill","settings","easter_egg","other"],H=se=>{var de;const ce=(de=se.tool)==null?void 0:de.name;return typeof ce!="string"?"other":ce.startsWith("mcp__")?"mcp":V[ce]||"other"},G=se=>{const ce=se.filter(we=>we.streaming);let de;if(ce.length>0)de=ce[ce.length-1];else{const we=se.filter(Le=>Le.type==="tool");we.length>0?de=we[we.length-1]:de=se[se.length-1]}if(!de)return"";if(de.type==="thinking"){const we=de.content||"";return v(we)}if(de.type==="tool"){const we=de.tool;if(!we)return"";const Le=t.form.tool_intent_enabled,He=we.intent_rendered||we.intent_full||"";return Le&&He?v(He):we.status==="preparing"?`准备调用 ${we.name||"工具"}...`:we.status==="running"?`正在调用 ${we.name||"工具"}...`:we.status==="completed"?we.display_name||we.name||"工具执行完成":de.streaming?"正在执行工具...":we.display_name||we.name||"执行工具"}return""},ee=se=>{const ce=se.filter(Le=>Le.type==="tool");if(ce.length===0){const Le=se.filter(He=>He.type==="thinking").pop();return Le?v(Le.content||""):""}if(ce.length===1)return g(ce[0]);const de=Object.fromEntries(O.map(Le=>[Le,0]));ce.forEach(Le=>{de[H(Le)]++});const we=[];return O.forEach(Le=>{const He=de[Le];He>0&&we.push(N[Le](He))}),we.join("")},ie=(se,ce)=>ve(se,ce)?G(se):ee(se),ve=(se,ce)=>{if(!i.conversationRunning||!i.isLatestMessage)return!1;const de=W.value.findIndex(Le=>Le.id===ce);return de===-1?!1:!W.value.slice(de+1).some(Le=>Le.type==="text")},le=se=>se.map((ce,de)=>({id:ce.id||ce.blockId||`step-${de}`,type:ce.type,content:ce.content||"",streaming:ce.streaming||!1,action:ce})),oe=se=>se.scrollHeight-se.scrollTop-se.clientHeight<=j4,I=(se,ce)=>{const de=ce.target;if(!de)return;const we=!oe(de);l.set(se,we)},K=(se,ce)=>{const de=c.get(se);de&&de.removeEventListener("scroll",I),ce instanceof HTMLElement?(c.set(se,ce),ce.addEventListener("scroll",we=>I(se,we))):(c.delete(se),l.delete(se))},X=se=>{const ce=c.get(se);ce&&!l.get(se)&&(ce.scrollTop=ce.scrollHeight)},J=se=>{o.value.has(se)?(o.value.delete(se),r("group-toggle",{groupId:se,expanded:!1}),ft(()=>{const ce=W.value.find(de=>de.id===se);ce&&ce.actions&&ce.actions.forEach(de=>{if(de.type==="thinking"){const we=de.id||de.blockId;we&&typeof i.registerThinkingRef=="function"&&i.registerThinkingRef(we,null)}})})):(o.value.add(se),r("group-toggle",{groupId:se,expanded:!0}),ft(()=>{const ce=W.value.find(de=>de.id===se);ce&&ce.actions&&(l.set(se,!1),ve(ce.actions,se)&&X(se),ce.actions.forEach(de=>{if(de.type==="thinking"){const we=de.id||de.blockId;if(we){const Le=a.get(we);Le&&typeof i.registerThinkingRef=="function"&&(i.registerThinkingRef(we,Le),de.streaming&&(Le.scrollTop=Le.scrollHeight))}}}))}))},he=se=>{if(se.type==="thinking")return i.iconStyle?i.iconStyle("brain"):{};if(se.type==="tool"&&se.action.tool){const ce=i.getToolIcon?i.getToolIcon(se.action.tool):"terminal";return i.iconStyle?i.iconStyle(ce):{}}return i.iconStyle?i.iconStyle("terminal"):{}},be=se=>{const ce=se.tool;if(!ce)return"执行工具";const de=t.form.tool_intent_enabled,we=ce.intent_rendered||ce.intent_full||"";return de&&we?we:ce.status==="preparing"?`准备调用 ${ce.name||"工具"}...`:ce.status==="running"?`正在调用 ${ce.name||"工具"}...`:ce.status==="completed"?"工具执行完成":ce.name||"执行工具"},Re=se=>{var ce;return((ce=se.tool)==null?void 0:ce.intent)||""},rt=se=>{var we;const ce=hE(se,i.formatSearchTopic||(()=>""),i.formatSearchTime||(()=>""),i.formatSearchDomains||(()=>""));if(ce)return ce;const de=(we=se.tool)==null?void 0:we.result;return de?typeof de=="string"?`<div class="result-item"><pre>${et(de)}</pre></div>`:`<div class="result-item"><pre>${et(JSON.stringify(de,null,2))}</pre></div>`:'<div class="result-item">执行中...</div>'},st=se=>se?et(se).replace(/\n/g,"<br>"):"",et=se=>{const ce=document.createElement("div");return ce.textContent=se,ce.innerHTML},De=(se,ce)=>{ce instanceof HTMLElement?a.set(se,ce):a.delete(se);const de=W.value.find(we=>we.type==="summary"&&we.actions&&we.actions.some(Le=>Le.id===se||Le.blockId===se));de&&o.value.has(de.id)&&typeof i.registerThinkingRef=="function"&&i.registerThinkingRef(se,ce)},xe=(se,ce)=>{typeof i.handleThinkingScroll=="function"&&i.handleThinkingScroll(se,ce)};return Xe(()=>i.actions,()=>{z(),ft(()=>{W.value.forEach(se=>{se.type==="summary"&&se.actions&&o.value.has(se.id)&&ve(se.actions,se.id)&&X(se.id)})})},{deep:!0,immediate:!0}),Xe(()=>[i.conversationRunning,i.isLatestMessage],()=>{z()}),xn(()=>{Object.keys(h).forEach(M),c.forEach(se=>{se.removeEventListener("scroll",I)}),c.clear(),l.clear()}),(se,ce)=>(F(),$("div",S4,[(F(!0),$(Ie,null,tt(W.value,de=>(F(),$(Ie,{key:de.id},[de.type==="summary"&&de.actions?(F(),$("div",w4,[E("div",{class:ke(["summary-line-text",{running:ve(de.actions,de.id)}]),"data-group-id":de.id,onClick:we=>J(de.id)},[E("div",C4,[E("span",T4,[T(de.actions,de.id)?(F(),$(Ie,{key:0},[C(de.actions,de.id)?(F(),$("span",A4,[E("span",{class:ke(["summary-tool-reel-track",k(de.id)]),style:Ke(A(de.id))},[(F(!0),$(Ie,null,tt(S(de.actions,de.id),(we,Le)=>(F(),$("span",{key:`${de.id}-tool-reel-${Le}-${we}`,class:"summary-tool-reel-item"},ae(we),1))),128))],6)])):(F(!0),$(Ie,{key:1},tt(m(ie(de.actions,de.id)),(we,Le)=>(F(),$("span",{key:`${de.id}-${Le}`,class:"summary-char",style:Ke({animationDelay:`${(Le+1)*.12}s`})},ae(we===" "?" ":we),5))),128))],64)):(F(),$(Ie,{key:1},[hn(ae(ie(de.actions,de.id)),1)],64))])]),E("div",E4,[ve(de.actions,de.id)?(F(),$("div",M4,[(F(),Wt(EF(Q(de.id))))])):(F(),$("svg",x4,[...ce[0]||(ce[0]=[E("circle",{cx:"12",cy:"12",r:"10"},null,-1),E("polyline",{points:"7.5 12 10.5 15 16.5 9"},null,-1)])]))])],10,k4),E("div",{class:ke(["steps-container",{show:o.value.has(de.id)}])},[E("div",{class:ke(["steps-wrapper",{"height-limited":n.value}]),ref_for:!0,ref:we=>K(de.id,we)},[(F(!0),$(Ie,null,tt(le(de.actions),we=>{var Le;return F(),$("div",{key:we.id,class:"step-item"},[E("div",I4,[E("span",{class:"step-icon icon icon-sm",style:Ke(he(we)),"aria-hidden":"true"},null,4),ce[1]||(ce[1]=E("div",{class:"step-line"},null,-1))]),E("div",R4,[we.type==="thinking"?(F(),$("div",L4,[E("div",{class:"thinking-content",ref_for:!0,ref:He=>De(we.id,He),onScroll:He=>xe(we.id,He),innerHTML:st(we.content)},null,40,P4)])):we.type==="tool"?(F(),$("div",O4,[E("div",D4,ae(be(we.action)),1),Re(we.action)?(F(),$("div",N4,ae(Re(we.action)),1)):ge("",!0),(Le=we.action.tool)!=null&&Le.result?(F(),$("div",B4,[E("div",{innerHTML:rt(we.action)},null,8,F4)])):(F(),$("div",$4,[...ce[2]||(ce[2]=[E("div",{class:"result-item"},"执行中...",-1)])]))])):ge("",!0)])])}),128))],2)],2)])):de.type==="text"?(F(),$("div",{key:1,class:ke(["text-output",{"streaming-text":de.streaming}])},[E("div",{class:ke(["text-content",{"streaming-text":de.streaming}])},[Qe(xm,{content:de.content||"","is-streaming":de.streaming},null,8,["content","is-streaming"])],2)],2)):de.type==="system"?(F(),$("div",H4,[E("div",U4,[E("div",W4,[E("span",z4,ae(de.content||""),1)]),ce[3]||(ce[3]=E("div",{class:"summary-status-icon"},[E("svg",{class:"check-icon",width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2"},[E("circle",{cx:"12",cy:"12",r:"10"}),E("polyline",{points:"7.5 12 10.5 15 16.5 9"})])],-1))])])):ge("",!0)],64))),128))]))}}),q4=Qt(G4,[["__scopeId","data-v-203da854"]]),K4={class:"edit-summary-card__header"},Q4={class:"edit-summary-card__title"},X4={class:"edit-summary-card__totals"},Y4={class:"edit-summary-plus"},J4={class:"edit-summary-minus"},Z4={class:"edit-summary-card__list"},eH=["onMouseenter","onClick"],tH=["title"],sH={class:"edit-summary-card__delta"},nH={class:"edit-summary-plus"},iH={class:"edit-summary-minus"},rH={key:0,class:"es-modal"},oH=["aria-label"],aH={class:"es-modal__header"},lH=["title"],cH={class:"es-modal__delta"},uH={class:"edit-summary-plus"},hH={class:"edit-summary-minus"},dH={class:"es-modal__body"},fH={key:0,class:"es-diff-sep","aria-hidden":"true"},pH={class:"es-diff-line-number"},gH={class:"es-diff-marker"},mH={class:"es-diff-content"},vH={key:0,class:"es-diff-note"},yH={key:1,class:"es-diff-empty"},bH=720,Qo=16,qM=140,_H=.7,SH=640,wH=260,kH=at({__name:"EditSummaryCard",props:{summary:{},iconStyle:{type:Function}},setup(s){const e=s,t=Vs(),n=ye(()=>!!t.isMobileViewport),i=ye(()=>{var W;const Q=(W=e.summary)==null?void 0:W.files;return Array.isArray(Q)?Q.filter(V=>V&&V.path):[]}),r=ye(()=>{let Q=0,W=0;for(const V of i.value)Q+=Number(V.added)||0,W+=Number(V.removed)||0;return{added:Q,removed:W}}),o=pe(null),a=pe(!1),c=pe(null),l=pe(null),u=pe({});let h=null,d=null;const p=ye(()=>o.value&&i.value.find(Q=>Q.path===o.value)||null);function m(){if(n.value||!c.value||!l.value){u.value={};return}const Q=window.innerWidth,W=window.innerHeight,V=Math.min(bH,Q-Qo*2),N=c.value.getBoundingClientRect(),O=N.left+N.width/2,H=Math.min(Math.max(O-V/2,Qo),Q-V-Qo),G=Math.min(W*_H,SH),ee=l.value.getBoundingClientRect(),ie=ee.top-ee.height/2,ve=ee.bottom+ee.height/2,le=ie-Qo,oe=W-Qo-ve,I=le>=wH||le>=oe,K={left:`${Math.round(H)}px`,width:`${Math.round(V)}px`,transform:"none"};if(I){const X=Math.min(Math.max(ie,Qo+qM),W-Qo);u.value={...K,top:"auto",bottom:`${Math.round(W-X)}px`,maxHeight:`${Math.round(Math.min(X-Qo,G))}px`}}else{const X=Math.min(Math.max(ve,Qo),W-Qo-qM);u.value={...K,top:`${Math.round(X)}px`,bottom:"auto",maxHeight:`${Math.round(Math.min(W-Qo-X,G))}px`}}}function v(){o.value&&m()}function g(){h&&(clearTimeout(h),h=null)}function y(){d&&(clearTimeout(d),d=null)}function b(Q,W,V=null){g(),y(),o.value=Q,a.value=W,l.value=V,m()}function _(Q,W){g(),h=setTimeout(()=>b(Q,!1,W),150)}function w(){a.value||(y(),d=setTimeout(()=>{o.value=null},200))}function S(Q,W){n.value||(y(),_(Q,W.currentTarget||null))}function C(){n.value||(g(),w())}function T(){n.value||y()}function k(){n.value||w()}function A(Q,W){b(Q,!0,W.currentTarget||null)}function M(){g(),y(),a.value=!1,o.value=null,l.value=null}function R(Q){Q.key==="Escape"&&o.value&&M()}Xe(o,Q=>{Q?(window.addEventListener("keydown",R),window.addEventListener("resize",v),window.addEventListener("scroll",v,!0)):(window.removeEventListener("keydown",R),window.removeEventListener("resize",v),window.removeEventListener("scroll",v,!0))}),xn(()=>{g(),y(),window.removeEventListener("keydown",R),window.removeEventListener("resize",v),window.removeEventListener("scroll",v,!0)});function P(Q){return Q.type==="add"?"es-diff-add":Q.type==="remove"?"es-diff-remove":"es-diff-context"}function L(Q){return Q.type==="add"?"+":Q.type==="remove"?"-":""}function z(Q){const W=Q.type==="remove"?Q.old_no:Q.new_no;return typeof W=="number"&&Number.isFinite(W)?String(W):""}return(Q,W)=>i.value.length?(F(),$("div",{key:0,class:"edit-summary-card",ref_key:"cardRef",ref:c},[E("div",K4,[E("span",{class:"icon icon-sm edit-summary-card__icon",style:Ke(e.iconStyle("filePen")),"aria-hidden":"true"},null,4),E("span",Q4,"已编辑 "+ae(i.value.length)+" 个文件",1),E("span",X4,[E("span",Y4,"+"+ae(r.value.added),1),E("span",J4,"-"+ae(r.value.removed),1)])]),E("div",Z4,[(F(!0),$(Ie,null,tt(i.value,V=>(F(),$("div",{key:V.path,class:ke(["edit-summary-card__row",{"is-active":a.value&&o.value===V.path}]),onMouseenter:N=>S(V.path,N),onMouseleave:C,onClick:Ne(N=>A(V.path,N),["stop"])},[E("span",{class:"edit-summary-card__path",title:V.path},ae(V.path),9,tH),E("span",sH,[E("span",nH,"+"+ae(V.added||0),1),E("span",iH,"-"+ae(V.removed||0),1)])],42,eH))),128))]),(F(),Wt(Sp,{to:"body"},[p.value?(F(),$("div",rH,[a.value||n.value?(F(),$("div",{key:0,class:"es-modal__overlay","aria-hidden":"true",onClick:M})):ge("",!0),E("div",{class:"es-modal__panel",style:Ke(u.value),role:"dialog","aria-label":`文件变更:${p.value.path}`,onMouseenter:T,onMouseleave:k},[E("div",aH,[E("span",{class:"icon icon-sm es-modal__header-icon",style:Ke(e.iconStyle("filePen")),"aria-hidden":"true"},null,4),E("span",{class:"es-modal__path",title:p.value.path},ae(p.value.path),9,lH),E("span",cH,[E("span",uH,"+"+ae(p.value.added||0),1),E("span",hH,"-"+ae(p.value.removed||0),1)]),a.value||n.value?(F(),$("button",{key:0,type:"button",class:"es-modal__close","aria-label":"关闭",onClick:Ne(M,["stop"])},[E("span",{class:"icon icon-sm",style:Ke(e.iconStyle("x")),"aria-hidden":"true"},null,4)])):ge("",!0)]),E("div",dH,[(p.value.lines||[]).length?(F(),$(Ie,{key:0},[(F(!0),$(Ie,null,tt(p.value.lines,(V,N)=>(F(),$(Ie,{key:N},[V.type==="sep"?(F(),$("div",fH,"⋮")):(F(),$("div",{key:1,class:ke(["es-diff-line",P(V)])},[E("span",pH,ae(z(V)),1),E("span",gH,ae(L(V)),1),E("span",mH,ae(V.content),1)],2))],64))),128)),p.value.truncated?(F(),$("div",vH,"内容过长,已截断展示")):ge("",!0)],64)):(F(),$("div",yH,"暂无可展示的文本变更行"))])],44,oH)])):ge("",!0)]))],512)):ge("",!0)}}),Gf=()=>({active:!1,name:"",status:null,history:[],current:null,next:null,reviewing:!1,footnote:null}),um=dn("workflow",{state:()=>({snapshot:Gf(),live:!1,exiting:!1}),getters:{isActive(s){return s.snapshot.active}},actions:{setWorkflow(s,e=!1){if(this.live=e,!s||s.active!==!0){if(this.exiting){e||(this.exiting=!1,this.snapshot=Gf());return}if(e&&this.snapshot.active){this.exiting=!0;return}this.snapshot=Gf();return}this.exiting=!1,this.snapshot={...Gf(),...s,active:!0}},finishExit(){this.exiting=!1,this.live=!1,this.snapshot=Gf()},reset(){this.snapshot=Gf(),this.live=!1,this.exiting=!1},async fetchStatus(s){var e;try{const t=await fetch(`/api/workflow/status?conversation_id=${encodeURIComponent(s)}`,{credentials:"same-origin"}),n=await t.json().catch(()=>({}));t.ok&&(n!=null&&n.success)&&((e=n==null?void 0:n.snapshot)==null?void 0:e.active)===!0?this.setWorkflow(n.snapshot,!1):this.reset()}catch{this.reset()}}}}),X2="agents_quick_dock_had_content",CH=()=>{if(typeof window>"u"||!window.localStorage)return!1;try{return window.localStorage.getItem(X2)==="1"}catch{return!1}},TH=s=>{if(!(typeof window>"u"||!window.localStorage))try{window.localStorage.setItem(X2,s?"1":"0")}catch(e){console.warn("写入快捷窗口内容状态缓存失败:",e)}},Y2="agents_quick_dock_conv_content",KM=50,J2=()=>{if(typeof window>"u"||!window.localStorage)return{};try{const s=window.localStorage.getItem(Y2),e=s?JSON.parse(s):{};return e&&typeof e=="object"?e:{}}catch{return{}}},AH=s=>J2()[s]===!0,EH=(s,e)=>{if(!(typeof window>"u"||!window.localStorage||!s))try{const t=J2();delete t[s],t[s]=e;const n=Object.keys(t);if(n.length>KM)for(const i of n.slice(0,n.length-KM))delete t[i];window.localStorage.setItem(Y2,JSON.stringify(t))}catch(t){console.warn("写入快捷窗口对话内容缓存失败:",t)}},QM=()=>{if(typeof window<"u"){const s=window.location.pathname.replace(/\/+$/,"")||"/";if(s==="/"||s==="/new")return!1}return CH()},Bo=dn("quickDock",{state:()=>({editedFiles:[],editedFilesLive:!1,detail:null,previewPath:null,menu:null,userCollapsed:!1,assumedContent:QM(),assumedActive:QM(),filesSyncSeq:0}),getters:{hasContent(s){var a,c;const e=Tc(),t=oh(),n=cm(),i=um(),o=(((c=(a=e.todoList)==null?void 0:a.tasks)==null?void 0:c.length)||0)>0||t.subAgents.length>0||n.commands.length>0||s.editedFiles.length>0;return i.isActive||i.exiting||(s.assumedActive?s.assumedContent:o)},expanded(s){return this.hasContent&&!s.userCollapsed}},actions:{setEditedFiles(s,e=!1){if(this.filesSyncSeq+=1,this.editedFilesLive=e,!Array.isArray(s)){this.editedFiles=[];return}const t=new Set,n=[];for(const i of s)!i||typeof i.path!="string"||!i.path||t.has(i.path)||(t.add(i.path),n.push({path:i.path,op:i.op,ts:i.ts}));this.editedFiles=n,this.previewPath&&!t.has(this.previewPath)&&(this.previewPath=null)},openDetail(s,e){if(e){if(this.detail&&this.detail.kind===s&&this.detail.id===e){this.detail=null;return}this.detail={kind:s,id:e}}},closeDetail(){this.detail=null},openPreview(s){if(s){if(this.previewPath===s){this.previewPath=null;return}this.previewPath=s}},closePreview(){this.previewPath=null},openMenu(s){if(this.menu&&this.menu.type===s.type&&this.menu.key===s.key){this.menu=null;return}this.menu=s},closeMenu(){this.menu=null},resetTransient(){this.detail=null,this.previewPath=null,this.menu=null},settleInitialContent(){this.assumedActive=!1,this.assumedContent=!1},assumeContentForConversation(s){this.assumedContent=s?AH(s):!1,this.assumedActive=!0}}}),MH={class:"file-chip-row",role:"list"},xH=["title","onClick"],IH={width:"22",height:"22",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true"},RH={class:"file-chip-meta"},LH={class:"file-chip-name"},PH={class:"file-chip-type"},OH=["aria-label","onClick"],DH="M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",NH=at({__name:"FileChips",props:{files:{default:()=>[]},removable:{type:Boolean,default:!1}},emits:["remove"],setup(s){const e={doc:{kind:"word",label:"文档"},docx:{kind:"word",label:"文档"},xls:{kind:"excel",label:"电子表格"},xlsx:{kind:"excel",label:"电子表格"},csv:{kind:"excel",label:"电子表格"},ppt:{kind:"ppt",label:"演示文稿"},pptx:{kind:"ppt",label:"演示文稿"},pdf:{kind:"pdf",label:"PDF"},txt:{kind:"text",label:"文本"},md:{kind:"text",label:"文本"},log:{kind:"text",label:"文本"},zip:{kind:"archive",label:"压缩包"},tar:{kind:"archive",label:"压缩包"},gz:{kind:"archive",label:"压缩包"},tgz:{kind:"archive",label:"压缩包"},bz2:{kind:"archive",label:"压缩包"},xz:{kind:"archive",label:"压缩包"},"7z":{kind:"archive",label:"压缩包"},rar:{kind:"archive",label:"压缩包"}},t=new Set(["js","mjs","cjs","ts","jsx","tsx","vue","py","java","c","h","cpp","cc","hpp","go","rs","rb","php","html","htm","css","scss","less","json","xml","yml","yaml","toml","ini","cfg","sh","bash","zsh","sql","swift","kt","kts","lua","r","dart"]),n=s,i=h=>{const d=String(h||"").split(/[/\\]/).filter(Boolean);return d.length?d[d.length-1]:String(h||"")},r=h=>{const d=(h.includes(".")&&h.split(".").pop()||"").trim().toLowerCase();return d&&e[d]?e[d]:d&&t.has(d)?{kind:"code",label:"代码"}:{kind:"generic",label:"文件"}},o=ye(()=>(n.files||[]).map(h=>{const d=typeof h=="string"?h:String((h==null?void 0:h.path)||"");if(!d)return null;const p=typeof h=="object"&&h&&typeof h.name=="string"&&h.name||i(d),{kind:m,label:v}=r(p);return{path:d,name:p,kind:m,label:v}}).filter(h=>!!h)),a=Bo(),c=Vs(),l=ye(()=>!c.isMobileViewport),u=h=>{l.value&&a.previewPath!==h.path&&a.openPreview(h.path)};return(h,d)=>(F(),$("div",MH,[(F(!0),$(Ie,null,tt(o.value,p=>(F(),$("div",{key:p.path,class:ke(["file-chip",{"is-clickable":l.value,"is-previewing":l.value&&We(a).previewPath===p.path}]),role:"listitem",title:p.name,onClick:m=>u(p)},[E("span",{class:"file-chip-icon",style:Ke({background:`var(--file-kind-${p.kind})`})},[(F(),$("svg",IH,[E("path",{d:DH}),d[16]||(d[16]=E("path",{d:"M14 2v5a1 1 0 0 0 1 1h5"},null,-1)),p.kind==="word"?(F(),$(Ie,{key:0},[d[0]||(d[0]=E("path",{d:"M9 13h6"},null,-1)),d[1]||(d[1]=E("path",{d:"M9 16.5h6"},null,-1))],64)):p.kind==="excel"?(F(),$(Ie,{key:1},[d[2]||(d[2]=E("path",{d:"M9 12h6v5H9z"},null,-1)),d[3]||(d[3]=E("path",{d:"M9 14.5h6"},null,-1)),d[4]||(d[4]=E("path",{d:"M12 12v5"},null,-1))],64)):p.kind==="ppt"?(F(),$(Ie,{key:2},[d[5]||(d[5]=E("path",{d:"M9.5 17v-3.5"},null,-1)),d[6]||(d[6]=E("path",{d:"M12.5 17V12"},null,-1)),d[7]||(d[7]=E("path",{d:"M15.5 17v-2"},null,-1))],64)):p.kind==="pdf"?(F(),$(Ie,{key:3},[d[8]||(d[8]=E("path",{d:"M12 11.5v6"},null,-1)),d[9]||(d[9]=E("path",{d:"m9.5 15 2.5 2.5 2.5-2.5"},null,-1))],64)):p.kind==="text"?(F(),$(Ie,{key:4},[d[10]||(d[10]=E("path",{d:"M9 13h6"},null,-1)),d[11]||(d[11]=E("path",{d:"M9 16.5h4"},null,-1))],64)):p.kind==="code"?(F(),$(Ie,{key:5},[d[12]||(d[12]=E("path",{d:"m10 12.5-2 2 2 2"},null,-1)),d[13]||(d[13]=E("path",{d:"m14 12.5 2 2-2 2"},null,-1))],64)):p.kind==="archive"?(F(),$(Ie,{key:6},[d[14]||(d[14]=E("path",{d:"M9 12.5h6v4.5H9z"},null,-1)),d[15]||(d[15]=E("path",{d:"M11 12.5V11h2v1.5"},null,-1))],64)):ge("",!0)]))],4),E("span",RH,[E("span",LH,ae(p.name),1),E("span",PH,ae(p.label),1)]),s.removable?(F(),$("button",{key:0,type:"button",class:"file-chip-remove","aria-label":`移除 ${p.name}`,onClick:Ne(m=>h.$emit("remove",p.path),["stop"])},[...d[17]||(d[17]=[E("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none","aria-hidden":"true"},[E("path",{d:"M2.5 2.5l5 5M7.5 2.5l-5 5",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round"})],-1)])],8,OH)):ge("",!0)],10,xH))),128))]))}}),Z2=Qt(NH,[["__scopeId","data-v-ffb20906"]]),BH={key:0,class:"compact-brief-line",role:"separator"},FH={class:"compact-brief-text"},$H={key:0},HH=["innerHTML"],UH={key:1,class:"image-inline-row"},WH=["onClick"],zH=["src","alt"],jH={key:2,class:"image-inline-row video-inline-row"},VH=["src","alt"],GH={key:3,class:"user-bubble-expand-row"},qH=["title","aria-label","onClick"],KH={key:0,class:"user-bubble-actions"},QH=["title","aria-label","onClick"],XH=["onClick"],YH={class:"user-bubble-time"},JH={key:1,class:"assistant-message"},ZH={key:0,class:"message-header icon-label"},e6={key:0,class:"assistant-work-status"},t6={key:1,class:"action-item streaming-content immediate-show assistant-generating-block"},s6={class:"text-output"},n6={class:"text-content assistant-generating-placeholder",role:"status","aria-live":"polite"},i6=["data-block-id"],r6=["onClick"],o6={class:"status-icon"},a6={class:"status-text"},l6=["onScroll"],c6={key:1,class:"text-output"},u6={key:2,class:"sub-agent-system-summary-line"},h6={class:"append-placeholder-content"},d6={key:0,class:"icon-label append-status"},f6={key:1,class:"icon-label append-status append-error-text"},p6={key:2,class:"append-meta"},g6={key:0},m6={key:1},v6={key:3,class:"append-warning icon-label"},y6={class:"append-placeholder-content"},b6={class:"icon-label append-status"},_6={key:0,class:"append-meta"},S6={key:0},w6={key:1},k6={key:1,class:"append-warning icon-label"},C6=["data-block-id"],T6=["onClick"],A6={class:"status-icon"},E6={class:"status-text"},M6=["onScroll"],x6={key:1,class:"text-output"},I6={key:2,class:"sub-agent-system-summary-line"},R6={class:"append-placeholder-content"},L6={key:0,class:"icon-label append-status"},P6={key:1,class:"icon-label append-status append-error-text"},O6={key:2,class:"append-meta"},D6={key:0},N6={key:1},B6={key:3,class:"append-warning icon-label"},F6={class:"append-placeholder-content"},$6={class:"icon-label append-status"},H6={key:0,class:"append-meta"},U6={key:0},W6={key:1},z6={key:1,class:"append-warning icon-label"},j6={key:2,class:"system-message"},V6=["data-block-id"],G6=["onClick"],q6={class:"status-icon"},K6={class:"status-text"},Q6={class:"content-inner"},X6=["onClick"],Y6={class:"quick-nav-preview-user"},J6={class:"quick-nav-preview-ai"},eC=10,Z6="生成中…",tC=240,qf=8,eU=900,tU=36,XM=48.74,sC=34,YM=116,sU=at({__name:"ChatArea",props:{messages:{},iconStyle:{type:Function},expandedBlocks:{},streamingMessage:{type:Boolean},toggleBlock:{type:Function},handleThinkingScroll:{type:Function},renderMarkdown:{type:Function},getToolIcon:{type:Function},getToolStatusText:{type:Function},getToolAnimationClass:{type:Function},getToolDescription:{type:Function},formatSearchTopic:{type:Function},formatSearchTime:{type:Function},formatSearchDomains:{type:Function},historyLoading:{type:Boolean}},emits:["stick-state-change","user-scroll-intent"],setup(s,{expose:e,emit:t}){const n=s,i=t,r=qs(),o=ye(()=>!!r.loaded||!!r.error),a=ye(()=>!!n.historyLoading||!o.value),c=ye(()=>r.experiments.blockDisplayMode||"stacked"),l=ye(()=>r.form.compact_message_display||r.experiments.compactMessageDisplay||"full"),u=ye(()=>c.value==="stacked"||c.value==="minimal"),h=ye(()=>r.form.use_custom_names&&r.form.self_identify||"Astrion"),d=ye(()=>r.form.use_custom_names&&r.form.user_name||"用户"),p=new Map,m=pe({}),v=pe(new Set),g=pe(!1);let y=null,b=new Map,_=0;const w=(q,te)=>(q==null?void 0:q.id)||`user-bubble-${te}`,S=(q,te,Z)=>{const re=w(q,te);if(Z instanceof HTMLElement){p.set(re,Z),y&&y.observe(Z);const Ae=m.value[re];Ae&&Ae.foldHeight===0&&requestAnimationFrame(()=>{Z.isConnected&&k()})}else p.delete(re)},C=q=>{const te=typeof(q==null?void 0:q.content)=="string"?q.content:"";if(!te)return!1;const re=48*(eC+2),Ae=(te.match(/\n/g)||[]).length;return te.length>re||Ae>=eC+2},T=()=>{(Array.isArray(st.value)?st.value:[]).forEach((q,te)=>{if(!q||q.role!=="user")return;const Z=w(q,te);if(m.value[Z])return;const re=C(q);m.value[Z]={needsFold:re,expanded:!1,foldHeight:0,fullHeight:0}})},k=()=>{p.forEach((q,te)=>{if(!q.isConnected){p.delete(te);return}const Z=window.getComputedStyle(q),re=parseFloat(Z.lineHeight),Ae=Number.isFinite(re)?re:24,ue=Math.round(Ae*eC),Ge=Math.ceil(q.scrollHeight),pt=Ge>ue+1,Bt=m.value[te];m.value[te]={needsFold:pt,expanded:(Bt==null?void 0:Bt.expanded)??!1,foldHeight:ue,fullHeight:Ge},q.style.setProperty("--bubble-fold-height",`${ue}px`),q.style.setProperty("--bubble-full-height",`${Ge}px`)})},A=(q,te)=>{var re;const Z=w(q,te);return!!((re=m.value[Z])!=null&&re.needsFold)},M=(q,te)=>{var re;const Z=w(q,te);return!!((re=m.value[Z])!=null&&re.expanded)},R=(q,te)=>{const Z=w(q,te),re=m.value[Z];return!!(re!=null&&re.needsFold)&&!(re!=null&&re.expanded)},P=(q,te)=>{const Z=w(q,te),re=m.value[Z];!re||!re.needsFold||(m.value[Z]={...re,expanded:!re.expanded})},L=q=>{const te=q==null?void 0:q.created_at;if(!te)return"";const Z=new Date(te),Ae=Math.max(0,new Date().getTime()-Z.getTime()),ue=Math.floor(Ae/1e3),Ge=Math.floor(ue/60),pt=Math.floor(Ge/60);if(Math.floor(pt/24)>=1){const Rt=Z.getMonth()+1,Ps=Z.getDate(),Us=String(Z.getHours()).padStart(2,"0"),Er=String(Z.getMinutes()).padStart(2,"0");return`${Rt}月${Ps}日 ${Us}:${Er}`}return pt>0?`${pt}小时前`:Ge>0?`${Ge}分钟前`:ue>0?`${ue}秒前`:"刚刚"},z=(q,te)=>{const Z=w(q,te);return v.value.has(Z)},Q=async(q,te)=>{const Z=w(q,te),re=typeof(q==null?void 0:q.content)=="string"?q.content:"";if(!(!re||v.value.has(Z)))try{await navigator.clipboard.writeText(re),v.value.add(Z);const Ae=b.get(Z);Ae&&window.clearTimeout(Ae);const ue=window.setTimeout(()=>{v.value.delete(Z),b.delete(Z)},5e3);b.set(Z,ue)}catch(Ae){console.warn("复制用户消息失败:",Ae)}},W=q=>{},V=()=>{y&&(y.disconnect(),p.forEach(q=>{q.isConnected&&y.observe(q)}))},N=()=>{const q=++_;requestAnimationFrame(()=>{requestAnimationFrame(()=>{q===_&&(g.value=!1)})})},O=/^来自\s+(.+?)\s+的(.+?)\nid:\s*(\S+)\n\n<(.+?)>\n<(\w+)([^>]*)>\n([\s\S]*?)\n<\/\5>\n<\/\4>$/;function H(q){const Z=String(q||"").match(O);if(!Z)return null;const Ae=(Z[6]||"").match(/subtype="([^"]+)"/);return{displayName:Z[1].trim(),subtype:Ae?Ae[1]:"",content:Z[7]}}function G(q){if(!q||q.role!=="user")return!1;const te=q.metadata||{};return String(te.auto_message_type||q.auto_message_type||"").startsWith("multi_agent_")}function ee(q){var re;const te=((re=q==null?void 0:q.metadata)==null?void 0:re.multi_agent_display_name)||(q==null?void 0:q.multi_agent_display_name);if(te)return te;const Z=H((q==null?void 0:q.content)||"");return(Z==null?void 0:Z.displayName)||"子智能体"}function ie(q,te){if(!G(q))return!1;const re=et()[te-1];return!re||!G(re)?!1:ee(q)===ee(re)}function ve(q){const te=H((q==null?void 0:q.content)||"");return((te==null?void 0:te.content)||(q==null?void 0:q.content)||"").trim()}const le=q=>String(q||"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),oe=/\[\$([^\]\n]+)\]\(((?:[^)\n]*[\\/])?\.astrion[\\/]skills[\\/][^)\n]+[\\/]SKILL\.md)\)/g,I=/\[([^\]\n]+)\]\(file:\/\/([^)\n]+)\)/g,K=/^子智能体\d+\s*任务完成$/,X=/^(?:✅\s*)?子智能体\s*#?\s*(\d+)\s*任务摘要[:]/,J=/^(?:\[)?后台\s*run_command\s*完成(?:\])?$/,he=new Set(["thinking","text","tool","append","append_payload","system"]);function be(q){const te=String(q||""),Z=new RegExp(`(?:${oe.source})|(?:${I.source})`,"g");let re="",Ae=0,ue;for(;ue=Z.exec(te);)re+=le(te.slice(Ae,ue.index)),ue[1]!==void 0?re+=` <span class="user-skill-link">${le(ue[1]||"")}</span> `:ue[3]!==void 0&&(re+=` <span class="user-file-link">${le(ue[3]||"")}</span> `),Ae=ue.index+ue[0].length;return re+=le(te.slice(Ae)),re}const Re=q=>!q||q.role!=="user"?!1:Oh(q)==="hidden",rt=q=>!q||q.role!=="assistant"||(Array.isArray(q.actions)?q.actions:[]).some(Ae=>ei(Ae))||q.awaitingFirstContent?!1:!!!(q.streaming||q.currentStreamingType||q.streamingText||q.streamingThinking),st=ye(()=>{const q=n.messages||[];q.filter(re=>re&&re.role==="system").length>0;const Z=q.filter(re=>re&&re.metadata&&re.metadata.system_injected_image||(re==null?void 0:re.role)==="system"||Re(re)?!1:rt(re)?(Le("ChatArea.filteredMessages:drop-empty-assistant",{actions:Array.isArray(re==null?void 0:re.actions)?re.actions.map(Ae=>Ae==null?void 0:Ae.type):[],awaitingFirstContent:!!(re!=null&&re.awaitingFirstContent)}),!1):!0);return q.length!==Z.length&&Le("ChatArea.filteredMessages:dropped",{sourceLength:q.length,resultLength:Z.length,dropped:q.length-Z.length}),Z}),et=()=>Array.isArray(st.value)?st.value:[],De=ye(()=>{var re,Ae,ue;const q=new Map,te=et(),Z=!!r.form.edit_summary_live_display;for(let Ge=0;Ge<te.length;Ge+=1){const pt=te[Ge];if(!pt||pt.role!=="user"||!kv(pt))continue;const Bt=(re=pt.metadata)==null?void 0:re.edit_summary;if(!Bt||!Array.isArray(Bt.files)||Bt.files.length===0)continue;if(!Z){const Ps=(ue=(Ae=pt.metadata)==null?void 0:Ae.work_timer)==null?void 0:ue.status;if(Ps&&Ps!=="completed")continue}let Rt=-1;for(let Ps=Ge+1;Ps<te.length;Ps+=1){const Us=te[Ps];if((Us==null?void 0:Us.role)==="user"&&kv(Us))break;(Us==null?void 0:Us.role)==="assistant"&&(Rt=Ps)}Rt>=0&&q.set(Rt,Bt)}return q}),xe=ye(()=>et().length-1),se=pe(Date.now());let ce=null;const de=new Set,we=new Set,Le=(...q)=>{},{scrollRef:He,contentRef:yt,isAtBottom:At,isNearBottom:Nt,escapedFromLock:It,scrollToBottom:Jt,stopScroll:$t}=P$({resize:"instant",initial:"instant"}),As=new WeakMap;let ut=0;const Hs=(q,te)=>{if(q&&typeof q=="object"){let Z=As.get(q);if(!Z){const re=q.id;Z=re!=null?`msg-${String(re)}`:`mk-${++ut}`,As.set(q,Z)}return Z}return`idx-${te}`},hl=ye(()=>He.value??void 0),In=ye(()=>{if(!n.streamingMessage)return[];const q=xe.value;return q>=0?[q]:[]});MF("mathRenderedCallback",()=>{_a||Nt.value&&Ue&&requestAnimationFrame(()=>{Ue({preserveScrollPosition:!1})})});const Uo=He,{anchorBlockElement:nr,stopAll:Qs}=Q$(He,{stopScroll:$t});let Yn=null;function Rn(){if(Yn=null,!n.streamingMessage)return;const q=He.value;if(q&&!_a&&At.value&&!It.value){const te=q.scrollHeight-q.clientHeight;te-q.scrollTop>1&&(wr("ChatArea.liveStickLock"),q.scrollTop=te)}Yn=requestAnimationFrame(Rn)}function ir(){Yn!==null&&(cancelAnimationFrame(Yn),Yn=null)}Xe(()=>n.streamingMessage,q=>{q?Yn===null&&(Yn=requestAnimationFrame(Rn)):ir()},{immediate:!0});const Wo=new Map;let Ln=null,ma=0;const zo=new Map;let io=0,dl=0,Jn=0,jo=0,va=0,fe="",me=0,Ce=!1,dt=null,qt=null,Ss=null,Kt=null,Es=null,ht=!1,pn=0,Vo=!1;function Ff(q){const te=He.value;if(!te||!(q instanceof HTMLElement))return!1;let Z=q;for(;Z&&Z!==te;){if(Z.scrollHeight>Z.clientHeight+2){const re=getComputedStyle(Z).overflowY;if(re==="auto"||re==="scroll")return!0}Z=Z.parentElement}return!1}function fl(){var q;if(typeof window>"u")return!1;try{const te=window.__SCROLL_BOUNCE_TRACE__;if(te===!1||te==="0")return!1;if(te===!0||te==="1")return!0;const Z=(q=window.localStorage)==null?void 0:q.getItem("scrollBounceTrace");return Z==="0"||Z==="false"?!1:Z==="1"||Z==="true"}catch{return!1}}function Di(q){const te=q.scrollTop,Z=q.scrollHeight,re=q.clientHeight;return{top:te,height:Z,client:re,remain:Z-te-re,hasShowHtml:!!q.querySelector("show_html, show-html, .chat-inline-html, .chat-inline-card--html")}}function Tn(q,te={},Z=q,re=120){if(!fl()||ma>=tC)return;const Ae=Date.now(),ue=zo.get(Z)||0;if(!(re>0&&Ae-ue<re)){if(zo.set(Z,Ae),ma+=1,ma===tC){console.warn("[SCROLL_BOUNCE_TRACE]","log-limit-reached",{max:tC});return}console.log("[SCROLL_BOUNCE_TRACE]",q,te)}}function wr(q){va=Date.now(),fe=q}function kr(){const q=He.value;q&&dt&&q.removeEventListener("scroll",dt),q&&qt&&q.removeEventListener("wheel",qt,!0),q&&Ss&&q.removeEventListener("touchstart",Ss,!0),q&&Kt&&q.removeEventListener("touchmove",Kt,!0),q&&Es&&(q.removeEventListener("touchend",Es,!0),q.removeEventListener("touchcancel",Es,!0)),dt=null,qt=null,Ss=null,Kt=null,Es=null}function Ni(){const q=He.value;q&&(dt&&q.removeEventListener("scroll",dt),qt&&q.removeEventListener("wheel",qt,!0),Ss&&q.removeEventListener("touchstart",Ss,!0),Kt&&q.removeEventListener("touchmove",Kt,!0),Es&&(q.removeEventListener("touchend",Es,!0),q.removeEventListener("touchcancel",Es,!0)),io=q.scrollTop||0,dl=q.scrollHeight||0,pn=0,Vo=!1,Ss=te=>{if(te.touches.length!==1){pn=0,Vo=!1;return}pn=te.touches[0].clientY,Vo=!1},Kt=te=>{if(Vo||!pn||te.touches.length!==1)return;const Z=He.value;if(!Z)return;const re=te.touches[0].clientY-pn;if(re<=8)return;const Ae=Date.now();Ae<=me||Ff(te.target)||(Vo=!0,jo=Ae,$t(),Qs(),Hf(),i("user-scroll-intent",{ts:Ae,delta:-re,top:Z.scrollTop||0}),Tn("user-scroll-intent:touch-drag",{deltaY:re,top:Z.scrollTop||0,...Di(Z)},"user-scroll-intent:touch-drag",80))},Es=()=>{pn=0,Vo=!1},q.addEventListener("touchstart",Ss,{passive:!0,capture:!0}),q.addEventListener("touchmove",Kt,{passive:!0,capture:!0}),q.addEventListener("touchend",Es,{passive:!0,capture:!0}),q.addEventListener("touchcancel",Es,{passive:!0,capture:!0}),qt=te=>{const Z=He.value;if(!Z)return;const re=te.isTrusted===!0,Ae=Number(te.deltaY||0);if(!(re&&Ae<-1&&Date.now()>me))return;const ue=Date.now();jo=ue,$t(),Qs(),Hf(),i("user-scroll-intent",{ts:ue,delta:Ae,top:Z.scrollTop||0}),Tn("user-scroll-intent:wheel-up",{deltaY:Ae,top:Z.scrollTop||0,...Di(Z)},"user-scroll-intent:wheel-up",80)},q.addEventListener("wheel",qt,{passive:!0,capture:!0}),dt=te=>{const Z=te.target;if(!Z)return;const re=te.isTrusted===!0,Ae=Z.scrollTop,ue=Ae-io,Ge=Z.scrollHeight||0,pt=Ge-dl;io=Ae,dl=Ge,Nc(Ae),pt!==0&&Tn("height-change",{heightDelta:pt,scrollHeight:Ge,top:Ae,delta:ue,escapedFromLock:It.value,isAtBottom:At.value,isNearBottom:Nt.value},"height-change",120);const Bt=Math.max(200,Z.clientHeight*.35||200);!Ce&&pt>Bt&&!It.value&&(Tn("large-growth:trigger",{heightDelta:pt,threshold:Bt,top:Ae,delta:ue,escapedFromLock:It.value,isAtBottom:At.value,isNearBottom:Nt.value},"large-growth:trigger",0),Ce=!0,wr("ChatArea.largeGrowth"),me=Date.now()+900,Jt({animation:"instant",preserveScrollPosition:!1}),Tn("large-growth:instant-scroll",{heightDelta:pt,threshold:Bt,...Di(Z)},"large-growth:instant-scroll",120),setTimeout(()=>{Ce=!1},400));const Rt=Date.now(),Ps=Rt-va<=140,Us=Math.abs(pt)>2,Er=ue<-3&&Rt-jo<=240,Mr=ue<-18&&Rt>me&&!Ps;if(re&&Math.abs(ue)>5&&Rt>me&&(!Ps||Mr)&&(ue<0&&(Mr||Er)||!Us)&&($t(),Qs(),Jn=Rt,i("user-scroll-intent",{ts:Jn,delta:ue,top:Ae}),Tn("user-scroll-intent",{delta:ue,top:Ae,ts:Jn,closeToProgrammaticHint:Ps,likelyLayoutDriven:Us,manualUpByWheel:Er,strongManualUp:Mr,...Di(Z)},"user-scroll-intent",120)),ue<-8){if(Rt-Jn<=1400){const Sa=Rt-va<=1200;Tn("rebound:detected",{delta:ue,trusted:re,likelySource:Sa?fe||"programmatic-unknown":"unknown(internal-stick/browser-anchor)",msSinceUserDown:Rt-Jn,msSinceProgrammatic:Rt-va,...Di(Z),stickState:{isAtBottom:!!At.value,isNearBottom:!!Nt.value,escapedFromLock:!!It.value}},"rebound:detected",0)}}else Tn("scroll:event",{delta:ue,trusted:re,...Di(Z),stickState:{isAtBottom:!!At.value,isNearBottom:!!Nt.value,escapedFromLock:!!It.value}},"scroll:event",180)},q.addEventListener("scroll",dt,{passive:!0}),!ht&&fl()&&(ht=!0,console.warn("[SCROLL_BOUNCE_TRACE]","listener-attached",{hasElement:!!q,className:q.className||""})))}function pl(){const q=He.value;if(!q)return;const te=Math.max(0,q.offsetWidth-q.clientWidth);q.style.setProperty("--chat-scrollbar-width",`${te}px`)}Xe([At,Nt,It],([q,te,Z])=>{i("stick-state-change",{isAtBottom:!!q,isNearBottom:!!te,escapedFromLock:!!Z})},{immediate:!0});function $f(q){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(q):q.replace(/["\\]/g,"\\$&")}const ya=pe(new Set);function gl(q){return n.streamingMessage?_a?!0:!(!It.value&&!!At.value)||!q?!1:q.classList.contains("processing")||q.classList.contains("running")||!!q.querySelector(".processing, .running, .thinking-animation"):!1}Xe(()=>n.expandedBlocks,(q,te)=>{const Z=te??ya.value,re=new Set([...Array.from(q),...Array.from(Z)]),Ae=new Set;for(const Ge of re)q.has(Ge)!==Z.has(Ge)&&Ae.add(Ge);if(ya.value=new Set(q),Ae.size===0)return;const ue=He.value;if(ue)for(const Ge of Ae){const pt=ue.querySelector(`[data-block-id="${$f(Ge)}"]`);gl(pt)||pt&&nr(pt,Ge,{direction:"auto",duration:260,phase:q.has(Ge)?"expand":"collapse"})}},{flush:"post"});function Rc(q){gl(q.element)||nr(q.element,`more-${q.stackKey}`,{direction:"auto",duration:260,phase:expanded?"expand":"collapse"})}function ba(q){const{groupId:te,expanded:Z}=q,re=He.value;if(!re)return;const Ae=re.querySelector(`[data-group-id="${$f(te)}"]`);gl(Ae)||Ae&&nr(Ae,te,{direction:"auto",duration:300,phase:Z?"expand":"collapse"})}const Je=(q,te)=>{if(!(te instanceof HTMLElement))return;const Z=600;requestAnimationFrame(()=>{const re=te.scrollHeight||te.offsetHeight||0;re>0&&te.style.setProperty("--collapse-max",`${Math.min(re,Z)}px`)})};function ne(q,te){te instanceof HTMLElement?Wo.set(q,te):Wo.delete(q)}function Ee(q){return Wo.get(q)||null}async function Ue(q={}){const te=He.value;return te&&Tn("programmatic:scrollToBottom:before",{source:"ChatArea.stickScrollToBottom",behavior:q.behavior||"auto",force:!!q.force,preserveScrollPosition:!!q.preserveScrollPosition,...Di(te)},"programmatic:scrollToBottom:before",80),wr("ChatArea.stickScrollToBottom"),(q.force||q.behavior==="smooth")&&(me=Date.now()+900),await Jt({animation:q.behavior==="smooth"?"smooth":"auto",ignoreEscapes:!!q.force,preserveScrollPosition:!!q.preserveScrollPosition,duration:q.force?260:0})}async function zt(q={}){const te=He.value;return te&&Tn("programmatic:conditional:before",{source:"ChatArea.stickConditionalScrollToBottom",force:!!q.force,...Di(te)},"programmatic:conditional:before",100),wr("ChatArea.stickConditionalScrollToBottom"),q.force?await Ue({force:!0,preserveScrollPosition:!1}):await Ue({preserveScrollPosition:!1})}function Mt(){return{isAtBottom:!!At.value,isNearBottom:!!Nt.value,escapedFromLock:!!It.value}}function mt(q,te){return typeof n.iconStyle=="function"?n.iconStyle(q,te):{}}function ws(q){return q?typeof q=="string"?q:typeof(q==null?void 0:q.path)=="string"?q.path:typeof(q==null?void 0:q.source_path)=="string"?q.source_path:"":""}function Pn(q){const te=ws(q);if(!te)return typeof(q==null?void 0:q.name)=="string"&&q.name?q.name:typeof(q==null?void 0:q.title)=="string"&&q.title?q.title:typeof(q==null?void 0:q.media_id)=="string"&&q.media_id?q.media_id:"";const Z=te.split(/[/\\]/);return Z[Z.length-1]||te}function On(q){var Z;const te=(Z=q==null?void 0:q.metadata)==null?void 0:Z.files;return Array.isArray(te)?te.filter(re=>typeof re=="string"&&re||re&&typeof re.path=="string"&&re.path).slice(0,9):[]}function Go(q,te){const Z=ts(q,te,"image");Z&&Vs().openImagePreview({url:Z,name:Pn(te)})}function Ms(q,te,Z){var pt;const re=(q==null?void 0:q.media_refs)||((pt=q==null?void 0:q.metadata)==null?void 0:pt.media_refs)||[];if(!Array.isArray(re)||!re.length)return null;const Ae=typeof(te==null?void 0:te.media_id)=="string"?te.media_id:"";if(Ae){const Bt=re.find(Rt=>(Rt==null?void 0:Rt.media_id)===Ae);if(Bt)return Bt}const ue=ws(te);if(ue){const Bt=re.find(Rt=>Rt&&Rt.kind===Z&&typeof Rt.source_path=="string"&&Rt.source_path===ue);if(Bt)return Bt}return re.find(Bt=>Bt&&Bt.kind===Z)||null}function ts(q,te,Z){const re=Ms(q,te,Z),Ae=typeof(re==null?void 0:re.media_id)=="string"?re.media_id:"";if(Ae)return`/api/conversations/media/${encodeURIComponent(Ae)}`;const ue=ws(te);return ue?`/api/gui/files/download?path=${encodeURIComponent(ue)}`:""}function Dn(q,te,Z){const re=Ms(q,te,"image")||Ms(q,te,"video");if(typeof(re==null?void 0:re.media_id)=="string"&&re.media_id)return`${re.media_id}-${Z}`;const Ae=ws(te);return Ae?`${Ae}-${Z}`:`media-${Z}`}function Lc(q){const te=Math.max(0,Math.floor((q||0)/1e3)),Z=Math.floor(te/3600),re=Math.floor(te%3600/60),Ae=te%60;return Z>0?`${String(Z).padStart(2,"0")}:${String(re).padStart(2,"0")}:${String(Ae).padStart(2,"0")}`:`${String(re).padStart(2,"0")}:${String(Ae).padStart(2,"0")}`}function Zn(q){if(!q||q.type!=="system")return null;const te=typeof q.content=="string"?q.content.trim():"",Z=(q==null?void 0:q.id)||`no-id-${te.slice(0,32)}`;if(!te)return de.has(`${Z}-empty`)||de.add(`${Z}-empty`),null;if(q.variant==="sub_agent_done"&&(K.test(te)||J.test(te)))return de.has(`${Z}-variant-pass`)||de.add(`${Z}-variant-pass`),te;const re=te.match(X);return re&&/已完成/.test(te)?(de.has(`${Z}-regex-pass`)||de.add(`${Z}-regex-pass`),`子智能体${re[1]} 任务完成`):(de.has(`${Z}-blocked`)||de.add(`${Z}-blocked`),null)}function ei(q){if(!q)return!1;const te=q.type;if(!he.has(te)){const Z=(q==null?void 0:q.id)||`unknown-${te||"none"}`;return we.has(Z)||we.add(Z),!1}if(q.type==="tool"){const Z=(q==null?void 0:q.tool)||{},re=typeof Z.name=="string"&&Z.name.trim().length>0,Ae=typeof Z.message=="string"&&Z.message.trim().length>0,ue=Z.result!==null&&Z.result!==void 0,Ge=Z.arguments&&typeof Z.arguments=="object"&&Object.keys(Z.arguments).length>0;return re||Ae||ue||Ge}return q.type!=="system"?!0:!!Zn(q)}function Cr(q=[]){return(q||[]).some(te=>ei(te))}function pm(q){if(!q||q.role!=="assistant")return!1;const te=(q.actions||[]).filter(Ae=>ei(Ae));if(te.length!==1)return!1;const Z=te[0],re=(Z==null?void 0:Z.type)==="system"&&!!Zn(Z);return re&&Le("ChatArea.isSubAgentNoticeOnlyMessage:hit",{actionId:Z==null?void 0:Z.id,content:Z==null?void 0:Z.content}),re}function Ck(q){var Ae;const te=et(),Z=te[q+1],re=!!Z&&pm(Z);return re&&Le("ChatArea.isFollowedBySubAgentNotice:hit",{index:q,currentRole:(Ae=te[q])==null?void 0:Ae.role,nextRole:Z==null?void 0:Z.role}),re}function a_(q){var Ge;if(q<=0)return"";const te=l_(q),Z=(Ge=te==null?void 0:te.metadata)==null?void 0:Ge.work_timer;if(!Z||!Z.started_at)return"";const re=Date.parse(Z.started_at);if(!Number.isFinite(re))return"";if((Z.status||"working")==="working")return`工作中 ${Lc(se.value-re)}`;const ue=typeof Z.duration_ms=="number"?Z.duration_ms:Math.max(0,(Number.isFinite(Date.parse(Z.finished_at||""))?Date.parse(Z.finished_at):se.value)-re);return`工作完成 ${Lc(ue)}`}function Tk(q){return!!l_(q)}function l_(q){if(q<=0)return null;const te=et(),Z=te[q-1];if(!Z||Z.role!=="user")return null;for(let re=q-1;re>=0;re-=1){const Ae=te[re];if(!Ae||Ae.role!=="user")break;if(kv(Ae))return Ae}return null}function gm(q){var te;return String(((te=q==null?void 0:q.metadata)==null?void 0:te.message_source)||"user").trim().toLowerCase()}function ph(q){const te=gm(q);return te==="guidance"?"引导":te==="goal"?"目标":te==="goal_review"?"审核":te==="compression"||te==="compression_handoff"?"压缩":te==="notify"||te==="sub_agent"||te==="background_command"?"通知":d.value}function Ak(q){const te=gm(q);return te==="guidance"?"navigation":te==="goal"?"flag":te==="goal_review"?"circleAlert":te==="compression"||te==="compression_handoff"?"layers":te==="notify"||te==="sub_agent"||te==="background_command"?"bell":"user"}function c_(q){return!q||q.role!=="user"||l.value!=="brief"?!1:Oh(q)==="compact"}function u_(q){switch(gm(q)){case"goal_review":return"目标审核完成";case"sub_agent":return"后台子智能体完成";case"background_command":return"后台指令完成";case"compression":case"compression_handoff":return"对话压缩完成";case"goal":return"目标进行中";case"guidance":return"运行中引导";case"notify":return"系统通知";default:return"系统消息"}}Xe(()=>et().map(q=>{var te;return(q==null?void 0:q.id)??((te=q==null?void 0:q.content)==null?void 0:te.slice(0,80))}),()=>{g.value=!0,T(),ft(()=>{requestAnimationFrame(()=>{k(),V(),N()})})},{immediate:!0}),Cn(()=>{Ni(),pl(),typeof ResizeObserver<"u"&&He.value&&(Ln=new ResizeObserver(pl),Ln.observe(He.value)),typeof ResizeObserver<"u"&&(y=new ResizeObserver(()=>{requestAnimationFrame(k)}),ft(()=>V())),fl()&&console.warn("[SCROLL_BOUNCE_TRACE]","mounted",{hasScrollRef:!!He.value}),ce=window.setInterval(()=>{se.value=Date.now()},1e3),Nn()}),Xe(He,()=>{Ni(),pl(),Ln&&(Ln.disconnect(),Ln=null),typeof ResizeObserver<"u"&&He.value&&(Ln=new ResizeObserver(pl),Ln.observe(He.value))}),xn(()=>{kr(),Qs(),Hf(),ir(),Ln&&(Ln.disconnect(),Ln=null),y&&(y.disconnect(),y=null),p.clear(),b.forEach(q=>window.clearTimeout(q)),b.clear(),ce!==null&&(clearInterval(ce),ce=null),Ar()});const ml=q=>q&&(q.type==="thinking"||q.type==="tool"),ro=q=>!q||q.type!=="text"?!1:!(typeof q.content=="string"?q.content:"").trim(),vl=(q=[],te=0)=>{const Z=[];let re=[];const Ae=()=>{re.length>=1&&Z.push({kind:"stack",actions:re.slice(),key:`stack-${te}-${Z.length}`}),re=[]};return q.forEach((ue,Ge)=>{ro(ue)||(ml(ue)?re.push(ue):(Ae(),Z.push({kind:"single",action:ue,actionIndex:Ge,key:ue.id||`single-${te}-${Ge}`})))}),Ae(),Z};function Pc(q){const te=typeof(q==null?void 0:q.generatingLabel)=="string"&&q.generatingLabel.trim()?q.generatingLabel.trim():Z6;return Array.from(te)}const Tr=pe(null),gh=pe(null),qo=pe(-1),Oc=new Map,yl=q=>{var te;return!q||q.role!=="user"?!1:String(((te=q==null?void 0:q.metadata)==null?void 0:te.message_source)||"user").trim().toLowerCase()==="user"};function Ek(q){const te=q==null?void 0:q.content;let Z="";return typeof te=="string"?Z=te:Array.isArray(te)?Z=te.filter(Ae=>Ae&&Ae.type==="text"&&typeof Ae.text=="string").map(Ae=>Ae.text).join(`
`):te!=null&&(Z=String(te)),Z.split(`
`).map(Ae=>Ae.trim()).filter(Ae=>Ae&&!Ae.startsWith("[系统通知|"))[0]||"(空输入)"}function h_(q){const te=Array.isArray(q==null?void 0:q.actions)?q.actions:[];for(let re=te.length-1;re>=0;re-=1){const Ae=te[re];if((Ae==null?void 0:Ae.type)==="text"&&typeof(Ae==null?void 0:Ae.content)=="string"&&Ae.content.trim())return Ae.content.trim()}const Z=q==null?void 0:q.content;return typeof Z=="string"?Z.trim():""}const Dc=ye(()=>{const q=et(),te=[];for(let Z=0;Z<q.length;Z+=1)yl(q[Z])&&te.push(Z);return te.map((Z,re)=>{const Ae=re+1<te.length?te[re+1]:q.length;let ue="";for(let Ge=Ae-1;Ge>Z;Ge-=1){const pt=q[Ge];if(!pt||pt.role!=="assistant")continue;const Bt=h_(pt);if(Bt){ue=Bt;break}}return{msgIndex:Z,userText:Ek(q[Z]),aiText:ue||"(暂无回复)"}})}),Mk=[34,25,17,12];function mh(q){const te=qo.value;if(te<0)return qf;const Z=Math.abs(q-te),re=Mk[Z]??qf;if(re===qf)return re;const Ae=xk.value;return Math.max(qf,Math.round(re*Ae))}const vh=pe(-1);function Nc(q){var Bt;const te=Dc.value;if(!te.length){vh.value=-1;return}const Z=gh.value;if(!Z)return;const re=typeof q=="number"?q:Number(Z.scrollOffset)||0,Ae=Number(Z.viewportSize)||((Bt=Tr.value)==null?void 0:Bt.clientHeight)||0,ue=re+Ae*.25,Ge=Z.findItemIndex(ue);let pt=-1;for(let Rt=0;Rt<te.length&&te[Rt].msgIndex<=Ge;Rt+=1)pt=Rt;vh.value=pt<0?0:pt}Xe(Dc,()=>{Nc()});const yh=pe(100),d_=pe(!0),mm=pe(XM/2),bh=ye(()=>yh.value<tU?"hidden":d_.value?"pinned":"center"),xk=ye(()=>{const q=yh.value;if(bh.value==="pinned"){const te=mm.value-qf/2;return Math.max(0,Math.min(1,(q-te-6)/sC))}return bh.value==="center"?Math.max(0,Math.min(1,(q-6)/sC)):1}),f_=ye(()=>{const q={"--qn-count":String(Dc.value.length)};if(bh.value==="center")return{...q,left:"0px",width:`${yh.value}px`};const te=mm.value-qf/2;return{...q,left:`${te}px`,width:`${sC}px`}});function p_(){const q=Tr.value,te=yt.value;if(!q||!te)return;const Z=q.getBoundingClientRect(),re=te.getBoundingClientRect(),Ae=He.value,ue=Ae?Math.max(0,Ae.offsetWidth-Ae.clientWidth):0;mm.value=(XM+ue/2)/2,yh.value=re.left-Z.left,d_.value=re.width>=eU-.5}let Bc=null;function Ik(q,te){te?Oc.set(q,te):Oc.delete(q)}function Rk(q){let te=-1,Z=1/0;Oc.forEach((re,Ae)=>{const ue=re.getBoundingClientRect(),Ge=Math.abs(q.clientY-(ue.top+ue.height/2));Ge<Z&&(Z=Ge,te=Ae)}),qo.value=te}function Lk(){qo.value=-1}function Nn(){typeof ResizeObserver>"u"||!Tr.value||(Bc=new ResizeObserver(()=>{p_()}),Bc.observe(Tr.value),yt.value&&Bc.observe(yt.value),p_())}function Ar(){Bc&&(Bc.disconnect(),Bc=null)}let Fc=null,_a=!1;function Hf(){Fc!==null&&(cancelAnimationFrame(Fc),Fc=null),_a=!1}function Pk(q){var pt;const te=He.value,Z=gh.value;if(!te||!Z||typeof Z.getItemOffset!="function"){(pt=Z==null?void 0:Z.scrollToIndex)==null||pt.call(Z,q,{align:"start",smooth:!0});return}Hf(),_a=!0;const re=te.scrollTop,Ae=performance.now(),ue=380,Ge=()=>{if(Fc=null,!_a)return;const Bt=Math.max(0,te.scrollHeight-te.clientHeight),Rt=Math.max(0,Math.min(Number(Z.getItemOffset(q))||0,Bt)),Ps=Math.min(1,(performance.now()-Ae)/ue),Us=1-Math.pow(1-Ps,3);wr("ChatArea.quickNavJump"),te.scrollTop=re+(Rt-re)*Us,Ps<1?Fc=requestAnimationFrame(Ge):(wr("ChatArea.quickNavJump"),te.scrollTop=Rt,_a=!1)};Fc=requestAnimationFrame(Ge)}function Ok(q){const te=He.value,Z=Date.now();$t(),Qs(),i("user-scroll-intent",{ts:Z,delta:-1,top:te&&te.scrollTop||0}),Pk(q.msgIndex)}const g_=pe(""),m_=pe(""),v_=pe({});return Xe(qo,q=>{if(q<0)return;const te=Dc.value[q];if(!te)return;g_.value=te.userText,m_.value=te.aiText;const Z=Tr.value,re=Oc.get(q);if(!Z||!re)return;const Ae=Z.getBoundingClientRect(),ue=re.getBoundingClientRect();let pt=ue.top-Ae.top+ue.height/2-YM/2;pt=Math.max(8,Math.min(pt,Ae.height-YM-8));const Bt=ue.right-Ae.left+14;v_.value={top:`${pt}px`,left:`${Bt}px`}}),e({rootEl:Uo,getThinkingRef:Ee,isUsingStickToBottom:()=>!0,getStickState:Mt,stopStickScroll:$t,scrollToBottom:Ue,conditionalStickToBottom:zt}),(q,te)=>(F(),$("div",{class:"chat-area-shell",ref_key:"shellRef",ref:Tr},[E("div",{class:ke(["messages-area messages-area--stick",{"messages-area--render-pending":a.value}]),ref_key:"scrollRef",ref:He},[E("div",{class:"messages-flow",ref_key:"contentRef",ref:yt},[hl.value?(F(),Wt(We(K$),{key:0,ref_key:"virtualizerRef",ref:gh,data:st.value||[],"scroll-ref":hl.value,"buffer-size":400,"keep-mounted":In.value},{default:Vt(({item:Z,index:re})=>{var Ae;return[(F(),$("div",{key:Hs(Z,re),class:ke(["message-block",{"message-block--compact-user":We(Oh)(Z)==="compact","message-block--sub-agent-notice":pm(Z),"message-block--before-sub-agent-notice":Ck(re),"message-block--multi-agent":G(Z),"message-block--first":re===0,"message-block--last":re===(st.value||[]).length-1}])},[Z.role==="user"?(F(),$("div",{key:0,class:ke(["user-message",{"user-message--multi-agent":G(Z),"user-message--compact":We(Oh)(Z)==="compact","user-message--brief":c_(Z)}])},[c_(Z)?(F(),$("div",BH,[E("span",FH,ae(u_(Z)),1)])):(F(),$(Ie,{key:1},[E("div",{class:ke(["message-header icon-label",{"message-header--multi-agent":G(Z),"message-header--hidden":G(Z)&&ie(Z,re)}])},[G(Z)?(F(),$("span",$H,ae(ee(Z)),1)):(F(),$(Ie,{key:1},[E("span",{class:"icon icon-sm",style:Ke(mt(Ak(Z))),"aria-hidden":"true"},null,4),E("span",null,ae(ph(Z)),1)],64))],2),E("div",{class:ke(["message-text user-bubble-text",{"is-collapsed":R(Z,re),"is-expandable":A(Z,re),"is-history-loading":n.historyLoading||g.value}])},[Z.content?(F(),$("div",{key:0,class:ke(["bubble-text",{"is-expanded":M(Z,re)}]),ref:ue=>S(Z,re,ue)},[G(Z)?(F(),Wt(xm,{key:0,content:ve(Z),"is-streaming":!1},null,8,["content"])):(F(),$("span",{key:1,innerHTML:be(Z.content)},null,8,HH))],2)):ge("",!0),Z.images&&Z.images.length||On(Z).length?(F(),$("div",UH,[(F(!0),$(Ie,null,tt(Z.images,(ue,Ge)=>(F(),$("div",{class:"image-thumbnail-wrapper",key:Dn(Z,ue,Ge),onClick:Ne(pt=>Go(Z,ue),["stop"])},[E("img",{src:ts(Z,ue,"image"),alt:Pn(ue),class:"image-thumbnail"},null,8,zH)],8,WH))),128)),On(Z).length?(F(),Wt(Z2,{key:0,files:On(Z)},null,8,["files"])):ge("",!0)])):ge("",!0),Z.videos&&Z.videos.length?(F(),$("div",jH,[(F(!0),$(Ie,null,tt(Z.videos,(ue,Ge)=>(F(),$("div",{class:"image-thumbnail-wrapper",key:Dn(Z,ue,Ge)},[E("img",{src:ts(Z,ue,"video"),alt:Pn(ue),class:"image-thumbnail"},null,8,VH)]))),128))])):ge("",!0),A(Z,re)?(F(),$("div",GH,[E("button",{class:ke(["user-bubble-action-btn user-bubble-expand-btn",{expanded:M(Z,re)}]),title:M(Z,re)?"收起":"展开","aria-label":M(Z,re)?"收起":"展开",onClick:Ne(ue=>P(Z,re),["stop"])},null,10,qH)])):ge("",!0)],2),G(Z)?ge("",!0):(F(),$("div",KH,[E("button",{class:ke(["user-bubble-action-btn copy",{copied:z(Z,re)}]),title:z(Z,re)?"已复制":"复制","aria-label":z(Z,re)?"已复制":"复制",onClick:ue=>Q(Z,re)},null,10,QH),E("button",{class:"user-bubble-action-btn branch",title:"分支","aria-label":"分支",onClick:ue=>W(Z)},null,8,XH),E("span",YH,ae(L(Z)),1)]))],64))],2)):Z.role==="assistant"?(F(),$("div",JH,[Tk(re)&&(Cr(Z.actions||[])||Z.awaitingFirstContent)?(F(),$("div",ZH,[E("span",null,ae(h.value),1),a_(re)?(F(),$("span",e6,ae(a_(re)),1)):ge("",!0)])):ge("",!0),Z.awaitingFirstContent?(F(),$("div",t6,[E("div",s6,[E("div",n6,[(F(!0),$(Ie,null,tt(Pc(Z),(ue,Ge)=>(F(),$("span",{key:Ge,class:"assistant-generating-letter",style:Ke({animationDelay:`${Ge*.08}s`})},ae(ue),5))),128))])])])):ge("",!0),c.value==="minimal"?(F(),$(Ie,{key:2},[Cr(Z.actions||[])?(F(),Wt(q4,{key:0,actions:Z.actions||[],"conversation-running":s.streamingMessage,"is-latest-message":re===xe.value,"icon-style":mt,"get-tool-icon":s.getToolIcon,"get-tool-status-text":s.getToolStatusText,"get-tool-description":s.getToolDescription,"format-search-topic":s.formatSearchTopic,"format-search-time":s.formatSearchTime,"format-search-domains":s.formatSearchDomains,"register-thinking-ref":ne,"handle-thinking-scroll":n.handleThinkingScroll,onGroupToggle:ba},null,8,["actions","conversation-running","is-latest-message","get-tool-icon","get-tool-status-text","get-tool-description","format-search-topic","format-search-time","format-search-domains","handle-thinking-scroll"])):ge("",!0)],64)):u.value?(F(!0),$(Ie,{key:3},tt(vl(Z.actions||[],re),ue=>{var Ge,pt,Bt,Rt,Ps,Us,Er,Mr,$c,Hc,Sa,oo,j,U,Y,Te,Me,Ve,$e,Ye,qe,Et,Lt,ys,xr;return F(),$(Ie,{key:ue.key},[ue.kind==="stack"?(F(),Wt(d5,{key:0,class:"stacked-blocks-wrapper",actions:ue.actions,"expanded-blocks":s.expandedBlocks,"conversation-running":s.streamingMessage,"is-latest-message":re===xe.value,"icon-style":mt,"toggle-block":s.toggleBlock,"register-thinking-ref":ne,"handle-thinking-scroll":s.handleThinkingScroll,"get-tool-animation-class":s.getToolAnimationClass,"get-tool-icon":s.getToolIcon,"get-tool-status-text":s.getToolStatusText,"get-tool-description":s.getToolDescription,"format-search-topic":s.formatSearchTopic,"format-search-time":s.formatSearchTime,"format-search-domains":s.formatSearchDomains,onMoreToggle:Rc},null,8,["actions","expanded-blocks","conversation-running","is-latest-message","toggle-block","handle-thinking-scroll","get-tool-animation-class","get-tool-icon","get-tool-status-text","get-tool-description","format-search-topic","format-search-time","format-search-domains"])):ei(ue.action)?(F(),$("div",{class:ke(["action-item",{"streaming-content":(Ge=ue.action)==null?void 0:Ge.streaming,"completed-tool":((pt=ue.action)==null?void 0:pt.type)==="tool"&&!((Bt=ue.action)!=null&&Bt.streaming),"immediate-show":((Rt=ue.action)==null?void 0:Rt.streaming)||((Ps=ue.action)==null?void 0:Ps.type)==="text"||((Us=ue.action)==null?void 0:Us.type)==="thinking","thinking-finished":((Er=ue.action)==null?void 0:Er.type)==="thinking"&&!((Mr=ue.action)!=null&&Mr.streaming),"no-entry-animation":!s.streamingMessage||re!==xe.value}]),key:(($c=ue.action)==null?void 0:$c.id)||`${re}-${ue.actionIndex}`},[((Hc=ue.action)==null?void 0:Hc.type)==="thinking"?(F(),$("div",{key:0,class:ke(["collapsible-block thinking-block",{expanded:(Sa=s.expandedBlocks)==null?void 0:Sa.has(ue.action.blockId||`${re}-thinking-${ue.actionIndex}`)}]),"data-block-id":ue.action.blockId||`${re}-thinking-${ue.actionIndex}`},[E("div",{class:"collapsible-header",onClick:ti=>s.toggleBlock(ue.action.blockId||`${re}-thinking-${ue.actionIndex}`)},[te[0]||(te[0]=E("div",{class:"arrow"},null,-1)),E("div",o6,[E("span",{class:ke(["thinking-icon",{"thinking-animation":ue.action.streaming}])},[E("span",{class:"icon icon-sm",style:Ke(mt("brain")),"aria-hidden":"true"},null,4)],2)]),E("span",a6,ae(ue.action.streaming?"正在思考...":"思考过程"),1)],8,r6),E("div",{class:"collapsible-content",ref_for:!0,ref:ti=>Je(ue.action.blockId||`${re}-thinking-${ue.actionIndex}`,ti)},[E("div",{class:"content-inner thinking-content",ref_for:!0,ref:ti=>ne(ue.action.blockId||`${re}-thinking-${ue.actionIndex}`,ti),onScroll:ti=>s.handleThinkingScroll(ue.action.blockId||`${re}-thinking-${ue.actionIndex}`,ti),style:{"max-height":"240px","overflow-y":"auto"}},ae(ue.action.content),41,l6)],512)],10,i6)):((oo=ue.action)==null?void 0:oo.type)==="text"?(F(),$("div",c6,[E("div",{class:ke(["text-content",{"streaming-text":ue.action.streaming}])},[Qe(xm,{content:ue.action.content||"","is-streaming":ue.action.streaming},null,8,["content","is-streaming"])],2)])):((j=ue.action)==null?void 0:j.type)==="system"&&Zn(ue.action)?(F(),$("div",u6,ae(Zn(ue.action)),1)):((U=ue.action)==null?void 0:U.type)==="append_payload"?(F(),$("div",{key:3,class:ke(["append-placeholder",{"append-error":((Y=ue.action.append)==null?void 0:Y.success)===!1}])},[E("div",h6,[((Te=ue.action.append)==null?void 0:Te.success)!==!1?(F(),$("div",d6,[E("span",{class:"icon icon-sm",style:Ke(mt("pencil")),"aria-hidden":"true"},null,4),E("span",null,"已写入 "+ae(((Me=ue.action.append)==null?void 0:Me.path)||"目标文件")+" 的追加内容(内容已保存至文件)",1)])):(F(),$("div",f6,[E("span",{class:"icon icon-sm",style:Ke(mt("x")),"aria-hidden":"true"},null,4),E("span",null,"向 "+ae(((Ve=ue.action.append)==null?void 0:Ve.path)||"目标文件")+" 写入失败,内容已截获供后续修复。",1)])),ue.action.append?(F(),$("div",p6,[ue.action.append.lines!==null&&ue.action.append.lines!==void 0?(F(),$("span",g6," · 行数 "+ae(ue.action.append.lines),1)):ge("",!0),ue.action.append.bytes!==null&&ue.action.append.bytes!==void 0?(F(),$("span",m6," · 字节 "+ae(ue.action.append.bytes),1)):ge("",!0)])):ge("",!0),($e=ue.action.append)!=null&&$e.forced?(F(),$("div",v6,[E("span",{class:"icon icon-sm",style:Ke(mt("triangleAlert")),"aria-hidden":"true"},null,4),te[1]||(te[1]=E("span",null,"未检测到结束标记,请根据提示继续补充。",-1))])):ge("",!0)])],2)):((Ye=ue.action)==null?void 0:Ye.type)==="append"?(F(),$("div",{key:4,class:ke(["append-placeholder",{"append-error":((qe=ue.action.append)==null?void 0:qe.success)===!1}])},[E("div",y6,[E("div",b6,[E("span",{class:"icon icon-sm",style:Ke(mt("pencil")),"aria-hidden":"true"},null,4),E("span",null,ae(((Et=ue.action.append)==null?void 0:Et.summary)||"文件追加完成"),1)]),ue.action.append?(F(),$("div",_6,[E("span",null,ae(ue.action.append.path||"目标文件"),1),ue.action.append.lines?(F(),$("span",S6,"· 行数 "+ae(ue.action.append.lines),1)):ge("",!0),ue.action.append.bytes?(F(),$("span",w6,"· 字节 "+ae(ue.action.append.bytes),1)):ge("",!0)])):ge("",!0),(Lt=ue.action.append)!=null&&Lt.forced?(F(),$("div",k6,[E("span",{class:"icon icon-sm",style:Ke(mt("triangleAlert")),"aria-hidden":"true"},null,4),te[2]||(te[2]=E("span",null,"未检测到结束标记,请按提示继续补充。",-1))])):ge("",!0)])],2)):((ys=ue.action)==null?void 0:ys.type)==="tool"?(F(),Wt(zM,{key:5,action:ue.action,expanded:(xr=s.expandedBlocks)==null?void 0:xr.has(ue.action.blockId||`${re}-tool-${ue.actionIndex}`),"icon-style":mt,"get-tool-animation-class":s.getToolAnimationClass,"get-tool-icon":s.getToolIcon,"get-tool-status-text":s.getToolStatusText,"get-tool-description":s.getToolDescription,"format-search-topic":s.formatSearchTopic,"format-search-time":s.formatSearchTime,"format-search-domains":s.formatSearchDomains,"streaming-message":s.streamingMessage,"register-collapse-content":Je,"collapse-key":ue.action.blockId||`${re}-tool-${ue.actionIndex}`,"block-id":ue.action.blockId||`${re}-tool-${ue.actionIndex}`,onToggle:ti=>s.toggleBlock(ue.action.blockId||`${re}-tool-${ue.actionIndex}`)},null,8,["action","expanded","get-tool-animation-class","get-tool-icon","get-tool-status-text","get-tool-description","format-search-topic","format-search-time","format-search-domains","streaming-message","collapse-key","block-id","onToggle"])):ge("",!0)],2)):ge("",!0)],64)}),128)):(F(!0),$(Ie,{key:4},tt(Z.actions||[],(ue,Ge)=>{var pt,Bt,Rt,Ps,Us,Er,Mr,$c,Hc,Sa;return F(),$(Ie,{key:ue.id||`${re}-${Ge}`},[ei(ue)?(F(),$("div",{key:0,class:ke(["action-item",{"streaming-content":ue.streaming,"completed-tool":ue.type==="tool"&&!ue.streaming,"immediate-show":ue.streaming||ue.type==="text"||ue.type==="thinking","thinking-finished":ue.type==="thinking"&&!ue.streaming,"no-entry-animation":!s.streamingMessage||re!==xe.value}])},[ue.type==="thinking"?(F(),$("div",{key:0,class:ke(["collapsible-block thinking-block",{expanded:(pt=s.expandedBlocks)==null?void 0:pt.has(ue.blockId||`${re}-thinking-${Ge}`)}]),"data-block-id":ue.blockId||`${re}-thinking-${Ge}`},[E("div",{class:"collapsible-header",onClick:oo=>s.toggleBlock(ue.blockId||`${re}-thinking-${Ge}`)},[te[3]||(te[3]=E("div",{class:"arrow"},null,-1)),E("div",A6,[E("span",{class:ke(["thinking-icon",{"thinking-animation":ue.streaming}])},[E("span",{class:"icon icon-sm",style:Ke(mt("brain")),"aria-hidden":"true"},null,4)],2)]),E("span",E6,ae(ue.streaming?"正在思考...":"思考过程"),1)],8,T6),E("div",{class:"collapsible-content",ref_for:!0,ref:oo=>Je(ue.blockId||`${re}-thinking-${Ge}`,oo)},[E("div",{class:"content-inner thinking-content",ref_for:!0,ref:oo=>ne(ue.blockId||`${re}-thinking-${Ge}`,oo),onScroll:oo=>s.handleThinkingScroll(ue.blockId||`${re}-thinking-${Ge}`,oo),style:{"max-height":"240px","overflow-y":"auto"}},ae(ue.content),41,M6)],512)],10,C6)):ue.type==="text"?(F(),$("div",x6,[E("div",{class:ke(["text-content",{"streaming-text":ue.streaming}])},[Qe(xm,{content:ue.content||"","is-streaming":ue.streaming},null,8,["content","is-streaming"])],2)])):ue.type==="system"&&Zn(ue)?(F(),$("div",I6,ae(Zn(ue)),1)):ue.type==="append_payload"?(F(),$("div",{key:3,class:ke(["append-placeholder",{"append-error":((Bt=ue.append)==null?void 0:Bt.success)===!1}])},[E("div",R6,[((Rt=ue.append)==null?void 0:Rt.success)!==!1?(F(),$("div",L6,[E("span",{class:"icon icon-sm",style:Ke(mt("pencil")),"aria-hidden":"true"},null,4),E("span",null,"已写入 "+ae(((Ps=ue.append)==null?void 0:Ps.path)||"目标文件")+" 的追加内容(内容已保存至文件)",1)])):(F(),$("div",P6,[E("span",{class:"icon icon-sm",style:Ke(mt("x")),"aria-hidden":"true"},null,4),E("span",null,"向 "+ae(((Us=ue.append)==null?void 0:Us.path)||"目标文件")+" 写入失败,内容已截获供后续修复。",1)])),ue.append?(F(),$("div",O6,[ue.append.lines!==null&&ue.append.lines!==void 0?(F(),$("span",D6," · 行数 "+ae(ue.append.lines),1)):ge("",!0),ue.append.bytes!==null&&ue.append.bytes!==void 0?(F(),$("span",N6," · 字节 "+ae(ue.append.bytes),1)):ge("",!0)])):ge("",!0),(Er=ue.append)!=null&&Er.forced?(F(),$("div",B6,[E("span",{class:"icon icon-sm",style:Ke(mt("triangleAlert")),"aria-hidden":"true"},null,4),te[4]||(te[4]=E("span",null,"未检测到结束标记,请根据提示继续补充。",-1))])):ge("",!0)])],2)):ue.type==="append"?(F(),$("div",{key:4,class:ke(["append-placeholder",{"append-error":((Mr=ue.append)==null?void 0:Mr.success)===!1}])},[E("div",F6,[E("div",$6,[E("span",{class:"icon icon-sm",style:Ke(mt("pencil")),"aria-hidden":"true"},null,4),E("span",null,ae((($c=ue.append)==null?void 0:$c.summary)||"文件追加完成"),1)]),ue.append?(F(),$("div",H6,[E("span",null,ae(ue.append.path||"目标文件"),1),ue.append.lines?(F(),$("span",U6,"· 行数 "+ae(ue.append.lines),1)):ge("",!0),ue.append.bytes?(F(),$("span",W6,"· 字节 "+ae(ue.append.bytes),1)):ge("",!0)])):ge("",!0),(Hc=ue.append)!=null&&Hc.forced?(F(),$("div",z6,[E("span",{class:"icon icon-sm",style:Ke(mt("triangleAlert")),"aria-hidden":"true"},null,4),te[5]||(te[5]=E("span",null,"未检测到结束标记,请按提示继续补充。",-1))])):ge("",!0)])],2)):ue.type==="tool"?(F(),Wt(zM,{key:5,action:ue,expanded:(Sa=s.expandedBlocks)==null?void 0:Sa.has(ue.blockId||`${re}-tool-${Ge}`),"icon-style":mt,"get-tool-animation-class":s.getToolAnimationClass,"get-tool-icon":s.getToolIcon,"get-tool-status-text":s.getToolStatusText,"get-tool-description":s.getToolDescription,"format-search-topic":s.formatSearchTopic,"format-search-time":s.formatSearchTime,"format-search-domains":s.formatSearchDomains,"streaming-message":s.streamingMessage,"register-collapse-content":Je,"collapse-key":ue.blockId||`${re}-tool-${Ge}`,"block-id":ue.blockId||`${re}-tool-${Ge}`,onToggle:oo=>s.toggleBlock(ue.blockId||`${re}-tool-${Ge}`)},null,8,["action","expanded","get-tool-animation-class","get-tool-icon","get-tool-status-text","get-tool-description","format-search-topic","format-search-time","format-search-domains","streaming-message","collapse-key","block-id","onToggle"])):ge("",!0)],2)):ge("",!0)],64)}),128)),De.value.has(re)?(F(),Wt(kH,{key:5,summary:De.value.get(re),"icon-style":mt},null,8,["summary"])):ge("",!0)])):(F(),$("div",j6,[E("div",{class:ke(["collapsible-block system-block",{expanded:(Ae=s.expandedBlocks)==null?void 0:Ae.has(`system-${re}`)}]),"data-block-id":`system-${re}`},[E("div",{class:"collapsible-header",onClick:ue=>s.toggleBlock(`system-${re}`)},[te[6]||(te[6]=E("div",{class:"arrow"},null,-1)),E("div",q6,[E("span",{class:"tool-icon icon icon-md",style:Ke(mt("info")),"aria-hidden":"true"},null,4)]),E("span",K6,"系统消息 (role: "+ae(Z.role)+")",1)],8,G6),E("div",{class:"collapsible-content",ref:ue=>Je(`system-${re}`,ue)},[E("div",Q6,ae(Z.content),1)],512)],10,V6)]))],2))]}),_:1},8,["data","scroll-ref","keep-mounted"])):ge("",!0)],512),te[7]||(te[7]=E("div",{class:"messages-bottom-spacer","aria-hidden":"true"},null,-1))],2),Dc.value.length>0&&bh.value!=="hidden"?(F(),$("nav",{key:0,class:ke(["chat-quick-nav",{"chat-quick-nav--center":bh.value==="center"}]),style:Ke(f_.value),"aria-label":"用户输入快捷跳转",onMousemove:Rk,onMouseleave:Lk},[(F(!0),$(Ie,null,tt(Dc.value,(Z,re)=>(F(),$("div",{key:Z.msgIndex,class:ke(["qn-line",{"is-hot":qo.value===re,"is-current":vh.value===re}]),style:Ke({width:mh(re)+"px"}),ref_for:!0,ref:Ae=>Ik(re,Ae),onClick:Ae=>Ok(Z)},null,14,X6))),128))],38)):ge("",!0),E("div",{class:ke(["quick-nav-preview",{"is-visible":qo.value>=0}]),style:Ke(v_.value)},[E("div",Y6,ae(g_.value),1),E("div",J6,[Qe(xm,{content:m_.value,"is-streaming":!1},null,8,["content"])])],6)],512))}}),nU=["aria-label"],iU={class:"ws-switcher__header"},rU={class:"ws-switcher__title"},oU={class:"ws-switcher__count"},aU=["data-ws-id","aria-selected","onClick"],lU={key:0,class:"ws-confirm"},cU={class:"ws-confirm-text"},uU={class:"ws-confirm-actions"},hU=["disabled"],dU=["disabled","onClick"],fU={class:"ws-row-text"},pU=["disabled","onKeydown"],gU={key:1,class:"ws-row-name"},mU={key:2,class:"ws-row-path"},vU={class:"ws-row-meta"},yU={key:0,class:"ws-tag"},bU=["aria-expanded","onClick"],_U={key:0,class:"ws-empty"},SU=["disabled"],wU=["placeholder","disabled"],kU=["disabled"],CU={key:1,class:"ws-create-error"},TU={class:"ws-create-actions"},AU=["disabled"],EU=["disabled"],MU=["disabled"],xU=["disabled"],IU=["disabled"],RU=["disabled"],JM=300,LU=at({name:"WorkspaceSwitcher",__name:"WorkspaceSwitcher",props:{open:{type:Boolean},anchorRect:{default:null},workspaces:{default:()=>[]},currentWorkspaceId:{default:""},defaultWorkspaceId:{default:""},workspaceKind:{default:"workspace"},busy:{type:Boolean,default:!1},createSubmitting:{type:Boolean,default:!1},errorMessage:{default:""}},emits:["close","switch","create","rename","delete","set-default","reveal"],setup(s,{emit:e}){const t=s,n=e,i=ye(()=>t.workspaceKind==="project"),r=ye(()=>i.value?"项目":"工作区"),o=pe(null),a=pe(null),c=pe(null),l=pe(null),u=pe(null),h=pe(null),d=pe(null),p=pe(null),m=pe(""),v=pe(!1),g=pe(""),y=pe(""),b=pe(!1),_=pe({}),w=()=>{var oe;const H=t.anchorRect;if(!H||typeof window>"u")return;const G=window.innerWidth,ee=window.innerHeight,ie=((oe=o.value)==null?void 0:oe.offsetHeight)||360;let ve=H.right+8,le=H.top-6;ve+JM>G-8&&(ve=Math.max(8,Math.min(H.left,G-JM-8)),le=H.bottom+6),le+ie>ee-8&&(le=Math.max(8,ee-ie-8)),_.value={left:`${Math.round(ve)}px`,top:`${Math.round(le)}px`}},S=pe({}),C=()=>{h.value=null},T=async H=>{var J;if(t.busy)return;if(h.value===H.workspace_id){C();return}d.value=null,p.value=null,h.value=H.workspace_id,await ft();const G=H.workspace_id,ee=(J=a.value)==null?void 0:J.querySelector(`.ws-row[data-ws-id="${CSS.escape(G)}"]`),ie=ee==null?void 0:ee.querySelector(".ws-more");if(!ie){C();return}const ve=ie.getBoundingClientRect(),le=document.querySelector(".ws-menu-floating"),oe=(le==null?void 0:le.offsetWidth)||150,I=(le==null?void 0:le.offsetHeight)||150;let K=ve.right-oe,X=ve.bottom+4;K=Math.max(8,Math.min(K,window.innerWidth-oe-8)),X+I>window.innerHeight-8&&(X=ve.top-I-4),S.value={left:`${Math.round(K)}px`,top:`${Math.round(X)}px`}},k=H=>{const G=h.value,ee=t.workspaces.find(ie=>ie.workspace_id===G);C(),ee&&(H==="set-default"?n("set-default",ee.workspace_id):H==="rename"?(d.value=ee.workspace_id,m.value=ee.label,ft(()=>{var ve;const ie=(ve=u.value)==null?void 0:ve[0];ie==null||ie.focus(),ie==null||ie.select()})):H==="reveal"?n("reveal",ee.workspace_id):H==="delete"&&(p.value=ee.workspace_id))},A=H=>{if(!t.busy&&!(d.value||p.value)){if(h.value){C();return}H.workspace_id!==t.currentWorkspaceId&&n("switch",H.workspace_id)}},M=H=>{const G=m.value.trim();G&&G!==H.label&&n("rename",{workspace_id:H.workspace_id,label:G}),d.value=null},R=H=>{p.value=null,n("delete",H)};let P=!1;const L=(H,G)=>{if(P)return;P=!0;const ee=c.value;if(!ee){v.value=H,P=!1,G&&G();return}const ie=ee.offsetHeight;ee.style.height=`${ie}px`,b.value=!0,window.setTimeout(()=>{v.value=H,ft(()=>{ee.style.height="auto";const ve=ee.offsetHeight;ee.style.height=`${ie}px`,ee.offsetHeight,ee.style.height=`${ve}px`,b.value=!1,window.setTimeout(()=>{ee.style.height="",P=!1,G&&G()},210)})},130)},z=()=>{v.value||t.busy||(C(),g.value="",y.value="",L(!0,()=>{var H;return(H=l.value)==null?void 0:H.focus()}))},Q=()=>{v.value&&L(!1)},W=()=>{n("create",{path:g.value.trim(),label:y.value.trim()})};Xe(()=>t.createSubmitting,(H,G)=>{G&&!H&&v.value&&!t.errorMessage&&Q()});const V=H=>{var ee;const G=H.target;if(G&&!((ee=G.closest)!=null&&ee.call(G,".ws-menu-floating"))&&o.value&&!o.value.contains(G)){const ie=t.anchorRect;if(ie){const ve=H.clientX,le=H.clientY;if(ve>=ie.left&&ve<=ie.right&&le>=ie.top&&le<=ie.bottom)return}n("close")}},N=H=>{if(H.key==="Escape"){if(h.value){C();return}if(d.value||p.value){d.value=null,p.value=null;return}if(v.value){Q();return}n("close")}},O=()=>{C(),w()};return Xe(()=>t.open,async H=>{H?(h.value=null,d.value=null,p.value=null,await ft(),w(),document.addEventListener("click",V,!0),document.addEventListener("keydown",N),window.addEventListener("resize",O)):(v.value&&(v.value=!1),document.removeEventListener("click",V,!0),document.removeEventListener("keydown",N),window.removeEventListener("resize",O))}),xn(()=>{document.removeEventListener("click",V,!0),document.removeEventListener("keydown",N),window.removeEventListener("resize",O)}),(H,G)=>(F(),Wt(Sp,{to:"body"},[Qe(us,{name:"ws-switcher"},{default:Vt(()=>[s.open?(F(),$("div",{key:0,ref_key:"popoverEl",ref:o,class:ke(["ws-switcher",{"ws-switcher--project":i.value}]),style:Ke(_.value),role:"dialog","aria-label":r.value,onClick:G[6]||(G[6]=Ne(()=>{},["stop"]))},[E("div",iU,[E("span",rU,ae(r.value),1),E("span",oU,ae(s.workspaces.length)+" 个",1)]),E("div",{class:"ws-switcher__list",ref_key:"listEl",ref:a,onScroll:C},[(F(!0),$(Ie,null,tt(s.workspaces,ee=>(F(),$("div",{key:ee.workspace_id,class:ke(["ws-row",{current:ee.workspace_id===s.currentWorkspaceId,"menu-open":h.value===ee.workspace_id}]),"data-ws-id":ee.workspace_id,role:"option","aria-selected":ee.workspace_id===s.currentWorkspaceId,onClick:ie=>A(ee)},[p.value===ee.workspace_id?(F(),$("div",lU,[E("div",cU," 删除「"+ae(ee.label)+"」?"+ae(i.value?"项目文件夹和对话记录将一并删除。":"不会删除磁盘上的文件夹。"),1),E("div",uU,[E("button",{type:"button",class:"ws-btn ghost",disabled:s.busy,onClick:G[0]||(G[0]=Ne(ie=>p.value=null,["stop"]))}," 取消 ",8,hU),E("button",{type:"button",class:"ws-btn danger",disabled:s.busy,onClick:Ne(ie=>R(ee),["stop"])}," 删除 ",8,dU)])])):(F(),$(Ie,{key:1},[G[13]||(G[13]=E("span",{class:"ws-row-icon","aria-hidden":"true"},[E("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"1.8","stroke-linecap":"round","stroke-linejoin":"round"},[E("path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"})])],-1)),E("span",fU,[d.value===ee.workspace_id?_v((F(),$("input",{key:0,ref_for:!0,ref_key:"renameInputEl",ref:u,"onUpdate:modelValue":G[1]||(G[1]=ie=>m.value=ie),class:"ws-rename-input",disabled:s.busy,onClick:G[2]||(G[2]=Ne(()=>{},["stop"])),onKeydown:[Sv(Ne(ie=>M(ee),["prevent"]),["enter"]),G[3]||(G[3]=Sv(Ne(ie=>d.value=null,["prevent"]),["esc"]))]},null,40,pU)),[[sS,m.value]]):(F(),$("span",gU,ae(ee.label),1)),i.value?ge("",!0):(F(),$("span",mU,ae(ee.path||"(未配置路径)"),1))]),E("span",vU,[ee.workspace_id===s.defaultWorkspaceId?(F(),$("span",yU,"默认")):ge("",!0),E("button",{type:"button",class:"ws-more","aria-expanded":h.value===ee.workspace_id,"aria-label":"更多操作",onClick:Ne(ie=>T(ee),["stop"])},[...G[12]||(G[12]=[E("svg",{viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true"},[E("circle",{cx:"5",cy:"12",r:"1.6"}),E("circle",{cx:"12",cy:"12",r:"1.6"}),E("circle",{cx:"19",cy:"12",r:"1.6"})],-1)])],8,bU)])],64))],10,aU))),128)),s.workspaces.length?ge("",!0):(F(),$("div",_U,ae(i.value?"暂无项目":"暂无工作区"),1))],544),E("div",{class:"ws-bottom",ref_key:"bottomEl",ref:c},[v.value?(F(),$("form",{key:1,class:ke(["ws-create-form",{fading:b.value}]),onSubmit:Ne(W,["prevent"])},[_v(E("input",{ref_key:"createNameEl",ref:l,"onUpdate:modelValue":G[4]||(G[4]=ee=>y.value=ee),type:"text",placeholder:i.value?"项目名称":"工作区名称(可选)",autocomplete:"off",disabled:s.createSubmitting},null,8,wU),[[sS,y.value]]),i.value?ge("",!0):_v((F(),$("input",{key:0,"onUpdate:modelValue":G[5]||(G[5]=ee=>g.value=ee),type:"text",placeholder:"路径:绝对路径或相对仓库路径",autocomplete:"off",disabled:s.createSubmitting},null,8,kU)),[[sS,g.value]]),s.errorMessage?(F(),$("div",CU,ae(s.errorMessage),1)):ge("",!0),E("div",TU,[E("button",{type:"button",class:"ws-btn ghost",disabled:s.createSubmitting,onClick:Ne(Q,["stop"])}," 取消 ",8,AU),E("button",{type:"submit",class:"ws-btn primary",disabled:s.createSubmitting},ae(s.createSubmitting?"创建中...":"创建"),9,EU)])],34)):(F(),$("div",{key:0,class:ke(["ws-footer",{fading:b.value}])},[E("button",{type:"button",class:"ws-create-btn",disabled:s.busy,onClick:Ne(z,["stop"])},[G[14]||(G[14]=E("span",{class:"ws-create-icon","aria-hidden":"true"},[E("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"1.8","stroke-linecap":"round","stroke-linejoin":"round"},[E("path",{d:"M5 12h14"}),E("path",{d:"M12 5v14"})])],-1)),E("span",null,"新建"+ae(r.value),1)],8,SU)],2))],512)],14,nU)):ge("",!0)]),_:1}),Qe(us,{name:"ws-menu"},{default:Vt(()=>[h.value?(F(),$("div",{key:0,class:"ws-menu-floating",style:Ke(S.value),role:"menu",onClick:G[11]||(G[11]=Ne(()=>{},["stop"]))},[E("button",{type:"button",disabled:h.value===s.defaultWorkspaceId||s.busy,onClick:G[7]||(G[7]=ee=>k("set-default"))}," 设为默认 ",8,MU),E("button",{type:"button",disabled:s.busy,onClick:G[8]||(G[8]=ee=>k("rename"))},"重命名",8,xU),E("button",{type:"button",disabled:i.value||s.busy,onClick:G[9]||(G[9]=ee=>k("reveal"))}," 在文件夹中打开 ",8,IU),G[15]||(G[15]=E("div",{class:"ws-menu-sep"},null,-1)),E("button",{type:"button",class:"danger",disabled:s.busy,onClick:G[10]||(G[10]=ee=>k("delete"))},"删除",8,RU)],4)):ge("",!0)]),_:1})]))}}),PU=Qt(LU,[["__scopeId","data-v-4dbd1c49"]]),OU={class:"conversation-sidebar-inner"},DU={class:"conversation-primary-actions"},NU=["title"],BU=["title"],FU={class:"sidebar-nav-label"},$U={class:"conversation-search"},HU={class:"search-input-wrap"},UU={class:"sidebar-nav-icon search-inline-icon","aria-hidden":"true"},WU=["value"],zU={key:0,class:"conversation-type-switch"},jU={key:0,class:"running-task-section"},VU=["onClick"],GU={class:"running-task-workspace"},qU={class:"running-task-main"},KU={class:"running-task-title"},QU={key:0,class:"conversation-running-loader running-task-state","aria-label":"运行中"},XU={key:1,class:"conversation-complete-check running-task-state","aria-label":"已完成"},YU=["onMouseenter"],JU=["onClick"],ZU={class:"workspace-group-label"},e8={key:0,class:"workspace-current-dot","aria-label":"当前工作区"},t8={key:1,class:"workspace-running-loader","aria-label":"运行中"},s8=["onClick"],n8=["aria-expanded","onClick"],i8=["onClick"],r8=["onClick"],o8=["onClick"],a8={class:"workspace-group-children-inner"},l8={key:0,class:"workspace-no-conversations"},c8=["onClick"],u8={class:"conversation-title"},h8={key:0,class:"conversation-running-loader","aria-label":"运行中",title:"运行中"},d8={key:1,class:"conversation-complete-check","aria-label":"已完成",title:"已完成"},f8=["data-action-trigger","aria-expanded","onClick"],p8=["onClick"],g8=["onClick"],m8={key:0,class:"load-more workspace-load-more"},v8=["disabled","onClick"],y8={key:2,class:"workspace-groups search-result-groups"},b8={key:0,class:"no-conversations"},_8={class:"workspace-group-header search-result-group-header"},S8={class:"workspace-group-toggle search-result-group-toggle"},w8={class:"workspace-group-label"},k8={class:"workspace-group-children expanded"},C8={class:"workspace-group-children-inner"},T8={class:"workspace-conversations-list"},A8=["onClick"],E8={class:"conversation-title"},M8={key:0,class:"conversation-running-loader","aria-label":"运行中",title:"运行中"},x8={key:1,class:"conversation-complete-check","aria-label":"已完成",title:"已完成"},I8=["data-action-trigger","aria-expanded","onClick"],R8=["onClick"],L8=["onClick"],P8={key:0,class:"loading-conversations"},O8={key:1,class:"no-conversations"},D8=["onClick"],N8={class:"conversation-title"},B8={key:0,class:"conversation-running-loader","aria-label":"运行中",title:"运行中"},F8={key:1,class:"conversation-complete-check","aria-label":"已完成",title:"已完成"},$8=["data-action-trigger","aria-expanded","onClick"],H8=["onClick"],U8=["onClick"],W8={key:4,class:"load-more"},z8=["disabled"],j8={key:5,class:"load-more search-more"},V8={key:0,class:"search-progress"},G8={class:"search-spinner","aria-hidden":"true"},q8={class:"search-spinner-orbit"},K8={key:2,class:"search-done"},Q8={class:"workspace-rename-card"},X8={class:"workspace-rename-title"},Y8=["onKeydown"],J8=at({name:"ConversationSidebar",__name:"ConversationSidebar",props:{formatTime:{},iconStyle:{},showCollapseButton:{type:Boolean,default:!0},collapseButtonVariant:{default:"toggle"},runningTasks:{default:()=>[]},currentWorkspaceId:{default:""},defaultWorkspaceId:{default:""},workspaces:{default:()=>[]},workspaceKind:{default:"workspace"},workspaceBusy:{type:Boolean,default:!1},workspaceCreateSubmitting:{type:Boolean,default:!1},workspaceError:{default:""},hostWorkspaceEnabled:{type:Boolean,default:!1},groupByWorkspace:{type:Boolean,default:!1},versioningHostMode:{type:Boolean,default:!1},currentTaskInProgress:{type:Boolean,default:!1},currentConversationId:{default:""}},emits:["toggle","create","search","search-submit","select","select-running-task","load-more","search-more","personal","delete","duplicate","switch-workspace","create-workspace","delete-workspace","set-default-workspace","select-workspace-conversation","create-workspace-conversation","reveal-workspace","rename-workspace","pin-workspace","conversation-type-change","open-workflows"],setup(s,{emit:e}){const t=s,n=e,i=Vs(),r=vr(),o=qs(),a=ye(()=>r.sidebarConversationType),c=ye(()=>a.value==="multi_agent"?"type-slide-left":"type-slide-right"),l=pe(null),u=fe=>{r.sidebarConversationType!==fe&&(l.value&&(l.value.scrollTop=0),r.setSidebarConversationType(fe),n("conversation-type-change",fe))},{sidebarCollapsed:h}=Ii(i),{searchQuery:d,searchResults:p,searchGroups:m,searchActive:v,searchInProgress:g,searchMoreAvailable:y,conversations:b,conversationInsertAnimations:_,conversationListAnimationMode:w,pendingDeletingConversationIds:S,conversationsLoading:C,hasMoreConversations:T,loadingMoreConversations:k,currentConversationId:A}=Ii(r),{visible:M}=Ii(o),R=fe=>t.iconStyle?t.iconStyle(fe):{},P=pe(null),L=pe(!1),z=pe(null),Q=()=>{if(L.value){L.value=!1;return}const fe=P.value;if(fe){const me=fe.getBoundingClientRect(),Ce=fe.closest(".conversation-sidebar"),dt=Ce?Ce.getBoundingClientRect().right:me.right;z.value={left:me.left,top:me.top,right:Math.min(me.right,dt),bottom:me.bottom}}L.value=!0},W=pe(null),V=pe({top:0,right:0}),N=pe(!1),O=pe(null),H=pe(null),G=pe(null),ee=pe(""),ie=pe(null);Xe(G,async fe=>{var me,Ce;fe&&(await ft(),(me=ie.value)==null||me.focus(),(Ce=ie.value)==null||Ce.select())});const ve=fe=>{if(typeof document>"u")return;const me=document.querySelector(`[data-action-trigger="${fe}"]`);if(!me)return;const Ce=me.getBoundingClientRect();V.value={top:Ce.bottom+6,right:(typeof window<"u"?window.innerWidth:0)-Ce.right}},le=fe=>{W.value===fe?W.value=null:(ve(fe),W.value=fe)};Xe(W,async fe=>{fe&&(await ft(),ve(fe))});const oe=fe=>W.value===fe&&!ut(fe)&&!Hs(fe),I=fe=>{const me=fe;me.style.top=`${me.offsetTop}px`},K=()=>{W.value=null},X=pe(new Set),J=pe([]),he=pe(!1),be=()=>{X.value=new Set(Array.isArray(o.form.sidebar_pinned_workspaces)?o.form.sidebar_pinned_workspaces:[])},Re=()=>{J.value=Array.isArray(o.form.sidebar_workspace_order)?[...o.form.sidebar_workspace_order]:[]},rt=()=>{if(!he.value)return;const fe=Array.from(X.value),me=o.form.sidebar_pinned_workspaces||[];JSON.stringify(fe)!==JSON.stringify(me)&&o.updateField({key:"sidebar_pinned_workspaces",value:fe})},st=()=>{if(!he.value)return;const fe=Array.from(J.value),me=o.form.sidebar_workspace_order||[];JSON.stringify(fe)!==JSON.stringify(me)&&o.updateField({key:"sidebar_workspace_order",value:fe})},et=()=>{if(!he.value)return;const fe=String(t.currentWorkspaceId||"");if(!fe||X.value.has(fe)||J.value[0]===fe)return;const me=J.value.filter(Ce=>Ce!==fe);me.unshift(fe),J.value=me,st()},De=fe=>{if(!he.value||!Array.isArray(fe))return;const me=fe.map(Kt=>String((Kt==null?void 0:Kt.workspace_id)||"")).filter(Boolean),Ce=new Set(J.value),dt=new Set(me.filter(Kt=>X.value.has(Kt))),qt=me.filter(Kt=>!Ce.has(Kt)&&!dt.has(Kt)),Ss=new Set(J.value.filter(Kt=>!me.includes(Kt)));(qt.length||Ss.size)&&(J.value=J.value.filter(Kt=>!Ss.has(Kt)).concat(qt),st())},xe=()=>{!o.loaded||he.value||(be(),Re(),he.value=!0,Array.isArray(t.workspaces)&&t.workspaces.length>0&&De(t.workspaces),et())};Xe(()=>o.loaded,fe=>{fe&&xe()},{immediate:!0}),Xe(()=>o.form.sidebar_pinned_workspaces,()=>{he.value&&be()},{deep:!0}),Xe(()=>o.form.sidebar_workspace_order,()=>{he.value&&(Re(),Array.isArray(t.workspaces)&&t.workspaces.length>0&&De(t.workspaces),et())},{deep:!0}),Xe(()=>t.workspaces,fe=>{Array.isArray(fe)&&fe.length>0&&De(fe)},{immediate:!0,deep:!0});const se=ye(()=>t.groupByWorkspace&&t.hostWorkspaceEnabled&&Array.isArray(t.workspaces)&&t.workspaces.length>0);Xe(()=>t.currentWorkspaceId,async()=>{se.value?(N.value=!0,et(),await ft(),N.value=!1):et()},{immediate:!0});const ce=ye(()=>(Array.isArray(t.workspaces)?[...t.workspaces]:[]).sort((me,Ce)=>{const dt=String((me==null?void 0:me.workspace_id)||""),qt=String((Ce==null?void 0:Ce.workspace_id)||""),Ss=X.value.has(dt)?1:0,Kt=X.value.has(qt)?1:0;if(Ss!==Kt)return Kt-Ss;const Es=J.value.indexOf(dt),ht=J.value.indexOf(qt);return Es!==-1&&ht!==-1?Es-ht:Es!==-1?-1:ht!==-1?1:String((me==null?void 0:me.label)||dt).localeCompare(String((Ce==null?void 0:Ce.label)||qt))})),de=ye(()=>v.value?p.value:b.value),we=ye(()=>(Array.isArray(m.value)?[...m.value]:[]).sort((me,Ce)=>{const dt=String((me==null?void 0:me.workspace_id)||""),qt=String((Ce==null?void 0:Ce.workspace_id)||""),Ss=X.value.has(dt)?1:0,Kt=X.value.has(qt)?1:0;if(Ss!==Kt)return Kt-Ss;const Es=J.value.indexOf(dt),ht=J.value.indexOf(qt);return Es!==-1&&ht!==-1?Es-ht:Es!==-1?-1:ht!==-1?1:String((me==null?void 0:me.label)||dt).localeCompare(String((Ce==null?void 0:Ce.label)||qt))})),Le=ye(()=>v.value?g.value:C.value),He=ye(()=>w.value==="delete"),yt=ye(()=>Array.isArray(t.runningTasks)?t.runningTasks.filter(fe=>fe&&fe.task_id&&fe.conversation_id&&fe.conversation_id!==A.value&&String(fe.workspace_id||"")!==String(t.currentWorkspaceId||"")):[]),At=new Set(["pending","running","cancel_requested"]),Nt=new Set(["succeeded","failed","canceled"]),It=fe=>At.has(String((fe==null?void 0:fe.status)||"")),Jt=fe=>Nt.has(String((fe==null?void 0:fe.status)||"")),$t=ye(()=>new Set((Array.isArray(t.runningTasks)?t.runningTasks:[]).filter(fe=>It(fe)).map(fe=>String((fe==null?void 0:fe.conversation_id)||"")).filter(Boolean))),As=ye(()=>new Set((Array.isArray(t.runningTasks)?t.runningTasks:[]).filter(fe=>Jt(fe)).map(fe=>String((fe==null?void 0:fe.conversation_id)||"")).filter(Boolean))),ut=fe=>!!($t.value.has(String(fe||""))||t.currentTaskInProgress&&String(fe||"")===String(t.currentConversationId||"")),Hs=fe=>As.value.has(String(fe||"")),hl=fe=>(Array.isArray(t.runningTasks)?t.runningTasks:[]).some(me=>It(me)&&String((me==null?void 0:me.workspace_id)||"")===fe),In=fe=>r.workspaceGroups.find(me=>me.workspaceId===fe),Uo=fe=>{const me=In(fe);if(!me)return[];const Ce=me.visibleLimit+me.bufferLimit;return me.conversations.slice(0,Ce)},nr=fe=>{const me=In(fe);return me?me.hasMore||me.conversations.length>me.visibleLimit:!1},Qs=fe=>{const me=In(fe);return me?me.expanded:!0},Yn=fe=>{const me=In(fe);if(!me){r.ensureWorkspaceGroup(fe),r.loadWorkspaceConversations(fe);return}r.setWorkspaceGroupExpanded(fe,!me.expanded),!me.expanded&&me.conversations.length===0&&!me.loading&&r.loadWorkspaceConversations(fe)},Rn=fe=>{const me=In(fe);me?me.conversations.length===0&&!me.loading&&!me.loadingMore&&r.loadWorkspaceConversations(fe):(r.ensureWorkspaceGroup(fe),r.loadWorkspaceConversations(fe))};Xe([se,ce],([fe,me])=>{fe&&me.length>0&&me.forEach(Ce=>Rn(String((Ce==null?void 0:Ce.workspace_id)||"")))},{immediate:!0});const ir=(fe,me)=>{H.value=null,n("select-workspace-conversation",{conversationId:fe,workspaceId:me})},Wo=fe=>{H.value=null,n("create-workspace-conversation",fe)},Ln=fe=>{H.value=H.value===fe?null:fe},ma=()=>{H.value=null},zo=fe=>{H.value=null;const me=[...J.value],Ce=me.indexOf(fe);if(X.value.has(fe)){X.value.delete(fe),Ce!==-1&&me.splice(Ce,1);const dt=String(t.currentWorkspaceId||""),qt=me.indexOf(dt),Ss=qt!==-1?qt+1:0;me.splice(Ss,0,fe)}else X.value.add(fe),Ce!==-1&&me.splice(Ce,1);J.value=me,rt(),st(),n("pin-workspace",fe)},io=fe=>{H.value=null,n("reveal-workspace",fe)},dl=fe=>{H.value=null,G.value=String((fe==null?void 0:fe.workspace_id)||""),ee.value=String((fe==null?void 0:fe.label)||(fe==null?void 0:fe.workspace_id)||"")},Jn=()=>{const fe=G.value,me=ee.value.trim();fe&&me&&n("rename-workspace",{workspaceId:fe,label:me}),G.value=null,ee.value=""},jo=()=>{G.value=null,ee.value=""},va=fe=>{r.loadMoreWorkspaceConversations(fe)};return Cn(()=>{document.addEventListener("click",K),document.addEventListener("click",ma),se.value&&ce.value.forEach(fe=>Rn(String((fe==null?void 0:fe.workspace_id)||"")))}),xn(()=>{document.removeEventListener("click",K),document.removeEventListener("click",ma)}),(fe,me)=>(F(),$("aside",{class:ke(["conversation-sidebar",{collapsed:We(h)}])},[E("div",OU,[E("div",DU,[E("button",{type:"button",class:"sidebar-nav-row conversation-menu-btn",title:We(h)?"展开对话记录":"收起对话记录",onClick:me[0]||(me[0]=Ce=>fe.$emit("toggle"))},[...me[22]||(me[22]=[mi('<span class="sidebar-nav-icon chat-icon" data-tutorial="conversation-menu" aria-hidden="true"><svg viewBox="0 0 28 28" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M5 6.5c0-1.38 1.12-2.5 2.5-2.5h13c1.38 0 2.5 1.12 2.5 2.5v8.5c0 1.38-1.12 2.5-2.5 2.5h-5.6l-3.4 3.2.6-3.2H7.5c-1.38 0-2.5-1.12-2.5-2.5V6.5z" stroke="currentColor" stroke-width="1.45" stroke-linejoin="round"></path><path d="M9 9.5h10" stroke="currentColor" stroke-width="1.45" stroke-linecap="round"></path><path d="M9 13h6" stroke="currentColor" stroke-width="1.45" stroke-linecap="round"></path></svg></span><span class="sidebar-nav-label">对话记录</span>',2)])],8,NU),E("button",{type:"button",class:"sidebar-nav-row",title:"新建对话",onClick:me[1]||(me[1]=Ce=>fe.$emit("create"))},[...me[23]||(me[23]=[mi('<span class="sidebar-nav-icon pencil-icon" data-tutorial="quick-new-conversation" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"></path><path d="m15 5 4 4"></path></svg></span><span class="sidebar-nav-label">新建对话</span>',2)])]),s.hostWorkspaceEnabled?(F(),$("button",{key:0,type:"button",class:ke(["sidebar-nav-row workspace-entry-btn",{active:L.value}]),title:s.workspaceKind==="project"?"项目":"工作区","data-tutorial":"workspace-toggle",ref_key:"workspaceEntryBtn",ref:P,onClick:Q},[me[24]||(me[24]=mi('<span class="sidebar-nav-icon layers-icon" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z"></path><path d="M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12"></path><path d="M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17"></path></svg></span>',1)),E("span",FU,ae(s.workspaceKind==="project"?"项目":"工作区"),1)],10,BU)):ge("",!0),E("button",{type:"button",class:"sidebar-nav-row",title:"工作流",onClick:me[2]||(me[2]=Ce=>fe.$emit("open-workflows"))},[...me[25]||(me[25]=[mi('<span class="sidebar-nav-icon workflow-icon" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="4.6" r="2.6"></circle><path d="M12 7.2 V10.1"></path><path d="M8.5 12.3 L12 10.1 L15.5 12.3 L12 14.5 Z" stroke-linejoin="miter"></path><path d="M8.5 12.3 H6.1 Q4.5 12.3 4.5 13.9 V16.3"></path><path d="M15.5 12.3 H17.9 Q19.5 12.3 19.5 13.9 V16.3"></path><rect x="2.4" y="16.3" width="4.2" height="4.2" rx="1.1"></rect><rect x="17.4" y="16.3" width="4.2" height="4.2" rx="1.1"></rect></svg></span><span class="sidebar-nav-label">工作流</span>',2)])])]),E("div",$U,[E("label",HU,[E("span",UU,[E("span",{class:"icon icon-sm",style:Ke(R("search"))},null,4)]),E("input",{class:"search-input",value:We(d),placeholder:"搜索对话",onInput:me[3]||(me[3]=Ce=>fe.$emit("search",Ce.target.value)),onKeydown:me[4]||(me[4]=Sv(Ne(Ce=>fe.$emit("search-submit",Ce.target.value),["prevent"]),["enter"]))},null,40,WU)])]),We(v)?ge("",!0):(F(),$("div",zU,[E("button",{type:"button",class:ke(["conversation-type-option",{active:a.value==="normal"}]),onClick:me[5]||(me[5]=Ce=>u("normal"))}," 普通对话 ",2),E("button",{type:"button",class:ke(["conversation-type-option",{active:a.value==="multi_agent"}]),onClick:me[6]||(me[6]=Ce=>u("multi_agent"))}," 多智能体 ",2)])),E("div",{ref_key:"conversationListEl",ref:l,class:"conversation-list"},[Qe(us,{name:c.value},{default:Vt(()=>[(F(),$("div",{key:a.value,class:"conversation-list-pane"},[yt.value.length&&!We(v)&&!se.value?(F(),$("div",jU,[me[26]||(me[26]=E("div",{class:"running-task-section-title"},"运行中的任务",-1)),(F(!0),$(Ie,null,tt(yt.value,Ce=>(F(),$("button",{key:Ce.task_id,type:"button",class:ke(["running-task-item",{active:Ce.conversation_id===We(A)}]),onClick:dt=>fe.$emit("select-running-task",Ce)},[E("span",GU,ae(Ce.workspace_label||Ce.workspace_id),1),E("span",qU,[E("span",KU,ae(Ce.conversation_title||Ce.message||"运行中的对话"),1),It(Ce)?(F(),$("span",QU)):(F(),$("span",XU))])],10,VU))),128))])):ge("",!0),se.value&&!We(v)?(F(),$("div",{key:1,class:ke(["workspace-groups",{"switch-instant":N.value}])},[(F(!0),$(Ie,null,tt(ce.value,Ce=>{var dt,qt,Ss,Kt,Es;return F(),$("div",{key:String(Ce.workspace_id||Ce.label),class:"workspace-group"},[E("div",{class:ke(["workspace-group-header",{active:String(Ce.workspace_id||"")===s.currentWorkspaceId}]),onMouseenter:ht=>O.value=String(Ce.workspace_id||""),onMouseleave:me[7]||(me[7]=ht=>O.value=null)},[E("button",{type:"button",class:"workspace-group-toggle",onClick:ht=>Yn(String(Ce.workspace_id||""))},[E("span",{class:"icon icon-sm workspace-folder-icon",style:Ke(R(Qs(String(Ce.workspace_id||""))?"folderOpen":"folderClosed")),"aria-hidden":"true"},null,4),E("span",ZU,ae(Ce.label||Ce.workspace_id),1),String(Ce.workspace_id||"")===s.currentWorkspaceId?(F(),$("span",e8)):ge("",!0),hl(String(Ce.workspace_id||""))&&!Qs(String(Ce.workspace_id||""))&&O.value!==String(Ce.workspace_id||"")&&H.value!==String(Ce.workspace_id||"")?(F(),$("span",t8)):ge("",!0)],8,JU),E("div",{class:ke(["workspace-group-actions",{visible:O.value===String(Ce.workspace_id||"")||H.value===String(Ce.workspace_id||"")}])},[E("button",{type:"button",class:"workspace-new-btn",title:"新建对话","aria-label":"新建对话",onClick:ht=>Wo(String(Ce.workspace_id||""))},[E("span",{class:"icon icon-sm",style:Ke(R("pencil")),"aria-hidden":"true"},null,4)],8,s8),E("button",{type:"button",class:"workspace-more-btn",title:"更多操作","aria-label":"更多操作","aria-expanded":H.value===String(Ce.workspace_id||""),onClick:Ne(ht=>Ln(String(Ce.workspace_id||"")),["stop"])},[...me[27]||(me[27]=[E("span",{"aria-hidden":"true"},null,-1)])],8,n8),E("div",{class:ke(["workspace-actions-menu",{open:H.value===String(Ce.workspace_id||"")}])},[E("button",{type:"button",onClick:ht=>zo(String(Ce.workspace_id||""))},[E("span",null,ae(X.value.has(String(Ce.workspace_id||""))?"取消置顶":"置顶"),1)],8,i8),t.versioningHostMode?(F(),$("button",{key:0,type:"button",onClick:ht=>io(String(Ce.workspace_id||""))},[...me[28]||(me[28]=[E("span",null,"在文件夹中打开",-1)])],8,r8)):ge("",!0),E("button",{type:"button",onClick:ht=>dl(Ce)},[...me[29]||(me[29]=[E("span",null,"重命名",-1)])],8,o8)],2)],2)],42,YU),E("div",{class:ke(["workspace-group-children",{expanded:Qs(String(Ce.workspace_id||""))}])},[E("div",a8,[(qt=(dt=In(String(Ce.workspace_id||"")))==null?void 0:dt.conversations)!=null&&qt.length?(F(),$(Ie,{key:1},[E("div",{class:"workspace-conversations-viewport",style:Ke({"--workspace-visible-count":((Ss=In(String(Ce.workspace_id||"")))==null?void 0:Ss.visibleLimit)||5})},[Qe(Vv,{name:"conversation-delete",tag:"div",class:ke(["workspace-conversations-list",`animation-mode-${We(w)}`]),onBeforeLeave:I},{default:Vt(()=>[(F(!0),$(Ie,null,tt(Uo(String(Ce.workspace_id||"")),ht=>(F(),$("div",{key:ht.id,class:ke(["conversation-item workspace-conversation-item",{active:ht.id===We(A),running:ut(ht.id)||Hs(ht.id),"insert-from-left":We(_)[ht.id]==="create","insert-from-under":We(_)[ht.id]==="duplicate","duplicate-source-mask":We(_)[ht.id]==="duplicateSource"}]),onClick:pn=>ir(ht.id,String(Ce.workspace_id||""))},[E("div",u8,ae(ht.title),1),E("div",{class:ke(["conversation-action-wrap",{"menu-open":W.value===ht.id}]),onClick:me[8]||(me[8]=Ne(()=>{},["stop"]))},[ut(ht.id)?(F(),$("span",h8)):Hs(ht.id)?(F(),$("span",d8)):(F(),$("button",{key:2,type:"button",class:"conversation-more-btn",title:"更多操作","aria-label":"更多操作","data-action-trigger":ht.id,"aria-expanded":W.value===ht.id,onClick:pn=>le(ht.id)},[...me[30]||(me[30]=[E("span",{"aria-hidden":"true"},null,-1)])],8,f8)),(F(),Wt(Sp,{to:"body"},[oe(ht.id)?(F(),$("div",{key:0,class:ke(["conversation-actions-menu conversation-actions-menu--fixed",{open:W.value===ht.id}]),style:Ke({top:V.value.top+"px",right:V.value.right+"px"})},[E("button",{type:"button",onClick:pn=>{W.value=null,fe.$emit("duplicate",ht.id)}},[E("span",{class:"icon icon-sm",style:Ke(R("copy")),"aria-hidden":"true"},null,4),me[31]||(me[31]=E("span",null,"复制",-1))],8,p8),E("button",{type:"button",class:"danger",onClick:pn=>{W.value=null,fe.$emit("delete",{id:ht.id,workspaceId:String(Ce.workspace_id||"")})}},[E("span",{class:"icon icon-sm",style:Ke(R("trash")),"aria-hidden":"true"},null,4),me[32]||(me[32]=E("span",null,"删除",-1))],8,g8)],6)):ge("",!0)]))],2)],10,c8))),128))]),_:2},1032,["class"])],4),nr(String(Ce.workspace_id||""))?(F(),$("div",m8,[E("button",{class:"load-more-btn",type:"button",disabled:(Kt=In(String(Ce.workspace_id||"")))==null?void 0:Kt.loadingMore,onClick:ht=>va(String(Ce.workspace_id||""))},ae((Es=In(String(Ce.workspace_id||"")))!=null&&Es.loadingMore?"载入中...":"加载更多"),9,v8)])):ge("",!0)],64)):(F(),$("div",l8," 暂无对话 "))])],2)])}),128))],2)):se.value&&We(v)?(F(),$("div",y8,[!We(g)&&!we.value.length?(F(),$("div",b8," 未找到匹配对话 ")):ge("",!0),(F(!0),$(Ie,null,tt(we.value,Ce=>(F(),$("div",{key:String(Ce.workspace_id||""),class:"workspace-group"},[E("div",_8,[E("div",S8,[E("span",{class:"icon icon-sm workspace-folder-icon",style:Ke(R("folderClosed")),"aria-hidden":"true"},null,4),E("span",w8,ae(Ce.label||Ce.workspace_id),1)])]),E("div",k8,[E("div",C8,[E("div",T8,[(F(!0),$(Ie,null,tt(Ce.results,dt=>(F(),$("div",{key:dt.id,class:ke(["conversation-item workspace-conversation-item",{active:dt.id===We(A),running:ut(dt.id)||Hs(dt.id)}]),onClick:qt=>ir(dt.id,String(Ce.workspace_id||""))},[E("div",E8,ae(dt.title),1),E("div",{class:ke(["conversation-action-wrap",{"menu-open":W.value===dt.id}]),onClick:me[9]||(me[9]=Ne(()=>{},["stop"]))},[ut(dt.id)?(F(),$("span",M8)):Hs(dt.id)?(F(),$("span",x8)):(F(),$("button",{key:2,type:"button",class:"conversation-more-btn",title:"更多操作","aria-label":"更多操作","data-action-trigger":dt.id,"aria-expanded":W.value===dt.id,onClick:qt=>le(dt.id)},[...me[33]||(me[33]=[E("span",{"aria-hidden":"true"},null,-1)])],8,I8)),(F(),Wt(Sp,{to:"body"},[oe(dt.id)?(F(),$("div",{key:0,class:ke(["conversation-actions-menu conversation-actions-menu--fixed",{open:W.value===dt.id}]),style:Ke({top:V.value.top+"px",right:V.value.right+"px"})},[E("button",{type:"button",onClick:qt=>{W.value=null,fe.$emit("duplicate",dt.id)}},[E("span",{class:"icon icon-sm",style:Ke(R("copy")),"aria-hidden":"true"},null,4),me[34]||(me[34]=E("span",null,"复制",-1))],8,R8),E("button",{type:"button",class:"danger",onClick:qt=>{W.value=null,fe.$emit("delete",{id:dt.id,workspaceId:String(Ce.workspace_id||"")})}},[E("span",{class:"icon icon-sm",style:Ke(R("trash")),"aria-hidden":"true"},null,4),me[35]||(me[35]=E("span",null,"删除",-1))],8,L8)],6)):ge("",!0)]))],2)],10,A8))),128))])])])]))),128))])):(F(),$(Ie,{key:3},[Le.value&&!de.value.length&&!We(v)&&!He.value?(F(),$("div",P8," 正在加载... ")):!de.value.length&&!Le.value&&!He.value?(F(),$("div",O8,ae(We(v)?"未找到匹配对话":"暂无对话记录"),1)):(F(),Wt(Vv,{key:2,name:"conversation-delete",tag:"div",class:ke(["conversation-list-items",`animation-mode-${We(w)}`])},{default:Vt(()=>[(F(!0),$(Ie,null,tt(de.value,Ce=>(F(),$("div",{key:Ce.id,class:ke(["conversation-item",{active:Ce.id===We(A),running:ut(Ce.id)||Hs(Ce.id),"insert-from-left":We(_)[Ce.id]==="create","insert-from-under":We(_)[Ce.id]==="duplicate","duplicate-source-mask":We(_)[Ce.id]==="duplicateSource",deleting:We(S).includes(Ce.id)}]),onClick:dt=>{W.value=null,fe.$emit("select",Ce.id)}},[E("div",N8,ae(Ce.title),1),E("div",{class:ke(["conversation-action-wrap",{"menu-open":W.value===Ce.id}]),onClick:me[10]||(me[10]=Ne(()=>{},["stop"]))},[ut(Ce.id)?(F(),$("span",B8)):Hs(Ce.id)?(F(),$("span",F8)):(F(),$("button",{key:2,type:"button",class:"conversation-more-btn",title:"更多操作","aria-label":"更多操作","data-action-trigger":Ce.id,"aria-expanded":W.value===Ce.id,onClick:dt=>le(Ce.id)},[...me[36]||(me[36]=[E("span",{"aria-hidden":"true"},null,-1)])],8,$8)),(F(),Wt(Sp,{to:"body"},[!ut(Ce.id)&&!Hs(Ce.id)&&W.value===Ce.id?(F(),$("div",{key:0,class:ke(["conversation-actions-menu conversation-actions-menu--fixed",{open:W.value===Ce.id}]),style:Ke({top:V.value.top+"px",right:V.value.right+"px"})},[E("button",{type:"button",onClick:dt=>{W.value=null,fe.$emit("duplicate",Ce.id)}},[E("span",{class:"icon icon-sm",style:Ke(R("copy")),"aria-hidden":"true"},null,4),me[37]||(me[37]=E("span",null,"复制",-1))],8,H8),E("button",{type:"button",class:"danger",onClick:dt=>{W.value=null,fe.$emit("delete",Ce.id)}},[E("span",{class:"icon icon-sm",style:Ke(R("trash")),"aria-hidden":"true"},null,4),me[38]||(me[38]=E("span",null,"删除",-1))],8,U8)],6)):ge("",!0)]))],2)],10,D8))),128))]),_:1},8,["class"]))],64)),!We(v)&&!se.value&&We(T)?(F(),$("div",W8,[E("button",{class:"load-more-btn",type:"button",disabled:We(k),onClick:me[11]||(me[11]=Ce=>fe.$emit("load-more"))},ae(We(k)?"载入中...":"加载更多"),9,z8)])):We(v)?(F(),$("div",j8,[We(g)?(F(),$("div",V8,[E("span",G8,[E("span",q8,[E("span",{class:"icon icon-sm search-spinner-icon",style:Ke(R("search"))},null,4)])]),me[39]||(me[39]=E("span",{class:"search-progress-text"},"搜索中...",-1))])):We(y)?(F(),$("button",{key:1,class:"load-more-btn",type:"button",onClick:me[12]||(me[12]=Ce=>fe.$emit("search-more"))}," 搜索更多 ")):de.value.length?(F(),$("div",K8,"已全部搜索")):ge("",!0)])):ge("",!0)]))]),_:1},8,["name"])],512),G.value?(F(),$("div",{key:1,class:"workspace-rename-overlay",onClick:Ne(jo,["self"])},[E("div",Q8,[E("div",X8," 重命名"+ae(s.workspaceKind==="workspace"?"工作区":"项目"),1),_v(E("input",{ref_key:"renameInput",ref:ie,"onUpdate:modelValue":me[13]||(me[13]=Ce=>ee.value=Ce),type:"text",class:"workspace-rename-input",placeholder:"请输入名称",onKeydown:[Sv(Ne(Jn,["prevent"]),["enter"]),Sv(Ne(jo,["prevent"]),["esc"])]},null,40,Y8),[[sS,ee.value]]),E("div",{class:"workspace-rename-actions"},[E("button",{type:"button",class:"workspace-rename-cancel",onClick:jo}," 取消 "),E("button",{type:"button",class:"workspace-rename-confirm",onClick:Jn}," 确认 ")])])])):ge("",!0),Qe(PU,{open:L.value,"anchor-rect":z.value,workspaces:s.workspaces,"current-workspace-id":s.currentWorkspaceId,"default-workspace-id":s.defaultWorkspaceId,"workspace-kind":s.workspaceKind,busy:s.workspaceBusy,"create-submitting":s.workspaceCreateSubmitting,"error-message":s.workspaceError,onClose:me[14]||(me[14]=Ce=>L.value=!1),onSwitch:me[15]||(me[15]=Ce=>fe.$emit("switch-workspace",Ce)),onCreate:me[16]||(me[16]=Ce=>fe.$emit("create-workspace",Ce)),onRename:me[17]||(me[17]=Ce=>fe.$emit("rename-workspace",Ce)),onDelete:me[18]||(me[18]=Ce=>fe.$emit("delete-workspace",Ce)),onSetDefault:me[19]||(me[19]=Ce=>fe.$emit("set-default-workspace",Ce)),onReveal:me[20]||(me[20]=Ce=>fe.$emit("reveal-workspace",Ce))},null,8,["open","anchor-rect","workspaces","current-workspace-id","default-workspace-id","workspace-kind","busy","create-submitting","error-message"]),E("div",{class:ke(["conversation-personal-entry",{active:We(M)}])},[E("button",{type:"button",class:"sidebar-nav-row personal-page-btn","data-tutorial":"open-personal-space",title:"个人空间",onClick:me[21]||(me[21]=Ce=>fe.$emit("personal"))},[...me[40]||(me[40]=[E("span",{class:"sidebar-nav-icon","aria-hidden":"true"},[E("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor"},[E("path",{"fill-rule":"evenodd","clip-rule":"evenodd",d:"M10 9a3 3 0 100-6 3 3 0 000 6zm-7 9a7 7 0 1114 0H3z"})])],-1),E("span",{class:"sidebar-nav-label personal-label"},"个人空间",-1)])])],2)])],2))}}),Z8={class:"icon-label"},eW={key:0,class:"approval-panel-body"},tW={key:0,class:"no-files"},sW={key:1,class:"approval-list"},nW={class:"approval-card__title"},iW={class:"approval-card__summary"},rW={key:0,class:"approval-edit-preview"},oW={class:"approval-path"},aW={class:"tool-result-diff approval-diff"},lW={key:1,class:"approval-edit-preview"},cW={class:"approval-path"},uW={class:"tool-result-diff approval-diff"},hW={key:2,class:"approval-kv"},dW={class:"approval-value approval-value--path"},fW={key:3,class:"approval-kv"},pW={class:"approval-value approval-value--path"},gW={key:4,class:"approval-lines approval-lines--cmd"},mW={key:5,class:"approval-kv"},vW={key:0},yW={class:"approval-actions"},bW=["disabled","onClick"],_W=["disabled","onClick"],SW=["disabled","onClick"],wW={key:0,class:"auto-approval-block__title"},kW={class:"auto-approval-block__content"},CW={key:1,class:"auto-approval-block__final"},TW={class:"auto-approval-block__reason"},AW=at({name:"ToolApprovalPanel",__name:"ToolApprovalPanel",props:{collapsed:{type:Boolean},width:{},approvals:{},decidingApprovalIds:{},autoApprovalFeedLines:{},autoApprovalFinalMessage:{},autoApprovalTitle:{}},emits:["approve","reject","switch-unrestricted","close"],setup(s,{emit:e}){const t=s,n=ye(()=>t.autoApprovalTitle||"自动审批记录"),i=ye(()=>n.value==="目标审批"),r=ye(()=>i.value?"目标审批":`工具审批 (${t.approvals.length})`),o=e,a=()=>{o("close")},c=ye(()=>typeof window<"u"&&window.innerWidth<=768);Cn(()=>{document.querySelector(".tool-approval-panel");const S=document.querySelector(".tool-approval-panel .sidebar-header");S&&window.getComputedStyle(S)});const l=S=>{var C;return(S==null?void 0:S.tool_name)==="edit_file"&&((C=S==null?void 0:S.preview)==null?void 0:C.edit_context)},u=S=>["run_command","terminal_input"].includes(S==null?void 0:S.tool_name),h=S=>(S==null?void 0:S.tool_name)==="write_file",d=S=>(S==null?void 0:S.tool_name)==="rename_file",p=S=>["create_file","create_folder","delete_file"].includes(S==null?void 0:S.tool_name),m=S=>Array.isArray(t.decidingApprovalIds)&&t.decidingApprovalIds.includes(S),v=S=>{var C,T,k,A;return((C=S==null?void 0:S.preview)==null?void 0:C.path)||((T=S==null?void 0:S.preview)==null?void 0:T.file_path)||((k=S==null?void 0:S.arguments)==null?void 0:k.path)||((A=S==null?void 0:S.arguments)==null?void 0:A.file_path)||""},g=S=>{const C=String(S||"");return{run_command:"执行命令",terminal_input:"终端输入",create_file:"创建文件",create_folder:"创建文件夹",delete_file:"删除文件",rename_file:"重命名文件",write_file:"写入文件",edit_file:"编辑文件"}[C]||C||"待审批操作"},y=S=>{var T;return String(((T=S==null?void 0:S.preview)==null?void 0:T.content_preview)||"").split(`
`)},b=S=>{var T,k;return(Array.isArray((k=(T=S==null?void 0:S.preview)==null?void 0:T.edit_context)==null?void 0:k.old)?S.preview.edit_context.old:[]).map(A=>String((A==null?void 0:A.content)??""))},_=S=>{var T,k;return(Array.isArray((k=(T=S==null?void 0:S.preview)==null?void 0:T.edit_context)==null?void 0:k.new)?S.preview.edit_context.new:[]).map(A=>String((A==null?void 0:A.content)??""))},w=S=>{const T=String(S||"").split(`
`),k=String(T[0]||"").trim(),A=String(T.slice(1).join(`
`)||"").trim();return{title:k,reason:A,isApproved:k.includes("批准通过")}};return(S,C)=>(F(),$("aside",{class:ke(["sidebar right-sidebar tool-approval-panel",{collapsed:s.collapsed,"is-goal-approval-mode":i.value}]),style:Ke({width:s.collapsed?"0px":s.width+"px"})},[E("div",{class:ke(["sidebar-header",{"mobile-header":c.value}])},[E("h3",Z8,ae(r.value),1),E("button",{type:"button",class:"approval-close-btn","aria-label":"关闭审批面板",onClick:a}," × ")],2),s.collapsed?ge("",!0):(F(),$("div",eW,[!s.approvals.length&&!i.value?(F(),$("div",tW,"暂无待审批操作")):(F(),$("div",sW,[(F(!0),$(Ie,null,tt(s.approvals,T=>{var k,A,M,R,P,L,z,Q;return F(),$("div",{key:T.approval_id,class:"approval-card"},[E("div",nW,ae(T.tool_name),1),E("div",iW,ae(g(T.tool_name)),1),l(T)?(F(),$("div",rW,[E("div",oW,ae(((k=T.preview)==null?void 0:k.file_path)||((A=T.preview)==null?void 0:A.resolved_path)),1),E("div",aW,[(F(!0),$(Ie,null,tt(b(T),(W,V)=>(F(),$("div",{class:"diff-line diff-remove",key:`o-${T.approval_id}-${V}`}," - "+ae(W),1))),128)),(F(!0),$(Ie,null,tt(_(T),(W,V)=>(F(),$("div",{class:"diff-line diff-add",key:`n-${T.approval_id}-${V}`}," + "+ae(W),1))),128))])])):h(T)?(F(),$("div",lW,[E("div",cW,ae((M=T.preview)==null?void 0:M.file_path),1),E("div",uW,[(F(!0),$(Ie,null,tt(y(T),(W,V)=>(F(),$("div",{class:"diff-line diff-add",key:`w-${T.approval_id}-${V}`}," + "+ae(W),1))),128))])])):p(T)?(F(),$("div",hW,[E("div",null,[C[0]||(C[0]=E("strong",null,"路径:",-1)),E("span",dW,ae(v(T)),1)])])):d(T)?(F(),$("div",fW,[E("div",null,[C[1]||(C[1]=E("strong",null,"重命名:",-1)),E("span",pW,ae((R=T.preview)==null?void 0:R.old_path)+" → "+ae((P=T.preview)==null?void 0:P.new_path),1)])])):u(T)?(F(),$("pre",gW,ae(((L=T.preview)==null?void 0:L.code)||((z=T.preview)==null?void 0:z.command)||""),1)):(F(),$("div",mW,[E("div",null,[C[2]||(C[2]=E("strong",null,"工具:",-1)),hn(ae(T.tool_name),1)]),(Q=T.preview)!=null&&Q.summary?(F(),$("div",vW,[C[3]||(C[3]=E("strong",null,"说明:",-1)),hn(ae(T.preview.summary),1)])):ge("",!0)])),E("div",yW,[E("button",{type:"button",class:"approval-btn approval-btn--switch",disabled:m(T.approval_id),onClick:W=>S.$emit("switch-unrestricted",T.approval_id)}," 切换到无限制 ",8,bW),E("button",{type:"button",class:"approval-btn approval-btn--approve",disabled:m(T.approval_id),onClick:W=>S.$emit("approve",T.approval_id)}," 运行 ",8,_W),E("button",{type:"button",class:"approval-btn approval-btn--reject",disabled:m(T.approval_id),onClick:W=>S.$emit("reject",T.approval_id)}," 拒绝 ",8,SW)])])}),128))])),s.autoApprovalFeedLines.length||s.autoApprovalFinalMessage?(F(),$("div",{key:2,class:ke(["auto-approval-block",{"auto-approval-block--goal":i.value}])},[i.value?ge("",!0):(F(),$("div",wW,ae(n.value),1)),E("pre",kW,ae(s.autoApprovalFeedLines.join(`
`)),1),s.autoApprovalFinalMessage?(F(),$("div",CW,[w(s.autoApprovalFinalMessage).title?(F(),$("div",{key:0,class:ke(["auto-approval-block__decision",w(s.autoApprovalFinalMessage).isApproved?"auto-approval-block__decision--approved":"auto-approval-block__decision--rejected"])},ae(w(s.autoApprovalFinalMessage).title),3)):ge("",!0),E("div",TW,ae(w(s.autoApprovalFinalMessage).reason),1)])):ge("",!0)],2)):ge("",!0)]))],6))}}),EW=Qt(AW,[["__scopeId","data-v-c836c8ac"]]),MW={class:"git-changes-panel__header"},xW={class:"git-changes-panel__title"},IW={class:"git-changes-panel__branch"},RW={class:"git-changes-panel__upstream"},LW={class:"git-changes-panel__summary"},PW={class:"git-changes-panel__add"},OW={class:"git-changes-panel__del"},DW={class:"git-changes-panel__body"},NW={key:0,class:"git-changes-panel__empty"},BW={key:1,class:"git-changes-panel__empty git-changes-panel__empty--error"},FW={key:2,class:"git-changes-panel__empty"},$W={class:"git-change-file__header"},HW={class:"git-change-file__title"},UW={class:"git-change-file__open-wrap"},WW=["disabled","title","onClick"],zW=["src"],jW={key:0,class:"git-change-file__open-empty"},VW=["onClick"],GW=["src"],qW={key:2,class:"git-change-file__open-empty"},KW={class:"git-change-file__path"},QW=["onClick"],XW={class:"git-change-file__stats"},YW={class:"git-changes-panel__add"},JW={class:"git-changes-panel__del"},ZW={class:"git-change-file__diff"},ez={class:"git-change-file__diff-inner"},tz=["onClick"],sz={class:"git-change-file__fold-content"},nz={class:"git-change-line__num"},iz={class:"git-change-line__marker"},rz={class:"git-change-line__text"},oz=["onClick"],az={class:"git-change-file__fold-content"},lz=at({name:"GitChangesPanel",__name:"GitChangesPanel",props:{width:{},loading:{type:Boolean},error:{},hostMode:{type:Boolean},foldContexts:{},diff:{}},emits:["close","expand-context","reset-context"],setup(s,{emit:e}){const t=s,n=e,i=ye(()=>{var S;return String(((S=t.diff)==null?void 0:S.branch)||"HEAD")}),r=ye(()=>{var S;return String(((S=t.diff)==null?void 0:S.upstream)||"未设置云端分支")}),o=ye(()=>{var S;return Math.max(0,Number(((S=t.diff)==null?void 0:S.additions)||0))}),a=ye(()=>{var S;return Math.max(0,Number(((S=t.diff)==null?void 0:S.deletions)||0))}),c=ye(()=>{var S;return Array.isArray((S=t.diff)==null?void 0:S.files)?t.diff.files:[]}),l=S=>{var T;const C=(T=t.foldContexts)==null?void 0:T[S];return!!C&&Object.values(C).some(k=>Number(k||0)>0)},u=new URL("data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%2024%2024'%20width='24'%20height='24'%20fill='none'%20stroke='%23000000'%20stroke-width='2'%20stroke-linecap='round'%20stroke-linejoin='round'%20style='opacity:1;'%3e%3cpath%20d='M12.5%2022H18a2%202%200%200%200%202-2V7l-5-5H6a2%202%200%200%200-2%202v9.5'/%3e%3cpath%20d='M14%202v4a2%202%200%200%200%202%202h4m-6.622%207.626a1%201%200%201%200-3.004-3.004l-5.01%205.012a2%202%200%200%200-.506.854l-.837%202.87a.5.5%200%200%200%20.62.62l2.87-.837a2%202%200%200%200%20.854-.506z'/%3e%3c/svg%3e",import.meta.url).href,h=pe(""),d=pe([]),p=pe(""),m=pe(""),v=S=>{const C=(S==null?void 0:S.kind)==="delete"?S.old_line:S==null?void 0:S.new_line,T=Number(C);return Number.isFinite(T)&&T>0?String(T):""},g=S=>S==="add"?"+":S==="delete"?"-":" ",y=(S,C)=>{n("expand-context",{path:S,foldKey:C})},b=S=>{n("reset-context",S)},_=async S=>{var C;if(t.hostMode){if(h.value===S){h.value="";return}h.value="",d.value=[],p.value="",m.value=S;try{const T=await fetch(`/api/project/file-open-apps?path=${encodeURIComponent(S)}`),k=await T.json().catch(()=>({}));if(!T.ok||!(k!=null&&k.success))throw new Error((k==null?void 0:k.error)||"检测应用失败");d.value=Array.isArray((C=k==null?void 0:k.data)==null?void 0:C.apps)?k.data.apps:[],h.value=S}catch(T){p.value=(T==null?void 0:T.message)||"检测应用失败",h.value=S}finally{m.value=""}}},w=async(S,C)=>{try{const T=await fetch("/api/project/open-file-with-app",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:S,app_id:C})}),k=await T.json().catch(()=>({}));if(!T.ok||!(k!=null&&k.success))throw new Error((k==null?void 0:k.error)||"打开文件失败");h.value=""}catch(T){p.value=T instanceof Error?T.message:"打开文件失败"}};return(S,C)=>(F(),$("aside",{class:"git-changes-panel",style:Ke({width:s.width+"px"})},[E("header",MW,[E("div",xW,[E("span",IW,ae(i.value),1),C[2]||(C[2]=E("span",{class:"git-changes-panel__arrow"},"→",-1)),E("span",RW,ae(r.value),1)]),E("div",LW,[E("span",PW,"+"+ae(o.value),1),E("span",OW,"-"+ae(a.value),1),E("button",{type:"button",class:"git-changes-panel__close","aria-label":"关闭 Git 变更面板",onClick:C[0]||(C[0]=T=>S.$emit("close"))}," × ")])]),E("div",DW,[s.loading&&!s.diff?(F(),$("div",NW,"正在加载 Git 变更…")):s.error&&!c.value.length?(F(),$("div",BW,ae(s.error),1)):c.value.length?(F(!0),$(Ie,{key:3},tt(c.value,T=>(F(),$("section",{key:T.path,class:"git-change-file"},[E("div",$W,[E("span",HW,[E("span",UW,[E("button",{type:"button",class:ke(["git-change-file__open-btn",{open:h.value===T.path||m.value===T.path}]),disabled:!s.hostMode,title:s.hostMode?"用应用打开文件":"Docker 模式不可用",onClick:Ne(k=>_(T.path),["stop","prevent"])},[E("img",{class:"git-change-file__open-icon",src:We(u),alt:"","aria-hidden":"true"},null,8,zW),C[4]||(C[4]=E("span",{class:"git-change-file__open-caret","aria-hidden":"true"},null,-1))],10,WW),h.value===T.path?(F(),$("div",{key:0,class:"git-change-file__open-menu",onClick:C[1]||(C[1]=Ne(()=>{},["stop"]))},[p.value?(F(),$("div",jW,ae(p.value),1)):(F(!0),$(Ie,{key:1},tt(d.value,k=>(F(),$("button",{key:k.id,type:"button",class:"git-change-file__open-option",onClick:Ne(A=>w(T.path,k.id),["stop","prevent"])},[E("img",{class:"git-change-file__open-option-icon",src:k.icon_url||We(u),alt:"","aria-hidden":"true"},null,8,GW),E("span",null,ae(k.label),1)],8,VW))),128)),!m.value&&!p.value&&!d.value.length?(F(),$("div",qW," 未检测到可用应用 ")):ge("",!0)])):ge("",!0)]),E("span",KW,ae(T.path),1),l(T.path)?(F(),$("button",{key:0,type:"button",class:"git-change-file__reset",onClick:Ne(k=>b(T.path),["stop","prevent"])}," 恢复 ",8,QW)):ge("",!0)]),E("span",XW,[E("span",YW,"+"+ae(T.additions||0),1),E("span",JW,"-"+ae(T.deletions||0),1)])]),E("div",ZW,[E("div",ez,[(F(!0),$(Ie,null,tt(T.hunks,(k,A)=>(F(),$(Ie,{key:`${T.path}-${A}`},[k.before_hidden>0?(F(),$("button",{key:0,type:"button",class:"git-change-file__fold",onClick:Ne(M=>y(T.path,k.before_fold_key),["stop","prevent"])},[E("span",sz,[C[5]||(C[5]=E("span",{class:"git-change-file__fold-icon git-change-file__fold-icon--up","aria-hidden":"true"},null,-1)),E("span",null,ae(k.before_hidden)+" 行未编辑的内容",1)])],8,tz)):ge("",!0),(F(!0),$(Ie,null,tt(k.lines,(M,R)=>(F(),$("div",{key:`${T.path}-${A}-${R}`,class:ke(["git-change-line",{"git-change-line--add":M.kind==="add","git-change-line--delete":M.kind==="delete"}])},[E("span",nz,ae(v(M)),1),E("span",iz,ae(g(M.kind)),1),E("span",rz,ae(M.text),1)],2))),128))],64))),128)),T.after_hidden>0?(F(),$("button",{key:0,type:"button",class:"git-change-file__fold",onClick:Ne(k=>y(T.path,T.after_fold_key||"after"),["stop","prevent"])},[E("span",az,[C[6]||(C[6]=E("span",{class:"git-change-file__fold-icon git-change-file__fold-icon--down","aria-hidden":"true"},null,-1)),E("span",null,ae(T.after_hidden)+" 行未编辑的内容",1)])],8,oz)):ge("",!0)])])]))),128)):(F(),$("div",FW,[...C[3]||(C[3]=[mi('<svg class="git-changes-panel__empty-svg" viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M9 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v5" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path><circle cx="13" cy="12" r="2" stroke="currentColor" stroke-width="2"></circle><path d="M18 19c-2.8 0-5-2.2-5-5v8" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path><circle cx="20" cy="19" r="2" stroke="currentColor" stroke-width="2"></circle></svg><span>当前没有未提交变更</span>',2)])]))])],4))}});var eL={exports:{}};(function(s,e){(function(t,n){s.exports=n()})(self,()=>(()=>{var t={4567:function(o,a,c){var l=this&&this.__decorate||function(_,w,S,C){var T,k=arguments.length,A=k<3?w:C===null?C=Object.getOwnPropertyDescriptor(w,S):C;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")A=Reflect.decorate(_,w,S,C);else for(var M=_.length-1;M>=0;M--)(T=_[M])&&(A=(k<3?T(A):k>3?T(w,S,A):T(w,S))||A);return k>3&&A&&Object.defineProperty(w,S,A),A},u=this&&this.__param||function(_,w){return function(S,C){w(S,C,_)}};Object.defineProperty(a,"__esModule",{value:!0}),a.AccessibilityManager=void 0;const h=c(9042),d=c(6114),p=c(9924),m=c(844),v=c(5596),g=c(4725),y=c(3656);let b=a.AccessibilityManager=class extends m.Disposable{constructor(_,w){super(),this._terminal=_,this._renderService=w,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="",this._accessibilityContainer=document.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=document.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let S=0;S<this._terminal.rows;S++)this._rowElements[S]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[S]);if(this._topBoundaryFocusListener=S=>this._handleBoundaryFocus(S,0),this._bottomBoundaryFocusListener=S=>this._handleBoundaryFocus(S,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions(),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=document.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this.register(new p.TimeBasedDebouncer(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this.register(this._terminal.onResize(S=>this._handleResize(S.rows))),this.register(this._terminal.onRender(S=>this._refreshRows(S.start,S.end))),this.register(this._terminal.onScroll(()=>this._refreshRows())),this.register(this._terminal.onA11yChar(S=>this._handleChar(S))),this.register(this._terminal.onLineFeed(()=>this._handleChar(`
`))),this.register(this._terminal.onA11yTab(S=>this._handleTab(S))),this.register(this._terminal.onKey(S=>this._handleKey(S.key))),this.register(this._terminal.onBlur(()=>this._clearLiveRegion())),this.register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._screenDprMonitor=new v.ScreenDprMonitor(window),this.register(this._screenDprMonitor),this._screenDprMonitor.setListener(()=>this._refreshRowsDimensions()),this.register((0,y.addDisposableDomListener)(window,"resize",()=>this._refreshRowsDimensions())),this._refreshRows(),this.register((0,m.toDisposable)(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(_){for(let w=0;w<_;w++)this._handleChar(" ")}_handleChar(_){this._liveRegionLineCount<21&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==_&&(this._charsToAnnounce+=_):this._charsToAnnounce+=_,_===`
`&&(this._liveRegionLineCount++,this._liveRegionLineCount===21&&(this._liveRegion.textContent+=h.tooMuchOutput)),d.isMac&&this._liveRegion.textContent&&this._liveRegion.textContent.length>0&&!this._liveRegion.parentNode&&setTimeout(()=>{this._accessibilityContainer.appendChild(this._liveRegion)},0))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0,d.isMac&&this._liveRegion.remove()}_handleKey(_){this._clearLiveRegion(),new RegExp("\\p{Control}","u").test(_)||this._charsToConsume.push(_)}_refreshRows(_,w){this._liveRegionDebouncer.refresh(_,w,this._terminal.rows)}_renderRows(_,w){const S=this._terminal.buffer,C=S.lines.length.toString();for(let T=_;T<=w;T++){const k=S.translateBufferLineToString(S.ydisp+T,!0),A=(S.ydisp+T+1).toString(),M=this._rowElements[T];M&&(k.length===0?M.innerText=" ":M.textContent=k,M.setAttribute("aria-posinset",A),M.setAttribute("aria-setsize",C))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(_,w){const S=_.target,C=this._rowElements[w===0?1:this._rowElements.length-2];if(S.getAttribute("aria-posinset")===(w===0?"1":`${this._terminal.buffer.lines.length}`)||_.relatedTarget!==C)return;let T,k;if(w===0?(T=S,k=this._rowElements.pop(),this._rowContainer.removeChild(k)):(T=this._rowElements.shift(),k=S,this._rowContainer.removeChild(T)),T.removeEventListener("focus",this._topBoundaryFocusListener),k.removeEventListener("focus",this._bottomBoundaryFocusListener),w===0){const A=this._createAccessibilityTreeNode();this._rowElements.unshift(A),this._rowContainer.insertAdjacentElement("afterbegin",A)}else{const A=this._createAccessibilityTreeNode();this._rowElements.push(A),this._rowContainer.appendChild(A)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(w===0?-1:1),this._rowElements[w===0?1:this._rowElements.length-2].focus(),_.preventDefault(),_.stopImmediatePropagation()}_handleResize(_){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let w=this._rowContainer.children.length;w<this._terminal.rows;w++)this._rowElements[w]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[w]);for(;this._rowElements.length>_;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){const _=document.createElement("div");return _.setAttribute("role","listitem"),_.tabIndex=-1,this._refreshRowDimensions(_),_}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){this._accessibilityContainer.style.width=`${this._renderService.dimensions.css.canvas.width}px`,this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let _=0;_<this._terminal.rows;_++)this._refreshRowDimensions(this._rowElements[_])}}_refreshRowDimensions(_){_.style.height=`${this._renderService.dimensions.css.cell.height}px`}};a.AccessibilityManager=b=l([u(1,g.IRenderService)],b)},3614:(o,a)=>{function c(d){return d.replace(/\r?\n/g,"\r")}function l(d,p){return p?"\x1B[200~"+d+"\x1B[201~":d}function u(d,p,m,v){d=l(d=c(d),m.decPrivateModes.bracketedPasteMode&&v.rawOptions.ignoreBracketedPasteMode!==!0),m.triggerDataEvent(d,!0),p.value=""}function h(d,p,m){const v=m.getBoundingClientRect(),g=d.clientX-v.left-10,y=d.clientY-v.top-10;p.style.width="20px",p.style.height="20px",p.style.left=`${g}px`,p.style.top=`${y}px`,p.style.zIndex="1000",p.focus()}Object.defineProperty(a,"__esModule",{value:!0}),a.rightClickHandler=a.moveTextAreaUnderMouseCursor=a.paste=a.handlePasteEvent=a.copyHandler=a.bracketTextForPaste=a.prepareTextForTerminal=void 0,a.prepareTextForTerminal=c,a.bracketTextForPaste=l,a.copyHandler=function(d,p){d.clipboardData&&d.clipboardData.setData("text/plain",p.selectionText),d.preventDefault()},a.handlePasteEvent=function(d,p,m,v){d.stopPropagation(),d.clipboardData&&u(d.clipboardData.getData("text/plain"),p,m,v)},a.paste=u,a.moveTextAreaUnderMouseCursor=h,a.rightClickHandler=function(d,p,m,v,g){h(d,p,m),g&&v.rightClickSelect(d),p.value=v.selectionText,p.select()}},7239:(o,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.ColorContrastCache=void 0;const l=c(1505);a.ColorContrastCache=class{constructor(){this._color=new l.TwoKeyMap,this._css=new l.TwoKeyMap}setCss(u,h,d){this._css.set(u,h,d)}getCss(u,h){return this._css.get(u,h)}setColor(u,h,d){this._color.set(u,h,d)}getColor(u,h){return this._color.get(u,h)}clear(){this._color.clear(),this._css.clear()}}},3656:(o,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.addDisposableDomListener=void 0,a.addDisposableDomListener=function(c,l,u,h){c.addEventListener(l,u,h);let d=!1;return{dispose:()=>{d||(d=!0,c.removeEventListener(l,u,h))}}}},6465:function(o,a,c){var l=this&&this.__decorate||function(g,y,b,_){var w,S=arguments.length,C=S<3?y:_===null?_=Object.getOwnPropertyDescriptor(y,b):_;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")C=Reflect.decorate(g,y,b,_);else for(var T=g.length-1;T>=0;T--)(w=g[T])&&(C=(S<3?w(C):S>3?w(y,b,C):w(y,b))||C);return S>3&&C&&Object.defineProperty(y,b,C),C},u=this&&this.__param||function(g,y){return function(b,_){y(b,_,g)}};Object.defineProperty(a,"__esModule",{value:!0}),a.Linkifier2=void 0;const h=c(3656),d=c(8460),p=c(844),m=c(2585);let v=a.Linkifier2=class extends p.Disposable{get currentLink(){return this._currentLink}constructor(g){super(),this._bufferService=g,this._linkProviders=[],this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this.register(new d.EventEmitter),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this.register(new d.EventEmitter),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this.register((0,p.getDisposeArrayDisposable)(this._linkCacheDisposables)),this.register((0,p.toDisposable)(()=>{this._lastMouseEvent=void 0})),this.register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0}))}registerLinkProvider(g){return this._linkProviders.push(g),{dispose:()=>{const y=this._linkProviders.indexOf(g);y!==-1&&this._linkProviders.splice(y,1)}}}attachToDom(g,y,b){this._element=g,this._mouseService=y,this._renderService=b,this.register((0,h.addDisposableDomListener)(this._element,"mouseleave",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this.register((0,h.addDisposableDomListener)(this._element,"mousemove",this._handleMouseMove.bind(this))),this.register((0,h.addDisposableDomListener)(this._element,"mousedown",this._handleMouseDown.bind(this))),this.register((0,h.addDisposableDomListener)(this._element,"mouseup",this._handleMouseUp.bind(this)))}_handleMouseMove(g){if(this._lastMouseEvent=g,!this._element||!this._mouseService)return;const y=this._positionFromMouseEvent(g,this._element,this._mouseService);if(!y)return;this._isMouseOut=!1;const b=g.composedPath();for(let _=0;_<b.length;_++){const w=b[_];if(w.classList.contains("xterm"))break;if(w.classList.contains("xterm-hover"))return}this._lastBufferCell&&y.x===this._lastBufferCell.x&&y.y===this._lastBufferCell.y||(this._handleHover(y),this._lastBufferCell=y)}_handleHover(g){if(this._activeLine!==g.y||this._wasResized)return this._clearCurrentLink(),this._askForLink(g,!1),void(this._wasResized=!1);this._currentLink&&this._linkAtPosition(this._currentLink.link,g)||(this._clearCurrentLink(),this._askForLink(g,!0))}_askForLink(g,y){var b,_;this._activeProviderReplies&&y||((b=this._activeProviderReplies)===null||b===void 0||b.forEach(S=>{S==null||S.forEach(C=>{C.link.dispose&&C.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=g.y);let w=!1;for(const[S,C]of this._linkProviders.entries())y?!((_=this._activeProviderReplies)===null||_===void 0)&&_.get(S)&&(w=this._checkLinkProviderResult(S,g,w)):C.provideLinks(g.y,T=>{var k,A;if(this._isMouseOut)return;const M=T==null?void 0:T.map(R=>({link:R}));(k=this._activeProviderReplies)===null||k===void 0||k.set(S,M),w=this._checkLinkProviderResult(S,g,w),((A=this._activeProviderReplies)===null||A===void 0?void 0:A.size)===this._linkProviders.length&&this._removeIntersectingLinks(g.y,this._activeProviderReplies)})}_removeIntersectingLinks(g,y){const b=new Set;for(let _=0;_<y.size;_++){const w=y.get(_);if(w)for(let S=0;S<w.length;S++){const C=w[S],T=C.link.range.start.y<g?0:C.link.range.start.x,k=C.link.range.end.y>g?this._bufferService.cols:C.link.range.end.x;for(let A=T;A<=k;A++){if(b.has(A)){w.splice(S--,1);break}b.add(A)}}}}_checkLinkProviderResult(g,y,b){var _;if(!this._activeProviderReplies)return b;const w=this._activeProviderReplies.get(g);let S=!1;for(let C=0;C<g;C++)this._activeProviderReplies.has(C)&&!this._activeProviderReplies.get(C)||(S=!0);if(!S&&w){const C=w.find(T=>this._linkAtPosition(T.link,y));C&&(b=!0,this._handleNewLink(C))}if(this._activeProviderReplies.size===this._linkProviders.length&&!b)for(let C=0;C<this._activeProviderReplies.size;C++){const T=(_=this._activeProviderReplies.get(C))===null||_===void 0?void 0:_.find(k=>this._linkAtPosition(k.link,y));if(T){b=!0,this._handleNewLink(T);break}}return b}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(g){if(!this._element||!this._mouseService||!this._currentLink)return;const y=this._positionFromMouseEvent(g,this._element,this._mouseService);y&&this._mouseDownLink===this._currentLink&&this._linkAtPosition(this._currentLink.link,y)&&this._currentLink.link.activate(g,this._currentLink.link.text)}_clearCurrentLink(g,y){this._element&&this._currentLink&&this._lastMouseEvent&&(!g||!y||this._currentLink.link.range.start.y>=g&&this._currentLink.link.range.end.y<=y)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,(0,p.disposeArray)(this._linkCacheDisposables))}_handleNewLink(g){if(!this._element||!this._lastMouseEvent||!this._mouseService)return;const y=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);y&&this._linkAtPosition(g.link,y)&&(this._currentLink=g,this._currentLink.state={decorations:{underline:g.link.decorations===void 0||g.link.decorations.underline,pointerCursor:g.link.decorations===void 0||g.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,g.link,this._lastMouseEvent),g.link.decorations={},Object.defineProperties(g.link.decorations,{pointerCursor:{get:()=>{var b,_;return(_=(b=this._currentLink)===null||b===void 0?void 0:b.state)===null||_===void 0?void 0:_.decorations.pointerCursor},set:b=>{var _,w;!((_=this._currentLink)===null||_===void 0)&&_.state&&this._currentLink.state.decorations.pointerCursor!==b&&(this._currentLink.state.decorations.pointerCursor=b,this._currentLink.state.isHovered&&((w=this._element)===null||w===void 0||w.classList.toggle("xterm-cursor-pointer",b)))}},underline:{get:()=>{var b,_;return(_=(b=this._currentLink)===null||b===void 0?void 0:b.state)===null||_===void 0?void 0:_.decorations.underline},set:b=>{var _,w,S;!((_=this._currentLink)===null||_===void 0)&&_.state&&((S=(w=this._currentLink)===null||w===void 0?void 0:w.state)===null||S===void 0?void 0:S.decorations.underline)!==b&&(this._currentLink.state.decorations.underline=b,this._currentLink.state.isHovered&&this._fireUnderlineEvent(g.link,b))}}}),this._renderService&&this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(b=>{if(!this._currentLink)return;const _=b.start===0?0:b.start+1+this._bufferService.buffer.ydisp,w=this._bufferService.buffer.ydisp+1+b.end;if(this._currentLink.link.range.start.y>=_&&this._currentLink.link.range.end.y<=w&&(this._clearCurrentLink(_,w),this._lastMouseEvent&&this._element)){const S=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);S&&this._askForLink(S,!1)}})))}_linkHover(g,y,b){var _;!((_=this._currentLink)===null||_===void 0)&&_.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(y,!0),this._currentLink.state.decorations.pointerCursor&&g.classList.add("xterm-cursor-pointer")),y.hover&&y.hover(b,y.text)}_fireUnderlineEvent(g,y){const b=g.range,_=this._bufferService.buffer.ydisp,w=this._createLinkUnderlineEvent(b.start.x-1,b.start.y-_-1,b.end.x,b.end.y-_-1,void 0);(y?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(w)}_linkLeave(g,y,b){var _;!((_=this._currentLink)===null||_===void 0)&&_.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(y,!1),this._currentLink.state.decorations.pointerCursor&&g.classList.remove("xterm-cursor-pointer")),y.leave&&y.leave(b,y.text)}_linkAtPosition(g,y){const b=g.range.start.y*this._bufferService.cols+g.range.start.x,_=g.range.end.y*this._bufferService.cols+g.range.end.x,w=y.y*this._bufferService.cols+y.x;return b<=w&&w<=_}_positionFromMouseEvent(g,y,b){const _=b.getCoords(g,y,this._bufferService.cols,this._bufferService.rows);if(_)return{x:_[0],y:_[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(g,y,b,_,w){return{x1:g,y1:y,x2:b,y2:_,cols:this._bufferService.cols,fg:w}}};a.Linkifier2=v=l([u(0,m.IBufferService)],v)},9042:(o,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.tooMuchOutput=a.promptLabel=void 0,a.promptLabel="Terminal input",a.tooMuchOutput="Too much output to announce, navigate to rows manually to read"},3730:function(o,a,c){var l=this&&this.__decorate||function(v,g,y,b){var _,w=arguments.length,S=w<3?g:b===null?b=Object.getOwnPropertyDescriptor(g,y):b;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")S=Reflect.decorate(v,g,y,b);else for(var C=v.length-1;C>=0;C--)(_=v[C])&&(S=(w<3?_(S):w>3?_(g,y,S):_(g,y))||S);return w>3&&S&&Object.defineProperty(g,y,S),S},u=this&&this.__param||function(v,g){return function(y,b){g(y,b,v)}};Object.defineProperty(a,"__esModule",{value:!0}),a.OscLinkProvider=void 0;const h=c(511),d=c(2585);let p=a.OscLinkProvider=class{constructor(v,g,y){this._bufferService=v,this._optionsService=g,this._oscLinkService=y}provideLinks(v,g){var y;const b=this._bufferService.buffer.lines.get(v-1);if(!b)return void g(void 0);const _=[],w=this._optionsService.rawOptions.linkHandler,S=new h.CellData,C=b.getTrimmedLength();let T=-1,k=-1,A=!1;for(let M=0;M<C;M++)if(k!==-1||b.hasContent(M)){if(b.loadCell(M,S),S.hasExtendedAttrs()&&S.extended.urlId){if(k===-1){k=M,T=S.extended.urlId;continue}A=S.extended.urlId!==T}else k!==-1&&(A=!0);if(A||k!==-1&&M===C-1){const R=(y=this._oscLinkService.getLinkData(T))===null||y===void 0?void 0:y.uri;if(R){const P={start:{x:k+1,y:v},end:{x:M+(A||M!==C-1?0:1),y:v}};let L=!1;if(!(w!=null&&w.allowNonHttpProtocols))try{const z=new URL(R);["http:","https:"].includes(z.protocol)||(L=!0)}catch{L=!0}L||_.push({text:R,range:P,activate:(z,Q)=>w?w.activate(z,Q,P):m(0,Q),hover:(z,Q)=>{var W;return(W=w==null?void 0:w.hover)===null||W===void 0?void 0:W.call(w,z,Q,P)},leave:(z,Q)=>{var W;return(W=w==null?void 0:w.leave)===null||W===void 0?void 0:W.call(w,z,Q,P)}})}A=!1,S.hasExtendedAttrs()&&S.extended.urlId?(k=M,T=S.extended.urlId):(k=-1,T=-1)}}g(_)}};function m(v,g){if(confirm(`Do you want to navigate to ${g}?
WARNING: This link could potentially be dangerous`)){const y=window.open();if(y){try{y.opener=null}catch{}y.location.href=g}else console.warn("Opening link blocked as opener could not be cleared")}}a.OscLinkProvider=p=l([u(0,d.IBufferService),u(1,d.IOptionsService),u(2,d.IOscLinkService)],p)},6193:(o,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.RenderDebouncer=void 0,a.RenderDebouncer=class{constructor(c,l){this._parentWindow=c,this._renderCallback=l,this._refreshCallbacks=[]}dispose(){this._animationFrame&&(this._parentWindow.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0)}addRefreshCallback(c){return this._refreshCallbacks.push(c),this._animationFrame||(this._animationFrame=this._parentWindow.requestAnimationFrame(()=>this._innerRefresh())),this._animationFrame}refresh(c,l,u){this._rowCount=u,c=c!==void 0?c:0,l=l!==void 0?l:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,c):c,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,l):l,this._animationFrame||(this._animationFrame=this._parentWindow.requestAnimationFrame(()=>this._innerRefresh()))}_innerRefresh(){if(this._animationFrame=void 0,this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return void this._runRefreshCallbacks();const c=Math.max(this._rowStart,0),l=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(c,l),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(const c of this._refreshCallbacks)c(0);this._refreshCallbacks=[]}}},5596:(o,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.ScreenDprMonitor=void 0;const l=c(844);class u extends l.Disposable{constructor(d){super(),this._parentWindow=d,this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this.register((0,l.toDisposable)(()=>{this.clearListener()}))}setListener(d){this._listener&&this.clearListener(),this._listener=d,this._outerListener=()=>{this._listener&&(this._listener(this._parentWindow.devicePixelRatio,this._currentDevicePixelRatio),this._updateDpr())},this._updateDpr()}_updateDpr(){var d;this._outerListener&&((d=this._resolutionMediaMatchList)===null||d===void 0||d.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){this._resolutionMediaMatchList&&this._listener&&this._outerListener&&(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._listener=void 0,this._outerListener=void 0)}}a.ScreenDprMonitor=u},3236:(o,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.Terminal=void 0;const l=c(3614),u=c(3656),h=c(6465),d=c(9042),p=c(3730),m=c(1680),v=c(3107),g=c(5744),y=c(2950),b=c(1296),_=c(428),w=c(4269),S=c(5114),C=c(8934),T=c(3230),k=c(9312),A=c(4725),M=c(6731),R=c(8055),P=c(8969),L=c(8460),z=c(844),Q=c(6114),W=c(8437),V=c(2584),N=c(7399),O=c(5941),H=c(9074),G=c(2585),ee=c(5435),ie=c(4567),ve=typeof window<"u"?window.document:null;class le extends P.CoreTerminal{get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}constructor(I={}){super(I),this.browser=Q,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this.register(new z.MutableDisposable),this._onCursorMove=this.register(new L.EventEmitter),this.onCursorMove=this._onCursorMove.event,this._onKey=this.register(new L.EventEmitter),this.onKey=this._onKey.event,this._onRender=this.register(new L.EventEmitter),this.onRender=this._onRender.event,this._onSelectionChange=this.register(new L.EventEmitter),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this.register(new L.EventEmitter),this.onTitleChange=this._onTitleChange.event,this._onBell=this.register(new L.EventEmitter),this.onBell=this._onBell.event,this._onFocus=this.register(new L.EventEmitter),this._onBlur=this.register(new L.EventEmitter),this._onA11yCharEmitter=this.register(new L.EventEmitter),this._onA11yTabEmitter=this.register(new L.EventEmitter),this._onWillOpen=this.register(new L.EventEmitter),this._setup(),this.linkifier2=this.register(this._instantiationService.createInstance(h.Linkifier2)),this.linkifier2.registerLinkProvider(this._instantiationService.createInstance(p.OscLinkProvider)),this._decorationService=this._instantiationService.createInstance(H.DecorationService),this._instantiationService.setService(G.IDecorationService,this._decorationService),this.register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this.register(this._inputHandler.onRequestRefreshRows((K,X)=>this.refresh(K,X))),this.register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this.register(this._inputHandler.onRequestReset(()=>this.reset())),this.register(this._inputHandler.onRequestWindowsOptionsReport(K=>this._reportWindowsOptions(K))),this.register(this._inputHandler.onColor(K=>this._handleColorEvent(K))),this.register((0,L.forwardEvent)(this._inputHandler.onCursorMove,this._onCursorMove)),this.register((0,L.forwardEvent)(this._inputHandler.onTitleChange,this._onTitleChange)),this.register((0,L.forwardEvent)(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this.register((0,L.forwardEvent)(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this.register(this._bufferService.onResize(K=>this._afterResize(K.cols,K.rows))),this.register((0,z.toDisposable)(()=>{var K,X;this._customKeyEventHandler=void 0,(X=(K=this.element)===null||K===void 0?void 0:K.parentNode)===null||X===void 0||X.removeChild(this.element)}))}_handleColorEvent(I){if(this._themeService)for(const K of I){let X,J="";switch(K.index){case 256:X="foreground",J="10";break;case 257:X="background",J="11";break;case 258:X="cursor",J="12";break;default:X="ansi",J="4;"+K.index}switch(K.type){case 0:const he=R.color.toColorRGB(X==="ansi"?this._themeService.colors.ansi[K.index]:this._themeService.colors[X]);this.coreService.triggerDataEvent(`${V.C0.ESC}]${J};${(0,O.toRgbString)(he)}${V.C1_ESCAPED.ST}`);break;case 1:if(X==="ansi")this._themeService.modifyColors(be=>be.ansi[K.index]=R.rgba.toColor(...K.color));else{const be=X;this._themeService.modifyColors(Re=>Re[be]=R.rgba.toColor(...K.color))}break;case 2:this._themeService.restoreColor(K.index)}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(I){I?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(ie.AccessibilityManager,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(I){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(V.C0.ESC+"[I"),this.updateCursorStyle(I),this.element.classList.add("focus"),this._showCursor(),this._onFocus.fire()}blur(){var I;return(I=this.textarea)===null||I===void 0?void 0:I.blur()}_handleTextAreaBlur(){this.textarea.value="",this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(V.C0.ESC+"[O"),this.element.classList.remove("focus"),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;const I=this.buffer.ybase+this.buffer.y,K=this.buffer.lines.get(I);if(!K)return;const X=Math.min(this.buffer.x,this.cols-1),J=this._renderService.dimensions.css.cell.height,he=K.getWidth(X),be=this._renderService.dimensions.css.cell.width*he,Re=this.buffer.y*this._renderService.dimensions.css.cell.height,rt=X*this._renderService.dimensions.css.cell.width;this.textarea.style.left=rt+"px",this.textarea.style.top=Re+"px",this.textarea.style.width=be+"px",this.textarea.style.height=J+"px",this.textarea.style.lineHeight=J+"px",this.textarea.style.zIndex="-5"}_initGlobal(){this._bindKeys(),this.register((0,u.addDisposableDomListener)(this.element,"copy",K=>{this.hasSelection()&&(0,l.copyHandler)(K,this._selectionService)}));const I=K=>(0,l.handlePasteEvent)(K,this.textarea,this.coreService,this.optionsService);this.register((0,u.addDisposableDomListener)(this.textarea,"paste",I)),this.register((0,u.addDisposableDomListener)(this.element,"paste",I)),Q.isFirefox?this.register((0,u.addDisposableDomListener)(this.element,"mousedown",K=>{K.button===2&&(0,l.rightClickHandler)(K,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this.register((0,u.addDisposableDomListener)(this.element,"contextmenu",K=>{(0,l.rightClickHandler)(K,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),Q.isLinux&&this.register((0,u.addDisposableDomListener)(this.element,"auxclick",K=>{K.button===1&&(0,l.moveTextAreaUnderMouseCursor)(K,this.textarea,this.screenElement)}))}_bindKeys(){this.register((0,u.addDisposableDomListener)(this.textarea,"keyup",I=>this._keyUp(I),!0)),this.register((0,u.addDisposableDomListener)(this.textarea,"keydown",I=>this._keyDown(I),!0)),this.register((0,u.addDisposableDomListener)(this.textarea,"keypress",I=>this._keyPress(I),!0)),this.register((0,u.addDisposableDomListener)(this.textarea,"compositionstart",()=>this._compositionHelper.compositionstart())),this.register((0,u.addDisposableDomListener)(this.textarea,"compositionupdate",I=>this._compositionHelper.compositionupdate(I))),this.register((0,u.addDisposableDomListener)(this.textarea,"compositionend",()=>this._compositionHelper.compositionend())),this.register((0,u.addDisposableDomListener)(this.textarea,"input",I=>this._inputEvent(I),!0)),this.register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(I){var K;if(!I)throw new Error("Terminal requires a parent element.");I.isConnected||this._logService.debug("Terminal.open was called on an element that was not attached to the DOM"),this._document=I.ownerDocument,this.element=this._document.createElement("div"),this.element.dir="ltr",this.element.classList.add("terminal"),this.element.classList.add("xterm"),I.appendChild(this.element);const X=ve.createDocumentFragment();this._viewportElement=ve.createElement("div"),this._viewportElement.classList.add("xterm-viewport"),X.appendChild(this._viewportElement),this._viewportScrollArea=ve.createElement("div"),this._viewportScrollArea.classList.add("xterm-scroll-area"),this._viewportElement.appendChild(this._viewportScrollArea),this.screenElement=ve.createElement("div"),this.screenElement.classList.add("xterm-screen"),this._helperContainer=ve.createElement("div"),this._helperContainer.classList.add("xterm-helpers"),this.screenElement.appendChild(this._helperContainer),X.appendChild(this.screenElement),this.textarea=ve.createElement("textarea"),this.textarea.classList.add("xterm-helper-textarea"),this.textarea.setAttribute("aria-label",d.promptLabel),Q.isChromeOS||this.textarea.setAttribute("aria-multiline","false"),this.textarea.setAttribute("autocorrect","off"),this.textarea.setAttribute("autocapitalize","off"),this.textarea.setAttribute("spellcheck","false"),this.textarea.tabIndex=0,this._coreBrowserService=this._instantiationService.createInstance(S.CoreBrowserService,this.textarea,(K=this._document.defaultView)!==null&&K!==void 0?K:window),this._instantiationService.setService(A.ICoreBrowserService,this._coreBrowserService),this.register((0,u.addDisposableDomListener)(this.textarea,"focus",J=>this._handleTextAreaFocus(J))),this.register((0,u.addDisposableDomListener)(this.textarea,"blur",()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(_.CharSizeService,this._document,this._helperContainer),this._instantiationService.setService(A.ICharSizeService,this._charSizeService),this._themeService=this._instantiationService.createInstance(M.ThemeService),this._instantiationService.setService(A.IThemeService,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(w.CharacterJoinerService),this._instantiationService.setService(A.ICharacterJoinerService,this._characterJoinerService),this._renderService=this.register(this._instantiationService.createInstance(T.RenderService,this.rows,this.screenElement)),this._instantiationService.setService(A.IRenderService,this._renderService),this.register(this._renderService.onRenderedViewportChange(J=>this._onRender.fire(J))),this.onResize(J=>this._renderService.resize(J.cols,J.rows)),this._compositionView=ve.createElement("div"),this._compositionView.classList.add("composition-view"),this._compositionHelper=this._instantiationService.createInstance(y.CompositionHelper,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this.element.appendChild(X);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this._mouseService=this._instantiationService.createInstance(C.MouseService),this._instantiationService.setService(A.IMouseService,this._mouseService),this.viewport=this._instantiationService.createInstance(m.Viewport,this._viewportElement,this._viewportScrollArea),this.viewport.onRequestScrollLines(J=>this.scrollLines(J.amount,J.suppressScrollEvent,1)),this.register(this._inputHandler.onRequestSyncScrollBar(()=>this.viewport.syncScrollArea())),this.register(this.viewport),this.register(this.onCursorMove(()=>{this._renderService.handleCursorMove(),this._syncTextArea()})),this.register(this.onResize(()=>this._renderService.handleResize(this.cols,this.rows))),this.register(this.onBlur(()=>this._renderService.handleBlur())),this.register(this.onFocus(()=>this._renderService.handleFocus())),this.register(this._renderService.onDimensionsChange(()=>this.viewport.syncScrollArea())),this._selectionService=this.register(this._instantiationService.createInstance(k.SelectionService,this.element,this.screenElement,this.linkifier2)),this._instantiationService.setService(A.ISelectionService,this._selectionService),this.register(this._selectionService.onRequestScrollLines(J=>this.scrollLines(J.amount,J.suppressScrollEvent))),this.register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this.register(this._selectionService.onRequestRedraw(J=>this._renderService.handleSelectionChanged(J.start,J.end,J.columnSelectMode))),this.register(this._selectionService.onLinuxMouseSelection(J=>{this.textarea.value=J,this.textarea.focus(),this.textarea.select()})),this.register(this._onScroll.event(J=>{this.viewport.syncScrollArea(),this._selectionService.refresh()})),this.register((0,u.addDisposableDomListener)(this._viewportElement,"scroll",()=>this._selectionService.refresh())),this.linkifier2.attachToDom(this.screenElement,this._mouseService,this._renderService),this.register(this._instantiationService.createInstance(v.BufferDecorationRenderer,this.screenElement)),this.register((0,u.addDisposableDomListener)(this.element,"mousedown",J=>this._selectionService.handleMouseDown(J))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add("enable-mouse-events")):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(ie.AccessibilityManager,this)),this.register(this.optionsService.onSpecificOptionChange("screenReaderMode",J=>this._handleScreenReaderModeOptionChange(J))),this.options.overviewRulerWidth&&(this._overviewRulerRenderer=this.register(this._instantiationService.createInstance(g.OverviewRulerRenderer,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRulerWidth",J=>{!this._overviewRulerRenderer&&J&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this.register(this._instantiationService.createInstance(g.OverviewRulerRenderer,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(b.DomRenderer,this.element,this.screenElement,this._viewportElement,this.linkifier2)}bindMouse(){const I=this,K=this.element;function X(be){const Re=I._mouseService.getMouseReportCoords(be,I.screenElement);if(!Re)return!1;let rt,st;switch(be.overrideType||be.type){case"mousemove":st=32,be.buttons===void 0?(rt=3,be.button!==void 0&&(rt=be.button<3?be.button:3)):rt=1&be.buttons?0:4&be.buttons?1:2&be.buttons?2:3;break;case"mouseup":st=0,rt=be.button<3?be.button:3;break;case"mousedown":st=1,rt=be.button<3?be.button:3;break;case"wheel":if(I.viewport.getLinesScrolled(be)===0)return!1;st=be.deltaY<0?0:1,rt=4;break;default:return!1}return!(st===void 0||rt===void 0||rt>4)&&I.coreMouseService.triggerMouseEvent({col:Re.col,row:Re.row,x:Re.x,y:Re.y,button:rt,action:st,ctrl:be.ctrlKey,alt:be.altKey,shift:be.shiftKey})}const J={mouseup:null,wheel:null,mousedrag:null,mousemove:null},he={mouseup:be=>(X(be),be.buttons||(this._document.removeEventListener("mouseup",J.mouseup),J.mousedrag&&this._document.removeEventListener("mousemove",J.mousedrag)),this.cancel(be)),wheel:be=>(X(be),this.cancel(be,!0)),mousedrag:be=>{be.buttons&&X(be)},mousemove:be=>{be.buttons||X(be)}};this.register(this.coreMouseService.onProtocolChange(be=>{be?(this.optionsService.rawOptions.logLevel==="debug"&&this._logService.debug("Binding to mouse events:",this.coreMouseService.explainEvents(be)),this.element.classList.add("enable-mouse-events"),this._selectionService.disable()):(this._logService.debug("Unbinding from mouse events."),this.element.classList.remove("enable-mouse-events"),this._selectionService.enable()),8&be?J.mousemove||(K.addEventListener("mousemove",he.mousemove),J.mousemove=he.mousemove):(K.removeEventListener("mousemove",J.mousemove),J.mousemove=null),16&be?J.wheel||(K.addEventListener("wheel",he.wheel,{passive:!1}),J.wheel=he.wheel):(K.removeEventListener("wheel",J.wheel),J.wheel=null),2&be?J.mouseup||(K.addEventListener("mouseup",he.mouseup),J.mouseup=he.mouseup):(this._document.removeEventListener("mouseup",J.mouseup),K.removeEventListener("mouseup",J.mouseup),J.mouseup=null),4&be?J.mousedrag||(J.mousedrag=he.mousedrag):(this._document.removeEventListener("mousemove",J.mousedrag),J.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this.register((0,u.addDisposableDomListener)(K,"mousedown",be=>{if(be.preventDefault(),this.focus(),this.coreMouseService.areMouseEventsActive&&!this._selectionService.shouldForceSelection(be))return X(be),J.mouseup&&this._document.addEventListener("mouseup",J.mouseup),J.mousedrag&&this._document.addEventListener("mousemove",J.mousedrag),this.cancel(be)})),this.register((0,u.addDisposableDomListener)(K,"wheel",be=>{if(!J.wheel){if(!this.buffer.hasScrollback){const Re=this.viewport.getLinesScrolled(be);if(Re===0)return;const rt=V.C0.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?"O":"[")+(be.deltaY<0?"A":"B");let st="";for(let et=0;et<Math.abs(Re);et++)st+=rt;return this.coreService.triggerDataEvent(st,!0),this.cancel(be,!0)}return this.viewport.handleWheel(be)?this.cancel(be):void 0}},{passive:!1})),this.register((0,u.addDisposableDomListener)(K,"touchstart",be=>{if(!this.coreMouseService.areMouseEventsActive)return this.viewport.handleTouchStart(be),this.cancel(be)},{passive:!0})),this.register((0,u.addDisposableDomListener)(K,"touchmove",be=>{if(!this.coreMouseService.areMouseEventsActive)return this.viewport.handleTouchMove(be)?void 0:this.cancel(be)},{passive:!1}))}refresh(I,K){var X;(X=this._renderService)===null||X===void 0||X.refreshRows(I,K)}updateCursorStyle(I){var K;!((K=this._selectionService)===null||K===void 0)&&K.shouldColumnSelect(I)?this.element.classList.add("column-select"):this.element.classList.remove("column-select")}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(I,K,X=0){var J;X===1?(super.scrollLines(I,K,X),this.refresh(0,this.rows-1)):(J=this.viewport)===null||J===void 0||J.scrollLines(I)}paste(I){(0,l.paste)(I,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(I){this._customKeyEventHandler=I}registerLinkProvider(I){return this.linkifier2.registerLinkProvider(I)}registerCharacterJoiner(I){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");const K=this._characterJoinerService.register(I);return this.refresh(0,this.rows-1),K}deregisterCharacterJoiner(I){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");this._characterJoinerService.deregister(I)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(I){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+I)}registerDecoration(I){return this._decorationService.registerDecoration(I)}hasSelection(){return!!this._selectionService&&this._selectionService.hasSelection}select(I,K,X){this._selectionService.setSelection(I,K,X)}getSelection(){return this._selectionService?this._selectionService.selectionText:""}getSelectionPosition(){if(this._selectionService&&this._selectionService.hasSelection)return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){var I;(I=this._selectionService)===null||I===void 0||I.clearSelection()}selectAll(){var I;(I=this._selectionService)===null||I===void 0||I.selectAll()}selectLines(I,K){var X;(X=this._selectionService)===null||X===void 0||X.selectLines(I,K)}_keyDown(I){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&this._customKeyEventHandler(I)===!1)return!1;const K=this.browser.isMac&&this.options.macOptionIsMeta&&I.altKey;if(!K&&!this._compositionHelper.keydown(I))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(),!1;K||I.key!=="Dead"&&I.key!=="AltGraph"||(this._unprocessedDeadKey=!0);const X=(0,N.evaluateKeyboardEvent)(I,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(I),X.type===3||X.type===2){const J=this.rows-1;return this.scrollLines(X.type===2?-J:J),this.cancel(I,!0)}return X.type===1&&this.selectAll(),!!this._isThirdLevelShift(this.browser,I)||(X.cancel&&this.cancel(I,!0),!X.key||!!(I.key&&!I.ctrlKey&&!I.altKey&&!I.metaKey&&I.key.length===1&&I.key.charCodeAt(0)>=65&&I.key.charCodeAt(0)<=90)||(this._unprocessedDeadKey?(this._unprocessedDeadKey=!1,!0):(X.key!==V.C0.ETX&&X.key!==V.C0.CR||(this.textarea.value=""),this._onKey.fire({key:X.key,domEvent:I}),this._showCursor(),this.coreService.triggerDataEvent(X.key,!0),!this.optionsService.rawOptions.screenReaderMode||I.altKey||I.ctrlKey?this.cancel(I,!0):void(this._keyDownHandled=!0))))}_isThirdLevelShift(I,K){const X=I.isMac&&!this.options.macOptionIsMeta&&K.altKey&&!K.ctrlKey&&!K.metaKey||I.isWindows&&K.altKey&&K.ctrlKey&&!K.metaKey||I.isWindows&&K.getModifierState("AltGraph");return K.type==="keypress"?X:X&&(!K.keyCode||K.keyCode>47)}_keyUp(I){this._keyDownSeen=!1,this._customKeyEventHandler&&this._customKeyEventHandler(I)===!1||(function(K){return K.keyCode===16||K.keyCode===17||K.keyCode===18}(I)||this.focus(),this.updateCursorStyle(I),this._keyPressHandled=!1)}_keyPress(I){let K;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&this._customKeyEventHandler(I)===!1)return!1;if(this.cancel(I),I.charCode)K=I.charCode;else if(I.which===null||I.which===void 0)K=I.keyCode;else{if(I.which===0||I.charCode===0)return!1;K=I.which}return!(!K||(I.altKey||I.ctrlKey||I.metaKey)&&!this._isThirdLevelShift(this.browser,I)||(K=String.fromCharCode(K),this._onKey.fire({key:K,domEvent:I}),this._showCursor(),this.coreService.triggerDataEvent(K,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,0))}_inputEvent(I){if(I.data&&I.inputType==="insertText"&&(!I.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;const K=I.data;return this.coreService.triggerDataEvent(K,!0),this.cancel(I),!0}return!1}resize(I,K){I!==this.cols||K!==this.rows?super.resize(I,K):this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure()}_afterResize(I,K){var X,J;(X=this._charSizeService)===null||X===void 0||X.measure(),(J=this.viewport)===null||J===void 0||J.syncScrollArea(!0)}clear(){var I;if(this.buffer.ybase!==0||this.buffer.y!==0){this.buffer.clearAllMarkers(),this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let K=1;K<this.rows;K++)this.buffer.lines.push(this.buffer.getBlankLine(W.DEFAULT_ATTR_DATA));this._onScroll.fire({position:this.buffer.ydisp,source:0}),(I=this.viewport)===null||I===void 0||I.reset(),this.refresh(0,this.rows-1)}}reset(){var I,K;this.options.rows=this.rows,this.options.cols=this.cols;const X=this._customKeyEventHandler;this._setup(),super.reset(),(I=this._selectionService)===null||I===void 0||I.reset(),this._decorationService.reset(),(K=this.viewport)===null||K===void 0||K.reset(),this._customKeyEventHandler=X,this.refresh(0,this.rows-1)}clearTextureAtlas(){var I;(I=this._renderService)===null||I===void 0||I.clearTextureAtlas()}_reportFocus(){var I;!((I=this.element)===null||I===void 0)&&I.classList.contains("focus")?this.coreService.triggerDataEvent(V.C0.ESC+"[I"):this.coreService.triggerDataEvent(V.C0.ESC+"[O")}_reportWindowsOptions(I){if(this._renderService)switch(I){case ee.WindowsOptionsReportType.GET_WIN_SIZE_PIXELS:const K=this._renderService.dimensions.css.canvas.width.toFixed(0),X=this._renderService.dimensions.css.canvas.height.toFixed(0);this.coreService.triggerDataEvent(`${V.C0.ESC}[4;${X};${K}t`);break;case ee.WindowsOptionsReportType.GET_CELL_SIZE_PIXELS:const J=this._renderService.dimensions.css.cell.width.toFixed(0),he=this._renderService.dimensions.css.cell.height.toFixed(0);this.coreService.triggerDataEvent(`${V.C0.ESC}[6;${he};${J}t`)}}cancel(I,K){if(this.options.cancelEvents||K)return I.preventDefault(),I.stopPropagation(),!1}}a.Terminal=le},9924:(o,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.TimeBasedDebouncer=void 0,a.TimeBasedDebouncer=class{constructor(c,l=1e3){this._renderCallback=c,this._debounceThresholdMS=l,this._lastRefreshMs=0,this._additionalRefreshRequested=!1}dispose(){this._refreshTimeoutID&&clearTimeout(this._refreshTimeoutID)}refresh(c,l,u){this._rowCount=u,c=c!==void 0?c:0,l=l!==void 0?l:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,c):c,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,l):l;const h=Date.now();if(h-this._lastRefreshMs>=this._debounceThresholdMS)this._lastRefreshMs=h,this._innerRefresh();else if(!this._additionalRefreshRequested){const d=h-this._lastRefreshMs,p=this._debounceThresholdMS-d;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=Date.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},p)}}_innerRefresh(){if(this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return;const c=Math.max(this._rowStart,0),l=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(c,l)}}},1680:function(o,a,c){var l=this&&this.__decorate||function(y,b,_,w){var S,C=arguments.length,T=C<3?b:w===null?w=Object.getOwnPropertyDescriptor(b,_):w;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")T=Reflect.decorate(y,b,_,w);else for(var k=y.length-1;k>=0;k--)(S=y[k])&&(T=(C<3?S(T):C>3?S(b,_,T):S(b,_))||T);return C>3&&T&&Object.defineProperty(b,_,T),T},u=this&&this.__param||function(y,b){return function(_,w){b(_,w,y)}};Object.defineProperty(a,"__esModule",{value:!0}),a.Viewport=void 0;const h=c(3656),d=c(4725),p=c(8460),m=c(844),v=c(2585);let g=a.Viewport=class extends m.Disposable{constructor(y,b,_,w,S,C,T,k){super(),this._viewportElement=y,this._scrollArea=b,this._bufferService=_,this._optionsService=w,this._charSizeService=S,this._renderService=C,this._coreBrowserService=T,this.scrollBarWidth=0,this._currentRowHeight=0,this._currentDeviceCellHeight=0,this._lastRecordedBufferLength=0,this._lastRecordedViewportHeight=0,this._lastRecordedBufferHeight=0,this._lastTouchY=0,this._lastScrollTop=0,this._wheelPartialScroll=0,this._refreshAnimationFrame=null,this._ignoreNextScrollEvent=!1,this._smoothScrollState={startTime:0,origin:-1,target:-1},this._onRequestScrollLines=this.register(new p.EventEmitter),this.onRequestScrollLines=this._onRequestScrollLines.event,this.scrollBarWidth=this._viewportElement.offsetWidth-this._scrollArea.offsetWidth||15,this.register((0,h.addDisposableDomListener)(this._viewportElement,"scroll",this._handleScroll.bind(this))),this._activeBuffer=this._bufferService.buffer,this.register(this._bufferService.buffers.onBufferActivate(A=>this._activeBuffer=A.activeBuffer)),this._renderDimensions=this._renderService.dimensions,this.register(this._renderService.onDimensionsChange(A=>this._renderDimensions=A)),this._handleThemeChange(k.colors),this.register(k.onChangeColors(A=>this._handleThemeChange(A))),this.register(this._optionsService.onSpecificOptionChange("scrollback",()=>this.syncScrollArea())),setTimeout(()=>this.syncScrollArea())}_handleThemeChange(y){this._viewportElement.style.backgroundColor=y.background.css}reset(){this._currentRowHeight=0,this._currentDeviceCellHeight=0,this._lastRecordedBufferLength=0,this._lastRecordedViewportHeight=0,this._lastRecordedBufferHeight=0,this._lastTouchY=0,this._lastScrollTop=0,this._coreBrowserService.window.requestAnimationFrame(()=>this.syncScrollArea())}_refresh(y){if(y)return this._innerRefresh(),void(this._refreshAnimationFrame!==null&&this._coreBrowserService.window.cancelAnimationFrame(this._refreshAnimationFrame));this._refreshAnimationFrame===null&&(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()))}_innerRefresh(){if(this._charSizeService.height>0){this._currentRowHeight=this._renderService.dimensions.device.cell.height/this._coreBrowserService.dpr,this._currentDeviceCellHeight=this._renderService.dimensions.device.cell.height,this._lastRecordedViewportHeight=this._viewportElement.offsetHeight;const b=Math.round(this._currentRowHeight*this._lastRecordedBufferLength)+(this._lastRecordedViewportHeight-this._renderService.dimensions.css.canvas.height);this._lastRecordedBufferHeight!==b&&(this._lastRecordedBufferHeight=b,this._scrollArea.style.height=this._lastRecordedBufferHeight+"px")}const y=this._bufferService.buffer.ydisp*this._currentRowHeight;this._viewportElement.scrollTop!==y&&(this._ignoreNextScrollEvent=!0,this._viewportElement.scrollTop=y),this._refreshAnimationFrame=null}syncScrollArea(y=!1){if(this._lastRecordedBufferLength!==this._bufferService.buffer.lines.length)return this._lastRecordedBufferLength=this._bufferService.buffer.lines.length,void this._refresh(y);this._lastRecordedViewportHeight===this._renderService.dimensions.css.canvas.height&&this._lastScrollTop===this._activeBuffer.ydisp*this._currentRowHeight&&this._renderDimensions.device.cell.height===this._currentDeviceCellHeight||this._refresh(y)}_handleScroll(y){if(this._lastScrollTop=this._viewportElement.scrollTop,!this._viewportElement.offsetParent)return;if(this._ignoreNextScrollEvent)return this._ignoreNextScrollEvent=!1,void this._onRequestScrollLines.fire({amount:0,suppressScrollEvent:!0});const b=Math.round(this._lastScrollTop/this._currentRowHeight)-this._bufferService.buffer.ydisp;this._onRequestScrollLines.fire({amount:b,suppressScrollEvent:!0})}_smoothScroll(){if(this._isDisposed||this._smoothScrollState.origin===-1||this._smoothScrollState.target===-1)return;const y=this._smoothScrollPercent();this._viewportElement.scrollTop=this._smoothScrollState.origin+Math.round(y*(this._smoothScrollState.target-this._smoothScrollState.origin)),y<1?this._coreBrowserService.window.requestAnimationFrame(()=>this._smoothScroll()):this._clearSmoothScrollState()}_smoothScrollPercent(){return this._optionsService.rawOptions.smoothScrollDuration&&this._smoothScrollState.startTime?Math.max(Math.min((Date.now()-this._smoothScrollState.startTime)/this._optionsService.rawOptions.smoothScrollDuration,1),0):1}_clearSmoothScrollState(){this._smoothScrollState.startTime=0,this._smoothScrollState.origin=-1,this._smoothScrollState.target=-1}_bubbleScroll(y,b){const _=this._viewportElement.scrollTop+this._lastRecordedViewportHeight;return!(b<0&&this._viewportElement.scrollTop!==0||b>0&&_<this._lastRecordedBufferHeight)||(y.cancelable&&y.preventDefault(),!1)}handleWheel(y){const b=this._getPixelsScrolled(y);return b!==0&&(this._optionsService.rawOptions.smoothScrollDuration?(this._smoothScrollState.startTime=Date.now(),this._smoothScrollPercent()<1?(this._smoothScrollState.origin=this._viewportElement.scrollTop,this._smoothScrollState.target===-1?this._smoothScrollState.target=this._viewportElement.scrollTop+b:this._smoothScrollState.target+=b,this._smoothScrollState.target=Math.max(Math.min(this._smoothScrollState.target,this._viewportElement.scrollHeight),0),this._smoothScroll()):this._clearSmoothScrollState()):this._viewportElement.scrollTop+=b,this._bubbleScroll(y,b))}scrollLines(y){if(y!==0)if(this._optionsService.rawOptions.smoothScrollDuration){const b=y*this._currentRowHeight;this._smoothScrollState.startTime=Date.now(),this._smoothScrollPercent()<1?(this._smoothScrollState.origin=this._viewportElement.scrollTop,this._smoothScrollState.target=this._smoothScrollState.origin+b,this._smoothScrollState.target=Math.max(Math.min(this._smoothScrollState.target,this._viewportElement.scrollHeight),0),this._smoothScroll()):this._clearSmoothScrollState()}else this._onRequestScrollLines.fire({amount:y,suppressScrollEvent:!1})}_getPixelsScrolled(y){if(y.deltaY===0||y.shiftKey)return 0;let b=this._applyScrollModifier(y.deltaY,y);return y.deltaMode===WheelEvent.DOM_DELTA_LINE?b*=this._currentRowHeight:y.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(b*=this._currentRowHeight*this._bufferService.rows),b}getBufferElements(y,b){var _;let w,S="";const C=[],T=b??this._bufferService.buffer.lines.length,k=this._bufferService.buffer.lines;for(let A=y;A<T;A++){const M=k.get(A);if(!M)continue;const R=(_=k.get(A+1))===null||_===void 0?void 0:_.isWrapped;if(S+=M.translateToString(!R),!R||A===k.length-1){const P=document.createElement("div");P.textContent=S,C.push(P),S.length>0&&(w=P),S=""}}return{bufferElements:C,cursorElement:w}}getLinesScrolled(y){if(y.deltaY===0||y.shiftKey)return 0;let b=this._applyScrollModifier(y.deltaY,y);return y.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(b/=this._currentRowHeight+0,this._wheelPartialScroll+=b,b=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):y.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(b*=this._bufferService.rows),b}_applyScrollModifier(y,b){const _=this._optionsService.rawOptions.fastScrollModifier;return _==="alt"&&b.altKey||_==="ctrl"&&b.ctrlKey||_==="shift"&&b.shiftKey?y*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:y*this._optionsService.rawOptions.scrollSensitivity}handleTouchStart(y){this._lastTouchY=y.touches[0].pageY}handleTouchMove(y){const b=this._lastTouchY-y.touches[0].pageY;return this._lastTouchY=y.touches[0].pageY,b!==0&&(this._viewportElement.scrollTop+=b,this._bubbleScroll(y,b))}};a.Viewport=g=l([u(2,v.IBufferService),u(3,v.IOptionsService),u(4,d.ICharSizeService),u(5,d.IRenderService),u(6,d.ICoreBrowserService),u(7,d.IThemeService)],g)},3107:function(o,a,c){var l=this&&this.__decorate||function(g,y,b,_){var w,S=arguments.length,C=S<3?y:_===null?_=Object.getOwnPropertyDescriptor(y,b):_;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")C=Reflect.decorate(g,y,b,_);else for(var T=g.length-1;T>=0;T--)(w=g[T])&&(C=(S<3?w(C):S>3?w(y,b,C):w(y,b))||C);return S>3&&C&&Object.defineProperty(y,b,C),C},u=this&&this.__param||function(g,y){return function(b,_){y(b,_,g)}};Object.defineProperty(a,"__esModule",{value:!0}),a.BufferDecorationRenderer=void 0;const h=c(3656),d=c(4725),p=c(844),m=c(2585);let v=a.BufferDecorationRenderer=class extends p.Disposable{constructor(g,y,b,_){super(),this._screenElement=g,this._bufferService=y,this._decorationService=b,this._renderService=_,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement("div"),this._container.classList.add("xterm-decoration-container"),this._screenElement.appendChild(this._container),this.register(this._renderService.onRenderedViewportChange(()=>this._doRefreshDecorations())),this.register(this._renderService.onDimensionsChange(()=>{this._dimensionsChanged=!0,this._queueRefresh()})),this.register((0,h.addDisposableDomListener)(window,"resize",()=>this._queueRefresh())),this.register(this._bufferService.buffers.onBufferActivate(()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt})),this.register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh())),this.register(this._decorationService.onDecorationRemoved(w=>this._removeDecoration(w))),this.register((0,p.toDisposable)(()=>{this._container.remove(),this._decorationElements.clear()}))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback(()=>{this._doRefreshDecorations(),this._animationFrame=void 0}))}_doRefreshDecorations(){for(const g of this._decorationService.decorations)this._renderDecoration(g);this._dimensionsChanged=!1}_renderDecoration(g){this._refreshStyle(g),this._dimensionsChanged&&this._refreshXPosition(g)}_createElement(g){var y,b;const _=document.createElement("div");_.classList.add("xterm-decoration"),_.classList.toggle("xterm-decoration-top-layer",((y=g==null?void 0:g.options)===null||y===void 0?void 0:y.layer)==="top"),_.style.width=`${Math.round((g.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,_.style.height=(g.options.height||1)*this._renderService.dimensions.css.cell.height+"px",_.style.top=(g.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height+"px",_.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;const w=(b=g.options.x)!==null&&b!==void 0?b:0;return w&&w>this._bufferService.cols&&(_.style.display="none"),this._refreshXPosition(g,_),_}_refreshStyle(g){const y=g.marker.line-this._bufferService.buffers.active.ydisp;if(y<0||y>=this._bufferService.rows)g.element&&(g.element.style.display="none",g.onRenderEmitter.fire(g.element));else{let b=this._decorationElements.get(g);b||(b=this._createElement(g),g.element=b,this._decorationElements.set(g,b),this._container.appendChild(b),g.onDispose(()=>{this._decorationElements.delete(g),b.remove()})),b.style.top=y*this._renderService.dimensions.css.cell.height+"px",b.style.display=this._altBufferIsActive?"none":"block",g.onRenderEmitter.fire(b)}}_refreshXPosition(g,y=g.element){var b;if(!y)return;const _=(b=g.options.x)!==null&&b!==void 0?b:0;(g.options.anchor||"left")==="right"?y.style.right=_?_*this._renderService.dimensions.css.cell.width+"px":"":y.style.left=_?_*this._renderService.dimensions.css.cell.width+"px":""}_removeDecoration(g){var y;(y=this._decorationElements.get(g))===null||y===void 0||y.remove(),this._decorationElements.delete(g),g.dispose()}};a.BufferDecorationRenderer=v=l([u(1,m.IBufferService),u(2,m.IDecorationService),u(3,d.IRenderService)],v)},5871:(o,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.ColorZoneStore=void 0,a.ColorZoneStore=class{constructor(){this._zones=[],this._zonePool=[],this._zonePoolIndex=0,this._linePadding={full:0,left:0,center:0,right:0}}get zones(){return this._zonePool.length=Math.min(this._zonePool.length,this._zones.length),this._zones}clear(){this._zones.length=0,this._zonePoolIndex=0}addDecoration(c){if(c.options.overviewRulerOptions){for(const l of this._zones)if(l.color===c.options.overviewRulerOptions.color&&l.position===c.options.overviewRulerOptions.position){if(this._lineIntersectsZone(l,c.marker.line))return;if(this._lineAdjacentToZone(l,c.marker.line,c.options.overviewRulerOptions.position))return void this._addLineToZone(l,c.marker.line)}if(this._zonePoolIndex<this._zonePool.length)return this._zonePool[this._zonePoolIndex].color=c.options.overviewRulerOptions.color,this._zonePool[this._zonePoolIndex].position=c.options.overviewRulerOptions.position,this._zonePool[this._zonePoolIndex].startBufferLine=c.marker.line,this._zonePool[this._zonePoolIndex].endBufferLine=c.marker.line,void this._zones.push(this._zonePool[this._zonePoolIndex++]);this._zones.push({color:c.options.overviewRulerOptions.color,position:c.options.overviewRulerOptions.position,startBufferLine:c.marker.line,endBufferLine:c.marker.line}),this._zonePool.push(this._zones[this._zones.length-1]),this._zonePoolIndex++}}setPadding(c){this._linePadding=c}_lineIntersectsZone(c,l){return l>=c.startBufferLine&&l<=c.endBufferLine}_lineAdjacentToZone(c,l,u){return l>=c.startBufferLine-this._linePadding[u||"full"]&&l<=c.endBufferLine+this._linePadding[u||"full"]}_addLineToZone(c,l){c.startBufferLine=Math.min(c.startBufferLine,l),c.endBufferLine=Math.max(c.endBufferLine,l)}}},5744:function(o,a,c){var l=this&&this.__decorate||function(w,S,C,T){var k,A=arguments.length,M=A<3?S:T===null?T=Object.getOwnPropertyDescriptor(S,C):T;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")M=Reflect.decorate(w,S,C,T);else for(var R=w.length-1;R>=0;R--)(k=w[R])&&(M=(A<3?k(M):A>3?k(S,C,M):k(S,C))||M);return A>3&&M&&Object.defineProperty(S,C,M),M},u=this&&this.__param||function(w,S){return function(C,T){S(C,T,w)}};Object.defineProperty(a,"__esModule",{value:!0}),a.OverviewRulerRenderer=void 0;const h=c(5871),d=c(3656),p=c(4725),m=c(844),v=c(2585),g={full:0,left:0,center:0,right:0},y={full:0,left:0,center:0,right:0},b={full:0,left:0,center:0,right:0};let _=a.OverviewRulerRenderer=class extends m.Disposable{get _width(){return this._optionsService.options.overviewRulerWidth||0}constructor(w,S,C,T,k,A,M){var R;super(),this._viewportElement=w,this._screenElement=S,this._bufferService=C,this._decorationService=T,this._renderService=k,this._optionsService=A,this._coreBrowseService=M,this._colorZoneStore=new h.ColorZoneStore,this._shouldUpdateDimensions=!0,this._shouldUpdateAnchor=!0,this._lastKnownBufferLength=0,this._canvas=document.createElement("canvas"),this._canvas.classList.add("xterm-decoration-overview-ruler"),this._refreshCanvasDimensions(),(R=this._viewportElement.parentElement)===null||R===void 0||R.insertBefore(this._canvas,this._viewportElement);const P=this._canvas.getContext("2d");if(!P)throw new Error("Ctx cannot be null");this._ctx=P,this._registerDecorationListeners(),this._registerBufferChangeListeners(),this._registerDimensionChangeListeners(),this.register((0,m.toDisposable)(()=>{var L;(L=this._canvas)===null||L===void 0||L.remove()}))}_registerDecorationListeners(){this.register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh(void 0,!0))),this.register(this._decorationService.onDecorationRemoved(()=>this._queueRefresh(void 0,!0)))}_registerBufferChangeListeners(){this.register(this._renderService.onRenderedViewportChange(()=>this._queueRefresh())),this.register(this._bufferService.buffers.onBufferActivate(()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?"none":"block"})),this.register(this._bufferService.onScroll(()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())}))}_registerDimensionChangeListeners(){this.register(this._renderService.onRender(()=>{this._containerHeight&&this._containerHeight===this._screenElement.clientHeight||(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)})),this.register(this._optionsService.onSpecificOptionChange("overviewRulerWidth",()=>this._queueRefresh(!0))),this.register((0,d.addDisposableDomListener)(this._coreBrowseService.window,"resize",()=>this._queueRefresh(!0))),this._queueRefresh(!0)}_refreshDrawConstants(){const w=Math.floor(this._canvas.width/3),S=Math.ceil(this._canvas.width/3);y.full=this._canvas.width,y.left=w,y.center=S,y.right=w,this._refreshDrawHeightConstants(),b.full=0,b.left=0,b.center=y.left,b.right=y.left+y.center}_refreshDrawHeightConstants(){g.full=Math.round(2*this._coreBrowseService.dpr);const w=this._canvas.height/this._bufferService.buffer.lines.length,S=Math.round(Math.max(Math.min(w,12),6)*this._coreBrowseService.dpr);g.left=S,g.center=S,g.right=S}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*g.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*g.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*g.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*g.right)}),this._lastKnownBufferLength=this._bufferService.buffers.normal.lines.length}_refreshCanvasDimensions(){this._canvas.style.width=`${this._width}px`,this._canvas.width=Math.round(this._width*this._coreBrowseService.dpr),this._canvas.style.height=`${this._screenElement.clientHeight}px`,this._canvas.height=Math.round(this._screenElement.clientHeight*this._coreBrowseService.dpr),this._refreshDrawConstants(),this._refreshColorZonePadding()}_refreshDecorations(){this._shouldUpdateDimensions&&this._refreshCanvasDimensions(),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._colorZoneStore.clear();for(const S of this._decorationService.decorations)this._colorZoneStore.addDecoration(S);this._ctx.lineWidth=1;const w=this._colorZoneStore.zones;for(const S of w)S.position!=="full"&&this._renderColorZone(S);for(const S of w)S.position==="full"&&this._renderColorZone(S);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderColorZone(w){this._ctx.fillStyle=w.color,this._ctx.fillRect(b[w.position||"full"],Math.round((this._canvas.height-1)*(w.startBufferLine/this._bufferService.buffers.active.lines.length)-g[w.position||"full"]/2),y[w.position||"full"],Math.round((this._canvas.height-1)*((w.endBufferLine-w.startBufferLine)/this._bufferService.buffers.active.lines.length)+g[w.position||"full"]))}_queueRefresh(w,S){this._shouldUpdateDimensions=w||this._shouldUpdateDimensions,this._shouldUpdateAnchor=S||this._shouldUpdateAnchor,this._animationFrame===void 0&&(this._animationFrame=this._coreBrowseService.window.requestAnimationFrame(()=>{this._refreshDecorations(),this._animationFrame=void 0}))}};a.OverviewRulerRenderer=_=l([u(2,v.IBufferService),u(3,v.IDecorationService),u(4,p.IRenderService),u(5,v.IOptionsService),u(6,p.ICoreBrowserService)],_)},2950:function(o,a,c){var l=this&&this.__decorate||function(v,g,y,b){var _,w=arguments.length,S=w<3?g:b===null?b=Object.getOwnPropertyDescriptor(g,y):b;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")S=Reflect.decorate(v,g,y,b);else for(var C=v.length-1;C>=0;C--)(_=v[C])&&(S=(w<3?_(S):w>3?_(g,y,S):_(g,y))||S);return w>3&&S&&Object.defineProperty(g,y,S),S},u=this&&this.__param||function(v,g){return function(y,b){g(y,b,v)}};Object.defineProperty(a,"__esModule",{value:!0}),a.CompositionHelper=void 0;const h=c(4725),d=c(2585),p=c(2584);let m=a.CompositionHelper=class{get isComposing(){return this._isComposing}constructor(v,g,y,b,_,w){this._textarea=v,this._compositionView=g,this._bufferService=y,this._optionsService=b,this._coreService=_,this._renderService=w,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=""}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent="",this._dataAlreadySent="",this._compositionView.classList.add("active")}compositionupdate(v){this._compositionView.textContent=v.data,this.updateCompositionElements(),setTimeout(()=>{this._compositionPosition.end=this._textarea.value.length},0)}compositionend(){this._finalizeComposition(!0)}keydown(v){if(this._isComposing||this._isSendingComposition){if(v.keyCode===229||v.keyCode===16||v.keyCode===17||v.keyCode===18)return!1;this._finalizeComposition(!1)}return v.keyCode!==229||(this._handleAnyTextareaChanges(),!1)}_finalizeComposition(v){if(this._compositionView.classList.remove("active"),this._isComposing=!1,v){const g={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){let y;this._isSendingComposition=!1,g.start+=this._dataAlreadySent.length,y=this._isComposing?this._textarea.value.substring(g.start,g.end):this._textarea.value.substring(g.start),y.length>0&&this._coreService.triggerDataEvent(y,!0)}},0)}else{this._isSendingComposition=!1;const g=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(g,!0)}}_handleAnyTextareaChanges(){const v=this._textarea.value;setTimeout(()=>{if(!this._isComposing){const g=this._textarea.value,y=g.replace(v,"");this._dataAlreadySent=y,g.length>v.length?this._coreService.triggerDataEvent(y,!0):g.length<v.length?this._coreService.triggerDataEvent(`${p.C0.DEL}`,!0):g.length===v.length&&g!==v&&this._coreService.triggerDataEvent(g,!0)}},0)}updateCompositionElements(v){if(this._isComposing){if(this._bufferService.buffer.isCursorInViewport){const g=Math.min(this._bufferService.buffer.x,this._bufferService.cols-1),y=this._renderService.dimensions.css.cell.height,b=this._bufferService.buffer.y*this._renderService.dimensions.css.cell.height,_=g*this._renderService.dimensions.css.cell.width;this._compositionView.style.left=_+"px",this._compositionView.style.top=b+"px",this._compositionView.style.height=y+"px",this._compositionView.style.lineHeight=y+"px",this._compositionView.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._compositionView.style.fontSize=this._optionsService.rawOptions.fontSize+"px";const w=this._compositionView.getBoundingClientRect();this._textarea.style.left=_+"px",this._textarea.style.top=b+"px",this._textarea.style.width=Math.max(w.width,1)+"px",this._textarea.style.height=Math.max(w.height,1)+"px",this._textarea.style.lineHeight=w.height+"px"}v||setTimeout(()=>this.updateCompositionElements(!0),0)}}};a.CompositionHelper=m=l([u(2,d.IBufferService),u(3,d.IOptionsService),u(4,d.ICoreService),u(5,h.IRenderService)],m)},9806:(o,a)=>{function c(l,u,h){const d=h.getBoundingClientRect(),p=l.getComputedStyle(h),m=parseInt(p.getPropertyValue("padding-left")),v=parseInt(p.getPropertyValue("padding-top"));return[u.clientX-d.left-m,u.clientY-d.top-v]}Object.defineProperty(a,"__esModule",{value:!0}),a.getCoords=a.getCoordsRelativeToElement=void 0,a.getCoordsRelativeToElement=c,a.getCoords=function(l,u,h,d,p,m,v,g,y){if(!m)return;const b=c(l,u,h);return b?(b[0]=Math.ceil((b[0]+(y?v/2:0))/v),b[1]=Math.ceil(b[1]/g),b[0]=Math.min(Math.max(b[0],1),d+(y?1:0)),b[1]=Math.min(Math.max(b[1],1),p),b):void 0}},9504:(o,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.moveToCellSequence=void 0;const l=c(2584);function u(g,y,b,_){const w=g-h(g,b),S=y-h(y,b),C=Math.abs(w-S)-function(T,k,A){let M=0;const R=T-h(T,A),P=k-h(k,A);for(let L=0;L<Math.abs(R-P);L++){const z=d(T,k)==="A"?-1:1,Q=A.buffer.lines.get(R+z*L);Q!=null&&Q.isWrapped&&M++}return M}(g,y,b);return v(C,m(d(g,y),_))}function h(g,y){let b=0,_=y.buffer.lines.get(g),w=_==null?void 0:_.isWrapped;for(;w&&g>=0&&g<y.rows;)b++,_=y.buffer.lines.get(--g),w=_==null?void 0:_.isWrapped;return b}function d(g,y){return g>y?"A":"B"}function p(g,y,b,_,w,S){let C=g,T=y,k="";for(;C!==b||T!==_;)C+=w?1:-1,w&&C>S.cols-1?(k+=S.buffer.translateBufferLineToString(T,!1,g,C),C=0,g=0,T++):!w&&C<0&&(k+=S.buffer.translateBufferLineToString(T,!1,0,g+1),C=S.cols-1,g=C,T--);return k+S.buffer.translateBufferLineToString(T,!1,g,C)}function m(g,y){const b=y?"O":"[";return l.C0.ESC+b+g}function v(g,y){g=Math.floor(g);let b="";for(let _=0;_<g;_++)b+=y;return b}a.moveToCellSequence=function(g,y,b,_){const w=b.buffer.x,S=b.buffer.y;if(!b.buffer.hasScrollback)return function(k,A,M,R,P,L){return u(A,R,P,L).length===0?"":v(p(k,A,k,A-h(A,P),!1,P).length,m("D",L))}(w,S,0,y,b,_)+u(S,y,b,_)+function(k,A,M,R,P,L){let z;z=u(A,R,P,L).length>0?R-h(R,P):A;const Q=R,W=function(V,N,O,H,G,ee){let ie;return ie=u(O,H,G,ee).length>0?H-h(H,G):N,V<O&&ie<=H||V>=O&&ie<H?"C":"D"}(k,A,M,R,P,L);return v(p(k,z,M,Q,W==="C",P).length,m(W,L))}(w,S,g,y,b,_);let C;if(S===y)return C=w>g?"D":"C",v(Math.abs(w-g),m(C,_));C=S>y?"D":"C";const T=Math.abs(S-y);return v(function(k,A){return A.cols-k}(S>y?g:w,b)+(T-1)*b.cols+1+((S>y?w:g)-1),m(C,_))}},1296:function(o,a,c){var l=this&&this.__decorate||function(P,L,z,Q){var W,V=arguments.length,N=V<3?L:Q===null?Q=Object.getOwnPropertyDescriptor(L,z):Q;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")N=Reflect.decorate(P,L,z,Q);else for(var O=P.length-1;O>=0;O--)(W=P[O])&&(N=(V<3?W(N):V>3?W(L,z,N):W(L,z))||N);return V>3&&N&&Object.defineProperty(L,z,N),N},u=this&&this.__param||function(P,L){return function(z,Q){L(z,Q,P)}};Object.defineProperty(a,"__esModule",{value:!0}),a.DomRenderer=void 0;const h=c(3787),d=c(2550),p=c(2223),m=c(6171),v=c(4725),g=c(8055),y=c(8460),b=c(844),_=c(2585),w="xterm-dom-renderer-owner-",S="xterm-rows",C="xterm-fg-",T="xterm-bg-",k="xterm-focus",A="xterm-selection";let M=1,R=a.DomRenderer=class extends b.Disposable{constructor(P,L,z,Q,W,V,N,O,H,G){super(),this._element=P,this._screenElement=L,this._viewportElement=z,this._linkifier2=Q,this._charSizeService=V,this._optionsService=N,this._bufferService=O,this._coreBrowserService=H,this._themeService=G,this._terminalClass=M++,this._rowElements=[],this.onRequestRedraw=this.register(new y.EventEmitter).event,this._rowContainer=document.createElement("div"),this._rowContainer.classList.add(S),this._rowContainer.style.lineHeight="normal",this._rowContainer.setAttribute("aria-hidden","true"),this._refreshRowElements(this._bufferService.cols,this._bufferService.rows),this._selectionContainer=document.createElement("div"),this._selectionContainer.classList.add(A),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions=(0,m.createRenderDimensions)(),this._updateDimensions(),this.register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this.register(this._themeService.onChangeColors(ee=>this._injectCss(ee))),this._injectCss(this._themeService.colors),this._rowFactory=W.createInstance(h.DomRendererRowFactory,document),this._element.classList.add(w+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this.register(this._linkifier2.onShowLinkUnderline(ee=>this._handleLinkHover(ee))),this.register(this._linkifier2.onHideLinkUnderline(ee=>this._handleLinkLeave(ee))),this.register((0,b.toDisposable)(()=>{this._element.classList.remove(w+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new d.WidthCache(document),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}_updateDimensions(){const P=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*P,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*P),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.left=0,this.dimensions.device.char.top=0,this.dimensions.device.canvas.width=this.dimensions.device.cell.width*this._bufferService.cols,this.dimensions.device.canvas.height=this.dimensions.device.cell.height*this._bufferService.rows,this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/P),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/P),this.dimensions.css.cell.width=this.dimensions.css.canvas.width/this._bufferService.cols,this.dimensions.css.cell.height=this.dimensions.css.canvas.height/this._bufferService.rows;for(const z of this._rowElements)z.style.width=`${this.dimensions.css.canvas.width}px`,z.style.height=`${this.dimensions.css.cell.height}px`,z.style.lineHeight=`${this.dimensions.css.cell.height}px`,z.style.overflow="hidden";this._dimensionsStyleElement||(this._dimensionsStyleElement=document.createElement("style"),this._screenElement.appendChild(this._dimensionsStyleElement));const L=`${this._terminalSelector} .${S} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=L,this._selectionContainer.style.height=this._viewportElement.style.height,this._screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._screenElement.style.height=`${this.dimensions.css.canvas.height}px`}_injectCss(P){this._themeStyleElement||(this._themeStyleElement=document.createElement("style"),this._screenElement.appendChild(this._themeStyleElement));let L=`${this._terminalSelector} .${S} { color: ${P.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;L+=`${this._terminalSelector} .${S} .xterm-dim { color: ${g.color.multiplyOpacity(P.foreground,.5).css};}`,L+=`${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`,L+="@keyframes blink_box_shadow_"+this._terminalClass+" { 50% { border-bottom-style: hidden; }}",L+="@keyframes blink_block_"+this._terminalClass+` { 0% { background-color: ${P.cursor.css}; color: ${P.cursorAccent.css}; } 50% { background-color: inherit; color: ${P.cursor.css}; }}`,L+=`${this._terminalSelector} .${S}.${k} .xterm-cursor.xterm-cursor-blink:not(.xterm-cursor-block) { animation: blink_box_shadow_`+this._terminalClass+` 1s step-end infinite;}${this._terminalSelector} .${S}.${k} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: blink_block_`+this._terminalClass+` 1s step-end infinite;}${this._terminalSelector} .${S} .xterm-cursor.xterm-cursor-block { background-color: ${P.cursor.css}; color: ${P.cursorAccent.css};}${this._terminalSelector} .${S} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${P.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${S} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${P.cursor.css} inset;}${this._terminalSelector} .${S} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${P.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,L+=`${this._terminalSelector} .${A} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${A} div { position: absolute; background-color: ${P.selectionBackgroundOpaque.css};}${this._terminalSelector} .${A} div { position: absolute; background-color: ${P.selectionInactiveBackgroundOpaque.css};}`;for(const[z,Q]of P.ansi.entries())L+=`${this._terminalSelector} .${C}${z} { color: ${Q.css}; }${this._terminalSelector} .${C}${z}.xterm-dim { color: ${g.color.multiplyOpacity(Q,.5).css}; }${this._terminalSelector} .${T}${z} { background-color: ${Q.css}; }`;L+=`${this._terminalSelector} .${C}${p.INVERTED_DEFAULT_COLOR} { color: ${g.color.opaque(P.background).css}; }${this._terminalSelector} .${C}${p.INVERTED_DEFAULT_COLOR}.xterm-dim { color: ${g.color.multiplyOpacity(g.color.opaque(P.background),.5).css}; }${this._terminalSelector} .${T}${p.INVERTED_DEFAULT_COLOR} { background-color: ${P.foreground.css}; }`,this._themeStyleElement.textContent=L}_setDefaultSpacing(){const P=this.dimensions.css.cell.width-this._widthCache.get("W",!1,!1);this._rowContainer.style.letterSpacing=`${P}px`,this._rowFactory.defaultSpacing=P}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(P,L){for(let z=this._rowElements.length;z<=L;z++){const Q=document.createElement("div");this._rowContainer.appendChild(Q),this._rowElements.push(Q)}for(;this._rowElements.length>L;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(P,L){this._refreshRowElements(P,L),this._updateDimensions()}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(k)}handleFocus(){this._rowContainer.classList.add(k),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(P,L,z){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(P,L,z),this.renderRows(0,this._bufferService.rows-1),!P||!L)return;const Q=P[1]-this._bufferService.buffer.ydisp,W=L[1]-this._bufferService.buffer.ydisp,V=Math.max(Q,0),N=Math.min(W,this._bufferService.rows-1);if(V>=this._bufferService.rows||N<0)return;const O=document.createDocumentFragment();if(z){const H=P[0]>L[0];O.appendChild(this._createSelectionElement(V,H?L[0]:P[0],H?P[0]:L[0],N-V+1))}else{const H=Q===V?P[0]:0,G=V===W?L[0]:this._bufferService.cols;O.appendChild(this._createSelectionElement(V,H,G));const ee=N-V-1;if(O.appendChild(this._createSelectionElement(V+1,0,this._bufferService.cols,ee)),V!==N){const ie=W===N?L[0]:this._bufferService.cols;O.appendChild(this._createSelectionElement(N,0,ie))}}this._selectionContainer.appendChild(O)}_createSelectionElement(P,L,z,Q=1){const W=document.createElement("div");return W.style.height=Q*this.dimensions.css.cell.height+"px",W.style.top=P*this.dimensions.css.cell.height+"px",W.style.left=L*this.dimensions.css.cell.width+"px",W.style.width=this.dimensions.css.cell.width*(z-L)+"px",W}handleCursorMove(){}_handleOptionsChanged(){this._updateDimensions(),this._injectCss(this._themeService.colors),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}clear(){for(const P of this._rowElements)P.replaceChildren()}renderRows(P,L){const z=this._bufferService.buffer,Q=z.ybase+z.y,W=Math.min(z.x,this._bufferService.cols-1),V=this._optionsService.rawOptions.cursorBlink,N=this._optionsService.rawOptions.cursorStyle,O=this._optionsService.rawOptions.cursorInactiveStyle;for(let H=P;H<=L;H++){const G=H+z.ydisp,ee=this._rowElements[H],ie=z.lines.get(G);if(!ee||!ie)break;ee.replaceChildren(...this._rowFactory.createRow(ie,G,G===Q,N,O,W,V,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${w}${this._terminalClass}`}_handleLinkHover(P){this._setCellUnderline(P.x1,P.x2,P.y1,P.y2,P.cols,!0)}_handleLinkLeave(P){this._setCellUnderline(P.x1,P.x2,P.y1,P.y2,P.cols,!1)}_setCellUnderline(P,L,z,Q,W,V){z<0&&(P=0),Q<0&&(L=0);const N=this._bufferService.rows-1;z=Math.max(Math.min(z,N),0),Q=Math.max(Math.min(Q,N),0),W=Math.min(W,this._bufferService.cols);const O=this._bufferService.buffer,H=O.ybase+O.y,G=Math.min(O.x,W-1),ee=this._optionsService.rawOptions.cursorBlink,ie=this._optionsService.rawOptions.cursorStyle,ve=this._optionsService.rawOptions.cursorInactiveStyle;for(let le=z;le<=Q;++le){const oe=le+O.ydisp,I=this._rowElements[le],K=O.lines.get(oe);if(!I||!K)break;I.replaceChildren(...this._rowFactory.createRow(K,oe,oe===H,ie,ve,G,ee,this.dimensions.css.cell.width,this._widthCache,V?le===z?P:0:-1,V?(le===Q?L:W)-1:-1))}}};a.DomRenderer=R=l([u(4,_.IInstantiationService),u(5,v.ICharSizeService),u(6,_.IOptionsService),u(7,_.IBufferService),u(8,v.ICoreBrowserService),u(9,v.IThemeService)],R)},3787:function(o,a,c){var l=this&&this.__decorate||function(C,T,k,A){var M,R=arguments.length,P=R<3?T:A===null?A=Object.getOwnPropertyDescriptor(T,k):A;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")P=Reflect.decorate(C,T,k,A);else for(var L=C.length-1;L>=0;L--)(M=C[L])&&(P=(R<3?M(P):R>3?M(T,k,P):M(T,k))||P);return R>3&&P&&Object.defineProperty(T,k,P),P},u=this&&this.__param||function(C,T){return function(k,A){T(k,A,C)}};Object.defineProperty(a,"__esModule",{value:!0}),a.DomRendererRowFactory=void 0;const h=c(2223),d=c(643),p=c(511),m=c(2585),v=c(8055),g=c(4725),y=c(4269),b=c(6171),_=c(3734);let w=a.DomRendererRowFactory=class{constructor(C,T,k,A,M,R,P){this._document=C,this._characterJoinerService=T,this._optionsService=k,this._coreBrowserService=A,this._coreService=M,this._decorationService=R,this._themeService=P,this._workCell=new p.CellData,this._columnSelectMode=!1,this.defaultSpacing=0}handleSelectionChanged(C,T,k){this._selectionStart=C,this._selectionEnd=T,this._columnSelectMode=k}createRow(C,T,k,A,M,R,P,L,z,Q,W){const V=[],N=this._characterJoinerService.getJoinedCharacters(T),O=this._themeService.colors;let H,G=C.getNoBgTrimmedLength();k&&G<R+1&&(G=R+1);let ee=0,ie="",ve=0,le=0,oe=0,I=!1,K=0,X=!1,J=0;const he=[],be=Q!==-1&&W!==-1;for(let Re=0;Re<G;Re++){C.loadCell(Re,this._workCell);let rt=this._workCell.getWidth();if(rt===0)continue;let st=!1,et=Re,De=this._workCell;if(N.length>0&&Re===N[0][0]){st=!0;const ut=N.shift();De=new y.JoinedCellData(this._workCell,C.translateToString(!0,ut[0],ut[1]),ut[1]-ut[0]),et=ut[1]-1,rt=De.getWidth()}const xe=this._isCellInSelection(Re,T),se=k&&Re===R,ce=be&&Re>=Q&&Re<=W;let de=!1;this._decorationService.forEachDecorationAtCell(Re,T,void 0,ut=>{de=!0});let we=De.getChars()||d.WHITESPACE_CELL_CHAR;if(we===" "&&(De.isUnderline()||De.isOverline())&&(we=" "),J=rt*L-z.get(we,De.isBold(),De.isItalic()),H){if(ee&&(xe&&X||!xe&&!X&&De.bg===ve)&&(xe&&X&&O.selectionForeground||De.fg===le)&&De.extended.ext===oe&&ce===I&&J===K&&!se&&!st&&!de){ie+=we,ee++;continue}ee&&(H.textContent=ie),H=this._document.createElement("span"),ee=0,ie=""}else H=this._document.createElement("span");if(ve=De.bg,le=De.fg,oe=De.extended.ext,I=ce,K=J,X=xe,st&&R>=Re&&R<=et&&(R=Re),!this._coreService.isCursorHidden&&se){if(he.push("xterm-cursor"),this._coreBrowserService.isFocused)P&&he.push("xterm-cursor-blink"),he.push(A==="bar"?"xterm-cursor-bar":A==="underline"?"xterm-cursor-underline":"xterm-cursor-block");else if(M)switch(M){case"outline":he.push("xterm-cursor-outline");break;case"block":he.push("xterm-cursor-block");break;case"bar":he.push("xterm-cursor-bar");break;case"underline":he.push("xterm-cursor-underline")}}if(De.isBold()&&he.push("xterm-bold"),De.isItalic()&&he.push("xterm-italic"),De.isDim()&&he.push("xterm-dim"),ie=De.isInvisible()?d.WHITESPACE_CELL_CHAR:De.getChars()||d.WHITESPACE_CELL_CHAR,De.isUnderline()&&(he.push(`xterm-underline-${De.extended.underlineStyle}`),ie===" "&&(ie=" "),!De.isUnderlineColorDefault()))if(De.isUnderlineColorRGB())H.style.textDecorationColor=`rgb(${_.AttributeData.toColorRGB(De.getUnderlineColor()).join(",")})`;else{let ut=De.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&De.isBold()&&ut<8&&(ut+=8),H.style.textDecorationColor=O.ansi[ut].css}De.isOverline()&&(he.push("xterm-overline"),ie===" "&&(ie=" ")),De.isStrikethrough()&&he.push("xterm-strikethrough"),ce&&(H.style.textDecoration="underline");let Le=De.getFgColor(),He=De.getFgColorMode(),yt=De.getBgColor(),At=De.getBgColorMode();const Nt=!!De.isInverse();if(Nt){const ut=Le;Le=yt,yt=ut;const Hs=He;He=At,At=Hs}let It,Jt,$t,As=!1;switch(this._decorationService.forEachDecorationAtCell(Re,T,void 0,ut=>{ut.options.layer!=="top"&&As||(ut.backgroundColorRGB&&(At=50331648,yt=ut.backgroundColorRGB.rgba>>8&16777215,It=ut.backgroundColorRGB),ut.foregroundColorRGB&&(He=50331648,Le=ut.foregroundColorRGB.rgba>>8&16777215,Jt=ut.foregroundColorRGB),As=ut.options.layer==="top")}),!As&&xe&&(It=this._coreBrowserService.isFocused?O.selectionBackgroundOpaque:O.selectionInactiveBackgroundOpaque,yt=It.rgba>>8&16777215,At=50331648,As=!0,O.selectionForeground&&(He=50331648,Le=O.selectionForeground.rgba>>8&16777215,Jt=O.selectionForeground)),As&&he.push("xterm-decoration-top"),At){case 16777216:case 33554432:$t=O.ansi[yt],he.push(`xterm-bg-${yt}`);break;case 50331648:$t=v.rgba.toColor(yt>>16,yt>>8&255,255&yt),this._addStyle(H,`background-color:#${S((yt>>>0).toString(16),"0",6)}`);break;default:Nt?($t=O.foreground,he.push(`xterm-bg-${h.INVERTED_DEFAULT_COLOR}`)):$t=O.background}switch(It||De.isDim()&&(It=v.color.multiplyOpacity($t,.5)),He){case 16777216:case 33554432:De.isBold()&&Le<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(Le+=8),this._applyMinimumContrast(H,$t,O.ansi[Le],De,It,void 0)||he.push(`xterm-fg-${Le}`);break;case 50331648:const ut=v.rgba.toColor(Le>>16&255,Le>>8&255,255&Le);this._applyMinimumContrast(H,$t,ut,De,It,Jt)||this._addStyle(H,`color:#${S(Le.toString(16),"0",6)}`);break;default:this._applyMinimumContrast(H,$t,O.foreground,De,It,void 0)||Nt&&he.push(`xterm-fg-${h.INVERTED_DEFAULT_COLOR}`)}he.length&&(H.className=he.join(" "),he.length=0),se||st||de?H.textContent=ie:ee++,J!==this.defaultSpacing&&(H.style.letterSpacing=`${J}px`),V.push(H),Re=et}return H&&ee&&(H.textContent=ie),V}_applyMinimumContrast(C,T,k,A,M,R){if(this._optionsService.rawOptions.minimumContrastRatio===1||(0,b.excludeFromContrastRatioDemands)(A.getCode()))return!1;const P=this._getContrastCache(A);let L;if(M||R||(L=P.getColor(T.rgba,k.rgba)),L===void 0){const z=this._optionsService.rawOptions.minimumContrastRatio/(A.isDim()?2:1);L=v.color.ensureContrastRatio(M||T,R||k,z),P.setColor((M||T).rgba,(R||k).rgba,L??null)}return!!L&&(this._addStyle(C,`color:${L.css}`),!0)}_getContrastCache(C){return C.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(C,T){C.setAttribute("style",`${C.getAttribute("style")||""}${T};`)}_isCellInSelection(C,T){const k=this._selectionStart,A=this._selectionEnd;return!(!k||!A)&&(this._columnSelectMode?k[0]<=A[0]?C>=k[0]&&T>=k[1]&&C<A[0]&&T<=A[1]:C<k[0]&&T>=k[1]&&C>=A[0]&&T<=A[1]:T>k[1]&&T<A[1]||k[1]===A[1]&&T===k[1]&&C>=k[0]&&C<A[0]||k[1]<A[1]&&T===A[1]&&C<A[0]||k[1]<A[1]&&T===k[1]&&C>=k[0])}};function S(C,T,k){for(;C.length<k;)C=T+C;return C}a.DomRendererRowFactory=w=l([u(1,g.ICharacterJoinerService),u(2,m.IOptionsService),u(3,g.ICoreBrowserService),u(4,m.ICoreService),u(5,m.IDecorationService),u(6,g.IThemeService)],w)},2550:(o,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.WidthCache=void 0,a.WidthCache=class{constructor(c){this._flat=new Float32Array(256),this._font="",this._fontSize=0,this._weight="normal",this._weightBold="bold",this._measureElements=[],this._container=c.createElement("div"),this._container.style.position="absolute",this._container.style.top="-50000px",this._container.style.width="50000px",this._container.style.whiteSpace="pre",this._container.style.fontKerning="none";const l=c.createElement("span"),u=c.createElement("span");u.style.fontWeight="bold";const h=c.createElement("span");h.style.fontStyle="italic";const d=c.createElement("span");d.style.fontWeight="bold",d.style.fontStyle="italic",this._measureElements=[l,u,h,d],this._container.appendChild(l),this._container.appendChild(u),this._container.appendChild(h),this._container.appendChild(d),c.body.appendChild(this._container),this.clear()}dispose(){this._container.remove(),this._measureElements.length=0,this._holey=void 0}clear(){this._flat.fill(-9999),this._holey=new Map}setFont(c,l,u,h){c===this._font&&l===this._fontSize&&u===this._weight&&h===this._weightBold||(this._font=c,this._fontSize=l,this._weight=u,this._weightBold=h,this._container.style.fontFamily=this._font,this._container.style.fontSize=`${this._fontSize}px`,this._measureElements[0].style.fontWeight=`${u}`,this._measureElements[1].style.fontWeight=`${h}`,this._measureElements[2].style.fontWeight=`${u}`,this._measureElements[3].style.fontWeight=`${h}`,this.clear())}get(c,l,u){let h=0;if(!l&&!u&&c.length===1&&(h=c.charCodeAt(0))<256)return this._flat[h]!==-9999?this._flat[h]:this._flat[h]=this._measure(c,0);let d=c;l&&(d+="B"),u&&(d+="I");let p=this._holey.get(d);if(p===void 0){let m=0;l&&(m|=1),u&&(m|=2),p=this._measure(c,m),this._holey.set(d,p)}return p}_measure(c,l){const u=this._measureElements[l];return u.textContent=c.repeat(32),u.offsetWidth/32}}},2223:(o,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.TEXT_BASELINE=a.DIM_OPACITY=a.INVERTED_DEFAULT_COLOR=void 0;const l=c(6114);a.INVERTED_DEFAULT_COLOR=257,a.DIM_OPACITY=.5,a.TEXT_BASELINE=l.isFirefox||l.isLegacyEdge?"bottom":"ideographic"},6171:(o,a)=>{function c(l){return 57508<=l&&l<=57558}Object.defineProperty(a,"__esModule",{value:!0}),a.createRenderDimensions=a.excludeFromContrastRatioDemands=a.isRestrictedPowerlineGlyph=a.isPowerlineGlyph=a.throwIfFalsy=void 0,a.throwIfFalsy=function(l){if(!l)throw new Error("value must not be falsy");return l},a.isPowerlineGlyph=c,a.isRestrictedPowerlineGlyph=function(l){return 57520<=l&&l<=57527},a.excludeFromContrastRatioDemands=function(l){return c(l)||function(u){return 9472<=u&&u<=9631}(l)},a.createRenderDimensions=function(){return{css:{canvas:{width:0,height:0},cell:{width:0,height:0}},device:{canvas:{width:0,height:0},cell:{width:0,height:0},char:{width:0,height:0,left:0,top:0}}}}},456:(o,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.SelectionModel=void 0,a.SelectionModel=class{constructor(c){this._bufferService=c,this.isSelectAllActive=!1,this.selectionStartLength=0}clearSelection(){this.selectionStart=void 0,this.selectionEnd=void 0,this.isSelectAllActive=!1,this.selectionStartLength=0}get finalSelectionStart(){return this.isSelectAllActive?[0,0]:this.selectionEnd&&this.selectionStart&&this.areSelectionValuesReversed()?this.selectionEnd:this.selectionStart}get finalSelectionEnd(){if(this.isSelectAllActive)return[this._bufferService.cols,this._bufferService.buffer.ybase+this._bufferService.rows-1];if(this.selectionStart){if(!this.selectionEnd||this.areSelectionValuesReversed()){const c=this.selectionStart[0]+this.selectionStartLength;return c>this._bufferService.cols?c%this._bufferService.cols==0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(c/this._bufferService.cols)-1]:[c%this._bufferService.cols,this.selectionStart[1]+Math.floor(c/this._bufferService.cols)]:[c,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){const c=this.selectionStart[0]+this.selectionStartLength;return c>this._bufferService.cols?[c%this._bufferService.cols,this.selectionStart[1]+Math.floor(c/this._bufferService.cols)]:[Math.max(c,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){const c=this.selectionStart,l=this.selectionEnd;return!(!c||!l)&&(c[1]>l[1]||c[1]===l[1]&&c[0]>l[0])}handleTrim(c){return this.selectionStart&&(this.selectionStart[1]-=c),this.selectionEnd&&(this.selectionEnd[1]-=c),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}}},428:function(o,a,c){var l=this&&this.__decorate||function(g,y,b,_){var w,S=arguments.length,C=S<3?y:_===null?_=Object.getOwnPropertyDescriptor(y,b):_;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")C=Reflect.decorate(g,y,b,_);else for(var T=g.length-1;T>=0;T--)(w=g[T])&&(C=(S<3?w(C):S>3?w(y,b,C):w(y,b))||C);return S>3&&C&&Object.defineProperty(y,b,C),C},u=this&&this.__param||function(g,y){return function(b,_){y(b,_,g)}};Object.defineProperty(a,"__esModule",{value:!0}),a.CharSizeService=void 0;const h=c(2585),d=c(8460),p=c(844);let m=a.CharSizeService=class extends p.Disposable{get hasValidSize(){return this.width>0&&this.height>0}constructor(g,y,b){super(),this._optionsService=b,this.width=0,this.height=0,this._onCharSizeChange=this.register(new d.EventEmitter),this.onCharSizeChange=this._onCharSizeChange.event,this._measureStrategy=new v(g,y,this._optionsService),this.register(this._optionsService.onMultipleOptionChange(["fontFamily","fontSize"],()=>this.measure()))}measure(){const g=this._measureStrategy.measure();g.width===this.width&&g.height===this.height||(this.width=g.width,this.height=g.height,this._onCharSizeChange.fire())}};a.CharSizeService=m=l([u(2,h.IOptionsService)],m);class v{constructor(y,b,_){this._document=y,this._parentElement=b,this._optionsService=_,this._result={width:0,height:0},this._measureElement=this._document.createElement("span"),this._measureElement.classList.add("xterm-char-measure-element"),this._measureElement.textContent="W".repeat(32),this._measureElement.setAttribute("aria-hidden","true"),this._measureElement.style.whiteSpace="pre",this._measureElement.style.fontKerning="none",this._parentElement.appendChild(this._measureElement)}measure(){this._measureElement.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._measureElement.style.fontSize=`${this._optionsService.rawOptions.fontSize}px`;const y={height:Number(this._measureElement.offsetHeight),width:Number(this._measureElement.offsetWidth)};return y.width!==0&&y.height!==0&&(this._result.width=y.width/32,this._result.height=Math.ceil(y.height)),this._result}}},4269:function(o,a,c){var l=this&&this.__decorate||function(y,b,_,w){var S,C=arguments.length,T=C<3?b:w===null?w=Object.getOwnPropertyDescriptor(b,_):w;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")T=Reflect.decorate(y,b,_,w);else for(var k=y.length-1;k>=0;k--)(S=y[k])&&(T=(C<3?S(T):C>3?S(b,_,T):S(b,_))||T);return C>3&&T&&Object.defineProperty(b,_,T),T},u=this&&this.__param||function(y,b){return function(_,w){b(_,w,y)}};Object.defineProperty(a,"__esModule",{value:!0}),a.CharacterJoinerService=a.JoinedCellData=void 0;const h=c(3734),d=c(643),p=c(511),m=c(2585);class v extends h.AttributeData{constructor(b,_,w){super(),this.content=0,this.combinedData="",this.fg=b.fg,this.bg=b.bg,this.combinedData=_,this._width=w}isCombined(){return 2097152}getWidth(){return this._width}getChars(){return this.combinedData}getCode(){return 2097151}setFromCharData(b){throw new Error("not implemented")}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}}a.JoinedCellData=v;let g=a.CharacterJoinerService=class tL{constructor(b){this._bufferService=b,this._characterJoiners=[],this._nextCharacterJoinerId=0,this._workCell=new p.CellData}register(b){const _={id:this._nextCharacterJoinerId++,handler:b};return this._characterJoiners.push(_),_.id}deregister(b){for(let _=0;_<this._characterJoiners.length;_++)if(this._characterJoiners[_].id===b)return this._characterJoiners.splice(_,1),!0;return!1}getJoinedCharacters(b){if(this._characterJoiners.length===0)return[];const _=this._bufferService.buffer.lines.get(b);if(!_||_.length===0)return[];const w=[],S=_.translateToString(!0);let C=0,T=0,k=0,A=_.getFg(0),M=_.getBg(0);for(let R=0;R<_.getTrimmedLength();R++)if(_.loadCell(R,this._workCell),this._workCell.getWidth()!==0){if(this._workCell.fg!==A||this._workCell.bg!==M){if(R-C>1){const P=this._getJoinedRanges(S,k,T,_,C);for(let L=0;L<P.length;L++)w.push(P[L])}C=R,k=T,A=this._workCell.fg,M=this._workCell.bg}T+=this._workCell.getChars().length||d.WHITESPACE_CELL_CHAR.length}if(this._bufferService.cols-C>1){const R=this._getJoinedRanges(S,k,T,_,C);for(let P=0;P<R.length;P++)w.push(R[P])}return w}_getJoinedRanges(b,_,w,S,C){const T=b.substring(_,w);let k=[];try{k=this._characterJoiners[0].handler(T)}catch(A){console.error(A)}for(let A=1;A<this._characterJoiners.length;A++)try{const M=this._characterJoiners[A].handler(T);for(let R=0;R<M.length;R++)tL._mergeRanges(k,M[R])}catch(M){console.error(M)}return this._stringRangesToCellRanges(k,S,C),k}_stringRangesToCellRanges(b,_,w){let S=0,C=!1,T=0,k=b[S];if(k){for(let A=w;A<this._bufferService.cols;A++){const M=_.getWidth(A),R=_.getString(A).length||d.WHITESPACE_CELL_CHAR.length;if(M!==0){if(!C&&k[0]<=T&&(k[0]=A,C=!0),k[1]<=T){if(k[1]=A,k=b[++S],!k)break;k[0]<=T?(k[0]=A,C=!0):C=!1}T+=R}}k&&(k[1]=this._bufferService.cols)}}static _mergeRanges(b,_){let w=!1;for(let S=0;S<b.length;S++){const C=b[S];if(w){if(_[1]<=C[0])return b[S-1][1]=_[1],b;if(_[1]<=C[1])return b[S-1][1]=Math.max(_[1],C[1]),b.splice(S,1),b;b.splice(S,1),S--}else{if(_[1]<=C[0])return b.splice(S,0,_),b;if(_[1]<=C[1])return C[0]=Math.min(_[0],C[0]),b;_[0]<C[1]&&(C[0]=Math.min(_[0],C[0]),w=!0)}}return w?b[b.length-1][1]=_[1]:b.push(_),b}};a.CharacterJoinerService=g=l([u(0,m.IBufferService)],g)},5114:(o,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.CoreBrowserService=void 0,a.CoreBrowserService=class{constructor(c,l){this._textarea=c,this.window=l,this._isFocused=!1,this._cachedIsFocused=void 0,this._textarea.addEventListener("focus",()=>this._isFocused=!0),this._textarea.addEventListener("blur",()=>this._isFocused=!1)}get dpr(){return this.window.devicePixelRatio}get isFocused(){return this._cachedIsFocused===void 0&&(this._cachedIsFocused=this._isFocused&&this._textarea.ownerDocument.hasFocus(),queueMicrotask(()=>this._cachedIsFocused=void 0)),this._cachedIsFocused}}},8934:function(o,a,c){var l=this&&this.__decorate||function(m,v,g,y){var b,_=arguments.length,w=_<3?v:y===null?y=Object.getOwnPropertyDescriptor(v,g):y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")w=Reflect.decorate(m,v,g,y);else for(var S=m.length-1;S>=0;S--)(b=m[S])&&(w=(_<3?b(w):_>3?b(v,g,w):b(v,g))||w);return _>3&&w&&Object.defineProperty(v,g,w),w},u=this&&this.__param||function(m,v){return function(g,y){v(g,y,m)}};Object.defineProperty(a,"__esModule",{value:!0}),a.MouseService=void 0;const h=c(4725),d=c(9806);let p=a.MouseService=class{constructor(m,v){this._renderService=m,this._charSizeService=v}getCoords(m,v,g,y,b){return(0,d.getCoords)(window,m,v,g,y,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,b)}getMouseReportCoords(m,v){const g=(0,d.getCoordsRelativeToElement)(window,m,v);if(this._charSizeService.hasValidSize)return g[0]=Math.min(Math.max(g[0],0),this._renderService.dimensions.css.canvas.width-1),g[1]=Math.min(Math.max(g[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(g[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(g[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(g[0]),y:Math.floor(g[1])}}};a.MouseService=p=l([u(0,h.IRenderService),u(1,h.ICharSizeService)],p)},3230:function(o,a,c){var l=this&&this.__decorate||function(w,S,C,T){var k,A=arguments.length,M=A<3?S:T===null?T=Object.getOwnPropertyDescriptor(S,C):T;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")M=Reflect.decorate(w,S,C,T);else for(var R=w.length-1;R>=0;R--)(k=w[R])&&(M=(A<3?k(M):A>3?k(S,C,M):k(S,C))||M);return A>3&&M&&Object.defineProperty(S,C,M),M},u=this&&this.__param||function(w,S){return function(C,T){S(C,T,w)}};Object.defineProperty(a,"__esModule",{value:!0}),a.RenderService=void 0;const h=c(3656),d=c(6193),p=c(5596),m=c(4725),v=c(8460),g=c(844),y=c(7226),b=c(2585);let _=a.RenderService=class extends g.Disposable{get dimensions(){return this._renderer.value.dimensions}constructor(w,S,C,T,k,A,M,R){if(super(),this._rowCount=w,this._charSizeService=T,this._renderer=this.register(new g.MutableDisposable),this._pausedResizeTask=new y.DebouncedIdleTask,this._isPaused=!1,this._needsFullRefresh=!1,this._isNextRenderRedrawOnly=!0,this._needsSelectionRefresh=!1,this._canvasWidth=0,this._canvasHeight=0,this._selectionState={start:void 0,end:void 0,columnSelectMode:!1},this._onDimensionsChange=this.register(new v.EventEmitter),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this.register(new v.EventEmitter),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this.register(new v.EventEmitter),this.onRender=this._onRender.event,this._onRefreshRequest=this.register(new v.EventEmitter),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new d.RenderDebouncer(M.window,(P,L)=>this._renderRows(P,L)),this.register(this._renderDebouncer),this._screenDprMonitor=new p.ScreenDprMonitor(M.window),this._screenDprMonitor.setListener(()=>this.handleDevicePixelRatioChange()),this.register(this._screenDprMonitor),this.register(A.onResize(()=>this._fullRefresh())),this.register(A.buffers.onBufferActivate(()=>{var P;return(P=this._renderer.value)===null||P===void 0?void 0:P.clear()})),this.register(C.onOptionChange(()=>this._handleOptionsChanged())),this.register(this._charSizeService.onCharSizeChange(()=>this.handleCharSizeChanged())),this.register(k.onDecorationRegistered(()=>this._fullRefresh())),this.register(k.onDecorationRemoved(()=>this._fullRefresh())),this.register(C.onMultipleOptionChange(["customGlyphs","drawBoldTextInBrightColors","letterSpacing","lineHeight","fontFamily","fontSize","fontWeight","fontWeightBold","minimumContrastRatio"],()=>{this.clear(),this.handleResize(A.cols,A.rows),this._fullRefresh()})),this.register(C.onMultipleOptionChange(["cursorBlink","cursorStyle"],()=>this.refreshRows(A.buffer.y,A.buffer.y,!0))),this.register((0,h.addDisposableDomListener)(M.window,"resize",()=>this.handleDevicePixelRatioChange())),this.register(R.onChangeColors(()=>this._fullRefresh())),"IntersectionObserver"in M.window){const P=new M.window.IntersectionObserver(L=>this._handleIntersectionChange(L[L.length-1]),{threshold:0});P.observe(S),this.register({dispose:()=>P.disconnect()})}}_handleIntersectionChange(w){this._isPaused=w.isIntersecting===void 0?w.intersectionRatio===0:!w.isIntersecting,this._isPaused||this._charSizeService.hasValidSize||this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(w,S,C=!1){this._isPaused?this._needsFullRefresh=!0:(C||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(w,S,this._rowCount))}_renderRows(w,S){this._renderer.value&&(w=Math.min(w,this._rowCount-1),S=Math.min(S,this._rowCount-1),this._renderer.value.renderRows(w,S),this._needsSelectionRefresh&&(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),this._needsSelectionRefresh=!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:w,end:S}),this._onRender.fire({start:w,end:S}),this._isNextRenderRedrawOnly=!0)}resize(w,S){this._rowCount=S,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(w){this._renderer.value=w,this._renderer.value.onRequestRedraw(S=>this.refreshRows(S.start,S.end,!0)),this._needsSelectionRefresh=!0,this._fullRefresh()}addRefreshCallback(w){return this._renderDebouncer.addRefreshCallback(w)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){var w,S;this._renderer.value&&((S=(w=this._renderer.value).clearTextureAtlas)===null||S===void 0||S.call(w),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(w,S){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set(()=>this._renderer.value.handleResize(w,S)):this._renderer.value.handleResize(w,S),this._fullRefresh())}handleCharSizeChanged(){var w;(w=this._renderer.value)===null||w===void 0||w.handleCharSizeChanged()}handleBlur(){var w;(w=this._renderer.value)===null||w===void 0||w.handleBlur()}handleFocus(){var w;(w=this._renderer.value)===null||w===void 0||w.handleFocus()}handleSelectionChanged(w,S,C){var T;this._selectionState.start=w,this._selectionState.end=S,this._selectionState.columnSelectMode=C,(T=this._renderer.value)===null||T===void 0||T.handleSelectionChanged(w,S,C)}handleCursorMove(){var w;(w=this._renderer.value)===null||w===void 0||w.handleCursorMove()}clear(){var w;(w=this._renderer.value)===null||w===void 0||w.clear()}};a.RenderService=_=l([u(2,b.IOptionsService),u(3,m.ICharSizeService),u(4,b.IDecorationService),u(5,b.IBufferService),u(6,m.ICoreBrowserService),u(7,m.IThemeService)],_)},9312:function(o,a,c){var l=this&&this.__decorate||function(k,A,M,R){var P,L=arguments.length,z=L<3?A:R===null?R=Object.getOwnPropertyDescriptor(A,M):R;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")z=Reflect.decorate(k,A,M,R);else for(var Q=k.length-1;Q>=0;Q--)(P=k[Q])&&(z=(L<3?P(z):L>3?P(A,M,z):P(A,M))||z);return L>3&&z&&Object.defineProperty(A,M,z),z},u=this&&this.__param||function(k,A){return function(M,R){A(M,R,k)}};Object.defineProperty(a,"__esModule",{value:!0}),a.SelectionService=void 0;const h=c(9806),d=c(9504),p=c(456),m=c(4725),v=c(8460),g=c(844),y=c(6114),b=c(4841),_=c(511),w=c(2585),S=" ",C=new RegExp(S,"g");let T=a.SelectionService=class extends g.Disposable{constructor(k,A,M,R,P,L,z,Q,W){super(),this._element=k,this._screenElement=A,this._linkifier=M,this._bufferService=R,this._coreService=P,this._mouseService=L,this._optionsService=z,this._renderService=Q,this._coreBrowserService=W,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new _.CellData,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this.register(new v.EventEmitter),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this.register(new v.EventEmitter),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this.register(new v.EventEmitter),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this.register(new v.EventEmitter),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=V=>this._handleMouseMove(V),this._mouseUpListener=V=>this._handleMouseUp(V),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(V=>this._handleTrim(V)),this.register(this._bufferService.buffers.onBufferActivate(V=>this._handleBufferActivate(V))),this.enable(),this._model=new p.SelectionModel(this._bufferService),this._activeSelectionMode=0,this.register((0,g.toDisposable)(()=>{this._removeMouseDownListeners()}))}reset(){this.clearSelection()}disable(){this.clearSelection(),this._enabled=!1}enable(){this._enabled=!0}get selectionStart(){return this._model.finalSelectionStart}get selectionEnd(){return this._model.finalSelectionEnd}get hasSelection(){const k=this._model.finalSelectionStart,A=this._model.finalSelectionEnd;return!(!k||!A||k[0]===A[0]&&k[1]===A[1])}get selectionText(){const k=this._model.finalSelectionStart,A=this._model.finalSelectionEnd;if(!k||!A)return"";const M=this._bufferService.buffer,R=[];if(this._activeSelectionMode===3){if(k[0]===A[0])return"";const P=k[0]<A[0]?k[0]:A[0],L=k[0]<A[0]?A[0]:k[0];for(let z=k[1];z<=A[1];z++){const Q=M.translateBufferLineToString(z,!0,P,L);R.push(Q)}}else{const P=k[1]===A[1]?A[0]:void 0;R.push(M.translateBufferLineToString(k[1],!0,k[0],P));for(let L=k[1]+1;L<=A[1]-1;L++){const z=M.lines.get(L),Q=M.translateBufferLineToString(L,!0);z!=null&&z.isWrapped?R[R.length-1]+=Q:R.push(Q)}if(k[1]!==A[1]){const L=M.lines.get(A[1]),z=M.translateBufferLineToString(A[1],!0,0,A[0]);L&&L.isWrapped?R[R.length-1]+=z:R.push(z)}}return R.map(P=>P.replace(C," ")).join(y.isWindows?`\r
`:`
`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(k){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh())),y.isLinux&&k&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(k){const A=this._getMouseBufferCoords(k),M=this._model.finalSelectionStart,R=this._model.finalSelectionEnd;return!!(M&&R&&A)&&this._areCoordsInSelection(A,M,R)}isCellInSelection(k,A){const M=this._model.finalSelectionStart,R=this._model.finalSelectionEnd;return!(!M||!R)&&this._areCoordsInSelection([k,A],M,R)}_areCoordsInSelection(k,A,M){return k[1]>A[1]&&k[1]<M[1]||A[1]===M[1]&&k[1]===A[1]&&k[0]>=A[0]&&k[0]<M[0]||A[1]<M[1]&&k[1]===M[1]&&k[0]<M[0]||A[1]<M[1]&&k[1]===A[1]&&k[0]>=A[0]}_selectWordAtCursor(k,A){var M,R;const P=(R=(M=this._linkifier.currentLink)===null||M===void 0?void 0:M.link)===null||R===void 0?void 0:R.range;if(P)return this._model.selectionStart=[P.start.x-1,P.start.y-1],this._model.selectionStartLength=(0,b.getRangeLength)(P,this._bufferService.cols),this._model.selectionEnd=void 0,!0;const L=this._getMouseBufferCoords(k);return!!L&&(this._selectWordAt(L,A),this._model.selectionEnd=void 0,!0)}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(k,A){this._model.clearSelection(),k=Math.max(k,0),A=Math.min(A,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,k],this._model.selectionEnd=[this._bufferService.cols,A],this.refresh(),this._onSelectionChange.fire()}_handleTrim(k){this._model.handleTrim(k)&&this.refresh()}_getMouseBufferCoords(k){const A=this._mouseService.getCoords(k,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(A)return A[0]--,A[1]--,A[1]+=this._bufferService.buffer.ydisp,A}_getMouseEventScrollAmount(k){let A=(0,h.getCoordsRelativeToElement)(this._coreBrowserService.window,k,this._screenElement)[1];const M=this._renderService.dimensions.css.canvas.height;return A>=0&&A<=M?0:(A>M&&(A-=M),A=Math.min(Math.max(A,-50),50),A/=50,A/Math.abs(A)+Math.round(14*A))}shouldForceSelection(k){return y.isMac?k.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:k.shiftKey}handleMouseDown(k){if(this._mouseDownTimeStamp=k.timeStamp,(k.button!==2||!this.hasSelection)&&k.button===0){if(!this._enabled){if(!this.shouldForceSelection(k))return;k.stopPropagation()}k.preventDefault(),this._dragScrollAmount=0,this._enabled&&k.shiftKey?this._handleIncrementalClick(k):k.detail===1?this._handleSingleClick(k):k.detail===2?this._handleDoubleClick(k):k.detail===3&&this._handleTripleClick(k),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener("mouseup",this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),50)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener("mouseup",this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(k){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(k))}_handleSingleClick(k){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(k)?3:0,this._model.selectionStart=this._getMouseBufferCoords(k),!this._model.selectionStart)return;this._model.selectionEnd=void 0;const A=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);A&&A.length!==this._model.selectionStart[0]&&A.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(k){this._selectWordAtCursor(k,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(k){const A=this._getMouseBufferCoords(k);A&&(this._activeSelectionMode=2,this._selectLineAt(A[1]))}shouldColumnSelect(k){return k.altKey&&!(y.isMac&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(k){if(k.stopImmediatePropagation(),!this._model.selectionStart)return;const A=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(k),!this._model.selectionEnd)return void this.refresh(!0);this._activeSelectionMode===2?this._model.selectionEnd[1]<this._model.selectionStart[1]?this._model.selectionEnd[0]=0:this._model.selectionEnd[0]=this._bufferService.cols:this._activeSelectionMode===1&&this._selectToWordAt(this._model.selectionEnd),this._dragScrollAmount=this._getMouseEventScrollAmount(k),this._activeSelectionMode!==3&&(this._dragScrollAmount>0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));const M=this._bufferService.buffer;if(this._model.selectionEnd[1]<M.lines.length){const R=M.lines.get(this._model.selectionEnd[1]);R&&R.hasWidth(this._model.selectionEnd[0])===0&&this._model.selectionEnd[0]++}A&&A[0]===this._model.selectionEnd[0]&&A[1]===this._model.selectionEnd[1]||this.refresh(!0)}_dragScroll(){if(this._model.selectionEnd&&this._model.selectionStart&&this._dragScrollAmount){this._onRequestScrollLines.fire({amount:this._dragScrollAmount,suppressScrollEvent:!1});const k=this._bufferService.buffer;this._dragScrollAmount>0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(k.ydisp+this._bufferService.rows,k.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=k.ydisp),this.refresh()}}_handleMouseUp(k){const A=k.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&A<500&&k.altKey&&this._optionsService.rawOptions.altClickMovesCursor){if(this._bufferService.buffer.ybase===this._bufferService.buffer.ydisp){const M=this._mouseService.getCoords(k,this._element,this._bufferService.cols,this._bufferService.rows,!1);if(M&&M[0]!==void 0&&M[1]!==void 0){const R=(0,d.moveToCellSequence)(M[0]-1,M[1]-1,this._bufferService,this._coreService.decPrivateModes.applicationCursorKeys);this._coreService.triggerDataEvent(R,!0)}}}else this._fireEventIfSelectionChanged()}_fireEventIfSelectionChanged(){const k=this._model.finalSelectionStart,A=this._model.finalSelectionEnd,M=!(!k||!A||k[0]===A[0]&&k[1]===A[1]);M?k&&A&&(this._oldSelectionStart&&this._oldSelectionEnd&&k[0]===this._oldSelectionStart[0]&&k[1]===this._oldSelectionStart[1]&&A[0]===this._oldSelectionEnd[0]&&A[1]===this._oldSelectionEnd[1]||this._fireOnSelectionChange(k,A,M)):this._oldHasSelection&&this._fireOnSelectionChange(k,A,M)}_fireOnSelectionChange(k,A,M){this._oldSelectionStart=k,this._oldSelectionEnd=A,this._oldHasSelection=M,this._onSelectionChange.fire()}_handleBufferActivate(k){this.clearSelection(),this._trimListener.dispose(),this._trimListener=k.activeBuffer.lines.onTrim(A=>this._handleTrim(A))}_convertViewportColToCharacterIndex(k,A){let M=A;for(let R=0;A>=R;R++){const P=k.loadCell(R,this._workCell).getChars().length;this._workCell.getWidth()===0?M--:P>1&&A!==R&&(M+=P-1)}return M}setSelection(k,A,M){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[k,A],this._model.selectionStartLength=M,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(k){this._isClickInSelection(k)||(this._selectWordAtCursor(k,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(k,A,M=!0,R=!0){if(k[0]>=this._bufferService.cols)return;const P=this._bufferService.buffer,L=P.lines.get(k[1]);if(!L)return;const z=P.translateBufferLineToString(k[1],!1);let Q=this._convertViewportColToCharacterIndex(L,k[0]),W=Q;const V=k[0]-Q;let N=0,O=0,H=0,G=0;if(z.charAt(Q)===" "){for(;Q>0&&z.charAt(Q-1)===" ";)Q--;for(;W<z.length&&z.charAt(W+1)===" ";)W++}else{let ve=k[0],le=k[0];L.getWidth(ve)===0&&(N++,ve--),L.getWidth(le)===2&&(O++,le++);const oe=L.getString(le).length;for(oe>1&&(G+=oe-1,W+=oe-1);ve>0&&Q>0&&!this._isCharWordSeparator(L.loadCell(ve-1,this._workCell));){L.loadCell(ve-1,this._workCell);const I=this._workCell.getChars().length;this._workCell.getWidth()===0?(N++,ve--):I>1&&(H+=I-1,Q-=I-1),Q--,ve--}for(;le<L.length&&W+1<z.length&&!this._isCharWordSeparator(L.loadCell(le+1,this._workCell));){L.loadCell(le+1,this._workCell);const I=this._workCell.getChars().length;this._workCell.getWidth()===2?(O++,le++):I>1&&(G+=I-1,W+=I-1),W++,le++}}W++;let ee=Q+V-N+H,ie=Math.min(this._bufferService.cols,W-Q+N+O-H-G);if(A||z.slice(Q,W).trim()!==""){if(M&&ee===0&&L.getCodePoint(0)!==32){const ve=P.lines.get(k[1]-1);if(ve&&L.isWrapped&&ve.getCodePoint(this._bufferService.cols-1)!==32){const le=this._getWordAt([this._bufferService.cols-1,k[1]-1],!1,!0,!1);if(le){const oe=this._bufferService.cols-le.start;ee-=oe,ie+=oe}}}if(R&&ee+ie===this._bufferService.cols&&L.getCodePoint(this._bufferService.cols-1)!==32){const ve=P.lines.get(k[1]+1);if(ve!=null&&ve.isWrapped&&ve.getCodePoint(0)!==32){const le=this._getWordAt([0,k[1]+1],!1,!1,!0);le&&(ie+=le.length)}}return{start:ee,length:ie}}}_selectWordAt(k,A){const M=this._getWordAt(k,A);if(M){for(;M.start<0;)M.start+=this._bufferService.cols,k[1]--;this._model.selectionStart=[M.start,k[1]],this._model.selectionStartLength=M.length}}_selectToWordAt(k){const A=this._getWordAt(k,!0);if(A){let M=k[1];for(;A.start<0;)A.start+=this._bufferService.cols,M--;if(!this._model.areSelectionValuesReversed())for(;A.start+A.length>this._bufferService.cols;)A.length-=this._bufferService.cols,M++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?A.start:A.start+A.length,M]}}_isCharWordSeparator(k){return k.getWidth()!==0&&this._optionsService.rawOptions.wordSeparator.indexOf(k.getChars())>=0}_selectLineAt(k){const A=this._bufferService.buffer.getWrappedRangeForLine(k),M={start:{x:0,y:A.first},end:{x:this._bufferService.cols-1,y:A.last}};this._model.selectionStart=[0,A.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=(0,b.getRangeLength)(M,this._bufferService.cols)}};a.SelectionService=T=l([u(3,w.IBufferService),u(4,w.ICoreService),u(5,m.IMouseService),u(6,w.IOptionsService),u(7,m.IRenderService),u(8,m.ICoreBrowserService)],T)},4725:(o,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.IThemeService=a.ICharacterJoinerService=a.ISelectionService=a.IRenderService=a.IMouseService=a.ICoreBrowserService=a.ICharSizeService=void 0;const l=c(8343);a.ICharSizeService=(0,l.createDecorator)("CharSizeService"),a.ICoreBrowserService=(0,l.createDecorator)("CoreBrowserService"),a.IMouseService=(0,l.createDecorator)("MouseService"),a.IRenderService=(0,l.createDecorator)("RenderService"),a.ISelectionService=(0,l.createDecorator)("SelectionService"),a.ICharacterJoinerService=(0,l.createDecorator)("CharacterJoinerService"),a.IThemeService=(0,l.createDecorator)("ThemeService")},6731:function(o,a,c){var l=this&&this.__decorate||function(T,k,A,M){var R,P=arguments.length,L=P<3?k:M===null?M=Object.getOwnPropertyDescriptor(k,A):M;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")L=Reflect.decorate(T,k,A,M);else for(var z=T.length-1;z>=0;z--)(R=T[z])&&(L=(P<3?R(L):P>3?R(k,A,L):R(k,A))||L);return P>3&&L&&Object.defineProperty(k,A,L),L},u=this&&this.__param||function(T,k){return function(A,M){k(A,M,T)}};Object.defineProperty(a,"__esModule",{value:!0}),a.ThemeService=a.DEFAULT_ANSI_COLORS=void 0;const h=c(7239),d=c(8055),p=c(8460),m=c(844),v=c(2585),g=d.css.toColor("#ffffff"),y=d.css.toColor("#000000"),b=d.css.toColor("#ffffff"),_=d.css.toColor("#000000"),w={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117};a.DEFAULT_ANSI_COLORS=Object.freeze((()=>{const T=[d.css.toColor("#2e3436"),d.css.toColor("#cc0000"),d.css.toColor("#4e9a06"),d.css.toColor("#c4a000"),d.css.toColor("#3465a4"),d.css.toColor("#75507b"),d.css.toColor("#06989a"),d.css.toColor("#d3d7cf"),d.css.toColor("#555753"),d.css.toColor("#ef2929"),d.css.toColor("#8ae234"),d.css.toColor("#fce94f"),d.css.toColor("#729fcf"),d.css.toColor("#ad7fa8"),d.css.toColor("#34e2e2"),d.css.toColor("#eeeeec")],k=[0,95,135,175,215,255];for(let A=0;A<216;A++){const M=k[A/36%6|0],R=k[A/6%6|0],P=k[A%6];T.push({css:d.channels.toCss(M,R,P),rgba:d.channels.toRgba(M,R,P)})}for(let A=0;A<24;A++){const M=8+10*A;T.push({css:d.channels.toCss(M,M,M),rgba:d.channels.toRgba(M,M,M)})}return T})());let S=a.ThemeService=class extends m.Disposable{get colors(){return this._colors}constructor(T){super(),this._optionsService=T,this._contrastCache=new h.ColorContrastCache,this._halfContrastCache=new h.ColorContrastCache,this._onChangeColors=this.register(new p.EventEmitter),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:g,background:y,cursor:b,cursorAccent:_,selectionForeground:void 0,selectionBackgroundTransparent:w,selectionBackgroundOpaque:d.color.blend(y,w),selectionInactiveBackgroundTransparent:w,selectionInactiveBackgroundOpaque:d.color.blend(y,w),ansi:a.DEFAULT_ANSI_COLORS.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this.register(this._optionsService.onSpecificOptionChange("minimumContrastRatio",()=>this._contrastCache.clear())),this.register(this._optionsService.onSpecificOptionChange("theme",()=>this._setTheme(this._optionsService.rawOptions.theme)))}_setTheme(T={}){const k=this._colors;if(k.foreground=C(T.foreground,g),k.background=C(T.background,y),k.cursor=C(T.cursor,b),k.cursorAccent=C(T.cursorAccent,_),k.selectionBackgroundTransparent=C(T.selectionBackground,w),k.selectionBackgroundOpaque=d.color.blend(k.background,k.selectionBackgroundTransparent),k.selectionInactiveBackgroundTransparent=C(T.selectionInactiveBackground,k.selectionBackgroundTransparent),k.selectionInactiveBackgroundOpaque=d.color.blend(k.background,k.selectionInactiveBackgroundTransparent),k.selectionForeground=T.selectionForeground?C(T.selectionForeground,d.NULL_COLOR):void 0,k.selectionForeground===d.NULL_COLOR&&(k.selectionForeground=void 0),d.color.isOpaque(k.selectionBackgroundTransparent)&&(k.selectionBackgroundTransparent=d.color.opacity(k.selectionBackgroundTransparent,.3)),d.color.isOpaque(k.selectionInactiveBackgroundTransparent)&&(k.selectionInactiveBackgroundTransparent=d.color.opacity(k.selectionInactiveBackgroundTransparent,.3)),k.ansi=a.DEFAULT_ANSI_COLORS.slice(),k.ansi[0]=C(T.black,a.DEFAULT_ANSI_COLORS[0]),k.ansi[1]=C(T.red,a.DEFAULT_ANSI_COLORS[1]),k.ansi[2]=C(T.green,a.DEFAULT_ANSI_COLORS[2]),k.ansi[3]=C(T.yellow,a.DEFAULT_ANSI_COLORS[3]),k.ansi[4]=C(T.blue,a.DEFAULT_ANSI_COLORS[4]),k.ansi[5]=C(T.magenta,a.DEFAULT_ANSI_COLORS[5]),k.ansi[6]=C(T.cyan,a.DEFAULT_ANSI_COLORS[6]),k.ansi[7]=C(T.white,a.DEFAULT_ANSI_COLORS[7]),k.ansi[8]=C(T.brightBlack,a.DEFAULT_ANSI_COLORS[8]),k.ansi[9]=C(T.brightRed,a.DEFAULT_ANSI_COLORS[9]),k.ansi[10]=C(T.brightGreen,a.DEFAULT_ANSI_COLORS[10]),k.ansi[11]=C(T.brightYellow,a.DEFAULT_ANSI_COLORS[11]),k.ansi[12]=C(T.brightBlue,a.DEFAULT_ANSI_COLORS[12]),k.ansi[13]=C(T.brightMagenta,a.DEFAULT_ANSI_COLORS[13]),k.ansi[14]=C(T.brightCyan,a.DEFAULT_ANSI_COLORS[14]),k.ansi[15]=C(T.brightWhite,a.DEFAULT_ANSI_COLORS[15]),T.extendedAnsi){const A=Math.min(k.ansi.length-16,T.extendedAnsi.length);for(let M=0;M<A;M++)k.ansi[M+16]=C(T.extendedAnsi[M],a.DEFAULT_ANSI_COLORS[M+16])}this._contrastCache.clear(),this._halfContrastCache.clear(),this._updateRestoreColors(),this._onChangeColors.fire(this.colors)}restoreColor(T){this._restoreColor(T),this._onChangeColors.fire(this.colors)}_restoreColor(T){if(T!==void 0)switch(T){case 256:this._colors.foreground=this._restoreColors.foreground;break;case 257:this._colors.background=this._restoreColors.background;break;case 258:this._colors.cursor=this._restoreColors.cursor;break;default:this._colors.ansi[T]=this._restoreColors.ansi[T]}else for(let k=0;k<this._restoreColors.ansi.length;++k)this._colors.ansi[k]=this._restoreColors.ansi[k]}modifyColors(T){T(this._colors),this._onChangeColors.fire(this.colors)}_updateRestoreColors(){this._restoreColors={foreground:this._colors.foreground,background:this._colors.background,cursor:this._colors.cursor,ansi:this._colors.ansi.slice()}}};function C(T,k){if(T!==void 0)try{return d.css.toColor(T)}catch{}return k}a.ThemeService=S=l([u(0,v.IOptionsService)],S)},6349:(o,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.CircularList=void 0;const l=c(8460),u=c(844);class h extends u.Disposable{constructor(p){super(),this._maxLength=p,this.onDeleteEmitter=this.register(new l.EventEmitter),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this.register(new l.EventEmitter),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this.register(new l.EventEmitter),this.onTrim=this.onTrimEmitter.event,this._array=new Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(p){if(this._maxLength===p)return;const m=new Array(p);for(let v=0;v<Math.min(p,this.length);v++)m[v]=this._array[this._getCyclicIndex(v)];this._array=m,this._maxLength=p,this._startIndex=0}get length(){return this._length}set length(p){if(p>this._length)for(let m=this._length;m<p;m++)this._array[m]=void 0;this._length=p}get(p){return this._array[this._getCyclicIndex(p)]}set(p,m){this._array[this._getCyclicIndex(p)]=m}push(p){this._array[this._getCyclicIndex(this._length)]=p,this._length===this._maxLength?(this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1)):this._length++}recycle(){if(this._length!==this._maxLength)throw new Error("Can only recycle when the buffer is full");return this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1),this._array[this._getCyclicIndex(this._length-1)]}get isFull(){return this._length===this._maxLength}pop(){return this._array[this._getCyclicIndex(this._length---1)]}splice(p,m,...v){if(m){for(let g=p;g<this._length-m;g++)this._array[this._getCyclicIndex(g)]=this._array[this._getCyclicIndex(g+m)];this._length-=m,this.onDeleteEmitter.fire({index:p,amount:m})}for(let g=this._length-1;g>=p;g--)this._array[this._getCyclicIndex(g+v.length)]=this._array[this._getCyclicIndex(g)];for(let g=0;g<v.length;g++)this._array[this._getCyclicIndex(p+g)]=v[g];if(v.length&&this.onInsertEmitter.fire({index:p,amount:v.length}),this._length+v.length>this._maxLength){const g=this._length+v.length-this._maxLength;this._startIndex+=g,this._length=this._maxLength,this.onTrimEmitter.fire(g)}else this._length+=v.length}trimStart(p){p>this._length&&(p=this._length),this._startIndex+=p,this._length-=p,this.onTrimEmitter.fire(p)}shiftElements(p,m,v){if(!(m<=0)){if(p<0||p>=this._length)throw new Error("start argument out of range");if(p+v<0)throw new Error("Cannot shift elements in list beyond index 0");if(v>0){for(let y=m-1;y>=0;y--)this.set(p+y+v,this.get(p+y));const g=p+m+v-this._length;if(g>0)for(this._length+=g;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let g=0;g<m;g++)this.set(p+g+v,this.get(p+g))}}_getCyclicIndex(p){return(this._startIndex+p)%this._maxLength}}a.CircularList=h},1439:(o,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.clone=void 0,a.clone=function c(l,u=5){if(typeof l!="object")return l;const h=Array.isArray(l)?[]:{};for(const d in l)h[d]=u<=1?l[d]:l[d]&&c(l[d],u-1);return h}},8055:(o,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.contrastRatio=a.toPaddedHex=a.rgba=a.rgb=a.css=a.color=a.channels=a.NULL_COLOR=void 0;const l=c(6114);let u=0,h=0,d=0,p=0;var m,v,g,y,b;function _(S){const C=S.toString(16);return C.length<2?"0"+C:C}function w(S,C){return S<C?(C+.05)/(S+.05):(S+.05)/(C+.05)}a.NULL_COLOR={css:"#00000000",rgba:0},function(S){S.toCss=function(C,T,k,A){return A!==void 0?`#${_(C)}${_(T)}${_(k)}${_(A)}`:`#${_(C)}${_(T)}${_(k)}`},S.toRgba=function(C,T,k,A=255){return(C<<24|T<<16|k<<8|A)>>>0}}(m||(a.channels=m={})),function(S){function C(T,k){return p=Math.round(255*k),[u,h,d]=b.toChannels(T.rgba),{css:m.toCss(u,h,d,p),rgba:m.toRgba(u,h,d,p)}}S.blend=function(T,k){if(p=(255&k.rgba)/255,p===1)return{css:k.css,rgba:k.rgba};const A=k.rgba>>24&255,M=k.rgba>>16&255,R=k.rgba>>8&255,P=T.rgba>>24&255,L=T.rgba>>16&255,z=T.rgba>>8&255;return u=P+Math.round((A-P)*p),h=L+Math.round((M-L)*p),d=z+Math.round((R-z)*p),{css:m.toCss(u,h,d),rgba:m.toRgba(u,h,d)}},S.isOpaque=function(T){return(255&T.rgba)==255},S.ensureContrastRatio=function(T,k,A){const M=b.ensureContrastRatio(T.rgba,k.rgba,A);if(M)return b.toColor(M>>24&255,M>>16&255,M>>8&255)},S.opaque=function(T){const k=(255|T.rgba)>>>0;return[u,h,d]=b.toChannels(k),{css:m.toCss(u,h,d),rgba:k}},S.opacity=C,S.multiplyOpacity=function(T,k){return p=255&T.rgba,C(T,p*k/255)},S.toColorRGB=function(T){return[T.rgba>>24&255,T.rgba>>16&255,T.rgba>>8&255]}}(v||(a.color=v={})),function(S){let C,T;if(!l.isNode){const k=document.createElement("canvas");k.width=1,k.height=1;const A=k.getContext("2d",{willReadFrequently:!0});A&&(C=A,C.globalCompositeOperation="copy",T=C.createLinearGradient(0,0,1,1))}S.toColor=function(k){if(k.match(/#[\da-f]{3,8}/i))switch(k.length){case 4:return u=parseInt(k.slice(1,2).repeat(2),16),h=parseInt(k.slice(2,3).repeat(2),16),d=parseInt(k.slice(3,4).repeat(2),16),b.toColor(u,h,d);case 5:return u=parseInt(k.slice(1,2).repeat(2),16),h=parseInt(k.slice(2,3).repeat(2),16),d=parseInt(k.slice(3,4).repeat(2),16),p=parseInt(k.slice(4,5).repeat(2),16),b.toColor(u,h,d,p);case 7:return{css:k,rgba:(parseInt(k.slice(1),16)<<8|255)>>>0};case 9:return{css:k,rgba:parseInt(k.slice(1),16)>>>0}}const A=k.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(A)return u=parseInt(A[1]),h=parseInt(A[2]),d=parseInt(A[3]),p=Math.round(255*(A[5]===void 0?1:parseFloat(A[5]))),b.toColor(u,h,d,p);if(!C||!T)throw new Error("css.toColor: Unsupported css format");if(C.fillStyle=T,C.fillStyle=k,typeof C.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(C.fillRect(0,0,1,1),[u,h,d,p]=C.getImageData(0,0,1,1).data,p!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:m.toRgba(u,h,d,p),css:k}}}(g||(a.css=g={})),function(S){function C(T,k,A){const M=T/255,R=k/255,P=A/255;return .2126*(M<=.03928?M/12.92:Math.pow((M+.055)/1.055,2.4))+.7152*(R<=.03928?R/12.92:Math.pow((R+.055)/1.055,2.4))+.0722*(P<=.03928?P/12.92:Math.pow((P+.055)/1.055,2.4))}S.relativeLuminance=function(T){return C(T>>16&255,T>>8&255,255&T)},S.relativeLuminance2=C}(y||(a.rgb=y={})),function(S){function C(k,A,M){const R=k>>24&255,P=k>>16&255,L=k>>8&255;let z=A>>24&255,Q=A>>16&255,W=A>>8&255,V=w(y.relativeLuminance2(z,Q,W),y.relativeLuminance2(R,P,L));for(;V<M&&(z>0||Q>0||W>0);)z-=Math.max(0,Math.ceil(.1*z)),Q-=Math.max(0,Math.ceil(.1*Q)),W-=Math.max(0,Math.ceil(.1*W)),V=w(y.relativeLuminance2(z,Q,W),y.relativeLuminance2(R,P,L));return(z<<24|Q<<16|W<<8|255)>>>0}function T(k,A,M){const R=k>>24&255,P=k>>16&255,L=k>>8&255;let z=A>>24&255,Q=A>>16&255,W=A>>8&255,V=w(y.relativeLuminance2(z,Q,W),y.relativeLuminance2(R,P,L));for(;V<M&&(z<255||Q<255||W<255);)z=Math.min(255,z+Math.ceil(.1*(255-z))),Q=Math.min(255,Q+Math.ceil(.1*(255-Q))),W=Math.min(255,W+Math.ceil(.1*(255-W))),V=w(y.relativeLuminance2(z,Q,W),y.relativeLuminance2(R,P,L));return(z<<24|Q<<16|W<<8|255)>>>0}S.ensureContrastRatio=function(k,A,M){const R=y.relativeLuminance(k>>8),P=y.relativeLuminance(A>>8);if(w(R,P)<M){if(P<R){const Q=C(k,A,M),W=w(R,y.relativeLuminance(Q>>8));if(W<M){const V=T(k,A,M);return W>w(R,y.relativeLuminance(V>>8))?Q:V}return Q}const L=T(k,A,M),z=w(R,y.relativeLuminance(L>>8));if(z<M){const Q=C(k,A,M);return z>w(R,y.relativeLuminance(Q>>8))?L:Q}return L}},S.reduceLuminance=C,S.increaseLuminance=T,S.toChannels=function(k){return[k>>24&255,k>>16&255,k>>8&255,255&k]},S.toColor=function(k,A,M,R){return{css:m.toCss(k,A,M,R),rgba:m.toRgba(k,A,M,R)}}}(b||(a.rgba=b={})),a.toPaddedHex=_,a.contrastRatio=w},8969:(o,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.CoreTerminal=void 0;const l=c(844),u=c(2585),h=c(4348),d=c(7866),p=c(744),m=c(7302),v=c(6975),g=c(8460),y=c(1753),b=c(1480),_=c(7994),w=c(9282),S=c(5435),C=c(5981),T=c(2660);let k=!1;class A extends l.Disposable{get onScroll(){return this._onScrollApi||(this._onScrollApi=this.register(new g.EventEmitter),this._onScroll.event(R=>{var P;(P=this._onScrollApi)===null||P===void 0||P.fire(R.position)})),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(R){for(const P in R)this.optionsService.options[P]=R[P]}constructor(R){super(),this._windowsWrappingHeuristics=this.register(new l.MutableDisposable),this._onBinary=this.register(new g.EventEmitter),this.onBinary=this._onBinary.event,this._onData=this.register(new g.EventEmitter),this.onData=this._onData.event,this._onLineFeed=this.register(new g.EventEmitter),this.onLineFeed=this._onLineFeed.event,this._onResize=this.register(new g.EventEmitter),this.onResize=this._onResize.event,this._onWriteParsed=this.register(new g.EventEmitter),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this.register(new g.EventEmitter),this._instantiationService=new h.InstantiationService,this.optionsService=this.register(new m.OptionsService(R)),this._instantiationService.setService(u.IOptionsService,this.optionsService),this._bufferService=this.register(this._instantiationService.createInstance(p.BufferService)),this._instantiationService.setService(u.IBufferService,this._bufferService),this._logService=this.register(this._instantiationService.createInstance(d.LogService)),this._instantiationService.setService(u.ILogService,this._logService),this.coreService=this.register(this._instantiationService.createInstance(v.CoreService)),this._instantiationService.setService(u.ICoreService,this.coreService),this.coreMouseService=this.register(this._instantiationService.createInstance(y.CoreMouseService)),this._instantiationService.setService(u.ICoreMouseService,this.coreMouseService),this.unicodeService=this.register(this._instantiationService.createInstance(b.UnicodeService)),this._instantiationService.setService(u.IUnicodeService,this.unicodeService),this._charsetService=this._instantiationService.createInstance(_.CharsetService),this._instantiationService.setService(u.ICharsetService,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(T.OscLinkService),this._instantiationService.setService(u.IOscLinkService,this._oscLinkService),this._inputHandler=this.register(new S.InputHandler(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this.register((0,g.forwardEvent)(this._inputHandler.onLineFeed,this._onLineFeed)),this.register(this._inputHandler),this.register((0,g.forwardEvent)(this._bufferService.onResize,this._onResize)),this.register((0,g.forwardEvent)(this.coreService.onData,this._onData)),this.register((0,g.forwardEvent)(this.coreService.onBinary,this._onBinary)),this.register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom())),this.register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this.register(this.optionsService.onMultipleOptionChange(["windowsMode","windowsPty"],()=>this._handleWindowsPtyOptionChange())),this.register(this._bufferService.onScroll(P=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp,source:0}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this.register(this._inputHandler.onScroll(P=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp,source:0}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this.register(new C.WriteBuffer((P,L)=>this._inputHandler.parse(P,L))),this.register((0,g.forwardEvent)(this._writeBuffer.onWriteParsed,this._onWriteParsed))}write(R,P){this._writeBuffer.write(R,P)}writeSync(R,P){this._logService.logLevel<=u.LogLevelEnum.WARN&&!k&&(this._logService.warn("writeSync is unreliable and will be removed soon."),k=!0),this._writeBuffer.writeSync(R,P)}resize(R,P){isNaN(R)||isNaN(P)||(R=Math.max(R,p.MINIMUM_COLS),P=Math.max(P,p.MINIMUM_ROWS),this._bufferService.resize(R,P))}scroll(R,P=!1){this._bufferService.scroll(R,P)}scrollLines(R,P,L){this._bufferService.scrollLines(R,P,L)}scrollPages(R){this.scrollLines(R*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(R){const P=R-this._bufferService.buffer.ydisp;P!==0&&this.scrollLines(P)}registerEscHandler(R,P){return this._inputHandler.registerEscHandler(R,P)}registerDcsHandler(R,P){return this._inputHandler.registerDcsHandler(R,P)}registerCsiHandler(R,P){return this._inputHandler.registerCsiHandler(R,P)}registerOscHandler(R,P){return this._inputHandler.registerOscHandler(R,P)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let R=!1;const P=this.optionsService.rawOptions.windowsPty;P&&P.buildNumber!==void 0&&P.buildNumber!==void 0?R=P.backend==="conpty"&&P.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(R=!0),R?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){const R=[];R.push(this.onLineFeed(w.updateWindowsModeWrappedState.bind(null,this._bufferService))),R.push(this.registerCsiHandler({final:"H"},()=>((0,w.updateWindowsModeWrappedState)(this._bufferService),!1))),this._windowsWrappingHeuristics.value=(0,l.toDisposable)(()=>{for(const P of R)P.dispose()})}}}a.CoreTerminal=A},8460:(o,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.forwardEvent=a.EventEmitter=void 0,a.EventEmitter=class{constructor(){this._listeners=[],this._disposed=!1}get event(){return this._event||(this._event=c=>(this._listeners.push(c),{dispose:()=>{if(!this._disposed){for(let l=0;l<this._listeners.length;l++)if(this._listeners[l]===c)return void this._listeners.splice(l,1)}}})),this._event}fire(c,l){const u=[];for(let h=0;h<this._listeners.length;h++)u.push(this._listeners[h]);for(let h=0;h<u.length;h++)u[h].call(void 0,c,l)}dispose(){this.clearListeners(),this._disposed=!0}clearListeners(){this._listeners&&(this._listeners.length=0)}},a.forwardEvent=function(c,l){return c(u=>l.fire(u))}},5435:function(o,a,c){var l=this&&this.__decorate||function(V,N,O,H){var G,ee=arguments.length,ie=ee<3?N:H===null?H=Object.getOwnPropertyDescriptor(N,O):H;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")ie=Reflect.decorate(V,N,O,H);else for(var ve=V.length-1;ve>=0;ve--)(G=V[ve])&&(ie=(ee<3?G(ie):ee>3?G(N,O,ie):G(N,O))||ie);return ee>3&&ie&&Object.defineProperty(N,O,ie),ie},u=this&&this.__param||function(V,N){return function(O,H){N(O,H,V)}};Object.defineProperty(a,"__esModule",{value:!0}),a.InputHandler=a.WindowsOptionsReportType=void 0;const h=c(2584),d=c(7116),p=c(2015),m=c(844),v=c(482),g=c(8437),y=c(8460),b=c(643),_=c(511),w=c(3734),S=c(2585),C=c(6242),T=c(6351),k=c(5941),A={"(":0,")":1,"*":2,"+":3,"-":1,".":2},M=131072;function R(V,N){if(V>24)return N.setWinLines||!1;switch(V){case 1:return!!N.restoreWin;case 2:return!!N.minimizeWin;case 3:return!!N.setWinPosition;case 4:return!!N.setWinSizePixels;case 5:return!!N.raiseWin;case 6:return!!N.lowerWin;case 7:return!!N.refreshWin;case 8:return!!N.setWinSizeChars;case 9:return!!N.maximizeWin;case 10:return!!N.fullscreenWin;case 11:return!!N.getWinState;case 13:return!!N.getWinPosition;case 14:return!!N.getWinSizePixels;case 15:return!!N.getScreenSizePixels;case 16:return!!N.getCellSizePixels;case 18:return!!N.getWinSizeChars;case 19:return!!N.getScreenSizeChars;case 20:return!!N.getIconTitle;case 21:return!!N.getWinTitle;case 22:return!!N.pushTitle;case 23:return!!N.popTitle;case 24:return!!N.setWinLines}return!1}var P;(function(V){V[V.GET_WIN_SIZE_PIXELS=0]="GET_WIN_SIZE_PIXELS",V[V.GET_CELL_SIZE_PIXELS=1]="GET_CELL_SIZE_PIXELS"})(P||(a.WindowsOptionsReportType=P={}));let L=0;class z extends m.Disposable{getAttrData(){return this._curAttrData}constructor(N,O,H,G,ee,ie,ve,le,oe=new p.EscapeSequenceParser){super(),this._bufferService=N,this._charsetService=O,this._coreService=H,this._logService=G,this._optionsService=ee,this._oscLinkService=ie,this._coreMouseService=ve,this._unicodeService=le,this._parser=oe,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new v.StringToUtf32,this._utf8Decoder=new v.Utf8ToUtf32,this._workCell=new _.CellData,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=g.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=g.DEFAULT_ATTR_DATA.clone(),this._onRequestBell=this.register(new y.EventEmitter),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this.register(new y.EventEmitter),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this.register(new y.EventEmitter),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this.register(new y.EventEmitter),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this.register(new y.EventEmitter),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this.register(new y.EventEmitter),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this.register(new y.EventEmitter),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this.register(new y.EventEmitter),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this.register(new y.EventEmitter),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this.register(new y.EventEmitter),this.onLineFeed=this._onLineFeed.event,this._onScroll=this.register(new y.EventEmitter),this.onScroll=this._onScroll.event,this._onTitleChange=this.register(new y.EventEmitter),this.onTitleChange=this._onTitleChange.event,this._onColor=this.register(new y.EventEmitter),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this.register(this._parser),this._dirtyRowTracker=new Q(this._bufferService),this._activeBuffer=this._bufferService.buffer,this.register(this._bufferService.buffers.onBufferActivate(I=>this._activeBuffer=I.activeBuffer)),this._parser.setCsiHandlerFallback((I,K)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(I),params:K.toArray()})}),this._parser.setEscHandlerFallback(I=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(I)})}),this._parser.setExecuteHandlerFallback(I=>{this._logService.debug("Unknown EXECUTE code: ",{code:I})}),this._parser.setOscHandlerFallback((I,K,X)=>{this._logService.debug("Unknown OSC code: ",{identifier:I,action:K,data:X})}),this._parser.setDcsHandlerFallback((I,K,X)=>{K==="HOOK"&&(X=X.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(I),action:K,payload:X})}),this._parser.setPrintHandler((I,K,X)=>this.print(I,K,X)),this._parser.registerCsiHandler({final:"@"},I=>this.insertChars(I)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},I=>this.scrollLeft(I)),this._parser.registerCsiHandler({final:"A"},I=>this.cursorUp(I)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},I=>this.scrollRight(I)),this._parser.registerCsiHandler({final:"B"},I=>this.cursorDown(I)),this._parser.registerCsiHandler({final:"C"},I=>this.cursorForward(I)),this._parser.registerCsiHandler({final:"D"},I=>this.cursorBackward(I)),this._parser.registerCsiHandler({final:"E"},I=>this.cursorNextLine(I)),this._parser.registerCsiHandler({final:"F"},I=>this.cursorPrecedingLine(I)),this._parser.registerCsiHandler({final:"G"},I=>this.cursorCharAbsolute(I)),this._parser.registerCsiHandler({final:"H"},I=>this.cursorPosition(I)),this._parser.registerCsiHandler({final:"I"},I=>this.cursorForwardTab(I)),this._parser.registerCsiHandler({final:"J"},I=>this.eraseInDisplay(I,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},I=>this.eraseInDisplay(I,!0)),this._parser.registerCsiHandler({final:"K"},I=>this.eraseInLine(I,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},I=>this.eraseInLine(I,!0)),this._parser.registerCsiHandler({final:"L"},I=>this.insertLines(I)),this._parser.registerCsiHandler({final:"M"},I=>this.deleteLines(I)),this._parser.registerCsiHandler({final:"P"},I=>this.deleteChars(I)),this._parser.registerCsiHandler({final:"S"},I=>this.scrollUp(I)),this._parser.registerCsiHandler({final:"T"},I=>this.scrollDown(I)),this._parser.registerCsiHandler({final:"X"},I=>this.eraseChars(I)),this._parser.registerCsiHandler({final:"Z"},I=>this.cursorBackwardTab(I)),this._parser.registerCsiHandler({final:"`"},I=>this.charPosAbsolute(I)),this._parser.registerCsiHandler({final:"a"},I=>this.hPositionRelative(I)),this._parser.registerCsiHandler({final:"b"},I=>this.repeatPrecedingCharacter(I)),this._parser.registerCsiHandler({final:"c"},I=>this.sendDeviceAttributesPrimary(I)),this._parser.registerCsiHandler({prefix:">",final:"c"},I=>this.sendDeviceAttributesSecondary(I)),this._parser.registerCsiHandler({final:"d"},I=>this.linePosAbsolute(I)),this._parser.registerCsiHandler({final:"e"},I=>this.vPositionRelative(I)),this._parser.registerCsiHandler({final:"f"},I=>this.hVPosition(I)),this._parser.registerCsiHandler({final:"g"},I=>this.tabClear(I)),this._parser.registerCsiHandler({final:"h"},I=>this.setMode(I)),this._parser.registerCsiHandler({prefix:"?",final:"h"},I=>this.setModePrivate(I)),this._parser.registerCsiHandler({final:"l"},I=>this.resetMode(I)),this._parser.registerCsiHandler({prefix:"?",final:"l"},I=>this.resetModePrivate(I)),this._parser.registerCsiHandler({final:"m"},I=>this.charAttributes(I)),this._parser.registerCsiHandler({final:"n"},I=>this.deviceStatus(I)),this._parser.registerCsiHandler({prefix:"?",final:"n"},I=>this.deviceStatusPrivate(I)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},I=>this.softReset(I)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},I=>this.setCursorStyle(I)),this._parser.registerCsiHandler({final:"r"},I=>this.setScrollRegion(I)),this._parser.registerCsiHandler({final:"s"},I=>this.saveCursor(I)),this._parser.registerCsiHandler({final:"t"},I=>this.windowOptions(I)),this._parser.registerCsiHandler({final:"u"},I=>this.restoreCursor(I)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},I=>this.insertColumns(I)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},I=>this.deleteColumns(I)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},I=>this.selectProtected(I)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},I=>this.requestMode(I,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},I=>this.requestMode(I,!1)),this._parser.setExecuteHandler(h.C0.BEL,()=>this.bell()),this._parser.setExecuteHandler(h.C0.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(h.C0.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(h.C0.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(h.C0.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(h.C0.BS,()=>this.backspace()),this._parser.setExecuteHandler(h.C0.HT,()=>this.tab()),this._parser.setExecuteHandler(h.C0.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(h.C0.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(h.C1.IND,()=>this.index()),this._parser.setExecuteHandler(h.C1.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(h.C1.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new C.OscHandler(I=>(this.setTitle(I),this.setIconName(I),!0))),this._parser.registerOscHandler(1,new C.OscHandler(I=>this.setIconName(I))),this._parser.registerOscHandler(2,new C.OscHandler(I=>this.setTitle(I))),this._parser.registerOscHandler(4,new C.OscHandler(I=>this.setOrReportIndexedColor(I))),this._parser.registerOscHandler(8,new C.OscHandler(I=>this.setHyperlink(I))),this._parser.registerOscHandler(10,new C.OscHandler(I=>this.setOrReportFgColor(I))),this._parser.registerOscHandler(11,new C.OscHandler(I=>this.setOrReportBgColor(I))),this._parser.registerOscHandler(12,new C.OscHandler(I=>this.setOrReportCursorColor(I))),this._parser.registerOscHandler(104,new C.OscHandler(I=>this.restoreIndexedColor(I))),this._parser.registerOscHandler(110,new C.OscHandler(I=>this.restoreFgColor(I))),this._parser.registerOscHandler(111,new C.OscHandler(I=>this.restoreBgColor(I))),this._parser.registerOscHandler(112,new C.OscHandler(I=>this.restoreCursorColor(I))),this._parser.registerEscHandler({final:"7"},()=>this.saveCursor()),this._parser.registerEscHandler({final:"8"},()=>this.restoreCursor()),this._parser.registerEscHandler({final:"D"},()=>this.index()),this._parser.registerEscHandler({final:"E"},()=>this.nextLine()),this._parser.registerEscHandler({final:"H"},()=>this.tabSet()),this._parser.registerEscHandler({final:"M"},()=>this.reverseIndex()),this._parser.registerEscHandler({final:"="},()=>this.keypadApplicationMode()),this._parser.registerEscHandler({final:">"},()=>this.keypadNumericMode()),this._parser.registerEscHandler({final:"c"},()=>this.fullReset()),this._parser.registerEscHandler({final:"n"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"o"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"|"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"}"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"~"},()=>this.setgLevel(1)),this._parser.registerEscHandler({intermediates:"%",final:"@"},()=>this.selectDefaultCharset()),this._parser.registerEscHandler({intermediates:"%",final:"G"},()=>this.selectDefaultCharset());for(const I in d.CHARSETS)this._parser.registerEscHandler({intermediates:"(",final:I},()=>this.selectCharset("("+I)),this._parser.registerEscHandler({intermediates:")",final:I},()=>this.selectCharset(")"+I)),this._parser.registerEscHandler({intermediates:"*",final:I},()=>this.selectCharset("*"+I)),this._parser.registerEscHandler({intermediates:"+",final:I},()=>this.selectCharset("+"+I)),this._parser.registerEscHandler({intermediates:"-",final:I},()=>this.selectCharset("-"+I)),this._parser.registerEscHandler({intermediates:".",final:I},()=>this.selectCharset("."+I)),this._parser.registerEscHandler({intermediates:"/",final:I},()=>this.selectCharset("/"+I));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(I=>(this._logService.error("Parsing error: ",I),I)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new T.DcsHandler((I,K)=>this.requestStatusString(I,K)))}_preserveStack(N,O,H,G){this._parseStack.paused=!0,this._parseStack.cursorStartX=N,this._parseStack.cursorStartY=O,this._parseStack.decodedLength=H,this._parseStack.position=G}_logSlowResolvingAsync(N){this._logService.logLevel<=S.LogLevelEnum.WARN&&Promise.race([N,new Promise((O,H)=>setTimeout(()=>H("#SLOW_TIMEOUT"),5e3))]).catch(O=>{if(O!=="#SLOW_TIMEOUT")throw O;console.warn("async parser handler taking longer than 5000 ms")})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(N,O){let H,G=this._activeBuffer.x,ee=this._activeBuffer.y,ie=0;const ve=this._parseStack.paused;if(ve){if(H=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,O))return this._logSlowResolvingAsync(H),H;G=this._parseStack.cursorStartX,ee=this._parseStack.cursorStartY,this._parseStack.paused=!1,N.length>M&&(ie=this._parseStack.position+M)}if(this._logService.logLevel<=S.LogLevelEnum.DEBUG&&this._logService.debug("parsing data"+(typeof N=="string"?` "${N}"`:` "${Array.prototype.map.call(N,le=>String.fromCharCode(le)).join("")}"`),typeof N=="string"?N.split("").map(le=>le.charCodeAt(0)):N),this._parseBuffer.length<N.length&&this._parseBuffer.length<M&&(this._parseBuffer=new Uint32Array(Math.min(N.length,M))),ve||this._dirtyRowTracker.clearRange(),N.length>M)for(let le=ie;le<N.length;le+=M){const oe=le+M<N.length?le+M:N.length,I=typeof N=="string"?this._stringDecoder.decode(N.substring(le,oe),this._parseBuffer):this._utf8Decoder.decode(N.subarray(le,oe),this._parseBuffer);if(H=this._parser.parse(this._parseBuffer,I))return this._preserveStack(G,ee,I,le),this._logSlowResolvingAsync(H),H}else if(!ve){const le=typeof N=="string"?this._stringDecoder.decode(N,this._parseBuffer):this._utf8Decoder.decode(N,this._parseBuffer);if(H=this._parser.parse(this._parseBuffer,le))return this._preserveStack(G,ee,le,0),this._logSlowResolvingAsync(H),H}this._activeBuffer.x===G&&this._activeBuffer.y===ee||this._onCursorMove.fire(),this._onRequestRefreshRows.fire(this._dirtyRowTracker.start,this._dirtyRowTracker.end)}print(N,O,H){let G,ee;const ie=this._charsetService.charset,ve=this._optionsService.rawOptions.screenReaderMode,le=this._bufferService.cols,oe=this._coreService.decPrivateModes.wraparound,I=this._coreService.modes.insertMode,K=this._curAttrData;let X=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&H-O>0&&X.getWidth(this._activeBuffer.x-1)===2&&X.setCellFromCodePoint(this._activeBuffer.x-1,0,1,K.fg,K.bg,K.extended);for(let J=O;J<H;++J){if(G=N[J],ee=this._unicodeService.wcwidth(G),G<127&&ie){const he=ie[String.fromCharCode(G)];he&&(G=he.charCodeAt(0))}if(ve&&this._onA11yChar.fire((0,v.stringFromCodePoint)(G)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),ee||!this._activeBuffer.x){if(this._activeBuffer.x+ee-1>=le){if(oe){for(;this._activeBuffer.x<le;)X.setCellFromCodePoint(this._activeBuffer.x++,0,1,K.fg,K.bg,K.extended);this._activeBuffer.x=0,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),X=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)}else if(this._activeBuffer.x=le-1,ee===2)continue}if(I&&(X.insertCells(this._activeBuffer.x,ee,this._activeBuffer.getNullCell(K),K),X.getWidth(le-1)===2&&X.setCellFromCodePoint(le-1,b.NULL_CELL_CODE,b.NULL_CELL_WIDTH,K.fg,K.bg,K.extended)),X.setCellFromCodePoint(this._activeBuffer.x++,G,ee,K.fg,K.bg,K.extended),ee>0)for(;--ee;)X.setCellFromCodePoint(this._activeBuffer.x++,0,0,K.fg,K.bg,K.extended)}else X.getWidth(this._activeBuffer.x-1)?X.addCodepointToCell(this._activeBuffer.x-1,G):X.addCodepointToCell(this._activeBuffer.x-2,G)}H-O>0&&(X.loadCell(this._activeBuffer.x-1,this._workCell),this._workCell.getWidth()===2||this._workCell.getCode()>65535?this._parser.precedingCodepoint=0:this._workCell.isCombined()?this._parser.precedingCodepoint=this._workCell.getChars().charCodeAt(0):this._parser.precedingCodepoint=this._workCell.content),this._activeBuffer.x<le&&H-O>0&&X.getWidth(this._activeBuffer.x)===0&&!X.hasContent(this._activeBuffer.x)&&X.setCellFromCodePoint(this._activeBuffer.x,0,1,K.fg,K.bg,K.extended),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(N,O){return N.final!=="t"||N.prefix||N.intermediates?this._parser.registerCsiHandler(N,O):this._parser.registerCsiHandler(N,H=>!R(H.params[0],this._optionsService.rawOptions.windowOptions)||O(H))}registerDcsHandler(N,O){return this._parser.registerDcsHandler(N,new T.DcsHandler(O))}registerEscHandler(N,O){return this._parser.registerEscHandler(N,O)}registerOscHandler(N,O){return this._parser.registerOscHandler(N,new C.OscHandler(O))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){var N;if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&(!((N=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y))===null||N===void 0)&&N.isWrapped)){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;const O=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);O.hasWidth(this._activeBuffer.x)&&!O.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;const N=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-N),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(N=this._bufferService.cols-1){this._activeBuffer.x=Math.min(N,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(N,O){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=N,this._activeBuffer.y=this._activeBuffer.scrollTop+O):(this._activeBuffer.x=N,this._activeBuffer.y=O),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(N,O){this._restrictCursor(),this._setCursor(this._activeBuffer.x+N,this._activeBuffer.y+O)}cursorUp(N){const O=this._activeBuffer.y-this._activeBuffer.scrollTop;return O>=0?this._moveCursor(0,-Math.min(O,N.params[0]||1)):this._moveCursor(0,-(N.params[0]||1)),!0}cursorDown(N){const O=this._activeBuffer.scrollBottom-this._activeBuffer.y;return O>=0?this._moveCursor(0,Math.min(O,N.params[0]||1)):this._moveCursor(0,N.params[0]||1),!0}cursorForward(N){return this._moveCursor(N.params[0]||1,0),!0}cursorBackward(N){return this._moveCursor(-(N.params[0]||1),0),!0}cursorNextLine(N){return this.cursorDown(N),this._activeBuffer.x=0,!0}cursorPrecedingLine(N){return this.cursorUp(N),this._activeBuffer.x=0,!0}cursorCharAbsolute(N){return this._setCursor((N.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(N){return this._setCursor(N.length>=2?(N.params[1]||1)-1:0,(N.params[0]||1)-1),!0}charPosAbsolute(N){return this._setCursor((N.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(N){return this._moveCursor(N.params[0]||1,0),!0}linePosAbsolute(N){return this._setCursor(this._activeBuffer.x,(N.params[0]||1)-1),!0}vPositionRelative(N){return this._moveCursor(0,N.params[0]||1),!0}hVPosition(N){return this.cursorPosition(N),!0}tabClear(N){const O=N.params[0];return O===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:O===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(N){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let O=N.params[0]||1;for(;O--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(N){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let O=N.params[0]||1;for(;O--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(N){const O=N.params[0];return O===1&&(this._curAttrData.bg|=536870912),O!==2&&O!==0||(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(N,O,H,G=!1,ee=!1){const ie=this._activeBuffer.lines.get(this._activeBuffer.ybase+N);ie.replaceCells(O,H,this._activeBuffer.getNullCell(this._eraseAttrData()),this._eraseAttrData(),ee),G&&(ie.isWrapped=!1)}_resetBufferLine(N,O=!1){const H=this._activeBuffer.lines.get(this._activeBuffer.ybase+N);H&&(H.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),O),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+N),H.isWrapped=!1)}eraseInDisplay(N,O=!1){let H;switch(this._restrictCursor(this._bufferService.cols),N.params[0]){case 0:for(H=this._activeBuffer.y,this._dirtyRowTracker.markDirty(H),this._eraseInBufferLine(H++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,O);H<this._bufferService.rows;H++)this._resetBufferLine(H,O);this._dirtyRowTracker.markDirty(H);break;case 1:for(H=this._activeBuffer.y,this._dirtyRowTracker.markDirty(H),this._eraseInBufferLine(H,0,this._activeBuffer.x+1,!0,O),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get(H+1).isWrapped=!1);H--;)this._resetBufferLine(H,O);this._dirtyRowTracker.markDirty(0);break;case 2:for(H=this._bufferService.rows,this._dirtyRowTracker.markDirty(H-1);H--;)this._resetBufferLine(H,O);this._dirtyRowTracker.markDirty(0);break;case 3:const G=this._activeBuffer.lines.length-this._bufferService.rows;G>0&&(this._activeBuffer.lines.trimStart(G),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-G,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-G,0),this._onScroll.fire(0))}return!0}eraseInLine(N,O=!1){switch(this._restrictCursor(this._bufferService.cols),N.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,O);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,O);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,O)}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(N){this._restrictCursor();let O=N.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const H=this._activeBuffer.ybase+this._activeBuffer.y,G=this._bufferService.rows-1-this._activeBuffer.scrollBottom,ee=this._bufferService.rows-1+this._activeBuffer.ybase-G+1;for(;O--;)this._activeBuffer.lines.splice(ee-1,1),this._activeBuffer.lines.splice(H,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}deleteLines(N){this._restrictCursor();let O=N.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const H=this._activeBuffer.ybase+this._activeBuffer.y;let G;for(G=this._bufferService.rows-1-this._activeBuffer.scrollBottom,G=this._bufferService.rows-1+this._activeBuffer.ybase-G;O--;)this._activeBuffer.lines.splice(H,1),this._activeBuffer.lines.splice(G,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}insertChars(N){this._restrictCursor();const O=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return O&&(O.insertCells(this._activeBuffer.x,N.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData()),this._eraseAttrData()),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}deleteChars(N){this._restrictCursor();const O=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return O&&(O.deleteCells(this._activeBuffer.x,N.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData()),this._eraseAttrData()),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}scrollUp(N){let O=N.params[0]||1;for(;O--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollDown(N){let O=N.params[0]||1;for(;O--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,0,this._activeBuffer.getBlankLine(g.DEFAULT_ATTR_DATA));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollLeft(N){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const O=N.params[0]||1;for(let H=this._activeBuffer.scrollTop;H<=this._activeBuffer.scrollBottom;++H){const G=this._activeBuffer.lines.get(this._activeBuffer.ybase+H);G.deleteCells(0,O,this._activeBuffer.getNullCell(this._eraseAttrData()),this._eraseAttrData()),G.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollRight(N){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const O=N.params[0]||1;for(let H=this._activeBuffer.scrollTop;H<=this._activeBuffer.scrollBottom;++H){const G=this._activeBuffer.lines.get(this._activeBuffer.ybase+H);G.insertCells(0,O,this._activeBuffer.getNullCell(this._eraseAttrData()),this._eraseAttrData()),G.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}insertColumns(N){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const O=N.params[0]||1;for(let H=this._activeBuffer.scrollTop;H<=this._activeBuffer.scrollBottom;++H){const G=this._activeBuffer.lines.get(this._activeBuffer.ybase+H);G.insertCells(this._activeBuffer.x,O,this._activeBuffer.getNullCell(this._eraseAttrData()),this._eraseAttrData()),G.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}deleteColumns(N){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const O=N.params[0]||1;for(let H=this._activeBuffer.scrollTop;H<=this._activeBuffer.scrollBottom;++H){const G=this._activeBuffer.lines.get(this._activeBuffer.ybase+H);G.deleteCells(this._activeBuffer.x,O,this._activeBuffer.getNullCell(this._eraseAttrData()),this._eraseAttrData()),G.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}eraseChars(N){this._restrictCursor();const O=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return O&&(O.replaceCells(this._activeBuffer.x,this._activeBuffer.x+(N.params[0]||1),this._activeBuffer.getNullCell(this._eraseAttrData()),this._eraseAttrData()),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}repeatPrecedingCharacter(N){if(!this._parser.precedingCodepoint)return!0;const O=N.params[0]||1,H=new Uint32Array(O);for(let G=0;G<O;++G)H[G]=this._parser.precedingCodepoint;return this.print(H,0,H.length),!0}sendDeviceAttributesPrimary(N){return N.params[0]>0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(h.C0.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(h.C0.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(N){return N.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(h.C0.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(h.C0.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(N.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(h.C0.ESC+"[>83;40003;0c")),!0}_is(N){return(this._optionsService.rawOptions.termName+"").indexOf(N)===0}setMode(N){for(let O=0;O<N.length;O++)switch(N.params[O]){case 4:this._coreService.modes.insertMode=!0;break;case 20:this._optionsService.options.convertEol=!0}return!0}setModePrivate(N){for(let O=0;O<N.length;O++)switch(N.params[O]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!0;break;case 2:this._charsetService.setgCharset(0,d.DEFAULT_CHARSET),this._charsetService.setgCharset(1,d.DEFAULT_CHARSET),this._charsetService.setgCharset(2,d.DEFAULT_CHARSET),this._charsetService.setgCharset(3,d.DEFAULT_CHARSET);break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(132,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!0,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!0;break;case 12:this._optionsService.options.cursorBlink=!0;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!0;break;case 66:this._logService.debug("Serial port requested application keypad."),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire();break;case 9:this._coreMouseService.activeProtocol="X10";break;case 1e3:this._coreMouseService.activeProtocol="VT200";break;case 1002:this._coreMouseService.activeProtocol="DRAG";break;case 1003:this._coreMouseService.activeProtocol="ANY";break;case 1004:this._coreService.decPrivateModes.sendFocus=!0,this._onRequestSendFocus.fire();break;case 1005:this._logService.debug("DECSET 1005 not supported (see #2507)");break;case 1006:this._coreMouseService.activeEncoding="SGR";break;case 1015:this._logService.debug("DECSET 1015 not supported (see #2507)");break;case 1016:this._coreMouseService.activeEncoding="SGR_PIXELS";break;case 25:this._coreService.isCursorHidden=!1;break;case 1048:this.saveCursor();break;case 1049:this.saveCursor();case 47:case 1047:this._bufferService.buffers.activateAltBuffer(this._eraseAttrData()),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(0,this._bufferService.rows-1),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!0}return!0}resetMode(N){for(let O=0;O<N.length;O++)switch(N.params[O]){case 4:this._coreService.modes.insertMode=!1;break;case 20:this._optionsService.options.convertEol=!1}return!0}resetModePrivate(N){for(let O=0;O<N.length;O++)switch(N.params[O]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!1;break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(80,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!1,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!1;break;case 12:this._optionsService.options.cursorBlink=!1;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!1;break;case 66:this._logService.debug("Switching back to normal keypad."),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire();break;case 9:case 1e3:case 1002:case 1003:this._coreMouseService.activeProtocol="NONE";break;case 1004:this._coreService.decPrivateModes.sendFocus=!1;break;case 1005:this._logService.debug("DECRST 1005 not supported (see #2507)");break;case 1006:case 1016:this._coreMouseService.activeEncoding="DEFAULT";break;case 1015:this._logService.debug("DECRST 1015 not supported (see #2507)");break;case 25:this._coreService.isCursorHidden=!0;break;case 1048:this.restoreCursor();break;case 1049:case 47:case 1047:this._bufferService.buffers.activateNormalBuffer(),N.params[O]===1049&&this.restoreCursor(),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(0,this._bufferService.rows-1),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!1}return!0}requestMode(N,O){const H=this._coreService.decPrivateModes,{activeProtocol:G,activeEncoding:ee}=this._coreMouseService,ie=this._coreService,{buffers:ve,cols:le}=this._bufferService,{active:oe,alt:I}=ve,K=this._optionsService.rawOptions,X=Re=>Re?1:2,J=N.params[0];return he=J,be=O?J===2?4:J===4?X(ie.modes.insertMode):J===12?3:J===20?X(K.convertEol):0:J===1?X(H.applicationCursorKeys):J===3?K.windowOptions.setWinLines?le===80?2:le===132?1:0:0:J===6?X(H.origin):J===7?X(H.wraparound):J===8?3:J===9?X(G==="X10"):J===12?X(K.cursorBlink):J===25?X(!ie.isCursorHidden):J===45?X(H.reverseWraparound):J===66?X(H.applicationKeypad):J===67?4:J===1e3?X(G==="VT200"):J===1002?X(G==="DRAG"):J===1003?X(G==="ANY"):J===1004?X(H.sendFocus):J===1005?4:J===1006?X(ee==="SGR"):J===1015?4:J===1016?X(ee==="SGR_PIXELS"):J===1048?1:J===47||J===1047||J===1049?X(oe===I):J===2004?X(H.bracketedPasteMode):0,ie.triggerDataEvent(`${h.C0.ESC}[${O?"":"?"}${he};${be}$y`),!0;var he,be}_updateAttrColor(N,O,H,G,ee){return O===2?(N|=50331648,N&=-16777216,N|=w.AttributeData.fromColorRGB([H,G,ee])):O===5&&(N&=-50331904,N|=33554432|255&H),N}_extractColor(N,O,H){const G=[0,0,-1,0,0,0];let ee=0,ie=0;do{if(G[ie+ee]=N.params[O+ie],N.hasSubParams(O+ie)){const ve=N.getSubParams(O+ie);let le=0;do G[1]===5&&(ee=1),G[ie+le+1+ee]=ve[le];while(++le<ve.length&&le+ie+1+ee<G.length);break}if(G[1]===5&&ie+ee>=2||G[1]===2&&ie+ee>=5)break;G[1]&&(ee=1)}while(++ie+O<N.length&&ie+ee<G.length);for(let ve=2;ve<G.length;++ve)G[ve]===-1&&(G[ve]=0);switch(G[0]){case 38:H.fg=this._updateAttrColor(H.fg,G[1],G[3],G[4],G[5]);break;case 48:H.bg=this._updateAttrColor(H.bg,G[1],G[3],G[4],G[5]);break;case 58:H.extended=H.extended.clone(),H.extended.underlineColor=this._updateAttrColor(H.extended.underlineColor,G[1],G[3],G[4],G[5])}return ie}_processUnderline(N,O){O.extended=O.extended.clone(),(!~N||N>5)&&(N=1),O.extended.underlineStyle=N,O.fg|=268435456,N===0&&(O.fg&=-268435457),O.updateExtended()}_processSGR0(N){N.fg=g.DEFAULT_ATTR_DATA.fg,N.bg=g.DEFAULT_ATTR_DATA.bg,N.extended=N.extended.clone(),N.extended.underlineStyle=0,N.extended.underlineColor&=-67108864,N.updateExtended()}charAttributes(N){if(N.length===1&&N.params[0]===0)return this._processSGR0(this._curAttrData),!0;const O=N.length;let H;const G=this._curAttrData;for(let ee=0;ee<O;ee++)H=N.params[ee],H>=30&&H<=37?(G.fg&=-50331904,G.fg|=16777216|H-30):H>=40&&H<=47?(G.bg&=-50331904,G.bg|=16777216|H-40):H>=90&&H<=97?(G.fg&=-50331904,G.fg|=16777224|H-90):H>=100&&H<=107?(G.bg&=-50331904,G.bg|=16777224|H-100):H===0?this._processSGR0(G):H===1?G.fg|=134217728:H===3?G.bg|=67108864:H===4?(G.fg|=268435456,this._processUnderline(N.hasSubParams(ee)?N.getSubParams(ee)[0]:1,G)):H===5?G.fg|=536870912:H===7?G.fg|=67108864:H===8?G.fg|=1073741824:H===9?G.fg|=2147483648:H===2?G.bg|=134217728:H===21?this._processUnderline(2,G):H===22?(G.fg&=-134217729,G.bg&=-134217729):H===23?G.bg&=-67108865:H===24?(G.fg&=-268435457,this._processUnderline(0,G)):H===25?G.fg&=-536870913:H===27?G.fg&=-67108865:H===28?G.fg&=-1073741825:H===29?G.fg&=2147483647:H===39?(G.fg&=-67108864,G.fg|=16777215&g.DEFAULT_ATTR_DATA.fg):H===49?(G.bg&=-67108864,G.bg|=16777215&g.DEFAULT_ATTR_DATA.bg):H===38||H===48||H===58?ee+=this._extractColor(N,ee,G):H===53?G.bg|=1073741824:H===55?G.bg&=-1073741825:H===59?(G.extended=G.extended.clone(),G.extended.underlineColor=-1,G.updateExtended()):H===100?(G.fg&=-67108864,G.fg|=16777215&g.DEFAULT_ATTR_DATA.fg,G.bg&=-67108864,G.bg|=16777215&g.DEFAULT_ATTR_DATA.bg):this._logService.debug("Unknown SGR attribute: %d.",H);return!0}deviceStatus(N){switch(N.params[0]){case 5:this._coreService.triggerDataEvent(`${h.C0.ESC}[0n`);break;case 6:const O=this._activeBuffer.y+1,H=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${h.C0.ESC}[${O};${H}R`)}return!0}deviceStatusPrivate(N){if(N.params[0]===6){const O=this._activeBuffer.y+1,H=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${h.C0.ESC}[?${O};${H}R`)}return!0}softReset(N){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=g.DEFAULT_ATTR_DATA.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(N){const O=N.params[0]||1;switch(O){case 1:case 2:this._optionsService.options.cursorStyle="block";break;case 3:case 4:this._optionsService.options.cursorStyle="underline";break;case 5:case 6:this._optionsService.options.cursorStyle="bar"}const H=O%2==1;return this._optionsService.options.cursorBlink=H,!0}setScrollRegion(N){const O=N.params[0]||1;let H;return(N.length<2||(H=N.params[1])>this._bufferService.rows||H===0)&&(H=this._bufferService.rows),H>O&&(this._activeBuffer.scrollTop=O-1,this._activeBuffer.scrollBottom=H-1,this._setCursor(0,0)),!0}windowOptions(N){if(!R(N.params[0],this._optionsService.rawOptions.windowOptions))return!0;const O=N.length>1?N.params[1]:0;switch(N.params[0]){case 14:O!==2&&this._onRequestWindowsOptionsReport.fire(P.GET_WIN_SIZE_PIXELS);break;case 16:this._onRequestWindowsOptionsReport.fire(P.GET_CELL_SIZE_PIXELS);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${h.C0.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:O!==0&&O!==2||(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>10&&this._windowTitleStack.shift()),O!==0&&O!==1||(this._iconNameStack.push(this._iconName),this._iconNameStack.length>10&&this._iconNameStack.shift());break;case 23:O!==0&&O!==2||this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),O!==0&&O!==1||this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop())}return!0}saveCursor(N){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(N){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(N){return this._windowTitle=N,this._onTitleChange.fire(N),!0}setIconName(N){return this._iconName=N,!0}setOrReportIndexedColor(N){const O=[],H=N.split(";");for(;H.length>1;){const G=H.shift(),ee=H.shift();if(/^\d+$/.exec(G)){const ie=parseInt(G);if(W(ie))if(ee==="?")O.push({type:0,index:ie});else{const ve=(0,k.parseColor)(ee);ve&&O.push({type:1,index:ie,color:ve})}}}return O.length&&this._onColor.fire(O),!0}setHyperlink(N){const O=N.split(";");return!(O.length<2)&&(O[1]?this._createHyperlink(O[0],O[1]):!O[0]&&this._finishHyperlink())}_createHyperlink(N,O){this._getCurrentLinkId()&&this._finishHyperlink();const H=N.split(":");let G;const ee=H.findIndex(ie=>ie.startsWith("id="));return ee!==-1&&(G=H[ee].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:G,uri:O}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(N,O){const H=N.split(";");for(let G=0;G<H.length&&!(O>=this._specialColors.length);++G,++O)if(H[G]==="?")this._onColor.fire([{type:0,index:this._specialColors[O]}]);else{const ee=(0,k.parseColor)(H[G]);ee&&this._onColor.fire([{type:1,index:this._specialColors[O],color:ee}])}return!0}setOrReportFgColor(N){return this._setOrReportSpecialColor(N,0)}setOrReportBgColor(N){return this._setOrReportSpecialColor(N,1)}setOrReportCursorColor(N){return this._setOrReportSpecialColor(N,2)}restoreIndexedColor(N){if(!N)return this._onColor.fire([{type:2}]),!0;const O=[],H=N.split(";");for(let G=0;G<H.length;++G)if(/^\d+$/.exec(H[G])){const ee=parseInt(H[G]);W(ee)&&O.push({type:2,index:ee})}return O.length&&this._onColor.fire(O),!0}restoreFgColor(N){return this._onColor.fire([{type:2,index:256}]),!0}restoreBgColor(N){return this._onColor.fire([{type:2,index:257}]),!0}restoreCursorColor(N){return this._onColor.fire([{type:2,index:258}]),!0}nextLine(){return this._activeBuffer.x=0,this.index(),!0}keypadApplicationMode(){return this._logService.debug("Serial port requested application keypad."),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire(),!0}keypadNumericMode(){return this._logService.debug("Switching back to normal keypad."),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire(),!0}selectDefaultCharset(){return this._charsetService.setgLevel(0),this._charsetService.setgCharset(0,d.DEFAULT_CHARSET),!0}selectCharset(N){return N.length!==2?(this.selectDefaultCharset(),!0):(N[0]==="/"||this._charsetService.setgCharset(A[N[0]],d.CHARSETS[N[1]]||d.DEFAULT_CHARSET),!0)}index(){return this._restrictCursor(),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){const N=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,N,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=g.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=g.DEFAULT_ATTR_DATA.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=67108863&this._curAttrData.bg,this._eraseAttrDataInternal}setgLevel(N){return this._charsetService.setgLevel(N),!0}screenAlignmentPattern(){const N=new _.CellData;N.content=4194373,N.fg=this._curAttrData.fg,N.bg=this._curAttrData.bg,this._setCursor(0,0);for(let O=0;O<this._bufferService.rows;++O){const H=this._activeBuffer.ybase+this._activeBuffer.y+O,G=this._activeBuffer.lines.get(H);G&&(G.fill(N),G.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(N,O){const H=this._bufferService.buffer,G=this._optionsService.rawOptions;return(ee=>(this._coreService.triggerDataEvent(`${h.C0.ESC}${ee}${h.C0.ESC}\\`),!0))(N==='"q'?`P1$r${this._curAttrData.isProtected()?1:0}"q`:N==='"p'?'P1$r61;1"p':N==="r"?`P1$r${H.scrollTop+1};${H.scrollBottom+1}r`:N==="m"?"P1$r0m":N===" q"?`P1$r${{block:2,underline:4,bar:6}[G.cursorStyle]-(G.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(N,O){this._dirtyRowTracker.markRangeDirty(N,O)}}a.InputHandler=z;let Q=class{constructor(V){this._bufferService=V,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(V){V<this.start?this.start=V:V>this.end&&(this.end=V)}markRangeDirty(V,N){V>N&&(L=V,V=N,N=L),V<this.start&&(this.start=V),N>this.end&&(this.end=N)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};function W(V){return 0<=V&&V<256}Q=l([u(0,S.IBufferService)],Q)},844:(o,a)=>{function c(l){for(const u of l)u.dispose();l.length=0}Object.defineProperty(a,"__esModule",{value:!0}),a.getDisposeArrayDisposable=a.disposeArray=a.toDisposable=a.MutableDisposable=a.Disposable=void 0,a.Disposable=class{constructor(){this._disposables=[],this._isDisposed=!1}dispose(){this._isDisposed=!0;for(const l of this._disposables)l.dispose();this._disposables.length=0}register(l){return this._disposables.push(l),l}unregister(l){const u=this._disposables.indexOf(l);u!==-1&&this._disposables.splice(u,1)}},a.MutableDisposable=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(l){var u;this._isDisposed||l===this._value||((u=this._value)===null||u===void 0||u.dispose(),this._value=l)}clear(){this.value=void 0}dispose(){var l;this._isDisposed=!0,(l=this._value)===null||l===void 0||l.dispose(),this._value=void 0}},a.toDisposable=function(l){return{dispose:l}},a.disposeArray=c,a.getDisposeArrayDisposable=function(l){return{dispose:()=>c(l)}}},1505:(o,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.FourKeyMap=a.TwoKeyMap=void 0;class c{constructor(){this._data={}}set(u,h,d){this._data[u]||(this._data[u]={}),this._data[u][h]=d}get(u,h){return this._data[u]?this._data[u][h]:void 0}clear(){this._data={}}}a.TwoKeyMap=c,a.FourKeyMap=class{constructor(){this._data=new c}set(l,u,h,d,p){this._data.get(l,u)||this._data.set(l,u,new c),this._data.get(l,u).set(h,d,p)}get(l,u,h,d){var p;return(p=this._data.get(l,u))===null||p===void 0?void 0:p.get(h,d)}clear(){this._data.clear()}}},6114:(o,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.isChromeOS=a.isLinux=a.isWindows=a.isIphone=a.isIpad=a.isMac=a.getSafariVersion=a.isSafari=a.isLegacyEdge=a.isFirefox=a.isNode=void 0,a.isNode=typeof navigator>"u";const c=a.isNode?"node":navigator.userAgent,l=a.isNode?"node":navigator.platform;a.isFirefox=c.includes("Firefox"),a.isLegacyEdge=c.includes("Edge"),a.isSafari=/^((?!chrome|android).)*safari/i.test(c),a.getSafariVersion=function(){if(!a.isSafari)return 0;const u=c.match(/Version\/(\d+)/);return u===null||u.length<2?0:parseInt(u[1])},a.isMac=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(l),a.isIpad=l==="iPad",a.isIphone=l==="iPhone",a.isWindows=["Windows","Win16","Win32","WinCE"].includes(l),a.isLinux=l.indexOf("Linux")>=0,a.isChromeOS=/\bCrOS\b/.test(c)},6106:(o,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.SortedList=void 0;let c=0;a.SortedList=class{constructor(l){this._getKey=l,this._array=[]}clear(){this._array.length=0}insert(l){this._array.length!==0?(c=this._search(this._getKey(l)),this._array.splice(c,0,l)):this._array.push(l)}delete(l){if(this._array.length===0)return!1;const u=this._getKey(l);if(u===void 0||(c=this._search(u),c===-1)||this._getKey(this._array[c])!==u)return!1;do if(this._array[c]===l)return this._array.splice(c,1),!0;while(++c<this._array.length&&this._getKey(this._array[c])===u);return!1}*getKeyIterator(l){if(this._array.length!==0&&(c=this._search(l),!(c<0||c>=this._array.length)&&this._getKey(this._array[c])===l))do yield this._array[c];while(++c<this._array.length&&this._getKey(this._array[c])===l)}forEachByKey(l,u){if(this._array.length!==0&&(c=this._search(l),!(c<0||c>=this._array.length)&&this._getKey(this._array[c])===l))do u(this._array[c]);while(++c<this._array.length&&this._getKey(this._array[c])===l)}values(){return[...this._array].values()}_search(l){let u=0,h=this._array.length-1;for(;h>=u;){let d=u+h>>1;const p=this._getKey(this._array[d]);if(p>l)h=d-1;else{if(!(p<l)){for(;d>0&&this._getKey(this._array[d-1])===l;)d--;return d}u=d+1}}return u}}},7226:(o,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.DebouncedIdleTask=a.IdleTaskQueue=a.PriorityTaskQueue=void 0;const l=c(6114);class u{constructor(){this._tasks=[],this._i=0}enqueue(p){this._tasks.push(p),this._start()}flush(){for(;this._i<this._tasks.length;)this._tasks[this._i]()||this._i++;this.clear()}clear(){this._idleCallback&&(this._cancelCallback(this._idleCallback),this._idleCallback=void 0),this._i=0,this._tasks.length=0}_start(){this._idleCallback||(this._idleCallback=this._requestCallback(this._process.bind(this)))}_process(p){this._idleCallback=void 0;let m=0,v=0,g=p.timeRemaining(),y=0;for(;this._i<this._tasks.length;){if(m=Date.now(),this._tasks[this._i]()||this._i++,m=Math.max(1,Date.now()-m),v=Math.max(m,v),y=p.timeRemaining(),1.5*v>y)return g-m<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(g-m))}ms`),void this._start();g=y}this.clear()}}class h extends u{_requestCallback(p){return setTimeout(()=>p(this._createDeadline(16)))}_cancelCallback(p){clearTimeout(p)}_createDeadline(p){const m=Date.now()+p;return{timeRemaining:()=>Math.max(0,m-Date.now())}}}a.PriorityTaskQueue=h,a.IdleTaskQueue=!l.isNode&&"requestIdleCallback"in window?class extends u{_requestCallback(d){return requestIdleCallback(d)}_cancelCallback(d){cancelIdleCallback(d)}}:h,a.DebouncedIdleTask=class{constructor(){this._queue=new a.IdleTaskQueue}set(d){this._queue.clear(),this._queue.enqueue(d)}flush(){this._queue.flush()}}},9282:(o,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.updateWindowsModeWrappedState=void 0;const l=c(643);a.updateWindowsModeWrappedState=function(u){const h=u.buffer.lines.get(u.buffer.ybase+u.buffer.y-1),d=h==null?void 0:h.get(u.cols-1),p=u.buffer.lines.get(u.buffer.ybase+u.buffer.y);p&&d&&(p.isWrapped=d[l.CHAR_DATA_CODE_INDEX]!==l.NULL_CELL_CODE&&d[l.CHAR_DATA_CODE_INDEX]!==l.WHITESPACE_CELL_CODE)}},3734:(o,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.ExtendedAttrs=a.AttributeData=void 0;class c{constructor(){this.fg=0,this.bg=0,this.extended=new l}static toColorRGB(h){return[h>>>16&255,h>>>8&255,255&h]}static fromColorRGB(h){return(255&h[0])<<16|(255&h[1])<<8|255&h[2]}clone(){const h=new c;return h.fg=this.fg,h.bg=this.bg,h.extended=this.extended.clone(),h}isInverse(){return 67108864&this.fg}isBold(){return 134217728&this.fg}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:268435456&this.fg}isBlink(){return 536870912&this.fg}isInvisible(){return 1073741824&this.fg}isItalic(){return 67108864&this.bg}isDim(){return 134217728&this.bg}isStrikethrough(){return 2147483648&this.fg}isProtected(){return 536870912&this.bg}isOverline(){return 1073741824&this.bg}getFgColorMode(){return 50331648&this.fg}getBgColorMode(){return 50331648&this.bg}isFgRGB(){return(50331648&this.fg)==50331648}isBgRGB(){return(50331648&this.bg)==50331648}isFgPalette(){return(50331648&this.fg)==16777216||(50331648&this.fg)==33554432}isBgPalette(){return(50331648&this.bg)==16777216||(50331648&this.bg)==33554432}isFgDefault(){return(50331648&this.fg)==0}isBgDefault(){return(50331648&this.bg)==0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(50331648&this.fg){case 16777216:case 33554432:return 255&this.fg;case 50331648:return 16777215&this.fg;default:return-1}}getBgColor(){switch(50331648&this.bg){case 16777216:case 33554432:return 255&this.bg;case 50331648:return 16777215&this.bg;default:return-1}}hasExtendedAttrs(){return 268435456&this.bg}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(268435456&this.bg&&~this.extended.underlineColor)switch(50331648&this.extended.underlineColor){case 16777216:case 33554432:return 255&this.extended.underlineColor;case 50331648:return 16777215&this.extended.underlineColor;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return 268435456&this.bg&&~this.extended.underlineColor?50331648&this.extended.underlineColor:this.getFgColorMode()}isUnderlineColorRGB(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==50331648:this.isFgRGB()}isUnderlineColorPalette(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==16777216||(50331648&this.extended.underlineColor)==33554432:this.isFgPalette()}isUnderlineColorDefault(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==0:this.isFgDefault()}getUnderlineStyle(){return 268435456&this.fg?268435456&this.bg?this.extended.underlineStyle:1:0}}a.AttributeData=c;class l{get ext(){return this._urlId?-469762049&this._ext|this.underlineStyle<<26:this._ext}set ext(h){this._ext=h}get underlineStyle(){return this._urlId?5:(469762048&this._ext)>>26}set underlineStyle(h){this._ext&=-469762049,this._ext|=h<<26&469762048}get underlineColor(){return 67108863&this._ext}set underlineColor(h){this._ext&=-67108864,this._ext|=67108863&h}get urlId(){return this._urlId}set urlId(h){this._urlId=h}constructor(h=0,d=0){this._ext=0,this._urlId=0,this._ext=h,this._urlId=d}clone(){return new l(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}}a.ExtendedAttrs=l},9092:(o,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.Buffer=a.MAX_BUFFER_SIZE=void 0;const l=c(6349),u=c(7226),h=c(3734),d=c(8437),p=c(4634),m=c(511),v=c(643),g=c(4863),y=c(7116);a.MAX_BUFFER_SIZE=4294967295,a.Buffer=class{constructor(b,_,w){this._hasScrollback=b,this._optionsService=_,this._bufferService=w,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=d.DEFAULT_ATTR_DATA.clone(),this.savedCharset=y.DEFAULT_CHARSET,this.markers=[],this._nullCell=m.CellData.fromCharData([0,v.NULL_CELL_CHAR,v.NULL_CELL_WIDTH,v.NULL_CELL_CODE]),this._whitespaceCell=m.CellData.fromCharData([0,v.WHITESPACE_CELL_CHAR,v.WHITESPACE_CELL_WIDTH,v.WHITESPACE_CELL_CODE]),this._isClearing=!1,this._memoryCleanupQueue=new u.IdleTaskQueue,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new l.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(b){return b?(this._nullCell.fg=b.fg,this._nullCell.bg=b.bg,this._nullCell.extended=b.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new h.ExtendedAttrs),this._nullCell}getWhitespaceCell(b){return b?(this._whitespaceCell.fg=b.fg,this._whitespaceCell.bg=b.bg,this._whitespaceCell.extended=b.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new h.ExtendedAttrs),this._whitespaceCell}getBlankLine(b,_){return new d.BufferLine(this._bufferService.cols,this.getNullCell(b),_)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){const b=this.ybase+this.y-this.ydisp;return b>=0&&b<this._rows}_getCorrectBufferLength(b){if(!this._hasScrollback)return b;const _=b+this._optionsService.rawOptions.scrollback;return _>a.MAX_BUFFER_SIZE?a.MAX_BUFFER_SIZE:_}fillViewportRows(b){if(this.lines.length===0){b===void 0&&(b=d.DEFAULT_ATTR_DATA);let _=this._rows;for(;_--;)this.lines.push(this.getBlankLine(b))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new l.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(b,_){const w=this.getNullCell(d.DEFAULT_ATTR_DATA);let S=0;const C=this._getCorrectBufferLength(_);if(C>this.lines.maxLength&&(this.lines.maxLength=C),this.lines.length>0){if(this._cols<b)for(let k=0;k<this.lines.length;k++)S+=+this.lines.get(k).resize(b,w);let T=0;if(this._rows<_)for(let k=this._rows;k<_;k++)this.lines.length<_+this.ybase&&(this._optionsService.rawOptions.windowsMode||this._optionsService.rawOptions.windowsPty.backend!==void 0||this._optionsService.rawOptions.windowsPty.buildNumber!==void 0?this.lines.push(new d.BufferLine(b,w)):this.ybase>0&&this.lines.length<=this.ybase+this.y+T+1?(this.ybase--,T++,this.ydisp>0&&this.ydisp--):this.lines.push(new d.BufferLine(b,w)));else for(let k=this._rows;k>_;k--)this.lines.length>_+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(C<this.lines.maxLength){const k=this.lines.length-C;k>0&&(this.lines.trimStart(k),this.ybase=Math.max(this.ybase-k,0),this.ydisp=Math.max(this.ydisp-k,0),this.savedY=Math.max(this.savedY-k,0)),this.lines.maxLength=C}this.x=Math.min(this.x,b-1),this.y=Math.min(this.y,_-1),T&&(this.y+=T),this.savedX=Math.min(this.savedX,b-1),this.scrollTop=0}if(this.scrollBottom=_-1,this._isReflowEnabled&&(this._reflow(b,_),this._cols>b))for(let T=0;T<this.lines.length;T++)S+=+this.lines.get(T).resize(b,w);this._cols=b,this._rows=_,this._memoryCleanupQueue.clear(),S>.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let b=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,b=!1);let _=0;for(;this._memoryCleanupPosition<this.lines.length;)if(_+=this.lines.get(this._memoryCleanupPosition++).cleanupMemory(),_>100)return!0;return b}get _isReflowEnabled(){const b=this._optionsService.rawOptions.windowsPty;return b&&b.buildNumber?this._hasScrollback&&b.backend==="conpty"&&b.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(b,_){this._cols!==b&&(b>this._cols?this._reflowLarger(b,_):this._reflowSmaller(b,_))}_reflowLarger(b,_){const w=(0,p.reflowLargerGetLinesToRemove)(this.lines,this._cols,b,this.ybase+this.y,this.getNullCell(d.DEFAULT_ATTR_DATA));if(w.length>0){const S=(0,p.reflowLargerCreateNewLayout)(this.lines,w);(0,p.reflowLargerApplyNewLayout)(this.lines,S.layout),this._reflowLargerAdjustViewport(b,_,S.countRemoved)}}_reflowLargerAdjustViewport(b,_,w){const S=this.getNullCell(d.DEFAULT_ATTR_DATA);let C=w;for(;C-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length<_&&this.lines.push(new d.BufferLine(b,S))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-w,0)}_reflowSmaller(b,_){const w=this.getNullCell(d.DEFAULT_ATTR_DATA),S=[];let C=0;for(let T=this.lines.length-1;T>=0;T--){let k=this.lines.get(T);if(!k||!k.isWrapped&&k.getTrimmedLength()<=b)continue;const A=[k];for(;k.isWrapped&&T>0;)k=this.lines.get(--T),A.unshift(k);const M=this.ybase+this.y;if(M>=T&&M<T+A.length)continue;const R=A[A.length-1].getTrimmedLength(),P=(0,p.reflowSmallerGetNewLineLengths)(A,this._cols,b),L=P.length-A.length;let z;z=this.ybase===0&&this.y!==this.lines.length-1?Math.max(0,this.y-this.lines.maxLength+L):Math.max(0,this.lines.length-this.lines.maxLength+L);const Q=[];for(let G=0;G<L;G++){const ee=this.getBlankLine(d.DEFAULT_ATTR_DATA,!0);Q.push(ee)}Q.length>0&&(S.push({start:T+A.length+C,newLines:Q}),C+=Q.length),A.push(...Q);let W=P.length-1,V=P[W];V===0&&(W--,V=P[W]);let N=A.length-L-1,O=R;for(;N>=0;){const G=Math.min(O,V);if(A[W]===void 0)break;if(A[W].copyCellsFrom(A[N],O-G,V-G,G,!0),V-=G,V===0&&(W--,V=P[W]),O-=G,O===0){N--;const ee=Math.max(N,0);O=(0,p.getWrappedLineTrimmedLength)(A,ee,this._cols)}}for(let G=0;G<A.length;G++)P[G]<b&&A[G].setCell(P[G],w);let H=L-z;for(;H-- >0;)this.ybase===0?this.y<_-1?(this.y++,this.lines.pop()):(this.ybase++,this.ydisp++):this.ybase<Math.min(this.lines.maxLength,this.lines.length+C)-_&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+L,this.ybase+_-1)}if(S.length>0){const T=[],k=[];for(let W=0;W<this.lines.length;W++)k.push(this.lines.get(W));const A=this.lines.length;let M=A-1,R=0,P=S[R];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+C);let L=0;for(let W=Math.min(this.lines.maxLength-1,A+C-1);W>=0;W--)if(P&&P.start>M+L){for(let V=P.newLines.length-1;V>=0;V--)this.lines.set(W--,P.newLines[V]);W++,T.push({index:M+1,amount:P.newLines.length}),L+=P.newLines.length,P=S[++R]}else this.lines.set(W,k[M--]);let z=0;for(let W=T.length-1;W>=0;W--)T[W].index+=z,this.lines.onInsertEmitter.fire(T[W]),z+=T[W].amount;const Q=Math.max(0,A+C-this.lines.maxLength);Q>0&&this.lines.onTrimEmitter.fire(Q)}}translateBufferLineToString(b,_,w=0,S){const C=this.lines.get(b);return C?C.translateToString(_,w,S):""}getWrappedRangeForLine(b){let _=b,w=b;for(;_>0&&this.lines.get(_).isWrapped;)_--;for(;w+1<this.lines.length&&this.lines.get(w+1).isWrapped;)w++;return{first:_,last:w}}setupTabStops(b){for(b!=null?this.tabs[b]||(b=this.prevStop(b)):(this.tabs={},b=0);b<this._cols;b+=this._optionsService.rawOptions.tabStopWidth)this.tabs[b]=!0}prevStop(b){for(b==null&&(b=this.x);!this.tabs[--b]&&b>0;);return b>=this._cols?this._cols-1:b<0?0:b}nextStop(b){for(b==null&&(b=this.x);!this.tabs[++b]&&b<this._cols;);return b>=this._cols?this._cols-1:b<0?0:b}clearMarkers(b){this._isClearing=!0;for(let _=0;_<this.markers.length;_++)this.markers[_].line===b&&(this.markers[_].dispose(),this.markers.splice(_--,1));this._isClearing=!1}clearAllMarkers(){this._isClearing=!0;for(let b=0;b<this.markers.length;b++)this.markers[b].dispose(),this.markers.splice(b--,1);this._isClearing=!1}addMarker(b){const _=new g.Marker(b);return this.markers.push(_),_.register(this.lines.onTrim(w=>{_.line-=w,_.line<0&&_.dispose()})),_.register(this.lines.onInsert(w=>{_.line>=w.index&&(_.line+=w.amount)})),_.register(this.lines.onDelete(w=>{_.line>=w.index&&_.line<w.index+w.amount&&_.dispose(),_.line>w.index&&(_.line-=w.amount)})),_.register(_.onDispose(()=>this._removeMarker(_))),_}_removeMarker(b){this._isClearing||this.markers.splice(this.markers.indexOf(b),1)}}},8437:(o,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.BufferLine=a.DEFAULT_ATTR_DATA=void 0;const l=c(3734),u=c(511),h=c(643),d=c(482);a.DEFAULT_ATTR_DATA=Object.freeze(new l.AttributeData);let p=0;class m{constructor(g,y,b=!1){this.isWrapped=b,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(3*g);const _=y||u.CellData.fromCharData([0,h.NULL_CELL_CHAR,h.NULL_CELL_WIDTH,h.NULL_CELL_CODE]);for(let w=0;w<g;++w)this.setCell(w,_);this.length=g}get(g){const y=this._data[3*g+0],b=2097151&y;return[this._data[3*g+1],2097152&y?this._combined[g]:b?(0,d.stringFromCodePoint)(b):"",y>>22,2097152&y?this._combined[g].charCodeAt(this._combined[g].length-1):b]}set(g,y){this._data[3*g+1]=y[h.CHAR_DATA_ATTR_INDEX],y[h.CHAR_DATA_CHAR_INDEX].length>1?(this._combined[g]=y[1],this._data[3*g+0]=2097152|g|y[h.CHAR_DATA_WIDTH_INDEX]<<22):this._data[3*g+0]=y[h.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|y[h.CHAR_DATA_WIDTH_INDEX]<<22}getWidth(g){return this._data[3*g+0]>>22}hasWidth(g){return 12582912&this._data[3*g+0]}getFg(g){return this._data[3*g+1]}getBg(g){return this._data[3*g+2]}hasContent(g){return 4194303&this._data[3*g+0]}getCodePoint(g){const y=this._data[3*g+0];return 2097152&y?this._combined[g].charCodeAt(this._combined[g].length-1):2097151&y}isCombined(g){return 2097152&this._data[3*g+0]}getString(g){const y=this._data[3*g+0];return 2097152&y?this._combined[g]:2097151&y?(0,d.stringFromCodePoint)(2097151&y):""}isProtected(g){return 536870912&this._data[3*g+2]}loadCell(g,y){return p=3*g,y.content=this._data[p+0],y.fg=this._data[p+1],y.bg=this._data[p+2],2097152&y.content&&(y.combinedData=this._combined[g]),268435456&y.bg&&(y.extended=this._extendedAttrs[g]),y}setCell(g,y){2097152&y.content&&(this._combined[g]=y.combinedData),268435456&y.bg&&(this._extendedAttrs[g]=y.extended),this._data[3*g+0]=y.content,this._data[3*g+1]=y.fg,this._data[3*g+2]=y.bg}setCellFromCodePoint(g,y,b,_,w,S){268435456&w&&(this._extendedAttrs[g]=S),this._data[3*g+0]=y|b<<22,this._data[3*g+1]=_,this._data[3*g+2]=w}addCodepointToCell(g,y){let b=this._data[3*g+0];2097152&b?this._combined[g]+=(0,d.stringFromCodePoint)(y):(2097151&b?(this._combined[g]=(0,d.stringFromCodePoint)(2097151&b)+(0,d.stringFromCodePoint)(y),b&=-2097152,b|=2097152):b=y|4194304,this._data[3*g+0]=b)}insertCells(g,y,b,_){if((g%=this.length)&&this.getWidth(g-1)===2&&this.setCellFromCodePoint(g-1,0,1,(_==null?void 0:_.fg)||0,(_==null?void 0:_.bg)||0,(_==null?void 0:_.extended)||new l.ExtendedAttrs),y<this.length-g){const w=new u.CellData;for(let S=this.length-g-y-1;S>=0;--S)this.setCell(g+y+S,this.loadCell(g+S,w));for(let S=0;S<y;++S)this.setCell(g+S,b)}else for(let w=g;w<this.length;++w)this.setCell(w,b);this.getWidth(this.length-1)===2&&this.setCellFromCodePoint(this.length-1,0,1,(_==null?void 0:_.fg)||0,(_==null?void 0:_.bg)||0,(_==null?void 0:_.extended)||new l.ExtendedAttrs)}deleteCells(g,y,b,_){if(g%=this.length,y<this.length-g){const w=new u.CellData;for(let S=0;S<this.length-g-y;++S)this.setCell(g+S,this.loadCell(g+y+S,w));for(let S=this.length-y;S<this.length;++S)this.setCell(S,b)}else for(let w=g;w<this.length;++w)this.setCell(w,b);g&&this.getWidth(g-1)===2&&this.setCellFromCodePoint(g-1,0,1,(_==null?void 0:_.fg)||0,(_==null?void 0:_.bg)||0,(_==null?void 0:_.extended)||new l.ExtendedAttrs),this.getWidth(g)!==0||this.hasContent(g)||this.setCellFromCodePoint(g,0,1,(_==null?void 0:_.fg)||0,(_==null?void 0:_.bg)||0,(_==null?void 0:_.extended)||new l.ExtendedAttrs)}replaceCells(g,y,b,_,w=!1){if(w)for(g&&this.getWidth(g-1)===2&&!this.isProtected(g-1)&&this.setCellFromCodePoint(g-1,0,1,(_==null?void 0:_.fg)||0,(_==null?void 0:_.bg)||0,(_==null?void 0:_.extended)||new l.ExtendedAttrs),y<this.length&&this.getWidth(y-1)===2&&!this.isProtected(y)&&this.setCellFromCodePoint(y,0,1,(_==null?void 0:_.fg)||0,(_==null?void 0:_.bg)||0,(_==null?void 0:_.extended)||new l.ExtendedAttrs);g<y&&g<this.length;)this.isProtected(g)||this.setCell(g,b),g++;else for(g&&this.getWidth(g-1)===2&&this.setCellFromCodePoint(g-1,0,1,(_==null?void 0:_.fg)||0,(_==null?void 0:_.bg)||0,(_==null?void 0:_.extended)||new l.ExtendedAttrs),y<this.length&&this.getWidth(y-1)===2&&this.setCellFromCodePoint(y,0,1,(_==null?void 0:_.fg)||0,(_==null?void 0:_.bg)||0,(_==null?void 0:_.extended)||new l.ExtendedAttrs);g<y&&g<this.length;)this.setCell(g++,b)}resize(g,y){if(g===this.length)return 4*this._data.length*2<this._data.buffer.byteLength;const b=3*g;if(g>this.length){if(this._data.buffer.byteLength>=4*b)this._data=new Uint32Array(this._data.buffer,0,b);else{const _=new Uint32Array(b);_.set(this._data),this._data=_}for(let _=this.length;_<g;++_)this.setCell(_,y)}else{this._data=this._data.subarray(0,b);const _=Object.keys(this._combined);for(let S=0;S<_.length;S++){const C=parseInt(_[S],10);C>=g&&delete this._combined[C]}const w=Object.keys(this._extendedAttrs);for(let S=0;S<w.length;S++){const C=parseInt(w[S],10);C>=g&&delete this._extendedAttrs[C]}}return this.length=g,4*b*2<this._data.buffer.byteLength}cleanupMemory(){if(4*this._data.length*2<this._data.buffer.byteLength){const g=new Uint32Array(this._data.length);return g.set(this._data),this._data=g,1}return 0}fill(g,y=!1){if(y)for(let b=0;b<this.length;++b)this.isProtected(b)||this.setCell(b,g);else{this._combined={},this._extendedAttrs={};for(let b=0;b<this.length;++b)this.setCell(b,g)}}copyFrom(g){this.length!==g.length?this._data=new Uint32Array(g._data):this._data.set(g._data),this.length=g.length,this._combined={};for(const y in g._combined)this._combined[y]=g._combined[y];this._extendedAttrs={};for(const y in g._extendedAttrs)this._extendedAttrs[y]=g._extendedAttrs[y];this.isWrapped=g.isWrapped}clone(){const g=new m(0);g._data=new Uint32Array(this._data),g.length=this.length;for(const y in this._combined)g._combined[y]=this._combined[y];for(const y in this._extendedAttrs)g._extendedAttrs[y]=this._extendedAttrs[y];return g.isWrapped=this.isWrapped,g}getTrimmedLength(){for(let g=this.length-1;g>=0;--g)if(4194303&this._data[3*g+0])return g+(this._data[3*g+0]>>22);return 0}getNoBgTrimmedLength(){for(let g=this.length-1;g>=0;--g)if(4194303&this._data[3*g+0]||50331648&this._data[3*g+2])return g+(this._data[3*g+0]>>22);return 0}copyCellsFrom(g,y,b,_,w){const S=g._data;if(w)for(let T=_-1;T>=0;T--){for(let k=0;k<3;k++)this._data[3*(b+T)+k]=S[3*(y+T)+k];268435456&S[3*(y+T)+2]&&(this._extendedAttrs[b+T]=g._extendedAttrs[y+T])}else for(let T=0;T<_;T++){for(let k=0;k<3;k++)this._data[3*(b+T)+k]=S[3*(y+T)+k];268435456&S[3*(y+T)+2]&&(this._extendedAttrs[b+T]=g._extendedAttrs[y+T])}const C=Object.keys(g._combined);for(let T=0;T<C.length;T++){const k=parseInt(C[T],10);k>=y&&(this._combined[k-y+b]=g._combined[k])}}translateToString(g=!1,y=0,b=this.length){g&&(b=Math.min(b,this.getTrimmedLength()));let _="";for(;y<b;){const w=this._data[3*y+0],S=2097151&w;_+=2097152&w?this._combined[y]:S?(0,d.stringFromCodePoint)(S):h.WHITESPACE_CELL_CHAR,y+=w>>22||1}return _}}a.BufferLine=m},4841:(o,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.getRangeLength=void 0,a.getRangeLength=function(c,l){if(c.start.y>c.end.y)throw new Error(`Buffer range end (${c.end.x}, ${c.end.y}) cannot be before start (${c.start.x}, ${c.start.y})`);return l*(c.end.y-c.start.y)+(c.end.x-c.start.x+1)}},4634:(o,a)=>{function c(l,u,h){if(u===l.length-1)return l[u].getTrimmedLength();const d=!l[u].hasContent(h-1)&&l[u].getWidth(h-1)===1,p=l[u+1].getWidth(0)===2;return d&&p?h-1:h}Object.defineProperty(a,"__esModule",{value:!0}),a.getWrappedLineTrimmedLength=a.reflowSmallerGetNewLineLengths=a.reflowLargerApplyNewLayout=a.reflowLargerCreateNewLayout=a.reflowLargerGetLinesToRemove=void 0,a.reflowLargerGetLinesToRemove=function(l,u,h,d,p){const m=[];for(let v=0;v<l.length-1;v++){let g=v,y=l.get(++g);if(!y.isWrapped)continue;const b=[l.get(v)];for(;g<l.length&&y.isWrapped;)b.push(y),y=l.get(++g);if(d>=v&&d<g){v+=b.length-1;continue}let _=0,w=c(b,_,u),S=1,C=0;for(;S<b.length;){const k=c(b,S,u),A=k-C,M=h-w,R=Math.min(A,M);b[_].copyCellsFrom(b[S],C,w,R,!1),w+=R,w===h&&(_++,w=0),C+=R,C===k&&(S++,C=0),w===0&&_!==0&&b[_-1].getWidth(h-1)===2&&(b[_].copyCellsFrom(b[_-1],h-1,w++,1,!1),b[_-1].setCell(h-1,p))}b[_].replaceCells(w,h,p);let T=0;for(let k=b.length-1;k>0&&(k>_||b[k].getTrimmedLength()===0);k--)T++;T>0&&(m.push(v+b.length-T),m.push(T)),v+=b.length-1}return m},a.reflowLargerCreateNewLayout=function(l,u){const h=[];let d=0,p=u[d],m=0;for(let v=0;v<l.length;v++)if(p===v){const g=u[++d];l.onDeleteEmitter.fire({index:v-m,amount:g}),v+=g-1,m+=g,p=u[++d]}else h.push(v);return{layout:h,countRemoved:m}},a.reflowLargerApplyNewLayout=function(l,u){const h=[];for(let d=0;d<u.length;d++)h.push(l.get(u[d]));for(let d=0;d<h.length;d++)l.set(d,h[d]);l.length=u.length},a.reflowSmallerGetNewLineLengths=function(l,u,h){const d=[],p=l.map((y,b)=>c(l,b,u)).reduce((y,b)=>y+b);let m=0,v=0,g=0;for(;g<p;){if(p-g<h){d.push(p-g);break}m+=h;const y=c(l,v,u);m>y&&(m-=y,v++);const b=l[v].getWidth(m-1)===2;b&&m--;const _=b?h-1:h;d.push(_),g+=_}return d},a.getWrappedLineTrimmedLength=c},5295:(o,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.BufferSet=void 0;const l=c(8460),u=c(844),h=c(9092);class d extends u.Disposable{constructor(m,v){super(),this._optionsService=m,this._bufferService=v,this._onBufferActivate=this.register(new l.EventEmitter),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this.register(this._optionsService.onSpecificOptionChange("scrollback",()=>this.resize(this._bufferService.cols,this._bufferService.rows))),this.register(this._optionsService.onSpecificOptionChange("tabStopWidth",()=>this.setupTabStops()))}reset(){this._normal=new h.Buffer(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new h.Buffer(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(m){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(m),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(m,v){this._normal.resize(m,v),this._alt.resize(m,v),this.setupTabStops(m)}setupTabStops(m){this._normal.setupTabStops(m),this._alt.setupTabStops(m)}}a.BufferSet=d},511:(o,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.CellData=void 0;const l=c(482),u=c(643),h=c(3734);class d extends h.AttributeData{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new h.ExtendedAttrs,this.combinedData=""}static fromCharData(m){const v=new d;return v.setFromCharData(m),v}isCombined(){return 2097152&this.content}getWidth(){return this.content>>22}getChars(){return 2097152&this.content?this.combinedData:2097151&this.content?(0,l.stringFromCodePoint)(2097151&this.content):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):2097151&this.content}setFromCharData(m){this.fg=m[u.CHAR_DATA_ATTR_INDEX],this.bg=0;let v=!1;if(m[u.CHAR_DATA_CHAR_INDEX].length>2)v=!0;else if(m[u.CHAR_DATA_CHAR_INDEX].length===2){const g=m[u.CHAR_DATA_CHAR_INDEX].charCodeAt(0);if(55296<=g&&g<=56319){const y=m[u.CHAR_DATA_CHAR_INDEX].charCodeAt(1);56320<=y&&y<=57343?this.content=1024*(g-55296)+y-56320+65536|m[u.CHAR_DATA_WIDTH_INDEX]<<22:v=!0}else v=!0}else this.content=m[u.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|m[u.CHAR_DATA_WIDTH_INDEX]<<22;v&&(this.combinedData=m[u.CHAR_DATA_CHAR_INDEX],this.content=2097152|m[u.CHAR_DATA_WIDTH_INDEX]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}}a.CellData=d},643:(o,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.WHITESPACE_CELL_CODE=a.WHITESPACE_CELL_WIDTH=a.WHITESPACE_CELL_CHAR=a.NULL_CELL_CODE=a.NULL_CELL_WIDTH=a.NULL_CELL_CHAR=a.CHAR_DATA_CODE_INDEX=a.CHAR_DATA_WIDTH_INDEX=a.CHAR_DATA_CHAR_INDEX=a.CHAR_DATA_ATTR_INDEX=a.DEFAULT_EXT=a.DEFAULT_ATTR=a.DEFAULT_COLOR=void 0,a.DEFAULT_COLOR=0,a.DEFAULT_ATTR=256|a.DEFAULT_COLOR<<9,a.DEFAULT_EXT=0,a.CHAR_DATA_ATTR_INDEX=0,a.CHAR_DATA_CHAR_INDEX=1,a.CHAR_DATA_WIDTH_INDEX=2,a.CHAR_DATA_CODE_INDEX=3,a.NULL_CELL_CHAR="",a.NULL_CELL_WIDTH=1,a.NULL_CELL_CODE=0,a.WHITESPACE_CELL_CHAR=" ",a.WHITESPACE_CELL_WIDTH=1,a.WHITESPACE_CELL_CODE=32},4863:(o,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.Marker=void 0;const l=c(8460),u=c(844);class h{get id(){return this._id}constructor(p){this.line=p,this.isDisposed=!1,this._disposables=[],this._id=h._nextId++,this._onDispose=this.register(new l.EventEmitter),this.onDispose=this._onDispose.event}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),(0,u.disposeArray)(this._disposables),this._disposables.length=0)}register(p){return this._disposables.push(p),p}}a.Marker=h,h._nextId=1},7116:(o,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.DEFAULT_CHARSET=a.CHARSETS=void 0,a.CHARSETS={},a.DEFAULT_CHARSET=a.CHARSETS.B,a.CHARSETS[0]={"`":"◆",a:"▒",b:"␉",c:"␌",d:"␍",e:"␊",f:"°",g:"±",h:"␤",i:"␋",j:"┘",k:"┐",l:"┌",m:"└",n:"┼",o:"⎺",p:"⎻",q:"─",r:"⎼",s:"⎽",t:"├",u:"┤",v:"┴",w:"┬",x:"│",y:"≤",z:"≥","{":"π","|":"≠","}":"£","~":"·"},a.CHARSETS.A={"#":"£"},a.CHARSETS.B=void 0,a.CHARSETS[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"},a.CHARSETS.C=a.CHARSETS[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"},a.CHARSETS.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"},a.CHARSETS.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"},a.CHARSETS.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"},a.CHARSETS.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"},a.CHARSETS.E=a.CHARSETS[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"},a.CHARSETS.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"},a.CHARSETS.H=a.CHARSETS[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"},a.CHARSETS["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"}},2584:(o,a)=>{var c,l,u;Object.defineProperty(a,"__esModule",{value:!0}),a.C1_ESCAPED=a.C1=a.C0=void 0,function(h){h.NUL="\0",h.SOH="",h.STX="",h.ETX="",h.EOT="",h.ENQ="",h.ACK="",h.BEL="\x07",h.BS="\b",h.HT=" ",h.LF=`
`,h.VT="\v",h.FF="\f",h.CR="\r",h.SO="",h.SI="",h.DLE="",h.DC1="",h.DC2="",h.DC3="",h.DC4="",h.NAK="",h.SYN="",h.ETB="",h.CAN="",h.EM="",h.SUB="",h.ESC="\x1B",h.FS="",h.GS="",h.RS="",h.US="",h.SP=" ",h.DEL=""}(c||(a.C0=c={})),function(h){h.PAD="€",h.HOP="",h.BPH="‚",h.NBH="ƒ",h.IND="„",h.NEL="…",h.SSA="†",h.ESA="‡",h.HTS="ˆ",h.HTJ="‰",h.VTS="Š",h.PLD="‹",h.PLU="Œ",h.RI="",h.SS2="Ž",h.SS3="",h.DCS="",h.PU1="‘",h.PU2="’",h.STS="“",h.CCH="”",h.MW="•",h.SPA="–",h.EPA="—",h.SOS="˜",h.SGCI="™",h.SCI="š",h.CSI="›",h.ST="œ",h.OSC="",h.PM="ž",h.APC="Ÿ"}(l||(a.C1=l={})),function(h){h.ST=`${c.ESC}\\`}(u||(a.C1_ESCAPED=u={}))},7399:(o,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.evaluateKeyboardEvent=void 0;const l=c(2584),u={48:["0",")"],49:["1","!"],50:["2","@"],51:["3","#"],52:["4","$"],53:["5","%"],54:["6","^"],55:["7","&"],56:["8","*"],57:["9","("],186:[";",":"],187:["=","+"],188:[",","<"],189:["-","_"],190:[".",">"],191:["/","?"],192:["`","~"],219:["[","{"],220:["\\","|"],221:["]","}"],222:["'",'"']};a.evaluateKeyboardEvent=function(h,d,p,m){const v={type:0,cancel:!1,key:void 0},g=(h.shiftKey?1:0)|(h.altKey?2:0)|(h.ctrlKey?4:0)|(h.metaKey?8:0);switch(h.keyCode){case 0:h.key==="UIKeyInputUpArrow"?v.key=d?l.C0.ESC+"OA":l.C0.ESC+"[A":h.key==="UIKeyInputLeftArrow"?v.key=d?l.C0.ESC+"OD":l.C0.ESC+"[D":h.key==="UIKeyInputRightArrow"?v.key=d?l.C0.ESC+"OC":l.C0.ESC+"[C":h.key==="UIKeyInputDownArrow"&&(v.key=d?l.C0.ESC+"OB":l.C0.ESC+"[B");break;case 8:if(h.altKey){v.key=l.C0.ESC+l.C0.DEL;break}v.key=l.C0.DEL;break;case 9:if(h.shiftKey){v.key=l.C0.ESC+"[Z";break}v.key=l.C0.HT,v.cancel=!0;break;case 13:v.key=h.altKey?l.C0.ESC+l.C0.CR:l.C0.CR,v.cancel=!0;break;case 27:v.key=l.C0.ESC,h.altKey&&(v.key=l.C0.ESC+l.C0.ESC),v.cancel=!0;break;case 37:if(h.metaKey)break;g?(v.key=l.C0.ESC+"[1;"+(g+1)+"D",v.key===l.C0.ESC+"[1;3D"&&(v.key=l.C0.ESC+(p?"b":"[1;5D"))):v.key=d?l.C0.ESC+"OD":l.C0.ESC+"[D";break;case 39:if(h.metaKey)break;g?(v.key=l.C0.ESC+"[1;"+(g+1)+"C",v.key===l.C0.ESC+"[1;3C"&&(v.key=l.C0.ESC+(p?"f":"[1;5C"))):v.key=d?l.C0.ESC+"OC":l.C0.ESC+"[C";break;case 38:if(h.metaKey)break;g?(v.key=l.C0.ESC+"[1;"+(g+1)+"A",p||v.key!==l.C0.ESC+"[1;3A"||(v.key=l.C0.ESC+"[1;5A")):v.key=d?l.C0.ESC+"OA":l.C0.ESC+"[A";break;case 40:if(h.metaKey)break;g?(v.key=l.C0.ESC+"[1;"+(g+1)+"B",p||v.key!==l.C0.ESC+"[1;3B"||(v.key=l.C0.ESC+"[1;5B")):v.key=d?l.C0.ESC+"OB":l.C0.ESC+"[B";break;case 45:h.shiftKey||h.ctrlKey||(v.key=l.C0.ESC+"[2~");break;case 46:v.key=g?l.C0.ESC+"[3;"+(g+1)+"~":l.C0.ESC+"[3~";break;case 36:v.key=g?l.C0.ESC+"[1;"+(g+1)+"H":d?l.C0.ESC+"OH":l.C0.ESC+"[H";break;case 35:v.key=g?l.C0.ESC+"[1;"+(g+1)+"F":d?l.C0.ESC+"OF":l.C0.ESC+"[F";break;case 33:h.shiftKey?v.type=2:h.ctrlKey?v.key=l.C0.ESC+"[5;"+(g+1)+"~":v.key=l.C0.ESC+"[5~";break;case 34:h.shiftKey?v.type=3:h.ctrlKey?v.key=l.C0.ESC+"[6;"+(g+1)+"~":v.key=l.C0.ESC+"[6~";break;case 112:v.key=g?l.C0.ESC+"[1;"+(g+1)+"P":l.C0.ESC+"OP";break;case 113:v.key=g?l.C0.ESC+"[1;"+(g+1)+"Q":l.C0.ESC+"OQ";break;case 114:v.key=g?l.C0.ESC+"[1;"+(g+1)+"R":l.C0.ESC+"OR";break;case 115:v.key=g?l.C0.ESC+"[1;"+(g+1)+"S":l.C0.ESC+"OS";break;case 116:v.key=g?l.C0.ESC+"[15;"+(g+1)+"~":l.C0.ESC+"[15~";break;case 117:v.key=g?l.C0.ESC+"[17;"+(g+1)+"~":l.C0.ESC+"[17~";break;case 118:v.key=g?l.C0.ESC+"[18;"+(g+1)+"~":l.C0.ESC+"[18~";break;case 119:v.key=g?l.C0.ESC+"[19;"+(g+1)+"~":l.C0.ESC+"[19~";break;case 120:v.key=g?l.C0.ESC+"[20;"+(g+1)+"~":l.C0.ESC+"[20~";break;case 121:v.key=g?l.C0.ESC+"[21;"+(g+1)+"~":l.C0.ESC+"[21~";break;case 122:v.key=g?l.C0.ESC+"[23;"+(g+1)+"~":l.C0.ESC+"[23~";break;case 123:v.key=g?l.C0.ESC+"[24;"+(g+1)+"~":l.C0.ESC+"[24~";break;default:if(!h.ctrlKey||h.shiftKey||h.altKey||h.metaKey)if(p&&!m||!h.altKey||h.metaKey)!p||h.altKey||h.ctrlKey||h.shiftKey||!h.metaKey?h.key&&!h.ctrlKey&&!h.altKey&&!h.metaKey&&h.keyCode>=48&&h.key.length===1?v.key=h.key:h.key&&h.ctrlKey&&(h.key==="_"&&(v.key=l.C0.US),h.key==="@"&&(v.key=l.C0.NUL)):h.keyCode===65&&(v.type=1);else{const y=u[h.keyCode],b=y==null?void 0:y[h.shiftKey?1:0];if(b)v.key=l.C0.ESC+b;else if(h.keyCode>=65&&h.keyCode<=90){const _=h.ctrlKey?h.keyCode-64:h.keyCode+32;let w=String.fromCharCode(_);h.shiftKey&&(w=w.toUpperCase()),v.key=l.C0.ESC+w}else if(h.keyCode===32)v.key=l.C0.ESC+(h.ctrlKey?l.C0.NUL:" ");else if(h.key==="Dead"&&h.code.startsWith("Key")){let _=h.code.slice(3,4);h.shiftKey||(_=_.toLowerCase()),v.key=l.C0.ESC+_,v.cancel=!0}}else h.keyCode>=65&&h.keyCode<=90?v.key=String.fromCharCode(h.keyCode-64):h.keyCode===32?v.key=l.C0.NUL:h.keyCode>=51&&h.keyCode<=55?v.key=String.fromCharCode(h.keyCode-51+27):h.keyCode===56?v.key=l.C0.DEL:h.keyCode===219?v.key=l.C0.ESC:h.keyCode===220?v.key=l.C0.FS:h.keyCode===221&&(v.key=l.C0.GS)}return v}},482:(o,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.Utf8ToUtf32=a.StringToUtf32=a.utf32ToString=a.stringFromCodePoint=void 0,a.stringFromCodePoint=function(c){return c>65535?(c-=65536,String.fromCharCode(55296+(c>>10))+String.fromCharCode(c%1024+56320)):String.fromCharCode(c)},a.utf32ToString=function(c,l=0,u=c.length){let h="";for(let d=l;d<u;++d){let p=c[d];p>65535?(p-=65536,h+=String.fromCharCode(55296+(p>>10))+String.fromCharCode(p%1024+56320)):h+=String.fromCharCode(p)}return h},a.StringToUtf32=class{constructor(){this._interim=0}clear(){this._interim=0}decode(c,l){const u=c.length;if(!u)return 0;let h=0,d=0;if(this._interim){const p=c.charCodeAt(d++);56320<=p&&p<=57343?l[h++]=1024*(this._interim-55296)+p-56320+65536:(l[h++]=this._interim,l[h++]=p),this._interim=0}for(let p=d;p<u;++p){const m=c.charCodeAt(p);if(55296<=m&&m<=56319){if(++p>=u)return this._interim=m,h;const v=c.charCodeAt(p);56320<=v&&v<=57343?l[h++]=1024*(m-55296)+v-56320+65536:(l[h++]=m,l[h++]=v)}else m!==65279&&(l[h++]=m)}return h}},a.Utf8ToUtf32=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(c,l){const u=c.length;if(!u)return 0;let h,d,p,m,v=0,g=0,y=0;if(this.interim[0]){let w=!1,S=this.interim[0];S&=(224&S)==192?31:(240&S)==224?15:7;let C,T=0;for(;(C=63&this.interim[++T])&&T<4;)S<<=6,S|=C;const k=(224&this.interim[0])==192?2:(240&this.interim[0])==224?3:4,A=k-T;for(;y<A;){if(y>=u)return 0;if(C=c[y++],(192&C)!=128){y--,w=!0;break}this.interim[T++]=C,S<<=6,S|=63&C}w||(k===2?S<128?y--:l[v++]=S:k===3?S<2048||S>=55296&&S<=57343||S===65279||(l[v++]=S):S<65536||S>1114111||(l[v++]=S)),this.interim.fill(0)}const b=u-4;let _=y;for(;_<u;){for(;!(!(_<b)||128&(h=c[_])||128&(d=c[_+1])||128&(p=c[_+2])||128&(m=c[_+3]));)l[v++]=h,l[v++]=d,l[v++]=p,l[v++]=m,_+=4;if(h=c[_++],h<128)l[v++]=h;else if((224&h)==192){if(_>=u)return this.interim[0]=h,v;if(d=c[_++],(192&d)!=128){_--;continue}if(g=(31&h)<<6|63&d,g<128){_--;continue}l[v++]=g}else if((240&h)==224){if(_>=u)return this.interim[0]=h,v;if(d=c[_++],(192&d)!=128){_--;continue}if(_>=u)return this.interim[0]=h,this.interim[1]=d,v;if(p=c[_++],(192&p)!=128){_--;continue}if(g=(15&h)<<12|(63&d)<<6|63&p,g<2048||g>=55296&&g<=57343||g===65279)continue;l[v++]=g}else if((248&h)==240){if(_>=u)return this.interim[0]=h,v;if(d=c[_++],(192&d)!=128){_--;continue}if(_>=u)return this.interim[0]=h,this.interim[1]=d,v;if(p=c[_++],(192&p)!=128){_--;continue}if(_>=u)return this.interim[0]=h,this.interim[1]=d,this.interim[2]=p,v;if(m=c[_++],(192&m)!=128){_--;continue}if(g=(7&h)<<18|(63&d)<<12|(63&p)<<6|63&m,g<65536||g>1114111)continue;l[v++]=g}}return v}}},225:(o,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.UnicodeV6=void 0;const c=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],l=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]];let u;a.UnicodeV6=class{constructor(){if(this.version="6",!u){u=new Uint8Array(65536),u.fill(1),u[0]=0,u.fill(0,1,32),u.fill(0,127,160),u.fill(2,4352,4448),u[9001]=2,u[9002]=2,u.fill(2,11904,42192),u[12351]=1,u.fill(2,44032,55204),u.fill(2,63744,64256),u.fill(2,65040,65050),u.fill(2,65072,65136),u.fill(2,65280,65377),u.fill(2,65504,65511);for(let h=0;h<c.length;++h)u.fill(0,c[h][0],c[h][1]+1)}}wcwidth(h){return h<32?0:h<127?1:h<65536?u[h]:function(d,p){let m,v=0,g=p.length-1;if(d<p[0][0]||d>p[g][1])return!1;for(;g>=v;)if(m=v+g>>1,d>p[m][1])v=m+1;else{if(!(d<p[m][0]))return!0;g=m-1}return!1}(h,l)?0:h>=131072&&h<=196605||h>=196608&&h<=262141?2:1}}},5981:(o,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.WriteBuffer=void 0;const l=c(8460),u=c(844);class h extends u.Disposable{constructor(p){super(),this._action=p,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this.register(new l.EventEmitter),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(p,m){if(m!==void 0&&this._syncCalls>m)return void(this._syncCalls=0);if(this._pendingData+=p.length,this._writeBuffer.push(p),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;let v;for(this._isSyncWriting=!0;v=this._writeBuffer.shift();){this._action(v);const g=this._callbacks.shift();g&&g()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(p,m){if(this._pendingData>5e7)throw new Error("write data discarded, use flow control to avoid losing data");if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput)return this._didUserInput=!1,this._pendingData+=p.length,this._writeBuffer.push(p),this._callbacks.push(m),void this._innerWrite();setTimeout(()=>this._innerWrite())}this._pendingData+=p.length,this._writeBuffer.push(p),this._callbacks.push(m)}_innerWrite(p=0,m=!0){const v=p||Date.now();for(;this._writeBuffer.length>this._bufferOffset;){const g=this._writeBuffer[this._bufferOffset],y=this._action(g,m);if(y){const _=w=>Date.now()-v>=12?setTimeout(()=>this._innerWrite(0,w)):this._innerWrite(v,w);return void y.catch(w=>(queueMicrotask(()=>{throw w}),Promise.resolve(!1))).then(_)}const b=this._callbacks[this._bufferOffset];if(b&&b(),this._bufferOffset++,this._pendingData-=g.length,Date.now()-v>=12)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>50&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout(()=>this._innerWrite())):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}}a.WriteBuffer=h},5941:(o,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.toRgbString=a.parseColor=void 0;const c=/^([\da-f])\/([\da-f])\/([\da-f])$|^([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})$|^([\da-f]{3})\/([\da-f]{3})\/([\da-f]{3})$|^([\da-f]{4})\/([\da-f]{4})\/([\da-f]{4})$/,l=/^[\da-f]+$/;function u(h,d){const p=h.toString(16),m=p.length<2?"0"+p:p;switch(d){case 4:return p[0];case 8:return m;case 12:return(m+m).slice(0,3);default:return m+m}}a.parseColor=function(h){if(!h)return;let d=h.toLowerCase();if(d.indexOf("rgb:")===0){d=d.slice(4);const p=c.exec(d);if(p){const m=p[1]?15:p[4]?255:p[7]?4095:65535;return[Math.round(parseInt(p[1]||p[4]||p[7]||p[10],16)/m*255),Math.round(parseInt(p[2]||p[5]||p[8]||p[11],16)/m*255),Math.round(parseInt(p[3]||p[6]||p[9]||p[12],16)/m*255)]}}else if(d.indexOf("#")===0&&(d=d.slice(1),l.exec(d)&&[3,6,9,12].includes(d.length))){const p=d.length/3,m=[0,0,0];for(let v=0;v<3;++v){const g=parseInt(d.slice(p*v,p*v+p),16);m[v]=p===1?g<<4:p===2?g:p===3?g>>4:g>>8}return m}},a.toRgbString=function(h,d=16){const[p,m,v]=h;return`rgb:${u(p,d)}/${u(m,d)}/${u(v,d)}`}},5770:(o,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.PAYLOAD_LIMIT=void 0,a.PAYLOAD_LIMIT=1e7},6351:(o,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.DcsHandler=a.DcsParser=void 0;const l=c(482),u=c(8742),h=c(5770),d=[];a.DcsParser=class{constructor(){this._handlers=Object.create(null),this._active=d,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=d}registerHandler(m,v){this._handlers[m]===void 0&&(this._handlers[m]=[]);const g=this._handlers[m];return g.push(v),{dispose:()=>{const y=g.indexOf(v);y!==-1&&g.splice(y,1)}}}clearHandler(m){this._handlers[m]&&delete this._handlers[m]}setHandlerFallback(m){this._handlerFb=m}reset(){if(this._active.length)for(let m=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;m>=0;--m)this._active[m].unhook(!1);this._stack.paused=!1,this._active=d,this._ident=0}hook(m,v){if(this.reset(),this._ident=m,this._active=this._handlers[m]||d,this._active.length)for(let g=this._active.length-1;g>=0;g--)this._active[g].hook(v);else this._handlerFb(this._ident,"HOOK",v)}put(m,v,g){if(this._active.length)for(let y=this._active.length-1;y>=0;y--)this._active[y].put(m,v,g);else this._handlerFb(this._ident,"PUT",(0,l.utf32ToString)(m,v,g))}unhook(m,v=!0){if(this._active.length){let g=!1,y=this._active.length-1,b=!1;if(this._stack.paused&&(y=this._stack.loopPosition-1,g=v,b=this._stack.fallThrough,this._stack.paused=!1),!b&&g===!1){for(;y>=0&&(g=this._active[y].unhook(m),g!==!0);y--)if(g instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=y,this._stack.fallThrough=!1,g;y--}for(;y>=0;y--)if(g=this._active[y].unhook(!1),g instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=y,this._stack.fallThrough=!0,g}else this._handlerFb(this._ident,"UNHOOK",m);this._active=d,this._ident=0}};const p=new u.Params;p.addParam(0),a.DcsHandler=class{constructor(m){this._handler=m,this._data="",this._params=p,this._hitLimit=!1}hook(m){this._params=m.length>1||m.params[0]?m.clone():p,this._data="",this._hitLimit=!1}put(m,v,g){this._hitLimit||(this._data+=(0,l.utf32ToString)(m,v,g),this._data.length>h.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))}unhook(m){let v=!1;if(this._hitLimit)v=!1;else if(m&&(v=this._handler(this._data,this._params),v instanceof Promise))return v.then(g=>(this._params=p,this._data="",this._hitLimit=!1,g));return this._params=p,this._data="",this._hitLimit=!1,v}}},2015:(o,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.EscapeSequenceParser=a.VT500_TRANSITION_TABLE=a.TransitionTable=void 0;const l=c(844),u=c(8742),h=c(6242),d=c(6351);class p{constructor(y){this.table=new Uint8Array(y)}setDefault(y,b){this.table.fill(y<<4|b)}add(y,b,_,w){this.table[b<<8|y]=_<<4|w}addMany(y,b,_,w){for(let S=0;S<y.length;S++)this.table[b<<8|y[S]]=_<<4|w}}a.TransitionTable=p;const m=160;a.VT500_TRANSITION_TABLE=function(){const g=new p(4095),y=Array.apply(null,Array(256)).map((T,k)=>k),b=(T,k)=>y.slice(T,k),_=b(32,127),w=b(0,24);w.push(25),w.push.apply(w,b(28,32));const S=b(0,14);let C;for(C in g.setDefault(1,0),g.addMany(_,0,2,0),S)g.addMany([24,26,153,154],C,3,0),g.addMany(b(128,144),C,3,0),g.addMany(b(144,152),C,3,0),g.add(156,C,0,0),g.add(27,C,11,1),g.add(157,C,4,8),g.addMany([152,158,159],C,0,7),g.add(155,C,11,3),g.add(144,C,11,9);return g.addMany(w,0,3,0),g.addMany(w,1,3,1),g.add(127,1,0,1),g.addMany(w,8,0,8),g.addMany(w,3,3,3),g.add(127,3,0,3),g.addMany(w,4,3,4),g.add(127,4,0,4),g.addMany(w,6,3,6),g.addMany(w,5,3,5),g.add(127,5,0,5),g.addMany(w,2,3,2),g.add(127,2,0,2),g.add(93,1,4,8),g.addMany(_,8,5,8),g.add(127,8,5,8),g.addMany([156,27,24,26,7],8,6,0),g.addMany(b(28,32),8,0,8),g.addMany([88,94,95],1,0,7),g.addMany(_,7,0,7),g.addMany(w,7,0,7),g.add(156,7,0,0),g.add(127,7,0,7),g.add(91,1,11,3),g.addMany(b(64,127),3,7,0),g.addMany(b(48,60),3,8,4),g.addMany([60,61,62,63],3,9,4),g.addMany(b(48,60),4,8,4),g.addMany(b(64,127),4,7,0),g.addMany([60,61,62,63],4,0,6),g.addMany(b(32,64),6,0,6),g.add(127,6,0,6),g.addMany(b(64,127),6,0,0),g.addMany(b(32,48),3,9,5),g.addMany(b(32,48),5,9,5),g.addMany(b(48,64),5,0,6),g.addMany(b(64,127),5,7,0),g.addMany(b(32,48),4,9,5),g.addMany(b(32,48),1,9,2),g.addMany(b(32,48),2,9,2),g.addMany(b(48,127),2,10,0),g.addMany(b(48,80),1,10,0),g.addMany(b(81,88),1,10,0),g.addMany([89,90,92],1,10,0),g.addMany(b(96,127),1,10,0),g.add(80,1,11,9),g.addMany(w,9,0,9),g.add(127,9,0,9),g.addMany(b(28,32),9,0,9),g.addMany(b(32,48),9,9,12),g.addMany(b(48,60),9,8,10),g.addMany([60,61,62,63],9,9,10),g.addMany(w,11,0,11),g.addMany(b(32,128),11,0,11),g.addMany(b(28,32),11,0,11),g.addMany(w,10,0,10),g.add(127,10,0,10),g.addMany(b(28,32),10,0,10),g.addMany(b(48,60),10,8,10),g.addMany([60,61,62,63],10,0,11),g.addMany(b(32,48),10,9,12),g.addMany(w,12,0,12),g.add(127,12,0,12),g.addMany(b(28,32),12,0,12),g.addMany(b(32,48),12,9,12),g.addMany(b(48,64),12,0,11),g.addMany(b(64,127),12,12,13),g.addMany(b(64,127),10,12,13),g.addMany(b(64,127),9,12,13),g.addMany(w,13,13,13),g.addMany(_,13,13,13),g.add(127,13,0,13),g.addMany([27,156,24,26],13,14,0),g.add(m,0,2,0),g.add(m,8,5,8),g.add(m,6,0,6),g.add(m,11,0,11),g.add(m,13,13,13),g}();class v extends l.Disposable{constructor(y=a.VT500_TRANSITION_TABLE){super(),this._transitions=y,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new u.Params,this._params.addParam(0),this._collect=0,this.precedingCodepoint=0,this._printHandlerFb=(b,_,w)=>{},this._executeHandlerFb=b=>{},this._csiHandlerFb=(b,_)=>{},this._escHandlerFb=b=>{},this._errorHandlerFb=b=>b,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this.register((0,l.toDisposable)(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this.register(new h.OscParser),this._dcsParser=this.register(new d.DcsParser),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},()=>!0)}_identifier(y,b=[64,126]){let _=0;if(y.prefix){if(y.prefix.length>1)throw new Error("only one byte as prefix supported");if(_=y.prefix.charCodeAt(0),_&&60>_||_>63)throw new Error("prefix must be in range 0x3c .. 0x3f")}if(y.intermediates){if(y.intermediates.length>2)throw new Error("only two bytes as intermediates are supported");for(let S=0;S<y.intermediates.length;++S){const C=y.intermediates.charCodeAt(S);if(32>C||C>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");_<<=8,_|=C}}if(y.final.length!==1)throw new Error("final must be a single byte");const w=y.final.charCodeAt(0);if(b[0]>w||w>b[1])throw new Error(`final must be in range ${b[0]} .. ${b[1]}`);return _<<=8,_|=w,_}identToString(y){const b=[];for(;y;)b.push(String.fromCharCode(255&y)),y>>=8;return b.reverse().join("")}setPrintHandler(y){this._printHandler=y}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(y,b){const _=this._identifier(y,[48,126]);this._escHandlers[_]===void 0&&(this._escHandlers[_]=[]);const w=this._escHandlers[_];return w.push(b),{dispose:()=>{const S=w.indexOf(b);S!==-1&&w.splice(S,1)}}}clearEscHandler(y){this._escHandlers[this._identifier(y,[48,126])]&&delete this._escHandlers[this._identifier(y,[48,126])]}setEscHandlerFallback(y){this._escHandlerFb=y}setExecuteHandler(y,b){this._executeHandlers[y.charCodeAt(0)]=b}clearExecuteHandler(y){this._executeHandlers[y.charCodeAt(0)]&&delete this._executeHandlers[y.charCodeAt(0)]}setExecuteHandlerFallback(y){this._executeHandlerFb=y}registerCsiHandler(y,b){const _=this._identifier(y);this._csiHandlers[_]===void 0&&(this._csiHandlers[_]=[]);const w=this._csiHandlers[_];return w.push(b),{dispose:()=>{const S=w.indexOf(b);S!==-1&&w.splice(S,1)}}}clearCsiHandler(y){this._csiHandlers[this._identifier(y)]&&delete this._csiHandlers[this._identifier(y)]}setCsiHandlerFallback(y){this._csiHandlerFb=y}registerDcsHandler(y,b){return this._dcsParser.registerHandler(this._identifier(y),b)}clearDcsHandler(y){this._dcsParser.clearHandler(this._identifier(y))}setDcsHandlerFallback(y){this._dcsParser.setHandlerFallback(y)}registerOscHandler(y,b){return this._oscParser.registerHandler(y,b)}clearOscHandler(y){this._oscParser.clearHandler(y)}setOscHandlerFallback(y){this._oscParser.setHandlerFallback(y)}setErrorHandler(y){this._errorHandler=y}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingCodepoint=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(y,b,_,w,S){this._parseStack.state=y,this._parseStack.handlers=b,this._parseStack.handlerPos=_,this._parseStack.transition=w,this._parseStack.chunkPos=S}parse(y,b,_){let w,S=0,C=0,T=0;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,T=this._parseStack.chunkPos+1;else{if(_===void 0||this._parseStack.state===1)throw this._parseStack.state=1,new Error("improper continuation due to previous async handler, giving up parsing");const k=this._parseStack.handlers;let A=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(_===!1&&A>-1){for(;A>=0&&(w=k[A](this._params),w!==!0);A--)if(w instanceof Promise)return this._parseStack.handlerPos=A,w}this._parseStack.handlers=[];break;case 4:if(_===!1&&A>-1){for(;A>=0&&(w=k[A](),w!==!0);A--)if(w instanceof Promise)return this._parseStack.handlerPos=A,w}this._parseStack.handlers=[];break;case 6:if(S=y[this._parseStack.chunkPos],w=this._dcsParser.unhook(S!==24&&S!==26,_),w)return w;S===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(S=y[this._parseStack.chunkPos],w=this._oscParser.end(S!==24&&S!==26,_),w)return w;S===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0}this._parseStack.state=0,T=this._parseStack.chunkPos+1,this.precedingCodepoint=0,this.currentState=15&this._parseStack.transition}for(let k=T;k<b;++k){switch(S=y[k],C=this._transitions.table[this.currentState<<8|(S<160?S:m)],C>>4){case 2:for(let L=k+1;;++L){if(L>=b||(S=y[L])<32||S>126&&S<m){this._printHandler(y,k,L),k=L-1;break}if(++L>=b||(S=y[L])<32||S>126&&S<m){this._printHandler(y,k,L),k=L-1;break}if(++L>=b||(S=y[L])<32||S>126&&S<m){this._printHandler(y,k,L),k=L-1;break}if(++L>=b||(S=y[L])<32||S>126&&S<m){this._printHandler(y,k,L),k=L-1;break}}break;case 3:this._executeHandlers[S]?this._executeHandlers[S]():this._executeHandlerFb(S),this.precedingCodepoint=0;break;case 0:break;case 1:if(this._errorHandler({position:k,code:S,currentState:this.currentState,collect:this._collect,params:this._params,abort:!1}).abort)return;break;case 7:const A=this._csiHandlers[this._collect<<8|S];let M=A?A.length-1:-1;for(;M>=0&&(w=A[M](this._params),w!==!0);M--)if(w instanceof Promise)return this._preserveStack(3,A,M,C,k),w;M<0&&this._csiHandlerFb(this._collect<<8|S,this._params),this.precedingCodepoint=0;break;case 8:do switch(S){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(S-48)}while(++k<b&&(S=y[k])>47&&S<60);k--;break;case 9:this._collect<<=8,this._collect|=S;break;case 10:const R=this._escHandlers[this._collect<<8|S];let P=R?R.length-1:-1;for(;P>=0&&(w=R[P](),w!==!0);P--)if(w instanceof Promise)return this._preserveStack(4,R,P,C,k),w;P<0&&this._escHandlerFb(this._collect<<8|S),this.precedingCodepoint=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|S,this._params);break;case 13:for(let L=k+1;;++L)if(L>=b||(S=y[L])===24||S===26||S===27||S>127&&S<m){this._dcsParser.put(y,k,L),k=L-1;break}break;case 14:if(w=this._dcsParser.unhook(S!==24&&S!==26),w)return this._preserveStack(6,[],0,C,k),w;S===27&&(C|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingCodepoint=0;break;case 4:this._oscParser.start();break;case 5:for(let L=k+1;;L++)if(L>=b||(S=y[L])<32||S>127&&S<m){this._oscParser.put(y,k,L),k=L-1;break}break;case 6:if(w=this._oscParser.end(S!==24&&S!==26),w)return this._preserveStack(5,[],0,C,k),w;S===27&&(C|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingCodepoint=0}this.currentState=15&C}}}a.EscapeSequenceParser=v},6242:(o,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.OscHandler=a.OscParser=void 0;const l=c(5770),u=c(482),h=[];a.OscParser=class{constructor(){this._state=0,this._active=h,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(d,p){this._handlers[d]===void 0&&(this._handlers[d]=[]);const m=this._handlers[d];return m.push(p),{dispose:()=>{const v=m.indexOf(p);v!==-1&&m.splice(v,1)}}}clearHandler(d){this._handlers[d]&&delete this._handlers[d]}setHandlerFallback(d){this._handlerFb=d}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=h}reset(){if(this._state===2)for(let d=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;d>=0;--d)this._active[d].end(!1);this._stack.paused=!1,this._active=h,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||h,this._active.length)for(let d=this._active.length-1;d>=0;d--)this._active[d].start();else this._handlerFb(this._id,"START")}_put(d,p,m){if(this._active.length)for(let v=this._active.length-1;v>=0;v--)this._active[v].put(d,p,m);else this._handlerFb(this._id,"PUT",(0,u.utf32ToString)(d,p,m))}start(){this.reset(),this._state=1}put(d,p,m){if(this._state!==3){if(this._state===1)for(;p<m;){const v=d[p++];if(v===59){this._state=2,this._start();break}if(v<48||57<v)return void(this._state=3);this._id===-1&&(this._id=0),this._id=10*this._id+v-48}this._state===2&&m-p>0&&this._put(d,p,m)}}end(d,p=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),this._active.length){let m=!1,v=this._active.length-1,g=!1;if(this._stack.paused&&(v=this._stack.loopPosition-1,m=p,g=this._stack.fallThrough,this._stack.paused=!1),!g&&m===!1){for(;v>=0&&(m=this._active[v].end(d),m!==!0);v--)if(m instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=v,this._stack.fallThrough=!1,m;v--}for(;v>=0;v--)if(m=this._active[v].end(!1),m instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=v,this._stack.fallThrough=!0,m}else this._handlerFb(this._id,"END",d);this._active=h,this._id=-1,this._state=0}}},a.OscHandler=class{constructor(d){this._handler=d,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(d,p,m){this._hitLimit||(this._data+=(0,u.utf32ToString)(d,p,m),this._data.length>l.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))}end(d){let p=!1;if(this._hitLimit)p=!1;else if(d&&(p=this._handler(this._data),p instanceof Promise))return p.then(m=>(this._data="",this._hitLimit=!1,m));return this._data="",this._hitLimit=!1,p}}},8742:(o,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.Params=void 0;const c=2147483647;class l{static fromArray(h){const d=new l;if(!h.length)return d;for(let p=Array.isArray(h[0])?1:0;p<h.length;++p){const m=h[p];if(Array.isArray(m))for(let v=0;v<m.length;++v)d.addSubParam(m[v]);else d.addParam(m)}return d}constructor(h=32,d=32){if(this.maxLength=h,this.maxSubParamsLength=d,d>256)throw new Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(h),this.length=0,this._subParams=new Int32Array(d),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(h),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}clone(){const h=new l(this.maxLength,this.maxSubParamsLength);return h.params.set(this.params),h.length=this.length,h._subParams.set(this._subParams),h._subParamsLength=this._subParamsLength,h._subParamsIdx.set(this._subParamsIdx),h._rejectDigits=this._rejectDigits,h._rejectSubDigits=this._rejectSubDigits,h._digitIsSub=this._digitIsSub,h}toArray(){const h=[];for(let d=0;d<this.length;++d){h.push(this.params[d]);const p=this._subParamsIdx[d]>>8,m=255&this._subParamsIdx[d];m-p>0&&h.push(Array.prototype.slice.call(this._subParams,p,m))}return h}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(h){if(this._digitIsSub=!1,this.length>=this.maxLength)this._rejectDigits=!0;else{if(h<-1)throw new Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=h>c?c:h}}addSubParam(h){if(this._digitIsSub=!0,this.length)if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength)this._rejectSubDigits=!0;else{if(h<-1)throw new Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=h>c?c:h,this._subParamsIdx[this.length-1]++}}hasSubParams(h){return(255&this._subParamsIdx[h])-(this._subParamsIdx[h]>>8)>0}getSubParams(h){const d=this._subParamsIdx[h]>>8,p=255&this._subParamsIdx[h];return p-d>0?this._subParams.subarray(d,p):null}getSubParamsAll(){const h={};for(let d=0;d<this.length;++d){const p=this._subParamsIdx[d]>>8,m=255&this._subParamsIdx[d];m-p>0&&(h[d]=this._subParams.slice(p,m))}return h}addDigit(h){let d;if(this._rejectDigits||!(d=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;const p=this._digitIsSub?this._subParams:this.params,m=p[d-1];p[d-1]=~m?Math.min(10*m+h,c):h}}a.Params=l},5741:(o,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.AddonManager=void 0,a.AddonManager=class{constructor(){this._addons=[]}dispose(){for(let c=this._addons.length-1;c>=0;c--)this._addons[c].instance.dispose()}loadAddon(c,l){const u={instance:l,dispose:l.dispose,isDisposed:!1};this._addons.push(u),l.dispose=()=>this._wrappedAddonDispose(u),l.activate(c)}_wrappedAddonDispose(c){if(c.isDisposed)return;let l=-1;for(let u=0;u<this._addons.length;u++)if(this._addons[u]===c){l=u;break}if(l===-1)throw new Error("Could not dispose an addon that has not been loaded");c.isDisposed=!0,c.dispose.apply(c.instance),this._addons.splice(l,1)}}},8771:(o,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.BufferApiView=void 0;const l=c(3785),u=c(511);a.BufferApiView=class{constructor(h,d){this._buffer=h,this.type=d}init(h){return this._buffer=h,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(h){const d=this._buffer.lines.get(h);if(d)return new l.BufferLineApiView(d)}getNullCell(){return new u.CellData}}},3785:(o,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.BufferLineApiView=void 0;const l=c(511);a.BufferLineApiView=class{constructor(u){this._line=u}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(u,h){if(!(u<0||u>=this._line.length))return h?(this._line.loadCell(u,h),h):this._line.loadCell(u,new l.CellData)}translateToString(u,h,d){return this._line.translateToString(u,h,d)}}},8285:(o,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.BufferNamespaceApi=void 0;const l=c(8771),u=c(8460),h=c(844);class d extends h.Disposable{constructor(m){super(),this._core=m,this._onBufferChange=this.register(new u.EventEmitter),this.onBufferChange=this._onBufferChange.event,this._normal=new l.BufferApiView(this._core.buffers.normal,"normal"),this._alternate=new l.BufferApiView(this._core.buffers.alt,"alternate"),this._core.buffers.onBufferActivate(()=>this._onBufferChange.fire(this.active))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw new Error("Active buffer is neither normal nor alternate")}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}}a.BufferNamespaceApi=d},7975:(o,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.ParserApi=void 0,a.ParserApi=class{constructor(c){this._core=c}registerCsiHandler(c,l){return this._core.registerCsiHandler(c,u=>l(u.toArray()))}addCsiHandler(c,l){return this.registerCsiHandler(c,l)}registerDcsHandler(c,l){return this._core.registerDcsHandler(c,(u,h)=>l(u,h.toArray()))}addDcsHandler(c,l){return this.registerDcsHandler(c,l)}registerEscHandler(c,l){return this._core.registerEscHandler(c,l)}addEscHandler(c,l){return this.registerEscHandler(c,l)}registerOscHandler(c,l){return this._core.registerOscHandler(c,l)}addOscHandler(c,l){return this.registerOscHandler(c,l)}}},7090:(o,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.UnicodeApi=void 0,a.UnicodeApi=class{constructor(c){this._core=c}register(c){this._core.unicodeService.register(c)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(c){this._core.unicodeService.activeVersion=c}}},744:function(o,a,c){var l=this&&this.__decorate||function(g,y,b,_){var w,S=arguments.length,C=S<3?y:_===null?_=Object.getOwnPropertyDescriptor(y,b):_;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")C=Reflect.decorate(g,y,b,_);else for(var T=g.length-1;T>=0;T--)(w=g[T])&&(C=(S<3?w(C):S>3?w(y,b,C):w(y,b))||C);return S>3&&C&&Object.defineProperty(y,b,C),C},u=this&&this.__param||function(g,y){return function(b,_){y(b,_,g)}};Object.defineProperty(a,"__esModule",{value:!0}),a.BufferService=a.MINIMUM_ROWS=a.MINIMUM_COLS=void 0;const h=c(8460),d=c(844),p=c(5295),m=c(2585);a.MINIMUM_COLS=2,a.MINIMUM_ROWS=1;let v=a.BufferService=class extends d.Disposable{get buffer(){return this.buffers.active}constructor(g){super(),this.isUserScrolling=!1,this._onResize=this.register(new h.EventEmitter),this.onResize=this._onResize.event,this._onScroll=this.register(new h.EventEmitter),this.onScroll=this._onScroll.event,this.cols=Math.max(g.rawOptions.cols||0,a.MINIMUM_COLS),this.rows=Math.max(g.rawOptions.rows||0,a.MINIMUM_ROWS),this.buffers=this.register(new p.BufferSet(g,this))}resize(g,y){this.cols=g,this.rows=y,this.buffers.resize(g,y),this._onResize.fire({cols:g,rows:y})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(g,y=!1){const b=this.buffer;let _;_=this._cachedBlankLine,_&&_.length===this.cols&&_.getFg(0)===g.fg&&_.getBg(0)===g.bg||(_=b.getBlankLine(g,y),this._cachedBlankLine=_),_.isWrapped=y;const w=b.ybase+b.scrollTop,S=b.ybase+b.scrollBottom;if(b.scrollTop===0){const C=b.lines.isFull;S===b.lines.length-1?C?b.lines.recycle().copyFrom(_):b.lines.push(_.clone()):b.lines.splice(S+1,0,_.clone()),C?this.isUserScrolling&&(b.ydisp=Math.max(b.ydisp-1,0)):(b.ybase++,this.isUserScrolling||b.ydisp++)}else{const C=S-w+1;b.lines.shiftElements(w+1,C-1,-1),b.lines.set(S,_.clone())}this.isUserScrolling||(b.ydisp=b.ybase),this._onScroll.fire(b.ydisp)}scrollLines(g,y,b){const _=this.buffer;if(g<0){if(_.ydisp===0)return;this.isUserScrolling=!0}else g+_.ydisp>=_.ybase&&(this.isUserScrolling=!1);const w=_.ydisp;_.ydisp=Math.max(Math.min(_.ydisp+g,_.ybase),0),w!==_.ydisp&&(y||this._onScroll.fire(_.ydisp))}};a.BufferService=v=l([u(0,m.IOptionsService)],v)},7994:(o,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.CharsetService=void 0,a.CharsetService=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(c){this.glevel=c,this.charset=this._charsets[c]}setgCharset(c,l){this._charsets[c]=l,this.glevel===c&&(this.charset=l)}}},1753:function(o,a,c){var l=this&&this.__decorate||function(_,w,S,C){var T,k=arguments.length,A=k<3?w:C===null?C=Object.getOwnPropertyDescriptor(w,S):C;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")A=Reflect.decorate(_,w,S,C);else for(var M=_.length-1;M>=0;M--)(T=_[M])&&(A=(k<3?T(A):k>3?T(w,S,A):T(w,S))||A);return k>3&&A&&Object.defineProperty(w,S,A),A},u=this&&this.__param||function(_,w){return function(S,C){w(S,C,_)}};Object.defineProperty(a,"__esModule",{value:!0}),a.CoreMouseService=void 0;const h=c(2585),d=c(8460),p=c(844),m={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:_=>_.button!==4&&_.action===1&&(_.ctrl=!1,_.alt=!1,_.shift=!1,!0)},VT200:{events:19,restrict:_=>_.action!==32},DRAG:{events:23,restrict:_=>_.action!==32||_.button!==3},ANY:{events:31,restrict:_=>!0}};function v(_,w){let S=(_.ctrl?16:0)|(_.shift?4:0)|(_.alt?8:0);return _.button===4?(S|=64,S|=_.action):(S|=3&_.button,4&_.button&&(S|=64),8&_.button&&(S|=128),_.action===32?S|=32:_.action!==0||w||(S|=3)),S}const g=String.fromCharCode,y={DEFAULT:_=>{const w=[v(_,!1)+32,_.col+32,_.row+32];return w[0]>255||w[1]>255||w[2]>255?"":`\x1B[M${g(w[0])}${g(w[1])}${g(w[2])}`},SGR:_=>{const w=_.action===0&&_.button!==4?"m":"M";return`\x1B[<${v(_,!0)};${_.col};${_.row}${w}`},SGR_PIXELS:_=>{const w=_.action===0&&_.button!==4?"m":"M";return`\x1B[<${v(_,!0)};${_.x};${_.y}${w}`}};let b=a.CoreMouseService=class extends p.Disposable{constructor(_,w){super(),this._bufferService=_,this._coreService=w,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._onProtocolChange=this.register(new d.EventEmitter),this.onProtocolChange=this._onProtocolChange.event;for(const S of Object.keys(m))this.addProtocol(S,m[S]);for(const S of Object.keys(y))this.addEncoding(S,y[S]);this.reset()}addProtocol(_,w){this._protocols[_]=w}addEncoding(_,w){this._encodings[_]=w}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(_){if(!this._protocols[_])throw new Error(`unknown protocol "${_}"`);this._activeProtocol=_,this._onProtocolChange.fire(this._protocols[_].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(_){if(!this._encodings[_])throw new Error(`unknown encoding "${_}"`);this._activeEncoding=_}reset(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null}triggerMouseEvent(_){if(_.col<0||_.col>=this._bufferService.cols||_.row<0||_.row>=this._bufferService.rows||_.button===4&&_.action===32||_.button===3&&_.action!==32||_.button!==4&&(_.action===2||_.action===3)||(_.col++,_.row++,_.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,_,this._activeEncoding==="SGR_PIXELS"))||!this._protocols[this._activeProtocol].restrict(_))return!1;const w=this._encodings[this._activeEncoding](_);return w&&(this._activeEncoding==="DEFAULT"?this._coreService.triggerBinaryEvent(w):this._coreService.triggerDataEvent(w,!0)),this._lastEvent=_,!0}explainEvents(_){return{down:!!(1&_),up:!!(2&_),drag:!!(4&_),move:!!(8&_),wheel:!!(16&_)}}_equalEvents(_,w,S){if(S){if(_.x!==w.x||_.y!==w.y)return!1}else if(_.col!==w.col||_.row!==w.row)return!1;return _.button===w.button&&_.action===w.action&&_.ctrl===w.ctrl&&_.alt===w.alt&&_.shift===w.shift}};a.CoreMouseService=b=l([u(0,h.IBufferService),u(1,h.ICoreService)],b)},6975:function(o,a,c){var l=this&&this.__decorate||function(b,_,w,S){var C,T=arguments.length,k=T<3?_:S===null?S=Object.getOwnPropertyDescriptor(_,w):S;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")k=Reflect.decorate(b,_,w,S);else for(var A=b.length-1;A>=0;A--)(C=b[A])&&(k=(T<3?C(k):T>3?C(_,w,k):C(_,w))||k);return T>3&&k&&Object.defineProperty(_,w,k),k},u=this&&this.__param||function(b,_){return function(w,S){_(w,S,b)}};Object.defineProperty(a,"__esModule",{value:!0}),a.CoreService=void 0;const h=c(1439),d=c(8460),p=c(844),m=c(2585),v=Object.freeze({insertMode:!1}),g=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,origin:!1,reverseWraparound:!1,sendFocus:!1,wraparound:!0});let y=a.CoreService=class extends p.Disposable{constructor(b,_,w){super(),this._bufferService=b,this._logService=_,this._optionsService=w,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this.register(new d.EventEmitter),this.onData=this._onData.event,this._onUserInput=this.register(new d.EventEmitter),this.onUserInput=this._onUserInput.event,this._onBinary=this.register(new d.EventEmitter),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this.register(new d.EventEmitter),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=(0,h.clone)(v),this.decPrivateModes=(0,h.clone)(g)}reset(){this.modes=(0,h.clone)(v),this.decPrivateModes=(0,h.clone)(g)}triggerDataEvent(b,_=!1){if(this._optionsService.rawOptions.disableStdin)return;const w=this._bufferService.buffer;_&&this._optionsService.rawOptions.scrollOnUserInput&&w.ybase!==w.ydisp&&this._onRequestScrollToBottom.fire(),_&&this._onUserInput.fire(),this._logService.debug(`sending data "${b}"`,()=>b.split("").map(S=>S.charCodeAt(0))),this._onData.fire(b)}triggerBinaryEvent(b){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${b}"`,()=>b.split("").map(_=>_.charCodeAt(0))),this._onBinary.fire(b))}};a.CoreService=y=l([u(0,m.IBufferService),u(1,m.ILogService),u(2,m.IOptionsService)],y)},9074:(o,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.DecorationService=void 0;const l=c(8055),u=c(8460),h=c(844),d=c(6106);let p=0,m=0;class v extends h.Disposable{get decorations(){return this._decorations.values()}constructor(){super(),this._decorations=new d.SortedList(b=>b==null?void 0:b.marker.line),this._onDecorationRegistered=this.register(new u.EventEmitter),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this.register(new u.EventEmitter),this.onDecorationRemoved=this._onDecorationRemoved.event,this.register((0,h.toDisposable)(()=>this.reset()))}registerDecoration(b){if(b.marker.isDisposed)return;const _=new g(b);if(_){const w=_.marker.onDispose(()=>_.dispose());_.onDispose(()=>{_&&(this._decorations.delete(_)&&this._onDecorationRemoved.fire(_),w.dispose())}),this._decorations.insert(_),this._onDecorationRegistered.fire(_)}return _}reset(){for(const b of this._decorations.values())b.dispose();this._decorations.clear()}*getDecorationsAtCell(b,_,w){var S,C,T;let k=0,A=0;for(const M of this._decorations.getKeyIterator(_))k=(S=M.options.x)!==null&&S!==void 0?S:0,A=k+((C=M.options.width)!==null&&C!==void 0?C:1),b>=k&&b<A&&(!w||((T=M.options.layer)!==null&&T!==void 0?T:"bottom")===w)&&(yield M)}forEachDecorationAtCell(b,_,w,S){this._decorations.forEachByKey(_,C=>{var T,k,A;p=(T=C.options.x)!==null&&T!==void 0?T:0,m=p+((k=C.options.width)!==null&&k!==void 0?k:1),b>=p&&b<m&&(!w||((A=C.options.layer)!==null&&A!==void 0?A:"bottom")===w)&&S(C)})}}a.DecorationService=v;class g extends h.Disposable{get isDisposed(){return this._isDisposed}get backgroundColorRGB(){return this._cachedBg===null&&(this.options.backgroundColor?this._cachedBg=l.css.toColor(this.options.backgroundColor):this._cachedBg=void 0),this._cachedBg}get foregroundColorRGB(){return this._cachedFg===null&&(this.options.foregroundColor?this._cachedFg=l.css.toColor(this.options.foregroundColor):this._cachedFg=void 0),this._cachedFg}constructor(b){super(),this.options=b,this.onRenderEmitter=this.register(new u.EventEmitter),this.onRender=this.onRenderEmitter.event,this._onDispose=this.register(new u.EventEmitter),this.onDispose=this._onDispose.event,this._cachedBg=null,this._cachedFg=null,this.marker=b.marker,this.options.overviewRulerOptions&&!this.options.overviewRulerOptions.position&&(this.options.overviewRulerOptions.position="full")}dispose(){this._onDispose.fire(),super.dispose()}}},4348:(o,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.InstantiationService=a.ServiceCollection=void 0;const l=c(2585),u=c(8343);class h{constructor(...p){this._entries=new Map;for(const[m,v]of p)this.set(m,v)}set(p,m){const v=this._entries.get(p);return this._entries.set(p,m),v}forEach(p){for(const[m,v]of this._entries.entries())p(m,v)}has(p){return this._entries.has(p)}get(p){return this._entries.get(p)}}a.ServiceCollection=h,a.InstantiationService=class{constructor(){this._services=new h,this._services.set(l.IInstantiationService,this)}setService(d,p){this._services.set(d,p)}getService(d){return this._services.get(d)}createInstance(d,...p){const m=(0,u.getServiceDependencies)(d).sort((y,b)=>y.index-b.index),v=[];for(const y of m){const b=this._services.get(y.id);if(!b)throw new Error(`[createInstance] ${d.name} depends on UNKNOWN service ${y.id}.`);v.push(b)}const g=m.length>0?m[0].index:p.length;if(p.length!==g)throw new Error(`[createInstance] First service dependency of ${d.name} at position ${g+1} conflicts with ${p.length} static arguments`);return new d(...p,...v)}}},7866:function(o,a,c){var l=this&&this.__decorate||function(g,y,b,_){var w,S=arguments.length,C=S<3?y:_===null?_=Object.getOwnPropertyDescriptor(y,b):_;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")C=Reflect.decorate(g,y,b,_);else for(var T=g.length-1;T>=0;T--)(w=g[T])&&(C=(S<3?w(C):S>3?w(y,b,C):w(y,b))||C);return S>3&&C&&Object.defineProperty(y,b,C),C},u=this&&this.__param||function(g,y){return function(b,_){y(b,_,g)}};Object.defineProperty(a,"__esModule",{value:!0}),a.traceCall=a.setTraceLogger=a.LogService=void 0;const h=c(844),d=c(2585),p={trace:d.LogLevelEnum.TRACE,debug:d.LogLevelEnum.DEBUG,info:d.LogLevelEnum.INFO,warn:d.LogLevelEnum.WARN,error:d.LogLevelEnum.ERROR,off:d.LogLevelEnum.OFF};let m,v=a.LogService=class extends h.Disposable{get logLevel(){return this._logLevel}constructor(g){super(),this._optionsService=g,this._logLevel=d.LogLevelEnum.OFF,this._updateLogLevel(),this.register(this._optionsService.onSpecificOptionChange("logLevel",()=>this._updateLogLevel())),m=this}_updateLogLevel(){this._logLevel=p[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(g){for(let y=0;y<g.length;y++)typeof g[y]=="function"&&(g[y]=g[y]())}_log(g,y,b){this._evalLazyOptionalParams(b),g.call(console,(this._optionsService.options.logger?"":"xterm.js: ")+y,...b)}trace(g,...y){var b,_;this._logLevel<=d.LogLevelEnum.TRACE&&this._log((_=(b=this._optionsService.options.logger)===null||b===void 0?void 0:b.trace.bind(this._optionsService.options.logger))!==null&&_!==void 0?_:console.log,g,y)}debug(g,...y){var b,_;this._logLevel<=d.LogLevelEnum.DEBUG&&this._log((_=(b=this._optionsService.options.logger)===null||b===void 0?void 0:b.debug.bind(this._optionsService.options.logger))!==null&&_!==void 0?_:console.log,g,y)}info(g,...y){var b,_;this._logLevel<=d.LogLevelEnum.INFO&&this._log((_=(b=this._optionsService.options.logger)===null||b===void 0?void 0:b.info.bind(this._optionsService.options.logger))!==null&&_!==void 0?_:console.info,g,y)}warn(g,...y){var b,_;this._logLevel<=d.LogLevelEnum.WARN&&this._log((_=(b=this._optionsService.options.logger)===null||b===void 0?void 0:b.warn.bind(this._optionsService.options.logger))!==null&&_!==void 0?_:console.warn,g,y)}error(g,...y){var b,_;this._logLevel<=d.LogLevelEnum.ERROR&&this._log((_=(b=this._optionsService.options.logger)===null||b===void 0?void 0:b.error.bind(this._optionsService.options.logger))!==null&&_!==void 0?_:console.error,g,y)}};a.LogService=v=l([u(0,d.IOptionsService)],v),a.setTraceLogger=function(g){m=g},a.traceCall=function(g,y,b){if(typeof b.value!="function")throw new Error("not supported");const _=b.value;b.value=function(...w){if(m.logLevel!==d.LogLevelEnum.TRACE)return _.apply(this,w);m.trace(`GlyphRenderer#${_.name}(${w.map(C=>JSON.stringify(C)).join(", ")})`);const S=_.apply(this,w);return m.trace(`GlyphRenderer#${_.name} return`,S),S}}},7302:(o,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.OptionsService=a.DEFAULT_OPTIONS=void 0;const l=c(8460),u=c(844),h=c(6114);a.DEFAULT_OPTIONS={cols:80,rows:24,cursorBlink:!1,cursorStyle:"block",cursorWidth:1,cursorInactiveStyle:"outline",customGlyphs:!0,drawBoldTextInBrightColors:!0,fastScrollModifier:"alt",fastScrollSensitivity:5,fontFamily:"courier-new, courier, monospace",fontSize:15,fontWeight:"normal",fontWeightBold:"bold",ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:"info",logger:null,scrollback:1e3,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},rightClickSelectsWord:h.isMac,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRulerWidth:0};const d=["normal","bold","100","200","300","400","500","600","700","800","900"];class p extends u.Disposable{constructor(v){super(),this._onOptionChange=this.register(new l.EventEmitter),this.onOptionChange=this._onOptionChange.event;const g=Object.assign({},a.DEFAULT_OPTIONS);for(const y in v)if(y in g)try{const b=v[y];g[y]=this._sanitizeAndValidateOption(y,b)}catch(b){console.error(b)}this.rawOptions=g,this.options=Object.assign({},g),this._setupOptions()}onSpecificOptionChange(v,g){return this.onOptionChange(y=>{y===v&&g(this.rawOptions[v])})}onMultipleOptionChange(v,g){return this.onOptionChange(y=>{v.indexOf(y)!==-1&&g()})}_setupOptions(){const v=y=>{if(!(y in a.DEFAULT_OPTIONS))throw new Error(`No option with key "${y}"`);return this.rawOptions[y]},g=(y,b)=>{if(!(y in a.DEFAULT_OPTIONS))throw new Error(`No option with key "${y}"`);b=this._sanitizeAndValidateOption(y,b),this.rawOptions[y]!==b&&(this.rawOptions[y]=b,this._onOptionChange.fire(y))};for(const y in this.rawOptions){const b={get:v.bind(this,y),set:g.bind(this,y)};Object.defineProperty(this.options,y,b)}}_sanitizeAndValidateOption(v,g){switch(v){case"cursorStyle":if(g||(g=a.DEFAULT_OPTIONS[v]),!function(y){return y==="block"||y==="underline"||y==="bar"}(g))throw new Error(`"${g}" is not a valid value for ${v}`);break;case"wordSeparator":g||(g=a.DEFAULT_OPTIONS[v]);break;case"fontWeight":case"fontWeightBold":if(typeof g=="number"&&1<=g&&g<=1e3)break;g=d.includes(g)?g:a.DEFAULT_OPTIONS[v];break;case"cursorWidth":g=Math.floor(g);case"lineHeight":case"tabStopWidth":if(g<1)throw new Error(`${v} cannot be less than 1, value: ${g}`);break;case"minimumContrastRatio":g=Math.max(1,Math.min(21,Math.round(10*g)/10));break;case"scrollback":if((g=Math.min(g,4294967295))<0)throw new Error(`${v} cannot be less than 0, value: ${g}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(g<=0)throw new Error(`${v} cannot be less than or equal to 0, value: ${g}`);break;case"rows":case"cols":if(!g&&g!==0)throw new Error(`${v} must be numeric, value: ${g}`);break;case"windowsPty":g=g??{}}return g}}a.OptionsService=p},2660:function(o,a,c){var l=this&&this.__decorate||function(p,m,v,g){var y,b=arguments.length,_=b<3?m:g===null?g=Object.getOwnPropertyDescriptor(m,v):g;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")_=Reflect.decorate(p,m,v,g);else for(var w=p.length-1;w>=0;w--)(y=p[w])&&(_=(b<3?y(_):b>3?y(m,v,_):y(m,v))||_);return b>3&&_&&Object.defineProperty(m,v,_),_},u=this&&this.__param||function(p,m){return function(v,g){m(v,g,p)}};Object.defineProperty(a,"__esModule",{value:!0}),a.OscLinkService=void 0;const h=c(2585);let d=a.OscLinkService=class{constructor(p){this._bufferService=p,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(p){const m=this._bufferService.buffer;if(p.id===void 0){const w=m.addMarker(m.ybase+m.y),S={data:p,id:this._nextId++,lines:[w]};return w.onDispose(()=>this._removeMarkerFromLink(S,w)),this._dataByLinkId.set(S.id,S),S.id}const v=p,g=this._getEntryIdKey(v),y=this._entriesWithId.get(g);if(y)return this.addLineToLink(y.id,m.ybase+m.y),y.id;const b=m.addMarker(m.ybase+m.y),_={id:this._nextId++,key:this._getEntryIdKey(v),data:v,lines:[b]};return b.onDispose(()=>this._removeMarkerFromLink(_,b)),this._entriesWithId.set(_.key,_),this._dataByLinkId.set(_.id,_),_.id}addLineToLink(p,m){const v=this._dataByLinkId.get(p);if(v&&v.lines.every(g=>g.line!==m)){const g=this._bufferService.buffer.addMarker(m);v.lines.push(g),g.onDispose(()=>this._removeMarkerFromLink(v,g))}}getLinkData(p){var m;return(m=this._dataByLinkId.get(p))===null||m===void 0?void 0:m.data}_getEntryIdKey(p){return`${p.id};;${p.uri}`}_removeMarkerFromLink(p,m){const v=p.lines.indexOf(m);v!==-1&&(p.lines.splice(v,1),p.lines.length===0&&(p.data.id!==void 0&&this._entriesWithId.delete(p.key),this._dataByLinkId.delete(p.id)))}};a.OscLinkService=d=l([u(0,h.IBufferService)],d)},8343:(o,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.createDecorator=a.getServiceDependencies=a.serviceRegistry=void 0;const c="di$target",l="di$dependencies";a.serviceRegistry=new Map,a.getServiceDependencies=function(u){return u[l]||[]},a.createDecorator=function(u){if(a.serviceRegistry.has(u))return a.serviceRegistry.get(u);const h=function(d,p,m){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");(function(v,g,y){g[c]===g?g[l].push({id:v,index:y}):(g[l]=[{id:v,index:y}],g[c]=g)})(h,d,m)};return h.toString=()=>u,a.serviceRegistry.set(u,h),h}},2585:(o,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.IDecorationService=a.IUnicodeService=a.IOscLinkService=a.IOptionsService=a.ILogService=a.LogLevelEnum=a.IInstantiationService=a.ICharsetService=a.ICoreService=a.ICoreMouseService=a.IBufferService=void 0;const l=c(8343);var u;a.IBufferService=(0,l.createDecorator)("BufferService"),a.ICoreMouseService=(0,l.createDecorator)("CoreMouseService"),a.ICoreService=(0,l.createDecorator)("CoreService"),a.ICharsetService=(0,l.createDecorator)("CharsetService"),a.IInstantiationService=(0,l.createDecorator)("InstantiationService"),function(h){h[h.TRACE=0]="TRACE",h[h.DEBUG=1]="DEBUG",h[h.INFO=2]="INFO",h[h.WARN=3]="WARN",h[h.ERROR=4]="ERROR",h[h.OFF=5]="OFF"}(u||(a.LogLevelEnum=u={})),a.ILogService=(0,l.createDecorator)("LogService"),a.IOptionsService=(0,l.createDecorator)("OptionsService"),a.IOscLinkService=(0,l.createDecorator)("OscLinkService"),a.IUnicodeService=(0,l.createDecorator)("UnicodeService"),a.IDecorationService=(0,l.createDecorator)("DecorationService")},1480:(o,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.UnicodeService=void 0;const l=c(8460),u=c(225);a.UnicodeService=class{constructor(){this._providers=Object.create(null),this._active="",this._onChange=new l.EventEmitter,this.onChange=this._onChange.event;const h=new u.UnicodeV6;this.register(h),this._active=h.version,this._activeProvider=h}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(h){if(!this._providers[h])throw new Error(`unknown Unicode version "${h}"`);this._active=h,this._activeProvider=this._providers[h],this._onChange.fire(h)}register(h){this._providers[h.version]=h}wcwidth(h){return this._activeProvider.wcwidth(h)}getStringCellWidth(h){let d=0;const p=h.length;for(let m=0;m<p;++m){let v=h.charCodeAt(m);if(55296<=v&&v<=56319){if(++m>=p)return d+this.wcwidth(v);const g=h.charCodeAt(m);56320<=g&&g<=57343?v=1024*(v-55296)+g-56320+65536:d+=this.wcwidth(g)}d+=this.wcwidth(v)}return d}}}},n={};function i(o){var a=n[o];if(a!==void 0)return a.exports;var c=n[o]={exports:{}};return t[o].call(c.exports,c,c.exports,i),c.exports}var r={};return(()=>{var o=r;Object.defineProperty(o,"__esModule",{value:!0}),o.Terminal=void 0;const a=i(9042),c=i(3236),l=i(844),u=i(5741),h=i(8285),d=i(7975),p=i(7090),m=["cols","rows"];class v extends l.Disposable{constructor(y){super(),this._core=this.register(new c.Terminal(y)),this._addonManager=this.register(new u.AddonManager),this._publicOptions=Object.assign({},this._core.options);const b=w=>this._core.options[w],_=(w,S)=>{this._checkReadonlyOptions(w),this._core.options[w]=S};for(const w in this._core.options){const S={get:b.bind(this,w),set:_.bind(this,w)};Object.defineProperty(this._publicOptions,w,S)}}_checkReadonlyOptions(y){if(m.includes(y))throw new Error(`Option "${y}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw new Error("You must set the allowProposedApi option to true to use proposed API")}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onKey(){return this._core.onKey}get onLineFeed(){return this._core.onLineFeed}get onRender(){return this._core.onRender}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onSelectionChange(){return this._core.onSelectionChange}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get element(){return this._core.element}get parser(){return this._parser||(this._parser=new d.ParserApi(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new p.UnicodeApi(this._core)}get textarea(){return this._core.textarea}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._buffer||(this._buffer=this.register(new h.BufferNamespaceApi(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){const y=this._core.coreService.decPrivateModes;let b="none";switch(this._core.coreMouseService.activeProtocol){case"X10":b="x10";break;case"VT200":b="vt200";break;case"DRAG":b="drag";break;case"ANY":b="any"}return{applicationCursorKeysMode:y.applicationCursorKeys,applicationKeypadMode:y.applicationKeypad,bracketedPasteMode:y.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:b,originMode:y.origin,reverseWraparoundMode:y.reverseWraparound,sendFocusMode:y.sendFocus,wraparoundMode:y.wraparound}}get options(){return this._publicOptions}set options(y){for(const b in y)this._publicOptions[b]=y[b]}blur(){this._core.blur()}focus(){this._core.focus()}resize(y,b){this._verifyIntegers(y,b),this._core.resize(y,b)}open(y){this._core.open(y)}attachCustomKeyEventHandler(y){this._core.attachCustomKeyEventHandler(y)}registerLinkProvider(y){return this._core.registerLinkProvider(y)}registerCharacterJoiner(y){return this._checkProposedApi(),this._core.registerCharacterJoiner(y)}deregisterCharacterJoiner(y){this._checkProposedApi(),this._core.deregisterCharacterJoiner(y)}registerMarker(y=0){return this._verifyIntegers(y),this._core.registerMarker(y)}registerDecoration(y){var b,_,w;return this._checkProposedApi(),this._verifyPositiveIntegers((b=y.x)!==null&&b!==void 0?b:0,(_=y.width)!==null&&_!==void 0?_:0,(w=y.height)!==null&&w!==void 0?w:0),this._core.registerDecoration(y)}hasSelection(){return this._core.hasSelection()}select(y,b,_){this._verifyIntegers(y,b,_),this._core.select(y,b,_)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(y,b){this._verifyIntegers(y,b),this._core.selectLines(y,b)}dispose(){super.dispose()}scrollLines(y){this._verifyIntegers(y),this._core.scrollLines(y)}scrollPages(y){this._verifyIntegers(y),this._core.scrollPages(y)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(y){this._verifyIntegers(y),this._core.scrollToLine(y)}clear(){this._core.clear()}write(y,b){this._core.write(y,b)}writeln(y,b){this._core.write(y),this._core.write(`\r
`,b)}paste(y){this._core.paste(y)}refresh(y,b){this._verifyIntegers(y,b),this._core.refresh(y,b)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(y){this._addonManager.loadAddon(this,y)}static get strings(){return a}_verifyIntegers(...y){for(const b of y)if(b===1/0||isNaN(b)||b%1!=0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...y){for(const b of y)if(b&&(b===1/0||isNaN(b)||b%1!=0||b<0))throw new Error("This API only accepts positive integers")}}o.Terminal=v})(),r})())})(eL);var cz=eL.exports;const rl=Object.create(null);rl.open="0";rl.close="1";rl.ping="2";rl.pong="3";rl.message="4";rl.upgrade="5";rl.noop="6";const oS=Object.create(null);Object.keys(rl).forEach(s=>{oS[rl[s]]=s});const w1={type:"error",data:"parser error"},sL=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",nL=typeof ArrayBuffer=="function",iL=s=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(s):s&&s.buffer instanceof ArrayBuffer,dE=({type:s,data:e},t,n)=>sL&&e instanceof Blob?t?n(e):ZM(e,n):nL&&(e instanceof ArrayBuffer||iL(e))?t?n(e):ZM(new Blob([e]),n):n(rl[s]+(e||"")),ZM=(s,e)=>{const t=new FileReader;return t.onload=function(){const n=t.result.split(",")[1];e("b"+(n||""))},t.readAsDataURL(s)};function ex(s){return s instanceof Uint8Array?s:s instanceof ArrayBuffer?new Uint8Array(s):new Uint8Array(s.buffer,s.byteOffset,s.byteLength)}let nC;function uz(s,e){if(sL&&s.data instanceof Blob)return s.data.arrayBuffer().then(ex).then(e);if(nL&&(s.data instanceof ArrayBuffer||iL(s.data)))return e(ex(s.data));dE(s,!1,t=>{nC||(nC=new TextEncoder),e(nC.encode(t))})}const tx="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Im=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let s=0;s<tx.length;s++)Im[tx.charCodeAt(s)]=s;const hz=s=>{let e=s.length*.75,t=s.length,n,i=0,r,o,a,c;s[s.length-1]==="="&&(e--,s[s.length-2]==="="&&e--);const l=new ArrayBuffer(e),u=new Uint8Array(l);for(n=0;n<t;n+=4)r=Im[s.charCodeAt(n)],o=Im[s.charCodeAt(n+1)],a=Im[s.charCodeAt(n+2)],c=Im[s.charCodeAt(n+3)],u[i++]=r<<2|o>>4,u[i++]=(o&15)<<4|a>>2,u[i++]=(a&3)<<6|c&63;return l},dz=typeof ArrayBuffer=="function",fE=(s,e)=>{if(typeof s!="string")return{type:"message",data:rL(s,e)};const t=s.charAt(0);return t==="b"?{type:"message",data:fz(s.substring(1),e)}:oS[t]?s.length>1?{type:oS[t],data:s.substring(1)}:{type:oS[t]}:w1},fz=(s,e)=>{if(dz){const t=hz(s);return rL(t,e)}else return{base64:!0,data:s}},rL=(s,e)=>{switch(e){case"blob":return s instanceof Blob?s:new Blob([s]);case"arraybuffer":default:return s instanceof ArrayBuffer?s:s.buffer}},oL="",pz=(s,e)=>{const t=s.length,n=new Array(t);let i=0;s.forEach((r,o)=>{dE(r,!1,a=>{n[o]=a,++i===t&&e(n.join(oL))})})},gz=(s,e)=>{const t=s.split(oL),n=[];for(let i=0;i<t.length;i++){const r=fE(t[i],e);if(n.push(r),r.type==="error")break}return n};function mz(){return new TransformStream({transform(s,e){uz(s,t=>{const n=t.length;let i;if(n<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,n);else if(n<65536){i=new Uint8Array(3);const r=new DataView(i.buffer);r.setUint8(0,126),r.setUint16(1,n)}else{i=new Uint8Array(9);const r=new DataView(i.buffer);r.setUint8(0,127),r.setBigUint64(1,BigInt(n))}s.data&&typeof s.data!="string"&&(i[0]|=128),e.enqueue(i),e.enqueue(t)})}})}let iC;function C_(s){return s.reduce((e,t)=>e+t.length,0)}function T_(s,e){if(s[0].length===e)return s.shift();const t=new Uint8Array(e);let n=0;for(let i=0;i<e;i++)t[i]=s[0][n++],n===s[0].length&&(s.shift(),n=0);return s.length&&n<s[0].length&&(s[0]=s[0].slice(n)),t}function vz(s,e){iC||(iC=new TextDecoder);const t=[];let n=0,i=-1,r=!1;return new TransformStream({transform(o,a){for(t.push(o);;){if(n===0){if(C_(t)<1)break;const c=T_(t,1);r=(c[0]&128)===128,i=c[0]&127,i<126?n=3:i===126?n=1:n=2}else if(n===1){if(C_(t)<2)break;const c=T_(t,2);i=new DataView(c.buffer,c.byteOffset,c.length).getUint16(0),n=3}else if(n===2){if(C_(t)<8)break;const c=T_(t,8),l=new DataView(c.buffer,c.byteOffset,c.length),u=l.getUint32(0);if(u>Math.pow(2,21)-1){a.enqueue(w1);break}i=u*Math.pow(2,32)+l.getUint32(4),n=3}else{if(C_(t)<i)break;const c=T_(t,i);a.enqueue(fE(r?c:iC.decode(c),e)),n=0}if(i===0||i>s){a.enqueue(w1);break}}}})}const aL=4;function _n(s){if(s)return yz(s)}function yz(s){for(var e in _n.prototype)s[e]=_n.prototype[e];return s}_n.prototype.on=_n.prototype.addEventListener=function(s,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+s]=this._callbacks["$"+s]||[]).push(e),this};_n.prototype.once=function(s,e){function t(){this.off(s,t),e.apply(this,arguments)}return t.fn=e,this.on(s,t),this};_n.prototype.off=_n.prototype.removeListener=_n.prototype.removeAllListeners=_n.prototype.removeEventListener=function(s,e){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var t=this._callbacks["$"+s];if(!t)return this;if(arguments.length==1)return delete this._callbacks["$"+s],this;for(var n,i=0;i<t.length;i++)if(n=t[i],n===e||n.fn===e){t.splice(i,1);break}return t.length===0&&delete this._callbacks["$"+s],this};_n.prototype.emit=function(s){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),t=this._callbacks["$"+s],n=1;n<arguments.length;n++)e[n-1]=arguments[n];if(t){t=t.slice(0);for(var n=0,i=t.length;n<i;++n)t[n].apply(this,e)}return this};_n.prototype.emitReserved=_n.prototype.emit;_n.prototype.listeners=function(s){return this._callbacks=this._callbacks||{},this._callbacks["$"+s]||[]};_n.prototype.hasListeners=function(s){return!!this.listeners(s).length};const K0=typeof Promise=="function"&&typeof Promise.resolve=="function"?e=>Promise.resolve().then(e):(e,t)=>t(e,0),xo=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),bz="arraybuffer";function lL(s,...e){return e.reduce((t,n)=>(s.hasOwnProperty(n)&&(t[n]=s[n]),t),{})}const _z=xo.setTimeout,Sz=xo.clearTimeout;function Q0(s,e){e.useNativeTimers?(s.setTimeoutFn=_z.bind(xo),s.clearTimeoutFn=Sz.bind(xo)):(s.setTimeoutFn=xo.setTimeout.bind(xo),s.clearTimeoutFn=xo.clearTimeout.bind(xo))}const wz=1.33;function kz(s){return typeof s=="string"?Cz(s):Math.ceil((s.byteLength||s.size)*wz)}function Cz(s){let e=0,t=0;for(let n=0,i=s.length;n<i;n++)e=s.charCodeAt(n),e<128?t+=1:e<2048?t+=2:e<55296||e>=57344?t+=3:(n++,t+=4);return t}function cL(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Tz(s){let e="";for(let t in s)s.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(s[t]));return e}function Az(s){let e={},t=s.split("&");for(let n=0,i=t.length;n<i;n++){let r=t[n].split("=");e[decodeURIComponent(r[0])]=decodeURIComponent(r[1])}return e}class Ez extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}}class pE extends _n{constructor(e){super(),this.writable=!1,Q0(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,n){return super.emitReserved("error",new Ez(e,t,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(e){this.readyState==="open"&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=fE(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return e.indexOf(":")===-1?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(e){const t=Tz(e);return t.length?"?"+t:""}}class Mz extends pE{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";const t=()=>{this.readyState="paused",e()};if(this._polling||!this.writable){let n=0;this._polling&&(n++,this.once("pollComplete",function(){--n||t()})),this.writable||(n++,this.once("drain",function(){--n||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){const t=n=>{if(this.readyState==="opening"&&n.type==="open"&&this.onOpen(),n.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(n)};gz(e,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){const e=()=>{this.write([{type:"close"}])};this.readyState==="open"?e():this.once("open",e)}write(e){this.writable=!1,pz(e,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return this.opts.timestampRequests!==!1&&(t[this.opts.timestampParam]=cL()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}}let uL=!1;try{uL=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const xz=uL;function Iz(){}class Rz extends Mz{constructor(e){if(super(e),typeof location<"u"){const t=location.protocol==="https:";let n=location.port;n||(n=t?"443":"80"),this.xd=typeof location<"u"&&e.hostname!==location.hostname||n!==e.port}}doWrite(e,t){const n=this.request({method:"POST",data:e});n.on("success",t),n.on("error",(i,r)=>{this.onError("xhr post error",i,r)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(t,n)=>{this.onError("xhr poll error",t,n)}),this.pollXhr=e}}class il extends _n{constructor(e,t,n){super(),this.createRequest=e,Q0(this,n),this._opts=n,this._method=n.method||"GET",this._uri=t,this._data=n.data!==void 0?n.data:null,this._create()}_create(){var e;const t=lL(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;const n=this._xhr=this.createRequest(t);try{n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let i in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(i)&&n.setRequestHeader(i,this._opts.extraHeaders[i])}}catch{}if(this._method==="POST")try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{n.setRequestHeader("Accept","*/*")}catch{}(e=this._opts.cookieJar)===null||e===void 0||e.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var i;n.readyState===3&&((i=this._opts.cookieJar)===null||i===void 0||i.parseCookies(n.getResponseHeader("set-cookie"))),n.readyState===4&&(n.status===200||n.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof n.status=="number"?n.status:0)},0))},n.send(this._data)}catch(i){this.setTimeoutFn(()=>{this._onError(i)},0);return}typeof document<"u"&&(this._index=il.requestsCount++,il.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=Iz,e)try{this._xhr.abort()}catch{}typeof document<"u"&&delete il.requests[this._index],this._xhr=null}}_onLoad(){const e=this._xhr.responseText;e!==null&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}il.requestsCount=0;il.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",sx);else if(typeof addEventListener=="function"){const s="onpagehide"in xo?"pagehide":"unload";addEventListener(s,sx,!1)}}function sx(){for(let s in il.requests)il.requests.hasOwnProperty(s)&&il.requests[s].abort()}const Lz=function(){const s=hL({xdomain:!1});return s&&s.responseType!==null}();class Pz extends Rz{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=Lz&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new il(hL,this.uri(),e)}}function hL(s){const e=s.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||xz))return new XMLHttpRequest}catch{}if(!e)try{return new xo[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const dL=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class Oz extends pE{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,n=dL?{}:lL(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,n)}catch(i){return this.emitReserved("error",i)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],i=t===e.length-1;dE(n,this.supportsBinary,r=>{try{this.doWrite(n,r)}catch{}i&&K0(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=cL()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const rC=xo.WebSocket||xo.MozWebSocket;let Dz=class extends Oz{createSocket(e,t,n){return dL?new rC(e,t,n):t?new rC(e,t):new rC(e)}doWrite(e,t){this.ws.send(t)}};class Nz extends pE{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved("error",e)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{const t=vz(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),i=mz();i.readable.pipeTo(e.writable),this._writer=i.writable.getWriter();const r=()=>{n.read().then(({done:a,value:c})=>{a||(this.onPacket(c),r())}).catch(a=>{})};r();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this._writer.write(o).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],i=t===e.length-1;this._writer.write(n).then(()=>{i&&K0(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}}const Bz={websocket:Dz,webtransport:Nz,polling:Pz},Fz=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,$z=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function k1(s){if(s.length>8e3)throw"URI too long";const e=s,t=s.indexOf("["),n=s.indexOf("]");t!=-1&&n!=-1&&(s=s.substring(0,t)+s.substring(t,n).replace(/:/g,";")+s.substring(n,s.length));let i=Fz.exec(s||""),r={},o=14;for(;o--;)r[$z[o]]=i[o]||"";return t!=-1&&n!=-1&&(r.source=e,r.host=r.host.substring(1,r.host.length-1).replace(/;/g,":"),r.authority=r.authority.replace("[","").replace("]","").replace(/;/g,":"),r.ipv6uri=!0),r.pathNames=Hz(r,r.path),r.queryKey=Uz(r,r.query),r}function Hz(s,e){const t=/\/{2,9}/g,n=e.replace(t,"/").split("/");return(e.slice(0,1)=="/"||e.length===0)&&n.splice(0,1),e.slice(-1)=="/"&&n.splice(n.length-1,1),n}function Uz(s,e){const t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(n,i,r){i&&(t[i]=r)}),t}const C1=typeof addEventListener=="function"&&typeof removeEventListener=="function",aS=[];C1&&addEventListener("offline",()=>{aS.forEach(s=>s())},!1);class sh extends _n{constructor(e,t){if(super(),this.binaryType=bz,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&typeof e=="object"&&(t=e,e=null),e){const n=k1(e);t.hostname=n.host,t.secure=n.protocol==="https"||n.protocol==="wss",t.port=n.port,n.query&&(t.query=n.query)}else t.host&&(t.hostname=k1(t.host).host);Q0(this,t),this.secure=t.secure!=null?t.secure:typeof location<"u"&&location.protocol==="https:",t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=t.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(n=>{const i=n.prototype.name;this.transports.push(i),this._transportsByName[i]=n}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=Az(this.opts.query)),C1&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},aS.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=aL,t.transport=e,this.id&&(t.sid=this.id);const n=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](n)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const e=this.opts.rememberUpgrade&&sh.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",t=>this._onClose("transport close",t))}onOpen(){this.readyState="open",sh.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(e){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data);break}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let n=0;n<this.writeBuffer.length;n++){const i=this.writeBuffer[n].data;if(i&&(t+=kz(i)),n>0&&t>this._maxPayload)return this.writeBuffer.slice(0,n);t+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,K0(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,n){return this._sendPacket("message",e,t,n),this}send(e,t,n){return this._sendPacket("message",e,t,n),this}_sendPacket(e,t,n,i){if(typeof t=="function"&&(i=t,t=void 0),typeof n=="function"&&(i=n,n=null),this.readyState==="closing"||this.readyState==="closed")return;n=n||{},n.compress=n.compress!==!1;const r={type:e,data:t,options:n};this.emitReserved("packetCreate",r),this.writeBuffer.push(r),i&&this.once("flush",i),this.flush()}close(){const e=()=>{this._onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},n=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():e()}):this.upgrading?n():e()),this}_onError(e){if(sh.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),C1&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const n=aS.indexOf(this._offlineEventListener);n!==-1&&aS.splice(n,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}sh.protocol=aL;class Wz extends sh{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),n=!1;sh.priorWebsocketSuccess=!1;const i=()=>{n||(t.send([{type:"ping",data:"probe"}]),t.once("packet",h=>{if(!n)if(h.type==="pong"&&h.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;sh.priorWebsocketSuccess=t.name==="websocket",this.transport.pause(()=>{n||this.readyState!=="closed"&&(u(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{const d=new Error("probe error");d.transport=t.name,this.emitReserved("upgradeError",d)}}))};function r(){n||(n=!0,u(),t.close(),t=null)}const o=h=>{const d=new Error("probe error: "+h);d.transport=t.name,r(),this.emitReserved("upgradeError",d)};function a(){o("transport closed")}function c(){o("socket closed")}function l(h){t&&h.name!==t.name&&r()}const u=()=>{t.removeListener("open",i),t.removeListener("error",o),t.removeListener("close",a),this.off("close",c),this.off("upgrading",l)};t.once("open",i),t.once("error",o),t.once("close",a),this.once("close",c),this.once("upgrading",l),this._upgrades.indexOf("webtransport")!==-1&&e!=="webtransport"?this.setTimeoutFn(()=>{n||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){const t=[];for(let n=0;n<e.length;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}}let zz=class extends Wz{constructor(e,t={}){const n=typeof e=="object"?e:t;(!n.transports||n.transports&&typeof n.transports[0]=="string")&&(n.transports=(n.transports||["polling","websocket","webtransport"]).map(i=>Bz[i]).filter(i=>!!i)),super(e,n)}};function jz(s,e="",t){let n=s;t=t||typeof location<"u"&&location,s==null&&(s=t.protocol+"//"+t.host),typeof s=="string"&&(s.charAt(0)==="/"&&(s.charAt(1)==="/"?s=t.protocol+s:s=t.host+s),/^(https?|wss?):\/\//.test(s)||(typeof t<"u"?s=t.protocol+"//"+s:s="https://"+s),n=k1(s)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";const r=n.host.indexOf(":")!==-1?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+r+":"+n.port+e,n.href=n.protocol+"://"+r+(t&&t.port===n.port?"":":"+n.port),n}const Vz=typeof ArrayBuffer=="function",Gz=s=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(s):s.buffer instanceof ArrayBuffer,fL=Object.prototype.toString,qz=typeof Blob=="function"||typeof Blob<"u"&&fL.call(Blob)==="[object BlobConstructor]",Kz=typeof File=="function"||typeof File<"u"&&fL.call(File)==="[object FileConstructor]";function gE(s){return Vz&&(s instanceof ArrayBuffer||Gz(s))||qz&&s instanceof Blob||Kz&&s instanceof File}function lS(s,e){if(!s||typeof s!="object")return!1;if(Array.isArray(s)){for(let t=0,n=s.length;t<n;t++)if(lS(s[t]))return!0;return!1}if(gE(s))return!0;if(s.toJSON&&typeof s.toJSON=="function"&&arguments.length===1)return lS(s.toJSON(),!0);for(const t in s)if(Object.prototype.hasOwnProperty.call(s,t)&&lS(s[t]))return!0;return!1}function Qz(s){const e=[],t=s.data,n=s;return n.data=T1(t,e),n.attachments=e.length,{packet:n,buffers:e}}function T1(s,e){if(!s)return s;if(gE(s)){const t={_placeholder:!0,num:e.length};return e.push(s),t}else if(Array.isArray(s)){const t=new Array(s.length);for(let n=0;n<s.length;n++)t[n]=T1(s[n],e);return t}else if(typeof s=="object"&&!(s instanceof Date)){const t={};for(const n in s)Object.prototype.hasOwnProperty.call(s,n)&&(t[n]=T1(s[n],e));return t}return s}function Xz(s,e){return s.data=A1(s.data,e),delete s.attachments,s}function A1(s,e){if(!s)return s;if(s&&s._placeholder===!0){if(typeof s.num=="number"&&s.num>=0&&s.num<e.length)return e[s.num];throw new Error("illegal attachments")}else if(Array.isArray(s))for(let t=0;t<s.length;t++)s[t]=A1(s[t],e);else if(typeof s=="object")for(const t in s)Object.prototype.hasOwnProperty.call(s,t)&&(s[t]=A1(s[t],e));return s}const Yz=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var Gt;(function(s){s[s.CONNECT=0]="CONNECT",s[s.DISCONNECT=1]="DISCONNECT",s[s.EVENT=2]="EVENT",s[s.ACK=3]="ACK",s[s.CONNECT_ERROR=4]="CONNECT_ERROR",s[s.BINARY_EVENT=5]="BINARY_EVENT",s[s.BINARY_ACK=6]="BINARY_ACK"})(Gt||(Gt={}));class Jz{constructor(e){this.replacer=e}encode(e){return(e.type===Gt.EVENT||e.type===Gt.ACK)&&lS(e)?this.encodeAsBinary({type:e.type===Gt.EVENT?Gt.BINARY_EVENT:Gt.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===Gt.BINARY_EVENT||e.type===Gt.BINARY_ACK)&&(t+=e.attachments+"-"),e.nsp&&e.nsp!=="/"&&(t+=e.nsp+","),e.id!=null&&(t+=e.id),e.data!=null&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){const t=Qz(e),n=this.encodeAsString(t.packet),i=t.buffers;return i.unshift(n),i}}class mE extends _n{constructor(e){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof e=="function"?{reviver:e}:e)}add(e){let t;if(typeof e=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const n=t.type===Gt.BINARY_EVENT;n||t.type===Gt.BINARY_ACK?(t.type=n?Gt.EVENT:Gt.ACK,this.reconstructor=new Zz(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if(gE(e)||e.base64)if(this.reconstructor)t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+e)}decodeString(e){let t=0;const n={type:Number(e.charAt(0))};if(Gt[n.type]===void 0)throw new Error("unknown packet type "+n.type);if(n.type===Gt.BINARY_EVENT||n.type===Gt.BINARY_ACK){const r=t+1;for(;e.charAt(++t)!=="-"&&t!=e.length;);const o=e.substring(r,t);if(o!=Number(o)||e.charAt(t)!=="-")throw new Error("Illegal attachments");const a=Number(o);if(!ej(a)||a<0)throw new Error("Illegal attachments");if(a>this.opts.maxAttachments)throw new Error("too many attachments");n.attachments=a}if(e.charAt(t+1)==="/"){const r=t+1;for(;++t&&!(e.charAt(t)===","||t===e.length););n.nsp=e.substring(r,t)}else n.nsp="/";const i=e.charAt(t+1);if(i!==""&&Number(i)==i){const r=t+1;for(;++t;){const o=e.charAt(t);if(o==null||Number(o)!=o){--t;break}if(t===e.length)break}n.id=Number(e.substring(r,t+1))}if(e.charAt(++t)){const r=this.tryParse(e.substr(t));if(mE.isPayloadValid(n.type,r))n.data=r;else throw new Error("invalid payload")}return n}tryParse(e){try{return JSON.parse(e,this.opts.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case Gt.CONNECT:return nx(t);case Gt.DISCONNECT:return t===void 0;case Gt.CONNECT_ERROR:return typeof t=="string"||nx(t);case Gt.EVENT:case Gt.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&Yz.indexOf(t[0])===-1);case Gt.ACK:case Gt.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class Zz{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const t=Xz(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const ej=Number.isInteger||function(s){return typeof s=="number"&&isFinite(s)&&Math.floor(s)===s};function nx(s){return Object.prototype.toString.call(s)==="[object Object]"}const tj=Object.freeze(Object.defineProperty({__proto__:null,Decoder:mE,Encoder:Jz,get PacketType(){return Gt}},Symbol.toStringTag,{value:"Module"}));function da(s,e,t){return s.on(e,t),function(){s.off(e,t)}}const sj=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class pL extends _n{constructor(e,t,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[da(e,"open",this.onopen.bind(this)),da(e,"packet",this.onpacket.bind(this)),da(e,"error",this.onerror.bind(this)),da(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var n,i,r;if(sj.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const o={type:Gt.EVENT,data:t};if(o.options={},o.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){const u=this.ids++,h=t.pop();this._registerAckCallback(u,h),o.id=u}const a=(i=(n=this.io.engine)===null||n===void 0?void 0:n.transport)===null||i===void 0?void 0:i.writable,c=this.connected&&!(!((r=this.io.engine)===null||r===void 0)&&r._hasPingExpired());return this.flags.volatile&&!a||(c?(this.notifyOutgoingListeners(o),this.packet(o)):this.sendBuffer.push(o)),this.flags={},this}_registerAckCallback(e,t){var n;const i=(n=this.flags.timeout)!==null&&n!==void 0?n:this._opts.ackTimeout;if(i===void 0){this.acks[e]=t;return}const r=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let a=0;a<this.sendBuffer.length;a++)this.sendBuffer[a].id===e&&this.sendBuffer.splice(a,1);t.call(this,new Error("operation has timed out"))},i),o=(...a)=>{this.io.clearTimeoutFn(r),t.apply(this,a)};o.withError=!0,this.acks[e]=o}emitWithAck(e,...t){return new Promise((n,i)=>{const r=(o,a)=>o?i(o):n(a);r.withError=!0,t.push(r),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]=="function"&&(t=e.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((i,...r)=>(this._queue[0],i!==null?n.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(i)):(this._queue.shift(),t&&t(null,...r)),n.pending=!1,this._drainQueue())),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||this._queue.length===0)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:Gt.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(n=>String(n.id)===e)){const n=this.acks[e];delete this.acks[e],n.withError&&n.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case Gt.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case Gt.EVENT:case Gt.BINARY_EVENT:this.onevent(e);break;case Gt.ACK:case Gt.BINARY_ACK:this.onack(e);break;case Gt.DISCONNECT:this.ondisconnect();break;case Gt.CONNECT_ERROR:this.destroy();const n=new Error(e.data.message);n.data=e.data.data,this.emitReserved("connect_error",n);break}}onevent(e){const t=e.data||[];e.id!=null&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const n of t)n.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]=="string"&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let n=!1;return function(...i){n||(n=!0,t.packet({type:Gt.ACK,id:e,data:i}))}}onack(e){const t=this.acks[e.id];typeof t=="function"&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:Gt.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const n of t)n.apply(this,e.data)}}}function hm(s){s=s||{},this.ms=s.min||100,this.max=s.max||1e4,this.factor=s.factor||2,this.jitter=s.jitter>0&&s.jitter<=1?s.jitter:0,this.attempts=0}hm.prototype.duration=function(){var s=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),t=Math.floor(e*this.jitter*s);s=Math.floor(e*10)&1?s+t:s-t}return Math.min(s,this.max)|0};hm.prototype.reset=function(){this.attempts=0};hm.prototype.setMin=function(s){this.ms=s};hm.prototype.setMax=function(s){this.max=s};hm.prototype.setJitter=function(s){this.jitter=s};class E1 extends _n{constructor(e,t){var n;super(),this.nsps={},this.subs=[],e&&typeof e=="object"&&(t=e,e=void 0),t=t||{},t.path=t.path||"/socket.io",this.opts=t,Q0(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor((n=t.randomizationFactor)!==null&&n!==void 0?n:.5),this.backoff=new hm({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState="closed",this.uri=e;const i=t.parser||tj;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)===null||t===void 0||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)===null||t===void 0||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)===null||t===void 0||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new zz(this.uri,this.opts);const t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const i=da(t,"open",function(){n.onopen(),e&&e()}),r=a=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",a),e?e(a):this.maybeReconnectOnOpen()},o=da(t,"error",r);if(this._timeout!==!1){const a=this._timeout,c=this.setTimeoutFn(()=>{i(),r(new Error("timeout")),t.close()},a);this.opts.autoUnref&&c.unref(),this.subs.push(()=>{this.clearTimeoutFn(c)})}return this.subs.push(i),this.subs.push(o),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(da(e,"ping",this.onping.bind(this)),da(e,"data",this.ondata.bind(this)),da(e,"error",this.onerror.bind(this)),da(e,"close",this.onclose.bind(this)),da(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(t){this.onclose("parse error",t)}}ondecoded(e){K0(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new pL(this,e,t),this.nsps[e]=n),n}_destroy(e){const t=Object.keys(this.nsps);for(const n of t)if(this.nsps[n].active)return;this._close()}_packet(e){const t=this.encoder.encode(e);for(let n=0;n<t.length;n++)this.engine.write(t[n],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var n;this.cleanup(),(n=this.engine)===null||n===void 0||n.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const n=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(i=>{i?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",i)):e.onreconnect()}))},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const bm={};function cS(s,e){typeof s=="object"&&(e=s,s=void 0),e=e||{};const t=jz(s,e.path||"/socket.io"),n=t.source,i=t.id,r=t.path,o=bm[i]&&r in bm[i].nsps,a=e.forceNew||e["force new connection"]||e.multiplex===!1||o;let c;return a?c=new E1(n,e):(bm[i]||(bm[i]=new E1(n,e)),c=bm[i]),t.query&&!e.query&&(e.query=t.queryKey),c.socket(t.path,e)}Object.assign(cS,{Manager:E1,Socket:pL,io:cS,connect:cS});const nj={class:"terminal-panel__header"},ij={class:"terminal-panel__tabs"},rj={key:0,class:"terminal-panel__empty-tab"},oj=["title","onClick"],aj={class:"terminal-panel__tab-name"},lj={key:0,class:"terminal-panel__idle"},cj=at({name:"TerminalPanel",__name:"TerminalPanel",props:{width:{},workspaceId:{},conversationId:{}},emits:["close"],setup(s,{emit:e}){const t=s,n=pe({}),i=pe(""),r=pe({}),o=pe({});let a=null;const c=pe(null);let l=null,u=null,h=null;const d=pe({}),p=pe({}),m=ye(()=>Object.keys(n.value));function v(A){const M=A==null?void 0:A.conversation_id;return!M||!t.conversationId?!1:M===t.conversationId}function g(){return document.documentElement.getAttribute("data-theme")==="dark"?"dark":"light"}function y(){return{background:"#ffffff",foreground:"#1f1f1f",cursor:"#3d3929",black:"#1f1f1f",red:"#c04a2f",green:"#4b8f60",yellow:"#b48a2c",blue:"#4a6ea9",magenta:"#9b4d88",cyan:"#2a8c8c",white:"#f4f0ea",brightBlack:"#6b6b6b",brightRed:"#d94a3a",brightGreen:"#5c9e6f",brightYellow:"#c49a3c",brightBlue:"#5a7eb9",brightMagenta:"#ab5d98",brightCyan:"#3a9c9c",brightWhite:"#faf9f5"}}function b(){return{background:"#181818",foreground:"#d4d4d8",cursor:"#d4d4d8",black:"#181818",red:"#f87171",green:"#4ade80",yellow:"#fbbf24",blue:"#60a5fa",magenta:"#c084fc",cyan:"#22d3ee",white:"#e4e4e7",brightBlack:"#3f3f46",brightRed:"#fb7185",brightGreen:"#86efac",brightYellow:"#fcd34d",brightBlue:"#93c5fd",brightMagenta:"#d8b4fe",brightCyan:"#67e8f9",brightWhite:"#fafafa"}}function _(){if(!l)return;const A=g()==="dark";l.options.theme=A?b():y()}function w(){if(!c.value)return;const M=g()==="dark"?b():y();l=new cz.Terminal({cursorBlink:!0,fontSize:13,fontFamily:'"JetBrains Mono", "SF Mono", "Fira Code", "Consolas", monospace',theme:M,scrollback:1e4,convertEol:!0,allowTransparency:!1,disableStdin:!0}),l.open(c.value),h=new ResizeObserver(()=>{if(!l||!c.value)return;const R=c.value.getBoundingClientRect();if(R.width<40||R.height<40)return;const P=l._core._renderService.dimensions.css.cell.width||7.8,L=l._core._renderService.dimensions.css.cell.height||17,z=Math.max(2,Math.floor((R.width-16)/P)),Q=Math.max(1,Math.floor((R.height-16)/L));(z!==l.cols||Q!==l.rows)&&l.resize(z,Q)}),h.observe(c.value),u=new MutationObserver(()=>_()),u.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]})}function S(){h==null||h.disconnect(),h=null,u==null||u.disconnect(),u=null,l==null||l.dispose(),l=null}function C(){if(!l||!i.value)return;const A=r.value[i.value]||"";l.clear(),A&&l.write(A,()=>{l==null||l.scrollToBottom()})}function T(A){if(A&&(i.value=A,!o.value[A])){d.value={...d.value,[A]:!1};const M={...p.value};delete M[A],p.value=M,a!=null&&a.connected&&a.emit("get_terminal_output",{session:A,lines:0,conversation_id:t.conversationId})}}Xe(i,A=>{l&&C()}),Xe(m,A=>{A.length>0&&l&&!i.value&&T(A[0])}),Xe(()=>t.workspaceId,(A,M)=>{A&&M&&A!==M&&(a&&(a.disconnect(),a=null),n.value={},i.value="",r.value={},o.value={},d.value={},p.value={},l&&l.clear(),k())}),Xe(()=>t.conversationId,(A,M)=>{A!==M&&(n.value={},i.value="",r.value={},o.value={},d.value={},p.value={},l&&l.clear(),a!=null&&a.connected&&a.emit("terminal_subscribe",{all:!0,conversation_id:A}))});async function k(){a=cS("/",{transports:["websocket","polling"],autoConnect:!1});const A=async()=>{const P=window;if(typeof P.requestSocketToken!="function")return console.warn("[TerminalPanel] requestSocketToken 不可用"),!1;try{const L=await P.requestSocketToken();return a.auth={socket_token:L},!0}catch(L){return console.error("[TerminalPanel] 获取 token 失败:",L),!1}};if(a.io.on("reconnect_attempt",()=>A()),!await A()){console.error("[TerminalPanel] token 获取失败,放弃 socket"),a=null;return}a.on("connect",()=>{a.emit("terminal_subscribe",{all:!0,conversation_id:t.conversationId})}),a.on("disconnect",()=>{}),a.on("terminal_subscribed",P=>{if(P!=null&&P.terminals){const L={};for(const z of P.terminals)L[z.name]={working_dir:z.working_dir,shell:"bash"};n.value=L,P.terminals.length>0&&!i.value&&T(P.terminals[0].name)}}),a.on("terminal_started",P=>{v(P)&&(n.value={...n.value,[P.session]:{working_dir:P.working_dir,shell:"bash"}},i.value||T(P.session))}),a.on("terminal_list_update",P=>{if(v(P)&&P!=null&&P.terminals){const L={};for(const z of P.terminals)L[z.name]={working_dir:z.working_dir,shell:"bash"};n.value=L,P.active&&!i.value&&T(P.active)}}),a.on("terminal_output",P=>{if(!v(P))return;const L=P.session;if(!L)return;const z=P.data||"",Q=p.value[L]||0,W=typeof P.timestamp=="number"?P.timestamp:0;Q>0&&W>0&&W<=Q||(r.value[L]=(r.value[L]||"")+z,L===i.value&&l&&d.value[L]&&l.write(z),i.value||T(L))}),a.on("terminal_input",P=>{v(P)&&!i.value&&P.session&&T(P.session)}),a.on("terminal_closed",P=>{if(!v(P))return;const L={...n.value};delete L[P.session],n.value=L;const z=Object.keys(L);i.value===P.session&&(i.value=z.length>0?z[0]:"")}),a.on("terminal_reset",P=>{if(!v(P))return;const L=P.session||i.value;if(L){r.value={...r.value,[L]:""},o.value={...o.value,[L]:!0};const z={...p.value};delete z[L],p.value=z,L===i.value&&C()}}),a.on("terminal_switched",P=>{v(P)&&P.current&&T(P.current)});const R=P=>{const L=P.session||P.active;if(!L)return;const z=P.output||P.data||"";let Q="";typeof z=="string"?Q=z:Array.isArray(z)&&(Q=z.join(`
`)),Q&&(r.value[L]=Q),o.value={...o.value,[L]:!0},d.value={...d.value,[L]:!0};const W=typeof P.last_event_time=="number"?P.last_event_time:0;p.value={...p.value,[L]:W},L===i.value&&C()};a.on("terminal_output_history",R),a.on("terminal_history",R),a.connect()}return Cn(()=>{ft(()=>{w(),k()})}),xn(()=>{S(),a&&(a.disconnect(),a=null)}),(A,M)=>(F(),$("aside",{class:"terminal-panel",style:Ke({width:s.width+"px"})},[E("header",nj,[E("div",ij,[m.value.length?ge("",!0):(F(),$("div",rj,[...M[1]||(M[1]=[E("span",null,"等待终端会话...",-1)])])),(F(!0),$(Ie,null,tt(m.value,R=>{var P;return F(),$("button",{key:R,type:"button",class:ke(["terminal-panel__tab",{active:R===i.value}]),title:((P=n.value[R])==null?void 0:P.working_dir)||R,onClick:L=>T(R)},[E("span",aj,ae(R),1)],10,oj)}),128))]),E("button",{type:"button",class:"terminal-panel__close","aria-label":"关闭终端面板",onClick:M[0]||(M[0]=R=>A.$emit("close"))},"×")]),E("div",{class:"terminal-panel__body",ref_key:"terminalContainer",ref:c},[m.value.length?ge("",!0):(F(),$("div",lj,[...M[2]||(M[2]=[E("svg",{class:"terminal-panel__idle-svg",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true"},[E("rect",{x:"2",y:"3",width:"20",height:"16",rx:"2",stroke:"currentColor","stroke-width":"1.5"}),E("path",{d:"M6 7h12M6 10h8",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round"})],-1),E("span",null,"当前没有开启的终端",-1)])]))],512)],4))}}),uj=Qt(cj,[["__scopeId","data-v-3e954344"]]),hj={class:"token-display-panel"},dj={class:"token-panel-content"},fj={class:"usage-dashboard"},pj={class:"usage-cell usage-cell--left usage-cell--token panel-card"},gj={class:"stat-grid stat-grid--triple"},mj={class:"stat-block"},vj={class:"stat-value stat-value--accent"},yj={class:"stat-block"},bj={class:"stat-value stat-value--success"},_j={class:"stat-block"},Sj={class:"stat-value stat-value--warning"},wj={class:"usage-cell usage-cell--right usage-cell--performance panel-card"},kj={class:"usage-title"},Cj={key:0,class:"stat-grid stat-grid--double"},Tj={class:"stat-block"},Aj={class:"stat-value"},Ej={class:"stat-block"},Mj={class:"stat-value stat-value--mono"},xj={key:0,class:"stat-foot"},Ij={key:1,class:"usage-placeholder"},Rj={key:1,class:"usage-placeholder"},Lj={class:"usage-cell usage-cell--left usage-cell--quota panel-card"},Pj={class:"stat-grid stat-grid--triple"},Oj={class:"stat-label"},Dj={class:"stat-value"},Nj={key:0,class:"stat-foot"},Bj={class:"usage-cell usage-cell--right usage-cell--resource panel-card"},Fj={class:"stat-grid stat-grid--double"},$j={class:"stat-block"},Hj={class:"stat-value stat-value--mono"},Uj={class:"stat-block"},Wj={class:"stat-value stat-value--mono"},zj={key:0,class:"stat-foot"},jj=at({name:"TokenDrawer",__name:"TokenDrawer",props:{visible:{type:Boolean},collapsed:{type:Boolean},currentConversationTokens:{},currentContextTokens:{},containerStatus:{},containerNetRate:{},projectStorage:{},usageQuota:{},formatTokenCount:{type:Function},formatPercentage:{type:Function},formatBytes:{type:Function},formatQuotaValue:{type:Function},formatResetTime:{type:Function},formatRate:{type:Function}},emits:["toggle"],setup(s,{emit:e}){const t=e,n=s,i=ye(()=>[{key:"fast",label:"常规模型",value:n.usageQuota.fast},{key:"thinking",label:"思考模型",value:n.usageQuota.thinking},{key:"search",label:"搜索",value:n.usageQuota.search}]),r=ye(()=>{const c=n.containerStatus;return!c||!c.stats?!1:typeof c.stats.cpu_percent<"u"?!0:!!(c.stats.memory&&typeof c.stats.memory.used_bytes<"u")}),o=ye(()=>{const c=n.containerStatus;if(!c)return{};if(c.mode!=="docker")return{"status-pill--host":!0};const l=c.state&&c.state.running===!1;return{"status-pill--running":!l,"status-pill--stopped":l}}),a=ye(()=>{const c=n.containerStatus;return c?c.mode!=="docker"?"Host":c.state&&c.state.running===!1?"停止":"运行":"未知"});return(c,l)=>s.visible?(F(),$("div",{key:0,class:ke(["token-drawer",{collapsed:s.collapsed}]),"data-tutorial":"token-drawer"},[E("div",hj,[E("button",{class:"token-close-btn",type:"button","data-tutorial":"token-close",onClick:l[0]||(l[0]=u=>t("toggle")),"aria-label":"收起用量统计"},[...l[1]||(l[1]=[E("span",{class:"sr-only"},"关闭",-1)])]),E("div",dj,[E("div",fj,[E("div",pj,[l[5]||(l[5]=E("div",{class:"usage-title"},"Token 统计",-1)),E("div",gj,[E("div",mj,[l[2]||(l[2]=E("div",{class:"stat-label"},"当前上下文",-1)),E("div",vj,ae(s.formatTokenCount(s.currentContextTokens||0)),1)]),E("div",yj,[l[3]||(l[3]=E("div",{class:"stat-label"},"累计输入",-1)),E("div",bj,ae(s.formatTokenCount(s.currentConversationTokens.cumulative_input_tokens||0)),1)]),E("div",_j,[l[4]||(l[4]=E("div",{class:"stat-label"},"累计输出",-1)),E("div",Sj,ae(s.formatTokenCount(s.currentConversationTokens.cumulative_output_tokens||0)),1)])])]),E("div",wj,[E("div",kj,[l[6]||(l[6]=E("span",null,"性能统计",-1)),s.containerStatus?(F(),$("span",{key:0,class:ke(["status-pill",o.value])},ae(a.value),3)):ge("",!0)]),s.containerStatus&&s.containerStatus.mode==="docker"?(F(),$(Ie,{key:0},[r.value?(F(),$("div",Cj,[E("div",Tj,[l[7]||(l[7]=E("div",{class:"stat-label"},"CPU",-1)),E("div",Aj,ae(s.formatPercentage(s.containerStatus.stats.cpu_percent)),1)]),E("div",Ej,[l[8]||(l[8]=E("div",{class:"stat-label"},"内存",-1)),E("div",Mj,[hn(ae(s.formatBytes(s.containerStatus.stats.memory.used_bytes))+" ",1),s.containerStatus.stats.memory.limit_bytes?(F(),$(Ie,{key:0},[hn(" / "+ae(s.formatBytes(s.containerStatus.stats.memory.limit_bytes)),1)],64)):ge("",!0)]),s.containerStatus.stats.memory.percent?(F(),$("div",xj,ae(s.formatPercentage(s.containerStatus.stats.memory.percent)),1)):ge("",!0)])])):(F(),$("div",Ij,"容器已运行,等待采集指标..."))],64)):(F(),$("div",Rj,"当前运行在宿主机模式,暂无容器指标。"))]),E("div",Lj,[l[9]||(l[9]=E("div",{class:"usage-title"},"额度统计",-1)),E("div",Pj,[(F(!0),$(Ie,null,tt(i.value,u=>(F(),$("div",{class:"stat-block",key:u.key},[E("div",Oj,ae(u.label),1),E("div",Dj,ae(s.formatQuotaValue(u.value)),1),(u.value.count||0)>0?(F(),$("div",Nj," 重置 "+ae(s.formatResetTime(u.value.reset_at)),1)):ge("",!0)]))),128))])]),E("div",Bj,[l[12]||(l[12]=E("div",{class:"usage-title"},"资源统计",-1)),E("div",Fj,[E("div",$j,[l[10]||(l[10]=E("div",{class:"stat-label"},"网络",-1)),E("div",Hj," ↓"+ae(s.formatRate(s.containerNetRate.down_bps))+" ↑"+ae(s.formatRate(s.containerNetRate.up_bps)),1)]),E("div",Uj,[l[11]||(l[11]=E("div",{class:"stat-label"},"存储",-1)),E("div",Wj,[hn(ae(s.formatBytes(s.projectStorage.used_bytes))+" ",1),s.projectStorage.limit_bytes?(F(),$(Ie,{key:0},[hn("/ "+ae(s.formatBytes(s.projectStorage.limit_bytes)),1)],64)):ge("",!0)]),typeof s.projectStorage.usage_percent=="number"?(F(),$("div",zj,ae(s.projectStorage.usage_percent.toFixed(1))+"% ",1)):ge("",!0)])])])])])])],2)):ge("",!0)}}),Vj={class:"quick-menu-list"},Gj=["disabled"],qj=["disabled"],Kj=["disabled"],Qj=["disabled"],Xj=["disabled"],Yj=["disabled"],Jj={class:"entry-arrow"},Zj=["disabled"],e9={key:0,class:"quick-submenu tool-submenu"},t9={key:0,class:"submenu-status"},s9={key:1,class:"submenu-empty"},n9={key:2,class:"submenu-list tool-submenu-list"},i9=["onClick","disabled"],r9={class:"submenu-label icon-label"},o9={class:"entry-arrow"},a9={key:0,class:"quick-submenu settings-submenu"},l9={class:"submenu-list"},c9=["disabled"],u9=["disabled"],h9=["disabled"],d9=["disabled"],f9=at({name:"QuickMenu",__name:"QuickMenu",props:{open:{type:Boolean},isConnected:{type:Boolean},uploading:{type:Boolean},streamingMessage:{type:Boolean},thinkingMode:{type:Boolean},toolMenuOpen:{type:Boolean},toolSettings:{},toolSettingsLoading:{type:Boolean},settingsOpen:{type:Boolean},compressing:{type:Boolean},currentConversationId:{},iconStyle:{type:Function},toolCategoryIcon:{type:Function},modeMenuOpen:{type:Boolean},runMode:{},modelMenuOpen:{type:Boolean},modelOptions:{},currentModelKey:{},blockUpload:{type:Boolean},blockToolToggle:{type:Boolean},blockRealtimeTerminal:{type:Boolean},blockFocusPanel:{type:Boolean},blockTokenPanel:{type:Boolean},blockCompressConversation:{type:Boolean},blockConversationReview:{type:Boolean},executionModeEnabled:{type:Boolean},goalModeArmed:{type:Boolean},goalRunning:{type:Boolean},goalProgress:{}},emits:["quick-upload","toggle-tool-menu","toggle-settings","update-tool-category","realtime-terminal","toggle-token-panel","compress-conversation","toggle-approval-panel","toggle-mode-menu","select-run-mode","toggle-model-menu","select-model","open-review","pick-video","open-path-authorization","toggle-goal-mode"],setup(s){const e=s,t=o=>e.iconStyle?e.iconStyle(o):{},n=ye(()=>{var a;const o=(a=e.modelOptions)==null?void 0:a.find(c=>c.key===e.currentModelKey);return!!(o!=null&&o.supportsImage)}),i=ye(()=>{var a;const o=(a=e.modelOptions)==null?void 0:a.find(c=>c.key===e.currentModelKey);return!!(o!=null&&o.supportsVideo)}),r=ye(()=>{var o;return String(((o=e.goalProgress)==null?void 0:o.status)||"").toLowerCase()==="done"});return(o,a)=>(F(),Wt(us,{name:"quick-menu"},{default:Vt(()=>[s.open?(F(),$("div",{key:0,class:"quick-menu",onClick:a[12]||(a[12]=Ne(()=>{},["stop"]))},[E("div",Vj,[E("button",{type:"button",class:"menu-entry","data-tutorial":"quick-upload",onClick:a[0]||(a[0]=c=>o.$emit("quick-upload")),disabled:!s.isConnected||s.uploading},ae(s.uploading?"上传中...":"上传文件"),9,Gj),E("button",{type:"button",class:"menu-entry","data-tutorial":"quick-review",onClick:a[1]||(a[1]=Ne(c=>o.$emit("open-review"),["stop"])),disabled:!s.isConnected||s.streamingMessage}," 对话回顾 ",8,qj),n.value?(F(),$("button",{key:0,type:"button",class:"menu-entry","data-tutorial":"quick-send-image",onClick:a[2]||(a[2]=Ne(c=>o.$emit("pick-images"),["stop"])),disabled:!s.isConnected||s.streamingMessage}," 发送图片 ",8,Kj)):ge("",!0),i.value?(F(),$("button",{key:1,type:"button",class:"menu-entry","data-tutorial":"quick-send-video",onClick:a[3]||(a[3]=Ne(c=>o.$emit("pick-video"),["stop"])),disabled:!s.isConnected||s.streamingMessage}," 发送视频 ",8,Qj)):ge("",!0),E("button",{type:"button",class:"menu-entry has-submenu","data-tutorial":"quick-tool-menu",onClick:a[4]||(a[4]=Ne(c=>o.$emit("toggle-tool-menu"),["stop"])),disabled:!s.isConnected},[...a[13]||(a[13]=[hn(" 工具禁用 ",-1),E("span",{class:"entry-arrow"},"",-1)])],8,Xj),E("button",{type:"button",class:ke(["menu-entry",{"goal-entry-active":s.goalModeArmed||s.goalRunning||r.value}]),onClick:a[5]||(a[5]=Ne(c=>o.$emit("toggle-goal-mode"),["stop"])),disabled:!s.isConnected},[a[14]||(a[14]=hn(" 目标模式 ",-1)),E("span",Jj,[s.goalRunning?(F(),$(Ie,{key:0},[hn("运行中")],64)):r.value?(F(),$(Ie,{key:1},[hn("完成")],64)):(F(),$(Ie,{key:2},[hn(ae(s.goalModeArmed?"已就绪":""),1)],64))])],10,Yj),E("button",{type:"button",class:"menu-entry has-submenu","data-tutorial":"quick-settings-menu",onClick:a[6]||(a[6]=Ne(c=>o.$emit("toggle-settings"),["stop"])),disabled:!s.isConnected},[...a[15]||(a[15]=[hn(" 设置 ",-1),E("span",{class:"entry-arrow"},"",-1)])],8,Zj)]),Qe(us,{name:"submenu-slide"},{default:Vt(()=>[s.toolMenuOpen?(F(),$("div",e9,[s.toolSettingsLoading?(F(),$("div",t9,"正在同步工具状态...")):s.toolSettings.length?(F(),$("div",n9,[(F(!0),$(Ie,null,tt(s.toolSettings,c=>(F(),$("button",{key:c.id,type:"button",class:ke(["menu-entry submenu-entry",{disabled:!c.enabled||c.locked}]),onClick:Ne(l=>o.$emit("update-tool-category",c.id,!c.enabled),["stop"]),disabled:s.streamingMessage||!s.isConnected||s.toolSettingsLoading},[E("span",r9,[E("span",{class:"icon icon-sm",style:Ke(t(s.toolCategoryIcon(c.id))),"aria-hidden":"true"},null,4),E("span",null,ae(c.label),1)]),E("span",o9,[c.locked?(F(),$(Ie,{key:0},[hn(" 被管理员锁定 ")],64)):(F(),$(Ie,{key:1},[hn(ae(c.enabled?"禁用":"启用"),1)],64))])],10,i9))),128))])):(F(),$("div",s9,"暂无可控工具"))])):ge("",!0)]),_:1}),Qe(us,{name:"submenu-slide"},{default:Vt(()=>[s.settingsOpen?(F(),$("div",a9,[E("div",l9,[E("button",{type:"button",class:"menu-entry submenu-entry",onClick:a[7]||(a[7]=c=>o.$emit("realtime-terminal")),disabled:!s.isConnected}," 实时终端 ",8,c9),E("button",{type:"button",class:"menu-entry submenu-entry","data-tutorial":"settings-token-panel",onClick:a[8]||(a[8]=c=>{console.log("[UI_DEBUG] QuickMenu 用量统计按钮 clicked, emitting toggle-token-panel with true"),o.$emit("toggle-token-panel",!0)}),disabled:!s.currentConversationId}," 用量统计 ",8,u9),E("button",{type:"button",class:"menu-entry submenu-entry",onClick:a[9]||(a[9]=c=>o.$emit("compress-conversation")),disabled:s.compressing||s.streamingMessage||!s.isConnected},ae(s.compressing?"压缩中...":"压缩对话"),9,h9),E("button",{type:"button",class:"menu-entry submenu-entry",onClick:a[10]||(a[10]=c=>o.$emit("toggle-approval-panel")),disabled:!s.currentConversationId}," 审批面板 ",8,d9),s.executionModeEnabled?(F(),$("button",{key:0,type:"button",class:"menu-entry submenu-entry",onClick:a[11]||(a[11]=c=>o.$emit("open-path-authorization"))}," 路径授权 ")):ge("",!0)])])):ge("",!0)]),_:1})])):ge("",!0)]),_:1}))}}),gL=Qt(f9,[["__scopeId","data-v-1e329b70"]]);function ui(s){this.content=s}ui.prototype={constructor:ui,find:function(s){for(var e=0;e<this.content.length;e+=2)if(this.content[e]===s)return e;return-1},get:function(s){var e=this.find(s);return e==-1?void 0:this.content[e+1]},update:function(s,e,t){var n=t&&t!=s?this.remove(t):this,i=n.find(s),r=n.content.slice();return i==-1?r.push(t||s,e):(r[i+1]=e,t&&(r[i]=t)),new ui(r)},remove:function(s){var e=this.find(s);if(e==-1)return this;var t=this.content.slice();return t.splice(e,2),new ui(t)},addToStart:function(s,e){return new ui([s,e].concat(this.remove(s).content))},addToEnd:function(s,e){var t=this.remove(s).content.slice();return t.push(s,e),new ui(t)},addBefore:function(s,e,t){var n=this.remove(e),i=n.content.slice(),r=n.find(s);return i.splice(r==-1?i.length:r,0,e,t),new ui(i)},forEach:function(s){for(var e=0;e<this.content.length;e+=2)s(this.content[e],this.content[e+1])},prepend:function(s){return s=ui.from(s),s.size?new ui(s.content.concat(this.subtract(s).content)):this},append:function(s){return s=ui.from(s),s.size?new ui(this.subtract(s).content.concat(s.content)):this},subtract:function(s){var e=this;s=ui.from(s);for(var t=0;t<s.content.length;t+=2)e=e.remove(s.content[t]);return e},toObject:function(){var s={};return this.forEach(function(e,t){s[e]=t}),s},get size(){return this.content.length>>1}};ui.from=function(s){if(s instanceof ui)return s;var e=[];if(s)for(var t in s)e.push(t,s[t]);return new ui(e)};function mL(s,e,t){for(let n=0;;n++){if(n==s.childCount||n==e.childCount)return s.childCount==e.childCount?null:t;let i=s.child(n),r=e.child(n);if(i==r){t+=i.nodeSize;continue}if(!i.sameMarkup(r))return t;if(i.isText&&i.text!=r.text){for(let o=0;i.text[o]==r.text[o];o++)t++;return t}if(i.content.size||r.content.size){let o=mL(i.content,r.content,t+1);if(o!=null)return o}t+=i.nodeSize}}function vL(s,e,t,n){for(let i=s.childCount,r=e.childCount;;){if(i==0||r==0)return i==r?null:{a:t,b:n};let o=s.child(--i),a=e.child(--r),c=o.nodeSize;if(o==a){t-=c,n-=c;continue}if(!o.sameMarkup(a))return{a:t,b:n};if(o.isText&&o.text!=a.text){let l=0,u=Math.min(o.text.length,a.text.length);for(;l<u&&o.text[o.text.length-l-1]==a.text[a.text.length-l-1];)l++,t--,n--;return{a:t,b:n}}if(o.content.size||a.content.size){let l=vL(o.content,a.content,t-1,n-1);if(l)return l}t-=c,n-=c}}let Fe=class Bi{constructor(e,t){if(this.content=e,this.size=t||0,t==null)for(let n=0;n<e.length;n++)this.size+=e[n].nodeSize}nodesBetween(e,t,n,i=0,r){for(let o=0,a=0;a<t;o++){let c=this.content[o],l=a+c.nodeSize;if(l>e&&n(c,i+a,r||null,o)!==!1&&c.content.size){let u=a+1;c.nodesBetween(Math.max(0,e-u),Math.min(c.content.size,t-u),n,i+u)}a=l}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,t,n,i){let r="",o=!0;return this.nodesBetween(e,t,(a,c)=>{let l=a.isText?a.text.slice(Math.max(e,c)-c,t-c):a.isLeaf?i?typeof i=="function"?i(a):i:a.type.spec.leafText?a.type.spec.leafText(a):"":"";a.isBlock&&(a.isLeaf&&l||a.isTextblock)&&n&&(o?o=!1:r+=n),r+=l},0),r}append(e){if(!e.size)return this;if(!this.size)return e;let t=this.lastChild,n=e.firstChild,i=this.content.slice(),r=0;for(t.isText&&t.sameMarkup(n)&&(i[i.length-1]=t.withText(t.text+n.text),r=1);r<e.content.length;r++)i.push(e.content[r]);return new Bi(i,this.size+e.size)}cut(e,t=this.size){if(e==0&&t==this.size)return this;let n=[],i=0;if(t>e)for(let r=0,o=0;o<t;r++){let a=this.content[r],c=o+a.nodeSize;c>e&&((o<e||c>t)&&(a.isText?a=a.cut(Math.max(0,e-o),Math.min(a.text.length,t-o)):a=a.cut(Math.max(0,e-o-1),Math.min(a.content.size,t-o-1))),n.push(a),i+=a.nodeSize),o=c}return new Bi(n,i)}cutByIndex(e,t){return e==t?Bi.empty:e==0&&t==this.content.length?this:new Bi(this.content.slice(e,t))}replaceChild(e,t){let n=this.content[e];if(n==t)return this;let i=this.content.slice(),r=this.size+t.nodeSize-n.nodeSize;return i[e]=t,new Bi(i,r)}addToStart(e){return new Bi([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new Bi(this.content.concat(e),this.size+e.nodeSize)}eq(e){if(this.content.length!=e.content.length)return!1;for(let t=0;t<this.content.length;t++)if(!this.content[t].eq(e.content[t]))return!1;return!0}get firstChild(){return this.content.length?this.content[0]:null}get lastChild(){return this.content.length?this.content[this.content.length-1]:null}get childCount(){return this.content.length}child(e){let t=this.content[e];if(!t)throw new RangeError("Index "+e+" out of range for "+this);return t}maybeChild(e){return this.content[e]||null}forEach(e){for(let t=0,n=0;t<this.content.length;t++){let i=this.content[t];e(i,n,t),n+=i.nodeSize}}findDiffStart(e,t=0){return mL(this,e,t)}findDiffEnd(e,t=this.size,n=e.size){return vL(this,e,t,n)}findIndex(e){if(e==0)return A_(0,e);if(e==this.size)return A_(this.content.length,e);if(e>this.size||e<0)throw new RangeError(`Position ${e} outside of fragment (${this})`);for(let t=0,n=0;;t++){let i=this.child(t),r=n+i.nodeSize;if(r>=e)return r==e?A_(t+1,r):A_(t,n);n=r}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(e=>e.toJSON()):null}static fromJSON(e,t){if(!t)return Bi.empty;if(!Array.isArray(t))throw new RangeError("Invalid input for Fragment.fromJSON");return Bi.fromArray(t.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return Bi.empty;let t,n=0;for(let i=0;i<e.length;i++){let r=e[i];n+=r.nodeSize,i&&r.isText&&e[i-1].sameMarkup(r)?(t||(t=e.slice(0,i)),t[t.length-1]=r.withText(t[t.length-1].text+r.text)):t&&t.push(r)}return new Bi(t||e,n)}static from(e){if(!e)return Bi.empty;if(e instanceof Bi)return e;if(Array.isArray(e))return this.fromArray(e);if(e.attrs)return new Bi([e],e.nodeSize);throw new RangeError("Can not convert "+e+" to a Fragment"+(e.nodesBetween?" (looks like multiple versions of prosemirror-model were loaded)":""))}};Fe.empty=new Fe([],0);const oC={index:0,offset:0};function A_(s,e){return oC.index=s,oC.offset=e,oC}function yw(s,e){if(s===e)return!0;if(!(s&&typeof s=="object")||!(e&&typeof e=="object"))return!1;let t=Array.isArray(s);if(Array.isArray(e)!=t)return!1;if(t){if(s.length!=e.length)return!1;for(let n=0;n<s.length;n++)if(!yw(s[n],e[n]))return!1}else{for(let n in s)if(!(n in e)||!yw(s[n],e[n]))return!1;for(let n in e)if(!(n in s))return!1}return!0}let _s=class M1{constructor(e,t){this.type=e,this.attrs=t}addToSet(e){let t,n=!1;for(let i=0;i<e.length;i++){let r=e[i];if(this.eq(r))return e;if(this.type.excludes(r.type))t||(t=e.slice(0,i));else{if(r.type.excludes(this.type))return e;!n&&r.type.rank>this.type.rank&&(t||(t=e.slice(0,i)),t.push(this),n=!0),t&&t.push(r)}}return t||(t=e.slice()),n||t.push(this),t}removeFromSet(e){for(let t=0;t<e.length;t++)if(this.eq(e[t]))return e.slice(0,t).concat(e.slice(t+1));return e}isInSet(e){for(let t=0;t<e.length;t++)if(this.eq(e[t]))return!0;return!1}eq(e){return this==e||this.type==e.type&&yw(this.attrs,e.attrs)}toJSON(){let e={type:this.type.name};for(let t in this.attrs){e.attrs=this.attrs;break}return e}static fromJSON(e,t){if(!t)throw new RangeError("Invalid input for Mark.fromJSON");let n=e.marks[t.type];if(!n)throw new RangeError(`There is no mark type ${t.type} in this schema`);let i=n.create(t.attrs);return n.checkAttrs(i.attrs),i}static sameSet(e,t){if(e==t)return!0;if(e.length!=t.length)return!1;for(let n=0;n<e.length;n++)if(!e[n].eq(t[n]))return!1;return!0}static setFrom(e){if(!e||Array.isArray(e)&&e.length==0)return M1.none;if(e instanceof M1)return[e];let t=e.slice();return t.sort((n,i)=>n.type.rank-i.type.rank),t}};_s.none=[];let bw=class extends Error{},nt=class sp{constructor(e,t,n){this.content=e,this.openStart=t,this.openEnd=n}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(e,t){let n=bL(this.content,e+this.openStart,t,this.openStart+1,this.openEnd+1);return n&&new sp(n,this.openStart,this.openEnd)}removeBetween(e,t){return new sp(yL(this.content,e+this.openStart,t+this.openStart),this.openStart,this.openEnd)}eq(e){return this.content.eq(e.content)&&this.openStart==e.openStart&&this.openEnd==e.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let e={content:this.content.toJSON()};return this.openStart>0&&(e.openStart=this.openStart),this.openEnd>0&&(e.openEnd=this.openEnd),e}static fromJSON(e,t){if(!t)return sp.empty;let n=t.openStart||0,i=t.openEnd||0;if(typeof n!="number"||typeof i!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new sp(Fe.fromJSON(e,t.content),n,i)}static maxOpen(e,t=!0){let n=0,i=0;for(let r=e.firstChild;r&&!r.isLeaf&&(t||!r.type.spec.isolating);r=r.firstChild)n++;for(let r=e.lastChild;r&&!r.isLeaf&&(t||!r.type.spec.isolating);r=r.lastChild)i++;return new sp(e,n,i)}};nt.empty=new nt(Fe.empty,0,0);function yL(s,e,t){let{index:n,offset:i}=s.findIndex(e),r=s.maybeChild(n),{index:o,offset:a}=s.findIndex(t);if(i==e||r.isText){if(a!=t&&!s.child(o).isText)throw new RangeError("Removing non-flat range");return s.cut(0,e).append(s.cut(t))}if(n!=o)throw new RangeError("Removing non-flat range");return s.replaceChild(n,r.copy(yL(r.content,e-i-1,t-i-1)))}function bL(s,e,t,n,i,r){let{index:o,offset:a}=s.findIndex(e),c=s.maybeChild(o);if(a==e||c.isText)return r&&n<=0&&i<=0&&!r.canReplace(o,o,t)?null:s.cut(0,e).append(t).append(s.cut(e));let l=bL(c.content,e-a-1,t,o==0?n-1:0,o==s.childCount-1?i-1:0,c);return l&&s.replaceChild(o,c.copy(l))}function p9(s,e,t){if(t.openStart>s.depth)throw new bw("Inserted content deeper than insertion position");if(s.depth-t.openStart!=e.depth-t.openEnd)throw new bw("Inconsistent open depths");return _L(s,e,t,0)}function _L(s,e,t,n){let i=s.index(n),r=s.node(n);if(i==e.index(n)&&n<s.depth-t.openStart){let o=_L(s,e,t,n+1);return r.copy(r.content.replaceChild(i,o))}else if(t.content.size)if(!t.openStart&&!t.openEnd&&s.depth==n&&e.depth==n){let o=s.parent,a=o.content;return Sf(o,a.cut(0,s.parentOffset).append(t.content).append(a.cut(e.parentOffset)))}else{let{start:o,end:a}=g9(t,s);return Sf(r,wL(s,o,a,e,n))}else return Sf(r,_w(s,e,n))}function SL(s,e){if(!e.type.compatibleContent(s.type))throw new bw("Cannot join "+e.type.name+" onto "+s.type.name)}function x1(s,e,t){let n=s.node(t);return SL(n,e.node(t)),n}function _f(s,e){let t=e.length-1;t>=0&&s.isText&&s.sameMarkup(e[t])?e[t]=s.withText(e[t].text+s.text):e.push(s)}function Tv(s,e,t,n){let i=(e||s).node(t),r=0,o=e?e.index(t):i.childCount;s&&(r=s.index(t),s.depth>t?r++:s.textOffset&&(_f(s.nodeAfter,n),r++));for(let a=r;a<o;a++)_f(i.child(a),n);e&&e.depth==t&&e.textOffset&&_f(e.nodeBefore,n)}function Sf(s,e){return s.type.checkContent(e),s.copy(e)}function wL(s,e,t,n,i){let r=s.depth>i&&x1(s,e,i+1),o=n.depth>i&&x1(t,n,i+1),a=[];return Tv(null,s,i,a),r&&o&&e.index(i)==t.index(i)?(SL(r,o),_f(Sf(r,wL(s,e,t,n,i+1)),a)):(r&&_f(Sf(r,_w(s,e,i+1)),a),Tv(e,t,i,a),o&&_f(Sf(o,_w(t,n,i+1)),a)),Tv(n,null,i,a),new Fe(a)}function _w(s,e,t){let n=[];if(Tv(null,s,t,n),s.depth>t){let i=x1(s,e,t+1);_f(Sf(i,_w(s,e,t+1)),n)}return Tv(e,null,t,n),new Fe(n)}function g9(s,e){let t=e.depth-s.openStart,i=e.node(t).copy(s.content);for(let r=t-1;r>=0;r--)i=e.node(r).copy(Fe.from(i));return{start:i.resolveNoCache(s.openStart+t),end:i.resolveNoCache(i.content.size-s.openEnd-t)}}class qv{constructor(e,t,n){this.pos=e,this.path=t,this.parentOffset=n,this.depth=t.length/3-1}resolveDepth(e){return e==null?this.depth:e<0?this.depth+e:e}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(e){return this.path[this.resolveDepth(e)*3]}index(e){return this.path[this.resolveDepth(e)*3+1]}indexAfter(e){return e=this.resolveDepth(e),this.index(e)+(e==this.depth&&!this.textOffset?0:1)}start(e){return e=this.resolveDepth(e),e==0?0:this.path[e*3-1]+1}end(e){return e=this.resolveDepth(e),this.start(e)+this.node(e).content.size}before(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position before the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]}after(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position after the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]+this.path[e*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let e=this.parent,t=this.index(this.depth);if(t==e.childCount)return null;let n=this.pos-this.path[this.path.length-1],i=e.child(t);return n?e.child(t).cut(n):i}get nodeBefore(){let e=this.index(this.depth),t=this.pos-this.path[this.path.length-1];return t?this.parent.child(e).cut(0,t):e==0?null:this.parent.child(e-1)}posAtIndex(e,t){t=this.resolveDepth(t);let n=this.path[t*3],i=t==0?0:this.path[t*3-1]+1;for(let r=0;r<e;r++)i+=n.child(r).nodeSize;return i}marks(){let e=this.parent,t=this.index();if(e.content.size==0)return _s.none;if(this.textOffset)return e.child(t).marks;let n=e.maybeChild(t-1),i=e.maybeChild(t);if(!n){let a=n;n=i,i=a}let r=n.marks;for(var o=0;o<r.length;o++)r[o].type.spec.inclusive===!1&&(!i||!r[o].isInSet(i.marks))&&(r=r[o--].removeFromSet(r));return r}marksAcross(e){let t=this.parent.maybeChild(this.index());if(!t||!t.isInline)return null;let n=t.marks,i=e.parent.maybeChild(e.index());for(var r=0;r<n.length;r++)n[r].type.spec.inclusive===!1&&(!i||!n[r].isInSet(i.marks))&&(n=n[r--].removeFromSet(n));return n}sharedDepth(e){for(let t=this.depth;t>0;t--)if(this.start(t)<=e&&this.end(t)>=e)return t;return 0}blockRange(e=this,t){if(e.pos<this.pos)return e.blockRange(this);for(let n=this.depth-(this.parent.inlineContent||this.pos==e.pos?1:0);n>=0;n--)if(e.pos<=this.end(n)&&(!t||t(this.node(n))))return new Sw(this,e,n);return null}sameParent(e){return this.pos-this.parentOffset==e.pos-e.parentOffset}max(e){return e.pos>this.pos?e:this}min(e){return e.pos<this.pos?e:this}toString(){let e="";for(let t=1;t<=this.depth;t++)e+=(e?"/":"")+this.node(t).type.name+"_"+this.index(t-1);return e+":"+this.parentOffset}static resolve(e,t){if(!(t>=0&&t<=e.content.size))throw new RangeError("Position "+t+" out of range");let n=[],i=0,r=t;for(let o=e;;){let{index:a,offset:c}=o.content.findIndex(r),l=r-c;if(n.push(o,a,i+c),!l||(o=o.child(a),o.isText))break;r=l-1,i+=c+1}return new qv(t,n,r)}static resolveCached(e,t){let n=ix.get(e);if(n)for(let r=0;r<n.elts.length;r++){let o=n.elts[r];if(o.pos==t)return o}else ix.set(e,n=new m9);let i=n.elts[n.i]=qv.resolve(e,t);return n.i=(n.i+1)%v9,i}}class m9{constructor(){this.elts=[],this.i=0}}const v9=12,ix=new WeakMap;class Sw{constructor(e,t,n){this.$from=e,this.$to=t,this.depth=n}get start(){return this.$from.before(this.depth+1)}get end(){return this.$to.after(this.depth+1)}get parent(){return this.$from.node(this.depth)}get startIndex(){return this.$from.index(this.depth)}get endIndex(){return this.$to.indexAfter(this.depth)}}const y9=Object.create(null);let yc=class I1{constructor(e,t,n,i=_s.none){this.type=e,this.attrs=t,this.marks=i,this.content=n||Fe.empty}get children(){return this.content.content}get nodeSize(){return this.isLeaf?1:2+this.content.size}get childCount(){return this.content.childCount}child(e){return this.content.child(e)}maybeChild(e){return this.content.maybeChild(e)}forEach(e){this.content.forEach(e)}nodesBetween(e,t,n,i=0){this.content.nodesBetween(e,t,n,i,this)}descendants(e){this.nodesBetween(0,this.content.size,e)}get textContent(){return this.isLeaf&&this.type.spec.leafText?this.type.spec.leafText(this):this.textBetween(0,this.content.size,"")}textBetween(e,t,n,i){return this.content.textBetween(e,t,n,i)}get firstChild(){return this.content.firstChild}get lastChild(){return this.content.lastChild}eq(e){return this==e||this.sameMarkup(e)&&this.content.eq(e.content)}sameMarkup(e){return this.hasMarkup(e.type,e.attrs,e.marks)}hasMarkup(e,t,n){return this.type==e&&yw(this.attrs,t||e.defaultAttrs||y9)&&_s.sameSet(this.marks,n||_s.none)}copy(e=null){return e==this.content?this:new I1(this.type,this.attrs,e,this.marks)}mark(e){return e==this.marks?this:new I1(this.type,this.attrs,this.content,e)}cut(e,t=this.content.size){return e==0&&t==this.content.size?this:this.copy(this.content.cut(e,t))}slice(e,t=this.content.size,n=!1){if(e==t)return nt.empty;let i=this.resolve(e),r=this.resolve(t),o=n?0:i.sharedDepth(t),a=i.start(o),l=i.node(o).content.cut(i.pos-a,r.pos-a);return new nt(l,i.depth-o,r.depth-o)}replace(e,t,n){return p9(this.resolve(e),this.resolve(t),n)}nodeAt(e){for(let t=this;;){let{index:n,offset:i}=t.content.findIndex(e);if(t=t.maybeChild(n),!t)return null;if(i==e||t.isText)return t;e-=i+1}}childAfter(e){let{index:t,offset:n}=this.content.findIndex(e);return{node:this.content.maybeChild(t),index:t,offset:n}}childBefore(e){if(e==0)return{node:null,index:0,offset:0};let{index:t,offset:n}=this.content.findIndex(e);if(n<e)return{node:this.content.child(t),index:t,offset:n};let i=this.content.child(t-1);return{node:i,index:t-1,offset:n-i.nodeSize}}resolve(e){return qv.resolveCached(this,e)}resolveNoCache(e){return qv.resolve(this,e)}rangeHasMark(e,t,n){let i=!1;return t>e&&this.nodesBetween(e,t,r=>(n.isInSet(r.marks)&&(i=!0),!i)),i}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let e=this.type.name;return this.content.size&&(e+="("+this.content.toStringInner()+")"),kL(this.marks,e)}contentMatchAt(e){let t=this.type.contentMatch.matchFragment(this.content,0,e);if(!t)throw new Error("Called contentMatchAt on a node with invalid content");return t}canReplace(e,t,n=Fe.empty,i=0,r=n.childCount){let o=this.contentMatchAt(e).matchFragment(n,i,r),a=o&&o.matchFragment(this.content,t);if(!a||!a.validEnd)return!1;for(let c=i;c<r;c++)if(!this.type.allowsMarks(n.child(c).marks))return!1;return!0}canReplaceWith(e,t,n,i){if(i&&!this.type.allowsMarks(i))return!1;let r=this.contentMatchAt(e).matchType(n),o=r&&r.matchFragment(this.content,t);return o?o.validEnd:!1}canAppend(e){return e.content.size?this.canReplace(this.childCount,this.childCount,e.content):this.type.compatibleContent(e.type)}check(){this.type.checkContent(this.content),this.type.checkAttrs(this.attrs);let e=_s.none;for(let t=0;t<this.marks.length;t++){let n=this.marks[t];n.type.checkAttrs(n.attrs),e=n.addToSet(e)}if(!_s.sameSet(e,this.marks))throw new RangeError(`Invalid collection of marks for node ${this.type.name}: ${this.marks.map(t=>t.type.name)}`);this.content.forEach(t=>t.check())}toJSON(){let e={type:this.type.name};for(let t in this.attrs){e.attrs=this.attrs;break}return this.content.size&&(e.content=this.content.toJSON()),this.marks.length&&(e.marks=this.marks.map(t=>t.toJSON())),e}static fromJSON(e,t){if(!t)throw new RangeError("Invalid input for Node.fromJSON");let n;if(t.marks){if(!Array.isArray(t.marks))throw new RangeError("Invalid mark data for Node.fromJSON");n=t.marks.map(e.markFromJSON)}if(t.type=="text"){if(typeof t.text!="string")throw new RangeError("Invalid text node in JSON");return e.text(t.text,n)}let i=Fe.fromJSON(e,t.content),r=e.nodeType(t.type).create(t.attrs,i,n);return r.type.checkAttrs(r.attrs),r}};yc.prototype.text=void 0;class ww extends yc{constructor(e,t,n,i){if(super(e,t,null,i),!n)throw new RangeError("Empty text nodes are not allowed");this.text=n}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):kL(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(e,t){return this.text.slice(e,t)}get nodeSize(){return this.text.length}mark(e){return e==this.marks?this:new ww(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new ww(this.type,this.attrs,e,this.marks)}cut(e=0,t=this.text.length){return e==0&&t==this.text.length?this:this.withText(this.text.slice(e,t))}eq(e){return this.sameMarkup(e)&&this.text==e.text}toJSON(){let e=super.toJSON();return e.text=this.text,e}}function kL(s,e){for(let t=s.length-1;t>=0;t--)e=s[t].type.name+"("+e+")";return e}class Tf{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,t){let n=new b9(e,t);if(n.next==null)return Tf.empty;let i=CL(n);n.next&&n.err("Unexpected trailing text");let r=A9(T9(i));return E9(r,n),r}matchType(e){for(let t=0;t<this.next.length;t++)if(this.next[t].type==e)return this.next[t].next;return null}matchFragment(e,t=0,n=e.childCount){let i=this;for(let r=t;i&&r<n;r++)i=i.matchType(e.child(r).type);return i}get inlineContent(){return this.next.length!=0&&this.next[0].type.isInline}get defaultType(){for(let e=0;e<this.next.length;e++){let{type:t}=this.next[e];if(!(t.isText||t.hasRequiredAttrs()))return t}return null}compatible(e){for(let t=0;t<this.next.length;t++)for(let n=0;n<e.next.length;n++)if(this.next[t].type==e.next[n].type)return!0;return!1}fillBefore(e,t=!1,n=0){let i=[this];function r(o,a){let c=o.matchFragment(e,n);if(c&&(!t||c.validEnd))return Fe.from(a.map(l=>l.createAndFill()));for(let l=0;l<o.next.length;l++){let{type:u,next:h}=o.next[l];if(!(u.isText||u.hasRequiredAttrs())&&i.indexOf(h)==-1){i.push(h);let d=r(h,a.concat(u));if(d)return d}}return null}return r(this,[])}findWrapping(e){for(let n=0;n<this.wrapCache.length;n+=2)if(this.wrapCache[n]==e)return this.wrapCache[n+1];let t=this.computeWrapping(e);return this.wrapCache.push(e,t),t}computeWrapping(e){let t=Object.create(null),n=[{match:this,type:null,via:null}];for(;n.length;){let i=n.shift(),r=i.match;if(r.matchType(e)){let o=[];for(let a=i;a.type;a=a.via)o.push(a.type);return o.reverse()}for(let o=0;o<r.next.length;o++){let{type:a,next:c}=r.next[o];!a.isLeaf&&!a.hasRequiredAttrs()&&!(a.name in t)&&(!i.type||c.validEnd)&&(n.push({match:a.contentMatch,type:a,via:i}),t[a.name]=!0)}}return null}get edgeCount(){return this.next.length}edge(e){if(e>=this.next.length)throw new RangeError(`There's no ${e}th edge in this content match`);return this.next[e]}toString(){let e=[];function t(n){e.push(n);for(let i=0;i<n.next.length;i++)e.indexOf(n.next[i].next)==-1&&t(n.next[i].next)}return t(this),e.map((n,i)=>{let r=i+(n.validEnd?"*":" ")+" ";for(let o=0;o<n.next.length;o++)r+=(o?", ":"")+n.next[o].type.name+"->"+e.indexOf(n.next[o].next);return r}).join(`
`)}}Tf.empty=new Tf(!0);class b9{constructor(e,t){this.string=e,this.nodeTypes=t,this.inline=null,this.pos=0,this.tokens=e.split(/\s*(?=\b|\W|$)/),this.tokens[this.tokens.length-1]==""&&this.tokens.pop(),this.tokens[0]==""&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(e){return this.next==e&&(this.pos++||!0)}err(e){throw new SyntaxError(e+" (in content expression '"+this.string+"')")}}function CL(s){let e=[];do e.push(_9(s));while(s.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function _9(s){let e=[];do e.push(S9(s));while(s.next&&s.next!=")"&&s.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function S9(s){let e=C9(s);for(;;)if(s.eat("+"))e={type:"plus",expr:e};else if(s.eat("*"))e={type:"star",expr:e};else if(s.eat("?"))e={type:"opt",expr:e};else if(s.eat("{"))e=w9(s,e);else break;return e}function rx(s){/\D/.test(s.next)&&s.err("Expected number, got '"+s.next+"'");let e=Number(s.next);return s.pos++,e}function w9(s,e){let t=rx(s),n=t;return s.eat(",")&&(s.next!="}"?n=rx(s):n=-1),s.eat("}")||s.err("Unclosed braced range"),{type:"range",min:t,max:n,expr:e}}function k9(s,e){let t=s.nodeTypes,n=t[e];if(n)return[n];let i=[];for(let r in t){let o=t[r];o.isInGroup(e)&&i.push(o)}return i.length==0&&s.err("No node type or group '"+e+"' found"),i}function C9(s){if(s.eat("(")){let e=CL(s);return s.eat(")")||s.err("Missing closing paren"),e}else if(/\W/.test(s.next))s.err("Unexpected token '"+s.next+"'");else{let e=k9(s,s.next).map(t=>(s.inline==null?s.inline=t.isInline:s.inline!=t.isInline&&s.err("Mixing inline and block content"),{type:"name",value:t}));return s.pos++,e.length==1?e[0]:{type:"choice",exprs:e}}}function T9(s){let e=[[]];return i(r(s,0),t()),e;function t(){return e.push([])-1}function n(o,a,c){let l={term:c,to:a};return e[o].push(l),l}function i(o,a){o.forEach(c=>c.to=a)}function r(o,a){if(o.type=="choice")return o.exprs.reduce((c,l)=>c.concat(r(l,a)),[]);if(o.type=="seq")for(let c=0;;c++){let l=r(o.exprs[c],a);if(c==o.exprs.length-1)return l;i(l,a=t())}else if(o.type=="star"){let c=t();return n(a,c),i(r(o.expr,c),c),[n(c)]}else if(o.type=="plus"){let c=t();return i(r(o.expr,a),c),i(r(o.expr,c),c),[n(c)]}else{if(o.type=="opt")return[n(a)].concat(r(o.expr,a));if(o.type=="range"){let c=a;for(let l=0;l<o.min;l++){let u=t();i(r(o.expr,c),u),c=u}if(o.max==-1)i(r(o.expr,c),c);else for(let l=o.min;l<o.max;l++){let u=t();n(c,u),i(r(o.expr,c),u),c=u}return[n(c)]}else{if(o.type=="name")return[n(a,void 0,o.value)];throw new Error("Unknown expr type")}}}}function TL(s,e){return e-s}function ox(s,e){let t=[];return n(e),t.sort(TL);function n(i){let r=s[i];if(r.length==1&&!r[0].term)return n(r[0].to);t.push(i);for(let o=0;o<r.length;o++){let{term:a,to:c}=r[o];!a&&t.indexOf(c)==-1&&n(c)}}}function A9(s){let e=Object.create(null);return t(ox(s,0));function t(n){let i=[];n.forEach(o=>{s[o].forEach(({term:a,to:c})=>{if(!a)return;let l;for(let u=0;u<i.length;u++)i[u][0]==a&&(l=i[u][1]);ox(s,c).forEach(u=>{l||i.push([a,l=[]]),l.indexOf(u)==-1&&l.push(u)})})});let r=e[n.join(",")]=new Tf(n.indexOf(s.length-1)>-1);for(let o=0;o<i.length;o++){let a=i[o][1].sort(TL);r.next.push({type:i[o][0],next:e[a.join(",")]||t(a)})}return r}}function E9(s,e){for(let t=0,n=[s];t<n.length;t++){let i=n[t],r=!i.validEnd,o=[];for(let a=0;a<i.next.length;a++){let{type:c,next:l}=i.next[a];o.push(c.name),r&&!(c.isText||c.hasRequiredAttrs())&&(r=!1),n.indexOf(l)==-1&&n.push(l)}r&&e.err("Only non-generatable nodes ("+o.join(", ")+") in a required position (see https://prosemirror.net/docs/guide/#generatable)")}}function AL(s){let e=Object.create(null);for(let t in s){let n=s[t];if(!n.hasDefault)return null;e[t]=n.default}return e}function EL(s,e){let t=Object.create(null);for(let n in s){let i=e&&e[n];if(i===void 0){let r=s[n];if(r.hasDefault)i=r.default;else throw new RangeError("No value supplied for attribute "+n)}t[n]=i}return t}function ML(s,e,t,n){for(let i in e)if(!(i in s))throw new RangeError(`Unsupported attribute ${i} for ${t} of type ${i}`);for(let i in s){let r=s[i];r.validate&&r.validate(e[i])}}function xL(s,e){let t=Object.create(null);if(e)for(let n in e)t[n]=new x9(s,n,e[n]);return t}let ax=class IL{constructor(e,t,n){this.name=e,this.schema=t,this.spec=n,this.markSet=null,this.groups=n.group?n.group.split(" "):[],this.attrs=xL(e,n.attrs),this.defaultAttrs=AL(this.attrs),this.contentMatch=null,this.inlineContent=null,this.isBlock=!(n.inline||e=="text"),this.isText=e=="text"}get isInline(){return!this.isBlock}get isTextblock(){return this.isBlock&&this.inlineContent}get isLeaf(){return this.contentMatch==Tf.empty}get isAtom(){return this.isLeaf||!!this.spec.atom}isInGroup(e){return this.groups.indexOf(e)>-1}get whitespace(){return this.spec.whitespace||(this.spec.code?"pre":"normal")}hasRequiredAttrs(){for(let e in this.attrs)if(this.attrs[e].isRequired)return!0;return!1}compatibleContent(e){return this==e||this.contentMatch.compatible(e.contentMatch)}computeAttrs(e){return!e&&this.defaultAttrs?this.defaultAttrs:EL(this.attrs,e)}create(e=null,t,n){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new yc(this,this.computeAttrs(e),Fe.from(t),_s.setFrom(n))}createChecked(e=null,t,n){return t=Fe.from(t),this.checkContent(t),new yc(this,this.computeAttrs(e),t,_s.setFrom(n))}createAndFill(e=null,t,n){if(e=this.computeAttrs(e),t=Fe.from(t),t.size){let o=this.contentMatch.fillBefore(t);if(!o)return null;t=o.append(t)}let i=this.contentMatch.matchFragment(t),r=i&&i.fillBefore(Fe.empty,!0);return r?new yc(this,e,t.append(r),_s.setFrom(n)):null}validContent(e){let t=this.contentMatch.matchFragment(e);if(!t||!t.validEnd)return!1;for(let n=0;n<e.childCount;n++)if(!this.allowsMarks(e.child(n).marks))return!1;return!0}checkContent(e){if(!this.validContent(e))throw new RangeError(`Invalid content for node ${this.name}: ${e.toString().slice(0,50)}`)}checkAttrs(e){ML(this.attrs,e,"node",this.name)}allowsMarkType(e){return this.markSet==null||this.markSet.indexOf(e)>-1}allowsMarks(e){if(this.markSet==null)return!0;for(let t=0;t<e.length;t++)if(!this.allowsMarkType(e[t].type))return!1;return!0}allowedMarks(e){if(this.markSet==null)return e;let t;for(let n=0;n<e.length;n++)this.allowsMarkType(e[n].type)?t&&t.push(e[n]):t||(t=e.slice(0,n));return t?t.length?t:_s.none:e}static compile(e,t){let n=Object.create(null);e.forEach((r,o)=>n[r]=new IL(r,t,o));let i=t.spec.topNode||"doc";if(!n[i])throw new RangeError("Schema is missing its top node type ('"+i+"')");if(!n.text)throw new RangeError("Every schema needs a 'text' type");for(let r in n.text.attrs)throw new RangeError("The text node type should not have attributes");return n}};function M9(s,e,t){let n=t.split("|");return i=>{let r=i===null?"null":typeof i;if(n.indexOf(r)<0)throw new RangeError(`Expected value of type ${n} for attribute ${e} on type ${s}, got ${r}`)}}class x9{constructor(e,t,n){this.hasDefault=Object.prototype.hasOwnProperty.call(n,"default"),this.default=n.default,this.validate=typeof n.validate=="string"?M9(e,t,n.validate):n.validate}get isRequired(){return!this.hasDefault}}class X0{constructor(e,t,n,i){this.name=e,this.rank=t,this.schema=n,this.spec=i,this.attrs=xL(e,i.attrs),this.excluded=null;let r=AL(this.attrs);this.instance=r?new _s(this,r):null}create(e=null){return!e&&this.instance?this.instance:new _s(this,EL(this.attrs,e))}static compile(e,t){let n=Object.create(null),i=0;return e.forEach((r,o)=>n[r]=new X0(r,i++,t,o)),n}removeFromSet(e){for(var t=0;t<e.length;t++)e[t].type==this&&(e=e.slice(0,t).concat(e.slice(t+1)),t--);return e}isInSet(e){for(let t=0;t<e.length;t++)if(e[t].type==this)return e[t]}checkAttrs(e){ML(this.attrs,e,"mark",this.name)}excludes(e){return this.excluded.indexOf(e)>-1}}class RL{constructor(e){this.linebreakReplacement=null,this.cached=Object.create(null);let t=this.spec={};for(let i in e)t[i]=e[i];t.nodes=ui.from(e.nodes),t.marks=ui.from(e.marks||{}),this.nodes=ax.compile(this.spec.nodes,this),this.marks=X0.compile(this.spec.marks,this);let n=Object.create(null);for(let i in this.nodes){if(i in this.marks)throw new RangeError(i+" can not be both a node and a mark");let r=this.nodes[i],o=r.spec.content||"",a=r.spec.marks;if(r.contentMatch=n[o]||(n[o]=Tf.parse(o,this.nodes)),r.inlineContent=r.contentMatch.inlineContent,r.spec.linebreakReplacement){if(this.linebreakReplacement)throw new RangeError("Multiple linebreak nodes defined");if(!r.isInline||!r.isLeaf)throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");this.linebreakReplacement=r}r.markSet=a=="_"?null:a?lx(this,a.split(" ")):a==""||!r.inlineContent?[]:null}for(let i in this.marks){let r=this.marks[i],o=r.spec.excludes;r.excluded=o==null?[r]:o==""?[]:lx(this,o.split(" "))}this.nodeFromJSON=i=>yc.fromJSON(this,i),this.markFromJSON=i=>_s.fromJSON(this,i),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(e,t=null,n,i){if(typeof e=="string")e=this.nodeType(e);else if(e instanceof ax){if(e.schema!=this)throw new RangeError("Node type from different schema used ("+e.name+")")}else throw new RangeError("Invalid node type: "+e);return e.createChecked(t,n,i)}text(e,t){let n=this.nodes.text;return new ww(n,n.defaultAttrs,e,_s.setFrom(t))}mark(e,t){return typeof e=="string"&&(e=this.marks[e]),e.create(t)}nodeType(e){let t=this.nodes[e];if(!t)throw new RangeError("Unknown node type: "+e);return t}}function lx(s,e){let t=[];for(let n=0;n<e.length;n++){let i=e[n],r=s.marks[i],o=r;if(r)t.push(r);else for(let a in s.marks){let c=s.marks[a];(i=="_"||c.spec.group&&c.spec.group.split(" ").indexOf(i)>-1)&&t.push(o=c)}if(!o)throw new SyntaxError("Unknown mark type: '"+e[n]+"'")}return t}function I9(s){return s.tag!=null}function R9(s){return s.style!=null}let Av=class R1{constructor(e,t){this.schema=e,this.rules=t,this.tags=[],this.styles=[];let n=this.matchedStyles=[];t.forEach(i=>{if(I9(i))this.tags.push(i);else if(R9(i)){let r=/[^=]*/.exec(i.style)[0];n.indexOf(r)<0&&n.push(r),this.styles.push(i)}}),this.normalizeLists=!this.tags.some(i=>{if(!/^(ul|ol)\b/.test(i.tag)||!i.node)return!1;let r=e.nodes[i.node];return r.contentMatch.matchType(r)})}parse(e,t={}){let n=new ux(this,t,!1);return n.addAll(e,_s.none,t.from,t.to),n.finish()}parseSlice(e,t={}){let n=new ux(this,t,!0);return n.addAll(e,_s.none,t.from,t.to),nt.maxOpen(n.finish())}matchTag(e,t,n){for(let i=n?this.tags.indexOf(n)+1:0;i<this.tags.length;i++){let r=this.tags[i];if(O9(e,r.tag)&&(r.namespace===void 0||e.namespaceURI==r.namespace)&&(!r.context||t.matchesContext(r.context))){if(r.getAttrs){let o=r.getAttrs(e);if(o===!1)continue;r.attrs=o||void 0}return r}}}matchStyle(e,t,n,i){for(let r=i?this.styles.indexOf(i)+1:0;r<this.styles.length;r++){let o=this.styles[r],a=o.style;if(!(a.indexOf(e)!=0||o.context&&!n.matchesContext(o.context)||a.length>e.length&&(a.charCodeAt(e.length)!=61||a.slice(e.length+1)!=t))){if(o.getAttrs){let c=o.getAttrs(t);if(c===!1)continue;o.attrs=c||void 0}return o}}}static schemaRules(e){let t=[];function n(i){let r=i.priority==null?50:i.priority,o=0;for(;o<t.length;o++){let a=t[o];if((a.priority==null?50:a.priority)<r)break}t.splice(o,0,i)}for(let i in e.marks){let r=e.marks[i].spec.parseDOM;r&&r.forEach(o=>{n(o=hx(o)),o.mark||o.ignore||o.clearMark||(o.mark=i)})}for(let i in e.nodes){let r=e.nodes[i].spec.parseDOM;r&&r.forEach(o=>{n(o=hx(o)),o.node||o.ignore||o.mark||(o.node=i)})}return t}static fromSchema(e){return e.cached.domParser||(e.cached.domParser=new R1(e,R1.schemaRules(e)))}};const LL={address:!0,article:!0,aside:!0,blockquote:!0,canvas:!0,dd:!0,div:!0,dl:!0,fieldset:!0,figcaption:!0,figure:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,li:!0,noscript:!0,ol:!0,output:!0,p:!0,pre:!0,section:!0,table:!0,tfoot:!0,ul:!0},L9={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},PL={ol:!0,ul:!0},Kv=1,L1=2,Ev=4;function cx(s,e,t){return e!=null?(e?Kv:0)|(e==="full"?L1:0):s&&s.whitespace=="pre"?Kv|L1:t&~Ev}class E_{constructor(e,t,n,i,r,o){this.type=e,this.attrs=t,this.marks=n,this.solid=i,this.options=o,this.content=[],this.activeMarks=_s.none,this.match=r||(o&Ev?null:e.contentMatch)}findWrapping(e){if(!this.match){if(!this.type)return[];let t=this.type.contentMatch.fillBefore(Fe.from(e));if(t)this.match=this.type.contentMatch.matchFragment(t);else{let n=this.type.contentMatch,i;return(i=n.findWrapping(e.type))?(this.match=n,i):null}}return this.match.findWrapping(e.type)}finish(e){if(!(this.options&Kv)){let n=this.content[this.content.length-1],i;if(n&&n.isText&&(i=/[ \t\r\n\u000c]+$/.exec(n.text))){let r=n;n.text.length==i[0].length?this.content.pop():this.content[this.content.length-1]=r.withText(r.text.slice(0,r.text.length-i[0].length))}}let t=Fe.from(this.content);return!e&&this.match&&(t=t.append(this.match.fillBefore(Fe.empty,!0))),this.type?this.type.create(this.attrs,t,this.marks):t}inlineContext(e){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:e.parentNode&&!LL.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}}class ux{constructor(e,t,n){this.parser=e,this.options=t,this.isOpen=n,this.open=0,this.localPreserveWS=!1;let i=t.topNode,r,o=cx(null,t.preserveWhitespace,0)|(n?Ev:0);i?r=new E_(i.type,i.attrs,_s.none,!0,t.topMatch||i.type.contentMatch,o):n?r=new E_(null,null,_s.none,!0,null,o):r=new E_(e.schema.topNodeType,null,_s.none,!0,null,o),this.nodes=[r],this.find=t.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(e,t){e.nodeType==3?this.addTextNode(e,t):e.nodeType==1&&this.addElement(e,t)}addTextNode(e,t){let n=e.nodeValue,i=this.top,r=i.options&L1?"full":this.localPreserveWS||(i.options&Kv)>0,{schema:o}=this.parser;if(r==="full"||i.inlineContext(e)||/[^ \t\r\n\u000c]/.test(n)){if(r)if(r==="full")n=n.replace(/\r\n?/g,`
`);else if(o.linebreakReplacement&&/[\r\n]/.test(n)&&this.top.findWrapping(o.linebreakReplacement.create())){let a=n.split(/\r?\n|\r/);for(let c=0;c<a.length;c++)c&&this.insertNode(o.linebreakReplacement.create(),t,!0),a[c]&&this.insertNode(o.text(a[c]),t,!/\S/.test(a[c]));n=""}else n=n.replace(/\r?\n|\r/g," ");else if(n=n.replace(/[ \t\r\n\u000c]+/g," "),/^[ \t\r\n\u000c]/.test(n)&&this.open==this.nodes.length-1){let a=i.content[i.content.length-1],c=e.previousSibling;(!a||c&&c.nodeName=="BR"||a.isText&&/[ \t\r\n\u000c]$/.test(a.text))&&(n=n.slice(1))}n&&this.insertNode(o.text(n),t,!/\S/.test(n)),this.findInText(e)}else this.findInside(e)}addElement(e,t,n){let i=this.localPreserveWS,r=this.top;(e.tagName=="PRE"||/pre/.test(e.style&&e.style.whiteSpace))&&(this.localPreserveWS=!0);let o=e.nodeName.toLowerCase(),a;PL.hasOwnProperty(o)&&this.parser.normalizeLists&&P9(e);let c=this.options.ruleFromNode&&this.options.ruleFromNode(e)||(a=this.parser.matchTag(e,this,n));e:if(c?c.ignore:L9.hasOwnProperty(o))this.findInside(e),this.ignoreFallback(e,t);else if(!c||c.skip||c.closeParent){c&&c.closeParent?this.open=Math.max(0,this.open-1):c&&c.skip.nodeType&&(e=c.skip);let l,u=this.needsBlock;if(LL.hasOwnProperty(o))r.content.length&&r.content[0].isInline&&this.open&&(this.open--,r=this.top),l=!0,r.type||(this.needsBlock=!0);else if(!e.firstChild){this.leafFallback(e,t);break e}let h=c&&c.skip?t:this.readStyles(e,t);h&&this.addAll(e,h),l&&this.sync(r),this.needsBlock=u}else{let l=this.readStyles(e,t);l&&this.addElementByRule(e,c,l,c.consuming===!1?a:void 0)}this.localPreserveWS=i}leafFallback(e,t){e.nodeName=="BR"&&this.top.type&&this.top.type.inlineContent&&this.addTextNode(e.ownerDocument.createTextNode(`
`),t)}ignoreFallback(e,t){e.nodeName=="BR"&&(!this.top.type||!this.top.type.inlineContent)&&this.findPlace(this.parser.schema.text("-"),t,!0)}readStyles(e,t){let n=e.style;if(n&&n.length)for(let i=0;i<this.parser.matchedStyles.length;i++){let r=this.parser.matchedStyles[i],o=n.getPropertyValue(r);if(o)for(let a=void 0;;){let c=this.parser.matchStyle(r,o,this,a);if(!c)break;if(c.ignore)return null;if(c.clearMark?t=t.filter(l=>!c.clearMark(l)):t=t.concat(this.parser.schema.marks[c.mark].create(c.attrs)),c.consuming===!1)a=c;else break}}return t}addElementByRule(e,t,n,i){let r,o;if(t.node)if(o=this.parser.schema.nodes[t.node],o.isLeaf)this.insertNode(o.create(t.attrs),n,e.nodeName=="BR")||this.leafFallback(e,n);else{let c=this.enter(o,t.attrs||null,n,t.preserveWhitespace);c&&(r=!0,n=c)}else{let c=this.parser.schema.marks[t.mark];n=n.concat(c.create(t.attrs))}let a=this.top;if(o&&o.isLeaf)this.findInside(e);else if(i)this.addElement(e,n,i);else if(t.getContent)this.findInside(e),t.getContent(e,this.parser.schema).forEach(c=>this.insertNode(c,n,!1));else{let c=e;typeof t.contentElement=="string"?c=e.querySelector(t.contentElement):typeof t.contentElement=="function"?c=t.contentElement(e):t.contentElement&&(c=t.contentElement),this.findAround(e,c,!0),this.addAll(c,n),this.findAround(e,c,!1)}r&&this.sync(a)&&this.open--}addAll(e,t,n,i){let r=n||0;for(let o=n?e.childNodes[n]:e.firstChild,a=i==null?null:e.childNodes[i];o!=a;o=o.nextSibling,++r)this.findAtPoint(e,r),this.addDOM(o,t);this.findAtPoint(e,r)}findPlace(e,t,n){let i,r;for(let o=this.open,a=0;o>=0;o--){let c=this.nodes[o],l=c.findWrapping(e);if(l&&(!i||i.length>l.length+a)&&(i=l,r=c,!l.length))break;if(c.solid){if(n)break;a+=2}}if(!i)return null;this.sync(r);for(let o=0;o<i.length;o++)t=this.enterInner(i[o],null,t,!1);return t}insertNode(e,t,n){if(e.isInline&&this.needsBlock&&!this.top.type){let r=this.textblockFromContext();r&&(t=this.enterInner(r,null,t))}let i=this.findPlace(e,t,n);if(i){this.closeExtra();let r=this.top;r.match&&(r.match=r.match.matchType(e.type));let o=_s.none;for(let a of i.concat(e.marks))(r.type?r.type.allowsMarkType(a.type):dx(a.type,e.type))&&(o=a.addToSet(o));return r.content.push(e.mark(o)),!0}return!1}enter(e,t,n,i){let r=this.findPlace(e.create(t),n,!1);return r&&(r=this.enterInner(e,t,n,!0,i)),r}enterInner(e,t,n,i=!1,r){this.closeExtra();let o=this.top;o.match=o.match&&o.match.matchType(e);let a=cx(e,r,o.options);o.options&Ev&&o.content.length==0&&(a|=Ev);let c=_s.none;return n=n.filter(l=>(o.type?o.type.allowsMarkType(l.type):dx(l.type,e))?(c=l.addToSet(c),!1):!0),this.nodes.push(new E_(e,t,c,i,null,a)),this.open++,n}closeExtra(e=!1){let t=this.nodes.length-1;if(t>this.open){for(;t>this.open;t--)this.nodes[t-1].content.push(this.nodes[t].finish(e));this.nodes.length=this.open+1}}finish(){return this.open=0,this.closeExtra(this.isOpen),this.nodes[0].finish(!!(this.isOpen||this.options.topOpen))}sync(e){for(let t=this.open;t>=0;t--){if(this.nodes[t]==e)return this.open=t,!0;this.localPreserveWS&&(this.nodes[t].options|=Kv)}return!1}get currentPos(){this.closeExtra();let e=0;for(let t=this.open;t>=0;t--){let n=this.nodes[t].content;for(let i=n.length-1;i>=0;i--)e+=n[i].nodeSize;t&&e++}return e}findAtPoint(e,t){if(this.find)for(let n=0;n<this.find.length;n++)this.find[n].node==e&&this.find[n].offset==t&&(this.find[n].pos=this.currentPos)}findInside(e){if(this.find)for(let t=0;t<this.find.length;t++)this.find[t].pos==null&&e.nodeType==1&&e.contains(this.find[t].node)&&(this.find[t].pos=this.currentPos)}findAround(e,t,n){if(e!=t&&this.find)for(let i=0;i<this.find.length;i++)this.find[i].pos==null&&e.nodeType==1&&e.contains(this.find[i].node)&&t.compareDocumentPosition(this.find[i].node)&(n?2:4)&&(this.find[i].pos=this.currentPos)}findInText(e){if(this.find)for(let t=0;t<this.find.length;t++)this.find[t].node==e&&(this.find[t].pos=this.currentPos-(e.nodeValue.length-this.find[t].offset))}matchesContext(e){if(e.indexOf("|")>-1)return e.split(/\s*\|\s*/).some(this.matchesContext,this);let t=e.split("/"),n=this.options.context,i=!this.isOpen&&(!n||n.parent.type==this.nodes[0].type),r=-(n?n.depth+1:0)+(i?0:1),o=(a,c)=>{for(;a>=0;a--){let l=t[a];if(l==""){if(a==t.length-1||a==0)continue;for(;c>=r;c--)if(o(a-1,c))return!0;return!1}else{let u=c>0||c==0&&i?this.nodes[c].type:n&&c>=r?n.node(c-r).type:null;if(!u||u.name!=l&&!u.isInGroup(l))return!1;c--}}return!0};return o(t.length-1,this.open)}textblockFromContext(){let e=this.options.context;if(e)for(let t=e.depth;t>=0;t--){let n=e.node(t).contentMatchAt(e.indexAfter(t)).defaultType;if(n&&n.isTextblock&&n.defaultAttrs)return n}for(let t in this.parser.schema.nodes){let n=this.parser.schema.nodes[t];if(n.isTextblock&&n.defaultAttrs)return n}}}function P9(s){for(let e=s.firstChild,t=null;e;e=e.nextSibling){let n=e.nodeType==1?e.nodeName.toLowerCase():null;n&&PL.hasOwnProperty(n)&&t?(t.appendChild(e),e=t):n=="li"?t=e:n&&(t=null)}}function O9(s,e){return(s.matches||s.msMatchesSelector||s.webkitMatchesSelector||s.mozMatchesSelector).call(s,e)}function hx(s){let e={};for(let t in s)e[t]=s[t];return e}function dx(s,e){let t=e.schema.nodes;for(let n in t){let i=t[n];if(!i.allowsMarkType(s))continue;let r=[],o=a=>{r.push(a);for(let c=0;c<a.edgeCount;c++){let{type:l,next:u}=a.edge(c);if(l==e||r.indexOf(u)<0&&o(u))return!0}};if(o(i.contentMatch))return!0}}class Of{constructor(e,t){this.nodes=e,this.marks=t}serializeFragment(e,t={},n){n||(n=M_(t).createDocumentFragment());let i=n,r=[];return e.forEach(o=>{if(r.length||o.marks.length){let a=0,c=0;for(;a<r.length&&c<o.marks.length;){let l=o.marks[c];if(!this.marks[l.type.name]){c++;continue}if(!l.eq(r[a][0])||l.type.spec.spanning===!1)break;a++,c++}for(;a<r.length;)i=r.pop()[1];for(;c<o.marks.length;){let l=o.marks[c++],u=this.serializeMark(l,o.isInline,t);u&&(r.push([l,i]),i.appendChild(u.dom),i=u.contentDOM||u.dom)}}i.appendChild(this.serializeNodeInner(o,t))}),n}serializeNodeInner(e,t){if(e.isText)return M_(t).createTextNode(e.text);let{dom:n,contentDOM:i}=uS(M_(t),this.nodes[e.type.name](e),null,e.attrs);if(i){if(e.isLeaf)throw new RangeError("Content hole not allowed in a leaf node spec");this.serializeFragment(e.content,t,i)}return n}serializeNode(e,t={}){let n=this.serializeNodeInner(e,t);for(let i=e.marks.length-1;i>=0;i--){let r=this.serializeMark(e.marks[i],e.isInline,t);r&&((r.contentDOM||r.dom).appendChild(n),n=r.dom)}return n}serializeMark(e,t,n={}){let i=this.marks[e.type.name];return i&&uS(M_(n),i(e,t),null,e.attrs)}static renderSpec(e,t,n=null,i){return typeof t=="string"?{dom:e.createTextNode(t)}:uS(e,t,n,i)}static fromSchema(e){return e.cached.domSerializer||(e.cached.domSerializer=new Of(this.nodesFromSchema(e),this.marksFromSchema(e)))}static nodesFromSchema(e){let t=fx(e.nodes);return t.text||(t.text=n=>n.text),t}static marksFromSchema(e){return fx(e.marks)}}function fx(s){let e={};for(let t in s){let n=s[t].spec.toDOM;n&&(e[t]=n)}return e}function M_(s){return s.document||window.document}const px=new WeakMap;function D9(s){let e=px.get(s);return e===void 0&&px.set(s,e=N9(s)),e}function N9(s){let e=null;function t(n){if(n&&typeof n=="object")if(Array.isArray(n))if(typeof n[0]=="string")e||(e=[]),e.push(n);else for(let i=0;i<n.length;i++)t(n[i]);else for(let i in n)t(n[i])}return t(s),e}function uS(s,e,t,n){if(e.nodeType==1)return{dom:e};if(e.dom&&e.dom.nodeType==1)return e;let i=e[0],r;if(typeof i!="string")throw new RangeError("Invalid array passed to renderSpec");if(n&&(r=D9(n))&&r.indexOf(e)>-1)throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.");let o=i.indexOf(" ");o>0&&(t=i.slice(0,o),i=i.slice(o+1));let a,c=t?s.createElementNS(t,i):s.createElement(i),l=e[1],u=1;if(l&&typeof l=="object"&&l.nodeType==null&&!Array.isArray(l)){u=2;for(let h in l)if(l[h]!=null){let d=h.indexOf(" ");d>0?c.setAttributeNS(h.slice(0,d),h.slice(d+1),l[h]):h=="style"&&c.style?c.style.cssText=l[h]:c.setAttribute(h,l[h])}}for(let h=u;h<e.length;h++){let d=e[h];if(d===0){if(h<e.length-1||h>u)throw new RangeError("Content hole must be the only child of its parent node");return{dom:c,contentDOM:c}}else if(typeof d=="string")c.appendChild(s.createTextNode(d));else{let{dom:p,contentDOM:m}=uS(s,d,t,n);if(c.appendChild(p),m){if(a)throw new RangeError("Multiple content holes");a=m}}}return{dom:c,contentDOM:a}}const OL=65535,DL=Math.pow(2,16);function B9(s,e){return s+e*DL}function gx(s){return s&OL}function F9(s){return(s-(s&OL))/DL}const NL=1,BL=2,hS=4,FL=8;let P1=class{constructor(e,t,n){this.pos=e,this.delInfo=t,this.recover=n}get deleted(){return(this.delInfo&FL)>0}get deletedBefore(){return(this.delInfo&(NL|hS))>0}get deletedAfter(){return(this.delInfo&(BL|hS))>0}get deletedAcross(){return(this.delInfo&hS)>0}},Af=class np{constructor(e,t=!1){if(this.ranges=e,this.inverted=t,!e.length&&np.empty)return np.empty}recover(e){let t=0,n=gx(e);if(!this.inverted)for(let i=0;i<n;i++)t+=this.ranges[i*3+2]-this.ranges[i*3+1];return this.ranges[n*3]+t+F9(e)}mapResult(e,t=1){return this._map(e,t,!1)}map(e,t=1){return this._map(e,t,!0)}_map(e,t,n){let i=0,r=this.inverted?2:1,o=this.inverted?1:2;for(let a=0;a<this.ranges.length;a+=3){let c=this.ranges[a]-(this.inverted?i:0);if(c>e)break;let l=this.ranges[a+r],u=this.ranges[a+o],h=c+l;if(e<=h){let d=l?e==c?-1:e==h?1:t:t,p=c+i+(d<0?0:u);if(n)return p;let m=e==(t<0?c:h)?null:B9(a/3,e-c),v=e==c?BL:e==h?NL:hS;return(t<0?e!=c:e!=h)&&(v|=FL),new P1(p,v,m)}i+=u-l}return n?e+i:new P1(e+i,0,null)}touches(e,t){let n=0,i=gx(t),r=this.inverted?2:1,o=this.inverted?1:2;for(let a=0;a<this.ranges.length;a+=3){let c=this.ranges[a]-(this.inverted?n:0);if(c>e)break;let l=this.ranges[a+r],u=c+l;if(e<=u&&a==i*3)return!0;n+=this.ranges[a+o]-l}return!1}forEach(e){let t=this.inverted?2:1,n=this.inverted?1:2;for(let i=0,r=0;i<this.ranges.length;i+=3){let o=this.ranges[i],a=o-(this.inverted?r:0),c=o+(this.inverted?0:r),l=this.ranges[i+t],u=this.ranges[i+n];e(a,a+l,c,c+u),r+=u-l}}invert(){return new np(this.ranges,!this.inverted)}toString(){return(this.inverted?"-":"")+JSON.stringify(this.ranges)}static offset(e){return e==0?np.empty:new np(e<0?[0,-e,0]:[0,0,e])}};Af.empty=new Af([]);class Qv{constructor(e,t,n=0,i=e?e.length:0){this.mirror=t,this.from=n,this.to=i,this._maps=e||[],this.ownData=!(e||t)}get maps(){return this._maps}slice(e=0,t=this.maps.length){return new Qv(this._maps,this.mirror,e,t)}appendMap(e,t){this.ownData||(this._maps=this._maps.slice(),this.mirror=this.mirror&&this.mirror.slice(),this.ownData=!0),this.to=this._maps.push(e),t!=null&&this.setMirror(this._maps.length-1,t)}appendMapping(e){for(let t=0,n=this._maps.length;t<e._maps.length;t++){let i=e.getMirror(t);this.appendMap(e._maps[t],i!=null&&i<t?n+i:void 0)}}getMirror(e){if(this.mirror){for(let t=0;t<this.mirror.length;t++)if(this.mirror[t]==e)return this.mirror[t+(t%2?-1:1)]}}setMirror(e,t){this.mirror||(this.mirror=[]),this.mirror.push(e,t)}appendMappingInverted(e){for(let t=e.maps.length-1,n=this._maps.length+e._maps.length;t>=0;t--){let i=e.getMirror(t);this.appendMap(e._maps[t].invert(),i!=null&&i>t?n-i-1:void 0)}}invert(){let e=new Qv;return e.appendMappingInverted(this),e}map(e,t=1){if(this.mirror)return this._map(e,t,!0);for(let n=this.from;n<this.to;n++)e=this._maps[n].map(e,t);return e}mapResult(e,t=1){return this._map(e,t,!1)}_map(e,t,n){let i=0;for(let r=this.from;r<this.to;r++){let o=this._maps[r],a=o.mapResult(e,t);if(a.recover!=null){let c=this.getMirror(r);if(c!=null&&c>r&&c<this.to){r=c,e=this._maps[c].recover(a.recover);continue}}i|=a.delInfo,e=a.pos}return n?e:new P1(e,i,null)}}const aC=Object.create(null);let Pi=class{getMap(){return Af.empty}merge(e){return null}static fromJSON(e,t){if(!t||!t.stepType)throw new RangeError("Invalid input for Step.fromJSON");let n=aC[t.stepType];if(!n)throw new RangeError(`No step type ${t.stepType} defined`);return n.fromJSON(e,t)}static jsonID(e,t){if(e in aC)throw new RangeError("Duplicate use of step JSON ID "+e);return aC[e]=t,t.prototype.jsonID=e,t}},Xi=class Rm{constructor(e,t){this.doc=e,this.failed=t}static ok(e){return new Rm(e,null)}static fail(e){return new Rm(null,e)}static fromReplace(e,t,n,i){try{return Rm.ok(e.replace(t,n,i))}catch(r){if(r instanceof bw)return Rm.fail(r.message);throw r}}};function vE(s,e,t){let n=[];for(let i=0;i<s.childCount;i++){let r=s.child(i);r.content.size&&(r=r.copy(vE(r.content,e,r))),r.isInline&&(r=e(r,t,i)),n.push(r)}return Fe.fromArray(n)}let yE=class Lm extends Pi{constructor(e,t,n){super(),this.from=e,this.to=t,this.mark=n}apply(e){let t=e.slice(this.from,this.to),n=e.resolve(this.from),i=n.node(n.sharedDepth(this.to)),r=new nt(vE(t.content,(o,a)=>!o.isAtom||!a.type.allowsMarkType(this.mark.type)?o:o.mark(this.mark.addToSet(o.marks)),i),t.openStart,t.openEnd);return Xi.fromReplace(e,this.from,this.to,r)}invert(){return new dm(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),n=e.mapResult(this.to,-1);return t.deleted&&n.deleted||t.pos>=n.pos?null:new Lm(t.pos,n.pos,this.mark)}merge(e){return e instanceof Lm&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new Lm(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new Lm(t.from,t.to,e.markFromJSON(t.mark))}};Pi.jsonID("addMark",yE);let dm=class Pm extends Pi{constructor(e,t,n){super(),this.from=e,this.to=t,this.mark=n}apply(e){let t=e.slice(this.from,this.to),n=new nt(vE(t.content,i=>i.mark(this.mark.removeFromSet(i.marks)),e),t.openStart,t.openEnd);return Xi.fromReplace(e,this.from,this.to,n)}invert(){return new yE(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),n=e.mapResult(this.to,-1);return t.deleted&&n.deleted||t.pos>=n.pos?null:new Pm(t.pos,n.pos,this.mark)}merge(e){return e instanceof Pm&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new Pm(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new Pm(t.from,t.to,e.markFromJSON(t.mark))}};Pi.jsonID("removeMark",dm);let bE=class Om extends Pi{constructor(e,t){super(),this.pos=e,this.mark=t}apply(e){let t=e.nodeAt(this.pos);if(!t)return Xi.fail("No node at mark step's position");let n=t.type.create(t.attrs,null,this.mark.addToSet(t.marks));return Xi.fromReplace(e,this.pos,this.pos+1,new nt(Fe.from(n),0,t.isLeaf?0:1))}invert(e){let t=e.nodeAt(this.pos);if(t){let n=this.mark.addToSet(t.marks);if(n.length==t.marks.length){for(let i=0;i<t.marks.length;i++)if(!t.marks[i].isInSet(n))return new Om(this.pos,t.marks[i]);return new Om(this.pos,this.mark)}}return new kw(this.pos,this.mark)}map(e){let t=e.mapResult(this.pos,1);return t.deletedAfter?null:new Om(t.pos,this.mark)}toJSON(){return{stepType:"addNodeMark",pos:this.pos,mark:this.mark.toJSON()}}static fromJSON(e,t){if(typeof t.pos!="number")throw new RangeError("Invalid input for AddNodeMarkStep.fromJSON");return new Om(t.pos,e.markFromJSON(t.mark))}};Pi.jsonID("addNodeMark",bE);let kw=class O1 extends Pi{constructor(e,t){super(),this.pos=e,this.mark=t}apply(e){let t=e.nodeAt(this.pos);if(!t)return Xi.fail("No node at mark step's position");let n=t.type.create(t.attrs,null,this.mark.removeFromSet(t.marks));return Xi.fromReplace(e,this.pos,this.pos+1,new nt(Fe.from(n),0,t.isLeaf?0:1))}invert(e){let t=e.nodeAt(this.pos);return!t||!this.mark.isInSet(t.marks)?this:new bE(this.pos,this.mark)}map(e){let t=e.mapResult(this.pos,1);return t.deletedAfter?null:new O1(t.pos,this.mark)}toJSON(){return{stepType:"removeNodeMark",pos:this.pos,mark:this.mark.toJSON()}}static fromJSON(e,t){if(typeof t.pos!="number")throw new RangeError("Invalid input for RemoveNodeMarkStep.fromJSON");return new O1(t.pos,e.markFromJSON(t.mark))}};Pi.jsonID("removeNodeMark",kw);let Fo=class jc extends Pi{constructor(e,t,n,i=!1){super(),this.from=e,this.to=t,this.slice=n,this.structure=i}apply(e){return this.structure&&D1(e,this.from,this.to)?Xi.fail("Structure replace would overwrite content"):Xi.fromReplace(e,this.from,this.to,this.slice)}getMap(){return new Af([this.from,this.to-this.from,this.slice.size])}invert(e){return new jc(this.from,this.from+this.slice.size,e.slice(this.from,this.to))}map(e){let t=e.mapResult(this.to,-1),n=this.from==this.to&&jc.MAP_BIAS<0?t:e.mapResult(this.from,1);return n.deletedAcross&&t.deletedAcross?null:new jc(n.pos,Math.max(n.pos,t.pos),this.slice,this.structure)}merge(e){if(!(e instanceof jc)||e.structure||this.structure)return null;if(this.from+this.slice.size==e.from&&!this.slice.openEnd&&!e.slice.openStart){let t=this.slice.size+e.slice.size==0?nt.empty:new nt(this.slice.content.append(e.slice.content),this.slice.openStart,e.slice.openEnd);return new jc(this.from,this.to+(e.to-e.from),t,this.structure)}else if(e.to==this.from&&!this.slice.openStart&&!e.slice.openEnd){let t=this.slice.size+e.slice.size==0?nt.empty:new nt(e.slice.content.append(this.slice.content),e.slice.openStart,this.slice.openEnd);return new jc(e.from,this.to,t,this.structure)}else return null}toJSON(){let e={stepType:"replace",from:this.from,to:this.to};return this.slice.size&&(e.slice=this.slice.toJSON()),this.structure&&(e.structure=!0),e}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for ReplaceStep.fromJSON");return new jc(t.from,t.to,nt.fromJSON(e,t.slice),!!t.structure)}};Fo.MAP_BIAS=1;Pi.jsonID("replace",Fo);let _r=class dS extends Pi{constructor(e,t,n,i,r,o,a=!1){super(),this.from=e,this.to=t,this.gapFrom=n,this.gapTo=i,this.slice=r,this.insert=o,this.structure=a}apply(e){if(this.structure&&(D1(e,this.from,this.gapFrom)||D1(e,this.gapTo,this.to)))return Xi.fail("Structure gap-replace would overwrite content");let t=e.slice(this.gapFrom,this.gapTo);if(t.openStart||t.openEnd)return Xi.fail("Gap is not a flat range");let n=this.slice.insertAt(this.insert,t.content);return n?Xi.fromReplace(e,this.from,this.to,n):Xi.fail("Content does not fit in gap")}getMap(){return new Af([this.from,this.gapFrom-this.from,this.insert,this.gapTo,this.to-this.gapTo,this.slice.size-this.insert])}invert(e){let t=this.gapTo-this.gapFrom;return new dS(this.from,this.from+this.slice.size+t,this.from+this.insert,this.from+this.insert+t,e.slice(this.from,this.to).removeBetween(this.gapFrom-this.from,this.gapTo-this.from),this.gapFrom-this.from,this.structure)}map(e){let t=e.mapResult(this.from,1),n=e.mapResult(this.to,-1),i=this.from==this.gapFrom?t.pos:e.map(this.gapFrom,-1),r=this.to==this.gapTo?n.pos:e.map(this.gapTo,1);return t.deletedAcross&&n.deletedAcross||i<t.pos||r>n.pos?null:new dS(t.pos,n.pos,i,r,this.slice,this.insert,this.structure)}toJSON(){let e={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(e.slice=this.slice.toJSON()),this.structure&&(e.structure=!0),e}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number"||typeof t.gapFrom!="number"||typeof t.gapTo!="number"||typeof t.insert!="number")throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new dS(t.from,t.to,t.gapFrom,t.gapTo,nt.fromJSON(e,t.slice),t.insert,!!t.structure)}};Pi.jsonID("replaceAround",_r);function D1(s,e,t){let n=s.resolve(e),i=t-e,r=n.depth;for(;i>0&&r>0&&n.indexAfter(r)==n.node(r).childCount;)r--,i--;if(i>0){let o=n.node(r).maybeChild(n.indexAfter(r));for(;i>0;){if(!o||o.isLeaf)return!0;o=o.firstChild,i--}}return!1}function $9(s,e,t,n){let i=[],r=[],o,a;s.doc.nodesBetween(e,t,(c,l,u)=>{if(!c.isInline)return;let h=c.marks;if(!n.isInSet(h)&&u.type.allowsMarkType(n.type)){let d=Math.max(l,e),p=Math.min(l+c.nodeSize,t),m=n.addToSet(h);for(let v=0;v<h.length;v++)h[v].isInSet(m)||(o&&o.to==d&&o.mark.eq(h[v])?o.to=p:i.push(o=new dm(d,p,h[v])));a&&a.to==d?a.to=p:r.push(a=new yE(d,p,n))}}),i.forEach(c=>s.step(c)),r.forEach(c=>s.step(c))}function H9(s,e,t,n){let i=[],r=0;s.doc.nodesBetween(e,t,(o,a)=>{if(!o.isInline)return;r++;let c=null;if(n instanceof X0){let l=o.marks,u;for(;u=n.isInSet(l);)(c||(c=[])).push(u),l=u.removeFromSet(l)}else n?n.isInSet(o.marks)&&(c=[n]):c=o.marks;if(c&&c.length){let l=Math.min(a+o.nodeSize,t);for(let u=0;u<c.length;u++){let h=c[u],d;for(let p=0;p<i.length;p++){let m=i[p];m.step==r-1&&h.eq(i[p].style)&&(d=m)}d?(d.to=l,d.step=r):i.push({style:h,from:Math.max(a,e),to:l,step:r})}}}),i.forEach(o=>s.step(new dm(o.from,o.to,o.style)))}function _E(s,e,t,n=t.contentMatch,i=!0){let r=s.doc.nodeAt(e),o=[],a=e+1;for(let c=0;c<r.childCount;c++){let l=r.child(c),u=a+l.nodeSize,h=n.matchType(l.type);if(!h)o.push(new Fo(a,u,nt.empty));else{n=h;for(let d=0;d<l.marks.length;d++)t.allowsMarkType(l.marks[d].type)||s.step(new dm(a,u,l.marks[d]));if(i&&l.isText&&t.whitespace!="pre"){let d,p=/\r?\n|\r/g,m;for(;d=p.exec(l.text);)m||(m=new nt(Fe.from(t.schema.text(" ",t.allowedMarks(l.marks))),0,0)),o.push(new Fo(a+d.index,a+d.index+d[0].length,m))}}a=u}if(!n.validEnd){let c=n.fillBefore(Fe.empty,!0);s.replace(a,a,new nt(c,0,0))}for(let c=o.length-1;c>=0;c--)s.step(o[c])}function U9(s,e,t){return(e==0||s.canReplace(e,s.childCount))&&(t==s.childCount||s.canReplace(0,t))}function fm(s){let t=s.parent.content.cutByIndex(s.startIndex,s.endIndex);for(let n=s.depth,i=0,r=0;;--n){let o=s.$from.node(n),a=s.$from.index(n)+i,c=s.$to.indexAfter(n)-r;if(n<s.depth&&o.canReplace(a,c,t))return n;if(n==0||o.type.spec.isolating||!U9(o,a,c))break;a&&(i=1),c<o.childCount&&(r=1)}return null}function W9(s,e,t){let{$from:n,$to:i,depth:r}=e,o=n.before(r+1),a=i.after(r+1),c=o,l=a,u=Fe.empty,h=0;for(let m=r,v=!1;m>t;m--)v||n.index(m)>0?(v=!0,u=Fe.from(n.node(m).copy(u)),h++):c--;let d=Fe.empty,p=0;for(let m=r,v=!1;m>t;m--)v||i.after(m+1)<i.end(m)?(v=!0,d=Fe.from(i.node(m).copy(d)),p++):l++;s.step(new _r(c,l,o,a,new nt(u.append(d),h,p),u.size-h,!0))}function SE(s,e,t=null,n=s){let i=z9(s,e),r=i&&j9(n,e);return r?i.map(mx).concat({type:e,attrs:t}).concat(r.map(mx)):null}function mx(s){return{type:s,attrs:null}}function z9(s,e){let{parent:t,startIndex:n,endIndex:i}=s,r=t.contentMatchAt(n).findWrapping(e);if(!r)return null;let o=r.length?r[0]:e;return t.canReplaceWith(n,i,o)?r:null}function j9(s,e){let{parent:t,startIndex:n,endIndex:i}=s,r=t.child(n),o=e.contentMatch.findWrapping(r.type);if(!o)return null;let c=(o.length?o[o.length-1]:e).contentMatch;for(let l=n;c&&l<i;l++)c=c.matchType(t.child(l).type);return!c||!c.validEnd?null:o}function V9(s,e,t){let n=Fe.empty;for(let o=t.length-1;o>=0;o--){if(n.size){let a=t[o].type.contentMatch.matchFragment(n);if(!a||!a.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}n=Fe.from(t[o].type.create(t[o].attrs,n))}let i=e.start,r=e.end;s.step(new _r(i,r,i,r,new nt(n,0,0),t.length,!0))}function G9(s,e,t,n,i){if(!n.isTextblock)throw new RangeError("Type given to setBlockType should be a textblock");let r=s.steps.length;s.doc.nodesBetween(e,t,(o,a)=>{let c=typeof i=="function"?i(o):i;if(o.isTextblock&&!o.hasMarkup(n,c)&&q9(s.doc,s.mapping.slice(r).map(a),n)){let l=null;if(n.schema.linebreakReplacement){let p=n.whitespace=="pre",m=!!n.contentMatch.matchType(n.schema.linebreakReplacement);p&&!m?l=!1:!p&&m&&(l=!0)}l===!1&&HL(s,o,a,r),_E(s,s.mapping.slice(r).map(a,1),n,void 0,l===null);let u=s.mapping.slice(r),h=u.map(a,1),d=u.map(a+o.nodeSize,1);return s.step(new _r(h,d,h+1,d-1,new nt(Fe.from(n.create(c,null,o.marks)),0,0),1,!0)),l===!0&&$L(s,o,a,r),!1}})}function $L(s,e,t,n){e.forEach((i,r)=>{if(i.isText){let o,a=/\r?\n|\r/g;for(;o=a.exec(i.text);){let c=s.mapping.slice(n).map(t+1+r+o.index);s.replaceWith(c,c+1,e.type.schema.linebreakReplacement.create())}}})}function HL(s,e,t,n){e.forEach((i,r)=>{if(i.type==i.type.schema.linebreakReplacement){let o=s.mapping.slice(n).map(t+1+r);s.replaceWith(o,o+1,e.type.schema.text(`
`))}})}function q9(s,e,t){let n=s.resolve(e),i=n.index();return n.parent.canReplaceWith(i,i+1,t)}function K9(s,e,t,n,i){let r=s.doc.nodeAt(e);if(!r)throw new RangeError("No node at given position");t||(t=r.type);let o=t.create(n,null,i||r.marks);if(r.isLeaf)return s.replaceWith(e,e+r.nodeSize,o);if(!t.validContent(r.content))throw new RangeError("Invalid content for node type "+t.name);s.step(new _r(e,e+r.nodeSize,e+1,e+r.nodeSize-1,new nt(Fe.from(o),0,0),1,!0))}function bc(s,e,t=1,n){let i=s.resolve(e),r=i.depth-t,o=n&&n[n.length-1]||i.parent;if(r<0||i.parent.type.spec.isolating||!i.parent.canReplace(i.index(),i.parent.childCount)||!o.type.validContent(i.parent.content.cutByIndex(i.index(),i.parent.childCount)))return!1;for(let l=i.depth-1,u=t-2;l>r;l--,u--){let h=i.node(l),d=i.index(l);if(h.type.spec.isolating)return!1;let p=h.content.cutByIndex(d,h.childCount),m=n&&n[u+1];m&&(p=p.replaceChild(0,m.type.create(m.attrs)));let v=n&&n[u]||h;if(!h.canReplace(d+1,h.childCount)||!v.type.validContent(p))return!1}let a=i.indexAfter(r),c=n&&n[0];return i.node(r).canReplaceWith(a,a,c?c.type:i.node(r+1).type)}function Q9(s,e,t=1,n){let i=s.doc.resolve(e),r=Fe.empty,o=Fe.empty;for(let a=i.depth,c=i.depth-t,l=t-1;a>c;a--,l--){r=Fe.from(i.node(a).copy(r));let u=n&&n[l];o=Fe.from(u?u.type.create(u.attrs,o):i.node(a).copy(o))}s.step(new Fo(e,e,new nt(r.append(o),t,t),!0))}function dh(s,e){let t=s.resolve(e),n=t.index();return UL(t.nodeBefore,t.nodeAfter)&&t.parent.canReplace(n,n+1)}function X9(s,e){e.content.size||s.type.compatibleContent(e.type);let t=s.contentMatchAt(s.childCount),{linebreakReplacement:n}=s.type.schema;for(let i=0;i<e.childCount;i++){let r=e.child(i),o=r.type==n?s.type.schema.nodes.text:r.type;if(t=t.matchType(o),!t||!s.type.allowsMarks(r.marks))return!1}return t.validEnd}function UL(s,e){return!!(s&&e&&!s.isLeaf&&X9(s,e))}function Y0(s,e,t=-1){let n=s.resolve(e);for(let i=n.depth;;i--){let r,o,a=n.index(i);if(i==n.depth?(r=n.nodeBefore,o=n.nodeAfter):t>0?(r=n.node(i+1),a++,o=n.node(i).maybeChild(a)):(r=n.node(i).maybeChild(a-1),o=n.node(i+1)),r&&!r.isTextblock&&UL(r,o)&&n.node(i).canReplace(a,a+1))return e;if(i==0)break;e=t<0?n.before(i):n.after(i)}}function Y9(s,e,t){let n=null,{linebreakReplacement:i}=s.doc.type.schema,r=s.doc.resolve(e-t),o=r.node().type;if(i&&o.inlineContent){let u=o.whitespace=="pre",h=!!o.contentMatch.matchType(i);u&&!h?n=!1:!u&&h&&(n=!0)}let a=s.steps.length;if(n===!1){let u=s.doc.resolve(e+t);HL(s,u.node(),u.before(),a)}o.inlineContent&&_E(s,e+t-1,o,r.node().contentMatchAt(r.index()),n==null);let c=s.mapping.slice(a),l=c.map(e-t);if(s.step(new Fo(l,c.map(e+t,-1),nt.empty,!0)),n===!0){let u=s.doc.resolve(l);$L(s,u.node(),u.before(),s.steps.length)}return s}function J9(s,e,t){let n=s.resolve(e);if(n.parent.canReplaceWith(n.index(),n.index(),t))return e;if(n.parentOffset==0)for(let i=n.depth-1;i>=0;i--){let r=n.index(i);if(n.node(i).canReplaceWith(r,r,t))return n.before(i+1);if(r>0)return null}if(n.parentOffset==n.parent.content.size)for(let i=n.depth-1;i>=0;i--){let r=n.indexAfter(i);if(n.node(i).canReplaceWith(r,r,t))return n.after(i+1);if(r<n.node(i).childCount)return null}return null}function WL(s,e,t){let n=s.resolve(e);if(!t.content.size)return e;let i=t.content;for(let r=0;r<t.openStart;r++)i=i.firstChild.content;for(let r=1;r<=(t.openStart==0&&t.size?2:1);r++)for(let o=n.depth;o>=0;o--){let a=o==n.depth?0:n.pos<=(n.start(o+1)+n.end(o+1))/2?-1:1,c=n.index(o)+(a>0?1:0),l=n.node(o),u=!1;if(r==1)u=l.canReplace(c,c,i);else{let h=l.contentMatchAt(c).findWrapping(i.firstChild.type);u=h&&l.canReplaceWith(c,c,h[0])}if(u)return a==0?n.pos:a<0?n.before(o+1):n.after(o+1)}return null}function J0(s,e,t=e,n=nt.empty){if(e==t&&!n.size)return null;let i=s.resolve(e),r=s.resolve(t);return zL(i,r,n)?new Fo(e,t,n):new Z9(i,r,n).fit()}function zL(s,e,t){return!t.openStart&&!t.openEnd&&s.start()==e.start()&&s.parent.canReplace(s.index(),e.index(),t.content)}class Z9{constructor(e,t,n){this.$from=e,this.$to=t,this.unplaced=n,this.frontier=[],this.placed=Fe.empty;for(let i=0;i<=e.depth;i++){let r=e.node(i);this.frontier.push({type:r.type,match:r.contentMatchAt(e.indexAfter(i))})}for(let i=e.depth;i>0;i--)this.placed=Fe.from(e.node(i).copy(this.placed))}get depth(){return this.frontier.length-1}fit(){for(;this.unplaced.size;){let l=this.findFittable();l?this.placeNodes(l):this.openMore()||this.dropNode()}let e=this.mustMoveInline(),t=this.placed.size-this.depth-this.$from.depth,n=this.$from,i=this.close(e<0?this.$to:n.doc.resolve(e));if(!i)return null;let r=this.placed,o=n.depth,a=i.depth;for(;o&&a&&r.childCount==1;)r=r.firstChild.content,o--,a--;let c=new nt(r,o,a);return e>-1?new _r(n.pos,e,this.$to.pos,this.$to.end(),c,t):c.size||n.pos!=this.$to.pos?new Fo(n.pos,i.pos,c):null}findFittable(){let e=this.unplaced.openStart;for(let t=this.unplaced.content,n=0,i=this.unplaced.openEnd;n<e;n++){let r=t.firstChild;if(t.childCount>1&&(i=0),r.type.spec.isolating&&i<=n){e=n;break}t=r.content}for(let t=1;t<=2;t++)for(let n=t==1?e:this.unplaced.openStart;n>=0;n--){let i,r=null;n?(r=lC(this.unplaced.content,n-1).firstChild,i=r.content):i=this.unplaced.content;let o=i.firstChild;for(let a=this.depth;a>=0;a--){let{type:c,match:l}=this.frontier[a],u,h=null;if(t==1&&(o?l.matchType(o.type)||(h=l.fillBefore(Fe.from(o),!1)):r&&c.compatibleContent(r.type)))return{sliceDepth:n,frontierDepth:a,parent:r,inject:h};if(t==2&&o&&(u=l.findWrapping(o.type)))return{sliceDepth:n,frontierDepth:a,parent:r,wrap:u};if(r&&l.matchType(r.type))break}}}openMore(){let{content:e,openStart:t,openEnd:n}=this.unplaced,i=lC(e,t);return!i.childCount||i.firstChild.isLeaf?!1:(this.unplaced=new nt(e,t+1,Math.max(n,i.size+t>=e.size-n?t+1:0)),!0)}dropNode(){let{content:e,openStart:t,openEnd:n}=this.unplaced,i=lC(e,t);if(i.childCount<=1&&t>0){let r=e.size-t<=t+i.size;this.unplaced=new nt(Dm(e,t-1,1),t-1,r?t-1:n)}else this.unplaced=new nt(Dm(e,t,1),t,n)}placeNodes({sliceDepth:e,frontierDepth:t,parent:n,inject:i,wrap:r}){for(;this.depth>t;)this.closeFrontierNode();if(r)for(let v=0;v<r.length;v++)this.openFrontierNode(r[v]);let o=this.unplaced,a=n?n.content:o.content,c=o.openStart-e,l=0,u=[],{match:h,type:d}=this.frontier[t];if(i){for(let v=0;v<i.childCount;v++)u.push(i.child(v));h=h.matchFragment(i)}let p=a.size+e-(o.content.size-o.openEnd);for(;l<a.childCount;){let v=a.child(l),g=h.matchType(v.type);if(!g)break;l++,(l>1||c==0||v.content.size)&&(h=g,u.push(jL(v.mark(d.allowedMarks(v.marks)),l==1?c:0,l==a.childCount?p:-1)))}let m=l==a.childCount;m||(p=-1),this.placed=Nm(this.placed,t,Fe.from(u)),this.frontier[t].match=h,m&&p<0&&n&&n.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let v=0,g=a;v<p;v++){let y=g.lastChild;this.frontier.push({type:y.type,match:y.contentMatchAt(y.childCount)}),g=y.content}this.unplaced=m?e==0?nt.empty:new nt(Dm(o.content,e-1,1),e-1,p<0?o.openEnd:e-1):new nt(Dm(o.content,e,l),o.openStart,o.openEnd)}mustMoveInline(){if(!this.$to.parent.isTextblock)return-1;let e=this.frontier[this.depth],t;if(!e.type.isTextblock||!cC(this.$to,this.$to.depth,e.type,e.match,!1)||this.$to.depth==this.depth&&(t=this.findCloseLevel(this.$to))&&t.depth==this.depth)return-1;let{depth:n}=this.$to,i=this.$to.after(n);for(;n>1&&i==this.$to.end(--n);)++i;return i}findCloseLevel(e){e:for(let t=Math.min(this.depth,e.depth);t>=0;t--){let{match:n,type:i}=this.frontier[t],r=t<e.depth&&e.end(t+1)==e.pos+(e.depth-(t+1)),o=cC(e,t,i,n,r);if(o){for(let a=t-1;a>=0;a--){let{match:c,type:l}=this.frontier[a],u=cC(e,a,l,c,!0);if(!u||u.childCount)continue e}return{depth:t,fit:o,move:r?e.doc.resolve(e.after(t+1)):e}}}}close(e){let t=this.findCloseLevel(e);if(!t)return null;for(;this.depth>t.depth;)this.closeFrontierNode();t.fit.childCount&&(this.placed=Nm(this.placed,t.depth,t.fit)),e=t.move;for(let n=t.depth+1;n<=e.depth;n++){let i=e.node(n),r=i.type.contentMatch.fillBefore(i.content,!0,e.index(n));this.openFrontierNode(i.type,i.attrs,r)}return e}openFrontierNode(e,t=null,n){let i=this.frontier[this.depth];i.match=i.match.matchType(e),this.placed=Nm(this.placed,this.depth,Fe.from(e.create(t,n))),this.frontier.push({type:e,match:e.contentMatch})}closeFrontierNode(){let t=this.frontier.pop().match.fillBefore(Fe.empty,!0);t.childCount&&(this.placed=Nm(this.placed,this.frontier.length,t))}}function Dm(s,e,t){return e==0?s.cutByIndex(t,s.childCount):s.replaceChild(0,s.firstChild.copy(Dm(s.firstChild.content,e-1,t)))}function Nm(s,e,t){return e==0?s.append(t):s.replaceChild(s.childCount-1,s.lastChild.copy(Nm(s.lastChild.content,e-1,t)))}function lC(s,e){for(let t=0;t<e;t++)s=s.firstChild.content;return s}function jL(s,e,t){if(e<=0)return s;let n=s.content;return e>1&&(n=n.replaceChild(0,jL(n.firstChild,e-1,n.childCount==1?t-1:0))),e>0&&(n=s.type.contentMatch.fillBefore(n).append(n),t<=0&&(n=n.append(s.type.contentMatch.matchFragment(n).fillBefore(Fe.empty,!0)))),s.copy(n)}function cC(s,e,t,n,i){let r=s.node(e),o=i?s.indexAfter(e):s.index(e);if(o==r.childCount&&!t.compatibleContent(r.type))return null;let a=n.fillBefore(r.content,!0,o);return a&&!e7(t,r.content,o)?a:null}function e7(s,e,t){for(let n=t;n<e.childCount;n++)if(!s.allowsMarks(e.child(n).marks))return!0;return!1}function t7(s){return s.spec.defining||s.spec.definingForContent}function s7(s,e,t,n){if(!n.size)return s.deleteRange(e,t);let i=s.doc.resolve(e),r=s.doc.resolve(t);if(zL(i,r,n))return s.step(new Fo(e,t,n));let o=GL(i,r);o[o.length-1]==0&&o.pop();let a=-(i.depth+1);o.unshift(a);for(let d=i.depth,p=i.pos-1;d>0;d--,p--){let m=i.node(d).type.spec;if(m.defining||m.definingAsContext||m.isolating)break;o.indexOf(d)>-1?a=d:i.before(d)==p&&o.splice(1,0,-d)}let c=o.indexOf(a),l=[],u=n.openStart;for(let d=n.content,p=0;;p++){let m=d.firstChild;if(l.push(m),p==n.openStart)break;d=m.content}for(let d=u-1;d>=0;d--){let p=l[d],m=t7(p.type);if(m&&!p.sameMarkup(i.node(Math.abs(a)-1)))u=d;else if(m||!p.type.isTextblock)break}for(let d=n.openStart;d>=0;d--){let p=(d+u+1)%(n.openStart+1),m=l[p];if(m)for(let v=0;v<o.length;v++){let g=o[(v+c)%o.length],y=!0;g<0&&(y=!1,g=-g);let b=i.node(g-1),_=i.index(g-1);if(b.canReplaceWith(_,_,m.type,m.marks))return s.replace(i.before(g),y?r.after(g):t,new nt(VL(n.content,0,n.openStart,p),p,n.openEnd))}}let h=s.steps.length;for(let d=o.length-1;d>=0&&(s.replace(e,t,n),!(s.steps.length>h));d--){let p=o[d];p<0||(e=i.before(p),t=r.after(p))}}function VL(s,e,t,n,i){if(e<t){let r=s.firstChild;s=s.replaceChild(0,r.copy(VL(r.content,e+1,t,n,r)))}if(e>n){let r=i.contentMatchAt(0),o=r.fillBefore(s).append(s);s=o.append(r.matchFragment(o).fillBefore(Fe.empty,!0))}return s}function n7(s,e,t,n){if(!n.isInline&&e==t&&s.doc.resolve(e).parent.content.size){let i=J9(s.doc,e,n.type);i!=null&&(e=t=i)}s.replaceRange(e,t,new nt(Fe.from(n),0,0))}function i7(s,e,t){let n=s.doc.resolve(e),i=s.doc.resolve(t);if(n.parent.isTextblock&&i.parent.isTextblock&&n.start()!=i.start()&&n.parentOffset==0&&i.parentOffset==0){let o=n.sharedDepth(t),a=!1;for(let c=n.depth;c>o;c--)n.node(c).type.spec.isolating&&(a=!0);for(let c=i.depth;c>o;c--)i.node(c).type.spec.isolating&&(a=!0);if(!a){for(let c=n.depth;c>0&&e==n.start(c);c--)e=n.before(c);for(let c=i.depth;c>0&&t==i.start(c);c--)t=i.before(c);n=s.doc.resolve(e),i=s.doc.resolve(t)}}let r=GL(n,i);for(let o=0;o<r.length;o++){let a=r[o],c=o==r.length-1;if(c&&a==0||n.node(a).type.contentMatch.validEnd)return s.delete(n.start(a),i.end(a));if(a>0&&(c||n.node(a-1).canReplace(n.index(a-1),i.indexAfter(a-1))))return s.delete(n.before(a),i.after(a))}for(let o=1;o<=n.depth&&o<=i.depth;o++)if(e-n.start(o)==n.depth-o&&t>n.end(o)&&i.end(o)-t!=i.depth-o&&n.start(o-1)==i.start(o-1)&&n.node(o-1).canReplace(n.index(o-1),i.index(o-1)))return s.delete(n.before(o),t);s.delete(e,t)}function GL(s,e){let t=[],n=Math.min(s.depth,e.depth);for(let i=n;i>=0;i--){let r=s.start(i);if(r<s.pos-(s.depth-i)||e.end(i)>e.pos+(e.depth-i)||s.node(i).type.spec.isolating||e.node(i).type.spec.isolating)break;(r==e.start(i)||i==s.depth&&i==e.depth&&s.parent.inlineContent&&e.parent.inlineContent&&i&&e.start(i-1)==r-1)&&t.push(i)}return t}let qL=class fS extends Pi{constructor(e,t,n){super(),this.pos=e,this.attr=t,this.value=n}apply(e){let t=e.nodeAt(this.pos);if(!t)return Xi.fail("No node at attribute step's position");let n=Object.create(null);for(let r in t.attrs)n[r]=t.attrs[r];n[this.attr]=this.value;let i=t.type.create(n,null,t.marks);return Xi.fromReplace(e,this.pos,this.pos+1,new nt(Fe.from(i),0,t.isLeaf?0:1))}getMap(){return Af.empty}invert(e){return new fS(this.pos,this.attr,e.nodeAt(this.pos).attrs[this.attr])}map(e){let t=e.mapResult(this.pos,1);return t.deletedAfter?null:new fS(t.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.pos!="number"||typeof t.attr!="string")throw new RangeError("Invalid input for AttrStep.fromJSON");return new fS(t.pos,t.attr,t.value)}};Pi.jsonID("attr",qL);let KL=class N1 extends Pi{constructor(e,t){super(),this.attr=e,this.value=t}apply(e){let t=Object.create(null);for(let i in e.attrs)t[i]=e.attrs[i];t[this.attr]=this.value;let n=e.type.create(t,e.content,e.marks);return Xi.ok(n)}getMap(){return Af.empty}invert(e){return new N1(this.attr,e.attrs[this.attr])}map(e){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.attr!="string")throw new RangeError("Invalid input for DocAttrStep.fromJSON");return new N1(t.attr,t.value)}};Pi.jsonID("docAttr",KL);let Jg=class extends Error{};Jg=function s(e){let t=Error.call(this,e);return t.__proto__=s.prototype,t};Jg.prototype=Object.create(Error.prototype);Jg.prototype.constructor=Jg;Jg.prototype.name="TransformError";class QL{constructor(e){this.doc=e,this.steps=[],this.docs=[],this.mapping=new Qv}get before(){return this.docs.length?this.docs[0]:this.doc}step(e){let t=this.maybeStep(e);if(t.failed)throw new Jg(t.failed);return this}maybeStep(e){let t=e.apply(this.doc);return t.failed||this.addStep(e,t.doc),t}get docChanged(){return this.steps.length>0}changedRange(){let e=1e9,t=-1e9;for(let n=0;n<this.mapping.maps.length;n++){let i=this.mapping.maps[n];n&&(e=i.map(e,1),t=i.map(t,-1)),i.forEach((r,o,a,c)=>{e=Math.min(e,a),t=Math.max(t,c)})}return e==1e9?null:{from:e,to:t}}addStep(e,t){this.docs.push(this.doc),this.steps.push(e),this.mapping.appendMap(e.getMap()),this.doc=t}replace(e,t=e,n=nt.empty){let i=J0(this.doc,e,t,n);return i&&this.step(i),this}replaceWith(e,t,n){return this.replace(e,t,new nt(Fe.from(n),0,0))}delete(e,t){return this.replace(e,t,nt.empty)}insert(e,t){return this.replaceWith(e,e,t)}replaceRange(e,t,n){return s7(this,e,t,n),this}replaceRangeWith(e,t,n){return n7(this,e,t,n),this}deleteRange(e,t){return i7(this,e,t),this}lift(e,t){return W9(this,e,t),this}join(e,t=1){return Y9(this,e,t),this}wrap(e,t){return V9(this,e,t),this}setBlockType(e,t=e,n,i=null){return G9(this,e,t,n,i),this}setNodeMarkup(e,t,n=null,i){return K9(this,e,t,n,i),this}setNodeAttribute(e,t,n){return this.step(new qL(e,t,n)),this}setDocAttribute(e,t){return this.step(new KL(e,t)),this}addNodeMark(e,t){return this.step(new bE(e,t)),this}removeNodeMark(e,t){let n=this.doc.nodeAt(e);if(!n)throw new RangeError("No node at position "+e);if(t instanceof _s)t.isInSet(n.marks)&&this.step(new kw(e,t));else{let i=n.marks,r,o=[];for(;r=t.isInSet(i);)o.push(new kw(e,r)),i=r.removeFromSet(i);for(let a=o.length-1;a>=0;a--)this.step(o[a])}return this}split(e,t=1,n){return Q9(this,e,t,n),this}addMark(e,t,n){return $9(this,e,t,n),this}removeMark(e,t,n){return H9(this,e,t,n),this}clearIncompatible(e,t,n){return _E(this,e,t,n),this}}const uC=Object.create(null);let Ft=class{constructor(e,t,n){this.$anchor=e,this.$head=t,this.ranges=n||[new r7(e.min(t),e.max(t))]}get anchor(){return this.$anchor.pos}get head(){return this.$head.pos}get from(){return this.$from.pos}get to(){return this.$to.pos}get $from(){return this.ranges[0].$from}get $to(){return this.ranges[0].$to}get empty(){let e=this.ranges;for(let t=0;t<e.length;t++)if(e[t].$from.pos!=e[t].$to.pos)return!1;return!0}content(){return this.$from.doc.slice(this.from,this.to,!0)}replace(e,t=nt.empty){let n=t.content.lastChild,i=null;for(let a=0;a<t.openEnd;a++)i=n,n=n.lastChild;let r=e.steps.length,o=this.ranges;for(let a=0;a<o.length;a++){let{$from:c,$to:l}=o[a],u=e.mapping.slice(r);e.replaceRange(u.map(c.pos),u.map(l.pos),a?nt.empty:t),a==0&&bx(e,r,(n?n.isInline:i&&i.isTextblock)?-1:1)}}replaceWith(e,t){let n=e.steps.length,i=this.ranges;for(let r=0;r<i.length;r++){let{$from:o,$to:a}=i[r],c=e.mapping.slice(n),l=c.map(o.pos),u=c.map(a.pos);r?e.deleteRange(l,u):(e.replaceRangeWith(l,u,t),bx(e,n,t.isInline?-1:1))}}static findFrom(e,t,n=!1){let i=e.parent.inlineContent?new _t(e):ip(e.node(0),e.parent,e.pos,e.index(),t,n);if(i)return i;for(let r=e.depth-1;r>=0;r--){let o=t<0?ip(e.node(0),e.node(r),e.before(r+1),e.index(r),t,n):ip(e.node(0),e.node(r),e.after(r+1),e.index(r)+1,t,n);if(o)return o}return null}static near(e,t=1){return this.findFrom(e,t)||this.findFrom(e,-t)||new _c(e.node(0))}static atStart(e){return ip(e,e,0,0,1)||new _c(e)}static atEnd(e){return ip(e,e,e.content.size,e.childCount,-1)||new _c(e)}static fromJSON(e,t){if(!t||!t.type)throw new RangeError("Invalid input for Selection.fromJSON");let n=uC[t.type];if(!n)throw new RangeError(`No selection type ${t.type} defined`);return n.fromJSON(e,t)}static jsonID(e,t){if(e in uC)throw new RangeError("Duplicate use of selection JSON ID "+e);return uC[e]=t,t.prototype.jsonID=e,t}getBookmark(){return _t.between(this.$anchor,this.$head).getBookmark()}};Ft.prototype.visible=!0;let r7=class{constructor(e,t){this.$from=e,this.$to=t}},vx=!1;function yx(s){!vx&&!s.parent.inlineContent&&(vx=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+s.parent.type.name+")"))}let _t=class Bm extends Ft{constructor(e,t=e){yx(e),yx(t),super(e,t)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(e,t){let n=e.resolve(t.map(this.head));if(!n.parent.inlineContent)return Ft.near(n);let i=e.resolve(t.map(this.anchor));return new Bm(i.parent.inlineContent?i:n,n)}replace(e,t=nt.empty){if(super.replace(e,t),t==nt.empty){let n=this.$from.marksAcross(this.$to);n&&e.ensureMarks(n)}}eq(e){return e instanceof Bm&&e.anchor==this.anchor&&e.head==this.head}getBookmark(){return new XL(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(e,t){if(typeof t.anchor!="number"||typeof t.head!="number")throw new RangeError("Invalid input for TextSelection.fromJSON");return new Bm(e.resolve(t.anchor),e.resolve(t.head))}static create(e,t,n=t){let i=e.resolve(t);return new this(i,n==t?i:e.resolve(n))}static between(e,t,n){let i=e.pos-t.pos;if((!n||i)&&(n=i>=0?1:-1),!t.parent.inlineContent){let r=Ft.findFrom(t,n,!0)||Ft.findFrom(t,-n,!0);if(r)t=r.$head;else return Ft.near(t,n)}return e.parent.inlineContent||(i==0?e=t:(e=(Ft.findFrom(e,-n,!0)||Ft.findFrom(e,n,!0)).$anchor,e.pos<t.pos!=i<0&&(e=t))),new Bm(e,t)}};Ft.jsonID("text",_t);let XL=class YL{constructor(e,t){this.anchor=e,this.head=t}map(e){return new YL(e.map(this.anchor),e.map(this.head))}resolve(e){return _t.between(e.resolve(this.anchor),e.resolve(this.head))}},vt=class Fm extends Ft{constructor(e){let t=e.nodeAfter,n=e.node(0).resolve(e.pos+t.nodeSize);super(e,n),this.node=t}map(e,t){let{deleted:n,pos:i}=t.mapResult(this.anchor),r=e.resolve(i);return n?Ft.near(r):new Fm(r)}content(){return new nt(Fe.from(this.node),0,0)}eq(e){return e instanceof Fm&&e.anchor==this.anchor}toJSON(){return{type:"node",anchor:this.anchor}}getBookmark(){return new o7(this.anchor)}static fromJSON(e,t){if(typeof t.anchor!="number")throw new RangeError("Invalid input for NodeSelection.fromJSON");return new Fm(e.resolve(t.anchor))}static create(e,t){return new Fm(e.resolve(t))}static isSelectable(e){return!e.isText&&e.type.spec.selectable!==!1}};vt.prototype.visible=!1;Ft.jsonID("node",vt);let o7=class JL{constructor(e){this.anchor=e}map(e){let{deleted:t,pos:n}=e.mapResult(this.anchor);return t?new XL(n,n):new JL(n)}resolve(e){let t=e.resolve(this.anchor),n=t.nodeAfter;return n&&vt.isSelectable(n)?new vt(t):Ft.near(t)}},_c=class pS extends Ft{constructor(e){super(e.resolve(0),e.resolve(e.content.size))}replace(e,t=nt.empty){if(t==nt.empty){e.delete(0,e.doc.content.size);let n=Ft.atStart(e.doc);n.eq(e.selection)||e.setSelection(n)}else super.replace(e,t)}toJSON(){return{type:"all"}}static fromJSON(e){return new pS(e)}map(e){return new pS(e)}eq(e){return e instanceof pS}getBookmark(){return a7}};Ft.jsonID("all",_c);const a7={map(){return this},resolve(s){return new _c(s)}};function ip(s,e,t,n,i,r=!1){if(e.inlineContent)return _t.create(s,t);for(let o=n-(i>0?0:1);i>0?o<e.childCount:o>=0;o+=i){let a=e.child(o);if(a.isAtom){if(!r&&vt.isSelectable(a))return vt.create(s,t-(i<0?a.nodeSize:0))}else{let c=ip(s,a,t+i,i<0?a.childCount:0,i,r);if(c)return c}t+=a.nodeSize*i}return null}function bx(s,e,t){let n=s.steps.length-1;if(n<e)return;let i=s.steps[n];if(!(i instanceof Fo||i instanceof _r))return;let r=s.mapping.maps[n],o;r.forEach((a,c,l,u)=>{o==null&&(o=u)}),s.setSelection(Ft.near(s.doc.resolve(o),t))}const _x=1,x_=2,Sx=4;class l7 extends QL{constructor(e){super(e.doc),this.curSelectionFor=0,this.updated=0,this.meta=Object.create(null),this.time=Date.now(),this.curSelection=e.selection,this.storedMarks=e.storedMarks}get selection(){return this.curSelectionFor<this.steps.length&&(this.curSelection=this.curSelection.map(this.doc,this.mapping.slice(this.curSelectionFor)),this.curSelectionFor=this.steps.length),this.curSelection}setSelection(e){if(e.$from.doc!=this.doc)throw new RangeError("Selection passed to setSelection must point at the current document");return this.curSelection=e,this.curSelectionFor=this.steps.length,this.updated=(this.updated|_x)&~x_,this.storedMarks=null,this}get selectionSet(){return(this.updated&_x)>0}setStoredMarks(e){return this.storedMarks=e,this.updated|=x_,this}ensureMarks(e){return _s.sameSet(this.storedMarks||this.selection.$from.marks(),e)||this.setStoredMarks(e),this}addStoredMark(e){return this.ensureMarks(e.addToSet(this.storedMarks||this.selection.$head.marks()))}removeStoredMark(e){return this.ensureMarks(e.removeFromSet(this.storedMarks||this.selection.$head.marks()))}get storedMarksSet(){return(this.updated&x_)>0}addStep(e,t){super.addStep(e,t),this.updated=this.updated&~x_,this.storedMarks=null}setTime(e){return this.time=e,this}replaceSelection(e){return this.selection.replace(this,e),this}replaceSelectionWith(e,t=!0){let n=this.selection;return t&&(e=e.mark(this.storedMarks||(n.empty?n.$from.marks():n.$from.marksAcross(n.$to)||_s.none))),n.replaceWith(this,e),this}deleteSelection(){return this.selection.replace(this),this}insertText(e,t,n){let i=this.doc.type.schema;if(t==null)return e?this.replaceSelectionWith(i.text(e),!0):this.deleteSelection();{if(n==null&&(n=t),!e)return this.deleteRange(t,n);let r=this.storedMarks;if(!r){let o=this.doc.resolve(t);r=n==t?o.marks():o.marksAcross(this.doc.resolve(n))}return this.replaceRangeWith(t,n,i.text(e,r)),!this.selection.empty&&this.selection.to==t+e.length&&this.setSelection(Ft.near(this.selection.$to)),this}}setMeta(e,t){return this.meta[typeof e=="string"?e:e.key]=t,this}getMeta(e){return this.meta[typeof e=="string"?e:e.key]}get isGeneric(){for(let e in this.meta)return!1;return!0}scrollIntoView(){return this.updated|=Sx,this}get scrolledIntoView(){return(this.updated&Sx)>0}}function wx(s,e){return!e||!s?s:s.bind(e)}let $m=class{constructor(e,t,n){this.name=e,this.init=wx(t.init,n),this.apply=wx(t.apply,n)}};const c7=[new $m("doc",{init(s){return s.doc||s.schema.topNodeType.createAndFill()},apply(s){return s.doc}}),new $m("selection",{init(s,e){return s.selection||Ft.atStart(e.doc)},apply(s){return s.selection}}),new $m("storedMarks",{init(s){return s.storedMarks||null},apply(s,e,t,n){return n.selection.$cursor?s.storedMarks:null}}),new $m("scrollToSelection",{init(){return 0},apply(s,e){return s.scrolledIntoView?e+1:e}})];class hC{constructor(e,t){this.schema=e,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=c7.slice(),t&&t.forEach(n=>{if(this.pluginsByKey[n.key])throw new RangeError("Adding different instances of a keyed plugin ("+n.key+")");this.plugins.push(n),this.pluginsByKey[n.key]=n,n.spec.state&&this.fields.push(new $m(n.key,n.spec.state,n))})}}class vp{constructor(e){this.config=e}get schema(){return this.config.schema}get plugins(){return this.config.plugins}apply(e){return this.applyTransaction(e).state}filterTransaction(e,t=-1){for(let n=0;n<this.config.plugins.length;n++)if(n!=t){let i=this.config.plugins[n];if(i.spec.filterTransaction&&!i.spec.filterTransaction.call(i,e,this))return!1}return!0}applyTransaction(e){if(!this.filterTransaction(e))return{state:this,transactions:[]};let t=[e],n=this.applyInner(e),i=null;for(;;){let r=!1;for(let o=0;o<this.config.plugins.length;o++){let a=this.config.plugins[o];if(a.spec.appendTransaction){let c=i?i[o].n:0,l=i?i[o].state:this,u=c<t.length&&a.spec.appendTransaction.call(a,c?t.slice(c):t,l,n);if(u&&n.filterTransaction(u,o)){if(u.setMeta("appendedTransaction",e),!i){i=[];for(let h=0;h<this.config.plugins.length;h++)i.push(h<o?{state:n,n:t.length}:{state:this,n:0})}t.push(u),n=n.applyInner(u),r=!0}i&&(i[o]={state:n,n:t.length})}}if(!r)return{state:n,transactions:t}}}applyInner(e){if(!e.before.eq(this.doc))throw new RangeError("Applying a mismatched transaction");let t=new vp(this.config),n=this.config.fields;for(let i=0;i<n.length;i++){let r=n[i];t[r.name]=r.apply(e,this[r.name],this,t)}return t}get tr(){return new l7(this)}static create(e){let t=new hC(e.doc?e.doc.type.schema:e.schema,e.plugins),n=new vp(t);for(let i=0;i<t.fields.length;i++)n[t.fields[i].name]=t.fields[i].init(e,n);return n}reconfigure(e){let t=new hC(this.schema,e.plugins),n=t.fields,i=new vp(t);for(let r=0;r<n.length;r++){let o=n[r].name;i[o]=this.hasOwnProperty(o)?this[o]:n[r].init(e,i)}return i}toJSON(e){let t={doc:this.doc.toJSON(),selection:this.selection.toJSON()};if(this.storedMarks&&(t.storedMarks=this.storedMarks.map(n=>n.toJSON())),e&&typeof e=="object")for(let n in e){if(n=="doc"||n=="selection")throw new RangeError("The JSON fields `doc` and `selection` are reserved");let i=e[n],r=i.spec.state;r&&r.toJSON&&(t[n]=r.toJSON.call(i,this[i.key]))}return t}static fromJSON(e,t,n){if(!t)throw new RangeError("Invalid input for EditorState.fromJSON");if(!e.schema)throw new RangeError("Required config field 'schema' missing");let i=new hC(e.schema,e.plugins),r=new vp(i);return i.fields.forEach(o=>{if(o.name=="doc")r.doc=yc.fromJSON(e.schema,t.doc);else if(o.name=="selection")r.selection=Ft.fromJSON(r.doc,t.selection);else if(o.name=="storedMarks")t.storedMarks&&(r.storedMarks=t.storedMarks.map(e.schema.markFromJSON));else{if(n)for(let a in n){let c=n[a],l=c.spec.state;if(c.key==o.name&&l&&l.fromJSON&&Object.prototype.hasOwnProperty.call(t,a)){r[o.name]=l.fromJSON.call(c,e,t[a],r);return}}r[o.name]=o.init(e,r)}}),r}}function ZL(s,e,t){for(let n in s){let i=s[n];i instanceof Function?i=i.bind(e):n=="handleDOMEvents"&&(i=ZL(i,e,{})),t[n]=i}return t}class $s{constructor(e){this.spec=e,this.props={},e.props&&ZL(e.props,this,this.props),this.key=e.key?e.key.key:eP("plugin")}getState(e){return e[this.key]}}const dC=Object.create(null);function eP(s){return s in dC?s+"$"+ ++dC[s]:(dC[s]=0,s+"$")}class fn{constructor(e="key"){this.key=eP(e)}get(e){return e.config.pluginsByKey[this.key]}getState(e){return e[this.key]}}const tP=(s,e)=>s.selection.empty?!1:(e&&e(s.tr.deleteSelection().scrollIntoView()),!0);function sP(s,e){let{$cursor:t}=s.selection;return!t||(e?!e.endOfTextblock("backward",s):t.parentOffset>0)?null:t}const nP=(s,e,t)=>{let n=sP(s,t);if(!n)return!1;let i=wE(n);if(!i){let o=n.blockRange(),a=o&&fm(o);return a==null?!1:(e&&e(s.tr.lift(o,a).scrollIntoView()),!0)}let r=i.nodeBefore;if(dP(s,i,e,-1))return!0;if(n.parent.content.size==0&&(Zg(r,"end")||vt.isSelectable(r)))for(let o=n.depth;;o--){let a=J0(s.doc,n.before(o),n.after(o),nt.empty);if(a&&a.slice.size<a.to-a.from){if(e){let c=s.tr.step(a);c.setSelection(Zg(r,"end")?Ft.findFrom(c.doc.resolve(c.mapping.map(i.pos,-1)),-1):vt.create(c.doc,i.pos-r.nodeSize)),e(c.scrollIntoView())}return!0}if(o==1||n.node(o-1).childCount>1)break}return r.isAtom&&i.depth==n.depth-1?(e&&e(s.tr.delete(i.pos-r.nodeSize,i.pos).scrollIntoView()),!0):!1},u7=(s,e,t)=>{let n=sP(s,t);if(!n)return!1;let i=wE(n);return i?iP(s,i,e):!1},h7=(s,e,t)=>{let n=oP(s,t);if(!n)return!1;let i=kE(n);return i?iP(s,i,e):!1};function iP(s,e,t){let n=e.nodeBefore,i=n,r=e.pos-1;for(;!i.isTextblock;r--){if(i.type.spec.isolating)return!1;let u=i.lastChild;if(!u)return!1;i=u}let o=e.nodeAfter,a=o,c=e.pos+1;for(;!a.isTextblock;c++){if(a.type.spec.isolating)return!1;let u=a.firstChild;if(!u)return!1;a=u}let l=J0(s.doc,r,c,nt.empty);if(!l||l.from!=r||l instanceof Fo&&l.slice.size>=c-r)return!1;if(t){let u=s.tr.step(l);u.setSelection(_t.create(u.doc,r)),t(u.scrollIntoView())}return!0}function Zg(s,e,t=!1){for(let n=s;n;n=e=="start"?n.firstChild:n.lastChild){if(n.isTextblock)return!0;if(t&&n.childCount!=1)return!1}return!1}const rP=(s,e,t)=>{let{$head:n,empty:i}=s.selection,r=n;if(!i)return!1;if(n.parent.isTextblock){if(t?!t.endOfTextblock("backward",s):n.parentOffset>0)return!1;r=wE(n)}let o=r&&r.nodeBefore;return!o||!vt.isSelectable(o)?!1:(e&&e(s.tr.setSelection(vt.create(s.doc,r.pos-o.nodeSize)).scrollIntoView()),!0)};function wE(s){if(!s.parent.type.spec.isolating)for(let e=s.depth-1;e>=0;e--){if(s.index(e)>0)return s.doc.resolve(s.before(e+1));if(s.node(e).type.spec.isolating)break}return null}function oP(s,e){let{$cursor:t}=s.selection;return!t||(e?!e.endOfTextblock("forward",s):t.parentOffset<t.parent.content.size)?null:t}const aP=(s,e,t)=>{let n=oP(s,t);if(!n)return!1;let i=kE(n);if(!i)return!1;let r=i.nodeAfter;if(dP(s,i,e,1))return!0;if(n.parent.content.size==0&&(Zg(r,"start")||vt.isSelectable(r))){let o=J0(s.doc,n.before(),n.after(),nt.empty);if(o&&o.slice.size<o.to-o.from){if(e){let a=s.tr.step(o);a.setSelection(Zg(r,"start")?Ft.findFrom(a.doc.resolve(a.mapping.map(i.pos)),1):vt.create(a.doc,a.mapping.map(i.pos))),e(a.scrollIntoView())}return!0}}return r.isAtom&&i.depth==n.depth-1?(e&&e(s.tr.delete(i.pos,i.pos+r.nodeSize).scrollIntoView()),!0):!1},lP=(s,e,t)=>{let{$head:n,empty:i}=s.selection,r=n;if(!i)return!1;if(n.parent.isTextblock){if(t?!t.endOfTextblock("forward",s):n.parentOffset<n.parent.content.size)return!1;r=kE(n)}let o=r&&r.nodeAfter;return!o||!vt.isSelectable(o)?!1:(e&&e(s.tr.setSelection(vt.create(s.doc,r.pos)).scrollIntoView()),!0)};function kE(s){if(!s.parent.type.spec.isolating)for(let e=s.depth-1;e>=0;e--){let t=s.node(e);if(s.index(e)+1<t.childCount)return s.doc.resolve(s.after(e+1));if(t.type.spec.isolating)break}return null}const d7=(s,e)=>{let t=s.selection,n=t instanceof vt,i;if(n){if(t.node.isTextblock||!dh(s.doc,t.from))return!1;i=t.from}else if(i=Y0(s.doc,t.from,-1),i==null)return!1;if(e){let r=s.tr.join(i);n&&r.setSelection(vt.create(r.doc,i-s.doc.resolve(i).nodeBefore.nodeSize)),e(r.scrollIntoView())}return!0},f7=(s,e)=>{let t=s.selection,n;if(t instanceof vt){if(t.node.isTextblock||!dh(s.doc,t.to))return!1;n=t.to}else if(n=Y0(s.doc,t.to,1),n==null)return!1;return e&&e(s.tr.join(n).scrollIntoView()),!0},p7=(s,e)=>{let{$from:t,$to:n}=s.selection,i=t.blockRange(n),r=i&&fm(i);return r==null?!1:(e&&e(s.tr.lift(i,r).scrollIntoView()),!0)},cP=(s,e)=>{let{$head:t,$anchor:n}=s.selection;return!t.parent.type.spec.code||!t.sameParent(n)?!1:(e&&e(s.tr.insertText(`
`).scrollIntoView()),!0)};function CE(s){for(let e=0;e<s.edgeCount;e++){let{type:t}=s.edge(e);if(t.isTextblock&&!t.hasRequiredAttrs())return t}return null}const g7=(s,e)=>{let{$head:t,$anchor:n}=s.selection;if(!t.parent.type.spec.code||!t.sameParent(n))return!1;let i=t.node(-1),r=t.indexAfter(-1),o=CE(i.contentMatchAt(r));if(!o||!i.canReplaceWith(r,r,o))return!1;if(e){let a=t.after(),c=s.tr.replaceWith(a,a,o.createAndFill());c.setSelection(Ft.near(c.doc.resolve(a),1)),e(c.scrollIntoView())}return!0},uP=(s,e)=>{let t=s.selection,{$from:n,$to:i}=t;if(t instanceof _c||n.parent.inlineContent||i.parent.inlineContent)return!1;let r=CE(i.parent.contentMatchAt(i.indexAfter()));if(!r||!r.isTextblock)return!1;if(e){let o=(!n.parentOffset&&i.index()<i.parent.childCount?n:i).pos,a=s.tr.insert(o,r.createAndFill());a.setSelection(_t.create(a.doc,o+1)),e(a.scrollIntoView())}return!0},hP=(s,e)=>{let{$cursor:t}=s.selection;if(!t||t.parent.content.size)return!1;if(t.depth>1&&t.after()!=t.end(-1)){let r=t.before();if(bc(s.doc,r))return e&&e(s.tr.split(r).scrollIntoView()),!0}let n=t.blockRange(),i=n&&fm(n);return i==null?!1:(e&&e(s.tr.lift(n,i).scrollIntoView()),!0)};function m7(s){return(e,t)=>{let{$from:n,$to:i}=e.selection;if(e.selection instanceof vt&&e.selection.node.isBlock)return!n.parentOffset||!bc(e.doc,n.pos)?!1:(t&&t(e.tr.split(n.pos).scrollIntoView()),!0);if(!n.depth)return!1;let r=[],o,a,c=!1,l=!1;for(let p=n.depth;;p--)if(n.node(p).isBlock){c=n.end(p)==n.pos+(n.depth-p),l=n.start(p)==n.pos-(n.depth-p),a=CE(n.node(p-1).contentMatchAt(n.indexAfter(p-1))),r.unshift(c&&a?{type:a}:null),o=p;break}else{if(p==1)return!1;r.unshift(null)}let u=e.tr;(e.selection instanceof _t||e.selection instanceof _c)&&u.deleteSelection();let h=u.mapping.map(n.pos),d=bc(u.doc,h,r.length,r);if(d||(r[0]=a?{type:a}:null,d=bc(u.doc,h,r.length,r)),!d)return!1;if(u.split(h,r.length,r),!c&&l&&n.node(o).type!=a){let p=u.mapping.map(n.before(o)),m=u.doc.resolve(p);a&&n.node(o-1).canReplaceWith(m.index(),m.index()+1,a)&&u.setNodeMarkup(u.mapping.map(n.before(o)),a)}return t&&t(u.scrollIntoView()),!0}}const v7=m7(),y7=(s,e)=>{let{$from:t,to:n}=s.selection,i,r=t.sharedDepth(n);return r==0?!1:(i=t.before(r),e&&e(s.tr.setSelection(vt.create(s.doc,i))),!0)};function b7(s,e,t){let n=e.nodeBefore,i=e.nodeAfter,r=e.index();return!n||!i||!n.type.compatibleContent(i.type)?!1:!n.content.size&&e.parent.canReplace(r-1,r)?(t&&t(s.tr.delete(e.pos-n.nodeSize,e.pos).scrollIntoView()),!0):!e.parent.canReplace(r,r+1)||!(i.isTextblock||dh(s.doc,e.pos))?!1:(t&&t(s.tr.join(e.pos).scrollIntoView()),!0)}function dP(s,e,t,n){let i=e.nodeBefore,r=e.nodeAfter,o,a,c=i.type.spec.isolating||r.type.spec.isolating;if(!c&&b7(s,e,t))return!0;let l=!c&&e.parent.canReplace(e.index(),e.index()+1);if(l&&(o=(a=i.contentMatchAt(i.childCount)).findWrapping(r.type))&&a.matchType(o[0]||r.type).validEnd){if(t){let p=e.pos+r.nodeSize,m=Fe.empty;for(let y=o.length-1;y>=0;y--)m=Fe.from(o[y].create(null,m));m=Fe.from(i.copy(m));let v=s.tr.step(new _r(e.pos-1,p,e.pos,p,new nt(m,1,0),o.length,!0)),g=v.doc.resolve(p+2*o.length);g.nodeAfter&&g.nodeAfter.type==i.type&&dh(v.doc,g.pos)&&v.join(g.pos),t(v.scrollIntoView())}return!0}let u=r.type.spec.isolating||n>0&&c?null:Ft.findFrom(e,1),h=u&&u.$from.blockRange(u.$to),d=h&&fm(h);if(d!=null&&d>=e.depth)return t&&t(s.tr.lift(h,d).scrollIntoView()),!0;if(l&&Zg(r,"start",!0)&&Zg(i,"end")){let p=i,m=[];for(;m.push(p),!p.isTextblock;)p=p.lastChild;let v=r,g=1;for(;!v.isTextblock;v=v.firstChild)g++;if(p.canReplace(p.childCount,p.childCount,v.content)){if(t){let y=Fe.empty;for(let _=m.length-1;_>=0;_--)y=Fe.from(m[_].copy(y));let b=s.tr.step(new _r(e.pos-m.length,e.pos+r.nodeSize,e.pos+g,e.pos+r.nodeSize-g,new nt(y,m.length,0),0,!0));t(b.scrollIntoView())}return!0}}return!1}function fP(s){return function(e,t){let n=e.selection,i=s<0?n.$from:n.$to,r=i.depth;for(;i.node(r).isInline;){if(!r)return!1;r--}return i.node(r).isTextblock?(t&&t(e.tr.setSelection(_t.create(e.doc,s<0?i.start(r):i.end(r)))),!0):!1}}const _7=fP(-1),S7=fP(1);function w7(s,e=null){return function(t,n){let{$from:i,$to:r}=t.selection,o=i.blockRange(r),a=o&&SE(o,s,e);return a?(n&&n(t.tr.wrap(o,a).scrollIntoView()),!0):!1}}function kx(s,e=null){return function(t,n){let i=!1;for(let r=0;r<t.selection.ranges.length&&!i;r++){let{$from:{pos:o},$to:{pos:a}}=t.selection.ranges[r];t.doc.nodesBetween(o,a,(c,l)=>{if(i)return!1;if(!(!c.isTextblock||c.hasMarkup(s,e)))if(c.type==s)i=!0;else{let u=t.doc.resolve(l),h=u.index();i=u.parent.canReplaceWith(h,h+1,s)}})}if(!i)return!1;if(n){let r=t.tr;for(let o=0;o<t.selection.ranges.length;o++){let{$from:{pos:a},$to:{pos:c}}=t.selection.ranges[o];r.setBlockType(a,c,s,e)}n(r.scrollIntoView())}return!0}}function TE(...s){return function(e,t,n){for(let i=0;i<s.length;i++)if(s[i](e,t,n))return!0;return!1}}TE(tP,nP,rP);TE(tP,aP,lP);TE(cP,uP,hP,v7);typeof navigator<"u"?/Mac|iP(hone|[oa]d)/.test(navigator.platform):typeof os<"u"&&os.platform&&os.platform()=="darwin";function k7(s,e=null){return function(t,n){let{$from:i,$to:r}=t.selection,o=i.blockRange(r);if(!o)return!1;let a=n?t.tr:null;return C7(a,o,s,e)?(n&&n(a.scrollIntoView()),!0):!1}}function C7(s,e,t,n=null){let i=!1,r=e,o=e.$from.doc;if(e.depth>=2&&e.$from.node(e.depth-1).type.compatibleContent(t)&&e.startIndex==0){if(e.$from.index(e.depth-1)==0)return!1;let c=o.resolve(e.start-2);r=new Sw(c,c,e.depth),e.endIndex<e.parent.childCount&&(e=new Sw(e.$from,o.resolve(e.$to.end(e.depth)),e.depth)),i=!0}let a=SE(r,t,n,e);return a?(s&&T7(s,e,a,i,t),!0):!1}function T7(s,e,t,n,i){let r=Fe.empty;for(let u=t.length-1;u>=0;u--)r=Fe.from(t[u].type.create(t[u].attrs,r));s.step(new _r(e.start-(n?2:0),e.end,e.start,e.end,new nt(r,0,0),t.length,!0));let o=0;for(let u=0;u<t.length;u++)t[u].type==i&&(o=u+1);let a=t.length-o,c=e.start+t.length-(n?2:0),l=e.parent;for(let u=e.startIndex,h=e.endIndex,d=!0;u<h;u++,d=!1)!d&&bc(s.doc,c,a)&&(s.split(c,a),c+=2*a),c+=l.child(u).nodeSize;return s}function A7(s){return function(e,t){let{$from:n,$to:i}=e.selection,r=n.blockRange(i,o=>o.childCount>0&&o.firstChild.type==s);return r?t?n.node(r.depth-1).type==s?E7(e,t,s,r):M7(e,t,r):!0:!1}}function E7(s,e,t,n){let i=s.tr,r=n.end,o=n.$to.end(n.depth);r<o&&(i.step(new _r(r-1,o,r,o,new nt(Fe.from(t.create(null,n.parent.copy())),1,0),1,!0)),n=new Sw(i.doc.resolve(n.$from.pos),i.doc.resolve(o),n.depth));const a=fm(n);if(a==null)return!1;i.lift(n,a);let c=i.doc.resolve(i.mapping.map(r,-1)-1);return dh(i.doc,c.pos)&&c.nodeBefore.type==c.nodeAfter.type&&i.join(c.pos),e(i.scrollIntoView()),!0}function M7(s,e,t){let n=s.tr,i=t.parent;for(let p=t.end,m=t.endIndex-1,v=t.startIndex;m>v;m--)p-=i.child(m).nodeSize,n.delete(p-1,p+1);let r=n.doc.resolve(t.start),o=r.nodeAfter;if(n.mapping.map(t.end)!=t.start+r.nodeAfter.nodeSize)return!1;let a=t.startIndex==0,c=t.endIndex==i.childCount,l=r.node(-1),u=r.index(-1);if(!l.canReplace(u+(a?0:1),u+1,o.content.append(c?Fe.empty:Fe.from(i))))return!1;let h=r.pos,d=h+o.nodeSize;return n.step(new _r(h-(a?1:0),d+(c?1:0),h+1,d-1,new nt((a?Fe.empty:Fe.from(i.copy(Fe.empty))).append(c?Fe.empty:Fe.from(i.copy(Fe.empty))),a?0:1,c?0:1),a?0:1)),e(n.scrollIntoView()),!0}function x7(s){return function(e,t){let{$from:n,$to:i}=e.selection,r=n.blockRange(i,l=>l.childCount>0&&l.firstChild.type==s);if(!r)return!1;let o=r.startIndex;if(o==0)return!1;let a=r.parent,c=a.child(o-1);if(c.type!=s)return!1;if(t){let l=c.lastChild&&c.lastChild.type==a.type,u=Fe.from(l?s.create():null),h=new nt(Fe.from(s.create(null,Fe.from(a.type.create(null,u)))),l?3:1,0),d=r.start,p=r.end;t(e.tr.step(new _r(d-(l?3:1),p,d,p,h,1,!0)).scrollIntoView())}return!0}}const fi=function(s){for(var e=0;;e++)if(s=s.previousSibling,!s)return e},em=function(s){let e=s.assignedSlot||s.parentNode;return e&&e.nodeType==11?e.host:e};let B1=null;const El=function(s,e,t){let n=B1||(B1=document.createRange());return n.setEnd(s,t??s.nodeValue.length),n.setStart(s,e||0),n},I7=function(){B1=null},Ef=function(s,e,t,n){return t&&(Cx(s,e,t,n,-1)||Cx(s,e,t,n,1))},R7=/^(img|br|input|textarea|hr)$/i;function Cx(s,e,t,n,i){for(var r;;){if(s==t&&e==n)return!0;if(e==(i<0?0:Ro(s))){let o=s.parentNode;if(!o||o.nodeType!=1||Zb(s)||R7.test(s.nodeName)||s.contentEditable=="false")return!1;e=fi(s)+(i<0?0:1),s=o}else if(s.nodeType==1){let o=s.childNodes[e+(i<0?-1:0)];if(o.nodeType==1&&o.contentEditable=="false")if(!((r=o.pmViewDesc)===null||r===void 0)&&r.ignoreForSelection)e+=i;else return!1;else s=o,e=i<0?Ro(s):0}else return!1}}function Ro(s){return s.nodeType==3?s.nodeValue.length:s.childNodes.length}function L7(s,e){for(;;){if(s.nodeType==3&&e)return s;if(s.nodeType==1&&e>0){if(s.contentEditable=="false")return null;s=s.childNodes[e-1],e=Ro(s)}else if(s.parentNode&&!Zb(s))e=fi(s),s=s.parentNode;else return null}}function P7(s,e){for(;;){if(s.nodeType==3&&e<s.nodeValue.length)return s;if(s.nodeType==1&&e<s.childNodes.length){if(s.contentEditable=="false")return null;s=s.childNodes[e],e=0}else if(s.parentNode&&!Zb(s))e=fi(s)+1,s=s.parentNode;else return null}}function O7(s,e,t){for(let n=e==0,i=e==Ro(s);n||i;){if(s==t)return!0;let r=fi(s);if(s=s.parentNode,!s)return!1;n=n&&r==0,i=i&&r==Ro(s)}}function Zb(s){let e;for(let t=s;t&&!(e=t.pmViewDesc);t=t.parentNode);return e&&e.node&&e.node.isBlock&&(e.dom==s||e.contentDOM==s)}const Z0=function(s){return s.focusNode&&Ef(s.focusNode,s.focusOffset,s.anchorNode,s.anchorOffset)};function Ih(s,e){let t=document.createEvent("Event");return t.initEvent("keydown",!0,!0),t.keyCode=s,t.key=t.code=e,t}function D7(s){let e=s.activeElement;for(;e&&e.shadowRoot;)e=e.shadowRoot.activeElement;return e}function N7(s,e,t){if(s.caretPositionFromPoint)try{let n=s.caretPositionFromPoint(e,t);if(n)return{node:n.offsetNode,offset:Math.min(Ro(n.offsetNode),n.offset)}}catch{}if(s.caretRangeFromPoint){let n=s.caretRangeFromPoint(e,t);if(n)return{node:n.startContainer,offset:Math.min(Ro(n.startContainer),n.startOffset)}}}const ol=typeof navigator<"u"?navigator:null,Tx=typeof document<"u"?document:null,fh=ol&&ol.userAgent||"",F1=/Edge\/(\d+)/.exec(fh),pP=/MSIE \d/.exec(fh),$1=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(fh),yr=!!(pP||$1||F1),nh=pP?document.documentMode:$1?+$1[1]:F1?+F1[1]:0,Po=!yr&&/gecko\/(\d+)/i.test(fh);Po&&+(/Firefox\/(\d+)/.exec(fh)||[0,0])[1];const H1=!yr&&/Chrome\/(\d+)/.exec(fh),vi=!!H1,gP=H1?+H1[1]:0,Li=!yr&&!!ol&&/Apple Computer/.test(ol.vendor),tm=Li&&(/Mobile\/\w+/.test(fh)||!!ol&&ol.maxTouchPoints>2),Mo=tm||(ol?/Mac/.test(ol.platform):!1),mP=ol?/Win/.test(ol.platform):!1,pc=/Android \d/.test(fh),e_=!!Tx&&"webkitFontSmoothing"in Tx.documentElement.style,B7=e_?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function F7(s){let e=s.defaultView&&s.defaultView.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:s.documentElement.clientWidth,top:0,bottom:s.documentElement.clientHeight}}function bl(s,e){return typeof s=="number"?s:s[e]}function $7(s){let e=s.getBoundingClientRect(),t=e.width/s.offsetWidth||1,n=e.height/s.offsetHeight||1;return{left:e.left,right:e.left+s.clientWidth*t,top:e.top,bottom:e.top+s.clientHeight*n}}function Ax(s,e,t){let n=s.someProp("scrollThreshold")||0,i=s.someProp("scrollMargin")||5,r=s.dom.ownerDocument;for(let o=t||s.dom;o;){if(o.nodeType!=1){o=em(o);continue}let a=o,c=a==r.body,l=c?F7(r):$7(a),u=0,h=0;if(e.top<l.top+bl(n,"top")?h=-(l.top-e.top+bl(i,"top")):e.bottom>l.bottom-bl(n,"bottom")&&(h=e.bottom-e.top>l.bottom-l.top?e.top+bl(i,"top")-l.top:e.bottom-l.bottom+bl(i,"bottom")),e.left<l.left+bl(n,"left")?u=-(l.left-e.left+bl(i,"left")):e.right>l.right-bl(n,"right")&&(u=e.right-l.right+bl(i,"right")),u||h)if(c)r.defaultView.scrollBy(u,h);else{let p=a.scrollLeft,m=a.scrollTop;h&&(a.scrollTop+=h),u&&(a.scrollLeft+=u);let v=a.scrollLeft-p,g=a.scrollTop-m;e={left:e.left-v,top:e.top-g,right:e.right-v,bottom:e.bottom-g}}let d=c?"fixed":getComputedStyle(o).position;if(/^(fixed|sticky)$/.test(d))break;o=d=="absolute"?o.offsetParent:em(o)}}function H7(s){let e=s.dom.getBoundingClientRect(),t=Math.max(0,e.top),n,i;for(let r=(e.left+e.right)/2,o=t+1;o<Math.min(innerHeight,e.bottom);o+=5){let a=s.root.elementFromPoint(r,o);if(!a||a==s.dom||!s.dom.contains(a))continue;let c=a.getBoundingClientRect();if(c.top>=t-20){n=a,i=c.top;break}}return{refDOM:n,refTop:i,stack:vP(s.dom)}}function vP(s){let e=[],t=s.ownerDocument;for(let n=s;n&&(e.push({dom:n,top:n.scrollTop,left:n.scrollLeft}),s!=t);n=em(n));return e}function U7({refDOM:s,refTop:e,stack:t}){let n=s?s.getBoundingClientRect().top:0;yP(t,n==0?0:n-e)}function yP(s,e){for(let t=0;t<s.length;t++){let{dom:n,top:i,left:r}=s[t];n.scrollTop!=i+e&&(n.scrollTop=i+e),n.scrollLeft!=r&&(n.scrollLeft=r)}}let Kf=null;function W7(s){if(s.setActive)return s.setActive();if(Kf)return s.focus(Kf);let e=vP(s);s.focus(Kf==null?{get preventScroll(){return Kf={preventScroll:!0},!0}}:void 0),Kf||(Kf=!1,yP(e,0))}function bP(s,e){let t,n=2e8,i,r=0,o=e.top,a=e.top,c,l;for(let u=s.firstChild,h=0;u;u=u.nextSibling,h++){let d;if(u.nodeType==1)d=u.getClientRects();else if(u.nodeType==3)d=El(u).getClientRects();else continue;for(let p=0;p<d.length;p++){let m=d[p];if(m.top<=o&&m.bottom>=a){o=Math.max(m.bottom,o),a=Math.min(m.top,a);let v=m.left>e.left?m.left-e.left:m.right<e.left?e.left-m.right:0;if(v<n){t=u,n=v,i=v&&t.nodeType==3?{left:m.right<e.left?m.right:m.left,top:e.top}:e,u.nodeType==1&&v&&(r=h+(e.left>=(m.left+m.right)/2?1:0));continue}}else m.top>e.top&&!c&&m.left<=e.left&&m.right>=e.left&&(c=u,l={left:Math.max(m.left,Math.min(m.right,e.left)),top:m.top});!t&&(e.left>=m.right&&e.top>=m.top||e.left>=m.left&&e.top>=m.bottom)&&(r=h+1)}}return!t&&c&&(t=c,i=l,n=0),t&&t.nodeType==3?z7(t,i):!t||n&&t.nodeType==1?{node:s,offset:r}:bP(t,i)}function z7(s,e){let t=s.nodeValue.length,n=document.createRange(),i;for(let r=0;r<t;r++){n.setEnd(s,r+1),n.setStart(s,r);let o=Vc(n,1);if(o.top!=o.bottom&&AE(e,o)){i={node:s,offset:r+(e.left>=(o.left+o.right)/2?1:0)};break}}return n.detach(),i||{node:s,offset:0}}function AE(s,e){return s.left>=e.left-1&&s.left<=e.right+1&&s.top>=e.top-1&&s.top<=e.bottom+1}function j7(s,e){let t=s.parentNode;return t&&/^li$/i.test(t.nodeName)&&e.left<s.getBoundingClientRect().left?t:s}function V7(s,e,t){let{node:n,offset:i}=bP(e,t),r=-1;if(n.nodeType==1&&!n.firstChild){let o=n.getBoundingClientRect();r=o.left!=o.right&&t.left>(o.left+o.right)/2?1:-1}return s.docView.posFromDOM(n,i,r)}function G7(s,e,t,n){let i=-1;for(let r=e,o=!1;r!=s.dom;){let a=s.docView.nearestDesc(r,!0),c;if(!a)return null;if(a.dom.nodeType==1&&(a.node.isBlock&&a.parent||!a.contentDOM)&&((c=a.dom.getBoundingClientRect()).width||c.height)&&(a.node.isBlock&&a.parent&&!/^T(R|BODY|HEAD|FOOT)$/.test(a.dom.nodeName)&&(!o&&c.left>n.left||c.top>n.top?i=a.posBefore:(!o&&c.right<n.left||c.bottom<n.top)&&(i=a.posAfter),o=!0),!a.contentDOM&&i<0&&!a.node.isText))return(a.node.isBlock?n.top<(c.top+c.bottom)/2:n.left<(c.left+c.right)/2)?a.posBefore:a.posAfter;r=a.dom.parentNode}return i>-1?i:s.docView.posFromDOM(e,t,-1)}function _P(s,e,t){let n=s.childNodes.length;if(n&&t.top<t.bottom)for(let i=Math.max(0,Math.min(n-1,Math.floor(n*(e.top-t.top)/(t.bottom-t.top))-2)),r=i;;){let o=s.childNodes[r];if(o.nodeType==1){let a=o.getClientRects();for(let c=0;c<a.length;c++){let l=a[c];if(AE(e,l))return _P(o,e,l)}}if((r=(r+1)%n)==i)break}return s}function q7(s,e){let t=s.dom.ownerDocument,n,i=0,r=N7(t,e.left,e.top);r&&({node:n,offset:i}=r);let o=(s.root.elementFromPoint?s.root:t).elementFromPoint(e.left,e.top),a;if(!o||!s.dom.contains(o.nodeType!=1?o.parentNode:o)){let l=s.dom.getBoundingClientRect();if(!AE(e,l)||(o=_P(s.dom,e,l),!o))return null}if(Li)for(let l=o;n&&l;l=em(l))l.draggable&&(n=void 0);if(o=j7(o,e),n){if(Po&&n.nodeType==1&&(i=Math.min(i,n.childNodes.length),i<n.childNodes.length)){let u=n.childNodes[i],h;u.nodeName=="IMG"&&(h=u.getBoundingClientRect()).right<=e.left&&h.bottom>e.top&&i++}let l;e_&&i&&n.nodeType==1&&(l=n.childNodes[i-1]).nodeType==1&&l.contentEditable=="false"&&l.getBoundingClientRect().top>=e.top&&i--,n==s.dom&&i==n.childNodes.length-1&&n.lastChild.nodeType==1&&e.top>n.lastChild.getBoundingClientRect().bottom?a=s.state.doc.content.size:(i==0||n.nodeType!=1||n.childNodes[i-1].nodeName!="BR")&&(a=G7(s,n,i,e))}a==null&&(a=V7(s,o,e));let c=s.docView.nearestDesc(o,!0);return{pos:a,inside:c?c.posAtStart-c.border:-1}}function Ex(s){return s.top<s.bottom||s.left<s.right}function Vc(s,e){let t=s.getClientRects();if(t.length){let n=t[e<0?0:t.length-1];if(Ex(n))return n}return Array.prototype.find.call(t,Ex)||s.getBoundingClientRect()}const K7=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;function SP(s,e,t){let{node:n,offset:i,atom:r}=s.docView.domFromPos(e,t<0?-1:1),o=e_||Po;if(n.nodeType==3)if(o&&(K7.test(n.nodeValue)||(t<0?!i:i==n.nodeValue.length))){let c=Vc(El(n,i,i),t);if(Po&&i&&/\s/.test(n.nodeValue[i-1])&&i<n.nodeValue.length){let l=Vc(El(n,i-1,i-1),-1);if(l.top==c.top){let u=Vc(El(n,i,i+1),-1);if(u.top!=c.top)return _m(u,u.left<l.left)}}return c}else{let c=i,l=i,u=t<0?1:-1;return t<0&&!i?(l++,u=-1):t>=0&&i==n.nodeValue.length?(c--,u=1):t<0?c--:l++,_m(Vc(El(n,c,l),u),u<0)}if(!s.state.doc.resolve(e-(r||0)).parent.inlineContent){if(r==null&&i&&(t<0||i==Ro(n))){let c=n.childNodes[i-1];if(c.nodeType==1)return fC(c.getBoundingClientRect(),!1)}if(r==null&&i<Ro(n)){let c=n.childNodes[i];if(c.nodeType==1)return fC(c.getBoundingClientRect(),!0)}return fC(n.getBoundingClientRect(),t>=0)}if(r==null&&i&&(t<0||i==Ro(n))){let c=n.childNodes[i-1],l=c.nodeType==3?El(c,Ro(c)-(o?0:1)):c.nodeType==1&&(c.nodeName!="BR"||!c.nextSibling)?c:null;if(l)return _m(Vc(l,1),!1)}if(r==null&&i<Ro(n)){let c=n.childNodes[i];for(;c.pmViewDesc&&c.pmViewDesc.ignoreForCoords;)c=c.nextSibling;let l=c?c.nodeType==3?El(c,0,o?0:1):c.nodeType==1?c:null:null;if(l)return _m(Vc(l,-1),!0)}return _m(Vc(n.nodeType==3?El(n):n,-t),t>=0)}function _m(s,e){if(s.width==0)return s;let t=e?s.left:s.right;return{top:s.top,bottom:s.bottom,left:t,right:t}}function fC(s,e){if(s.height==0)return s;let t=e?s.top:s.bottom;return{top:t,bottom:t,left:s.left,right:s.right}}function wP(s,e,t){let n=s.state,i=s.root.activeElement;n!=e&&s.updateState(e),i!=s.dom&&s.focus();try{return t()}finally{n!=e&&s.updateState(n),i!=s.dom&&i&&i.focus()}}function Q7(s,e,t){let n=e.selection,i=t=="up"?n.$from:n.$to;return wP(s,e,()=>{let{node:r}=s.docView.domFromPos(i.pos,t=="up"?-1:1);for(;;){let a=s.docView.nearestDesc(r,!0);if(!a)break;if(a.node.isBlock){r=a.contentDOM||a.dom;break}r=a.dom.parentNode}let o=SP(s,i.pos,1);for(let a=r.firstChild;a;a=a.nextSibling){let c;if(a.nodeType==1)c=a.getClientRects();else if(a.nodeType==3)c=El(a,0,a.nodeValue.length).getClientRects();else continue;for(let l=0;l<c.length;l++){let u=c[l];if(u.bottom>u.top+1&&(t=="up"?o.top-u.top>(u.bottom-o.top)*2:u.bottom-o.bottom>(o.bottom-u.top)*2))return!1}}return!0})}const X7=/[\u0590-\u08ac]/;function Y7(s,e,t){let{$head:n}=e.selection;if(!n.parent.isTextblock)return!1;let i=n.parentOffset,r=!i,o=i==n.parent.content.size,a=s.domSelection();return a?!X7.test(n.parent.textContent)||!a.modify?t=="left"||t=="backward"?r:o:wP(s,e,()=>{let{focusNode:c,focusOffset:l,anchorNode:u,anchorOffset:h}=s.domSelectionRange(),d=a.caretBidiLevel;a.modify("move",t,"character");let p=n.depth?s.docView.domAfterPos(n.before()):s.dom,{focusNode:m,focusOffset:v}=s.domSelectionRange(),g=m&&!p.contains(m.nodeType==1?m:m.parentNode)||c==m&&l==v;try{a.collapse(u,h),c&&(c!=u||l!=h)&&a.extend&&a.extend(c,l)}catch{}return d!=null&&(a.caretBidiLevel=d),g}):n.pos==n.start()||n.pos==n.end()}let Mx=null,xx=null,Ix=!1;function J7(s,e,t){return Mx==e&&xx==t?Ix:(Mx=e,xx=t,Ix=t=="up"||t=="down"?Q7(s,e,t):Y7(s,e,t))}const Oo=0,Rx=1,Nh=2,al=3;class t_{constructor(e,t,n,i){this.parent=e,this.children=t,this.dom=n,this.contentDOM=i,this.dirty=Oo,n.pmViewDesc=this}matchesWidget(e){return!1}matchesMark(e){return!1}matchesNode(e,t,n){return!1}matchesHack(e){return!1}parseRule(){return null}stopEvent(e){return!1}get size(){let e=0;for(let t=0;t<this.children.length;t++)e+=this.children[t].size;return e}get border(){return 0}destroy(){this.parent=void 0,this.dom.pmViewDesc==this&&(this.dom.pmViewDesc=void 0);for(let e=0;e<this.children.length;e++)this.children[e].destroy()}posBeforeChild(e){for(let t=0,n=this.posAtStart;;t++){let i=this.children[t];if(i==e)return n;n+=i.size}}get posBefore(){return this.parent.posBeforeChild(this)}get posAtStart(){return this.parent?this.parent.posBeforeChild(this)+this.border:0}get posAfter(){return this.posBefore+this.size}get posAtEnd(){return this.posAtStart+this.size-2*this.border}localPosFromDOM(e,t,n){if(this.contentDOM&&this.contentDOM.contains(e.nodeType==1?e:e.parentNode))if(n<0){let r,o;if(e==this.contentDOM)r=e.childNodes[t-1];else{for(;e.parentNode!=this.contentDOM;)e=e.parentNode;r=e.previousSibling}for(;r&&!((o=r.pmViewDesc)&&o.parent==this);)r=r.previousSibling;return r?this.posBeforeChild(o)+o.size:this.posAtStart}else{let r,o;if(e==this.contentDOM)r=e.childNodes[t];else{for(;e.parentNode!=this.contentDOM;)e=e.parentNode;r=e.nextSibling}for(;r&&!((o=r.pmViewDesc)&&o.parent==this);)r=r.nextSibling;return r?this.posBeforeChild(o):this.posAtEnd}let i;if(e==this.dom&&this.contentDOM)i=t>fi(this.contentDOM);else if(this.contentDOM&&this.contentDOM!=this.dom&&this.dom.contains(this.contentDOM))i=e.compareDocumentPosition(this.contentDOM)&2;else if(this.dom.firstChild){if(t==0)for(let r=e;;r=r.parentNode){if(r==this.dom){i=!1;break}if(r.previousSibling)break}if(i==null&&t==e.childNodes.length)for(let r=e;;r=r.parentNode){if(r==this.dom){i=!0;break}if(r.nextSibling)break}}return i??n>0?this.posAtEnd:this.posAtStart}nearestDesc(e,t=!1){for(let n=!0,i=e;i;i=i.parentNode){let r=this.getDesc(i),o;if(r&&(!t||r.node))if(n&&(o=r.nodeDOM)&&!(o.nodeType==1?o.contains(e.nodeType==1?e:e.parentNode):o==e))n=!1;else return r}}getDesc(e){let t=e.pmViewDesc;for(let n=t;n;n=n.parent)if(n==this)return t}posFromDOM(e,t,n){for(let i=e;i;i=i.parentNode){let r=this.getDesc(i);if(r)return r.localPosFromDOM(e,t,n)}return-1}descAt(e){for(let t=0,n=0;t<this.children.length;t++){let i=this.children[t],r=n+i.size;if(n==e&&r!=n){for(;!i.border&&i.children.length;)for(let o=0;o<i.children.length;o++){let a=i.children[o];if(a.size){i=a;break}}return i}if(e<r)return i.descAt(e-n-i.border);n=r}}domFromPos(e,t){if(!this.contentDOM)return{node:this.dom,offset:0,atom:e+1};let n=0,i=0;for(let r=0;n<this.children.length;n++){let o=this.children[n],a=r+o.size;if(a>e||o instanceof CP){i=e-r;break}r=a}if(i)return this.children[n].domFromPos(i-this.children[n].border,t);for(let r;n&&!(r=this.children[n-1]).size&&r instanceof kP&&r.side>=0;n--);if(t<=0){let r,o=!0;for(;r=n?this.children[n-1]:null,!(!r||r.dom.parentNode==this.contentDOM);n--,o=!1);return r&&t&&o&&!r.border&&!r.domAtom?r.domFromPos(r.size,t):{node:this.contentDOM,offset:r?fi(r.dom)+1:0}}else{let r,o=!0;for(;r=n<this.children.length?this.children[n]:null,!(!r||r.dom.parentNode==this.contentDOM);n++,o=!1);return r&&o&&!r.border&&!r.domAtom?r.domFromPos(0,t):{node:this.contentDOM,offset:r?fi(r.dom):this.contentDOM.childNodes.length}}}parseRange(e,t,n=0){if(this.children.length==0)return{node:this.contentDOM,from:e,to:t,fromOffset:0,toOffset:this.contentDOM.childNodes.length};let i=-1,r=-1;for(let o=n,a=0;;a++){let c=this.children[a],l=o+c.size;if(i==-1&&e<=l){let u=o+c.border;if(e>=u&&t<=l-c.border&&c.node&&c.contentDOM&&this.contentDOM.contains(c.contentDOM))return c.parseRange(e,t,u);e=o;for(let h=a;h>0;h--){let d=this.children[h-1];if(d.size&&d.dom.parentNode==this.contentDOM&&!d.emptyChildAt(1)){i=fi(d.dom)+1;break}e-=d.size}i==-1&&(i=0)}if(i>-1&&(l>t||a==this.children.length-1)){t=l;for(let u=a+1;u<this.children.length;u++){let h=this.children[u];if(h.size&&h.dom.parentNode==this.contentDOM&&!h.emptyChildAt(-1)){r=fi(h.dom);break}t+=h.size}r==-1&&(r=this.contentDOM.childNodes.length);break}o=l}return{node:this.contentDOM,from:e,to:t,fromOffset:i,toOffset:r}}emptyChildAt(e){if(this.border||!this.contentDOM||!this.children.length)return!1;let t=this.children[e<0?0:this.children.length-1];return t.size==0||t.emptyChildAt(e)}domAfterPos(e){let{node:t,offset:n}=this.domFromPos(e,0);if(t.nodeType!=1||n==t.childNodes.length)throw new RangeError("No node after pos "+e);return t.childNodes[n]}setSelection(e,t,n,i=!1){let r=Math.min(e,t),o=Math.max(e,t);for(let p=0,m=0;p<this.children.length;p++){let v=this.children[p],g=m+v.size;if(r>m&&o<g)return v.setSelection(e-m-v.border,t-m-v.border,n,i);m=g}let a=this.domFromPos(e,e?-1:1),c=t==e?a:this.domFromPos(t,t?-1:1),l=n.root.getSelection(),u=n.domSelectionRange(),h=!1;if((Po||Li)&&e==t){let{node:p,offset:m}=a;if(p.nodeType==3){if(h=!!(m&&p.nodeValue[m-1]==`
`),h&&m==p.nodeValue.length)for(let v=p,g;v;v=v.parentNode){if(g=v.nextSibling){g.nodeName=="BR"&&(a=c={node:g.parentNode,offset:fi(g)+1});break}let y=v.pmViewDesc;if(y&&y.node&&y.node.isBlock)break}}else{let v=p.childNodes[m-1];h=v&&(v.nodeName=="BR"||v.contentEditable=="false")}}if(Po&&u.focusNode&&u.focusNode!=c.node&&u.focusNode.nodeType==1){let p=u.focusNode.childNodes[u.focusOffset];p&&p.contentEditable=="false"&&(i=!0)}if(!(i||h&&Li)&&Ef(a.node,a.offset,u.anchorNode,u.anchorOffset)&&Ef(c.node,c.offset,u.focusNode,u.focusOffset))return;let d=!1;if((l.extend||e==t)&&!(h&&Po)){l.collapse(a.node,a.offset);try{e!=t&&l.extend(c.node,c.offset),d=!0}catch{}}if(!d){if(e>t){let m=a;a=c,c=m}let p=document.createRange();p.setEnd(c.node,c.offset),p.setStart(a.node,a.offset),l.removeAllRanges(),l.addRange(p)}}ignoreMutation(e){return!this.contentDOM&&e.type!="selection"}get contentLost(){return this.contentDOM&&this.contentDOM!=this.dom&&!this.dom.contains(this.contentDOM)}markDirty(e,t){for(let n=0,i=0;i<this.children.length;i++){let r=this.children[i],o=n+r.size;if(n==o?e<=o&&t>=n:e<o&&t>n){let a=n+r.border,c=o-r.border;if(e>=a&&t<=c){this.dirty=e==n||t==o?Nh:Rx,e==a&&t==c&&(r.contentLost||r.dom.parentNode!=this.contentDOM)?r.dirty=al:r.markDirty(e-a,t-a);return}else r.dirty=r.dom==r.contentDOM&&r.dom.parentNode==this.contentDOM&&!r.children.length?Nh:al}n=o}this.dirty=Nh}markParentsDirty(){let e=1;for(let t=this.parent;t;t=t.parent,e++){let n=e==1?Nh:Rx;t.dirty<n&&(t.dirty=n)}}get domAtom(){return!1}get ignoreForCoords(){return!1}get ignoreForSelection(){return!1}isText(e){return!1}}class kP extends t_{constructor(e,t,n,i){let r,o=t.type.toDOM;if(typeof o=="function"&&(o=o(n,()=>{if(!r)return i;if(r.parent)return r.parent.posBeforeChild(r)})),!t.type.spec.raw){if(o.nodeType!=1){let a=document.createElement("span");a.appendChild(o),o=a}o.contentEditable="false",o.classList.add("ProseMirror-widget")}super(e,[],o,null),this.widget=t,this.widget=t,r=this}matchesWidget(e){return this.dirty==Oo&&e.type.eq(this.widget.type)}parseRule(){return{ignore:!0}}stopEvent(e){let t=this.widget.spec.stopEvent;return t?t(e):!1}ignoreMutation(e){return e.type!="selection"||this.widget.spec.ignoreSelection}destroy(){this.widget.type.destroy(this.dom),super.destroy()}get domAtom(){return!0}get ignoreForSelection(){return!!this.widget.type.spec.relaxedSide}get side(){return this.widget.type.side}}class Z7 extends t_{constructor(e,t,n,i){super(e,[],t,null),this.textDOM=n,this.text=i}get size(){return this.text.length}localPosFromDOM(e,t){return e!=this.textDOM?this.posAtStart+(t?this.size:0):this.posAtStart+t}domFromPos(e){return{node:this.textDOM,offset:e}}ignoreMutation(e){return e.type==="characterData"&&e.target.nodeValue==e.oldValue}}class Mf extends t_{constructor(e,t,n,i,r){super(e,[],n,i),this.mark=t,this.spec=r}static create(e,t,n,i){let r=i.nodeViews[t.type.name],o=r&&r(t,i,n);return(!o||!o.dom)&&(o=Of.renderSpec(document,t.type.spec.toDOM(t,n),null,t.attrs)),new Mf(e,t,o.dom,o.contentDOM||o.dom,o)}parseRule(){return this.dirty&al||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(e){return this.dirty!=al&&this.mark.eq(e)}markDirty(e,t){if(super.markDirty(e,t),this.dirty!=Oo){let n=this.parent;for(;!n.node;)n=n.parent;n.dirty<this.dirty&&(n.dirty=this.dirty),this.dirty=Oo}}slice(e,t,n){let i=Mf.create(this.parent,this.mark,!0,n),r=this.children,o=this.size;t<o&&(r=W1(r,t,o,n)),e>0&&(r=W1(r,0,e,n));for(let a=0;a<r.length;a++)r[a].parent=i;return i.children=r,i}ignoreMutation(e){return this.spec.ignoreMutation?this.spec.ignoreMutation(e):super.ignoreMutation(e)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}}class ih extends t_{constructor(e,t,n,i,r,o,a,c,l){super(e,[],r,o),this.node=t,this.outerDeco=n,this.innerDeco=i,this.nodeDOM=a}static create(e,t,n,i,r,o){let a=r.nodeViews[t.type.name],c,l=a&&a(t,r,()=>{if(!c)return o;if(c.parent)return c.parent.posBeforeChild(c)},n,i),u=l&&l.dom,h=l&&l.contentDOM;if(t.isText){if(!u)u=document.createTextNode(t.text);else if(u.nodeType!=3)throw new RangeError("Text must be rendered as a DOM text node")}else u||({dom:u,contentDOM:h}=Of.renderSpec(document,t.type.spec.toDOM(t),null,t.attrs));!h&&!t.isText&&u.nodeName!="BR"&&(u.hasAttribute("contenteditable")||(u.contentEditable="false"),t.type.spec.draggable&&(u.draggable=!0));let d=u;return u=EP(u,n,t),l?c=new eV(e,t,n,i,u,h||null,d,l,r,o+1):t.isText?new ek(e,t,n,i,u,d,r):new ih(e,t,n,i,u,h||null,d,r,o+1)}parseRule(){if(this.node.type.spec.reparseInView)return null;let e={node:this.node.type.name,attrs:this.node.attrs};if(this.node.type.whitespace=="pre"&&(e.preserveWhitespace="full"),!this.contentDOM)e.getContent=()=>this.node.content;else if(!this.contentLost)e.contentElement=this.contentDOM;else{for(let t=this.children.length-1;t>=0;t--){let n=this.children[t];if(this.dom.contains(n.dom.parentNode)){e.contentElement=n.dom.parentNode;break}}e.contentElement||(e.getContent=()=>Fe.empty)}return e}matchesNode(e,t,n){return this.dirty==Oo&&e.eq(this.node)&&Cw(t,this.outerDeco)&&n.eq(this.innerDeco)}get size(){return this.node.nodeSize}get border(){return this.node.isLeaf?0:1}updateChildren(e,t){let n=this.node.inlineContent,i=t,r=e.composing?this.localCompositionInfo(e,t):null,o=r&&r.pos>-1?r:null,a=r&&r.pos<0,c=new sV(this,o&&o.node,e);rV(this.node,this.innerDeco,(l,u,h)=>{l.spec.marks?c.syncToMarks(l.spec.marks,n,e,u):l.type.side>=0&&!h&&c.syncToMarks(u==this.node.childCount?_s.none:this.node.child(u).marks,n,e,u),c.placeWidget(l,e,i)},(l,u,h,d)=>{c.syncToMarks(l.marks,n,e,d);let p;c.findNodeMatch(l,u,h,d)||a&&e.state.selection.from>i&&e.state.selection.to<i+l.nodeSize&&(p=c.findIndexWithChild(r.node))>-1&&c.updateNodeAt(l,u,h,p,e)||c.updateNextNode(l,u,h,e,d,i)||c.addNode(l,u,h,e,i),i+=l.nodeSize}),c.syncToMarks([],n,e,0),this.node.isTextblock&&c.addTextblockHacks(),c.destroyRest(),(c.changed||this.dirty==Nh)&&(o&&this.protectLocalComposition(e,o),TP(this.contentDOM,this.children,e),tm&&oV(this.dom))}localCompositionInfo(e,t){let{from:n,to:i}=e.state.selection;if(!(e.state.selection instanceof _t)||n<t||i>t+this.node.content.size)return null;let r=e.input.compositionNode;if(!r||!this.dom.contains(r.parentNode))return null;if(this.node.inlineContent){let o=r.nodeValue,a=aV(this.node.content,o,n-t,i-t);return a<0?null:{node:r,pos:a,text:o}}else return{node:r,pos:-1,text:""}}protectLocalComposition(e,{node:t,pos:n,text:i}){if(this.getDesc(t))return;let r=t;for(;r.parentNode!=this.contentDOM;r=r.parentNode){for(;r.previousSibling;)r.parentNode.removeChild(r.previousSibling);for(;r.nextSibling;)r.parentNode.removeChild(r.nextSibling);r.pmViewDesc&&(r.pmViewDesc=void 0)}let o=new Z7(this,r,t,i);e.input.compositionNodes.push(o),this.children=W1(this.children,n,n+i.length,e,o)}update(e,t,n,i){return this.dirty==al||!e.sameMarkup(this.node)?!1:(this.updateInner(e,t,n,i),!0)}updateInner(e,t,n,i){this.updateOuterDeco(t),this.node=e,this.innerDeco=n,this.contentDOM&&this.updateChildren(i,this.posAtStart),this.dirty=Oo}updateOuterDeco(e){if(Cw(e,this.outerDeco))return;let t=this.nodeDOM.nodeType!=1,n=this.dom;this.dom=AP(this.dom,this.nodeDOM,U1(this.outerDeco,this.node,t),U1(e,this.node,t)),this.dom!=n&&(n.pmViewDesc=void 0,this.dom.pmViewDesc=this),this.outerDeco=e}selectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.add("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&(this.nodeDOM.draggable=!0))}deselectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.remove("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&this.nodeDOM.removeAttribute("draggable"))}get domAtom(){return this.node.isAtom}}function Lx(s,e,t,n,i){EP(n,e,s);let r=new ih(void 0,s,e,t,n,n,n,i,0);return r.contentDOM&&r.updateChildren(i,0),r}class ek extends ih{constructor(e,t,n,i,r,o,a){super(e,t,n,i,r,null,o,a,0)}parseRule(){let e=this.nodeDOM.parentNode;for(;e&&e!=this.dom&&!e.pmIsDeco;)e=e.parentNode;return{skip:e||!0}}update(e,t,n,i){return this.dirty==al||this.dirty!=Oo&&!this.inParent()||!e.sameMarkup(this.node)?!1:(this.updateOuterDeco(t),(this.dirty!=Oo||e.text!=this.node.text)&&e.text!=this.nodeDOM.nodeValue&&(this.nodeDOM.nodeValue=e.text,i.trackWrites==this.nodeDOM&&(i.trackWrites=null)),this.node=e,this.dirty=Oo,!0)}inParent(){let e=this.parent.contentDOM;for(let t=this.nodeDOM;t;t=t.parentNode)if(t==e)return!0;return!1}domFromPos(e){return{node:this.nodeDOM,offset:e}}localPosFromDOM(e,t,n){return e==this.nodeDOM?this.posAtStart+Math.min(t,this.node.text.length):super.localPosFromDOM(e,t,n)}ignoreMutation(e){return e.type!="characterData"&&e.type!="selection"}slice(e,t,n){let i=this.node.cut(e,t),r=document.createTextNode(i.text);return new ek(this.parent,i,this.outerDeco,this.innerDeco,r,r,n)}markDirty(e,t){super.markDirty(e,t),this.dom!=this.nodeDOM&&(e==0||t==this.nodeDOM.nodeValue.length)&&(this.dirty=al)}get domAtom(){return!1}isText(e){return this.node.text==e}}class CP extends t_{parseRule(){return{ignore:!0}}matchesHack(e){return this.dirty==Oo&&this.dom.nodeName==e}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class eV extends ih{constructor(e,t,n,i,r,o,a,c,l,u){super(e,t,n,i,r,o,a,l,u),this.spec=c}update(e,t,n,i){if(this.dirty==al)return!1;if(this.spec.update&&(this.node.type==e.type||this.spec.multiType)){let r=this.spec.update(e,t,n);return r&&this.updateInner(e,t,n,i),r}else return!this.contentDOM&&!e.isLeaf?!1:super.update(e,t,n,i)}selectNode(){this.spec.selectNode?this.spec.selectNode():super.selectNode()}deselectNode(){this.spec.deselectNode?this.spec.deselectNode():super.deselectNode()}setSelection(e,t,n,i){this.spec.setSelection?this.spec.setSelection(e,t,n.root):super.setSelection(e,t,n,i)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}stopEvent(e){return this.spec.stopEvent?this.spec.stopEvent(e):!1}ignoreMutation(e){return this.spec.ignoreMutation?this.spec.ignoreMutation(e):super.ignoreMutation(e)}}function TP(s,e,t){let n=s.firstChild,i=!1;for(let r=0;r<e.length;r++){let o=e[r],a=o.dom;if(a.parentNode==s){for(;a!=n;)n=Px(n),i=!0;n=n.nextSibling}else i=!0,s.insertBefore(a,n);if(o instanceof Mf){let c=n?n.previousSibling:s.lastChild;TP(o.contentDOM,o.children,t),n=c?c.nextSibling:s.firstChild}}for(;n;)n=Px(n),i=!0;i&&t.trackWrites==s&&(t.trackWrites=null)}const Mv=function(s){s&&(this.nodeName=s)};Mv.prototype=Object.create(null);const Bh=[new Mv];function U1(s,e,t){if(s.length==0)return Bh;let n=t?Bh[0]:new Mv,i=[n];for(let r=0;r<s.length;r++){let o=s[r].type.attrs;if(o){o.nodeName&&i.push(n=new Mv(o.nodeName));for(let a in o){let c=o[a];c!=null&&(t&&i.length==1&&i.push(n=new Mv(e.isInline?"span":"div")),a=="class"?n.class=(n.class?n.class+" ":"")+c:a=="style"?n.style=(n.style?n.style+";":"")+c:a!="nodeName"&&(n[a]=c))}}}return i}function AP(s,e,t,n){if(t==Bh&&n==Bh)return e;let i=e;for(let r=0;r<n.length;r++){let o=n[r],a=t[r];if(r){let c;a&&a.nodeName==o.nodeName&&i!=s&&(c=i.parentNode)&&c.nodeName.toLowerCase()==o.nodeName||(c=document.createElement(o.nodeName),c.pmIsDeco=!0,c.appendChild(i),a=Bh[0]),i=c}tV(i,a||Bh[0],o)}return i}function tV(s,e,t){for(let n in e)n!="class"&&n!="style"&&n!="nodeName"&&!(n in t)&&s.removeAttribute(n);for(let n in t)n!="class"&&n!="style"&&n!="nodeName"&&t[n]!=e[n]&&s.setAttribute(n,t[n]);if(e.class!=t.class){let n=e.class?e.class.split(" ").filter(Boolean):[],i=t.class?t.class.split(" ").filter(Boolean):[];for(let r=0;r<n.length;r++)i.indexOf(n[r])==-1&&s.classList.remove(n[r]);for(let r=0;r<i.length;r++)n.indexOf(i[r])==-1&&s.classList.add(i[r]);s.classList.length==0&&s.removeAttribute("class")}if(e.style!=t.style){if(e.style){let n=/\s*([\w\-\xa1-\uffff]+)\s*:(?:"(?:\\.|[^"])*"|'(?:\\.|[^'])*'|\(.*?\)|[^;])*/g,i;for(;i=n.exec(e.style);)s.style.removeProperty(i[1])}t.style&&(s.style.cssText+=t.style)}}function EP(s,e,t){return AP(s,s,Bh,U1(e,t,s.nodeType!=1))}function Cw(s,e){if(s.length!=e.length)return!1;for(let t=0;t<s.length;t++)if(!s[t].type.eq(e[t].type))return!1;return!0}function Px(s){let e=s.nextSibling;return s.parentNode.removeChild(s),e}class sV{constructor(e,t,n){this.lock=t,this.view=n,this.index=0,this.stack=[],this.changed=!1,this.top=e,this.preMatch=nV(e.node.content,e)}destroyBetween(e,t){if(e!=t){for(let n=e;n<t;n++)this.top.children[n].destroy();this.top.children.splice(e,t-e),this.changed=!0}}destroyRest(){this.destroyBetween(this.index,this.top.children.length)}syncToMarks(e,t,n,i){let r=0,o=this.stack.length>>1,a=Math.min(o,e.length);for(;r<a&&(r==o-1?this.top:this.stack[r+1<<1]).matchesMark(e[r])&&e[r].type.spec.spanning!==!1;)r++;for(;r<o;)this.destroyRest(),this.top.dirty=Oo,this.index=this.stack.pop(),this.top=this.stack.pop(),o--;for(;o<e.length;){this.stack.push(this.top,this.index+1);let c=-1,l=this.top.children.length;i<this.preMatch.index&&(l=Math.min(this.index+3,l));for(let u=this.index;u<l;u++){let h=this.top.children[u];if(h.matchesMark(e[o])&&!this.isLocked(h.dom)){c=u;break}}if(c>-1)c>this.index&&(this.changed=!0,this.destroyBetween(this.index,c)),this.top=this.top.children[this.index];else{let u=Mf.create(this.top,e[o],t,n);this.top.children.splice(this.index,0,u),this.top=u,this.changed=!0}this.index=0,o++}}findNodeMatch(e,t,n,i){let r=-1,o;if(i>=this.preMatch.index&&(o=this.preMatch.matches[i-this.preMatch.index]).parent==this.top&&o.matchesNode(e,t,n))r=this.top.children.indexOf(o,this.index);else for(let a=this.index,c=Math.min(this.top.children.length,a+5);a<c;a++){let l=this.top.children[a];if(l.matchesNode(e,t,n)&&!this.preMatch.matched.has(l)){r=a;break}}return r<0?!1:(this.destroyBetween(this.index,r),this.index++,!0)}updateNodeAt(e,t,n,i,r){let o=this.top.children[i];return o.dirty==al&&o.dom==o.contentDOM&&(o.dirty=Nh),o.update(e,t,n,r)?(this.destroyBetween(this.index,i),this.index++,!0):!1}findIndexWithChild(e){for(;;){let t=e.parentNode;if(!t)return-1;if(t==this.top.contentDOM){let n=e.pmViewDesc;if(n){for(let i=this.index;i<this.top.children.length;i++)if(this.top.children[i]==n)return i}return-1}e=t}}updateNextNode(e,t,n,i,r,o){for(let a=this.index;a<this.top.children.length;a++){let c=this.top.children[a];if(c instanceof ih){let l=this.preMatch.matched.get(c);if(l!=null&&l!=r)return!1;let u=c.dom,h,d=this.isLocked(u)&&!(e.isText&&c.node&&c.node.isText&&c.nodeDOM.nodeValue==e.text&&c.dirty!=al&&Cw(t,c.outerDeco));if(!d&&c.update(e,t,n,i))return this.destroyBetween(this.index,a),c.dom!=u&&(this.changed=!0),this.index++,!0;if(!d&&(h=this.recreateWrapper(c,e,t,n,i,o)))return this.destroyBetween(this.index,a),this.top.children[this.index]=h,h.contentDOM&&(h.dirty=Nh,h.updateChildren(i,o+1),h.dirty=Oo),this.changed=!0,this.index++,!0;break}}return!1}recreateWrapper(e,t,n,i,r,o){if(e.dirty||t.isAtom||!e.children.length||!e.node.content.eq(t.content)||!Cw(n,e.outerDeco)||!i.eq(e.innerDeco))return null;let a=ih.create(this.top,t,n,i,r,o);if(a.contentDOM){a.children=e.children,e.children=[];for(let c of a.children)c.parent=a}return e.destroy(),a}addNode(e,t,n,i,r){let o=ih.create(this.top,e,t,n,i,r);o.contentDOM&&o.updateChildren(i,r+1),this.top.children.splice(this.index++,0,o),this.changed=!0}placeWidget(e,t,n){let i=this.index<this.top.children.length?this.top.children[this.index]:null;if(i&&i.matchesWidget(e)&&(e==i.widget||!i.widget.type.toDOM.parentNode))this.index++;else{let r=new kP(this.top,e,t,n);this.top.children.splice(this.index++,0,r),this.changed=!0}}addTextblockHacks(){let e=this.top.children[this.index-1],t=this.top;for(;e instanceof Mf;)t=e,e=t.children[t.children.length-1];(!e||!(e instanceof ek)||/\n$/.test(e.node.text)||this.view.requiresGeckoHackNode&&/\s$/.test(e.node.text))&&((Li||vi)&&e&&e.dom.contentEditable=="false"&&this.addHackNode("IMG",t),this.addHackNode("BR",this.top))}addHackNode(e,t){if(t==this.top&&this.index<t.children.length&&t.children[this.index].matchesHack(e))this.index++;else{let n=document.createElement(e);e=="IMG"&&(n.className="ProseMirror-separator",n.alt=""),e=="BR"&&(n.className="ProseMirror-trailingBreak");let i=new CP(this.top,[],n,null);t!=this.top?t.children.push(i):t.children.splice(this.index++,0,i),this.changed=!0}}isLocked(e){return this.lock&&(e==this.lock||e.nodeType==1&&e.contains(this.lock.parentNode))}}function nV(s,e){let t=e,n=t.children.length,i=s.childCount,r=new Map,o=[];e:for(;i>0;){let a;for(;;)if(n){let l=t.children[n-1];if(l instanceof Mf)t=l,n=l.children.length;else{a=l,n--;break}}else{if(t==e)break e;n=t.parent.children.indexOf(t),t=t.parent}let c=a.node;if(c){if(c!=s.child(i-1))break;--i,r.set(a,i),o.push(a)}}return{index:i,matched:r,matches:o.reverse()}}function iV(s,e){return s.type.side-e.type.side}function rV(s,e,t,n){let i=e.locals(s),r=0;if(i.length==0){for(let l=0;l<s.childCount;l++){let u=s.child(l);n(u,i,e.forChild(r,u),l),r+=u.nodeSize}return}let o=0,a=[],c=null;for(let l=0;;){let u,h;for(;o<i.length&&i[o].to==r;){let g=i[o++];g.widget&&(u?(h||(h=[u])).push(g):u=g)}if(u)if(h){h.sort(iV);for(let g=0;g<h.length;g++)t(h[g],l,!!c)}else t(u,l,!!c);let d,p;if(c)p=-1,d=c,c=null;else if(l<s.childCount)p=l,d=s.child(l++);else break;for(let g=0;g<a.length;g++)a[g].to<=r&&a.splice(g--,1);for(;o<i.length&&i[o].from<=r&&i[o].to>r;)a.push(i[o++]);let m=r+d.nodeSize;if(d.isText){let g=m;o<i.length&&i[o].from<g&&(g=i[o].from);for(let y=0;y<a.length;y++)a[y].to<g&&(g=a[y].to);g<m&&(c=d.cut(g-r),d=d.cut(0,g-r),m=g,p=-1)}else for(;o<i.length&&i[o].to<m;)o++;let v=d.isInline&&!d.isLeaf?a.filter(g=>!g.inline):a.slice();n(d,v,e.forChild(r,d),p),r=m}}function oV(s){if(s.nodeName=="UL"||s.nodeName=="OL"){let e=s.style.cssText;s.style.cssText=e+"; list-style: square !important",window.getComputedStyle(s).listStyle,s.style.cssText=e}}function aV(s,e,t,n){for(let i=0,r=0;i<s.childCount&&r<=n;){let o=s.child(i++),a=r;if(r+=o.nodeSize,!o.isText)continue;let c=o.text;for(;i<s.childCount;){let l=s.child(i++);if(r+=l.nodeSize,!l.isText)break;c+=l.text}if(r>=t){if(r>=n&&c.slice(n-e.length-a,n-a)==e)return n-e.length;let l=a<n?c.lastIndexOf(e,n-a-1):-1;if(l>=0&&l+e.length+a>=t)return a+l;if(t==n&&c.length>=n+e.length-a&&c.slice(n-a,n-a+e.length)==e)return n}}return-1}function W1(s,e,t,n,i){let r=[];for(let o=0,a=0;o<s.length;o++){let c=s[o],l=a,u=a+=c.size;l>=t||u<=e?r.push(c):(l<e&&r.push(c.slice(0,e-l,n)),i&&(r.push(i),i=void 0),u>t&&r.push(c.slice(t-l,c.size,n)))}return r}function EE(s,e=null){let t=s.domSelectionRange(),n=s.state.doc;if(!t.focusNode)return null;let i=s.docView.nearestDesc(t.focusNode),r=i&&i.size==0,o=s.docView.posFromDOM(t.focusNode,t.focusOffset,1);if(o<0)return null;let a=n.resolve(o),c,l;if(Z0(t)){for(c=o;i&&!i.node;)i=i.parent;let h=i.node;if(i&&h.isAtom&&vt.isSelectable(h)&&i.parent&&!(h.isInline&&O7(t.focusNode,t.focusOffset,i.dom))){let d=i.posBefore;l=new vt(o==d?a:n.resolve(d))}}else{if(t instanceof s.dom.ownerDocument.defaultView.Selection&&t.rangeCount>1){let h=o,d=o;for(let p=0;p<t.rangeCount;p++){let m=t.getRangeAt(p);h=Math.min(h,s.docView.posFromDOM(m.startContainer,m.startOffset,1)),d=Math.max(d,s.docView.posFromDOM(m.endContainer,m.endOffset,-1))}if(h<0)return null;[c,o]=d==s.state.selection.anchor?[d,h]:[h,d],a=n.resolve(o)}else c=s.docView.posFromDOM(t.anchorNode,t.anchorOffset,1);if(c<0)return null}let u=n.resolve(c);if(!l){let h=e=="pointer"||s.state.selection.head<a.pos&&!r?1:-1;l=ME(s,u,a,h)}return l}function MP(s){return s.editable?s.hasFocus():IP(s)&&document.activeElement&&document.activeElement.contains(s.dom)}function Sc(s,e=!1){let t=s.state.selection;if(xP(s,t),!!MP(s)){if(!e&&s.input.mouseDown&&s.input.mouseDown.allowDefault&&vi){let n=s.domSelectionRange(),i=s.domObserver.currentSelection;if(n.anchorNode&&i.anchorNode&&Ef(n.anchorNode,n.anchorOffset,i.anchorNode,i.anchorOffset)){s.input.mouseDown.delayedSelectionSync=!0,s.domObserver.setCurSelection();return}}if(s.domObserver.disconnectSelection(),s.cursorWrapper)cV(s);else{let{anchor:n,head:i}=t,r,o;Ox&&!(t instanceof _t)&&(t.$from.parent.inlineContent||(r=Dx(s,t.from)),!t.empty&&!t.$from.parent.inlineContent&&(o=Dx(s,t.to))),s.docView.setSelection(n,i,s,e),Ox&&(r&&Nx(r),o&&Nx(o)),t.visible?s.dom.classList.remove("ProseMirror-hideselection"):(s.dom.classList.add("ProseMirror-hideselection"),"onselectionchange"in document&&lV(s))}s.domObserver.setCurSelection(),s.domObserver.connectSelection()}}const Ox=Li||vi&&gP<63;function Dx(s,e){let{node:t,offset:n}=s.docView.domFromPos(e,0),i=n<t.childNodes.length?t.childNodes[n]:null,r=n?t.childNodes[n-1]:null;if(Li&&i&&i.contentEditable=="false")return pC(i);if((!i||i.contentEditable=="false")&&(!r||r.contentEditable=="false")){if(i)return pC(i);if(r)return pC(r)}}function pC(s){return s.contentEditable="true",Li&&s.draggable&&(s.draggable=!1,s.wasDraggable=!0),s}function Nx(s){s.contentEditable="false",s.wasDraggable&&(s.draggable=!0,s.wasDraggable=null)}function lV(s){let e=s.dom.ownerDocument;e.removeEventListener("selectionchange",s.input.hideSelectionGuard);let t=s.domSelectionRange(),n=t.anchorNode,i=t.anchorOffset;e.addEventListener("selectionchange",s.input.hideSelectionGuard=()=>{(t.anchorNode!=n||t.anchorOffset!=i)&&(e.removeEventListener("selectionchange",s.input.hideSelectionGuard),setTimeout(()=>{(!MP(s)||s.state.selection.visible)&&s.dom.classList.remove("ProseMirror-hideselection")},20))})}function cV(s){let e=s.domSelection();if(!e)return;let t=s.cursorWrapper.dom,n=t.nodeName=="IMG";n?e.collapse(t.parentNode,fi(t)+1):e.collapse(t,0),!n&&!s.state.selection.visible&&yr&&nh<=11&&(t.disabled=!0,t.disabled=!1)}function xP(s,e){if(e instanceof vt){let t=s.docView.descAt(e.from);t!=s.lastSelectedViewDesc&&(Bx(s),t&&t.selectNode(),s.lastSelectedViewDesc=t)}else Bx(s)}function Bx(s){s.lastSelectedViewDesc&&(s.lastSelectedViewDesc.parent&&s.lastSelectedViewDesc.deselectNode(),s.lastSelectedViewDesc=void 0)}function ME(s,e,t,n){return s.someProp("createSelectionBetween",i=>i(s,e,t))||_t.between(e,t,n)}function Fx(s){return s.editable&&!s.hasFocus()?!1:IP(s)}function IP(s){let e=s.domSelectionRange();if(!e.anchorNode)return!1;try{return s.dom.contains(e.anchorNode.nodeType==3?e.anchorNode.parentNode:e.anchorNode)&&(s.editable||s.dom.contains(e.focusNode.nodeType==3?e.focusNode.parentNode:e.focusNode))}catch{return!1}}function uV(s){let e=s.docView.domFromPos(s.state.selection.anchor,0),t=s.domSelectionRange();return Ef(e.node,e.offset,t.anchorNode,t.anchorOffset)}function z1(s,e){let{$anchor:t,$head:n}=s.selection,i=e>0?t.max(n):t.min(n),r=i.parent.inlineContent?i.depth?s.doc.resolve(e>0?i.after():i.before()):null:i;return r&&Ft.findFrom(r,e)}function Qc(s,e){return s.dispatch(s.state.tr.setSelection(e).scrollIntoView()),!0}function $x(s,e,t){let n=s.state.selection;if(n instanceof _t)if(t.indexOf("s")>-1){let{$head:i}=n,r=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter;if(!r||r.isText||!r.isLeaf)return!1;let o=s.state.doc.resolve(i.pos+r.nodeSize*(e<0?-1:1));return Qc(s,new _t(n.$anchor,o))}else if(n.empty){if(s.endOfTextblock(e>0?"forward":"backward")){let i=z1(s.state,e);return i&&i instanceof vt?Qc(s,i):!1}else if(!(Mo&&t.indexOf("m")>-1)){let i=n.$head,r=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter,o;if(!r||r.isText)return!1;let a=e<0?i.pos-r.nodeSize:i.pos;return r.isAtom||(o=s.docView.descAt(a))&&!o.contentDOM?vt.isSelectable(r)?Qc(s,new vt(e<0?s.state.doc.resolve(i.pos-r.nodeSize):i)):e_?Qc(s,new _t(s.state.doc.resolve(e<0?a:a+r.nodeSize))):!1:!1}}else return!1;else{if(n instanceof vt&&n.node.isInline)return Qc(s,new _t(e>0?n.$to:n.$from));{let i=z1(s.state,e);return i?Qc(s,i):!1}}}function Tw(s){return s.nodeType==3?s.nodeValue.length:s.childNodes.length}function xv(s,e){let t=s.pmViewDesc;return t&&t.size==0&&(e<0||s.nextSibling||s.nodeName!="BR")}function Qf(s,e){return e<0?hV(s):dV(s)}function hV(s){let e=s.domSelectionRange(),t=e.focusNode,n=e.focusOffset;if(!t)return;let i,r,o=!1;for(Po&&t.nodeType==1&&n<Tw(t)&&xv(t.childNodes[n],-1)&&(o=!0);;)if(n>0){if(t.nodeType!=1)break;{let a=t.childNodes[n-1];if(xv(a,-1))i=t,r=--n;else if(a.nodeType==3)t=a,n=t.nodeValue.length;else break}}else{if(RP(t))break;{let a=t.previousSibling;for(;a&&xv(a,-1);)i=t.parentNode,r=fi(a),a=a.previousSibling;if(a)t=a,n=Tw(t);else{if(t=t.parentNode,t==s.dom)break;n=0}}}o?j1(s,t,n):i&&j1(s,i,r)}function dV(s){let e=s.domSelectionRange(),t=e.focusNode,n=e.focusOffset;if(!t)return;let i=Tw(t),r,o;for(;;)if(n<i){if(t.nodeType!=1)break;let a=t.childNodes[n];if(xv(a,1))r=t,o=++n;else break}else{if(RP(t))break;{let a=t.nextSibling;for(;a&&xv(a,1);)r=a.parentNode,o=fi(a)+1,a=a.nextSibling;if(a)t=a,n=0,i=Tw(t);else{if(t=t.parentNode,t==s.dom)break;n=i=0}}}r&&j1(s,r,o)}function RP(s){let e=s.pmViewDesc;return e&&e.node&&e.node.isBlock}function fV(s,e){for(;s&&e==s.childNodes.length&&!Zb(s);)e=fi(s)+1,s=s.parentNode;for(;s&&e<s.childNodes.length;){let t=s.childNodes[e];if(t.nodeType==3)return t;if(t.nodeType==1&&t.contentEditable=="false")break;s=t,e=0}}function pV(s,e){for(;s&&!e&&!Zb(s);)e=fi(s),s=s.parentNode;for(;s&&e;){let t=s.childNodes[e-1];if(t.nodeType==3)return t;if(t.nodeType==1&&t.contentEditable=="false")break;s=t,e=s.childNodes.length}}function j1(s,e,t){if(e.nodeType!=3){let r,o;(o=fV(e,t))?(e=o,t=0):(r=pV(e,t))&&(e=r,t=r.nodeValue.length)}let n=s.domSelection();if(!n)return;if(Z0(n)){let r=document.createRange();r.setEnd(e,t),r.setStart(e,t),n.removeAllRanges(),n.addRange(r)}else n.extend&&n.extend(e,t);s.domObserver.setCurSelection();let{state:i}=s;setTimeout(()=>{s.state==i&&Sc(s)},50)}function Hx(s,e){let t=s.state.doc.resolve(e);if(!(vi||mP)&&t.parent.inlineContent){let i=s.coordsAtPos(e);if(e>t.start()){let r=s.coordsAtPos(e-1),o=(r.top+r.bottom)/2;if(o>i.top&&o<i.bottom&&Math.abs(r.left-i.left)>1)return r.left<i.left?"ltr":"rtl"}if(e<t.end()){let r=s.coordsAtPos(e+1),o=(r.top+r.bottom)/2;if(o>i.top&&o<i.bottom&&Math.abs(r.left-i.left)>1)return r.left>i.left?"ltr":"rtl"}}return getComputedStyle(s.dom).direction=="rtl"?"rtl":"ltr"}function Ux(s,e,t){let n=s.state.selection;if(n instanceof _t&&!n.empty||t.indexOf("s")>-1||Mo&&t.indexOf("m")>-1)return!1;let{$from:i,$to:r}=n;if(!i.parent.inlineContent||s.endOfTextblock(e<0?"up":"down")){let o=z1(s.state,e);if(o&&o instanceof vt)return Qc(s,o)}if(!i.parent.inlineContent){let o=e<0?i:r,a=n instanceof _c?Ft.near(o,e):Ft.findFrom(o,e);return a?Qc(s,a):!1}return!1}function Wx(s,e){if(!(s.state.selection instanceof _t))return!0;let{$head:t,$anchor:n,empty:i}=s.state.selection;if(!t.sameParent(n))return!0;if(!i)return!1;if(s.endOfTextblock(e>0?"forward":"backward"))return!0;let r=!t.textOffset&&(e<0?t.nodeBefore:t.nodeAfter);if(r&&!r.isText){let o=s.state.tr;return e<0?o.delete(t.pos-r.nodeSize,t.pos):o.delete(t.pos,t.pos+r.nodeSize),s.dispatch(o),!0}return!1}function zx(s,e,t){s.domObserver.stop(),e.contentEditable=t,s.domObserver.start()}function gV(s){if(!Li||s.state.selection.$head.parentOffset>0)return!1;let{focusNode:e,focusOffset:t}=s.domSelectionRange();if(e&&e.nodeType==1&&t==0&&e.firstChild&&e.firstChild.contentEditable=="false"){let n=e.firstChild;zx(s,n,"true"),setTimeout(()=>zx(s,n,"false"),20)}return!1}function mV(s){let e="";return s.ctrlKey&&(e+="c"),s.metaKey&&(e+="m"),s.altKey&&(e+="a"),s.shiftKey&&(e+="s"),e}function vV(s,e){let t=e.keyCode,n=mV(e);if(t==8||Mo&&t==72&&n=="c")return Wx(s,-1)||Qf(s,-1);if(t==46&&!e.shiftKey||Mo&&t==68&&n=="c")return Wx(s,1)||Qf(s,1);if(t==13||t==27)return!0;if(t==37||Mo&&t==66&&n=="c"){let i=t==37?Hx(s,s.state.selection.from)=="ltr"?-1:1:-1;return $x(s,i,n)||Qf(s,i)}else if(t==39||Mo&&t==70&&n=="c"){let i=t==39?Hx(s,s.state.selection.from)=="ltr"?1:-1:1;return $x(s,i,n)||Qf(s,i)}else{if(t==38||Mo&&t==80&&n=="c")return Ux(s,-1,n)||Qf(s,-1);if(t==40||Mo&&t==78&&n=="c")return gV(s)||Ux(s,1,n)||Qf(s,1);if(n==(Mo?"m":"c")&&(t==66||t==73||t==89||t==90))return!0}return!1}function xE(s,e){s.someProp("transformCopied",p=>{e=p(e,s)});let t=[],{content:n,openStart:i,openEnd:r}=e;for(;i>1&&r>1&&n.childCount==1&&n.firstChild.childCount==1;){i--,r--;let p=n.firstChild;t.push(p.type.name,p.attrs!=p.type.defaultAttrs?p.attrs:null),n=p.content}let o=s.someProp("clipboardSerializer")||Of.fromSchema(s.state.schema),a=BP(),c=a.createElement("div");c.appendChild(o.serializeFragment(n,{document:a}));let l=c.firstChild,u,h=0;for(;l&&l.nodeType==1&&(u=NP[l.nodeName.toLowerCase()]);){for(let p=u.length-1;p>=0;p--){let m=a.createElement(u[p]);for(;c.firstChild;)m.appendChild(c.firstChild);c.appendChild(m),h++}l=c.firstChild}l&&l.nodeType==1&&l.setAttribute("data-pm-slice",`${i} ${r}${h?` -${h}`:""} ${JSON.stringify(t)}`);let d=s.someProp("clipboardTextSerializer",p=>p(e,s))||e.content.textBetween(0,e.content.size,`
`);return{dom:c,text:d,slice:e}}function LP(s,e,t,n,i){let r=i.parent.type.spec.code,o,a;if(!t&&!e)return null;let c=!!e&&(n||r||!t);if(c){if(s.someProp("transformPastedText",d=>{e=d(e,r||n,s)}),r)return a=new nt(Fe.from(s.state.schema.text(e.replace(/\r\n?/g,`
`))),0,0),s.someProp("transformPasted",d=>{a=d(a,s,!0)}),a;let h=s.someProp("clipboardTextParser",d=>d(e,i,n,s));if(h)a=h;else{let d=i.marks(),{schema:p}=s.state,m=Of.fromSchema(p);o=document.createElement("div"),e.split(/(?:\r\n?|\n)+/).forEach(v=>{let g=o.appendChild(document.createElement("p"));v&&g.appendChild(m.serializeNode(p.text(v,d)))})}}else s.someProp("transformPastedHTML",h=>{t=h(t,s)}),o=SV(t),e_&&wV(o);let l=o&&o.querySelector("[data-pm-slice]"),u=l&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(l.getAttribute("data-pm-slice")||"");if(u&&u[3])for(let h=+u[3];h>0;h--){let d=o.firstChild;for(;d&&d.nodeType!=1;)d=d.nextSibling;if(!d)break;o=d}if(a||(a=(s.someProp("clipboardParser")||s.someProp("domParser")||Av.fromSchema(s.state.schema)).parseSlice(o,{preserveWhitespace:!!(c||u),context:i,ruleFromNode(d){return d.nodeName=="BR"&&!d.nextSibling&&d.parentNode&&!yV.test(d.parentNode.nodeName)?{ignore:!0}:null}})),u)a=kV(jx(a,+u[1],+u[2]),u[4]);else if(a=nt.maxOpen(bV(a.content,i),!0),a.openStart||a.openEnd){let h=0,d=0;for(let p=a.content.firstChild;h<a.openStart&&!p.type.spec.isolating;h++,p=p.firstChild);for(let p=a.content.lastChild;d<a.openEnd&&!p.type.spec.isolating;d++,p=p.lastChild);a=jx(a,h,d)}return s.someProp("transformPasted",h=>{a=h(a,s,c)}),a}const yV=/^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var)$/i;function bV(s,e){if(s.childCount<2)return s;for(let t=e.depth;t>=0;t--){let i=e.node(t).contentMatchAt(e.index(t)),r,o=[];if(s.forEach(a=>{if(!o)return;let c=i.findWrapping(a.type),l;if(!c)return o=null;if(l=o.length&&r.length&&OP(c,r,a,o[o.length-1],0))o[o.length-1]=l;else{o.length&&(o[o.length-1]=DP(o[o.length-1],r.length));let u=PP(a,c);o.push(u),i=i.matchType(u.type),r=c}}),o)return Fe.from(o)}return s}function PP(s,e,t=0){for(let n=e.length-1;n>=t;n--)s=e[n].create(null,Fe.from(s));return s}function OP(s,e,t,n,i){if(i<s.length&&i<e.length&&s[i]==e[i]){let r=OP(s,e,t,n.lastChild,i+1);if(r)return n.copy(n.content.replaceChild(n.childCount-1,r));if(n.contentMatchAt(n.childCount).matchType(i==s.length-1?t.type:s[i+1]))return n.copy(n.content.append(Fe.from(PP(t,s,i+1))))}}function DP(s,e){if(e==0)return s;let t=s.content.replaceChild(s.childCount-1,DP(s.lastChild,e-1)),n=s.contentMatchAt(s.childCount).fillBefore(Fe.empty,!0);return s.copy(t.append(n))}function V1(s,e,t,n,i,r){let o=e<0?s.firstChild:s.lastChild,a=o.content;return s.childCount>1&&(r=0),i<n-1&&(a=V1(a,e,t,n,i+1,r)),i>=t&&(a=e<0?o.contentMatchAt(0).fillBefore(a,r<=i).append(a):a.append(o.contentMatchAt(o.childCount).fillBefore(Fe.empty,!0))),s.replaceChild(e<0?0:s.childCount-1,o.copy(a))}function jx(s,e,t){return e<s.openStart&&(s=new nt(V1(s.content,-1,e,s.openStart,0,s.openEnd),e,s.openEnd)),t<s.openEnd&&(s=new nt(V1(s.content,1,t,s.openEnd,0,0),s.openStart,t)),s}const NP={thead:["table"],tbody:["table"],tfoot:["table"],caption:["table"],colgroup:["table"],col:["table","colgroup"],tr:["table","tbody"],td:["table","tbody","tr"],th:["table","tbody","tr"]};let Vx=null;function BP(){return Vx||(Vx=document.implementation.createHTMLDocument("title"))}let gC=null;function _V(s){let e=window.trustedTypes;return e?(gC||(gC=e.defaultPolicy||e.createPolicy("ProseMirrorClipboard",{createHTML:t=>t})),gC.createHTML(s)):s}function SV(s){let e=/^(\s*<meta [^>]*>)*/.exec(s);e&&(s=s.slice(e[0].length));let t=BP().createElement("div"),n=/<([a-z][^>\s]+)/i.exec(s),i;if((i=n&&NP[n[1].toLowerCase()])&&(s=i.map(r=>"<"+r+">").join("")+s+i.map(r=>"</"+r+">").reverse().join("")),t.innerHTML=_V(s),i)for(let r=0;r<i.length;r++)t=t.querySelector(i[r])||t;return t}function wV(s){let e=s.querySelectorAll(vi?"span:not([class]):not([style])":"span.Apple-converted-space");for(let t=0;t<e.length;t++){let n=e[t];n.childNodes.length==1&&n.textContent==" "&&n.parentNode&&n.parentNode.replaceChild(s.ownerDocument.createTextNode(" "),n)}}function kV(s,e){if(!s.size)return s;let t=s.content.firstChild.type.schema,n;try{n=JSON.parse(e)}catch{return s}let{content:i,openStart:r,openEnd:o}=s;for(let a=n.length-2;a>=0;a-=2){let c=t.nodes[n[a]];if(!c||c.hasRequiredAttrs())break;i=Fe.from(c.create(n[a+1],i)),r++,o++}return new nt(i,r,o)}const er={},tr={},CV={touchstart:!0,touchmove:!0};class TV{constructor(){this.shiftKey=!1,this.mouseDown=null,this.lastKeyCode=null,this.lastKeyCodeTime=0,this.lastClick={time:0,x:0,y:0,type:"",button:0},this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastIOSEnter=0,this.lastIOSEnterFallbackTimeout=-1,this.lastFocus=0,this.lastTouch=0,this.lastChromeDelete=0,this.composing=!1,this.compositionNode=null,this.composingTimeout=-1,this.compositionNodes=[],this.compositionEndedAt=-2e8,this.compositionID=1,this.badSafariComposition=!1,this.compositionPendingChanges=0,this.domChangeCount=0,this.eventHandlers=Object.create(null),this.hideSelectionGuard=null}}function AV(s){for(let e in er){let t=er[e];s.dom.addEventListener(e,s.input.eventHandlers[e]=n=>{MV(s,n)&&!IE(s,n)&&(s.editable||!(n.type in tr))&&t(s,n)},CV[e]?{passive:!0}:void 0)}Li&&s.dom.addEventListener("input",()=>null),G1(s)}function th(s,e){s.input.lastSelectionOrigin=e,s.input.lastSelectionTime=Date.now()}function EV(s){s.domObserver.stop();for(let e in s.input.eventHandlers)s.dom.removeEventListener(e,s.input.eventHandlers[e]);clearTimeout(s.input.composingTimeout),clearTimeout(s.input.lastIOSEnterFallbackTimeout)}function G1(s){s.someProp("handleDOMEvents",e=>{for(let t in e)s.input.eventHandlers[t]||s.dom.addEventListener(t,s.input.eventHandlers[t]=n=>IE(s,n))})}function IE(s,e){return s.someProp("handleDOMEvents",t=>{let n=t[e.type];return n?n(s,e)||e.defaultPrevented:!1})}function MV(s,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let t=e.target;t!=s.dom;t=t.parentNode)if(!t||t.nodeType==11||t.pmViewDesc&&t.pmViewDesc.stopEvent(e))return!1;return!0}function xV(s,e){!IE(s,e)&&er[e.type]&&(s.editable||!(e.type in tr))&&er[e.type](s,e)}tr.keydown=(s,e)=>{let t=e;if(s.input.shiftKey=t.keyCode==16||t.shiftKey,!$P(s,t)&&(s.input.lastKeyCode=t.keyCode,s.input.lastKeyCodeTime=Date.now(),!(pc&&vi&&t.keyCode==13)))if(t.keyCode!=229&&s.domObserver.forceFlush(),tm&&t.keyCode==13&&!t.ctrlKey&&!t.altKey&&!t.metaKey){let n=Date.now();s.input.lastIOSEnter=n,s.input.lastIOSEnterFallbackTimeout=setTimeout(()=>{s.input.lastIOSEnter==n&&(s.someProp("handleKeyDown",i=>i(s,Ih(13,"Enter"))),s.input.lastIOSEnter=0)},200)}else s.someProp("handleKeyDown",n=>n(s,t))||vV(s,t)?t.preventDefault():th(s,"key")};tr.keyup=(s,e)=>{e.keyCode==16&&(s.input.shiftKey=!1)};tr.keypress=(s,e)=>{let t=e;if($P(s,t)||!t.charCode||t.ctrlKey&&!t.altKey||Mo&&t.metaKey)return;if(s.someProp("handleKeyPress",i=>i(s,t))){t.preventDefault();return}let n=s.state.selection;if(!(n instanceof _t)||!n.$from.sameParent(n.$to)){let i=String.fromCharCode(t.charCode),r=()=>s.state.tr.insertText(i).scrollIntoView();!/[\r\n]/.test(i)&&!s.someProp("handleTextInput",o=>o(s,n.$from.pos,n.$to.pos,i,r))&&s.dispatch(r()),t.preventDefault()}};function tk(s){return{left:s.clientX,top:s.clientY}}function IV(s,e){let t=e.x-s.clientX,n=e.y-s.clientY;return t*t+n*n<100}function RE(s,e,t,n,i){if(n==-1)return!1;let r=s.state.doc.resolve(n);for(let o=r.depth+1;o>0;o--)if(s.someProp(e,a=>o>r.depth?a(s,t,r.nodeAfter,r.before(o),i,!0):a(s,t,r.node(o),r.before(o),i,!1)))return!0;return!1}function wp(s,e,t){if(s.focused||s.focus(),s.state.selection.eq(e))return;let n=s.state.tr.setSelection(e);n.setMeta("pointer",!0),s.dispatch(n)}function RV(s,e){if(e==-1)return!1;let t=s.state.doc.resolve(e),n=t.nodeAfter;return n&&n.isAtom&&vt.isSelectable(n)?(wp(s,new vt(t)),!0):!1}function LV(s,e){if(e==-1)return!1;let t=s.state.selection,n,i;t instanceof vt&&(n=t.node);let r=s.state.doc.resolve(e);for(let o=r.depth+1;o>0;o--){let a=o>r.depth?r.nodeAfter:r.node(o);if(vt.isSelectable(a)){n&&t.$from.depth>0&&o>=t.$from.depth&&r.before(t.$from.depth+1)==t.$from.pos?i=r.before(t.$from.depth):i=r.before(o);break}}return i!=null?(wp(s,vt.create(s.state.doc,i)),!0):!1}function PV(s,e,t,n,i){return RE(s,"handleClickOn",e,t,n)||s.someProp("handleClick",r=>r(s,e,n))||(i?LV(s,t):RV(s,t))}function OV(s,e,t,n){return RE(s,"handleDoubleClickOn",e,t,n)||s.someProp("handleDoubleClick",i=>i(s,e,n))}function DV(s,e,t,n){return RE(s,"handleTripleClickOn",e,t,n)||s.someProp("handleTripleClick",i=>i(s,e,n))||NV(s,t,n)}function NV(s,e,t){if(t.button!=0)return!1;let n=s.state.doc;if(e==-1)return n.inlineContent?(wp(s,_t.create(n,0,n.content.size)),!0):!1;let i=n.resolve(e);for(let r=i.depth+1;r>0;r--){let o=r>i.depth?i.nodeAfter:i.node(r),a=i.before(r);if(o.inlineContent)wp(s,_t.create(n,a+1,a+1+o.content.size));else if(vt.isSelectable(o))wp(s,vt.create(n,a));else continue;return!0}}function LE(s){return Aw(s)}const FP=Mo?"metaKey":"ctrlKey";er.mousedown=(s,e)=>{let t=e;s.input.shiftKey=t.shiftKey;let n=LE(s),i=Date.now(),r="singleClick";i-s.input.lastClick.time<500&&IV(t,s.input.lastClick)&&!t[FP]&&s.input.lastClick.button==t.button&&(s.input.lastClick.type=="singleClick"?r="doubleClick":s.input.lastClick.type=="doubleClick"&&(r="tripleClick")),s.input.lastClick={time:i,x:t.clientX,y:t.clientY,type:r,button:t.button};let o=s.posAtCoords(tk(t));o&&(r=="singleClick"?(s.input.mouseDown&&s.input.mouseDown.done(),s.input.mouseDown=new BV(s,o,t,!!n)):(r=="doubleClick"?OV:DV)(s,o.pos,o.inside,t)?t.preventDefault():th(s,"pointer"))};class BV{constructor(e,t,n,i){this.view=e,this.pos=t,this.event=n,this.flushed=i,this.delayedSelectionSync=!1,this.mightDrag=null,this.startDoc=e.state.doc,this.selectNode=!!n[FP],this.allowDefault=n.shiftKey;let r,o;if(t.inside>-1)r=e.state.doc.nodeAt(t.inside),o=t.inside;else{let u=e.state.doc.resolve(t.pos);r=u.parent,o=u.depth?u.before():0}const a=i?null:n.target,c=a?e.docView.nearestDesc(a,!0):null;this.target=c&&c.nodeDOM.nodeType==1?c.nodeDOM:null;let{selection:l}=e.state;n.button==0&&(r.type.spec.draggable&&r.type.spec.selectable!==!1||l instanceof vt&&l.from<=o&&l.to>o)&&(this.mightDrag={node:r,pos:o,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&Po&&!this.target.hasAttribute("contentEditable"))}),this.target&&this.mightDrag&&(this.mightDrag.addAttr||this.mightDrag.setUneditable)&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&(this.target.draggable=!0),this.mightDrag.setUneditable&&setTimeout(()=>{this.view.input.mouseDown==this&&this.target.setAttribute("contentEditable","false")},20),this.view.domObserver.start()),e.root.addEventListener("mouseup",this.up=this.up.bind(this)),e.root.addEventListener("mousemove",this.move=this.move.bind(this)),th(e,"pointer")}done(){this.view.root.removeEventListener("mouseup",this.up),this.view.root.removeEventListener("mousemove",this.move),this.mightDrag&&this.target&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&this.target.removeAttribute("draggable"),this.mightDrag.setUneditable&&this.target.removeAttribute("contentEditable"),this.view.domObserver.start()),this.delayedSelectionSync&&setTimeout(()=>Sc(this.view)),this.view.input.mouseDown=null}up(e){if(this.done(),!this.view.dom.contains(e.target))return;let t=this.pos;this.view.state.doc!=this.startDoc&&(t=this.view.posAtCoords(tk(e))),this.updateAllowDefault(e),this.allowDefault||!t?th(this.view,"pointer"):PV(this.view,t.pos,t.inside,e,this.selectNode)?e.preventDefault():e.button==0&&(this.flushed||Li&&this.mightDrag&&!this.mightDrag.node.isAtom||vi&&!this.view.state.selection.visible&&Math.min(Math.abs(t.pos-this.view.state.selection.from),Math.abs(t.pos-this.view.state.selection.to))<=2)?(wp(this.view,Ft.near(this.view.state.doc.resolve(t.pos))),e.preventDefault()):th(this.view,"pointer")}move(e){this.updateAllowDefault(e),th(this.view,"pointer"),e.buttons==0&&this.done()}updateAllowDefault(e){!this.allowDefault&&(Math.abs(this.event.x-e.clientX)>4||Math.abs(this.event.y-e.clientY)>4)&&(this.allowDefault=!0)}}er.touchstart=s=>{s.input.lastTouch=Date.now(),LE(s),th(s,"pointer")};er.touchmove=s=>{s.input.lastTouch=Date.now(),th(s,"pointer")};er.contextmenu=s=>LE(s);function $P(s,e){return s.composing?!0:Li&&Math.abs(e.timeStamp-s.input.compositionEndedAt)<500?(s.input.compositionEndedAt=-2e8,!0):!1}const FV=pc?5e3:-1;tr.compositionstart=tr.compositionupdate=s=>{if(!s.composing){s.domObserver.flush();let{state:e}=s,t=e.selection.$to;if(e.selection instanceof _t&&(e.storedMarks||!t.textOffset&&t.parentOffset&&t.nodeBefore.marks.some(n=>n.type.spec.inclusive===!1)||vi&&mP&&$V(s)))s.markCursor=s.state.storedMarks||t.marks(),Aw(s,!0),s.markCursor=null;else if(Aw(s,!e.selection.empty),Po&&e.selection.empty&&t.parentOffset&&!t.textOffset&&t.nodeBefore.marks.length){let n=s.domSelectionRange();for(let i=n.focusNode,r=n.focusOffset;i&&i.nodeType==1&&r!=0;){let o=r<0?i.lastChild:i.childNodes[r-1];if(!o)break;if(o.nodeType==3){let a=s.domSelection();a&&a.collapse(o,o.nodeValue.length);break}else i=o,r=-1}}s.input.composing=!0}HP(s,FV)};function $V(s){let{focusNode:e,focusOffset:t}=s.domSelectionRange();if(!e||e.nodeType!=1||t>=e.childNodes.length)return!1;let n=e.childNodes[t];return n.nodeType==1&&n.contentEditable=="false"}tr.compositionend=(s,e)=>{s.composing&&(s.input.composing=!1,s.input.compositionEndedAt=e.timeStamp,s.input.compositionPendingChanges=s.domObserver.pendingRecords().length?s.input.compositionID:0,s.input.compositionNode=null,s.input.badSafariComposition?s.domObserver.forceFlush():s.input.compositionPendingChanges&&Promise.resolve().then(()=>s.domObserver.flush()),s.input.compositionID++,HP(s,20))};function HP(s,e){clearTimeout(s.input.composingTimeout),e>-1&&(s.input.composingTimeout=setTimeout(()=>Aw(s),e))}function UP(s){for(s.composing&&(s.input.composing=!1,s.input.compositionEndedAt=UV());s.input.compositionNodes.length>0;)s.input.compositionNodes.pop().markParentsDirty()}function HV(s){let e=s.domSelectionRange();if(!e.focusNode)return null;let t=L7(e.focusNode,e.focusOffset),n=P7(e.focusNode,e.focusOffset);if(t&&n&&t!=n){let i=n.pmViewDesc,r=s.domObserver.lastChangedTextNode;if(t==r||n==r)return r;if(!i||!i.isText(n.nodeValue))return n;if(s.input.compositionNode==n){let o=t.pmViewDesc;if(!(!o||!o.isText(t.nodeValue)))return n}}return t||n}function UV(){let s=document.createEvent("Event");return s.initEvent("event",!0,!0),s.timeStamp}function Aw(s,e=!1){if(!(pc&&s.domObserver.flushingSoon>=0)){if(s.domObserver.forceFlush(),UP(s),e||s.docView&&s.docView.dirty){let t=EE(s),n=s.state.selection;return t&&!t.eq(n)?s.dispatch(s.state.tr.setSelection(t)):(s.markCursor||e)&&!n.$from.node(n.$from.sharedDepth(n.to)).inlineContent?s.dispatch(s.state.tr.deleteSelection()):s.updateState(s.state),!0}return!1}}function WV(s,e){if(!s.dom.parentNode)return;let t=s.dom.parentNode.appendChild(document.createElement("div"));t.appendChild(e),t.style.cssText="position: fixed; left: -10000px; top: 10px";let n=getSelection(),i=document.createRange();i.selectNodeContents(e),s.dom.blur(),n.removeAllRanges(),n.addRange(i),setTimeout(()=>{t.parentNode&&t.parentNode.removeChild(t),s.focus()},50)}const Xv=yr&&nh<15||tm&&B7<604;er.copy=tr.cut=(s,e)=>{let t=e,n=s.state.selection,i=t.type=="cut";if(n.empty)return;let r=Xv?null:t.clipboardData,o=n.content(),{dom:a,text:c}=xE(s,o);r?(t.preventDefault(),r.clearData(),r.setData("text/html",a.innerHTML),r.setData("text/plain",c)):WV(s,a),i&&s.dispatch(s.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function zV(s){return s.openStart==0&&s.openEnd==0&&s.content.childCount==1?s.content.firstChild:null}function jV(s,e){if(!s.dom.parentNode)return;let t=s.input.shiftKey||s.state.selection.$from.parent.type.spec.code,n=s.dom.parentNode.appendChild(document.createElement(t?"textarea":"div"));t||(n.contentEditable="true"),n.style.cssText="position: fixed; left: -10000px; top: 10px",n.focus();let i=s.input.shiftKey&&s.input.lastKeyCode!=45;setTimeout(()=>{s.focus(),n.parentNode&&n.parentNode.removeChild(n),t?Yv(s,n.value,null,i,e):Yv(s,n.textContent,n.innerHTML,i,e)},50)}function Yv(s,e,t,n,i){let r=LP(s,e,t,n,s.state.selection.$from);if(s.someProp("handlePaste",c=>c(s,i,r||nt.empty)))return!0;if(!r)return!1;let o=zV(r),a=o?s.state.tr.replaceSelectionWith(o,n):s.state.tr.replaceSelection(r);return s.dispatch(a.scrollIntoView().setMeta("paste",!0).setMeta("uiEvent","paste")),!0}function WP(s){let e=s.getData("text/plain")||s.getData("Text");if(e)return e;let t=s.getData("text/uri-list");return t?t.replace(/\r?\n/g," "):""}tr.paste=(s,e)=>{let t=e;if(s.composing&&!pc)return;let n=Xv?null:t.clipboardData,i=s.input.shiftKey&&s.input.lastKeyCode!=45;n&&Yv(s,WP(n),n.getData("text/html"),i,t)?t.preventDefault():jV(s,t)};class zP{constructor(e,t,n){this.slice=e,this.move=t,this.node=n}}const VV=Mo?"altKey":"ctrlKey";function jP(s,e){let t;return s.someProp("dragCopies",n=>{t=t||n(e)}),t!=null?!t:!e[VV]}er.dragstart=(s,e)=>{let t=e,n=s.input.mouseDown;if(n&&n.done(),!t.dataTransfer)return;let i=s.state.selection,r=i.empty?null:s.posAtCoords(tk(t)),o;if(!(r&&r.pos>=i.from&&r.pos<=(i instanceof vt?i.to-1:i.to))){if(n&&n.mightDrag)o=vt.create(s.state.doc,n.mightDrag.pos);else if(t.target&&t.target.nodeType==1){let h=s.docView.nearestDesc(t.target,!0);h&&h.node.type.spec.draggable&&h!=s.docView&&(o=vt.create(s.state.doc,h.posBefore))}}let a=(o||s.state.selection).content(),{dom:c,text:l,slice:u}=xE(s,a);(!t.dataTransfer.files.length||!vi||gP>120)&&t.dataTransfer.clearData(),t.dataTransfer.setData(Xv?"Text":"text/html",c.innerHTML),t.dataTransfer.effectAllowed="copyMove",Xv||t.dataTransfer.setData("text/plain",l),s.dragging=new zP(u,jP(s,t),o)};er.dragend=s=>{let e=s.dragging;window.setTimeout(()=>{s.dragging==e&&(s.dragging=null)},50)};tr.dragover=tr.dragenter=(s,e)=>e.preventDefault();tr.drop=(s,e)=>{try{GV(s,e,s.dragging)}finally{s.dragging=null}};function GV(s,e,t){if(!e.dataTransfer)return;let n=s.posAtCoords(tk(e));if(!n)return;let i=s.state.doc.resolve(n.pos),r=t&&t.slice;r?s.someProp("transformPasted",p=>{r=p(r,s,!1)}):r=LP(s,WP(e.dataTransfer),Xv?null:e.dataTransfer.getData("text/html"),!1,i);let o=!!(t&&jP(s,e));if(s.someProp("handleDrop",p=>p(s,e,r||nt.empty,o))){e.preventDefault();return}if(!r)return;e.preventDefault();let a=r?WL(s.state.doc,i.pos,r):i.pos;a==null&&(a=i.pos);let c=s.state.tr;if(o){let{node:p}=t;p?p.replace(c):c.deleteSelection()}let l=c.mapping.map(a),u=r.openStart==0&&r.openEnd==0&&r.content.childCount==1,h=c.doc;if(u?c.replaceRangeWith(l,l,r.content.firstChild):c.replaceRange(l,l,r),c.doc.eq(h))return;let d=c.doc.resolve(l);if(u&&vt.isSelectable(r.content.firstChild)&&d.nodeAfter&&d.nodeAfter.sameMarkup(r.content.firstChild))c.setSelection(new vt(d));else{let p=c.mapping.map(a);c.mapping.maps[c.mapping.maps.length-1].forEach((m,v,g,y)=>p=y),c.setSelection(ME(s,d,c.doc.resolve(p)))}s.focus(),s.dispatch(c.setMeta("uiEvent","drop"))}er.focus=s=>{s.input.lastFocus=Date.now(),s.focused||(s.domObserver.stop(),s.dom.classList.add("ProseMirror-focused"),s.domObserver.start(),s.focused=!0,setTimeout(()=>{s.docView&&s.hasFocus()&&!s.domObserver.currentSelection.eq(s.domSelectionRange())&&Sc(s)},20))};er.blur=(s,e)=>{let t=e;s.focused&&(s.domObserver.stop(),s.dom.classList.remove("ProseMirror-focused"),s.domObserver.start(),t.relatedTarget&&s.dom.contains(t.relatedTarget)&&s.domObserver.currentSelection.clear(),s.focused=!1)};er.beforeinput=(s,e)=>{if(vi&&pc&&e.inputType=="deleteContentBackward"){s.domObserver.flushSoon();let{domChangeCount:n}=s.input;setTimeout(()=>{if(s.input.domChangeCount!=n||(s.dom.blur(),s.focus(),s.someProp("handleKeyDown",r=>r(s,Ih(8,"Backspace")))))return;let{$cursor:i}=s.state.selection;i&&i.pos>0&&s.dispatch(s.state.tr.delete(i.pos-1,i.pos).scrollIntoView())},50)}};for(let s in tr)er[s]=tr[s];function Jv(s,e){if(s==e)return!0;for(let t in s)if(s[t]!==e[t])return!1;for(let t in e)if(!(t in s))return!1;return!0}class Ew{constructor(e,t){this.toDOM=e,this.spec=t||wf,this.side=this.spec.side||0}map(e,t,n,i){let{pos:r,deleted:o}=e.mapResult(t.from+i,this.side<0?-1:1);return o?null:new Mi(r-n,r-n,this)}valid(){return!0}eq(e){return this==e||e instanceof Ew&&(this.spec.key&&this.spec.key==e.spec.key||this.toDOM==e.toDOM&&Jv(this.spec,e.spec))}destroy(e){this.spec.destroy&&this.spec.destroy(e)}}class rh{constructor(e,t){this.attrs=e,this.spec=t||wf}map(e,t,n,i){let r=e.map(t.from+i,this.spec.inclusiveStart?-1:1)-n,o=e.map(t.to+i,this.spec.inclusiveEnd?1:-1)-n;return r>=o?null:new Mi(r,o,this)}valid(e,t){return t.from<t.to}eq(e){return this==e||e instanceof rh&&Jv(this.attrs,e.attrs)&&Jv(this.spec,e.spec)}static is(e){return e.type instanceof rh}destroy(){}}class PE{constructor(e,t){this.attrs=e,this.spec=t||wf}map(e,t,n,i){let r=e.mapResult(t.from+i,1);if(r.deleted)return null;let o=e.mapResult(t.to+i,-1);return o.deleted||o.pos<=r.pos?null:new Mi(r.pos-n,o.pos-n,this)}valid(e,t){let{index:n,offset:i}=e.content.findIndex(t.from),r;return i==t.from&&!(r=e.child(n)).isText&&i+r.nodeSize==t.to}eq(e){return this==e||e instanceof PE&&Jv(this.attrs,e.attrs)&&Jv(this.spec,e.spec)}destroy(){}}class Mi{constructor(e,t,n){this.from=e,this.to=t,this.type=n}copy(e,t){return new Mi(e,t,this.type)}eq(e,t=0){return this.type.eq(e.type)&&this.from+t==e.from&&this.to+t==e.to}map(e,t,n){return this.type.map(e,this,t,n)}static widget(e,t,n){return new Mi(e,e,new Ew(t,n))}static inline(e,t,n,i){return new Mi(e,t,new rh(n,i))}static node(e,t,n,i){return new Mi(e,t,new PE(n,i))}get spec(){return this.type.spec}get inline(){return this.type instanceof rh}get widget(){return this.type instanceof Ew}}const rp=[],wf={};class Bs{constructor(e,t){this.local=e.length?e:rp,this.children=t.length?t:rp}static create(e,t){return t.length?Mw(t,e,0,wf):Ti}find(e,t,n){let i=[];return this.findInner(e??0,t??1e9,i,0,n),i}findInner(e,t,n,i,r){for(let o=0;o<this.local.length;o++){let a=this.local[o];a.from<=t&&a.to>=e&&(!r||r(a.spec))&&n.push(a.copy(a.from+i,a.to+i))}for(let o=0;o<this.children.length;o+=3)if(this.children[o]<t&&this.children[o+1]>e){let a=this.children[o]+1;this.children[o+2].findInner(e-a,t-a,n,i+a,r)}}map(e,t,n){return this==Ti||e.maps.length==0?this:this.mapInner(e,t,0,0,n||wf)}mapInner(e,t,n,i,r){let o;for(let a=0;a<this.local.length;a++){let c=this.local[a].map(e,n,i);c&&c.type.valid(t,c)?(o||(o=[])).push(c):r.onRemove&&r.onRemove(this.local[a].spec)}return this.children.length?qV(this.children,o||[],e,t,n,i,r):o?new Bs(o.sort(kf),rp):Ti}add(e,t){return t.length?this==Ti?Bs.create(e,t):this.addInner(e,t,0):this}addInner(e,t,n){let i,r=0;e.forEach((a,c)=>{let l=c+n,u;if(u=GP(t,a,l)){for(i||(i=this.children.slice());r<i.length&&i[r]<c;)r+=3;i[r]==c?i[r+2]=i[r+2].addInner(a,u,l+1):i.splice(r,0,c,c+a.nodeSize,Mw(u,a,l+1,wf)),r+=3}});let o=VP(r?qP(t):t,-n);for(let a=0;a<o.length;a++)o[a].type.valid(e,o[a])||o.splice(a--,1);return new Bs(o.length?this.local.concat(o).sort(kf):this.local,i||this.children)}remove(e){return e.length==0||this==Ti?this:this.removeInner(e,0)}removeInner(e,t){let n=this.children,i=this.local;for(let r=0;r<n.length;r+=3){let o,a=n[r]+t,c=n[r+1]+t;for(let u=0,h;u<e.length;u++)(h=e[u])&&h.from>a&&h.to<c&&(e[u]=null,(o||(o=[])).push(h));if(!o)continue;n==this.children&&(n=this.children.slice());let l=n[r+2].removeInner(o,a+1);l!=Ti?n[r+2]=l:(n.splice(r,3),r-=3)}if(i.length){for(let r=0,o;r<e.length;r++)if(o=e[r])for(let a=0;a<i.length;a++)i[a].eq(o,t)&&(i==this.local&&(i=this.local.slice()),i.splice(a--,1))}return n==this.children&&i==this.local?this:i.length||n.length?new Bs(i,n):Ti}forChild(e,t){if(this==Ti)return this;if(t.isLeaf)return Bs.empty;let n,i;for(let a=0;a<this.children.length;a+=3)if(this.children[a]>=e){this.children[a]==e&&(n=this.children[a+2]);break}let r=e+1,o=r+t.content.size;for(let a=0;a<this.local.length;a++){let c=this.local[a];if(c.from<o&&c.to>r&&c.type instanceof rh){let l=Math.max(r,c.from)-r,u=Math.min(o,c.to)-r;l<u&&(i||(i=[])).push(c.copy(l,u))}}if(i){let a=new Bs(i.sort(kf),rp);return n?new Jc([a,n]):a}return n||Ti}eq(e){if(this==e)return!0;if(!(e instanceof Bs)||this.local.length!=e.local.length||this.children.length!=e.children.length)return!1;for(let t=0;t<this.local.length;t++)if(!this.local[t].eq(e.local[t]))return!1;for(let t=0;t<this.children.length;t+=3)if(this.children[t]!=e.children[t]||this.children[t+1]!=e.children[t+1]||!this.children[t+2].eq(e.children[t+2]))return!1;return!0}locals(e){return OE(this.localsInner(e))}localsInner(e){if(this==Ti)return rp;if(e.inlineContent||!this.local.some(rh.is))return this.local;let t=[];for(let n=0;n<this.local.length;n++)this.local[n].type instanceof rh||t.push(this.local[n]);return t}forEachSet(e){e(this)}}Bs.empty=new Bs([],[]);Bs.removeOverlap=OE;const Ti=Bs.empty;class Jc{constructor(e){this.members=e}map(e,t){const n=this.members.map(i=>i.map(e,t,wf));return Jc.from(n)}forChild(e,t){if(t.isLeaf)return Bs.empty;let n=[];for(let i=0;i<this.members.length;i++){let r=this.members[i].forChild(e,t);r!=Ti&&(r instanceof Jc?n=n.concat(r.members):n.push(r))}return Jc.from(n)}eq(e){if(!(e instanceof Jc)||e.members.length!=this.members.length)return!1;for(let t=0;t<this.members.length;t++)if(!this.members[t].eq(e.members[t]))return!1;return!0}locals(e){let t,n=!0;for(let i=0;i<this.members.length;i++){let r=this.members[i].localsInner(e);if(r.length)if(!t)t=r;else{n&&(t=t.slice(),n=!1);for(let o=0;o<r.length;o++)t.push(r[o])}}return t?OE(n?t:t.sort(kf)):rp}static from(e){switch(e.length){case 0:return Ti;case 1:return e[0];default:return new Jc(e.every(t=>t instanceof Bs)?e:e.reduce((t,n)=>t.concat(n instanceof Bs?n:n.members),[]))}}forEachSet(e){for(let t=0;t<this.members.length;t++)this.members[t].forEachSet(e)}}function qV(s,e,t,n,i,r,o){let a=s.slice();for(let l=0,u=r;l<t.maps.length;l++){let h=0;t.maps[l].forEach((d,p,m,v)=>{let g=v-m-(p-d);for(let y=0;y<a.length;y+=3){let b=a[y+1];if(b<0||d>b+u-h)continue;let _=a[y]+u-h;p>=_?a[y+1]=d<=_?-2:-1:d>=u&&g&&(a[y]+=g,a[y+1]+=g)}h+=g}),u=t.maps[l].map(u,-1)}let c=!1;for(let l=0;l<a.length;l+=3)if(a[l+1]<0){if(a[l+1]==-2){c=!0,a[l+1]=-1;continue}let u=t.map(s[l]+r),h=u-i;if(h<0||h>=n.content.size){c=!0;continue}let d=t.map(s[l+1]+r,-1),p=d-i,{index:m,offset:v}=n.content.findIndex(h),g=n.maybeChild(m);if(g&&v==h&&v+g.nodeSize==p){let y=a[l+2].mapInner(t,g,u+1,s[l]+r+1,o);y!=Ti?(a[l]=h,a[l+1]=p,a[l+2]=y):(a[l+1]=-2,c=!0)}else c=!0}if(c){let l=KV(a,s,e,t,i,r,o),u=Mw(l,n,0,o);e=u.local;for(let h=0;h<a.length;h+=3)a[h+1]<0&&(a.splice(h,3),h-=3);for(let h=0,d=0;h<u.children.length;h+=3){let p=u.children[h];for(;d<a.length&&a[d]<p;)d+=3;a.splice(d,0,u.children[h],u.children[h+1],u.children[h+2])}}return new Bs(e.sort(kf),a)}function VP(s,e){if(!e||!s.length)return s;let t=[];for(let n=0;n<s.length;n++){let i=s[n];t.push(new Mi(i.from+e,i.to+e,i.type))}return t}function KV(s,e,t,n,i,r,o){function a(c,l){for(let u=0;u<c.local.length;u++){let h=c.local[u].map(n,i,l);h?t.push(h):o.onRemove&&o.onRemove(c.local[u].spec)}for(let u=0;u<c.children.length;u+=3)a(c.children[u+2],c.children[u]+l+1)}for(let c=0;c<s.length;c+=3)s[c+1]==-1&&a(s[c+2],e[c]+r+1);return t}function GP(s,e,t){if(e.isLeaf)return null;let n=t+e.nodeSize,i=null;for(let r=0,o;r<s.length;r++)(o=s[r])&&o.from>t&&o.to<n&&((i||(i=[])).push(o),s[r]=null);return i}function qP(s){let e=[];for(let t=0;t<s.length;t++)s[t]!=null&&e.push(s[t]);return e}function Mw(s,e,t,n){let i=[],r=!1;e.forEach((a,c)=>{let l=GP(s,a,c+t);if(l){r=!0;let u=Mw(l,a,t+c+1,n);u!=Ti&&i.push(c,c+a.nodeSize,u)}});let o=VP(r?qP(s):s,-t).sort(kf);for(let a=0;a<o.length;a++)o[a].type.valid(e,o[a])||(n.onRemove&&n.onRemove(o[a].spec),o.splice(a--,1));return o.length||i.length?new Bs(o,i):Ti}function kf(s,e){return s.from-e.from||s.to-e.to}function OE(s){let e=s;for(let t=0;t<e.length-1;t++){let n=e[t];if(n.from!=n.to)for(let i=t+1;i<e.length;i++){let r=e[i];if(r.from==n.from){r.to!=n.to&&(e==s&&(e=s.slice()),e[i]=r.copy(r.from,n.to),Gx(e,i+1,r.copy(n.to,r.to)));continue}else{r.from<n.to&&(e==s&&(e=s.slice()),e[t]=n.copy(n.from,r.from),Gx(e,i,n.copy(r.from,n.to)));break}}}return e}function Gx(s,e,t){for(;e<s.length&&kf(t,s[e])>0;)e++;s.splice(e,0,t)}function mC(s){let e=[];return s.someProp("decorations",t=>{let n=t(s.state);n&&n!=Ti&&e.push(n)}),s.cursorWrapper&&e.push(Bs.create(s.state.doc,[s.cursorWrapper.deco])),Jc.from(e)}const QV={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},XV=yr&&nh<=11;class YV{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}set(e){this.anchorNode=e.anchorNode,this.anchorOffset=e.anchorOffset,this.focusNode=e.focusNode,this.focusOffset=e.focusOffset}clear(){this.anchorNode=this.focusNode=null}eq(e){return e.anchorNode==this.anchorNode&&e.anchorOffset==this.anchorOffset&&e.focusNode==this.focusNode&&e.focusOffset==this.focusOffset}}class JV{constructor(e,t){this.view=e,this.handleDOMChange=t,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new YV,this.onCharData=null,this.suppressingSelectionUpdates=!1,this.lastChangedTextNode=null,this.observer=window.MutationObserver&&new window.MutationObserver(n=>{for(let i=0;i<n.length;i++)this.queue.push(n[i]);yr&&nh<=11&&n.some(i=>i.type=="childList"&&i.removedNodes.length||i.type=="characterData"&&i.oldValue.length>i.target.nodeValue.length)?this.flushSoon():Li&&e.composing&&n.some(i=>i.type=="childList"&&i.target.nodeName=="TR")?(e.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),XV&&(this.onCharData=n=>{this.queue.push({target:n.target,type:"characterData",oldValue:n.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this)}flushSoon(){this.flushingSoon<0&&(this.flushingSoon=window.setTimeout(()=>{this.flushingSoon=-1,this.flush()},20))}forceFlush(){this.flushingSoon>-1&&(window.clearTimeout(this.flushingSoon),this.flushingSoon=-1,this.flush())}start(){this.observer&&(this.observer.takeRecords(),this.observer.observe(this.view.dom,QV)),this.onCharData&&this.view.dom.addEventListener("DOMCharacterDataModified",this.onCharData),this.connectSelection()}stop(){if(this.observer){let e=this.observer.takeRecords();if(e.length){for(let t=0;t<e.length;t++)this.queue.push(e[t]);window.setTimeout(()=>this.flush(),20)}this.observer.disconnect()}this.onCharData&&this.view.dom.removeEventListener("DOMCharacterDataModified",this.onCharData),this.disconnectSelection()}connectSelection(){this.view.dom.ownerDocument.addEventListener("selectionchange",this.onSelectionChange)}disconnectSelection(){this.view.dom.ownerDocument.removeEventListener("selectionchange",this.onSelectionChange)}suppressSelectionUpdates(){this.suppressingSelectionUpdates=!0,setTimeout(()=>this.suppressingSelectionUpdates=!1,50)}onSelectionChange(){if(Fx(this.view)){if(this.suppressingSelectionUpdates)return Sc(this.view);if(yr&&nh<=11&&!this.view.state.selection.empty){let e=this.view.domSelectionRange();if(e.focusNode&&Ef(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset))return this.flushSoon()}this.flush()}}setCurSelection(){this.currentSelection.set(this.view.domSelectionRange())}ignoreSelectionChange(e){if(!e.focusNode)return!0;let t=new Set,n;for(let r=e.focusNode;r;r=em(r))t.add(r);for(let r=e.anchorNode;r;r=em(r))if(t.has(r)){n=r;break}let i=n&&this.view.docView.nearestDesc(n);if(i&&i.ignoreMutation({type:"selection",target:n.nodeType==3?n.parentNode:n}))return this.setCurSelection(),!0}pendingRecords(){if(this.observer)for(let e of this.observer.takeRecords())this.queue.push(e);return this.queue}flush(){let{view:e}=this;if(!e.docView||this.flushingSoon>-1)return;let t=this.pendingRecords();t.length&&(this.queue=[]);let n=e.domSelectionRange(),i=!this.suppressingSelectionUpdates&&!this.currentSelection.eq(n)&&Fx(e)&&!this.ignoreSelectionChange(n),r=-1,o=-1,a=!1,c=[];if(e.editable)for(let u=0;u<t.length;u++){let h=this.registerMutation(t[u],c);h&&(r=r<0?h.from:Math.min(h.from,r),o=o<0?h.to:Math.max(h.to,o),h.typeOver&&(a=!0))}if(c.some(u=>u.nodeName=="BR")&&(e.input.lastKeyCode==8||e.input.lastKeyCode==46)){for(let u of c)if(u.nodeName=="BR"&&u.parentNode){let h=u.nextSibling;for(;h&&h.nodeType==1;){if(h.contentEditable=="false"){u.parentNode.removeChild(u);break}h=h.firstChild}}}else if(Po&&c.length){let u=c.filter(h=>h.nodeName=="BR");if(u.length==2){let[h,d]=u;h.parentNode&&h.parentNode.parentNode==d.parentNode?d.remove():h.remove()}else{let{focusNode:h}=this.currentSelection;for(let d of u){let p=d.parentNode;p&&p.nodeName=="LI"&&(!h||tG(e,h)!=p)&&d.remove()}}}let l=null;r<0&&i&&e.input.lastFocus>Date.now()-200&&Math.max(e.input.lastTouch,e.input.lastClick.time)<Date.now()-300&&Z0(n)&&(l=EE(e))&&l.eq(Ft.near(e.state.doc.resolve(0),1))?(e.input.lastFocus=0,Sc(e),this.currentSelection.set(n),e.scrollToSelection()):(r>-1||i)&&(r>-1&&(e.docView.markDirty(r,o),ZV(e)),e.input.badSafariComposition&&(e.input.badSafariComposition=!1,sG(e,c)),this.handleDOMChange(r,o,a,c),e.docView&&e.docView.dirty?e.updateState(e.state):this.currentSelection.eq(n)||Sc(e),this.currentSelection.set(n))}registerMutation(e,t){if(t.indexOf(e.target)>-1)return null;let n=this.view.docView.nearestDesc(e.target);if(e.type=="attributes"&&(n==this.view.docView||e.attributeName=="contenteditable"||e.attributeName=="style"&&!e.oldValue&&!e.target.getAttribute("style"))||!n||n.ignoreMutation(e))return null;if(e.type=="childList"){for(let u=0;u<e.addedNodes.length;u++){let h=e.addedNodes[u];t.push(h),h.nodeType==3&&(this.lastChangedTextNode=h)}if(n.contentDOM&&n.contentDOM!=n.dom&&!n.contentDOM.contains(e.target))return{from:n.posBefore,to:n.posAfter};let i=e.previousSibling,r=e.nextSibling;if(yr&&nh<=11&&e.addedNodes.length)for(let u=0;u<e.addedNodes.length;u++){let{previousSibling:h,nextSibling:d}=e.addedNodes[u];(!h||Array.prototype.indexOf.call(e.addedNodes,h)<0)&&(i=h),(!d||Array.prototype.indexOf.call(e.addedNodes,d)<0)&&(r=d)}let o=i&&i.parentNode==e.target?fi(i)+1:0,a=n.localPosFromDOM(e.target,o,-1),c=r&&r.parentNode==e.target?fi(r):e.target.childNodes.length,l=n.localPosFromDOM(e.target,c,1);return{from:a,to:l}}else return e.type=="attributes"?{from:n.posAtStart-n.border,to:n.posAtEnd+n.border}:(this.lastChangedTextNode=e.target,{from:n.posAtStart,to:n.posAtEnd,typeOver:e.target.nodeValue==e.oldValue})}}let qx=new WeakMap,Kx=!1;function ZV(s){if(!qx.has(s)&&(qx.set(s,null),["normal","nowrap","pre-line"].indexOf(getComputedStyle(s.dom).whiteSpace)!==-1)){if(s.requiresGeckoHackNode=Po,Kx)return;console.warn("ProseMirror expects the CSS white-space property to be set, preferably to 'pre-wrap'. It is recommended to load style/prosemirror.css from the prosemirror-view package."),Kx=!0}}function Qx(s,e){let t=e.startContainer,n=e.startOffset,i=e.endContainer,r=e.endOffset,o=s.domAtPos(s.state.selection.anchor);return Ef(o.node,o.offset,i,r)&&([t,n,i,r]=[i,r,t,n]),{anchorNode:t,anchorOffset:n,focusNode:i,focusOffset:r}}function eG(s,e){if(e.getComposedRanges){let i=e.getComposedRanges(s.root)[0];if(i)return Qx(s,i)}let t;function n(i){i.preventDefault(),i.stopImmediatePropagation(),t=i.getTargetRanges()[0]}return s.dom.addEventListener("beforeinput",n,!0),document.execCommand("indent"),s.dom.removeEventListener("beforeinput",n,!0),t?Qx(s,t):null}function tG(s,e){for(let t=e.parentNode;t&&t!=s.dom;t=t.parentNode){let n=s.docView.nearestDesc(t,!0);if(n&&n.node.isBlock)return t}return null}function sG(s,e){var t;let{focusNode:n,focusOffset:i}=s.domSelectionRange();for(let r of e)if(((t=r.parentNode)===null||t===void 0?void 0:t.nodeName)=="TR"){let o=r.nextSibling;for(;o&&o.nodeName!="TD"&&o.nodeName!="TH";)o=o.nextSibling;if(o){let a=o;for(;;){let c=a.firstChild;if(!c||c.nodeType!=1||c.contentEditable=="false"||/^(BR|IMG)$/.test(c.nodeName))break;a=c}a.insertBefore(r,a.firstChild),n==r&&s.domSelection().collapse(r,i)}else r.parentNode.removeChild(r)}}function nG(s,e,t){let{node:n,fromOffset:i,toOffset:r,from:o,to:a}=s.docView.parseRange(e,t),c=s.domSelectionRange(),l,u=c.anchorNode;if(u&&s.dom.contains(u.nodeType==1?u:u.parentNode)&&(l=[{node:u,offset:c.anchorOffset}],Z0(c)||l.push({node:c.focusNode,offset:c.focusOffset})),vi&&s.input.lastKeyCode===8)for(let g=r;g>i;g--){let y=n.childNodes[g-1],b=y.pmViewDesc;if(y.nodeName=="BR"&&!b){r=g;break}if(!b||b.size)break}let h=s.state.doc,d=s.someProp("domParser")||Av.fromSchema(s.state.schema),p=h.resolve(o),m=null,v=d.parse(n,{topNode:p.parent,topMatch:p.parent.contentMatchAt(p.index()),topOpen:!0,from:i,to:r,preserveWhitespace:p.parent.type.whitespace=="pre"?"full":!0,findPositions:l,ruleFromNode:iG,context:p});if(l&&l[0].pos!=null){let g=l[0].pos,y=l[1]&&l[1].pos;y==null&&(y=g),m={anchor:g+o,head:y+o}}return{doc:v,sel:m,from:o,to:a}}function iG(s){let e=s.pmViewDesc;if(e)return e.parseRule();if(s.nodeName=="BR"&&s.parentNode){if(Li&&/^(ul|ol)$/i.test(s.parentNode.nodeName)){let t=document.createElement("div");return t.appendChild(document.createElement("li")),{skip:t}}else if(s.parentNode.lastChild==s||Li&&/^(tr|table)$/i.test(s.parentNode.nodeName))return{ignore:!0}}else if(s.nodeName=="IMG"&&s.getAttribute("mark-placeholder"))return{ignore:!0};return null}const rG=/^(a|abbr|acronym|b|bd[io]|big|br|button|cite|code|data(list)?|del|dfn|em|i|img|ins|kbd|label|map|mark|meter|output|q|ruby|s|samp|small|span|strong|su[bp]|time|u|tt|var)$/i;function oG(s,e,t,n,i){let r=s.input.compositionPendingChanges||(s.composing?s.input.compositionID:0);if(s.input.compositionPendingChanges=0,e<0){let T=s.input.lastSelectionTime>Date.now()-50?s.input.lastSelectionOrigin:null,k=EE(s,T);if(k&&!s.state.selection.eq(k)){if(vi&&pc&&s.input.lastKeyCode===13&&Date.now()-100<s.input.lastKeyCodeTime&&s.someProp("handleKeyDown",M=>M(s,Ih(13,"Enter"))))return;let A=s.state.tr.setSelection(k);T=="pointer"?A.setMeta("pointer",!0):T=="key"&&A.scrollIntoView(),r&&A.setMeta("composition",r),s.dispatch(A)}return}let o=s.state.doc.resolve(e),a=o.sharedDepth(t);e=o.before(a+1),t=s.state.doc.resolve(t).after(a+1);let c=s.state.selection,l=nG(s,e,t),u=s.state.doc,h=u.slice(l.from,l.to),d,p;s.input.lastKeyCode===8&&Date.now()-100<s.input.lastKeyCodeTime?(d=s.state.selection.to,p="end"):(d=s.state.selection.from,p="start"),s.input.lastKeyCode=null;let m=cG(h.content,l.doc.content,l.from,d,p);if(m&&s.input.domChangeCount++,(tm&&s.input.lastIOSEnter>Date.now()-225||pc)&&i.some(T=>T.nodeType==1&&!rG.test(T.nodeName))&&(!m||m.endA>=m.endB)&&s.someProp("handleKeyDown",T=>T(s,Ih(13,"Enter")))){s.input.lastIOSEnter=0;return}if(!m)if(n&&c instanceof _t&&!c.empty&&c.$head.sameParent(c.$anchor)&&!s.composing&&!(l.sel&&l.sel.anchor!=l.sel.head))m={start:c.from,endA:c.to,endB:c.to};else{if(l.sel){let T=Xx(s,s.state.doc,l.sel);if(T&&!T.eq(s.state.selection)){let k=s.state.tr.setSelection(T);r&&k.setMeta("composition",r),s.dispatch(k)}}return}s.state.selection.from<s.state.selection.to&&m.start==m.endB&&s.state.selection instanceof _t&&(m.start>s.state.selection.from&&m.start<=s.state.selection.from+2&&s.state.selection.from>=l.from?m.start=s.state.selection.from:m.endA<s.state.selection.to&&m.endA>=s.state.selection.to-2&&s.state.selection.to<=l.to&&(m.endB+=s.state.selection.to-m.endA,m.endA=s.state.selection.to)),yr&&nh<=11&&m.endB==m.start+1&&m.endA==m.start&&m.start>l.from&&l.doc.textBetween(m.start-l.from-1,m.start-l.from+1)=="  "&&(m.start--,m.endA--,m.endB--);let v=l.doc.resolveNoCache(m.start-l.from),g=l.doc.resolveNoCache(m.endB-l.from),y=u.resolve(m.start),b=v.sameParent(g)&&v.parent.inlineContent&&y.end()>=m.endA;if((tm&&s.input.lastIOSEnter>Date.now()-225&&(!b||i.some(T=>T.nodeName=="DIV"||T.nodeName=="P"))||!b&&v.pos<l.doc.content.size&&(!v.sameParent(g)||!v.parent.inlineContent)&&v.pos<g.pos&&!/\S/.test(l.doc.textBetween(v.pos,g.pos,"","")))&&s.someProp("handleKeyDown",T=>T(s,Ih(13,"Enter")))){s.input.lastIOSEnter=0;return}if(s.state.selection.anchor>m.start&&lG(u,m.start,m.endA,v,g)&&s.someProp("handleKeyDown",T=>T(s,Ih(8,"Backspace")))){pc&&vi&&s.domObserver.suppressSelectionUpdates();return}vi&&m.endB==m.start&&(s.input.lastChromeDelete=Date.now()),pc&&!b&&v.start()!=g.start()&&g.parentOffset==0&&v.depth==g.depth&&l.sel&&l.sel.anchor==l.sel.head&&l.sel.head==m.endA&&(m.endB-=2,g=l.doc.resolveNoCache(m.endB-l.from),setTimeout(()=>{s.someProp("handleKeyDown",function(T){return T(s,Ih(13,"Enter"))})},20));let _=m.start,w=m.endA,S=T=>{let k=T||s.state.tr.replace(_,w,l.doc.slice(m.start-l.from,m.endB-l.from));if(l.sel){let A=Xx(s,k.doc,l.sel);A&&!(vi&&s.composing&&A.empty&&(m.start!=m.endB||s.input.lastChromeDelete<Date.now()-100)&&(A.head==_||A.head==k.mapping.map(w)-1)||yr&&A.empty&&A.head==_)&&k.setSelection(A)}return r&&k.setMeta("composition",r),k.scrollIntoView()},C;if(b)if(v.pos==g.pos){yr&&nh<=11&&v.parentOffset==0&&(s.domObserver.suppressSelectionUpdates(),setTimeout(()=>Sc(s),20));let T=S(s.state.tr.delete(_,w)),k=u.resolve(m.start).marksAcross(u.resolve(m.endA));k&&T.ensureMarks(k),s.dispatch(T)}else if(m.endA==m.endB&&(C=aG(v.parent.content.cut(v.parentOffset,g.parentOffset),y.parent.content.cut(y.parentOffset,m.endA-y.start())))){let T=S(s.state.tr);C.type=="add"?T.addMark(_,w,C.mark):T.removeMark(_,w,C.mark),s.dispatch(T)}else if(v.parent.child(v.index()).isText&&v.index()==g.index()-(g.textOffset?0:1)){let T=v.parent.textBetween(v.parentOffset,g.parentOffset),k=()=>S(s.state.tr.insertText(T,_,w));s.someProp("handleTextInput",A=>A(s,_,w,T,k))||s.dispatch(k())}else s.dispatch(S());else s.dispatch(S())}function Xx(s,e,t){return Math.max(t.anchor,t.head)>e.content.size?null:ME(s,e.resolve(t.anchor),e.resolve(t.head))}function aG(s,e){let t=s.firstChild.marks,n=e.firstChild.marks,i=t,r=n,o,a,c;for(let u=0;u<n.length;u++)i=n[u].removeFromSet(i);for(let u=0;u<t.length;u++)r=t[u].removeFromSet(r);if(i.length==1&&r.length==0)a=i[0],o="add",c=u=>u.mark(a.addToSet(u.marks));else if(i.length==0&&r.length==1)a=r[0],o="remove",c=u=>u.mark(a.removeFromSet(u.marks));else return null;let l=[];for(let u=0;u<e.childCount;u++)l.push(c(e.child(u)));if(Fe.from(l).eq(s))return{mark:a,type:o}}function lG(s,e,t,n,i){if(t-e<=i.pos-n.pos||vC(n,!0,!1)<i.pos)return!1;let r=s.resolve(e);if(!n.parent.isTextblock){let a=r.nodeAfter;return a!=null&&t==e+a.nodeSize}if(r.parentOffset<r.parent.content.size||!r.parent.isTextblock)return!1;let o=s.resolve(vC(r,!0,!0));return!o.parent.isTextblock||o.pos>t||vC(o,!0,!1)<t?!1:n.parent.content.cut(n.parentOffset).eq(o.parent.content)}function vC(s,e,t){let n=s.depth,i=e?s.end():s.pos;for(;n>0&&(e||s.indexAfter(n)==s.node(n).childCount);)n--,i++,e=!1;if(t){let r=s.node(n).maybeChild(s.indexAfter(n));for(;r&&!r.isLeaf;)r=r.firstChild,i++}return i}function cG(s,e,t,n,i){let r=s.findDiffStart(e,t);if(r==null)return null;let{a:o,b:a}=s.findDiffEnd(e,t+s.size,t+e.size);if(i=="end"){let c=Math.max(0,r-Math.min(o,a));n-=o+c-r}if(o<r&&s.size<e.size){let c=n<=r&&n>=o?r-n:0;r-=c,r&&r<e.size&&Yx(e.textBetween(r-1,r+1))&&(r+=c?1:-1),a=r+(a-o),o=r}else if(a<r){let c=n<=r&&n>=a?r-n:0;r-=c,r&&r<s.size&&Yx(s.textBetween(r-1,r+1))&&(r+=c?1:-1),o=r+(o-a),a=r}return{start:r,endA:o,endB:a}}function Yx(s){if(s.length!=2)return!1;let e=s.charCodeAt(0),t=s.charCodeAt(1);return e>=56320&&e<=57343&&t>=55296&&t<=56319}class KP{constructor(e,t){this._root=null,this.focused=!1,this.trackWrites=null,this.mounted=!1,this.markCursor=null,this.cursorWrapper=null,this.lastSelectedViewDesc=void 0,this.input=new TV,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=t,this.state=t.state,this.directPlugins=t.plugins||[],this.directPlugins.forEach(sI),this.dispatch=this.dispatch.bind(this),this.dom=e&&e.mount||document.createElement("div"),e&&(e.appendChild?e.appendChild(this.dom):typeof e=="function"?e(this.dom):e.mount&&(this.mounted=!0)),this.editable=eI(this),Zx(this),this.nodeViews=tI(this),this.docView=Lx(this.state.doc,Jx(this),mC(this),this.dom,this),this.domObserver=new JV(this,(n,i,r,o)=>oG(this,n,i,r,o)),this.domObserver.start(),AV(this),this.updatePluginViews()}get composing(){return this.input.composing}get props(){if(this._props.state!=this.state){let e=this._props;this._props={};for(let t in e)this._props[t]=e[t];this._props.state=this.state}return this._props}update(e){e.handleDOMEvents!=this._props.handleDOMEvents&&G1(this);let t=this._props;this._props=e,e.plugins&&(e.plugins.forEach(sI),this.directPlugins=e.plugins),this.updateStateInner(e.state,t)}setProps(e){let t={};for(let n in this._props)t[n]=this._props[n];t.state=this.state;for(let n in e)t[n]=e[n];this.update(t)}updateState(e){this.updateStateInner(e,this._props)}updateStateInner(e,t){var n;let i=this.state,r=!1,o=!1;e.storedMarks&&this.composing&&(UP(this),o=!0),this.state=e;let a=i.plugins!=e.plugins||this._props.plugins!=t.plugins;if(a||this._props.plugins!=t.plugins||this._props.nodeViews!=t.nodeViews){let p=tI(this);hG(p,this.nodeViews)&&(this.nodeViews=p,r=!0)}(a||t.handleDOMEvents!=this._props.handleDOMEvents)&&G1(this),this.editable=eI(this),Zx(this);let c=mC(this),l=Jx(this),u=i.plugins!=e.plugins&&!i.doc.eq(e.doc)?"reset":e.scrollToSelection>i.scrollToSelection?"to selection":"preserve",h=r||!this.docView.matchesNode(e.doc,l,c);(h||!e.selection.eq(i.selection))&&(o=!0);let d=u=="preserve"&&o&&this.dom.style.overflowAnchor==null&&H7(this);if(o){this.domObserver.stop();let p=h&&(yr||vi)&&!this.composing&&!i.selection.empty&&!e.selection.empty&&uG(i.selection,e.selection);if(h){let m=vi?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=HV(this)),(r||!this.docView.update(e.doc,l,c,this))&&(this.docView.updateOuterDeco(l),this.docView.destroy(),this.docView=Lx(e.doc,l,c,this.dom,this)),m&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(p=!0)}p||!(this.input.mouseDown&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&uV(this))?Sc(this,p):(xP(this,e.selection),this.domObserver.setCurSelection()),this.domObserver.start()}this.updatePluginViews(i),!((n=this.dragging)===null||n===void 0)&&n.node&&!i.doc.eq(e.doc)&&this.updateDraggedNode(this.dragging,i),u=="reset"?this.dom.scrollTop=0:u=="to selection"?this.scrollToSelection():d&&U7(d)}scrollToSelection(){let e=this.domSelectionRange().focusNode;if(!(!e||!this.dom.contains(e.nodeType==1?e:e.parentNode))){if(!this.someProp("handleScrollToSelection",t=>t(this)))if(this.state.selection instanceof vt){let t=this.docView.domAfterPos(this.state.selection.from);t.nodeType==1&&Ax(this,t.getBoundingClientRect(),e)}else Ax(this,this.coordsAtPos(this.state.selection.head,1),e)}}destroyPluginViews(){let e;for(;e=this.pluginViews.pop();)e.destroy&&e.destroy()}updatePluginViews(e){if(!e||e.plugins!=this.state.plugins||this.directPlugins!=this.prevDirectPlugins){this.prevDirectPlugins=this.directPlugins,this.destroyPluginViews();for(let t=0;t<this.directPlugins.length;t++){let n=this.directPlugins[t];n.spec.view&&this.pluginViews.push(n.spec.view(this))}for(let t=0;t<this.state.plugins.length;t++){let n=this.state.plugins[t];n.spec.view&&this.pluginViews.push(n.spec.view(this))}}else for(let t=0;t<this.pluginViews.length;t++){let n=this.pluginViews[t];n.update&&n.update(this,e)}}updateDraggedNode(e,t){let n=e.node,i=-1;if(n.from<this.state.doc.content.size&&this.state.doc.nodeAt(n.from)==n.node)i=n.from;else{let r=n.from+(this.state.doc.content.size-t.doc.content.size);(r>0&&r<this.state.doc.content.size&&this.state.doc.nodeAt(r))==n.node&&(i=r)}this.dragging=new zP(e.slice,e.move,i<0?void 0:vt.create(this.state.doc,i))}someProp(e,t){let n=this._props&&this._props[e],i;if(n!=null&&(i=t?t(n):n))return i;for(let o=0;o<this.directPlugins.length;o++){let a=this.directPlugins[o].props[e];if(a!=null&&(i=t?t(a):a))return i}let r=this.state.plugins;if(r)for(let o=0;o<r.length;o++){let a=r[o].props[e];if(a!=null&&(i=t?t(a):a))return i}}hasFocus(){if(yr){let e=this.root.activeElement;if(e==this.dom)return!0;if(!e||!this.dom.contains(e))return!1;for(;e&&this.dom!=e&&this.dom.contains(e);){if(e.contentEditable=="false")return!1;e=e.parentElement}return!0}return this.root.activeElement==this.dom}focus(){this.domObserver.stop(),this.editable&&W7(this.dom),Sc(this),this.domObserver.start()}get root(){let e=this._root;if(e==null){for(let t=this.dom.parentNode;t;t=t.parentNode)if(t.nodeType==9||t.nodeType==11&&t.host)return t.getSelection||(Object.getPrototypeOf(t).getSelection=()=>t.ownerDocument.getSelection()),this._root=t}return e||document}updateRoot(){this._root=null}posAtCoords(e){return q7(this,e)}coordsAtPos(e,t=1){return SP(this,e,t)}domAtPos(e,t=0){return this.docView.domFromPos(e,t)}nodeDOM(e){let t=this.docView.descAt(e);return t?t.nodeDOM:null}posAtDOM(e,t,n=-1){let i=this.docView.posFromDOM(e,t,n);if(i==null)throw new RangeError("DOM position not inside the editor");return i}endOfTextblock(e,t){return J7(this,t||this.state,e)}pasteHTML(e,t){return Yv(this,"",e,!1,t||new ClipboardEvent("paste"))}pasteText(e,t){return Yv(this,e,null,!0,t||new ClipboardEvent("paste"))}serializeForClipboard(e){return xE(this,e)}destroy(){this.docView&&(EV(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],mC(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,I7())}get isDestroyed(){return this.docView==null}dispatchEvent(e){return xV(this,e)}domSelectionRange(){let e=this.domSelection();return e?Li&&this.root.nodeType===11&&D7(this.dom.ownerDocument)==this.dom&&eG(this,e)||e:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}KP.prototype.dispatch=function(s){let e=this._props.dispatchTransaction;e?e.call(this,s):this.updateState(this.state.apply(s))};function Jx(s){let e=Object.create(null);return e.class="ProseMirror",e.contenteditable=String(s.editable),s.someProp("attributes",t=>{if(typeof t=="function"&&(t=t(s.state)),t)for(let n in t)n=="class"?e.class+=" "+t[n]:n=="style"?e.style=(e.style?e.style+";":"")+t[n]:!e[n]&&n!="contenteditable"&&n!="nodeName"&&(e[n]=String(t[n]))}),e.translate||(e.translate="no"),[Mi.node(0,s.state.doc.content.size,e)]}function Zx(s){if(s.markCursor){let e=document.createElement("img");e.className="ProseMirror-separator",e.setAttribute("mark-placeholder","true"),e.setAttribute("alt",""),s.cursorWrapper={dom:e,deco:Mi.widget(s.state.selection.from,e,{raw:!0,marks:s.markCursor})}}else s.cursorWrapper=null}function eI(s){return!s.someProp("editable",e=>e(s.state)===!1)}function uG(s,e){let t=Math.min(s.$anchor.sharedDepth(s.head),e.$anchor.sharedDepth(e.head));return s.$anchor.start(t)!=e.$anchor.start(t)}function tI(s){let e=Object.create(null);function t(n){for(let i in n)Object.prototype.hasOwnProperty.call(e,i)||(e[i]=n[i])}return s.someProp("nodeViews",t),s.someProp("markViews",t),e}function hG(s,e){let t=0,n=0;for(let i in s){if(s[i]!=e[i])return!0;t++}for(let i in e)n++;return t!=n}function sI(s){if(s.spec.state||s.spec.filterTransaction||s.spec.appendTransaction)throw new RangeError("Plugins passed directly to the view must not have a state component")}var ah={8:"Backspace",9:"Tab",10:"Enter",12:"NumLock",13:"Enter",16:"Shift",17:"Control",18:"Alt",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",44:"PrintScreen",45:"Insert",46:"Delete",59:";",61:"=",91:"Meta",92:"Meta",106:"*",107:"+",108:",",109:"-",110:".",111:"/",144:"NumLock",145:"ScrollLock",160:"Shift",161:"Shift",162:"Control",163:"Control",164:"Alt",165:"Alt",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"},xw={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},dG=typeof navigator<"u"&&/Mac/.test(navigator.platform),fG=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(var pi=0;pi<10;pi++)ah[48+pi]=ah[96+pi]=String(pi);for(var pi=1;pi<=24;pi++)ah[pi+111]="F"+pi;for(var pi=65;pi<=90;pi++)ah[pi]=String.fromCharCode(pi+32),xw[pi]=String.fromCharCode(pi);for(var yC in ah)xw.hasOwnProperty(yC)||(xw[yC]=ah[yC]);function pG(s){var e=dG&&s.metaKey&&s.shiftKey&&!s.ctrlKey&&!s.altKey||fG&&s.shiftKey&&s.key&&s.key.length==1||s.key=="Unidentified",t=!e&&s.key||(s.shiftKey?xw:ah)[s.keyCode]||s.key||"Unidentified";return t=="Esc"&&(t="Escape"),t=="Del"&&(t="Delete"),t=="Left"&&(t="ArrowLeft"),t=="Up"&&(t="ArrowUp"),t=="Right"&&(t="ArrowRight"),t=="Down"&&(t="ArrowDown"),t}const gG=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),mG=typeof navigator<"u"&&/Win/.test(navigator.platform);function vG(s){let e=s.split(/-(?!$)/),t=e[e.length-1];t=="Space"&&(t=" ");let n,i,r,o;for(let a=0;a<e.length-1;a++){let c=e[a];if(/^(cmd|meta|m)$/i.test(c))o=!0;else if(/^a(lt)?$/i.test(c))n=!0;else if(/^(c|ctrl|control)$/i.test(c))i=!0;else if(/^s(hift)?$/i.test(c))r=!0;else if(/^mod$/i.test(c))gG?o=!0:i=!0;else throw new Error("Unrecognized modifier name: "+c)}return n&&(t="Alt-"+t),i&&(t="Ctrl-"+t),o&&(t="Meta-"+t),r&&(t="Shift-"+t),t}function yG(s){let e=Object.create(null);for(let t in s)e[vG(t)]=s[t];return e}function bC(s,e,t=!0){return e.altKey&&(s="Alt-"+s),e.ctrlKey&&(s="Ctrl-"+s),e.metaKey&&(s="Meta-"+s),t&&e.shiftKey&&(s="Shift-"+s),s}function bG(s){return new $s({props:{handleKeyDown:QP(s)}})}function QP(s){let e=yG(s);return function(t,n){let i=pG(n),r,o=e[bC(i,n)];if(o&&o(t.state,t.dispatch,t))return!0;if(i.length==1&&i!=" "){if(n.shiftKey){let a=e[bC(i,n,!1)];if(a&&a(t.state,t.dispatch,t))return!0}if((n.altKey||n.metaKey||n.ctrlKey)&&!(mG&&n.ctrlKey&&n.altKey)&&(r=ah[n.keyCode])&&r!=i){let a=e[bC(r,n)];if(a&&a(t.state,t.dispatch,t))return!0}}return!1}}var _G=Object.defineProperty,DE=(s,e)=>{for(var t in e)_G(s,t,{get:e[t],enumerable:!0})};function sk(s){const{state:e,transaction:t}=s;let{selection:n}=t,{doc:i}=t,{storedMarks:r}=t;return{...e,apply:e.apply.bind(e),applyTransaction:e.applyTransaction.bind(e),plugins:e.plugins,schema:e.schema,reconfigure:e.reconfigure.bind(e),toJSON:e.toJSON.bind(e),get storedMarks(){return r},get selection(){return n},get doc(){return i},get tr(){return n=t.selection,i=t.doc,r=t.storedMarks,t}}}var nk=class{constructor(e){this.editor=e.editor,this.rawCommands=this.editor.extensionManager.commands,this.customState=e.state}get hasCustomState(){return!!this.customState}get state(){return this.customState||this.editor.state}get commands(){const{rawCommands:e,editor:t,state:n}=this,{view:i}=t,{tr:r}=n,o=this.buildProps(r);return Object.fromEntries(Object.entries(e).map(([a,c])=>[a,(...u)=>{const h=c(...u)(o);return!r.getMeta("preventDispatch")&&!this.hasCustomState&&i.dispatch(r),h}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(e,t=!0){const{rawCommands:n,editor:i,state:r}=this,{view:o}=i,a=[],c=!!e,l=e||r.tr,u=()=>(!c&&t&&!l.getMeta("preventDispatch")&&!this.hasCustomState&&o.dispatch(l),a.every(d=>d===!0)),h={...Object.fromEntries(Object.entries(n).map(([d,p])=>[d,(...v)=>{const g=this.buildProps(l,t),y=p(...v)(g);return a.push(y),h}])),run:u};return h}createCan(e){const{rawCommands:t,state:n}=this,i=!1,r=e||n.tr,o=this.buildProps(r,i);return{...Object.fromEntries(Object.entries(t).map(([c,l])=>[c,(...u)=>l(...u)({...o,dispatch:void 0})])),chain:()=>this.createChain(r,i)}}buildProps(e,t=!0){const{rawCommands:n,editor:i,state:r}=this,{view:o}=i,a={tr:e,editor:i,view:o,state:sk({state:r,transaction:e}),dispatch:t?()=>{}:void 0,chain:()=>this.createChain(e,t),can:()=>this.createCan(e),get commands(){return Object.fromEntries(Object.entries(n).map(([c,l])=>[c,(...u)=>l(...u)(a)]))}};return a}},XP={};DE(XP,{blur:()=>SG,clearContent:()=>wG,clearNodes:()=>kG,command:()=>CG,createParagraphNear:()=>TG,cut:()=>AG,deleteCurrentNode:()=>EG,deleteNode:()=>MG,deleteRange:()=>xG,deleteSelection:()=>LG,enter:()=>PG,exitCode:()=>OG,extendMarkRange:()=>DG,first:()=>NG,focus:()=>FG,forEach:()=>$G,insertContent:()=>HG,insertContentAt:()=>zG,joinBackward:()=>GG,joinDown:()=>VG,joinForward:()=>qG,joinItemBackward:()=>KG,joinItemForward:()=>QG,joinTextblockBackward:()=>XG,joinTextblockForward:()=>YG,joinUp:()=>jG,keyboardShortcut:()=>ZG,lift:()=>eq,liftEmptyBlock:()=>tq,liftListItem:()=>sq,newlineInCode:()=>nq,resetAttributes:()=>iq,scrollIntoView:()=>rq,selectAll:()=>oq,selectNodeBackward:()=>aq,selectNodeForward:()=>lq,selectParentNode:()=>cq,selectTextblockEnd:()=>uq,selectTextblockStart:()=>hq,setContent:()=>dq,setMark:()=>Pq,setMeta:()=>Oq,setNode:()=>Dq,setNodeSelection:()=>Nq,setTextDirection:()=>Bq,setTextSelection:()=>Fq,sinkListItem:()=>$q,splitBlock:()=>Hq,splitListItem:()=>Uq,toggleList:()=>zq,toggleMark:()=>jq,toggleNode:()=>Vq,toggleWrap:()=>Gq,undoInputRule:()=>qq,unsetAllMarks:()=>Kq,unsetMark:()=>Qq,unsetTextDirection:()=>Xq,updateAttributes:()=>Yq,wrapIn:()=>Jq,wrapInList:()=>Zq});var SG=()=>({editor:s,view:e})=>(requestAnimationFrame(()=>{var t;s.isDestroyed||(e.dom.blur(),(t=window==null?void 0:window.getSelection())==null||t.removeAllRanges())}),!0),wG=(s=!0)=>({commands:e})=>e.setContent("",{emitUpdate:s}),kG=()=>({state:s,tr:e,dispatch:t})=>{const{selection:n}=e,{ranges:i}=n;return t&&i.forEach(({$from:r,$to:o})=>{s.doc.nodesBetween(r.pos,o.pos,(a,c)=>{if(a.type.isText)return;const{doc:l,mapping:u}=e,h=l.resolve(u.map(c)),d=l.resolve(u.map(c+a.nodeSize)),p=h.blockRange(d);if(!p)return;const m=fm(p);if(a.type.isTextblock){const{defaultType:v}=h.parent.contentMatchAt(h.index());e.setNodeMarkup(p.start,v)}(m||m===0)&&e.lift(p,m)})}),!0},CG=s=>e=>s(e),TG=()=>({state:s,dispatch:e})=>uP(s,e),AG=(s,e)=>({editor:t,tr:n})=>{const{state:i}=t,r=i.doc.slice(s.from,s.to);n.deleteRange(s.from,s.to);const o=n.mapping.map(e);return n.insert(o,r.content),n.setSelection(new _t(n.doc.resolve(Math.max(o-1,0)))),!0},EG=()=>({tr:s,dispatch:e})=>{const{selection:t}=s,n=t.$anchor.node();if(n.content.size>0)return!1;const i=s.selection.$anchor;for(let r=i.depth;r>0;r-=1)if(i.node(r).type===n.type){if(e){const a=i.before(r),c=i.after(r);s.delete(a,c).scrollIntoView()}return!0}return!1};function wn(s,e){if(typeof s=="string"){if(!e.nodes[s])throw Error(`There is no node type named '${s}'. Maybe you forgot to add the extension?`);return e.nodes[s]}return s}var MG=s=>({tr:e,state:t,dispatch:n})=>{const i=wn(s,t.schema),r=e.selection.$anchor;for(let o=r.depth;o>0;o-=1)if(r.node(o).type===i){if(n){const c=r.before(o),l=r.after(o);e.delete(c,l).scrollIntoView()}return!0}return!1},xG=s=>({tr:e,dispatch:t})=>{const{from:n,to:i}=s;return t&&e.delete(n,i),!0},IG=s=>s.content?/^text(\*|\+)/.test(s.content):!1,nI=(s,e,t)=>{if(!s.parent.isInline||t==="left"&&s.pos>s.start()||t==="right"&&s.pos<s.end())return s.pos;const n=e.nodes[s.parent.type.name].spec;return IG(n)?t==="left"?s.start()-1:s.end()+1:s.pos},RG=(s,e,t)=>{const n=nI(s,t,"left"),i=nI(e,t,"right");return{from:n,to:i}},LG=()=>({state:s,dispatch:e})=>{const{$from:t,$to:n}=s.selection;if(s.selection.empty)return!1;const{from:i,to:r}=RG(t,n,s.schema);return e&&(s.tr.deleteRange(i,r).scrollIntoView(),e(s.tr)),!0},PG=()=>({commands:s})=>s.keyboardShortcut("Enter"),OG=()=>({state:s,dispatch:e})=>g7(s,e);function NE(s){return Object.prototype.toString.call(s)==="[object RegExp]"}function Iw(s,e,t={strict:!0}){const n=Object.keys(e);return n.length?n.every(i=>t.strict?e[i]===s[i]:NE(e[i])?e[i].test(s[i]):e[i]===s[i]):!0}function YP(s,e,t={}){return s.find(n=>n.type===e&&Iw(Object.fromEntries(Object.keys(t).map(i=>[i,n.attrs[i]])),t))}function iI(s,e,t={}){return!!YP(s,e,t)}function BE(s,e,t){if(!s||!e)return;let n=s.parent.childAfter(s.parentOffset);if((!n.node||!n.node.marks.some(l=>l.type===e))&&(n=s.parent.childBefore(s.parentOffset)),!n.node||!n.node.marks.some(l=>l.type===e))return;if(!t){const l=n.node.marks.find(u=>u.type===e);l&&(t=l.attrs)}if(!YP([...n.node.marks],e,t))return;let r=n.index,o=s.start()+n.offset,a=r+1,c=o+n.node.nodeSize;for(;r>0&&iI([...s.parent.child(r-1).marks],e,t);)r-=1,o-=s.parent.child(r).nodeSize;for(;a<s.parent.childCount&&iI([...s.parent.child(a).marks],e,t);)c+=s.parent.child(a).nodeSize,a+=1;return{from:o,to:c}}function Ic(s,e){if(typeof s=="string"){if(!e.marks[s])throw Error(`There is no mark type named '${s}'. Maybe you forgot to add the extension?`);return e.marks[s]}return s}var DG=(s,e)=>({tr:t,state:n,dispatch:i})=>{const r=Ic(s,n.schema),{doc:o,selection:a}=t,{$from:c,from:l,to:u}=a;if(i){const h=BE(c,r,e);if(h&&h.from<=l&&h.to>=u){const d=_t.create(o,h.from,h.to);t.setSelection(d)}}return!0},NG=s=>e=>{const t=typeof s=="function"?s(e):s;for(let n=0;n<t.length;n+=1)if(t[n](e))return!0;return!1};function JP(s){return s instanceof _t}function Fh(s=0,e=0,t=0){return Math.min(Math.max(s,e),t)}function ZP(s,e=null){if(!e)return null;const t=Ft.atStart(s),n=Ft.atEnd(s);if(e==="start"||e===!0)return t;if(e==="end")return n;const i=t.from,r=n.to;return e==="all"?_t.create(s,Fh(0,i,r),Fh(s.content.size,i,r)):_t.create(s,Fh(e,i,r),Fh(e,i,r))}function rI(){return navigator.platform==="Android"||/android/i.test(navigator.userAgent)}function Rw(){return["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"].includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"ontouchend"in document}function BG(){return typeof navigator<"u"?/^((?!chrome|android).)*safari/i.test(navigator.userAgent):!1}var FG=(s=null,e={})=>({editor:t,view:n,tr:i,dispatch:r})=>{e={scrollIntoView:!0,...e};const o=()=>{(Rw()||rI())&&n.dom.focus(),BG()&&!Rw()&&!rI()&&n.dom.focus({preventScroll:!0}),requestAnimationFrame(()=>{t.isDestroyed||(n.focus(),e!=null&&e.scrollIntoView&&t.commands.scrollIntoView())})};try{if(n.hasFocus()&&s===null||s===!1)return!0}catch{return!1}if(r&&s===null&&!JP(t.state.selection))return o(),!0;const a=ZP(i.doc,s)||t.state.selection,c=t.state.selection.eq(a);return r&&(c||i.setSelection(a),c&&i.storedMarks&&i.setStoredMarks(i.storedMarks),o()),!0},$G=(s,e)=>t=>s.every((n,i)=>e(n,{...t,index:i})),HG=(s,e)=>({tr:t,commands:n})=>n.insertContentAt({from:t.selection.from,to:t.selection.to},s,e),eO=s=>{const e=s.childNodes;for(let t=e.length-1;t>=0;t-=1){const n=e[t];n.nodeType===3&&n.nodeValue&&/^(\n\s\s|\n)$/.test(n.nodeValue)?s.removeChild(n):n.nodeType===1&&eO(n)}return s};function I_(s){if(typeof window>"u")throw new Error("[tiptap error]: there is no window object available, so this function cannot be used");const e=`<body>${s}</body>`,t=new window.DOMParser().parseFromString(e,"text/html").body;return eO(t)}function Zv(s,e,t){if(s instanceof yc||s instanceof Fe)return s;t={slice:!0,parseOptions:{},...t};const n=typeof s=="object"&&s!==null,i=typeof s=="string";if(n)try{if(Array.isArray(s)&&s.length>0)return Fe.fromArray(s.map(a=>e.nodeFromJSON(a)));const o=e.nodeFromJSON(s);return t.errorOnInvalidContent&&o.check(),o}catch(r){if(t.errorOnInvalidContent)throw new Error("[tiptap error]: Invalid JSON content",{cause:r});return console.warn("[tiptap warn]: Invalid content.","Passed value:",s,"Error:",r),Zv("",e,t)}if(i){if(t.errorOnInvalidContent){let o=!1,a="";const c=new RL({topNode:e.spec.topNode,marks:e.spec.marks,nodes:e.spec.nodes.append({__tiptap__private__unknown__catch__all__node:{content:"inline*",group:"block",parseDOM:[{tag:"*",getAttrs:l=>(o=!0,a=typeof l=="string"?l:l.outerHTML,null)}]}})});if(t.slice?Av.fromSchema(c).parseSlice(I_(s),t.parseOptions):Av.fromSchema(c).parse(I_(s),t.parseOptions),t.errorOnInvalidContent&&o)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${a}`)})}const r=Av.fromSchema(e);return t.slice?r.parseSlice(I_(s),t.parseOptions).content:r.parse(I_(s),t.parseOptions)}return Zv("",e,t)}function UG(s,e,t){const n=s.steps.length-1;if(n<e)return;const i=s.steps[n];if(!(i instanceof Fo||i instanceof _r))return;const r=s.mapping.maps[n];let o=0;r.forEach((a,c,l,u)=>{o===0&&(o=u)}),s.setSelection(Ft.near(s.doc.resolve(o),t))}var WG=s=>!("type"in s),zG=(s,e,t)=>({tr:n,dispatch:i,editor:r})=>{var o;if(i){t={parseOptions:r.options.parseOptions,updateSelection:!0,applyInputRules:!1,applyPasteRules:!1,...t};let a;const c=g=>{r.emit("contentError",{editor:r,error:g,disableCollaboration:()=>{"collaboration"in r.storage&&typeof r.storage.collaboration=="object"&&r.storage.collaboration&&(r.storage.collaboration.isDisabled=!0)}})},l={preserveWhitespace:"full",...t.parseOptions};if(!t.errorOnInvalidContent&&!r.options.enableContentCheck&&r.options.emitContentError)try{Zv(e,r.schema,{parseOptions:l,errorOnInvalidContent:!0})}catch(g){c(g)}try{a=Zv(e,r.schema,{parseOptions:l,errorOnInvalidContent:(o=t.errorOnInvalidContent)!=null?o:r.options.enableContentCheck})}catch(g){return c(g),!1}let{from:u,to:h}=typeof s=="number"?{from:s,to:s}:{from:s.from,to:s.to},d=!0,p=!0;if((WG(a)?a:[a]).forEach(g=>{g.check(),d=d?g.isText&&g.marks.length===0:!1,p=p?g.isBlock:!1}),u===h&&p){const{parent:g}=n.doc.resolve(u);g.isTextblock&&!g.type.spec.code&&!g.childCount&&(u-=1,h+=1)}let v;if(d){if(Array.isArray(e))v=e.map(g=>g.text||"").join("");else if(e instanceof Fe){let g="";e.forEach(y=>{y.text&&(g+=y.text)}),v=g}else typeof e=="object"&&e&&e.text?v=e.text:v=e;n.insertText(v,u,h)}else{v=a;const g=n.doc.resolve(u),y=g.node(),b=g.parentOffset===0,_=y.isText||y.isTextblock,w=y.content.size>0;b&&_&&w&&p&&(u=Math.max(0,u-1)),n.replaceWith(u,h,v)}t.updateSelection&&UG(n,n.steps.length-1,-1),t.applyInputRules&&n.setMeta("applyInputRules",{from:u,text:v}),t.applyPasteRules&&n.setMeta("applyPasteRules",{from:u,text:v})}return!0},jG=()=>({state:s,dispatch:e})=>d7(s,e),VG=()=>({state:s,dispatch:e})=>f7(s,e),GG=()=>({state:s,dispatch:e})=>nP(s,e),qG=()=>({state:s,dispatch:e})=>aP(s,e),KG=()=>({state:s,dispatch:e,tr:t})=>{try{const n=Y0(s.doc,s.selection.$from.pos,-1);return n==null?!1:(t.join(n,2),e&&e(t),!0)}catch{return!1}},QG=()=>({state:s,dispatch:e,tr:t})=>{try{const n=Y0(s.doc,s.selection.$from.pos,1);return n==null?!1:(t.join(n,2),e&&e(t),!0)}catch{return!1}},XG=()=>({state:s,dispatch:e})=>u7(s,e),YG=()=>({state:s,dispatch:e})=>h7(s,e);function tO(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function JG(s){const e=s.split(/-(?!$)/);let t=e[e.length-1];t==="Space"&&(t=" ");let n,i,r,o;for(let a=0;a<e.length-1;a+=1){const c=e[a];if(/^(cmd|meta|m)$/i.test(c))o=!0;else if(/^a(lt)?$/i.test(c))n=!0;else if(/^(c|ctrl|control)$/i.test(c))i=!0;else if(/^s(hift)?$/i.test(c))r=!0;else if(/^mod$/i.test(c))Rw()||tO()?o=!0:i=!0;else throw new Error(`Unrecognized modifier name: ${c}`)}return n&&(t=`Alt-${t}`),i&&(t=`Ctrl-${t}`),o&&(t=`Meta-${t}`),r&&(t=`Shift-${t}`),t}var ZG=s=>({editor:e,view:t,tr:n,dispatch:i})=>{const r=JG(s).split(/-(?!$)/),o=r.find(l=>!["Alt","Ctrl","Meta","Shift"].includes(l)),a=new KeyboardEvent("keydown",{key:o==="Space"?" ":o,altKey:r.includes("Alt"),ctrlKey:r.includes("Ctrl"),metaKey:r.includes("Meta"),shiftKey:r.includes("Shift"),bubbles:!0,cancelable:!0}),c=e.captureTransaction(()=>{t.someProp("handleKeyDown",l=>l(t,a))});return c==null||c.steps.forEach(l=>{const u=l.map(n.mapping);u&&i&&n.maybeStep(u)}),!0};function lh(s,e,t={}){const{from:n,to:i,empty:r}=s.selection,o=e?wn(e,s.schema):null,a=[];s.doc.nodesBetween(n,i,(h,d)=>{if(h.isText)return;const p=Math.max(n,d),m=Math.min(i,d+h.nodeSize);a.push({node:h,from:p,to:m})});const c=i-n,l=a.filter(h=>o?o.name===h.node.type.name:!0).filter(h=>Iw(h.node.attrs,t,{strict:!1}));return r?!!l.length:l.reduce((h,d)=>h+d.to-d.from,0)>=c}var eq=(s,e={})=>({state:t,dispatch:n})=>{const i=wn(s,t.schema);return lh(t,i,e)?p7(t,n):!1},tq=()=>({state:s,dispatch:e})=>hP(s,e),sq=s=>({state:e,dispatch:t})=>{const n=wn(s,e.schema);return A7(n)(e,t)},nq=()=>({state:s,dispatch:e})=>cP(s,e);function ik(s,e){return e.nodes[s]?"node":e.marks[s]?"mark":null}function oI(s,e){const t=typeof e=="string"?[e]:e;return Object.keys(s).reduce((n,i)=>(t.includes(i)||(n[i]=s[i]),n),{})}var iq=(s,e)=>({tr:t,state:n,dispatch:i})=>{let r=null,o=null;const a=ik(typeof s=="string"?s:s.name,n.schema);if(!a)return!1;a==="node"&&(r=wn(s,n.schema)),a==="mark"&&(o=Ic(s,n.schema));let c=!1;return t.selection.ranges.forEach(l=>{n.doc.nodesBetween(l.$from.pos,l.$to.pos,(u,h)=>{r&&r===u.type&&(c=!0,i&&t.setNodeMarkup(h,void 0,oI(u.attrs,e))),o&&u.marks.length&&u.marks.forEach(d=>{o===d.type&&(c=!0,i&&t.addMark(h,h+u.nodeSize,o.create(oI(d.attrs,e))))})})}),c},rq=()=>({tr:s,dispatch:e})=>(e&&s.scrollIntoView(),!0),oq=()=>({tr:s,dispatch:e})=>{if(e){const t=new _c(s.doc);s.setSelection(t)}return!0},aq=()=>({state:s,dispatch:e})=>rP(s,e),lq=()=>({state:s,dispatch:e})=>lP(s,e),cq=()=>({state:s,dispatch:e})=>y7(s,e),uq=()=>({state:s,dispatch:e})=>S7(s,e),hq=()=>({state:s,dispatch:e})=>_7(s,e);function q1(s,e,t={},n={}){return Zv(s,e,{slice:!1,parseOptions:t,errorOnInvalidContent:n.errorOnInvalidContent})}var dq=(s,{errorOnInvalidContent:e,emitUpdate:t=!0,parseOptions:n={}}={})=>({editor:i,tr:r,dispatch:o,commands:a})=>{const{doc:c}=r;if(n.preserveWhitespace!=="full"){const l=q1(s,i.schema,n,{errorOnInvalidContent:e??i.options.enableContentCheck});return o&&r.replaceWith(0,c.content.size,l).setMeta("preventUpdate",!t),!0}return o&&r.setMeta("preventUpdate",!t),a.insertContentAt({from:0,to:c.content.size},s,{parseOptions:n,errorOnInvalidContent:e??i.options.enableContentCheck})};function sO(s,e){const t=Ic(e,s.schema),{from:n,to:i,empty:r}=s.selection,o=[];r?(s.storedMarks&&o.push(...s.storedMarks),o.push(...s.selection.$head.marks())):s.doc.nodesBetween(n,i,c=>{o.push(...c.marks)});const a=o.find(c=>c.type.name===t.name);return a?{...a.attrs}:{}}function nO(s,e){const t=new QL(s);return e.forEach(n=>{n.steps.forEach(i=>{t.step(i)})}),t}function fq(s){for(let e=0;e<s.edgeCount;e+=1){const{type:t}=s.edge(e);if(t.isTextblock&&!t.hasRequiredAttrs())return t}return null}function pq(s,e,t){const n=[];return s.nodesBetween(e.from,e.to,(i,r)=>{t(i)&&n.push({node:i,pos:r})}),n}function gq(s,e){for(let t=s.depth;t>0;t-=1){const n=s.node(t);if(e(n))return{pos:t>0?s.before(t):0,start:s.start(t),depth:t,node:n}}}function rk(s){return e=>gq(e.$from,s)}function ot(s,e,t){return s.config[e]===void 0&&s.parent?ot(s.parent,e,t):typeof s.config[e]=="function"?s.config[e].bind({...t,parent:s.parent?ot(s.parent,e,t):null}):s.config[e]}function FE(s){return s.map(e=>{const t={name:e.name,options:e.options,storage:e.storage},n=ot(e,"addExtensions",t);return n?[e,...FE(n())]:e}).flat(10)}function $E(s,e){const t=Of.fromSchema(e).serializeFragment(s),i=document.implementation.createHTMLDocument().createElement("div");return i.appendChild(t),i.innerHTML}function iO(s){return typeof s=="function"}function ns(s,e=void 0,...t){return iO(s)?e?s.bind(e)(...t):s(...t):s}function mq(s={}){return Object.keys(s).length===0&&s.constructor===Object}function sm(s){const e=s.filter(i=>i.type==="extension"),t=s.filter(i=>i.type==="node"),n=s.filter(i=>i.type==="mark");return{baseExtensions:e,nodeExtensions:t,markExtensions:n}}function rO(s){const e=[],{nodeExtensions:t,markExtensions:n}=sm(s),i=[...t,...n],r={default:null,validate:void 0,rendered:!0,renderHTML:null,parseHTML:null,keepOnSplit:!0,isRequired:!1},o=t.filter(l=>l.name!=="text").map(l=>l.name),a=n.map(l=>l.name),c=[...o,...a];return s.forEach(l=>{const u={name:l.name,options:l.options,storage:l.storage,extensions:i},h=ot(l,"addGlobalAttributes",u);if(!h)return;h().forEach(p=>{let m;Array.isArray(p.types)?m=p.types:p.types==="*"?m=c:p.types==="nodes"?m=o:p.types==="marks"?m=a:m=[],m.forEach(v=>{Object.entries(p.attributes).forEach(([g,y])=>{e.push({type:v,name:g,attribute:{...r,...y}})})})})}),i.forEach(l=>{const u={name:l.name,options:l.options,storage:l.storage},h=ot(l,"addAttributes",u);if(!h)return;const d=h();Object.entries(d).forEach(([p,m])=>{const v={...r,...m};typeof(v==null?void 0:v.default)=="function"&&(v.default=v.default()),v!=null&&v.isRequired&&(v==null?void 0:v.default)===void 0&&delete v.default,e.push({type:l.name,name:p,attribute:v})})}),e}function vq(s){const e=[];let t="",n=!1,i=!1,r=0;const o=s.length;for(let a=0;a<o;a+=1){const c=s[a];if(c==="'"&&!i){n=!n,t+=c;continue}if(c==='"'&&!n){i=!i,t+=c;continue}if(!n&&!i){if(c==="("){r+=1,t+=c;continue}if(c===")"&&r>0){r-=1,t+=c;continue}if(c===";"&&r===0){e.push(t),t="";continue}}t+=c}return t&&e.push(t),e}function aI(s){const e=[],t=vq(s||""),n=t.length;for(let i=0;i<n;i+=1){const r=t[i],o=r.indexOf(":");if(o===-1)continue;const a=r.slice(0,o).trim(),c=r.slice(o+1).trim();a&&c&&e.push([a,c])}return e}function Fs(...s){return s.filter(e=>!!e).reduce((e,t)=>{const n={...e};return Object.entries(t).forEach(([i,r])=>{if(!n[i]){n[i]=r;return}if(i==="class"){const a=r?String(r).split(" "):[],c=n[i]?n[i].split(" "):[],l=a.filter(u=>!c.includes(u));n[i]=[...c,...l].join(" ")}else if(i==="style"){const a=new Map([...aI(n[i]),...aI(r)]);n[i]=Array.from(a.entries()).map(([c,l])=>`${c}: ${l}`).join("; ")}else n[i]=r}),n},{})}function ey(s,e){return e.filter(t=>t.type===s.type.name).filter(t=>t.attribute.rendered).map(t=>t.attribute.renderHTML?t.attribute.renderHTML(s.attrs)||{}:{[t.name]:s.attrs[t.name]}).reduce((t,n)=>Fs(t,n),{})}function yq(s){return typeof s!="string"?s:s.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(s):s==="true"?!0:s==="false"?!1:s}function lI(s,e){return"style"in s?s:{...s,getAttrs:t=>{const n=s.getAttrs?s.getAttrs(t):s.attrs;if(n===!1)return!1;const i=e.reduce((r,o)=>{const a=o.attribute.parseHTML?o.attribute.parseHTML(t):yq(t.getAttribute(o.name));return a==null?r:{...r,[o.name]:a}},{});return{...n,...i}}}}function cI(s){return Object.fromEntries(Object.entries(s).filter(([e,t])=>e==="attrs"&&mq(t)?!1:t!=null))}function uI(s){var e,t;const n={};return!((e=s==null?void 0:s.attribute)!=null&&e.isRequired)&&"default"in((s==null?void 0:s.attribute)||{})&&(n.default=s.attribute.default),((t=s==null?void 0:s.attribute)==null?void 0:t.validate)!==void 0&&(n.validate=s.attribute.validate),[s.name,n]}function bq(s,e){var t;const n=rO(s),{nodeExtensions:i,markExtensions:r}=sm(s),o=(t=i.find(l=>ot(l,"topNode")))==null?void 0:t.name,a=Object.fromEntries(i.map(l=>{const u=n.filter(y=>y.type===l.name),h={name:l.name,options:l.options,storage:l.storage,editor:e},d=s.reduce((y,b)=>{const _=ot(b,"extendNodeSchema",h);return{...y,..._?_(l):{}}},{}),p=cI({...d,content:ns(ot(l,"content",h)),marks:ns(ot(l,"marks",h)),group:ns(ot(l,"group",h)),inline:ns(ot(l,"inline",h)),atom:ns(ot(l,"atom",h)),selectable:ns(ot(l,"selectable",h)),draggable:ns(ot(l,"draggable",h)),code:ns(ot(l,"code",h)),whitespace:ns(ot(l,"whitespace",h)),linebreakReplacement:ns(ot(l,"linebreakReplacement",h)),defining:ns(ot(l,"defining",h)),isolating:ns(ot(l,"isolating",h)),attrs:Object.fromEntries(u.map(uI))}),m=ns(ot(l,"parseHTML",h));m&&(p.parseDOM=m.map(y=>lI(y,u)));const v=ot(l,"renderHTML",h);v&&(p.toDOM=y=>v({node:y,HTMLAttributes:ey(y,u)}));const g=ot(l,"renderText",h);return g&&(p.toText=g),[l.name,p]})),c=Object.fromEntries(r.map(l=>{const u=n.filter(g=>g.type===l.name),h={name:l.name,options:l.options,storage:l.storage,editor:e},d=s.reduce((g,y)=>{const b=ot(y,"extendMarkSchema",h);return{...g,...b?b(l):{}}},{}),p=cI({...d,inclusive:ns(ot(l,"inclusive",h)),excludes:ns(ot(l,"excludes",h)),group:ns(ot(l,"group",h)),spanning:ns(ot(l,"spanning",h)),code:ns(ot(l,"code",h)),attrs:Object.fromEntries(u.map(uI))}),m=ns(ot(l,"parseHTML",h));m&&(p.parseDOM=m.map(g=>lI(g,u)));const v=ot(l,"renderHTML",h);return v&&(p.toDOM=g=>v({mark:g,HTMLAttributes:ey(g,u)})),[l.name,p]}));return new RL({topNode:o,nodes:a,marks:c})}function _q(s){const e=s.filter((t,n)=>s.indexOf(t)!==n);return Array.from(new Set(e))}function Iv(s){return s.sort((t,n)=>{const i=ot(t,"priority")||100,r=ot(n,"priority")||100;return i>r?-1:i<r?1:0})}function oO(s){const e=Iv(FE(s)),t=_q(e.map(n=>n.name));return t.length&&console.warn(`[tiptap warn]: Duplicate extension names found: [${t.map(n=>`'${n}'`).join(", ")}]. This can lead to issues.`),e}function aO(s,e,t){const{from:n,to:i}=e,{blockSeparator:r=`
`,textSerializers:o={}}=t||{};let a="";return s.nodesBetween(n,i,(c,l,u,h)=>{var d;c.isBlock&&l>n&&(a+=r);const p=o==null?void 0:o[c.type.name];if(p)return u&&(a+=p({node:c,pos:l,parent:u,index:h,range:e})),!1;c.isText&&(a+=(d=c==null?void 0:c.text)==null?void 0:d.slice(Math.max(n,l)-l,i-l))}),a}function Sq(s,e){const t={from:0,to:s.content.size};return aO(s,t,e)}function lO(s){return Object.fromEntries(Object.entries(s.nodes).filter(([,e])=>e.spec.toText).map(([e,t])=>[e,t.spec.toText]))}function wq(s,e){const t=wn(e,s.schema),{from:n,to:i}=s.selection,r=[];s.doc.nodesBetween(n,i,a=>{r.push(a)});const o=r.reverse().find(a=>a.type.name===t.name);return o?{...o.attrs}:{}}function cO(s,e){const t=ik(typeof e=="string"?e:e.name,s.schema);return t==="node"?wq(s,e):t==="mark"?sO(s,e):{}}function kq(s,e=JSON.stringify){const t={};return s.filter(n=>{const i=e(n);return Object.prototype.hasOwnProperty.call(t,i)?!1:t[i]=!0})}function Cq(s){const e=kq(s);return e.length===1?e:e.filter((t,n)=>!e.filter((r,o)=>o!==n).some(r=>t.oldRange.from>=r.oldRange.from&&t.oldRange.to<=r.oldRange.to&&t.newRange.from>=r.newRange.from&&t.newRange.to<=r.newRange.to))}function uO(s){const{mapping:e,steps:t}=s,n=[];return e.maps.forEach((i,r)=>{const o=[];if(i.ranges.length)i.forEach((a,c)=>{o.push({from:a,to:c})});else{const{from:a,to:c}=t[r];if(a===void 0||c===void 0)return;o.push({from:a,to:c})}o.forEach(({from:a,to:c})=>{const l=e.slice(r).map(a,-1),u=e.slice(r).map(c),h=e.invert().map(l,-1),d=e.invert().map(u);n.push({oldRange:{from:h,to:d},newRange:{from:l,to:u}})})}),Cq(n)}function HE(s,e,t){const n=[];return s===e?t.resolve(s).marks().forEach(i=>{const r=t.resolve(s),o=BE(r,i.type);o&&n.push({mark:i,...o})}):t.nodesBetween(s,e,(i,r)=>{!i||(i==null?void 0:i.nodeSize)===void 0||n.push(...i.marks.map(o=>({from:r,to:r+i.nodeSize,mark:o})))}),n}var Tq=(s,e,t,n=20)=>{const i=s.doc.resolve(t);let r=n,o=null;for(;r>0&&o===null;){const a=i.node(r);(a==null?void 0:a.type.name)===e?o=a:r-=1}return[o,r]};function Sm(s,e){return e.nodes[s]||e.marks[s]||null}function gS(s,e,t){return Object.fromEntries(Object.entries(t).filter(([n])=>{const i=s.find(r=>r.type===e&&r.name===n);return i?i.attribute.keepOnSplit:!1}))}var Aq=(s,e=500)=>{let t="";const n=s.parentOffset;return s.parent.nodesBetween(Math.max(0,n-e),n,(i,r,o,a)=>{var c,l;const u=((l=(c=i.type.spec).toText)==null?void 0:l.call(c,{node:i,pos:r,parent:o,index:a}))||i.textContent||"%leaf%";t+=i.isAtom&&!i.isText?u:u.slice(0,Math.max(0,n-r))}),t};function K1(s,e,t={}){const{empty:n,ranges:i}=s.selection,r=e?Ic(e,s.schema):null;if(n)return!!(s.storedMarks||s.selection.$from.marks()).filter(h=>r?r.name===h.type.name:!0).find(h=>Iw(h.attrs,t,{strict:!1}));let o=0;const a=[];if(i.forEach(({$from:h,$to:d})=>{const p=h.pos,m=d.pos;s.doc.nodesBetween(p,m,(v,g)=>{if(r&&v.inlineContent&&!v.type.allowsMarkType(r))return!1;if(!v.isText&&!v.marks.length)return;const y=Math.max(p,g),b=Math.min(m,g+v.nodeSize),_=b-y;o+=_,a.push(...v.marks.map(w=>({mark:w,from:y,to:b})))})}),o===0)return!1;const c=a.filter(h=>r?r.name===h.mark.type.name:!0).filter(h=>Iw(h.mark.attrs,t,{strict:!1})).reduce((h,d)=>h+d.to-d.from,0),l=a.filter(h=>r?h.mark.type!==r&&h.mark.type.excludes(r):!0).reduce((h,d)=>h+d.to-d.from,0);return(c>0?c+l:c)>=o}function Eq(s,e,t={}){if(!e)return lh(s,null,t)||K1(s,null,t);const n=ik(e,s.schema);return n==="node"?lh(s,e,t):n==="mark"?K1(s,e,t):!1}var Mq=(s,e)=>{const{$from:t,$to:n,$anchor:i}=s.selection;if(e){const r=rk(a=>a.type.name===e)(s.selection);if(!r)return!1;const o=s.doc.resolve(r.pos+1);return i.pos+1===o.end()}return!(n.parentOffset<n.parent.nodeSize-2||t.pos!==n.pos)},xq=s=>{const{$from:e,$to:t}=s.selection;return!(e.parentOffset>0||e.pos!==t.pos)};function hI(s,e){return Array.isArray(e)?e.some(t=>(typeof t=="string"?t:t.name)===s.name):e}function _C(s,e){const{nodeExtensions:t}=sm(e),n=t.find(o=>o.name===s);if(!n)return!1;const i={name:n.name,options:n.options,storage:n.storage},r=ns(ot(n,"group",i));return typeof r!="string"?!1:r.split(" ").includes("list")}function ty(s,{checkChildren:e=!0,ignoreWhitespace:t=!1}={}){var n;if(t){if(s.type.name==="hardBreak")return!0;if(s.isText)return!/\S/.test((n=s.text)!=null?n:"")}if(s.isText)return!s.text;if(s.isAtom||s.isLeaf)return!1;if(s.content.childCount===0)return!0;if(e){let i=!0;return s.content.forEach(r=>{i!==!1&&(ty(r,{ignoreWhitespace:t,checkChildren:e})||(i=!1))}),i}return!1}function hO(s){return s instanceof vt}var dO=class fO{constructor(e){this.position=e}static fromJSON(e){return new fO(e.position)}toJSON(){return{position:this.position}}};function Iq(s,e){const t=e.mapping.mapResult(s.position);return{position:new dO(t.pos),mapResult:t}}function Rq(s){return new dO(s)}function Lq(s,e,t){var n;const{selection:i}=e;let r=null;if(JP(i)&&(r=i.$cursor),r){const a=(n=s.storedMarks)!=null?n:r.marks();return r.parent.type.allowsMarkType(t)&&(!!t.isInSet(a)||!a.some(l=>l.type.excludes(t)))}const{ranges:o}=i;return o.some(({$from:a,$to:c})=>{let l=a.depth===0?s.doc.inlineContent&&s.doc.type.allowsMarkType(t):!1;return s.doc.nodesBetween(a.pos,c.pos,(u,h,d)=>{if(l)return!1;if(u.isInline){const p=!d||d.type.allowsMarkType(t),m=!!t.isInSet(u.marks)||!u.marks.some(v=>v.type.excludes(t));l=p&&m}return!l}),l})}var Pq=(s,e={})=>({tr:t,state:n,dispatch:i})=>{const{selection:r}=t,{empty:o,ranges:a}=r,c=Ic(s,n.schema);if(i)if(o){const l=sO(n,c);t.addStoredMark(c.create({...l,...e}))}else a.forEach(l=>{const u=l.$from.pos,h=l.$to.pos;n.doc.nodesBetween(u,h,(d,p)=>{const m=Math.max(p,u),v=Math.min(p+d.nodeSize,h);d.marks.find(y=>y.type===c)?d.marks.forEach(y=>{c===y.type&&t.addMark(m,v,c.create({...y.attrs,...e}))}):t.addMark(m,v,c.create(e))})});return Lq(n,t,c)},Oq=(s,e)=>({tr:t})=>(t.setMeta(s,e),!0),Dq=(s,e={})=>({state:t,dispatch:n,chain:i})=>{const r=wn(s,t.schema);let o;return t.selection.$anchor.sameParent(t.selection.$head)&&(o=t.selection.$anchor.parent.attrs),r.isTextblock?i().command(({commands:a})=>kx(r,{...o,...e})(t)?!0:a.clearNodes()).command(({state:a})=>kx(r,{...o,...e})(a,n)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},Nq=s=>({tr:e,dispatch:t})=>{if(t){const{doc:n}=e,i=Fh(s,0,n.content.size),r=vt.create(n,i);e.setSelection(r)}return!0},Bq=(s,e)=>({tr:t,state:n,dispatch:i})=>{const{selection:r}=n;let o,a;return typeof e=="number"?(o=e,a=e):e&&"from"in e&&"to"in e?(o=e.from,a=e.to):(o=r.from,a=r.to),i&&t.doc.nodesBetween(o,a,(c,l)=>{c.isText||t.setNodeMarkup(l,void 0,{...c.attrs,dir:s})}),!0},Fq=s=>({tr:e,dispatch:t})=>{if(t){const{doc:n}=e,{from:i,to:r}=typeof s=="number"?{from:s,to:s}:s,o=_t.atStart(n).from,a=_t.atEnd(n).to,c=Fh(i,o,a),l=Fh(r,o,a),u=_t.create(n,c,l);e.setSelection(u)}return!0},$q=s=>({state:e,dispatch:t})=>{const n=wn(s,e.schema);return x7(n)(e,t)};function dI(s,e){const t=s.storedMarks||s.selection.$to.parentOffset&&s.selection.$from.marks();if(t){const n=t.filter(i=>e==null?void 0:e.includes(i.type.name));s.tr.ensureMarks(n)}}var Hq=({keepMarks:s=!0}={})=>({tr:e,state:t,dispatch:n,editor:i})=>{const{selection:r,doc:o}=e,{$from:a,$to:c}=r,l=i.extensionManager.attributes,u=gS(l,a.node().type.name,a.node().attrs);if(r instanceof vt&&r.node.isBlock)return!a.parentOffset||!bc(o,a.pos)?!1:(n&&(s&&dI(t,i.extensionManager.splittableMarks),e.split(a.pos).scrollIntoView()),!0);if(!a.parent.isBlock)return!1;const h=c.parentOffset===c.parent.content.size,d=a.depth===0?void 0:fq(a.node(-1).contentMatchAt(a.indexAfter(-1)));let p=h&&d?[{type:d,attrs:u}]:void 0,m=bc(e.doc,e.mapping.map(a.pos),1,p);if(!p&&!m&&bc(e.doc,e.mapping.map(a.pos),1,d?[{type:d}]:void 0)&&(m=!0,p=d?[{type:d,attrs:u}]:void 0),n){if(m&&(r instanceof _t&&e.deleteSelection(),e.split(e.mapping.map(a.pos),1,p),d&&!h&&!a.parentOffset&&a.parent.type!==d)){const v=e.mapping.map(a.before()),g=e.doc.resolve(v);a.node(-1).canReplaceWith(g.index(),g.index()+1,d)&&e.setNodeMarkup(e.mapping.map(a.before()),d)}s&&dI(t,i.extensionManager.splittableMarks),e.scrollIntoView()}return m},Uq=(s,e={})=>({tr:t,state:n,dispatch:i,editor:r})=>{var o;const a=wn(s,n.schema),{$from:c,$to:l}=n.selection,u=n.selection.node;if(u&&u.isBlock||c.depth<2||!c.sameParent(l))return!1;const h=c.node(-1);if(h.type!==a)return!1;const d=r.extensionManager.attributes;if(c.parent.content.size===0&&c.node(-1).childCount===c.indexAfter(-1)){if(c.depth===2||c.node(-3).type!==a||c.index(-2)!==c.node(-2).childCount-1)return!1;if(i){let y=Fe.empty;const b=c.index(-1)?1:c.index(-2)?2:3;for(let k=c.depth-b;k>=c.depth-3;k-=1)y=Fe.from(c.node(k).copy(y));const _=c.indexAfter(-1)<c.node(-2).childCount?1:c.indexAfter(-2)<c.node(-3).childCount?2:3,w={...gS(d,c.node().type.name,c.node().attrs),...e},S=((o=a.contentMatch.defaultType)==null?void 0:o.createAndFill(w))||void 0;y=y.append(Fe.from(a.createAndFill(null,S)||void 0));const C=c.before(c.depth-(b-1));t.replace(C,c.after(-_),new nt(y,4-b,0));let T=-1;t.doc.nodesBetween(C,t.doc.content.size,(k,A)=>{if(T>-1)return!1;k.isTextblock&&k.content.size===0&&(T=A+1)}),T>-1&&t.setSelection(_t.near(t.doc.resolve(T))),t.scrollIntoView()}return!0}const p=l.pos===c.end()?h.contentMatchAt(0).defaultType:null,m={...gS(d,h.type.name,h.attrs),...e},v={...gS(d,c.node().type.name,c.node().attrs),...e};t.delete(c.pos,l.pos);const g=p?[{type:a,attrs:m},{type:p,attrs:v}]:[{type:a,attrs:m}];if(!bc(t.doc,c.pos,2))return!1;if(i){const{selection:y,storedMarks:b}=n,{splittableMarks:_}=r.extensionManager,w=b||y.$to.parentOffset&&y.$from.marks();if(t.split(c.pos,2,g).scrollIntoView(),!w||!i)return!0;const S=w.filter(C=>_.includes(C.type.name));t.ensureMarks(S)}return!0},SC=(s,e)=>{const t=rk(o=>o.type===e)(s.selection);if(!t)return!0;const n=s.doc.resolve(Math.max(0,t.pos-1)).before(t.depth);if(n===void 0)return!0;const i=s.doc.nodeAt(n);return t.node.type===(i==null?void 0:i.type)&&dh(s.doc,t.pos)&&s.join(t.pos),!0},wC=(s,e)=>{const t=rk(o=>o.type===e)(s.selection);if(!t)return!0;const n=s.doc.resolve(t.start).after(t.depth);if(n===void 0)return!0;const i=s.doc.nodeAt(n);return t.node.type===(i==null?void 0:i.type)&&dh(s.doc,n)&&s.join(n),!0};function Wq(s){const e=s.doc,t=e.firstChild;if(!t)return null;const n=e.resolve(1),i=e.resolve(t.nodeSize-1);return _t.between(n,i)}var zq=(s,e,t,n={})=>({editor:i,tr:r,state:o,dispatch:a,chain:c,commands:l,can:u})=>{const{extensions:h,splittableMarks:d}=i.extensionManager,p=wn(s,o.schema),m=wn(e,o.schema),{selection:v,storedMarks:g}=o,{$from:y,$to:b}=v,_=y.blockRange(b),w=g||v.$to.parentOffset&&v.$from.marks();if(!_)return!1;const S=rk(L=>_C(L.type.name,h))(v),C=v.from===0&&v.to===o.doc.content.size,T=o.doc.content.content,k=T.length===1?T[0]:null,A=C&&k&&_C(k.type.name,h)?{node:k,pos:0}:null,M=S??A,R=!!S&&_.depth>=1&&_.depth-S.depth<=1,P=!!A;if((R||P)&&M){if(M.node.type===p)return C&&P?c().command(({tr:L,dispatch:z})=>{const Q=Wq(L);return Q?(L.setSelection(Q),z&&z(L),!0):!1}).liftListItem(m).run():l.liftListItem(m);if(_C(M.node.type.name,h)&&p.validContent(M.node.content))return c().command(()=>(r.setNodeMarkup(M.pos,p),!0)).command(()=>SC(r,p)).command(()=>wC(r,p)).run()}return!t||!w||!a?c().command(()=>u().wrapInList(p,n)?!0:l.clearNodes()).wrapInList(p,n).command(()=>SC(r,p)).command(()=>wC(r,p)).run():c().command(()=>{const L=u().wrapInList(p,n),z=w.filter(Q=>d.includes(Q.type.name));return r.ensureMarks(z),L?!0:l.clearNodes()}).wrapInList(p,n).command(()=>SC(r,p)).command(()=>wC(r,p)).run()},jq=(s,e={},t={})=>({state:n,commands:i})=>{const{extendEmptyMarkRange:r=!1}=t,o=Ic(s,n.schema);return K1(n,o,e)?i.unsetMark(o,{extendEmptyMarkRange:r}):i.setMark(o,e)},Vq=(s,e,t={})=>({state:n,commands:i})=>{const r=wn(s,n.schema),o=wn(e,n.schema),a=lh(n,r,t);let c;return n.selection.$anchor.sameParent(n.selection.$head)&&(c=n.selection.$anchor.parent.attrs),a?i.setNode(o,c):i.setNode(r,{...c,...t})},Gq=(s,e={})=>({state:t,commands:n})=>{const i=wn(s,t.schema);return lh(t,i,e)?n.lift(i):n.wrapIn(i,e)},qq=()=>({state:s,dispatch:e})=>{const t=s.plugins;for(let n=0;n<t.length;n+=1){const i=t[n];let r;if(i.spec.isInputRules&&(r=i.getState(s))){if(e){const o=s.tr,a=r.transform;for(let c=a.steps.length-1;c>=0;c-=1)o.step(a.steps[c].invert(a.docs[c]));if(r.text){const c=o.doc.resolve(r.from).marks();o.replaceWith(r.from,r.to,s.schema.text(r.text,c))}else o.delete(r.from,r.to)}return!0}}return!1},Kq=(s={})=>({tr:e,dispatch:t,editor:n})=>{const{ignoreClearable:i=!1}=s,{selection:r}=e,{empty:o,ranges:a}=r;if(o)return!0;const{nonClearableMarks:c}=n.extensionManager;if(t){const l=Object.values(n.schema.marks).filter(u=>i||!c.includes(u.name));a.forEach(u=>{for(const h of l)e.removeMark(u.$from.pos,u.$to.pos,h)})}return!0},Qq=(s,e={})=>({tr:t,state:n,dispatch:i})=>{var r;const{extendEmptyMarkRange:o=!1}=e,{selection:a}=t,c=Ic(s,n.schema),{$from:l,empty:u,ranges:h}=a;if(!i)return!0;if(u&&o){let{from:d,to:p}=a;const m=(r=l.marks().find(g=>g.type===c))==null?void 0:r.attrs,v=BE(l,c,m);v&&(d=v.from,p=v.to),t.removeMark(d,p,c)}else h.forEach(d=>{t.removeMark(d.$from.pos,d.$to.pos,c)});return t.removeStoredMark(c),!0},Xq=s=>({tr:e,state:t,dispatch:n})=>{const{selection:i}=t;let r,o;return typeof s=="number"?(r=s,o=s):s&&"from"in s&&"to"in s?(r=s.from,o=s.to):(r=i.from,o=i.to),n&&e.doc.nodesBetween(r,o,(a,c)=>{if(a.isText)return;const l={...a.attrs};delete l.dir,e.setNodeMarkup(c,void 0,l)}),!0},Yq=(s,e={})=>({tr:t,state:n,dispatch:i})=>{let r=null,o=null;const a=ik(typeof s=="string"?s:s.name,n.schema);if(!a)return!1;a==="node"&&(r=wn(s,n.schema)),a==="mark"&&(o=Ic(s,n.schema));let c=!1;return t.selection.ranges.forEach(l=>{const u=l.$from.pos,h=l.$to.pos;let d,p,m,v;t.selection.empty?n.doc.nodesBetween(u,h,(g,y)=>{r&&r===g.type&&(c=!0,m=Math.max(y,u),v=Math.min(y+g.nodeSize,h),d=y,p=g)}):n.doc.nodesBetween(u,h,(g,y)=>{y<u&&r&&r===g.type&&(c=!0,m=Math.max(y,u),v=Math.min(y+g.nodeSize,h),d=y,p=g),y>=u&&y<=h&&(r&&r===g.type&&(c=!0,i&&t.setNodeMarkup(y,void 0,{...g.attrs,...e})),o&&g.marks.length&&g.marks.forEach(b=>{if(o===b.type&&(c=!0,i)){const _=Math.max(y,u),w=Math.min(y+g.nodeSize,h);t.addMark(_,w,o.create({...b.attrs,...e}))}}))}),p&&(d!==void 0&&i&&t.setNodeMarkup(d,void 0,{...p.attrs,...e}),o&&p.marks.length&&p.marks.forEach(g=>{o===g.type&&i&&t.addMark(m,v,o.create({...g.attrs,...e}))}))}),c},Jq=(s,e={})=>({state:t,dispatch:n})=>{const i=wn(s,t.schema);return w7(i,e)(t,n)},Zq=(s,e={})=>({state:t,dispatch:n})=>{const i=wn(s,t.schema);return k7(i,e)(t,n)},eK=class{constructor(){this.callbacks={}}on(s,e){return this.callbacks[s]||(this.callbacks[s]=[]),this.callbacks[s].push(e),this}emit(s,...e){const t=this.callbacks[s];return t&&t.forEach(n=>n.apply(this,e)),this}off(s,e){const t=this.callbacks[s];return t&&(e?this.callbacks[s]=t.filter(n=>n!==e):delete this.callbacks[s]),this}once(s,e){const t=(...n)=>{this.off(s,t),e.apply(this,n)};return this.on(s,t)}removeAllListeners(){this.callbacks={}}},ok=class{constructor(s){var e;this.find=s.find,this.handler=s.handler,this.undoable=(e=s.undoable)!=null?e:!0}},tK=(s,e)=>{if(NE(e))return e.exec(s);const t=e(s);if(!t)return null;const n=[t.text];return n.index=t.index,n.input=s,n.data=t.data,t.replaceWith&&(t.text.includes(t.replaceWith)||console.warn('[tiptap warn]: "inputRuleMatch.replaceWith" must be part of "inputRuleMatch.text".'),n.push(t.replaceWith)),n};function R_(s){var e;const{editor:t,from:n,to:i,text:r,rules:o,plugin:a}=s,{view:c}=t;if(c.composing)return!1;const l=c.state.doc.resolve(n);if(l.parent.type.spec.code||(e=l.nodeBefore||l.nodeAfter)!=null&&e.marks.find(d=>d.type.spec.code))return!1;let u=!1;const h=Aq(l)+r;return o.forEach(d=>{if(u)return;const p=tK(h,d.find);if(!p)return;const m=c.state.tr,v=sk({state:c.state,transaction:m}),g={from:n-(p[0].length-r.length),to:i},{commands:y,chain:b,can:_}=new nk({editor:t,state:v});d.handler({state:v,range:g,match:p,commands:y,chain:b,can:_})===null||!m.steps.length||(d.undoable&&m.setMeta(a,{transform:m,from:n,to:i,text:r}),c.dispatch(m),u=!0)}),u}function sK(s){const{editor:e,rules:t}=s,n=new $s({state:{init(){return null},apply(i,r,o){const a=i.getMeta(n);if(a)return a;const c=i.getMeta("applyInputRules");return!!c&&setTimeout(()=>{let{text:u}=c;typeof u=="string"?u=u:u=$E(Fe.from(u),o.schema);const{from:h}=c,d=h+u.length;R_({editor:e,from:h,to:d,text:u,rules:t,plugin:n})}),i.selectionSet||i.docChanged?null:r}},props:{handleTextInput(i,r,o,a){return R_({editor:e,from:r,to:o,text:a,rules:t,plugin:n})},handleDOMEvents:{compositionend:i=>(setTimeout(()=>{const{$cursor:r}=i.state.selection;r&&R_({editor:e,from:r.pos,to:r.pos,text:"",rules:t,plugin:n})}),!1)},handleKeyDown(i,r){if(r.key!=="Enter")return!1;const{$cursor:o}=i.state.selection;return o?R_({editor:e,from:o.pos,to:o.pos,text:`
`,rules:t,plugin:n}):!1}},isInputRules:!0});return n}function nK(s){return Object.prototype.toString.call(s).slice(8,-1)}function L_(s){return nK(s)!=="Object"?!1:s.constructor===Object&&Object.getPrototypeOf(s)===Object.prototype}function pO(s,e){const t={...s};return L_(s)&&L_(e)&&Object.keys(e).forEach(n=>{L_(e[n])&&L_(s[n])?t[n]=pO(s[n],e[n]):t[n]=e[n]}),t}var UE=class{constructor(s={}){this.type="extendable",this.parent=null,this.child=null,this.name="",this.config={name:this.name},this.config={...this.config,...s},this.name=this.config.name}get options(){return{...ns(ot(this,"addOptions",{name:this.name}))}}get storage(){return{...ns(ot(this,"addStorage",{name:this.name,options:this.options}))}}configure(s={}){const e=this.extend({...this.config,addOptions:()=>pO(this.options,s)});return e.name=this.name,e.parent=this.parent,this.child=null,e}extend(s={}){const e=new this.constructor({...this.config,...s});return e.parent=this,this.child=e,e.name="name"in s?s.name:e.parent.name,e}},Df=class gO extends UE{constructor(){super(...arguments),this.type="mark"}static create(e={}){const t=typeof e=="function"?e():e;return new gO(t)}static handleExit({editor:e,mark:t}){const{tr:n}=e.state,i=e.state.selection.$from;if(i.pos===i.end()){const o=i.marks();if(!!!o.find(l=>(l==null?void 0:l.type.name)===t.name))return!1;const c=o.find(l=>(l==null?void 0:l.type.name)===t.name);return c&&n.removeStoredMark(c),n.insertText(" ",i.pos),e.view.dispatch(n),!0}return!1}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}};function iK(s){return typeof s=="number"}var rK=class{constructor(s){this.find=s.find,this.handler=s.handler}},oK=(s,e,t)=>{if(NE(e))return[...s.matchAll(e)];const n=e(s,t);return n?n.map(i=>{const r=[i.text];return r.index=i.index,r.input=s,r.data=i.data,i.replaceWith&&(i.text.includes(i.replaceWith)||console.warn('[tiptap warn]: "pasteRuleMatch.replaceWith" must be part of "pasteRuleMatch.text".'),r.push(i.replaceWith)),r}):[]};function aK(s){const{editor:e,state:t,from:n,to:i,rule:r,pasteEvent:o,dropEvent:a}=s,{commands:c,chain:l,can:u}=new nk({editor:e,state:t}),h=[];return t.doc.nodesBetween(n,i,(p,m)=>{var v,g,y,b,_;if((g=(v=p.type)==null?void 0:v.spec)!=null&&g.code||!(p.isText||p.isTextblock||p.isInline))return;const w=(_=(b=(y=p.content)==null?void 0:y.size)!=null?b:p.nodeSize)!=null?_:0,S=Math.max(n,m),C=Math.min(i,m+w);if(S>=C)return;const T=p.isText?p.text||"":p.textBetween(S-m,C-m,void 0,"");oK(T,r.find,o).forEach(A=>{if(A.index===void 0)return;const M=S+A.index+1,R=M+A[0].length,P={from:t.tr.mapping.map(M),to:t.tr.mapping.map(R)},L=r.handler({state:t,range:P,match:A,commands:c,chain:l,can:u,pasteEvent:o,dropEvent:a});h.push(L)})}),h.every(p=>p!==null)}var P_=null,lK=s=>{var e;const t=new ClipboardEvent("paste",{clipboardData:new DataTransfer});return(e=t.clipboardData)==null||e.setData("text/html",s),t};function cK(s){const{editor:e,rules:t}=s;let n=null,i=!1,r=!1,o=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,a;try{a=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{a=null}const c=({state:u,from:h,to:d,rule:p,pasteEvt:m})=>{const v=u.tr,g=sk({state:u,transaction:v});if(!(!aK({editor:e,state:g,from:Math.max(h-1,0),to:d.b-1,rule:p,pasteEvent:m,dropEvent:a})||!v.steps.length)){try{a=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{a=null}return o=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,v}};return t.map(u=>new $s({view(h){const d=m=>{var v;n=(v=h.dom.parentElement)!=null&&v.contains(m.target)?h.dom.parentElement:null,n&&(P_=e)},p=()=>{P_&&(P_=null)};return window.addEventListener("dragstart",d),window.addEventListener("dragend",p),{destroy(){window.removeEventListener("dragstart",d),window.removeEventListener("dragend",p)}}},props:{handleDOMEvents:{drop:(h,d)=>{if(r=n===h.dom.parentElement,a=d,!r){const p=P_;p!=null&&p.isEditable&&setTimeout(()=>{const m=p.state.selection;m&&p.commands.deleteRange({from:m.from,to:m.to})},10)}return!1},paste:(h,d)=>{var p;const m=(p=d.clipboardData)==null?void 0:p.getData("text/html");return o=d,i=!!(m!=null&&m.includes("data-pm-slice")),!1}}},appendTransaction:(h,d,p)=>{const m=h[0],v=m.getMeta("uiEvent")==="paste"&&!i,g=m.getMeta("uiEvent")==="drop"&&!r,y=m.getMeta("applyPasteRules"),b=!!y;if(!v&&!g&&!b)return;if(b){let{text:S}=y;typeof S=="string"?S=S:S=$E(Fe.from(S),p.schema);const{from:C}=y,T=C+S.length,k=lK(S);return c({rule:u,state:p,from:C,to:{b:T},pasteEvt:k})}const _=d.doc.content.findDiffStart(p.doc.content),w=d.doc.content.findDiffEnd(p.doc.content);if(!(!iK(_)||!w||_===w.b))return c({rule:u,state:p,from:_,to:w,pasteEvt:o})}}))}var ak=class{constructor(s,e){this.splittableMarks=[],this.nonClearableMarks=[],this.editor=e,this.baseExtensions=s,this.extensions=oO(s),this.schema=bq(this.extensions,e),this.setupExtensions()}get commands(){return this.extensions.reduce((s,e)=>{const t={name:e.name,options:e.options,storage:this.editor.extensionStorage[e.name],editor:this.editor,type:Sm(e.name,this.schema)},n=ot(e,"addCommands",t);return n?{...s,...n()}:s},{})}get plugins(){const{editor:s}=this;return Iv([...this.extensions].reverse()).flatMap(n=>{const i={name:n.name,options:n.options,storage:this.editor.extensionStorage[n.name],editor:s,type:Sm(n.name,this.schema)},r=[],o=ot(n,"addKeyboardShortcuts",i);let a={};if(n.type==="mark"&&ot(n,"exitable",i)&&(a.ArrowRight=()=>Df.handleExit({editor:s,mark:n})),o){const d=Object.fromEntries(Object.entries(o()).map(([p,m])=>[p,()=>m({editor:s})]));a={...a,...d}}const c=bG(a);r.push(c);const l=ot(n,"addInputRules",i);if(hI(n,s.options.enableInputRules)&&l){const d=l();if(d&&d.length){const p=sK({editor:s,rules:d}),m=Array.isArray(p)?p:[p];r.push(...m)}}const u=ot(n,"addPasteRules",i);if(hI(n,s.options.enablePasteRules)&&u){const d=u();if(d&&d.length){const p=cK({editor:s,rules:d});r.push(...p)}}const h=ot(n,"addProseMirrorPlugins",i);if(h){const d=h();r.push(...d)}return r})}get attributes(){return rO(this.extensions)}get nodeViews(){const{editor:s}=this,{nodeExtensions:e}=sm(this.extensions);return Object.fromEntries(e.filter(t=>!!ot(t,"addNodeView")).map(t=>{const n=this.attributes.filter(c=>c.type===t.name),i={name:t.name,options:t.options,storage:this.editor.extensionStorage[t.name],editor:s,type:wn(t.name,this.schema)},r=ot(t,"addNodeView",i);if(!r)return[];const o=r();if(!o)return[];const a=(c,l,u,h,d)=>{const p=ey(c,n);return o({node:c,view:l,getPos:u,decorations:h,innerDecorations:d,editor:s,extension:t,HTMLAttributes:p})};return[t.name,a]}))}dispatchTransaction(s){const{editor:e}=this;return Iv([...this.extensions].reverse()).reduceRight((n,i)=>{const r={name:i.name,options:i.options,storage:this.editor.extensionStorage[i.name],editor:e,type:Sm(i.name,this.schema)},o=ot(i,"dispatchTransaction",r);return o?a=>{o.call(r,{transaction:a,next:n})}:n},s)}transformPastedHTML(s){const{editor:e}=this;return Iv([...this.extensions]).reduce((n,i)=>{const r={name:i.name,options:i.options,storage:this.editor.extensionStorage[i.name],editor:e,type:Sm(i.name,this.schema)},o=ot(i,"transformPastedHTML",r);return o?(a,c)=>{const l=n(a,c);return o.call(r,l)}:n},s||(n=>n))}get markViews(){const{editor:s}=this,{markExtensions:e}=sm(this.extensions);return Object.fromEntries(e.filter(t=>!!ot(t,"addMarkView")).map(t=>{const n=this.attributes.filter(a=>a.type===t.name),i={name:t.name,options:t.options,storage:this.editor.extensionStorage[t.name],editor:s,type:Ic(t.name,this.schema)},r=ot(t,"addMarkView",i);if(!r)return[];const o=(a,c,l)=>{const u=ey(a,n);return r()({mark:a,view:c,inline:l,editor:s,extension:t,HTMLAttributes:u,updateAttributes:h=>{wK(a,s,h)}})};return[t.name,o]}))}destroy(){this.extensions.forEach(s=>{let e=s;for(;e.parent;){const t=e.parent;t.child===e&&(t.child=null),e=t}}),this.extensions=[],this.baseExtensions=[],this.schema=null,this.editor=null}setupExtensions(){const s=this.extensions;this.editor.extensionStorage=Object.fromEntries(s.map(e=>[e.name,e.storage])),s.forEach(e=>{var t,n;const i={name:e.name,options:e.options,storage:this.editor.extensionStorage[e.name],editor:this.editor,type:Sm(e.name,this.schema)};e.type==="mark"&&(((t=ns(ot(e,"keepOnSplit",i)))==null||t)&&this.splittableMarks.push(e.name),(n=ns(ot(e,"clearable",i)))==null||n||this.nonClearableMarks.push(e.name));const r=ot(e,"onBeforeCreate",i),o=ot(e,"onCreate",i),a=ot(e,"onUpdate",i),c=ot(e,"onSelectionUpdate",i),l=ot(e,"onTransaction",i),u=ot(e,"onFocus",i),h=ot(e,"onBlur",i),d=ot(e,"onDestroy",i);r&&this.editor.on("beforeCreate",r),o&&this.editor.on("create",o),a&&this.editor.on("update",a),c&&this.editor.on("selectionUpdate",c),l&&this.editor.on("transaction",l),u&&this.editor.on("focus",u),h&&this.editor.on("blur",h),d&&this.editor.on("destroy",d)})}};ak.resolve=oO;ak.sort=Iv;ak.flatten=FE;var uK={};DE(uK,{ClipboardTextSerializer:()=>vO,Commands:()=>yO,Delete:()=>bO,Drop:()=>_O,Editable:()=>SO,FocusEvents:()=>kO,Keymap:()=>CO,Paste:()=>TO,Tabindex:()=>AO,TextDirection:()=>EO,focusEventsPluginKey:()=>wO});var on=class mO extends UE{constructor(){super(...arguments),this.type="extension"}static create(e={}){const t=typeof e=="function"?e():e;return new mO(t)}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}},vO=on.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new $s({key:new fn("clipboardTextSerializer"),props:{clipboardTextSerializer:()=>{const{editor:s}=this,{state:e,schema:t}=s,{doc:n,selection:i}=e,r=lO(t),{blockSeparator:o}=this.options,a={...o!==void 0?{blockSeparator:o}:{},textSerializers:r};return[...i.ranges].sort((l,u)=>l.$from.pos-u.$from.pos).map(({$from:l,$to:u})=>aO(n,{from:l.pos,to:u.pos},a)).join(o??`
`)}}})]}}),yO=on.create({name:"commands",addCommands(){return{...XP}}}),bO=on.create({name:"delete",onUpdate({transaction:s,appendedTransactions:e}){var t,n,i;const r=()=>{var o,a,c,l;if((l=(c=(a=(o=this.editor.options.coreExtensionOptions)==null?void 0:o.delete)==null?void 0:a.filterTransaction)==null?void 0:c.call(a,s))!=null?l:s.getMeta("y-sync$"))return;const u=nO(s.before,[s,...e]);uO(u).forEach(p=>{u.mapping.mapResult(p.oldRange.from).deletedAfter&&u.mapping.mapResult(p.oldRange.to).deletedBefore&&u.before.nodesBetween(p.oldRange.from,p.oldRange.to,(m,v)=>{const g=v+m.nodeSize-2,y=p.oldRange.from<=v&&g<=p.oldRange.to;this.editor.emit("delete",{type:"node",node:m,from:v,to:g,newFrom:u.mapping.map(v),newTo:u.mapping.map(g),deletedRange:p.oldRange,newRange:p.newRange,partial:!y,editor:this.editor,transaction:s,combinedTransform:u})})});const d=u.mapping;u.steps.forEach((p,m)=>{var v,g;if(p instanceof dm){const y=d.slice(m).map(p.from,-1),b=d.slice(m).map(p.to),_=d.invert().map(y,-1),w=d.invert().map(b),S=y>0?(v=u.doc.nodeAt(y-1))==null?void 0:v.marks.some(T=>T.eq(p.mark)):!1,C=(g=u.doc.nodeAt(b))==null?void 0:g.marks.some(T=>T.eq(p.mark));this.editor.emit("delete",{type:"mark",mark:p.mark,from:p.from,to:p.to,deletedRange:{from:_,to:w},newRange:{from:y,to:b},partial:!!(C||S),editor:this.editor,transaction:s,combinedTransform:u})}})};(i=(n=(t=this.editor.options.coreExtensionOptions)==null?void 0:t.delete)==null?void 0:n.async)==null||i?setTimeout(r,0):r()}}),_O=on.create({name:"drop",addProseMirrorPlugins(){return[new $s({key:new fn("tiptapDrop"),props:{handleDrop:(s,e,t,n)=>{this.editor.emit("drop",{editor:this.editor,event:e,slice:t,moved:n})}}})]}}),SO=on.create({name:"editable",addProseMirrorPlugins(){return[new $s({key:new fn("editable"),props:{editable:()=>this.editor.options.editable}})]}}),wO=new fn("focusEvents"),kO=on.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:s}=this;return[new $s({key:wO,props:{handleDOMEvents:{focus:(e,t)=>{s.isFocused=!0;const n=s.state.tr.setMeta("focus",{event:t}).setMeta("addToHistory",!1);return e.dispatch(n),!1},blur:(e,t)=>{s.isFocused=!1;const n=s.state.tr.setMeta("blur",{event:t}).setMeta("addToHistory",!1);return e.dispatch(n),!1}}}})]}}),CO=on.create({name:"keymap",addKeyboardShortcuts(){const s=()=>this.editor.commands.first(({commands:o})=>[()=>o.undoInputRule(),()=>o.command(({tr:a})=>{const{selection:c,doc:l}=a,{empty:u,$anchor:h}=c,{pos:d,parent:p}=h,m=h.parent.isTextblock&&d>0?a.doc.resolve(d-1):h,v=m.parent.type.spec.isolating,g=h.pos-h.parentOffset,y=v&&m.parent.childCount===1?g===h.pos:Ft.atStart(l).from===d;return!u||!p.type.isTextblock||p.textContent.length||!y||y&&h.parent.type.name==="paragraph"?!1:o.clearNodes()}),()=>o.deleteSelection(),()=>o.joinBackward(),()=>o.selectNodeBackward()]),e=()=>this.editor.commands.first(({commands:o})=>[()=>o.deleteSelection(),()=>o.deleteCurrentNode(),()=>o.joinForward(),()=>o.selectNodeForward()]),n={Enter:()=>this.editor.commands.first(({commands:o})=>[()=>o.newlineInCode(),()=>o.createParagraphNear(),()=>o.liftEmptyBlock(),()=>o.splitBlock()]),"Mod-Enter":()=>this.editor.commands.exitCode(),Backspace:s,"Mod-Backspace":s,"Shift-Backspace":s,Delete:e,"Mod-Delete":e,"Mod-a":()=>this.editor.commands.selectAll()},i={...n},r={...n,"Ctrl-h":s,"Alt-Backspace":s,"Ctrl-d":e,"Ctrl-Alt-Backspace":e,"Alt-Delete":e,"Alt-d":e,"Ctrl-a":()=>this.editor.commands.selectTextblockStart(),"Ctrl-e":()=>this.editor.commands.selectTextblockEnd()};return Rw()||tO()?r:i},addProseMirrorPlugins(){return[new $s({key:new fn("clearDocument"),appendTransaction:(s,e,t)=>{if(s.some(v=>v.getMeta("composition")))return;const n=s.some(v=>v.docChanged)&&!e.doc.eq(t.doc),i=s.some(v=>v.getMeta("preventClearDocument"));if(!n||i)return;const{empty:r,from:o,to:a}=e.selection,c=Ft.atStart(e.doc).from,l=Ft.atEnd(e.doc).to;if(r||!(o===c&&a===l)||!ty(t.doc))return;const d=t.tr,p=sk({state:t,transaction:d}),{commands:m}=new nk({editor:this.editor,state:p});if(m.clearNodes(),!!d.steps.length)return d}})]}}),TO=on.create({name:"paste",addProseMirrorPlugins(){return[new $s({key:new fn("tiptapPaste"),props:{handlePaste:(s,e,t)=>{this.editor.emit("paste",{editor:this.editor,event:e,slice:t})}}})]}}),AO=on.create({name:"tabindex",addOptions(){return{value:void 0}},addProseMirrorPlugins(){return[new $s({key:new fn("tabindex"),props:{attributes:()=>{var s;return!this.editor.isEditable&&this.options.value===void 0?{}:{tabindex:(s=this.options.value)!=null?s:"0"}}}})]}}),EO=on.create({name:"textDirection",addOptions(){return{direction:void 0}},addGlobalAttributes(){if(!this.options.direction)return[];const{nodeExtensions:s}=sm(this.extensions);return[{types:s.filter(e=>e.name!=="text").map(e=>e.name),attributes:{dir:{default:this.options.direction,parseHTML:e=>{const t=e.getAttribute("dir");return t&&(t==="ltr"||t==="rtl"||t==="auto")?t:this.options.direction},renderHTML:e=>e.dir?{dir:e.dir}:{}}}}]},addProseMirrorPlugins(){return[new $s({key:new fn("textDirection"),props:{attributes:()=>{const s=this.options.direction;return s?{dir:s}:{}}}})]}}),hK=class Hm{constructor(e,t,n=!1,i=null){this.currentNode=null,this.actualDepth=null,this.isBlock=n,this.resolvedPos=e,this.editor=t,this.currentNode=i}get name(){return this.node.type.name}get node(){return this.currentNode||this.resolvedPos.node()}get element(){return this.editor.view.domAtPos(this.pos).node}get depth(){var e;return(e=this.actualDepth)!=null?e:this.resolvedPos.depth}get pos(){return this.resolvedPos.pos}get content(){return this.node.content}set content(e){let t=this.from,n=this.to;if(this.isBlock){if(this.content.size===0){console.error(`You cant set content on a block node. Tried to set content on ${this.name} at ${this.pos}`);return}t=this.from+1,n=this.to-1}this.editor.commands.insertContentAt({from:t,to:n},e)}get attributes(){return this.node.attrs}get textContent(){return this.node.textContent}get size(){return this.node.nodeSize}get from(){return this.isBlock?this.pos:this.resolvedPos.start(this.resolvedPos.depth)}get range(){return{from:this.from,to:this.to}}get to(){return this.isBlock?this.pos+this.size:this.resolvedPos.end(this.resolvedPos.depth)+(this.node.isText?0:1)}get parent(){if(this.depth===0)return null;const e=this.resolvedPos.start(this.resolvedPos.depth-1),t=this.resolvedPos.doc.resolve(e);return new Hm(t,this.editor)}get before(){let e=this.resolvedPos.doc.resolve(this.from-(this.isBlock?1:2));return e.depth!==this.depth&&(e=this.resolvedPos.doc.resolve(this.from-3)),new Hm(e,this.editor)}get after(){let e=this.resolvedPos.doc.resolve(this.to+(this.isBlock?2:1));return e.depth!==this.depth&&(e=this.resolvedPos.doc.resolve(this.to+3)),new Hm(e,this.editor)}get children(){const e=[];return this.node.content.forEach((t,n)=>{const i=t.isBlock&&!t.isTextblock,r=t.isAtom&&!t.isText,o=t.isInline,a=this.pos+n+(r?0:1);if(a<0||a>this.resolvedPos.doc.nodeSize-2)return;const c=this.resolvedPos.doc.resolve(a);if(!i&&!o&&c.depth<=this.depth)return;const l=new Hm(c,this.editor,i,i||o?t:null);i&&(l.actualDepth=this.depth+1),e.push(l)}),e}get firstChild(){return this.children[0]||null}get lastChild(){const e=this.children;return e[e.length-1]||null}closest(e,t={}){let n=null,i=this.parent;for(;i&&!n;){if(i.node.type.name===e)if(Object.keys(t).length>0){const r=i.node.attrs,o=Object.keys(t);for(let a=0;a<o.length;a+=1){const c=o[a];if(r[c]!==t[c])break}}else n=i;i=i.parent}return n}querySelector(e,t={}){return this.querySelectorAll(e,t,!0)[0]||null}querySelectorAll(e,t={},n=!1){let i=[];if(!this.children||this.children.length===0)return i;const r=Object.keys(t);return this.children.forEach(o=>{n&&i.length>0||(o.node.type.name===e&&r.every(c=>t[c]===o.node.attrs[c])&&i.push(o),!(n&&i.length>0)&&(i=i.concat(o.querySelectorAll(e,t,n))))}),i}setAttribute(e){const{tr:t}=this.editor.state;t.setNodeMarkup(this.from,void 0,{...this.node.attrs,...e}),this.editor.view.dispatch(t)}},dK=`.ProseMirror {
position: relative;
}
.ProseMirror {
word-wrap: break-word;
white-space: pre-wrap;
white-space: break-spaces;
-webkit-font-variant-ligatures: none;
font-variant-ligatures: none;
font-feature-settings: "liga" 0; /* the above doesn't seem to work in Edge */
}
.ProseMirror [contenteditable="false"] {
white-space: normal;
}
.ProseMirror [contenteditable="false"] [contenteditable="true"] {
white-space: pre-wrap;
}
.ProseMirror pre {
white-space: pre-wrap;
}
img.ProseMirror-separator {
display: inline !important;
border: none !important;
margin: 0 !important;
width: 0 !important;
height: 0 !important;
}
.ProseMirror-gapcursor {
display: none;
pointer-events: none;
position: absolute;
margin: 0;
}
.ProseMirror-gapcursor:after {
content: "";
display: block;
position: absolute;
top: -2px;
width: 20px;
border-top: 1px solid black;
animation: ProseMirror-cursor-blink 1.1s steps(2, start) infinite;
}
@keyframes ProseMirror-cursor-blink {
to {
visibility: hidden;
}
}
.ProseMirror-hideselection *::selection {
background: transparent;
}
.ProseMirror-hideselection *::-moz-selection {
background: transparent;
}
.ProseMirror-hideselection * {
caret-color: transparent;
}
.ProseMirror-focused .ProseMirror-gapcursor {
display: block;
}`;function MO(s,e,t){const n=document.querySelector(`style[data-tiptap-style${t?`-${t}`:""}]`);if(n!==null)return n;const i=document.createElement("style");return e&&i.setAttribute("nonce",e),i.setAttribute(`data-tiptap-style${t?`-${t}`:""}`,""),i.innerHTML=s,document.getElementsByTagName("head")[0].appendChild(i),i}var fK=class extends eK{constructor(e={}){super(),this.css=null,this.className="tiptap",this.editorView=null,this.isFocused=!1,this.destroyed=!1,this.isInitialized=!1,this.extensionStorage={},this.instanceId=Math.random().toString(36).slice(2,9),this.options={element:typeof document<"u"?document.createElement("div"):null,content:"",injectCSS:!0,injectNonce:void 0,extensions:[],autofocus:!1,editable:!0,textDirection:void 0,editorProps:{},parseOptions:{},coreExtensionOptions:{},enableInputRules:!0,enablePasteRules:!0,enableCoreExtensions:!0,enableContentCheck:!1,emitContentError:!1,onBeforeCreate:()=>null,onCreate:()=>null,onMount:()=>null,onUnmount:()=>null,onUpdate:()=>null,onSelectionUpdate:()=>null,onTransaction:()=>null,onFocus:()=>null,onBlur:()=>null,onDestroy:()=>null,onContentError:({error:i})=>{throw i},onPaste:()=>null,onDrop:()=>null,onDelete:()=>null,enableExtensionDispatchTransaction:!0},this.isCapturingTransaction=!1,this.capturedTransaction=null,this.utils={getUpdatedPosition:Iq,createMappablePosition:Rq},this.setOptions(e),this.createExtensionManager(),this.createCommandManager(),this.createSchema(),this.on("beforeCreate",this.options.onBeforeCreate),this.emit("beforeCreate",{editor:this}),this.on("mount",this.options.onMount),this.on("unmount",this.options.onUnmount),this.on("contentError",this.options.onContentError),this.on("create",this.options.onCreate),this.on("update",this.options.onUpdate),this.on("selectionUpdate",this.options.onSelectionUpdate),this.on("transaction",this.options.onTransaction),this.on("focus",this.options.onFocus),this.on("blur",this.options.onBlur),this.on("destroy",this.options.onDestroy),this.on("drop",({event:i,slice:r,moved:o})=>this.options.onDrop(i,r,o)),this.on("paste",({event:i,slice:r})=>this.options.onPaste(i,r)),this.on("delete",this.options.onDelete);const t=this.createDoc(),n=ZP(t,this.options.autofocus);this.editorState=vp.create({doc:t,schema:this.schema,selection:n||void 0}),this.options.element&&this.mount(this.options.element)}mount(e){if(typeof document>"u")throw new Error("[tiptap error]: The editor cannot be mounted because there is no 'document' defined in this environment.");this.createView(e),this.emit("mount",{editor:this}),this.css&&!document.head.contains(this.css)&&document.head.appendChild(this.css),window.setTimeout(()=>{this.isDestroyed||(this.options.autofocus!==!1&&this.options.autofocus!==null&&this.commands.focus(this.options.autofocus),this.emit("create",{editor:this}),this.isInitialized=!0)},0)}unmount(){if(this.editorView){const e=this.editorView.dom;e!=null&&e.editor&&delete e.editor,this.editorView.destroy()}if(this.editorView=null,this.isInitialized=!1,this.css&&!document.querySelectorAll(`.${this.className}`).length)try{typeof this.css.remove=="function"?this.css.remove():this.css.parentNode&&this.css.parentNode.removeChild(this.css)}catch(e){console.warn("Failed to remove CSS element:",e)}this.css=null,this.emit("unmount",{editor:this})}get storage(){return this.extensionStorage}get commands(){return this.commandManager.commands}chain(){return this.commandManager.chain()}can(){return this.commandManager.can()}injectCSS(){this.options.injectCSS&&typeof document<"u"&&(this.css=MO(dK,this.options.injectNonce))}setOptions(e={}){this.options={...this.options,...e},!(!this.editorView||!this.state||this.isDestroyed)&&(this.options.editorProps&&this.view.setProps(this.options.editorProps),this.view.updateState(this.state))}setEditable(e,t=!0){this.setOptions({editable:e}),t&&this.emit("update",{editor:this,transaction:this.state.tr,appendedTransactions:[]})}get isEditable(){return this.options.editable&&this.view&&this.view.editable}get view(){return this.editorView?this.editorView:new Proxy({state:this.editorState,updateState:e=>{this.editorState=e},dispatch:e=>{this.dispatchTransaction(e)},composing:!1,dragging:null,editable:!0,isDestroyed:!1},{get:(e,t)=>{if(this.editorView)return this.editorView[t];if(t==="state")return this.editorState;if(t in e)return Reflect.get(e,t);throw new Error(`[tiptap error]: The editor view is not available. Cannot access view['${t}']. The editor may not be mounted yet.`)}})}get state(){return this.editorView&&(this.editorState=this.view.state),this.editorState}registerPlugin(e,t){const n=iO(t)?t(e,[...this.state.plugins]):[...this.state.plugins,e],i=this.state.reconfigure({plugins:n});return this.view.updateState(i),i}unregisterPlugin(e){if(this.isDestroyed)return;const t=this.state.plugins;let n=t;if([].concat(e).forEach(r=>{const o=typeof r=="string"?`${r}$`:r.key;n=n.filter(a=>!a.key.startsWith(o))}),t.length===n.length)return;const i=this.state.reconfigure({plugins:n});return this.view.updateState(i),i}createExtensionManager(){var e,t,n,i;const o=[...this.options.enableCoreExtensions?[SO,vO.configure({blockSeparator:(t=(e=this.options.coreExtensionOptions)==null?void 0:e.clipboardTextSerializer)==null?void 0:t.blockSeparator}),yO,kO,CO,AO.configure({value:(i=(n=this.options.coreExtensionOptions)==null?void 0:n.tabindex)==null?void 0:i.value}),_O,TO,bO,EO.configure({direction:this.options.textDirection})].filter(a=>typeof this.options.enableCoreExtensions=="object"?this.options.enableCoreExtensions[a.name]!==!1:!0):[],...this.options.extensions].filter(a=>["extension","node","mark"].includes(a==null?void 0:a.type));this.extensionManager=new ak(o,this)}createCommandManager(){this.commandManager=new nk({editor:this})}createSchema(){this.schema=this.extensionManager.schema}createDoc(){let e;try{e=q1(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:this.options.enableContentCheck})}catch(t){if(!(t instanceof Error)||!["[tiptap error]: Invalid JSON content","[tiptap error]: Invalid HTML content"].includes(t.message))throw t;this.emit("contentError",{editor:this,error:t,disableCollaboration:()=>{"collaboration"in this.storage&&typeof this.storage.collaboration=="object"&&this.storage.collaboration&&(this.storage.collaboration.isDisabled=!0),this.options.extensions=this.options.extensions.filter(n=>n.name!=="collaboration"),this.createExtensionManager()}}),e=q1(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:!1})}return e}createView(e){const{editorProps:t,enableExtensionDispatchTransaction:n}=this.options,i=t.dispatchTransaction||this.dispatchTransaction.bind(this),r=n?this.extensionManager.dispatchTransaction(i):i,o=t.transformPastedHTML,a=this.extensionManager.transformPastedHTML(o);this.editorView=new KP(e,{...t,attributes:{role:"textbox",...t==null?void 0:t.attributes},dispatchTransaction:r,transformPastedHTML:a,state:this.editorState,markViews:this.extensionManager.markViews,nodeViews:this.extensionManager.nodeViews});const c=this.state.reconfigure({plugins:this.extensionManager.plugins});this.view.updateState(c),this.prependClass(),this.injectCSS();const l=this.view.dom;l.editor=this}createNodeViews(){this.view.isDestroyed||this.view.setProps({markViews:this.extensionManager.markViews,nodeViews:this.extensionManager.nodeViews})}prependClass(){this.view.dom.className=`${this.className} ${this.view.dom.className}`}captureTransaction(e){this.isCapturingTransaction=!0,e(),this.isCapturingTransaction=!1;const t=this.capturedTransaction;return this.capturedTransaction=null,t}dispatchTransaction(e){if(this.view.isDestroyed)return;if(this.isCapturingTransaction){if(!this.capturedTransaction){this.capturedTransaction=e;return}e.steps.forEach(u=>{var h;return(h=this.capturedTransaction)==null?void 0:h.step(u)});return}const{state:t,transactions:n}=this.state.applyTransaction(e),i=!this.state.selection.eq(t.selection),r=n.includes(e),o=this.state;if(this.emit("beforeTransaction",{editor:this,transaction:e,nextState:t}),!r)return;this.view.updateState(t),this.emit("transaction",{editor:this,transaction:e,appendedTransactions:n.slice(1)}),i&&this.emit("selectionUpdate",{editor:this,transaction:e});const a=n.findLast(u=>u.getMeta("focus")||u.getMeta("blur")),c=a==null?void 0:a.getMeta("focus"),l=a==null?void 0:a.getMeta("blur");c&&this.emit("focus",{editor:this,event:c.event,transaction:a}),l&&this.emit("blur",{editor:this,event:l.event,transaction:a}),!(e.getMeta("preventUpdate")||!n.some(u=>u.docChanged)||o.doc.eq(t.doc))&&this.emit("update",{editor:this,transaction:e,appendedTransactions:n.slice(1)})}getAttributes(e){return cO(this.state,e)}isActive(e,t){const n=typeof e=="string"?e:null,i=typeof e=="string"?t:e;return Eq(this.state,n,i)}getJSON(){return this.state.doc.toJSON()}getHTML(){return $E(this.state.doc.content,this.schema)}getText(e){const{blockSeparator:t=`
`,textSerializers:n={}}=e||{};return Sq(this.state.doc,{blockSeparator:t,textSerializers:{...lO(this.schema),...n}})}get isEmpty(){return ty(this.state.doc)}destroy(){this.destroyed||(this.destroyed=!0,this.emit("destroy"),this.unmount(),this.removeAllListeners(),this.extensionManager.destroy(),this.extensionManager=null,this.schema=null,this.commandManager=null,this.extensionStorage={})}get isDestroyed(){var e,t;return(t=(e=this.editorView)==null?void 0:e.isDestroyed)!=null?t:!0}$node(e,t){var n;return((n=this.$doc)==null?void 0:n.querySelector(e,t))||null}$nodes(e,t){var n;return((n=this.$doc)==null?void 0:n.querySelectorAll(e,t))||null}$pos(e){const t=this.state.doc.resolve(e),n=e>0&&t.nodeAfter&&!t.nodeAfter.isText?t.nodeAfter:null;return new hK(t,this,!1,n)}get $doc(){return this.$pos(0)}};function nm(s){return new ok({find:s.find,handler:({state:e,range:t,match:n})=>{const i=ns(s.getAttributes,void 0,n);if(i===!1||i===null)return null;const{tr:r}=e,o=n[n.length-1],a=n[0];if(o){const c=a.search(/\S/),l=t.from+a.indexOf(o),u=l+o.length;if(HE(t.from,t.to,e.doc).filter(p=>p.mark.type.excluded.find(v=>v===s.type&&v!==p.mark.type)).filter(p=>p.to>l).length)return null;u<t.to&&r.delete(u,t.to),l>t.from&&r.delete(t.from+c,l);const d=t.from+c+o.length;r.addMark(t.from+c,d,s.type.create(i||{})),r.removeStoredMark(s.type)}},undoable:s.undoable})}function pK(s){return new ok({find:s.find,handler:({state:e,range:t,match:n})=>{const i=ns(s.getAttributes,void 0,n)||{},{tr:r}=e,o=t.from;let a=t.to;const c=s.type.create(i);if(n[1]){const l=n[0].lastIndexOf(n[1]);let u=o+l;u>a?u=a:a=u+n[1].length;const h=n[0][n[0].length-1];r.insertText(h,o+n[0].length-1),r.replaceWith(u,a,c)}else if(n[0]){const l=s.type.isInline?o:o-1;r.insert(l,s.type.create(i)).delete(r.mapping.map(o),r.mapping.map(a))}r.scrollIntoView()},undoable:s.undoable})}function Q1(s){return new ok({find:s.find,handler:({state:e,range:t,match:n})=>{const i=e.doc.resolve(t.from),r=ns(s.getAttributes,void 0,n)||{};if(!i.node(-1).canReplaceWith(i.index(-1),i.indexAfter(-1),s.type))return null;e.tr.delete(t.from,t.to).setBlockType(t.from,t.from,s.type,r)},undoable:s.undoable})}function im(s){return new ok({find:s.find,handler:({state:e,range:t,match:n,chain:i})=>{const r=ns(s.getAttributes,void 0,n)||{},o=e.tr.delete(t.from,t.to),c=o.doc.resolve(t.from).blockRange(),l=c&&SE(c,s.type,r);if(!l)return null;if(o.wrap(c,l),s.keepMarks&&s.editor){const{selection:h,storedMarks:d}=e,{splittableMarks:p}=s.editor.extensionManager,m=d||h.$to.parentOffset&&h.$from.marks();if(m){const v=m.filter(g=>p.includes(g.type.name));o.ensureMarks(v)}}if(s.keepAttributes){const h=s.type.name==="bulletList"||s.type.name==="orderedList"?"listItem":"taskList";i().updateAttributes(h,r).run()}const u=o.doc.resolve(t.from-1).nodeBefore;u&&u.type===s.type&&dh(o.doc,t.from-1)&&(!s.joinPredicate||s.joinPredicate(n,u))&&o.join(t.from-1)},undoable:s.undoable})}function gK(s,e){const{selection:t}=s,{$from:n}=t;if(t instanceof vt){const r=n.index();return n.parent.canReplaceWith(r,r+1,e)}let i=n.depth;for(;i>=0;){const r=n.index(i);if(n.node(i).contentMatchAt(r).matchType(e))return!0;i-=1}return!1}function mK(s){return s.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&")}var vK={};DE(vK,{createAtomBlockMarkdownSpec:()=>yK,createBlockMarkdownSpec:()=>bK,createInlineMarkdownSpec:()=>xO,parseAttributes:()=>WE,parseIndentedBlocks:()=>X1,renderNestedMarkdownContent:()=>jE,serializeAttributes:()=>zE});function WE(s){if(!(s!=null&&s.trim()))return{};const e={},t=[],n=s.replace(/["']([^"']*)["']/g,l=>(t.push(l),`__QUOTED_${t.length-1}__`)),i=n.match(/(?:^|\s)\.([a-zA-Z][\w-]*)/g);if(i){const l=i.map(u=>u.trim().slice(1));e.class=l.join(" ")}const r=n.match(/(?:^|\s)#([a-zA-Z][\w-]*)/);r&&(e.id=r[1]);const o=/([a-zA-Z][\w-]*)\s*=\s*(__QUOTED_\d+__)/g;Array.from(n.matchAll(o)).forEach(([,l,u])=>{var h;const d=parseInt(((h=u.match(/__QUOTED_(\d+)__/))==null?void 0:h[1])||"0",10),p=t[d];p&&(e[l]=p.slice(1,-1))});const c=n.replace(/(?:^|\s)\.([a-zA-Z][\w-]*)/g,"").replace(/(?:^|\s)#([a-zA-Z][\w-]*)/g,"").replace(/([a-zA-Z][\w-]*)\s*=\s*__QUOTED_\d+__/g,"").trim();return c&&c.split(/\s+/).filter(Boolean).forEach(u=>{u.match(/^[a-zA-Z][\w-]*$/)&&(e[u]=!0)}),e}function zE(s){if(!s||Object.keys(s).length===0)return"";const e=[];return s.class&&String(s.class).split(/\s+/).filter(Boolean).forEach(n=>e.push(`.${n}`)),s.id&&e.push(`#${s.id}`),Object.entries(s).forEach(([t,n])=>{t==="class"||t==="id"||(n===!0?e.push(t):n!==!1&&n!=null&&e.push(`${t}="${String(n)}"`))}),e.join(" ")}function yK(s){const{nodeName:e,name:t,parseAttributes:n=WE,serializeAttributes:i=zE,defaultAttributes:r={},requiredAttributes:o=[],allowedAttributes:a}=s,c=t||e,l=u=>{if(!a)return u;const h={};return a.forEach(d=>{d in u&&(h[d]=u[d])}),h};return{parseMarkdown:(u,h)=>{const d={...r,...u.attributes};return h.createNode(e,d,[])},markdownTokenizer:{name:e,level:"block",start(u){var h;const d=new RegExp(`^:::${c}(?:\\s|$)`,"m"),p=(h=u.match(d))==null?void 0:h.index;return p!==void 0?p:-1},tokenize(u,h,d){const p=new RegExp(`^:::${c}(?:\\s+\\{([^}]*)\\})?\\s*:::(?:\\n|$)`),m=u.match(p);if(!m)return;const v=m[1]||"",g=n(v);if(!o.find(b=>!(b in g)))return{type:e,raw:m[0],attributes:g}}},renderMarkdown:u=>{const h=l(u.attrs||{}),d=i(h),p=d?` {${d}}`:"";return`:::${c}${p} :::`}}}function bK(s){const{nodeName:e,name:t,getContent:n,parseAttributes:i=WE,serializeAttributes:r=zE,defaultAttributes:o={},content:a="block",allowedAttributes:c}=s,l=t||e,u=h=>{if(!c)return h;const d={};return c.forEach(p=>{p in h&&(d[p]=h[p])}),d};return{parseMarkdown:(h,d)=>{let p;if(n){const v=n(h);p=typeof v=="string"?[{type:"text",text:v}]:v}else a==="block"?p=d.parseChildren(h.tokens||[]):p=d.parseInline(h.tokens||[]);const m={...o,...h.attributes};return d.createNode(e,m,p)},markdownTokenizer:{name:e,level:"block",start(h){var d;const p=new RegExp(`^:::${l}`,"m"),m=(d=h.match(p))==null?void 0:d.index;return m!==void 0?m:-1},tokenize(h,d,p){var m;const v=new RegExp(`^:::${l}(?:\\s+\\{([^}]*)\\})?\\s*\\n`),g=h.match(v);if(!g)return;const[y,b=""]=g,_=i(b);let w=1;const S=y.length;let C="";const T=/^:::([\w-]*)(\s.*)?/gm,k=h.slice(S);for(T.lastIndex=0;;){const A=T.exec(k);if(A===null)break;const M=A.index,R=A[1];if(!((m=A[2])!=null&&m.endsWith(":::"))){if(R)w+=1;else if(w-=1,w===0){const P=k.slice(0,M);C=P.trim();const L=h.slice(0,S+M+A[0].length);let z=[];if(C)if(a==="block")for(z=p.blockTokens(P),z.forEach(Q=>{Q.text&&(!Q.tokens||Q.tokens.length===0)&&(Q.tokens=p.inlineTokens(Q.text))});z.length>0;){const Q=z[z.length-1];if(Q.type==="paragraph"&&(!Q.text||Q.text.trim()===""))z.pop();else break}else z=p.inlineTokens(C);return{type:e,raw:L,attributes:_,content:C,tokens:z}}}}}},renderMarkdown:(h,d)=>{const p=u(h.attrs||{}),m=r(p),v=m?` {${m}}`:"",g=d.renderChildren(h.content||[],`
`);return`:::${l}${v}
${g}
:::`}}}function _K(s){if(!s.trim())return{};const e={},t=/(\w+)=(?:"([^"]*)"|'([^']*)')/g;let n=t.exec(s);for(;n!==null;){const[,i,r,o]=n;e[i]=r||o,n=t.exec(s)}return e}function SK(s){return Object.entries(s).filter(([,e])=>e!=null).map(([e,t])=>`${e}="${t}"`).join(" ")}function xO(s){const{nodeName:e,name:t,getContent:n,parseAttributes:i=_K,serializeAttributes:r=SK,defaultAttributes:o={},selfClosing:a=!1,allowedAttributes:c}=s,l=t||e,u=d=>{if(!c)return d;const p={};return c.forEach(m=>{const v=typeof m=="string"?m:m.name,g=typeof m=="string"?void 0:m.skipIfDefault;if(v in d){const y=d[v];if(g!==void 0&&y===g)return;p[v]=y}}),p},h=l.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return{parseMarkdown:(d,p)=>{const m={...o,...d.attributes};if(a)return p.createNode(e,m);const v=n?n(d):d.content||"";return v?p.createNode(e,m,[p.createTextNode(v)]):p.createNode(e,m,[])},markdownTokenizer:{name:e,level:"inline",start(d){const p=a?new RegExp(`\\[${h}\\s*[^\\]]*\\]`):new RegExp(`\\[${h}\\s*[^\\]]*\\][\\s\\S]*?\\[\\/${h}\\]`),m=d.match(p),v=m==null?void 0:m.index;return v!==void 0?v:-1},tokenize(d,p,m){const v=a?new RegExp(`^\\[${h}\\s*([^\\]]*)\\]`):new RegExp(`^\\[${h}\\s*([^\\]]*)\\]([\\s\\S]*?)\\[\\/${h}\\]`),g=d.match(v);if(!g)return;let y="",b="";if(a){const[,w]=g;b=w}else{const[,w,S]=g;b=w,y=S||""}const _=i(b.trim());return{type:e,raw:g[0],content:y.trim(),attributes:_}}},renderMarkdown:d=>{let p="";n?p=n(d):d.content&&d.content.length>0&&(p=d.content.filter(y=>y.type==="text").map(y=>y.text).join(""));const m=u(d.attrs||{}),v=r(m),g=v?` ${v}`:"";return a?`[${l}${g}]`:`[${l}${g}]${p}[/${l}]`}}}function X1(s,e,t){var n,i,r,o;const a=s.split(`
`),c=[];let l="",u=0;const h=e.baseIndentSize||2;for(;u<a.length;){const d=a[u],p=d.match(e.itemPattern);if(!p){if(c.length>0)break;if(d.trim()===""){u+=1,l=`${l}${d}
`;continue}else return}const m=e.extractItemData(p),{indentLevel:v,mainContent:g}=m;l=`${l}${d}
`;const y=[g];for(u+=1;u<a.length;){const S=a[u];if(S.trim()===""){const T=a.slice(u+1).findIndex(M=>M.trim()!=="");if(T===-1)break;if((((i=(n=a[u+1+T].match(/^(\s*)/))==null?void 0:n[1])==null?void 0:i.length)||0)>v){y.push(S),l=`${l}${S}
`,u+=1;continue}else break}if((((o=(r=S.match(/^(\s*)/))==null?void 0:r[1])==null?void 0:o.length)||0)>v)y.push(S),l=`${l}${S}
`,u+=1;else break}let b;const _=y.slice(1);if(_.length>0){const S=_.map(C=>C.slice(v+h)).join(`
`);S.trim()&&(e.customNestedParser?b=e.customNestedParser(S):b=t.blockTokens(S))}const w=e.createToken(m,b);c.push(w)}if(c.length!==0)return{items:c,raw:l}}function jE(s,e,t,n){if(!s||!Array.isArray(s.content))return"";const i=typeof t=="function"?t(n):t,[r,...o]=s.content,a=e.renderChildren([r]);let c=`${i}${a}`;return o&&o.length>0&&o.forEach((l,u)=>{var h,d;const p=(d=(h=e.renderChild)==null?void 0:h.call(e,l,u+1))!=null?d:e.renderChildren([l]);if(p!=null){const m=p.split(`
`).map(v=>v?e.indent(v):e.indent("")).join(`
`);c+=l.type==="paragraph"?`
${m}`:`
${m}`}}),c}function wK(s,e,t={}){const{state:n}=e,{doc:i,tr:r}=n,o=s;i.descendants((a,c)=>{const l=r.mapping.map(c),u=r.mapping.map(c)+a.nodeSize;let h=null;if(a.marks.forEach(p=>{if(p!==o)return!1;h=p}),!h)return;let d=!1;if(Object.keys(t).forEach(p=>{t[p]!==h.attrs[p]&&(d=!0)}),d){const p=s.type.create({...s.attrs,...t});r.removeMark(l,u,s.type),r.addMark(l,u,p)}}),r.docChanged&&e.view.dispatch(r)}var Sr=class IO extends UE{constructor(){super(...arguments),this.type="node"}static create(e={}){const t=typeof e=="function"?e():e;return new IO(t)}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}};function xf(s){return new rK({find:s.find,handler:({state:e,range:t,match:n,pasteEvent:i})=>{const r=ns(s.getAttributes,void 0,n,i);if(r===!1||r===null)return null;const{tr:o}=e,a=n[n.length-1],c=n[0];let l=t.to;if(a){const u=c.search(/\S/),h=t.from+c.indexOf(a),d=h+a.length;if(HE(t.from,t.to,e.doc).filter(v=>v.mark.type.excluded.find(y=>y===s.type&&y!==v.mark.type)).filter(v=>v.to>h).length)return null;d<t.to&&o.delete(d,t.to),h>t.from&&o.delete(t.from+u,h),l=t.from+u+a.length,o.addMark(t.from+u,l,s.type.create(r||{})),n.index!==void 0&&n.input!==void 0&&n.index+n[0].length>=n.input.length||o.removeStoredMark(s.type)}}})}function fI(s){return RF((e,t)=>({get(){return e(),s},set(n){s=n,requestAnimationFrame(()=>{requestAnimationFrame(()=>{t()})})}}))}var kK=class extends fK{constructor(s={}){return super(s),this.contentComponent=null,this.appContext=null,this.reactiveState=fI(this.view.state),this.reactiveExtensionStorage=fI(this.extensionStorage),this.on("beforeTransaction",({nextState:e})=>{this.reactiveState.value=e,this.reactiveExtensionStorage.value=this.extensionStorage}),rE(this)}get state(){return this.reactiveState?this.reactiveState.value:this.view.state}get storage(){return this.reactiveExtensionStorage?this.reactiveExtensionStorage.value:super.storage}registerPlugin(s,e){const t=super.registerPlugin(s,e);return this.reactiveState&&(this.reactiveState.value=t),t}unregisterPlugin(s){const e=super.unregisterPlugin(s);return this.reactiveState&&e&&(this.reactiveState.value=e),e}},CK=at({name:"EditorContent",props:{editor:{default:null,type:Object}},setup(s){const e=pe(),t=LF();return b2(()=>{const n=s.editor;n&&n.options.element&&e.value&&ft(()=>{var i;if(!e.value||!((i=n.view.dom)!=null&&i.parentNode))return;const r=We(e.value);e.value.append(...n.view.dom.parentNode.childNodes),n.contentComponent=t.ctx._,t&&(n.appContext={...t.appContext,provides:t.provides}),n.setOptions({element:r}),n.createNodeViews()})}),xn(()=>{const n=s.editor;n&&(n.contentComponent=null,n.appContext=null)}),{rootEl:e}},render(){return xF("div",{ref:s=>{this.rootEl=s}})}}),TK=(s={})=>{const e=IF();return Cn(()=>{e.value=new kK(s)}),xn(()=>{var t;(t=e.value)==null||t.destroy()}),e},Lw=(s,e)=>{if(s==="slot")return 0;if(s instanceof Function)return s(e);const{children:t,...n}=e??{};if(s==="svg")throw new Error("SVG elements are not supported in the JSX syntax, use the array syntax instead");return[s,n,t]};function RO(s,e,t){for(let n=0;;n++){if(n==s.childCount||n==e.childCount)return s.childCount==e.childCount?null:t;let i=s.child(n),r=e.child(n);if(i==r){t+=i.nodeSize;continue}if(!i.sameMarkup(r))return t;if(i.isText&&i.text!=r.text){for(let o=0;i.text[o]==r.text[o];o++)t++;return t}if(i.content.size||r.content.size){let o=RO(i.content,r.content,t+1);if(o!=null)return o}t+=i.nodeSize}}function LO(s,e,t,n){for(let i=s.childCount,r=e.childCount;;){if(i==0||r==0)return i==r?null:{a:t,b:n};let o=s.child(--i),a=e.child(--r),c=o.nodeSize;if(o==a){t-=c,n-=c;continue}if(!o.sameMarkup(a))return{a:t,b:n};if(o.isText&&o.text!=a.text){let l=0,u=Math.min(o.text.length,a.text.length);for(;l<u&&o.text[o.text.length-l-1]==a.text[a.text.length-l-1];)l++,t--,n--;return{a:t,b:n}}if(o.content.size||a.content.size){let l=LO(o.content,a.content,t-1,n-1);if(l)return l}t-=c,n-=c}}var Ac=class Fi{constructor(e,t){if(this.content=e,this.size=t||0,t==null)for(let n=0;n<e.length;n++)this.size+=e[n].nodeSize}nodesBetween(e,t,n,i=0,r){for(let o=0,a=0;a<t;o++){let c=this.content[o],l=a+c.nodeSize;if(l>e&&n(c,i+a,r||null,o)!==!1&&c.content.size){let u=a+1;c.nodesBetween(Math.max(0,e-u),Math.min(c.content.size,t-u),n,i+u)}a=l}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,t,n,i){let r="",o=!0;return this.nodesBetween(e,t,(a,c)=>{let l=a.isText?a.text.slice(Math.max(e,c)-c,t-c):a.isLeaf?i?typeof i=="function"?i(a):i:a.type.spec.leafText?a.type.spec.leafText(a):"":"";a.isBlock&&(a.isLeaf&&l||a.isTextblock)&&n&&(o?o=!1:r+=n),r+=l},0),r}append(e){if(!e.size)return this;if(!this.size)return e;let t=this.lastChild,n=e.firstChild,i=this.content.slice(),r=0;for(t.isText&&t.sameMarkup(n)&&(i[i.length-1]=t.withText(t.text+n.text),r=1);r<e.content.length;r++)i.push(e.content[r]);return new Fi(i,this.size+e.size)}cut(e,t=this.size){if(e==0&&t==this.size)return this;let n=[],i=0;if(t>e)for(let r=0,o=0;o<t;r++){let a=this.content[r],c=o+a.nodeSize;c>e&&((o<e||c>t)&&(a.isText?a=a.cut(Math.max(0,e-o),Math.min(a.text.length,t-o)):a=a.cut(Math.max(0,e-o-1),Math.min(a.content.size,t-o-1))),n.push(a),i+=a.nodeSize),o=c}return new Fi(n,i)}cutByIndex(e,t){return e==t?Fi.empty:e==0&&t==this.content.length?this:new Fi(this.content.slice(e,t))}replaceChild(e,t){let n=this.content[e];if(n==t)return this;let i=this.content.slice(),r=this.size+t.nodeSize-n.nodeSize;return i[e]=t,new Fi(i,r)}addToStart(e){return new Fi([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new Fi(this.content.concat(e),this.size+e.nodeSize)}eq(e){if(this.content.length!=e.content.length)return!1;for(let t=0;t<this.content.length;t++)if(!this.content[t].eq(e.content[t]))return!1;return!0}get firstChild(){return this.content.length?this.content[0]:null}get lastChild(){return this.content.length?this.content[this.content.length-1]:null}get childCount(){return this.content.length}child(e){let t=this.content[e];if(!t)throw new RangeError("Index "+e+" out of range for "+this);return t}maybeChild(e){return this.content[e]||null}forEach(e){for(let t=0,n=0;t<this.content.length;t++){let i=this.content[t];e(i,n,t),n+=i.nodeSize}}findDiffStart(e,t=0){return RO(this,e,t)}findDiffEnd(e,t=this.size,n=e.size){return LO(this,e,t,n)}findIndex(e){if(e==0)return O_(0,e);if(e==this.size)return O_(this.content.length,e);if(e>this.size||e<0)throw new RangeError(`Position ${e} outside of fragment (${this})`);for(let t=0,n=0;;t++){let i=this.child(t),r=n+i.nodeSize;if(r>=e)return r==e?O_(t+1,r):O_(t,n);n=r}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(e=>e.toJSON()):null}static fromJSON(e,t){if(!t)return Fi.empty;if(!Array.isArray(t))throw new RangeError("Invalid input for Fragment.fromJSON");return Fi.fromArray(t.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return Fi.empty;let t,n=0;for(let i=0;i<e.length;i++){let r=e[i];n+=r.nodeSize,i&&r.isText&&e[i-1].sameMarkup(r)?(t||(t=e.slice(0,i)),t[t.length-1]=r.withText(t[t.length-1].text+r.text)):t&&t.push(r)}return new Fi(t||e,n)}static from(e){if(!e)return Fi.empty;if(e instanceof Fi)return e;if(Array.isArray(e))return this.fromArray(e);if(e.attrs)return new Fi([e],e.nodeSize);throw new RangeError("Can not convert "+e+" to a Fragment"+(e.nodesBetween?" (looks like multiple versions of prosemirror-model were loaded)":""))}};Ac.empty=new Ac([],0);var kC={index:0,offset:0};function O_(s,e){return kC.index=s,kC.offset=e,kC}var AK=class extends Error{},bn=class op{constructor(e,t,n){this.content=e,this.openStart=t,this.openEnd=n}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(e,t){let n=OO(this.content,e+this.openStart,t,this.openStart+1,this.openEnd+1);return n&&new op(n,this.openStart,this.openEnd)}removeBetween(e,t){return new op(PO(this.content,e+this.openStart,t+this.openStart),this.openStart,this.openEnd)}eq(e){return this.content.eq(e.content)&&this.openStart==e.openStart&&this.openEnd==e.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let e={content:this.content.toJSON()};return this.openStart>0&&(e.openStart=this.openStart),this.openEnd>0&&(e.openEnd=this.openEnd),e}static fromJSON(e,t){if(!t)return op.empty;let n=t.openStart||0,i=t.openEnd||0;if(typeof n!="number"||typeof i!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new op(Ac.fromJSON(e,t.content),n,i)}static maxOpen(e,t=!0){let n=0,i=0;for(let r=e.firstChild;r&&!r.isLeaf&&(t||!r.type.spec.isolating);r=r.firstChild)n++;for(let r=e.lastChild;r&&!r.isLeaf&&(t||!r.type.spec.isolating);r=r.lastChild)i++;return new op(e,n,i)}};bn.empty=new bn(Ac.empty,0,0);function PO(s,e,t){let{index:n,offset:i}=s.findIndex(e),r=s.maybeChild(n),{index:o,offset:a}=s.findIndex(t);if(i==e||r.isText){if(a!=t&&!s.child(o).isText)throw new RangeError("Removing non-flat range");return s.cut(0,e).append(s.cut(t))}if(n!=o)throw new RangeError("Removing non-flat range");return s.replaceChild(n,r.copy(PO(r.content,e-i-1,t-i-1)))}function OO(s,e,t,n,i,r){let{index:o,offset:a}=s.findIndex(e),c=s.maybeChild(o);if(a==e||c.isText)return r&&n<=0&&i<=0&&!r.canReplace(o,o,t)?null:s.cut(0,e).append(t).append(s.cut(e));let l=OO(c.content,e-a-1,t,o==0?n-1:0,o==s.childCount-1?i-1:0,c);return l&&s.replaceChild(o,c.copy(l))}var DO=65535,NO=Math.pow(2,16);function EK(s,e){return s+e*NO}function pI(s){return s&DO}function MK(s){return(s-(s&DO))/NO}var BO=1,FO=2,mS=4,$O=8,gI=class{constructor(s,e,t){this.pos=s,this.delInfo=e,this.recover=t}get deleted(){return(this.delInfo&$O)>0}get deletedBefore(){return(this.delInfo&(BO|mS))>0}get deletedAfter(){return(this.delInfo&(FO|mS))>0}get deletedAcross(){return(this.delInfo&mS)>0}},If=class ap{constructor(e,t=!1){if(this.ranges=e,this.inverted=t,!e.length&&ap.empty)return ap.empty}recover(e){let t=0,n=pI(e);if(!this.inverted)for(let i=0;i<n;i++)t+=this.ranges[i*3+2]-this.ranges[i*3+1];return this.ranges[n*3]+t+MK(e)}mapResult(e,t=1){return this._map(e,t,!1)}map(e,t=1){return this._map(e,t,!0)}_map(e,t,n){let i=0,r=this.inverted?2:1,o=this.inverted?1:2;for(let a=0;a<this.ranges.length;a+=3){let c=this.ranges[a]-(this.inverted?i:0);if(c>e)break;let l=this.ranges[a+r],u=this.ranges[a+o],h=c+l;if(e<=h){let d=l?e==c?-1:e==h?1:t:t,p=c+i+(d<0?0:u);if(n)return p;let m=e==(t<0?c:h)?null:EK(a/3,e-c),v=e==c?FO:e==h?BO:mS;return(t<0?e!=c:e!=h)&&(v|=$O),new gI(p,v,m)}i+=u-l}return n?e+i:new gI(e+i,0,null)}touches(e,t){let n=0,i=pI(t),r=this.inverted?2:1,o=this.inverted?1:2;for(let a=0;a<this.ranges.length;a+=3){let c=this.ranges[a]-(this.inverted?n:0);if(c>e)break;let l=this.ranges[a+r],u=c+l;if(e<=u&&a==i*3)return!0;n+=this.ranges[a+o]-l}return!1}forEach(e){let t=this.inverted?2:1,n=this.inverted?1:2;for(let i=0,r=0;i<this.ranges.length;i+=3){let o=this.ranges[i],a=o-(this.inverted?r:0),c=o+(this.inverted?0:r),l=this.ranges[i+t],u=this.ranges[i+n];e(a,a+l,c,c+u),r+=u-l}}invert(){return new ap(this.ranges,!this.inverted)}toString(){return(this.inverted?"-":"")+JSON.stringify(this.ranges)}static offset(e){return e==0?ap.empty:new ap(e<0?[0,-e,0]:[0,0,e])}};If.empty=new If([]);var CC=Object.create(null),Oi=class{getMap(){return If.empty}merge(s){return null}static fromJSON(s,e){if(!e||!e.stepType)throw new RangeError("Invalid input for Step.fromJSON");let t=CC[e.stepType];if(!t)throw new RangeError(`No step type ${e.stepType} defined`);return t.fromJSON(s,e)}static jsonID(s,e){if(s in CC)throw new RangeError("Duplicate use of step JSON ID "+s);return CC[s]=e,e.prototype.jsonID=s,e}},Yi=class Um{constructor(e,t){this.doc=e,this.failed=t}static ok(e){return new Um(e,null)}static fail(e){return new Um(null,e)}static fromReplace(e,t,n,i){try{return Um.ok(e.replace(t,n,i))}catch(r){if(r instanceof AK)return Um.fail(r.message);throw r}}};function VE(s,e,t){let n=[];for(let i=0;i<s.childCount;i++){let r=s.child(i);r.content.size&&(r=r.copy(VE(r.content,e,r))),r.isInline&&(r=e(r,t,i)),n.push(r)}return Ac.fromArray(n)}var HO=class Wm extends Oi{constructor(e,t,n){super(),this.from=e,this.to=t,this.mark=n}apply(e){let t=e.slice(this.from,this.to),n=e.resolve(this.from),i=n.node(n.sharedDepth(this.to)),r=new bn(VE(t.content,(o,a)=>!o.isAtom||!a.type.allowsMarkType(this.mark.type)?o:o.mark(this.mark.addToSet(o.marks)),i),t.openStart,t.openEnd);return Yi.fromReplace(e,this.from,this.to,r)}invert(){return new UO(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),n=e.mapResult(this.to,-1);return t.deleted&&n.deleted||t.pos>=n.pos?null:new Wm(t.pos,n.pos,this.mark)}merge(e){return e instanceof Wm&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new Wm(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new Wm(t.from,t.to,e.markFromJSON(t.mark))}};Oi.jsonID("addMark",HO);var UO=class zm extends Oi{constructor(e,t,n){super(),this.from=e,this.to=t,this.mark=n}apply(e){let t=e.slice(this.from,this.to),n=new bn(VE(t.content,i=>i.mark(this.mark.removeFromSet(i.marks)),e),t.openStart,t.openEnd);return Yi.fromReplace(e,this.from,this.to,n)}invert(){return new HO(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),n=e.mapResult(this.to,-1);return t.deleted&&n.deleted||t.pos>=n.pos?null:new zm(t.pos,n.pos,this.mark)}merge(e){return e instanceof zm&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new zm(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new zm(t.from,t.to,e.markFromJSON(t.mark))}};Oi.jsonID("removeMark",UO);var WO=class jm extends Oi{constructor(e,t){super(),this.pos=e,this.mark=t}apply(e){let t=e.nodeAt(this.pos);if(!t)return Yi.fail("No node at mark step's position");let n=t.type.create(t.attrs,null,this.mark.addToSet(t.marks));return Yi.fromReplace(e,this.pos,this.pos+1,new bn(Ac.from(n),0,t.isLeaf?0:1))}invert(e){let t=e.nodeAt(this.pos);if(t){let n=this.mark.addToSet(t.marks);if(n.length==t.marks.length){for(let i=0;i<t.marks.length;i++)if(!t.marks[i].isInSet(n))return new jm(this.pos,t.marks[i]);return new jm(this.pos,this.mark)}}return new zO(this.pos,this.mark)}map(e){let t=e.mapResult(this.pos,1);return t.deletedAfter?null:new jm(t.pos,this.mark)}toJSON(){return{stepType:"addNodeMark",pos:this.pos,mark:this.mark.toJSON()}}static fromJSON(e,t){if(typeof t.pos!="number")throw new RangeError("Invalid input for AddNodeMarkStep.fromJSON");return new jm(t.pos,e.markFromJSON(t.mark))}};Oi.jsonID("addNodeMark",WO);var zO=class Y1 extends Oi{constructor(e,t){super(),this.pos=e,this.mark=t}apply(e){let t=e.nodeAt(this.pos);if(!t)return Yi.fail("No node at mark step's position");let n=t.type.create(t.attrs,null,this.mark.removeFromSet(t.marks));return Yi.fromReplace(e,this.pos,this.pos+1,new bn(Ac.from(n),0,t.isLeaf?0:1))}invert(e){let t=e.nodeAt(this.pos);return!t||!this.mark.isInSet(t.marks)?this:new WO(this.pos,this.mark)}map(e){let t=e.mapResult(this.pos,1);return t.deletedAfter?null:new Y1(t.pos,this.mark)}toJSON(){return{stepType:"removeNodeMark",pos:this.pos,mark:this.mark.toJSON()}}static fromJSON(e,t){if(typeof t.pos!="number")throw new RangeError("Invalid input for RemoveNodeMarkStep.fromJSON");return new Y1(t.pos,e.markFromJSON(t.mark))}};Oi.jsonID("removeNodeMark",zO);var GE=class Gc extends Oi{constructor(e,t,n,i=!1){super(),this.from=e,this.to=t,this.slice=n,this.structure=i}apply(e){return this.structure&&J1(e,this.from,this.to)?Yi.fail("Structure replace would overwrite content"):Yi.fromReplace(e,this.from,this.to,this.slice)}getMap(){return new If([this.from,this.to-this.from,this.slice.size])}invert(e){return new Gc(this.from,this.from+this.slice.size,e.slice(this.from,this.to))}map(e){let t=e.mapResult(this.to,-1),n=this.from==this.to&&Gc.MAP_BIAS<0?t:e.mapResult(this.from,1);return n.deletedAcross&&t.deletedAcross?null:new Gc(n.pos,Math.max(n.pos,t.pos),this.slice,this.structure)}merge(e){if(!(e instanceof Gc)||e.structure||this.structure)return null;if(this.from+this.slice.size==e.from&&!this.slice.openEnd&&!e.slice.openStart){let t=this.slice.size+e.slice.size==0?bn.empty:new bn(this.slice.content.append(e.slice.content),this.slice.openStart,e.slice.openEnd);return new Gc(this.from,this.to+(e.to-e.from),t,this.structure)}else if(e.to==this.from&&!this.slice.openStart&&!e.slice.openEnd){let t=this.slice.size+e.slice.size==0?bn.empty:new bn(e.slice.content.append(this.slice.content),e.slice.openStart,this.slice.openEnd);return new Gc(e.from,this.to,t,this.structure)}else return null}toJSON(){let e={stepType:"replace",from:this.from,to:this.to};return this.slice.size&&(e.slice=this.slice.toJSON()),this.structure&&(e.structure=!0),e}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for ReplaceStep.fromJSON");return new Gc(t.from,t.to,bn.fromJSON(e,t.slice),!!t.structure)}};GE.MAP_BIAS=1;Oi.jsonID("replace",GE);var jO=class vS extends Oi{constructor(e,t,n,i,r,o,a=!1){super(),this.from=e,this.to=t,this.gapFrom=n,this.gapTo=i,this.slice=r,this.insert=o,this.structure=a}apply(e){if(this.structure&&(J1(e,this.from,this.gapFrom)||J1(e,this.gapTo,this.to)))return Yi.fail("Structure gap-replace would overwrite content");let t=e.slice(this.gapFrom,this.gapTo);if(t.openStart||t.openEnd)return Yi.fail("Gap is not a flat range");let n=this.slice.insertAt(this.insert,t.content);return n?Yi.fromReplace(e,this.from,this.to,n):Yi.fail("Content does not fit in gap")}getMap(){return new If([this.from,this.gapFrom-this.from,this.insert,this.gapTo,this.to-this.gapTo,this.slice.size-this.insert])}invert(e){let t=this.gapTo-this.gapFrom;return new vS(this.from,this.from+this.slice.size+t,this.from+this.insert,this.from+this.insert+t,e.slice(this.from,this.to).removeBetween(this.gapFrom-this.from,this.gapTo-this.from),this.gapFrom-this.from,this.structure)}map(e){let t=e.mapResult(this.from,1),n=e.mapResult(this.to,-1),i=this.from==this.gapFrom?t.pos:e.map(this.gapFrom,-1),r=this.to==this.gapTo?n.pos:e.map(this.gapTo,1);return t.deletedAcross&&n.deletedAcross||i<t.pos||r>n.pos?null:new vS(t.pos,n.pos,i,r,this.slice,this.insert,this.structure)}toJSON(){let e={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(e.slice=this.slice.toJSON()),this.structure&&(e.structure=!0),e}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number"||typeof t.gapFrom!="number"||typeof t.gapTo!="number"||typeof t.insert!="number")throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new vS(t.from,t.to,t.gapFrom,t.gapTo,bn.fromJSON(e,t.slice),t.insert,!!t.structure)}};Oi.jsonID("replaceAround",jO);function J1(s,e,t){let n=s.resolve(e),i=t-e,r=n.depth;for(;i>0&&r>0&&n.indexAfter(r)==n.node(r).childCount;)r--,i--;if(i>0){let o=n.node(r).maybeChild(n.indexAfter(r));for(;i>0;){if(!o||o.isLeaf)return!0;o=o.firstChild,i--}}return!1}var xK=class yS extends Oi{constructor(e,t,n){super(),this.pos=e,this.attr=t,this.value=n}apply(e){let t=e.nodeAt(this.pos);if(!t)return Yi.fail("No node at attribute step's position");let n=Object.create(null);for(let r in t.attrs)n[r]=t.attrs[r];n[this.attr]=this.value;let i=t.type.create(n,null,t.marks);return Yi.fromReplace(e,this.pos,this.pos+1,new bn(Ac.from(i),0,t.isLeaf?0:1))}getMap(){return If.empty}invert(e){return new yS(this.pos,this.attr,e.nodeAt(this.pos).attrs[this.attr])}map(e){let t=e.mapResult(this.pos,1);return t.deletedAfter?null:new yS(t.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.pos!="number"||typeof t.attr!="string")throw new RangeError("Invalid input for AttrStep.fromJSON");return new yS(t.pos,t.attr,t.value)}};Oi.jsonID("attr",xK);var IK=class Z1 extends Oi{constructor(e,t){super(),this.attr=e,this.value=t}apply(e){let t=Object.create(null);for(let i in e.attrs)t[i]=e.attrs[i];t[this.attr]=this.value;let n=e.type.create(t,e.content,e.marks);return Yi.ok(n)}getMap(){return If.empty}invert(e){return new Z1(this.attr,e.attrs[this.attr])}map(e){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.attr!="string")throw new RangeError("Invalid input for DocAttrStep.fromJSON");return new Z1(t.attr,t.value)}};Oi.jsonID("docAttr",IK);var sy=class extends Error{};sy=function s(e){let t=Error.call(this,e);return t.__proto__=s.prototype,t};sy.prototype=Object.create(Error.prototype);sy.prototype.constructor=sy;sy.prototype.name="TransformError";var TC=Object.create(null),Qn=class{constructor(s,e,t){this.$anchor=s,this.$head=e,this.ranges=t||[new RK(s.min(e),s.max(e))]}get anchor(){return this.$anchor.pos}get head(){return this.$head.pos}get from(){return this.$from.pos}get to(){return this.$to.pos}get $from(){return this.ranges[0].$from}get $to(){return this.ranges[0].$to}get empty(){let s=this.ranges;for(let e=0;e<s.length;e++)if(s[e].$from.pos!=s[e].$to.pos)return!1;return!0}content(){return this.$from.doc.slice(this.from,this.to,!0)}replace(s,e=bn.empty){let t=e.content.lastChild,n=null;for(let o=0;o<e.openEnd;o++)n=t,t=t.lastChild;let i=s.steps.length,r=this.ranges;for(let o=0;o<r.length;o++){let{$from:a,$to:c}=r[o],l=s.mapping.slice(i);s.replaceRange(l.map(a.pos),l.map(c.pos),o?bn.empty:e),o==0&&yI(s,i,(t?t.isInline:n&&n.isTextblock)?-1:1)}}replaceWith(s,e){let t=s.steps.length,n=this.ranges;for(let i=0;i<n.length;i++){let{$from:r,$to:o}=n[i],a=s.mapping.slice(t),c=a.map(r.pos),l=a.map(o.pos);i?s.deleteRange(c,l):(s.replaceRangeWith(c,l,e),yI(s,t,e.isInline?-1:1))}}static findFrom(s,e,t=!1){let n=s.parent.inlineContent?new rm(s):lp(s.node(0),s.parent,s.pos,s.index(),e,t);if(n)return n;for(let i=s.depth-1;i>=0;i--){let r=e<0?lp(s.node(0),s.node(i),s.before(i+1),s.index(i),e,t):lp(s.node(0),s.node(i),s.after(i+1),s.index(i)+1,e,t);if(r)return r}return null}static near(s,e=1){return this.findFrom(s,e)||this.findFrom(s,-e)||new Rv(s.node(0))}static atStart(s){return lp(s,s,0,0,1)||new Rv(s)}static atEnd(s){return lp(s,s,s.content.size,s.childCount,-1)||new Rv(s)}static fromJSON(s,e){if(!e||!e.type)throw new RangeError("Invalid input for Selection.fromJSON");let t=TC[e.type];if(!t)throw new RangeError(`No selection type ${e.type} defined`);return t.fromJSON(s,e)}static jsonID(s,e){if(s in TC)throw new RangeError("Duplicate use of selection JSON ID "+s);return TC[s]=e,e.prototype.jsonID=s,e}getBookmark(){return rm.between(this.$anchor,this.$head).getBookmark()}};Qn.prototype.visible=!0;var RK=class{constructor(s,e){this.$from=s,this.$to=e}},mI=!1;function vI(s){!mI&&!s.parent.inlineContent&&(mI=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+s.parent.type.name+")"))}var rm=class Vm extends Qn{constructor(e,t=e){vI(e),vI(t),super(e,t)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(e,t){let n=e.resolve(t.map(this.head));if(!n.parent.inlineContent)return Qn.near(n);let i=e.resolve(t.map(this.anchor));return new Vm(i.parent.inlineContent?i:n,n)}replace(e,t=bn.empty){if(super.replace(e,t),t==bn.empty){let n=this.$from.marksAcross(this.$to);n&&e.ensureMarks(n)}}eq(e){return e instanceof Vm&&e.anchor==this.anchor&&e.head==this.head}getBookmark(){return new VO(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(e,t){if(typeof t.anchor!="number"||typeof t.head!="number")throw new RangeError("Invalid input for TextSelection.fromJSON");return new Vm(e.resolve(t.anchor),e.resolve(t.head))}static create(e,t,n=t){let i=e.resolve(t);return new this(i,n==t?i:e.resolve(n))}static between(e,t,n){let i=e.pos-t.pos;if((!n||i)&&(n=i>=0?1:-1),!t.parent.inlineContent){let r=Qn.findFrom(t,n,!0)||Qn.findFrom(t,-n,!0);if(r)t=r.$head;else return Qn.near(t,n)}return e.parent.inlineContent||(i==0?e=t:(e=(Qn.findFrom(e,-n,!0)||Qn.findFrom(e,n,!0)).$anchor,e.pos<t.pos!=i<0&&(e=t))),new Vm(e,t)}};Qn.jsonID("text",rm);var VO=class GO{constructor(e,t){this.anchor=e,this.head=t}map(e){return new GO(e.map(this.anchor),e.map(this.head))}resolve(e){return rm.between(e.resolve(this.anchor),e.resolve(this.head))}},om=class Gm extends Qn{constructor(e){let t=e.nodeAfter,n=e.node(0).resolve(e.pos+t.nodeSize);super(e,n),this.node=t}map(e,t){let{deleted:n,pos:i}=t.mapResult(this.anchor),r=e.resolve(i);return n?Qn.near(r):new Gm(r)}content(){return new bn(Ac.from(this.node),0,0)}eq(e){return e instanceof Gm&&e.anchor==this.anchor}toJSON(){return{type:"node",anchor:this.anchor}}getBookmark(){return new LK(this.anchor)}static fromJSON(e,t){if(typeof t.anchor!="number")throw new RangeError("Invalid input for NodeSelection.fromJSON");return new Gm(e.resolve(t.anchor))}static create(e,t){return new Gm(e.resolve(t))}static isSelectable(e){return!e.isText&&e.type.spec.selectable!==!1}};om.prototype.visible=!1;Qn.jsonID("node",om);var LK=class qO{constructor(e){this.anchor=e}map(e){let{deleted:t,pos:n}=e.mapResult(this.anchor);return t?new VO(n,n):new qO(n)}resolve(e){let t=e.resolve(this.anchor),n=t.nodeAfter;return n&&om.isSelectable(n)?new om(t):Qn.near(t)}},Rv=class bS extends Qn{constructor(e){super(e.resolve(0),e.resolve(e.content.size))}replace(e,t=bn.empty){if(t==bn.empty){e.delete(0,e.doc.content.size);let n=Qn.atStart(e.doc);n.eq(e.selection)||e.setSelection(n)}else super.replace(e,t)}toJSON(){return{type:"all"}}static fromJSON(e){return new bS(e)}map(e){return new bS(e)}eq(e){return e instanceof bS}getBookmark(){return PK}};Qn.jsonID("all",Rv);var PK={map(){return this},resolve(s){return new Rv(s)}};function lp(s,e,t,n,i,r=!1){if(e.inlineContent)return rm.create(s,t);for(let o=n-(i>0?0:1);i>0?o<e.childCount:o>=0;o+=i){let a=e.child(o);if(a.isAtom){if(!r&&om.isSelectable(a))return om.create(s,t-(i<0?a.nodeSize:0))}else{let c=lp(s,a,t+i,i<0?a.childCount:0,i,r);if(c)return c}t+=a.nodeSize*i}return null}function yI(s,e,t){let n=s.steps.length-1;if(n<e)return;let i=s.steps[n];if(!(i instanceof GE||i instanceof jO))return;let r=s.mapping.maps[n],o;r.forEach((a,c,l,u)=>{o==null&&(o=u)}),s.setSelection(Qn.near(s.doc.resolve(o),t))}function bI(s,e){return!e||!s?s:s.bind(e)}var D_=class{constructor(s,e,t){this.name=s,this.init=bI(e.init,t),this.apply=bI(e.apply,t)}};new D_("doc",{init(s){return s.doc||s.schema.topNodeType.createAndFill()},apply(s){return s.doc}}),new D_("selection",{init(s,e){return s.selection||Qn.atStart(e.doc)},apply(s){return s.selection}}),new D_("storedMarks",{init(s){return s.storedMarks||null},apply(s,e,t,n){return n.selection.$cursor?s.storedMarks:null}}),new D_("scrollToSelection",{init(){return 0},apply(s,e){return s.scrolledIntoView?e+1:e}});var OK=(s,e)=>{var t;const{state:n,view:i}=s,{selection:r}=n;if(!r.empty)return!1;const{$from:o}=r;if(o.parentOffset!==0)return!1;const a=o.depth-1,c=o.node(a),l=o.index(a);if(l===0)return!1;if(c.type===e)return s.commands.lift(e.name);const u=c.child(l-1);if(u.type!==e||!((t=u.lastChild)!=null&&t.isTextblock))return!1;const h=o.before(),p=h-1-1,{tr:m}=n;return m.delete(h,o.after()).insert(p,o.parent.content),m.setSelection(rm.create(m.doc,p)),i.dispatch(m.scrollIntoView()),!0},DK=/^\s*>\s$/,NK=Sr.create({name:"blockquote",addOptions(){return{HTMLAttributes:{}}},content:"block+",group:"block",defining:!0,parseHTML(){return[{tag:"blockquote"}]},renderHTML({HTMLAttributes:s}){return Lw("blockquote",{...Fs(this.options.HTMLAttributes,s),children:Lw("slot",{})})},parseMarkdown:(s,e)=>{var t;const n=(t=e.parseBlockChildren)!=null?t:e.parseChildren;return e.createNode("blockquote",void 0,n(s.tokens||[]))},renderMarkdown:(s,e)=>{if(!s.content)return"";const t=">",n=[];return s.content.forEach((i,r)=>{var o,a;const u=((a=(o=e.renderChild)==null?void 0:o.call(e,i,r))!=null?a:e.renderChildren([i])).split(`
`).map(h=>h.trim()===""?t:`${t} ${h}`);n.push(u.join(`
`))}),n.join(`
${t}
`)},addCommands(){return{setBlockquote:()=>({commands:s})=>s.wrapIn(this.name),toggleBlockquote:()=>({commands:s})=>s.toggleWrap(this.name),unsetBlockquote:()=>({commands:s})=>s.lift(this.name)}},addKeyboardShortcuts(){return{"Mod-Shift-b":()=>this.editor.commands.toggleBlockquote(),Backspace:()=>OK(this.editor,this.type)}},addInputRules(){return[im({find:DK,type:this.type})]}}),BK=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,FK=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,$K=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,HK=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g,UK=Df.create({name:"bold",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"strong"},{tag:"b",getAttrs:s=>s.style.fontWeight!=="normal"&&null},{style:"font-weight=400",clearMark:s=>s.type.name===this.name},{style:"font-weight",getAttrs:s=>/^(bold(er)?|[5-9]\d{2,})$/.test(s)&&null}]},renderHTML({HTMLAttributes:s}){return Lw("strong",{...Fs(this.options.HTMLAttributes,s),children:Lw("slot",{})})},markdownTokenName:"strong",parseMarkdown:(s,e)=>e.applyMark("bold",e.parseInline(s.tokens||[])),markdownOptions:{htmlReopen:{open:"<strong>",close:"</strong>"}},renderMarkdown:(s,e)=>`**${e.renderChildren(s)}**`,addCommands(){return{setBold:()=>({commands:s})=>s.setMark(this.name),toggleBold:()=>({commands:s})=>s.toggleMark(this.name),unsetBold:()=>({commands:s})=>s.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-b":()=>this.editor.commands.toggleBold(),"Mod-B":()=>this.editor.commands.toggleBold()}},addInputRules(){return[nm({find:BK,type:this.type}),nm({find:$K,type:this.type})]},addPasteRules(){return[xf({find:FK,type:this.type}),xf({find:HK,type:this.type})]}}),WK=s=>{const e=/`([^`]+)`(?!`)$/.exec(s);return!e||e.index>0&&s[e.index-1]==="`"?null:{index:e.index,text:e[0],replaceWith:e[1]}},zK=s=>{const e=/`([^`]+)`(?!`)/g,t=[];let n;for(;(n=e.exec(s))!==null;)n.index>0&&s[n.index-1]==="`"||t.push({index:n.index,text:n[0],replaceWith:n[1]});return t},jK=Df.create({name:"code",addOptions(){return{HTMLAttributes:{}}},excludes:"_",code:!0,exitable:!0,parseHTML(){return[{tag:"code"}]},renderHTML({HTMLAttributes:s}){return["code",Fs(this.options.HTMLAttributes,s),0]},markdownTokenName:"codespan",parseMarkdown:(s,e)=>e.applyMark("code",[{type:"text",text:s.text||""}]),renderMarkdown:(s,e)=>s.content?`\`${e.renderChildren(s.content)}\``:"",addCommands(){return{setCode:()=>({commands:s})=>s.setMark(this.name),toggleCode:()=>({commands:s})=>s.toggleMark(this.name),unsetCode:()=>({commands:s})=>s.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-e":()=>this.editor.commands.toggleCode()}},addInputRules(){return[nm({find:WK,type:this.type})]},addPasteRules(){return[xf({find:zK,type:this.type})]}}),AC=4,VK=/^```([a-z]+)?[\s\n]$/,GK=/^~~~([a-z]+)?[\s\n]$/,qK=Sr.create({name:"codeBlock",addOptions(){return{languageClassPrefix:"language-",exitOnTripleEnter:!0,exitOnArrowDown:!0,defaultLanguage:null,enableTabIndentation:!1,tabSize:AC,HTMLAttributes:{}}},content:"text*",marks:"",group:"block",code:!0,defining:!0,addAttributes(){return{language:{default:this.options.defaultLanguage,parseHTML:s=>{var e;const{languageClassPrefix:t}=this.options;if(!t)return null;const r=[...((e=s.firstElementChild)==null?void 0:e.classList)||[]].filter(o=>o.startsWith(t)).map(o=>o.replace(t,""))[0];return r||null},rendered:!1}}},parseHTML(){return[{tag:"pre",preserveWhitespace:"full"}]},renderHTML({node:s,HTMLAttributes:e}){return["pre",Fs(this.options.HTMLAttributes,e),["code",{class:s.attrs.language?this.options.languageClassPrefix+s.attrs.language:null},0]]},markdownTokenName:"code",parseMarkdown:(s,e)=>{var t,n;return((t=s.raw)==null?void 0:t.startsWith("```"))===!1&&((n=s.raw)==null?void 0:n.startsWith("~~~"))===!1&&s.codeBlockStyle!=="indented"?[]:e.createNode("codeBlock",{language:s.lang||null},s.text?[e.createTextNode(s.text)]:[])},renderMarkdown:(s,e)=>{var t;let n="";const i=((t=s.attrs)==null?void 0:t.language)||"";return s.content?n=[`\`\`\`${i}`,e.renderChildren(s.content),"```"].join(`
`):n=`\`\`\`${i}
\`\`\``,n},addCommands(){return{setCodeBlock:s=>({commands:e})=>e.setNode(this.name,s),toggleCodeBlock:s=>({commands:e})=>e.toggleNode(this.name,"paragraph",s)}},addKeyboardShortcuts(){return{"Mod-Alt-c":()=>this.editor.commands.toggleCodeBlock(),Backspace:()=>{const{empty:s,$anchor:e}=this.editor.state.selection,t=e.pos===1;return!s||e.parent.type.name!==this.name?!1:t||!e.parent.textContent.length?this.editor.commands.clearNodes():!1},Tab:({editor:s})=>{var e;if(!this.options.enableTabIndentation)return!1;const t=(e=this.options.tabSize)!=null?e:AC,{state:n}=s,{selection:i}=n,{$from:r,empty:o}=i;if(r.parent.type!==this.type)return!1;const a=" ".repeat(t);return o?s.commands.insertContent(a):s.commands.command(({tr:c})=>{const{from:l,to:u}=i,p=n.doc.textBetween(l,u,`
`,`
`).split(`
`).map(m=>a+m).join(`
`);return c.replaceWith(l,u,n.schema.text(p)),!0})},"Shift-Tab":({editor:s})=>{var e;if(!this.options.enableTabIndentation)return!1;const t=(e=this.options.tabSize)!=null?e:AC,{state:n}=s,{selection:i}=n,{$from:r,empty:o}=i;return r.parent.type!==this.type?!1:o?s.commands.command(({tr:a})=>{var c;const{pos:l}=r,u=r.start(),h=r.end(),p=n.doc.textBetween(u,h,`
`,`
`).split(`
`);let m=0,v=0;const g=l-u;for(let C=0;C<p.length;C+=1){if(v+p[C].length>=g){m=C;break}v+=p[C].length+1}const b=((c=p[m].match(/^ */))==null?void 0:c[0])||"",_=Math.min(b.length,t);if(_===0)return!0;let w=u;for(let C=0;C<m;C+=1)w+=p[C].length+1;return a.delete(w,w+_),l-w<=_&&a.setSelection(_t.create(a.doc,w)),!0}):s.commands.command(({tr:a})=>{const{from:c,to:l}=i,d=n.doc.textBetween(c,l,`
`,`
`).split(`
`).map(p=>{var m;const v=((m=p.match(/^ */))==null?void 0:m[0])||"",g=Math.min(v.length,t);return p.slice(g)}).join(`
`);return a.replaceWith(c,l,n.schema.text(d)),!0})},Enter:({editor:s})=>{if(!this.options.exitOnTripleEnter)return!1;const{state:e}=s,{selection:t}=e,{$from:n,empty:i}=t;if(!i||n.parent.type!==this.type)return!1;const r=n.parentOffset===n.parent.nodeSize-2,o=n.parent.textContent.endsWith(`
`);return!r||!o?!1:s.chain().command(({tr:a})=>(a.delete(n.pos-2,n.pos),!0)).exitCode().run()},ArrowDown:({editor:s})=>{if(!this.options.exitOnArrowDown)return!1;const{state:e}=s,{selection:t,doc:n}=e,{$from:i,empty:r}=t;if(!r||i.parent.type!==this.type||!(i.parentOffset===i.parent.nodeSize-2))return!1;const a=i.after();return a===void 0?!1:n.nodeAt(a)?s.commands.command(({tr:l})=>(l.setSelection(Ft.near(n.resolve(a))),!0)):s.commands.exitCode()}}},addInputRules(){return[Q1({find:VK,type:this.type,getAttributes:s=>({language:s[1]})}),Q1({find:GK,type:this.type,getAttributes:s=>({language:s[1]})})]},addProseMirrorPlugins(){return[new $s({key:new fn("codeBlockVSCodeHandler"),props:{handlePaste:(s,e)=>{if(!e.clipboardData||this.editor.isActive(this.type.name))return!1;const t=e.clipboardData.getData("text/plain"),n=e.clipboardData.getData("vscode-editor-data"),i=n?JSON.parse(n):void 0,r=i==null?void 0:i.mode;if(!t||!r)return!1;const{tr:o,schema:a}=s.state,c=a.text(t.replace(/\r\n?/g,`
`));return o.replaceSelectionWith(this.type.create({language:r},c)),o.selection.$from.parent.type!==this.type&&o.setSelection(_t.near(o.doc.resolve(Math.max(0,o.selection.from-2)))),o.setMeta("paste",!0),s.dispatch(o),!0}}})]}}),KK=Sr.create({name:"doc",topNode:!0,content:"block+",renderMarkdown:(s,e)=>s.content?e.renderChildren(s.content,`
`):""}),QK=Sr.create({name:"hardBreak",markdownTokenName:"br",addOptions(){return{keepMarks:!0,HTMLAttributes:{}}},inline:!0,group:"inline",selectable:!1,linebreakReplacement:!0,parseHTML(){return[{tag:"br"}]},renderHTML({HTMLAttributes:s}){return["br",Fs(this.options.HTMLAttributes,s)]},renderText(){return`
`},renderMarkdown:()=>`
`,parseMarkdown:()=>({type:"hardBreak"}),addCommands(){return{setHardBreak:()=>({commands:s,chain:e,state:t,editor:n})=>s.first([()=>s.exitCode(),()=>s.command(()=>{const{selection:i,storedMarks:r}=t;if(i.$from.parent.type.spec.isolating)return!1;const{keepMarks:o}=this.options,{splittableMarks:a}=n.extensionManager,c=r||i.$to.parentOffset&&i.$from.marks();return e().insertContent({type:this.name}).command(({tr:l,dispatch:u})=>{if(u&&c&&o){const h=c.filter(d=>a.includes(d.type.name));l.ensureMarks(h)}return!0}).run()})])}},addKeyboardShortcuts(){return{"Mod-Enter":()=>this.editor.commands.setHardBreak(),"Shift-Enter":()=>this.editor.commands.setHardBreak()}}}),XK=Sr.create({name:"heading",addOptions(){return{levels:[1,2,3,4,5,6],HTMLAttributes:{}}},content:"inline*",group:"block",defining:!0,addAttributes(){return{level:{default:1,rendered:!1}}},parseHTML(){return this.options.levels.map(s=>({tag:`h${s}`,attrs:{level:s}}))},renderHTML({node:s,HTMLAttributes:e}){return[`h${this.options.levels.includes(s.attrs.level)?s.attrs.level:this.options.levels[0]}`,Fs(this.options.HTMLAttributes,e),0]},parseMarkdown:(s,e)=>e.createNode("heading",{level:s.depth||1},e.parseInline(s.tokens||[])),renderMarkdown:(s,e)=>{var t;const n=(t=s.attrs)!=null&&t.level?parseInt(s.attrs.level,10):1,i="#".repeat(n);return s.content?`${i} ${e.renderChildren(s.content)}`:""},addCommands(){return{setHeading:s=>({commands:e})=>this.options.levels.includes(s.level)?e.setNode(this.name,s):!1,toggleHeading:s=>({commands:e})=>this.options.levels.includes(s.level)?e.toggleNode(this.name,"paragraph",s):!1}},addKeyboardShortcuts(){return this.options.levels.reduce((s,e)=>({...s,[`Mod-Alt-${e}`]:()=>this.editor.commands.toggleHeading({level:e})}),{})},addInputRules(){return this.options.levels.map(s=>Q1({find:new RegExp(`^(#{${Math.min(...this.options.levels)},${s}})\\s$`),type:this.type,getAttributes:{level:s}}))}}),YK=Sr.create({name:"horizontalRule",addOptions(){return{HTMLAttributes:{},nextNodeType:"paragraph"}},group:"block",parseHTML(){return[{tag:"hr"}]},renderHTML({HTMLAttributes:s}){return["hr",Fs(this.options.HTMLAttributes,s)]},markdownTokenName:"hr",parseMarkdown:(s,e)=>e.createNode("horizontalRule"),renderMarkdown:()=>"---",addCommands(){return{setHorizontalRule:()=>({chain:s,state:e})=>{if(!gK(e,e.schema.nodes[this.name]))return!1;const{selection:t}=e,{$to:n}=t,i=s();return hO(t)?i.insertContentAt(n.pos,{type:this.name}):i.insertContent({type:this.name}),i.command(({state:r,tr:o,dispatch:a})=>{if(a){const{$to:c}=o.selection,l=c.end();if(c.nodeAfter)c.nodeAfter.isTextblock?o.setSelection(_t.create(o.doc,c.pos+1)):c.nodeAfter.isBlock?o.setSelection(vt.create(o.doc,c.pos)):o.setSelection(_t.create(o.doc,c.pos));else{const u=r.schema.nodes[this.options.nextNodeType]||c.parent.type.contentMatch.defaultType,h=u==null?void 0:u.create();h&&(o.insert(l,h),o.setSelection(_t.create(o.doc,l+1)))}o.scrollIntoView()}return!0}).run()}}},addInputRules(){return[pK({find:/^(?:---|—-|___\s|\*\*\*\s)$/,type:this.type})]}}),JK=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,ZK=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,eQ=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,tQ=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g,sQ=Df.create({name:"italic",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"em"},{tag:"i",getAttrs:s=>s.style.fontStyle!=="normal"&&null},{style:"font-style=normal",clearMark:s=>s.type.name===this.name},{style:"font-style=italic"}]},renderHTML({HTMLAttributes:s}){return["em",Fs(this.options.HTMLAttributes,s),0]},addCommands(){return{setItalic:()=>({commands:s})=>s.setMark(this.name),toggleItalic:()=>({commands:s})=>s.toggleMark(this.name),unsetItalic:()=>({commands:s})=>s.unsetMark(this.name)}},markdownTokenName:"em",parseMarkdown:(s,e)=>e.applyMark("italic",e.parseInline(s.tokens||[])),markdownOptions:{htmlReopen:{open:"<em>",close:"</em>"}},renderMarkdown:(s,e)=>`*${e.renderChildren(s)}*`,addKeyboardShortcuts(){return{"Mod-i":()=>this.editor.commands.toggleItalic(),"Mod-I":()=>this.editor.commands.toggleItalic()}},addInputRules(){return[nm({find:JK,type:this.type}),nm({find:eQ,type:this.type})]},addPasteRules(){return[xf({find:ZK,type:this.type}),xf({find:tQ,type:this.type})]}});const nQ="aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2odyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos4niper7kaufen5ddi3e0rryhotels6properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3nd0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rck0msd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0axi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5mögensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2oodside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2",iQ="ελ1υ2бг1ел3дети4ею2католик6ом3мкд2он1сква6онлайн5рг3рус2ф2сайт3рб3украз3հայ3ישראל5קום3ابوظبي5رامكو5لاردن4بحرين5جزائر5سعودية6عليان5مغرب5مارات5یران5بارت2زار4يتك3ھارت5تونس4سودان3رية5شبكة4عراق2ب2مان4فلسطين6قطر3كاثوليك6وم3مصر2ليسيا5وريتانيا7قع4همراهاکستان7ڀارت4कॉम3नेट3भारत0म्3ोत5संगठन5বাংলা5ভারত2ৰত4ਭਾਰਤ4ભારત4ଭାରତ4இந்தியா6லங்கை6சிங்கப்பூர்11భారత్5ಭಾರತ4ഭാരത5ලකා4คอม3ไทย3ລາວ3გე2みんな3アマゾン4クラウド4グーグル4コム2ストア3セール3ファッション6ポイント4世界2中信1国1國1文网3亚马逊3企业2佛山2信息2健康2八卦2公司1益2台湾1灣2商城1店1标2嘉里0大酒店5在线2大拿2天主教3娱乐2家電2广东2微博2慈善2我爱你3手机2招聘2政务1府2新加坡2闻2时尚2書籍2机构2淡马锡3游戏2澳門2点看2移动2组织机构4网址1店1站1络2联通2谷歌2购物2通販2集团2電訊盈科4飞利浦3食品2餐厅2香格里拉3港2닷넷1컴2삼성2한국2",eT="numeric",tT="ascii",sT="alpha",Lv="asciinumeric",qm="alphanumeric",nT="domain",KO="emoji",rQ="scheme",oQ="slashscheme",EC="whitespace";function aQ(s,e){return s in e||(e[s]=[]),e[s]}function $h(s,e,t){e[eT]&&(e[Lv]=!0,e[qm]=!0),e[tT]&&(e[Lv]=!0,e[sT]=!0),e[Lv]&&(e[qm]=!0),e[sT]&&(e[qm]=!0),e[qm]&&(e[nT]=!0),e[KO]&&(e[nT]=!0);for(const n in e){const i=aQ(n,t);i.indexOf(s)<0&&i.push(s)}}function lQ(s,e){const t={};for(const n in e)e[n].indexOf(s)>=0&&(t[n]=!0);return t}function mr(s=null){this.j={},this.jr=[],this.jd=null,this.t=s}mr.groups={};mr.prototype={accepts(){return!!this.t},go(s){const e=this,t=e.j[s];if(t)return t;for(let n=0;n<e.jr.length;n++){const i=e.jr[n][0],r=e.jr[n][1];if(r&&i.test(s))return r}return e.jd},has(s,e=!1){return e?s in this.j:!!this.go(s)},ta(s,e,t,n){for(let i=0;i<s.length;i++)this.tt(s[i],e,t,n)},tr(s,e,t,n){n=n||mr.groups;let i;return e&&e.j?i=e:(i=new mr(e),t&&n&&$h(e,t,n)),this.jr.push([s,i]),i},ts(s,e,t,n){let i=this;const r=s.length;if(!r)return i;for(let o=0;o<r-1;o++)i=i.tt(s[o]);return i.tt(s[r-1],e,t,n)},tt(s,e,t,n){n=n||mr.groups;const i=this;if(e&&e.j)return i.j[s]=e,e;const r=e;let o,a=i.go(s);if(a?(o=new mr,Object.assign(o.j,a.j),o.jr.push.apply(o.jr,a.jr),o.jd=a.jd,o.t=a.t):o=new mr,r){if(n)if(o.t&&typeof o.t=="string"){const c=Object.assign(lQ(o.t,n),t);$h(r,c,n)}else t&&$h(r,t,n);o.t=r}return i.j[s]=o,o}};const Ht=(s,e,t,n,i)=>s.ta(e,t,n,i),Ys=(s,e,t,n,i)=>s.tr(e,t,n,i),_I=(s,e,t,n,i)=>s.ts(e,t,n,i),Pe=(s,e,t,n,i)=>s.tt(e,t,n,i),Cl="WORD",iT="UWORD",QO="ASCIINUMERICAL",XO="ALPHANUMERICAL",ny="LOCALHOST",rT="TLD",oT="UTLD",_S="SCHEME",cp="SLASH_SCHEME",qE="NUM",aT="WS",KE="NL",Pv="OPENBRACE",Ov="CLOSEBRACE",Pw="OPENBRACKET",Ow="CLOSEBRACKET",Dw="OPENPAREN",Nw="CLOSEPAREN",Bw="OPENANGLEBRACKET",Fw="CLOSEANGLEBRACKET",$w="FULLWIDTHLEFTPAREN",Hw="FULLWIDTHRIGHTPAREN",Uw="LEFTCORNERBRACKET",Ww="RIGHTCORNERBRACKET",zw="LEFTWHITECORNERBRACKET",jw="RIGHTWHITECORNERBRACKET",Vw="FULLWIDTHLESSTHAN",Gw="FULLWIDTHGREATERTHAN",qw="AMPERSAND",Kw="APOSTROPHE",Qw="ASTERISK",Xc="AT",Xw="BACKSLASH",Yw="BACKTICK",Jw="CARET",Hh="COLON",QE="COMMA",Zw="DOLLAR",Ea="DOT",e0="EQUALS",XE="EXCLAMATION",fo="HYPHEN",Dv="PERCENT",t0="PIPE",s0="PLUS",n0="POUND",Nv="QUERY",YE="QUOTE",YO="FULLWIDTHMIDDLEDOT",JE="SEMI",Ma="SLASH",Bv="TILDE",i0="UNDERSCORE",JO="EMOJI",r0="SYM";var ZO=Object.freeze({__proto__:null,ALPHANUMERICAL:XO,AMPERSAND:qw,APOSTROPHE:Kw,ASCIINUMERICAL:QO,ASTERISK:Qw,AT:Xc,BACKSLASH:Xw,BACKTICK:Yw,CARET:Jw,CLOSEANGLEBRACKET:Fw,CLOSEBRACE:Ov,CLOSEBRACKET:Ow,CLOSEPAREN:Nw,COLON:Hh,COMMA:QE,DOLLAR:Zw,DOT:Ea,EMOJI:JO,EQUALS:e0,EXCLAMATION:XE,FULLWIDTHGREATERTHAN:Gw,FULLWIDTHLEFTPAREN:$w,FULLWIDTHLESSTHAN:Vw,FULLWIDTHMIDDLEDOT:YO,FULLWIDTHRIGHTPAREN:Hw,HYPHEN:fo,LEFTCORNERBRACKET:Uw,LEFTWHITECORNERBRACKET:zw,LOCALHOST:ny,NL:KE,NUM:qE,OPENANGLEBRACKET:Bw,OPENBRACE:Pv,OPENBRACKET:Pw,OPENPAREN:Dw,PERCENT:Dv,PIPE:t0,PLUS:s0,POUND:n0,QUERY:Nv,QUOTE:YE,RIGHTCORNERBRACKET:Ww,RIGHTWHITECORNERBRACKET:jw,SCHEME:_S,SEMI:JE,SLASH:Ma,SLASH_SCHEME:cp,SYM:r0,TILDE:Bv,TLD:rT,UNDERSCORE:i0,UTLD:oT,UWORD:iT,WORD:Cl,WS:aT});const _l=/[a-z]/,wm=new RegExp("\\p{L}","u"),MC=new RegExp("\\p{Emoji}","u"),Sl=/\d/,xC=/\s/,SI="\r",IC=`
`,cQ="",uQ="",RC="";let N_=null,B_=null;function hQ(s=[]){const e={};mr.groups=e;const t=new mr;N_==null&&(N_=wI(nQ)),B_==null&&(B_=wI(iQ)),Pe(t,"'",Kw),Pe(t,"{",Pv),Pe(t,"}",Ov),Pe(t,"[",Pw),Pe(t,"]",Ow),Pe(t,"(",Dw),Pe(t,")",Nw),Pe(t,"<",Bw),Pe(t,">",Fw),Pe(t,"",$w),Pe(t,"",Hw),Pe(t,"「",Uw),Pe(t,"」",Ww),Pe(t,"『",zw),Pe(t,"』",jw),Pe(t,"",Vw),Pe(t,"",Gw),Pe(t,"&",qw),Pe(t,"*",Qw),Pe(t,"@",Xc),Pe(t,"`",Yw),Pe(t,"^",Jw),Pe(t,":",Hh),Pe(t,",",QE),Pe(t,"$",Zw),Pe(t,".",Ea),Pe(t,"=",e0),Pe(t,"!",XE),Pe(t,"-",fo),Pe(t,"%",Dv),Pe(t,"|",t0),Pe(t,"+",s0),Pe(t,"#",n0),Pe(t,"?",Nv),Pe(t,'"',YE),Pe(t,"/",Ma),Pe(t,";",JE),Pe(t,"~",Bv),Pe(t,"_",i0),Pe(t,"\\",Xw),Pe(t,"・",YO);const n=Ys(t,Sl,qE,{[eT]:!0});Ys(n,Sl,n);const i=Ys(n,_l,QO,{[Lv]:!0}),r=Ys(n,wm,XO,{[qm]:!0}),o=Ys(t,_l,Cl,{[tT]:!0});Ys(o,Sl,i),Ys(o,_l,o),Ys(i,Sl,i),Ys(i,_l,i);const a=Ys(t,wm,iT,{[sT]:!0});Ys(a,_l),Ys(a,Sl,r),Ys(a,wm,a),Ys(r,Sl,r),Ys(r,_l),Ys(r,wm,r);const c=Pe(t,IC,KE,{[EC]:!0}),l=Pe(t,SI,aT,{[EC]:!0}),u=Ys(t,xC,aT,{[EC]:!0});Pe(t,RC,u),Pe(l,IC,c),Pe(l,RC,u),Ys(l,xC,u),Pe(u,SI),Pe(u,IC),Ys(u,xC,u),Pe(u,RC,u);const h=Ys(t,MC,JO,{[KO]:!0});Pe(h,"#"),Ys(h,MC,h),Pe(h,cQ,h);const d=Pe(h,uQ);Pe(d,"#"),Ys(d,MC,h);const p=[[_l,o],[Sl,i]],m=[[_l,null],[wm,a],[Sl,r]];for(let v=0;v<N_.length;v++)Uc(t,N_[v],rT,Cl,p);for(let v=0;v<B_.length;v++)Uc(t,B_[v],oT,iT,m);$h(rT,{tld:!0,ascii:!0},e),$h(oT,{utld:!0,alpha:!0},e),Uc(t,"file",_S,Cl,p),Uc(t,"mailto",_S,Cl,p),Uc(t,"http",cp,Cl,p),Uc(t,"https",cp,Cl,p),Uc(t,"ftp",cp,Cl,p),Uc(t,"ftps",cp,Cl,p),$h(_S,{scheme:!0,ascii:!0},e),$h(cp,{slashscheme:!0,ascii:!0},e),s=s.sort((v,g)=>v[0]>g[0]?1:-1);for(let v=0;v<s.length;v++){const g=s[v][0],b=s[v][1]?{[rQ]:!0}:{[oQ]:!0};g.indexOf("-")>=0?b[nT]=!0:_l.test(g)?Sl.test(g)?b[Lv]=!0:b[tT]=!0:b[eT]=!0,_I(t,g,g,b)}return _I(t,"localhost",ny,{ascii:!0}),t.jd=new mr(r0),{start:t,tokens:Object.assign({groups:e},ZO)}}function eD(s,e){const t=dQ(e.replace(/[A-Z]/g,a=>a.toLowerCase())),n=t.length,i=[];let r=0,o=0;for(;o<n;){let a=s,c=null,l=0,u=null,h=-1,d=-1;for(;o<n&&(c=a.go(t[o]));)a=c,a.accepts()?(h=0,d=0,u=a):h>=0&&(h+=t[o].length,d++),l+=t[o].length,r+=t[o].length,o++;r-=h,o-=d,l-=h,i.push({t:u.t,v:e.slice(r-l,r),s:r-l,e:r})}return i}function dQ(s){const e=[],t=s.length;let n=0;for(;n<t;){let i=s.charCodeAt(n),r,o=i<55296||i>56319||n+1===t||(r=s.charCodeAt(n+1))<56320||r>57343?s[n]:s.slice(n,n+2);e.push(o),n+=o.length}return e}function Uc(s,e,t,n,i){let r;const o=e.length;for(let a=0;a<o-1;a++){const c=e[a];s.j[c]?r=s.j[c]:(r=new mr(n),r.jr=i.slice(),s.j[c]=r),s=r}return r=new mr(t),r.jr=i.slice(),s.j[e[o-1]]=r,r}function wI(s){const e=[],t=[];let n=0,i="0123456789";for(;n<s.length;){let r=0;for(;i.indexOf(s[n+r])>=0;)r++;if(r>0){e.push(t.join(""));for(let o=parseInt(s.substring(n,n+r),10);o>0;o--)t.pop();n+=r}else t.push(s[n]),n++}return e}const iy={defaultProtocol:"http",events:null,format:kI,formatHref:kI,nl2br:!1,tagName:"a",target:null,rel:null,validate:!0,truncate:1/0,className:null,attributes:null,ignoreTags:[],render:null};function ZE(s,e=null){let t=Object.assign({},iy);s&&(t=Object.assign(t,s instanceof ZE?s.o:s));const n=t.ignoreTags,i=[];for(let r=0;r<n.length;r++)i.push(n[r].toUpperCase());this.o=t,e&&(this.defaultRender=e),this.ignoreTags=i}ZE.prototype={o:iy,ignoreTags:[],defaultRender(s){return s},check(s){return this.get("validate",s.toString(),s)},get(s,e,t){const n=e!=null;let i=this.o[s];return i&&(typeof i=="object"?(i=t.t in i?i[t.t]:iy[s],typeof i=="function"&&n&&(i=i(e,t))):typeof i=="function"&&n&&(i=i(e,t.t,t)),i)},getObj(s,e,t){let n=this.o[s];return typeof n=="function"&&e!=null&&(n=n(e,t.t,t)),n},render(s){const e=s.render(this);return(this.get("render",null,s)||this.defaultRender)(e,s.t,s)}};function kI(s){return s}function tD(s,e){this.t="token",this.v=s,this.tk=e}tD.prototype={isLink:!1,toString(){return this.v},toHref(s){return this.toString()},toFormattedString(s){const e=this.toString(),t=s.get("truncate",e,this),n=s.get("format",e,this);return t&&n.length>t?n.substring(0,t)+"…":n},toFormattedHref(s){return s.get("formatHref",this.toHref(s.get("defaultProtocol")),this)},startIndex(){return this.tk[0].s},endIndex(){return this.tk[this.tk.length-1].e},toObject(s=iy.defaultProtocol){return{type:this.t,value:this.toString(),isLink:this.isLink,href:this.toHref(s),start:this.startIndex(),end:this.endIndex()}},toFormattedObject(s){return{type:this.t,value:this.toFormattedString(s),isLink:this.isLink,href:this.toFormattedHref(s),start:this.startIndex(),end:this.endIndex()}},validate(s){return s.get("validate",this.toString(),this)},render(s){const e=this,t=this.toHref(s.get("defaultProtocol")),n=s.get("formatHref",t,this),i=s.get("tagName",t,e),r=this.toFormattedString(s),o={},a=s.get("className",t,e),c=s.get("target",t,e),l=s.get("rel",t,e),u=s.getObj("attributes",t,e),h=s.getObj("events",t,e);return o.href=n,a&&(o.class=a),c&&(o.target=c),l&&(o.rel=l),u&&Object.assign(o,u),{tagName:i,attributes:o,content:r,eventListeners:h}}};function lk(s,e){class t extends tD{constructor(i,r){super(i,r),this.t=s}}for(const n in e)t.prototype[n]=e[n];return t.t=s,t}const fQ=lk("email",{isLink:!0,toHref(){return"mailto:"+this.toString()}}),CI=lk("text"),pQ=lk("nl"),F_=lk("url",{isLink:!0,toHref(s=iy.defaultProtocol){return this.hasProtocol()?this.v:`${s}://${this.v}`},hasProtocol(){const s=this.tk;return s.length>=2&&s[0].t!==ny&&s[1].t===Hh}}),ao=s=>new mr(s);function gQ({groups:s}){const e=s.domain.concat([qw,Qw,Xc,Xw,Yw,Jw,Zw,e0,fo,qE,Dv,t0,s0,n0,Ma,r0,Bv,i0]),t=[Kw,Hh,QE,Ea,XE,Dv,Nv,YE,JE,Bw,Fw,Pv,Ov,Ow,Pw,Dw,Nw,$w,Hw,Uw,Ww,zw,jw,Vw,Gw],n=[qw,Kw,Qw,Xw,Yw,Jw,Zw,e0,fo,Pv,Ov,Dv,t0,s0,n0,Nv,Ma,r0,Bv,i0],i=ao(),r=Pe(i,Bv);Ht(r,n,r),Ht(r,s.domain,r);const o=ao(),a=ao(),c=ao();Ht(i,s.domain,o),Ht(i,s.scheme,a),Ht(i,s.slashscheme,c),Ht(o,n,r),Ht(o,s.domain,o);const l=Pe(o,Xc);Pe(r,Xc,l),Pe(a,Xc,l),Pe(c,Xc,l);const u=Pe(r,Ea);Ht(u,n,r),Ht(u,s.domain,r);const h=ao();Ht(l,s.domain,h),Ht(h,s.domain,h);const d=Pe(h,Ea);Ht(d,s.domain,h);const p=ao(fQ);Ht(d,s.tld,p),Ht(d,s.utld,p),Pe(l,ny,p);const m=Pe(h,fo);Pe(m,fo,m),Ht(m,s.domain,h),Ht(p,s.domain,h),Pe(p,Ea,d),Pe(p,fo,m);const v=Pe(o,fo),g=Pe(o,Ea);Pe(v,fo,v),Ht(v,s.domain,o),Ht(g,n,r),Ht(g,s.domain,o);const y=ao(F_);Ht(g,s.tld,y),Ht(g,s.utld,y),Ht(y,s.domain,o),Ht(y,n,r),Pe(y,Ea,g),Pe(y,fo,v),Pe(y,Xc,l);const b=Pe(y,Hh),_=ao(F_);Ht(b,s.numeric,_);const w=ao(F_),S=ao();Ht(w,e,w),Ht(w,t,S),Ht(S,e,w),Ht(S,t,S),Pe(y,Ma,w),Pe(_,Ma,w);const C=Pe(a,Hh),T=Pe(c,Hh),k=Pe(T,Ma),A=Pe(k,Ma);Ht(a,s.domain,o),Pe(a,Ea,g),Pe(a,fo,v),Ht(c,s.domain,o),Pe(c,Ea,g),Pe(c,fo,v),Ht(C,s.domain,w),Pe(C,Ma,w),Pe(C,Nv,w),Ht(A,s.domain,w),Ht(A,e,w),Pe(A,Ma,w);const M=[[Pv,Ov],[Pw,Ow],[Dw,Nw],[Bw,Fw],[$w,Hw],[Uw,Ww],[zw,jw],[Vw,Gw]];for(let R=0;R<M.length;R++){const[P,L]=M[R],z=Pe(w,P);Pe(S,P,z);const Q=ao(F_);Ht(z,e,Q);const W=ao();Ht(z,t,W),Pe(z,L,w),Ht(Q,e,Q),Ht(Q,t,W),Ht(W,e,Q),Ht(W,t,W),Pe(Q,L,w),Pe(W,L,w)}return Pe(i,ny,y),Pe(i,KE,pQ),{start:i,tokens:ZO}}function mQ(s,e,t){let n=t.length,i=0,r=[],o=[];for(;i<n;){let a=s,c=null,l=null,u=0,h=null,d=-1;for(;i<n&&!(c=a.go(t[i].t));)o.push(t[i++]);for(;i<n&&(l=c||a.go(t[i].t));)c=null,a=l,a.accepts()?(d=0,h=a):d>=0&&d++,i++,u++;if(d<0)i-=u,i<n&&(o.push(t[i]),i++);else{o.length>0&&(r.push(LC(CI,e,o)),o=[]),i-=d,u-=d;const p=h.t,m=t.slice(i-u,i);r.push(LC(p,e,m))}}return o.length>0&&r.push(LC(CI,e,o)),r}function LC(s,e,t){const n=t[0].s,i=t[t.length-1].e,r=e.slice(n,i);return new s(r,t)}const vQ=typeof console<"u"&&console&&console.warn||(()=>{}),yQ="until manual call of linkify.init(). Register all schemes and plugins before invoking linkify the first time.",Ls={scanner:null,parser:null,tokenQueue:[],pluginQueue:[],customSchemes:[],initialized:!1};function bQ(){return mr.groups={},Ls.scanner=null,Ls.parser=null,Ls.tokenQueue=[],Ls.pluginQueue=[],Ls.customSchemes=[],Ls.initialized=!1,Ls}function TI(s,e=!1){if(Ls.initialized&&vQ(`linkifyjs: already initialized - will not register custom scheme "${s}" ${yQ}`),!/^[0-9a-z]+(-[0-9a-z]+)*$/.test(s))throw new Error(`linkifyjs: incorrect scheme format.
1. Must only contain digits, lowercase ASCII letters or "-"
2. Cannot start or end with "-"
3. "-" cannot repeat`);Ls.customSchemes.push([s,e])}function _Q(){Ls.scanner=hQ(Ls.customSchemes);for(let s=0;s<Ls.tokenQueue.length;s++)Ls.tokenQueue[s][1]({scanner:Ls.scanner});Ls.parser=gQ(Ls.scanner.tokens);for(let s=0;s<Ls.pluginQueue.length;s++)Ls.pluginQueue[s][1]({scanner:Ls.scanner,parser:Ls.parser});return Ls.initialized=!0,Ls}function eM(s){return Ls.initialized||_Q(),mQ(Ls.parser.start,s,eD(Ls.scanner.start,s))}eM.scan=eD;function sD(s,e=null,t=null){if(e&&typeof e=="object"){if(t)throw Error(`linkifyjs: Invalid link type ${e}; must be a string`);t=e,e=null}const n=new ZE(t),i=eM(s),r=[];for(let o=0;o<i.length;o++){const a=i[o];a.isLink&&(!e||a.t===e)&&n.check(a)&&r.push(a.toFormattedObject(n))}return r}var tM="[\0-   -\u2029 ]",SQ=new RegExp(tM),wQ=new RegExp(`${tM}$`),kQ=new RegExp(tM,"g");function CQ(s){return s.length===1?s[0].isLink:s.length===3&&s[1].isLink?["()","[]"].includes(s[0].value+s[2].value):!1}function TQ(s){return new $s({key:new fn("autolink"),appendTransaction:(e,t,n)=>{const i=e.some(l=>l.docChanged)&&!t.doc.eq(n.doc),r=e.some(l=>l.getMeta("preventAutolink"));if(!i||r)return;const{tr:o}=n,a=nO(t.doc,[...e]);if(uO(a).forEach(({newRange:l})=>{const u=pq(n.doc,l,p=>p.isTextblock);let h,d;if(u.length>1)h=u[0],d=n.doc.textBetween(h.pos,h.pos+h.node.nodeSize,void 0," ");else if(u.length){const p=n.doc.textBetween(l.from,l.to," "," ");if(!wQ.test(p))return;h=u[0],d=n.doc.textBetween(h.pos,l.to,void 0," ")}if(h&&d){const p=d.split(SQ).filter(Boolean);if(p.length<=0)return!1;const m=p[p.length-1],v=h.pos+d.lastIndexOf(m);if(!m)return!1;const g=eM(m).map(y=>y.toObject(s.defaultProtocol));if(!CQ(g))return!1;g.filter(y=>y.isLink).map(y=>({...y,from:v+y.start+1,to:v+y.end+1})).filter(y=>n.schema.marks.code?!n.doc.rangeHasMark(y.from,y.to,n.schema.marks.code):!0).filter(y=>s.validate(y.value)).filter(y=>s.shouldAutoLink(y.value)).forEach(y=>{HE(y.from,y.to,n.doc).some(b=>b.mark.type===s.type)||o.addMark(y.from,y.to,s.type.create({href:y.href}))})}}),!!o.steps.length)return o}})}function AQ(s){return new $s({key:new fn("handleClickLink"),props:{handleClick:(e,t,n)=>{var i,r;if(n.button!==0||!e.editable)return!1;let o=null;if(n.target instanceof HTMLAnchorElement)o=n.target;else{const c=n.target;if(!c)return!1;const l=s.editor.view.dom;o=c.closest("a"),o&&!l.contains(o)&&(o=null)}if(!o)return!1;let a=!1;if(s.enableClickSelection&&(a=s.editor.commands.extendMarkRange(s.type.name)),s.openOnClick){const c=cO(e.state,s.type.name),l=(i=o.href)!=null?i:c.href,u=(r=o.target)!=null?r:c.target;l&&(window.open(l,u),a=!0)}return a}}})}function EQ(s){return new $s({key:new fn("handlePasteLink"),props:{handlePaste:(e,t,n)=>{const{shouldAutoLink:i}=s,{state:r}=e,{selection:o}=r,{empty:a}=o;if(a)return!1;let c="";n.content.forEach(u=>{c+=u.textContent});const l=sD(c,{defaultProtocol:s.defaultProtocol}).find(u=>u.isLink&&u.value===c);return!c||!l||i!==void 0&&!i(l.value)?!1:s.editor.commands.setMark(s.type,{href:l.href})}}})}function Sh(s,e){const t=["http","https","ftp","ftps","mailto","tel","callto","sms","cid","xmpp"];return e&&e.forEach(n=>{const i=typeof n=="string"?n:n.scheme;i&&t.push(i)}),!s||s.replace(kQ,"").match(new RegExp(`^(?:(?:${t.join("|")}):|[^a-z]|[a-z0-9+.-]+(?:[^a-z+.-:]|$))`,"i"))}var MQ=Df.create({name:"link",priority:1e3,keepOnSplit:!1,exitable:!0,onCreate(){this.options.validate&&!this.options.shouldAutoLink&&(this.options.shouldAutoLink=this.options.validate,console.warn("The `validate` option is deprecated. Rename to the `shouldAutoLink` option instead.")),this.options.protocols.forEach(s=>{if(typeof s=="string"){TI(s);return}TI(s.scheme,s.optionalSlashes)})},onDestroy(){bQ()},inclusive(){return this.options.autolink},addOptions(){return{openOnClick:!0,enableClickSelection:!1,linkOnPaste:!0,autolink:!0,protocols:[],defaultProtocol:"http",HTMLAttributes:{target:"_blank",rel:"noopener noreferrer nofollow",class:null},isAllowedUri:(s,e)=>!!Sh(s,e.protocols),validate:s=>!!s,shouldAutoLink:s=>{const e=/^[a-z][a-z0-9+.-]*:\/\//i.test(s),t=/^[a-z][a-z0-9+.-]*:/i.test(s);if(e||t&&!s.includes("@"))return!0;const i=(s.includes("@")?s.split("@").pop():s).split(/[/?#:]/)[0];return!(/^\d{1,3}(\.\d{1,3}){3}$/.test(i)||!/\./.test(i))}}},addAttributes(){return{href:{default:null,parseHTML(s){return s.getAttribute("href")}},target:{default:this.options.HTMLAttributes.target},rel:{default:this.options.HTMLAttributes.rel},class:{default:this.options.HTMLAttributes.class},title:{default:null}}},parseHTML(){return[{tag:"a[href]",getAttrs:s=>{const e=s.getAttribute("href");return!e||!this.options.isAllowedUri(e,{defaultValidate:t=>!!Sh(t,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?!1:null}}]},renderHTML({HTMLAttributes:s}){return this.options.isAllowedUri(s.href,{defaultValidate:e=>!!Sh(e,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?["a",Fs(this.options.HTMLAttributes,s),0]:["a",Fs(this.options.HTMLAttributes,{...s,href:""}),0]},markdownTokenName:"link",parseMarkdown:(s,e)=>e.applyMark("link",e.parseInline(s.tokens||[]),{href:s.href,title:s.title||null}),renderMarkdown:(s,e)=>{var t,n,i,r;const o=(n=(t=s.attrs)==null?void 0:t.href)!=null?n:"",a=(r=(i=s.attrs)==null?void 0:i.title)!=null?r:"",c=e.renderChildren(s);return a?`[${c}](${o} "${a}")`:`[${c}](${o})`},addCommands(){return{setLink:s=>({chain:e})=>{const{href:t}=s;return this.options.isAllowedUri(t,{defaultValidate:n=>!!Sh(n,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?e().setMark(this.name,s).setMeta("preventAutolink",!0).run():!1},toggleLink:s=>({chain:e})=>{const{href:t}=s||{};return t&&!this.options.isAllowedUri(t,{defaultValidate:n=>!!Sh(n,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?!1:e().toggleMark(this.name,s,{extendEmptyMarkRange:!0}).setMeta("preventAutolink",!0).run()},unsetLink:()=>({chain:s})=>s().unsetMark(this.name,{extendEmptyMarkRange:!0}).setMeta("preventAutolink",!0).run()}},addPasteRules(){return[xf({find:s=>{const e=[];if(s){const{protocols:t,defaultProtocol:n}=this.options,i=sD(s).filter(r=>r.isLink&&this.options.isAllowedUri(r.value,{defaultValidate:o=>!!Sh(o,t),protocols:t,defaultProtocol:n}));i.length&&i.forEach(r=>{this.options.shouldAutoLink(r.value)&&e.push({text:r.value,data:{href:r.href},index:r.start})})}return e},type:this.type,getAttributes:s=>{var e;return{href:(e=s.data)==null?void 0:e.href}}})]},addProseMirrorPlugins(){const s=[],{protocols:e,defaultProtocol:t}=this.options;return this.options.autolink&&s.push(TQ({type:this.type,defaultProtocol:this.options.defaultProtocol,validate:n=>this.options.isAllowedUri(n,{defaultValidate:i=>!!Sh(i,e),protocols:e,defaultProtocol:t}),shouldAutoLink:this.options.shouldAutoLink})),s.push(AQ({type:this.type,editor:this.editor,openOnClick:this.options.openOnClick==="whenNotEditable"?!0:this.options.openOnClick,enableClickSelection:this.options.enableClickSelection})),this.options.linkOnPaste&&s.push(EQ({editor:this.editor,defaultProtocol:this.options.defaultProtocol,type:this.type,shouldAutoLink:this.options.shouldAutoLink})),s}}),xQ=Object.defineProperty,IQ=(s,e)=>{for(var t in e)xQ(s,t,{get:e[t],enumerable:!0})},RQ="listItem",AI="textStyle",EI=/^\s*([-+*])\s$/,nD=Sr.create({name:"bulletList",addOptions(){return{itemTypeName:"listItem",HTMLAttributes:{},keepMarks:!1,keepAttributes:!1}},group:"block list",content(){return`${this.options.itemTypeName}+`},parseHTML(){return[{tag:"ul"}]},renderHTML({HTMLAttributes:s}){return["ul",Fs(this.options.HTMLAttributes,s),0]},markdownTokenName:"list",parseMarkdown:(s,e)=>s.type!=="list"||s.ordered?[]:{type:"bulletList",content:s.items?e.parseChildren(s.items):[]},renderMarkdown:(s,e)=>s.content?e.renderChildren(s.content,`
`):"",markdownOptions:{indentsContent:!0},addCommands(){return{toggleBulletList:()=>({commands:s,chain:e})=>this.options.keepAttributes?e().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes(RQ,this.editor.getAttributes(AI)).run():s.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-8":()=>this.editor.commands.toggleBulletList()}},addInputRules(){let s=im({find:EI,type:this.type});return(this.options.keepMarks||this.options.keepAttributes)&&(s=im({find:EI,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:()=>this.editor.getAttributes(AI),editor:this.editor})),[s]}}),LQ=(s,e,t)=>{const{selection:n}=s;if(!n.empty)return null;const{$from:i}=n;if(!i.parent.isTextblock||i.parentOffset!==i.parent.content.size)return null;let r=-1;for(let p=i.depth;p>0;p-=1)if(i.node(p).type.name===e){r=p;break}if(r<0)return null;const o=i.node(r),a=i.index(r);if(a+1>=o.childCount)return null;const c=o.child(a+1);if(!t.includes(c.type.name))return null;const l=s.schema.nodes[e];let u=!1;if(c.forEach(p=>{p.type===l&&p.childCount>1&&(u=!0)}),!u)return null;const h=s.doc.resolve(i.after()).nodeAfter;if(!h||!t.includes(h.type.name))return null;const d=[];return h.forEach(p=>{d.push(p)}),d.length===0?null:{listItemDepth:r,nestedList:h,nestedListPos:i.after(),insertPos:i.after(r),items:d}},PQ=(s,e,t,n)=>{const i=LQ(s,t,n);if(!i)return!1;const{selection:r}=s,{nestedList:o,nestedListPos:a,insertPos:c,items:l}=i,u=s.tr;u.delete(a,a+o.nodeSize);const h=u.mapping.map(c);return u.insert(h,Fe.from(l)),u.setSelection(r.map(u.doc,u.mapping)),e&&e(u),!0},OQ=(s,e,t)=>PQ(s.state,s.view.dispatch,e,t),iD=(s,e)=>on.create({name:`${s}BranchingDeleteKeymap`,priority:101,addKeyboardShortcuts(){const t=()=>OQ(this.editor,s,e);return{Delete:t,"Mod-Delete":t}}});function DQ(s){var e,t;const n=(e=s.tokens)==null?void 0:e[0];return!!(s.text&&((t=s.tokens)==null?void 0:t.length)===1&&(n==null?void 0:n.type)==="list"&&n.ordered&&n.raw===s.text)}function NQ(s,e){return e.tokenizeInline?e.parseInline(e.tokenizeInline(s)):e.parseInline([{type:"text",raw:s,text:s}])}var rD=Sr.create({name:"listItem",addOptions(){return{HTMLAttributes:{},bulletListTypeName:"bulletList",orderedListTypeName:"orderedList"}},content:"paragraph block*",defining:!0,parseHTML(){return[{tag:"li"}]},renderHTML({HTMLAttributes:s}){return["li",Fs(this.options.HTMLAttributes,s),0]},markdownTokenName:"list_item",parseMarkdown:(s,e)=>{var t;if(s.type!=="list_item")return[];const n=(t=e.parseBlockChildren)!=null?t:e.parseChildren;let i=[];if(s.tokens&&s.tokens.length>0){if(DQ(s))return{type:"listItem",content:[{type:"paragraph",content:NQ(s.text||"",e)}]};if(s.tokens.some(o=>o.type==="paragraph"))i=n(s.tokens);else{const o=s.tokens[0];if(o&&o.type==="text"&&o.tokens&&o.tokens.length>0){if(i=[{type:"paragraph",content:e.parseInline(o.tokens)}],s.tokens.length>1){const c=s.tokens.slice(1),l=n(c);i.push(...l)}}else i=n(s.tokens)}}return i.length===0&&(i=[{type:"paragraph",content:[]}]),{type:"listItem",content:i}},renderMarkdown:(s,e,t)=>jE(s,e,n=>{var i,r;return n.parentType==="bulletList"?"- ":n.parentType==="orderedList"?`${(((r=(i=n.meta)==null?void 0:i.parentAttrs)==null?void 0:r.start)||1)+n.index}. `:"- "},t),addExtensions(){return[iD(this.name,[this.options.bulletListTypeName,this.options.orderedListTypeName])]},addKeyboardShortcuts(){return{Enter:()=>this.editor.commands.splitListItem(this.name),Tab:()=>this.editor.commands.sinkListItem(this.name),"Shift-Tab":()=>this.editor.commands.liftListItem(this.name)}}}),BQ={};IQ(BQ,{findListItemPos:()=>ck,getNextListDepth:()=>sM,handleBackspace:()=>lT,handleDelete:()=>cT,hasListBefore:()=>oD,hasListItemAfter:()=>FQ,hasListItemBefore:()=>$Q,listItemHasSubList:()=>HQ,nextListIsDeeper:()=>aD,nextListIsHigher:()=>lD});var ck=(s,e)=>{const{$from:t}=e.selection,n=wn(s,e.schema);let i=null,r=t.depth,o=t.pos,a=null;for(;r>0&&a===null;)i=t.node(r),i.type===n?a=r:(r-=1,o-=1);return a===null?null:{$pos:e.doc.resolve(o),depth:a}},sM=(s,e)=>{const t=ck(s,e);if(!t)return!1;const[,n]=Tq(e,s,t.$pos.pos+4);return n},oD=(s,e,t)=>{const{$anchor:n}=s.selection,i=Math.max(0,n.pos-2),r=s.doc.resolve(i).node();return!(!r||!t.includes(r.type.name))},lT=(s,e,t)=>{if(s.commands.undoInputRule())return!0;if(s.state.selection.from!==s.state.selection.to)return!1;if(!lh(s.state,e)&&oD(s.state,e,t)){const{$anchor:n}=s.state.selection,i=s.state.doc.resolve(n.before()-1),r=[];i.node().descendants((c,l)=>{c.type.name===e&&r.push({node:c,pos:l})});const o=r.at(-1);if(!o)return!1;const a=s.state.doc.resolve(i.start()+o.pos+1);return s.chain().cut({from:n.start()-1,to:n.end()+1},a.end()).joinForward().run()}return!lh(s.state,e)||!xq(s.state)?!1:s.chain().liftListItem(e).run()},aD=(s,e)=>{const t=sM(s,e),n=ck(s,e);return!n||!t?!1:t>n.depth},lD=(s,e)=>{const t=sM(s,e),n=ck(s,e);return!n||!t?!1:t<n.depth},cT=(s,e)=>{if(!lh(s.state,e)||!Mq(s.state,e))return!1;const{selection:t}=s.state,{$from:n,$to:i}=t;return!t.empty&&n.sameParent(i)?!1:aD(e,s.state)?s.chain().focus(s.state.selection.from+4).lift(e).joinBackward().run():lD(e,s.state)?s.chain().joinForward().joinBackward().run():s.commands.joinItemForward()},FQ=(s,e)=>{var t;const{$anchor:n}=e.selection,i=e.doc.resolve(n.pos-n.parentOffset-2);return!(i.index()===i.parent.childCount-1||((t=i.nodeAfter)==null?void 0:t.type.name)!==s)},$Q=(s,e)=>{var t;const{$anchor:n}=e.selection,i=e.doc.resolve(n.pos-2);return!(i.index()===0||((t=i.nodeBefore)==null?void 0:t.type.name)!==s)},HQ=(s,e,t)=>{if(!t)return!1;const n=wn(s,e.schema);let i=!1;return t.descendants(r=>{r.type===n&&(i=!0)}),i},cD=on.create({name:"listKeymap",addOptions(){return{listTypes:[{itemName:"listItem",wrapperNames:["bulletList","orderedList"]},{itemName:"taskItem",wrapperNames:["taskList"]}]}},addKeyboardShortcuts(){return{Delete:({editor:s})=>{let e=!1;return this.options.listTypes.forEach(({itemName:t})=>{s.state.schema.nodes[t]!==void 0&&cT(s,t)&&(e=!0)}),e},"Mod-Delete":({editor:s})=>{let e=!1;return this.options.listTypes.forEach(({itemName:t})=>{s.state.schema.nodes[t]!==void 0&&cT(s,t)&&(e=!0)}),e},Backspace:({editor:s})=>{let e=!1;return this.options.listTypes.forEach(({itemName:t,wrapperNames:n})=>{s.state.schema.nodes[t]!==void 0&&lT(s,t,n)&&(e=!0)}),e},"Mod-Backspace":({editor:s})=>{let e=!1;return this.options.listTypes.forEach(({itemName:t,wrapperNames:n})=>{s.state.schema.nodes[t]!==void 0&&lT(s,t,n)&&(e=!0)}),e}}}}),MI=/^(\s*)(\d+)\.\s+(.*)$/,UQ=/^\s/;function WQ(s){const e=s.trimStart();return/^[-+*]\s+/.test(e)||/^\d+\.\s+/.test(e)||/^>\s?/.test(e)||/^```/.test(e)||/^~~~/.test(e)}function zQ(s){const e=[],t=[];let n=!1;return s.forEach(i=>{if(n){t.push(i);return}if(i.trim()===""){n=!0,t.push(i);return}if(e.length>0&&WQ(i)){n=!0,t.push(i);return}e.push(i)}),{paragraphLines:e,blockLines:t}}function jQ(s){const e=[];let t=0,n=0;for(;t<s.length;){const i=s[t],r=i.match(MI);if(!r)break;const[,o,a,c]=r,l=o.length,u=[c];let h=t+1;const d=[i];let p=!1;for(;h<s.length;){const m=s[h];if(m.match(MI))break;if(m.trim()==="")d.push(m),u.push(""),p=!0,h+=1;else if(m.match(UQ))d.push(m),u.push(m.slice(l+2)),h+=1;else{if(p)break;d.push(m),u.push(m),h+=1}}e.push({indent:l,number:parseInt(a,10),content:u.join(`
`).trim(),contentLines:u,raw:d.join(`
`)}),n=h,t=h}return[e,n]}function uD(s,e,t){const n=[];let i=0;for(;i<s.length;){const r=s[i];if(r.indent===e){const{paragraphLines:o,blockLines:a}=zQ(r.contentLines),c=o.join(`
`).trim(),l=[];c&&l.push({type:"paragraph",raw:c,tokens:t.inlineTokens(c)});const u=a.join(`
`).trim();if(u){const p=t.blockTokens(u);l.push(...p)}let h=i+1;const d=[];for(;h<s.length&&s[h].indent>e;)d.push(s[h]),h+=1;if(d.length>0){const p=Math.min(...d.map(v=>v.indent)),m=uD(d,p,t);l.push({type:"list",ordered:!0,start:d[0].number,items:m,raw:d.map(v=>v.raw).join(`
`)})}n.push({type:"list_item",raw:r.raw,tokens:l}),i=h}else i+=1}return n}function VQ(s,e){return s.map(t=>{if(t.type!=="list_item")return e.parseChildren([t])[0];const n=[];return t.tokens&&t.tokens.length>0&&t.tokens.forEach(i=>{if(i.type==="paragraph"||i.type==="list"||i.type==="blockquote"||i.type==="code")n.push(...e.parseChildren([i]));else if(i.type==="text"&&i.tokens){const r=e.parseChildren([i]);n.push({type:"paragraph",content:r})}else{const r=e.parseChildren([i]);r.length>0&&n.push(...r)}}),{type:"listItem",content:n}})}var GQ="listItem",xI="textStyle",II=/^(\d+)\.\s$/,hD=Sr.create({name:"orderedList",addOptions(){return{itemTypeName:"listItem",HTMLAttributes:{},keepMarks:!1,keepAttributes:!1}},group:"block list",content(){return`${this.options.itemTypeName}+`},addAttributes(){return{start:{default:1,parseHTML:s=>s.hasAttribute("start")?parseInt(s.getAttribute("start")||"",10):1},type:{default:null,parseHTML:s=>s.getAttribute("type")}}},parseHTML(){return[{tag:"ol"}]},renderHTML({HTMLAttributes:s}){const{start:e,...t}=s;return e===1?["ol",Fs(this.options.HTMLAttributes,t),0]:["ol",Fs(this.options.HTMLAttributes,s),0]},markdownTokenName:"list",parseMarkdown:(s,e)=>{if(s.type!=="list"||!s.ordered)return[];const t=s.start||1,n=s.items?VQ(s.items,e):[];return t!==1?{type:"orderedList",attrs:{start:t},content:n}:{type:"orderedList",content:n}},renderMarkdown:(s,e)=>s.content?e.renderChildren(s.content,`
`):"",markdownTokenizer:{name:"orderedList",level:"block",start:s=>{const e=s.match(/^(\s*)(\d+)\.\s+/),t=e==null?void 0:e.index;return t!==void 0?t:-1},tokenize:(s,e,t)=>{var n;const i=s.split(`
`),[r,o]=jQ(i);if(r.length===0)return;const a=uD(r,0,t);return a.length===0?void 0:{type:"list",ordered:!0,start:((n=r[0])==null?void 0:n.number)||1,items:a,raw:i.slice(0,o).join(`
`)}}},markdownOptions:{indentsContent:!0},addCommands(){return{toggleOrderedList:()=>({commands:s,chain:e})=>this.options.keepAttributes?e().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes(GQ,this.editor.getAttributes(xI)).run():s.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-7":()=>this.editor.commands.toggleOrderedList()}},addInputRules(){let s=im({find:II,type:this.type,getAttributes:e=>({start:+e[1]}),joinPredicate:(e,t)=>t.childCount+t.attrs.start===+e[1]});return(this.options.keepMarks||this.options.keepAttributes)&&(s=im({find:II,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:e=>({start:+e[1],...this.editor.getAttributes(xI)}),joinPredicate:(e,t)=>t.childCount+t.attrs.start===+e[1],editor:this.editor})),[s]}}),qQ=/^\s*(\[([( |x])?\])\s$/,KQ=Sr.create({name:"taskItem",addOptions(){return{nested:!1,HTMLAttributes:{},taskListTypeName:"taskList",a11y:void 0}},content(){return this.options.nested?"paragraph block*":"paragraph+"},defining:!0,addAttributes(){return{checked:{default:!1,keepOnSplit:!1,parseHTML:s=>{const e=s.getAttribute("data-checked");return e===""||e==="true"},renderHTML:s=>({"data-checked":s.checked})}}},parseHTML(){return[{tag:`li[data-type="${this.name}"]`,priority:51}]},renderHTML({node:s,HTMLAttributes:e}){return["li",Fs(this.options.HTMLAttributes,e,{"data-type":this.name}),["label",["input",{type:"checkbox",checked:s.attrs.checked?"checked":null}],["span"]],["div",0]]},parseMarkdown:(s,e)=>{const t=[];if(s.tokens&&s.tokens.length>0?t.push(e.createNode("paragraph",{},e.parseInline(s.tokens))):s.text?t.push(e.createNode("paragraph",{},[e.createNode("text",{text:s.text})])):t.push(e.createNode("paragraph",{},[])),s.nestedTokens&&s.nestedTokens.length>0){const n=e.parseChildren(s.nestedTokens);t.push(...n)}return e.createNode("taskItem",{checked:s.checked||!1},t)},renderMarkdown:(s,e)=>{var t;const i=`- [${(t=s.attrs)!=null&&t.checked?"x":" "}] `;return jE(s,e,i)},addExtensions(){return this.options.nested?[iD(this.name,[this.options.taskListTypeName])]:[]},addKeyboardShortcuts(){const s={Enter:()=>this.editor.commands.splitListItem(this.name),"Shift-Tab":()=>this.editor.commands.liftListItem(this.name)};return this.options.nested?{...s,Tab:()=>this.editor.commands.sinkListItem(this.name)}:s},addNodeView(){return({node:s,HTMLAttributes:e,getPos:t,editor:n})=>{const i=document.createElement("li"),r=document.createElement("label"),o=document.createElement("span"),a=document.createElement("input"),c=document.createElement("div"),l=h=>{var d,p;a.ariaLabel=((p=(d=this.options.a11y)==null?void 0:d.checkboxLabel)==null?void 0:p.call(d,h,a.checked))||`Task item checkbox for ${h.textContent||"empty task item"}`};l(s),r.contentEditable="false",a.type="checkbox",a.addEventListener("mousedown",h=>h.preventDefault()),a.addEventListener("change",h=>{if(!n.isEditable&&!this.options.onReadOnlyChecked){a.checked=!a.checked;return}const{checked:d}=h.target;n.isEditable&&typeof t=="function"&&n.chain().focus(void 0,{scrollIntoView:!1}).command(({tr:p})=>{const m=t();if(typeof m!="number")return!1;const v=p.doc.nodeAt(m);return p.setNodeMarkup(m,void 0,{...v==null?void 0:v.attrs,checked:d}),!0}).run(),!n.isEditable&&this.options.onReadOnlyChecked&&(this.options.onReadOnlyChecked(s,d)||(a.checked=!a.checked))}),Object.entries(this.options.HTMLAttributes).forEach(([h,d])=>{i.setAttribute(h,d)}),i.dataset.checked=s.attrs.checked,a.checked=s.attrs.checked,r.append(a,o),i.append(r,c),Object.entries(e).forEach(([h,d])=>{i.setAttribute(h,d)});let u=new Set(Object.keys(e));return{dom:i,contentDOM:c,update:h=>{if(h.type!==this.type)return!1;i.dataset.checked=h.attrs.checked,a.checked=h.attrs.checked,l(h);const d=n.extensionManager.attributes,p=ey(h,d),m=new Set(Object.keys(p)),v=this.options.HTMLAttributes;return u.forEach(g=>{m.has(g)||(g in v?i.setAttribute(g,v[g]):i.removeAttribute(g))}),Object.entries(p).forEach(([g,y])=>{y==null?g in v?i.setAttribute(g,v[g]):i.removeAttribute(g):i.setAttribute(g,y)}),u=m,!0}}}},addInputRules(){return[im({find:qQ,type:this.type,getAttributes:s=>({checked:s[s.length-1]==="x"})})]}}),QQ=Sr.create({name:"taskList",addOptions(){return{itemTypeName:"taskItem",HTMLAttributes:{}}},group:"block list",content(){return`${this.options.itemTypeName}+`},parseHTML(){return[{tag:`ul[data-type="${this.name}"]`,priority:51}]},renderHTML({HTMLAttributes:s}){return["ul",Fs(this.options.HTMLAttributes,s,{"data-type":this.name}),0]},parseMarkdown:(s,e)=>e.createNode("taskList",{},e.parseChildren(s.items||[])),renderMarkdown:(s,e)=>s.content?e.renderChildren(s.content,`
`):"",markdownTokenizer:{name:"taskList",level:"block",start(s){var e;const t=(e=s.match(/^\s*[-+*]\s+\[([ xX])\]\s+/))==null?void 0:e.index;return t!==void 0?t:-1},tokenize(s,e,t){const n=r=>{const o=X1(r,{itemPattern:/^(\s*)([-+*])\s+\[([ xX])\]\s+(.*)$/,extractItemData:a=>({indentLevel:a[1].length,mainContent:a[4],checked:a[3].toLowerCase()==="x"}),createToken:(a,c)=>({type:"taskItem",raw:"",mainContent:a.mainContent,indentLevel:a.indentLevel,checked:a.checked,text:a.mainContent,tokens:t.inlineTokens(a.mainContent),nestedTokens:c}),customNestedParser:n},t);return o?[{type:"taskList",raw:o.raw,items:o.items}]:t.blockTokens(r)},i=X1(s,{itemPattern:/^(\s*)([-+*])\s+\[([ xX])\]\s+(.*)$/,extractItemData:r=>({indentLevel:r[1].length,mainContent:r[4],checked:r[3].toLowerCase()==="x"}),createToken:(r,o)=>({type:"taskItem",raw:"",mainContent:r.mainContent,indentLevel:r.indentLevel,checked:r.checked,text:r.mainContent,tokens:t.inlineTokens(r.mainContent),nestedTokens:o}),customNestedParser:n},t);if(i)return{type:"taskList",raw:i.raw,items:i.items}}},markdownOptions:{indentsContent:!0},addCommands(){return{toggleTaskList:()=>({commands:s})=>s.toggleList(this.name,this.options.itemTypeName)}},addKeyboardShortcuts(){return{"Mod-Shift-9":()=>this.editor.commands.toggleTaskList()}}});on.create({name:"listKit",addExtensions(){const s=[];return this.options.bulletList!==!1&&s.push(nD.configure(this.options.bulletList)),this.options.listItem!==!1&&s.push(rD.configure(this.options.listItem)),this.options.listKeymap!==!1&&s.push(cD.configure(this.options.listKeymap)),this.options.orderedList!==!1&&s.push(hD.configure(this.options.orderedList)),this.options.taskItem!==!1&&s.push(KQ.configure(this.options.taskItem)),this.options.taskList!==!1&&s.push(QQ.configure(this.options.taskList)),s}});var $_="&nbsp;",PC=" ",XQ=Sr.create({name:"paragraph",priority:1e3,addOptions(){return{HTMLAttributes:{}}},group:"block",content:"inline*",parseHTML(){return[{tag:"p"}]},renderHTML({HTMLAttributes:s}){return["p",Fs(this.options.HTMLAttributes,s),0]},parseMarkdown:(s,e)=>{const t=s.tokens||[];if(t.length===1&&t[0].type==="image")return e.parseChildren([t[0]]);const n=e.parseInline(t);return t.length===1&&t[0].type==="text"&&(t[0].raw===$_||t[0].text===$_||t[0].raw===PC||t[0].text===PC)&&n.length===1&&n[0].type==="text"&&(n[0].text===$_||n[0].text===PC)?e.createNode("paragraph",void 0,[]):e.createNode("paragraph",void 0,n)},renderMarkdown:(s,e,t)=>{var n,i;if(!s)return"";const r=Array.isArray(s.content)?s.content:[];if(r.length===0){const o=Array.isArray((n=t==null?void 0:t.previousNode)==null?void 0:n.content)?t.previousNode.content:[];return((i=t==null?void 0:t.previousNode)==null?void 0:i.type)==="paragraph"&&o.length===0?$_:""}return e.renderChildren(r)},addCommands(){return{setParagraph:()=>({commands:s})=>s.setNode(this.name)}},addKeyboardShortcuts(){return{"Mod-Alt-0":()=>this.editor.commands.setParagraph()}}}),YQ=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/,JQ=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g,ZQ=Df.create({name:"strike",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"s"},{tag:"del"},{tag:"strike"},{style:"text-decoration",consuming:!1,getAttrs:s=>s.includes("line-through")?{}:!1}]},renderHTML({HTMLAttributes:s}){return["s",Fs(this.options.HTMLAttributes,s),0]},markdownTokenName:"del",parseMarkdown:(s,e)=>e.applyMark("strike",e.parseInline(s.tokens||[])),renderMarkdown:(s,e)=>`~~${e.renderChildren(s)}~~`,addCommands(){return{setStrike:()=>({commands:s})=>s.setMark(this.name),toggleStrike:()=>({commands:s})=>s.toggleMark(this.name),unsetStrike:()=>({commands:s})=>s.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-Shift-s":()=>this.editor.commands.toggleStrike()}},addInputRules(){return[nm({find:YQ,type:this.type})]},addPasteRules(){return[xf({find:JQ,type:this.type})]}}),eX=Sr.create({name:"text",group:"inline",parseMarkdown:s=>({type:"text",text:s.text||""}),renderMarkdown:s=>s.text||""}),tX=Df.create({name:"underline",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"u"},{style:"text-decoration",consuming:!1,getAttrs:s=>s.includes("underline")?{}:!1}]},renderHTML({HTMLAttributes:s}){return["u",Fs(this.options.HTMLAttributes,s),0]},parseMarkdown(s,e){return e.applyMark(this.name||"underline",e.parseInline(s.tokens||[]))},renderMarkdown(s,e){return`++${e.renderChildren(s)}++`},markdownTokenizer:{name:"underline",level:"inline",start(s){return s.indexOf("++")},tokenize(s,e,t){const i=/^(\+\+)([\s\S]+?)(\+\+)/.exec(s);if(!i)return;const r=i[2].trim();return{type:"underline",raw:i[0],text:r,tokens:t.inlineTokens(r)}}},addCommands(){return{setUnderline:()=>({commands:s})=>s.setMark(this.name),toggleUnderline:()=>({commands:s})=>s.toggleMark(this.name),unsetUnderline:()=>({commands:s})=>s.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-u":()=>this.editor.commands.toggleUnderline(),"Mod-U":()=>this.editor.commands.toggleUnderline()}}});function sX(s={}){return new $s({view(e){return new nX(e,s)}})}class nX{constructor(e,t){var n;this.editorView=e,this.cursorPos=null,this.element=null,this.timeout=-1,this.width=(n=t.width)!==null&&n!==void 0?n:1,this.color=t.color===!1?void 0:t.color||"black",this.class=t.class,this.handlers=["dragover","dragend","drop","dragleave"].map(i=>{let r=o=>{this[i](o)};return e.dom.addEventListener(i,r),{name:i,handler:r}})}destroy(){this.handlers.forEach(({name:e,handler:t})=>this.editorView.dom.removeEventListener(e,t))}update(e,t){this.cursorPos!=null&&t.doc!=e.state.doc&&(this.cursorPos>e.state.doc.content.size?this.setCursor(null):this.updateOverlay())}setCursor(e){e!=this.cursorPos&&(this.cursorPos=e,e==null?(this.element.parentNode.removeChild(this.element),this.element=null):this.updateOverlay())}updateOverlay(){let e=this.editorView.state.doc.resolve(this.cursorPos),t=!e.parent.inlineContent,n,i=this.editorView.dom,r=i.getBoundingClientRect(),o=r.width/i.offsetWidth,a=r.height/i.offsetHeight;if(t){let h=e.nodeBefore,d=e.nodeAfter;if(h||d){let p=this.editorView.nodeDOM(this.cursorPos-(h?h.nodeSize:0));if(p){let m=p.getBoundingClientRect(),v=h?m.bottom:m.top;h&&d&&(v=(v+this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top)/2);let g=this.width/2*a;n={left:m.left,right:m.right,top:v-g,bottom:v+g}}}}if(!n){let h=this.editorView.coordsAtPos(this.cursorPos),d=this.width/2*o;n={left:h.left-d,right:h.left+d,top:h.top,bottom:h.bottom}}let c=this.editorView.dom.offsetParent;this.element||(this.element=c.appendChild(document.createElement("div")),this.class&&(this.element.className=this.class),this.element.style.cssText="position: absolute; z-index: 50; pointer-events: none;",this.color&&(this.element.style.backgroundColor=this.color)),this.element.classList.toggle("prosemirror-dropcursor-block",t),this.element.classList.toggle("prosemirror-dropcursor-inline",!t);let l,u;if(!c||c==document.body&&getComputedStyle(c).position=="static")l=-pageXOffset,u=-pageYOffset;else{let h=c.getBoundingClientRect(),d=h.width/c.offsetWidth,p=h.height/c.offsetHeight;l=h.left-c.scrollLeft*d,u=h.top-c.scrollTop*p}this.element.style.left=(n.left-l)/o+"px",this.element.style.top=(n.top-u)/a+"px",this.element.style.width=(n.right-n.left)/o+"px",this.element.style.height=(n.bottom-n.top)/a+"px"}scheduleRemoval(e){clearTimeout(this.timeout),this.timeout=setTimeout(()=>this.setCursor(null),e)}dragover(e){if(!this.editorView.editable)return;let t=this.editorView.posAtCoords({left:e.clientX,top:e.clientY}),n=t&&t.inside>=0&&this.editorView.state.doc.nodeAt(t.inside),i=n&&n.type.spec.disableDropCursor,r=typeof i=="function"?i(this.editorView,t,e):i;if(t&&!r){let o=t.pos;if(this.editorView.dragging&&this.editorView.dragging.slice){let a=WL(this.editorView.state.doc,o,this.editorView.dragging.slice);a!=null&&(o=a)}this.setCursor(o),this.scheduleRemoval(5e3)}}dragend(){this.scheduleRemoval(20)}drop(){this.scheduleRemoval(20)}dragleave(e){this.editorView.dom.contains(e.relatedTarget)||this.setCursor(null)}}class rn extends Ft{constructor(e){super(e,e)}map(e,t){let n=e.resolve(t.map(this.head));return rn.valid(n)?new rn(n):Ft.near(n)}content(){return nt.empty}eq(e){return e instanceof rn&&e.head==this.head}toJSON(){return{type:"gapcursor",pos:this.head}}static fromJSON(e,t){if(typeof t.pos!="number")throw new RangeError("Invalid input for GapCursor.fromJSON");return new rn(e.resolve(t.pos))}getBookmark(){return new nM(this.anchor)}static valid(e){let t=e.parent;if(t.inlineContent||!iX(e)||!rX(e))return!1;let n=t.type.spec.allowGapCursor;if(n!=null)return n;let i=t.contentMatchAt(e.index()).defaultType;return i&&i.isTextblock}static findGapCursorFrom(e,t,n=!1){e:for(;;){if(!n&&rn.valid(e))return e;let i=e.pos,r=null;for(let o=e.depth;;o--){let a=e.node(o);if(t>0?e.indexAfter(o)<a.childCount:e.index(o)>0){r=a.child(t>0?e.indexAfter(o):e.index(o)-1);break}else if(o==0)return null;i+=t;let c=e.doc.resolve(i);if(rn.valid(c))return c}for(;;){let o=t>0?r.firstChild:r.lastChild;if(!o){if(r.isAtom&&!r.isText&&!vt.isSelectable(r)){e=e.doc.resolve(i+r.nodeSize*t),n=!1;continue e}break}r=o,i+=t;let a=e.doc.resolve(i);if(rn.valid(a))return a}return null}}}rn.prototype.visible=!1;rn.findFrom=rn.findGapCursorFrom;Ft.jsonID("gapcursor",rn);class nM{constructor(e){this.pos=e}map(e){return new nM(e.map(this.pos))}resolve(e){let t=e.resolve(this.pos);return rn.valid(t)?new rn(t):Ft.near(t)}}function dD(s){return s.isAtom||s.spec.isolating||s.spec.createGapCursor}function iX(s){for(let e=s.depth;e>=0;e--){let t=s.index(e),n=s.node(e);if(t==0){if(n.type.spec.isolating)return!0;continue}for(let i=n.child(t-1);;i=i.lastChild){if(i.childCount==0&&!i.inlineContent||dD(i.type))return!0;if(i.inlineContent)return!1}}return!0}function rX(s){for(let e=s.depth;e>=0;e--){let t=s.indexAfter(e),n=s.node(e);if(t==n.childCount){if(n.type.spec.isolating)return!0;continue}for(let i=n.child(t);;i=i.firstChild){if(i.childCount==0&&!i.inlineContent||dD(i.type))return!0;if(i.inlineContent)return!1}}return!0}function oX(){return new $s({props:{decorations:uX,createSelectionBetween(s,e,t){return e.pos==t.pos&&rn.valid(t)?new rn(t):null},handleClick:lX,handleKeyDown:aX,handleDOMEvents:{beforeinput:cX}}})}const aX=QP({ArrowLeft:H_("horiz",-1),ArrowRight:H_("horiz",1),ArrowUp:H_("vert",-1),ArrowDown:H_("vert",1)});function H_(s,e){const t=s=="vert"?e>0?"down":"up":e>0?"right":"left";return function(n,i,r){let o=n.selection,a=e>0?o.$to:o.$from,c=o.empty;if(o instanceof _t){if(!r.endOfTextblock(t)||a.depth==0)return!1;c=!1,a=n.doc.resolve(e>0?a.after():a.before())}let l=rn.findGapCursorFrom(a,e,c);return l?(i&&i(n.tr.setSelection(new rn(l))),!0):!1}}function lX(s,e,t){if(!s||!s.editable)return!1;let n=s.state.doc.resolve(e);if(!rn.valid(n))return!1;let i=s.posAtCoords({left:t.clientX,top:t.clientY});return i&&i.inside>-1&&vt.isSelectable(s.state.doc.nodeAt(i.inside))?!1:(s.dispatch(s.state.tr.setSelection(new rn(n))),!0)}function cX(s,e){if(e.inputType!="insertCompositionText"||!(s.state.selection instanceof rn))return!1;let{$from:t}=s.state.selection,n=t.parent.contentMatchAt(t.index()).findWrapping(s.state.schema.nodes.text);if(!n)return!1;let i=Fe.empty;for(let o=n.length-1;o>=0;o--)i=Fe.from(n[o].createAndFill(null,i));let r=s.state.tr.replace(t.pos,t.pos,new nt(i,0,0));return r.setSelection(_t.near(r.doc.resolve(t.pos+1))),s.dispatch(r),!1}function uX(s){if(!(s.selection instanceof rn))return null;let e=document.createElement("div");return e.className="ProseMirror-gapcursor",Bs.create(s.doc,[Mi.widget(s.selection.head,e,{key:"gapcursor"})])}var o0=200,Xn=function(){};Xn.prototype.append=function(e){return e.length?(e=Xn.from(e),!this.length&&e||e.length<o0&&this.leafAppend(e)||this.length<o0&&e.leafPrepend(this)||this.appendInner(e)):this};Xn.prototype.prepend=function(e){return e.length?Xn.from(e).append(this):this};Xn.prototype.appendInner=function(e){return new hX(this,e)};Xn.prototype.slice=function(e,t){return e===void 0&&(e=0),t===void 0&&(t=this.length),e>=t?Xn.empty:this.sliceInner(Math.max(0,e),Math.min(this.length,t))};Xn.prototype.get=function(e){if(!(e<0||e>=this.length))return this.getInner(e)};Xn.prototype.forEach=function(e,t,n){t===void 0&&(t=0),n===void 0&&(n=this.length),t<=n?this.forEachInner(e,t,n,0):this.forEachInvertedInner(e,t,n,0)};Xn.prototype.map=function(e,t,n){t===void 0&&(t=0),n===void 0&&(n=this.length);var i=[];return this.forEach(function(r,o){return i.push(e(r,o))},t,n),i};Xn.from=function(e){return e instanceof Xn?e:e&&e.length?new fD(e):Xn.empty};var fD=function(s){function e(n){s.call(this),this.values=n}s&&(e.__proto__=s),e.prototype=Object.create(s&&s.prototype),e.prototype.constructor=e;var t={length:{configurable:!0},depth:{configurable:!0}};return e.prototype.flatten=function(){return this.values},e.prototype.sliceInner=function(i,r){return i==0&&r==this.length?this:new e(this.values.slice(i,r))},e.prototype.getInner=function(i){return this.values[i]},e.prototype.forEachInner=function(i,r,o,a){for(var c=r;c<o;c++)if(i(this.values[c],a+c)===!1)return!1},e.prototype.forEachInvertedInner=function(i,r,o,a){for(var c=r-1;c>=o;c--)if(i(this.values[c],a+c)===!1)return!1},e.prototype.leafAppend=function(i){if(this.length+i.length<=o0)return new e(this.values.concat(i.flatten()))},e.prototype.leafPrepend=function(i){if(this.length+i.length<=o0)return new e(i.flatten().concat(this.values))},t.length.get=function(){return this.values.length},t.depth.get=function(){return 0},Object.defineProperties(e.prototype,t),e}(Xn);Xn.empty=new fD([]);var hX=function(s){function e(t,n){s.call(this),this.left=t,this.right=n,this.length=t.length+n.length,this.depth=Math.max(t.depth,n.depth)+1}return s&&(e.__proto__=s),e.prototype=Object.create(s&&s.prototype),e.prototype.constructor=e,e.prototype.flatten=function(){return this.left.flatten().concat(this.right.flatten())},e.prototype.getInner=function(n){return n<this.left.length?this.left.get(n):this.right.get(n-this.left.length)},e.prototype.forEachInner=function(n,i,r,o){var a=this.left.length;if(i<a&&this.left.forEachInner(n,i,Math.min(r,a),o)===!1||r>a&&this.right.forEachInner(n,Math.max(i-a,0),Math.min(this.length,r)-a,o+a)===!1)return!1},e.prototype.forEachInvertedInner=function(n,i,r,o){var a=this.left.length;if(i>a&&this.right.forEachInvertedInner(n,i-a,Math.max(r,a)-a,o+a)===!1||r<a&&this.left.forEachInvertedInner(n,Math.min(i,a),r,o)===!1)return!1},e.prototype.sliceInner=function(n,i){if(n==0&&i==this.length)return this;var r=this.left.length;return i<=r?this.left.slice(n,i):n>=r?this.right.slice(n-r,i-r):this.left.slice(n,r).append(this.right.slice(0,i-r))},e.prototype.leafAppend=function(n){var i=this.right.leafAppend(n);if(i)return new e(this.left,i)},e.prototype.leafPrepend=function(n){var i=this.left.leafPrepend(n);if(i)return new e(i,this.right)},e.prototype.appendInner=function(n){return this.left.depth>=Math.max(this.right.depth,n.depth)+1?new e(this.left,new e(this.right,n)):new e(this,n)},e}(Xn);const dX=500;class fa{constructor(e,t){this.items=e,this.eventCount=t}popEvent(e,t){if(this.eventCount==0)return null;let n=this.items.length;for(;;n--)if(this.items.get(n-1).selection){--n;break}let i,r;t&&(i=this.remapping(n,this.items.length),r=i.maps.length);let o=e.tr,a,c,l=[],u=[];return this.items.forEach((h,d)=>{if(!h.step){i||(i=this.remapping(n,d+1),r=i.maps.length),r--,u.push(h);return}if(i){u.push(new xa(h.map));let p=h.step.map(i.slice(r)),m;p&&o.maybeStep(p).doc&&(m=o.mapping.maps[o.mapping.maps.length-1],l.push(new xa(m,void 0,void 0,l.length+u.length))),r--,m&&i.appendMap(m,r)}else o.maybeStep(h.step);if(h.selection)return a=i?h.selection.map(i.slice(r)):h.selection,c=new fa(this.items.slice(0,n).append(u.reverse().concat(l)),this.eventCount-1),!1},this.items.length,0),{remaining:c,transform:o,selection:a}}addTransform(e,t,n,i){let r=[],o=this.eventCount,a=this.items,c=!i&&a.length?a.get(a.length-1):null;for(let u=0;u<e.steps.length;u++){let h=e.steps[u].invert(e.docs[u]),d=new xa(e.mapping.maps[u],h,t),p;(p=c&&c.merge(d))&&(d=p,u?r.pop():a=a.slice(0,a.length-1)),r.push(d),t&&(o++,t=void 0),i||(c=d)}let l=o-n.depth;return l>pX&&(a=fX(a,l),o-=l),new fa(a.append(r),o)}remapping(e,t){let n=new Qv;return this.items.forEach((i,r)=>{let o=i.mirrorOffset!=null&&r-i.mirrorOffset>=e?n.maps.length-i.mirrorOffset:void 0;n.appendMap(i.map,o)},e,t),n}addMaps(e){return this.eventCount==0?this:new fa(this.items.append(e.map(t=>new xa(t))),this.eventCount)}rebased(e,t){if(!this.eventCount)return this;let n=[],i=Math.max(0,this.items.length-t),r=e.mapping,o=e.steps.length,a=this.eventCount;this.items.forEach(d=>{d.selection&&a--},i);let c=t;this.items.forEach(d=>{let p=r.getMirror(--c);if(p==null)return;o=Math.min(o,p);let m=r.maps[p];if(d.step){let v=e.steps[p].invert(e.docs[p]),g=d.selection&&d.selection.map(r.slice(c+1,p));g&&a++,n.push(new xa(m,v,g))}else n.push(new xa(m))},i);let l=[];for(let d=t;d<o;d++)l.push(new xa(r.maps[d]));let u=this.items.slice(0,i).append(l).append(n),h=new fa(u,a);return h.emptyItemCount()>dX&&(h=h.compress(this.items.length-n.length)),h}emptyItemCount(){let e=0;return this.items.forEach(t=>{t.step||e++}),e}compress(e=this.items.length){let t=this.remapping(0,e),n=t.maps.length,i=[],r=0;return this.items.forEach((o,a)=>{if(a>=e)i.push(o),o.selection&&r++;else if(o.step){let c=o.step.map(t.slice(n)),l=c&&c.getMap();if(n--,l&&t.appendMap(l,n),c){let u=o.selection&&o.selection.map(t.slice(n));u&&r++;let h=new xa(l.invert(),c,u),d,p=i.length-1;(d=i.length&&i[p].merge(h))?i[p]=d:i.push(h)}}else o.map&&n--},this.items.length,0),new fa(Xn.from(i.reverse()),r)}}fa.empty=new fa(Xn.empty,0);function fX(s,e){let t;return s.forEach((n,i)=>{if(n.selection&&e--==0)return t=i,!1}),s.slice(t)}class xa{constructor(e,t,n,i){this.map=e,this.step=t,this.selection=n,this.mirrorOffset=i}merge(e){if(this.step&&e.step&&!e.selection){let t=e.step.merge(this.step);if(t)return new xa(t.getMap().invert(),t,this.selection)}}}class Yc{constructor(e,t,n,i,r){this.done=e,this.undone=t,this.prevRanges=n,this.prevTime=i,this.prevComposition=r}}const pX=20;function gX(s,e,t,n){let i=t.getMeta(Cf),r;if(i)return i.historyState;t.getMeta(yX)&&(s=new Yc(s.done,s.undone,null,0,-1));let o=t.getMeta("appendedTransaction");if(t.steps.length==0)return s;if(o&&o.getMeta(Cf))return o.getMeta(Cf).redo?new Yc(s.done.addTransform(t,void 0,n,SS(e)),s.undone,RI(t.mapping.maps),s.prevTime,s.prevComposition):new Yc(s.done,s.undone.addTransform(t,void 0,n,SS(e)),null,s.prevTime,s.prevComposition);if(t.getMeta("addToHistory")!==!1&&!(o&&o.getMeta("addToHistory")===!1)){let a=t.getMeta("composition"),c=s.prevTime==0||!o&&s.prevComposition!=a&&(s.prevTime<(t.time||0)-n.newGroupDelay||!mX(t,s.prevRanges)),l=o?OC(s.prevRanges,t.mapping):RI(t.mapping.maps);return new Yc(s.done.addTransform(t,c?e.selection.getBookmark():void 0,n,SS(e)),fa.empty,l,t.time,a??s.prevComposition)}else return(r=t.getMeta("rebased"))?new Yc(s.done.rebased(t,r),s.undone.rebased(t,r),OC(s.prevRanges,t.mapping),s.prevTime,s.prevComposition):new Yc(s.done.addMaps(t.mapping.maps),s.undone.addMaps(t.mapping.maps),OC(s.prevRanges,t.mapping),s.prevTime,s.prevComposition)}function mX(s,e){if(!e)return!1;if(!s.docChanged)return!0;let t=!1;return s.mapping.maps[0].forEach((n,i)=>{for(let r=0;r<e.length;r+=2)n<=e[r+1]&&i>=e[r]&&(t=!0)}),t}function RI(s){let e=[];for(let t=s.length-1;t>=0&&e.length==0;t--)s[t].forEach((n,i,r,o)=>e.push(r,o));return e}function OC(s,e){if(!s)return null;let t=[];for(let n=0;n<s.length;n+=2){let i=e.map(s[n],1),r=e.map(s[n+1],-1);i<=r&&t.push(i,r)}return t}function vX(s,e,t){let n=SS(e),i=Cf.get(e).spec.config,r=(t?s.undone:s.done).popEvent(e,n);if(!r)return null;let o=r.selection.resolve(r.transform.doc),a=(t?s.done:s.undone).addTransform(r.transform,e.selection.getBookmark(),i,n),c=new Yc(t?a:r.remaining,t?r.remaining:a,null,0,-1);return r.transform.setSelection(o).setMeta(Cf,{redo:t,historyState:c})}let DC=!1,LI=null;function SS(s){let e=s.plugins;if(LI!=e){DC=!1,LI=e;for(let t=0;t<e.length;t++)if(e[t].spec.historyPreserveItems){DC=!0;break}}return DC}const Cf=new fn("history"),yX=new fn("closeHistory");function bX(s={}){return s={depth:s.depth||100,newGroupDelay:s.newGroupDelay||500},new $s({key:Cf,state:{init(){return new Yc(fa.empty,fa.empty,null,0,-1)},apply(e,t,n){return gX(t,n,e,s)}},config:s,props:{handleDOMEvents:{beforeinput(e,t){let n=t.inputType,i=n=="historyUndo"?gD:n=="historyRedo"?mD:null;return!i||!e.editable?!1:(t.preventDefault(),i(e.state,e.dispatch))}}}})}function pD(s,e){return(t,n)=>{let i=Cf.getState(t);if(!i||(s?i.undone:i.done).eventCount==0)return!1;if(n){let r=vX(i,t,s);r&&n(e?r.scrollIntoView():r)}return!0}}const gD=pD(!1,!0),mD=pD(!0,!0);on.create({name:"characterCount",addOptions(){return{limit:null,autoTrim:!0,mode:"textSize",textCounter:s=>s.length,wordCounter:s=>s.split(" ").filter(e=>e!=="").length}},addStorage(){return{characters:()=>0,words:()=>0}},onBeforeCreate(){this.storage.characters=s=>{const e=(s==null?void 0:s.node)||this.editor.state.doc;if(((s==null?void 0:s.mode)||this.options.mode)==="textSize"){const n=e.textBetween(0,e.content.size,void 0," ");return this.options.textCounter(n)}return e.nodeSize},this.storage.words=s=>{const e=(s==null?void 0:s.node)||this.editor.state.doc,t=e.textBetween(0,e.content.size," "," ");return this.options.wordCounter(t)}},addProseMirrorPlugins(){let s=!1;return[new $s({key:new fn("characterCount"),appendTransaction:(e,t,n)=>{if(s)return;const i=this.options.limit,r=this.options.autoTrim;if(i==null||i===0||r===!1){s=!0;return}const o=this.storage.characters({node:n.doc});if(o>i){const a=o-i,c=0,l=a;console.warn(`[CharacterCount] Initial content exceeded limit of ${i} characters. Content was automatically trimmed.`);const u=n.tr.deleteRange(c,l);return s=!0,u}s=!0},filterTransaction:(e,t)=>{const n=this.options.limit;if(!e.docChanged||n===0||n===null||n===void 0)return!0;const i=this.storage.characters({node:t.doc}),r=this.storage.characters({node:e.doc});if(r<=n||i>n&&r>n&&r<=i)return!0;if(i>n&&r>n&&r>i||!e.getMeta("paste"))return!1;const a=e.selection.$head.pos,c=r-n,l=a-c,u=a;return e.deleteRange(l,u),!(this.storage.characters({node:e.doc})>n)}})]}});var _X=on.create({name:"dropCursor",addOptions(){return{color:"currentColor",width:1,class:void 0}},addProseMirrorPlugins(){return[sX(this.options)]}});on.create({name:"focus",addOptions(){return{className:"has-focus",mode:"all"}},addProseMirrorPlugins(){return[new $s({key:new fn("focus"),props:{decorations:({doc:s,selection:e})=>{const{isEditable:t,isFocused:n}=this.editor,{anchor:i}=e,r=[];if(!t||!n)return Bs.create(s,[]);let o=0;this.options.mode==="deepest"&&s.descendants((c,l)=>{if(c.isText)return;if(!(i>=l&&i<=l+c.nodeSize-1))return!1;o+=1});let a=0;return s.descendants((c,l)=>{if(c.isText||!(i>=l&&i<=l+c.nodeSize-1))return!1;if(a+=1,this.options.mode==="deepest"&&o-a>0||this.options.mode==="shallowest"&&a>1)return this.options.mode==="deepest";r.push(Mi.node(l,l+c.nodeSize,{class:this.options.className}))}),Bs.create(s,r)}}})]}});var SX=on.create({name:"gapCursor",addProseMirrorPlugins(){return[oX()]},extendNodeSchema(s){var e;const t={name:s.name,options:s.options,storage:s.storage};return{allowGapCursor:(e=ns(ot(s,"allowGapCursor",t)))!=null?e:null}}}),vD="placeholder",ry=new fn("tiptap__placeholder"),PI=200;function OI(s){const{editor:e,placeholder:t,dataAttribute:n,pos:i,node:r,isEmptyDoc:o,hasAnchor:a,classes:{emptyNode:c,emptyEditor:l}}=s,u=[c];return o&&u.push(l),Mi.node(i,i+r.nodeSize,{class:u.join(" "),[n]:typeof t=="function"?t({editor:e,node:r,pos:i,hasAnchor:a}):t})}function DI(s,e){return typeof s=="function"?s(e):s}function wX({editor:s,options:e,dataAttribute:t,doc:n,selection:i}){var r,o;if(!(s.isEditable||!e.showOnlyWhenEditable))return null;const{anchor:c}=i,l=[],u=s.isEmpty;if(e.showOnlyCurrent&&!e.includeChildren){const d=n.resolve(c),p=d.depth>0?d.node(1):d.nodeAfter,m=d.depth>0?d.before(1):c;if(p&&p.type.isTextblock&&ty(p)){const v=c>=m&&c<=m+p.nodeSize;l.push(OI({editor:s,isEmptyDoc:u,dataAttribute:t,hasAnchor:v,placeholder:e.placeholder,classes:{emptyEditor:e.emptyEditorClass,emptyNode:DI(e.emptyNodeClass,{editor:s,node:p,pos:m,hasAnchor:v})},node:p,pos:m}))}}else{const d=ry.getState(s.state),p=(r=d==null?void 0:d.topPos)!=null?r:0,m=(o=d==null?void 0:d.bottomPos)!=null?o:n.content.size;n.nodesBetween(p,m,(v,g)=>{const y=c>=g&&c<=g+v.nodeSize,b=!v.isLeaf&&ty(v);return v.type.isTextblock&&(y||!e.showOnlyCurrent)&&b&&l.push(OI({editor:s,isEmptyDoc:u,dataAttribute:t,hasAnchor:y,placeholder:e.placeholder,classes:{emptyEditor:e.emptyEditorClass,emptyNode:DI(e.emptyNodeClass,{editor:s,node:v,pos:g,hasAnchor:y})},node:v,pos:g})),e.includeChildren})}return Bs.create(n,l)}function kX(s){return s.replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-]/g,"").replace(/^[0-9-]+/,"").replace(/^-+/,"").toLowerCase()}function CX(s){const e=getComputedStyle(s),t=`${e.overflow} ${e.overflowY} ${e.overflowX}`;return/auto|scroll|overlay/.test(t)}function TX(s){let e=s;for(;e;){if(CX(e))return e;const t=e.parentElement;if(!t){const n=e.getRootNode();if(n instanceof ShadowRoot){e=n.host;continue}return window}e=t}return window}function AX(s){return s===window?{top:0,bottom:window.innerHeight}:s.getBoundingClientRect()}function EX({doc:s,view:e,scrollContainer:t}){const n=e.dom.getBoundingClientRect(),i=t?AX(t):{top:0,bottom:window.innerHeight},r=Math.max(n.top,i.top)-PI,o=Math.min(n.bottom,i.bottom)+PI;if(r>=o)return{top:0,bottom:s.content.size};const c=getComputedStyle(e.dom).direction==="rtl"?Math.max(n.right-2,n.left+2):n.left+2,l=e.posAtCoords({left:c,top:r+2}),u=e.posAtCoords({left:c,top:o-2});return{top:l?l.pos:0,bottom:u?u.pos:s.content.size}}var MX={init(){return{topPos:null,bottomPos:null}},apply(s,e){const t=s.getMeta(ry);return t!=null&&t.positions?{topPos:t.positions.top,bottomPos:t.positions.bottom}:s.docChanged?{topPos:e.topPos!==null?s.mapping.map(e.topPos):null,bottomPos:e.bottomPos!==null?s.mapping.map(e.bottomPos):null}:e}};function xX(s){const e=TX(s.dom),t=()=>{const a=EX({view:s,doc:s.state.doc,scrollContainer:e}),c=ry.getState(s.state);if((c==null?void 0:c.topPos)===a.top&&(c==null?void 0:c.bottomPos)===a.bottom)return;const l=s.state.tr.setMeta(ry,{positions:a});s.dispatch(l)};let n=null,i=0;const r=150,o=()=>{n===null&&(n=requestAnimationFrame(()=>{n=null;const a=performance.now();a-i>=r?(i=a,t()):o()}))};return e.addEventListener("scroll",o,{passive:!0}),t(),{update(a,c){s.state.doc.content.size!==c.doc.content.size&&o()},destroy:()=>{n!==null&&cancelAnimationFrame(n),e.removeEventListener("scroll",o)}}}function IX({editor:s,options:e}){const t=e.dataAttribute?`data-${kX(e.dataAttribute)}`:`data-${vD}`;return new $s({key:ry,state:MX,view:xX,props:{decorations:({doc:n,selection:i})=>wX({editor:s,options:e,dataAttribute:t,doc:n,selection:i})}})}var RX=on.create({name:"placeholder",addOptions(){return{emptyEditorClass:"is-editor-empty",emptyNodeClass:"is-empty",dataAttribute:vD,placeholder:"Write something …",showOnlyWhenEditable:!0,showOnlyCurrent:!0,includeChildren:!1}},addProseMirrorPlugins(){return[IX({editor:this.editor,options:this.options})]}}),LX=`.ProseMirror:not(.ProseMirror-focused) *::selection {
background: transparent;
}
.ProseMirror:not(.ProseMirror-focused) *::-moz-selection {
background: transparent;
}`;on.create({name:"selection",addOptions(){return{className:"selection"}},addProseMirrorPlugins(){const{editor:s,options:e}=this;return s.options.injectCSS&&typeof document<"u"&&MO(LX,s.options.injectNonce,"selection"),[new $s({key:new fn("selection"),props:{decorations(t){return t.selection.empty||s.isFocused||!s.isEditable||hO(t.selection)||s.view.dragging?null:Bs.create(t.doc,[Mi.inline(t.selection.from,t.selection.to,{class:e.className})])}}})]}});var PX="skipTrailingNode";function NI({types:s,node:e}){return e&&Array.isArray(s)&&s.includes(e.type)||(e==null?void 0:e.type)===s}var OX=on.create({name:"trailingNode",addOptions(){return{node:void 0,notAfter:[]}},addProseMirrorPlugins(){var s;const e=new fn(this.name),t=this.options.node||((s=this.editor.schema.topNodeType.contentMatch.defaultType)==null?void 0:s.name)||"paragraph",n=Object.entries(this.editor.schema.nodes).map(([,i])=>i).filter(i=>(this.options.notAfter||[]).concat(t).includes(i.name));return[new $s({key:e,appendTransaction:(i,r,o)=>{const{doc:a,tr:c,schema:l}=o,u=e.getState(o),h=a.content.size,d=l.nodes[t];if(!i.some(p=>p.getMeta(PX))&&u)return c.insert(h,d.create())},state:{init:(i,r)=>{const o=r.tr.doc.lastChild;return!NI({node:o,types:n})},apply:(i,r)=>{if(!i.docChanged||i.getMeta("__uniqueIDTransaction"))return r;const o=i.doc.lastChild;return!NI({node:o,types:n})}}})]}}),DX=on.create({name:"undoRedo",addOptions(){return{depth:100,newGroupDelay:500}},addCommands(){return{undo:()=>({state:s,dispatch:e})=>gD(s,e),redo:()=>({state:s,dispatch:e})=>mD(s,e)}},addProseMirrorPlugins(){return[bX(this.options)]},addKeyboardShortcuts(){return{"Mod-z":()=>this.editor.commands.undo(),"Shift-Mod-z":()=>this.editor.commands.redo(),"Mod-y":()=>this.editor.commands.redo(),"Mod-я":()=>this.editor.commands.undo(),"Shift-Mod-я":()=>this.editor.commands.redo()}}}),NX=on.create({name:"starterKit",addExtensions(){var s,e,t,n;const i=[];return this.options.bold!==!1&&i.push(UK.configure(this.options.bold)),this.options.blockquote!==!1&&i.push(NK.configure(this.options.blockquote)),this.options.bulletList!==!1&&i.push(nD.configure(this.options.bulletList)),this.options.code!==!1&&i.push(jK.configure(this.options.code)),this.options.codeBlock!==!1&&i.push(qK.configure(this.options.codeBlock)),this.options.document!==!1&&i.push(KK.configure(this.options.document)),this.options.dropcursor!==!1&&i.push(_X.configure(this.options.dropcursor)),this.options.gapcursor!==!1&&i.push(SX.configure(this.options.gapcursor)),this.options.hardBreak!==!1&&i.push(QK.configure(this.options.hardBreak)),this.options.heading!==!1&&i.push(XK.configure(this.options.heading)),this.options.undoRedo!==!1&&i.push(DX.configure(this.options.undoRedo)),this.options.horizontalRule!==!1&&i.push(YK.configure(this.options.horizontalRule)),this.options.italic!==!1&&i.push(sQ.configure(this.options.italic)),this.options.listItem!==!1&&i.push(rD.configure(this.options.listItem)),this.options.listKeymap!==!1&&i.push(cD.configure((s=this.options)==null?void 0:s.listKeymap)),this.options.link!==!1&&i.push(MQ.configure((e=this.options)==null?void 0:e.link)),this.options.orderedList!==!1&&i.push(hD.configure(this.options.orderedList)),this.options.paragraph!==!1&&i.push(XQ.configure(this.options.paragraph)),this.options.strike!==!1&&i.push(ZQ.configure(this.options.strike)),this.options.text!==!1&&i.push(eX.configure(this.options.text)),this.options.underline!==!1&&i.push(tX.configure((t=this.options)==null?void 0:t.underline)),this.options.trailingNode!==!1&&i.push(OX.configure((n=this.options)==null?void 0:n.trailingNode)),i}}),BX=NX;function FX(s){var e;const{char:t,allowSpaces:n,allowToIncludeChar:i,allowedPrefixes:r,startOfLine:o,$position:a}=s,c=n&&!i,l=mK(t),u=new RegExp(`\\s${l}$`),h=o?"^":"",d=i?"":l,p=c?new RegExp(`${h}${l}.*?(?=\\s${d}|$)`,"gm"):new RegExp(`${h}(?:^)?${l}[^\\s${d}]*`,"gm"),m=((e=a.nodeBefore)==null?void 0:e.isText)&&a.nodeBefore.text;if(!m)return null;const v=a.pos-m.length,g=Array.from(m.matchAll(p)).pop();if(!g||g.input===void 0||g.index===void 0)return null;const y=g.input.slice(Math.max(0,g.index-1),g.index),b=new RegExp(`^[${r==null?void 0:r.join("")}\0]?$`).test(y);if(r!==null&&!b)return null;const _=v+g.index;let w=_+g[0].length;return c&&u.test(m.slice(w-1,w+1))&&(g[0]+=" ",w+=1),_<a.pos&&w>=a.pos?{range:{from:_,to:w},query:g[0].slice(t.length),text:g[0]}:null}function $X(s){return s.docChanged?s.steps.some(e=>{const t=e.slice;if(!(t!=null&&t.content))return!1;const n=t.content.textBetween(0,t.content.size,`
`);return/\s/.test(n)}):!1}var HX=new fn("suggestion");function UX({pluginKey:s=HX,editor:e,char:t="@",allowSpaces:n=!1,allowToIncludeChar:i=!1,allowedPrefixes:r=[" "],startOfLine:o=!1,decorationTag:a="span",decorationClass:c="suggestion",decorationContent:l="",decorationEmptyClass:u="is-empty",command:h=()=>null,items:d=()=>[],render:p=()=>({}),allow:m=()=>!0,findSuggestionMatch:v=FX,shouldShow:g,shouldResetDismissed:y}){let b;const _=p==null?void 0:p(),w=n&&!i,S=()=>{const M=e.state.selection.$anchor.pos,R=e.view.coordsAtPos(M),{top:P,right:L,bottom:z,left:Q}=R;try{return new DOMRect(Q,P,L-Q,z-P)}catch{return null}},C=(M,R)=>R?()=>{const P=s.getState(e.state),L=P==null?void 0:P.decorationId,z=M.dom.querySelector(`[data-decoration-id="${L}"]`);return(z==null?void 0:z.getBoundingClientRect())||null}:S,T=({match:M,dismissedRange:R,state:P,transaction:L})=>y!=null&&y({editor:e,state:P,range:R,match:M,transaction:L,allowSpaces:w})?!1:w?M.range.from===R.from:M.range.from===R.from&&!$X(L);function k(M,R){var P;try{const z=s.getState(M.state),Q=z!=null&&z.decorationId?M.dom.querySelector(`[data-decoration-id="${z.decorationId}"]`):null,W={editor:e,range:(z==null?void 0:z.range)||{from:0,to:0},query:(z==null?void 0:z.query)||null,text:(z==null?void 0:z.text)||null,items:[],command:V=>h({editor:e,range:(z==null?void 0:z.range)||{from:0,to:0},props:V}),decorationNode:Q,clientRect:C(M,Q)};(P=_==null?void 0:_.onExit)==null||P.call(_,W)}catch{}const L=M.state.tr.setMeta(R,{exit:!0});M.dispatch(L)}const A=new $s({key:s,view(){return{update:async(M,R)=>{var P,L,z,Q,W,V,N;const O=(P=this.key)==null?void 0:P.getState(R),H=(L=this.key)==null?void 0:L.getState(M.state),G=O.active&&H.active&&O.range.from!==H.range.from,ee=!O.active&&H.active,ie=O.active&&!H.active,ve=!ee&&!ie&&O.query!==H.query,le=ee||G&&ve,oe=ve||G,I=ie||G&&ve;if(!le&&!oe&&!I)return;const K=I&&!le?O:H,X=M.dom.querySelector(`[data-decoration-id="${K.decorationId}"]`);b={editor:e,range:K.range,query:K.query,text:K.text,items:[],command:J=>h({editor:e,range:K.range,props:J}),decorationNode:X,clientRect:C(M,X)},le&&((z=_==null?void 0:_.onBeforeStart)==null||z.call(_,b)),oe&&((Q=_==null?void 0:_.onBeforeUpdate)==null||Q.call(_,b)),(oe||le)&&(b.items=await d({editor:e,query:K.query})),I&&((W=_==null?void 0:_.onExit)==null||W.call(_,b)),oe&&((V=_==null?void 0:_.onUpdate)==null||V.call(_,b)),le&&((N=_==null?void 0:_.onStart)==null||N.call(_,b))},destroy:()=>{var M;b&&((M=_==null?void 0:_.onExit)==null||M.call(_,b))}}},state:{init(){return{active:!1,range:{from:0,to:0},query:null,text:null,composing:!1,dismissedRange:null}},apply(M,R,P,L){const{isEditable:z}=e,{composing:Q}=e.view,{selection:W}=M,{empty:V,from:N}=W,O={...R},H=M.getMeta(s);if(H&&H.exit)return O.active=!1,O.decorationId=null,O.range={from:0,to:0},O.query=null,O.text=null,O.dismissedRange=R.active?{...R.range}:R.dismissedRange,O;if(O.composing=Q,M.docChanged&&O.dismissedRange!==null&&(O.dismissedRange={from:M.mapping.map(O.dismissedRange.from),to:M.mapping.map(O.dismissedRange.to)}),z&&(V||e.view.composing)){(N<R.range.from||N>R.range.to)&&!Q&&!R.composing&&(O.active=!1);const G=v({char:t,allowSpaces:n,allowToIncludeChar:i,allowedPrefixes:r,startOfLine:o,$position:W.$from}),ee=`id_${Math.floor(Math.random()*4294967295)}`;G&&m({editor:e,state:L,range:G.range,isActive:R.active})&&(!g||g({editor:e,range:G.range,query:G.query,text:G.text,transaction:M}))?(O.dismissedRange!==null&&!T({match:G,dismissedRange:O.dismissedRange,state:L,transaction:M})&&(O.dismissedRange=null),O.dismissedRange===null?(O.active=!0,O.decorationId=R.decorationId?R.decorationId:ee,O.range=G.range,O.query=G.query,O.text=G.text):O.active=!1):(G||(O.dismissedRange=null),O.active=!1)}else O.active=!1;return O.active||(O.decorationId=null,O.range={from:0,to:0},O.query=null,O.text=null),O}},props:{handleKeyDown(M,R){var P,L;const{active:z,range:Q}=A.getState(M.state);if(!z)return!1;if(R.key==="Escape"||R.key==="Esc"){const V=A.getState(M.state);return(P=_==null?void 0:_.onKeyDown)==null||P.call(_,{view:M,event:R,range:V.range}),k(M,s),!0}return((L=_==null?void 0:_.onKeyDown)==null?void 0:L.call(_,{view:M,event:R,range:Q}))||!1},decorations(M){const{active:R,range:P,decorationId:L,query:z}=A.getState(M);if(!R)return null;const Q=!(z!=null&&z.length),W=[c];return Q&&W.push(u),Bs.create(M.doc,[Mi.inline(P.from,P.to,{nodeName:a,class:W.join(" "),"data-decoration-id":L,"data-decoration-content":l})])}}});return A}function WX({editor:s,overrideSuggestionOptions:e,extensionName:t,char:n="@"}){const i=new fn;return{editor:s,char:n,pluginKey:i,command:({editor:r,range:o,props:a})=>{var c,l,u;const h=r.view.state.selection.$to.nodeAfter;((c=h==null?void 0:h.text)==null?void 0:c.startsWith(" "))&&(o.to+=1),r.chain().focus().insertContentAt(o,[{type:t,attrs:{...a,mentionSuggestionChar:n}},{type:"text",text:" "}]).run(),(u=(l=r.view.dom.ownerDocument.defaultView)==null?void 0:l.getSelection())==null||u.collapseToEnd()},allow:({state:r,range:o})=>{const a=r.doc.resolve(o.from),c=r.schema.nodes[t];return!!a.parent.type.contentMatch.matchType(c)},...e}}function yD(s){return(s.options.suggestions.length?s.options.suggestions:[s.options.suggestion]).map(e=>WX({editor:s.editor,overrideSuggestionOptions:e,extensionName:s.name,char:e.char}))}function BI(s,e){const t=yD(s),n=t.find(i=>i.char===e);return n||(t.length?t[0]:null)}var zX=Sr.create({name:"mention",priority:101,addOptions(){return{HTMLAttributes:{},renderText({node:s,suggestion:e}){var t,n;return`${(t=e==null?void 0:e.char)!=null?t:"@"}${(n=s.attrs.label)!=null?n:s.attrs.id}`},deleteTriggerWithBackspace:!1,renderHTML({options:s,node:e,suggestion:t}){var n,i;return["span",Fs(this.HTMLAttributes,s.HTMLAttributes),`${(n=t==null?void 0:t.char)!=null?n:"@"}${(i=e.attrs.label)!=null?i:e.attrs.id}`]},suggestions:[],suggestion:{}}},group:"inline",inline:!0,selectable:!1,atom:!0,addAttributes(){return{id:{default:null,parseHTML:s=>s.getAttribute("data-id"),renderHTML:s=>s.id?{"data-id":s.id}:{}},label:{default:null,parseHTML:s=>s.getAttribute("data-label"),renderHTML:s=>s.label?{"data-label":s.label}:{}},mentionSuggestionChar:{default:"@",parseHTML:s=>s.getAttribute("data-mention-suggestion-char"),renderHTML:s=>({"data-mention-suggestion-char":s.mentionSuggestionChar})}}},parseHTML(){return[{tag:`span[data-type="${this.name}"]`}]},renderHTML({node:s,HTMLAttributes:e}){const t=BI(this,s.attrs.mentionSuggestionChar);if(this.options.renderLabel!==void 0)return console.warn("renderLabel is deprecated use renderText and renderHTML instead"),["span",Fs({"data-type":this.name},this.options.HTMLAttributes,e),this.options.renderLabel({options:this.options,node:s,suggestion:t})];const n={...this.options};n.HTMLAttributes=Fs({"data-type":this.name},this.options.HTMLAttributes,e);const i=this.options.renderHTML({options:n,node:s,suggestion:t});return typeof i=="string"?["span",Fs({"data-type":this.name},this.options.HTMLAttributes,e),i]:i},...xO({nodeName:"mention",name:"@",selfClosing:!0,allowedAttributes:["id","label",{name:"mentionSuggestionChar",skipIfDefault:"@"}],parseAttributes:s=>{const e={},t=/(\w+)=(?:"([^"]*)"|'([^']*)')/g;let n=t.exec(s);for(;n!==null;){const[,i,r,o]=n,a=r??o;e[i==="char"?"mentionSuggestionChar":i]=a,n=t.exec(s)}return e},serializeAttributes:s=>Object.entries(s).filter(([,e])=>e!=null).map(([e,t])=>`${e==="mentionSuggestionChar"?"char":e}="${t}"`).join(" ")}),renderText({node:s}){const e={options:this.options,node:s,suggestion:BI(this,s.attrs.mentionSuggestionChar)};return this.options.renderLabel!==void 0?(console.warn("renderLabel is deprecated use renderText and renderHTML instead"),this.options.renderLabel(e)):this.options.renderText(e)},addKeyboardShortcuts(){return{Backspace:()=>this.editor.commands.command(({tr:s,state:e})=>{let t=!1;const{selection:n}=e,{empty:i,anchor:r}=n;if(!i)return!1;let o=new yc,a=0;return e.doc.nodesBetween(r-1,r,(c,l)=>{if(c.type.name===this.name)return t=!0,o=c,a=l,!1}),t&&s.insertText(this.options.deleteTriggerWithBackspace?"":o.attrs.mentionSuggestionChar,a,a+o.nodeSize),t})}},addProseMirrorPlugins(){return yD(this).map(UX)}}),jX=zX,VX=RX;const GX=["aria-selected"],qX=["aria-selected","onMouseenter","onMousedown"],KX={class:"file-at-item__name"},QX={class:"file-at-item__description"},XX={key:1,class:"file-at-empty"},YX={key:2,class:"file-at-empty"},JX=at({__name:"FileAtMenu",props:{visible:{type:Boolean},items:{},activeIndex:{},loading:{type:Boolean},hostMode:{type:Boolean},menuStyle:{}},emits:["select","hover"],setup(s,{expose:e}){const t=s,n=pe(null),i=ye(()=>t.hostMode),r=ye(()=>t.items||[]),o=u=>i.value?u+1:u;Xe(()=>t.visible,()=>{t.visible&&ft(()=>{const u=n.value;u&&(u.scrollTop=0)})});const a=u=>{const h=n.value;if(!h)return;const d=31,p=u*d,m=p+d;p<h.scrollTop?h.scrollTop=p:m>h.scrollTop+h.clientHeight&&(h.scrollTop=m-h.clientHeight)};return e({focusActive:()=>{ft(()=>{a(t.activeIndex)})},setManualScroll:()=>{}}),(u,h)=>(F(),Wt(us,{name:"file-at-menu-motion"},{default:Vt(()=>[s.visible?(F(),$("div",{key:0,class:"file-at-menu-wrapper",role:"listbox","aria-label":"文件引用",style:Ke(s.menuStyle),onClick:h[2]||(h[2]=Ne(()=>{},["stop"]))},[E("div",{ref_key:"fileAtList",ref:n,class:"file-at-menu"},[s.hostMode?(F(),$("button",{key:0,type:"button",class:ke(["file-at-item file-at-item--picker",{"file-at-item--active":s.activeIndex===0}]),role:"option","aria-selected":s.activeIndex===0,onMouseenter:h[0]||(h[0]=d=>u.$emit("hover",0)),onMousedown:h[1]||(h[1]=Ne(d=>u.$emit("select",0),["prevent"]))},[...h[3]||(h[3]=[E("span",{class:"file-at-item__name"},"在文件管理器中选中",-1),E("span",{class:"file-at-item__description"},"选择本地文件",-1)])],42,GX)):ge("",!0),(F(!0),$(Ie,null,tt(r.value,(d,p)=>(F(),$("button",{key:d.path,type:"button",class:ke(["file-at-item",{"file-at-item--active":o(p)===s.activeIndex}]),role:"option","aria-selected":o(p)===s.activeIndex,onMouseenter:m=>u.$emit("hover",o(p)),onMousedown:Ne(m=>u.$emit("select",o(p)),["prevent"])},[E("span",KX,ae(d.name),1),E("span",QX,ae(d.path),1)],42,qX))),128)),!s.hostMode&&!r.value.length&&!s.loading?(F(),$("div",XX," 没有匹配的文件 ")):ge("",!0),s.loading?(F(),$("div",YX,"搜索中...")):ge("",!0)],512)],4)):ge("",!0)]),_:1}))}}),ZX=Qt(JX,[["__scopeId","data-v-a6111ba8"]]),eY={class:"rolling-number"},tY={class:"rolling-number__cell"},sY={class:"rolling-number__cell"},FI=38,nY=360,iY=at({__name:"RollingNumber",props:{value:{}},setup(s){const e=s,t=pe([]),n=new Map;let i=!1,r=0;const o=new Set,a=new Map;function c(h){const d=Math.max(0,Math.trunc(Number(h)||0)).toString(),p=d.length,m=new Map;for(let v=0;v<p;v++)m.set(p-1-v,Number(d[v]));return m}const l=ye(()=>t.value.map(h=>({place:h,state:n.get(h)})).filter(h=>!!h.state));function u(h){t.value=[...new Set(h)].sort((d,p)=>p-d)}return Xe(()=>e.value,async h=>{const d=c(h),p=++r;if(!i){i=!0,n.clear();for(const[w,S]of d)n.set(w,mw({top:S,bottom:S,offset:0,animate:!1,delay:0}));u(d.keys());return}const m=new Set([...n.keys(),...d.keys()]),v=Math.max(...m,0),g=[],y=[];for(const w of d.keys()){const S=a.get(w);S&&(window.clearTimeout(S),a.delete(w))}for(const w of m){const S=(v-w)*FI,C=d.get(w);if(C===void 0)continue;const T=n.get(w);if(!T){n.set(w,mw({top:C,bottom:C,offset:0,animate:!1,delay:S}));continue}T.delay=S;const k=T.top;if(k===C){T.bottom=C,T.offset=0,T.animate=!1;continue}k<C?(T.animate=!1,T.top=k,T.bottom=C,T.offset=0,g.push(T)):(T.animate=!1,T.top=C,T.bottom=k,T.offset=1,y.push(T))}u(d.keys());for(const w of[...n.keys()])if(!d.has(w)&&!a.has(w)){const S=window.setTimeout(()=>{a.delete(w),n.delete(w)},260);a.set(w,S)}await ft(),requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(p===r){for(const w of g)w.animate=!0,w.offset=1;for(const w of y)w.animate=!0,w.offset=0}})});const b=v*FI+nY+80,_=window.setTimeout(()=>{if(o.delete(_),p===r)for(const[w,S]of d){const C=n.get(w);C&&(C.animate=!1,C.top=S,C.bottom=S,C.offset=0)}},b);o.add(_)},{immediate:!0}),xn(()=>{o.forEach(h=>window.clearTimeout(h)),o.clear(),a.forEach(h=>window.clearTimeout(h)),a.clear()}),(h,d)=>(F(),$("span",eY,[Qe(Vv,{name:"rn-place",tag:"span",class:"rolling-number__track"},{default:Vt(()=>[(F(!0),$(Ie,null,tt(l.value,p=>(F(),$("span",{key:p.place,class:"rolling-number__digit"},[E("span",{class:ke(["rolling-number__strip",{"is-animating":p.state.animate}]),style:Ke({"--rn-offset":p.state.offset,transitionDelay:p.state.delay+"ms"})},[E("span",tY,ae(p.state.top),1),E("span",sY,ae(p.state.bottom),1)],6)]))),128))]),_:1})]))}}),$I=Qt(iY,[["__scopeId","data-v-492eb155"]]),rY={key:0,class:"sa-bg",d:"M 175.959,107.000 Q 180.000,100.000 175.959,93.000 L 144.041,37.718 Q 140.000,30.718 131.917,30.718 L 68.083,30.718 Q 60.000,30.718 55.959,37.718 L 24.041,93.000 Q 20.000,100.000 24.041,107.000 L 55.959,162.282 Q 60.000,169.282 68.083,169.282 L 131.917,169.282 Q 140.000,169.282 144.041,162.282 Z"},oY=["clip-path"],aY=["innerHTML"],lY=150,cY=210,HI="transform 0.55s cubic-bezier(0.22, 1, 0.36, 1)",UI="transform 0.22s cubic-bezier(0.65, 0, 0.35, 1)",uY=at({__name:"StatusAvatar",props:{mode:{default:"idle"},toolKeys:{default:()=>[]},tracking:{type:Boolean,default:!1},size:{default:30},hexBackground:{type:Boolean,default:!1}},emits:["poke"],setup(s,{emit:e}){const t=s,n=e,i=`sa-hex-clip-${Math.random().toString(36).slice(2,9)}`,r=pe(null),o=pe(null),a=pe(null),c=pe(null),l=pe(null),u=pe(!0),h=[{key:"search",motion:"wiggle",svg:'<path class="sa-inner" d="m21 21-4.34-4.34"/><circle class="sa-inner" cx="11" cy="11" r="8"/>'},{key:"webpage",motion:"bob",svg:'<circle class="sa-inner" cx="12" cy="12" r="10"/><path class="sa-inner" d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"/><line class="sa-inner" x1="2" x2="22" y1="12" y2="12"/>'},{key:"write",motion:"wiggle",svg:'<path class="sa-inner" d="M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"/><path class="sa-inner" d="m15 5 4 4"/>'},{key:"read",motion:"bob",svg:'<path class="sa-inner" d="M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20"/>'},{key:"save",motion:"bob",svg:'<path class="sa-inner" d="M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z"/><path class="sa-inner" d="M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7"/><path class="sa-inner" d="M7 3v4a1 1 0 0 0 1 1h7"/>'},{key:"camera",motion:"bob",svg:'<path class="sa-inner" d="M13.997 4a2 2 0 0 1 1.76 1.05l.486.9A2 2 0 0 0 18.003 7H20a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9a2 2 0 0 1 2-2h1.997a2 2 0 0 0 1.759-1.048l.489-.904A2 2 0 0 1 10.004 4z"/><circle class="sa-inner" cx="12" cy="13" r="3"/>'},{key:"monitor",motion:"bob",svg:'<rect class="sa-inner" width="20" height="14" x="2" y="3" rx="2"/><line class="sa-inner" x1="8" x2="16" y1="21" y2="21"/><line class="sa-inner" x1="12" x2="12" y1="17" y2="21"/>'},{key:"keyboard",motion:"bob",svg:'<path class="sa-inner" d="M10 8h.01M12 12h.01M14 8h.01M16 12h.01M18 8h.01M6 8h.01M7 16h10m-9-4h.01"/><rect class="sa-inner" width="20" height="16" x="2" y="4" rx="2"/>'},{key:"clipboard",motion:"bob",svg:'<rect class="sa-inner" width="8" height="4" x="8" y="2" rx="1" ry="1"/><path class="sa-inner" d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"/>'},{key:"command",motion:"bob",svg:'<path class="sa-inner" d="M12 19h8"/><path class="sa-inner" d="m4 17 6-6-6-6"/>'},{key:"brain",motion:"bob",svg:'<path class="sa-inner" d="M12 18V5"/><path class="sa-inner" d="M15 13a4.17 4.17 0 0 1-3-4 4.17 4.17 0 0 1-3 4"/><path class="sa-inner" d="M17.598 6.5A3 3 0 1 0 12 5a3 3 0 1 0-5.598 1.5"/><path class="sa-inner" d="M17.997 5.125a4 4 0 0 1 2.526 5.77"/><path class="sa-inner" d="M18 18a4 4 0 0 0 2-7.464"/><path class="sa-inner" d="M19.967 17.483A4 4 0 1 1 12 18a4 4 0 1 1-7.967-.517"/><path class="sa-inner" d="M6 18a4 4 0 0 1-2-7.464"/><path class="sa-inner" d="M6.003 5.125a4 4 0 0 0-2.526 5.77"/>'},{key:"notebook",motion:"bob",svg:'<path class="sa-inner" d="M2 6h4m-4 4h4m-4 4h4m-4 4h4"/><rect class="sa-inner" width="16" height="20" x="4" y="2" rx="2"/><path class="sa-inner" d="M16 2v20"/>'},{key:"note",motion:"bob",svg:'<path class="sa-inner" d="M21 9a2.4 2.4 0 0 0-.706-1.706l-3.588-3.588A2.4 2.4 0 0 0 15 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2z"/><path class="sa-inner" d="M15 3v5a1 1 0 0 0 1 1h5"/>'},{key:"check",motion:"bob",svg:'<path class="sa-inner" d="M20 6 9 17l-5-5"/>'},{key:"skill",motion:"bob",svg:'<path class="sa-inner" d="M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z"/><path class="sa-inner" d="M20 2v4"/><path class="sa-inner" d="M22 4h-4"/><circle class="sa-inner" cx="4" cy="20" r="2"/>'},{key:"persona",motion:"bob",svg:'<path class="sa-inner" d="M11.5 15H7a4 4 0 0 0-4 4v2m18.378-4.374a1 1 0 0 0-3.004-3.004l-4.01 4.012a2 2 0 0 0-.506.854l-.837 2.87a.5.5 0 0 0 .62.62l2.87-.837a2 2 0 0 0 .854-.506z"/><circle class="sa-inner" cx="10" cy="7" r="4"/>'},{key:"mcp",motion:"bob",raw:'<g transform="translate(100,100) scale(0.30) translate(-90,-90)"><path class="sa-inner" style="stroke-width:16.8" d="M18 84.8528L85.8822 16.9706C95.2548 7.59798 110.451 7.59798 119.823 16.9706C129.196 26.3431 129.196 41.5391 119.823 50.9117L68.5581 102.177"/><path class="sa-inner" style="stroke-width:16.8" d="M69.2652 101.47L119.823 50.9117C129.196 41.5391 144.392 41.5391 153.765 50.9117L154.118 51.2652C163.491 60.6378 163.491 75.8338 154.118 85.2063L92.7248 146.6C89.6006 149.724 89.6006 154.789 92.7248 157.913L105.331 170.52"/><path class="sa-inner" style="stroke-width:16.8" d="M102.853 33.9411L52.6482 84.1457C43.2756 93.5183 43.2756 108.714 52.6482 118.087C62.0208 127.459 77.2167 127.459 86.5893 118.087L136.794 67.8822"/></g>'},{key:"ask",motion:"bob",scale:3.7,svg:'<path class="sa-inner" style="stroke-width:1.6" d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"/><path class="sa-inner" style="stroke-width:1.6" d="M12 17h.01"/>'},{key:"sleep",motion:"special",raw:'<g class="sa-z z3"><text x="130" y="94" text-anchor="middle" font-size="34" font-weight="600">Z</text></g><g class="sa-z z2"><text x="100" y="109" text-anchor="middle" font-size="26" font-weight="600">Z</text></g><g class="sa-z z1"><text x="70" y="123" text-anchor="middle" font-size="18" font-weight="600">Z</text></g>'}];function d(xe){if(xe.raw)return xe.motion==="bob"?`<g class="sa-bob">${xe.raw}</g>`:xe.raw;const ce=`<g transform="translate(100, 100) scale(${xe.scale||2.75}) translate(-12, -12)">${xe.svg}</g>`;return`<g class="${xe.motion==="wiggle"?"sa-wiggle":"sa-bob"}">${ce}</g>`}const p={idle:"M 0,-11 Q 0,-5.5 0,0 Q 0,5.5 0,11 Q 0,5.5 0,0 Q 0,-5.5 0,-11",blink:"M 0,0 Q 0,0 0,0 Q 0,0 0,0 Q 0,0 0,0 Q 0,0 0,0",nervousLeft:"M -10,-12 Q -2,-6 6,0 Q -2,6 -10,12 Q -2,6 6,0 Q -2,-6 -10,-12",nervousRight:"M 10,-12 Q 2,-6 -6,0 Q 2,6 10,12 Q 2,6 -6,0 Q 2,-6 10,-12",work:"M 0,0 Q 8.5,0 17,0 Q 25.5,0 34,0 Q 25.5,0 17,0 Q 8.5,0 0,0"},m={x:84,y:96},v={x:116,y:96},g={x:82,y:96},y={x:118,y:96},b={x:117,y:100};let _="idle",w="idle";function S(xe,se,ce,de){const we=3*xe,Le=3*(ce-xe)-we,He=1-we-Le,yt=3*se,At=3*(de-se)-yt,Nt=1-yt-At,It=Jt=>((He*Jt+Le)*Jt+we)*Jt;return Jt=>{let $t=Jt;for(let As=0;As<8;As++){const ut=It($t)-Jt;if(Math.abs(ut)<1e-6)return((Nt*$t+At)*$t+yt)*$t;const Hs=(3*He*$t+2*Le)*$t+we;if(Math.abs(Hs)<1e-6)break;$t-=ut/Hs}return((Nt*$t+At)*$t+yt)*$t}}const C=S(.22,1,.36,1),T=S(.65,0,.35,1);function k(xe){return(xe.match(/[-\d.]+/g)||[]).map(Number)}function A(xe){return`M ${xe[0]},${xe[1]} Q ${xe[2]},${xe[3]} ${xe[4]},${xe[5]} Q ${xe[6]},${xe[7]} ${xe[8]},${xe[9]} Q ${xe[10]},${xe[11]} ${xe[12]},${xe[13]} Q ${xe[14]},${xe[15]} ${xe[16]},${xe[17]}`}const M=new Map;function R(xe,se,ce,de=550,we=C){if(!xe)return;xe.setAttribute("d",p[se]);const Le=k(p[se]),He=k(p[ce]),yt=performance.now(),At=M.get(xe);At&&cancelAnimationFrame(At);const Nt=It=>{const Jt=Math.min((It-yt)/de,1),$t=we(Jt),As=Le.map((ut,Hs)=>ut+(He[Hs]-ut)*$t);xe.setAttribute("d",A(As)),Jt<1?M.set(xe,requestAnimationFrame(Nt)):M.delete(xe)};M.set(xe,requestAnimationFrame(Nt))}function P(){a.value&&(a.value.style.transition=HI,a.value.style.transform=`translate(${b.x}px, ${b.y}px) rotate(${lY}deg)`),c.value&&(c.value.style.transition=HI,c.value.style.transform=`translate(${b.x}px, ${b.y}px) rotate(${cY}deg)`)}function L(xe=!0){a.value&&(xe||(a.value.style.transition="none"),a.value.style.transform=`translate(${m.x}px, ${m.y}px)`,xe||(a.value.offsetWidth,a.value.style.transition="")),c.value&&(xe||(c.value.style.transition="none"),c.value.style.transform=`translate(${v.x}px, ${v.y}px)`,xe||(c.value.offsetWidth,c.value.style.transition=""))}function z(){a.value&&(a.value.style.transition=UI,a.value.style.transform=`translate(${g.x}px, ${g.y}px)`),c.value&&(c.value.style.transition=UI,c.value.style.transform=`translate(${y.x}px, ${y.y}px)`)}let Q=0,W=0,V=0,N=0,O=null;function H(xe){Q=xe.clientX,W=xe.clientY}function G(){O&&cancelAnimationFrame(O),O=null,o.value&&(o.value.style.transform="translate(0px, 0px)")}function ee(){const xe=I.value||t.mode;if(!(t.tracking&&(xe==="idle"||xe==="nervous"))||!r.value){G();return}const se=r.value.getBoundingClientRect(),ce=se.left+se.width/2,de=se.top+se.height/2,we=Q-ce,Le=W-de,He=Math.sqrt(we*we+Le*Le),yt=Math.atan2(Le,we),At=Math.min(He/180,1),Nt=Math.cos(yt)*10*At,It=Math.sin(yt)*10*At;V+=(Nt-V)*.15,N+=(It-N)*.15,o.value&&(o.value.style.transform=`translate(${V}px, ${N}px)`),O=requestAnimationFrame(ee)}let ie=null,ve=null,le=null,oe=!1;const I=pe(null);function K(){ie&&clearTimeout(ie),ie=null}function X(){ve&&clearTimeout(ve),ve=null}function J(){le&&clearTimeout(le),le=null}function he(xe){return new Promise(se=>window.setTimeout(se,xe))}function be(){if(X(),t.mode!=="idle"||I.value)return;const xe=2800+Math.random()*3600;ve=window.setTimeout(async()=>{await Re(),be()},xe)}async function Re(){if(t.mode!=="idle"||I.value||oe)return;oe=!0;const xe=Math.random()<.5?1:2;for(let se=0;se<xe;se++){if(R(a.value,"idle","blink",150,T),R(c.value,"idle","blink",150,T),await he(120),t.mode!=="idle"||I.value){oe=!1;return}await he(45),R(a.value,"blink","idle",210,T),R(c.value,"blink","idle",210,T),await he(se===xe-1?200:250)}oe=!1}function rt(){t.mode==="idle"&&(I.value="nervous",X(),J(),G(),K(),l.value=null,u.value=!0,z(),R(a.value,_,"nervousLeft",220,T),R(c.value,w,"nervousRight",220,T),_="nervousLeft",w="nervousRight",t.tracking&&ee(),le=window.setTimeout(()=>{I.value==="nervous"&&(I.value=null)},500))}function st(){t.mode==="idle"&&(n("poke"),rt())}function et(xe,se=!0){const ce=u.value&&!l.value;if(u.value=!1,!se||l.value===xe){l.value=xe;return}if(ce){l.value=null,K(),ie=window.setTimeout(()=>{l.value=xe,ie=null},160);return}if(!l.value){l.value=xe;return}l.value=null,K(),ie=window.setTimeout(()=>{l.value=xe,ie=null},160)}function De(){t.mode!=="idle"&&I.value&&(I.value=null,J());const xe=I.value||t.mode;if(xe!=="idle"&&X(),xe==="tool"){G();const we=(t.toolKeys||[]).filter(Boolean);et(we.length?we[0]:"command");return}if(K(),xe==="think"){G(),et("think");return}if(xe==="nervous")return;const se=xe==="work"?"work":"idle",ce=!!l.value;l.value=null;const de=()=>{u.value=!0,R(a.value,_,se),R(c.value,w,se),se==="work"?P():L(),_=se,w=se};ce?ie=window.setTimeout(()=>{de(),ie=null},160):de(),se==="idle"&&t.tracking?(G(),ee(),be()):(G(),X())}return Xe(()=>[t.mode,(t.toolKeys||[]).join(""),t.tracking,I.value],()=>De()),Cn(()=>{L(!1),document.addEventListener("mousemove",H),De()}),xn(()=>{document.removeEventListener("mousemove",H),G(),K(),X(),J(),M.forEach(xe=>cancelAnimationFrame(xe)),M.clear()}),(xe,se)=>(F(),$("svg",{ref_key:"svgRef",ref:r,class:ke(["status-avatar",`status-avatar--${t.mode||"idle"}`]),style:Ke({width:s.size+"px",height:s.size+"px"}),viewBox:"0 0 200 200","aria-hidden":"true",onClick:st},[t.hexBackground?(F(),$("path",rY)):ge("",!0),se[3]||(se[3]=E("path",{class:"sa-frame",d:"M 175.959,107.000 Q 180.000,100.000 175.959,93.000 L 144.041,37.718 Q 140.000,30.718 131.917,30.718 L 68.083,30.718 Q 60.000,30.718 55.959,37.718 L 24.041,93.000 Q 20.000,100.000 24.041,107.000 L 55.959,162.282 Q 60.000,169.282 68.083,169.282 L 131.917,169.282 Q 140.000,169.282 144.041,162.282 Z"},null,-1)),E("defs",null,[E("clipPath",{id:i},[...se[0]||(se[0]=[E("path",{d:"M 180,100 L 140,30.718 L 60,30.718 L 20,100 L 60,169.282 L 140,169.282 Z"},null,-1)])])]),E("g",{class:"sa-face",ref_key:"faceRef",ref:o},[E("g",{class:ke(["sa-fc sa-shared",{hidden:!u.value}])},[E("path",{class:"sa-eye",ref_key:"eyeLeftRef",ref:a,d:"M 0,-11 Q 0,-5.5 0,0 Q 0,5.5 0,11 Q 0,5.5 0,0 Q 0,-5.5 0,-11",transform:"translate(84, 96)"},null,512),E("path",{class:"sa-eye",ref_key:"eyeRightRef",ref:c,d:"M 0,-11 Q 0,-5.5 0,0 Q 0,5.5 0,11 Q 0,5.5 0,0 Q 0,-5.5 0,-11",transform:"translate(116, 96)"},null,512)],2),E("g",{class:ke(["sa-fc sa-icon",{active:l.value==="think"}])},[...se[1]||(se[1]=[E("circle",{class:"sa-think-dot",cx:"80",cy:"100",r:"7"},null,-1),E("circle",{class:"sa-think-dot",cx:"100",cy:"100",r:"7"},null,-1),E("circle",{class:"sa-think-dot",cx:"120",cy:"100",r:"7"},null,-1)])],2),E("g",{class:ke(["sa-fc sa-icon",{active:l.value==="subagent"}]),"clip-path":`url(#${i})`},[...se[2]||(se[2]=[mi('<g class="sa-sub-scene" data-v-05190602><line class="sa-sub-ray" x1="180" y1="100" x2="140" y2="100" data-v-05190602></line><line class="sa-sub-ray" x1="140" y1="30.718" x2="120" y2="65.359" data-v-05190602></line><line class="sa-sub-ray" x1="60" y1="30.718" x2="80" y2="65.359" data-v-05190602></line><line class="sa-sub-ray" x1="20" y1="100" x2="60" y2="100" data-v-05190602></line><line class="sa-sub-ray" x1="60" y1="169.282" x2="80" y2="134.641" data-v-05190602></line><line class="sa-sub-ray" x1="140" y1="169.282" x2="120" y2="134.641" data-v-05190602></line><path class="sa-sub-hex" d="M 137.9795,103.5 Q 140,100 137.9795,96.5 L 122.0205,68.859 Q 120,65.359 115.9585,65.359 L 84.0415,65.359 Q 80,65.359 77.9795,68.859 L 62.0205,96.5 Q 60,100 62.0205,103.5 L 77.9795,131.141 Q 80,134.641 84.0415,134.641 L 115.9585,134.641 Q 120,134.641 122.0205,131.141 Z" data-v-05190602></path><g class="sa-sub-eyes" data-v-05190602><line class="sa-sub-eye" x1="0" y1="0" x2="11" y2="0" style="transform:translate(92px, 92px) rotate(90deg);" data-v-05190602></line><line class="sa-sub-eye" x1="0" y1="0" x2="11" y2="0" style="transform:translate(108px, 92px) rotate(90deg);" data-v-05190602></line></g></g>',1)])],10,oY),(F(),$(Ie,null,tt(h,ce=>E("g",{key:ce.key,class:ke(["sa-fc sa-icon",{active:l.value===ce.key}]),innerHTML:d(ce)},null,10,aY)),64))],512)],6))}}),bD=Qt(uY,[["__scopeId","data-v-05190602"]]),hY=["data-runtime-queue-id"],dY={class:"runtime-queue-item__text"},fY=["onClick"],pY=["onClick"],gY=["aria-label"],mY=["aria-selected","disabled","onMousedown"],vY={class:"skill-slash-item__name"},yY={class:"skill-slash-item__description"},bY={key:0,class:"skill-slash-empty"},_Y={key:0,class:"floating-project-status__left"},SY={class:"floating-project-status__menu-wrap"},wY={class:"floating-project-status__menu-wrap"},kY={class:"floating-project-status__right"},CY={key:0,class:"floating-project-status__notice"},TY={key:1,class:"floating-project-status__notice"},AY={class:"floating-project-status__add"},EY={class:"floating-project-status__del"},MY={class:"input-stack"},xY={key:0,class:"image-inline-row"},IY=["onClick"],RY=["src","alt"],LY=["onClick"],PY={key:1,class:"image-inline-row video-inline-row"},OY=["src","alt"],DY=["onClick"],NY={class:"input-row"},BY={class:"stadium-input-rich"},FY={class:"input-actions"},$Y={class:"input-actions-left"},HY=["disabled"],UY=["disabled","aria-expanded"],WY=["onClick"],zY={class:"agent-type-switcher__menu-label"},jY={class:"agent-type-switcher__menu-desc"},VY=["disabled","aria-expanded","title"],GY=["onClick"],qY={class:"agent-type-switcher__menu-label"},KY={class:"agent-type-switcher__menu-desc"},QY={class:"input-actions-right"},XY=["disabled","title"],YY={key:0,class:"mic-icon",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",width:"20",height:"20",fill:"none",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round","stroke-linejoin":"round"},JY={key:1,class:"voice-wave"},ZY=["disabled"],eJ={key:0,class:"stop-icon"},tJ={key:1,class:"send-icon"},sJ=["disabled"],nJ={class:"permission-switcher__block"},iJ=["disabled","title"],rJ={key:0,class:"permission-switcher__lock",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",width:"12",height:"12",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true"},oJ={class:"permission-switcher__group-title"},aJ={key:0,class:"permission-switcher__group-lock"},lJ=["disabled","onClick"],cJ={class:"permission-switcher__item-label"},uJ={class:"permission-switcher__item-desc"},hJ={class:"permission-switcher__group-title"},dJ={key:0,class:"permission-switcher__group-lock"},fJ={key:1,class:"permission-switcher__group-lock"},pJ=["disabled","onClick"],gJ={class:"permission-switcher__item-desc"},mJ=["disabled","onClick"],vJ={class:"permission-switcher__item-desc"},yJ=["disabled"],bJ={class:"context-usage-switcher__tooltip"},NC=300,_J="cubic-bezier(0.25, 0.8, 0.25, 1)",SJ=at({name:"InputComposer",__name:"InputComposer",props:{inputMessage:{},inputIsMultiline:{type:Boolean},inputIsFocused:{type:Boolean},isConnected:{type:Boolean},streamingMessage:{type:Boolean},inputLocked:{type:Boolean},uploading:{type:Boolean},thinkingMode:{type:Boolean},runMode:{},quickMenuOpen:{type:Boolean},toolMenuOpen:{type:Boolean},modeMenuOpen:{type:Boolean},modelMenuOpen:{type:Boolean},toolSettings:{},toolSettingsLoading:{type:Boolean},settingsOpen:{type:Boolean},compressing:{type:Boolean},currentConversationId:{},iconStyle:{type:Function},toolCategoryIcon:{type:Function},modelOptions:{},currentModelKey:{},selectedImages:{},selectedFiles:{},selectedVideos:{},mediaUploading:{type:Boolean},blockUpload:{type:Boolean},blockToolToggle:{type:Boolean},blockRealtimeTerminal:{type:Boolean},blockFocusPanel:{type:Boolean},blockTokenPanel:{type:Boolean},blockCompressConversation:{type:Boolean},blockConversationReview:{type:Boolean},currentPermissionMode:{},permissionMenuOpen:{type:Boolean},permissionOptions:{},executionModeEnabled:{type:Boolean},currentExecutionMode:{},executionModeOptions:{},networkPermissionEnabled:{type:Boolean},currentNetworkPermission:{},networkPermissionOptions:{},currentContextTokens:{},versioningEnabled:{type:Boolean},runtimeQueuedMessages:{},projectGitSummary:{},userQuestionMinimized:{type:Boolean},pendingUserQuestionCount:{},goalModeArmed:{type:Boolean},goalRunning:{type:Boolean},goalProgress:{},currentConversationType:{},newConversationType:{},agentTypeMenuOpen:{type:Boolean},currentWorkMode:{},workModeMenuOpen:{type:Boolean},workModeOptions:{},hostWorkspaces:{},currentHostWorkspaceId:{},hostWorkspaceSwitching:{type:Boolean},workspaceKind:{},mainChatIdle:{type:Boolean},activeSubAgentCount:{},hasPendingRuntimeGuidance:{type:Boolean},terminalCount:{},hostMode:{type:Boolean},avatarStatus:{}},emits:["update:input-message","input-change","input-focus","input-blur","toggle-quick-menu","send-message","send-or-stop","quick-upload","pick-images","pick-video","toggle-tool-menu","toggle-mode-menu","toggle-model-menu","select-run-mode","select-model","toggle-settings","update-tool-category","realtime-terminal","toggle-focus-panel","toggle-token-panel","compress-conversation","toggle-approval-panel","file-selected","paste-files","remove-image","remove-video","remove-file","open-review","open-path-authorization","toggle-permission-menu","change-permission-mode","change-execution-mode","change-network-permission","open-versioning-dialog","guide-runtime-message","delete-runtime-message","composer-height-change","restore-user-question","toggle-goal-mode","open-goal-dialog","workflow-activated","open-git-changes-panel","toggle-agent-type-menu","select-new-conversation-type","toggle-work-mode-menu","change-work-mode","new-conversation","switch-host-workspace","fetch-host-workspaces","stop-all-sub-agents"],setup(s,{expose:e,emit:t}){const n=t,i=s,r=q0(),o=qs(),a=pe(null),c=pe(null),l=pe(null),u=pe(null),h=pe(null),d=pe(0),p=pe([]),m=pe([]),v=pe(!1),g=pe(!1),y=pe(!1),b=pe(""),_=pe(0),w=pe(null),S=pe("root"),C=pe(0),T=pe(!1),k=pe(4),A=pe(!1),M=pe(null),R=pe(!1),P=um(),L=pe([]),z=pe(!1),Q=pe(!1),W=pe(!1);let V=null,N=!1,O=null,H=0;const G=pe(null),ee=pe(!1),ie=pe(null),ve=pe(0),le=pe([]),oe=pe(!1),I=pe({}),K=pe(!1);let X=null;const J=pe("");let he=null;const be=["不要!","停下来!","别戳啦!","哎呀!","你戳到我了!","轻一点嘛!","我不是按钮!","不许乱点!","呜……别戳我了……","六边形也是会痛的!","再戳我要变形了!","我会紧张的……","正在假装镇定……","Token 掉了一地!","上下文被你戳乱了!","防戳模式启动失败","系统提示AI 被戳了一下","警告:检测到手欠行为","我记住你了!","戳回去!"],Re=ye(()=>{var U;if(A.value)return{display:"none"};const j=_.value===0&&((U=w.value)==null?void 0:U.scrollTop)===0;return{top:`${k.value}px`,...j?{borderTopLeftRadius:"calc(var(--skill-slash-radius) - var(--skill-slash-gap))",borderTopRightRadius:"calc(var(--skill-slash-radius) - var(--skill-slash-gap))"}:{}}}),rt=(j,U)=>{const Y=V!==null;Y&&cancelAnimationFrame(V),N=!0,O=U;const Te=j.scrollTop,Me=k.value,Ve=U-Te,Ye=4+_.value*31-U-Me,qe=Y?60:180,Et=performance.now(),Lt=ys=>{const xr=Math.max(0,ys-Et),ti=Math.min(xr/qe,1),y_=1-Math.pow(1-ti,3);j.scrollTop=Te+Ve*y_,k.value=Me+Ye*y_,ti<1?V=requestAnimationFrame(Lt):(V=null,N=!1,H=performance.now())};V=requestAnimationFrame(Lt)},st=()=>{if(N||V!==null)return;const j=w.value;if(!j)return;const U=performance.now();O!==null&&U-H<150&&Math.abs(j.scrollTop-O)<1||(A.value=!0)};let et=null,De=!1;const xe=j=>{if(!j)return"";const U=j.split(/[/\\]/);return U[U.length-1]||j},se=j=>{const U=ce(j);U&&Vs().openImagePreview({url:U,name:xe(j)})},ce=j=>j?`/api/gui/files/download?path=${encodeURIComponent(j)}`:"",de=(j,U)=>{r.setInputLineCount(j),r.setInputMultiline(U)},we=ye(()=>(Array.isArray(i.runtimeQueuedMessages)?i.runtimeQueuedMessages:[]).filter(U=>U&&U.id&&U.text).map(U=>({...U,text:String(U.text||"").replace(/[\r\n\u2028\u2029]+/g," ")}))),Le=ye(()=>{var Me;if(((Me=o==null?void 0:o.form)==null?void 0:Me.show_git_status_bar)===!1)return null;const j=i.projectGitSummary;if(!(j!=null&&j.has_git))return null;const U=String(j.project_name||"").trim(),Y=String(j.branch||"").trim();return!U||!Y?null:{projectName:U,projectPath:String(j.project_path||"").trim(),branch:Y,additions:Math.max(0,Number(j.additions||0)),deletions:Math.max(0,Number(j.deletions||0))}}),He=ye(()=>ya.value||ee.value||i.quickMenuOpen||we.value.length>0||i.hasPendingRuntimeGuidance?!1:!!Le.value||!!i.goalRunning||!!i.goalModeArmed||Number(i.pendingUserQuestionCount||0)>0||Number(i.activeSubAgentCount||0)>0),yt=ye(()=>ya.value||ee.value||i.quickMenuOpen||we.value.length>0||i.hasPendingRuntimeGuidance?!1:!!i.avatarStatus),At=ye(()=>i.avatarStatus&&(i.avatarStatus.mode==="tool"||i.avatarStatus.mode==="think")&&i.avatarStatus.text||""),Nt=ye(()=>{var U;const j=i.avatarStatus;return j?j.mode==="tool"?`avatar-tool-${((U=j.toolKeys)==null?void 0:U[0])||""}`:`avatar-${j.mode}`:"avatar-none"}),It=pe(null),Jt=()=>{It.value=null},$t=j=>{It.value=It.value===j?null:j},As=async j=>{var Y;const U=String(j||"").trim();!U||typeof navigator>"u"||!((Y=navigator.clipboard)!=null&&Y.writeText)||(await navigator.clipboard.writeText(U),Jt())},ut=()=>{var j;As(((j=Le.value)==null?void 0:j.projectPath)||"")},Hs=()=>{var j;As(((j=Le.value)==null?void 0:j.branch)||"")},hl=async()=>{try{await fetch("/api/project/open-in-file-manager",{method:"POST"})}catch(j){console.warn("打开项目文件管理器失败:",j)}finally{Jt()}},In=()=>{const j=ts.value;if(!j)return null;const{state:U}=j,{$from:Y}=U.selection;Y.start();const Te=Y.parent.textBetween(0,Y.parentOffset,`
`,`
`),Me=/(^|[ \n])(\/{1,2})([^\s/]*)$/.exec(Te);if(!Me)return null;const Ve=Me[2]||"/",$e=Me[3]||"",Ye=Y.pos-$e.length-Ve.length,qe=Y.pos;return{start:Ye,end:qe,query:$e,doubleSlash:Ve.length===2}},Uo=()=>{const j=ts.value;if(!j)return null;const{state:U}=j,{$from:Y}=U.selection,Te=Y.parent.textBetween(0,Y.parentOffset,`
`,`
`),Me=/(^|[ \n])@([^\s@]*)$/.exec(Te);if(!Me)return null;const Ve=Me[2]||"",$e=Y.pos-Ve.length-1,Ye=Y.pos;return{start:$e,end:Ye,query:Ve,charStart:$e}},nr=()=>{V!==null&&(cancelAnimationFrame(V),V=null),N=!1,O=null,H=0,y.value=!1,b.value="",_.value=0,S.value="root",C.value=0,k.value=4,A.value=!1,M.value=null,R.value=!1},Qs=()=>{ee.value=!1,ie.value=null,ve.value=0,le.value=[],oe.value=!1,I.value={},X!==null&&(window.clearTimeout(X),X=null)},Yn=()=>{he!==null&&(window.clearTimeout(he),he=null),J.value=""},Rn=()=>{if(!i.avatarStatus||i.avatarStatus.mode!=="idle")return;const j=be;J.value=j[Math.floor(Math.random()*j.length)]||"不要!",he!==null&&window.clearTimeout(he),he=window.setTimeout(()=>{J.value="",he=null},1800)},ir=j=>{ft(()=>{const U=ts.value;if(U)try{const Y=U.view.coordsAtPos(j),Te=window.innerWidth,Me=window.innerHeight,Ve=280,$e=250,Ye=4;let qe=Y.right,Et=Y.top-$e;qe+Ve>Te-Ye&&(qe=Math.max(Ye,Te-Ve-Ye)),Et<Ye&&(Et=Y.bottom),Et+$e>Me-Ye&&(Et=Math.max(Ye,Me-$e-Ye)),I.value={left:`${qe}px`,top:`${Et}px`,width:`${Ve}px`,maxHeight:`${$e}px`}}catch{I.value={}}})},Wo=j=>{var Y;if(!j)return!1;const U=((Y=j.split(".").pop())==null?void 0:Y.toLowerCase())||"";return["jpg","jpeg","png","gif","webp","bmp","ico"].includes(U)},Ln=async j=>{var U;oe.value=!0;try{const Y=`/api/project/files/search?q=${encodeURIComponent(j)}&limit=50`,Te=await fetch(Y),Me=await Te.json().catch(()=>({}));if(!Te.ok||!(Me!=null&&Me.success)){le.value=[];return}le.value=Array.isArray((U=Me==null?void 0:Me.data)==null?void 0:U.items)?Me.data.items:[]}catch(Y){console.warn("[FileAt] 搜索文件失败:",Y),le.value=[]}finally{oe.value=!1}},ma=j=>{X!==null&&window.clearTimeout(X),X=window.setTimeout(()=>{Ln(j)},120)},zo=()=>{const j=Uo();if(!j||!i.isConnected||i.inputLocked){Qs();return}Jt();const U=ie.value!==j.query;ee.value=!0,(U||le.value.length===0)&&(ve.value=0,ie.value=j.query,ma(j.query)),ir(j.end)},io=j=>{const U=Uo(),Y=ts.value;if(!U||!Y)return;const{state:Te,view:Me,schema:Ve}=Y,$e=Ve.nodes.mention;if(!$e)return;const Ye=$e.create({id:`file://${j.path}`,label:j.name});let qe=Te.tr.delete(U.start,U.end);qe=qe.insert(U.start,Ye);const Et=U.start+Ye.nodeSize;qe=qe.insertText(" ",Et),qe=qe.setSelection(_t.near(qe.doc.resolve(Et+1))),Me.dispatch(qe),Me.focus(),Qs(),ft(()=>{Ar()})},dl=()=>{var j;Qs(),i.hostMode&&(K.value=!0,(j=h.value)==null||j.click())},Jn=j=>{const U=!!i.hostMode;if(U&&j===0){dl();return}const Y=U?j-1:j,Te=le.value[Y];if(Te){if(Te.type==="file"&&Wo(Te.path)){Qs(),n("pick-images");return}io(Te)}},jo=j=>{var Te,Me,Ve,$e;if(!ee.value)return!1;const Y=(!!i.hostMode?1:0)+le.value.length;return Y<=0?!1:j.key==="ArrowDown"?(j.preventDefault(),(Te=G.value)==null||Te.setManualScroll(!1),ve.value=(ve.value+1)%Y,(Me=G.value)==null||Me.focusActive(),!0):j.key==="ArrowUp"?(j.preventDefault(),(Ve=G.value)==null||Ve.setManualScroll(!1),ve.value=(ve.value-1+Y)%Y,($e=G.value)==null||$e.focusActive(),!0):j.key==="Enter"?(j.preventDefault(),Jn(ve.value),!0):j.key==="Escape"?(j.preventDefault(),Qs(),!0):!1},va=()=>{const j=In(),U=ts.value;if(!j||!U)return;const{state:Y,view:Te}=U;let Me=Y.tr.delete(j.start,j.end);Me=Me.setSelection(_t.near(Me.doc.resolve(Math.max(0,j.start)))),Te.dispatch(Me),Te.focus(),ft(()=>{Ar()})},fe=()=>{ft(()=>{const j=w.value;if(!j)return;const U=getComputedStyle(j),Y=parseFloat(U.getPropertyValue("--skill-slash-row-height")),Te=parseFloat(U.getPropertyValue("--skill-slash-gap")),Me=(Number.isFinite(Y)?Y:38)+(Number.isFinite(Te)?Te:5),Ve=Math.max(1,Math.floor(j.clientHeight/Me)||5),$e=Math.floor(Ve/2),Ye=Math.max(0,j.scrollHeight-j.clientHeight),qe=Math.max(0,Math.min(Ye,(_.value-$e)*Me));rt(j,qe)})},me=ye(()=>{const j=b.value.trim().toLowerCase(),U=Array.isArray(p.value)?p.value:[];return(j?U.filter(Te=>String(Te.name||"").toLowerCase().includes(j)):U).slice(0,100)}),Ce=ye(()=>{var U;const j=(U=i.modelOptions)==null?void 0:U.find(Y=>Y.key===i.currentModelKey);return!!(j!=null&&j.supportsImage)}),dt=ye(()=>{var U;const j=(U=i.modelOptions)==null?void 0:U.find(Y=>Y.key===i.currentModelKey);return!!(j!=null&&j.supportsVideo)}),qt=async j=>{o.applyTheme(j),o.updateField({key:"theme",value:j});try{const U=await fetch("/api/personalization",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({theme:j})}),Y=await U.json().catch(()=>({}));(!U.ok||!Y.success)&&console.warn("保存主题到后端失败:",Y==null?void 0:Y.error)}catch(U){console.warn("保存主题到后端失败:",U)}},Ss=j=>{va(),nr(),j()},Kt=ye(()=>{var Y;const j=[{id:"new",label:"新建对话",description:"开始一个新的对话new / clear",disabled:!i.isConnected,action:()=>n("new-conversation")},{id:"upload",label:"上传文件",description:i.uploading?"上传中...":"选择本地文件上传",disabled:!i.isConnected||i.uploading||i.blockUpload,action:()=>n("quick-upload")},{id:"image",label:"发送图片",description:Ce.value?"选择图片并附加到消息":"当前模型不支持图片",disabled:!i.isConnected||i.streamingMessage||!Ce.value,action:()=>n("pick-images")},{id:"video",label:"发送视频",description:dt.value?"选择视频并附加到消息":"当前模型不支持视频",disabled:!i.isConnected||i.streamingMessage||!dt.value,action:()=>n("pick-video")},{id:"compress",label:"压缩对话",description:i.compressing?"压缩中...":"手动压缩当前对话上下文",disabled:!i.isConnected||i.compressing||i.streamingMessage||i.blockCompressConversation,action:()=>n("compress-conversation")},{id:"skills",label:"选择 AgentSkill",description:"插入一个 AgentSkill 引用(// 快捷直达)",mode:"skills"},{id:"workflows",label:"工作流",description:P.isActive?`进行中:${P.snapshot.name} · 查看或退出`:"激活一个工作流,让智能体按流程推进",disabled:!i.isConnected,mode:"workflows"},{id:"conversation-type",label:"对话类型",description:"agent / multi-agent · 智能体 / 多智能体(仅新对话可切换)",disabled:!i.isConnected,mode:"conversation-type"},{id:"work-mode",label:"切换工作模式",description:"plan / ask / execute · 计划 / 询问 / 执行",disabled:!i.isConnected||i.streamingMessage,mode:"work-mode"},{id:"theme",label:"切换主题",description:"经典 / 明亮 / 夜间",mode:"theme"},{id:"review",label:"对话回顾",description:"打开当前对话回顾",disabled:!i.isConnected||i.streamingMessage||i.blockConversationReview,action:()=>n("open-review")},{id:"tokens",label:"用量统计",description:"打开上下文与 token 用量面板",disabled:!i.currentConversationId||i.blockTokenPanel,action:()=>n("toggle-token-panel",!0)},{id:"goal",label:"目标模式",description:i.goalRunning?"目标模式运行中":i.goalModeArmed?"目标模式已就绪":"切换目标模式",disabled:!i.isConnected,action:()=>n("toggle-goal-mode")},{id:"personalization",label:"个人设置",description:"打开个人空间设置",action:()=>{o.openDrawer()}},{id:"terminal",label:"实时终端",description:"打开实时终端面板",disabled:!i.isConnected||i.blockRealtimeTerminal,action:()=>n("realtime-terminal")},{id:"model",label:"切换模型",description:"选择对话使用的模型",disabled:!i.isConnected||i.streamingMessage,mode:"model"},{id:"run-mode",label:"思考模式",description:"切换 fast / thinking",disabled:!i.isConnected||i.streamingMessage,mode:"run-mode"},{id:"permission",label:"权限模式",description:"切换 readonly / approval / auto / unrestricted",disabled:!i.isConnected||i.streamingMessage,mode:"permission"},{id:"network",label:"网络权限",description:i.networkPermissionEnabled?"restricted / full · 受限 / 完整":"当前环境不支持网络权限切换",disabled:!i.isConnected||i.streamingMessage||!i.networkPermissionEnabled,mode:"network"},...i.executionModeEnabled?[{id:"execution",label:"执行环境",description:"切换 sandbox / direct",disabled:!i.isConnected||i.streamingMessage,mode:"execution"}]:[],...i.workspaceKind?[{id:"workspace",label:i.workspaceKind==="project"?"切换项目":"切换工作区",description:"workspace / project · 工作区 / 项目",disabled:!i.isConnected||i.streamingMessage,mode:"workspace"}]:[],{id:"versioning",label:"版本控制",description:i.versioningEnabled?"当前:开启":"当前:关闭",disabled:!i.isConnected||i.streamingMessage,action:()=>n("open-versioning-dialog")},{id:"git-bar",label:"Git 状态栏",description:((Y=o==null?void 0:o.form)==null?void 0:Y.show_git_status_bar)!==!1?"当前:显示":"当前:隐藏",action:()=>{var Ve;const Me=!(((Ve=o==null?void 0:o.form)==null?void 0:Ve.show_git_status_bar)!==!1);o!=null&&o.form&&(o.form.show_git_status_bar=Me),fetch("/api/personalization",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({show_git_status_bar:Me})}).catch(()=>{})}},{id:"path-auth",label:"路径授权",description:"查看和管理路径授权",disabled:!i.isConnected,action:()=>n("open-path-authorization")},{id:"approval",label:"审批面板",description:"查看审批记录",disabled:!i.isConnected,action:()=>n("toggle-approval-panel")}],U=b.value.trim().toLowerCase();return U?j.filter(Te=>`${Te.label} ${Te.description} ${Te.id}`.toLowerCase().includes(U)):j}),Es=ye(()=>[{id:"theme-classic",label:"经典",description:"米色质感,柔和高对比",theme:"classic"},{id:"theme-light",label:"明亮",description:"纯白底色 + 优雅灰,简洁清爽",theme:"light"},{id:"theme-dark",label:"夜间",description:"深灰 + 黑,低亮度显示",theme:"dark"}].map(U=>({...U,action:()=>{qt(U.theme)}}))),ht=ye(()=>{const j=i.permissionOptions||[],U=String(i.currentPermissionMode||""),Y=i.currentWorkMode==="plan";return j.map(Te=>({id:`perm:${Te.value}`,label:Te.label,description:Y?"计划模式下权限锁定为只读":`${Te.value===U?"当前 · ":""}${Te.description||""}`,disabled:Y,action:()=>n("change-permission-mode",Te.value)}))}),pn=ye(()=>{const j=i.executionModeOptions||[],U=String(i.currentExecutionMode||""),Y=i.currentWorkMode==="plan";return j.map(Te=>({id:`exec:${Te.value}`,label:Te.label,description:Y?"计划模式下执行环境锁定为沙箱":`${Te.value===U?"当前 · ":""}${Te.description||""}`,disabled:Y,action:()=>n("change-execution-mode",Te.value)}))}),Vo=ye(()=>{const j=Array.isArray(i.modelOptions)?i.modelOptions:[],U=String(i.currentModelKey||"");return j.map(Y=>({id:`model:${Y.key}`,label:Y.label,description:`${Y.key===U?"当前 · ":""}${Y.description||""}`,disabled:!!Y.disabled,action:()=>n("select-model",Y.key)}))}),Ff=ye(()=>{const j=[{value:"fast",label:"快速"},{value:"thinking",label:"思考"}],U=String(i.runMode||"");return j.map(Y=>({id:`runmode:${Y.value}`,label:Y.label,description:Y.value===U?"当前":"",action:()=>n("select-run-mode",Y.value)}))}),fl=ye(()=>{const j=i.networkPermissionOptions||[],U=String(i.currentNetworkPermission||"");return j.map(Y=>({id:`network:${Y.value}`,label:Y.label,description:`${Y.value===U?"当前 · ":""}${Y.description||""}`,action:()=>n("change-network-permission",Y.value)}))}),Di=ye(()=>{const j=i.workModeOptions||[],U=String(i.currentWorkMode||"");return j.map(Y=>({id:`workmode:${Y.value}`,label:Y.label,description:`${Y.value===U?"当前 · ":""}${Y.description||""}`,action:()=>n("change-work-mode",Y.value)}))}),Tn=ye(()=>{const j=Array.isArray(i.hostWorkspaces)?i.hostWorkspaces:[],U=String(i.currentHostWorkspaceId||""),Y=!!i.hostWorkspaceSwitching;return j.map(Te=>({id:`workspace:${Te.workspace_id}`,label:Te.label,description:`${Te.workspace_id===U?"当前 · ":""}${Te.path||""}`,disabled:Y||Te.workspace_id===U,action:()=>n("switch-host-workspace",Te.workspace_id)}))}),wr=ye(()=>{const j=te.value,U=String(i.newConversationType||"agent");return q.map(Y=>({id:`convtype:${Y.value}`,label:Y.label,description:j?"对话类型创建后不可变,仅新对话可切换":`${Y.value===U?"当前 · ":""}${Y.description||""}`,disabled:j,action:()=>n("select-new-conversation-type",Y.value)}))}),kr=ye(()=>me.value.map(j=>({id:`skill:${j.path}`,label:j.name,description:j.description,skill:j}))),Ni=ye(()=>S.value==="skills"?kr.value:S.value==="workflows"?ne.value:S.value==="theme"?Es.value:S.value==="permission"?ht.value:S.value==="execution"?pn.value:S.value==="model"?Vo.value:S.value==="run-mode"?Ff.value:S.value==="network"?fl.value:S.value==="work-mode"?Di.value:S.value==="workspace"?Tn.value:S.value==="conversation-type"?wr.value:Kt.value),pl=ye(()=>S.value==="skills"?"可用 AgentSkills":S.value==="workflows"?"工作流选项":S.value==="theme"?"主题选项":S.value==="permission"?"权限模式选项":S.value==="execution"?"执行环境选项":S.value==="model"?"模型选项":S.value==="run-mode"?"思考模式选项":S.value==="network"?"网络权限选项":S.value==="work-mode"?"工作模式选项":S.value==="workspace"?i.workspaceKind==="project"?"项目选项":"工作区选项":S.value==="conversation-type"?"对话类型选项":"快捷指令"),$f=ye(()=>S.value==="skills"?g.value?"正在加载 skills...":"没有匹配的 skill":S.value==="workflows"?Q.value?"正在加载工作流...":"暂无可用工作流(可去 /workflows 创建)":S.value==="permission"?"无可用权限模式":S.value==="execution"?"无可用执行环境":S.value==="model"?"无可用模型":S.value==="network"?"无可用网络权限选项":S.value==="work-mode"?"无可用工作模式":S.value==="workspace"?i.workspaceKind==="project"?"暂无其他项目":"暂无其他工作区":S.value==="conversation-type"?"无可用对话类型":"没有匹配的指令"),ya=ye(()=>y.value&&(g.value||Ni.value.length>=0)),gl=async()=>{if(!(v.value||g.value)){g.value=!0;try{const j=await fetch("/api/skills"),U=await j.json().catch(()=>({}));if(!j.ok||!(U!=null&&U.success))throw new Error((U==null?void 0:U.error)||"加载 skills 失败");p.value=Array.isArray(U.skills)?U.skills.filter(Y=>Y&&Y.name&&Y.path).map(Y=>({name:String(Y.name||""),description:String(Y.description||""),path:String(Y.path||"")})):[],v.value=!0}catch(j){p.value=[],v.value=!1,console.warn("[SkillSlash] 加载 skills 失败:",j)}finally{g.value=!1}}},Rc=async(j=!1)=>{if(!(z.value&&!j||Q.value)){Q.value=!0;try{const U=await fetch("/api/workflows"),Y=await U.json().catch(()=>({}));if(!U.ok)throw new Error((Y==null?void 0:Y.error)||"加载工作流列表失败");L.value=Array.isArray(Y.workflows)?Y.workflows.filter(Te=>Te&&Te.name).map(Te=>({name:String(Te.name||""),description:String(Te.description||""),source:String(Te.source||""),updatedAt:String(Te.updatedAt||""),nodeCount:Number(Te.nodeCount??0)})):[],z.value=!0}catch(U){L.value=[],z.value=!1,console.warn("[WorkflowSlash] 加载工作流列表失败:",U)}finally{Q.value=!1}}},ba=async j=>{if(W.value)return;const U=String(i.currentConversationId||"").trim();W.value=!0;try{const Y={name:j};U&&(Y.conversation_id=U);const Te=await fetch("/api/workflow/activate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Y)}),Me=await Te.json().catch(()=>({}));if(!Te.ok||!(Me!=null&&Me.success))throw new Error((Me==null?void 0:Me.error)||"激活工作流失败");Me!=null&&Me.snapshot&&P.setWorkflow(Me.snapshot,!0),Vs().pushToast({title:`工作流「${j}」已激活`,type:"success"});const Ve=String((Me==null?void 0:Me.conversation_id)||"").trim();Ve&&Ve!==U&&n("workflow-activated",Ve)}catch(Y){Vs().pushToast({title:"激活工作流失败",message:String((Y==null?void 0:Y.message)||Y||""),type:"error"})}finally{W.value=!1}},Je=async()=>{if(W.value)return;const j=String(i.currentConversationId||"").trim();if(j){W.value=!0;try{const U=await fetch("/api/workflow/deactivate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({conversation_id:j})}),Y=await U.json().catch(()=>({}));if(!U.ok||!(Y!=null&&Y.success))throw new Error((Y==null?void 0:Y.error)||"退出工作流失败");P.setWorkflow(null,!0),Vs().pushToast({title:`已退出工作流「${(Y==null?void 0:Y.workflow_name)||""}」`,type:"success"})}catch(U){Vs().pushToast({title:"退出工作流失败",message:String((U==null?void 0:U.message)||U||""),type:"error"})}finally{W.value=!1}}},ne=ye(()=>{const j=[],U=P.isActive?String(P.snapshot.name||""):"";U&&j.push({id:"workflow-deactivate",label:"退出当前工作流",description:`进行中:${U} · 摘牌退出(不打断当前工作)`,disabled:W.value,action:()=>{Je()}});const Y=!i.isConnected||i.streamingMessage||W.value||!!U;for(const Te of L.value){const Me=U&&Te.name===U;j.push({id:`workflow-activate-${Te.name}`,label:Te.name,description:Me?"当前激活中":`${Te.description||"(无描述)"}${Te.source==="builtin"?" · 内置":""}`,disabled:Y||!!Me,action:()=>{ba(Te.name)}})}return j}),Ee=()=>{const j=In();if(!j||!i.isConnected||i.inputLocked){nr();return}Jt(),y.value=!0,b.value!==j.query&&(_.value=0),b.value=j.query,j.doubleSlash&&S.value==="root"&&!R.value?(S.value="skills",M.value="typed",_.value=0):!j.doubleSlash&&S.value==="skills"&&M.value==="typed"&&(S.value="root",M.value=null,_.value=0),S.value==="skills"&&gl(),_.value=Math.min(_.value,Math.max(0,Ni.value.length-1)),fe()},Ue=(j=_.value)=>{const U=In(),Y=me.value[j],Te=ts.value;if(!U||!Y||!Te)return;m.value=[...m.value.filter(ys=>ys.path!==Y.path),Y];const{state:Me,view:Ve,schema:$e}=Te,Ye=$e.nodes.mention;if(!Ye)return;const qe=Ye.create({id:Y.path,label:Y.name,path:Y.path,description:Y.description||"",mentionSuggestionChar:""});let Et=Me.tr.delete(U.start,U.end);Et=Et.insert(U.start,qe);const Lt=U.start+qe.nodeSize;Et=Et.insertText(" ",Lt),Et=Et.setSelection(_t.near(Et.doc.resolve(Lt+1))),Ve.dispatch(Et),Ve.focus(),nr(),ft(()=>{Ar()})},zt=(j=_.value)=>{const U=Ni.value[j];if(!(!U||U.disabled)){if(U.mode){C.value=j,S.value=U.mode,_.value=0,M.value=U.mode==="skills"?"menu":null,U.mode==="skills"&&gl(),U.mode==="workflows"&&Rc(),U.mode==="workspace"&&n("fetch-host-workspaces"),fe();return}if(U.skill){const Y=me.value.findIndex(Te=>{var Me;return Te.path===((Me=U.skill)==null?void 0:Me.path)});Ue(Y>=0?Y:j);return}U.action&&Ss(U.action)}},Mt=j=>{if(j.ctrlKey&&j.key==="Enter")return!1;if(y.value){if(j.key==="ArrowDown"){j.preventDefault(),A.value=!1;const U=Ni.value.length;return U>0&&(_.value=(_.value+1)%U,fe()),!0}if(j.key==="ArrowUp"){j.preventDefault(),A.value=!1;const U=Ni.value.length;return U>0&&(_.value=(_.value-1+U)%U,fe()),!0}if(j.key==="Enter")return Ni.value.length>0&&(j.preventDefault(),zt(_.value)),!0;if(j.key==="Escape")return j.preventDefault(),S.value!=="root"?(S.value==="skills"&&M.value==="typed"&&(R.value=!0),M.value=null,S.value="root",_.value=Math.min(C.value,Math.max(0,Ni.value.length-1)),fe()):nr(),!0}return!1},mt=j=>jo(j)||Mt(j)?!0:(requestAnimationFrame(()=>{Ee(),zo()}),!1),ws=()=>{n("input-blur"),window.setTimeout(()=>{nr(),Qs()},120)},Pn=j=>{const U=j.clipboardData;if(!U)return[];const Y=[];if(U.items&&U.items.length)for(const Te of Array.from(U.items)){if(Te.kind!=="file")continue;const Me=Te.getAsFile();Me&&Y.push(Me)}return!Y.length&&U.files&&U.files.length&&Y.push(...Array.from(U.files)),Y},On=(j="")=>{const U=String(j||"").split(`
`);return{type:"doc",content:(U.length?U:[""]).map(Y=>({type:"paragraph",content:Y?[{type:"text",text:Y}]:void 0}))}},Go=()=>{const j=ts.value;return j?j.getText({blockSeparator:`
`}):i.inputMessage||""},Ms=j=>{const U=[],Y=Ve=>{if(!Ve)return"";if(Ve.type==="text")return Ve.text||"";if(Ve.type==="mention"){const $e=Ve.attrs||{},Ye=String($e.id||""),qe=String($e.label||Ye).trim();if(Ye.startsWith("file://")){const xr=Ye.slice(7);return qe&&xr?`[${qe}](file://${xr})`:qe}const Lt=qe,ys=String($e.path||Ye).trim();return Lt&&ys&&!U.some(xr=>xr.path===ys)&&U.push({name:Lt,path:ys}),Lt&&ys?`[$${Lt}](${ys})`:Lt}return Ve.type==="hardBreak"?`
`:Array.isArray(Ve.content)?Ve.content.map(Y).join(""):""};return{message:(Array.isArray(j==null?void 0:j.content)?j.content:[]).map(Ve=>Y(Ve)).join(`
`).trim(),skillRefs:U}},ts=TK({content:On(i.inputMessage||""),editable:i.isConnected&&!i.inputLocked,extensions:[BX.configure({codeBlock:!1,heading:!1,blockquote:!1,bulletList:!1,orderedList:!1,listItem:!1,horizontalRule:!1}),VX.configure({placeholder:"输入消息... (Ctrl+Enter 发送)"}),jX.configure({HTMLAttributes:{class:"skill-md-link"},deleteTriggerWithBackspace:!0,renderText({node:j}){return String(j.attrs.label||j.attrs.id||"")},renderHTML({node:j,HTMLAttributes:U}){const Y=U||{},Te=String(j.attrs.id||""),Me=Te.startsWith("file://"),Ve=Me?`${Y.class||""} file-md-link`.trim():`${Y.class||""} skill-md-link`.trim(),$e=Me?"data-file-path":"data-skill-path",Ye=Me?Te.slice(7):j.attrs.path||j.attrs.id||"";return["span",{...Y,class:Ve,[$e]:Ye},String(j.attrs.label||j.attrs.id||"")]},suggestion:{char:"\0"}})],editorProps:{attributes:{class:"stadium-input-editor","data-placeholder":"输入消息... (Ctrl+Enter 发送)"},handleKeyDown(j,U){return U.ctrlKey&&U.key==="Enter"?(U.preventDefault(),n("send-or-stop"),!0):mt(U)},handlePaste(j,U){const Y=Pn(U);return Y.length?(U.preventDefault(),n("paste-files",Y),!0):!1}},onUpdate(){De||(n("update:input-message",Go()),n("input-change"),ft(()=>{Ar(),Ee(),zo()}))},onFocus(){n("input-focus")}}),Dn=pe(!1),Lc=pe(null);let Zn=0,ei=0;const Cr=pe("idle"),pm=pe(0),Ck=pe(""),a_=ye(()=>typeof window>"u"?!1:!!window.AndroidVoiceBridge),Tk=ye(()=>Cr.value==="downloading"?`模型下载中 ${pm.value}%`:Cr.value==="model_not_ready"?"模型未下载,请在个人空间下载":Dn.value?"停止录音":"语音输入"),l_=()=>{typeof window>"u"||(window.__onVoiceResult=j=>{const U=window.AndroidVoiceBridge;if(U==null||U.debugLog("__onVoiceResult 被调用, text="+JSON.stringify(j)),!j){U==null||U.debugLog("__onVoiceResult: text 为空,跳过");return}const Y=ts.value;if(!Y){U==null||U.debugLog("__onVoiceResult: editor.value 为 null"),console.warn("[VoiceInput] editor is null");return}U==null||U.debugLog("__onVoiceResult: editor.value 存在,准备插入文字"),U==null||U.debugLog("__onVoiceResult: voiceAnchorPos="+Zn+" lastVoiceTextLength="+ei);const{state:Te,view:Me}=Y,Ve=Te.doc.content.size,$e=Math.max(0,Math.min(Zn,Ve)),Ye=Math.min($e+ei,Ve);U==null||U.debugLog("__onVoiceResult: docSize="+Ve+" safeAnchor="+$e+" oldEnd="+Ye);try{let qe=Te.tr;Ye>$e&&(qe=qe.delete($e,Ye)),qe=qe.insertText(j,$e);const Et=Math.min($e+j.length,qe.doc.content.size),Lt=window.TextSelection;Lt&&(qe=qe.setSelection(Lt.create(qe.doc,Et))),Me.dispatch(qe),Me.focus(),ei=j.length,n("update:input-message",Go()),n("input-change"),ft(()=>Ar()),U==null||U.debugLog("__onVoiceResult: 文字插入成功")}catch(qe){U==null||U.debugLog("__onVoiceResult: 插入异常 "+(qe.message||String(qe)))}},window.__onVoiceStatus=j=>{j==="listening"||j==="processing"||j==="initializing"?Dn.value=!0:j==="idle"?(Dn.value=!1,Zn=0,ei=0):j==="model_not_ready"&&(Cr.value="model_not_ready")},window.__onVoiceError=j=>{console.warn("[VoiceInput] 错误:",j),Dn.value=!1,Zn=0,ei=0},window.__onVoiceDownloadProgress=(j,U)=>{Cr.value="downloading",pm.value=j,Ck.value=U,j>=100&&(Cr.value="ready")},window.__onVoiceModelReady=()=>{Cr.value="ready"})};if(typeof window<"u"){l_();const j=window.AndroidVoiceBridge;if(j&&typeof j.isModelReady=="function")try{Cr.value=j.isModelReady()?"ready":"model_not_ready"}catch{Cr.value="idle"}}const gm=()=>typeof window>"u"?null:window.SpeechRecognition||window.webkitSpeechRecognition||null,ph=()=>{if(Lc.value){try{Lc.value.stop()}catch(j){console.warn("[VoiceInput] recognition.stop() error:",j)}Lc.value=null}Dn.value=!1,Zn=0,ei=0},Ak=()=>{const j=gm();if(!j)return null;const U=new j;U.lang="zh-CN",U.continuous=!0,U.interimResults=!0,U.maxAlternatives=1;const Y=ts.value;return Y?Zn=Y.state.selection.from:Zn=0,ei=0,U.onresult=Te=>{let Me="";for(let ti=0;ti<Te.results.length;ti++){const y_=Te.results[ti];Me+=y_[0].transcript}if(!Me)return;const Ve=ts.value;if(!Ve){console.warn("[VoiceInput] editor is null");return}const{state:$e,view:Ye}=Ve,qe=$e.doc.content.size,Et=Math.max(0,Math.min(Zn,qe)),Lt=Math.min(Et+ei,qe);let ys=$e.tr;Lt>Et&&(ys=ys.delete(Et,Lt)),ys=ys.insertText(Me,Et);const xr=Math.min(Et+Me.length,ys.doc.content.size);ys=ys.setSelection(_t.create(ys.doc,xr)),Ye.dispatch(ys),Ye.focus(),ei=Me.length,n("update:input-message",Go()),n("input-change"),ft(()=>{Ar()})},U.onerror=Te=>{console.warn("[VoiceInput] onerror:",{error:Te.error,message:Te.message}),Te.error!=="aborted"&&(console.warn("[VoiceInput] stopping due to error:",Te.error),ph())},U.onstart=()=>{},U.onaudiostart=()=>{},U.onsoundstart=()=>{},U.onspeechstart=()=>{},U.onspeechend=()=>{},U.onsoundend=()=>{},U.onaudioend=()=>{},U.onend=()=>{Dn.value=!1,Lc.value=null,Zn=0,ei=0},U},c_=()=>{const j=window.AndroidVoiceBridge;if(j){if(Dn.value){j.stopListening();return}const Y=ts.value;Zn=Y?Y.state.selection.from:0,ei=0,j.startListening();return}if(Dn.value){ph();return}const U=Ak();if(!U){console.warn("[VoiceInput] 浏览器不支持语音识别");return}try{U.start(),Lc.value=U,Dn.value=!0}catch(Y){console.warn("[VoiceInput] 启动语音识别失败:",Y),ph()}},u_=pe(null),ml=new Map,ro=[],vl=new Map,Pc=new Map,Tr=new Map,gh=new WeakMap,qo=pe(!1);let Oc=!1,yl=null;const Ek=j=>U=>{j&&(U instanceof HTMLElement?ml.set(j,U):ml.delete(j))},h_=j=>{const U=Math.round(j.getBoundingClientRect().height);return U>0?U:j.offsetHeight>0?j.offsetHeight:34},Dc=()=>we.value.map(j=>String((j==null?void 0:j.id)||"").trim()).filter(j=>!!j),Mk=()=>{qo.value=!0,yl!==null&&window.clearTimeout(yl),yl=window.setTimeout(()=>{qo.value=!1,yl=null,Nn()},NC+40)},mh=j=>{const U=gh.get(j);U&&(clearTimeout(U),gh.delete(j)),j.style.removeProperty("transition"),j.style.removeProperty("transform"),j.style.removeProperty("opacity")},vh=(j,U,Y,Te,Me)=>{const Ve=()=>{j.style.removeProperty("transition"),U.forEach($e=>j.style.removeProperty($e)),Me==null||Me()};j.style.transition="none",Object.entries(Y).forEach(([$e,Ye])=>{j.style.setProperty($e,Ye)}),requestAnimationFrame(()=>{j.style.transition=U.map(Ye=>`${Ye} ${NC}ms ${_J}`).join(", "),Object.entries(Te).forEach(([Ye,qe])=>{j.style.setProperty(Ye,qe)});const $e=window.setTimeout(Ve,NC+40);gh.set(j,$e)})};let Nc=[];PF(()=>{ro.splice(0,ro.length,...Nc),vl.clear(),Pc.clear(),Nc.forEach(j=>{const U=ml.get(j);U!=null&&U.isConnected&&(vl.set(j,U.getBoundingClientRect()),Pc.set(j,U))})}),S2(()=>{const j=u_.value,U=Dc();if(!Oc){Oc=!0,Nc=[...U],ro.splice(0,ro.length),vl.clear(),Pc.clear();return}Mk();const Y=new Set(ro),Te=new Set(U),Me=U.filter($e=>!Y.has($e)),Ve=ro.filter($e=>!Te.has($e));!Me.length&&!Ve.length||(Ve.forEach($e=>{const Ye=Pc.get($e),qe=vl.get($e);if(!Ye||!qe||!(j!=null&&j.isConnected))return;mh(Ye);const Et=Tr.get($e);Et&&(mh(Et),Et.remove(),Tr.delete($e));const Lt=Ye.cloneNode(!0),ys=j.getBoundingClientRect();Lt.style.position="absolute",Lt.style.left="0",Lt.style.top=`${Math.round(qe.top-ys.top)}px`,Lt.style.width=`${Math.round(qe.width>0?qe.width:ys.width)}px`,Lt.style.pointerEvents="none",Lt.style.zIndex="0",Lt.style.margin="0",Lt.style.opacity="1",Lt.querySelectorAll("button").forEach(ti=>{ti instanceof HTMLButtonElement&&(ti.disabled=!0)}),j.appendChild(Lt),Tr.set($e,Lt);const xr=h_(Lt);vh(Lt,["transform"],{transform:"translateY(0)"},{transform:`translateY(${xr}px)`},()=>{Tr.delete($e),Lt.remove()}),ml.delete($e)}),U.forEach($e=>{const Ye=ml.get($e);if(!(Ye!=null&&Ye.isConnected))return;if(mh(Ye),Me.includes($e)){const ys=h_(Ye);vh(Ye,["transform"],{transform:`translateY(${ys}px)`},{transform:"translateY(0)"});return}const qe=vl.get($e);if(!qe)return;const Et=Ye.getBoundingClientRect(),Lt=qe.top-Et.top;Math.abs(Lt)<.5||vh(Ye,["transform"],{transform:`translateY(${Lt}px)`},{transform:"translateY(0)"})}),ro.splice(0,ro.length),vl.clear(),Pc.clear(),Nc=[...U])});const yh=ye(()=>{const j=!!(i.inputMessage||"").trim();if(i.streamingMessage)return j;const U=Array.isArray(i.selectedImages)&&i.selectedImages.length>0,Y=Array.isArray(i.selectedVideos)&&i.selectedVideos.length>0;return j||U||Y}),d_=ye(()=>!!i.streamingMessage&&!yh.value),mm=ye(()=>i.isConnected?i.streamingMessage?!1:i.inputLocked||i.mediaUploading?!0:!yh.value:!0),bh=ye(()=>{const j=we.value.length>0,U=Array.isArray(i.selectedImages)&&i.selectedImages.length>0,Y=Array.isArray(i.selectedVideos)&&i.selectedVideos.length>0,Te=Array.isArray(i.selectedFiles)&&i.selectedFiles.length>0;return j||He.value||yt.value||y.value||ee.value||U||Y||Te||!!i.inputIsMultiline||!!i.goalModeArmed||!!i.goalRunning||xk.value}),xk=ye(()=>{var j;return String(((j=i.goalProgress)==null?void 0:j.status)||"").toLowerCase()==="done"}),f_=()=>{T.value=!0},p_=()=>{T.value=!1,Nn()},Bc=()=>{T.value=!1,Nn()},Ik=ye(()=>we.value.length>0||qo.value||ya.value||T.value),Rk=()=>{const j=a.value,U=l.value;if(!j||!U)return 0;let Y=U.offsetTop,Te=U.offsetTop+U.offsetHeight;const Me=j.querySelector(".skill-slash-menu");if(Me instanceof HTMLElement){const $e=Me.offsetTop,Ye=Me.offsetTop+Me.offsetHeight;return Math.max(0,Math.max(Te,Ye)-Math.min(Y,$e))}return j.querySelectorAll(".runtime-queue-list:not(.runtime-queue-list--empty), .floating-status-row, .composer-avatar").forEach($e=>{$e instanceof HTMLElement&&($e.classList.contains("floating-status-row")&&!He.value||$e.classList.contains("composer-avatar")&&!yt.value||(Y=Math.min(Y,$e.offsetTop),Te=Math.max(Te,$e.offsetTop+$e.offsetHeight)))}),Math.max(0,Te-Y)},Lk=()=>{const j=l.value;return j?Math.max(0,j.getBoundingClientRect().height):0},Nn=()=>{const j=Rk();if(!j)return;const U=Lk();bh.value?d.value<=0&&U>0?d.value=U:d.value>0&&U>0?d.value=Math.min(d.value,U):d.value<=0&&(d.value=j):d.value=j;const Y=d.value||j,Te=Math.max(0,j-Y),Ve=Math.ceil(123+Te);n("composer-height-change",{reservedHeight:Ve,visualHeight:j,growth:Te})},Ar=()=>{var Lt;const j=(Lt=a.value)==null?void 0:Lt.querySelector(".stadium-input-editor");if(!j)return;const U=j,Y=U.scrollTop,Te=document.activeElement===U||U.contains(document.activeElement);U.style.height="auto";const Me=window.getComputedStyle(U),Ve=parseFloat(Me.lineHeight||"20")||20,$e=Ve*10,Ye=Math.min(U.scrollHeight,$e),qe=Math.max(1,Math.round(Ye/Ve)),Et=Ye>Ve*1.4;de(qe,Et),U.style.height=`${Ye}px`,Fc(U,{previousScrollTop:Y,selectionShouldStayVisible:Te,padding:Math.max(4,Ve*.3)}),ft(()=>{Nn()})},Fc=(j,U)=>{const Y=Math.max(0,j.scrollHeight-j.clientHeight);if(Y<=0){j.scrollTop=0;return}if(!U.selectionShouldStayVisible){j.scrollTop=Math.min(Y,Math.max(0,U.previousScrollTop));return}requestAnimationFrame(()=>{const Te=ts.value;if(!Te){j.scrollTop=Math.min(Y,Math.max(0,U.previousScrollTop));return}try{const Me=Te.view.coordsAtPos(Te.state.selection.head),Ve=j.getBoundingClientRect(),$e=U.padding,Ye=Math.max(0,j.scrollHeight-j.clientHeight);let qe=j.scrollTop;Me.bottom>Ve.bottom-$e?qe+=Me.bottom-Ve.bottom+$e:Me.top<Ve.top+$e&&(qe-=Ve.top+$e-Me.top),j.scrollTop=Math.min(Ye,Math.max(0,qe))}catch{j.scrollTop=Math.min(Y,Math.max(0,U.previousScrollTop))}})},_a=(j,U)=>{const Y=Uo(),Te=ts.value;if(!Te||!Y)return;const Me=Te.schema.nodes.mention;if(!Me)return;const Ve=Me.create({id:`file://${j}`,label:U}),{state:$e,view:Ye}=Te;let qe=$e.tr.delete(Y.start,Y.end);qe=qe.insert(Y.start,Ve);const Et=Y.start+Ve.nodeSize;qe=qe.insertText(" ",Et),qe=qe.setSelection(_t.near(qe.doc.resolve(Et+1))),Ye.dispatch(qe),Ye.focus(),Qs(),ft(()=>{Ar()})},Hf=async j=>{var Te;const U=j.target,Y=(U==null?void 0:U.files)||null;if(K.value&&Y&&Y.length>0){K.value=!1;const Me=Y[0];try{const $e=await(await fetch(`/api/project/files/search?q=${encodeURIComponent(Me.name)}&limit=10`)).json().catch(()=>({})),Ye=Array.isArray((Te=$e==null?void 0:$e.data)==null?void 0:Te.items)?$e.data.items:[],qe=Ye.find(Et=>Et.name===Me.name)||Ye[0];qe?io(qe):_a(Me.name,Me.name)}catch(Ve){console.warn("[FileAt] 通过文件选择器查找路径失败:",Ve),_a(Me.name,Me.name)}U&&(U.value="");return}n("file-selected",Y),U&&(U.value="")},Pk=()=>{var j;return Ms((j=ts.value)==null?void 0:j.getJSON())},Ok=()=>{var j,U;return{editor_json:((j=ts.value)==null?void 0:j.getJSON())||null,skill_refs:Ms((U=ts.value)==null?void 0:U.getJSON()).skillRefs}},g_=j=>{const U=ts.value;U&&j!=null&&j.editor_json&&typeof j.editor_json=="object"&&(De=!0,U.commands.setContent(j.editor_json),De=!1,n("update:input-message",Go()),ft(Ar))},m_=()=>{!i.isConnected||i.uploading||n("quick-upload")},v_=ye(()=>{const j=(i.permissionOptions||[]).find(U=>U.value===i.currentPermissionMode);return j?j.label:i.currentPermissionMode}),q=[{value:"agent",label:"智能体",description:"单智能体对话"},{value:"multi_agent",label:"多智能体",description:"Team Leader + 子智能体协作"}],te=ye(()=>!!i.currentConversationId),Z=ye(()=>i.currentConversationId?i.currentConversationType==="multi_agent"?"多智能体":"智能体":i.newConversationType==="multi_agent"?"多智能体":"智能体"),re=ye(()=>!!i.streamingMessage),Ae=ye(()=>{const j=(i.workModeOptions||[]).find(U=>U.value===i.currentWorkMode);return j?j.label:i.currentWorkMode||"计划"}),ue=ye(()=>i.currentWorkMode==="plan"),Ge=ye(()=>i.currentPermissionMode==="readonly"),pt=ye(()=>ue.value||Ge.value),Bt=ye(()=>{const j=String(i.currentExecutionMode||"");return j==="direct"?"完全访问":j==="sandbox"?"沙箱":j}),Rt=ye(()=>{const U=(Array.isArray(i.modelOptions)?i.modelOptions:[]).find(Y=>Y.key===i.currentModelKey);return Number((U==null?void 0:U.contextWindow)||0)}),Ps=ye(()=>{var j;return!!((j=o==null?void 0:o.form)!=null&&j.auto_deep_compress_enabled)}),Us=ye(()=>{var U;const j=Number(((U=o==null?void 0:o.form)==null?void 0:U.deep_compress_trigger_tokens)||0);return j>0?j:15e4}),Er=ye(()=>Ps.value?Us.value:Rt.value>0?Rt.value:0),Mr=ye(()=>{const j=Number(Er.value||0);if(j<=0)return 0;const U=Math.max(0,Number(i.currentContextTokens||0));return Math.max(0,Math.min(100,U/j*100))}),$c=ye(()=>`${Math.round(Mr.value)}%`),Hc=ye(()=>{const j=Mr.value;return j<40?"var(--state-success)":j<=80?"var(--state-warning)":"var(--state-danger)"}),Sa=j=>{const U=Math.max(0,Number(j||0));if(U>=1e3){const Y=U/1e3;return`${Y>=100?Math.round(Y).toString():Y.toFixed(1).replace(/\.0$/,"")}k`}return`${Math.round(U)}`},oo=ye(()=>{const j=Sa(i.currentContextTokens||0),U=Number(Er.value||0);return U<=0?`${j}/--`:`${j}/${Sa(U)}`});return e({inputAreaRoot:a,stadiumShellOuter:c,compactInputShell:l,stadiumInput:u,fileUploadInput:h,emitComposerHeight:Nn,prepareMessageForSend:Pk,getComposerDraftMeta:Ok,restoreComposerDraftMeta:g_}),Xe(()=>i.inputMessage,async()=>{const j=ts.value;j&&!De&&Go()!==(i.inputMessage||"")&&(De=!0,j.commands.setContent(On(i.inputMessage||"")),De=!1),await ft(),Ar(),Ee()}),Xe(()=>i.isConnected,async j=>{var U,Y;(U=ts.value)==null||U.setEditable(!!j&&!i.inputLocked),j||(Y=ts.value)==null||Y.commands.blur(),await ft(),Ar()}),Xe(()=>i.inputLocked,j=>{var U;(U=ts.value)==null||U.setEditable(i.isConnected&&!j)}),Xe(()=>i.currentConversationId,async()=>{d.value=0,await ft(),Nn()}),Xe(()=>i.runtimeQueuedMessages,async()=>{await ft(),Nn()},{deep:!0}),Xe(()=>i.projectGitSummary,async()=>{Le.value||Jt(),await ft(),Nn()},{deep:!0}),Xe(He,async()=>{await ft(),Nn(),window.setTimeout(()=>{Nn()},280)}),Xe(yt,async()=>{await ft(),Nn(),window.setTimeout(()=>{Nn()},280)}),Xe(()=>{var j;return(j=i.avatarStatus)==null?void 0:j.mode},()=>{var j;((j=i.avatarStatus)==null?void 0:j.mode)!=="idle"&&Yn()}),Xe(()=>{var j,U;return[((j=i.selectedImages)==null?void 0:j.length)||0,((U=i.selectedVideos)==null?void 0:U.length)||0]},async()=>{await ft(),Nn()}),Xe(Ik,async()=>{await ft(),Nn()}),Xe(()=>i.streamingMessage||i.inputLocked,j=>{j&&Dn.value&&ph()}),Cn(()=>{document.addEventListener("click",Jt),Ar(),ft(()=>{Nn(),typeof ResizeObserver<"u"&&(et=new ResizeObserver(()=>{Nn()}),a.value&&et.observe(a.value),c.value&&et.observe(c.value),l.value&&et.observe(l.value))})}),xn(()=>{var j;ph(),document.removeEventListener("click",Jt),(j=ts.value)==null||j.destroy(),ml.forEach(U=>{U&&mh(U)}),Tr.forEach(U=>{mh(U),U.remove()}),Tr.clear(),ml.clear(),ro.splice(0,ro.length),vl.clear(),Pc.clear(),Oc=!1,Nc=[],yl!==null&&(window.clearTimeout(yl),yl=null),qo.value=!1,et&&(et.disconnect(),et=null),Yn()}),(j,U)=>(F(),$("div",{class:"input-area compact-input-area",ref_key:"inputAreaRoot",ref:a},[E("div",{class:"stadium-input-wrapper",ref_key:"stadiumShellOuter",ref:c},[E("div",{class:ke(["runtime-queue-list",{"runtime-queue-list--empty":!we.value.length}]),ref_key:"runtimeQueueList",ref:u_},[(F(!0),$(Ie,null,tt(we.value,(Y,Te)=>(F(),$("div",{key:Y.id,class:ke(["runtime-queue-item",{"runtime-queue-item--top":Te===0}]),"data-runtime-queue-id":Y.id||"",ref_for:!0,ref:Ek(Y.id)},[E("span",dY,ae(Y.text||""),1),E("button",{type:"button",class:"runtime-queue-item__action",onClick:Ne(Me=>j.$emit("guide-runtime-message",Y.id),["stop"])}," 引导 ",8,fY),E("button",{type:"button",class:"runtime-queue-item__action runtime-queue-item__action--danger",onClick:Ne(Me=>j.$emit("delete-runtime-message",Y.id),["stop"])}," 删除 ",8,pY)],10,hY))),128))],2),Qe(us,{name:"skill-slash-menu-motion",onBeforeEnter:f_,onBeforeLeave:f_,onAfterEnter:p_,onAfterLeave:Bc},{default:Vt(()=>[ya.value?(F(),$("div",{key:S.value,class:"skill-slash-menu-wrapper",role:"listbox","aria-label":pl.value},[E("div",{ref_key:"skillSlashList",ref:w,class:"skill-slash-menu",onScroll:st},[(F(!0),$(Ie,null,tt(Ni.value,(Y,Te)=>(F(),$("button",{key:Y.id,type:"button",class:ke(["skill-slash-item",{"skill-slash-item--active":Te===_.value&&!A.value,"skill-slash-item--disabled":Y.disabled}]),role:"option","aria-selected":Te===_.value,disabled:Y.disabled,onMousedown:Ne(Me=>zt(Te),["prevent"])},[E("span",vY,ae(Y.label),1),E("span",yY,ae(Y.description),1)],42,mY))),128)),Ni.value.length?ge("",!0):(F(),$("div",bY,ae($f.value),1))],544),E("div",{class:"skill-slash-menu__highlight",style:Ke(Re.value)},null,4)],8,gY)):ge("",!0)]),_:1}),Qe(ZX,{ref_key:"fileAtMenuRef",ref:G,visible:ee.value,items:le.value,"active-index":ve.value,loading:oe.value,"host-mode":!!i.hostMode,"menu-style":I.value,onSelect:Jn,onHover:U[0]||(U[0]=Y=>ve.value=Y)},null,8,["visible","items","active-index","loading","host-mode","menu-style"]),Qe(us,{name:"floating-status-motion"},{default:Vt(()=>[yt.value?(F(),$("div",{key:0,class:"composer-avatar",onClick:Ne(Rn,["stop"])},[Qe(bD,{mode:i.avatarStatus.mode,"tool-keys":i.avatarStatus.toolKeys||[],tracking:i.avatarStatus.tracking!==!1,size:45,"hex-background":""},null,8,["mode","tool-keys","tracking"]),Qe(us,{name:"composer-avatar-text-fade",mode:"out-in"},{default:Vt(()=>[J.value?(F(),$("span",{key:`poke-${J.value}`,class:ke(["composer-avatar__text",{"composer-avatar__text--right":!He.value,"composer-avatar__text--top":He.value}])},ae(J.value),3)):At.value?(F(),$("span",{key:Nt.value,class:ke(["composer-avatar__text",{"composer-avatar__text--right":!He.value,"composer-avatar__text--top":He.value}])},ae(At.value),3)):ge("",!0)]),_:1})])):ge("",!0)]),_:1}),Qe(us,{name:"floating-status-motion"},{default:Vt(()=>[He.value?(F(),$("div",{key:0,class:"floating-status-row",onClick:U[10]||(U[10]=Ne(()=>{},["stop"]))},[E("div",{class:"floating-project-status",onClick:U[9]||(U[9]=Ne(()=>{},["stop"]))},[Le.value?(F(),$("span",_Y,[E("span",SY,[E("button",{type:"button",class:ke(["floating-project-status__button floating-project-status__button--project",{"floating-project-status__button--active":It.value==="project"}]),onClick:U[1]||(U[1]=Ne(Y=>$t("project"),["stop"]))},ae(Le.value.projectName),3),It.value==="project"?(F(),$("div",{key:0,class:"floating-project-status__submenu floating-project-status__submenu--project",onClick:U[2]||(U[2]=Ne(()=>{},["stop"]))},[E("button",{type:"button",onClick:Ne(hl,["stop"])}," 在文件管理器中打开 "),E("button",{type:"button",onClick:Ne(ut,["stop"])},"复制地址")])):ge("",!0)]),E("span",wY,[E("button",{type:"button",class:ke(["floating-project-status__button floating-project-status__button--branch",{"floating-project-status__button--active":It.value==="branch"}]),onClick:U[3]||(U[3]=Ne(Y=>$t("branch"),["stop"]))},ae(Le.value.branch),3),It.value==="branch"?(F(),$("div",{key:0,class:"floating-project-status__submenu floating-project-status__submenu--branch",onClick:U[4]||(U[4]=Ne(()=>{},["stop"]))},[E("button",{type:"button",onClick:Ne(Hs,["stop"])},"复制分支名称")])):ge("",!0)])])):ge("",!0),E("span",kY,[s.goalRunning?(F(),$("span",CY,"目标模式运行中")):s.goalModeArmed?(F(),$("span",TY,"目标模式就绪")):ge("",!0),s.pendingUserQuestionCount>0?(F(),$("button",{key:2,type:"button",class:"floating-project-status__notice floating-project-status__notice--button",onClick:U[5]||(U[5]=Ne(Y=>j.$emit("restore-user-question"),["stop"]))}," 等待回答问题 ")):ge("",!0),(s.activeSubAgentCount||0)>0?(F(),$("button",{key:3,type:"button",class:"floating-project-status__notice floating-project-status__notice--button",onClick:U[6]||(U[6]=Ne(Y=>j.$emit("stop-all-sub-agents"),["stop"]))},ae(s.activeSubAgentCount)+" 个子智能体运行中 ",1)):ge("",!0),s.terminalCount>0?(F(),$("button",{key:4,type:"button",class:"floating-project-status__terminal",onClick:U[7]||(U[7]=Ne(Y=>j.$emit("realtime-terminal"),["stop"]))},ae(s.terminalCount)+" 个终端 ",1)):ge("",!0),Le.value?(F(),$("button",{key:5,type:"button",class:"floating-project-status__stats",onClick:U[8]||(U[8]=Ne(Y=>j.$emit("open-git-changes-panel"),["stop"]))},[E("span",AY,[U[41]||(U[41]=hn("+",-1)),Qe($I,{value:Le.value.additions},null,8,["value"])]),E("span",EY,[U[42]||(U[42]=hn("-",-1)),Qe($I,{value:Le.value.deletions},null,8,["value"])])])):ge("",!0)])])])):ge("",!0)]),_:1}),E("div",{class:ke(["stadium-shell",{"is-multiline":s.inputIsMultiline,"is-focused":s.inputIsFocused,"has-text":(s.inputMessage||"").trim().length>0}]),ref_key:"compactInputShell",ref:l},[E("input",{type:"file",ref_key:"fileUploadInput",ref:h,class:"file-input-hidden",multiple:"",onChange:Hf},null,544),E("div",MY,[s.selectedImages&&s.selectedImages.length||s.selectedFiles&&s.selectedFiles.length?(F(),$("div",xY,[(F(!0),$(Ie,null,tt(s.selectedImages,Y=>(F(),$("div",{class:"image-thumbnail-wrapper",key:Y,onClick:Ne(Te=>se(Y),["stop"])},[E("img",{src:ce(Y),alt:xe(Y),class:"image-thumbnail"},null,8,RY),E("button",{type:"button",class:"image-remove-btn-hover",onClick:Ne(Te=>j.$emit("remove-image",Y),["stop"])},[...U[43]||(U[43]=[E("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none","aria-hidden":"true"},[E("path",{d:"M2.5 2.5l5 5M7.5 2.5l-5 5",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round"})],-1)])],8,LY)],8,IY))),128)),s.selectedFiles&&s.selectedFiles.length?(F(),Wt(Z2,{key:0,files:s.selectedFiles,removable:"",onRemove:U[11]||(U[11]=Y=>j.$emit("remove-file",Y))},null,8,["files"])):ge("",!0)])):ge("",!0),s.selectedVideos&&s.selectedVideos.length?(F(),$("div",PY,[(F(!0),$(Ie,null,tt(s.selectedVideos,Y=>(F(),$("div",{class:"image-thumbnail-wrapper",key:Y},[E("img",{src:ce(Y),alt:xe(Y),class:"image-thumbnail"},null,8,OY),E("button",{type:"button",class:"image-remove-btn-hover",onClick:Ne(Te=>j.$emit("remove-video",Y),["stop"])},[...U[44]||(U[44]=[E("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none","aria-hidden":"true"},[E("path",{d:"M2.5 2.5l5 5M7.5 2.5l-5 5",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round"})],-1)])],8,DY)]))),128))])):ge("",!0),E("div",NY,[E("div",BY,[Qe(We(CK),{editor:We(ts),class:ke(["stadium-input stadium-input-tiptap",{"is-disabled":!s.isConnected||s.inputLocked}]),onFocusin:U[12]||(U[12]=Y=>j.$emit("input-focus")),onFocusout:ws},null,8,["editor","class"])])]),E("div",FY,[E("div",$Y,[E("button",{type:"button",class:"stadium-btn add-btn","data-tutorial":"quick-menu-open",onClick:U[13]||(U[13]=Ne(Y=>j.$emit("toggle-quick-menu"),["stop"])),disabled:!s.isConnected,"aria-label":"快捷菜单"},[...U[45]||(U[45]=[E("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",width:"16",height:"16",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true"},[E("path",{d:"M5 12h14"}),E("path",{d:"M12 5v14"})],-1)])],8,HY),E("div",{class:ke(["agent-type-switcher",{"is-disabled":te.value}])},[E("button",{type:"button",class:"agent-type-switcher__btn",onClick:U[14]||(U[14]=Ne(Y=>j.$emit("toggle-agent-type-menu"),["stop"])),disabled:!s.isConnected||te.value,"aria-expanded":s.agentTypeMenuOpen,"aria-haspopup":"true"},[E("span",null,ae(Z.value),1),E("span",{class:ke(["agent-type-switcher__caret",{open:s.agentTypeMenuOpen}]),"aria-hidden":"true"},"",2)],8,UY),s.agentTypeMenuOpen&&!te.value?(F(),$("div",{key:0,class:"agent-type-switcher__menu",onClick:U[15]||(U[15]=Ne(()=>{},["stop"]))},[(F(),$(Ie,null,tt(q,Y=>E("button",{key:Y.value,type:"button",class:ke(["agent-type-switcher__menu-item",{"is-active":Y.value===s.newConversationType}]),onClick:Ne(Te=>j.$emit("select-new-conversation-type",Y.value),["stop"])},[E("span",zY,ae(Y.label),1),E("span",jY,ae(Y.description),1)],10,WY)),64))])):ge("",!0)],2),E("div",{class:ke(["agent-type-switcher work-mode-switcher",{"is-disabled":re.value}])},[E("button",{type:"button",class:"agent-type-switcher__btn",onClick:U[16]||(U[16]=Ne(Y=>j.$emit("toggle-work-mode-menu"),["stop"])),disabled:!s.isConnected||re.value,"aria-expanded":s.workModeMenuOpen,"aria-haspopup":"true",title:re.value?"对话运行中,运行模式只能在空闲时切换":"运行模式"},[E("span",null,ae(Ae.value),1),E("span",{class:ke(["agent-type-switcher__caret",{open:s.workModeMenuOpen}]),"aria-hidden":"true"},"",2)],8,VY),s.workModeMenuOpen&&!re.value?(F(),$("div",{key:0,class:"agent-type-switcher__menu",onClick:U[17]||(U[17]=Ne(()=>{},["stop"]))},[(F(!0),$(Ie,null,tt(s.workModeOptions,Y=>(F(),$("button",{key:Y.value,type:"button",class:ke(["agent-type-switcher__menu-item",{"is-active":Y.value===s.currentWorkMode}]),onClick:Ne(Te=>j.$emit("change-work-mode",Y.value),["stop"])},[E("span",qY,ae(Y.label),1),E("span",KY,ae(Y.description),1)],10,GY))),128))])):ge("",!0)],2)]),E("div",QY,[a_.value?(F(),$("button",{key:0,type:"button",class:ke(["stadium-btn voice-btn",{"voice-btn--recording":Dn.value,"voice-btn--disabled":Cr.value==="downloading"||Cr.value==="model_not_ready"}]),onClick:c_,disabled:!s.isConnected||s.inputLocked,title:Tk.value},[Dn.value?(F(),$("div",JY,[...U[47]||(U[47]=[E("span",{class:"voice-wave-bar"},null,-1),E("span",{class:"voice-wave-bar"},null,-1),E("span",{class:"voice-wave-bar"},null,-1),E("span",{class:"voice-wave-bar"},null,-1)])])):(F(),$("svg",YY,[...U[46]||(U[46]=[E("path",{d:"M12 19v3m7-12v2a7 7 0 0 1-14 0v-2"},null,-1),E("rect",{width:"6",height:"13",x:"9",y:"2",rx:"3"},null,-1)])]))],10,XY)):ge("",!0),E("button",{type:"button",class:"stadium-btn send-btn",onClick:U[18]||(U[18]=Y=>j.$emit("send-or-stop")),disabled:mm.value},[d_.value?(F(),$("span",eJ)):(F(),$("span",tJ))],8,ZY)])])])],2),Qe(gL,{open:s.quickMenuOpen,"is-connected":s.isConnected,uploading:s.uploading,"streaming-message":s.streamingMessage,"thinking-mode":s.thinkingMode,"run-mode":s.runMode,"model-menu-open":s.modelMenuOpen,"model-options":s.modelOptions,"current-model-key":s.currentModelKey,"tool-menu-open":s.toolMenuOpen,"tool-settings":s.toolSettings,"tool-settings-loading":s.toolSettingsLoading,"settings-open":s.settingsOpen,"mode-menu-open":s.modeMenuOpen,compressing:s.compressing,"current-conversation-id":s.currentConversationId,"icon-style":s.iconStyle,"tool-category-icon":s.toolCategoryIcon,"block-upload":s.blockUpload,"block-tool-toggle":s.blockToolToggle,"block-realtime-terminal":s.blockRealtimeTerminal,"block-focus-panel":s.blockFocusPanel,"block-token-panel":s.blockTokenPanel,"block-compress-conversation":s.blockCompressConversation,"block-conversation-review":s.blockConversationReview,"execution-mode-enabled":s.executionModeEnabled,"goal-mode-armed":s.goalModeArmed,"goal-running":s.goalRunning,onQuickUpload:m_,onPickImages:U[19]||(U[19]=Y=>j.$emit("pick-images")),onPickVideo:U[20]||(U[20]=Y=>j.$emit("pick-video")),onToggleToolMenu:U[21]||(U[21]=Y=>j.$emit("toggle-tool-menu")),onToggleSettings:U[22]||(U[22]=Y=>j.$emit("toggle-settings")),onToggleModeMenu:U[23]||(U[23]=Y=>j.$emit("toggle-mode-menu")),onSelectRunMode:U[24]||(U[24]=Y=>j.$emit("select-run-mode",Y)),onToggleModelMenu:U[25]||(U[25]=Y=>j.$emit("toggle-model-menu")),onSelectModel:U[26]||(U[26]=Y=>j.$emit("select-model",Y)),onUpdateToolCategory:U[27]||(U[27]=(Y,Te)=>j.$emit("update-tool-category",Y,Te)),onRealtimeTerminal:U[28]||(U[28]=Y=>j.$emit("realtime-terminal")),onToggleFocusPanel:U[29]||(U[29]=Y=>j.$emit("toggle-focus-panel")),onToggleTokenPanel:U[30]||(U[30]=Y=>j.$emit("toggle-token-panel",Y)),onCompressConversation:U[31]||(U[31]=Y=>j.$emit("compress-conversation")),onToggleApprovalPanel:U[32]||(U[32]=Y=>j.$emit("toggle-approval-panel")),onOpenReview:U[33]||(U[33]=Y=>j.$emit("open-review")),onOpenPathAuthorization:U[34]||(U[34]=Y=>j.$emit("open-path-authorization")),onToggleGoalMode:U[35]||(U[35]=Y=>j.$emit("toggle-goal-mode"))},null,8,["open","is-connected","uploading","streaming-message","thinking-mode","run-mode","model-menu-open","model-options","current-model-key","tool-menu-open","tool-settings","tool-settings-loading","settings-open","mode-menu-open","compressing","current-conversation-id","icon-style","tool-category-icon","block-upload","block-tool-toggle","block-realtime-terminal","block-focus-panel","block-token-panel","block-compress-conversation","block-conversation-review","execution-mode-enabled","goal-mode-armed","goal-running"]),E("div",{class:"permission-switcher",onClick:U[38]||(U[38]=Ne(()=>{},["stop"]))},[E("button",{type:"button",class:"permission-switcher__btn",disabled:!s.isConnected||s.streamingMessage,onClick:U[36]||(U[36]=Y=>j.$emit("open-versioning-dialog"))},[...U[48]||(U[48]=[E("span",null,"版本控制",-1)])],8,sJ),E("div",nJ,[E("button",{type:"button",class:"permission-switcher__btn",disabled:!s.isConnected,title:ue.value?"计划模式下权限与执行环境已锁定,网络权限仍可调整":Ge.value?"只读模式下执行环境已锁定为沙箱":"",onClick:U[37]||(U[37]=Y=>j.$emit("toggle-permission-menu"))},[ue.value||Ge.value?(F(),$("svg",rJ,[...U[49]||(U[49]=[E("rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2"},null,-1),E("path",{d:"M7 11V7a5 5 0 0 1 10 0v4"},null,-1)])])):ge("",!0),E("span",null,ae(v_.value),1),s.executionModeEnabled?(F(),$("span",{key:1,class:ke(["permission-switcher__exec",{"permission-switcher__exec--warn":s.currentExecutionMode==="direct"}])},ae(Bt.value),3)):ge("",!0),E("span",{class:ke(["permission-switcher__caret",{open:s.permissionMenuOpen}])},"",2)],8,iJ),s.permissionMenuOpen?(F(),$("div",{key:0,class:ke(["permission-switcher__menu",{"permission-switcher__menu--split":s.executionModeEnabled}])},[E("div",{class:ke(["permission-switcher__group",{"permission-switcher__group--disabled":ue.value}])},[E("div",oJ,[U[50]||(U[50]=hn(" 权限",-1)),ue.value?(F(),$("span",aJ,"计划模式锁定")):ge("",!0)]),(F(!0),$(Ie,null,tt(s.permissionOptions,Y=>(F(),$("button",{key:`permission-${Y.value}`,type:"button",class:ke(["permission-switcher__item",{active:Y.value===s.currentPermissionMode}]),disabled:ue.value,onClick:Te=>j.$emit("change-permission-mode",Y.value)},[E("span",cJ,ae(Y.label),1),E("span",uJ,ae(Y.description),1)],10,lJ))),128))],2),s.executionModeEnabled?(F(),$("div",{key:0,class:ke(["permission-switcher__group",{"permission-switcher__group--disabled":pt.value}])},[E("div",hJ,[U[51]||(U[51]=hn(" 执行环境 ",-1)),ue.value?(F(),$("span",dJ,"计划模式锁定")):Ge.value?(F(),$("span",fJ,"只读模式锁定")):ge("",!0)]),(F(!0),$(Ie,null,tt(s.executionModeOptions,Y=>(F(),$("button",{key:`execution-${Y.value}`,type:"button",class:ke(["permission-switcher__item",{active:Y.value===s.currentExecutionMode}]),disabled:pt.value,onClick:Te=>j.$emit("change-execution-mode",Y.value)},[E("span",{class:ke(["permission-switcher__item-label",{"permission-switcher__item-label--warn":Y.value==="direct"}])},ae(Y.label),3),E("span",gJ,ae(Y.description),1)],10,pJ))),128))],2)):ge("",!0),s.networkPermissionEnabled?(F(),$("div",{key:1,class:ke(["permission-switcher__group",{"permission-switcher__group--disabled":s.currentExecutionMode==="direct"}])},[U[52]||(U[52]=E("div",{class:"permission-switcher__group-title"},"网络权限",-1)),(F(!0),$(Ie,null,tt(s.networkPermissionOptions,Y=>(F(),$("button",{key:`network-${Y.value}`,type:"button",class:ke(["permission-switcher__item",{active:Y.value===s.currentNetworkPermission}]),disabled:s.currentExecutionMode==="direct",onClick:Te=>j.$emit("change-network-permission",Y.value)},[E("span",{class:ke(["permission-switcher__item-label",{"permission-switcher__item-label--warn":Y.value==="full"}])},ae(Y.label),3),E("span",vJ,ae(Y.description),1)],10,mJ))),128))],2)):ge("",!0)],2)):ge("",!0)])]),E("div",{class:"context-usage-switcher",onClick:U[40]||(U[40]=Ne(()=>{},["stop"]))},[E("button",{type:"button",class:"context-usage-switcher__btn",disabled:!s.isConnected,onClick:U[39]||(U[39]=Y=>j.$emit("toggle-token-panel"))},[E("span",{class:"context-usage-ring",style:Ke({"--context-progress":`${Mr.value}%`,"--context-ring-color":Hc.value}),"aria-hidden":"true"},[...U[53]||(U[53]=[E("span",{class:"context-usage-ring__inner"},null,-1)])],4)],8,yJ),E("div",bJ,[E("div",null,ae($c.value)+"已用",1),E("div",null,ae(oo.value),1)])])],512)],512))}}),wJ=Qt(SJ,[["__scopeId","data-v-1f19a619"]]),kJ={class:"effort-header"},CJ={class:"header-state header-idle"},TJ={class:"slider-zone"},AJ={class:"level-labels"},lo=20,EJ=200,MJ=at({__name:"EffortSlider",props:{modelValue:{}},emits:["update:modelValue"],setup(s,{emit:e}){const t=["low","medium","high","xhigh","max"],n=s,i=e,r=pe(null),o=pe(null),a=pe(null),c=[],l=(H,G)=>{c[G]=H??null},u=pe(0),h=pe(2),d=pe(2),p=pe(!1),m=pe(!1);let v=0,g=0,y=0;const b=ye(()=>n.modelValue===null),_=H=>H/(t.length-1),w=H=>`calc(${lo}px + (100% - ${lo*2}px) * ${_(H)})`,S=H=>lo+(u.value-lo*2)*_(H),C=H=>{const G=u.value;if(G<=lo*2)return 0;const ee=(H-lo)/(G-lo*2);return Math.max(0,Math.min(t.length-1,Math.round(ee*(t.length-1))))},T=H=>{const G=r.value;if(!G)return lo;const ee=G.getBoundingClientRect(),ie=H-ee.left;return Math.max(lo,Math.min(ee.width-lo,ie))},k=H=>H<.5?2*H*H:1-(-2*H+2)**2/2,A=H=>{const G=u.value>lo*2,ee=G?`${H}px`:w(h.value),ie=o.value;ie&&(ie.style.transform=`translate(calc(${ee} - 50%), -50%)`);const ve=a.value;ve&&(ve.style.clipPath=`inset(0 calc(100% - (${ee})) 0 0 round 17px)`);for(let le=0;le<t.length;le++){const oe=c[le];if(!oe)continue;const I=G?S(le)<=H:le<=h.value;oe.classList.toggle("covered",I)}},M=()=>{g&&(cancelAnimationFrame(g),g=0)},R=H=>{M(),y=H,A(H)},P=H=>{const G=y;if(G===H)return;M();const ee=performance.now(),ie=ve=>{const le=Math.min(1,(ve-ee)/EJ);y=G+(H-G)*k(le),A(y),le<1?g=requestAnimationFrame(ie):g=0};g=requestAnimationFrame(ie)},L=(H=!1)=>{const G=S(h.value);d.value=h.value,H&&u.value>lo*2?P(G):R(G)},z=()=>{i("update:modelValue",t[h.value])},Q=H=>{var G;p.value=!0,m.value=!1,v=H.clientX,(G=r.value)==null||G.setPointerCapture(H.pointerId),h.value=C(T(H.clientX)),z(),L(!0)},W=H=>{if(p.value&&(!m.value&&Math.abs(H.clientX-v)>3&&(m.value=!0),m.value)){const G=T(H.clientX);M(),y=G,A(G),d.value=C(G)}},V=H=>{if(p.value){if(p.value=!1,m.value){m.value=!1,h.value=C(T(H.clientX)),z(),L(!0);return}L(!0)}},N=()=>{i("update:modelValue",b.value?t[h.value]:null)},O=()=>{var H;u.value=((H=r.value)==null?void 0:H.clientWidth)??0,L()};return Xe(()=>n.modelValue,H=>{if(H===null)return;const G=t.indexOf(H);G<0||G===h.value||(h.value=G,L(!1))},{immediate:!0}),Cn(()=>{O(),window.addEventListener("resize",O)}),xn(()=>{M(),window.removeEventListener("resize",O)}),(H,G)=>(F(),$("div",{class:ke(["effort-slider",{"is-default":b.value,"live-drag":m.value}])},[E("div",kJ,[E("div",CJ,[G[1]||(G[1]=E("span",{class:"header-title"},"推理强度",-1)),E("span",{class:ke(["default-toggle",{checked:b.value}]),onClick:Ne(N,["stop"])},[G[0]||(G[0]=E("span",{class:"default-label"},"默认",-1)),Qe(HF,{checked:b.value,size:14},null,8,["checked"])],2)]),G[2]||(G[2]=E("div",{class:"header-state header-drag"},[E("span",null,"更高效"),E("span",null,"更智能")],-1))]),E("div",TJ,[E("div",{ref_key:"trackRef",ref:r,class:"track",onPointerdown:Q,onPointermove:W,onPointerup:V,onPointercancel:V},[E("div",{ref_key:"fillRef",ref:a,class:"fill-stack"},[(F(),$(Ie,null,tt(t,(ee,ie)=>E("div",{key:`lv-${ie}`,class:ke(["fill-layer",[`lv-${ie}`,{on:ie===d.value}]])},null,2)),64))],512),(F(),$(Ie,null,tt(t,(ee,ie)=>E("div",{key:`dot-${ie}`,class:"dot",ref_for:!0,ref:ve=>l(ve,ie),style:Ke({left:w(ie)})},null,4)),64)),E("div",{ref_key:"knobRef",ref:o,class:"knob"},null,512)],544),E("div",AJ,[(F(),$(Ie,null,tt(t,(ee,ie)=>E("span",{key:`label-${ie}`,class:ke(["level-label",{active:ie===d.value}]),style:Ke({left:w(ie)})},ae(ee),7)),64))])])],2))}}),xJ=Qt(MJ,[["__scopeId","data-v-cf3df9ee"]]),IJ={class:"confirm-modal"},RJ={class:"confirm-title"},LJ={class:"confirm-message"},PJ={key:0,class:"confirm-warning"},OJ=at({__name:"ConfirmDialog",setup(s){const e=Vs(),{confirmDialog:t}=Ii(e),n=i=>e.resolveConfirm(i);return(i,r)=>(F(),Wt(us,{name:"confirm-dialog-fade"},{default:Vt(()=>{var o;return[(o=We(t))!=null&&o.visible?(F(),$("div",{key:0,class:"confirm-overlay",onClick:r[2]||(r[2]=Ne(a=>{var c;return((c=We(t))==null?void 0:c.closeOnBackdrop)!==!1&&n(!1)},["self"]))},[E("div",IJ,[E("div",RJ,ae(We(t).title||"确认操作"),1),E("div",LJ,ae(We(t).message),1),We(t).warningText?(F(),$("div",PJ,ae(We(t).warningText),1)):ge("",!0),E("div",{class:ke(["confirm-actions",{"confirm-actions--confirm-left":We(t).confirmOnLeft}])},[E("button",{type:"button",class:"confirm-button confirm-button--cancel",onClick:r[0]||(r[0]=a=>n(!1))},ae(We(t).cancelText||"取消"),1),E("button",{type:"button",class:ke(["confirm-button confirm-button--confirm",We(t).confirmVariant==="danger"?"confirm-button--danger":"confirm-button--primary"]),onClick:r[1]||(r[1]=a=>n(!0))},ae(We(t).confirmText||"确认"),3)],2)])])):ge("",!0)]}),_:1}))}});let U_=null;function Km(){const s=Vs(),e=o=>{U_=o,o||t()},t=()=>{const o=s.easterEgg;o.cleanupTimer&&clearTimeout(o.cleanupTimer);const a=U_;a&&(a.innerHTML=""),s.clearEasterEgg()},n=(o=!1)=>{const a=s.easterEgg;a.cleanupTimer&&(clearTimeout(a.cleanupTimer),s.setEasterEggState({cleanupTimer:null}));const c=a.instance;if(!c)return t(),Promise.resolve();if(a.destroying)return a.destroyPromise||Promise.resolve();s.setEasterEggState({destroying:!0});let l;try{l=c.destroy({immediate:o,payload:a.payload,root:U_})}catch(h){return console.warn("销毁彩蛋时发生错误:",h),s.setEasterEggState({destroying:!1}),t(),Promise.resolve()}const u=()=>{s.setEasterEggState({destroyPromise:null,destroying:!1}),t()};if(l&&typeof l.then=="function"){const h=l.then(()=>{u()}).catch(d=>{console.warn("彩蛋清理失败:",d),u()});return s.setEasterEggState({destroyPromise:h}),h}return u(),Promise.resolve()},i=async(o,a={},c)=>{const l=window.EasterEggRegistry;if(!l){console.warn("EasterEggRegistry 尚未加载,无法播放彩蛋");return}if(!l.has(o)){console.warn("未注册的彩蛋 effect:",o),await n(!0);return}const u=U_;if(!u){console.warn("未找到彩蛋根节点");return}await n(!0),s.setEasterEggState({active:!0,effect:o,payload:a});const h=l.start(o,{root:u,payload:a,app:c});if(!h){t();return}s.setEasterEggState({instance:h,destroyPromise:null,destroying:!1}),s.easterEgg.cleanupTimer&&clearTimeout(s.easterEgg.cleanupTimer);const d=Math.max(8,Number(a==null?void 0:a.duration_seconds)||45),p=setTimeout(()=>{const m=n(!1);m&&typeof m.catch=="function"&&m.catch(()=>{})},d*1e3);s.setEasterEggState({cleanupTimer:p}),a!=null&&a.message};return{registerOverlayRoot:e,handlePayload:async(o,a)=>{let c=o;if(typeof o=="string")try{c=JSON.parse(o)}catch{console.warn("无法解析彩蛋结果:",o);return}if(!c||typeof c!="object")return;if(!c.success){c.error&&console.warn("彩蛋触发失败:",c.error),await n(!0);return}const l=(c.effect||"").toLowerCase();if(!l){console.warn("彩蛋结果缺少 effect 字段");return}await i(l,c,a)},startEffect:i,destroyEffect:n,finishCleanup:t}}const DJ=at({__name:"EasterEggOverlay",setup(s){const e=Vs(),{easterEgg:t}=Ii(e),n=pe(null),i=Km();return Cn(()=>{i.registerOverlayRoot(n.value)}),xn(()=>{i.registerOverlayRoot(null)}),(r,o)=>(F(),$("div",{class:ke(["easter-egg-overlay",{active:We(t).active}]),"aria-hidden":"true",ref_key:"overlayRoot",ref:n},null,2))}}),NJ=["disabled"],BJ=at({__name:"FileContextMenu",props:{downloadFile:{type:Function},downloadFolder:{type:Function}},setup(s){const e=s,t=Tc(),{contextMenu:n}=Ii(t),i=()=>{const l=n.value.node;!l||l.type!=="file"||!l.path||(e.downloadFile(l.path),t.hideContextMenu())},r=()=>{const l=n.value.node;!l||l.type!=="folder"||!l.path||(e.downloadFolder(l.path),t.hideContextMenu())},o=l=>{if(!n.value.visible)return;const u=l.target;u&&u.closest(".context-menu")||t.hideContextMenu()},a=()=>{n.value.visible&&t.hideContextMenu()},c=l=>{l.key==="Escape"&&n.value.visible&&t.hideContextMenu()};return Cn(()=>{document.addEventListener("click",o),window.addEventListener("scroll",a,!0),document.addEventListener("keydown",c)}),xn(()=>{document.removeEventListener("click",o),window.removeEventListener("scroll",a,!0),document.removeEventListener("keydown",c)}),(l,u)=>We(n).visible?(F(),$("div",{key:0,class:"context-menu",style:Ke({top:We(n).y+"px",left:We(n).x+"px"}),onClick:u[0]||(u[0]=Ne(()=>{},["stop"]))},[We(n).node&&We(n).node.type==="file"?(F(),$("button",{key:0,type:"button",onClick:Ne(i,["stop"])}," 下载文件 ")):ge("",!0),We(n).node&&We(n).node.type==="folder"?(F(),$("button",{key:1,type:"button",disabled:!We(n).node.path,onClick:Ne(r,["stop"])}," 下载压缩包 ",8,NJ)):ge("",!0)],4)):ge("",!0)}}),FJ={key:0,class:"quota-toast"},$J={class:"quota-toast-label"},HJ=at({__name:"QuotaToast",setup(s){const e=Vs(),{quotaToast:t}=Ii(e),n=()=>e.dismissQuotaToast();return(i,r)=>(F(),Wt(us,{name:"quota-toast-fade"},{default:Vt(()=>[We(t)?(F(),$("div",FJ,[E("span",$J,ae(We(t).message),1),E("button",{type:"button",class:"toast-close","aria-label":"关闭通知",onClick:n},"×")])):ge("",!0)]),_:1}))}}),UJ={class:"app-toast-body"},WJ={key:0,class:"app-toast-title"},zJ={class:"app-toast-message"},jJ=["onClick"],VJ=at({__name:"ToastStack",setup(s){const e=Vs(),{toastQueue:t}=Ii(e),n=i=>e.dismissToast(i);return(i,r)=>(F(),$("div",{class:ke(["toast-stack",{"toast-stack--empty":!We(t).length}])},[Qe(Vv,{name:"quota-toast-fade",tag:"div"},{default:Vt(()=>[(F(!0),$(Ie,null,tt(We(t),o=>(F(),$("div",{key:o.id,class:ke(["app-toast",o.type?`app-toast--${o.type}`:""])},[E("div",UJ,[o.title?(F(),$("div",WJ,ae(o.title),1)):ge("",!0),E("div",zJ,ae(o.message),1)]),o.closable!==!1?(F(),$("button",{key:0,type:"button",class:"toast-close","aria-label":"关闭通知",onClick:a=>n(o.id)}," × ",8,jJ)):ge("",!0)],2))),128))]),_:1})],2))}}),GJ={class:"app-root"},qJ=at({__name:"AppShell",props:{downloadFile:{type:Function},downloadFolder:{type:Function}},setup(s){return(e,t)=>(F(),$("div",GJ,[Qe(HJ),Qe(VJ),Qe(OJ),OF(e.$slots,"default"),Qe(DJ),Qe(BJ,{"download-file":s.downloadFile,"download-folder":s.downloadFolder},null,8,["download-file","download-folder"])]))}}),KJ=br(()=>wt(()=>import("./PersonalizationDrawer.js"),__vite__mapDeps([0,1,2,3,4,5,6]))),QJ=br(()=>wt(()=>import("./ImagePicker.js"),__vite__mapDeps([7,1,3,8]))),XJ=br(()=>wt(()=>import("./ConversationReviewDialog.js"),__vite__mapDeps([9,1,3,10]))),YJ=br(()=>wt(()=>import("./SubAgentActivityDialog.js"),__vite__mapDeps([11,1,3,5,2,4,12]))),JJ=br(()=>wt(()=>import("./BackgroundCommandDialog.js"),__vite__mapDeps([13,1,3,5,2,4]))),ZJ=br(()=>wt(()=>import("./VersioningDialog.js"),__vite__mapDeps([14,1,3,15]))),eZ=br(()=>wt(()=>import("./UserQuestionDialog.js"),__vite__mapDeps([16,1,3,17]))),tZ=br(()=>wt(()=>import("./PlanApprovalDialog.js"),__vite__mapDeps([18,1,3,5,2,4,19]))),sZ=br(()=>wt(()=>import("./TutorialOverlay.js"),__vite__mapDeps([20,1,3,5,2,4]))),nZ=br(()=>wt(()=>import("./NewUserTutorialPrompt.js"),__vite__mapDeps([21,1,3,22]))),iZ=br(()=>wt(()=>import("./GoalProgressDialog.js"),__vite__mapDeps([23,1,3,24]))),rZ=br(()=>wt(()=>import("./WorkflowDemoShell.js"),__vite__mapDeps([25,1,3,5,2,4,26]))),oZ={ChatArea:sU,ConversationSidebar:J8,ToolApprovalPanel:EW,GitChangesPanel:lz,TerminalPanel:uj,TokenDrawer:jj,PersonalizationDrawer:KJ,QuickMenu:gL,InputComposer:wJ,EffortSlider:xJ,AppShell:qJ,StatusAvatar:bD,ImagePicker:QJ,ConversationReviewDialog:XJ,SubAgentActivityDialog:YJ,BackgroundCommandDialog:JJ,VersioningDialog:ZJ,UserQuestionDialog:eZ,PlanApprovalDialog:tZ,TutorialOverlay:sZ,NewUserTutorialPrompt:nZ,GoalProgressDialog:iZ,WorkflowDemoShell:rZ},aZ=Object.freeze({alignLeft:"/static/icons/align-left.svg",arrowLeft:"/static/icons/arrow-left.svg",bot:"/static/icons/bot.svg",book:"/static/icons/book.svg",brain:"/static/icons/brain.svg",brainCog:"/static/icons/brain-cog.svg",camera:"/static/icons/camera.svg",check:"/static/icons/check.svg",chatBubble:"/static/icons/chat-bubble.svg",messageQuestion:"/static/icons/message-circle-question-mark.svg",checkbox:"/static/icons/checkbox.svg",chevronDown:"/static/icons/chevron-down.svg",circleAlert:"/static/icons/circle-alert.svg",clipboard:"/static/icons/clipboard.svg",copy:"/static/icons/copy.svg",clock:"/static/icons/clock.svg",eye:"/static/icons/eye.svg",file:"/static/icons/file.svg",filePen:"/static/icons/file-pen.svg",flag:"/static/icons/flag.svg",folder:"/static/icons/folder.svg",folderClosed:"/static/icons/folder-closed.svg",folderOpen:"/static/icons/folder-open.svg",gitBranch:"/static/icons/git-branch.svg",globe:"/static/icons/globe.svg",hammer:"/static/icons/hammer.svg",info:"/static/icons/info.svg",laptop:"/static/icons/laptop.svg",layers:"/static/icons/layers.svg",keyboard:"/static/icons/keyboard.svg",layoutGrid:"/static/icons/layout-grid.svg",menu:"/static/icons/menu.svg",mic:"/static/icons/mic.svg",mcpLogo:"/static/icons/mcp-logo.svg",monitor:"/static/icons/monitor.svg",navigation:"/static/icons/navigation.svg",notebook:"/static/icons/notebook.svg",notebookPen:"/static/icons/notebook-pen.svg",notebookSearch:"/static/icons/notebook-search.svg",octagon:"/static/icons/octagon.svg",pencil:"/static/icons/pencil.svg",play:"/static/icons/play.svg",plus:"/static/icons/plus.svg",python:"/static/icons/python.svg",recycle:"/static/icons/recycle.svg",refreshCw:"/static/icons/refresh-cw.svg",save:"/static/icons/save.svg",search:"/static/icons/search.svg",settings:"/static/icons/settings.svg",sparkles:"/static/icons/sparkles.svg",stickyNote:"/static/icons/sticky-note.svg",terminal:"/static/icons/terminal.svg",trash:"/static/icons/trash.svg",triangleAlert:"/static/icons/triangle-alert.svg",bell:"/static/icons/bell.svg",user:"/static/icons/user.svg",userPen:"/static/icons/user-pen.svg",workflow:"/static/icons/workflow.svg",wrench:"/static/icons/wrench.svg",x:"/static/icons/x.svg",zap:"/static/icons/zap.svg"}),lZ=Object.freeze({close_sub_agent:"bot",create_file:"file",create_skill:"sparkles",manage_personalization:"userPen",ask_user:"messageQuestion",create_folder:"folder",create_sub_agent:"bot",delete_file:"trash",extract_webpage:"globe",write_file:"pencil",edit_file:"pencil",vlm_analyze:"camera",ocr_image:"camera",read_file:"book",read_skill:"book",rename_file:"pencil",run_command:"terminal",save_webpage:"save",sleep:"clock",todo_create:"stickyNote",todo_update_task:"check",terminal_input:"keyboard",terminal_session:"monitor",terminal_snapshot:"clipboard",unfocus_file:"eye",update_memory:"brain",recall_project_memory:"notebook",search_project_memory:"notebookSearch",update_project_memory:"notebookPen",conversation_search:"search",conversation_review:"book",get_sub_agent_status:"bot",web_search:"search",trigger_easter_egg:"sparkles",list_mcp_servers:"mcpLogo",view_image:"camera",view_video:"eye",activate_workflow:"workflow",report_workflow_stage:"workflow",choose_workflow_branch:"workflow",get_workflow_status:"workflow",deactivate_workflow:"workflow",list_workflows:"workflow",save_workflow:"workflow",submit_plan:"clipboard",terminate_sub_agent:"bot"}),cZ=Object.freeze({network:"globe",mcp:"mcpLogo",file_edit:"pencil",personalization:"userPen",communication:"messageQuestion",read_focus:"eye",skills:"sparkles",terminal_realtime:"monitor",terminal_command:"terminal",memory:"brain",todo:"stickyNote",sub_agent:"bot",easter_egg:"sparkles"}),_D="agents_workspace_mode",uZ=()=>{try{const s=window.localStorage.getItem(_D);return s==="host"||s==="docker"?s:null}catch{return null}},uT=s=>{try{window.localStorage.setItem(_D,s?"host":"docker")}catch{}},SD="agents_new_conversation_type",hZ=()=>{try{return window.localStorage.getItem(SD)==="multi_agent"?"multi_agent":"agent"}catch{return"agent"}},wD=s=>{try{window.localStorage.setItem(SD,s)}catch{}},WI=uZ(),dZ=hZ();function fZ(){return{initialRouteResolved:!1,dropToolEvents:!1,workflowDemoRoute:"",currentConversationType:null,newConversationType:dZ,agentTypeMenuOpen:!1,multiAgentIndexRebuildTriggered:!1,usePollingMode:!0,waitingForSubAgent:!1,waitingForBackgroundCommand:!1,hideSystemMessages:!0,preparingTools:new Map,activeTools:new Map,toolActionIndex:new Map,toolStacks:new Map,taskInProgress:!1,runningStateReconcileTimer:null,_runningStateIdleStreak:0,runningWorkspaceTasksRefreshTimer:null,runtimeQueuedMessages:[],runtimeGuidanceFallbackQueue:[],runtimeQueueSuppressedMessageIds:new Set,runtimeGuidanceSuppressedTextCounts:{},runtimeQueueLimit:5,runtimeQueueAutoSendInProgress:!1,runtimeQueueSyncLockKey:"",runtimeQueueSyncLockUntil:0,projectGitSummary:null,projectGitSummaryRefreshTimer:null,terminalCountRefreshTimer:null,projectGitSummaryRefreshing:!1,gitChangesPanelOpen:!1,gitChangesLoading:!1,gitChangesError:"",gitChangesContext:3,gitChangesFileContexts:{},gitChangesFoldContexts:{},gitChangesDiff:null,terminalPanelOpen:!1,terminalSessions:{},terminalActiveSession:"",terminalSessionLogs:{},terminalHydrated:{},terminalCount:0,previousTerminalCount:0,rightSplitRatio:.5,composerReservedHeight:80,lastHistoryLoadedConversationId:null,searchRequestSeq:0,searchActiveQuery:"",compressing:!1,compressionInProgress:!1,compressionConversationId:null,compressionMode:"",compressionStage:"",compressionError:"",compressionToastId:null,skipConversationLoadedEvent:!1,skipConversationHistoryReload:!1,_scrollListenerReady:!1,historyLoading:!1,historyLoadingFor:null,historyLoadSeq:0,blankHeroActive:!1,blankHeroExiting:!1,blankWelcomeText:"",lastBlankConversationId:null,titleTypingText:"",titleTypingTarget:"",titleTypingTimer:null,titleReady:!1,suppressTitleTyping:!1,headerMenuOpen:!1,blankWelcomePool:["有什么可以帮忙的?","想了解些热点吗?","要我帮你完成作业吗?","整点代码?","随便聊点什么?","想让我帮你整理一下思路吗?","要不要我帮你写个小工具?","发我一句话,我来接着做。","我来给你画幅画?","想看小猫吗?","有什么难题丢过来吧。","想不想看个有意思的?","来,说说你的需求~"],mobileViewportQuery:null,modeMenuOpen:!1,modelMenuOpen:!1,permissionMenuOpen:!1,currentPermissionMode:"unrestricted",pendingPermissionMode:"",executionModeEnabled:!1,currentExecutionMode:"sandbox",pendingExecutionMode:"",networkPermissionEnabled:!1,currentNetworkPermission:"restricted",pendingNetworkPermission:"",networkPermissionOptions:[{value:"restricted",label:"受限",description:"仅允许本地回环访问,外部网络不可用"},{value:"full",label:"完全开放",description:"允许所有出站和入站网络连接"}],workModeMenuOpen:!1,currentWorkMode:"plan",workModeOptions:[{value:"plan",label:"计划",description:"只制定计划,批准后执行"},{value:"ask",label:"询问",description:"先讨论确认,再开工"},{value:"execute",label:"执行",description:"自行补全细节,直接开工"}],pathAuthorizationDialogOpen:!1,pathAuthorizationMode:"writable",pathAuthorizationWritableDraft:"",pathAuthorizationReadableDraft:"",pathAuthorizationDraft:"",pathAuthorizationSaving:!1,versioningHostMode:WI==="host",dockerProjectMode:WI==="docker",hostWorkspaces:[],currentHostWorkspaceId:"",defaultHostWorkspaceId:"",hostWorkspaceSwitching:!1,hostWorkspaceCreatePath:"",hostWorkspaceCreateLabel:"",hostWorkspaceCreateSubmitting:!1,hostWorkspaceCreateError:"",hostWorkspaceManageSubmitting:!1,versioningEnabled:!1,versioningTrackingMode:"conversation_only",versioningMode:"overwrite",versioningDialogOpen:!1,versioningLoading:!1,versioningCheckpoints:[],versioningSelectedSeq:null,versioningSelectedDetail:null,versioningDetailLoading:!1,versioningRestoring:!1,versioningRestoreMode:"overwrite",versioningInitializingBackupToastId:null,permissionModeOptions:[{value:"readonly",label:"只读",description:"仅允许读取/搜索类工具,禁止修改工作区"},{value:"approval",label:"批准",description:"对工作区文件进行修改的工具需用户批准后才会执行"},{value:"auto_approval",label:"自动审核",description:"工作区内写入直通,高风险操作由后台审核智能体自动审批"},{value:"unrestricted",label:"无限制",description:"保持当前默认行为,不额外拦截"}],executionModeOptions:[{value:"sandbox",label:"沙箱",description:"所有指令会在系统沙箱中执行"},{value:"direct",label:"完全访问权限",description:"所有指令会在宿主机直接执行"}],pendingToolApprovals:[],decidingApprovalIds:[],pendingUserQuestions:[],pendingPlanApprovals:[],answeringPlanApprovalIds:[],userQuestionDialogVisible:!1,userQuestionMinimized:!1,userQuestionActiveIndex:0,answeringUserQuestionIds:[],userQuestionOriginalTitle:"",userQuestionTitleBlinkTimer:null,userQuestionTitleBlinkRed:!0,autoApprovalFeedLines:[],autoApprovalFinalMessage:"",autoApprovalTitle:"自动审批记录",approvalAutoCloseTimer:null,imageEntries:[],imageLoading:!1,videoEntries:[],videoLoading:!1,conversationHasImages:!1,conversationHasVideos:!1,conversationListRequestSeq:0,conversationListRefreshToken:0,connectionHeartbeatTimer:null,connectionHeartbeatActive:!1,connectionHeartbeatFailCount:0,connectionHeartbeatSeq:0,connectionHeartbeatLastLatencyMs:0,connectionHeartbeatLastError:"",connectionHeartbeatLastStatusCode:null,connectionHeartbeatLastChangeAt:0,connectionHeartbeatInFlight:!1,connectionHeartbeatFailThreshold:3,connectionHeartbeatRequestTimeoutMs:5e3,connectionHeartbeatIntervalMs:8e3,connectionHeartbeatDisconnectedIntervalMs:1e3,composerDraftSaveTimer:null,composerDraftDirty:!1,composerDraftLastSyncedContent:"",composerDraftFetchSeq:0,icons:aZ,toolCategoryIcons:cZ,reviewDialogOpen:!1,reviewSelectedConversationId:null,reviewSubmitting:!1,reviewPreviewLines:[],reviewPreviewLoading:!1,reviewPreviewError:null,reviewPreviewLimit:20,reviewSendToModel:!0,reviewGeneratedPath:null,reviewConversations:[],reviewListLoading:!1,reviewListLoadingMore:!1,reviewListHasMore:!1,reviewListOffset:0,reviewListLimit:20,tutorialPromptVisible:!1,tutorialPromptLoading:!1,tutorialPromptUsername:"",dragOverActive:!1,_boundDragEnter:null,_boundDragOver:null,_boundDragLeave:null,_boundDrop:null,_manualScrollSuppressUntil:0,_escapedByUserScroll:!1,_autoRelockCooldownUntil:0,stickIsAtBottom:!0,stickIsNearBottom:!0}}const pZ={web_search:"search",conversation_search:"search",extract_webpage:"webpage",save_webpage:"save",write_file:"write",edit_file:"write",read_file:"read",read_skill:"read",conversation_review:"read",vlm_analyze:"camera",ocr_image:"camera",view_image:"camera",view_video:"camera",create_skill:"skill",trigger_easter_egg:"skill",terminal_session:"monitor",terminal_input:"keyboard",terminal_snapshot:"clipboard",sleep:"sleep",run_command:"command",update_memory:"brain",recall_project_memory:"notebook",search_project_memory:"search",update_project_memory:"notebook",todo_create:"note",todo_update_task:"check",create_sub_agent:"subagent",close_sub_agent:"subagent",terminate_sub_agent:"subagent",get_sub_agent_status:"subagent",manage_personalization:"persona",ask_user:"ask",list_mcp_servers:"mcp"};function gZ(s){const e=String(s||"");return e.startsWith("mcp__")?"mcp":pZ[e]||"command"}function mZ(s){var n,i,r;if(!Array.isArray(s))return[];let e=-1;for(let o=s.length-1;o>=0;o--){if(((n=s[o])==null?void 0:n.type)==="tool"){e=o;break}if(((i=s[o])==null?void 0:i.type)==="thinking")break}if(e<0)return[];let t=e;for(;t>0&&((r=s[t-1])==null?void 0:r.type)==="tool";)t--;return s.slice(t,e+1)}const zI=new Set(["preparing","running","pending","queued","awaiting_approval","pending_approval","awaiting_user_answer"]),vZ=new Set(["completed","failed","timeout","terminated","cancelled"]),yZ={...Ko(z2,["isConnected","socket","stopRequested","projectPath","agentVersion","thinkingMode","runMode","reasoningEffort"]),...b_(Tc,["contextMenu","fileTree","expandedFolders","todoList"]),...b_(Bo,{qdHasContent:"hasContent",qdExpanded:"expanded"}),...Ko(Bo,{qdUserCollapsed:"userCollapsed"}),...Ko(Vs,["sidebarCollapsed","chatDisplayMode","rightWidth","rightCollapsed","isResizing","resizingPanel","minPanelWidth","maxPanelWidth","quotaToast","toastQueue","confirmDialog","easterEgg","isMobileViewport","mobileOverlayMenuOpen","activeMobileOverlay"]),...Ko(vr,["conversations","conversationsLoading","hasMoreConversations","loadingMoreConversations","currentConversationId","currentConversationTitle","searchQuery","searchTimer","searchResults","searchGroups","conversationInsertAnimations","conversationListAnimationMode","pendingDeletingConversationIds","searchActive","searchInProgress","searchMoreAvailable","searchOffset","searchTotal","conversationsOffset","conversationsLimit","runningWorkspaceTasks","acknowledgedCompletedTaskIds","workspaceGroups"]),...Ko(Qi,["currentModelKey"]),...b_(Qi,["models"]),...Ko(oE,["messages","currentMessageIndex","streamingMessage","expandedBlocks","autoScrollEnabled","userScrolling","thinkingScrollLocks"]),...Ko(q0,["inputMessage","inputLineCount","inputIsMultiline","inputIsFocused","quickMenuOpen","toolMenuOpen","settingsOpen","imagePickerOpen","videoPickerOpen","selectedImages","selectedVideos","selectedFiles","goalModeArmed","goalRunning","goalProgress","goalDialogOpen"]),resolvedRunMode(){const s=this.runMode==="deep"?"thinking":this.runMode;return["fast","thinking"].includes(s)?s:this.thinkingMode?"thinking":"fast"},headerRunModeOptions(){return[{value:"fast",label:"快速模式",desc:"低思考,响应更快"},{value:"thinking",label:"思考模式",desc:"持续推理,适合复杂任务"}]},headerRunModeLabel(){const s=this.headerRunModeOptions.find(e=>e.value===this.resolvedRunMode);return s?s.label:"快速模式"},showEffortSlider(){var e;const s=Qi();return this.resolvedRunMode==="thinking"&&!!((e=s.currentModel)!=null&&e.supportsReasoningEffort)},currentModelLabel(){var e;return((e=Qi().currentModel)==null?void 0:e.label)||"未选择模型"},policyUiBlocks(){return No().uiBlocks||{}},adminDisabledModels(){return No().disabledModelSet},modelOptions(){const s=this.adminDisabledModels||new Set;return(this.models||[]).map(t=>({...t,disabled:s.has(t.key)}))},titleRibbonVisible(){return!this.isMobileViewport&&this.chatDisplayMode==="chat"},chatContainerStyle(){const e=Number(this.composerReservedHeight||0),t=Number.isFinite(e)?Math.max(90,Math.round(e)):90,n=Math.max(0,t-90);return{"--composer-base-height":"calc(90px + var(--app-bottom-inset, 0px))","--composer-reserved-height":`calc(${t}px + var(--app-bottom-inset, 0px))`,"--composer-growth-height":`${n}px`}},...Ko(I2,["preparingTools","activeTools","toolActionIndex","toolStacks","toolSettings","toolSettingsLoading"]),...Ko(R2,["tokenPanelCollapsed","currentContextTokens","currentConversationTokens","projectStorage","containerStatus","containerNetRate","usageQuota"]),...Ko(N2,["focusedFiles"]),...Ko(D2,["uploading","mediaUploading"]),...b_(j2,{monitorIsLocked:s=>s.isLocked}),displayModeSwitchDisabled(){return!!this.policyUiBlocks.block_virtual_monitor},compressionActiveForCurrentConversation(){if(!this.compressionInProgress&&!this.compressing)return!1;const s=this.compressionConversationId;return s?s===this.currentConversationId:!!this.currentConversationId},displayLockEngaged(){return this.compressionActiveForCurrentConversation},currentWorkspaceHasRunningTask(){return!(this.versioningHostMode||this.dockerProjectMode)||!this.currentHostWorkspaceId?!1:(Array.isArray(this.runningWorkspaceTasks)?this.runningWorkspaceTasks:[]).some(e=>{const t=String((e==null?void 0:e.status)||"");return(e==null?void 0:e.workspace_id)===this.currentHostWorkspaceId&&(e==null?void 0:e.conversation_id)===this.currentConversationId&&["pending","running","cancel_requested"].includes(t)})},streamingUi(){return this.streamingMessage||this.hasPendingToolActions()},composerBusy(){const s=this.monitorIsLocked&&this.chatDisplayMode==="monitor";return this.streamingUi||this.taskInProgress||s||this.stopRequested||this.compressionActiveForCurrentConversation},activeSubAgentCount(){const s=oh(),e=Array.isArray(s.subAgents)?s.subAgents:[],t=new Set(["completed","failed","timeout","terminated"]);return e.filter(n=>{const i=String((n==null?void 0:n.status)||"").toLowerCase();return!t.has(i)}).length},mainChatIdle(){return!this.streamingUi&&!this.stopRequested&&!(this.monitorIsLocked&&this.chatDisplayMode==="monitor")&&!this.compressionActiveForCurrentConversation},composerStreamingForInput(){return this.composerBusy&&!this.displayLockEngaged},composerHeroActive(){return(this.blankHeroActive||this.blankHeroExiting)&&!this.composerInteractionActive},showStatusAvatar(){var s;return((s=qs().form)==null?void 0:s.show_status_avatar)!==!1},composerInteractionActive(){const s=!!(this.inputMessage&&this.inputMessage.trim().length>0),e=Array.isArray(this.selectedImages)&&this.selectedImages.length>0,t=Array.isArray(this.selectedFiles)&&this.selectedFiles.length>0;return this.quickMenuOpen||s||e||t},showScrollToBottomButton(){return this.chatDisplayMode==="chat"&&!this.stickIsNearBottom},rightPanelsStyle(){const s=Math.min(this.rightWidth||420,600),e=this.terminalPanelOpen,t=this.gitChangesPanelOpen,n=this.rightSplitRatio??.5,i=Math.max(.15,Math.min(.85,Number(n)||.5));let r;return e&&t?r=`${i}fr 2px ${1-i}fr`:e?r="1fr 0px 0fr":t?r="0fr 0px 1fr":r="0fr 0px 0fr",{width:s+"px",gridTemplateRows:r}},avatarStatus(){var p,m,v,g,y,b;const s=Array.isArray(this.messages)?this.messages:[],e=(()=>{var _;for(let w=s.length-1;w>=0;w--)if(((_=s[w])==null?void 0:_.role)==="assistant")return s[w];return null})(),t=oh(),n=cm(),i=_=>(Array.isArray(_)?_:[]).filter(w=>{if(!w)return!1;const S=String((w==null?void 0:w.status)||"").toLowerCase();return S?!vZ.has(S):!0}).length,r=i(t.subAgents),o=i(n.commands),a=(()=>{const _=[];return o>0&&_.push(`${o}个后台指令`),r>0&&_.push(`${r}个后台智能体`),_.length?`${_.join("")}运行中...`:""})(),c=!!((p=qs().form)!=null&&p.tool_intent_enabled),l=!!e&&(e.currentStreamingType==="thinking"||e.activeThinkingId!=null);let u=[];e&&(u=mZ(e.actions||[]).filter(w=>{var C,T;const S=String(((C=w==null?void 0:w.tool)==null?void 0:C.status)||"").toLowerCase();return((T=w==null?void 0:w.tool)==null?void 0:T.awaiting_content)||!S||zI.has(S)})),u.length===0&&(u=[...Array.from(((v=(m=this.preparingTools)==null?void 0:m.values)==null?void 0:v.call(m))||[]),...Array.from(((y=(g=this.activeTools)==null?void 0:g.values)==null?void 0:y.call(g))||[])].map(w=>(w==null?void 0:w.type)==="tool"?w:{type:"tool",tool:w}).filter(w=>{const S=w==null?void 0:w.tool;if(!S)return!1;const C=String((S==null?void 0:S.status)||"").toLowerCase();return(S==null?void 0:S.awaiting_content)||!C||zI.has(C)}));const h=this.preparingTools&&this.preparingTools.size>0||this.activeTools&&this.activeTools.size>0,d=this.streamingMessage||this.taskInProgress||this.waitingForSubAgent||this.waitingForBackgroundCommand||this.stopRequested||h||u.length>0||r>0||o>0;if(l)return{mode:"think",toolKeys:[],toolTexts:[],text:"思考中...",tracking:!1};if(u.length>0){const _=u.map(T=>{var k;return gZ((k=T==null?void 0:T.tool)==null?void 0:k.name)}),w=T=>{if(!T)return"";const k=T.intent_full||"",A=T.intent_rendered||"";return k&&A===k?k:""},S=u.map(T=>c?w(T==null?void 0:T.tool):"");let C=S[0]||"";return u.length>1?C=S[0]||"":C||(C=c?w((b=u[0])==null?void 0:b.tool):""),{mode:"tool",toolKeys:_,toolTexts:S,text:C,tracking:!1}}if(d){let _=a;if(!_){const w=e&&e.awaitingFirstContent?e:null;w&&(_=typeof w.generatingLabel=="string"&&w.generatingLabel.trim()||"")}return{mode:"work",toolKeys:[],toolTexts:[],text:_,tracking:!1}}return{mode:"idle",toolKeys:[],toolTexts:[],text:"",tracking:!0}}};function Oe(...s){}const nl=(...s)=>{};function bZ(){var s;if(typeof window>"u")return!1;try{const e=window.__GOAL_MODE_DEBUG__;if(e===!0||e==="1")return!0;if(e===!1||e==="0")return!1;const t=(s=window.localStorage)==null?void 0:s.getItem("goalModeDebug");return t==="1"||t==="true"}catch{return!1}}let jI=0;function yn(s,e={}){if(bZ())try{jI+=1;const t={event:s,seq:jI,client_ts:new Date().toISOString(),...e};console.log("[GOAL_MODE_DEBUG]",s,t),typeof fetch<"u"&&fetch("/api/client_debug_log",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}).catch(()=>{})}catch{}}const _Z={inputMessage(){this.autoResizeInput(),typeof this.scheduleComposerDraftPersist=="function"&&this.scheduleComposerDraftPersist("watch-input-message")},messages:{deep:!0,handler(){this.refreshBlankHeroState()}},composerBusy(s,e){e&&!s&&typeof this.tryAutoSendRuntimeQueuedMessages=="function"&&this.tryAutoSendRuntimeQueuedMessages("watch-composer-idle")},runtimeQueuedMessages:{deep:!0,handler(s){Array.isArray(s)&&s.length>0&&!this.composerBusy&&typeof this.tryAutoSendRuntimeQueuedMessages=="function"&&this.tryAutoSendRuntimeQueuedMessages("watch-runtime-queue")}},runtimeGuidanceFallbackQueue:{deep:!0,handler(s){Array.isArray(s)&&s.length>0&&!this.composerBusy&&typeof this.tryAutoSendRuntimeQueuedMessages=="function"&&this.tryAutoSendRuntimeQueuedMessages("watch-runtime-guidance-fallback")}},currentConversationTitle(s,e){const t=s&&s.trim()||"";if(this.suppressTitleTyping){this.titleTypingText=t,this.titleTypingTarget=t;return}const n=e&&e.trim()||this.titleTypingText&&this.titleTypingText.trim()||"",o=(!n||n==="新对话")&&!(!t||t==="新对话");this.startTitleTyping(t,{animate:o})},currentConversationId:{immediate:!1,handler(s,e){if(s!==e){vr().setCurrentConversationId(s||null),s||(this.currentConversationType=null,vr().$patch({multiAgentMode:!1}));const t=Bo();t.resetTransient(),s||(t.setEditedFiles([]),Tc().setTodoList(null))}if(Oe("currentConversationId 变化",{oldValue:e,newValue:s,skipConversationHistoryReload:this.skipConversationHistoryReload}),nl("watch:currentConversationId",{oldValue:e,newValue:s,skipConversationHistoryReload:this.skipConversationHistoryReload,historyLoading:this.historyLoading,historyLoadingFor:this.historyLoadingFor,historyLoadSeq:this.historyLoadSeq}),this.refreshBlankHeroState(),this.logMessageState("watch:currentConversationId",{oldValue:e,newValue:s,skipConversationHistoryReload:this.skipConversationHistoryReload}),e!==s&&!this.taskInProgress&&!this.composerBusy&&typeof this.restoreComposerDraftState=="function"&&this.restoreComposerDraftState(`watch-conversation-id:${e||"none"}->${s||"none"}`),!s||typeof s!="string"||s.startsWith("temp_")){this.versioningEnabled=!1,this.versioningTrackingMode="conversation_only";return}if(this.fetchVersioningStatus(s,{silent:!0}),this.skipConversationHistoryReload){this.skipConversationHistoryReload=!1;return}e&&s===e||(this.fetchAndDisplayHistory(),this.fetchConversationTokenStatistics(),this.updateCurrentContextTokens())}},fileTree:{immediate:!0,handler(s){this.monitorSyncDesktop(s)}}},SZ={pushToast:()=>{},autoResizeInput:()=>{},focusComposer:()=>{},isConnected:()=>!1,executeCommand:async()=>({success:!1,message:"命令通道不可用"}),downloadResource:async()=>{}};function wZ(s){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(s):s.replace(/["\\]/g,"\\$&")}function kZ(s){const e=document.createElement("textarea");return e.innerHTML=s,e.value}const CZ=dn("chatActions",{state:()=>({dependencies:{...SZ}}),actions:{registerDependencies(s){this.dependencies={...this.dependencies,...s}},async copyActionContent(s,e){var n;const t=(n=s&&(s.content||s.text||""))==null?void 0:n.toString();if(!t)return this.dependencies.pushToast({title:"复制失败",message:"未找到可复制的内容",type:"warning"}),!1;try{return await this.copyText(t),this.dependencies.pushToast({title:"已复制",message:e?`片段 ${e} 已复制到剪贴板`:"内容已复制到剪贴板",type:"success"}),!0}catch(i){return console.warn("复制失败:",i),this.dependencies.pushToast({title:"复制失败",message:"浏览器阻止了复制操作,请手动选择文本后复制。",type:"error"}),!1}},async copyCodeBlock(s){if(!s)return!1;const e=`[data-code-id="${wZ(s)}"]`,t=document.querySelector(e);if(!t)return this.dependencies.pushToast({title:"复制失败",message:"未找到对应的代码块",type:"warning"}),!1;const n=t.getAttribute("data-original-code"),i=n?kZ(n):t.textContent||"";if(!i.trim())return this.dependencies.pushToast({title:"复制失败",message:"代码内容为空",type:"warning"}),!1;try{return await this.copyText(i),this.dependencies.pushToast({title:"已复制",message:"代码已复制到剪贴板",type:"success"}),!0}catch(r){return console.warn("复制代码失败:",r),this.dependencies.pushToast({title:"复制失败",message:"浏览器阻止了复制操作,请手动复制。",type:"error"}),!1}},applyActionContent(s){return!s||!s.content?(this.dependencies.pushToast({title:"无法应用",message:"缺少可应用的内容",type:"warning"}),!1):(q0().setInputMessage(s.content),this.dependencies.autoResizeInput(),this.dependencies.focusComposer(),this.dependencies.pushToast({title:"已填充",message:"请检查内容后发送以应用这些修改。",type:"info"}),!0)},async runCommand(s){var t;const e=(t=s&&(s.command||s.content))==null?void 0:t.toString();if(!e)return this.dependencies.pushToast({title:"无法执行",message:"没有可执行的命令内容",type:"warning"}),!1;if(!this.dependencies.isConnected())return this.dependencies.pushToast({title:"连接已断开",message:"请重新连接后再试。",type:"error"}),!1;try{const n=await this.dependencies.executeCommand(e);return n&&n.success===!1?(this.dependencies.pushToast({title:"命令执行失败",message:n.message||"请稍后重试",type:"error"}),!1):(this.dependencies.pushToast({title:"命令已执行",message:e,type:"success"}),!0)}catch(n){return this.dependencies.pushToast({title:"命令执行失败",message:(n==null?void 0:n.message)||"请稍后重试",type:"error"}),!1}},async downloadActionAttachment(s){return!s||!s.path?(this.dependencies.pushToast({title:"下载失败",message:"没有可下载的目标文件",type:"warning"}),!1):this.downloadFile(s.path)},async downloadFile(s){if(!s)return this.dependencies.pushToast({title:"下载失败",message:"没有提供有效的文件路径",type:"warning"}),!1;const e=`/api/download/file?path=${encodeURIComponent(s)}`,t=s.split("/").pop()||"file";try{return await this.dependencies.downloadResource(e,t),!0}catch(n){return console.warn("下载失败:",n),n&&n.message&&this.dependencies.pushToast({title:"下载失败",message:n.message,type:"error"}),!1}},async copyText(s){if(navigator.clipboard&&navigator.clipboard.writeText){await navigator.clipboard.writeText(s);return}const e=document.createElement("textarea");e.value=s,e.style.position="fixed",e.style.top="-1000px",document.body.appendChild(e),e.focus(),e.select(),document.execCommand("copy"),document.body.removeChild(e)}}}),a0=new WeakMap;let W_=null;const VI=new WeakMap;let z_=null,BC=0;const FC=1200,GI=new Map;let $C=0;const HC=160,qI=new Map;function wS(){if(typeof window>"u")return!1;try{const s=Number(window.__SHOW_TAG_DRAWING_UNTIL__||0);return Date.now()<=s}catch{return!1}}function TZ(){var s;if(typeof window>"u")return!1;try{const e=window.__SCROLL_DEBUG__;if(e===!1||e==="0")return!1;if(e===!0||e==="1"){const i=Number(window.__SHOW_TAG_DRAWING_UNTIL__||0);return Date.now()<=i}const t=(s=window.localStorage)==null?void 0:s.getItem("scrollDebug");if(t==="0"||t==="false")return!1;if(t==="1"||t==="true"){const i=Number(window.__SHOW_TAG_DRAWING_UNTIL__||0);return Date.now()<=i}const n=Number(window.__SHOW_TAG_DRAWING_UNTIL__||0);return Date.now()<=n}catch{return!1}}function AZ(){var s;if(typeof window>"u")return!1;try{const e=window.__SHOW_HTML_SCROLL_TRACE__;if(e===!1||e==="0")return!1;if(e===!0||e==="1")return!0;const t=(s=window.localStorage)==null?void 0:s.getItem("showHtmlScrollTrace");return t==="0"||t==="false"?!1:t==="1"||t==="true"}catch{return!1}}function kS(s){const e=s.scrollTop,t=s.scrollHeight,n=s.clientHeight,i=Math.max(0,t-n),r=t-e-n;return{top:e,height:t,client:n,maxTop:i,remain:r}}function Fv(s){const e=s.querySelectorAll(".chat-inline-card--html, .chat-inline-html"),t=e[e.length-1]||null;if(!t)return null;const n=s.getBoundingClientRect(),i=t.getBoundingClientRect();return{count:e.length,y:Math.round(i.y),h:Math.round(i.height),bottomInArea:Math.round(i.bottom-n.top),areaClient:Math.round(s.clientHeight),belowViewportPx:Math.round(Math.max(0,i.bottom-n.bottom))}}function hT(s){return!!s.querySelector("show_html, show-html, .chat-inline-html, .chat-inline-card--html")}function Uh(s,e={},t=s,n=280){if(!AZ()||$C>=HC)return;const i=Date.now(),r=qI.get(t)||0;if(!(n>0&&i-r<n)){if(qI.set(t,i),$C+=1,$C===HC){console.warn("[SHOW_HTML_SCROLL_TRACE]","log-limit-reached",{max:HC});return}console.log("[SHOW_HTML_SCROLL_TRACE]",s,e)}}function Ai(s,e={},t=s,n=120){if(!TZ()||BC>=FC)return;const i=Date.now(),r=GI.get(t)||0;if(!(n>0&&i-r<n)){if(GI.set(t,i),BC+=1,BC===FC){console.warn("[SCROLL_DEBUG]","log-limit-reached",{max:FC});return}console.log("[SCROLL_DEBUG]",s,e)}}function dT(s,e){var u,h;const t=(u=s.getMessagesAreaElement)==null?void 0:u.call(s);if(!t){Ai("scrollToBottom:skip:no-area");return}const n=wS()&&hT(t);if(!(t.scrollHeight>t.clientHeight+2)&&!(e!=null&&e.force)&&!n){Ai("scrollToBottom:skip:no-overflow",{top:t.scrollTop,height:t.scrollHeight,client:t.clientHeight,drawingActive:n},"scrollToBottom:skip:no-overflow",120),typeof s._setScrollingFlag=="function"&&s._setScrollingFlag(!1),e!=null&&e.resetUserScrolling&&((h=s.chatSetScrollState)==null||h.call(s,{userScrolling:!1}));return}const r=`t${Date.now()}_${Math.random().toString(36).slice(2,7)}`,o=kS(t);(n||e!=null&&e.force)&&Uh("scrollToBottom:start",{traceId:r,drawingActive:n,force:!!(e!=null&&e.force),...o,lastShowHtml:Fv(t)},"scrollToBottom:start",120);const a=(e==null?void 0:e.behavior)==="smooth"&&typeof t.scrollTo=="function";Ai("scrollToBottom:start",{traceId:r,useSmooth:a,ignoreUserScrolling:!!(e!=null&&e.ignoreUserScrolling),resetUserScrolling:!!(e!=null&&e.resetUserScrolling),autoScrollEnabled:s.autoScrollEnabled,userScrolling:s.userScrolling,drawingActive:n,top:t.scrollTop,height:t.scrollHeight,client:t.clientHeight},`scrollToBottom:start:${r}`,0);let c=a0.get(t);c||(c={rafId:null,settleTimer:null},a0.set(t,c)),c.rafId!==null&&(cancelAnimationFrame(c.rafId),c.rafId=null),c.settleTimer&&(clearTimeout(c.settleTimer),c.settleTimer=null);const l=()=>{if(s.userScrolling&&!(e!=null&&e.ignoreUserScrolling)&&!(e!=null&&e.force)){Ai("scrollToBottom:skip:user-scrolling",{traceId:r,userScrolling:s.userScrolling},"scrollToBottom:skip:user-scrolling",0),typeof s._setScrollingFlag=="function"&&s._setScrollingFlag(!1);return}a?t.scrollTo({top:t.scrollHeight+(n?Math.max(24,Math.floor(t.clientHeight*.12)):0),behavior:"smooth"}):t.scrollTop=t.scrollHeight+(n?Math.max(24,Math.floor(t.clientHeight*.12)):0),(n||e!=null&&e.force)&&Uh("scrollToBottom:after-write",{traceId:r,drawingActive:n,...kS(t),lastShowHtml:Fv(t)},"scrollToBottom:after-write",120);let d=0,p=-1;const m=Date.now(),v=n?30:12,g=n?3200:1200,y=()=>{d+=1,t.scrollTop=t.scrollHeight+(n?Math.max(24,Math.floor(t.clientHeight*.12)):0);const b=t.scrollHeight,_=b-t.scrollTop-t.clientHeight,w=Math.abs(b-p)<=2,S=Math.abs(_)<=2,C=Date.now()-m,T=!S&&d<v&&C<g;if(Ai("scrollToBottom:settle",{traceId:r,settleCount:d,settleElapsed:C,currentHeight:b,lastHeight:p,remain:_,atBottom:S,heightStable:w,top:t.scrollTop,client:t.clientHeight},"scrollToBottom:settle",80),p=b,T){(n||e!=null&&e.force)&&(d===1||d===4||d===6)&&Uh("scrollToBottom:settle-progress",{traceId:r,settleCount:d,drawingActive:n,currentHeight:b,top:t.scrollTop,client:t.clientHeight,remain:_},"scrollToBottom:settle-progress",140),c.settleTimer=setTimeout(y,80);return}typeof s._setScrollingFlag=="function"&&s._setScrollingFlag(!1),e!=null&&e.resetUserScrolling&&(typeof s.chatSetScrollState=="function"?s.chatSetScrollState({userScrolling:!1}):"userScrolling"in s&&(s.userScrolling=!1)),c.settleTimer=null,(n||e!=null&&e.force||Math.abs(_)>2)&&Uh("scrollToBottom:done",{traceId:r,settleCount:d,drawingActive:n,...kS(t),lastShowHtml:Fv(t)},"scrollToBottom:done",120),Ai("scrollToBottom:done",{traceId:r,settleCount:d,top:t.scrollTop,height:t.scrollHeight,client:t.clientHeight},`scrollToBottom:done:${r}`,0)};c.settleTimer=setTimeout(y,120)};typeof s._setScrollingFlag=="function"&&s._setScrollingFlag(!0),c.rafId=requestAnimationFrame(()=>{c.rafId=null,Ai("scrollToBottom:raf",{traceId:r},`scrollToBottom:raf:${r}`,0),l(),!c.settleTimer&&typeof s._setScrollingFlag=="function"&&s._setScrollingFlag(!1)})}function KI(s){var i,r,o;const e=typeof s.isOutputActive=="function"?s.isOutputActive():!0,t=(i=s.getMessagesAreaElement)==null?void 0:i.call(s),n=!!t&&wS()&&hT(t);if(!n&&wS()&&t&&Uh("conditional:skip-stale-drawing-window",{...kS(t),lastShowHtml:Fv(t)},"conditional:skip-stale-drawing-window",260),Ai("conditional:start",{active:e,autoScrollEnabled:s.autoScrollEnabled,userScrolling:s.userScrolling,drawingActive:n},"conditional:start",120),s.autoScrollEnabled===!0&&e){if(!t){Ai("conditional:skip:no-area");return}if(z_&&z_!==t){Ai("conditional:area-replaced",{},"conditional:area-replaced",0);const m=a0.get(z_);m&&m.rafId!==null&&(cancelAnimationFrame(m.rafId),m.rafId=null),m&&m.settleTimer&&(clearTimeout(m.settleTimer),m.settleTimer=null)}z_=t;const a=t.scrollTop,c=t.scrollHeight,l=t.clientHeight,u=c-a-l;if(c<=l+2&&!n){(r=s.chatSetScrollState)==null||r.call(s,{userScrolling:!1}),Ai("conditional:skip:no-overflow",{top:a,height:c,client:l,remain:u},"conditional:skip:no-overflow",120);return}c<=l+2&&n&&Uh("conditional:drawing-no-overflow-but-continue",{top:a,height:c,client:l,remain:u,drawingActive:n},"conditional:drawing-no-overflow-but-continue",200);const h=a0.get(t);if((h==null?void 0:h.rafId)!==null||h!=null&&h.settleTimer){Ai("conditional:skip:pending-task",{hasRaf:(h==null?void 0:h.rafId)!==null,hasSettle:!!(h!=null&&h.settleTimer),top:a,height:c,client:l},"conditional:skip:pending-task",100);return}const d=Date.now(),p=VI.get(t)||0;if(d-p<90){Ai("conditional:skip:too-frequent",{gap:d-p,top:a,height:c,client:l},"conditional:skip:too-frequent",100);return}VI.set(t,d),s.userScrolling===!0&&((o=s.chatSetScrollState)==null||o.call(s,{userScrolling:!1})),W_!==null&&cancelAnimationFrame(W_),W_=requestAnimationFrame(()=>{var b;W_=null;const m=(b=s.getMessagesAreaElement)==null?void 0:b.call(s);if(!m||m!==t){Ai("conditional:skip:area-changed-before-raf",{},"conditional:skip:area-changed-before-raf",0);return}const v=m.scrollHeight,g=m.clientHeight,y=wS()&&hT(m);if(v<=g+2&&!y){Ai("conditional:skip:no-overflow-before-raf",{top:m.scrollTop,height:v,client:g},"conditional:skip:no-overflow-before-raf",100);return}y&&Uh("conditional:raf-scroll",{top:m.scrollTop,height:v,client:g,remain:v-m.scrollTop-g,lastShowHtml:Fv(m)},"conditional:raf-scroll",140),Ai("conditional:raf-scroll",{top:m.scrollTop,height:v,client:g},"conditional:raf-scroll",80),dT(s,{ignoreUserScrolling:!0,resetUserScrolling:!0,force:y})})}}function EZ(s){var e;s.autoScrollEnabled||(e=s.chatSetScrollState)==null||e.call(s,{autoScrollEnabled:!0,userScrolling:!1})}function MZ(s,e){var n,i;if(!e||!((n=s.thinkingScrollLocks)!=null&&n.get(e)))return;const t=(i=s.getThinkingContentElement)==null?void 0:i.call(s,e);t&&(t.scrollTop=t.scrollHeight)}/*! @license DOMPurify 3.4.8 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.4.8/LICENSE */function QI(s,e){(e==null||e>s.length)&&(e=s.length);for(var t=0,n=Array(e);t<e;t++)n[t]=s[t];return n}function xZ(s){if(Array.isArray(s))return s}function IZ(s,e){var t=s==null?null:typeof Symbol<"u"&&s[Symbol.iterator]||s["@@iterator"];if(t!=null){var n,i,r,o,a=[],c=!0,l=!1;try{if(r=(t=t.call(s)).next,e!==0)for(;!(c=(n=r.call(t)).done)&&(a.push(n.value),a.length!==e);c=!0);}catch(u){l=!0,i=u}finally{try{if(!c&&t.return!=null&&(o=t.return(),Object(o)!==o))return}finally{if(l)throw i}}return a}}function RZ(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function LZ(s,e){return xZ(s)||IZ(s,e)||PZ(s,e)||RZ()}function PZ(s,e){if(s){if(typeof s=="string")return QI(s,e);var t={}.toString.call(s).slice(8,-1);return t==="Object"&&s.constructor&&(t=s.constructor.name),t==="Map"||t==="Set"?Array.from(s):t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?QI(s,e):void 0}}const kD=Object.entries,XI=Object.setPrototypeOf,OZ=Object.isFrozen,DZ=Object.getPrototypeOf,NZ=Object.getOwnPropertyDescriptor;let sr=Object.freeze,$o=Object.seal,up=Object.create,CD=typeof Reflect<"u"&&Reflect,fT=CD.apply,pT=CD.construct;sr||(sr=function(e){return e});$o||($o=function(e){return e});fT||(fT=function(e,t){for(var n=arguments.length,i=new Array(n>2?n-2:0),r=2;r<n;r++)i[r-2]=arguments[r];return e.apply(t,i)});pT||(pT=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return new e(...n)});const wh=kn(Array.prototype.forEach),BZ=kn(Array.prototype.lastIndexOf),YI=kn(Array.prototype.pop),Xf=kn(Array.prototype.push),FZ=kn(Array.prototype.splice),Hi=Array.isArray,Qm=kn(String.prototype.toLowerCase),UC=kn(String.prototype.toString),JI=kn(String.prototype.match),Yf=kn(String.prototype.replace),ZI=kn(String.prototype.indexOf),$Z=kn(String.prototype.trim),HZ=kn(Number.prototype.toString),UZ=kn(Boolean.prototype.toString),eR=typeof BigInt>"u"?null:kn(BigInt.prototype.toString),tR=typeof Symbol>"u"?null:kn(Symbol.prototype.toString),Js=kn(Object.prototype.hasOwnProperty),km=kn(Object.prototype.toString),si=kn(RegExp.prototype.test),Jf=WZ(TypeError);function kn(s){return function(e){e instanceof RegExp&&(e.lastIndex=0);for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return fT(s,e,n)}}function WZ(s){return function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return pT(s,t)}}function Pt(s,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Qm;if(XI&&XI(s,null),!Hi(e))return s;let n=e.length;for(;n--;){let i=e[n];if(typeof i=="string"){const r=t(i);r!==i&&(OZ(e)||(e[n]=r),i=r)}s[i]=!0}return s}function zZ(s){for(let e=0;e<s.length;e++)Js(s,e)||(s[e]=null);return s}function yi(s){const e=up(null);for(const n of kD(s)){var t=LZ(n,2);const i=t[0],r=t[1];Js(s,i)&&(Hi(r)?e[i]=zZ(r):r&&typeof r=="object"&&r.constructor===Object?e[i]=yi(r):e[i]=r)}return e}function jZ(s){switch(typeof s){case"string":return s;case"number":return HZ(s);case"boolean":return UZ(s);case"bigint":return eR?eR(s):"0";case"symbol":return tR?tR(s):"Symbol()";case"undefined":return km(s);case"function":case"object":{if(s===null)return km(s);const e=s,t=Ta(e,"toString");if(typeof t=="function"){const n=t(e);return typeof n=="string"?n:km(n)}return km(s)}default:return km(s)}}function Ta(s,e){for(;s!==null;){const n=NZ(s,e);if(n){if(n.get)return kn(n.get);if(typeof n.value=="function")return kn(n.value)}s=DZ(s)}function t(){return null}return t}function VZ(s){try{return si(s,""),!0}catch{return!1}}const sR=sr(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),WC=sr(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),zC=sr(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),GZ=sr(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),jC=sr(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),qZ=sr(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),nR=sr(["#text"]),iR=sr(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","command","commandfor","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns"]),VC=sr(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),rR=sr(["accent","accentunder","align","bevelled","close","columnalign","columnlines","columnspacing","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lquote","lspace","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),j_=sr(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),KZ=$o(/{{[\w\W]*|^[\w\W]*}}/g),QZ=$o(/<%[\w\W]*|^[\w\W]*%>/g),XZ=$o(/\${[\w\W]*/g),YZ=$o(/^data-[\-\w.\u00B7-\uFFFF]+$/),JZ=$o(/^aria-[\-\w]+$/),oR=$o(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),ZZ=$o(/^(?:\w+script|data):/i),eee=$o(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),tee=$o(/^html$/i),see=$o(/^[a-z][.\w]*(-[.\w]+)+$/i),wa={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},nee=function(){return typeof window>"u"?null:window},iee=function(e,t){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let n=null;const i="data-tt-policy-suffix";t&&t.hasAttribute(i)&&(n=t.getAttribute(i));const r="dompurify"+(n?"#"+n:"");try{return e.createPolicy(r,{createHTML(o){return o},createScriptURL(o){return o}})}catch{return console.warn("TrustedTypes policy "+r+" could not be created."),null}},aR=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function TD(){let s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:nee();const e=Je=>TD(Je);if(e.version="3.4.8",e.removed=[],!s||!s.document||s.document.nodeType!==wa.document||!s.Element)return e.isSupported=!1,e;let t=s.document;const n=t,i=n.currentScript;s.DocumentFragment;const r=s.HTMLTemplateElement,o=s.Node,a=s.Element,c=s.NodeFilter,l=s.NamedNodeMap;l===void 0&&(s.NamedNodeMap||s.MozNamedAttrMap),s.HTMLFormElement;const u=s.DOMParser,h=s.trustedTypes,d=a.prototype,p=Ta(d,"cloneNode"),m=Ta(d,"remove"),v=Ta(d,"nextSibling"),g=Ta(d,"childNodes"),y=Ta(d,"parentNode"),b=Ta(d,"shadowRoot"),_=Ta(d,"attributes"),w=o&&o.prototype?Ta(o.prototype,"nodeType"):null,S=o&&o.prototype?Ta(o.prototype,"nodeName"):null;if(typeof r=="function"){const Je=t.createElement("template");Je.content&&Je.content.ownerDocument&&(t=Je.content.ownerDocument)}let C,T="",k=0;const A=function(ne){if(k>0)throw Jf('The configured TRUSTED_TYPES_POLICY.createHTML must not call DOMPurify.sanitize, as that causes infinite recursion. Do not pass a policy whose createHTML wraps DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted Types" section of the README.');k++;try{return C.createHTML(ne)}finally{k--}},M=t,R=M.implementation,P=M.createNodeIterator,L=M.createDocumentFragment,z=M.getElementsByTagName,Q=n.importNode;let W=aR();e.isSupported=typeof kD=="function"&&typeof y=="function"&&R&&R.createHTMLDocument!==void 0;const V=KZ,N=QZ,O=XZ,H=YZ,G=JZ,ee=ZZ,ie=eee,ve=see;let le=oR,oe=null;const I=Pt({},[...sR,...WC,...zC,...jC,...nR]);let K=null;const X=Pt({},[...iR,...VC,...rR,...j_]);let J=Object.seal(up(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),he=null,be=null;const Re=Object.seal(up(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let rt=!0,st=!0,et=!1,De=!0,xe=!1,se=!0,ce=!1,de=!1,we=!1,Le=!1,He=!1,yt=!1,At=!0,Nt=!1;const It="user-content-";let Jt=!0,$t=!1,As={},ut=null;const Hs=Pt({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let hl=null;const In=Pt({},["audio","video","img","source","image","track"]);let Uo=null;const nr=Pt({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Qs="http://www.w3.org/1998/Math/MathML",Yn="http://www.w3.org/2000/svg",Rn="http://www.w3.org/1999/xhtml";let ir=Rn,Wo=!1,Ln=null;const ma=Pt({},[Qs,Yn,Rn],UC);let zo=Pt({},["mi","mo","mn","ms","mtext"]),io=Pt({},["annotation-xml"]);const dl=Pt({},["title","style","font","a","script"]);let Jn=null;const jo=["application/xhtml+xml","text/html"],va="text/html";let fe=null,me=null;const Ce=t.createElement("form"),dt=function(ne){return ne instanceof RegExp||ne instanceof Function},qt=function(){let ne=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(me&&me===ne)return;(!ne||typeof ne!="object")&&(ne={}),ne=yi(ne),Jn=jo.indexOf(ne.PARSER_MEDIA_TYPE)===-1?va:ne.PARSER_MEDIA_TYPE,fe=Jn==="application/xhtml+xml"?UC:Qm,oe=Js(ne,"ALLOWED_TAGS")&&Hi(ne.ALLOWED_TAGS)?Pt({},ne.ALLOWED_TAGS,fe):I,K=Js(ne,"ALLOWED_ATTR")&&Hi(ne.ALLOWED_ATTR)?Pt({},ne.ALLOWED_ATTR,fe):X,Ln=Js(ne,"ALLOWED_NAMESPACES")&&Hi(ne.ALLOWED_NAMESPACES)?Pt({},ne.ALLOWED_NAMESPACES,UC):ma,Uo=Js(ne,"ADD_URI_SAFE_ATTR")&&Hi(ne.ADD_URI_SAFE_ATTR)?Pt(yi(nr),ne.ADD_URI_SAFE_ATTR,fe):nr,hl=Js(ne,"ADD_DATA_URI_TAGS")&&Hi(ne.ADD_DATA_URI_TAGS)?Pt(yi(In),ne.ADD_DATA_URI_TAGS,fe):In,ut=Js(ne,"FORBID_CONTENTS")&&Hi(ne.FORBID_CONTENTS)?Pt({},ne.FORBID_CONTENTS,fe):Hs,he=Js(ne,"FORBID_TAGS")&&Hi(ne.FORBID_TAGS)?Pt({},ne.FORBID_TAGS,fe):yi({}),be=Js(ne,"FORBID_ATTR")&&Hi(ne.FORBID_ATTR)?Pt({},ne.FORBID_ATTR,fe):yi({}),As=Js(ne,"USE_PROFILES")?ne.USE_PROFILES&&typeof ne.USE_PROFILES=="object"?yi(ne.USE_PROFILES):ne.USE_PROFILES:!1,rt=ne.ALLOW_ARIA_ATTR!==!1,st=ne.ALLOW_DATA_ATTR!==!1,et=ne.ALLOW_UNKNOWN_PROTOCOLS||!1,De=ne.ALLOW_SELF_CLOSE_IN_ATTR!==!1,xe=ne.SAFE_FOR_TEMPLATES||!1,se=ne.SAFE_FOR_XML!==!1,ce=ne.WHOLE_DOCUMENT||!1,Le=ne.RETURN_DOM||!1,He=ne.RETURN_DOM_FRAGMENT||!1,yt=ne.RETURN_TRUSTED_TYPE||!1,we=ne.FORCE_BODY||!1,At=ne.SANITIZE_DOM!==!1,Nt=ne.SANITIZE_NAMED_PROPS||!1,Jt=ne.KEEP_CONTENT!==!1,$t=ne.IN_PLACE||!1,le=VZ(ne.ALLOWED_URI_REGEXP)?ne.ALLOWED_URI_REGEXP:oR,ir=typeof ne.NAMESPACE=="string"?ne.NAMESPACE:Rn,zo=Js(ne,"MATHML_TEXT_INTEGRATION_POINTS")&&ne.MATHML_TEXT_INTEGRATION_POINTS&&typeof ne.MATHML_TEXT_INTEGRATION_POINTS=="object"?yi(ne.MATHML_TEXT_INTEGRATION_POINTS):Pt({},["mi","mo","mn","ms","mtext"]),io=Js(ne,"HTML_INTEGRATION_POINTS")&&ne.HTML_INTEGRATION_POINTS&&typeof ne.HTML_INTEGRATION_POINTS=="object"?yi(ne.HTML_INTEGRATION_POINTS):Pt({},["annotation-xml"]);const Ee=Js(ne,"CUSTOM_ELEMENT_HANDLING")&&ne.CUSTOM_ELEMENT_HANDLING&&typeof ne.CUSTOM_ELEMENT_HANDLING=="object"?yi(ne.CUSTOM_ELEMENT_HANDLING):up(null);if(J=up(null),Js(Ee,"tagNameCheck")&&dt(Ee.tagNameCheck)&&(J.tagNameCheck=Ee.tagNameCheck),Js(Ee,"attributeNameCheck")&&dt(Ee.attributeNameCheck)&&(J.attributeNameCheck=Ee.attributeNameCheck),Js(Ee,"allowCustomizedBuiltInElements")&&typeof Ee.allowCustomizedBuiltInElements=="boolean"&&(J.allowCustomizedBuiltInElements=Ee.allowCustomizedBuiltInElements),xe&&(st=!1),He&&(Le=!0),As&&(oe=Pt({},nR),K=up(null),As.html===!0&&(Pt(oe,sR),Pt(K,iR)),As.svg===!0&&(Pt(oe,WC),Pt(K,VC),Pt(K,j_)),As.svgFilters===!0&&(Pt(oe,zC),Pt(K,VC),Pt(K,j_)),As.mathMl===!0&&(Pt(oe,jC),Pt(K,rR),Pt(K,j_))),Re.tagCheck=null,Re.attributeCheck=null,Js(ne,"ADD_TAGS")&&(typeof ne.ADD_TAGS=="function"?Re.tagCheck=ne.ADD_TAGS:Hi(ne.ADD_TAGS)&&(oe===I&&(oe=yi(oe)),Pt(oe,ne.ADD_TAGS,fe))),Js(ne,"ADD_ATTR")&&(typeof ne.ADD_ATTR=="function"?Re.attributeCheck=ne.ADD_ATTR:Hi(ne.ADD_ATTR)&&(K===X&&(K=yi(K)),Pt(K,ne.ADD_ATTR,fe))),Js(ne,"ADD_URI_SAFE_ATTR")&&Hi(ne.ADD_URI_SAFE_ATTR)&&Pt(Uo,ne.ADD_URI_SAFE_ATTR,fe),Js(ne,"FORBID_CONTENTS")&&Hi(ne.FORBID_CONTENTS)&&(ut===Hs&&(ut=yi(ut)),Pt(ut,ne.FORBID_CONTENTS,fe)),Js(ne,"ADD_FORBID_CONTENTS")&&Hi(ne.ADD_FORBID_CONTENTS)&&(ut===Hs&&(ut=yi(ut)),Pt(ut,ne.ADD_FORBID_CONTENTS,fe)),Jt&&(oe["#text"]=!0),ce&&Pt(oe,["html","head","body"]),oe.table&&(Pt(oe,["tbody"]),delete he.tbody),ne.TRUSTED_TYPES_POLICY){if(typeof ne.TRUSTED_TYPES_POLICY.createHTML!="function")throw Jf('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof ne.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw Jf('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');const Ue=C;C=ne.TRUSTED_TYPES_POLICY;try{T=A("")}catch(zt){throw C=Ue,zt}}else C===void 0&&ne.TRUSTED_TYPES_POLICY!==null&&(C=iee(h,i)),C&&typeof T=="string"&&(T=A(""));(W.uponSanitizeElement.length>0||W.uponSanitizeAttribute.length>0)&&oe===I&&(oe=yi(oe)),W.uponSanitizeAttribute.length>0&&K===X&&(K=yi(K)),sr&&sr(ne),me=ne},Ss=Pt({},[...WC,...zC,...GZ]),Kt=Pt({},[...jC,...qZ]),Es=function(ne){let Ee=y(ne);(!Ee||!Ee.tagName)&&(Ee={namespaceURI:ir,tagName:"template"});const Ue=Qm(ne.tagName),zt=Qm(Ee.tagName);return Ln[ne.namespaceURI]?ne.namespaceURI===Yn?Ee.namespaceURI===Rn?Ue==="svg":Ee.namespaceURI===Qs?Ue==="svg"&&(zt==="annotation-xml"||zo[zt]):!!Ss[Ue]:ne.namespaceURI===Qs?Ee.namespaceURI===Rn?Ue==="math":Ee.namespaceURI===Yn?Ue==="math"&&io[zt]:!!Kt[Ue]:ne.namespaceURI===Rn?Ee.namespaceURI===Yn&&!io[zt]||Ee.namespaceURI===Qs&&!zo[zt]?!1:!Kt[Ue]&&(dl[Ue]||!Ss[Ue]):!!(Jn==="application/xhtml+xml"&&Ln[ne.namespaceURI]):!1},ht=function(ne){Xf(e.removed,{element:ne});try{y(ne).removeChild(ne)}catch{m(ne)}},pn=function(ne,Ee){try{Xf(e.removed,{attribute:Ee.getAttributeNode(ne),from:Ee})}catch{Xf(e.removed,{attribute:null,from:Ee})}if(Ee.removeAttribute(ne),ne==="is")if(Le||He)try{ht(Ee)}catch{}else try{Ee.setAttribute(ne,"")}catch{}},Vo=function(ne){let Ee=null,Ue=null;if(we)ne="<remove></remove>"+ne;else{const mt=JI(ne,/^[\r\n\t ]+/);Ue=mt&&mt[0]}Jn==="application/xhtml+xml"&&ir===Rn&&(ne='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+ne+"</body></html>");const zt=C?A(ne):ne;if(ir===Rn)try{Ee=new u().parseFromString(zt,Jn)}catch{}if(!Ee||!Ee.documentElement){Ee=R.createDocument(ir,"template",null);try{Ee.documentElement.innerHTML=Wo?T:zt}catch{}}const Mt=Ee.body||Ee.documentElement;return ne&&Ue&&Mt.insertBefore(t.createTextNode(Ue),Mt.childNodes[0]||null),ir===Rn?z.call(Ee,ce?"html":"body")[0]:ce?Ee.documentElement:Mt},Ff=function(ne){return P.call(ne.ownerDocument||ne,ne,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},fl=function(ne){var Ee,Ue;ne.normalize();const zt=P.call(ne.ownerDocument||ne,ne,c.SHOW_TEXT|c.SHOW_COMMENT|c.SHOW_CDATA_SECTION|c.SHOW_PROCESSING_INSTRUCTION,null);let Mt=zt.nextNode();for(;Mt;){let ws=Mt.data;wh([V,N,O],Pn=>{ws=Yf(ws,Pn," ")}),Mt.data=ws,Mt=zt.nextNode()}const mt=(Ee=(Ue=ne.querySelectorAll)===null||Ue===void 0?void 0:Ue.call(ne,"template"))!==null&&Ee!==void 0?Ee:[];wh(Array.from(mt),ws=>{Tn(ws.content)&&fl(ws.content)})},Di=function(ne){const Ee=S?S(ne):null;return typeof Ee!="string"||fe(Ee)!=="form"?!1:typeof ne.nodeName!="string"||typeof ne.textContent!="string"||typeof ne.removeChild!="function"||ne.attributes!==_(ne)||typeof ne.removeAttribute!="function"||typeof ne.setAttribute!="function"||typeof ne.namespaceURI!="string"||typeof ne.insertBefore!="function"||typeof ne.hasChildNodes!="function"||ne.nodeType!==w(ne)||ne.childNodes!==g(ne)},Tn=function(ne){if(!w||typeof ne!="object"||ne===null)return!1;try{return w(ne)===wa.documentFragment}catch{return!1}},wr=function(ne){if(!w||typeof ne!="object"||ne===null)return!1;try{return typeof w(ne)=="number"}catch{return!1}};function kr(Je,ne,Ee){wh(Je,Ue=>{Ue.call(e,ne,Ee,me)})}const Ni=function(ne){let Ee=null;if(kr(W.beforeSanitizeElements,ne,null),Di(ne))return ht(ne),!0;const Ue=fe(S?S(ne):ne.nodeName);if(kr(W.uponSanitizeElement,ne,{tagName:Ue,allowedTags:oe}),se&&ne.hasChildNodes()&&!wr(ne.firstElementChild)&&si(/<[/\w!]/g,ne.innerHTML)&&si(/<[/\w!]/g,ne.textContent)||se&&ne.namespaceURI===Rn&&Ue==="style"&&wr(ne.firstElementChild)||ne.nodeType===wa.progressingInstruction||se&&ne.nodeType===wa.comment&&si(/<[/\w]/g,ne.data))return ht(ne),!0;if(he[Ue]||!(Re.tagCheck instanceof Function&&Re.tagCheck(Ue))&&!oe[Ue]){if(!he[Ue]&&ya(Ue)&&(J.tagNameCheck instanceof RegExp&&si(J.tagNameCheck,Ue)||J.tagNameCheck instanceof Function&&J.tagNameCheck(Ue)))return!1;if(Jt&&!ut[Ue]){const Mt=y(ne),mt=g(ne);if(mt&&Mt){const ws=mt.length;for(let Pn=ws-1;Pn>=0;--Pn){const On=p(mt[Pn],!0);Mt.insertBefore(On,v(ne))}}}return ht(ne),!0}return(w?w(ne):ne.nodeType)===wa.element&&!Es(ne)||(Ue==="noscript"||Ue==="noembed"||Ue==="noframes")&&si(/<\/no(script|embed|frames)/i,ne.innerHTML)?(ht(ne),!0):(xe&&ne.nodeType===wa.text&&(Ee=ne.textContent,wh([V,N,O],Mt=>{Ee=Yf(Ee,Mt," ")}),ne.textContent!==Ee&&(Xf(e.removed,{element:ne.cloneNode()}),ne.textContent=Ee)),kr(W.afterSanitizeElements,ne,null),!1)},pl=function(ne,Ee,Ue){if(be[Ee]||At&&(Ee==="id"||Ee==="name")&&(Ue in t||Ue in Ce))return!1;const zt=K[Ee]||Re.attributeCheck instanceof Function&&Re.attributeCheck(Ee,ne);if(!(st&&!be[Ee]&&si(H,Ee))){if(!(rt&&si(G,Ee))){if(!zt||be[Ee]){if(!(ya(ne)&&(J.tagNameCheck instanceof RegExp&&si(J.tagNameCheck,ne)||J.tagNameCheck instanceof Function&&J.tagNameCheck(ne))&&(J.attributeNameCheck instanceof RegExp&&si(J.attributeNameCheck,Ee)||J.attributeNameCheck instanceof Function&&J.attributeNameCheck(Ee,ne))||Ee==="is"&&J.allowCustomizedBuiltInElements&&(J.tagNameCheck instanceof RegExp&&si(J.tagNameCheck,Ue)||J.tagNameCheck instanceof Function&&J.tagNameCheck(Ue))))return!1}else if(!Uo[Ee]){if(!si(le,Yf(Ue,ie,""))){if(!((Ee==="src"||Ee==="xlink:href"||Ee==="href")&&ne!=="script"&&ZI(Ue,"data:")===0&&hl[ne])){if(!(et&&!si(ee,Yf(Ue,ie,"")))){if(Ue)return!1}}}}}}return!0},$f=Pt({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),ya=function(ne){return!$f[Qm(ne)]&&si(ve,ne)},gl=function(ne){kr(W.beforeSanitizeAttributes,ne,null);const Ee=ne.attributes;if(!Ee||Di(ne))return;const Ue={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:K,forceKeepAttr:void 0};let zt=Ee.length;for(;zt--;){const Mt=Ee[zt],mt=Mt.name,ws=Mt.namespaceURI,Pn=Mt.value,On=fe(mt),Go=Pn;let Ms=mt==="value"?Go:$Z(Go);if(Ue.attrName=On,Ue.attrValue=Ms,Ue.keepAttr=!0,Ue.forceKeepAttr=void 0,kr(W.uponSanitizeAttribute,ne,Ue),Ms=Ue.attrValue,Nt&&(On==="id"||On==="name")&&ZI(Ms,It)!==0&&(pn(mt,ne),Ms=It+Ms),se&&si(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,Ms)){pn(mt,ne);continue}if(On==="attributename"&&JI(Ms,"href")){pn(mt,ne);continue}if(Ue.forceKeepAttr)continue;if(!Ue.keepAttr){pn(mt,ne);continue}if(!De&&si(/\/>/i,Ms)){pn(mt,ne);continue}xe&&wh([V,N,O],Dn=>{Ms=Yf(Ms,Dn," ")});const ts=fe(ne.nodeName);if(!pl(ts,On,Ms)){pn(mt,ne);continue}if(C&&typeof h=="object"&&typeof h.getAttributeType=="function"&&!ws)switch(h.getAttributeType(ts,On)){case"TrustedHTML":{Ms=A(Ms);break}case"TrustedScriptURL":{Ms=C.createScriptURL(Ms);break}}if(Ms!==Go)try{ws?ne.setAttributeNS(ws,mt,Ms):ne.setAttribute(mt,Ms),Di(ne)?ht(ne):YI(e.removed)}catch{pn(mt,ne)}}kr(W.afterSanitizeAttributes,ne,null)},Rc=function(ne){let Ee=null;const Ue=Ff(ne);for(kr(W.beforeSanitizeShadowDOM,ne,null);Ee=Ue.nextNode();)if(kr(W.uponSanitizeShadowNode,Ee,null),Ni(Ee),gl(Ee),Tn(Ee.content)&&Rc(Ee.content),(w?w(Ee):Ee.nodeType)===wa.element){const Mt=b?b(Ee):Ee.shadowRoot;Tn(Mt)&&(ba(Mt),Rc(Mt))}kr(W.afterSanitizeShadowDOM,ne,null)},ba=function(ne){const Ee=w?w(ne):ne.nodeType;if(Ee===wa.element){const Mt=b?b(ne):ne.shadowRoot;Tn(Mt)&&(ba(Mt),Rc(Mt))}const Ue=g?g(ne):ne.childNodes;if(!Ue)return;const zt=[];wh(Ue,Mt=>{Xf(zt,Mt)});for(const Mt of zt)ba(Mt);if(Ee===wa.element){const Mt=S?S(ne):null;if(typeof Mt=="string"&&fe(Mt)==="template"){const mt=ne.content;Tn(mt)&&ba(mt)}}};return e.sanitize=function(Je){let ne=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},Ee=null,Ue=null,zt=null,Mt=null;if(Wo=!Je,Wo&&(Je="<!-->"),typeof Je!="string"&&!wr(Je)&&(Je=jZ(Je),typeof Je!="string"))throw Jf("dirty is not a string, aborting");if(!e.isSupported)return Je;if(de||qt(ne),e.removed=[],typeof Je=="string"&&($t=!1),$t){const Pn=S?S(Je):Je.nodeName;if(typeof Pn=="string"){const On=fe(Pn);if(!oe[On]||he[On])throw Jf("root node is forbidden and cannot be sanitized in-place")}if(Di(Je))throw Jf("root node is clobbered and cannot be sanitized in-place");ba(Je)}else if(wr(Je))Ee=Vo("<!---->"),Ue=Ee.ownerDocument.importNode(Je,!0),Ue.nodeType===wa.element&&Ue.nodeName==="BODY"||Ue.nodeName==="HTML"?Ee=Ue:Ee.appendChild(Ue),ba(Ue);else{if(!Le&&!xe&&!ce&&Je.indexOf("<")===-1)return C&&yt?A(Je):Je;if(Ee=Vo(Je),!Ee)return Le?null:yt?T:""}Ee&&we&&ht(Ee.firstChild);const mt=Ff($t?Je:Ee);for(;zt=mt.nextNode();)Ni(zt),gl(zt),Tn(zt.content)&&Rc(zt.content);if($t)return xe&&fl(Je),Je;if(Le){if(xe&&fl(Ee),He)for(Mt=L.call(Ee.ownerDocument);Ee.firstChild;)Mt.appendChild(Ee.firstChild);else Mt=Ee;return(K.shadowroot||K.shadowrootmode)&&(Mt=Q.call(n,Mt,!0)),Mt}let ws=ce?Ee.outerHTML:Ee.innerHTML;return ce&&oe["!doctype"]&&Ee.ownerDocument&&Ee.ownerDocument.doctype&&Ee.ownerDocument.doctype.name&&si(tee,Ee.ownerDocument.doctype.name)&&(ws="<!DOCTYPE "+Ee.ownerDocument.doctype.name+`>
`+ws),xe&&wh([V,N,O],Pn=>{ws=Yf(ws,Pn," ")}),C&&yt?A(ws):ws},e.setConfig=function(){let Je=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};qt(Je),de=!0},e.clearConfig=function(){me=null,de=!1},e.isValidAttribute=function(Je,ne,Ee){me||qt({});const Ue=fe(Je),zt=fe(ne);return pl(Ue,zt,Ee)},e.addHook=function(Je,ne){typeof ne=="function"&&Xf(W[Je],ne)},e.removeHook=function(Je,ne){if(ne!==void 0){const Ee=BZ(W[Je],ne);return Ee===-1?void 0:FZ(W[Je],Ee,1)[0]}return YI(W[Je])},e.removeHooks=function(Je){W[Je]=[]},e.removeAllHooks=function(){W=aR()},e}var ree=TD();(function(s){function e(t,n){return"___"+t.toUpperCase()+n+"___"}Object.defineProperties(s.languages["markup-templating"]={},{buildPlaceholders:{value:function(t,n,i,r){if(t.language===n){var o=t.tokenStack=[];t.code=t.code.replace(i,function(a){if(typeof r=="function"&&!r(a))return a;for(var c=o.length,l;t.code.indexOf(l=e(n,c))!==-1;)++c;return o[c]=a,l}),t.grammar=s.languages.markup}}},tokenizePlaceholders:{value:function(t,n){if(t.language!==n||!t.tokenStack)return;t.grammar=s.languages[n];var i=0,r=Object.keys(t.tokenStack);function o(a){for(var c=0;c<a.length&&!(i>=r.length);c++){var l=a[c];if(typeof l=="string"||l.content&&typeof l.content=="string"){var u=r[i],h=t.tokenStack[u],d=typeof l=="string"?l:l.content,p=e(n,u),m=d.indexOf(p);if(m>-1){++i;var v=d.substring(0,m),g=new s.Token(n,s.tokenize(h,t.grammar),"language-"+n,h),y=d.substring(m+p.length),b=[];v&&b.push.apply(b,o([v])),b.push(g),y&&b.push.apply(b,o([y])),typeof l=="string"?a.splice.apply(a,[c,1].concat(b)):l.content=b}}else l.content&&o(l.content)}return a}o(t.tokens)}}})})(Prism);Prism.languages.c=Prism.languages.extend("clike",{comment:{pattern:/\/\/(?:[^\r\n\\]|\\(?:\r\n?|\n|(?![\r\n])))*|\/\*[\s\S]*?(?:\*\/|$)/,greedy:!0},string:{pattern:/"(?:\\(?:\r\n|[\s\S])|[^"\\\r\n])*"/,greedy:!0},"class-name":{pattern:/(\b(?:enum|struct)\s+(?:__attribute__\s*\(\([\s\S]*?\)\)\s*)?)\w+|\b[a-z]\w*_t\b/,lookbehind:!0},keyword:/\b(?:_Alignas|_Alignof|_Atomic|_Bool|_Complex|_Generic|_Imaginary|_Noreturn|_Static_assert|_Thread_local|__attribute__|asm|auto|break|case|char|const|continue|default|do|double|else|enum|extern|float|for|goto|if|inline|int|long|register|return|short|signed|sizeof|static|struct|switch|typedef|typeof|union|unsigned|void|volatile|while)\b/,function:/\b[a-z_]\w*(?=\s*\()/i,number:/(?:\b0x(?:[\da-f]+(?:\.[\da-f]*)?|\.[\da-f]+)(?:p[+-]?\d+)?|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:e[+-]?\d+)?)[ful]{0,4}/i,operator:/>>=?|<<=?|->|([-+&|:])\1|[?:~]|[-+*/%&|^!=<>]=?/});Prism.languages.insertBefore("c","string",{char:{pattern:/'(?:\\(?:\r\n|[\s\S])|[^'\\\r\n]){0,32}'/,greedy:!0}});Prism.languages.insertBefore("c","string",{macro:{pattern:/(^[\t ]*)#\s*[a-z](?:[^\r\n\\/]|\/(?!\*)|\/\*(?:[^*]|\*(?!\/))*\*\/|\\(?:\r\n|[\s\S]))*/im,lookbehind:!0,greedy:!0,alias:"property",inside:{string:[{pattern:/^(#\s*include\s*)<[^>]+>/,lookbehind:!0},Prism.languages.c.string],char:Prism.languages.c.char,comment:Prism.languages.c.comment,"macro-name":[{pattern:/(^#\s*define\s+)\w+\b(?!\()/i,lookbehind:!0},{pattern:/(^#\s*define\s+)\w+\b(?=\()/i,lookbehind:!0,alias:"function"}],directive:{pattern:/^(#\s*)[a-z]+/,lookbehind:!0,alias:"keyword"},"directive-hash":/^#/,punctuation:/##|\\(?=[\r\n])/,expression:{pattern:/\S[\s\S]*/,inside:Prism.languages.c}}}});Prism.languages.insertBefore("c","function",{constant:/\b(?:EOF|NULL|SEEK_CUR|SEEK_END|SEEK_SET|__DATE__|__FILE__|__LINE__|__TIMESTAMP__|__TIME__|__func__|stderr|stdin|stdout)\b/});delete Prism.languages.c.boolean;(function(s){var e=/\b(?:alignas|alignof|asm|auto|bool|break|case|catch|char|char16_t|char32_t|char8_t|class|co_await|co_return|co_yield|compl|concept|const|const_cast|consteval|constexpr|constinit|continue|decltype|default|delete|do|double|dynamic_cast|else|enum|explicit|export|extern|final|float|for|friend|goto|if|import|inline|int|int16_t|int32_t|int64_t|int8_t|long|module|mutable|namespace|new|noexcept|nullptr|operator|override|private|protected|public|register|reinterpret_cast|requires|return|short|signed|sizeof|static|static_assert|static_cast|struct|switch|template|this|thread_local|throw|try|typedef|typeid|typename|uint16_t|uint32_t|uint64_t|uint8_t|union|unsigned|using|virtual|void|volatile|wchar_t|while)\b/,t=/\b(?!<keyword>)\w+(?:\s*\.\s*\w+)*\b/.source.replace(/<keyword>/g,function(){return e.source});s.languages.cpp=s.languages.extend("c",{"class-name":[{pattern:RegExp(/(\b(?:class|concept|enum|struct|typename)\s+)(?!<keyword>)\w+/.source.replace(/<keyword>/g,function(){return e.source})),lookbehind:!0},/\b[A-Z]\w*(?=\s*::\s*\w+\s*\()/,/\b[A-Z_]\w*(?=\s*::\s*~\w+\s*\()/i,/\b\w+(?=\s*<(?:[^<>]|<(?:[^<>]|<[^<>]*>)*>)*>\s*::\s*\w+\s*\()/],keyword:e,number:{pattern:/(?:\b0b[01']+|\b0x(?:[\da-f']+(?:\.[\da-f']*)?|\.[\da-f']+)(?:p[+-]?[\d']+)?|(?:\b[\d']+(?:\.[\d']*)?|\B\.[\d']+)(?:e[+-]?[\d']+)?)[ful]{0,4}/i,greedy:!0},operator:/>>=?|<<=?|->|--|\+\+|&&|\|\||[?:~]|<=>|[-+*/%&|^!=<>]=?|\b(?:and|and_eq|bitand|bitor|not|not_eq|or|or_eq|xor|xor_eq)\b/,boolean:/\b(?:false|true)\b/}),s.languages.insertBefore("cpp","string",{module:{pattern:RegExp(/(\b(?:import|module)\s+)/.source+"(?:"+/"(?:\\(?:\r\n|[\s\S])|[^"\\\r\n])*"|<[^<>\r\n]*>/.source+"|"+/<mod-name>(?:\s*:\s*<mod-name>)?|:\s*<mod-name>/.source.replace(/<mod-name>/g,function(){return t})+")"),lookbehind:!0,greedy:!0,inside:{string:/^[<"][\s\S]+/,operator:/:/,punctuation:/\./}},"raw-string":{pattern:/R"([^()\\ ]{0,16})\([\s\S]*?\)\1"/,alias:"string",greedy:!0}}),s.languages.insertBefore("cpp","keyword",{"generic-function":{pattern:/\b(?!operator\b)[a-z_]\w*\s*<(?:[^<>]|<[^<>]*>)*>(?=\s*\()/i,inside:{function:/^\w+/,generic:{pattern:/<[\s\S]+/,alias:"class-name",inside:s.languages.cpp}}}}),s.languages.insertBefore("cpp","operator",{"double-colon":{pattern:/::/,alias:"punctuation"}}),s.languages.insertBefore("cpp","class-name",{"base-clause":{pattern:/(\b(?:class|struct)\s+\w+\s*:\s*)[^;{}"'\s]+(?:\s+[^;{}"'\s]+)*(?=\s*[;{])/,lookbehind:!0,greedy:!0,inside:s.languages.extend("cpp",{})}}),s.languages.insertBefore("inside","double-colon",{"class-name":/\b[a-z_]\w*\b(?!\s*::)/i},s.languages.cpp["base-clause"])})(Prism);(function(s){var e=/\b(?:abstract|assert|boolean|break|byte|case|catch|char|class|const|continue|default|do|double|else|enum|exports|extends|final|finally|float|for|goto|if|implements|import|instanceof|int|interface|long|module|native|new|non-sealed|null|open|opens|package|permits|private|protected|provides|public|record(?!\s*[(){}[\]<>=%~.:,;?+\-*/&|^])|requires|return|sealed|short|static|strictfp|super|switch|synchronized|this|throw|throws|to|transient|transitive|try|uses|var|void|volatile|while|with|yield)\b/,t=/(?:[a-z]\w*\s*\.\s*)*(?:[A-Z]\w*\s*\.\s*)*/.source,n={pattern:RegExp(/(^|[^\w.])/.source+t+/[A-Z](?:[\d_A-Z]*[a-z]\w*)?\b/.source),lookbehind:!0,inside:{namespace:{pattern:/^[a-z]\w*(?:\s*\.\s*[a-z]\w*)*(?:\s*\.)?/,inside:{punctuation:/\./}},punctuation:/\./}};s.languages.java=s.languages.extend("clike",{string:{pattern:/(^|[^\\])"(?:\\.|[^"\\\r\n])*"/,lookbehind:!0,greedy:!0},"class-name":[n,{pattern:RegExp(/(^|[^\w.])/.source+t+/[A-Z]\w*(?=\s+\w+\s*[;,=()]|\s*(?:\[[\s,]*\]\s*)?::\s*new\b)/.source),lookbehind:!0,inside:n.inside},{pattern:RegExp(/(\b(?:class|enum|extends|implements|instanceof|interface|new|record|throws)\s+)/.source+t+/[A-Z]\w*\b/.source),lookbehind:!0,inside:n.inside}],keyword:e,function:[s.languages.clike.function,{pattern:/(::\s*)[a-z_]\w*/,lookbehind:!0}],number:/\b0b[01][01_]*L?\b|\b0x(?:\.[\da-f_p+-]+|[\da-f_]+(?:\.[\da-f_p+-]+)?)\b|(?:\b\d[\d_]*(?:\.[\d_]*)?|\B\.\d[\d_]*)(?:e[+-]?\d[\d_]*)?[dfl]?/i,operator:{pattern:/(^|[^.])(?:<<=?|>>>?=?|->|--|\+\+|&&|\|\||::|[?:~]|[-+*/%&|^!=<>]=?)/m,lookbehind:!0},constant:/\b[A-Z][A-Z_\d]+\b/}),s.languages.insertBefore("java","string",{"triple-quoted-string":{pattern:/"""[ \t]*[\r\n](?:(?:"|"")?(?:\\.|[^"\\]))*"""/,greedy:!0,alias:"string"},char:{pattern:/'(?:\\.|[^'\\\r\n]){1,6}'/,greedy:!0}}),s.languages.insertBefore("java","class-name",{annotation:{pattern:/(^|[^.])@\w+(?:\s*\.\s*\w+)*/,lookbehind:!0,alias:"punctuation"},generics:{pattern:/<(?:[\w\s,.?]|&(?!&)|<(?:[\w\s,.?]|&(?!&)|<(?:[\w\s,.?]|&(?!&)|<(?:[\w\s,.?]|&(?!&))*>)*>)*>)*>/,inside:{"class-name":n,keyword:e,punctuation:/[<>(),.:]/,operator:/[?&|]/}},import:[{pattern:RegExp(/(\bimport\s+)/.source+t+/(?:[A-Z]\w*|\*)(?=\s*;)/.source),lookbehind:!0,inside:{namespace:n.inside.namespace,punctuation:/\./,operator:/\*/,"class-name":/\w+/}},{pattern:RegExp(/(\bimport\s+static\s+)/.source+t+/(?:\w+|\*)(?=\s*;)/.source),lookbehind:!0,alias:"static",inside:{namespace:n.inside.namespace,static:/\b\w+$/,punctuation:/\./,operator:/\*/,"class-name":/\w+/}}],namespace:{pattern:RegExp(/(\b(?:exports|import(?:\s+static)?|module|open|opens|package|provides|requires|to|transitive|uses|with)\s+)(?!<keyword>)[a-z]\w*(?:\.[a-z]\w*)*\.?/.source.replace(/<keyword>/g,function(){return e.source})),lookbehind:!0,inside:{punctuation:/\./}}})})(Prism);(function(s){function e(O,H){return O.replace(/<<(\d+)>>/g,function(G,ee){return"(?:"+H[+ee]+")"})}function t(O,H,G){return RegExp(e(O,H),"")}function n(O,H){for(var G=0;G<H;G++)O=O.replace(/<<self>>/g,function(){return"(?:"+O+")"});return O.replace(/<<self>>/g,"[^\\s\\S]")}var i={type:"bool byte char decimal double dynamic float int long object sbyte short string uint ulong ushort var void",typeDeclaration:"class enum interface record struct",contextual:"add alias and ascending async await by descending from(?=\\s*(?:\\w|$)) get global group into init(?=\\s*;) join let nameof not notnull on or orderby partial remove select set unmanaged value when where with(?=\\s*{)",other:"abstract as base break case catch checked const continue default delegate do else event explicit extern finally fixed for foreach goto if implicit in internal is lock namespace new null operator out override params private protected public readonly ref return sealed sizeof stackalloc static switch this throw try typeof unchecked unsafe using virtual volatile while yield"};function r(O){return"\\b(?:"+O.trim().replace(/ /g,"|")+")\\b"}var o=r(i.typeDeclaration),a=RegExp(r(i.type+" "+i.typeDeclaration+" "+i.contextual+" "+i.other)),c=r(i.typeDeclaration+" "+i.contextual+" "+i.other),l=r(i.type+" "+i.typeDeclaration+" "+i.other),u=n(/<(?:[^<>;=+\-*/%&|^]|<<self>>)*>/.source,2),h=n(/\((?:[^()]|<<self>>)*\)/.source,2),d=/@?\b[A-Za-z_]\w*\b/.source,p=e(/<<0>>(?:\s*<<1>>)?/.source,[d,u]),m=e(/(?!<<0>>)<<1>>(?:\s*\.\s*<<1>>)*/.source,[c,p]),v=/\[\s*(?:,\s*)*\]/.source,g=e(/<<0>>(?:\s*(?:\?\s*)?<<1>>)*(?:\s*\?)?/.source,[m,v]),y=e(/[^,()<>[\];=+\-*/%&|^]|<<0>>|<<1>>|<<2>>/.source,[u,h,v]),b=e(/\(<<0>>+(?:,<<0>>+)+\)/.source,[y]),_=e(/(?:<<0>>|<<1>>)(?:\s*(?:\?\s*)?<<2>>)*(?:\s*\?)?/.source,[b,m,v]),w={keyword:a,punctuation:/[<>()?,.:[\]]/},S=/'(?:[^\r\n'\\]|\\.|\\[Uux][\da-fA-F]{1,8})'/.source,C=/"(?:\\.|[^\\"\r\n])*"/.source,T=/@"(?:""|\\[\s\S]|[^\\"])*"(?!")/.source;s.languages.csharp=s.languages.extend("clike",{string:[{pattern:t(/(^|[^$\\])<<0>>/.source,[T]),lookbehind:!0,greedy:!0},{pattern:t(/(^|[^@$\\])<<0>>/.source,[C]),lookbehind:!0,greedy:!0}],"class-name":[{pattern:t(/(\busing\s+static\s+)<<0>>(?=\s*;)/.source,[m]),lookbehind:!0,inside:w},{pattern:t(/(\busing\s+<<0>>\s*=\s*)<<1>>(?=\s*;)/.source,[d,_]),lookbehind:!0,inside:w},{pattern:t(/(\busing\s+)<<0>>(?=\s*=)/.source,[d]),lookbehind:!0},{pattern:t(/(\b<<0>>\s+)<<1>>/.source,[o,p]),lookbehind:!0,inside:w},{pattern:t(/(\bcatch\s*\(\s*)<<0>>/.source,[m]),lookbehind:!0,inside:w},{pattern:t(/(\bwhere\s+)<<0>>/.source,[d]),lookbehind:!0},{pattern:t(/(\b(?:is(?:\s+not)?|as)\s+)<<0>>/.source,[g]),lookbehind:!0,inside:w},{pattern:t(/\b<<0>>(?=\s+(?!<<1>>|with\s*\{)<<2>>(?:\s*[=,;:{)\]]|\s+(?:in|when)\b))/.source,[_,l,d]),inside:w}],keyword:a,number:/(?:\b0(?:x[\da-f_]*[\da-f]|b[01_]*[01])|(?:\B\.\d+(?:_+\d+)*|\b\d+(?:_+\d+)*(?:\.\d+(?:_+\d+)*)?)(?:e[-+]?\d+(?:_+\d+)*)?)(?:[dflmu]|lu|ul)?\b/i,operator:/>>=?|<<=?|[-=]>|([-+&|])\1|~|\?\?=?|[-+*/%&|^!=<>]=?/,punctuation:/\?\.?|::|[{}[\];(),.:]/}),s.languages.insertBefore("csharp","number",{range:{pattern:/\.\./,alias:"operator"}}),s.languages.insertBefore("csharp","punctuation",{"named-parameter":{pattern:t(/([(,]\s*)<<0>>(?=\s*:)/.source,[d]),lookbehind:!0,alias:"punctuation"}}),s.languages.insertBefore("csharp","class-name",{namespace:{pattern:t(/(\b(?:namespace|using)\s+)<<0>>(?:\s*\.\s*<<0>>)*(?=\s*[;{])/.source,[d]),lookbehind:!0,inside:{punctuation:/\./}},"type-expression":{pattern:t(/(\b(?:default|sizeof|typeof)\s*\(\s*(?!\s))(?:[^()\s]|\s(?!\s)|<<0>>)*(?=\s*\))/.source,[h]),lookbehind:!0,alias:"class-name",inside:w},"return-type":{pattern:t(/<<0>>(?=\s+(?:<<1>>\s*(?:=>|[({]|\.\s*this\s*\[)|this\s*\[))/.source,[_,m]),inside:w,alias:"class-name"},"constructor-invocation":{pattern:t(/(\bnew\s+)<<0>>(?=\s*[[({])/.source,[_]),lookbehind:!0,inside:w,alias:"class-name"},"generic-method":{pattern:t(/<<0>>\s*<<1>>(?=\s*\()/.source,[d,u]),inside:{function:t(/^<<0>>/.source,[d]),generic:{pattern:RegExp(u),alias:"class-name",inside:w}}},"type-list":{pattern:t(/\b((?:<<0>>\s+<<1>>|record\s+<<1>>\s*<<5>>|where\s+<<2>>)\s*:\s*)(?:<<3>>|<<4>>|<<1>>\s*<<5>>|<<6>>)(?:\s*,\s*(?:<<3>>|<<4>>|<<6>>))*(?=\s*(?:where|[{;]|=>|$))/.source,[o,p,d,_,a.source,h,/\bnew\s*\(\s*\)/.source]),lookbehind:!0,inside:{"record-arguments":{pattern:t(/(^(?!new\s*\()<<0>>\s*)<<1>>/.source,[p,h]),lookbehind:!0,greedy:!0,inside:s.languages.csharp},keyword:a,"class-name":{pattern:RegExp(_),greedy:!0,inside:w},punctuation:/[,()]/}},preprocessor:{pattern:/(^[\t ]*)#.*/m,lookbehind:!0,alias:"property",inside:{directive:{pattern:/(#)\b(?:define|elif|else|endif|endregion|error|if|line|nullable|pragma|region|undef|warning)\b/,lookbehind:!0,alias:"keyword"}}}});var k=C+"|"+S,A=e(/\/(?![*/])|\/\/[^\r\n]*[\r\n]|\/\*(?:[^*]|\*(?!\/))*\*\/|<<0>>/.source,[k]),M=n(e(/[^"'/()]|<<0>>|\(<<self>>*\)/.source,[A]),2),R=/\b(?:assembly|event|field|method|module|param|property|return|type)\b/.source,P=e(/<<0>>(?:\s*\(<<1>>*\))?/.source,[m,M]);s.languages.insertBefore("csharp","class-name",{attribute:{pattern:t(/((?:^|[^\s\w>)?])\s*\[\s*)(?:<<0>>\s*:\s*)?<<1>>(?:\s*,\s*<<1>>)*(?=\s*\])/.source,[R,P]),lookbehind:!0,greedy:!0,inside:{target:{pattern:t(/^<<0>>(?=\s*:)/.source,[R]),alias:"keyword"},"attribute-arguments":{pattern:t(/\(<<0>>*\)/.source,[M]),inside:s.languages.csharp},"class-name":{pattern:RegExp(m),inside:{punctuation:/\./}},punctuation:/[:,]/}}});var L=/:[^}\r\n]+/.source,z=n(e(/[^"'/()]|<<0>>|\(<<self>>*\)/.source,[A]),2),Q=e(/\{(?!\{)(?:(?![}:])<<0>>)*<<1>>?\}/.source,[z,L]),W=n(e(/[^"'/()]|\/(?!\*)|\/\*(?:[^*]|\*(?!\/))*\*\/|<<0>>|\(<<self>>*\)/.source,[k]),2),V=e(/\{(?!\{)(?:(?![}:])<<0>>)*<<1>>?\}/.source,[W,L]);function N(O,H){return{interpolation:{pattern:t(/((?:^|[^{])(?:\{\{)*)<<0>>/.source,[O]),lookbehind:!0,inside:{"format-string":{pattern:t(/(^\{(?:(?![}:])<<0>>)*)<<1>>(?=\}$)/.source,[H,L]),lookbehind:!0,inside:{punctuation:/^:/}},punctuation:/^\{|\}$/,expression:{pattern:/[\s\S]+/,alias:"language-csharp",inside:s.languages.csharp}}},string:/[\s\S]+/}}s.languages.insertBefore("csharp","string",{"interpolation-string":[{pattern:t(/(^|[^\\])(?:\$@|@\$)"(?:""|\\[\s\S]|\{\{|<<0>>|[^\\{"])*"/.source,[Q]),lookbehind:!0,greedy:!0,inside:N(Q,z)},{pattern:t(/(^|[^@\\])\$"(?:\\.|\{\{|<<0>>|[^\\"{])*"/.source,[V]),lookbehind:!0,greedy:!0,inside:N(V,W)}],char:{pattern:RegExp(S),greedy:!0}}),s.languages.dotnet=s.languages.cs=s.languages.csharp})(Prism);(function(s){s.languages.kotlin=s.languages.extend("clike",{keyword:{pattern:/(^|[^.])\b(?:abstract|actual|annotation|as|break|by|catch|class|companion|const|constructor|continue|crossinline|data|do|dynamic|else|enum|expect|external|final|finally|for|fun|get|if|import|in|infix|init|inline|inner|interface|internal|is|lateinit|noinline|null|object|open|operator|out|override|package|private|protected|public|reified|return|sealed|set|super|suspend|tailrec|this|throw|to|try|typealias|val|var|vararg|when|where|while)\b/,lookbehind:!0},function:[{pattern:/(?:`[^\r\n`]+`|\b\w+)(?=\s*\()/,greedy:!0},{pattern:/(\.)(?:`[^\r\n`]+`|\w+)(?=\s*\{)/,lookbehind:!0,greedy:!0}],number:/\b(?:0[xX][\da-fA-F]+(?:_[\da-fA-F]+)*|0[bB][01]+(?:_[01]+)*|\d+(?:_\d+)*(?:\.\d+(?:_\d+)*)?(?:[eE][+-]?\d+(?:_\d+)*)?[fFL]?)\b/,operator:/\+[+=]?|-[-=>]?|==?=?|!(?:!|==?)?|[\/*%<>]=?|[?:]:?|\.\.|&&|\|\||\b(?:and|inv|or|shl|shr|ushr|xor)\b/}),delete s.languages.kotlin["class-name"];var e={"interpolation-punctuation":{pattern:/^\$\{?|\}$/,alias:"punctuation"},expression:{pattern:/[\s\S]+/,inside:s.languages.kotlin}};s.languages.insertBefore("kotlin","string",{"string-literal":[{pattern:/"""(?:[^$]|\$(?:(?!\{)|\{[^{}]*\}))*?"""/,alias:"multiline",inside:{interpolation:{pattern:/\$(?:[a-z_]\w*|\{[^{}]*\})/i,inside:e},string:/[\s\S]+/}},{pattern:/"(?:[^"\\\r\n$]|\\.|\$(?:(?!\{)|\{[^{}]*\}))*"/,alias:"singleline",inside:{interpolation:{pattern:/((?:^|[^\\])(?:\\{2})*)\$(?:[a-z_]\w*|\{[^{}]*\})/i,lookbehind:!0,inside:e},string:/[\s\S]+/}}],char:{pattern:/'(?:[^'\\\r\n]|\\(?:.|u[a-fA-F0-9]{0,4}))'/,greedy:!0}}),delete s.languages.kotlin.string,s.languages.insertBefore("kotlin","keyword",{annotation:{pattern:/\B@(?:\w+:)?(?:[A-Z]\w*|\[[^\]]+\])/,alias:"builtin"}}),s.languages.insertBefore("kotlin","function",{label:{pattern:/\b\w+@|@\w+\b/,alias:"symbol"}}),s.languages.kt=s.languages.kotlin,s.languages.kts=s.languages.kotlin})(Prism);Prism.languages.swift={comment:{pattern:/(^|[^\\:])(?:\/\/.*|\/\*(?:[^/*]|\/(?!\*)|\*(?!\/)|\/\*(?:[^*]|\*(?!\/))*\*\/)*\*\/)/,lookbehind:!0,greedy:!0},"string-literal":[{pattern:RegExp(/(^|[^"#])/.source+"(?:"+/"(?:\\(?:\((?:[^()]|\([^()]*\))*\)|\r\n|[^(])|[^\\\r\n"])*"/.source+"|"+/"""(?:\\(?:\((?:[^()]|\([^()]*\))*\)|[^(])|[^\\"]|"(?!""))*"""/.source+")"+/(?!["#])/.source),lookbehind:!0,greedy:!0,inside:{interpolation:{pattern:/(\\\()(?:[^()]|\([^()]*\))*(?=\))/,lookbehind:!0,inside:null},"interpolation-punctuation":{pattern:/^\)|\\\($/,alias:"punctuation"},punctuation:/\\(?=[\r\n])/,string:/[\s\S]+/}},{pattern:RegExp(/(^|[^"#])(#+)/.source+"(?:"+/"(?:\\(?:#+\((?:[^()]|\([^()]*\))*\)|\r\n|[^#])|[^\\\r\n])*?"/.source+"|"+/"""(?:\\(?:#+\((?:[^()]|\([^()]*\))*\)|[^#])|[^\\])*?"""/.source+")\\2"),lookbehind:!0,greedy:!0,inside:{interpolation:{pattern:/(\\#+\()(?:[^()]|\([^()]*\))*(?=\))/,lookbehind:!0,inside:null},"interpolation-punctuation":{pattern:/^\)|\\#+\($/,alias:"punctuation"},string:/[\s\S]+/}}],directive:{pattern:RegExp(/#/.source+"(?:"+(/(?:elseif|if)\b/.source+"(?:[ ]*"+/(?:![ \t]*)?(?:\b\w+\b(?:[ \t]*\((?:[^()]|\([^()]*\))*\))?|\((?:[^()]|\([^()]*\))*\))(?:[ \t]*(?:&&|\|\|))?/.source+")+")+"|"+/(?:else|endif)\b/.source+")"),alias:"property",inside:{"directive-name":/^#\w+/,boolean:/\b(?:false|true)\b/,number:/\b\d+(?:\.\d+)*\b/,operator:/!|&&|\|\||[<>]=?/,punctuation:/[(),]/}},literal:{pattern:/#(?:colorLiteral|column|dsohandle|file(?:ID|Literal|Path)?|function|imageLiteral|line)\b/,alias:"constant"},"other-directive":{pattern:/#\w+\b/,alias:"property"},attribute:{pattern:/@\w+/,alias:"atrule"},"function-definition":{pattern:/(\bfunc\s+)\w+/,lookbehind:!0,alias:"function"},label:{pattern:/\b(break|continue)\s+\w+|\b[a-zA-Z_]\w*(?=\s*:\s*(?:for|repeat|while)\b)/,lookbehind:!0,alias:"important"},keyword:/\b(?:Any|Protocol|Self|Type|actor|as|assignment|associatedtype|associativity|async|await|break|case|catch|class|continue|convenience|default|defer|deinit|didSet|do|dynamic|else|enum|extension|fallthrough|fileprivate|final|for|func|get|guard|higherThan|if|import|in|indirect|infix|init|inout|internal|is|isolated|lazy|left|let|lowerThan|mutating|none|nonisolated|nonmutating|open|operator|optional|override|postfix|precedencegroup|prefix|private|protocol|public|repeat|required|rethrows|return|right|safe|self|set|some|static|struct|subscript|super|switch|throw|throws|try|typealias|unowned|unsafe|var|weak|where|while|willSet)\b/,boolean:/\b(?:false|true)\b/,nil:{pattern:/\bnil\b/,alias:"constant"},"short-argument":/\$\d+\b/,omit:{pattern:/\b_\b/,alias:"keyword"},number:/\b(?:[\d_]+(?:\.[\de_]+)?|0x[a-f0-9_]+(?:\.[a-f0-9p_]+)?|0b[01_]+|0o[0-7_]+)\b/i,"class-name":/\b[A-Z](?:[A-Z_\d]*[a-z]\w*)?\b/,function:/\b[a-z_]\w*(?=\s*\()/i,constant:/\b(?:[A-Z_]{2,}|k[A-Z][A-Za-z_]+)\b/,operator:/[-+*/%=!<>&|^~?]+|\.[.\-+*/%=!<>&|^~?]+/,punctuation:/[{}[\]();,.:\\]/};Prism.languages.swift["string-literal"].forEach(function(s){s.inside.interpolation.inside=Prism.languages.swift});Prism.languages.go=Prism.languages.extend("clike",{string:{pattern:/(^|[^\\])"(?:\\.|[^"\\\r\n])*"|`[^`]*`/,lookbehind:!0,greedy:!0},keyword:/\b(?:break|case|chan|const|continue|default|defer|else|fallthrough|for|func|go(?:to)?|if|import|interface|map|package|range|return|select|struct|switch|type|var)\b/,boolean:/\b(?:_|false|iota|nil|true)\b/,number:[/\b0(?:b[01_]+|o[0-7_]+)i?\b/i,/\b0x(?:[a-f\d_]+(?:\.[a-f\d_]*)?|\.[a-f\d_]+)(?:p[+-]?\d+(?:_\d+)*)?i?(?!\w)/i,/(?:\b\d[\d_]*(?:\.[\d_]*)?|\B\.\d[\d_]*)(?:e[+-]?[\d_]+)?i?(?!\w)/i],operator:/[*\/%^!=]=?|\+[=+]?|-[=-]?|\|[=|]?|&(?:=|&|\^=?)?|>(?:>=?|=)?|<(?:<=?|=|-)?|:=|\.\.\./,builtin:/\b(?:append|bool|byte|cap|close|complex|complex(?:64|128)|copy|delete|error|float(?:32|64)|u?int(?:8|16|32|64)?|imag|len|make|new|panic|print(?:ln)?|real|recover|rune|string|uintptr)\b/});Prism.languages.insertBefore("go","string",{char:{pattern:/'(?:\\.|[^'\\\r\n]){0,10}'/,greedy:!0}});delete Prism.languages.go["class-name"];(function(s){for(var e=/\/\*(?:[^*/]|\*(?!\/)|\/(?!\*)|<self>)*\*\//.source,t=0;t<2;t++)e=e.replace(/<self>/g,function(){return e});e=e.replace(/<self>/g,function(){return/[^\s\S]/.source}),s.languages.rust={comment:[{pattern:RegExp(/(^|[^\\])/.source+e),lookbehind:!0,greedy:!0},{pattern:/(^|[^\\:])\/\/.*/,lookbehind:!0,greedy:!0}],string:{pattern:/b?"(?:\\[\s\S]|[^\\"])*"|b?r(#*)"(?:[^"]|"(?!\1))*"\1/,greedy:!0},char:{pattern:/b?'(?:\\(?:x[0-7][\da-fA-F]|u\{(?:[\da-fA-F]_*){1,6}\}|.)|[^\\\r\n\t'])'/,greedy:!0},attribute:{pattern:/#!?\[(?:[^\[\]"]|"(?:\\[\s\S]|[^\\"])*")*\]/,greedy:!0,alias:"attr-name",inside:{string:null}},"closure-params":{pattern:/([=(,:]\s*|\bmove\s*)\|[^|]*\||\|[^|]*\|(?=\s*(?:\{|->))/,lookbehind:!0,greedy:!0,inside:{"closure-punctuation":{pattern:/^\||\|$/,alias:"punctuation"},rest:null}},"lifetime-annotation":{pattern:/'\w+/,alias:"symbol"},"fragment-specifier":{pattern:/(\$\w+:)[a-z]+/,lookbehind:!0,alias:"punctuation"},variable:/\$\w+/,"function-definition":{pattern:/(\bfn\s+)\w+/,lookbehind:!0,alias:"function"},"type-definition":{pattern:/(\b(?:enum|struct|trait|type|union)\s+)\w+/,lookbehind:!0,alias:"class-name"},"module-declaration":[{pattern:/(\b(?:crate|mod)\s+)[a-z][a-z_\d]*/,lookbehind:!0,alias:"namespace"},{pattern:/(\b(?:crate|self|super)\s*)::\s*[a-z][a-z_\d]*\b(?:\s*::(?:\s*[a-z][a-z_\d]*\s*::)*)?/,lookbehind:!0,alias:"namespace",inside:{punctuation:/::/}}],keyword:[/\b(?:Self|abstract|as|async|await|become|box|break|const|continue|crate|do|dyn|else|enum|extern|final|fn|for|if|impl|in|let|loop|macro|match|mod|move|mut|override|priv|pub|ref|return|self|static|struct|super|trait|try|type|typeof|union|unsafe|unsized|use|virtual|where|while|yield)\b/,/\b(?:bool|char|f(?:32|64)|[ui](?:8|16|32|64|128|size)|str)\b/],function:/\b[a-z_]\w*(?=\s*(?:::\s*<|\())/,macro:{pattern:/\b\w+!/,alias:"property"},constant:/\b[A-Z_][A-Z_\d]+\b/,"class-name":/\b[A-Z]\w*\b/,namespace:{pattern:/(?:\b[a-z][a-z_\d]*\s*::\s*)*\b[a-z][a-z_\d]*\s*::(?!\s*<)/,inside:{punctuation:/::/}},number:/\b(?:0x[\dA-Fa-f](?:_?[\dA-Fa-f])*|0o[0-7](?:_?[0-7])*|0b[01](?:_?[01])*|(?:(?:\d(?:_?\d)*)?\.)?\d(?:_?\d)*(?:[Ee][+-]?\d+)?)(?:_?(?:f32|f64|[iu](?:8|16|32|64|size)?))?\b/,boolean:/\b(?:false|true)\b/,punctuation:/->|\.\.=|\.{1,3}|::|[{}[\];(),:]/,operator:/[-+*\/%!^]=?|=[=>]?|&[&=]?|\|[|=]?|<<?=?|>>?=?|[@?]/},s.languages.rust["closure-params"].inside.rest=s.languages.rust,s.languages.rust.attribute.inside.string=s.languages.rust.string})(Prism);(function(s){var e=/\/\*[\s\S]*?\*\/|\/\/.*|#(?!\[).*/,t=[{pattern:/\b(?:false|true)\b/i,alias:"boolean"},{pattern:/(::\s*)\b[a-z_]\w*\b(?!\s*\()/i,greedy:!0,lookbehind:!0},{pattern:/(\b(?:case|const)\s+)\b[a-z_]\w*(?=\s*[;=])/i,greedy:!0,lookbehind:!0},/\b(?:null)\b/i,/\b[A-Z_][A-Z0-9_]*\b(?!\s*\()/],n=/\b0b[01]+(?:_[01]+)*\b|\b0o[0-7]+(?:_[0-7]+)*\b|\b0x[\da-f]+(?:_[\da-f]+)*\b|(?:\b\d+(?:_\d+)*\.?(?:\d+(?:_\d+)*)?|\B\.\d+)(?:e[+-]?\d+)?/i,i=/<?=>|\?\?=?|\.{3}|\??->|[!=]=?=?|::|\*\*=?|--|\+\+|&&|\|\||<<|>>|[?~]|[/^|%*&<>.+-]=?/,r=/[{}\[\](),:;]/;s.languages.php={delimiter:{pattern:/\?>$|^<\?(?:php(?=\s)|=)?/i,alias:"important"},comment:e,variable:/\$+(?:\w+\b|(?=\{))/,package:{pattern:/(namespace\s+|use\s+(?:function\s+)?)(?:\\?\b[a-z_]\w*)+\b(?!\\)/i,lookbehind:!0,inside:{punctuation:/\\/}},"class-name-definition":{pattern:/(\b(?:class|enum|interface|trait)\s+)\b[a-z_]\w*(?!\\)\b/i,lookbehind:!0,alias:"class-name"},"function-definition":{pattern:/(\bfunction\s+)[a-z_]\w*(?=\s*\()/i,lookbehind:!0,alias:"function"},keyword:[{pattern:/(\(\s*)\b(?:array|bool|boolean|float|int|integer|object|string)\b(?=\s*\))/i,alias:"type-casting",greedy:!0,lookbehind:!0},{pattern:/([(,?]\s*)\b(?:array(?!\s*\()|bool|callable|(?:false|null)(?=\s*\|)|float|int|iterable|mixed|object|self|static|string)\b(?=\s*\$)/i,alias:"type-hint",greedy:!0,lookbehind:!0},{pattern:/(\)\s*:\s*(?:\?\s*)?)\b(?:array(?!\s*\()|bool|callable|(?:false|null)(?=\s*\|)|float|int|iterable|mixed|never|object|self|static|string|void)\b/i,alias:"return-type",greedy:!0,lookbehind:!0},{pattern:/\b(?:array(?!\s*\()|bool|float|int|iterable|mixed|object|string|void)\b/i,alias:"type-declaration",greedy:!0},{pattern:/(\|\s*)(?:false|null)\b|\b(?:false|null)(?=\s*\|)/i,alias:"type-declaration",greedy:!0,lookbehind:!0},{pattern:/\b(?:parent|self|static)(?=\s*::)/i,alias:"static-context",greedy:!0},{pattern:/(\byield\s+)from\b/i,lookbehind:!0},/\bclass\b/i,{pattern:/((?:^|[^\s>:]|(?:^|[^-])>|(?:^|[^:]):)\s*)\b(?:abstract|and|array|as|break|callable|case|catch|clone|const|continue|declare|default|die|do|echo|else|elseif|empty|enddeclare|endfor|endforeach|endif|endswitch|endwhile|enum|eval|exit|extends|final|finally|fn|for|foreach|function|global|goto|if|implements|include|include_once|instanceof|insteadof|interface|isset|list|match|namespace|never|new|or|parent|print|private|protected|public|readonly|require|require_once|return|self|static|switch|throw|trait|try|unset|use|var|while|xor|yield|__halt_compiler)\b/i,lookbehind:!0}],"argument-name":{pattern:/([(,]\s*)\b[a-z_]\w*(?=\s*:(?!:))/i,lookbehind:!0},"class-name":[{pattern:/(\b(?:extends|implements|instanceof|new(?!\s+self|\s+static))\s+|\bcatch\s*\()\b[a-z_]\w*(?!\\)\b/i,greedy:!0,lookbehind:!0},{pattern:/(\|\s*)\b[a-z_]\w*(?!\\)\b/i,greedy:!0,lookbehind:!0},{pattern:/\b[a-z_]\w*(?!\\)\b(?=\s*\|)/i,greedy:!0},{pattern:/(\|\s*)(?:\\?\b[a-z_]\w*)+\b/i,alias:"class-name-fully-qualified",greedy:!0,lookbehind:!0,inside:{punctuation:/\\/}},{pattern:/(?:\\?\b[a-z_]\w*)+\b(?=\s*\|)/i,alias:"class-name-fully-qualified",greedy:!0,inside:{punctuation:/\\/}},{pattern:/(\b(?:extends|implements|instanceof|new(?!\s+self\b|\s+static\b))\s+|\bcatch\s*\()(?:\\?\b[a-z_]\w*)+\b(?!\\)/i,alias:"class-name-fully-qualified",greedy:!0,lookbehind:!0,inside:{punctuation:/\\/}},{pattern:/\b[a-z_]\w*(?=\s*\$)/i,alias:"type-declaration",greedy:!0},{pattern:/(?:\\?\b[a-z_]\w*)+(?=\s*\$)/i,alias:["class-name-fully-qualified","type-declaration"],greedy:!0,inside:{punctuation:/\\/}},{pattern:/\b[a-z_]\w*(?=\s*::)/i,alias:"static-context",greedy:!0},{pattern:/(?:\\?\b[a-z_]\w*)+(?=\s*::)/i,alias:["class-name-fully-qualified","static-context"],greedy:!0,inside:{punctuation:/\\/}},{pattern:/([(,?]\s*)[a-z_]\w*(?=\s*\$)/i,alias:"type-hint",greedy:!0,lookbehind:!0},{pattern:/([(,?]\s*)(?:\\?\b[a-z_]\w*)+(?=\s*\$)/i,alias:["class-name-fully-qualified","type-hint"],greedy:!0,lookbehind:!0,inside:{punctuation:/\\/}},{pattern:/(\)\s*:\s*(?:\?\s*)?)\b[a-z_]\w*(?!\\)\b/i,alias:"return-type",greedy:!0,lookbehind:!0},{pattern:/(\)\s*:\s*(?:\?\s*)?)(?:\\?\b[a-z_]\w*)+\b(?!\\)/i,alias:["class-name-fully-qualified","return-type"],greedy:!0,lookbehind:!0,inside:{punctuation:/\\/}}],constant:t,function:{pattern:/(^|[^\\\w])\\?[a-z_](?:[\w\\]*\w)?(?=\s*\()/i,lookbehind:!0,inside:{punctuation:/\\/}},property:{pattern:/(->\s*)\w+/,lookbehind:!0},number:n,operator:i,punctuation:r};var o={pattern:/\{\$(?:\{(?:\{[^{}]+\}|[^{}]+)\}|[^{}])+\}|(^|[^\\{])\$+(?:\w+(?:\[[^\r\n\[\]]+\]|->\w+)?)/,lookbehind:!0,inside:s.languages.php},a=[{pattern:/<<<'([^']+)'[\r\n](?:.*[\r\n])*?\1;/,alias:"nowdoc-string",greedy:!0,inside:{delimiter:{pattern:/^<<<'[^']+'|[a-z_]\w*;$/i,alias:"symbol",inside:{punctuation:/^<<<'?|[';]$/}}}},{pattern:/<<<(?:"([^"]+)"[\r\n](?:.*[\r\n])*?\1;|([a-z_]\w*)[\r\n](?:.*[\r\n])*?\2;)/i,alias:"heredoc-string",greedy:!0,inside:{delimiter:{pattern:/^<<<(?:"[^"]+"|[a-z_]\w*)|[a-z_]\w*;$/i,alias:"symbol",inside:{punctuation:/^<<<"?|[";]$/}},interpolation:o}},{pattern:/`(?:\\[\s\S]|[^\\`])*`/,alias:"backtick-quoted-string",greedy:!0},{pattern:/'(?:\\[\s\S]|[^\\'])*'/,alias:"single-quoted-string",greedy:!0},{pattern:/"(?:\\[\s\S]|[^\\"])*"/,alias:"double-quoted-string",greedy:!0,inside:{interpolation:o}}];s.languages.insertBefore("php","variable",{string:a,attribute:{pattern:/#\[(?:[^"'\/#]|\/(?![*/])|\/\/.*$|#(?!\[).*$|\/\*(?:[^*]|\*(?!\/))*\*\/|"(?:\\[\s\S]|[^\\"])*"|'(?:\\[\s\S]|[^\\'])*')+\](?=\s*[a-z$#])/im,greedy:!0,inside:{"attribute-content":{pattern:/^(#\[)[\s\S]+(?=\]$)/,lookbehind:!0,inside:{comment:e,string:a,"attribute-class-name":[{pattern:/([^:]|^)\b[a-z_]\w*(?!\\)\b/i,alias:"class-name",greedy:!0,lookbehind:!0},{pattern:/([^:]|^)(?:\\?\b[a-z_]\w*)+/i,alias:["class-name","class-name-fully-qualified"],greedy:!0,lookbehind:!0,inside:{punctuation:/\\/}}],constant:t,number:n,operator:i,punctuation:r}},delimiter:{pattern:/^#\[|\]$/,alias:"punctuation"}}}}),s.hooks.add("before-tokenize",function(c){if(/<\?/.test(c.code)){var l=/<\?(?:[^"'/#]|\/(?![*/])|("|')(?:\\[\s\S]|(?!\1)[^\\])*\1|(?:\/\/|#(?!\[))(?:[^?\n\r]|\?(?!>))*(?=$|\?>|[\r\n])|#\[|\/\*(?:[^*]|\*(?!\/))*(?:\*\/|$))*?(?:\?>|$)/g;s.languages["markup-templating"].buildPlaceholders(c,"php",l)}}),s.hooks.add("after-tokenize",function(c){s.languages["markup-templating"].tokenizePlaceholders(c,"php")})})(Prism);Prism.languages.python={comment:{pattern:/(^|[^\\])#.*/,lookbehind:!0,greedy:!0},"string-interpolation":{pattern:/(?:f|fr|rf)(?:("""|''')[\s\S]*?\1|("|')(?:\\.|(?!\2)[^\\\r\n])*\2)/i,greedy:!0,inside:{interpolation:{pattern:/((?:^|[^{])(?:\{\{)*)\{(?!\{)(?:[^{}]|\{(?!\{)(?:[^{}]|\{(?!\{)(?:[^{}])+\})+\})+\}/,lookbehind:!0,inside:{"format-spec":{pattern:/(:)[^:(){}]+(?=\}$)/,lookbehind:!0},"conversion-option":{pattern:/![sra](?=[:}]$)/,alias:"punctuation"},rest:null}},string:/[\s\S]+/}},"triple-quoted-string":{pattern:/(?:[rub]|br|rb)?("""|''')[\s\S]*?\1/i,greedy:!0,alias:"string"},string:{pattern:/(?:[rub]|br|rb)?("|')(?:\\.|(?!\1)[^\\\r\n])*\1/i,greedy:!0},function:{pattern:/((?:^|\s)def[ \t]+)[a-zA-Z_]\w*(?=\s*\()/g,lookbehind:!0},"class-name":{pattern:/(\bclass\s+)\w+/i,lookbehind:!0},decorator:{pattern:/(^[\t ]*)@\w+(?:\.\w+)*/m,lookbehind:!0,alias:["annotation","punctuation"],inside:{punctuation:/\./}},keyword:/\b(?:_(?=\s*:)|and|as|assert|async|await|break|case|class|continue|def|del|elif|else|except|exec|finally|for|from|global|if|import|in|is|lambda|match|nonlocal|not|or|pass|print|raise|return|try|while|with|yield)\b/,builtin:/\b(?:__import__|abs|all|any|apply|ascii|basestring|bin|bool|buffer|bytearray|bytes|callable|chr|classmethod|cmp|coerce|compile|complex|delattr|dict|dir|divmod|enumerate|eval|execfile|file|filter|float|format|frozenset|getattr|globals|hasattr|hash|help|hex|id|input|int|intern|isinstance|issubclass|iter|len|list|locals|long|map|max|memoryview|min|next|object|oct|open|ord|pow|property|range|raw_input|reduce|reload|repr|reversed|round|set|setattr|slice|sorted|staticmethod|str|sum|super|tuple|type|unichr|unicode|vars|xrange|zip)\b/,boolean:/\b(?:False|None|True)\b/,number:/\b0(?:b(?:_?[01])+|o(?:_?[0-7])+|x(?:_?[a-f0-9])+)\b|(?:\b\d+(?:_\d+)*(?:\.(?:\d+(?:_\d+)*)?)?|\B\.\d+(?:_\d+)*)(?:e[+-]?\d+(?:_\d+)*)?j?(?!\w)/i,operator:/[-+%=]=?|!=|:=|\*\*?=?|\/\/?=?|<[<=>]?|>[=>]?|[&|^~]/,punctuation:/[{}[\];(),.:]/};Prism.languages.python["string-interpolation"].inside.interpolation.inside.rest=Prism.languages.python;Prism.languages.py=Prism.languages.python;(function(s){s.languages.ruby=s.languages.extend("clike",{comment:{pattern:/#.*|^=begin\s[\s\S]*?^=end/m,greedy:!0},"class-name":{pattern:/(\b(?:class|module)\s+|\bcatch\s+\()[\w.\\]+|\b[A-Z_]\w*(?=\s*\.\s*new\b)/,lookbehind:!0,inside:{punctuation:/[.\\]/}},keyword:/\b(?:BEGIN|END|alias|and|begin|break|case|class|def|define_method|defined|do|each|else|elsif|end|ensure|extend|for|if|in|include|module|new|next|nil|not|or|prepend|private|protected|public|raise|redo|require|rescue|retry|return|self|super|then|throw|undef|unless|until|when|while|yield)\b/,operator:/\.{2,3}|&\.|===|<?=>|[!=]?~|(?:&&|\|\||<<|>>|\*\*|[+\-*/%<>!^&|=])=?|[?:]/,punctuation:/[(){}[\].,;]/}),s.languages.insertBefore("ruby","operator",{"double-colon":{pattern:/::/,alias:"punctuation"}});var e={pattern:/((?:^|[^\\])(?:\\{2})*)#\{(?:[^{}]|\{[^{}]*\})*\}/,lookbehind:!0,inside:{content:{pattern:/^(#\{)[\s\S]+(?=\}$)/,lookbehind:!0,inside:s.languages.ruby},delimiter:{pattern:/^#\{|\}$/,alias:"punctuation"}}};delete s.languages.ruby.function;var t="(?:"+[/([^a-zA-Z0-9\s{(\[<=])(?:(?!\1)[^\\]|\\[\s\S])*\1/.source,/\((?:[^()\\]|\\[\s\S]|\((?:[^()\\]|\\[\s\S])*\))*\)/.source,/\{(?:[^{}\\]|\\[\s\S]|\{(?:[^{}\\]|\\[\s\S])*\})*\}/.source,/\[(?:[^\[\]\\]|\\[\s\S]|\[(?:[^\[\]\\]|\\[\s\S])*\])*\]/.source,/<(?:[^<>\\]|\\[\s\S]|<(?:[^<>\\]|\\[\s\S])*>)*>/.source].join("|")+")",n=/(?:"(?:\\.|[^"\\\r\n])*"|(?:\b[a-zA-Z_]\w*|[^\s\0-\x7F]+)[?!]?|\$.)/.source;s.languages.insertBefore("ruby","keyword",{"regex-literal":[{pattern:RegExp(/%r/.source+t+/[egimnosux]{0,6}/.source),greedy:!0,inside:{interpolation:e,regex:/[\s\S]+/}},{pattern:/(^|[^/])\/(?!\/)(?:\[[^\r\n\]]+\]|\\.|[^[/\\\r\n])+\/[egimnosux]{0,6}(?=\s*(?:$|[\r\n,.;})#]))/,lookbehind:!0,greedy:!0,inside:{interpolation:e,regex:/[\s\S]+/}}],variable:/[@$]+[a-zA-Z_]\w*(?:[?!]|\b)/,symbol:[{pattern:RegExp(/(^|[^:]):/.source+n),lookbehind:!0,greedy:!0},{pattern:RegExp(/([\r\n{(,][ \t]*)/.source+n+/(?=:(?!:))/.source),lookbehind:!0,greedy:!0}],"method-definition":{pattern:/(\bdef\s+)\w+(?:\s*\.\s*\w+)?/,lookbehind:!0,inside:{function:/\b\w+$/,keyword:/^self\b/,"class-name":/^\w+/,punctuation:/\./}}}),s.languages.insertBefore("ruby","string",{"string-literal":[{pattern:RegExp(/%[qQiIwWs]?/.source+t),greedy:!0,inside:{interpolation:e,string:/[\s\S]+/}},{pattern:/("|')(?:#\{[^}]+\}|#(?!\{)|\\(?:\r\n|[\s\S])|(?!\1)[^\\#\r\n])*\1/,greedy:!0,inside:{interpolation:e,string:/[\s\S]+/}},{pattern:/<<[-~]?([a-z_]\w*)[\r\n](?:.*[\r\n])*?[\t ]*\1/i,alias:"heredoc-string",greedy:!0,inside:{delimiter:{pattern:/^<<[-~]?[a-z_]\w*|\b[a-z_]\w*$/i,inside:{symbol:/\b\w+/,punctuation:/^<<[-~]?/}},interpolation:e,string:/[\s\S]+/}},{pattern:/<<[-~]?'([a-z_]\w*)'[\r\n](?:.*[\r\n])*?[\t ]*\1/i,alias:"heredoc-string",greedy:!0,inside:{delimiter:{pattern:/^<<[-~]?'[a-z_]\w*'|\b[a-z_]\w*$/i,inside:{symbol:/\b\w+/,punctuation:/^<<[-~]?'|'$/}},string:/[\s\S]+/}}],"command-literal":[{pattern:RegExp(/%x/.source+t),greedy:!0,inside:{interpolation:e,command:{pattern:/[\s\S]+/,alias:"string"}}},{pattern:/`(?:#\{[^}]+\}|#(?!\{)|\\(?:\r\n|[\s\S])|[^\\`#\r\n])*`/,greedy:!0,inside:{interpolation:e,command:{pattern:/[\s\S]+/,alias:"string"}}}]}),delete s.languages.ruby.string,s.languages.insertBefore("ruby","number",{builtin:/\b(?:Array|Bignum|Binding|Class|Continuation|Dir|Exception|FalseClass|File|Fixnum|Float|Hash|IO|Integer|MatchData|Method|Module|NilClass|Numeric|Object|Proc|Range|Regexp|Stat|String|Struct|Symbol|TMS|Thread|ThreadGroup|Time|TrueClass)\b/,constant:/\b[A-Z][A-Z0-9_]*(?:[?!]|\b)/}),s.languages.rb=s.languages.ruby})(Prism);(function(s){var e="\\b(?:BASH|BASHOPTS|BASH_ALIASES|BASH_ARGC|BASH_ARGV|BASH_CMDS|BASH_COMPLETION_COMPAT_DIR|BASH_LINENO|BASH_REMATCH|BASH_SOURCE|BASH_VERSINFO|BASH_VERSION|COLORTERM|COLUMNS|COMP_WORDBREAKS|DBUS_SESSION_BUS_ADDRESS|DEFAULTS_PATH|DESKTOP_SESSION|DIRSTACK|DISPLAY|EUID|GDMSESSION|GDM_LANG|GNOME_KEYRING_CONTROL|GNOME_KEYRING_PID|GPG_AGENT_INFO|GROUPS|HISTCONTROL|HISTFILE|HISTFILESIZE|HISTSIZE|HOME|HOSTNAME|HOSTTYPE|IFS|INSTANCE|JOB|LANG|LANGUAGE|LC_ADDRESS|LC_ALL|LC_IDENTIFICATION|LC_MEASUREMENT|LC_MONETARY|LC_NAME|LC_NUMERIC|LC_PAPER|LC_TELEPHONE|LC_TIME|LESSCLOSE|LESSOPEN|LINES|LOGNAME|LS_COLORS|MACHTYPE|MAILCHECK|MANDATORY_PATH|NO_AT_BRIDGE|OLDPWD|OPTERR|OPTIND|ORBIT_SOCKETDIR|OSTYPE|PAPERSIZE|PATH|PIPESTATUS|PPID|PS1|PS2|PS3|PS4|PWD|RANDOM|REPLY|SECONDS|SELINUX_INIT|SESSION|SESSIONTYPE|SESSION_MANAGER|SHELL|SHELLOPTS|SHLVL|SSH_AUTH_SOCK|TERM|UID|UPSTART_EVENTS|UPSTART_INSTANCE|UPSTART_JOB|UPSTART_SESSION|USER|WINDOWID|XAUTHORITY|XDG_CONFIG_DIRS|XDG_CURRENT_DESKTOP|XDG_DATA_DIRS|XDG_GREETER_DATA_DIR|XDG_MENU_PREFIX|XDG_RUNTIME_DIR|XDG_SEAT|XDG_SEAT_PATH|XDG_SESSION_DESKTOP|XDG_SESSION_ID|XDG_SESSION_PATH|XDG_SESSION_TYPE|XDG_VTNR|XMODIFIERS)\\b",t={pattern:/(^(["']?)\w+\2)[ \t]+\S.*/,lookbehind:!0,alias:"punctuation",inside:null},n={bash:t,environment:{pattern:RegExp("\\$"+e),alias:"constant"},variable:[{pattern:/\$?\(\([\s\S]+?\)\)/,greedy:!0,inside:{variable:[{pattern:/(^\$\(\([\s\S]+)\)\)/,lookbehind:!0},/^\$\(\(/],number:/\b0x[\dA-Fa-f]+\b|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:[Ee]-?\d+)?/,operator:/--|\+\+|\*\*=?|<<=?|>>=?|&&|\|\||[=!+\-*/%<>^&|]=?|[?~:]/,punctuation:/\(\(?|\)\)?|,|;/}},{pattern:/\$\((?:\([^)]+\)|[^()])+\)|`[^`]+`/,greedy:!0,inside:{variable:/^\$\(|^`|\)$|`$/}},{pattern:/\$\{[^}]+\}/,greedy:!0,inside:{operator:/:[-=?+]?|[!\/]|##?|%%?|\^\^?|,,?/,punctuation:/[\[\]]/,environment:{pattern:RegExp("(\\{)"+e),lookbehind:!0,alias:"constant"}}},/\$(?:\w+|[#?*!@$])/],entity:/\\(?:[abceEfnrtv\\"]|O?[0-7]{1,3}|U[0-9a-fA-F]{8}|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{1,2})/};s.languages.bash={shebang:{pattern:/^#!\s*\/.*/,alias:"important"},comment:{pattern:/(^|[^"{\\$])#.*/,lookbehind:!0},"function-name":[{pattern:/(\bfunction\s+)[\w-]+(?=(?:\s*\(?:\s*\))?\s*\{)/,lookbehind:!0,alias:"function"},{pattern:/\b[\w-]+(?=\s*\(\s*\)\s*\{)/,alias:"function"}],"for-or-select":{pattern:/(\b(?:for|select)\s+)\w+(?=\s+in\s)/,alias:"variable",lookbehind:!0},"assign-left":{pattern:/(^|[\s;|&]|[<>]\()\w+(?:\.\w+)*(?=\+?=)/,inside:{environment:{pattern:RegExp("(^|[\\s;|&]|[<>]\\()"+e),lookbehind:!0,alias:"constant"}},alias:"variable",lookbehind:!0},parameter:{pattern:/(^|\s)-{1,2}(?:\w+:[+-]?)?\w+(?:\.\w+)*(?=[=\s]|$)/,alias:"variable",lookbehind:!0},string:[{pattern:/((?:^|[^<])<<-?\s*)(\w+)\s[\s\S]*?(?:\r?\n|\r)\2/,lookbehind:!0,greedy:!0,inside:n},{pattern:/((?:^|[^<])<<-?\s*)(["'])(\w+)\2\s[\s\S]*?(?:\r?\n|\r)\3/,lookbehind:!0,greedy:!0,inside:{bash:t}},{pattern:/(^|[^\\](?:\\\\)*)"(?:\\[\s\S]|\$\([^)]+\)|\$(?!\()|`[^`]+`|[^"\\`$])*"/,lookbehind:!0,greedy:!0,inside:n},{pattern:/(^|[^$\\])'[^']*'/,lookbehind:!0,greedy:!0},{pattern:/\$'(?:[^'\\]|\\[\s\S])*'/,greedy:!0,inside:{entity:n.entity}}],environment:{pattern:RegExp("\\$?"+e),alias:"constant"},variable:n.variable,function:{pattern:/(^|[\s;|&]|[<>]\()(?:add|apropos|apt|apt-cache|apt-get|aptitude|aspell|automysqlbackup|awk|basename|bash|bc|bconsole|bg|bzip2|cal|cargo|cat|cfdisk|chgrp|chkconfig|chmod|chown|chroot|cksum|clear|cmp|column|comm|composer|cp|cron|crontab|csplit|curl|cut|date|dc|dd|ddrescue|debootstrap|df|diff|diff3|dig|dir|dircolors|dirname|dirs|dmesg|docker|docker-compose|du|egrep|eject|env|ethtool|expand|expect|expr|fdformat|fdisk|fg|fgrep|file|find|fmt|fold|format|free|fsck|ftp|fuser|gawk|git|gparted|grep|groupadd|groupdel|groupmod|groups|grub-mkconfig|gzip|halt|head|hg|history|host|hostname|htop|iconv|id|ifconfig|ifdown|ifup|import|install|ip|java|jobs|join|kill|killall|less|link|ln|locate|logname|logrotate|look|lpc|lpr|lprint|lprintd|lprintq|lprm|ls|lsof|lynx|make|man|mc|mdadm|mkconfig|mkdir|mke2fs|mkfifo|mkfs|mkisofs|mknod|mkswap|mmv|more|most|mount|mtools|mtr|mutt|mv|nano|nc|netstat|nice|nl|node|nohup|notify-send|npm|nslookup|op|open|parted|passwd|paste|pathchk|ping|pkill|pnpm|podman|podman-compose|popd|pr|printcap|printenv|ps|pushd|pv|quota|quotacheck|quotactl|ram|rar|rcp|reboot|remsync|rename|renice|rev|rm|rmdir|rpm|rsync|scp|screen|sdiff|sed|sendmail|seq|service|sftp|sh|shellcheck|shuf|shutdown|sleep|slocate|sort|split|ssh|stat|strace|su|sudo|sum|suspend|swapon|sync|sysctl|tac|tail|tar|tee|time|timeout|top|touch|tr|traceroute|tsort|tty|umount|uname|unexpand|uniq|units|unrar|unshar|unzip|update-grub|uptime|useradd|userdel|usermod|users|uudecode|uuencode|v|vcpkg|vdir|vi|vim|virsh|vmstat|wait|watch|wc|wget|whereis|which|who|whoami|write|xargs|xdg-open|yarn|yes|zenity|zip|zsh|zypper)(?=$|[)\s;|&])/,lookbehind:!0},keyword:{pattern:/(^|[\s;|&]|[<>]\()(?:case|do|done|elif|else|esac|fi|for|function|if|in|select|then|until|while)(?=$|[)\s;|&])/,lookbehind:!0},builtin:{pattern:/(^|[\s;|&]|[<>]\()(?:\.|:|alias|bind|break|builtin|caller|cd|command|continue|declare|echo|enable|eval|exec|exit|export|getopts|hash|help|let|local|logout|mapfile|printf|pwd|read|readarray|readonly|return|set|shift|shopt|source|test|times|trap|type|typeset|ulimit|umask|unalias|unset)(?=$|[)\s;|&])/,lookbehind:!0,alias:"class-name"},boolean:{pattern:/(^|[\s;|&]|[<>]\()(?:false|true)(?=$|[)\s;|&])/,lookbehind:!0},"file-descriptor":{pattern:/\B&\d\b/,alias:"important"},operator:{pattern:/\d?<>|>\||\+=|=[=~]?|!=?|<<[<-]?|[&\d]?>>|\d[<>]&?|[<>][&=]?|&[>&]?|\|[&|]?/,inside:{"file-descriptor":{pattern:/^\d/,alias:"important"}}},punctuation:/\$?\(\(?|\)\)?|\.\.|[{}[\];\\]/,number:{pattern:/(^|\s)(?:[1-9]\d*|0)(?:[.,]\d+)?\b/,lookbehind:!0}},t.inside=s.languages.bash;for(var i=["comment","function-name","for-or-select","assign-left","parameter","string","environment","function","keyword","builtin","boolean","file-descriptor","operator","punctuation","number"],r=n.variable[1].inside,o=0;o<i.length;o++)r[i[o]]=s.languages.bash[i[o]];s.languages.sh=s.languages.bash,s.languages.shell=s.languages.bash})(Prism);(function(s){var e=s.languages.powershell={comment:[{pattern:/(^|[^`])<#[\s\S]*?#>/,lookbehind:!0},{pattern:/(^|[^`])#.*/,lookbehind:!0}],string:[{pattern:/"(?:`[\s\S]|[^`"])*"/,greedy:!0,inside:null},{pattern:/'(?:[^']|'')*'/,greedy:!0}],namespace:/\[[a-z](?:\[(?:\[[^\]]*\]|[^\[\]])*\]|[^\[\]])*\]/i,boolean:/\$(?:false|true)\b/i,variable:/\$\w+\b/,function:[/\b(?:Add|Approve|Assert|Backup|Block|Checkpoint|Clear|Close|Compare|Complete|Compress|Confirm|Connect|Convert|ConvertFrom|ConvertTo|Copy|Debug|Deny|Disable|Disconnect|Dismount|Edit|Enable|Enter|Exit|Expand|Export|Find|ForEach|Format|Get|Grant|Group|Hide|Import|Initialize|Install|Invoke|Join|Limit|Lock|Measure|Merge|Move|New|Open|Optimize|Out|Ping|Pop|Protect|Publish|Push|Read|Receive|Redo|Register|Remove|Rename|Repair|Request|Reset|Resize|Resolve|Restart|Restore|Resume|Revoke|Save|Search|Select|Send|Set|Show|Skip|Sort|Split|Start|Step|Stop|Submit|Suspend|Switch|Sync|Tee|Test|Trace|Unblock|Undo|Uninstall|Unlock|Unprotect|Unpublish|Unregister|Update|Use|Wait|Watch|Where|Write)-[a-z]+\b/i,/\b(?:ac|cat|chdir|clc|cli|clp|clv|compare|copy|cp|cpi|cpp|cvpa|dbp|del|diff|dir|ebp|echo|epal|epcsv|epsn|erase|fc|fl|ft|fw|gal|gbp|gc|gci|gcs|gdr|gi|gl|gm|gp|gps|group|gsv|gu|gv|gwmi|iex|ii|ipal|ipcsv|ipsn|irm|iwmi|iwr|kill|lp|ls|measure|mi|mount|move|mp|mv|nal|ndr|ni|nv|ogv|popd|ps|pushd|pwd|rbp|rd|rdr|ren|ri|rm|rmdir|rni|rnp|rp|rv|rvpa|rwmi|sal|saps|sasv|sbp|sc|select|set|shcm|si|sl|sleep|sls|sort|sp|spps|spsv|start|sv|swmi|tee|trcm|type|write)\b/i],keyword:/\b(?:Begin|Break|Catch|Class|Continue|Data|Define|Do|DynamicParam|Else|ElseIf|End|Exit|Filter|Finally|For|ForEach|From|Function|If|InlineScript|Parallel|Param|Process|Return|Sequence|Switch|Throw|Trap|Try|Until|Using|Var|While|Workflow)\b/i,operator:{pattern:/(^|\W)(?:!|-(?:b?(?:and|x?or)|as|(?:Not)?(?:Contains|In|Like|Match)|eq|ge|gt|is(?:Not)?|Join|le|lt|ne|not|Replace|sh[lr])\b|-[-=]?|\+[+=]?|[*\/%]=?)/i,lookbehind:!0},punctuation:/[|{}[\];(),.]/};e.string[0].inside={function:{pattern:/(^|[^`])\$\((?:\$\([^\r\n()]*\)|(?!\$\()[^\r\n)])*\)/,lookbehind:!0,inside:e},boolean:e.boolean,variable:e.variable}})(Prism);(function(s){var e=/%%?[~:\w]+%?|!\S+!/,t={pattern:/\/[a-z?]+(?=[ :]|$):?|-[a-z]\b|--[a-z-]+\b/im,alias:"attr-name",inside:{punctuation:/:/}},n=/"(?:[\\"]"|[^"])*"(?!")/,i=/(?:\b|-)\d+\b/;s.languages.batch={comment:[/^::.*/m,{pattern:/((?:^|[&(])[ \t]*)rem\b(?:[^^&)\r\n]|\^(?:\r\n|[\s\S]))*/im,lookbehind:!0}],label:{pattern:/^:.*/m,alias:"property"},command:[{pattern:/((?:^|[&(])[ \t]*)for(?: \/[a-z?](?:[ :](?:"[^"]*"|[^\s"/]\S*))?)* \S+ in \([^)]+\) do/im,lookbehind:!0,inside:{keyword:/\b(?:do|in)\b|^for\b/i,string:n,parameter:t,variable:e,number:i,punctuation:/[()',]/}},{pattern:/((?:^|[&(])[ \t]*)if(?: \/[a-z?](?:[ :](?:"[^"]*"|[^\s"/]\S*))?)* (?:not )?(?:cmdextversion \d+|defined \w+|errorlevel \d+|exist \S+|(?:"[^"]*"|(?!")(?:(?!==)\S)+)?(?:==| (?:equ|geq|gtr|leq|lss|neq) )(?:"[^"]*"|[^\s"]\S*))/im,lookbehind:!0,inside:{keyword:/\b(?:cmdextversion|defined|errorlevel|exist|not)\b|^if\b/i,string:n,parameter:t,variable:e,number:i,operator:/\^|==|\b(?:equ|geq|gtr|leq|lss|neq)\b/i}},{pattern:/((?:^|[&()])[ \t]*)else\b/im,lookbehind:!0,inside:{keyword:/^else\b/i}},{pattern:/((?:^|[&(])[ \t]*)set(?: \/[a-z](?:[ :](?:"[^"]*"|[^\s"/]\S*))?)* (?:[^^&)\r\n]|\^(?:\r\n|[\s\S]))*/im,lookbehind:!0,inside:{keyword:/^set\b/i,string:n,parameter:t,variable:[e,/\w+(?=(?:[*\/%+\-&^|]|<<|>>)?=)/],number:i,operator:/[*\/%+\-&^|]=?|<<=?|>>=?|[!~_=]/,punctuation:/[()',]/}},{pattern:/((?:^|[&(])[ \t]*@?)\w+\b(?:"(?:[\\"]"|[^"])*"(?!")|[^"^&)\r\n]|\^(?:\r\n|[\s\S]))*/m,lookbehind:!0,inside:{keyword:/^\w+\b/,string:n,parameter:t,label:{pattern:/(^\s*):\S+/m,lookbehind:!0,alias:"property"},variable:e,number:i,operator:/\^/}}],operator:/[&@]/,punctuation:/[()']/}})(Prism);(function(s){var e=/[*&][^\s[\]{},]+/,t=/!(?:<[\w\-%#;/?:@&=+$,.!~*'()[\]]+>|(?:[a-zA-Z\d-]*!)?[\w\-%#;/?:@&=+$.~*'()]+)?/,n="(?:"+t.source+"(?:[ ]+"+e.source+")?|"+e.source+"(?:[ ]+"+t.source+")?)",i=/(?:[^\s\x00-\x08\x0e-\x1f!"#%&'*,\-:>?@[\]`{|}\x7f-\x84\x86-\x9f\ud800-\udfff\ufffe\uffff]|[?:-]<PLAIN>)(?:[ \t]*(?:(?![#:])<PLAIN>|:<PLAIN>))*/.source.replace(/<PLAIN>/g,function(){return/[^\s\x00-\x08\x0e-\x1f,[\]{}\x7f-\x84\x86-\x9f\ud800-\udfff\ufffe\uffff]/.source}),r=/"(?:[^"\\\r\n]|\\.)*"|'(?:[^'\\\r\n]|\\.)*'/.source;function o(a,c){c=(c||"").replace(/m/g,"")+"m";var l=/([:\-,[{]\s*(?:\s<<prop>>[ \t]+)?)(?:<<value>>)(?=[ \t]*(?:$|,|\]|\}|(?:[\r\n]\s*)?#))/.source.replace(/<<prop>>/g,function(){return n}).replace(/<<value>>/g,function(){return a});return RegExp(l,c)}s.languages.yaml={scalar:{pattern:RegExp(/([\-:]\s*(?:\s<<prop>>[ \t]+)?[|>])[ \t]*(?:((?:\r?\n|\r)[ \t]+)\S[^\r\n]*(?:\2[^\r\n]+)*)/.source.replace(/<<prop>>/g,function(){return n})),lookbehind:!0,alias:"string"},comment:/#.*/,key:{pattern:RegExp(/((?:^|[:\-,[{\r\n?])[ \t]*(?:<<prop>>[ \t]+)?)<<key>>(?=\s*:\s)/.source.replace(/<<prop>>/g,function(){return n}).replace(/<<key>>/g,function(){return"(?:"+i+"|"+r+")"})),lookbehind:!0,greedy:!0,alias:"atrule"},directive:{pattern:/(^[ \t]*)%.+/m,lookbehind:!0,alias:"important"},datetime:{pattern:o(/\d{4}-\d\d?-\d\d?(?:[tT]|[ \t]+)\d\d?:\d{2}:\d{2}(?:\.\d*)?(?:[ \t]*(?:Z|[-+]\d\d?(?::\d{2})?))?|\d{4}-\d{2}-\d{2}|\d\d?:\d{2}(?::\d{2}(?:\.\d*)?)?/.source),lookbehind:!0,alias:"number"},boolean:{pattern:o(/false|true/.source,"i"),lookbehind:!0,alias:"important"},null:{pattern:o(/null|~/.source,"i"),lookbehind:!0,alias:"important"},string:{pattern:o(r),lookbehind:!0,greedy:!0},number:{pattern:o(/[+-]?(?:0x[\da-f]+|0o[0-7]+|(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?|\.inf|\.nan)/.source,"i"),lookbehind:!0},tag:t,important:e,punctuation:/---|[:[\]{}\-,|>?]|\.\.\./},s.languages.yml=s.languages.yaml})(Prism);Prism.languages.json={property:{pattern:/(^|[^\\])"(?:\\.|[^\\"\r\n])*"(?=\s*:)/,lookbehind:!0,greedy:!0},string:{pattern:/(^|[^\\])"(?:\\.|[^\\"\r\n])*"(?!\s*:)/,lookbehind:!0,greedy:!0},comment:{pattern:/\/\/.*|\/\*[\s\S]*?(?:\*\/|$)/,greedy:!0},number:/-?\b\d+(?:\.\d+)?(?:e[+-]?\d+)?\b/i,punctuation:/[{}[\],]/,operator:/:/,boolean:/\b(?:false|true)\b/,null:{pattern:/\bnull\b/,alias:"keyword"}};Prism.languages.webmanifest=Prism.languages.json;Prism.languages.sql={comment:{pattern:/(^|[^\\])(?:\/\*[\s\S]*?\*\/|(?:--|\/\/|#).*)/,lookbehind:!0},variable:[{pattern:/@(["'`])(?:\\[\s\S]|(?!\1)[^\\])+\1/,greedy:!0},/@[\w.$]+/],string:{pattern:/(^|[^@\\])("|')(?:\\[\s\S]|(?!\2)[^\\]|\2\2)*\2/,greedy:!0,lookbehind:!0},identifier:{pattern:/(^|[^@\\])`(?:\\[\s\S]|[^`\\]|``)*`/,greedy:!0,lookbehind:!0,inside:{punctuation:/^`|`$/}},function:/\b(?:AVG|COUNT|FIRST|FORMAT|LAST|LCASE|LEN|MAX|MID|MIN|MOD|NOW|ROUND|SUM|UCASE)(?=\s*\()/i,keyword:/\b(?:ACTION|ADD|AFTER|ALGORITHM|ALL|ALTER|ANALYZE|ANY|APPLY|AS|ASC|AUTHORIZATION|AUTO_INCREMENT|BACKUP|BDB|BEGIN|BERKELEYDB|BIGINT|BINARY|BIT|BLOB|BOOL|BOOLEAN|BREAK|BROWSE|BTREE|BULK|BY|CALL|CASCADED?|CASE|CHAIN|CHAR(?:ACTER|SET)?|CHECK(?:POINT)?|CLOSE|CLUSTERED|COALESCE|COLLATE|COLUMNS?|COMMENT|COMMIT(?:TED)?|COMPUTE|CONNECT|CONSISTENT|CONSTRAINT|CONTAINS(?:TABLE)?|CONTINUE|CONVERT|CREATE|CROSS|CURRENT(?:_DATE|_TIME|_TIMESTAMP|_USER)?|CURSOR|CYCLE|DATA(?:BASES?)?|DATE(?:TIME)?|DAY|DBCC|DEALLOCATE|DEC|DECIMAL|DECLARE|DEFAULT|DEFINER|DELAYED|DELETE|DELIMITERS?|DENY|DESC|DESCRIBE|DETERMINISTIC|DISABLE|DISCARD|DISK|DISTINCT|DISTINCTROW|DISTRIBUTED|DO|DOUBLE|DROP|DUMMY|DUMP(?:FILE)?|DUPLICATE|ELSE(?:IF)?|ENABLE|ENCLOSED|END|ENGINE|ENUM|ERRLVL|ERRORS|ESCAPED?|EXCEPT|EXEC(?:UTE)?|EXISTS|EXIT|EXPLAIN|EXTENDED|FETCH|FIELDS|FILE|FILLFACTOR|FIRST|FIXED|FLOAT|FOLLOWING|FOR(?: EACH ROW)?|FORCE|FOREIGN|FREETEXT(?:TABLE)?|FROM|FULL|FUNCTION|GEOMETRY(?:COLLECTION)?|GLOBAL|GOTO|GRANT|GROUP|HANDLER|HASH|HAVING|HOLDLOCK|HOUR|IDENTITY(?:COL|_INSERT)?|IF|IGNORE|IMPORT|INDEX|INFILE|INNER|INNODB|INOUT|INSERT|INT|INTEGER|INTERSECT|INTERVAL|INTO|INVOKER|ISOLATION|ITERATE|JOIN|KEYS?|KILL|LANGUAGE|LAST|LEAVE|LEFT|LEVEL|LIMIT|LINENO|LINES|LINESTRING|LOAD|LOCAL|LOCK|LONG(?:BLOB|TEXT)|LOOP|MATCH(?:ED)?|MEDIUM(?:BLOB|INT|TEXT)|MERGE|MIDDLEINT|MINUTE|MODE|MODIFIES|MODIFY|MONTH|MULTI(?:LINESTRING|POINT|POLYGON)|NATIONAL|NATURAL|NCHAR|NEXT|NO|NONCLUSTERED|NULLIF|NUMERIC|OFF?|OFFSETS?|ON|OPEN(?:DATASOURCE|QUERY|ROWSET)?|OPTIMIZE|OPTION(?:ALLY)?|ORDER|OUT(?:ER|FILE)?|OVER|PARTIAL|PARTITION|PERCENT|PIVOT|PLAN|POINT|POLYGON|PRECEDING|PRECISION|PREPARE|PREV|PRIMARY|PRINT|PRIVILEGES|PROC(?:EDURE)?|PUBLIC|PURGE|QUICK|RAISERROR|READS?|REAL|RECONFIGURE|REFERENCES|RELEASE|RENAME|REPEAT(?:ABLE)?|REPLACE|REPLICATION|REQUIRE|RESIGNAL|RESTORE|RESTRICT|RETURN(?:ING|S)?|REVOKE|RIGHT|ROLLBACK|ROUTINE|ROW(?:COUNT|GUIDCOL|S)?|RTREE|RULE|SAVE(?:POINT)?|SCHEMA|SECOND|SELECT|SERIAL(?:IZABLE)?|SESSION(?:_USER)?|SET(?:USER)?|SHARE|SHOW|SHUTDOWN|SIMPLE|SMALLINT|SNAPSHOT|SOME|SONAME|SQL|START(?:ING)?|STATISTICS|STATUS|STRIPED|SYSTEM_USER|TABLES?|TABLESPACE|TEMP(?:ORARY|TABLE)?|TERMINATED|TEXT(?:SIZE)?|THEN|TIME(?:STAMP)?|TINY(?:BLOB|INT|TEXT)|TOP?|TRAN(?:SACTIONS?)?|TRIGGER|TRUNCATE|TSEQUAL|TYPES?|UNBOUNDED|UNCOMMITTED|UNDEFINED|UNION|UNIQUE|UNLOCK|UNPIVOT|UNSIGNED|UPDATE(?:TEXT)?|USAGE|USE|USER|USING|VALUES?|VAR(?:BINARY|CHAR|CHARACTER|YING)|VIEW|WAITFOR|WARNINGS|WHEN|WHERE|WHILE|WITH(?: ROLLUP|IN)?|WORK|WRITE(?:TEXT)?|YEAR)\b/i,boolean:/\b(?:FALSE|NULL|TRUE)\b/i,number:/\b0x[\da-f]+\b|\b\d+(?:\.\d*)?|\B\.\d+\b/i,operator:/[-+*\/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?|\b(?:AND|BETWEEN|DIV|ILIKE|IN|IS|LIKE|NOT|OR|REGEXP|RLIKE|SOUNDS LIKE|XOR)\b/i,punctuation:/[;[\]()`,.]/};Prism.languages.scss=Prism.languages.extend("css",{comment:{pattern:/(^|[^\\])(?:\/\*[\s\S]*?\*\/|\/\/.*)/,lookbehind:!0},atrule:{pattern:/@[\w-](?:\([^()]+\)|[^()\s]|\s+(?!\s))*?(?=\s+[{;])/,inside:{rule:/@[\w-]+/}},url:/(?:[-a-z]+-)?url(?=\()/i,selector:{pattern:/(?=\S)[^@;{}()]?(?:[^@;{}()\s]|\s+(?!\s)|#\{\$[-\w]+\})+(?=\s*\{(?:\}|\s|[^}][^:{}]*[:{][^}]))/,inside:{parent:{pattern:/&/,alias:"important"},placeholder:/%[-\w]+/,variable:/\$[-\w]+|#\{\$[-\w]+\}/}},property:{pattern:/(?:[-\w]|\$[-\w]|#\{\$[-\w]+\})+(?=\s*:)/,inside:{variable:/\$[-\w]+|#\{\$[-\w]+\}/}}});Prism.languages.insertBefore("scss","atrule",{keyword:[/@(?:content|debug|each|else(?: if)?|extend|for|forward|function|if|import|include|mixin|return|use|warn|while)\b/i,{pattern:/( )(?:from|through)(?= )/,lookbehind:!0}]});Prism.languages.insertBefore("scss","important",{variable:/\$[-\w]+|#\{\$[-\w]+\}/});Prism.languages.insertBefore("scss","function",{"module-modifier":{pattern:/\b(?:as|hide|show|with)\b/i,alias:"keyword"},placeholder:{pattern:/%[-\w]+/,alias:"selector"},statement:{pattern:/\B!(?:default|optional)\b/i,alias:"keyword"},boolean:/\b(?:false|true)\b/,null:{pattern:/\bnull\b/,alias:"keyword"},operator:{pattern:/(\s)(?:[-+*\/%]|[=!]=|<=?|>=?|and|not|or)(?=\s)/,lookbehind:!0}});Prism.languages.scss.atrule.inside.rest=Prism.languages.scss;(function(s){s.languages.sass=s.languages.extend("css",{comment:{pattern:/^([ \t]*)\/[\/*].*(?:(?:\r?\n|\r)\1[ \t].+)*/m,lookbehind:!0,greedy:!0}}),s.languages.insertBefore("sass","atrule",{"atrule-line":{pattern:/^(?:[ \t]*)[@+=].+/m,greedy:!0,inside:{atrule:/(?:@[\w-]+|[+=])/}}}),delete s.languages.sass.atrule;var e=/\$[-\w]+|#\{\$[-\w]+\}/,t=[/[+*\/%]|[=!]=|<=?|>=?|\b(?:and|not|or)\b/,{pattern:/(\s)-(?=\s)/,lookbehind:!0}];s.languages.insertBefore("sass","property",{"variable-line":{pattern:/^[ \t]*\$.+/m,greedy:!0,inside:{punctuation:/:/,variable:e,operator:t}},"property-line":{pattern:/^[ \t]*(?:[^:\s]+ *:.*|:[^:\s].*)/m,greedy:!0,inside:{property:[/[^:\s]+(?=\s*:)/,{pattern:/(:)[^:\s]+/,lookbehind:!0}],punctuation:/:/,variable:e,operator:t,important:s.languages.sass.important}}}),delete s.languages.sass.property,delete s.languages.sass.important,s.languages.insertBefore("sass","punctuation",{selector:{pattern:/^([ \t]*)\S(?:,[^,\r\n]+|[^,\r\n]*)(?:,[^,\r\n]+)*(?:,(?:\r?\n|\r)\1[ \t]+\S(?:,[^,\r\n]+|[^,\r\n]*)(?:,[^,\r\n]+)*)*/m,lookbehind:!0,greedy:!0}})})(Prism);Prism.languages.less=Prism.languages.extend("css",{comment:[/\/\*[\s\S]*?\*\//,{pattern:/(^|[^\\])\/\/.*/,lookbehind:!0}],atrule:{pattern:/@[\w-](?:\((?:[^(){}]|\([^(){}]*\))*\)|[^(){};\s]|\s+(?!\s))*?(?=\s*\{)/,inside:{punctuation:/[:()]/}},selector:{pattern:/(?:@\{[\w-]+\}|[^{};\s@])(?:@\{[\w-]+\}|\((?:[^(){}]|\([^(){}]*\))*\)|[^(){};@\s]|\s+(?!\s))*?(?=\s*\{)/,inside:{variable:/@+[\w-]+/}},property:/(?:@\{[\w-]+\}|[\w-])+(?:\+_?)?(?=\s*:)/,operator:/[+\-*\/]/});Prism.languages.insertBefore("less","property",{variable:[{pattern:/@[\w-]+\s*:/,inside:{punctuation:/:/}},/@@?[\w-]+/],"mixin-usage":{pattern:/([{;]\s*)[.#](?!\d)[\w-].*?(?=[(;])/,lookbehind:!0,alias:"function"}});(function(s){s.languages.typescript=s.languages.extend("javascript",{"class-name":{pattern:/(\b(?:class|extends|implements|instanceof|interface|new|type)\s+)(?!keyof\b)(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?:\s*<(?:[^<>]|<(?:[^<>]|<[^<>]*>)*>)*>)?/,lookbehind:!0,greedy:!0,inside:null},builtin:/\b(?:Array|Function|Promise|any|boolean|console|never|number|string|symbol|unknown)\b/}),s.languages.typescript.keyword.push(/\b(?:abstract|declare|is|keyof|readonly|require)\b/,/\b(?:asserts|infer|interface|module|namespace|type)\b(?=\s*(?:[{_$a-zA-Z\xA0-\uFFFF]|$))/,/\btype\b(?=\s*(?:[\{*]|$))/),delete s.languages.typescript.parameter,delete s.languages.typescript["literal-property"];var e=s.languages.extend("typescript",{});delete e["class-name"],s.languages.typescript["class-name"].inside=e,s.languages.insertBefore("typescript","function",{decorator:{pattern:/@[$\w\xA0-\uFFFF]+/,inside:{at:{pattern:/^@/,alias:"operator"},function:/^[\s\S]+/}},"generic-function":{pattern:/#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*\s*<(?:[^<>]|<(?:[^<>]|<[^<>]*>)*>)*>(?=\s*\()/,greedy:!0,inside:{function:/^#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*/,generic:{pattern:/<[\s\S]+/,alias:"class-name",inside:e}}}}),s.languages.ts=s.languages.typescript})(Prism);(function(s){var e=s.util.clone(s.languages.javascript),t=/(?:\s|\/\/.*(?!.)|\/\*(?:[^*]|\*(?!\/))\*\/)/.source,n=/(?:\{(?:\{(?:\{[^{}]*\}|[^{}])*\}|[^{}])*\})/.source,i=/(?:\{<S>*\.{3}(?:[^{}]|<BRACES>)*\})/.source;function r(c,l){return c=c.replace(/<S>/g,function(){return t}).replace(/<BRACES>/g,function(){return n}).replace(/<SPREAD>/g,function(){return i}),RegExp(c,l)}i=r(i).source,s.languages.jsx=s.languages.extend("markup",e),s.languages.jsx.tag.pattern=r(/<\/?(?:[\w.:-]+(?:<S>+(?:[\w.:$-]+(?:=(?:"(?:\\[\s\S]|[^\\"])*"|'(?:\\[\s\S]|[^\\'])*'|[^\s{'"/>=]+|<BRACES>))?|<SPREAD>))*<S>*\/?)?>/.source),s.languages.jsx.tag.inside.tag.pattern=/^<\/?[^\s>\/]*/,s.languages.jsx.tag.inside["attr-value"].pattern=/=(?!\{)(?:"(?:\\[\s\S]|[^\\"])*"|'(?:\\[\s\S]|[^\\'])*'|[^\s'">]+)/,s.languages.jsx.tag.inside.tag.inside["class-name"]=/^[A-Z]\w*(?:\.[A-Z]\w*)*$/,s.languages.jsx.tag.inside.comment=e.comment,s.languages.insertBefore("inside","attr-name",{spread:{pattern:r(/<SPREAD>/.source),inside:s.languages.jsx}},s.languages.jsx.tag),s.languages.insertBefore("inside","special-attr",{script:{pattern:r(/=<BRACES>/.source),alias:"language-javascript",inside:{"script-punctuation":{pattern:/^=(?=\{)/,alias:"punctuation"},rest:s.languages.jsx}}},s.languages.jsx.tag);var o=function(c){return c?typeof c=="string"?c:typeof c.content=="string"?c.content:c.content.map(o).join(""):""},a=function(c){for(var l=[],u=0;u<c.length;u++){var h=c[u],d=!1;if(typeof h!="string"&&(h.type==="tag"&&h.content[0]&&h.content[0].type==="tag"?h.content[0].content[0].content==="</"?l.length>0&&l[l.length-1].tagName===o(h.content[0].content[1])&&l.pop():h.content[h.content.length-1].content==="/>"||l.push({tagName:o(h.content[0].content[1]),openedBraces:0}):l.length>0&&h.type==="punctuation"&&h.content==="{"?l[l.length-1].openedBraces++:l.length>0&&l[l.length-1].openedBraces>0&&h.type==="punctuation"&&h.content==="}"?l[l.length-1].openedBraces--:d=!0),(d||typeof h=="string")&&l.length>0&&l[l.length-1].openedBraces===0){var p=o(h);u<c.length-1&&(typeof c[u+1]=="string"||c[u+1].type==="plain-text")&&(p+=o(c[u+1]),c.splice(u+1,1)),u>0&&(typeof c[u-1]=="string"||c[u-1].type==="plain-text")&&(p=o(c[u-1])+p,c.splice(u-1,1),u--),c[u]=new s.Token("plain-text",p,null,p)}h.content&&typeof h.content!="string"&&a(h.content)}};s.hooks.add("after-tokenize",function(c){c.language!=="jsx"&&c.language!=="tsx"||a(c.tokens)})})(Prism);(function(s){var e=s.util.clone(s.languages.typescript);s.languages.tsx=s.languages.extend("jsx",e),delete s.languages.tsx.parameter,delete s.languages.tsx["literal-property"];var t=s.languages.tsx.tag;t.pattern=RegExp(/(^|[^\w$]|(?=<\/))/.source+"(?:"+t.pattern.source+")",t.pattern.flags),t.lookbehind=!0})(Prism);(function(s){var e=/(?:[\w-]+|'[^'\n\r]*'|"(?:\\.|[^\\"\r\n])*")/.source;function t(n){return n.replace(/__/g,function(){return e})}s.languages.toml={comment:{pattern:/#.*/,greedy:!0},table:{pattern:RegExp(t(/(^[\t ]*\[\s*(?:\[\s*)?)__(?:\s*\.\s*__)*(?=\s*\])/.source),"m"),lookbehind:!0,greedy:!0,alias:"class-name"},key:{pattern:RegExp(t(/(^[\t ]*|[{,]\s*)__(?:\s*\.\s*__)*(?=\s*=)/.source),"m"),lookbehind:!0,greedy:!0,alias:"property"},string:{pattern:/"""(?:\\[\s\S]|[^\\])*?"""|'''[\s\S]*?'''|'[^'\n\r]*'|"(?:\\.|[^\\"\r\n])*"/,greedy:!0},date:[{pattern:/\b\d{4}-\d{2}-\d{2}(?:[T\s]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})?)?\b/i,alias:"number"},{pattern:/\b\d{2}:\d{2}:\d{2}(?:\.\d+)?\b/,alias:"number"}],number:/(?:\b0(?:x[\da-zA-Z]+(?:_[\da-zA-Z]+)*|o[0-7]+(?:_[0-7]+)*|b[10]+(?:_[10]+)*))\b|[-+]?\b\d+(?:_\d+)*(?:\.\d+(?:_\d+)*)?(?:[eE][+-]?\d+(?:_\d+)*)?\b|[-+]?\b(?:inf|nan)\b/,boolean:/\b(?:false|true)\b/,punctuation:/[.,=[\]{}]/}})(Prism);Prism.languages.ini={comment:{pattern:/(^[ \f\t\v]*)[#;][^\n\r]*/m,lookbehind:!0},section:{pattern:/(^[ \f\t\v]*)\[[^\n\r\]]*\]?/m,lookbehind:!0,inside:{"section-name":{pattern:/(^\[[ \f\t\v]*)[^ \f\t\v\]]+(?:[ \f\t\v]+[^ \f\t\v\]]+)*/,lookbehind:!0,alias:"selector"},punctuation:/\[|\]/}},key:{pattern:/(^[ \f\t\v]*)[^ \f\n\r\t\v=]+(?:[ \f\t\v]+[^ \f\n\r\t\v=]+)*(?=[ \f\t\v]*=)/m,lookbehind:!0,alias:"attr-name"},value:{pattern:/(=[ \f\t\v]*)[^ \f\n\r\t\v]+(?:[ \f\t\v]+[^ \f\n\r\t\v]+)*/,lookbehind:!0,alias:"attr-value",inside:{"inner-value":{pattern:/^("|').+(?=\1$)/,lookbehind:!0}}},punctuation:/=/};(function(s){var e=/(?:\\.|[^\\\n\r]|(?:\n|\r\n?)(?![\r\n]))/.source;function t(u){return u=u.replace(/<inner>/g,function(){return e}),RegExp(/((?:^|[^\\])(?:\\{2})*)/.source+"(?:"+u+")")}var n=/(?:\\.|``(?:[^`\r\n]|`(?!`))+``|`[^`\r\n]+`|[^\\|\r\n`])+/.source,i=/\|?__(?:\|__)+\|?(?:(?:\n|\r\n?)|(?![\s\S]))/.source.replace(/__/g,function(){return n}),r=/\|?[ \t]*:?-{3,}:?[ \t]*(?:\|[ \t]*:?-{3,}:?[ \t]*)+\|?(?:\n|\r\n?)/.source;s.languages.markdown=s.languages.extend("markup",{}),s.languages.insertBefore("markdown","prolog",{"front-matter-block":{pattern:/(^(?:\s*[\r\n])?)---(?!.)[\s\S]*?[\r\n]---(?!.)/,lookbehind:!0,greedy:!0,inside:{punctuation:/^---|---$/,"front-matter":{pattern:/\S+(?:\s+\S+)*/,alias:["yaml","language-yaml"],inside:s.languages.yaml}}},blockquote:{pattern:/^>(?:[\t ]*>)*/m,alias:"punctuation"},table:{pattern:RegExp("^"+i+r+"(?:"+i+")*","m"),inside:{"table-data-rows":{pattern:RegExp("^("+i+r+")(?:"+i+")*$"),lookbehind:!0,inside:{"table-data":{pattern:RegExp(n),inside:s.languages.markdown},punctuation:/\|/}},"table-line":{pattern:RegExp("^("+i+")"+r+"$"),lookbehind:!0,inside:{punctuation:/\||:?-{3,}:?/}},"table-header-row":{pattern:RegExp("^"+i+"$"),inside:{"table-header":{pattern:RegExp(n),alias:"important",inside:s.languages.markdown},punctuation:/\|/}}}},code:[{pattern:/((?:^|\n)[ \t]*\n|(?:^|\r\n?)[ \t]*\r\n?)(?: {4}|\t).+(?:(?:\n|\r\n?)(?: {4}|\t).+)*/,lookbehind:!0,alias:"keyword"},{pattern:/^```[\s\S]*?^```$/m,greedy:!0,inside:{"code-block":{pattern:/^(```.*(?:\n|\r\n?))[\s\S]+?(?=(?:\n|\r\n?)^```$)/m,lookbehind:!0},"code-language":{pattern:/^(```).+/,lookbehind:!0},punctuation:/```/}}],title:[{pattern:/\S.*(?:\n|\r\n?)(?:==+|--+)(?=[ \t]*$)/m,alias:"important",inside:{punctuation:/==+$|--+$/}},{pattern:/(^\s*)#.+/m,lookbehind:!0,alias:"important",inside:{punctuation:/^#+|#+$/}}],hr:{pattern:/(^\s*)([*-])(?:[\t ]*\2){2,}(?=\s*$)/m,lookbehind:!0,alias:"punctuation"},list:{pattern:/(^\s*)(?:[*+-]|\d+\.)(?=[\t ].)/m,lookbehind:!0,alias:"punctuation"},"url-reference":{pattern:/!?\[[^\]]+\]:[\t ]+(?:\S+|<(?:\\.|[^>\\])+>)(?:[\t ]+(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\((?:\\.|[^)\\])*\)))?/,inside:{variable:{pattern:/^(!?\[)[^\]]+/,lookbehind:!0},string:/(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\((?:\\.|[^)\\])*\))$/,punctuation:/^[\[\]!:]|[<>]/},alias:"url"},bold:{pattern:t(/\b__(?:(?!_)<inner>|_(?:(?!_)<inner>)+_)+__\b|\*\*(?:(?!\*)<inner>|\*(?:(?!\*)<inner>)+\*)+\*\*/.source),lookbehind:!0,greedy:!0,inside:{content:{pattern:/(^..)[\s\S]+(?=..$)/,lookbehind:!0,inside:{}},punctuation:/\*\*|__/}},italic:{pattern:t(/\b_(?:(?!_)<inner>|__(?:(?!_)<inner>)+__)+_\b|\*(?:(?!\*)<inner>|\*\*(?:(?!\*)<inner>)+\*\*)+\*/.source),lookbehind:!0,greedy:!0,inside:{content:{pattern:/(^.)[\s\S]+(?=.$)/,lookbehind:!0,inside:{}},punctuation:/[*_]/}},strike:{pattern:t(/(~~?)(?:(?!~)<inner>)+\2/.source),lookbehind:!0,greedy:!0,inside:{content:{pattern:/(^~~?)[\s\S]+(?=\1$)/,lookbehind:!0,inside:{}},punctuation:/~~?/}},"code-snippet":{pattern:/(^|[^\\`])(?:``[^`\r\n]+(?:`[^`\r\n]+)*``(?!`)|`[^`\r\n]+`(?!`))/,lookbehind:!0,greedy:!0,alias:["code","keyword"]},url:{pattern:t(/!?\[(?:(?!\])<inner>)+\](?:\([^\s)]+(?:[\t ]+"(?:\\.|[^"\\])*")?\)|[ \t]?\[(?:(?!\])<inner>)+\])/.source),lookbehind:!0,greedy:!0,inside:{operator:/^!/,content:{pattern:/(^\[)[^\]]+(?=\])/,lookbehind:!0,inside:{}},variable:{pattern:/(^\][ \t]?\[)[^\]]+(?=\]$)/,lookbehind:!0},url:{pattern:/(^\]\()[^\s)]+/,lookbehind:!0},string:{pattern:/(^[ \t]+)"(?:\\.|[^"\\])*"(?=\)$)/,lookbehind:!0}}}}),["url","bold","italic","strike"].forEach(function(u){["url","bold","italic","strike","code-snippet"].forEach(function(h){u!==h&&(s.languages.markdown[u].inside.content.inside[h]=s.languages.markdown[h])})}),s.hooks.add("after-tokenize",function(u){if(u.language!=="markdown"&&u.language!=="md")return;function h(d){if(!(!d||typeof d=="string"))for(var p=0,m=d.length;p<m;p++){var v=d[p];if(v.type!=="code"){h(v.content);continue}var g=v.content[1],y=v.content[3];if(g&&y&&g.type==="code-language"&&y.type==="code-block"&&typeof g.content=="string"){var b=g.content.replace(/\b#/g,"sharp").replace(/\b\+\+/g,"pp");b=(/[a-z][\w-]*/i.exec(b)||[""])[0].toLowerCase();var _="language-"+b;y.alias?typeof y.alias=="string"?y.alias=[y.alias,_]:y.alias.push(_):y.alias=[_]}}}h(u.tokens)}),s.hooks.add("wrap",function(u){if(u.type==="code-block"){for(var h="",d=0,p=u.classes.length;d<p;d++){var m=u.classes[d],v=/language-(.+)/.exec(m);if(v){h=v[1];break}}var g=s.languages[h];if(g)u.content=s.highlight(l(u.content),g,h);else if(h&&h!=="none"&&s.plugins.autoloader){var y="md-"+new Date().valueOf()+"-"+Math.floor(Math.random()*1e16);u.attributes.id=y,s.plugins.autoloader.loadLanguages(h,function(){var b=document.getElementById(y);b&&(b.innerHTML=s.highlight(b.textContent,s.languages[h],h))})}}});var o=RegExp(s.languages.markup.tag.pattern.source,"gi"),a={amp:"&",lt:"<",gt:">",quot:'"'},c=String.fromCodePoint||String.fromCharCode;function l(u){var h=u.replace(o,"");return h=h.replace(/&(\w{1,8}|#x?[\da-f]{1,8});/gi,function(d,p){if(p=p.toLowerCase(),p[0]==="#"){var m;return p[1]==="x"?m=parseInt(p.slice(2),16):m=Number(p.slice(1)),c(m)}else{var v=a[p];return v||d}}),h}s.languages.md=s.languages.markdown})(Prism);const oee={".js":"javascript",".mjs":"javascript",".cjs":"javascript",".jsx":"jsx",".ts":"typescript",".mts":"typescript",".cts":"typescript",".tsx":"tsx",".vue":"markup",".py":"python",".rb":"ruby",".go":"go",".rs":"rust",".java":"java",".c":"c",".h":"c",".cpp":"cpp",".hpp":"cpp",".cc":"cpp",".hh":"cpp",".cxx":"cpp",".cs":"csharp",".php":"php",".swift":"swift",".kt":"kotlin",".kts":"kotlin",".sh":"bash",".bash":"bash",".zsh":"bash",".ps1":"powershell",".bat":"batch",".cmd":"batch",".html":"markup",".htm":"markup",".xhtml":"markup",".xml":"markup",".svg":"markup",".css":"css",".scss":"scss",".sass":"sass",".less":"less",".json":"json",".json5":"json",".yaml":"yaml",".yml":"yaml",".toml":"toml",".ini":"ini",".cfg":"ini",".conf":"ini",".sql":"sql",".md":"markdown",".markdown":"markdown"};function AD(s){const e=s.split("/").pop()||"",t=e.lastIndexOf(".");if(t<0)return null;const n=e.slice(t).toLowerCase();return oee[n]||null}function aee(s){return s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function gT(s,e){if(e){const t=vw.languages[e];if(t)try{return vw.highlight(s,t,e)}catch{}}return aee(s)}const lee=["default-src 'none'","script-src 'unsafe-inline' https:","style-src 'unsafe-inline' https:","img-src data: blob: https:","font-src data: https:","media-src data: blob: https:","connect-src 'none'","form-action 'none'","base-uri 'none'","frame-src 'none'","child-src 'none'","worker-src 'none'","object-src 'none'"].join("; "),cee=`(function () {
'use strict';
if (window.__astrionSandboxGuard) return;
window.__astrionSandboxGuard = true;
function scrollingContainerList(el) {
var list = [];
var node = el.parentElement;
while (node && node !== document.body && node !== document.documentElement) {
var s = window.getComputedStyle(node);
if (/(auto|scroll|overlay)/.test(String(s.overflow) + String(s.overflowY) + String(s.overflowX))) {
list.push(node);
}
node = node.parentElement;
}
list.push(document.scrollingElement || document.documentElement);
return list;
}
function scrollOneContainer(container, el, block) {
var isRoot = container === (document.scrollingElement || document.documentElement);
var eRect = el.getBoundingClientRect();
var viewH = isRoot ? window.innerHeight : container.clientHeight;
var top = isRoot ? eRect.top : eRect.top - container.getBoundingClientRect().top;
var bottom = top + eRect.height;
var delta = 0;
if (block === 'start') delta = top;
else if (block === 'end') delta = bottom - viewH;
else if (block === 'center') delta = top - (viewH - eRect.height) / 2;
else if (top < 0) delta = top;
else if (bottom > viewH) delta = Math.min(bottom - viewH, top);
if (delta) container.scrollTop += delta;
}
function localScrollIntoView(el, arg) {
var block = 'start';
if (arg === false) block = 'end';
else if (arg && typeof arg === 'object' && typeof arg.block === 'string') block = arg.block;
var containers = scrollingContainerList(el);
for (var i = 0; i < containers.length; i++) {
scrollOneContainer(containers[i], el, block);
}
}
Element.prototype.scrollIntoView = function (arg) { localScrollIntoView(this, arg); };
if ('scrollIntoViewIfNeeded' in Element.prototype) {
Element.prototype.scrollIntoViewIfNeeded = function () { localScrollIntoView(this, { block: 'nearest' }); };
}
var origFocus = HTMLElement.prototype.focus;
HTMLElement.prototype.focus = function (options) {
var opts = options && typeof options === 'object'
? Object.assign({}, options, { preventScroll: true })
: { preventScroll: true };
origFocus.call(this, opts);
localScrollIntoView(this, { block: 'nearest' });
};
document.addEventListener('click', function (ev) {
var t = ev.target;
var anchor = t && t.closest ? t.closest('a[href^="#"]') : null;
if (!anchor) return;
var id = (anchor.getAttribute('href') || '').slice(1);
ev.preventDefault();
if (!id) return;
var target = document.getElementById(id);
if (target) {
// 先摘掉 id 再更新 hash避免浏览器默认锚点滚动穿透到宿主页面
target.removeAttribute('id');
try { window.location.hash = id; } catch (err) { /* opaque origin 下忽略 */ }
target.setAttribute('id', id);
localScrollIntoView(target, { block: 'start' });
} else {
try { window.location.hash = id; } catch (err) { /* ignore */ }
}
}, true);
function patchFrame(win) {
try {
win.Element.prototype.scrollIntoView = Element.prototype.scrollIntoView;
win.HTMLElement.prototype.focus = HTMLElement.prototype.focus;
} catch (err) { /* 跨源子 frame 跳过 */ }
}
new MutationObserver(function (mutations) {
for (var i = 0; i < mutations.length; i++) {
var added = mutations[i].addedNodes;
for (var j = 0; j < added.length; j++) {
var n = added[j];
if (!n || n.nodeType !== 1) continue;
var frames = [];
if (n.tagName === 'IFRAME' || n.tagName === 'FRAME') frames.push(n);
if (n.querySelectorAll) {
var found = n.querySelectorAll('iframe,frame');
for (var k = 0; k < found.length; k++) frames.push(found[k]);
}
for (var m = 0; m < frames.length; m++) {
if (frames[m].contentWindow) patchFrame(frames[m].contentWindow);
}
}
}
}).observe(document.documentElement, { childList: true, subtree: true });
})();`;function ED(){return`<meta http-equiv="Content-Security-Policy" content="${lee}" /><script>${cee}<\/script>`}function uee(s){const e=ED(),t=/<head\b[^>]*>/i.exec(s);if(t){const i=t.index+t[0].length;return s.slice(0,i)+e+s.slice(i)}const n=/<html\b[^>]*>/i.exec(s);if(n){const i=n.index+n[0].length;return s.slice(0,i)+`<head>${e}</head>`+s.slice(i)}return e+s}const iM='<!doctype html><html><head><meta charset="utf-8"></head><body></body></html>';function mT(s){const e=(s||"").trim();return e?/<html[\s>]/i.test(e)?uee(e):`<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
${ED()}
<style>
html, body {
margin: 0;
padding: 0;
width: 100%;
min-height: 100%;
background: transparent;
scrollbar-width: thin;
scrollbar-color: rgba(121, 109, 94, 0.48) transparent;
}
html::-webkit-scrollbar, body::-webkit-scrollbar {
width: 8px;
height: 8px;
}
html::-webkit-scrollbar-track, body::-webkit-scrollbar-track {
background: transparent;
}
html::-webkit-scrollbar-thumb, body::-webkit-scrollbar-thumb {
background: rgba(121, 109, 94, 0.48);
border-radius: 8px;
}
html::-webkit-scrollbar-thumb:hover, body::-webkit-scrollbar-thumb:hover {
background: rgba(121, 109, 94, 0.62);
}
</style>
</head>
<body>${e}</body>
</html>`:iM}const GC=500;let qC=0;function hee(){var s;if(typeof window>"u")return!1;try{const e=window.__SHOW_HTML_DEBUG__;if(e===!0||e==="1")return!0;if(e===!1||e==="0")return!1;const t=(s=window.localStorage)==null?void 0:s.getItem("showHtmlDebug");return t==="1"||t==="true"}catch{return!1}}function rM(s,e={}){if(hee()&&!(qC>=GC)){if(qC+=1,qC===GC){console.warn("[SHOW_HTML_DEBUG]","log-limit-reached",{max:GC});return}console.log("[SHOW_HTML_DEBUG]",s,e)}}let Yr=null,lR=!1;function MD(){return!!(Yr!=null&&Yr.root.classList.contains("is-open"))}function dee(){lR||typeof document>"u"||(lR=!0,document.addEventListener("keydown",s=>{s.key!=="Escape"||!MD()||(s.stopPropagation(),oM())}))}function fee(){if(Yr)return Yr;dee();const s=document.createElement("div");s.className="show-html-fullscreen",s.setAttribute("role","dialog"),s.setAttribute("aria-modal","true"),s.setAttribute("aria-label","全屏预览");const e=document.createElement("div");e.className="show-html-fullscreen__bar";const t=document.createElement("div");t.className="show-html-fullscreen__heading";const n=document.createElement("span");n.className="show-html-fullscreen__title",n.textContent="全屏预览";const i=document.createElement("span");i.className="show-html-fullscreen__notice",i.style.display="none",t.appendChild(n),t.appendChild(i);const r=document.createElement("div");r.className="show-html-fullscreen__actions";const o=document.createElement("button");o.type="button",o.className="show-html-fullscreen__btn",o.title="刷新",o.setAttribute("aria-label","刷新"),o.textContent="↻";const a=document.createElement("button");a.type="button",a.className="show-html-fullscreen__btn show-html-fullscreen__btn--close",a.title="关闭Esc",a.setAttribute("aria-label","关闭全屏预览"),a.textContent="✕",r.appendChild(o),r.appendChild(a),e.appendChild(t),e.appendChild(r);const c=document.createElement("div");c.className="show-html-fullscreen__body";const l=document.createElement("iframe");return l.className="show-html-fullscreen__iframe",l.setAttribute("referrerpolicy","no-referrer"),l.setAttribute("allow","fullscreen 'none'"),c.appendChild(l),s.appendChild(e),s.appendChild(c),o.onclick=u=>{u.preventDefault(),u.stopPropagation();const h=Yr;if(!(h!=null&&h.payload))return;const d=h.payload.srcdoc;h.iframe.srcdoc=iM,requestAnimationFrame(()=>{Yr!=null&&Yr.payload&&(Yr.iframe.srcdoc=d)}),rM("fullscreen:refresh",{srcdocLength:d.length})},a.onclick=u=>{u.preventDefault(),u.stopPropagation(),oM()},document.body.appendChild(s),Yr={root:s,iframe:l,titleEl:n,noticeEl:i,payload:null},Yr}function xD(s){if(typeof document>"u")return;const e=fee();e.payload=s,e.titleEl.textContent=s.title||"全屏预览";const t=(s.notice||"").trim();e.noticeEl.textContent=t,e.noticeEl.style.display=t?"":"none",e.iframe.setAttribute("sandbox",s.allowScripts?"allow-scripts":""),e.iframe.srcdoc=s.srcdoc,e.root.classList.add("is-open"),document.documentElement.classList.add("show-html-fullscreen-open"),rM("fullscreen:open",{allowScripts:s.allowScripts,srcdocLength:s.srcdoc.length,hasNotice:!!t})}function oM(){const s=Yr;!s||!MD()||(s.root.classList.remove("is-open"),document.documentElement.classList.remove("show-html-fullscreen-open"),s.payload=null,s.iframe.srcdoc=iM,rM("fullscreen:close",{}))}var pee={9306(s,e,t){var n=t(4901),i=t(6823),r=TypeError;s.exports=function(o){if(n(o))return o;throw new r(i(o)+" is not a function")}},3506(s,e,t){var n=t(3925),i=String,r=TypeError;s.exports=function(o){if(n(o))return o;throw new r("Can't set "+i(o)+" as a prototype")}},7080(s,e,t){var n=t(4402).has;s.exports=function(i){return n(i),i}},3463(s){var e=TypeError;s.exports=function(t){if(typeof t=="string")return t;throw new e("Argument is not a string")}},4328(s,e,t){var n=t(4995),i=new n.WeakMap,r=n.set,o=n.remove;s.exports=function(a){return r(i,a,1),o(i,a),a}},6557(s,e,t){var n=t(4995).has;s.exports=function(i){return n(i),i}},6469(s,e,t){var n=t(8227),i=t(2360),r=t(4913).f,o=n("unscopables"),a=Array.prototype;a[o]===void 0&&r(a,o,{configurable:!0,value:i(null)}),s.exports=function(c){a[o][c]=!0}},679(s,e,t){var n=t(1625),i=TypeError;s.exports=function(r,o){if(n(o,r))return r;throw new i("Incorrect invocation")}},3972(s,e,t){var n=t(34),i=String,r=TypeError;s.exports=function(o){if(o===void 0||n(o))return o;throw new r(i(o)+" is not an object or undefined")}},8551(s,e,t){var n=t(34),i=String,r=TypeError;s.exports=function(o){if(n(o))return o;throw new r(i(o)+" is not an object")}},4154(s,e,t){var n=t(6955),i=TypeError;s.exports=function(r){if(n(r)==="Uint8Array")return r;throw new i("Argument is not an Uint8Array")}},7811(s){s.exports=typeof ArrayBuffer<"u"&&typeof DataView<"u"},7394(s,e,t){var n=t(4576),i=t(6706),r=t(2195),o=n.ArrayBuffer,a=n.TypeError;s.exports=o&&i(o.prototype,"byteLength","get")||function(c){if(r(c)!=="ArrayBuffer")throw new a("ArrayBuffer expected");return c.byteLength}},3238(s,e,t){var n=t(4576),i=t(7811),r=t(7394),o=n.DataView;s.exports=function(a){if(!i||r(a)!==0)return!1;try{return new o(a),!1}catch{return!0}}},5169(s,e,t){var n=t(3238),i=TypeError;s.exports=function(r){if(n(r))throw new i("ArrayBuffer is detached");return r}},5636(s,e,t){var n=t(4576),i=t(9504),r=t(6706),o=t(7696),a=t(5169),c=t(7394),l=t(4483),u=t(1548),h=n.structuredClone,d=n.ArrayBuffer,p=n.DataView,m=Math.max,v=Math.min,g=d.prototype,y=p.prototype,b=i(g.slice),_=r(g,"resizable","get"),w=r(g,"maxByteLength","get"),S=i(y.getInt8),C=i(y.setInt8);s.exports=(u||l)&&function(T,k,A){var M=c(T),R=k===void 0?M:o(k),P=!_||!_(T),L;if(a(T),u&&(T=h(T,{transfer:[T]}),M===R&&(A||P)))return T;if(M>=R&&(!A||P))L=b(T,0,R);else{var z=A&&!P&&w?{maxByteLength:m(R,w(T))}:void 0;L=new d(R,z);for(var Q=new p(T),W=new p(L),V=v(R,M),N=0;N<V;N++)C(W,N,S(Q,N))}return u||l(T),L}},4644(s,e,t){var n=t(7811),i=t(3724),r=t(4576),o=t(4901),a=t(34),c=t(9297),l=t(6955),u=t(6823),h=t(6699),d=t(6840),p=t(2106),m=t(1625),v=t(2787),g=t(2967),y=t(8227),b=t(3392),_=t(1181),w=_.enforce,S=_.get,C=r.Int8Array,T=C&&C.prototype,k=r.Uint8ClampedArray,A=k&&k.prototype,M=C&&v(C),R=T&&v(T),P=Object.prototype,L=r.TypeError,z=y("toStringTag"),Q=b("TYPED_ARRAY_TAG"),W="TypedArrayConstructor",V=n&&!!g&&l(r.opera)!=="Opera",N=!1,O,H,G,ee={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8},ie={BigInt64Array:8,BigUint64Array:8},ve=function(be){if(!a(be))return!1;var Re=l(be);return Re==="DataView"||c(ee,Re)||c(ie,Re)},le=function(he){var be=v(he);if(a(be)){var Re=S(be);return Re&&c(Re,W)?Re[W]:le(be)}},oe=function(he){if(!a(he))return!1;var be=l(he);return c(ee,be)||c(ie,be)},I=function(he){if(oe(he))return he;throw new L("Target is not a typed array")},K=function(he){if(o(he)&&(!g||m(M,he)))return he;throw new L(u(he)+" is not a typed array constructor")},X=function(he,be,Re,rt){if(i){if(Re)for(var st in ee){var et=r[st];if(et&&c(et.prototype,he))try{delete et.prototype[he]}catch{try{et.prototype[he]=be}catch{}}}(!R[he]||Re)&&d(R,he,Re?be:V&&T[he]||be,rt)}},J=function(he,be,Re){var rt,st;if(i){if(g){if(Re){for(rt in ee)if(st=r[rt],st&&c(st,he))try{delete st[he]}catch{}}if(!M[he]||Re)try{return d(M,he,Re?be:V&&M[he]||be)}catch{}else return}for(rt in ee)st=r[rt],st&&(!st[he]||Re)&&d(st,he,be)}};for(O in ee)H=r[O],G=H&&H.prototype,G?w(G)[W]=H:V=!1;for(O in ie)H=r[O],G=H&&H.prototype,G&&(w(G)[W]=H);if((!V||!o(M)||M===Function.prototype)&&(M=function(){throw new L("Incorrect invocation")},V))for(O in ee)r[O]&&g(r[O],M);if((!V||!R||R===P)&&(R=M.prototype,V))for(O in ee)r[O]&&g(r[O].prototype,R);if(V&&v(A)!==R&&g(A,R),i&&!c(R,z)){N=!0,p(R,z,{configurable:!0,get:function(){return a(this)?this[Q]:void 0}});for(O in ee)r[O]&&h(r[O].prototype,Q,O)}s.exports={NATIVE_ARRAY_BUFFER_VIEWS:V,TYPED_ARRAY_TAG:N&&Q,aTypedArray:I,aTypedArrayConstructor:K,exportTypedArrayMethod:X,exportTypedArrayStaticMethod:J,getTypedArrayConstructor:le,isView:ve,isTypedArray:oe,TypedArray:M,TypedArrayPrototype:R}},5370(s,e,t){var n=t(6198);s.exports=function(i,r,o){for(var a=0,c=arguments.length>2?o:n(r),l=new i(c);c>a;)l[a]=r[a++];return l}},9617(s,e,t){var n=t(5397),i=t(5610),r=t(6198),o=function(a){return function(c,l,u){var h=n(c),d=r(h);if(d===0)return!a&&-1;var p=i(u,d),m;if(a&&l!==l){for(;d>p;)if(m=h[p++],m!==m)return!0}else for(;d>p;p++)if((a||p in h)&&h[p]===l)return a||p||0;return!a&&-1}};s.exports={includes:o(!0),indexOf:o(!1)}},4527(s,e,t){var n=t(3724),i=t(4376),r=TypeError,o=Object.getOwnPropertyDescriptor,a=n&&!function(){if(this!==void 0)return!0;try{Object.defineProperty([],"length",{writable:!1}).length=1}catch(c){return c instanceof TypeError}}();s.exports=a?function(c,l){if(i(c)&&!o(c,"length").writable)throw new r("Cannot set read only .length");return c.length=l}:function(c,l){return c.length=l}},7680(s,e,t){var n=t(9504);s.exports=n([].slice)},2804(s){var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t=e+"+/",n=e+"-_",i=function(r){for(var o={},a=0;a<64;a++)o[r.charAt(a)]=a;return o};s.exports={i2c:t,c2i:i(t),i2cUrl:n,c2iUrl:i(n)}},6319(s,e,t){var n=t(8551),i=t(9539);s.exports=function(r,o,a,c){try{return c?o(n(a)[0],a[1]):o(a)}catch(l){i(r,"throw",l)}}},2195(s,e,t){var n=t(9504),i=n({}.toString),r=n("".slice);s.exports=function(o){return r(i(o),8,-1)}},6955(s,e,t){var n=t(2140),i=t(4901),r=t(2195),o=t(8227),a=o("toStringTag"),c=Object,l=r(function(){return arguments}())==="Arguments",u=function(h,d){try{return h[d]}catch{}};s.exports=n?r:function(h){var d,p,m;return h===void 0?"Undefined":h===null?"Null":typeof(p=u(d=c(h),a))=="string"?p:l?r(d):(m=r(d))==="Object"&&i(d.callee)?"Arguments":m}},7740(s,e,t){var n=t(9297),i=t(5031),r=t(7347),o=t(4913);s.exports=function(a,c,l){for(var u=i(c),h=o.f,d=r.f,p=0;p<u.length;p++){var m=u[p];!n(a,m)&&!(l&&n(l,m))&&h(a,m,d(c,m))}}},2211(s,e,t){var n=t(9039);s.exports=!n(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype})},2529(s){s.exports=function(e,t){return{value:e,done:t}}},6699(s,e,t){var n=t(3724),i=t(4913),r=t(6980);s.exports=n?function(o,a,c){return i.f(o,a,r(1,c))}:function(o,a,c){return o[a]=c,o}},6980(s){s.exports=function(e,t){return{enumerable:!(e&1),configurable:!(e&2),writable:!(e&4),value:t}}},4659(s,e,t){var n=t(3724),i=t(4913),r=t(6980);s.exports=function(o,a,c){n?i.f(o,a,r(0,c)):o[a]=c}},2106(s,e,t){var n=t(283),i=t(4913);s.exports=function(r,o,a){return a.get&&n(a.get,o,{getter:!0}),a.set&&n(a.set,o,{setter:!0}),i.f(r,o,a)}},6840(s,e,t){var n=t(4901),i=t(4913),r=t(283),o=t(9433);s.exports=function(a,c,l,u){u||(u={});var h=u.enumerable,d=u.name!==void 0?u.name:c;if(n(l)&&r(l,d,u),u.global)h?a[c]=l:o(c,l);else{try{u.unsafe?a[c]&&(h=!0):delete a[c]}catch{}h?a[c]=l:i.f(a,c,{value:l,enumerable:!1,configurable:!u.nonConfigurable,writable:!u.nonWritable})}return a}},6279(s,e,t){var n=t(6840);s.exports=function(i,r,o){for(var a in r)n(i,a,r[a],o);return i}},9433(s,e,t){var n=t(4576),i=Object.defineProperty;s.exports=function(r,o){try{i(n,r,{value:o,configurable:!0,writable:!0})}catch{n[r]=o}return o}},3724(s,e,t){var n=t(9039);s.exports=!n(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})},4483(s,e,t){var n=t(4576),i=t(9429),r=t(1548),o=n.structuredClone,a=n.ArrayBuffer,c=n.MessageChannel,l=!1,u,h,d,p;if(r)l=function(m){o(m,{transfer:[m]})};else if(a)try{c||(u=i("worker_threads"),u&&(c=u.MessageChannel)),c&&(h=new c,d=new a(2),p=function(m){h.port1.postMessage(null,[m])},d.byteLength===2&&(p(d),d.byteLength===0&&(l=p)))}catch{}s.exports=l},4055(s,e,t){var n=t(4576),i=t(34),r=n.document,o=i(r)&&i(r.createElement);s.exports=function(a){return o?r.createElement(a):{}}},6837(s){var e=TypeError,t=9007199254740991;s.exports=function(n){if(n>t)throw new e("Maximum allowed index exceeded");return n}},5002(s){s.exports={IndexSizeError:{s:"INDEX_SIZE_ERR",c:1,m:1},DOMStringSizeError:{s:"DOMSTRING_SIZE_ERR",c:2,m:0},HierarchyRequestError:{s:"HIERARCHY_REQUEST_ERR",c:3,m:1},WrongDocumentError:{s:"WRONG_DOCUMENT_ERR",c:4,m:1},InvalidCharacterError:{s:"INVALID_CHARACTER_ERR",c:5,m:1},NoDataAllowedError:{s:"NO_DATA_ALLOWED_ERR",c:6,m:0},NoModificationAllowedError:{s:"NO_MODIFICATION_ALLOWED_ERR",c:7,m:1},NotFoundError:{s:"NOT_FOUND_ERR",c:8,m:1},NotSupportedError:{s:"NOT_SUPPORTED_ERR",c:9,m:1},InUseAttributeError:{s:"INUSE_ATTRIBUTE_ERR",c:10,m:1},InvalidStateError:{s:"INVALID_STATE_ERR",c:11,m:1},SyntaxError:{s:"SYNTAX_ERR",c:12,m:1},InvalidModificationError:{s:"INVALID_MODIFICATION_ERR",c:13,m:1},NamespaceError:{s:"NAMESPACE_ERR",c:14,m:1},InvalidAccessError:{s:"INVALID_ACCESS_ERR",c:15,m:1},ValidationError:{s:"VALIDATION_ERR",c:16,m:0},TypeMismatchError:{s:"TYPE_MISMATCH_ERR",c:17,m:1},SecurityError:{s:"SECURITY_ERR",c:18,m:1},NetworkError:{s:"NETWORK_ERR",c:19,m:1},AbortError:{s:"ABORT_ERR",c:20,m:1},URLMismatchError:{s:"URL_MISMATCH_ERR",c:21,m:1},QuotaExceededError:{s:"QUOTA_EXCEEDED_ERR",c:22,m:1},TimeoutError:{s:"TIMEOUT_ERR",c:23,m:1},InvalidNodeTypeError:{s:"INVALID_NODE_TYPE_ERR",c:24,m:1},DataCloneError:{s:"DATA_CLONE_ERR",c:25,m:1}}},8727(s){s.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]},6193(s,e,t){var n=t(4215);s.exports=n==="NODE"},2839(s,e,t){var n=t(4576),i=n.navigator,r=i&&i.userAgent;s.exports=r?String(r):""},9519(s,e,t){var n=t(4576),i=t(2839),r=n.process,o=n.Deno,a=r&&r.versions||o&&o.version,c=a&&a.v8,l,u;c&&(l=c.split("."),u=l[0]>0&&l[0]<4?1:+(l[0]+l[1])),!u&&i&&(l=i.match(/Edge\/(\d+)/),(!l||l[1]>=74)&&(l=i.match(/Chrome\/(\d+)/),l&&(u=+l[1]))),s.exports=u},4215(s,e,t){var n=t(4576),i=t(2839),r=t(2195),o=function(a){return i.slice(0,a.length)===a};s.exports=function(){return o("Bun/")?"BUN":o("Cloudflare-Workers")?"CLOUDFLARE":o("Deno/")?"DENO":o("Node.js/")?"NODE":n.Bun&&typeof Bun.version=="string"?"BUN":n.Deno&&typeof Deno.version=="object"?"DENO":r(n.process)==="process"?"NODE":n.window&&n.document?"BROWSER":"REST"}()},8574(s,e,t){var n=t(9504),i=Error,r=n("".replace),o=function(l){return String(new i(l).stack)}("zxcasd"),a=/\n\s*at [^:]*:[^\n]*/,c=a.test(o);s.exports=function(l,u){if(c&&typeof l=="string"&&!i.prepareStackTrace)for(;u--;)l=r(l,a,"");return l}},6518(s,e,t){var n=t(4576),i=t(7347).f,r=t(6699),o=t(6840),a=t(9433),c=t(7740),l=t(2796);s.exports=function(u,h){var d=u.target,p=u.global,m=u.stat,v,g,y,b,_,w;if(p?g=n:m?g=n[d]||a(d,{}):g=n[d]&&n[d].prototype,g)for(y in h){if(_=h[y],u.dontCallGetSet?(w=i(g,y),b=w&&w.value):b=g[y],v=l(p?y:d+(m?".":"#")+y,u.forced),!v&&b!==void 0){if(typeof _==typeof b)continue;c(_,b)}(u.sham||b&&b.sham)&&r(_,"sham",!0),o(g,y,_,u)}}},9039(s){s.exports=function(e){try{return!!e()}catch{return!0}}},8745(s,e,t){var n=t(616),i=Function.prototype,r=i.apply,o=i.call;s.exports=typeof Reflect=="object"&&Reflect.apply||(n?o.bind(r):function(){return o.apply(r,arguments)})},6080(s,e,t){var n=t(7476),i=t(9306),r=t(616),o=n(n.bind);s.exports=function(a,c){return i(a),c===void 0?a:r?o(a,c):function(){return a.apply(c,arguments)}}},616(s,e,t){var n=t(9039);s.exports=!n(function(){var i=(function(){}).bind();return typeof i!="function"||i.hasOwnProperty("prototype")})},9565(s,e,t){var n=t(616),i=Function.prototype.call;s.exports=n?i.bind(i):function(){return i.apply(i,arguments)}},350(s,e,t){var n=t(3724),i=t(9297),r=Function.prototype,o=n&&Object.getOwnPropertyDescriptor,a=i(r,"name"),c=a&&(function(){}).name==="something",l=a&&(!n||n&&o(r,"name").configurable);s.exports={EXISTS:a,PROPER:c,CONFIGURABLE:l}},6706(s,e,t){var n=t(9504),i=t(9306);s.exports=function(r,o,a){try{return n(i(Object.getOwnPropertyDescriptor(r,o)[a]))}catch{}}},7476(s,e,t){var n=t(2195),i=t(9504);s.exports=function(r){if(n(r)==="Function")return i(r)}},9504(s,e,t){var n=t(616),i=Function.prototype,r=i.call,o=n&&i.bind.bind(r,r);s.exports=n?o:function(a){return function(){return r.apply(a,arguments)}}},944(s){var e=TypeError;s.exports=function(t){var n=t&&t.alphabet;if(n===void 0||n==="base64"||n==="base64url")return n||"base64";throw new e("Incorrect `alphabet` option")}},9429(s,e,t){var n=t(4576),i=t(6193);s.exports=function(r){if(i){try{return n.process.getBuiltinModule(r)}catch{}try{return Function('return require("'+r+'")')()}catch{}}}},7751(s,e,t){var n=t(4576),i=t(4901),r=function(o){return i(o)?o:void 0};s.exports=function(o,a){return arguments.length<2?r(n[o]):n[o]&&n[o][a]}},1767(s){s.exports=function(e){return{iterator:e,next:e.next,done:!1}}},8646(s,e,t){var n=t(9565),i=t(8551),r=t(1767),o=t(851);s.exports=function(a,c){(!c||typeof a!="string")&&i(a);var l=o(a);return r(i(l!==void 0?n(l,a):a))}},851(s,e,t){var n=t(6955),i=t(5966),r=t(4117),o=t(6269),a=t(8227),c=a("iterator");s.exports=function(l){if(!r(l))return i(l,c)||i(l,"@@iterator")||o[n(l)]}},81(s,e,t){var n=t(9565),i=t(9306),r=t(8551),o=t(6823),a=t(851),c=TypeError;s.exports=function(l,u){var h=arguments.length<2?a(l):u;if(i(h))return r(n(h,l));throw new c(o(l)+" is not iterable")}},5966(s,e,t){var n=t(9306),i=t(4117);s.exports=function(r,o){var a=r[o];return i(a)?void 0:n(a)}},3789(s,e,t){var n=t(9306),i=t(8551),r=t(9565),o=t(1291),a=t(1767),c="Invalid size",l=RangeError,u=TypeError,h=Math.max,d=function(p,m){this.set=p,this.size=h(m,0),this.has=n(p.has),this.keys=n(p.keys)};d.prototype={getIterator:function(){return a(i(r(this.keys,this.set)))},includes:function(p){return r(this.has,this.set,p)}},s.exports=function(p){i(p);var m=+p.size;if(m!==m)throw new u(c);var v=o(m);if(v<0)throw new l(c);return new d(p,v)}},4576(s){var e=function(t){return t&&t.Math===Math&&t};s.exports=e(typeof globalThis=="object"&&globalThis)||e(typeof window=="object"&&window)||e(typeof self=="object"&&self)||e(typeof global=="object"&&global)||e(typeof this=="object"&&this)||function(){return this}()||Function("return this")()},9297(s,e,t){var n=t(9504),i=t(8981),r=n({}.hasOwnProperty);s.exports=Object.hasOwn||function(a,c){return r(i(a),c)}},421(s){s.exports={}},397(s,e,t){var n=t(7751);s.exports=n("document","documentElement")},5917(s,e,t){var n=t(3724),i=t(9039),r=t(4055);s.exports=!n&&!i(function(){return Object.defineProperty(r("div"),"a",{get:function(){return 7}}).a!==7})},7055(s,e,t){var n=t(9504),i=t(9039),r=t(2195),o=Object,a=n("".split);s.exports=i(function(){return!o("z").propertyIsEnumerable(0)})?function(c){return r(c)==="String"?a(c,""):o(c)}:o},3167(s,e,t){var n=t(4901),i=t(34),r=t(2967);s.exports=function(o,a,c){var l,u;return r&&n(l=a.constructor)&&l!==c&&i(u=l.prototype)&&u!==c.prototype&&r(o,u),o}},3706(s,e,t){var n=t(9504),i=t(4901),r=t(7629),o=n(Function.toString);i(r.inspectSource)||(r.inspectSource=function(a){return o(a)}),s.exports=r.inspectSource},1181(s,e,t){var n=t(8622),i=t(4576),r=t(34),o=t(6699),a=t(9297),c=t(7629),l=t(6119),u=t(421),h="Object already initialized",d=i.TypeError,p=i.WeakMap,m,v,g,y=function(S){return g(S)?v(S):m(S,{})},b=function(S){return function(C){var T;if(!r(C)||(T=v(C)).type!==S)throw new d("Incompatible receiver, "+S+" required");return T}};if(n||c.state){var _=c.state||(c.state=new p);_.get=_.get,_.has=_.has,_.set=_.set,m=function(S,C){if(_.has(S))throw new d(h);return C.facade=S,_.set(S,C),C},v=function(S){return _.get(S)||{}},g=function(S){return _.has(S)}}else{var w=l("state");u[w]=!0,m=function(S,C){if(a(S,w))throw new d(h);return C.facade=S,o(S,w,C),C},v=function(S){return a(S,w)?S[w]:{}},g=function(S){return a(S,w)}}s.exports={set:m,get:v,has:g,enforce:y,getterFor:b}},4209(s,e,t){var n=t(8227),i=t(6269),r=n("iterator"),o=Array.prototype;s.exports=function(a){return a!==void 0&&(i.Array===a||o[r]===a)}},4376(s,e,t){var n=t(2195);s.exports=Array.isArray||function(r){return n(r)==="Array"}},1108(s,e,t){var n=t(6955);s.exports=function(i){var r=n(i);return r==="BigInt64Array"||r==="BigUint64Array"}},4901(s){var e=typeof document=="object"&&document.all;s.exports=typeof e>"u"&&e!==void 0?function(t){return typeof t=="function"||t===e}:function(t){return typeof t=="function"}},2796(s,e,t){var n=t(9039),i=t(4901),r=/#|\.prototype\./,o=function(h,d){var p=c[a(h)];return p===u?!0:p===l?!1:i(d)?n(d):!!d},a=o.normalize=function(h){return String(h).replace(r,".").toLowerCase()},c=o.data={},l=o.NATIVE="N",u=o.POLYFILL="P";s.exports=o},4117(s){s.exports=function(e){return e==null}},34(s,e,t){var n=t(4901);s.exports=function(i){return typeof i=="object"?i!==null:n(i)}},3925(s,e,t){var n=t(34);s.exports=function(i){return n(i)||i===null}},6395(s){s.exports=!1},5810(s,e,t){var n=t(34),i=t(1181).get;s.exports=function(o){if(!n(o))return!1;var a=i(o);return!!a&&a.type==="RawJSON"}},757(s,e,t){var n=t(7751),i=t(4901),r=t(1625),o=t(7040),a=Object;s.exports=o?function(c){return typeof c=="symbol"}:function(c){var l=n("Symbol");return i(l)&&r(l.prototype,a(c))}},507(s,e,t){var n=t(9565);s.exports=function(i,r,o){for(var a=o?i:i.iterator,c=i.next,l,u;!(l=n(c,a)).done;)if(u=r(l.value),u!==void 0)return u}},2652(s,e,t){var n=t(6080),i=t(9565),r=t(8551),o=t(6823),a=t(4209),c=t(6198),l=t(1625),u=t(81),h=t(851),d=t(9539),p=TypeError,m=function(g,y){this.stopped=g,this.result=y},v=m.prototype;s.exports=function(g,y,b){var _=b&&b.that,w=!!(b&&b.AS_ENTRIES),S=!!(b&&b.IS_RECORD),C=!!(b&&b.IS_ITERATOR),T=!!(b&&b.INTERRUPTED),k=n(y,_),A,M,R,P,L,z,Q,W=function(O){var H=A;return A=void 0,H&&d(H,"normal"),new m(!0,O)},V=function(O){return w?(r(O),T?k(O[0],O[1],W):k(O[0],O[1])):T?k(O,W):k(O)};if(S)A=g.iterator;else if(C)A=g;else{if(M=h(g),!M)throw new p(o(g)+" is not iterable");if(a(M)){for(R=0,P=c(g);P>R;R++)if(L=V(g[R]),L&&l(v,L))return L;return new m(!1)}A=u(g,M)}for(z=S?g.next:A.next;!(Q=i(z,A)).done;){var N=Q.value;try{L=V(N)}catch(O){if(A)d(A,"throw",O);else throw O}if(typeof L=="object"&&L&&l(v,L))return L}return new m(!1)}},1385(s,e,t){var n=t(9539);s.exports=function(i,r,o){for(var a=i.length-1;a>=0;a--)if(i[a]!==void 0)try{o=n(i[a].iterator,r,o)}catch(c){r="throw",o=c}if(r==="throw")throw o;return o}},9539(s,e,t){var n=t(9565),i=t(8551),r=t(5966);s.exports=function(o,a,c){var l,u;i(o);try{if(l=r(o,"return"),!l){if(a==="throw")throw c;return c}l=n(l,o)}catch(h){u=!0,l=h}if(a==="throw")throw c;if(u)throw l;return i(l),c}},9462(s,e,t){var n=t(9565),i=t(2360),r=t(6699),o=t(6279),a=t(8227),c=t(1181),l=t(5966),u=t(7657).IteratorPrototype,h=t(2529),d=t(9539),p=t(1385),m=a("toStringTag"),v="IteratorHelper",g="WrapForValidIterator",y="normal",b="throw",_=c.set,w=function(T){var k=c.getterFor(T?g:v);return o(i(u),{next:function(){var M=k(this);if(T)return M.nextHandler();if(M.done)return h(void 0,!0);try{var R=M.nextHandler();return M.returnHandlerResult?R:h(R,M.done)}catch(P){throw M.done=!0,P}},return:function(){var A=k(this),M=A.iterator,R=A.done;if(A.done=!0,T){var P=l(M,"return");return P?n(P,M):h(void 0,!0)}if(R)return h(void 0,!0);if(A.inner)try{d(A.inner.iterator,y)}catch(L){return d(M,b,L)}if(A.openIters)try{p(A.openIters,y)}catch(L){if(M)return d(M,b,L);throw L}return M&&d(M,y),h(void 0,!0)}})},S=w(!0),C=w(!1);r(C,m,"Iterator Helper"),s.exports=function(T,k,A){var M=function(P,L){L?(L.iterator=P.iterator,L.next=P.next):L=P,L.type=k?g:v,L.returnHandlerResult=!!A,L.nextHandler=T,L.counter=0,L.done=!1,_(this,L)};return M.prototype=k?S:C,M}},684(s){s.exports=function(e,t){var n=typeof Iterator=="function"&&Iterator.prototype[e];if(n)try{n.call({next:null},t).next()}catch{return!0}}},4549(s,e,t){var n=t(4576);s.exports=function(i,r){var o=n.Iterator,a=o&&o.prototype,c=a&&a[i],l=!1;if(c)try{c.call({next:function(){return{done:!0}},return:function(){l=!0}},-1)}catch(u){u instanceof r||(l=!1)}if(!l)return c}},7657(s,e,t){var n=t(9039),i=t(4901),r=t(34),o=t(2360),a=t(2787),c=t(6840),l=t(8227),u=t(6395),h=l("iterator"),d=!1,p,m,v;[].keys&&(v=[].keys(),"next"in v?(m=a(a(v)),m!==Object.prototype&&(p=m)):d=!0);var g=!r(p)||n(function(){var y={};return p[h].call(y)!==y});g?p={}:u&&(p=o(p)),i(p[h])||c(p,h,function(){return this}),s.exports={IteratorPrototype:p,BUGGY_SAFARI_ITERATORS:d}},6269(s){s.exports={}},6198(s,e,t){var n=t(8014);s.exports=function(i){return n(i.length)}},283(s,e,t){var n=t(9504),i=t(9039),r=t(4901),o=t(9297),a=t(3724),c=t(350).CONFIGURABLE,l=t(3706),u=t(1181),h=u.enforce,d=u.get,p=String,m=Object.defineProperty,v=n("".slice),g=n("".replace),y=n([].join),b=a&&!i(function(){return m(function(){},"length",{value:8}).length!==8}),_=String(String).split("String"),w=s.exports=function(S,C,T){v(p(C),0,7)==="Symbol("&&(C="["+g(p(C),/^Symbol\(([^)]*)\).*$/,"$1")+"]"),T&&T.getter&&(C="get "+C),T&&T.setter&&(C="set "+C),(!o(S,"name")||c&&S.name!==C)&&(a?m(S,"name",{value:C,configurable:!0}):S.name=C),b&&T&&o(T,"arity")&&S.length!==T.arity&&m(S,"length",{value:T.arity});try{T&&o(T,"constructor")&&T.constructor?a&&m(S,"prototype",{writable:!1}):S.prototype&&(S.prototype=void 0)}catch{}var k=h(S);return o(k,"source")||(k.source=y(_,typeof C=="string"?C:"")),S};Function.prototype.toString=w(function(){return r(this)&&d(this).source||l(this)},"toString")},2248(s,e,t){var n=t(9504),i=Map.prototype;s.exports={Map,set:n(i.set),get:n(i.get),has:n(i.has),remove:n(i.delete),proto:i}},741(s){var e=Math.ceil,t=Math.floor;s.exports=Math.trunc||function(i){var r=+i;return(r>0?t:e)(r)}},7819(s,e,t){var n=t(9039);s.exports=!n(function(){var i="9007199254740993",r=JSON.rawJSON(i);return!JSON.isRawJSON(r)||JSON.stringify(r)!==i})},6043(s,e,t){var n=t(9306),i=TypeError,r=function(o){var a,c;this.promise=new o(function(l,u){if(a!==void 0||c!==void 0)throw new i("Bad Promise constructor");a=l,c=u}),this.resolve=n(a),this.reject=n(c)};s.exports.f=function(o){return new r(o)}},2603(s,e,t){var n=t(655);s.exports=function(i,r){return i===void 0?arguments.length<2?"":r:n(i)}},4149(s){var e=RangeError;s.exports=function(t){if(t===t)return t;throw new e("NaN is not allowed")}},2360(s,e,t){var n=t(8551),i=t(6801),r=t(8727),o=t(421),a=t(397),c=t(4055),l=t(6119),u=">",h="<",d="prototype",p="script",m=l("IE_PROTO"),v=function(){},g=function(S){return h+p+u+S+h+"/"+p+u},y=function(S){S.write(g("")),S.close();var C=S.parentWindow.Object;return S=null,C},b=function(){var S=c("iframe"),C="java"+p+":",T;return S.style.display="none",a.appendChild(S),S.src=String(C),T=S.contentWindow.document,T.open(),T.write(g("document.F=Object")),T.close(),T.F},_,w=function(){try{_=new ActiveXObject("htmlfile")}catch{}w=typeof document<"u"?document.domain&&_?y(_):b():y(_);for(var S=r.length;S--;)delete w[d][r[S]];return w()};o[m]=!0,s.exports=Object.create||function(C,T){var k;return C!==null?(v[d]=n(C),k=new v,v[d]=null,k[m]=C):k=w(),T===void 0?k:i.f(k,T)}},6801(s,e,t){var n=t(3724),i=t(8686),r=t(4913),o=t(8551),a=t(5397),c=t(1072);e.f=n&&!i?Object.defineProperties:function(u,h){o(u);for(var d=a(h),p=c(h),m=p.length,v=0,g;m>v;)r.f(u,g=p[v++],d[g]);return u}},4913(s,e,t){var n=t(3724),i=t(5917),r=t(8686),o=t(8551),a=t(6969),c=TypeError,l=Object.defineProperty,u=Object.getOwnPropertyDescriptor,h="enumerable",d="configurable",p="writable";e.f=n?r?function(v,g,y){if(o(v),g=a(g),o(y),typeof v=="function"&&g==="prototype"&&"value"in y&&p in y&&!y[p]){var b=u(v,g);b&&b[p]&&(v[g]=y.value,y={configurable:d in y?y[d]:b[d],enumerable:h in y?y[h]:b[h],writable:!1})}return l(v,g,y)}:l:function(v,g,y){if(o(v),g=a(g),o(y),i)try{return l(v,g,y)}catch{}if("get"in y||"set"in y)throw new c("Accessors not supported");return"value"in y&&(v[g]=y.value),v}},7347(s,e,t){var n=t(3724),i=t(9565),r=t(8773),o=t(6980),a=t(5397),c=t(6969),l=t(9297),u=t(5917),h=Object.getOwnPropertyDescriptor;e.f=n?h:function(p,m){if(p=a(p),m=c(m),u)try{return h(p,m)}catch{}if(l(p,m))return o(!i(r.f,p,m),p[m])}},8480(s,e,t){var n=t(1828),i=t(8727),r=i.concat("length","prototype");e.f=Object.getOwnPropertyNames||function(a){return n(a,r)}},3717(s,e){e.f=Object.getOwnPropertySymbols},2787(s,e,t){var n=t(9297),i=t(4901),r=t(8981),o=t(6119),a=t(2211),c=o("IE_PROTO"),l=Object,u=l.prototype;s.exports=a?l.getPrototypeOf:function(h){var d=r(h);if(n(d,c))return d[c];var p=d.constructor;return i(p)&&d instanceof p?p.prototype:d instanceof l?u:null}},1625(s,e,t){var n=t(9504);s.exports=n({}.isPrototypeOf)},1828(s,e,t){var n=t(9504),i=t(9297),r=t(5397),o=t(9617).indexOf,a=t(421),c=n([].push);s.exports=function(l,u){var h=r(l),d=0,p=[],m;for(m in h)!i(a,m)&&i(h,m)&&c(p,m);for(;u.length>d;)i(h,m=u[d++])&&(~o(p,m)||c(p,m));return p}},1072(s,e,t){var n=t(1828),i=t(8727);s.exports=Object.keys||function(o){return n(o,i)}},8773(s,e){var t={}.propertyIsEnumerable,n=Object.getOwnPropertyDescriptor,i=n&&!t.call({1:2},1);e.f=i?function(o){var a=n(this,o);return!!a&&a.enumerable}:t},2967(s,e,t){var n=t(6706),i=t(34),r=t(7750),o=t(3506);s.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,c={},l;try{l=n(Object.prototype,"__proto__","set"),l(c,[]),a=c instanceof Array}catch{}return function(h,d){return r(h),o(d),i(h)&&(a?l(h,d):h.__proto__=d),h}}():void 0)},4270(s,e,t){var n=t(9565),i=t(4901),r=t(34),o=TypeError;s.exports=function(a,c){var l,u;if(c==="string"&&i(l=a.toString)&&!r(u=n(l,a))||i(l=a.valueOf)&&!r(u=n(l,a))||c!=="string"&&i(l=a.toString)&&!r(u=n(l,a)))return u;throw new o("Can't convert object to primitive value")}},5031(s,e,t){var n=t(7751),i=t(9504),r=t(8480),o=t(3717),a=t(8551),c=i([].concat);s.exports=n("Reflect","ownKeys")||function(u){var h=r.f(a(u)),d=o.f;return d?c(h,d(u)):h}},8235(s,e,t){var n=t(9504),i=t(9297),r=SyntaxError,o=parseInt,a=String.fromCharCode,c=n("".charAt),l=n("".slice),u=n(/./.exec),h={'\\"':'"',"\\\\":"\\","\\/":"/","\\b":"\b","\\f":"\f","\\n":`
`,"\\r":"\r","\\t":" "},d=/^[\da-f]{4}$/i,p=/^[\u0000-\u001F]$/;s.exports=function(m,v){for(var g=!0,y="";v<m.length;){var b=c(m,v);if(b==="\\"){var _=l(m,v,v+2);if(i(h,_))y+=h[_],v+=2;else if(_==="\\u"){v+=2;var w=l(m,v,v+4);if(!u(d,w))throw new r("Bad Unicode escape at: "+v);y+=a(o(w,16)),v+=4}else throw new r('Unknown escape sequence: "'+_+'"')}else if(b==='"'){g=!1,v++;break}else{if(u(p,b))throw new r("Bad control character in string literal at: "+v);y+=b,v++}}if(g)throw new r("Unterminated string at: "+v);return{value:y,end:v}}},1103(s){s.exports=function(e){try{return{error:!1,value:e()}}catch(t){return{error:!0,value:t}}}},7750(s,e,t){var n=t(4117),i=TypeError;s.exports=function(r){if(n(r))throw new i("Can't call method on "+r);return r}},9286(s,e,t){var n=t(4402),i=t(8469),r=n.Set,o=n.add;s.exports=function(a){var c=new r;return i(a,function(l){o(c,l)}),c}},3440(s,e,t){var n=t(7080),i=t(4402),r=t(9286),o=t(5170),a=t(3789),c=t(8469),l=t(507),u=i.has,h=i.remove;s.exports=function(p){var m=n(this),v=a(p),g=r(m);return o(g)<=v.size?c(g,function(y){v.includes(y)&&h(g,y)}):l(v.getIterator(),function(y){u(g,y)&&h(g,y)}),g}},4402(s,e,t){var n=t(9504),i=Set.prototype;s.exports={Set,add:n(i.add),has:n(i.has),remove:n(i.delete),proto:i}},8750(s,e,t){var n=t(7080),i=t(4402),r=t(5170),o=t(3789),a=t(8469),c=t(507),l=i.Set,u=i.add,h=i.has;s.exports=function(p){var m=n(this),v=o(p),g=new l;return r(m)>v.size?c(v.getIterator(),function(y){h(m,y)&&u(g,y)}):a(m,function(y){v.includes(y)&&u(g,y)}),g}},4449(s,e,t){var n=t(7080),i=t(4402).has,r=t(5170),o=t(3789),a=t(8469),c=t(507),l=t(9539);s.exports=function(h){var d=n(this),p=o(h);if(r(d)<=p.size)return a(d,function(v){if(p.includes(v))return!1},!0)!==!1;var m=p.getIterator();return c(m,function(v){if(i(d,v))return l(m.iterator,"normal",!1)})!==!1}},3838(s,e,t){var n=t(7080),i=t(5170),r=t(8469),o=t(3789);s.exports=function(c){var l=n(this),u=o(c);return i(l)>u.size?!1:r(l,function(h){if(!u.includes(h))return!1},!0)!==!1}},8527(s,e,t){var n=t(7080),i=t(4402).has,r=t(5170),o=t(3789),a=t(507),c=t(9539);s.exports=function(u){var h=n(this),d=o(u);if(r(h)<d.size)return!1;var p=d.getIterator();return a(p,function(m){if(!i(h,m))return c(p.iterator,"normal",!1)})!==!1}},8469(s,e,t){var n=t(9504),i=t(507),r=t(4402),o=r.Set,a=r.proto,c=n(a.forEach),l=n(a.keys),u=l(new o).next;s.exports=function(h,d,p){return p?i({iterator:l(h),next:u},d):c(h,d)}},4916(s,e,t){var n=t(7751),i=function(o){return{size:o,has:function(){return!1},keys:function(){return{next:function(){return{done:!0}}}}}},r=function(o){return{size:o,has:function(){return!0},keys:function(){throw new Error("e")}}};s.exports=function(o,a){var c=n("Set");try{new c()[o](i(0));try{return new c()[o](i(-1)),!1}catch{if(!a)return!0;try{return new c()[o](r(-1/0)),!1}catch{var l=new c([1,2]);return a(l[o](r(1/0)))}}}catch{return!1}}},9835(s){s.exports=function(e){try{var t=new Set,n={size:0,has:function(){return!0},keys:function(){return Object.defineProperty({},"next",{get:function(){return t.clear(),t.add(4),function(){return{done:!0}}}})}},i=t[e](n);return i.size===1&&i.values().next().value===4}catch{return!1}}},5170(s,e,t){var n=t(6706),i=t(4402);s.exports=n(i.proto,"size","get")||function(r){return r.size}},3650(s,e,t){var n=t(7080),i=t(4402),r=t(9286),o=t(3789),a=t(507),c=i.add,l=i.has,u=i.remove;s.exports=function(d){var p=n(this),m=o(d).getIterator(),v=r(p);return a(m,function(g){l(p,g)?u(v,g):c(v,g)}),v}},4204(s,e,t){var n=t(7080),i=t(4402).add,r=t(9286),o=t(3789),a=t(507);s.exports=function(l){var u=n(this),h=o(l).getIterator(),d=r(u);return a(h,function(p){i(d,p)}),d}},6119(s,e,t){var n=t(5745),i=t(3392),r=n("keys");s.exports=function(o){return r[o]||(r[o]=i(o))}},7629(s,e,t){var n=t(6395),i=t(4576),r=t(9433),o="__core-js_shared__",a=s.exports=i[o]||r(o,{});(a.versions||(a.versions=[])).push({version:"3.49.0",mode:n?"pure":"global",copyright:"© 20132025 Denis Pushkarev (zloirock.ru), 20252026 CoreJS Company (core-js.io). All rights reserved.",license:"https://github.com/zloirock/core-js/blob/v3.49.0/LICENSE",source:"https://github.com/zloirock/core-js"})},5745(s,e,t){var n=t(7629);s.exports=function(i,r){return n[i]||(n[i]=r||{})}},1548(s,e,t){var n=t(4576),i=t(9039),r=t(9519),o=t(4215),a=n.structuredClone;s.exports=!!a&&!i(function(){if(o==="DENO"&&r>92||o==="NODE"&&r>94||o==="BROWSER"&&r>97)return!1;var c=new ArrayBuffer(8),l=a(c,{transfer:[c]});return c.byteLength!==0||l.byteLength!==8})},4495(s,e,t){var n=t(9519),i=t(9039),r=t(4576),o=r.String;s.exports=!!Object.getOwnPropertySymbols&&!i(function(){var a=Symbol("symbol detection");return!o(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&n&&n<41})},5610(s,e,t){var n=t(1291),i=Math.max,r=Math.min;s.exports=function(o,a){var c=n(o);return c<0?i(c+a,0):r(c,a)}},5854(s,e,t){var n=t(2777),i=TypeError;s.exports=function(r){var o=n(r,"number");if(typeof o=="number")throw new i("Can't convert number to bigint");return BigInt(o)}},7696(s,e,t){var n=t(1291),i=t(8014),r=RangeError;s.exports=function(o){if(o===void 0)return 0;var a=n(o),c=i(a);if(a!==c)throw new r("Wrong length or index");return c}},5397(s,e,t){var n=t(7055),i=t(7750);s.exports=function(r){return n(i(r))}},1291(s,e,t){var n=t(741);s.exports=function(i){var r=+i;return r!==r||r===0?0:n(r)}},8014(s,e,t){var n=t(1291),i=Math.min;s.exports=function(r){var o=n(r);return o>0?i(o,9007199254740991):0}},8981(s,e,t){var n=t(7750),i=Object;s.exports=function(r){return i(n(r))}},9590(s,e,t){var n=t(1291),i=RangeError;s.exports=function(r){var o=n(r);if(o<0)throw new i("The argument can't be less than 0");return o}},2777(s,e,t){var n=t(9565),i=t(34),r=t(757),o=t(5966),a=t(4270),c=t(8227),l=TypeError,u=c("toPrimitive");s.exports=function(h,d){if(!i(h)||r(h))return h;var p=o(h,u),m;if(p){if(d===void 0&&(d="default"),m=n(p,h,d),!i(m)||r(m))return m;throw new l("Can't convert object to primitive value")}return d===void 0&&(d="number"),a(h,d)}},6969(s,e,t){var n=t(2777),i=t(757);s.exports=function(r){var o=n(r,"string");return i(o)?o:o+""}},2140(s,e,t){var n=t(8227),i=n("toStringTag"),r={};r[i]="z",s.exports=String(r)==="[object z]"},655(s,e,t){var n=t(6955),i=String;s.exports=function(r){if(n(r)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return i(r)}},6823(s){var e=String;s.exports=function(t){try{return e(t)}catch{return"Object"}}},3392(s,e,t){var n=t(9504),i=0,r=Math.random(),o=n(1.1.toString);s.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+o(++i+r,36)}},9143(s,e,t){var n=t(4576),i=t(9504),r=t(3972),o=t(3463),a=t(9297),c=t(2804),l=t(944),u=t(5169),h=c.c2i,d=c.c2iUrl,p=n.SyntaxError,m=n.TypeError,v=i("".charAt),g=function(_,w){for(var S=_.length;w<S;w++){var C=v(_,w);if(C!==" "&&C!==" "&&C!==`
`&&C!=="\f"&&C!=="\r")break}return w},y=function(_,w,S){var C=_.length;C<4&&(_+=C===2?"AA":"A");var T=(w[v(_,0)]<<18)+(w[v(_,1)]<<12)+(w[v(_,2)]<<6)+w[v(_,3)],k=[T>>16&255,T>>8&255,T&255];if(C===2){if(S&&k[1]!==0)throw new p("Extra bits");return[k[0]]}if(C===3){if(S&&k[2]!==0)throw new p("Extra bits");return[k[0],k[1]]}return k},b=function(_,w,S){for(var C=w.length,T=0;T<C;T++)_[S+T]=w[T];return S+C};s.exports=function(_,w,S,C){o(_),r(w);var T=l(w)==="base64"?h:d,k=w?w.lastChunkHandling:void 0;if(k===void 0&&(k="loose"),k!=="loose"&&k!=="strict"&&k!=="stop-before-partial")throw new m("Incorrect `lastChunkHandling` option");S&&u(S.buffer);var A=_.length,M=S||[],R=0,P=0,L="",z=0;if(C)for(;;){if(z=g(_,z),z===A){if(L.length>0){if(k==="stop-before-partial")break;if(k==="loose"){if(L.length===1)throw new p("Malformed padding: exactly one additional character");R=b(M,y(L,T,!1),R)}else throw new p("Missing padding")}P=A;break}var Q=v(_,z);if(++z,Q==="="){if(L.length<2)throw new p("Padding is too early");if(z=g(_,z),L.length===2){if(z===A){if(k==="stop-before-partial")break;throw new p("Malformed padding: only one =")}v(_,z)==="="&&(++z,z=g(_,z))}if(z<A)throw new p("Unexpected character after padding");R=b(M,y(L,T,k==="strict"),R),P=A;break}if(!a(T,Q))throw new p("Unexpected character");var W=C-R;if(W===1&&L.length===2||W===2&&L.length===3||(L+=Q,L.length===4&&(R=b(M,y(L,T,!1),R),L="",P=z,R===C)))break}return{bytes:M,read:P,written:R}}},2303(s,e,t){var n=t(4576),i=t(9504),r=n.Uint8Array,o=n.SyntaxError,a=Math.min,c=i("".match);s.exports=function(l,u){var h=l.length;if(h%2!==0)throw new o("String should be an even number of characters");for(var d=u?a(u.length,h/2):h/2,p=u||new r(d),m=c(l,/.{2}/g),v=0;v<d;v++){var g=+("0x"+m[v]+"0");if(g!==g)throw new o("String should only contain hex characters");p[v]=g>>4}return{bytes:p,read:v<<1}}},7416(s,e,t){var n=t(9039),i=t(8227),r=t(3724),o=t(6395),a=i("iterator");s.exports=!n(function(){var c=new URL("b?a=1&b=2&c=3","https://a"),l=c.searchParams,u=new URLSearchParams("a=1&a=2&b=3"),h="";return c.pathname="c%20d",l.forEach(function(d,p){l.delete("b"),h+=p+d}),u.delete("a",2),u.delete("b",void 0),o&&(!c.toJSON||!u.has("a",1)||u.has("a",2)||!u.has("a",void 0)||u.has("b"))||!l.size&&(o||!r)||!l.sort||c.href!=="https://a/c%20d?a=1&c=3"||l.get("c")!=="3"||String(new URLSearchParams("?a=1"))!=="a=1"||!l[a]||new URL("https://a@b").username!=="a"||new URLSearchParams(new URLSearchParams("a=b")).get("a")!=="b"||new URL("https://тест").host!=="xn--e1aybc"||new URL("https://a#б").hash!=="#%D0%B1"||h!=="a1c3"||new URL("https://x",void 0).host!=="x"})},7040(s,e,t){var n=t(4495);s.exports=n&&!Symbol.sham&&typeof Symbol.iterator=="symbol"},8686(s,e,t){var n=t(3724),i=t(9039);s.exports=n&&i(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})},2812(s){var e=TypeError;s.exports=function(t,n){if(t<n)throw new e("Not enough arguments");return t}},8622(s,e,t){var n=t(4576),i=t(4901),r=n.WeakMap;s.exports=i(r)&&/native code/.test(String(r))},4995(s,e,t){var n=t(9504),i=WeakMap.prototype;s.exports={WeakMap,set:n(i.set),get:n(i.get),has:n(i.has),remove:n(i.delete)}},8227(s,e,t){var n=t(4576),i=t(5745),r=t(9297),o=t(3392),a=t(4495),c=t(7040),l=n.Symbol,u=i("wks"),h=c?l.for||l:l&&l.withoutSetter||o;s.exports=function(d){return r(u,d)||(u[d]=a&&r(l,d)?l[d]:h("Symbol."+d)),u[d]}},6573(s,e,t){var n=t(3724),i=t(2106),r=t(3238),o=ArrayBuffer.prototype;n&&!("detached"in o)&&i(o,"detached",{configurable:!0,get:function(){return r(this)}})},7936(s,e,t){var n=t(6518),i=t(5636);i&&n({target:"ArrayBuffer",proto:!0},{transferToFixedLength:function(){return i(this,arguments.length?arguments[0]:void 0,!1)}})},8100(s,e,t){var n=t(6518),i=t(5636);i&&n({target:"ArrayBuffer",proto:!0},{transfer:function(){return i(this,arguments.length?arguments[0]:void 0,!0)}})},4423(s,e,t){var n=t(6518),i=t(9617).includes,r=t(9039),o=t(6469),a=r(function(){return!Array(1).includes()}),c=r(function(){return[,1].includes(void 0,1)});n({target:"Array",proto:!0,forced:a||c},{includes:function(u){return i(this,u,arguments.length>1?arguments[1]:void 0)}}),o("includes")},4114(s,e,t){var n=t(6518),i=t(8981),r=t(6198),o=t(4527),a=t(6837),c=t(9039),l=c(function(){return[].push.call({length:4294967296},1)!==4294967297}),u=function(){try{Object.defineProperty([],"length",{writable:!1}).push()}catch(d){return d instanceof TypeError}},h=l||!u();n({target:"Array",proto:!0,arity:1,forced:h},{push:function(p){var m=i(this),v=r(m),g=arguments.length;a(v+g);for(var y=0;y<g;y++)m[v]=arguments[y],v++;return o(m,v),v}})},8111(s,e,t){var n=t(6518),i=t(4576),r=t(679),o=t(8551),a=t(4901),c=t(2787),l=t(2106),u=t(4659),h=t(9039),d=t(9297),p=t(8227),m=t(7657).IteratorPrototype,v=t(3724),g=t(6395),y="constructor",b="Iterator",_=p("toStringTag"),w=TypeError,S=i[b],C=g||!a(S)||S.prototype!==m||!h(function(){S({})}),T=function(){if(r(this,m),c(this)===m)throw new w("Abstract class Iterator not directly constructable")},k=function(A,M){v?l(m,A,{configurable:!0,get:function(){return M},set:function(R){if(o(this),this===m)throw new w("You can't redefine this property");d(this,A)?this[A]=R:u(this,A,R)}}):m[A]=M};d(m,_)||k(_,b),(C||!d(m,y)||m[y]===Object)&&k(y,T),T.prototype=m,n({global:!0,constructor:!0,forced:C},{Iterator:T})},9314(s,e,t){var n=t(6518),i=t(9565),r=t(8551),o=t(1767),a=t(4149),c=t(9590),l=t(9539),u=t(9462),h=t(684),d=t(4549),p=t(6395),m=!p&&!h("drop",0),v=!p&&!m&&d("drop",RangeError),g=p||m||v,y=u(function(){for(var b=this.iterator,_=this.next,w,S;this.remaining;)if(this.remaining--,w=r(i(_,b)),S=this.done=!!w.done,S)return;if(w=r(i(_,b)),S=this.done=!!w.done,!S)return w.value});n({target:"Iterator",proto:!0,real:!0,forced:g},{drop:function(_){r(this);var w;try{w=c(a(+_))}catch(S){l(this,"throw",S)}return v?i(v,this,w):new y(o(this),{remaining:w})}})},1148(s,e,t){var n=t(6518),i=t(9565),r=t(2652),o=t(9306),a=t(8551),c=t(1767),l=t(9539),u=t(4549),h=u("every",TypeError);n({target:"Iterator",proto:!0,real:!0,forced:h},{every:function(p){a(this);try{o(p)}catch(g){l(this,"throw",g)}if(h)return i(h,this,p);var m=c(this),v=0;return!r(m,function(g,y){if(!p(g,v++))return y()},{IS_RECORD:!0,INTERRUPTED:!0}).stopped}})},2489(s,e,t){var n=t(6518),i=t(9565),r=t(9306),o=t(8551),a=t(1767),c=t(9462),l=t(6319),u=t(6395),h=t(9539),d=t(684),p=t(4549),m=!u&&!d("filter",function(){}),v=!u&&!m&&p("filter",TypeError),g=u||m||v,y=c(function(){for(var b=this.iterator,_=this.predicate,w=this.next,S,C,T;;){if(S=o(i(w,b)),C=this.done=!!S.done,C)return;if(T=S.value,l(b,_,[T,this.counter++],!0))return T}});n({target:"Iterator",proto:!0,real:!0,forced:g},{filter:function(_){o(this);try{r(_)}catch(w){h(this,"throw",w)}return v?i(v,this,_):new y(a(this),{predicate:_})}})},116(s,e,t){var n=t(6518),i=t(9565),r=t(2652),o=t(9306),a=t(8551),c=t(1767),l=t(9539),u=t(4549),h=u("find",TypeError);n({target:"Iterator",proto:!0,real:!0,forced:h},{find:function(p){a(this);try{o(p)}catch(g){l(this,"throw",g)}if(h)return i(h,this,p);var m=c(this),v=0;return r(m,function(g,y){if(p(g,v++))return y(g)},{IS_RECORD:!0,INTERRUPTED:!0}).result}})},531(s,e,t){var n=t(6518),i=t(9565),r=t(9306),o=t(8551),a=t(1767),c=t(8646),l=t(9462),u=t(9539),h=t(6395),d=t(684),p=t(4549);function m(){try{var _=Iterator.prototype.flatMap.call(new Map([[4,5]]).entries(),function(w){return w});_.next(),_.return()}catch{return!0}}var v=!h&&!d("flatMap",function(){}),g=!h&&!v&&p("flatMap",TypeError),y=h||v||g||m(),b=l(function(){for(var _=this.iterator,w=this.mapper,S,C;;){if(C=this.inner)try{if(S=o(i(C.next,C.iterator)),!S.done)return S.value;this.inner=null}catch(T){u(_,"throw",T)}if(S=o(i(this.next,_)),this.done=!!S.done)return;try{this.inner=c(w(S.value,this.counter++),!1)}catch(T){u(_,"throw",T)}}});n({target:"Iterator",proto:!0,real:!0,forced:y},{flatMap:function(w){o(this);try{r(w)}catch(S){u(this,"throw",S)}return g?i(g,this,w):new b(a(this),{mapper:w,inner:null})}})},7588(s,e,t){var n=t(6518),i=t(9565),r=t(2652),o=t(9306),a=t(8551),c=t(1767),l=t(9539),u=t(4549),h=u("forEach",TypeError);n({target:"Iterator",proto:!0,real:!0,forced:h},{forEach:function(p){a(this);try{o(p)}catch(g){l(this,"throw",g)}if(h)return i(h,this,p);var m=c(this),v=0;r(m,function(g){p(g,v++)},{IS_RECORD:!0})}})},1701(s,e,t){var n=t(6518),i=t(9565),r=t(9306),o=t(8551),a=t(1767),c=t(9462),l=t(6319),u=t(9539),h=t(684),d=t(4549),p=t(6395),m=!p&&!h("map",function(){}),v=!p&&!m&&d("map",TypeError),g=p||m||v,y=c(function(){var b=this.iterator,_=o(i(this.next,b)),w=this.done=!!_.done;if(!w)return l(b,this.mapper,[_.value,this.counter++],!0)});n({target:"Iterator",proto:!0,real:!0,forced:g},{map:function(_){o(this);try{r(_)}catch(w){u(this,"throw",w)}return v?i(v,this,_):new y(a(this),{mapper:_})}})},3579(s,e,t){var n=t(6518),i=t(9565),r=t(2652),o=t(9306),a=t(8551),c=t(1767),l=t(9539),u=t(4549),h=u("some",TypeError);n({target:"Iterator",proto:!0,real:!0,forced:h},{some:function(p){a(this);try{o(p)}catch(g){l(this,"throw",g)}if(h)return i(h,this,p);var m=c(this),v=0;return r(m,function(g,y){if(p(g,v++))return y()},{IS_RECORD:!0,INTERRUPTED:!0}).stopped}})},4972(s,e,t){var n=t(6518),i=t(9565),r=t(8551),o=t(1767),a=t(4149),c=t(9590),l=t(9462),u=t(9539),h=t(684),d=t(4549),p=t(6395),m=!p&&!h("take",1),v=!p&&!m&&d("take",RangeError),g=p||m||v,y=l(function(){var b=this.iterator;if(!this.remaining--)return this.done=!0,u(b,"normal",void 0);var _=r(i(this.next,b)),w=this.done=!!_.done;if(!w)return _.value});n({target:"Iterator",proto:!0,real:!0,forced:g},{take:function(_){r(this);var w;try{w=c(a(+_))}catch(S){u(this,"throw",S)}return v?i(v,this,w):new y(o(this),{remaining:w})}})},9112(s,e,t){var n=t(6518),i=t(3724),r=t(4576),o=t(7751),a=t(9504),c=t(9565),l=t(4901),u=t(34),h=t(4376),d=t(9297),p=t(655),m=t(6198),v=t(4659),g=t(9039),y=t(8235),b=t(4495),_=r.JSON,w=r.Number,S=r.SyntaxError,C=_&&_.parse,T=o("Object","keys"),k=Object.getOwnPropertyDescriptor,A=a("".charAt),M=a("".slice),R=a(/./.exec),P=a([].push),L=/^\d$/,z=/^[1-9]$/,Q=/^[\d-]$/,W=/^[\t\n\r ]$/,V=0,N=1,O=function(oe,I){oe=p(oe);var K=new ie(oe,0),X=K.parse(),J=X.value,he=K.skip(W,X.end);if(he<oe.length)throw new S('Unexpected extra character: "'+A(oe,he)+'" after the parsed data at: '+he);return l(I)?H({"":J},"",I,X):J},H=function(oe,I,K,X){var J=oe[I],he=X&&J===X.value,be=he&&typeof X.source=="string"?{source:X.source}:{},Re,rt,st,et,De;if(u(J)){var xe=h(J),se=he?X.nodes:xe?[]:{};if(xe)for(Re=se.length,st=m(J),et=0;et<st;et++)G(J,et,H(J,""+et,K,et<Re?se[et]:void 0));else for(rt=T(J),st=m(rt),et=0;et<st;et++)De=rt[et],G(J,De,H(J,De,K,d(se,De)?se[De]:void 0))}return c(K,oe,I,J,be)},G=function(oe,I,K){if(i){var X=k(oe,I);if(X&&!X.configurable)return}K===void 0?delete oe[I]:v(oe,I,K)},ee=function(oe,I,K,X){this.value=oe,this.end=I,this.source=K,this.nodes=X},ie=function(oe,I){this.source=oe,this.index=I};ie.prototype={fork:function(oe){return new ie(this.source,oe)},parse:function(){var oe=this.source,I=this.skip(W,this.index),K=this.fork(I),X=A(oe,I);if(R(Q,X))return K.number();switch(X){case"{":return K.object();case"[":return K.array();case'"':return K.string();case"t":return K.keyword(!0);case"f":return K.keyword(!1);case"n":return K.keyword(null)}throw new S('Unexpected character: "'+X+'" at: '+I)},node:function(oe,I,K,X,J){return new ee(I,X,oe?null:M(this.source,K,X),J)},object:function(){for(var oe=this.source,I=this.index+1,K=!1,X={},J={},he=!1;I<oe.length;){if(I=this.until(['"',"}"],I),A(oe,I)==="}"&&!K){I++,he=!0;break}var be=this.fork(I).string(),Re=be.value;I=be.end,I=this.until([":"],I)+1,I=this.skip(W,I),be=this.fork(I).parse(),v(J,Re,be),v(X,Re,be.value),I=this.until([",","}"],be.end);var rt=A(oe,I);if(rt===",")K=!0,I++;else if(rt==="}"){I++,he=!0;break}}if(!he)throw new S("Unterminated object at: "+I);return this.node(N,X,this.index,I,J)},array:function(){for(var oe=this.source,I=this.index+1,K=!1,X=[],J=[],he=!1;I<oe.length;){if(I=this.skip(W,I),A(oe,I)==="]"&&!K){I++,he=!0;break}var be=this.fork(I).parse();if(P(J,be),P(X,be.value),I=this.until([",","]"],be.end),A(oe,I)===",")K=!0,I++;else if(A(oe,I)==="]"){I++,he=!0;break}}if(!he)throw new S("Unterminated array at: "+I);return this.node(N,X,this.index,I,J)},string:function(){var oe=this.index,I=y(this.source,this.index+1);return this.node(V,I.value,oe,I.end)},number:function(){var oe=this.source,I=this.index,K=I;if(A(oe,K)==="-"&&K++,A(oe,K)==="0")K++;else if(R(z,A(oe,K)))K=this.skip(L,K+1);else throw new S("Failed to parse number at: "+K);if(A(oe,K)==="."){var X=K+1;if(K=this.skip(L,X),X===K)throw new S("Failed to parse number's fraction at: "+K)}if(A(oe,K)==="e"||A(oe,K)==="E"){K++,(A(oe,K)==="+"||A(oe,K)==="-")&&K++;var J=K;if(K=this.skip(L,K),J===K)throw new S("Failed to parse number's exponent value at: "+K)}return this.node(V,w(M(oe,I,K)),I,K)},keyword:function(oe){var I=""+oe,K=this.index,X=K+I.length;if(M(this.source,K,X)!==I)throw new S("Failed to parse value at: "+K);return this.node(V,oe,K,X)},skip:function(oe,I){for(var K=this.source;I<K.length&&R(oe,A(K,I));I++);return I},until:function(oe,I){I=this.skip(W,I);for(var K=A(this.source,I),X=0;X<oe.length;X++)if(oe[X]===K)return I;throw new S('Unexpected character: "'+K+'" at: '+I)}};var ve=g(function(){var oe="9007199254740993",I;return C(oe,function(K,X,J){I=J.source}),I!==oe}),le=b&&!g(function(){return 1/C("-0 ")!==-1/0});n({target:"JSON",stat:!0,forced:ve},{parse:function(I,K){return le&&!l(K)?C(I):O(I,K)}})},3110(s,e,t){var n=t(6518),i=t(7751),r=t(8745),o=t(9565),a=t(9504),c=t(9039),l=t(4376),u=t(4901),h=t(5810),d=t(757),p=t(2195),m=t(655),v=t(7680),g=t(8235),y=t(3392),b=t(4495),_=t(7819),w=String,S=i("JSON","stringify"),C=a(/./.exec),T=a("".charAt),k=a("".charCodeAt),A=a("".replace),M=a("".slice),R=a([].push),P=a(1.1.toString),L=/[\uD800-\uDFFF]/g,z=/^[\uD800-\uDBFF]$/,Q=/^[\uDC00-\uDFFF]$/,W=y(),V=W.length,N=!b||c(function(){var ie=i("Symbol")("stringify detection");return S([ie])!=="[null]"||S({a:ie})!=="{}"||S(Object(ie))!=="{}"}),O=c(function(){return S("\uDF06\uD834")!=='"\\udf06\\ud834"'||S("\uDEAD")!=='"\\udead"'}),H=N?function(ie,ve){var le=v(arguments),oe=ee(ve);if(!(!u(oe)&&(ie===void 0||d(ie))))return le[1]=function(I,K){if(u(oe)&&(K=o(oe,this,w(I),K)),!d(K))return K},r(S,null,le)}:S,G=function(ie,ve,le){var oe=T(le,ve-1),I=T(le,ve+1);return C(z,ie)&&!C(Q,I)||C(Q,ie)&&!C(z,oe)?"\\u"+P(k(ie,0),16):ie},ee=function(ie){if(u(ie))return ie;if(l(ie)){for(var ve=ie.length,le=[],oe=0;oe<ve;oe++){var I=ie[oe];typeof I=="string"?R(le,I):(typeof I=="number"||p(I)==="Number"||p(I)==="String")&&R(le,m(I))}var K=le.length,X=!0;return function(J,he){if(X)return X=!1,he;if(l(this))return he;for(var be=0;be<K;be++)if(le[be]===J)return he}}};S&&n({target:"JSON",stat:!0,arity:3,forced:N||O||!_},{stringify:function(ve,le,oe){var I=ee(le),K=[],X=H(ve,function(et,De){var xe=u(I)?o(I,this,w(et),De):De;return!_&&h(xe)?W+(R(K,xe.rawJSON)-1):xe},oe);if(typeof X!="string"||(O&&(X=A(X,L,G)),_))return X;for(var J="",he=X.length,be=0;be<he;be++){var Re=T(X,be);if(Re==='"'){var rt=g(X,++be).end-1,st=M(X,be,rt);J+=M(st,0,V)===W?K[M(st,V)]:'"'+st+'"',be=rt}else J+=Re}return J}})},2731(s,e,t){var n=t(6518),i=t(9306),r=t(2248),o=t(6395),a=r.get,c=r.has,l=r.set;n({target:"Map",proto:!0,real:!0,forced:o},{getOrInsertComputed:function(h,d){var p=c(this,h);if(i(d),p)return a(this,h);h===0&&1/h===-1/0&&(h=0);var m=d(h);return l(this,h,m),m}})},5367(s,e,t){var n=t(6518),i=t(2248),r=t(6395),o=i.get,a=i.has,c=i.set;n({target:"Map",proto:!0,real:!0,forced:r},{getOrInsert:function(u,h){return a(this,u)?o(this,u):(c(this,u,h),h)}})},3068(s,e,t){var n=t(6518),i=t(9504),r=t(2652),o=RangeError,a=TypeError,c=1/0,l=NaN,u=Math.abs,h=Math.pow,d=i([].push),p=h(2,1023),m=h(2,53)-1,v=Number.MAX_VALUE,g=h(2,971),y={},b={},_={},w={},S={},C=function(T,k){var A=T+k,M=k-(A-T);return{hi:A,lo:M}};n({target:"Math",stat:!0},{sumPrecise:function(k){var A=[],M=0,R=w;switch(r(k,function(oe){if(++M>m)throw new o("Maximum allowed index exceeded");if(typeof oe!="number")throw new a("Value is not a number");R!==y&&(oe!==oe?R=y:oe===c?R=R===b?y:_:oe===-c?R=R===_?y:b:(oe!==0||1/oe===c)&&(R===w||R===S)&&(R=S,d(A,oe)))}),R){case y:return l;case b:return-c;case _:return c;case w:return-0}for(var P=[],L=0,z,Q,W,V,N,O,H=0;H<A.length;H++){z=A[H];for(var G=0,ee=0;ee<P.length;ee++){if(Q=P[ee],u(z)<u(Q)&&(O=z,z=Q,Q=O),W=C(z,Q),V=W.hi,N=W.lo,u(V)===c){var ie=V===c?1:-1;L+=ie,z=z-ie*p-ie*p,u(z)<u(Q)&&(O=z,z=Q,Q=O),W=C(z,Q),V=W.hi,N=W.lo}N!==0&&(P[G++]=N),z=V}P.length=G,z!==0&&d(P,z)}var ve=P.length-1;if(V=0,N=0,L!==0){var le=ve>=0?P[ve]:0;if(ve--,u(L)>1||L>0&&le>0||L<0&&le<0)return L>0?c:-c;if(W=C(L*p,le/2),V=W.hi,N=W.lo,N*=2,u(2*V)===c)return V>0?V===p&&N===-(g/2)&&ve>=0&&P[ve]<0?v:c:V===-p&&N===g/2&&ve>=0&&P[ve]>0?-v:-c;N!==0&&(P[++ve]=N,N=0),V*=2}for(;ve>=0&&(W=C(V,P[ve--]),V=W.hi,N=W.lo,N===0););return ve>=0&&(N<0&&P[ve]<0||N>0&&P[ve]>0)&&(Q=N*2,z=V+Q,Q===z-V&&(V=z)),V}})},1689(s,e,t){var n=t(6518),i=t(4576),r=t(8745),o=t(7680),a=t(6043),c=t(9306),l=t(1103),u=i.Promise,h=!1,d=!u||!u.try||l(function(){u.try(function(p){h=p===8},8)}).error||!h;n({target:"Promise",stat:!0,forced:d},{try:function(p){var m=arguments.length>1?o(arguments,1):[],v=a.f(this),g=l(function(){return r(c(p),void 0,m)});return(g.error?v.reject:v.resolve)(g.value),v.promise}})},4628(s,e,t){var n=t(6518),i=t(6043);n({target:"Promise",stat:!0},{withResolvers:function(){var o=i.f(this);return{promise:o.promise,resolve:o.resolve,reject:o.reject}}})},7642(s,e,t){var n=t(6518),i=t(3440),r=t(9039),o=t(4916),a=!o("difference",function(l){return l.size===0}),c=a||r(function(){var l={size:1,has:function(){return!0},keys:function(){var h=0;return{next:function(){var d=h++>1;return u.has(1)&&u.clear(),{done:d,value:2}}}}},u=new Set([1,2,3,4]);return u.difference(l).size!==3});n({target:"Set",proto:!0,real:!0,forced:c},{difference:i})},8004(s,e,t){var n=t(6518),i=t(9039),r=t(8750),o=t(4916),a=!o("intersection",function(c){return c.size===2&&c.has(1)&&c.has(2)})||i(function(){return String(Array.from(new Set([1,2,3]).intersection(new Set([3,2]))))!=="3,2"});n({target:"Set",proto:!0,real:!0,forced:a},{intersection:r})},3853(s,e,t){var n=t(6518),i=t(4449),r=t(4916),o=!r("isDisjointFrom",function(a){return!a});n({target:"Set",proto:!0,real:!0,forced:o},{isDisjointFrom:i})},5876(s,e,t){var n=t(6518),i=t(3838),r=t(4916),o=!r("isSubsetOf",function(a){return a});n({target:"Set",proto:!0,real:!0,forced:o},{isSubsetOf:i})},2475(s,e,t){var n=t(6518),i=t(8527),r=t(4916),o=!r("isSupersetOf",function(a){return!a});n({target:"Set",proto:!0,real:!0,forced:o},{isSupersetOf:i})},5024(s,e,t){var n=t(6518),i=t(3650),r=t(9835),o=t(4916),a=!o("symmetricDifference")||!r("symmetricDifference");n({target:"Set",proto:!0,real:!0,forced:a},{symmetricDifference:i})},1698(s,e,t){var n=t(6518),i=t(4204),r=t(9835),o=t(4916),a=!o("union")||!r("union");n({target:"Set",proto:!0,real:!0,forced:a},{union:i})},9577(s,e,t){var n=t(4644),i=t(1108),r=t(6198),o=t(1291),a=t(5854),c=n.aTypedArray,l=n.getTypedArrayConstructor,u=n.exportTypedArrayMethod,h=RangeError,d=function(){try{new Int8Array(1).with(2,{valueOf:function(){throw 8}})}catch(m){return m===8}}(),p=d&&function(){try{new Int8Array(1).with(-.5,1)}catch{return!0}}();u("with",function(m,v){var g=c(this),y=r(g),b=o(m),_=b<0?y+b:b,w=i(g)?a(v):+v;if(_>=y||_<0)throw new h("Incorrect index");for(var S=new(l(g))(y),C=0;C<y;C++)S[C]=C===_?w:g[C];return S},!d||p)},5213(s,e,t){var n=t(6518),i=t(4576),r=t(5370),o=t(9143),a=i.Uint8Array,c=!a||!a.fromBase64||!function(){try{a.fromBase64("a");return}catch{}try{a.fromBase64("",null)}catch{return!0}}();a&&n({target:"Uint8Array",stat:!0,forced:c},{fromBase64:function(u){var h=o(u,arguments.length>1?arguments[1]:void 0,null,9007199254740991);return r(a,h.bytes)}})},6632(s,e,t){var n=t(6518),i=t(4576),r=t(9143),o=t(4154),a=i.Uint8Array,c=!a||!a.prototype.setFromBase64||!function(){var l=new a([255,255,255,255,255]);try{l.setFromBase64("",null);return}catch{}try{l.setFromBase64("a");return}catch{}try{l.setFromBase64("MjYyZg===")}catch{return l[0]===50&&l[1]===54&&l[2]===50&&l[3]===255&&l[4]===255}}();a&&n({target:"Uint8Array",proto:!0,forced:c},{setFromBase64:function(u){o(this);var h=r(u,arguments.length>1?arguments[1]:void 0,this,this.length);return{read:h.read,written:h.written}}})},4226(s,e,t){var n=t(6518),i=t(4576),r=t(3463),o=t(4154),a=t(5169),c=t(2303);function l(){try{var u=new ArrayBuffer(16,{maxByteLength:1024});new Uint8Array(u).setFromHex("cafed00d")}catch{return!0}}i.Uint8Array&&n({target:"Uint8Array",proto:!0,forced:l()},{setFromHex:function(h){o(this),r(h),a(this.buffer);var d=c(h,this).read;return{read:d,written:d/2}}})},9486(s,e,t){var n=t(6518),i=t(4576),r=t(9504),o=t(3972),a=t(4154),c=t(5169),l=t(2804),u=t(944),h=l.i2c,d=l.i2cUrl,p=r("".charAt),m=i.Uint8Array,v=!m||!m.prototype.toBase64||!function(){try{var g=new m;g.toBase64(null)}catch{return!0}}();m&&n({target:"Uint8Array",proto:!0,forced:v},{toBase64:function(){var y=a(this),b=arguments.length?o(arguments[0]):void 0,_=u(b)==="base64"?h:d,w=!!b&&!!b.omitPadding;c(this.buffer);for(var S="",C=0,T=y.length,k,A=function(M){return p(_,k>>6*M&63)};C+2<T;C+=3)k=(y[C]<<16)+(y[C+1]<<8)+y[C+2],S+=A(3)+A(2)+A(1)+A(0);return C+2===T?(k=(y[C]<<16)+(y[C+1]<<8),S+=A(3)+A(2)+A(1)+(w?"":"=")):C+1===T&&(k=y[C]<<16,S+=A(3)+A(2)+(w?"":"==")),S}})},456(s,e,t){var n=t(6518),i=t(4576),r=t(9504),o=t(4154),a=t(5169),c=r(1.1.toString),l=r([].join),u=Array,h=i.Uint8Array,d=!h||!h.prototype.toHex||!function(){try{var p=new h([255,255,255,255,255,255,255,255]);return p.toHex()==="ffffffffffffffff"}catch{return!1}}();h&&n({target:"Uint8Array",proto:!0,forced:d},{toHex:function(){o(this),a(this.buffer);for(var m=u(this.length),v=0,g=this.length;v<g;v++){var y=c(this[v],16);m[v]=y.length===1?"0"+y:y}return l(m,"")}})},9452(s,e,t){var n=t(6518),i=t(9306),r=t(6557),o=t(4328),a=t(4995),c=t(6395),l=a.get,u=a.has,h=a.set,d=c||!function(){try{WeakMap.prototype.getOrInsertComputed&&new WeakMap().getOrInsertComputed(1,function(){throw 1})}catch(p){return p instanceof TypeError}}();n({target:"WeakMap",proto:!0,real:!0,forced:d},{getOrInsertComputed:function(m,v){if(c||r(this),o(m),i(v),u(this,m))return l(this,m);var g=v(m);return h(this,m,g),g}})},8454(s,e,t){var n=t(6518),i=t(4995),r=t(6395),o=i.get,a=i.has,c=i.set;n({target:"WeakMap",proto:!0,real:!0,forced:r},{getOrInsert:function(u,h){return a(this,u)?o(this,u):(c(this,u,h),h)}})},4979(s,e,t){var n=t(6518),i=t(4576),r=t(7751),o=t(6980),a=t(4913).f,c=t(9297),l=t(679),u=t(3167),h=t(2603),d=t(5002),p=t(8574),m=t(3724),v=t(6395),g="DOMException",y=r("Error"),b=r(g),_=function(){l(this,w);var W=arguments.length,V=h(W<1?void 0:arguments[0]),N=h(W<2?void 0:arguments[1],"Error"),O=new b(V,N),H=new y(V);return H.name=g,a(O,"stack",o(1,p(H.stack,1))),u(O,this,_),O},w=_.prototype=b.prototype,S="stack"in new y(g),C="stack"in new b(1,2),T=b&&m&&Object.getOwnPropertyDescriptor(i,g),k=!!T&&!(T.writable&&T.configurable),A=S&&!k&&!C;n({global:!0,constructor:!0,forced:v||A},{DOMException:A?_:b});var M=r(g),R=M.prototype;if(R.constructor!==M){v||a(R,"constructor",o(1,M));for(var P in d)if(c(d,P)){var L=d[P],z=L.s;c(M,z)||a(M,z,o(6,L.c))}}},4603(s,e,t){var n=t(6840),i=t(9504),r=t(655),o=t(2812),a=URLSearchParams,c=a.prototype,l=i(c.append),u=i(c.delete),h=i(c.forEach),d=i([].push),p=new a("a=1&a=2&b=3");p.delete("a",1),p.delete("b",void 0),p+""!="a=2"&&n(c,"delete",function(m){var v=arguments.length,g=v<2?void 0:arguments[1];if(v&&g===void 0)return u(this,m);var y=[];h(this,function(T,k){d(y,{key:k,value:T})}),o(v,1);for(var b=r(m),_=r(g),w=0,S=y.length,C;w<S;)C=y[w],u(this,C.key),w++;for(w=0;w<S;)C=y[w++],C.key===b&&C.value===_||l(this,C.key,C.value)},{enumerable:!0,unsafe:!0})},7566(s,e,t){var n=t(6840),i=t(9504),r=t(655),o=t(2812),a=URLSearchParams,c=a.prototype,l=i(c.getAll),u=i(c.has),h=new a("a=1");(h.has("a",2)||!h.has("a",void 0))&&n(c,"has",function(p){var m=arguments.length,v=m<2?void 0:arguments[1];if(m&&v===void 0)return u(this,p);var g=l(this,p);o(m,1);for(var y=r(v),b=0;b<g.length;)if(g[b++]===y)return!0;return!1},{enumerable:!0,unsafe:!0})},8721(s,e,t){var n=t(3724),i=t(9504),r=t(2106),o=URLSearchParams.prototype,a=i(o.forEach);n&&!("size"in o)&&r(o,"size",{get:function(){var l=0;return a(this,function(){l++}),l},configurable:!0,enumerable:!0})},5781(s,e,t){var n=t(6518),i=t(7751),r=t(2812),o=t(655),a=t(7416),c=i("URL");n({target:"URL",stat:!0,forced:!a},{parse:function(u){var h=r(arguments.length,1),d=o(u),p=h<2||arguments[1]===void 0?void 0:o(arguments[1]);try{return new c(d,p)}catch{return null}}})}},cR={};function St(s){var e=cR[s];if(e!==void 0)return e.exports;var t=cR[s]={exports:{}};return pee[s].call(t.exports,t,t.exports,St),t.exports}St.d=(s,e)=>{for(var t in e)St.o(e,t)&&!St.o(s,t)&&Object.defineProperty(s,t,{enumerable:!0,get:e[t]})};St.o=(s,e)=>Object.prototype.hasOwnProperty.call(s,e);St(4423);St(4114);St(6573);St(8100);St(7936);St(8111);St(2489);St(5367);St(2731);St(9577);St(6632);St(4226);St(9486);St(456);St(5781);const Zr=typeof process=="object"&&process+""=="[object process]"&&!process.versions.nw&&!(process.versions.electron&&process.type&&process.type!=="browser"),gc=[1/0,1/0,-1/0,-1/0],Wh=new Float32Array(gc),vT=[.001,0,0,.001,0,0],KC=1.35,Pr="http://www.w3.org/2000/svg",Jr={ANY:1,DISPLAY:2,PRINT:4,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,IS_EDITING:128,OPLIST:256},Zc={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},yp="pdfjs_internal_id_",oy="pdfjs_internal_editor_",Ct={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15,POPUP:16,SIGNATURE:101,COMMENT:102},xt={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,INK_COLOR_AND_OPACITY:24,HIGHLIGHT_COLOR:31,HIGHLIGHT_THICKNESS:32,HIGHLIGHT_FREE:33,HIGHLIGHT_SHOW_ALL:34,DRAW_STEP:41},gee={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},An={FILL:0,STROKE:1,FILL_STROKE:2,INVISIBLE:3,FILL_STROKE_MASK:3,ADD_TO_PATH_FLAG:4},CS={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},mn={TEXT:1,LINK:2,FREETEXT:3,LINE:4,SQUARE:5,CIRCLE:6,POLYGON:7,POLYLINE:8,HIGHLIGHT:9,UNDERLINE:10,SQUIGGLY:11,STRIKEOUT:12,STAMP:13,CARET:14,INK:15,POPUP:16,FILEATTACHMENT:17,SOUND:18,MOVIE:19,WIDGET:20,SCREEN:21,PRINTERMARK:22,TRAPNET:23,WATERMARK:24,THREED:25,REDACT:26},hp={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},uk={ERRORS:0,WARNINGS:1,INFOS:5},Il={dependency:1,setLineWidth:2,setLineCap:3,setLineJoin:4,setMiterLimit:5,setDash:6,setRenderingIntent:7,setFlatness:8,setGState:9,save:10,restore:11,transform:12,moveTo:13,lineTo:14,curveTo:15,curveTo2:16,curveTo3:17,closePath:18,rectangle:19,stroke:20,closeStroke:21,fill:22,eoFill:23,fillStroke:24,eoFillStroke:25,closeFillStroke:26,closeEOFillStroke:27,endPath:28,clip:29,eoClip:30,beginText:31,endText:32,setCharSpacing:33,setWordSpacing:34,setHScale:35,setLeading:36,setFont:37,setTextRenderingMode:38,setTextRise:39,moveText:40,setLeadingMoveText:41,setTextMatrix:42,nextLine:43,showText:44,showSpacedText:45,nextLineShowText:46,nextLineSetSpacingShowText:47,setCharWidth:48,setCharWidthAndBounds:49,setStrokeColorSpace:50,setFillColorSpace:51,setStrokeColor:52,setStrokeColorN:53,setFillColor:54,setFillColorN:55,setStrokeGray:56,setFillGray:57,setStrokeRGBColor:58,setFillRGBColor:59,setStrokeCMYKColor:60,setFillCMYKColor:61,shadingFill:62,beginInlineImage:63,beginImageData:64,endInlineImage:65,paintXObject:66,markPoint:67,markPointProps:68,beginMarkedContent:69,beginMarkedContentProps:70,endMarkedContent:71,beginCompat:72,endCompat:73,paintFormXObjectBegin:74,paintFormXObjectEnd:75,beginGroup:76,endGroup:77,beginAnnotation:80,endAnnotation:81,paintImageMaskXObject:83,paintImageMaskXObjectGroup:84,paintImageXObject:85,paintInlineImageXObject:86,paintInlineImageXObjectGroup:87,paintImageXObjectRepeat:88,paintImageMaskXObjectRepeat:89,paintSolidColorImageMask:90,constructPath:91,setStrokeTransparent:92,setFillTransparent:93,rawFillPath:94},Cm={moveTo:0,lineTo:1,curveTo:2,quadraticCurveTo:3,closePath:4},mee={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let hk=uk.WARNINGS;function vee(s){Number.isInteger(s)&&(hk=s)}function yee(){return hk}function dk(s){hk>=uk.INFOS&&console.info(`Info: ${s}`)}function kt(s){hk>=uk.WARNINGS&&console.warn(`Warning: ${s}`)}function es(s){throw new Error(s)}function Gs(s,e){s||es(e)}function bee(s){switch(s==null?void 0:s.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}function ID(s,e=null,t=null){if(!s)return null;if(t&&typeof s=="string"){if(t.addDefaultProtocol&&s.startsWith("www.")){const i=s.match(/\./g);(i==null?void 0:i.length)>=2&&(s=`http://${s}`)}if(t.tryConvertEncoding)try{s=wee(s)}catch{}}const n=e?URL.parse(s,e):URL.parse(s);return bee(n)?n:null}function RD(s,e,t=!1){const n=URL.parse(s);return n?(n.hash=e,n.href):t&&ID(s,"http://example.com")?s.split("#",1)[0]+`${e?`#${e}`:""}`:""}function yT(s){return s.substring(s.lastIndexOf("/")+1)}function Tt(s,e,t,n=!1){return Object.defineProperty(s,e,{value:t,enumerable:!n,configurable:!0,writable:!1}),t}const Nf=function(){function e(t,n){this.message=t,this.name=n}return e.prototype=new Error,e.constructor=e,e}();class uR extends Nf{constructor(e,t){super(e,"PasswordException"),this.code=t}}class QC extends Nf{constructor(e,t){super(e,"UnknownErrorException"),this.details=t}}class bT extends Nf{constructor(e){super(e,"InvalidPDFException")}}class l0 extends Nf{constructor(e,t,n){super(e,"ResponseException"),this.status=t,this.missing=n}}class _ee extends Nf{constructor(e){super(e,"FormatError")}}class ch extends Nf{constructor(e){super(e,"AbortException")}}function See(s){(typeof s!="object"||(s==null?void 0:s.length)===void 0)&&es("Invalid argument for bytesToString");const e=s.length,t=8192;if(e<t)return String.fromCharCode.apply(null,s);const n=[];for(let i=0;i<e;i+=t){const r=Math.min(i+t,e),o=s.subarray(i,r);n.push(String.fromCharCode.apply(null,o))}return n.join("")}function fk(s){typeof s!="string"&&es("Invalid argument for stringToBytes");const e=s.length,t=new Uint8Array(e);for(let n=0;n<e;++n)t[n]=s.charCodeAt(n)&255;return t}class Ts{static get isLittleEndian(){const e=new Uint8Array(4);e[0]=1;const t=new Uint32Array(e.buffer,0,1);return Tt(this,"isLittleEndian",t[0]===1)}static get isOffscreenCanvasSupported(){return Tt(this,"isOffscreenCanvasSupported",typeof OffscreenCanvas<"u")}static get isImageDecoderSupported(){return Tt(this,"isImageDecoderSupported",typeof ImageDecoder<"u")}static get isFloat16ArraySupported(){return Tt(this,"isFloat16ArraySupported",typeof Float16Array<"u")}static get isSanitizerSupported(){return Tt(this,"isSanitizerSupported",typeof Sanitizer<"u")}static get platform(){const{platform:e,userAgent:t}=navigator;return Tt(this,"platform",{isAndroid:t.includes("Android"),isLinux:e.includes("Linux"),isMac:e.includes("Mac"),isWindows:e.includes("Win"),isFirefox:t.includes("Firefox")})}static get isCanvasFilterSupported(){let e;return this.isOffscreenCanvasSupported?e=new OffscreenCanvas(1,1).getContext("2d"):typeof document<"u"&&(e=document.createElement("canvas").getContext("2d")),Tt(this,"isCanvasFilterSupported",(e==null?void 0:e.filter)!==void 0)}static get isAlphaColorInputSupported(){if(typeof document>"u")return Tt(this,"isAlphaColorInputSupported",!1);const e=document.createElement("input");return e.type="color",e.setAttribute("alpha",""),e.value="#ff000080",Tt(this,"isAlphaColorInputSupported",e.value!=="#ff0000")}}var wc,TS,_T;class Be{static get hexNums(){return Tt(this,"hexNums",Array.from(Array(256).keys(),e=>e.toString(16).padStart(2,"0")))}static makeHexColor(e,t,n){return`#${this.hexNums[e]}${this.hexNums[t]}${this.hexNums[n]}`}static transform(e,t){return[e[0]*t[0]+e[2]*t[1],e[1]*t[0]+e[3]*t[1],e[0]*t[2]+e[2]*t[3],e[1]*t[2]+e[3]*t[3],e[0]*t[4]+e[2]*t[5]+e[4],e[1]*t[4]+e[3]*t[5]+e[5]]}static multiplyByDOMMatrix(e,t){return[e[0]*t.a+e[2]*t.b,e[1]*t.a+e[3]*t.b,e[0]*t.c+e[2]*t.d,e[1]*t.c+e[3]*t.d,e[0]*t.e+e[2]*t.f+e[4],e[1]*t.e+e[3]*t.f+e[5]]}static applyTransform(e,t,n=0){const i=e[n],r=e[n+1];e[n]=i*t[0]+r*t[2]+t[4],e[n+1]=i*t[1]+r*t[3]+t[5]}static applyTransformToBezier(e,t,n=0){const i=t[0],r=t[1],o=t[2],a=t[3],c=t[4],l=t[5];for(let u=0;u<6;u+=2){const h=e[n+u],d=e[n+u+1];e[n+u]=h*i+d*o+c,e[n+u+1]=h*r+d*a+l}}static applyInverseTransform(e,t){const n=e[0],i=e[1],r=t[0]*t[3]-t[1]*t[2];e[0]=(n*t[3]-i*t[2]+t[2]*t[5]-t[4]*t[3])/r,e[1]=(-n*t[1]+i*t[0]+t[4]*t[1]-t[5]*t[0])/r}static axialAlignedBoundingBox(e,t,n){const i=t[0],r=t[1],o=t[2],a=t[3],c=t[4],l=t[5],u=e[0],h=e[1],d=e[2],p=e[3];let m=i*u+c,v=m,g=i*d+c,y=g,b=a*h+l,_=b,w=a*p+l,S=w;if(r!==0||o!==0){const C=r*u,T=r*d,k=o*h,A=o*p;m+=k,y+=k,g+=A,v+=A,b+=C,S+=C,w+=T,_+=T}n[0]=Math.min(n[0],m,g,v,y),n[1]=Math.min(n[1],b,w,_,S),n[2]=Math.max(n[2],m,g,v,y),n[3]=Math.max(n[3],b,w,_,S)}static inverseTransform(e){const t=e[0]*e[3]-e[1]*e[2];return[e[3]/t,-e[1]/t,-e[2]/t,e[0]/t,(e[2]*e[5]-e[4]*e[3])/t,(e[4]*e[1]-e[5]*e[0])/t]}static singularValueDecompose2dScale(e,t){const n=e[0],i=e[1],r=e[2],o=e[3],a=n**2+i**2,c=n*r+i*o,l=r**2+o**2,u=(a+l)/2,h=Math.sqrt(u**2-(a*l-c**2));t[0]=Math.sqrt(u+h||1),t[1]=Math.sqrt(u-h||1)}static normalizeRect(e){const t=e.slice(0);return e[0]>e[2]&&(t[0]=e[2],t[2]=e[0]),e[1]>e[3]&&(t[1]=e[3],t[3]=e[1]),t}static intersect(e,t){const n=Math.max(Math.min(e[0],e[2]),Math.min(t[0],t[2])),i=Math.min(Math.max(e[0],e[2]),Math.max(t[0],t[2]));if(n>i)return null;const r=Math.max(Math.min(e[1],e[3]),Math.min(t[1],t[3])),o=Math.min(Math.max(e[1],e[3]),Math.max(t[1],t[3]));return r>o?null:[n,r,i,o]}static pointBoundingBox(e,t,n){n[0]=Math.min(n[0],e),n[1]=Math.min(n[1],t),n[2]=Math.max(n[2],e),n[3]=Math.max(n[3],t)}static rectBoundingBox(e,t,n,i,r){r[0]=Math.min(r[0],e,n),r[1]=Math.min(r[1],t,i),r[2]=Math.max(r[2],e,n),r[3]=Math.max(r[3],t,i)}static bezierBoundingBox(e,t,n,i,r,o,a,c,l){l[0]=Math.min(l[0],e,a),l[1]=Math.min(l[1],t,c),l[2]=Math.max(l[2],e,a),l[3]=Math.max(l[3],t,c),B(this,wc,_T).call(this,e,n,r,a,t,i,o,c,3*(-e+3*(n-r)+a),6*(e-2*n+r),3*(n-e),l),B(this,wc,_T).call(this,e,n,r,a,t,i,o,c,3*(-t+3*(i-o)+c),6*(t-2*i+o),3*(i-t),l)}}wc=new WeakSet,TS=function(e,t,n,i,r,o,a,c,l,u){if(l<=0||l>=1)return;const h=1-l,d=l*l,p=d*l,m=h*(h*(h*e+3*l*t)+3*d*n)+p*i,v=h*(h*(h*r+3*l*o)+3*d*a)+p*c;u[0]=Math.min(u[0],m),u[1]=Math.min(u[1],v),u[2]=Math.max(u[2],m),u[3]=Math.max(u[3],v)},_T=function(e,t,n,i,r,o,a,c,l,u,h,d){if(Math.abs(l)<1e-12){Math.abs(u)>=1e-12&&B(this,wc,TS).call(this,e,t,n,i,r,o,a,c,-h/u,d);return}const p=u**2-4*h*l;if(p<0)return;const m=Math.sqrt(p),v=2*l;B(this,wc,TS).call(this,e,t,n,i,r,o,a,c,(-u+m)/v,d),B(this,wc,TS).call(this,e,t,n,i,r,o,a,c,(-u-m)/v,d)},D(Be,wc);function wee(s){return decodeURIComponent(escape(s))}let XC=null,hR=null;function kee(s){return XC||(XC=/([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu,hR=new Map([["ſt","ſt"]])),s.replaceAll(XC,(e,t,n)=>t?t.normalize("NFKC"):hR.get(n))}function LD(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();const s=new Uint8Array(32);return crypto.getRandomValues(s),See(s)}function Cee(s,e,t){if(!Array.isArray(t)||t.length<2)return!1;const[n,i,...r]=t;if(!s(n)&&!Number.isInteger(n)||!e(i))return!1;const o=r.length;let a=!0;switch(i.name){case"XYZ":if(o<2||o>3)return!1;break;case"Fit":case"FitB":return o===0;case"FitH":case"FitBH":case"FitV":case"FitBV":if(o>1)return!1;break;case"FitR":if(o!==4)return!1;a=!1;break;default:return!1}for(const c of r)if(!(typeof c=="number"||a&&c===null))return!1;return!0}const aM=()=>[],lM=()=>new Map,ST=()=>Object.create(null);typeof Blob.prototype.bytes!="function"&&(Blob.prototype.bytes=async function(){return new Uint8Array(await this.arrayBuffer())});typeof Response.prototype.bytes!="function"&&(Response.prototype.bytes=async function(){return new Uint8Array(await this.arrayBuffer())});St(1701);St(4603);St(7566);St(8721);function Ns(s,e,t){return Math.min(Math.max(s,e),t)}class s_{constructor({viewBox:e,userUnit:t,scale:n,rotation:i,offsetX:r=0,offsetY:o=0,dontFlip:a=!1}){this.viewBox=e,this.userUnit=t,this.scale=n,this.rotation=i,this.offsetX=r,this.offsetY=o,n*=t;const c=(e[2]+e[0])/2,l=(e[3]+e[1])/2;let u,h,d,p;switch(i%=360,i<0&&(i+=360),i){case 180:u=-1,h=0,d=0,p=1;break;case 90:u=0,h=1,d=1,p=0;break;case 270:u=0,h=-1,d=-1,p=0;break;case 0:u=1,h=0,d=0,p=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}a&&(d=-d,p=-p);let m,v,g,y;u===0?(m=Math.abs(l-e[1])*n+r,v=Math.abs(c-e[0])*n+o,g=(e[3]-e[1])*n,y=(e[2]-e[0])*n):(m=Math.abs(c-e[0])*n+r,v=Math.abs(l-e[1])*n+o,g=(e[2]-e[0])*n,y=(e[3]-e[1])*n),this.transform=[u*n,h*n,d*n,p*n,m-u*n*c-d*n*l,v-h*n*c-p*n*l],this.width=g,this.height=y}get rawDims(){const e=this.viewBox;return Tt(this,"rawDims",{pageWidth:e[2]-e[0],pageHeight:e[3]-e[1],pageX:e[0],pageY:e[1]})}clone({scale:e=this.scale,rotation:t=this.rotation,offsetX:n=this.offsetX,offsetY:i=this.offsetY,dontFlip:r=!1}={}){return new s_({viewBox:this.viewBox.slice(),userUnit:this.userUnit,scale:e,rotation:t,offsetX:n,offsetY:i,dontFlip:r})}convertToViewportPoint(e,t){const n=[e,t];return Be.applyTransform(n,this.transform),n}convertToViewportRectangle(e){const t=[e[0],e[1]];Be.applyTransform(t,this.transform);const n=[e[2],e[3]];return Be.applyTransform(n,this.transform),[t[0],t[1],n[0],n[1]]}convertToPdfPoint(e,t){const n=[e,t];return Be.applyInverseTransform(n,this.transform),n}}class ay{static textContent(e){const t=[],n={items:t,styles:Object.create(null)};function i(r){var c;if(!r)return;let o=null;const a=r.name;if(a==="#text")o=r.value;else if(ay.shouldBuildText(a))(c=r==null?void 0:r.attributes)!=null&&c.textContent?o=r.attributes.textContent:r.value&&(o=r.value);else return;if(o!==null&&t.push({str:o}),!!r.children)for(const l of r.children)i(l)}return i(e),n}static shouldBuildText(e){return!(e==="textarea"||e==="input"||e==="option"||e==="select")}}class PD{static setupStorage(e,t,n,i,r){const o=i.getValue(t,{value:null});switch(n.name){case"textarea":if(o.value!==null&&(e.textContent=o.value),r==="print")break;e.addEventListener("input",a=>{i.setValue(t,{value:a.target.value})});break;case"input":if(n.attributes.type==="radio"||n.attributes.type==="checkbox"){if(o.value===n.attributes.xfaOn?e.setAttribute("checked",!0):o.value===n.attributes.xfaOff&&e.removeAttribute("checked"),r==="print")break;e.addEventListener("change",a=>{i.setValue(t,{value:a.target.checked?a.target.getAttribute("xfaOn"):a.target.getAttribute("xfaOff")})})}else{if(o.value!==null&&e.setAttribute("value",o.value),r==="print")break;e.addEventListener("input",a=>{i.setValue(t,{value:a.target.value})})}break;case"select":if(o.value!==null){e.setAttribute("value",o.value);for(const a of n.children)a.attributes.value===o.value?a.attributes.selected=!0:Object.hasOwn(a.attributes,"selected")&&delete a.attributes.selected}e.addEventListener("input",a=>{const c=a.target.options,l=c.selectedIndex===-1?"":c[c.selectedIndex].value;i.setValue(t,{value:l})});break}}static setAttributes({html:e,element:t,storage:n=null,intent:i,linkService:r}){const{attributes:o}=t,a=e instanceof HTMLAnchorElement;o.type==="radio"&&(o.name=`${o.name}-${i}`);for(const[c,l]of Object.entries(o))if(l!=null)switch(c){case"class":l.length&&e.setAttribute(c,l.join(" "));break;case"dataId":break;case"id":e.setAttribute("data-element-id",l);break;case"style":Object.assign(e.style,l);break;case"textContent":e.textContent=l;break;default:(!a||c!=="href"&&c!=="newWindow")&&e.setAttribute(c,l)}a&&r.addLinkAttributes(e,o.href,o.newWindow),n&&o.dataId&&this.setupStorage(e,o.dataId,t,n)}static render(e){var h,d;const t=e.annotationStorage,n=e.linkService,i=e.xfaHtml,r=e.intent||"display",o=document.createElement(i.name);i.attributes&&this.setAttributes({html:o,element:i,intent:r,linkService:n});const a=r!=="richText",c=e.div;if(c.append(o),e.viewport){const p=`matrix(${e.viewport.transform.join(",")})`;c.style.transform=p}a&&c.setAttribute("class","xfaLayer xfaFont");const l=[];if(i.children.length===0){if(i.value){const p=document.createTextNode(i.value);o.append(p),a&&ay.shouldBuildText(i.name)&&l.push(p)}return{textDivs:l}}const u=[[i,-1,o]];for(;u.length>0;){const[p,m,v]=u.at(-1);if(m+1===p.children.length){u.pop();continue}const g=p.children[++u.at(-1)[1]];if(g===null)continue;const{name:y}=g;if(y==="#text"){const _=document.createTextNode(g.value);l.push(_),v.append(_);continue}const b=(h=g==null?void 0:g.attributes)!=null&&h.xmlns?document.createElementNS(g.attributes.xmlns,y):document.createElement(y);if(v.append(b),g.attributes&&this.setAttributes({html:b,element:g,storage:t,intent:r,linkService:n}),((d=g.children)==null?void 0:d.length)>0)u.push([g,-1,b]);else if(g.value){const _=document.createTextNode(g.value);a&&ay.shouldBuildText(y)&&l.push(_),b.append(_)}}for(const p of c.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))p.setAttribute("readOnly",!0);return{textDivs:l}}static update(e){const t=`matrix(${e.viewport.transform.join(",")})`;e.div.style.transform=t,e.div.hidden=!1}static getPageViewport(e,{scale:t=1,rotation:n=0}){const{width:i,height:r}=e.attributes.style;return new s_({viewBox:[0,0,parseInt(i,10),parseInt(r,10)],userUnit:1,scale:t,rotation:n})}}const Rh=class Rh{};_e(Rh,"CSS",96),_e(Rh,"PDF",72),_e(Rh,"PDF_TO_CSS_UNITS",Rh.CSS/Rh.PDF);let uh=Rh;async function cM(s,e="text"){if($v(s,document.baseURI)){const t=await fetch(s);if(!t.ok)throw new Error(t.statusText);switch(e){case"blob":return t.blob();case"bytes":return t.bytes();case"json":return t.json()}return t.text()}return new Promise((t,n)=>{const i=new XMLHttpRequest;i.open("GET",s,!0),i.responseType=e==="bytes"?"arraybuffer":e,i.onreadystatechange=()=>{if(i.readyState===XMLHttpRequest.DONE){if(i.status===200||i.status===0){switch(e){case"bytes":t(new Uint8Array(i.response));return;case"blob":case"json":t(i.response);return}t(i.responseText);return}n(new Error(i.statusText))}},i.send(null)})}class uM extends Nf{constructor(e,t=0){super(e,"RenderingCancelledException"),this.extraDelay=t}}function pk(s){const e=s.length;let t=0;for(;t<e&&s[t].trim()==="";)t++;return s.substring(t,t+5).toLowerCase()==="data:"}function hM(s){return typeof s=="string"&&/\.pdf$/i.test(s)}function Tee(s){return[s]=s.split(/[#?]/,1),yT(s)}function Aee(s,e="document.pdf"){if(typeof s!="string")return e;if(pk(s))return kt('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.'),e;const n=(a=>{try{return new URL(a)}catch{}try{return new URL(decodeURIComponent(a))}catch{}try{return new URL(a,"https://foo.bar")}catch{}try{return new URL(decodeURIComponent(a),"https://foo.bar")}catch{}return null})(s);if(!n)return e;const i=a=>{try{let c=decodeURIComponent(a);return c.includes("/")&&(c=yT(c),c.length===4&&r.test(c))?a:c}catch{return a}},r=/\.pdf$/i,o=yT(n.pathname);if(r.test(o))return i(o);if(n.searchParams.size>0){const a=l=>[...l].findLast(u=>r.test(u)),c=a(n.searchParams.values())??a(n.searchParams.keys());if(c)return i(c)}if(n.hash){const c=/[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i.exec(n.hash);if(c)return i(c[0])}return e}var eu;class dR{constructor(){D(this,eu,new Map);_e(this,"times",[])}time(e){f(this,eu).has(e)&&kt(`Timer is already running for ${e}`),f(this,eu).set(e,Date.now())}timeEnd(e){f(this,eu).has(e)||kt(`Timer has not been started for ${e}`),this.times.push({name:e,start:f(this,eu).get(e),end:Date.now()}),f(this,eu).delete(e)}toString(){const e=Math.max(...this.times.map(t=>t.name.length));return this.times.map(t=>`${t.name.padEnd(e)} ${t.end-t.start}ms
`).join("")}}eu=new WeakMap;function $v(s,e){const t=e?URL.parse(s,e):URL.parse(s);return/https?:/.test((t==null?void 0:t.protocol)??"")}function Ho(s){s.preventDefault()}function js(s){s.preventDefault(),s.stopPropagation()}var fy;class c0{static toDateObject(e){if(e instanceof Date)return e;if(!e||typeof e!="string")return null;f(this,fy)||x(this,fy,new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+\\-])?(\\d{2})?'?(\\d{2})?'?"));const t=f(this,fy).exec(e);if(!t)return null;const n=parseInt(t[1],10);let i=parseInt(t[2],10);i=i>=1&&i<=12?i-1:0;let r=parseInt(t[3],10);r=r>=1&&r<=31?r:1;let o=parseInt(t[4],10);o=o>=0&&o<=23?o:0;let a=parseInt(t[5],10);a=a>=0&&a<=59?a:0;let c=parseInt(t[6],10);c=c>=0&&c<=59?c:0;const l=t[7]||"Z";let u=parseInt(t[8],10);u=u>=0&&u<=23?u:0;let h=parseInt(t[9],10)||0;return h=h>=0&&h<=59?h:0,l==="-"?(o+=u,a+=h):l==="+"&&(o-=u,a-=h),new Date(Date.UTC(n,i,r,o,a,c))}}fy=new WeakMap,D(c0,fy);function n_(s){if(s.startsWith("#")){const t=s.slice(1);return[parseInt(t.slice(0,2),16),parseInt(t.slice(2,4),16),parseInt(t.slice(4,6),16),t.length>=8?parseInt(t.slice(6,8),16)/255:1]}if(s.startsWith("rgb(")){const[t,n,i]=s.slice(4,-1).split(",").map(r=>parseInt(r,10));return[t,n,i,1]}if(s.startsWith("rgba(")){const t=s.slice(5,-1).split(",");return[parseInt(t[0],10),parseInt(t[1],10),parseInt(t[2],10),parseFloat(t[3])]}const e=s.match(/^color\(srgb\s+([\d.]+)\s+([\d.]+)\s+([\d.]+)(?:\s*\/\s*([\d.]+|none))?\)$/);return e?[Math.round(parseFloat(e[1])*255),Math.round(parseFloat(e[2])*255),Math.round(parseFloat(e[3])*255),e[4]!==void 0&&e[4]!=="none"?parseFloat(e[4]):1]:null}function i_(s){const e=n_(s);return e?e.slice(0,3):(kt(`Not a valid color format: "${s}"`),[0,0,0])}function Eee(s){const e=document.createElement("span");e.style.visibility="hidden",e.style.colorScheme="only light",document.body.append(e);for(const t of s.keys()){e.style.color=t;const n=window.getComputedStyle(e).color;s.set(t,i_(n))}e.remove()}function Cs(s){const{a:e,b:t,c:n,d:i,e:r,f:o}=s.getTransform();return[e,t,n,i,r,o]}function ka(s){const{a:e,b:t,c:n,d:i,e:r,f:o}=s.getTransform().invertSelf();return[e,t,n,i,r,o]}function Rf(s,e,t=!1,n=!0){if(e instanceof s_){const{pageWidth:i,pageHeight:r}=e.rawDims,{style:o}=s,a=`round(down, var(--total-scale-factor) * ${i}px, var(--scale-round-x))`,c=`round(down, var(--total-scale-factor) * ${r}px, var(--scale-round-y))`;!t||e.rotation%180===0?(o.width=a,o.height=c):(o.width=c,o.height=a)}n&&s.setAttribute("data-main-rotation",e.rotation)}class ll{constructor(){const{pixelRatio:e}=ll;this.sx=e,this.sy=e}get scaled(){return this.sx!==1||this.sy!==1}get symmetric(){return this.sx===this.sy}limitCanvas(e,t,n,i,r=-1){let o=1/0,a=1/0,c=1/0;n=ll.capPixels(n,r),n>0&&(o=Math.sqrt(n/(e*t))),i!==-1&&(a=i/e,c=i/t);const l=Math.min(o,a,c);return this.sx>l||this.sy>l?(this.sx=l,this.sy=l,!0):!1}static get pixelRatio(){return globalThis.devicePixelRatio||1}static capPixels(e,t){if(t>=0){const n=Math.ceil(window.screen.availWidth*window.screen.availHeight*this.pixelRatio**2*(1+t/100));return e>0?Math.min(e,n):n}return e}}const wT=["image/apng","image/avif","image/bmp","image/gif","image/jpeg","image/png","image/svg+xml","image/webp","image/x-icon"];class Mee{static get isDarkMode(){var e;return Tt(this,"isDarkMode",!!((e=window==null?void 0:window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches))}}class xee{static get commentForegroundColor(){const e=document.createElement("span");e.classList.add("comment","sidebar");const{style:t}=e;t.width=t.height="0",t.display="none",t.color="var(--comment-fg-color)",document.body.append(e);const{color:n}=window.getComputedStyle(e);return e.remove(),Tt(this,"commentForegroundColor",i_(n))}}function Iee(s,e){e=Ns(e??1,0,1);const t=255*(1-e);return s.map(n=>Math.round(n*e+t))}function fR(s,e){const t=s[0]/255,n=s[1]/255,i=s[2]/255,r=Math.max(t,n,i),o=Math.min(t,n,i),a=(r+o)/2;if(r===o)e[0]=e[1]=0;else{const c=r-o;switch(e[1]=a<.5?c/(r+o):c/(2-r-o),r){case t:e[0]=((n-i)/c+(n<i?6:0))*60;break;case n:e[0]=((i-t)/c+2)*60;break;case i:e[0]=((t-n)/c+4)*60;break}}e[2]=a}function kT(s,e){const t=s[0],n=s[1],i=s[2],r=(1-Math.abs(2*i-1))*n,o=r*(1-Math.abs(t/60%2-1)),a=i-r/2;switch(Math.floor(t/60)){case 0:e[0]=r+a,e[1]=o+a,e[2]=a;break;case 1:e[0]=o+a,e[1]=r+a,e[2]=a;break;case 2:e[0]=a,e[1]=r+a,e[2]=o+a;break;case 3:e[0]=a,e[1]=o+a,e[2]=r+a;break;case 4:e[0]=o+a,e[1]=a,e[2]=r+a;break;case 5:case 6:e[0]=r+a,e[1]=a,e[2]=o+a;break}}function pR(s){return s<=.03928?s/12.92:((s+.055)/1.055)**2.4}function gR(s,e,t){kT(s,t),t.map(pR);const n=.2126*t[0]+.7152*t[1]+.0722*t[2];kT(e,t),t.map(pR);const i=.2126*t[0]+.7152*t[1]+.0722*t[2];return n>i?(n+.05)/(i+.05):(i+.05)/(n+.05)}const mR=new Map;function Ree(s,e){const t=s[0]+s[1]*256+s[2]*65536+e[0]*16777216+e[1]*4294967296+e[2]*1099511627776;let n=mR.get(t);if(n)return n;const i=new Float32Array(9),r=i.subarray(0,3),o=i.subarray(3,6);fR(s,o);const a=i.subarray(6,9);fR(e,a);const c=a[2]<.5,l=c?12:4.5;if(o[2]=c?Math.sqrt(o[2]):1-Math.sqrt(1-o[2]),gR(o,a,r)<l){let u,h;c?(u=o[2],h=1):(u=0,h=o[2]);const d=.005;for(;h-u>d;){const p=o[2]=(u+h)/2;c===gR(o,a,r)<l?u=p:h=p}o[2]=c?h:u}return kT(o,r),n=Be.makeHexColor(Math.round(r[0]*255),Math.round(r[1]*255),Math.round(r[2]*255)),mR.set(t,n),n}function OD({html:s,dir:e,className:t},n){const i=document.createDocumentFragment();if(typeof s=="string"){const r=document.createElement("p");r.dir=e||"auto";const o=s.split(/\r\n?|\n/);for(let a=0,c=o.length;a<c;++a){const l=o[a];r.append(document.createTextNode(l)),a<c-1&&r.append(document.createElement("br"))}i.append(r)}else PD.render({xfaHtml:s,div:i,intent:"richText"});i.firstElementChild.classList.add("richText",t),n.append(i)}function DD(s){const e=new Path2D;if(!s)return e;for(let t=0,n=s.length;t<n;)switch(s[t++]){case Cm.moveTo:e.moveTo(s[t++],s[t++]);break;case Cm.lineTo:e.lineTo(s[t++],s[t++]);break;case Cm.curveTo:e.bezierCurveTo(s[t++],s[t++],s[t++],s[t++],s[t++],s[t++]);break;case Cm.quadraticCurveTo:e.quadraticCurveTo(s[t++],s[t++],s[t++],s[t++]);break;case Cm.closePath:e.closePath();break;default:kt(`Unrecognized drawing path operator: ${s[t-1]}`);break}return e}St(4972);St(4628);St(7642);St(8004);St(3853);St(5876);St(2475);St(5024);St(1698);St(8454);St(9452);St(4979);St(3579);St(3110);St(9314);St(1148);St(9112);var tu,su,po,go,py,nu,Ap,Ep,gy,_0,ND,gi,BD,FD,dp,Xm;const Ml=class Ml{constructor(e){D(this,gi);D(this,tu,null);D(this,su,null);D(this,po);D(this,go,null);D(this,py,null);D(this,nu,null);D(this,Ap,null);D(this,Ep,null);x(this,po,e),f(Ml,gy)||x(Ml,gy,Object.freeze({freetext:"pdfjs-editor-remove-freetext-button",highlight:"pdfjs-editor-remove-highlight-button",ink:"pdfjs-editor-remove-ink-button",stamp:"pdfjs-editor-remove-stamp-button",signature:"pdfjs-editor-remove-signature-button"}))}render(){const e=x(this,tu,document.createElement("div"));e.classList.add("editToolbar","hidden"),e.setAttribute("role","toolbar");const t=f(this,po)._uiManager._signal;t instanceof AbortSignal&&!t.aborted&&(e.addEventListener("contextmenu",Ho,{signal:t}),e.addEventListener("pointerdown",B(Ml,_0,ND),{signal:t}));const n=x(this,go,document.createElement("div"));n.className="buttons",e.append(n);const i=f(this,po).toolbarPosition;if(i){const{style:r}=e,o=f(this,po)._uiManager.direction==="ltr"?1-i[0]:i[0];r.insetInlineEnd=`${100*o}%`,r.top=`calc(${100*i[1]}% + var(--editor-toolbar-vert-offset))`}return e}get div(){return f(this,tu)}hide(){var e;f(this,tu).classList.add("hidden"),(e=f(this,su))==null||e.hideDropdown()}show(){var e,t;f(this,tu).classList.remove("hidden"),(e=f(this,py))==null||e.shown(),(t=f(this,nu))==null||t.shown()}addDeleteButton(){const{editorType:e,_uiManager:t}=f(this,po),n=document.createElement("button");n.classList.add("basic","deleteButton"),n.tabIndex=0,n.setAttribute("data-l10n-id",f(Ml,gy)[e]),B(this,gi,dp).call(this,n)&&n.addEventListener("click",i=>{t.delete()},{signal:t._signal}),f(this,go).append(n)}async addAltText(e){const t=await e.render();B(this,gi,dp).call(this,t),f(this,go).append(t,f(this,gi,Xm)),x(this,py,e)}addComment(e,t=null){if(f(this,nu))return;const n=e.renderForToolbar();if(!n)return;B(this,gi,dp).call(this,n);const i=x(this,Ap,f(this,gi,Xm));t?(f(this,go).insertBefore(n,t),f(this,go).insertBefore(i,t)):f(this,go).append(n,i),x(this,nu,e),e.toolbar=this}addColorPicker(e){if(f(this,su))return;x(this,su,e);const t=e.renderButton();B(this,gi,dp).call(this,t),f(this,go).append(t,f(this,gi,Xm))}async addEditSignatureButton(e){const t=x(this,Ep,await e.renderEditButton(f(this,po)));B(this,gi,dp).call(this,t),f(this,go).append(t,f(this,gi,Xm))}removeButton(e){var t,n;switch(e){case"comment":(t=f(this,nu))==null||t.removeToolbarCommentButton(),x(this,nu,null),(n=f(this,Ap))==null||n.remove(),x(this,Ap,null);break}}async addButton(e,t){switch(e){case"colorPicker":t&&this.addColorPicker(t);break;case"altText":t&&await this.addAltText(t);break;case"editSignature":t&&await this.addEditSignatureButton(t);break;case"delete":this.addDeleteButton();break;case"comment":t&&this.addComment(t);break}}async addButtonBefore(e,t,n){if(!t&&e==="comment")return;const i=f(this,go).querySelector(n);i&&e==="comment"&&this.addComment(t,i)}updateEditSignatureButton(e){f(this,Ep)&&(f(this,Ep).title=e)}remove(){var e;f(this,tu).remove(),(e=f(this,su))==null||e.destroy(),x(this,su,null)}};tu=new WeakMap,su=new WeakMap,po=new WeakMap,go=new WeakMap,py=new WeakMap,nu=new WeakMap,Ap=new WeakMap,Ep=new WeakMap,gy=new WeakMap,_0=new WeakSet,ND=function(e){e.stopPropagation()},gi=new WeakSet,BD=function(e){f(this,po)._focusEventsAllowed=!1,js(e)},FD=function(e){f(this,po)._focusEventsAllowed=!0,js(e)},dp=function(e){const t=f(this,po)._uiManager._signal;return!(t instanceof AbortSignal)||t.aborted?!1:(e.addEventListener("focusin",B(this,gi,BD).bind(this),{capture:!0,signal:t}),e.addEventListener("focusout",B(this,gi,FD).bind(this),{capture:!0,signal:t}),e.addEventListener("contextmenu",Ho,{signal:t}),!0)},Xm=function(){const e=document.createElement("div");return e.className="divider",e},D(Ml,_0),D(Ml,gy,null);let CT=Ml;var my,Vh,Ll,Ec,$D,HD,TT;class Lee{constructor(e){D(this,Ec);D(this,my,null);D(this,Vh,null);D(this,Ll);x(this,Ll,e)}show(e,t,n){const[i,r]=B(this,Ec,HD).call(this,t,n),{style:o}=f(this,Vh)||x(this,Vh,B(this,Ec,$D).call(this));e.append(f(this,Vh)),o.insetInlineEnd=`${100*i}%`,o.top=`calc(${100*r}% + var(--editor-toolbar-vert-offset))`}hide(){f(this,Vh).remove()}}my=new WeakMap,Vh=new WeakMap,Ll=new WeakMap,Ec=new WeakSet,$D=function(){const e=x(this,Vh,document.createElement("div"));e.className="editToolbar",e.setAttribute("role","toolbar");const t=f(this,Ll)._signal;t instanceof AbortSignal&&!t.aborted&&e.addEventListener("contextmenu",Ho,{signal:t});const n=x(this,my,document.createElement("div"));return n.className="buttons",e.append(n),f(this,Ll).hasCommentManager()&&B(this,Ec,TT).call(this,"commentButton","pdfjs-comment-floating-button","pdfjs-comment-floating-button-label",()=>{f(this,Ll).commentSelection("floating_button")}),B(this,Ec,TT).call(this,"highlightButton","pdfjs-highlight-floating-button1","pdfjs-highlight-floating-button-label",()=>{f(this,Ll).highlightSelection("floating_button")}),e},HD=function(e,t){let n=0,i=0;for(const r of e){const o=r.y+r.height;if(o<n)continue;const a=r.x+(t?r.width:0);if(o>n){i=a,n=o;continue}t?a>i&&(i=a):a<i&&(i=a)}return[t?1-i:i,n]},TT=function(e,t,n,i){const r=document.createElement("button");r.classList.add("basic",e),r.tabIndex=0,r.setAttribute("data-l10n-id",t);const o=document.createElement("span");r.append(o),o.className="visuallyHidden",o.setAttribute("data-l10n-id",n);const a=f(this,Ll)._signal;a instanceof AbortSignal&&!a.aborted&&(r.addEventListener("contextmenu",Ho,{signal:a}),r.addEventListener("click",i,{signal:a})),f(this,my).append(r)};const Pee="9556e50a-f4f8-4f57-9831-f9ddff0176eb",Oee=Object.freeze({internal:Pee});function UD(s,e,t){for(const n of t)e.addEventListener(n,s[n].bind(s))}var Gh,qh,Mp,Kh;const ds=class ds{static initializeAndAddPointerId(e){(f(ds,qh)||x(ds,qh,new Set)).add(e)}static setPointer(e,t){f(ds,Gh)||x(ds,Gh,t),f(ds,Kh)??x(ds,Kh,e)}static setTimeStamp(e){x(ds,Mp,e)}static isSamePointerId(e){return f(ds,Gh)===e}static isSamePointerIdOrRemove(e){var t;return f(ds,Gh)===e?!0:((t=f(ds,qh))==null||t.delete(e),!1)}static isSamePointerType(e){return f(ds,Kh)===e}static isInitializedAndDifferentPointerType(e){return f(ds,Kh)!==null&&!ds.isSamePointerType(e)}static isSameTimeStamp(e){return f(ds,Mp)===e}static isUsingMultiplePointers(){var e;return((e=f(ds,qh))==null?void 0:e.size)>=1}static clearPointerType(){x(ds,Kh,null)}static clearPointerIds(){x(ds,Gh,NaN),x(ds,qh,null)}static clearTimeStamp(){x(ds,Mp,NaN)}};Gh=new WeakMap,qh=new WeakMap,Mp=new WeakMap,Kh=new WeakMap,D(ds,Gh,NaN),D(ds,qh,null),D(ds,Mp,NaN),D(ds,Kh,null);let Si=ds;var S0;class Dee{constructor(){D(this,S0,0)}get id(){return`${oy}${xs(this,S0)._++}`}}S0=new WeakMap;var xp,vy,wi,Ip,AS;const SM=class SM{constructor(){D(this,Ip);D(this,xp,LD());D(this,vy,0);D(this,wi,null)}static get _isSVGFittingCanvas(){const e=`data:image/svg+xml;charset=UTF-8,<svg viewBox="0 0 1 1" width="1" height="1" xmlns="${Pr}"><rect width="1" height="1" style="fill:red;"/></svg>`,n=new OffscreenCanvas(1,3).getContext("2d",{willReadFrequently:!0}),i=new Image;i.src=e;const r=i.decode().then(()=>(n.drawImage(i,0,0,1,1,0,0,1,3),new Uint32Array(n.getImageData(0,0,1,1).data.buffer)[0]===0));return Tt(this,"_isSVGFittingCanvas",r)}async getFromFile(e){const{lastModified:t,name:n,size:i,type:r}=e;return B(this,Ip,AS).call(this,`${t}_${n}_${i}_${r}`,e)}async getFromUrl(e){return B(this,Ip,AS).call(this,e,e)}async getFromBlob(e,t){const n=await t;return B(this,Ip,AS).call(this,e,n)}async getFromId(e){f(this,wi)||x(this,wi,new Map);const t=f(this,wi).get(e);if(!t)return null;if(t.bitmap)return t.refCounter+=1,t;if(t.file)return this.getFromFile(t.file);if(t.blobPromise){const{blobPromise:n}=t;return delete t.blobPromise,this.getFromBlob(t.id,n)}return this.getFromUrl(t.url)}getFromCanvas(e,t){f(this,wi)||x(this,wi,new Map);let n=f(this,wi).get(e);if(n!=null&&n.bitmap)return n.refCounter+=1,n;const i=new OffscreenCanvas(t.width,t.height);return i.getContext("2d").drawImage(t,0,0),n={bitmap:i.transferToImageBitmap(),id:`image_${f(this,xp)}_${xs(this,vy)._++}`,refCounter:1,isSvg:!1},f(this,wi).set(e,n),f(this,wi).set(n.id,n),n}getSvgUrl(e){const t=f(this,wi).get(e);return t!=null&&t.isSvg?t.svgUrl:null}deleteId(e){var i;f(this,wi)||x(this,wi,new Map);const t=f(this,wi).get(e);if(!t||(t.refCounter-=1,t.refCounter!==0))return;const{bitmap:n}=t;if(!t.url&&!t.file){const r=new OffscreenCanvas(n.width,n.height);r.getContext("bitmaprenderer").transferFromImageBitmap(n),t.blobPromise=r.convertToBlob()}(i=n.close)==null||i.call(n),t.bitmap=null}isValidId(e){return e.startsWith(`image_${f(this,xp)}_`)}};xp=new WeakMap,vy=new WeakMap,wi=new WeakMap,Ip=new WeakSet,AS=async function(e,t){f(this,wi)||x(this,wi,new Map);let n=f(this,wi).get(e);if(n===null)return null;if(n!=null&&n.bitmap)return n.refCounter+=1,n;try{n||(n={bitmap:null,id:`image_${f(this,xp)}_${xs(this,vy)._++}`,refCounter:0,isSvg:!1});let i;if(typeof t=="string"?(n.url=t,i=await cM(t,"blob")):t instanceof File?i=n.file=t:t instanceof Blob&&(i=t),i.type==="image/svg+xml"){const r=SM._isSVGFittingCanvas,o=new FileReader,a=new Image,c=new Promise((l,u)=>{a.onload=()=>{n.bitmap=a,n.isSvg=!0,l()},o.onload=async()=>{const h=n.svgUrl=o.result;a.src=await r?`${h}#svgView(preserveAspectRatio(none))`:h},a.onerror=o.onerror=u});o.readAsDataURL(i),await c}else n.bitmap=await createImageBitmap(i);n.refCounter=1}catch(i){kt(i),n=null}return f(this,wi).set(e,n),n&&f(this,wi).set(n.id,n),n};let AT=SM;var an,iu,yy,Ws;class Nee{constructor(e=128){D(this,an,[]);D(this,iu,!1);D(this,yy);D(this,Ws,-1);x(this,yy,e)}add({cmd:e,undo:t,post:n,mustExec:i,type:r=NaN,overwriteIfSameType:o=!1,keepUndo:a=!1}){if(i&&e(),f(this,iu))return;const c={cmd:e,undo:t,post:n,type:r};if(f(this,Ws)===-1){f(this,an).length>0&&(f(this,an).length=0),x(this,Ws,0),f(this,an).push(c);return}if(o&&f(this,an)[f(this,Ws)].type===r){a&&(c.undo=f(this,an)[f(this,Ws)].undo),f(this,an)[f(this,Ws)]=c;return}const l=f(this,Ws)+1;l===f(this,yy)?f(this,an).splice(0,1):(x(this,Ws,l),l<f(this,an).length&&f(this,an).splice(l)),f(this,an).push(c)}undo(){if(f(this,Ws)===-1)return;x(this,iu,!0);const{undo:e,post:t}=f(this,an)[f(this,Ws)];e(),t==null||t(),x(this,iu,!1),x(this,Ws,f(this,Ws)-1)}redo(){if(f(this,Ws)<f(this,an).length-1){x(this,Ws,f(this,Ws)+1),x(this,iu,!0);const{cmd:e,post:t}=f(this,an)[f(this,Ws)];e(),t==null||t(),x(this,iu,!1)}}hasSomethingToUndo(){return f(this,Ws)!==-1}hasSomethingToRedo(){return f(this,Ws)<f(this,an).length-1}cleanType(e){if(f(this,Ws)!==-1){for(let t=f(this,Ws);t>=0;t--)if(f(this,an)[t].type!==e){f(this,an).splice(t+1,f(this,Ws)-t),x(this,Ws,t);return}f(this,an).length=0,x(this,Ws,-1)}}destroy(){x(this,an,null)}}an=new WeakMap,iu=new WeakMap,yy=new WeakMap,Ws=new WeakMap;var w0,WD;class r_{constructor(e){D(this,w0);this.buffer=[],this.callbacks=new Map,this.allKeys=new Set;const{isMac:t}=Ts.platform;for(const[n,i,r={}]of e)for(const o of n){const a=o.startsWith("mac+");t&&a?(this.callbacks.set(o.slice(4),{callback:i,options:r}),this.allKeys.add(o.split("+").at(-1))):!t&&!a&&(this.callbacks.set(o,{callback:i,options:r}),this.allKeys.add(o.split("+").at(-1)))}}exec(e,t){if(!this.allKeys.has(t.key))return;const n=this.callbacks.get(B(this,w0,WD).call(this,t));if(!n)return;const{callback:i,options:{bubbles:r=!1,args:o=[],checker:a=null}}=n;a&&!a(e,t)||(i.bind(e,...o,t)(),r||js(t))}}w0=new WeakSet,WD=function(e){e.altKey&&this.buffer.push("alt"),e.ctrlKey&&this.buffer.push("ctrl"),e.metaKey&&this.buffer.push("meta"),e.shiftKey&&this.buffer.push("shift"),this.buffer.push(e.key);const t=this.buffer.join("+");return this.buffer.length=0,t};const k0=class k0{get _colors(){const e=new Map([["CanvasText",null],["Canvas",null]]);return Eee(e),Tt(this,"_colors",e)}convert(e){const t=i_(e);if(!window.matchMedia("(forced-colors: active)").matches)return t;for(const[n,i]of this._colors)if(i.every((r,o)=>r===t[o]))return k0._colorsMapping.get(n);return t}getHexCode(e){const t=this._colors.get(e);return t?Be.makeHexColor(...t):e}};_e(k0,"_colorsMapping",new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]));let ET=k0;var Rp,Or,Lp,en,zs,Pp,Op,Wi,Dp,mo,$n,ru,ou,au,lu,La,vo,Qh,by,_y,Np,Sy,Pa,cu,Bp,uu,Oa,C0,Pl,Fp,wy,hu,Xh,$p,du,ky,vn,ls,Ol,fu,pu,Cy,Hp,Ty,gu,Da,Dl,Ay,Ey,yo,je,ES,MT,zD,jD,VD,Ym,GD,qD,KD,xT,QD,XD,YD,JD,$i,Tl,ZD,eN,IT,tN,Jm,RT;const bp=class bp{constructor(e,t,n,i,r,o,a,c,l,u,h,d,p,m,v,g){D(this,je);D(this,Rp,new AbortController);D(this,Or,null);D(this,Lp,null);D(this,en,new Map);D(this,zs,new Map);D(this,Pp,null);D(this,Op,null);D(this,Wi,null);D(this,Dp,null);D(this,mo,new Nee);D(this,$n,null);D(this,ru,null);D(this,ou,null);D(this,au,0);D(this,lu,new Set);D(this,La,null);D(this,vo,null);D(this,Qh,new Set);_e(this,"_editorUndoBar",null);D(this,by,!1);D(this,_y,!1);D(this,Np,!1);D(this,Sy,null);D(this,Pa,null);D(this,cu,null);D(this,Bp,null);D(this,uu,!1);D(this,Oa,null);D(this,C0,new Dee);D(this,Pl,!1);D(this,Fp,!1);D(this,wy,!1);D(this,hu,null);D(this,Xh,null);D(this,$p,null);D(this,du,null);D(this,ky,null);D(this,vn,Ct.NONE);D(this,ls,new Set);D(this,Ol,null);D(this,fu,null);D(this,pu,null);D(this,Cy,null);D(this,Hp,null);D(this,Ty,{isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1});D(this,gu,[0,0]);D(this,Da,null);D(this,Dl,null);D(this,Ay,null);D(this,Ey,null);D(this,yo,null);const y=this._signal=f(this,Rp).signal;x(this,Dl,e),x(this,Ay,t),x(this,Ey,n),x(this,Op,i),x(this,$n,r),x(this,fu,o),x(this,Hp,c),this._eventBus=a;const b={signal:y,...Oee};a.on("editingaction",this.onEditingAction.bind(this),b),a.on("pagechanging",this.onPageChanging.bind(this),b),a.on("scalechanging",this.onScaleChanging.bind(this),b),a.on("rotationchanging",this.onRotationChanging.bind(this),b),a.on("setpreference",this.onSetPreference.bind(this),b),a.on("switchannotationeditorparams",_=>this.updateParams(_.type,_.value),b),window.addEventListener("pointerdown",()=>{x(this,Fp,!0)},{capture:!0,signal:y}),window.addEventListener("pointerup",()=>{x(this,Fp,!1)},{capture:!0,signal:y}),window.addEventListener("beforeunload",B(this,je,zD).bind(this),{capture:!0,signal:y}),B(this,je,GD).call(this),B(this,je,JD).call(this),B(this,je,xT).call(this),x(this,Wi,c.annotationStorage),x(this,Sy,c.filterFactory),x(this,pu,l),x(this,Bp,u||null),x(this,by,h),x(this,_y,d),x(this,Np,p),x(this,ky,m||null),this.viewParameters={realScale:uh.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1,this._editorUndoBar=v||null,this._supportsPinchToZoom=g!==!1,r==null||r.setSidebarUiManager(this)}static get _keyboardManager(){const e=bp.prototype,t=o=>f(o,Dl).contains(document.activeElement)&&document.activeElement.tagName!=="BUTTON"&&o.hasSomethingToControl(),n=(o,{target:a})=>{if(a instanceof HTMLInputElement){const{type:c}=a;return c!=="text"&&c!=="number"}return!0},i=this.TRANSLATE_SMALL,r=this.TRANSLATE_BIG;return Tt(this,"_keyboardManager",new r_([[["ctrl+a","mac+meta+a"],e.selectAll,{checker:n}],[["ctrl+z","mac+meta+z"],e.undo,{checker:n}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],e.redo,{checker:n}],[["Backspace","alt+Backspace","ctrl+Backspace","shift+Backspace","mac+Backspace","mac+alt+Backspace","mac+ctrl+Backspace","Delete","ctrl+Delete","shift+Delete","mac+Delete"],e.delete,{checker:n}],[["Enter","mac+Enter"],e.addNewEditorFromKeyboard,{checker:(o,{target:a})=>!(a instanceof HTMLButtonElement)&&f(o,Dl).contains(a)&&!o.isEnterHandled}],[[" ","mac+ "],e.addNewEditorFromKeyboard,{checker:(o,{target:a})=>!(a instanceof HTMLButtonElement)&&f(o,Dl).contains(document.activeElement)}],[["Escape","mac+Escape"],e.unselectAll],[["ArrowLeft","mac+ArrowLeft"],e.translateSelectedEditors,{args:[-i,0],checker:t}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],e.translateSelectedEditors,{args:[-r,0],checker:t}],[["ArrowRight","mac+ArrowRight"],e.translateSelectedEditors,{args:[i,0],checker:t}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],e.translateSelectedEditors,{args:[r,0],checker:t}],[["ArrowUp","mac+ArrowUp"],e.translateSelectedEditors,{args:[0,-i],checker:t}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],e.translateSelectedEditors,{args:[0,-r],checker:t}],[["ArrowDown","mac+ArrowDown"],e.translateSelectedEditors,{args:[0,i],checker:t}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],e.translateSelectedEditors,{args:[0,r],checker:t}]]))}destroy(){var e,t,n,i,r,o,a,c,l;(e=f(this,yo))==null||e.resolve(),x(this,yo,null),(t=f(this,Rp))==null||t.abort(),x(this,Rp,null),this._signal=null;for(const u of f(this,zs).values())u.destroy();f(this,zs).clear(),f(this,en).clear(),f(this,Qh).clear(),(n=f(this,du))==null||n.clear(),x(this,Or,null),f(this,ls).clear(),f(this,mo).destroy(),(i=f(this,Op))==null||i.destroy(),(r=f(this,$n))==null||r.destroy(),(o=f(this,fu))==null||o.destroy(),(a=f(this,Oa))==null||a.hide(),x(this,Oa,null),(c=f(this,$p))==null||c.destroy(),x(this,$p,null),x(this,Lp,null),f(this,Pa)&&(clearTimeout(f(this,Pa)),x(this,Pa,null)),f(this,Da)&&(clearTimeout(f(this,Da)),x(this,Da,null)),(l=this._editorUndoBar)==null||l.destroy(),x(this,Hp,null)}combinedSignal(e){return AbortSignal.any([this._signal,e.signal])}get mlManager(){return f(this,ky)}get useNewAltTextFlow(){return f(this,_y)}get useNewAltTextWhenAddingImage(){return f(this,Np)}get hcmFilter(){return Tt(this,"hcmFilter",f(this,pu)?f(this,Sy).addHCMFilter(f(this,pu).foreground,f(this,pu).background):"none")}get direction(){return Tt(this,"direction",getComputedStyle(f(this,Dl)).direction)}get _highlightColors(){return Tt(this,"_highlightColors",f(this,Bp)?new Map(f(this,Bp).split(",").map(e=>(e=e.split("=").map(t=>t.trim()),e[1]=e[1].toUpperCase(),e))):null)}get highlightColors(){const{_highlightColors:e}=this;if(!e)return Tt(this,"highlightColors",null);const t=new Map,n=!!f(this,pu);for(const[i,r]of e){const o=i.endsWith("_HCM");if(n&&o){t.set(i.replace("_HCM",""),r);continue}!n&&!o&&t.set(i,r)}return Tt(this,"highlightColors",t)}get highlightColorNames(){return Tt(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,e=>e.reverse())):null)}getNonHCMColor(e){if(!this._highlightColors)return e;const t=this.highlightColorNames.get(e);return this._highlightColors.get(t)||e}getNonHCMColorName(e){return this.highlightColorNames.get(e)||e}setCurrentDrawingSession(e){e?(this.unselectAll(),this.disableUserSelect(!0)):this.disableUserSelect(!1),x(this,ou,e)}setMainHighlightColorPicker(e){x(this,$p,e)}editAltText(e,t=!1){var n;(n=f(this,Op))==null||n.editAltText(this,e,t)}hasCommentManager(){return!!f(this,$n)}editComment(e,t,n,i){var r;(r=f(this,$n))==null||r.showDialog(this,e,t,n,i)}selectComment(e,t){const n=f(this,zs).get(e),i=n==null?void 0:n.getEditorByUID(t);i==null||i.toggleComment(!0,!0)}updateComment(e){var t;(t=f(this,$n))==null||t.updateComment(e.getData())}updatePopupColor(e){var t;(t=f(this,$n))==null||t.updatePopupColor(e)}removeComment(e){var t;(t=f(this,$n))==null||t.removeComments([e.uid])}deleteComment(e,t){const n=()=>{e.comment=t},i=()=>{var r;(r=this._editorUndoBar)==null||r.show(n,"comment"),this.toggleComment(null),e.comment=null};this.addCommands({cmd:i,undo:n,mustExec:!0})}toggleComment(e,t,n=void 0){var i;(i=f(this,$n))==null||i.toggleCommentPopup(e,t,n)}makeCommentColor(e,t){var n;return e&&((n=f(this,$n))==null?void 0:n.makeCommentColor(e,t))||null}getCommentDialogElement(){var e;return((e=f(this,$n))==null?void 0:e.dialogElement)||null}async waitForEditorsRendered(e){if(f(this,zs).has(e-1))return;const{resolve:t,promise:n}=Promise.withResolvers(),i=r=>{r.pageNumber===e&&(this._eventBus.off("editorsrendered",i),t())};this._eventBus.on("editorsrendered",i),await n}getSignature(e){var t;(t=f(this,fu))==null||t.getSignature({uiManager:this,editor:e})}get signatureManager(){return f(this,fu)}switchToMode(e,t){this._eventBus.on("annotationeditormodechanged",t,{once:!0,signal:this._signal}),this._eventBus.dispatch("showannotationeditorui",{source:this,mode:e})}setPreference(e,t){this._eventBus.dispatch("setpreference",{source:this,name:e,value:t})}onSetPreference({name:e,value:t}){switch(e){case"enableNewAltTextWhenAddingImage":x(this,Np,t);break}}onPageChanging({pageNumber:e}){x(this,au,e-1)}deletePage(e){for(const t of this.getEditors(e))t.remove();f(this,zs).delete(e),f(this,au)===e&&x(this,au,0)}focusMainContainer(){f(this,Dl).focus()}findParent(e,t){for(const n of f(this,zs).values()){const{x:i,y:r,width:o,height:a}=n.div.getBoundingClientRect();if(e>=i&&e<=i+o&&t>=r&&t<=r+a)return n}return null}disableUserSelect(e=!1){f(this,Ay).classList.toggle("noUserSelect",e)}addShouldRescale(e){f(this,Qh).add(e)}removeShouldRescale(e){f(this,Qh).delete(e)}onScaleChanging({scale:e}){var t;this.commitOrRemove(),this.viewParameters.realScale=e*uh.PDF_TO_CSS_UNITS;for(const n of f(this,Qh))n.onScaleChanging();(t=f(this,ou))==null||t.onScaleChanging()}onRotationChanging({pagesRotation:e}){this.commitOrRemove(),this.viewParameters.rotation=e}highlightSelection(e="",t=!1){const n=document.getSelection();if(!n||n.isCollapsed)return;const{anchorNode:i,anchorOffset:r,focusNode:o,focusOffset:a}=n,c=n.toString(),u=B(this,je,ES).call(this,n).closest(".textLayer"),h=this.getSelectionBoxes(u);if(!h)return;n.empty();const d=B(this,je,MT).call(this,u),p=f(this,vn)===Ct.NONE,m=()=>{const v=d==null?void 0:d.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:e,boxes:h,anchorNode:i,anchorOffset:r,focusNode:o,focusOffset:a,text:c});p&&this.showAllEditors("highlight",!0,!0),t&&(v==null||v.editComment())};if(p){this.switchToMode(Ct.HIGHLIGHT,m);return}m()}commentSelection(e=""){this.highlightSelection(e,!0)}getAndRemoveDataFromAnnotationStorage(e){if(!f(this,Wi))return null;const t=`${oy}${e}`,n=f(this,Wi).getRawValue(t);return n&&f(this,Wi).remove(t),n}addToAnnotationStorage(e){!e.isEmpty()&&f(this,Wi)&&!f(this,Wi).has(e.id)&&f(this,Wi).setValue(e.id,e)}a11yAlert(e,t=null){const n=f(this,Ey);n&&(n.setAttribute("data-l10n-id",e),t?n.setAttribute("data-l10n-args",JSON.stringify(t)):n.removeAttribute("data-l10n-args"))}blur(){if(this.isShiftKeyDown=!1,f(this,uu)&&(x(this,uu,!1),B(this,je,Ym).call(this,"main_toolbar")),!this.hasSelection)return;const{activeElement:e}=document;for(const t of f(this,ls))if(t.div.contains(e)){x(this,Xh,[t,e]),t._focusEventsAllowed=!1;break}}focus(){if(!f(this,Xh))return;const[e,t]=f(this,Xh);x(this,Xh,null),t.addEventListener("focusin",()=>{e._focusEventsAllowed=!0},{once:!0,signal:this._signal}),t.focus()}addEditListeners(){B(this,je,xT).call(this),this.setEditingState(!0)}removeEditListeners(){B(this,je,QD).call(this),this.setEditingState(!1)}dragOver(e){for(const{type:t}of e.dataTransfer.items)for(const n of f(this,vo))if(n.isHandlingMimeForPasting(t)){e.dataTransfer.dropEffect="copy",e.preventDefault();return}}drop(e){for(const t of e.dataTransfer.items)for(const n of f(this,vo))if(n.isHandlingMimeForPasting(t.type)){n.paste(t,this.currentLayer),e.preventDefault();return}}copy(e){var n;if(e.preventDefault(),(n=f(this,Or))==null||n.commitOrRemove(),!this.hasSelection)return;const t=[];for(const i of f(this,ls)){const r=i.serialize(!0);r&&t.push(r)}t.length!==0&&e.clipboardData.setData("application/pdfjs",JSON.stringify(t))}cut(e){this.copy(e),this.delete()}async paste(e){e.preventDefault();const{clipboardData:t}=e;for(const r of t.items)for(const o of f(this,vo))if(o.isHandlingMimeForPasting(r.type)){o.paste(r,this.currentLayer);return}let n=t.getData("application/pdfjs");if(!n)return;try{n=JSON.parse(n)}catch(r){kt(`paste: "${r.message}".`);return}if(!Array.isArray(n))return;this.unselectAll();const i=this.currentLayer;try{const r=[];for(const c of n){const l=await i.deserialize(c);if(!l)return;r.push(l)}const o=()=>{for(const c of r)B(this,je,IT).call(this,c);B(this,je,RT).call(this,r)},a=()=>{for(const c of r)c.remove()};this.addCommands({cmd:o,undo:a,mustExec:!0})}catch(r){kt(`paste: "${r.message}".`)}}keydown(e){!this.isShiftKeyDown&&e.key==="Shift"&&(this.isShiftKeyDown=!0),f(this,vn)!==Ct.NONE&&!this.isEditorHandlingKeyboard&&bp._keyboardManager.exec(this,e)}keyup(e){this.isShiftKeyDown&&e.key==="Shift"&&(this.isShiftKeyDown=!1,f(this,uu)&&(x(this,uu,!1),B(this,je,Ym).call(this,"main_toolbar")))}onEditingAction({name:e}){switch(e){case"undo":case"redo":case"delete":case"selectAll":this[e]();break;case"highlightSelection":this.highlightSelection("context_menu");break;case"commentSelection":this.commentSelection("context_menu");break}}updatePageIndex(e,t){for(const i of this.getEditors(e))i.pageIndex=t;const n=f(this,Pp).get(e);n&&(n.pageIndex=t,f(this,zs).set(t,n),f(this,Pl)?n.enable():n.disable())}startUpdatePages(){x(this,Pp,new Map(f(this,zs))),f(this,zs).clear()}endUpdatePages(){x(this,Pp,null)}clonePage(e,t){for(const n of this.getEditors(e)){const i=n.serialize(n.mode!==Ct.HIGHLIGHT);i&&(i.pageIndex=t,i.id=this.getId(),i.isClone=!0,delete i.popupRef,f(this,Wi).setValue(i.id,i))}}findClonesForPage(e){const t=[],{pageIndex:n}=e;for(const[i,r]of f(this,Wi))r.pageIndex===n&&r.isClone&&(f(this,Wi).remove(i),t.push(e.deserialize(r).then(o=>{o&&(o.isClone=!0,e.addOrRebuild(o))})));return Promise.all(t)}setEditingState(e){e?(B(this,je,qD).call(this),B(this,je,XD).call(this),B(this,je,$i).call(this,{isEditing:f(this,vn)!==Ct.NONE,isEmpty:B(this,je,Jm).call(this),hasSomethingToUndo:f(this,mo).hasSomethingToUndo(),hasSomethingToRedo:f(this,mo).hasSomethingToRedo(),hasSelectedEditor:!1})):(B(this,je,KD).call(this),B(this,je,YD).call(this),B(this,je,$i).call(this,{isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(e){if(!f(this,vo)){x(this,vo,e);for(const t of f(this,vo))B(this,je,Tl).call(this,t.defaultPropertiesToUpdate)}}getId(){return f(this,C0).id}get currentLayer(){return f(this,zs).get(f(this,au))}getLayer(e){return f(this,zs).get(e)}get currentPageIndex(){return f(this,au)}addLayer(e){f(this,zs).set(e.pageIndex,e),f(this,Pl)?e.enable():e.disable()}removeLayer(e){f(this,zs).delete(e.pageIndex)}async updateMode(e,t=null,n=!1,i=!1,r=!1,o=!1){var a,c,l,u,h,d;if(f(this,vn)!==e&&!(f(this,yo)&&(await f(this,yo).promise,!f(this,yo)))){if(x(this,yo,Promise.withResolvers()),(a=f(this,ou))==null||a.commitOrRemove(),f(this,vn)===Ct.POPUP&&((c=f(this,$n))==null||c.hideSidebar()),(l=f(this,$n))==null||l.destroyPopup(),x(this,vn,e),e===Ct.NONE){this.setEditingState(!1),B(this,je,eN).call(this);for(const p of f(this,en).values())p.hideStandaloneCommentButton();(u=this._editorUndoBar)==null||u.hide(),this.toggleComment(null),f(this,yo).resolve();return}for(const p of f(this,en).values())p.addStandaloneCommentButton();e===Ct.SIGNATURE&&await((h=f(this,fu))==null?void 0:h.loadSignatures()),n&&Si.clearPointerType(),this.setEditingState(!0),await B(this,je,ZD).call(this),this.unselectAll();for(const p of f(this,zs).values())p.updateMode(e);if(e===Ct.POPUP){f(this,Lp)||x(this,Lp,await f(this,Hp).getAnnotationsByType(new Set(f(this,vo).map(v=>v._editorType))));const p=new Set,m=[];for(const v of f(this,en).values()){const{annotationElementId:g,hasComment:y,deleted:b}=v;g&&p.add(g),y&&!b&&m.push(v.getData())}for(const v of f(this,Lp)){const{id:g,popupRef:y,contentsObj:b}=v;y&&(b!=null&&b.str)&&!p.has(g)&&!f(this,lu).has(g)&&m.push(v)}(d=f(this,$n))==null||d.showSidebar(m)}if(!t){i&&this.addNewEditorFromKeyboard(),f(this,yo).resolve();return}for(const p of f(this,en).values())p.uid===t?(this.setSelected(p),o?p.editComment():r?p.enterInEditMode():p.focus()):p.unselect();f(this,yo).resolve()}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(e){e.mode!==f(this,vn)&&this._eventBus.dispatch("switchannotationeditormode",{source:this,...e})}updateParams(e,t){if(f(this,vo)){switch(e){case xt.CREATE:this.currentLayer.addNewEditor(t);return;case xt.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(f(this,Cy)||x(this,Cy,new Map)).set(e,t),this.showAllEditors("highlight",t);break}if(this.hasSelection)for(const n of f(this,ls))n.updateParams(e,t);else for(const n of f(this,vo))n.updateDefaultParams(e,t)}}showAllEditors(e,t,n=!1){var r;for(const o of f(this,en).values())o.editorType===e&&o.show(t);(((r=f(this,Cy))==null?void 0:r.get(xt.HIGHLIGHT_SHOW_ALL))??!0)!==t&&B(this,je,Tl).call(this,[[xt.HIGHLIGHT_SHOW_ALL,t]])}enableWaiting(e=!1){if(f(this,wy)!==e){x(this,wy,e);for(const t of f(this,zs).values())e?t.disableClick():t.enableClick(),t.div.classList.toggle("waiting",e)}}*getEditors(e){for(const t of f(this,en).values())t.pageIndex===e&&(yield t)}getEditor(e){return f(this,en).get(e)}addEditor(e){f(this,en).set(e.id,e)}removeEditor(e){var t,n;e.div.contains(document.activeElement)&&(f(this,Pa)&&clearTimeout(f(this,Pa)),x(this,Pa,setTimeout(()=>{this.focusMainContainer(),x(this,Pa,null)},0))),f(this,en).delete(e.id),e.annotationElementId&&((t=f(this,du))==null||t.delete(e.annotationElementId)),this.unselect(e),(!e.annotationElementId||!f(this,lu).has(e.annotationElementId))&&((n=f(this,Wi))==null||n.remove(e.id))}addDeletedAnnotationElement(e){f(this,lu).add(e.annotationElementId),this.addChangedExistingAnnotation(e),e.deleted=!0}isDeletedAnnotationElement(e){return f(this,lu).has(e)}removeDeletedAnnotationElement(e){f(this,lu).delete(e.annotationElementId),this.removeChangedExistingAnnotation(e),e.deleted=!1}setActiveEditor(e){f(this,Or)!==e&&(x(this,Or,e),e&&B(this,je,Tl).call(this,e.propertiesToUpdate))}updateUI(e){f(this,je,tN)===e&&B(this,je,Tl).call(this,e.propertiesToUpdate)}updateUIForDefaultProperties(e){B(this,je,Tl).call(this,e.defaultPropertiesToUpdate)}toggleSelected(e){if(f(this,ls).has(e)){f(this,ls).delete(e),e.unselect(),B(this,je,$i).call(this,{hasSelectedEditor:this.hasSelection});return}f(this,ls).add(e),e.select(),B(this,je,Tl).call(this,e.propertiesToUpdate),B(this,je,$i).call(this,{hasSelectedEditor:!0})}setSelected(e){var t,n;this.updateToolbar({mode:e.mode,editId:e.uid}),(t=f(this,ou))==null||t.commitOrRemove();for(const i of f(this,ls))i!==e&&i.unselect();(n=f(this,$n))==null||n.destroyPopup(),f(this,ls).clear(),f(this,ls).add(e),e.select(),B(this,je,Tl).call(this,e.propertiesToUpdate),B(this,je,$i).call(this,{hasSelectedEditor:!0})}isSelected(e){return f(this,ls).has(e)}get firstSelectedEditor(){return f(this,ls).values().next().value}unselect(e){e.unselect(),f(this,ls).delete(e),B(this,je,$i).call(this,{hasSelectedEditor:this.hasSelection})}get hasSelection(){return f(this,ls).size!==0}get isEnterHandled(){return f(this,ls).size===1&&this.firstSelectedEditor.isEnterHandled}undo(){var e;f(this,mo).undo(),B(this,je,$i).call(this,{hasSomethingToUndo:f(this,mo).hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:B(this,je,Jm).call(this)}),(e=this._editorUndoBar)==null||e.hide()}redo(){f(this,mo).redo(),B(this,je,$i).call(this,{hasSomethingToUndo:!0,hasSomethingToRedo:f(this,mo).hasSomethingToRedo(),isEmpty:B(this,je,Jm).call(this)})}addCommands(e){f(this,mo).add(e),B(this,je,$i).call(this,{hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:B(this,je,Jm).call(this)})}cleanUndoStack(e){f(this,mo).cleanType(e)}delete(){var r;this.commitOrRemove();const e=(r=this.currentLayer)==null?void 0:r.endDrawingSession(!0);if(!this.hasSelection&&!e)return;const t=e?[e]:[...f(this,ls)],n=()=>{var o;(o=this._editorUndoBar)==null||o.show(i,t.length===1?t[0].editorType:t.length);for(const a of t)a.remove()},i=()=>{for(const o of t)B(this,je,IT).call(this,o)};this.addCommands({cmd:n,undo:i,mustExec:!0})}commitOrRemove(){var e;(e=f(this,Or))==null||e.commitOrRemove()}hasSomethingToControl(){return f(this,Or)||this.hasSelection}selectAll(){for(const e of f(this,ls))e.commit();B(this,je,RT).call(this,f(this,en).values())}unselectAll(){var e,t;if(!(f(this,Or)&&(f(this,Or).commitOrRemove(),f(this,vn)!==Ct.NONE))&&!((e=f(this,ou))!=null&&e.commitOrRemove())&&((t=f(this,$n))==null||t.destroyPopup(),!!this.hasSelection)){for(const n of f(this,ls))n.unselect();f(this,ls).clear(),B(this,je,$i).call(this,{hasSelectedEditor:!1})}}translateSelectedEditors(e,t,n=!1){if(n||this.commitOrRemove(),!this.hasSelection)return;f(this,gu)[0]+=e,f(this,gu)[1]+=t;const[i,r]=f(this,gu),o=[...f(this,ls)],a=1e3;f(this,Da)&&clearTimeout(f(this,Da)),x(this,Da,setTimeout(()=>{x(this,Da,null),f(this,gu)[0]=f(this,gu)[1]=0,this.addCommands({cmd:()=>{for(const c of o)f(this,en).has(c.id)&&(c.translateInPage(i,r),c.translationDone())},undo:()=>{for(const c of o)f(this,en).has(c.id)&&(c.translateInPage(-i,-r),c.translationDone())},mustExec:!1})},a));for(const c of o)c.translateInPage(e,t),c.translationDone()}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0),x(this,La,new Map);for(const e of f(this,ls))f(this,La).set(e,{savedX:e.x,savedY:e.y,savedPageIndex:e.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!f(this,La))return!1;this.disableUserSelect(!1);const e=f(this,La);x(this,La,null);let t=!1;for(const[{x:i,y:r,pageIndex:o},a]of e)a.newX=i,a.newY=r,a.newPageIndex=o,t||(t=i!==a.savedX||r!==a.savedY||o!==a.savedPageIndex);if(!t)return!1;const n=(i,r,o,a)=>{if(f(this,en).has(i.id)){const c=f(this,zs).get(a);c?i._setParentAndPosition(c,r,o):(i.pageIndex=a,i.x=r,i.y=o)}};return this.addCommands({cmd:()=>{for(const[i,{newX:r,newY:o,newPageIndex:a}]of e)n(i,r,o,a)},undo:()=>{for(const[i,{savedX:r,savedY:o,savedPageIndex:a}]of e)n(i,r,o,a)},mustExec:!0}),!0}dragSelectedEditors(e,t){if(f(this,La))for(const n of f(this,La).keys())n.drag(e,t)}rebuild(e){if(e.parent===null){const t=this.getLayer(e.pageIndex);t?(t.changeParent(e),t.addOrRebuild(e)):(this.addEditor(e),this.addToAnnotationStorage(e),e.rebuild())}else e.parent.addOrRebuild(e)}get isEditorHandlingKeyboard(){var e;return((e=this.getActive())==null?void 0:e.shouldGetKeyboardEvents())||f(this,ls).size===1&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(e){return f(this,Or)===e}getActive(){return f(this,Or)}getMode(){return f(this,vn)}isEditingMode(){return f(this,vn)!==Ct.NONE}get imageManager(){return Tt(this,"imageManager",new AT)}getSelectionBoxes(e){if(!e)return null;const t=document.getSelection();for(let l=0,u=t.rangeCount;l<u;l++)if(!e.contains(t.getRangeAt(l).commonAncestorContainer))return null;const{x:n,y:i,width:r,height:o}=e.getBoundingClientRect();let a;switch(e.getAttribute("data-main-rotation")){case"90":a=(l,u,h,d)=>({x:(u-i)/o,y:1-(l+h-n)/r,width:d/o,height:h/r});break;case"180":a=(l,u,h,d)=>({x:1-(l+h-n)/r,y:1-(u+d-i)/o,width:h/r,height:d/o});break;case"270":a=(l,u,h,d)=>({x:1-(u+d-i)/o,y:(l-n)/r,width:d/o,height:h/r});break;default:a=(l,u,h,d)=>({x:(l-n)/r,y:(u-i)/o,width:h/r,height:d/o});break}const c=[];for(let l=0,u=t.rangeCount;l<u;l++){const h=t.getRangeAt(l);if(!h.collapsed)for(const{x:d,y:p,width:m,height:v}of h.getClientRects())m===0||v===0||c.push(a(d,p,m,v))}return c.length===0?null:c}addChangedExistingAnnotation({annotationElementId:e,id:t}){(f(this,Dp)||x(this,Dp,new Map)).set(e,t)}removeChangedExistingAnnotation({annotationElementId:e}){var t;(t=f(this,Dp))==null||t.delete(e)}renderAnnotationElement(e){var i;const t=(i=f(this,Dp))==null?void 0:i.get(e.data.id);if(!t)return;const n=f(this,Wi).getRawValue(t);n&&(f(this,vn)===Ct.NONE&&!n.hasBeenModified||n.renderAnnotationElement(e))}setMissingCanvas(e,t,n){var r;const i=(r=f(this,du))==null?void 0:r.get(e);i&&(i.setCanvas(t,n),f(this,du).delete(e))}addMissingCanvas(e,t){(f(this,du)||x(this,du,new Map)).set(e,t)}};Rp=new WeakMap,Or=new WeakMap,Lp=new WeakMap,en=new WeakMap,zs=new WeakMap,Pp=new WeakMap,Op=new WeakMap,Wi=new WeakMap,Dp=new WeakMap,mo=new WeakMap,$n=new WeakMap,ru=new WeakMap,ou=new WeakMap,au=new WeakMap,lu=new WeakMap,La=new WeakMap,vo=new WeakMap,Qh=new WeakMap,by=new WeakMap,_y=new WeakMap,Np=new WeakMap,Sy=new WeakMap,Pa=new WeakMap,cu=new WeakMap,Bp=new WeakMap,uu=new WeakMap,Oa=new WeakMap,C0=new WeakMap,Pl=new WeakMap,Fp=new WeakMap,wy=new WeakMap,hu=new WeakMap,Xh=new WeakMap,$p=new WeakMap,du=new WeakMap,ky=new WeakMap,vn=new WeakMap,ls=new WeakMap,Ol=new WeakMap,fu=new WeakMap,pu=new WeakMap,Cy=new WeakMap,Hp=new WeakMap,Ty=new WeakMap,gu=new WeakMap,Da=new WeakMap,Dl=new WeakMap,Ay=new WeakMap,Ey=new WeakMap,yo=new WeakMap,je=new WeakSet,ES=function({anchorNode:e}){return e.nodeType===Node.TEXT_NODE?e.parentElement:e},MT=function(e){const{currentLayer:t}=this;if(t.hasTextLayer(e))return t;for(const n of f(this,zs).values())if(n.hasTextLayer(e))return n;return null},zD=function(e){var t;this.commitOrRemove(),(t=this.currentLayer)==null||t.endDrawingSession(!1)},jD=function(){const e=document.getSelection();if(!e||e.isCollapsed)return;const n=B(this,je,ES).call(this,e).closest(".textLayer"),i=this.getSelectionBoxes(n);i&&(f(this,Oa)||x(this,Oa,new Lee(this)),f(this,Oa).show(n,i,this.direction==="ltr"))},VD=function(){var r,o,a;const e=document.getSelection();if(!e||e.isCollapsed){f(this,Ol)&&((r=f(this,Oa))==null||r.hide(),x(this,Ol,null),B(this,je,$i).call(this,{hasSelectedText:!1}));return}const{anchorNode:t}=e;if(t===f(this,Ol))return;const i=B(this,je,ES).call(this,e).closest(".textLayer");if(!i){f(this,Ol)&&((o=f(this,Oa))==null||o.hide(),x(this,Ol,null),B(this,je,$i).call(this,{hasSelectedText:!1}));return}if((a=f(this,Oa))==null||a.hide(),x(this,Ol,t),B(this,je,$i).call(this,{hasSelectedText:!0}),!(f(this,vn)!==Ct.HIGHLIGHT&&f(this,vn)!==Ct.NONE)&&(f(this,vn)===Ct.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0),x(this,uu,this.isShiftKeyDown),!this.isShiftKeyDown)){const c=f(this,vn)===Ct.HIGHLIGHT?B(this,je,MT).call(this,i):null;if(c==null||c.toggleDrawing(),f(this,Fp)){const l=new AbortController,u=this.combinedSignal(l),h=d=>{d.type==="pointerup"&&d.button!==0||(l.abort(),c==null||c.toggleDrawing(!0),d.type==="pointerup"&&B(this,je,Ym).call(this,"main_toolbar"))};window.addEventListener("pointerup",h,{signal:u}),window.addEventListener("blur",h,{signal:u})}else c==null||c.toggleDrawing(!0),B(this,je,Ym).call(this,"main_toolbar")}},Ym=function(e=""){f(this,vn)===Ct.HIGHLIGHT?this.highlightSelection(e):f(this,by)&&B(this,je,jD).call(this)},GD=function(){document.addEventListener("selectionchange",B(this,je,VD).bind(this),{signal:this._signal})},qD=function(){if(f(this,cu))return;x(this,cu,new AbortController);const e=this.combinedSignal(f(this,cu));window.addEventListener("focus",this.focus.bind(this),{signal:e}),window.addEventListener("blur",this.blur.bind(this),{signal:e})},KD=function(){var e;(e=f(this,cu))==null||e.abort(),x(this,cu,null)},xT=function(){if(f(this,hu))return;x(this,hu,new AbortController);const e=this.combinedSignal(f(this,hu));window.addEventListener("keydown",this.keydown.bind(this),{signal:e}),window.addEventListener("keyup",this.keyup.bind(this),{signal:e})},QD=function(){var e;(e=f(this,hu))==null||e.abort(),x(this,hu,null)},XD=function(){if(f(this,ru))return;x(this,ru,new AbortController);const e=this.combinedSignal(f(this,ru));document.addEventListener("copy",this.copy.bind(this),{signal:e}),document.addEventListener("cut",this.cut.bind(this),{signal:e}),document.addEventListener("paste",this.paste.bind(this),{signal:e})},YD=function(){var e;(e=f(this,ru))==null||e.abort(),x(this,ru,null)},JD=function(){const e=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:e}),document.addEventListener("drop",this.drop.bind(this),{signal:e})},$i=function(e){Object.entries(e).some(([n,i])=>f(this,Ty)[n]!==i)&&(this._eventBus.dispatch("editingstateschanged",{source:this,details:Object.assign(f(this,Ty),e)}),f(this,vn)===Ct.HIGHLIGHT&&e.hasSelectedEditor===!1&&B(this,je,Tl).call(this,[[xt.HIGHLIGHT_FREE,!0]]))},Tl=function(e){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:e})},ZD=async function(){if(!f(this,Pl)){x(this,Pl,!0);const e=[];for(const t of f(this,zs).values())e.push(t.enable());await Promise.all(e);for(const t of f(this,en).values())t.enable()}},eN=function(){if(this.unselectAll(),f(this,Pl)){x(this,Pl,!1);for(const e of f(this,zs).values())e.disable();for(const e of f(this,en).values())e.disable()}},IT=function(e){const t=f(this,zs).get(e.pageIndex);t?t.addOrRebuild(e):(this.addEditor(e),this.addToAnnotationStorage(e))},tN=function(){let e=null;for(e of f(this,ls));return e},Jm=function(){if(f(this,en).size===0)return!0;if(f(this,en).size===1)for(const e of f(this,en).values())return e.isEmpty();return!1},RT=function(e){for(const t of f(this,ls))t.unselect();f(this,ls).clear();for(const t of e)t.isEmpty()||(f(this,ls).add(t),t.select());B(this,je,$i).call(this,{hasSelectedEditor:this.hasSelection})},_e(bp,"TRANSLATE_SMALL",1),_e(bp,"TRANSLATE_BIG",10);let Lf=bp;var Hn,Na,Zo,Up,Ba,Dr,Wp,Fa,lr,Nl,Yh,$a,mu,pa,Zm,MS;const Ui=class Ui{constructor(e){D(this,pa);D(this,Hn,null);D(this,Na,!1);D(this,Zo,null);D(this,Up,null);D(this,Ba,null);D(this,Dr,null);D(this,Wp,!1);D(this,Fa,null);D(this,lr,null);D(this,Nl,null);D(this,Yh,null);D(this,$a,!1);x(this,lr,e),x(this,$a,e._uiManager.useNewAltTextFlow),f(Ui,mu)||x(Ui,mu,Object.freeze({added:"pdfjs-editor-new-alt-text-added-button","added-label":"pdfjs-editor-new-alt-text-added-button-label",missing:"pdfjs-editor-new-alt-text-missing-button","missing-label":"pdfjs-editor-new-alt-text-missing-button-label",review:"pdfjs-editor-new-alt-text-to-review-button","review-label":"pdfjs-editor-new-alt-text-to-review-button-label"}))}static initialize(e){Ui._l10n??(Ui._l10n=e)}async render(){const e=x(this,Zo,document.createElement("button"));e.className="altText",e.tabIndex="0";const t=x(this,Up,document.createElement("span"));e.append(t),f(this,$a)?(e.classList.add("new"),e.setAttribute("data-l10n-id",f(Ui,mu).missing),t.setAttribute("data-l10n-id",f(Ui,mu)["missing-label"])):(e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button"),t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button-label"));const n=f(this,lr)._uiManager._signal;e.addEventListener("contextmenu",Ho,{signal:n}),e.addEventListener("pointerdown",r=>r.stopPropagation(),{signal:n});const i=r=>{r.preventDefault(),f(this,lr)._uiManager.editAltText(f(this,lr)),f(this,$a)&&f(this,lr)._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:f(this,pa,Zm)}})};return e.addEventListener("click",i,{capture:!0,signal:n}),e.addEventListener("keydown",r=>{r.target===e&&r.key==="Enter"&&(x(this,Wp,!0),i(r))},{signal:n}),await B(this,pa,MS).call(this),e}finish(){f(this,Zo)&&(f(this,Zo).focus({focusVisible:f(this,Wp)}),x(this,Wp,!1))}isEmpty(){return f(this,$a)?f(this,Hn)===null:!f(this,Hn)&&!f(this,Na)}hasData(){return f(this,$a)?f(this,Hn)!==null||!!f(this,Nl):this.isEmpty()}get guessedText(){return f(this,Nl)}async setGuessedText(e){f(this,Hn)===null&&(x(this,Nl,e),x(this,Yh,await Ui._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:e})),B(this,pa,MS).call(this))}toggleAltTextBadge(e=!1){var t;if(!f(this,$a)||f(this,Hn)){(t=f(this,Fa))==null||t.remove(),x(this,Fa,null);return}if(!f(this,Fa)){const n=x(this,Fa,document.createElement("div"));n.className="noAltTextBadge",f(this,lr).div.append(n)}f(this,Fa).classList.toggle("hidden",!e)}serialize(e){let t=f(this,Hn);return!e&&f(this,Nl)===t&&(t=f(this,Yh)),{altText:t,decorative:f(this,Na),guessedText:f(this,Nl),textWithDisclaimer:f(this,Yh)}}get data(){return{altText:f(this,Hn),decorative:f(this,Na)}}set data({altText:e,decorative:t,guessedText:n,textWithDisclaimer:i,cancel:r=!1}){n&&(x(this,Nl,n),x(this,Yh,i)),!(f(this,Hn)===e&&f(this,Na)===t)&&(r||(x(this,Hn,e),x(this,Na,t)),B(this,pa,MS).call(this))}toggle(e=!1){f(this,Zo)&&(!e&&f(this,Dr)&&(clearTimeout(f(this,Dr)),x(this,Dr,null)),f(this,Zo).disabled=!e)}shown(){f(this,lr)._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:f(this,pa,Zm)}})}destroy(){var e,t;(e=f(this,Zo))==null||e.remove(),x(this,Zo,null),x(this,Up,null),x(this,Ba,null),(t=f(this,Fa))==null||t.remove(),x(this,Fa,null)}};Hn=new WeakMap,Na=new WeakMap,Zo=new WeakMap,Up=new WeakMap,Ba=new WeakMap,Dr=new WeakMap,Wp=new WeakMap,Fa=new WeakMap,lr=new WeakMap,Nl=new WeakMap,Yh=new WeakMap,$a=new WeakMap,mu=new WeakMap,pa=new WeakSet,Zm=function(){return f(this,Hn)&&"added"||f(this,Hn)===null&&this.guessedText&&"review"||"missing"},MS=async function(){var i,r,o;const e=f(this,Zo);if(!e)return;if(f(this,$a)){if(e.classList.toggle("done",!!f(this,Hn)),e.setAttribute("data-l10n-id",f(Ui,mu)[f(this,pa,Zm)]),(i=f(this,Up))==null||i.setAttribute("data-l10n-id",f(Ui,mu)[`${f(this,pa,Zm)}-label`]),!f(this,Hn)){(r=f(this,Ba))==null||r.remove();return}}else{if(!f(this,Hn)&&!f(this,Na)){e.classList.remove("done"),(o=f(this,Ba))==null||o.remove();return}e.classList.add("done"),e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let t=f(this,Ba);if(!t){x(this,Ba,t=document.createElement("span")),t.className="tooltip",t.setAttribute("role","tooltip"),t.id=`alt-text-tooltip-${f(this,lr).id}`;const a=100,c=f(this,lr)._uiManager._signal;c.addEventListener("abort",()=>{clearTimeout(f(this,Dr)),x(this,Dr,null)},{once:!0}),e.addEventListener("mouseenter",()=>{x(this,Dr,setTimeout(()=>{x(this,Dr,null),f(this,Ba).classList.add("show"),f(this,lr)._reportTelemetry({action:"alt_text_tooltip"})},a))},{signal:c}),e.addEventListener("mouseleave",()=>{var l;f(this,Dr)&&(clearTimeout(f(this,Dr)),x(this,Dr,null)),(l=f(this,Ba))==null||l.classList.remove("show")},{signal:c})}f(this,Na)?t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-decorative-tooltip"):(t.removeAttribute("data-l10n-id"),t.textContent=f(this,Hn)),t.parentNode||e.append(t);const n=f(this,lr).getElementForAltText();n==null||n.setAttribute("aria-describedby",t.id)},D(Ui,mu,null),_e(Ui,"_l10n",null);let u0=Ui;var ii,bo,Jh,ks,My,vu,_o,yu,bu,Zh,xy,LT;class V_{constructor(e){D(this,xy);D(this,ii,null);D(this,bo,null);D(this,Jh,!1);D(this,ks,null);D(this,My,null);D(this,vu,null);D(this,_o,null);D(this,yu,null);D(this,bu,!1);D(this,Zh,null);x(this,ks,e)}renderForToolbar(){const e=x(this,bo,document.createElement("button"));return e.className="comment",B(this,xy,LT).call(this,e,!1)}renderForStandalone(){const e=x(this,ii,document.createElement("button"));e.className="annotationCommentButton";const t=f(this,ks).commentButtonPosition;if(t){const{style:n}=e;n.insetInlineEnd=`calc(${100*(f(this,ks)._uiManager.direction==="ltr"?1-t[0]:t[0])}% - var(--comment-button-dim))`,n.top=`calc(${100*t[1]}% - var(--comment-button-dim))`;const i=f(this,ks).commentButtonColor;i&&(n.backgroundColor=i)}return B(this,xy,LT).call(this,e,!0)}focusButton(){setTimeout(()=>{var e;(e=f(this,ii)??f(this,bo))==null||e.focus()},0)}onUpdatedColor(){if(!f(this,ii))return;const e=f(this,ks).commentButtonColor;e&&(f(this,ii).style.backgroundColor=e),f(this,ks)._uiManager.updatePopupColor(f(this,ks))}get commentButtonWidth(){var e;return(((e=f(this,ii))==null?void 0:e.getBoundingClientRect().width)??0)/f(this,ks).parent.boundingClientRect.width}get commentPopupPositionInLayer(){if(f(this,Zh))return f(this,Zh);if(!f(this,ii))return null;const{x:e,y:t,height:n}=f(this,ii).getBoundingClientRect(),{x:i,y:r,width:o,height:a}=f(this,ks).parent.boundingClientRect;return[(e-i)/o,(t+n-r)/a]}set commentPopupPositionInLayer(e){x(this,Zh,e)}hasDefaultPopupPosition(){return f(this,Zh)===null}removeStandaloneCommentButton(){var e;(e=f(this,ii))==null||e.remove(),x(this,ii,null)}removeToolbarCommentButton(){var e;(e=f(this,bo))==null||e.remove(),x(this,bo,null)}setCommentButtonStates({selected:e,hasPopup:t}){f(this,ii)&&(f(this,ii).classList.toggle("selected",e),f(this,ii).ariaExpanded=t)}edit(e){const t=this.commentPopupPositionInLayer;let n,i;if(t)[n,i]=t;else{[n,i]=f(this,ks).commentButtonPosition;const{width:u,height:h,x:d,y:p}=f(this,ks);n=d+n*u,i=p+i*h}const r=f(this,ks).parent.boundingClientRect,{x:o,y:a,width:c,height:l}=r;f(this,ks)._uiManager.editComment(f(this,ks),o+n*c,a+i*l,{...e,parentDimensions:r})}finish(){f(this,bo)&&(f(this,bo).focus({focusVisible:f(this,Jh)}),x(this,Jh,!1))}isDeleted(){return f(this,bu)||f(this,_o)===""}isEmpty(){return f(this,_o)===null}hasBeenEdited(){return this.isDeleted()||f(this,_o)!==f(this,My)}serialize(){return this.data}get data(){return{text:f(this,_o),richText:f(this,vu),date:f(this,yu),deleted:this.isDeleted()}}set data(e){if(e!==f(this,_o)&&x(this,vu,null),e===null){x(this,_o,""),x(this,bu,!0);return}x(this,_o,e),x(this,yu,new Date),x(this,bu,!1)}restoreData({text:e,richText:t,date:n}){x(this,_o,e),x(this,vu,t),x(this,yu,n),x(this,bu,!1)}setInitialText(e,t=null){x(this,My,e),this.data=e,x(this,yu,null),x(this,vu,t)}shown(){}destroy(){var e,t;(e=f(this,bo))==null||e.remove(),x(this,bo,null),(t=f(this,ii))==null||t.remove(),x(this,ii,null),x(this,_o,""),x(this,vu,null),x(this,yu,null),x(this,ks,null),x(this,Jh,!1),x(this,bu,!1)}}ii=new WeakMap,bo=new WeakMap,Jh=new WeakMap,ks=new WeakMap,My=new WeakMap,vu=new WeakMap,_o=new WeakMap,yu=new WeakMap,bu=new WeakMap,Zh=new WeakMap,xy=new WeakSet,LT=function(e,t){if(!f(this,ks)._uiManager.hasCommentManager())return null;e.tabIndex="0",e.ariaHasPopup="dialog",t?(e.ariaControls="commentPopup",e.setAttribute("data-l10n-id","pdfjs-show-comment-button")):(e.ariaControlsElements=[f(this,ks)._uiManager.getCommentDialogElement()],e.setAttribute("data-l10n-id","pdfjs-editor-add-comment-button"));const n=f(this,ks)._uiManager._signal;if(!(n instanceof AbortSignal)||n.aborted)return e;e.addEventListener("contextmenu",Ho,{signal:n}),t&&(e.addEventListener("focusin",r=>{f(this,ks)._focusEventsAllowed=!1,js(r)},{capture:!0,signal:n}),e.addEventListener("focusout",r=>{f(this,ks)._focusEventsAllowed=!0,js(r)},{capture:!0,signal:n})),e.addEventListener("pointerdown",r=>r.stopPropagation(),{signal:n});const i=r=>{r.preventDefault(),e===f(this,bo)?this.edit():f(this,ks).toggleComment(!0)};return e.addEventListener("click",i,{capture:!0,signal:n}),e.addEventListener("keydown",r=>{r.target===e&&r.key==="Enter"&&(x(this,Jh,!0),i(r))},{signal:n}),e.addEventListener("pointerenter",()=>{f(this,ks).toggleComment(!1,!0)},{signal:n}),e.addEventListener("pointerleave",()=>{f(this,ks).toggleComment(!1,!1)},{signal:n}),e};var zp,ed,Iy,Ry,Ly,Py,Oy,Bl,td,Fl,sd,$l,hh,sN,nN,iN;const wM=class wM{constructor({container:e,isPinchingDisabled:t=null,isPinchingStopped:n=null,onPinchStart:i=null,onPinching:r=null,onPinchEnd:o=null,signal:a}){D(this,hh);D(this,zp);D(this,ed,!1);D(this,Iy,null);D(this,Ry);D(this,Ly);D(this,Py);D(this,Oy);D(this,Bl,null);D(this,td);D(this,Fl,null);D(this,sd);D(this,$l,null);x(this,zp,e),x(this,Iy,n),x(this,Ry,t),x(this,Ly,i),x(this,Py,r),x(this,Oy,o),x(this,sd,new AbortController),x(this,td,AbortSignal.any([a,f(this,sd).signal])),e.addEventListener("touchstart",B(this,hh,sN).bind(this),{passive:!1,signal:f(this,td)})}get MIN_TOUCH_DISTANCE_TO_PINCH(){return 35/ll.pixelRatio}destroy(){var e,t;(e=f(this,sd))==null||e.abort(),x(this,sd,null),(t=f(this,Bl))==null||t.abort(),x(this,Bl,null)}};zp=new WeakMap,ed=new WeakMap,Iy=new WeakMap,Ry=new WeakMap,Ly=new WeakMap,Py=new WeakMap,Oy=new WeakMap,Bl=new WeakMap,td=new WeakMap,Fl=new WeakMap,sd=new WeakMap,$l=new WeakMap,hh=new WeakSet,sN=function(e){var i,r,o;if((i=f(this,Ry))!=null&&i.call(this))return;if(e.touches.length===1){if(f(this,Bl))return;const a=x(this,Bl,new AbortController),c=AbortSignal.any([f(this,td),a.signal]),l=f(this,zp),u={capture:!0,signal:c,passive:!1},h=d=>{var p;d.pointerType==="touch"&&((p=f(this,Bl))==null||p.abort(),x(this,Bl,null))};l.addEventListener("pointerdown",d=>{d.pointerType==="touch"&&(js(d),h(d))},u),l.addEventListener("pointerup",h,u),l.addEventListener("pointercancel",h,u);return}if(!f(this,$l)){x(this,$l,new AbortController);const a=AbortSignal.any([f(this,td),f(this,$l).signal]),c=f(this,zp),l={signal:a,capture:!1,passive:!1};c.addEventListener("touchmove",B(this,hh,nN).bind(this),l);const u=B(this,hh,iN).bind(this);c.addEventListener("touchend",u,l),c.addEventListener("touchcancel",u,l),l.capture=!0,c.addEventListener("pointerdown",js,l),c.addEventListener("pointermove",js,l),c.addEventListener("pointercancel",js,l),c.addEventListener("pointerup",js,l),(r=f(this,Ly))==null||r.call(this)}if(js(e),e.touches.length!==2||(o=f(this,Iy))!=null&&o.call(this)){x(this,Fl,null);return}let[t,n]=e.touches;t.identifier>n.identifier&&([t,n]=[n,t]),x(this,Fl,{touch0X:t.screenX,touch0Y:t.screenY,touch1X:n.screenX,touch1Y:n.screenY})},nN=function(e){var w;if(!f(this,Fl)||e.touches.length!==2)return;js(e);let[t,n]=e.touches;t.identifier>n.identifier&&([t,n]=[n,t]);const{screenX:i,screenY:r}=t,{screenX:o,screenY:a}=n,c=f(this,Fl),{touch0X:l,touch0Y:u,touch1X:h,touch1Y:d}=c,p=h-l,m=d-u,v=o-i,g=a-r,y=Math.hypot(v,g)||1,b=Math.hypot(p,m)||1;if(!f(this,ed)&&Math.abs(b-y)<=wM.MIN_TOUCH_DISTANCE_TO_PINCH)return;if(c.touch0X=i,c.touch0Y=r,c.touch1X=o,c.touch1Y=a,!f(this,ed)){x(this,ed,!0);return}const _=[(i+o)/2,(r+a)/2];(w=f(this,Py))==null||w.call(this,_,b,y)},iN=function(e){var t;e.touches.length>=2||(f(this,$l)&&(f(this,$l).abort(),x(this,$l,null),(t=f(this,Oy))==null||t.call(this)),f(this,Fl)&&(js(e),x(this,Fl,null),x(this,ed,!1)))};let h0=wM;var nd,ea,Os,cs,Hl,jp,_u,Dy,ri,id,Ul,So,Su,Ny,rd,Nr,By,od,Wl,Ha,Vp,Gp,wo,ad,Fy,T0,gt,PT,$y,OT,xS,rN,oN,DT,IS,NT,aN,lN,cN,BT,uN,FT,hN,dN,fN,$T,ev;const bt=class bt{constructor(e){D(this,gt);D(this,nd,null);D(this,ea,null);D(this,Os,null);D(this,cs,null);D(this,Hl,null);D(this,jp,!1);D(this,_u,null);D(this,Dy,"");D(this,ri,null);D(this,id,null);D(this,Ul,null);D(this,So,null);D(this,Su,null);D(this,Ny,"");D(this,rd,!1);D(this,Nr,null);D(this,By,!1);D(this,od,!1);D(this,Wl,!1);D(this,Ha,null);D(this,Vp,0);D(this,Gp,0);D(this,wo,null);D(this,ad,null);_e(this,"isSelected",!1);_e(this,"_isCopy",!1);_e(this,"_editToolbar",null);_e(this,"_initialOptions",Object.create(null));_e(this,"_initialData",null);_e(this,"_isVisible",!0);_e(this,"_uiManager",null);_e(this,"_focusEventsAllowed",!0);D(this,Fy,!1);D(this,T0,bt._zIndex++);this.parent=e.parent,this.id=e.id,this.width=this.height=null,this.pageIndex=e.parent.pageIndex,this.name=e.name,this.div=null,this._uiManager=e.uiManager,this.annotationElementId=null,this._willKeepAspectRatio=!1,this._initialOptions.isCentered=e.isCentered,this._structTreeParentId=null,this.annotationElementId=e.annotationElementId||null,this.creationDate=e.creationDate||new Date,this.modificationDate=e.modificationDate||null,this.canAddComment=!0;const{rotation:t,rawDims:{pageWidth:n,pageHeight:i,pageX:r,pageY:o}}=this.parent.viewport;this.rotation=t,this.pageRotation=(360+t-this._uiManager.viewParameters.rotation)%360,this.pageDimensions=[n,i],this.pageTranslation=[r,o];const[a,c]=this.parentDimensions;this.x=e.x/a,this.y=e.y/c,this.isAttachedToDOM=!1,this.deleted=!1}static get _resizerKeyboardManager(){const e=bt.prototype._resizeWithKeyboard,t=Lf.TRANSLATE_SMALL,n=Lf.TRANSLATE_BIG;return Tt(this,"_resizerKeyboardManager",new r_([[["ArrowLeft","mac+ArrowLeft"],e,{args:[-t,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],e,{args:[-n,0]}],[["ArrowRight","mac+ArrowRight"],e,{args:[t,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],e,{args:[n,0]}],[["ArrowUp","mac+ArrowUp"],e,{args:[0,-t]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],e,{args:[0,-n]}],[["ArrowDown","mac+ArrowDown"],e,{args:[0,t]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],e,{args:[0,n]}],[["Escape","mac+Escape"],bt.prototype._stopResizingWithKeyboard]]))}updatePageIndex(e){this.pageIndex=e}get editorType(){return Object.getPrototypeOf(this).constructor._type}get mode(){return Object.getPrototypeOf(this).constructor._editorType}static get isDrawer(){return!1}static get _defaultLineColor(){return Tt(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(e){const t=new Bee({id:e._uiManager.getId(),parent:e.parent,uiManager:e._uiManager});t.annotationElementId=e.annotationElementId,t.deleted=!0,t._uiManager.addToAnnotationStorage(t)}static initialize(e,t){if(bt._l10n??(bt._l10n=e),bt._l10nAlert??(bt._l10nAlert=Object.freeze({highlight:"pdfjs-editor-highlight-added-alert",freetext:"pdfjs-editor-freetext-added-alert",ink:"pdfjs-editor-ink-added-alert",stamp:"pdfjs-editor-stamp-added-alert",signature:"pdfjs-editor-signature-added-alert"})),bt._l10nResizer??(bt._l10nResizer=Object.freeze({topLeft:"pdfjs-editor-resizer-top-left",topMiddle:"pdfjs-editor-resizer-top-middle",topRight:"pdfjs-editor-resizer-top-right",middleRight:"pdfjs-editor-resizer-middle-right",bottomRight:"pdfjs-editor-resizer-bottom-right",bottomMiddle:"pdfjs-editor-resizer-bottom-middle",bottomLeft:"pdfjs-editor-resizer-bottom-left",middleLeft:"pdfjs-editor-resizer-middle-left"})),bt._borderLineWidth!==-1)return;const n=getComputedStyle(document.documentElement);bt._borderLineWidth=parseFloat(n.getPropertyValue("--outline-width"))||0}static updateDefaultParams(e,t){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(e){return!1}static paste(e,t){es("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return f(this,Fy)}set _isDraggable(e){var t;x(this,Fy,e),(t=this.div)==null||t.classList.toggle("draggable",e)}get uid(){return this.annotationElementId||this.id}get isEnterHandled(){return!0}center(){const[e,t]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*t/(e*2),this.y+=this.width*e/(t*2);break;case 180:this.x+=this.width/2,this.y+=this.height/2;break;case 270:this.x+=this.height*t/(e*2),this.y-=this.width*e/(t*2);break;default:this.x-=this.width/2,this.y-=this.height/2;break}this.fixAndSetPosition()}addCommands(e){this._uiManager.addCommands(e)}get currentLayer(){return this._uiManager.currentLayer}setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=f(this,T0)}setParent(e){var t;e!==null?(this.pageIndex=e.pageIndex,this.pageDimensions=e.pageDimensions):(B(this,gt,ev).call(this),(t=f(this,So))==null||t.remove(),x(this,So,null)),this.parent=e}focusin(e){this._focusEventsAllowed&&(f(this,rd)?x(this,rd,!1):this.parent.setSelected(this))}focusout(e){var n;if(!this._focusEventsAllowed||!this.isAttachedToDOM)return;const t=e.relatedTarget;t!=null&&t.closest(`#${this.id}`)||(e.preventDefault(),(n=this.parent)!=null&&n.isMultipleSelection||this.commitOrRemove())}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.isInEditMode()&&this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(e,t,n,i){const[r,o]=this.parentDimensions;[n,i]=this.screenToPageTranslation(n,i),this.x=(e+n)/r,this.y=(t+i)/o,this.fixAndSetPosition()}_moveAfterPaste(e,t){if(this.isClone){delete this.isClone;return}const[n,i]=this.parentDimensions;this.setAt(e*n,t*i,this.width*n,this.height*i),this._onTranslated()}translate(e,t){B(this,gt,PT).call(this,this.parentDimensions,e,t)}translateInPage(e,t){f(this,Nr)||x(this,Nr,[this.x,this.y,this.width,this.height]),B(this,gt,PT).call(this,this.pageDimensions,e,t),this.div.scrollIntoView({block:"nearest"})}translationDone(){this._onTranslated(this.x,this.y)}drag(e,t){f(this,Nr)||x(this,Nr,[this.x,this.y,this.width,this.height]);const{div:n,parentDimensions:[i,r]}=this;if(this.x+=e/i,this.y+=t/r,this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){const{x:h,y:d}=this.div.getBoundingClientRect();this.parent.findNewParent(this,h,d)&&(this.x-=Math.floor(this.x),this.y-=Math.floor(this.y))}let{x:o,y:a}=this;const[c,l]=this.getBaseTranslation();o+=c,a+=l;const{style:u}=n;u.left=`${(100*o).toFixed(2)}%`,u.top=`${(100*a).toFixed(2)}%`,this._onTranslating(o,a),n.scrollIntoView({block:"nearest"})}_onTranslating(e,t){}_onTranslated(e,t){}get _hasBeenMoved(){return!!f(this,Nr)&&(f(this,Nr)[0]!==this.x||f(this,Nr)[1]!==this.y)}get _hasBeenResized(){return!!f(this,Nr)&&(f(this,Nr)[2]!==this.width||f(this,Nr)[3]!==this.height)}getBaseTranslation(){const[e,t]=this.parentDimensions,{_borderLineWidth:n}=bt,i=n/e,r=n/t;switch(this.rotation){case 90:return[-i,r];case 180:return[i,r];case 270:return[i,-r];default:return[-i,-r]}}get _mustFixPosition(){return!0}fixAndSetPosition(e=this.rotation){const{div:{style:t},pageDimensions:[n,i]}=this;let{x:r,y:o,width:a,height:c}=this;if(a*=n,c*=i,r*=n,o*=i,this._mustFixPosition)switch(e){case 0:r=Ns(r,0,n-a),o=Ns(o,0,i-c);break;case 90:r=Ns(r,0,n-c),o=Ns(o,a,i);break;case 180:r=Ns(r,a,n),o=Ns(o,c,i);break;case 270:r=Ns(r,c,n),o=Ns(o,0,i-a);break}this.x=r/=n,this.y=o/=i;const[l,u]=this.getBaseTranslation();r+=l,o+=u,t.left=`${(100*r).toFixed(2)}%`,t.top=`${(100*o).toFixed(2)}%`,this.moveInDOM()}screenToPageTranslation(e,t){var n;return B(n=bt,$y,OT).call(n,e,t,this.parentRotation)}pageTranslationToScreen(e,t){var n;return B(n=bt,$y,OT).call(n,e,t,360-this.parentRotation)}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){const{parentScale:e,pageDimensions:[t,n]}=this;return[t*e,n*e]}setDims(){const{div:{style:e},width:t,height:n}=this;e.width=`${(100*t).toFixed(2)}%`,e.height=`${(100*n).toFixed(2)}%`}getInitialTranslation(){return[0,0]}_onResized(){}static _round(e){return Math.round(e*1e4)/1e4}_onResizing(){}altTextFinish(){var e;(e=f(this,Os))==null||e.finish()}get toolbarButtons(){return null}async addEditToolbar(){if(this._editToolbar||f(this,od))return this._editToolbar;this._editToolbar=new CT(this),this.div.append(this._editToolbar.render());const{toolbarButtons:e}=this;if(e)for(const[t,n]of e)await this._editToolbar.addButton(t,n);return this.hasComment||this._editToolbar.addButton("comment",this.addCommentButton()),this._editToolbar.addButton("delete"),this._editToolbar}addCommentButtonInToolbar(){var e;(e=this._editToolbar)==null||e.addButtonBefore("comment",this.addCommentButton(),".deleteButton")}removeCommentButtonFromToolbar(){var e;(e=this._editToolbar)==null||e.removeButton("comment")}removeEditToolbar(){var e,t;(e=this._editToolbar)==null||e.remove(),this._editToolbar=null,(t=f(this,Os))==null||t.destroy()}addContainer(e){var n;const t=(n=this._editToolbar)==null?void 0:n.div;t?t.before(e):this.div.append(e)}getClientDimensions(){return this.div.getBoundingClientRect()}createAltText(){return f(this,Os)||(u0.initialize(bt._l10n),x(this,Os,new u0(this)),f(this,nd)&&(f(this,Os).data=f(this,nd),x(this,nd,null))),f(this,Os)}get altTextData(){var e;return(e=f(this,Os))==null?void 0:e.data}set altTextData(e){f(this,Os)&&(f(this,Os).data=e)}get guessedAltText(){var e;return(e=f(this,Os))==null?void 0:e.guessedText}async setGuessedAltText(e){var t;await((t=f(this,Os))==null?void 0:t.setGuessedText(e))}serializeAltText(e){var t;return(t=f(this,Os))==null?void 0:t.serialize(e)}hasAltText(){return!!f(this,Os)&&!f(this,Os).isEmpty()}hasAltTextData(){var e;return((e=f(this,Os))==null?void 0:e.hasData())??!1}focusCommentButton(){var e;(e=f(this,cs))==null||e.focusButton()}addCommentButton(){return this.canAddComment?f(this,cs)||x(this,cs,new V_(this)):null}addStandaloneCommentButton(){if(this._uiManager.hasCommentManager()){if(f(this,Hl)){this._uiManager.isEditingMode()&&f(this,Hl).classList.remove("hidden");return}this.hasComment&&(x(this,Hl,f(this,cs).renderForStandalone()),this.div.append(f(this,Hl)))}}removeStandaloneCommentButton(){f(this,cs).removeStandaloneCommentButton(),x(this,Hl,null)}hideStandaloneCommentButton(){var e;(e=f(this,Hl))==null||e.classList.add("hidden")}get comment(){if(!f(this,cs))return null;const{data:{richText:e,text:t,date:n,deleted:i}}=f(this,cs);return{text:t,richText:e,date:n,deleted:i,color:this.getNonHCMColor(),opacity:this.opacity??1}}set comment(e){f(this,cs)||x(this,cs,new V_(this)),typeof e=="object"&&e!==null?f(this,cs).restoreData(e):f(this,cs).data=e,this.hasComment?(this.removeCommentButtonFromToolbar(),this.addStandaloneCommentButton(),this._uiManager.updateComment(this)):(this.addCommentButtonInToolbar(),this.removeStandaloneCommentButton(),this._uiManager.removeComment(this))}setCommentData({comment:e,popupRef:t,richText:n}){if(!t||(f(this,cs)||x(this,cs,new V_(this)),f(this,cs).setInitialText(e,n),!this.annotationElementId))return;const i=this._uiManager.getAndRemoveDataFromAnnotationStorage(this.annotationElementId);i&&this.updateFromAnnotationLayer(i)}get hasEditedComment(){var e;return(e=f(this,cs))==null?void 0:e.hasBeenEdited()}get hasDeletedComment(){var e;return(e=f(this,cs))==null?void 0:e.isDeleted()}get hasComment(){return!!f(this,cs)&&!f(this,cs).isEmpty()&&!f(this,cs).isDeleted()}async editComment(e){f(this,cs)||x(this,cs,new V_(this)),f(this,cs).edit(e)}toggleComment(e,t=void 0){this.hasComment&&this._uiManager.toggleComment(this,e,t)}setSelectedCommentButton(e){f(this,cs).setSelectedButton(e)}addComment(e){if(this.hasEditedComment){const[,,,i]=e.rect,[r]=this.pageDimensions,[o]=this.pageTranslation,a=o+r+1,c=i-100,l=a+180;e.popup={contents:this.comment.text,deleted:this.comment.deleted,rect:[a,c,l,i]}}}updateFromAnnotationLayer({popup:{contents:e,deleted:t}}){f(this,cs).data=t?null:e}get parentBoundingClientRect(){return this.parent.boundingClientRect}render(){var o;const e=this.div=document.createElement("div");e.setAttribute("data-editor-rotation",(360-this.rotation)%360),e.className=this.name,e.setAttribute("id",this.id),e.tabIndex=f(this,jp)?-1:0,e.setAttribute("role","application"),this.defaultL10nId&&e.setAttribute("data-l10n-id",this.defaultL10nId),this._isVisible||e.classList.add("hidden"),this.setInForeground(),B(this,gt,FT).call(this);const[t,n]=this.parentDimensions;this.parentRotation%180!==0&&(e.style.maxWidth=`${(100*n/t).toFixed(2)}%`,e.style.maxHeight=`${(100*t/n).toFixed(2)}%`);const[i,r]=this.getInitialTranslation();return this.translate(i,r),UD(this,e,["keydown","pointerdown","dblclick"]),this.isResizable&&this._uiManager._supportsPinchToZoom&&(f(this,ad)||x(this,ad,new h0({container:e,isPinchingDisabled:()=>!this.isSelected,onPinchStart:B(this,gt,aN).bind(this),onPinching:B(this,gt,lN).bind(this),onPinchEnd:B(this,gt,cN).bind(this),signal:this._uiManager._signal}))),this.addStandaloneCommentButton(),(o=this._uiManager._editorUndoBar)==null||o.hide(),e}pointerdown(e){const{isMac:t}=Ts.platform;if(e.button!==0||e.ctrlKey&&t){e.preventDefault();return}if(x(this,rd,!0),this._isDraggable){B(this,gt,uN).call(this,e);return}B(this,gt,BT).call(this,e)}_onStartDragging(){}_onStopDragging(){}moveInDOM(){f(this,Ha)&&clearTimeout(f(this,Ha)),x(this,Ha,setTimeout(()=>{var e;x(this,Ha,null),(e=this.parent)==null||e.moveEditorInDOM(this)},0))}_setParentAndPosition(e,t,n){e.changeParent(this),this.x=t,this.y=n,this.fixAndSetPosition(),this._onTranslated()}getRect(e,t,n=this.rotation){const i=this.parentScale,[r,o]=this.pageDimensions,[a,c]=this.pageTranslation,l=e/i,u=t/i,h=this.x*r,d=this.y*o,p=this.width*r,m=this.height*o;switch(n){case 0:return[h+l+a,o-d-u-m+c,h+l+p+a,o-d-u+c];case 90:return[h+u+a,o-d+l+c,h+u+m+a,o-d+l+p+c];case 180:return[h-l-p+a,o-d+u+c,h-l+a,o-d+u+m+c];case 270:return[h-u-m+a,o-d-l-p+c,h-u+a,o-d-l+c];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(e,t){const[n,i,r,o]=e,a=r-n,c=o-i;switch(this.rotation){case 0:return[n,t-o,a,c];case 90:return[n,t-i,c,a];case 180:return[r,t-i,a,c];case 270:return[r,t-o,c,a];default:throw new Error("Invalid rotation")}}getPDFRect(){return this.getRect(0,0)}getNonHCMColor(){return this.color&&bt._colorManager.convert(this._uiManager.getNonHCMColor(this.color))}onUpdatedColor(){var e;(e=f(this,cs))==null||e.onUpdatedColor()}getData(){const{comment:{text:e,color:t,date:n,opacity:i,deleted:r,richText:o},uid:a,pageIndex:c,creationDate:l,modificationDate:u}=this;return{id:a,pageIndex:c,rect:this.getPDFRect(),richText:o,contentsObj:{str:e},creationDate:l,modificationDate:n||u,popupRef:!r,color:t,opacity:i}}onceAdded(e){}isEmpty(){return!1}enableEditMode(){return this.isInEditMode()?!1:(this.parent.setEditingState(!1),x(this,od,!0),!0)}disableEditMode(){return this.isInEditMode()?(this.parent.setEditingState(!0),x(this,od,!1),!0):!1}isInEditMode(){return f(this,od)}shouldGetKeyboardEvents(){return f(this,Wl)}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}get isOnScreen(){const{top:e,left:t,bottom:n,right:i}=this.getClientDimensions(),{innerHeight:r,innerWidth:o}=window;return t<o&&i>0&&e<r&&n>0}rebuild(){B(this,gt,FT).call(this)}rotate(e){}resize(){}serializeDeleted(){var e;return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:((e=this._initialData)==null?void 0:e.popupRef)||""}}serialize(e=!1,t=null){var n;return{annotationType:this.mode,pageIndex:this.pageIndex,rect:this.getPDFRect(),rotation:this.rotation,structTreeParentId:this._structTreeParentId,popupRef:((n=this._initialData)==null?void 0:n.popupRef)||""}}static async deserialize(e,t,n){const i=new this.prototype.constructor({parent:t,id:n.getId(),uiManager:n,annotationElementId:e.annotationElementId,creationDate:e.creationDate,modificationDate:e.modificationDate});i.rotation=e.rotation,x(i,nd,e.accessibilityData),i._isCopy=e.isCopy||!1;const[r,o]=i.pageDimensions,[a,c,l,u]=i.getRectInCurrentCoords(e.rect,o);return i.x=a/r,i.y=c/o,i.width=l/r,i.height=u/o,i}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||this.serialize()!==null)}remove(){var e,t,n;if((e=f(this,Su))==null||e.abort(),x(this,Su,null),this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),this.hideCommentPopup(),f(this,Ha)&&(clearTimeout(f(this,Ha)),x(this,Ha,null)),B(this,gt,ev).call(this),this.removeEditToolbar(),f(this,wo)){for(const i of f(this,wo).values())clearTimeout(i);x(this,wo,null)}this.parent=null,(t=f(this,ad))==null||t.destroy(),x(this,ad,null),(n=f(this,So))==null||n.remove(),x(this,So,null)}get isResizable(){return!1}makeResizable(){this.isResizable&&(B(this,gt,rN).call(this),f(this,ri).classList.remove("hidden"))}get toolbarPosition(){return null}get commentButtonPosition(){return this._uiManager.direction==="ltr"?[1,0]:[0,0]}get commentButtonPositionInPage(){const{commentButtonPosition:[e,t]}=this,[n,i,r,o]=this.getPDFRect();return[bt._round(n+(r-n)*e),bt._round(i+(o-i)*(1-t))]}get commentButtonColor(){return this._uiManager.makeCommentColor(this.getNonHCMColor(),this.opacity)}get commentPopupPosition(){return f(this,cs).commentPopupPositionInLayer}set commentPopupPosition(e){f(this,cs).commentPopupPositionInLayer=e}hasDefaultPopupPosition(){return f(this,cs).hasDefaultPopupPosition()}get commentButtonWidth(){return f(this,cs).commentButtonWidth}get elementBeforePopup(){return this.div}setCommentButtonStates(e){var t;(t=f(this,cs))==null||t.setCommentButtonStates(e)}keydown(e){if(!this.isResizable||e.target!==this.div||e.key!=="Enter")return;this._uiManager.setSelected(this),x(this,Ul,{savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height});const t=f(this,ri).children;if(!f(this,ea)){x(this,ea,Array.from(t));const o=B(this,gt,hN).bind(this),a=B(this,gt,dN).bind(this),c=this._uiManager._signal;for(const l of f(this,ea)){const u=l.getAttribute("data-resizer-name");l.setAttribute("role","spinbutton"),l.addEventListener("keydown",o,{signal:c}),l.addEventListener("blur",a,{signal:c}),l.addEventListener("focus",B(this,gt,fN).bind(this,u),{signal:c}),l.setAttribute("data-l10n-id",bt._l10nResizer[u])}}const n=f(this,ea)[0];let i=0;for(const o of t){if(o===n)break;i++}const r=(360-this.rotation+this.parentRotation)%360/90*(f(this,ea).length/4);if(r!==i){if(r<i)for(let a=0;a<i-r;a++)f(this,ri).append(f(this,ri).firstElementChild);else if(r>i)for(let a=0;a<r-i;a++)f(this,ri).firstElementChild.before(f(this,ri).lastElementChild);let o=0;for(const a of t){const l=f(this,ea)[o++].getAttribute("data-resizer-name");a.setAttribute("data-l10n-id",bt._l10nResizer[l])}}B(this,gt,$T).call(this,0),x(this,Wl,!0),f(this,ri).firstElementChild.focus({focusVisible:!0}),e.preventDefault(),e.stopImmediatePropagation()}_resizeWithKeyboard(e,t){f(this,Wl)&&B(this,gt,NT).call(this,f(this,Ny),{deltaX:e,deltaY:t,fromKeyboard:!0})}_stopResizingWithKeyboard(){B(this,gt,ev).call(this),this.div.focus()}select(){var e,t,n;if(this.isSelected&&this._editToolbar){this._editToolbar.show();return}if(this.isSelected=!0,this.makeResizable(),(e=this.div)==null||e.classList.add("selectedEditor"),!this._editToolbar){this.addEditToolbar().then(()=>{var i,r;(i=this.div)!=null&&i.classList.contains("selectedEditor")&&((r=this._editToolbar)==null||r.show())});return}(t=this._editToolbar)==null||t.show(),(n=f(this,Os))==null||n.toggleAltTextBadge(!1)}focus(){this.div&&!this.div.contains(document.activeElement)&&setTimeout(()=>{var e;return(e=this.div)==null?void 0:e.focus({preventScroll:!0})},0)}unselect(){var e,t,n,i,r;this.isSelected&&(this.isSelected=!1,(e=f(this,ri))==null||e.classList.add("hidden"),(t=this.div)==null||t.classList.remove("selectedEditor"),(n=this.div)!=null&&n.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0}),(i=this._editToolbar)==null||i.hide(),(r=f(this,Os))==null||r.toggleAltTextBadge(!0),this.hideCommentPopup())}hideCommentPopup(){this.hasComment&&this._uiManager.toggleComment(null)}updateParams(e,t){}disableEditing(){}enableEditing(){}get canChangeContent(){return!1}enterInEditMode(){this.canChangeContent&&(this.enableEditMode(),this.div.focus())}dblclick(e){e.target.nodeName!=="BUTTON"&&(this.enterInEditMode(),this.parent.updateToolbar({mode:this.constructor._editorType,editId:this.uid}))}getElementForAltText(){return this.div}get contentDiv(){return this.div}get isEditing(){return f(this,By)}set isEditing(e){x(this,By,e),this.parent&&(e?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}static get MIN_SIZE(){return 16}static canCreateNewEmptyEditor(){return!0}get telemetryInitialData(){return{action:"added"}}get telemetryFinalData(){return null}_reportTelemetry(e,t=!1){if(t){f(this,wo)||x(this,wo,new Map);const{action:n}=e;let i=f(this,wo).get(n);i&&clearTimeout(i),i=setTimeout(()=>{this._reportTelemetry(e),f(this,wo).delete(n),f(this,wo).size===0&&x(this,wo,null)},bt._telemetryTimeout),f(this,wo).set(n,i);return}e.type||(e.type=this.editorType),this._uiManager._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:e}})}show(e=this._isVisible){this.div.classList.toggle("hidden",!e),this._isVisible=e}enable(){this.div&&(this.div.tabIndex=0),x(this,jp,!1)}disable(){this.div&&(this.div.tabIndex=-1),x(this,jp,!0)}updateFakeAnnotationElement(e){if(!f(this,So)&&!this.deleted){x(this,So,e.addFakeAnnotation(this));return}if(this.deleted){f(this,So).remove(),x(this,So,null);return}(this.hasEditedComment||this._hasBeenMoved||this._hasBeenResized)&&f(this,So).updateEdited({rect:this.getPDFRect(),popup:this.comment})}renderAnnotationElement(e){if(this.deleted)return e.hide(),null;let t=e.container.querySelector(".annotationContent");if(!t)t=document.createElement("div"),t.classList.add("annotationContent",this.editorType),e.container.prepend(t);else if(t.nodeName==="CANVAS"){const n=t;t=document.createElement("div"),t.classList.add("annotationContent",this.editorType),n.before(t)}return t}resetAnnotationElement(e){const{firstElementChild:t}=e.container;(t==null?void 0:t.nodeName)==="DIV"&&t.classList.contains("annotationContent")&&t.remove()}};nd=new WeakMap,ea=new WeakMap,Os=new WeakMap,cs=new WeakMap,Hl=new WeakMap,jp=new WeakMap,_u=new WeakMap,Dy=new WeakMap,ri=new WeakMap,id=new WeakMap,Ul=new WeakMap,So=new WeakMap,Su=new WeakMap,Ny=new WeakMap,rd=new WeakMap,Nr=new WeakMap,By=new WeakMap,od=new WeakMap,Wl=new WeakMap,Ha=new WeakMap,Vp=new WeakMap,Gp=new WeakMap,wo=new WeakMap,ad=new WeakMap,Fy=new WeakMap,T0=new WeakMap,gt=new WeakSet,PT=function([e,t],n,i){[n,i]=this.screenToPageTranslation(n,i),this.x+=n/e,this.y+=i/t,this._onTranslating(this.x,this.y),this.fixAndSetPosition()},$y=new WeakSet,OT=function(e,t,n){switch(n){case 90:return[t,-e];case 180:return[-e,-t];case 270:return[-t,e];default:return[e,t]}},xS=function(e){switch(e){case 90:{const[t,n]=this.pageDimensions;return[0,-t/n,n/t,0]}case 180:return[-1,0,0,-1];case 270:{const[t,n]=this.pageDimensions;return[0,t/n,-n/t,0]}default:return[1,0,0,1]}},rN=function(){if(f(this,ri))return;x(this,ri,document.createElement("div")),f(this,ri).classList.add("resizers");const e=this._willKeepAspectRatio?["topLeft","topRight","bottomRight","bottomLeft"]:["topLeft","topMiddle","topRight","middleRight","bottomRight","bottomMiddle","bottomLeft","middleLeft"],t=this._uiManager._signal;for(const n of e){const i=document.createElement("div");f(this,ri).append(i),i.classList.add("resizer",n),i.setAttribute("data-resizer-name",n),i.addEventListener("pointerdown",B(this,gt,oN).bind(this,n),{signal:t}),i.addEventListener("contextmenu",Ho,{signal:t}),i.tabIndex=-1}this.div.prepend(f(this,ri))},oN=function(e,t){var u;t.preventDefault();const{isMac:n}=Ts.platform;if(t.button!==0||t.ctrlKey&&n)return;(u=f(this,Os))==null||u.toggle(!1);const i=this._isDraggable;this._isDraggable=!1,x(this,id,[t.screenX,t.screenY]);const r=new AbortController,o=this._uiManager.combinedSignal(r);this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",B(this,gt,NT).bind(this,e),{passive:!0,capture:!0,signal:o}),window.addEventListener("touchmove",js,{passive:!1,signal:o}),window.addEventListener("contextmenu",Ho,{signal:o}),x(this,Ul,{savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height});const a=this.parent.div.style.cursor,c=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(t.target).cursor;const l=()=>{var h;r.abort(),this.parent.togglePointerEvents(!0),(h=f(this,Os))==null||h.toggle(!0),this._isDraggable=i,this.parent.div.style.cursor=a,this.div.style.cursor=c,B(this,gt,IS).call(this)};window.addEventListener("pointerup",l,{signal:o}),window.addEventListener("blur",l,{signal:o})},DT=function(e,t,n,i){this.width=n,this.height=i,this.x=e,this.y=t,this.setDims(),this.fixAndSetPosition(),this._onResized()},IS=function(){if(!f(this,Ul))return;const{savedX:e,savedY:t,savedWidth:n,savedHeight:i}=f(this,Ul);x(this,Ul,null);const r=this.x,o=this.y,a=this.width,c=this.height;r===e&&o===t&&a===n&&c===i||this.addCommands({cmd:B(this,gt,DT).bind(this,r,o,a,c),undo:B(this,gt,DT).bind(this,e,t,n,i),mustExec:!0})},NT=function(e,t){const[n,i]=this.parentDimensions,r=this.x,o=this.y,a=this.width,c=this.height,l=bt.MIN_SIZE/n,u=bt.MIN_SIZE/i,h=B(this,gt,xS).call(this,this.rotation),d=(W,V)=>[h[0]*W+h[2]*V,h[1]*W+h[3]*V],p=B(this,gt,xS).call(this,360-this.rotation),m=(W,V)=>[p[0]*W+p[2]*V,p[1]*W+p[3]*V];let v,g,y=!1,b=!1;switch(e){case"topLeft":y=!0,v=(W,V)=>[0,0],g=(W,V)=>[W,V];break;case"topMiddle":v=(W,V)=>[W/2,0],g=(W,V)=>[W/2,V];break;case"topRight":y=!0,v=(W,V)=>[W,0],g=(W,V)=>[0,V];break;case"middleRight":b=!0,v=(W,V)=>[W,V/2],g=(W,V)=>[0,V/2];break;case"bottomRight":y=!0,v=(W,V)=>[W,V],g=(W,V)=>[0,0];break;case"bottomMiddle":v=(W,V)=>[W/2,V],g=(W,V)=>[W/2,0];break;case"bottomLeft":y=!0,v=(W,V)=>[0,V],g=(W,V)=>[W,0];break;case"middleLeft":b=!0,v=(W,V)=>[0,V/2],g=(W,V)=>[W,V/2];break}const _=v(a,c),w=g(a,c);let S=d(...w);const C=bt._round(r+S[0]),T=bt._round(o+S[1]);let k=1,A=1,M,R;if(t.fromKeyboard)({deltaX:M,deltaY:R}=t);else{const{screenX:W,screenY:V}=t,[N,O]=f(this,id);[M,R]=this.screenToPageTranslation(W-N,V-O),f(this,id)[0]=W,f(this,id)[1]=V}if([M,R]=m(M/n,R/i),y){const W=Math.hypot(a,c);k=A=Math.max(Math.min(Math.hypot(w[0]-_[0]-M,w[1]-_[1]-R)/W,1/a,1/c),l/a,u/c)}else b?k=Ns(Math.abs(w[0]-_[0]-M),l,1)/a:A=Ns(Math.abs(w[1]-_[1]-R),u,1)/c;const P=bt._round(a*k),L=bt._round(c*A);S=d(...g(P,L));const z=C-S[0],Q=T-S[1];f(this,Nr)||x(this,Nr,[this.x,this.y,this.width,this.height]),this.width=P,this.height=L,this.x=z,this.y=Q,this.setDims(),this.fixAndSetPosition(),this._onResizing()},aN=function(){var e;x(this,Ul,{savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height}),(e=f(this,Os))==null||e.toggle(!1),this.parent.togglePointerEvents(!1)},lN=function(e,t,n){let r=.7*(n/t)+1-.7;if(r===1)return;const o=B(this,gt,xS).call(this,this.rotation),a=(C,T)=>[o[0]*C+o[2]*T,o[1]*C+o[3]*T],[c,l]=this.parentDimensions,u=this.x,h=this.y,d=this.width,p=this.height,m=bt.MIN_SIZE/c,v=bt.MIN_SIZE/l;r=Math.max(Math.min(r,1/d,1/p),m/d,v/p);const g=bt._round(d*r),y=bt._round(p*r);if(g===d&&y===p)return;f(this,Nr)||x(this,Nr,[u,h,d,p]);const b=a(d/2,p/2),_=bt._round(u+b[0]),w=bt._round(h+b[1]),S=a(g/2,y/2);this.x=_-S[0],this.y=w-S[1],this.width=g,this.height=y,this.setDims(),this.fixAndSetPosition(),this._onResizing()},cN=function(){var e;(e=f(this,Os))==null||e.toggle(!0),this.parent.togglePointerEvents(!0),B(this,gt,IS).call(this)},BT=function(e){const{isMac:t}=Ts.platform;e.ctrlKey&&!t||e.shiftKey||e.metaKey&&t?this.parent.toggleSelected(this):this.parent.setSelected(this)},uN=function(e){const{isSelected:t}=this;this._uiManager.setUpDragSession();let n=!1;const i=new AbortController,r=this._uiManager.combinedSignal(i),o={capture:!0,passive:!1,signal:r},a=l=>{i.abort(),x(this,_u,null),x(this,rd,!1),this._uiManager.endDragSession()||B(this,gt,BT).call(this,l),n&&this._onStopDragging()};t&&(x(this,Vp,e.clientX),x(this,Gp,e.clientY),x(this,_u,e.pointerId),x(this,Dy,e.pointerType),window.addEventListener("pointermove",l=>{n||(n=!0,this._uiManager.toggleComment(this,!0,!1),this._onStartDragging());const{clientX:u,clientY:h,pointerId:d}=l;if(d!==f(this,_u)){js(l);return}const[p,m]=this.screenToPageTranslation(u-f(this,Vp),h-f(this,Gp));x(this,Vp,u),x(this,Gp,h),this._uiManager.dragSelectedEditors(p,m)},o),window.addEventListener("touchmove",js,o),window.addEventListener("pointerdown",l=>{l.pointerType===f(this,Dy)&&(f(this,ad)||l.isPrimary)&&a(l),js(l)},o));const c=l=>{if(!f(this,_u)||f(this,_u)===l.pointerId){a(l);return}js(l)};window.addEventListener("pointerup",c,{signal:r}),window.addEventListener("blur",c,{signal:r})},FT=function(){if(f(this,Su)||!this.div)return;x(this,Su,new AbortController);const e=this._uiManager.combinedSignal(f(this,Su));this.div.addEventListener("focusin",this.focusin.bind(this),{signal:e}),this.div.addEventListener("focusout",this.focusout.bind(this),{signal:e})},hN=function(e){bt._resizerKeyboardManager.exec(this,e)},dN=function(e){var t;f(this,Wl)&&((t=e.relatedTarget)==null?void 0:t.parentNode)!==f(this,ri)&&B(this,gt,ev).call(this)},fN=function(e){x(this,Ny,f(this,Wl)?e:"")},$T=function(e){if(f(this,ea))for(const t of f(this,ea))t.tabIndex=e},ev=function(){x(this,Wl,!1),B(this,gt,$T).call(this,-1),B(this,gt,IS).call(this)},D(bt,$y),_e(bt,"_l10n",null),_e(bt,"_l10nAlert",null),_e(bt,"_l10nResizer",null),_e(bt,"_borderLineWidth",-1),_e(bt,"_colorManager",new ET),_e(bt,"_zIndex",1),_e(bt,"_telemetryTimeout",1e3);let is=bt;class Bee extends is{constructor(e){super(e),this.annotationElementId=e.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}}const vR=3285377520,co=4294901760,Ca=65535;class HT{constructor(e){this.h1=e?e&4294967295:vR,this.h2=e?e&4294967295:vR}update(e){let t,n;if(typeof e=="string"){t=new Uint8Array(e.length*2),n=0;for(let v=0,g=e.length;v<g;v++){const y=e.charCodeAt(v);y<=255?t[n++]=y:(t[n++]=y>>>8,t[n++]=y&255)}}else if(ArrayBuffer.isView(e))t=e.slice(),n=t.byteLength;else throw new Error("Invalid data format, must be a string or TypedArray.");const i=n>>2,r=n-i*4,o=new Uint32Array(t.buffer,0,i);let a=0,c=0,l=this.h1,u=this.h2;const h=3432918353,d=461845907,p=h&Ca,m=d&Ca;for(let v=0;v<i;v++)v&1?(a=o[v],a=a*h&co|a*p&Ca,a=a<<15|a>>>17,a=a*d&co|a*m&Ca,l^=a,l=l<<13|l>>>19,l=l*5+3864292196):(c=o[v],c=c*h&co|c*p&Ca,c=c<<15|c>>>17,c=c*d&co|c*m&Ca,u^=c,u=u<<13|u>>>19,u=u*5+3864292196);switch(a=0,r){case 3:a^=t[i*4+2]<<16;case 2:a^=t[i*4+1]<<8;case 1:a^=t[i*4],a=a*h&co|a*p&Ca,a=a<<15|a>>>17,a=a*d&co|a*m&Ca,i&1?l^=a:u^=a}this.h1=l,this.h2=u}hexdigest(){let e=this.h1,t=this.h2;return e^=t>>>1,e=e*3981806797&co|e*36045&Ca,t=t*4283543511&co|((t<<16|e>>>16)*2950163797&co)>>>16,e^=t>>>1,e=e*444984403&co|e*60499&Ca,t=t*3301882366&co|((t<<16|e>>>16)*3120437893&co)>>>16,e^=t>>>1,(e>>>0).toString(16).padStart(8,"0")+(t>>>0).toString(16).padStart(8,"0")}}const ly=Object.freeze({map:null,hash:"",transfer:void 0});var ld,cd,zl,oi,A0,pN;class dM{constructor(){D(this,A0);D(this,ld,!1);D(this,cd,null);D(this,zl,null);D(this,oi,new Map);_e(this,"onSetModified",null);_e(this,"onResetModified",null);_e(this,"onAnnotationEditor",null)}getValue(e,t){const n=f(this,oi).get(e);return n===void 0?t:Object.assign(t,n)}getRawValue(e){return f(this,oi).get(e)}remove(e){var n;const t=f(this,oi).get(e);t!==void 0&&(t instanceof is&&f(this,zl).delete(t.annotationElementId),f(this,oi).delete(e),f(this,oi).size===0&&this.resetModified(),!f(this,oi).values().some(i=>i instanceof is)&&((n=this.onAnnotationEditor)==null||n.call(this,null)))}setValue(e,t){var r;const n=f(this,oi).get(e);let i=!1;if(n!==void 0)for(const[o,a]of Object.entries(t))n[o]!==a&&(i=!0,n[o]=a);else i=!0,f(this,oi).set(e,t);i&&B(this,A0,pN).call(this),t instanceof is&&((f(this,zl)||x(this,zl,new Map)).set(t.annotationElementId,t),(r=this.onAnnotationEditor)==null||r.call(this,t.constructor._type))}has(e){return f(this,oi).has(e)}get size(){return f(this,oi).size}resetModified(){var e;f(this,ld)&&(x(this,ld,!1),(e=this.onResetModified)==null||e.call(this))}get print(){return new gN(this)}get serializable(){if(f(this,oi).size===0)return ly;const e=new Map,t=new HT,n=[],i=Object.create(null);let r=!1;for(const[o,a]of f(this,oi)){const c=a instanceof is?a.serialize(!1,i):a;a.page&&(a.pageIndex=a.page._pageIndex,delete a.page),c&&(e.set(o,c),t.update(`${o}:${JSON.stringify(c)}`),r||(r=!!c.bitmap))}if(r)for(const o of e.values())o.bitmap&&n.push(o.bitmap);return e.size>0?{map:e,hash:t.hexdigest(),transfer:n}:ly}get editorStats(){let e=null;const t=new Map;let n=0,i=0;for(const r of f(this,oi).values()){if(!(r instanceof is)){r.popup&&(r.popup.deleted?i+=1:n+=1);continue}r.isCommentDeleted?i+=1:r.hasEditedComment&&(n+=1);const o=r.telemetryFinalData;if(!o)continue;const{type:a}=o;t.has(a)||t.set(a,Object.getPrototypeOf(r).constructor),e||(e=Object.create(null));const c=e[a]||(e[a]=new Map);for(const[l,u]of Object.entries(o)){if(l==="type")continue;const h=c.getOrInsertComputed(l,lM);h.set(u,(h.get(u)??0)+1)}}if((i>0||n>0)&&(e||(e=Object.create(null)),e.comments={deleted:i,edited:n}),!e)return null;for(const[r,o]of t)e[r]=o.computeTelemetryFinalData(e[r]);return e}resetModifiedIds(){x(this,cd,null)}updateEditor(e,t){var i;const n=(i=f(this,zl))==null?void 0:i.get(e);return n?(n.updateFromAnnotationLayer(t),!0):!1}getEditor(e){var t;return((t=f(this,zl))==null?void 0:t.get(e))||null}get modifiedIds(){if(f(this,cd))return f(this,cd);const e=[];if(f(this,zl))for(const n of f(this,zl).values())n.serialize()&&e.push(n.annotationElementId);let t="";if(e.length){const n=new HT;n.update(e.join(",")),t=n.hexdigest()}return x(this,cd,{ids:new Set(e),hash:t})}[Symbol.iterator](){return f(this,oi).entries()}}ld=new WeakMap,cd=new WeakMap,zl=new WeakMap,oi=new WeakMap,A0=new WeakSet,pN=function(){var e;f(this,ld)||(x(this,ld,!0),(e=this.onSetModified)==null||e.call(this))};var Hy;class gN extends dM{constructor(t){super();D(this,Hy,ly);const{serializable:n}=t;if(n===ly)return;const{map:i,hash:r,transfer:o}=n,a=structuredClone(i,o?{transfer:o}:null);x(this,Hy,{map:a,hash:r,transfer:[]})}get print(){es("Should not call PrintAnnotationStorage.print")}get serializable(){return f(this,Hy)}get modifiedIds(){return Tt(this,"modifiedIds",{ids:new Set,hash:""})}}Hy=new WeakMap;St(7588);const Zf="__forcedDependency",{floor:yR,ceil:bR}=Math;function _R(s,e,t,n,i,r){s[e*4+0]=Math.min(s[e*4+0],t),s[e*4+1]=Math.min(s[e*4+1],n),s[e*4+2]=Math.max(s[e*4+2],i),s[e*4+3]=Math.max(s[e*4+3],r)}function Fee(s,e,t,n,i){let r;s?(s<0&&(r=i[0],i[0]=i[2],i[2]=r),i[0]*=s,i[2]*=s,e<0&&(r=i[1],i[1]=i[3],i[3]=r),i[1]*=e,i[3]*=e):i.fill(0),i[0]+=t,i[1]+=n,i[2]+=t,i[3]+=n}const UT=new Uint32Array(new Uint8Array([255,255,0,0]).buffer)[0];var qp,wu;class $ee{constructor(e,t){D(this,qp);D(this,wu);x(this,qp,e),x(this,wu,t)}get length(){return f(this,qp).length}isEmpty(e){return f(this,qp)[e]===UT}minX(e){return f(this,wu)[e*4+0]/256}minY(e){return f(this,wu)[e*4+1]/256}maxX(e){return(f(this,wu)[e*4+2]+1)/256}maxY(e){return(f(this,wu)[e*4+3]+1)/256}}qp=new WeakMap,wu=new WeakMap;const SR=(s,e)=>s==null?void 0:s.getOrInsertComputed(e,()=>({dependencies:new Set,isRenderingOperation:!1}));var jl,ss,Rs,ud,hd,dd,ki,Uy,WT;class Hee{constructor(e,t){D(this,Uy);D(this,jl,[[1,0,0,1,0,0]]);D(this,ss,[-1/0,-1/0,1/0,1/0]);D(this,Rs,new Float64Array(gc));_e(this,"_pendingBBoxIdx",-1);D(this,ud);D(this,hd);D(this,dd);D(this,ki);_e(this,"_savesStack",[]);_e(this,"_markedContentStack",[]);x(this,ud,e.width),x(this,hd,e.height),B(this,Uy,WT).call(this,t)}growOperationsCount(e){e>=f(this,ki).length&&B(this,Uy,WT).call(this,e,f(this,ki))}get clipBox(){return f(this,ss)}save(e){return x(this,ss,{__proto__:f(this,ss)}),this._savesStack.push(e),this}restore(e,t){const n=Object.getPrototypeOf(f(this,ss));if(n===null)return this;x(this,ss,n);const i=this._savesStack.pop();return i!==void 0&&(t==null||t(i,e),f(this,ki)[e]=f(this,ki)[i]),this}recordOpenMarker(e){return this._savesStack.push(e),this}getOpenMarker(){return this._savesStack.length===0?null:this._savesStack.at(-1)}recordCloseMarker(e,t){const n=this._savesStack.pop();return n!==void 0&&(t==null||t(n,e),f(this,ki)[e]=f(this,ki)[n]),this}beginMarkedContent(e){return this._markedContentStack.push(e),this}endMarkedContent(e,t){const n=this._markedContentStack.pop();return n!==void 0&&(t==null||t(n,e),f(this,ki)[e]=f(this,ki)[n]),this}pushBaseTransform(e){return f(this,jl).push(Be.multiplyByDOMMatrix(f(this,jl).at(-1),e.getTransform())),this}popBaseTransform(){return f(this,jl).length>1&&f(this,jl).pop(),this}resetBBox(e){return this._pendingBBoxIdx!==e&&(this._pendingBBoxIdx=e,f(this,Rs).set(gc,0)),this}recordClipBox(e,t,n,i,r,o){const a=Be.multiplyByDOMMatrix(f(this,jl).at(-1),t.getTransform()),c=gc.slice();Be.axialAlignedBoundingBox([n,r,i,o],a,c);const l=Be.intersect(f(this,ss),c);return l?(f(this,ss)[0]=l[0],f(this,ss)[1]=l[1],f(this,ss)[2]=l[2],f(this,ss)[3]=l[3]):(f(this,ss)[0]=f(this,ss)[1]=1/0,f(this,ss)[2]=f(this,ss)[3]=-1/0),this}recordBBox(e,t,n,i,r,o){const a=f(this,ss);if(a[0]===1/0)return this;const c=Be.multiplyByDOMMatrix(f(this,jl).at(-1),t.getTransform());if(a[0]===-1/0)return Be.axialAlignedBoundingBox([n,r,i,o],c,f(this,Rs)),this;const l=gc.slice();return Be.axialAlignedBoundingBox([n,r,i,o],c,l),f(this,Rs)[0]=Ns(l[0],a[0],f(this,Rs)[0]),f(this,Rs)[1]=Ns(l[1],a[1],f(this,Rs)[1]),f(this,Rs)[2]=Ns(l[2],f(this,Rs)[2],a[2]),f(this,Rs)[3]=Ns(l[3],f(this,Rs)[3],a[3]),this}recordFullPageBBox(e){return f(this,Rs)[0]=Math.max(0,f(this,ss)[0]),f(this,Rs)[1]=Math.max(0,f(this,ss)[1]),f(this,Rs)[2]=Math.min(f(this,ud),f(this,ss)[2]),f(this,Rs)[3]=Math.min(f(this,hd),f(this,ss)[3]),this}recordOperation(e,t=!1,n){if(this._pendingBBoxIdx!==e)return this;const i=yR(f(this,Rs)[0]*256/f(this,ud)),r=yR(f(this,Rs)[1]*256/f(this,hd)),o=bR(f(this,Rs)[2]*256/f(this,ud)),a=bR(f(this,Rs)[3]*256/f(this,hd));if(_R(f(this,dd),e,i,r,o,a),n)for(const c of n)for(const l of c)l!==e&&_R(f(this,dd),l,i,r,o,a);return t||(this._pendingBBoxIdx=-1),this}bboxToClipBoxDropOperation(e){return this._pendingBBoxIdx===e&&(this._pendingBBoxIdx=-1,f(this,ss)[0]=Math.max(f(this,ss)[0],f(this,Rs)[0]),f(this,ss)[1]=Math.max(f(this,ss)[1],f(this,Rs)[1]),f(this,ss)[2]=Math.min(f(this,ss)[2],f(this,Rs)[2]),f(this,ss)[3]=Math.min(f(this,ss)[3],f(this,Rs)[3])),this}take(){return new $ee(f(this,ki),f(this,dd))}takeDebugMetadata(){throw new Error("Unreachable")}recordSimpleData(e,t){return this}recordIncrementalData(e,t){return this}resetIncrementalData(e,t){return this}recordNamedData(e,t){return this}recordSimpleDataFromNamed(e,t,n){return this}recordFutureForcedDependency(e,t){return this}inheritSimpleDataAsFutureForcedDependencies(e){return this}inheritPendingDependenciesAsFutureForcedDependencies(){return this}recordCharacterBBox(e,t,n,i=1,r=0,o=0,a){return this}getSimpleIndex(e){}recordDependencies(e,t){return this}recordNamedDependency(e,t){return this}recordShowTextOperation(e,t=!1){return this}}jl=new WeakMap,ss=new WeakMap,Rs=new WeakMap,ud=new WeakMap,hd=new WeakMap,dd=new WeakMap,ki=new WeakMap,Uy=new WeakSet,WT=function(e,t){const n=new ArrayBuffer(e*4);x(this,dd,new Uint8ClampedArray(n)),x(this,ki,new Uint32Array(n)),t&&t.length>0?(f(this,ki).set(t),f(this,ki).fill(UT,t.length)):f(this,ki).fill(UT)};var cr,ur,fd,ta,Kp,ku,Cu,fs;class Uee{constructor(e,t=!1){D(this,cr,{__proto__:null});D(this,ur,{__proto__:null,transform:[],moveText:[],sameLineText:[],[Zf]:[]});D(this,fd,new Map);D(this,ta,new Set);D(this,Kp,new Map);D(this,ku);D(this,Cu);D(this,fs);x(this,fs,e),t&&(x(this,ku,new Map),x(this,Cu,(n,i)=>{SR(f(this,ku),i).dependencies.add(n)}))}get clipBox(){return f(this,fs).clipBox}growOperationsCount(e){f(this,fs).growOperationsCount(e)}save(e){return x(this,cr,{__proto__:f(this,cr)}),x(this,ur,{__proto__:f(this,ur),transform:{__proto__:f(this,ur).transform},moveText:{__proto__:f(this,ur).moveText},sameLineText:{__proto__:f(this,ur).sameLineText},[Zf]:{__proto__:f(this,ur)[Zf]}}),f(this,fs).save(e),this}restore(e){f(this,fs).restore(e,f(this,Cu));const t=Object.getPrototypeOf(f(this,cr));return t===null?this:(x(this,cr,t),x(this,ur,Object.getPrototypeOf(f(this,ur))),this)}recordOpenMarker(e){return f(this,fs).recordOpenMarker(e,f(this,Cu)),this}getOpenMarker(){return f(this,fs).getOpenMarker()}recordCloseMarker(e){return f(this,fs).recordCloseMarker(e,f(this,Cu)),this}beginMarkedContent(e){return f(this,fs).beginMarkedContent(e),this}endMarkedContent(e){return f(this,fs).endMarkedContent(e,f(this,Cu)),this}pushBaseTransform(e){return f(this,fs).pushBaseTransform(e),this}popBaseTransform(){return f(this,fs).popBaseTransform(),this}recordSimpleData(e,t){return f(this,cr)[e]=t,this}recordIncrementalData(e,t){return f(this,ur)[e].push(t),this}resetIncrementalData(e,t){return f(this,ur)[e].length=0,this}recordNamedData(e,t){return f(this,fd).set(e,t),this}recordSimpleDataFromNamed(e,t,n){f(this,cr)[e]=f(this,fd).get(t)??n}recordFutureForcedDependency(e,t){return this.recordIncrementalData(Zf,t),this}inheritSimpleDataAsFutureForcedDependencies(e){for(const t of e)t in f(this,cr)&&this.recordFutureForcedDependency(t,f(this,cr)[t]);return this}inheritPendingDependenciesAsFutureForcedDependencies(){for(const e of f(this,ta))this.recordFutureForcedDependency(Zf,e);return this}resetBBox(e){return f(this,fs).resetBBox(e),this}recordClipBox(e,t,n,i,r,o){return f(this,fs).recordClipBox(e,t,n,i,r,o),this}recordBBox(e,t,n,i,r,o){return f(this,fs).recordBBox(e,t,n,i,r,o),this}recordCharacterBBox(e,t,n,i=1,r=0,o=0,a){const c=n.bbox;let l,u;if(c&&(l=c[2]!==c[0]&&c[3]!==c[1]&&f(this,Kp).get(n),l!==!1&&(u=[0,0,0,0],Be.axialAlignedBoundingBox(c,n.fontMatrix,u),(i!==1||r!==0||o!==0)&&Fee(i,-i,r,o,u),l)))return this.recordBBox(e,t,u[0],u[2],u[1],u[3]);if(!a)return this.recordFullPageBBox(e);const h=a();return c&&u&&l===void 0&&(l=u[0]<=r-h.actualBoundingBoxLeft&&u[2]>=r+h.actualBoundingBoxRight&&u[1]<=o-h.actualBoundingBoxAscent&&u[3]>=o+h.actualBoundingBoxDescent,f(this,Kp).set(n,l),l)?this.recordBBox(e,t,u[0],u[2],u[1],u[3]):this.recordBBox(e,t,r-h.actualBoundingBoxLeft,r+h.actualBoundingBoxRight,o-h.actualBoundingBoxAscent,o+h.actualBoundingBoxDescent)}recordFullPageBBox(e){return f(this,fs).recordFullPageBBox(e),this}getSimpleIndex(e){return f(this,cr)[e]}recordDependencies(e,t){const n=f(this,ta),i=f(this,cr),r=f(this,ur);for(const o of t)o in f(this,cr)?n.add(i[o]):o in r&&r[o].forEach(n.add,n);return this}recordNamedDependency(e,t){return f(this,fd).has(t)&&f(this,ta).add(f(this,fd).get(t)),this}recordOperation(e,t=!1){if(this.recordDependencies(e,[Zf]),f(this,ku)){const i=SR(f(this,ku),e),{dependencies:r}=i;f(this,ta).forEach(r.add,r),f(this,fs)._savesStack.forEach(r.add,r),f(this,fs)._markedContentStack.forEach(r.add,r),r.delete(e),i.isRenderingOperation=!0}const n=!t&&e===f(this,fs)._pendingBBoxIdx;return f(this,fs).recordOperation(e,t,[f(this,ta),f(this,fs)._savesStack,f(this,fs)._markedContentStack]),n&&f(this,ta).clear(),this}recordShowTextOperation(e,t=!1){const n=Array.from(f(this,ta));this.recordOperation(e,t),this.recordIncrementalData("sameLineText",e);for(const i of n)this.recordIncrementalData("sameLineText",i);return this}bboxToClipBoxDropOperation(e,t=!1){const n=!t&&e===f(this,fs)._pendingBBoxIdx;return f(this,fs).bboxToClipBoxDropOperation(e),n&&f(this,ta).clear(),this}take(){return f(this,Kp).clear(),f(this,fs).take()}takeDebugMetadata(){return f(this,ku)}}cr=new WeakMap,ur=new WeakMap,fd=new WeakMap,ta=new WeakMap,Kp=new WeakMap,ku=new WeakMap,Cu=new WeakMap,fs=new WeakMap;var ps,tn,sa,Qp,Xp;const kM=class kM{constructor(e,t,n){D(this,ps);D(this,tn);D(this,sa);D(this,Qp,0);D(this,Xp,0);if(e instanceof kM&&f(e,sa)===!!n)return e;x(this,ps,e),x(this,tn,t),x(this,sa,!!n)}get clipBox(){return f(this,ps).clipBox}growOperationsCount(){throw new Error("Unreachable")}save(e){return xs(this,Xp)._++,f(this,ps).save(f(this,tn)),this}restore(e){return f(this,Xp)>0&&(f(this,ps).restore(f(this,tn)),xs(this,Xp)._--),this}recordOpenMarker(e){return xs(this,Qp)._++,this}getOpenMarker(){return f(this,Qp)>0?f(this,tn):f(this,ps).getOpenMarker()}recordCloseMarker(e){return xs(this,Qp)._--,this}beginMarkedContent(e){return this}endMarkedContent(e){return this}pushBaseTransform(e){return f(this,ps).pushBaseTransform(e),this}popBaseTransform(){return f(this,ps).popBaseTransform(),this}recordSimpleData(e,t){return f(this,ps).recordSimpleData(e,f(this,tn)),this}recordIncrementalData(e,t){return f(this,ps).recordIncrementalData(e,f(this,tn)),this}resetIncrementalData(e,t){return f(this,ps).resetIncrementalData(e,f(this,tn)),this}recordNamedData(e,t){return this}recordSimpleDataFromNamed(e,t,n){return f(this,ps).recordSimpleDataFromNamed(e,t,f(this,tn)),this}recordFutureForcedDependency(e,t){return f(this,ps).recordFutureForcedDependency(e,f(this,tn)),this}inheritSimpleDataAsFutureForcedDependencies(e){return f(this,ps).inheritSimpleDataAsFutureForcedDependencies(e),this}inheritPendingDependenciesAsFutureForcedDependencies(){return f(this,ps).inheritPendingDependenciesAsFutureForcedDependencies(),this}resetBBox(e){return f(this,sa)||f(this,ps).resetBBox(f(this,tn)),this}recordClipBox(e,t,n,i,r,o){return f(this,sa)||f(this,ps).recordClipBox(f(this,tn),t,n,i,r,o),this}recordBBox(e,t,n,i,r,o){return f(this,sa)||f(this,ps).recordBBox(f(this,tn),t,n,i,r,o),this}recordCharacterBBox(e,t,n,i,r,o,a){return f(this,sa)||f(this,ps).recordCharacterBBox(f(this,tn),t,n,i,r,o,a),this}recordFullPageBBox(e){return f(this,sa)||f(this,ps).recordFullPageBBox(f(this,tn)),this}getSimpleIndex(e){return f(this,ps).getSimpleIndex(e)}recordDependencies(e,t){return f(this,ps).recordDependencies(f(this,tn),t),this}recordNamedDependency(e,t){return f(this,ps).recordNamedDependency(f(this,tn),t),this}recordOperation(e){return f(this,ps).recordOperation(f(this,tn),!0),this}recordShowTextOperation(e){return f(this,ps).recordShowTextOperation(f(this,tn),!0),this}bboxToClipBoxDropOperation(e){return f(this,sa)||f(this,ps).bboxToClipBoxDropOperation(f(this,tn),!0),this}take(){throw new Error("Unreachable")}takeDebugMetadata(){throw new Error("Unreachable")}};ps=new WeakMap,tn=new WeakMap,sa=new WeakMap,Qp=new WeakMap,Xp=new WeakMap;let cy=kM;const uo={stroke:["path","transform","filter","strokeColor","strokeAlpha","lineWidth","lineCap","lineJoin","miterLimit","dash"],fill:["path","transform","filter","fillColor","fillAlpha","globalCompositeOperation","SMask"],imageXObject:["transform","SMask","filter","fillAlpha","strokeAlpha","globalCompositeOperation"],rawFillPath:["filter","fillColor","fillAlpha"],showText:["transform","leading","charSpacing","wordSpacing","hScale","textRise","moveText","textMatrix","font","fontObj","filter","fillColor","textRenderingMode","SMask","fillAlpha","strokeAlpha","globalCompositeOperation","sameLineText"],transform:["transform"],transformAndFill:["transform","fillColor"]};var pd,gd,md,vd,yd,Wy;const Wv=class Wv{constructor(e){D(this,pd);D(this,gd);D(this,md,4);D(this,vd,0);D(this,yd,new(f(Wv,Wy))(f(this,md)*6));x(this,pd,e.width),x(this,gd,e.height)}record(e,t,n,i){if(f(this,vd)===f(this,md)){x(this,md,f(this,md)*2);const a=new(f(Wv,Wy))(f(this,md)*6);a.set(f(this,yd)),x(this,yd,a)}const r=Cs(e);let o;if(i[0]!==1/0){const a=gc.slice();Be.axialAlignedBoundingBox([0,-n,t,0],r,a);const c=Be.intersect(i,a);if(!c)return;const[l,u,h,d]=c;if(l!==a[0]||u!==a[1]||h!==a[2]||d!==a[3]){const p=Math.atan2(r[1],r[0]),m=Math.abs(Math.sin(p)),v=Math.abs(Math.cos(p));if(m<1e-6||v<1e-6||Math.abs(m-v)<1e-6)o=[l,u,l,d,h,u];else{const g=h-l,y=d-u,b=m*m,_=v*v,w=v*m,S=_-b,C=(y*_-g*w)/S,T=(y*w-g*b)/S;o=[l+T,u,l,u+C,h,d-C]}}}o||(o=[0,-n,0,0,t,-n],Be.applyTransform(o,r,0),Be.applyTransform(o,r,2),Be.applyTransform(o,r,4)),o[0]/=f(this,pd),o[1]/=f(this,gd),o[2]/=f(this,pd),o[3]/=f(this,gd),o[4]/=f(this,pd),o[5]/=f(this,gd),f(this,yd).set(o,f(this,vd)*6),xs(this,vd)._++}take(){return f(this,yd).subarray(0,f(this,vd)*6)}};pd=new WeakMap,gd=new WeakMap,md=new WeakMap,vd=new WeakMap,yd=new WeakMap,Wy=new WeakMap,D(Wv,Wy,Ts.isFloat16ArraySupported?Float16Array:Float32Array);let zT=Wv;var Yp;class Wee{constructor({ownerDocument:e=globalThis.document,styleElement:t=null}){D(this,Yp,new Set);this._document=e,this.nativeFontFaces=new Set,this.styleElement=null,this.loadingRequests=[],this.loadTestFontId=0}addNativeFontFace(e){this.nativeFontFaces.add(e),this._document.fonts.add(e)}removeNativeFontFace(e){this.nativeFontFaces.delete(e),this._document.fonts.delete(e)}insertRule(e){this.styleElement||(this.styleElement=this._document.createElement("style"),this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement));const t=this.styleElement.sheet;t.insertRule(e,t.cssRules.length)}clear(){for(const e of this.nativeFontFaces)this._document.fonts.delete(e);this.nativeFontFaces.clear(),f(this,Yp).clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:e,disableFontFace:t,_inspectFont:n}){if(!(!e||f(this,Yp).has(e.loadedName))){if(Gs(!t,"loadSystemFont shouldn't be called when `disableFontFace` is set."),this.isFontLoadingAPISupported){const{loadedName:i,src:r,style:o}=e,a=new FontFace(i,r,o);this.addNativeFontFace(a);try{await a.load(),f(this,Yp).add(i),n==null||n(e)}catch{kt(`Cannot load system font: ${e.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(a)}return}es("Not implemented: loadSystemFont without the Font Loading API.")}}async bind(e){if(e.attached||e.missingFile&&!e.systemFontInfo)return;if(e.attached=!0,e.systemFontInfo){await this.loadSystemFont(e);return}if(this.isFontLoadingAPISupported){const n=e.createNativeFontFace();if(n){this.addNativeFontFace(n);try{await n.loaded}catch(i){throw kt(`Failed to load font '${n.family}': '${i}'.`),e.disableFontFace=!0,i}}return}const t=e.createFontFaceRule();if(t){if(this.insertRule(t),this.isSyncFontLoadingSupported)return;await new Promise(n=>{const i=this._queueLoadingCallback(n);this._prepareFontLoadEvent(e,i)})}}get isFontLoadingAPISupported(){var t;const e=!!((t=this._document)!=null&&t.fonts);return Tt(this,"isFontLoadingAPISupported",e)}get isSyncFontLoadingSupported(){return Tt(this,"isSyncFontLoadingSupported",Zr||Ts.platform.isFirefox)}_queueLoadingCallback(e){function t(){for(Gs(!i.done,"completeRequest() cannot be called twice."),i.done=!0;n.length>0&&n[0].done;){const r=n.shift();setTimeout(r.callback,0)}}const{loadingRequests:n}=this,i={done:!1,complete:t,callback:e};return n.push(i),i}get _loadTestFont(){const e=atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==");return Tt(this,"_loadTestFont",e)}_prepareFontLoadEvent(e,t){function n(S,C){return S.charCodeAt(C)<<24|S.charCodeAt(C+1)<<16|S.charCodeAt(C+2)<<8|S.charCodeAt(C+3)&255}function i(S){return String.fromCharCode(S>>24&255,S>>16&255,S>>8&255,S&255)}function r(S,C,T,k){const A=S.substring(0,C),M=S.substring(C+T);return A+k+M}let o,a;const c=this._document.createElement("canvas");c.width=1,c.height=1;const l=c.getContext("2d");let u=0;function h(S,C){if(++u>30){kt("Load test font never loaded."),C();return}if(l.font="30px "+S,l.fillText(".",0,20),l.getImageData(0,0,1,1).data[3]>0){C();return}setTimeout(h.bind(null,S,C))}const d=`lt${Date.now()}${this.loadTestFontId++}`;let p=this._loadTestFont;p=r(p,976,d.length,d);const v=16,g=1482184792;let y=n(p,v);for(o=0,a=d.length-3;o<a;o+=4)y=y-g+n(d,o)|0;o<d.length&&(y=y-g+n(d+"XXX",o)|0),p=r(p,v,4,i(y));const b=`url(data:font/opentype;base64,${btoa(p)});`,_=`@font-face {font-family:"${d}";src:${b}}`;this.insertRule(_);const w=this._document.createElement("div");w.style.visibility="hidden",w.style.width=w.style.height="10px",w.style.position="absolute",w.style.top=w.style.left="0px";for(const S of[e.loadedName,d]){const C=this._document.createElement("span");C.textContent="Hi",C.style.fontFamily=S,w.append(C)}this._document.body.append(w),h(d,()=>{w.remove(),t.complete()})}}Yp=new WeakMap;var gs;class zee{constructor(e,t=null,n,i){_e(this,"compiledGlyphs",Object.create(null));D(this,gs);x(this,gs,e),this._inspectFont=t,n&&(this.charProcOperatorList=n),i&&Object.assign(this,i)}createNativeFontFace(){var t;if(!this.data||this.disableFontFace)return null;let e;if(!this.cssFontInfo)e=new FontFace(this.loadedName,this.data,{});else{const n={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(n.style=`oblique ${this.cssFontInfo.italicAngle}deg`),e=new FontFace(this.cssFontInfo.fontFamily,this.data,n)}return(t=this._inspectFont)==null||t.call(this,this),e}createFontFaceRule(){var n;if(!this.data||this.disableFontFace)return null;const e=`url(data:${this.mimetype};base64,${this.data.toBase64()});`;let t;if(!this.cssFontInfo)t=`@font-face {font-family:"${this.loadedName}";src:${e}}`;else{let i=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(i+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`),t=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${i}src:${e}}`}return(n=this._inspectFont)==null||n.call(this,this,e),t}getPathGenerator(e,t){if(this.compiledGlyphs[t]!==void 0)return this.compiledGlyphs[t];const n=this.loadedName+"_path_"+t;let i;try{i=e.get(n)}catch(o){kt(`getPathGenerator - ignoring character: "${o}".`)}const r=DD(i==null?void 0:i.path);return this.fontExtraProperties||e.delete(n),this.compiledGlyphs[t]=r}get black(){return f(this,gs).black}get bold(){return f(this,gs).bold}get disableFontFace(){return f(this,gs).disableFontFace}set disableFontFace(e){Tt(this,"disableFontFace",!!e)}get fontExtraProperties(){return f(this,gs).fontExtraProperties}get isInvalidPDFjsFont(){return f(this,gs).isInvalidPDFjsFont}get isType3Font(){return f(this,gs).isType3Font}get italic(){return f(this,gs).italic}get missingFile(){return f(this,gs).missingFile}get remeasure(){return f(this,gs).remeasure}get vertical(){return f(this,gs).vertical}get ascent(){return f(this,gs).ascent}get defaultWidth(){return f(this,gs).defaultWidth}get descent(){return f(this,gs).descent}get bbox(){return f(this,gs).bbox}get fontMatrix(){return f(this,gs).fontMatrix}get fallbackName(){return f(this,gs).fallbackName}get loadedName(){return f(this,gs).loadedName}get mimetype(){return f(this,gs).mimetype}get name(){return f(this,gs).name}get data(){return f(this,gs).data}clearData(){f(this,gs).clearData()}get cssFontInfo(){return f(this,gs).cssFontInfo}get systemFontInfo(){return f(this,gs).systemFontInfo}get defaultVMetrics(){return f(this,gs).defaultVMetrics}}gs=new WeakMap;class mN{}_e(mN,"strings",["fontFamily","fontWeight","italicAngle"]);class vN{}_e(vN,"strings",["css","loadedName","baseFontName","src"]);const _i=class _i{};_e(_i,"bools",["black","bold","disableFontFace","fontExtraProperties","isInvalidPDFjsFont","isType3Font","italic","missingFile","remeasure","vertical"]),_e(_i,"numbers",["ascent","defaultWidth","descent"]),_e(_i,"strings",["fallbackName","loadedName","mimetype","name"]),_e(_i,"OFFSET_NUMBERS",Math.ceil(_i.bools.length*2/8)),_e(_i,"OFFSET_BBOX",_i.OFFSET_NUMBERS+_i.numbers.length*8),_e(_i,"OFFSET_FONT_MATRIX",_i.OFFSET_BBOX+1+2*4),_e(_i,"OFFSET_DEFAULT_VMETRICS",_i.OFFSET_FONT_MATRIX+1+8*6),_e(_i,"OFFSET_STRINGS",_i.OFFSET_DEFAULT_VMETRICS+1+2*3);let Rr=_i;class Ki{}_e(Ki,"KIND",0),_e(Ki,"HAS_BBOX",1),_e(Ki,"HAS_BACKGROUND",2),_e(Ki,"SHADING_TYPE",3),_e(Ki,"N_COORD",4),_e(Ki,"N_COLOR",8),_e(Ki,"N_STOP",12),_e(Ki,"N_FIGURES",16);var zy,E0,Jp,Zp,RS;class jee{constructor(e){D(this,Zp);D(this,zy);D(this,E0,new TextDecoder);D(this,Jp);x(this,zy,e),x(this,Jp,new DataView(e))}get fontFamily(){return B(this,Zp,RS).call(this,0)}get fontWeight(){return B(this,Zp,RS).call(this,1)}get italicAngle(){return B(this,Zp,RS).call(this,2)}}zy=new WeakMap,E0=new WeakMap,Jp=new WeakMap,Zp=new WeakSet,RS=function(e){Gs(e<mN.strings.length,"Invalid string index");let t=0;for(let i=0;i<e;i++)t+=f(this,Jp).getUint32(t)+4;const n=f(this,Jp).getUint32(t);return f(this,E0).decode(new Uint8Array(f(this,zy),t+4,n))};var bd,eg,Ua,_d,tv;class Vee{constructor(e){D(this,_d);D(this,bd);D(this,eg,new TextDecoder);D(this,Ua);x(this,bd,e),x(this,Ua,new DataView(e))}get guessFallback(){return f(this,Ua).getUint8(0)!==0}get css(){return B(this,_d,tv).call(this,0)}get loadedName(){return B(this,_d,tv).call(this,1)}get baseFontName(){return B(this,_d,tv).call(this,2)}get src(){return B(this,_d,tv).call(this,3)}get style(){let e=1;e+=4+f(this,Ua).getUint32(e);const t=f(this,Ua).getUint32(e),n=f(this,eg).decode(new Uint8Array(f(this,bd),e+4,t));e+=4+t;const i=f(this,Ua).getUint32(e),r=f(this,eg).decode(new Uint8Array(f(this,bd),e+4,i));return{style:n,weight:r}}}bd=new WeakMap,eg=new WeakMap,Ua=new WeakMap,_d=new WeakSet,tv=function(e){Gs(e<vN.strings.length,"Invalid string index");let t=5;for(let i=0;i<e;i++)t+=f(this,Ua).getUint32(t)+4;const n=f(this,Ua).getUint32(t);return f(this,eg).decode(new Uint8Array(f(this,bd),t+4,n))};var na,M0,ln,hs,Xo,LS,PS,sv,jT;class Gee{constructor({buffer:e,extra:t}){D(this,hs);D(this,na);D(this,M0,new TextDecoder);D(this,ln);x(this,na,e),x(this,ln,new DataView(e)),t&&Object.assign(this,t)}get black(){return B(this,hs,Xo).call(this,0)}get bold(){return B(this,hs,Xo).call(this,1)}get disableFontFace(){return B(this,hs,Xo).call(this,2)}get fontExtraProperties(){return B(this,hs,Xo).call(this,3)}get isInvalidPDFjsFont(){return B(this,hs,Xo).call(this,4)}get isType3Font(){return B(this,hs,Xo).call(this,5)}get italic(){return B(this,hs,Xo).call(this,6)}get missingFile(){return B(this,hs,Xo).call(this,7)}get remeasure(){return B(this,hs,Xo).call(this,8)}get vertical(){return B(this,hs,Xo).call(this,9)}get ascent(){return B(this,hs,LS).call(this,0)}get defaultWidth(){return B(this,hs,LS).call(this,1)}get descent(){return B(this,hs,LS).call(this,2)}get bbox(){return B(this,hs,PS).call(this,Rr.OFFSET_BBOX,4,"getInt16",2)}get fontMatrix(){return B(this,hs,PS).call(this,Rr.OFFSET_FONT_MATRIX,6,"getFloat64",8)}get defaultVMetrics(){return B(this,hs,PS).call(this,Rr.OFFSET_DEFAULT_VMETRICS,3,"getInt16",2)}get fallbackName(){return B(this,hs,sv).call(this,0)}get loadedName(){return B(this,hs,sv).call(this,1)}get mimetype(){return B(this,hs,sv).call(this,2)}get name(){return B(this,hs,sv).call(this,3)}get data(){const{offset:e,length:t}=B(this,hs,jT).call(this);return t===0?void 0:new Uint8Array(f(this,na),e+4,t)}clearData(){const{offset:e,length:t}=B(this,hs,jT).call(this);t!==0&&(f(this,ln).setUint32(e,0),x(this,na,new Uint8Array(f(this,na),0,e+4).slice().buffer),x(this,ln,new DataView(f(this,na))))}get cssFontInfo(){let e=Rr.OFFSET_STRINGS;const t=f(this,ln).getUint32(e);e+=4+t;const n=f(this,ln).getUint32(e);e+=4+n;const i=f(this,ln).getUint32(e);if(i===0)return null;const r=new Uint8Array(i);return r.set(new Uint8Array(f(this,na),e+4,i)),new jee(r.buffer)}get systemFontInfo(){let e=Rr.OFFSET_STRINGS;const t=f(this,ln).getUint32(e);e+=4+t;const n=f(this,ln).getUint32(e);if(n===0)return null;const i=new Uint8Array(n);return i.set(new Uint8Array(f(this,na),e+4,n)),new Vee(i.buffer)}}na=new WeakMap,M0=new WeakMap,ln=new WeakMap,hs=new WeakSet,Xo=function(e){Gs(e<Rr.bools.length,"Invalid boolean index");const t=Math.floor(e/4),n=e*2%8,i=f(this,ln).getUint8(t)>>n&3;return i===0?void 0:i===2},LS=function(e){return Gs(e<Rr.numbers.length,"Invalid number index"),f(this,ln).getFloat64(Rr.OFFSET_NUMBERS+e*8)},PS=function(e,t,n,i){const r=f(this,ln).getUint8(e);if(r===0)return;Gs(r===t,"Invalid array length."),e+=1;const o=new Array(r);for(let a=0;a<r;a++)o[a]=f(this,ln)[n](e,!0),e+=i;return o},sv=function(e){Gs(e<Rr.strings.length,"Invalid string index");let t=Rr.OFFSET_STRINGS+4;for(let i=0;i<e;i++)t+=f(this,ln).getUint32(t)+4;const n=f(this,ln).getUint32(t);return f(this,M0).decode(new Uint8Array(f(this,na),t+4,n))},jT=function(){let e=Rr.OFFSET_STRINGS;const t=f(this,ln).getUint32(e);e+=4+t;const n=f(this,ln).getUint32(e);e+=4+n;const i=f(this,ln).getUint32(e);e+=4+i;const r=f(this,ln).getUint32(e);return{offset:e,length:r}};class qee{constructor(e){this.buffer=e,this.view=new DataView(e),this.data=new Uint8Array(e)}getIR(){const e=this.view,t=this.data[Ki.KIND],n=!!this.data[Ki.HAS_BBOX],i=!!this.data[Ki.HAS_BACKGROUND],r=e.getUint32(Ki.N_COORD,!0),o=e.getUint32(Ki.N_COLOR,!0),a=e.getUint32(Ki.N_STOP,!0);let c=20;const l=new Float32Array(this.buffer,c,r*2);c+=r*8;const u=new Uint8Array(this.buffer,c,o*4);c+=o*4;const h=[];for(let m=0;m<a;++m){const v=e.getFloat32(c,!0);c+=4;const g=e.getUint32(c,!0);c+=4,h.push([v,`#${g.toString(16).padStart(6,"0")}`])}let d=null;if(n){d=[];for(let m=0;m<4;++m)d.push(e.getFloat32(c,!0)),c+=4}let p=null;if(i&&(p=new Uint8Array(this.buffer,c,3),c+=3),t===1)return["RadialAxial","axial",d,h,Array.from(l.slice(0,2)),Array.from(l.slice(2,4)),null,null];if(t===2)return["RadialAxial","radial",d,h,[l[0],l[1]],[l[3],l[4]],l[2],l[5]];if(t===3){const m=this.data[Ki.SHADING_TYPE];let v=null;if(l.length>0){v=gc.slice();for(let g=0,y=l.length;g<y;g+=2)Be.pointBoundingBox(l[g],l[g+1],v)}return["Mesh",m,l,u,r,v,d,p]}throw new Error(`Unsupported pattern kind: ${t}`)}}var tg;class Kee{constructor(e){D(this,tg);x(this,tg,e)}get path(){return Ts.isFloat16ArraySupported?new Float16Array(f(this,tg)):new Float32Array(f(this,tg))}}tg=new WeakMap;function Qee(s){if(s instanceof URL)return s;if(typeof s=="string"){if(Zr){if(/^[a-z][a-z0-9\-+.]+:/i.test(s))return new URL(s);const t=process.getBuiltinModule("url");return new URL(t.pathToFileURL(s))}const e=URL.parse(s,window.location);if(e)return e}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}function Xee(s){if(Zr&&typeof Buffer<"u"&&s instanceof Buffer)throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");if(s instanceof Uint8Array&&s.byteLength===s.buffer.byteLength)return s;if(typeof s=="string")return fk(s);if(s instanceof ArrayBuffer||ArrayBuffer.isView(s)||typeof s=="object"&&!isNaN(s==null?void 0:s.length))return new Uint8Array(s);throw new Error("Invalid PDF binary data: either TypedArray, string, or array-like object is expected in the data property.")}function G_(s){if(typeof s!="string")return null;if(s.endsWith("/"))return s;throw new Error(`Invalid factory url: "${s}" must include trailing slash.`)}const VT=s=>typeof s=="object"&&Number.isInteger(s==null?void 0:s.num)&&s.num>=0&&Number.isInteger(s==null?void 0:s.gen)&&s.gen>=0,Yee=s=>typeof s=="object"&&typeof(s==null?void 0:s.name)=="string",Jee=Cee.bind(null,VT,Yee);var Vl,x0;class Zee{constructor(){D(this,Vl,new Map);D(this,x0,Promise.resolve())}postMessage(e,t){const n={data:structuredClone(e,t?{transfer:t}:null)};f(this,x0).then(()=>{for(const[i]of f(this,Vl))i.call(this,n)})}addEventListener(e,t,n=null){let i=null;if((n==null?void 0:n.signal)instanceof AbortSignal){const{signal:r}=n;if(r.aborted){kt("LoopbackPort - cannot use an `aborted` signal.");return}const o=()=>this.removeEventListener(e,t);i=()=>r.removeEventListener("abort",o),r.addEventListener("abort",o)}f(this,Vl).set(t,i)}removeEventListener(e,t){const n=f(this,Vl).get(t);n==null||n(),f(this,Vl).delete(t)}terminate(){for(const[,e]of f(this,Vl))e==null||e();f(this,Vl).clear()}}Vl=new WeakMap,x0=new WeakMap;St(1689);const q_={DATA:1,ERROR:2},gn={CANCEL:1,CANCEL_COMPLETE:2,CLOSE:3,ENQUEUE:4,ERROR:5,PULL:6,PULL_COMPLETE:7,START_COMPLETE:8};function wR(){}function or(s){if(s instanceof ch||s instanceof bT||s instanceof uR||s instanceof l0||s instanceof QC)return s;switch(s instanceof Error||typeof s=="object"&&s!==null||es('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),s.name){case"AbortException":return new ch(s.message);case"InvalidPDFException":return new bT(s.message);case"PasswordException":return new uR(s.message,s.code);case"ResponseException":return new l0(s.message,s.status,s.missing);case"UnknownErrorException":return new QC(s.message,s.details)}return new QC(s.message,s.toString())}var sg,Do,yN,bN,_N,OS;class nv{constructor(e,t,n){D(this,Do);D(this,sg,new AbortController);this.sourceName=e,this.targetName=t,this.comObj=n,this.callbackId=1,this.streamId=1,this.streamSinks=Object.create(null),this.streamControllers=Object.create(null),this.callbackCapabilities=Object.create(null),this.actionHandler=Object.create(null),n.addEventListener("message",B(this,Do,yN).bind(this),{signal:f(this,sg).signal})}on(e,t){const n=this.actionHandler;if(n[e])throw new Error(`There is already an actionName called "${e}"`);n[e]=t}send(e,t,n){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:e,data:t},n)}sendWithPromise(e,t,n){const i=this.callbackId++,r=Promise.withResolvers();this.callbackCapabilities[i]=r;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:e,callbackId:i,data:t},n)}catch(o){r.reject(o)}return r.promise}sendWithStream(e,t,n,i){const r=this.streamId++,o=this.sourceName,a=this.targetName,c=this.comObj;return new ReadableStream({start:l=>{const u=Promise.withResolvers();return this.streamControllers[r]={controller:l,startCall:u,pullCall:null,cancelCall:null,isClosed:!1},c.postMessage({sourceName:o,targetName:a,action:e,streamId:r,data:t,desiredSize:l.desiredSize},i),u.promise},pull:l=>{const u=Promise.withResolvers();return this.streamControllers[r].pullCall=u,c.postMessage({sourceName:o,targetName:a,stream:gn.PULL,streamId:r,desiredSize:l.desiredSize}),u.promise},cancel:l=>{Gs(l instanceof Error,"cancel must have a valid reason");const u=Promise.withResolvers();return this.streamControllers[r].cancelCall=u,this.streamControllers[r].isClosed=!0,c.postMessage({sourceName:o,targetName:a,stream:gn.CANCEL,streamId:r,reason:or(l)}),u.promise}},n)}destroy(){var e;(e=f(this,sg))==null||e.abort(),x(this,sg,null)}}sg=new WeakMap,Do=new WeakSet,yN=function({data:e}){if(e.targetName!==this.sourceName)return;if(e.stream){B(this,Do,_N).call(this,e);return}if(e.callback){const n=e.callbackId,i=this.callbackCapabilities[n];if(!i)throw new Error(`Cannot resolve callback ${n}`);if(delete this.callbackCapabilities[n],e.callback===q_.DATA)i.resolve(e.data);else if(e.callback===q_.ERROR)i.reject(or(e.reason));else throw new Error("Unexpected callback case");return}const t=this.actionHandler[e.action];if(!t)throw new Error(`Unknown action from worker: ${e.action}`);if(e.callbackId){const n=this.sourceName,i=e.sourceName,r=this.comObj;Promise.try(t,e.data).then(function(o){r.postMessage({sourceName:n,targetName:i,callback:q_.DATA,callbackId:e.callbackId,data:o})},function(o){r.postMessage({sourceName:n,targetName:i,callback:q_.ERROR,callbackId:e.callbackId,reason:or(o)})});return}if(e.streamId){B(this,Do,bN).call(this,e);return}t(e.data)},bN=function(e){const t=e.streamId,n=this.sourceName,i=e.sourceName,r=this.comObj,o=this,a=this.actionHandler[e.action],c={enqueue(l,u=1,h){if(this.isCancelled)return;const d=this.desiredSize;this.desiredSize-=u,d>0&&this.desiredSize<=0&&(this.sinkCapability=Promise.withResolvers(),this.ready=this.sinkCapability.promise),r.postMessage({sourceName:n,targetName:i,stream:gn.ENQUEUE,streamId:t,chunk:l},h)},close(){this.isCancelled||(this.isCancelled=!0,r.postMessage({sourceName:n,targetName:i,stream:gn.CLOSE,streamId:t}),delete o.streamSinks[t])},error(l){Gs(l instanceof Error,"error must have a valid reason"),!this.isCancelled&&(this.isCancelled=!0,r.postMessage({sourceName:n,targetName:i,stream:gn.ERROR,streamId:t,reason:or(l)}))},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:e.desiredSize,ready:null};c.sinkCapability.resolve(),c.ready=c.sinkCapability.promise,this.streamSinks[t]=c,Promise.try(a,e.data,c).then(function(){r.postMessage({sourceName:n,targetName:i,stream:gn.START_COMPLETE,streamId:t,success:!0})},function(l){r.postMessage({sourceName:n,targetName:i,stream:gn.START_COMPLETE,streamId:t,reason:or(l)})})},_N=function(e){const t=e.streamId,n=this.sourceName,i=e.sourceName,r=this.comObj,o=this.streamControllers[t],a=this.streamSinks[t];switch(e.stream){case gn.START_COMPLETE:e.success?o.startCall.resolve():o.startCall.reject(or(e.reason));break;case gn.PULL_COMPLETE:e.success?o.pullCall.resolve():o.pullCall.reject(or(e.reason));break;case gn.PULL:if(!a){r.postMessage({sourceName:n,targetName:i,stream:gn.PULL_COMPLETE,streamId:t,success:!0});break}a.desiredSize<=0&&e.desiredSize>0&&a.sinkCapability.resolve(),a.desiredSize=e.desiredSize,Promise.try(a.onPull||wR).then(function(){r.postMessage({sourceName:n,targetName:i,stream:gn.PULL_COMPLETE,streamId:t,success:!0})},function(l){r.postMessage({sourceName:n,targetName:i,stream:gn.PULL_COMPLETE,streamId:t,reason:or(l)})});break;case gn.ENQUEUE:if(Gs(o,"enqueue should have stream controller"),o.isClosed)break;o.controller.enqueue(e.chunk);break;case gn.CLOSE:if(Gs(o,"close should have stream controller"),o.isClosed)break;o.isClosed=!0,o.controller.close(),B(this,Do,OS).call(this,o,t);break;case gn.ERROR:Gs(o,"error should have stream controller"),o.controller.error(or(e.reason)),B(this,Do,OS).call(this,o,t);break;case gn.CANCEL_COMPLETE:e.success?o.cancelCall.resolve():o.cancelCall.reject(or(e.reason)),B(this,Do,OS).call(this,o,t);break;case gn.CANCEL:if(!a)break;const c=or(e.reason);Promise.try(a.onCancel||wR,c).then(function(){r.postMessage({sourceName:n,targetName:i,stream:gn.CANCEL_COMPLETE,streamId:t,success:!0})},function(l){r.postMessage({sourceName:n,targetName:i,stream:gn.CANCEL_COMPLETE,streamId:t,reason:or(l)})}),a.sinkCapability.reject(c),a.isCancelled=!0,delete this.streamSinks[t];break;default:throw new Error("Unexpected stream case")}},OS=async function(e,t){var n,i,r;await Promise.allSettled([(n=e.startCall)==null?void 0:n.promise,(i=e.pullCall)==null?void 0:i.promise,(r=e.cancelCall)==null?void 0:r.promise]),delete this.streamControllers[t]};var I0;class SN{constructor({cMapUrl:e=null,standardFontDataUrl:t=null,wasmUrl:n=null}){D(this,I0,Object.freeze({cMapUrl:"CMap",standardFontDataUrl:"font",wasmUrl:"wasm"}));this.cMapUrl=e,this.standardFontDataUrl=t,this.wasmUrl=n}async fetch({kind:e,filename:t}){switch(e){case"cMapUrl":case"standardFontDataUrl":case"wasmUrl":break;default:es(`Not implemented: ${e}`)}const n=this[e];if(!n)throw new Error(`Ensure that the \`${e}\` API parameter is provided.`);const i=`${n}${t}`;return this._fetch(i,e).catch(r=>{throw new Error(`Unable to load ${f(this,I0)[e]} data at: ${i}`)})}async _fetch(e,t){es("Abstract method `_fetch` called.")}}I0=new WeakMap;class kR extends SN{async _fetch(e,t){const n=t==="cMapUrl"&&!e.endsWith(".bcmap")?"text":"bytes",i=await cM(e,n);return i instanceof Uint8Array?i:fk(i)}}var jy;class wN{constructor({enableHWA:e=!1}){D(this,jy,!1);x(this,jy,e)}create(e,t){if(e<=0||t<=0)throw new Error("Invalid canvas size");const n=this._createCanvas(e,t);return{canvas:n,context:n.getContext("2d",{willReadFrequently:!f(this,jy)})}}reset({canvas:e},t,n){if(!e)throw new Error("Canvas is not specified");if(t<=0||n<=0)throw new Error("Invalid canvas size");e.width=t,e.height=n}destroy(e){const{canvas:t}=e;if(!t)throw new Error("Canvas is not specified");t.width=t.height=0,e.canvas=null,e.context=null}_createCanvas(e,t){es("Abstract method `_createCanvas` called.")}}jy=new WeakMap;class ete extends wN{constructor({ownerDocument:e=globalThis.document,enableHWA:t=!1}){super({enableHWA:t}),this._document=e}_createCanvas(e,t){const n=this._document.createElement("canvas");return n.width=e,n.height=t,n}}class kN{addFilter(e){return"none"}addHCMFilter(e,t){return"none"}addAlphaFilter(e){return"none"}addLuminosityFilter(e){return"none"}addKnockoutFilter(e=0){return"none"}addHighlightHCMFilter(e,t,n,i,r){return"none"}addSelectionHCMFilter(e,t){return"none"}addSelectionFilter(){return"none"}createSelectionStyle(e=null){return null}destroy(e=!1){}}var Sd,ng,Gl,Wa,Un,wd,Tu,ze,Fn,iv,qc,DS,Th,CN,GT,Ah,rv,ov,qT,av,TN,AN;class tte extends kN{constructor({docId:t,ownerDocument:n=globalThis.document}){super();D(this,ze);D(this,Sd);D(this,ng);D(this,Gl);D(this,Wa);D(this,Un);D(this,wd);D(this,Tu,0);x(this,Wa,t),x(this,Un,n)}addFilter(t){if(!t)return"none";let n=f(this,ze,Fn).get(t);if(n)return n;const[i,r,o]=B(this,ze,DS).call(this,t),a=t.length===1?i:`${i}${r}${o}`;if(n=f(this,ze,Fn).get(a),n)return f(this,ze,Fn).set(t,n),n;const c=`g_${f(this,Wa)}_transfer_map_${xs(this,Tu)._++}`,l=B(this,ze,Th).call(this,c);f(this,ze,Fn).set(t,l),f(this,ze,Fn).set(a,l);const u=B(this,ze,Ah).call(this,c);return B(this,ze,ov).call(this,i,r,o,u),l}addHCMFilter(t,n){var m;const i=`${t}-${n}`,r="base";let o=f(this,ze,iv).get(r);if((o==null?void 0:o.key)===i||(o?((m=o.filter)==null||m.remove(),o.key=i,o.url="none",o.filter=null):(o={key:i,url:"none",filter:null},f(this,ze,iv).set(r,o)),!t||!n))return o.url;const a=B(this,ze,av).call(this,t);t=Be.makeHexColor(...a);const c=B(this,ze,av).call(this,n);if(n=Be.makeHexColor(...c),f(this,ze,qc).style.color="",t==="#000000"&&n==="#ffffff"||t===n)return o.url;const l=new Array(256);for(let v=0;v<=255;v++){const g=v/255;l[v]=g<=.03928?g/12.92:((g+.055)/1.055)**2.4}const u=l.join(","),h=`g_${f(this,Wa)}_hcm_filter`,d=o.filter=B(this,ze,Ah).call(this,h);B(this,ze,ov).call(this,u,u,u,d),B(this,ze,GT).call(this,d);const p=(v,g)=>{const y=a[v]/255,b=c[v]/255,_=new Array(g+1);for(let w=0;w<=g;w++)_[w]=y+w/g*(b-y);return _.join(",")};return B(this,ze,ov).call(this,p(0,5),p(1,5),p(2,5),d),o.url=B(this,ze,Th).call(this,h),o.url}addSelectionHCMFilter(t,n){return this.addHighlightHCMFilter("selection",t,n,"HighlightText","Highlight")}addSelectionFilter(){return this.addHighlightHCMFilter("selection_default","black","white","HighlightText","Highlight")}createSelectionStyle(t=null){const n=t?this.addSelectionHCMFilter(t.foreground,t.background):this.addSelectionFilter();return n==="none"||!Ts.platform.isFirefox?null:{"backdrop-filter":n,"background-color":"transparent"}}addAlphaFilter(t){let n=f(this,ze,Fn).get(t);if(n)return n;const[i]=B(this,ze,DS).call(this,[t]),r=`alpha_${i}`;if(n=f(this,ze,Fn).get(r),n)return f(this,ze,Fn).set(t,n),n;const o=`g_${f(this,Wa)}_alpha_map_${xs(this,Tu)._++}`,a=B(this,ze,Th).call(this,o);f(this,ze,Fn).set(t,a),f(this,ze,Fn).set(r,a);const c=B(this,ze,Ah).call(this,o);return B(this,ze,qT).call(this,i,c),a}addLuminosityFilter(t){let n=f(this,ze,Fn).get(t||"luminosity");if(n)return n;let i,r;if(t?([i]=B(this,ze,DS).call(this,[t]),r=`luminosity_${i}`):r="luminosity",n=f(this,ze,Fn).get(r),n)return f(this,ze,Fn).set(t,n),n;const o=`g_${f(this,Wa)}_luminosity_map_${xs(this,Tu)._++}`,a=B(this,ze,Th).call(this,o);f(this,ze,Fn).set(t,a),f(this,ze,Fn).set(r,a);const c=B(this,ze,Ah).call(this,o);return B(this,ze,CN).call(this,c),t&&B(this,ze,qT).call(this,i,c),a}addKnockoutFilter(t=0){const n=t>0?Math.min(1/t,1e6):1e6,i=`knockout_${n}`,r=f(this,ze,Fn).get(i);if(r)return r;const o=`g_${f(this,Wa)}_knockout_filter_${xs(this,Tu)._++}`,a=B(this,ze,Th).call(this,o);f(this,ze,Fn).set(i,a);const c=B(this,ze,Ah).call(this,o),l=f(this,Un).createElementNS(Pr,"feComponentTransfer");c.append(l);const u=f(this,Un).createElementNS(Pr,"feFuncA");return u.setAttribute("type","linear"),u.setAttribute("slope",`${n}`),u.setAttribute("intercept","0"),l.append(u),a}addHighlightHCMFilter(t,n,i,r,o){var b;const a=`${n}-${i}-${r}-${o}`;let c=f(this,ze,iv).get(t);if((c==null?void 0:c.key)===a||(c?((b=c.filter)==null||b.remove(),c.key=a,c.url="none",c.filter=null):(c={key:a,url:"none",filter:null},f(this,ze,iv).set(t,c)),!n||!i))return c.url;const[l,u]=[n,i].map(B(this,ze,av).bind(this));let h=Math.round(.2126*l[0]+.7152*l[1]+.0722*l[2]),d=Math.round(.2126*u[0]+.7152*u[1]+.0722*u[2]),[p,m]=[r,o].map(B(this,ze,AN).bind(this));d<h&&([h,d,p,m]=[d,h,m,p]),f(this,ze,qc).style.color="";const v=(_,w,S)=>{const C=new Array(256),T=(d-h)/S,k=_/255,A=(w-_)/(255*S);let M=0;for(let R=0;R<=S;R++){const P=Math.round(h+R*T),L=k+R*A;for(let z=M;z<=P;z++)C[z]=L;M=P+1}for(let R=M;R<256;R++)C[R]=C[M-1];return C.join(",")},g=`g_${f(this,Wa)}_hcm_${t}_filter`,y=c.filter=B(this,ze,Ah).call(this,g);return B(this,ze,GT).call(this,y),B(this,ze,ov).call(this,v(p[0],m[0],5),v(p[1],m[1],5),v(p[2],m[2],5),y),c.url=B(this,ze,Th).call(this,g),c.url}destroy(t=!1){var n,i,r,o;t&&((n=f(this,wd))!=null&&n.size)||((i=f(this,Gl))==null||i.parentNode.parentNode.remove(),x(this,Gl,null),(r=f(this,ng))==null||r.clear(),x(this,ng,null),(o=f(this,wd))==null||o.clear(),x(this,wd,null),x(this,Tu,0))}}Sd=new WeakMap,ng=new WeakMap,Gl=new WeakMap,Wa=new WeakMap,Un=new WeakMap,wd=new WeakMap,Tu=new WeakMap,ze=new WeakSet,Fn=function(){return f(this,ng)||x(this,ng,new Map)},iv=function(){return f(this,wd)||x(this,wd,new Map)},qc=function(){if(!f(this,Gl)){const t=f(this,Un).createElement("div"),{style:n}=t;n.colorScheme="only light",n.visibility="hidden",n.contain="strict",n.width=n.height=0,n.position="absolute",n.top=n.left=0,n.zIndex=-1;const i=f(this,Un).createElementNS(Pr,"svg");i.setAttribute("width",0),i.setAttribute("height",0),x(this,Gl,f(this,Un).createElementNS(Pr,"defs")),t.append(i),i.append(f(this,Gl)),f(this,Un).body.append(t)}return f(this,Gl)},DS=function(t){if(t.length===1){const l=t[0],u=new Array(256);for(let d=0;d<256;d++)u[d]=l[d]/255;const h=u.join(",");return[h,h,h]}const[n,i,r]=t,o=new Array(256),a=new Array(256),c=new Array(256);for(let l=0;l<256;l++)o[l]=n[l]/255,a[l]=i[l]/255,c[l]=r[l]/255;return[o.join(","),a.join(","),c.join(",")]},Th=function(t){if(f(this,Sd)===void 0){x(this,Sd,"");const n=f(this,Un).URL;n!==f(this,Un).baseURI&&(pk(n)?kt('#createUrl: ignore "data:"-URL for performance reasons.'):x(this,Sd,RD(n,"")))}return`url(${f(this,Sd)}#${t})`},CN=function(t){const n=f(this,Un).createElementNS(Pr,"feColorMatrix");n.setAttribute("type","matrix"),n.setAttribute("values","0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0"),t.append(n)},GT=function(t){const n=f(this,Un).createElementNS(Pr,"feColorMatrix");n.setAttribute("type","matrix"),n.setAttribute("values","0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0"),t.append(n)},Ah=function(t){const n=f(this,Un).createElementNS(Pr,"filter");return n.setAttribute("color-interpolation-filters","sRGB"),n.setAttribute("id",t),f(this,ze,qc).append(n),n},rv=function(t,n,i){const r=f(this,Un).createElementNS(Pr,n);r.setAttribute("type","discrete"),r.setAttribute("tableValues",i),t.append(r)},ov=function(t,n,i,r){const o=f(this,Un).createElementNS(Pr,"feComponentTransfer");r.append(o),B(this,ze,rv).call(this,o,"feFuncR",t),B(this,ze,rv).call(this,o,"feFuncG",n),B(this,ze,rv).call(this,o,"feFuncB",i)},qT=function(t,n){const i=f(this,Un).createElementNS(Pr,"feComponentTransfer");n.append(i),B(this,ze,rv).call(this,i,"feFuncA",t)},av=function(t){return f(this,ze,qc).style.color=t,i_(getComputedStyle(f(this,ze,qc)).getPropertyValue("color"))},TN=function(t){return f(this,ze,qc).style.color=t,n_(getComputedStyle(f(this,ze,qc)).getPropertyValue("color"))},AN=function(t){const[n,i,r,o]=B(this,ze,TN).call(this,t);if(o===1)return[n,i,r];const[a,c,l]=B(this,ze,av).call(this,"Canvas");return[YC(n,a,o),YC(i,c,o),YC(r,l,o)]};function YC(s,e,t){return Math.round(t*s+(1-t)*e)}var p2;if(Zr){let s;try{const e=process.getBuiltinModule("module").createRequire(import.meta.url);try{s=e("@napi-rs/canvas")}catch(t){kt(`Cannot load "@napi-rs/canvas" package: "${t}".`)}}catch(e){kt(`Cannot access the \`require\` function: "${e}".`)}globalThis.DOMMatrix||(s!=null&&s.DOMMatrix?globalThis.DOMMatrix=s.DOMMatrix:kt("Cannot polyfill `DOMMatrix`, rendering may be broken.")),globalThis.ImageData||(s!=null&&s.ImageData?globalThis.ImageData=s.ImageData:kt("Cannot polyfill `ImageData`, rendering may be broken.")),globalThis.Path2D||(s!=null&&s.Path2D?globalThis.Path2D=s.Path2D:kt("Cannot polyfill `Path2D`, rendering may be broken.")),(p2=globalThis.navigator)!=null&&p2.language||(globalThis.navigator={language:"en-US",platform:"",userAgent:""})}async function ste(s){const t=await process.getBuiltinModule("fs/promises").readFile(s);return new Uint8Array(t)}class nte extends kN{}class ite extends wN{_createCanvas(e,t){return process.getBuiltinModule("module").createRequire(import.meta.url)("@napi-rs/canvas").createCanvas(e,t)}}class rte extends SN{async _fetch(e,t){return ste(e)}}const ote=`
struct Uniforms {
offsetX : f32,
offsetY : f32,
scaleX : f32,
scaleY : f32,
paddedWidth : f32,
paddedHeight : f32,
borderSize : f32,
_pad : f32,
};
@group(0) @binding(0) var<uniform> u : Uniforms;
struct VertexInput {
@location(0) position : vec2<f32>,
@location(1) color : vec4<f32>,
};
struct VertexOutput {
@builtin(position) position : vec4<f32>,
@location(0) color : vec3<f32>,
};
@vertex
fn vs_main(in : VertexInput) -> VertexOutput {
var out : VertexOutput;
let cx = (in.position.x + u.offsetX) * u.scaleX;
let cy = (in.position.y + u.offsetY) * u.scaleY;
out.position = vec4<f32>(
((cx + u.borderSize) / u.paddedWidth) * 2.0 - 1.0,
1.0 - ((cy + u.borderSize) / u.paddedHeight) * 2.0,
0.0,
1.0
);
out.color = in.color.rgb;
return out;
}
@fragment
fn fs_main(in : VertexOutput) -> @location(0) vec4<f32> {
return vec4<f32>(in.color, 1.0);
}
`;var R0,ql,kd,ig,L0,EN;class ate{constructor(){D(this,L0);D(this,R0,null);D(this,ql,null);D(this,kd,null);D(this,ig,null)}init(){return f(this,R0)||x(this,R0,B(this,L0,EN).call(this))}get isReady(){return f(this,ql)!==null}loadMeshShader(){if(!f(this,ql)||f(this,kd))return;const e=f(this,ql).createShaderModule({code:ote});x(this,kd,f(this,ql).createRenderPipeline({layout:"auto",vertex:{module:e,entryPoint:"vs_main",buffers:[{arrayStride:2*4,attributes:[{shaderLocation:0,offset:0,format:"float32x2"}]},{arrayStride:4,attributes:[{shaderLocation:1,offset:0,format:"unorm8x4"}]}]},fragment:{module:e,entryPoint:"fs_main",targets:[{format:f(this,ig)}]},primitive:{topology:"triangle-list"}}))}draw(e,t,n,i,r,o,a,c){this.loadMeshShader();const l=f(this,ql),{offsetX:u,offsetY:h,scaleX:d,scaleY:p}=i,m=l.createBuffer({size:Math.max(e.byteLength,4),usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST});e.byteLength>0&&l.queue.writeBuffer(m,0,e);const v=l.createBuffer({size:Math.max(t.byteLength,4),usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST});t.byteLength>0&&l.queue.writeBuffer(v,0,t);const g=l.createBuffer({size:8*4,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});l.queue.writeBuffer(g,0,new Float32Array([u,h,d,p,o,a,c,0]));const y=l.createBindGroup({layout:f(this,kd).getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:g}}]}),b=new OffscreenCanvas(o,a),_=b.getContext("webgpu");_.configure({device:l,format:f(this,ig),alphaMode:r?"opaque":"premultiplied"});const w=r?{r:r[0]/255,g:r[1]/255,b:r[2]/255,a:1}:{r:0,g:0,b:0,a:0},S=l.createCommandEncoder(),C=S.beginRenderPass({colorAttachments:[{view:_.getCurrentTexture().createView(),clearValue:w,loadOp:"clear",storeOp:"store"}]});return n>0&&(C.setPipeline(f(this,kd)),C.setBindGroup(0,y),C.setVertexBuffer(0,m),C.setVertexBuffer(1,v),C.draw(n)),C.end(),l.queue.submit([S.finish()]),m.destroy(),v.destroy(),g.destroy(),b.transferToImageBitmap()}}R0=new WeakMap,ql=new WeakMap,kd=new WeakMap,ig=new WeakMap,L0=new WeakSet,EN=async function(){var e;if(!((e=globalThis.navigator)!=null&&e.gpu))return!1;try{const t=await navigator.gpu.requestAdapter();return t?(x(this,ig,navigator.gpu.getPreferredCanvasFormat()),x(this,ql,await t.requestDevice()),!0):!1}catch{return!1}};const gk=new ate;function lte(){return gk.init()}function cte(){return gk.isReady}function ute(){gk.loadMeshShader()}function hte(s,e,t,n,i,r,o,a){return gk.draw(s,e,t,n,i,r,o,a)}const hi={FILL:"Fill",STROKE:"Stroke",SHADING:"Shading"};function NS(s,e){if(!e)return;const t=e[2]-e[0],n=e[3]-e[1],i=new Path2D;i.rect(e[0],e[1],t,n),s.clip(i)}class fM{isModifyingCurrentTransform(){return!1}getPattern(){es("Abstract method `getPattern` called.")}}class dte extends fM{constructor(e){super(),this._type=e[1],this._bbox=e[2],this._colorStops=e[3],this._p0=e[4],this._p1=e[5],this._r0=e[6],this._r1=e[7],this.matrix=null}isOriginBased(){return this._p0[0]===0&&this._p0[1]===0&&(!this.isRadial()||this._p1[0]===0&&this._p1[1]===0)}isRadial(){return this._type==="radial"}areConic(){if(!this.isRadial())return!1;const e=Math.hypot(this._p0[0]-this._p1[0],this._p0[1]-this._p1[1]);return e+this._r1>this._r0&&e+this._r0>this._r1}_createGradient(e,t=null){let n,i=this._p0,r=this._p1;if(t&&(i=i.slice(),r=r.slice(),Be.applyTransform(i,t),Be.applyTransform(r,t)),this._type==="axial")n=e.createLinearGradient(i[0],i[1],r[0],r[1]);else if(this._type==="radial"){let o=this._r0,a=this._r1;if(t){const c=new Float32Array(2);Be.singularValueDecompose2dScale(t,c),o*=c[0],a*=c[0]}n=e.createRadialGradient(i[0],i[1],o,r[0],r[1],a)}for(const o of this._colorStops)n.addColorStop(o[0],o[1]);return n}_createReversedGradient(e,t=null){let n=this._p1,i=this._p0;t&&(n=n.slice(),i=i.slice(),Be.applyTransform(n,t),Be.applyTransform(i,t));let r=this._r1,o=this._r0;if(t){const l=new Float32Array(2);Be.singularValueDecompose2dScale(t,l),r*=l[0],o*=l[0]}const a=e.createRadialGradient(n[0],n[1],r,i[0],i[1],o),c=this._colorStops.map(([l,u])=>[1-l,u]).reverse();for(const[l,u]of c)a.addColorStop(l,u);return a}getPattern(e,t,n,i){let r;if(i===hi.STROKE||i===hi.FILL){if(this.isOriginBased()){let d=Be.transform(n,t.baseTransform);this.matrix&&(d=Be.transform(d,this.matrix));const p=.001,m=Math.hypot(d[0],d[1]),v=Math.hypot(d[2],d[3]),g=(d[0]*d[2]+d[1]*d[3])/(m*v);if(Math.abs(g)<p)if(this.isRadial()){if(Math.abs(m-v)<p)return this._createGradient(e,d)}else return this._createGradient(e,d)}const o=t.current.getClippedPathBoundingBox(i,Cs(e))||[0,0,0,0],a=Math.ceil(o[2]-o[0])||1,c=Math.ceil(o[3]-o[1])||1,l=t.canvasFactory.create(a,c),u=l.context;u.clearRect(0,0,u.canvas.width,u.canvas.height),u.beginPath(),u.rect(0,0,u.canvas.width,u.canvas.height),u.translate(-o[0],-o[1]),n=Be.transform(n,[1,0,0,1,o[0],o[1]]),u.transform(...t.baseTransform),this.matrix&&u.transform(...this.matrix),NS(u,this._bbox),this.areConic()&&(u.fillStyle=this._createReversedGradient(u),u.fill()),u.fillStyle=this._createGradient(u),u.fill(),r=e.createPattern(l.canvas,"no-repeat"),t.canvasFactory.destroy(l);const h=new DOMMatrix(n);r.setTransform(h)}else this.areConic()&&(e.save(),NS(e,this._bbox),e.fillStyle=this._createReversedGradient(e),e.fillRect(-1e10,-1e10,2e10,2e10),e.restore()),NS(e,this._bbox),r=this._createGradient(e);return r}}function fte(s,e,t,n,i,r,o,a){const c=e.coords,l=e.colors,u=s.data,h=s.width*4;let d;c[t*2+1]>c[n*2+1]&&(d=t,t=n,n=d,d=r,r=o,o=d),c[n*2+1]>c[i*2+1]&&(d=n,n=i,i=d,d=o,o=a,a=d),c[t*2+1]>c[n*2+1]&&(d=t,t=n,n=d,d=r,r=o,o=d);const p=(c[t*2]+e.offsetX)*e.scaleX,m=(c[t*2+1]+e.offsetY)*e.scaleY,v=(c[n*2]+e.offsetX)*e.scaleX,g=(c[n*2+1]+e.offsetY)*e.scaleY,y=(c[i*2]+e.offsetX)*e.scaleX,b=(c[i*2+1]+e.offsetY)*e.scaleY;if(m>=b)return;const _=l[r*4],w=l[r*4+1],S=l[r*4+2],C=l[o*4],T=l[o*4+1],k=l[o*4+2],A=l[a*4],M=l[a*4+1],R=l[a*4+2],P=Math.round(m),L=Math.round(b);let z,Q,W,V,N,O,H,G;for(let ee=P;ee<=L;ee++){if(ee<g){const I=ee<m?0:(m-ee)/(m-g);z=p-(p-v)*I,Q=_-(_-C)*I,W=w-(w-T)*I,V=S-(S-k)*I}else{let I;ee>b?I=1:g===b?I=0:I=(g-ee)/(g-b),z=v-(v-y)*I,Q=C-(C-A)*I,W=T-(T-M)*I,V=k-(k-R)*I}let ie;ee<m?ie=0:ee>b?ie=1:ie=(m-ee)/(m-b),N=p-(p-y)*ie,O=_-(_-A)*ie,H=w-(w-M)*ie,G=S-(S-R)*ie;const ve=Math.round(Math.min(z,N)),le=Math.round(Math.max(z,N));let oe=h*ee+ve*4;for(let I=ve;I<=le;I++)ie=(z-I)/(z-N),ie<0?ie=0:ie>1&&(ie=1),u[oe++]=Q-(Q-O)*ie|0,u[oe++]=W-(W-H)*ie|0,u[oe++]=V-(V-G)*ie|0,u[oe++]=255}}class pte extends fM{constructor(e){super(),this._posData=e[2],this._colData=e[3],this._vertexCount=e[4],this._bounds=e[5],this._bbox=e[6],this._background=e[7],this.matrix=null,ute()}_createMeshCanvas(e,t,n){const a=Math.floor(this._bounds[0]),c=Math.floor(this._bounds[1]),l=Math.ceil(this._bounds[2])-a,u=Math.ceil(this._bounds[3])-c,h=Math.min(Math.ceil(Math.abs(l*e[0]*1.1)),3e3)||1,d=Math.min(Math.ceil(Math.abs(u*e[1]*1.1)),3e3)||1,p=l?l/h:1,m=u?u/d:1,v={coords:this._posData,colors:this._colData,offsetX:-a,offsetY:-c,scaleX:1/p,scaleY:1/m},g=h+2*2,y=d+2*2,b=n.create(g,y);if(cte()&&this._vertexCount>48)b.context.drawImage(hte(this._posData,this._colData,this._vertexCount,v,t,g,y,2),0,0);else{const _=b.context.createImageData(h,d);if(t){const w=_.data;for(let S=0,C=w.length;S<C;S+=4)w[S]=t[0],w[S+1]=t[1],w[S+2]=t[2],w[S+3]=255}for(let w=0,S=this._vertexCount;w<S;w+=3)fte(_,v,w,w+1,w+2,w,w+1,w+2);b.context.putImageData(_,2,2)}return{canvas:b.canvas,offsetX:a-2*p,offsetY:c-2*m,scaleX:p,scaleY:m}}isModifyingCurrentTransform(){return!0}getPattern(e,t,n,i){NS(e,this._bbox);const r=new Float32Array(2);if(i===hi.SHADING)Be.singularValueDecompose2dScale(Cs(e),r);else if(this.matrix){Be.singularValueDecompose2dScale(this.matrix,r);const[c,l]=r;Be.singularValueDecompose2dScale(t.baseTransform,r),r[0]*=c,r[1]*=l}else Be.singularValueDecompose2dScale(t.baseTransform,r);const o=this._createMeshCanvas(r,i===hi.SHADING?null:this._background,t.canvasFactory);i!==hi.SHADING&&(e.setTransform(...t.baseTransform),this.matrix&&e.transform(...this.matrix)),e.translate(o.offsetX,o.offsetY),e.scale(o.scaleX,o.scaleY);const a=e.createPattern(o.canvas,"no-repeat");return t.canvasFactory.destroy(o),a}}class gte extends fM{getPattern(){return"hotpink"}}function mte(s){switch(s[0]){case"RadialAxial":return new dte(s);case"Mesh":return new pte(s);case"Dummy":return new gte}throw new Error(`Unknown IR type: ${s[0]}`)}const CR={COLORED:1,UNCOLORED:2},P0=class P0{constructor(e,t,n,i){this.color=e[1],this.operatorList=e[2],this.matrix=e[3],this.bbox=e[4],this.xstep=e[5],this.ystep=e[6],this.paintType=e[7],this.tilingType=e[8],this.needsIsolation=e[9]??!0,this.ctx=t,this.canvasGraphicsFactory=n,this.baseTransform=i,this.patternBaseMatrix=this.matrix?Be.transform(i,this.matrix):i}canSkipPatternCanvas([e,t,n,i]){const[r,o,a,c]=this.bbox,l=Math.abs(this.xstep),u=Math.abs(this.ystep);if(e>l+1e-6||t>u+1e-6)return null;const h=Math.floor((n-a)/l)+1,d=Math.ceil((n+e-r)/l)-1,p=Math.floor((i-c)/u)+1,m=Math.ceil((i+t-o)/u)-1;return d<=h&&m<=p?[h,p]:null}updatePatternDims(e,t){const n=Be.inverseTransform(this.patternBaseMatrix),i=[e[0],e[1]],r=[e[2],e[3]];Be.applyTransform(i,n),Be.applyTransform(r,n),t[0]=Math.abs(r[0]-i[0]),t[1]=Math.abs(r[1]-i[1]),t[2]=Math.min(i[0],r[0]),t[3]=Math.min(i[1],r[1])}_renderTileCanvas(e,t,n,i){var d,p;const[r,o,a,c]=this.bbox,l=e.canvasFactory.create(n.size,i.size),u=l.context,h=this.canvasGraphicsFactory.createCanvasGraphics(u,t);return h.groupLevel=e.groupLevel,this.setFillAndStrokeStyleToContext(h,this.paintType,this.color),u.translate(-n.scale*r,-i.scale*o),h.transform(0,n.scale,0,0,i.scale,0,0),u.save(),(d=h.dependencyTracker)==null||d.save(),this.clipBbox(h,r,o,a,c),h.baseTransform=Cs(h.ctx),h.executeOperatorList(this.operatorList),h.endDrawing(),(p=h.dependencyTracker)==null||p.restore(),u.restore(),l}_getCombinedScales(){const e=new Float32Array(2);Be.singularValueDecompose2dScale(this.matrix,e);const[t,n]=e;return Be.singularValueDecompose2dScale(this.baseTransform,e),[t*e[0],n*e[1]]}drawPattern(e,t,n=!1,[i,r],o){const[a,c,l,u]=this.bbox,h=e.dependencyTracker;if(h&&(e.dependencyTracker=new cy(h,o)),e.save(),n?e.ctx.clip(t,"evenodd"):e.ctx.clip(t),e.ctx.setTransform(...this.patternBaseMatrix),e.ctx.translate(i*this.xstep,r*this.ystep),this.needsIsolation||e.ctx.globalAlpha!==1||e.ctx.globalCompositeOperation!=="source-over"||e.inSMaskMode){const d=l-a,p=u-c,[m,v]=this._getCombinedScales(),g=this.getSizeAndScale(d,this.ctx.canvas.width,m),y=this.getSizeAndScale(p,this.ctx.canvas.height,v),b=this._renderTileCanvas(e,o,g,y);e.ctx.drawImage(b.canvas,a,c,d,p),e.canvasFactory.destroy(b)}else this.setFillAndStrokeStyleToContext(e,this.paintType,this.color),this.clipBbox(e,a,c,l,u),e.baseTransformStack.push(e.baseTransform),e.baseTransform=Cs(e.ctx),e.executeOperatorList(this.operatorList),e.baseTransform=e.baseTransformStack.pop();e.restore(),h&&(e.dependencyTracker=h)}createPatternCanvas(e,t){const[n,i,r,o]=this.bbox,a=r-n,c=o-i;let{xstep:l,ystep:u}=this;l=Math.abs(l),u=Math.abs(u),dk("TilingType: "+this.tilingType);const[h,d]=this._getCombinedScales();let p=a,m=c,v=!1,g=!1;Math.ceil(l*h)>=Math.ceil(a*h)?p=l:v=!0,Math.ceil(u*d)>=Math.ceil(c*d)?m=u:g=!0;const y=this.getSizeAndScale(p,this.ctx.canvas.width,h),b=this.getSizeAndScale(m,this.ctx.canvas.height,d),_=this._renderTileCanvas(e,t,y,b);if(v||g){const w=_.canvas;v&&(p=l),g&&(m=u);const S=this.getSizeAndScale(p,this.ctx.canvas.width,h),C=this.getSizeAndScale(m,this.ctx.canvas.height,d),T=S.size,k=C.size,A=e.canvasFactory.create(T,k),M=A.context,R=v?Math.floor(a/l):0,P=g?Math.floor(c/u):0;for(let L=0;L<=R;L++)for(let z=0;z<=P;z++)M.drawImage(w,T*L,k*z,T,k,0,0,T,k);return e.canvasFactory.destroy(_),{canvas:A.canvas,canvasEntry:A,scaleX:S.scale,scaleY:C.scale,offsetX:n,offsetY:i}}return{canvas:_.canvas,canvasEntry:_,scaleX:y.scale,scaleY:b.scale,offsetX:n,offsetY:i}}getSizeAndScale(e,t,n){const i=Math.max(P0.MAX_PATTERN_SIZE,t);let r=Math.ceil(e*n);return r>=i?r=i:n=r/e,{scale:n,size:r}}clipBbox(e,t,n,i,r){const o=i-t,a=r-n,c=new Path2D;c.rect(t,n,o,a),Be.axialAlignedBoundingBox([t,n,i,r],Cs(e.ctx),e.current.minMax),e.ctx.clip(c),e.current.updateClipFromPath()}setFillAndStrokeStyleToContext(e,t,n){const i=e.ctx,r=e.current;switch(r.patternFill=r.patternStroke=!1,t){case CR.COLORED:const{fillStyle:o,strokeStyle:a}=this.ctx;i.fillStyle=r.fillColor=o,i.strokeStyle=r.strokeColor=a;break;case CR.UNCOLORED:i.fillStyle=i.strokeStyle=n,r.fillColor=r.strokeColor=n;break;default:throw new _ee(`Unsupported paint type: ${t}`)}}isModifyingCurrentTransform(){return!1}getPattern(e,t,n,i,r){const o=i!==hi.SHADING?Be.transform(n,this.patternBaseMatrix):n,a=this.createPatternCanvas(t,r);let c=new DOMMatrix(o);c=c.translate(a.offsetX,a.offsetY),c=c.scale(1/a.scaleX,1/a.scaleY);const l=e.createPattern(a.canvas,"repeat");return t.canvasFactory.destroy(a.canvasEntry),l.setTransform(c),l}};_e(P0,"MAX_PATTERN_SIZE",3e3);let Hv=P0;function vte({src:s,srcPos:e=0,dest:t,width:n,height:i,nonBlackColor:r=4294967295,inverseDecode:o=!1}){const a=Ts.isLittleEndian?4278190080:255,[c,l]=o?[r,a]:[a,r],u=n>>3,h=n&7,d=c^l,p=s.length;t=new Uint32Array(t.buffer);let m=0;for(let v=0;v<i;++v){for(const y=e+u;e<y;++e,m+=8){const b=s[e];t[m]=c^-(b>>7&1)&d,t[m+1]=c^-(b>>6&1)&d,t[m+2]=c^-(b>>5&1)&d,t[m+3]=c^-(b>>4&1)&d,t[m+4]=c^-(b>>3&1)&d,t[m+5]=c^-(b>>2&1)&d,t[m+6]=c^-(b>>1&1)&d,t[m+7]=c^-(b&1)&d}if(h===0)continue;const g=e<p?s[e++]:255;for(let y=0;y<h;++y,++m)t[m]=c^-(g>>7-y&1)&d}return{srcPos:e,destPos:m}}const TR=16,AR=100,yte=15,ER=10,gr=16,JC=new DOMMatrix,eo=new Float32Array(2);function MR(s,e){if(s._removeMirroring)throw new Error("Context is already forwarding operations.");const t=new Map;for(const n of["save","restore","rotate","scale","translate","transform","setTransform","resetTransform","clip","moveTo","lineTo","bezierCurveTo","quadraticCurveTo","arc","arcTo","ellipse","rect","roundRect","closePath","beginPath"]){const i=s[n];typeof i!="function"||typeof e[n]!="function"||(t.set(n,i),s[n]=function(...r){return e[n](...r),i.apply(this,r)})}s._removeMirroring=()=>{for(const[n,i]of t)s[n]=i;delete s._removeMirroring}}function K_(s,e,t,n,i,r,o,a,c,l){const[u,h,d,p,m,v]=Cs(s);if(h===0&&d===0){const b=o*u+m,_=Math.round(b),w=a*p+v,S=Math.round(w),C=(o+c)*u+m,T=Math.abs(Math.round(C)-_)||1,k=(a+l)*p+v,A=Math.abs(Math.round(k)-S)||1;return s.setTransform(Math.sign(u),0,0,Math.sign(p),_,S),s.drawImage(e,t,n,i,r,0,0,T,A),s.setTransform(u,h,d,p,m,v),[T,A]}if(u===0&&p===0){const b=a*d+m,_=Math.round(b),w=o*h+v,S=Math.round(w),C=(a+l)*d+m,T=Math.abs(Math.round(C)-_)||1,k=(o+c)*h+v,A=Math.abs(Math.round(k)-S)||1;return s.setTransform(0,Math.sign(h),Math.sign(d),0,_,S),s.drawImage(e,t,n,i,r,0,0,A,T),s.setTransform(u,h,d,p,m,v),[A,T]}s.drawImage(e,t,n,i,r,o,a,c,l);const g=Math.hypot(u,h),y=Math.hypot(d,p);return[g*c,y*l]}class xR{constructor(e,t){_e(this,"alphaIsShape",!1);_e(this,"fontSize",0);_e(this,"fontSizeScale",1);_e(this,"textMatrix",null);_e(this,"textMatrixScale",1);_e(this,"fontMatrix",vT);_e(this,"leading",0);_e(this,"x",0);_e(this,"y",0);_e(this,"lineX",0);_e(this,"lineY",0);_e(this,"charSpacing",0);_e(this,"wordSpacing",0);_e(this,"textHScale",1);_e(this,"textRenderingMode",An.FILL);_e(this,"textRise",0);_e(this,"fillColor","#000000");_e(this,"strokeColor","#000000");_e(this,"tilingPatternDims",null);_e(this,"patternFill",!1);_e(this,"patternStroke",!1);_e(this,"fillAlpha",1);_e(this,"strokeAlpha",1);_e(this,"lineWidth",1);_e(this,"activeSMask",null);_e(this,"transferMaps","none");_e(this,"minMax",Wh.slice());this.clipBox=new Float32Array([0,0,e,t])}clone(){var t;const e=Object.create(this);return e.clipBox=this.clipBox.slice(),e.minMax=this.minMax.slice(),e.tilingPatternDims=(t=this.tilingPatternDims)==null?void 0:t.slice(),e}getPathBoundingBox(e=hi.FILL,t=null){const n=this.minMax.slice();if(e===hi.STROKE){t||es("Stroke bounding box must include transform."),Be.singularValueDecompose2dScale(t,eo);const i=eo[0]*this.lineWidth/2,r=eo[1]*this.lineWidth/2;n[0]-=i,n[1]-=r,n[2]+=i,n[3]+=r}return n}updateClipFromPath(){const e=Be.intersect(this.clipBox,this.getPathBoundingBox());this.startNewPathAndClipBox(e||[0,0,0,0])}isEmptyClip(){return this.minMax[0]===1/0}startNewPathAndClipBox(e){this.clipBox.set(e,0),this.minMax.set(Wh,0)}getClippedPathBoundingBox(e=hi.FILL,t=null){return Be.intersect(this.clipBox,this.getPathBoundingBox(e,t))}}function IR(s,e){if(e instanceof ImageData){s.putImageData(e,0,0);return}const t=e.height,n=e.width,i=t%gr,r=(t-i)/gr,o=i===0?r:r+1,a=s.createImageData(n,gr);let c=0,l;const u=e.data,h=a.data;let d,p,m,v;if(e.kind===CS.GRAYSCALE_1BPP){const g=u.byteLength,y=new Uint32Array(h.buffer,0,h.byteLength>>2),b=y.length,_=n+7>>3,w=4294967295,S=Ts.isLittleEndian?4278190080:255;for(d=0;d<o;d++){for(m=d<r?gr:i,l=0,p=0;p<m;p++){const C=g-c;let T=0;const k=C>_?n:C*8-7,A=k&-8;let M=0,R=0;for(;T<A;T+=8)R=u[c++],y[l++]=R&128?w:S,y[l++]=R&64?w:S,y[l++]=R&32?w:S,y[l++]=R&16?w:S,y[l++]=R&8?w:S,y[l++]=R&4?w:S,y[l++]=R&2?w:S,y[l++]=R&1?w:S;for(;T<k;T++)M===0&&(R=u[c++],M=128),y[l++]=R&M?w:S,M>>=1}for(;l<b;)y[l++]=0;s.putImageData(a,0,d*gr)}}else if(e.kind===CS.RGBA_32BPP){for(p=0,v=n*gr*4,d=0;d<r;d++)h.set(u.subarray(c,c+v)),c+=v,s.putImageData(a,0,p),p+=gr;d<o&&(v=n*i*4,h.set(u.subarray(c,c+v)),s.putImageData(a,0,p))}else if(e.kind===CS.RGB_24BPP)for(m=gr,v=n*m,d=0;d<o;d++){for(d>=r&&(m=i,v=n*m),l=0,p=v;p--;)h[l++]=u[c++],h[l++]=u[c++],h[l++]=u[c++],h[l++]=255;s.putImageData(a,0,d*gr)}else throw new Error(`bad image kind: ${e.kind}`)}function RR(s,e){if(e.bitmap){s.drawImage(e.bitmap,0,0);return}const t=e.height,n=e.width,i=t%gr,r=(t-i)/gr,o=i===0?r:r+1,a=s.createImageData(n,gr);let c=0;const l=e.data,u=a.data;for(let h=0;h<o;h++){const d=h<r?gr:i;({srcPos:c}=vte({src:l,srcPos:c,dest:u,width:n,height:d,nonBlackColor:0})),s.putImageData(a,0,h*gr)}}function kh(s,e){const t=["strokeStyle","fillStyle","fillRule","globalAlpha","lineWidth","lineCap","lineJoin","miterLimit","globalCompositeOperation","font","filter"];for(const n of t)s[n]!==void 0&&(e[n]=s[n]);s.setLineDash!==void 0&&(e.setLineDash(s.getLineDash()),e.lineDashOffset=s.lineDashOffset)}function Q_(s){s.strokeStyle=s.fillStyle="#000000",s.fillRule="nonzero",s.globalAlpha=1,s.lineWidth=1,s.lineCap="butt",s.lineJoin="miter",s.miterLimit=10,s.globalCompositeOperation="source-over",s.font="10px sans-serif",s.setLineDash!==void 0&&(s.setLineDash([]),s.lineDashOffset=0);const{filter:e}=s;e!=="none"&&e!==""&&(s.filter="none")}function LR(s,e){if(e)return!0;Be.singularValueDecompose2dScale(s,eo);const t=Math.fround(ll.pixelRatio*uh.PDF_TO_CSS_UNITS);return eo[0]<=t&&eo[1]<=t}const bte=["butt","round","square"],_te=["miter","round","bevel"],Ste={},PR={};var Br,Au,Cd,Td,Ad,Ed,Md,Eu,xd,za,ct,KT,QT,XT,YT,JT,rr,bi,ZT,BS;const CM=class CM{constructor(e,t,n,i,r,{optionalContentConfig:o,markedContentStack:a=null},c,l,u,h){D(this,ct);D(this,Br,0);D(this,Au,0);D(this,Cd,null);D(this,Td,null);D(this,Ad,null);D(this,Ed,null);D(this,Md,1);D(this,Eu);D(this,xd,null);D(this,za,[]);this.ctx=e,this.current=new xR(this.ctx.canvas.width,this.ctx.canvas.height),this.stateStack=[],this.pendingClip=null,this.pendingEOFill=!1,this.commonObjs=t,this.objs=n,this.canvasFactory=i,this.filterFactory=r,this.groupStack=[],this.baseTransform=null,this.baseTransformStack=[],this.groupLevel=0,this.smaskStack=[],this.tempSMask=null,this.smaskGroupCanvases=[],this.smaskPreparedEntry=null,this.smaskPreparedFor=null,this.smaskPreparedOffsetX=0,this.smaskPreparedOffsetY=0,this.smaskPreparedOOBAlpha=null,this.suspendedCtx=null,this.contentVisible=!0,this.markedContentStack=a||[],this.optionalContentConfig=o,this.cachedPatterns=new Map,this.annotationCanvasMap=c,this.viewportScale=1,this.outputScaleX=1,this.outputScaleY=1,this.pageColors=l,this._cachedScaleForStroking=[-1,0],this._cachedGetSinglePixelWidth=null,this._cachedBitmapsMap=new Map,this.dependencyTracker=u??null,this.imagesTracker=h??null}getObject(e,t,n=null){var i;return typeof t=="string"?((i=this.dependencyTracker)==null||i.recordNamedDependency(e,t),t.startsWith("g_")?this.commonObjs.get(t):this.objs.get(t)):n}beginDrawing({transform:e,viewport:t,transparency:n=!1,background:i=null}){const r=this.ctx.canvas.width,o=this.ctx.canvas.height,a=this.ctx.fillStyle;if(this.ctx.fillStyle=i||"#ffffff",this.ctx.fillRect(0,0,r,o),this.ctx.fillStyle=a,n){const c=this.transparentCanvasEntry=this.canvasFactory.create(r,o);this.compositeCtx=this.ctx,{canvas:this.transparentCanvas,context:this.ctx}=c,this.ctx.save(),this.ctx.transform(...Cs(this.compositeCtx))}this.ctx.save(),Q_(this.ctx),e&&(this.ctx.transform(...e),this.outputScaleX=e[0],this.outputScaleY=e[3]),this.ctx.transform(...t.transform),this.viewportScale=t.scale,this.baseTransform=Cs(this.ctx)}executeOperatorList(e,t,n,i,r){var y;const o=e.argsArray,a=e.fnArray;let c=t||0;const l=o.length;if(l===c)return c;const u=l-c>ER&&typeof n=="function",h=u?Date.now()+yte:0;let d=0;const p=this.commonObjs,m=this.objs;let v,g;for(;;){if(i!==void 0){if(c===i.nextBreakPoint)return i.breakIt(c,n),c;if(i.shouldSkip(c)){if(++c===l)return c;continue}}if(!r||r(c))if(v=a[c],g=o[c]??null,v!==Il.dependency)g===null?this[v](c):this[v](c,...g);else for(const b of g){(y=this.dependencyTracker)==null||y.recordNamedData(b,c);const _=b.startsWith("g_")?p:m;if(!_.has(b))return _.get(b,n),c}if(c++,c===l)return c;if(u&&++d>ER){if(Date.now()>h)return n(),c;d=0}}}endDrawing(){B(this,ct,KT).call(this);for(const e of this.smaskGroupCanvases)this.canvasFactory.destroy(e);this.smaskGroupCanvases.length=0,this._clearPreparedSMask(),this.tempSMask=null,this.smaskStack.length=0;for(const e of f(this,za))B(this,ct,BS).call(this,e);f(this,za).length=0,x(this,Cd,null),x(this,Td,null),x(this,Ad,null),x(this,Ed,null),x(this,Md,1),x(this,xd,null),x(this,Au,0),x(this,Br,0),this.cachedPatterns.clear();for(const e of this._cachedBitmapsMap.values()){for(const t of e.values())typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement&&(t.width=t.height=0);e.clear()}this._cachedBitmapsMap.clear(),B(this,ct,QT).call(this)}_scaleImage(e,t){const n=e.width??e.displayWidth,i=e.height??e.displayHeight,r=Math.max(Math.hypot(t[0],t[1]),1),o=Math.max(Math.hypot(t[2],t[3]),1),a=[];let c=r,l=o,u=n,h=i;for(;c>2&&u>1||l>2&&h>1;){let y=u,b=h;c>2&&u>1&&(y=Math.ceil(u/2),c/=u/y),l>2&&h>1&&(b=Math.ceil(h/2),l/=h/b),a.push({newWidth:y,newHeight:b}),u=y,h=b}if(a.length===0)return{img:e,paintWidth:n,paintHeight:i,tmpCanvas:null};if(a.length===1){const{newWidth:y,newHeight:b}=a[0],_=this.canvasFactory.create(y,b);return _.context.drawImage(e,0,0,n,i,0,0,y,b),{img:_.canvas,paintWidth:y,paintHeight:b,tmpCanvas:_}}let d=this.canvasFactory.create(1,1),p=this.canvasFactory.create(1,1),m=n,v=i,g=e;for(const{newWidth:y,newHeight:b}of a)this.canvasFactory.reset(p,y,b),p.context.drawImage(g,0,0,m,v,0,0,y,b),[d,p]=[p,d],g=d.canvas,m=y,v=b;return this.canvasFactory.destroy(p),{img:d.canvas,paintWidth:m,paintHeight:v,tmpCanvas:d}}_createMaskCanvas(e,t){var R,P;const n=this.ctx,{width:i,height:r}=t,o=this.current.fillColor,a=this.current.patternFill,c=Cs(n);let l,u,h,d;if((t.bitmap||t.data)&&t.count>1){const L=t.bitmap||t.data.buffer;u=JSON.stringify(a?c:[c.slice(0,4),o]),l=this._cachedBitmapsMap.getOrInsertComputed(L,lM);const z=l.get(u);if(z&&!a){const Q=Math.round(Math.min(c[0],c[2])+c[4]),W=Math.round(Math.min(c[1],c[3])+c[5]);return(R=this.dependencyTracker)==null||R.recordDependencies(e,uo.transformAndFill),{canvas:z,offsetX:Q,offsetY:W}}h=z}h||(d=this.canvasFactory.create(i,r),RR(d.context,t));let p=Be.transform(c,[1/i,0,0,-1/r,0,0]);p=Be.transform(p,[1,0,0,1,0,-r]);const m=Wh.slice();Be.axialAlignedBoundingBox([0,0,i,r],p,m);const[v,g,y,b]=m,_=Math.round(y-v)||1,w=Math.round(b-g)||1,S=this.canvasFactory.create(_,w),C=S.context,T=v,k=g;C.translate(-T,-k),C.transform(...p);let A=null;if(!h){const L=this._scaleImage(d.canvas,ka(C));h=L.img,A=L.tmpCanvas,h!==d.canvas&&(this.canvasFactory.destroy(d),d=null),l&&a&&(l.set(u,h),A=null,d=null)}C.imageSmoothingEnabled=LR(Cs(C),t.interpolate),K_(C,h,0,0,h.width,h.height,0,0,i,r),A&&this.canvasFactory.destroy(A),d&&this.canvasFactory.destroy(d),C.globalCompositeOperation="source-in";const M=Be.transform(ka(C),[1,0,0,1,-T,-k]);return C.fillStyle=a?o.getPattern(n,this,M,hi.FILL,e):o,C.fillRect(0,0,i,r),l&&!a&&l.set(u,S.canvas),(P=this.dependencyTracker)==null||P.recordDependencies(e,uo.transformAndFill),{canvas:S.canvas,canvasEntry:l&&!a?null:S,offsetX:Math.round(T),offsetY:Math.round(k)}}setLineWidth(e,t){var n;(n=this.dependencyTracker)==null||n.recordSimpleData("lineWidth",e),t!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=t,this.ctx.lineWidth=t}setLineCap(e,t){var n;(n=this.dependencyTracker)==null||n.recordSimpleData("lineCap",e),this.ctx.lineCap=bte[t]}setLineJoin(e,t){var n;(n=this.dependencyTracker)==null||n.recordSimpleData("lineJoin",e),this.ctx.lineJoin=_te[t]}setMiterLimit(e,t){var n;(n=this.dependencyTracker)==null||n.recordSimpleData("miterLimit",e),this.ctx.miterLimit=t}setDash(e,t,n){var r;(r=this.dependencyTracker)==null||r.recordSimpleData("dash",e);const i=this.ctx;i.setLineDash!==void 0&&(i.setLineDash(t),i.lineDashOffset=n)}setRenderingIntent(e,t){}setFlatness(e,t){}setGState(e,t){var n,i,r,o,a;for(const[c,l]of t)switch(c){case"LW":this.setLineWidth(e,l);break;case"LC":this.setLineCap(e,l);break;case"LJ":this.setLineJoin(e,l);break;case"ML":this.setMiterLimit(e,l);break;case"D":this.setDash(e,l[0],l[1]);break;case"RI":this.setRenderingIntent(e,l);break;case"FL":this.setFlatness(e,l);break;case"Font":this.setFont(e,l[0],l[1]);break;case"CA":(n=this.dependencyTracker)==null||n.recordSimpleData("strokeAlpha",e),this.current.strokeAlpha=l;break;case"ca":(i=this.dependencyTracker)==null||i.recordSimpleData("fillAlpha",e),this.ctx.globalAlpha=this.current.fillAlpha=l;break;case"BM":(r=this.dependencyTracker)==null||r.recordSimpleData("globalCompositeOperation",e),this.ctx.globalCompositeOperation=l;break;case"SMask":(o=this.dependencyTracker)==null||o.recordSimpleData("SMask",e),this.current.activeSMask=l?this.tempSMask:null,this.current.activeSMask&&(this.current.activeSMask.blendMode=this.ctx.globalCompositeOperation),this.tempSMask=null,this.checkSMaskState(e);break;case"TR":(a=this.dependencyTracker)==null||a.recordSimpleData("filter",e),this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(l);break}}get inSMaskMode(){return!!this.suspendedCtx}_clearPreparedSMask(){this.smaskPreparedEntry&&(this.canvasFactory.destroy(this.smaskPreparedEntry),this.smaskPreparedEntry=null),this.smaskPreparedFor=null,this.smaskPreparedOffsetX=0,this.smaskPreparedOffsetY=0,this.smaskPreparedOOBAlpha=null}_ensurePreparedSMask(e){e!==this.smaskPreparedFor&&(this._clearPreparedSMask(),this._prepareSMaskCanvas(e))}checkSMaskState(e){const t=this.inSMaskMode;this.current.activeSMask&&!t?this.beginSMaskMode(e):!this.current.activeSMask&&t?this.endSMaskMode():this.current.activeSMask&&t&&this._ensurePreparedSMask(this.current.activeSMask)}_prepareSMaskCanvas(e){const{canvas:t,subtype:n,backdrop:i,transferMap:r}=e,o=n==="Luminosity"||n==="Alpha"&&r;if(!o&&!(n==="Luminosity"&&i)){this.smaskPreparedFor=e;return}let a;if(n==="Luminosity"&&i){const[b,_,w]=n_(i),S=Math.round(.3*b+.59*_+.11*w);a=(r==null?void 0:r[S])??S}else a=(r==null?void 0:r[0])??0;const c=4,{width:l,height:u}=this.ctx.canvas,h=t.width*t.height,d=l*u<c*h,p=o?{url:n==="Alpha"?this.filterFactory.addAlphaFilter(r):this.filterFactory.addLuminosityFilter(r),subtype:n,transferMap:r}:null,m=n==="Luminosity"?i:null;let v,g,y;d?(v=this._bakeSMaskCanvas(t,e.offsetX,e.offsetY,l,u,m,p),g=0,y=0):(v=this._bakeSMaskCanvas(t,0,0,t.width,t.height,m,p),g=e.offsetX,y=e.offsetY),this.smaskPreparedEntry=v,this.smaskPreparedFor=e,this.smaskPreparedOffsetX=g,this.smaskPreparedOffsetY=y,this.smaskPreparedOOBAlpha=!d&&a!==0?a:null}_bakeSMaskCanvas(e,t,n,i,r,o,a){!o&&!a&&es("_bakeSMaskCanvas with neither backdrop nor filter");const c=this.canvasFactory.create(i,r),l=c.context;if(l.drawImage(e,t,n),o&&(l.globalCompositeOperation="destination-atop",l.fillStyle=o,l.fillRect(0,0,i,r)),!a)return c;const u=this.canvasFactory.create(i,r),h=u.context;h.filter=a.url;const d=Ts.isCanvasFilterSupported&&h.filter!=="none"&&h.filter!=="";if(h.drawImage(c.canvas,0,0),Ts.isCanvasFilterSupported&&(h.filter="none"),!d){const p=h.getImageData(0,0,i,r),{data:m}=p,{transferMap:v}=a;if(a.subtype==="Luminosity")for(let g=0,y=m.length;g<y;g+=4){const b=.3*m[g]+.59*m[g+1]+.11*m[g+2]+.5|0;m[g]=m[g+1]=m[g+2]=0,m[g+3]=(v==null?void 0:v[b])??b}else for(let g=3,y=m.length;g<y;g+=4)m[g]=v[m[g]];h.putImageData(p,0,0)}return this.canvasFactory.destroy(c),u}beginSMaskMode(e){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");const{width:t,height:n}=this.ctx.canvas,i=this.canvasFactory.create(t,n);this.smaskScratchCanvas=i,this.suspendedCtx=this.ctx;const r=this.ctx=i.context;r.setTransform(this.suspendedCtx.getTransform()),kh(this.suspendedCtx,r),MR(r,this.suspendedCtx),this._ensurePreparedSMask(this.current.activeSMask),this.setGState(e,[["BM","source-over"]])}endSMaskMode(){if(!this.inSMaskMode)throw new Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring(),kh(this.ctx,this.suspendedCtx),this.ctx=this.suspendedCtx,this.suspendedCtx=null,this.canvasFactory.destroy(this.smaskScratchCanvas),this.smaskScratchCanvas=null,this._clearPreparedSMask()}compose(e){if(!this.current.activeSMask)return;e=e?[Math.floor(e[0]),Math.floor(e[1]),Math.ceil(e[2]),Math.ceil(e[3])]:[0,0,this.ctx.canvas.width,this.ctx.canvas.height];const t=this.current.activeSMask,n=this.suspendedCtx,i=f(this,Au)>0&&n===this.ctx;this.composeSMask(i?null:n,t,this.ctx,e),!i&&(this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height),this.ctx.restore())}composeSMask(e,t,n,i){const r=i[0],o=i[1],a=i[2]-r,c=i[3]-o;if(a===0||c===0)return;const l=this.smaskPreparedEntry;if(l){let u=r,h=o,d=a,p=c;const m=this.smaskPreparedOOBAlpha,v=m!==null;if(v){u=Math.max(r,t.offsetX),h=Math.max(o,t.offsetY);const g=Math.min(r+a,t.offsetX+t.canvas.width),y=Math.min(o+c,t.offsetY+t.canvas.height);d=g-u,p=y-h}if(d>0&&p>0){const g=u-this.smaskPreparedOffsetX,y=h-this.smaskPreparedOffsetY;n.save(),n.globalAlpha=1,n.setTransform(1,0,0,1,0,0);const b=new Path2D;b.rect(u,h,d,p),n.clip(b),n.globalCompositeOperation="destination-in",n.drawImage(l.canvas,g,y,d,p,u,h,d,p),n.restore()}v&&m<255&&this._applySMaskOOBAlpha(n,r,o,a,c,u,h,u+d,h+p,m)}else this.genericComposeSMask(t,n,a,c,r,o);e&&(e.save(),e.globalAlpha=1,e.globalCompositeOperation=t.blendMode||"source-over",e.setTransform(1,0,0,1,0,0),e.drawImage(n.canvas,r,o,a,c,r,o,a,c),e.restore())}_applySMaskOOBAlpha(e,t,n,i,r,o,a,c,l,u){const h=o<c&&a<l;if(h&&o===t&&a===n&&c===t+i&&l===n+r)return;const d=new Path2D;d.rect(t,n,i,r),h&&d.rect(o,a,c-o,l-a),e.save(),e.globalAlpha=u/255,e.setTransform(1,0,0,1,0,0),e.clip(d,"evenodd"),e.globalCompositeOperation="destination-in",e.fillStyle="#000000",e.fillRect(t,n,i,r),e.restore()}genericComposeSMask(e,t,n,i,r,o){const{context:a,offsetX:c,offsetY:l}=e;t.save(),t.globalAlpha=1,t.setTransform(1,0,0,1,0,0);const u=new Path2D;u.rect(r,o,n,i),t.clip(u),t.globalCompositeOperation="destination-in",t.drawImage(a.canvas,r-c,o-l,n,i,r,o,n,i),t.restore()}save(e){var n;this.inSMaskMode&&kh(this.ctx,this.suspendedCtx),this.ctx.save();const t=this.current;this.stateStack.push(t),this.current=t.clone(),(n=this.dependencyTracker)==null||n.save(e)}restore(e){var t;if((t=this.dependencyTracker)==null||t.restore(e),this.stateStack.length===0){this.inSMaskMode&&this.endSMaskMode();return}this.current=this.stateStack.pop(),this.ctx.restore(),this.inSMaskMode&&(kh(this.suspendedCtx,this.ctx),this.ctx.setTransform(this.suspendedCtx.getTransform())),this.checkSMaskState(e),this.pendingClip=null,this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}transform(e,t,n,i,r,o,a){var c;(c=this.dependencyTracker)==null||c.recordIncrementalData("transform",e),this.ctx.transform(t,n,i,r,o,a),this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}constructPath(e,t,n,i){let[r]=n;if(!i){r||(r=n[0]=new Path2D),t!==Il.stroke&&t!==Il.closeStroke&&(this.current.tilingPatternDims=null),this[t](e,r);return}if(this.dependencyTracker!==null){const a=t===Il.stroke?this.current.lineWidth/2:0;this.dependencyTracker.resetBBox(e).recordBBox(e,this.ctx,i[0]-a,i[2]+a,i[1]-a,i[3]+a).recordDependencies(e,["transform"])}r instanceof Path2D||(r=n[0]=DD(r)),Be.axialAlignedBoundingBox(i,Cs(this.ctx),this.current.minMax);const o=this.current.tilingPatternDims;if(o&&t!==Il.stroke&&t!==Il.closeStroke&&this.current.fillColor instanceof Hv){const a=Be.intersect(this.current.clipBox,this.current.minMax);a?this.current.fillColor.updatePatternDims(a,o):this.current.tilingPatternDims=null}this[t](e,r),this._pathStartIdx=e}closePath(e){this.ctx.closePath()}stroke(e,t,n=!0){var a;const i=n&&B(this,ct,rr).call(this,this.current.strokeAlpha),r=this.ctx,o=this.current.strokeColor;if(r.globalAlpha=this.current.strokeAlpha,this.contentVisible)if(typeof o=="object"&&(o!=null&&o.getPattern)){const c=o.isModifyingCurrentTransform()?r.getTransform():null;if(r.save(),r.strokeStyle=o.getPattern(r,this,ka(r),hi.STROKE,e),c){const l=new Path2D;l.addPath(t,r.getTransform().invertSelf().multiplySelf(c)),t=l}this.rescaleAndStroke(t,!1),r.restore()}else this.rescaleAndStroke(t,!0);(a=this.dependencyTracker)==null||a.recordDependencies(e,uo.stroke),n&&this.consumePath(e,t,this.current.getClippedPathBoundingBox(hi.STROKE,Cs(this.ctx))),r.globalAlpha=this.current.fillAlpha,B(this,ct,bi).call(this,i)}closeStroke(e,t){this.stroke(e,t)}fill(e,t,n=!0){var u,h,d;const i=n&&B(this,ct,rr).call(this,this.current.fillAlpha),r=this.ctx,o=this.current.fillColor,a=this.current.patternFill;let c=!1;const l=this.current.getClippedPathBoundingBox();if((u=this.dependencyTracker)==null||u.recordDependencies(e,uo.fill),a){const p=this.current.tilingPatternDims,m=p&&o.canSkipPatternCanvas(p);if(m){o.drawPattern(this,t,this.pendingEOFill,m,e),this.pendingEOFill=!1,n&&this.consumePath(e,t,l),this.current.tilingPatternDims=null,B(this,ct,bi).call(this,i);return}const v=o.isModifyingCurrentTransform()?r.getTransform():null;if((h=this.dependencyTracker)==null||h.save(e),r.save(),r.fillStyle=o.getPattern(r,this,ka(r),hi.FILL,e),v){const g=new Path2D;g.addPath(t,r.getTransform().invertSelf().multiplySelf(v)),t=g}c=!0}this.contentVisible&&l!==null&&(this.pendingEOFill?(r.fill(t,"evenodd"),this.pendingEOFill=!1):r.fill(t)),c&&(r.restore(),(d=this.dependencyTracker)==null||d.restore(e)),n&&this.consumePath(e,t,l),B(this,ct,bi).call(this,i)}eoFill(e,t){this.pendingEOFill=!0,this.fill(e,t)}fillStroke(e,t){const n=B(this,ct,rr).call(this,Math.min(this.current.fillAlpha,this.current.strokeAlpha));this.fill(e,t,!1),this.stroke(e,t,!1),this.consumePath(e,t),B(this,ct,bi).call(this,n)}eoFillStroke(e,t){this.pendingEOFill=!0,this.fillStroke(e,t)}closeFillStroke(e,t){this.fillStroke(e,t)}closeEOFillStroke(e,t){this.pendingEOFill=!0,this.fillStroke(e,t)}endPath(e,t){this.consumePath(e,t)}rawFillPath(e,t){var i;const n=B(this,ct,rr).call(this,this.current.fillAlpha);this.ctx.fill(t),(i=this.dependencyTracker)==null||i.recordDependencies(e,uo.rawFillPath).recordOperation(e),B(this,ct,bi).call(this,n)}clip(e){var t;(t=this.dependencyTracker)==null||t.recordFutureForcedDependency("clipMode",e),this.pendingClip=Ste}eoClip(e){var t;(t=this.dependencyTracker)==null||t.recordFutureForcedDependency("clipMode",e),this.pendingClip=PR}beginText(e){var t;this.current.textMatrix=null,this.current.textMatrixScale=1,this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0,(t=this.dependencyTracker)==null||t.recordOpenMarker(e).resetIncrementalData("sameLineText").resetIncrementalData("moveText",e)}endText(e){const t=this.pendingTextPaths,n=this.ctx;if(this.dependencyTracker){const{dependencyTracker:i}=this;t!==void 0&&i.recordFutureForcedDependency("textClip",i.getOpenMarker()).recordFutureForcedDependency("textClip",e),i.recordCloseMarker(e)}if(t!==void 0){const i=new Path2D,r=n.getTransform().invertSelf();for(const{transform:o,x:a,y:c,fontSize:l,path:u}of t)u&&i.addPath(u,new DOMMatrix(o).preMultiplySelf(r).translate(a,c).scale(l,-l));n.clip(i)}delete this.pendingTextPaths}setCharSpacing(e,t){var n;(n=this.dependencyTracker)==null||n.recordSimpleData("charSpacing",e),this.current.charSpacing=t}setWordSpacing(e,t){var n;(n=this.dependencyTracker)==null||n.recordSimpleData("wordSpacing",e),this.current.wordSpacing=t}setHScale(e,t){var n;(n=this.dependencyTracker)==null||n.recordSimpleData("hScale",e),this.current.textHScale=t/100}setLeading(e,t){var n;(n=this.dependencyTracker)==null||n.recordSimpleData("leading",e),this.current.leading=-t}setFont(e,t,n){var h,d;(h=this.dependencyTracker)==null||h.recordSimpleData("font",e).recordSimpleDataFromNamed("fontObj",t,e);const i=this.commonObjs.get(t),r=this.current;if(!i)throw new Error(`Can't find font for ${t}`);if(r.fontMatrix=i.fontMatrix||vT,(r.fontMatrix[0]===0||r.fontMatrix[3]===0)&&kt("Invalid font matrix for font "+t),n<0?(n=-n,r.fontDirection=-1):r.fontDirection=1,this.current.font=i,this.current.fontSize=n,i.isType3Font)return;const o=i.loadedName||"sans-serif",a=((d=i.systemFontInfo)==null?void 0:d.css)||`"${o}", ${i.fallbackName}`;let c="normal";i.black?c="900":i.bold&&(c="bold");const l=i.italic?"italic":"normal";let u=n;n<TR?u=TR:n>AR&&(u=AR),this.current.fontSizeScale=n/u,this.ctx.font=`${l} ${c} ${u}px ${a}`}setTextRenderingMode(e,t){var n;(n=this.dependencyTracker)==null||n.recordSimpleData("textRenderingMode",e),this.current.textRenderingMode=t}setTextRise(e,t){var n;(n=this.dependencyTracker)==null||n.recordSimpleData("textRise",e),this.current.textRise=t}moveText(e,t,n){var i;(i=this.dependencyTracker)==null||i.resetIncrementalData("sameLineText").recordIncrementalData("moveText",e),this.current.x=this.current.lineX+=t,this.current.y=this.current.lineY+=n}setLeadingMoveText(e,t,n){this.setLeading(e,-n),this.moveText(e,t,n)}setTextMatrix(e,t){var i;(i=this.dependencyTracker)==null||i.resetIncrementalData("sameLineText").recordSimpleData("textMatrix",e);const{current:n}=this;n.textMatrix=t,n.textMatrixScale=Math.hypot(t[0],t[1]),n.x=n.lineX=0,n.y=n.lineY=0}nextLine(e){var t;this.moveText(e,0,this.current.leading),(t=this.dependencyTracker)==null||t.recordIncrementalData("moveText",this.dependencyTracker.getSimpleIndex("leading")??e)}paintChar(e,t,n,i,r,o){var y,b,_,w;const a=this.ctx,c=this.current,l=c.font,u=c.textRenderingMode,h=c.fontSize/c.fontSizeScale,d=u&An.FILL_STROKE_MASK,p=!!(u&An.ADD_TO_PATH_FLAG),m=c.patternFill&&!l.missingFile,v=c.patternStroke&&!l.missingFile;let g;if((l.disableFontFace||p||m||v)&&!l.missingFile&&(g=l.getPathGenerator(this.commonObjs,t)),g&&(l.disableFontFace||m||v)){a.save(),a.translate(n,i),a.scale(h,-h),(y=this.dependencyTracker)==null||y.recordCharacterBBox(e,a,l);let S;if(d===An.FILL||d===An.FILL_STROKE)if(r){S=a.getTransform(),a.setTransform(...r);const C=B(this,ct,ZT).call(this,g,S,r);a.fill(C)}else a.fill(g);if(d===An.STROKE||d===An.FILL_STROKE)if(o){S||(S=a.getTransform()),a.setTransform(...o);const{a:C,b:T,c:k,d:A}=S,M=Be.inverseTransform(o),R=Be.transform([C,T,k,A,0,0],M);Be.singularValueDecompose2dScale(R,eo),a.lineWidth*=Math.max(eo[0],eo[1])/h,a.stroke(B(this,ct,ZT).call(this,g,S,o))}else a.lineWidth/=h,a.stroke(g);a.restore()}else(d===An.FILL||d===An.FILL_STROKE)&&(a.fillText(t,n,i),(b=this.dependencyTracker)==null||b.recordCharacterBBox(e,a,l,h,n,i,()=>a.measureText(t))),(d===An.STROKE||d===An.FILL_STROKE)&&(this.dependencyTracker&&((_=this.dependencyTracker)==null||_.recordCharacterBBox(e,a,l,h,n,i,()=>a.measureText(t)).recordDependencies(e,uo.stroke)),a.strokeText(t,n,i));p&&((this.pendingTextPaths||(this.pendingTextPaths=[])).push({transform:Cs(a),x:n,y:i,fontSize:h,path:g}),(w=this.dependencyTracker)==null||w.recordCharacterBBox(e,a,l,h,n,i))}get isFontSubpixelAAEnabled(){const e=this.canvasFactory.create(10,10),t=e.context;t.scale(1.5,1),t.fillText("I",0,10);const n=t.getImageData(0,0,10,10).data;this.canvasFactory.destroy(e);let i=!1;for(let r=3;r<n.length;r+=4)if(n[r]>0&&n[r]<255){i=!0;break}return Tt(this,"isFontSubpixelAAEnabled",i)}showText(e,t){var P,L,z,Q;this.dependencyTracker&&(this.dependencyTracker.recordDependencies(e,uo.showText).resetBBox(e),this.current.textRenderingMode&An.ADD_TO_PATH_FLAG&&this.dependencyTracker.recordFutureForcedDependency("textClip",e).inheritPendingDependenciesAsFutureForcedDependencies());const n=this.current,i=n.font;if(i.isType3Font){const W=B(this,ct,rr).call(this,n.fillAlpha);this.showType3Text(e,t),(P=this.dependencyTracker)==null||P.recordShowTextOperation(e),B(this,ct,bi).call(this,W);return}const r=n.fontSize;if(r===0){(L=this.dependencyTracker)==null||L.recordOperation(e);return}const o=B(this,ct,rr).call(this,n.fillAlpha),a=this.ctx,c=n.fontSizeScale,l=n.charSpacing,u=n.wordSpacing,h=n.fontDirection,d=n.textHScale*h,p=t.length,m=i.vertical,v=m?1:-1,g=i.defaultVMetrics,y=r*n.fontMatrix[0],b=n.textRenderingMode===An.FILL&&!i.disableFontFace&&!n.patternFill;a.save(),n.textMatrix&&a.transform(...n.textMatrix),a.translate(n.x,n.y+n.textRise),h>0?a.scale(d,-1):a.scale(d,1);let _,w;const S=n.textRenderingMode&An.FILL_STROKE_MASK,C=S===An.FILL||S===An.FILL_STROKE,T=S===An.STROKE||S===An.FILL_STROKE;let k=n.lineWidth;const A=n.textMatrixScale;if(A===0||k===0?T&&(k=this.getSinglePixelWidth()):k/=A,c!==1&&(a.scale(c,c),k/=c),a.lineWidth=k,C&&n.patternFill){a.save();const W=n.fillColor.getPattern(a,this,ka(a),hi.FILL,e);_=Cs(a),a.restore(),a.fillStyle=W}if(T&&n.patternStroke){a.save();const W=n.strokeColor.getPattern(a,this,ka(a),hi.STROKE,e);w=Cs(a),a.restore(),a.strokeStyle=W}if(i.isInvalidPDFjsFont){const W=[];let V=0;for(const O of t)W.push(O.unicode),V+=O.width;const N=W.join("");if(a.fillText(N,0,0),this.dependencyTracker!==null){const O=a.measureText(N);this.dependencyTracker.recordBBox(e,this.ctx,-O.actualBoundingBoxLeft,O.actualBoundingBoxRight,-O.actualBoundingBoxAscent,O.actualBoundingBoxDescent).recordShowTextOperation(e)}n.x+=V*y*d,a.restore(),this.compose(),B(this,ct,bi).call(this,o);return}let M=0,R;for(R=0;R<p;++R){const W=t[R];if(typeof W=="number"){M+=v*W*r/1e3;continue}let V=!1;const N=(W.isSpace?u:0)+l,O=W.fontChar,H=W.accent;let G,ee,ie=W.width;if(m){const oe=W.vmetric||g,I=-(W.vmetric?oe[1]:ie*.5)*y,K=oe[2]*y;ie=oe?-oe[0]:ie,G=I/c,ee=(M+K)/c}else G=M/c,ee=0;let ve;if(i.remeasure&&ie>0){ve=a.measureText(O);const oe=ve.width*1e3/r*c;if(ie<oe&&this.isFontSubpixelAAEnabled){const I=ie/oe;V=!0,a.save(),a.scale(I,1),G/=I}else ie!==oe&&(G+=(ie-oe)/2e3*r/c)}if(this.contentVisible&&(W.isInFont||i.missingFile)){if(b&&!H)a.fillText(O,G,ee),(z=this.dependencyTracker)==null||z.recordCharacterBBox(e,a,ve?{bbox:null}:i,r/c,G,ee,()=>ve??a.measureText(O));else if(this.paintChar(e,O,G,ee,_,w),H){const oe=G+r*H.offset.x/c,I=ee-r*H.offset.y/c;this.paintChar(e,H.fontChar,oe,I,_,w)}}const le=m?ie*y-N*h:ie*y+N*h;M+=le,V&&a.restore()}m?n.y-=M:n.x+=M*d,a.restore(),this.compose(),(Q=this.dependencyTracker)==null||Q.recordShowTextOperation(e),B(this,ct,bi).call(this,o)}showType3Text(e,t){const n=this.ctx,i=this.current,r=i.font,o=i.fontSize,a=i.fontDirection,c=r.vertical?1:-1,l=i.charSpacing,u=i.wordSpacing,h=i.textHScale*a,d=i.fontMatrix||vT,p=t.length,m=i.textRenderingMode===An.INVISIBLE;let v,g,y,b;if(m||o===0)return;this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null,n.save(),i.textMatrix&&n.transform(...i.textMatrix),n.translate(i.x,i.y+i.textRise),n.scale(h,a);const _=this.dependencyTracker;for(this.dependencyTracker=_?new cy(_,e):null,v=0;v<p;++v){if(g=t[v],typeof g=="number"){b=c*g*o/1e3,this.ctx.translate(b,0),i.x+=b*h;continue}const w=(g.isSpace?u:0)+l,S=r.charProcOperatorList[g.operatorListId];S?this.contentVisible&&(this.save(),n.scale(o,o),n.transform(...d),this.executeOperatorList(S),this.restore()):kt(`Type3 character "${g.operatorListId}" is not available.`);const C=[g.width,0];Be.applyTransform(C,d),y=C[0]*o+w,n.translate(y,0),i.x+=y*h}n.restore(),_&&(this.dependencyTracker=_)}setCharWidth(e,t,n){}setCharWidthAndBounds(e,t,n,i,r,o,a){var l;const c=new Path2D;c.rect(i,r,o-i,a-r),this.ctx.clip(c),(l=this.dependencyTracker)==null||l.recordBBox(e,this.ctx,i,o,r,a).recordClipBox(e,this.ctx,i,o,r,a),this.endPath(e)}getColorN_Pattern(e,t){let n;if(t[0]==="TilingPattern"){const i=this.baseTransform||Cs(this.ctx),r={createCanvasGraphics:(o,a)=>new CM(o,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack},void 0,void 0,this.dependencyTracker?new cy(this.dependencyTracker,a,!0):null)};n=new Hv(t,this.ctx,r,i)}else n=this._getPattern(e,t[1],t[2]);return n}setStrokeColorN(e,...t){var n;(n=this.dependencyTracker)==null||n.recordSimpleData("strokeColor",e),this.current.strokeColor=this.getColorN_Pattern(e,t),this.current.patternStroke=!0}setFillColorN(e,...t){var i;(i=this.dependencyTracker)==null||i.recordSimpleData("fillColor",e);const n=this.current.fillColor=this.getColorN_Pattern(e,t);this.current.patternFill=!0,this.current.tilingPatternDims=n instanceof Hv?[0,0,0,0]:null}setStrokeRGBColor(e,t){var n;(n=this.dependencyTracker)==null||n.recordSimpleData("strokeColor",e),this.ctx.strokeStyle=this.current.strokeColor=t,this.current.patternStroke=!1}setStrokeTransparent(e){var t;(t=this.dependencyTracker)==null||t.recordSimpleData("strokeColor",e),this.ctx.strokeStyle=this.current.strokeColor="transparent",this.current.patternStroke=!1}setFillRGBColor(e,t){var n;(n=this.dependencyTracker)==null||n.recordSimpleData("fillColor",e),this.ctx.fillStyle=this.current.fillColor=t,this.current.patternFill=!1,this.current.tilingPatternDims=null}setFillTransparent(e){var t;(t=this.dependencyTracker)==null||t.recordSimpleData("fillColor",e),this.ctx.fillStyle=this.current.fillColor="transparent",this.current.patternFill=!1,this.current.tilingPatternDims=null}_getPattern(e,t,n=null){let i;return this.cachedPatterns.has(t)?i=this.cachedPatterns.get(t):(i=mte(this.getObject(e,t)),this.cachedPatterns.set(t,i)),n&&(i.matrix=n),i}shadingFill(e,t){var a;if(!this.contentVisible)return;const n=B(this,ct,rr).call(this,this.current.fillAlpha),i=this.ctx;this.save(e);const r=this._getPattern(e,t);i.fillStyle=r.getPattern(i,this,ka(i),hi.SHADING,e);const o=ka(i);if(o){const{width:c,height:l}=i.canvas,u=Wh.slice();Be.axialAlignedBoundingBox([0,0,c,l],o,u);const[h,d,p,m]=u;this.ctx.fillRect(h,d,p-h,m-d)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);(a=this.dependencyTracker)==null||a.resetBBox(e).recordFullPageBBox(e).recordDependencies(e,uo.transform).recordDependencies(e,uo.fill).recordOperation(e),this.compose(this.current.getClippedPathBoundingBox()),this.restore(e),B(this,ct,bi).call(this,n)}beginInlineImage(){es("Should not call beginInlineImage")}beginImageData(){es("Should not call beginImageData")}paintFormXObjectBegin(e,t,n){var i;if(this.contentVisible&&(this.save(e),this.baseTransformStack.push(this.baseTransform),t&&this.transform(e,...t),this.baseTransform=Cs(this.ctx),n)){Be.axialAlignedBoundingBox(n,this.baseTransform,this.current.minMax);const[r,o,a,c]=n,l=new Path2D;l.rect(r,o,a-r,c-o),this.ctx.clip(l),(i=this.dependencyTracker)==null||i.recordClipBox(e,this.ctx,r,a,o,c),this.endPath(e)}}paintFormXObjectEnd(e){this.contentVisible&&(this.restore(e),this.baseTransform=this.baseTransformStack.pop())}beginGroup(e,t){var b;if(!this.contentVisible)return;this.save(e);const{inSMaskMode:n}=this;n&&(this.endSMaskMode(),this.current.activeSMask=null);const i=this.ctx;if(!t.isolated&&!t.knockout&&f(this,Br)===0&&dk("TODO: Fully support non-isolated non-knockout groups."),!t.needsIsolation&&!t.knockout&&f(this,Br)===0&&i.globalAlpha===1&&i.globalCompositeOperation==="source-over"&&!n){if(t.bbox){let _=new Path2D;const[w,S,C,T]=t.bbox;if(_.rect(w,S,C-w,T-S),t.matrix){const k=new Path2D;k.addPath(_,new DOMMatrix(t.matrix)),_=k}i.clip(_)}this.groupStack.push(null),f(this,za).push(null),this.groupLevel++;return}const r=Cs(i);t.matrix&&i.transform(...t.matrix);const o=[0,0,i.canvas.width,i.canvas.height];let a;t.bbox?(a=Wh.slice(),Be.axialAlignedBoundingBox(t.bbox,Cs(i),a),a=Be.intersect(a,o)||[0,0,0,0]):a=o;const c=Math.floor(a[0]),l=Math.floor(a[1]),u=Math.max(Math.ceil(a[2])-c,1),h=Math.max(Math.ceil(a[3])-l,1);this.current.startNewPathAndClipBox([0,0,u,h]);const d=this.canvasFactory.create(u,h);t.smask&&this.smaskGroupCanvases.push(d);const p=d.context,m=t.knockout&&!t.isolated?i:null,v=!t.isolated&&!t.knockout&&!t.smask&&t.needsIsolation&&f(this,Br)>0,g=t.knockout?this.canvasFactory.create(u,h):null,y=f(this,Br);if(t.knockout?xs(this,Br)._++:x(this,Br,0),p.translate(-c,-l),p.transform(...r),!t.isolated&&!t.smask&&n&&t.needsIsolation&&(p.save(),p.setTransform(1,0,0,1,0,0),p.drawImage(i.canvas,-c,-l),p.restore()),t.bbox){let _=new Path2D;const[w,S,C,T]=t.bbox;if(_.rect(w,S,C-w,T-S),t.matrix){const k=new Path2D;k.addPath(_,new DOMMatrix(t.matrix)),_=k}p.clip(_)}t.smask&&this.smaskStack.push({canvas:d.canvas,context:p,offsetX:c,offsetY:l,subtype:t.smask.subtype,backdrop:t.smask.backdrop,transferMap:t.smask.transferMap||null}),(!t.smask||this.dependencyTracker)&&(i.setTransform(1,0,0,1,0,0),i.translate(c,l),i.save()),kh(i,p),this.ctx=p,(b=this.dependencyTracker)==null||b.inheritSimpleDataAsFutureForcedDependencies(["fillAlpha","strokeAlpha","globalCompositeOperation"]).pushBaseTransform(i),this.setGState(e,[["BM","source-over"],["ca",1],["CA",1],["TR",null]]),this.groupStack.push(i),f(this,za).push({backdropCtx:m,savedKnockoutLevel:y,offsetX:c,offsetY:l,hasInnerBackdrop:v,knockoutMaskEntry:g,knockoutTempEntry:null,knockoutBackdropEntry:null}),this.groupLevel++}endGroup(e,t){var o;if(!this.contentVisible)return;this.groupLevel--;const n=this.ctx,i=this.groupStack.pop(),r=f(this,za).pop();if(r&&x(this,Br,r.savedKnockoutLevel),i===null){this.restore(e);return}if(this.ctx=i,this.ctx.imageSmoothingEnabled=!1,(o=this.dependencyTracker)==null||o.popBaseTransform(),t.smask)this.tempSMask=this.smaskStack.pop(),this.restore(e),this.dependencyTracker&&(this.ctx.restore(),this.inSMaskMode&&this.ctx.setTransform(this.suspendedCtx.getTransform())),B(this,ct,BS).call(this,r);else{this.ctx.restore();const a=Cs(this.ctx);this.restore(e),this.ctx.save(),this.ctx.setTransform(...a);const c=Wh.slice();Be.axialAlignedBoundingBox([0,0,n.canvas.width,n.canvas.height],a,c);const l=f(this,za).at(-1);if(f(this,Br)>0)if(r.hasInnerBackdrop){const{width:u,height:h}=n.canvas,d=this.canvasFactory.create(u,h),p=d.context;p.drawImage(i.canvas,r.offsetX,r.offsetY,u,h,0,0,u,h),p.globalCompositeOperation="source-over",p.drawImage(n.canvas,0,0);const m=B(this,ct,XT).call(this,n.canvas);p.globalCompositeOperation="destination-in",p.drawImage(m.canvas,0,0);const v=this.ctx.globalCompositeOperation,g=this.ctx.globalAlpha,y=this.ctx.filter;this.ctx.save(),this.ctx.setTransform(...a),this.ctx.globalAlpha=1,Ts.isCanvasFilterSupported&&(this.ctx.filter="none"),this.ctx.globalCompositeOperation="destination-out",this.ctx.drawImage(m.canvas,0,0),this.ctx.globalCompositeOperation=v,this.ctx.globalAlpha=g,Ts.isCanvasFilterSupported&&(this.ctx.filter=y??"none"),this.ctx.drawImage(d.canvas,0,0),this.ctx.restore(),this.canvasFactory.destroy(m),this.canvasFactory.destroy(d)}else{const u=(l==null?void 0:l.backdropCtx)??null;B(this,ct,JT).call(this,this.ctx,n.canvas,{backdropCanvas:(u==null?void 0:u.canvas)??null,destTransform:a,backdropOffset:u?[l.offsetX+r.offsetX,l.offsetY+r.offsetY]:[0,0],sourceAlpha:this.ctx.globalAlpha,sourceFilter:this.ctx.filter})}else this.ctx.drawImage(n.canvas,0,0);this.ctx.restore(),this.canvasFactory.destroy({canvas:n.canvas,context:n}),B(this,ct,BS).call(this,r),this.compose(c)}}beginAnnotation(e,t,n,i,r,o){if(B(this,ct,KT).call(this),Q_(this.ctx),this.ctx.save(),this.save(e),this.baseTransform&&this.ctx.setTransform(...this.baseTransform),n){const a=n[2]-n[0],c=n[3]-n[1];if(o&&this.annotationCanvasMap){i=i.slice(),i[4]-=n[0],i[5]-=n[1],n=n.slice(),n[0]=n[1]=0,n[2]=a,n[3]=c,Be.singularValueDecompose2dScale(Cs(this.ctx),eo);const{viewportScale:l}=this,u=Math.ceil(a*this.outputScaleX*l),h=Math.ceil(c*this.outputScaleY*l);this.annotationCanvas=this.canvasFactory.create(u,h);const{canvas:d,context:p}=this.annotationCanvas;this.annotationCanvasMap.set(t,d),this.annotationCanvas.savedCtx=this.ctx,this.ctx=p,this.ctx.save(),this.ctx.setTransform(eo[0],0,0,-eo[1],0,c*eo[1]),Q_(this.ctx)}else{Q_(this.ctx),this.endPath(e);const l=new Path2D;l.rect(n[0],n[1],a,c),this.ctx.clip(l)}}this.current=new xR(this.ctx.canvas.width,this.ctx.canvas.height),this.baseTransformStack.push(this.baseTransform),this.transform(e,...i),this.transform(e,...r),this.baseTransform=Cs(this.ctx)}endAnnotation(e){this.annotationCanvas&&(this.ctx.restore(),B(this,ct,QT).call(this),this.ctx=this.annotationCanvas.savedCtx,delete this.annotationCanvas.savedCtx,delete this.annotationCanvas),this.baseTransform=this.baseTransformStack.pop()}paintImageMaskXObject(e,t){var c;if(!this.contentVisible)return;const n=t.count;t=this.getObject(e,t.data,t),t.count=n;const i=B(this,ct,rr).call(this,this.current.fillAlpha),r=this.ctx,o=this._createMaskCanvas(e,t),a=o.canvas;r.save(),r.setTransform(1,0,0,1,0,0),r.drawImage(a,o.offsetX,o.offsetY),(c=this.dependencyTracker)==null||c.resetBBox(e).recordBBox(e,this.ctx,o.offsetX,o.offsetX+a.width,o.offsetY,o.offsetY+a.height).recordOperation(e),r.restore(),o.canvasEntry&&this.canvasFactory.destroy(o.canvasEntry),this.compose(),B(this,ct,bi).call(this,i)}paintImageMaskXObjectRepeat(e,t,n,i=0,r=0,o,a){var d,p,m;if(!this.contentVisible)return;t=this.getObject(e,t.data,t);const c=B(this,ct,rr).call(this,this.current.fillAlpha),l=this.ctx;l.save();const u=Cs(l);l.transform(n,i,r,o,0,0);const h=this._createMaskCanvas(e,t);l.setTransform(1,0,0,1,h.offsetX-u[4],h.offsetY-u[5]),(d=this.dependencyTracker)==null||d.resetBBox(e);for(let v=0,g=a.length;v<g;v+=2){const y=Be.transform(u,[n,i,r,o,a[v],a[v+1]]);l.drawImage(h.canvas,y[4],y[5]),(p=this.dependencyTracker)==null||p.recordBBox(e,this.ctx,y[4],y[4]+h.canvas.width,y[5],y[5]+h.canvas.height)}l.restore(),h.canvasEntry&&this.canvasFactory.destroy(h.canvasEntry),this.compose(),(m=this.dependencyTracker)==null||m.recordOperation(e),B(this,ct,bi).call(this,c)}paintImageMaskXObjectGroup(e,t){var a,c,l;if(!this.contentVisible)return;const n=B(this,ct,rr).call(this,this.current.fillAlpha),i=this.ctx,r=this.current.fillColor,o=this.current.patternFill;(a=this.dependencyTracker)==null||a.resetBBox(e).recordDependencies(e,uo.transformAndFill);for(const u of t){const{data:h,width:d,height:p,transform:m}=u,v=this.canvasFactory.create(d,p),g=v.context;g.save();const y=this.getObject(e,h,u);RR(g,y),g.globalCompositeOperation="source-in",g.fillStyle=o?r.getPattern(g,this,ka(i),hi.FILL,e):r,g.fillRect(0,0,d,p),g.restore(),i.save(),i.transform(...m),i.scale(1,-1),K_(i,v.canvas,0,0,d,p,0,-1,1,1),this.canvasFactory.destroy(v),(c=this.dependencyTracker)==null||c.recordBBox(e,i,0,d,0,p),i.restore()}this.compose(),(l=this.dependencyTracker)==null||l.recordOperation(e),B(this,ct,bi).call(this,n)}paintImageXObject(e,t){if(!this.contentVisible)return;const n=this.getObject(e,t);if(!n){kt("Dependent image isn't ready yet");return}this.paintInlineImageXObject(e,n)}paintImageXObjectRepeat(e,t,n,i,r){if(!this.contentVisible)return;const o=this.getObject(e,t);if(!o){kt("Dependent image isn't ready yet");return}const a=o.width,c=o.height,l=[];for(let u=0,h=r.length;u<h;u+=2)l.push({transform:[n,0,0,i,r[u],r[u+1]],x:0,y:0,w:a,h:c});this.paintInlineImageXObjectGroup(e,o,l)}applyTransferMapsToCanvas(e){return this.current.transferMaps!=="none"&&(e.filter=this.current.transferMaps,e.drawImage(e.canvas,0,0),e.filter="none"),e.canvas}applyTransferMapsToBitmap(e){if(this.current.transferMaps==="none")return{img:e.bitmap,canvasEntry:null};const{bitmap:t,width:n,height:i}=e,r=this.canvasFactory.create(n,i),o=r.context;return o.filter=this.current.transferMaps,o.drawImage(t,0,0),o.filter="none",{img:r.canvas,canvasEntry:r}}paintInlineImageXObject(e,t){var h;if(!this.contentVisible)return;const n=t.width,i=t.height,r=B(this,ct,rr).call(this,this.current.fillAlpha),o=this.ctx;this.save(e);const{filter:a}=o;a!=="none"&&a!==""&&(o.filter="none"),o.scale(1/n,-1/i);let c,l=null;if(t.bitmap){const d=this.applyTransferMapsToBitmap(t);c=d.img,l=d.canvasEntry}else if(typeof HTMLElement=="function"&&t instanceof HTMLElement||!t.data)c=t;else{const d=this.canvasFactory.create(n,i);IR(d.context,t),c=this.applyTransferMapsToCanvas(d.context),l=d}const u=this._scaleImage(c,ka(o));o.imageSmoothingEnabled=LR(Cs(o),t.interpolate),this.dependencyTracker&&(this.dependencyTracker.resetBBox(e).recordBBox(e,o,0,n,-i,0).recordDependencies(e,uo.imageXObject).recordOperation(e),(h=this.imagesTracker)==null||h.record(o,n,i,this.dependencyTracker.clipBox)),K_(o,u.img,0,0,u.paintWidth,u.paintHeight,0,-i,n,i),u.tmpCanvas&&this.canvasFactory.destroy(u.tmpCanvas),l&&this.canvasFactory.destroy(l),this.compose(),this.restore(e),B(this,ct,bi).call(this,r)}paintInlineImageXObjectGroup(e,t,n){var c,l,u;if(!this.contentVisible)return;const i=B(this,ct,rr).call(this,this.current.fillAlpha),r=this.ctx;let o,a=null;if(t.bitmap)o=t.bitmap;else{const h=t.width,d=t.height,p=this.canvasFactory.create(h,d);IR(p.context,t),o=this.applyTransferMapsToCanvas(p.context),a=p}(c=this.dependencyTracker)==null||c.resetBBox(e);for(const h of n)r.save(),r.transform(...h.transform),r.scale(1,-1),K_(r,o,h.x,h.y,h.w,h.h,0,-1,1,1),(l=this.dependencyTracker)==null||l.recordBBox(e,r,0,1,-1,0),r.restore();a&&this.canvasFactory.destroy(a),(u=this.dependencyTracker)==null||u.recordOperation(e),this.compose(),B(this,ct,bi).call(this,i)}paintSolidColorImageMask(e){var n;if(!this.contentVisible)return;const t=B(this,ct,rr).call(this,this.current.fillAlpha);(n=this.dependencyTracker)==null||n.resetBBox(e).recordBBox(e,this.ctx,0,1,0,1).recordDependencies(e,uo.fill).recordOperation(e),this.ctx.fillRect(0,0,1,1),this.compose(),B(this,ct,bi).call(this,t)}markPoint(e,t){}markPointProps(e,t,n){}beginMarkedContent(e,t){var n;(n=this.dependencyTracker)==null||n.beginMarkedContent(e),this.markedContentStack.push({visible:!0})}beginMarkedContentProps(e,t,n){var i;(i=this.dependencyTracker)==null||i.beginMarkedContent(e),t==="OC"?this.markedContentStack.push({visible:this.optionalContentConfig.isVisible(n)}):this.markedContentStack.push({visible:!0}),this.contentVisible=this.isContentVisible()}endMarkedContent(e){var t;(t=this.dependencyTracker)==null||t.endMarkedContent(e),this.markedContentStack.pop(),this.contentVisible=this.isContentVisible()}beginCompat(e){}endCompat(e){}consumePath(e,t,n){var o,a;const i=this.current.isEmptyClip();this.pendingClip&&this.current.updateClipFromPath(),this.pendingClip||this.compose(n);const r=this.ctx;this.pendingClip?(i||(this.pendingClip===PR?r.clip(t,"evenodd"):r.clip(t)),this.pendingClip=null,(o=this.dependencyTracker)==null||o.bboxToClipBoxDropOperation(e).recordFutureForcedDependency("clipPath",e)):(a=this.dependencyTracker)==null||a.recordOperation(e),this.current.startNewPathAndClipBox(this.current.clipBox)}getSinglePixelWidth(){if(!this._cachedGetSinglePixelWidth){const e=Cs(this.ctx);if(e[1]===0&&e[2]===0)this._cachedGetSinglePixelWidth=1/Math.min(Math.abs(e[0]),Math.abs(e[3]));else{const t=Math.abs(e[0]*e[3]-e[2]*e[1]),n=Math.hypot(e[0],e[2]),i=Math.hypot(e[1],e[3]);this._cachedGetSinglePixelWidth=Math.max(n,i)/t}}return this._cachedGetSinglePixelWidth}getScaleForStroking(){if(this._cachedScaleForStroking[0]===-1){const{lineWidth:e}=this.current,{a:t,b:n,c:i,d:r}=this.ctx.getTransform();let o,a;if(n===0&&i===0){const c=Math.abs(t),l=Math.abs(r);if(c===l)if(e===0)o=a=1/c;else{const u=c*e;o=a=u<1?1/u:1}else if(e===0)o=1/c,a=1/l;else{const u=c*e,h=l*e;o=u<1?1/u:1,a=h<1?1/h:1}}else{const c=Math.abs(t*r-n*i),l=Math.hypot(t,n),u=Math.hypot(i,r);if(e===0)o=u/c,a=l/c;else{const h=e*c;o=u>h?u/h:1,a=l>h?l/h:1}}this._cachedScaleForStroking[0]=o,this._cachedScaleForStroking[1]=a}return this._cachedScaleForStroking}rescaleAndStroke(e,t){const{ctx:n,current:{lineWidth:i}}=this,[r,o]=this.getScaleForStroking();if(r===o){n.lineWidth=(i||1)*r,n.stroke(e);return}const a=n.getLineDash();t&&n.save(),n.scale(r,o),JC.a=1/r,JC.d=1/o;const c=new Path2D;if(c.addPath(e,JC),a.length>0){const l=Math.max(r,o);n.setLineDash(a.map(u=>u/l)),n.lineDashOffset/=l}n.lineWidth=i||1,n.stroke(c),t&&n.restore()}isContentVisible(){for(let e=this.markedContentStack.length-1;e>=0;e--)if(!this.markedContentStack[e].visible)return!1;return!0}};Br=new WeakMap,Au=new WeakMap,Cd=new WeakMap,Td=new WeakMap,Ad=new WeakMap,Ed=new WeakMap,Md=new WeakMap,Eu=new WeakMap,xd=new WeakMap,za=new WeakMap,ct=new WeakSet,KT=function(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.current.activeSMask=null,this.ctx.restore(),this.transparentCanvas&&(this.ctx=this.compositeCtx,this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.drawImage(this.transparentCanvas,0,0),this.ctx.restore(),this.canvasFactory.destroy(this.transparentCanvasEntry),this.transparentCanvas=null,this.transparentCanvasEntry=null)},QT=function(){if(this.pageColors){const e=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if(e!=="none"){const t=this.ctx.filter;this.ctx.filter=e,this.ctx.drawImage(this.ctx.canvas,0,0),this.ctx.filter=t}}},XT=function(e,t=null,n=1){const{width:i,height:r}=e,o=t??this.canvasFactory.create(i,r),a=o.context;n=Math.round(n*255)/255;const c=n<1;c&&f(this,Eu)===void 0&&x(this,Eu,Ts.isCanvasFilterSupported?new Map:"none");let l="none";if(c&&f(this,Eu)instanceof Map&&(l=f(this,Eu).get(n),l||(l=this.filterFactory.addKnockoutFilter(n),f(this,Eu).set(n,l))),!c||l!=="none")return t&&(a.save(),a.setTransform(1,0,0,1,0,0),a.clearRect(0,0,i,r),a.restore()),a.filter=l,a.drawImage(e,0,0),a.filter="none",o;const u=e.getContext("2d",{willReadFrequently:!0}).getImageData(0,0,i,r),h=a.createImageData(i,r),d=u.data,p=h.data,m=n>0?1/n:1e6;for(let v=3,g=d.length;v<g;v+=4)p[v]=Math.min(Math.round(d[v]*m),255);return a.putImageData(h,0,0),o},YT=function(e,t,n,i){let r=(e==null?void 0:e[t])??null;if(r&&(r.canvas.width!==n||r.canvas.height!==i)&&(this.canvasFactory.destroy(r),r=null),!r)return r=this.canvasFactory.create(n,i),e&&(e[t]=r),r;const o=r.context;return o.save(),o.setTransform(1,0,0,1,0,0),o.clearRect(0,0,n,i),o.restore(),r},JT=function(e,t,n={}){const{backdropCanvas:i=null,destTransform:r=[1,0,0,1,0,0],backdropOffset:o=[0,0],reuseMaskEntry:a=null,poolMeta:c=null,sourceAlpha:l=1,sourceFilter:u="none",knockoutAlpha:h=1}=n,{width:d,height:p}=t,m=B(this,ct,XT).call(this,t,a,h),v=e.globalCompositeOperation;if(e.save(),e.setTransform(...r),e.globalAlpha=1,Ts.isCanvasFilterSupported&&(e.filter="none"),e.globalCompositeOperation="destination-out",e.drawImage(m.canvas,0,0),i){const[g,y]=o,b=B(this,ct,YT).call(this,c,"knockoutBackdropEntry",d,p),_=b.context;_.drawImage(i,g,y,d,p,0,0,d,p),_.globalCompositeOperation="destination-in",_.drawImage(m.canvas,0,0),_.globalCompositeOperation="source-over",e.globalCompositeOperation="destination-over",e.drawImage(b.canvas,0,0),c||this.canvasFactory.destroy(b)}e.globalCompositeOperation=v,e.globalAlpha=l,Ts.isCanvasFilterSupported&&(e.filter=u??"none"),e.drawImage(t,0,0),e.restore(),a||this.canvasFactory.destroy(m)},rr=function(e=1){if(f(this,Br)===0||f(this,Au)>0||!this.contentVisible)return!1;xs(this,Au)._++,x(this,Md,e);const t=f(this,za).at(-1),{canvas:n}=this.ctx,i=B(this,ct,YT).call(this,t,"knockoutTempEntry",n.width,n.height);x(this,Cd,i);const r=i.context;return r.save(),r.setTransform(this.ctx.getTransform()),kh(this.ctx,r),x(this,Ed,r.globalCompositeOperation),r.globalCompositeOperation="source-over",MR(r,this.ctx),x(this,xd,t),x(this,Td,this.ctx),x(this,Ad,this.suspendedCtx),this.ctx=r,this.inSMaskMode&&(this.suspendedCtx=r),!0},bi=function(e){var c;if(!e)return;const t=f(this,Cd),n=f(this,Td),i=f(this,Ad),r=t.context;x(this,Cd,null),x(this,Td,null),x(this,Ad,null),this.inSMaskMode&&this.suspendedCtx===r&&this.ctx!==r&&this.endSMaskMode(),this.inSMaskMode&&(this.suspendedCtx=i),this.ctx._removeMirroring(),this.ctx.globalCompositeOperation=f(this,Ed),x(this,Ed,null),kh(this.ctx,n),this.ctx=n;const o=f(this,xd);x(this,xd,null);const a=f(this,Md);x(this,Md,1);try{B(this,ct,JT).call(this,i??n,t.canvas,{backdropCanvas:((c=o==null?void 0:o.backdropCtx)==null?void 0:c.canvas)??null,backdropOffset:o!=null&&o.backdropCtx?[o.offsetX,o.offsetY]:[0,0],reuseMaskEntry:(o==null?void 0:o.knockoutMaskEntry)??null,poolMeta:o,knockoutAlpha:a})}finally{r.restore(),xs(this,Au)._--,o||this.canvasFactory.destroy(t)}},ZT=function(e,t,n){const i=new Path2D;return i.addPath(e,new DOMMatrix(n).invertSelf().multiplySelf(t)),i},BS=function(e){e&&(e.knockoutMaskEntry&&(this.canvasFactory.destroy(e.knockoutMaskEntry),e.knockoutMaskEntry=null),e.knockoutTempEntry&&(this.canvasFactory.destroy(e.knockoutTempEntry),e.knockoutTempEntry=null),e.knockoutBackdropEntry&&(this.canvasFactory.destroy(e.knockoutBackdropEntry),e.knockoutBackdropEntry=null))};let kp=CM;for(const s in Il)kp.prototype[s]!==void 0&&(kp.prototype[Il[s]]=kp.prototype[s]);var Vy,Gy;class mk{constructor(e,t,n){D(this,Vy,null);D(this,Gy,null);_e(this,"_fullReader",null);_e(this,"_rangeReaders",new Set);_e(this,"_source",null);this._source=e,x(this,Vy,t),x(this,Gy,n)}get _progressiveDataLength(){var e;return((e=this._fullReader)==null?void 0:e._loaded)??0}getFullReader(){return Gs(!this._fullReader,"BasePDFStream.getFullReader can only be called once."),this._fullReader=new(f(this,Vy))(this)}getRangeReader(e,t){if(t<=this._progressiveDataLength)return null;const n=new(f(this,Gy))(this,e,t);return this._rangeReaders.add(n),n}cancelAllRequests(e){var t;(t=this._fullReader)==null||t.cancel(e);for(const n of new Set(this._rangeReaders))n.cancel(e)}}Vy=new WeakMap,Gy=new WeakMap;class vk{constructor(e){_e(this,"onProgress",null);_e(this,"_contentLength",0);_e(this,"_filename",null);_e(this,"_headersCapability",Promise.withResolvers());_e(this,"_isRangeSupported",!1);_e(this,"_isStreamingSupported",!1);_e(this,"_loaded",0);_e(this,"_stream",null);this._stream=e}_callOnProgress(){var e;(e=this.onProgress)==null||e.call(this,{loaded:this._loaded,total:this._contentLength})}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){es("Abstract method `read` called")}cancel(e){es("Abstract method `cancel` called")}}class yk{constructor(e,t,n){_e(this,"_stream",null);this._stream=e}async read(){es("Abstract method `read` called")}cancel(e){es("Abstract method `cancel` called")}}function wte(s){let e=!0,t=n("filename\\*","i").exec(s);if(t){t=t[1];let u=a(t);return u=unescape(u),u=c(u),u=l(u),r(u)}if(t=o(s),t){const u=l(t);return r(u)}if(t=n("filename","i").exec(s),t){t=t[1];let u=a(t);return u=l(u),r(u)}function n(u,h){return new RegExp("(?:^|;)\\s*"+u+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',h)}function i(u,h){if(u){if(!/^[\x00-\xFF]+$/.test(h))return h;try{const d=new TextDecoder(u,{fatal:!0}),p=fk(h);h=d.decode(p),e=!1}catch{}}return h}function r(u){return e&&/[\x80-\xff]/.test(u)&&(u=i("utf-8",u),e&&(u=i("iso-8859-1",u))),u}function o(u){const h=[];let d;const p=n("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;(d=p.exec(u))!==null;){let[,v,g,y]=d;if(v=parseInt(v,10),v in h){if(v===0)break;continue}h[v]=[g,y]}const m=[];for(let v=0;v<h.length&&v in h;++v){let[g,y]=h[v];y=a(y),g&&(y=unescape(y),v===0&&(y=c(y))),m.push(y)}return m.join("")}function a(u){if(u.startsWith('"')){const h=u.slice(1).split('\\"');for(let d=0;d<h.length;++d){const p=h[d].indexOf('"');p!==-1&&(h[d]=h[d].slice(0,p),h.length=d+1),h[d]=h[d].replaceAll(/\\(.)/g,"$1")}u=h.join('"')}return u}function c(u){const h=u.indexOf("'");if(h===-1)return u;const d=u.slice(0,h),m=u.slice(h+1).replace(/^[^']*'/,"");return i(d,m)}function l(u){return!u.startsWith("=?")||/[\x00-\x19\x80-\xff]/.test(u)?u:u.replaceAll(/=\?([\w-]*)\?([QB])\?((?:[^?]|\?(?!=))*)\?=/gi,function(h,d,p,m){if(p==="q"||p==="Q")return m=m.replaceAll("_"," "),m=m.replaceAll(/=([0-9a-f]{2})/gi,function(v,g){return String.fromCharCode(parseInt(g,16))}),i(d,m);try{m=atob(m)}catch{}return i(d,m)})}return""}function MN(s,e){const t=new Headers;if(!s||!e||typeof e!="object")return t;for(const n in e){const i=e[n];i!==void 0&&t.append(n,i)}return t}function bk(s){var e;return((e=URL.parse(s))==null?void 0:e.origin)??null}function xN({responseHeaders:s,isHttp:e,rangeChunkSize:t,disableRange:n}){const i={contentLength:0,isRangeSupported:!1},r=parseInt(s.get("Content-Length"),10);return!Number.isInteger(r)||(i.contentLength=r,r<=2*t)||n||!e||s.get("Accept-Ranges")!=="bytes"||(s.get("Content-Encoding")||"identity")==="identity"&&(i.isRangeSupported=!0),i}function IN(s){const e=s.get("Content-Disposition");if(e){let t=wte(e);if(t.includes("%"))try{t=decodeURIComponent(t)}catch{}if(hM(t))return t}return null}function _k(s,e){return new l0(`Unexpected server response (${s}) while retrieving PDF "${e.href}".`,s,s===404||s===0&&e.protocol==="file:")}function RN(s,e){if(s!==e)throw new Error(`Expected range response-origin "${s}" to match "${e}".`)}function LN(s,e,t,n){return fetch(s,{method:"GET",headers:e,signal:n.signal,mode:"cors",credentials:t?"include":"same-origin",redirect:"follow"})}function PN(s,e){if(s!==200&&s!==206)throw _k(s,e)}function Sk(s){if(s instanceof Uint8Array)return s.buffer;if(s instanceof ArrayBuffer)return s;throw new Error(`getArrayBuffer - unexpected data: ${s}`)}class kte extends mk{constructor(t){super(t,Cte,Tte);_e(this,"_responseOrigin",null);const{httpHeaders:n,url:i}=t;Gs(/https?:/.test(i.protocol),"PDFFetchStream only supports http(s):// URLs."),this.headers=MN(!0,n)}}class Cte extends vk{constructor(t){super(t);_e(this,"_abortController",new AbortController);_e(this,"_reader",null);const{disableRange:n,disableStream:i,rangeChunkSize:r,url:o,withCredentials:a}=t._source;this._isStreamingSupported=!i;const c=new Headers(t.headers);LN(o,c,a,this._abortController).then(l=>{t._responseOrigin=bk(l.url),PN(l.status,o),this._reader=l.body.getReader();const u=l.headers,{contentLength:h,isRangeSupported:d}=xN({responseHeaders:u,isHttp:!0,rangeChunkSize:r,disableRange:n});this._contentLength=h,this._isRangeSupported=d,this._filename=IN(u),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new ch("Streaming is disabled.")),this._headersCapability.resolve()}).catch(this._headersCapability.reject)}async read(){await this._headersCapability.promise;const{value:t,done:n}=await this._reader.read();return n?{value:t,done:n}:(this._loaded+=t.byteLength,this._callOnProgress(),{value:Sk(t),done:!1})}cancel(t){var n;(n=this._reader)==null||n.cancel(t),this._abortController.abort()}}class Tte extends yk{constructor(t,n,i){super(t,n,i);_e(this,"_abortController",new AbortController);_e(this,"_readCapability",Promise.withResolvers());_e(this,"_reader",null);const{url:r,withCredentials:o}=t._source,a=new Headers(t.headers);a.append("Range",`bytes=${n}-${i-1}`),LN(r,a,o,this._abortController).then(c=>{const l=bk(c.url);RN(l,t._responseOrigin),PN(c.status,r),this._reader=c.body.getReader(),this._readCapability.resolve()}).catch(this._readCapability.reject)}async read(){await this._readCapability.promise;const{value:t,done:n}=await this._reader.read();return n?{value:t,done:n}:{value:Sk(t),done:!1}}cancel(t){var n;(n=this._reader)==null||n.cancel(t),this._abortController.abort()}}St(116);function OR(s){return s instanceof Uint8Array&&s.byteLength===s.buffer.byteLength?s.buffer:new Uint8Array(s).buffer}function wk(){for(const s of this._requests)s.resolve({value:void 0,done:!0});this._requests.length=0}var O0,ON;class Ate extends mk{constructor(t){super(t,Ete,Mte);D(this,O0);_e(this,"_progressiveDone",!1);_e(this,"_queuedChunks",[]);const{pdfDataRangeTransport:n}=t,{initialData:i,progressiveDone:r}=n;if((i==null?void 0:i.length)>0){const a=OR(i);this._queuedChunks.push(a)}this._progressiveDone=r;const o=a=>{var c;switch(a.type){case"range":case"progressiveRead":B(this,O0,ON).call(this,a.begin,a.chunk);break;case"progressiveDone":(c=this._fullReader)==null||c.progressiveDone(),this._progressiveDone=!0;break}};n.transportReady(o)}getFullReader(){const t=super.getFullReader();return this._queuedChunks=null,t}getRangeReader(t,n){const i=super.getRangeReader(t,n);return i&&(i.onDone=()=>this._rangeReaders.delete(i),this._source.pdfDataRangeTransport.requestDataRange(t,n)),i}cancelAllRequests(t){super.cancelAllRequests(t),this._source.pdfDataRangeTransport.abort()}}O0=new WeakSet,ON=function(t,n){const i=OR(n);if(t===void 0)this._fullReader?this._fullReader._enqueue(i):this._queuedChunks.push(i);else{const r=this._rangeReaders.keys().find(o=>o._begin===t);Gs(r,"#onReceiveData - no `PDFDataTransportStreamRangeReader` instance found."),r._enqueue(i)}};var qy;class Ete extends vk{constructor(t){super(t);D(this,qy,wk.bind(this));_e(this,"_done",!1);_e(this,"_queuedChunks",null);_e(this,"_requests",[]);const{pdfDataRangeTransport:n,disableRange:i,disableStream:r}=t._source,{length:o,contentDispositionFilename:a}=n;this._queuedChunks=t._queuedChunks||[];for(const l of this._queuedChunks)this._loaded+=l.byteLength;this._done=t._progressiveDone,this._contentLength=o,this._isStreamingSupported=!r,this._isRangeSupported=!i,hM(a)&&(this._filename=a),this._headersCapability.resolve();const c=this._loaded;Promise.resolve().then(()=>{c>0&&this._loaded===c&&this._callOnProgress()})}_enqueue(t){this._done||(this._requests.length>0?this._requests.shift().resolve({value:t,done:!1}):this._queuedChunks.push(t),this._loaded+=t.byteLength,this._callOnProgress())}async read(){if(this._queuedChunks.length>0)return{value:this._queuedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0,f(this,qy).call(this)}progressiveDone(){this._done||(this._done=!0),this._queuedChunks.length===0&&f(this,qy).call(this)}}qy=new WeakMap;var Ky;class Mte extends yk{constructor(t,n,i){super(t,n,i);D(this,Ky,wk.bind(this));_e(this,"onDone",null);_e(this,"_begin",-1);_e(this,"_done",!1);_e(this,"_queuedChunk",null);_e(this,"_requests",[]);this._begin=n}_enqueue(t){var n;this._done||(this._requests.length===0?this._queuedChunk=t:(this._requests.shift().resolve({value:t,done:!1}),f(this,Ky).call(this)),this._done=!0,(n=this.onDone)==null||n.call(this))}async read(){if(this._queuedChunk){const n=this._queuedChunk;return this._queuedChunk=null,{value:n,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){var n;this._done=!0,f(this,Ky).call(this),(n=this.onDone)==null||n.call(this)}}Ky=new WeakMap;const ZC=200,DR=206;function xte(s){return typeof s!="string"?s:fk(s).buffer}var ja,lm,DN,NN;class Ite extends mk{constructor(t){super(t,Rte,Lte);D(this,lm);D(this,ja,new WeakMap);_e(this,"_responseOrigin",null);const{httpHeaders:n,url:i}=t;this.url=i,this.isHttp=/https?:/.test(i.protocol),this.headers=MN(this.isHttp,n)}_request(t){const n=new XMLHttpRequest,i={validateStatus:null,onHeadersReceived:t.onHeadersReceived,onDone:t.onDone,onError:t.onError,onProgress:t.onProgress};f(this,ja).set(n,i),n.open("GET",this.url),n.withCredentials=this._source.withCredentials;for(const[r,o]of this.headers)n.setRequestHeader(r,o);return this.isHttp&&"begin"in t&&"end"in t?(n.setRequestHeader("Range",`bytes=${t.begin}-${t.end-1}`),i.validateStatus=r=>r===DR||r===ZC):i.validateStatus=r=>r===ZC,n.responseType="arraybuffer",Gs(t.onError,"Expected `onError` callback to be provided."),n.onerror=()=>t.onError(n.status),n.onreadystatechange=B(this,lm,NN).bind(this,n),n.onprogress=B(this,lm,DN).bind(this,n),n.send(null),n}_abortRequest(t){f(this,ja).has(t)&&(f(this,ja).delete(t),t.abort())}getRangeReader(t,n){const i=super.getRangeReader(t,n);return i&&(i.onClosed=()=>this._rangeReaders.delete(i)),i}}ja=new WeakMap,lm=new WeakSet,DN=function(t,n){var r;const i=f(this,ja).get(t);(r=i==null?void 0:i.onProgress)==null||r.call(i,n)},NN=function(t,n){const i=f(this,ja).get(t);if(!i||(t.readyState>=2&&i.onHeadersReceived&&(i.onHeadersReceived(),delete i.onHeadersReceived),t.readyState!==4)||!f(this,ja).has(t))return;if(f(this,ja).delete(t),t.status===0&&this.isHttp){i.onError(t.status);return}const r=t.status||ZC;if(!i.validateStatus(r)){i.onError(t.status);return}const o=xte(t.response);if(r===DR){const a=t.getResponseHeader("Content-Range");/bytes \d+-\d+\/\d+/.test(a)?i.onDone(o):(kt('Missing or invalid "Content-Range" header.'),i.onError(0))}else o?i.onDone(o):i.onError(t.status)};var Qy,cl,BN,FN,$N,HN;class Rte extends vk{constructor(t){super(t);D(this,cl);D(this,Qy,wk.bind(this));_e(this,"_cachedChunks",[]);_e(this,"_done",!1);_e(this,"_requests",[]);_e(this,"_storedError",null);this._fullRequestXhr=t._request({onHeadersReceived:B(this,cl,BN).bind(this),onDone:B(this,cl,FN).bind(this),onError:B(this,cl,$N).bind(this),onProgress:B(this,cl,HN).bind(this)})}async read(){if(await this._headersCapability.promise,this._storedError)throw this._storedError;if(this._cachedChunks.length>0)return{value:this._cachedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0,this._headersCapability.reject(t),f(this,Qy).call(this),this._stream._abortRequest(this._fullRequestXhr),this._fullRequestXhr=null}}Qy=new WeakMap,cl=new WeakSet,BN=function(){const t=this._stream,{disableRange:n,rangeChunkSize:i}=t._source,r=this._fullRequestXhr;t._responseOrigin=bk(r.responseURL);const o=r.getAllResponseHeaders(),a=new Headers(o?o.trimStart().replace(/[^\S ]+$/,"").split(/[\r\n]+/).map(u=>{const[h,...d]=u.split(": ");return[h,d.join(": ")]}):[]),{contentLength:c,isRangeSupported:l}=xN({responseHeaders:a,isHttp:t.isHttp,rangeChunkSize:i,disableRange:n});this._contentLength=c,this._isRangeSupported=l,this._filename=IN(a),this._isRangeSupported&&t._abortRequest(r),this._headersCapability.resolve()},FN=function(t){this._requests.length>0?this._requests.shift().resolve({value:t,done:!1}):this._cachedChunks.push(t),this._done=!0,this._cachedChunks.length===0&&f(this,Qy).call(this)},$N=function(t){this._storedError=_k(t,this._stream.url),this._headersCapability.reject(this._storedError);for(const n of this._requests)n.reject(this._storedError);this._requests.length=0,this._cachedChunks.length=0},HN=function(t){var n;(n=this.onProgress)==null||n.call(this,{loaded:t.loaded,total:t.lengthComputable?t.total:this._contentLength})};var Xy,Mc,UN,WN,eA;class Lte extends yk{constructor(t,n,i){super(t,n,i);D(this,Mc);D(this,Xy,wk.bind(this));_e(this,"onClosed",null);_e(this,"_done",!1);_e(this,"_queuedChunk",null);_e(this,"_requests",[]);_e(this,"_storedError",null);this._requestXhr=t._request({begin:n,end:i,onHeadersReceived:B(this,Mc,UN).bind(this),onDone:B(this,Mc,WN).bind(this),onError:B(this,Mc,eA).bind(this),onProgress:null})}async read(){if(this._storedError)throw this._storedError;if(this._queuedChunk!==null){const n=this._queuedChunk;return this._queuedChunk=null,{value:n,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){var n;this._done=!0,f(this,Xy).call(this),this._stream._abortRequest(this._requestXhr),(n=this.onClosed)==null||n.call(this)}}Xy=new WeakMap,Mc=new WeakSet,UN=function(){var n;const t=bk((n=this._requestXhr)==null?void 0:n.responseURL);try{RN(t,this._stream._responseOrigin)}catch(i){this._storedError=i,B(this,Mc,eA).call(this,0)}},WN=function(t){var n;this._requests.length>0?this._requests.shift().resolve({value:t,done:!1}):this._queuedChunk=t,this._done=!0,f(this,Xy).call(this),(n=this.onClosed)==null||n.call(this)},eA=function(t){this._storedError??(this._storedError=_k(t,this._stream.url));for(const n of this._requests)n.reject(this._storedError);this._requests.length=0,this._queuedChunk=null};function zN(s,e=null){const t=process.getBuiltinModule("fs"),{Readable:n}=process.getBuiltinModule("stream"),i=t.createReadStream(s,e);return n.toWeb(i)}class Pte extends mk{constructor(e){super(e,Ote,Dte);const{url:t}=e;Gs(t.protocol==="file:","PDFNodeStream only supports file:// URLs.")}}class Ote extends vk{constructor(t){super(t);_e(this,"_reader",null);const{disableRange:n,disableStream:i,rangeChunkSize:r,url:o}=t._source;this._isStreamingSupported=!i,process.getBuiltinModule("fs/promises").lstat(o).then(c=>{const l=zN(o);this._reader=l.getReader();const{size:u}=c;this._contentLength=u,this._isRangeSupported=!n&&u>2*r,!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new ch("Streaming is disabled.")),this._headersCapability.resolve()}).catch(c=>{c.code==="ENOENT"&&(c=_k(0,o)),this._headersCapability.reject(c)})}async read(){await this._headersCapability.promise;const{value:t,done:n}=await this._reader.read();return n?{value:t,done:n}:(this._loaded+=t.byteLength,this._callOnProgress(),{value:Sk(t),done:!1})}cancel(t){var n;(n=this._reader)==null||n.cancel(t)}}class Dte extends yk{constructor(t,n,i){super(t,n,i);_e(this,"_readCapability",Promise.withResolvers());_e(this,"_reader",null);const{url:r}=t._source;try{const o=zN(r,{start:n,end:i-1});this._reader=o.getReader(),this._readCapability.resolve()}catch(o){this._readCapability.reject(o)}}async read(){await this._readCapability.promise;const{value:t,done:n}=await this._reader.read();return n?{value:t,done:n}:{value:Sk(t),done:!1}}cancel(t){var n;(n=this._reader)==null||n.cancel(t)}}function Nte(s){return $v(s)?kte:Zr?Pte:Ite}var Yy,Jy;class sl{static get workerPort(){return f(this,Yy)}static set workerPort(e){if(!(typeof Worker<"u"&&e instanceof Worker)&&e!==null)throw new Error("Invalid `workerPort` type.");x(this,Yy,e)}static get workerSrc(){return f(this,Jy)}static set workerSrc(e){if(typeof e!="string")throw new Error("Invalid `workerSrc` type.");x(this,Jy,e)}}Yy=new WeakMap,Jy=new WeakMap,D(sl,Yy,null),D(sl,Jy,"");var rg,Zy;class Bte{constructor({parsedData:e,rawData:t}){D(this,rg);D(this,Zy);x(this,rg,e),x(this,Zy,t)}getRaw(){return f(this,Zy)}get(e){return f(this,rg).get(e)??null}[Symbol.iterator](){return f(this,rg).entries()}}rg=new WeakMap,Zy=new WeakMap;const fp=Symbol("INTERNAL");var eb,tb,sb,og;class Fte{constructor(e,{name:t,intent:n,usage:i,rbGroups:r}){D(this,eb,!1);D(this,tb,!1);D(this,sb,!1);D(this,og,!0);x(this,eb,!!(e&Jr.DISPLAY)),x(this,tb,!!(e&Jr.PRINT)),this.name=t,this.intent=n,this.usage=i,this.rbGroups=r}get visible(){if(f(this,sb))return f(this,og);if(!f(this,og))return!1;const{print:e,view:t}=this.usage;return f(this,eb)?(t==null?void 0:t.viewState)!=="OFF":f(this,tb)?(e==null?void 0:e.printState)!=="OFF":!0}_setVisible(e,t,n=!1){e!==fp&&es("Internal method `_setVisible` called."),x(this,sb,n),x(this,og,t)}}eb=new WeakMap,tb=new WeakMap,sb=new WeakMap,og=new WeakMap;var Mu,ms,ag,lg,nb,tA;class $te{constructor(e,t=Jr.DISPLAY){D(this,nb);D(this,Mu,null);D(this,ms,new Map);D(this,ag,null);D(this,lg,null);if(this.renderingIntent=t,this.name=null,this.creator=null,e!==null){this.name=e.name,this.creator=e.creator,x(this,lg,e.order);for(const n of e.groups)f(this,ms).set(n.id,new Fte(t,n));if(e.baseState==="OFF")for(const n of f(this,ms).values())n._setVisible(fp,!1);for(const n of e.on)f(this,ms).get(n)._setVisible(fp,!0);for(const n of e.off)f(this,ms).get(n)._setVisible(fp,!1);x(this,ag,this.getHash())}}isVisible(e){if(f(this,ms).size===0)return!0;if(!e)return dk("Optional content group not defined."),!0;if(e.type==="OCG")return f(this,ms).has(e.id)?f(this,ms).get(e.id).visible:(kt(`Optional content group not found: ${e.id}`),!0);if(e.type==="OCMD"){if(e.expression)return B(this,nb,tA).call(this,e.expression);if(!e.policy||e.policy==="AnyOn"){for(const t of e.ids){if(!f(this,ms).has(t))return kt(`Optional content group not found: ${t}`),!0;if(f(this,ms).get(t).visible)return!0}return!1}else if(e.policy==="AllOn"){for(const t of e.ids){if(!f(this,ms).has(t))return kt(`Optional content group not found: ${t}`),!0;if(!f(this,ms).get(t).visible)return!1}return!0}else if(e.policy==="AnyOff"){for(const t of e.ids){if(!f(this,ms).has(t))return kt(`Optional content group not found: ${t}`),!0;if(!f(this,ms).get(t).visible)return!0}return!1}else if(e.policy==="AllOff"){for(const t of e.ids){if(!f(this,ms).has(t))return kt(`Optional content group not found: ${t}`),!0;if(f(this,ms).get(t).visible)return!1}return!0}return kt(`Unknown optional content policy ${e.policy}.`),!0}return kt(`Unknown group type ${e.type}.`),!0}setVisibility(e,t=!0,n=!0){var r;const i=f(this,ms).get(e);if(!i){kt(`Optional content group not found: ${e}`);return}if(n&&t&&i.rbGroups.length)for(const o of i.rbGroups)for(const a of o)a!==e&&((r=f(this,ms).get(a))==null||r._setVisible(fp,!1,!0));i._setVisible(fp,!!t,!0),x(this,Mu,null)}setOCGState({state:e,preserveRB:t}){let n;for(const i of e){switch(i){case"ON":case"OFF":case"Toggle":n=i;continue}const r=f(this,ms).get(i);if(r)switch(n){case"ON":this.setVisibility(i,!0,t);break;case"OFF":this.setVisibility(i,!1,t);break;case"Toggle":this.setVisibility(i,!r.visible,t);break}}x(this,Mu,null)}get hasInitialVisibility(){return f(this,ag)===null||this.getHash()===f(this,ag)}getOrder(){return f(this,ms).size?f(this,lg)?f(this,lg).slice():[...f(this,ms).keys()]:null}getGroup(e){return f(this,ms).get(e)||null}getHash(){if(f(this,Mu)!==null)return f(this,Mu);const e=new HT;for(const[t,n]of f(this,ms))e.update(`${t}:${n.visible}`);return x(this,Mu,e.hexdigest())}[Symbol.iterator](){return f(this,ms).entries()}}Mu=new WeakMap,ms=new WeakMap,ag=new WeakMap,lg=new WeakMap,nb=new WeakSet,tA=function(e){const t=e.length;if(t<2)return!0;const n=e[0];for(let i=1;i<t;i++){const r=e[i];let o;if(Array.isArray(r))o=B(this,nb,tA).call(this,r);else if(f(this,ms).has(r))o=f(this,ms).get(r).visible;else return kt(`Optional content group not found: ${r}`),!0;switch(n){case"And":if(!o)return!1;break;case"Or":if(o)return!0;break;case"Not":return!o;default:return!0}}return n==="And"};var cn,ia,ai,Id,Va,xi,lv,cv,FS;class Hte{constructor(){D(this,xi);D(this,cn,null);D(this,ia,null);D(this,ai,0);D(this,Id,null);D(this,Va,null)}get pagesNumber(){return f(this,ai)}set pagesNumber(e){f(this,ai)!==e&&(x(this,ai,e),x(this,cn,null),x(this,ia,null))}movePages(e,t,n){B(this,xi,lv).call(this);const i=f(this,cn),r=B(this,xi,cv).call(this),o=t.length,a=new Uint32Array(o);let c=0;for(let d=0;d<o;d++){const p=t[d]-1;a[d]=i[p],p<n&&c++}const l=f(this,ai),u=l-o,h=Ns(n-c,0,u);for(let d=0,p=0;d<l;d++)e.has(d+1)||(i[p++]=i[d]);i.copyWithin(h+o,h,u),i.set(a,h),B(this,xi,FS).call(this,r),i.every((d,p)=>d===p+1)&&x(this,cn,null)}deletePages(e){B(this,xi,lv).call(this);const t=f(this,cn),n=B(this,xi,cv).call(this);x(this,Va,{pageNumberToId:t.slice(),pagesNumber:f(this,ai),prevPageNumbers:f(this,ia).slice()});const i=f(this,ai)-e.length;x(this,ai,i);const r=x(this,cn,new Uint32Array(i));x(this,ia,new Int32Array(i));let o=0,a=0;for(const c of e){const l=c-1;l!==o&&(r.set(t.subarray(o,l),a),a+=l-o),o=l+1}o<t.length&&r.set(t.subarray(o),a),B(this,xi,FS).call(this,n,new Set(e))}cancelDelete(){f(this,Va)&&(x(this,cn,f(this,Va).pageNumberToId),x(this,ai,f(this,Va).pagesNumber),x(this,ia,f(this,Va).prevPageNumbers),x(this,Va,null))}cleanSavedData(){x(this,Va,null)}copyPages(e){B(this,xi,lv).call(this),x(this,Id,{pageNumbers:e,pageIds:e.map(t=>f(this,cn)[t-1])})}cancelCopy(){x(this,Id,null)}pastePages(e){B(this,xi,lv).call(this);const t=f(this,cn),n=B(this,xi,cv).call(this),{pageNumbers:i,pageIds:r}=f(this,Id),o=f(this,ai)+i.length;x(this,ai,o);const a=x(this,cn,new Uint32Array(o));x(this,ia,new Int32Array(o)),a.set(t.subarray(0,e),0),a.set(r,e),a.set(t.subarray(e),e+i.length),B(this,xi,FS).call(this,n,null,e,i),x(this,Id,null)}hasBeenAltered(){return f(this,cn)!==null}getPageMappingForSaving(e=null){e??(e=B(this,xi,cv).call(this));let t=0;for(const i of e.values())t=Math.max(t,i.length);const n=new Array(t);for(let i=0;i<t;i++)n[i]={document:null,pageIndices:[],includePages:[]};for(const[i,r]of e)for(let o=0,a=r.length;o<a;o++)n[o].includePages.push([i-1,r[o]-1]);for(const{includePages:i,pageIndices:r}of n){i.sort((o,a)=>o[0]-a[0]);for(let o=0,a=i.length;o<a;o++)r.push(i[o][1]),i[o]=i[o][0]}return n}extractPages(e){e=Array.from(e).sort((n,i)=>n-i);const t=new Map;for(let n=0,i=e.length;n<i;n++){const r=this.getPageId(e[n]);t.getOrInsertComputed(r,aM).push(n+1)}return this.getPageMappingForSaving(t)}getPrevPageNumber(e){var t;return((t=f(this,ia))==null?void 0:t[e-1])??0}getPageNumber(e){if(!f(this,cn))return e;const t=f(this,cn);for(let n=0,i=f(this,ai);n<i;n++)if(t[n]===e)return n+1;return 0}getPageId(e){var t;return((t=f(this,cn))==null?void 0:t[e-1])??e}getMapping(){var e;return(e=f(this,cn))==null?void 0:e.subarray(0,this.pagesNumber)}}cn=new WeakMap,ia=new WeakMap,ai=new WeakMap,Id=new WeakMap,Va=new WeakMap,xi=new WeakSet,lv=function(){if(f(this,cn))return;const e=f(this,ai),t=x(this,cn,new Uint32Array(e));for(let n=0;n<e;n++)t[n]=n+1;x(this,ia,new Int32Array(t))},cv=function(){const e=new Map,t=f(this,cn);for(let n=0,i=f(this,ai);n<i;n++){const r=t[n],o=e.get(r);o?o.push(n+1):e.set(r,[n+1])}return e},FS=function(e,t=null,n=-1,i=null){const r=f(this,ia),o=f(this,cn),a=n+((i==null?void 0:i.length)??0),c=new Map;for(let l=0,u=f(this,ai);l<u;l++){if(l>=n&&l<a){r[l]=-i[l-n];continue}const h=o[l],d=e.get(h);let p=c.get(h)||0;if(t&&d)for(;p<d.length&&t.has(d[p]);)p++;r[l]=d==null?void 0:d[p],c.set(h,p+1)}};const pp=Symbol("INITIAL_DATA"),NR=()=>({...Promise.withResolvers(),data:pp});var ko;class jN{constructor(){D(this,ko,new Map)}get(e,t=null){if(t){const i=f(this,ko).getOrInsertComputed(e,NR);return i.promise.then(()=>t(i.data)),null}const n=f(this,ko).get(e);if(!n||n.data===pp)throw new Error(`Requesting object that isn't resolved yet ${e}.`);return n.data}has(e){const t=f(this,ko).get(e);return!!t&&t.data!==pp}delete(e){const t=f(this,ko).get(e);return!t||t.data===pp?!1:(f(this,ko).delete(e),!0)}resolve(e,t=null){const n=f(this,ko).getOrInsertComputed(e,NR);if(n.data!==pp)throw new Error(`Object already resolved ${e}.`);n.data=t,n.resolve()}clear(){var e;for(const{data:t}of f(this,ko).values())(e=t==null?void 0:t.bitmap)==null||e.close();f(this,ko).clear()}*[Symbol.iterator](){for(const[e,{data:t}]of f(this,ko))t!==pp&&(yield[e,t])}}ko=new WeakMap;const Ute=1e5,BR=30;var g2,xu,zi,ib,rb,cg,Rd,Kl,ob,ab,Ld,lb,ug,Iu,hg,cb,dg,Pd,ub,hb,fg,Od,db,pg,gg,xc,VN,GN,sA,no,$S,nA,qN,KN;const ni=class ni{constructor({textContentSource:e,images:t,container:n,viewport:i}){D(this,xc);D(this,xu,Promise.withResolvers());D(this,zi,null);D(this,ib,!1);D(this,rb,!!((g2=globalThis.FontInspector)!=null&&g2.enabled));D(this,cg,null);D(this,Rd,null);D(this,Kl,null);D(this,ob,0);D(this,ab,0);D(this,Ld,null);D(this,lb,null);D(this,ug,0);D(this,Iu,0);D(this,hg,Object.create(null));D(this,cb,[]);D(this,dg,null);D(this,Pd,[]);D(this,ub,new WeakMap);D(this,hb,null);var l;if(e instanceof ReadableStream)x(this,dg,e);else if(typeof e=="object")x(this,dg,new ReadableStream({start(u){u.enqueue(e),u.close()}}));else throw new Error('No "textContentSource" parameter specified.');x(this,zi,x(this,lb,n)),x(this,cg,t),x(this,Iu,i.scale*ll.pixelRatio),x(this,ug,i.rotation),x(this,Kl,{div:null,properties:null,ctx:null});const{pageWidth:r,pageHeight:o,pageX:a,pageY:c}=i.rawDims;x(this,hb,[1,0,0,-1,-a,c+o]),x(this,ab,r),x(this,ob,o),B(l=ni,no,qN).call(l),n.style.setProperty("--min-font-size",f(ni,pg)),Rf(n,i),f(this,xu).promise.finally(()=>{f(ni,gg).delete(this),x(this,Kl,null),x(this,hg,null)}).catch(()=>{})}static get fontFamilyMap(){const{isWindows:e,isFirefox:t}=Ts.platform;return Tt(this,"fontFamilyMap",new Map([["sans-serif",`${e&&t?"Calibri, ":""}sans-serif`],["monospace",`${e&&t?"Lucida Console, ":""}monospace`]]))}render(){f(this,cg)&&f(this,zi).append(f(this,cg).render());const e=()=>{f(this,Ld).read().then(({value:t,done:n})=>{if(n){f(this,xu).resolve();return}f(this,Rd)??x(this,Rd,t.lang),Object.assign(f(this,hg),t.styles),B(this,xc,VN).call(this,t.items),e()},f(this,xu).reject)};return x(this,Ld,f(this,dg).getReader()),f(ni,gg).add(this),e(),f(this,xu).promise}update({viewport:e,onBefore:t=null}){var r;const n=e.scale*ll.pixelRatio,i=e.rotation;if(i!==f(this,ug)&&(t==null||t(),x(this,ug,i),Rf(f(this,lb),{rotation:i})),n!==f(this,Iu)){t==null||t(),x(this,Iu,n);const o={div:null,properties:null,ctx:B(r=ni,no,$S).call(r,f(this,Rd))};for(const a of f(this,Pd))o.properties=f(this,ub).get(a),o.div=a,B(this,xc,sA).call(this,o)}}cancel(){var t;const e=new ch("TextLayer task cancelled.");(t=f(this,Ld))==null||t.cancel(e).catch(()=>{}),x(this,Ld,null),f(this,xu).reject(e)}get textDivs(){return f(this,Pd)}get textContentItemsStr(){return f(this,cb)}static cleanup(){if(!(f(this,gg).size>0)){f(this,fg).clear();for(const{canvas:e}of f(this,Od).values())e.remove();f(this,Od).clear()}}};xu=new WeakMap,zi=new WeakMap,ib=new WeakMap,rb=new WeakMap,cg=new WeakMap,Rd=new WeakMap,Kl=new WeakMap,ob=new WeakMap,ab=new WeakMap,Ld=new WeakMap,lb=new WeakMap,ug=new WeakMap,Iu=new WeakMap,hg=new WeakMap,cb=new WeakMap,dg=new WeakMap,Pd=new WeakMap,ub=new WeakMap,hb=new WeakMap,fg=new WeakMap,Od=new WeakMap,db=new WeakMap,pg=new WeakMap,gg=new WeakMap,xc=new WeakSet,VN=function(e){var i,r;if(f(this,ib))return;(r=f(this,Kl)).ctx??(r.ctx=B(i=ni,no,$S).call(i,f(this,Rd)));const t=f(this,Pd),n=f(this,cb);for(const o of e){if(t.length>Ute){kt("Ignoring additional textDivs for performance reasons."),x(this,ib,!0);return}if(o.str===void 0){if(o.type==="beginMarkedContentProps"||o.type==="beginMarkedContent"){const a=f(this,zi);x(this,zi,document.createElement("span")),f(this,zi).classList.add("markedContent"),o.id&&f(this,zi).setAttribute("id",`${o.id}`),o.tag==="Artifact"&&(f(this,zi).ariaHidden=!0),a.append(f(this,zi))}else o.type==="endMarkedContent"&&x(this,zi,f(this,zi).parentNode);continue}n.push(o.str),B(this,xc,GN).call(this,o)}},GN=function(e){var m;const t=document.createElement("span"),n={angle:0,canvasWidth:0,hasText:e.str!=="",hasEOL:e.hasEOL,fontSize:0};f(this,Pd).push(t);const i=Be.transform(f(this,hb),e.transform);let r=Math.atan2(i[1],i[0]);const o=f(this,hg)[e.fontName];o.vertical&&(r+=Math.PI/2);let a=f(this,rb)&&o.fontSubstitution||o.fontFamily;a=ni.fontFamilyMap.get(a)||a;const c=Math.hypot(i[2],i[3]),l=c*B(m=ni,no,KN).call(m,a,o,f(this,Rd));let u,h;r===0?(u=i[4],h=i[5]-l):(u=i[4]+l*Math.sin(r),h=i[5]-l*Math.cos(r));const d=t.style;d.left=`${(100*u/f(this,ab)).toFixed(2)}%`,d.top=`${(100*h/f(this,ob)).toFixed(2)}%`,d.setProperty("--font-height",`${c.toFixed(2)}px`),d.fontFamily=a,n.fontSize=c,t.setAttribute("role","presentation"),t.textContent=e.str,t.dir=e.dir,f(this,rb)&&(t.dataset.fontName=o.fontSubstitutionLoadedName||e.fontName),r!==0&&(n.angle=r*(180/Math.PI));let p=!1;if(e.str.length>1)p=!0;else if(e.str!==" "&&e.transform[0]!==e.transform[3]){const v=Math.abs(e.transform[0]),g=Math.abs(e.transform[3]);v!==g&&Math.max(v,g)/Math.min(v,g)>1.5&&(p=!0)}if(p&&(n.canvasWidth=o.vertical?e.height:e.width),f(this,ub).set(t,n),f(this,Kl).div=t,f(this,Kl).properties=n,B(this,xc,sA).call(this,f(this,Kl)),n.hasText&&f(this,zi).append(t),n.hasEOL){const v=document.createElement("br");v.setAttribute("role","presentation"),f(this,zi).append(v)}},sA=function(e){var o;const{div:t,properties:n,ctx:i}=e,{style:r}=t;if(n.canvasWidth!==0&&n.hasText){const{fontFamily:a}=r,{canvasWidth:c,fontSize:l}=n;B(o=ni,no,nA).call(o,i,l*f(this,Iu),a);const{width:u}=i.measureText(t.textContent);u>0&&r.setProperty("--scale-x",c*f(this,Iu)/u)}n.angle!==0&&r.setProperty("--rotate",`${n.angle}deg`)},no=new WeakSet,$S=function(e=null){let t=f(this,Od).get(e||(e=""));if(!t){const n=document.createElement("canvas");n.style.cssText="position:absolute;top:0;left:0;width:0;height:0;display:none;letter-spacing:normal;word-spacing:normal",n.lang=e,document.body.append(n),t=n.getContext("2d",{alpha:!1,willReadFrequently:!0}),f(this,Od).set(e,t),f(this,db).set(t,{size:0,family:""})}return t},nA=function(e,t,n){const i=f(this,db).get(e);t===i.size&&n===i.family||(e.font=`${t}px ${n}`,i.size=t,i.family=n)},qN=function(){if(f(this,pg)!==null)return;const e=document.createElement("div");e.style.opacity=0,e.style.lineHeight=1,e.style.fontSize="1px",e.style.position="absolute",e.textContent="X",document.body.append(e),x(this,pg,e.getBoundingClientRect().height),e.remove()},KN=function(e,t,n){const i=f(this,fg).get(e);if(i)return i;const r=B(this,no,$S).call(this,n);r.canvas.width=r.canvas.height=BR,B(this,no,nA).call(this,r,BR,e);const o=r.measureText(""),a=o.fontBoundingBoxAscent,c=Math.abs(o.fontBoundingBoxDescent);r.canvas.width=r.canvas.height=0;let l=.8;return a?l=a/(a+c):(Ts.platform.isFirefox&&kt("Enable the `dom.textMetrics.fontBoundingBox.enabled` preference in `about:config` to improve TextLayer rendering."),t.ascent?l=t.ascent:t.descent&&(l=1+t.descent)),f(this,fg).set(e,l),l},D(ni,no),D(ni,fg,new Map),D(ni,Od,new Map),D(ni,db,new WeakMap),D(ni,pg,null),D(ni,gg,new Set);let uy=ni;const Wte=100;function QN(s={}){const e=new iA,{docId:t}=e,n=s.url?Qee(s.url):null,i=s.data?Xee(s.data):null,r=s.httpHeaders||null,o=s.withCredentials===!0,a=s.password??null,c=s.range instanceof XN?s.range:null,l=Number.isInteger(s.rangeChunkSize)&&s.rangeChunkSize>0?s.rangeChunkSize:2**16;let u=s.worker instanceof hy?s.worker:null;const h=s.verbosity,d=typeof s.docBaseUrl=="string"&&!pk(s.docBaseUrl)?s.docBaseUrl:null,p=G_(s.cMapUrl),m=s.cMapPacked!==!1,v=G_(s.iccUrl),g=G_(s.standardFontDataUrl),y=G_(s.wasmUrl),b=s.stopAtErrors!==!0,_=Number.isInteger(s.maxImageSize)&&s.maxImageSize>-1?s.maxImageSize:-1,w=typeof s.isOffscreenCanvasSupported=="boolean"?s.isOffscreenCanvasSupported:!Zr,S=typeof s.isImageDecoderSupported=="boolean"?s.isImageDecoderSupported:!Zr,C=Number.isInteger(s.canvasMaxAreaInBytes)?s.canvasMaxAreaInBytes:-1,T=typeof s.disableFontFace=="boolean"?s.disableFontFace:Zr,k=s.fontExtraProperties===!0,A=s.enableXfa===!0,M=s.ownerDocument||globalThis.document,R=s.disableRange===!0,P=s.disableStream===!0,L=s.disableAutoFetch===!0,z=s.pdfBug===!0,Q=s.CanvasFactory||(Zr?ite:ete),W=s.FilterFactory||(Zr?nte:tte),V=s.BinaryDataFactory||(Zr?rte:kR),N=s.enableHWA===!0,H=s.enableWebGPU===!0?lte():Promise.resolve(!1),G=s.useWasm!==!1,ee=s.pagesMapper||new Hte,ie=typeof s.useSystemFonts=="boolean"?s.useSystemFonts:!Zr&&!T,ve=typeof s.useWorkerFetch=="boolean"?s.useWorkerFetch:!!(V===kR&&p&&m&&g&&y&&$v(p,document.baseURI)&&$v(g,document.baseURI)&&$v(y,document.baseURI)),le=null;vee(h);const oe={canvasFactory:new Q({ownerDocument:M,enableHWA:N}),filterFactory:new W({docId:t,ownerDocument:M}),binaryDataFactory:ve?null:new V({cMapUrl:p,standardFontDataUrl:g,wasmUrl:y})};u||(u=hy.create({verbosity:h,port:sl.workerPort}),e._worker=u);const I={docId:t,apiVersion:"6.0.227",data:i,password:a,disableAutoFetch:L,rangeChunkSize:l,docBaseUrl:d,enableXfa:A,evaluatorOptions:{maxImageSize:_,disableFontFace:T,ignoreErrors:b,isOffscreenCanvasSupported:w,isImageDecoderSupported:S,canvasMaxAreaInBytes:C,fontExtraProperties:k,useSystemFonts:ie,useWasm:G,useWorkerFetch:ve,cMapUrl:p,cMapPacked:m,iccUrl:v,standardFontDataUrl:g,wasmUrl:y,hasGPU:!1}},K={ownerDocument:M,pdfBug:z,styleElement:le,enableHWA:N,loadingParams:{disableAutoFetch:L,enableXfa:A}};return Promise.all([u.promise,H]).then(function([,X]){if(u.destroyed)throw new Error("Worker was destroyed");I.evaluatorOptions.hasGPU=X;const J=u.messageHandler.sendWithPromise("GetDocRequest",I,i?[i.buffer]:null);let he;if(!i)if(c)he=new Ate({pdfDataRangeTransport:c,disableRange:R,disableStream:P});else if(n){const be=Nte(n);he=new be({url:n,httpHeaders:r,withCredentials:o,rangeChunkSize:l,disableRange:R,disableStream:P})}else throw new Error("getDocument - expected either `data`, `range`, or `url` parameter.");return J.then(be=>{if(u.destroyed)throw new Error("Worker was destroyed");const Re=new nv(t,be,u.port),rt=new jte(Re,e,he,K,oe,ee);if(e._transport=rt,e.destroyed)throw new Error("Loading aborted");Re.send("Ready",null)})}).catch(e._capability.reject).finally(e._setupCapability.resolve),e}var D0;const N0=class N0{constructor(){_e(this,"_capability",Promise.withResolvers());_e(this,"_setupCapability",Promise.withResolvers());_e(this,"_transport",null);_e(this,"_worker",null);_e(this,"docId",`d${xs(N0,D0)._++}`);_e(this,"destroyed",!1);_e(this,"onPassword",null);_e(this,"onProgress",null)}get promise(){return this._capability.promise}async destroy(){var e,t,n,i;this.destroyed=!0,this._capability.promise.catch(()=>{});try{(e=this._worker)!=null&&e.port&&(this._worker._pendingDestroy=!0),await this._setupCapability.promise,await((t=this._transport)==null?void 0:t.destroy())}catch(r){throw(n=this._worker)!=null&&n.port&&delete this._worker._pendingDestroy,r}this._transport=null,(i=this._worker)==null||i.destroy(),this._worker=null}async getData(){return this._transport.getData()}};D0=new WeakMap,D(N0,D0,0);let iA=N0;var mg,Dd;class XN{constructor(e,t,n=!1,i=null){D(this,mg,Promise.withResolvers());D(this,Dd,null);this.length=e,this.initialData=t,this.progressiveDone=n,this.contentDispositionFilename=i}onDataRange(e,t){f(this,Dd).call(this,{type:"range",begin:e,chunk:t})}onDataProgressiveRead(e){f(this,mg).promise.then(()=>{f(this,Dd).call(this,{type:"progressiveRead",chunk:e})})}onDataProgressiveDone(){f(this,mg).promise.then(()=>{f(this,Dd).call(this,{type:"progressiveDone"})})}transportReady(e){x(this,Dd,e),f(this,mg).resolve()}requestDataRange(e,t){es("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}mg=new WeakMap,Dd=new WeakMap;class zte{constructor(e,t){this._pdfInfo=e,this._transport=t}get pagesMapper(){return this._transport.pagesMapper}get annotationStorage(){return this._transport.annotationStorage}get canvasFactory(){return this._transport.canvasFactory}get filterFactory(){return this._transport.filterFactory}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get isPureXfa(){return Tt(this,"isPureXfa",!!this._transport._htmlForXfa)}get allXfaHtml(){return this._transport._htmlForXfa}getPage(e){return this._transport.getPage(e)}getPageIndex(e){return this._transport.getPageIndex(e)}getDestinations(){return this._transport.getDestinations()}getDestination(e){return this._transport.getDestination(e)}getPageLabels(){return this._transport.getPageLabels()}getPageLayout(){return this._transport.getPageLayout()}getPageMode(){return this._transport.getPageMode()}getViewerPreferences(){return this._transport.getViewerPreferences()}getOpenAction(){return this._transport.getOpenAction()}getAttachments(){return this._transport.getAttachments()}getAnnotationsByType(e,t){return this._transport.getAnnotationsByType(e,t)}getJSActions(){return this._transport.getDocJSActions()}getOutline(){return this._transport.getOutline()}getOptionalContentConfig({intent:e="display"}={}){const{renderingIntent:t}=this._transport.getRenderingIntent(e);return this._transport.getOptionalContentConfig(t)}getPermissions(){return this._transport.getPermissions()}getMetadata(){return this._transport.getMetadata()}getMarkInfo(){return this._transport.getMarkInfo()}getData(){return this._transport.getData()}saveDocument(){return this._transport.saveDocument()}extractPages(e){return this._transport.extractPages(e)}getDownloadInfo(){return this._transport.downloadInfoCapability.promise}getRawData(e){return this._transport.getRawData(e)}cleanup(e=!1){return this._transport.startCleanup(e||this.isPureXfa)}cachedPageNumber(e){return this._transport.cachedPageNumber(e)}get loadingParams(){return this._transport.loadingParams}get loadingTask(){return this._transport.loadingTask}getFieldObjects(){return this._transport.getFieldObjects()}hasJSActions(){return this._transport.hasJSActions()}getCalculationOrderIds(){return this._transport.getCalculationOrderIds()}}var Ql,Nd,Bd,uv;const TM=class TM{constructor(e,t,n,i,r=!1){D(this,Bd);D(this,Ql,!1);D(this,Nd,null);this._pageIndex=e,this._pageInfo=t,this._transport=n,this._stats=r?new dR:null,this._pdfBug=r,this.commonObjs=n.commonObjs,this.objs=new jN,this._intentStates=new Map,this.destroyed=!1,this.recordedBBoxes=null,x(this,Nd,i),this.imageCoordinates=null}clone(e){const t=new TM(e,this._pageInfo,this._transport,f(this,Nd),this._pdfBug);return t.clonedFromIndex=this.clonedFromIndex??this._pageIndex,this._transport.updatePage(t),t}get pageNumber(){return this._pageIndex+1}set pageNumber(e){this._pageIndex=e-1,this._transport.updatePage(this)}get rotate(){return this._pageInfo.rotate}get ref(){return this._pageInfo.ref}get userUnit(){return this._pageInfo.userUnit}get view(){return this._pageInfo.view}getViewport({scale:e,rotation:t=this.rotate,offsetX:n=0,offsetY:i=0,dontFlip:r=!1}={}){return new s_({viewBox:this.view,userUnit:this.userUnit,scale:e,rotation:t,offsetX:n,offsetY:i,dontFlip:r})}getAnnotations({intent:e="display"}={}){const{renderingIntent:t}=this._transport.getRenderingIntent(e);return this._transport.getAnnotations(this._pageIndex,t)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return Tt(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){var e;return((e=this._transport._htmlForXfa)==null?void 0:e.children[this._pageIndex])||null}render({canvasContext:e,canvas:t=e.canvas,viewport:n,intent:i="display",annotationMode:r=Zc.ENABLE,transform:o=null,background:a=null,optionalContentConfigPromise:c=null,annotationCanvasMap:l=null,pageColors:u=null,printAnnotationStorage:h=null,isEditing:d=!1,recordImages:p=!1,recordOperations:m=!1,operationsFilter:v=null}){var L,z,Q;(L=this._stats)==null||L.time("Overall");const g=this._transport.getRenderingIntent(i,r,h,d),{renderingIntent:y,cacheKey:b}=g;x(this,Ql,!1),c||(c=this._transport.getOptionalContentConfig(y));const _=this._intentStates.getOrInsertComputed(b,ST);_.streamReaderCancelTimeout&&(clearTimeout(_.streamReaderCancelTimeout),_.streamReaderCancelTimeout=null);const w=!!(y&Jr.PRINT);_.displayReadyCapability||(_.displayReadyCapability=Promise.withResolvers(),_.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},(z=this._stats)==null||z.time("Page Request"),this._pumpOperatorList(g));const S=!!(this._pdfBug&&((Q=globalThis.StepperManager)!=null&&Q.enabled)),C=!!t&&!this.recordedBBoxes&&(m||S),T=!!t&&!this.imageCoordinates&&p,k=W=>{var V,N,O,H;if(_.renderTasks.delete(R),C){const G=(V=R.gfx)==null?void 0:V.dependencyTracker.take();G&&((N=R.stepper)==null||N.setOperatorBBoxes(G,R.gfx.dependencyTracker.takeDebugMetadata()),m&&(this.recordedBBoxes=G))}T&&!W&&(this.imageCoordinates=(O=R.gfx)==null?void 0:O.imagesTracker.take()),w&&x(this,Ql,!0),B(this,Bd,uv).call(this),W?(R.capability.reject(W),this._abortOperatorList({intentState:_,reason:W instanceof Error?W:new Error(W)})):R.capability.resolve(),this._stats&&(this._stats.timeEnd("Rendering"),this._stats.timeEnd("Overall"),(H=globalThis.Stats)!=null&&H.enabled&&globalThis.Stats.add(this.pageNumber,this._stats))};let A=null,M=null;(C||T)&&(M=new Hee(t,_.operatorList.length)),C&&(A=new Uee(M,S));const R=new oA({callback:k,params:{canvas:t,canvasContext:e,dependencyTracker:A??M,imagesTracker:T?new zT(t):null,viewport:n,transform:o,background:a},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:l,operatorList:_.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!w,pdfBug:this._pdfBug,pageColors:u,enableHWA:this._transport.enableHWA,operationsFilter:v});(_.renderTasks||(_.renderTasks=new Set)).add(R);const P=R.task;return Promise.all([_.displayReadyCapability.promise,c]).then(([W,V])=>{var N;if(this.destroyed){k();return}if((N=this._stats)==null||N.time("Rendering"),!(V.renderingIntent&y))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");R.initializeGraphics({transparency:W,optionalContentConfig:V}),R.operatorListChanged()}).catch(k),P}getOperatorList({intent:e="display",annotationMode:t=Zc.ENABLE,printAnnotationStorage:n=null,isEditing:i=!1}={}){var l;function r(){a.operatorList.lastChunk&&(a.opListReadCapability.resolve(a.operatorList),a.renderTasks.delete(c))}const o=this._transport.getRenderingIntent(e,t,n,i,!0),a=this._intentStates.getOrInsertComputed(o.cacheKey,ST);let c;return a.opListReadCapability||(c=Object.create(null),c.operatorListChanged=r,a.opListReadCapability=Promise.withResolvers(),(a.renderTasks||(a.renderTasks=new Set)).add(c),a.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},(l=this._stats)==null||l.time("Page Request"),this._pumpOperatorList(o)),a.opListReadCapability.promise}streamTextContent({includeMarkedContent:e=!1,disableNormalization:t=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageId:f(this,Nd).getPageId(this._pageIndex+1)-1,pageIndex:this._pageIndex,includeMarkedContent:e===!0,disableNormalization:t===!0},{highWaterMark:100,size(i){return i.items.length}})}async getTextContent(e={}){if(this._transport._htmlForXfa)return this.getXfa().then(i=>ay.textContent(i));const t=this.streamTextContent(e),n={items:[],styles:Object.create(null),lang:null};for await(const i of t)n.lang??(n.lang=i.lang),Object.assign(n.styles,i.styles),n.items.push(...i.items);return n}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;const e=[];for(const t of this._intentStates.values())if(this._abortOperatorList({intentState:t,reason:new Error("Page was destroyed."),force:!0}),!t.opListReadCapability)for(const n of t.renderTasks)e.push(n.completed),n.cancel();return this.objs.clear(),x(this,Ql,!1),Promise.all(e)}cleanup(e=!1){x(this,Ql,!0);const t=B(this,Bd,uv).call(this);return e&&t&&this._stats&&(this._stats=new dR),t}_startRenderPage(e,t){var i,r;const n=this._intentStates.get(t);n&&((i=this._stats)==null||i.timeEnd("Page Request"),(r=n.displayReadyCapability)==null||r.resolve(e))}_renderPageChunk(e,t){for(let n=0,i=e.length;n<i;n++)t.operatorList.fnArray.push(e.fnArray[n]),t.operatorList.argsArray.push(e.argsArray[n]);t.operatorList.lastChunk=e.lastChunk,t.operatorList.separateAnnots=e.separateAnnots;for(const n of t.renderTasks)n.operatorListChanged();e.lastChunk&&B(this,Bd,uv).call(this)}_pumpOperatorList({renderingIntent:e,cacheKey:t,annotationStorageSerializable:n,modifiedIds:i}){const{map:r,transfer:o}=n,c=this._transport.messageHandler.sendWithStream("GetOperatorList",{pageId:f(this,Nd).getPageId(this._pageIndex+1)-1,pageIndex:this._pageIndex,intent:e,cacheKey:t,annotationStorage:r,modifiedIds:i},void 0,o).getReader(),l=this._intentStates.get(t);l.streamReader=c;const u=()=>{c.read().then(({value:h,done:d})=>{if(d){l.streamReader=null;return}this._transport.destroyed||(this._renderPageChunk(h,l),u())},h=>{if(l.streamReader=null,!this._transport.destroyed){if(l.operatorList){l.operatorList.lastChunk=!0;for(const d of l.renderTasks)d.operatorListChanged();B(this,Bd,uv).call(this)}if(l.displayReadyCapability)l.displayReadyCapability.reject(h);else if(l.opListReadCapability)l.opListReadCapability.reject(h);else throw h}})};u()}_abortOperatorList({intentState:e,reason:t,force:n=!1}){if(e.streamReader){if(e.streamReaderCancelTimeout&&(clearTimeout(e.streamReaderCancelTimeout),e.streamReaderCancelTimeout=null),!n){if(e.renderTasks.size>0)return;if(t instanceof uM){let i=Wte;t.extraDelay>0&&t.extraDelay<1e3&&(i+=t.extraDelay),e.streamReaderCancelTimeout=setTimeout(()=>{e.streamReaderCancelTimeout=null,this._abortOperatorList({intentState:e,reason:t,force:!0})},i);return}}if(e.streamReader.cancel(new ch(t.message)).catch(()=>{}),e.streamReader=null,!this._transport.destroyed){for(const[i,r]of this._intentStates)if(r===e){this._intentStates.delete(i);break}this.cleanup()}}}get stats(){return this._stats}};Ql=new WeakMap,Nd=new WeakMap,Bd=new WeakSet,uv=function(){if(!f(this,Ql)||this.destroyed)return!1;for(const{renderTasks:e,operatorList:t}of this._intentStates.values())if(e.size>0||!t.lastChunk)return!1;return this._intentStates.clear(),this.objs.clear(),x(this,Ql,!1),!0};let rA=TM;var Ru,ra,Xl,Fd,B0,$d,Hd,Ji,HS,YN,JN,hv,vg,US;const Zs=class Zs{constructor({name:e=null,port:t=null,verbosity:n=yee()}={}){D(this,Ji);D(this,Ru,Promise.withResolvers());D(this,ra,null);D(this,Xl,null);D(this,Fd,null);if(this.name=e,this.destroyed=!1,this.verbosity=n,t){if(f(Zs,Hd).has(t))throw new Error("Cannot use more than one PDFWorker per port.");f(Zs,Hd).set(t,this),B(this,Ji,YN).call(this,t)}else B(this,Ji,JN).call(this)}get promise(){return f(this,Ru).promise}get port(){return f(this,Xl)}get messageHandler(){return f(this,ra)}destroy(){var e,t;this.destroyed=!0,(e=f(this,Fd))==null||e.terminate(),x(this,Fd,null),f(Zs,Hd).delete(f(this,Xl)),x(this,Xl,null),(t=f(this,ra))==null||t.destroy(),x(this,ra,null)}static create(e){const t=f(this,Hd).get(e==null?void 0:e.port);if(t){if(t._pendingDestroy)throw new Error("PDFWorker.create - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return t}return new Zs(e)}static get workerSrc(){if(sl.workerSrc)return sl.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get _setupFakeWorkerGlobal(){return Tt(this,"_setupFakeWorkerGlobal",(async()=>f(this,vg,US)?f(this,vg,US):(await import(this.workerSrc)).WorkerMessageHandler)())}};Ru=new WeakMap,ra=new WeakMap,Xl=new WeakMap,Fd=new WeakMap,B0=new WeakMap,$d=new WeakMap,Hd=new WeakMap,Ji=new WeakSet,HS=function(){f(this,Ru).resolve(),f(this,ra).send("configure",{verbosity:this.verbosity})},YN=function(e){x(this,Xl,e),x(this,ra,new nv("main","worker",e)),f(this,ra).on("ready",()=>{}),B(this,Ji,HS).call(this)},JN=function(){if(f(Zs,$d)||f(Zs,vg,US)){B(this,Ji,hv).call(this);return}let{workerSrc:e}=Zs;try{Zs._isSameOrigin(window.location,e)||(e=Zs._createCDNWrapper(new URL(e,window.location).href));const t=new Worker(e,{type:"module"}),n=new nv("main","worker",t),i=()=>{r.abort(),n.destroy(),t.terminate(),this.destroyed?f(this,Ru).reject(new Error("Worker was destroyed")):B(this,Ji,hv).call(this)},r=new AbortController;t.addEventListener("error",()=>{f(this,Fd)||i()},{signal:r.signal}),n.on("test",a=>{if(r.abort(),this.destroyed||!a){i();return}x(this,ra,n),x(this,Xl,t),x(this,Fd,t),B(this,Ji,HS).call(this)}),n.on("ready",a=>{if(r.abort(),this.destroyed){i();return}try{o()}catch{B(this,Ji,hv).call(this)}});const o=()=>{const a=new Uint8Array;n.send("test",a,[a.buffer])};o();return}catch{dk("The worker has been disabled.")}B(this,Ji,hv).call(this)},hv=function(){f(Zs,$d)||(kt("Setting up fake worker."),x(Zs,$d,!0)),Zs._setupFakeWorkerGlobal.then(e=>{if(this.destroyed){f(this,Ru).reject(new Error("Worker was destroyed"));return}const t=new Zee;x(this,Xl,t);const n=`fake${xs(Zs,B0)._++}`,i=new nv(n+"_worker",n,t);e.setup(i,t),x(this,ra,new nv(n,n+"_worker",t)),B(this,Ji,HS).call(this)}).catch(e=>{f(this,Ru).reject(new Error(`Setting up fake worker failed: "${e.message}".`))})},vg=new WeakSet,US=function(){var e;try{return((e=globalThis.pdfjsWorker)==null?void 0:e.WorkerMessageHandler)||null}catch{return null}},D(Zs,vg),D(Zs,B0,0),D(Zs,$d,!1),D(Zs,Hd,new WeakMap),Zr&&(x(Zs,$d,!0),sl.workerSrc||(sl.workerSrc="./pdf.worker.mjs")),Zs._isSameOrigin=(e,t)=>{const n=URL.parse(e);if(!(n!=null&&n.origin)||n.origin==="null")return!1;const i=new URL(t,n);return n.origin===i.origin},Zs._createCDNWrapper=e=>{const t=`await import("${e}");`;return URL.createObjectURL(new Blob([t],{type:"text/javascript"}))};let hy=Zs;var Fr,Ud,Yl,oa,Wd,yg,Jl,ga,dv,WS;class jte{constructor(e,t,n,i,r,o){D(this,ga);_e(this,"downloadInfoCapability",Promise.withResolvers());D(this,Fr,null);D(this,Ud,new Map);D(this,Yl,null);D(this,oa,new Map);D(this,Wd,new Map);D(this,yg,new Map);D(this,Jl,null);this.messageHandler=e,this.loadingTask=t,x(this,Yl,n),this.commonObjs=new jN,this.fontLoader=new Wee({ownerDocument:i.ownerDocument,styleElement:i.styleElement}),this.enableHWA=i.enableHWA,this.loadingParams=i.loadingParams,this._params=i,this.canvasFactory=r.canvasFactory,this.filterFactory=r.filterFactory,this.binaryDataFactory=r.binaryDataFactory,this.pagesMapper=o,this.destroyed=!1,this.destroyCapability=null,this.setupMessageHandler()}updatePage(e){const{_pageIndex:t}=e;f(this,oa).set(t,e),f(this,Wd).set(t,Promise.resolve(e))}get annotationStorage(){return Tt(this,"annotationStorage",new dM)}getRenderingIntent(e,t=Zc.ENABLE,n=null,i=!1,r=!1){let o=Jr.DISPLAY,a=ly;switch(e){case"any":o=Jr.ANY;break;case"display":break;case"print":o=Jr.PRINT;break;default:kt(`getRenderingIntent - invalid intent: ${e}`)}const c=o&Jr.PRINT&&n instanceof gN?n:this.annotationStorage;switch(t){case Zc.DISABLE:o+=Jr.ANNOTATIONS_DISABLE;break;case Zc.ENABLE:break;case Zc.ENABLE_FORMS:o+=Jr.ANNOTATIONS_FORMS;break;case Zc.ENABLE_STORAGE:o+=Jr.ANNOTATIONS_STORAGE,a=c.serializable;break;default:kt(`getRenderingIntent - invalid annotationMode: ${t}`)}i&&(o+=Jr.IS_EDITING),r&&(o+=Jr.OPLIST);const{ids:l,hash:u}=c.modifiedIds,h=[o,a.hash,u];return{renderingIntent:o,cacheKey:h.join("_"),annotationStorageSerializable:a,modifiedIds:l}}destroy(){var n;if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=Promise.withResolvers(),(n=f(this,Jl))==null||n.reject(new Error("Worker was destroyed during onPassword callback"));const e=[];for(const i of f(this,oa).values())e.push(i._destroy());f(this,oa).clear(),f(this,Wd).clear(),f(this,yg).clear(),Object.hasOwn(this,"annotationStorage")&&this.annotationStorage.resetModified();const t=this.messageHandler.sendWithPromise("Terminate",null);return e.push(t),Promise.all(e).then(()=>{var i,r;this.commonObjs.clear(),this.fontLoader.clear(),f(this,Ud).clear(),this.filterFactory.destroy(),uy.cleanup(),(i=f(this,Yl))==null||i.cancelAllRequests(new ch("Worker was terminated.")),(r=this.messageHandler)==null||r.destroy(),this.messageHandler=null,this.destroyCapability.resolve()},this.destroyCapability.reject),this.destroyCapability.promise}setupMessageHandler(){const{messageHandler:e,loadingTask:t}=this;e.on("GetReader",(n,i)=>{Gs(f(this,Yl),"GetReader - no `BasePDFStream` instance available."),x(this,Fr,f(this,Yl).getFullReader()),f(this,Fr).onProgress=r=>B(this,ga,WS).call(this,r),i.onPull=()=>{f(this,Fr).read().then(function({value:r,done:o}){if(o){i.close();return}Gs(r instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer."),i.enqueue(new Uint8Array(r),1,[r])}).catch(r=>{i.error(r)})},i.onCancel=r=>{f(this,Fr).cancel(r),i.ready.catch(o=>{if(!this.destroyed)throw o})}}),e.on("ReaderHeadersReady",async n=>{await f(this,Fr).headersReady;const{isStreamingSupported:i,isRangeSupported:r,contentLength:o}=f(this,Fr);return i&&r&&(f(this,Fr).onProgress=null),{isStreamingSupported:i,isRangeSupported:r,contentLength:o}}),e.on("GetRangeReader",(n,i)=>{Gs(f(this,Yl),"GetRangeReader - no `BasePDFStream` instance available.");const r=f(this,Yl).getRangeReader(n.begin,n.end);if(!r){i.close();return}i.onPull=()=>{r.read().then(function({value:o,done:a}){if(a){i.close();return}Gs(o instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer."),i.enqueue(new Uint8Array(o),1,[o])}).catch(o=>{i.error(o)})},i.onCancel=o=>{r.cancel(o),i.ready.catch(a=>{if(!this.destroyed)throw a})}}),e.on("GetDoc",({pdfInfo:n})=>{this.pagesMapper.pagesNumber=n.numPages,this._numPages=n.numPages,this._htmlForXfa=n.htmlForXfa,delete n.htmlForXfa,t._capability.resolve(new zte(n,this))}),e.on("DocException",n=>{t._capability.reject(or(n))}),e.on("PasswordRequest",n=>{x(this,Jl,Promise.withResolvers());try{if(!t.onPassword)throw or(n);const i=r=>{r instanceof Error?f(this,Jl).reject(r):f(this,Jl).resolve({password:r})};t.onPassword(i,n.code)}catch(i){f(this,Jl).reject(i)}return f(this,Jl).promise}),e.on("DataLoaded",n=>{B(this,ga,WS).call(this,{loaded:n.length,total:n.length}),this.downloadInfoCapability.resolve(n)}),e.on("StartRenderPage",n=>{if(this.destroyed)return;f(this,oa).get(n.pageIndex)._startRenderPage(n.transparency,n.cacheKey)}),e.on("commonobj",([n,i,r])=>{var o;if(this.destroyed||this.commonObjs.has(n))return null;switch(i){case"Font":if("error"in r){const d=r.error;kt(`Error during font loading: ${d}`),this.commonObjs.resolve(n,d);break}const a=new Gee(r),c=this._params.pdfBug&&((o=globalThis.FontInspector)!=null&&o.enabled)?(d,p)=>globalThis.FontInspector.fontAdded(d,p):null,l=new zee(a,c,r.charProcOperatorList,r.extra);this.fontLoader.bind(l).catch(()=>e.sendWithPromise("FontFallback",{id:n})).finally(()=>{l.fontExtraProperties||l.clearData(),this.commonObjs.resolve(n,l)});break;case"CopyLocalImage":const{imageRef:u}=r;Gs(u,"The imageRef must be defined.");for(const d of f(this,oa).values())for(const[,p]of d.objs){if((p==null?void 0:p.ref)!==u)continue;if(!p.dataLen)return null;const m=structuredClone(p);return this.commonObjs.resolve(n,m),p.dataLen}break;case"FontPath":this.commonObjs.resolve(n,new Kee(r));break;case"Image":this.commonObjs.resolve(n,r);break;case"Pattern":const h=new qee(r);this.commonObjs.resolve(n,h.getIR());break;default:throw new Error(`Got unknown common object type ${i}`)}return null}),e.on("obj",([n,i,r,o])=>{var c;if(this.destroyed)return;const a=f(this,oa).get(i);if(!a.objs.has(n)){if(a._intentStates.size===0){(c=o==null?void 0:o.bitmap)==null||c.close();return}switch(r){case"Image":case"Pattern":a.objs.resolve(n,o);break;default:throw new Error(`Got unknown object type ${r}`)}}}),e.on("DocProgress",n=>{this.destroyed||B(this,ga,WS).call(this,n)}),e.on("FetchBinaryData",async n=>{if(this.destroyed)throw new Error("Worker was destroyed.");if(!this.binaryDataFactory)throw new Error("`BinaryDataFactory` not initialized, see the `useWorkerFetch` parameter.");return this.binaryDataFactory.fetch(n)})}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){var n;this.annotationStorage.size<=0&&kt("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");const{map:e,transfer:t}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:e,filename:((n=f(this,Fr))==null?void 0:n.filename)??null},t).finally(()=>{this.annotationStorage.resetModified()})}extractPages(e){var r;const t={pageInfos:e};let n;const i=globalThis.ImageBitmap;if(typeof i=="function"){const o=Array.isArray(e)?e:[e];for(const a of o)(a==null?void 0:a.image)instanceof i&&(n||(n=[])).push(a.image)}if(this.annotationStorage.size>0){const o=this.annotationStorage.serializable;let{map:a}=o;(r=o.transfer)!=null&&r.length&&(n?n.push(...o.transfer):n=o.transfer);const c=this.pagesMapper.getMapping();if(c){const l=new Map;for(const[u,h]of a){if((h==null?void 0:h.pageIndex)!==void 0&&h.pageIndex>=0&&h.pageIndex<c.length){const d=c[h.pageIndex]-1;if(d!==h.pageIndex){l.set(u,{...h,pageIndex:d});continue}}l.set(u,h)}a=l}t.annotationStorage=a}return this.messageHandler.sendWithPromise("ExtractPages",t,n).finally(()=>{this.annotationStorage.resetModified()})}getPage(e){if(!Number.isInteger(e)||e<=0||e>this.pagesMapper.pagesNumber)return Promise.reject(new Error("Invalid page request."));const t=e-1,n=this.pagesMapper.getPageId(e)-1,i=f(this,Wd).get(t);if(i)return i;const r=this.messageHandler.sendWithPromise("GetPage",{pageIndex:n}).then(o=>{if(this.destroyed)throw new Error("Transport destroyed");o.refStr&&f(this,yg).set(o.refStr,n);const a=new rA(t,o,this,this.pagesMapper,this._params.pdfBug);return f(this,oa).set(t,a),a});return f(this,Wd).set(t,r),r}async getPageIndex(e){if(!VT(e))throw new Error("Invalid pageIndex request.");const t=await this.messageHandler.sendWithPromise("GetPageIndex",{num:e.num,gen:e.gen}),n=this.pagesMapper.getPageNumber(t+1);if(n===0)throw new Error("GetPageIndex: page has been removed.");return n-1}getAnnotations(e,t){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:this.pagesMapper.getPageId(e+1)-1,intent:t})}getFieldObjects(){return B(this,ga,dv).call(this,"GetFieldObjects")}hasJSActions(){return B(this,ga,dv).call(this,"HasJSActions")}getCalculationOrderIds(){return this.messageHandler.sendWithPromise("GetCalculationOrderIds",null)}getDestinations(){return this.messageHandler.sendWithPromise("GetDestinations",null)}getDestination(e){return typeof e!="string"?Promise.reject(new Error("Invalid destination request.")):this.messageHandler.sendWithPromise("GetDestination",{id:e})}getPageLabels(){return this.messageHandler.sendWithPromise("GetPageLabels",null)}getPageLayout(){return this.messageHandler.sendWithPromise("GetPageLayout",null)}getPageMode(){return this.messageHandler.sendWithPromise("GetPageMode",null)}getViewerPreferences(){return this.messageHandler.sendWithPromise("GetViewerPreferences",null)}getOpenAction(){return this.messageHandler.sendWithPromise("GetOpenAction",null)}getAttachments(){return this.messageHandler.sendWithPromise("GetAttachments",null)}getAnnotationsByType(e,t){return this.messageHandler.sendWithPromise("GetAnnotationsByType",{types:e,pageIndexesToSkip:t})}getDocJSActions(){return B(this,ga,dv).call(this,"GetDocJSActions")}getPageJSActions(e){return this.messageHandler.sendWithPromise("GetPageJSActions",{pageIndex:this.pagesMapper.getPageId(e+1)-1})}getStructTree(e){return this.messageHandler.sendWithPromise("GetStructTree",{pageIndex:this.pagesMapper.getPageId(e+1)-1})}getOutline(){return this.messageHandler.sendWithPromise("GetOutline",null)}getOptionalContentConfig(e){return B(this,ga,dv).call(this,"GetOptionalContentConfig").then(t=>new $te(t,e))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const e="GetMetadata";return f(this,Ud).getOrInsertComputed(e,()=>this.messageHandler.sendWithPromise(e,null).then(t=>{var n,i;return{info:t[0],metadata:t[1]?new Bte(t[1]):null,contentDispositionFilename:((n=f(this,Fr))==null?void 0:n.filename)??null,contentLength:((i=f(this,Fr))==null?void 0:i.contentLength)??null,hasStructTree:t[2]}}))}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}getRawData(e){return this.messageHandler.sendWithPromise("GetRawData",e)}async startCleanup(e=!1){if(!this.destroyed){await this.messageHandler.sendWithPromise("Cleanup",null);for(const t of f(this,oa).values())if(!t.cleanup())throw new Error(`startCleanup: Page ${t.pageNumber} is currently rendering.`);this.commonObjs.clear(),e||this.fontLoader.clear(),f(this,Ud).clear(),this.filterFactory.destroy(!0),uy.cleanup()}}cachedPageNumber(e){if(!VT(e))return null;const t=e.gen===0?`${e.num}R`:`${e.num}R${e.gen}`,n=f(this,yg).get(t);if(n>=0){const i=this.pagesMapper.getPageNumber(n+1);if(i!==0)return i}return null}}Fr=new WeakMap,Ud=new WeakMap,Yl=new WeakMap,oa=new WeakMap,Wd=new WeakMap,yg=new WeakMap,Jl=new WeakMap,ga=new WeakSet,dv=function(e,t=null){return f(this,Ud).getOrInsertComputed(e,()=>this.messageHandler.sendWithPromise(e,t))},WS=function({loaded:e,total:t}){var n,i;(i=(n=this.loadingTask).onProgress)==null||i.call(n,{loaded:e,total:t,percent:t?Ns(Math.round(e/t*100),0,100):NaN})};class Vte{constructor(e){_e(this,"_internalRenderTask",null);_e(this,"onContinue",null);_e(this,"onError",null);this._internalRenderTask=e}get promise(){return this._internalRenderTask.capability.promise}cancel(e=0){this._internalRenderTask.cancel(null,e)}get separateAnnots(){const{separateAnnots:e}=this._internalRenderTask.operatorList;if(!e)return!1;const{annotationCanvasMap:t}=this._internalRenderTask;return e.form||e.canvas&&(t==null?void 0:t.size)>0}get imageCoordinates(){return this._internalRenderTask.imageCoordinates||null}}var Lu,zd;const Lh=class Lh{constructor({callback:e,params:t,objs:n,commonObjs:i,annotationCanvasMap:r,operatorList:o,pageIndex:a,canvasFactory:c,filterFactory:l,useRequestAnimationFrame:u=!1,pdfBug:h=!1,pageColors:d=null,enableHWA:p=!1,operationsFilter:m=null}){D(this,Lu,null);this.callback=e,this.params=t,this.objs=n,this.commonObjs=i,this.annotationCanvasMap=r,this.operatorListIdx=null,this.operatorList=o,this._pageIndex=a,this.canvasFactory=c,this.filterFactory=l,this._pdfBug=h,this.pageColors=d,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this._useRequestAnimationFrame=u===!0&&typeof window<"u",this.cancelled=!1,this.capability=Promise.withResolvers(),this.task=new Vte(this),this._cancelBound=this.cancel.bind(this),this._continueBound=this._continue.bind(this),this._scheduleNextBound=this._scheduleNext.bind(this),this._nextBound=this._next.bind(this),this._canvas=t.canvas,this._canvasContext=t.canvas?null:t.canvasContext,this._enableHWA=p,this._dependencyTracker=t.dependencyTracker,this._imagesTracker=t.imagesTracker,this._operationsFilter=m}get completed(){return this.capability.promise.catch(function(){})}initializeGraphics({transparency:e=!1,optionalContentConfig:t}){var l,u;if(this.cancelled)return;if(this._canvas){if(f(Lh,zd).has(this._canvas))throw new Error("Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.");f(Lh,zd).add(this._canvas)}this._pdfBug&&((l=globalThis.StepperManager)!=null&&l.enabled)&&(this.stepper=globalThis.StepperManager.create(this._pageIndex),this.stepper.init(this.operatorList),this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint());const{viewport:n,transform:i,background:r,dependencyTracker:o,imagesTracker:a}=this.params,c=this._canvasContext||this._canvas.getContext("2d",{alpha:!1,willReadFrequently:!this._enableHWA});this.gfx=new kp(c,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:t},this.annotationCanvasMap,this.pageColors,o,a),this.gfx.beginDrawing({transform:i,viewport:n,transparency:e,background:r}),this.operatorListIdx=0,this.graphicsReady=!0,(u=this.graphicsReadyCallback)==null||u.call(this)}cancel(e=null,t=0){var n,i,r;this.running=!1,this.cancelled=!0,(n=this.gfx)==null||n.endDrawing(),f(this,Lu)&&(window.cancelAnimationFrame(f(this,Lu)),x(this,Lu,null)),f(Lh,zd).delete(this._canvas),e||(e=new uM(`Rendering cancelled, page ${this._pageIndex+1}`,t)),this.callback(e),(r=(i=this.task).onError)==null||r.call(i,e)}operatorListChanged(){var e,t;if(!this.graphicsReady){this.graphicsReadyCallback||(this.graphicsReadyCallback=this._continueBound);return}(e=this.gfx.dependencyTracker)==null||e.growOperationsCount(this.operatorList.fnArray.length),(t=this.stepper)==null||t.updateOperatorList(this.operatorList),!this.running&&this._continue()}_continue(){this.running=!0,!this.cancelled&&(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())}_scheduleNext(){this._useRequestAnimationFrame?x(this,Lu,window.requestAnimationFrame(()=>{x(this,Lu,null),this._nextBound().catch(this._cancelBound)})):Promise.resolve().then(this._nextBound).catch(this._cancelBound)}async _next(){this.cancelled||(this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper,this._operationsFilter),this.operatorListIdx===this.operatorList.argsArray.length&&(this.running=!1,this.operatorList.lastChunk&&(this.gfx.endDrawing(),f(Lh,zd).delete(this._canvas),this.callback())))}};Lu=new WeakMap,zd=new WeakMap,D(Lh,zd,new WeakSet);let oA=Lh;const Gte="6.0.227",qte="241dbabbf";St(3068);var $r,jd,bg,En,fb,_g,Zl,pb,Pu,aa,gb,vs,aA,lA,cA,Eh,ZN,Kc;const ar=class ar{constructor({editor:e=null,uiManager:t=null}){D(this,vs);D(this,$r,null);D(this,jd,null);D(this,bg);D(this,En,null);D(this,fb,!1);D(this,_g,!1);D(this,Zl,null);D(this,pb);D(this,Pu,null);D(this,aa,null);var n,i;e?(x(this,_g,!1),x(this,Zl,e)):x(this,_g,!0),x(this,aa,(e==null?void 0:e._uiManager)||t),x(this,pb,f(this,aa)._eventBus),x(this,bg,((n=e==null?void 0:e.color)==null?void 0:n.toUpperCase())||((i=f(this,aa))==null?void 0:i.highlightColors.values().next().value)||"#FFFF98"),f(ar,gb)||x(ar,gb,Object.freeze({blue:"pdfjs-editor-colorpicker-blue",green:"pdfjs-editor-colorpicker-green",pink:"pdfjs-editor-colorpicker-pink",red:"pdfjs-editor-colorpicker-red",yellow:"pdfjs-editor-colorpicker-yellow"}))}static get _keyboardManager(){return Tt(this,"_keyboardManager",new r_([[["Escape","mac+Escape"],ar.prototype._hideDropdownFromKeyboard],[[" ","mac+ "],ar.prototype._colorSelectFromKeyboard],[["ArrowDown","ArrowRight","mac+ArrowDown","mac+ArrowRight"],ar.prototype._moveToNext],[["ArrowUp","ArrowLeft","mac+ArrowUp","mac+ArrowLeft"],ar.prototype._moveToPrevious],[["Home","mac+Home"],ar.prototype._moveToBeginning],[["End","mac+End"],ar.prototype._moveToEnd]]))}renderButton(){const e=x(this,$r,document.createElement("button"));e.className="colorPicker",e.tabIndex="0",e.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-button"),e.ariaHasPopup="true",f(this,Zl)&&(e.ariaControls=`${f(this,Zl).id}_colorpicker_dropdown`);const t=f(this,aa)._signal;e.addEventListener("click",B(this,vs,Eh).bind(this),{signal:t}),e.addEventListener("keydown",B(this,vs,cA).bind(this),{signal:t});const n=x(this,jd,document.createElement("span"));return n.className="swatch",n.ariaHidden="true",n.style.backgroundColor=f(this,bg),e.append(n),e}renderMainDropdown(){const e=x(this,En,B(this,vs,aA).call(this));return e.ariaOrientation="horizontal",e.ariaLabelledBy="highlightColorPickerLabel",e}_colorSelectFromKeyboard(e){if(e.target===f(this,$r)){B(this,vs,Eh).call(this,e);return}const t=e.target.getAttribute("data-color");t&&B(this,vs,lA).call(this,t,e)}_moveToNext(e){var t,n;if(!f(this,vs,Kc)){B(this,vs,Eh).call(this,e);return}if(e.target===f(this,$r)){(t=f(this,En).firstElementChild)==null||t.focus();return}(n=e.target.nextSibling)==null||n.focus()}_moveToPrevious(e){var t,n;if(e.target===((t=f(this,En))==null?void 0:t.firstElementChild)||e.target===f(this,$r)){f(this,vs,Kc)&&this._hideDropdownFromKeyboard();return}f(this,vs,Kc)||B(this,vs,Eh).call(this,e),(n=e.target.previousSibling)==null||n.focus()}_moveToBeginning(e){var t;if(!f(this,vs,Kc)){B(this,vs,Eh).call(this,e);return}(t=f(this,En).firstElementChild)==null||t.focus()}_moveToEnd(e){var t;if(!f(this,vs,Kc)){B(this,vs,Eh).call(this,e);return}(t=f(this,En).lastElementChild)==null||t.focus()}hideDropdown(){var e,t;(e=f(this,En))==null||e.classList.add("hidden"),f(this,$r).ariaExpanded="false",(t=f(this,Pu))==null||t.abort(),x(this,Pu,null)}_hideDropdownFromKeyboard(){var e;if(!f(this,_g)){if(!f(this,vs,Kc)){(e=f(this,Zl))==null||e.unselect();return}this.hideDropdown(),f(this,$r).focus({preventScroll:!0,focusVisible:f(this,fb)})}}updateColor(e){if(f(this,jd)&&(f(this,jd).style.backgroundColor=e),!f(this,En))return;const t=f(this,aa).highlightColors.values();for(const n of f(this,En).children)n.ariaSelected=t.next().value===e.toUpperCase()}destroy(){var e,t;(e=f(this,$r))==null||e.remove(),x(this,$r,null),x(this,jd,null),(t=f(this,En))==null||t.remove(),x(this,En,null)}};$r=new WeakMap,jd=new WeakMap,bg=new WeakMap,En=new WeakMap,fb=new WeakMap,_g=new WeakMap,Zl=new WeakMap,pb=new WeakMap,Pu=new WeakMap,aa=new WeakMap,gb=new WeakMap,vs=new WeakSet,aA=function(){const e=document.createElement("div"),t=f(this,aa)._signal;e.addEventListener("contextmenu",Ho,{signal:t}),e.className="dropdown",e.role="listbox",e.ariaMultiSelectable="false",e.ariaOrientation="vertical",e.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-dropdown"),f(this,Zl)&&(e.id=`${f(this,Zl).id}_colorpicker_dropdown`);for(const[n,i]of f(this,aa).highlightColors){const r=document.createElement("button");r.tabIndex="0",r.role="option",r.setAttribute("data-color",i),r.title=n,r.setAttribute("data-l10n-id",f(ar,gb)[n]);const o=document.createElement("span");r.append(o),o.className="swatch",o.style.backgroundColor=i,r.ariaSelected=i===f(this,bg),r.addEventListener("click",B(this,vs,lA).bind(this,i),{signal:t}),e.append(r)}return e.addEventListener("keydown",B(this,vs,cA).bind(this),{signal:t}),e},lA=function(e,t){t.stopPropagation(),f(this,pb).dispatch("switchannotationeditorparams",{source:this,type:xt.HIGHLIGHT_COLOR,value:e}),this.updateColor(e)},cA=function(e){ar._keyboardManager.exec(this,e)},Eh=function(e){if(f(this,vs,Kc)){this.hideDropdown();return}if(x(this,fb,e.detail===0),f(this,Pu)||(x(this,Pu,new AbortController),window.addEventListener("pointerdown",B(this,vs,ZN).bind(this),{signal:f(this,aa).combinedSignal(f(this,Pu))})),f(this,$r).ariaExpanded="true",f(this,En)){f(this,En).classList.remove("hidden");return}const t=x(this,En,B(this,vs,aA).call(this));f(this,$r).append(t)},ZN=function(e){var t;(t=f(this,En))!=null&&t.contains(e.target)||this.hideDropdown()},Kc=function(){return f(this,En)&&!f(this,En).classList.contains("hidden")},D(ar,gb,null);let d0=ar;var Hr,Sg,Vd,ec,mb;const Ph=class Ph{constructor(e){D(this,Hr,null);D(this,Sg,!1);D(this,Vd,null);D(this,ec,null);x(this,Vd,e),x(this,ec,e._uiManager),f(Ph,mb)||x(Ph,mb,Object.freeze({freetext:"pdfjs-editor-color-picker-free-text-input",ink:"pdfjs-editor-color-picker-ink-input"}))}renderButton(){if(f(this,Hr))return f(this,Hr);const{editorType:e,colorType:t,colorAndOpacityType:n,opacityType:i,color:r,opacity:o}=f(this,Vd),a=x(this,Sg,Ts.isAlphaColorInputSupported&&i!==void 0),c=x(this,Hr,document.createElement("input"));if(c.type="color",a){c.setAttribute("alpha","");const l=Be.hexNums[Math.round((o??1)*255)];c.value=(r||"#000000")+l}else c.value=r||"#000000";return c.className="basicColorPicker",c.tabIndex=0,c.setAttribute("data-l10n-id",f(Ph,mb)[e]),c.addEventListener("input",()=>{if(a){const l=n_(c.value);if(!l)return;const[u,h,d,p]=l,m=Be.makeHexColor(u,h,d);n!==void 0?f(this,ec).updateParams(n,{color:m,opacity:p}):(f(this,ec).updateParams(t,m),f(this,ec).updateParams(i,p))}else f(this,ec).updateParams(t,c.value)},{signal:f(this,ec)._signal}),c}update(e){if(f(this,Hr))if(f(this,Sg)){const t=Be.hexNums[Math.round(f(this,Vd).opacity*255)];f(this,Hr).value=e+t}else f(this,Hr).value=e}updateOpacity(e){if(!f(this,Hr)||!f(this,Sg))return;const t=Be.hexNums[Math.round(e*255)];f(this,Hr).value=f(this,Vd).color+t}destroy(){var e;(e=f(this,Hr))==null||e.remove(),x(this,Hr,null)}hideDropdown(){}};Hr=new WeakMap,Sg=new WeakMap,Vd=new WeakMap,ec=new WeakMap,mb=new WeakMap,D(Ph,mb,null);let f0=Ph;St(531);function FR(s){return Math.floor(Ns(s,0,1)*255).toString(16).padStart(2,"0")}function Tm(s){return Ns(s,0,1)*255}class $R{static CMYK_G([e,t,n,i]){return["G",1-Math.min(1,.3*e+.59*n+.11*t+i)]}static G_CMYK([e]){return["CMYK",0,0,0,1-e]}static G_RGB([e]){return["RGB",e,e,e]}static G_rgb([e]){return e=Tm(e),[e,e,e]}static G_HTML([e]){const t=FR(e);return`#${t}${t}${t}`}static RGB_G([e,t,n]){return["G",.3*e+.59*t+.11*n]}static RGB_rgb(e){return e.map(Tm)}static RGB_HTML(e){return`#${e.map(FR).join("")}`}static T_HTML(){return"#00000000"}static T_rgb(){return[null]}static CMYK_RGB([e,t,n,i]){return["RGB",1-Math.min(1,e+i),1-Math.min(1,n+i),1-Math.min(1,t+i)]}static CMYK_rgb([e,t,n,i]){return[Tm(1-Math.min(1,e+i)),Tm(1-Math.min(1,n+i)),Tm(1-Math.min(1,t+i))]}static CMYK_HTML(e){const t=this.CMYK_RGB(e).slice(1);return this.RGB_HTML(t)}static RGB_CMYK([e,t,n]){const i=1-e,r=1-t,o=1-n,a=Math.min(i,r,o);return["CMYK",i,r,o,a]}}class Kte{create(e,t,n=!1){if(e<=0||t<=0)throw new Error("Invalid SVG dimensions");const i=this._createSVG("svg:svg");return i.setAttribute("version","1.1"),n||(i.setAttribute("width",`${e}px`),i.setAttribute("height",`${t}px`)),i.setAttribute("preserveAspectRatio","none"),i.setAttribute("viewBox",`0 0 ${e} ${t}`),i}createElement(e){if(typeof e!="string")throw new Error("Invalid SVG element type");return this._createSVG(e)}_createSVG(e){es("Abstract method `_createSVG` called.")}}class p0 extends Kte{_createSVG(e){return document.createElementNS(Pr,e)}}const Qte=9,Pf=new WeakSet,Xte=new Date().getTimezoneOffset()*60*1e3;class e1{static create(e){switch(e.data.annotationType){case mn.LINK:return new pM(e);case mn.TEXT:return new Jte(e);case mn.WIDGET:switch(e.data.fieldType){case"Tx":return new Zte(e);case"Btn":return e.data.radioButton?new sB(e):e.data.checkBox?new tse(e):new sse(e);case"Ch":return new nse(e);case"Sig":return new ese(e)}return new Bf(e);case mn.POPUP:return new hA(e);case mn.FREETEXT:return new aB(e);case mn.LINE:return new rse(e);case mn.SQUARE:return new ose(e);case mn.CIRCLE:return new ase(e);case mn.POLYLINE:return new lB(e);case mn.CARET:return new cse(e);case mn.INK:return new gM(e);case mn.POLYGON:return new lse(e);case mn.HIGHLIGHT:return new cB(e);case mn.UNDERLINE:return new use(e);case mn.SQUIGGLY:return new hse(e);case mn.STRIKEOUT:return new dse(e);case mn.STAMP:return new uB(e);case mn.FILEATTACHMENT:return new fse(e);default:return new Ks(e)}}}var Gd,wg,Co,vb,uA;const AM=class AM{constructor(e,{isRenderable:t=!1,ignoreBorder:n=!1,createQuadrilaterals:i=!1}={}){D(this,vb);D(this,Gd,null);D(this,wg,!1);D(this,Co,null);this.isRenderable=t,this.data=e.data,this.layer=e.layer,this.linkService=e.linkService,this.downloadManager=e.downloadManager,this.imageResourcesPath=e.imageResourcesPath,this.renderForms=e.renderForms,this.svgFactory=e.svgFactory,this.annotationStorage=e.annotationStorage,this.enableComment=e.enableComment,this.enableScripting=e.enableScripting,this.hasJSActions=e.hasJSActions,this._fieldObjects=e.fieldObjects,this.parent=e.parent,this.hasOwnCommentButton=!1,t&&(this.contentElement=this.container=this._createContainer(n)),i&&this._createQuadrilaterals()}static _hasPopupData({contentsObj:e,richText:t}){return!!(e!=null&&e.str||t!=null&&t.str)}get _isEditable(){return this.data.isEditable}get hasPopupData(){return AM._hasPopupData(this.data)||this.enableComment&&!!this.commentText}get commentData(){var n;const{data:e}=this,t=(n=this.annotationStorage)==null?void 0:n.getEditor(e.id);return t?t.getData():e}get hasCommentButton(){return this.enableComment&&this.hasPopupElement}get commentButtonPosition(){var a;const e=(a=this.annotationStorage)==null?void 0:a.getEditor(this.data.id);if(e)return e.commentButtonPositionInPage;const{quadPoints:t,inkLists:n,rect:i}=this.data;let r=-1/0,o=-1/0;if((t==null?void 0:t.length)>=8){for(let c=0;c<t.length;c+=8)t[c+1]>o?(o=t[c+1],r=t[c+2]):t[c+1]===o&&(r=Math.max(r,t[c+2]));return[r,o]}if((n==null?void 0:n.length)>=1){for(const c of n)for(let l=0,u=c.length;l<u;l+=2)c[l+1]>o?(o=c[l+1],r=c[l]):c[l+1]===o&&(r=Math.max(r,c[l]));if(r!==1/0)return[r,o]}return i?[i[2],i[3]]:null}_normalizePoint(e){const{page:{view:t},viewport:{rawDims:{pageWidth:n,pageHeight:i,pageX:r,pageY:o}}}=this.parent;return e[1]=t[3]-e[1]+t[1],e[0]=100*(e[0]-r)/n,e[1]=100*(e[1]-o)/i,e}get commentText(){var t,n,i;const{data:e}=this;return((n=(t=this.annotationStorage.getRawValue(`${oy}${e.id}`))==null?void 0:t.popup)==null?void 0:n.contents)||((i=e.contentsObj)==null?void 0:i.str)||""}set commentText(e){const{data:t}=this,n={deleted:!e,contents:e||""};this.annotationStorage.updateEditor(t.id,{popup:n})||this.annotationStorage.setValue(`${oy}${t.id}`,{id:t.id,annotationType:t.annotationType,page:this.parent.page,popup:n,popupRef:t.popupRef,modificationDate:new Date}),e||this.removePopup()}removePopup(){var e,t;(t=((e=f(this,Co))==null?void 0:e.popup)||this.popup)==null||t.remove(),x(this,Co,this.popup=null)}updateEdited(e){var r;if(!this.container)return;e.rect&&(f(this,Gd)||x(this,Gd,{rect:this.data.rect.slice(0)}));const{rect:t,popup:n}=e;t&&B(this,vb,uA).call(this,t);let i=((r=f(this,Co))==null?void 0:r.popup)||this.popup;!i&&(n!=null&&n.text)&&(this._createPopup(n),i=f(this,Co).popup),i&&(i.updateEdited(e),n!=null&&n.deleted&&(i.remove(),x(this,Co,null),this.popup=null))}resetEdited(){var e;f(this,Gd)&&(B(this,vb,uA).call(this,f(this,Gd).rect),(e=f(this,Co))==null||e.popup.resetEdited(),x(this,Gd,null))}_createContainer(e){const{data:t,parent:{page:n,viewport:i}}=this,r=document.createElement("section");r.setAttribute("data-annotation-id",t.id),!(this instanceof Bf)&&!(this instanceof pM)&&(r.tabIndex=0);const{style:o}=r;if(o.zIndex=this.parent.zIndex,this.parent.zIndex+=2,t.alternativeText&&(r.title=t.alternativeText),t.noRotate&&r.classList.add("norotate"),!t.rect||this instanceof hA){const{rotation:v}=t;return!t.hasOwnCanvas&&v!==0&&this.setRotation(v,r),r}const{width:a,height:c}=this;if(!e&&t.borderStyle.width>0){o.borderWidth=`${t.borderStyle.width}px`;const v=t.borderStyle.horizontalCornerRadius,g=t.borderStyle.verticalCornerRadius;if(v>0||g>0){const b=`calc(${v}px * var(--total-scale-factor)) / calc(${g}px * var(--total-scale-factor))`;o.borderRadius=b}else if(this instanceof sB){const b=`calc(${a}px * var(--total-scale-factor)) / calc(${c}px * var(--total-scale-factor))`;o.borderRadius=b}switch(t.borderStyle.style){case hp.SOLID:o.borderStyle="solid";break;case hp.DASHED:o.borderStyle="dashed";break;case hp.BEVELED:kt("Unimplemented border style: beveled");break;case hp.INSET:kt("Unimplemented border style: inset");break;case hp.UNDERLINE:o.borderBottomStyle="solid";break}const y=t.borderColor||null;y?(x(this,wg,!0),o.borderColor=Be.makeHexColor(...y)):o.borderWidth=0}const l=Be.normalizeRect([t.rect[0],n.view[3]-t.rect[1]+n.view[1],t.rect[2],n.view[3]-t.rect[3]+n.view[1]]),{pageWidth:u,pageHeight:h,pageX:d,pageY:p}=i.rawDims;o.left=`${100*(l[0]-d)/u}%`,o.top=`${100*(l[1]-p)/h}%`;const{rotation:m}=t;return t.hasOwnCanvas||m===0?(o.width=`${100*a/u}%`,o.height=`${100*c/h}%`):this.setRotation(m,r),r}setRotation(e,t=this.container){if(!this.data.rect)return;const{pageWidth:n,pageHeight:i}=this.parent.viewport.rawDims;let{width:r,height:o}=this;e%180!==0&&([r,o]=[o,r]),t.style.width=`${100*r/n}%`,t.style.height=`${100*o/i}%`,t.setAttribute("data-main-rotation",(360-e)%360)}get _commonActions(){const e=(t,n,i)=>{const r=i.detail[t],o=r[0],a=r.slice(1);i.target.style[n]=$R[`${o}_HTML`](a),this.annotationStorage.setValue(this.data.id,{[n]:$R[`${o}_rgb`](a)})};return Tt(this,"_commonActions",{display:t=>{const{display:n}=t.detail,i=n%2===1;this.container.style.visibility=i?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noView:i,noPrint:n===1||n===2})},print:t=>{this.annotationStorage.setValue(this.data.id,{noPrint:!t.detail.print})},hidden:t=>{const{hidden:n}=t.detail;this.container.style.visibility=n?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noPrint:n,noView:n})},focus:t=>{setTimeout(()=>t.target.focus({preventScroll:!1}),0)},userName:t=>{t.target.title=t.detail.userName},readonly:t=>{t.target.disabled=t.detail.readonly},required:t=>{this._setRequired(t.target,t.detail.required)},bgColor:t=>{e("bgColor","backgroundColor",t)},fillColor:t=>{e("fillColor","backgroundColor",t)},fgColor:t=>{e("fgColor","color",t)},textColor:t=>{e("textColor","color",t)},borderColor:t=>{e("borderColor","borderColor",t)},strokeColor:t=>{e("strokeColor","borderColor",t)},rotation:t=>{const n=t.detail.rotation;this.setRotation(n),this.annotationStorage.setValue(this.data.id,{rotation:n})}})}_dispatchEventFromSandbox(e,t){const n=this._commonActions;for(const i of Object.keys(t.detail)){const r=e[i]||n[i];r==null||r(t)}}_setDefaultPropertiesFromJS(e){if(!this.enableScripting)return;const t=this.annotationStorage.getRawValue(this.data.id);if(!t)return;const n=this._commonActions;for(const[i,r]of Object.entries(t)){const o=n[i];if(o){const a={detail:{[i]:r},target:e};o(a),delete t[i]}}}_createQuadrilaterals(){if(!this.container)return;const{quadPoints:e}=this.data;if(!e)return;const[t,n,i,r]=this.data.rect.map(v=>Math.fround(v));if(e.length===8){const[v,g,y,b]=e.subarray(2,6);if(i===v&&r===g&&t===y&&n===b)return}const{style:o}=this.container;let a;if(f(this,wg)){const{borderColor:v,borderWidth:g}=o;o.borderWidth=0,a=["url('data:image/svg+xml;utf8,",`<svg xmlns="${Pr}" preserveAspectRatio="none" viewBox="0 0 1 1">`,`<g fill="transparent" stroke="${v}" stroke-width="${g}">`],this.container.classList.add("hasBorder")}const c=i-t,l=r-n,{svgFactory:u}=this,h=u.createElement("svg");h.classList.add("quadrilateralsContainer"),h.setAttribute("width",0),h.setAttribute("height",0),h.role="none";const d=u.createElement("defs");h.append(d);const p=u.createElement("clipPath"),m=`clippath_${this.data.id}`;p.setAttribute("id",m),p.setAttribute("clipPathUnits","objectBoundingBox"),d.append(p);for(let v=2,g=e.length;v<g;v+=8){const y=e[v],b=e[v+1],_=e[v+2],w=e[v+3],S=u.createElement("rect"),C=(_-t)/c,T=(r-b)/l,k=(y-_)/c,A=(b-w)/l;S.setAttribute("x",C),S.setAttribute("y",T),S.setAttribute("width",k),S.setAttribute("height",A),p.append(S),a==null||a.push(`<rect vector-effect="non-scaling-stroke" x="${C}" y="${T}" width="${k}" height="${A}"/>`)}f(this,wg)&&(a.push("</g></svg>')"),o.backgroundImage=a.join("")),this.container.append(h),this.container.style.clipPath=`url(#${m})`}_createPopup(e=null){const{data:t}=this;let n,i;e?(n={str:e.text},i=e.date):(n=t.contentsObj,i=t.modificationDate),x(this,Co,new hA({data:{color:t.color,titleObj:t.titleObj,modificationDate:i,contentsObj:n,richText:t.richText,parentRect:t.rect,borderStyle:0,id:`popup_${t.id}`,rotation:t.rotation,noRotate:!0},linkService:this.linkService,parent:this.parent,elements:[this]}))}get hasPopupElement(){return!!(f(this,Co)||this.popup||this.data.popupRef)}get extraPopupElement(){return f(this,Co)}render(){es("Abstract method `AnnotationElement.render` called")}_getElementsByName(e,t=null){const n=[];if(this._fieldObjects){const i=this._fieldObjects[e];if(i)for(const{page:r,id:o,exportValues:a}of i){if(r===-1||o===t)continue;const c=typeof a=="string"?a:null,l=document.querySelector(`[data-element-id="${o}"]`);if(l&&!Pf.has(l)){kt(`_getElementsByName - element not allowed: ${o}`);continue}n.push({id:o,exportValue:c,domElement:l})}return n}for(const i of document.getElementsByName(e)){const{exportValue:r}=i,o=i.getAttribute("data-element-id");o!==t&&Pf.has(i)&&n.push({id:o,exportValue:r,domElement:i})}return n}show(){var e;this.container&&(this.container.hidden=!1),(e=this.popup)==null||e.maybeShow()}hide(){var e;this.container&&(this.container.hidden=!0),(e=this.popup)==null||e.forceHide()}getElementsToTriggerPopup(){return this.container}addHighlightArea(){const e=this.getElementsToTriggerPopup();if(Array.isArray(e))for(const t of e)t.classList.add("highlightArea");else e.classList.add("highlightArea")}_editOnDoubleClick(){if(!this._isEditable)return;const{annotationEditorType:e,data:{id:t}}=this;this.container.addEventListener("dblclick",()=>{var n;(n=this.linkService.eventBus)==null||n.dispatch("switchannotationeditormode",{source:this,mode:e,editId:t,mustEnterInEditMode:!0})})}updateOC(e){if(!this.data.oc||!e)return;e.isVisible(this.data.oc)?this.show():this.hide()}get width(){return this.data.rect[2]-this.data.rect[0]}get height(){return this.data.rect[3]-this.data.rect[1]}};Gd=new WeakMap,wg=new WeakMap,Co=new WeakMap,vb=new WeakSet,uA=function(e){const{container:{style:t},data:{rect:n,rotation:i},parent:{viewport:{rawDims:{pageWidth:r,pageHeight:o,pageX:a,pageY:c}}}}=this;n==null||n.splice(0,4,...e),t.left=`${100*(e[0]-a)/r}%`,t.top=`${100*(o-e[3]+c)/o}%`,i===0?(t.width=`${100*(e[2]-e[0])/r}%`,t.height=`${100*(e[3]-e[1])/o}%`):this.setRotation(i)};let Ks=AM;class Yte extends Ks{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0}),this.editor=e.editor}render(){return this.container.className="editorAnnotation",this.container}createOrUpdatePopup(){const{editor:e}=this;e.hasComment&&this._createPopup(e.comment)}get hasCommentButton(){return this.enableComment&&this.editor.hasComment}get commentButtonPosition(){return this.editor.commentButtonPositionInPage}get commentText(){return this.editor.comment.text}set commentText(e){this.editor.comment=e,e||this.removePopup()}get commentData(){return this.editor.getData()}remove(){this.parent.removeAnnotation(this.data.id),this.container.remove(),this.container=null,this.removePopup()}}var to,Mh,eB,tB;class pM extends Ks{constructor(t,n=null){super(t,{isRenderable:!0,ignoreBorder:!!(n!=null&&n.ignoreBorder),createQuadrilaterals:!0});D(this,to);this.isTooltipOnly=t.data.isTooltipOnly}render(){const{data:t,linkService:n}=this,i=document.createElement("a");i.setAttribute("data-element-id",t.id);let r=!1;return t.url?(n.addLinkAttributes(i,t.url,t.newWindow),r=!0):t.action?(this._bindNamedAction(i,t.action,t.overlaidText),r=!0):t.attachment?(B(this,to,eB).call(this,i,t.attachment,t.overlaidText,t.attachmentDest),r=!0):t.setOCGState?(B(this,to,tB).call(this,i,t.setOCGState,t.overlaidText),r=!0):t.dest?(this._bindLink(i,t.dest,t.overlaidText),r=!0):(t.actions&&(t.actions.Action||t.actions["Mouse Up"]||t.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions&&(this._bindJSAction(i,t),r=!0),t.resetForm?(this._bindResetFormAction(i,t.resetForm),r=!0):this.isTooltipOnly&&!r&&(this._bindLink(i,""),r=!0)),this.container.classList.add("linkAnnotation"),r&&(this.contentElement=i,this.container.append(i)),this.container}_bindLink(t,n,i=""){t.href=this.linkService.getDestinationHash(n),t.onclick=()=>(n&&this.linkService.goToDestination(n),!1),(n||n==="")&&B(this,to,Mh).call(this),i&&(t.title=i)}_bindNamedAction(t,n,i=""){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeNamedAction(n),!1),i&&(t.title=i),B(this,to,Mh).call(this)}_bindJSAction(t,n){t.href=this.linkService.getAnchorUrl("");const i=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(const r of Object.keys(n.actions)){const o=i.get(r);o&&(t[o]=()=>{var a;return(a=this.linkService.eventBus)==null||a.dispatch("dispatcheventinsandbox",{source:this,detail:{id:n.id,name:r}}),!1})}n.overlaidText&&(t.title=n.overlaidText),t.onclick||(t.onclick=()=>!1),B(this,to,Mh).call(this)}_bindResetFormAction(t,n){const i=t.onclick;if(i||(t.href=this.linkService.getAnchorUrl("")),B(this,to,Mh).call(this),!this._fieldObjects){kt('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),i||(t.onclick=()=>!1);return}t.onclick=()=>{var h;i==null||i();const{fields:r,refs:o,include:a}=n,c=[];if(r.length!==0||o.length!==0){const d=new Set(o);for(const p of r){const m=this._fieldObjects[p]||[];for(const{id:v}of m)d.add(v)}for(const p of Object.values(this._fieldObjects))for(const m of p)d.has(m.id)===a&&c.push(m)}else for(const d of Object.values(this._fieldObjects))c.push(...d);const l=this.annotationStorage,u=[];for(const d of c){const{id:p}=d;switch(u.push(p),d.type){case"text":{const v=d.defaultValue||"";l.setValue(p,{value:v});break}case"checkbox":case"radiobutton":{const v=d.defaultValue===d.exportValues;l.setValue(p,{value:v});break}case"combobox":case"listbox":{const v=d.defaultValue||"";l.setValue(p,{value:v});break}default:continue}const m=document.querySelector(`[data-element-id="${p}"]`);if(m){if(!Pf.has(m)){kt(`_bindResetFormAction - element not allowed: ${p}`);continue}}else continue;m.dispatchEvent(new Event("resetform"))}return this.enableScripting&&((h=this.linkService.eventBus)==null||h.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:u,name:"ResetForm"}})),!1}}}to=new WeakSet,Mh=function(){this.container.setAttribute("data-internal-link","")},eB=function(t,n,i="",r=null){t.href=this.linkService.getAnchorUrl(""),n.description?t.title=n.description:i&&(t.title=i),t.onclick=()=>{var o;return(o=this.downloadManager)==null||o.openOrDownloadData(n.content,n.filename,r),!1},B(this,to,Mh).call(this)},tB=function(t,n,i=""){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeSetOCGState(n),!1),i&&(t.title=i),B(this,to,Mh).call(this)};class Jte extends Ks{constructor(e){super(e,{isRenderable:!0})}render(){this.container.classList.add("textAnnotation");const e=document.createElement("img");return e.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg",e.setAttribute("data-l10n-id","pdfjs-text-annotation-type"),e.setAttribute("data-l10n-args",JSON.stringify({type:this.data.name})),!this.data.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container.append(e),this.container}}class Bf extends Ks{render(){return this.container}showElementAndHideCanvas(e){var t;this.data.hasOwnCanvas&&(((t=e.previousSibling)==null?void 0:t.nodeName)==="CANVAS"&&(e.previousSibling.hidden=!0),e.hidden=!1)}_getKeyModifier(e){return Ts.platform.isMac?e.metaKey:e.ctrlKey}_setEventListener(e,t,n,i,r){n.includes("mouse")?e.addEventListener(n,o=>{var a;(a=this.linkService.eventBus)==null||a.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:i,value:r(o),shift:o.shiftKey,modifier:this._getKeyModifier(o)}})}):e.addEventListener(n,o=>{var a;if(n==="blur"){if(!t.focused||!o.relatedTarget)return;t.focused=!1}else if(n==="focus"){if(t.focused)return;t.focused=!0}r&&((a=this.linkService.eventBus)==null||a.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:i,value:r(o)}}))})}_setEventListeners(e,t,n,i){var r,o,a;for(const[c,l]of n)(l==="Action"||(r=this.data.actions)!=null&&r[l])&&((l==="Focus"||l==="Blur")&&(t||(t={focused:!1})),this._setEventListener(e,t,c,l,i),l==="Focus"&&!((o=this.data.actions)!=null&&o.Blur)?this._setEventListener(e,t,"blur","Blur",null):l==="Blur"&&!((a=this.data.actions)!=null&&a.Focus)&&this._setEventListener(e,t,"focus","Focus",null))}_setBackgroundColor(e){const t=this.data.backgroundColor||null;e.style.backgroundColor=t===null?"transparent":Be.makeHexColor(...t)}_setTextStyle(e){const t=["left","center","right"],{fontColor:n}=this.data.defaultAppearanceData,i=this.data.defaultAppearanceData.fontSize||Qte,r=e.style;let o;const a=2,c=l=>Math.round(10*l)/10;if(this.data.multiLine){const l=Math.abs(this.data.rect[3]-this.data.rect[1]-a),u=Math.round(l/(KC*i))||1,h=l/u;o=Math.min(i,c(h/KC))}else{const l=Math.abs(this.data.rect[3]-this.data.rect[1]-a);o=Math.min(i,c(l/KC))}r.fontSize=`calc(${o}px * var(--total-scale-factor))`,r.color=Be.makeHexColor(...n),this.data.textAlignment!==null&&(r.textAlign=t[this.data.textAlignment])}_setRequired(e,t){t?e.setAttribute("required",!0):e.removeAttribute("required"),e.setAttribute("aria-required",t)}}class Zte extends Bf{constructor(e){const t=e.renderForms||e.data.hasOwnCanvas||!e.data.hasAppearance&&!!e.data.fieldValue;super(e,{isRenderable:t})}setPropertyOnSiblings(e,t,n,i){const r=this.annotationStorage;for(const o of this._getElementsByName(e.name,e.id))o.domElement&&(o.domElement[t]=n),r.setValue(o.id,{[i]:n})}render(){var i,r;const e=this.annotationStorage,t=this.data.id;this.container.classList.add("textWidgetAnnotation");let n=null;if(this.renderForms){const o=e.getValue(t,{value:this.data.fieldValue});let a=o.value||"";const c=e.getValue(t,{charLimit:this.data.maxLen}).charLimit;c&&a.length>c&&(a=a.slice(0,c));let l=o.formattedValue||((i=this.data.textContent)==null?void 0:i.join(`
`))||null;l&&this.data.comb&&(l=l.replaceAll(/\s+/g,""));const u={userValue:a,formattedValue:l,lastCommittedValue:null,commitKey:1,focused:!1};this.data.multiLine?(n=document.createElement("textarea"),n.textContent=l??a,this.data.doNotScroll&&(n.style.overflowY="hidden")):(n=document.createElement("input"),n.type=this.data.password?"password":"text",n.setAttribute("value",l??a),this.data.doNotScroll&&(n.style.overflowX="hidden")),this.data.hasOwnCanvas&&(n.hidden=!0),Pf.add(n),this.contentElement=n,n.setAttribute("data-element-id",t),n.disabled=this.data.readOnly,n.name=this.data.fieldName,n.tabIndex=0;const{datetimeFormat:h,datetimeType:d,timeStep:p}=this.data,m=!!d&&this.enableScripting;h&&(n.title=h),this._setRequired(n,this.data.required),c&&(n.maxLength=c),n.addEventListener("input",g=>{e.setValue(t,{value:g.target.value}),this.setPropertyOnSiblings(n,"value",g.target.value,"value"),u.formattedValue=null}),n.addEventListener("resetform",g=>{const y=this.data.defaultFieldValue??"";n.value=u.userValue=y,u.formattedValue=null});let v=g=>{const{formattedValue:y}=u;y!=null&&(g.target.value=y),g.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){n.addEventListener("focus",y=>{var _;if(u.focused)return;const{target:b}=y;if(m&&(b.type=d,p&&(b.step=p)),u.userValue){const w=u.userValue;if(m)if(d==="time"){const S=new Date(w),C=[S.getHours(),S.getMinutes(),S.getSeconds()];b.value=C.map(T=>T.toString().padStart(2,"0")).join(":")}else b.value=new Date(w-Xte).toISOString().split(d==="date"?"T":".",1)[0];else b.value=w}u.lastCommittedValue=b.value,u.commitKey=1,(_=this.data.actions)!=null&&_.Focus||(u.focused=!0)}),n.addEventListener("updatefromsandbox",y=>{this.showElementAndHideCanvas(y.target);const b={value(_){u.userValue=_.detail.value??"",m||e.setValue(t,{value:u.userValue.toString()}),_.target.value=u.userValue},formattedValue(_){const{formattedValue:w}=_.detail;u.formattedValue=w,w!=null&&_.target!==document.activeElement&&(_.target.value=w);const S={formattedValue:w};m&&(S.value=w),e.setValue(t,S)},selRange(_){_.target.setSelectionRange(..._.detail.selRange)},charLimit:_=>{var T;const{charLimit:w}=_.detail,{target:S}=_;if(w===0){S.removeAttribute("maxLength");return}S.setAttribute("maxLength",w);let C=u.userValue;!C||C.length<=w||(C=C.slice(0,w),S.value=u.userValue=C,e.setValue(t,{value:C}),(T=this.linkService.eventBus)==null||T.dispatch("dispatcheventinsandbox",{source:this,detail:{id:t,name:"Keystroke",value:C,willCommit:!0,commitKey:1,selStart:S.selectionStart,selEnd:S.selectionEnd}}))}};this._dispatchEventFromSandbox(b,y)}),n.addEventListener("keydown",y=>{var w;u.commitKey=1;let b=-1;if(y.key==="Escape"?b=0:y.key==="Enter"&&!this.data.multiLine?b=2:y.key==="Tab"&&(u.commitKey=3),b===-1)return;const{value:_}=y.target;u.lastCommittedValue!==_&&(u.lastCommittedValue=_,u.userValue=_,(w=this.linkService.eventBus)==null||w.dispatch("dispatcheventinsandbox",{source:this,detail:{id:t,name:"Keystroke",value:_,willCommit:!0,commitKey:b,selStart:y.target.selectionStart,selEnd:y.target.selectionEnd}}))});const g=v;v=null,n.addEventListener("blur",y=>{var w,S;if(!u.focused||!y.relatedTarget)return;(w=this.data.actions)!=null&&w.Blur||(u.focused=!1);const{target:b}=y;let{value:_}=b;if(m){if(_&&d==="time"){const C=_.split(":").map(T=>parseInt(T,10));_=new Date(2e3,0,1,C[0],C[1],C[2]||0).valueOf(),b.step=""}else _.includes("T")||(_=`${_}T00:00`),_=new Date(_).valueOf();b.type="text"}u.userValue=_,u.lastCommittedValue!==_&&((S=this.linkService.eventBus)==null||S.dispatch("dispatcheventinsandbox",{source:this,detail:{id:t,name:"Keystroke",value:_,willCommit:!0,commitKey:u.commitKey,selStart:y.target.selectionStart,selEnd:y.target.selectionEnd}})),g(y)}),(r=this.data.actions)!=null&&r.Keystroke&&n.addEventListener("beforeinput",y=>{var A;u.lastCommittedValue=null;const{data:b,target:_}=y,{value:w,selectionStart:S,selectionEnd:C}=_;let T=S,k=C;switch(y.inputType){case"deleteWordBackward":{const M=w.substring(0,S).match(/\w*\W*$/);M&&(T-=M[0].length);break}case"deleteWordForward":{const M=w.substring(S).match(/^\W*\w*/);M&&(k+=M[0].length);break}case"deleteContentBackward":S===C&&(T-=1);break;case"deleteContentForward":S===C&&(k+=1);break}y.preventDefault(),(A=this.linkService.eventBus)==null||A.dispatch("dispatcheventinsandbox",{source:this,detail:{id:t,name:"Keystroke",value:w,change:b||"",willCommit:!1,selStart:T,selEnd:k}})}),this._setEventListeners(n,u,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],y=>y.target.value)}if(v&&n.addEventListener("blur",v),this.data.comb){const y=(this.data.rect[2]-this.data.rect[0])/c;n.classList.add("comb"),n.style.letterSpacing=`calc(${y}px * var(--total-scale-factor) - 1ch)`}}else n=document.createElement("div"),n.textContent=this.data.fieldValue,n.style.verticalAlign="middle",n.style.display="table-cell",this.data.hasOwnCanvas&&(n.hidden=!0);return this._setTextStyle(n),this._setBackgroundColor(n),this._setDefaultPropertiesFromJS(n),this.container.append(n),this.container}}class ese extends Bf{constructor(e){super(e,{isRenderable:!!e.data.hasOwnCanvas})}}class tse extends Bf{constructor(e){super(e,{isRenderable:e.renderForms})}render(){const e=this.annotationStorage,t=this.data,n=t.id;let i=e.getValue(n,{value:t.exportValue===t.fieldValue}).value;typeof i=="string"&&(i=i!=="Off",e.setValue(n,{value:i})),this.container.classList.add("buttonWidgetAnnotation","checkBox");const r=document.createElement("input");return Pf.add(r),r.setAttribute("data-element-id",n),r.disabled=t.readOnly,this._setRequired(r,this.data.required),r.type="checkbox",r.name=t.fieldName,i&&r.setAttribute("checked",!0),r.setAttribute("exportValue",t.exportValue),r.tabIndex=0,r.addEventListener("change",o=>{const{name:a,checked:c}=o.target;for(const l of this._getElementsByName(a,n)){const u=c&&l.exportValue===t.exportValue;l.domElement&&(l.domElement.checked=u),e.setValue(l.id,{value:u})}e.setValue(n,{value:c})}),r.addEventListener("resetform",o=>{const a=t.defaultFieldValue||"Off";o.target.checked=a===t.exportValue}),this.enableScripting&&this.hasJSActions&&(r.addEventListener("updatefromsandbox",o=>{const a={value(c){c.target.checked=c.detail.value!=="Off",e.setValue(n,{value:c.target.checked})}};this._dispatchEventFromSandbox(a,o)}),this._setEventListeners(r,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],o=>o.target.checked)),this._setBackgroundColor(r),this._setDefaultPropertiesFromJS(r),this.container.append(r),this.container}}class sB extends Bf{constructor(e){super(e,{isRenderable:e.renderForms})}render(){this.container.classList.add("buttonWidgetAnnotation","radioButton");const e=this.annotationStorage,t=this.data,n=t.id;let i=e.getValue(n,{value:t.fieldValue===t.buttonValue}).value;if(typeof i=="string"&&(i=i!==t.buttonValue,e.setValue(n,{value:i})),i)for(const o of this._getElementsByName(t.fieldName,n))e.setValue(o.id,{value:!1});const r=document.createElement("input");if(Pf.add(r),r.setAttribute("data-element-id",n),r.disabled=t.readOnly,this._setRequired(r,this.data.required),r.type="radio",r.name=t.fieldName,i&&r.setAttribute("checked",!0),r.tabIndex=0,r.addEventListener("change",o=>{const{name:a,checked:c}=o.target;for(const l of this._getElementsByName(a,n))e.setValue(l.id,{value:!1});e.setValue(n,{value:c})}),r.addEventListener("resetform",o=>{const a=t.defaultFieldValue;o.target.checked=a!=null&&a===t.buttonValue}),this.enableScripting&&this.hasJSActions){const o=t.buttonValue;r.addEventListener("updatefromsandbox",a=>{const c={value:l=>{const u=o===l.detail.value;for(const h of this._getElementsByName(l.target.name)){const d=u&&h.id===n;h.domElement&&(h.domElement.checked=d),e.setValue(h.id,{value:d})}}};this._dispatchEventFromSandbox(c,a)}),this._setEventListeners(r,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],a=>a.target.checked)}return this._setBackgroundColor(r),this._setDefaultPropertiesFromJS(r),this.container.append(r),this.container}}class sse extends pM{constructor(e){super(e,{ignoreBorder:e.data.hasAppearance})}render(){const e=super.render();e.classList.add("buttonWidgetAnnotation","pushButton");const t=e.lastChild;return this.enableScripting&&this.hasJSActions&&t&&(this._setDefaultPropertiesFromJS(t),t.addEventListener("updatefromsandbox",n=>{this._dispatchEventFromSandbox({},n)})),e}}class nse extends Bf{constructor(e){super(e,{isRenderable:e.renderForms})}render(){this.container.classList.add("choiceWidgetAnnotation");const e=this.annotationStorage,t=this.data.id,n=e.getValue(t,{value:this.data.fieldValue}),i=document.createElement("select");Pf.add(i),i.setAttribute("data-element-id",t),i.disabled=this.data.readOnly,this._setRequired(i,this.data.required),i.name=this.data.fieldName,i.tabIndex=0;let r=this.data.combo&&this.data.options.length>0;this.data.combo||(i.size=this.data.options.length,this.data.multiSelect&&(i.multiple=!0)),i.addEventListener("resetform",h=>{const d=this.data.defaultFieldValue;for(const p of i.options)p.selected=p.value===d});const o=(h,d)=>{const p=d.replaceAll(" "," ");h.textContent=p,p!==d&&h.setAttribute("display-value",d)};for(const h of this.data.options){const d=document.createElement("option");o(d,h.displayValue),d.value=h.exportValue,n.value.includes(h.exportValue)&&(d.setAttribute("selected",!0),r=!1),i.append(d)}let a=null;if(r){const h=document.createElement("option");h.value=" ",h.setAttribute("hidden",!0),h.setAttribute("selected",!0),i.prepend(h),a=()=>{h.remove(),i.removeEventListener("input",a),a=null},i.addEventListener("input",a)}const c=h=>{const d=h?"value":"textContent",{options:p,multiple:m}=i;return m?Array.prototype.filter.call(p,v=>v.selected).map(v=>v[d]):p.selectedIndex===-1?null:p[p.selectedIndex][d]};let l=c(!1);const u=h=>{const d=h.target.options;return Array.prototype.map.call(d,p=>({displayValue:p.getAttribute("display-value")||p.textContent,exportValue:p.value}))};return this.enableScripting&&this.hasJSActions?(i.addEventListener("updatefromsandbox",h=>{const d={value(p){a==null||a();const m=p.detail.value,v=new Set(Array.isArray(m)?m:[m]);for(const g of i.options)g.selected=v.has(g.value);e.setValue(t,{value:c(!0)}),l=c(!1)},multipleSelection(p){i.multiple=!0},remove(p){const m=i.options,v=p.detail.remove;m[v].selected=!1,i.remove(v),m.length>0&&Array.prototype.findIndex.call(m,y=>y.selected)===-1&&(m[0].selected=!0),e.setValue(t,{value:c(!0),items:u(p)}),l=c(!1)},clear(p){for(;i.length!==0;)i.remove(0);e.setValue(t,{value:null,items:[]}),l=c(!1)},insert(p){const{index:m,displayValue:v,exportValue:g}=p.detail.insert,y=i.children[m],b=document.createElement("option");o(b,v),b.value=g,y?y.before(b):i.append(b),e.setValue(t,{value:c(!0),items:u(p)}),l=c(!1)},items(p){const{items:m}=p.detail;for(;i.length!==0;)i.remove(0);for(const v of m){const{displayValue:g,exportValue:y}=v,b=document.createElement("option");o(b,g),b.value=y,i.append(b)}i.options.length>0&&(i.options[0].selected=!0),e.setValue(t,{value:c(!0),items:u(p)}),l=c(!1)},indices(p){const m=new Set(p.detail.indices);for(const v of p.target.options)v.selected=m.has(v.index);e.setValue(t,{value:c(!0)}),l=c(!1)},editable(p){p.target.disabled=!p.detail.editable}};this._dispatchEventFromSandbox(d,h)}),i.addEventListener("input",h=>{var m;const d=c(!0),p=c(!1);e.setValue(t,{value:d}),h.preventDefault(),(m=this.linkService.eventBus)==null||m.dispatch("dispatcheventinsandbox",{source:this,detail:{id:t,name:"Keystroke",value:l,change:p,changeEx:d,willCommit:!1,commitKey:1,keyDown:!1}})}),this._setEventListeners(i,null,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"],["input","Action"],["input","Validate"]],h=>h.target.value)):i.addEventListener("input",function(h){e.setValue(t,{value:c(!0)})}),this.data.combo&&this._setTextStyle(i),this._setBackgroundColor(i),this._setDefaultPropertiesFromJS(i),this.container.append(i),this.container}}var yb,dA;class hA extends Ks{constructor(t){const{data:n,elements:i,parent:r}=t,o=!!r._commentManager;super(t,{isRenderable:!o&&Ks._hasPopupData(n)});D(this,yb);if(this.elements=i,o&&Ks._hasPopupData(n)){const a=this.popup=B(this,yb,dA).call(this);for(const c of i)c.popup=a}else this.popup=null}render(){const{container:t}=this;t.classList.add("popupAnnotation"),t.role="comment";const n=this.popup=B(this,yb,dA).call(this),i=[];for(const r of this.elements)r.popup=n,r.container.ariaHasPopup="dialog",i.push(r.data.id),r.addHighlightArea();return this.container.setAttribute("aria-controls",i.map(r=>`${yp}${r}`).join(",")),this.container}}yb=new WeakSet,dA=function(){return new ise({container:this.container,color:this.data.color,titleObj:this.data.titleObj,modificationDate:this.data.modificationDate||this.data.creationDate,contentsObj:this.data.contentsObj,richText:this.data.richText,rect:this.data.rect,parentRect:this.data.parentRect||null,parent:this.parent,elements:this.elements,open:this.data.open,commentManager:this.parent._commentManager})};var Ur,Ou,F0,$0,kg,Cg,sn,Ga,Du,qd,Tg,Ag,qa,Wr,tc,sc,nn,nc,Nu,bb,ic,Eg,Kd,Bu,Wn,Fu,Dt,zS,fA,pA,gA,jS,mA,nB,iB,rB,oB,VS,GS,vA;class ise{constructor({container:e,color:t,elements:n,titleObj:i,modificationDate:r,contentsObj:o,richText:a,parent:c,rect:l,parentRect:u,open:h,commentManager:d=null}){D(this,Dt);D(this,Ur,null);D(this,Ou,B(this,Dt,rB).bind(this));D(this,F0,B(this,Dt,vA).bind(this));D(this,$0,B(this,Dt,GS).bind(this));D(this,kg,B(this,Dt,VS).bind(this));D(this,Cg,null);D(this,sn,null);D(this,Ga,null);D(this,Du,null);D(this,qd,null);D(this,Tg,null);D(this,Ag,null);D(this,qa,!1);D(this,Wr,null);D(this,tc,null);D(this,sc,null);D(this,nn,null);D(this,nc,null);D(this,Nu,null);D(this,bb,null);D(this,ic,null);D(this,Eg,null);D(this,Kd,null);D(this,Bu,!1);D(this,Wn,null);D(this,Fu,null);x(this,sn,e),x(this,Eg,i),x(this,Ga,o),x(this,ic,a),x(this,Tg,c),x(this,Cg,t),x(this,bb,l),x(this,Ag,u),x(this,qd,n),x(this,Ur,d),x(this,Wn,n[0]),x(this,Du,c0.toDateObject(r)),this.trigger=n.flatMap(p=>p.getElementsToTriggerPopup()),d||(B(this,Dt,zS).call(this),f(this,sn).hidden=!0,h&&B(this,Dt,VS).call(this))}renderCommentButton(){if(f(this,nn)){f(this,nn).parentNode||f(this,Wn).container.after(f(this,nn));return}if(f(this,nc)||B(this,Dt,fA).call(this),!f(this,nc))return;const{signal:e}=x(this,tc,new AbortController),t=f(this,Wn).hasOwnCommentButton,n=()=>{f(this,Ur).toggleCommentPopup(this,!0,void 0,!t)},i=()=>{f(this,Ur).toggleCommentPopup(this,!1,!0,!t)},r=()=>{f(this,Ur).toggleCommentPopup(this,!1,!1)};if(t){x(this,nn,f(this,Wn).container);for(const o of this.trigger)o.ariaHasPopup="dialog",o.ariaControls="commentPopup",o.addEventListener("keydown",f(this,Ou),{signal:e}),o.addEventListener("click",n,{signal:e}),o.addEventListener("pointerenter",i,{signal:e}),o.addEventListener("pointerleave",r,{signal:e}),o.classList.add("popupTriggerArea")}else{const o=x(this,nn,document.createElement("button"));o.className="annotationCommentButton";const a=f(this,Wn).container;o.style.zIndex=parseInt(a.style.zIndex,10)+1,o.tabIndex=0,o.ariaHasPopup="dialog",o.ariaControls="commentPopup",o.setAttribute("data-l10n-id","pdfjs-show-comment-button"),B(this,Dt,gA).call(this),B(this,Dt,pA).call(this),o.addEventListener("keydown",f(this,Ou),{signal:e}),o.addEventListener("click",n,{signal:e}),o.addEventListener("pointerenter",i,{signal:e}),o.addEventListener("pointerleave",r,{signal:e}),a.after(o)}}get commentButtonColor(){const{color:e,opacity:t}=f(this,Wn).commentData;return e?f(this,Tg)._commentManager.makeCommentColor(e,t):null}focusCommentButton(){setTimeout(()=>{var e;(e=f(this,nn))==null||e.focus()},0)}getData(){const{richText:e,color:t,opacity:n,creationDate:i,modificationDate:r}=f(this,Wn).commentData;return{contentsObj:{str:this.comment},richText:e,color:t,opacity:n,creationDate:i,modificationDate:r}}get elementBeforePopup(){return f(this,nn)}get comment(){return f(this,Fu)||x(this,Fu,f(this,Wn).commentText),f(this,Fu)}set comment(e){e!==this.comment&&(f(this,Wn).commentText=x(this,Fu,e))}focus(){var e;(e=f(this,Wn).container)==null||e.focus()}get parentBoundingClientRect(){return f(this,Wn).layer.getBoundingClientRect()}setCommentButtonStates({selected:e,hasPopup:t}){f(this,nn)&&(f(this,nn).classList.toggle("selected",e),f(this,nn).ariaExpanded=t)}setSelectedCommentButton(e){f(this,nn).classList.toggle("selected",e)}get commentPopupPosition(){if(f(this,Nu))return f(this,Nu);const{x:e,y:t,height:n}=f(this,nn).getBoundingClientRect(),{x:i,y:r,width:o,height:a}=f(this,Wn).layer.getBoundingClientRect();return[(e-i)/o,(t+n-r)/a]}set commentPopupPosition(e){x(this,Nu,e)}hasDefaultPopupPosition(){return f(this,Nu)===null}get commentButtonPosition(){return f(this,nc)}get commentButtonWidth(){return f(this,nn).getBoundingClientRect().width/this.parentBoundingClientRect.width}editComment(e){const[t,n]=f(this,Nu)||this.commentButtonPosition.map(l=>l/100),i=this.parentBoundingClientRect,{x:r,y:o,width:a,height:c}=i;f(this,Ur).showDialog(null,this,r+t*a,o+n*c,{...e,parentDimensions:i})}render(){var n,i;if(f(this,Wr))return;const e=x(this,Wr,document.createElement("div"));if(e.className="popup",f(this,Cg)){const r=e.style.outlineColor=Be.makeHexColor(...f(this,Cg));e.style.backgroundColor=`color-mix(in srgb, ${r} 30%, white)`}const t=document.createElement("span");if(t.className="header",(n=f(this,Eg))!=null&&n.str){const r=document.createElement("span");r.className="title",t.append(r),{dir:r.dir,str:r.textContent}=f(this,Eg)}if(e.append(t),f(this,Du)){const r=document.createElement("time");r.className="popupDate",r.setAttribute("data-l10n-id","pdfjs-annotation-date-time-string"),r.setAttribute("data-l10n-args",JSON.stringify({dateObj:f(this,Du).valueOf()})),r.dateTime=f(this,Du).toISOString(),t.append(r)}OD({html:f(this,Dt,jS)||f(this,Ga).str,dir:(i=f(this,Ga))==null?void 0:i.dir,className:"popupContent"},e),f(this,sn).append(e)}updateEdited({rect:e,popup:t,deleted:n}){var i;if(f(this,Ur)){n?(this.remove(),x(this,Fu,null)):t&&(t.deleted?this.remove():(B(this,Dt,gA).call(this),x(this,Fu,t.text))),e&&(x(this,nc,null),B(this,Dt,fA).call(this),B(this,Dt,pA).call(this));return}if(n||t!=null&&t.deleted){this.remove();return}B(this,Dt,zS).call(this),f(this,Kd)||x(this,Kd,{contentsObj:f(this,Ga),richText:f(this,ic)}),e&&x(this,sc,null),t&&t.text&&(x(this,ic,B(this,Dt,iB).call(this,t.text)),x(this,Du,c0.toDateObject(t.date)),x(this,Ga,null)),(i=f(this,Wr))==null||i.remove(),x(this,Wr,null)}resetEdited(){var e;f(this,Kd)&&({contentsObj:xs(this,Ga)._,richText:xs(this,ic)._}=f(this,Kd),x(this,Kd,null),(e=f(this,Wr))==null||e.remove(),x(this,Wr,null),x(this,sc,null))}remove(){var e,t,n;if((e=f(this,tc))==null||e.abort(),x(this,tc,null),(t=f(this,Wr))==null||t.remove(),x(this,Wr,null),x(this,Bu,!1),x(this,qa,!1),(n=f(this,nn))==null||n.remove(),x(this,nn,null),this.trigger)for(const i of this.trigger)i.classList.remove("popupTriggerArea")}forceHide(){x(this,Bu,this.isVisible),f(this,Bu)&&(f(this,sn).hidden=!0)}maybeShow(){f(this,Ur)||(B(this,Dt,zS).call(this),f(this,Bu)&&(f(this,Wr)||B(this,Dt,GS).call(this),x(this,Bu,!1),f(this,sn).hidden=!1))}get isVisible(){return f(this,Ur)?!1:f(this,sn).hidden===!1}}Ur=new WeakMap,Ou=new WeakMap,F0=new WeakMap,$0=new WeakMap,kg=new WeakMap,Cg=new WeakMap,sn=new WeakMap,Ga=new WeakMap,Du=new WeakMap,qd=new WeakMap,Tg=new WeakMap,Ag=new WeakMap,qa=new WeakMap,Wr=new WeakMap,tc=new WeakMap,sc=new WeakMap,nn=new WeakMap,nc=new WeakMap,Nu=new WeakMap,bb=new WeakMap,ic=new WeakMap,Eg=new WeakMap,Kd=new WeakMap,Bu=new WeakMap,Wn=new WeakMap,Fu=new WeakMap,Dt=new WeakSet,zS=function(){var t;if(f(this,tc))return;x(this,tc,new AbortController);const{signal:e}=f(this,tc);for(const n of this.trigger)n.addEventListener("click",f(this,kg),{signal:e}),n.addEventListener("pointerenter",f(this,$0),{signal:e}),n.addEventListener("pointerleave",f(this,F0),{signal:e}),n.classList.add("popupTriggerArea");for(const n of f(this,qd))(t=n.container)==null||t.addEventListener("keydown",f(this,Ou),{signal:e})},fA=function(){const e=f(this,qd).find(t=>t.hasCommentButton);e&&x(this,nc,e._normalizePoint(e.commentButtonPosition))},pA=function(){if(f(this,Wn).extraPopupElement&&!f(this,Wn).editor)return;f(this,nn)||this.renderCommentButton();const[e,t]=f(this,nc),{style:n}=f(this,nn);n.left=`calc(${e}%)`,n.top=`calc(${t}% - var(--comment-button-dim))`},gA=function(){f(this,Wn).extraPopupElement||(f(this,nn)||this.renderCommentButton(),f(this,nn).style.backgroundColor=this.commentButtonColor||"")},jS=function(){const e=f(this,ic),t=f(this,Ga);return e!=null&&e.str&&(!(t!=null&&t.str)||t.str===e.str)&&f(this,ic).html||null},mA=function(){var e,t,n;return((n=(t=(e=f(this,Dt,jS))==null?void 0:e.attributes)==null?void 0:t.style)==null?void 0:n.fontSize)||0},nB=function(){var e,t,n;return((n=(t=(e=f(this,Dt,jS))==null?void 0:e.attributes)==null?void 0:t.style)==null?void 0:n.color)||null},iB=function(e){const t=[],n={str:e,html:{name:"div",attributes:{dir:"auto"},children:[{name:"p",children:t}]}},i={style:{color:f(this,Dt,nB),fontSize:f(this,Dt,mA)?`calc(${f(this,Dt,mA)}px * var(--total-scale-factor))`:""}};for(const r of e.split(`
`))t.push({name:"span",value:r,attributes:i});return n},rB=function(e){e.altKey||e.shiftKey||e.ctrlKey||e.metaKey||(e.key==="Enter"||e.key==="Escape"&&f(this,qa))&&B(this,Dt,VS).call(this)},oB=function(){if(f(this,sc)!==null)return;const{page:{view:e},viewport:{rawDims:{pageWidth:t,pageHeight:n,pageX:i,pageY:r}}}=f(this,Tg);let o=!!f(this,Ag),a=o?f(this,Ag):f(this,bb);for(const m of f(this,qd))if(!a||Be.intersect(m.data.rect,a)!==null){a=m.data.rect,o=!0;break}const c=Be.normalizeRect([a[0],e[3]-a[1]+e[1],a[2],e[3]-a[3]+e[1]]),u=o?a[2]-a[0]+5:0,h=c[0]+u,d=c[1];x(this,sc,[100*(h-i)/t,100*(d-r)/n]);const{style:p}=f(this,sn);p.left=`${f(this,sc)[0]}%`,p.top=`${f(this,sc)[1]}%`},VS=function(){if(f(this,Ur)){f(this,Ur).toggleCommentPopup(this,!1);return}x(this,qa,!f(this,qa)),f(this,qa)?(B(this,Dt,GS).call(this),f(this,sn).addEventListener("click",f(this,kg)),f(this,sn).addEventListener("keydown",f(this,Ou))):(B(this,Dt,vA).call(this),f(this,sn).removeEventListener("click",f(this,kg)),f(this,sn).removeEventListener("keydown",f(this,Ou)))},GS=function(){f(this,Wr)||this.render(),this.isVisible?f(this,qa)&&f(this,sn).classList.add("focused"):(B(this,Dt,oB).call(this),f(this,sn).hidden=!1,f(this,sn).style.zIndex=parseInt(f(this,sn).style.zIndex,10)+1e3)},vA=function(){f(this,sn).classList.remove("focused"),!(f(this,qa)||!this.isVisible)&&(f(this,sn).hidden=!0,f(this,sn).style.zIndex=parseInt(f(this,sn).style.zIndex,10)-1e3)};class aB extends Ks{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0}),this.textContent=e.data.textContent,this.textPosition=e.data.textPosition,this.annotationEditorType=Ct.FREETEXT}render(){if(this.container.classList.add("freeTextAnnotation"),this.textContent){const e=this.contentElement=document.createElement("div");e.classList.add("annotationTextContent"),e.setAttribute("role","comment");for(const t of this.textContent){const n=document.createElement("span");n.textContent=t,e.append(n)}this.container.append(e)}return!this.data.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this._editOnDoubleClick(),this.container}}var _b;class rse extends Ks{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0});D(this,_b,null)}render(){this.container.classList.add("lineAnnotation");const{data:t,width:n,height:i}=this,r=this.svgFactory.create(n,i,!0),o=x(this,_b,this.svgFactory.createElement("svg:line"));return o.setAttribute("x1",t.rect[2]-t.lineCoordinates[0]),o.setAttribute("y1",t.rect[3]-t.lineCoordinates[1]),o.setAttribute("x2",t.rect[2]-t.lineCoordinates[2]),o.setAttribute("y2",t.rect[3]-t.lineCoordinates[3]),o.setAttribute("stroke-width",t.borderStyle.width||1),o.setAttribute("stroke","transparent"),o.setAttribute("fill","transparent"),r.append(o),this.container.append(r),!t.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container}getElementsToTriggerPopup(){return f(this,_b)}addHighlightArea(){this.container.classList.add("highlightArea")}}_b=new WeakMap;var Sb;class ose extends Ks{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0});D(this,Sb,null)}render(){this.container.classList.add("squareAnnotation");const{data:t,width:n,height:i}=this,r=this.svgFactory.create(n,i,!0),o=t.borderStyle.width,a=x(this,Sb,this.svgFactory.createElement("svg:rect"));return a.setAttribute("x",o/2),a.setAttribute("y",o/2),a.setAttribute("width",n-o),a.setAttribute("height",i-o),a.setAttribute("stroke-width",o||1),a.setAttribute("stroke","transparent"),a.setAttribute("fill","transparent"),r.append(a),this.container.append(r),!t.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container}getElementsToTriggerPopup(){return f(this,Sb)}addHighlightArea(){this.container.classList.add("highlightArea")}}Sb=new WeakMap;var wb;class ase extends Ks{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0});D(this,wb,null)}render(){this.container.classList.add("circleAnnotation");const{data:t,width:n,height:i}=this,r=this.svgFactory.create(n,i,!0),o=t.borderStyle.width,a=x(this,wb,this.svgFactory.createElement("svg:ellipse"));return a.setAttribute("cx",n/2),a.setAttribute("cy",i/2),a.setAttribute("rx",n/2-o/2),a.setAttribute("ry",i/2-o/2),a.setAttribute("stroke-width",o||1),a.setAttribute("stroke","transparent"),a.setAttribute("fill","transparent"),r.append(a),this.container.append(r),!t.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container}getElementsToTriggerPopup(){return f(this,wb)}addHighlightArea(){this.container.classList.add("highlightArea")}}wb=new WeakMap;var kb;class lB extends Ks{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0});D(this,kb,null);this.containerClassName="polylineAnnotation",this.svgElementName="svg:polyline"}render(){this.container.classList.add(this.containerClassName);const{data:{rect:t,vertices:n,borderStyle:i,popupRef:r},width:o,height:a}=this;if(!n)return this.container;const c=this.svgFactory.create(o,a,!0);let l=[];for(let h=0,d=n.length;h<d;h+=2){const p=n[h]-t[0],m=t[3]-n[h+1];l.push(`${p},${m}`)}l=l.join(" ");const u=x(this,kb,this.svgFactory.createElement(this.svgElementName));return u.setAttribute("points",l),u.setAttribute("stroke-width",i.width||1),u.setAttribute("stroke","transparent"),u.setAttribute("fill","transparent"),c.append(u),this.container.append(c),!r&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container}getElementsToTriggerPopup(){return f(this,kb)}addHighlightArea(){this.container.classList.add("highlightArea")}}kb=new WeakMap;class lse extends lB{constructor(e){super(e),this.containerClassName="polygonAnnotation",this.svgElementName="svg:polygon"}}class cse extends Ks{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0})}render(){return this.container.classList.add("caretAnnotation"),!this.data.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container}}var Cb,Qd,Tb,yA;class gM extends Ks{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0});D(this,Tb);D(this,Cb,null);D(this,Qd,[]);this.containerClassName="inkAnnotation",this.svgElementName="svg:polyline",this.annotationEditorType=this.data.it==="InkHighlight"?Ct.HIGHLIGHT:Ct.INK}render(){this.container.classList.add(this.containerClassName);const{data:{rect:t,rotation:n,inkLists:i,borderStyle:r,popupRef:o}}=this,{transform:a,width:c,height:l}=B(this,Tb,yA).call(this,n,t),u=this.svgFactory.create(c,l,!0),h=x(this,Cb,this.svgFactory.createElement("svg:g"));u.append(h),h.setAttribute("stroke-width",r.width||1),h.setAttribute("stroke-linecap","round"),h.setAttribute("stroke-linejoin","round"),h.setAttribute("stroke-miterlimit",10),h.setAttribute("stroke","transparent"),h.setAttribute("fill","transparent"),h.setAttribute("transform",a);for(let d=0,p=i.length;d<p;d++){const m=this.svgFactory.createElement(this.svgElementName);f(this,Qd).push(m),m.setAttribute("points",i[d].join(",")),h.append(m)}return!o&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container.append(u),this._editOnDoubleClick(),this.container}updateEdited(t){super.updateEdited(t);const{thickness:n,points:i,rect:r}=t,o=f(this,Cb);if(n>=0&&o.setAttribute("stroke-width",n||1),i)for(let a=0,c=f(this,Qd).length;a<c;a++)f(this,Qd)[a].setAttribute("points",i[a].join(","));if(r){const{transform:a,width:c,height:l}=B(this,Tb,yA).call(this,this.data.rotation,r);o.parentElement.setAttribute("viewBox",`0 0 ${c} ${l}`),o.setAttribute("transform",a)}}getElementsToTriggerPopup(){return f(this,Qd)}addHighlightArea(){this.container.classList.add("highlightArea")}}Cb=new WeakMap,Qd=new WeakMap,Tb=new WeakSet,yA=function(t,n){switch(t){case 90:return{transform:`rotate(90) translate(${-n[0]},${n[1]}) scale(1,-1)`,width:n[3]-n[1],height:n[2]-n[0]};case 180:return{transform:`rotate(180) translate(${-n[2]},${n[1]}) scale(1,-1)`,width:n[2]-n[0],height:n[3]-n[1]};case 270:return{transform:`rotate(270) translate(${-n[2]},${n[3]}) scale(1,-1)`,width:n[3]-n[1],height:n[2]-n[0]};default:return{transform:`translate(${-n[0]},${n[3]}) scale(1,-1)`,width:n[2]-n[0],height:n[3]-n[1]}}};class cB extends Ks{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0}),this.annotationEditorType=Ct.HIGHLIGHT}render(){const{data:{overlaidText:e,popupRef:t}}=this;if(!t&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container.classList.add("highlightAnnotation"),this._editOnDoubleClick(),e){const n=document.createElement("mark");n.classList.add("overlaidText"),n.textContent=e,this.container.append(n)}return this.container}}class use extends Ks{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){const{data:{overlaidText:e,popupRef:t}}=this;if(!t&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container.classList.add("underlineAnnotation"),e){const n=document.createElement("u");n.classList.add("overlaidText"),n.textContent=e,this.container.append(n)}return this.container}}class hse extends Ks{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){const{data:{overlaidText:e,popupRef:t}}=this;if(!t&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container.classList.add("squigglyAnnotation"),e){const n=document.createElement("u");n.classList.add("overlaidText"),n.textContent=e,this.container.append(n)}return this.container}}class dse extends Ks{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){const{data:{overlaidText:e,popupRef:t}}=this;if(!t&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container.classList.add("strikeoutAnnotation"),e){const n=document.createElement("s");n.classList.add("overlaidText"),n.textContent=e,this.container.append(n)}return this.container}}class uB extends Ks{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0}),this.annotationEditorType=Ct.STAMP}render(){return this.container.classList.add("stampAnnotation"),this.container.setAttribute("role","img"),!this.data.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this._editOnDoubleClick(),this.container}}var Ab,Eb,bA;class fse extends Ks{constructor(t){var i;super(t,{isRenderable:!0});D(this,Eb);D(this,Ab,null);const{file:n}=this.data;this.filename=n.filename,this.content=n.content,(i=this.linkService.eventBus)==null||i.dispatch("fileattachmentannotation",{source:this,...n})}render(){this.container.classList.add("fileAttachmentAnnotation");const{container:t,data:n}=this;let i;n.hasAppearance||n.fillAlpha===0?i=document.createElement("div"):(i=document.createElement("img"),i.src=`${this.imageResourcesPath}annotation-${/paperclip/i.test(n.name)?"paperclip":"pushpin"}.svg`,n.fillAlpha&&n.fillAlpha<1&&(i.style=`filter: opacity(${Math.round(n.fillAlpha*100)}%);`)),i.addEventListener("dblclick",B(this,Eb,bA).bind(this)),x(this,Ab,i);const{isMac:r}=Ts.platform;return t.addEventListener("keydown",o=>{o.key==="Enter"&&(r?o.metaKey:o.ctrlKey)&&B(this,Eb,bA).call(this)}),!n.popupRef&&this.hasPopupData?(this.hasOwnCommentButton=!0,this._createPopup()):i.classList.add("popupTriggerArea"),t.append(i),t}getElementsToTriggerPopup(){return f(this,Ab)}addHighlightArea(){this.container.classList.add("highlightArea")}}Ab=new WeakMap,Eb=new WeakSet,bA=function(){var t;(t=this.downloadManager)==null||t.openOrDownloadData(this.content,this.filename)};var Xd,Yd,Mg,$u,Mb,Jd,hr,xb,kc,qS,SA;const EM=class EM{constructor({div:e,accessibilityManager:t,annotationCanvasMap:n,annotationEditorUIManager:i,page:r,viewport:o,structTreeLayer:a,commentManager:c,linkService:l,annotationStorage:u}){D(this,kc);D(this,Xd,null);D(this,Yd,null);D(this,Mg,null);D(this,$u,new Map);D(this,Mb,null);D(this,Jd,null);D(this,hr,[]);D(this,xb,!1);_e(this,"zIndex",0);this.div=e,x(this,Xd,t),x(this,Yd,n),x(this,Mb,a||null),x(this,Jd,l||null),x(this,Mg,u||new dM),this.page=r,this.viewport=o,this._annotationEditorUIManager=i,this._commentManager=c||null}hasEditableAnnotations(){return f(this,$u).size>0}async render(e){var c;const{annotations:t,optionalContentConfig:n}=e,i=this.div;Rf(i,this.viewport);const r=new Map,o=[],a={data:null,layer:i,linkService:f(this,Jd),downloadManager:e.downloadManager,imageResourcesPath:e.imageResourcesPath||"",renderForms:e.renderForms!==!1,svgFactory:new p0,annotationStorage:f(this,Mg),enableComment:e.enableComment===!0,enableScripting:e.enableScripting===!0,hasJSActions:e.hasJSActions,fieldObjects:e.fieldObjects,parent:this,elements:null};for(const l of t){if(l.noHTML)continue;const u=l.annotationType===mn.POPUP;if(u){const p=r.get(l.id);if(!p)continue;if(!this._commentManager){o.push(l);continue}a.elements=p}else if(l.rect[2]===l.rect[0]||l.rect[3]===l.rect[1])continue;a.data=l;const h=e1.create(a);if(!h.isRenderable)continue;u||(f(this,hr).push(h),l.popupRef&&r.getOrInsertComputed(l.popupRef,aM).push(h));const d=h.render();l.hidden&&(d.style.visibility="hidden"),h.updateOC(n),h._isEditable&&(f(this,$u).set(h.data.id,h),(c=this._annotationEditorUIManager)==null||c.renderAnnotationElement(h))}await B(this,kc,qS).call(this);for(const l of o){const u=a.elements=r.get(l.id);a.data=l;const h=e1.create(a);if(!h.isRenderable)continue;const d=h.render();h.contentElement.id=`${yp}${l.id}`,l.hidden&&(d.style.visibility="hidden"),u.at(-1).container.after(d)}B(this,kc,SA).call(this)}async addLinkAnnotations(e){const t={data:null,layer:this.div,linkService:f(this,Jd),svgFactory:new p0,parent:this};for(const n of e){n.borderStyle||(n.borderStyle=EM._defaultBorderStyle),t.data=n;const i=e1.create(t);i.isRenderable&&(i.render(),i.contentElement.id=`${yp}${n.id}`,f(this,hr).push(i))}await B(this,kc,qS).call(this)}update({viewport:e,optionalContentConfig:t}){const n=this.div;this.viewport=e,Rf(n,{rotation:e.rotation});for(const i of f(this,hr))i.updateOC(t);B(this,kc,SA).call(this),n.hidden=!1}getEditableAnnotations(){return f(this,$u).values()}getEditableAnnotation(e){return f(this,$u).get(e)}addFakeAnnotation(e){const{div:t}=this,{id:n,rotation:i}=e,r=new Yte({data:{id:n,rect:e.getPDFRect(),rotation:i},editor:e,layer:t,parent:this,enableComment:!!this._commentManager,linkService:f(this,Jd),annotationStorage:f(this,Mg)});return r.render(),r.contentElement.id=`${yp}${n}`,r.createOrUpdatePopup(),f(this,hr).push(r),r}removeAnnotation(e){var i;const t=f(this,hr).findIndex(r=>r.data.id===e);if(t<0)return;const[n]=f(this,hr).splice(t,1);(i=f(this,Xd))==null||i.removePointerInTextLayer(n.contentElement)}updateFakeAnnotations(e){if(e.length!==0){for(const t of e)t.updateFakeAnnotationElement(this);B(this,kc,qS).call(this)}}togglePointerEvents(e=!1){this.div.classList.toggle("disabled",!e)}static get _defaultBorderStyle(){return Tt(this,"_defaultBorderStyle",Object.freeze({width:1,rawWidth:1,style:hp.SOLID,dashArray:[3],horizontalCornerRadius:0,verticalCornerRadius:0}))}};Xd=new WeakMap,Yd=new WeakMap,Mg=new WeakMap,$u=new WeakMap,Mb=new WeakMap,Jd=new WeakMap,hr=new WeakMap,xb=new WeakMap,kc=new WeakSet,qS=async function(){var n,i,r;if(f(this,hr).length===0)return;this.div.replaceChildren();const e=[];if(!f(this,xb)){x(this,xb,!0);for(const{contentElement:o,data:{id:a}}of f(this,hr)){const c=o.id=`${yp}${a}`;e.push((n=f(this,Mb))==null?void 0:n.getAriaAttributes(c).then(l=>{if(l)for(const[u,h]of l)o.setAttribute(u,h)}))}}f(this,hr).sort(({data:{rect:[o,a,c,l]}},{data:{rect:[u,h,d,p]}})=>{if(o===c&&a===l)return 1;if(u===d&&h===p)return-1;const m=l,v=a,g=(a+l)/2,y=p,b=h,_=(h+p)/2;if(g>=y&&_<=v)return-1;if(_>=m&&g<=b)return 1;const w=(o+c)/2,S=(u+d)/2;return w-S});const t=document.createDocumentFragment();for(const o of f(this,hr))t.append(o.container),this._commentManager?(r=((i=o.extraPopupElement)==null?void 0:i.popup)||o.popup)==null||r.renderCommentButton():o.extraPopupElement&&t.append(o.extraPopupElement.render());if(this.div.append(t),await Promise.all(e),f(this,Xd))for(const o of f(this,hr))f(this,Xd).addPointerInTextLayer(o.contentElement,!1)},SA=function(){var t;if(!f(this,Yd))return;const e=this.div;for(const[n,i]of f(this,Yd)){const r=e.querySelector(`[data-annotation-id="${n}"]`);if(!r)continue;i.className="annotationContent";const{firstChild:o}=r;o?o.nodeName==="CANVAS"?o.replaceWith(i):o.classList.contains("annotationContent")?o.after(i):o.before(i):r.append(i);const a=f(this,$u).get(n);a&&(a._hasNoCanvas?((t=this._annotationEditorUIManager)==null||t.setMissingCanvas(n,r.id,i),a._hasNoCanvas=!1):a.canvas=i)}f(this,Yd).clear()};let _A=EM;const X_=/\r\n?|\n/g;var zr,Ib,Zd,jr,Sn,hB,dB,fB,KS,Cc,QS,XS,pB,kA,gB;const Is=class Is extends is{constructor(t){super({...t,name:"freeTextEditor"});D(this,Sn);D(this,zr,"");D(this,Ib,`${this.id}-editor`);D(this,Zd,null);D(this,jr);_e(this,"_colorPicker",null);this.color=t.color||Is._defaultColor||is._defaultLineColor,x(this,jr,t.fontSize||Is._defaultFontSize),this.annotationElementId||this._uiManager.a11yAlert(is._l10nAlert.freetext),this.canAddComment=!1}static get _keyboardManager(){const t=Is.prototype,n=o=>o.isEmpty(),i=Lf.TRANSLATE_SMALL,r=Lf.TRANSLATE_BIG;return Tt(this,"_keyboardManager",new r_([[["ctrl+s","mac+meta+s","ctrl+p","mac+meta+p"],t.commitOrRemove,{bubbles:!0}],[["ctrl+Enter","mac+meta+Enter","Escape","mac+Escape"],t.commitOrRemove],[["ArrowLeft","mac+ArrowLeft"],t._translateEmpty,{args:[-i,0],checker:n}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t._translateEmpty,{args:[-r,0],checker:n}],[["ArrowRight","mac+ArrowRight"],t._translateEmpty,{args:[i,0],checker:n}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t._translateEmpty,{args:[r,0],checker:n}],[["ArrowUp","mac+ArrowUp"],t._translateEmpty,{args:[0,-i],checker:n}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t._translateEmpty,{args:[0,-r],checker:n}],[["ArrowDown","mac+ArrowDown"],t._translateEmpty,{args:[0,i],checker:n}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t._translateEmpty,{args:[0,r],checker:n}]]))}static initialize(t,n){is.initialize(t,n);const i=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(i.getPropertyValue("--freetext-padding"))}static updateDefaultParams(t,n){switch(t){case xt.FREETEXT_SIZE:Is._defaultFontSize=n;break;case xt.FREETEXT_COLOR:Is._defaultColor=n;break}}updateParams(t,n){switch(t){case xt.FREETEXT_SIZE:B(this,Sn,hB).call(this,n);break;case xt.FREETEXT_COLOR:B(this,Sn,dB).call(this,n);break}}static get defaultPropertiesToUpdate(){return[[xt.FREETEXT_SIZE,Is._defaultFontSize],[xt.FREETEXT_COLOR,Is._defaultColor||is._defaultLineColor]]}get propertiesToUpdate(){return[[xt.FREETEXT_SIZE,f(this,jr)],[xt.FREETEXT_COLOR,this.color]]}get toolbarButtons(){return this._colorPicker||(this._colorPicker=new f0(this)),[["colorPicker",this._colorPicker]]}get colorType(){return xt.FREETEXT_COLOR}onUpdatedColor(){var t;this.editorDiv.style.color=this.color,(t=this._colorPicker)==null||t.update(this.color),super.onUpdatedColor()}_translateEmpty(t,n){this._uiManager.translateSelectedEditors(t,n,!0)}getInitialTranslation(){const t=this.parentScale;return[-Is._internalPadding*t,-(Is._internalPadding+f(this,jr))*t]}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.isAttachedToDOM||this.parent.add(this)))}enableEditMode(){if(!super.enableEditMode())return!1;this.overlayDiv.classList.remove("enabled"),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute("aria-activedescendant"),x(this,Zd,new AbortController);const t=this._uiManager.combinedSignal(f(this,Zd));return this.editorDiv.addEventListener("keydown",this.editorDivKeydown.bind(this),{signal:t}),this.editorDiv.addEventListener("focus",this.editorDivFocus.bind(this),{signal:t}),this.editorDiv.addEventListener("blur",this.editorDivBlur.bind(this),{signal:t}),this.editorDiv.addEventListener("input",this.editorDivInput.bind(this),{signal:t}),this.editorDiv.addEventListener("paste",this.editorDivPaste.bind(this),{signal:t}),!0}disableEditMode(){var t;return super.disableEditMode()?(this.overlayDiv.classList.add("enabled"),this.editorDiv.contentEditable=!1,this.div.setAttribute("aria-activedescendant",f(this,Ib)),this._isDraggable=!0,(t=f(this,Zd))==null||t.abort(),x(this,Zd,null),this.div.focus({preventScroll:!0}),this.isEditing=!1,this.parent.div.classList.add("freetextEditing"),!0):!1}focusin(t){this._focusEventsAllowed&&(super.focusin(t),t.target!==this.editorDiv&&this.editorDiv.focus())}onceAdded(t){var n;this.width||(this.enableEditMode(),t&&this.editorDiv.focus(),(n=this._initialOptions)!=null&&n.isCentered&&this.center(),this._initialOptions=null)}isEmpty(){return!this.editorDiv||this.editorDiv.innerText.trim()===""}remove(){this.isEditing=!1,this.parent&&(this.parent.setEditingState(!0),this.parent.div.classList.add("freetextEditing")),super.remove()}commit(){if(!this.isInEditMode())return;super.commit(),this.disableEditMode();const t=f(this,zr),n=x(this,zr,B(this,Sn,fB).call(this).trimEnd());if(t===n)return;const i=r=>{if(x(this,zr,r),!r){this.remove();return}B(this,Sn,XS).call(this),this._uiManager.rebuild(this),B(this,Sn,KS).call(this)};this.addCommands({cmd:()=>{i(n)},undo:()=>{i(t)},mustExec:!1}),B(this,Sn,KS).call(this)}shouldGetKeyboardEvents(){return this.isInEditMode()}enterInEditMode(){this.enableEditMode(),this.editorDiv.focus()}keydown(t){t.target===this.div&&t.key==="Enter"&&(this.enterInEditMode(),t.preventDefault())}editorDivKeydown(t){Is._keyboardManager.exec(this,t)}editorDivFocus(t){this.isEditing=!0}editorDivBlur(t){this.isEditing=!1}editorDivInput(t){this.parent.div.classList.toggle("freetextEditing",this.isEmpty())}disableEditing(){this.editorDiv.setAttribute("role","comment"),this.editorDiv.removeAttribute("aria-multiline")}enableEditing(){this.editorDiv.setAttribute("role","textbox"),this.editorDiv.setAttribute("aria-multiline",!0)}get canChangeContent(){return!0}render(){if(this.div)return this.div;let t,n;(this._isCopy||this.annotationElementId)&&(t=this.x,n=this.y),super.render(),this.editorDiv=document.createElement("div"),this.editorDiv.className="internal",this.editorDiv.setAttribute("id",f(this,Ib)),this.editorDiv.setAttribute("data-l10n-id","pdfjs-free-text2"),this.editorDiv.setAttribute("data-l10n-attrs","default-content"),this.enableEditing(),this.editorDiv.contentEditable=!0;const{style:i}=this.editorDiv;if(i.fontSize=`calc(${f(this,jr)}px * var(--total-scale-factor))`,i.color=this.color,this.div.append(this.editorDiv),this.overlayDiv=document.createElement("div"),this.overlayDiv.classList.add("overlay","enabled"),this.div.append(this.overlayDiv),this._isCopy||this.annotationElementId){const[r,o]=this.parentDimensions;if(this.annotationElementId){const{position:a}=this._initialData;let[c,l]=this.getInitialTranslation();[c,l]=this.pageTranslationToScreen(c,l);const[u,h]=this.pageDimensions,[d,p]=this.pageTranslation;let m,v;switch(this.rotation){case 0:m=t+(a[0]-d)/u,v=n+this.height-(a[1]-p)/h;break;case 90:m=t+(a[0]-d)/u,v=n-(a[1]-p)/h,[c,l]=[l,-c];break;case 180:m=t-this.width+(a[0]-d)/u,v=n-(a[1]-p)/h,[c,l]=[-c,-l];break;case 270:m=t+(a[0]-d-this.height*h)/u,v=n+(a[1]-p-this.width*u)/h,[c,l]=[-l,c];break}this.setAt(m*r,v*o,c,l)}else this._moveAfterPaste(t,n);B(this,Sn,XS).call(this),this._isDraggable=!0,this.editorDiv.contentEditable=!1}else this._isDraggable=!1,this.editorDiv.contentEditable=!0;return this.div}editorDivPaste(t){var m,v,g;const n=t.clipboardData||window.clipboardData,{types:i}=n;if(i.length===1&&i[0]==="text/plain")return;t.preventDefault();const r=B(m=Is,Cc,kA).call(m,n.getData("text")||"").replaceAll(X_,`
`);if(!r)return;const o=window.getSelection();if(!o.rangeCount)return;this.editorDiv.normalize(),o.deleteFromDocument();const a=o.getRangeAt(0);if(!r.includes(`
`)){a.insertNode(document.createTextNode(r)),this.editorDiv.normalize(),o.collapseToStart();return}const{startContainer:c,startOffset:l}=a,u=[],h=[];if(c.nodeType===Node.TEXT_NODE){const y=c.parentElement;if(h.push(c.nodeValue.slice(l).replaceAll(X_,"")),y!==this.editorDiv){let b=u;for(const _ of this.editorDiv.childNodes){if(_===y){b=h;continue}b.push(B(v=Is,Cc,QS).call(v,_))}}u.push(c.nodeValue.slice(0,l).replaceAll(X_,""))}else if(c===this.editorDiv){let y=u,b=0;for(const _ of this.editorDiv.childNodes)b++===l&&(y=h),y.push(B(g=Is,Cc,QS).call(g,_))}x(this,zr,`${u.join(`
`)}${r}${h.join(`
`)}`),B(this,Sn,XS).call(this);const d=new Range;let p=Math.sumPrecise(u.map(y=>y.length));for(const{firstChild:y}of this.editorDiv.childNodes)if(y.nodeType===Node.TEXT_NODE){const b=y.nodeValue.length;if(p<=b){d.setStart(y,p),d.setEnd(y,p);break}p-=b}o.removeAllRanges(),o.addRange(d)}get contentDiv(){return this.editorDiv}getPDFRect(){const t=Is._internalPadding*this.parentScale;return this.getRect(t,t)}static async deserialize(t,n,i){var a;let r=null;if(t instanceof aB){const{data:{defaultAppearanceData:{fontSize:c,fontColor:l},rect:u,rotation:h,id:d,popupRef:p,richText:m,contentsObj:v,creationDate:g,modificationDate:y},textContent:b,textPosition:_,parent:{page:{pageNumber:w}}}=t;if(!b||b.length===0)return null;r=t={annotationType:Ct.FREETEXT,color:Array.from(l),fontSize:c,value:b.join(`
`),position:_,pageIndex:w-1,rect:u.slice(0),rotation:h,annotationElementId:d,id:d,deleted:!1,popupRef:p,comment:(v==null?void 0:v.str)||null,richText:m,creationDate:g,modificationDate:y}}const o=await super.deserialize(t,n,i);return x(o,jr,t.fontSize),o.color=Be.makeHexColor(...t.color),x(o,zr,B(a=Is,Cc,kA).call(a,t.value)),o._initialData=r,t.comment&&o.setCommentData(t),o}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const n=is._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.color),i=Object.assign(super.serialize(t),{color:n,fontSize:f(this,jr),value:B(this,Sn,pB).call(this)});return this.addComment(i),t?(i.isCopy=!0,i):this.annotationElementId&&!B(this,Sn,gB).call(this,i)?null:(i.id=this.annotationElementId,i)}renderAnnotationElement(t){const n=super.renderAnnotationElement(t);if(!n)return null;const{style:i}=n;i.fontSize=`calc(${f(this,jr)}px * var(--total-scale-factor))`,i.color=this.color,n.replaceChildren();for(const r of f(this,zr).split(`
`)){const o=document.createElement("div");o.append(r?document.createTextNode(r):document.createElement("br")),n.append(o)}return t.updateEdited({rect:this.getPDFRect(),popup:this._uiManager.hasCommentManager()||this.hasEditedComment?this.comment:{text:f(this,zr)}}),n}resetAnnotationElement(t){super.resetAnnotationElement(t),t.resetEdited()}};zr=new WeakMap,Ib=new WeakMap,Zd=new WeakMap,jr=new WeakMap,Sn=new WeakSet,hB=function(t){const n=r=>{this.editorDiv.style.fontSize=`calc(${r}px * var(--total-scale-factor))`,this.translate(0,-(r-f(this,jr))*this.parentScale),x(this,jr,r),B(this,Sn,KS).call(this)},i=f(this,jr);this.addCommands({cmd:n.bind(this,t),undo:n.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:xt.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})},dB=function(t){const n=r=>{this.color=r,this.onUpdatedColor()},i=this.color;this.addCommands({cmd:n.bind(this,t),undo:n.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:xt.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})},fB=function(){var i;const t=[];this.editorDiv.normalize();let n=null;for(const r of this.editorDiv.childNodes)(n==null?void 0:n.nodeType)===Node.TEXT_NODE&&r.nodeName==="BR"||(t.push(B(i=Is,Cc,QS).call(i,r)),n=r);return t.join(`
`)},KS=function(){const[t,n]=this.parentDimensions;let i;if(this.isAttachedToDOM)i=this.div.getBoundingClientRect();else{const{currentLayer:r,div:o}=this,a=o.style.display,c=o.classList.contains("hidden");o.classList.remove("hidden"),o.style.display="hidden",r.div.append(this.div),i=o.getBoundingClientRect(),o.remove(),o.style.display=a,o.classList.toggle("hidden",c)}this.rotation%180===this.parentRotation%180?(this.width=i.width/t,this.height=i.height/n):(this.width=i.height/t,this.height=i.width/n),this.fixAndSetPosition()},Cc=new WeakSet,QS=function(t){return(t.nodeType===Node.TEXT_NODE?t.nodeValue:t.innerText).replaceAll(X_,"")},XS=function(){if(this.editorDiv.replaceChildren(),!!f(this,zr))for(const t of f(this,zr).split(`
`)){const n=document.createElement("div");n.append(t?document.createTextNode(t):document.createElement("br")),this.editorDiv.append(n)}},pB=function(){return f(this,zr).replaceAll(" "," ")},kA=function(t){return t.replaceAll(" "," ")},gB=function(t){const{value:n,fontSize:i,color:r,pageIndex:o}=this._initialData;return this.hasEditedComment||this._hasBeenMoved||t.value!==n||t.fontSize!==i||t.color.some((a,c)=>a!==r[c])||t.pageIndex!==o},D(Is,Cc),_e(Is,"_freeTextDefaultContent",""),_e(Is,"_internalPadding",0),_e(Is,"_defaultColor",null),_e(Is,"_defaultFontSize",10),_e(Is,"_type","freetext"),_e(Is,"_editorType",Ct.FREETEXT);let wA=Is;class Ze{toSVGPath(){es("Abstract method `toSVGPath` must be implemented.")}get box(){es("Abstract getter `box` must be implemented.")}serialize(e,t){es("Abstract method `serialize` must be implemented.")}static _rescale(e,t,n,i,r,o){o||(o=new Float32Array(e.length));for(let a=0,c=e.length;a<c;a+=2)o[a]=t+e[a]*i,o[a+1]=n+e[a+1]*r;return o}static _rescaleAndSwap(e,t,n,i,r,o){o||(o=new Float32Array(e.length));for(let a=0,c=e.length;a<c;a+=2)o[a]=t+e[a+1]*i,o[a+1]=n+e[a]*r;return o}static _translate(e,t,n,i){i||(i=new Float32Array(e.length));for(let r=0,o=e.length;r<o;r+=2)i[r]=t+e[r],i[r+1]=n+e[r+1];return i}static svgRound(e){return Math.round(e*1e4)}static _normalizePoint(e,t,n,i,r){switch(r){case 90:return[1-t/n,e/i];case 180:return[1-e/n,1-t/i];case 270:return[t/n,1-e/i];default:return[e/n,t/i]}}static createBezierPoints(e,t,n,i,r,o){return[(e+5*n)/6,(t+5*i)/6,(5*n+r)/6,(5*i+o)/6,(n+r)/2,(i+o)/2]}}_e(Ze,"PRECISION",1e-4);var Vr,la,xg,Ig,Ka,Ut,ef,tf,Rb,Lb,Rg,Lg,Hu,Pb,H0,U0,Mn,fv,mB,vB,yB,bB,_B,SB;const xl=class xl{constructor({x:e,y:t},n,i,r,o,a=0){D(this,Mn);D(this,Vr);D(this,la,[]);D(this,xg);D(this,Ig);D(this,Ka,[]);D(this,Ut,new Float32Array(18));D(this,ef);D(this,tf);D(this,Rb);D(this,Lb);D(this,Rg);D(this,Lg);D(this,Hu,[]);x(this,Vr,n),x(this,Lg,r*i),x(this,Ig,o),f(this,Ut).set([NaN,NaN,NaN,NaN,e,t],6),x(this,xg,a),x(this,Lb,f(xl,Pb)*i),x(this,Rb,f(xl,U0)*i),x(this,Rg,i),f(this,Hu).push(e,t)}isEmpty(){return isNaN(f(this,Ut)[8])}add({x:e,y:t}){var A;x(this,ef,e),x(this,tf,t);const[n,i,r,o]=f(this,Vr);let[a,c,l,u]=f(this,Ut).subarray(8,12);const h=e-l,d=t-u,p=Math.hypot(h,d);if(p<f(this,Rb))return!1;const m=p-f(this,Lb),v=m/p,g=v*h,y=v*d;let b=a,_=c;a=l,c=u,l+=g,u+=y,(A=f(this,Hu))==null||A.push(e,t);const w=-y/m,S=g/m,C=w*f(this,Lg),T=S*f(this,Lg);return f(this,Ut).set(f(this,Ut).subarray(2,8),0),f(this,Ut).set([l+C,u+T],4),f(this,Ut).set(f(this,Ut).subarray(14,18),12),f(this,Ut).set([l-C,u-T],16),isNaN(f(this,Ut)[6])?(f(this,Ka).length===0&&(f(this,Ut).set([a+C,c+T],2),f(this,Ka).push(NaN,NaN,NaN,NaN,(a+C-n)/r,(c+T-i)/o),f(this,Ut).set([a-C,c-T],14),f(this,la).push(NaN,NaN,NaN,NaN,(a-C-n)/r,(c-T-i)/o)),f(this,Ut).set([b,_,a,c,l,u],6),!this.isEmpty()):(f(this,Ut).set([b,_,a,c,l,u],6),Math.abs(Math.atan2(_-c,b-a)-Math.atan2(y,g))<Math.PI/2?([a,c,l,u]=f(this,Ut).subarray(2,6),f(this,Ka).push(NaN,NaN,NaN,NaN,((a+l)/2-n)/r,((c+u)/2-i)/o),[a,c,b,_]=f(this,Ut).subarray(14,18),f(this,la).push(NaN,NaN,NaN,NaN,((b+a)/2-n)/r,((_+c)/2-i)/o),!0):([b,_,a,c,l,u]=f(this,Ut).subarray(0,6),f(this,Ka).push(((b+5*a)/6-n)/r,((_+5*c)/6-i)/o,((5*a+l)/6-n)/r,((5*c+u)/6-i)/o,((a+l)/2-n)/r,((c+u)/2-i)/o),[l,u,a,c,b,_]=f(this,Ut).subarray(12,18),f(this,la).push(((b+5*a)/6-n)/r,((_+5*c)/6-i)/o,((5*a+l)/6-n)/r,((5*c+u)/6-i)/o,((a+l)/2-n)/r,((c+u)/2-i)/o),!0))}toSVGPath(){if(this.isEmpty())return"";const e=f(this,Ka),t=f(this,la);if(isNaN(f(this,Ut)[6])&&!this.isEmpty())return B(this,Mn,mB).call(this);const n=[];n.push(`M${e[4]} ${e[5]}`);for(let i=6;i<e.length;i+=6)isNaN(e[i])?n.push(`L${e[i+4]} ${e[i+5]}`):n.push(`C${e[i]} ${e[i+1]} ${e[i+2]} ${e[i+3]} ${e[i+4]} ${e[i+5]}`);B(this,Mn,yB).call(this,n);for(let i=t.length-6;i>=6;i-=6)isNaN(t[i])?n.push(`L${t[i+4]} ${t[i+5]}`):n.push(`C${t[i]} ${t[i+1]} ${t[i+2]} ${t[i+3]} ${t[i+4]} ${t[i+5]}`);return B(this,Mn,vB).call(this,n),n.join(" ")}newFreeDrawOutline(e,t,n,i,r,o){return new wB(e,t,n,i,r,o)}getOutlines(){var h;const e=f(this,Ka),t=f(this,la),n=f(this,Ut),[i,r,o,a]=f(this,Vr),c=new Float32Array((((h=f(this,Hu))==null?void 0:h.length)??0)+2);for(let d=0,p=c.length-2;d<p;d+=2)c[d]=(f(this,Hu)[d]-i)/o,c[d+1]=(f(this,Hu)[d+1]-r)/a;if(c[c.length-2]=(f(this,ef)-i)/o,c[c.length-1]=(f(this,tf)-r)/a,isNaN(n[6])&&!this.isEmpty())return B(this,Mn,bB).call(this,c);const l=new Float32Array(f(this,Ka).length+24+f(this,la).length);let u=e.length;for(let d=0;d<u;d+=2){if(isNaN(e[d])){l[d]=l[d+1]=NaN;continue}l[d]=e[d],l[d+1]=e[d+1]}u=B(this,Mn,SB).call(this,l,u);for(let d=t.length-6;d>=6;d-=6)for(let p=0;p<6;p+=2){if(isNaN(t[d+p])){l[u]=l[u+1]=NaN,u+=2;continue}l[u]=t[d+p],l[u+1]=t[d+p+1],u+=2}return B(this,Mn,_B).call(this,l,u),this.newFreeDrawOutline(l,c,f(this,Vr),f(this,Rg),f(this,xg),f(this,Ig))}};Vr=new WeakMap,la=new WeakMap,xg=new WeakMap,Ig=new WeakMap,Ka=new WeakMap,Ut=new WeakMap,ef=new WeakMap,tf=new WeakMap,Rb=new WeakMap,Lb=new WeakMap,Rg=new WeakMap,Lg=new WeakMap,Hu=new WeakMap,Pb=new WeakMap,H0=new WeakMap,U0=new WeakMap,Mn=new WeakSet,fv=function(){const e=f(this,Ut).subarray(4,6),t=f(this,Ut).subarray(16,18),[n,i,r,o]=f(this,Vr);return[(f(this,ef)+(e[0]-t[0])/2-n)/r,(f(this,tf)+(e[1]-t[1])/2-i)/o,(f(this,ef)+(t[0]-e[0])/2-n)/r,(f(this,tf)+(t[1]-e[1])/2-i)/o]},mB=function(){const[e,t,n,i]=f(this,Vr),[r,o,a,c]=B(this,Mn,fv).call(this);return`M${(f(this,Ut)[2]-e)/n} ${(f(this,Ut)[3]-t)/i} L${(f(this,Ut)[4]-e)/n} ${(f(this,Ut)[5]-t)/i} L${r} ${o} L${a} ${c} L${(f(this,Ut)[16]-e)/n} ${(f(this,Ut)[17]-t)/i} L${(f(this,Ut)[14]-e)/n} ${(f(this,Ut)[15]-t)/i} Z`},vB=function(e){const t=f(this,la);e.push(`L${t[4]} ${t[5]} Z`)},yB=function(e){const[t,n,i,r]=f(this,Vr),o=f(this,Ut).subarray(4,6),a=f(this,Ut).subarray(16,18),[c,l,u,h]=B(this,Mn,fv).call(this);e.push(`L${(o[0]-t)/i} ${(o[1]-n)/r} L${c} ${l} L${u} ${h} L${(a[0]-t)/i} ${(a[1]-n)/r}`)},bB=function(e){const t=f(this,Ut),[n,i,r,o]=f(this,Vr),[a,c,l,u]=B(this,Mn,fv).call(this),h=new Float32Array(36);return h.set([NaN,NaN,NaN,NaN,(t[2]-n)/r,(t[3]-i)/o,NaN,NaN,NaN,NaN,(t[4]-n)/r,(t[5]-i)/o,NaN,NaN,NaN,NaN,a,c,NaN,NaN,NaN,NaN,l,u,NaN,NaN,NaN,NaN,(t[16]-n)/r,(t[17]-i)/o,NaN,NaN,NaN,NaN,(t[14]-n)/r,(t[15]-i)/o],0),this.newFreeDrawOutline(h,e,f(this,Vr),f(this,Rg),f(this,xg),f(this,Ig))},_B=function(e,t){const n=f(this,la);return e.set([NaN,NaN,NaN,NaN,n[4],n[5]],t),t+=6},SB=function(e,t){const n=f(this,Ut).subarray(4,6),i=f(this,Ut).subarray(16,18),[r,o,a,c]=f(this,Vr),[l,u,h,d]=B(this,Mn,fv).call(this);return e.set([NaN,NaN,NaN,NaN,(n[0]-r)/a,(n[1]-o)/c,NaN,NaN,NaN,NaN,l,u,NaN,NaN,NaN,NaN,h,d,NaN,NaN,NaN,NaN,(i[0]-r)/a,(i[1]-o)/c],t),t+=24},D(xl,Pb,8),D(xl,H0,2),D(xl,U0,f(xl,Pb)+f(xl,H0));let g0=xl;var Pg,sf,rc,Ob,Gr,Db,un,W0,kB;class wB extends Ze{constructor(t,n,i,r,o,a){super();D(this,W0);D(this,Pg);D(this,sf,new Float32Array(4));D(this,rc);D(this,Ob);D(this,Gr);D(this,Db);D(this,un);x(this,un,t),x(this,Gr,n),x(this,Pg,i),x(this,Db,r),x(this,rc,o),x(this,Ob,a),this.firstPoint=[NaN,NaN],this.lastPoint=[NaN,NaN],B(this,W0,kB).call(this,a);const[c,l,u,h]=f(this,sf);for(let d=0,p=t.length;d<p;d+=2)t[d]=(t[d]-c)/u,t[d+1]=(t[d+1]-l)/h;for(let d=0,p=n.length;d<p;d+=2)n[d]=(n[d]-c)/u,n[d+1]=(n[d+1]-l)/h}toSVGPath(){const t=[`M${f(this,un)[4]} ${f(this,un)[5]}`];for(let n=6,i=f(this,un).length;n<i;n+=6){if(isNaN(f(this,un)[n])){t.push(`L${f(this,un)[n+4]} ${f(this,un)[n+5]}`);continue}t.push(`C${f(this,un)[n]} ${f(this,un)[n+1]} ${f(this,un)[n+2]} ${f(this,un)[n+3]} ${f(this,un)[n+4]} ${f(this,un)[n+5]}`)}return t.push("Z"),t.join(" ")}serialize([t,n,i,r],o){const a=i-t,c=r-n;let l,u;switch(o){case 0:l=Ze._rescale(f(this,un),t,r,a,-c),u=Ze._rescale(f(this,Gr),t,r,a,-c);break;case 90:l=Ze._rescaleAndSwap(f(this,un),t,n,a,c),u=Ze._rescaleAndSwap(f(this,Gr),t,n,a,c);break;case 180:l=Ze._rescale(f(this,un),i,n,-a,c),u=Ze._rescale(f(this,Gr),i,n,-a,c);break;case 270:l=Ze._rescaleAndSwap(f(this,un),i,r,-a,-c),u=Ze._rescaleAndSwap(f(this,Gr),i,r,-a,-c);break}return{outline:Array.from(l),points:[Array.from(u)]}}get box(){return f(this,sf)}newOutliner(t,n,i,r,o,a=0){return new g0(t,n,i,r,o,a)}getNewOutline(t,n){const[i,r,o,a]=f(this,sf),[c,l,u,h]=f(this,Pg),d=o*u,p=a*h,m=i*u+c,v=r*h+l,g=this.newOutliner({x:f(this,Gr)[0]*d+m,y:f(this,Gr)[1]*p+v},f(this,Pg),f(this,Db),t,f(this,Ob),n??f(this,rc));for(let y=2;y<f(this,Gr).length;y+=2)g.add({x:f(this,Gr)[y]*d+m,y:f(this,Gr)[y+1]*p+v});return g.getOutlines()}}Pg=new WeakMap,sf=new WeakMap,rc=new WeakMap,Ob=new WeakMap,Gr=new WeakMap,Db=new WeakMap,un=new WeakMap,W0=new WeakSet,kB=function(t){const n=f(this,un);let i=n[4],r=n[5];const o=[i,r,i,r];let a=i,c=r,l=i,u=r;const h=t?Math.max:Math.min,d=new Float32Array(4);for(let m=6,v=n.length;m<v;m+=6){const g=n[m+4],y=n[m+5];isNaN(n[m])?(Be.pointBoundingBox(g,y,o),c>y?(a=g,c=y):c===y&&(a=h(a,g)),u<y?(l=g,u=y):u===y&&(l=h(l,g))):(d.set(gc,0),Be.bezierBoundingBox(i,r,...n.slice(m,m+6),d),Be.rectBoundingBox(...d,o),c>d[1]?(a=d[0],c=d[1]):c===d[1]&&(a=h(a,d[0])),u<d[3]?(l=d[2],u=d[3]):u===d[3]&&(l=h(l,d[2]))),i=g,r=y}const p=f(this,sf);p[0]=o[0]-f(this,rc),p[1]=o[1]-f(this,rc),p[2]=o[2]-o[0]+2*f(this,rc),p[3]=o[3]-o[1]+2*f(this,rc),this.firstPoint=[a,c],this.lastPoint=[l,u]};var Nb,Bb,Fb,Uu,ca,Zi,CB,YS,TB,AB,TA;class CA{constructor(e,t=0,n=0,i=!0){D(this,Zi);D(this,Nb);D(this,Bb);D(this,Fb);D(this,Uu,[]);D(this,ca,[]);const r=gc.slice(),o=10**-4;for(const{x:v,y:g,width:y,height:b}of e){const _=Math.floor((v-t)/o)*o,w=Math.ceil((v+y+t)/o)*o,S=Math.floor((g-t)/o)*o,C=Math.ceil((g+b+t)/o)*o,T=[_,S,C,!0],k=[w,S,C,!1];f(this,Uu).push(T,k),Be.rectBoundingBox(_,S,w,C,r)}const a=r[2]-r[0]+2*n,c=r[3]-r[1]+2*n,l=r[0]-n,u=r[1]-n;let h=i?-1/0:1/0,d=1/0;const p=f(this,Uu).at(i?-1:-2),m=[p[0],p[2]];for(const v of f(this,Uu)){const[g,y,b,_]=v;!_&&i?y<d?(d=y,h=g):y===d&&(h=Math.max(h,g)):_&&!i&&(y<d?(d=y,h=g):y===d&&(h=Math.min(h,g))),v[0]=(g-l)/a,v[1]=(y-u)/c,v[2]=(b-u)/c}x(this,Nb,new Float32Array([l,u,a,c])),x(this,Bb,[h,d]),x(this,Fb,m)}getOutlines(){f(this,Uu).sort((t,n)=>t[0]-n[0]||t[1]-n[1]||t[2]-n[2]);const e=[];for(const t of f(this,Uu))t[3]?(e.push(...B(this,Zi,TA).call(this,t)),B(this,Zi,TB).call(this,t)):(B(this,Zi,AB).call(this,t),e.push(...B(this,Zi,TA).call(this,t)));return B(this,Zi,CB).call(this,e)}}Nb=new WeakMap,Bb=new WeakMap,Fb=new WeakMap,Uu=new WeakMap,ca=new WeakMap,Zi=new WeakSet,CB=function(e){const t=[],n=new Set;for(const o of e){const[a,c,l]=o;t.push([a,c,o],[a,l,o])}t.sort((o,a)=>o[1]-a[1]||o[0]-a[0]);for(let o=0,a=t.length;o<a;o+=2){const c=t[o][2],l=t[o+1][2];c.push(l),l.push(c),n.add(c),n.add(l)}const i=[];let r;for(;n.size>0;){const o=n.values().next().value;let[a,c,l,u,h]=o;n.delete(o);let d=a,p=c;for(r=[a,l],i.push(r);;){let m;if(n.has(u))m=u;else if(n.has(h))m=h;else break;n.delete(m),[a,c,l,u,h]=m,d!==a&&(r.push(d,p,a,p===c?c:l),d=a),p=p===c?l:c}r.push(d,p)}return new pse(i,f(this,Nb),f(this,Bb),f(this,Fb))},YS=function(e){const t=f(this,ca);let n=0,i=t.length-1;for(;n<=i;){const r=n+i>>1,o=t[r][0];if(o===e)return r;o<e?n=r+1:i=r-1}return i+1},TB=function([,e,t]){const n=B(this,Zi,YS).call(this,e);f(this,ca).splice(n,0,[e,t])},AB=function([,e,t]){const n=B(this,Zi,YS).call(this,e);for(let i=n;i<f(this,ca).length;i++){const[r,o]=f(this,ca)[i];if(r!==e)break;if(r===e&&o===t){f(this,ca).splice(i,1);return}}for(let i=n-1;i>=0;i--){const[r,o]=f(this,ca)[i];if(r!==e)break;if(r===e&&o===t){f(this,ca).splice(i,1);return}}},TA=function(e){const[t,n,i]=e,r=[[t,n,i]],o=B(this,Zi,YS).call(this,i);for(let a=0;a<o;a++){const[c,l]=f(this,ca)[a];for(let u=0,h=r.length;u<h;u++){const[,d,p]=r[u];if(!(l<=d||p<=c)){if(d>=c){if(p>l)r[u][1]=l;else{if(h===1)return[];r.splice(u,1),u--,h--}continue}r[u][2]=c,p>l&&r.push([t,l,p])}}}return r};var $b,Og;class pse extends Ze{constructor(t,n,i,r){super();D(this,$b);D(this,Og);x(this,Og,t),x(this,$b,n),this.firstPoint=i,this.lastPoint=r}toSVGPath(){const t=[];for(const n of f(this,Og)){let[i,r]=n;t.push(`M${i} ${r}`);for(let o=2;o<n.length;o+=2){const a=n[o],c=n[o+1];a===i?(t.push(`V${c}`),r=c):c===r&&(t.push(`H${a}`),i=a)}t.push("Z")}return t.join(" ")}serialize([t,n,i,r],o){const a=[],c=i-t,l=r-n;for(const u of f(this,Og)){const h=new Array(u.length);for(let d=0;d<u.length;d+=2)h[d]=t+u[d]*c,h[d+1]=r-u[d+1]*l;a.push(h)}return a}get box(){return f(this,$b)}get classNamesForOutlining(){return["highlightOutline"]}}$b=new WeakMap,Og=new WeakMap;class AA extends g0{newFreeDrawOutline(e,t,n,i,r,o){return new gse(e,t,n,i,r,o)}}class gse extends wB{newOutliner(e,t,n,i,r,o=0){return new AA(e,t,n,i,r,o)}}var Dg,Hb,oc,nf,Ub,dr,Wb,zb,rf,qr,Kr,li,Ng,Bg,Ci,Fg,To,jb,Ot,EA,JS,EB,MB,xB,MA,xh,Lo,gp,IB,ZS,ew,RB,LB,PB,OB,DB;const Zt=class Zt extends is{constructor(t){super({...t,name:"highlightEditor"});D(this,Ot);D(this,Dg,null);D(this,Hb,0);D(this,oc);D(this,nf,null);D(this,Ub,null);D(this,dr,null);D(this,Wb,null);D(this,zb,0);D(this,rf,null);D(this,qr,null);D(this,Kr,null);D(this,li,!1);D(this,Ng,null);D(this,Bg,null);D(this,Ci,null);D(this,Fg,"");D(this,To);D(this,jb,"");this.color=t.color||Zt._defaultColor,x(this,To,t.thickness||Zt._defaultThickness),this.opacity=t.opacity||Zt._defaultOpacity,x(this,oc,t.boxes||null),x(this,jb,t.methodOfCreation||""),x(this,Fg,t.text||""),this._isDraggable=!1,this.defaultL10nId="pdfjs-editor-highlight-editor",t.highlightId>-1?(x(this,li,!0),B(this,Ot,JS).call(this,t),B(this,Ot,xh).call(this)):f(this,oc)&&(x(this,Dg,t.anchorNode),x(this,Hb,t.anchorOffset),x(this,Wb,t.focusNode),x(this,zb,t.focusOffset),B(this,Ot,EA).call(this),B(this,Ot,xh).call(this),this.rotate(this.rotation)),this.annotationElementId||this._uiManager.a11yAlert(is._l10nAlert.highlight)}static get _keyboardManager(){const t=Zt.prototype;return Tt(this,"_keyboardManager",new r_([[["ArrowLeft","mac+ArrowLeft"],t._moveCaret,{args:[0]}],[["ArrowRight","mac+ArrowRight"],t._moveCaret,{args:[1]}],[["ArrowUp","mac+ArrowUp"],t._moveCaret,{args:[2]}],[["ArrowDown","mac+ArrowDown"],t._moveCaret,{args:[3]}]]))}get telemetryInitialData(){return{action:"added",type:f(this,li)?"free_highlight":"highlight",color:this._uiManager.getNonHCMColorName(this.color),thickness:f(this,To),methodOfCreation:f(this,jb)}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.getNonHCMColorName(this.color)}}static computeTelemetryFinalData(t){return{numberOfColors:t.get("color").size}}static initialize(t,n){var i;is.initialize(t,n),Zt._defaultColor||(Zt._defaultColor=((i=n.highlightColors)==null?void 0:i.values().next().value)||"#fff066")}static updateDefaultParams(t,n){switch(t){case xt.HIGHLIGHT_COLOR:Zt._defaultColor=n;break;case xt.HIGHLIGHT_THICKNESS:Zt._defaultThickness=n;break}}translateInPage(t,n){}get toolbarPosition(){return f(this,Bg)}get commentButtonPosition(){return f(this,Ng)}updateParams(t,n){switch(t){case xt.HIGHLIGHT_COLOR:B(this,Ot,EB).call(this,n);break;case xt.HIGHLIGHT_THICKNESS:B(this,Ot,MB).call(this,n);break}}static get defaultPropertiesToUpdate(){return[[xt.HIGHLIGHT_COLOR,Zt._defaultColor],[xt.HIGHLIGHT_THICKNESS,Zt._defaultThickness]]}get propertiesToUpdate(){return[[xt.HIGHLIGHT_COLOR,this.color||Zt._defaultColor],[xt.HIGHLIGHT_THICKNESS,f(this,To)||Zt._defaultThickness],[xt.HIGHLIGHT_FREE,f(this,li)]]}onUpdatedColor(){var t,n;(t=this.parent)==null||t.drawLayer.updateProperties(f(this,Kr),{root:{fill:this.color,"fill-opacity":this.opacity}}),(n=f(this,Ub))==null||n.updateColor(this.color),super.onUpdatedColor()}get toolbarButtons(){return this._uiManager.highlightColors?[["colorPicker",x(this,Ub,new d0({editor:this}))]]:super.toolbarButtons}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(B(this,Ot,ew).call(this))}getBaseTranslation(){return[0,0]}getRect(t,n){return super.getRect(t,n,B(this,Ot,ew).call(this))}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this),t&&this.div.focus()}remove(){B(this,Ot,MA).call(this),this._reportTelemetry({action:"deleted"}),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(B(this,Ot,xh).call(this),this.isAttachedToDOM||this.parent.add(this)))}setParent(t){var i;let n=!1;this.parent&&!t?B(this,Ot,MA).call(this):t&&(B(this,Ot,xh).call(this,t),n=!this.parent&&((i=this.div)==null?void 0:i.classList.contains("selectedEditor"))),super.setParent(t),this.show(this._isVisible),n&&this.select()}rotate(t){var r,o,a;const{drawLayer:n}=this.parent;let i;f(this,li)?(t=(t-this.rotation+360)%360,i=B(r=Zt,Lo,gp).call(r,f(this,qr).box,t)):i=B(o=Zt,Lo,gp).call(o,[this.x,this.y,this.width,this.height],t),n.updateProperties(f(this,Kr),{bbox:i,root:{"data-main-rotation":t}}),n.updateProperties(f(this,Ci),{bbox:B(a=Zt,Lo,gp).call(a,f(this,dr).box,t),root:{"data-main-rotation":t}})}render(){if(this.div)return this.div;const t=super.render();f(this,Fg)&&(t.setAttribute("aria-label",f(this,Fg)),t.setAttribute("role","mark")),f(this,li)?t.classList.add("free"):this.div.addEventListener("keydown",B(this,Ot,IB).bind(this),{signal:this._uiManager._signal});const n=x(this,rf,document.createElement("div"));return t.append(n),n.setAttribute("aria-hidden","true"),n.className="internal",n.style.clipPath=f(this,nf),this.setDims(),UD(this,f(this,rf),["pointerover","pointerleave"]),this.enableEditing(),t}pointerover(){var t;this.isSelected||(t=this.parent)==null||t.drawLayer.updateProperties(f(this,Ci),{rootClass:{hovered:!0}})}pointerleave(){var t;this.isSelected||(t=this.parent)==null||t.drawLayer.updateProperties(f(this,Ci),{rootClass:{hovered:!1}})}_moveCaret(t){switch(this.parent.unselect(this),t){case 0:case 2:B(this,Ot,ZS).call(this,!0);break;case 1:case 3:B(this,Ot,ZS).call(this,!1);break}}select(){var t;super.select(),f(this,Ci)&&((t=this.parent)==null||t.drawLayer.updateProperties(f(this,Ci),{rootClass:{hovered:!1,selected:!0}}))}unselect(){var t;super.unselect(),f(this,Ci)&&((t=this.parent)==null||t.drawLayer.updateProperties(f(this,Ci),{rootClass:{selected:!1}}),f(this,li)||B(this,Ot,ZS).call(this,!1))}get _mustFixPosition(){return!f(this,li)}show(t=this._isVisible){super.show(t),this.parent&&(this.parent.drawLayer.updateProperties(f(this,Kr),{rootClass:{hidden:!t}}),this.parent.drawLayer.updateProperties(f(this,Ci),{rootClass:{hidden:!t}}))}static startHighlighting(t,n,{target:i,x:r,y:o}){const{x:a,y:c,width:l,height:u}=i.getBoundingClientRect(),h=new AbortController,d=t.combinedSignal(h),p=m=>{h.abort(),B(this,Lo,OB).call(this,t,m)};window.addEventListener("blur",p,{signal:d}),window.addEventListener("pointerup",p,{signal:d}),window.addEventListener("pointerdown",js,{capture:!0,passive:!1,signal:d}),window.addEventListener("contextmenu",Ho,{signal:d}),i.addEventListener("pointermove",B(this,Lo,PB).bind(this,t),{signal:d}),this._freeHighlight=new AA({x:r,y:o},[a,c,l,u],t.scale,this._defaultThickness/2,n,.001),{id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=t.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:this._defaultColor,"fill-opacity":this._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:this._freeHighlight.toSVGPath()}},!0,!0)}static async deserialize(t,n,i){var g,y,b,_;let r=null;if(t instanceof cB){const{data:{quadPoints:w,rect:S,rotation:C,id:T,color:k,opacity:A,popupRef:M,richText:R,contentsObj:P,creationDate:L,modificationDate:z},parent:{page:{pageNumber:Q}}}=t;r=t={annotationType:Ct.HIGHLIGHT,color:Array.from(k),opacity:A,quadPoints:w,boxes:null,pageIndex:Q-1,rect:S.slice(0),rotation:C,annotationElementId:T,id:T,deleted:!1,popupRef:M,richText:R,comment:(P==null?void 0:P.str)||null,creationDate:L,modificationDate:z}}else if(t instanceof gM){const{data:{inkLists:w,rect:S,rotation:C,id:T,color:k,borderStyle:{rawWidth:A},popupRef:M,richText:R,contentsObj:P,creationDate:L,modificationDate:z},parent:{page:{pageNumber:Q}}}=t;r=t={annotationType:Ct.HIGHLIGHT,color:Array.from(k),thickness:A,inkLists:w,boxes:null,pageIndex:Q-1,rect:S.slice(0),rotation:C,annotationElementId:T,id:T,deleted:!1,popupRef:M,richText:R,comment:(P==null?void 0:P.str)||null,creationDate:L,modificationDate:z}}const{color:o,quadPoints:a,inkLists:c,outlines:l,opacity:u}=t,h=await super.deserialize(t,n,i);h.color=Be.makeHexColor(...o),h.opacity=u||1,c&&x(h,To,t.thickness),h._initialData=r,t.comment&&h.setCommentData(t);const[d,p]=h.pageDimensions,[m,v]=h.pageTranslation;if(a){const w=x(h,oc,[]);for(let S=0;S<a.length;S+=8)w.push({x:(a[S]-m)/d,y:1-(a[S+1]-v)/p,width:(a[S+2]-a[S])/d,height:(a[S+1]-a[S+5])/p});B(g=h,Ot,EA).call(g),B(y=h,Ot,xh).call(y),h.rotate(h.rotation)}else if(c||l){x(h,li,!0);const w=(c||l.points)[0],S={x:w[0]-m,y:p-(w[1]-v)},C=new AA(S,[0,0,d,p],1,f(h,To)/2,!0,.001);for(let A=0,M=w.length;A<M;A+=2)S.x=w[A]-m,S.y=p-(w[A+1]-v),C.add(S);const{id:T,clipPathId:k}=n.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:h.color,"fill-opacity":h._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:C.toSVGPath()}},!0,!0);B(b=h,Ot,JS).call(b,{highlightOutlines:C.getOutlines(),highlightId:T,clipPathId:k}),B(_=h,Ot,xh).call(_),h.rotate(h.parentRotation)}return h}serialize(t=!1){if(this.isEmpty()||t)return null;if(this.deleted)return this.serializeDeleted();const n=is._colorManager.convert(this._uiManager.getNonHCMColor(this.color)),i=super.serialize(t);return Object.assign(i,{color:n,opacity:this.opacity,thickness:f(this,To),quadPoints:B(this,Ot,RB).call(this),outlines:B(this,Ot,LB).call(this,i.rect)}),this.addComment(i),this.annotationElementId&&!B(this,Ot,DB).call(this,i)?null:(i.id=this.annotationElementId,i)}renderAnnotationElement(t){return this.deleted?(t.hide(),null):(t.updateEdited({rect:this.getPDFRect(),popup:this.comment}),null)}static canCreateNewEmptyEditor(){return!1}};Dg=new WeakMap,Hb=new WeakMap,oc=new WeakMap,nf=new WeakMap,Ub=new WeakMap,dr=new WeakMap,Wb=new WeakMap,zb=new WeakMap,rf=new WeakMap,qr=new WeakMap,Kr=new WeakMap,li=new WeakMap,Ng=new WeakMap,Bg=new WeakMap,Ci=new WeakMap,Fg=new WeakMap,To=new WeakMap,jb=new WeakMap,Ot=new WeakSet,EA=function(){const t=new CA(f(this,oc),.001);x(this,qr,t.getOutlines()),[this.x,this.y,this.width,this.height]=f(this,qr).box;const n=new CA(f(this,oc),.0025,.001,this._uiManager.direction==="ltr");x(this,dr,n.getOutlines());const{firstPoint:i}=f(this,qr);x(this,Ng,[(i[0]-this.x)/this.width,(i[1]-this.y)/this.height]);const{lastPoint:r}=f(this,dr);x(this,Bg,[(r[0]-this.x)/this.width,(r[1]-this.y)/this.height])},JS=function({highlightOutlines:t,highlightId:n,clipPathId:i}){var d,p;if(x(this,qr,t),x(this,dr,t.getNewOutline(f(this,To)/2+1.5,.0025)),n>=0)x(this,Kr,n),x(this,nf,i),this.parent.drawLayer.finalizeDraw(n,{bbox:t.box,path:{d:t.toSVGPath()}}),x(this,Ci,this.parent.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:!0},bbox:f(this,dr).box,path:{d:f(this,dr).toSVGPath()}},!0));else if(this.parent){const m=this.parent.viewport.rotation;this.parent.drawLayer.updateProperties(f(this,Kr),{bbox:B(d=Zt,Lo,gp).call(d,f(this,qr).box,(m-this.rotation+360)%360),path:{d:t.toSVGPath()}}),this.parent.drawLayer.updateProperties(f(this,Ci),{bbox:B(p=Zt,Lo,gp).call(p,f(this,dr).box,m),path:{d:f(this,dr).toSVGPath()}})}const[o,a,c,l]=t.box;switch(this.rotation){case 0:this.x=o,this.y=a,this.width=c,this.height=l;break;case 90:{const[m,v]=this.parentDimensions;this.x=a,this.y=1-o,this.width=c*v/m,this.height=l*m/v;break}case 180:this.x=1-o,this.y=1-a,this.width=c,this.height=l;break;case 270:{const[m,v]=this.parentDimensions;this.x=1-a,this.y=o,this.width=c*v/m,this.height=l*m/v;break}}const{firstPoint:u}=t;x(this,Ng,[(u[0]-o)/c,(u[1]-a)/l]);const{lastPoint:h}=f(this,dr);x(this,Bg,[(h[0]-o)/c,(h[1]-a)/l])},EB=function(t){const n=(o,a)=>{this.color=o,this.opacity=a,this.onUpdatedColor()},i=this.color,r=this.opacity;this.addCommands({cmd:n.bind(this,t,Zt._defaultOpacity),undo:n.bind(this,i,r),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:xt.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"color_changed",color:this._uiManager.getNonHCMColorName(t)},!0)},MB=function(t){const n=f(this,To),i=r=>{x(this,To,r),B(this,Ot,xB).call(this,r)};this.addCommands({cmd:i.bind(this,t),undo:i.bind(this,n),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:xt.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"thickness_changed",thickness:t},!0)},xB=function(t){f(this,li)&&(B(this,Ot,JS).call(this,{highlightOutlines:f(this,qr).getNewOutline(t/2)}),this.fixAndSetPosition(),this.setDims())},MA=function(){f(this,Kr)===null||!this.parent||(this.parent.drawLayer.remove(f(this,Kr)),x(this,Kr,null),this.parent.drawLayer.remove(f(this,Ci)),x(this,Ci,null))},xh=function(t=this.parent){f(this,Kr)===null&&({id:xs(this,Kr)._,clipPathId:xs(this,nf)._}=t.drawLayer.draw({bbox:f(this,qr).box,root:{viewBox:"0 0 1 1",fill:this.color,"fill-opacity":this.opacity},rootClass:{highlight:!0,free:f(this,li)},path:{d:f(this,qr).toSVGPath()}},!1,!0),x(this,Ci,t.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:f(this,li)},bbox:f(this,dr).box,path:{d:f(this,dr).toSVGPath()}},f(this,li))),f(this,rf)&&(f(this,rf).style.clipPath=f(this,nf)))},Lo=new WeakSet,gp=function([t,n,i,r],o){switch(o){case 90:return[1-n-r,t,r,i];case 180:return[1-t-i,1-n-r,i,r];case 270:return[n,1-t-i,r,i]}return[t,n,i,r]},IB=function(t){Zt._keyboardManager.exec(this,t)},ZS=function(t){if(!f(this,Dg))return;const n=window.getSelection();t?n.setPosition(f(this,Dg),f(this,Hb)):n.setPosition(f(this,Wb),f(this,zb))},ew=function(){return f(this,li)?this.rotation:0},RB=function(){if(f(this,li))return null;const[t,n]=this.pageDimensions,[i,r]=this.pageTranslation,o=f(this,oc),a=new Float32Array(o.length*8);let c=0;for(const{x:l,y:u,width:h,height:d}of o){const p=l*t+i,m=(1-u)*n+r;a[c]=a[c+4]=p,a[c+1]=a[c+3]=m,a[c+2]=a[c+6]=p+h*t,a[c+5]=a[c+7]=m-d*n,c+=8}return a},LB=function(t){return f(this,qr).serialize(t,B(this,Ot,ew).call(this))},PB=function(t,n){this._freeHighlight.add(n)&&t.drawLayer.updateProperties(this._freeHighlightId,{path:{d:this._freeHighlight.toSVGPath()}})},OB=function(t,n){this._freeHighlight.isEmpty()?t.drawLayer.remove(this._freeHighlightId):t.createAndAddNewEditor(n,!1,{highlightId:this._freeHighlightId,highlightOutlines:this._freeHighlight.getOutlines(),clipPathId:this._freeHighlightClipId,methodOfCreation:"main_toolbar"}),this._freeHighlightId=-1,this._freeHighlight=null,this._freeHighlightClipId=""},DB=function(t){const{color:n}=this._initialData;return this.hasEditedComment||t.color.some((i,r)=>i!==n[r])},D(Zt,Lo),_e(Zt,"_defaultColor",null),_e(Zt,"_defaultOpacity",1),_e(Zt,"_defaultThickness",12),_e(Zt,"_type","highlight"),_e(Zt,"_editorType",Ct.HIGHLIGHT),_e(Zt,"_freeHighlightId",-1),_e(Zt,"_freeHighlight",null),_e(Zt,"_freeHighlightClipId","");let m0=Zt;var of;class NB{constructor(){D(this,of,Object.create(null))}updateProperty(e,t){this[e]=t,this.updateSVGProperty(e,t)}updateProperties(e){if(e)for(const[t,n]of Object.entries(e))t.startsWith("_")||this.updateProperty(t,n)}updateSVGProperty(e,t){f(this,of)[e]=t}toSVGProperties(){const e=f(this,of);return x(this,of,Object.create(null)),{root:e}}reset(){x(this,of,Object.create(null))}updateAll(e=this){this.updateProperties(e)}clone(){es("Not implemented")}}of=new WeakMap;var ji,$g,zn,af,lf,Xt,xA,IA,RA,pv,BB,tw,gv,mp;const jt=class jt extends is{constructor(t){super(t);D(this,Xt);D(this,ji,null);D(this,$g);_e(this,"_colorPicker",null);_e(this,"_drawId",null);x(this,$g,t.mustBeCommitted||!1),this._addOutlines(t)}onUpdatedColor(){var t;(t=this._colorPicker)==null||t.update(this.color),super.onUpdatedColor()}onUpdatedOpacity(){var t,n;(n=(t=this._colorPicker)==null?void 0:t.updateOpacity)==null||n.call(t,this.opacity)}_addOutlines(t){t.drawOutlines&&(B(this,Xt,xA).call(this,t),B(this,Xt,pv).call(this))}static _mergeSVGProperties(t,n){const i=new Set(Object.keys(t));for(const[r,o]of Object.entries(n))i.has(r)?Object.assign(t[r],o):t[r]=o;return t}static getDefaultDrawingOptions(t){es("Not implemented")}static get typesMap(){es("Not implemented")}static get isDrawer(){return!0}static get supportMultipleDrawings(){return!1}static updateDefaultParams(t,n){const i=this.typesMap.get(t);i&&this._defaultDrawingOptions.updateProperty(i,n),this._currentParent&&(f(jt,zn).updateProperty(i,n),this._currentParent.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties()))}updateParams(t,n){const i=this.constructor.typesMap.get(t);i&&this._updateProperty(t,i,n)}static get defaultPropertiesToUpdate(){const t=[],n=this._defaultDrawingOptions;for(const[i,r]of this.typesMap)t.push([i,n[r]]);return t}get propertiesToUpdate(){const t=[],{_drawingOptions:n}=this;for(const[i,r]of this.constructor.typesMap)t.push([i,n[r]]);return t}_updateProperty(t,n,i){const r=this._drawingOptions,o=r[n],a=c=>{var u;r.updateProperty(n,c);const l=f(this,ji).updateProperty(n,c);l&&B(this,Xt,gv).call(this,l),(u=this.parent)==null||u.drawLayer.updateProperties(this._drawId,r.toSVGProperties()),t===this.colorType?this.onUpdatedColor():t===this.opacityType&&this.onUpdatedOpacity()};this.addCommands({cmd:a.bind(this,i),undo:a.bind(this,o),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:t,overwriteIfSameType:!0,keepUndo:!0})}_updateColorAndOpacity(t,n){const i=this.constructor.typesMap.get(this.colorType),r=this.constructor.typesMap.get(this.opacityType),o=this._drawingOptions,a=o[i],c=o[r],l=(u,h)=>{var d;o.updateProperty(i,u),o.updateProperty(r,h),f(this,ji).updateProperty(i,u),f(this,ji).updateProperty(r,h),(d=this.parent)==null||d.drawLayer.updateProperties(this._drawId,o.toSVGProperties()),this.onUpdatedColor(),this.onUpdatedOpacity()};this.addCommands({cmd:l.bind(this,t,n),undo:l.bind(this,a,c),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:xt.INK_COLOR_AND_OPACITY,overwriteIfSameType:!0,keepUndo:!0})}_onResizing(){var t;(t=this.parent)==null||t.drawLayer.updateProperties(this._drawId,jt._mergeSVGProperties(f(this,ji).getPathResizingSVGProperties(B(this,Xt,tw).call(this)),{bbox:B(this,Xt,mp).call(this)}))}_onResized(){var t;(t=this.parent)==null||t.drawLayer.updateProperties(this._drawId,jt._mergeSVGProperties(f(this,ji).getPathResizedSVGProperties(B(this,Xt,tw).call(this)),{bbox:B(this,Xt,mp).call(this)}))}_onTranslating(t,n){var i;(i=this.parent)==null||i.drawLayer.updateProperties(this._drawId,{bbox:B(this,Xt,mp).call(this)})}_onTranslated(){var t;(t=this.parent)==null||t.drawLayer.updateProperties(this._drawId,jt._mergeSVGProperties(f(this,ji).getPathTranslatedSVGProperties(B(this,Xt,tw).call(this),this.parentDimensions),{bbox:B(this,Xt,mp).call(this)}))}_onStartDragging(){var t;(t=this.parent)==null||t.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!0}})}_onStopDragging(){var t;(t=this.parent)==null||t.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!1}})}commit(){super.commit(),this.disableEditMode(),this.disableEditing()}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}getBaseTranslation(){return[0,0]}get isResizable(){return!0}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this),this._isDraggable=!0,f(this,$g)&&(x(this,$g,!1),this.commit(),this.parent.setSelected(this),t&&this.isOnScreen&&this.div.focus())}remove(){B(this,Xt,RA).call(this),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(B(this,Xt,pv).call(this),B(this,Xt,gv).call(this,f(this,ji).box),this.isAttachedToDOM||this.parent.add(this)))}setParent(t){var i;let n=!1;this.parent&&!t?(this._uiManager.removeShouldRescale(this),B(this,Xt,RA).call(this)):t&&(this._uiManager.addShouldRescale(this),B(this,Xt,pv).call(this,t),n=!this.parent&&((i=this.div)==null?void 0:i.classList.contains("selectedEditor"))),super.setParent(t),n&&this.select()}rotate(){this.parent&&this.parent.drawLayer.updateProperties(this._drawId,jt._mergeSVGProperties({bbox:B(this,Xt,mp).call(this)},f(this,ji).updateRotation((this.parentRotation-this.rotation+360)%360)))}onScaleChanging(){this.parent&&B(this,Xt,gv).call(this,f(this,ji).updateParentDimensions(this.parentDimensions,this.parent.scale))}static onScaleChangingWhenDrawing(){}render(){if(this.div)return this.div;let t,n;this._isCopy&&(t=this.x,n=this.y);const i=super.render();i.classList.add("draw");const r=document.createElement("div");return i.append(r),r.setAttribute("aria-hidden","true"),r.className="internal",this.setDims(),this._uiManager.addShouldRescale(this),this.disableEditing(),this._isCopy&&this._moveAfterPaste(t,n),i}static createDrawerInstance(t,n,i,r,o){es("Not implemented")}static startDrawing(t,n,i,r){var g;const{target:o,offsetX:a,offsetY:c,pointerId:l,pointerType:u}=r;if(Si.isInitializedAndDifferentPointerType(u))return;const{viewport:{rotation:h}}=t,{width:d,height:p}=o.getBoundingClientRect(),m=x(jt,af,new AbortController),v=t.combinedSignal(m);if(Si.setPointer(u,l),window.addEventListener("pointerup",y=>{Si.isSamePointerIdOrRemove(y.pointerId)&&this._endDraw(y)},{signal:v}),window.addEventListener("pointercancel",y=>{Si.isSamePointerIdOrRemove(y.pointerId)&&this._currentParent.endDrawingSession()},{signal:v}),window.addEventListener("pointerdown",y=>{Si.isSamePointerType(y.pointerType)&&(Si.initializeAndAddPointerId(y.pointerId),f(jt,zn).isCancellable()&&(f(jt,zn).removeLastElement(),f(jt,zn).isEmpty()?this._currentParent.endDrawingSession(!0):this._endDraw(null)))},{capture:!0,passive:!1,signal:v}),window.addEventListener("contextmenu",Ho,{signal:v}),o.addEventListener("pointermove",this._drawMove.bind(this),{signal:v}),o.addEventListener("touchmove",y=>{Si.isSameTimeStamp(y.timeStamp)&&js(y)},{signal:v}),t.toggleDrawing(),(g=n._editorUndoBar)==null||g.hide(),f(jt,zn)){t.drawLayer.updateProperties(this._currentDrawId,f(jt,zn).startNew(a,c,d,p,h));return}n.updateUIForDefaultProperties(this),x(jt,zn,this.createDrawerInstance(a,c,d,p,h)),x(jt,lf,this.getDefaultDrawingOptions()),this._currentParent=t,{id:this._currentDrawId}=t.drawLayer.draw(this._mergeSVGProperties(f(jt,lf).toSVGProperties(),f(jt,zn).defaultSVGProperties),!0,!1)}static _drawMove(t){if(Si.isSameTimeStamp(t.timeStamp),!f(jt,zn))return;const{offsetX:n,offsetY:i,pointerId:r}=t;if(Si.isSamePointerId(r)){if(Si.isUsingMultiplePointers()){this._endDraw(t);return}this._currentParent.drawLayer.updateProperties(this._currentDrawId,f(jt,zn).add(n,i)),Si.setTimeStamp(t.timeStamp),js(t)}}static _cleanup(t){t&&(this._currentDrawId=-1,this._currentParent=null,x(jt,zn,null),x(jt,lf,null),Si.clearTimeStamp()),f(jt,af)&&(f(jt,af).abort(),x(jt,af,null),Si.clearPointerIds())}static _endDraw(t){const n=this._currentParent;if(n){if(n.toggleDrawing(!0),this._cleanup(!1),(t==null?void 0:t.target)===n.div&&n.drawLayer.updateProperties(this._currentDrawId,f(jt,zn).end(t.offsetX,t.offsetY)),this.supportMultipleDrawings){const i=f(jt,zn),r=this._currentDrawId,o=i.getLastElement();n.addCommands({cmd:()=>{n.drawLayer.updateProperties(r,i.setLastElement(o))},undo:()=>{n.drawLayer.updateProperties(r,i.removeLastElement())},mustExec:!1,type:xt.DRAW_STEP});return}this.endDrawing(!1)}}static endDrawing(t){const n=this._currentParent;if(!n)return null;if(n.toggleDrawing(!0),n.cleanUndoStack(xt.DRAW_STEP),!f(jt,zn).isEmpty()){const{pageDimensions:[i,r],scale:o}=n,a=n.createAndAddNewEditor({offsetX:0,offsetY:0},!1,{drawId:this._currentDrawId,drawOutlines:f(jt,zn).getOutlines(i*o,r*o,o,this._INNER_MARGIN),drawingOptions:f(jt,lf),mustBeCommitted:!t});return this._cleanup(!0),a}return n.drawLayer.remove(this._currentDrawId),this._cleanup(!0),null}createDrawingOptions(t){}static deserializeDraw(t,n,i,r,o,a){es("Not implemented")}static async deserialize(t,n,i){var h,d;const{rawDims:{pageWidth:r,pageHeight:o,pageX:a,pageY:c}}=n.viewport,l=this.deserializeDraw(a,c,r,o,this._INNER_MARGIN,t),u=await super.deserialize(t,n,i);return u.createDrawingOptions(t),B(h=u,Xt,xA).call(h,{drawOutlines:l}),B(d=u,Xt,pv).call(d),u.onScaleChanging(),u.rotate(),u}serializeDraw(t){const[n,i]=this.pageTranslation,[r,o]=this.pageDimensions;return f(this,ji).serialize([n,i,r,o],t)}renderAnnotationElement(t){return t.updateEdited({rect:this.getPDFRect()}),null}static canCreateNewEmptyEditor(){return!1}};ji=new WeakMap,$g=new WeakMap,zn=new WeakMap,af=new WeakMap,lf=new WeakMap,Xt=new WeakSet,xA=function({drawOutlines:t,drawId:n,drawingOptions:i}){x(this,ji,t),this._drawingOptions||(this._drawingOptions=i),this.annotationElementId||this._uiManager.a11yAlert(is._l10nAlert[this.editorType]),n>=0?(this._drawId=n,this.parent.drawLayer.finalizeDraw(n,t.defaultProperties)):this._drawId=B(this,Xt,IA).call(this,t,this.parent),B(this,Xt,gv).call(this,t.box)},IA=function(t,n){const{id:i}=n.drawLayer.draw(jt._mergeSVGProperties(this._drawingOptions.toSVGProperties(),t.defaultSVGProperties),!1,!1);return i},RA=function(){this._drawId===null||!this.parent||(this.parent.drawLayer.remove(this._drawId),this._drawId=null,this._drawingOptions.reset())},pv=function(t=this.parent){if(!(this._drawId!==null&&this.parent===t)){if(this._drawId!==null){this.parent.drawLayer.updateParent(this._drawId,t.drawLayer);return}this._drawingOptions.updateAll(),this._drawId=B(this,Xt,IA).call(this,f(this,ji),t)}},BB=function([t,n,i,r]){const{parentDimensions:[o,a],rotation:c}=this;switch(c){case 90:return[n,1-t,i*(a/o),r*(o/a)];case 180:return[1-t,1-n,i,r];case 270:return[1-n,t,i*(a/o),r*(o/a)];default:return[t,n,i,r]}},tw=function(){const{x:t,y:n,width:i,height:r,parentDimensions:[o,a],rotation:c}=this;switch(c){case 90:return[1-n,t,i*(o/a),r*(a/o)];case 180:return[1-t,1-n,i,r];case 270:return[n,1-t,i*(o/a),r*(a/o)];default:return[t,n,i,r]}},gv=function(t){[this.x,this.y,this.width,this.height]=B(this,Xt,BB).call(this,t),this.div&&(this.fixAndSetPosition(),this.setDims()),this._onResized()},mp=function(){const{x:t,y:n,width:i,height:r,rotation:o,parentRotation:a,parentDimensions:[c,l]}=this;switch((o*4+a)/90){case 1:return[1-n-r,t,r,i];case 2:return[1-t-i,1-n-r,i,r];case 3:return[n,1-t-i,r,i];case 4:return[t,n-i*(c/l),r*(l/c),i*(c/l)];case 5:return[1-n,t,i*(c/l),r*(l/c)];case 6:return[1-t-r*(l/c),1-n,r*(l/c),i*(c/l)];case 7:return[n-i*(c/l),1-t-r*(l/c),i*(c/l),r*(l/c)];case 8:return[t-i,n-r,i,r];case 9:return[1-n,t-i,r,i];case 10:return[1-t,1-n,i,r];case 11:return[n-r,1-t,r,i];case 12:return[t-r*(l/c),n,r*(l/c),i*(c/l)];case 13:return[1-n-i*(c/l),t-r*(l/c),i*(c/l),r*(l/c)];case 14:return[1-t,1-n-i*(c/l),r*(l/c),i*(c/l)];case 15:return[n,1-t,i*(c/l),r*(l/c)];default:return[t,n,i,r]}},_e(jt,"_currentDrawId",-1),_e(jt,"_currentParent",null),D(jt,zn,null),D(jt,af,null),D(jt,lf,null),_e(jt,"_INNER_MARGIN",3);let v0=jt;var Qa,jn,Vn,cf,Hg,Vi,ci,Ao,uf,hf,df,Ug,sw;class mse{constructor(e,t,n,i,r,o){D(this,Ug);D(this,Qa,new Float64Array(6));D(this,jn);D(this,Vn);D(this,cf);D(this,Hg);D(this,Vi);D(this,ci,"");D(this,Ao,0);D(this,uf,new o_);D(this,hf);D(this,df);x(this,hf,n),x(this,df,i),x(this,cf,r),x(this,Hg,o),[e,t]=B(this,Ug,sw).call(this,e,t);const a=x(this,jn,[NaN,NaN,NaN,NaN,e,t]);x(this,Vi,[e,t]),x(this,Vn,[{line:a,points:f(this,Vi)}]),f(this,Qa).set(a,0)}updateProperty(e,t){e==="stroke-width"&&x(this,Hg,t)}isEmpty(){return!f(this,Vn)||f(this,Vn).length===0}isCancellable(){return f(this,Vi).length<=10}add(e,t){[e,t]=B(this,Ug,sw).call(this,e,t);const[n,i,r,o]=f(this,Qa).subarray(2,6),a=e-r,c=t-o;return Math.hypot(f(this,hf)*a,f(this,df)*c)<=2?null:(f(this,Vi).push(e,t),isNaN(n)?(f(this,Qa).set([r,o,e,t],2),f(this,jn).push(NaN,NaN,NaN,NaN,e,t),{path:{d:this.toSVGPath()}}):(isNaN(f(this,Qa)[0])&&f(this,jn).splice(6,6),f(this,Qa).set([n,i,r,o,e,t],0),f(this,jn).push(...Ze.createBezierPoints(n,i,r,o,e,t)),{path:{d:this.toSVGPath()}}))}end(e,t){const n=this.add(e,t);return n||(f(this,Vi).length===2?{path:{d:this.toSVGPath()}}:null)}startNew(e,t,n,i,r){x(this,hf,n),x(this,df,i),x(this,cf,r),[e,t]=B(this,Ug,sw).call(this,e,t);const o=x(this,jn,[NaN,NaN,NaN,NaN,e,t]);x(this,Vi,[e,t]);const a=f(this,Vn).at(-1);return a&&(a.line=new Float32Array(a.line),a.points=new Float32Array(a.points)),f(this,Vn).push({line:o,points:f(this,Vi)}),f(this,Qa).set(o,0),x(this,Ao,0),this.toSVGPath(),null}getLastElement(){return f(this,Vn).at(-1)}setLastElement(e){return f(this,Vn)?(f(this,Vn).push(e),x(this,jn,e.line),x(this,Vi,e.points),x(this,Ao,0),{path:{d:this.toSVGPath()}}):f(this,uf).setLastElement(e)}removeLastElement(){if(!f(this,Vn))return f(this,uf).removeLastElement();f(this,Vn).pop(),x(this,ci,"");for(let e=0,t=f(this,Vn).length;e<t;e++){const{line:n,points:i}=f(this,Vn)[e];x(this,jn,n),x(this,Vi,i),x(this,Ao,0),this.toSVGPath()}return{path:{d:f(this,ci)}}}toSVGPath(){const e=Ze.svgRound(f(this,jn)[4]),t=Ze.svgRound(f(this,jn)[5]);if(f(this,Vi).length===2)return x(this,ci,`${f(this,ci)} M ${e} ${t} Z`),f(this,ci);if(f(this,Vi).length<=6){const i=f(this,ci).lastIndexOf("M");x(this,ci,`${f(this,ci).slice(0,i)} M ${e} ${t}`),x(this,Ao,6)}if(f(this,Vi).length===4){const i=Ze.svgRound(f(this,jn)[10]),r=Ze.svgRound(f(this,jn)[11]);return x(this,ci,`${f(this,ci)} L ${i} ${r}`),x(this,Ao,12),f(this,ci)}const n=[];f(this,Ao)===0&&(n.push(`M ${e} ${t}`),x(this,Ao,6));for(let i=f(this,Ao),r=f(this,jn).length;i<r;i+=6){const[o,a,c,l,u,h]=f(this,jn).slice(i,i+6).map(Ze.svgRound);n.push(`C${o} ${a} ${c} ${l} ${u} ${h}`)}return x(this,ci,f(this,ci)+n.join(" ")),x(this,Ao,f(this,jn).length),f(this,ci)}getOutlines(e,t,n,i){const r=f(this,Vn).at(-1);return r.line=new Float32Array(r.line),r.points=new Float32Array(r.points),f(this,uf).build(f(this,Vn),e,t,n,f(this,cf),f(this,Hg),i),x(this,Qa,null),x(this,jn,null),x(this,Vn,null),x(this,ci,null),f(this,uf)}get defaultSVGProperties(){return{root:{viewBox:"0 0 10000 10000"},rootClass:{draw:!0},bbox:[0,0,1,1]}}}Qa=new WeakMap,jn=new WeakMap,Vn=new WeakMap,cf=new WeakMap,Hg=new WeakMap,Vi=new WeakMap,ci=new WeakMap,Ao=new WeakMap,uf=new WeakMap,hf=new WeakMap,df=new WeakMap,Ug=new WeakSet,sw=function(e,t){return Ze._normalizePoint(e,t,f(this,hf),f(this,df),f(this,cf))};var Gi,Vb,Gb,Qr,Xa,Ya,Wg,zg,ff,di,Al,FB,$B,HB;class o_ extends Ze{constructor(){super(...arguments);D(this,di);D(this,Gi);D(this,Vb,0);D(this,Gb);D(this,Qr);D(this,Xa);D(this,Ya);D(this,Wg);D(this,zg);D(this,ff)}build(t,n,i,r,o,a,c){x(this,Xa,n),x(this,Ya,i),x(this,Wg,r),x(this,zg,o),x(this,ff,a),x(this,Gb,c??0),x(this,Qr,t),B(this,di,$B).call(this)}get thickness(){return f(this,ff)}setLastElement(t){return f(this,Qr).push(t),{path:{d:this.toSVGPath()}}}removeLastElement(){return f(this,Qr).pop(),{path:{d:this.toSVGPath()}}}toSVGPath(){const t=[];for(const{line:n}of f(this,Qr)){if(t.push(`M${Ze.svgRound(n[4])} ${Ze.svgRound(n[5])}`),n.length===6){t.push("Z");continue}if(n.length===12&&isNaN(n[6])){t.push(`L${Ze.svgRound(n[10])} ${Ze.svgRound(n[11])}`);continue}for(let i=6,r=n.length;i<r;i+=6){const[o,a,c,l,u,h]=n.subarray(i,i+6).map(Ze.svgRound);t.push(`C${o} ${a} ${c} ${l} ${u} ${h}`)}}return t.join("")}serialize([t,n,i,r],o){const a=[],c=[],[l,u,h,d]=B(this,di,FB).call(this);let p,m,v,g,y,b,_,w,S;switch(f(this,zg)){case 0:S=Ze._rescale,p=t,m=n+r,v=i,g=-r,y=t+l*i,b=n+(1-u-d)*r,_=t+(l+h)*i,w=n+(1-u)*r;break;case 90:S=Ze._rescaleAndSwap,p=t,m=n,v=i,g=r,y=t+u*i,b=n+l*r,_=t+(u+d)*i,w=n+(l+h)*r;break;case 180:S=Ze._rescale,p=t+i,m=n,v=-i,g=r,y=t+(1-l-h)*i,b=n+u*r,_=t+(1-l)*i,w=n+(u+d)*r;break;case 270:S=Ze._rescaleAndSwap,p=t+i,m=n+r,v=-i,g=-r,y=t+(1-u-d)*i,b=n+(1-l-h)*r,_=t+(1-u)*i,w=n+(1-l)*r;break}for(const{line:C,points:T}of f(this,Qr))a.push(S(C,p,m,v,g,o?new Array(C.length):null)),c.push(S(T,p,m,v,g,o?new Array(T.length):null));return{lines:a,points:c,rect:[y,b,_,w]}}static deserialize(t,n,i,r,o,{paths:{lines:a,points:c},rotation:l,thickness:u}){const h=[];let d,p,m,v,g;switch(l){case 0:g=Ze._rescale,d=-t/i,p=n/r+1,m=1/i,v=-1/r;break;case 90:g=Ze._rescaleAndSwap,d=-n/r,p=-t/i,m=1/r,v=1/i;break;case 180:g=Ze._rescale,d=t/i+1,p=-n/r,m=-1/i,v=1/r;break;case 270:g=Ze._rescaleAndSwap,d=n/r+1,p=t/i+1,m=-1/r,v=-1/i;break}if(!a){a=[];for(const b of c){const _=b.length;if(_===2){a.push(new Float32Array([NaN,NaN,NaN,NaN,b[0],b[1]]));continue}if(_===4){a.push(new Float32Array([NaN,NaN,NaN,NaN,b[0],b[1],NaN,NaN,NaN,NaN,b[2],b[3]]));continue}const w=new Float32Array(3*(_-2));a.push(w);let[S,C,T,k]=b.subarray(0,4);w.set([NaN,NaN,NaN,NaN,S,C],0);for(let A=4;A<_;A+=2){const M=b[A],R=b[A+1];w.set(Ze.createBezierPoints(S,C,T,k,M,R),(A-2)*3),[S,C,T,k]=[T,k,M,R]}}}for(let b=0,_=a.length;b<_;b++)h.push({line:g(a[b].map(w=>w??NaN),d,p,m,v),points:g(c[b].map(w=>w??NaN),d,p,m,v)});const y=new this.prototype.constructor;return y.build(h,i,r,1,l,u,o),y}get box(){return f(this,Gi)}updateProperty(t,n){return t==="stroke-width"?B(this,di,HB).call(this,n):null}updateParentDimensions([t,n],i){const[r,o]=B(this,di,Al).call(this);x(this,Xa,t),x(this,Ya,n),x(this,Wg,i);const[a,c]=B(this,di,Al).call(this),l=a-r,u=c-o,h=f(this,Gi);return h[0]-=l,h[1]-=u,h[2]+=2*l,h[3]+=2*u,h}updateRotation(t){return x(this,Vb,t),{path:{transform:this.rotationTransform}}}get viewBox(){return f(this,Gi).map(Ze.svgRound).join(" ")}get defaultProperties(){const[t,n]=f(this,Gi);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${Ze.svgRound(t)} ${Ze.svgRound(n)}`}}}get rotationTransform(){const[,,t,n]=f(this,Gi);let i=0,r=0,o=0,a=0,c=0,l=0;switch(f(this,Vb)){case 90:r=n/t,o=-t/n,c=t;break;case 180:i=-1,a=-1,c=t,l=n;break;case 270:r=-n/t,o=t/n,l=n;break;default:return""}return`matrix(${i} ${r} ${o} ${a} ${Ze.svgRound(c)} ${Ze.svgRound(l)})`}getPathResizingSVGProperties([t,n,i,r]){const[o,a]=B(this,di,Al).call(this),[c,l,u,h]=f(this,Gi);if(Math.abs(u-o)<=Ze.PRECISION||Math.abs(h-a)<=Ze.PRECISION){const g=t+i/2-(c+u/2),y=n+r/2-(l+h/2);return{path:{"transform-origin":`${Ze.svgRound(t)} ${Ze.svgRound(n)}`,transform:`${this.rotationTransform} translate(${g} ${y})`}}}const d=(i-2*o)/(u-2*o),p=(r-2*a)/(h-2*a),m=u/i,v=h/r;return{path:{"transform-origin":`${Ze.svgRound(c)} ${Ze.svgRound(l)}`,transform:`${this.rotationTransform} scale(${m} ${v}) translate(${Ze.svgRound(o)} ${Ze.svgRound(a)}) scale(${d} ${p}) translate(${Ze.svgRound(-o)} ${Ze.svgRound(-a)})`}}}getPathResizedSVGProperties([t,n,i,r]){const[o,a]=B(this,di,Al).call(this),c=f(this,Gi),[l,u,h,d]=c;if(c[0]=t,c[1]=n,c[2]=i,c[3]=r,Math.abs(h-o)<=Ze.PRECISION||Math.abs(d-a)<=Ze.PRECISION){const y=t+i/2-(l+h/2),b=n+r/2-(u+d/2);for(const{line:_,points:w}of f(this,Qr))Ze._translate(_,y,b,_),Ze._translate(w,y,b,w);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${Ze.svgRound(t)} ${Ze.svgRound(n)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}const p=(i-2*o)/(h-2*o),m=(r-2*a)/(d-2*a),v=-p*(l+o)+t+o,g=-m*(u+a)+n+a;if(p!==1||m!==1||v!==0||g!==0)for(const{line:y,points:b}of f(this,Qr))Ze._rescale(y,v,g,p,m,y),Ze._rescale(b,v,g,p,m,b);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${Ze.svgRound(t)} ${Ze.svgRound(n)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}getPathTranslatedSVGProperties([t,n],i){const[r,o]=i,a=f(this,Gi),c=t-a[0],l=n-a[1];if(f(this,Xa)===r&&f(this,Ya)===o)for(const{line:u,points:h}of f(this,Qr))Ze._translate(u,c,l,u),Ze._translate(h,c,l,h);else{const u=f(this,Xa)/r,h=f(this,Ya)/o;x(this,Xa,r),x(this,Ya,o);for(const{line:d,points:p}of f(this,Qr))Ze._rescale(d,c,l,u,h,d),Ze._rescale(p,c,l,u,h,p);a[2]*=u,a[3]*=h}return a[0]=t,a[1]=n,{root:{viewBox:this.viewBox},path:{d:this.toSVGPath(),"transform-origin":`${Ze.svgRound(t)} ${Ze.svgRound(n)}`}}}get defaultSVGProperties(){const t=f(this,Gi);return{root:{viewBox:this.viewBox},rootClass:{draw:!0},path:{d:this.toSVGPath(),"transform-origin":`${Ze.svgRound(t[0])} ${Ze.svgRound(t[1])}`,transform:this.rotationTransform||null},bbox:t}}}Gi=new WeakMap,Vb=new WeakMap,Gb=new WeakMap,Qr=new WeakMap,Xa=new WeakMap,Ya=new WeakMap,Wg=new WeakMap,zg=new WeakMap,ff=new WeakMap,di=new WeakSet,Al=function(t=f(this,ff)){const n=f(this,Gb)+t/2*f(this,Wg);return f(this,zg)%180===0?[n/f(this,Xa),n/f(this,Ya)]:[n/f(this,Ya),n/f(this,Xa)]},FB=function(){const[t,n,i,r]=f(this,Gi),[o,a]=B(this,di,Al).call(this,0);return[t+o,n+a,i-2*o,r-2*a]},$B=function(){const t=x(this,Gi,Wh.slice());for(const{line:r}of f(this,Qr)){if(r.length<=12){for(let c=4,l=r.length;c<l;c+=6)Be.pointBoundingBox(r[c],r[c+1],t);continue}let o=r[4],a=r[5];for(let c=6,l=r.length;c<l;c+=6){const[u,h,d,p,m,v]=r.subarray(c,c+6);Be.bezierBoundingBox(o,a,u,h,d,p,m,v,t),o=m,a=v}}const[n,i]=B(this,di,Al).call(this);t[0]=Ns(t[0]-n,0,1),t[1]=Ns(t[1]-i,0,1),t[2]=Ns(t[2]+n,0,1),t[3]=Ns(t[3]+i,0,1),t[2]-=t[0],t[3]-=t[1]},HB=function(t){const[n,i]=B(this,di,Al).call(this);x(this,ff,t);const[r,o]=B(this,di,Al).call(this),[a,c]=[r-n,o-i],l=f(this,Gi);return l[0]-=a,l[1]-=c,l[2]+=2*a,l[3]+=2*c,l};class kk extends NB{constructor(e){super(),this._viewParameters=e,super.updateProperties({fill:"none",stroke:is._defaultLineColor,"stroke-opacity":1,"stroke-width":1,"stroke-linecap":"round","stroke-linejoin":"round","stroke-miterlimit":10})}updateSVGProperty(e,t){e==="stroke-width"&&(t??(t=this["stroke-width"]),t*=this._viewParameters.realScale),super.updateSVGProperty(e,t)}clone(){const e=new kk(this._viewParameters);return e.updateAll(this),e}}var z0,UB;const _p=class _p extends v0{constructor(t){super({...t,name:"inkEditor"});D(this,z0);this._willKeepAspectRatio=!0,this.defaultL10nId="pdfjs-editor-ink-editor"}static initialize(t,n){is.initialize(t,n),this._defaultDrawingOptions=new kk(n.viewParameters)}static getDefaultDrawingOptions(t){const n=this._defaultDrawingOptions.clone();return n.updateProperties(t),n}static get supportMultipleDrawings(){return!0}static get typesMap(){return Tt(this,"typesMap",new Map([[xt.INK_THICKNESS,"stroke-width"],[xt.INK_COLOR,"stroke"],[xt.INK_OPACITY,"stroke-opacity"]]))}static createDrawerInstance(t,n,i,r,o){return new mse(t,n,i,r,o,this._defaultDrawingOptions["stroke-width"])}static deserializeDraw(t,n,i,r,o,a){return o_.deserialize(t,n,i,r,o,a)}static async deserialize(t,n,i){let r=null;if(t instanceof gM){const{data:{inkLists:a,rect:c,rotation:l,id:u,color:h,opacity:d,borderStyle:{rawWidth:p},popupRef:m,richText:v,contentsObj:g,creationDate:y,modificationDate:b},parent:{page:{pageNumber:_}}}=t;r=t={annotationType:Ct.INK,color:Array.from(h),thickness:p,opacity:d,paths:{points:a},boxes:null,pageIndex:_-1,rect:c.slice(0),rotation:l,annotationElementId:u,id:u,deleted:!1,popupRef:m,richText:v,comment:(g==null?void 0:g.str)||null,creationDate:y,modificationDate:b}}const o=await super.deserialize(t,n,i);return o._initialData=r,t.comment&&o.setCommentData(t),o}get toolbarButtons(){return this._colorPicker||(this._colorPicker=new f0(this)),[["colorPicker",this._colorPicker]]}get colorType(){return xt.INK_COLOR}get colorAndOpacityType(){return xt.INK_COLOR_AND_OPACITY}get opacityType(){return xt.INK_OPACITY}updateParams(t,n){if(t===xt.INK_COLOR_AND_OPACITY){this._updateColorAndOpacity(n.color,n.opacity);return}super.updateParams(t,n)}static updateDefaultParams(t,n){if(t===xt.INK_COLOR_AND_OPACITY){super.updateDefaultParams(xt.INK_COLOR,n.color),super.updateDefaultParams(xt.INK_OPACITY,n.opacity);return}super.updateDefaultParams(t,n)}get color(){return this._drawingOptions.stroke}get opacity(){return this._drawingOptions["stroke-opacity"]}onScaleChanging(){if(!this.parent)return;super.onScaleChanging();const{_drawId:t,_drawingOptions:n,parent:i}=this;n.updateSVGProperty("stroke-width"),i.drawLayer.updateProperties(t,n.toSVGProperties())}static onScaleChangingWhenDrawing(){const t=this._currentParent;t&&(super.onScaleChangingWhenDrawing(),this._defaultDrawingOptions.updateSVGProperty("stroke-width"),t.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties()))}createDrawingOptions({color:t,thickness:n,opacity:i}){this._drawingOptions=_p.getDefaultDrawingOptions({stroke:Be.makeHexColor(...t),"stroke-width":n,"stroke-opacity":i})}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const{lines:n,points:i}=this.serializeDraw(t),{_drawingOptions:{stroke:r,"stroke-opacity":o,"stroke-width":a}}=this,c=Object.assign(super.serialize(t),{color:is._colorManager.convert(r),opacity:o,thickness:a,paths:{lines:n,points:i}});return this.addComment(c),t?(c.isCopy=!0,c):this.annotationElementId&&!B(this,z0,UB).call(this,c)?null:(c.id=this.annotationElementId,c)}renderAnnotationElement(t){if(this.deleted)return t.hide(),null;const{points:n,rect:i}=this.serializeDraw(!1);return t.updateEdited({rect:i,thickness:this._drawingOptions["stroke-width"],points:n,popup:this.comment}),null}};z0=new WeakSet,UB=function(t){const{color:n,thickness:i,opacity:r,pageIndex:o}=this._initialData;return this.hasEditedComment||this._hasBeenMoved||this._hasBeenResized||t.color.some((a,c)=>a!==n[c])||t.thickness!==i||t.opacity!==r||t.pageIndex!==o},_e(_p,"_type","ink"),_e(_p,"_editorType",Ct.INK),_e(_p,"_defaultDrawingOptions",null);let LA=_p;class PA extends o_{toSVGPath(){let e=super.toSVGPath();return e.endsWith("Z")||(e+="Z"),e}}St(5213);const Y_=8,Am=3;var pf,rs,OA,ua,WB,zB,DA,nw,jB,VB,GB,NA,BA,qB;class fc{static extractContoursFromText(e,{fontFamily:t,fontStyle:n,fontWeight:i},r,o,a,c){let l=new OffscreenCanvas(1,1),u=l.getContext("2d",{alpha:!1});const h=200,d=u.font=`${n} ${i} ${h}px ${t}`,{actualBoundingBoxLeft:p,actualBoundingBoxRight:m,actualBoundingBoxAscent:v,actualBoundingBoxDescent:g,fontBoundingBoxAscent:y,fontBoundingBoxDescent:b,width:_}=u.measureText(e),w=1.5,S=Math.ceil(Math.max(Math.abs(p)+Math.abs(m)||0,_)*w),C=Math.ceil(Math.max(Math.abs(v)+Math.abs(g)||h,Math.abs(y)+Math.abs(b)||h)*w);l=new OffscreenCanvas(S,C),u=l.getContext("2d",{alpha:!0,willReadFrequently:!0}),u.font=d,u.filter="grayscale(1)",u.fillStyle="white",u.fillRect(0,0,S,C),u.fillStyle="black",u.fillText(e,S*(w-1)/2,C*(3-w)/2);const T=B(this,rs,NA).call(this,u.getImageData(0,0,S,C).data),k=B(this,rs,GB).call(this,T),A=B(this,rs,BA).call(this,k),M=B(this,rs,DA).call(this,T,S,C,A);return this.processDrawnLines({lines:{curves:M,width:S,height:C},pageWidth:r,pageHeight:o,rotation:a,innerMargin:c,mustSmooth:!0,areContours:!0})}static process(e,t,n,i,r){const[o,a,c]=B(this,rs,qB).call(this,e),[l,u]=B(this,rs,VB).call(this,o,a,c,Math.hypot(a,c)*f(this,pf).sigmaSFactor,f(this,pf).sigmaR,f(this,pf).kernelSize),h=B(this,rs,BA).call(this,u),d=B(this,rs,DA).call(this,l,a,c,h);return this.processDrawnLines({lines:{curves:d,width:a,height:c},pageWidth:t,pageHeight:n,rotation:i,innerMargin:r,mustSmooth:!0,areContours:!0})}static processDrawnLines({lines:e,pageWidth:t,pageHeight:n,rotation:i,innerMargin:r,mustSmooth:o,areContours:a}){i%180!==0&&([t,n]=[n,t]);const{curves:c,width:l,height:u}=e,h=e.thickness??0,d=[],p=Math.min(t/l,n/u),m=p/t,v=p/n,g=[];for(const{points:b}of c){const _=o?B(this,rs,jB).call(this,b):b;if(!_)continue;g.push(_);const w=_.length,S=new Float32Array(w),C=new Float32Array(3*(w===2?2:w-2));if(d.push({line:C,points:S}),w===2){S[0]=_[0]*m,S[1]=_[1]*v,C.set([NaN,NaN,NaN,NaN,S[0],S[1]],0);continue}let[T,k,A,M]=_;T*=m,k*=v,A*=m,M*=v,S.set([T,k,A,M],0),C.set([NaN,NaN,NaN,NaN,T,k],0);for(let R=4;R<w;R+=2){const P=S[R]=_[R]*m,L=S[R+1]=_[R+1]*v;C.set(Ze.createBezierPoints(T,k,A,M,P,L),(R-2)*3),[T,k,A,M]=[A,M,P,L]}}if(d.length===0)return null;const y=a?new PA:new o_;return y.build(d,t,n,1,i,a?0:h,r),{outline:y,newCurves:g,areContours:a,thickness:h,width:l,height:u}}static async compressSignature({outlines:e,areContours:t,thickness:n,width:i,height:r}){let o=1/0,a=-1/0,c=0;for(const b of e){c+=b.length;for(let _=2,w=b.length;_<w;_++){const S=b[_]-b[_-2];o=Math.min(o,S),a=Math.max(a,S)}}let l;o>=-128&&a<=127?l=Int8Array:o>=-32768&&a<=32767?l=Int16Array:l=Int32Array;const u=e.length,h=Y_+Am*u,d=new Uint32Array(h);let p=0;d[p++]=h*Uint32Array.BYTES_PER_ELEMENT+(c-2*u)*l.BYTES_PER_ELEMENT,d[p++]=0,d[p++]=i,d[p++]=r,d[p++]=t?0:1,d[p++]=Math.max(0,Math.floor(n??0)),d[p++]=u,d[p++]=l.BYTES_PER_ELEMENT;for(const b of e)d[p++]=b.length-2,d[p++]=b[0],d[p++]=b[1];const m=new CompressionStream("deflate-raw"),v=m.writable.getWriter();await v.ready,v.write(d);const g=l.prototype.constructor;for(const b of e){const _=new g(b.length-2);for(let w=2,S=b.length;w<S;w++)_[w-2]=b[w]-b[w-2];v.write(_)}return v.close(),(await new Response(m.readable).bytes()).toBase64()}static async decompressSignature(e){try{const t=Uint8Array.fromBase64(e),{readable:n,writable:i}=new DecompressionStream("deflate-raw"),r=i.getWriter();await r.ready,r.write(t).then(async()=>{await r.ready,await r.close()}).catch(()=>{});let o=null,a=0;for await(const _ of n)o||(o=new Uint8Array(new Uint32Array(_.buffer,0,4)[0])),o.set(_,a),a+=_.length;const c=new Uint32Array(o.buffer,0,o.length>>2),l=c[1];if(l!==0)throw new Error(`Invalid version: ${l}`);const u=c[2],h=c[3],d=c[4]===0,p=c[5],m=c[6],v=c[7],g=[],y=(Y_+Am*m)*Uint32Array.BYTES_PER_ELEMENT;let b;switch(v){case Int8Array.BYTES_PER_ELEMENT:b=new Int8Array(o.buffer,y);break;case Int16Array.BYTES_PER_ELEMENT:b=new Int16Array(o.buffer,y);break;case Int32Array.BYTES_PER_ELEMENT:b=new Int32Array(o.buffer,y);break}a=0;for(let _=0;_<m;_++){const w=c[Am*_+Y_],S=new Float32Array(w+2);g.push(S);for(let C=0;C<Am-1;C++)S[C]=c[Am*_+Y_+C+1];for(let C=0;C<w;C++)S[C+2]=S[C]+b[a++]}return{areContours:d,thickness:p,outlines:g,width:u,height:h}}catch(t){return kt(`decompressSignature: ${t}`),null}}}pf=new WeakMap,rs=new WeakSet,OA=function(e,t,n,i){return n-=e,i-=t,n===0?i>0?0:4:n===1?i+6:2-i},ua=new WeakMap,WB=function(e,t,n,i,r,o,a){const c=B(this,rs,OA).call(this,n,i,r,o);for(let l=0;l<8;l++){const u=(-l+c-a+16)%8,h=f(this,ua)[2*u],d=f(this,ua)[2*u+1];if(e[(n+h)*t+(i+d)]!==0)return u}return-1},zB=function(e,t,n,i,r,o,a){const c=B(this,rs,OA).call(this,n,i,r,o);for(let l=0;l<8;l++){const u=(l+c+a+16)%8,h=f(this,ua)[2*u],d=f(this,ua)[2*u+1];if(e[(n+h)*t+(i+d)]!==0)return u}return-1},DA=function(e,t,n,i){const r=e.length,o=new Int32Array(r);for(let u=0;u<r;u++)o[u]=e[u]<=i?1:0;for(let u=1;u<n-1;u++)o[u*t]=o[u*t+t-1]=0;for(let u=0;u<t;u++)o[u]=o[t*n-1-u]=0;let a=1,c;const l=[];for(let u=1;u<n-1;u++){c=1;for(let h=1;h<t-1;h++){const d=u*t+h,p=o[d];if(p===0)continue;let m=u,v=h;if(p===1&&o[d-1]===0)a+=1,v-=1;else if(p>=1&&o[d+1]===0)a+=1,v+=1,p>1&&(c=p);else{p!==1&&(c=Math.abs(p));continue}const g=[h,u],y=v===h+1,b={isHole:y,points:g,id:a,parent:0};l.push(b);let _;for(const R of l)if(R.id===c){_=R;break}_?_.isHole?b.parent=y?_.parent:c:b.parent=y?c:_.parent:b.parent=y?c:0;const w=B(this,rs,WB).call(this,o,t,u,h,m,v,0);if(w===-1){o[d]=-a,o[d]!==1&&(c=Math.abs(o[d]));continue}let S=f(this,ua)[2*w],C=f(this,ua)[2*w+1];const T=u+S,k=h+C;m=T,v=k;let A=u,M=h;for(;;){const R=B(this,rs,zB).call(this,o,t,A,M,m,v,1);S=f(this,ua)[2*R],C=f(this,ua)[2*R+1];const P=A+S,L=M+C;g.push(L,P);const z=A*t+M;if(o[z+1]===0?o[z]=-a:o[z]===1&&(o[z]=a),P===u&&L===h&&A===T&&M===k){o[d]!==1&&(c=Math.abs(o[d]));break}else m=A,v=M,A=P,M=L}}}return l},nw=function(e,t,n,i){if(n-t<=4){for(let T=t;T<n-2;T+=2)i.push(e[T],e[T+1]);return}const r=e[t],o=e[t+1],a=e[n-4]-r,c=e[n-3]-o,l=Math.hypot(a,c),u=a/l,h=c/l,d=u*o-h*r,p=c/a,m=1/l,v=Math.atan(p),g=Math.cos(v),y=Math.sin(v),b=m*(Math.abs(g)+Math.abs(y)),_=m*(1-b+b**2),w=Math.max(Math.atan(Math.abs(y+g)*_),Math.atan(Math.abs(y-g)*_));let S=0,C=t;for(let T=t+2;T<n-2;T+=2){const k=Math.abs(d-u*e[T+1]+h*e[T]);k>S&&(C=T,S=k)}S>(l*w)**2?(B(this,rs,nw).call(this,e,t,C+2,i),B(this,rs,nw).call(this,e,C,n,i)):i.push(r,o)},jB=function(e){const t=[],n=e.length;return B(this,rs,nw).call(this,e,0,n,t),t.push(e[n-2],e[n-1]),t.length<=4?null:t},VB=function(e,t,n,i,r,o){const a=new Float32Array(o**2),c=-2*i**2,l=o>>1;for(let v=0;v<o;v++){const g=(v-l)**2;for(let y=0;y<o;y++)a[v*o+y]=Math.exp((g+(y-l)**2)/c)}const u=new Float32Array(256),h=-2*r**2;for(let v=0;v<256;v++)u[v]=Math.exp(v**2/h);const d=e.length,p=new Uint8Array(d),m=new Uint32Array(256);for(let v=0;v<n;v++)for(let g=0;g<t;g++){const y=v*t+g,b=e[y];let _=0,w=0;for(let C=0;C<o;C++){const T=v+C-l;if(!(T<0||T>=n))for(let k=0;k<o;k++){const A=g+k-l;if(A<0||A>=t)continue;const M=e[T*t+A],R=a[C*o+k]*u[Math.abs(M-b)];_+=M*R,w+=R}}const S=p[y]=Math.round(_/w);m[S]++}return[p,m]},GB=function(e){const t=new Uint32Array(256);for(const n of e)t[n]++;return t},NA=function(e){const t=e.length,n=new Uint8ClampedArray(t>>2);let i=-1/0,r=1/0;for(let a=0,c=n.length;a<c;a++){const l=n[a]=e[a<<2];i=Math.max(i,l),r=Math.min(r,l)}const o=255/(i-r);for(let a=0,c=n.length;a<c;a++)n[a]=(n[a]-r)*o;return n},BA=function(e){let t,n=-1/0,i=-1/0;const r=e.findIndex(c=>c!==0);let o=r,a=r;for(t=r;t<256;t++){const c=e[t];c>n&&(t-o>i&&(i=t-o,a=t-1),n=c,o=t)}for(t=a-1;t>=0&&!(e[t]>e[t+1]);t--);return t},qB=function(e){const t=e,{width:n,height:i}=e,{maxDim:r}=f(this,pf);let o=n,a=i;if(n>r||i>r){let d=n,p=i,m=Math.log2(Math.max(n,i)/r);const v=Math.floor(m);m=m===v?v-1:v;for(let y=0;y<m;y++){o=Math.ceil(d/2),a=Math.ceil(p/2);const b=new OffscreenCanvas(o,a);b.getContext("2d").drawImage(e,0,0,d,p,0,0,o,a),d=o,p=a,e!==t&&e.close(),e=b.transferToImageBitmap()}const g=Math.min(r/o,r/a);o=Math.round(o*g),a=Math.round(a*g)}const l=new OffscreenCanvas(o,a).getContext("2d",{willReadFrequently:!0});l.fillStyle="white",l.fillRect(0,0,o,a),l.filter="grayscale(1)",l.drawImage(e,0,0,e.width,e.height,0,0,o,a);const u=l.getImageData(0,0,o,a).data;return[B(this,rs,NA).call(this,u),o,a]},D(fc,rs),D(fc,pf,{maxDim:512,sigmaSFactor:.02,sigmaR:25,kernelSize:16}),D(fc,ua,new Int32Array([0,1,-1,1,-1,0,-1,-1,0,-1,1,-1,1,0,1,1]));class mM extends NB{constructor(){super(),super.updateProperties({fill:is._defaultLineColor,"stroke-width":0})}clone(){const e=new mM;return e.updateAll(this),e}}class vM extends kk{constructor(e){super(e),super.updateProperties({stroke:is._defaultLineColor,"stroke-width":1})}clone(){const e=new vM(this._viewParameters);return e.updateAll(this),e}}var Wu,Ja,zu,gf;const Lr=class Lr extends v0{constructor(t){super({...t,mustBeCommitted:!0,name:"signatureEditor"});D(this,Wu,!1);D(this,Ja,null);D(this,zu,null);D(this,gf,null);this._willKeepAspectRatio=!0,x(this,zu,t.signatureData||null),x(this,Ja,null),this.defaultL10nId="pdfjs-editor-signature-editor1"}static initialize(t,n){is.initialize(t,n),this._defaultDrawingOptions=new mM,this._defaultDrawnSignatureOptions=new vM(n.viewParameters)}static getDefaultDrawingOptions(t){const n=this._defaultDrawingOptions.clone();return n.updateProperties(t),n}static get supportMultipleDrawings(){return!1}static get typesMap(){return Tt(this,"typesMap",new Map)}static get isDrawer(){return!1}get telemetryFinalData(){return{type:"signature",hasDescription:!!f(this,Ja)}}static computeTelemetryFinalData(t){const n=t.get("hasDescription");return{hasAltText:n.get(!0)??0,hasNoAltText:n.get(!1)??0}}get isResizable(){return!0}onScaleChanging(){this._drawId!==null&&super.onScaleChanging()}render(){if(this.div)return this.div;let t,n;const{_isCopy:i}=this;if(i&&(this._isCopy=!1,t=this.x,n=this.y),super.render(),this._drawId===null)if(f(this,zu)){const{lines:r,mustSmooth:o,areContours:a,description:c,uuid:l,heightInPage:u}=f(this,zu),{rawDims:{pageWidth:h,pageHeight:d},rotation:p}=this.parent.viewport,m=fc.processDrawnLines({lines:r,pageWidth:h,pageHeight:d,rotation:p,innerMargin:Lr._INNER_MARGIN,mustSmooth:o,areContours:a});this.addSignature(m,u,c,l)}else this.div.setAttribute("data-l10n-args",JSON.stringify({description:""})),this.div.hidden=!0,this._uiManager.getSignature(this);else this.div.setAttribute("data-l10n-args",JSON.stringify({description:f(this,Ja)||""}));return i&&(this._isCopy=!0,this._moveAfterPaste(t,n)),this.div}setUuid(t){x(this,gf,t),this.addEditToolbar()}getUuid(){return f(this,gf)}get description(){return f(this,Ja)}set description(t){x(this,Ja,t),this.div&&(this.div.setAttribute("data-l10n-args",JSON.stringify({description:t})),super.addEditToolbar().then(n=>{n==null||n.updateEditSignatureButton(t)}))}getSignaturePreview(){const{newCurves:t,areContours:n,thickness:i,width:r,height:o}=f(this,zu),a=Math.max(r,o),c=fc.processDrawnLines({lines:{curves:t.map(l=>({points:l})),thickness:i,width:r,height:o},pageWidth:a,pageHeight:a,rotation:0,innerMargin:0,mustSmooth:!1,areContours:n});return{areContours:n,outline:c.outline}}get toolbarButtons(){return this._uiManager.signatureManager?[["editSignature",this._uiManager.signatureManager]]:super.toolbarButtons}addSignature(t,n,i,r){const{x:o,y:a}=this,{outline:c}=x(this,zu,t);x(this,Wu,c instanceof PA),this.description=i;let l;f(this,Wu)?l=Lr.getDefaultDrawingOptions():(l=Lr._defaultDrawnSignatureOptions.clone(),l.updateProperties({"stroke-width":c.thickness})),this._addOutlines({drawOutlines:c,drawingOptions:l});const[,u]=this.pageDimensions;let h=n/u;h=h>=1?.5:h,this.width*=h/this.height,this.width>=1&&(h*=.9/this.width,this.width=.9),this.height=h,this.setDims(),this.x=o,this.y=a,this.center(),this._onResized(),this.onScaleChanging(),this.rotate(),this._uiManager.addToAnnotationStorage(this),this.setUuid(r),this._reportTelemetry({action:"pdfjs.signature.inserted",data:{hasBeenSaved:!!r,hasDescription:!!i}}),this.div.hidden=!1}getFromImage(t){const{rawDims:{pageWidth:n,pageHeight:i},rotation:r}=this.parent.viewport;return fc.process(t,n,i,r,Lr._INNER_MARGIN)}getFromText(t,n){const{rawDims:{pageWidth:i,pageHeight:r},rotation:o}=this.parent.viewport;return fc.extractContoursFromText(t,n,i,r,o,Lr._INNER_MARGIN)}getDrawnSignature(t){const{rawDims:{pageWidth:n,pageHeight:i},rotation:r}=this.parent.viewport;return fc.processDrawnLines({lines:t,pageWidth:n,pageHeight:i,rotation:r,innerMargin:Lr._INNER_MARGIN,mustSmooth:!1,areContours:!1})}createDrawingOptions({areContours:t,thickness:n}){t?this._drawingOptions=Lr.getDefaultDrawingOptions():(this._drawingOptions=Lr._defaultDrawnSignatureOptions.clone(),this._drawingOptions.updateProperties({"stroke-width":n}))}serialize(t=!1){if(this.isEmpty())return null;const{lines:n,points:i}=this.serializeDraw(t),{_drawingOptions:{"stroke-width":r}}=this,o=Object.assign(super.serialize(t),{isSignature:!0,areContours:f(this,Wu),color:[0,0,0],thickness:f(this,Wu)?0:r});return this.addComment(o),t?(o.paths={lines:n,points:i},o.uuid=f(this,gf),o.isCopy=!0):o.lines=n,f(this,Ja)&&(o.accessibilityData={type:"Figure",alt:f(this,Ja)}),o}static deserializeDraw(t,n,i,r,o,a){return a.areContours?PA.deserialize(t,n,i,r,o,a):o_.deserialize(t,n,i,r,o,a)}static async deserialize(t,n,i){var o;const r=await super.deserialize(t,n,i);return x(r,Wu,t.areContours),r.description=((o=t.accessibilityData)==null?void 0:o.alt)||"",x(r,gf,t.uuid),r}};Wu=new WeakMap,Ja=new WeakMap,zu=new WeakMap,gf=new WeakMap,_e(Lr,"_type","signature"),_e(Lr,"_editorType",Ct.SIGNATURE),_e(Lr,"_defaultDrawingOptions",null);let FA=Lr;var Ds,Gn,ju,ac,Vu,jg,lc,mf,Za,Xr,Vg,Yt,mv,vv,iw,rw,ow,HA,aw,KB;class $A extends is{constructor(t){super({...t,name:"stampEditor"});D(this,Yt);D(this,Ds,null);D(this,Gn,null);D(this,ju,null);D(this,ac,null);D(this,Vu,null);D(this,jg,"");D(this,lc,null);D(this,mf,!1);D(this,Za,null);D(this,Xr,!1);D(this,Vg,!1);x(this,ac,t.bitmapUrl),x(this,Vu,t.bitmapFile),this.defaultL10nId="pdfjs-editor-stamp-editor"}static initialize(t,n){is.initialize(t,n)}static isHandlingMimeForPasting(t){return wT.includes(t)}static paste(t,n){n.pasteEditor({mode:Ct.STAMP},{bitmapFile:t.getAsFile()})}altTextFinish(){this._uiManager.useNewAltTextFlow&&(this.div.hidden=!1),super.altTextFinish()}get telemetryFinalData(){var t;return{type:"stamp",hasAltText:!!((t=this.altTextData)!=null&&t.altText)}}static computeTelemetryFinalData(t){const n=t.get("hasAltText");return{hasAltText:n.get(!0)??0,hasNoAltText:n.get(!1)??0}}async mlGuessAltText(t=null,n=!0){if(this.hasAltTextData())return null;const{mlManager:i}=this._uiManager;if(!i)throw new Error("No ML.");if(!await i.isEnabledFor("altText"))throw new Error("ML isn't enabled for alt text.");const{data:r,width:o,height:a}=t||this.copyCanvas(null,null,!0).imageData,c=await i.guess({name:"altText",request:{data:r,width:o,height:a,channels:r.length/(o*a)}});if(!c)throw new Error("No response from the AI service.");if(c.error)throw new Error("Error from the AI service.");if(c.cancel)return null;if(!c.output)throw new Error("No valid response from the AI service.");const l=c.output;return await this.setGuessedAltText(l),n&&!this.hasAltTextData()&&(this.altTextData={alt:l,decorative:!1}),l}remove(){var t;f(this,Gn)&&(x(this,Ds,null),this._uiManager.imageManager.deleteId(f(this,Gn)),(t=f(this,lc))==null||t.remove(),x(this,lc,null),f(this,Za)&&(clearTimeout(f(this,Za)),x(this,Za,null))),super.remove()}rebuild(){if(!this.parent){f(this,Gn)&&B(this,Yt,iw).call(this);return}super.rebuild(),this.div!==null&&(f(this,Gn)&&f(this,lc)===null&&B(this,Yt,iw).call(this),this.isAttachedToDOM||this.parent.add(this))}onceAdded(t){this._isDraggable=!0,t&&this.div.focus()}isEmpty(){return!(f(this,ju)||f(this,Ds)||f(this,ac)||f(this,Vu)||f(this,Gn)||f(this,mf))}get toolbarButtons(){return[["altText",this.createAltText()]]}get isResizable(){return!0}render(){if(this.div)return this.div;let t,n;return this._isCopy&&(t=this.x,n=this.y),super.render(),this.div.hidden=!0,this.createAltText(),f(this,mf)||(f(this,Ds)?B(this,Yt,rw).call(this):B(this,Yt,iw).call(this)),this._isCopy&&this._moveAfterPaste(t,n),this._uiManager.addShouldRescale(this),this.div}setCanvas(t,n){const{id:i,bitmap:r}=this._uiManager.imageManager.getFromCanvas(t,n);n.remove(),i&&this._uiManager.imageManager.isValidId(i)&&(x(this,Gn,i),r&&x(this,Ds,r),x(this,mf,!1),B(this,Yt,rw).call(this))}_onResized(){this.onScaleChanging()}onScaleChanging(){if(!this.parent)return;f(this,Za)!==null&&clearTimeout(f(this,Za)),x(this,Za,setTimeout(()=>{x(this,Za,null),B(this,Yt,HA).call(this)},200))}copyCanvas(t,n,i=!1){t||(t=224);const{width:r,height:o}=f(this,Ds),a=new ll;let c=f(this,Ds),l=r,u=o,h=null;if(n){if(r>n||o>n){const T=Math.min(n/r,n/o);l=Math.floor(r*T),u=Math.floor(o*T)}h=document.createElement("canvas");const p=h.width=Math.ceil(l*a.sx),m=h.height=Math.ceil(u*a.sy);f(this,Xr)||(c=B(this,Yt,ow).call(this,p,m));const v=h.getContext("2d");v.filter=this._uiManager.hcmFilter;let g="white",y="#cfcfd8";this._uiManager.hcmFilter!=="none"?y="black":Mee.isDarkMode&&(g="#8f8f9d",y="#42414d");const b=15,_=b*a.sx,w=b*a.sy,S=new OffscreenCanvas(_*2,w*2),C=S.getContext("2d");C.fillStyle=g,C.fillRect(0,0,_*2,w*2),C.fillStyle=y,C.fillRect(0,0,_,w),C.fillRect(_,w,_,w),v.fillStyle=v.createPattern(S,"repeat"),v.fillRect(0,0,p,m),v.drawImage(c,0,0,c.width,c.height,0,0,p,m)}let d=null;if(i){let p,m;if(a.symmetric&&c.width<t&&c.height<t)p=c.width,m=c.height;else if(c=f(this,Ds),r>t||o>t){const y=Math.min(t/r,t/o);p=Math.floor(r*y),m=Math.floor(o*y),f(this,Xr)||(c=B(this,Yt,ow).call(this,p,m))}const g=new OffscreenCanvas(p,m).getContext("2d",{willReadFrequently:!0});g.drawImage(c,0,0,c.width,c.height,0,0,p,m),d={width:p,height:m,data:g.getImageData(0,0,p,m).data}}return{canvas:h,width:l,height:u,imageData:d}}static async deserialize(t,n,i){var g;let r=null,o=!1;if(t instanceof uB){const{data:{rect:y,rotation:b,id:_,structParent:w,popupRef:S,richText:C,contentsObj:T,creationDate:k,modificationDate:A},container:M,parent:{page:{pageNumber:R}},canvas:P}=t;let L,z;P?(delete t.canvas,{id:L,bitmap:z}=i.imageManager.getFromCanvas(M.id,P),P.remove()):(o=!0,t._hasNoCanvas=!0);const Q=((g=await n._structTree.getAriaAttributes(`${yp}${_}`))==null?void 0:g.get("aria-label"))||"";r=t={annotationType:Ct.STAMP,bitmapId:L,bitmap:z,pageIndex:R-1,rect:y.slice(0),rotation:b,annotationElementId:_,id:_,deleted:!1,accessibilityData:{decorative:!1,altText:Q},isSvg:!1,structParent:w,popupRef:S,richText:C,comment:(T==null?void 0:T.str)||null,creationDate:k,modificationDate:A}}const a=await super.deserialize(t,n,i),{rect:c,bitmap:l,bitmapUrl:u,bitmapId:h,isSvg:d,accessibilityData:p}=t;o?(i.addMissingCanvas(t.id,a),x(a,mf,!0)):h&&i.imageManager.isValidId(h)?(x(a,Gn,h),l&&x(a,Ds,l)):x(a,ac,u),x(a,Xr,d);const[m,v]=a.pageDimensions;return a.width=(c[2]-c[0])/m,a.height=(c[3]-c[1])/v,p&&(a.altTextData=p),a._initialData=r,t.comment&&a.setCommentData(t),x(a,Vg,!!r),a}serialize(t=!1,n=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const i=Object.assign(super.serialize(t),{bitmapId:f(this,Gn),isSvg:f(this,Xr)});if(this.addComment(i),t)return i.bitmapUrl=B(this,Yt,aw).call(this,!0),i.accessibilityData=this.serializeAltText(!0),i.isCopy=!0,i;const{decorative:r,altText:o}=this.serializeAltText(!1);if(!r&&o&&(i.accessibilityData={type:"Figure",alt:o}),this.annotationElementId){const c=B(this,Yt,KB).call(this,i);return c.isSame?null:(c.isSameAltText?delete i.accessibilityData:i.accessibilityData.structParent=this._initialData.structParent??-1,i.id=this.annotationElementId,delete i.bitmapId,i)}if(n===null)return i;n.stamps||(n.stamps=new Map);const a=f(this,Xr)?(i.rect[2]-i.rect[0])*(i.rect[3]-i.rect[1]):null;if(!n.stamps.has(f(this,Gn)))n.stamps.set(f(this,Gn),{area:a,serialized:i}),i.bitmap=B(this,Yt,aw).call(this,!1);else if(f(this,Xr)){const c=n.stamps.get(f(this,Gn));a>c.area&&(c.area=a,c.serialized.bitmap.close(),c.serialized.bitmap=B(this,Yt,aw).call(this,!1))}return i}renderAnnotationElement(t){return this.deleted?(t.hide(),null):(t.updateEdited({rect:this.getPDFRect(),popup:this.comment}),null)}}Ds=new WeakMap,Gn=new WeakMap,ju=new WeakMap,ac=new WeakMap,Vu=new WeakMap,jg=new WeakMap,lc=new WeakMap,mf=new WeakMap,Za=new WeakMap,Xr=new WeakMap,Vg=new WeakMap,Yt=new WeakSet,mv=function(t,n=!1){if(!t){this.remove();return}x(this,Ds,t.bitmap),n||(x(this,Gn,t.id),x(this,Xr,t.isSvg)),t.file&&x(this,jg,t.file.name),B(this,Yt,rw).call(this)},vv=function(){if(x(this,ju,null),this._uiManager.enableWaiting(!1),!!f(this,lc)){if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&f(this,Ds)){this.addEditToolbar().then(()=>{this._editToolbar.hide(),this._uiManager.editAltText(this,!0)});return}if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&f(this,Ds)){this._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!1,alt_text_type:"empty"}});try{this.mlGuessAltText()}catch{}}this.div.focus()}},iw=function(){if(f(this,Gn)){this._uiManager.enableWaiting(!0),this._uiManager.imageManager.getFromId(f(this,Gn)).then(i=>B(this,Yt,mv).call(this,i,!0)).finally(()=>B(this,Yt,vv).call(this));return}if(f(this,ac)){const i=f(this,ac);x(this,ac,null),this._uiManager.enableWaiting(!0),x(this,ju,this._uiManager.imageManager.getFromUrl(i).then(r=>B(this,Yt,mv).call(this,r)).finally(()=>B(this,Yt,vv).call(this)));return}if(f(this,Vu)){const i=f(this,Vu);x(this,Vu,null),this._uiManager.enableWaiting(!0),x(this,ju,this._uiManager.imageManager.getFromFile(i).then(r=>B(this,Yt,mv).call(this,r)).finally(()=>B(this,Yt,vv).call(this)));return}const t=document.createElement("input");t.type="file",t.accept=wT.join(",");const n=this._uiManager._signal;x(this,ju,new Promise(i=>{t.addEventListener("change",async()=>{if(!t.files||t.files.length===0)this.remove();else{this._uiManager.enableWaiting(!0);const r=await this._uiManager.imageManager.getFromFile(t.files[0]);this._reportTelemetry({action:"pdfjs.image.image_selected",data:{alt_text_modal:this._uiManager.useNewAltTextFlow}}),B(this,Yt,mv).call(this,r)}i()},{signal:n}),t.addEventListener("cancel",()=>{this.remove(),i()},{signal:n})}).finally(()=>B(this,Yt,vv).call(this))),t.click()},rw=function(){var l;const{div:t}=this;let{width:n,height:i}=f(this,Ds);const[r,o]=this.pageDimensions,a=.75;if(this.width)n=this.width*r,i=this.height*o;else if(n>a*r||i>a*o){const u=Math.min(a*r/n,a*o/i);n*=u,i*=u}this._uiManager.enableWaiting(!1);const c=x(this,lc,document.createElement("canvas"));c.setAttribute("role","img"),this.addContainer(c),this.width=n/r,this.height=i/o,this.setDims(),(l=this._initialOptions)!=null&&l.isCentered?this.center():this.fixAndSetPosition(),this._initialOptions=null,(!this._uiManager.useNewAltTextWhenAddingImage||!this._uiManager.useNewAltTextFlow||this.annotationElementId)&&(t.hidden=!1),B(this,Yt,HA).call(this),f(this,Vg)||(this.parent.addUndoableEditor(this),x(this,Vg,!0)),this._reportTelemetry({action:"inserted_image"}),f(this,jg)&&this.div.setAttribute("aria-description",f(this,jg)),this.annotationElementId||this._uiManager.a11yAlert(is._l10nAlert.stamp)},ow=function(t,n){const{width:i,height:r}=f(this,Ds);let o=i,a=r,c=f(this,Ds);for(;o>2*t||a>2*n;){const l=o,u=a;o>2*t&&(o=Math.ceil(o/2)),a>2*n&&(a=Math.ceil(a/2));const h=new OffscreenCanvas(o,a);h.getContext("2d").drawImage(c,0,0,l,u,0,0,o,a),c=h.transferToImageBitmap()}return c},HA=function(){const[t,n]=this.parentDimensions,{width:i,height:r}=this,o=new ll,a=Math.ceil(i*t*o.sx),c=Math.ceil(r*n*o.sy),l=f(this,lc);if(!l||l.width===a&&l.height===c)return;l.width=a,l.height=c;const u=f(this,Xr)?f(this,Ds):B(this,Yt,ow).call(this,a,c),h=l.getContext("2d");h.filter=this._uiManager.hcmFilter,h.drawImage(u,0,0,u.width,u.height,0,0,a,c)},aw=function(t){if(t){if(f(this,Xr)){const r=this._uiManager.imageManager.getSvgUrl(f(this,Gn));if(r)return r}const n=document.createElement("canvas");return{width:n.width,height:n.height}=f(this,Ds),n.getContext("2d").drawImage(f(this,Ds),0,0),n.toDataURL()}if(f(this,Xr)){const[n,i]=this.pageDimensions,r=Math.round(this.width*n*uh.PDF_TO_CSS_UNITS),o=Math.round(this.height*i*uh.PDF_TO_CSS_UNITS),a=new OffscreenCanvas(r,o);return a.getContext("2d").drawImage(f(this,Ds),0,0,f(this,Ds).width,f(this,Ds).height,0,0,r,o),a.transferToImageBitmap()}return structuredClone(f(this,Ds))},KB=function(t){var a;const{pageIndex:n,accessibilityData:{altText:i}}=this._initialData,r=t.pageIndex===n,o=(((a=t.accessibilityData)==null?void 0:a.alt)||"")===i;return{isSame:!this.hasEditedComment&&!this._hasBeenMoved&&!this._hasBeenResized&&r&&o,isSameAltText:o}},_e($A,"_type","stamp"),_e($A,"_editorType",Ct.STAMP);var vf,Gg,Gu,qu,cc,fr,Ku,qg,Kg,ha,uc,qn,hc,Qu,Qg,it,Xu,bs,WA,QB,Aa,zA,jA,lw;const Jo=class Jo{constructor({uiManager:e,pageIndex:t,div:n,structTreeLayer:i,accessibilityManager:r,annotationLayer:o,drawLayer:a,textLayer:c,viewport:l,l10n:u}){D(this,bs);D(this,vf);D(this,Gg,!1);D(this,Gu,null);D(this,qu,null);D(this,cc,null);D(this,fr,new Map);D(this,Ku,!1);D(this,qg,!1);D(this,Kg,!1);D(this,ha,null);D(this,uc,null);D(this,qn,null);D(this,hc,null);D(this,Qu,null);D(this,Qg,-1);D(this,it);const h=[...f(Jo,Xu).values()];if(!Jo._initialized){Jo._initialized=!0;for(const d of h)d.initialize(u,e)}e.registerEditorTypes(h),x(this,it,e),this.pageIndex=t,this.div=n,x(this,vf,r),x(this,Gu,o),this.viewport=l,x(this,qn,c),this.drawLayer=a,this._structTree=i,f(this,it).addLayer(this)}get isEmpty(){return f(this,fr).size===0}get isInvisible(){return this.isEmpty&&f(this,it).getMode()===Ct.NONE}updateToolbar(e){f(this,it).updateToolbar(e)}updateMode(e=f(this,it).getMode()){switch(B(this,bs,lw).call(this),e){case Ct.NONE:this.div.classList.toggle("nonEditing",!0),this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),this.disableClick();return;case Ct.INK:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick();break;case Ct.HIGHLIGHT:this.enableTextSelection(),this.togglePointerEvents(!1),this.disableClick();break;default:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick()}this.toggleAnnotationLayerPointerEvents(!1);const{classList:t}=this.div;if(t.toggle("nonEditing",!1),e===Ct.POPUP)t.toggle("commentEditing",!0);else{t.toggle("commentEditing",!1);for(const n of f(Jo,Xu).values())t.toggle(`${n._type}Editing`,e===n._editorType)}this.div.hidden=!1}hasTextLayer(e){var t;return e===((t=f(this,qn))==null?void 0:t.div)}setEditingState(e){f(this,it).setEditingState(e)}addCommands(e){f(this,it).addCommands(e)}cleanUndoStack(e){f(this,it).cleanUndoStack(e)}toggleDrawing(e=!1){this.div.classList.toggle("drawing",!e)}togglePointerEvents(e=!1){this.div.classList.toggle("disabled",!e)}toggleAnnotationLayerPointerEvents(e=!1){var t;(t=f(this,Gu))==null||t.togglePointerEvents(e)}async enable(){var n;x(this,Kg,!0),this.div.tabIndex=0,this.togglePointerEvents(!0),this.div.classList.toggle("nonEditing",!1),(n=f(this,Qu))==null||n.abort(),x(this,Qu,null);const e=new Set;for(const i of f(this,bs,WA))i.enableEditing(),i.show(!0),i.annotationElementId&&(f(this,it).removeChangedExistingAnnotation(i),e.add(i.annotationElementId));const t=f(this,Gu);if(t)for(const i of t.getEditableAnnotations()){if(i.hide(),f(this,it).isDeletedAnnotationElement(i.data.id)||e.has(i.data.id))continue;const r=await this.deserialize(i);r&&(this.addOrRebuild(r),r.enableEditing())}x(this,Kg,!1),f(this,it)._eventBus.dispatch("editorsrendered",{source:this,pageNumber:this.pageIndex+1})}disable(){var i;if(x(this,qg,!0),this.div.tabIndex=-1,this.togglePointerEvents(!1),this.div.classList.toggle("nonEditing",!0),f(this,qn)&&!f(this,Qu)){x(this,Qu,new AbortController);const r=f(this,it).combinedSignal(f(this,Qu));f(this,qn).div.addEventListener("pointerdown",o=>{const{clientX:c,clientY:l,timeStamp:u}=o,h=f(this,Qg);if(u-h>500){x(this,Qg,u);return}x(this,Qg,-1);const{classList:d}=this.div;d.toggle("getElements",!0);const p=document.elementsFromPoint(c,l);if(d.toggle("getElements",!1),!this.div.contains(p[0]))return;let m;const v=new RegExp(`^${oy}[0-9]+$`);for(const y of p)if(v.test(y.id)){m=y.id;break}if(!m)return;const g=f(this,fr).get(m);(g==null?void 0:g.annotationElementId)===null&&(js(o),g.dblclick(o))},{signal:r,capture:!0})}const e=f(this,Gu),t=[];if(e){const r=new Map,o=new Map;for(const a of f(this,bs,WA)){if(a.disableEditing(),!a.annotationElementId){t.push(a);continue}if(a.serialize()!==null){r.set(a.annotationElementId,a);continue}else o.set(a.annotationElementId,a);(i=this.getEditableAnnotation(a.annotationElementId))==null||i.show(),a.remove()}for(const a of e.getEditableAnnotations()){const{id:c}=a.data;if(f(this,it).isDeletedAnnotationElement(c)){a.updateEdited({deleted:!0});continue}let l=o.get(c);if(l){l.resetAnnotationElement(a),l.show(!1),a.show();continue}l=r.get(c),l&&(f(this,it).addChangedExistingAnnotation(l),l.renderAnnotationElement(a)&&l.show(!1)),a.show()}}B(this,bs,lw).call(this),this.isEmpty&&(this.div.hidden=!0);const{classList:n}=this.div;for(const r of f(Jo,Xu).values())n.remove(`${r._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),e==null||e.updateFakeAnnotations(t),x(this,qg,!1)}getEditableAnnotation(e){var t;return((t=f(this,Gu))==null?void 0:t.getEditableAnnotation(e))||null}setActiveEditor(e){f(this,it).getActive()!==e&&f(this,it).setActiveEditor(e)}enableTextSelection(){var e;if(this.div.tabIndex=-1,(e=f(this,qn))!=null&&e.div&&!f(this,hc)){x(this,hc,new AbortController);const t=f(this,it).combinedSignal(f(this,hc));f(this,qn).div.addEventListener("pointerdown",B(this,bs,QB).bind(this),{signal:t}),f(this,qn).div.classList.add("highlighting")}}disableTextSelection(){var e;this.div.tabIndex=0,(e=f(this,qn))!=null&&e.div&&f(this,hc)&&(f(this,hc).abort(),x(this,hc,null),f(this,qn).div.classList.remove("highlighting"))}enableClick(){if(f(this,qu))return;x(this,qu,new AbortController);const e=f(this,it).combinedSignal(f(this,qu));this.div.addEventListener("pointerdown",this.pointerdown.bind(this),{signal:e});const t=this.pointerup.bind(this);this.div.addEventListener("pointerup",t,{signal:e}),this.div.addEventListener("pointercancel",t,{signal:e})}disableClick(){var e;(e=f(this,qu))==null||e.abort(),x(this,qu,null)}attach(e){f(this,fr).set(e.id,e);const{annotationElementId:t}=e;t&&f(this,it).isDeletedAnnotationElement(t)&&f(this,it).removeDeletedAnnotationElement(e)}detach(e){var t;f(this,fr).delete(e.id),(t=f(this,vf))==null||t.removePointerInTextLayer(e.contentDiv),!f(this,qg)&&e.annotationElementId&&f(this,it).addDeletedAnnotationElement(e)}remove(e){this.detach(e),f(this,it).removeEditor(e),e.div.remove(),e.isAttachedToDOM=!1}changeParent(e){var t;e.parent!==this&&(e.parent&&e.annotationElementId&&(f(this,it).addDeletedAnnotationElement(e),is.deleteAnnotationElement(e),e.annotationElementId=null),this.attach(e),(t=e.parent)==null||t.detach(e),e.setParent(this),e.div&&e.isAttachedToDOM&&(e.div.remove(),this.div.append(e.div)))}add(e){if(!(e.parent===this&&e.isAttachedToDOM)){if(this.changeParent(e),f(this,it).addEditor(e),this.attach(e),!e.isAttachedToDOM){const t=e.render();this.div.append(t),e.isAttachedToDOM=!0}e.fixAndSetPosition(),e.onceAdded(!f(this,Kg)),f(this,it).addToAnnotationStorage(e),e._reportTelemetry(e.telemetryInitialData)}}moveEditorInDOM(e){var n;if(!e.isAttachedToDOM)return;const{activeElement:t}=document;e.div.contains(t)&&!f(this,cc)&&(e._focusEventsAllowed=!1,x(this,cc,setTimeout(()=>{x(this,cc,null),e.div.contains(document.activeElement)?e._focusEventsAllowed=!0:(e.div.addEventListener("focusin",()=>{e._focusEventsAllowed=!0},{once:!0,signal:f(this,it)._signal}),t.focus())},0))),e._structTreeParentId=(n=f(this,vf))==null?void 0:n.moveElementInDOM(this.div,e.div,e.contentDiv,!0)}addOrRebuild(e){e.needsToBeRebuilt()?(e.parent||(e.parent=this),e.rebuild(),e.show()):this.add(e)}addUndoableEditor(e){const t=()=>e._uiManager.rebuild(e),n=()=>{e.remove()};this.addCommands({cmd:t,undo:n,mustExec:!1})}getEditorByUID(e){for(const t of f(this,fr).values())if(t.uid===e)return t;return null}combinedSignal(e){return f(this,it).combinedSignal(e)}canCreateNewEmptyEditor(){var e;return(e=f(this,bs,Aa))==null?void 0:e.canCreateNewEmptyEditor()}async pasteEditor(e,t){this.updateToolbar(e),await f(this,it).updateMode(e.mode);const{offsetX:n,offsetY:i}=B(this,bs,jA).call(this),r=f(this,it).getId(),o=B(this,bs,zA).call(this,{parent:this,id:r,x:n,y:i,uiManager:f(this,it),isCentered:!0,...t});o&&this.add(o)}async deserialize(e){var t;return await((t=f(Jo,Xu).get(e.annotationType??e.annotationEditorType))==null?void 0:t.deserialize(e,this,f(this,it)))||null}createAndAddNewEditor(e,t,n={}){const i=f(this,it).getId(),r=B(this,bs,zA).call(this,{parent:this,id:i,x:e.offsetX,y:e.offsetY,uiManager:f(this,it),isCentered:t,...n});return r&&this.add(r),r}get boundingClientRect(){return this.div.getBoundingClientRect()}addNewEditor(e={}){this.createAndAddNewEditor(B(this,bs,jA).call(this),!0,e)}setSelected(e){f(this,it).setSelected(e)}toggleSelected(e){f(this,it).toggleSelected(e)}unselect(e){f(this,it).unselect(e)}pointerup(e){var i;const{isMac:t}=Ts.platform;if(e.button!==0||e.ctrlKey&&t||e.target!==this.div||!f(this,Ku)||(x(this,Ku,!1),(i=f(this,bs,Aa))!=null&&i.isDrawer&&f(this,bs,Aa).supportMultipleDrawings))return;if(!f(this,Gg)){x(this,Gg,!0);return}const n=f(this,it).getMode();if(n===Ct.STAMP||n===Ct.POPUP||n===Ct.SIGNATURE){f(this,it).unselectAll();return}this.createAndAddNewEditor(e,!1)}pointerdown(e){var i;if(f(this,it).getMode()===Ct.HIGHLIGHT&&this.enableTextSelection(),f(this,Ku)){x(this,Ku,!1);return}const{isMac:t}=Ts.platform;if(e.button!==0||e.ctrlKey&&t||e.target!==this.div)return;if(x(this,Ku,!0),(i=f(this,bs,Aa))!=null&&i.isDrawer){this.startDrawingSession(e);return}const n=f(this,it).getActive();x(this,Gg,!n||n.isEmpty())}startDrawingSession(e){if(this.div.focus({preventScroll:!0}),f(this,ha)){f(this,bs,Aa).startDrawing(this,f(this,it),!1,e);return}f(this,it).setCurrentDrawingSession(this),x(this,ha,new AbortController);const t=f(this,it).combinedSignal(f(this,ha));this.div.addEventListener("blur",({relatedTarget:n})=>{n&&!this.div.contains(n)&&(x(this,uc,null),this.commitOrRemove())},{signal:t}),f(this,bs,Aa).startDrawing(this,f(this,it),!1,e)}pause(e){if(e){const{activeElement:t}=document;this.div.contains(t)&&x(this,uc,t);return}f(this,uc)&&setTimeout(()=>{var t;(t=f(this,uc))==null||t.focus(),x(this,uc,null)},0)}endDrawingSession(e=!1){return f(this,ha)?(f(this,it).setCurrentDrawingSession(null),f(this,ha).abort(),x(this,ha,null),x(this,uc,null),f(this,bs,Aa).endDrawing(e)):null}findNewParent(e,t,n){const i=f(this,it).findParent(t,n);return i===null||i===this?!1:(i.changeParent(e),!0)}commitOrRemove(){return f(this,ha)?(this.endDrawingSession(),!0):!1}onScaleChanging(){f(this,ha)&&f(this,bs,Aa).onScaleChangingWhenDrawing(this)}destroy(){var e,t;this.commitOrRemove(),((e=f(this,it).getActive())==null?void 0:e.parent)===this&&(f(this,it).commitOrRemove(),f(this,it).setActiveEditor(null)),f(this,cc)&&(clearTimeout(f(this,cc)),x(this,cc,null));for(const n of f(this,fr).values())(t=f(this,vf))==null||t.removePointerInTextLayer(n.contentDiv),n.setParent(null),n.isAttachedToDOM=!1,n.div.remove();this.div=null,f(this,fr).clear(),f(this,it).removeLayer(this)}async render({viewport:e}){this.viewport=e,Rf(this.div,e);for(const t of f(this,it).getEditors(this.pageIndex))this.add(t),t.rebuild();await f(this,it).findClonesForPage(this),this.div.hidden=this.isEmpty,this.updateMode()}update({viewport:e}){f(this,it).commitOrRemove(),B(this,bs,lw).call(this);const t=this.viewport.rotation,n=e.rotation;if(this.viewport=e,Rf(this.div,{rotation:n}),t!==n)for(const i of f(this,fr).values())i.rotate(n)}get pageDimensions(){const{pageWidth:e,pageHeight:t}=this.viewport.rawDims;return[e,t]}get scale(){return f(this,it).viewParameters.realScale}};vf=new WeakMap,Gg=new WeakMap,Gu=new WeakMap,qu=new WeakMap,cc=new WeakMap,fr=new WeakMap,Ku=new WeakMap,qg=new WeakMap,Kg=new WeakMap,ha=new WeakMap,uc=new WeakMap,qn=new WeakMap,hc=new WeakMap,Qu=new WeakMap,Qg=new WeakMap,it=new WeakMap,Xu=new WeakMap,bs=new WeakSet,WA=function(){return f(this,fr).size!==0?f(this,fr).values():f(this,it).getEditors(this.pageIndex)},QB=function(e){f(this,it).unselectAll();const{target:t}=e;if(t===f(this,qn).div||(t.getAttribute("role")==="img"||t.classList.contains("endOfContent")||t.classList.contains("textLayerImages")||t.classList.contains("textLayerImagePlaceholder"))&&f(this,qn).div.contains(t)){const{isMac:n}=Ts.platform;if(e.button!==0||e.ctrlKey&&n)return;f(this,it).showAllEditors("highlight",!0,!0),f(this,qn).div.classList.add("free"),this.toggleDrawing(),m0.startHighlighting(this,f(this,it).direction==="ltr",{target:f(this,qn).div,x:e.x,y:e.y}),f(this,qn).div.addEventListener("pointerup",()=>{f(this,qn).div.classList.remove("free"),this.toggleDrawing(!0)},{once:!0,signal:f(this,it)._signal}),e.preventDefault()}},Aa=function(){return f(Jo,Xu).get(f(this,it).getMode())},zA=function(e){const t=f(this,bs,Aa);return t?new t.prototype.constructor(e):null},jA=function(){const{x:e,y:t,width:n,height:i}=this.boundingClientRect,r=Math.max(0,e),o=Math.max(0,t),a=Math.min(window.innerWidth,e+n),c=Math.min(window.innerHeight,t+i),l=(r+a)/2-e,u=(o+c)/2-t,[h,d]=this.viewport.rotation%180===0?[l,u]:[u,l];return{offsetX:h,offsetY:d}},lw=function(){for(const e of f(this,fr).values())e.isEmpty()&&e.remove()},_e(Jo,"_initialized",!1),D(Jo,Xu,new Map([wA,LA,$A,m0,FA].map(e=>[e._editorType,e])));let UA=Jo;function vse(s,e){return s===e?0:s.compareDocumentPosition(e)&Node.DOCUMENT_POSITION_FOLLOWING?-1:1}function J_(s){var e;return s?s.nodeType===Node.ELEMENT_NODE?s.closest(".textLayer"):((e=s.parentElement)==null?void 0:e.closest(".textLayer"))||null:null}function yse(s,e,t,n){if(s===t)return e<=n;const i=s.compareDocumentPosition(t);return i&Node.DOCUMENT_POSITION_FOLLOWING?!0:i&Node.DOCUMENT_POSITION_PRECEDING?!1:null}function HR(s,e,t){if(s.nodeType!==Node.ELEMENT_NODE||!s.classList.contains("textLayer")||e!==s.childNodes.length)return{container:s,offset:e};let n=s.lastChild;return(n==null?void 0:n.nodeType)===Node.ELEMENT_NODE&&n.classList.contains("endOfContent")&&(n=n.previousSibling),!n||!t.contains(n)?null:n.nodeType===Node.TEXT_NODE?{container:n,offset:n.textContent.length}:{container:n,offset:n.childNodes.length}}var pr,qi,Eo,qb,Kb,yf,bf,Qb,j0,Yu,Ju,Zu,eh,dc,Ri,GA,qA,XB,cw,YB,ul,KA,JB,QA;const lt=class lt{constructor({filterFactory:e=null,pageColors:t=null,pageIndex:n,textLayer:i=null}){D(this,ul);D(this,pr,null);D(this,qi,new Map);D(this,Eo,null);D(this,qb,null);D(this,Kb,null);D(this,yf,null);D(this,bf,new Map);if(this.pageIndex=n,x(this,qb,e),x(this,Kb,t),i){const r=f(lt,dc).get(i);if(r!=null&&r.selectionDiv&&(r.selectionDiv.remove(),f(lt,Ju).delete(r.selectionDiv)),f(lt,dc).set(i,{drawLayer:this}),f(lt,eh).add(i),x(this,Eo,i),x(this,yf,new MutationObserver(o=>{var a,c,l;if(!(!f(this,pr)||!((a=f(this,Eo))!=null&&a.isConnected)||!B(c=lt,Ri,qA).call(c))){for(const{addedNodes:u}of o)for(const h of u)if(h.nodeType===Node.ELEMENT_NODE&&h.classList.contains("endOfContent")){B(l=lt,Ri,cw).call(l);return}}})),f(this,yf).observe(i,{childList:!0}),f(lt,Yu)===null){x(lt,Yu,new AbortController);const{signal:o}=f(lt,Yu);document.addEventListener("selectionchange",B(lt,Ri,cw).bind(lt),{signal:o}),document.addEventListener("pointerdown",()=>{x(lt,Zu,!0)},{signal:o}),document.addEventListener("pointerup",()=>{x(lt,Zu,!1)},{signal:o}),window.addEventListener("blur",()=>{x(lt,Zu,!1)},{signal:o})}}}setParent(e){var t,n,i;if(!f(this,pr)){x(this,pr,e),(t=f(this,Eo))!=null&&t.isConnected&&B(n=lt,Ri,qA).call(n)&&B(i=lt,Ri,cw).call(i);return}if(f(this,pr)!==e){if(f(this,qi).size>0)for(const r of f(this,qi).values())r.remove(),e.append(r);x(this,pr,e)}}static get _svgFactory(){return Tt(this,"_svgFactory",new p0)}draw(e,t=!1,n=!1){const i=xs(lt,Qb)._++,r=B(this,ul,KA).call(this),o=lt._svgFactory.createElement("defs");r.append(o);const a=lt._svgFactory.createElement("path");o.append(a);const c=`path_${i}`;a.setAttribute("id",c),a.setAttribute("vector-effect","non-scaling-stroke"),t&&f(this,bf).set(i,a);const l=n?B(this,ul,JB).call(this,o,c):null,u=lt._svgFactory.createElement("use");return r.append(u),u.setAttribute("href",`#${c}`),this.updateProperties(r,e),f(this,qi).set(i,r),{id:i,clipPathId:`url(#${l})`}}drawOutline(e,t){const n=xs(lt,Qb)._++,i=B(this,ul,KA).call(this),r=lt._svgFactory.createElement("defs");i.append(r);const o=lt._svgFactory.createElement("path");r.append(o);const a=`path_${n}`;o.setAttribute("id",a),o.setAttribute("vector-effect","non-scaling-stroke");let c;if(t){const h=lt._svgFactory.createElement("mask");r.append(h),c=`mask_${n}`,h.setAttribute("id",c),h.setAttribute("maskUnits","objectBoundingBox");const d=lt._svgFactory.createElement("rect");h.append(d),d.setAttribute("width","1"),d.setAttribute("height","1"),d.setAttribute("fill","white");const p=lt._svgFactory.createElement("use");h.append(p),p.setAttribute("href",`#${a}`),p.setAttribute("stroke","none"),p.setAttribute("fill","black"),p.setAttribute("fill-rule","nonzero"),p.classList.add("mask")}const l=lt._svgFactory.createElement("use");i.append(l),l.setAttribute("href",`#${a}`),c&&l.setAttribute("mask",`url(#${c})`);const u=l.cloneNode();return i.append(u),l.classList.add("mainOutline"),u.classList.add("secondaryOutline"),this.updateProperties(i,e),f(this,qi).set(n,i),n}finalizeDraw(e,t){f(this,bf).delete(e),this.updateProperties(e,t)}updateProperties(e,t){var c;if(!t)return;const{root:n,bbox:i,rootClass:r,path:o}=t,a=typeof e=="number"?f(this,qi).get(e):e;if(a){if(n&&B(this,ul,QA).call(this,a,n),i&&B(c=lt,Ri,YB).call(c,a,i),r){const{classList:l}=a;for(const[u,h]of Object.entries(r))l.toggle(u,h)}if(o){const u=a.firstElementChild.firstElementChild;B(this,ul,QA).call(this,u,o)}}}updateParent(e,t){if(t===this)return;const n=f(this,qi).get(e);n&&(f(t,pr).append(n),f(this,qi).delete(e),f(t,qi).set(e,n))}remove(e){f(this,bf).delete(e),f(this,pr)!==null&&(f(this,qi).get(e).remove(),f(this,qi).delete(e))}destroy(){var e,t,n;x(this,pr,null);for(const i of f(this,qi).values())i.remove();if(f(this,qi).clear(),f(this,bf).clear(),(e=f(this,yf))==null||e.disconnect(),x(this,yf,null),f(this,Eo)){const i=f(lt,dc).get(f(this,Eo));(i==null?void 0:i.drawLayer)===this&&(B(t=lt,Ri,GA).call(t,f(this,Eo)),f(lt,dc).delete(f(this,Eo)),f(lt,eh).delete(f(this,Eo)),f(lt,eh).size===0&&((n=f(lt,Yu))==null||n.abort(),x(lt,Yu,null),x(lt,Zu,!1))),x(this,Eo,null)}}};pr=new WeakMap,qi=new WeakMap,Eo=new WeakMap,qb=new WeakMap,Kb=new WeakMap,yf=new WeakMap,bf=new WeakMap,Qb=new WeakMap,j0=new WeakMap,Yu=new WeakMap,Ju=new WeakMap,Zu=new WeakMap,eh=new WeakMap,dc=new WeakMap,Ri=new WeakSet,GA=function(e){const t=f(this,dc).get(e);t!=null&&t.selectionDiv&&(t.selectionDiv.remove(),f(this,Ju).delete(t.selectionDiv),t.selectionDiv=null,t.path=null)},qA=function(){const e=document.getSelection();return!!e&&!e.isCollapsed},XB=function(){return[...f(this,eh)].filter(e=>e.isConnected).sort(vse)},cw=function(){var o;const e=document.getSelection();if(!e||e.isCollapsed){for(const a of f(this,Ju))a.remove();f(this,Ju).clear();return}const t=new WeakMap,n=B(this,Ri,XB).call(this),i=[];for(let a=0,c=e.rangeCount;a<c;a++){const l=e.getRangeAt(a);if(l.collapsed)continue;let{startContainer:u,startOffset:h,endContainer:d,endOffset:p}=l,m=J_(u),v=J_(d);const g=m===null,y=v===null;if(f(this,Zu)&&g!==y)return;if(e.rangeCount===1){const{anchorNode:w,anchorOffset:S,focusNode:C,focusOffset:T}=e,k=J_(w),A=J_(C),M=yse(w,S,C,T);k&&A&&M!==null&&(M?(u=w,h=S,m=k,d=C,p=T,v=A):(u=C,h=T,m=A,d=w,p=S,v=k))}const b=n.filter(w=>l.intersectsNode(w));if(b.length===0)continue;let _=!1;if(m||(m=b[0],u=m,h=0,_=!0),v||(v=b.at(-1),d=v,p=v.childNodes.length,_=!0),d.nodeType===Node.ELEMENT_NODE){if(d.classList.contains("endOfContent")){const w=d.previousSibling;if(!w)continue;d=w,p=w.nodeType===Node.TEXT_NODE?w.textContent.length:w.childNodes.length}else if(d.classList.contains("textLayer")&&d.childNodes.length===p){const w=HR(d,p,v);if(!w)continue;d=w.container,p=w.offset}}if(u.nodeType===Node.ELEMENT_NODE){const w=HR(u,h,m);if(!w)continue;u=w.container,h=w.offset}if(m===v&&!_&&b.includes(m)){i.push([l,m]);continue}for(const w of b){const S=w.firstChild;if(!S)continue;const C=document.createRange();if(w===m?C.setStart(u,h):C.setStartBefore(S),w===v)C.setEnd(d,p);else{const T=w.lastChild;if(!T)continue;if(T.nodeType===Node.ELEMENT_NODE&&T.classList.contains("endOfContent")){const k=T.previousSibling;if(!k)continue;C.setEndAfter(k)}else C.setEndAfter(T)}C.collapsed||i.push([C,w])}}const r=new Set(i.map(a=>a[1]));for(const a of f(this,eh))r.has(a)||B(this,Ri,GA).call(this,a);for(const[a,c]of i){const l=f(lt,dc).get(c);if(!l)continue;let u=t.get(c);if(!u){const v=c.getBoundingClientRect();u=(g,y,b,_)=>({x:(g-v.x)/v.width,y:(y-v.y)/v.height,width:b/v.width,height:_/v.height}),t.set(c,u)}const h=[];for(let{x:v,y:g,width:y,height:b}of a.getClientRects())y===0||b===0||({x:v,y:g,width:y,height:b}=u(v,g,y,b),!(y===1&&b===1)&&h.push(`M${v} ${g} h${y} v${b} h-${y} Z`));if(h.length===0)continue;const d=l.drawLayer;let p=l.selectionDiv,m=l.path;if(!p){const v=`clip_selection_${xs(lt,j0)._++}`;p=document.createElement("div"),p.className="selection",p.style.clipPath=`url(#${v})`;const g=(o=f(d,qb))==null?void 0:o.createSelectionStyle(f(d,Kb));if(g)for(const[_,w]of Object.entries(g))p.style.setProperty(_,w);const y=lt._svgFactory.create(1,1,!0);y.setAttribute("aria-hidden","true"),y.setAttribute("width","100%"),y.setAttribute("height","100%");const b=lt._svgFactory.createElement("clipPath");b.setAttribute("id",v),b.setAttribute("clipPathUnits","objectBoundingBox"),m=lt._svgFactory.createElement("path"),b.append(m),y.append(b),p.append(y),l.path=m,l.selectionDiv=p}!p.parentNode&&f(d,pr)&&(f(d,pr).append(p),f(this,Ju).add(p)),m.setAttribute("d",h.join(" "))}},YB=function(e,[t,n,i,r]){const{style:o}=e;o.top=`${100*n}%`,o.left=`${100*t}%`,o.width=`${100*i}%`,o.height=`${100*r}%`},ul=new WeakSet,KA=function(){const e=lt._svgFactory.create(1,1,!0);return f(this,pr).append(e),e.setAttribute("aria-hidden","true"),e},JB=function(e,t){const n=lt._svgFactory.createElement("clipPath");e.append(n);const i=`clip_${t}`;n.setAttribute("id",i),n.setAttribute("clipPathUnits","objectBoundingBox");const r=lt._svgFactory.createElement("use");return n.append(r),r.setAttribute("href",`#${t}`),r.classList.add("clip"),i},QA=function(e,t){for(const[n,i]of Object.entries(t))i===null?e.removeAttribute(n):e.setAttribute(n,i)},D(lt,Ri),D(lt,Qb,0),D(lt,j0,0),D(lt,Yu,null),D(lt,Ju,new Set),D(lt,Zu,!1),D(lt,eh,new Set),D(lt,dc,new WeakMap);let VA=lt;function Z_(s){return`${(s*100).toFixed(2)}%`}var Xg,Xb,Yb,Yg,el,tl,Jb,V0,ZB;const zv=class zv{constructor(e,t,n,i){D(this,V0);D(this,Xg,[]);D(this,Xb,new Map);D(this,Yb,null);D(this,Yg,0);D(this,el,0);D(this,tl,0);x(this,Yg,e),x(this,Xg,t),x(this,el,n.rawDims.pageWidth),x(this,tl,n.rawDims.pageHeight),x(this,Yb,i)}render(){const e=document.createElement("div");e.className="textLayerImages";for(let t=0;t<f(this,Xg).length;t+=6){const n=B(this,V0,ZB).call(this,f(this,Xg).subarray(t,t+6));n&&e.append(n)}return e.addEventListener("contextmenu",t=>{var y;if(!(t.target instanceof HTMLCanvasElement))return;const n=t.target,i=f(this,Xb).get(n);if(!i)return;const r=(y=f(zv,Jb))==null?void 0:y.deref();if(r===n)return;r&&(r.width=0,r.height=0),x(zv,Jb,new WeakRef(n));const{inverseTransform:o,x1:a,y1:c,width:l,height:u}=i,h=f(this,Yb).call(this),d=Math.ceil(a*h.width),p=Math.ceil(c*h.height),m=Math.floor((a+l/f(this,el))*h.width),v=Math.floor((c+u/f(this,tl))*h.height);n.width=m-d,n.height=v-p;const g=n.getContext("2d");g.setTransform(...o),g.translate(-d,-p),g.drawImage(h,0,0)}),e}};Xg=new WeakMap,Xb=new WeakMap,Yb=new WeakMap,Yg=new WeakMap,el=new WeakMap,tl=new WeakMap,Jb=new WeakMap,V0=new WeakSet,ZB=function([e,t,n,i,r,o]){const a=Math.hypot((r-e)*f(this,el),(o-t)*f(this,tl)),c=Math.hypot((n-e)*f(this,el),(i-t)*f(this,tl));if(a<f(this,Yg)||c<f(this,Yg))return null;const l=[(r-e)*f(this,el)/a,(o-t)*f(this,tl)/a,(n-e)*f(this,el)/c,(i-t)*f(this,tl)/c,0,0],u=Be.inverseTransform(l),h=document.createElement("canvas");return h.className="textLayerImagePlaceholder",h.width=0,h.height=0,Object.assign(h.style,{opacity:0,position:"absolute",left:Z_(e),top:Z_(t),width:Z_(a/f(this,el)),height:Z_(c/f(this,tl)),transformOrigin:"0% 0%",transform:`matrix(${l.join(",")})`}),f(this,Xb).set(h,{inverseTransform:u,width:a,height:c,x1:e,y1:t}),h},D(zv,Jb,null);let XA=zv;globalThis._pdfjsTestingUtils={HighlightOutliner:CA};globalThis.pdfjsLib={AbortException:ch,AnnotationEditorLayer:UA,AnnotationEditorParamsType:xt,AnnotationEditorType:Ct,AnnotationEditorUIManager:Lf,AnnotationLayer:_A,AnnotationMode:Zc,AnnotationType:mn,applyOpacity:Iee,build:qte,ColorPicker:d0,createValidAbsoluteUrl:ID,CSSConstants:xee,DOMSVGFactory:p0,DrawLayer:VA,FeatureTest:Ts,fetchData:cM,findContrastColor:Ree,getDocument:QN,getFilenameFromUrl:Tee,getPdfFilenameFromUrl:Aee,getRGB:i_,getRGBA:n_,getUuid:LD,GlobalWorkerOptions:sl,ImageKind:CS,InvalidPDFException:bT,isDataScheme:pk,isPdfFile:hM,isValidExplicitDest:Jee,makeArr:aM,makeMap:lM,makeObj:ST,MathClamp:Ns,noContextMenu:Ho,normalizeUnicode:kee,OPS:Il,OutputScale:ll,PasswordResponses:mee,PDFDataRangeTransport:XN,PDFDateString:c0,PDFWorker:hy,PermissionFlag:gee,PixelsPerInch:uh,RenderingCancelledException:uM,renderRichText:OD,ResponseException:l0,setLayerDimensions:Rf,shadow:Tt,SignatureExtractor:fc,stopEvent:js,SupportedImageMimeTypes:wT,TextLayer:uy,TextLayerImages:XA,TouchManager:h0,updateUrlHash:RD,Util:Be,VerbosityLevel:uk,version:Gte,XfaLayer:PD};const bse="/static/dist/assets/pdf.worker.min.mjs",_se={key:0,class:"pdf-preview-loading"},Sse={key:1,class:"pdf-preview-error"},wse=at({name:"PdfPreview",__name:"PdfPreview",props:{source:{}},setup(s){sl.workerSrc=bse;const e=s,t=pe(null),n=pe(!0),i=pe("");let r=null,o=[];function a(){const h=t.value;h&&h.querySelectorAll("canvas").forEach(d=>d.remove())}function c(){o.forEach(h=>{try{h.cancel()}catch{}}),o=[]}async function l(){if(c(),a(),r){try{await r.destroy()}catch{}r=null}}async function u(){const h=t.value;if(!(!h||!e.source)){await l(),n.value=!0,i.value="";try{const d=await fetch(e.source,{credentials:"same-origin"});if(!d.ok)throw new Error(d.statusText||"PDF 加载失败");const p=await d.arrayBuffer();if(!p.byteLength)throw new Error("PDF 内容为空");r=await QN({data:p}).promise;const v=r.numPages,g=h.clientWidth;for(let y=1;y<=v;y++){const b=await r.getPage(y),_=b.getViewport({scale:1}),w=g>0?g/_.width:1,S=b.getViewport({scale:w}),C=document.createElement("canvas");C.className="pdf-preview-page",C.style.display="block",C.style.width="100%",C.style.height="auto";const T=window.devicePixelRatio||1;C.width=Math.floor(S.width*T),C.height=Math.floor(S.height*T),h.appendChild(C);const k=C.getContext("2d");if(!k)continue;k.scale(T,T);const A=b.render({canvasContext:k,viewport:S});o.push(A),await A.promise,o=o.filter(M=>M!==A)}n.value=!1}catch(d){const p=(d==null?void 0:d.message)||"PDF 渲染失败";if(p.toLowerCase().includes("cancel"))return;i.value=p,n.value=!1}}}return Cn(()=>{u()}),xn(()=>{l()}),Xe(()=>e.source,()=>{u()}),(h,d)=>(F(),$("div",{ref_key:"containerRef",ref:t,class:"pdf-preview"},[n.value?(F(),$("div",_se,[...d[0]||(d[0]=[E("span",{class:"pdf-preview-spinner"},null,-1),E("span",null,"PDF 加载中...",-1)])])):i.value?(F(),$("div",Sse,ae(i.value),1)):ge("",!0)],512))}}),kse=Qt(wse,[["__scopeId","data-v-f74a8bf6"]]),Cse={class:"show-file-card"},Tse={class:"sfc-header"},Ase=["title"],Ese={class:"sfc-actions"},Mse=["disabled"],xse={key:0,class:"sfc-loading"},Ise={key:1,class:"sfc-error"},Rse=["innerHTML"],Lse={class:"sfc-csv-table"},Pse={key:0,class:"sfc-csv-meta"},Ose=["innerHTML"],Dse=["src","alt"],Nse=5*60*1e3,Bse=at({name:"ShowFileCard",__name:"ShowFileCard",props:{path:{},name:{},type:{},description:{},preview:{}},setup(s){const e=new Map;function t(V){const N=e.get(V);return N?Date.now()-N.ts>Nse?(e.delete(V),null):N.content:null}function n(V,N){e.set(V,{content:N,ts:Date.now()})}const i=s,r=pe(!1),o=pe(""),a=pe(""),c=pe(!1),l=pe(""),u=pe(!1),h=ye(()=>i.type||k(i.path)),d=ye(()=>i.name||i.path.split("/").pop()||"file"),p=ye(()=>i.preview==="off"?!1:["text","code","json","csv","markdown","image","pdf"].includes(h.value)),m=ye(()=>["text","code","json","csv","markdown"].includes(h.value)),v=ye(()=>/\.html?$/i.test(i.path)),g=ye(()=>typeof window.AndroidDownloadBridge<"u"||typeof window.AndroidThemeBridge<"u"),y=ye(()=>AD(i.path)),b=ye(()=>{if(!a.value)return"";let V=a.value;if(h.value==="json")try{V=JSON.stringify(JSON.parse(V),null,2)}catch{}return gT(V,y.value)}),_=ye(()=>a.value?k2(a.value,!1):""),w=ye(()=>{if(h.value!=="csv"||!a.value)return null;const V=a.value.split(/\r?\n/).filter(ee=>ee.trim()),N=ee=>{const ie=[];let ve="",le=!1;for(let oe=0;oe<ee.length;oe++){const I=ee[oe];le?I==='"'&&ee[oe+1]==='"'?(ve+='"',oe++):I==='"'?le=!1:ve+=I:I==='"'?le=!0:I===","?(ie.push(ve),ve=""):ve+=I}return ie.push(ve),ie},O=100,H=N(V[0]||""),G=V.slice(1,O+1).map(N);return{header:H,rows:G,truncated:V.length>O+1}}),S=ye(()=>{var V;return((V=w.value)==null?void 0:V.header)||[]}),C=ye(()=>{var V;return((V=w.value)==null?void 0:V.rows)||[]}),T=ye(()=>{var V;return((V=w.value)==null?void 0:V.truncated)||!1});function k(V){const N={".txt":"text",".md":"markdown",".markdown":"markdown",".json":"json",".json5":"json",".csv":"csv",".tsv":"csv",".yaml":"text",".yml":"text",".toml":"text",".ini":"text",".cfg":"text",".conf":"text",".log":"text",".js":"code",".ts":"code",".jsx":"code",".tsx":"code",".vue":"code",".py":"code",".rb":"code",".go":"code",".rs":"code",".java":"code",".c":"code",".h":"code",".cpp":"code",".hpp":"code",".cs":"code",".php":"code",".swift":"code",".kt":"code",".sh":"code",".bash":"code",".html":"code",".htm":"code",".css":"code",".scss":"code",".less":"code",".xml":"code",".svg":"image",".sql":"code",".png":"image",".jpg":"image",".jpeg":"image",".gif":"image",".webp":"image",".bmp":"image",".ico":"image",".avif":"image",".pdf":"pdf"},O=V.toLowerCase(),H=O.lastIndexOf(".");if(H>=0){const G=O.slice(H);if(N[G])return N[G]}return"binary"}function A(){return`/api/file/content?path=${encodeURIComponent(i.path)}`}function M(V){const N=/\b(?:src|href)\s*=\s*["']([^"']*)["']/gi;let O;for(;O=N.exec(V);){const H=(O[1]||"").trim();if(!(!H||H.startsWith("#"))&&!/^(https?:)?\/\//i.test(H)&&!/^(data|blob|mailto|tel|javascript):/i.test(H))return!0}return!1}async function R(){if(!u.value){u.value=!0,o.value="";try{let V=a.value||t(i.path)||"";if(!V){const N=await fetch(A());if(!N.ok){let O=N.statusText;try{O=(await N.json()).error||O}catch{}o.value=O||"加载失败";return}V=await N.text(),n(i.path,V),a.value=V}if(!V.trim()){o.value="文件内容为空";return}xD({srcdoc:mT(V),allowScripts:!0,title:d.value,notice:M(V)?"含外部资源引用,预览可能不完整":void 0})}catch(V){o.value=V.message||"网络错误"}finally{u.value=!1}}}async function P(){if(p.value){if(o.value="",!["image","pdf"].includes(h.value)){const V=t(i.path);if(V!==null){a.value=V;return}}r.value=!0;try{if(["image","pdf"].includes(h.value))l.value=A();else{const V=await fetch(A());if(!V.ok){let O=V.statusText;try{O=(await V.json()).error||O}catch{}o.value=O||"加载失败";return}const N=await V.text();a.value=N,n(i.path,N)}}catch(V){o.value=V.message||"网络错误"}finally{r.value=!1}}}async function L(){const V=`/api/download/file?path=${encodeURIComponent(i.path)}`,N=i.path.split("/").pop()||"file",O=window.AndroidDownloadBridge;if(O&&typeof O.downloadFile=="function")try{O.downloadFile(V,N);return}catch(H){console.warn("[ShowFileCard] Android 桥接下载失败,回退:",H)}try{const H=await fetch(V);if(!H.ok){let ve=H.statusText;try{ve=(await H.json()).error||ve}catch{}throw new Error(ve||"下载失败")}const G=await H.blob(),ee=URL.createObjectURL(G),ie=document.createElement("a");ie.href=ee,ie.download=N,document.body.appendChild(ie),ie.click(),document.body.removeChild(ie),setTimeout(()=>URL.revokeObjectURL(ee),1e3)}catch(H){console.warn("[ShowFileCard] 下载失败:",H),window.open(V,"_blank")}}async function z(){if(a.value)try{await navigator.clipboard.writeText(a.value),c.value=!0,setTimeout(()=>{c.value=!1},2e3)}catch{}}function Q(){l.value&&window.open(l.value,"_blank")}function W(){o.value="图片加载失败"}return Cn(()=>{p.value&&P()}),(V,N)=>(F(),$("div",Cse,[E("div",Tse,[N[1]||(N[1]=E("span",{class:"sfc-file-icon","aria-hidden":"true"},null,-1)),E("span",{class:"sfc-name",title:d.value},ae(d.value),9,Ase),E("div",Ese,[v.value?(F(),$("button",{key:0,type:"button",class:"sfc-btn",disabled:u.value,onClick:R},ae(u.value?"加载中…":"预览"),9,Mse)):ge("",!0),m.value?(F(),$("button",{key:1,type:"button",class:"sfc-btn",onClick:z},ae(c.value?"已复制":"复制"),1)):ge("",!0),E("button",{type:"button",class:"sfc-btn sfc-btn-download",onClick:L},"下载")])]),p.value?(F(),$("div",{key:0,class:ke(["sfc-preview",{"sfc-preview--csv":h.value==="csv"}])},[r.value?(F(),$("div",xse,[...N[2]||(N[2]=[E("span",{class:"sfc-spinner"},null,-1),E("span",null,"加载中...",-1)])])):o.value?(F(),$("div",Ise,ae(o.value),1)):h.value==="text"||h.value==="code"||h.value==="json"?(F(),$("pre",{key:2,class:"sfc-code",innerHTML:b.value},null,8,Rse)):h.value==="csv"?(F(),$(Ie,{key:3},[E("div",{class:ke(["sfc-csv-scroll",{"sfc-csv-scroll--loading":r.value}])},[E("table",Lse,[E("thead",null,[E("tr",null,[(F(!0),$(Ie,null,tt(S.value,(O,H)=>(F(),$("th",{key:H},ae(O),1))),128))])]),E("tbody",null,[(F(!0),$(Ie,null,tt(C.value,(O,H)=>(F(),$("tr",{key:H},[(F(!0),$(Ie,null,tt(O,(G,ee)=>(F(),$("td",{key:ee},ae(G),1))),128))]))),128))])])],2),T.value?(F(),$("div",Pse," 仅显示前 "+ae(C.value.length)+" 行,完整内容请下载查看 ",1)):ge("",!0)],64)):h.value==="markdown"?(F(),$("div",{key:4,class:"sfc-md",innerHTML:_.value},null,8,Ose)):h.value==="image"?(F(),$("img",{key:5,class:ke(["sfc-image",{"sfc-image--android":g.value}]),src:l.value,alt:d.value,onClick:N[0]||(N[0]=O=>!g.value&&Q()),onError:W},null,42,Dse)):h.value==="pdf"?(F(),Wt(kse,{key:6,source:l.value},null,8,["source"])):ge("",!0)],2)):ge("",!0)]))}}),Fse=Qt(Bse,[["__scopeId","data-v-4a12c216"]]);let $se=0,t1=0;const eF="v2-lite-throttled",s1=200;let n1=0;const i1=500;function y0(){var s;if(typeof window>"u")return"off";try{const e=window.__SHOW_IMAGE_DEBUG__;if(e===!1||e==="0"||e==="off"||e==="false")return"off";if(e==="verbose")return"verbose";if(e===!0||e==="1"||e==="lite")return"lite";const t=(s=window.localStorage)==null?void 0:s.getItem("showImageDebug");return t==="0"||t==="off"||t==="false"||t==="none"?"off":t==="verbose"?"verbose":t==="1"||t==="true"||t==="lite"?"lite":"off"}catch{return"off"}}function Ia(s,e={}){const t=y0();if(t!=="off"&&!(t==="lite"&&!["observer:setup","observer:show-image-mutation","render:start","render:end"].includes(s))&&!(t1>=s1)){if(t1+=1,t1===s1){console.warn("[SHOW_IMAGE_DEBUG]","log-limit-reached",{max:s1,version:eF});return}console.log("[SHOW_IMAGE_DEBUG]",s,e)}}function Hse(){var s;if(typeof window>"u")return!1;try{const e=window.__SHOW_HTML_DEBUG__;if(e===!0||e==="1")return!0;if(e===!1||e==="0")return!1;const t=(s=window.localStorage)==null?void 0:s.getItem("showHtmlDebug");return t==="1"||t==="true"}catch{return!1}}function ho(s,e={}){if(Hse()&&!(n1>=i1)){if(n1+=1,n1===i1){console.warn("[SHOW_HTML_DEBUG]","log-limit-reached",{max:i1});return}console.log("[SHOW_HTML_DEBUG]",s,e)}}function YA(s=1600){if(!(typeof window>"u"))try{window.__SHOW_TAG_DRAWING_UNTIL__=Date.now()+s}catch{}}function Io(s){if(!s)return"null";if(s.nodeType===Node.TEXT_NODE)return`TEXT(${(s.textContent||"").replace(/\s+/g," ").trim().slice(0,80)})`;if(s.nodeType===Node.ELEMENT_NODE){const e=s,t=e.tagName.toLowerCase();return t==="show_image"||t==="show-image"?`SHOW_IMAGE(src=${e.getAttribute("src")||""})`:`${t.toUpperCase()}`}return`NODE(${s.nodeType})`}function UR(s=document){if(!s||!(s instanceof Node))return[];const e=document.createTreeWalker(s,NodeFilter.SHOW_ALL),t=[];let n=e.currentNode;for(;n;){if(n.nodeType===Node.TEXT_NODE){const i=(n.textContent||"").replace(/\s+/g," ").trim();i&&t.push(`TEXT(${i.slice(0,40)})`)}else if(n.nodeType===Node.ELEMENT_NODE){const i=n,r=i.tagName.toLowerCase();r==="show_image"||r==="show-image"?t.push(`SHOW_IMAGE(${i.getAttribute("src")||""})`):(r==="show_html"||r==="show-html")&&t.push(`SHOW_HTML(ratio=${nF(i)},js=${iF(i)})`)}n=e.nextNode()}return t.slice(0,200)}function Use(s){if(!s)return"";const e=s.trim();if(/^https?:\/\//i.test(e)||e.startsWith("/user_upload/"))return e;const t=e.toLowerCase().indexOf("/user_upload/");return t>=0?"/user_upload/"+e.slice(t+13):e.startsWith("/")||e.startsWith("./")||e.startsWith("../")?e:""}function WR(s,e){if(!s)return e;const t=Number.parseInt(s.trim(),10);return!Number.isFinite(t)||t<=0?e:Math.min(4096,t)}const tF=["1:1","16:9","9:16","4:3","3:4"],sF={"1:1":1,"16:9":16/9,"9:16":9/16,"4:3":4/3,"3:4":3/4};function Wse(s){if(!s)return"1:1";const e=s.trim().toLowerCase().replace(/[x/]/g,":").replace(/\s+/g,"");return tF.includes(e)?e:"1:1"}function zse(s,e){if(!Number.isFinite(s)||!Number.isFinite(e)||s<=0||e<=0)return"1:1";const t=s/e;let n="1:1",i=Number.POSITIVE_INFINITY;for(const r of tF){const o=Math.abs(sF[r]-t);o<i&&(i=o,n=r)}return n}function nF(s){const e=s.getAttribute("ratio");if(e)return Wse(e);const t=WR(s.getAttribute("width"),0),n=WR(s.getAttribute("height"),0);return t>0&&n>0?zse(t,n):"1:1"}function jse(s){if(!s)return"off";const e=s.trim().toLowerCase();return["on","1","true","yes","enabled","enable"].includes(e)?"on":"off"}function iF(s){return jse(s.getAttribute("js"))}function zR(s){if(!s)return"";try{return decodeURIComponent(escape(atob(s)))}catch{return""}}function jR(s){return s?s.replace(/expression\s*\([^)]*\)/gi,"").replace(/url\s*\(\s*['"]?\s*javascript:[^)]+\)/gi,"url(about:blank)").replace(/@import[^;]+;/gi,""):""}function Vse(s){if(!s)return"";const e="__SHOW_HTML_ROOT_SELECTOR__";return s.replace(/\bhtml\s*,\s*body\b/gi,e).replace(/\bbody\s*,\s*html\b/gi,e).replace(/\bhtml\b/gi,e).replace(/\bbody\b/gi,e).replace(new RegExp(e,"g"),".show-html-root")}function Gse(s){const e=ree.sanitize(s||"",{USE_PROFILES:{html:!0,svg:!0,svgFilters:!0,mathMl:!0},FORBID_TAGS:["script","noscript","iframe","object","embed","link"],ALLOW_DATA_ATTR:!1,ALLOW_ARIA_ATTR:!0}),n=new DOMParser().parseFromString(`<body>${e}</body>`,"text/html");return Array.from(n.body.querySelectorAll("*")).forEach(r=>{Array.from(r.attributes).forEach(o=>{const a=o.name.toLowerCase(),c=o.value||"";if(a.startsWith("on")){r.removeAttribute(o.name);return}if((a==="src"||a==="href"||a==="xlink:href")&&/^\s*javascript:/i.test(c)){r.removeAttribute(o.name);return}a==="style"&&r.setAttribute("style",jR(c))})}),n.querySelectorAll("style").forEach(r=>{r.textContent=Vse(jR(r.textContent||""))}),n.body.innerHTML}function qse(s){return s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}const rF="__showHtmlCardControls";function oF(s){return s[rF]||null}function Kse(s,e){const t=oF(s);if(t){YA(1200),e&&(e.classList.remove("is-refreshing"),e.offsetWidth,e.classList.add("is-refreshing"),window.setTimeout(()=>e.classList.remove("is-refreshing"),720));try{t.onRefresh()}catch(n){ho("refresh:error",{message:n instanceof Error?n.message:String(n||"")})}}}let mc=null,Cp=null,VR=!1;function vc(){mc&&(mc.remove(),mc=null,Cp=null)}function Qse(){VR||typeof document>"u"||(VR=!0,document.addEventListener("click",s=>{if(!mc)return;const e=s.target;e&&mc.contains(e)||e&&(Cp!=null&&Cp.contains(e))||vc()},!0),document.addEventListener("keydown",s=>{s.key==="Escape"&&mc&&(s.stopPropagation(),vc())},!0),window.addEventListener("resize",vc),document.addEventListener("scroll",()=>{mc&&vc()},!0))}function GR(s){const e=document.createElement("button");return e.type="button",e.className="show-html-card-menu__item",e.textContent=s,e}function Xse(s,e){if(Qse(),mc&&Cp===s){vc();return}vc();const t=document.createElement("div");t.className="show-html-card-menu",t.setAttribute("role","menu");const n=GR("刷新");n.onclick=c=>{c.preventDefault(),c.stopPropagation(),vc(),Kse(e,s)};const i=GR("全屏");i.onclick=c=>{var h;c.preventDefault(),c.stopPropagation();const l=oF(e);vc();const u=(h=l==null?void 0:l.getFullscreenPayload)==null?void 0:h.call(l);!u||!u.srcdoc||xD(u)},t.appendChild(n),t.appendChild(i),document.body.appendChild(t);const r=s.getBoundingClientRect(),o=t.offsetWidth;let a=Math.round(r.right-o);a=Math.max(8,Math.min(a,window.innerWidth-o-8)),t.style.left=`${a}px`,t.style.top=`${Math.round(r.bottom+6)}px`,mc=t,Cp=s}function qR(s,e){s[rF]=e;let t=s.querySelector(":scope > .chat-inline-card__toolbar");t||(t=document.createElement("div"),t.className="chat-inline-card__toolbar",s.appendChild(t));let n=t.querySelector(":scope > .chat-inline-card__menu-btn");n||(n=document.createElement("button"),n.type="button",n.className="chat-inline-card__menu-btn",n.title="卡片操作",n.setAttribute("aria-label","卡片操作"),n.setAttribute("aria-haspopup","menu"),n.textContent="⋯",t.appendChild(n)),n.onclick=i=>{i.preventDefault(),i.stopPropagation(),Xse(n,s)}}function aF(s=document){if(!s)return;const t=y0()==="verbose",n=++$se,i=Array.from(s.querySelectorAll("show_image:not([data-rendered]), show-image:not([data-rendered])")),r=Array.from(s.querySelectorAll("show_html:not([data-rendered]), show-html:not([data-rendered])")),o=Array.from(s.querySelectorAll("show_file:not([data-rendered]), show-file:not([data-rendered])")),a=!!s.querySelector('a.md-download-link:not([data-download-bound]), a[data-download="1"]:not([data-download-bound])');if((r.length>0||o.length>0)&&YA(),!t&&i.length===0&&r.length===0&&o.length===0&&!a)return;const c=s;Ia("render:start",{renderId:n,rootType:(c==null?void 0:c.nodeType)===Node.ELEMENT_NODE?c.tagName.toLowerCase():`nodeType:${c==null?void 0:c.nodeType}`,pendingImageCount:i.length,pendingHtmlCount:r.length,pendingFileCount:o.length,orderBefore:UR(s)}),t&&Ia("render:pending-show-images",{renderId:n,count:i.length,nodes:i.map(l=>l.getAttribute("src")||"")}),i.forEach(l=>{if(!l.isConnected||l.hasAttribute("data-rendered"))return;if(t&&Ia("render:node-start",{renderId:n,src:l.getAttribute("src")||"",parent:Io(l.parentNode),prevSibling:Io(l.previousSibling),nextSibling:Io(l.nextSibling),childCount:l.childNodes.length,childPreview:Array.from(l.childNodes).slice(0,6).map(g=>Io(g))}),l.parentNode&&l.firstChild){const g=l.parentNode,y=l.nextSibling,b=Array.from(l.childNodes);t&&Ia("render:unwrap-children",{renderId:n,src:l.getAttribute("src")||"",moveCount:b.length,ref:Io(y),children:b.slice(0,10).map(_=>Io(_))}),b.forEach(_=>g.insertBefore(_,y))}const u=l.getAttribute("src")||"",h=Use(u);if(!h){l.setAttribute("data-rendered","1"),l.setAttribute("data-rendered-error","invalid-src"),t&&Ia("render:invalid-src",{renderId:n,rawSrc:u});return}const d=l.getAttribute("alt")||"",p=qse(d.trim()),m=document.createElement("figure");m.className="chat-inline-card chat-inline-card--image chat-inline-image";const v=document.createElement("img");if(v.loading="lazy",v.src=h,v.alt=p,v.onerror=()=>{m.classList.add("chat-inline-card--error","chat-inline-image--error");const g=document.createElement("div");g.className="chat-inline-card__error chat-inline-image__error",g.textContent="图片加载失败",m.appendChild(g)},m.appendChild(v),p){const g=document.createElement("figcaption");g.className="chat-inline-card__caption",g.innerHTML=p,m.appendChild(g)}l.replaceChildren(m),l.setAttribute("data-rendered","1"),t&&Ia("render:node-done",{renderId:n,rawSrc:u,mappedSrc:h,alt:d})}),r.forEach(l=>{if(YA(),!l.isConnected)return;const u=!!l.closest(".streaming-text"),h=Jse(l),d=l.getAttribute("data-partial")==="1",p=l.getAttribute("data-encoded")||"",m=iF(l),v=nF(l);let g=v;if(u&&!d&&p){const k=yv.get(h);(!k||k.encoded!==p||k.ratioKey!==g)&&yv.set(h,{encoded:p,ratioKey:g})}else u||yv.delete(h);const y=u?yv.get(h):null,b=(y==null?void 0:y.encoded)||p;if(y!=null&&y.ratioKey&&(g=y.ratioKey),u){const k=bv.get(h);k?g!==k&&(k==="1:1"||g!=="1:1")?(g=v,bv.set(h,g)):g=k:bv.set(h,g)}else bv.delete(h);if(l.style.setProperty("--show-html-ar",String(sF[g]||1)),ho("render:node-seen",{renderId:n,inStreaming:u,pathKey:h,hasRendered:l.hasAttribute("data-rendered"),ratioAttr:l.getAttribute("ratio")||"",jsMode:m,ratioKey:g,partial:l.getAttribute("data-partial")||"",encodedLength:p.length,effectiveEncodedLength:b.length,innerLength:(l.innerHTML||"").length}),m==="on"&&d){let k=fw.get(h);if(!k){const A=document.createElement("div");A.className="chat-inline-card chat-inline-card--html chat-inline-card--pending chat-inline-html chat-inline-html--pending";const M=document.createElement("div");M.className="chat-inline-card__body chat-inline-html__host chat-inline-html__host--pending";const R=document.createElement("div");R.className="chat-inline-card__pending-tip chat-inline-html__pending-tip",R.textContent="正在渲染内容...",M.appendChild(R),A.appendChild(M),k={wrapper:A,host:M,tip:R},fw.set(h,k)}l.replaceChildren(k.wrapper),l.setAttribute("data-rendered","1"),ho("render:node-js-pending",{renderId:n,pathKey:h,ratioKey:g});return}if(m==="on"){const k=b?zR(b):l.innerHTML||"",A=mT(k);let M=JA.get(h);if(!M){const P=document.createElement("div");P.className="chat-inline-card chat-inline-card--html chat-inline-card--iframe chat-inline-html chat-inline-html--iframe";const L=document.createElement("iframe");L.className="chat-inline-html__iframe",L.setAttribute("sandbox","allow-scripts"),L.setAttribute("referrerpolicy","no-referrer"),L.setAttribute("loading","lazy"),L.setAttribute("allow","fullscreen 'none'"),P.appendChild(L),M={encoded:"",ratioKey:"1:1",srcdoc:"",wrapper:P,iframe:L},JA.set(h,M)}qR(M.wrapper,{onRefresh:()=>{const P=(M==null?void 0:M.srcdoc)||A;M.iframe.srcdoc='<!doctype html><html><head><meta charset="utf-8"></head><body></body></html>',requestAnimationFrame(()=>{M!=null&&M.iframe&&(M.iframe.srcdoc=P)}),ho("refresh:iframe",{pathKey:h,ratioKey:(M==null?void 0:M.ratioKey)||g,srcdocLength:P.length})},getFullscreenPayload:()=>{const P=(M==null?void 0:M.srcdoc)||"";return P?{srcdoc:P,allowScripts:!0}:null}});const R=M.encoded!==b||M.ratioKey!==g||M.srcdoc!==A;R&&(M.iframe.srcdoc=A,M.encoded=b,M.ratioKey=g,M.srcdoc=A),(!u||d||R||!l.hasAttribute("data-rendered"))&&l.replaceChildren(M.wrapper),l.setAttribute("data-rendered","1"),fw.delete(h),ho("render:node-js-iframe",{renderId:n,pathKey:h,ratioKey:g,encodedLength:b.length,srcdocLength:A.length,needsUpdate:R});return}if(u){const k=Date.now(),A=hw.get(h)||0;if(k-A<KR){const M=dw.get(h);M&&(l.replaceChildren(M.wrapper),l.setAttribute("data-rendered","1"),ho("render:node-throttled-rehydrate",{renderId:n,pathKey:h,ratioKey:g})),ho("render:node-throttled",{renderId:n,pathKey:h,now:k,lastTs:A,interval:KR});return}hw.set(h,k)}else hw.delete(h);const _=b?zR(b):l.innerHTML||"",w=Gse(_);ho("render:node-content",{renderId:n,pathKey:h,jsMode:m,encodedLength:p.length,effectiveEncodedLength:b.length,rawLength:_.length,safeLength:w.length,ratioKey:g});let S=dw.get(h);if(!S){const k=document.createElement("div");k.className="chat-inline-card chat-inline-card--html chat-inline-html";const A=document.createElement("div");A.className="chat-inline-card__body chat-inline-html__host";const M=A.attachShadow({mode:"open"}),R=document.createElement("style");R.textContent=`
:host {
display: block;
box-sizing: border-box;
width: 100%;
height: 100%;
overflow: auto;
background: transparent;
color: inherit;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
font-size: 14px;
line-height: 1.5;
}
*, *::before, *::after {
box-sizing: border-box;
}
.show-html-root {
width: 100%;
height: 100%;
min-height: 100%;
overflow: auto;
background: transparent;
scrollbar-width: thin;
scrollbar-color: rgba(121, 109, 94, 0.48) transparent;
}
.show-html-root::-webkit-scrollbar {
width: 8px;
height: 8px;
}
.show-html-root::-webkit-scrollbar-track {
background: transparent;
}
.show-html-root::-webkit-scrollbar-thumb {
background: rgba(121, 109, 94, 0.48);
border-radius: 8px;
}
.show-html-root::-webkit-scrollbar-thumb:hover {
background: rgba(121, 109, 94, 0.62);
}
`;const P=document.createElement("div");P.className="show-html-root",M.appendChild(R),M.appendChild(P),k.appendChild(A),S={encoded:"",safeHtml:"",ratioKey:"1:1",wrapper:k,host:A,root:P},dw.set(h,S)}qR(S.wrapper,{onRefresh:()=>{const k=(S==null?void 0:S.safeHtml)||"";S.root.innerHTML="",requestAnimationFrame(()=>{S!=null&&S.root&&(S.root.innerHTML=k)}),ho("refresh:shadow-root",{pathKey:h,ratioKey:(S==null?void 0:S.ratioKey)||g,safeLength:k.length})},getFullscreenPayload:()=>{const k=(S==null?void 0:S.safeHtml)||"";return k.trim()?{srcdoc:mT(k),allowScripts:!1}:null}});const C=S.encoded!==b||S.ratioKey!==g;C?(S.root.innerHTML=w,S.encoded=b,S.safeHtml=w,S.ratioKey=g,ho("render:node-persistent-update",{renderId:n,pathKey:h,encodedLength:b.length,ratioKey:g})):ho("render:node-persistent-reuse",{renderId:n,pathKey:h,encodedLength:b.length}),(!u||d||C||!l.hasAttribute("data-rendered"))&&l.replaceChildren(S.wrapper),l.setAttribute("data-rendered","1");const T=S.wrapper.getBoundingClientRect();ho("render:node-done",{renderId:n,pathKey:h,jsMode:m,ratioKey:g,rect:{x:Math.round(T.x),y:Math.round(T.y),w:Math.round(T.width),h:Math.round(T.height)},partial:l.getAttribute("data-partial")||"",inStreaming:u}),t&&Ia("render:show-html-done",{renderId:n,ratioKey:g,contentLength:_.length})}),o.forEach(l=>{!l.isConnected||l.hasAttribute("data-rendered")||(sne(l),l.setAttribute("data-rendered","1"))}),nne(s),Ia("render:end",{renderId:n,orderAfter:UR(s)})}let Ra=null,Tp=null,r1=!1,Rl=null,uw=null;const hw=new Map,KR=180,yv=new Map,bv=new Map,dw=new Map,fw=new Map,JA=new Map;let Uv=null,zh=null,ZA=!1,jh=null,pw=0;const o1=300,eE=new Map;function Yse(s){if(r1)return;r1=!0;const e=()=>{r1=!1,aF(s)};if(typeof queueMicrotask=="function"){queueMicrotask(e);return}Promise.resolve().then(e)}function QR(){return document.querySelector(".messages-area")}function lF(){var s;if(typeof window>"u")return!1;try{const e=window.__LAYOUT_DEBUG__;if(e===!1||e==="0")return!1;if(e===!0||e==="1")return!0;const t=(s=window.localStorage)==null?void 0:s.getItem("layoutDebug");return t==="0"||t==="false"?!1:t==="1"||t==="true"}catch{return!1}}function Em(s,e={},t=s){if(!lF()||pw>=o1)return;const n=Date.now(),i=eE.get(t)||0;if(!(n-i<120)){if(eE.set(t,n),pw+=1,pw===o1){console.warn("[LAYOUT_DEBUG]","log-limit-reached",{max:o1});return}console.log("[LAYOUT_DEBUG]",s,e)}}function Mm(s){if(!s)return null;const e=s.getBoundingClientRect();return{className:s.className||"",x:Math.round(e.x),y:Math.round(e.y),width:Math.round(e.width),height:Math.round(e.height)}}function cF(){if(ZA||!lF())return;const e=[".main-container",".workspace-region",".workspace-panel",".chat-container",".messages-area"].map(n=>document.querySelector(n)).filter(n=>!!n);if(e.length===0){Em("layout:setup-wait",{reason:"targets-not-mounted"},"layout:setup-wait"),jh&&window.clearTimeout(jh),jh=window.setTimeout(()=>{jh=null,cF()},250);return}ZA=!0,Em("layout:setup",{trackedCount:e.length,tracked:e.map(n=>n.className||n.tagName.toLowerCase())});const t=()=>{Em("layout:snapshot",{window:{innerWidth:window.innerWidth,innerHeight:window.innerHeight},main:Mm(document.querySelector(".main-container")),workspace:Mm(document.querySelector(".workspace-region")),panel:Mm(document.querySelector(".workspace-panel")),chat:Mm(document.querySelector(".chat-container")),messages:Mm(document.querySelector(".messages-area"))},"layout:snapshot")};t(),Uv=new MutationObserver(n=>{const i=n.filter(r=>{if(!(r.target instanceof Element))return!1;const o=typeof r.target.className=="string"?r.target.className:r.target.getAttribute("class")||"";return r.type==="attributes"&&(e.some(a=>a===r.target)||o.includes("chat-container")||o.includes("workspace-panel")||o.includes("main-container"))});i.length&&(Em("layout:mutation",{count:i.length,items:i.slice(0,8).map(r=>({attr:r.attributeName,target:Io(r.target)}))}),t())}),Uv.observe(document.body,{subtree:!0,attributes:!0,attributeFilter:["class","style"]}),zh=new ResizeObserver(n=>{n.length&&(Em("layout:resize",{items:n.slice(0,8).map(i=>({target:Io(i.target),width:Math.round(i.contentRect.width),height:Math.round(i.contentRect.height)}))}),t())}),e.forEach(n=>zh==null?void 0:zh.observe(n)),window.addEventListener("resize",t)}function Jse(s){const e=(a,c)=>{const u=Array.from(document.querySelectorAll(c)).indexOf(a);return u>=0?u:-1},t=[],n=s.closest(".message-block");n&&t.push(`msg:${e(n,".message-block")}`);const i=s.closest(".action-item");i&&t.push(`action:${e(i,".action-item")}`);const r=s.closest(".text-content");r&&t.push(`text:${e(r,".text-content")}`);let o=s;for(;o&&o!==document.body&&t.length<12;){const a=o.parentElement;if(!a)break;const c=Array.prototype.indexOf.call(a.children,o);if(t.push(`${o.tagName.toLowerCase()}:${c}`),o.classList.contains("text-content"))break;o=a}return t.reverse().join("/")}function Zse(){if(Ra||Tp)return;cF();const s=()=>{const e=QR();if(!e){Rl&&window.clearTimeout(Rl),Rl=window.setTimeout(s,250);return}Rl&&(window.clearTimeout(Rl),Rl=null),!(uw===e&&Ra)&&(Ra&&(Ra.disconnect(),Ra=null),uw=e,Ia("observer:setup",{container:Io(e),debugMode:y0(),version:eF}),aF(e),Ra=new MutationObserver(t=>{const i=y0()==="verbose";t.some(o=>{const a=o.target instanceof Element&&["show_image","show_html","show_file","show-image","show-html","show-file"].includes(o.target.tagName.toLowerCase()),c=Array.from(o.addedNodes).some(l=>{var u;return l instanceof Element&&(["show_image","show_html","show_file","show-image","show-html","show-file"].includes(l.tagName.toLowerCase())||!!((u=l.querySelector)!=null&&u.call(l,'show_image,show_html,show_file,show-image,show-html,show-file,a.md-download-link,a[data-download="1"]')))});return a||c})&&(Ia("observer:show-image-mutation",{mutationCount:t.length,mutations:i?t.slice(0,20).map(o=>({type:o.type,target:Io(o.target),added:Array.from(o.addedNodes).slice(0,6).map(a=>Io(a)),removed:Array.from(o.removedNodes).slice(0,6).map(a=>Io(a))})):void 0}),Yse(e))}),Ra.observe(e,{childList:!0,subtree:!0}))};s(),Tp=new MutationObserver(()=>{const e=QR();e&&e!==uw&&s()}),Tp.observe(document.body,{childList:!0,subtree:!0})}function ene(){Rl&&(window.clearTimeout(Rl),Rl=null),Ra&&(Ra.disconnect(),Ra=null),Tp&&(Tp.disconnect(),Tp=null),Uv&&(Uv.disconnect(),Uv=null),zh&&(zh.disconnect(),zh=null),jh&&(window.clearTimeout(jh),jh=null),ZA=!1,pw=0,eE.clear(),hw.clear(),yv.clear(),bv.clear(),dw.clear(),fw.clear(),JA.clear(),uw=null,vc(),oM()}function ep(){const s=document.documentElement,e=window.visualViewport;if(e){const t=e.height,n=Math.max(0,(window.innerHeight||s.clientHeight||t)-e.height-e.offsetTop);s.style.setProperty("--app-viewport",`${t}px`),s.style.setProperty("--app-bottom-inset",`${n}px`)}else{const t=window.innerHeight||s.clientHeight;t&&s.style.setProperty("--app-viewport",`${t}px`),s.style.setProperty("--app-bottom-inset","env(safe-area-inset-bottom, 0px)")}}function tne(s){const e=`/api/download/file?path=${encodeURIComponent(s)}`,t=s.split("/").pop()||"file",n=window.AndroidDownloadBridge;if(n&&typeof n.downloadFile=="function")try{const i=new URL(e,window.location.href).href;n.downloadFile(i,t);return}catch(i){console.warn("[show_file] Android 桥接下载失败,回退:",i)}fetch(e).then(i=>i.ok?i.blob():i.json().then(r=>{throw new Error(r.error||r.message||i.statusText)}).catch(()=>{throw new Error(i.statusText||"下载失败")})).then(i=>{const r=URL.createObjectURL(i),o=document.createElement("a");o.href=r,o.download=t,document.body.appendChild(o),o.click(),document.body.removeChild(o),setTimeout(()=>URL.revokeObjectURL(r),1e3)}).catch(i=>{console.warn("[show_file] 下载失败:",i),window.open(e,"_blank")})}const a1=new WeakMap;function sne(s){const e=(s.getAttribute("path")||"").trim().replace(/^\/+/,"");if(!e){s.replaceChildren(document.createTextNode("[show_file: 缺少 path 属性]"));return}const t=a1.get(s);if(t){try{t.unmount()}catch{}a1.delete(s)}const n=document.createElement("div");n.className="show-file-card-root",s.replaceChildren(n);const i=w2(Fse,{path:e});i.mount(n),a1.set(s,i)}function nne(s){s.querySelectorAll('a[data-download="1"]:not([data-download-bound]), a.md-download-link:not([data-download-bound])').forEach(t=>{t.setAttribute("data-download-bound","1"),t.addEventListener("click",n=>{n.preventDefault(),n.stopPropagation();const i=t.getAttribute("data-path")||"";i&&tne(i)})})}typeof window<"u"&&(window.katex=$F,ep(),window.addEventListener("resize",ep),window.addEventListener("orientationchange",ep),window.addEventListener("pageshow",ep),window.visualViewport&&(window.visualViewport.addEventListener("resize",ep),window.visualViewport.addEventListener("scroll",ep)));function ine(){CZ().registerDependencies({pushToast:e=>this.uiPushToast(e),autoResizeInput:()=>this.autoResizeInput(),focusComposer:()=>{const e=this.getComposerElement("stadiumInput");e&&typeof e.focus=="function"&&e.focus()},isConnected:()=>this.isConnected,executeCommand:async e=>this.executeSystemCommand(e,{showToast:!1}),downloadResource:(e,t)=>this.downloadResource(e,t)})}async function rne(){var t;window.ensureCsrfToken&&window.ensureCsrfToken().catch(n=>{console.warn("CSRF token 初始化失败:",n)}),this.setupMobileViewportWatcher(),await this.bootstrapRoute(),this.$nextTick(()=>{this.ensureScrollListener(),EZ(this)}),Zse();const e=this.loadInitialData();(t=this.startProjectGitSummaryIdleRefresh)==null||t.call(this),this.startConnectionHeartbeat(),this.fetchTerminalCount(),this.startTerminalCountIdleRefresh(),this.checkTutorialPrompt(),e&&typeof e.then=="function"&&e.then(()=>{var n;(n=this.refreshProjectGitSummary)==null||n.call(this),this.checkTutorialPrompt()}).catch(()=>{}),window.__taskEventHandler=n=>{typeof this.handleTaskEvent=="function"&&this.handleTaskEvent(n)},typeof this.restoreTaskState=="function"&&this.restoreTaskState(),document.addEventListener("click",this.handleClickOutsideQuickMenu),document.addEventListener("click",this.handleClickOutsideHeaderMenu),document.addEventListener("click",this.handleClickOutsideMobileMenu),document.addEventListener("click",this.handleCopyCodeClick),window.addEventListener("popstate",this.handlePopState),window.addEventListener("keydown",this.handleMobileOverlayEscape),window.addEventListener("beforeunload",this.handleBeforeUnloadDraftPersist),this.subAgentFetch(),this.backgroundCommandFetch(),this.$nextTick(()=>{this.autoResizeInput()}),this.resourceBindContainerVisibilityWatcher(),this.resourceStartContainerStatsPolling(),this.resourceStartProjectStoragePolling(),this.resourceStartUsageQuotaPolling(),this.setupDragAndDrop()}function one(){var e,t;this._todoRefreshTimer&&(clearTimeout(this._todoRefreshTimer),this._todoRefreshTimer=null);try{const{useTaskStore:n}=require("../stores/task");n().stopPolling()}catch{}document.removeEventListener("click",this.handleClickOutsideQuickMenu),document.removeEventListener("click",this.handleClickOutsideHeaderMenu),document.removeEventListener("click",this.handleClickOutsideMobileMenu),document.removeEventListener("click",this.handleCopyCodeClick),window.removeEventListener("popstate",this.handlePopState),window.removeEventListener("keydown",this.handleMobileOverlayEscape),window.removeEventListener("beforeunload",this.handleBeforeUnloadDraftPersist),this.teardownMobileViewportWatcher(),(e=this.stopProjectGitSummaryIdleRefresh)==null||e.call(this),(t=this.stopTerminalCountIdleRefresh)==null||t.call(this),this.resourceStopContainerStatsPolling(),this.resourceStopProjectStoragePolling(),this.resourceStopUsageQuotaPolling(),this.stopConnectionHeartbeat(),ene(),this.teardownDragAndDrop(),this.titleTypingTimer&&(clearInterval(this.titleTypingTimer),this.titleTypingTimer=null);const s=this.destroyEasterEggEffect(!0);s&&typeof s.catch=="function"&&s.catch(()=>{})}const ane={resetAllStates(s="unspecified",e={}){this.waitingForSubAgent||(Oe("重置所有前端状态",{reason:s,conversationId:this.currentConversationId}),this.logMessageState("resetAllStates:before-cleanup",{reason:s}),this.fileHideContextMenu(),this.monitorResetVisual({preserveBubble:!0,preservePointer:!0,preserveWindows:!!(e!=null&&e.preserveMonitorWindows),preserveQueue:!!(e!=null&&e.preserveMonitorWindows)}),this.streamingMessage=!1,this.currentMessageIndex=-1,this.stopRequested=!1,this.taskInProgress=!1,this.dropToolEvents=!1,this.toolResetTracking(),this.messages.filter(t=>t.role==="assistant").map(t=>({awaitingFirstContent:t.awaitingFirstContent,generatingLabel:t.generatingLabel})),this.messages.forEach(t=>{t.role==="assistant"&&(t.awaitingFirstContent&&(t.awaitingFirstContent=!1),t.generatingLabel&&(t.generatingLabel=""),t.actions&&t.actions.forEach(n=>{n.type==="tool"&&(n.tool.status==="preparing"||n.tool.status==="running")&&(n.tool.status="completed")}))}),this.messages.filter(t=>t.role==="assistant").map(t=>({awaitingFirstContent:t.awaitingFirstContent,generatingLabel:t.generatingLabel})),this.markdownCache&&this.markdownCache.clear(),this.chatClearThinkingLocks(),this.$forceUpdate(),this.inputSetSettingsOpen(!1),this.inputSetToolMenuOpen(!1),this.inputSetQuickMenuOpen(!1),this.modeMenuOpen=!1,this.permissionMenuOpen=!1,this.workModeMenuOpen=!1,this.inputSetLineCount(1),this.inputSetMultiline(!1),this.inputClearMessage(),this.runtimeQueuedMessages=[],this.runtimeGuidanceFallbackQueue=[],this.runtimeQueueAutoSendInProgress=!1,this.runtimeQueueSyncLockKey="",this.runtimeQueueSyncLockUntil=0,typeof this.clearRuntimeQueueSuppressionState=="function"?this.clearRuntimeQueueSuppressionState():(this.runtimeQueueSuppressedMessageIds=new Set,this.runtimeGuidanceSuppressedTextCounts={}),this.composerReservedHeight=80,this.inputClearSelectedImages(),this.inputSetImagePickerOpen(!1),this.imageEntries=[],this.imageLoading=!1,this.conversationHasImages=!1,this.conversationHasVideos=!1,this.toolSetSettingsLoading(!1),this.toolSetSettings([]),this.pendingToolApprovals=[],this.decidingApprovalIds=[],this.autoApprovalTitle="自动审批记录",this.goalModeArmed=!1,this.goalRunning=!1,this.goalProgress=null,this.goalDialogOpen=!1,this._scrollListenerReady=!1,this._manualScrollSuppressUntil=0,this._escapedByUserScroll=!1,this._autoRelockCooldownUntil=0,this.$nextTick(()=>{this.ensureScrollListener();const t=typeof this.getInputComposerRef=="function"?this.getInputComposerRef():null;t&&typeof t.emitComposerHeight=="function"&&t.emitComposerHeight()}),this.lastHistoryLoadedConversationId=null,this.logMessageState("resetAllStates:after-cleanup",{reason:s}))},scheduleResetAfterTask(s="unspecified",e={}){const t=Date.now(),n=4e3,i=200,r=()=>{if(!this.monitorIsLocked||Date.now()-t>=n){this.resetAllStates(s,e);return}setTimeout(r,i)};r()},resetTokenStatistics(){this.resourceResetTokenStatistics()}},lne={async handleSidebarConversationTypeChange(s){var i,r,o;const{useConversationStore:e}=await wt(async()=>{const{useConversationStore:a}=await Promise.resolve().then(()=>Ei);return{useConversationStore:a}},[]),t=e(),n=t.sidebarConversationType;(i=t.conversationsCache[n])!=null&&i.loaded||(this.conversationsOffset=0,this.hasMoreConversations=!1,await this.loadConversationsList());try{const a=Array.isArray(t.workspaceGroups)?t.workspaceGroups:[];for(const c of a)c&&c.workspaceId&&!((o=(r=c.pagingByType)==null?void 0:r[n])!=null&&o.loaded)&&await t.loadWorkspaceConversations(c.workspaceId)}catch(a){console.error("补载工作区分组对话失败:",a)}},async loadConversationsList(){const s=this.conversationsOffset,e=this.conversationsLimit,{useConversationStore:t}=await wt(async()=>{const{useConversationStore:a}=await Promise.resolve().then(()=>Ei);return{useConversationStore:a}},void 0),n=t(),i=n.sidebarConversationType,r=s===0?++this.conversationListRefreshToken:this.conversationListRefreshToken,o=++this.conversationListRequestSeq;this.conversationsLoading=!0;try{const l=await(await fetch(`/api/conversations?limit=${e}&offset=${s}${i==="multi_agent"?"&multi_agent_mode=1":"&multi_agent_mode=0"}`)).json();if(l.success){if(r<this.conversationListRefreshToken){Oe("忽略已过期的对话列表响应",{requestSeq:o,responseOffset:s,refreshToken:r,currentRefreshToken:this.conversationListRefreshToken});return}const u=n.conversationsCache[i],h=l.data.conversations;if(s===0?u.list.splice(0,u.list.length,...h):u.list.push(...h),u.offset=s,u.hasMore=l.data.has_more,u.loaded=!0,i===n.sidebarConversationType&&(this.conversations=u.list,this.hasMoreConversations=u.hasMore,this.currentConversationId&&this.promoteConversationToTop(this.currentConversationId),s===0&&!this.currentConversationId&&u.list.length>0&&!this.isExplicitNewConversationRoute()&&!this.isConversationIndependentRoute()&&this.initialRouteResolved)){const p=u.list[0];p&&p.id&&await this.loadConversation(p.id)}Oe(`已加载 ${u.list.length} 个对话`);const d=i==="multi_agent"?"normal":"multi_agent";s===0&&!n.conversationsCache[d].loaded&&this.loadConversationTypeCache(d).catch(()=>{})}else console.error("加载对话列表失败:",l.error)}catch(a){console.error("加载对话列表异常:",a)}finally{r===this.conversationListRefreshToken&&(this.conversationsLoading=!1)}},async loadConversationTypeCache(s){var o,a;const{useConversationStore:e}=await wt(async()=>{const{useConversationStore:c}=await Promise.resolve().then(()=>Ei);return{useConversationStore:c}},void 0),n=e().conversationsCache[s];if(!n||n.loaded)return;const i=this.conversationListRefreshToken,r=s==="multi_agent"?"&multi_agent_mode=1":"&multi_agent_mode=0";try{const l=await(await fetch(`/api/conversations?limit=${this.conversationsLimit}&offset=0${r}`)).json();if(!(l!=null&&l.success)||i!==this.conversationListRefreshToken||n.loaded)return;const u=((o=l.data)==null?void 0:o.conversations)||[];n.list.push(...u),n.offset=0,n.hasMore=!!((a=l.data)!=null&&a.has_more),n.loaded=!0}catch(c){console.error("补载对话列表缓存异常:",c)}},async loadMoreConversations(){this.loadingMoreConversations||!this.hasMoreConversations||(this.loadingMoreConversations=!0,this.conversationsOffset+=this.conversationsLimit,await this.loadConversationsList(),this.loadingMoreConversations=!1)},async loadConversation(s,e={}){var r,o,a,c;const t=!!e.force,n=!!e.preserveListPosition,i=e.workspaceId?String(e.workspaceId):"";if(nl("loadConversation:start",{conversationId:s,currentConversationId:this.currentConversationId,force:t}),this.logMessageState("loadConversation:start",{conversationId:s,force:t}),this.suppressTitleTyping=!0,this.titleReady=!1,this.currentConversationTitle="",this.titleTypingText="",!t&&s===this.currentConversationId){this.suppressTitleTyping=!1,this.titleReady=!0;return}(r=this.flushReasoningEffortSave)==null||r.call(this);try{const{useTaskStore:l}=await wt(async()=>{const{useTaskStore:h}=await Promise.resolve().then(()=>so);return{useTaskStore:h}},void 0),u=l();(u.hasActiveTask||this.taskInProgress)&&(u.clearTask(),typeof this.clearProcessedEvents=="function"&&this.clearProcessedEvents()),(o=this.clearLocalTaskUiState)==null||o.call(this,`switch-conversation:${s}`)}catch(l){console.error("[切换对话] 停止本地轮询失败:",l)}await this.persistComposerDraftNow({reason:`switch-conversation:${s}`,force:!0,keepalive:!0}).catch(()=>{});try{const l=await this.enterConversation(s,{source:"sidebar",workspaceId:i,urlMode:"push",preserveListPosition:n,resetUI:!0});if(l.success){Oe("对话 bootstrap 成功:",l),nl("loadConversation:api-success",{conversationId:s,title:l.title}),this.currentConversationTitle=l.title,this.titleReady=!0,this.suppressTitleTyping=!1,this.startTitleTyping(this.currentConversationTitle,{animate:!1}),this.subAgentFetch(),this.fetchTodoList(),await((a=this.refreshRunningWorkspaceTasks)==null?void 0:a.call(this));const u=typeof this.getVisibleWorkspaceTaskForConversation=="function"?this.getVisibleWorkspaceTaskForConversation(s):null,h=String((u==null?void 0:u.status)||"");u&&new Set(["succeeded","failed","canceled"]).has(h)&&((c=this.acknowledgeCompletedWorkspaceTask)==null||c.call(this,u.task_id)),this.fetchWorkMode(),this.fetchPermissionMode(),this.fetchExecutionMode(),this.fetchNetworkPermission(),await this.fetchVersioningStatus(s,{silent:!0}),this.fetchPendingToolApprovals(),this.fetchPendingUserQuestions(),this.fetchPendingPlanApprovals(),this.refreshProjectGitSummary(),this.fetchConversationTokenStatistics(),this.updateCurrentContextTokens(),nl("loadConversation:after-history",{conversationId:s,messagesLen:Array.isArray(this.messages)?this.messages.length:"n/a"})}else console.error("对话加载失败:",l.message),this.suppressTitleTyping=!1,this.titleReady=!0,this.uiPushToast({title:"加载对话失败",message:l.message||"服务器未返回成功状态",type:"error"})}catch(l){console.error("加载对话异常:",l),nl("loadConversation:error",{conversationId:s,error:(l==null?void 0:l.message)||String(l)}),this.suppressTitleTyping=!1,this.titleReady=!0,this.uiPushToast({title:"加载对话异常",message:l.message||String(l),type:"error"})}}},cne={promoteConversationToTop(s){if(!Array.isArray(this.conversations)||!s)return;const e=this.conversations.findIndex(t=>t&&t.id===s);if(e>0){const[t]=this.conversations.splice(e,1);this.conversations.unshift(t)}},async createNewConversation(){var t,n,i,r,o;nl("createNewConversation:start",{currentConversationId:this.currentConversationId,convCount:Array.isArray(this.conversations)?this.conversations.length:"n/a"}),this.logMessageState("createNewConversation:start"),(t=this.flushReasoningEffortSave)==null||t.call(this),await this.persistComposerDraftNow({reason:"create-new-conversation",force:!0,keepalive:!0}).catch(()=>{});let s="route";try{s=((i=(n=qs())==null?void 0:n.form)==null?void 0:i.new_chat_button_behavior)||"route"}catch(a){console.warn("读取新建对话按钮行为设置失败,按默认跳转处理:",a)}if(s!=="blank"){try{const{useConversationStore:l}=await wt(async()=>{const{useConversationStore:u}=await Promise.resolve().then(()=>Ei);return{useConversationStore:u}},void 0);this.newConversationType=l().sidebarConversationType==="multi_agent"?"multi_agent":"agent",wD(this.newConversationType)}catch{}const a="/new",c=l=>String(l||"/").replace(/^\/+|\/+$/g,"");c(window.location.pathname)!==c(a)&&(window.location.href=a);return}try{const a=qs();if(a.loaded){const c=a.form.default_run_mode,l=a.form.default_model,u=a.form.default_reasoning_effort;c&&(this.runMode=c,Oe("应用默认运行模式:",c)),this.reasoningEffort=u,l&&(this.currentModelKey=l,Oe("应用默认模型:",l)),c==="thinking"?this.thinkingMode=!0:c==="fast"&&(this.thinkingMode=!1)}}catch(a){console.warn("应用个性化默认设置失败:",a)}try{const{useTaskStore:a}=await wt(async()=>{const{useTaskStore:l}=await Promise.resolve().then(()=>so);return{useTaskStore:l}},void 0),c=a();(c.hasActiveTask||this.taskInProgress)&&(c.clearTask(),typeof this.clearProcessedEvents=="function"&&this.clearProcessedEvents()),(r=this.clearLocalTaskUiState)==null||r.call(this,"create-new-conversation")}catch(a){console.error("[创建新对话] 停止本地轮询失败:",a)}let e=null;try{const a=qs();this.versioningHostMode&&a.form.versioning_enabled_by_default&&a.form.versioning_backup_mode==="full"&&(e=this.uiPushToast({title:"正在初始化备份",message:"正在创建完整工作区快照,请稍候…",type:"info",duration:null,closable:!1}),this.versioningInitializingBackupToastId=e);const{useConversationStore:l}=await wt(async()=>{const{useConversationStore:v}=await Promise.resolve().then(()=>Ei);return{useConversationStore:v}},void 0),u=l().sidebarConversationType==="multi_agent",h=u?"/api/multiagent/conversations":"/api/conversations",d=JSON.stringify(u?{preserve_mode:!0,thinking_mode:this.thinkingMode,mode:this.runMode,reasoning_effort:this.reasoningEffort}:{thinking_mode:this.thinkingMode,mode:this.runMode,reasoning_effort:this.reasoningEffort}),m=await(await fetch(h,{method:"POST",headers:{"Content-Type":"application/json"},body:d})).json();if(m.success){const v=m.conversation_id,g=b=>new Promise(_=>{window.setTimeout(_,b)});Oe("新对话创建成功:",v),nl("createNewConversation:created",{newConversationId:v});const y={id:v,title:"新对话",updated_at:new Date().toISOString(),total_messages:0,total_tools:0};this.conversationInsertAnimations={...this.conversationInsertAnimations,[v]:"create"},this.conversationListAnimationMode="create",this.conversations.splice(0,this.conversations.length,y,...this.conversations.filter(b=>b&&b.id!==v));try{const{useConversationStore:b}=await wt(async()=>{const{useConversationStore:S}=await Promise.resolve().then(()=>Ei);return{useConversationStore:S}},void 0),_=b(),w=this.currentHostWorkspaceId;if(w){_.ensureWorkspaceGroup(w);const S=_.workspaceGroups.find(C=>C.workspaceId===w);S&&(S.conversations.splice(0,S.conversations.length,y,...S.conversations.filter(C=>C.id!==v)),S.expanded=!0,S.visibleOffset=0)}}catch{}window.setTimeout(()=>{const b={...this.conversationInsertAnimations};delete b[v],this.conversationInsertAnimations=b,this.conversationListAnimationMode="idle"},700),await g(540),await this.loadConversation(v,{force:!0}),nl("createNewConversation:after-load",{newConversationId:v,currentConversationId:this.currentConversationId}),this.conversationsOffset=0,await this.loadConversationsList(),nl("createNewConversation:after-refresh",{newConversationId:v,conversationsLen:Array.isArray(this.conversations)?this.conversations.length:"n/a"});try{const{useConversationStore:b}=await wt(async()=>{const{useConversationStore:S}=await Promise.resolve().then(()=>Ei);return{useConversationStore:S}},void 0),_=b(),w=this.currentHostWorkspaceId;w&&await _.loadWorkspaceConversations(w,{refresh:!0})}catch{}await((o=this.refreshRunningWorkspaceTasks)==null?void 0:o.call(this))}else console.error("创建对话失败:",m.message),this.uiPushToast({title:"创建对话失败",message:m.message||"服务器未返回成功状态",type:"error"})}catch(a){console.error("创建对话异常:",a),this.uiPushToast({title:"创建对话异常",message:a.message||String(a),type:"error"})}finally{e&&(this.uiDismissToast(e),this.versioningInitializingBackupToastId=null)}},async createWorkspaceConversation(s){if(s)try{const{useConversationStore:e}=await wt(async()=>{const{useConversationStore:c}=await Promise.resolve().then(()=>Ei);return{useConversationStore:c}},void 0),n=e().sidebarConversationType==="multi_agent",a=await(await fetch(n?"/api/multiagent/conversations":"/api/conversations",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n?{workspace_id:s,preserve_mode:!0}:{workspace_id:s})})).json();if(a.success){const c=a.conversation_id;Oe("工作区新对话创建成功:",c);const l={id:c,title:"新对话",updated_at:new Date().toISOString(),total_messages:0,total_tools:0};this.conversationInsertAnimations={...this.conversationInsertAnimations,[c]:"create"},this.conversationListAnimationMode="create",window.setTimeout(()=>{const u={...this.conversationInsertAnimations};delete u[c],this.conversationInsertAnimations=u,this.conversationListAnimationMode="idle"},700);try{const{useConversationStore:u}=await wt(async()=>{const{useConversationStore:p}=await Promise.resolve().then(()=>Ei);return{useConversationStore:p}},void 0),h=u();h.ensureWorkspaceGroup(s);const d=h.workspaceGroups.find(p=>p.workspaceId===s);d&&(d.conversations.splice(0,d.conversations.length,l,...d.conversations.filter(p=>p.id!==c)),d.expanded=!0,d.visibleOffset=0),window.setTimeout(()=>{h.loadWorkspaceConversations(s,{refresh:!0}).catch(()=>{})},300)}catch{}}else console.error("创建对话失败:",a.message),this.uiPushToast({title:"创建对话失败",message:a.message||"服务器未返回成功状态",type:"error"})}catch(e){console.error("创建工作区对话异常:",e),this.uiPushToast({title:"创建工作区对话异常",message:e.message||String(e),type:"error"})}},async deleteConversation(s){const e=typeof s=="string"?s:s==null?void 0:s.id,t=typeof s=="object"?s==null?void 0:s.workspaceId:void 0;if(!e||!await this.confirmAction({title:"删除对话",message:"确定要删除这个对话吗?删除后无法恢复。",confirmText:"删除",cancelText:"取消"}))return;const i=r=>new Promise(o=>{window.setTimeout(o,r)});await i(270),this.logMessageState("deleteConversation:start",{conversationId:e});try{const r=t?`/api/conversations/${e}?workspace_id=${encodeURIComponent(t)}`:`/api/conversations/${e}`,a=await(await fetch(r,{method:"DELETE"})).json();if(a.success){Oe("对话删除成功"),e===this.currentConversationId&&(this.logMessageState("deleteConversation:before-clear",{conversationId:e}),this.messages=[],this.logMessageState("deleteConversation:after-clear",{conversationId:e}),this.currentConversationId=null,this.currentConversationTitle="",this.resetAllStates(`deleteConversation:${e}`),this.resetTokenStatistics(),history.replaceState({},"","/new")),this.conversationListAnimationMode="delete";const c=Array.isArray(this.pendingDeletingConversationIds)?this.pendingDeletingConversationIds:[];c.includes(e)||(this.pendingDeletingConversationIds=[...c,e]),await this.$nextTick();try{const{useConversationStore:l}=await wt(async()=>{const{useConversationStore:h}=await Promise.resolve().then(()=>Ei);return{useConversationStore:h}},void 0);l().workspaceGroups.forEach(h=>{h.conversations.splice(0,h.conversations.length,...h.conversations.filter(p=>p.id!==e));const d=Math.max(0,h.conversations.length-h.visibleLimit);h.visibleOffset>d&&(h.visibleOffset=d)})}catch{}await i(430),this.conversations.splice(0,this.conversations.length,...this.conversations.filter(l=>l.id!==e)),this.searchResults=this.searchResults.filter(l=>l.id!==e),this.searchGroups=(Array.isArray(this.searchGroups)?this.searchGroups:[]).map(l=>({...l,results:(l.results||[]).filter(u=>u.id!==e)})).filter(l=>l.results.length>0),this.pendingDeletingConversationIds=(Array.isArray(this.pendingDeletingConversationIds)?this.pendingDeletingConversationIds:[]).filter(l=>l!==e),await i(180),this.conversationsOffset=0,await this.loadConversationsList(),this.conversationListAnimationMode="idle"}else console.error("删除对话失败:",a.message),this.uiPushToast({title:"删除对话失败",message:a.message||"服务器未返回成功状态",type:"error"})}catch(r){this.pendingDeletingConversationIds=(Array.isArray(this.pendingDeletingConversationIds)?this.pendingDeletingConversationIds:[]).filter(o=>o!==e),this.conversationListAnimationMode="idle",console.error("删除对话异常:",r),this.uiPushToast({title:"删除对话异常",message:r.message||String(r),type:"error"})}},async duplicateConversation(s){var e;try{const t=await fetch(`/api/conversations/${s}/duplicate`,{method:"POST"}),n=await t.json();if(t.ok&&n.success){const i=n.duplicate_conversation_id,r=o=>new Promise(a=>{window.setTimeout(a,o)});if(i){const o=this.conversations.findIndex(d=>d&&d.id===s),a=o>=0?this.conversations[o]:null,c=((e=n.load_result)==null?void 0:e.title)||(a==null?void 0:a.title)||"复制的对话",l={id:i,title:c,updated_at:new Date().toISOString(),total_messages:(a==null?void 0:a.total_messages)||0,total_tools:(a==null?void 0:a.total_tools)||0};this.conversationInsertAnimations={...this.conversationInsertAnimations,[s]:"duplicateSource",[i]:"duplicate"},this.conversationListAnimationMode="duplicate";const u=this.conversations.filter(d=>d&&d.id!==i),h=u.findIndex(d=>d&&d.id===s);h>=0?this.conversations.splice(0,this.conversations.length,...u.slice(0,h+1),l,...u.slice(h+1)):this.conversations.splice(0,this.conversations.length,l,...u),window.setTimeout(()=>{const d={...this.conversationInsertAnimations};delete d[s],delete d[i],this.conversationInsertAnimations=d,this.conversationListAnimationMode="idle"},860);try{const{useConversationStore:d}=await wt(async()=>{const{useConversationStore:v}=await Promise.resolve().then(()=>Ei);return{useConversationStore:v}},void 0),m=d().workspaceGroups.find(v=>v.conversations.some(g=>g.id===s));if(m){const v=m.conversations.findIndex(y=>y.id===s),g=m.conversations.filter(y=>y.id!==i);v>=0?m.conversations.splice(0,m.conversations.length,...g.slice(0,v+1),l,...g.slice(v+1)):m.conversations.splice(0,m.conversations.length,l,...g),m.expanded=!0}}catch{}await r(860),await this.loadConversation(i,{force:!0,preserveListPosition:!0})}}else{const i=n.message||n.error||"复制失败";this.uiPushToast({title:"复制对话失败",message:i,type:"error"})}}catch(t){console.error("复制对话异常:",t),this.uiPushToast({title:"复制对话异常",message:t.message||String(t),type:"error"})}}},une={async enterConversation(s,e={}){var g,y,b;const{source:t="sidebar",workspaceId:n="",urlMode:i="push",preserveListPosition:r=!1,resetUI:o=!1}=e,a=!!(this.versioningHostMode||this.dockerProjectMode),c=n&&a?`/api/conversations/${s}/bootstrap?workspace_id=${encodeURIComponent(n)}`:`/api/conversations/${s}/bootstrap`,u=await(await fetch(c)).json();if(!u.success)return Oe("enterConversation:failed",{conversationId:s,error:u.error||u.message}),u;const h=u.data||{},d=h.meta||{},p=h.conversation_id||s;typeof d.run_mode=="string"?(this.runMode=d.run_mode==="deep"?"thinking":d.run_mode,this.thinkingMode=typeof d.thinking_mode=="boolean"?d.thinking_mode:d.run_mode!=="fast"):typeof d.thinking_mode=="boolean"&&(this.thinkingMode=d.thinking_mode,this.runMode=d.thinking_mode?"thinking":"fast"),typeof d.model_key=="string"&&d.model_key&&this.modelSet(d.model_key),this.reasoningEffort=typeof d.reasoning_effort=="string"?d.reasoning_effort:null,this.currentConversationType=d.multi_agent_mode===!0?"multi_agent":"normal",vr().$patch({multiAgentMode:d.multi_agent_mode===!0}),this.skipConversationHistoryReload=!0,this.currentConversationId=p,(g=this.refreshProjectGitSummary)==null||g.call(this),this.fetchTerminalCount(),r||this.promoteConversationToTop(p),i!=="none"&&history[i==="replace"?"replaceState":"pushState"]({conversationId:p},"",`/${this.stripConversationPrefix(p)}`),this.skipConversationLoadedEvent=!0,o&&this.resetAllStates(`enterConversation:${p}`);const m=Array.isArray(h.messages)?h.messages:[];(y=this.logMessageState)==null||y.call(this,"enterConversation:before-render",{conversationId:p,count:m.length}),this.messages=[],m.length>0&&(this.renderHistoryMessages(m),typeof this.settleHistoryRenderAndScroll=="function"?await this.settleHistoryRenderAndScroll():(await this.$nextTick(),this.scrollHistoryToBottomInstant())),this.lastHistoryLoadedConversationId=p,this.refreshBlankHeroState(),await new Promise(_=>setTimeout(_,0)),Bo().setEditedFiles(Array.isArray(h.edited_files)?h.edited_files:[]);try{const _=await fetch(`/api/workflow/status?conversation_id=${encodeURIComponent(p)}`);if(_.ok){const w=await _.json();um().setWorkflow(w==null?void 0:w.snapshot,!1)}}catch{}const v=h.running||{};return v.is_main_running&&h.task_replay&&await this.restoreTaskState({bootstrapReplay:h.task_replay}),nl("enterConversation:done",{conversationId:p,messagesCount:m.length,isTrulyActive:!!v.is_truly_active,needsRebuild:(b=h.task_replay)==null?void 0:b.needs_rebuild}),{success:!0,title:d.title||"",run_mode:d.run_mode,thinking_mode:d.thinking_mode,model_key:d.model_key,multi_agent_mode:d.multi_agent_mode,conversation_id:p}}},hne={...ane,...lne,...cne,...une},tp=(...s)=>{},dne="[RESTORE_DEBUG]",fne=new Set(["history:fetch:start","history:fetch:response","history:render:done"]);function pne(){var s;if(typeof window>"u")return!1;try{const e=window.__RESTORE_DEBUG__;if(e===!0||e==="1")return!0;if(e===!1||e==="0")return!1;const t=(s=window.localStorage)==null?void 0:s.getItem("restoreDebug");return t==="1"||t==="true"}catch{return!1}}function l1(s,e={}){pne()&&fne.has(s)&&console.log(dne,s,e)}const gne=/^(?:✅\s*)?子智能体\s*#?\s*(\d+)\s*任务摘要[:]/,mne=/^\[后台\s*run_command\s*完成\]/;function vne(s){const e=(s||"").toString().trim();if(!e)return null;const t=e.match(gne);return!t||!/已完成/.test(e)?null:`子智能体${t[1]} 任务完成`}function yne(s){const e=(s||"").toString().trim();return!e||!mne.test(e)?null:"后台 run_command 完成"}function bne(s){const e=(s||"").toString().trim();return e?vne(e)||yne(e):null}const _ne={async fetchAndDisplayHistory(s={}){var r,o,a,c,l,u,h;const{force:e=!1}=s,t=this.currentConversationId;if(!t||t.startsWith("temp_")){this.refreshBlankHeroState();return}if(this.historyLoading&&this.historyLoadingFor===t)return;if(!e&&this.lastHistoryLoadedConversationId===t&&Array.isArray(this.messages)&&this.messages.length>0){this.logMessageState("fetchAndDisplayHistory:skip-duplicate",{conversationId:t});return}const i=++this.historyLoadSeq;l1("history:fetch:start",{loadSeq:i,targetConversationId:t,currentConversationId:this.currentConversationId,force:e}),tp("history.fetch:start",{loadSeq:i,force:e,targetConversationId:t,currentConversationId:this.currentConversationId,currentMessagesCount:Array.isArray(this.messages)?this.messages.length:-1}),this.historyLoading=!0,this.historyLoadingFor=t;try{Oe("开始获取历史对话内容..."),this.logMessageState("fetchAndDisplayHistory:start",{conversationId:this.currentConversationId});try{const d=await fetch(`/api/conversations/${t}/messages`);if(!d.ok){console.warn("无法获取消息历史,尝试备用方法");const y=await(await fetch("/api/status")).json();if(Oe("系统状态:",y),this.applyStatusSnapshot(y),y.conversation_history&&Array.isArray(y.conversation_history)){this.renderHistoryMessages(y.conversation_history);return}Oe("备用方案也无法获取历史消息");return}if(i!==this.historyLoadSeq||this.currentConversationId!==t){Oe("检测到对话已切换,丢弃过期的历史加载结果");return}const p=await d.json(),m=Array.isArray((r=p==null?void 0:p.data)==null?void 0:r.messages)?p.data.messages:[];Bo().setEditedFiles(Array.isArray((o=p==null?void 0:p.data)==null?void 0:o.edited_files)?p.data.edited_files:[]);const v=[...m].reverse().find(g=>(g==null?void 0:g.role)==="assistant");if(l1("history:fetch:response",{loadSeq:i,success:!!(p!=null&&p.success),rawCount:m.length,responseConversationId:(a=p==null?void 0:p.data)==null?void 0:a.conversation_id,lastAssistantContentLength:((v==null?void 0:v.content)||"").length,lastAssistantReasoningLength:((v==null?void 0:v.reasoning_content)||"").length,lastAssistantHasShowHtml:/<show_html/i.test((v==null?void 0:v.content)||"")}),tp("history.fetch:response",{loadSeq:i,success:!!(p!=null&&p.success),responseConversationId:(c=p==null?void 0:p.data)==null?void 0:c.conversation_id,messagesCount:Array.isArray((l=p==null?void 0:p.data)==null?void 0:l.messages)?p.data.messages.length:-1}),Oe("获取到消息数据:",p),p.success&&p.data&&p.data.messages){const g=p.data.messages;Oe(`发现 ${g.length} 条历史消息`),g.length>0?(this.logMessageState("fetchAndDisplayHistory:before-clear-existing"),this.messages=[],this.logMessageState("fetchAndDisplayHistory:after-clear-existing"),this.renderHistoryMessages(g),tp("history.fetch:rendered",{loadSeq:i,renderedMessagesCount:Array.isArray(this.messages)?this.messages.length:-1,lastRole:((h=(u=this.messages)==null?void 0:u[this.messages.length-1])==null?void 0:h.role)||null}),typeof this.settleHistoryRenderAndScroll=="function"?await this.settleHistoryRenderAndScroll():(await this.$nextTick(),this.scrollHistoryToBottomInstant()),Oe("历史对话内容显示完成")):(Oe("对话存在但没有历史消息"),this.logMessageState("fetchAndDisplayHistory:no-history-clear"),this.messages=[],this.logMessageState("fetchAndDisplayHistory:no-history-cleared"))}else Oe("消息数据格式不正确:",p),this.logMessageState("fetchAndDisplayHistory:invalid-data-clear"),this.messages=[],this.logMessageState("fetchAndDisplayHistory:invalid-data-cleared")}catch(d){console.error("获取历史对话失败:",d),Oe("尝试不显示错误弹窗,仅在控制台记录"),this.logMessageState("fetchAndDisplayHistory:error-clear",{error:(d==null?void 0:d.message)||String(d)}),this.messages=[],this.logMessageState("fetchAndDisplayHistory:error-cleared")}}finally{i===this.historyLoadSeq&&(this.historyLoading=!1,this.historyLoadingFor=null),this.refreshBlankHeroState()}},renderHistoryMessages(s){var l,u,h;if(Oe("历史消息数量:",s.length),this.logMessageState("renderHistoryMessages:start",{historyCount:s.length}),!Array.isArray(s)){console.error("历史消息不是数组格式");return}let e=null,t=!1,n=!1,i=0,r=0;s.forEach((d,p)=>{var v,g;Oe(`处理消息 ${p+1}/${s.length}:`,d.role,d);const m=d.metadata||{};if(!(d.role==="user"&&(m.system_injected_image||m.system_injected_video)))if(d.role==="user"){e&&e.actions.length>0&&(this.messages.push(e),e=null);const y=d.images||d.metadata&&d.metadata.images||[],b=d.videos||d.metadata&&d.metadata.videos||[],_=d.media_refs||d.metadata&&d.metadata.media_refs||[];Array.isArray(y)&&y.length&&(t=!0),Array.isArray(b)&&b.length&&(n=!0);const w=d.created_at??d.createdAt??d.timestamp??null,S=typeof w=="number"&&w>0?new Date(w*1e3).toISOString():w||null;this.messages.push({role:"user",content:d.content||"",images:y,videos:b,media_refs:Array.isArray(_)?_:[],metadata:d.metadata||{},created_at:S}),Oe("添加用户消息:",((v=d.content)==null?void 0:v.substring(0,50))+"...")}else if(d.role==="assistant"){e||(e={role:"assistant",actions:[],streamingThinking:"",streamingText:"",currentStreamingType:null,activeThinkingId:null,awaitingFirstContent:!1,generatingLabel:""});const y=d.content||"",b=(d.reasoning_content||"").trim();if(b){const w=`history-thinking-${Date.now()}-${Math.random().toString(36).slice(2)}`;e.actions.push({id:`history-think-${Date.now()}-${Math.random()}`,type:"thinking",content:b,streaming:!1,collapsed:!0,timestamp:Date.now(),blockId:w}),Oe("添加思考内容:",b.substring(0,50)+"...")}const _=y.trim();_&&(e.actions.push({id:`history-text-${Date.now()}-${Math.random()}`,type:"text",content:_,streaming:!1,timestamp:Date.now()}),Oe("添加文本内容:",_.substring(0,50)+"...")),d.tool_calls&&Array.isArray(d.tool_calls)&&d.tool_calls.forEach((w,S)=>{var k;let C={};try{C=typeof w.function.arguments=="string"?JSON.parse(w.function.arguments||"{}"):w.function.arguments||{}}catch(A){console.warn("解析工具参数失败:",A),C={},i+=1,tp("history.render:tool-args-parse-fail",{toolName:(k=w==null?void 0:w.function)==null?void 0:k.name,toolCallId:w==null?void 0:w.id,error:(A==null?void 0:A.message)||String(A)})}const T={id:`history-tool-${w.id||Date.now()}-${S}`,type:"tool",tool:{id:w.id,name:w.function.name,arguments:C,argumentSnapshot:this.cloneToolArguments(C),argumentLabel:this.buildToolLabel(C),intent_full:C.intent||"",intent_rendered:C.intent||"",status:"preparing",result:null},timestamp:Date.now()};["preparing","running","awaiting_content"].includes(T.tool.status)&&(T.tool.status="stale",T.tool.awaiting_content=!1,T.streaming=!1),e.actions.push(T),Oe("添加工具调用:",w.function.name)})}else if(d.role==="tool"){if(e){let y=null;if(d.tool_call_id&&(y=e.actions.find(b=>b.type==="tool"&&b.tool.id===d.tool_call_id)),!y&&d.name){const b=e.actions.filter(_=>_.type==="tool"&&_.tool.name===d.name);y=b[b.length-1]}if(y){let b;try{b=JSON.parse(d.content)}catch(_){r+=1,tp("history.render:tool-result-parse-fail",{toolName:d==null?void 0:d.name,toolCallId:d==null?void 0:d.tool_call_id,error:(_==null?void 0:_.message)||String(_)}),d.metadata&&d.metadata.tool_payload?b=d.metadata.tool_payload:b={output:d.content,success:!0}}y.tool.status="completed",y.tool.result=b,b&&typeof b=="object"&&(b.error?y.tool.message=b.error:b.message&&!y.tool.message&&(y.tool.message=b.message)),Oe(`更新工具结果: ${d.name} -> ${(g=d.content)==null?void 0:g.substring(0,50)}...`)}else console.warn("找不到对应的工具调用:",d.name,d.tool_call_id)}}else{if(e&&e.actions.length>0&&(this.messages.push(e),e=null),d.role==="system"){const y=d.content||"",b=bne(y);b&&this.messages.push({role:"assistant",actions:[{id:`history-system-${Date.now()}-${Math.random()}`,type:"system",content:b,variant:"sub_agent_done",streaming:!1,timestamp:Date.now()}],streamingThinking:"",streamingText:"",currentStreamingType:null,activeThinkingId:null,awaitingFirstContent:!1,generatingLabel:""});return}Oe("处理其他类型消息:",d.role),this.messages.push({role:d.role,content:d.content||""})}}),e&&e.actions.length>0&&this.messages.push(e),this.conversationHasImages=t,this.conversationHasVideos=n,Oe(`历史消息渲染完成,共 ${this.messages.length} 条消息`);const o=((l=this.messages)==null?void 0:l[this.messages.length-1])||null,a=Array.isArray(o==null?void 0:o.actions)?o.actions:[],c=a.filter(d=>(d==null?void 0:d.type)==="text").map(d=>String((d==null?void 0:d.content)||"")).join(`
`);l1("history:render:done",{currentConversationId:this.currentConversationId,historyInputCount:Array.isArray(s)?s.length:-1,finalMessagesCount:Array.isArray(this.messages)?this.messages.length:-1,lastRole:(o==null?void 0:o.role)||null,lastActionsCount:a.length,lastHasThinkingAction:a.some(d=>(d==null?void 0:d.type)==="thinking"),lastHasTextAction:a.some(d=>(d==null?void 0:d.type)==="text"),lastTextLength:c.length,lastTextHasShowHtml:/<show_html/i.test(c)}),tp("history.render:done",{historyInputCount:Array.isArray(s)?s.length:-1,finalMessagesCount:Array.isArray(this.messages)?this.messages.length:-1,lastRole:((h=(u=this.messages)==null?void 0:u[this.messages.length-1])==null?void 0:h.role)||null,toolArgsParseFailCount:i,toolResultParseFailCount:r}),this.logMessageState("renderHistoryMessages:after-render"),this.lastHistoryLoadedConversationId=this.currentConversationId||null,this.$forceUpdate(),this.$nextTick(()=>{this.scrollHistoryToBottomInstant(),setTimeout(()=>{const d=this.$el&&this.$el.querySelectorAll?this.$el.querySelectorAll(".message-block").length:"N/A";Oe("[Messages] DOM 渲染统计",{blocks:d,conversationId:this.currentConversationId})},0)})}},Sne={buildRuntimeQueueSnapshotKey(s=[]){const e=Array.isArray(s)?s:[];return JSON.stringify(e.map(t=>[String((t==null?void 0:t.id)||""),String((t==null?void 0:t.text)||""),Number((t==null?void 0:t.createdAt)||0),Array.isArray(t==null?void 0:t.files)?t.files:[]]))},setRuntimeQueueSyncLock(s=[],e=1800){this.runtimeQueueSyncLockKey=this.buildRuntimeQueueSnapshotKey(s),this.runtimeQueueSyncLockUntil=Date.now()+Math.max(300,Number(e||0))},ensureRuntimeQueueSuppressionState(){this.runtimeQueueSuppressedMessageIds instanceof Set||(this.runtimeQueueSuppressedMessageIds=new Set),(!this.runtimeGuidanceSuppressedTextCounts||typeof this.runtimeGuidanceSuppressedTextCounts!="object"||Array.isArray(this.runtimeGuidanceSuppressedTextCounts))&&(this.runtimeGuidanceSuppressedTextCounts={})},markRuntimeQueueSuppressedByManualStop(){this.ensureRuntimeQueueSuppressionState(),(Array.isArray(this.runtimeQueuedMessages)?this.runtimeQueuedMessages:[]).forEach(t=>{const n=String((t==null?void 0:t.id)||"").trim();n&&this.runtimeQueueSuppressedMessageIds.add(n)}),(Array.isArray(this.runtimeGuidanceFallbackQueue)?this.runtimeGuidanceFallbackQueue:[]).forEach(t=>{const n=String(t||"").trim();if(!n)return;const i=this.runtimeGuidanceSuppressedTextCounts;i[n]=Number(i[n]||0)+1})},consumeSuppressedRuntimeGuidanceText(s){this.ensureRuntimeQueueSuppressionState();const e=String(s||"").trim();if(!e)return!1;const t=this.runtimeGuidanceSuppressedTextCounts,n=Number(t[e]||0);return Number.isFinite(n)&&n>0},consumeSuppressedRuntimeQueueMessageId(s){this.ensureRuntimeQueueSuppressionState();const e=String(s||"").trim();return e?this.runtimeQueueSuppressedMessageIds.has(e):!1},clearRuntimeQueueSuppressionState(){this.runtimeQueueSuppressedMessageIds=new Set,this.runtimeGuidanceSuppressedTextCounts={}},pruneSuppressedRuntimeQueues(){this.ensureRuntimeQueueSuppressionState();const s=this.runtimeQueueSuppressedMessageIds,e=Array.isArray(this.runtimeQueuedMessages)?this.runtimeQueuedMessages:[],t=e.filter(i=>{const r=String((i==null?void 0:i.id)||"").trim();return r?!s.has(r):!1});t.length!==e.length&&(this.runtimeQueuedMessages=t,this.setRuntimeQueueSyncLock(t,2200));const n=Array.isArray(this.runtimeGuidanceFallbackQueue)?this.runtimeGuidanceFallbackQueue:[];if(n.length>0){const i=[];n.forEach(r=>{const o=String(r||"").trim();o&&(this.consumeSuppressedRuntimeGuidanceText(o)||i.push(o))}),i.length!==n.length&&(this.runtimeGuidanceFallbackQueue=i)}},applyRuntimeQueuedMessages(s=[]){this.ensureRuntimeQueueSuppressionState();const e=Array.isArray(this.runtimeQueuedMessages)?this.runtimeQueuedMessages:[],t=new Map(e.map(l=>[l==null?void 0:l.id,l])),n=new Map(e.map((l,u)=>[l==null?void 0:l.id,u])),i=Math.max(1,Number(this.runtimeQueueLimit||5)),r=(Array.isArray(s)?s:[]).map(l=>{if(!l)return null;const u=String(l.id||"").trim(),h=String(l.text||"").trim();if(!u||!h)return null;const d=t.get(u),p=Number(l.created_at??l.createdAt??Date.now()),m=Array.isArray(l.files)?l.files:Array.isArray(d==null?void 0:d.files)?d.files:[];return{id:u,text:h,createdAt:Number.isFinite(p)?p:Date.now(),source:(d==null?void 0:d.source)||"user",files:m.filter(v=>typeof v=="string"&&v).slice(0,9)}}).filter(l=>!!l),o=new Map;r.forEach(l=>{!(l!=null&&l.id)||o.has(l.id)||o.set(l.id,l)});const a=Array.from(o.values()).sort((l,u)=>{const h=Number((l==null?void 0:l.createdAt)||0),d=Number((u==null?void 0:u.createdAt)||0);if(h!==d)return h-d;const p=n.has(l==null?void 0:l.id)?Number(n.get(l==null?void 0:l.id)):Number.MAX_SAFE_INTEGER,m=n.has(u==null?void 0:u.id)?Number(n.get(u==null?void 0:u.id)):Number.MAX_SAFE_INTEGER;return p!==m?p-m:String((l==null?void 0:l.id)||"").localeCompare(String((u==null?void 0:u.id)||""))}).slice(0,i);return e.length===a.length&&e.every((l,u)=>{const h=a[u];return(l==null?void 0:l.id)===(h==null?void 0:h.id)&&(l==null?void 0:l.text)===(h==null?void 0:h.text)&&Number((l==null?void 0:l.createdAt)||0)===Number((h==null?void 0:h.createdAt)||0)})?e:(this.runtimeQueuedMessages=a,a)},async enqueueRuntimeQueuedMessage(s,e=[]){var i;const t=(s||"").toString().trim();if(!t)return!1;const n=(Array.isArray(e)?e:[]).filter(r=>typeof r=="string"&&r).slice(0,9);try{const{useTaskStore:r}=await wt(async()=>{const{useTaskStore:h}=await Promise.resolve().then(()=>so);return{useTaskStore:h}},void 0),a=r().currentTaskId;if(!a)return this.uiPushToast({title:"暂不可堆积",message:"未检测到活跃任务,请稍后再试",type:"warning"}),!1;const c=await fetch(`/api/tasks/${encodeURIComponent(a)}/runtime_queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:t,files:n.length?n:void 0})}),l=await c.json().catch(()=>({}));if(!c.ok||!(l!=null&&l.success))throw new Error((l==null?void 0:l.error)||"堆积消息失败");const u=this.applyRuntimeQueuedMessages(((i=l==null?void 0:l.data)==null?void 0:i.messages)||[])||[];return this.setRuntimeQueueSyncLock(u,2200),!0}catch(r){return this.uiPushToast({title:"堆积失败",message:(r==null?void 0:r.message)||"请稍后重试",type:"error"}),!1}},async handleDeleteRuntimeMessage(s){var t;const e=String(s||"").trim();if(e)try{const{useTaskStore:n}=await wt(async()=>{const{useTaskStore:l}=await Promise.resolve().then(()=>so);return{useTaskStore:l}},void 0),r=n().currentTaskId;if(!r){const l=(this.runtimeQueuedMessages||[]).filter(u=>(u==null?void 0:u.id)!==e);this.runtimeQueuedMessages=l,this.setRuntimeQueueSyncLock(l,1200);return}const o=await fetch(`/api/tasks/${encodeURIComponent(r)}/runtime_queue/${encodeURIComponent(e)}`,{method:"DELETE"}),a=await o.json().catch(()=>({}));if(!o.ok||!(a!=null&&a.success))throw new Error((a==null?void 0:a.error)||"删除失败");const c=this.applyRuntimeQueuedMessages(((t=a==null?void 0:a.data)==null?void 0:t.messages)||[])||[];this.setRuntimeQueueSyncLock(c,2200)}catch(n){this.uiPushToast({title:"删除失败",message:(n==null?void 0:n.message)||"请稍后重试",type:"error"})}},async handleGuideRuntimeMessage(s){var t;const e=(this.runtimeQueuedMessages||[]).find(n=>(n==null?void 0:n.id)===s);if(e!=null&&e.text){if(!this.composerBusy){if(!!!await this.sendMessage({presetText:String(e.text||"").trim(),source:"runtime_queue_manual_guide",files:Array.isArray(e==null?void 0:e.files)?[...e.files]:[]})){this.uiPushToast({title:"发送失败",message:"引导消息未发出,请稍后重试",type:"warning"});return}const i=Array.isArray(this.runtimeQueuedMessages)?[...this.runtimeQueuedMessages]:[],r=i.filter(o=>(o==null?void 0:o.id)!==e.id);r.length!==i.length&&(this.runtimeQueuedMessages=r,this.setRuntimeQueueSyncLock(r,2200)),this.ensureRuntimeQueueSuppressionState(),e!=null&&e.id&&this.runtimeQueueSuppressedMessageIds.delete(e.id);return}try{const{useTaskStore:n}=await wt(async()=>{const{useTaskStore:l}=await Promise.resolve().then(()=>so);return{useTaskStore:l}},void 0),r=n().currentTaskId;if(!r){this.uiPushToast({title:"暂不可引导",message:"未检测到活跃任务,请稍后再试",type:"warning"});return}const o=await fetch(`/api/tasks/${encodeURIComponent(r)}/runtime_queue/${encodeURIComponent(s)}/guide`,{method:"POST"}),a=await o.json().catch(()=>({}));if(!o.ok||!(a!=null&&a.success))throw new Error((a==null?void 0:a.error)||"提交引导失败");const c=this.applyRuntimeQueuedMessages(((t=a==null?void 0:a.data)==null?void 0:t.messages)||[])||[];this.setRuntimeQueueSyncLock(c,2200),this.uiPushToast({title:"已设为引导对话",message:"将在下一次工具结果后插入到当前对话",type:"success",duration:1800})}catch(n){this.uiPushToast({title:"引导失败",message:(n==null?void 0:n.message)||"请稍后重试",type:"error"})}}},async tryAutoSendRuntimeQueuedMessages(s="unspecified"){if(this.runtimeQueueAutoSendInProgress||this.composerBusy||this.streamingMessage||this.taskInProgress||this.stopRequested||this.waitingForSubAgent)return!1;const e=Array.isArray(this.runtimeGuidanceFallbackQueue)?this.runtimeGuidanceFallbackQueue:[],t=Array.isArray(this.runtimeQueuedMessages)?this.runtimeQueuedMessages:[];let n="",i="runtime_queue",r=null,o=[],a=-1;if(e.length>0)for(let l=0;l<e.length;l+=1){const u=(e[l]||"").toString().trim();if(u&&!this.consumeSuppressedRuntimeGuidanceText(u)){n=u,i="runtime_guidance_fallback",a=l;break}}if(!n&&t.length>0)for(let l=0;l<t.length;l+=1){const u=t[l],h=String((u==null?void 0:u.id)||"").trim(),d=((u==null?void 0:u.text)||"").toString().trim();if(!(!h||!d)&&!this.consumeSuppressedRuntimeQueueMessageId(h)){n=d,i=(u==null?void 0:u.source)||"runtime_queue",r=h,o=Array.isArray(u==null?void 0:u.files)?[...u.files]:[];break}}if(!n)return!1;this.runtimeQueueAutoSendInProgress=!0;let c=!1;try{c=!!await this.sendMessage({presetText:n,source:i,files:o})}catch{c=!1}finally{this.runtimeQueueAutoSendInProgress=!1}if(!c)return!1;if(i==="runtime_guidance_fallback"){const l=Array.isArray(this.runtimeGuidanceFallbackQueue)?[...this.runtimeGuidanceFallbackQueue]:[],u=a>=0?a:l.findIndex(h=>String(h||"").trim()===n);u>=0&&(l.splice(u,1),this.runtimeGuidanceFallbackQueue=l)}else{const l=Array.isArray(this.runtimeQueuedMessages)?[...this.runtimeQueuedMessages]:[];if(r){const u=l.filter(h=>(h==null?void 0:h.id)!==r);this.runtimeQueuedMessages=u,this.setRuntimeQueueSyncLock(u,1500)}else{const u=l.findIndex(h=>String((h==null?void 0:h.text)||"").trim()===n);u>=0&&(l.splice(u,1),this.runtimeQueuedMessages=l,this.setRuntimeQueueSyncLock(l,1500))}}return Oe("[RuntimeQueue] auto-send success",{reason:s,source:i,messagePreview:n.slice(0,60)}),!0}},wne={async executeSystemCommand(s,e={}){const t=(s||"").toString().trim();if(!t)return{success:!1,message:"命令不能为空"};if(!this.isConnected)return e.showToast!==!1&&this.uiPushToast({title:"连接不可用",message:"当前无法执行命令,请稍后重试。",type:"error"}),{success:!1,message:"连接不可用"};try{const i=await(await fetch("/api/commands",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({command:t})})).json().catch(()=>({})),r={command:i.command||t.replace(/^\//,""),success:!!i.success,message:i.message,data:i.data};return this.handleSystemCommandResult(r,e),r}catch(n){const i=n instanceof Error?n.message:"命令执行失败",r={command:t.replace(/^\//,""),success:!1,message:i};return this.handleSystemCommandResult(r,e),r}},handleSystemCommandResult(s,e={}){var n,i;const t=e.showToast!==!1;if(s.command==="clear"&&s.success){(n=this.logMessageState)==null||n.call(this,"command_result-clear",{data:s}),this.messages=[],(i=this.logMessageState)==null||i.call(this,"command_result-cleared",{data:s}),this.currentMessageIndex=-1,this.chatClearExpandedBlocks(),this.resetTokenStatistics(),t&&this.uiPushToast({title:"已清除",message:s.message||"对话已清除",type:"success"});return}if(s.command==="status"&&s.success){this.addSystemMessage(`系统状态:
${JSON.stringify(s.data||{},null,2)}`),t&&this.uiPushToast({title:"状态已更新",message:"已获取系统状态",type:"success"});return}if(!s.success){this.addSystemMessage(`命令失败: ${s.message||"未知错误"}`),t&&this.uiPushToast({title:"命令执行失败",message:s.message||"请稍后重试",type:"error"});return}t&&this.uiPushToast({title:"命令已执行",message:s.command||"完成",type:"success"})}},XR=/\[\$([^\]\n]+)\]\(((?:[^)\n]*[\\/])?\.astrion[\\/]skills[\\/][^)\n]+[\\/]SKILL\.md)\)/g;function kne(s=""){const e=[],t=new Set,n=String(s||"");let i;for(XR.lastIndex=0;i=XR.exec(n);){const r=String(i[1]||"").trim().replace(/^\$/,""),o=String(i[2]||"").trim();!o||t.has(o)||(t.add(o),e.push({name:r,path:o}))}return e}const Cne={async handleSendOrStop(){if(this.compressionActiveForCurrentConversation){this.uiPushToast({title:"对话自动压缩中",message:"当前不可发送/停止,请等待压缩完成",type:"warning"});return}const s=(this.inputMessage||"").trim().length>0,e=Array.isArray(this.selectedImages)&&this.selectedImages.length>0||Array.isArray(this.selectedVideos)&&this.selectedVideos.length>0;if(Array.isArray(this.selectedFiles)&&this.selectedFiles.length>0&&!s&&!e&&!this.composerBusy){this.uiPushToast({title:"需要文字消息",message:"附加文件需随文字消息一起发送",type:"warning"});return}const n=typeof this.mainChatIdle=="function"?this.mainChatIdle:!this.streamingUi&&!this.stopRequested&&!this.compressionActiveForCurrentConversation;if(this.composerBusy&&n&&s){if(Array.isArray(this.pendingUserQuestions)&&this.pendingUserQuestions.length>0){await this.answerUserQuestionFromComposer(this.inputMessage)&&(this.inputClearMessage(),this.inputSetLineCount(1),this.inputSetMultiline(!1),this.autoResizeInput());return}this.sendMessage();return}if(this.composerBusy&&n&&e){this.uiPushToast({title:"后台子智能体运行中",message:"请等待后台任务结束后再发送图片/视频",type:"warning"});return}if(this.composerBusy){if(s){if(Array.isArray(this.pendingUserQuestions)&&this.pendingUserQuestions.length>0){await this.answerUserQuestionFromComposer(this.inputMessage)&&(this.inputClearMessage(),this.inputSetLineCount(1),this.inputSetMultiline(!1),this.autoResizeInput());return}await this.enqueueRuntimeQueuedMessage(this.inputMessage,Array.isArray(this.selectedFiles)?[...this.selectedFiles]:[])&&(this.inputClearMessage(),this.inputClearSelectedFiles(),this.inputSetLineCount(1),this.inputSetMultiline(!1),this.autoResizeInput());return}if(e){this.uiPushToast({title:"运行中仅支持文本",message:"图片/视频请等待当前任务结束后发送",type:"warning"});return}this.stopTask()}else{if(this.currentWorkspaceHasRunningTask){this.uiPushToast({title:"当前对话正在运行",message:"请等待当前对话任务完成后再发送新消息;同工作区的其他对话可正常并行。",type:"warning"});return}this.sendMessage()}},async sendMessage(s={}){var S;const e=typeof(s==null?void 0:s.presetText)=="string"?s.presetText:null,t=e!==null;if(this.compressionActiveForCurrentConversation)return this.uiPushToast({title:"对话自动压缩中",message:"压缩完成后才能继续发送消息",type:"warning"}),!1;if(this.streamingUi&&!t)return!1;if(!this.isConnected)return this.uiPushToast({title:"连接已断开",message:"当前无法发送消息,请等待连接恢复后重试",type:"warning"}),!1;if(this.mediaUploading&&!t)return this.uiPushToast({title:"上传中",message:"请等待图片/视频上传完成后再发送",type:"info"}),!1;let n=((t?e:this.inputMessage)||"").trim(),i=[];if(!t){const C=typeof this.getInputComposerRef=="function"?this.getInputComposerRef():null,T=C&&typeof C.prepareMessageForSend=="function"?C.prepareMessageForSend(this.inputMessage):null;T&&typeof T.message=="string"&&(n=T.message.trim(),i=Array.isArray(T.skillRefs)?T.skillRefs:[])}const r=t?[]:Array.isArray(this.selectedImages)?this.selectedImages.slice(0,9):[],o=t?[]:Array.isArray(this.selectedVideos)?this.selectedVideos.slice(0,1):[],a=t?Array.isArray(s==null?void 0:s.files)?s.files.slice(0,9):[]:Array.isArray(this.selectedFiles)?this.selectedFiles.slice(0,9):[],c=n.length>0,l=r.length>0,u=o.length>0,h=a.length>0;if(!c&&!l&&!u)return!1;const d=this.thinkingMode?"thinking":"fast";if(this.isQuotaExceeded(d))return this.showQuotaToast({type:d}),!1;const m=Qi().models.find(C=>C.key===this.currentModelKey);if(l&&!(m!=null&&m.supportsImage))return this.uiPushToast({title:"当前模型不支持图片",message:"请切换到支持图片输入的模型再发送图片",type:"error"}),!1;if(u&&!(m!=null&&m.supportsVideo))return this.uiPushToast({title:"当前模型不支持视频",message:"请切换到支持视频输入的模型后再发送视频",type:"error"}),!1;if(u&&l)return this.uiPushToast({title:"请勿同时发送",message:"视频与图片需分开发送,每条仅包含一种媒体",type:"warning"}),!1;u&&this.uiPushToast({title:"视频处理中",message:"读取视频需要较长时间,请耐心等待",type:"info",duration:5e3});const v=n,g=t?[]:i.length?i:kne(v);this.isConversationBlank()&&(this.blankHeroExiting=!0,this.blankHeroActive=!0,setTimeout(()=>{this.blankHeroExiting=!1,this.blankHeroActive=!1},320));let b=this.currentConversationId,_=null;if(!b)try{const C=qs();this.versioningHostMode&&C.form.versioning_enabled_by_default&&C.form.versioning_backup_mode==="full"&&(_=this.uiPushToast({title:"正在初始化备份",message:"正在创建完整工作区快照,请稍候…",type:"info",duration:null,closable:!1}),this.versioningInitializingBackupToastId=_);const k=this.newConversationType==="multi_agent",A=k?"/api/multiagent/conversations":"/api/conversations",M=JSON.stringify(k?{preserve_mode:!0,thinking_mode:this.thinkingMode,mode:this.runMode,reasoning_effort:this.reasoningEffort}:{thinking_mode:this.thinkingMode,mode:this.runMode,reasoning_effort:this.reasoningEffort}),R=await fetch(A,{method:"POST",headers:{"Content-Type":"application/json"},body:M}),P=await R.json().catch(()=>({}));if(!R.ok||!(P!=null&&P.success)||!(P!=null&&P.conversation_id))throw new Error((P==null?void 0:P.message)||(P==null?void 0:P.error)||"创建对话失败");b=P.conversation_id,this.currentConversationType=k?"multi_agent":"normal";try{const{useConversationStore:Q}=await wt(async()=>{const{useConversationStore:W}=await Promise.resolve().then(()=>Ei);return{useConversationStore:W}},void 0);Q().$patch({multiAgentMode:k})}catch{}this.skipConversationHistoryReload=!0,this.currentConversationId=b,this.currentConversationTitle="新对话";const L={id:b,title:"新对话",updated_at:new Date().toISOString(),total_messages:0,total_tools:0};this.conversations.splice(0,this.conversations.length,L,...this.conversations.filter(Q=>Q&&Q.id!==b));try{const{useConversationStore:Q}=await wt(async()=>{const{useConversationStore:N}=await Promise.resolve().then(()=>Ei);return{useConversationStore:N}},void 0),W=Q(),V=this.currentHostWorkspaceId;if(V){W.ensureWorkspaceGroup(V);const N=W.workspaceGroups.find(O=>O.workspaceId===V);N&&(N.conversations.splice(0,N.conversations.length,L,...N.conversations.filter(O=>O.id!==b)),N.expanded=!0,N.visibleOffset=0,N.visibleLimit=5)}}catch{}const z=this.stripConversationPrefix(b);history.replaceState({conversationId:b},"",`/${z}`)}catch(C){return this.uiPushToast({title:"发送失败",message:(C==null?void 0:C.message)||"创建新对话失败,请重试",type:"error"}),!1}finally{_&&(this.uiDismissToast(_),this.versioningInitializingBackupToastId=null)}this.taskInProgress=!0,typeof this.startRunningStateReconcile=="function"&&this.startRunningStateReconcile();const w=t?(s==null?void 0:s.source)==="runtime_queue_manual_guide"?"guidance":"presend":"user";this.chatAddUserMessage(v,r,o,[],w,h?{files:[...a]}:{}),this.chatStartAssistantMessage(),this.stopRequested=!1,typeof this.monitorShowPendingReply=="function"&&this.monitorShowPendingReply(),this.autoScrollEnabled&&this.scrollToBottom();try{const{useTaskStore:C}=await wt(async()=>{const{useTaskStore:A}=await Promise.resolve().then(()=>so);return{useTaskStore:A}},void 0),T=C();typeof this.clearProcessedEvents=="function"&&this.clearProcessedEvents();const k=this.goalModeArmed===!0;k&&(this.goalModeArmed=!1,this.goalRunning=!0,this.goalProgress={goal:v,status:"running",turn_count:0,tokens_used:0,tool_calls:0,duration_seconds:0}),await T.createTask(v,r,o,b,{model_key:this.currentModelKey,run_mode:this.runMode,thinking_mode:this.thinkingMode,message_source:w,goal_mode:k,skill_refs:g,files:a,eventHandler:A=>this.handleTaskEvent(A)}),Oe("[Message] 任务已创建,开始轮询"),await((S=this.refreshRunningWorkspaceTasks)==null?void 0:S.call(this))}catch(C){return console.error("[Message] 创建任务失败:",C),this.uiPushToast({title:"发送失败",message:C.message||"创建任务失败,请重试",type:"error"}),this.streamingMessage=!1,this.taskInProgress=!1,typeof this.cleanupTrailingEmptyAssistantPlaceholder=="function"&&this.cleanupTrailingEmptyAssistantPlaceholder("create_task_failed"),typeof this.forceUnlockMonitor=="function"&&this.forceUnlockMonitor("create_task_failed"),!1}return t||(this.inputClearMessage(),this.inputClearSelectedImages(),this.inputClearSelectedVideos(),this.inputClearSelectedFiles(),this.inputSetImagePickerOpen(!1),this.inputSetVideoPickerOpen(!1),this.inputSetLineCount(1),this.inputSetMultiline(!1),this.persistComposerDraftNow({reason:"send-message-cleared",force:!0,keepalive:!0}).catch(()=>{})),l&&(this.conversationHasImages=!0,this.conversationHasVideos=!1),u&&(this.conversationHasVideos=!0,this.conversationHasImages=!1),this.autoScrollEnabled&&this.scrollToBottom(),this.autoResizeInput(),setTimeout(()=>{this.currentConversationId&&this.updateCurrentContextTokens()},1e3),!0},async stopTask(){if(this._stopTaskRunning){yn("stopTask:debounce-rejected",{stopRequested:this.stopRequested});return}if(this._stopTaskRunning=!0,this.compressionActiveForCurrentConversation){this._stopTaskRunning=!1,this.uiPushToast({title:"对话自动压缩中",message:"压缩进行中,当前不可停止任务",type:"warning"});return}const s=this.streamingUi&&!this.stopRequested;if(yn("stopTask:entry",{composerBusy:this.composerBusy,stopRequested:this.stopRequested,taskInProgress:this.taskInProgress,streamingUi:this.streamingUi,canStop:s,currentTaskId:this.currentTaskId}),!s){this._stopTaskRunning=!1;return}const e=this.streamingUi;typeof this.markRuntimeQueueSuppressedByManualStop=="function"&&this.markRuntimeQueueSuppressedByManualStop(),this.stopRequested=!0,this.dropToolEvents=e,(this.goalRunning||this.goalModeArmed)&&(this.goalRunning=!1,this.goalModeArmed=!1,this.goalProgress=null,this.goalDialogOpen=!1);try{const{useTaskStore:t}=await wt(async()=>{const{useTaskStore:o}=await Promise.resolve().then(()=>so);return{useTaskStore:o}},void 0),n=t();n.currentTaskId&&await n.cancelTask(),await new Promise(o=>setTimeout(o,300));const i=["running","pending","cancel_requested","canceled"].includes(String(n.taskStatus));yn("stopTask:try-end",{currentTaskId:n.currentTaskId,taskStatus:n.taskStatus,shouldKeepBusy:i,streamingMessage:this.streamingMessage}),this.clearPendingTools("user_stop"),this.streamingMessage=!1,this.taskInProgress=i,this.forceUnlockMonitor("user_stop"),typeof this.clearProcessedEvents=="function"&&this.clearProcessedEvents();const r=this.messages[this.messages.length-1];r&&r.role==="assistant"&&(r.awaitingFirstContent=!1,r.generatingLabel="")}catch(t){console.error("[Message] 取消任务失败:",t);const{useTaskStore:n}=await wt(async()=>{const{useTaskStore:a}=await Promise.resolve().then(()=>so);return{useTaskStore:a}},void 0),i=n(),r=["running","pending","cancel_requested","canceled"].includes(String(i.taskStatus));yn("stopTask:catch",{error:String(t),currentTaskId:i.currentTaskId,taskStatus:i.taskStatus,shouldKeepBusy:r}),this.clearPendingTools("user_stop"),this.streamingMessage=!1,this.taskInProgress=r,this.forceUnlockMonitor("user_stop"),typeof this.clearProcessedEvents=="function"&&this.clearProcessedEvents();const o=this.messages[this.messages.length-1];o&&o.role==="assistant"&&(o.awaitingFirstContent=!1,o.generatingLabel=""),this.uiPushToast({title:"停止请求已发送",message:"若主对话未停止,请稍候;后台任务可通过状态栏单独停止",type:"info"})}finally{this.dropToolEvents=!1,this.stopRequested=!1,this._stopTaskRunning=!1}}},Tne={async clearChat(){await this.confirmAction({title:"清除对话",message:"确定要清除所有对话记录吗?该操作不可撤销。",confirmText:"清除",cancelText:"取消"})&&await this.executeSystemCommand("/clear",{showToast:!1})},async compressConversation(){if(!this.currentConversationId){this.uiPushToast({title:"无法压缩",message:"当前没有可压缩的对话。",type:"info"});return}if(!this.compressing){this.compressing=!0,this.compressionInProgress=!0,this.compressionConversationId=this.currentConversationId,this.compressionMode="manual",this.compressionStage="requesting",this.compressionError="",this.compressionToastId&&(this.uiDismissToast(this.compressionToastId),this.compressionToastId=null),this.compressionToastId=this.uiPushToast({title:"压缩中",message:"对话正在压缩,请稍候…",type:"info",duration:null,closable:!1});try{const s=await fetch(`/api/conversations/${this.currentConversationId}/compress`,{method:"POST"}),e=await s.json();if(s.ok&&e.success){this.compressionStage="switching";const t=e.compressed_conversation_id,n=t&&t===this.currentConversationId;t&&!n&&await this.loadConversation(t,{force:!0});const i=(e.guide_message||"").trim();t&&!n?await this.loadConversation(t,{force:!0}):n&&await this.loadConversation(this.currentConversationId,{force:!0}),n||await this.loadConversationsList(),Oe("对话压缩完成:",e),this.uiPushToast({title:"压缩完成",message:"已压缩较早的对话内容",type:"success",duration:2200})}else{const t=e.message||e.error||"压缩失败";this.compressionError=t,this.uiPushToast({title:"压缩失败",message:t,type:"error"})}}catch(s){console.error("压缩对话异常:",s),this.compressionError=s.message||"请稍后重试",this.uiPushToast({title:"压缩对话异常",message:s.message||"请稍后重试",type:"error"})}finally{this.compressionToastId&&(this.uiDismissToast(this.compressionToastId),this.compressionToastId=null),this.compressing=!1,this.compressionInProgress=!1,this.compressionConversationId=null,this.compressionMode="",this.compressionStage=""}}},async sendAutoUserMessage(s){const e=(s||"").trim();if(!e||!this.isConnected)return!1;const t=this.thinkingMode?"thinking":"fast";if(this.isQuotaExceeded(t))return this.showQuotaToast({type:t}),!1;this.taskInProgress=!0,this.chatAddUserMessage(e,[],[],[],"user"),this.chatStartAssistantMessage(),this.stopRequested=!1,typeof this.monitorShowPendingReply=="function"&&this.monitorShowPendingReply();try{const{useTaskStore:n}=await wt(async()=>{const{useTaskStore:r}=await Promise.resolve().then(()=>so);return{useTaskStore:r}},void 0),i=n();typeof this.clearProcessedEvents=="function"&&this.clearProcessedEvents(),await i.createTask(e,[],[],this.currentConversationId,{eventHandler:r=>this.handleTaskEvent(r)})}catch(n){return console.error("[Message] 自动消息创建任务失败:",n),this.uiPushToast({title:"发送失败",message:(n==null?void 0:n.message)||"创建任务失败,请重试",type:"error"}),this.streamingMessage=!1,this.taskInProgress=!1,typeof this.cleanupTrailingEmptyAssistantPlaceholder=="function"&&this.cleanupTrailingEmptyAssistantPlaceholder("auto_create_task_failed"),typeof this.forceUnlockMonitor=="function"&&this.forceUnlockMonitor("auto_create_task_failed"),!1}return this.autoScrollEnabled&&this.scrollToBottom(),this.autoResizeInput(),setTimeout(()=>{this.currentConversationId&&this.updateCurrentContextTokens()},1e3),!0},autoResizeInput(){this.$nextTick(()=>{const s=this.getComposerElement("stadiumInput");if(!s||!(s instanceof HTMLTextAreaElement))return;const e=s.offsetHeight;s.style.height="auto";const t=window.getComputedStyle(s),n=parseFloat(t.lineHeight||"20")||20,i=n*6,r=Math.min(s.scrollHeight,i);if(this.inputSetLineCount(Math.max(1,Math.round(r/n))),this.inputSetMultiline(r>n*1.4),Math.abs(r-e)<=.5){s.style.height=`${r}px`;return}s.style.height=`${e}px`,s.offsetHeight,requestAnimationFrame(()=>{s.style.height=`${r}px`})})}},Ane={...Sne,...wne,...Cne,...Tne},Ene=50,Mne=20,xne={handleSidebarSearchInput(s){this.searchQuery=s},handleSidebarSearchSubmit(s){this.searchQuery=s;const e=String(s||"").trim();if(!e){this.exitConversationSearch();return}this.startConversationSearch(e)},exitConversationSearch(){this.searchActive=!1,this.searchInProgress=!1,this.searchMoreAvailable=!1,this.searchOffset=0,this.searchTotal=0,this.searchResults=[],this.searchGroups=[],this.searchActiveQuery="",this.conversationsOffset=0,this.loadConversationsList()},isGroupedSidebarSearch(){var e;const s=qs();return!!((e=s==null?void 0:s.form)!=null&&e.group_sidebar_by_workspace)&&!!(this.versioningHostMode||this.dockerProjectMode)},async startConversationSearch(s){const e=String(s||"").trim();if(!e)return;const t=++this.searchRequestSeq;this.searchActiveQuery=e,this.searchActive=!0,this.searchInProgress=!0,this.searchMoreAvailable=!1,this.searchOffset=0,this.searchTotal=0,this.searchResults=[],this.searchGroups=[];const{useConversationStore:n}=await wt(async()=>{const{useConversationStore:a}=await Promise.resolve().then(()=>Ei);return{useConversationStore:a}},void 0),i=n().sidebarConversationType==="multi_agent"?"&multi_agent_mode=1":"&multi_agent_mode=0",r=this.isGroupedSidebarSearch(),o=r?`/api/conversations/search?q=${encodeURIComponent(e)}&limit=${Mne}&all_workspaces=1${i}`:`/api/conversations/search?q=${encodeURIComponent(e)}&limit=${Ene}${i}`;try{const c=await(await fetch(o)).json();if(t!==this.searchRequestSeq)return;if(!c.success){console.error("搜索对话失败:",c.error||c.message);return}const l=c.data||{};r?this.searchGroups=Array.isArray(l.groups)?l.groups:[]:(this.searchResults=Array.isArray(l.results)?l.results:[],this.searchTotal=l.count||this.searchResults.length)}catch(a){console.error("搜索对话异常:",a)}finally{t===this.searchRequestSeq&&(this.searchInProgress=!1)}},async loadMoreSearchResults(){}},Ine={triggerFileUpload(){if(this.uploading)return;const s=this.getComposerElement("fileUploadInput");s&&s.click()},handleFileSelected(s){var n;if((n=No().uiBlocks)!=null&&n.block_upload){this.uiPushToast({title:"上传被禁用",message:"已被管理员禁用上传功能",type:"warning"});return}const t=Array.isArray(s)?s.filter(Boolean):Array.from(s||[]).filter(Boolean);t.length&&this.processDroppedFiles(t)},async openImagePicker(){const e=Qi().models.find(t=>t.key===this.currentModelKey);if(!(e!=null&&e.supportsImage)){this.uiPushToast({title:"当前模型不支持图片",message:"请选择支持图片输入的模型后再发送图片",type:"error"});return}this.closeQuickMenu(),this.inputSetImagePickerOpen(!0),await this.loadWorkspaceImages()},closeImagePicker(){this.inputSetImagePickerOpen(!1)},async openVideoPicker(){const e=Qi().models.find(t=>t.key===this.currentModelKey);if(!(e!=null&&e.supportsVideo)){this.uiPushToast({title:"当前模型不支持视频",message:"请切换到支持视频输入的模型后再发送视频",type:"error"});return}this.closeQuickMenu(),this.inputSetVideoPickerOpen(!0),await this.loadWorkspaceVideos()},closeVideoPicker(){this.inputSetVideoPickerOpen(!1)}},Rne={normalizeLocalFiles(s){return s?(Array.isArray(s)?s:Array.from(s)).filter(Boolean):[]},isImageFile(s){const e=(s==null?void 0:s.name)||"",t=((s==null?void 0:s.type)||"").toLowerCase();return t==="image/svg+xml"||/\.svg$/i.test(e)?!1:t.startsWith("image/")||/\.(png|jpe?g|webp|gif|bmp)$/i.test(e)},isVideoFile(s){const e=(s==null?void 0:s.name)||"";return((s==null?void 0:s.type)||"").startsWith("video/")||/\.(mp4|mov|m4v|webm|avi|mkv|flv|mpg|mpeg)$/i.test(e)},async handleLocalImageFiles(s){if(!this.isConnected)return;if(this.mediaUploading){this.uiPushToast({title:"上传中",message:"请等待当前图片上传完成",type:"info"});return}const e=this.normalizeLocalFiles(s);if(!e.length){this.uiPushToast({title:"未获取到文件",message:"系统未返回有效的文件内容,请重试",type:"warning"});return}const t=Array.isArray(this.selectedImages)?this.selectedImages.length:0,n=Math.max(0,9-t);if(!n){this.uiPushToast({title:"已达上限",message:"最多只能选择 9 张图片",type:"warning"});return}const i=e.filter(c=>this.isImageFile(c)),r=i.length?i:e;i.length<e.length&&i.length>0&&this.uiPushToast({title:"已忽略",message:"已跳过非图片文件",type:"info"});const o=r.slice(0,n);r.length>n&&this.uiPushToast({title:"已超出数量",message:`最多还能添加 ${n} 张图片,已自动截断`,type:"warning"});const a=await this.uploadBatchFiles(o,{markUploading:!0,markMediaUploading:!0});a.length&&(a.forEach(c=>{c!=null&&c.path&&(this.inputAddSelectedImage(c.path),this.upsertImageEntry(c.path,c.filename))}),this.closeImagePicker())},async handleLocalGenericFiles(s){if(!this.isConnected)return;if(this.uploading){this.uiPushToast({title:"上传中",message:"请等待当前文件上传完成",type:"info"});return}const e=this.normalizeLocalFiles(s);if(!e.length){this.uiPushToast({title:"未获取到文件",message:"系统未返回有效的文件内容,请重试",type:"warning"});return}const t=Array.isArray(this.selectedFiles)?this.selectedFiles.length:0,n=Math.max(0,9-t);if(!n){this.uiPushToast({title:"已达上限",message:"最多只能附加 9 个文件",type:"warning"});return}const i=e.slice(0,n);e.length>n&&this.uiPushToast({title:"已超出数量",message:`最多还能附加 ${n} 个文件,已自动截断`,type:"warning"});const r=await this.uploadBatchFiles(i,{markUploading:!0,markMediaUploading:!1});r.length&&r.forEach(o=>{o!=null&&o.path&&this.inputAddSelectedFile(o.path)})},async handleLocalVideoFiles(s){if(!this.isConnected)return;if(this.mediaUploading){this.uiPushToast({title:"上传中",message:"请等待当前视频上传完成",type:"info"});return}const e=this.normalizeLocalFiles(s);if(!e.length){this.uiPushToast({title:"未获取到文件",message:"系统未返回有效的文件内容,请重试",type:"warning"});return}const t=e.filter(a=>this.isVideoFile(a)),n=t.length?t:e;t.length<e.length&&t.length>0&&this.uiPushToast({title:"已忽略",message:"已跳过非视频文件",type:"info"}),n.length>1&&this.uiPushToast({title:"视频数量过多",message:"一次只能选择 1 个视频,已使用第一个",type:"warning"});const[i]=n;if(!i)return;const r=await this.uploadBatchFiles([i],{markUploading:!0,markMediaUploading:!0}),[o]=r;o!=null&&o.path&&(this.inputSetSelectedVideos([o.path]),this.inputClearSelectedImages(),this.upsertVideoEntry(o.path,o.filename))}},Lne={upsertImageEntry(s,e){if(!s)return;const t=e||s.split("/").pop()||s,n=Array.isArray(this.imageEntries)?this.imageEntries:[];n.some(i=>i.path===s)||(this.imageEntries=[{name:t,path:s},...n])},upsertVideoEntry(s,e){if(!s)return;const t=e||s.split("/").pop()||s,n=Array.isArray(this.videoEntries)?this.videoEntries:[];n.some(i=>i.path===s)||(this.videoEntries=[{name:t,path:s},...n])},async fetchAllImageEntries(s=""){var o,a;const e=[s||""],t=new Set,n=[],i=new Set([".png",".jpg",".jpeg",".webp",".gif",".bmp",".svg"]),r=120;for(;e.length&&t.size<r;){const c=e.shift()||"";if(!t.has(c)){t.add(c);try{const u=await(await fetch(`/api/gui/files/entries?path=${encodeURIComponent(c)}`,{method:"GET",credentials:"include",headers:{Accept:"application/json"}})).json().catch(()=>null);if(!(u!=null&&u.success))continue;const h=Array.isArray((o=u==null?void 0:u.data)==null?void 0:o.items)?u.data.items:[];for(const d of h){const p=(d==null?void 0:d.path)||[c,d==null?void 0:d.name].filter(Boolean).join("/").replace(/\\/g,"/").replace(/\/{2,}/g,"/"),m=String((d==null?void 0:d.type)||"").toLowerCase();if(m==="directory"||m==="folder"){e.push(p);continue}const v=String((d==null?void 0:d.extension)||"").toLowerCase()||(p.includes(".")?`.${(a=p.split(".").pop())==null?void 0:a.toLowerCase()}`:"");if(i.has(v)&&(n.push({name:(d==null?void 0:d.name)||p.split("/").pop()||p,path:p}),n.length>=400))return n}}catch(l){console.warn("遍历文件夹失败",c,l)}}}return n},async fetchAllVideoEntries(s=""){var o,a;const e=[s||""],t=new Set,n=[],i=new Set([".mp4",".mov",".mkv",".avi",".webm"]),r=120;for(;e.length&&t.size<r;){const c=e.shift()||"";if(!t.has(c)){t.add(c);try{const u=await(await fetch(`/api/gui/files/entries?path=${encodeURIComponent(c)}`,{method:"GET",credentials:"include",headers:{Accept:"application/json"}})).json().catch(()=>null);if(!(u!=null&&u.success))continue;const h=Array.isArray((o=u==null?void 0:u.data)==null?void 0:o.items)?u.data.items:[];for(const d of h){const p=(d==null?void 0:d.path)||[c,d==null?void 0:d.name].filter(Boolean).join("/").replace(/\\/g,"/").replace(/\/{2,}/g,"/"),m=String((d==null?void 0:d.type)||"").toLowerCase();if(m==="directory"||m==="folder"){e.push(p);continue}const v=String((d==null?void 0:d.extension)||"").toLowerCase()||(p.includes(".")?`.${(a=p.split(".").pop())==null?void 0:a.toLowerCase()}`:"");if(i.has(v)&&(n.push({name:(d==null?void 0:d.name)||p.split("/").pop()||p,path:p}),n.length>=200))return n}}catch(l){console.warn("遍历文件夹失败",c,l)}}}return n},async loadWorkspaceImages(){this.imageLoading=!0;try{const s=await this.fetchAllImageEntries("");this.imageEntries=s,s.length||this.uiPushToast({title:"未找到图片",message:"工作区内没有可用的图片文件",type:"info"})}catch(s){console.error("加载图片列表失败",s),this.uiPushToast({title:"加载图片失败",message:(s==null?void 0:s.message)||"请稍后重试",type:"error"})}finally{this.imageLoading=!1}},async loadWorkspaceVideos(){this.videoLoading=!0;try{const s=await this.fetchAllVideoEntries("");this.videoEntries=s,s.length||this.uiPushToast({title:"未找到视频",message:"工作区内没有可用的视频文件",type:"info"})}catch(s){console.error("加载视频列表失败",s),this.uiPushToast({title:"加载视频失败",message:(s==null?void 0:s.message)||"请稍后重试",type:"error"})}finally{this.videoLoading=!1}}},Pne={handleImagesConfirmed(s){this.inputSetSelectedImages(Array.isArray(s)?s:[]),this.inputSetImagePickerOpen(!1)},handleRemoveImage(s){this.inputRemoveSelectedImage(s)},handleVideosConfirmed(s){const e=Array.isArray(s)?s.slice(0,1):[];this.inputSetSelectedVideos(e),this.inputSetVideoPickerOpen(!1),e.length&&this.inputClearSelectedImages()},handleRemoveVideo(s){this.inputRemoveSelectedVideo(s)},handleRemoveFile(s){this.inputRemoveSelectedFile(s)}},One={handleQuickUpload(){this.uploading||!this.isConnected||this.isPolicyBlocked("block_upload","上传功能已被管理员禁用")||this.triggerFileUpload()}},Dne={handleDragEnter(s){var e,t;s.preventDefault(),s.stopPropagation(),(t=(e=s.dataTransfer)==null?void 0:e.types)!=null&&t.includes("Files")&&(this.dragOverActive=!0)},handleDragOver(s){s.preventDefault(),s.stopPropagation()},handleDragLeave(s){s.preventDefault(),s.stopPropagation();const e=document.body.getBoundingClientRect(),t=s.clientX,n=s.clientY;(t<=e.left||t>=e.right||n<=e.top||n>=e.bottom)&&(this.dragOverActive=!1)},handleDrop(s){var n,i;if(s.preventDefault(),s.stopPropagation(),this.dragOverActive=!1,!this.isConnected){this.uiPushToast({title:"未连接",message:"请等待服务器连接后再上传",type:"warning"});return}if((n=No().uiBlocks)!=null&&n.block_upload){this.uiPushToast({title:"上传被禁用",message:"已被管理员禁用上传功能",type:"warning"});return}const t=(i=s.dataTransfer)==null?void 0:i.files;!t||t.length===0||this.processDroppedFiles(Array.from(t))},async processDroppedFiles(s){if(!s.length)return;const e=s.filter(i=>this.isImageFile(i)),t=s.filter(i=>this.isVideoFile(i)),n=s.filter(i=>!this.isImageFile(i)&&!this.isVideoFile(i));e.length>0?await this.handleDroppedImages(e):t.length>0&&await this.handleDroppedVideo(t[0]),n.length>0&&await this.handleLocalGenericFiles(n)},async handleDroppedImages(s){const t=Qi().models.find(n=>n.key===this.currentModelKey);if(!(t!=null&&t.supportsImage)){this.uiPushToast({title:"当前模型不支持图片",message:"请选择支持图片输入的模型后再发送图片",type:"error"});return}await this.handleLocalImageFiles(s)},async handleDroppedVideo(s){const t=Qi().models.find(n=>n.key===this.currentModelKey);if(!(t!=null&&t.supportsVideo)){this.uiPushToast({title:"当前模型不支持视频",message:"请切换到支持视频输入的模型后再发送视频",type:"error"});return}await this.handleLocalVideoFiles([s])},_boundDragEnter:null,_boundDragOver:null,_boundDragLeave:null,_boundDrop:null,setupDragAndDrop(){this._boundDragEnter=this.handleDragEnter.bind(this),this._boundDragOver=this.handleDragOver.bind(this),this._boundDragLeave=this.handleDragLeave.bind(this),this._boundDrop=this.handleDrop.bind(this),document.body.addEventListener("dragenter",this._boundDragEnter),document.body.addEventListener("dragover",this._boundDragOver),document.body.addEventListener("dragleave",this._boundDragLeave),document.body.addEventListener("drop",this._boundDrop)},teardownDragAndDrop(){this._boundDragEnter&&document.body.removeEventListener("dragenter",this._boundDragEnter),this._boundDragOver&&document.body.removeEventListener("dragover",this._boundDragOver),this._boundDragLeave&&document.body.removeEventListener("dragleave",this._boundDragLeave),this._boundDrop&&document.body.removeEventListener("drop",this._boundDrop),this._boundDragEnter=null,this._boundDragOver=null,this._boundDragLeave=null,this._boundDrop=null}},Nne={handlePastedFiles(s){var n;const e=Array.isArray(s)?s.filter(Boolean):[];if(!e.length)return;if(!this.isConnected){this.uiPushToast({title:"未连接",message:"请等待服务器连接后再上传",type:"warning"});return}if((n=No().uiBlocks)!=null&&n.block_upload){this.uiPushToast({title:"上传被禁用",message:"已被管理员禁用上传功能",type:"warning"});return}this.processDroppedFiles(e)}},Bne={...Ine,...Rne,...Lne,...Pne,...One,...Dne,...Nne},YR=["B","KB","MB","GB","TB"],JR=["B/s","KB/s","MB/s","GB/s"],ZR={thinking:"思考模型",search:"搜索",fast:"常规模型"};function am(s){const e=Number(s);return Number.isFinite(e)?e:0}function Fne(s){const e=am(s);return e<1e3?e.toString():e<1e6?`${(e/1e3).toFixed(1)}K`:`${(e/1e6).toFixed(1)}M`}function $ne(s){if(s===null||typeof s>"u")return"—";let e=Number(s);if(!Number.isFinite(e))return"—";let t=0;for(;e>=1024&&t<YR.length-1;)e/=1024,t++;const n=e>=10||t===0?0:1;return`${e.toFixed(n)} ${YR[t]}`}function Hne(s){if(s===null||typeof s>"u")return"—";const e=Number(s);return Number.isFinite(e)?`${e.toFixed(1)}%`:"—"}function Une(s){if(s===null||typeof s>"u")return"—";let e=Number(s);if(!Number.isFinite(e))return"—";let t=0;for(;e>=1024&&t<JR.length-1;)e/=1024,t++;const n=e>=10||t===0?0:1;return`${e.toFixed(n)} ${JR[t]}`}function yM(s){return ZR[s]||ZR.fast}function bM(s){if(!s)return"--:--";const e=new Date(s);return Number.isNaN(e.getTime())?"--:--":e.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}function Wne(s){if(!s)return"--";const e=am(s.count),t=am(s.limit);return t?`${e} / ${t}`:`${e}`}function zne(s){if(!s)return"";const e=[];return["fast","thinking","search"].forEach(t=>{const n=s==null?void 0:s[t];n&&n.reset_at&&am(n.count)>0&&e.push(`${yM(t)} ${bM(n.reset_at)}`)}),e.join(" · ")}function jne(s,e){if(!s)return!1;const t=s[e];if(!t)return!1;const n=am(t.limit);return n?am(t.count)>=n:!1}function Vne(s,e,t){const n=e==null?void 0:e[s],i=typeof t<"u"?t:n==null?void 0:n.reset_at;return`${yM(s)} 配额已用完,将在 ${bM(i)} 重置`}const Gne={hasContainerStats(){return!!(this.containerStatus&&this.containerStatus.mode==="docker"&&this.containerStatus.stats)},containerStatusClass(){if(!this.containerStatus||this.containerStatus.mode!=="docker")return"status-pill--host";const s=this.containerStatus.state&&(this.containerStatus.state.status||this.containerStatus.state.Status)||"",e=String(s).toLowerCase();return e.includes("running")?"status-pill--running":e.includes("paused")||e.includes("exited")||e.includes("dead")?"status-pill--stopped":"status-pill--running"},containerStatusText(){if(!this.containerStatus)return"未知";if(this.containerStatus.mode!=="docker")return"宿主机模式";const s=this.containerStatus.state&&(this.containerStatus.state.status||this.containerStatus.state.Status)||"",e=String(s).toLowerCase();return e.includes("running")?"运行中":e.includes("paused")?"已暂停":e.includes("exited")||e.includes("dead")?"已停止":s||"容器模式"},formatTime(s){if(!s)return"未知时间";let e;if(typeof s=="number")e=new Date(s);else if(typeof s=="string"){const r=Date.parse(s);if(!Number.isNaN(r))e=new Date(r);else{const o=Number(s);Number.isNaN(o)||(e=new Date(o))}}else s instanceof Date&&(e=s);if(!e||Number.isNaN(e.getTime()))return String(s);const n=Date.now()-e.getTime();return n<6e4?"刚刚":n<36e5?`${Math.floor(n/6e4)} 分钟前`:n<864e5?`${Math.floor(n/36e5)} 小时前`:new Intl.DateTimeFormat("zh-CN",{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}).format(e)},async updateCurrentContextTokens(){await this.resourceUpdateCurrentContextTokens(this.currentConversationId)},async fetchConversationTokenStatistics(){await this.resourceFetchConversationTokenStatistics(this.currentConversationId)},toggleTokenPanel(){this.resourceToggleTokenPanel()},applyStatusSnapshot(s){var o;this.resourceApplyStatusSnapshot(s);const e=this.currentConversationId,t=typeof e=="string"&&e.length>0&&!e.startsWith("temp_"),n=typeof this.isExplicitNewConversationRoute=="function"&&this.isExplicitNewConversationRoute();!t&&!n&&(s&&typeof s.thinking_mode<"u"&&(this.thinkingMode=!!s.thinking_mode),s&&typeof s.run_mode=="string"?this.runMode=s.run_mode==="deep"?"thinking":s.run_mode:s&&typeof s.thinking_mode<"u"&&(this.runMode=s.thinking_mode?"thinking":"fast"),s&&Object.prototype.hasOwnProperty.call(s,"reasoning_effort")&&(this.reasoningEffort=typeof s.reasoning_effort=="string"?s.reasoning_effort:null),s&&typeof s.model_key=="string"&&this.modelSet(s.model_key)),s&&typeof s.permission_mode=="string"&&(this.currentPermissionMode=s.permission_mode),s&&typeof s.work_mode=="string"&&(this.currentWorkMode=s.work_mode);const i=(s==null?void 0:s.pending_runtime_modes)||{};typeof i.permission_mode=="string"?this.pendingPermissionMode=i.permission_mode:this.pendingPermissionMode="",s!=null&&s.execution_mode&&typeof s.execution_mode=="object"&&(typeof s.execution_mode.mode=="string"&&(this.currentExecutionMode=s.execution_mode.mode),this.executionModeEnabled=typeof s.execution_mode_enabled=="boolean"?s.execution_mode_enabled:!0),typeof s.network_permission=="string"&&(this.currentNetworkPermission=s.network_permission),this.networkPermissionEnabled=typeof s.network_permission_enabled=="boolean"?s.network_permission_enabled:!1,typeof i.network_permission=="string"?this.pendingNetworkPermission=i.network_permission:this.pendingNetworkPermission="",typeof i.execution_mode=="string"?this.pendingExecutionMode=i.execution_mode:this.pendingExecutionMode="",t&&!n?(s&&typeof s.has_images<"u"&&(this.conversationHasImages=!!s.has_images),s&&typeof s.has_videos<"u"&&(this.conversationHasVideos=!!s.has_videos)):(this.conversationHasImages=!1,this.conversationHasVideos=!1);const r=(o=s==null?void 0:s.conversation)==null?void 0:o.compression;t&&!n&&(r&&typeof r=="object"?(this.compressionInProgress=!!r.in_progress,this.compressionMode=r.mode||"",this.compressionStage=r.stage||"",this.compressionError=r.error||"",this.compressionConversationId=this.compressionInProgress?this.currentConversationId:null):(this.compressionInProgress=!1,this.compressionConversationId=null,this.compressionMode="",this.compressionStage="",this.compressionError=""))},updateContainerStatus(s){this.resourceUpdateContainerStatus(s)},pollContainerStats(){return this.resourcePollContainerStats()},startContainerStatsPolling(){this.resourceStartContainerStatsPolling()},stopContainerStatsPolling(){this.resourceStopContainerStatsPolling()},pollProjectStorage(){return this.resourcePollProjectStorage()},startProjectStoragePolling(){this.resourceStartProjectStoragePolling()},stopProjectStoragePolling(){this.resourceStopProjectStoragePolling()},fetchUsageQuota(){return this.resourceFetchUsageQuota()},startUsageQuotaPolling(){this.resourceStartUsageQuotaPolling()},stopUsageQuotaPolling(){this.resourceStopUsageQuotaPolling()},async downloadFile(s){if(!s){this.fileHideContextMenu();return}const e=`/api/download/file?path=${encodeURIComponent(s)}`,t=s.split("/").pop()||"file";await this.downloadResource(e,t)},async downloadFolder(s){if(!s){this.fileHideContextMenu();return}const e=`/api/download/folder?path=${encodeURIComponent(s)}`,t=s.split("/").filter(Boolean),n=t.length?t.pop():"folder";await this.downloadResource(e,`${n}.zip`)},async downloadResource(s,e){const t=window.AndroidDownloadBridge;if(t&&typeof t.downloadFile=="function")try{const n=new URL(s,window.location.href).href;t.downloadFile(n,e||"download");return}catch(n){console.warn("Android 桥接下载失败,回退:",n)}try{const n=await fetch(s);if(!n.ok){let c=n.statusText;try{const l=await n.json();c=l.error||l.message||c}catch{c=await n.text()}this.uiPushToast({title:"下载失败",message:c||"无法完成下载",type:"error"});return}const i=await n.blob(),r=e||"download",o=document.createElement("a"),a=URL.createObjectURL(i);o.href=a,o.download=r,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(a)}catch(n){console.error("下载失败:",n),this.uiPushToast({title:"下载失败",message:n.message||String(n),type:"error"})}finally{this.fileHideContextMenu()}},formatTokenCount:Fne,formatBytes:$ne,formatPercentage:Hne,formatRate:Une,formatResetTime:bM,formatQuotaValue:Wne,quotaTypeLabel:yM,quotaResetSummary(){return zne(this.usageQuota)},isQuotaExceeded(s){return jne(this.usageQuota,s)},showQuotaToast(s){if(!s)return;const e=s.type||"fast",t=Vne(e,this.usageQuota,s.reset_at);this.uiShowQuotaToastMessage(t,e)}},qne={create_file:"file-animation",read_file:"read-animation",read_skill:"read-animation",create_skill:"file-animation",delete_file:"file-animation",rename_file:"file-animation",write_file:"file-animation",edit_file:"file-animation",create_folder:"file-animation",web_search:"search-animation",extract_webpage:"search-animation",save_webpage:"file-animation",vlm_analyze:"file-animation",run_command:"terminal-animation",update_memory:"memory-animation",recall_project_memory:"read-animation",search_project_memory:"search-animation",update_project_memory:"memory-animation",sleep:"wait-animation",terminal_session:"terminal-animation",terminal_input:"terminal-animation",terminal_snapshot:"terminal-animation",todo_create:"file-animation",todo_update_task:"file-animation",create_sub_agent:"terminal-animation",ask_user:"default-animation"},Kne={create_file:"正在创建文件...",sleep:"正在等待...",delete_file:"正在删除文件...",rename_file:"正在重命名文件...",write_file:"正在写入文件...",edit_file:"正在编辑文件...",create_folder:"正在创建文件夹...",web_search:"正在搜索网络...",extract_webpage:"正在提取网页...",save_webpage:"正在保存网页...",run_command:"调用 run_command",update_memory:"正在更新记忆...",recall_project_memory:"正在回顾项目记忆...",search_project_memory:"正在检索项目记忆...",update_project_memory:"正在更新项目记忆...",terminal_session:"正在管理终端会话...",terminal_input:"调用 terminal_input",terminal_snapshot:"正在获取终端快照...",read_skill:"正在读取技能...",create_skill:"正在归档技能...",ask_user:"等待用户回答..."},Qne={create_file:"文件创建成功",delete_file:"文件删除成功",sleep:"等待完成",rename_file:"文件重命名成功",write_file:"文件写入完成",edit_file:"文件编辑完成",create_folder:"文件夹创建成功",web_search:"搜索完成",extract_webpage:"网页提取完成",save_webpage:"网页保存完成(纯文本)",vlm_analyze:"图片解析完成",run_command:"命令执行完成",update_memory:"记忆更新成功",recall_project_memory:"项目记忆已读取",search_project_memory:"项目记忆检索完成",update_project_memory:"项目记忆已更新",terminal_session:"终端操作完成",terminal_input:"终端输入完成",terminal_snapshot:"终端快照已返回",read_skill:"技能读取完成",create_skill:"技能归档完成",ask_user:"用户已回答"},Xne={py:"language-python",js:"language-javascript",html:"language-html",css:"language-css",json:"language-json",md:"language-markdown",txt:"language-plain"},Yne={general:"通用",news:"新闻",finance:"金融"},Jne={day:"过去24小时",week:"过去7天",month:"过去30天",year:"过去365天"};function Zne(s){const e=typeof s=="string"?s:s==null?void 0:s.name;return typeof e=="string"&&e.startsWith("mcp__")?"mcpLogo":lZ[e]||"settings"}function eie(s){return s?s.status==="hinted"?"hint-animation pulse-slow":s.status==="preparing"?"preparing-animation":s.status==="running"?qne[s.name]||"default-animation":"":""}function tie(s){if(!(s!=null&&s.result)||typeof s.result!="object")return"文件读取完成";const e=String(s.result.type||"read").toLowerCase();if(e==="search"){const t=s.result.query?`「${s.result.query}」`:"",n=typeof s.result.returned_matches=="number"?s.result.returned_matches:s.result.actual_matches||0;return`搜索${t},得到${n}个结果`}return e==="extract"?`提取了${(Array.isArray(s.result.segments)?s.result.segments:[]).reduce((r,o)=>{const a=Number(o.line_start)||0,c=Number(o.line_end)||0;return!a||!c||c<a?r:r+(c-a+1)},0)||s.result.char_count||0}行`:"文件读取完成"}function sie(s){return String((s==null?void 0:s.name)||"").startsWith("mcp__")}function nie(s){const e=String((s==null?void 0:s.display_name)||"").trim();if(e)return e;const t=String((s==null?void 0:s.name)||"").trim();if(!t.startsWith("mcp__"))return t||"MCP 工具";const n=t.split("__").filter(Boolean);if(n.length>=3){const i=n.slice(2).join("__").trim();if(i)return i}return t||"MCP 工具"}function iie(s,e){var r,o;if(!s)return"";const t=(e==null?void 0:e.intentEnabled)!==!1,n=s.intent_rendered||s.intent_full||"",i=!!n;if(s.message&&(s.status==="failed"||s.status==="error"||s.result&&s.result.error))return s.message;if(s.status==="completed"&&sie(s))return`${nie(s)} 执行完成`;if(t&&i)return n;if(s.message)return s.message;if(s.status==="hinted")return`可能需要 ${s.name}...`;if(s.status==="preparing")return`准备调用 ${s.name}...`;if(s.status==="running"){if(s.name==="read_file"||s.name==="read_skill"){const c=String(((r=s.argumentSnapshot)==null?void 0:r.type)||((o=s.arguments)==null?void 0:o.type)||"read").toLowerCase();return{read:"正在读取文件...",search:"正在执行搜索...",extract:"正在提取内容..."}[c]||"正在读取文件..."}const a=Kne[s.name]||s.display_name||s.name||"";return a||"调用工具中"}return s.status==="awaiting_user_answer"?"等待回答":s.status==="awaiting_approval"||s.status==="pending_approval"||s.status==="pending"?"等待审批...":s.status==="completed"?s.name==="read_file"||s.name==="read_skill"?tie(s):Qne[s.name]||"执行完成":s.status?`${s.name} - ${s.status}`:s.name||""}function rie(s){if(!s||s.name==="ask_user")return"";const e=s.argumentSnapshot||s.arguments,t=s.argumentLabel||uF(e);return t||(s.statusDetail?s.statusDetail:s.result&&typeof s.result=="object"&&s.result.path&&String(s.result.path).split("/").pop()||"")}function oie(s){if(!s||typeof s!="object")return null;try{return JSON.parse(JSON.stringify(s))}catch(e){return console.warn("无法克隆工具参数:",e),{...s}}}function uF(s){return!s||typeof s!="object"?"":s.command?s.command:s.path?String(s.path).split("/").pop()||"":s.target_path?String(s.target_path).split("/").pop()||"":s.query?`"${s.query}"`:s.question?String(s.question):typeof s.seconds<"u"?`${s.seconds} 秒`:s.name?s.name:""}function aie(s){const e=s!=null&&s.topic?String(s.topic).toLowerCase():"general";return Yne[e]||"通用"}function lie(s){if(!s)return"未限定时间";if(s.time_range){const e=String(s.time_range).toLowerCase();return Jne[e]||`相对范围:${s.time_range}`}return typeof s.days=="number"?`过去${s.days}天`:s.start_date&&s.end_date?`${s.start_date} 至 ${s.end_date}`:"未限定时间"}function cie(s){const e=s==null?void 0:s.include_domains;if(!Array.isArray(e)||e.length===0)return"未限定网站";const t=e.map(n=>String(n||"").trim()).filter(Boolean);return t.length?t.join(", "):"未限定网站"}function uie(s){var t;if(!s)return"language-plain";const e=((t=s.split(".").pop())==null?void 0:t.toLowerCase())||"";return Xne[e]||"language-plain"}const hie={toolCategoryIcon(s){return typeof s=="string"&&s.startsWith("mcp_server__")?this.toolCategoryIcons.mcp||"settings":this.toolCategoryIcons[s]||"settings"},findMessageByAction(s){if(!s)return null;for(const e of this.messages)if(e.actions&&e.actions.includes(s))return e;return null},cleanupStaleToolActions(){this.messages.forEach(s=>{s.actions&&s.actions.forEach(e=>{e.type!=="tool"||!e.tool||["running","preparing"].includes(e.tool.status)&&(e.tool.status="stale",e.tool.message=e.tool.message||"已被新的响应中断",this.toolUnregisterAction(e))})}),this.preparingTools.clear(),this.toolActionIndex.clear()},clearPendingTools(s="unspecified"){this.messages.forEach(e=>{e.actions&&e.actions.forEach(t=>{if(t.type!=="tool"||!t.tool)return;const n=typeof t.tool.status=="string"?t.tool.status.toLowerCase():"";(!n||["preparing","running","pending","queued","stale","awaiting_user_answer"].includes(n))&&(t.tool.status="cancelled",t.tool.message=t.tool.message||"已停止")})}),this.preparingTools&&this.preparingTools.clear&&this.preparingTools.clear(),this.activeTools&&this.activeTools.clear&&this.activeTools.clear(),this.toolActionIndex&&this.toolActionIndex.clear&&this.toolActionIndex.clear(),this.toolStacks&&this.toolStacks.clear&&this.toolStacks.clear(),typeof this.toolResetTracking=="function"&&this.toolResetTracking()},hasPendingToolActions(){const s=e=>e&&typeof e.size=="number"&&e.size>0;return s(this.preparingTools)||s(this.activeTools)?!0:Array.isArray(this.messages)?this.messages.some(e=>!e||e.role!=="assistant"||!Array.isArray(e.actions)?!1:e.actions.some(t=>{if(!t||t.type!=="tool"||!t.tool)return!1;if(t.tool.awaiting_content)return!0;const n=typeof t.tool.status=="string"?t.tool.status.toLowerCase():"";return!n||["preparing","running","pending","queued","awaiting_user_answer"].includes(n)})):!1},maybeResetStreamingState(s="unspecified"){return!this.streamingMessage||this.hasPendingToolActions()?!1:(this.streamingMessage=!1,this.stopRequested=!1,!0)},applyToolSettingsSnapshot(s){if(!Array.isArray(s)){console.warn("[ToolSettings] Snapshot skipped: categories not array",s);return}const e=s.map(i=>({id:i.id,label:i.label||i.id,enabled:!!i.enabled,tools:Array.isArray(i.tools)?i.tools:[],locked:!!i.locked,locked_state:typeof i.locked_state=="boolean"?i.locked_state:null}));let t=e;const n=e.filter(i=>typeof i.id=="string"&&i.id.startsWith("mcp_server__")).sort((i,r)=>String(i.label||"").localeCompare(String(r.label||"")));if(n.length>0){const i=e.filter(o=>!(typeof o.id=="string"&&o.id.startsWith("mcp_server__"))),r=i.findIndex(o=>o.id==="mcp");r>=0?t=[...i.slice(0,r+1),...n,...i.slice(r+1)]:t=[...n,...i]}Oe("[ToolSettings] Snapshot applied",{received:s.length,normalized:t,anyEnabled:t.some(i=>i.enabled),toolExamples:t.slice(0,3)}),this.toolSetSettings(t),this.toolSetSettingsLoading(!1)},async loadToolSettings(s=!1){if(!(!this.isConnected&&!s)&&!this.toolSettingsLoading&&!(!s&&this.toolSettings.length>0)){Oe("[ToolSettings] Fetch start",{force:s,hasConnection:this.isConnected}),this.toolSetSettingsLoading(!0);try{const e=await fetch("/api/tool-settings"),t=await e.json();Oe("[ToolSettings] Fetch response",{status:e.status,data:t}),e.ok&&t.success&&Array.isArray(t.categories)?this.applyToolSettingsSnapshot(t.categories):(console.warn("获取工具设置失败:",t),this.toolSetSettingsLoading(!1))}catch(e){console.error("获取工具设置异常:",e),this.toolSetSettingsLoading(!1)}}},async updateToolCategory(s,e){if(!this.isConnected||this.toolSettingsLoading)return;if(No().isCategoryLocked(s)){this.uiPushToast({title:"无法修改",message:"该工具类别被管理员强制设置",type:"warning"});return}const n=this.toolSettings.map(r=>({...r})),i=this.toolSettings.map(r=>r.id===s?{...r,enabled:e}:r);this.toolSetSettings(i);try{const r=await fetch("/api/tool-settings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:s,enabled:e})}),o=await r.json();r.ok&&o.success&&Array.isArray(o.categories)?this.applyToolSettingsSnapshot(o.categories):(console.warn("更新工具设置失败:",o),o&&(o.message||o.error)&&this.uiPushToast({title:"无法切换工具",message:o.message||o.error,type:"warning"}),this.toolSetSettings(n))}catch(r){console.error("更新工具设置异常:",r),this.toolSetSettings(n)}this.toolSetSettingsLoading(!1)},toggleToolMenu(){if(!this.isConnected||this.isPolicyBlocked("block_tool_toggle","工具启用/禁用已被管理员锁定"))return;this.modeMenuOpen=!1,this.modelMenuOpen=!1,this.inputToggleToolMenu()?(this.inputSetSettingsOpen(!1),this.quickMenuOpen||this.inputOpenQuickMenu(),this.loadToolSettings(!0)):this.inputSetToolMenuOpen(!1)},getToolIcon:Zne,getToolAnimationClass:eie,getToolStatusText(s){var n;const e=qs(),t=((n=e==null?void 0:e.form)==null?void 0:n.tool_intent_enabled)??(e==null?void 0:e.tool_intent_enabled)??!0;return iie(s,{intentEnabled:t})},getToolDescription:rie,cloneToolArguments:oie,buildToolLabel:uF,formatSearchTopic:aie,formatSearchTime:lie,formatSearchDomains:cie,getLanguageClass:uie},die={startProjectGitSummaryIdleRefresh(){this.projectGitSummaryRefreshTimer||(this.projectGitSummaryRefreshTimer=window.setInterval(()=>{var s;this.isConnected&&(typeof this.isOutputActive=="function"&&this.isOutputActive()||(s=this.refreshProjectGitSummary)==null||s.call(this,{idleFallback:!0}))},5e3))},startTerminalCountIdleRefresh(){this.terminalCountRefreshTimer||(this.terminalCountRefreshTimer=window.setInterval(()=>{this.isConnected&&this.fetchTerminalCount()},5e3))},stopTerminalCountIdleRefresh(){this.terminalCountRefreshTimer&&(window.clearInterval(this.terminalCountRefreshTimer),this.terminalCountRefreshTimer=null)},stopProjectGitSummaryIdleRefresh(){this.projectGitSummaryRefreshTimer&&(window.clearInterval(this.projectGitSummaryRefreshTimer),this.projectGitSummaryRefreshTimer=null)},async refreshProjectGitSummary(){var s;if(!this.projectGitSummaryRefreshing){this.projectGitSummaryRefreshing=!0;try{const e=await fetch("/api/project/git-summary"),t=await e.json().catch(()=>({}));if(!e.ok||!(t!=null&&t.success)){this.projectGitSummary=null,this.gitChangesDiff=null;return}this.projectGitSummary=t.data||null,this.gitChangesPanelOpen&&((s=this.loadGitChangesDiff)==null||s.call(this))}catch{this.projectGitSummary=null,this.gitChangesDiff=null}finally{this.projectGitSummaryRefreshing=!1}}},async loadGitChangesDiff(){var e,t;if(!this.gitChangesPanelOpen)return;const s=!!((e=this.gitChangesDiff)!=null&&e.has_git);this.gitChangesLoading=!0,this.gitChangesError="";try{const n=Math.max(0,Math.min(200,Number(this.gitChangesContext||3))),i=this.gitChangesFoldContexts&&typeof this.gitChangesFoldContexts=="object"?this.gitChangesFoldContexts:{},r=new URLSearchParams;r.set("context",String(n)),r.set("_",String(Date.now())),Object.keys(i).length>0&&r.set("fold_context_map",JSON.stringify(i));const o=await fetch(`/api/project/git-diff?${r.toString()}`,{cache:"no-store"}),a=await o.json().catch(()=>({}));if(!o.ok||!(a!=null&&a.success)){this.gitChangesError=(a==null?void 0:a.error)||"加载 Git 变更失败",s||(this.gitChangesDiff=null);return}this.gitChangesDiff=a.data||null,(t=this.gitChangesDiff)!=null&&t.has_git||(this.gitChangesPanelOpen=!1)}catch{this.gitChangesError="加载 Git 变更失败",s||(this.gitChangesDiff=null)}finally{this.gitChangesLoading=!1}},openGitChangesPanel(){var s,e;(s=this.projectGitSummary)!=null&&s.has_git&&(this.gitChangesPanelOpen=!this.gitChangesPanelOpen,this.gitChangesPanelOpen&&(this.gitChangesContext=3,this.gitChangesFileContexts={},this.gitChangesFoldContexts={},(e=this.loadGitChangesDiff)==null||e.call(this)))},closeGitChangesPanel(){this.gitChangesPanelOpen=!1},expandGitChangesContext(s){var c;const e=typeof s=="object"?s==null?void 0:s.path:s,t=typeof s=="object"?s==null?void 0:s.foldKey:"",n=String(e||"").trim(),i=String(t||"").trim();if(!n||!i)return;const r=this.gitChangesFoldContexts&&typeof this.gitChangesFoldContexts=="object"?this.gitChangesFoldContexts:{},o=r[n]&&typeof r[n]=="object"?r[n]:{},a=Number(o[i]||0);this.gitChangesFoldContexts={...r,[n]:{...o,[i]:Math.min(200,(Number.isFinite(a)?a:0)+20)}},(c=this.loadGitChangesDiff)==null||c.call(this)},resetGitChangesContext(s){var i;const e=String(s||"").trim();if(!e)return;const t=this.gitChangesFoldContexts&&typeof this.gitChangesFoldContexts=="object"?this.gitChangesFoldContexts:{};if(!t[e])return;const n={...t};delete n[e],this.gitChangesFoldContexts=n,(i=this.loadGitChangesDiff)==null||i.call(this)}},fie=/^(?:✅\s*)?子智能体\s*#?\s*(\d+)\s*任务摘要[:]/,pie=/^\[后台\s*run_command\s*完成\]/;let c1=0;const u1=140,e2=new Map;function gie(){var s;if(typeof window>"u")return!1;try{const e=window.__SCROLL_BOUNCE_TRACE__;if(e===!1||e==="0")return!1;if(e===!0||e==="1")return!0;const t=(s=window.localStorage)==null?void 0:s.getItem("scrollBounceTrace");return t==="0"||t==="false"?!1:t==="1"||t==="true"}catch{return!1}}function Wc(s,e={},t=s,n=140){if(!gie()||c1>=u1)return;const i=Date.now(),r=e2.get(t)||0;if(!(n>0&&i-r<n)){if(e2.set(t,i),c1+=1,c1===u1){console.warn("[SCROLL_BOUNCE_TRACE_UI]","log-limit-reached",{max:u1});return}console.log("[SCROLL_BOUNCE_TRACE_UI]",s,e)}}function gw(){var s;if(typeof window>"u")return!1;try{const e=window.__CONN_DIAG__;if(e===!1||e==="0")return!1;if(e===!0||e==="1")return!0;const t=(s=window.localStorage)==null?void 0:s.getItem("connDiag");return t==="0"||t==="false"?!1:t==="1"||t==="true"}catch{return!1}}function mie(s){if(!(typeof window>"u"))try{const e=window;Array.isArray(e.__CONN_DIAG_LOGS__)||(e.__CONN_DIAG_LOGS__=[]),e.__CONN_DIAG_LOGS__.push(s);const t=400;e.__CONN_DIAG_LOGS__.length>t&&e.__CONN_DIAG_LOGS__.splice(0,e.__CONN_DIAG_LOGS__.length-t)}catch{}}function Ch(s,e,t={},n={}){const i=!!n.force;if(!gw()&&!i)return;const o={ts:new Date().toISOString(),event:e,...t};mie(o),(s==="error"?console.error:s==="warn"?console.warn:console.log)("[CONN_DIAG]",e,o)}function vie(s){const e=(s||"").toString().trim();if(!e)return null;const t=e.match(fie),n=/已完成/.test(e);return!t||!n?null:`子智能体${t[1]} 任务完成`}function yie(s){const e=(s||"").toString().trim();return!e||!pie.test(e)?null:"后台 run_command 完成"}function bie(s){const e=(s||"").toString().trim();return e?vie(e)||yie(e):null}const _ie={clearLocalTaskUiState(s="safe-navigation"){var e,t,n,i,r,o,a,c,l;try{typeof this.stopWaitingTaskProbe=="function"&&this.stopWaitingTaskProbe()}catch{}this.streamingMessage=!1,this.taskInProgress=!1,this.stopRequested=!1,this.waitingForSubAgent=!1,this.waitingForBackgroundCommand=!1,this.dropToolEvents=!1,this.runtimeQueuedMessages=[],this.runtimeGuidanceFallbackQueue=[],this.runtimeQueueAutoSendInProgress=!1,this.runtimeQueueSyncLockKey="",this.runtimeQueueSyncLockUntil=0,this.goalModeArmed=!1,this.goalRunning=!1,this.goalProgress=null,this.goalDialogOpen=!1,typeof this.clearRuntimeQueueSuppressionState=="function"?this.clearRuntimeQueueSuppressionState():(this.runtimeQueueSuppressedMessageIds=new Set,this.runtimeGuidanceSuppressedTextCounts={}),typeof this.clearPendingTools=="function"?this.clearPendingTools(s):((t=(e=this.preparingTools)==null?void 0:e.clear)==null||t.call(e),(i=(n=this.activeTools)==null?void 0:n.clear)==null||i.call(n),(o=(r=this.toolActionIndex)==null?void 0:r.clear)==null||o.call(r),(c=(a=this.toolStacks)==null?void 0:a.clear)==null||c.call(a)),typeof this.chatClearThinkingLocks=="function"&&this.chatClearThinkingLocks(),(l=this.$forceUpdate)==null||l.call(this)},ensureScrollListener(){this._scrollListenerReady||!this.getMessagesAreaElement()||(this.initScrollListener(),this._scrollListenerReady=!0)},handleStickStateChange(s){const e=!!(s!=null&&s.escapedFromLock),t=!!(s!=null&&s.isAtBottom),n=!!(s!=null&&s.isNearBottom),i=!!this._escapedByUserScroll;if(Wc("stick-state-change",{isAtBottom:t,isNearBottom:n,escapedFromLock:e,userEscaped:i,autoScrollEnabled:this.autoScrollEnabled,userScrolling:this.userScrolling},"stick-state-change",180),this.stickIsAtBottom=t,this.stickIsNearBottom=n,i){const a=Date.now()<=(this._manualScrollSuppressUntil||0),c=this.getMessagesAreaElement();(c?c.scrollHeight-c.scrollTop-c.clientHeight<=4:t)&&!a?(this._escapedByUserScroll=!1,this.chatSetScrollState({userScrolling:!1})):this.chatSetScrollState({userScrolling:!0});return}if(this.chatSetScrollState({userScrolling:!1}),!e)return;const r=typeof this.isOutputActive=="function"?this.isOutputActive():!0;if(!this.autoScrollEnabled||!r)return;const o=this.getChatAreaController();if(o&&typeof o.conditionalStickToBottom=="function"){o.conditionalStickToBottom({force:!1});return}KI(this)},handleUserScrollIntent(s){const e=Number((s==null?void 0:s.ts)||Date.now()),t=this.getChatAreaController();t&&typeof t.stopStickScroll=="function"&&t.stopStickScroll(),this._manualScrollSuppressUntil=Math.max(this._manualScrollSuppressUntil||0,e+1600),this._escapedByUserScroll=!0,this.chatSetScrollState({userScrolling:!0}),Wc("ui.user-scroll-intent",{ts:e,delta:Number((s==null?void 0:s.delta)||0),top:Number((s==null?void 0:s.top)||0),suppressUntil:this._manualScrollSuppressUntil},"ui.user-scroll-intent",80)},scrollHistoryToBottomInstant(){this._escapedByUserScroll=!1;const s=this.getChatAreaController();s&&typeof s.stopStickScroll=="function"&&s.stopStickScroll();const e=this.getMessagesAreaElement();if(!e)return;const t=()=>{e.scrollTop=e.scrollHeight};t(),requestAnimationFrame(()=>{t(),requestAnimationFrame(t)}),this.chatSetScrollState({userScrolling:!1})},async settleHistoryRenderAndScroll(){this._escapedByUserScroll=!1;const s=this.getChatAreaController();s&&typeof s.stopStickScroll=="function"&&s.stopStickScroll();const e=this.getMessagesAreaElement();if(!e)return;const t=()=>new Promise(c=>requestAnimationFrame(c)),n=c=>new Promise(l=>window.setTimeout(l,c)),i=()=>{e.scrollTop=e.scrollHeight};let r=-1,o=0;const a=Date.now();for(;Date.now()-a<900&&o<4;){await t(),i();const c=e.scrollHeight;Math.abs(c-r)<=1?o+=1:(o=0,r=c)}await n(80),i(),await t(),i(),this.chatSetScrollState({userScrolling:!1})},scrollToBottom(){Wc("ui.scrollToBottom:called",{autoScrollEnabled:this.autoScrollEnabled,userScrolling:this.userScrolling},"ui.scrollToBottom:called",80),this._escapedByUserScroll=!1;const s=this.getChatAreaController();if(s&&typeof s.scrollToBottom=="function"){s.scrollToBottom({behavior:"auto",force:this.autoScrollEnabled}),this.chatSetScrollState({userScrolling:!1});return}dT(this)},conditionalScrollToBottom(){const s=typeof this.isOutputActive=="function"?this.isOutputActive():!0,e=this.getChatAreaController(),t=e&&typeof e.getStickState=="function"?e.getStickState():null;if(Wc("ui.conditionalScrollToBottom:called",{active:s,autoScrollEnabled:this.autoScrollEnabled,userScrolling:this.userScrolling,stickIsNearBottom:this.stickIsNearBottom,escapedFromLock:!!(t!=null&&t.escapedFromLock)},"ui.conditionalScrollToBottom:called",120),!s)return;const n=Date.now();if(n<=(this._manualScrollSuppressUntil||0)){Wc("ui.conditionalScrollToBottom:skip-manual-cooldown",{now:n,suppressUntil:this._manualScrollSuppressUntil},"ui.conditionalScrollToBottom:skip-manual-cooldown",120);return}if(t!=null&&t.escapedFromLock&&this._escapedByUserScroll){Wc("ui.conditionalScrollToBottom:skip-escaped-lock",{escapedFromLock:!!(t!=null&&t.escapedFromLock),escapedByUser:!!this._escapedByUserScroll,isNearBottom:!!(t!=null&&t.isNearBottom),isAtBottom:!!(t!=null&&t.isAtBottom)},"ui.conditionalScrollToBottom:skip-escaped-lock",120);return}if(this.userScrolling){Wc("ui.conditionalScrollToBottom:skip-user-scrolling",{userScrolling:this.userScrolling,stickIsNearBottom:this.stickIsNearBottom},"ui.conditionalScrollToBottom:skip-user-scrolling",120);return}if(e&&typeof e.conditionalStickToBottom=="function"){e.conditionalStickToBottom({force:!1});return}KI(this)},toggleScrollLock(){Wc("ui.scrollToBottomButton:clicked",{autoScrollEnabled:this.autoScrollEnabled,userScrolling:this.userScrolling,stickNearBottom:this.stickIsNearBottom},"ui.scrollToBottomButton:clicked",0);const s=this.getChatAreaController();return s&&typeof s.scrollToBottom=="function"?s.scrollToBottom({behavior:"smooth",force:!0}):dT(this,{ignoreUserScrolling:!0,resetUserScrolling:!0,behavior:"smooth",force:!0}),this._escapedByUserScroll=!1,this.chatSetScrollState({autoScrollEnabled:!0,userScrolling:!1}),!0},scrollThinkingToBottom(s){MZ(this,s)},initScrollListener(){const s=this.getChatAreaController();if(s&&typeof s.isUsingStickToBottom=="function"&&s.isUsingStickToBottom()){this._scrollListenerReady=!0;return}const e=this.getMessagesAreaElement();if(!e){console.warn("消息区域未找到");return}this._scrollListenerReady=!0;let t=0;const n=1200;let i=0;const r=()=>{if(typeof window>"u")return!1;const l=Number(window.__SHOW_TAG_DRAWING_UNTIL__||0);return Date.now()<=l},o=(l,u={},h=80)=>{if(!r()||t>=n)return;const d=Date.now();if(!(h>0&&d-i<h)){if(i=d,t+=1,t===n){console.warn("[SCROLL_DEBUG]","listener:log-limit-reached",{max:n});return}console.log("[SCROLL_DEBUG]",l,u)}};o("listener:setup",{autoScrollEnabled:this.autoScrollEnabled,userScrolling:this.userScrolling},0);let a=!1;const c=12;this._setScrollingFlag=l=>{a=!!l,o("listener:programmatic-flag",{flag:!!l},0)},e.addEventListener("scroll",()=>{if(a){o("listener:scroll:ignore-programmatic",{top:e.scrollTop,height:e.scrollHeight,client:e.clientHeight},120);return}const l=e.scrollTop,u=e.scrollHeight,h=e.clientHeight,d=u-l-h<c,m=u-l-h<48,v=typeof this.isOutputActive=="function"?this.isOutputActive():!0;if(this.autoScrollEnabled&&v){this.chatSetScrollState({userScrolling:!1}),o("listener:scroll:locked-keep-bottom-state",{top:l,height:u,client:h,remain:u-l-h,isAtBottom:d,isNearBottom:m});return}this.chatSetScrollState({userScrolling:!(d||m)}),o("listener:scroll:update-state",{top:l,height:u,client:h,remain:u-l-h,isAtBottom:d,isNearBottom:m,autoScrollEnabled:this.autoScrollEnabled,userScrollingBefore:this.userScrolling,userScrollingNext:!(d||m)})})},handleThinkingScroll(s,e){if(!s||!e||!e.target)return;const t=e.target,i=t.scrollHeight-t.scrollTop-t.clientHeight<12;this.chatSetThinkingLock(s,i)},toggleBlock(s){s&&(this.expandedBlocks&&this.expandedBlocks.has(s)?this.chatCollapseBlock(s):this.chatExpandBlock(s))}},Sie={setupMobileViewportWatcher(){if(typeof window>"u"||typeof window.matchMedia!="function"){this.updateMobileViewportState(!1);return}const s=window.matchMedia("(max-width: 768px)");this.mobileViewportQuery=s,this.updateMobileViewportState(s.matches),typeof s.addEventListener=="function"?s.addEventListener("change",this.handleMobileViewportQueryChange):typeof s.addListener=="function"&&s.addListener(this.handleMobileViewportQueryChange)},teardownMobileViewportWatcher(){const s=this.mobileViewportQuery;s&&(typeof s.removeEventListener=="function"?s.removeEventListener("change",this.handleMobileViewportQueryChange):typeof s.removeListener=="function"&&s.removeListener(this.handleMobileViewportQueryChange),this.mobileViewportQuery=null)},handleMobileViewportQueryChange(s){this.updateMobileViewportState(s.matches)},updateMobileViewportState(s){this.uiSetMobileViewport(!!s),s||(this.uiSetMobileOverlayMenuOpen(!1),this.closeMobileOverlay())},toggleMobileOverlayMenu(){this.isMobileViewport&&this.uiToggleMobileOverlayMenu()},openMobileOverlay(s){if(this.isMobileViewport){if(s==="approval"&&this.fetchPendingToolApprovals(),this.activeMobileOverlay===s){this.closeMobileOverlay("same-target-click");return}this.activeMobileOverlay==="conversation"&&this.uiSetSidebarCollapsed(!0),s==="conversation"&&this.uiSetSidebarCollapsed(!1),this.uiSetActiveMobileOverlay(s),this.uiSetMobileOverlayMenuOpen(!1)}},closeMobileOverlay(s="unknown"){if(!this.activeMobileOverlay){this.uiCloseMobileOverlay();return}this.activeMobileOverlay==="conversation"&&this.uiSetSidebarCollapsed(!0),this.uiCloseMobileOverlay()},handleMobileOverlayEscape(s){if(!(s.key!=="Escape"||!this.isMobileViewport)){if(this.mobileOverlayMenuOpen){this.uiSetMobileOverlayMenuOpen(!1);return}this.activeMobileOverlay&&this.closeMobileOverlay()}},handleMobileOverlaySelect(s){this.loadConversation(s),this.closeMobileOverlay()},handleMobilePersonalClick(){this.closeMobileOverlay(),this.uiSetMobileOverlayMenuOpen(!1),this.openPersonalPage()},handleMobileRefreshClick(){this.uiSetMobileOverlayMenuOpen(!1),this.refreshCurrentPage()},handleClickOutsideMobileMenu(s){if(!this.isMobileViewport||!this.mobileOverlayMenuOpen)return;const e=this.$refs.mobilePanelTrigger;e&&typeof e.contains=="function"&&e.contains(s.target)||this.uiSetMobileOverlayMenuOpen(!1)}},wie={normalizeComposerDraftContent(s){let e="";return typeof s=="string"?e=s:s==null?e="":e=String(s),e.length>4e4&&(e=e.slice(0,4e4)),e},scheduleComposerDraftPersist(s="input"){const e=this.normalizeComposerDraftContent(this.inputMessage),t=this.normalizeComposerDraftContent(this.composerDraftLastSyncedContent),n=e!==t;this.composerDraftDirty=n,this.composerDraftSaveTimer&&(clearTimeout(this.composerDraftSaveTimer),this.composerDraftSaveTimer=null),n&&(this.composerDraftSaveTimer=window.setTimeout(()=>{this.persistComposerDraftNow({reason:`debounce:${s}`}).catch(()=>{})},1e3))},async persistComposerDraftNow(s={}){const e=String((s==null?void 0:s.reason)||"manual"),t=!!(s!=null&&s.force),n=!!(s!=null&&s.useBeacon),i=this.normalizeComposerDraftContent(Object.prototype.hasOwnProperty.call(s||{},"content")?s.content:this.inputMessage),r=this.normalizeComposerDraftContent(this.composerDraftLastSyncedContent);if(!t&&i===r)return this.composerDraftDirty=!1,{success:!0,skipped:!0};this.composerDraftSaveTimer&&(clearTimeout(this.composerDraftSaveTimer),this.composerDraftSaveTimer=null);const o=typeof this.getInputComposerRef=="function"?this.getInputComposerRef():null,a=o&&typeof o.getComposerDraftMeta=="function"?o.getComposerDraftMeta():{},c=JSON.stringify({content:i,editor_json:a!=null&&a.editor_json&&typeof a.editor_json=="object"?a.editor_json:null,skill_refs:Array.isArray(a==null?void 0:a.skill_refs)?a.skill_refs:[]});if(n&&typeof navigator<"u"&&typeof navigator.sendBeacon=="function")try{const h=new Blob([c],{type:"application/json"});return navigator.sendBeacon("/api/input-draft",h),this.composerDraftLastSyncedContent=i,this.composerDraftDirty=!1,{success:!0,queued:!0,reason:e}}catch{}const l=await fetch("/api/input-draft",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"same-origin",body:c,keepalive:!!(s!=null&&s.keepalive)}),u=await l.json().catch(()=>({}));if(!l.ok||!(u!=null&&u.success))throw new Error((u==null?void 0:u.error)||"保存输入草稿失败");return this.composerDraftLastSyncedContent=i,this.composerDraftDirty=!1,{success:!0,saved:!0,reason:e}},async restoreComposerDraftState(s="manual"){var t,n,i;const e=Number(this.composerDraftFetchSeq||0)+1;this.composerDraftFetchSeq=e;try{const r=await fetch("/api/input-draft",{method:"GET",credentials:"same-origin"}),o=await r.json().catch(()=>({}));if(!r.ok||!(o!=null&&o.success))throw new Error((o==null?void 0:o.error)||"获取输入草稿失败");if(Number(this.composerDraftFetchSeq||0)!==e)return;if(this.taskInProgress||this.composerBusy){Oe("[UI] 跳过输入草稿恢复(任务运行中)",{reason:s,taskInProgress:!!this.taskInProgress,composerBusy:!!this.composerBusy});return}const a=this.normalizeComposerDraftContent(((t=o==null?void 0:o.data)==null?void 0:t.content)||""),c=Array.isArray((n=o==null?void 0:o.data)==null?void 0:n.skill_refs)?o.data.skill_refs:[],l=(i=o==null?void 0:o.data)!=null&&i.editor_json&&typeof o.data.editor_json=="object"?o.data.editor_json:null;this.composerDraftLastSyncedContent=a,this.composerDraftDirty=!1,this.inputSetMessage(a),this.$nextTick(()=>{const u=typeof this.getInputComposerRef=="function"?this.getInputComposerRef():null;u&&typeof u.restoreComposerDraftMeta=="function"&&u.restoreComposerDraftMeta({skill_refs:c,editor_json:l}),typeof this.autoResizeInput=="function"&&this.autoResizeInput()}),Oe("[UI] 输入草稿已恢复",{reason:s,length:a.length})}catch(r){console.warn("[UI] 恢复输入草稿失败:",r)}},handleBeforeUnloadDraftPersist(){this.persistComposerDraftNow({reason:"beforeunload",force:!0,useBeacon:!0}).catch(()=>{})},clearComposerDraftState(s="manual"){this.inputClearMessage(),this.composerDraftLastSyncedContent="",this.composerDraftDirty=!1,this.composerDraftSaveTimer&&(clearTimeout(this.composerDraftSaveTimer),this.composerDraftSaveTimer=null),this.inputSetLineCount(1),this.inputSetMultiline(!1),this.inputClearSelectedImages(),this.inputClearSelectedVideos(),this.inputSetImagePickerOpen(!1),this.inputSetVideoPickerOpen(!1),this.imageEntries=[],this.videoEntries=[],this.imageLoading=!1,this.videoLoading=!1,this.mediaUploading=!1,this.$nextTick(()=>{typeof this.autoResizeInput=="function"&&this.autoResizeInput()})},handleInputChange(){this.autoResizeInput(),this.scheduleComposerDraftPersist("input-change")},handleInputFocus(){this.inputSetFocused(!0),this.closeQuickMenu(),this.closePermissionMenu()},handleInputBlur(){this.inputSetFocused(!1)},getComposerElement(s){const e=this.getInputComposerRef(),t=n=>n?n instanceof HTMLElement?n:typeof n=="object"&&"value"in n&&!(n instanceof Window)?n.value:n:null;return e&&e[s]?t(e[s]):this.$refs&&this.$refs[s]?t(this.$refs[s]):null},getInputComposerRef(){return this.$refs.inputComposer||null},handleComposerHeightChange(s={}){const e=Number((s==null?void 0:s.reservedHeight)||0)||Number((s==null?void 0:s.height)||0)||Number((s==null?void 0:s.composerHeight)||0);if(!Number.isFinite(e)||e<=0)return;const t=Math.max(80,Math.min(560,Math.round(e)));Math.abs(t-Number(this.composerReservedHeight||0))<1||(this.composerReservedHeight=t)}},kie={toggleSidebar(){if(this.isMobileViewport&&this.activeMobileOverlay==="conversation"){this.closeMobileOverlay();return}this.uiToggleSidebar()},toggleFocusPanel(){this.rightCollapsed=!this.rightCollapsed,!this.rightCollapsed&&this.rightWidth<this.minPanelWidth&&(this.rightWidth=this.minPanelWidth)},toggleApprovalPanel(){this.rightCollapsed=!this.rightCollapsed,!this.rightCollapsed&&this.rightWidth<this.minPanelWidth&&(this.rightWidth=this.minPanelWidth),this.rightCollapsed||this.fetchPendingToolApprovals()},toggleTerminalPanel(){this.terminalPanelOpen=!this.terminalPanelOpen,this.terminalPanelOpen&&this.subscribeTerminalEvents()},closeTerminalPanel(){this.terminalPanelOpen=!1},handleFocusPanelToggleClick(){this.isConnected&&(this.isPolicyBlocked("block_focus_panel","聚焦面板已被管理员禁用")||this.toggleFocusPanel())},handleApprovalPanelToggleClick(){if(this.currentConversationId){if(this.isMobileViewport){this.fetchPendingToolApprovals(),this.openMobileOverlay("approval");return}this.toggleApprovalPanel()}},handleTokenPanelToggleClick(s=!1){this.currentConversationId&&(this.isPolicyBlocked("block_token_panel","用量统计已被管理员禁用")||this.isMobileViewport&&this.tokenPanelCollapsed&&!s||this.toggleTokenPanel())},getMessagesAreaElement(){const s=this.$refs.messagesArea;if(!s)return null;if(s instanceof HTMLElement)return s;if(s.rootEl)return s.rootEl.value||s.rootEl;if(s.$el&&s.$el.querySelector){const e=s.$el.querySelector(".messages-area");if(e)return e}return null},getChatAreaController(){const s=this.$refs.messagesArea;return s&&typeof s=="object"?s:null},getThinkingContentElement(s){const e=this.$refs.messagesArea;if(e&&typeof e.getThinkingRef=="function"){const i=e.getThinkingRef(s);if(i)return i}const t=`thinkingContent-${s}`,n=this.$refs[t];return Array.isArray(n)?n[0]||null:n||null}},Cie={openPersonalPage(){this.isPolicyBlocked("block_personal_space","个人空间已被管理员禁用")||this.personalizationOpenDrawer()},minimizeUserQuestionDialog(){!Array.isArray(this.pendingUserQuestions)||!this.pendingUserQuestions.length||(this.userQuestionDialogVisible=!1,this.userQuestionMinimized=!0)},restoreUserQuestionDialog(){!Array.isArray(this.pendingUserQuestions)||!this.pendingUserQuestions.length||(this.userQuestionDialogVisible=!0,this.userQuestionMinimized=!1)},async fetchPendingUserQuestions(){if(!this.currentConversationId){this.pendingUserQuestions=[];return}try{const s=await fetch(`/api/user-questions/pending?conversation_id=${encodeURIComponent(this.currentConversationId)}`),e=await s.json().catch(()=>({}));if(!s.ok||!(e!=null&&e.success))return;const t=Array.isArray(e.items)?e.items:[];this.pendingUserQuestions=t,t.length>0?this.userQuestionActiveIndex=Math.min(Math.max(0,Number(this.userQuestionActiveIndex||0)),Math.max(0,t.length-1)):(this.userQuestionDialogVisible=!1,this.userQuestionMinimized=!1,this.userQuestionActiveIndex=0)}catch{}},approveToolApproval(s){return this.decideToolApproval(s,"approved")},async fetchPendingPlanApprovals(){if(!this.currentConversationId){this.pendingPlanApprovals=[];return}try{const s=await fetch(`/api/plan-approvals/pending?conversation_id=${encodeURIComponent(this.currentConversationId)}`),e=await s.json().catch(()=>({}));if(!s.ok||!(e!=null&&e.success))return;this.pendingPlanApprovals=Array.isArray(e.items)?e.items:[]}catch{}},async submitPlanApproval(s){const e=String((s==null?void 0:s.approval_id)||"").trim();if(e){this.answeringPlanApprovalIds=[e];try{const t=await fetch(`/api/plan-approvals/${encodeURIComponent(e)}/answer`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({approved:(s==null?void 0:s.approved)===!0,comment:String((s==null?void 0:s.comment)||"").trim()})}),n=await t.json().catch(()=>({}));if(!t.ok||!(n!=null&&n.success))throw new Error((n==null?void 0:n.message)||(n==null?void 0:n.error)||"提交计划决策失败");this.pendingPlanApprovals=(this.pendingPlanApprovals||[]).filter(i=>i&&String(i.approval_id||"")!==e),(s==null?void 0:s.approved)===!0?(this.fetchWorkMode(),this.fetchPermissionMode(),this.fetchExecutionMode(),this.uiPushToast({title:"计划已批准",message:"已切换到执行模式,开始实施",type:"success",duration:2200})):this.uiPushToast({title:"已拒绝计划",message:"AI 将根据你的意见修订后重新提交",type:"info",duration:2200})}catch(t){const n=t instanceof Error?t.message:String(t||"提交计划决策失败");this.uiPushToast({title:"提交计划决策失败",message:n,type:"error"})}finally{this.answeringPlanApprovalIds=[]}}},rejectToolApproval(s){return this.decideToolApproval(s,"rejected")},openReviewDialog(){if(!this.isPolicyBlocked("block_conversation_review","对话引用已被管理员禁用")){if(!this.isConnected){this.uiPushToast({title:"无法使用",message:"当前未连接,无法生成回顾文件",type:"warning"});return}this.reviewDialogOpen=!0,this.reviewSelectedConversationId=null,this.reviewPreviewLines=[],this.reviewPreviewError=null,this.reviewGeneratedPath=null,this.closeQuickMenu(),this.loadReviewConversations()}},autoSelectReviewConversation(){if(this.reviewSelectedConversationId)return;const s=this.reviewConversations.find(e=>e.id!==this.currentConversationId);s&&s.id&&(this.reviewSelectedConversationId=s.id,this.loadReviewPreview(s.id))},closeHeaderMenu(){this.headerMenuOpen=!1},handleReviewSelect(s){if(s===this.currentConversationId){this.uiPushToast({title:"无法引用当前对话",message:"请选择其他对话生成回顾",type:"warning"});return}this.reviewSelectedConversationId=s,this.loadReviewPreview(s)},confirmAction(s={}){return this.uiRequestConfirm(s)},async submitUserQuestionAnswers(s){const e=Array.isArray(s)?s:[];if(!e.length)return;const t=e.map(n=>String((n==null?void 0:n.question_id)||"")).filter(Boolean);this.answeringUserQuestionIds=t;try{for(const n of e){const i=String((n==null?void 0:n.question_id)||"").trim();if(!i)continue;const r=await fetch(`/api/user-questions/${encodeURIComponent(i)}/answer`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({selected_option_id:(n==null?void 0:n.selected_option_id)||void 0,text:(n==null?void 0:n.text)||"",dismissed:(n==null?void 0:n.dismissed)===!0})}),o=await r.json().catch(()=>({}));if(!r.ok||!(o!=null&&o.success))throw new Error((o==null?void 0:o.message)||(o==null?void 0:o.error)||"提交回答失败")}this.pendingUserQuestions=(this.pendingUserQuestions||[]).filter(n=>n&&!t.includes(String(n.question_id||""))),this.pendingUserQuestions.length?this.userQuestionActiveIndex=Math.min(this.userQuestionActiveIndex,this.pendingUserQuestions.length-1):(this.userQuestionDialogVisible=!1,this.userQuestionMinimized=!1,this.userQuestionActiveIndex=0,typeof this.restoreUserQuestionTitle=="function"&&this.restoreUserQuestionTitle())}catch(n){const i=n instanceof Error?n.message:String(n||"提交回答失败");this.uiPushToast({title:"提交回答失败",message:i,type:"error"})}finally{this.answeringUserQuestionIds=[]}},async dismissUserQuestions(s){const e=String(s||"").trim();e&&await this.submitUserQuestionAnswers([{question_id:e,dismissed:!0}])},async answerUserQuestionFromComposer(s){const e=String(s||"").trim();if(!e||!Array.isArray(this.pendingUserQuestions)||!this.pendingUserQuestions.length)return!1;const t=Math.min(Math.max(0,Number(this.userQuestionActiveIndex||0)),Math.max(0,this.pendingUserQuestions.length-1)),n=this.pendingUserQuestions[t]||this.pendingUserQuestions[0];return n!=null&&n.question_id?(await this.submitUserQuestionAnswers([{question_id:n.question_id,text:e}]),this.pendingUserQuestions.length>0&&(this.userQuestionDialogVisible=!0,this.userQuestionMinimized=!1),!0):!1},async decideToolApproval(s,e){const t=String(s||"").trim();if(t){Array.isArray(this.decidingApprovalIds)||(this.decidingApprovalIds=[]),this.decidingApprovalIds.includes(t)||this.decidingApprovalIds.push(t);try{const n=await fetch(`/api/tool-approvals/${encodeURIComponent(t)}/decision`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({decision:e})}),i=await n.json().catch(()=>({}));if(!n.ok||!(i!=null&&i.success))throw new Error((i==null?void 0:i.message)||(i==null?void 0:i.error)||"提交审批失败");this.pendingToolApprovals=(this.pendingToolApprovals||[]).filter(r=>r&&r.approval_id!==t),this.pendingToolApprovals.length||(this.rightCollapsed=!0,this.isMobileViewport&&this.activeMobileOverlay==="approval"&&this.closeMobileOverlay())}catch(n){const i=n instanceof Error?n.message:String(n||"审批失败");this.uiPushToast({title:"审批失败",message:i,type:"error"})}finally{this.decidingApprovalIds=(this.decidingApprovalIds||[]).filter(n=>n!==t)}}}},Tie={getVisibleWorkspaceTaskForConversation(s){const e=String(s||"").trim();return e&&(Array.isArray(this.runningWorkspaceTasks)?this.runningWorkspaceTasks:[]).find(n=>String((n==null?void 0:n.conversation_id)||"")===e)||null},getStoredWorkspaceTaskIdSet(s="tracked"){var t;if(typeof window>"u")return new Set;const e=s==="acknowledged"?"agents.hostWorkspaceTasks.acknowledged":"agents.hostWorkspaceTasks.tracked";try{const n=(t=window.localStorage)==null?void 0:t.getItem(e),i=JSON.parse(n||"[]");return new Set((Array.isArray(i)?i:[]).map(r=>String(r||"").trim()).filter(Boolean))}catch{return new Set}},setStoredWorkspaceTaskIdSet(s="tracked",e){var n;if(typeof window>"u")return;const t=s==="acknowledged"?"agents.hostWorkspaceTasks.acknowledged":"agents.hostWorkspaceTasks.tracked";try{(n=window.localStorage)==null||n.setItem(t,JSON.stringify(Array.from(e||[]).map(i=>String(i))))}catch{}},acknowledgeCompletedWorkspaceTask(s){var r,o,a,c;const e=String(s||"").trim();if(!e)return;const t=Array.isArray(this.acknowledgedCompletedTaskIds)?this.acknowledgedCompletedTaskIds:[];t.includes(e)||(this.acknowledgedCompletedTaskIds=[...t,e]);const n=((r=this.getStoredWorkspaceTaskIdSet)==null?void 0:r.call(this,"acknowledged"))||new Set;n.add(e),(o=this.setStoredWorkspaceTaskIdSet)==null||o.call(this,"acknowledged",n);const i=((a=this.getStoredWorkspaceTaskIdSet)==null?void 0:a.call(this,"tracked"))||new Set;i.delete(e),(c=this.setStoredWorkspaceTaskIdSet)==null||c.call(this,"tracked",i),this.runningWorkspaceTasks=(Array.isArray(this.runningWorkspaceTasks)?this.runningWorkspaceTasks:[]).filter(l=>String((l==null?void 0:l.task_id)||"")!==e)},async getRunningTaskConversationId(){try{const s=await fetch("/api/tasks");if(!s.ok)return null;const e=await s.json(),n=(Array.isArray(e==null?void 0:e.data)?e.data:[]).find(i=>(i==null?void 0:i.status)==="running"&&(i==null?void 0:i.conversation_id)&&(!(this.versioningHostMode||this.dockerProjectMode)||!this.currentHostWorkspaceId||(i==null?void 0:i.workspace_id)===this.currentHostWorkspaceId));return(n==null?void 0:n.conversation_id)||null}catch(s){return console.warn("获取运行中任务失败:",s),null}}},Aie={async fetchHostWorkspaces(){if(!(this.versioningHostMode||this.dockerProjectMode)){this.hostWorkspaces=[],this.currentHostWorkspaceId="",this.defaultHostWorkspaceId="";return}try{const s=await fetch(this.versioningHostMode?"/api/host/workspaces":"/api/projects"),e=await s.json().catch(()=>({}));if(!s.ok||!(e!=null&&e.success))throw new Error((e==null?void 0:e.error)||"获取项目列表失败");const t=e.data||{},n=Array.isArray(t.workspaces)?t.workspaces:[];this.hostWorkspaces=n.map(i=>({workspace_id:String(i.workspace_id||""),label:String(i.label||i.workspace_id||"未命名项目"),path:String(i.path||""),is_current:!!i.is_current,running_task_count:Number(i.running_task_count||0)})),this.currentHostWorkspaceId=String(t.current_workspace_id||""),this.defaultHostWorkspaceId=String(t.default_workspace_id||""),await this.refreshRunningWorkspaceTasks()}catch(s){console.warn("加载工作区/项目失败:",s),this.hostWorkspaces=[],this.currentHostWorkspaceId="",this.defaultHostWorkspaceId="",this.runningWorkspaceTasks=[]}},async handleHostWorkspaceSwitch(s,e={}){var a,c,l;const t=!!(e&&e.preserveConversationView),n=String(s||"").trim();if(!n||this.hostWorkspaceSwitching||!(this.versioningHostMode||this.dockerProjectMode)||n===this.currentHostWorkspaceId)return;this.hostWorkspaceSwitching=!0;const i=Array.isArray(this.conversations)?[...this.conversations]:[],r=this.searchActive;this.searchActive=!1,this.searchResults=[];const{useConversationStore:o}=await wt(async()=>{const{useConversationStore:u}=await Promise.resolve().then(()=>Ei);return{useConversationStore:u}},void 0);o().resetConversationsTypeCache(),this.conversationsOffset=0,this.hasMoreConversations=!1,this.conversationsLoading=!0;try{await this.persistComposerDraftNow({reason:"switch-host-workspace:before-select",force:!0,keepalive:!0}).catch(()=>{});const u=encodeURIComponent(n),h=this.versioningHostMode?"/api/host/workspaces/select":"/api/projects/select",d=await fetch(`${h}?workspace_id=${u}`),p=await d.json().catch(()=>({}));if(!d.ok||!(p!=null&&p.success))throw new Error((p==null?void 0:p.error)||(this.versioningHostMode?"切换宿主机工作区失败":"切换项目失败"));const m=p.data||{};if(this.currentHostWorkspaceId=String(m.current_workspace_id||n),m.project_path&&(this.projectPath=String(m.project_path)),m.default_workspace_id&&(this.defaultHostWorkspaceId=String(m.default_workspace_id)),!t){this.messages=[],this.currentConversationId=null,(a=this.resetTokenStatistics)==null||a.call(this),this.currentConversationTitle="新对话",this.titleReady=!0,this.suppressTitleTyping=!1;try{const{useTaskStore:y}=await wt(async()=>{const{useTaskStore:_}=await Promise.resolve().then(()=>so);return{useTaskStore:_}},void 0);y().clearTask()}catch{}(c=this.clearLocalTaskUiState)==null||c.call(this,"switch-host-workspace")}if(await this.fetchHostWorkspaces(),t)this.conversationsOffset=0,await this.loadConversationsList();else{const y=new Set(["pending","running","cancel_requested"]),b=(Array.isArray(this.runningWorkspaceTasks)?this.runningWorkspaceTasks:[]).filter(_=>String((_==null?void 0:_.workspace_id)||"")===this.currentHostWorkspaceId).find(_=>y.has(String((_==null?void 0:_.status)||""))&&(_==null?void 0:_.conversation_id));b!=null&&b.conversation_id?(await this.loadConversation(String(b.conversation_id),{force:!0}),this.conversationsOffset=0,await this.loadConversationsList()):(this.startTitleTyping("新对话",{animate:!1}),history.replaceState({},"","/new"),await this.loadConversationsList())}const v=(Array.isArray(this.hostWorkspaces)?this.hostWorkspaces:[]).find(y=>String((y==null?void 0:y.workspace_id)||"")===this.currentHostWorkspaceId),g=String((v==null?void 0:v.label)||"").trim();this.uiPushToast({title:this.versioningHostMode?"工作区已切换":"项目已切换",message:this.versioningHostMode?m.project_path||g||n:g||n,type:"success"}),(l=this.refreshProjectGitSummary)==null||l.call(this),this.fetchTerminalCount()}catch(u){const h=o(),d=h.conversationsCache[h.sidebarConversationType];d.list=i,d.loaded=!0,this.conversations=d.list,this.searchActive=r,this.conversationsLoading=!1;const p=u instanceof Error?u.message:String(u||"切换失败");this.uiPushToast({title:this.versioningHostMode?"切换工作区失败":"切换项目失败",message:p,type:"error"})}finally{this.hostWorkspaceSwitching=!1}},async submitHostWorkspaceCreate(){var t,n;if(!(this.versioningHostMode||this.dockerProjectMode)||this.hostWorkspaceSwitching||this.hostWorkspaceCreateSubmitting)return;const s=String(this.hostWorkspaceCreatePath||"").trim(),e=String(this.hostWorkspaceCreateLabel||"").trim();if(this.versioningHostMode&&!s){this.hostWorkspaceCreateError="路径不能为空";return}if(this.dockerProjectMode&&!e){this.hostWorkspaceCreateError="项目名称不能为空";return}this.hostWorkspaceCreateSubmitting=!0,this.hostWorkspaceCreateError="";try{const i=await fetch(this.versioningHostMode?"/api/host/workspaces/create":"/api/projects/create",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"same-origin",body:JSON.stringify({path:this.versioningHostMode?s:void 0,label:e})}),r=await i.json().catch(()=>({}));if(!i.ok||!(r!=null&&r.success))throw new Error((r==null?void 0:r.error)||(this.versioningHostMode?"新建宿主机工作区失败":"新建项目失败"));await this.fetchHostWorkspaces();const o=((n=(t=r==null?void 0:r.data)==null?void 0:t.workspace)==null?void 0:n.label)||e||s;this.hostWorkspaceCreateDialogOpen=!1,this.hostWorkspaceCreatePath="",this.hostWorkspaceCreateLabel="",this.uiPushToast({title:this.versioningHostMode?"工作区已创建":"项目已创建",message:o,type:"success"})}catch(i){const r=i instanceof Error?i.message:String(i||"新建失败");this.hostWorkspaceCreateError=r,this.uiPushToast({title:this.versioningHostMode?"新建工作区失败":"新建项目失败",message:r,type:"error"})}finally{this.hostWorkspaceCreateSubmitting=!1}},async submitHostWorkspaceCreateFromManage(s={}){this.hostWorkspaceCreatePath=String((s==null?void 0:s.path)||"").trim(),this.hostWorkspaceCreateLabel=String((s==null?void 0:s.label)||"").trim(),await this.submitHostWorkspaceCreate()},async renameHostWorkspace(s={}){if(!(this.versioningHostMode||this.dockerProjectMode))return;const e=String((s==null?void 0:s.workspace_id)||"").trim(),t=String((s==null?void 0:s.label)||"").trim();if(!e||!t){this.hostWorkspaceCreateError=this.dockerProjectMode?"项目名称不能为空":"工作区名称不能为空";return}this.hostWorkspaceManageSubmitting=!0,this.hostWorkspaceCreateError="";try{const n=this.versioningHostMode?"/api/host/workspaces/rename":"/api/projects/rename",i=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"same-origin",body:JSON.stringify({workspace_id:e,label:t})}),r=await i.json().catch(()=>({}));if(!i.ok||!(r!=null&&r.success))throw new Error((r==null?void 0:r.error)||"重命名失败");await this.fetchHostWorkspaces(),this.uiPushToast({title:this.versioningHostMode?"工作区已重命名":"项目已重命名",message:t,type:"success"})}catch(n){const i=n instanceof Error?n.message:String(n||"重命名失败");this.hostWorkspaceCreateError=i,this.uiPushToast({title:this.versioningHostMode?"重命名工作区失败":"重命名项目失败",message:i,type:"error"})}finally{this.hostWorkspaceManageSubmitting=!1}},async handleDeleteWorkspaceFromSwitcher(s){await this.deleteHostWorkspace(s,{skipConfirm:!0})},async deleteHostWorkspace(s,e={}){if(!(this.versioningHostMode||this.dockerProjectMode))return;const t=String((s==null?void 0:s.workspace_id)||"").trim();if(!t)return;const n=this.versioningHostMode?"工作区":"项目",i=t===this.currentHostWorkspaceId;if(e.skipConfirm||await this.confirmAction({title:`删除${n}`,message:this.versioningHostMode?`确定要从列表中删除“${(s==null?void 0:s.label)||t}”吗?不会删除磁盘上的工作区文件夹。`:`确定要删除项目“${(s==null?void 0:s.label)||t}”吗?该项目文件夹和对话记录会被一并删除。`,confirmText:"删除",cancelText:"取消",confirmVariant:"danger"})){this.hostWorkspaceManageSubmitting=!0,this.hostWorkspaceCreateError="";try{const o=this.versioningHostMode?"/api/host/workspaces/delete":"/api/projects/delete",a=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"same-origin",body:JSON.stringify({workspace_id:t})}),c=await a.json().catch(()=>({}));if(!a.ok||!(c!=null&&c.success))throw new Error((c==null?void 0:c.error)||"删除失败");const l=c.data||{};if(this.currentHostWorkspaceId=String(l.current_workspace_id||this.currentHostWorkspaceId||""),l.default_workspace_id&&(this.defaultHostWorkspaceId=String(l.default_workspace_id)),await this.fetchHostWorkspaces(),i){this.messages=[],this.currentConversationId=null,this.currentConversationTitle="新对话",this.searchActive=!1,this.searchResults=[];const{useConversationStore:u}=await wt(async()=>{const{useConversationStore:h}=await Promise.resolve().then(()=>Ei);return{useConversationStore:h}},void 0);u().resetConversationsTypeCache(),this.conversationsOffset=0,this.hasMoreConversations=!1,this.conversationsLoading=!0,history.replaceState({},"","/new"),await this.loadConversationsList()}this.uiPushToast({title:`${n}已删除`,message:(s==null?void 0:s.label)||t,type:"success"})}catch(o){const a=o instanceof Error?o.message:String(o||"删除失败");this.hostWorkspaceCreateError=a,this.uiPushToast({title:`删除${n}失败`,message:a,type:"error"})}finally{this.hostWorkspaceManageSubmitting=!1}}},async handleSelectWorkspaceConversation(s){const{conversationId:e,workspaceId:t}=s||{};!e||!t||((this.versioningHostMode||this.dockerProjectMode)&&t!==this.currentHostWorkspaceId&&await this.handleHostWorkspaceSwitch(t,{preserveConversationView:!0}),await this.loadConversation(e,{force:!0,workspaceId:t}))},async handleRenameWorkspaceFromSidebar(s){const e=String((s==null?void 0:s.workspace_id)||(s==null?void 0:s.workspaceId)||"").trim(),t=String((s==null?void 0:s.label)||"").trim();!e||!t||await this.renameHostWorkspace({workspace_id:e,label:t})},async handlePinWorkspaceFromSidebar(s){},async revealHostWorkspace(s){if(!(this.versioningHostMode||this.dockerProjectMode))return;const e=String(s||"").trim();if(e)try{const t=await fetch("/api/project/open-in-file-manager",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({workspace_id:e})}),n=await t.json().catch(()=>({}));if(!t.ok||!(n!=null&&n.success))throw new Error((n==null?void 0:n.error)||"打开失败")}catch(t){const n=t instanceof Error?t.message:String(t||"打开失败");this.uiPushToast({title:this.versioningHostMode?"打开工作区失败":"打开项目失败",message:n,type:"error"})}},async setDefaultHostWorkspace(s={}){var n;if(!(this.versioningHostMode||this.dockerProjectMode))return;const e=String((s==null?void 0:s.workspace_id)||"").trim();if(!e||e===this.defaultHostWorkspaceId)return;this.hostWorkspaceManageSubmitting=!0,this.hostWorkspaceCreateError="";const t=this.versioningHostMode?"工作区":"项目";try{const i=this.versioningHostMode?"/api/host/workspaces/set-default":"/api/projects/set-default",r=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"same-origin",body:JSON.stringify({workspace_id:e})}),o=await r.json().catch(()=>({}));if(!r.ok||!(o!=null&&o.success))throw new Error((o==null?void 0:o.error)||`设置默认${t}失败`);const a=o.data||{};this.defaultHostWorkspaceId=String(a.default_workspace_id||e),await this.fetchHostWorkspaces(),this.uiPushToast({title:`已设为默认${t}`,message:((n=(this.hostWorkspaces||[]).find(c=>c.workspace_id===e))==null?void 0:n.label)||e,type:"success"})}catch(i){const r=i instanceof Error?i.message:String(i||`设置默认${t}失败`);this.hostWorkspaceCreateError=r,this.uiPushToast({title:`设置默认${t}失败`,message:r,type:"error"})}finally{this.hostWorkspaceManageSubmitting=!1}}},Eie={async refreshRunningWorkspaceTasks(){var s,e,t,n;if(!(this.versioningHostMode||this.dockerProjectMode)){this.runningWorkspaceTasks=[],this.runningWorkspaceTasksRefreshTimer&&(clearTimeout(this.runningWorkspaceTasksRefreshTimer),this.runningWorkspaceTasksRefreshTimer=null);return}try{const i=await fetch("/api/tasks"),r=await i.json().catch(()=>({}));if(!i.ok||!(r!=null&&r.success))throw new Error((r==null?void 0:r.error)||"获取运行任务失败");const o=Array.isArray(r.data)?r.data:[],a=new Set(["pending","running","cancel_requested"]),c=new Set(["succeeded","failed","canceled"]),l=((s=this.getStoredWorkspaceTaskIdSet)==null?void 0:s.call(this,"tracked"))||new Set,u=new Set(Array.isArray(this.acknowledgedCompletedTaskIds)?this.acknowledgedCompletedTaskIds:[]);(((e=this.getStoredWorkspaceTaskIdSet)==null?void 0:e.call(this,"acknowledged"))||new Set).forEach(v=>u.add(v)),this.acknowledgedCompletedTaskIds=Array.from(u);const d=new Set((Array.isArray(this.runningWorkspaceTasks)?this.runningWorkspaceTasks:[]).map(v=>String((v==null?void 0:v.task_id)||"")).filter(Boolean)),p=o.filter(v=>{const g=String((v==null?void 0:v.task_id)||""),y=String((v==null?void 0:v.status)||""),b=String((v==null?void 0:v.conversation_id)||"");return g?a.has(y)?(l.add(g),!0):c.has(y)&&b===this.currentConversationId?(u.has(g)||(u.add(g),this.acknowledgedCompletedTaskIds=[...Array.isArray(this.acknowledgedCompletedTaskIds)?this.acknowledgedCompletedTaskIds:[],g]),l.delete(g),!1):c.has(y)&&(d.has(g)||l.has(g))&&!u.has(g):!1});this.runningWorkspaceTasks=p,p.forEach(v=>{const g=String((v==null?void 0:v.task_id)||"");g&&l.add(g)}),u.forEach(v=>l.delete(v)),(t=this.setStoredWorkspaceTaskIdSet)==null||t.call(this,"tracked",l),(n=this.setStoredWorkspaceTaskIdSet)==null||n.call(this,"acknowledged",u);const m=p.some(v=>a.has(String((v==null?void 0:v.status)||"")));if(this.runningWorkspaceTasksRefreshTimer&&(clearTimeout(this.runningWorkspaceTasksRefreshTimer),this.runningWorkspaceTasksRefreshTimer=null),m&&(this.runningWorkspaceTasksRefreshTimer=window.setTimeout(()=>{var v;this.runningWorkspaceTasksRefreshTimer=null,(v=this.refreshRunningWorkspaceTasks)==null||v.call(this)},1500)),Array.isArray(this.hostWorkspaces)){const v=p.reduce((g,y)=>{const b=String((y==null?void 0:y.workspace_id)||""),_=String((y==null?void 0:y.status)||"");return b&&a.has(_)&&(g[b]=(g[b]||0)+1),g},{});this.hostWorkspaces=this.hostWorkspaces.map(g=>({...g,running_task_count:Number(v[g.workspace_id]||0)}))}}catch(i){console.warn("刷新运行中任务失败:",i),this.runningWorkspaceTasks=[],this.runningWorkspaceTasksRefreshTimer&&(clearTimeout(this.runningWorkspaceTasksRefreshTimer),this.runningWorkspaceTasksRefreshTimer=null)}},async openRunningWorkspaceTask(s){const e=String((s==null?void 0:s.workspace_id)||"").trim(),t=String((s==null?void 0:s.conversation_id)||"").trim();if(!e||!t||((this.versioningHostMode||this.dockerProjectMode)&&e!==this.currentHostWorkspaceId&&await this.handleHostWorkspaceSwitch(e),this.currentConversationId===t))return;await this.loadConversation(t,{force:!0});const n=String((s==null?void 0:s.task_id)||"");if(n&&!["pending","running","cancel_requested"].includes(String((s==null?void 0:s.status)||""))){this.acknowledgeCompletedWorkspaceTask(n);return}await this.restoreTaskState()}},hF="agents_tutorial_completed_v1",dF="agents_tutorial_version",fF="v1",Mie=[{id:"welcome",title:"欢迎使用 Astrion",description:"我们将用 2-3 分钟带你快速了解核心功能。",target:null,mode:"info",placement:"center"},{id:"sidebar-conversations-open",title:"展开对话记录",description:"下一步会自动点击展开对话记录。",target:'[data-tutorial="conversation-menu"]',mode:"info",autoClick:!0,placement:"right",condition:"not_mobile_viewport"},{id:"sidebar-conversations-close",title:"折叠对话记录",description:"下一步会自动点击折叠按钮收起对话记录。",target:'[data-tutorial="conversation-collapse"]',mode:"info",autoClick:!0,placement:"right",condition:"not_mobile_viewport"},{id:"sidebar-new-chat",title:"新建对话",description:"下一步会自动新建并进入一个对话。",target:'[data-tutorial="quick-new-conversation"]',mode:"info",autoClick:!0,placement:"right",condition:"not_mobile_viewport"},{id:"sidebar-workspace-toggle",title:"工作区折叠",description:"显示/隐藏左侧工作区面板。",target:'[data-tutorial="workspace-toggle"]',mode:"info",placement:"right",condition:"not_mobile_viewport"},{id:"sidebar-monitor-toggle",title:"虚拟显示器",description:"切换到虚拟显示器模式。",target:'[data-tutorial="monitor-toggle"]',mode:"info",placement:"right",condition:"not_mobile_viewport"},{id:"workspace-panel-switch",title:"工作区面板切换",description:"下一步会自动展开面板切换菜单。",target:'[data-tutorial="panel-menu-toggle"]',mode:"info",autoClick:!0,placement:"right",condition:"not_mobile_viewport"},{id:"workspace-panel-options",title:"四合一面板",description:"这里可以切换文件 / 待办 / 子智能体 / 后台指令。",target:'[data-tutorial="panel-menu"]',mode:"info",placement:"right",condition:"not_mobile_viewport"},{id:"workspace-mode-indicator",title:"思考模式",description:"点击切换快速 / 思考。",target:'[data-tutorial="run-mode-indicator"]',mode:"info",placement:"right",condition:"not_mobile_viewport"},{id:"workspace-connection-indicator",title:"连接状态指示灯",description:"绿色表示连接正常;红色表示与后端断开连接。",target:'[data-tutorial="connection-indicator"]',mode:"info",placement:"right",condition:"not_mobile_viewport"},{id:"header-model-selector",title:"模型与模式选择",description:"下一步会自动展开模型与运行模式弹窗。",target:'[data-tutorial="header-model-selector"]',mode:"info",autoClick:!0,placement:"bottom",condition:"not_mobile_viewport"},{id:"header-model-options",title:"模型列表",description:"这里是可用模型列表。",target:'[data-tutorial="header-model-options"]',mode:"info",placement:"bottom",condition:"not_mobile_viewport"},{id:"header-runmode-options",title:"运行模式列表",description:"这里可切换快速 / 思考。",target:'[data-tutorial="header-runmode-options"]',mode:"info",placement:"bottom",condition:"not_mobile_viewport"},{id:"header-menu-close",title:"关闭模型菜单",description:"下一步会自动点击空白区域关闭菜单。",target:".model-mode-dropdown",mode:"info",autoOutsideClick:!0,placement:"bottom",condition:"not_mobile_viewport"},{id:"mobile-menu-open-conversation",title:"打开菜单",description:"下一步会自动打开左上角菜单。",target:'[data-tutorial="mobile-menu-trigger"]',mode:"info",autoClick:!0,placement:"bottom",condition:"is_mobile_viewport"},{id:"mobile-menu-conversation",title:"对话记录",description:"下一步会自动进入对话记录。",target:'[data-tutorial="mobile-menu-conversation"]',mode:"info",autoClick:!0,placement:"bottom",condition:"is_mobile_viewport"},{id:"mobile-conversation-close",title:"关闭对话记录",description:"下一步会自动关闭对话记录面板。",target:'[data-tutorial="conversation-collapse"]',mode:"info",autoClick:!0,placement:"right",condition:"is_mobile_viewport"},{id:"mobile-menu-open-workspace",title:"再次打开菜单",description:"下一步会自动打开菜单。",target:'[data-tutorial="mobile-menu-trigger"]',mode:"info",autoClick:!0,placement:"bottom",condition:"is_mobile_viewport"},{id:"mobile-menu-workspace",title:"工作文件",description:"下一步会自动进入工作文件。",target:'[data-tutorial="mobile-menu-workspace"]',mode:"info",autoClick:!0,placement:"bottom",condition:"is_mobile_viewport"},{id:"mobile-workspace-panel-switch",title:"工作区面板切换",description:"下一步会自动展开切换弹窗。",target:'[data-tutorial="panel-menu-toggle"]',mode:"info",autoClick:!0,placement:"bottom",condition:"is_mobile_viewport"},{id:"mobile-workspace-panel-options",title:"切换弹窗选项",description:"这里可切换文件 / 待办 / 子智能体 / 后台指令。",target:'[data-tutorial="panel-menu"]',mode:"info",placement:"bottom",condition:"is_mobile_viewport"},{id:"mobile-workspace-close",title:"关闭工作文件",description:"下一步会自动关闭工作文件面板。",target:'[data-tutorial="mobile-workspace-close"]',mode:"info",autoClick:!0,placement:"right",condition:"is_mobile_viewport"},{id:"mobile-menu-open-newchat",title:"再次打开菜单",description:"下一步会自动打开菜单。",target:'[data-tutorial="mobile-menu-trigger"]',mode:"info",autoClick:!0,placement:"bottom",condition:"is_mobile_viewport"},{id:"mobile-menu-new-chat",title:"新建对话",description:"下一步会自动新建对话。",target:'[data-tutorial="mobile-menu-new-chat"]',mode:"info",autoClick:!0,placement:"bottom",condition:"is_mobile_viewport"},{id:"mobile-model-selector-open",title:"模型与思考模式",description:"下一步会自动展开手机端模型/思考模式选择。",target:'[data-tutorial="header-model-selector-mobile"]',mode:"info",autoClick:!0,placement:"bottom",condition:"is_mobile_viewport"},{id:"mobile-model-options",title:"模型列表",description:"这里是手机端可选模型。",target:'[data-tutorial="header-model-options"]',mode:"info",placement:"bottom",condition:"is_mobile_viewport"},{id:"mobile-runmode-options",title:"思考模式列表",description:"这里可切换快速 / 思考。",target:'[data-tutorial="header-runmode-options"]',mode:"info",placement:"bottom",condition:"is_mobile_viewport"},{id:"mobile-model-selector-close",title:"关闭选择菜单",description:"下一步会自动点击空白区域关闭菜单。",target:".model-mode-dropdown",mode:"info",autoOutsideClick:!0,placement:"bottom",condition:"is_mobile_viewport"},{id:"open-quick-menu",title:"打开 + 菜单",description:"将自动为你展开快捷菜单。",target:'[data-tutorial="quick-menu-open"]',mode:"info",autoClick:!0,placement:"top"},{id:"quick-upload",title:"上传文件",description:"上传本地文件到当前工作区。",target:'[data-tutorial="quick-upload"]',mode:"info",placement:"left"},{id:"quick-review",title:"对话回顾",description:"回顾并压缩上下文。",target:'[data-tutorial="quick-review"]',mode:"info",placement:"left"},{id:"quick-send-image",title:"发送图片",description:"当前模型支持时,可发送图片给 AI 分析。",target:'[data-tutorial="quick-send-image"]',mode:"info",placement:"left",condition:"model_supports_media"},{id:"quick-send-video",title:"发送视频",description:"当前模型支持时,可发送视频给 AI 分析。",target:'[data-tutorial="quick-send-video"]',mode:"info",placement:"left",condition:"model_supports_media"},{id:"quick-tool-disable",title:"工具禁用",description:"临时禁用工具分类,控制模型行为范围。",target:'[data-tutorial="quick-tool-menu"]',mode:"info",placement:"left"},{id:"quick-settings",title:"设置菜单",description:"这里可快速访问常用功能。",target:'[data-tutorial="quick-settings-menu"]',mode:"info",placement:"left"},{id:"open-settings-submenu",title:"打开设置子菜单",description:"下一步会自动展开设置子菜单。",target:'[data-tutorial="quick-settings-menu"]',mode:"info",autoClick:!0,placement:"left"},{id:"open-token-panel",title:"打开用量统计",description:"下一步会自动打开用量统计面板。",target:'[data-tutorial="settings-token-panel"]',mode:"info",autoClick:!0,placement:"left"},{id:"token-panel",title:"Token 统计面板",description:"这里可以查看上下文、额度和资源统计。",target:'[data-tutorial="token-drawer"]',mode:"info",placement:"left"},{id:"close-token-panel",title:"关闭统计面板",description:"下一步会自动关闭统计面板。",target:'[data-tutorial="token-close"]',mode:"info",autoClick:!0,placement:"left"},{id:"open-personal-space",title:"打开个人空间",description:"下一步会自动打开个人空间。",target:'[data-tutorial="open-personal-space"]',mode:"info",autoClick:!0,placement:"right",condition:"not_mobile_viewport"},{id:"mobile-menu-open-personal",title:"打开菜单",description:"下一步会自动打开菜单。",target:'[data-tutorial="mobile-menu-trigger"]',mode:"info",autoClick:!0,placement:"bottom",condition:"is_mobile_viewport"},{id:"mobile-menu-personal",title:"进入个人空间",description:"下一步会自动进入个人空间。",target:'[data-tutorial="mobile-menu-personal"]',mode:"info",autoClick:!0,placement:"bottom",condition:"is_mobile_viewport"},{id:"personal-overview",title:"个人空间总览",description:"这里是个性化设置与高级配置中心。",target:'[data-tutorial="personal-card"]',mode:"info",placement:"right"},{id:"tab-preferences",title:"个性化设置",description:"下一步自动切换到“个性化设置”。",target:'[data-tutorial="personal-tab-preferences"]',mode:"info",autoClick:!0,placement:"right"},{id:"page-preferences",title:"个性化设置内容",description:"可配置昵称、语气、职业和必备信息。",target:'[data-tutorial="personal-content-shell"]',mode:"info",placement:"right"},{id:"tab-model",title:"模型偏好",description:"下一步自动切换到“模型偏好”。",target:'[data-tutorial="personal-tab-model"]',mode:"info",autoClick:!0,placement:"right"},{id:"page-model",title:"模型偏好内容",description:"可设置默认模型、默认运行模式和思考频率。",target:'[data-tutorial="personal-content-shell"]',mode:"info",placement:"right"},{id:"tab-usage",title:"用量统计",description:"下一步自动切换到“用量统计”。",target:'[data-tutorial="personal-tab-usage"]',mode:"info",autoClick:!0,placement:"right"},{id:"page-usage",title:"用量统计内容",description:"可查看累计 Token、对话数和工具调用数据。",target:'[data-tutorial="personal-content-shell"]',mode:"info",placement:"right"},{id:"tab-app-update",title:"软件更新",description:"移动端将自动切换到“软件更新”。",target:'[data-tutorial="personal-tab-app-update"]',mode:"info",autoClick:!0,placement:"right",condition:"is_app_shell"},{id:"page-app-update",title:"软件更新内容",description:"这里会展示最新版本和更新说明。",target:'[data-tutorial="personal-content-shell"]',mode:"info",placement:"right",condition:"is_app_shell"},{id:"tab-behavior",title:"智能体行为",description:"下一步自动切换到“智能体行为”。",target:'[data-tutorial="personal-tab-behavior"]',mode:"info",autoClick:!0,placement:"right"},{id:"page-behavior",title:"智能体行为内容",description:"可配置工具显示、压缩策略等高级选项。",target:'[data-tutorial="personal-content-shell"]',mode:"info",placement:"right"},{id:"tab-skills",title:"Skills",description:"下一步自动切换到“Skills”。",target:'[data-tutorial="personal-tab-skills"]',mode:"info",autoClick:!0,placement:"right"},{id:"page-skills",title:"Skills 内容",description:"可启用/禁用技能并同步到工作区。",target:'[data-tutorial="personal-content-shell"]',mode:"info",placement:"right"},{id:"tab-image",title:"图片压缩",description:"下一步自动切换到“图片压缩”。",target:'[data-tutorial="personal-tab-image"]',mode:"info",autoClick:!0,placement:"right"},{id:"page-image",title:"图片压缩内容",description:"可选择原图、1080p、720p、540p 压缩策略。",target:'[data-tutorial="personal-content-shell"]',mode:"info",placement:"right"},{id:"tab-theme",title:"主题切换",description:"下一步自动切换到“主题切换”。",target:'[data-tutorial="personal-tab-theme"]',mode:"info",autoClick:!0,placement:"right"},{id:"page-theme",title:"主题切换内容",description:"可在经典、明亮、夜间主题间切换。",target:'[data-tutorial="personal-content-shell"]',mode:"info",placement:"right"},{id:"close-personal-space",title:"关闭个人空间",description:"下一步自动关闭个人空间并结束导览。",target:'[data-tutorial="personal-close"]',mode:"info",autoClick:!0,placement:"bottom"},{id:"done",title:"教程完成!",description:"恭喜你完成新手教程。可随时在个人空间「新手教程」再次查看。",target:null,mode:"info",placement:"center"}],xie=()=>typeof window>"u"?!1:new URLSearchParams(window.location.search).has("app_shell")?!0:!!(window!=null&&window.AndroidThemeBridge),t2=()=>typeof window>"u"?!1:window.innerWidth<=768,h1=s=>{if(!s.condition)return!0;if(s.condition==="is_app_shell")return xie();if(s.condition==="model_supports_media"){const t=Qi().currentModel;return!!(t!=null&&t.supportsImage||t!=null&&t.supportsVideo)}return s.condition==="is_mobile_viewport"?t2():s.condition==="not_mobile_viewport"?!t2():!0},Iie=()=>{if(typeof window>"u"||!window.localStorage)return!1;try{return window.localStorage.getItem(dF)!==fF?!1:window.localStorage.getItem(hF)==="1"}catch{return!1}},d1=s=>{if(!(typeof window>"u"||!window.localStorage))try{window.localStorage.setItem(dF,fF),window.localStorage.setItem(hF,s?"1":"0")}catch{}},tE=dn("tutorial",{state:()=>({running:!1,completed:Iie(),currentIndex:0,steps:Mie,activeSelector:null}),getters:{activeStep(s){return s.steps[s.currentIndex]||null},totalVisibleSteps(s){return s.steps.filter(e=>h1(e)).length},visibleStepIndex(s){if(!s.running)return 0;let e=0;for(let t=0;t<=s.currentIndex;t+=1){const n=s.steps[t];n&&h1(n)&&(e+=1)}return e}},actions:{shouldIncludeStep(s){return h1(s)},startTutorial(){this.running=!0,this.completed=!1,this.currentIndex=0,this.activeSelector=null,d1(!1),this.skipHiddenSteps("forward")},exitTutorial(){this.running=!1,this.activeSelector=null},finishTutorial(){this.running=!1,this.completed=!0,this.activeSelector=null,d1(!0)},goNext(){var s;if(this.running){if(this.currentIndex>=this.steps.length-1){this.finishTutorial();return}this.currentIndex+=1,this.skipHiddenSteps("forward"),this.currentIndex>=this.steps.length-1&&((s=this.activeStep)==null?void 0:s.id)==="done"&&(this.completed=!0)}},goPrev(){this.running&&(this.currentIndex<=0||(this.currentIndex-=1,this.skipHiddenSteps("backward")))},skipCurrentStep(){this.goNext()},markCompleted(){this.completed=!0,d1(!0)},skipHiddenSteps(s){if(this.running)if(s==="forward"){for(;this.currentIndex<this.steps.length&&!this.shouldIncludeStep(this.steps[this.currentIndex]);)this.currentIndex+=1;if(this.currentIndex>=this.steps.length){this.finishTutorial();return}}else for(;this.currentIndex>0&&!this.shouldIncludeStep(this.steps[this.currentIndex]);)this.currentIndex-=1},setActiveSelector(s){this.activeSelector=s}}}),Rie={async checkTutorialPrompt(){this.tutorialPromptVisible=!1,this.tutorialPromptUsername="";try{const s=await fetch("/api/tutorial-status",{credentials:"same-origin"}),e=await s.json().catch(()=>({}));if(!s.ok||!(e!=null&&e.success))return;const t=e.data||{};if(!t.applicable||!t.should_prompt)return;this.tutorialPromptUsername=t.username||"",this.tutorialPromptVisible=!0}catch(s){console.warn("获取新手教程提示状态失败:",s)}},async updateTutorialPromptStatus(s=!0){this.tutorialPromptLoading=!0;try{const e=await fetch("/api/tutorial-status",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"same-origin",body:JSON.stringify({tutorial_completed:!!s})}),t=await e.json().catch(()=>({}));if(!e.ok||!(t!=null&&t.success))throw new Error((t==null?void 0:t.error)||"更新新手教程状态失败");return tE().markCompleted(),this.tutorialPromptVisible=!1,!0}catch(e){return console.warn("更新新手教程提示状态失败:",e),this.uiPushToast({title:"提示",message:"保存新手教程状态失败,请稍后重试",type:"warning"}),!1}finally{this.tutorialPromptLoading=!1}},async handleNewUserTutorialStart(){if(!await this.updateTutorialPromptStatus(!0))return;qs().closeDrawer();const t=tE();window.setTimeout(()=>{t.startTutorial()},220)},async handleNewUserTutorialSkip(){await this.updateTutorialPromptStatus(!0)}},Bn={timer:null,rollback:void 0,latest:void 0,conversationId:null},Lie={handleQuickModeToggle(){!this.isConnected||this.streamingMessage||this.handleCycleRunMode()},toggleQuickMenu(){if(!this.isConnected)return;this.inputToggleQuickMenu()||(this.modeMenuOpen=!1,this.modelMenuOpen=!1)},closeQuickMenu(){this.inputCloseMenus(),this.modeMenuOpen=!1,this.modelMenuOpen=!1,this.agentTypeMenuOpen=!1,this.workModeMenuOpen=!1},handleToggleGoalMode(){var e;if(!this.isConnected)return;if(this.goalRunning){this.goalDialogOpen=!0,this.inputCloseMenus();return}const s=String(((e=this.goalProgress)==null?void 0:e.status)||"").toLowerCase();(s==="done"||s==="stopped")&&(this.goalProgress=null,this.goalDialogOpen=!1),this.inputToggleGoalArmed(),this.inputCloseMenus(),this.modeMenuOpen=!1,this.modelMenuOpen=!1},async handleWorkflowActivated(s){const e=String(s||"").trim();if(!(!e||e===this.currentConversationId)){try{await this.persistComposerDraftNow({reason:"workflow-activated",force:!0})}catch{}try{const t={id:e,title:"新对话",updated_at:new Date().toISOString(),total_messages:0,total_tools:0};Array.isArray(this.conversations)&&this.conversations.splice(0,this.conversations.length,t,...this.conversations.filter(n=>n&&n.id!==e))}catch{}try{await this.enterConversation(e,{source:"sidebar",urlMode:"push"})}catch(t){console.warn("[Workflow] 激活后进入新对话失败:",t)}}},handleToggleAgentTypeMenu(){var e;if(!this.isConnected||this.currentConversationId)return;const s=!this.agentTypeMenuOpen;this.agentTypeMenuOpen=s,s&&(this.permissionMenuOpen=!1,this.workModeMenuOpen=!1,this.modelMenuOpen=!1,this.modeMenuOpen=!1,(e=this.inputCloseMenus)==null||e.call(this))},handleSelectNewConversationType(s){const e=s==="multi_agent"?"multi_agent":"agent";this.newConversationType=e,wD(e),this.agentTypeMenuOpen=!1},toggleModeMenu(){if(!this.isConnected||this.streamingMessage)return;const s=!this.modeMenuOpen;this.modeMenuOpen=s,s&&(this.modelMenuOpen=!1),s&&(this.inputSetToolMenuOpen(!1),this.inputSetSettingsOpen(!1),this.quickMenuOpen||this.inputOpenQuickMenu())},async handleModeSelect(s){!this.isConnected||this.streamingMessage||await this.setRunMode(s)},async handleHeaderRunModeSelect(s){await this.handleModeSelect(s),this.closeHeaderMenu()},async handleCycleRunMode(){const s=["fast","thinking"],e=this.resolvedRunMode,t=s.indexOf(e),n=s[(t+1)%s.length];await this.setRunMode(n)},async setRunMode(s,e={}){var r,o;if(!this.isConnected||this.streamingMessage){this.modeMenuOpen=!1;return}s==="deep"&&(s="thinking");const t=Qi(),n=(r=t.currentModel)==null?void 0:r.fastOnly,i=(o=t.currentModel)==null?void 0:o.thinkingOnly;if(n&&s!=="fast"){e.suppressToast||this.uiPushToast({title:"模式不可用",message:"当前模型仅支持快速模式",type:"warning"}),this.modeMenuOpen=!1,this.inputCloseMenus();return}if(i&&s!=="thinking"){e.suppressToast||this.uiPushToast({title:"模式不可用",message:"当前模型仅支持思考模式",type:"warning"}),this.modeMenuOpen=!1,this.inputCloseMenus();return}if(s===this.resolvedRunMode){this.modeMenuOpen=!1,this.closeQuickMenu();return}try{const a=await fetch("/api/thinking-mode",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:s})}),c=await a.json();if(!a.ok||!c.success)throw new Error(c.message||c.error||"切换失败");const l=c.data||{};this.thinkingMode=typeof l.thinking_mode=="boolean"?l.thinking_mode:s!=="fast",this.runMode=l.mode||s}catch(a){console.error("切换运行模式失败:",a);const c=a instanceof Error?a.message:String(a||"未知错误");this.uiPushToast({title:"切换思考模式失败",message:c||"请稍后重试",type:"error"})}finally{this.modeMenuOpen=!1,this.inputCloseMenus()}},async toggleThinkingMode(){await this.handleCycleRunMode()},async setReasoningEffort(s){Bn.rollback===void 0&&(Bn.rollback=this.reasoningEffort,Bn.conversationId=this.currentConversationId||null),Bn.latest=s,this.reasoningEffort=s,Bn.timer&&clearTimeout(Bn.timer),Bn.timer=setTimeout(()=>{Bn.timer=null,this.flushReasoningEffortSave()},600)},async flushReasoningEffortSave(){if(Bn.timer&&(clearTimeout(Bn.timer),Bn.timer=null),Bn.rollback===void 0)return;const s=Bn.latest,e=Bn.rollback,t=Bn.conversationId;Bn.rollback=void 0,Bn.latest=void 0,Bn.conversationId=null;try{const n=await fetch("/api/reasoning-effort",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({effort:s,conversation_id:t})}),i=await n.json();if(!n.ok||!i.success)throw new Error(i.message||i.error||"设置失败");const r=i.data||{};Object.prototype.hasOwnProperty.call(r,"reasoning_effort")&&this.reasoningEffort===s&&(this.reasoningEffort=typeof r.reasoning_effort=="string"?r.reasoning_effort:null)}catch(n){this.reasoningEffort===s&&(this.reasoningEffort=e),console.error("设置推理强度失败:",n);const i=n instanceof Error?n.message:String(n||"未知错误");this.uiPushToast({title:"设置推理强度失败",message:i||"请稍后重试",type:"error"})}},async handleStopAllSubAgents(){const s=this.currentConversationType==="multi_agent",e=s?"soft_stop":"terminate",t=s?"是否暂停所有子智能体?":"是否终结所有子智能体?",n=s?"所有正在运行的子智能体将停止工作并变为空闲状态。取消表示不执行操作。":"所有后台子智能体将被强制终止。取消表示不执行操作。",i=s?"暂停":"终结";let r=!1;try{r=await(await wt(async()=>{const{useUiStore:a}=await Promise.resolve().then(()=>XF);return{useUiStore:a}},void 0)).useUiStore().requestConfirm({title:t,message:n,confirmText:i,cancelText:"取消",confirmVariant:"danger",closeOnBackdrop:!0})}catch(o){console.error("[stopAllSubAgents] 弹窗异常:",o);return}if(r)try{const{useSubAgentStore:o}=await wt(async()=>{const{useSubAgentStore:l}=await Promise.resolve().then(()=>f$);return{useSubAgentStore:l}},void 0),c=await o().stopAllAgents(e);if(!c.success){this.uiPushToast({title:"停止子智能体失败",message:c.error||"请重试",type:"error"});return}this.uiPushToast({title:s?"子智能体已暂停":"子智能体已终结",message:`已处理 ${c.stoppedCount||0} 个子智能体`,type:"info"})}catch(o){console.error("[stopAllSubAgents] 调用失败:",o),this.uiPushToast({title:"停止子智能体失败",message:(o==null?void 0:o.message)||String(o),type:"error"})}}},Pie={toggleModelMenu(){if(!this.isConnected||this.streamingMessage)return;const s=!this.modelMenuOpen;this.modelMenuOpen=s,s&&(this.modeMenuOpen=!1,this.inputSetToolMenuOpen(!1),this.inputSetSettingsOpen(!1),this.quickMenuOpen||this.inputOpenQuickMenu())},async handleModelSelect(s){var r;if(!this.isConnected||this.streamingMessage)return;if(No().isModelDisabled(s)){this.uiPushToast({title:"模型被禁用",message:"被管理员强制禁用",type:"warning"});return}const t=Qi(),n=t.models.find(o=>o.key===s);if(this.conversationHasImages&&!(n!=null&&n.supportsImage)){this.uiPushToast({title:"切换失败",message:"当前对话包含图片,目标模型不支持图片输入",type:"error"});return}if(this.conversationHasVideos&&!(n!=null&&n.supportsVideo)){this.uiPushToast({title:"切换失败",message:"当前对话包含视频,目标模型不支持视频输入",type:"error"});return}const i=this.currentModelKey;try{const o=await fetch("/api/model",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model_key:s,conversation_id:this.currentConversationId||void 0})}),a=await o.json();if(!o.ok||!a.success)throw new Error(a.error||a.message||"切换失败");const c=a.data||{};if(t.setModel(c.model_key||s),c.run_mode)this.runMode=c.run_mode,this.thinkingMode=c.thinking_mode??c.run_mode!=="fast";else{const l=t.currentModel;l!=null&&l.thinkingOnly?(this.runMode="thinking",this.thinkingMode=!0):l!=null&&l.fastOnly?(this.runMode="fast",this.thinkingMode=!1):this.thinkingMode=this.runMode!=="fast"}this.uiPushToast({title:"模型已切换",message:((r=t.currentModel)==null?void 0:r.label)||s,type:"success"})}catch(o){t.setModel(i);const a=o instanceof Error?o.message:String(o||"切换失败");this.uiPushToast({title:"切换模型失败",message:a,type:"error"})}finally{this.modelMenuOpen=!1,this.inputCloseMenus(),this.inputSetQuickMenuOpen(!1)}},async handleHeaderModelSelect(s,e){e||(await this.handleModelSelect(s),this.closeHeaderMenu())}},Oie={applyPolicyUiLocks(){const e=No().uiBlocks;e.collapse_workspace&&this.uiSetWorkspaceCollapsed(!0),e.block_virtual_monitor&&this.chatDisplayMode==="monitor"&&this.uiSetChatDisplayMode("chat")},isPolicyBlocked(s,e){return No().uiBlocks[s]?(this.uiPushToast({title:"已被管理员禁用",message:e||"被管理员强制禁用",type:"warning"}),!0):!1},getPermissionModeLabel(s){const t=(Array.isArray(this.permissionModeOptions)?this.permissionModeOptions:[]).find(n=>n.value===s);return t?t.label:s||"未知"},getExecutionModeLabel(s){const t=(Array.isArray(this.executionModeOptions)?this.executionModeOptions:[]).find(n=>n.value===s);return t?t.label:s||"未知"},async changePermissionMode(s){const e=String(s||"").trim().toLowerCase();if(!e){this.closePermissionMenu();return}try{const t=await fetch("/api/permission-mode",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:e,...this.currentConversationId?{conversation_id:this.currentConversationId}:{}})}),n=await t.json().catch(()=>({}));if(!t.ok||!(n!=null&&n.success))throw new Error((n==null?void 0:n.message)||(n==null?void 0:n.error)||"切换权限失败");typeof(n==null?void 0:n.mode)=="string"&&(this.currentPermissionMode=n.mode);const i=(n==null?void 0:n.state)||{};typeof i.mode=="string"&&(this.currentExecutionMode=i.mode),this.pendingPermissionMode="",this.uiPushToast({title:"权限已更新",message:(n==null?void 0:n.message)||"已立即生效",type:"info",duration:1800})}catch(t){const n=t instanceof Error?t.message:String(t||"切换权限失败");this.uiPushToast({title:"切换权限失败",message:n,type:"error"})}finally{this.closePermissionMenu()}},async changeExecutionMode(s){const e=String(s||"").trim().toLowerCase();if(!(!this.executionModeEnabled||!e))try{const t=await fetch("/api/execution-mode",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:e,...this.currentConversationId?{conversation_id:this.currentConversationId}:{}})}),n=await t.json().catch(()=>({}));if(!t.ok||!(n!=null&&n.success))throw new Error((n==null?void 0:n.message)||(n==null?void 0:n.error)||"切换执行环境失败");const i=(n==null?void 0:n.state)||{};typeof i.mode=="string"&&(this.currentExecutionMode=i.mode),this.pendingExecutionMode="",this.uiPushToast({title:"执行环境已更新",message:(n==null?void 0:n.message)||"已立即生效",type:this.currentExecutionMode==="direct"?"warning":"info",duration:1800})}catch(t){const n=t instanceof Error?t.message:String(t||"切换执行环境失败");this.uiPushToast({title:"切换执行环境失败",message:n,type:"error"})}},async handleSwitchPermissionToUnrestricted(s){await this.changePermissionMode("unrestricted"),s&&await this.approveToolApproval(s)},async changeNetworkPermission(s){const e=String(s||"").trim().toLowerCase();if(!(!this.networkPermissionEnabled||!e))try{const t=await fetch("/api/network-permission",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:e,...this.currentConversationId?{conversation_id:this.currentConversationId}:{}})}),n=await t.json().catch(()=>({}));if(!t.ok||!(n!=null&&n.success))throw new Error((n==null?void 0:n.message)||(n==null?void 0:n.error)||"切换网络权限失败");typeof n.mode=="string"&&(this.currentNetworkPermission=n.mode),this.pendingNetworkPermission=typeof n.pending_mode=="string"?n.pending_mode:"";const i={restricted:"受限",full:"完全开放"};this.uiPushToast({title:"网络权限已更新",message:(n==null?void 0:n.message)||`已切换为 ${i[this.currentNetworkPermission]||this.currentNetworkPermission}`,type:this.currentNetworkPermission==="full"?"warning":"info",duration:1800})}catch(t){const n=t instanceof Error?t.message:String(t||"切换网络权限失败");this.uiPushToast({title:"切换网络权限失败",message:n,type:"error"})}},async fetchNetworkPermission(){try{const s=this.currentConversationId?`?conversation_id=${encodeURIComponent(this.currentConversationId)}`:"",e=await fetch(`/api/network-permission${s}`),t=await e.json().catch(()=>({}));if(!e.ok||!(t!=null&&t.success))return;this.networkPermissionEnabled=!!t.enabled,typeof t.mode=="string"&&(this.currentNetworkPermission=t.mode),this.pendingNetworkPermission=typeof t.pending_mode=="string"?t.pending_mode:""}catch{}},async fetchPermissionMode(){try{const s=this.currentConversationId?`?conversation_id=${encodeURIComponent(this.currentConversationId)}`:"",e=await fetch(`/api/permission-mode${s}`),t=await e.json().catch(()=>({}));if(!e.ok||!(t!=null&&t.success))return;typeof t.mode=="string"&&(this.currentPermissionMode=t.mode),this.pendingPermissionMode=typeof t.pending_mode=="string"?t.pending_mode:""}catch{}},async fetchExecutionMode(){try{const s=this.currentConversationId?`?conversation_id=${encodeURIComponent(this.currentConversationId)}`:"",e=await fetch(`/api/execution-mode${s}`),t=await e.json().catch(()=>({}));if(!e.ok||!(t!=null&&t.success))return;this.executionModeEnabled=!!t.enabled;const n=t.state||{};typeof n.mode=="string"&&(this.currentExecutionMode=n.mode),this.pendingExecutionMode=typeof t.pending_mode=="string"?t.pending_mode:""}catch{}},async openPathAuthorizationDialog(){if(this.executionModeEnabled){this.pathAuthorizationDialogOpen=!0;try{const s=await fetch("/api/path-authorization"),e=await s.json().catch(()=>({}));if(s.ok&&(e!=null&&e.success)){const t=Array.isArray(e.writable_paths)?e.writable_paths:[],n=Array.isArray(e.readable_extra_paths)?e.readable_extra_paths:[];this.pathAuthorizationWritableDraft=t.join(`
`),this.pathAuthorizationReadableDraft=n.join(`
`),this.pathAuthorizationMode="writable",this.pathAuthorizationDraft=this.pathAuthorizationWritableDraft}}catch{}}},setPathAuthorizationMode(s){this.pathAuthorizationMode==="readable"?this.pathAuthorizationReadableDraft=String(this.pathAuthorizationDraft||""):this.pathAuthorizationWritableDraft=String(this.pathAuthorizationDraft||"");const e=s==="readable"?"readable":"writable";this.pathAuthorizationMode=e,this.pathAuthorizationDraft=e==="readable"?this.pathAuthorizationReadableDraft:this.pathAuthorizationWritableDraft},closePathAuthorizationDialog(){this.pathAuthorizationDialogOpen=!1},async savePathAuthorization(){const s=String(this.pathAuthorizationDraft||"").split(`
`).map(n=>n.trim()).filter(Boolean);this.pathAuthorizationMode==="readable"?this.pathAuthorizationReadableDraft=s.join(`
`):this.pathAuthorizationWritableDraft=s.join(`
`);const e=String(this.pathAuthorizationWritableDraft||"").split(`
`).map(n=>n.trim()).filter(Boolean),t=String(this.pathAuthorizationReadableDraft||"").split(`
`).map(n=>n.trim()).filter(Boolean);this.pathAuthorizationSaving=!0;try{const n=await fetch("/api/path-authorization",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({writable_paths:e,readable_extra_paths:t})}),i=await n.json().catch(()=>({}));if(!n.ok||!(i!=null&&i.success))throw new Error((i==null?void 0:i.error)||"保存失败");const r=Array.isArray(i.writable_paths)?i.writable_paths:e,o=Array.isArray(i.readable_extra_paths)?i.readable_extra_paths:t;this.pathAuthorizationWritableDraft=r.join(`
`),this.pathAuthorizationReadableDraft=o.join(`
`),this.pathAuthorizationDraft=this.pathAuthorizationMode==="readable"?this.pathAuthorizationReadableDraft:this.pathAuthorizationWritableDraft,this.uiPushToast({title:"路径授权已保存",message:"命令工具立即生效;终端会话请重开后生效",type:"success"}),this.pathAuthorizationDialogOpen=!1}catch(n){const i=n instanceof Error?n.message:String(n||"保存失败");this.uiPushToast({title:"保存路径授权失败",message:i,type:"error"})}finally{this.pathAuthorizationSaving=!1}},async fetchPendingToolApprovals(){if(!this.currentConversationId){this.pendingToolApprovals=[];return}try{const s=await fetch(`/api/tool-approvals/pending?conversation_id=${encodeURIComponent(this.currentConversationId)}`),e=await s.json().catch(()=>({}));if(!s.ok||!(e!=null&&e.success))return;const t=Array.isArray(e.items)?e.items:[];this.pendingToolApprovals=t;const n=this.currentPermissionMode==="auto_approval"&&qs().form.hide_tool_approval_panel!==!1;t.length>0&&!this.isMobileViewport&&!n&&(this.rightCollapsed=!1,this.rightWidth<this.minPanelWidth&&(this.rightWidth=this.minPanelWidth))}catch{}},togglePermissionMenu(){this.isConnected&&(this.permissionMenuOpen=!this.permissionMenuOpen)},closePermissionMenu(){this.permissionMenuOpen=!1}},Die={getWorkModeLabel(s){const t=(Array.isArray(this.workModeOptions)?this.workModeOptions:[]).find(n=>n.value===s);return t?t.label:s||"未知"},async fetchWorkMode(){try{const s=this.currentConversationId?`?conversation_id=${encodeURIComponent(this.currentConversationId)}`:"",e=await fetch(`/api/work-mode${s}`),t=await e.json().catch(()=>({}));if(!e.ok||!(t!=null&&t.success))return;typeof t.mode=="string"&&(this.currentWorkMode=t.mode),typeof t.permission_mode=="string"&&t.permission_mode&&(this.currentPermissionMode=t.permission_mode),typeof t.execution_mode=="string"&&t.execution_mode&&(this.currentExecutionMode=t.execution_mode)}catch{}},async changeWorkMode(s){const e=String(s||"").trim().toLowerCase();if(!e){this.closeWorkModeMenu();return}try{const t=await fetch("/api/work-mode",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:e,...this.currentConversationId?{conversation_id:this.currentConversationId}:{}})}),n=await t.json().catch(()=>({}));if(t.status===409)throw new Error((n==null?void 0:n.message)||"对话运行中,请等待当前任务结束后再切换运行模式");if(!t.ok||!(n!=null&&n.success))throw new Error((n==null?void 0:n.message)||(n==null?void 0:n.error)||"切换运行模式失败");typeof(n==null?void 0:n.mode)=="string"&&(this.currentWorkMode=n.mode),typeof(n==null?void 0:n.permission_mode)=="string"&&n.permission_mode?this.currentPermissionMode=n.permission_mode:this.fetchPermissionMode(),typeof(n==null?void 0:n.execution_mode)=="string"&&n.execution_mode?this.currentExecutionMode=n.execution_mode:this.fetchExecutionMode();const i={plan:"计划",ask:"询问",execute:"执行"};this.uiPushToast({title:"运行模式已更新",message:(n==null?void 0:n.message)||`已切换为 ${i[this.currentWorkMode]||this.currentWorkMode}`,type:"info",duration:1800})}catch(t){const n=t instanceof Error?t.message:String(t||"切换运行模式失败");this.uiPushToast({title:"切换运行模式失败",message:n,type:"error"})}finally{this.closeWorkModeMenu()}},toggleWorkModeMenu(){var e;if(!this.isConnected||this.streamingMessage)return;const s=!this.workModeMenuOpen;this.workModeMenuOpen=s,s&&(this.permissionMenuOpen=!1,this.modelMenuOpen=!1,this.modeMenuOpen=!1,this.agentTypeMenuOpen=!1,(e=this.inputCloseMenus)==null||e.call(this))},closeWorkModeMenu(){this.workModeMenuOpen=!1}},Nie={toggleHeaderMenu(){this.isConnected&&(this.headerMenuOpen=!this.headerMenuOpen,this.headerMenuOpen&&(this.closeQuickMenu(),this.inputCloseMenus()))},togglePermissionMenu(){if(!this.isConnected)return;const s=!this.permissionMenuOpen;this.permissionMenuOpen=s,s&&(this.workModeMenuOpen=!1)},closePermissionMenu(){this.permissionMenuOpen=!1},toggleSettings(){if(!this.isConnected)return;this.modeMenuOpen=!1,this.modelMenuOpen=!1,this.inputToggleSettingsMenu()&&(this.inputSetToolMenuOpen(!1),this.quickMenuOpen||this.inputOpenQuickMenu())},handleClickOutsideQuickMenu(s){if(!this.quickMenuOpen&&!this.permissionMenuOpen&&!this.agentTypeMenuOpen&&!this.workModeMenuOpen)return;const e=this.getComposerElement("stadiumShellOuter")||this.getComposerElement("compactInputShell");e&&e.contains(s.target)||(this.closeQuickMenu(),this.closePermissionMenu(),this.closeWorkModeMenu())},handleClickOutsideHeaderMenu(s){if(!this.headerMenuOpen)return;const e=this.$refs.titleRibbon,t=this.$refs.headerMenu;e&&e.contains(s.target)||t&&t.contains(s.target)||this.closeHeaderMenu()}},Bie={handleRealtimeTerminalClick(){this.isConnected&&(this.isPolicyBlocked("block_realtime_terminal","实时终端已被管理员禁用")||this.toggleTerminalPanel())},subscribeTerminalEvents(){const s=this.socket;s&&s.emit("terminal_subscribe",{all:!0,conversation_id:this.currentConversationId||void 0})},setTerminalSessions(s){this.terminalSessions=s},setTerminalActiveSession(s){this.terminalActiveSession=s},switchTerminalSession(s){this.terminalActiveSession=s,this.socket&&this.socket.emit("get_terminal_output",{session:s,lines:0,conversation_id:this.currentConversationId||void 0})},async fetchTerminalCount(){try{const s=encodeURIComponent(this.currentConversationId||""),e=await fetch(`/api/terminals?conversation_id=${s}`);if(!e.ok)return;const t=await e.json();if(t!=null&&t.sessions){const n={};for(const c of t.sessions){const l=c.session_name||c.name||c.session||c.id;l&&(n[l]={})}this.terminalSessions=n;const r=qs().form.auto_open_terminal_panel!==!1,o=Object.keys(n).length,a=this.previousTerminalCount??0;r&&(a===0&&o>0&&!this.terminalPanelOpen?this.toggleTerminalPanel():a>0&&o===0&&this.terminalPanelOpen&&this.closeTerminalPanel()),this.previousTerminalCount=o}}catch{}}},Fie={handleCompressConversationClick(){if(!(this.compressing||this.streamingMessage||!this.isConnected)){if(this.compressionActiveForCurrentConversation){this.uiPushToast({title:"对话自动压缩中",message:"当前对话正在压缩,请稍后再试",type:"warning"});return}this.isPolicyBlocked("block_compress_conversation","压缩对话已被管理员禁用")||this.compressConversation()}},async loadReviewConversations(){if(!this.reviewListLoading){this.reviewListLoading=!0,this.reviewListOffset=0;try{const s=this.reviewListLimit,t=await(await fetch(`/api/conversations?limit=${s}&offset=0&non_empty=1`)).json().catch(()=>({}));t!=null&&t.success?(this.reviewConversations=t.data.conversations||[],this.reviewListHasMore=!!t.data.has_more,this.autoSelectReviewConversation()):(this.reviewConversations=[],this.reviewListHasMore=!1)}catch(s){console.error("加载回顾对话列表异常:",s),this.reviewConversations=[],this.reviewListHasMore=!1}finally{this.reviewListLoading=!1}}},async loadMoreReviewConversations(){if(!(this.reviewListLoadingMore||!this.reviewListHasMore)){this.reviewListLoadingMore=!0;try{const s=this.reviewListLimit,e=this.reviewListOffset+s,n=await(await fetch(`/api/conversations?limit=${s}&offset=${e}&non_empty=1`)).json().catch(()=>({}));n!=null&&n.success&&(this.reviewConversations.push(...n.data.conversations||[]),this.reviewListHasMore=!!n.data.has_more,this.reviewListOffset=e,this.autoSelectReviewConversation())}catch(s){console.error("加载更多回顾对话异常:",s)}finally{this.reviewListLoadingMore=!1}}},async handleConfirmReview(){if(!this.reviewSubmitting){if(!this.reviewSelectedConversationId){this.uiPushToast({title:"请选择对话",message:"请选择要生成回顾的对话记录",type:"info"});return}if(this.reviewSelectedConversationId===this.currentConversationId){this.uiPushToast({title:"无法引用当前对话",message:"请选择其他对话生成回顾",type:"warning"});return}if(!this.currentConversationId){this.uiPushToast({title:"无法发送",message:"当前没有活跃对话,无法自动发送提示消息",type:"warning"});return}this.reviewSubmitting=!0;try{const{path:s,char_count:e}=await this.generateConversationReview(this.reviewSelectedConversationId);if(!s)throw new Error("未获取到生成的文件路径");const t=typeof e=="number"?e:0;this.reviewGeneratedPath=s;const n=t&&t<=1e4?"建议直接完整阅读。":"建议使用 read 工具进行搜索或分段阅读。";if(this.reviewSendToModel){const i=`帮我继续这个任务,对话文件在 ${s},文件长 ${t||"未知"} 字符,${n} 请阅读文件了解后,不要直接继续工作,而是向我汇报你的理解,然后等我做出指示。`;await this.sendAutoUserMessage(i)&&(this.reviewDialogOpen=!1)}else this.uiPushToast({title:"回顾文件已生成",message:s,type:"success"})}catch(s){const e=s instanceof Error?s.message:String(s||"生成失败");this.uiPushToast({title:"生成回顾失败",message:e,type:"error"})}finally{this.reviewSubmitting=!1}}},async loadReviewPreview(s){var e;this.reviewPreviewLoading=!0,this.reviewPreviewError=null,this.reviewPreviewLines=[];try{const t=await fetch(`/api/conversations/${s}/review_preview?limit=${this.reviewPreviewLimit}`),n=await t.json().catch(()=>({}));if(!t.ok||!(n!=null&&n.success)){const i=(n==null?void 0:n.message)||(n==null?void 0:n.error)||"获取预览失败";throw new Error(i)}this.reviewPreviewLines=((e=n==null?void 0:n.data)==null?void 0:e.preview)||[]}catch(t){const n=t instanceof Error?t.message:String(t||"获取预览失败");this.reviewPreviewError=n}finally{this.reviewPreviewLoading=!1}},async generateConversationReview(s){const e=await fetch(`/api/conversations/${s}/review`,{method:"POST"}),t=await e.json().catch(()=>({}));if(!e.ok||!(t!=null&&t.success)){const i=(t==null?void 0:t.message)||(t==null?void 0:t.error)||"生成失败";throw new Error(i)}const n=t.data||t;return{path:n.path||n.file_path||n.relative_path,char_count:n.char_count??n.length??n.size??0}}},$ie={async initSocket(){this.socket=null},async checkConnectionHealth(){if(this.connectionHeartbeatInFlight){Ch("log","health-skip-inflight",{seq:this.connectionHeartbeatSeq,isConnected:!!this.isConnected,failCount:this.connectionHeartbeatFailCount});return}this.connectionHeartbeatInFlight=!0;const s=Number(this.connectionHeartbeatSeq||0)+1;this.connectionHeartbeatSeq=s;const e=`${Date.now()}-${s}`,t=Date.now(),n=gw(),i=n?"/api/health?diag=1":"/api/health",r=!!this.isConnected;let o=null;const a=typeof AbortController<"u"?new AbortController:null,c=typeof this.connectionHeartbeatRequestTimeoutMs=="number"&&this.connectionHeartbeatRequestTimeoutMs>0?this.connectionHeartbeatRequestTimeoutMs:5e3,l=a?window.setTimeout(()=>a.abort(),c):null;try{const u=await fetch(i,{method:"GET",cache:"no-store",headers:{"X-Connection-Heartbeat":e},signal:a==null?void 0:a.signal});if(o=u.status,!u.ok)throw new Error(`HTTP ${u.status}`);const h=this.connectionHeartbeatFailCount||0;this.isConnected=!0,this.connectionHeartbeatFailCount=0,this.connectionHeartbeatLastLatencyMs=Date.now()-t,this.connectionHeartbeatLastStatusCode=o,this.connectionHeartbeatLastError="",r?gw()&&(this.connectionHeartbeatLastLatencyMs>=700||s<=3||s%60===0)&&Ch("log","health-ok",{requestId:e,seq:s,elapsedMs:this.connectionHeartbeatLastLatencyMs,status:o,endpoint:i,visibility:(document==null?void 0:document.visibilityState)||"unknown"}):(this.connectionHeartbeatLastChangeAt=Date.now(),Ch("warn","health-recovered",{requestId:e,seq:s,elapsedMs:this.connectionHeartbeatLastLatencyMs,failCountBeforeRecover:h,status:o,diagEnabled:n,endpoint:i,conversationId:this.currentConversationId||null,taskInProgress:!!this.taskInProgress,streamingMessage:!!this.streamingMessage,visibility:(document==null?void 0:document.visibilityState)||"unknown",online:typeof navigator<"u"?navigator.onLine:null}))}catch(u){const h=(this.connectionHeartbeatFailCount||0)+1;this.connectionHeartbeatFailCount=h,this.connectionHeartbeatLastLatencyMs=Date.now()-t,this.connectionHeartbeatLastStatusCode=o;const d=(u==null?void 0:u.name)||"Error",p=(u==null?void 0:u.message)||String(u);this.connectionHeartbeatLastError=`${d}: ${p}`;const m=typeof this.connectionHeartbeatFailThreshold=="number"&&this.connectionHeartbeatFailThreshold>0?this.connectionHeartbeatFailThreshold:3,v=h>=m;v&&(this.isConnected=!1),r&&v&&(this.connectionHeartbeatLastChangeAt=Date.now());const g=r||h<=m||h%10===0;Ch(g?"warn":"log","health-failed",{requestId:e,seq:s,elapsedMs:this.connectionHeartbeatLastLatencyMs,failCount:h,status:o,endpoint:i,diagEnabled:n,wasConnected:r,nowConnected:!!this.isConnected,failThreshold:m,shouldDisconnect:v,errorName:d,errorMessage:p,timeout:d==="AbortError",visibility:(document==null?void 0:document.visibilityState)||"unknown",online:typeof navigator<"u"?navigator.onLine:null,conversationId:this.currentConversationId||null,taskInProgress:!!this.taskInProgress,streamingMessage:!!this.streamingMessage,hasPendingTools:typeof this.hasPendingToolActions=="function"?this.hasPendingToolActions():null},{force:g})}finally{this.connectionHeartbeatInFlight=!1,l&&clearTimeout(l)}},startConnectionHeartbeat(){if(this.connectionHeartbeatActive)return;this.connectionHeartbeatActive=!0,this.connectionHeartbeatFailCount=0,Ch("log","heartbeat-start",{connectedIntervalMs:this.connectionHeartbeatIntervalMs,disconnectedIntervalMs:this.connectionHeartbeatDisconnectedIntervalMs});const s=async()=>{if(!this.connectionHeartbeatActive||(await this.checkConnectionHealth(),!this.connectionHeartbeatActive))return;const e=typeof this.connectionHeartbeatIntervalMs=="number"&&this.connectionHeartbeatIntervalMs>0?this.connectionHeartbeatIntervalMs:8e3,t=typeof this.connectionHeartbeatDisconnectedIntervalMs=="number"&&this.connectionHeartbeatDisconnectedIntervalMs>0?this.connectionHeartbeatDisconnectedIntervalMs:1e3,n=this.isConnected?e:t;gw()&&(!this.isConnected||(this.connectionHeartbeatSeq||0)<=3)&&Ch("log","heartbeat-next",{seq:this.connectionHeartbeatSeq,isConnected:!!this.isConnected,failCount:this.connectionHeartbeatFailCount,nextInterval:n}),this.connectionHeartbeatTimer=window.setTimeout(()=>{s()},n)};s()},stopConnectionHeartbeat(){this.connectionHeartbeatActive=!1,this.connectionHeartbeatTimer&&(clearTimeout(this.connectionHeartbeatTimer),this.connectionHeartbeatTimer=null),Ch("log","heartbeat-stop",{})},async enterWorkspaceBootstrapMode(){this.versioningHostMode=!0,this.dockerProjectMode=!1,uT(!0),this.isConnected=!0;try{await this.fetchHostWorkspaces()}catch(s){console.warn("引导模式加载工作区列表失败:",s)}this.uiPushToast({title:"尚未创建工作区",message:"请点击侧边栏的「工作区」按钮创建第一个工作区",type:"info"})},async loadInitialData(){var s,e;try{Oe("加载初始数据...");const t=Qi();await t.fetchModels().catch(S=>{console.warn("加载模型列表失败,使用前端默认列表:",S)});const n=await fetch("/api/status");if(!n.ok){const S=await n.json().catch(()=>({}));if((S==null?void 0:S.code)==="no_workspace"){await this.enterWorkspaceBootstrapMode();return}throw new Error(`状态接口请求失败: ${n.status}`)}const i=await n.json();this.socket=null,this.projectPath=i.project_path||"",this.agentVersion=i.version||this.agentVersion,this.applyStatusSnapshot(i),this.fetchWorkMode(),this.fetchPermissionMode(),this.fetchExecutionMode(),this.fetchNetworkPermission(),this.fetchPendingToolApprovals(),this.fetchUsageQuota(),i&&typeof i.model_key=="string"&&(t.setModel(i.model_key),this.currentModelKey=t.currentModelKey),await No().fetchPolicy(),this.applyPolicyUiLocks();const o=qs();!o.loaded&&!o.loading&&await o.fetchPersonalization().catch(S=>{console.warn("加载个性化设置失败:",S)});const a=(s=i==null?void 0:i.conversation)==null?void 0:s.current_id,c=typeof a=="string"&&a.length>0&&!a.startsWith("temp_"),l=typeof this.isExplicitNewConversationRoute=="function"&&this.isExplicitNewConversationRoute();if(o.loaded&&!this.currentConversationId&&(!c||l)){const S=o.form.default_run_mode,C=o.form.default_model,T=o.form.default_reasoning_effort;S&&(this.runMode=S,Oe("应用默认运行模式:",S)),this.reasoningEffort=T,T&&Oe("应用默认推理强度:",T),C&&(t.setModel(C),this.currentModelKey=t.currentModelKey,Oe("应用默认模型:",C)),S==="thinking"?this.thinkingMode=!0:S==="fast"&&(this.thinkingMode=!1)}this.isConnected=!0;const u=this.focusFetchFiles();let h=null;const d=((e=i==null?void 0:i.container)==null?void 0:e.mode)==="host";this.versioningHostMode=!!d,this.dockerProjectMode=!d,uT(!!d),d?(this.fileMarkTreeUnavailable("宿主机模式下文件树不可用"),await this.fetchHostWorkspaces()):(this.fileMarkTreeUnavailable("Docker 模式下文件区已改为项目列表"),await this.fetchHostWorkspaces(),this.hostWorkspaceCreatePath="",this.hostWorkspaceCreateLabel="",this.hostWorkspaceCreateError="",this.hostWorkspaceCreateSubmitting=!1);const p=this.isExplicitNewConversationRoute(),m=await this.getRunningTaskConversationId(),g=i.conversation&&i.conversation.current_id||m,y=window.location.pathname.replace(/^\/+/,""),b=y==="multiagent/new"||y==="multiagent";if(g&&!this.currentConversationId&&!b&&!p&&!this.isConversationIndependentRoute()){this.skipConversationHistoryReload=!0,this.skipConversationLoadedEvent=!0,this.suppressTitleTyping=!0,this.titleReady=!1,this.currentConversationTitle="",this.titleTypingText="",this.currentConversationId=g;const S=this.stripConversationPrefix(g);window.location.pathname.replace(/^\/+/,"")!==S&&history.replaceState({conversationId:g},"",`/${S}`);try{const k=await(await fetch("/api/conversations/current")).json();if(k.success&&k.data)this.currentConversationTitle=k.data.title,this.titleReady=!0,this.suppressTitleTyping=!1,this.startTitleTyping(this.currentConversationTitle,{animate:!1});else{this.titleReady=!0,this.suppressTitleTyping=!1;const A=this.currentConversationTitle||"新对话";this.currentConversationTitle=A,this.startTitleTyping(A,{animate:!1})}(this.lastHistoryLoadedConversationId!==this.currentConversationId||!Array.isArray(this.messages)||this.messages.length===0)&&await this.fetchAndDisplayHistory(),this.fetchConversationTokenStatistics(),this.updateCurrentContextTokens(),await this.fetchVersioningStatus(this.currentConversationId,{silent:!0}),this.fetchPendingUserQuestions()}catch(T){console.warn("获取当前对话标题失败:",T),this.titleReady=!0,this.suppressTitleTyping=!1,this.startTitleTyping(this.currentConversationTitle||"新对话","")}}const _=this.fileFetchTodoList(),w=[u,_];await Promise.allSettled(w),await this.loadToolSettings(!0),this.conversationsOffset=0,await this.loadConversationsList(),Oe("初始数据加载完成")}catch(t){console.error("加载初始数据失败:",t),this.isConnected=!1}}},Hie={async bootstrapRoute(){var t;this.suppressTitleTyping=!0,this.titleReady=!1,this.currentConversationTitle="",this.titleTypingText="";let s=window.location.pathname.replace(/^\/+|\/+$/g,"");if(s==="multiagent/new"||s==="multiagent")history.replaceState({},"","/new"),s="new";else if(s.startsWith("multiagent/")){const n=s.slice(11),i=n.startsWith("conv_")?n.slice(5):n;history.replaceState({},"",`/${i}`),s=i}if(this.isConversationIndependentRoute()){s==="workflow"&&(history.replaceState({},"","/workflows"),s="workflows"),this.workflowDemoRoute=s,this.currentConversationId=null,this.currentConversationTitle="",this.messages=[],this.titleReady=!0,this.suppressTitleTyping=!1,this.initialRouteResolved=!0;return}if(!s||this.isExplicitNewConversationRoute()){if(this.currentConversationId=null,this.currentConversationTitle="新对话",this.logMessageState("bootstrapRoute:clear-messages-for-new"),this.messages=[],this.titleReady=!0,this.suppressTitleTyping=!1,this.startTitleTyping("新对话",{animate:!1}),this.initialRouteResolved=!0,this.refreshBlankHeroState(),!this.multiAgentIndexRebuildTriggered){this.multiAgentIndexRebuildTriggered=!0;try{await fetch("/api/multiagent/rebuild-index",{method:"POST"})}catch{}}await this.restoreComposerDraftState("bootstrap-route:new");return}const e=s.startsWith("conv_")?s:`conv_${s}`;try{const n=await this.enterConversation(e,{source:"refresh",urlMode:"replace"});n.success?(this.currentConversationTitle=n.title||"",this.titleReady=!0,this.suppressTitleTyping=!1,this.startTitleTyping(this.currentConversationTitle,{animate:!1}),this.fetchConversationTokenStatistics(),this.updateCurrentContextTokens()):(history.replaceState({},"","/new"),this.currentConversationId=null,this.currentConversationTitle="新对话",this.titleReady=!0,this.suppressTitleTyping=!1,this.startTitleTyping("新对话",{animate:!1}))}catch(n){console.warn("初始化路由失败:",n),history.replaceState({},"","/new"),this.currentConversationId=null,this.currentConversationTitle="新对话",this.titleReady=!0,this.suppressTitleTyping=!1,this.startTitleTyping("新对话",{animate:!1})}finally{this.initialRouteResolved=!0}await this.restoreComposerDraftState("bootstrap-route:conversation"),this.currentConversationId&&((t=this.fetchPendingUserQuestions)==null||t.call(this))},handlePopState(s){const t=(s.state||{}).conversationId;if(!t){this.currentConversationId=null,this.currentConversationTitle="新对话",this.logMessageState("handlePopState:clear-messages-no-conversation"),this.messages=[],this.logMessageState("handlePopState:after-clear-no-conversation"),this.resetAllStates("handlePopState:no-conversation"),this.resetTokenStatistics(),this.restoreComposerDraftState("popstate:new").catch(()=>{});return}this.loadConversation(t)},refreshCurrentPage(){typeof window>"u"||this.persistComposerDraftNow({reason:"refresh-page",force:!0,keepalive:!0}).catch(()=>{}).finally(()=>{window.location.reload()})},isExplicitNewConversationRoute(){return window.location.pathname.replace(/^\/+|\/+$/g,"")==="new"},isConversationIndependentRoute(){const s=window.location.pathname.replace(/^\/+|\/+$/g,"");return s==="workflows"||s==="workflow"||s.startsWith("workflow/")},openWorkflowsPage(){window.location.assign("/workflows")},stripConversationPrefix(s){return s?s.startsWith("conv_")?s.slice(5):s:""}},Uie={addSystemMessage(s){const e=bie(s);e&&(this.chatAddSystemMessage(e,{variant:"sub_agent_done"}),this.$forceUpdate(),this.conditionalScrollToBottom())},appendSystemAction(s){this.addSystemMessage(s)},startTitleTyping(s,e={}){this.titleTypingTimer&&(clearInterval(this.titleTypingTimer),this.titleTypingTimer=null);const t=(s||"").trim();if(!(e.animate??!0)){this.titleTypingTarget=t,this.titleTypingText=t;return}const i=(this.titleTypingText||"").trim();if(i===t){this.titleTypingTarget=t,this.titleTypingText=t;return}this.titleTypingTarget=t,this.titleTypingText=i;const r=[];for(let a=i.length;a>=0;a--)r.push(i.slice(0,a));for(let a=1;a<=t.length;a++)r.push(t.slice(0,a));let o=0;this.titleTypingTimer=window.setInterval(()=>{if(o>=r.length){clearInterval(this.titleTypingTimer),this.titleTypingTimer=null,this.titleTypingText=t;return}this.titleTypingText=r[o],o+=1},32)},isConversationBlank(){return!Array.isArray(this.messages)||!this.messages.length?!0:!this.messages.some(s=>s&&(s.role==="user"||s.role==="assistant"))},pickWelcomeText(){const s=this.blankWelcomePool;if(!Array.isArray(s)||!s.length){this.blankWelcomeText="有什么可以帮忙的?";return}const e=Math.floor(Math.random()*s.length);this.blankWelcomeText=s[e]},refreshBlankHeroState(){const s=this.isConversationBlank(),e=this.currentConversationId||"temp",t=!this.blankHeroActive||this.lastBlankConversationId!==e;s?(t&&!this.blankHeroExiting&&this.pickWelcomeText(),this.blankHeroActive=!0,this.lastBlankConversationId=e):(this.blankHeroActive=!1,this.blankHeroExiting=!1,this.lastBlankConversationId=null)},isOutputActive(){return!!(this.streamingMessage||this.taskInProgress||this.hasPendingToolActions())},logMessageState(s,e={}){const t=Array.isArray(this.messages)?this.messages.length:"N/A";Oe("[Messages]",{action:s,count:t,conversationId:this.currentConversationId,streaming:this.streamingMessage,...e})},iconStyle(s,e){const t=this.icons?this.icons[s]:null;if(!t)return{};const n={"--icon-src":`url(${t})`};return e&&(n["--icon-size"]=e),n},renderMarkdown(s,e=!1){return k2(s,e)},decodeHtmlEntities(s){const e=document.createElement("textarea");return e.innerHTML=s,e.value},async handleCopyCodeClick(s){const e=s.target;if(!e||!e.classList||!e.classList.contains("copy-code-btn")||e.classList.contains("copied"))return;const t=e.closest(".code-block-wrapper");let n=t?t.querySelector("pre code"):null;if(!n){const o=e.getAttribute("data-code");if(o){const a=`[data-code-id="${o.replace(/"/g,'\\"')}"]`;n=document.querySelector(a)}}if(!n)return;const i=n.getAttribute("data-original-code"),r=i?this.decodeHtmlEntities(i):n.textContent||"";if(r.trim())try{await navigator.clipboard.writeText(r),e.classList.add("copied"),setTimeout(()=>{e.classList.remove("copied")},5e3)}catch(o){console.warn("复制失败:",o)}},fetchTodoList(){return this.fileFetchTodoList()},fetchSubAgents(){return this.subAgentFetch()}};function s2(s,e,t){return Math.max(e,Math.min(s,t))}function Wie(s,e,t){e==="right"&&!s.terminalPanelOpen&&!s.gitChangesPanelOpen||(s.isResizing=!0,s.resizingPanel=e,s.handleResize&&document.addEventListener("mousemove",s.handleResize),s.stopResize&&document.addEventListener("mouseup",s.stopResize),document.body.style.userSelect="none",document.body.style.cursor="col-resize",t.preventDefault())}function zie(s,e){if(!s.isResizing||!s.resizingPanel)return;const t=document.querySelector(".main-container");if(!t)return;const n=t.offsetWidth,i=s.minPanelWidth??240,r=s.maxPanelWidth??480;if(s.resizingPanel==="right"){let o=n-e.clientX;o=s2(o,i,r),s.rightWidth=o}else s.resizingPanel==="conversation"&&s2(e.clientX,200,400)}function jie(s){s.isResizing=!1,s.resizingPanel=null,s.handleResize&&document.removeEventListener("mousemove",s.handleResize),s.stopResize&&document.removeEventListener("mouseup",s.stopResize),document.body.style.userSelect="",document.body.style.cursor=""}const Vie={startResize(s,e){Wie(this,s,e)},handleResize(s){zie(this,s)},stopResize(){jie(this)},startRightSplitResize(s){s.preventDefault();const e=s.target.closest(".right-panels");if(!e)return;const t=s.clientY,n=e.offsetHeight,i=this.rightSplitRatio??.5;e.classList.add("right-panels--resizing");const r=a=>{const c=a.clientY-t,l=i+c/n;this.rightSplitRatio=Math.max(.15,Math.min(.85,l))},o=()=>{document.removeEventListener("mousemove",r),document.removeEventListener("mouseup",o),document.body.style.cursor="",document.body.style.userSelect="",e.classList.remove("right-panels--resizing")};document.addEventListener("mousemove",r),document.addEventListener("mouseup",o),document.body.style.cursor="row-resize",document.body.style.userSelect="none"}},Gie={...die,..._ie,...Sie,...wie,...kie,...Cie,...Tie,...Aie,...Eie,...Rie,...Lie,...Pie,...Oie,...Die,...Nie,...Bie,...Fie,...$ie,...Hie,...Uie,...Vie},pF=(...s)=>{},gF=(...s)=>{},wl=(...s)=>{},dy=(...s)=>{},n2="[RESTORE_DEBUG]";let f1=0;const p1=800,qie=new Set(["restore:start","restore:running-task-found","restore:history-empty","restore:task-detail-events","restore:rebuild-decision","restore:rebuild-polling-started","restore:polling-started-follow","restore:thinking-chunk-auto-start","restore:text-chunk-auto-start","restore:error","event:drop-duplicate","event:drop-conversation-mismatch"]);function Kie(){var s;if(typeof window>"u")return!1;try{const e=window.__RESTORE_DEBUG__;if(e===!0||e==="1")return!0;if(e===!1||e==="0")return!1;const t=(s=window.localStorage)==null?void 0:s.getItem("restoreDebug");return t==="1"||t==="true"}catch{return!1}}function Kn(s,e={}){if(Kie()&&qie.has(s)&&!(f1>=p1)){if(f1+=1,f1===p1){console.warn(n2,"log-limit-reached",{max:p1});return}console.log(n2,s,e)}}function Qie(s){if(!s||typeof s!="object")return!1;const e=s.metadata||{};return!!(s.is_auto_generated||e.is_auto_generated||s.auto_message_type||e.auto_message_type||s.sub_agent_notice||e.sub_agent_notice||s.background_command_notice||e.background_command_notice||s.runtime_guidance||e.runtime_guidance||s.runtime_mode_notice||e.runtime_mode_notice)}function Xie(s){if(!s||typeof s!="object")return!1;const e=s.metadata||{};return!!(s.runtime_mode_notice||e.runtime_mode_notice)}function Yie(s){if(!s||typeof s!="object")return"user";const e=s.metadata||{},t=String(s.message_source||e.message_source||"").trim().toLowerCase();return t||(s.runtime_mode_notice||e.runtime_mode_notice?"notify":s.runtime_guidance||e.runtime_guidance?"guidance":s.background_command_notice||e.background_command_notice?"background_command":s.sub_agent_notice||e.sub_agent_notice?"sub_agent":"user")}function Jie(s,e,t){const i={...s&&typeof s.metadata=="object"&&s.metadata?{...s.metadata}:{},message_source:e};return s&&Object.prototype.hasOwnProperty.call(s,"visibility")&&(i.visibility=s.visibility),s&&Object.prototype.hasOwnProperty.call(s,"starts_work")&&(i.starts_work=s.starts_work),i.visibility=Oh({content:t,metadata:i,...s}),i.starts_work=kv({content:t,metadata:i,...s}),i}function b0(s){return!s||s.role!=="assistant"?!1:(Array.isArray(s.actions)?s.actions:[]).length===0&&!!s.awaitingFirstContent}function Zie(s){if(!Array.isArray(s)||s.length===0)return null;const e=s.length-1,t=s[e];if((t==null?void 0:t.role)==="user")return t;if(b0(t)&&e>0){const n=s[e-1];if((n==null?void 0:n.role)==="user")return n}return null}function i2(s,e,t=[],n=[],i=""){var o;if(!Array.isArray(s)||!e)return null;const r=String(i||"").trim().toLowerCase();for(let a=s.length-1,c=0;a>=0&&c<12;a-=1){const l=s[a];if(!l||l.role!=="user")continue;c+=1;const u=String(((o=l==null?void 0:l.metadata)==null?void 0:o.message_source)||"user").trim().toLowerCase();if(String(l.content||"").trim()===e&&JSON.stringify(l.images||[])===JSON.stringify(t||[])&&JSON.stringify(l.videos||[])===JSON.stringify(n||[])&&(!r||u===r))return l}return null}const ere={cleanupTrailingEmptyAssistantPlaceholder(s="unspecified"){if(!Array.isArray(this.messages)||!this.messages.length)return!1;const e=this.messages[this.messages.length-1];return b0(e)?(this.messages.pop(),typeof this.currentMessageIndex=="number"&&(this.currentMessageIndex=this.messages.length-1),dy("taskPolling.cleanupTrailingEmptyAssistantPlaceholder:removed",{reason:s,messagesLengthAfter:this.messages.length,currentMessageIndex:this.currentMessageIndex}),!0):!1},moveTrailingEmptyAssistantPlaceholderAfterUserInsert(s="runtime-user-insert"){if(!Array.isArray(this.messages)||!this.messages.length)return!1;const e=this.messages[this.messages.length-1];return b0(e)?(this.messages.pop(),typeof this.currentMessageIndex=="number"&&(this.currentMessageIndex=-1),dy("taskPolling.moveTrailingEmptyAssistantPlaceholderAfterUserInsert:removed-before-insert",{reason:s,messagesLengthAfterRemove:this.messages.length}),!0):!1},ensureRunningAssistantPlaceholder(s=null,e="restore-running-task"){var o;if(!Array.isArray(this.messages)||this.messages.length===0)return!1;const t=this.messages[this.messages.length-1],n=Array.isArray(t==null?void 0:t.actions)?t.actions:[];if((t==null?void 0:t.role)==="assistant"&&n.length===0&&!!t.awaitingFirstContent)return this.taskInProgress=!0,this.streamingMessage=!0,this.stopRequested=!1,!1;if((t==null?void 0:t.role)==="assistant"&&n.length>0||(t==null?void 0:t.role)!=="user")return!1;const r=typeof(s==null?void 0:s.created_at)=="number"?new Date(s.created_at*1e3).toISOString():new Date().toISOString();return t.metadata={...t.metadata||{},work_timer:((o=t.metadata)==null?void 0:o.work_timer)||{status:"working",started_at:r}},this.taskInProgress=!0,this.stopRequested=!1,this.streamingMessage=!0,this.chatStartAssistantMessage(),typeof this.monitorShowPendingReply=="function"&&this.monitorShowPendingReply(),this.$forceUpdate(),this.$nextTick(()=>{var a;(a=this.conditionalScrollToBottom)==null||a.call(this)}),Oe("[TaskPolling] 已恢复等待首包占位",{reason:e,conversationId:this.currentConversationId,taskId:(s==null?void 0:s.task_id)||null}),!0},markLatestUserWorkCompleted(){if(!(!Array.isArray(this.messages)||this.messages.length===0))for(let s=this.messages.length-1;s>=0;s-=1){const e=this.messages[s];if(!e||e.role!=="user")continue;e.metadata=e.metadata||{};const t=e.metadata.work_timer;if(!t||typeof t!="object")continue;if(t.status==="completed"&&typeof t.duration_ms=="number")return;const n=new Date().toISOString(),i=t.started_at||e.timestamp||n,r=Date.parse(i),o=Date.now(),a=Number.isFinite(r)?Math.max(0,o-r):0;t.status="completed",t.started_at=i,t.finished_at=n,t.duration_ms=a;return}},isPlaceholderConversationTitle(s){const e=String(s||"").trim();return!e||e==="新对话"}},eS=(...s)=>{},r2=(...s)=>{},tS=(...s)=>{},tre="[CONN_DIAG]",o2=2e3,sre=()=>{var s;if(typeof window>"u")return!1;try{const e=window;if(e.__CONN_DIAG__===!0||e.__CONN_DIAG__==="1")return!0;const t=(s=window.localStorage)==null?void 0:s.getItem("connDiag");return t==="1"||t==="true"}catch{return!1}},kl=(s,e={})=>{const n={ts:new Date().toISOString(),event:s,...e};try{if(typeof window<"u"){const i=window;Array.isArray(i.__CONN_DIAG_LOGS__)||(i.__CONN_DIAG_LOGS__=[]),i.__CONN_DIAG_LOGS__.push(n),i.__CONN_DIAG_LOGS__.length>o2&&i.__CONN_DIAG_LOGS__.splice(0,i.__CONN_DIAG_LOGS__.length-o2)}}catch{}sre()&&console.log(tre,s,n)},_M=dn("task",{state:()=>({currentTaskId:null,lastEventIndex:0,pollingInterval:null,taskStatus:"idle",isPolling:!1,pollingError:null,pollingErrorCount:0,pollingInFlight:!1,pollingSeq:0,pollingWarned:!1,pollingRequestTimeoutMs:12e3,pollingFailThreshold:8,pollingIntervalMs:250,taskCreatedAt:null,taskUpdatedAt:null,runtimeQueueSnapshotKey:""}),getters:{hasActiveTask:s=>s.currentTaskId!==null&&s.taskStatus==="running",isTaskCompleted:s=>["succeeded","failed","canceled","stopped"].includes(s.taskStatus)},actions:{async createTask(s,e=[],t=[],n=null,i={}){try{Oe("[Task] 创建任务:",{message:s,conversationId:n});const r=await fetch("/api/tasks",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:s,images:e,videos:t,conversation_id:n,model_key:i.model_key??void 0,run_mode:i.run_mode??void 0,thinking_mode:typeof i.thinking_mode=="boolean"?i.thinking_mode:void 0,message_source:i.message_source??void 0,goal_mode:i.goal_mode===!0?!0:void 0,skill_refs:Array.isArray(i.skill_refs)?i.skill_refs:void 0,files:Array.isArray(i.files)&&i.files.length?i.files:void 0})});if(!r.ok){const a=await r.json();throw new Error(a.error||"创建任务失败")}const o=await r.json();if(!o.success)throw new Error(o.error||"创建任务失败");return this.currentTaskId=o.data.task_id,this.taskStatus=o.data.status,this.lastEventIndex=0,this.taskCreatedAt=o.data.created_at,this.runtimeQueueSnapshotKey="",this.pollingError=null,this.pollingErrorCount=0,this.pollingWarned=!1,Oe("[Task] 任务创建成功:",o.data.task_id),kl("task-created",{taskId:o.data.task_id,conversationId:n}),this.startPolling(i.eventHandler),o.data}catch(r){throw kl("task-create-failed",{error:(r==null?void 0:r.message)||String(r),conversationId:n}),r}},async pollTaskEvents(s){var r;if(!this.currentTaskId){this.stopPolling("no-active-task");return}if(this.pollingInFlight)return;this.pollingInFlight=!0;const e=this.currentTaskId,t=this.lastEventIndex,n=`${Date.now()}-${++this.pollingSeq}`,i=Date.now();try{const o=await fetch(`/api/tasks/${e}?from=${t}`,{signal:AbortSignal.timeout(this.pollingRequestTimeoutMs),headers:{"X-Task-Poll":n}});if(!o.ok)throw new Error(`HTTP ${o.status}`);const a=await o.json();if(!a.success)throw new Error(a.error||"轮询任务失败");const c=a.data;if(this.currentTaskId!==e){kl("task-poll-stale-response-ignored",{requestId:n,responseTaskId:(c==null?void 0:c.task_id)||e,activeTaskId:this.currentTaskId,from:t});return}const l=Array.isArray(c==null?void 0:c.events)?c.events.length:0;tS("taskStore.poll:response",{taskId:e,from:t,status:c==null?void 0:c.status,nextOffset:c==null?void 0:c.next_offset,eventsCount:l}),(l>0||this.pollingErrorCount>0||(c==null?void 0:c.status)!=="running"||t===0)&&kl("task-poll-ok",{requestId:n,taskId:e,from:t,nextOffset:c==null?void 0:c.next_offset,status:c==null?void 0:c.status,eventsCount:l,elapsedMs:Date.now()-i}),yn("taskStore.poll:status",{taskId:e,from:t,status:c.status,isTaskCompleted:this.isTaskCompleted}),this.taskStatus=c.status,this.taskUpdatedAt=c.updated_at;const u=Array.isArray(c==null?void 0:c.runtime_queued_messages)?c.runtime_queued_messages:[],h=JSON.stringify(u.map(m=>[String((m==null?void 0:m.id)||""),String((m==null?void 0:m.text)||"")]));if(h!==this.runtimeQueueSnapshotKey){this.runtimeQueueSnapshotKey=h;try{s({type:"runtime_queue_sync",data:{task_id:(c==null?void 0:c.task_id)||this.currentTaskId,conversation_id:(c==null?void 0:c.conversation_id)||null,messages:u}})}catch(m){console.warn("[Task] 处理 runtime_queue_sync 失败:",m)}}let d=!1,p=!1;if(c.events&&c.events.length>0){Oe(`[Task] 收到 ${c.events.length} 个新事件`);for(const v of c.events){if(this.currentTaskId!==e){kl("task-poll-stale-event-loop-abort",{requestId:n,responseTaskId:(c==null?void 0:c.task_id)||e,activeTaskId:this.currentTaskId});return}((v==null?void 0:v.type)==="task_complete"||(v==null?void 0:v.type)==="task_stopped"||(v==null?void 0:v.type)==="error")&&tS("taskStore.poll:event",{idx:v==null?void 0:v.idx,type:v==null?void 0:v.type,data:v==null?void 0:v.data}),(v==null?void 0:v.type)==="task_complete"&&(d=!0),(v==null?void 0:v.type)==="task_stopped"&&(p=!0);try{s(v)}catch(g){console.error("[Task] 处理事件失败:",g,v)}}const m=c.events.filter(v=>["user_message","sub_agent_waiting","task_complete","task_stopped","error"].includes(v==null?void 0:v.type));m.length>0&&r2("[DEBUG_NOTIFY_KEY][task] events",{taskId:this.currentTaskId,from:this.lastEventIndex,nextOffset:c.next_offset,count:m.length,items:m.map(v=>{var g,y,b,_;return{idx:v==null?void 0:v.idx,type:v==null?void 0:v.type,sub_agent_notice:!!((g=v==null?void 0:v.data)!=null&&g.sub_agent_notice),has_running_sub_agents:(y=v==null?void 0:v.data)==null?void 0:y.has_running_sub_agents,has_running_background_commands:(b=v==null?void 0:v.data)==null?void 0:b.has_running_background_commands,task_id:(_=v==null?void 0:v.data)==null?void 0:_.task_id}})}),this.lastEventIndex=c.next_offset}if(c.status==="canceled"&&!p){Oe("[Task] 状态已取消但未收到 task_stopped补发本地事件"),tS("taskStore.poll:emit-synthetic-task-stopped",{taskId:c.task_id||this.currentTaskId,conversation_id:c.conversation_id||null});try{s({type:"task_stopped",data:{task_id:c.task_id||this.currentTaskId,conversation_id:c.conversation_id||null,synthetic:!0}})}catch(m){console.error("[Task] 处理补发 task_stopped 失败:",m)}}if(c.status==="succeeded"&&!d){Oe("[Task] 状态已成功但未收到 task_complete补发本地事件"),tS("taskStore.poll:emit-synthetic-task-complete",{taskId:c.task_id||this.currentTaskId,conversation_id:c.conversation_id||null});try{s({type:"task_complete",data:{task_id:c.task_id||this.currentTaskId,conversation_id:c.conversation_id||null,synthetic:!0,has_running_sub_agents:!1,has_running_background_commands:!1}})}catch(m){console.error("[Task] 处理补发 task_complete 失败:",m)}}this.isTaskCompleted&&(Oe("[Task] 任务已完成,停止轮询:",this.taskStatus),this.stopPolling(`task-${this.taskStatus}`)),this.pollingError=null,this.pollingErrorCount=0,this.pollingWarned=!1}catch(o){this.pollingErrorCount++,this.pollingError=o.message;const a=(o==null?void 0:o.message)||String(o),c=/timeout|timed out|abort|aborted/i.test(a);if(console.error("[Task] 轮询失败:",o),kl("task-poll-failed",{requestId:n,taskId:e,from:t,elapsedMs:Date.now()-i,error:a,isTimeoutLike:c,pollingErrorCount:this.pollingErrorCount}),eS("[DEBUG_NOTIFY][task] pollTaskEvents:error",{taskId:this.currentTaskId,from:this.lastEventIndex,error:(o==null?void 0:o.message)||String(o),pollingErrorCount:this.pollingErrorCount}),/HTTP 404|HTTP 410/.test(a)){this.stopPolling("task-not-found");return}this.pollingErrorCount>=this.pollingFailThreshold&&!this.pollingWarned&&(this.pollingWarned=!0,(r=window.__vueApp)!=null&&r.uiPushToast&&window.__vueApp.uiPushToast({title:"轮询波动",message:"消息更新暂时不稳定,正在自动重试",type:"warning",duration:5e3}))}finally{this.pollingInFlight=!1}},startPolling(s){if(this.isPolling){yn("taskStore.startPolling_already_running",{taskId:this.currentTaskId,lastEventIndex:this.lastEventIndex}),eS("[DEBUG_NOTIFY][task] startPolling:already-running",{taskId:this.currentTaskId,lastEventIndex:this.lastEventIndex});return}if(!this.currentTaskId){yn("taskStore.startPolling_no_task_id");return}Oe("[Task] 启动轮询:",this.currentTaskId),yn("taskStore.startPolling",{taskId:this.currentTaskId,lastEventIndex:this.lastEventIndex,hasHandler:!!(s||window.__taskEventHandler)}),eS("[DEBUG_NOTIFY][task] startPolling",{taskId:this.currentTaskId,lastEventIndex:this.lastEventIndex}),this.isPolling=!0,this.pollingError=null,this.pollingErrorCount=0,this.pollingWarned=!1;const e=s||window.__taskEventHandler;if(!e){console.error("[Task] 没有事件处理器,无法启动轮询"),kl("task-poll-start-failed-no-handler",{taskId:this.currentTaskId}),this.isPolling=!1;return}kl("task-poll-start",{taskId:this.currentTaskId,from:this.lastEventIndex,intervalMs:this.pollingIntervalMs,timeoutMs:this.pollingRequestTimeoutMs}),this.pollTaskEvents(e),this.pollingInterval=window.setInterval(()=>{this.pollTaskEvents(e)},this.pollingIntervalMs)},resumeTask(s,e={}){if(!s){yn("taskStore.resumeTask_no_task_id");return}yn("taskStore.resumeTask",{incomingTaskId:s,currentTaskId:this.currentTaskId,isPolling:this.isPolling,resetOffset:(e==null?void 0:e.resetOffset)!==!1}),eS("[DEBUG_NOTIFY][task] resumeTask",{incomingTaskId:s,currentTaskId:this.currentTaskId,options:e}),r2("[DEBUG_NOTIFY_KEY][task] resumeTask",{incomingTaskId:s,currentTaskId:this.currentTaskId,resetOffset:(e==null?void 0:e.resetOffset)!==!1});const t=!!this.currentTaskId&&this.currentTaskId===s,n=this.isPolling;this.currentTaskId&&this.currentTaskId!==s&&this.stopPolling(),this.currentTaskId=s,this.taskStatus=e.status||"running",e.resetOffset!==!1&&!(t&&n)?this.lastEventIndex=0:e.resetOffset!==!1&&yn("taskStore.resumeTask_resetOffset_skipped",{taskId:s,reason:"same-task-polling-active",lastEventIndex:this.lastEventIndex}),this.pollingError=null,this.runtimeQueueSnapshotKey="",this.startPolling(e.eventHandler),yn("taskStore.resumeTask_started",{taskId:s,isPolling:this.isPolling,lastEventIndex:this.lastEventIndex})},stopPolling(s="manual"){kl("task-poll-stop",{reason:s,taskId:this.currentTaskId,status:this.taskStatus,from:this.lastEventIndex,pollingErrorCount:this.pollingErrorCount}),this.pollingInterval&&(clearInterval(this.pollingInterval),this.pollingInterval=null),this.isPolling=!1,this.pollingInFlight=!1,this.pollingWarned=!1,this.runtimeQueueSnapshotKey="",yn("taskStore.stopPolling",{reason:s,taskStatus:this.taskStatus,currentTaskId:this.currentTaskId}),this.currentTaskId=null},async cancelTask(){if(this.currentTaskId)try{Oe("[Task] 取消任务:",this.currentTaskId);const s=await fetch(`/api/tasks/${this.currentTaskId}/cancel`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!s.ok)throw new Error("取消任务失败");const e=await s.json();if(!e.success)throw new Error(e.error||"取消任务失败");Oe("[Task] 已发送取消请求,等待后端停止确认")}catch(s){throw console.error("[Task] 取消任务失败:",s),s}},async loadRunningTask(s=null){try{Oe("[Task] 查找运行中的任务"),yn("taskStore.loadRunningTask_start",{conversationId:s});const e=await fetch("/api/tasks");if(!e.ok)throw new Error("获取任务列表失败");const t=await e.json();if(!t.success)throw new Error(t.error||"获取任务列表失败");const n=new Set(["pending","running","cancel_requested"]),i=t.data.find(r=>n.has(String(r.status||""))&&(!s||r.conversation_id===s));if(i){Oe("[Task] 发现运行中的任务:",i.task_id),yn("taskStore.loadRunningTask_found",{taskId:i.task_id,status:i.status,conversationId:i.conversation_id}),this.currentTaskId=i.task_id,this.taskStatus=i.status,this.taskCreatedAt=i.created_at,this.taskUpdatedAt=i.updated_at,this.pollingError=null,this.pollingErrorCount=0,this.pollingWarned=!1,this.runtimeQueueSnapshotKey="";try{const r=await fetch(`/api/tasks/${i.task_id}`);if(r.ok){const o=await r.json();o.success&&o.data.events?(this.lastEventIndex=o.data.next_offset||o.data.events.length,Oe("[Task] 设置起始偏移量:",this.lastEventIndex)):this.lastEventIndex=0}else this.lastEventIndex=0}catch(r){console.warn("[Task] 获取任务详情失败,从头开始:",r),this.lastEventIndex=0}return i}return Oe("[Task] 没有运行中的任务"),yn("taskStore.loadRunningTask_not_found",{conversationId:s}),null}catch(e){return console.error("[Task] 加载运行中任务失败:",e),yn("taskStore.loadRunningTask_error",{conversationId:s,error:String(e)}),null}},clearTask(){this.stopPolling(),this.currentTaskId=null,this.lastEventIndex=0,this.taskStatus="idle",this.pollingError=null,this.pollingErrorCount=0,this.pollingWarned=!1,this.taskCreatedAt=null,this.taskUpdatedAt=null,this.runtimeQueueSnapshotKey=""},resetForNewConversation(){this.stopPolling(),this.currentTaskId=null,this.lastEventIndex=0,this.taskStatus="idle",this.pollingError=null,this.pollingErrorCount=0,this.pollingWarned=!1,this.runtimeQueueSnapshotKey=""}}}),so=Object.freeze(Object.defineProperty({__proto__:null,useTaskStore:_M},Symbol.toStringTag,{value:"Module"})),nre={scheduleTodoListRefresh(s=120){const e=Number.isFinite(s)?Math.max(0,Number(s)):120;this._todoRefreshTimer&&(clearTimeout(this._todoRefreshTimer),this._todoRefreshTimer=null),this._todoRefreshTimer=setTimeout(()=>{this._todoRefreshTimer=null,typeof this.fetchTodoList=="function"&&Promise.resolve(this.fetchTodoList()).catch(()=>{})},e)},startRunningStateReconcile(){this.runningStateReconcileTimer||(this._runningStateIdleStreak=0,this.runningStateReconcileTimer=setInterval(()=>{this.reconcileRunningStateOnce()},2500),this.reconcileRunningStateOnce())},stopRunningStateReconcile(){this.runningStateReconcileTimer&&(clearInterval(this.runningStateReconcileTimer),this.runningStateReconcileTimer=null),this._runningStateIdleStreak=0},async reconcileRunningStateOnce(){const s=this.currentConversationId;if(!s)return;let e=null;try{const i=(this.versioningHostMode||this.dockerProjectMode)&&this.currentHostWorkspaceId?`?workspace_id=${encodeURIComponent(this.currentHostWorkspaceId)}`:"",r=await fetch(`/api/conversations/${encodeURIComponent(s)}/running-status${i}`);if(!r.ok)return;const o=await r.json().catch(()=>({}));if(!(o!=null&&o.success)||!(o!=null&&o.data))return;e=o.data}catch{return}if(this.currentConversationId!==s)return;const t=_M();if(e.is_truly_active){this._runningStateIdleStreak=0;const i=!!e.main_task_id&&t.currentTaskId===e.main_task_id&&t.isPolling;e.is_main_running&&e.main_task_id&&!i?(pF("[DEBUG_NOTIFY][ui] reconcile:resume-main-task",{taskId:e.main_task_id,conversationId:s}),typeof this.clearProcessedEvents=="function"&&this.clearProcessedEvents(),t.resumeTask(e.main_task_id,{status:"running",resetOffset:!0,eventHandler:r=>this.handleTaskEvent(r)}),this.taskInProgress=!0):e.is_main_running&&i&&(this.taskInProgress=!0),e.has_running_sub_agents&&(this.waitingForSubAgent=!0,this.taskInProgress=!0),e.has_running_background_commands&&(this.waitingForBackgroundCommand=!0,this.taskInProgress=!0),e.has_running_multi_agent&&(this.taskInProgress=!0);return}if(!(this.streamingMessage||this.taskInProgress||this.waitingForSubAgent||this.waitingForBackgroundCommand)&&!t.hasActiveTask){this._runningStateIdleStreak=0;return}t.isPolling||(this._runningStateIdleStreak=(this._runningStateIdleStreak||0)+1,!(this._runningStateIdleStreak<2)&&(this._runningStateIdleStreak=0,Oe("[TaskPolling] 对账清理:服务端确认对话已空闲,清除本地卡住的运行状态",{conversationId:s,streamingMessage:this.streamingMessage,taskInProgress:this.taskInProgress,waitingForSubAgent:this.waitingForSubAgent,waitingForBackgroundCommand:this.waitingForBackgroundCommand,taskStatus:t.taskStatus}),this.streamingMessage=!1,this.taskInProgress=!1,this.stopRequested=!1,this.waitingForSubAgent=!1,this.waitingForBackgroundCommand=!1,typeof this.clearPendingTools=="function"&&this.clearPendingTools("reconcile_auto_clear"),this.clearTaskState(),this.$forceUpdate()))},stopWaitingTaskProbe(){},startWaitingTaskProbe(){this.startRunningStateReconcile()},stopMultiAgentTaskProbe(){},startMultiAgentTaskProbe(){this.startRunningStateReconcile()},async restoreSubAgentWaitingState(s=0){if(!this.currentConversationId){s<5&&setTimeout(()=>{this.restoreSubAgentWaitingState(s+1)},300);return}this.startRunningStateReconcile()},clearProcessedEvents(){this._processedEventIndices&&this._processedEventIndices.clear()}},ire={handleAiMessageStart(s,e){const t=this.messages[this.messages.length-1];this.waitingForSubAgent&&(this.waitingForSubAgent=!1);const n=t&&t.role==="assistant",i=Array.isArray(t==null?void 0:t.actions)?t.actions:[],r=i.some(l=>{if(!l)return!1;if(l.streaming)return!0;if(l.type==="tool"&&l.tool){const u=String(l.tool.status||"").toLowerCase();return["preparing","running","pending","queued","awaiting_approval","awaiting_user_answer"].includes(u)}return!1}),o=!i.length,a=n&&(o||r||t.awaitingFirstContent===!0)&&(this.taskInProgress||this.streamingMessage);if(dy("taskPolling.handleAiMessageStart:decision",{eventIdx:e,hasAssistantMessage:n,hasNoActionsYet:o,hasUnfinishedAction:r,awaitingFirstContent:!!(t!=null&&t.awaitingFirstContent),taskInProgress:this.taskInProgress,streamingMessage:this.streamingMessage,isRefreshRestore:a}),a){this.taskInProgress=!0,this.stopRequested=!1,this.streamingMessage=!0;const l=t.actions&&t.actions.length>0;this._rebuildingFromScratch||(l?(t.awaitingFirstContent=!1,t.generatingLabel=""):(t.awaitingFirstContent=!0,t.generatingLabel=t.generatingLabel||"思考中..."));return}this.monitorResetSpeech(),this.cleanupStaleToolActions(),this.taskInProgress=!0,this.chatStartAssistantMessage(),this.stopRequested=!1,this.streamingMessage=!0;const c=this.messages[this.messages.length-1];this._rebuildingFromScratch&&c&&c.role==="assistant"&&(c.awaitingFirstContent=!1,c.generatingLabel=""),this.$forceUpdate(),this.$nextTick(()=>{this.conditionalScrollToBottom()})},handleThinkingStart(s,e){if(this.runMode==="fast"||this.thinkingMode===!1){this.monitorEndModelOutput();return}const n=this.messages[this.messages.length-1];(!n||n.role!=="assistant")&&this.chatStartAssistantMessage(),this.monitorShowThinking();const i=this.chatStartThinkingAction();if(i&&i.blockId){const r=i.blockId,o=this.messages[this.messages.length-1];o&&o.role==="assistant"&&(o.awaitingFirstContent=!1,o.generatingLabel=""),this._rebuildingFromScratch||this.chatExpandBlock(r),this.conditionalScrollToBottom(),this.chatSetThinkingLock(r,!0),o&&o.actions&&(o.actions=[...o.actions]),this.$forceUpdate()}},handleThinkingChunk(s){if(this.runMode==="fast"||this.thinkingMode===!1)return;let e=this.chatAppendThinkingChunk(s.content);if(!e&&(s!=null&&s.content)){const t=this.chatStartThinkingAction();e=this.chatAppendThinkingChunk(s.content),Kn("restore:thinking-chunk-auto-start",{startedBlockId:(t==null?void 0:t.blockId)||null,contentLength:String(s.content||"").length,currentConversationId:this.currentConversationId})}e&&(this.$forceUpdate(),this.$nextTick(()=>{e&&e.blockId&&this.scrollThinkingToBottom(e.blockId),this.conditionalScrollToBottom()})),this.monitorShowThinking()},handleThinkingEnd(s){if(this.runMode==="fast"||this.thinkingMode===!1)return;const e=this.chatCompleteThinkingAction(s.full_content);e&&(this.chatSetThinkingLock(e,!1),this._rebuildingFromScratch?this.chatCollapseBlock(e):setTimeout(()=>{this.chatCollapseBlock(e),this.$forceUpdate()},1e3),this.$nextTick(()=>this.scrollThinkingToBottom(e))),this.$forceUpdate(),this.monitorEndModelOutput()},handleTextStart(){const s=this.messages[this.messages.length-1];(!s||s.role!=="assistant")&&this.chatStartAssistantMessage(),this.chatStartTextAction();const e=this.messages[this.messages.length-1];e&&e.role==="assistant"&&(e.awaitingFirstContent=!1,e.generatingLabel=""),this.$forceUpdate()},handleTextChunk(s){if(s&&typeof s.content=="string"&&s.content.length){let e=this.chatAppendTextChunk(s.content);e||(this.chatStartTextAction(),e=this.chatAppendTextChunk(s.content),Kn("restore:text-chunk-auto-start",{contentLength:s.content.length,appendedAfterStart:!!e,currentConversationId:this.currentConversationId})),this.$forceUpdate(),this.conditionalScrollToBottom();const t=s.content.replace(/\r/g,"");t&&this.monitorShowSpeech(t)}},handleTextEnd(s){const e=(s==null?void 0:s.full_content)||"";this.chatCompleteTextAction(e),this.$forceUpdate(),this.monitorEndModelOutput()}},rre={handleToolPreparing(s){var i;if(Oe("[TaskPolling] 工具准备中:",s.name),this.dropToolEvents)return;const e=this.chatEnsureAssistantMessage();if(!e)return;e.awaitingFirstContent&&(e.awaitingFirstContent=!1,e.generatingLabel="");let t=null;if(s.id&&this.preparingTools.has(s.id)?t=this.preparingTools.get(s.id):s.id&&(t=this.toolFindAction(s.id,s.preparing_id,s.execution_id)),t){String(((i=t.tool)==null?void 0:i.status)||"").toLowerCase()==="preparing"&&(t.tool.message=s.message||t.tool.message,s.intent&&(t.tool.intent_full=s.intent,t.tool.intent_rendered=s.intent),this.$forceUpdate());return}const n={id:s.id,type:"tool",tool:{id:s.id,name:s.name,arguments:{},argumentSnapshot:null,argumentLabel:"",status:"preparing",result:null,message:s.message||`准备调用 ${s.name}...`,intent_full:s.intent||"",intent_rendered:s.intent||""},timestamp:Date.now()};e.actions.push(n),this.preparingTools.set(s.id,n),this.toolRegisterAction(n,s.id),this.toolTrackAction(s.name,n),this.$forceUpdate(),this.conditionalScrollToBottom(),this.monitorPreviewTool&&this.monitorPreviewTool(s)},handleToolStart(s){if(Oe("[TaskPolling] 工具开始:",s.name),this.dropToolEvents)return;const e=this.chatEnsureAssistantMessage();e&&e.awaitingFirstContent&&(e.awaitingFirstContent=!1,e.generatingLabel="");let t=null;if(s.preparing_id&&this.preparingTools.has(s.preparing_id)?(t=this.preparingTools.get(s.preparing_id),this.preparingTools.delete(s.preparing_id)):t=this.toolFindAction(s.id,s.preparing_id,s.execution_id),!t){const n=this.chatEnsureAssistantMessage();if(!n)return;t={id:s.id,type:"tool",tool:{id:s.id,name:s.name,arguments:{},argumentSnapshot:null,argumentLabel:"",status:"running",result:null},timestamp:Date.now()},n.actions.push(t)}t.tool.status="running",t.tool.arguments=s.arguments,t.tool.argumentSnapshot=this.cloneToolArguments(s.arguments),t.tool.argumentLabel=this.buildToolLabel(t.tool.argumentSnapshot),t.tool.message=null,t.tool.id=s.id,t.tool.executionId=s.id,this.toolRegisterAction(t,s.id),this.toolTrackAction(s.name,t),this.$forceUpdate(),this.conditionalScrollToBottom(),this.monitorQueueTool&&this.monitorQueueTool(s)},handleToolIntent(s){if(Oe("[TaskPolling] 工具意图:",s.name,s.intent),this.dropToolEvents)return;const e=this.toolFindAction(s.id,s.preparing_id,s.execution_id);if(e&&e.tool){const t=s.intent||"";if(e.tool.intent_full===t)return;if(e.tool._intentTyping&&(e.tool._intentTyping=!1,e.tool._intentTimer&&(clearTimeout(e.tool._intentTimer),e.tool._intentTimer=null)),e.tool.intent_full=t,this._rebuildingFromScratch)e.tool.intent_rendered=t;else{e.tool.intent_rendered="",e.tool._intentTyping=!0;const r=Math.max(500,Math.min(1e3,t.length*50))/t.length;let o=0;const a=()=>{o<t.length&&e.tool._intentTyping?(e.tool.intent_rendered+=t[o],o++,this.$forceUpdate(),e.tool._intentTimer=setTimeout(a,r)):(e.tool._intentTyping=!1,e.tool.intent_rendered=t,e.tool._intentTimer=null,this.$forceUpdate())};e.tool._intentTimer=setTimeout(a,50)}e.tool.arguments&&(e.tool.arguments.intent=t,e.tool.argumentSnapshot=this.cloneToolArguments(e.tool.arguments),e.tool.argumentLabel=this.buildToolLabel(e.tool.argumentSnapshot)),this.$forceUpdate(),Oe("[TaskPolling] 已更新工具意图:",s.name)}else Oe("[TaskPolling] 未找到对应的工具 action:",s.id)},handleToolUpdateAction(s){var t,n;if(this.dropToolEvents)return;Oe("[TaskPolling] 更新action:",s.id,"status:",s.status);let e=this.toolFindAction(s.id,s.preparing_id,s.execution_id);if(!e&&s.preparing_id&&this.preparingTools.has(s.preparing_id)&&(e=this.preparingTools.get(s.preparing_id)),!!e){if(s.status&&(e.tool.status=s.status,new Set(["completed","failed","timeout","terminated","cancelled","canceled"]).has(String(s.status))&&((t=this.refreshProjectGitSummary)==null||t.call(this),this.fetchTerminalCount())),s.result!==void 0&&(e.tool.result=s.result,e.tool&&e.tool.name==="manage_personalization")){let i=s.result;if(typeof i=="string")try{i=JSON.parse(i)}catch{}if((i==null?void 0:i.theme_changed)===!0&&i.new_theme){const r=i.new_theme;typeof window<"u"&&window.localStorage&&window.localStorage.setItem("agents_ui_theme",r),document.documentElement.setAttribute("data-theme",r),document.body.setAttribute("data-theme",r)}(async()=>{try{const{usePersonalizationStore:r}=await wt(async()=>{const{usePersonalizationStore:a}=await Promise.resolve().then(()=>C$);return{usePersonalizationStore:a}},void 0);await r().fetchPersonalization()}catch{}})()}if(s.message!==void 0&&(e.tool.message=s.message),s.content!==void 0&&(e.tool.content=s.content),s.status==="completed"){const i=String(((n=e==null?void 0:e.tool)==null?void 0:n.name)||"").toLowerCase();(i.startsWith("todo_")||i==="todo_create"||i==="todo_update_task")&&this.scheduleTodoListRefresh(80)}this.$forceUpdate(),this.conditionalScrollToBottom(),this.monitorResolveTool&&s.status==="completed"&&this.monitorResolveTool(s)}},handleToolApprovalRequired(s){const e=s==null?void 0:s.approval;if(!e||!e.approval_id)return;Array.isArray(this.pendingToolApprovals)||(this.pendingToolApprovals=[]);const t=this.pendingToolApprovals.findIndex(i=>i&&i.approval_id===e.approval_id);t>=0?this.pendingToolApprovals.splice(t,1,e):this.pendingToolApprovals.push(e),this.approvalAutoCloseTimer&&(clearTimeout(this.approvalAutoCloseTimer),this.approvalAutoCloseTimer=null),(this.autoApprovalFeedLines||[]).length===0&&(this.autoApprovalFinalMessage=""),this.currentPermissionMode==="auto_approval"&&qs().form.hide_tool_approval_panel!==!1||(this.rightCollapsed=!1,this.rightWidth<this.minPanelWidth&&(this.rightWidth=this.minPanelWidth),this.isMobileViewport&&this.activeMobileOverlay!=="approval"&&this.openMobileOverlay("approval")),this.$forceUpdate()},handleUserQuestionsRequired(s){const t=(Array.isArray(s==null?void 0:s.questions)?s.questions:s!=null&&s.question?[s.question]:[]).filter(n=>n&&n.question_id);t.length&&(Array.isArray(this.pendingUserQuestions)||(this.pendingUserQuestions=[]),t.forEach(n=>{const i=this.pendingUserQuestions.findIndex(r=>r&&r.question_id===n.question_id);i>=0?this.pendingUserQuestions.splice(i,1,n):this.pendingUserQuestions.push(n)}),this.pendingUserQuestions.sort((n,i)=>{const r=String((n==null?void 0:n.batch_id)||""),o=String((i==null?void 0:i.batch_id)||"");return r&&o&&r!==o?Number((n==null?void 0:n.created_at)||0)-Number((i==null?void 0:i.created_at)||0):Number((n==null?void 0:n.batch_index)||0)-Number((i==null?void 0:i.batch_index)||0)}),this.userQuestionActiveIndex=Math.min(Math.max(0,Number(this.userQuestionActiveIndex||0)),Math.max(0,this.pendingUserQuestions.length-1)),this.userQuestionDialogVisible=!0,this.userQuestionMinimized=!1,this.notifyUserQuestion(t[0]),this.$forceUpdate())},handleUserQuestionsResolved(s){const e=Array.isArray(s==null?void 0:s.question_ids)?s.question_ids.map(t=>String(t||"")).filter(Boolean):s!=null&&s.question_id?[String(s.question_id)]:[];!e.length||!Array.isArray(this.pendingUserQuestions)||(this.pendingUserQuestions=this.pendingUserQuestions.filter(t=>t&&!e.includes(String(t.question_id||""))),this.pendingUserQuestions.length?this.userQuestionActiveIndex=Math.min(this.userQuestionActiveIndex,this.pendingUserQuestions.length-1):(this.userQuestionDialogVisible=!1,this.userQuestionMinimized=!1,this.userQuestionActiveIndex=0,this.restoreUserQuestionTitle()),this.$forceUpdate())},handlePlanApprovalRequired(s){const e=s==null?void 0:s.approval;if(!e||!e.approval_id)return;Array.isArray(this.pendingPlanApprovals)||(this.pendingPlanApprovals=[]);const t=this.pendingPlanApprovals.findIndex(n=>n&&n.approval_id===e.approval_id);t>=0?this.pendingPlanApprovals.splice(t,1,e):this.pendingPlanApprovals.push(e),this.pendingPlanApprovals.sort((n,i)=>Number((n==null?void 0:n.created_at)||0)-Number((i==null?void 0:i.created_at)||0)),this.$forceUpdate()},handlePlanApprovalResolved(s){const e=String((s==null?void 0:s.approval_id)||"").trim();!e||!Array.isArray(this.pendingPlanApprovals)||(this.pendingPlanApprovals=this.pendingPlanApprovals.filter(t=>t&&String(t.approval_id||"")!==e),String((s==null?void 0:s.decision)||"")==="approved"&&(this.fetchWorkMode(),this.fetchPermissionMode(),this.fetchExecutionMode()),this.$forceUpdate())},notifyUserQuestion(s){try{if(!this.userQuestionOriginalTitle&&typeof document<"u"&&(this.userQuestionOriginalTitle=document.title||""),typeof document<"u"){this.userQuestionTitleBlinkTimer&&(clearInterval(this.userQuestionTitleBlinkTimer),this.userQuestionTitleBlinkTimer=null),this.userQuestionTitleBlinkRed=!0;const n=()=>{const i=this.userQuestionTitleBlinkRed?"🔴":"⚪";document.title=`${i} 需要回答 - Agents`,this.userQuestionTitleBlinkRed=!this.userQuestionTitleBlinkRed};n(),this.userQuestionTitleBlinkTimer=setInterval(n,900)}if(typeof window>"u"||!("Notification"in window))return;const e="需要你确认一个问题",t=String((s==null?void 0:s.question)||"").slice(0,120);Notification.permission==="granted"?new Notification(e,{body:t}):Notification.permission!=="denied"&&Notification.requestPermission().then(n=>{n==="granted"&&new Notification(e,{body:t})}).catch(()=>{})}catch{}},restoreUserQuestionTitle(){try{this.userQuestionTitleBlinkTimer&&(clearInterval(this.userQuestionTitleBlinkTimer),this.userQuestionTitleBlinkTimer=null),this.userQuestionOriginalTitle&&typeof document<"u"&&(document.title=this.userQuestionOriginalTitle),this.userQuestionOriginalTitle="",this.userQuestionTitleBlinkRed=!0}catch{}},handleToolApprovalResolved(s){const e=s==null?void 0:s.approval_id;if(!e||!Array.isArray(this.pendingToolApprovals))return;this.pendingToolApprovals=this.pendingToolApprovals.filter(i=>i&&i.approval_id!==e);const t=String((s==null?void 0:s.decision)||"").trim().toLowerCase(),n=String((s==null?void 0:s.reason)||"").trim();if(t==="approved"||t==="rejected"){const i=t==="approved"?"批准通过":"拒绝";this.autoApprovalFinalMessage=`${i}
原因:${n||"未提供"}`}!this.pendingToolApprovals.length&&!this.isMobileViewport&&(this.approvalAutoCloseTimer&&clearTimeout(this.approvalAutoCloseTimer),this.approvalAutoCloseTimer=setTimeout(()=>{this.rightCollapsed=!0},3e3)),this.$forceUpdate()},handleAutoApprovalProgress(s){const e=s==null?void 0:s.progress;!e||typeof e!="object"||(Array.isArray(this.autoApprovalFeedLines)||(this.autoApprovalFeedLines=[]),this.autoApprovalTitle="自动审批记录",e.stage==="start"?(this.autoApprovalFeedLines=["自动审批开始"],this.autoApprovalFinalMessage=""):e.stage==="run_command"&&e.command&&this.autoApprovalFeedLines.push(String(e.command)),this.autoApprovalFeedLines=this.autoApprovalFeedLines.slice(-20),this.$forceUpdate())},handleAppendPayload(s){Oe("[TaskPolling] 文件追加:",s.path),this.chatAddAppendPayloadAction(s),this.$forceUpdate(),this.conditionalScrollToBottom()},handleModifyPayload(s){Oe("[TaskPolling] 文件修改:",s.path),this.chatAddModifyPayloadAction(s),this.$forceUpdate(),this.conditionalScrollToBottom()}},ore={handleGoalProgress(s){var t;if(s!=null&&s.conversation_id&&this.currentConversationId&&s.conversation_id!==this.currentConversationId){Oe("[Goal] 忽略不匹配对话的目标进度事件",{eventCid:s.conversation_id,currentCid:this.currentConversationId});return}const e=String((s==null?void 0:s.status)||"running").toLowerCase();this.goalRunning=e==="running",this.goalModeArmed=!1,this.goalProgress={...s||{},goal:(s==null?void 0:s.goal)||((t=this.goalProgress)==null?void 0:t.goal)||"",status:e,turn_count:Number((s==null?void 0:s.turn_count)??0),tokens_used:Number((s==null?void 0:s.tokens_used)??0),tool_calls:Number((s==null?void 0:s.tool_calls)??0),duration_seconds:Number((s==null?void 0:s.duration_seconds)??0)}},handleGoalReviewProgress(s){const e=(s==null?void 0:s.progress)||s||{};!e||typeof e!="object"||(Array.isArray(this.autoApprovalFeedLines)||(this.autoApprovalFeedLines=[]),this.autoApprovalTitle="目标审批",e.stage==="start"?(this.autoApprovalFeedLines=["开始审核"],this.autoApprovalFinalMessage=""):e.stage==="model_call"?this.autoApprovalFeedLines.push(String(e.message||`审核轮次 ${e.round||""}`).trim()):e.stage==="run_command"&&e.command?this.autoApprovalFeedLines.push(String(e.command)):e.message&&this.autoApprovalFeedLines.push(String(e.message)),this.autoApprovalFeedLines=this.autoApprovalFeedLines.slice(-20),this.$forceUpdate())},scheduleGoalApprovalPanelAutoClose(){this.isMobileViewport||this.autoApprovalTitle!=="目标审批"||(this.approvalAutoCloseTimer&&clearTimeout(this.approvalAutoCloseTimer),this.approvalAutoCloseTimer=setTimeout(()=>{this.rightCollapsed=!0},3e3))},handleGoalCompleted(s){var e;if(s!=null&&s.conversation_id&&this.currentConversationId&&s.conversation_id!==this.currentConversationId){Oe("[Goal] 忽略不匹配对话的目标完成事件",{eventCid:s.conversation_id,currentCid:this.currentConversationId});return}this.goalRunning=!1,this.goalModeArmed=!1,this.goalProgress={...s||{},status:"done"},this.goalDialogOpen=!0,(e=this.scheduleGoalApprovalPanelAutoClose)==null||e.call(this)},handleGoalStopped(s){var e;if(s!=null&&s.conversation_id&&this.currentConversationId&&s.conversation_id!==this.currentConversationId){Oe("[Goal] 忽略不匹配对话的目标停止事件",{eventCid:s.conversation_id,currentCid:this.currentConversationId});return}if(this.goalRunning=!1,this.goalModeArmed=!1,String((s==null?void 0:s.stopped_reason)||"").toLowerCase()==="user_cancel"){this.goalProgress=null,this.goalDialogOpen=!1;return}this.goalProgress={...s||{},status:"stopped"},this.goalDialogOpen=!0,(e=this.scheduleGoalApprovalPanelAutoClose)==null||e.call(this)}},are={handleWorkflowProgress(s){s!=null&&s.conversation_id&&this.currentConversationId&&s.conversation_id!==this.currentConversationId||um().setWorkflow(s,!0)},handleWorkflowReviewProgress(s){if(s!=null&&s.conversation_id&&this.currentConversationId&&s.conversation_id!==this.currentConversationId)return;const e=(s==null?void 0:s.progress)||s||{};!e||typeof e!="object"||(Array.isArray(this.autoApprovalFeedLines)||(this.autoApprovalFeedLines=[]),this.autoApprovalTitle="工作流审核",e.stage==="start"?(this.autoApprovalFeedLines=["开始审核"],this.autoApprovalFinalMessage=""):e.stage==="model_call"?this.autoApprovalFeedLines.push(String(e.message||`审核轮次 ${e.round||""}`).trim()):e.stage==="run_command"&&e.command?this.autoApprovalFeedLines.push(String(e.command)):e.message&&this.autoApprovalFeedLines.push(String(e.message)),this.autoApprovalFeedLines=this.autoApprovalFeedLines.slice(-20),this.$forceUpdate())}},lre={applyConversationTitleUpdate(s,e,t="unknown"){const n=String(e||"").trim(),i=String(s||"").trim();if(!i||this.isPlaceholderConversationTitle(n))return!1;let r=!1;if(i===this.currentConversationId&&this.currentConversationTitle!==n&&(this.suppressTitleTyping=!1,this.titleReady=!0,this.currentConversationTitle=n,r=!0),Array.isArray(this.conversations)){const o=this.conversations.findIndex(a=>a&&a.id===i&&a.title!==n);o>=0&&(this.conversations.splice(o,1,{...this.conversations[o],title:n}),r=!0)}return r&&this.$forceUpdate(),r},scheduleGeneratedTitleRefresh(s="unknown",e={}){const t=String(e.conversationId||this.currentConversationId||"").trim();if(!t)return;const n=Math.max(15e3,Number(e.deadlineMs||9e4)),i=Math.max(1,Number(e.maxAttempts||60)),r=Array.isArray(e.delays)?e.delays:[0,800,1200,1600,2200,3e3,4e3,5e3,6e3],o=Date.now(),a=Number(this.generatedTitleRefreshSeq||0)+1;this.generatedTitleRefreshSeq=a,this.generatedTitleRefreshTimer&&(clearTimeout(this.generatedTitleRefreshTimer),this.generatedTitleRefreshTimer=null);const c=async l=>{if(this.generatedTitleRefreshSeq!==a||this.currentConversationId!==t||(this.generatedTitleRefreshTimer=null,await this.fetchGeneratedConversationTitle(t,`${s}:attempt-${l}`)))return;const h=Date.now()-o;if(l>=i||h>=n)return;const d=Number(r[Math.min(l,r.length-1)]||1e3),p=Math.min(d,Math.max(0,n-h));this.generatedTitleRefreshTimer=window.setTimeout(()=>{c(l+1)},p)};c(1)},async fetchGeneratedConversationTitle(s,e="unknown"){var n;const t=String(s||"").trim();if(!t||t!==this.currentConversationId)return!1;try{const i=await fetch("/api/conversations/current",{cache:"no-store"});if(!i.ok)throw new Error(`HTTP ${i.status}`);const r=await i.json(),o=(r==null?void 0:r.data)||{};if(!(r!=null&&r.success)||o.id!==t)return!1;const a=String(o.title||"").trim(),c=!!(o.title_locked||(n=o.metadata)!=null&&n.title_locked);return this.isPlaceholderConversationTitle(a)||!c?!1:(this.applyConversationTitleUpdate(t,a,e),!0)}catch(i){return console.warn("[TaskPolling] 同步生成后的对话标题失败:",i),!1}}},cre={handleTaskEvent(s){var h,d,p,m,v,g;if(!s||!s.type)return;const e=s.type,t=s.data||{},n=s.idx,i=_M();(e==="task_complete"||e==="task_stopped"||e==="error")&&wl("task-event",{eventType:e,eventIdx:n,currentConversationId:this.currentConversationId,eventConversationId:t==null?void 0:t.conversation_id,taskInProgress:this.taskInProgress,streamingMessage:this.streamingMessage,stopRequested:this.stopRequested,waitingForSubAgent:this.waitingForSubAgent,waitingForBackgroundCommand:this.waitingForBackgroundCommand,errorType:t==null?void 0:t.error_type,errorMessage:t==null?void 0:t.message}),(e==="system_message"||e==="sub_agent_waiting"||e==="user_message"&&(t!=null&&t.sub_agent_notice))&&gF("[DEBUG_NOTIFY_KEY][event] key-event",{eventType:e,idx:n,task_id:t==null?void 0:t.task_id,sub_agent_notice:!!(t!=null&&t.sub_agent_notice),has_running_sub_agents:t==null?void 0:t.has_running_sub_agents,has_running_background_commands:t==null?void 0:t.has_running_background_commands});const r=new Set(["shallow_compression","compression_finished"]),o=typeof this.isExplicitNewConversationRoute=="function"&&this.isExplicitNewConversationRoute(),a=typeof this.isConversationIndependentRoute=="function"&&this.isConversationIndependentRoute(),c=!!(t.conversation_id&&(this.currentConversationId?t.conversation_id!==this.currentConversationId:o||a));if(!r.has(e)&&c){["ai_message_start","thinking_start","thinking_chunk","thinking_end","text_start","text_chunk","text_end"].includes(e)&&Kn("event:drop-conversation-mismatch",{eventType:e,eventIdx:n,eventConversationId:t.conversation_id,currentConversationId:this.currentConversationId}),Oe(`[TaskPolling] 忽略不匹配的事件 #${n}: ${e}, 事件对话=${t.conversation_id}, 当前对话=${this.currentConversationId}`);return}const l=["task_complete","task_stopped","error"].includes(e);if(!r.has(e)&&t.task_id&&(!i.currentTaskId||t.task_id!==i.currentTaskId)&&!(l&&t.conversation_id===this.currentConversationId)){Kn("event:drop-task-mismatch",{eventType:e,eventIdx:n,eventTaskId:t.task_id,currentTaskId:i.currentTaskId,eventConversationId:t.conversation_id,currentConversationId:this.currentConversationId}),Oe(`[TaskPolling] 忽略不匹配的任务事件 #${n}: ${e}, 事件任务=${t.task_id}, 当前任务=${i.currentTaskId}`);return}const u=t.task_id&&typeof n=="number"?`${t.task_id}:${n}`:typeof n=="number"?`idx:${n}`:"";if(u){if(this._processedEventIndices||(this._processedEventIndices=new Set),this._processedEventIndices.has(u)){["ai_message_start","thinking_start","thinking_chunk","thinking_end","text_start","text_chunk","text_end"].includes(e)&&Kn("event:drop-duplicate",{eventType:e,eventIdx:n,dedupeKey:u,currentConversationId:this.currentConversationId});return}if(this._processedEventIndices.add(u),this._processedEventIndices.size>1e3){const y=this._processedEventIndices.values().next().value;this._processedEventIndices.delete(y)}}switch(e){case"ai_message_start":this.handleAiMessageStart(t,n);break;case"thinking_start":this.handleThinkingStart(t,n);break;case"thinking_chunk":this.handleThinkingChunk(t,n);break;case"thinking_end":this.handleThinkingEnd(t,n);break;case"text_start":this.handleTextStart(t,n);break;case"text_chunk":this.handleTextChunk(t,n);break;case"text_end":this.handleTextEnd(t,n);break;case"tool_preparing":this.handleToolPreparing(t,n);break;case"tool_start":this.handleToolStart(t,n);break;case"tool_intent":this.handleToolIntent(t,n);break;case"tool_update_action":case"update_action":this.handleToolUpdateAction(t,n);break;case"tool_approval_required":this.handleToolApprovalRequired(t,n);break;case"tool_approval_resolved":this.handleToolApprovalResolved(t,n);break;case"user_question_required":case"user_questions_required":this.handleUserQuestionsRequired(t,n);break;case"user_question_resolved":case"user_questions_resolved":this.handleUserQuestionsResolved(t,n);break;case"plan_approval_required":this.handlePlanApprovalRequired(t,n);break;case"plan_approval_resolved":this.handlePlanApprovalResolved(t,n);break;case"auto_approval_progress":this.handleAutoApprovalProgress(t,n);break;case"goal_progress":(h=this.handleGoalProgress)==null||h.call(this,t,n);break;case"goal_review_progress":(d=this.handleGoalReviewProgress)==null||d.call(this,t,n);break;case"goal_completed":(p=this.handleGoalCompleted)==null||p.call(this,t,n);break;case"goal_stopped":(m=this.handleGoalStopped)==null||m.call(this,t,n);break;case"workflow_progress":(v=this.handleWorkflowProgress)==null||v.call(this,t,n);break;case"workflow_review_progress":(g=this.handleWorkflowReviewProgress)==null||g.call(this,t,n);break;case"append_payload":this.handleAppendPayload(t,n);break;case"modify_payload":this.handleModifyPayload(t,n);break;case"task_complete":this.handleTaskComplete(t,n);break;case"task_stopped":this.handleTaskStopped(t,n);break;case"error":this.handleTaskError(t,n);break;case"token_update":this.handleTokenUpdate(t,n);break;case"conversation_changed":this.handleConversationChanged(t,n);break;case"conversation_resolved":this.handleConversationResolved(t,n);break;case"todo_updated":t&&"todo_list"in t?this.fileSetTodoList(t.todo_list||null,!0):typeof this.scheduleTodoListRefresh=="function"&&this.scheduleTodoListRefresh(0);break;case"edited_files_updated":Bo().setEditedFiles(Array.isArray(t==null?void 0:t.edited_files)?t.edited_files:[],!0);break;case"edit_summary_updated":if(this._rebuildingFromScratch)break;oE().updateEditSummaryByMessageId(typeof(t==null?void 0:t.message_id)=="string"?t.message_id:"",(t==null?void 0:t.edit_summary)||null);break;case"compression_state":if(this._rebuildingFromScratch)break;this.handleCompressionState(t,n);break;case"compression_finished":if(this._rebuildingFromScratch)break;this.handleCompressionFinished(t,n);break;case"shallow_compression":if(this._rebuildingFromScratch)break;this.handleShallowCompression(t,n);break;case"user_message":this.handleUserMessage(t,n);break;case"system_message":this.handleSystemMessage(t,n);break;case"runtime_queue_sync":if(this._rebuildingFromScratch)break;this.handleRuntimeQueueSync(t);break}},handleTaskComplete(s){var a,c,l,u,h;const e=typeof this.hasPendingToolActions=="function"?this.hasPendingToolActions():null,t=Array.isArray(s==null?void 0:s.pending_runtime_guidance_messages)?s.pending_runtime_guidance_messages.map(d=>String(d||"").trim()).filter(d=>d.length>0):[];if(t.length>0){const d=Math.max(1,Number(this.runtimeQueueLimit||5)),p=[...this.runtimeGuidanceFallbackQueue||[],...t].map(v=>String(v||"").trim()).filter(v=>v.length>0).slice(0,d),m=Math.max(0,d-p.length);Array.isArray(this.runtimeQueuedMessages)&&this.runtimeQueuedMessages.length>m&&(this.runtimeQueuedMessages=this.runtimeQueuedMessages.slice(0,m)),this.runtimeGuidanceFallbackQueue=p}wl("handleTaskComplete:before",{data:s,taskInProgress:this.taskInProgress,streamingMessage:this.streamingMessage,stopRequested:this.stopRequested,pendingToolsBefore:e,preparingToolsSize:((a=this.preparingTools)==null?void 0:a.size)??null,activeToolsSize:((c=this.activeTools)==null?void 0:c.size)??null,waitingForSubAgent:this.waitingForSubAgent,waitingForBackgroundCommand:this.waitingForBackgroundCommand});const n=!!(s!=null&&s.has_running_sub_agents),i=!!(s!=null&&s.has_running_background_commands),r=!!(s!=null&&s.has_running_multi_agent);this.streamingMessage=!1,this.stopRequested=!1,!n&&!r&&this.markLatestUserWorkCompleted(),r?(wl("handleTaskComplete:hasRunningMultiAgent",{taskInProgress:this.taskInProgress,currentConversationId:this.currentConversationId}),this.taskInProgress=!0,this.waitingForSubAgent=!1,this.waitingForBackgroundCommand=i,this.startMultiAgentTaskProbe()):n?(this.taskInProgress=!0,this.waitingForSubAgent=!0,this.waitingForBackgroundCommand=i,this.clearProcessedEvents(),this.startWaitingTaskProbe()):(this.cleanupTrailingEmptyAssistantPlaceholder("task_complete"),typeof this.clearPendingTools=="function"&&this.clearPendingTools("task_complete"),this.taskInProgress=!1,this.waitingForSubAgent=!1,this.waitingForBackgroundCommand=!1,this.stopWaitingTaskProbe(),this.stopMultiAgentTaskProbe(),this.clearTaskState(),this.$nextTick(()=>{typeof this.tryAutoSendRuntimeQueuedMessages=="function"&&this.tryAutoSendRuntimeQueuedMessages("task_complete")})),this.$forceUpdate(),this.currentConversationId&&setTimeout(()=>{this.fetchConversationTokenStatistics(),this.updateCurrentContextTokens()},500),this.scheduleTodoListRefresh(100),s!=null&&s.conversation_id&&s.conversation_id===this.currentConversationId&&(s!=null&&s.task_id)&&((l=this.acknowledgeCompletedWorkspaceTask)==null||l.call(this,s.task_id)),setTimeout(()=>{var d;return(d=this.refreshRunningWorkspaceTasks)==null?void 0:d.call(this)},0),this.scheduleGeneratedTitleRefresh("task_complete",{conversationId:(s==null?void 0:s.conversation_id)||this.currentConversationId,deadlineMs:9e4,maxAttempts:60});const o=typeof this.hasPendingToolActions=="function"?this.hasPendingToolActions():null;wl("handleTaskComplete:after",{taskInProgress:this.taskInProgress,streamingMessage:this.streamingMessage,stopRequested:this.stopRequested,pendingToolsAfter:o,preparingToolsSize:((u=this.preparingTools)==null?void 0:u.size)??null,activeToolsSize:((h=this.activeTools)==null?void 0:h.size)??null,waitingForSubAgent:this.waitingForSubAgent,waitingForBackgroundCommand:this.waitingForBackgroundCommand})},handleTaskStopped(s,e){yn("handleTaskStopped:entered",{eventIdx:e,data:s}),wl("handleTaskStopped:before",{eventIdx:e,data:s,taskInProgress:this.taskInProgress,streamingMessage:this.streamingMessage,stopRequested:this.stopRequested});const t=!!(s!=null&&s.has_running_sub_agents),n=!!(s!=null&&s.has_running_background_commands),i=t||n;yn("handleTaskStopped",{taskInProgress:this.taskInProgress,streamingMessage:this.streamingMessage,hasRunningSubAgents:t,hasRunningBackgroundCommands:n,data:s}),this.cleanupTrailingEmptyAssistantPlaceholder("task_stopped"),this.streamingMessage=!1,this.stopRequested=!1,i?(this.taskInProgress=!0,this.waitingForSubAgent=t,this.waitingForBackgroundCommand=n):(this.markLatestUserWorkCompleted(),this.taskInProgress=!1,this.waitingForSubAgent=!1,this.waitingForBackgroundCommand=!1,this.stopWaitingTaskProbe(),typeof this.clearPendingTools=="function"&&this.clearPendingTools("task_stopped"),this.clearTaskState(),this.$nextTick(()=>{typeof this.tryAutoSendRuntimeQueuedMessages=="function"&&this.tryAutoSendRuntimeQueuedMessages("task_stopped")})),yn("handleTaskStopped:after",{taskInProgress:this.taskInProgress,waitingForSubAgent:this.waitingForSubAgent,waitingForBackgroundCommand:this.waitingForBackgroundCommand,hasRunningBackground:i}),this.scheduleTodoListRefresh(100),setTimeout(()=>{var r;return(r=this.refreshRunningWorkspaceTasks)==null?void 0:r.call(this)},0),this.$forceUpdate(),wl("handleTaskStopped:after",{taskInProgress:this.taskInProgress,streamingMessage:this.streamingMessage,stopRequested:this.stopRequested})},clearTaskState(){this.stopWaitingTaskProbe(),(async()=>{const{useTaskStore:s}=await wt(async()=>{const{useTaskStore:t}=await Promise.resolve().then(()=>so);return{useTaskStore:t}},void 0);s().clearTask()})(),typeof this.clearProcessedEvents=="function"&&this.clearProcessedEvents()},handleTaskError(s){if(wl("handleTaskError:incoming",{data:s,taskInProgress:this.taskInProgress,streamingMessage:this.streamingMessage,stopRequested:this.stopRequested}),!!(s!=null&&s.retry)){const a=Number(s==null?void 0:s.retry_in)||5,c=Number(s==null?void 0:s.attempt)||1,l=Number(s==null?void 0:s.max_attempts)||c;Oe("[TaskPolling] API错误等待自动重试",{retryIn:a,attempt:c,maxAttempts:l,message:s==null?void 0:s.message}),this.stopRequested=!1,this.taskInProgress=!0,this.streamingMessage=!0,this.$forceUpdate(),this.uiPushToast({title:"即将重试",message:`将在 ${a} 秒后重试(第 ${c}/${l} 次)
错误:${(s==null?void 0:s.message)||"未知错误"}`,type:"info",duration:Math.max(a,1)*1e3});return}const t=s.message||"未知错误",n=s.error_type||"unknown";if(n==="parameter_format_error"||/工具参数解析失败/.test(String(t))){console.warn("[TaskPolling] 工具参数解析失败(非致命),继续轮询任务:",s),wl("handleTaskError:tool-args-parse-error-ignored",{errorType:n,errorMessage:t,taskInProgress:this.taskInProgress,streamingMessage:this.streamingMessage,stopRequested:this.stopRequested}),this.uiPushToast({title:"工具调用失败",message:t,type:"warning",duration:6e3}),this.stopRequested=!1,this.$forceUpdate();return}let r="任务执行失败",o=t;n==="api_error"?(r="API 调用失败",o=`模型服务异常:${t}`):n==="timeout"?(r="任务超时",o="任务执行时间过长,已自动停止"):n==="quota_exceeded"&&(r="配额不足",o="您的使用配额已用尽"),console.error("[TaskPolling] 任务错误:",s.message),this.uiPushToast({title:r,message:o,type:"error",duration:8e3}),this.markLatestUserWorkCompleted(),this.streamingMessage=!1,this.taskInProgress=!1,this.stopRequested=!1,this.$forceUpdate(),wl("handleTaskError:fatal-after-state-update",{errorType:n,errorMessage:t,taskInProgress:this.taskInProgress,streamingMessage:this.streamingMessage,stopRequested:this.stopRequested}),(async()=>{const{useTaskStore:a}=await wt(async()=>{const{useTaskStore:l}=await Promise.resolve().then(()=>so);return{useTaskStore:l}},void 0);a().stopPolling()})(),this.$nextTick(()=>{typeof this.tryAutoSendRuntimeQueuedMessages=="function"&&this.tryAutoSendRuntimeQueuedMessages("task_error")})}},ure={handleUserMessage(s){var l;const e=((s==null?void 0:s.message)||(s==null?void 0:s.content)||"").trim();if(!e)return;pF("[DEBUG_NOTIFY][ui] handleUserMessage",{messagePreview:e.slice(0,120),sub_agent_notice:!!(s!=null&&s.sub_agent_notice),background_command_notice:!!(s!=null&&s.background_command_notice),task_id:s==null?void 0:s.task_id,has_running_sub_agents:s==null?void 0:s.has_running_sub_agents,has_running_background_commands:s==null?void 0:s.has_running_background_commands}),gF("[DEBUG_NOTIFY_KEY][ui] handleUserMessage",{messagePreview:e.slice(0,80),task_id:s==null?void 0:s.task_id,sub_agent_notice:!!(s!=null&&s.sub_agent_notice),background_command_notice:!!(s!=null&&s.background_command_notice)});const t=Qie(s),n=Xie(s),i=Yie(s),r=Jie(s,i,e),o=Array.isArray(s==null?void 0:s.images)?s.images:[],a=Array.isArray(s==null?void 0:s.videos)?s.videos:[],c=Array.isArray(s==null?void 0:s.media_refs)?s.media_refs:Array.isArray(s==null?void 0:s.mediaRefs)?s.mediaRefs:[];if(t)if(n&&!(this.taskInProgress||this.streamingMessage))Oe("[TaskPolling] 空闲态跳过 runtime_mode_notice 用户通知",{messagePreview:e.slice(0,80)});else{r.starts_work===!0&&this.markLatestUserWorkCompleted();const u=this.moveTrailingEmptyAssistantPlaceholderAfterUserInsert("auto_user_message")&&(this.taskInProgress||this.streamingMessage),h=i2(this.messages||[],e,o,a,i);if(h){h.media_refs=c,h.metadata={...h.metadata||{},...r,media_refs:c,message_source:i};const d=(s==null?void 0:s.timestamp)??(s==null?void 0:s.created_at)??(s==null?void 0:s.createdAt)??null;d&&(h.created_at=d)}else this.chatAddUserMessage(e,o,a,c,i,r);u&&(this.chatStartAssistantMessage(),this.taskInProgress=!0,this.streamingMessage=!0,this.stopRequested=!1)}else{const u=Zie(this.messages||[]),h=i2(this.messages||[],e,o,a,i),d=!!(u&&u.role==="user"&&String(u.content||"").trim()===e&&JSON.stringify(u.images||[])===JSON.stringify(o||[])&&JSON.stringify(u.videos||[])===JSON.stringify(a||[]));if(d||h){const p=d?u:h;p.media_refs=c,p.metadata={...p.metadata||{},...r,media_refs:c};const m=(s==null?void 0:s.timestamp)??(s==null?void 0:s.created_at)??(s==null?void 0:s.createdAt)??null;m&&(p.created_at=m)}else this.chatAddUserMessage(e,o,a,c,i,r);this.taskInProgress=!0,this.streamingMessage=!!b0((l=this.messages)==null?void 0:l[this.messages.length-1]),this.stopRequested=!1}s!=null&&s.sub_agent_notice&&(typeof(s==null?void 0:s.has_running_sub_agents)=="boolean"?this.waitingForSubAgent=s.has_running_sub_agents:typeof(s==null?void 0:s.remaining_count)=="number"&&(this.waitingForSubAgent=s.remaining_count>0),typeof(s==null?void 0:s.has_running_background_commands)=="boolean"?this.waitingForBackgroundCommand=s.has_running_background_commands:s!=null&&s.background_command_notice&&(this.waitingForBackgroundCommand=this.waitingForSubAgent),this.waitingForSubAgent?this.startWaitingTaskProbe():this.stopWaitingTaskProbe()),this.$forceUpdate(),this.conditionalScrollToBottom()},handleSystemMessage(s){var t,n,i,r,o;const e=((s==null?void 0:s.content)||(s==null?void 0:s.message)||"").trim();dy("taskPolling.handleSystemMessage:incoming",{raw:s,normalizedContent:e,currentConversationId:this.currentConversationId,currentMessagesLength:Array.isArray(this.messages)?this.messages.length:-1}),e&&(this.cleanupTrailingEmptyAssistantPlaceholder("before_system_message_append"),this.appendSystemAction(e),dy("taskPolling.handleSystemMessage:after-append",{currentMessagesLength:Array.isArray(this.messages)?this.messages.length:-1,lastRole:((n=(t=this.messages)==null?void 0:t[this.messages.length-1])==null?void 0:n.role)||null,lastActions:((o=(r=(i=this.messages)==null?void 0:i[this.messages.length-1])==null?void 0:r.actions)==null?void 0:o.map(a=>a==null?void 0:a.type))||[]}))}},hre={handleRuntimeQueueSync(s){const e=Array.isArray(s==null?void 0:s.messages)?s.messages:[],t=typeof this.buildRuntimeQueueSnapshotKey=="function"?this.buildRuntimeQueueSnapshotKey:l=>JSON.stringify((Array.isArray(l)?l:[]).map(u=>[String((u==null?void 0:u.id)||""),String((u==null?void 0:u.text)||""),Number((u==null?void 0:u.createdAt)??(u==null?void 0:u.created_at)??0)])),n=(Array.isArray(e)?e:[]).map(l=>({id:String((l==null?void 0:l.id)||"").trim(),text:String((l==null?void 0:l.text)||"").trim(),createdAt:Number((l==null?void 0:l.created_at)??(l==null?void 0:l.createdAt)??0)})),i=t(n),r=Date.now(),o=String(this.runtimeQueueSyncLockKey||""),a=Number(this.runtimeQueueSyncLockUntil||0);if(o&&r<a&&i!==o){Oe("[RuntimeQueue] 忽略可能过期的轮询同步",{now:r,lockUntil:a,incomingSize:n.length});return}if(o&&i===o&&(this.runtimeQueueSyncLockKey="",this.runtimeQueueSyncLockUntil=0),typeof this.applyRuntimeQueuedMessages=="function"){this.applyRuntimeQueuedMessages(e);return}const c=Math.max(1,Number(this.runtimeQueueLimit||5));this.runtimeQueuedMessages=e.map(l=>({id:String((l==null?void 0:l.id)||"").trim(),text:String((l==null?void 0:l.text)||"").trim(),createdAt:Number((l==null?void 0:l.created_at)??(l==null?void 0:l.createdAt)??Date.now())})).filter(l=>l.id&&l.text).slice(0,c)},handleTokenUpdate(s){s.conversation_id===this.currentConversationId&&(this.currentConversationTokens.cumulative_input_tokens=s.cumulative_input_tokens||0,this.currentConversationTokens.cumulative_output_tokens=s.cumulative_output_tokens||0,this.currentConversationTokens.cumulative_total_tokens=s.cumulative_total_tokens||0,typeof s.current_context_tokens=="number"?this.resourceSetCurrentContextTokens(s.current_context_tokens):this.updateCurrentContextTokens(),this.$forceUpdate())},handleConversationChanged(s,e){if(s&&s.conversation_id===this.currentConversationId){if(s.title&&(this.currentConversationTitle=s.title,Oe("[TaskPolling] 更新当前对话标题:",s.title)),s.title&&Array.isArray(this.conversations)){const t=this.conversations.find(n=>n&&n.id===s.conversation_id);t&&(t.title=s.title,Oe("[TaskPolling] 更新对话列表中的标题:",s.title))}this.$forceUpdate()}},handleConversationResolved(s){if(!this.isConversationIndependentRoute()&&s&&s.conversation_id){if(this.currentConversationId=s.conversation_id,s.title&&(this.currentConversationTitle=s.title),s.title&&Array.isArray(this.runningWorkspaceTasks)){const i=String(s.task_id||"").trim(),r=String(s.source_conversation_id||"").trim(),o=String(s.conversation_id||"").trim();this.runningWorkspaceTasks=this.runningWorkspaceTasks.map(a=>{const c=i&&String((a==null?void 0:a.task_id)||"")===i,l=r&&String((a==null?void 0:a.conversation_id)||"")===r,u=o&&String((a==null?void 0:a.conversation_id)||"")===o;return!c&&!l&&!u?a:{...a,conversation_id:o||(a==null?void 0:a.conversation_id),conversation_title:s.title}})}this.promoteConversationToTop(s.conversation_id);const e=this.stripConversationPrefix(s.conversation_id),t=window.location.pathname.replace(/^\/+/,""),n=`/${e}`;s.created?history.pushState({conversationId:s.conversation_id},"",n):t!==e&&history.replaceState({conversationId:s.conversation_id},"",n)}}},dre={handleCompressionState(s){if(!s||typeof s!="object")return;const e=!!this.compressionInProgress;if(this.compressionInProgress=!!s.in_progress,this.compressionConversationId=this.compressionInProgress&&(s.conversation_id||this.currentConversationId)||null,this.compressionMode=s.mode||"",this.compressionStage=s.stage||"",this.compressionInProgress&&!e){const t=this.compressionMode==="manual"?"手动":"自动";this.compressionToastId&&(this.uiDismissToast(this.compressionToastId),this.compressionToastId=null),this.compressionToastId=this.uiPushToast({title:"压缩中",message:`对话正在${t}压缩,请稍候…`,type:"info",duration:null,closable:!1})}this.compressionInProgress||(this.compressionError=s.error||"",this.compressionToastId&&(this.uiDismissToast(this.compressionToastId),this.compressionToastId=null))},handleShallowCompression(s,e){const t=Number((s==null?void 0:s.compressed_count)||0);t<=0||this.uiPushToast({title:"自动浅层压缩",message:`已自动压缩 ${t} 条较早工具结果`,type:"info",duration:2500})},async handleCompressionFinished(s){var n,i;this.compressionToastId&&(this.uiDismissToast(this.compressionToastId),this.compressionToastId=null),this.compressionInProgress=!1,this.compressionConversationId=null,this.compressionMode="",this.compressionStage="",this.compressionError="";const e=s==null?void 0:s.conversation_id,t=e&&e===this.currentConversationId;e&&!t&&(await this.loadConversation(e,{force:!0}),this.conversationsOffset=0,typeof this.loadConversationsList=="function"&&await this.loadConversationsList(),await((n=this.refreshRunningWorkspaceTasks)==null?void 0:n.call(this)),await((i=this.restoreTaskState)==null?void 0:i.call(this))),this.uiPushToast({title:"压缩完成",message:"已压缩较早的对话内容",type:"success",duration:2400})},async restoreTaskState(s={}){var n,i,r,o,a,c;const e=s&&s.bootstrapReplay?s.bootstrapReplay:null;this.clearProcessedEvents(),typeof this.startRunningStateReconcile=="function"&&this.startRunningStateReconcile(),Kn("restore:start",{currentConversationId:this.currentConversationId,streamingMessage:this.streamingMessage,taskInProgress:this.taskInProgress,historyLoading:this.historyLoading,historyLoadingFor:this.historyLoadingFor,messagesLen:Array.isArray(this.messages)?this.messages.length:-1});const t=typeof this.isConversationIndependentRoute=="function"&&this.isConversationIndependentRoute();if(!this.currentConversationId&&(typeof this.isExplicitNewConversationRoute=="function"&&this.isExplicitNewConversationRoute()||t)){Kn("restore:skip-explicit-new-route",{path:typeof window<"u"?window.location.pathname:""}),this._restoreTaskStateWaitCount=0;return}try{const{useTaskStore:l}=await wt(async()=>{const{useTaskStore:L}=await Promise.resolve().then(()=>so);return{useTaskStore:L}},void 0),u=l();if(this.streamingMessage||this.taskInProgress){Kn("restore:skip-already-running",{streamingMessage:this.streamingMessage,taskInProgress:this.taskInProgress,currentConversationId:this.currentConversationId}),Oe("[TaskPolling] 任务已在进行中,跳过恢复",{streamingMessage:this.streamingMessage,taskInProgress:this.taskInProgress,currentConversationId:this.currentConversationId});return}let h;if(e&&e.task&&e.task.task_id?(h=e.task,u.currentTaskId=h.task_id,u.taskStatus=h.status,u.taskCreatedAt=h.created_at,u.taskUpdatedAt=h.updated_at,u.pollingError=null,u.pollingErrorCount=0,u.pollingWarned=!1,u.runtimeQueueSnapshotKey="",u.lastEventIndex=typeof e.replay_from=="number"?e.replay_from:Array.isArray(e.events)?e.events.length:0):h=await u.loadRunningTask(this.currentConversationId),!h){Kn("restore:no-running-task",{currentConversationId:this.currentConversationId}),Oe("[TaskPolling] 没有运行中的任务",{currentConversationId:this.currentConversationId}),this._restoreTaskStateWaitCount=0,await this.restoreSubAgentWaitingState();return}if((this.versioningHostMode||this.dockerProjectMode)&&this.currentHostWorkspaceId&&(h!=null&&h.workspace_id)&&h.workspace_id!==this.currentHostWorkspaceId){Kn("restore:skip-workspace-mismatch",{taskId:h==null?void 0:h.task_id,taskWorkspaceId:h==null?void 0:h.workspace_id,currentHostWorkspaceId:this.currentHostWorkspaceId}),u.clearTask(),await this.restoreSubAgentWaitingState();return}if(Oe("[TaskPolling] 发现运行中的任务,开始恢复状态",{taskId:h==null?void 0:h.task_id,status:h==null?void 0:h.status,conversationId:h==null?void 0:h.conversation_id}),h!=null&&h.goal_mode){const L=this.goalProgress&&typeof this.goalProgress=="object"?this.goalProgress:{},z=h!=null&&h.goal_progress&&typeof h.goal_progress=="object"?h.goal_progress:{};this.goalRunning=!0,this.goalModeArmed=!1,this.goalProgress={...L,...z,goal:(z==null?void 0:z.goal)||(L==null?void 0:L.goal)||(h==null?void 0:h.message)||"",status:"running",turn_count:Number((z==null?void 0:z.turn_count)??(L==null?void 0:L.turn_count)??0),tokens_used:Number((z==null?void 0:z.tokens_used)??(L==null?void 0:L.tokens_used)??0),tool_calls:Number((z==null?void 0:z.tool_calls)??(L==null?void 0:L.tool_calls)??0),duration_seconds:Number((z==null?void 0:z.duration_seconds)??(L==null?void 0:L.duration_seconds)??0)}}Kn("restore:running-task-found",{taskId:h==null?void 0:h.task_id,status:h==null?void 0:h.status,taskConversationId:h==null?void 0:h.conversation_id,currentConversationId:this.currentConversationId});const d=Array.isArray(this.messages)&&this.messages.length>0,p=!!this.historyLoading&&this.historyLoadingFor===this.currentConversationId;if(!d&&!e){this._restoreTaskStateWaitCount=(this._restoreTaskStateWaitCount||0)+1;const L=this._restoreTaskStateWaitCount>=8;if(Kn("restore:history-empty",{waitCount:this._restoreTaskStateWaitCount,waitedTooLong:L,historyLoading:this.historyLoading,historyLoadingFor:this.historyLoadingFor,currentConversationId:this.currentConversationId}),p&&!L){Oe("[TaskPolling] 历史未加载,等待历史加载完成",{waitCount:this._restoreTaskStateWaitCount,historyLoading:this.historyLoading,historyLoadingFor:this.historyLoadingFor}),setTimeout(()=>{this.restoreTaskState()},500);return}Oe("[TaskPolling] 历史为空,启用事件重放兜底恢复",{waitCount:this._restoreTaskStateWaitCount,historyLoading:this.historyLoading,historyLoadingFor:this.historyLoadingFor})}else this._restoreTaskStateWaitCount=0;Oe("[TaskPolling] 开始精细恢复",{hasMessages:d,historyLoading:this.historyLoading,historyLoadingFor:this.historyLoadingFor});let m;if(e)m=Array.isArray(e.events)?e.events:[];else{const L=await fetch(`/api/tasks/${u.currentTaskId}`);if(!L.ok){Oe("[TaskPolling] 获取任务详情失败");return}const z=await L.json();if(!z.success||!z.data.events){Kn("restore:task-detail-invalid",{ok:!!(z!=null&&z.success),hasData:!!(z!=null&&z.data),hasEvents:!!((n=z==null?void 0:z.data)!=null&&n.events)}),Oe("[TaskPolling] 任务详情无效");return}m=z.data.events}Oe(`[TaskPolling] 获取到 ${m.length} 个事件`),Kn("restore:task-detail-events",{total:m.length,firstIdx:(i=m[0])==null?void 0:i.idx,firstType:(r=m[0])==null?void 0:r.type,lastIdx:(o=m[m.length-1])==null?void 0:o.idx,lastType:(a=m[m.length-1])==null?void 0:a.type});const v=this.messages[this.messages.length-1],g=v&&v.role==="assistant",y=e&&e.decision_inputs||null;let b=!1,_=!1,w=!1,S=!1,C=!1;if(y)b=!!y.in_thinking,_=!!y.in_text,w=!!y.has_text_chunk_event,S=!!y.has_assistant_response_event,C=!!y.has_assistant_content_event;else for(let L=0;L<m.length;L++){const z=m[L],Q=String((z==null?void 0:z.type)||"");["ai_message_start","thinking_start","thinking_chunk","thinking_end","text_start","text_chunk","text_end","tool_preparing","tool_start","tool_update","tool_complete"].includes(Q)&&(S=!0),["thinking_chunk","text_chunk","tool_preparing","tool_start","tool_update","tool_complete"].includes(Q)&&(C=!0),z.type==="thinking_start"?b=!0:z.type==="thinking_end"&&(b=!1),z.type==="text_start"?_=!0:z.type==="text_end"&&(_=!1),z.type==="text_chunk"&&(w=!0)}const T=_||w||b,k=g&&Array.isArray(v.actions)&&v.actions.some(L=>{if(!L)return!1;if(L.streaming)return!0;if(L.type==="tool"&&L.tool){const z=String(L.tool.status||"").toLowerCase();if(["preparing","running","pending","queued"].includes(z))return!0}return!1}),A=!!(e&&e.needs_rebuild===!0),M=!!(y&&y.has_pending_tool_calls===!0),R=!g||g&&(!v.actions||v.actions.length===0)||T||k||A||M;if(Kn("restore:rebuild-decision",{needsRebuild:R,isAssistantMessage:g,hasAssistantResponseEvent:S,hasAssistantContentEvent:C,inText:_,hasTextChunkEvent:w,inThinking:b,forceRebuildForStreamingText:T,hasInProgressActions:k,serverNeedsRebuild:A,serverHasPendingToolCalls:M}),R){Oe("[TaskPolling] 需要从头重建 assistant 响应");const L=V=>{if(!V||V.role!=="user")return!1;const N=V.metadata||{};if(N.runtime_injected===!0)return!0;const O=String(N.message_source||"").trim().toLowerCase();return O==="compression"||O==="compression_handoff"};let z=this.messages.length-1;for(;z>=0;){const V=this.messages[z];if(V&&V.role==="assistant"){z-=1;continue}if(L(V)){z-=1;continue}break}let Q=null,W=-1;for(let V=Math.max(z+1,0);V<this.messages.length;V+=1)if(this.messages[V]&&this.messages[V].role==="assistant"){Q=this.messages[V],W=V;break}Q&&(Oe("[TaskPolling] 复用现有 assistant 消息容器,清空 actions 等待事件重建",{hasAssistantContentEvent:C,rebuildContainerIdx:W,removedAfterContainer:this.messages.length-1-W}),W<this.messages.length-1&&this.messages.splice(W+1),Q.actions=[],Q.awaitingFirstContent=!C,Q.generatingLabel=Q.generatingLabel||"思考中...",typeof Q.streaming=="boolean"&&(Q.streaming=!0),this.currentMessageIndex=W),this.streamingMessage=!0,this.taskInProgress=!0,!C&&!Q&&((c=this.ensureRunningAssistantPlaceholder)==null||c.call(this,h,"restore:no-visible-content-yet")),this.$forceUpdate(),u.lastEventIndex=0,Oe("[TaskPolling] 重置偏移量为 0从头开始轮询"),this._rebuildingFromScratch=!0,this._rebuildingEventCount=m.length,window.__taskEventHandler=V=>{this.handleTaskEvent(V)},u.startPolling(V=>{this.handleTaskEvent(V)}),Kn("restore:rebuild-polling-started",{lastEventIndex:u.lastEventIndex,currentConversationId:this.currentConversationId}),setTimeout(()=>{Oe("[TaskPolling] 历史事件处理完毕,清除重建标记"),this._rebuildingFromScratch=!1,this._rebuildingEventCount=0},2e3);return}if(v.actions){const L=v.actions.filter(W=>W.type==="thinking");if(b&&L.length>0){const W=L[L.length-1];W.streaming&&W.blockId&&this.$nextTick(()=>{this.chatSetThinkingLock(W.blockId,!0)})}for(const W of L)W.blockId&&(W.collapsed=!0);const z=v.actions.filter(W=>W.type==="text");if(_&&z.length>0){const W=z[z.length-1];W.streaming=!0}const Q=v.actions.filter(W=>W.type==="tool");for(const W of Q)W.tool&&W.tool.id&&(this.toolRegisterAction(W,W.tool.id),W.tool.executionId&&this.toolRegisterAction(W,W.tool.executionId),W.tool.name&&this.toolTrackAction(W.tool.name,W))}this.streamingMessage=!0,this.taskInProgress=!0;const P=this.messages.length-1;v&&v.role==="assistant"&&(this.currentMessageIndex=P),this.$forceUpdate(),this.$nextTick(()=>{this.conditionalScrollToBottom()}),window.__taskEventHandler=L=>{this.handleTaskEvent(L)},Oe("[TaskPolling] 启动轮询,起始偏移量:",u.lastEventIndex),u.startPolling(L=>{this.handleTaskEvent(L)}),Kn("restore:polling-started-follow",{lastEventIndex:u.lastEventIndex,currentConversationId:this.currentConversationId}),this.uiPushToast({title:"任务恢复",message:"检测到进行中的任务,已恢复连接",type:"info",duration:3e3})}catch(l){Kn("restore:error",{message:(l==null?void 0:l.message)||String(l)}),console.error("[TaskPolling] 恢复任务状态失败:",l)}}},fre={...ere,...nre,...ire,...rre,...ore,...are,...lre,...cre,...ure,...hre,...dre},pre={async handleEasterEggPayload(s){await Km().handlePayload(s,this)},async startEasterEggEffect(s,e={}){await Km().startEffect(s,e,this)},destroyEasterEggEffect(s=!1){return Km().destroyEffect(s)},finishEasterEggCleanup(){Km().finishCleanup()}},gre=s=>String(s||"").toLowerCase()==="conversation_only"?"conversation_only":"workspace_and_conversation",mre={async fetchVersioningStatus(s=null,e={}){const t=s||this.currentConversationId,{silent:n=!1}=e;if(!t)return null;try{const i=await fetch(`/api/conversations/${t}/versioning`),r=await i.json().catch(()=>({}));if(!i.ok||!(r!=null&&r.success)){if(!n)throw new Error((r==null?void 0:r.error)||"获取版本状态失败");return null}const o=r.data||{};return this.versioningHostMode=!!o.host_mode,uT(!!o.host_mode),this.versioningEnabled=!!o.enabled,this.versioningMode="overwrite",this.versioningRestoreMode="overwrite",o}catch(i){return n||this.uiPushToast({title:"版本管理",message:(i==null?void 0:i.message)||"获取版本状态失败",type:"error"}),null}},async fetchVersioningCheckpoints(s=null){var t;const e=s||this.currentConversationId;if(!e)return[];this.versioningLoading=!0;try{const n=await fetch(`/api/conversations/${e}/versioning/checkpoints`),i=await n.json().catch(()=>({}));if(!n.ok||!(i!=null&&i.success))throw new Error((i==null?void 0:i.error)||"加载版本点失败");const r=Array.isArray((t=i==null?void 0:i.data)==null?void 0:t.items)?i.data.items:[];return this.versioningCheckpoints=r,r.length||(this.versioningSelectedSeq=null,this.versioningSelectedDetail=null),r}catch(n){return this.uiPushToast({title:"版本管理",message:(n==null?void 0:n.message)||"加载版本点失败",type:"error"}),[]}finally{this.versioningLoading=!1}},async openVersioningDialog(){if(this.versioningRestoreMode="overwrite",this.versioningTrackingMode="conversation_only",this.versioningDialogOpen=!0,this.versioningSelectedSeq=null,this.versioningSelectedDetail=null,this.versioningCheckpoints=[],!this.currentConversationId){this.versioningEnabled=!1;return}await this.fetchVersioningStatus(this.currentConversationId),await this.fetchVersioningCheckpoints(this.currentConversationId)},async refreshVersioningDialog(){await this.fetchVersioningStatus(this.currentConversationId),await this.fetchVersioningCheckpoints(this.currentConversationId)},async toggleConversationVersioning(s){var e;if(!this.currentConversationId){this.versioningEnabled=!!s,this.uiPushToast({title:"版本管理",message:s?"已为下一次新对话开启版本管理":"已取消下一次新对话的版本管理",type:"success"});return}this.versioningLoading=!0;try{const t=await fetch(`/api/conversations/${this.currentConversationId}/versioning`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:!!s,mode:"overwrite"})}),n=await t.json().catch(()=>({}));if(!t.ok||!(n!=null&&n.success))throw new Error((n==null?void 0:n.error)||"切换版本管理失败");this.versioningEnabled=!!((e=n==null?void 0:n.data)!=null&&e.enabled),this.versioningMode="overwrite",this.versioningRestoreMode="overwrite",this.uiPushToast({title:"版本管理",message:this.versioningEnabled?"已开启":"已关闭",type:"success"}),this.versioningEnabled?await this.fetchVersioningCheckpoints(this.currentConversationId):(this.versioningCheckpoints=[],this.versioningSelectedSeq=null,this.versioningSelectedDetail=null)}catch(t){this.uiPushToast({title:"版本管理",message:(t==null?void 0:t.message)||"切换失败",type:"error"})}finally{this.versioningLoading=!1}},async selectVersioningCheckpoint(s){if(!this.currentConversationId||s===null||s===void 0||Number.isNaN(Number(s)))return;const e=Number(s);this.versioningSelectedSeq=e,this.versioningDetailLoading=!0;try{const t=await fetch(`/api/conversations/${this.currentConversationId}/versioning/checkpoints/${encodeURIComponent(String(e))}`),n=await t.text();let i={};try{i=n?JSON.parse(n):{}}catch(r){throw console.error("[VersioningDetail] parse failed:",r==null?void 0:r.message,"status=",t.status,"text=",n),new Error(`详情响应解析失败: ${(r==null?void 0:r.message)||"未知错误"}`)}if(!t.ok||!(i!=null&&i.success))throw new Error((i==null?void 0:i.error)||"加载详情失败");this.versioningSelectedDetail=i.data||null}catch(t){console.error("[VersioningDetail] error:",t),this.uiPushToast({title:"版本管理",message:(t==null?void 0:t.message)||"加载详情失败",type:"error"})}finally{this.versioningDetailLoading=!1}},async confirmVersioningRestore(){var r;if(!this.currentConversationId||this.versioningSelectedSeq===null||this.versioningSelectedSeq===void 0)return;const s=this.versioningRestoreMode||"overwrite",e=gre(this.versioningTrackingMode),t=e==="conversation_only"?"仅回溯对话":"回溯对话和工作区",n=s==="copy"?"复制对话":"覆盖当前对话";if(await this.confirmAction({title:"确认回溯",message:`将${t}到输入 #${this.versioningSelectedSeq} 对应的状态,并${n}。是否继续?`,confirmText:"回溯",cancelText:"取消"})){this.versioningRestoring=!0;try{const o=await fetch(`/api/conversations/${this.currentConversationId}/versioning/restore`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({seq:this.versioningSelectedSeq,mode:s,tracking_mode:e})}),a=await o.json().catch(()=>({}));if(!o.ok||!(a!=null&&a.success))throw new Error((a==null?void 0:a.error)||"回溯失败");const c=((r=a==null?void 0:a.data)==null?void 0:r.conversation_id)||this.currentConversationId;this.versioningDialogOpen=!1,await this.loadConversation(c,{force:!0}),this.conversationsOffset=0,await this.loadConversationsList(),s==="copy"&&!this.conversations.some(l=>l&&l.id===c)&&this.conversations.splice(0,this.conversations.length,{id:c,title:"版本回溯对话",updated_at:new Date().toISOString(),total_messages:0,total_tools:0},...this.conversations.filter(l=>l&&l.id!==c)),this.uiPushToast({title:"版本管理",message:s==="copy"?"已复制并回溯到新对话":"回溯完成",type:"success"})}catch(o){this.uiPushToast({title:"版本管理",message:(o==null?void 0:o.message)||"回溯失败",type:"error"})}finally{this.versioningRestoring=!1}}}},mF={data:fZ,created:ine,mounted:rne,beforeUnmount:one,computed:yZ,watch:_Z,methods:{...hne,..._ne,...xne,...Ane,...Bne,...Gne,...hie,...Gie,...mre,...pre,...fre,...Ir(Vs,{uiToggleSidebar:"toggleSidebar",uiSetSidebarCollapsed:"setSidebarCollapsed",uiSetChatDisplayMode:"setChatDisplayMode",uiSetMobileViewport:"setIsMobileViewport",uiSetMobileOverlayMenuOpen:"setMobileOverlayMenuOpen",uiToggleMobileOverlayMenu:"toggleMobileOverlayMenu",uiSetActiveMobileOverlay:"setActiveMobileOverlay",uiCloseMobileOverlay:"closeMobileOverlay",uiPushToast:"pushToast",uiUpdateToast:"updateToast",uiDismissToast:"dismissToast",uiShowQuotaToastMessage:"showQuotaToastMessage",uiDismissQuotaToast:"dismissQuotaToast",uiRequestConfirm:"requestConfirm",uiResolveConfirm:"resolveConfirm"}),...Ir(Qi,{modelSet:"setModel"}),...Ir(oE,{chatExpandBlock:"expandBlock",chatCollapseBlock:"collapseBlock",chatClearExpandedBlocks:"clearExpandedBlocks",chatSetThinkingLock:"setThinkingLock",chatClearThinkingLocks:"clearThinkingLocks",chatSetScrollState:"setScrollState",chatEnableAutoScroll:"enableAutoScroll",chatDisableAutoScroll:"disableAutoScroll",chatToggleScrollLockState:"toggleScrollLockState",chatAddUserMessage:"addUserMessage",chatStartAssistantMessage:"startAssistantMessage",chatStartThinkingAction:"startThinkingAction",chatAppendThinkingChunk:"appendThinkingChunk",chatCompleteThinkingAction:"completeThinking",chatStartTextAction:"startTextAction",chatAppendTextChunk:"appendTextChunk",chatCompleteTextAction:"completeText",chatAddSystemMessage:"addSystemMessage",chatEnsureAssistantMessage:"ensureAssistantMessage"}),...Ir(q0,{inputSetFocused:"setInputFocused",inputToggleQuickMenu:"toggleQuickMenu",inputCloseMenus:"closeMenus",inputOpenQuickMenu:"openQuickMenu",inputSetQuickMenuOpen:"setQuickMenuOpen",inputToggleToolMenu:"toggleToolMenu",inputSetToolMenuOpen:"setToolMenuOpen",inputToggleSettingsMenu:"toggleSettingsMenu",inputSetSettingsOpen:"setSettingsOpen",inputSetMessage:"setInputMessage",inputClearMessage:"clearInputMessage",inputSetLineCount:"setInputLineCount",inputSetMultiline:"setInputMultiline",inputSetImagePickerOpen:"setImagePickerOpen",inputSetSelectedImages:"setSelectedImages",inputAddSelectedImage:"addSelectedImage",inputClearSelectedImages:"clearSelectedImages",inputRemoveSelectedImage:"removeSelectedImage",inputSetVideoPickerOpen:"setVideoPickerOpen",inputSetSelectedVideos:"setSelectedVideos",inputAddSelectedVideo:"addSelectedVideo",inputClearSelectedVideos:"clearSelectedVideos",inputRemoveSelectedVideo:"removeSelectedVideo",inputAddSelectedFile:"addSelectedFile",inputRemoveSelectedFile:"removeSelectedFile",inputClearSelectedFiles:"clearSelectedFiles",inputToggleGoalArmed:"toggleGoalArmed",inputSetGoalArmed:"setGoalArmed",inputSetGoalRunning:"setGoalRunning",inputSetGoalProgress:"setGoalProgress",inputSetGoalDialogOpen:"setGoalDialogOpen"}),...Ir(I2,{toolRegisterAction:"registerToolAction",toolUnregisterAction:"unregisterToolAction",toolFindAction:"findToolAction",toolTrackAction:"trackToolAction",toolReleaseAction:"releaseToolAction",toolGetLatestAction:"getLatestActiveToolAction",toolResetTracking:"resetToolTracking",toolSetSettings:"setToolSettings",toolSetSettingsLoading:"setToolSettingsLoading"}),...Ir(R2,{resourceUpdateCurrentContextTokens:"updateCurrentContextTokens",resourceFetchConversationTokenStatistics:"fetchConversationTokenStatistics",resourceSetCurrentContextTokens:"setCurrentContextTokens",resourceToggleTokenPanel:"toggleTokenPanel",resourceApplyStatusSnapshot:"applyStatusSnapshot",resourceUpdateContainerStatus:"updateContainerStatus",resourceStartContainerStatsPolling:"startContainerStatsPolling",resourceStopContainerStatsPolling:"stopContainerStatsPolling",resourceStartProjectStoragePolling:"startProjectStoragePolling",resourceStopProjectStoragePolling:"stopProjectStoragePolling",resourceStartUsageQuotaPolling:"startUsageQuotaPolling",resourceStopUsageQuotaPolling:"stopUsageQuotaPolling",resourcePollContainerStats:"pollContainerStats",resourceBindContainerVisibilityWatcher:"bindContainerVisibilityWatcher",resourcePollProjectStorage:"pollProjectStorage",resourceFetchUsageQuota:"fetchUsageQuota",resourceResetTokenStatistics:"resetTokenStatistics",resourceSetUsageQuota:"setUsageQuota"}),...Ir(D2,{uploadHandleSelected:"handleSelectedFiles",uploadBatchFiles:"uploadFiles"}),...Ir(Tc,{fileFetchTree:"fetchFileTree",fileSetTreeFromResponse:"setFileTreeFromResponse",fileFetchTodoList:"fetchTodoList",fileSetTodoList:"setTodoList",fileHideContextMenu:"hideContextMenu",fileMarkTreeUnavailable:"markFileTreeUnavailable"}),...Ir(j2,{monitorSyncDesktop:"syncDesktopFromTree",monitorResetVisual:"resetVisualState",monitorResetSpeech:"resetSpeechBuffer",monitorShowSpeech:"enqueueModelSpeech",monitorShowThinking:"enqueueModelThinking",monitorEndModelOutput:"endModelOutput",monitorShowPendingReply:"showPendingReply",monitorPreviewTool:"previewToolIntent",monitorQueueTool:"enqueueToolEvent",monitorResolveTool:"resolveToolResult",forceUnlockMonitor:"resetVisualState"}),...Ir(oh,{subAgentFetch:"fetchSubAgents"}),...Ir(cm,{backgroundCommandFetch:"fetchCommands"}),...Ir(N2,{focusFetchFiles:"fetchFocusedFiles",focusSetFiles:"setFocusedFiles"}),...Ir(qs,{personalizationOpenDrawer:"openDrawer",personalizationFetch:"fetchPersonalization"})}};mF.components=oZ;const vre={class:"image-picker-panel"},yre={class:"header"},bre={class:"header-left"},_re=["disabled"],Sre={class:"body"},wre={key:0,class:"loading"},kre={key:1,class:"empty"},Cre={key:2,class:"grid"},Tre=["onClick","title"],Are={class:"video-thumb"},Ere={class:"ext"},Mre={class:"name"},xre={class:"footer"},Ire={class:"count"},Rre={class:"actions"},Lre=["disabled"],Pre=at({__name:"VideoPicker",props:{open:{type:Boolean},entries:{},initialSelected:{},loading:{type:Boolean},uploading:{type:Boolean,default:!1}},emits:["close","confirm","local-files"],setup(s,{emit:e}){const t=s,n=e,i=pe(new Set(t.initialSelected||[])),r=pe(null);let o=0;Xe(()=>t.initialSelected,m=>{i.value=new Set(m||[])});const a=ye(()=>t.entries||[]),c=m=>{if(!m)return;const v=new Set(i.value);v.has(m)?v.delete(m):(v.clear(),v.add(m)),i.value=v},l=()=>{Date.now()<o||n("close")},u=()=>n("confirm",Array.from(i.value)),h=()=>{var m;t.uploading||(o=Date.now()+1500,(m=r.value)==null||m.click())},d=m=>{const v=m.target,g=v==null?void 0:v.files,y=g&&g.length?Array.from(g):null;(!y||y.length===0)&&console.warn("[VideoPicker] change fired but files empty — likely WebView compat issue"),n("local-files",y),v&&(v.value="")},p=m=>{var v;return!m||!m.includes(".")?"":(v=m.split(".").pop())==null?void 0:v.toLowerCase()};return Cn(()=>{i.value=new Set(t.initialSelected||[])}),(m,v)=>(F(),Wt(us,{name:"overlay-fade"},{default:Vt(()=>[s.open?(F(),$("div",{key:0,class:"image-picker-backdrop",onClick:Ne(l,["self"])},[E("div",vre,[E("div",yre,[E("div",bre,[v[0]||(v[0]=E("div",{class:"title"},"选择视频(一次最多 1 个)",-1)),E("button",{type:"button",class:"local-btn",disabled:s.uploading,onClick:h},ae(s.uploading?"上传中...":"从本地发送"),9,_re),E("input",{ref_key:"localInput",ref:r,type:"file",class:"file-input-hidden",accept:"video/*",onChange:d},null,544)]),E("button",{class:"close-btn",onClick:l},"×")]),E("div",Sre,[s.loading?(F(),$("div",wre,"加载中...")):a.value.length?(F(),$("div",Cre,[(F(!0),$(Ie,null,tt(a.value,g=>(F(),$("div",{key:g.path,class:ke(["card",{selected:i.value.has(g.path)}]),onClick:y=>c(g.path),title:g.path},[E("div",Are,[v[1]||(v[1]=E("span",{class:"icon icon-sm"},"🎞️",-1)),E("span",Ere,ae(p(g.name)),1)]),E("div",Mre,ae(g.name),1)],10,Tre))),128))])):(F(),$("div",kre,"未找到视频文件"))]),E("div",xre,[E("div",Ire,"已选 "+ae(i.value.size)+" / 1",1),E("div",Rre,[E("button",{type:"button",class:"btn secondary",onClick:l},"取消"),E("button",{type:"button",class:"btn primary",disabled:!i.value.size,onClick:u}," 确认 ",8,Lre)])])])])):ge("",!0)]),_:1}))}}),Ore=Qt(Pre,[["__scopeId","data-v-d233bcfe"]]),Dre=["aria-label"],Nre=["src","alt"],Bre={key:0,class:"image-lightbox__caption"},Fre=at({__name:"ImageLightbox",setup(s){const e=Vs(),t=ye(()=>e.imagePreview),n=()=>{e.closeImagePreview()},i=o=>{o.key==="Escape"&&t.value&&(o.preventDefault(),n())},r=o=>{typeof document>"u"||(o?(document.addEventListener("keydown",i),document.body.style.overflow="hidden"):(document.removeEventListener("keydown",i),document.body.style.overflow=""))};return Xe(t,o=>r(!!o),{immediate:!0}),xn(()=>r(!1)),(o,a)=>(F(),Wt(Sp,{to:"body"},[Qe(us,{name:"lightbox-fade"},{default:Vt(()=>[t.value?(F(),$("div",{key:0,class:"image-lightbox",role:"dialog","aria-modal":"true","aria-label":t.value.name||"图片预览",onClick:Ne(n,["self"])},[E("button",{type:"button",class:"image-lightbox__close","aria-label":"关闭预览",onClick:Ne(n,["stop"])}," × "),E("div",{class:"image-lightbox__stage",onClick:Ne(n,["self"])},[E("img",{class:"image-lightbox__img",src:t.value.url,alt:t.value.name||"图片预览",draggable:"false"},null,8,Nre),t.value.name?(F(),$("div",Bre,ae(t.value.name),1)):ge("",!0)])],8,Dre)):ge("",!0)]),_:1})]))}}),$re=Qt(Fre,[["__scopeId","data-v-0ed2e5c7"]]),Hre={class:"qd-window__header"},Ure={class:"qd-window__counter"},Wre={class:"qd-todo-text"},a2=60,l2=45,zre=260,jre=at({__name:"TodoWindow",setup(s){const e=Tc(),t=ye(()=>e.todoList),n=pe([]),i=pe(!1),r=pe(!1),o=pe(!1),a=pe(null);let c=0;const l=ye(()=>n.value.filter(_=>_.done).length),u=_=>new Promise(w=>setTimeout(w,_));function h(_){return Array.isArray(_==null?void 0:_.tasks)?_.tasks:[]}function d(_){return _.map(w=>`${w.index}:${w.title}`).join("|")}function p(_){return _==="done"||_==="completed"}function m(_){if(_.entering&&_.enterDelay)return{animationDelay:`${_.enterDelay}ms`};if(_.leaving&&_.leaveDelay)return{animationDelay:`${_.leaveDelay}ms`}}async function v(){const _=n.value;_.length&&(_.forEach((w,S)=>{w.leaveDelay=S*l2,w.leaving=!0}),await u(_.length*l2+zre+20))}function g(_,w=0){n.value=_.map((T,k)=>({key:`${T.index}:${T.title}`,title:T.title,done:p(T.status),entering:!0,leaving:!1,justDone:!1,enterDelay:w+k*a2,leaveDelay:0}));const S=w+_.length*a2+340+30,C=c;setTimeout(()=>{C===c&&n.value.forEach(T=>{T.entering=!1,T.enterDelay=0})},S)}function y(_){return new Promise(w=>{ft(()=>{const S=a.value,C=S==null?void 0:S.children[_];if(!S||!C){w();return}const T=S.getBoundingClientRect(),k=C.getBoundingClientRect();if(k.top>=T.top&&k.bottom<=T.bottom){w();return}let M=!1,R;const P=()=>{M||(M=!0,R&&clearTimeout(R),S.removeEventListener("scroll",L),w())},L=()=>{R&&clearTimeout(R),R=setTimeout(P,90)};S.addEventListener("scroll",L),C.scrollIntoView({behavior:"smooth",block:"nearest"}),R=setTimeout(P,800)})})}function b(_){n.value=_.map(w=>({key:`${w.index}:${w.title}`,title:w.title,done:p(w.status),entering:!1,leaving:!1,justDone:!1,enterDelay:0,leaveDelay:0}))}return Xe(t,async(_,w)=>{const S=++c,C=h(_),T=h(w),k=e.todoListLive;if(!C.length){if(n.value.length&&k){if(o.value=!0,await v(),S!==c)return;o.value=!1}n.value=[],i.value=!1;return}if(!n.value.length){i.value=!0,k?(r.value=!0,setTimeout(()=>{r.value=!1},320),g(C,300)):b(C);return}if(d(T)===d(C)){if(!k){C.forEach((A,M)=>{const R=n.value[M];R&&(R.done=p(A.status))});return}for(let A=0;A<C.length;A+=1){const M=n.value[A];if(!M)continue;const R=p(C[A].status);if(M.done!==R){for(;o.value;)if(await u(50),S!==c)return;if(R&&(await y(A),S!==c))return;if(M.done=R,R){M.justDone=!0;const P=M;setTimeout(()=>{P.justDone=!1},400)}}}return}if(!k){b(C);return}o.value=!0,await v(),S===c&&(g(C),o.value=!1)},{flush:"sync",immediate:!0}),(_,w)=>i.value?(F(),$("section",{key:0,class:ke(["qd-window",{"qd-window-enter":r.value}])},[E("header",Hre,[w[0]||(w[0]=mi('<svg class="qd-window__icon" viewBox="0 0 16 16" fill="none"><path d="M2 4.5 3.5 6 6 3.5" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"></path><path d="M8.5 5H14" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"></path><path d="M2 11 3.5 12.5 6 10" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"></path><path d="M8.5 11.5H14" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"></path></svg><span class="qd-window__title">待办事项</span>',2)),E("span",Ure,ae(l.value)+"/"+ae(n.value.length),1)]),E("ul",{ref_key:"listRef",ref:a,class:"qd-list"},[(F(!0),$(Ie,null,tt(n.value,S=>(F(),$("li",{key:S.key,class:ke(["qd-todo-item",{"is-done":S.done,"just-done":S.justDone,"qd-row-enter":S.entering,"qd-row-leave":S.leaving}]),style:Ke(m(S))},[w[1]||(w[1]=E("span",{class:"qd-todo-dot"},null,-1)),E("span",Wre,ae(S.title),1)],6))),128))],512)],2)):ge("",!0)}}),Vre={class:"qd-window__header"},Gre={class:"qd-window__title"},qre={ref:"listRef",class:"wf-list"},Kre={class:"wf-row__name"},Qre={key:0,class:"wf-row__meta"},Xre={key:1,class:"wf-row__meta"},Yre={class:"wf-footnote__text"},Jre=420,Zre=660,eoe=240,toe=240,soe=1600,noe=at({__name:"WorkflowWindow",setup(s){const e=um(),{snapshot:t}=Ii(e),n=pe([]),i=pe(!1),r=pe(!1),o=pe(!1),a=pe(null),c=pe(!1),l=pe(null);let u=0,h=0;const d=k=>new Promise(A=>setTimeout(A,k));function p(k){return{"is-done":k.kind==="done","is-current":k.kind==="current","is-next":k.kind==="next","is-just-done":k.justDone,"is-reviving":k.reviving,"is-leaving":k.leaving,"is-entering":k.entering,"is-reject-flash":k.rejectFlash,"is-reviewing":k.reviewing}}function m(k,A,M){return h+=1,{key:`${A}-${k}-${h}`,name:k,kind:A,rounds:M,reviewing:!1,justDone:!1,reviving:!1,leaving:!1,entering:!1,rejectFlash:!1}}function v(k){const A=k.history.map(M=>m(M.name,"done",M.rounds));if(k.current){const M=m(k.current.name,"current",k.current.rounds);M.reviewing=k.reviewing,A.push(M),k.next&&A.push(m(k.next,"next",null))}else k.status==="completed"&&A.push(m("结束","done",null));return A}function g(k){return ft(()=>{const A=l.value;if(!A)return;const M=A.scrollHeight;if(!k){A.scrollTop=M;return}return y(A,M,Jre)})}function y(k,A,M){return new Promise(R=>{const P=k.scrollTop,L=A-P;if(Math.abs(L)<1){k.scrollTop=A,R();return}const z=performance.now(),Q=W=>{const V=Math.min(1,(W-z)/M),N=1-Math.pow(1-V,3);k.scrollTop=P+L*N,V<1?requestAnimationFrame(Q):R()};requestAnimationFrame(Q)})}function b(k){n.value=v(k),g(!1)}function _(k,A){var P,L,z;const M=k.history.map(Q=>Q.name),R=A.history.map(Q=>Q.name);return R.length===M.length+1&&R[R.length-1]===((P=k.current)==null?void 0:P.name)?"advance":R.length<M.length&&M.slice(0,R.length).every((Q,W)=>Q===R[W])?"reject":R.join("|")===M.join("|")&&((L=A.current)==null?void 0:L.name)===((z=k.current)==null?void 0:z.name)&&A.next===k.next?"update":"replace"}async function w(k,A){if(await g(!0),A!==u)return;const M=n.value.find(P=>P.kind==="current"),R=n.value.find(P=>P.kind==="next");if(M&&(M.kind="done",M.reviewing=!1,M.justDone=!0),R&&(R.kind=k.current?"current":"done"),k.current&&k.next){const P=m(k.next,"next",null);P.entering=!0,n.value.push(P)}await g(!0),A===u&&b(k)}async function S(k,A,M){var z;const R=n.value.find(Q=>Q.kind==="current");if(R&&(R.rejectFlash=!0),await d(Zre),M!==u)return;const P=A.history.length,L=n.value[P];n.value.forEach((Q,W)=>{W>P&&Q.kind!=="current"&&(Q.leaving=!0)}),L&&L.kind==="done"&&(L.kind="current",L.reviving=!0,L.rounds=((z=A.current)==null?void 0:z.rounds)??null),R&&(R.rejectFlash=!1,R.kind="next",R.rounds=null,R.reviewing=!1),await d(eoe),M===u&&(n.value=n.value.filter(Q=>!Q.leaving),await g(!0),M===u&&b(A))}function C(k){const A=n.value.find(M=>M.kind==="current");A&&k.current&&(A.reviewing=k.reviewing,A.rounds=k.current.rounds)}async function T(k){o.value=!0,await d(toe),k===u&&(o.value=!1)}return Xe(t,async(k,A)=>{const M=++u,R=e.live;if(!k.active){if(A!=null&&A.active&&R&&n.value.length&&(await T(M),M!==u))return;n.value=[],a.value=null,i.value=!1;return}if(a.value=k.footnote,!(A!=null&&A.active)||!n.value.length){i.value=!0,b(k),R&&(r.value=!0,setTimeout(()=>{r.value=!1},320));return}if(!R){b(k);return}const P=_(A,k);if(P==="advance"?await w(k,M):P==="reject"?await S(A,k,M):P==="update"?C(k):b(k),k.status==="completed"&&M===u){if(await d(soe),M!==u||(await T(M),M!==u))return;n.value=[],a.value=null,i.value=!1,e.reset()}},{flush:"sync",immediate:!0}),Xe(()=>e.exiting,async k=>{if(!k)return;const A=++u;if(await T(A),A!==u){o.value=!1;return}o.value=!1,n.value=[],a.value=null,i.value=!1,e.finishExit()},{flush:"sync"}),Xe(()=>t.value.footnote,(k,A)=>{k&&k!==A&&(c.value=!0,setTimeout(()=>{c.value=!1},260))}),(k,A)=>i.value?(F(),$("section",{key:0,class:ke(["qd-window",{"qd-window-enter":r.value,"qd-window-exit":o.value}])},[E("header",Vre,[A[0]||(A[0]=mi('<svg class="qd-window__icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="4.6" r="2.6"></circle><path d="M12 7.2 V10.1"></path><path d="M8.5 12.3 L12 10.1 L15.5 12.3 L12 14.5 Z" stroke-linejoin="miter"></path><path d="M8.5 12.3 H6.1 Q4.5 12.3 4.5 13.9 V16.3"></path><path d="M15.5 12.3 H17.9 Q19.5 12.3 19.5 13.9 V16.3"></path><rect x="2.4" y="16.3" width="4.2" height="4.2" rx="1.1"></rect><rect x="17.4" y="16.3" width="4.2" height="4.2" rx="1.1"></rect></svg>',1)),E("span",Gre,ae(We(t).name),1)]),E("div",{ref_key:"viewportRef",ref:l,class:"wf-viewport"},[E("ul",qre,[(F(!0),$(Ie,null,tt(n.value,M=>(F(),$("li",{key:M.key,class:ke(["wf-row",p(M)])},[A[2]||(A[2]=E("span",{class:"wf-row__dot"},null,-1)),E("span",Kre,ae(M.name),1),M.kind==="current"&&M.reviewing?(F(),$("span",Qre,[...A[1]||(A[1]=[E("span",{class:"wf-spinner"},null,-1),hn("审核中 ",-1)])])):M.rounds!=null&&M.kind!=="next"?(F(),$("span",Xre,ae(M.rounds)+" 轮 ",1)):ge("",!0)],2))),128))],512)],512),a.value?(F(),$("div",{key:0,class:ke(["wf-footnote",[`wf-footnote--${a.value.kind}`,{"is-entering":c.value}]])},[A[3]||(A[3]=E("span",{class:"wf-footnote__dot"},null,-1)),E("span",Yre,ae(a.value.text),1)],2)):ge("",!0)],2)):ge("",!0)}}),ioe={class:"qd-window__header"},roe={key:0,class:"qd-window__icon",viewBox:"0 0 16 16",fill:"none"},ooe={key:1,class:"qd-window__icon",viewBox:"0 0 16 16",fill:"none"},aoe={class:"qd-window__title"},loe={class:"qd-window__counter"},coe=["data-kind","onClick"],uoe=["title"],hoe=["onClick"],c2=at({__name:"RunnerWindow",props:{kind:{}},setup(s){function e(b){return b==="idle"?"idle":b==="completed"?"done":b==="failed"||b==="timeout"||b==="terminated"||b==="cancelled"?"ended":"running"}function t(b){return b==="completed"?"done":b==="failed"||b==="timeout"||b==="cancelled"?"ended":"running"}const n=s,i=oh(),r=cm(),o=Bo(),{detail:a}=Ii(o),c=pe([]),l=pe(!1),u=pe(null);let h=!1;const d=ye(()=>n.kind==="agent"?i.subAgents.map(b=>{const _=(b.task_id||"").toString();if(!_)return null;const w=(b.status||"").toString().toLowerCase();return{id:_,name:b.display_name||b.summary||`子智能体 ${b.agent_id??_}`,state:e(w)}}).filter(b=>b!==null):r.commands.map(b=>{const _=(b.command_id||"").toString();if(!_)return null;const w=(b.status||"").toString().toLowerCase();return{id:_,name:b.command||_,state:t(w)}}).filter(b=>b!==null));function p(b){var _,w;return((_=a.value)==null?void 0:_.kind)===n.kind&&((w=a.value)==null?void 0:w.id)===b.id}function m(b){o.closeMenu(),o.openDetail(n.kind,b.id)}function v(b,_){const S=b.currentTarget.getBoundingClientRect();o.openMenu({type:"runner",kind:n.kind,key:_.id,left:S.right,top:S.bottom+6,alignRight:!0})}function g(b){return new Promise(_=>{const w=u.value;if(!w){_();return}const S=w.getBoundingClientRect(),C=b.getBoundingClientRect();if(C.top>=S.top&&C.bottom<=S.bottom){_();return}let k=!1,A;const M=()=>{k||(k=!0,A&&clearTimeout(A),w.removeEventListener("scroll",R),_())},R=()=>{A&&clearTimeout(A),A=setTimeout(M,90)};w.addEventListener("scroll",R),b.scrollIntoView({behavior:"smooth",block:"nearest"}),A=setTimeout(M,800)})}async function y(b,_=0){_>0&&await new Promise(T=>setTimeout(T,_)),await ft();const w=u.value,S=c.value.indexOf(b),C=w==null?void 0:w.children[S];if(!C){b.pendingEnter=!1,b.entering=!0,setTimeout(()=>{b.entering=!1},380);return}await g(C),b.pendingEnter=!1,b.entering=!0,setTimeout(()=>{b.entering=!1},380)}return Xe(d,b=>{const _=new Map(b.map(T=>[T.id,T]));c.value=c.value.filter(T=>_.has(T.id)),c.value.forEach(T=>{const k=_.get(T.id);k&&(T.name=k.name,T.state=k.state)});const w=new Set(c.value.map(T=>T.id)),S=b.filter(T=>!w.has(T.id)),C=S.some(T=>T.state==="running");if(S.length){const T=C&&!h&&!c.value.length;T&&(h=!0,l.value=!0,setTimeout(()=>{l.value=!1},320)),S.forEach((k,A)=>{const M={id:k.id,name:k.name,state:k.state,entering:!1,pendingEnter:C};if(c.value.push(M),C){const R=(T?300:0)+A*60;y(c.value[c.value.length-1],R)}})}},{immediate:!0}),(b,_)=>c.value.length?(F(),$("section",{key:0,class:ke(["qd-window",{"qd-window-enter":l.value}])},[E("header",ioe,[s.kind==="agent"?(F(),$("svg",roe,[..._[0]||(_[0]=[E("circle",{cx:"8",cy:"5.5",r:"2.5",stroke:"currentColor","stroke-width":"1.4"},null,-1),E("path",{d:"M3 13c.7-2.6 2.7-4 5-4s4.3 1.4 5 4",stroke:"currentColor","stroke-width":"1.4","stroke-linecap":"round"},null,-1)])])):(F(),$("svg",ooe,[..._[1]||(_[1]=[E("path",{d:"M2.5 4.5 6 8l-3.5 3.5",stroke:"currentColor","stroke-width":"1.4","stroke-linecap":"round","stroke-linejoin":"round"},null,-1),E("path",{d:"M8 12h5.5",stroke:"currentColor","stroke-width":"1.4","stroke-linecap":"round"},null,-1)])])),E("span",aoe,ae(s.kind==="agent"?"子智能体":"后台指令"),1),E("span",loe,ae(c.value.length),1)]),E("ul",{ref_key:"listRef",ref:u,class:"qd-list"},[(F(!0),$(Ie,null,tt(c.value,w=>(F(),$("li",{key:w.id,class:ke(["qd-run-item",[`is-${w.state}`,{"is-active":p(w),"qd-row-enter":w.entering}]]),"data-kind":s.kind,style:Ke(w.pendingEnter?{opacity:"0"}:void 0),onClick:S=>m(w)},[_[3]||(_[3]=E("span",{class:"qd-run-status"},null,-1)),E("span",{class:"qd-run-name",title:w.name},ae(w.name),9,uoe),E("button",{class:"qd-row-menu-btn",title:"更多",onClick:Ne(S=>v(S,w),["stop"])},[..._[2]||(_[2]=[E("svg",{viewBox:"0 0 16 16"},[E("circle",{cx:"3.5",cy:"8",r:"1.3",fill:"currentColor"}),E("circle",{cx:"8",cy:"8",r:"1.3",fill:"currentColor"}),E("circle",{cx:"12.5",cy:"8",r:"1.3",fill:"currentColor"})],-1)])],8,hoe)],14,coe))),128))],512)],2)):ge("",!0)}}),doe={class:"qd-detail__header"},foe=["title"],poe=["title"],goe={key:0,class:"qd-detail__empty"},moe={key:0,class:"qd-tool-spinner"},voe={key:1,class:"qd-tool-done"},yoe={class:"tool-name"},boe=["title"],_oe={key:0,class:"qd-detail__empty"},Soe=at({__name:"RunnerDetailPanel",setup(s){const e=new Set(["completed","failed","timeout","terminated"]),t=new Set(["completed","failed","timeout","cancelled"]),n=Bo(),i=oh(),r=cm(),{detail:o}=Ii(n),{activityEntries:a,activityLoading:c}=Ii(i),{activeDetail:l,detailLoading:u}=Ii(r),h=pe(null);Xe(o,I=>{I&&(h.value={kind:I.kind,id:I.id})},{immediate:!0});const d=ye(()=>o.value||h.value),p=pe(""),m=ye(()=>{var J,he;const I=d.value;if(!I)return"";if(I.kind==="agent"){const be=i.subAgents.find(rt=>rt.task_id===I.id),Re=((J=i.activeAgent)==null?void 0:J.task_id)===I.id?i.activeAgent:null;return String((Re==null?void 0:Re.status)||(be==null?void 0:be.status)||"")}const K=r.commands.find(be=>be.command_id===I.id),X=((he=r.activeCommand)==null?void 0:he.command_id)===I.id?r.activeCommand:null;return String((X==null?void 0:X.status)||(K==null?void 0:K.status)||"")});Xe(m,I=>{I&&(p.value=I)},{immediate:!0});const v=pe(!1),g=pe(!1),y=pe(!1),b=pe(!1),_=pe(null),w=ye(()=>m.value||p.value||""),S=ye(()=>{const I=w.value.toLowerCase();return!d.value||!I||I==="idle"?!1:!(d.value.kind==="agent"?e:t).has(I)}),C=ye(()=>{const I=w.value.toLowerCase();return I==="idle"?"idle":S.value?"running":I==="completed"?"done":"ended"}),T=ye(()=>{var K,X;if(!d.value)return"";if(d.value.kind==="agent"){const J=i.subAgents.find(he=>{var be;return he.task_id===((be=d.value)==null?void 0:be.id)});return(J==null?void 0:J.display_name)||(J==null?void 0:J.summary)||((K=i.activeAgent)==null?void 0:K.display_name)||"子智能体"}const I=r.commands.find(J=>{var he;return J.command_id===((he=d.value)==null?void 0:he.id)});return(I==null?void 0:I.command)||((X=r.activeCommand)==null?void 0:X.command)||"后台指令"}),k=ye(()=>{const I=w.value.toLowerCase();return I==="idle"?"空闲":S.value?"运行中":I==="completed"?"已完成":I==="failed"?"已失败":I==="timeout"?"已超时":I==="terminated"||I==="cancelled"?"已终止":"已结束"}),A=ye(()=>{const I=d.value;if(!I||I.kind!=="agent")return 0;const K=i.subAgents.find(J=>J.task_id===I.id),X=Number(K==null?void 0:K.current_context_tokens);return Number.isFinite(X)&&X>0?X:0}),M=pe(0);Xe(A,I=>{I>0&&(M.value=I)},{immediate:!0});const R=ye(()=>A.value||M.value);function P(I){return!I||I<=0?"":I>=1e3?`${(I/1e3).toFixed(1)}k Tokens`:`${I} Tokens`}const L=ye(()=>{var I;return((I=d.value)==null?void 0:I.kind)!=="agent"?"":P(R.value)}),z=ye(()=>`上下文 ${R.value.toLocaleString()} tokens`);function Q(I){return I==="running"||I==="in_progress"?"running":I==="completed"||I==="done"||I==="success"?"completed":I==="failed"||I==="error"?"failed":I||"running"}function W(I){const K=(I||"").toString().toLowerCase();return["completed","failed","timeout","terminated","cancelled","done","success","error"].includes(K)}function V(I){const K=I.tool||"",X=I.args||{};return K==="read_file"?`阅读 ${X.path||X.file_path||""}`:K==="write_file"?`写入文件 ${X.file_path||X.path||""}`:K==="read_skill"?`阅读技能 ${X.skill_name||""}`:K==="web_search"?`搜索 ${X.query||X.q||""}`:K==="extract_webpage"?`提取 ${X.url||""}`:K==="run_command"?`运行命令 ${X.command||""}`:K==="edit_file"?`编辑 ${X.path||X.file_path||""}`:K==="read_mediafile"?`读取媒体文件 ${X.path||X.file_path||""}`:K||"工具"}const N=ye(()=>{const I=a.value||[],K=[];let X=null;const J=()=>{X&&(K.push(X),X=null)};return I.forEach((he,be)=>{if((he==null?void 0:he.type)==="progress"&&(he==null?void 0:he.subtype)==="output"&&typeof he.content=="string"){J(),K.push({kind:"output",key:`output-${he.ts||be}`,content:he.content});return}if(!he||he.type!=="progress"||!he.tool)return;const Re=he.id||`${he.tool}-${he.ts||be}`;if(X&&(X.entry.id===he.id||X.key===Re)&&!W(X.entry.status)){X.entry={...X.entry,...he};return}J();let rt=Re,st=0;for(;K.some(et=>et.kind==="tool"&&et.key===rt);)st+=1,rt=`${Re}--${st}`;X={kind:"tool",key:rt,entry:{...he}}}),J(),K.map(he=>{if(he.kind==="output")return he;const be=Q(he.entry.status);return{kind:"tool",key:he.key,state:be,stateLabel:be==="completed"?"完成":be==="failed"?"失败":"进行中",toolName:he.entry.tool||"工具",text:V(he.entry)}})}),O=ye(()=>{var K,X;if(((K=d.value)==null?void 0:K.kind)!=="cmd")return[];const I=(X=l.value)==null?void 0:X.output;return typeof I!="string"?[]:I.split(`
`)}),H=pe(new Set);let G=new Set,ee=!1;function ie(){G=new Set,ee=!1,H.value=new Set}Xe([N,O],()=>{var X;const I=((X=d.value)==null?void 0:X.kind)==="agent"?N.value.map(J=>J.key):O.value.map((J,he)=>`term-${he}`);if(!ee){if(!I.length)return;ee=!0,I.forEach(J=>G.add(J)),ft(()=>ve(!1));return}const K=I.filter(J=>!G.has(J));K.length&&(K.forEach(J=>G.add(J)),H.value=new Set(K),setTimeout(()=>{H.value=new Set},400))},{flush:"post"}),Xe(o,(I,K)=>{if(!I){const X=()=>{(K==null?void 0:K.kind)==="agent"&&i.closeSubAgent(),(K==null?void 0:K.kind)==="cmd"&&r.closeCommand()};v.value?(g.value=!1,y.value=!0,setTimeout(()=>{y.value=!1,v.value=!1,X()},190)):X();return}if((K==null?void 0:K.kind)==="agent"&&i.closeSubAgent(),(K==null?void 0:K.kind)==="cmd"&&r.closeCommand(),ie(),I.kind==="agent"){const X=i.subAgents.find(J=>J.task_id===I.id);X&&i.openSubAgent(X,{silent:!0})}else{const X=r.commands.find(J=>J.command_id===I.id);X&&r.openCommand(X,{silent:!0})}v.value?(b.value=!1,ft(()=>{b.value=!0,ve(!1),setTimeout(()=>{b.value=!1},200)})):(v.value=!0,g.value=!0,setTimeout(()=>{g.value=!1},260),ft(()=>{ve(!1)}))},{immediate:!0});function ve(I){const K=_.value;K&&K.scrollTo({top:K.scrollHeight,behavior:I?"smooth":"auto"})}function le(){const I=_.value;if(!I||!ee)return;I.scrollHeight-I.scrollTop-I.clientHeight<80&&ft(()=>ve(!0))}Xe(()=>[N.value.length,O.value.length],()=>{le()});function oe(){n.closeDetail()}return(I,K)=>{var X;return v.value?(F(),$("section",{key:0,class:ke(["qd-detail",{"panel-enter":g.value,"panel-leave":y.value}])},[E("header",doe,[E("span",{class:ke(["qd-detail__dot",`is-${C.value}`])},null,2),E("span",{class:"qd-detail__title",title:T.value},ae(T.value),9,foe),E("span",{class:ke(["qd-detail__badge",`is-${C.value}`])},ae(k.value),3),L.value?(F(),$("span",{key:0,class:"qd-detail__tokens",title:z.value},ae(L.value),9,poe)):ge("",!0),E("button",{class:"qd-detail__close",title:"关闭",onClick:oe},[...K[0]||(K[0]=[E("svg",{viewBox:"0 0 16 16",fill:"none"},[E("path",{d:"M4 4l8 8M12 4l-8 8",stroke:"currentColor","stroke-width":"1.4","stroke-linecap":"round"})],-1)])])]),E("div",{ref_key:"bodyRef",ref:_,class:ke(["qd-detail__body",{"body-fade":b.value}])},[((X=d.value)==null?void 0:X.kind)==="agent"?(F(),$(Ie,{key:0},[N.value.length?ge("",!0):(F(),$("div",goe,ae(We(c)?"加载中…":"暂无进度"),1)),(F(!0),$(Ie,null,tt(N.value,J=>(F(),$("div",{key:J.key,class:ke(["qd-feed-row",[J.kind==="tool"?"feed-tool":"feed-text",{"is-new":H.value.has(J.key)}]])},[J.kind==="tool"?(F(),$(Ie,{key:0},[J.state==="running"?(F(),$("span",moe)):(F(),$("span",voe,ae(J.state==="failed"?"✕":"✓"),1)),E("span",yoe,ae(J.toolName),1),E("span",{class:"tool-param",title:J.text},ae(J.text),9,boe),E("span",{class:ke(["tool-result",{"is-error":J.state==="failed"}])},ae(J.stateLabel),3)],64)):(F(),$(Ie,{key:1},[hn(ae(J.content),1)],64))],2))),128))],64)):(F(),$(Ie,{key:1},[O.value.length?ge("",!0):(F(),$("div",_oe,ae(We(u)?"加载中…":"暂无输出"),1)),(F(!0),$(Ie,null,tt(O.value,(J,he)=>(F(),$("div",{key:he,class:ke(["qd-feed-row feed-term",{"is-new":H.value.has(`term-${he}`)}])},ae(J),3))),128))],64))],2)],2)):ge("",!0)}}}),woe={class:"qd-window__header"},koe={class:"qd-window__counter"},Coe=["title","onClick"],Toe=["onClick"],Aoe={class:"qd-file-name"},Eoe=at({__name:"FileWindow",setup(s){const e=Bo(),{editedFiles:t,previewPath:n}=Ii(e),i=pe([]),r=pe(!1),o=pe(null);let a=!1;function c(m){return m.split("/").pop()||m}function l(m){e.closeMenu(),e.openPreview(m.path)}function u(m,v){const y=m.currentTarget.getBoundingClientRect();e.openMenu({type:"file",key:v.path,left:y.left,top:y.bottom+6,alignRight:!1})}function h(m){return new Promise(v=>{const g=o.value;if(!g){v();return}const y=g.getBoundingClientRect(),b=m.getBoundingClientRect();if(b.top>=y.top&&b.bottom<=y.bottom){v();return}let w=!1,S;const C=()=>{w||(w=!0,S&&clearTimeout(S),g.removeEventListener("scroll",T),v())},T=()=>{S&&clearTimeout(S),S=setTimeout(C,90)};g.addEventListener("scroll",T),m.scrollIntoView({behavior:"smooth",block:"nearest"}),S=setTimeout(C,800)})}async function d(m,v=0){v>0&&await new Promise(_=>setTimeout(_,v)),await ft();const g=o.value,y=i.value.indexOf(m),b=g==null?void 0:g.children[y];if(!b){m.pendingEnter=!1,m.entering=!0,setTimeout(()=>{m.entering=!1},380);return}await h(b),m.pendingEnter=!1,m.entering=!0,setTimeout(()=>{m.entering=!1},380)}let p=!1;return Xe(t,m=>{const v=e.editedFilesLive&&p;p=!0;const g=new Map(m.map(_=>[_.path,_]));i.value=i.value.filter(_=>g.has(_.path));const y=new Set(i.value.map(_=>_.path)),b=m.filter(_=>!y.has(_.path));if(b.length){const _=v&&!a&&!i.value.length;_&&(a=!0,r.value=!0,setTimeout(()=>{r.value=!1},320)),b.forEach((w,S)=>{const C={path:w.path,entering:!1,pendingEnter:v};if(i.value.push(C),v){const T=(_?300:0)+S*60;d(i.value[i.value.length-1],T)}})}},{immediate:!0}),(m,v)=>i.value.length?(F(),$("section",{key:0,class:ke(["qd-window",{"qd-window-enter":r.value}])},[E("header",woe,[v[0]||(v[0]=E("svg",{class:"qd-window__icon",viewBox:"0 0 16 16",fill:"none"},[E("path",{d:"M4 2.5h5.5L12 5v8.5H4V2.5z",stroke:"currentColor","stroke-width":"1.3","stroke-linejoin":"round"}),E("path",{d:"M9.5 2.5V5H12",stroke:"currentColor","stroke-width":"1.3","stroke-linejoin":"round"})],-1)),v[1]||(v[1]=E("span",{class:"qd-window__title"},"文件",-1)),E("span",koe,ae(i.value.length),1)]),E("ul",{ref_key:"listRef",ref:o,class:"qd-list"},[(F(!0),$(Ie,null,tt(i.value,g=>(F(),$("li",{key:g.path,class:ke(["qd-file-item",{"is-active":We(n)===g.path,"qd-row-enter":g.entering}]),style:Ke(g.pendingEnter?{opacity:"0"}:void 0),title:g.path,onClick:y=>l(g)},[E("button",{class:"qd-row-menu-btn",title:"更多",onClick:Ne(y=>u(y,g),["stop"])},[...v[2]||(v[2]=[E("svg",{viewBox:"0 0 16 16"},[E("circle",{cx:"3.5",cy:"8",r:"1.3",fill:"currentColor"}),E("circle",{cx:"8",cy:"8",r:"1.3",fill:"currentColor"}),E("circle",{cx:"12.5",cy:"8",r:"1.3",fill:"currentColor"})],-1)])],8,Toe),E("span",Aoe,ae(c(g.path)),1)],14,Coe))),128))],512)],2)):ge("",!0)}}),Moe=["disabled"],xoe=300,Ioe=3e3,Roe=128,Loe=at({__name:"QuickDock",props:{hostMode:{type:Boolean}},setup(s){const e=Bo(),t=oh(),n=cm(),i=vr(),r=Vs(),o=Tc(),a=um(),c=qs(),{menu:l,hasContent:u,userCollapsed:h}=Ii(e),d=pe(null);Xe(h,le=>{le&&e.resetTransient()});const p=ye(()=>c.form.quick_dock_auto_expand!==!1),m=ye(()=>W2()||c.loaded||!!c.error),v=pe(!0);let g=0,y=null,b=null,_=null,w=null,S=!0;function C(){return S?!1:y?e.filesSyncSeq>y.filesSeq&&o.todoSyncSeq>y.todoSeq:!0}function T(){_!==null&&(clearTimeout(_),_=null),w!==null&&(clearTimeout(w),w=null)}function k(){g+=1,v.value=!0,y={filesSeq:e.filesSyncSeq,todoSeq:o.todoSyncSeq},T(),b||(b=Xe(()=>[e.filesSyncSeq,o.todoSyncSeq],()=>{A()})),A(),w=setTimeout(()=>{M(!0)},Ioe)}function A(){!v.value||!C()||(_!==null&&clearTimeout(_),_=setTimeout(()=>{_=null,M()},xoe))}function M(le=!1){if(!v.value||!le&&!C())return;T(),b&&(b(),b=null),y=null,e.settleInitialContent();const oe=g;requestAnimationFrame(()=>{requestAnimationFrame(()=>{oe===g&&(v.value=!1)})})}Xe(u,le=>{e.userCollapsed=!p.value},{immediate:!0}),Xe(p,le=>{e.userCollapsed=!le}),Xe(u,le=>{if(!e.assumedActive){TH(le);const oe=i.currentConversationId;oe&&EH(oe,le)}});const R=new Set(["completed","failed","timeout","terminated"]),P=new Set(["completed","failed","timeout","cancelled"]),L=ye(()=>{const le=l.value;if(!le)return{};const oe=Math.min(le.top,window.innerHeight-Roe-8);return le.alignRight?{right:`${window.innerWidth-le.left}px`,top:`${oe}px`}:{left:`${le.left}px`,top:`${oe}px`}}),z=ye(()=>{const le=l.value;if(!le||le.type!=="runner")return!1;if(le.kind==="agent"){const K=t.subAgents.find(J=>J.task_id===le.key),X=((K==null?void 0:K.status)||"").toString().toLowerCase();return!!K&&!R.has(X)}const oe=n.commands.find(K=>K.command_id===le.key),I=((oe==null?void 0:oe.status)||"").toString().toLowerCase();return!!oe&&!P.has(I)});async function Q(){const le=l.value;if(!le||le.type!=="runner")return;e.closeMenu();const oe=le.kind==="agent"?await t.terminateSubAgent(le.key):await n.cancelCommand(le.key);oe!=null&&oe.success||r.pushToast({message:(oe==null?void 0:oe.error)||"强制关闭失败",type:"error"})}function W(le){return le.split("/").pop()||le}function V(){const le=l.value;if(!le||le.type!=="file")return;e.closeMenu();const oe=document.createElement("a");oe.href=`/api/download/file?path=${encodeURIComponent(le.key)}`,oe.download=W(le.key),document.body.appendChild(oe),oe.click(),oe.remove()}async function N(){var I;const le=l.value;if(!le||le.type!=="file")return;const oe=le.key;e.closeMenu();try{const K=await fetch(`/api/project/file-open-apps?path=${encodeURIComponent(oe)}`),X=await K.json().catch(()=>({}));if(!K.ok||!(X!=null&&X.success))throw new Error((X==null?void 0:X.error)||"检测可用应用失败");const J=Array.isArray((I=X==null?void 0:X.data)==null?void 0:I.apps)?X.data.apps:[];if(!J.length)throw new Error("未找到可用应用");const he=await fetch("/api/project/open-file-with-app",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:oe,app_id:J[0].id})}),be=await he.json().catch(()=>({}));if(!he.ok||!(be!=null&&be.success))throw new Error((be==null?void 0:be.error)||"打开文件失败")}catch(K){r.pushToast({message:(K==null?void 0:K.message)||"打开文件失败",type:"error"})}}async function O(){var X;const le=l.value;if(!le||le.type!=="file")return;const oe=le.key;e.closeMenu();const I=(J,he="info")=>r.pushToast({message:J,type:he,duration:2e3});if((X=navigator.clipboard)!=null&&X.writeText)try{await navigator.clipboard.writeText(oe),I("已复制相对路径","success");return}catch{}const K=document.createElement("textarea");K.value=oe,K.style.position="fixed",K.style.opacity="0",document.body.appendChild(K),K.select();try{document.execCommand("copy"),I("已复制相对路径","success")}catch{I("复制失败","error")}K.remove()}function H(le){if(!(le.key!=="Escape"||le.defaultPrevented)){if(l.value){e.closeMenu(),le.preventDefault();return}if(e.detail){e.closeDetail(),le.preventDefault();return}e.previewPath&&(e.closePreview(),le.preventDefault())}}function G(le){if(!l.value)return;const oe=le.target;oe!=null&&oe.closest(".qd-menu")||oe!=null&&oe.closest(".qd-row-menu-btn")||e.closeMenu()}function ee(){l.value&&e.closeMenu()}let ie=null;function ve(){t.fetchSubAgents(),n.fetchCommands()}return Cn(()=>{const le=Promise.allSettled([t.fetchSubAgents(),n.fetchCommands()]);ie=setInterval(ve,5e3),document.addEventListener("keydown",H),document.addEventListener("click",G),k(),le.then(()=>{S=!1,A()})}),xn(()=>{ie&&(clearInterval(ie),ie=null),T(),document.removeEventListener("keydown",H),document.removeEventListener("click",G),e.resetTransient()}),Xe(()=>i.currentConversationId,()=>{e.resetTransient();const le=i.currentConversationId;le?a.fetchStatus(le):a.reset(),ve(),k(),e.assumeContentForConversation(i.currentConversationId)},{flush:"sync"}),(le,oe)=>(F(),$("aside",{class:ke(["quick-dock",{"quick-dock--empty":!m.value||!We(u)||We(h),"quick-dock--no-anim":v.value}])},[E("div",{ref_key:"scrollRef",ref:d,class:"quick-dock__scroll",onScrollPassive:ee},[Qe(noe),Qe(jre),Qe(c2,{kind:"agent"}),Qe(c2,{kind:"cmd"}),Qe(Eoe)],544),Qe(Soe),We(l)?(F(),$("div",{key:0,class:"qd-menu menu-enter",style:Ke(L.value),onClick:oe[0]||(oe[0]=Ne(()=>{},["stop"]))},[We(l).type==="runner"?(F(),$("button",{key:0,class:"qd-menu__item qd-menu__item--danger",disabled:!z.value,onClick:Q}," 强制关闭 ",8,Moe)):(F(),$(Ie,{key:1},[E("button",{class:"qd-menu__item",onClick:V},"下载"),s.hostMode?(F(),$("button",{key:0,class:"qd-menu__item",onClick:N}," 在文件管理器中打开 ")):ge("",!0),E("button",{class:"qd-menu__item",onClick:O},"复制路径")],64))],4)):ge("",!0)],2))}}),Poe={class:"qd-preview__panel"},Ooe={class:"qd-preview__header"},Doe=["title"],Noe=["title"],Boe={class:"qd-preview__body"},Foe={key:0,class:"qd-preview__loading"},$oe={key:1,class:"qd-preview__error"},Hoe={key:0,class:"qd-code qd-code--wrap"},Uoe={class:"qd-code-line-no","aria-hidden":"true"},Woe=["innerHTML"],zoe={class:"qd-code-gutter","aria-hidden":"true"},joe={class:"qd-code-pre"},Voe=["innerHTML"],u2=21,Goe=100*1024,h2="agents_qd_preview_width",d2=320,f2=860,g1=452,qoe=at({__name:"FilePreviewPanel",setup(s){const e=new Set([".txt",".md",".markdown",".csv",".json",".json5",".yaml",".yml",".js",".ts",".jsx",".tsx",".vue",".py",".rb",".go",".rs",".java",".c",".h",".cpp",".hpp",".cs",".php",".swift",".kt",".sh",".bash",".zsh",".ps1",".bat",".cmd",".html",".htm",".css",".scss",".sass",".less",".xml",".svg",".toml",".ini",".cfg",".conf",".log",".sql"]),t=Bo(),{previewPath:n}=Ii(t),r=pe((()=>{if(typeof window>"u"||!window.localStorage)return g1;try{const T=Number(window.localStorage.getItem(h2));return!Number.isFinite(T)||T<=0?g1:Math.max(d2,Math.min(f2,T))}catch{return g1}})());function o(T){T.preventDefault();const k=T.clientX,A=r.value,M=P=>{const L=A+(k-P.clientX);r.value=Math.max(d2,Math.min(f2,L))},R=()=>{document.removeEventListener("mousemove",M),document.removeEventListener("mouseup",R),document.body.style.cursor="",document.body.style.userSelect="";try{window.localStorage.setItem(h2,String(r.value))}catch{}};document.addEventListener("mousemove",M),document.addEventListener("mouseup",R),document.body.style.cursor="col-resize",document.body.style.userSelect="none"}const a=pe(""),c=pe(!1),l=pe(""),u=pe(-1),h=ye(()=>a.value.length>Goe?null:AD(n.value||"")),d=ye(()=>{const T=gT(a.value,h.value);return a.value.endsWith(`
`)?T+`
`:T}),p=ye(()=>a.value?a.value.split(`
`).length:0),m=qs(),v=ye(()=>m.form.file_preview_auto_wrap===!0),g=ye(()=>a.value?a.value.split(`
`).map(T=>gT(T,h.value)):[]),y=ye(()=>{const T=n.value||"";return T.split("/").pop()||T}),b=ye(()=>{const k=(n.value||"").split("/");return k.length>1?`${k.slice(0,-1).join("/")}/`:""});function _(T){const k=T.split("/").pop()||"",A=k.lastIndexOf(".");return A>=0?k.slice(A).toLowerCase():""}let w=0;Xe(n,async T=>{const k=++w;if(a.value="",l.value="",u.value=-1,!!T){if(!e.has(_(T))){l.value="该文件类型不支持预览";return}c.value=!0;try{const A=await fetch(`/api/file/content?path=${encodeURIComponent(T)}`);if(!A.ok){const R=await A.json().catch(()=>({}));throw new Error((R==null?void 0:R.error)||`加载失败HTTP ${A.status}`)}const M=await A.text();if(k!==w)return;a.value=M}catch(A){if(k!==w)return;l.value=(A==null?void 0:A.message)||"加载失败"}finally{k===w&&(c.value=!1)}}},{immediate:!0});function S(T){const A=T.currentTarget.getBoundingClientRect(),M=Math.floor((T.clientY-A.top)/u2);u.value=M>=0&&M<p.value?M:-1}function C(){t.closePreview()}return(T,k)=>(F(),Wt(us,{name:"qd-preview-slide"},{default:Vt(()=>[We(n)?(F(),$("aside",{key:0,class:"qd-preview",style:Ke({width:r.value+"px"})},[E("div",{class:"qd-preview__resize",title:"拖拽调整宽度",onMousedown:o},null,32),E("section",Poe,[E("header",Ooe,[k[2]||(k[2]=E("svg",{viewBox:"0 0 16 16",fill:"none"},[E("path",{d:"M4 2.5h5.5L12 5v8.5H4V2.5z",stroke:"currentColor","stroke-width":"1.3","stroke-linejoin":"round"}),E("path",{d:"M9.5 2.5V5H12",stroke:"currentColor","stroke-width":"1.3","stroke-linejoin":"round"})],-1)),E("span",{class:"qd-preview__name",title:We(n)},ae(y.value),9,Doe),E("span",{class:"qd-preview__path",title:We(n)},ae(b.value),9,Noe),E("button",{class:"qd-preview__close",title:"关闭",onClick:C},[...k[1]||(k[1]=[E("svg",{viewBox:"0 0 16 16",fill:"none"},[E("path",{d:"M4 4l8 8M12 4l-8 8",stroke:"currentColor","stroke-width":"1.4","stroke-linecap":"round"})],-1)])])]),E("div",Boe,[c.value?(F(),$("div",Foe,"加载中…")):l.value?(F(),$("div",$oe,ae(l.value),1)):(F(),$(Ie,{key:2},[v.value?(F(),$("div",Hoe,[(F(!0),$(Ie,null,tt(g.value,(A,M)=>(F(),$("div",{key:M,class:"qd-code-line"},[E("span",Uoe,ae(M+1),1),E("span",{class:"qd-code-line-text",innerHTML:A},null,8,Woe)]))),128))])):(F(),$("div",{key:1,class:"qd-code",onMousemove:S,onMouseleave:k[0]||(k[0]=A=>u.value=-1)},[u.value>=0?(F(),$("div",{key:0,class:"qd-code-hoverline",style:Ke({top:`${u.value*u2}px`})},null,4)):ge("",!0),E("div",zoe,[(F(!0),$(Ie,null,tt(p.value,A=>(F(),$("span",{key:A},ae(A),1))),128))]),E("pre",joe,[E("code",{innerHTML:d.value},null,8,Voe)])],32))],64))])])],4)):ge("",!0)]),_:1}))}}),Koe={key:0,class:"drag-upload-overlay"},Qoe={key:0,class:"app-loading-state"},Xoe={class:"loading-copy"},Yoe={class:"main-container"},Joe={key:0,class:"conversation-ribbon",ref:"titleRibbon"},Zoe=["disabled"],eae={class:"selector-label"},tae={class:"selector-model"},sae={class:"selector-mode"},nae={class:"conversation-ribbon__text"},iae={key:0,class:"model-mode-dropdown",ref:"headerMenu"},rae={class:"dropdown-column","data-tutorial":"header-model-options"},oae={class:"dropdown-list dropdown-list--models"},aae=["onClick","disabled"],lae={class:"item-label"},cae={class:"item-desc"},uae={key:0,class:"item-check"},hae={class:"dropdown-column","data-tutorial":"header-runmode-options"},dae=["onClick","disabled"],fae={class:"item-label"},pae={class:"item-desc"},gae={key:0,class:"item-check"},mae={key:0,class:"dropdown-effort"},vae={key:2,class:"blank-hero-overlay"},yae={class:"blank-hero-text"},bae={key:0,class:"scroll-lock-toggle"},_ae={key:2,class:"qd-toggle-anchor"},Sae=["aria-label","aria-pressed"],wae={class:"right-panels__slot"},kae={class:"right-panels__slot"},Cae={key:0,class:"desktop-approval-overlay"},Tae={class:"mobile-panel-topbar"},Aae=["src"],Eae=["disabled"],Mae={class:"mobile-selector-label"},xae={class:"mobile-selector-model"},Iae={class:"mobile-selector-mode"},Rae=["title"],Lae={key:0,class:"mobile-panel-menu mobile-panel-menu--dropdown"},Pae=["src"],Oae=["src"],Dae=["src"],Nae={key:0,class:"model-mode-dropdown model-mode-dropdown--mobile",ref:"headerMenu"},Bae={class:"dropdown-column","data-tutorial":"header-model-options"},Fae={class:"dropdown-list dropdown-list--models"},$ae=["onClick","disabled"],Hae={class:"item-label"},Uae={key:0,class:"item-check"},Wae={class:"dropdown-column","data-tutorial":"header-runmode-options"},zae=["onClick","disabled"],jae={class:"item-label"},Vae={key:0,class:"item-check"},Gae={key:0,class:"dropdown-effort"},qae={class:"mobile-panel-sheet mobile-panel-sheet--conversation"},Kae={class:"mobile-panel-sheet mobile-panel-sheet--approval"},Qae=at({...mF,__name:"App",setup(s){const e=br(()=>wt(()=>import("./VirtualMonitorSurface.js"),__vite__mapDeps([27,1,3,5,2,4]))),t=br(()=>wt(()=>import("./PathAuthorizationDialog.js"),__vite__mapDeps([28,1,3,29]))),n=tE(),i=qs(),r=new URL("data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%2024%2024'%20fill='none'%20stroke='currentColor'%20stroke-width='2'%20stroke-linecap='round'%20stroke-linejoin='round'%3e%3cpath%20d='M15%2012H3m14%206H3M21%206H3'%20/%3e%3c/svg%3e",import.meta.url).href,o=()=>{var h;if(typeof window>"u")return!1;const l=new URLSearchParams(window.location.search),u=((h=window.navigator)==null?void 0:h.userAgent)||"";return l.has("app_shell")||!!(window!=null&&window.AndroidThemeBridge)||/;\s*wv\)/i.test(u)},a=pe(o());Cn(()=>{a.value=o(),window.setTimeout(()=>{a.value=o()},300)});const c={personal:new URL("data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20width='24'%20height='24'%20viewBox='0%200%2024%2024'%20fill='none'%20stroke='currentColor'%20stroke-width='2'%20stroke-linecap='round'%20stroke-linejoin='round'%20%3e%3cpath%20d='M19%2021v-2a4%204%200%200%200-4-4H9a4%204%200%200%200-4%204v2'%20/%3e%3ccircle%20cx='12'%20cy='7'%20r='4'%20/%3e%3c/svg%3e",import.meta.url).href,newChat:new URL("data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20width='24'%20height='24'%20viewBox='0%200%2024%2024'%20fill='none'%20stroke='currentColor'%20stroke-width='2'%20stroke-linecap='round'%20stroke-linejoin='round'%20%3e%3cpath%20d='M21.174%206.812a1%201%200%200%200-3.986-3.987L3.842%2016.174a2%202%200%200%200-.5.83l-1.321%204.352a.5.5%200%200%200%20.623.622l4.353-1.32a2%202%200%200%200%20.83-.497z'%20/%3e%3cpath%20d='m15%205%204%204'%20/%3e%3c/svg%3e",import.meta.url).href,refresh:new URL("data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%2024%2024'%20width='24'%20height='24'%20fill='none'%20stroke='%23000000'%20stroke-width='2'%20stroke-linecap='round'%20stroke-linejoin='round'%20style='opacity:1;'%3e%3cpath%20d='M3%2012a9%209%200%200%201%209-9a9.75%209.75%200%200%201%206.74%202.74L21%208'/%3e%3cpath%20d='M21%203v5h-5m5%204a9%209%200%200%201-9%209a9.75%209.75%200%200%201-6.74-2.74L3%2016'/%3e%3cpath%20d='M8%2016H3v5'/%3e%3c/svg%3e",import.meta.url).href};return(l,u)=>{const h=Xs("ConversationSidebar"),d=Xs("TokenDrawer"),p=Xs("EffortSlider"),m=Xs("ChatArea"),v=Xs("StatusAvatar"),g=Xs("InputComposer"),y=Xs("TerminalPanel"),b=Xs("GitChangesPanel"),_=Xs("ToolApprovalPanel"),w=Xs("PersonalizationDrawer"),S=Xs("ImagePicker"),C=Xs("ConversationReviewDialog"),T=Xs("SubAgentActivityDialog"),k=Xs("BackgroundCommandDialog"),A=Xs("GoalProgressDialog"),M=Xs("UserQuestionDialog"),R=Xs("PlanApprovalDialog"),P=Xs("VersioningDialog"),L=Xs("TutorialOverlay"),z=Xs("NewUserTutorialPrompt"),Q=Xs("WorkflowDemoShell"),W=Xs("AppShell");return F(),Wt(W,{"download-file":l.downloadFile,"download-folder":l.downloadFolder},{default:Vt(()=>{var V,N;return[Qe(us,{name:"drag-overlay-fade"},{default:Vt(()=>[l.dragOverActive?(F(),$("div",Koe,[...u[27]||(u[27]=[E("div",{class:"drag-upload-content"},[E("div",{class:"drag-upload-icon"},[E("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"1.5"},[E("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),E("polyline",{points:"17 8 12 3 7 8"}),E("line",{x1:"12",y1:"3",x2:"12",y2:"15"})])]),E("div",{class:"drag-upload-text"},"松开鼠标上传图片"),E("div",{class:"drag-upload-hint"},"支持拖拽图片、视频文件到此处")],-1)])])):ge("",!0)]),_:1}),!l.isConnected&&l.messages.length===0?(F(),$("div",Qoe,[u[30]||(u[30]=E("div",{class:"loading-animation","aria-hidden":"true"},[E("div",{class:"boxes"},[E("div",{class:"box"},[E("div"),E("div"),E("div"),E("div")]),E("div",{class:"box"},[E("div"),E("div"),E("div"),E("div")]),E("div",{class:"box"},[E("div"),E("div"),E("div"),E("div")]),E("div",{class:"box"},[E("div"),E("div"),E("div"),E("div")])])],-1)),E("div",Xoe,[u[28]||(u[28]=E("h2",null,"加载中...",-1)),u[29]||(u[29]=E("p",null,"正在连接服务器,请稍候",-1)),E("button",{type:"button",class:"loading-refresh-btn",onClick:u[0]||(u[0]=(...O)=>l.refreshCurrentPage&&l.refreshCurrentPage(...O))}," 刷新页面 ")])])):(F(),$(Ie,{key:1},[E("div",Yoe,[l.isMobileViewport?ge("",!0):(F(),Wt(h,{key:0,"icon-style":l.iconStyle,"format-time":l.formatTime,"running-tasks":l.runningWorkspaceTasks,"current-task-in-progress":l.taskInProgress,"current-conversation-id":l.currentConversationId,"current-workspace-id":l.currentHostWorkspaceId,"default-workspace-id":l.defaultHostWorkspaceId,workspaces:l.hostWorkspaces,"workspace-kind":l.versioningHostMode?"workspace":"project","host-workspace-enabled":l.versioningHostMode||l.dockerProjectMode,"workspace-busy":l.hostWorkspaceSwitching||l.hostWorkspaceManageSubmitting,"workspace-create-submitting":l.hostWorkspaceCreateSubmitting,"workspace-error":l.hostWorkspaceCreateError,"group-by-workspace":(N=(V=We(i))==null?void 0:V.form)==null?void 0:N.group_sidebar_by_workspace,"versioning-host-mode":l.versioningHostMode,onToggle:l.toggleSidebar,onCreate:l.createNewConversation,onSearch:l.handleSidebarSearchInput,onSearchSubmit:l.handleSidebarSearchSubmit,onSearchMore:l.loadMoreSearchResults,onSelect:l.loadConversation,onSelectRunningTask:l.openRunningWorkspaceTask,onLoadMore:l.loadMoreConversations,onPersonal:l.openPersonalPage,onDelete:l.deleteConversation,onDuplicate:l.duplicateConversation,onSwitchWorkspace:l.handleHostWorkspaceSwitch,onCreateWorkspace:l.submitHostWorkspaceCreateFromManage,onDeleteWorkspace:l.handleDeleteWorkspaceFromSwitcher,onSetDefaultWorkspace:l.setDefaultHostWorkspace,onSelectWorkspaceConversation:l.handleSelectWorkspaceConversation,onCreateWorkspaceConversation:l.createWorkspaceConversation,onRevealWorkspace:l.revealHostWorkspace,onRenameWorkspace:l.handleRenameWorkspaceFromSidebar,onPinWorkspace:l.handlePinWorkspaceFromSidebar,onConversationTypeChange:l.handleSidebarConversationTypeChange,onOpenWorkflows:l.openWorkflowsPage},null,8,["icon-style","format-time","running-tasks","current-task-in-progress","current-conversation-id","current-workspace-id","default-workspace-id","workspaces","workspace-kind","host-workspace-enabled","workspace-busy","workspace-create-submitting","workspace-error","group-by-workspace","versioning-host-mode","onToggle","onCreate","onSearch","onSearchSubmit","onSearchMore","onSelect","onSelectRunningTask","onLoadMore","onPersonal","onDelete","onDuplicate","onSwitchWorkspace","onCreateWorkspace","onDeleteWorkspace","onSetDefaultWorkspace","onSelectWorkspaceConversation","onCreateWorkspaceConversation","onRevealWorkspace","onRenameWorkspace","onPinWorkspace","onConversationTypeChange","onOpenWorkflows"])),E("main",{class:ke(["chat-container",{"chat-container--mobile":l.isMobileViewport,"chat-container--app-shell":a.value,"chat-container--monitor":l.chatDisplayMode==="monitor","has-title-ribbon":l.titleRibbonVisible}]),style:Ke(l.chatContainerStyle)},[Qe(d,{visible:!!l.currentConversationId,collapsed:l.tokenPanelCollapsed,onToggle:l.handleTokenPanelToggleClick,"current-conversation-tokens":l.currentConversationTokens,"current-context-tokens":l.currentContextTokens,"container-status":l.containerStatus,"container-net-rate":l.containerNetRate,"project-storage":l.projectStorage,"usage-quota":l.usageQuota,"format-token-count":l.formatTokenCount,"format-percentage":l.formatPercentage,"format-bytes":l.formatBytes,"format-quota-value":l.formatQuotaValue,"format-reset-time":l.formatResetTime,"format-rate":l.formatRate},null,8,["visible","collapsed","onToggle","current-conversation-tokens","current-context-tokens","container-status","container-net-rate","project-storage","usage-quota","format-token-count","format-percentage","format-bytes","format-quota-value","format-reset-time","format-rate"]),l.titleRibbonVisible?(F(),$("div",Joe,[E("button",{type:"button",class:ke(["conversation-ribbon__selector",{open:l.headerMenuOpen}]),"data-tutorial":"header-model-selector",onClick:u[1]||(u[1]=Ne((...O)=>l.toggleHeaderMenu&&l.toggleHeaderMenu(...O),["stop"])),disabled:!l.isConnected},[E("span",eae,[E("span",tae,ae(l.currentModelLabel),1),u[31]||(u[31]=E("span",{class:"selector-sep"},"·",-1)),E("span",sae,ae(l.headerRunModeLabel),1)]),u[32]||(u[32]=E("svg",{viewBox:"0 0 24 24","aria-hidden":"true",class:"selector-caret"},[E("path",{d:"M7 10l5 5 5-5",fill:"none",stroke:"currentColor","stroke-width":"1.8","stroke-linecap":"round","stroke-linejoin":"round"})],-1))],10,Zoe),E("span",nae,ae(l.titleTypingText||l.currentConversationTitle),1),Qe(us,{name:"header-menu"},{default:Vt(()=>[l.headerMenuOpen?(F(),$("div",iae,[E("div",rae,[u[33]||(u[33]=E("div",{class:"dropdown-title"},"模型",-1)),E("div",oae,[(F(!0),$(Ie,null,tt(l.modelOptions,O=>(F(),$("button",{key:O.key,type:"button",class:ke(["dropdown-item",{active:O.key===l.currentModelKey,disabled:O.disabled}]),onClick:Ne(H=>l.handleHeaderModelSelect(O.key,O.disabled),["stop"]),disabled:l.streamingMessage||!l.isConnected||O.disabled},[E("div",lae,ae(O.label),1),E("div",cae,ae(O.description),1),O.key===l.currentModelKey?(F(),$("span",uae,"✓")):ge("",!0)],10,aae))),128))])]),E("div",hae,[u[34]||(u[34]=E("div",{class:"dropdown-title"},"运行模式",-1)),(F(!0),$(Ie,null,tt(l.headerRunModeOptions,O=>(F(),$("button",{key:O.value,type:"button",class:ke(["dropdown-item",{active:O.value===l.resolvedRunMode}]),onClick:Ne(H=>l.handleHeaderRunModeSelect(O.value),["stop"]),disabled:l.streamingMessage||!l.isConnected},[E("div",fae,ae(O.label),1),E("div",pae,ae(O.desc),1),O.value===l.resolvedRunMode?(F(),$("span",gae,"✓")):ge("",!0)],10,dae))),128)),l.showEffortSlider?(F(),$("div",mae,[Qe(p,{"model-value":l.reasoningEffort,"onUpdate:modelValue":l.setReasoningEffort},null,8,["model-value","onUpdate:modelValue"])])):ge("",!0)])],512)):ge("",!0)]),_:1})],512)):ge("",!0),_v(Qe(m,{ref:"messagesArea",messages:l.messages,"icon-style":l.iconStyle,"expanded-blocks":l.expandedBlocks,"render-markdown":l.renderMarkdown,"toggle-block":l.toggleBlock,"handle-thinking-scroll":l.handleThinkingScroll,"streaming-message":l.streamingMessage,"get-tool-icon":l.getToolIcon,"get-tool-status-text":l.getToolStatusText,"get-tool-animation-class":l.getToolAnimationClass,"get-tool-description":l.getToolDescription,"format-search-topic":l.formatSearchTopic,"format-search-time":l.formatSearchTime,"format-search-domains":l.formatSearchDomains,"history-loading":l.historyLoading,onStickStateChange:l.handleStickStateChange,onUserScrollIntent:l.handleUserScrollIntent},null,8,["messages","icon-style","expanded-blocks","render-markdown","toggle-block","handle-thinking-scroll","streaming-message","get-tool-icon","get-tool-status-text","get-tool-animation-class","get-tool-description","format-search-topic","format-search-time","format-search-domains","history-loading","onStickStateChange","onUserScrollIntent"]),[[DF,l.chatDisplayMode==="chat"]]),l.chatDisplayMode==="monitor"?(F(),Wt(We(e),{key:1})):ge("",!0),l.blankHeroActive?(F(),$("div",vae,[l.showStatusAvatar?(F(),Wt(v,{key:0,mode:"idle",size:58,tracking:""})):ge("",!0),E("p",yae,ae(l.blankWelcomeText),1)])):ge("",!0),Qe(us,{name:"scroll-to-bottom-fade"},{default:Vt(()=>[l.showScrollToBottomButton?(F(),$("div",bae,[E("button",{onClick:u[2]||(u[2]=(...O)=>l.toggleScrollLock&&l.toggleScrollLock(...O)),class:"scroll-lock-btn"},[...u[35]||(u[35]=[E("svg",{viewBox:"0 0 24 24","aria-hidden":"true","stroke-linecap":"round","stroke-linejoin":"round"},[E("path",{d:"M12 5v12"}),E("path",{d:"M7 13l5 5 5-5"})],-1)])])])):ge("",!0)]),_:1}),E("div",{class:ke(["composer-container",{"blank-hero-mode":l.composerHeroActive}])},[Qe(g,{ref:"inputComposer","input-message":l.inputMessage,"input-is-multiline":l.inputIsMultiline,"input-is-focused":l.inputIsFocused,"is-connected":l.isConnected,"streaming-message":l.streamingUi,"input-locked":l.displayLockEngaged,uploading:l.uploading,"media-uploading":l.mediaUploading,"thinking-mode":l.thinkingMode,"run-mode":l.resolvedRunMode,"model-menu-open":l.modelMenuOpen,"model-options":l.modelOptions,"current-model-key":l.currentModelKey,"quick-menu-open":l.quickMenuOpen,"tool-menu-open":l.toolMenuOpen,"mode-menu-open":l.modeMenuOpen,"tool-settings":l.toolSettings,"tool-settings-loading":l.toolSettingsLoading,"settings-open":l.settingsOpen,compressing:l.compressionActiveForCurrentConversation,"current-conversation-id":l.currentConversationId,"icon-style":l.iconStyle,"tool-category-icon":l.toolCategoryIcon,"selected-images":l.selectedImages,"selected-videos":l.selectedVideos,"selected-files":l.selectedFiles,"block-upload":l.policyUiBlocks.block_upload,"block-tool-toggle":l.policyUiBlocks.block_tool_toggle,"block-realtime-terminal":l.policyUiBlocks.block_realtime_terminal,"terminal-count":l.terminalSessions?Object.keys(l.terminalSessions).length:0,"host-mode":l.versioningHostMode,"block-focus-panel":l.policyUiBlocks.block_focus_panel,"block-token-panel":l.policyUiBlocks.block_token_panel,"block-compress-conversation":l.policyUiBlocks.block_compress_conversation,"block-conversation-review":l.policyUiBlocks.block_conversation_review,"current-permission-mode":l.currentPermissionMode,"permission-menu-open":l.permissionMenuOpen,"permission-options":l.permissionModeOptions,"execution-mode-enabled":l.executionModeEnabled,"current-execution-mode":l.currentExecutionMode,"execution-mode-options":l.executionModeOptions,"network-permission-enabled":l.networkPermissionEnabled,"current-network-permission":l.currentNetworkPermission,"network-permission-options":l.networkPermissionOptions,"current-context-tokens":l.currentContextTokens,"versioning-enabled":l.versioningEnabled,"runtime-queued-messages":l.runtimeQueuedMessages,"has-pending-runtime-guidance":l.runtimeGuidanceFallbackQueue.length>0,"project-git-summary":l.projectGitSummary,"user-question-minimized":l.userQuestionMinimized,"pending-user-question-count":l.pendingUserQuestions.length,"goal-mode-armed":l.goalModeArmed,"goal-running":l.goalRunning,"goal-progress":l.goalProgress,"current-conversation-type":l.currentConversationType,"new-conversation-type":l.newConversationType,"agent-type-menu-open":l.agentTypeMenuOpen,"current-work-mode":l.currentWorkMode,"work-mode-menu-open":l.workModeMenuOpen,"work-mode-options":l.workModeOptions,"host-workspaces":l.hostWorkspaces,"current-host-workspace-id":l.currentHostWorkspaceId,"host-workspace-switching":l.hostWorkspaceSwitching,"workspace-kind":l.versioningHostMode?"workspace":l.dockerProjectMode?"project":null,"main-chat-idle":l.mainChatIdle,"active-sub-agent-count":l.activeSubAgentCount,"avatar-status":l.showStatusAvatar&&l.messages.length>0?l.avatarStatus:null,onRestoreUserQuestion:l.restoreUserQuestionDialog,onStopAllSubAgents:l.handleStopAllSubAgents,"onUpdate:inputMessage":l.inputSetMessage,onInputChange:l.handleInputChange,onInputFocus:l.handleInputFocus,onInputBlur:l.handleInputBlur,onToggleQuickMenu:l.toggleQuickMenu,onSendMessage:l.sendMessage,onSendOrStop:l.handleSendOrStop,onQuickUpload:l.handleQuickUpload,onToggleToolMenu:l.toggleToolMenu,onToggleModeMenu:l.toggleModeMenu,onToggleModelMenu:l.toggleModelMenu,onSelectRunMode:l.handleModeSelect,onSelectModel:l.handleModelSelect,onToggleSettings:l.toggleSettings,onUpdateToolCategory:l.updateToolCategory,onRealtimeTerminal:l.handleRealtimeTerminalClick,onToggleFocusPanel:l.handleFocusPanelToggleClick,onToggleTokenPanel:u[3]||(u[3]=O=>l.handleTokenPanelToggleClick(O)),onCompressConversation:l.handleCompressConversationClick,onToggleApprovalPanel:l.handleApprovalPanelToggleClick,onFileSelected:l.handleFileSelected,onPasteFiles:l.handlePastedFiles,onPickImages:l.openImagePicker,onPickVideo:l.openVideoPicker,onRemoveImage:l.handleRemoveImage,onRemoveVideo:l.handleRemoveVideo,onRemoveFile:l.handleRemoveFile,onOpenReview:l.openReviewDialog,onTogglePermissionMenu:l.togglePermissionMenu,onChangePermissionMode:l.changePermissionMode,onChangeExecutionMode:l.changeExecutionMode,onChangeNetworkPermission:l.changeNetworkPermission,onOpenPathAuthorization:l.openPathAuthorizationDialog,onOpenVersioningDialog:l.openVersioningDialog,onGuideRuntimeMessage:l.handleGuideRuntimeMessage,onDeleteRuntimeMessage:l.handleDeleteRuntimeMessage,onComposerHeightChange:l.handleComposerHeightChange,onToggleGoalMode:l.handleToggleGoalMode,onWorkflowActivated:l.handleWorkflowActivated,onToggleAgentTypeMenu:l.handleToggleAgentTypeMenu,onSelectNewConversationType:l.handleSelectNewConversationType,onToggleWorkModeMenu:l.toggleWorkModeMenu,onChangeWorkMode:l.changeWorkMode,onNewConversation:l.createNewConversation,onSwitchHostWorkspace:l.handleHostWorkspaceSwitch,onFetchHostWorkspaces:l.fetchHostWorkspaces,onOpenGoalDialog:u[4]||(u[4]=O=>l.goalDialogOpen=!0),onOpenGitChangesPanel:l.openGitChangesPanel},null,8,["input-message","input-is-multiline","input-is-focused","is-connected","streaming-message","input-locked","uploading","media-uploading","thinking-mode","run-mode","model-menu-open","model-options","current-model-key","quick-menu-open","tool-menu-open","mode-menu-open","tool-settings","tool-settings-loading","settings-open","compressing","current-conversation-id","icon-style","tool-category-icon","selected-images","selected-videos","selected-files","block-upload","block-tool-toggle","block-realtime-terminal","terminal-count","host-mode","block-focus-panel","block-token-panel","block-compress-conversation","block-conversation-review","current-permission-mode","permission-menu-open","permission-options","execution-mode-enabled","current-execution-mode","execution-mode-options","network-permission-enabled","current-network-permission","network-permission-options","current-context-tokens","versioning-enabled","runtime-queued-messages","has-pending-runtime-guidance","project-git-summary","user-question-minimized","pending-user-question-count","goal-mode-armed","goal-running","goal-progress","current-conversation-type","new-conversation-type","agent-type-menu-open","current-work-mode","work-mode-menu-open","work-mode-options","host-workspaces","current-host-workspace-id","host-workspace-switching","workspace-kind","main-chat-idle","active-sub-agent-count","avatar-status","onRestoreUserQuestion","onStopAllSubAgents","onUpdate:inputMessage","onInputChange","onInputFocus","onInputBlur","onToggleQuickMenu","onSendMessage","onSendOrStop","onQuickUpload","onToggleToolMenu","onToggleModeMenu","onToggleModelMenu","onSelectRunMode","onSelectModel","onToggleSettings","onUpdateToolCategory","onRealtimeTerminal","onToggleFocusPanel","onCompressConversation","onToggleApprovalPanel","onFileSelected","onPasteFiles","onPickImages","onPickVideo","onRemoveImage","onRemoveVideo","onRemoveFile","onOpenReview","onTogglePermissionMenu","onChangePermissionMode","onChangeExecutionMode","onChangeNetworkPermission","onOpenPathAuthorization","onOpenVersioningDialog","onGuideRuntimeMessage","onDeleteRuntimeMessage","onComposerHeightChange","onToggleGoalMode","onWorkflowActivated","onToggleAgentTypeMenu","onSelectNewConversationType","onToggleWorkModeMenu","onChangeWorkMode","onNewConversation","onSwitchHostWorkspace","onFetchHostWorkspaces","onOpenGitChangesPanel"])],2)],6),l.isMobileViewport?ge("",!0):(F(),Wt(Loe,{key:1,"host-mode":l.versioningHostMode},null,8,["host-mode"])),l.isMobileViewport?ge("",!0):(F(),$("div",_ae,[E("button",{type:"button",class:"qd-toggle","aria-label":l.qdExpanded?"收起快捷窗口":"展开快捷窗口","aria-pressed":l.qdExpanded,onClick:u[5]||(u[5]=O=>l.qdUserCollapsed=!l.qdUserCollapsed)},[...u[36]||(u[36]=[E("svg",{viewBox:"0 0 18 18",width:"16",height:"16","aria-hidden":"true"},[E("line",{x1:"2",y1:"3.5",x2:"16",y2:"3.5"}),E("line",{x1:"2",y1:"7.5",x2:"10",y2:"7.5"}),E("line",{x1:"2",y1:"11.5",x2:"14",y2:"11.5"}),E("line",{x1:"2",y1:"15.5",x2:"7",y2:"15.5"})],-1)])],8,Sae)])),l.isMobileViewport?ge("",!0):(F(),Wt(qoe,{key:3})),!l.isMobileViewport&&(l.terminalPanelOpen||l.gitChangesPanelOpen)?(F(),$("div",{key:4,class:"resize-handle resize-handle--right-panels",onMousedown:u[6]||(u[6]=O=>l.startResize("right",O))},null,32)):ge("",!0),Qe(us,{name:"right-panels-slide"},{default:Vt(()=>[!l.isMobileViewport&&(l.terminalPanelOpen||l.gitChangesPanelOpen)?(F(),$("div",{key:0,class:"right-panels",style:Ke(l.rightPanelsStyle)},[E("div",wae,[Qe(y,{width:Math.min(l.rightWidth||420,600),"workspace-id":l.currentHostWorkspaceId,"conversation-id":l.currentConversationId,onClose:l.closeTerminalPanel},null,8,["width","workspace-id","conversation-id","onClose"])]),l.terminalPanelOpen&&l.gitChangesPanelOpen?(F(),$("div",{key:0,class:"right-panels__split-handle",onMousedown:u[7]||(u[7]=(...O)=>l.startRightSplitResize&&l.startRightSplitResize(...O))},null,32)):ge("",!0),E("div",kae,[Qe(b,{width:Math.min(l.rightWidth||420,600),loading:l.gitChangesLoading,error:l.gitChangesError,diff:l.gitChangesDiff,"fold-contexts":l.gitChangesFoldContexts,"host-mode":l.versioningHostMode,onClose:l.closeGitChangesPanel,onExpandContext:l.expandGitChangesContext,onResetContext:l.resetGitChangesContext},null,8,["width","loading","error","diff","fold-contexts","host-mode","onClose","onExpandContext","onResetContext"])])],4)):ge("",!0)]),_:1})]),Qe(us,{name:"desktop-approval-fade"},{default:Vt(()=>[!l.isMobileViewport&&!l.rightCollapsed?(F(),$("div",Cae,[E("div",{class:"desktop-approval-sheet",style:Ke({width:Math.min(l.rightWidth||420,520)+"px"})},[Qe(_,{collapsed:!1,width:Math.min(l.rightWidth||420,520),approvals:l.pendingToolApprovals,"deciding-approval-ids":l.decidingApprovalIds,"auto-approval-feed-lines":l.autoApprovalFeedLines,"auto-approval-final-message":l.autoApprovalFinalMessage,"auto-approval-title":l.autoApprovalTitle,onSwitchUnrestricted:l.handleSwitchPermissionToUnrestricted,onApprove:l.approveToolApproval,onReject:l.rejectToolApproval,onClose:u[8]||(u[8]=O=>l.rightCollapsed=!0)},null,8,["width","approvals","deciding-approval-ids","auto-approval-feed-lines","auto-approval-final-message","auto-approval-title","onSwitchUnrestricted","onApprove","onReject"])],4)])):ge("",!0)]),_:1}),Qe(w),Qe(We(t),{open:l.pathAuthorizationDialogOpen,value:l.pathAuthorizationDraft,mode:l.pathAuthorizationMode,saving:l.pathAuthorizationSaving,"onUpdate:value":u[9]||(u[9]=O=>l.pathAuthorizationDraft=O),"onUpdate:mode":l.setPathAuthorizationMode,onClose:l.closePathAuthorizationDialog,onSave:l.savePathAuthorization},null,8,["open","value","mode","saving","onUpdate:mode","onClose","onSave"]),Qe(us,{name:"overlay-fade"},{default:Vt(()=>[l.imagePickerOpen?(F(),Wt(S,{key:0,open:l.imagePickerOpen,entries:l.imageEntries,"initial-selected":l.selectedImages,loading:l.imageLoading,uploading:l.mediaUploading,onClose:l.closeImagePicker,onConfirm:l.handleImagesConfirmed,onLocalFiles:l.handleLocalImageFiles},null,8,["open","entries","initial-selected","loading","uploading","onClose","onConfirm","onLocalFiles"])):ge("",!0)]),_:1}),Qe(us,{name:"overlay-fade"},{default:Vt(()=>[l.videoPickerOpen?(F(),Wt(Ore,{key:0,open:l.videoPickerOpen,entries:l.videoEntries,"initial-selected":l.selectedVideos,loading:l.videoLoading,uploading:l.mediaUploading,onClose:l.closeVideoPicker,onConfirm:l.handleVideosConfirmed,onLocalFiles:l.handleLocalVideoFiles},null,8,["open","entries","initial-selected","loading","uploading","onClose","onConfirm","onLocalFiles"])):ge("",!0)]),_:1}),Qe($re),Qe(us,{name:"overlay-fade"},{default:Vt(()=>[l.reviewDialogOpen?(F(),Wt(C,{key:0,open:l.reviewDialogOpen,conversations:l.reviewConversations,"current-conversation-id":l.currentConversationId,"selected-id":l.reviewSelectedConversationId,loading:l.reviewListLoading,"loading-more":l.reviewListLoadingMore,"has-more":l.reviewListHasMore,submitting:l.reviewSubmitting,preview:l.reviewPreviewLines,"preview-loading":l.reviewPreviewLoading,"preview-error":l.reviewPreviewError,"preview-limit":l.reviewPreviewLimit,"send-to-model":l.reviewSendToModel,"generated-path":l.reviewGeneratedPath,"icon-style":l.iconStyle,onClose:u[10]||(u[10]=O=>l.reviewDialogOpen=!1),onSelect:l.handleReviewSelect,onLoadMore:l.loadMoreReviewConversations,onToggleSend:u[11]||(u[11]=O=>l.reviewSendToModel=O),onConfirm:l.handleConfirmReview},null,8,["open","conversations","current-conversation-id","selected-id","loading","loading-more","has-more","submitting","preview","preview-loading","preview-error","preview-limit","send-to-model","generated-path","icon-style","onSelect","onLoadMore","onConfirm"])):ge("",!0)]),_:1}),Qe(T),Qe(k),Qe(A,{open:l.goalDialogOpen,progress:l.goalProgress,onClose:u[12]||(u[12]=O=>l.goalDialogOpen=!1)},null,8,["open","progress"]),Qe(M,{visible:l.userQuestionDialogVisible&&!l.userQuestionMinimized&&l.pendingUserQuestions.length>0,questions:l.pendingUserQuestions,"active-index":l.userQuestionActiveIndex,"submitting-ids":l.answeringUserQuestionIds,onMinimize:l.minimizeUserQuestionDialog,"onUpdate:activeIndex":u[13]||(u[13]=O=>l.userQuestionActiveIndex=O),onSubmit:l.submitUserQuestionAnswers,onDismiss:l.dismissUserQuestions},null,8,["visible","questions","active-index","submitting-ids","onMinimize","onSubmit","onDismiss"]),Qe(R,{visible:l.pendingPlanApprovals.length>0,approvals:l.pendingPlanApprovals,"submitting-ids":l.answeringPlanApprovalIds,onSubmit:l.submitPlanApproval},null,8,["visible","approvals","submitting-ids","onSubmit"]),Qe(us,{name:"overlay-fade"},{default:Vt(()=>[l.versioningDialogOpen?(F(),Wt(P,{key:0,"host-mode":l.versioningHostMode,enabled:l.versioningEnabled,"tracking-mode":l.versioningTrackingMode,loading:l.versioningLoading,items:l.versioningCheckpoints,"selected-seq":l.versioningSelectedSeq,detail:l.versioningSelectedDetail,"detail-loading":l.versioningDetailLoading,restoring:l.versioningRestoring,"restore-mode":l.versioningRestoreMode,"icon-style":l.iconStyle,onClose:u[14]||(u[14]=O=>l.versioningDialogOpen=!1),onRefresh:l.refreshVersioningDialog,onToggleEnabled:l.toggleConversationVersioning,onSelect:l.selectVersioningCheckpoint,"onUpdate:restoreMode":u[15]||(u[15]=O=>l.versioningRestoreMode=O),"onUpdate:trackingMode":u[16]||(u[16]=O=>l.versioningTrackingMode=O),onConfirm:l.confirmVersioningRestore},null,8,["host-mode","enabled","tracking-mode","loading","items","selected-seq","detail","detail-loading","restoring","restore-mode","icon-style","onRefresh","onToggleEnabled","onSelect","onConfirm"])):ge("",!0)]),_:1}),We(n).running?(F(),Wt(L,{key:0})):ge("",!0),Qe(z,{visible:l.tutorialPromptVisible,username:l.tutorialPromptUsername,loading:l.tutorialPromptLoading,onStart:l.handleNewUserTutorialStart,onSkip:l.handleNewUserTutorialSkip},null,8,["visible","username","loading","onStart","onSkip"]),l.isMobileViewport?(F(),$("div",{key:1,class:ke(["mobile-panel-trigger",{"is-hidden":!!l.activeMobileOverlay}]),ref:"mobilePanelTrigger"},[E("div",Tae,[E("button",{type:"button",class:"mobile-panel-fab","data-tutorial":"mobile-menu-trigger","aria-label":"切换工作区",onClick:u[17]||(u[17]=(...O)=>l.toggleMobileOverlayMenu&&l.toggleMobileOverlayMenu(...O))},[E("img",{src:We(r),alt:"","aria-hidden":"true"},null,8,Aae)]),E("button",{type:"button",class:ke(["mobile-topbar-selector",{open:l.headerMenuOpen}]),"data-tutorial":"header-model-selector-mobile",onClick:u[18]||(u[18]=Ne((...O)=>l.toggleHeaderMenu&&l.toggleHeaderMenu(...O),["stop"])),disabled:!l.isConnected},[E("span",Mae,[E("span",xae,ae(l.currentModelLabel),1),u[37]||(u[37]=E("span",{class:"mobile-selector-sep"},"·",-1)),E("span",Iae,ae(l.headerRunModeLabel),1)])],10,Eae),E("div",{class:"mobile-topbar-title",title:l.currentConversationTitle||"未命名对话"},ae(l.currentConversationTitle||"未命名对话"),9,Rae)]),Qe(us,{name:"mobile-panel-menu"},{default:Vt(()=>[l.mobileOverlayMenuOpen?(F(),$("div",Lae,[E("button",{type:"button",class:"dropdown-item mobile-menu-item","data-tutorial":"mobile-menu-conversation","aria-label":"对话记录",onClick:u[19]||(u[19]=O=>l.openMobileOverlay("conversation"))},[...u[38]||(u[38]=[E("svg",{class:"mobile-menu-icon",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true"},[E("path",{d:"M4 5.5c0-1.38 1.12-2.5 2.5-2.5h11c1.38 0 2.5 1.12 2.5 2.5v7.5c0 1.38-1.12 2.5-2.5 2.5h-4.8l-2.9 2.7.5-2.7H6.5c-1.38 0-2.5-1.12-2.5-2.5V5.5z",fill:"none",stroke:"currentColor","stroke-width":"1.7","stroke-linecap":"round","stroke-linejoin":"round"}),E("path",{d:"M8 8.5h8",stroke:"currentColor","stroke-width":"1.7","stroke-linecap":"round"}),E("path",{d:"M8 11.5h5",stroke:"currentColor","stroke-width":"1.7","stroke-linecap":"round"})],-1),E("div",{class:"item-label"},"对话记录",-1)])]),E("button",{type:"button",class:"dropdown-item mobile-menu-item mobile-menu-item--personal","data-tutorial":"mobile-menu-personal","aria-label":"个人空间",onClick:u[20]||(u[20]=(...O)=>l.handleMobilePersonalClick&&l.handleMobilePersonalClick(...O))},[E("img",{class:"mobile-menu-icon",src:c.personal,alt:"","aria-hidden":"true"},null,8,Pae),u[39]||(u[39]=E("div",{class:"item-label"},"个人空间",-1))]),E("button",{type:"button",class:"dropdown-item mobile-menu-item","data-tutorial":"mobile-menu-new-chat","aria-label":"新建对话",onClick:u[21]||(u[21]=(...O)=>l.createNewConversation&&l.createNewConversation(...O))},[E("img",{class:"mobile-menu-icon",src:c.newChat,alt:"","aria-hidden":"true"},null,8,Oae),u[40]||(u[40]=E("div",{class:"item-label"},"新建对话",-1))]),a.value?(F(),$("button",{key:0,type:"button",class:"dropdown-item mobile-menu-item mobile-menu-item--refresh","aria-label":"刷新页面",onClick:u[22]||(u[22]=(...O)=>l.handleMobileRefreshClick&&l.handleMobileRefreshClick(...O))},[E("img",{class:"mobile-menu-icon",src:c.refresh,alt:"","aria-hidden":"true"},null,8,Dae),u[41]||(u[41]=E("div",{class:"item-label"},"刷新页面",-1))])):ge("",!0)])):ge("",!0)]),_:1}),Qe(us,{name:"header-menu"},{default:Vt(()=>[l.headerMenuOpen&&l.isMobileViewport?(F(),$("div",Nae,[E("div",Bae,[u[42]||(u[42]=E("div",{class:"dropdown-title"},"模型",-1)),E("div",Fae,[(F(!0),$(Ie,null,tt(l.modelOptions,O=>(F(),$("button",{key:O.key,type:"button",class:ke(["dropdown-item",{active:O.key===l.currentModelKey,disabled:O.disabled}]),onClick:Ne(H=>l.handleHeaderModelSelect(O.key,O.disabled),["stop"]),disabled:l.streamingMessage||!l.isConnected||O.disabled},[E("div",Hae,ae(O.label),1),O.key===l.currentModelKey?(F(),$("span",Uae,"✓")):ge("",!0)],10,$ae))),128))])]),E("div",Wae,[u[43]||(u[43]=E("div",{class:"dropdown-title"},"运行模式",-1)),(F(!0),$(Ie,null,tt(l.headerRunModeOptions,O=>(F(),$("button",{key:O.value,type:"button",class:ke(["dropdown-item",{active:O.value===l.resolvedRunMode}]),onClick:Ne(H=>l.handleHeaderRunModeSelect(O.value),["stop"]),disabled:l.streamingMessage||!l.isConnected},[E("div",jae,ae(O.label),1),O.value===l.resolvedRunMode?(F(),$("span",Vae,"✓")):ge("",!0)],10,zae))),128)),l.showEffortSlider?(F(),$("div",Gae,[Qe(p,{"model-value":l.reasoningEffort,"onUpdate:modelValue":l.setReasoningEffort},null,8,["model-value","onUpdate:modelValue"])])):ge("",!0)])],512)):ge("",!0)]),_:1})],2)):ge("",!0),Qe(us,{name:"mobile-panel-overlay"},{default:Vt(()=>{var O,H;return[l.isMobileViewport&&l.activeMobileOverlay==="conversation"?(F(),$("div",{key:0,class:"mobile-panel-overlay mobile-panel-overlay--left",onClick:u[24]||(u[24]=Ne((...G)=>l.closeMobileOverlay&&l.closeMobileOverlay(...G),["self"]))},[E("div",qae,[Qe(h,{class:"mobile-overlay-content","icon-style":l.iconStyle,"format-time":l.formatTime,"running-tasks":l.runningWorkspaceTasks,"current-task-in-progress":l.taskInProgress,"current-conversation-id":l.currentConversationId,"current-workspace-id":l.currentHostWorkspaceId,"default-workspace-id":l.defaultHostWorkspaceId,workspaces:l.hostWorkspaces,"workspace-kind":l.versioningHostMode?"workspace":"project","host-workspace-enabled":l.versioningHostMode||l.dockerProjectMode,"workspace-busy":l.hostWorkspaceSwitching||l.hostWorkspaceManageSubmitting,"workspace-create-submitting":l.hostWorkspaceCreateSubmitting,"workspace-error":l.hostWorkspaceCreateError,"group-by-workspace":(H=(O=We(i))==null?void 0:O.form)==null?void 0:H.group_sidebar_by_workspace,"versioning-host-mode":l.versioningHostMode,"show-collapse-button":!0,"collapse-button-variant":"close",onToggle:l.closeMobileOverlay,onCreate:l.createNewConversation,onSearch:l.handleSidebarSearchInput,onSearchSubmit:l.handleSidebarSearchSubmit,onSearchMore:l.loadMoreSearchResults,onSelect:u[23]||(u[23]=G=>l.handleMobileOverlaySelect(G)),onSelectRunningTask:l.openRunningWorkspaceTask,onLoadMore:l.loadMoreConversations,onPersonal:l.openPersonalPage,onDelete:l.deleteConversation,onDuplicate:l.duplicateConversation,onSwitchWorkspace:l.handleHostWorkspaceSwitch,onCreateWorkspace:l.submitHostWorkspaceCreateFromManage,onDeleteWorkspace:l.handleDeleteWorkspaceFromSwitcher,onSetDefaultWorkspace:l.setDefaultHostWorkspace,onSelectWorkspaceConversation:l.handleSelectWorkspaceConversation,onCreateWorkspaceConversation:l.createWorkspaceConversation,onRevealWorkspace:l.revealHostWorkspace,onRenameWorkspace:l.handleRenameWorkspaceFromSidebar,onPinWorkspace:l.handlePinWorkspaceFromSidebar,onConversationTypeChange:l.handleSidebarConversationTypeChange},null,8,["icon-style","format-time","running-tasks","current-task-in-progress","current-conversation-id","current-workspace-id","default-workspace-id","workspaces","workspace-kind","host-workspace-enabled","workspace-busy","workspace-create-submitting","workspace-error","group-by-workspace","versioning-host-mode","onToggle","onCreate","onSearch","onSearchSubmit","onSearchMore","onSelectRunningTask","onLoadMore","onPersonal","onDelete","onDuplicate","onSwitchWorkspace","onCreateWorkspace","onDeleteWorkspace","onSetDefaultWorkspace","onSelectWorkspaceConversation","onCreateWorkspaceConversation","onRevealWorkspace","onRenameWorkspace","onPinWorkspace","onConversationTypeChange"])])])):ge("",!0)]}),_:1}),Qe(us,{name:"mobile-panel-overlay"},{default:Vt(()=>[l.isMobileViewport&&l.activeMobileOverlay==="approval"?(F(),$("div",{key:0,class:"mobile-panel-overlay mobile-panel-overlay--right mobile-approval-overlay",onClick:u[26]||(u[26]=Ne(O=>l.closeMobileOverlay("backdrop-click"),["self"]))},[E("div",Kae,[Qe(_,{class:"mobile-overlay-content",collapsed:!1,width:Math.min(l.rightWidth||420,460),approvals:l.pendingToolApprovals,"deciding-approval-ids":l.decidingApprovalIds,"auto-approval-feed-lines":l.autoApprovalFeedLines,"auto-approval-final-message":l.autoApprovalFinalMessage,onSwitchUnrestricted:l.handleSwitchPermissionToUnrestricted,onApprove:l.approveToolApproval,onReject:l.rejectToolApproval,onClose:u[25]||(u[25]=O=>l.closeMobileOverlay("approval-panel-close-btn"))},null,8,["width","approvals","deciding-approval-ids","auto-approval-feed-lines","auto-approval-final-message","onSwitchUnrestricted","onApprove","onReject"])])])):ge("",!0)]),_:1}),l.workflowDemoRoute?(F(),Wt(Q,{key:2,"route-path":l.workflowDemoRoute},null,8,["route-path"])):ge("",!0)],64))]}),_:1},8,["download-file","download-folder"])}}}),vF="agents_ui_theme",sE=s=>{document.documentElement.setAttribute("data-theme",s),document.body.setAttribute("data-theme",s),setTimeout(()=>{const t=document.querySelector(".stadium-shell");t&&window.getComputedStyle(t);const n=document.querySelector(".conversation-ribbon__selector");n&&window.getComputedStyle(n);const i=document.querySelector(".selector-model");i&&window.getComputedStyle(i);const r=document.querySelector(".selector-mode");r&&window.getComputedStyle(r);const o=document.querySelector(".model-mode-dropdown");o&&window.getComputedStyle(o);const a=document.querySelector(".dropdown-item");a&&window.getComputedStyle(a)},100)},nE=()=>{if(typeof window>"u")return"classic";const s=window.localStorage.getItem(vF);return s==="light"||s==="dark"||s==="classic"?s:"classic"},Xae=s=>{typeof window>"u"||window.localStorage.setItem(vF,s)},Yae=()=>{const s=nE();sE(s)},gle=()=>{const s=t=>{sE(t),Xae(t)},e=()=>sE(nE());return Cn(()=>{e()}),{setTheme:s,restore:e,loadTheme:nE}},yF=w2(Qae),Jae=UF();yF.use(Jae);Yae();yF.mount("#app");export{aZ as I,xm as M,qs as a,R2 as b,Vs as c,tE as d,No as e,Qi as f,FM as g,gle as h,Fne as i,oh as j,cm as k,Ii as s,j2 as u};